hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
92a092fff07525e601f6c144294ed119d47662c1
46,076
cxx
C++
main/svx/source/sidebar/possize/PosSizePropertyPanel.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/svx/source/sidebar/possize/PosSizePropertyPanel.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/svx/source/sidebar/possize/PosSizePropertyPanel.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #include <sfx2/sidebar/ResourceDefinitions.hrc> #include <sfx2/sidebar/Theme.hxx> #include <sfx2/sidebar/ControlFactory.hxx> #include <sfx2/sidebar/Layouter.hxx> #include "PosSizePropertyPanel.hxx" #include "PosSizePropertyPanel.hrc" #include <svx/sidebar/SidebarDialControl.hxx> #include <svx/dialogs.hrc> #include <svx/dialmgr.hxx> #include <sfx2/dispatch.hxx> #include <sfx2/bindings.hxx> #include <sfx2/viewsh.hxx> #include <sfx2/objsh.hxx> #include <sfx2/imagemgr.hxx> #include <svx/dlgutil.hxx> #include <unotools/viewoptions.hxx> #include <vcl/virdev.hxx> #include <vcl/svapp.hxx> #include <vcl/field.hxx> #include <vcl/fixed.hxx> #include <vcl/toolbox.hxx> #include <svx/svdview.hxx> #include <svl/aeitem.hxx> using namespace css; using namespace cssu; using ::sfx2::sidebar::Layouter; using ::sfx2::sidebar::Theme; #define A2S(pString) (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(pString))) #define USERITEM_NAME rtl::OUString::createFromAscii("FitItem") #define NO_SELECT (65535) namespace svx { namespace sidebar { PosSizePropertyPanel::PosSizePropertyPanel( Window* pParent, const cssu::Reference<css::frame::XFrame>& rxFrame, SfxBindings* pBindings, const cssu::Reference<css::ui::XSidebar>& rxSidebar) : Control( pParent, SVX_RES(RID_SIDEBAR_POSSIZE_PANEL)), mpFtPosX(new FixedText(this, SVX_RES(FT_SBSHAPE_HORIZONTAL))), mpMtrPosX(new MetricField(this, SVX_RES(MF_SBSHAPE_HORIZONTAL))), mpFtPosY(new FixedText(this, SVX_RES(FT_SBSHAPE_VERTICAL))), mpMtrPosY(new MetricField(this, SVX_RES(MF_SBSHAPE_VERTICAL))), mpFtWidth(new FixedText(this, SVX_RES(FT_WIDTH))), mpMtrWidth(new MetricField(this, SVX_RES(MTR_FLD_WIDTH))), mpFtHeight(new FixedText(this, SVX_RES(FT_HEIGHT))), mpMtrHeight(new MetricField(this, SVX_RES(MTR_FLD_HEIGHT))), mpCbxScale(new CheckBox(this, SVX_RES(CBX_SCALE))), mpFtAngle(new FixedText(this, SVX_RES(FT_ANGLE))), mpMtrAngle(new MetricBox(this, SVX_RES(MTR_FLD_ANGLE))), mpDial(new SidebarDialControl(this, SVX_RES(DIAL_CONTROL))), mpFtFlip(new FixedText(this, SVX_RES(FT_FLIP))), mpFlipTbxBackground(sfx2::sidebar::ControlFactory::CreateToolBoxBackground(this)), mpFlipTbx(sfx2::sidebar::ControlFactory::CreateToolBox(mpFlipTbxBackground.get(), SVX_RES(TBX_FLIP))), maRect(), mpView(0), mlOldWidth(1), mlOldHeight(1), meRP(RP_LT), maAnchorPos(), mlRotX(0), mlRotY(0), maUIScale(), mePoolUnit(), // #124409# init with fallback default meDlgUnit(FUNIT_INCH), maTransfPosXControl(SID_ATTR_TRANSFORM_POS_X, *pBindings, *this), maTransfPosYControl(SID_ATTR_TRANSFORM_POS_Y, *pBindings, *this), maTransfWidthControl(SID_ATTR_TRANSFORM_WIDTH, *pBindings, *this), maTransfHeightControl(SID_ATTR_TRANSFORM_HEIGHT, *pBindings, *this), maSvxAngleControl( SID_ATTR_TRANSFORM_ANGLE, *pBindings, *this), maRotXControl(SID_ATTR_TRANSFORM_ROT_X, *pBindings, *this), maRotYControl(SID_ATTR_TRANSFORM_ROT_Y, *pBindings, *this), maProPosControl(SID_ATTR_TRANSFORM_PROTECT_POS, *pBindings, *this), maProSizeControl(SID_ATTR_TRANSFORM_PROTECT_SIZE, *pBindings, *this), maAutoWidthControl(SID_ATTR_TRANSFORM_AUTOWIDTH, *pBindings, *this), maAutoHeightControl(SID_ATTR_TRANSFORM_AUTOHEIGHT, *pBindings, *this), m_aMetricCtl(SID_ATTR_METRIC, *pBindings, *this), mxFrame(rxFrame), maContext(), mpBindings(pBindings), maFtWidthOrigPos(mpFtWidth->GetPosPixel()), maMtrWidthOrigPos(mpMtrWidth->GetPosPixel()), maFtHeightOrigPos(mpFtHeight->GetPosPixel()), maMtrHeightOrigPos(mpMtrHeight->GetPosPixel()), maCbxScaleOrigPos(mpCbxScale->GetPosPixel()), maFtAngleOrigPos(mpFtAngle->GetPosPixel()), maMtrAnglOrigPos(mpMtrAngle->GetPosPixel()), maFlipTbxOrigPos(mpFlipTbx->GetPosPixel()), maDialOrigPos(mpDial->GetPosPixel()), maFtFlipOrigPos(mpFtFlip->GetPosPixel()), mbMtrPosXMirror(false), mbSizeProtected(false), mbPositionProtected(false), mbAutoWidth(false), mbAutoHeight(false), mbAdjustEnabled(false), mbIsFlip(false), mxSidebar(rxSidebar), maLayouter(*this) { Initialize(); FreeResource(); mpBindings->Update( SID_ATTR_TRANSFORM_WIDTH ); mpBindings->Update( SID_ATTR_TRANSFORM_HEIGHT ); mpBindings->Update( SID_ATTR_TRANSFORM_PROTECT_SIZE ); mpBindings->Update( SID_ATTR_METRIC ); // Setup the grid layouter. const sal_Int32 nMappedMboxWidth (Layouter::MapWidth(*this, MBOX_WIDTH)); maLayouter.GetCell(0,0).SetControl(*mpFtPosX); maLayouter.GetCell(1,0).SetControl(*mpMtrPosX); maLayouter.GetCell(0,2).SetControl(*mpFtPosY); maLayouter.GetCell(1,2).SetControl(*mpMtrPosY); maLayouter.GetCell(2,0).SetControl(*mpFtWidth); maLayouter.GetCell(3,0).SetControl(*mpMtrWidth); maLayouter.GetCell(2,2).SetControl(*mpFtHeight); maLayouter.GetCell(3,2).SetControl(*mpMtrHeight); maLayouter.GetCell(4,0).SetControl(*mpCbxScale).SetGridWidth(3); maLayouter.GetCell(5,0).SetControl(*mpFtAngle).SetGridWidth(3); maLayouter.GetColumn(0) .SetWeight(1) .SetLeftPadding(Layouter::MapWidth(*this,SECTIONPAGE_MARGIN_HORIZONTAL)) .SetMinimumWidth(nMappedMboxWidth); maLayouter.GetColumn(1) .SetWeight(0) .SetMinimumWidth(Layouter::MapWidth(*this, CONTROL_SPACING_HORIZONTAL)); maLayouter.GetColumn(2) .SetWeight(1) .SetRightPadding(Layouter::MapWidth(*this,SECTIONPAGE_MARGIN_HORIZONTAL)) .SetMinimumWidth(nMappedMboxWidth); // Make controls that display text handle short widths more // graceful. Layouter::PrepareForLayouting(*mpFtPosX); Layouter::PrepareForLayouting(*mpFtPosY); Layouter::PrepareForLayouting(*mpFtWidth); Layouter::PrepareForLayouting(*mpFtHeight); Layouter::PrepareForLayouting(*mpCbxScale); Layouter::PrepareForLayouting(*mpFtAngle); } PosSizePropertyPanel::~PosSizePropertyPanel() { // Destroy the background windows of the toolboxes. mpFlipTbx.reset(); mpFlipTbxBackground.reset(); } void PosSizePropertyPanel::ShowMenu (void) { if (mpBindings != NULL) { SfxDispatcher* pDispatcher = mpBindings->GetDispatcher(); if (pDispatcher != NULL) pDispatcher->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_ASYNCHRON); } } namespace { bool hasText(const SdrView& rSdrView) { const SdrMarkList& rMarkList = rSdrView.GetMarkedObjectList(); if(1 == rMarkList.GetMarkCount()) { const SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); const SdrObjKind eKind((SdrObjKind)pObj->GetObjIdentifier()); if((pObj->GetObjInventor() == SdrInventor) && (OBJ_TEXT == eKind || OBJ_TITLETEXT == eKind || OBJ_OUTLINETEXT == eKind)) { const SdrTextObj* pSdrTextObj = dynamic_cast< const SdrTextObj* >(pObj); if(pSdrTextObj && pSdrTextObj->HasText()) { return true; } } } return false; } } // end of anonymous namespace void PosSizePropertyPanel::Resize (void) { maLayouter.Layout(); } void PosSizePropertyPanel::Initialize() { mpFtPosX->SetBackground(Wallpaper()); mpFtPosY->SetBackground(Wallpaper()); mpFtWidth->SetBackground(Wallpaper()); mpFtHeight->SetBackground(Wallpaper()); mpFtAngle->SetBackground(Wallpaper()); mpFtFlip->SetBackground(Wallpaper()); //Position : Horizontal / Vertical mpMtrPosX->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangePosXHdl ) ); mpMtrPosY->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangePosYHdl ) ); mpMtrPosX->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Horizontal"))); //wj acc mpMtrPosY->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Vertical"))); //wj acc //Size : Width / Height mpMtrWidth->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangeWidthHdl ) ); mpMtrHeight->SetModifyHdl( LINK( this, PosSizePropertyPanel, ChangeHeightHdl ) ); mpMtrWidth->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Width"))); //wj acc mpMtrHeight->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Height"))); //wj acc //Size : Keep ratio mpCbxScale->SetClickHdl( LINK( this, PosSizePropertyPanel, ClickAutoHdl ) ); //rotation: mpMtrAngle->SetModifyHdl(LINK( this, PosSizePropertyPanel, AngleModifiedHdl)); mpMtrAngle->EnableAutocomplete( false ); mpMtrAngle->SetAccessibleName(::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("Rotation"))); //wj acc //rotation control mpDial->SetModifyHdl(LINK( this, PosSizePropertyPanel, RotationHdl)); //flip: mpFlipTbx->SetSelectHdl( LINK( this, PosSizePropertyPanel, FlipHdl) ); mpFlipTbx->SetItemImage( FLIP_HORIZONTAL, GetImage(mxFrame, A2S(".uno:FlipHorizontal"), sal_False, Theme::IsHighContrastMode())); mpFlipTbx->SetItemImage( FLIP_VERTICAL, GetImage(mxFrame, A2S(".uno:FlipVertical"), sal_False, Theme::IsHighContrastMode())); mpFlipTbx->SetQuickHelpText(FLIP_HORIZONTAL,String(SVX_RES(STR_QH_HORI_FLIP))); //Add mpFlipTbx->SetQuickHelpText(FLIP_VERTICAL,String(SVX_RES(STR_QH_VERT_FLIP))); //Add mpMtrPosX->SetAccessibleRelationLabeledBy(mpFtPosX.get()); mpMtrPosY->SetAccessibleRelationLabeledBy(mpFtPosY.get()); mpMtrWidth->SetAccessibleRelationLabeledBy(mpFtWidth.get()); mpMtrHeight->SetAccessibleRelationLabeledBy(mpFtHeight.get()); mpMtrAngle->SetAccessibleRelationLabeledBy(mpFtAngle.get()); #ifdef HAS_IA2 mpMtrAngle->SetMpSubEditAccLableBy(mpFtAngle.get()); #endif mpFlipTbx->SetAccessibleRelationLabeledBy(mpFtFlip.get()); mpMtrAngle->InsertValue(0, FUNIT_CUSTOM); mpMtrAngle->InsertValue(4500, FUNIT_CUSTOM); mpMtrAngle->InsertValue(9000, FUNIT_CUSTOM); mpMtrAngle->InsertValue(13500, FUNIT_CUSTOM); mpMtrAngle->InsertValue(18000, FUNIT_CUSTOM); mpMtrAngle->InsertValue(22500, FUNIT_CUSTOM); mpMtrAngle->InsertValue(27000, FUNIT_CUSTOM); mpMtrAngle->InsertValue(31500, FUNIT_CUSTOM); mpMtrAngle->AdaptDropDownLineCountToMaximum(); SfxViewShell* pCurSh = SfxViewShell::Current(); if ( pCurSh ) mpView = pCurSh->GetDrawView(); else mpView = NULL; if ( mpView != NULL ) { maUIScale = mpView->GetModel()->GetUIScale(); mbAdjustEnabled = hasText(*mpView); } mePoolUnit = maTransfWidthControl.GetCoreMetric(); // #124409# no need to do this, the mpBindings->Update( SID_ATTR_METRIC ) // call in the constructor will trigger MetricState and will get the correct unit // // meDlgUnit = GetModuleFieldUnit(); // SetFieldUnit( *mpMtrPosX, meDlgUnit, true ); // SetFieldUnit( *mpMtrPosY, meDlgUnit, true ); // SetFieldUnit( *mpMtrWidth, meDlgUnit, true ); // SetFieldUnit( *mpMtrHeight, meDlgUnit, true ); } void PosSizePropertyPanel::SetupIcons(void) { if(Theme::GetBoolean(Theme::Bool_UseSymphonyIcons)) { // todo } else { // todo } } PosSizePropertyPanel* PosSizePropertyPanel::Create ( Window* pParent, const cssu::Reference<css::frame::XFrame>& rxFrame, SfxBindings* pBindings, const cssu::Reference<css::ui::XSidebar>& rxSidebar) { if (pParent == NULL) throw lang::IllegalArgumentException(A2S("no parent Window given to PosSizePropertyPanel::Create"), NULL, 0); if ( ! rxFrame.is()) throw lang::IllegalArgumentException(A2S("no XFrame given to PosSizePropertyPanel::Create"), NULL, 1); if (pBindings == NULL) throw lang::IllegalArgumentException(A2S("no SfxBindings given to PosSizePropertyPanel::Create"), NULL, 2); return new PosSizePropertyPanel( pParent, rxFrame, pBindings, rxSidebar); } void PosSizePropertyPanel::DataChanged( const DataChangedEvent& rEvent) { (void)rEvent; SetupIcons(); } void PosSizePropertyPanel::AdaptWidthHeightScalePosition(bool bOriginal) { if(bOriginal) { mpFtWidth->SetPosPixel(maFtWidthOrigPos); mpMtrWidth->SetPosPixel(maMtrWidthOrigPos); mpFtHeight->SetPosPixel(maFtHeightOrigPos); mpMtrHeight->SetPosPixel(maMtrHeightOrigPos); mpCbxScale->SetPosPixel(maCbxScaleOrigPos); } else { mpFtWidth->SetPosPixel(Point(LogicToPixel(Point(FT_POSITION_X_X,FT_POSITION_X_Y), MAP_APPFONT))); mpMtrWidth->SetPosPixel(Point(LogicToPixel(Point(MF_POSITION_X_X,MF_POSITION_X_Y), MAP_APPFONT))); mpFtHeight->SetPosPixel(Point(LogicToPixel(Point(FT_POSITION_Y_X,FT_POSITION_Y_Y), MAP_APPFONT))); mpMtrHeight->SetPosPixel(Point(LogicToPixel(Point(MF_POSITION_Y_X,MF_POSITION_Y_Y), MAP_APPFONT))); mpCbxScale->SetPosPixel(Point(LogicToPixel(Point(FT_WIDTH_X,FT_WIDTH_Y), MAP_APPFONT))); } } void PosSizePropertyPanel::AdaptAngleFlipDialPosition(bool bOriginal) { if(bOriginal) { mpFtAngle->SetPosPixel(maFtAngleOrigPos); mpMtrAngle->SetPosPixel(maMtrAnglOrigPos); mpFlipTbx->SetPosPixel(maFlipTbxOrigPos); mpDial->SetPosPixel(maDialOrigPos); mpFtFlip->SetPosPixel(maFtFlipOrigPos); } else { mpFtAngle->SetPosPixel(Point(LogicToPixel(Point(FT_ANGLE_X,FT_ANGLE_Y), MAP_APPFONT))); mpMtrAngle->SetPosPixel(Point(LogicToPixel(Point(MF_ANGLE_X2,MF_ANGLE_Y2), MAP_APPFONT))); mpFlipTbx->SetPosPixel(Point(LogicToPixel(Point(FLIP_HORI_X2,FLIP_HORI_Y2), MAP_APPFONT))); mpDial->SetPosPixel(Point(LogicToPixel(Point(ROTATE_CONTROL_X2,ROTATE_CONTROL_Y2), MAP_APPFONT))); mpFtFlip->SetPosPixel(Point(LogicToPixel(Point(FT_FLIP_X2,FT_FLIP_Y2), MAP_APPFONT))); } } void PosSizePropertyPanel::HandleContextChange( const ::sfx2::sidebar::EnumContext aContext) { if(maContext == aContext) { // Nothing to do. return; } maContext = aContext; sal_Int32 nLayoutMode (0); switch (maContext.GetCombinedContext_DI()) { case CombinedEnumContext(Application_WriterVariants, Context_Draw): nLayoutMode = 0; break; case CombinedEnumContext(Application_WriterVariants, Context_Graphic): case CombinedEnumContext(Application_WriterVariants, Context_Media): case CombinedEnumContext(Application_WriterVariants, Context_Frame): case CombinedEnumContext(Application_WriterVariants, Context_OLE): case CombinedEnumContext(Application_WriterVariants, Context_Form): nLayoutMode = 1; break; case CombinedEnumContext(Application_Calc, Context_Draw): case CombinedEnumContext(Application_Calc, Context_Graphic): case CombinedEnumContext(Application_DrawImpress, Context_Draw): case CombinedEnumContext(Application_DrawImpress, Context_TextObject): case CombinedEnumContext(Application_DrawImpress, Context_Graphic): nLayoutMode = 2; break; case CombinedEnumContext(Application_Calc, Context_Chart): case CombinedEnumContext(Application_Calc, Context_Form): case CombinedEnumContext(Application_Calc, Context_Media): case CombinedEnumContext(Application_Calc, Context_OLE): case CombinedEnumContext(Application_Calc, Context_MultiObject): case CombinedEnumContext(Application_DrawImpress, Context_Media): case CombinedEnumContext(Application_DrawImpress, Context_Form): case CombinedEnumContext(Application_DrawImpress, Context_OLE): case CombinedEnumContext(Application_DrawImpress, Context_3DObject): case CombinedEnumContext(Application_DrawImpress, Context_MultiObject): nLayoutMode = 3; break; } switch (nLayoutMode) { case 0: { mpMtrWidth->SetMin( 2 ); mpMtrHeight->SetMin( 2 ); mpFtPosX->Hide(); mpMtrPosX->Hide(); mpFtPosY->Hide(); mpMtrPosY->Hide(); //rotation mpFtAngle->Show(); mpMtrAngle->Show(); mpDial->Show(); //flip mpFtFlip->Show(); mpFlipTbx->Show(); Size aTbxSize = mpFlipTbx->CalcWindowSizePixel(); mpFlipTbx->SetOutputSizePixel( aTbxSize ); mbIsFlip = true; AdaptWidthHeightScalePosition(false); AdaptAngleFlipDialPosition(false); mpFtAngle->SetPosPixel(Point(LogicToPixel(Point(FT_ANGLE_X,FT_ANGLE_Y), MAP_APPFONT))); mpMtrAngle->SetPosPixel(Point(LogicToPixel(Point(MF_ANGLE_X2,MF_ANGLE_Y2), MAP_APPFONT))); mpFlipTbx->SetPosPixel(Point(LogicToPixel(Point(FLIP_HORI_X2,FLIP_HORI_Y2), MAP_APPFONT))); mpDial->SetPosPixel(Point(LogicToPixel(Point(ROTATE_CONTROL_X2,ROTATE_CONTROL_Y2), MAP_APPFONT))); mpFtFlip->SetPosPixel(Point(LogicToPixel(Point(FT_FLIP_X2,FT_FLIP_Y2), MAP_APPFONT))); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT2); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; case 1: { mpMtrWidth->SetMin( 2 ); mpMtrHeight->SetMin( 2 ); mpFtPosX->Hide(); mpMtrPosX->Hide(); mpFtPosY->Hide(); mpMtrPosY->Hide(); //rotation mpFtAngle->Hide(); mpMtrAngle->Hide(); mpDial->Hide(); //flip mpFlipTbx->Hide(); mpFtFlip->Hide(); mbIsFlip = false; AdaptWidthHeightScalePosition(false); AdaptAngleFlipDialPosition(true); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT3); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; case 2: { mpMtrWidth->SetMin( 1 ); mpMtrHeight->SetMin( 1 ); mpFtPosX->Show(); mpMtrPosX->Show(); mpFtPosY->Show(); mpMtrPosY->Show(); //rotation mpFtAngle->Show(); mpMtrAngle->Show(); mpDial->Show(); //flip mpFlipTbx->Show(); mpFtFlip->Show(); Size aTbxSize = mpFlipTbx->CalcWindowSizePixel(); mpFlipTbx->SetOutputSizePixel( aTbxSize ); mbIsFlip = true; AdaptWidthHeightScalePosition(true); AdaptAngleFlipDialPosition(true); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; case 3: { mpMtrWidth->SetMin( 1 ); mpMtrHeight->SetMin( 1 ); mpFtPosX->Show(); mpMtrPosX->Show(); mpFtPosY->Show(); mpMtrPosY->Show(); //rotation mpFtAngle->Hide(); mpMtrAngle->Hide(); mpDial->Hide(); //flip mpFlipTbx->Hide(); mpFtFlip->Hide(); mbIsFlip = false; AdaptWidthHeightScalePosition(true); AdaptAngleFlipDialPosition(true); Size aSize(GetOutputSizePixel().Width(),PS_SECTIONPAGE_HEIGHT4); aSize = LogicToPixel( aSize, MapMode(MAP_APPFONT) ); SetSizePixel(aSize); if (mxSidebar.is()) mxSidebar->requestLayout(); } break; } //Added for windows classic theme mpFlipTbx->SetBackground(Wallpaper()); mpFlipTbx->SetPaintTransparent(true); } IMPL_LINK( PosSizePropertyPanel, ChangeWidthHdl, void*, /*pBox*/ ) { if( mpCbxScale->IsChecked() && mpCbxScale->IsEnabled() ) { long nHeight = (long) ( ((double) mlOldHeight * (double) mpMtrWidth->GetValue()) / (double) mlOldWidth ); if( nHeight <= mpMtrHeight->GetMax( FUNIT_NONE ) ) { mpMtrHeight->SetUserValue( nHeight, FUNIT_NONE ); } else { nHeight = (long)mpMtrHeight->GetMax( FUNIT_NONE ); mpMtrHeight->SetUserValue( nHeight ); const long nWidth = (long) ( ((double) mlOldWidth * (double) nHeight) / (double) mlOldHeight ); mpMtrWidth->SetUserValue( nWidth, FUNIT_NONE ); } } executeSize(); return 0; } IMPL_LINK( PosSizePropertyPanel, ChangeHeightHdl, void *, EMPTYARG ) { if( mpCbxScale->IsChecked() && mpCbxScale->IsEnabled() ) { long nWidth = (long) ( ((double)mlOldWidth * (double)mpMtrHeight->GetValue()) / (double)mlOldHeight ); if( nWidth <= mpMtrWidth->GetMax( FUNIT_NONE ) ) { mpMtrWidth->SetUserValue( nWidth, FUNIT_NONE ); } else { nWidth = (long)mpMtrWidth->GetMax( FUNIT_NONE ); mpMtrWidth->SetUserValue( nWidth ); const long nHeight = (long) ( ((double)mlOldHeight * (double)nWidth) / (double)mlOldWidth ); mpMtrHeight->SetUserValue( nHeight, FUNIT_NONE ); } } executeSize(); return 0; } IMPL_LINK( PosSizePropertyPanel, ChangePosXHdl, void *, EMPTYARG ) { executePosX(); return 0; } IMPL_LINK( PosSizePropertyPanel, ChangePosYHdl, void *, EMPTYARG ) { executePosY(); return 0; } IMPL_LINK( PosSizePropertyPanel, ClickAutoHdl, void *, EMPTYARG ) { if ( mpCbxScale->IsChecked() ) { mlOldWidth = Max( GetCoreValue( *mpMtrWidth, mePoolUnit ), 1L ); mlOldHeight = Max( GetCoreValue( *mpMtrHeight, mePoolUnit ), 1L ); } // mpCbxScale must synchronized with that on Position and Size tabpage on Shape Properties dialog SvtViewOptions aPageOpt( E_TABPAGE, String::CreateFromInt32( RID_SVXPAGE_POSITION_SIZE ) ); aPageOpt.SetUserItem( USERITEM_NAME, ::com::sun::star::uno::makeAny( ::rtl::OUString( String::CreateFromInt32( mpCbxScale->IsChecked() ) ) ) ); return 0; } IMPL_LINK( PosSizePropertyPanel, AngleModifiedHdl, void *, EMPTYARG ) { String sTmp = mpMtrAngle->GetText(); bool bNegative = 0; sal_Unicode nChar = sTmp.GetChar( 0 ); if( nChar == '-' ) { bNegative = 1; nChar = sTmp.GetChar( 1 ); } if( (nChar < '0') || (nChar > '9') ) return 0; double dTmp = sTmp.ToDouble(); if(bNegative) { while(dTmp<0) dTmp += 360; } sal_Int64 nTmp = dTmp*100; // #123993# Need to take UIScale into account when executing rotations const double fUIScale(mpView && mpView->GetModel() ? double(mpView->GetModel()->GetUIScale()) : 1.0); SfxInt32Item aAngleItem( SID_ATTR_TRANSFORM_ANGLE,(sal_uInt32) nTmp); SfxInt32Item aRotXItem( SID_ATTR_TRANSFORM_ROT_X, basegfx::fround(mlRotX * fUIScale)); SfxInt32Item aRotYItem( SID_ATTR_TRANSFORM_ROT_Y, basegfx::fround(mlRotY * fUIScale)); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aAngleItem, &aRotXItem, &aRotYItem, 0L ); return 0; } IMPL_LINK( PosSizePropertyPanel, RotationHdl, void *, EMPTYARG ) { sal_Int32 nTmp = mpDial->GetRotation(); // #123993# Need to take UIScale into account when executing rotations const double fUIScale(mpView && mpView->GetModel() ? double(mpView->GetModel()->GetUIScale()) : 1.0); SfxInt32Item aAngleItem( SID_ATTR_TRANSFORM_ANGLE,(sal_uInt32) nTmp); SfxInt32Item aRotXItem( SID_ATTR_TRANSFORM_ROT_X, basegfx::fround(mlRotX * fUIScale)); SfxInt32Item aRotYItem( SID_ATTR_TRANSFORM_ROT_Y, basegfx::fround(mlRotY * fUIScale)); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aAngleItem, &aRotXItem, &aRotYItem, 0L ); return 0; } IMPL_LINK( PosSizePropertyPanel, FlipHdl, ToolBox*, pBox ) { switch (pBox->GetCurItemId()) { case FLIP_HORIZONTAL: { SfxVoidItem aHoriItem (SID_FLIP_HORIZONTAL); GetBindings()->GetDispatcher()->Execute( SID_FLIP_HORIZONTAL, SFX_CALLMODE_RECORD, &aHoriItem, 0L ); } break; case FLIP_VERTICAL: { SfxVoidItem aVertItem (SID_FLIP_VERTICAL ); GetBindings()->GetDispatcher()->Execute( SID_FLIP_VERTICAL, SFX_CALLMODE_RECORD, &aVertItem, 0L ); } break; } return 0; } void PosSizePropertyPanel::NotifyItemUpdate( sal_uInt16 nSID, SfxItemState eState, const SfxPoolItem* pState, const bool /* bIsEnabled */) { mpFtAngle->Enable(); mpMtrAngle->Enable(); mpDial->Enable(); mpFtFlip->Enable(); mpFlipTbx->Enable(); const SfxUInt32Item* pWidthItem; const SfxUInt32Item* pHeightItem; SfxViewShell* pCurSh = SfxViewShell::Current(); if ( pCurSh ) mpView = pCurSh->GetDrawView(); else mpView = NULL; if ( mpView == NULL ) return; mbAdjustEnabled = hasText(*mpView); // Pool unit and dialog unit may have changed, make sure that we // have the current values. mePoolUnit = maTransfWidthControl.GetCoreMetric(); // #124409# do not change; GetModuleFieldUnit uses SfxModule::GetCurrentFieldUnit() // which uses GetActiveModule() and if no items are set there (which is the case e.g. // for writer), will just return the system fallback of FUNIT_INCH which is wrong. // Anyways, with multiple open views the static call GetActiveModule is ambigious // // meDlgUnit = GetModuleFieldUnit(); switch (nSID) { case SID_ATTR_TRANSFORM_WIDTH: if ( SFX_ITEM_AVAILABLE == eState ) { pWidthItem = dynamic_cast< const SfxUInt32Item* >(pState); if(pWidthItem) { long mlOldWidth1 = pWidthItem->GetValue(); mlOldWidth1 = Fraction( mlOldWidth1 ) / maUIScale; SetFieldUnit( *mpMtrWidth, meDlgUnit, true ); SetMetricValue( *mpMtrWidth, mlOldWidth1, mePoolUnit ); mlOldWidth = mlOldWidth1; break; } } mpMtrWidth->SetText( String()); break; case SID_ATTR_TRANSFORM_HEIGHT: if ( SFX_ITEM_AVAILABLE == eState ) { pHeightItem = dynamic_cast< const SfxUInt32Item* >(pState); if(pHeightItem) { long mlOldHeight1 = pHeightItem->GetValue(); mlOldHeight1 = Fraction( mlOldHeight1 ) / maUIScale; SetFieldUnit( *mpMtrHeight, meDlgUnit, true ); SetMetricValue( *mpMtrHeight, mlOldHeight1, mePoolUnit ); mlOldHeight = mlOldHeight1; break; } } mpMtrHeight->SetText( String()); break; case SID_ATTR_TRANSFORM_POS_X: if(SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { long nTmp = pItem->GetValue(); nTmp = Fraction( nTmp ) / maUIScale; SetFieldUnit( *mpMtrPosX, meDlgUnit, true ); SetMetricValue( *mpMtrPosX, nTmp, mePoolUnit ); break; } } mpMtrPosX->SetText( String()); break; case SID_ATTR_TRANSFORM_POS_Y: if(SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { long nTmp = pItem->GetValue(); nTmp = Fraction( nTmp ) / maUIScale; SetFieldUnit( *mpMtrPosY, meDlgUnit, true ); SetMetricValue( *mpMtrPosY, nTmp, mePoolUnit ); break; } } mpMtrPosY->SetText( String()); break; case SID_ATTR_TRANSFORM_ROT_X: if (SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { mlRotX = pItem->GetValue(); mlRotX = Fraction( mlRotX ) / maUIScale; } } break; case SID_ATTR_TRANSFORM_ROT_Y: if (SFX_ITEM_AVAILABLE == eState) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { mlRotY = pItem->GetValue(); mlRotY = Fraction( mlRotY ) / maUIScale; } } break; case SID_ATTR_TRANSFORM_PROTECT_POS: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { // record the state of position protect mbPositionProtected = pItem->GetValue(); break; } } mbPositionProtected = false; break; case SID_ATTR_TRANSFORM_PROTECT_SIZE: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { // record the state of size protect mbSizeProtected = pItem->GetValue(); break; } } mbSizeProtected = false; break; case SID_ATTR_TRANSFORM_AUTOWIDTH: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { mbAutoWidth = pItem->GetValue(); } } break; case SID_ATTR_TRANSFORM_AUTOHEIGHT: if(SFX_ITEM_AVAILABLE == eState) { const SfxBoolItem* pItem = dynamic_cast< const SfxBoolItem* >(pState); if(pItem) { mbAutoHeight = pItem->GetValue(); } } break; case SID_ATTR_TRANSFORM_ANGLE: if (eState >= SFX_ITEM_AVAILABLE) { const SfxInt32Item* pItem = dynamic_cast< const SfxInt32Item* >(pState); if(pItem) { long nTmp = pItem->GetValue(); mpMtrAngle->SetValue( nTmp ); mpDial->SetRotation( nTmp ); switch(nTmp) { case 0: mpMtrAngle->SelectEntryPos(0); break; case 4500: mpMtrAngle->SelectEntryPos(1); break; case 9000: mpMtrAngle->SelectEntryPos(2); break; case 13500: mpMtrAngle->SelectEntryPos(3); break; case 18000: mpMtrAngle->SelectEntryPos(4); break; case 22500: mpMtrAngle->SelectEntryPos(5); break; case 27000: mpMtrAngle->SelectEntryPos(6); break; case 315000: mpMtrAngle->SelectEntryPos(7); break; } break; } } mpMtrAngle->SetText( String() ); mpDial->SetRotation( 0 ); break; case SID_ATTR_METRIC: MetricState( eState, pState ); UpdateUIScale(); break; default: break; } const sal_Int32 nCombinedContext(maContext.GetCombinedContext_DI()); const SdrMarkList& rMarkList = mpView->GetMarkedObjectList(); switch (rMarkList.GetMarkCount()) { case 0: break; case 1: { const SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); const SdrObjKind eKind((SdrObjKind)pObj->GetObjIdentifier()); if(((nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_Draw) || nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_TextObject) ) && OBJ_EDGE == eKind) || OBJ_CAPTION == eKind) { mpFtAngle->Disable(); mpMtrAngle->Disable(); mpDial->Disable(); mpFlipTbx->Disable(); mpFtFlip->Disable(); } break; } default: { sal_uInt16 nMarkObj = 0; bool isNoEdge = true; while(isNoEdge && rMarkList.GetMark(nMarkObj)) { const SdrObject* pObj = rMarkList.GetMark(nMarkObj)->GetMarkedSdrObj(); const SdrObjKind eKind((SdrObjKind)pObj->GetObjIdentifier()); if(((nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_Draw) || nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_TextObject) ) && OBJ_EDGE == eKind) || OBJ_CAPTION == eKind) { isNoEdge = false; break; } nMarkObj++; } if(!isNoEdge) { mpFtAngle->Disable(); mpMtrAngle->Disable(); mpDial->Disable(); mpFlipTbx->Disable(); mpFtFlip->Disable(); } break; } } if(nCombinedContext == CombinedEnumContext(Application_DrawImpress, Context_TextObject)) { mpFlipTbx->Disable(); mpFtFlip->Disable(); } DisableControls(); // mpCbxScale must synchronized with that on Position and Size tabpage on Shape Properties dialog SvtViewOptions aPageOpt( E_TABPAGE, String::CreateFromInt32( RID_SVXPAGE_POSITION_SIZE ) ); String sUserData; ::com::sun::star::uno::Any aUserItem = aPageOpt.GetUserItem( USERITEM_NAME ); ::rtl::OUString aTemp; if ( aUserItem >>= aTemp ) sUserData = String( aTemp ); mpCbxScale->Check( (bool)sUserData.ToInt32() ); } SfxBindings* PosSizePropertyPanel::GetBindings() { return mpBindings; } void PosSizePropertyPanel::executeSize() { if ( mpMtrWidth->IsValueModified() || mpMtrHeight->IsValueModified()) { Fraction aUIScale = mpView->GetModel()->GetUIScale(); // get Width double nWidth = (double)mpMtrWidth->GetValue( meDlgUnit ); nWidth = MetricField::ConvertDoubleValue( nWidth, mpMtrWidth->GetBaseValue(), mpMtrWidth->GetDecimalDigits(), meDlgUnit, FUNIT_100TH_MM ); long lWidth = (long)(nWidth * (double)aUIScale); lWidth = OutputDevice::LogicToLogic( lWidth, MAP_100TH_MM, (MapUnit)mePoolUnit ); lWidth = (long)mpMtrWidth->Denormalize( lWidth ); // get Height double nHeight = (double)mpMtrHeight->GetValue( meDlgUnit ); nHeight = MetricField::ConvertDoubleValue( nHeight, mpMtrHeight->GetBaseValue(), mpMtrHeight->GetDecimalDigits(), meDlgUnit, FUNIT_100TH_MM ); long lHeight = (long)(nHeight * (double)aUIScale); lHeight = OutputDevice::LogicToLogic( lHeight, MAP_100TH_MM, (MapUnit)mePoolUnit ); lHeight = (long)mpMtrWidth->Denormalize( lHeight ); // put Width & Height to itemset SfxUInt32Item aWidthItem( SID_ATTR_TRANSFORM_WIDTH, (sal_uInt32) lWidth); SfxUInt32Item aHeightItem( SID_ATTR_TRANSFORM_HEIGHT, (sal_uInt32) lHeight); SfxAllEnumItem aPointItem (SID_ATTR_TRANSFORM_SIZE_POINT, (sal_uInt16)meRP); const sal_Int32 nCombinedContext(maContext.GetCombinedContext_DI()); if( nCombinedContext == CombinedEnumContext(Application_WriterVariants, Context_Graphic) || nCombinedContext == CombinedEnumContext(Application_WriterVariants, Context_OLE) ) { GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aWidthItem, &aHeightItem, &aPointItem, 0L ); } else { if ( (mpMtrWidth->IsValueModified()) && (mpMtrHeight->IsValueModified())) GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aWidthItem, &aHeightItem, &aPointItem, 0L ); else if( mpMtrWidth->IsValueModified()) GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aWidthItem, &aPointItem, 0L ); else if ( mpMtrHeight->IsValueModified()) GetBindings()->GetDispatcher()->Execute(SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aHeightItem, &aPointItem, 0L ); } } } void PosSizePropertyPanel::executePosX() { if ( mpMtrPosX->IsValueModified()) { long lX = GetCoreValue( *mpMtrPosX, mePoolUnit ); if( mbMtrPosXMirror ) lX = -lX; long lY = GetCoreValue( *mpMtrPosY, mePoolUnit ); Size aPageSize; Rectangle aRect; maRect = mpView->GetAllMarkedRect(); aRect = mpView->GetAllMarkedRect(); Fraction aUIScale = mpView->GetModel()->GetUIScale(); lX += maAnchorPos.X(); lX = Fraction( lX ) * aUIScale; lY += maAnchorPos.Y(); lY = Fraction( lY ) * aUIScale; SfxInt32Item aPosXItem( SID_ATTR_TRANSFORM_POS_X,(sal_uInt32) lX); SfxInt32Item aPosYItem( SID_ATTR_TRANSFORM_POS_Y,(sal_uInt32) lY); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aPosXItem, 0L ); } } void PosSizePropertyPanel::executePosY() { if ( mpMtrPosY->IsValueModified() ) { long lX = GetCoreValue( *mpMtrPosX, mePoolUnit ); long lY = GetCoreValue( *mpMtrPosY, mePoolUnit ); Size aPageSize; Rectangle aRect; maRect = mpView->GetAllMarkedRect(); aRect = mpView->GetAllMarkedRect(); Fraction aUIScale = mpView->GetModel()->GetUIScale(); lX += maAnchorPos.X(); lX = Fraction( lX ) * aUIScale; lY += maAnchorPos.Y(); lY = Fraction( lY ) * aUIScale; SfxInt32Item aPosXItem( SID_ATTR_TRANSFORM_POS_X,(sal_uInt32) lX); SfxInt32Item aPosYItem( SID_ATTR_TRANSFORM_POS_Y,(sal_uInt32) lY); GetBindings()->GetDispatcher()->Execute( SID_ATTR_TRANSFORM, SFX_CALLMODE_RECORD, &aPosYItem, 0L ); } } void PosSizePropertyPanel::MetricState( SfxItemState eState, const SfxPoolItem* pState ) { bool bPosXBlank = false; bool bPosYBlank = false; bool bWidthBlank = false; bool bHeightBlank = false; String sNull = String::CreateFromAscii(""); // #124409# use the given Item to get the correct UI unit and initialize it // and the Fields using it meDlgUnit = GetCurrentUnit(eState,pState); if( mpMtrPosX->GetText() == sNull ) bPosXBlank = true; SetFieldUnit( *mpMtrPosX, meDlgUnit, true ); if(bPosXBlank) mpMtrPosX->SetText(String()); if( mpMtrPosY->GetText() == sNull ) bPosYBlank = true; SetFieldUnit( *mpMtrPosY, meDlgUnit, true ); if(bPosYBlank) mpMtrPosY->SetText(String()); if( mpMtrWidth->GetText() == sNull ) bWidthBlank = true; SetFieldUnit( *mpMtrWidth, meDlgUnit, true ); if(bWidthBlank) mpMtrWidth->SetText(String()); if( mpMtrHeight->GetText() == sNull ) bHeightBlank = true; SetFieldUnit( *mpMtrHeight, meDlgUnit, true ); if(bHeightBlank) mpMtrHeight->SetText(String()); } FieldUnit PosSizePropertyPanel::GetCurrentUnit( SfxItemState eState, const SfxPoolItem* pState ) { FieldUnit eUnit = FUNIT_NONE; if ( pState && eState >= SFX_ITEM_DEFAULT ) { eUnit = (FieldUnit)( (const SfxUInt16Item*)pState )->GetValue(); } else { SfxViewFrame* pFrame = SfxViewFrame::Current(); SfxObjectShell* pSh = NULL; if ( pFrame ) pSh = pFrame->GetObjectShell(); if ( pSh ) { SfxModule* pModule = pSh->GetModule(); if ( pModule ) { const SfxPoolItem* pItem = pModule->GetItem( SID_ATTR_METRIC ); if ( pItem ) eUnit = (FieldUnit)( (SfxUInt16Item*)pItem )->GetValue(); } else { DBG_ERRORFILE( "GetModuleFieldUnit(): no module found" ); } } } return eUnit; } void PosSizePropertyPanel::DisableControls() { if( mbPositionProtected ) { // the position is protected("Position protect" option in modal dialog is checked), // disable all the Position controls in sidebar mpFtPosX->Disable(); mpMtrPosX->Disable(); mpFtPosY->Disable(); mpMtrPosY->Disable(); mpFtAngle->Disable(); mpMtrAngle->Disable(); mpDial->Disable(); mpFtFlip->Disable(); mpFlipTbx->Disable(); mpFtWidth->Disable(); mpMtrWidth->Disable(); mpFtHeight->Disable(); mpMtrHeight->Disable(); mpCbxScale->Disable(); } else { mpFtPosX->Enable(); mpMtrPosX->Enable(); mpFtPosY->Enable(); mpMtrPosY->Enable(); //mpFtAngle->Enable(); //mpMtrAngle->Enable(); //mpDial->Enable(); //mpFtFlip->Enable(); //mpFlipTbx->Enable(); if( mbSizeProtected ) { mpFtWidth->Disable(); mpMtrWidth->Disable(); mpFtHeight->Disable(); mpMtrHeight->Disable(); mpCbxScale->Disable(); } else { if( mbAdjustEnabled ) { if( mbAutoWidth ) { mpFtWidth->Disable(); mpMtrWidth->Disable(); mpCbxScale->Disable(); } else { mpFtWidth->Enable(); mpMtrWidth->Enable(); } if( mbAutoHeight ) { mpFtHeight->Disable(); mpMtrHeight->Disable(); mpCbxScale->Disable(); } else { mpFtHeight->Enable(); mpMtrHeight->Enable(); } if( !mbAutoWidth && !mbAutoHeight ) mpCbxScale->Enable(); } else { mpFtWidth->Enable(); mpMtrWidth->Enable(); mpFtHeight->Enable(); mpMtrHeight->Enable(); mpCbxScale->Enable(); } } } } void PosSizePropertyPanel::UpdateUIScale (void) { const Fraction aUIScale (mpView->GetModel()->GetUIScale()); if (maUIScale != aUIScale) { // UI scale has changed. // Remember the new UI scale. maUIScale = aUIScale; // The content of the position and size boxes is only updated when item changes are notified. // Request such notifications without changing the actual item values. GetBindings()->Invalidate(SID_ATTR_TRANSFORM_POS_X, sal_True, sal_False); GetBindings()->Invalidate(SID_ATTR_TRANSFORM_POS_Y, sal_True, sal_False); GetBindings()->Invalidate(SID_ATTR_TRANSFORM_WIDTH, sal_True, sal_False); GetBindings()->Invalidate(SID_ATTR_TRANSFORM_HEIGHT, sal_True, sal_False); } } } } // end of namespace svx::sidebar // eof
33.029391
150
0.604197
Grosskopf
92a3e1d4806cae5c3d7ca202b9cf2a8d325e996e
3,059
cpp
C++
UVa 1083 - Fare and Balanced/sample/1083 - Fare and Balanced.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 1083 - Fare and Balanced/sample/1083 - Fare and Balanced.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 1083 - Fare and Balanced/sample/1083 - Fare and Balanced.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <vector> #include <queue> #include <algorithm> #include <assert.h> using namespace std; struct Edge { int from, to; int64_t c; Edge(int from=0, int to=0, int64_t c=0): from(from), to(to), c(c) {} }; const int MAXN = 50005; static vector<Edge> g[MAXN]; static int indeg[MAXN]; static int64_t toST[MAXN], diffST[MAXN]; static int64_t toED[MAXN], diffED[MAXN]; static vector<int> order; static vector<Edge> in; static int n; void topo() { memset(toST, 0, sizeof(toST)); memset(diffST, 0, sizeof(diffST)); memset(toED, 0, sizeof(toED)); memset(diffED, 0, sizeof(diffED)); order.clear(); queue<int> Q; for (int i = 1; i <= n; i++) { if (indeg[i] == 0) Q.push(i); } while (!Q.empty()) { int u = Q.front(); Q.pop(); order.push_back(u); for (auto e : g[u]) { if (toST[e.to] && toST[e.to] != toST[u] + e.c) diffST[e.to]++; diffST[e.to] = diffST[e.to] + diffST[u]; toST[e.to] = max(toST[e.to], toST[u] + e.c); if (--indeg[e.to] == 0) Q.push(e.to); } } assert(order.size() == n); for (int i = (int) order.size()-1; i >= 0; i--) { int u = order[i]; if (u == n) continue; for (auto e : g[u]) { toED[u] = max(toED[u], toED[e.to] + e.c); diffED[u] += diffED[e.to]; } if (g[u].size()) { Edge e = g[u][0]; int64_t dd = toED[e.to] + e.c; for (int j = 1; j < g[u].size(); j++) diffED[u] += (toED[g[u][j].to] + g[u][j].c != dd); } } for (int i = 1; i <= n; i++) { if (diffST[i] > 0 && diffED[i] > 0) { puts("No solution"); return ; } } vector< pair<int, int64_t> > ret; for (int i = 0; i < in.size(); i++) { Edge e = in[i]; if (diffST[e.from] == 0 && diffST[e.to] > 0) { int64_t cc = toST[n] - (toST[e.from] + toED[e.to] + e.c); assert(cc >= 0); if (cc > 0) ret.push_back(make_pair(i+1, cc)); } } printf("%d %lld\n", (int) ret.size(), toST[n]); for (auto e : ret) printf("%d %lld\n", e.first, e.second); } int main() { int cases = 0; int m; while (scanf("%d %d", &n, &m) == 2 && n) { for (int i = 0; i <= n; i++) g[i].clear(); in.clear(); memset(indeg, 0, sizeof(indeg)); for (int i = 0; i < m; i++) { int x, y, c; scanf("%d %d %d", &x, &y, &c); g[x].push_back(Edge(x, y, c)); in.push_back(Edge(x, y, c)); indeg[y]++; } printf("Case %d: ", ++cases); topo(); } return 0; } /* 3 3 1 3 10 1 2 3 2 3 5 4 5 1 3 5 3 2 1 2 4 6 1 4 10 3 4 3 3 4 1 2 1 1 2 2 2 3 1 2 3 2 0 0 */
23
69
0.430206
tadvi
92a57ef5e759d6605d43b995e30da1833c5f2339
734
cpp
C++
lib/src/Flag.cpp
Kylerchrdsn/OOP-Strategoo
da182252ed37eca4c30d7aefa513434abb4a2ff2
[ "MIT" ]
null
null
null
lib/src/Flag.cpp
Kylerchrdsn/OOP-Strategoo
da182252ed37eca4c30d7aefa513434abb4a2ff2
[ "MIT" ]
null
null
null
lib/src/Flag.cpp
Kylerchrdsn/OOP-Strategoo
da182252ed37eca4c30d7aefa513434abb4a2ff2
[ "MIT" ]
null
null
null
/****************************************************** Flag.cpp This is the implementation file for the Flag class. ******************************************************/ #include "headers/Flag.h" //***************************************************** Flag::Flag(Player* owner, int xPos, int yPos, int boardSpace) : Piece(owner, xPos, yPos, "lib/images/flag.png"){ setBoardSpace(boardSpace); setRank(12); } //***************************************************** Flag::Flag(Player* owner, std::string filename) : Piece(owner, 0, 0, filename.c_str()){ setBoardSpace(-1); setRank(12); } //***************************************************** Piece* Flag::move(Piece* const destination){ return 0; }
31.913043
113
0.415531
Kylerchrdsn
92a6839c1a7fd14a2799534fec331e167a03b54e
23,292
cpp
C++
src/tools/rest-backend/tests/test_service_storageengine.cpp
0003088/qt-gui-test
0ceaa19e5d4b50b110047c0b73eb4f79164f4532
[ "BSD-3-Clause" ]
null
null
null
src/tools/rest-backend/tests/test_service_storageengine.cpp
0003088/qt-gui-test
0ceaa19e5d4b50b110047c0b73eb4f79164f4532
[ "BSD-3-Clause" ]
null
null
null
src/tools/rest-backend/tests/test_service_storageengine.cpp
0003088/qt-gui-test
0ceaa19e5d4b50b110047c0b73eb4f79164f4532
[ "BSD-3-Clause" ]
null
null
null
/** * @file * * @brief tests for the storage service * * @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org) */ #include <gtest/gtest.h> #include <config.hpp> #include <kdb_includes.hpp> #include <model_entry.hpp> #include <model_user.hpp> #include <service.hpp> /** * TESTS for kdbrest::service::StorageEngine */ TEST (kdbrestServicesStorageengineTest, CreateEntryCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; std::string testSubKey1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/confkey1"; std::string testSubKey2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/conf/iguration/key1"; Key subKey1 (testSubKey1, KEY_END); Key subKey2 (testSubKey2, KEY_END); Entry testEntry (testKey); testEntry.addSubkey (subKey1); testEntry.addSubkey (subKey2); testEntry.setTitle ("test-title"); testEntry.setDescription ("test-description"); testEntry.setAuthor ("test-author"); auto tags = testEntry.getTags (); tags.push_back ("test-tag"); tags.push_back ("test-tag2"); testEntry.setTags (tags); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // do storage StorageEngine::instance ().createEntry (testEntry); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (k) { ASSERT_EQ (k.getName (), testEntry.getName ()); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_TITLE)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_DESCRIPTION)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_TAGS)); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR), testEntry.getAuthor ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_TITLE), testEntry.getTitle ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_DESCRIPTION), testEntry.getDescription ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_TAGS), testEntry.getTags ().at (0) + " " + testEntry.getTags ().at (1)); ASSERT_TRUE (ks.lookup (subKey1)); ASSERT_TRUE (ks.lookup (subKey2)); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, UpdateEntryCheck) { using namespace kdb; using namespace kdbrest::exception; using namespace kdbrest::model; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; std::string testSubKey1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/confkey1"; std::string testSubKey2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/conf/iguration/key1"; std::string testSubKeyNew1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/configuration/k1"; std::string testSubKeyNew2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/co/nf/ig/u/ra/ti/on/key1"; Key subKey1 (testSubKey1, KEY_END); Key subKey2 (testSubKey2, KEY_END); Key newSubKey1 (testSubKeyNew1, KEY_END); Key newSubKey2 (testSubKeyNew2, KEY_END); Entry testEntry (testKey); testEntry.addSubkey (subKey1); testEntry.addSubkey (subKey2); testEntry.setTitle ("test-title"); testEntry.setAuthor ("test-author"); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // create entry { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.append (testEntry); ks.append (testEntry.getSubkeys ()); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (!k) { ASSERT_TRUE (false); // force error } } // force re-fetching of entry cache (void)StorageEngine::instance ().getAllEntriesRef (true); // update the entry testEntry.setTitle ("new-test-title"); testEntry.setAuthor ("new-test-author"); testEntry.getSubkeys ().clear (); ASSERT_EQ (testEntry.getSubkeys ().size (), 0); testEntry.addSubkey (newSubKey1); testEntry.addSubkey (newSubKey2); try { StorageEngine::instance ().updateEntry (testEntry); } catch (EntryNotFoundException & e) { ASSERT_TRUE (false); } // ensure that entry has been updated { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (k) { ASSERT_EQ (k.getName (), testEntry.getName ()); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_TITLE)); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR)); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_TITLE), testEntry.getTitle ()); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR), testEntry.getAuthor ()); ASSERT_TRUE (ks.lookup (newSubKey1)); ASSERT_TRUE (ks.lookup (newSubKey2)); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, DeleteEntryCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; std::string testSubKey1 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/confkey1"; std::string testSubKey2 = kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + "test/test/test/entry1/conf/iguration/key1"; Key subKey1 (testSubKey1, KEY_END); Key subKey2 (testSubKey2, KEY_END); Entry testEntry (testKey); testEntry.addSubkey (subKey1); testEntry.addSubkey (subKey2); testEntry.setAuthor ("test-author"); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // force re-fetching of entry cache (void)StorageEngine::instance ().getAllEntriesRef (true); // do storage StorageEngine::instance ().createEntry (testEntry); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); Key k = ks.lookup (testEntry); if (k) { ASSERT_EQ (k.getName (), testEntry.getName ()); ASSERT_TRUE (k.hasMeta (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR)); ASSERT_EQ (k.getMeta<std::string> (ELEKTRA_REST_MODEL_ENTRY_META_AUTHOR), testEntry.getAuthor ()); ASSERT_TRUE (ks.lookup (subKey1)); ASSERT_TRUE (ks.lookup (subKey2)); } else { ASSERT_TRUE (false); // force error } } // delete entry by storage engine StorageEngine::instance ().deleteEntry (testEntry); // ensure entry is not in database ASSERT_FALSE (StorageEngine::instance ().entryExists (testEntry.getPublicName ())); { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testEntry); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, EntryExistsCheck) { using namespace kdb; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; Key testKeyAbs = Key (kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + testKey, KEY_VALUE, "testvalue", KEY_END); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.cut (testKeyAbs); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.append (testKeyAbs); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // make sure that entry cache is re-fetched (void)StorageEngine::instance ().getAllEntriesRef (true); // check if exists now ASSERT_TRUE (StorageEngine::instance ().entryExists (testKey)); // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.lookup (testKeyAbs, KDB_O_POP); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, GetEntryCheck) { using namespace kdb; using namespace kdbrest::service; std::string testKey = "test/test/test/entry1"; Key testKeyAbs = Key (kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs") + std::string ("/") + testKey, KEY_VALUE, "testvalue", KEY_END); // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.append (testKeyAbs); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } // make sure that entry cache is re-fetched (void)StorageEngine::instance ().getAllEntriesRef (true); // find entry, check function try { kdbrest::model::Entry entry = StorageEngine::instance ().getEntry (testKey); ASSERT_TRUE (entry.isValid ()); ASSERT_EQ (entry.getName (), testKeyAbs.getName ()); ASSERT_EQ (entry.get<std::string> (), testKeyAbs.get<std::string> ()); } catch (kdbrest::exception::EntryNotFoundException & e) { ASSERT_TRUE (false); } // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); ks.lookup (testKeyAbs, KDB_O_POP); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.configs")); } } TEST (kdbrestServicesStorageengineTest, CreateUserCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; User testUser (username); testUser.setPasswordHash (passwordHash); testUser.setEmail (email); testUser.setRank (rank); testUser.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // do storage StorageEngine::instance ().createUser (testUser); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (k) { ASSERT_EQ (k.getName (), testUser.getName ()); ASSERT_EQ (k.get<std::string> (), passwordHash); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT)); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL) .get<std::string> (), email); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK).get<int> (), rank); ASSERT_EQ ( ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT).get<long> (), created_at); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, UpdateUserCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; User testUser (username); testUser.setPasswordHash (passwordHash); testUser.setEmail (email); testUser.setRank (rank); testUser.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // do storage StorageEngine::instance ().createUser (testUser); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (!k) { ASSERT_TRUE (false); // force error } } // change user data std::string newPasswordHash = "alskdjgasdlkj"; std::string newEmail = "new@email.org"; int newRank = 1; long newCreated_at = 1238799237; testUser.setPasswordHash (newPasswordHash); testUser.setEmail (newEmail); testUser.setRank (newRank); testUser.setCreatedAt (newCreated_at); StorageEngine::instance ().updateUser (testUser); // check that update has been successful { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (k) { ASSERT_EQ (k.getName (), testUser.getName ()); ASSERT_EQ (k.get<std::string> (), newPasswordHash); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT)); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL) .get<std::string> (), newEmail); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK).get<int> (), newRank); ASSERT_EQ ( ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT).get<long> (), newCreated_at); } else { ASSERT_TRUE (false); // force error } } // delete entry after test { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, DeleteUserCheck) { using namespace kdb; using namespace kdbrest::model; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; User testUser (username); testUser.setPasswordHash (passwordHash); testUser.setEmail (email); testUser.setRank (rank); testUser.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // do storage StorageEngine::instance ().createUser (testUser); // ensure that entry has been saved { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); Key k = ks.lookup (testUser); if (k) { ASSERT_EQ (k.getName (), testUser.getName ()); ASSERT_EQ (k.get<std::string> (), passwordHash); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK)); ASSERT_TRUE (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT)); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_EMAIL) .get<std::string> (), email); ASSERT_EQ (ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_RANK).get<int> (), rank); ASSERT_EQ ( ks.lookup (testUser.getName () + std::string ("/") + ELEKTRA_REST_MODEL_USER_META_CREATEDAT).get<long> (), created_at); } else { ASSERT_TRUE (false); // force error } } // delete user by storage engine StorageEngine::instance ().deleteUser (testUser); // ensure entry is not in database ASSERT_FALSE (StorageEngine::instance ().userExists (testUser.getUsername ())); { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (testUser); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, UserExistsCheck) { using namespace kdb; using namespace kdbrest::service; std::string username = "test-username"; kdbrest::model::User user (username); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check exists before creating key ASSERT_FALSE (StorageEngine::instance ().userExists (username)); // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.append (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check if exists now ASSERT_TRUE (StorageEngine::instance ().userExists (username)); // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } TEST (kdbrestServicesStorageengineTest, GetUserCheck) { using namespace kdb; using namespace kdbrest::service; std::string username = "test-username"; std::string passwordHash = "p455w0rdh45h"; std::string email = "random@email.org"; int rank = 2; long created_at = 123872923; kdbrest::model::User user (username); user.setPasswordHash (passwordHash); user.setEmail (email); user.setRank (rank); user.setCreatedAt (created_at); // ensure entry is not in database { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check exists before creating key ASSERT_FALSE (StorageEngine::instance ().userExists (username)); // create key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.append (user); ks.append (user.getSubkeys ()); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } // force re-fetching of user cache (void)StorageEngine::instance ().getAllUsersRef (true); // check if exists now ASSERT_TRUE (StorageEngine::instance ().userExists (username)); // find entry, check function kdbrest::model::User findUser = StorageEngine::instance ().getUser (username); ASSERT_TRUE (findUser.isValid ()); ASSERT_EQ (findUser.getName (), user.getName ()); ASSERT_EQ (findUser.getPasswordHash (), passwordHash); ASSERT_EQ (findUser.getEmail (), email); ASSERT_EQ (findUser.getRank (), rank); ASSERT_EQ (findUser.getCreatedAt (), created_at); // delete test key { KDB kdb; KeySet ks; kdb.get (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); ks.cut (user); kdb.set (ks, kdbrest::Config::instance ().getConfig ().get<std::string> ("kdb.path.users")); } } int main (int argc, char * argv[]) { testing::InitGoogleTest (&argc, argv); // initialize test config cppcms::json::value config = kdbrest::service::ConfigEngine::instance ().loadApplicationConfiguration (); (void)kdbrest::Config::instance ().initializeConfiguration (config); // force default config kdbrest::Config::instance ().setValue<std::string> ("kdb.path.configs", std::string (ELEKTRA_REST_DEFAULT_PATH_CONFIGS)); kdbrest::Config::instance ().setValue<std::string> ("kdb.path.users", std::string (ELEKTRA_REST_DEFAULT_PATH_USERS)); return RUN_ALL_TESTS (); }
31.390836
133
0.686072
0003088
92a7dd51e820cf25de011412acb3e38f1faad724
37,939
cpp
C++
Engine/Source/Developer/Profiler/Private/Widgets/SFiltersAndPresets.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Developer/Profiler/Private/Widgets/SFiltersAndPresets.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Developer/Profiler/Private/Widgets/SFiltersAndPresets.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "ProfilerPrivatePCH.h" #include "SSearchBox.h" #define LOCTEXT_NAMESPACE "SFiltersAndPresets" struct SFiltersAndPresetsHelper { static const FSlateBrush* GetIconForGroup() { return FEditorStyle::GetBrush( TEXT( "Profiler.Misc.GenericGroup" ) ); } static const FSlateBrush* GetIconForStatType( const EProfilerSampleTypes::Type StatType ) { const FSlateBrush* HierarchicalTimeIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.Hierarchical" ) ); const FSlateBrush* NumberIntIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.NumberInt" ) ); const FSlateBrush* NumberFloatIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.NumberFloat" ) ); const FSlateBrush* MemoryIcon = FEditorStyle::GetBrush( TEXT( "Profiler.Type.Memory" ) ); const FSlateBrush* const StatIcons[ EProfilerSampleTypes::InvalidOrMax ] = { HierarchicalTimeIcon, NumberIntIcon, NumberFloatIcon, MemoryIcon }; return StatIcons[ (int32)StatType ]; } }; /*----------------------------------------------------------------------------- Filter and presets tooltip -----------------------------------------------------------------------------*/ class SFiltersAndPresetsTooltip { const uint32 StatID; FProfilerSessionPtr ProfilerSession; public: SFiltersAndPresetsTooltip( const uint32 InStatID ) : StatID( InStatID ) { // TODO: At this moment only single profiler instance is supported. const int32 NumInstances = FProfilerManager::Get()->GetProfilerInstancesNum(); if( NumInstances == 1 ) { ProfilerSession = FProfilerManager::Get()->GetProfilerInstancesIterator().Value(); } } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION TSharedRef<SToolTip> GetTooltip() { if( ProfilerSession.IsValid() ) { const TSharedRef<SGridPanel> ToolTipGrid = SNew(SGridPanel); int CurrentRowPos = 0; AddHeader( ToolTipGrid, CurrentRowPos ); AddDescription( ToolTipGrid, CurrentRowPos ); const FProfilerAggregatedStat* AggregatedPtr = ProfilerSession->GetAggregatedStat( StatID ); if( AggregatedPtr ) { AddValuesInformation( ToolTipGrid, CurrentRowPos, *AggregatedPtr ); AddCallsInformation( ToolTipGrid, CurrentRowPos, *AggregatedPtr ); } else { AddNoDataInformation( ToolTipGrid, CurrentRowPos ); } return SNew(SToolTip) [ ToolTipGrid ]; } else { return SNew(SToolTip) .Text( LOCTEXT("NotImplemented","Tooltip for multiple profiler instances has not been implemented yet") ); } } protected: void AddNoDataInformation( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("NoStatData","There is no data for this stat") ) ]; RowPos++; } void AddHeader( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { const FString InstanceName = ProfilerSession->GetSessionType() == EProfilerSessionTypes::StatsFile ? FPaths::GetBaseFilename( ProfilerSession->GetName() ) : ProfilerSession->GetName(); Grid->AddSlot( 0, RowPos++ ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("StatInstance","Stat information for profiler instance") ) ]; Grid->AddSlot( 0, RowPos++ ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text( FText::FromString(InstanceName) ) ]; AddSeparator( Grid, RowPos ); } void AddDescription( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { const FProfilerStat& ProfilerStat = ProfilerSession->GetMetaData()->GetStatByID( StatID ); const EProfilerSampleTypes::Type SampleType = ProfilerSession->GetMetaData()->GetSampleTypeForStatID( StatID ); const FSlateBrush* const StatIcon = SFiltersAndPresetsHelper::GetIconForStatType( SampleType ); Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("GroupDesc","Group:") ) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) .ColumnSpan( 2 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text( FText::FromName(ProfilerStat.OwningGroup().Name() )) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("NameDesc","Name:") ) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) .ColumnSpan( 2 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text( FText::FromName(ProfilerStat.Name()) ) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("TypeDesc","Type:") ) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) .ColumnSpan( 2 ) [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .AutoWidth() [ SNew( SImage ) .Image( StatIcon ) ] +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Left) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text( FText::FromString(EProfilerSampleTypes::ToDescription(SampleType)) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) ] ]; RowPos++; AddSeparator( Grid, RowPos ); } void AddValuesInformation( const TSharedRef<SGridPanel>& Grid, int32& RowPos, const FProfilerAggregatedStat& Aggregated ) { Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text( LOCTEXT("ValueDesc","Value") ) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MinDesc", "Min: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMinValue)))) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("AvgDesc", "Avg: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EAvgValue)))) ]; Grid->AddSlot( 2, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MaxDesc", "Max: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMaxValue)))) ]; RowPos++; AddSeparator( Grid, RowPos ); } void AddCallsInformation( const TSharedRef<SGridPanel>& Grid, int32& RowPos, const FProfilerAggregatedStat& Aggregated ) { if( !Aggregated.HasCalls() ) { return; } Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.TooltipBold") ) .Text(FText::Format(LOCTEXT("CallsFramesPctDesc", "Calls Frames with call: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EFramesWithCallPct)))) ]; RowPos++; Grid->AddSlot( 0, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MinDesc", "Min: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMinNumCalls)))) ]; Grid->AddSlot( 1, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("AvgDesc", "Avg: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EAvgNumCalls)))) ]; Grid->AddSlot( 2, RowPos ) .Padding( 2.0f ) [ SNew(STextBlock) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .Text(FText::Format(LOCTEXT("MaxDesc", "Max: {0}"), FText::FromString(Aggregated.GetFormattedValue(FProfilerAggregatedStat::EMaxNumCalls)))) ]; RowPos++; AddSeparator( Grid, RowPos ); } void AddSeparator( const TSharedRef<SGridPanel>& Grid, int32& RowPos ) { Grid->AddSlot( 0, RowPos++ ) .Padding( 2.0f ) .ColumnSpan( 3 ) [ SNew(SSeparator) .Orientation( Orient_Horizontal ) ]; } END_SLATE_FUNCTION_BUILD_OPTIMIZATION }; /*----------------------------------------------------------------------------- EStatGroupingOrSortingMode -----------------------------------------------------------------------------*/ FText EStatGroupingOrSortingMode::ToName( const Type StatGroupingOrSortingMode ) { switch( StatGroupingOrSortingMode ) { case GroupName: return LOCTEXT("GroupingOrSorting_Name_GroupName", "Group Name"); case StatName: return LOCTEXT("GroupingOrSorting_Name_StatName", "Stat Name"); case StatType: return LOCTEXT("GroupingOrSorting_Name_StatType", "Stat Type"); case StatValue: return LOCTEXT("GroupingOrSorting_Name_StatValue", "Stat Value"); default: return LOCTEXT("InvalidOrMax", "InvalidOrMax"); } } FText EStatGroupingOrSortingMode::ToDescription(const Type StatGroupingOrSortingMode) { switch( StatGroupingOrSortingMode ) { case GroupName: return LOCTEXT("GroupingOrSorting_Desc_GroupName", "Creates groups based on stat metadata groups"); case StatName: return LOCTEXT("GroupingOrSorting_Desc_StatName", "Creates one group for one letter"); case StatType: return LOCTEXT("GroupingOrSorting_Desc_StatType", "Creates one group for each stat type"); case StatValue: return LOCTEXT("GroupingOrSorting_Desc_StatValue", "Creates one group for each logarithmic range ie. 0.001 - 0.01, 0.01 - 0.1, 0.1 - 1.0, 1.0 - 10.0 etc"); default: return LOCTEXT("InvalidOrMax", "InvalidOrMax"); } } FName EStatGroupingOrSortingMode::ToBrushName( const Type StatGroupingOrSortingMode ) { switch( StatGroupingOrSortingMode ) { case GroupName: return TEXT("Profiler.FiltersAndPresets.GroupNameIcon"); case StatName: return TEXT("Profiler.FiltersAndPresets.StatNameIcon"); case StatType: return TEXT("Profiler.FiltersAndPresets.StatTypeIcon"); case StatValue: return TEXT("Profiler.FiltersAndPresets.StatValueIcon"); default: return NAME_None; } } /*----------------------------------------------------------------------------- SGroupAndStatTableRow -----------------------------------------------------------------------------*/ DECLARE_DELEGATE_RetVal_OneParam( bool, FShouldBeEnabledDelegate, const uint32 /*StatID*/ ); /** Widget that represents a table row in the groups and stats' tree control. Generates widgets for each column on demand. */ class SGroupAndStatTableRow : public STableRow< FGroupOrStatNodePtr > { public: SLATE_BEGIN_ARGS( SGroupAndStatTableRow ) {} /** Text to be highlighted. */ SLATE_ATTRIBUTE( FText, HighlightText ) SLATE_EVENT( FShouldBeEnabledDelegate, OnShouldBeEnabled ) SLATE_END_ARGS() public: /** * Construct this widget. Called by the SNew() Slate macro. * * @param InArgs - Declaration used by the SNew() macro to construct this widget. * @param InOwnerTableView - The owner table into which this row is being placed. */ BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void Construct( const FArguments& InArgs, const TSharedRef<STableViewBase>& InOwnerTableView, const TSharedRef<FGroupOrStatNode>& InGroupOrStatNode ) { GroupOrStatNode = InGroupOrStatNode; OnShouldBeEnabled = InArgs._OnShouldBeEnabled; SetEnabled( TAttribute<bool>( this, &SGroupAndStatTableRow::HandleShouldBeEnabled ) ); const FSlateBrush* const IconForGroupOrStat = InGroupOrStatNode->IsGroup() ? SFiltersAndPresetsHelper::GetIconForGroup() : SFiltersAndPresetsHelper::GetIconForStatType( InGroupOrStatNode->GetStatType() ); const TSharedRef<SToolTip> Tooltip = InGroupOrStatNode->IsGroup() ? SNew(SToolTip) : SFiltersAndPresetsTooltip(InGroupOrStatNode->GetStatID()).GetTooltip(); ChildSlot [ SNew(SHorizontalBox) // Expander arrow. +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Right) .VAlign(VAlign_Center) [ SNew( SExpanderArrow, SharedThis(this) ) ] // Icon to visualize group or stat type. +SHorizontalBox::Slot() .AutoWidth() .Padding( 0.0f, 0.0f, 8.0f, 0.0f ) [ SNew( SImage ) .Image( IconForGroupOrStat ) .ToolTip( Tooltip ) ] // Description text. +SHorizontalBox::Slot() .AutoWidth() .VAlign( VAlign_Center ) .HAlign( HAlign_Left ) .Padding( FMargin( 2.0f, 0.0f ) ) [ SNew( STextBlock ) .Text( this, &SGroupAndStatTableRow::GetText ) .HighlightText( InArgs._HighlightText ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .ColorAndOpacity( this, &SGroupAndStatTableRow::GetColorAndOpacity ) ] +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Top ) .Padding( 0.0f, 1.0f, 0.0f, 0.0f ) [ SNew( SImage ) .Visibility( !InGroupOrStatNode->IsGroup() ? EVisibility::Visible : EVisibility::Collapsed ) .Image( FEditorStyle::GetBrush("Profiler.Tooltip.HintIcon10") ) .ToolTip( Tooltip ) ] ]; STableRow< FGroupOrStatNodePtr >::ConstructInternal( STableRow::FArguments() .ShowSelection(true), InOwnerTableView ); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION /** * Called when Slate detects that a widget started to be dragged. * Usage: * A widget can ask Slate to detect a drag. * OnMouseDown() reply with FReply::Handled().DetectDrag( SharedThis(this) ). * Slate will either send an OnDragDetected() event or do nothing. * If the user releases a mouse button or leaves the widget before * a drag is triggered (maybe user started at the very edge) then no event will be * sent. * * @param InMyGeometry Widget geometry * @param InMouseEvent MouseMove that triggered the drag * */ virtual FReply OnDragDetected( const FGeometry& MyGeometry, const FPointerEvent& MouseEvent ) override { if( MouseEvent.IsMouseButtonDown( EKeys::LeftMouseButton )) { if( GroupOrStatNode->IsGroup() ) { // Add all stat IDs for the group. TArray<int32> StatIDs; const TArray<FGroupOrStatNodePtr>& FilteredChildren = GroupOrStatNode->GetFilteredChildren(); const int32 NumFilteredChildren = FilteredChildren.Num(); StatIDs.Reserve( NumFilteredChildren ); for( int32 Nx = 0; Nx < NumFilteredChildren; ++Nx ) { StatIDs.Add( FilteredChildren[Nx]->GetStatID() ); } return FReply::Handled().BeginDragDrop( FStatIDDragDropOp::NewGroup( StatIDs, GroupOrStatNode->GetName().GetPlainNameString() ) ); } else { return FReply::Handled().BeginDragDrop( FStatIDDragDropOp::NewSingle( GroupOrStatNode->GetStatID(), GroupOrStatNode->GetName().GetPlainNameString() ) ); } } return STableRow< FGroupOrStatNodePtr >::OnDragDetected(MyGeometry,MouseEvent); } protected: /** * @return a text which describes this table row, refers to both groups and stats */ FText GetText() const { FText Text = FText::GetEmpty(); if( GroupOrStatNode->IsGroup() ) { int32 NumDisplayedStats = 0; const TArray<FGroupOrStatNodePtr>& Children = GroupOrStatNode->GetChildren(); const int32 NumChildren = Children.Num(); for( int32 Nx = 0; Nx < NumChildren; ++Nx ) { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( Children[Nx]->GetStatID() ); if( bIsStatTracked ) { NumDisplayedStats ++; } } Text = FText::Format(LOCTEXT("GroupAndStat_GroupNodeTextFmt", "{0} ({1}) ({2})"), FText::FromName(GroupOrStatNode->GetName()), FText::AsNumber(GroupOrStatNode->GetChildren().Num()), FText::AsNumber(NumDisplayedStats)); } else { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); if(bIsStatTracked) { Text = FText::Format(LOCTEXT("GroupAndStat_GroupNodeTrackedTextFmt", "{0}*"), FText::FromName(GroupOrStatNode->GetName())); } else { Text = FText::FromName(GroupOrStatNode->GetName()); } } return Text; } /** * @return a color and opacity value used to draw this table row, refers to both groups and stats */ FSlateColor GetColorAndOpacity() const { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); const FSlateColor Color = bIsStatTracked ? FProfilerManager::Get()->GetColorForStatID( GroupOrStatNode->GetStatID() ) : FLinearColor::White; return Color; //FProfilerManager::GetSettings().GetColorForStat( FName StatName ) } /** * @return a font style which is used to draw this table row, refers to both groups and stats */ FSlateFontInfo GetFont() const { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); const FSlateFontInfo FontInfo = bIsStatTracked ? FEditorStyle::GetFontStyle("BoldFont") : FEditorStyle::GetFontStyle("NormalFont"); return FontInfo; } bool HandleShouldBeEnabled() const { bool bResult = false; if( GroupOrStatNode->IsGroup() ) { bResult = true; } else { if( OnShouldBeEnabled.IsBound() ) { bResult = OnShouldBeEnabled.Execute( GroupOrStatNode->GetStatID() ); } } return bResult; } /** The tree item associated with this row of data. */ FGroupOrStatNodePtr GroupOrStatNode; FShouldBeEnabledDelegate OnShouldBeEnabled; }; /*----------------------------------------------------------------------------- SFiltersAndPresets -----------------------------------------------------------------------------*/ SFiltersAndPresets::SFiltersAndPresets() : GroupingMode( EStatGroupingOrSortingMode::GroupName ) , SortingMode( EStatGroupingOrSortingMode::StatName ) , bExpansionSaved( false ) { FMemory::Memset( bStatTypeIsVisible, 1 ); } SFiltersAndPresets::~SFiltersAndPresets() { // Remove ourselves from the profiler manager. if( FProfilerManager::Get().IsValid() ) { FProfilerManager::Get()->OnRequestFilterAndPresetsUpdate().RemoveAll( this ); } } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SFiltersAndPresets::Construct( const FArguments& InArgs ) { ChildSlot [ SNew(SVerticalBox) // Search box +SVerticalBox::Slot() .VAlign(VAlign_Center) .AutoHeight() [ SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush("ToolPanel.GroupBorder") ) .Padding( 2.0f ) [ SNew(SVerticalBox) // Search box +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SAssignNew( GroupAndStatSearchBox, SSearchBox ) .HintText( LOCTEXT("SearchBoxHint", "Search stats or groups") ) .OnTextChanged( this, &SFiltersAndPresets::SearchBox_OnTextChanged ) .IsEnabled( this, &SFiltersAndPresets::SearchBox_IsEnabled ) .ToolTipText( LOCTEXT("FilterSearchHint", "Type here to search stats or group") ) ] // Group by and Sort By +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .FillWidth( 1.0f ) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text( LOCTEXT("GroupByText", "Group by") ) ] +SHorizontalBox::Slot() .FillWidth( 2.0f ) .VAlign(VAlign_Center) [ SAssignNew( GroupByComboBox, SComboBox< TSharedPtr<EStatGroupingOrSortingMode::Type> > ) .ToolTipText( this, &SFiltersAndPresets::GroupBy_GetSelectedTooltipText ) .OptionsSource( &GroupByOptionsSource ) .OnSelectionChanged( this, &SFiltersAndPresets::GroupBy_OnSelectionChanged ) .OnGenerateWidget( this, &SFiltersAndPresets::GroupBy_OnGenerateWidget ) [ SNew( STextBlock ) .Text( this, &SFiltersAndPresets::GroupBy_GetSelectedText ) ] ] ] // Sort by +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .FillWidth( 1.0f ) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text( LOCTEXT("SortByText", "Sort by") ) ] +SHorizontalBox::Slot() .FillWidth( 2.0f ) .VAlign(VAlign_Center) [ SAssignNew( SortByComboBox, SComboBox< TSharedPtr<EStatGroupingOrSortingMode::Type> > ) .OptionsSource( &SortByOptionsSource ) .OnSelectionChanged( this, &SFiltersAndPresets::SortBy_OnSelectionChanged ) .OnGenerateWidget( this, &SFiltersAndPresets::SortBy_OnGenerateWidget ) [ SNew( STextBlock ) .Text( this, &SFiltersAndPresets::SortBy_GetSelectedText ) ] ] ] // Check boxes for: HierarchicalTime NumberFloat, NumberInt, Memory +SVerticalBox::Slot() .VAlign(VAlign_Center) .Padding( 2.0f ) .AutoHeight() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .Padding( FMargin(0.0f,0.0f,1.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::HierarchicalTime ) ] +SHorizontalBox::Slot() .Padding( FMargin(1.0f,0.0f,1.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::NumberFloat ) ] +SHorizontalBox::Slot() .Padding( FMargin(1.0f,0.0f,1.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::NumberInt ) ] +SHorizontalBox::Slot() .Padding( FMargin(1.0f,0.0f,0.0f,0.0f) ) .FillWidth( 1.0f ) [ GetToggleButtonForStatType( EProfilerSampleTypes::Memory ) ] ] ] ] // Stat groups tree +SVerticalBox::Slot() .FillHeight( 1.0f ) .Padding(0.0f, 6.0f, 0.0f, 0.0f) [ SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush("ToolPanel.GroupBorder") ) .Padding( 2.0f ) [ SAssignNew( GroupAndStatTree, STreeView< FGroupOrStatNodePtr > ) .SelectionMode(ESelectionMode::Single) .TreeItemsSource( &FilteredGroupNodes ) .OnGetChildren( this, &SFiltersAndPresets::GroupAndStatTree_OnGetChildren ) .OnGenerateRow( this, &SFiltersAndPresets::GroupAndStatTree_OnGenerateRow ) .OnMouseButtonDoubleClick( this, &SFiltersAndPresets::GroupAndStatTree_OnMouseButtonDoubleClick ) //.OnSelectionChanged( this, &SFiltersAndPresets::GroupAndStatTree_OnSelectionChanged ) .ItemHeight( 12 ) ] ] ]; // Register ourselves with the profiler manager. FProfilerManager::Get()->OnRequestFilterAndPresetsUpdate().AddSP( this, &SFiltersAndPresets::ProfilerManager_OnRequestFilterAndPresetsUpdate ); // Create the search filters: text based, stat type based etc. // @TODO: HandleItemToStringArray should be moved somewhere else GroupAndStatTextFilter = MakeShareable( new FGroupAndStatTextFilter( FGroupAndStatTextFilter::FItemToStringArray::CreateSP( this, &SFiltersAndPresets::HandleItemToStringArray ) ) ); GroupAndStatFilters = MakeShareable( new FGroupAndStatFilterCollection() ); GroupAndStatFilters->Add( GroupAndStatTextFilter ); CreateGroupByOptionsSources(); RecreateSortByOptionsSources(); } void SFiltersAndPresets::ProfilerManager_OnRequestFilterAndPresetsUpdate() { auto It = FProfilerManager::Get()->GetProfilerInstancesIterator(); UpdateGroupAndStatTree(It.Value()); } void SFiltersAndPresets::UpdateGroupAndStatTree( const FProfilerSessionPtr InProfilerSession ) { const bool bRebuild = InProfilerSession != ProfilerSession; if( bRebuild ) { StatNodesMap.Empty( StatNodesMap.Num() ); } ProfilerSession = InProfilerSession; const FProfilerStatMetaDataRef StatMetaData = ProfilerSession->GetMetaData(); // Create all stat nodes. for( auto It = StatMetaData->GetStatIterator(); It; ++It ) { const FProfilerStat& ProfilerStat = *It.Value(); const FName StatName = ProfilerStat.Name(); FGroupOrStatNodePtr* StatPtr = StatNodesMap.Find( StatName ); if( !StatPtr ) { StatPtr = &StatNodesMap.Add( StatName, MakeShareable( new FGroupOrStatNode( ProfilerStat.OwningGroup().Name(), StatName, ProfilerStat.ID(), ProfilerStat.Type() ) ) ); } // Update stat value ? } // Create groups, sort stats within the group and apply filtering. CreateGroups(); SortStats(); ApplyFiltering(); } void SFiltersAndPresets::CreateGroups() { // Creates groups based on stat metadata groups. TMap< FName, FGroupOrStatNodePtr > GroupNodeSet; if( GroupingMode == EStatGroupingOrSortingMode::GroupName ) { for( auto It = StatNodesMap.CreateIterator(); It; ++It ) { const FGroupOrStatNodePtr& StatNodePtr = It.Value(); const FName GroupName = StatNodePtr->GetMetaGropName(); FGroupOrStatNodePtr* GroupPtr = GroupNodeSet.Find( GroupName ); if( !GroupPtr ) { GroupPtr = &GroupNodeSet.Add( GroupName, MakeShareable(new FGroupOrStatNode( GroupName )) ); } (*GroupPtr)->AddChildAndSetGroupPtr( StatNodePtr ); } } // Creates one group for each stat type. else if( GroupingMode == EStatGroupingOrSortingMode::StatType ) { for( auto It = StatNodesMap.CreateIterator(); It; ++It ) { const FGroupOrStatNodePtr& StatNodePtr = It.Value(); const FName GroupName = *EProfilerSampleTypes::ToName( StatNodePtr->GetStatType() ); FGroupOrStatNodePtr* GroupPtr = GroupNodeSet.Find( GroupName ); if( !GroupPtr ) { GroupPtr = &GroupNodeSet.Add( GroupName, MakeShareable(new FGroupOrStatNode( GroupName )) ); } (*GroupPtr)->AddChildAndSetGroupPtr( StatNodePtr ); } } // Creates one group for each logarithmic range ie. 0.001 - 0.01, 0.01 - 0.1, 0.1 - 1.0, 1.0 - 10.0 etc. else if( GroupingMode == EStatGroupingOrSortingMode::StatValue ) { // TODO: } // Creates one group for one letter. else if( GroupingMode == EStatGroupingOrSortingMode::StatName ) { for( auto It = StatNodesMap.CreateIterator(); It; ++It ) { const FGroupOrStatNodePtr& StatNodePtr = It.Value(); const FName GroupName = *StatNodePtr->GetName().GetPlainNameString().Left(1); FGroupOrStatNodePtr* GroupPtr = GroupNodeSet.Find( GroupName ); if( !GroupPtr ) { GroupPtr = &GroupNodeSet.Add( GroupName, MakeShareable(new FGroupOrStatNode( GroupName )) ); } (*GroupPtr)->AddChildAndSetGroupPtr( StatNodePtr ); } } GroupNodeSet.GenerateValueArray( GroupNodes ); // Sort by a fake group name. GroupNodes.Sort( FGroupAndStatSorting::ByStatName() ); } void SFiltersAndPresets::SortStats() { const int32 NumGroups = GroupNodes.Num(); // Sorts stats inside group by a group name. if( SortingMode == EStatGroupingOrSortingMode::GroupName ) { for( int32 ID = 0; ID < NumGroups; ++ID ) { GroupNodes[ID]->SortChildren( FGroupAndStatSorting::ByGroupName() ); } } // Sorts stats inside group by a stat type. else if( SortingMode == EStatGroupingOrSortingMode::StatType ) { for( int32 ID = 0; ID < NumGroups; ++ID ) { GroupNodes[ID]->SortChildren( FGroupAndStatSorting::ByStatType() ); } } // Sorts stats inside group by a stat value. else if( SortingMode == EStatGroupingOrSortingMode::StatValue ) { } // Sorts stats inside group by a stat name. else if( SortingMode == EStatGroupingOrSortingMode::StatName ) { for( int32 ID = 0; ID < NumGroups; ++ID ) { GroupNodes[ID]->SortChildren( FGroupAndStatSorting::ByStatName() ); } } } void SFiltersAndPresets::ApplyFiltering() { FilteredGroupNodes.Reset(); // Apply filter to all groups and its children. const int32 NumGroups = GroupNodes.Num(); for( int32 ID = 0; ID < NumGroups; ++ID ) { FGroupOrStatNodePtr& GroupPtr = GroupNodes[ID]; GroupPtr->ClearFilteredChildren(); const bool bIsGroupVisible = GroupAndStatFilters->PassesAllFilters( GroupPtr ); const TArray<FGroupOrStatNodePtr>& GroupChildren = GroupPtr->GetChildren(); const int32 NumChildren = GroupChildren.Num(); int32 NumVisibleChildren = 0; for( int32 Cx = 0; Cx < NumChildren; ++Cx ) { // Add a child. const FGroupOrStatNodePtr& StatPtr = GroupChildren[Cx]; const bool bIsChildVisible = GroupAndStatFilters->PassesAllFilters( StatPtr ) && bStatTypeIsVisible[StatPtr->GetStatType()]; if( bIsChildVisible ) { GroupPtr->AddFilteredChild( StatPtr ); } NumVisibleChildren += bIsChildVisible ? 1 : 0; } if( bIsGroupVisible || NumVisibleChildren>0 ) { // Add a group. FilteredGroupNodes.Add( GroupPtr ); GroupPtr->bForceExpandGroupNode = true; } else { GroupPtr->bForceExpandGroupNode = false; } } // Only expand group and stat nodes if we have a text filter. const bool bNonEmptyTextFilter = !GroupAndStatTextFilter->GetRawFilterText().IsEmpty(); if( bNonEmptyTextFilter ) { if( !bExpansionSaved ) { ExpandedNodes.Empty(); GroupAndStatTree->GetExpandedItems( ExpandedNodes ); bExpansionSaved = true; } for( int32 Fx = 0; Fx < FilteredGroupNodes.Num(); Fx++ ) { const FGroupOrStatNodePtr& GroupPtr = FilteredGroupNodes[Fx]; GroupAndStatTree->SetItemExpansion( GroupPtr, GroupPtr->bForceExpandGroupNode ); } } else { if( bExpansionSaved ) { // Restore previously expanded nodes when the text filter is disabled. GroupAndStatTree->ClearExpandedItems(); for( auto It = ExpandedNodes.CreateConstIterator(); It; ++It ) { GroupAndStatTree->SetItemExpansion( *It, true ); } bExpansionSaved = false; } } // Request tree refresh GroupAndStatTree->RequestTreeRefresh(); } void SFiltersAndPresets::HandleItemToStringArray( const FGroupOrStatNodePtr& GroupOrStatNodePtr, TArray< FString >& out_SearchStrings ) const { // Add group or stat name. out_SearchStrings.Add( GroupOrStatNodePtr->GetName().GetPlainNameString() ); } void SFiltersAndPresets::CreateGroupByOptionsSources() { GroupByOptionsSource.Reset( 4 ); // Must be added in order of elements in the EStatGroupingOrSortingMode. GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::GroupName ) ) ); GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatName ) ) ); GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatType ) ) ); //GroupByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatValue ) ) ); GroupByComboBox->SetSelectedItem( GroupByOptionsSource[EStatGroupingOrSortingMode::GroupName] ); GroupByComboBox->RefreshOptions(); } void SFiltersAndPresets::RecreateSortByOptionsSources() { SortByOptionsSource.Reset( 4 ); // Must be added in order of elements in the EStatGroupingOrSortingMode. SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::GroupName ) ) ); SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatName ) ) ); SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatType ) ) ); //SortByOptionsSource.Add( MakeShareable( new EStatGroupingOrSortingMode::Type( EStatGroupingOrSortingMode::StatValue ) ) ); // @TODO: Remove useless stat sorting ie: when grouped by group name, sorting by group name doesn't change anything. // Select default sorting mode based on the grouping mode. if( GroupingMode == EStatGroupingOrSortingMode::GroupName ) { SortingMode = EStatGroupingOrSortingMode::StatName; SortByComboBox->SetSelectedItem( SortByOptionsSource[SortingMode] ); SortByOptionsSource.RemoveAtSwap( (int32)GroupingMode ); } else if( GroupingMode == EStatGroupingOrSortingMode::StatName ) { SortingMode = EStatGroupingOrSortingMode::StatName; SortByComboBox->SetSelectedItem( SortByOptionsSource[SortingMode] ); } else if( GroupingMode == EStatGroupingOrSortingMode::StatType ) { SortingMode = EStatGroupingOrSortingMode::StatName; SortByComboBox->SetSelectedItem( SortByOptionsSource[SortingMode] ); } else if( GroupingMode == EStatGroupingOrSortingMode::StatValue ) { // TODO: } SortByComboBox->RefreshOptions(); } TSharedRef<SWidget> SFiltersAndPresets::GetToggleButtonForStatType( const EProfilerSampleTypes::Type StatType ) { return SNew( SCheckBox ) .Style( FEditorStyle::Get(), "ToggleButtonCheckbox" ) .HAlign( HAlign_Center ) .Padding( 2.0f ) .OnCheckStateChanged( this, &SFiltersAndPresets::FilterByStatType_OnCheckStateChanged, StatType ) .IsChecked( this, &SFiltersAndPresets::FilterByStatType_IsChecked, StatType ) .ToolTipText( FText::FromString(EProfilerSampleTypes::ToDescription( StatType )) ) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .VAlign( VAlign_Center ) [ SNew(SImage) .Image( SFiltersAndPresetsHelper::GetIconForStatType( StatType ) ) ] +SHorizontalBox::Slot() .Padding(2.0f, 0.0f, 0.0f, 0.0f) .VAlign( VAlign_Center ) [ SNew( STextBlock ) .Text( FText::FromString(EProfilerSampleTypes::ToName( StatType )) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Caption") ) ] ]; } void SFiltersAndPresets::FilterByStatType_OnCheckStateChanged( ECheckBoxState NewRadioState, const EProfilerSampleTypes::Type InStatType ) { bStatTypeIsVisible[InStatType] = NewRadioState == ECheckBoxState::Checked; ApplyFiltering(); } ECheckBoxState SFiltersAndPresets::FilterByStatType_IsChecked( const EProfilerSampleTypes::Type InStatType ) const { return bStatTypeIsVisible[InStatType] ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; } /*----------------------------------------------------------------------------- GroupAndStatTree -----------------------------------------------------------------------------*/ TSharedRef< ITableRow > SFiltersAndPresets::GroupAndStatTree_OnGenerateRow( FGroupOrStatNodePtr GroupOrStatNode, const TSharedRef< STableViewBase >& OwnerTable ) { TSharedRef< ITableRow > TableRow = SNew(SGroupAndStatTableRow, OwnerTable, GroupOrStatNode.ToSharedRef()) .OnShouldBeEnabled( this, &SFiltersAndPresets::GroupAndStatTableRow_ShouldBeEnabled ) .HighlightText( this, &SFiltersAndPresets::GroupAndStatTableRow_GetHighlightText ); return TableRow; } void SFiltersAndPresets::GroupAndStatTree_OnGetChildren( FGroupOrStatNodePtr InParent, TArray< FGroupOrStatNodePtr >& out_Children ) { out_Children = InParent->GetFilteredChildren(); } void SFiltersAndPresets::GroupAndStatTree_OnMouseButtonDoubleClick( FGroupOrStatNodePtr GroupOrStatNode ) { // @TODO: Add mechanism which will synchronize displayed stats between: GraphPanel, FilterAndPresets and ProfilerManager if( !GroupOrStatNode->IsGroup() ) { const bool bIsStatTracked = FProfilerManager::Get()->IsStatTracked( GroupOrStatNode->GetStatID() ); if( !bIsStatTracked ) { // Add a new graph. FProfilerManager::Get()->TrackStat( GroupOrStatNode->GetStatID() ); } else { // Remove a graph FProfilerManager::Get()->UntrackStat( GroupOrStatNode->GetStatID() ); } } else { const bool bIsGroupExpanded = GroupAndStatTree->IsItemExpanded( GroupOrStatNode ); GroupAndStatTree->SetItemExpansion( GroupOrStatNode, !bIsGroupExpanded ); } } FText SFiltersAndPresets::GroupAndStatTableRow_GetHighlightText() const { return GroupAndStatSearchBox->GetText(); } bool SFiltersAndPresets::GroupAndStatTableRow_ShouldBeEnabled( const uint32 StatID ) const { return ProfilerSession->GetAggregatedStat( StatID ) != nullptr; } /*----------------------------------------------------------------------------- SearchBox -----------------------------------------------------------------------------*/ void SFiltersAndPresets::SearchBox_OnTextChanged( const FText& InFilterText ) { GroupAndStatTextFilter->SetRawFilterText( InFilterText ); GroupAndStatSearchBox->SetError( GroupAndStatTextFilter->GetFilterErrorText() ); ApplyFiltering(); } bool SFiltersAndPresets::SearchBox_IsEnabled() const { return StatNodesMap.Num() > 0; } /*----------------------------------------------------------------------------- GroupBy -----------------------------------------------------------------------------*/ void SFiltersAndPresets::GroupBy_OnSelectionChanged( TSharedPtr<EStatGroupingOrSortingMode::Type> NewGroupingMode, ESelectInfo::Type SelectInfo ) { if( SelectInfo != ESelectInfo::Direct ) { GroupingMode = *NewGroupingMode; // Create groups, sort stats within the group and apply filtering. CreateGroups(); SortStats(); ApplyFiltering(); RecreateSortByOptionsSources(); } } TSharedRef<SWidget> SFiltersAndPresets::GroupBy_OnGenerateWidget( TSharedPtr<EStatGroupingOrSortingMode::Type> InGroupingMode ) const { return SNew( STextBlock ) .Text( EStatGroupingOrSortingMode::ToName( *InGroupingMode ) ) .ToolTipText( EStatGroupingOrSortingMode::ToDescription( *InGroupingMode ) ); } FText SFiltersAndPresets::GroupBy_GetSelectedText() const { return EStatGroupingOrSortingMode::ToName( GroupingMode ); } FText SFiltersAndPresets::GroupBy_GetSelectedTooltipText() const { return EStatGroupingOrSortingMode::ToDescription( GroupingMode ); } /*----------------------------------------------------------------------------- SortBy -----------------------------------------------------------------------------*/ void SFiltersAndPresets::SortBy_OnSelectionChanged( TSharedPtr<EStatGroupingOrSortingMode::Type> NewSortingMode, ESelectInfo::Type SelectInfo ) { if( SelectInfo != ESelectInfo::Direct ) { SortingMode = *NewSortingMode; // Create groups, sort stats within the group and apply filtering. SortStats(); ApplyFiltering(); } } TSharedRef<SWidget> SFiltersAndPresets::SortBy_OnGenerateWidget( TSharedPtr<EStatGroupingOrSortingMode::Type> InSortingMode ) const { return SNew( STextBlock ) .Text( EStatGroupingOrSortingMode::ToName( *InSortingMode ) ) .ToolTipText( EStatGroupingOrSortingMode::ToDescription( *InSortingMode ) ); } FText SFiltersAndPresets::SortBy_GetSelectedText() const { return EStatGroupingOrSortingMode::ToName( SortingMode ); } #undef LOCTEXT_NAMESPACE
31.432477
221
0.699518
PopCap
92ac653f1ffe2d4ef4b60de2ad61758cf81572e8
1,018
cpp
C++
ABC/ABC123/D.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
1
2021-06-01T17:13:44.000Z
2021-06-01T17:13:44.000Z
ABC/ABC123/D.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
ABC/ABC123/D.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <cstdio> #include <cmath> #include <vector> #include <string> #include <algorithm> #include <map> #include <set> #include <queue> #define FOR(idx, begin, end) for(int idx = (int)(begin); idx < (int)(end); ++idx) #ifdef _DEBUG #define DMP(x) cerr << #x << ": " << x << "\n" #else #define DMP(x) ((void)0) #endif using namespace std; typedef long long lint; const int MOD = 100000007; const int INF = 1 << 29; const double EPS = 1e-9; int main() { cin.tie(0); lint X, Y, Z, K; cin >> X >> Y >> Z >> K; vector<lint> A(X), B(Y), C(Z), ans(K); FOR(i, 0, X)cin >> A[i]; FOR(i, 0, Y)cin >> B[i]; FOR(i, 0, Z)cin >> C[i]; sort(A.begin(), A.end(), greater<lint>()); sort(B.begin(), B.end(), greater<lint>()); sort(C.begin(), C.end(), greater<lint>()); FOR(a,0,X)FOR(b,0,Y)FOR(c,0,Z){ if ((a + 1)*(b + 1)*(c+1)<=K) ans.emplace_back(A[a] + B[b] + C[c]); } sort(ans.begin(), ans.end(), greater<lint>()); FOR(i, 0, K) cout << ans[i] << "\n"; return 0; }
19.576923
81
0.561886
rajyan
92ad49abdabd7841d02335f02ead881f4afa5eaf
2,569
cc
C++
src/developer/debug/zxdb/symbols/dwarf_lang.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/developer/debug/zxdb/symbols/dwarf_lang.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/developer/debug/zxdb/symbols/dwarf_lang.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2019 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 "src/developer/debug/zxdb/symbols/dwarf_lang.h" namespace zxdb { bool DwarfLangIsCFamily(DwarfLang lang) { // clang-format off return lang == DwarfLang::kC89 || lang == DwarfLang::kC || lang == DwarfLang::kCpp || lang == DwarfLang::kC99 || lang == DwarfLang::kObjC || lang == DwarfLang::kObjCpp || lang == DwarfLang::kCpp03 || lang == DwarfLang::kCpp11 || lang == DwarfLang::kC11 || lang == DwarfLang::kCpp14; // clang-format on } const char* DwarfLangToString(DwarfLang lang) { // clang-format off switch (lang) { case DwarfLang::kNone: return "None"; case DwarfLang::kC89: return "C89"; case DwarfLang::kC: return "C"; case DwarfLang::kAda83: return "Ada83"; case DwarfLang::kCpp: return "C++"; case DwarfLang::kCobol74: return "Cobol74"; case DwarfLang::kCobol85: return "Cobol85"; case DwarfLang::kFortran77: return "Fortran77"; case DwarfLang::kFortran90: return "Fortran90"; case DwarfLang::kPascal83: return "Pascal83"; case DwarfLang::kModula2: return "Modula2"; case DwarfLang::kJava: return "Java"; case DwarfLang::kC99: return "C99"; case DwarfLang::kAda95: return "Ada95"; case DwarfLang::kFortran95: return "Fortran95"; case DwarfLang::kPLI: return "PLI"; case DwarfLang::kObjC: return "ObjC"; case DwarfLang::kObjCpp: return "ObjC++"; case DwarfLang::kUPC: return "UPC"; case DwarfLang::kD: return "D"; case DwarfLang::kPython: return "Python"; case DwarfLang::kOpenCL: return "OpenCL"; case DwarfLang::kGo: return "Go"; case DwarfLang::kModula3: return "Modula3"; case DwarfLang::kHaskell: return "Haskell"; case DwarfLang::kCpp03: return "C++03"; case DwarfLang::kCpp11: return "C++11"; case DwarfLang::kOCaml: return "OCaml"; case DwarfLang::kRust: return "Rust"; case DwarfLang::kC11: return "C11"; case DwarfLang::kSwift: return "Swift"; case DwarfLang::kJulia: return "Julia"; case DwarfLang::kDylan: return "Dylan"; case DwarfLang::kCpp14: return "C++14"; case DwarfLang::kFortran03: return "Fortran03"; case DwarfLang::kFortran08: return "Fortran08"; case DwarfLang::kRenderScript: return "RenderScript"; case DwarfLang::kBLISS: return "BLISS"; default: return "<Unknown>"; } // clang-format on } } // namespace zxdb
36.183099
73
0.661736
allansrc
92b1144443ce18ad5f19b27b82200db1b051780f
7,191
cpp
C++
src/BabylonCpp/src/gizmos/plane_drag_gizmo.cpp
samdauwe/BabylonCpp
eea9f761a49bb460ff1324c20e4674ef120e94f1
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/BabylonCpp/src/gizmos/plane_drag_gizmo.cpp
samdauwe/BabylonCpp
eea9f761a49bb460ff1324c20e4674ef120e94f1
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/BabylonCpp/src/gizmos/plane_drag_gizmo.cpp
samdauwe/BabylonCpp
eea9f761a49bb460ff1324c20e4674ef120e94f1
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/gizmos/plane_drag_gizmo.h> #include <babylon/babylon_stl_util.h> #include <babylon/engines/scene.h> #include <babylon/gizmos/position_gizmo.h> #include <babylon/lights/hemispheric_light.h> #include <babylon/materials/standard_material.h> #include <babylon/meshes/builders/mesh_builder_options.h> #include <babylon/meshes/builders/plane_builder.h> #include <babylon/meshes/instanced_mesh.h> #include <babylon/meshes/mesh.h> #include <babylon/meshes/transform_node.h> namespace BABYLON { TransformNodePtr PlaneDragGizmo::_CreatePlane(Scene* scene, const StandardMaterialPtr& material) { auto plane = TransformNode::New("plane", scene); // make sure plane is double sided PlaneOptions options; options.width = 0.1375f; options.height = 0.1375f; options.sideOrientation = 2u; auto dragPlane = PlaneBuilder::CreatePlane("dragPlane", options, scene); dragPlane->material = material; dragPlane->parent = plane.get(); return plane; } PlaneDragGizmo::PlaneDragGizmo(const Vector3& dragPlaneNormal, const Color3& color, const UtilityLayerRendererPtr& iGizmoLayer, PositionGizmo* parent) : Gizmo{iGizmoLayer} , snapDistance{0.f} , isEnabled{this, &PlaneDragGizmo::get_isEnabled, &PlaneDragGizmo::set_isEnabled} , _pointerObserver{nullptr} , _gizmoMesh{nullptr} , _coloredMaterial{nullptr} , _hoverMaterial{nullptr} , _disableMaterial{nullptr} , _isEnabled{false} , _parent{nullptr} , _dragging{false} , tmpSnapEvent{SnapEvent{0.f}} { _parent = parent; // Create Material _coloredMaterial = StandardMaterial::New("", iGizmoLayer->utilityLayerScene.get()); _coloredMaterial->diffuseColor = color; _coloredMaterial->specularColor = color.subtract(Color3(0.1f, 0.1f, 0.1f)); _hoverMaterial = StandardMaterial::New("", iGizmoLayer->utilityLayerScene.get()); _hoverMaterial->diffuseColor = Color3::Yellow(); _disableMaterial = StandardMaterial::New("", gizmoLayer->utilityLayerScene.get()); _disableMaterial->diffuseColor = Color3::Gray(); _disableMaterial->alpha = 0.4f; // Build plane mesh on root node _gizmoMesh = PlaneDragGizmo::_CreatePlane(gizmoLayer->utilityLayerScene.get(), _coloredMaterial); _gizmoMesh->lookAt(_rootMesh->position().add(dragPlaneNormal)); _gizmoMesh->scaling().scaleInPlace(1.f / 3.f); _gizmoMesh->parent = _rootMesh.get(); currentSnapDragDistance = 0.f; // Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged PointerDragBehaviorOptions options; options.dragPlaneNormal = dragPlaneNormal; dragBehavior = std::make_shared<PointerDragBehavior>(options); dragBehavior->moveAttached = false; // _rootMesh->addBehavior(dragBehavior); dragBehavior->onDragObservable.add([this](DragMoveEvent* event, EventState& /*es*/) -> void { if (attachedNode()) { _handlePivot(); // Keep world translation and use it to update world transform // if the node has parent, the local transform properties (position, rotation, scale) // will be recomputed in _matrixChanged function // Snapping logic if (snapDistance == 0.f) { attachedNode()->getWorldMatrix().addTranslationFromFloats(event->delta.x, event->delta.y, event->delta.z); } else { currentSnapDragDistance += event->dragDistance; if (std::abs(currentSnapDragDistance) > snapDistance) { auto dragSteps = std::floor(std::abs(currentSnapDragDistance) / snapDistance); currentSnapDragDistance = std::fmod(currentSnapDragDistance, snapDistance); event->delta.normalizeToRef(tmpVector); tmpVector.scaleInPlace(snapDistance * dragSteps); attachedNode()->getWorldMatrix().addTranslationFromFloats(tmpVector.x, tmpVector.y, tmpVector.z); tmpSnapEvent.snapDistance = snapDistance * dragSteps; onSnapObservable.notifyObservers(&tmpSnapEvent); } } _matrixChanged(); } }); dragBehavior->onDragStartObservable.add( [this](DragStartOrEndEvent* /*evt*/, EventState& /*es*/) -> void { _dragging = true; }); dragBehavior->onDragEndObservable.add( [this](DragStartOrEndEvent* /*evt*/, EventState& /*es*/) -> void { _dragging = false; }); auto light = gizmoLayer->_getSharedGizmoLight(); light->includedOnlyMeshes = stl_util::concat(light->includedOnlyMeshes(), _rootMesh->getChildMeshes(false)); const auto toMeshArray = [](const std::vector<AbstractMeshPtr>& meshes) -> std::vector<MeshPtr> { std::vector<MeshPtr> meshArray; meshArray.reserve(meshes.size()); for (const auto& mesh : meshes) { meshArray.emplace_back(std::static_pointer_cast<Mesh>(mesh)); } return meshArray; }; _cache.gizmoMeshes = toMeshArray(_gizmoMesh->getChildMeshes()); _cache.colliderMeshes = toMeshArray(_gizmoMesh->getChildMeshes()); _cache.material = _coloredMaterial; _cache.hoverMaterial = _hoverMaterial; _cache.disableMaterial = _disableMaterial; _cache.active = false; _cache.dragBehavior = dragBehavior; if (_parent) { _parent->addToAxisCache(static_cast<Mesh*>(_gizmoMesh.get()), _cache); } _pointerObserver = gizmoLayer->utilityLayerScene->onPointerObservable.add( [this](PointerInfo* pointerInfo, EventState& /*es*/) -> void { if (_customMeshSet) { return; } auto pickedMesh = std::static_pointer_cast<Mesh>(pointerInfo->pickInfo.pickedMesh); _isHovered = stl_util::contains(_cache.colliderMeshes, pickedMesh); if (!_parent) { const auto material = _cache.dragBehavior->enabled ? (_isHovered || _dragging ? _hoverMaterial : _coloredMaterial) : _disableMaterial; _setGizmoMeshMaterial(_cache.gizmoMeshes, material); } }); dragBehavior->onEnabledObservable.add([this](bool* newState, EventState& /*es*/) -> void { _setGizmoMeshMaterial(_cache.gizmoMeshes, *newState ? _coloredMaterial : _disableMaterial); }); } PlaneDragGizmo::~PlaneDragGizmo() = default; void PlaneDragGizmo::_attachedNodeChanged(const NodePtr& value) { dragBehavior->enabled = value ? true : false; } void PlaneDragGizmo::set_isEnabled(bool value) { _isEnabled = value; if (!value) { attachedNode = nullptr; } else { if (_parent) { attachedNode = _parent->attachedNode(); } } } bool PlaneDragGizmo::get_isEnabled() const { return _isEnabled; } void PlaneDragGizmo::dispose(bool /*doNotRecurse*/, bool /*disposeMaterialAndTextures*/) { onSnapObservable.clear(); gizmoLayer->utilityLayerScene->onPointerObservable.remove(_pointerObserver); dragBehavior->detach(); Gizmo::dispose(); if (_gizmoMesh) { _gizmoMesh->dispose(); } for (const auto& matl : {_coloredMaterial, _hoverMaterial, _disableMaterial}) { if (matl) { matl->dispose(); } } } } // namespace BABYLON
36.688776
100
0.681129
samdauwe
92b27659ae0fc9884ea551f525dc787337b01179
534
hpp
C++
table/include/item_set.hpp
TheAspiringHacker/Asparserations
2962c685f5aa36fde966a1ea2a4549401c39ba37
[ "MIT" ]
12
2017-08-27T21:12:30.000Z
2018-09-17T05:42:42.000Z
table/include/item_set.hpp
TheAspiringHacker/Asparserations
2962c685f5aa36fde966a1ea2a4549401c39ba37
[ "MIT" ]
1
2021-06-16T20:44:33.000Z
2021-06-16T20:44:33.000Z
table/include/item_set.hpp
TheAspiringHacker/Asparserations
2962c685f5aa36fde966a1ea2a4549401c39ba37
[ "MIT" ]
1
2021-07-27T07:42:26.000Z
2021-07-27T07:42:26.000Z
#ifndef ASPARSERATIONS_TABLE_ITEM_SET_H_ #define ASPARSERATIONS_TABLE_ITEM_SET_H_ #include "item.hpp" #include <set> namespace asparserations { namespace table { class Item_Set { friend bool operator<(const Item_Set&, const Item_Set&); public: Item_Set(const std::set<Item>&); const std::set<Item>& items() const; void insert(const Item&); bool merge(const Item_Set&); private: std::set<Item> m_items; }; bool operator<(const Item_Set&, const Item_Set&); } } #endif
20.538462
62
0.666667
TheAspiringHacker
92b39c56d4725cc5af4999bb319eda82e936e79c
32,603
cpp
C++
src/OpenGL/frontend/gl_formats.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
114
2018-08-05T16:26:53.000Z
2021-12-30T07:28:35.000Z
src/OpenGL/frontend/gl_formats.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
5
2018-08-18T21:16:58.000Z
2018-11-22T21:50:48.000Z
src/OpenGL/frontend/gl_formats.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
6
2018-08-05T22:32:28.000Z
2021-10-04T15:39:53.000Z
/* VKGL (c) 2018 Dominik Witczak * * This code is licensed under MIT license (see LICENSE.txt for details) */ #include "Common/macros.h" #include "OpenGL/frontend/gl_formats.h" typedef struct InternalFormatData { OpenGL::FormatDataType data_type; uint32_t n_components; /* For base and compressed internal formats, "1" indicates the component is used. * For sized internal formats, non-zero value indicates the component is used and describes the component size in bits. */ uint32_t component_size_r; uint32_t component_size_g; uint32_t component_size_b; uint32_t component_size_a; uint32_t component_size_depth; uint32_t component_size_stencil; uint32_t component_size_shared; bool is_base_internal_format; bool is_compressed_internal_format; bool is_sized_internal_format; InternalFormatData() { memset(this, 0, sizeof(*this) ); } InternalFormatData(const OpenGL::FormatDataType& in_data_type, const uint32_t& in_n_components, const uint32_t& in_component_size_r, const uint32_t& in_component_size_g, const uint32_t& in_component_size_b, const uint32_t& in_component_size_a, const uint32_t& in_component_size_depth, const uint32_t& in_component_size_stencil, const uint32_t& in_component_size_shared, const bool& in_is_base_internal_format, const bool& in_is_compressed_internal_format, const bool& in_is_sized_internal_format) :data_type (in_data_type), n_components (in_n_components), component_size_r (in_component_size_r), component_size_g (in_component_size_g), component_size_b (in_component_size_b), component_size_a (in_component_size_a), component_size_depth (in_component_size_depth), component_size_stencil (in_component_size_stencil), component_size_shared (in_component_size_shared), is_base_internal_format (in_is_base_internal_format), is_compressed_internal_format(in_is_compressed_internal_format), is_sized_internal_format (in_is_sized_internal_format) { /* Stub */ } } InternalFormatData; OpenGL::PixelFormat; static const std::unordered_map<OpenGL::InternalFormat, InternalFormatData> g_gl_internalformat_data = { /* Base internal formats */ /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::Depth_Component, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 0, 0, 0, 0, 1, 0, 0, true, false, false)}, {OpenGL::InternalFormat::Depth_Stencil, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 0, 0, 0, 0, 1, 1, 0, true, false, false)}, {OpenGL::InternalFormat::Red, InternalFormatData(OpenGL::FormatDataType::Unknown, 1, 1, 0, 0, 0, 0, 0, 0, true, false, false)}, {OpenGL::InternalFormat::RG, InternalFormatData(OpenGL::FormatDataType::Unknown, 2, 1, 1, 0, 0, 0, 0, 0, true, false, false)}, {OpenGL::InternalFormat::RGB, InternalFormatData(OpenGL::FormatDataType::Unknown, 3, 1, 1, 1, 0, 0, 0, 0, true, false, false)}, {OpenGL::InternalFormat::RGBA, InternalFormatData(OpenGL::FormatDataType::Unknown, 4, 1, 1, 1, 1, 0, 0, 0, true, false, false)}, /* Sized internal formats */ /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::R11F_G11F_B10F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 11, 11, 10, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 16, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R3_G3_B2, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 3, 3, 2, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R32I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 32, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8I, InternalFormatData(OpenGL::FormatDataType::SInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::R8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 1, 8, 0, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 16, 16, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG32I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 32, 32, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8I, InternalFormatData(OpenGL::FormatDataType::SInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RG8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 2, 8, 8, 0, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB10, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 10, 10, 10, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB10_A2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB10_A2UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 10, 10, 10, 2, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB12, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 12, 12, 12, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 16, 16, 16, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB32I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 32, 32, 32, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB4, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 4, 4, 4, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB5, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 5, 5, 5, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB5_A1, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 5, 5, 5, 1, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8I, InternalFormatData(OpenGL::FormatDataType::SInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGB9_E5, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 9, 9, 9, 0, 0, 0, 5, false, false, true)}, {OpenGL::InternalFormat::RGBA12, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 12, 12, 12, 12, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA16UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 16, 16, 16, 16, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA2, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 2, 2, 2, 2, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA32F, InternalFormatData(OpenGL::FormatDataType::SFloat, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA32I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA32UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 32, 32, 32, 32, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA4, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 4, 4, 4, 4, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8_SNorm, InternalFormatData(OpenGL::FormatDataType::SNorm, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8I, InternalFormatData(OpenGL::FormatDataType::SInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::RGBA8UI, InternalFormatData(OpenGL::FormatDataType::UInt, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::SRGB8, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 8, 8, 8, 0, 0, 0, 0, false, false, true)}, {OpenGL::InternalFormat::SRGB8_Alpha8, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 8, 8, 8, 8, 0, 0, 0, false, false, true)}, /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::Depth_Component16, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 16, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth_Component24, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 24, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth_Component32, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth_Component32_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 1, 0, 0, 0, 0, 32, 0, 0, false, false, true) }, {OpenGL::InternalFormat::Depth24_Stencil8, InternalFormatData(OpenGL::FormatDataType::UNorm_UInt, 2, 0, 0, 0, 0, 24, 8, 0, false, false, true) }, {OpenGL::InternalFormat::Depth32_Float_Stencil8, InternalFormatData(OpenGL::FormatDataType::UFloat_UInt, 2, 0, 0, 0, 0, 32, 8, 0, false, false, true) }, /* Compressed internal formats */ /* Format | data_type | n_components | r size | g size | b size | a size | d size | s size | shared size | is base? | is compressed? | is sized? */ {OpenGL::InternalFormat::Compressed_Red, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::UNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RG, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::UNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGB, InternalFormatData(OpenGL::FormatDataType::UNorm, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGB_BPTC_Signed_Float, InternalFormatData(OpenGL::FormatDataType::SFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGB_BPTC_Unsigned_Float, InternalFormatData(OpenGL::FormatDataType::UFloat, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGBA, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_RGBA_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::UNorm, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_Signed_Red_RGTC1, InternalFormatData(OpenGL::FormatDataType::SNorm, 1, 1, 0, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_Signed_RG_RGTC2, InternalFormatData(OpenGL::FormatDataType::SNorm, 2, 1, 1, 0, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_SRGB, InternalFormatData(OpenGL::FormatDataType::SRGB, 3, 1, 1, 1, 0, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_SRGB_Alpha, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, {OpenGL::InternalFormat::Compressed_SRGB_Alpha_BPTC_UNorm, InternalFormatData(OpenGL::FormatDataType::SRGB, 4, 1, 1, 1, 1, 0, 0, 0, false, true, false)}, }; static const std::vector<OpenGL::InternalFormat> g_color_sized_internalformats = { OpenGL::InternalFormat::R11F_G11F_B10F, OpenGL::InternalFormat::R16, OpenGL::InternalFormat::R16_SNorm, OpenGL::InternalFormat::R16F, OpenGL::InternalFormat::R16I, OpenGL::InternalFormat::R16UI, OpenGL::InternalFormat::R3_G3_B2, OpenGL::InternalFormat::R32F, OpenGL::InternalFormat::R32I, OpenGL::InternalFormat::R32UI, OpenGL::InternalFormat::R8, OpenGL::InternalFormat::R8_SNorm, OpenGL::InternalFormat::R8I, OpenGL::InternalFormat::R8UI, OpenGL::InternalFormat::RG16, OpenGL::InternalFormat::RG16_SNorm, OpenGL::InternalFormat::RG16F, OpenGL::InternalFormat::RG16I, OpenGL::InternalFormat::RG16UI, OpenGL::InternalFormat::RG32F, OpenGL::InternalFormat::RG32I, OpenGL::InternalFormat::RG32UI, OpenGL::InternalFormat::RG8, OpenGL::InternalFormat::RG8_SNorm, OpenGL::InternalFormat::RG8I, OpenGL::InternalFormat::RG8UI, OpenGL::InternalFormat::RGB10, OpenGL::InternalFormat::RGB10_A2, OpenGL::InternalFormat::RGB10_A2UI, OpenGL::InternalFormat::RGB12, OpenGL::InternalFormat::RGB16_SNorm, OpenGL::InternalFormat::RGB16F, OpenGL::InternalFormat::RGB16I, OpenGL::InternalFormat::RGB16UI, OpenGL::InternalFormat::RGB32F, OpenGL::InternalFormat::RGB32I, OpenGL::InternalFormat::RGB32UI, OpenGL::InternalFormat::RGB4, OpenGL::InternalFormat::RGB5, OpenGL::InternalFormat::RGB5_A1, OpenGL::InternalFormat::RGB8, OpenGL::InternalFormat::RGB8_SNorm, OpenGL::InternalFormat::RGB8I, OpenGL::InternalFormat::RGB8UI, OpenGL::InternalFormat::RGB9_E5, OpenGL::InternalFormat::RGBA12, OpenGL::InternalFormat::RGBA16, OpenGL::InternalFormat::RGBA16F, OpenGL::InternalFormat::RGBA16I, OpenGL::InternalFormat::RGBA16UI, OpenGL::InternalFormat::RGBA2, OpenGL::InternalFormat::RGBA32F, OpenGL::InternalFormat::RGBA32I, OpenGL::InternalFormat::RGBA32UI, OpenGL::InternalFormat::RGBA4, OpenGL::InternalFormat::RGBA8, OpenGL::InternalFormat::RGBA8_SNorm, OpenGL::InternalFormat::RGBA8I, OpenGL::InternalFormat::RGBA8UI, OpenGL::InternalFormat::SRGB8, OpenGL::InternalFormat::SRGB8_Alpha8, }; static const std::vector<OpenGL::InternalFormat> g_ds_sized_internalformats = { OpenGL::InternalFormat::Depth_Component16, OpenGL::InternalFormat::Depth_Component24, OpenGL::InternalFormat::Depth_Component32, OpenGL::InternalFormat::Depth_Component32_Float, OpenGL::InternalFormat::Depth24_Stencil8, OpenGL::InternalFormat::Depth32_Float_Stencil8, }; OpenGL::InternalFormat OpenGL::GLFormats::get_best_fit_ds_internal_format(const uint32_t& in_depth_bits, const uint32_t& in_stencil_bits) { OpenGL::InternalFormat result = OpenGL::InternalFormat::Unknown; uint32_t result_n_depth_bits = 0; uint32_t result_n_stencil_bits = 0; vkgl_assert(in_depth_bits != 0 || in_stencil_bits != 0); for (const auto& current_internalformat : g_ds_sized_internalformats) { const auto& internalformat_data_iterator = g_gl_internalformat_data.find(current_internalformat); vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); const auto& internalformat_data = internalformat_data_iterator->second; if ((in_depth_bits == 0 && internalformat_data.component_size_depth != 0) || (in_stencil_bits == 0 && internalformat_data.component_size_stencil != 0) ) { continue; } if ((in_depth_bits != 0 && internalformat_data.component_size_depth == 0) || (in_stencil_bits != 0 && internalformat_data.component_size_stencil == 0) ) { continue; } if (result == OpenGL::InternalFormat::Unknown) { result = current_internalformat; result_n_depth_bits = internalformat_data.component_size_depth; result_n_stencil_bits = internalformat_data.component_size_stencil; } else { const auto current_depth_diff = abs(static_cast<int32_t>(internalformat_data.component_size_depth) - static_cast<int32_t>(in_depth_bits) ); const auto current_stencil_diff = abs(static_cast<int32_t>(internalformat_data.component_size_stencil) - static_cast<int32_t>(in_stencil_bits) ); const auto result_depth_diff = abs(static_cast<int32_t>(result_n_depth_bits) - static_cast<int32_t>(in_depth_bits) ); const auto result_stencil_diff = abs(static_cast<int32_t>(result_n_stencil_bits) - static_cast<int32_t>(in_stencil_bits) ); if (current_depth_diff + current_stencil_diff < result_depth_diff + result_stencil_diff) { result = current_internalformat; result_n_depth_bits = internalformat_data.component_size_depth; result_n_stencil_bits = internalformat_data.component_size_stencil; } } } vkgl_assert(result != OpenGL::InternalFormat::Unknown); return result; } OpenGL::FormatDataType OpenGL::GLFormats::get_format_data_type_for_non_base_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); OpenGL::FormatDataType result = OpenGL::FormatDataType::Unknown; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.data_type; } return result; } uint32_t OpenGL::GLFormats::get_n_components_for_sized_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); uint32_t result = 0; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.n_components; } return result; } bool OpenGL::GLFormats::get_per_component_bit_size_for_sized_internal_format(const OpenGL::InternalFormat& in_format, uint32_t* out_rgba_bit_size_ptr, uint32_t* out_ds_size_ptr, uint32_t* out_shared_size_ptr) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { out_rgba_bit_size_ptr[0] = internalformat_data_iterator->second.component_size_r; out_rgba_bit_size_ptr[1] = internalformat_data_iterator->second.component_size_g; out_rgba_bit_size_ptr[2] = internalformat_data_iterator->second.component_size_b; out_rgba_bit_size_ptr[3] = internalformat_data_iterator->second.component_size_a; out_ds_size_ptr [0] = internalformat_data_iterator->second.component_size_depth; out_ds_size_ptr [1] = internalformat_data_iterator->second.component_size_stencil; *out_shared_size_ptr = internalformat_data_iterator->second.component_size_shared; result = true; } return result; } bool OpenGL::GLFormats::is_base_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.is_base_internal_format; } return result; } bool OpenGL::GLFormats::is_compressed_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.is_compressed_internal_format; } return result; } bool OpenGL::GLFormats::is_sized_internal_format(const OpenGL::InternalFormat& in_format) { const auto internalformat_data_iterator = g_gl_internalformat_data.find(in_format); bool result = false; vkgl_assert(internalformat_data_iterator != g_gl_internalformat_data.end() ); if (internalformat_data_iterator != g_gl_internalformat_data.end() ) { result = internalformat_data_iterator->second.is_sized_internal_format; } return result; }
83.170918
240
0.52121
kbiElude
92b5fdc2de86dc8bea366b6becd7a3a38690d844
175
cpp
C++
ChronicleLogger/src/main/com/sowrov/util/thread/ThreadLocker.cpp
sowrov/ChronicleLogger
50678be7e2987211ab976d105fcd8549e5b8744b
[ "Apache-2.0" ]
1
2020-03-05T10:36:48.000Z
2020-03-05T10:36:48.000Z
ChronicleLogger/src/main/com/sowrov/util/thread/ThreadLocker.cpp
sowrov/ChronicleLogger
50678be7e2987211ab976d105fcd8549e5b8744b
[ "Apache-2.0" ]
null
null
null
ChronicleLogger/src/main/com/sowrov/util/thread/ThreadLocker.cpp
sowrov/ChronicleLogger
50678be7e2987211ab976d105fcd8549e5b8744b
[ "Apache-2.0" ]
null
null
null
#include "ThreadLocker.h" #ifdef _P_THREAD pthread_mutex_t Global_Mutex_Lock = PTHREAD_MUTEX_INITIALIZER; #elif defined(_BOOST_THREAD) boost::mutex Global_Mutex_Lock; #endif
21.875
62
0.84
sowrov
92b8092a9f85b860b199b56c2b1e305758fa1b0e
1,812
cpp
C++
src/NavRouting/SdkModel/NavRoutingRouteModel.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
69
2017-06-07T10:47:03.000Z
2022-03-24T08:33:33.000Z
src/NavRouting/SdkModel/NavRoutingRouteModel.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
23
2017-06-07T10:47:00.000Z
2020-07-09T10:31:17.000Z
src/NavRouting/SdkModel/NavRoutingRouteModel.cpp
usamakhan049/assignment
40eb153e8fd74f73ba52ce29417d8220ab744b5d
[ "BSD-2-Clause" ]
31
2017-08-12T13:19:32.000Z
2022-01-04T20:33:40.000Z
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "NavRoutingRouteModel.h" namespace ExampleApp { namespace NavRouting { namespace SdkModel { NavRoutingRouteModel::NavRoutingRouteModel() : m_duration(0) , m_distance(0) { } NavRoutingRouteModel::NavRoutingRouteModel(const double duration, const double distance, const std::vector<NavRoutingDirectionModel>& directions, const Eegeo::Routes::Webservice::RouteData& sourceRouteData) : m_duration(duration) , m_distance(distance) , m_directions(directions) , m_sourceRoute(sourceRouteData) { } const double NavRoutingRouteModel::GetDuration() const { return m_duration; } const double NavRoutingRouteModel::GetDistance() const { return m_distance; } const std::vector<NavRoutingDirectionModel>& NavRoutingRouteModel::GetDirections() const { return m_directions; } const Eegeo::Routes::Webservice::RouteData& NavRoutingRouteModel::GetSourceRouteData() const { return m_sourceRoute; } void NavRoutingRouteModel::UpdateDirection(int index, const NavRoutingDirectionModel& directionModel) { if (index >= 0 && index < m_directions.size()) { m_directions[index] = directionModel; } } } } }
30.2
115
0.505519
usamakhan049
92b83bce1d4838000a01a8ef9ab4735c2ff19055
5,525
hpp
C++
src/libraries/core/db/functionObjects/functionObjectList/functionObjectList.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/db/functionObjects/functionObjectList/functionObjectList.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/core/db/functionObjects/functionObjectList/functionObjectList.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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 3 of the License, or (at your option) any later version. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::functionObjectList Description List of function objects with start(), execute() and end() functions that is called for each object. See Also CML::functionObject and CML::OutputFilterFunctionObject SourceFiles functionObjectList.cpp \*---------------------------------------------------------------------------*/ #ifndef functionObjectList_H #define functionObjectList_H #include "PtrList.hpp" #include "functionObject.hpp" #include "SHA1Digest.hpp" #include "HashTable.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class functionObjectList Declaration \*---------------------------------------------------------------------------*/ class functionObjectList : private PtrList<functionObject> { // Private data //- A list of SHA1 digests for the function object dictionaries List<SHA1Digest> digests_; //- Quick lookup of the index into functions/digests HashTable<label> indices_; const Time& time_; //- The parent dictionary containing a "functions" entry // This entry can either be a list or a dictionary of // functionObject specifications. const dictionary& parentDict_; //- Switch for the execution of the functionObjects bool execution_; //- Tracks if read() was called while execution is on bool updated_; // Private Member Functions //- Remove and return the function object pointer by name, // and returns the old index via the parameter. // Returns a nullptr pointer (and index -1) if it didn't exist. functionObject* remove(const word&, label& oldIndex); //- Disallow default bitwise copy construct functionObjectList(const functionObjectList&); //- Disallow default bitwise assignment void operator=(const functionObjectList&); public: // Constructors //- Construct from Time and the execution setting // The functionObject specifications are read from the controlDict functionObjectList ( const Time&, const bool execution=true ); //- Construct from Time, a dictionary with "functions" entry // and the execution setting. // \param[in] parentDict - the parent dictionary containing // a "functions" entry, which can either be a list or a dictionary // of functionObject specifications. functionObjectList ( const Time&, const dictionary& parentDict, const bool execution=true ); //- Destructor virtual ~functionObjectList(); // Member Functions //- Return the number of elements in the List. using PtrList<functionObject>::size; //- Return true if the List is empty (ie, size() is zero). using PtrList<functionObject>::empty; //- Access to the functionObjects using PtrList<functionObject>::operator[]; //- Clear the list of function objects virtual void clear(); //- Find the ID of a given function object by name virtual label findObjectID(const word& name) const; //- Switch the function objects on virtual void on(); //- Switch the function objects off virtual void off(); //- Return the execution status (on/off) of the function objects virtual bool status() const; //- Called at the start of the time-loop virtual bool start(); //- Called at each ++ or += of the time-loop. forceWrite overrides // the usual outputControl behaviour and forces writing always // (used in postprocessing mode) virtual bool execute(const bool forceWrite = false); //- Called when Time::run() determines that the time-loop exits virtual bool end(); //- Called when time was set at the end of the Time::operator++ virtual bool timeSet(); //- Called at the end of Time::adjustDeltaT() if adjustTime is true virtual bool adjustTimeStep(); //- Read and set the function objects if their data have changed virtual bool read(); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
30.524862
79
0.568326
MrAwesomeRocks
92bd45d18ef918903db08b75c6e57deeeace48f6
2,913
cc
C++
test/soa/benchmarks/codegen_test.cc
prg-titech/ikra-cpp
5b9dc816fe5c63ad1aa7464d3ce9ca612927423d
[ "MIT" ]
20
2017-12-25T16:38:51.000Z
2022-02-28T10:41:39.000Z
test/soa/benchmarks/codegen_test.cc
prg-titech/ikra-cpp
5b9dc816fe5c63ad1aa7464d3ce9ca612927423d
[ "MIT" ]
1
2017-11-25T06:08:35.000Z
2017-11-25T06:08:35.000Z
test/soa/benchmarks/codegen_test.cc
prg-titech/ikra-cpp
5b9dc816fe5c63ad1aa7464d3ce9ca612927423d
[ "MIT" ]
null
null
null
// This is a minimal test case whose purpose is to check if the compiler // generates efficient assembly code. Should be built with -O3 optimization // and not through Bazel (is not set up to generate such optimized code). #include <stdio.h> #define NDEBUG // No asserts. #include "soa/soa.h" #include "soa/storage.h" using ikra::soa::SoaLayout; using ikra::soa::kAddressModeZero; using ikra::soa::DynamicStorage; using ikra::soa::StaticStorage; using ikra::soa::kLayoutModeAos; using ikra::soa::kLayoutModeSoa; // Compiler flags determine addressing mode and storage strategy. #ifndef ADDRESS_MODE #error Address mode undefined #endif #ifndef STORAGE_STRATEGY #error Storage strategy undefined #endif #ifndef LAYOUT_MODE #error Layout mode undefined #endif static const uint32_t kClassMaxInst = 0x1234; class TestClass : public SoaLayout<TestClass, kClassMaxInst, ADDRESS_MODE, STORAGE_STRATEGY, PP_CONCAT(kLayoutMode, LAYOUT_MODE)> { public: IKRA_INITIALIZE_CLASS int_ field0; int_ field1; void increase_field0() { field0 *= 0x5555; } void increase_field1() { field1 *= 0x4444; } }; IKRA_HOST_STORAGE(TestClass); class TestClassCompare { public: int field0; int field1; void increase_field0() { field0 *= 0x5555; } void increase_field1() { field1 *= 0x4444; } }; TestClassCompare test_compare_array[kClassMaxInst]; int main() { TestClass::initialize_storage(); TestClass* instance = new TestClass(); instance->field0 = 0x7777; instance->field1 = 0x8888; instance->increase_field0(); instance->increase_field1(); // Expected output: FIELD0: 668085635, FIELD1: 610821152 printf("FIELD0: %i, FIELD1: %i\n", (int) instance->field0, (int) instance->field1); // Return 0 if correct result. return !(instance->field0 == 668085635 && instance->field1 == 610821152); } // Extra methods for code isolation: Will show up in .S file. TestClass* new_instance() { return new TestClass(); } void write_field0(TestClass* instance) { instance->field0 = 0x7777; } int read_field0(TestClass* instance) { return instance->field0; } void write_field1(TestClass* instance) { instance->field1 = 0x7777; } int read_field1(TestClass* instance) { return instance->field1; } // Compare with explicit, hand-written SOA code. int explicit_field0[100]; void explicit_write_field0(uintptr_t id) { explicit_field0[id] = 0x7777; } int explicit_read_field0(uintptr_t id) { return explicit_field0[id]; } void explicit_write_field0_aos(TestClassCompare* obj) { obj->field0 = 0x7777; } int explicit_read_field0_aos(TestClassCompare* obj) { return obj->field0; } void explicit_write_field1_aos(TestClassCompare* obj) { obj->field1 = 0x7777; } int explicit_read_field1_aos(TestClassCompare* obj) { return obj->field1; }
21.577778
75
0.709578
prg-titech
92bee56ecc80bf9553166f15e34a53e576ba9213
3,371
cpp
C++
src/baxter_collaboration/baxter_collaboration_lib/src/robot_interface/gripper.cpp
UCRoboticsLab/BaxterTictactoe
34e4761467af3dc7c9ad65726360e0d1f1923c51
[ "Apache-2.0" ]
1
2017-12-22T20:32:04.000Z
2017-12-22T20:32:04.000Z
src/baxter_collaboration/baxter_collaboration_lib/src/robot_interface/gripper.cpp
u3099811/BaxterTictacToe
967ab0ea8496ca4ce54db41b20c05de68cfe1bb9
[ "Apache-2.0" ]
2
2017-08-16T00:18:52.000Z
2017-08-16T04:30:05.000Z
src/baxter_collaboration/baxter_collaboration_lib/src/robot_interface/gripper.cpp
u3099811/BaxterTictacToe
967ab0ea8496ca4ce54db41b20c05de68cfe1bb9
[ "Apache-2.0" ]
null
null
null
#include "robot_interface/gripper.h" #include <iostream> using namespace baxter_core_msgs; using namespace std; Gripper::Gripper(std::string limb, bool no_robot) : _limb(limb), _no_robot(no_robot), _first_run(true) { if (no_robot) return; _pub_command = _nh.advertise<EndEffectorCommand>( "/robot/end_effector/" + _limb + "_gripper/command", 1); _sub_state = _nh.subscribe("/robot/end_effector/" + _limb + "_gripper/state", SUBSCRIBER_BUFFER, &Gripper::gripperCb, this); //Initially all the interesting properties of the state are unknown EndEffectorState initial_gripper_state; initial_gripper_state.calibrated= \ initial_gripper_state.enabled= \ initial_gripper_state.error= \ initial_gripper_state.gripping= \ initial_gripper_state.missed= \ initial_gripper_state.ready= \ initial_gripper_state.moving=EndEffectorState::STATE_UNKNOWN; _state = initial_gripper_state; pthread_mutex_init(&_mutex, NULL); } bool Gripper::gripObject() { suck(); // int cnt = 0; // while (!_gripper->is_sucking()) // { // ROS_WARN("Requested a suck to the gripper, but the gripper is not sucking."); // ++cnt; // if (cnt == 10) return false; // pause(); // ros::spinOnce(); // } return true; } bool Gripper::releaseObject() { if (is_sucking()) { blow(); return true; } ROS_WARN("[%s_gripper] Requested a release of the gripper, but the gripper is not sucking.", getGripperLimb().c_str()); return false; } void Gripper::gripperCb(const EndEffectorState &msg) { pthread_mutex_lock(&_mutex); _state = msg; pthread_mutex_unlock(&_mutex); if (_first_run) { if (!is_calibrated()) { ROS_INFO("[%s_gripper] Calibrating the gripper..", getGripperLimb().c_str()); calibrate(); } _first_run=false; } } void Gripper::calibrate() { EndEffectorCommand sucking_command; sucking_command.id=get_id(); sucking_command.command=EndEffectorCommand::CMD_CALIBRATE; _pub_command.publish(sucking_command); } void Gripper::suck() { EndEffectorCommand sucking_command; sucking_command.id=get_id(); sucking_command.command=EndEffectorCommand::CMD_GRIP; if (_limb == "left") { sucking_command.args="{\"grip_attempt_seconds\": 5.0}"; } _pub_command.publish(sucking_command); } void Gripper::blow() { EndEffectorCommand release_command; release_command.id=get_id(); release_command.command=EndEffectorCommand::CMD_RELEASE; _pub_command.publish(release_command); } int Gripper::get_id() { return _state.id; } bool Gripper::is_enabled() { return _state.enabled==EndEffectorState::STATE_TRUE; } bool Gripper::is_calibrated() { return _state.calibrated==EndEffectorState::STATE_TRUE; } bool Gripper::is_ready_to_grip() { return _state.ready==EndEffectorState::STATE_TRUE; } bool Gripper::has_error() { return _state.error==EndEffectorState::STATE_TRUE; } bool Gripper::is_sucking() { // ROS_INFO("force is: %g\n",_state.force); return _state.position<80; } bool Gripper::is_gripping() { return true; return _state.gripping==EndEffectorState::STATE_TRUE; }
22.931973
123
0.661228
UCRoboticsLab
92bf7d31bc4c58b0562703293346ffdce4311edb
8,873
cpp
C++
src/output_wasapi.cpp
Energy0124/freepiano
7ddaaff5a0712b811f24b7bc42f07abeefcb659c
[ "BSD-3-Clause" ]
54
2018-08-09T16:16:13.000Z
2022-03-29T08:50:26.000Z
src/output_wasapi.cpp
luotuo/freepiano
7ddaaff5a0712b811f24b7bc42f07abeefcb659c
[ "BSD-3-Clause" ]
null
null
null
src/output_wasapi.cpp
luotuo/freepiano
7ddaaff5a0712b811f24b7bc42f07abeefcb659c
[ "BSD-3-Clause" ]
16
2018-08-09T16:16:15.000Z
2022-03-20T09:47:51.000Z
#include "pch.h" #include <mmreg.h> #include <mmsystem.h> #include <mmdeviceapi.h> #include <audioclient.h> #include <mbctype.h> #include "output_wasapi.h" #include "synthesizer_vst.h" #include "display.h" #include "song.h" #include "config.h" #include "export.h" // pkey static const PROPERTYKEY PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0 } }, 14 }; // global wasapi client static IAudioClient *client = NULL; // global renderer client static IAudioRenderClient *render_client = NULL; // playing event and thread static HANDLE wasapi_thread = NULL; // format static WAVEFORMATEX *pwfx = NULL; // output buffer size static double buffer_time = 0.01; // class id and interface id static const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator); static const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator); static const IID IID_IAudioClient = __uuidof(IAudioClient); static const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient); // write buffer static void write_buffer(float *dst, float *left, float *right, int size) { float volume = config_get_output_volume() / 100.f; while (size--) { dst[0] = *left * volume; dst[1] = *right * volume; left++; right++; dst += 2; } } // playing thread static DWORD __stdcall wasapi_play_thread(void *param) { HRESULT hr; uint bufferFrameCount; BYTE *data; // Get the actual size of the allocated buffer. if (FAILED(hr = client->GetBufferSize(&bufferFrameCount))) return 0; // timer resolustion timeBeginPeriod(1); // temp buffer for vsti process float output_buffer[2][4096]; // start playing hr = client->Start(); while (wasapi_thread) { uint numFramesPadding; // See how much buffer space is available. if (SUCCEEDED(hr = client->GetCurrentPadding(&numFramesPadding))) { uint buffer_size = pwfx->nSamplesPerSec * buffer_time; if (numFramesPadding <= buffer_size) { uint numFramesAvailable = bufferFrameCount - numFramesPadding; uint numFramesProcess = 32; // write data at least 32 samles if (numFramesAvailable >= numFramesProcess) { //printf("write %d\n", numFramesAvailable); if (export_rendering()) { memset(output_buffer[0], 0, numFramesProcess * sizeof(float)); memset(output_buffer[1], 0, numFramesProcess * sizeof(float)); } else { // update song song_update(1000.0 * (double)32 / (double)pwfx->nSamplesPerSec); // update effect vsti_update_config((float)pwfx->nSamplesPerSec, 32); // call vsti process func vsti_process(output_buffer[0], output_buffer[1], numFramesProcess); } // Grab the entire buffer for the initial fill operation. if (SUCCEEDED(hr = render_client->GetBuffer(numFramesAvailable, &data))) { // write buffer write_buffer((float *)data, output_buffer[0], output_buffer[1], numFramesProcess); // release buffer render_client->ReleaseBuffer(numFramesProcess, 0); // continue processing continue; } } } } Sleep(1); } // stop playing client->Stop(); // stop vsti process vsti_stop_process(); return 0; } // open wasapi. int wasapi_open(const char *name) { HRESULT hr; IMMDeviceEnumerator *enumerator = NULL; IMMDevice *device = NULL; REFERENCE_TIME hnsRequestedDuration = 1000000; // close wasapi device wasapi_close(); // create enumerator if (FAILED(hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void * *)&enumerator))) goto error; if (name && name[0]) { struct enum_callback : public wasapi_enum_callback { void operator () (const char *name, void *device) { if (_stricmp(name, devname) == 0) { result = (IMMDevice *)device; result->AddRef(); } } const char *devname; IMMDevice *result; } callback; callback.devname = name; callback.result = 0; wasapi_enum_device(callback); device = callback.result; } else { // make a default name name = "Default"; // get default device if (FAILED(hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device))) { fprintf(stderr, "WASAPI: Failed to get default endpoint. name=%s, hr=%x\n", name, hr); goto error; } } // no device if (device == NULL) { hr = E_FAIL; goto error; } // activate if (FAILED(hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&client))) { fprintf(stderr, "WASAPI: Failed to active audio client. name=%s, hr=%x\n", name, hr); goto error; } // get mix format if (FAILED(hr = client->GetMixFormat(&pwfx))) { fprintf(stderr, "WASAPI: Failed to get mix format. name=%s, hr=%x\n", name, hr); goto error; } bool supported = false; if (pwfx->wFormatTag == WAVE_FORMAT_EXTENSIBLE) { WAVEFORMATEXTENSIBLE* format = (WAVEFORMATEXTENSIBLE*)pwfx; if (format->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {\ if (pwfx->wBitsPerSample == 32) { supported = true; } } fprintf(stdout, "WASAPI: name=%s, format={%x, %x, %x, %x}, bits=%d, samplerate=%d\n", name, format->SubFormat.Data1, format->SubFormat.Data2, format->SubFormat.Data3, format->SubFormat.Data4, pwfx->wBitsPerSample, pwfx->nSamplesPerSec); } if (!supported) { fprintf(stderr, "WASAPI: current mix format is not supported. name=%s\n", name); goto error; } // initialize if (FAILED(hr = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, hnsRequestedDuration, 0, pwfx, NULL))) { fprintf(stderr, "WASAPI: Failed to initialize audio client. name=%s, hr=%x\n", name, hr); goto error; } // get render client if (FAILED(hr = client->GetService(IID_IAudioRenderClient, (void **)&render_client))) { fprintf(stderr, "WASAPI: Failed to get render client. name=%s, hr=%x\n", name, hr); goto error; } // create input thread wasapi_thread = CreateThread(NULL, 0, &wasapi_play_thread, NULL, NULL, NULL); // change thread priority to highest SetThreadPriority(wasapi_thread, THREAD_PRIORITY_TIME_CRITICAL); SAFE_RELEASE(device); SAFE_RELEASE(enumerator); return 0; error: SAFE_RELEASE(device); SAFE_RELEASE(enumerator); wasapi_close(); return hr; } // close wasapi device void wasapi_close() { // wait input thread exit if (wasapi_thread) { HANDLE thread = wasapi_thread; wasapi_thread = NULL; WaitForSingleObject(thread, -1); CloseHandle(thread); } if (pwfx) { CoTaskMemFree(pwfx); pwfx = NULL; } SAFE_RELEASE(render_client); SAFE_RELEASE(client); } // set buffer size void wasapi_set_buffer_time(double time) { if (time > 0) { buffer_time = time * 0.001; } } // get output samplerate uint wasapi_get_samplerate() { if (pwfx) { return pwfx->nSamplesPerSec; } return 44100; } // enum device void wasapi_enum_device(wasapi_enum_callback &callback) { HRESULT hr; IMMDeviceEnumerator *enumerator = NULL; IMMDeviceCollection *devices = NULL; IPropertyStore *props = NULL; // create enumerator if (FAILED(hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void * *)&enumerator))) goto error; if (FAILED(hr = enumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices))) goto error; uint device_count = 0; if (SUCCEEDED(devices->GetCount(&device_count))) { for (uint i = 0; i < device_count; i++) { IMMDevice *device = NULL; if (SUCCEEDED(devices->Item(i, &device))) { if (SUCCEEDED(device->OpenPropertyStore(STGM_READ, &props))) { PROPVARIANT varName; // Initialize container for property value. PropVariantInit(&varName); // Get the endpoint's friendly-name property. if (SUCCEEDED(props->GetValue(PKEY_Device_FriendlyName, &varName))) { char buff[256]; WideCharToMultiByte(_getmbcp(), 0, varName.pwszVal, -1, buff, sizeof(buff), NULL, NULL); callback(buff, (void *)device); } PropVariantClear(&varName); } } SAFE_RELEASE(device); } } error: SAFE_RELEASE(props); SAFE_RELEASE(devices); SAFE_RELEASE(enumerator); }
27.902516
150
0.627409
Energy0124
92c1746c8d3a8d16fb209eedc62b2e190decd3cf
1,142
cpp
C++
src/Utils/mpcdiUtils.cpp
scaredyfish/MPCDI
1ddbc9abf99d39d4464afa2005934c325443cf28
[ "BSD-3-Clause" ]
3
2021-03-09T01:57:37.000Z
2021-05-07T08:40:41.000Z
src/Utils/mpcdiUtils.cpp
scaredyfish/MPCDI
1ddbc9abf99d39d4464afa2005934c325443cf28
[ "BSD-3-Clause" ]
1
2021-06-01T07:52:36.000Z
2021-06-03T00:54:49.000Z
src/Utils/mpcdiUtils.cpp
scaredyfish/MPCDI
1ddbc9abf99d39d4464afa2005934c325443cf28
[ "BSD-3-Clause" ]
4
2020-06-22T14:14:15.000Z
2021-11-11T14:34:42.000Z
/* ========================================================================= Program: MPCDI Library Language: C++ Date: $Date: 2012-08-22 20:19:58 -0400 (Wed, 22 Aug 2012) $ Version: $Revision: 19513 $ Copyright (c) 2013 Scalable Display Technologies, Inc. All Rights Reserved. The MPCDI Library is distributed under the BSD license. Please see License.txt distributed with this package. ===================================================================auto== */ #include "mpcdiUtils.h" using namespace mpcdi; std::string Utils::ProfileVersionToString(const ProfileVersion& pv) { std::stringstream ss; ss << pv.MajorVersion << "." << pv.MinorVersion; return ss.str(); } MPCDI_Error Utils::StringToProfileVersion(const std::string &text, ProfileVersion& pv) { pv = ProfileVersion(); size_t pos = text.find_first_of("."); if (pos==std::string::npos) return MPCDI_FAILURE; pv.MajorVersion = StringToNumber<int>(text.substr(0,pos)); pv.MinorVersion = 0; if (text.size() >= pos+1) pv.MinorVersion = StringToNumber<int>(text.substr(pos+1,text.length())); return MPCDI_SUCCESS; }
27.853659
86
0.60683
scaredyfish
92c2194c831fa6102456e80f868b6c6f385ccb51
1,508
cpp
C++
ex03/main.cpp
Gundul42/CPP_mod03
822c83ebca93e9a519bc8629c58ac39ef02365d6
[ "MIT" ]
null
null
null
ex03/main.cpp
Gundul42/CPP_mod03
822c83ebca93e9a519bc8629c58ac39ef02365d6
[ "MIT" ]
null
null
null
ex03/main.cpp
Gundul42/CPP_mod03
822c83ebca93e9a519bc8629c58ac39ef02365d6
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: graja <graja@student.42wolfsburg.de> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/02/12 14:02:52 by graja #+# #+# */ /* Updated: 2022/02/17 10:05:47 by graja ### ########.fr */ /* */ /* ************************************************************************** */ #include "DiamondTrap.hpp" int main(void) { DiamondTrap test; DiamondTrap lala("LaLa"); DiamondTrap kuemmel(test); //attack method overloaded by ScavTrap lala.attack("LOLO"); test.attack("TestTrapper"); //methods from ClapTrap lala.beRepaired(20); kuemmel.takeDamage(10); //method ScavTrap test.guardGate(); //method FragTrap test.highFivesGuys(); //method DiamondTrap test.whoAmI(); lala.whoAmI(); //operator overload for = test = lala; //check if it works test.whoAmI(); std::cout << "--------------------------------------------"; std::cout << std::endl << std::endl; return (0); }
31.416667
80
0.322944
Gundul42
92c35370d69641889736865a3d06ccea318d9824
8,562
inl
C++
src/core/containers/internal/hash_map.inl
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
4
2017-10-04T11:38:48.000Z
2021-11-16T20:35:37.000Z
src/core/containers/internal/hash_map.inl
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
4
2018-06-07T23:27:02.000Z
2018-10-18T12:19:57.000Z
src/core/containers/internal/hash_map.inl
JakubLukas/NewEngine
38ea585a37347ec0630673b9d4a7f948e4dc1477
[ "MIT" ]
null
null
null
namespace Veng { template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(const KeyType& key, const ValueType& value) : key(key) , value(value) , next(INVALID_INDEX) {} template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(const KeyType& key, const ValueType& value, int next) : key(key) , value(value) , next(next) {} template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashNode::HashNode(HashNode&& other) : key(other.key) , value(other.value) , next(other.next) { other.next = INVALID_INDEX; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode& HashMap<KeyType, ValueType, Hasher>::HashNode::operator=(typename HashMap<KeyType, ValueType, Hasher>::HashNode&& other) { KeyType k = key; ValueType v = value; key = other.key; value = other.value; next = other.next; other.key = k; other.value = v; other.next = INVALID_INDEX; return *this; } template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashMap(Allocator& allocator) : m_allocator(allocator) {} template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::HashMap(HashMap<KeyType, ValueType, Hasher>&& other) : m_allocator(other.m_allocator) , m_buckets(other.m_buckets) , m_bucketSize(other.m_bucketSize) , m_table(other.m_table) , m_size(other.m_size) { other.m_buckets = nullptr; other.m_bucketSize = 0; other.m_table = nullptr; other.m_size = 0; } template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>& HashMap<KeyType, ValueType, Hasher>::operator=(HashMap<KeyType, ValueType, Hasher>&& other) { int* buckets = m_buckets; unsigned bucketSize = m_bucketSize; HashNode* table = m_table; unsigned size = m_size; m_allocator = other.m_allocator; m_buckets = other.m_buckets; m_bucketSize = other.m_bucketSize; m_table = other.m_table; m_size = other.m_size; other.m_buckets = buckets; other.m_bucketSize = bucketSize; other.m_table = table; other.m_size = size; return *this; } template<class KeyType, class ValueType, class Hasher> HashMap<KeyType, ValueType, Hasher>::~HashMap() { for (unsigned i = 0; i < m_size; ++i) { DELETE_PLACEMENT(m_table + i); } if (m_buckets != nullptr) m_allocator.Deallocate(m_buckets); } template<class KeyType, class ValueType, class Hasher> void HashMap<KeyType, ValueType, Hasher>::Clear() { for (unsigned i = 0; i < m_bucketSize; ++i) { m_buckets[i] = INVALID_INDEX; } for (unsigned i = 0; i < m_size; ++i) { DELETE_PLACEMENT(m_table + i); } m_size = 0; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::Begin() { return m_table; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::End() { return m_table + m_size; } template<class KeyType, class ValueType, class Hasher> typename const HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::Begin() const { return m_table; } template<class KeyType, class ValueType, class Hasher> typename const HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::End() const { return m_table + m_size; } template<class KeyType, class ValueType, class Hasher> bool HashMap<KeyType, ValueType, Hasher>::Find(const KeyType& key, ValueType*& value) const { if (m_size == 0) return false; unsigned bucketIdx = GetIndex(key); if (m_buckets[bucketIdx] == INVALID_INDEX) return false; HashNode* node = &m_table[m_buckets[bucketIdx]]; while (node->next != INVALID_INDEX && node->key != key) { node = &m_table[node->next]; } if (node->key == key) { value = &node->value; return true; } else { return false; } } template<class KeyType, class ValueType, class Hasher> ValueType* HashMap<KeyType, ValueType, Hasher>::Insert(const KeyType& key, const ValueType& value) { if (m_bucketSize == 0) Rehash(INITIAL_SIZE); if ((m_size / (float)m_bucketSize) * 100 > MAX_FACTOR) Rehash(m_bucketSize * ENLARGE_MULTIPLIER); unsigned bucketIdx = GetIndex(key); return Insert(bucketIdx, key, value); } template<class KeyType, class ValueType, class Hasher> bool HashMap<KeyType, ValueType, Hasher>::Erase(const KeyType& key) { unsigned bucketIdx = GetIndex(key); if (m_buckets[bucketIdx] == INVALID_INDEX) return false; int* pointingIdx = &m_buckets[bucketIdx]; HashNode* node = &m_table[*pointingIdx]; while (node->next != INVALID_INDEX && node->key != key) { pointingIdx = &node->next; node = &m_table[node->next]; } if (node->key != key) return false; int freeNodeIdx = *pointingIdx; *pointingIdx = node->next; DELETE_PLACEMENT(node); m_size--; if(m_size > 0 && freeNodeIdx != m_size) { //fill up hole in m_table HashNode& lastNode = m_table[m_size]; unsigned lastNodeBucketIdx = GetIndex(lastNode.key); pointingIdx = &m_buckets[lastNodeBucketIdx]; while(m_table[*pointingIdx].key != lastNode.key) { pointingIdx = &(m_table[*pointingIdx].next); } *pointingIdx = freeNodeIdx; NEW_PLACEMENT(node, HashNode)(Utils::Move(lastNode)); //DELETE_PLACEMENT(&lastNode); } return true; } template<class KeyType, class ValueType, class Hasher> void HashMap<KeyType, ValueType, Hasher>::Rehash(unsigned bucketSize) { ASSERT(bucketSize > m_bucketSize); int* oldBuckets = m_buckets; unsigned oldBucketSize = m_bucketSize; HashNode* oldTable = m_table; unsigned oldSize = m_size; m_bucketSize = bucketSize; m_size = 0; void* data = m_allocator.Allocate(bucketSize * (sizeof(int) + sizeof(HashNode)) + alignof(HashNode), alignof(int)); m_buckets = static_cast<int*>(data); m_table = static_cast<HashNode*>(AlignPointer(m_buckets + bucketSize, alignof(HashNode))); for (unsigned i = 0; i < m_bucketSize; ++i) { m_buckets[i] = INVALID_INDEX; } for (unsigned i = 0; i < oldSize; ++i) { HashNode& node = oldTable[i]; unsigned idx = GetIndex(node.key); Insert(idx, node.key, node.value); } if (oldBuckets != nullptr) m_allocator.Deallocate(oldBuckets); } template<class KeyType, class ValueType, class Hasher> size_t HashMap<KeyType, ValueType, Hasher>::GetBucketsSize() const { return m_bucketSize; } template<class KeyType, class ValueType, class Hasher> size_t HashMap<KeyType, ValueType, Hasher>::GetSize() const { return m_size; } template<class KeyType, class ValueType, class Hasher> ValueType* HashMap<KeyType, ValueType, Hasher>::Insert(unsigned bucketIdx, const KeyType& key, const ValueType& value) { ASSERT(m_size < m_bucketSize); if (m_buckets[bucketIdx] == INVALID_INDEX) { HashNode* newNode = NEW_PLACEMENT(m_table + m_size, HashNode)(key, value); m_buckets[bucketIdx] = m_size++; return &newNode->value; } HashNode* node = &m_table[m_buckets[bucketIdx]]; while (node->key != key && node->next != INVALID_INDEX) { node = &m_table[node->next]; } if (node->key == key) { return nullptr; } else { HashNode* newNode = NEW_PLACEMENT(m_table + m_size, HashNode)(key, value); node->next = m_size++; return &newNode->value; } } template<class KeyType, class ValueType, class Hasher> unsigned HashMap<KeyType, ValueType, Hasher>::GetIndex(const KeyType& key) const { auto hash = Hasher::get(key); return hash % m_bucketSize; } template<class KeyType, class ValueType, class Hasher> typename HashMap<KeyType, ValueType, Hasher>::HashNode* HashMap<KeyType, ValueType, Hasher>::GetNode(unsigned index) { ASSERT(index < m_bucketSize); return &m_table[index]; } template<class KeyType, class ValueType, class Hasher> inline typename HashMap<KeyType, ValueType, Hasher>::HashNode* begin(HashMap<KeyType, ValueType, Hasher>& a) { return a.Begin(); } template<class KeyType, class ValueType, class Hasher> inline typename HashMap<KeyType, ValueType, Hasher>::HashNode* end(HashMap<KeyType, ValueType, Hasher>& a) { return a.End(); } template<class KeyType, class ValueType, class Hasher> inline typename const HashMap<KeyType, ValueType, Hasher>::HashNode* begin(const HashMap<KeyType, ValueType, Hasher>& a) { return a.Begin(); } template<class KeyType, class ValueType, class Hasher> inline typename const HashMap<KeyType, ValueType, Hasher>::HashNode* end(const HashMap<KeyType, ValueType, Hasher>& a) { return a.End(); } }
26.103659
176
0.726583
JakubLukas
92c3decbf871b019c6694afd8c9bea1858e7186f
968
cpp
C++
PlacementQuestions/OYO/decodingbottomup.cpp
UltraProton/Placement-Prepration
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
null
null
null
PlacementQuestions/OYO/decodingbottomup.cpp
UltraProton/Placement-Prepration
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
3
2020-05-08T18:02:51.000Z
2020-05-09T08:37:35.000Z
PlacementQuestions/OYO/decodingbottomup.cpp
UltraProton/PlacementPrep
cc70f174c4410c254ce0469737a884fffdc81164
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int decodings(string &str); int main(){ string str=""; cin>>str; cout<<decodings(str)<<endl; return 0; } int decodings(string &str){ int n=str.size(); /* Here just do the reverse process of memoization and get the ans in the bottom up manner. Compare it with the memoized version and you will get more clarity. */ vector<int> dp(n+1,0); //base case dp[0]=1; dp[1]=1; //Here we are going to fill the table bottomup both the conditions are same here also just the order is different and even if you look //closely then you will see that the order of filling the table is same in both the cases it's just difference in methodology for(int i=2;i<=n;i++){ if(str[i-1]>'0'){ dp[i]+=dp[i-1]; } if(str[i-2]=='1' || (str[i-2]=='2' && str[i-1]<'7')){ dp[i]+=dp[i-2]; } } return dp[n]; }
24.2
138
0.578512
UltraProton
92c44819ec2878a97e864ef8ba12077f9b4084e3
731
cpp
C++
cpp/src/main/data_generators/TimeframeDataGenerator.cpp
fbobee/Alpenglow
5f956511017c1bee72390aaecd964c04d8ad4b45
[ "Apache-2.0" ]
28
2017-07-23T22:47:44.000Z
2022-03-12T15:11:13.000Z
cpp/src/main/data_generators/TimeframeDataGenerator.cpp
fbobee/Alpenglow
5f956511017c1bee72390aaecd964c04d8ad4b45
[ "Apache-2.0" ]
4
2017-05-10T10:23:17.000Z
2019-05-23T14:07:09.000Z
cpp/src/main/data_generators/TimeframeDataGenerator.cpp
fbobee/Alpenglow
5f956511017c1bee72390aaecd964c04d8ad4b45
[ "Apache-2.0" ]
9
2017-05-04T09:20:58.000Z
2021-12-14T08:19:01.000Z
#include "TimeframeDataGenerator.h" RecommenderData* TimeframeDataGenerator::generate_recommender_data(RecDat*){ local_recommender_data_.clear(); double now = recommender_data_iterator_->get_actual()->time; double timeframe_begin=now-timeframe_length_; vector<RecDat>* train_data = local_recommender_data_.get_rec_data(); for(int counter = recommender_data_iterator_->get_counter();counter>=0;counter--){ RecDat* rec_dat = recommender_data_iterator_->get(counter); if(rec_dat->time<=timeframe_begin) break; train_data->push_back(*rec_dat); } if (!local_recommender_data_.initialize()) throw runtime_error("Initialization of local_recommender_data was unsuccesful."); return &local_recommender_data_; }
45.6875
126
0.793434
fbobee
92c4de0efac80a39026d318d969880de4dc60da2
4,966
cpp
C++
aws-cpp-sdk-inspector2/source/model/Ec2InstanceAggregation.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-inspector2/source/model/Ec2InstanceAggregation.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-inspector2/source/model/Ec2InstanceAggregation.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/inspector2/model/Ec2InstanceAggregation.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Inspector2 { namespace Model { Ec2InstanceAggregation::Ec2InstanceAggregation() : m_amisHasBeenSet(false), m_instanceIdsHasBeenSet(false), m_instanceTagsHasBeenSet(false), m_operatingSystemsHasBeenSet(false), m_sortBy(Ec2InstanceSortBy::NOT_SET), m_sortByHasBeenSet(false), m_sortOrder(SortOrder::NOT_SET), m_sortOrderHasBeenSet(false) { } Ec2InstanceAggregation::Ec2InstanceAggregation(JsonView jsonValue) : m_amisHasBeenSet(false), m_instanceIdsHasBeenSet(false), m_instanceTagsHasBeenSet(false), m_operatingSystemsHasBeenSet(false), m_sortBy(Ec2InstanceSortBy::NOT_SET), m_sortByHasBeenSet(false), m_sortOrder(SortOrder::NOT_SET), m_sortOrderHasBeenSet(false) { *this = jsonValue; } Ec2InstanceAggregation& Ec2InstanceAggregation::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("amis")) { Array<JsonView> amisJsonList = jsonValue.GetArray("amis"); for(unsigned amisIndex = 0; amisIndex < amisJsonList.GetLength(); ++amisIndex) { m_amis.push_back(amisJsonList[amisIndex].AsObject()); } m_amisHasBeenSet = true; } if(jsonValue.ValueExists("instanceIds")) { Array<JsonView> instanceIdsJsonList = jsonValue.GetArray("instanceIds"); for(unsigned instanceIdsIndex = 0; instanceIdsIndex < instanceIdsJsonList.GetLength(); ++instanceIdsIndex) { m_instanceIds.push_back(instanceIdsJsonList[instanceIdsIndex].AsObject()); } m_instanceIdsHasBeenSet = true; } if(jsonValue.ValueExists("instanceTags")) { Array<JsonView> instanceTagsJsonList = jsonValue.GetArray("instanceTags"); for(unsigned instanceTagsIndex = 0; instanceTagsIndex < instanceTagsJsonList.GetLength(); ++instanceTagsIndex) { m_instanceTags.push_back(instanceTagsJsonList[instanceTagsIndex].AsObject()); } m_instanceTagsHasBeenSet = true; } if(jsonValue.ValueExists("operatingSystems")) { Array<JsonView> operatingSystemsJsonList = jsonValue.GetArray("operatingSystems"); for(unsigned operatingSystemsIndex = 0; operatingSystemsIndex < operatingSystemsJsonList.GetLength(); ++operatingSystemsIndex) { m_operatingSystems.push_back(operatingSystemsJsonList[operatingSystemsIndex].AsObject()); } m_operatingSystemsHasBeenSet = true; } if(jsonValue.ValueExists("sortBy")) { m_sortBy = Ec2InstanceSortByMapper::GetEc2InstanceSortByForName(jsonValue.GetString("sortBy")); m_sortByHasBeenSet = true; } if(jsonValue.ValueExists("sortOrder")) { m_sortOrder = SortOrderMapper::GetSortOrderForName(jsonValue.GetString("sortOrder")); m_sortOrderHasBeenSet = true; } return *this; } JsonValue Ec2InstanceAggregation::Jsonize() const { JsonValue payload; if(m_amisHasBeenSet) { Array<JsonValue> amisJsonList(m_amis.size()); for(unsigned amisIndex = 0; amisIndex < amisJsonList.GetLength(); ++amisIndex) { amisJsonList[amisIndex].AsObject(m_amis[amisIndex].Jsonize()); } payload.WithArray("amis", std::move(amisJsonList)); } if(m_instanceIdsHasBeenSet) { Array<JsonValue> instanceIdsJsonList(m_instanceIds.size()); for(unsigned instanceIdsIndex = 0; instanceIdsIndex < instanceIdsJsonList.GetLength(); ++instanceIdsIndex) { instanceIdsJsonList[instanceIdsIndex].AsObject(m_instanceIds[instanceIdsIndex].Jsonize()); } payload.WithArray("instanceIds", std::move(instanceIdsJsonList)); } if(m_instanceTagsHasBeenSet) { Array<JsonValue> instanceTagsJsonList(m_instanceTags.size()); for(unsigned instanceTagsIndex = 0; instanceTagsIndex < instanceTagsJsonList.GetLength(); ++instanceTagsIndex) { instanceTagsJsonList[instanceTagsIndex].AsObject(m_instanceTags[instanceTagsIndex].Jsonize()); } payload.WithArray("instanceTags", std::move(instanceTagsJsonList)); } if(m_operatingSystemsHasBeenSet) { Array<JsonValue> operatingSystemsJsonList(m_operatingSystems.size()); for(unsigned operatingSystemsIndex = 0; operatingSystemsIndex < operatingSystemsJsonList.GetLength(); ++operatingSystemsIndex) { operatingSystemsJsonList[operatingSystemsIndex].AsObject(m_operatingSystems[operatingSystemsIndex].Jsonize()); } payload.WithArray("operatingSystems", std::move(operatingSystemsJsonList)); } if(m_sortByHasBeenSet) { payload.WithString("sortBy", Ec2InstanceSortByMapper::GetNameForEc2InstanceSortBy(m_sortBy)); } if(m_sortOrderHasBeenSet) { payload.WithString("sortOrder", SortOrderMapper::GetNameForSortOrder(m_sortOrder)); } return payload; } } // namespace Model } // namespace Inspector2 } // namespace Aws
29.384615
130
0.751108
perfectrecall
92c53c9df52cadbe122e3624411e3485c05c45f3
1,587
hpp
C++
include/nifty/meta/tuple.hpp
DerThorsten/nifty_meta
d31d35f54b8bf252518bee18eacaa696fee82e9b
[ "MIT" ]
null
null
null
include/nifty/meta/tuple.hpp
DerThorsten/nifty_meta
d31d35f54b8bf252518bee18eacaa696fee82e9b
[ "MIT" ]
null
null
null
include/nifty/meta/tuple.hpp
DerThorsten/nifty_meta
d31d35f54b8bf252518bee18eacaa696fee82e9b
[ "MIT" ]
null
null
null
#pragma once #include <utility> #include <tuple> #include <type_traits> #include "nifty/meta/integral_constant.hpp" namespace nifty{ namespace meta{ // find the position of a type in a tuple template <class T, class Tuple> struct TupleTypeIndex; template <class T, class... Types> struct TupleTypeIndex<T, std::tuple<T, Types...>> : SizeT<0>{ }; template <class T, class U, class... Types> struct TupleTypeIndex<T, std::tuple<U, Types...>> : SizeT<1 + TupleTypeIndex<T, std::tuple<Types...>>::value>{ }; template<class TUPLE, template<typename ...> typename C> struct TransformTuple; template<class ... TUPLE_ARGS , template< typename ... ARGS> class C> struct TransformTuple<std::tuple<TUPLE_ARGS ...>, C >{ typedef std::tuple< C<TUPLE_ARGS> ...> type; }; ///\cond namespace detail{ template<class INDEX_SEQUENCE, template<std::size_t I> typename C> struct GenerateTupleImpl; template<std::size_t... Ints, template<std::size_t I> typename C> struct GenerateTupleImpl<std::index_sequence<Ints ... >, C>{ typedef std::tuple<C<Ints> ...> type; }; } ///\endcond template<std::size_t N, template<std::size_t I> typename C> struct GenerateTuple : detail::GenerateTupleImpl<std::make_index_sequence<N>, C>{ }; template<std::size_t N, class T> struct GenerateUniformTuple{ template<std::size_t I> using Helper = T; typedef typename GenerateTuple<N, Helper>::type type; }; } }
24.415385
90
0.626969
DerThorsten
92c6ba5a053d1160281fff124d7e8af06a1982bc
2,579
cpp
C++
Gems/SceneLoggingExample/Code/SceneLoggingExampleModule.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2021-08-08T19:54:51.000Z
2021-08-08T19:54:51.000Z
Gems/SceneLoggingExample/Code/SceneLoggingExampleModule.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
2
2022-01-13T04:29:38.000Z
2022-03-12T01:05:31.000Z
Gems/SceneLoggingExample/Code/SceneLoggingExampleModule.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <IGem.h> #include <AzCore/Module/DynamicModuleHandle.h> #include <Behaviors/LoggingGroupBehavior.h> #include <Processors/LoadingTrackingProcessor.h> #include <Processors/ExportTrackingProcessor.h> namespace SceneLoggingExample { // The SceneLoggingExampleModule is the entry point for gems. To extend the SceneAPI, the // logging, loading, and export components must be registered here. // // NOTE: The gem system currently does not support registering file extensions through the // AssetImportRequest EBus. class SceneLoggingExampleModule : public CryHooksModule { public: AZ_RTTI(SceneLoggingExampleModule, "{36AA9C0F-7976-40C7-AF54-C492AC5B16F6}", CryHooksModule); SceneLoggingExampleModule() : CryHooksModule() { // The SceneAPI libraries require specialized initialization. As early as possible, be // sure to repeat the following two lines for any SceneAPI you want to use. Omitting these // calls or making them too late can cause problems such as missing EBus events. m_sceneCoreModule = AZ::DynamicModuleHandle::Create("SceneCore"); m_sceneCoreModule->Load(true); m_descriptors.insert(m_descriptors.end(), { LoggingGroupBehavior::CreateDescriptor(), LoadingTrackingProcessor::CreateDescriptor(), ExportTrackingProcessor::CreateDescriptor() }); } // In this example, no system components are added. You can use system components // to set global settings for this gem from the Project Configurator. // For functionality that should always be available to the SceneAPI, we recommend // that you use a BehaviorComponent instead. AZ::ComponentTypeList GetRequiredSystemComponents() const override { return AZ::ComponentTypeList {}; } private: AZStd::unique_ptr<AZ::DynamicModuleHandle> m_sceneCoreModule; }; } // namespace SceneLoggingExample // DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM. // The first parameter should be GemName_GemIdLower. // The second should be the fully qualified name of the class above. AZ_DECLARE_MODULE_CLASS(Gem_SceneLoggingExample, SceneLoggingExample::SceneLoggingExampleModule)
41.596774
103
0.700271
cypherdotXd
92c86eff570db4bfbf5327d180ddc0796b1655e6
1,379
cpp
C++
tests/channels.cpp
DEGoodmanWilson/plaidapi
ae993f45865811b8480e74466c3de88954f25b69
[ "MIT" ]
29
2015-12-21T21:46:10.000Z
2021-05-03T19:09:27.000Z
tests/channels.cpp
DEGoodmanWilson/cpp-slack-client
ae993f45865811b8480e74466c3de88954f25b69
[ "MIT" ]
4
2016-07-10T04:22:25.000Z
2018-02-08T18:33:40.000Z
tests/channels.cpp
DEGoodmanWilson/cpp-slack-client
ae993f45865811b8480e74466c3de88954f25b69
[ "MIT" ]
7
2017-08-16T17:00:11.000Z
2019-09-20T05:53:31.000Z
// // engine // // Copyright © 2015–2016 D.E. Goodman-Wilson. All rights reserved. // #include <gtest/gtest.h> #include <slack/slack.h> #include <random> #include "environment.h" slack::channel_id id; TEST(channels, channels_list_basic) { auto result = env->slack.channels.list(); ASSERT_TRUE(result); ASSERT_LT(0, result.channels.size()); //in most cases it will be at least 2 (#general and #random) } TEST(channels, channels_create_basic) { std::string name = "tc"; auto result = env->slack.channels.create(name); ASSERT_TRUE(result); ASSERT_TRUE(static_cast<bool>(result.channel)); slack::channel chan{*result.channel}; //TODO store the ID so we can delete its id = chan.id; ASSERT_EQ(name, chan.name); } //TODO shouldn't depend upon id stored in last test! Should find it anew! TEST(channels, channels_rename_basic) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis{}; int rand = dis(gen); std::string new_name = "tc-"+std::to_string(rand); auto result = env->slack.channels.rename(id, new_name); ASSERT_TRUE(result); slack::channel chan{*result.channel}; ASSERT_EQ(new_name, chan.name); } TEST(channels, channels_archive_basic) { auto result = env->slack.channels.archive(id); ASSERT_TRUE(result); //really not much else we can check here. }
26.519231
102
0.68673
DEGoodmanWilson
92c886868c9ee688b61549cd38d011f4d4e9cc10
4,506
cpp
C++
src/mongo/dbtests/counttests.cpp
corefan/mongo
c949cad1fa6e4cb26693748b1751f4fd2e6113b8
[ "Apache-2.0" ]
null
null
null
src/mongo/dbtests/counttests.cpp
corefan/mongo
c949cad1fa6e4cb26693748b1751f4fd2e6113b8
[ "Apache-2.0" ]
null
null
null
src/mongo/dbtests/counttests.cpp
corefan/mongo
c949cad1fa6e4cb26693748b1751f4fd2e6113b8
[ "Apache-2.0" ]
1
2021-02-28T12:03:02.000Z
2021-02-28T12:03:02.000Z
// counttests.cpp : count.{h,cpp} unit tests. /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "../db/ops/count.h" #include "../db/cursor.h" #include "../db/pdfile.h" #include "dbtests.h" namespace CountTests { class Base { Lock::DBWrite lk; Client::Context _context; public: Base() : lk(ns()), _context( ns() ) { addIndex( fromjson( "{\"a\":1}" ) ); } ~Base() { try { boost::shared_ptr<Cursor> c = theDataFileMgr.findAll( ns() ); vector< DiskLoc > toDelete; for(; c->ok(); c->advance() ) toDelete.push_back( c->currLoc() ); for( vector< DiskLoc >::iterator i = toDelete.begin(); i != toDelete.end(); ++i ) theDataFileMgr.deleteRecord( ns(), i->rec(), *i, false ); DBDirectClient cl; cl.dropIndexes( ns() ); } catch ( ... ) { FAIL( "Exception while cleaning up collection" ); } } protected: static const char *ns() { return "unittests.counttests"; } static void addIndex( const BSONObj &key ) { BSONObjBuilder b; b.append( "name", key.firstElementFieldName() ); b.append( "ns", ns() ); b.append( "key", key ); BSONObj o = b.done(); stringstream indexNs; indexNs << "unittests.system.indexes"; theDataFileMgr.insert( indexNs.str().c_str(), o.objdata(), o.objsize() ); } static void insert( const char *s ) { insert( fromjson( s ) ); } static void insert( const BSONObj &o ) { theDataFileMgr.insert( ns(), o.objdata(), o.objsize() ); } }; class CountBasic : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); BSONObj cmd = fromjson( "{\"query\":{}}" ); string err; ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) ); } }; class CountQuery : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"a\":\"b\",\"x\":\"y\"}" ); insert( "{\"a\":\"c\"}" ); BSONObj cmd = fromjson( "{\"query\":{\"a\":\"b\"}}" ); string err; ASSERT_EQUALS( 2, runCount( ns(), cmd, err ) ); } }; class CountFields : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"c\":\"d\"}" ); BSONObj cmd = fromjson( "{\"query\":{},\"fields\":{\"a\":1}}" ); string err; ASSERT_EQUALS( 2, runCount( ns(), cmd, err ) ); } }; class CountQueryFields : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"a\":\"c\"}" ); insert( "{\"d\":\"e\"}" ); BSONObj cmd = fromjson( "{\"query\":{\"a\":\"b\"},\"fields\":{\"a\":1}}" ); string err; ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) ); } }; class CountIndexedRegex : public Base { public: void run() { insert( "{\"a\":\"b\"}" ); insert( "{\"a\":\"c\"}" ); BSONObj cmd = fromjson( "{\"query\":{\"a\":/^b/}}" ); string err; ASSERT_EQUALS( 1, runCount( ns(), cmd, err ) ); } }; class All : public Suite { public: All() : Suite( "count" ) { } void setupTests() { add< CountBasic >(); add< CountQuery >(); add< CountFields >(); add< CountQueryFields >(); add< CountIndexedRegex >(); } } myall; } // namespace CountTests
31.51049
97
0.46893
corefan
92c8fb05fa571187ba977c80c16b54df073d7bc5
771
cc
C++
src/InsetOp.cc
pbrier/Mandoline
bb517e7e5ba531d4e20c2474a53ee521dd1d1642
[ "BSD-2-Clause-FreeBSD" ]
1
2017-01-05T06:40:55.000Z
2017-01-05T06:40:55.000Z
src/InsetOp.cc
pbrier/Mandoline
bb517e7e5ba531d4e20c2474a53ee521dd1d1642
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/InsetOp.cc
pbrier/Mandoline
bb517e7e5ba531d4e20c2474a53ee521dd1d1642
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
// // InsetOp.cc // Mandoline // // Created by GM on 11/24/10. // Copyright 2010 Belfry DevWorks. All rights reserved. // #include "InsetOp.h" #include "BGL/BGL.h" #include "SlicingContext.h" #include "CarvedSlice.h" InsetOp::~InsetOp() { } void InsetOp::main() { if ( isCancelled ) return; if ( NULL == context ) return; if ( NULL == slice ) return; double extWidth = context->standardExtrusionWidth(); int shells = context->perimeterShells; slice->perimeter.inset(shells*extWidth, slice->infillMask); for (int i = 0; i < shells; i++) { BGL::CompoundRegion compReg; slice->perimeter.inset((i+0.5)*extWidth, compReg); slice->shells.push_back(compReg); } slice->state = INSET; if ( isCancelled ) return; }
17.930233
63
0.642023
pbrier
92ca45d952b728252016469f97d12fc89da27889
1,020
cpp
C++
src/test_suites/oclc/oclc_attribute_qualifiers/src/aligned.cpp
intel/cassian
8e9594f053f9b9464066c8002297346580e4aa2a
[ "MIT" ]
1
2021-10-05T14:15:34.000Z
2021-10-05T14:15:34.000Z
src/test_suites/oclc/oclc_attribute_qualifiers/src/aligned.cpp
intel/cassian
8e9594f053f9b9464066c8002297346580e4aa2a
[ "MIT" ]
null
null
null
src/test_suites/oclc/oclc_attribute_qualifiers/src/aligned.cpp
intel/cassian
8e9594f053f9b9464066c8002297346580e4aa2a
[ "MIT" ]
null
null
null
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "common.hpp" #include "test_config.hpp" #include <cassian/cli/cli.hpp> #include <cassian/runtime/runtime.hpp> #include <cassian/utility/utility.hpp> #include <catch2/catch.hpp> #include <cstdint> #include <numeric> #include <string> #include <vector> namespace ca = cassian; namespace { void test_aligned(ca::Runtime *runtime, const size_t global_work_size, const std::string &program_type) { const std::string source = ca::load_text_file( ca::get_asset("kernels/oclc_attribute_qualifiers/aligned.cl")); ca::Kernel kernel = runtime->create_kernel("test_kernel", source, "", program_type); runtime->run_kernel(kernel, global_work_size); runtime->release_kernel(kernel); } } // namespace TEST_CASE("aligned", "") { const TestConfig &config = get_test_config(); const auto size = config.work_size(); REQUIRE_NOTHROW(test_aligned(config.runtime(), size, config.program_type())); }
26.153846
79
0.716667
intel
92cba6c170fecd7e2b901c7d0f2beb71fa644f35
8,542
hpp
C++
dakota-6.3.0.Windows.x86/include/HOPSPACK_GssPoint.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/HOPSPACK_GssPoint.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/HOPSPACK_GssPoint.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
1
2022-03-18T14:13:14.000Z
2022-03-18T14:13:14.000Z
// $Id: HOPSPACK_GssPoint.hpp 149 2009-11-12 02:40:41Z tplante $ // $URL: https://software.sandia.gov/svn/hopspack/tags/dakota-6.3/src/src-citizens/citizen-gss/HOPSPACK_GssPoint.hpp $ //@HEADER // ************************************************************************ // // HOPSPACK: Hybrid Optimization Parallel Search Package // Copyright 2009 Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // This file is part of HOPSPACK. // // HOPSPACK is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library. If not, see http://www.gnu.org/licenses/. // // Questions? Contact Tammy Kolda (tgkolda@sandia.gov) // or Todd Plantenga (tplante@sandia.gov) // // ************************************************************************ //@HEADER /*! @file HOPSPACK_GssPoint.hpp @brief Class declaration for HOPSPACK::GssPoint, subclass of DataPoint. */ #ifndef HOPSPACK_GSSPOINT_HPP #define HOPSPACK_GSSPOINT_HPP #include "HOPSPACK_common.hpp" #include "HOPSPACK_DataPoint.hpp" #include "HOPSPACK_NonlConstrPenalty.hpp" #include "HOPSPACK_ProblemDef.hpp" #include "HOPSPACK_Vector.hpp" namespace HOPSPACK { //---------------------------------------------------------------------- //! Contains a trial location, evaluation results, and GSS parent information. /*! An instance contains the DataPoint base class members, plus GSS parent information and a method to compare evaluation results as a scalar. */ //---------------------------------------------------------------------- class GssPoint : public DataPoint { public: //! Tag value if a point has no GSS parent. static const int NO_PARENT_TAG = -1; //! Direction index value if a point has no parent direction. static const int NO_DIR_INDEX = -1; //! Constructor for a point with no parent. /*! * @param[in] nObjGoal Optimization goal: minimize, maximize, etc. * @param[in] cPenalty Penalty function for nonlinear constraints. * @param[in] cX Location of the trial point. * @param[in] dStep Step length used to generate this point. */ GssPoint (const ProblemDef::ObjectiveType nObjGoal, const NonlConstrPenalty & cPenalty, const Vector & cX, const double dStep); //! Constructor for a point generated from a parent point. /*! * @param[in] nObjGoal Optimization goal: minimize, maximize, etc. * @param[in] cPenalty Penalty function for nonlinear constraints. * @param[in] cX Location of the trial point. * @param[in] dStep Step length used to generate this point. * @param[in] nParentTag Tag of the parent of this point. * @param[in] dParentObj Objective of the parent of this point. * @param[in] dPenaltyTerm Nonlinear constraint penalty of the parent * at this point. * @param[in] dSuffImprvAmt Sufficient improvement amount (>= 0) that * the point must make over dParentObj. * @param[in] nDirIndex Direction index that generated this point. */ GssPoint (const ProblemDef::ObjectiveType nObjGoal, const NonlConstrPenalty & cPenalty, const Vector & cX, const double dStep, const int nParentTag, const double dParentObj, const double dPenaltyTerm, const double dSuffImprvAmt, const int nDirIndex); //! Constructor that makes an instance from a DataPoint not from GSS. /*! * The GSS citizen may use DataPoint instances generated from other * citizens or the framework. The new GssPoint has no parent, and is * typically assigned the GSS default initial step length for purposes * of computing more trial points. * * @param[in] cArg Existing point to be copied. * @param[in] cPenalty Penalty function for nonlinear constraints. * @param[in] dStep Step length to use. */ GssPoint (const DataPoint & cArg, const NonlConstrPenalty & cPenalty, const double dStep); //! Copy Constructor that makes a deep copy. GssPoint (const GssPoint & cArg); //! Destructor. ~GssPoint (void); //! Return the parent tag of the point. int getParentTag (void) const; //! Return the step length used to generate this point. double getStepLength (void) const; //! Return the index of the direction that generated this point. int getDirIndex (void) const; //! Return the evaluated objective function value plus penalty. /*! * This overrides the method in HOPSPACK_DataPoint to allow the citizen * to add nonlinear constraints as penalty terms. * * If getVecF() contains multiple objectives, then the "best" objective * is determined by calling HOPSPACK_DataPoint::getBestF(). * The NonlConstrPenalty associated with this point is used to compute * a penalty term for violated nonlinear constraints. The term causes * the objective to become worse if constraints are violated. * For instance, if optimization is trying to minimize the objective, * then a positive penalty term is added to the output of getBestF(). * If maximizing, then a positive penalty term is subtracted. */ double getBestF (void) const; //! Return true if this point's objective plus penalty is better. /*! * The method assumes both points are linearly feasible. * It calls DataPoint::getBestF() to combine multiple objectives and then * make a scalar inequality comparison. Special rules apply * if the point has not been evaluated, or the objective does not exist. * If nonlinear constraints are present, then the objective includes * a penalty term. */ bool isBetterObjThan (const GssPoint & other) const; //! Return true if the evaluated objective makes sufficient improvement. /*! * The objective of the point must improve over its parent's by an * amount that exceeds the "sufficient decrease" forcing function. * The forcing function is defined in GssIterator where it computes * the sufficient improvement amount for the GssPoint constructor. * The function is \f[ \rho (\Delta) = \alpha \Delta^2 \f] * where \f$ \Delta \f$ is step length, and \f$ \alpha \f$ is the * user parameter "Sufficient Improvement Factor". * If \f$ \alpha = 0 \f$, then the point need only make "simple decrease" * over the parent point. * If the point has no GSS parent, then the method returns true. */ bool hasSufficientImprovement (void) const; //! Print to the given stream. void print (ostream & stream, const bool bIncludeMsg = true) const; private: //! By design, there is no assignment operator. GssPoint & operator= (const GssPoint &); //! GSS parent point tag, or the value NO_PARENT_TAG if none. int _nParentTag; //! Index of the direction that generated this point. int _nDirIndex; //! Step length that was used to generate this point. double _dStep; //! Parent's objective value. double _dParentObjective; //! Sufficient improvement amount needed compared with parent's objective. double _dSufficientImprovementAmount; //! Penalty function for nonlinear constraints. const NonlConstrPenalty & _cPenalty; }; } //-- namespace HOPSPACK #endif //-- HOPSPACK_GSSPOINT_HPP
40.103286
118
0.629127
seakers
92ce80dee32381fbf4485023ff9bb4205014b7fe
320
hpp
C++
include/Resources.hpp
iElden/GameJam2019
fc013ac865e62ad9e815734ebca7bc2371febaff
[ "MIT" ]
5
2019-01-25T18:21:55.000Z
2019-01-29T08:44:54.000Z
include/Resources.hpp
iElden/GameJam2019
fc013ac865e62ad9e815734ebca7bc2371febaff
[ "MIT" ]
null
null
null
include/Resources.hpp
iElden/GameJam2019
fc013ac865e62ad9e815734ebca7bc2371febaff
[ "MIT" ]
null
null
null
// // Created by Andgel on 25/01/2019. // #ifndef GRANDMATD_RESOURCES_HPP #define GRANDMATD_RESOURCES_HPP #include <vector> namespace gtd { struct Food { enum Type { Any, GlutenFree = 0, Vegan = 0, Carnivore = 0, NbOfTypes }; std::vector<double> stock; }; } #endif //GRANDMATD_RESOURCES_HPP
12.307692
35
0.665625
iElden
92d2a9768ca8e325449061abc08f2601190a0678
1,264
cpp
C++
engine/src/Threading/WorkerThread.cpp
Husenap/Wraith
79bdfdda77a97ee2859ea2455647b59700e22753
[ "MIT" ]
1
2021-06-27T14:46:46.000Z
2021-06-27T14:46:46.000Z
engine/src/Threading/WorkerThread.cpp
Husenap/2DGE
79bdfdda77a97ee2859ea2455647b59700e22753
[ "MIT" ]
19
2021-10-29T19:20:40.000Z
2021-12-20T01:18:34.000Z
engine/src/Threading/WorkerThread.cpp
KyaZero/Wraith
6e084f46c3c6ca1bcbedb7950d33d10b546e6454
[ "MIT" ]
1
2021-06-27T15:09:52.000Z
2021-06-27T15:09:52.000Z
#include "WorkerThread.h" #include "Engine.h" namespace Wraith { WorkerThread::WorkerThread(const std::string& id) : Thread(id) { Clear(); } WorkerThread::~WorkerThread() { } void WorkerThread::Clear() { m_ProjectedTime = 0; m_QueuedJobs.clear(); } void WorkerThread::Queue(std::shared_ptr<PersistentJob> job) { if (ShouldRun()) { m_QueuedJobs.push_back(job); m_ProjectedTime += job->GetAverageTime(); } } void WorkerThread::Run() { SetActive(true); m_Channel.notify_all(); } const f32 WorkerThread::GetProjectedTime() const { return m_ProjectedTime; } void WorkerThread::Execute() { while (ShouldRun()) { std::unique_lock<std::mutex> wait_lock(m_Mutex); while (!IsRunning() && ShouldRun()) { m_Channel.wait(wait_lock); } wait_lock.unlock(); if (!ShouldRun()) return; f32 accumulated_time = 0.0f; for (auto& job : m_QueuedJobs) accumulated_time += job->Execute(); SetActive(false); } } } // namespace Wraith
21.066667
80
0.522943
Husenap
92d4102f3c57548f3009437cd233061ce61c065c
4,684
cpp
C++
src/slg/textures/triplanar.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
826
2017-12-12T15:38:16.000Z
2022-03-28T07:12:40.000Z
src/slg/textures/triplanar.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
531
2017-12-03T17:21:06.000Z
2022-03-20T19:22:11.000Z
src/slg/textures/triplanar.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
133
2017-12-13T18:46:10.000Z
2022-03-27T16:21:00.000Z
/*************************************************************************** * Copyright 1998-2020 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * 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 "slg/textures/triplanar.h" using namespace std; using namespace luxrays; using namespace slg; //------------------------------------------------------------------------------ // Triplanar mapping texture //------------------------------------------------------------------------------ float TriplanarTexture::GetFloatValue(const HitPoint &hitPoint) const { return GetSpectrumValue(hitPoint).Y(); } Spectrum TriplanarTexture::GetSpectrumValue(const HitPoint &hitPoint) const { Normal localShadeN; const Point localPoint = mapping->Map(hitPoint, &localShadeN); float weights[3] = { Sqr(Sqr(localShadeN.x)), Sqr(Sqr(localShadeN.y)), Sqr(Sqr(localShadeN.z)) }; const float sum = weights[0] + weights[1] + weights[2]; weights[0] = weights[0] / sum; weights[1] = weights[1] / sum; weights[2] = weights[2] / sum; HitPoint hitPointTmp = hitPoint; hitPointTmp.defaultUV.u = localPoint.y; hitPointTmp.defaultUV.v = localPoint.z; Spectrum result = texX->GetSpectrumValue(hitPointTmp) * weights[0]; hitPointTmp.defaultUV.u = localPoint.x; hitPointTmp.defaultUV.v = localPoint.z; result += texY->GetSpectrumValue(hitPointTmp) * weights[1]; hitPointTmp.defaultUV.u = localPoint.x; hitPointTmp.defaultUV.v = localPoint.y; result += texZ->GetSpectrumValue(hitPointTmp) * weights[2]; return result; } Normal TriplanarTexture::Bump(const HitPoint &hitPoint, const float sampleDistance) const { if (enableUVlessBumpMap) { // Calculate bump map value at intersection point const float base = GetFloatValue(hitPoint); // Compute offset positions and evaluate displacement texture const Point origP = hitPoint.p; HitPoint hitPointTmp = hitPoint; Normal dhdx; // Note: I should update not only hitPointTmp.p but also hitPointTmp.shadeN // however I can't because I don't know dndv/dndu so this is nearly an hack. hitPointTmp.p.x = origP.x + sampleDistance; hitPointTmp.p.y = origP.y; hitPointTmp.p.z = origP.z; const float offsetX = GetFloatValue(hitPointTmp); dhdx.x = (offsetX - base) / sampleDistance; hitPointTmp.p.x = origP.x; hitPointTmp.p.y = origP.y + sampleDistance; hitPointTmp.p.z = origP.z; const float offsetY = GetFloatValue(hitPointTmp); dhdx.y = (offsetY - base) / sampleDistance; hitPointTmp.p.x = origP.x; hitPointTmp.p.y = origP.y; hitPointTmp.p.z = origP.z + sampleDistance; const float offsetZ = GetFloatValue(hitPointTmp); dhdx.z = (offsetZ - base) / sampleDistance; Normal newShadeN = Normalize(hitPoint.shadeN - dhdx); newShadeN *= (Dot(hitPoint.shadeN, newShadeN) < 0.f) ? -1.f : 1.f; return newShadeN; } else return Texture::Bump(hitPoint, sampleDistance); } Properties TriplanarTexture::ToProperties(const ImageMapCache &imgMapCache, const bool useRealFileName) const { Properties props; const string name = GetName(); props.Set(Property("scene.textures." + name + ".type")("triplanar")); props.Set(Property("scene.textures." + name + ".texture1")(texX->GetSDLValue())); props.Set(Property("scene.textures." + name + ".texture2")(texY->GetSDLValue())); props.Set(Property("scene.textures." + name + ".texture3")(texZ->GetSDLValue())); props.Set(Property("scene.textures." + name + ".uvlessbumpmap.enable")(enableUVlessBumpMap)); props.Set(mapping->ToProperties("scene.textures." + name + ".mapping")); return props; }
40.034188
111
0.596926
julescmay
92d7471ba22507bd808e06cfc9cc30a49bf903a6
8,606
cpp
C++
SurgSim/Devices/MultiAxis/UnitTests/RawMultiAxisDeviceTest.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
24
2015-01-19T16:18:59.000Z
2022-03-13T03:29:11.000Z
SurgSim/Devices/MultiAxis/UnitTests/RawMultiAxisDeviceTest.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
3
2018-12-21T14:54:08.000Z
2022-03-14T12:38:07.000Z
SurgSim/Devices/MultiAxis/UnitTests/RawMultiAxisDeviceTest.cpp
dbungert/opensurgsim
bd30629f2fd83f823632293959b7654275552fa9
[ "Apache-2.0" ]
8
2015-04-10T19:45:36.000Z
2022-02-02T17:00:59.000Z
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \file /// Tests for the RawMultiAxisDevice class. #include <memory> #include <string> #include <boost/thread.hpp> #include <boost/chrono.hpp> #include <gtest/gtest.h> #include "SurgSim/Devices/MultiAxis/RawMultiAxisDevice.h" #include "SurgSim/DataStructures/DataGroup.h" #include "SurgSim/Math/RigidTransform.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Testing/MockInputOutput.h" using SurgSim::Devices::RawMultiAxisDevice; using SurgSim::Devices::RawMultiAxisScaffold; using SurgSim::DataStructures::DataGroup; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Matrix44d; using SurgSim::Testing::MockInputOutput; TEST(RawMultiAxisDeviceTest, CreateUninitializedDevice) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; } TEST(RawMultiAxisDeviceTest, CreateAndInitializeDevice) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_FALSE(device->isInitialized()); ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; EXPECT_TRUE(device->isInitialized()); } TEST(RawMultiAxisDeviceTest, Name) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; EXPECT_EQ("TestRawMultiAxis", device->getName()); EXPECT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; EXPECT_EQ("TestRawMultiAxis", device->getName()); } TEST(RawMultiAxisDeviceTest, Factory) { std::shared_ptr<SurgSim::Input::DeviceInterface> device; ASSERT_NO_THROW(device = SurgSim::Input::DeviceInterface::getFactory().create( "SurgSim::Devices::RawMultiAxisDevice", "Device")); EXPECT_NE(nullptr, device); } static void testCreateDeviceSeveralTimes(bool doSleep) { for (int i = 0; i < 6; ++i) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; if (doSleep) { boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(100)); } // the device will be destroyed here } } TEST(RawMultiAxisDeviceTest, CreateDeviceSeveralTimes) { testCreateDeviceSeveralTimes(true); } TEST(RawMultiAxisDeviceTest, CreateSeveralDevices) { std::shared_ptr<RawMultiAxisDevice> device1 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis1"); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; // We can't check what happens with the scaffolds, since those are no longer a part of the device's API... std::shared_ptr<RawMultiAxisDevice> device2 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis2"); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; if (! device2->initialize()) { std::cerr << "[Warning: second RawMultiAxis controller did not come up; is it plugged in?]" << std::endl; } } TEST(RawMultiAxisDeviceTest, CreateDevicesWithSameName) { std::shared_ptr<RawMultiAxisDevice> device1 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis"); ASSERT_TRUE(device1 != nullptr) << "Device creation failed."; ASSERT_TRUE(device1->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; std::shared_ptr<RawMultiAxisDevice> device2 = std::make_shared<RawMultiAxisDevice>("RawMultiAxis"); ASSERT_TRUE(device2 != nullptr) << "Device creation failed."; ASSERT_FALSE(device2->initialize()) << "Initialization succeeded despite duplicate name."; } // Create a string representation from an int. // C++11 adds std::to_string() to do this for various types, but VS2010 only half-supports that. template <typename T> inline std::string makeString(T value) { std::ostringstream out; out << value; return out.str(); } TEST(RawMultiAxisDeviceTest, CreateAllDevices) { std::vector<std::shared_ptr<RawMultiAxisDevice>> devices; for (int i = 1; ; ++i) { std::string name = "RawMultiAxis" + makeString(i); std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>(name); ASSERT_TRUE(device != nullptr) << "Device creation failed."; if (! device->initialize()) { break; } devices.emplace_back(std::move(device)); } std::cout << devices.size() << " devices initialized." << std::endl; ASSERT_GT(devices.size(), 0U) << "Initialization failed. Is a RawMultiAxis device plugged in?"; } TEST(RawMultiAxisDeviceTest, InputConsumer) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; std::shared_ptr<MockInputOutput> consumer = std::make_shared<MockInputOutput>(); EXPECT_EQ(0, consumer->m_numTimesInitializedInput); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_FALSE(device->removeInputConsumer(consumer)); EXPECT_EQ(0, consumer->m_numTimesInitializedInput); EXPECT_EQ(0, consumer->m_numTimesReceivedInput); EXPECT_TRUE(device->addInputConsumer(consumer)); // Adding the same input consumer again should fail. EXPECT_FALSE(device->addInputConsumer(consumer)); // Sleep for a second, to see how many times the consumer is invoked. // (A RawMultiAxis device updates internally at 60Hz, but our code currently runs at 100Hz to reduce latency.) boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeInputConsumer(consumer)); // Removing the same input consumer again should fail. EXPECT_FALSE(device->removeInputConsumer(consumer)); // Check the number of invocations. EXPECT_EQ(1, consumer->m_numTimesInitializedInput); EXPECT_GE(consumer->m_numTimesReceivedInput, 90); EXPECT_LE(consumer->m_numTimesReceivedInput, 110); EXPECT_TRUE(consumer->m_lastReceivedInput.poses().hasData(SurgSim::DataStructures::Names::POSE)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_1)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_2)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_3)); EXPECT_TRUE(consumer->m_lastReceivedInput.booleans().hasData(SurgSim::DataStructures::Names::BUTTON_4)); } TEST(RawMultiAxisDeviceTest, OutputProducer) { std::shared_ptr<RawMultiAxisDevice> device = std::make_shared<RawMultiAxisDevice>("TestRawMultiAxis"); ASSERT_TRUE(device != nullptr) << "Device creation failed."; ASSERT_TRUE(device->initialize()) << "Initialization failed. Is a RawMultiAxis device plugged in?"; std::shared_ptr<MockInputOutput> producer = std::make_shared<MockInputOutput>(); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_FALSE(device->removeOutputProducer(producer)); EXPECT_EQ(0, producer->m_numTimesRequestedOutput); EXPECT_TRUE(device->setOutputProducer(producer)); // Sleep for a second, to see how many times the producer is invoked. // (A RawMultiAxis device is does not request any output.) boost::this_thread::sleep_until(boost::chrono::steady_clock::now() + boost::chrono::milliseconds(1000)); EXPECT_TRUE(device->removeOutputProducer(producer)); // Removing the same input producer again should fail. EXPECT_FALSE(device->removeOutputProducer(producer)); // Check the number of invocations. EXPECT_GE(producer->m_numTimesRequestedOutput, 90); EXPECT_LE(producer->m_numTimesRequestedOutput, 110); }
40.214953
111
0.765629
dbungert
92da1c435775bc9520949451a04473e003db78f7
1,676
cpp
C++
bitbots_throw_engine/src/throws/throw_curves/throw_movement_position_only.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
bitbots_throw_engine/src/throws/throw_curves/throw_movement_position_only.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
bitbots_throw_engine/src/throws/throw_curves/throw_movement_position_only.cpp
5reichar/bitbots_kick_engine
0817f4f0a206de6f0f01a0cedfe201f62e677a11
[ "BSD-3-Clause" ]
null
null
null
#include "throws/throw_curves/throw_movement_position_only.h" namespace bitbots_throw{ ThrowMovementPositionOnly::ThrowMovementPositionOnly(std::shared_ptr<ThrowMaterial> material) : ThrowMovement(material){ } void ThrowMovementPositionOnly::add_movement_prepare_throw(){ throw_start_time_ = trajectory_time_; ThrowMovement::add_movement_prepare_throw(); } void ThrowMovementPositionOnly::add_movement_throw(){ // get Values auto current_throw_release_time = trajectory_time_; double duration_throw = sp_service_->get_movement_time_throw(); duration_throw -= sp_service_->get_movement_offset_move_arms_away_from_ball(); Struct3dRPY velocity = sp_service_->calculate_throw_velocity(duration_throw); auto left_arm_throw_release = sp_service_->get_left_arm_throw_release(); auto diff = left_arm_throw_release.x_ - sp_service_->get_left_arm_ball_behind_head().x_; trajectory_time_ = throw_start_time_ + (diff / velocity.x_); //// Movement ////==== Release ball add_to_left_hand( left_arm_throw_release); add_to_right_hand(sp_service_->get_right_arm_throw_release()); ////==== Move arms away from the ball trajectory_time_ += sp_service_->get_movement_offset_move_arms_away_from_ball(); add_to_left_hand(sp_service_->get_left_arm_move_away_from_ball(velocity.x_)); add_to_right_hand(sp_service_->get_right_arm_move_away_from_ball(velocity.x_)); if(current_throw_release_time > trajectory_time_){ trajectory_time_ = current_throw_release_time; } } } //bitbots_throw
42.974359
97
0.73389
5reichar
92ddce5f43a5131e26d6b3cb705efcb8c1bfe597
82
cpp
C++
1-15/thefunction.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
1-15/thefunction.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
1-15/thefunction.cpp
domijin/ComPhy
0dea6d7b09eb4880b7f2d8f55c321c827e713488
[ "MIT" ]
null
null
null
#include<math.h> double cubeandmult(double u, double v) { return(pow(u,3)*v); }
13.666667
38
0.670732
domijin
92dfb4364f3f1b724689b74edb8cb2b31bac747a
43,626
cpp
C++
3rdParty/iresearch/tests/search/sort_tests.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1
2020-07-30T23:33:02.000Z
2020-07-30T23:33:02.000Z
3rdParty/iresearch/tests/search/sort_tests.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
null
null
null
3rdParty/iresearch/tests/search/sort_tests.cpp
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
1
2020-10-01T08:49:12.000Z
2020-10-01T08:49:12.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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 holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include "tests_shared.hpp" #include "analysis/token_attributes.hpp" #include "formats/empty_term_reader.hpp" #include "search/scorers.hpp" #include "search/score.hpp" #include "utils/misc.hpp" NS_LOCAL struct empty_attribute_provider : irs::attribute_provider { virtual irs::attribute* get_mutable(irs::type_info::type_id) { return nullptr; } }; empty_attribute_provider EMPTY_ATTRIBUTE_PROVIDER; template<size_t Size, size_t Align> struct aligned_value { irs::memory::aligned_storage<Size, Align> data; // need these operators only to be sort API compliant bool operator<(const aligned_value&) const noexcept { return false; } const aligned_value& operator+=(const aligned_value&) const noexcept { return *this; } const aligned_value& operator+(const aligned_value&) const noexcept { return *this; } }; template<typename ScoreType, typename StatsType> struct aligned_scorer : public irs::sort { class prepared final : public irs::prepared_sort_basic<ScoreType, StatsType> { public: explicit prepared(const irs::flags& features, bool empty_scorer) noexcept : features_(features), empty_scorer_(empty_scorer) { } virtual field_collector::ptr prepare_field_collector() const override { return nullptr; } virtual term_collector::ptr prepare_term_collector() const override { return nullptr; } virtual void collect( irs::byte_type*, const irs::index_reader&, const field_collector*, const term_collector* ) const override { // NOOP } virtual irs::score_function prepare_scorer( const irs::sub_reader& /*segment*/, const irs::term_reader& /*field*/, const irs::byte_type* /*stats*/, irs::byte_type* score_buf, const irs::attribute_provider& /*doc_attrs*/, irs::boost_t /*boost*/) const override { if (empty_scorer_) { return { nullptr, nullptr }; } struct ctx : public irs::score_ctx { ctx(const irs::byte_type* score_buf) : score_buf(score_buf) { } const irs::byte_type* score_buf; }; return { std::make_unique<ctx>(score_buf), [](irs::score_ctx* ctx) noexcept { return reinterpret_cast<struct ctx*>(ctx)->score_buf; } }; } virtual const irs::flags& features() const override { return features_; } irs::flags features_; bool empty_scorer_; }; static constexpr irs::string_ref type_name() noexcept { return __FILE__ ":" STRINGIFY(__LINE__); } static ptr make(const irs::flags& features = irs::flags::empty_instance(), bool empty_scorer = true) { return std::make_unique<aligned_scorer>(features, empty_scorer); } explicit aligned_scorer( const irs::flags& features = irs::flags::empty_instance(), bool empty_scorer = true) : irs::sort(irs::type<aligned_scorer>::get()), features_(features), empty_scorer_(empty_scorer) { } virtual irs::sort::prepared::ptr prepare() const override { return irs::memory::make_unique<aligned_scorer<ScoreType, StatsType>::prepared>( features_, empty_scorer_); } irs::flags features_; bool empty_scorer_; }; struct dummy_scorer0: public irs::sort { static constexpr irs::string_ref type_name() noexcept { return __FILE__ ":" STRINGIFY(__LINE__); } static ptr make() { return std::make_unique<dummy_scorer0>(); } dummy_scorer0(): irs::sort(irs::type<dummy_scorer0>::get()) { } virtual prepared::ptr prepare() const override { return nullptr; } }; NS_END TEST(sort_tests, order_equal) { struct dummy_scorer1: public irs::sort { static constexpr irs::string_ref type_name() noexcept { return __FILE__ ":" STRINGIFY(__LINE__); } static ptr make() { return std::make_unique<dummy_scorer1>(); } dummy_scorer1(): irs::sort(irs::type<dummy_scorer1>::get()) { } virtual prepared::ptr prepare() const override { return nullptr; } }; // empty == empty { irs::order ord0; irs::order ord1; ASSERT_TRUE(ord0 == ord1); ASSERT_FALSE(ord0 != ord1); } // empty == !empty { irs::order ord0; irs::order ord1; ord1.add<dummy_scorer1>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different sort types { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord1.add<dummy_scorer1>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different order same sort type { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord0.add<dummy_scorer1>(false); ord1.add<dummy_scorer1>(false); ord1.add<dummy_scorer0>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different number same sorts { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord1.add<dummy_scorer0>(false); ord1.add<dummy_scorer0>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // different number different sorts { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord1.add<dummy_scorer1>(false); ord1.add<dummy_scorer1>(false); ASSERT_FALSE(ord0 == ord1); ASSERT_TRUE(ord0 != ord1); } // same sorts same types { irs::order ord0; irs::order ord1; ord0.add<dummy_scorer0>(false); ord0.add<dummy_scorer1>(false); ord1.add<dummy_scorer0>(false); ord1.add<dummy_scorer1>(false); ASSERT_TRUE(ord0 == ord1); ASSERT_FALSE(ord0 != ord1); } } TEST(sort_tests, static_const) { ASSERT_TRUE(irs::order::unordered().empty()); ASSERT_TRUE(irs::order::prepared::unordered().empty()); } TEST(sort_tests, score_traits) { const size_t values[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; const size_t* ptrs[IRESEARCH_COUNTOF(values)]; std::iota(std::begin(ptrs), std::end(ptrs), values); irs::order_bucket bucket(aligned_scorer<size_t, size_t>().prepare(), 0, 0, true); for (size_t i = 0; i < IRESEARCH_COUNTOF(values); ++i) { size_t max_dst = 0; size_t aggregated_dst = 0; irs::score_traits<size_t>::bulk_aggregate( &bucket, reinterpret_cast<irs::byte_type*>(&aggregated_dst), reinterpret_cast<const irs::byte_type**>(ptrs), i); irs::score_traits<size_t>::bulk_max( &bucket, reinterpret_cast<irs::byte_type*>(&max_dst), reinterpret_cast<const irs::byte_type**>(ptrs), i); const auto begin = std::begin(values); const auto end = begin + i; ASSERT_EQ(std::accumulate(begin, end, 0), aggregated_dst); const auto it = std::max_element(begin, end); ASSERT_EQ(end == it ? 0 : *it, max_dst); } } TEST(sort_tests, merge_func) { aligned_scorer<size_t, size_t> scorer; auto prepared = scorer.prepare(); ASSERT_NE(nullptr, prepared); ASSERT_EQ(prepared->aggregate_func(), irs::sort::prepared::merge_func<irs::sort::MergeType::AGGREGATE>(*prepared)); ASSERT_EQ(&irs::score_traits<size_t>::aggregate, prepared->aggregate_func()); ASSERT_EQ(prepared->max_func(), irs::sort::prepared::merge_func<irs::sort::MergeType::MAX>(*prepared)); ASSERT_EQ(&irs::score_traits<size_t>::max, prepared->max_func()); // ensure order optimizes single scorer cases { irs::order ord; ord.add<aligned_scorer<size_t, size_t>>(true); auto prepared_order = ord.prepare(); ASSERT_FALSE(prepared_order.empty()); ASSERT_EQ(prepared_order.prepare_merger(irs::sort::MergeType::AGGREGATE), prepared->aggregate_func()); ASSERT_EQ(prepared_order.prepare_merger(irs::sort::MergeType::MAX), prepared->max_func()); } } TEST(sort_tests, prepare_order) { { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 4>, aligned_value<1, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(1, prepared.size()); ASSERT_EQ(4, prepared.score_size()); ASSERT_EQ(4, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-1 { 2, 2 }, // score: 2-3 { 4, 4 }, // score: 4-7 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); // returns valid scorers ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-1 { 2, 2 }, // score: 2-3 { 4, 4 }, // score: 4-7 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(1 == scorers.size()); auto& scorer = scorers.front(); ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[0], scorer.bucket); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); // returns valid scorer ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-1 { 2, 2 }, // score: 2-3 { 4, 4 }, // score: 4-7 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(1 == scorers.size()); auto& scorer = scorers.front(); ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[1], scorer.bucket); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0 { 1, 1 }, // score: 1-1 { 2, 2 } // score: 2-2 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(3, prepared.score_size()); ASSERT_EQ(3, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true, irs::flags::empty_instance(), false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); ord.add<dummy_scorer0>(false); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0, padding: 1-1 { 2, 2 } // score: 2-3 }; auto prepared = ord.prepare(); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_EQ(2, prepared.size()); ASSERT_EQ(4, prepared.score_size()); ASSERT_EQ(4, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(2 == scorers.size()); auto& front = scorers.front(); ASSERT_NE(nullptr, front.func()); ASSERT_EQ(&prepared[0], front.bucket); auto& back = scorers.back(); ASSERT_NE(nullptr, back.func()); ASSERT_EQ(&prepared[1], back.bucket); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(true, irs::flags::empty_instance(), false); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(true, irs::flags::empty_instance(), false); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(true, irs::flags::empty_instance(), false); auto prepared = ord.prepare(); ASSERT_EQ(irs::flags::empty_instance(), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(8, prepared.score_size()); ASSERT_EQ(8, prepared.stats_size()); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0, padding: 1-1 { 2, 2 }, // score: 2-3 { 4, 4 } // score: 4-7 }; auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_TRUE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(3 == scorers.size()); { auto& scorer = scorers[0]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[0], scorer.bucket); } { auto& scorer = scorers[1]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[1], scorer.bucket); } { auto& scorer = scorers[2]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[2], scorer.bucket); } irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::document>::get()}, false); ord.add<aligned_scorer<aligned_value<5, 4>, aligned_value<5, 4>>>(false); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::frequency>::get()}, false); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-0, padding: 1-3 { 4, 4 }, // score: 4-8, padding: 9-11 { 12, 12 } // score: 12-14 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(3, prepared.size()); ASSERT_EQ(16, prepared.score_size()); ASSERT_EQ(16, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(2 == scorers.size()); { auto& scorer = scorers[0]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[0], scorer.bucket); } { auto& scorer = scorers[1]; ASSERT_NE(nullptr, scorer.func()); ASSERT_EQ(&prepared[2], scorer.bucket); } irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_FALSE(score.is_default()); ASSERT_EQ(score_buf.c_str(), score.evaluate()); // returns pointer to the beginning of score_buf } { irs::order ord; ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<3, 1>, aligned_value<3, 1>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<7, 4>, aligned_value<7, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<dummy_scorer0>(false); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<dummy_scorer0>(false); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-2, padding: 3-7 { 8, 8 }, // score: 8-34, padding: 35-39 { 40, 40 }, // score: 40-46, padding: 47-47 { 48, 48 }, // score: 48-48 { 49, 49 } // score: 49-49 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(56, prepared.score_size()); ASSERT_EQ(56, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<3, 1>, aligned_value<3, 1>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<7, 4>, aligned_value<7, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-34, padding: 34-35 { 36, 36 }, // score: 36-42, padding: 43-43 { 44, 44 }, // score: 44-44 { 45, 45 } // score: 45-45 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(48, prepared.score_size()); ASSERT_EQ(48, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<7, 4>, aligned_value<7, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<3, 1>, aligned_value<3, 1>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-38, padding: 39-39 { 40, 40 }, // score: 40-42 { 43, 43 }, // score: 43-43 { 44, 44 } // score: 44-44 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(48, prepared.score_size()); ASSERT_EQ(48, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-33, padding: 34-35 { 36, 36 }, // score: 36-39 { 40, 40 }, // score: 40-40 { 41, 41 } // score: 41-41 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(48, prepared.score_size()); ASSERT_EQ(48, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-35 { 36, 36 }, // score: 36-37 { 38, 38 }, // score: 38-38 { 39, 39 } // score: 39-39 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(40, prepared.score_size()); ASSERT_EQ(40, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } { irs::order ord; ord.add<aligned_scorer<aligned_value<27, 8>, aligned_value<27, 8>>>(false); ord.add<aligned_scorer<aligned_value<4, 4>, aligned_value<4, 4>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<2, 2>, aligned_value<2, 2>>>(false, irs::flags{irs::type<irs::document>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); ord.add<aligned_scorer<aligned_value<1, 1>, aligned_value<1, 1>>>(false, irs::flags{irs::type<irs::frequency>::get()}); // first - score offset // second - stats offset const std::vector<std::pair<size_t, size_t>> expected_offsets { { 0, 0 }, // score: 0-26, padding: 27-31 { 32, 32 }, // score: 32-35 { 36, 36 }, // score: 36-37 { 38, 38 }, // score: 38-38 { 39, 39 } // score: 39-39 }; auto prepared = ord.prepare(); ASSERT_EQ(irs::flags({ irs::type<irs::document>::get(), irs::type<irs::frequency>::get() }), prepared.features()); ASSERT_FALSE(prepared.empty()); ASSERT_EQ(5, prepared.size()); ASSERT_EQ(40, prepared.score_size()); ASSERT_EQ(40, prepared.stats_size()); auto expected_offset = expected_offsets.begin(); for (auto& bucket : prepared) { ASSERT_NE(nullptr, bucket.bucket); ASSERT_EQ(expected_offset->first, bucket.score_offset); ASSERT_EQ(expected_offset->second, bucket.stats_offset); ASSERT_FALSE(bucket.reverse); ++expected_offset; } ASSERT_EQ(expected_offset, expected_offsets.end()); irs::bstring stats_buf(prepared.stats_size(), 0); irs::bstring score_buf(prepared.score_size(), 0); irs::order::prepared::scorers scorers( prepared, irs::sub_reader::empty(), irs::empty_term_reader(0), stats_buf.c_str(), const_cast<irs::byte_type*>(score_buf.c_str()), EMPTY_ATTRIBUTE_PROVIDER, irs::no_boost()); ASSERT_TRUE(0 == scorers.size()); irs::score score; ASSERT_TRUE(score.is_default()); irs::reset(score, std::move(scorers)); ASSERT_TRUE(score.is_default()); } } TEST(score_function_test, construct) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; }; { irs::score_function func; ASSERT_TRUE(func); ASSERT_NE(nullptr, func.func()); ASSERT_EQ(nullptr, func.ctx()); ASSERT_EQ(nullptr, func()); } { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); } { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func( irs::memory::to_managed<irs::score_ctx, false>(&ctx), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 42; return buf; }; irs::score_function func(std::make_unique<struct ctx>(), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(42, *value); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 42; return buf; }; irs::score_function func( irs::memory::to_managed<irs::score_ctx>(std::make_unique<struct ctx>()), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(42, *value); } } TEST(score_function_test, reset) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; }; irs::score_function func; ASSERT_TRUE(func); ASSERT_NE(nullptr, func.func()); ASSERT_EQ(nullptr, func.ctx()); ASSERT_EQ(nullptr, func()); { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; func.reset(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); func.reset( irs::memory::to_managed<irs::score_ctx, false>(&ctx), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(ctx.buf, func()); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 42; return buf; }; func.reset(std::make_unique<struct ctx>(), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(42, *value); } { auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { auto* buf = static_cast<struct ctx*>(ctx)->buf; buf[0] = 43; return buf; }; func.reset( irs::memory::to_managed<irs::score_ctx>(std::make_unique<struct ctx>()), score_func); ASSERT_TRUE(func); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_NE(nullptr, func.ctx()); auto* value = func(); ASSERT_NE(nullptr, value); ASSERT_EQ(43, *value); } { struct ctx ctx; func.reset(&ctx, nullptr); ASSERT_FALSE(func); } } TEST(score_function_test, move) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; }; // move construction { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(ctx.buf, func()); irs::score_function moved(std::move(func)); ASSERT_TRUE(moved); ASSERT_EQ(&ctx, moved.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), moved.func()); ASSERT_EQ(ctx.buf, moved()); ASSERT_TRUE(func); ASSERT_EQ(nullptr, func.ctx()); ASSERT_NE(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(nullptr, func()); } // move assignment { struct ctx ctx; auto score_func = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function moved; ASSERT_TRUE(moved); ASSERT_EQ(nullptr, moved.ctx()); ASSERT_NE(static_cast<irs::score_f>(score_func), moved.func()); ASSERT_EQ(nullptr, moved()); irs::score_function func(&ctx, score_func); ASSERT_TRUE(func); ASSERT_EQ(&ctx, func.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(ctx.buf, func()); moved = std::move(func); ASSERT_TRUE(moved); ASSERT_EQ(&ctx, moved.ctx()); ASSERT_EQ(static_cast<irs::score_f>(score_func), moved.func()); ASSERT_EQ(ctx.buf, moved()); ASSERT_TRUE(func); ASSERT_EQ(nullptr, func.ctx()); ASSERT_NE(static_cast<irs::score_f>(score_func), func.func()); ASSERT_EQ(nullptr, func()); } } TEST(score_function_test, equality) { struct ctx : irs::score_ctx { irs::byte_type buf[1]{}; } ctx0, ctx1; auto score_func0 = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; auto score_func1 = [](irs::score_ctx* ctx) -> const irs::byte_type* { return static_cast<struct ctx*>(ctx)->buf; }; irs::score_function func0; irs::score_function func1(&ctx0, score_func0); irs::score_function func2(&ctx1, score_func1); irs::score_function func3(&ctx0, score_func1); irs::score_function func4(&ctx1, score_func0); ASSERT_EQ(func0, irs::score_function()); ASSERT_NE(func0, func1); ASSERT_NE(func2, func3); ASSERT_NE(func2, func4); ASSERT_EQ(func1, irs::score_function(&ctx0, score_func0)); ASSERT_EQ(func2, irs::score_function(&ctx1, score_func1)); }
34.956731
138
0.650667
rajeev02101987
92e010291c2ea4a5cc83c09327e575f3bde61fe4
627
cpp
C++
1128_N_Queens_Puzzle/1128_N_Queens_Puzzle/1128_N_Queens_Puzzle.cpp
Iluvata/PAT-Advanced-Level-Practice
08a02e82eef30c81ed9ef8e4f327f7b2a9535582
[ "MIT" ]
2
2020-10-17T12:26:42.000Z
2021-11-12T08:47:10.000Z
1128_N_Queens_Puzzle/1128_N_Queens_Puzzle/1128_N_Queens_Puzzle.cpp
Iluvata/PAT-Advanced-Level-Practice
08a02e82eef30c81ed9ef8e4f327f7b2a9535582
[ "MIT" ]
1
2020-10-19T11:31:55.000Z
2020-10-19T11:31:55.000Z
1128_N_Queens_Puzzle/1128_N_Queens_Puzzle/1128_N_Queens_Puzzle.cpp
Iluvata/PAT-Advanced-Level-Practice
08a02e82eef30c81ed9ef8e4f327f7b2a9535582
[ "MIT" ]
1
2020-10-18T01:08:34.000Z
2020-10-18T01:08:34.000Z
// 1128_N_Queens_Puzzle.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include <vector> #include <cmath> #include <map> using namespace std; int main() { int k, n; cin >> k; for (int i = 0; i < k; ++i) { cin >> n; vector<bool> row(n + 1, false); map<int, bool> diagsum; map<int, bool> diagdel; int p; bool flag = true; for (int j = 1; j <= n; ++j) { cin >> p; if (row[p] || diagsum[j + p] || diagdel[j - p]) flag = false; row[p] = diagsum[j + p] = diagdel[j - p] = true; } if (flag) { cout << "YES" << endl; } else { cout << "NO" << endl; } } }
16.945946
61
0.527911
Iluvata
2baf016f451c314c8757506b9861d33fd0efd790
34,785
cpp
C++
aoiduino/esp-esp8266.cpp
gunjouinc/Aoiduino
f2b954010672d60bec69d6019cd1e77a14d21046
[ "MIT" ]
null
null
null
aoiduino/esp-esp8266.cpp
gunjouinc/Aoiduino
f2b954010672d60bec69d6019cd1e77a14d21046
[ "MIT" ]
null
null
null
aoiduino/esp-esp8266.cpp
gunjouinc/Aoiduino
f2b954010672d60bec69d6019cd1e77a14d21046
[ "MIT" ]
null
null
null
/****************************************************************************** ** ** Copyright 2009-2020 Gunjou Inc. All rights reserved. ** Contact: Gunjou Inc. (information@gunjou.co.jp) ** ** This software is released under the MIT License. ** https://github.com/gunjouinc/Aoiduino/blob/master/LICENSE ** ******************************************************************************/ #ifdef ESP8266 /** Esp WiFi timeout */ #define ESP_WIFI_TIMEOUT 30000 #include "esp-esp8266.h" /* Flash */ #include <FS.h> FS *EspStorage = &SPIFFS; /* RTC */ #include <time.h> /* Servo */ #include <Servo.h> /* Ticker */ #include <Ticker.h> Ticker ticker; Ticker watchdog; uint32_t watchdogSecond = 0; uint32_t watchdogMills = 0; /* WiFi */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <WiFiClientSecure.h> WiFiClient wifiClient; WiFiClientSecure wifiClientSecure; /** File mode - append */ #define _FILE_APPEND_ "a" /** File mode - read */ #define _FILE_READ_ "r" /** File mode - write */ #define _FILE_WRITE_ "w" /** Flash root path */ #define _FLASH_ "/mnt/spif" /** * @namespace AoiEsp * @brief Aoi esp classes. */ namespace AoiEsp { // Static variables. AoiBase::FunctionTable *Esp8266::m_functionTable = 0; Servo *Esp8266::m_servo = 0; int Esp8266::m_servoCount = 0; /** * @fn Esp8266::Esp8266( void ) * * Constructor. Member variables are initialized. */ Esp8266::Esp8266( void ) { if( m_functionTable ) return; // Sets function table, If there is no instance. AoiBase::FunctionTable ftl[] = { // ^ Please set your function to use. /* Arduino Core */ { "analogRead", &Arduino::analogRead }, { "analogWrite", &Arduino::analogWrite }, { "delay", &Arduino::delay }, { "delayMicroseconds", &Arduino::delayMicroseconds }, { "digitalRead", &Arduino::digitalRead }, { "digitalWrite", &Arduino::digitalWrite }, { "echo", &Arduino::echo }, { "micros", &Arduino::micros }, { "millis", &Arduino::millis }, { "noTone", &Arduino::noTone }, { "pinMode", &Arduino::pinMode }, { "tone", &Arduino::tone }, { "yield", &Arduino::yield }, /* File */ { ">", &Esp8266::create }, { ">>", &Esp8266::append }, { "cat", &Esp8266::read }, { "cd", &Esp8266::cd }, { "format", &Esp8266::format }, { "ll", &Esp8266::ll }, { "mkdir", &Esp8266::mkdir }, { "pwd", &Esp8266::pwd }, { "rm", &Esp8266::remove }, { "rmdir", &Esp8266::rmdir }, { "touch", &Esp8266::touch }, /* LowPower */ { "deepSleep", &Esp8266::deepSleep }, { "dmesg", &Esp8266::dmesg }, { "reboot", &Esp8266::restart }, /* HTTP */ { "httpBegin", &Esp8266::httpBegin }, { "httpGet", &AoiUtil::Http::httpGet }, { "httpPost", &Esp8266::httpPost }, /* RTC */ { "date", &Esp8266::date }, /* Servo */ { "servoAttach", &Esp8266::servoAttach }, { "servoBegin", &Esp8266::servoBegin }, { "servoEnd", &Esp8266::servoEnd }, { "servoWriteMicroseconds", &Esp8266::servoWriteMicroseconds }, /* Watchdog */ { "watchdogBegin", &Esp8266::watchdogBegin }, { "watchdogEnd", &Esp8266::watchdogEnd }, { "watchdogKick", &Esp8266::watchdogKick }, { "watchdogTimeleft", &Esp8266::watchdogTimeleft }, /* WiFi */ { "ifconfig", &Esp8266::ifConfig }, { "iwlist", &Esp8266::wifiScanNetworks }, { "wifiBegin", &Esp8266::wifiBegin }, { "wifiEnd", &Esp8266::wifiEnd }, { "wifiRtc", &Esp8266::wifiRtc }, // $ Please set your function to use. { "", 0 } }; // Creates function table to avoid kernel panic. uint8_t c = sizeof(ftl) / sizeof(AoiBase::FunctionTable); m_functionTable = Arduino::functionTable( ftl, c ); // Initalize library /* File */ SPIFFS.begin(); /* HTTP */ http = &wifiClient; } /** * @fn Esp8266::~Esp8266( void ) * * Destructor. Member variables are deleted. */ Esp8266::~Esp8266( void ) { } /** * @fn String Esp8266::className( void ) * * @see bool AbstractBase::className( void ) */ String Esp8266::className( void ) { return String( "Esp8266" ); } /** * @fn bool Esp8266::isExist( const String &function ) * * @see bool AbstractBase::isExist( const String &function ) */ bool Esp8266::isExist( const String &function ) { return Arduino::isExist( function, m_functionTable ); } /** * @fn String Esp8266::practice( StringList *args ) * * @see String AbstractBase::practice( StringList *args ) */ String Esp8266::practice( StringList *args ) { return Arduino::practice( args, m_functionTable ); } /** * @fn String Esp8266::usages( void ) * * @see String AbstractBase::usages( void ) */ String Esp8266::usages( void ) { return Arduino::usages( m_functionTable ); } /** * @fn StringList* Esp8266::rcScript( const String &index ) * * @see StringList* AbstractBase::rcScript( const String &index ) */ StringList* Esp8266::rcScript( const String &index ) { StringList *sl = 0; String s = appendRootPath( index ); if( !EspStorage->exists(s) ) return sl; File f = EspStorage->open( s, _FILE_READ_ ); if( f ) { String s = f.readString(); f.close(); sl = split( s, String(_lf) ); } return sl; } /** * @fn String Esp8266::append( StringList *args ) * * Append value on current device. * * @param[in] args Reference to arguments. * @return value string. */ String Esp8266::append( StringList *args ) { String s, t; int c = count( args ); if( c<2 ) s = usage( ">> file .+" ); else { t = appendRootPath( _a(0) ); // Create file if need if( !EspStorage->exists(t) ) { File w = EspStorage->open( t, _FILE_WRITE_ ); w.close(); } File f = EspStorage->open( t, _FILE_APPEND_ ); if( 0<f.size() ) f.print( _lf ); for( int i=1; i<c; i++ ) { if( 1<i ) f.print( STR_SPACE ); f.print( _a(i) ); } f.close(); // Re-open, Can't practice f.seek( 0 ) f = EspStorage->open( t, _FILE_READ_ ); s = prettyPrintTo( "value", f.readString() ); f.close(); } return s; } /** * @fn String Esp8266::cd( StringList *args ) * * Change device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::cd( StringList *args ) { String s; String path; switch( count(args) ) { case 1: path = _a( 0 ); if( (path==_FLASH_) || (path=="/") ) EspStorage = &SPIFFS; else s = cd( 0 ); break; default: s = usage( "cd ("+String(_FLASH_)+")" ); break; } return s; } /** * @fn String Esp8266::create( StringList *args ) * * Create value on current device. * * @param[in] args Reference to arguments. * @return value string. */ String Esp8266::create( StringList *args ) { String s, t; int c = count( args ); if( c<2 ) s = usage( "> file .+" ); else { t = appendRootPath( _a(0) ); if( EspStorage->exists(t) ) EspStorage->remove( t ); s = append( args ); } return s; } /** * @fn String Esp8266::format( StringList *args ) * * Format file device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::format( StringList *args ) { String s; String path; switch( count(args) ) { case 1: path = _a( 0 ); if( path==_FLASH_ ) SPIFFS.format(); else s = format( 0 ); break; default: s = usage( "format ("+String(_FLASH_)+")" ); break; } return s; } /** * @fn String Esp8266::ll( StringList *args ) * * Return file detail list in current device. * * @param[in] args Reference to arguments. * @return Current device. */ String Esp8266::ll( StringList *args ) { String s, p, root; DynamicJsonBuffer json; JsonArray &r = json.createArray(); Dir d; File f; switch( count(args) ) { case 1: root = _a( 0 ); case 0: // Root path root = appendRootPath( root ); d = EspStorage->openDir( root ); p = root; // File info to JSON while( d.next() ) { File f = d.openFile( "r" ); JsonObject &o = r.createNestedObject(); o[ "type" ] = f.isDirectory() ? "d" : "-"; o[ "name" ] = String(f.name()).substring( p.length() ); o[ "size" ] = f.size(); f.close(); } s = ""; r.prettyPrintTo( s ); break; default: s = usage( "ll (path)?" ); break; } return s; } /** * @fn String Esp8266::mkdir( StringList *args ) * * Make directory on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::mkdir( StringList *args ) { String s, t; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( EspStorage->exists(t) ) s = mkdir( 0 ); else EspStorage->mkdir( t ); break; default: s = usage( "mkdir path" ); break; } return s; } /** * @fn String Esp8266::pwd( StringList *args ) * * Return current device. * * @param[in] args Reference to arguments. * @return Current device. */ String Esp8266::pwd( StringList *args ) { String s; switch( count(args) ) { case 0: s = prettyPrintTo( "value" , _FLASH_ ); break; default: s = usage( "pwd" ); break; } return s; } /** * @fn String Esp8266::read( StringList *args ) * * Return file content on current device. * * @param[in] args Reference to arguments. * @return File content. */ String Esp8266::read( StringList *args ) { String s, t; File f; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( !EspStorage->exists(t) ) s = read( 0 ); else { f = EspStorage->open( t, _FILE_READ_ ); if( f ) { s = prettyPrintTo( "value" , f.readString() ); f.close(); } } break; default: s = usage( "cat file" ); break; } return s; } /** * @fn String Esp8266::remove( StringList *args ) * * Remove file on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::remove( StringList *args ) { String s, t; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( !EspStorage->exists(t) ) s = remove( 0 ); else EspStorage->remove( t ); break; default: s = usage( "rm file" ); break; } return s; } /** * @fn String Esp8266::rmdir( StringList *args ) * * Remove directory on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::rmdir( StringList *args ) { String s, t; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); if( !EspStorage->exists(t) ) s = rmdir( 0 ); else EspStorage->rmdir( t ); break; default: s = usage( "rmdir path" ); break; } return s; } /** * @fn String Esp8266::httpBegin( StringList *args ) * * Initalize https certs. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::httpBegin( StringList *args ) { String s, t; File rc, cc, pk; switch( count(args) ) { case 0: http = &wifiClient; break; case 3: http = &wifiClientSecure; // RootCA rc = EspStorage->open( appendRootPath(_a(0)), _FILE_READ_ ); t = rc.readString(); wifiClientSecure.setCACert( (uint8_t*)t.c_str(), t.length() ); rc.close(); // Client certificate cc = EspStorage->open( appendRootPath(_a(1)), _FILE_READ_ ); t = cc.readString(); wifiClientSecure.setCertificate( (uint8_t*)t.c_str(), t.length() ); cc.close(); // Client private key pk = EspStorage->open( appendRootPath(_a(2)), _FILE_READ_ ); t = pk.readString(); wifiClientSecure.setPrivateKey( (uint8_t*)t.c_str(), t.length() ); pk.close(); break; default: s = usage( "httpBegin CACert Certificate PrivateKey" ); break; } return s; } /** * @fn String Esp8266::httpPost( StringList *args ) * * Send HTTP POST to server. * * @param[in] args Reference to arguments. * @return Recieved content. */ String Esp8266::httpPost( StringList *args ) { String s, t, header, footer; File f; int size = 0; String host; int port = 80; int timeout = 30 * 1000; uint8_t *buf = 0; switch( count(args) ) { case 5: timeout = _atoi( 4 ) * 1000; case 4: port = _atoi( 3 ); case 3: t = appendRootPath( _a(2) ); if( !EspStorage->exists(t) ) return AoiUtil::Http::httpPost( args ); // Request body header = requestBodyHeaderInPut( STR_BOUNDARY, STR_AOIDUINO, t, &size ); footer = requestBodyFooterInPut( STR_BOUNDARY ); size += header.length() + footer.length(); // POST host = _a( 0 ); if( !http->connect(host.c_str(),port) ) return httpPost( 0 ); http->println( "POST "+_a(1)+" HTTP/1.0" ); http->println( "Host: " + host ); http->println( "User-Agent: " + String(STR_USER_AGENT) ); http->print( "Content-Type: multipart/form-data; " ); http->println( "boundary=\""+String(STR_BOUNDARY)+"\"" ); http->println( "Content-Length: "+String(size) ); http->println( "Connection: close" ); http->println(); http->print( header ); // Upload file f = EspStorage->open( t, _FILE_READ_ ); buf = new uint8_t[ _AOIUTIL_HTTP_BUFFER_SIZE_ ]; while( f.available() ) { size = f.read( buf, _AOIUTIL_HTTP_BUFFER_SIZE_ ); http->write( buf, size ); } delete [] buf; f.close(); http->print( footer ); // Response s = response( timeout ); s = prettyPrintTo( "value", s ); break; default: s = usage( "httpPost host path (file|text) (port timeout)?" ); break; } return s; } /** * @fn String Esp8266::touch( StringList *args ) * * Create empty file on current device. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::touch( StringList *args ) { String s, t; File f; switch( count(args) ) { case 1: t = appendRootPath( _a(0) ); f = EspStorage->open( t, _FILE_WRITE_ ); if( f ) f.close(); break; default: s = usage( "touch file" ); break; } return s; } /** * @fn String Esp8266::deepSleep( StringList *args ) * * Enter the deep sleep state. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::deepSleep( StringList *args ) { String s; RFMode mode; switch( count(args) ) { case 0: ESP.deepSleep( 0 ); break; case 1: // Micro second. mode = WAKE_RF_DEFAULT; ESP.deepSleep( _atoi(0) * 1000 * 1000, mode ); break; default: s = usage( "deepSleep [0-9]*" ); break; } return s; } /** * @fn String Esp8266::dmesg( StringList *args ) * * Returns system information. * * @param[in] args Reference to arguments. * @return System information. */ String Esp8266::dmesg( StringList *args ) { String s; DynamicJsonBuffer json; JsonObject &r = json.createObject(); switch( count(args) ) { case 0: r[ "chipId" ] = String( ESP.getChipId(), HEX ); r[ "coreVersion" ] = ESP.getCoreVersion(); r[ "cpuFreqMHz" ] = ESP.getCpuFreqMHz(); r[ "flashChipId" ] = String( ESP.getFlashChipId(), HEX ); r[ "flashChipSize" ] = ESP.getFlashChipSize(); r[ "freeHeap" ] = ESP.getFreeHeap(); r[ "freeSketchSpace" ] = ESP.getFreeSketchSpace(); r[ "resetReason" ] = ESP.getResetReason(); r[ "sdkVersion" ] = ESP.getSdkVersion(); r[ "sketchSize" ] = ESP.getSketchSize(); r.prettyPrintTo( s ); break; default: s = usage( "dmesg" ); break; } return s; } /** * @fn String Esp8266::restart( StringList *args ) * * Reboot the system. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::restart( StringList *args ) { String s; switch( count(args) ) { case 0: ESP.restart(); break; case 1: ticker.once_ms( _atoi(0), reboot ); break; default: s = usage( "reboot ([0-9]+)" ); break; } return s; } /** * @fn String Esp8266::date( StringList *args ) * * Print date. * * @param[in] args Reference to arguments. * @return date string. */ String Esp8266::date( StringList *args ) { String s; uint8_t size = 20; char *buf = NULL; time_t t; struct tm *rtc; struct timeval tv; switch( count(args) ) { case 0: t = time( NULL ); rtc = localtime( &t ); buf = new char[ size ]; snprintf( buf, size, "%04d-%02d-%02dT%02d:%02d:%02d", rtc->tm_year+1900, rtc->tm_mon+1, rtc->tm_mday, rtc->tm_hour, rtc->tm_min, rtc->tm_sec ); s = prettyPrintTo( "value", buf ); delete [] buf; break; case 1: tv.tv_sec = _atoul( 0 ); settimeofday( &tv, NULL ); break; default: s = usage( "date (unixtime)?" ); break; } return s; } /** * @fn String Esp8266::servoAttach( StringList *args ) * * Attach the Servo variable to a pin. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoAttach( StringList *args ) { String s; switch( count(args) ) { case 1: ( m_servo+0 )->attach( _atoi(0) ); break; case 2: ( m_servo+_atoi(1) )->attach( _atoi(0) ); break; default: s = usage( "servoAttach pin ([0-(count-1)])" ); break; } return s; } /** * @fn String Esp8266::servoBegin( StringList *args ) * * Initialize the servo using count. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoBegin( StringList *args ) { String s; StringList sl; switch( count(args) ) { case 1: servoEnd( &sl ); m_servoCount = _atoi( 0 ); m_servo = new Servo[ m_servoCount ]; break; default: s = usage( "servoBegin count" ); break; } return s; } /** * @fn String Esp8266::servoEnd( StringList *args ) * * Detach the all Servo variable from its pin. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoEnd( StringList *args ) { String s; switch( count(args) ) { case 0: if( m_servo ) { for( int i=0; i<m_servoCount; i++ ) (m_servo+i)->detach(); delete [] m_servo; } m_servo = 0; m_servoCount = 0; break; default: s = usage( "servoEnd" ); break; } return s; } /** * @fn String Esp8266::servoWriteMicroseconds( StringList *args ) * * Set microseconds to servo using pin number. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::servoWriteMicroseconds( StringList *args ) { String s; switch( count(args) ) { case 1: ( m_servo+0 )->writeMicroseconds( _atoi(0) ); break; case 2: ( m_servo+_atoi(1) )->writeMicroseconds( _atoi(0) ); break; default: s = usage( "servoWriteMicroseconds micros ([0-(count-1)])" ); break; } return s; } /** * @fn String Esp8266::watchdogBegin( StringList *args ) * * Initialize the Watchdog and start to check timer(mesc). * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::watchdogBegin( StringList *args ) { String s; switch( count(args) ) { case 1: watchdog.once_ms( _atoi(0), reboot ); watchdogSecond = _atoi(0); watchdogMills = ::millis(); break; default: s = usage( "watchdogBegin [0-9]+" ); break; } return s; } /** * @fn String Esp8266::watchdogEnd( StringList *args ) * * Stop to check timer for avoid bite watchdog. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::watchdogEnd( StringList *args ) { String s; switch( count(args) ) { case 0: watchdog.detach(); watchdogSecond = 0; watchdogMills = 0; break; default: s = usage( "watchdogEnd" ); break; } return s; } /** * @fn String Ast::watchdogKick( StringList *args ) * * Kick to watchdog for notify keep alive. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::watchdogKick( StringList *args ) { String s; switch( count(args) ) { case 0: watchdog.detach(); watchdog.once_ms( watchdogSecond, reboot ); watchdogMills = ::millis(); break; default: s = usage( "watchdogKick" ); break; } return s; } /** * @fn String Esp8266::watchdogTimeleft( StringList *args ) * * Get a remain time for bite watchdog. * * @param[in] args Reference to arguments. * @return Remain time to expire timeout(mesc). */ String Esp8266::watchdogTimeleft( StringList *args ) { String s; uint32_t i = 0; switch( count(args) ) { case 0: i = watchdogSecond - (::millis()-watchdogMills); s = prettyPrintTo( "value" , i ); break; default: s = usage( "watchdogTimeleft" ); break; } return s; } /** * @fn String Esp8266::ifConfig( StringList *args ) * * Show network information. * * @param[in] args Reference to arguments. * @return Network information. */ String Esp8266::ifConfig( StringList *args ) { String s; DynamicJsonBuffer json; JsonObject &r = json.createObject(); switch( count(args) ) { case 0: r[ "ipAddress" ] = WiFi.localIP().toString(); r[ "subnetMask" ] = WiFi.subnetMask().toString(); r[ "gatewayIp" ] = WiFi.gatewayIP().toString(); r[ "macAddress" ] = WiFi.macAddress(); r[ "dnsIP1" ] = WiFi.dnsIP( 0 ).toString(); r[ "dnsIP2" ] = WiFi.dnsIP( 1 ).toString(); r[ "softAP" ] = WiFi.softAPIP().toString(); r.prettyPrintTo( s ); break; default: s = usage( "ifconfig" ); break; } return s; } /** * @fn String Esp8266::wifiScanNetworks( StringList *args ) * * Scan wifi networks. * * @param[in] args Reference to arguments. * @return Returns SSID, RSSI and Encryption type. */ String Esp8266::wifiScanNetworks( StringList *args ) { String s; int i = 0; DynamicJsonBuffer json; JsonArray &r = json.createArray(); switch( count(args) ) { case 0: i = WiFi.scanNetworks(); if( !i ) s = STR_NO_NETWORKS_FOUND; else { for( int j=0; j<i; j++ ) { JsonObject &o = r.createNestedObject(); o[ "ssid" ] = WiFi.SSID( j ); o[ "rssi" ] = WiFi.RSSI( j ); // Sets encription type. String t = ""; switch( WiFi.encryptionType(j) ) { case 2: t = "TKIP(WPA)"; break; case 5: t = "WEP"; break; case 4: t = "CCMP(WPA)"; break; case 7: t = "None"; break; case 8: t = "Auto"; break; default: t = "Other"; break; } o[ "type" ] = t; } r.prettyPrintTo( s ); } break; default: s = usage( "iwlist" ); break; } return s; } /** * @fn String Esp8266::wifiBegin( StringList *args ) * * Connect to wireless network. * * @param[in] args Reference to arguments. * @return Wireless ip address, Otherwise error string. */ String Esp8266::wifiBegin( StringList *args ) { String s; unsigned long i = 0; switch( count(args) ) { case 2: // Start WiFi.disconnect(); WiFi.mode( WIFI_STA ); WiFi.begin( _a(0).c_str(), _a(1).c_str() ); // Waiting i = ::millis(); while( WiFi.status()!=WL_CONNECTED && (::millis()-i)<ESP_WIFI_TIMEOUT ) ::delay( 500 ); // Result if( WiFi.status()!=WL_CONNECTED ) s = STR_CANT_CONNECT_TO_WIRELESS_NETWORK; else { StringList sl; s = ifConfig( &sl ); } break; default: s = usage( "wifiBegin ssid password" ); break; } return s; } /** * @fn String Esp8266::wifiEnd( StringList *args ) * * Detach from wireless network. * * @param[in] args Reference to arguments. * @return Empty string. */ String Esp8266::wifiEnd( StringList *args ) { String s; switch( count(args) ) { case 0: if( WiFi.status()!=WL_CONNECTED ) s = wifiEnd( 0 ); else WiFi.disconnect(); break; default: s = usage( "wifiEnd" ); break; } return s; } /** * @fn String Esp8266::wifiRtc( StringList *args ) * * Get rtc from the WiFi network. * * @param[in] args Reference to arguments. * @return unixtime string. */ String Esp8266::wifiRtc( StringList *args ) { String s; time_t now; switch( count(args) ) { case 0: if( WiFi.status()!=WL_CONNECTED ) s = wifiRtc( 0 ); else { configTzTime( "JST-9", "ntp.nict.jp", "time.google.com", "ntp.jst.mfeed.ad.jp" ); time( &now ); s = String( now ); s = prettyPrintTo( "value", s ); } break; default: s = usage( "wifiRtc" ); break; } return s; } /** * @fn String Esp8266::appendRootPath( const String &path ) * * Append root path ("/") if need. * * @return Path include root. */ String Esp8266::appendRootPath( const String &path ) { String s = path; String r = "/"; if( s.indexOf(r) ) s = r + s; return s; } /** * @fn void Esp8266::reboot( void ) * * Reboot the system. */ void Esp8266::reboot( void ) { ESP.restart(); } /** * @fn String Esp8266::requestBodyHeaderInPut( const String &value ) * * Return request body header in HTTP PUT. * * @param[in] boundary Boundary string. * @param[in] name Content-Disposition: name attribute string. * @param[in] value Putted value. * @param[in/out] size Putted value size. If value is file, File size is used. * @return Request body header string in HTTP PUT. */ String Esp8266::requestBodyHeaderInPut( const String &boundary, const String &name, const String &value, int *size ) { String s; String t = appendRootPath( value ); // If file is exitst, use file size if( !EspStorage->exists(t) ) s = AoiUtil::Http::requestBodyHeaderInPut( boundary, name, value, size ); else { s += "--" + boundary + "\r\n"; s += "Content-Disposition: form-data; name=\"" + name + "\";"; s += " filename=\"" + value + "\"\r\n"; s += "Content-Type: application/octet-stream\r\n"; s += "Content-Transfer-Encoding: binary\r\n"; File f = EspStorage->open( t, _FILE_READ_ ); *size = f.size(); f.close(); s += "\r\n"; } return s; } } #endif
27.629071
120
0.43812
gunjouinc
2bb0e4b01eb05a6a8ba1ded0a5f2b6258a848804
2,487
cpp
C++
hw4/src/lib/sema/SymbolTable.cpp
idoleat/P-Language-Compiler-CourseProject
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
7
2020-09-10T16:54:49.000Z
2022-03-15T12:39:23.000Z
hw4/src/lib/sema/SymbolTable.cpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
hw4/src/lib/sema/SymbolTable.cpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
#include "sema/SemanticAnalyzer.hpp" /* std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, int attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); } std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, float attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); } std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, bool attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); }*/ std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::addSymbol(const char *name, int kind, uint32_t level, const char *type, const char *attribute){ dumpList.push_back(name); return insert(name, new SymbolEntry(name, kind, level, type, attribute)); } std::unordered_map<std::string, SemanticAnalyzer::SymbolEntry *>::iterator SemanticAnalyzer::SymbolTable::insert(const char *name, SymbolEntry *symbol){ return entries.insert(std::pair<std::string, SymbolEntry *>(std::string(name), symbol)).first; } void SemanticAnalyzer::SymbolTable::SetLevel(uint32_t lv){ level = lv; } uint32_t SemanticAnalyzer::SymbolTable::GetLevel(){ return level; } std::list<const char *>::iterator SemanticAnalyzer::SymbolTable::GetDumpListBegin(){ return dumpList.begin(); } std::list<const char *>::iterator SemanticAnalyzer::SymbolTable::GetDumpListEnd(){ return dumpList.end(); } int SemanticAnalyzer::SymbolTable::GetDumpListSize(){ return (int)dumpList.size(); } SemanticAnalyzer::SymbolEntry *SemanticAnalyzer::SymbolTable::lookup(const char *name){ std::unordered_map<std::string, SymbolEntry *>::iterator got = entries.find(std::string(name)); if(got != entries.end()) return (got->second); else return NULL; } bool SemanticAnalyzer::SymbolTable::EraseSymbol(const char *name){ int result = entries.erase(std::string(name)); dumpList.remove(std::string(name).c_str()); if(result > 0) return true; else return false; }
42.87931
201
0.741053
idoleat
2bb251b150d7c580d7b5451af22aa93e9d8bb7f1
10,234
cc
C++
net/disk_cache/v3/block_bitmaps.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/disk_cache/v3/block_bitmaps.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
net/disk_cache/v3/block_bitmaps.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/disk_cache/block_files.h" #include "base/atomicops.h" #include "base/file_util.h" #include "base/metrics/histogram.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/threading/thread_checker.h" #include "base/time.h" #include "net/disk_cache/cache_util.h" #include "net/disk_cache/file_lock.h" #include "net/disk_cache/trace.h" using base::TimeTicks; namespace disk_cache { BlockFiles::BlockFiles(const base::FilePath& path) : init_(false), zero_buffer_(NULL), path_(path) { } BlockFiles::~BlockFiles() { if (zero_buffer_) delete[] zero_buffer_; CloseFiles(); } bool BlockFiles::Init(bool create_files) { DCHECK(!init_); if (init_) return false; thread_checker_.reset(new base::ThreadChecker); block_files_.resize(kFirstAdditionalBlockFile); for (int i = 0; i < kFirstAdditionalBlockFile; i++) { if (create_files) if (!CreateBlockFile(i, static_cast<FileType>(i + 1), true)) return false; if (!OpenBlockFile(i)) return false; // Walk this chain of files removing empty ones. if (!RemoveEmptyFile(static_cast<FileType>(i + 1))) return false; } init_ = true; return true; } bool BlockFiles::CreateBlock(FileType block_type, int block_count, Addr* block_address) { DCHECK(thread_checker_->CalledOnValidThread()); if (block_type < RANKINGS || block_type > BLOCK_4K || block_count < 1 || block_count > 4) return false; if (!init_) return false; MappedFile* file = FileForNewBlock(block_type, block_count); if (!file) return false; ScopedFlush flush(file); BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); int target_size = 0; for (int i = block_count; i <= 4; i++) { if (header->empty[i - 1]) { target_size = i; break; } } DCHECK(target_size); int index; if (!CreateMapBlock(target_size, block_count, header, &index)) return false; Addr address(block_type, block_count, header->this_file, index); block_address->set_value(address.value()); Trace("CreateBlock 0x%x", address.value()); return true; } void BlockFiles::DeleteBlock(Addr address, bool deep) { DCHECK(thread_checker_->CalledOnValidThread()); if (!address.is_initialized() || address.is_separate_file()) return; if (!zero_buffer_) { zero_buffer_ = new char[Addr::BlockSizeForFileType(BLOCK_4K) * 4]; memset(zero_buffer_, 0, Addr::BlockSizeForFileType(BLOCK_4K) * 4); } MappedFile* file = GetFile(address); if (!file) return; Trace("DeleteBlock 0x%x", address.value()); size_t size = address.BlockSize() * address.num_blocks(); size_t offset = address.start_block() * address.BlockSize() + kBlockHeaderSize; if (deep) file->Write(zero_buffer_, size, offset); BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); DeleteMapBlock(address.start_block(), address.num_blocks(), header); file->Flush(); if (!header->num_entries) { // This file is now empty. Let's try to delete it. FileType type = Addr::RequiredFileType(header->entry_size); if (Addr::BlockSizeForFileType(RANKINGS) == header->entry_size) type = RANKINGS; RemoveEmptyFile(type); // Ignore failures. } } void BlockFiles::CloseFiles() { if (init_) { DCHECK(thread_checker_->CalledOnValidThread()); } init_ = false; for (unsigned int i = 0; i < block_files_.size(); i++) { if (block_files_[i]) { block_files_[i]->Release(); block_files_[i] = NULL; } } block_files_.clear(); } void BlockFiles::ReportStats() { DCHECK(thread_checker_->CalledOnValidThread()); int used_blocks[kFirstAdditionalBlockFile]; int load[kFirstAdditionalBlockFile]; for (int i = 0; i < kFirstAdditionalBlockFile; i++) { GetFileStats(i, &used_blocks[i], &load[i]); } UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_0", used_blocks[0]); UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_1", used_blocks[1]); UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_2", used_blocks[2]); UMA_HISTOGRAM_COUNTS("DiskCache.Blocks_3", used_blocks[3]); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_0", load[0], 101); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_1", load[1], 101); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_2", load[2], 101); UMA_HISTOGRAM_ENUMERATION("DiskCache.BlockLoad_3", load[3], 101); } bool BlockFiles::IsValid(Addr address) { #ifdef NDEBUG return true; #else if (!address.is_initialized() || address.is_separate_file()) return false; MappedFile* file = GetFile(address); if (!file) return false; BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); bool rv = UsedMapBlock(address.start_block(), address.num_blocks(), header); DCHECK(rv); static bool read_contents = false; if (read_contents) { scoped_ptr<char[]> buffer; buffer.reset(new char[Addr::BlockSizeForFileType(BLOCK_4K) * 4]); size_t size = address.BlockSize() * address.num_blocks(); size_t offset = address.start_block() * address.BlockSize() + kBlockHeaderSize; bool ok = file->Read(buffer.get(), size, offset); DCHECK(ok); } return rv; #endif } MappedFile* BlockFiles::GetFile(Addr address) { DCHECK(thread_checker_->CalledOnValidThread()); DCHECK(block_files_.size() >= 4); DCHECK(address.is_block_file() || !address.is_initialized()); if (!address.is_initialized()) return NULL; int file_index = address.FileNumber(); if (static_cast<unsigned int>(file_index) >= block_files_.size() || !block_files_[file_index]) { // We need to open the file if (!OpenBlockFile(file_index)) return NULL; } DCHECK(block_files_.size() >= static_cast<unsigned int>(file_index)); return block_files_[file_index]; } bool BlockFiles::GrowBlockFile(MappedFile* file, BlockFileHeader* header) { if (kMaxBlocks == header->max_entries) return false; ScopedFlush flush(file); DCHECK(!header->empty[3]); int new_size = header->max_entries + 1024; if (new_size > kMaxBlocks) new_size = kMaxBlocks; int new_size_bytes = new_size * header->entry_size + sizeof(*header); if (!file->SetLength(new_size_bytes)) { // Most likely we are trying to truncate the file, so the header is wrong. if (header->updating < 10 && !FixBlockFileHeader(file)) { // If we can't fix the file increase the lock guard so we'll pick it on // the next start and replace it. header->updating = 100; return false; } return (header->max_entries >= new_size); } FileLock lock(header); header->empty[3] = (new_size - header->max_entries) / 4; // 4 blocks entries header->max_entries = new_size; return true; } MappedFile* BlockFiles::FileForNewBlock(FileType block_type, int block_count) { COMPILE_ASSERT(RANKINGS == 1, invalid_file_type); MappedFile* file = block_files_[block_type - 1]; BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); TimeTicks start = TimeTicks::Now(); while (NeedToGrowBlockFile(header, block_count)) { if (kMaxBlocks == header->max_entries) { file = NextFile(file); if (!file) return NULL; header = reinterpret_cast<BlockFileHeader*>(file->buffer()); continue; } if (!GrowBlockFile(file, header)) return NULL; break; } HISTOGRAM_TIMES("DiskCache.GetFileForNewBlock", TimeTicks::Now() - start); return file; } // Note that we expect to be called outside of a FileLock... however, we cannot // DCHECK on header->updating because we may be fixing a crash. bool BlockFiles::FixBlockFileHeader(MappedFile* file) { ScopedFlush flush(file); BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(file->buffer()); int file_size = static_cast<int>(file->GetLength()); if (file_size < static_cast<int>(sizeof(*header))) return false; // file_size > 2GB is also an error. const int kMinBlockSize = 36; const int kMaxBlockSize = 4096; if (header->entry_size < kMinBlockSize || header->entry_size > kMaxBlockSize || header->num_entries < 0) return false; // Make sure that we survive crashes. header->updating = 1; int expected = header->entry_size * header->max_entries + sizeof(*header); if (file_size != expected) { int max_expected = header->entry_size * kMaxBlocks + sizeof(*header); if (file_size < expected || header->empty[3] || file_size > max_expected) { NOTREACHED(); LOG(ERROR) << "Unexpected file size"; return false; } // We were in the middle of growing the file. int num_entries = (file_size - sizeof(*header)) / header->entry_size; header->max_entries = num_entries; } FixAllocationCounters(header); int empty_blocks = EmptyBlocks(header); if (empty_blocks + header->num_entries > header->max_entries) header->num_entries = header->max_entries - empty_blocks; if (!ValidateCounters(header)) return false; header->updating = 0; return true; } // We are interested in the total number of blocks used by this file type, and // the max number of blocks that we can store (reported as the percentage of // used blocks). In order to find out the number of used blocks, we have to // substract the empty blocks from the total blocks for each file in the chain. void BlockFiles::GetFileStats(int index, int* used_count, int* load) { int max_blocks = 0; *used_count = 0; *load = 0; for (;;) { if (!block_files_[index] && !OpenBlockFile(index)) return; BlockFileHeader* header = reinterpret_cast<BlockFileHeader*>(block_files_[index]->buffer()); max_blocks += header->max_entries; int used = header->max_entries; for (int i = 0; i < 4; i++) { used -= header->empty[i] * (i + 1); DCHECK_GE(used, 0); } *used_count += used; if (!header->next_file) break; index = header->next_file; } if (max_blocks) *load = *used_count * 100 / max_blocks; } } // namespace disk_cache
30.732733
79
0.687317
pozdnyakov
2bb38f193fc366ae90906435b71efe731f765443
7,249
cpp
C++
Benchmarks/lud/lud_1_tiling/src/lud.cpp
LemonAndRabbit/rodinia-hls
097e8cf572a9ab04403c4eb0cfdb042f233f4aea
[ "BSD-2-Clause" ]
16
2020-12-28T15:07:53.000Z
2022-02-16T08:55:40.000Z
Benchmarks/lud/lud_1_tiling/src/lud.cpp
LemonAndRabbit/rodinia-hls
097e8cf572a9ab04403c4eb0cfdb042f233f4aea
[ "BSD-2-Clause" ]
null
null
null
Benchmarks/lud/lud_1_tiling/src/lud.cpp
LemonAndRabbit/rodinia-hls
097e8cf572a9ab04403c4eb0cfdb042f233f4aea
[ "BSD-2-Clause" ]
6
2020-12-28T07:33:08.000Z
2022-01-13T16:31:22.000Z
#include"lud.h" #include <iostream> //Elment with the block BSIZE, diagonal #define AA(i,j) result[(offset + i) * matrix_dim + j + offset] //Elment with global index #define BB(i,j) result[i * matrix_dim + j] using namespace std; extern "C"{ void diagonal_load(float* result, float* buffer, int offset){ int i, j; for(i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ buffer[i * BSIZE + j] = AA(i, j); } } } void diagonal_store(float* result, float* buffer, int offset){ int i, j; for(i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ AA(i, j) = buffer[i * BSIZE + j]; } } } void lud_diagonal(float* result, int offset) { int i, j, k; float buffer[BSIZE * BSIZE]; diagonal_load(result, buffer, offset); for (i = 0; i < BSIZE; i++){ top:for (j = i; j < BSIZE; j++){ for (k = 0; k < i; k++){ buffer[i * BSIZE + j] = buffer[i * BSIZE + j] - buffer[i * BSIZE + k]* buffer[k * BSIZE + j]; } } float temp = 1.f / buffer[i * BSIZE + i]; left:for (j = i + 1; j < BSIZE; j++){ for (k = 0; k < i; k++){ buffer[j * BSIZE + i]= buffer[j * BSIZE + i]- buffer[j * BSIZE + k] * buffer[k * BSIZE + i]; } buffer[j * BSIZE + i] = buffer[j * BSIZE + i] * temp; } } diagonal_store(result, buffer, offset); } void perimeter_load(float* result, float* top, float* left, int offset, int chunk_idx){ int i, j; int i_top = offset; int j_top = offset + BSIZE * (chunk_idx + 1); int i_left = offset + BSIZE * (chunk_idx + 1); int j_left = offset; for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ top[i * BSIZE + j] = BB((i_top + i), (j_top + j)); } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ left[i * BSIZE + j] = BB((i_left + i), (j_left + j)); } } } void perimeter_store(float* result, float* top, float* left, int offset, int chunk_idx){ int i, j; int i_top = offset; int j_top = offset + BSIZE * (chunk_idx + 1); int i_left = offset + BSIZE * (chunk_idx + 1); int j_left = offset; for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ BB((i_top + i), (j_top + j)) = top[i * BSIZE + j]; } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ BB((i_left + i), (j_left + j)) = left[i * BSIZE + j]; } } } //99327 void lud_perimeter(float* result, int offset) { float diagonal_buffer[BSIZE * BSIZE]; float top_buffer[BSIZE * BSIZE]; float left_buffer[BSIZE * BSIZE]; int i, j, k; diagonal:for (i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ diagonal_buffer[i * BSIZE + j] = AA(i, j); } } int chunk_idx, chunk_num; chunk_num = ((matrix_dim - offset) / BSIZE) - 1; for (chunk_idx = 0; chunk_idx < chunk_num; chunk_idx++){ perimeter_load(result, top_buffer, left_buffer, offset, chunk_idx); float sum; // processing top perimeter for (j = 0; j < BSIZE; j++){ for (i = 0; i < BSIZE; i++){ sum = 0.0f; for (k = 0; k < i; k++){ sum += diagonal_buffer[BSIZE * i + k] * top_buffer[k * BSIZE + j]; } top_buffer[i * BSIZE + j] = top_buffer[i * BSIZE + j] - sum; } } // processing left perimeter for (i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ sum = 0.0f; for (k = 0; k < j; k++){ sum += left_buffer[i * BSIZE + k] * diagonal_buffer[BSIZE * k + j]; } left_buffer[i * BSIZE + j] = (left_buffer[i * BSIZE + j] - sum) / diagonal_buffer[j * BSIZE + j]; } } perimeter_store(result, top_buffer, left_buffer, offset, chunk_idx); } cout << "success here perimeter" << endl; } void internal_load(float* result, float* top, float* left, float* inner, int offset, int chunk_idx, int chunk_num){ int i, j; int i_global, j_global; i_global = offset + BSIZE * (1 + chunk_idx / chunk_num); j_global = offset + BSIZE * (1 + chunk_idx % chunk_num); for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ top[i * BSIZE + j] = result[matrix_dim * (i + offset) + j + j_global]; } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ left[i * BSIZE + j] = result[matrix_dim * (i + i_global) + offset + j]; } } for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ inner[i * BSIZE + j] = result[matrix_dim * (i + i_global) + j + j_global]; } } } void internal_store(float* result, float* inner, int offset, int chunk_idx, int chunk_num){ int i, j; int i_global, j_global; i_global = offset + BSIZE * (1 + chunk_idx / chunk_num); j_global = offset + BSIZE * (1 + chunk_idx % chunk_num); for(i = 0; i < BSIZE; i++){ for(j = 0; j < BSIZE; j++){ result[matrix_dim * (i + i_global) + j + j_global] = inner[i * BSIZE + j]; } } } void lud_internal( float* result, int offset) { int chunk_idx, chunk_num; chunk_num = ((matrix_dim - offset) / BSIZE) - 1; float top_buffer[BSIZE * BSIZE]; float left_buffer[BSIZE * BSIZE]; float inner_buffer[BSIZE * BSIZE]; int i, j, k, i_global, j_global; for (chunk_idx = 0; chunk_idx < chunk_num * chunk_num; chunk_idx++){ internal_load(result, top_buffer, left_buffer, inner_buffer, offset, chunk_idx, chunk_num); for (i = 0; i < BSIZE; i++){ for (j = 0; j < BSIZE; j++){ float sum = 0.0f; //#pragma HLS unsafemath for (k = 0; k < BSIZE; k++){ sum += left_buffer[BSIZE * i + k] * top_buffer[BSIZE * k + j]; } inner_buffer[i * BSIZE + j] -= sum; } } internal_store(result, inner_buffer, offset, chunk_idx, chunk_num); } cout << "success internal" << endl; } void workload(float result[GRID_ROWS * GRID_COLS]){ #pragma HLS INTERFACE m_axi port=result offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=result bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control for(int i = 0; i < matrix_dim - BSIZE; i += BSIZE){ lud_diagonal(result, i); lud_perimeter(result, i); lud_internal(result, i); } int i = matrix_dim - BSIZE; lud_diagonal(result, i); return; } }
29.831276
130
0.473445
LemonAndRabbit
2bb70bca0865eccc1abd01bd4004fbefdf209038
1,636
hpp
C++
menoh/array.hpp
gwtnb/menoh
7df4100a2e30ea8133a9fd08ead1ea7d46793401
[ "MIT" ]
null
null
null
menoh/array.hpp
gwtnb/menoh
7df4100a2e30ea8133a9fd08ead1ea7d46793401
[ "MIT" ]
null
null
null
menoh/array.hpp
gwtnb/menoh
7df4100a2e30ea8133a9fd08ead1ea7d46793401
[ "MIT" ]
null
null
null
#ifndef MENOH_ARRAY_HPP #define MENOH_ARRAY_HPP #include <algorithm> #include <memory> #include <vector> #include <menoh/dims.hpp> #include <menoh/dtype.hpp> #include <menoh/exception.hpp> namespace menoh_impl { class array { public: array() = default; array(dtype_t d, std::vector<int> const& dims, void* data_handle); array(dtype_t d, std::vector<int> const& dims, std::shared_ptr<void> data); array(dtype_t d, std::vector<int> const& dims); dtype_t dtype() const { return dtype_; } auto const& dims() const { return dims_; } auto* data() const { return data_handle_; } bool has_ownership() const { return static_cast<bool>(data_); } private: dtype_t dtype_ = dtype_t::undefined; std::vector<int> dims_; std::shared_ptr<void> data_; void* data_handle_ = nullptr; }; std::size_t total_size(array const& a); float* fbegin(array const& a); float* fend(array const& a); float& fat(array const& a, std::size_t i); template <typename T> auto uniforms(dtype_t d, std::vector<int> const& dims, T val) { static_assert(std::is_arithmetic<T>::value, ""); auto arr = array(d, dims); if(d == dtype_t::float_) { std::fill_n(static_cast<float*>(arr.data()), calc_total_size(dims), static_cast<float>(val)); return arr; } throw invalid_dtype(std::to_string(static_cast<int>(d))); } array zeros(dtype_t d, std::vector<int> const& dims); } // namespace menoh_impl #endif // MENOH_ARRAY_HPP
26.819672
79
0.611247
gwtnb
2bb78be9e19739ee70cd0fd08d20d3b9cb48b7e1
1,287
cc
C++
GeneralUtilities/src/VMInfo.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
1
2021-06-23T22:09:28.000Z
2021-06-23T22:09:28.000Z
GeneralUtilities/src/VMInfo.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
125
2020-04-03T13:44:30.000Z
2021-10-15T21:29:57.000Z
GeneralUtilities/src/VMInfo.cc
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
null
null
null
#include "GeneralUtilities/inc/VMInfo.hh" #include <array> #include <fstream> #include <map> #include <sstream> #include <stdexcept> #include <unistd.h> namespace { // Helper function to check the units and return the value. long parseLine ( std::string const& line, std::string const& unitExpected ){ std::istringstream is(line); std::string key, unit; long val; is >> key >> val >> unit; if ( unit!=unitExpected ){ throw std::runtime_error( "ProcStatus: cannot parse: " + line ); } return val; } } // end anonymous namespace // The c'tor does all of the work. mu2e::VMInfo::VMInfo(){ // The information we want. std::array<std::string,4> wanted{ "VmPeak", "VmSize", "VmHWM", "VmRSS"}; // Parse the information to get what we need. std::ifstream proc("/proc/self/status"); std::map<std::string,long> values; while ( proc ){ std::string line; getline( proc, line); if ( !proc ) break; for ( auto const& name: wanted ){ if ( line.find(name) != std::string::npos ){ long val = parseLine( line, "kB"); values[name] = val; break; } } } vmPeak = values["VmPeak"]; vmSize = values["VmSize"]; vmHWM = values["VmHWM"]; vmRSS = values["VmRSS"]; }
23.833333
74
0.602176
lborrel
2bb9375679e453bbb52cceb696885b9fe5125bd0
3,125
ipp
C++
libember/Headers/ember/glow/impl/GlowParameter.ipp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
78
2015-07-31T14:46:38.000Z
2022-03-28T09:28:28.000Z
libember/Headers/ember/glow/impl/GlowParameter.ipp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
81
2015-08-03T07:58:19.000Z
2022-02-28T16:21:19.000Z
libember/Headers/ember/glow/impl/GlowParameter.ipp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
49
2015-08-03T12:53:10.000Z
2022-03-17T17:25:49.000Z
/* libember -- C++ 03 implementation of the Ember+ Protocol Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com). 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 __LIBEMBER_GLOW_GLOWPARAMETER_IPP #define __LIBEMBER_GLOW_GLOWPARAMETER_IPP #include "../../util/Inline.hpp" #include "../util/ValueConverter.hpp" #include "../GlowStringIntegerPair.hpp" #include "../GlowTags.hpp" #include "../GlowNodeBase.hpp" namespace libember { namespace glow { LIBEMBER_INLINE GlowParameter::GlowParameter(int number) : GlowParameterBase(GlowType::Parameter, GlowTags::ElementDefault(), GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) { insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number)); } LIBEMBER_INLINE GlowParameter::GlowParameter(GlowNodeBase* parent, int number) : GlowParameterBase(GlowType::Parameter, GlowTags::ElementDefault(), GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) { insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number)); if (parent) { GlowElementCollection* children = parent->children(); GlowElementCollection::iterator const where = children->end(); children->insert(where, this); } } LIBEMBER_INLINE GlowParameter::GlowParameter(int number, ber::Tag const& tag) : GlowParameterBase(GlowType::Parameter, tag, GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) { insert(begin(), new dom::VariantLeaf(GlowTags::Parameter::Number(), number)); } LIBEMBER_INLINE GlowParameter::GlowParameter(ber::Tag const& tag) : GlowParameterBase(GlowType::Parameter, tag, GlowTags::Parameter::Contents(), GlowTags::Parameter::Children()) , m_cachedNumber(-1) {} LIBEMBER_INLINE int GlowParameter::number() const { if (m_cachedNumber == -1) { ber::Tag const tag = GlowTags::Parameter::Number(); const_iterator const first = begin(); const_iterator const last = end(); const_iterator const result = util::find_tag(first, last, tag); if (result != last) { m_cachedNumber = util::ValueConverter::valueOf(&*result, -1); } else { m_cachedNumber = -1; } } return m_cachedNumber; } LIBEMBER_INLINE GlowParameter::iterator GlowParameter::insertImpl(iterator const& where, Node* child) { m_cachedNumber = -1; return GlowContainer::insertImpl(where, child); } LIBEMBER_INLINE void GlowParameter::eraseImpl(iterator const& first, iterator const& last) { m_cachedNumber = -1; GlowContainer::eraseImpl(first, last); } } } #endif // __LIBEMBER_GLOW_GLOWPARAMETER_IPP
32.894737
142
0.64096
purefunsolutions
2bbc823dacc872e579598f40345eddda0492ea26
1,095
cpp
C++
codeforces/A - Edit Distance/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Edit Distance/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Edit Distance/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Nov/29/2019 12:50 * solution_verdict: Accepted language: GNU C++14 * run_time: 31 ms memory_used: 0 KB * problem: https://codeforces.com/gym/102001/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6,inf=1e9; int main() { ios_base::sync_with_stdio(0);cin.tie(0); string s;cin>>s;int one=0,zero=0; for(auto x:s)x=='1'?one++:zero++; char c='0';if(zero>=one)c='1'; string p; for(int i=1;i<=s.size();i++)p.push_back(c); if(one!=zero)cout<<p<<endl,exit(0); if(s[0]=='0') { cout<<'1'; for(int i=2;i<=s.size();i++)cout<<'0'; } else { cout<<'0'; for(int i=2;i<=s.size();i++)cout<<'1'; } return 0; }
35.322581
111
0.389954
kzvd4729
2bbf29d7d690776f16f91246827260af76486411
2,333
hxx
C++
opencascade/HLRTopoBRep_OutLiner.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/HLRTopoBRep_OutLiner.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/HLRTopoBRep_OutLiner.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
// Created on: 1994-08-03 // Created by: Christophe MARION // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRTopoBRep_OutLiner_HeaderFile #define _HLRTopoBRep_OutLiner_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopoDS_Shape.hxx> #include <HLRTopoBRep_Data.hxx> #include <Standard_Transient.hxx> #include <BRepTopAdaptor_MapOfShapeTool.hxx> #include <Standard_Integer.hxx> class HLRAlgo_Projector; class TopoDS_Face; class HLRTopoBRep_OutLiner; DEFINE_STANDARD_HANDLE(HLRTopoBRep_OutLiner, Standard_Transient) class HLRTopoBRep_OutLiner : public Standard_Transient { public: Standard_EXPORT HLRTopoBRep_OutLiner(); Standard_EXPORT HLRTopoBRep_OutLiner(const TopoDS_Shape& OriSh); Standard_EXPORT HLRTopoBRep_OutLiner(const TopoDS_Shape& OriS, const TopoDS_Shape& OutS); void OriginalShape (const TopoDS_Shape& OriS); TopoDS_Shape& OriginalShape(); void OutLinedShape (const TopoDS_Shape& OutS); TopoDS_Shape& OutLinedShape(); HLRTopoBRep_Data& DataStructure(); Standard_EXPORT void Fill (const HLRAlgo_Projector& P, BRepTopAdaptor_MapOfShapeTool& MST, const Standard_Integer nbIso); DEFINE_STANDARD_RTTIEXT(HLRTopoBRep_OutLiner,Standard_Transient) protected: private: //! Builds faces from F and add them to S. Standard_EXPORT void ProcessFace (const TopoDS_Face& F, TopoDS_Shape& S, BRepTopAdaptor_MapOfShapeTool& M); Standard_EXPORT void BuildShape (BRepTopAdaptor_MapOfShapeTool& M); TopoDS_Shape myOriginalShape; TopoDS_Shape myOutLinedShape; HLRTopoBRep_Data myDS; }; #include <HLRTopoBRep_OutLiner.lxx> #endif // _HLRTopoBRep_OutLiner_HeaderFile
25.086022
123
0.786541
mgreminger
2bc03ccbf03b7b3f4f96170fa1423fdfff7cfef1
10,301
cpp
C++
tests/tensor/test_tensor_io.cpp
lauracanalini/eddl
c5efac642e8e1f99b31dfaaacd0a5a058b09923b
[ "MIT" ]
30
2019-10-11T21:03:43.000Z
2022-02-17T19:56:15.000Z
tests/tensor/test_tensor_io.cpp
lauracanalini/eddl
c5efac642e8e1f99b31dfaaacd0a5a058b09923b
[ "MIT" ]
151
2019-10-16T06:47:23.000Z
2022-03-07T15:15:58.000Z
tests/tensor/test_tensor_io.cpp
lauracanalini/eddl
c5efac642e8e1f99b31dfaaacd0a5a058b09923b
[ "MIT" ]
20
2019-10-16T09:37:37.000Z
2022-02-22T09:47:14.000Z
#include <gtest/gtest.h> #include <random> #include <string> #include "eddl/tensor/tensor.h" #include "eddl/tensor/nn/tensor_nn.h" #include "eddl/descriptors/descriptors.h" using namespace std; // Demo dataset static auto *ptr_iris = new float[150*4]{ 5.10, 3.50, 1.40, 0.20, 4.90, 3.00, 1.40, 0.20, 4.70, 3.20, 1.30, 0.20, 4.60, 3.10, 1.50, 0.20, 5.00, 3.60, 1.40, 0.20, 5.40, 3.90, 1.70, 0.40, 4.60, 3.40, 1.40, 0.30, 5.00, 3.40, 1.50, 0.20, 4.40, 2.90, 1.40, 0.20, 4.90, 3.10, 1.50, 0.10, 5.40, 3.70, 1.50, 0.20, 4.80, 3.40, 1.60, 0.20, 4.80, 3.00, 1.40, 0.10, 4.30, 3.00, 1.10, 0.10, 5.80, 4.00, 1.20, 0.20, 5.70, 4.40, 1.50, 0.40, 5.40, 3.90, 1.30, 0.40, 5.10, 3.50, 1.40, 0.30, 5.70, 3.80, 1.70, 0.30, 5.10, 3.80, 1.50, 0.30, 5.40, 3.40, 1.70, 0.20, 5.10, 3.70, 1.50, 0.40, 4.60, 3.60, 1.00, 0.20, 5.10, 3.30, 1.70, 0.50, 4.80, 3.40, 1.90, 0.20, 5.00, 3.00, 1.60, 0.20, 5.00, 3.40, 1.60, 0.40, 5.20, 3.50, 1.50, 0.20, 5.20, 3.40, 1.40, 0.20, 4.70, 3.20, 1.60, 0.20, 4.80, 3.10, 1.60, 0.20, 5.40, 3.40, 1.50, 0.40, 5.20, 4.10, 1.50, 0.10, 5.50, 4.20, 1.40, 0.20, 4.90, 3.10, 1.50, 0.20, 5.00, 3.20, 1.20, 0.20, 5.50, 3.50, 1.30, 0.20, 4.90, 3.60, 1.40, 0.10, 4.40, 3.00, 1.30, 0.20, 5.10, 3.40, 1.50, 0.20, 5.00, 3.50, 1.30, 0.30, 4.50, 2.30, 1.30, 0.30, 4.40, 3.20, 1.30, 0.20, 5.00, 3.50, 1.60, 0.60, 5.10, 3.80, 1.90, 0.40, 4.80, 3.00, 1.40, 0.30, 5.10, 3.80, 1.60, 0.20, 4.60, 3.20, 1.40, 0.20, 5.30, 3.70, 1.50, 0.20, 5.00, 3.30, 1.40, 0.20, 7.00, 3.20, 4.70, 1.40, 6.40, 3.20, 4.50, 1.50, 6.90, 3.10, 4.90, 1.50, 5.50, 2.30, 4.00, 1.30, 6.50, 2.80, 4.60, 1.50, 5.70, 2.80, 4.50, 1.30, 6.30, 3.30, 4.70, 1.60, 4.90, 2.40, 3.30, 1.00, 6.60, 2.90, 4.60, 1.30, 5.20, 2.70, 3.90, 1.40, 5.00, 2.00, 3.50, 1.00, 5.90, 3.00, 4.20, 1.50, 6.00, 2.20, 4.00, 1.00, 6.10, 2.90, 4.70, 1.40, 5.60, 2.90, 3.60, 1.30, 6.70, 3.10, 4.40, 1.40, 5.60, 3.00, 4.50, 1.50, 5.80, 2.70, 4.10, 1.00, 6.20, 2.20, 4.50, 1.50, 5.60, 2.50, 3.90, 1.10, 5.90, 3.20, 4.80, 1.80, 6.10, 2.80, 4.00, 1.30, 6.30, 2.50, 4.90, 1.50, 6.10, 2.80, 4.70, 1.20, 6.40, 2.90, 4.30, 1.30, 6.60, 3.00, 4.40, 1.40, 6.80, 2.80, 4.80, 1.40, 6.70, 3.00, 5.00, 1.70, 6.00, 2.90, 4.50, 1.50, 5.70, 2.60, 3.50, 1.00, 5.50, 2.40, 3.80, 1.10, 5.50, 2.40, 3.70, 1.00, 5.80, 2.70, 3.90, 1.20, 6.00, 2.70, 5.10, 1.60, 5.40, 3.00, 4.50, 1.50, 6.00, 3.40, 4.50, 1.60, 6.70, 3.10, 4.70, 1.50, 6.30, 2.30, 4.40, 1.30, 5.60, 3.00, 4.10, 1.30, 5.50, 2.50, 4.00, 1.30, 5.50, 2.60, 4.40, 1.20, 6.10, 3.00, 4.60, 1.40, 5.80, 2.60, 4.00, 1.20, 5.00, 2.30, 3.30, 1.00, 5.60, 2.70, 4.20, 1.30, 5.70, 3.00, 4.20, 1.20, 5.70, 2.90, 4.20, 1.30, 6.20, 2.90, 4.30, 1.30, 5.10, 2.50, 3.00, 1.10, 5.70, 2.80, 4.10, 1.30, 6.30, 3.30, 6.00, 2.50, 5.80, 2.70, 5.10, 1.90, 7.10, 3.00, 5.90, 2.10, 6.30, 2.90, 5.60, 1.80, 6.50, 3.00, 5.80, 2.20, 7.60, 3.00, 6.60, 2.10, 4.90, 2.50, 4.50, 1.70, 7.30, 2.90, 6.30, 1.80, 6.70, 2.50, 5.80, 1.80, 7.20, 3.60, 6.10, 2.50, 6.50, 3.20, 5.10, 2.00, 6.40, 2.70, 5.30, 1.90, 6.80, 3.00, 5.50, 2.10, 5.70, 2.50, 5.00, 2.00, 5.80, 2.80, 5.10, 2.40, 6.40, 3.20, 5.30, 2.30, 6.50, 3.00, 5.50, 1.80, 7.70, 3.80, 6.70, 2.20, 7.70, 2.60, 6.90, 2.30, 6.00, 2.20, 5.00, 1.50, 6.90, 3.20, 5.70, 2.30, 5.60, 2.80, 4.90, 2.00, 7.70, 2.80, 6.70, 2.00, 6.30, 2.70, 4.90, 1.80, 6.70, 3.30, 5.70, 2.10, 7.20, 3.20, 6.00, 1.80, 6.20, 2.80, 4.80, 1.80, 6.10, 3.00, 4.90, 1.80, 6.40, 2.80, 5.60, 2.10, 7.20, 3.00, 5.80, 1.60, 7.40, 2.80, 6.10, 1.90, 7.90, 3.80, 6.40, 2.00, 6.40, 2.80, 5.60, 2.20, 6.30, 2.80, 5.10, 1.50, 6.10, 2.60, 5.60, 1.40, 7.70, 3.00, 6.10, 2.30, 6.30, 3.40, 5.60, 2.40, 6.40, 3.10, 5.50, 1.80, 6.00, 3.00, 4.80, 1.80, 6.90, 3.10, 5.40, 2.10, 6.70, 3.10, 5.60, 2.40, 6.90, 3.10, 5.10, 2.30, 5.80, 2.70, 5.10, 1.90, 6.80, 3.20, 5.90, 2.30, 6.70, 3.30, 5.70, 2.50, 6.70, 3.00, 5.20, 2.30, 6.30, 2.50, 5.00, 1.90, 6.50, 3.00, 5.20, 2.00, 6.20, 3.40, 5.40, 2.30, 5.90, 3.00, 5.10, 1.80, }; static auto* t_iris = new Tensor({150, 4}, ptr_iris, DEV_CPU); // Demo image static auto* t_image = Tensor::arange(0, 100); // Random generators const int MIN_RANDOM = 0; const int MAX_RANDOM = 999999; static std::random_device rd; static std::mt19937 mt(rd()); static std::uniform_int_distribution<std::mt19937::result_type> dist6(MIN_RANDOM, MAX_RANDOM); TEST(TensorTestSuite, tensor_io_jpg) { // Generate random name int rdn_name = dist6(mt); string fname = "image_" + to_string(rdn_name) + ".jpg"; // Save file Tensor *t_ref = Tensor::concat({t_image, t_image, t_image}); // This jpeg needs 3 channels t_ref->reshape_({3, 10, 10}); // This jpeg needs 3 channels t_ref->save(fname); // All values are cast to integers // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_ref, t_load, 1e-3f, 0.0f, true, true)); delete t_ref; delete t_load; } TEST(TensorTestSuite, tensor_io_png) { // Generate random name int rdn_name = dist6(mt); string fname = "image_" + to_string(rdn_name) + ".png"; // Save file Tensor *t_ref = Tensor::concat({t_image, t_image, t_image}); // This jpeg needs 3 channels t_ref->reshape_({3, 10, 10}); // This jpeg needs 3 channels t_ref->save(fname); // All values are cast to integers // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_ref, t_load, 1e-3f, 0.0f, true, true)); delete t_ref; delete t_load; } TEST(TensorTestSuite, tensor_io_bmp) { // Generate random name int rdn_name = dist6(mt); string fname = "image_" + to_string(rdn_name) + ".bmp"; // Save file Tensor *t_ref = Tensor::concat({t_image, t_image, t_image}); // This jpeg needs 3 channels t_ref->reshape_({3, 10, 10}); // This jpeg needs 3 channels t_ref->save(fname); // All values are cast to integers // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_ref, t_load, 1e-3f, 0.0f, true, true)); delete t_ref; delete t_load; } //TEST(TensorTestSuite, tensor_io_numpy) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".npy"; // // // Save file // t_iris->save(fname); // // // Load saved file // Tensor* t_load = Tensor::load<float>(fname); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} //TEST(TensorTestSuite, tensor_io_csv) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".csv"; // // // Save file // t_iris->save(fname); // // // Load saved file // Tensor* t_load = Tensor::load(fname); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} //TEST(TensorTestSuite, tensor_io_tsv) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".tsv"; // // // Save file // t_iris->save(fname); // // // Load saved file // Tensor* t_load = Tensor::load(fname); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} //TEST(TensorTestSuite, tensor_io_txt) //{ // // Generate random name // int rdn_name = dist6(mt); // string fname = "iris_" + to_string(rdn_name) + ".txt"; // // // Save file // t_iris->save2txt(fname, ' ', {"sepal.length" , "sepal.width", "petal.length", "petal.width"}); // // // Load saved file // Tensor* t_load = Tensor::load_from_txt(fname, ' ', 1); // // // Delete file // int hasFailed = std::remove(fname.c_str()); // if(hasFailed) { cout << "Error deleting file: " << fname << endl; } // // ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); //} TEST(TensorTestSuite, tensor_io_bin) { // Generate random name int rdn_name = dist6(mt); string fname = "iris_" + to_string(rdn_name) + ".bin"; // Save file t_iris->save(fname); // Load saved file Tensor* t_load = Tensor::load(fname); // Delete file int hasFailed = std::remove(fname.c_str()); if(hasFailed) { cout << "Error deleting file: " << fname << endl; } ASSERT_TRUE(Tensor::equivalent(t_iris, t_load, 1e-3f, 0.0f, true, true)); delete t_iris; delete t_load; }
29.347578
100
0.507718
lauracanalini
2bc18e603b704b5cd7e08cc5db9102970ac0fcd6
1,096
cpp
C++
Codeforces/Round-734-Div3/E.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-01-30T13:21:30.000Z
2018-01-30T13:21:30.000Z
Codeforces/Round-734-Div3/E.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
null
null
null
Codeforces/Round-734-Div3/E.cpp
TISparta/competitive-programming-solutions
31987d4e67bb874bf15653565c6418b5605a20a8
[ "MIT" ]
1
2018-08-29T13:26:50.000Z
2018-08-29T13:26:50.000Z
// Tags: DP // Difficulty: 4.5 // Priority: 1 // Date: 23-07-2021 #include <bits/stdc++.h> #define all(A) begin(A), end(A) #define rall(A) rbegin(A), rend(A) #define sz(A) int(A.size()) #define pb push_back #define mp make_pair using namespace std; typedef long long ll; typedef pair <int, int> pii; typedef pair <ll, ll> pll; typedef vector <int> vi; typedef vector <ll> vll; typedef vector <pii> vpii; typedef vector <pll> vpll; int main () { ios::sync_with_stdio(false); cin.tie(0); int tt; cin >> tt; while (tt--) { int n, k; cin >> n >> k; vi a(n + 1); for (int i = 1; i <= n; i++) cin >> a[i]; vi dp(n + 1, -1); // dp(i) = maximum number of fixed points with an array of size i dp[0] = 0; for (int i = 1; i <= n; i++) { for (int j = n; j > 0; j--) { if (dp[j - 1] == -1) continue; dp[j] = max(dp[j], dp[j - 1] + (a[i] == j)); } } int ans = -1; for (int i = n; i >= 1; i--) { if (dp[i] >= k) { ans = n - i; break; } } cout << ans << '\n'; } return (0); }
21.076923
87
0.494526
TISparta
2bc41f310b986fe7940cfe2ab64e3fefd9973fed
1,017
hpp
C++
src/service/MoleculeService.hpp
MichelML/chempp
cba27b910e7cbf626bcd4e1c25e394311e5f74e9
[ "Apache-2.0" ]
5
2021-05-21T17:15:32.000Z
2021-07-26T17:38:52.000Z
src/service/MoleculeService.hpp
MichelML/chempp
cba27b910e7cbf626bcd4e1c25e394311e5f74e9
[ "Apache-2.0" ]
15
2021-05-17T14:24:15.000Z
2021-08-12T15:30:11.000Z
src/service/MoleculeService.hpp
MichelML/chempp
cba27b910e7cbf626bcd4e1c25e394311e5f74e9
[ "Apache-2.0" ]
1
2021-06-26T01:07:18.000Z
2021-06-26T01:07:18.000Z
#ifndef EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP #define EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP #include "db/MoleculeDb.hpp" #include "dto/StatusDto.hpp" #include "dto/MoleculeDto.hpp" #include "dto/MoleculesListDto.hpp" #include "oatpp/web/protocol/http/Http.hpp" #include "oatpp/core/macro/component.hpp" class MoleculeService { private: typedef oatpp::web::protocol::http::Status Status; private: OATPP_COMPONENT(std::shared_ptr<MoleculeDb>, m_database); // Inject database component public: oatpp::Object<MoleculeDto> getMoleculeById(const oatpp::Int64& id); oatpp::Object<MoleculeDetailedDto> getExactMolecule(const oatpp::String& structure); oatpp::Object<ListDto<oatpp::Object<MoleculeDto>>> getSubstructureMatches(const oatpp::String& structure, const oatpp::Int64& limit); oatpp::Object<SimListDto<oatpp::Object<MoleculeDto>>> getSimilarityMatches(const oatpp::String& structure, const oatpp::Int64& limit, const oatpp::Float64& threshold); }; #endif //EXAMPLE_POSTGRESQL_MOLECULESERVICE_HPP
37.666667
169
0.797443
MichelML
2bc42c4bafc9df7ba7729f3a502e5669e9893ba0
3,234
hpp
C++
qipython/pyguard.hpp
Maelic/libqi-python
d5e250a7ce1b6039bb1f57f750cab51412dfecca
[ "BSD-3-Clause" ]
7
2015-08-12T01:25:11.000Z
2021-07-15T11:08:34.000Z
qipython/pyguard.hpp
Maelic/libqi-python
d5e250a7ce1b6039bb1f57f750cab51412dfecca
[ "BSD-3-Clause" ]
10
2015-10-01T11:33:53.000Z
2022-03-23T10:19:33.000Z
qipython/pyguard.hpp
Maelic/libqi-python
d5e250a7ce1b6039bb1f57f750cab51412dfecca
[ "BSD-3-Clause" ]
7
2015-02-24T10:38:52.000Z
2022-03-14T10:18:26.000Z
/* ** Copyright (C) 2020 SoftBank Robotics Europe ** See COPYING for the license */ #pragma once #ifndef QIPYTHON_GUARD_HPP #define QIPYTHON_GUARD_HPP #include <qipython/common.hpp> #include <ka/typetraits.hpp> #include <type_traits> namespace qi { namespace py { /// DefaultConstructible Guard /// Procedure<_ (Args)> F template<typename Guard, typename F, typename... Args> ka::ResultOf<F(Args&&...)> invokeGuarded(F&& f, Args&&... args) { Guard g; return std::forward<F>(f)(std::forward<Args>(args)...); } namespace detail { // Guards the copy, construction and destruction of an object, and only when // in case of copy construction the source object evaluates to true, and in case // of destruction, the object itself evaluates to true. // // Explanation: // pybind11::object only requires the GIL to be locked on copy and if the // source is not null. Default construction does not require the GIL either. template<typename Guard, typename Object> class Guarded { using Storage = typename std::aligned_storage<sizeof(Object), alignof(Object)>::type; Storage _object; Object& object() { return reinterpret_cast<Object&>(_object); } const Object& object() const { return reinterpret_cast<const Object&>(_object); } public: template<typename Arg0, typename... Args, ka::EnableIf<std::is_constructible<Object, Arg0&&, Args&&...>::value, int> = 0> explicit Guarded(Arg0&& arg0, Args&&... args) { Guard g; new(&_object) Object(std::forward<Arg0>(arg0), std::forward<Args>(args)...); } Guarded() { // Default construction, no GIL needed. new(&_object) Object(); } Guarded(Guarded& o) { boost::optional<Guard> optGuard; if (o.object()) optGuard.emplace(); new(&_object) Object(o.object()); } Guarded(const Guarded& o) { boost::optional<Guard> optGuard; if (o.object()) optGuard.emplace(); new(&_object) Object(o.object()); } Guarded(Guarded&& o) { new(&_object) Object(std::move(o.object())); } ~Guarded() { boost::optional<Guard> optGuard; if (object()) optGuard.emplace(); object().~Object(); } Guarded& operator=(const Guarded& o) { if (this == &o) return *this; { boost::optional<Guard> optGuard; if (o.object()) optGuard.emplace(); object() = o.object(); } return *this; } Guarded& operator=(Guarded&& o) { if (this == &o) return *this; object() = std::move(o.object()); return *this; } Object& operator*() { return object(); } const Object& operator*() const { return object(); } Object* operator->() { return &object(); } const Object* operator->() const { return &object(); } explicit operator Object&() { return object(); } explicit operator const Object&() const { return object(); } }; } // namespace detail /// Wraps a pybind11::object value and locks the GIL on copy and destruction. /// /// This is useful for instance to put pybind11 objects in lambda functions so /// that they can be copied around safely. using GILGuardedObject = detail::Guarded<pybind11::gil_scoped_acquire, pybind11::object>; } // namespace py } // namespace qi #endif // QIPYTHON_GUARD_HPP
23.779412
90
0.653061
Maelic
2bc58ddcf7479e5d3006b54cb23426bb1db7b70d
7,820
cpp
C++
src/gui/qt/qt_backend.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
src/gui/qt/qt_backend.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
src/gui/qt/qt_backend.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
/* * djnn v2 * * The copyright holders for the contents of this file are: * Ecole Nationale de l'Aviation Civile, France (2018) * See file "license.terms" for the rights and conditions * defined by copyright holders. * * * Contributors: * Mathieu Magnaudet <mathieu.magnaudet@enac.fr> * */ #include "../backend.h" #include "../transformation/transformations.h" #include "qt_context.h" #include "qt_backend.h" #include "qt_window.h" #include <QtWidgets/QWidget> #include <QtGui/QPainter> #include <QtCore/QtMath> #include <QtCore/QFileInfo> #include <iostream> #include <cmath> namespace djnn { QtBackend *QtBackend::_instance; std::once_flag QtBackend::onceFlag; QtBackend* QtBackend::instance () { std::call_once (QtBackend::onceFlag, [] () { _instance = new QtBackend(); }); return _instance; } QtBackend::QtBackend () : _painter (nullptr), _picking_view (nullptr) { _context_manager = new QtContextManager (); } QtBackend::~QtBackend () { if (_context_manager) { delete _context_manager; _context_manager = nullptr;} } void QtBackend::save_context () { if (_painter != nullptr) _painter->save (); } void QtBackend::restore_context () { if (_painter != nullptr) _painter->restore (); } void QtBackend::set_painter (QPainter* p) { _painter = p; } void QtBackend::set_picking_view (QtPickingView* p) { _picking_view = p; } /* Qt context management is imported from djnn v1 */ void QtBackend::load_drawing_context (AbstractGShape *s, double tx, double ty, double width, double height) { QtContext *cur_context = _context_manager->get_current (); QMatrix4x4 matrix = cur_context->matrix; QTransform transform = matrix.toTransform (); if (s->matrix () != nullptr) { Homography *h = dynamic_cast<Homography*> (s->matrix ()); Homography *hi = dynamic_cast<Homography*> (s->inverted_matrix ()); QMatrix4x4 loc_matrix = QMatrix4x4 (matrix); h->_m11->set_value (loc_matrix (0, 0), false); h->_m12->set_value (loc_matrix (0, 1), false); h->_m13->set_value (loc_matrix (0, 2), false); h->_m14->set_value (loc_matrix (0, 3), false); h->_m21->set_value (loc_matrix (1, 0), false); h->_m22->set_value (loc_matrix (1, 1), false); h->_m23->set_value (loc_matrix (1, 2), false); h->_m24->set_value (loc_matrix (1, 3), false); h->_m31->set_value (loc_matrix (2, 0), false); h->_m32->set_value (loc_matrix (2, 1), false); h->_m33->set_value (loc_matrix (2, 2), false); h->_m34->set_value (loc_matrix (2, 3), false); h->_m41->set_value (loc_matrix (3, 0), false); h->_m42->set_value (loc_matrix (3, 1), false); h->_m43->set_value (loc_matrix (3, 2), false); h->_m44->set_value (loc_matrix (3, 3), false); loc_matrix = loc_matrix.inverted (); hi->_m11->set_value (loc_matrix (0, 0), false); hi->_m12->set_value (loc_matrix (0, 1), false); hi->_m13->set_value (loc_matrix (0, 2), false); hi->_m14->set_value (loc_matrix (0, 3), false); hi->_m21->set_value (loc_matrix (1, 0), false); hi->_m22->set_value (loc_matrix (1, 1), false); hi->_m23->set_value (loc_matrix (1, 2), false); hi->_m24->set_value (loc_matrix (1, 3), false); hi->_m31->set_value (loc_matrix (2, 0), false); hi->_m32->set_value (loc_matrix (2, 1), false); hi->_m33->set_value (loc_matrix (2, 2), false); hi->_m34->set_value (loc_matrix (2, 3), false); hi->_m41->set_value (loc_matrix (3, 0), false); hi->_m42->set_value (loc_matrix (3, 1), false); hi->_m43->set_value (loc_matrix (3, 2), false); hi->_m44->set_value (loc_matrix (3, 3), false); } /* setup the painting environment of the drawing view */ QPen tmpPen (cur_context->pen); /* * with Qt, dash pattern and dash offset are specified * in stroke-width unit so we need to update the values accordingly */ if (cur_context->pen.style () == Qt::CustomDashLine) { qreal w = cur_context->pen.widthF () || 1; QVector<qreal> dashPattern = cur_context->pen.dashPattern (); QVector<qreal> tmp (dashPattern.size ()); for (int i = 0; i < dashPattern.size (); i++) tmp[i] = dashPattern.value (i) / w; tmpPen.setDashPattern (tmp); tmpPen.setDashOffset (cur_context->pen.dashOffset () / w); } _painter->setRenderHint (QPainter::Antialiasing, true); _painter->setPen (tmpPen); _painter->setTransform (transform); /* If the brush style is gradient and the coordinate mode is ObjectBoundingMode * then translate the rotation axis of the gradient transform and transpose * the translation values in the global coordinate system*/ if (cur_context->brush.style () == Qt::LinearGradientPattern || cur_context->brush.style () == Qt::RadialGradientPattern) { if (cur_context->brush.gradient ()->coordinateMode () == QGradient::ObjectBoundingMode) { QTransform origin = cur_context->gradientTransform; QTransform newT = QTransform (); newT.translate (tx, ty); QTransform result = origin * newT; result.translate (-tx, -ty); double m11 = result.m11 (); double m12 = result.m12 (); double m13 = result.m13 (); double m21 = result.m21 (); double m22 = result.m22 (); double m23 = result.m23 (); double m31 = result.m31 () * width; double m32 = result.m32 () * height; double m33 = result.m33 (); result.setMatrix (m11, m12, m13, m21, m22, m23, m31, m32, m33); cur_context->gradientTransform = result; } } cur_context->brush.setTransform (cur_context->gradientTransform); _painter->setBrush (cur_context->brush); } void QtBackend::load_pick_context (AbstractGShape *s) { QtContext *cur_context = _context_manager->get_current (); QPen pickPen; QBrush pickBrush (_picking_view->pick_color ()); pickPen.setStyle (Qt::SolidLine); pickPen.setColor (_picking_view->pick_color ()); pickPen.setWidth (cur_context->pen.width()); _picking_view->painter ()->setPen (pickPen); _picking_view->painter ()->setBrush (pickBrush); _picking_view->painter ()->setTransform (cur_context->matrix.toTransform ()); _picking_view->add_gobj (s); } WinImpl* QtBackend::create_window (Window *win, const std::string& title, double x, double y, double w, double h) { return new QtWindow (win, title, x, y, w, h); } bool QtBackend::is_in_picking_view (AbstractGShape *s) { return is_pickable (s); /*return s->press ()->has_coupling () || s->x ()->has_coupling () || s->y ()->has_coupling () || s->move ()->has_coupling () || s->release ()->has_coupling () || s->enter ()->has_coupling () || s->leave ()->has_coupling ();*/ } static QFont::Style fontStyleArray[3] = { QFont::StyleNormal, QFont::StyleItalic, QFont::StyleOblique }; void QtBackend::update_text_geometry (Text* text, FontFamily* ff, FontSize* fsz, FontStyle* fs, FontWeight *fw) { QFont qfont; if (ff) { QString val (ff->family()->get_value ().c_str ()); qfont.setFamily (val); } if (fsz) { qfont.setPixelSize (fsz->size ()->get_value ()); } if (fs) { int i = fs->style ()->get_value (); if (i >= 0 && i <= 3) qfont.setStyle (fontStyleArray [i]); } if (fw) { qfont.setWeight (fw->weight ()->get_value ()); } QString str (text->text ()->get_value().c_str ()); QFontMetrics fm (qfont); int width = fm.width (str); int height = fm.height (); text->set_width (width); text->set_height (height); } } /* namespace djnn */
32.995781
108
0.625575
alicemona
2bc7cc8408c2e86201c75f4a22350f032a56f075
979
cpp
C++
Source/Foundation/bsfCore/Managers/BsMeshManager.cpp
myrgy/bsf
2c31da99f5763a47c0dee7e2cdb3d4ac3b3c37a6
[ "MIT" ]
1
2018-04-16T12:14:52.000Z
2018-04-16T12:14:52.000Z
Source/Foundation/bsfCore/Managers/BsMeshManager.cpp
myrgy/bsf
2c31da99f5763a47c0dee7e2cdb3d4ac3b3c37a6
[ "MIT" ]
null
null
null
Source/Foundation/bsfCore/Managers/BsMeshManager.cpp
myrgy/bsf
2c31da99f5763a47c0dee7e2cdb3d4ac3b3c37a6
[ "MIT" ]
null
null
null
//************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "Managers/BsMeshManager.h" #include "BsCoreApplication.h" #include "Math/BsVector3.h" #include "Mesh/BsMesh.h" #include "RenderAPI/BsVertexDataDesc.h" namespace bs { MeshManager::MeshManager() { } MeshManager::~MeshManager() { } void MeshManager::onStartUp() { SPtr<VertexDataDesc> vertexDesc = bs_shared_ptr_new<VertexDataDesc>(); vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION); mDummyMeshData = bs_shared_ptr_new<MeshData>(1, 3, vertexDesc); auto vecIter = mDummyMeshData->getVec3DataIter(VES_POSITION); vecIter.setValue(Vector3(0, 0, 0)); auto indices = mDummyMeshData->getIndices32(); indices[0] = 0; indices[1] = 0; indices[2] = 0; mDummyMesh = Mesh::create(mDummyMeshData); } }
28.794118
124
0.658836
myrgy
2bc81063a73e18c00b73fdb550fd89f181f2c024
8,210
cc
C++
src/Formlsms/rss_expl.cc
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
6
2018-05-30T23:02:14.000Z
2022-01-19T07:30:46.000Z
src/Formlsms/rss_expl.cc
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
null
null
null
src/Formlsms/rss_expl.cc
asminer/smart
269747c4578b670e5c3973f93a1e6ec71d95be78
[ "Apache-2.0" ]
2
2018-07-13T18:53:27.000Z
2021-04-12T17:54:02.000Z
#include <cstdio> #include "rss_expl.h" #include "../ExprLib/exprman.h" #include "../ExprLib/mod_vars.h" // For ordering states #include "../include/heap.h" #include "../Modules/expl_states.h" // ****************************************************************** // * * // * expl_reachset methods * // * * // ****************************************************************** expl_reachset::expl_reachset(StateLib::state_db* ss) { state_dictionary = ss; state_dictionary->ConvertToStatic(true); state_handle = 0; state_collection = 0; DCASSERT(state_dictionary); natorder = new natural_db_iter(*state_dictionary); needs_discorder = false; discorder = 0; lexorder = 0; } expl_reachset::~expl_reachset() { delete state_dictionary; delete[] state_handle; delete state_collection; delete natorder; delete discorder; delete lexorder; } StateLib::state_db* expl_reachset::getStateDatabase() const { return state_dictionary; } void expl_reachset::getNumStates(long &ns) const { if (state_dictionary) { ns = state_dictionary->Size(); } else { DCASSERT(state_collection); ns = state_collection->Size(); } } void expl_reachset::showInternal(OutputStream &os) const { long ns; getNumStates(ns); for (long i=0; i<ns; i++) { long bytes = 0; const unsigned char* ptr = 0; os << "State " << i << " internal:"; if (state_dictionary) { ptr = state_dictionary->GetRawState(i, bytes); } else { DCASSERT(state_collection); DCASSERT(state_handle); ptr = state_collection->GetRawState(state_handle[i], bytes); } for (long b=0; b<bytes; b++) { os.Put(' '); os.PutHex(ptr[b]); } os.Put('\n'); os.flush(); } } void expl_reachset::showState(OutputStream &os, const shared_state* st) const { st->Print(os, 0); } state_lldsm::reachset::iterator& expl_reachset ::iteratorForOrder(state_lldsm::display_order ord) { DCASSERT(state_dictionary || (state_collection && state_handle)); switch (ord) { case state_lldsm::DISCOVERY: if (needs_discorder) { if (0==discorder) { discorder = new discovery_coll_iter(*state_collection, state_handle); } return *discorder; } DCASSERT(natorder); return *natorder; case state_lldsm::LEXICAL: if (0==lexorder) { if (state_dictionary) { lexorder = new lexical_db_iter(getGrandParent(), *state_dictionary); } else { lexorder = new lexical_coll_iter(getGrandParent(), *state_collection, state_handle); } } return *lexorder; case state_lldsm::NATURAL: default: DCASSERT(natorder); return *natorder; }; } state_lldsm::reachset::iterator& expl_reachset::easiestIterator() const { DCASSERT(natorder); return *natorder; } void expl_reachset::Finish() { // Compact states state_collection = state_dictionary->TakeStateCollection(); delete state_dictionary; state_dictionary = 0; state_handle = state_collection->RemoveIndexHandles(); // Update iterators DCASSERT(state_collection); DCASSERT(state_handle); delete natorder; natorder = new natural_coll_iter(*state_collection, state_handle); delete lexorder; lexorder = 0; delete discorder; discorder = 0; } void expl_reachset::Renumber(const GraphLib::node_renumberer* Ren) { if (0==Ren) return; if (!Ren->changes_something()) return; DCASSERT(state_collection); DCASSERT(state_handle); // Renumber state_handle array long* aux = new long[state_collection->Size()]; for (long i=state_collection->Size()-1; i>=0; i--) { aux[i] = state_handle[i]; } for (long i=state_collection->Size()-1; i>=0; i--) { CHECK_RANGE(0, Ren->new_number(i), state_collection->Size()); state_handle[Ren->new_number(i)] = aux[i]; } delete[] aux; needs_discorder = true; } // ****************************************************************** // * * // * expl_reachset::db_iterator methods * // * * // ****************************************************************** expl_reachset::db_iterator::db_iterator(const StateLib::state_db &s) : indexed_iterator(s.Size()), states(s) { } expl_reachset::db_iterator::~db_iterator() { } void expl_reachset::db_iterator::copyState(shared_state* st, long o) const { states.GetStateKnown(ord2index(o), st->writeState(), st->getStateSize()); } // ****************************************************************** // * * // * expl_reachset::coll_iterator methods * // * * // ****************************************************************** expl_reachset::coll_iterator::coll_iterator(const StateLib::state_coll &SC, const long* SH) : indexed_iterator(SC.Size()), states(SC), state_handle(SH) { DCASSERT(state_handle); } expl_reachset::coll_iterator::~coll_iterator() { } void expl_reachset::coll_iterator::copyState(shared_state* st, long o) const { states.GetStateKnown(state_handle[ord2index(o)], st->writeState(), st->getStateSize()); } // ****************************************************************** // * * // * expl_reachset::natural_db_iter methods * // * * // ****************************************************************** expl_reachset::natural_db_iter::natural_db_iter(const StateLib::state_db &s) : db_iterator(s) { // nothing! } // ****************************************************************** // * * // * expl_reachset::natural_coll_iter methods * // * * // ****************************************************************** expl_reachset::natural_coll_iter::natural_coll_iter(const StateLib::state_coll &SC, const long* SH) : coll_iterator(SC, SH) { // nothing! } // ****************************************************************** // * * // * expl_reachset::discovery_coll_iter methods * // * * // ****************************************************************** expl_reachset::discovery_coll_iter::discovery_coll_iter(const StateLib::state_coll &SC, const long* SH) : coll_iterator(SC, SH) { long* M = new long[SC.Size()]; DCASSERT(SH); HeapSort(SH, M, SC.Size()); setMap(M); } // ****************************************************************** // * * // * expl_reachset::lexical_db_iter methods * // * * // ****************************************************************** expl_reachset::lexical_db_iter::lexical_db_iter(const hldsm* hm, const StateLib::state_db &s) : db_iterator(s) { long* M = new long[s.Size()]; const StateLib::state_coll* coll = s.GetStateCollection(); LexicalSort(hm, coll, M); setMap(M); } // ****************************************************************** // * * // * expl_reachset::lexical_coll_iter methods * // * * // ****************************************************************** expl_reachset::lexical_coll_iter::lexical_coll_iter(const hldsm* hm, const StateLib::state_coll &SC, const long* SH) : coll_iterator(SC, SH) { long* M = new long[SC.Size()]; DCASSERT(SH); LexicalSort(hm, &SC, SH, M); setMap(M); }
29.746377
94
0.484409
asminer
2bc8a6f2fe10326db472411451506169927da2c8
357
cpp
C++
compiler-rt/test/msan/ftime.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
compiler-rt/test/msan/ftime.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
compiler-rt/test/msan/ftime.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %clangxx_msan -O0 -g %s -o %t && %run %t // ftime() is deprecated on FreeBSD and NetBSD. // UNSUPPORTED: freebsd, netbsd #include <assert.h> #include <sys/timeb.h> #include <sanitizer/msan_interface.h> int main(void) { struct timeb tb; int res = ftime(&tb); assert(!res); assert(__msan_test_shadow(&tb, sizeof(tb)) == -1); return 0; }
19.833333
52
0.652661
medismailben
2bce03c358b7d9221c58a8ab25166381d8f27de2
698
cc
C++
cmd/cmd_args.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
cmd/cmd_args.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
cmd/cmd_args.cc
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
#include <system.hh> #include <urbite.hh> #include <process.hh> #include <strutils.hh> using namespace makemore; extern "C" void mainmore(Process *); void mainmore( Process *process ) { unsigned int itabn = process->itab.size(); if (itabn < 2) return; strvec argext; if (!process->read(&argext, itabn - 1)) return; process->itab[itabn - 1]->unlink_reader(process); process->itab.resize(itabn - 1); Command shellmore = find_command("sh"); process->cmd = "sh"; process->func = shellmore; strvec bak_args = process->args; catstrvec(process->args, argext); shellmore(process); process->cmd = "args"; process->func = mainmore; process->args = bak_args; }
19.388889
51
0.667622
jdb19937
2bcef84f16db5b67460b4be9c6bec13eb5570382
122
cpp
C++
ACEXML/common/Element_Def_Builder.cpp
BeiJiaan/ace
2845970c894bb350d12d6a32e867d7ddf2487f25
[ "DOC" ]
16
2015-05-11T04:33:44.000Z
2022-02-15T04:28:39.000Z
ACEXML/common/Element_Def_Builder.cpp
BeiJiaan/ace
2845970c894bb350d12d6a32e867d7ddf2487f25
[ "DOC" ]
null
null
null
ACEXML/common/Element_Def_Builder.cpp
BeiJiaan/ace
2845970c894bb350d12d6a32e867d7ddf2487f25
[ "DOC" ]
7
2015-01-08T16:11:34.000Z
2021-07-04T16:04:40.000Z
// $Id$ #include "ACEXML/common/Element_Def_Builder.h" ACEXML_Element_Def_Builder::~ACEXML_Element_Def_Builder () { }
12.2
58
0.762295
BeiJiaan
2bd23f8c9b1f6d6f07901780f6f8045644b96d26
12,695
cpp
C++
ThirdParty/UPnP/Platinum/Source/Devices/MediaServer/PltSyncMediaBrowser.cpp
snazy2000/MediaBrowser.Plugins
8c3a23fc0ce0186dd1ef048bf51a0eb7a1ee42b0
[ "MIT" ]
1
2021-05-15T16:24:07.000Z
2021-05-15T16:24:07.000Z
ThirdParty/UPnP/Platinum/Source/Devices/MediaServer/PltSyncMediaBrowser.cpp
bllakjakk/MediaBrowser.Plugins
4b115a832f7f31d752ba0c135c65d570c6220bec
[ "MIT" ]
null
null
null
ThirdParty/UPnP/Platinum/Source/Devices/MediaServer/PltSyncMediaBrowser.cpp
bllakjakk/MediaBrowser.Plugins
4b115a832f7f31d752ba0c135c65d570c6220bec
[ "MIT" ]
null
null
null
/***************************************************************** | | Platinum - Synchronous Media Browser | | Copyright (c) 2004-2010, Plutinosoft, LLC. | All rights reserved. | http://www.plutinosoft.com | | This program is free software; you can redistribute it and/or | modify it under the terms of the GNU General Public License | as published by the Free Software Foundation; either version 2 | of the License, or (at your option) any later version. | | OEMs, ISVs, VARs and other distributors that combine and | distribute commercially licensed software with Platinum software | and do not wish to distribute the source code for the commercially | licensed software under version 2, or (at your option) any later | version, of the GNU General Public License (the "GPL") must enter | into a commercial license agreement with Plutinosoft, LLC. | licensing@plutinosoft.com | | 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; see the file LICENSE.txt. If not, write to | the Free Software Foundation, Inc., | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. | http://www.gnu.org/licenses/gpl-2.0.html | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "PltSyncMediaBrowser.h" NPT_SET_LOCAL_LOGGER("platinum.media.server.syncbrowser") /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::PLT_SyncMediaBrowser +---------------------------------------------------------------------*/ PLT_SyncMediaBrowser::PLT_SyncMediaBrowser(PLT_CtrlPointReference& ctrlPoint, bool use_cache /* = false */, PLT_MediaContainerChangesListener* listener /* = NULL */) : PLT_MediaBrowser(ctrlPoint), m_ContainerListener(listener), m_UseCache(use_cache) { SetDelegate(this); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::~PLT_SyncMediaBrowser +---------------------------------------------------------------------*/ PLT_SyncMediaBrowser::~PLT_SyncMediaBrowser() { } /* Blocks forever waiting for a response from a request * It is expected the request to succeed or to timeout and return an error eventually */ /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::WaitForResponse +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::WaitForResponse(NPT_SharedVariable& shared_var) { return shared_var.WaitUntilEquals(1, 30000); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnDeviceAdded +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::OnDeviceAdded(PLT_DeviceDataReference& device) { NPT_String uuid = device->GetUUID(); // test if it's a media server PLT_Service* service; if (NPT_SUCCEEDED(device->FindServiceByType("urn:schemas-upnp-org:service:ContentDirectory:*", service))) { NPT_AutoLock lock(m_MediaServers); m_MediaServers.Put(uuid, device); } return PLT_MediaBrowser::OnDeviceAdded(device); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnDeviceRemoved +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::OnDeviceRemoved(PLT_DeviceDataReference& device) { NPT_String uuid = device->GetUUID(); // Remove from our list of servers first if found { NPT_AutoLock lock(m_MediaServers); m_MediaServers.Erase(uuid); } // clear cache for that device if (m_UseCache) m_Cache.Clear(device.AsPointer()->GetUUID()); return PLT_MediaBrowser::OnDeviceRemoved(device); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::Find +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::Find(const char* ip, PLT_DeviceDataReference& device) { NPT_AutoLock lock(m_MediaServers); const NPT_List<PLT_DeviceMapEntry*>::Iterator it = m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByIp(ip)); if (it) { device = (*it)->GetValue(); return NPT_SUCCESS; } return NPT_FAILURE; } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnBrowseResult +---------------------------------------------------------------------*/ void PLT_SyncMediaBrowser::OnBrowseResult(NPT_Result res, PLT_DeviceDataReference& device, PLT_BrowseInfo* info, void* userdata) { NPT_COMPILER_UNUSED(device); if (!userdata) return; PLT_BrowseDataReference* data = (PLT_BrowseDataReference*) userdata; (*data)->res = res; if (NPT_SUCCEEDED(res) && info) { (*data)->info = *info; } (*data)->shared_var.SetValue(1); delete data; } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::OnMSStateVariablesChanged +---------------------------------------------------------------------*/ void PLT_SyncMediaBrowser::OnMSStateVariablesChanged(PLT_Service* service, NPT_List<PLT_StateVariable*>* vars) { NPT_AutoLock lock(m_MediaServers); PLT_DeviceDataReference device; const NPT_List<PLT_DeviceMapEntry*>::Iterator it = m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByUUID(service->GetDevice()->GetUUID())); if (!it) return; // device with this service has gone away device = (*it)->GetValue(); PLT_StateVariable* var = PLT_StateVariable::Find(*vars, "ContainerUpdateIDs"); if (var) { // variable found, parse value NPT_String value = var->GetValue(); NPT_String item_id, update_id; int index; while (value.GetLength()) { // look for container id index = value.Find(','); if (index < 0) break; item_id = value.Left(index); value = value.SubString(index+1); // look for update id if (value.GetLength()) { index = value.Find(','); update_id = (index<0)?value:value.Left(index); value = (index<0)?"":value.SubString(index+1); // clear cache for that device if (m_UseCache) m_Cache.Clear(device->GetUUID(), item_id); // notify listener if (m_ContainerListener) m_ContainerListener->OnContainerChanged(device, item_id, update_id); } } } } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::BrowseSync +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::BrowseSync(PLT_BrowseDataReference& browse_data, PLT_DeviceDataReference& device, const char* object_id, NPT_Int32 index, NPT_Int32 count, bool browse_metadata, const char* filter, const char* sort) { NPT_Result res; browse_data->shared_var.SetValue(0); browse_data->info.si = index; // send off the browse packet. Note that this will // not block. There is a call to WaitForResponse in order // to block until the response comes back. res = PLT_MediaBrowser::Browse(device, (const char*)object_id, index, count, browse_metadata, filter, sort, new PLT_BrowseDataReference(browse_data)); NPT_CHECK_SEVERE(res); return WaitForResponse(browse_data->shared_var); } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::BrowseSync +---------------------------------------------------------------------*/ NPT_Result PLT_SyncMediaBrowser::BrowseSync(PLT_DeviceDataReference& device, const char* object_id, PLT_MediaObjectListReference& list, bool metadata, /* = false */ NPT_Int32 start, /* = 0 */ NPT_Cardinal max_results /* = 0 */) { NPT_Result res = NPT_FAILURE; NPT_Int32 index = start; // only cache metadata or if starting from 0 and asking for maximum bool cache = m_UseCache && (metadata || (start == 0 && max_results == 0)); // reset output params list = NULL; // look into cache first if (cache && NPT_SUCCEEDED(m_Cache.Get(device->GetUUID(), object_id, list))) return NPT_SUCCESS; do { PLT_BrowseDataReference browse_data(new PLT_BrowseData(), true); // send off the browse packet. Note that this will // not block. There is a call to WaitForResponse in order // to block until the response comes back. res = BrowseSync( browse_data, device, (const char*)object_id, index, metadata?1:30, // DLNA recommendations for browsing children is no more than 30 at a time metadata); NPT_CHECK_LABEL_WARNING(res, done); if (NPT_FAILED(browse_data->res)) { res = browse_data->res; NPT_CHECK_LABEL_WARNING(res, done); } // server returned no more, bail now if (browse_data->info.items->GetItemCount() == 0) break; if (list.IsNull()) { list = browse_data->info.items; } else { list->Add(*browse_data->info.items); // clear the list items so that the data inside is not // cleaned up by PLT_MediaItemList dtor since we copied // each pointer into the new list. browse_data->info.items->Clear(); } // stop now if our list contains exactly what the server said it had. // Note that the server could return 0 if it didn't know how many items were // available. In this case we have to continue browsing until // nothing is returned back by the server. // Unless we were told to stop after reaching a certain amount to avoid // length delays // (some servers may return a total matches out of whack at some point too) if ((browse_data->info.tm && browse_data->info.tm <= list->GetItemCount()) || (max_results && list->GetItemCount() >= max_results)) break; // ask for the next chunk of entries index = list->GetItemCount(); } while(1); done: // cache the result if (cache && NPT_SUCCEEDED(res) && !list.IsNull() && list->GetItemCount()) { m_Cache.Put(device->GetUUID(), object_id, list); } // clear entire cache data for device if failed, the device could be gone if (NPT_FAILED(res) && cache) m_Cache.Clear(device->GetUUID()); return res; } /*---------------------------------------------------------------------- | PLT_SyncMediaBrowser::IsCached +---------------------------------------------------------------------*/ bool PLT_SyncMediaBrowser::IsCached(const char* uuid, const char* object_id) { NPT_AutoLock lock(m_MediaServers); const NPT_List<PLT_DeviceMapEntry*>::Iterator it = m_MediaServers.GetEntries().Find(PLT_DeviceMapFinderByUUID(uuid)); if (!it) { m_Cache.Clear(uuid); return false; // device with this service has gone away } PLT_MediaObjectListReference list; return NPT_SUCCEEDED(m_Cache.Get(uuid, object_id, list))?true:false; }
38.353474
111
0.525876
snazy2000
2bd294ab16d7655a50aa5695947407f549e42368
4,795
cpp
C++
src/pxr/imaging/plugin/hdLava/lavaApiFramebuffer.cpp
cinepost/Falcor
f70bd1d97c064d6f91a017d4409aa2037fd6903a
[ "BSD-3-Clause" ]
null
null
null
src/pxr/imaging/plugin/hdLava/lavaApiFramebuffer.cpp
cinepost/Falcor
f70bd1d97c064d6f91a017d4409aa2037fd6903a
[ "BSD-3-Clause" ]
2
2021-03-02T10:16:06.000Z
2021-08-13T10:10:21.000Z
src/pxr/imaging/plugin/hdLava/lavaApiFramebuffer.cpp
cinepost/Lava
f70bd1d97c064d6f91a017d4409aa2037fd6903a
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************ Copyright 2020 Advanced Micro Devices, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************/ #include "lavaApiFramebuffer.h" #include "aovDescriptor.h" #include "pxr/imaging/rprUsd/helpers.h" PXR_NAMESPACE_OPEN_SCOPE HdRprApiFramebuffer::HdRprApiFramebuffer(rpr::Context* context, uint32_t width, uint32_t height) : m_context(context) , m_rprFb(nullptr) , m_width(0) , m_height(0) , m_aov(kAovNone) { if (!m_context) { LAVA_THROW_ERROR_MSG("Failed to create framebuffer: missing rpr context"); } Create(width, height); } HdRprApiFramebuffer::HdRprApiFramebuffer(HdRprApiFramebuffer&& fb) noexcept { *this = std::move(fb); } HdRprApiFramebuffer::~HdRprApiFramebuffer() { Delete(); } HdRprApiFramebuffer& HdRprApiFramebuffer::operator=(HdRprApiFramebuffer&& fb) noexcept { m_context = fb.m_context; m_width = fb.m_width; m_height = fb.m_height; m_aov = fb.m_aov; m_rprFb = fb.m_rprFb; fb.m_width = 0u; fb.m_height = 0u; fb.m_aov = kAovNone; fb.m_rprFb = nullptr; return *this; } void HdRprApiFramebuffer::AttachAs(lava::Aov aov) { if (m_aov != kAovNone || aov == kAovNone) { //LAVA_ERROR_CHECK(m_context->SetAOV(m_aov, nullptr), "Failed to detach aov framebuffer"); } if (aov != kAovNone) { //LAVA_ERROR_CHECK_THROW(m_context->SetAOV(aov, m_rprFb), "Failed to attach aov framebuffer"); } m_aov = aov; } void HdRprApiFramebuffer::Clear(float r, float g, float b, float a) { if (m_width == 0 || m_height == 0) { return; } LAVA_ERROR_CHECK(m_rprFb->Clear(), "Failed to clear framebuffer"); // XXX (FIR-1681): We can not rely on clear values because every AOV in LAVA is multisampled, i.e. // value of singlesampled AOV (any ID AOV, worldCoordinate, etc) is always equals to `clearValue + renderedValue` /*if (r == 0.0f && g == 0.0f && b == 0.0f && a == 0.0f) { LAVA_ERROR_CHECK(m_rprFb->Clear(), "Failed to clear framebuffer"); } else { LAVA_ERROR_CHECK(m_rprFb->FillWithColor(r, g, b, a), "Failed to clear framebuffer"); }*/ } void HdRprApiFramebuffer::Resolve(HdRprApiFramebuffer* dstFrameBuffer) { if (!m_rprFb || !dstFrameBuffer || !dstFrameBuffer->m_rprFb) { return; } LAVA_ERROR_CHECK_THROW(m_context->ResolveFrameBuffer(m_rprFb, dstFrameBuffer->m_rprFb, true), "Failed to resolve framebuffer"); } bool HdRprApiFramebuffer::Resize(uint32_t width, uint32_t height) { if (m_width == width && m_height == height) { return false; } lava::Aov aov = m_aov; Delete(); Create(width, height); if (aov != kAovNone) { AttachAs(aov); } return true; } bool HdRprApiFramebuffer::GetData(void* dstBuffer, size_t dstBufferSize) { if (m_width == 0 || m_height == 0 || !m_rprFb) { return false; } auto size = GetSize(); if (size > dstBufferSize) { return false; } return !LAVA_ERROR_CHECK(m_rprFb->GetInfo(LAVA_FRAMEBUFFER_DATA, size, dstBuffer, nullptr), "Failed to get framebuffer data"); } size_t HdRprApiFramebuffer::GetSize() const { return m_width * m_height * kNumChannels * sizeof(float); } rpr::FramebufferDesc HdRprApiFramebuffer::GetDesc() const { rpr::FramebufferDesc desc = {}; desc.fb_width = m_width; desc.fb_height = m_height; return desc; } void HdRprApiFramebuffer::Create(uint32_t width, uint32_t height) { if (width == 0 || height == 0) { return; } rpr::FramebufferFormat format = {}; format.num_components = kNumChannels; format.type = LAVA_COMPONENT_TYPE_FLOAT32; rpr::FramebufferDesc desc = {}; desc.fb_width = width; desc.fb_height = height; rpr::Status status; m_rprFb = m_context->CreateFrameBuffer(format, desc, &status); if (!m_rprFb) { LAVA_ERROR_CHECK_THROW(status, "Failed to create framebuffer"); } m_width = width; m_height = height; } void HdRprApiFramebuffer::Delete() { if (m_aov != kAovNone) { AttachAs(kAovNone); } if (m_rprFb) { delete m_rprFb; m_rprFb = nullptr; } } PXR_NAMESPACE_CLOSE_SCOPE
29.060606
131
0.652972
cinepost
2bd59c798ec49b645948eba76e89ff8976eb5747
2,308
cpp
C++
src/py/wrapper/wrapper_206185953d7651e78a6714d1fe602758.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
null
null
null
src/py/wrapper/wrapper_206185953d7651e78a6714d1fe602758.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
7
2018-03-20T14:23:16.000Z
2019-04-09T11:57:57.000Z
src/py/wrapper/wrapper_206185953d7651e78a6714d1fe602758.cpp
StatisKit/Core
79d8ec07c203eb7973a6cf482852ddb2e8e1e93e
[ "Apache-2.0" ]
7
2017-04-28T07:41:01.000Z
2021-03-15T18:17:20.000Z
#include "_core.h" namespace autowig { typedef ::statiskit::ContinuousUnivariateConditionalDistribution class_type; class Trampoline : public class_type { public: using ::statiskit::ContinuousUnivariateConditionalDistribution::ContinuousUnivariateConditionalDistribution; typedef class ::std::unique_ptr< struct ::statiskit::UnivariateConditionalDistribution, struct ::std::default_delete< struct ::statiskit::UnivariateConditionalDistribution > > return_type_2d42bbbaff065a9cb38813f62e9dafda; virtual return_type_2d42bbbaff065a9cb38813f62e9dafda copy() const override { PYBIND11_OVERLOAD_PURE_UNIQUE_PTR(return_type_2d42bbbaff065a9cb38813f62e9dafda, class_type, copy, ); }; typedef unsigned int return_type_a19605344e725c65ab302819d1663dbe; virtual return_type_a19605344e725c65ab302819d1663dbe get_nb_parameters() const override { PYBIND11_OVERLOAD_PURE(return_type_a19605344e725c65ab302819d1663dbe, class_type, get_nb_parameters, ); }; typedef struct ::statiskit::MultivariateSampleSpace const * return_type_152a627d69cd5b35837e015943fc1e75; virtual return_type_152a627d69cd5b35837e015943fc1e75 get_explanatory_space() const override { PYBIND11_OVERLOAD_PURE(return_type_152a627d69cd5b35837e015943fc1e75, class_type, get_explanatory_space, ); }; typedef struct ::statiskit::UnivariateDistribution const * return_type_53f978a20dca5ccd9144b1aeb74559b6; typedef struct ::statiskit::MultivariateEvent const & param_53f978a20dca5ccd9144b1aeb74559b6_0_type; virtual return_type_53f978a20dca5ccd9144b1aeb74559b6 operator()(param_53f978a20dca5ccd9144b1aeb74559b6_0_type param_0) const override { PYBIND11_OVERLOAD_PURE(return_type_53f978a20dca5ccd9144b1aeb74559b6, class_type, operator(), param_0); }; }; } namespace autowig { } void wrapper_206185953d7651e78a6714d1fe602758(pybind11::module& module) { pybind11::class_<struct ::statiskit::ContinuousUnivariateConditionalDistribution, autowig::Trampoline, autowig::HolderType< struct ::statiskit::ContinuousUnivariateConditionalDistribution >::Type, struct ::statiskit::UnivariateConditionalDistribution > class_206185953d7651e78a6714d1fe602758(module, "ContinuousUnivariateConditionalDistribution", ""); }
69.939394
355
0.811958
StatisKit
2bd5f01f06663a342f74b66285a85f87c2949906
53,792
cpp
C++
src/aes_ni_botan.cpp
GeneralZero/aes-brute-force
0498afc3e086e3c2ae57a4151e47c1143b944ed6
[ "Apache-2.0" ]
4
2020-10-18T03:28:56.000Z
2022-02-22T11:49:29.000Z
src/aes_ni_botan.cpp
GeneralZero/aes-brute-force
0498afc3e086e3c2ae57a4151e47c1143b944ed6
[ "Apache-2.0" ]
4
2020-09-23T21:00:51.000Z
2021-01-15T17:55:21.000Z
src/aes_ni_botan.cpp
GeneralZero/aes-brute-force
0498afc3e086e3c2ae57a4151e47c1143b944ed6
[ "Apache-2.0" ]
null
null
null
/* * AES using AES-NI instructions * (C) 2009,2012 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <stdint.h> #include <cstring> #ifdef __x86_64 #include <wmmintrin.h> inline void load_le(uint32_t* output, const uint8_t* input, size_t count) { //Not dealing with endianness right now //std::memcpy(output, reinterpret_cast<const uint32_t*>(input), count); std::memcpy(output, input, count * sizeof(uint32_t)); } __m128i aes_128_key_expansion(__m128i key, __m128i key_with_rcon) { key_with_rcon = _mm_shuffle_epi32(key_with_rcon, _MM_SHUFFLE(3,3,3,3)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); return _mm_xor_si128(key, key_with_rcon); } void aes_192_key_expansion(__m128i* K1, __m128i* K2, __m128i key2_with_rcon, uint32_t out[], bool last) { __m128i key1 = *K1; __m128i key2 = *K2; key2_with_rcon = _mm_shuffle_epi32(key2_with_rcon, _MM_SHUFFLE(1,1,1,1)); key1 = _mm_xor_si128(key1, _mm_slli_si128(key1, 4)); key1 = _mm_xor_si128(key1, _mm_slli_si128(key1, 4)); key1 = _mm_xor_si128(key1, _mm_slli_si128(key1, 4)); key1 = _mm_xor_si128(key1, key2_with_rcon); *K1 = key1; _mm_storeu_si128(reinterpret_cast<__m128i*>(out), key1); if(last) return; key2 = _mm_xor_si128(key2, _mm_slli_si128(key2, 4)); key2 = _mm_xor_si128(key2, _mm_shuffle_epi32(key1, _MM_SHUFFLE(3,3,3,3))); *K2 = key2; out[4] = _mm_cvtsi128_si32(key2); out[5] = _mm_cvtsi128_si32(_mm_srli_si128(key2, 4)); } /* * The second half of the AES-256 key expansion (other half same as AES-128) */ __m128i aes_256_key_expansion(__m128i key, __m128i key2) { __m128i key_with_rcon = _mm_aeskeygenassist_si128(key2, 0x00); key_with_rcon = _mm_shuffle_epi32(key_with_rcon, _MM_SHUFFLE(2,2,2,2)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); key = _mm_xor_si128(key, _mm_slli_si128(key, 4)); return _mm_xor_si128(key, key_with_rcon); } #define AES_ENC_4_ROUNDS(K) \ do \ { \ B0 = _mm_aesenc_si128(B0, K); \ B1 = _mm_aesenc_si128(B1, K); \ B2 = _mm_aesenc_si128(B2, K); \ B3 = _mm_aesenc_si128(B3, K); \ } while(0) #define AES_ENC_4_LAST_ROUNDS(K) \ do \ { \ B0 = _mm_aesenclast_si128(B0, K); \ B1 = _mm_aesenclast_si128(B1, K); \ B2 = _mm_aesenclast_si128(B2, K); \ B3 = _mm_aesenclast_si128(B3, K); \ } while(0) #define AES_DEC_4_ROUNDS(K) \ do \ { \ B0 = _mm_aesdec_si128(B0, K); \ B1 = _mm_aesdec_si128(B1, K); \ B2 = _mm_aesdec_si128(B2, K); \ B3 = _mm_aesdec_si128(B3, K); \ } while(0) #define AES_DEC_4_LAST_ROUNDS(K) \ do \ { \ B0 = _mm_aesdeclast_si128(B0, K); \ B1 = _mm_aesdeclast_si128(B1, K); \ B2 = _mm_aesdeclast_si128(B2, K); \ B3 = _mm_aesdeclast_si128(B3, K); \ } while(0) /* * AES-128 Encryption */ void aesni_128_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[44]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(encryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); while(blocks >= 4){ __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_LAST_ROUNDS(K10); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesenc_si128(B, K1); B = _mm_aesenc_si128(B, K2); B = _mm_aesenc_si128(B, K3); B = _mm_aesenc_si128(B, K4); B = _mm_aesenc_si128(B, K5); B = _mm_aesenc_si128(B, K6); B = _mm_aesenc_si128(B, K7); B = _mm_aesenc_si128(B, K8); B = _mm_aesenc_si128(B, K9); B = _mm_aesenclast_si128(B, K10); _mm_storeu_si128(out_mm + i, B); } } /* * AES-128 Decryption */ void aesni_128_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[44]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(decryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); while(blocks >= 4){ __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_LAST_ROUNDS(K10); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i){ __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesdec_si128(B, K1); B = _mm_aesdec_si128(B, K2); B = _mm_aesdec_si128(B, K3); B = _mm_aesdec_si128(B, K4); B = _mm_aesdec_si128(B, K5); B = _mm_aesdec_si128(B, K6); B = _mm_aesdec_si128(B, K7); B = _mm_aesdec_si128(B, K8); B = _mm_aesdec_si128(B, K9); B = _mm_aesdeclast_si128(B, K10); _mm_storeu_si128(out_mm + i, B); } } /* * AES-128 Key Schedule */ void aesni_128_key_schedule(const uint8_t key[], uint32_t encryption_keys[44], uint32_t decryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, _mm_aeskeygenassist_si128(K, RCON)) const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(key)); const __m128i K1 = AES_128_key_exp(K0, 0x01); const __m128i K2 = AES_128_key_exp(K1, 0x02); const __m128i K3 = AES_128_key_exp(K2, 0x04); const __m128i K4 = AES_128_key_exp(K3, 0x08); const __m128i K5 = AES_128_key_exp(K4, 0x10); const __m128i K6 = AES_128_key_exp(K5, 0x20); const __m128i K7 = AES_128_key_exp(K6, 0x40); const __m128i K8 = AES_128_key_exp(K7, 0x80); const __m128i K9 = AES_128_key_exp(K8, 0x1B); const __m128i K10 = AES_128_key_exp(K9, 0x36); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); // Now generate decryption keys __m128i* DK_mm = reinterpret_cast<__m128i*>(decryption_keys); _mm_storeu_si128(DK_mm , K10); _mm_storeu_si128(DK_mm + 1, _mm_aesimc_si128(K9)); _mm_storeu_si128(DK_mm + 2, _mm_aesimc_si128(K8)); _mm_storeu_si128(DK_mm + 3, _mm_aesimc_si128(K7)); _mm_storeu_si128(DK_mm + 4, _mm_aesimc_si128(K6)); _mm_storeu_si128(DK_mm + 5, _mm_aesimc_si128(K5)); _mm_storeu_si128(DK_mm + 6, _mm_aesimc_si128(K4)); _mm_storeu_si128(DK_mm + 7, _mm_aesimc_si128(K3)); _mm_storeu_si128(DK_mm + 8, _mm_aesimc_si128(K2)); _mm_storeu_si128(DK_mm + 9, _mm_aesimc_si128(K1)); _mm_storeu_si128(DK_mm + 10, K0); } void aesni_128_key_schedule_only_encryption(const uint8_t key[], uint32_t encryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, _mm_aeskeygenassist_si128(K, RCON)) const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(key)); const __m128i K1 = AES_128_key_exp(K0, 0x01); const __m128i K2 = AES_128_key_exp(K1, 0x02); const __m128i K3 = AES_128_key_exp(K2, 0x04); const __m128i K4 = AES_128_key_exp(K3, 0x08); const __m128i K5 = AES_128_key_exp(K4, 0x10); const __m128i K6 = AES_128_key_exp(K5, 0x20); const __m128i K7 = AES_128_key_exp(K6, 0x40); const __m128i K8 = AES_128_key_exp(K7, 0x80); const __m128i K9 = AES_128_key_exp(K8, 0x1B); const __m128i K10 = AES_128_key_exp(K9, 0x36); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); } /* * AES-192 Encryption */ void aesni_192_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[52]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(encryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_ROUNDS(K11); AES_ENC_4_LAST_ROUNDS(K12); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesenc_si128(B, K1); B = _mm_aesenc_si128(B, K2); B = _mm_aesenc_si128(B, K3); B = _mm_aesenc_si128(B, K4); B = _mm_aesenc_si128(B, K5); B = _mm_aesenc_si128(B, K6); B = _mm_aesenc_si128(B, K7); B = _mm_aesenc_si128(B, K8); B = _mm_aesenc_si128(B, K9); B = _mm_aesenc_si128(B, K10); B = _mm_aesenc_si128(B, K11); B = _mm_aesenclast_si128(B, K12); _mm_storeu_si128(out_mm + i, B); } } /* * AES-192 Decryption */ void aesni_192_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[52]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(decryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_ROUNDS(K11); AES_DEC_4_LAST_ROUNDS(K12); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesdec_si128(B, K1); B = _mm_aesdec_si128(B, K2); B = _mm_aesdec_si128(B, K3); B = _mm_aesdec_si128(B, K4); B = _mm_aesdec_si128(B, K5); B = _mm_aesdec_si128(B, K6); B = _mm_aesdec_si128(B, K7); B = _mm_aesdec_si128(B, K8); B = _mm_aesdec_si128(B, K9); B = _mm_aesdec_si128(B, K10); B = _mm_aesdec_si128(B, K11); B = _mm_aesdeclast_si128(B, K12); _mm_storeu_si128(out_mm + i, B); } } /* * AES-192 Key Schedule */ void aesni_192_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[52], uint32_t decryption_keys[52]) { __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 8)); K1 = _mm_srli_si128(K1, 8); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ _mm_aeskeygenassist_si128(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp // Now generate decryption keys const __m128i* EK_mm = reinterpret_cast<const __m128i*>(encryption_keys); __m128i* DK_mm = reinterpret_cast<__m128i*>(decryption_keys); _mm_storeu_si128(DK_mm , _mm_loadu_si128(EK_mm + 12)); _mm_storeu_si128(DK_mm + 1, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 11))); _mm_storeu_si128(DK_mm + 2, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 10))); _mm_storeu_si128(DK_mm + 3, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 9))); _mm_storeu_si128(DK_mm + 4, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 8))); _mm_storeu_si128(DK_mm + 5, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 7))); _mm_storeu_si128(DK_mm + 6, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 6))); _mm_storeu_si128(DK_mm + 7, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 5))); _mm_storeu_si128(DK_mm + 8, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 4))); _mm_storeu_si128(DK_mm + 9, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 3))); _mm_storeu_si128(DK_mm + 10, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 2))); _mm_storeu_si128(DK_mm + 11, _mm_aesimc_si128(_mm_loadu_si128(EK_mm + 1))); _mm_storeu_si128(DK_mm + 12, _mm_loadu_si128(EK_mm + 0)); } void aesni_192_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[52]) { __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 8)); K1 = _mm_srli_si128(K1, 8); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ _mm_aeskeygenassist_si128(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp } /* * AES-256 Encryption */ void aesni_256_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[60]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(encryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); const __m128i K13 = _mm_loadu_si128(key_mm + 13); const __m128i K14 = _mm_loadu_si128(key_mm + 14); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_ROUNDS(K11); AES_ENC_4_ROUNDS(K12); AES_ENC_4_ROUNDS(K13); AES_ENC_4_LAST_ROUNDS(K14); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesenc_si128(B, K1); B = _mm_aesenc_si128(B, K2); B = _mm_aesenc_si128(B, K3); B = _mm_aesenc_si128(B, K4); B = _mm_aesenc_si128(B, K5); B = _mm_aesenc_si128(B, K6); B = _mm_aesenc_si128(B, K7); B = _mm_aesenc_si128(B, K8); B = _mm_aesenc_si128(B, K9); B = _mm_aesenc_si128(B, K10); B = _mm_aesenc_si128(B, K11); B = _mm_aesenc_si128(B, K12); B = _mm_aesenc_si128(B, K13); B = _mm_aesenclast_si128(B, K14); _mm_storeu_si128(out_mm + i, B); } } /* * AES-256 Decryption */ void aesni_256_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[60]) { const __m128i* in_mm = reinterpret_cast<const __m128i*>(in); __m128i* out_mm = reinterpret_cast<__m128i*>(out); const __m128i* key_mm = reinterpret_cast<const __m128i*>(decryption_keys); const __m128i K0 = _mm_loadu_si128(key_mm); const __m128i K1 = _mm_loadu_si128(key_mm + 1); const __m128i K2 = _mm_loadu_si128(key_mm + 2); const __m128i K3 = _mm_loadu_si128(key_mm + 3); const __m128i K4 = _mm_loadu_si128(key_mm + 4); const __m128i K5 = _mm_loadu_si128(key_mm + 5); const __m128i K6 = _mm_loadu_si128(key_mm + 6); const __m128i K7 = _mm_loadu_si128(key_mm + 7); const __m128i K8 = _mm_loadu_si128(key_mm + 8); const __m128i K9 = _mm_loadu_si128(key_mm + 9); const __m128i K10 = _mm_loadu_si128(key_mm + 10); const __m128i K11 = _mm_loadu_si128(key_mm + 11); const __m128i K12 = _mm_loadu_si128(key_mm + 12); const __m128i K13 = _mm_loadu_si128(key_mm + 13); const __m128i K14 = _mm_loadu_si128(key_mm + 14); while(blocks >= 4) { __m128i B0 = _mm_loadu_si128(in_mm + 0); __m128i B1 = _mm_loadu_si128(in_mm + 1); __m128i B2 = _mm_loadu_si128(in_mm + 2); __m128i B3 = _mm_loadu_si128(in_mm + 3); B0 = _mm_xor_si128(B0, K0); B1 = _mm_xor_si128(B1, K0); B2 = _mm_xor_si128(B2, K0); B3 = _mm_xor_si128(B3, K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_ROUNDS(K11); AES_DEC_4_ROUNDS(K12); AES_DEC_4_ROUNDS(K13); AES_DEC_4_LAST_ROUNDS(K14); _mm_storeu_si128(out_mm + 0, B0); _mm_storeu_si128(out_mm + 1, B1); _mm_storeu_si128(out_mm + 2, B2); _mm_storeu_si128(out_mm + 3, B3); blocks -= 4; in_mm += 4; out_mm += 4; } for(size_t i = 0; i != blocks; ++i) { __m128i B = _mm_loadu_si128(in_mm + i); B = _mm_xor_si128(B, K0); B = _mm_aesdec_si128(B, K1); B = _mm_aesdec_si128(B, K2); B = _mm_aesdec_si128(B, K3); B = _mm_aesdec_si128(B, K4); B = _mm_aesdec_si128(B, K5); B = _mm_aesdec_si128(B, K6); B = _mm_aesdec_si128(B, K7); B = _mm_aesdec_si128(B, K8); B = _mm_aesdec_si128(B, K9); B = _mm_aesdec_si128(B, K10); B = _mm_aesdec_si128(B, K11); B = _mm_aesdec_si128(B, K12); B = _mm_aesdec_si128(B, K13); B = _mm_aesdeclast_si128(B, K14); _mm_storeu_si128(out_mm + i, B); } } /* * AES-256 Key Schedule */ void aesni_256_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[60], uint32_t decryption_keys[60]) { const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); const __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 16)); const __m128i K2 = aes_128_key_expansion(K0, _mm_aeskeygenassist_si128(K1, 0x01)); const __m128i K3 = aes_256_key_expansion(K1, K2); const __m128i K4 = aes_128_key_expansion(K2, _mm_aeskeygenassist_si128(K3, 0x02)); const __m128i K5 = aes_256_key_expansion(K3, K4); const __m128i K6 = aes_128_key_expansion(K4, _mm_aeskeygenassist_si128(K5, 0x04)); const __m128i K7 = aes_256_key_expansion(K5, K6); const __m128i K8 = aes_128_key_expansion(K6, _mm_aeskeygenassist_si128(K7, 0x08)); const __m128i K9 = aes_256_key_expansion(K7, K8); const __m128i K10 = aes_128_key_expansion(K8, _mm_aeskeygenassist_si128(K9, 0x10)); const __m128i K11 = aes_256_key_expansion(K9, K10); const __m128i K12 = aes_128_key_expansion(K10, _mm_aeskeygenassist_si128(K11, 0x20)); const __m128i K13 = aes_256_key_expansion(K11, K12); const __m128i K14 = aes_128_key_expansion(K12, _mm_aeskeygenassist_si128(K13, 0x40)); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); _mm_storeu_si128(EK_mm + 11, K11); _mm_storeu_si128(EK_mm + 12, K12); _mm_storeu_si128(EK_mm + 13, K13); _mm_storeu_si128(EK_mm + 14, K14); // Now generate decryption keys __m128i* DK_mm = reinterpret_cast<__m128i*>(decryption_keys); _mm_storeu_si128(DK_mm , K14); _mm_storeu_si128(DK_mm + 1, _mm_aesimc_si128(K13)); _mm_storeu_si128(DK_mm + 2, _mm_aesimc_si128(K12)); _mm_storeu_si128(DK_mm + 3, _mm_aesimc_si128(K11)); _mm_storeu_si128(DK_mm + 4, _mm_aesimc_si128(K10)); _mm_storeu_si128(DK_mm + 5, _mm_aesimc_si128(K9)); _mm_storeu_si128(DK_mm + 6, _mm_aesimc_si128(K8)); _mm_storeu_si128(DK_mm + 7, _mm_aesimc_si128(K7)); _mm_storeu_si128(DK_mm + 8, _mm_aesimc_si128(K6)); _mm_storeu_si128(DK_mm + 9, _mm_aesimc_si128(K5)); _mm_storeu_si128(DK_mm + 10, _mm_aesimc_si128(K4)); _mm_storeu_si128(DK_mm + 11, _mm_aesimc_si128(K3)); _mm_storeu_si128(DK_mm + 12, _mm_aesimc_si128(K2)); _mm_storeu_si128(DK_mm + 13, _mm_aesimc_si128(K1)); _mm_storeu_si128(DK_mm + 14, K0); } void aesni_256_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[60]) { const __m128i K0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key)); const __m128i K1 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(input_key + 16)); const __m128i K2 = aes_128_key_expansion(K0, _mm_aeskeygenassist_si128(K1, 0x01)); const __m128i K3 = aes_256_key_expansion(K1, K2); const __m128i K4 = aes_128_key_expansion(K2, _mm_aeskeygenassist_si128(K3, 0x02)); const __m128i K5 = aes_256_key_expansion(K3, K4); const __m128i K6 = aes_128_key_expansion(K4, _mm_aeskeygenassist_si128(K5, 0x04)); const __m128i K7 = aes_256_key_expansion(K5, K6); const __m128i K8 = aes_128_key_expansion(K6, _mm_aeskeygenassist_si128(K7, 0x08)); const __m128i K9 = aes_256_key_expansion(K7, K8); const __m128i K10 = aes_128_key_expansion(K8, _mm_aeskeygenassist_si128(K9, 0x10)); const __m128i K11 = aes_256_key_expansion(K9, K10); const __m128i K12 = aes_128_key_expansion(K10, _mm_aeskeygenassist_si128(K11, 0x20)); const __m128i K13 = aes_256_key_expansion(K11, K12); const __m128i K14 = aes_128_key_expansion(K12, _mm_aeskeygenassist_si128(K13, 0x40)); __m128i* EK_mm = reinterpret_cast<__m128i*>(encryption_keys); _mm_storeu_si128(EK_mm , K0); _mm_storeu_si128(EK_mm + 1, K1); _mm_storeu_si128(EK_mm + 2, K2); _mm_storeu_si128(EK_mm + 3, K3); _mm_storeu_si128(EK_mm + 4, K4); _mm_storeu_si128(EK_mm + 5, K5); _mm_storeu_si128(EK_mm + 6, K6); _mm_storeu_si128(EK_mm + 7, K7); _mm_storeu_si128(EK_mm + 8, K8); _mm_storeu_si128(EK_mm + 9, K9); _mm_storeu_si128(EK_mm + 10, K10); _mm_storeu_si128(EK_mm + 11, K11); _mm_storeu_si128(EK_mm + 12, K12); _mm_storeu_si128(EK_mm + 13, K13); _mm_storeu_si128(EK_mm + 14, K14); } #undef AES_ENC_4_ROUNDS #undef AES_ENC_4_LAST_ROUNDS #undef AES_DEC_4_ROUNDS #undef AES_DEC_4_LAST_ROUNDS #else #include <arm_neon.h> inline void load_le(uint32_t* output, const uint8_t* input, size_t count) { //Not dealing with endianness right now //std::memcpy(output, reinterpret_cast<const uint32_t*>(input), count); std::memcpy(output, input, count * sizeof(uint32_t)); } uint8x16_t aeskeygenassist_si8x16(uint8x16_t a, const int rcon) { // AESE does ShiftRows and SubBytes on A uint8x16_t u8 = vaeseq_u8(a, vdupq_n_u8(0)); uint8x16_t dest = { // Undo ShiftRows step from AESE and extract X1 and X3 u8[0x4], u8[0x1], u8[0xE], u8[0xB], // SubBytes(X1) u8[0x1], u8[0xE], u8[0xB], u8[0x4], // ROT(SubBytes(X1)) u8[0xC], u8[0x9], u8[0x6], u8[0x3], // SubBytes(X3) u8[0x9], u8[0x6], u8[0x3], u8[0xC], // ROT(SubBytes(X3)) }; uint32x4_t r = {0, (unsigned) rcon, 0, (unsigned) rcon}; return veorq_u8(dest, vreinterpretq_u8_u32(r)); } uint8x16_t aes_128_key_expansion(uint8x16_t key, uint8x16_t key_with_rcon) { //_mm_shuffle_epi32_splat((a), 3); // key_with_rcon = vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key_with_rcon), 3))); //vextq_s8((key, vdupq_n_u8(0), 16 - 4) key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); return veorq_u8(key, key_with_rcon); } void aes_192_key_expansion(uint8x16_t* K1, uint8x16_t* K2, uint8x16_t key2_with_rcon, uint32_t out[], bool last) { uint8x16_t key1 = *K1; uint8x16_t key2 = *K2; key2_with_rcon = vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key2_with_rcon), 1))); key1 = veorq_u8(key1, vextq_u8(vdupq_n_u8(0), key1, 16 - 4)); key1 = veorq_u8(key1, vextq_u8(vdupq_n_u8(0), key1, 16 - 4)); key1 = veorq_u8(key1, vextq_u8(vdupq_n_u8(0), key1, 16 - 4)); key1 = veorq_u8(key1, key2_with_rcon); *K1 = key1; vst1q_u8(reinterpret_cast<uint8_t*>(out), key1); if(last) return; key2 = veorq_u8(key2, vextq_u8(vdupq_n_u8(0), key2, 16 - 4)); key2 = veorq_u8(key2, vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key1), 3)))); *K2 = key2; out[4] = vgetq_lane_u32(vreinterpretq_u32_u8(key2), 0); out[5] = vgetq_lane_u32(vreinterpretq_u32_u8(vextq_u8(key2, vdupq_n_u8(0), 16 - 12)), 0); } /* * The second half of the AES-256 key expansion (other half same as AES-128) */ uint8x16_t aes_256_key_expansion(uint8x16_t key, uint8x16_t key2) { uint8x16_t key_with_rcon = aeskeygenassist_si8x16(key2, 0x00); key_with_rcon = vreinterpretq_u8_u32(vdupq_n_u32(vgetq_lane_u32(vreinterpretq_u32_u8(key_with_rcon), 2))); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); key = veorq_u8(key, vextq_u8(vdupq_n_u8(0), key, 16 - 4)); return veorq_u8(key, key_with_rcon); } #define AES_ENC_4_ROUNDS(K) \ do \ { \ B0 = vaesmcq_u8(vaeseq_u8(B0, K)); \ B1 = vaesmcq_u8(vaeseq_u8(B1, K)); \ B2 = vaesmcq_u8(vaeseq_u8(B2, K)); \ B3 = vaesmcq_u8(vaeseq_u8(B3, K)); \ } while(0) #define AES_ENC_4_LAST_ROUNDS(K, K2) \ do \ { \ B0 = veorq_u8(vaeseq_u8(B0, K), K2); \ B1 = veorq_u8(vaeseq_u8(B1, K), K2); \ B2 = veorq_u8(vaeseq_u8(B2, K), K2); \ B3 = veorq_u8(vaeseq_u8(B3, K), K2); \ } while(0) #define AES_DEC_4_ROUNDS(K) \ do \ { \ B0 = vaesimcq_u8(vaesdq_u8(B0, K)); \ B1 = vaesimcq_u8(vaesdq_u8(B1, K)); \ B2 = vaesimcq_u8(vaesdq_u8(B2, K)); \ B3 = vaesimcq_u8(vaesdq_u8(B3, K)); \ } while(0) #define AES_DEC_4_LAST_ROUNDS(K, K2) \ do \ { \ B0 = veorq_u8(vaesdq_u8(B0, K), K2); \ B1 = veorq_u8(vaesdq_u8(B1, K), K2); \ B2 = veorq_u8(vaesdq_u8(B2, K), K2); \ B3 = veorq_u8(vaesdq_u8(B3, K), K2); \ } while(0) /* * AES-128 Encryption */ void aesni_128_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[44]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(encryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); while(blocks >= 4){ uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_ENC_4_ROUNDS(K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_LAST_ROUNDS(K9, K10); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesmcq_u8(vaeseq_u8(B, K0)); B = vaesmcq_u8(vaeseq_u8(B, K1)); B = vaesmcq_u8(vaeseq_u8(B, K2)); B = vaesmcq_u8(vaeseq_u8(B, K3)); B = vaesmcq_u8(vaeseq_u8(B, K4)); B = vaesmcq_u8(vaeseq_u8(B, K5)); B = vaesmcq_u8(vaeseq_u8(B, K6)); B = vaesmcq_u8(vaeseq_u8(B, K7)); B = vaesmcq_u8(vaeseq_u8(B, K8)); B = veorq_u8(vaeseq_u8(B, K9), K10); vst1q_u8(out+16*i, B); } } /* * AES-128 Decryption */ void aesni_128_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[44]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(decryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); while(blocks >= 4){ uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_DEC_4_ROUNDS(K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_LAST_ROUNDS(K9, K10); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i){ uint8x16_t B = vld1q_u8(in+16*i); B = vaesimcq_u8(vaesdq_u8(B, K0)); B = vaesimcq_u8(vaesdq_u8(B, K1)); B = vaesimcq_u8(vaesdq_u8(B, K2)); B = vaesimcq_u8(vaesdq_u8(B, K3)); B = vaesimcq_u8(vaesdq_u8(B, K4)); B = vaesimcq_u8(vaesdq_u8(B, K5)); B = vaesimcq_u8(vaesdq_u8(B, K6)); B = vaesimcq_u8(vaesdq_u8(B, K7)); B = vaesimcq_u8(vaesdq_u8(B, K8)); B = veorq_u8(vaesdq_u8(B, K9), K10); vst1q_u8(out+16*i, B); } } /* * AES-128 Key Schedule */ void aesni_128_key_schedule(const uint8_t key[], uint32_t encryption_keys[44], uint32_t decryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, aeskeygenassist_si8x16(K, RCON)) const uint8x16_t K0 = vld1q_u8(key); const uint8x16_t K1 = AES_128_key_exp(K0, 0x01); const uint8x16_t K2 = AES_128_key_exp(K1, 0x02); const uint8x16_t K3 = AES_128_key_exp(K2, 0x04); const uint8x16_t K4 = AES_128_key_exp(K3, 0x08); const uint8x16_t K5 = AES_128_key_exp(K4, 0x10); const uint8x16_t K6 = AES_128_key_exp(K5, 0x20); const uint8x16_t K7 = AES_128_key_exp(K6, 0x40); const uint8x16_t K8 = AES_128_key_exp(K7, 0x80); const uint8x16_t K9 = AES_128_key_exp(K8, 0x1B); const uint8x16_t K10 = AES_128_key_exp(K9, 0x36); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; // Now generate decryption keys uint8x16_t* DK_mm = reinterpret_cast<uint8x16_t*>(decryption_keys); DK_mm[0] = K10; DK_mm[1] = vaesimcq_u8(K9); DK_mm[2] = vaesimcq_u8(K8); DK_mm[3] = vaesimcq_u8(K7); DK_mm[4] = vaesimcq_u8(K6); DK_mm[5] = vaesimcq_u8(K5); DK_mm[6] = vaesimcq_u8(K4); DK_mm[7] = vaesimcq_u8(K3); DK_mm[8] = vaesimcq_u8(K2); DK_mm[9] = vaesimcq_u8(K1); DK_mm[10] = K0; } void aesni_128_key_schedule_only_encryption(const uint8_t key[], uint32_t encryption_keys[44]) { #define AES_128_key_exp(K, RCON) \ aes_128_key_expansion(K, aeskeygenassist_si8x16(K, RCON)) const uint8x16_t K0 = vld1q_u8(key); const uint8x16_t K1 = AES_128_key_exp(K0, 0x01); const uint8x16_t K2 = AES_128_key_exp(K1, 0x02); const uint8x16_t K3 = AES_128_key_exp(K2, 0x04); const uint8x16_t K4 = AES_128_key_exp(K3, 0x08); const uint8x16_t K5 = AES_128_key_exp(K4, 0x10); const uint8x16_t K6 = AES_128_key_exp(K5, 0x20); const uint8x16_t K7 = AES_128_key_exp(K6, 0x40); const uint8x16_t K8 = AES_128_key_exp(K7, 0x80); const uint8x16_t K9 = AES_128_key_exp(K8, 0x1B); const uint8x16_t K10 = AES_128_key_exp(K9, 0x36); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; } /* * AES-192 Encryption */ void aesni_192_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[52]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(encryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_ENC_4_ROUNDS(K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_LAST_ROUNDS(K11, K12); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesmcq_u8(vaeseq_u8(B, K0)); B = vaesmcq_u8(vaeseq_u8(B, K1)); B = vaesmcq_u8(vaeseq_u8(B, K2)); B = vaesmcq_u8(vaeseq_u8(B, K3)); B = vaesmcq_u8(vaeseq_u8(B, K4)); B = vaesmcq_u8(vaeseq_u8(B, K5)); B = vaesmcq_u8(vaeseq_u8(B, K6)); B = vaesmcq_u8(vaeseq_u8(B, K7)); B = vaesmcq_u8(vaeseq_u8(B, K8)); B = vaesmcq_u8(vaeseq_u8(B, K9)); B = vaesmcq_u8(vaeseq_u8(B, K10)); B = veorq_u8(vaeseq_u8(B, K11), K12); vst1q_u8(out+16*i, B); } } /* * AES-192 Decryption */ void aesni_192_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[52]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(decryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_DEC_4_ROUNDS(K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_LAST_ROUNDS(K11, K12); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesimcq_u8(vaesdq_u8(B, K0)); B = vaesimcq_u8(vaesdq_u8(B, K1)); B = vaesimcq_u8(vaesdq_u8(B, K2)); B = vaesimcq_u8(vaesdq_u8(B, K3)); B = vaesimcq_u8(vaesdq_u8(B, K4)); B = vaesimcq_u8(vaesdq_u8(B, K5)); B = vaesimcq_u8(vaesdq_u8(B, K6)); B = vaesimcq_u8(vaesdq_u8(B, K7)); B = vaesimcq_u8(vaesdq_u8(B, K8)); B = vaesimcq_u8(vaesdq_u8(B, K9)); B = vaesimcq_u8(vaesdq_u8(B, K10)); B = veorq_u8(vaesdq_u8(B, K11), K12); vst1q_u8(out+16*i, B); } } /* * AES-192 Key Schedule */ void aesni_192_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[52], uint32_t decryption_keys[52]) { uint8x16_t K0 = vld1q_u8(input_key); uint8x16_t K1 = vld1q_u8(input_key + 8); //vextq_u8 K1 = vextq_u8(K1, vdupq_n_u8(0), 16 - 8); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ aeskeygenassist_si8x16(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp // Now generate decryption keys const uint8x16_t* EK_mm = reinterpret_cast<const uint8x16_t*>(encryption_keys); uint8x16_t* DK_mm = reinterpret_cast<uint8x16_t*>(decryption_keys); DK_mm[0] = EK_mm[12]; DK_mm[1] = vaesimcq_u8(EK_mm[11]); DK_mm[2] = vaesimcq_u8(EK_mm[10]); DK_mm[3] = vaesimcq_u8(EK_mm[9]); DK_mm[4] = vaesimcq_u8(EK_mm[8]); DK_mm[5] = vaesimcq_u8(EK_mm[7]); DK_mm[6] = vaesimcq_u8(EK_mm[6]); DK_mm[7] = vaesimcq_u8(EK_mm[5]); DK_mm[8] = vaesimcq_u8(EK_mm[4]); DK_mm[9] = vaesimcq_u8(EK_mm[3]); DK_mm[10] = vaesimcq_u8(EK_mm[2]); DK_mm[11] = vaesimcq_u8(EK_mm[1]); DK_mm[12] = EK_mm[0]; } void aesni_192_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[52]) { uint8x16_t K0 = vld1q_u8(input_key); uint8x16_t K1 = vld1q_u8(input_key + 8); K1 = vextq_u8(vdupq_n_u8(0), K1, 16 - 4); load_le(encryption_keys, input_key, 6); #define AES_192_key_exp(RCON, EK_OFF) \ aes_192_key_expansion(&K0, &K1, \ aeskeygenassist_si8x16(K1, RCON), \ (uint32_t*)(&encryption_keys[EK_OFF]), EK_OFF == 48) AES_192_key_exp(0x01, 6); AES_192_key_exp(0x02, 12); AES_192_key_exp(0x04, 18); AES_192_key_exp(0x08, 24); AES_192_key_exp(0x10, 30); AES_192_key_exp(0x20, 36); AES_192_key_exp(0x40, 42); AES_192_key_exp(0x80, 48); #undef AES_192_key_exp } /* * AES-256 Encryption */ void aesni_256_encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t encryption_keys[60]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(encryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); const uint8x16_t K13 = vld1q_u8(skey + 13*16); const uint8x16_t K14 = vld1q_u8(skey + 14*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_ENC_4_ROUNDS(K0); AES_ENC_4_ROUNDS(K1); AES_ENC_4_ROUNDS(K2); AES_ENC_4_ROUNDS(K3); AES_ENC_4_ROUNDS(K4); AES_ENC_4_ROUNDS(K5); AES_ENC_4_ROUNDS(K6); AES_ENC_4_ROUNDS(K7); AES_ENC_4_ROUNDS(K8); AES_ENC_4_ROUNDS(K9); AES_ENC_4_ROUNDS(K10); AES_ENC_4_ROUNDS(K11); AES_ENC_4_ROUNDS(K12); AES_ENC_4_LAST_ROUNDS(K13, K14); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesmcq_u8(vaeseq_u8(B, K0)); B = vaesmcq_u8(vaeseq_u8(B, K1)); B = vaesmcq_u8(vaeseq_u8(B, K2)); B = vaesmcq_u8(vaeseq_u8(B, K3)); B = vaesmcq_u8(vaeseq_u8(B, K4)); B = vaesmcq_u8(vaeseq_u8(B, K5)); B = vaesmcq_u8(vaeseq_u8(B, K6)); B = vaesmcq_u8(vaeseq_u8(B, K7)); B = vaesmcq_u8(vaeseq_u8(B, K8)); B = vaesmcq_u8(vaeseq_u8(B, K9)); B = vaesmcq_u8(vaeseq_u8(B, K10)); B = vaesmcq_u8(vaeseq_u8(B, K11)); B = vaesmcq_u8(vaeseq_u8(B, K12)); B = veorq_u8(vaeseq_u8(B, K13), K14); vst1q_u8(out+16*i, B); } } /* * AES-256 Decryption */ void aesni_256_decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks, uint32_t decryption_keys[60]) { const uint8_t *skey = reinterpret_cast<const uint8_t*>(decryption_keys); const uint8x16_t K0 = vld1q_u8(skey + 0*16); const uint8x16_t K1 = vld1q_u8(skey + 1*16); const uint8x16_t K2 = vld1q_u8(skey + 2*16); const uint8x16_t K3 = vld1q_u8(skey + 3*16); const uint8x16_t K4 = vld1q_u8(skey + 4*16); const uint8x16_t K5 = vld1q_u8(skey + 5*16); const uint8x16_t K6 = vld1q_u8(skey + 6*16); const uint8x16_t K7 = vld1q_u8(skey + 7*16); const uint8x16_t K8 = vld1q_u8(skey + 8*16); const uint8x16_t K9 = vld1q_u8(skey + 9*16); const uint8x16_t K10 = vld1q_u8(skey + 10*16); const uint8x16_t K11 = vld1q_u8(skey + 11*16); const uint8x16_t K12 = vld1q_u8(skey + 12*16); const uint8x16_t K13 = vld1q_u8(skey + 13*16); const uint8x16_t K14 = vld1q_u8(skey + 14*16); while(blocks >= 4) { uint8x16_t B0 = vld1q_u8(in); uint8x16_t B1 = vld1q_u8(in+16); uint8x16_t B2 = vld1q_u8(in+32); uint8x16_t B3 = vld1q_u8(in+48); AES_DEC_4_ROUNDS(K0); AES_DEC_4_ROUNDS(K1); AES_DEC_4_ROUNDS(K2); AES_DEC_4_ROUNDS(K3); AES_DEC_4_ROUNDS(K4); AES_DEC_4_ROUNDS(K5); AES_DEC_4_ROUNDS(K6); AES_DEC_4_ROUNDS(K7); AES_DEC_4_ROUNDS(K8); AES_DEC_4_ROUNDS(K9); AES_DEC_4_ROUNDS(K10); AES_DEC_4_ROUNDS(K11); AES_DEC_4_ROUNDS(K12); AES_DEC_4_LAST_ROUNDS(K13, K14); vst1q_u8(out, B0); vst1q_u8(out+16, B1); vst1q_u8(out+32, B2); vst1q_u8(out+48, B3); in += 16*4; out += 16*4; blocks -= 4; } for(size_t i = 0; i != blocks; ++i) { uint8x16_t B = vld1q_u8(in+16*i); B = vaesimcq_u8(vaesdq_u8(B, K0)); B = vaesimcq_u8(vaesdq_u8(B, K1)); B = vaesimcq_u8(vaesdq_u8(B, K2)); B = vaesimcq_u8(vaesdq_u8(B, K3)); B = vaesimcq_u8(vaesdq_u8(B, K4)); B = vaesimcq_u8(vaesdq_u8(B, K5)); B = vaesimcq_u8(vaesdq_u8(B, K6)); B = vaesimcq_u8(vaesdq_u8(B, K7)); B = vaesimcq_u8(vaesdq_u8(B, K8)); B = vaesimcq_u8(vaesdq_u8(B, K9)); B = vaesimcq_u8(vaesdq_u8(B, K10)); B = vaesimcq_u8(vaesdq_u8(B, K11)); B = vaesimcq_u8(vaesdq_u8(B, K12)); B = veorq_u8(vaesdq_u8(B, K13), K14); vst1q_u8(out+16*i, B); } } /* * AES-256 Key Schedule */ void aesni_256_key_schedule(const uint8_t input_key[], uint32_t encryption_keys[60], uint32_t decryption_keys[60]) { const uint8x16_t K0 = vld1q_u8(input_key); const uint8x16_t K1 = vld1q_u8(input_key + 16); const uint8x16_t K2 = aes_128_key_expansion(K0, aeskeygenassist_si8x16(K1, 0x01)); const uint8x16_t K3 = aes_256_key_expansion(K1, K2); const uint8x16_t K4 = aes_128_key_expansion(K2, aeskeygenassist_si8x16(K3, 0x02)); const uint8x16_t K5 = aes_256_key_expansion(K3, K4); const uint8x16_t K6 = aes_128_key_expansion(K4, aeskeygenassist_si8x16(K5, 0x04)); const uint8x16_t K7 = aes_256_key_expansion(K5, K6); const uint8x16_t K8 = aes_128_key_expansion(K6, aeskeygenassist_si8x16(K7, 0x08)); const uint8x16_t K9 = aes_256_key_expansion(K7, K8); const uint8x16_t K10 = aes_128_key_expansion(K8, aeskeygenassist_si8x16(K9, 0x10)); const uint8x16_t K11 = aes_256_key_expansion(K9, K10); const uint8x16_t K12 = aes_128_key_expansion(K10, aeskeygenassist_si8x16(K11, 0x20)); const uint8x16_t K13 = aes_256_key_expansion(K11, K12); const uint8x16_t K14 = aes_128_key_expansion(K12, aeskeygenassist_si8x16(K13, 0x40)); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; EK_mm[11] = K11; EK_mm[12] = K12; EK_mm[13] = K13; EK_mm[14] = K14; // Now generate decryption keys uint8x16_t* DK_mm = reinterpret_cast<uint8x16_t*>(decryption_keys); DK_mm[0] = K14; DK_mm[1] = vaesimcq_u8(K13); DK_mm[2] = vaesimcq_u8(K12); DK_mm[3] = vaesimcq_u8(K11); DK_mm[4] = vaesimcq_u8(K10); DK_mm[5] = vaesimcq_u8(K9); DK_mm[6] = vaesimcq_u8(K8); DK_mm[7] = vaesimcq_u8(K7); DK_mm[8] = vaesimcq_u8(K6); DK_mm[9] = vaesimcq_u8(K5); DK_mm[10] = vaesimcq_u8(K4); DK_mm[11] = vaesimcq_u8(K3); DK_mm[12] = vaesimcq_u8(K2); DK_mm[13] = vaesimcq_u8(K1); DK_mm[14] = K0; } void aesni_256_key_schedule_only_encryption(const uint8_t input_key[], uint32_t encryption_keys[60]) { const uint8x16_t K0 = vld1q_u8(input_key); const uint8x16_t K1 = vld1q_u8(input_key + 16); const uint8x16_t K2 = aes_128_key_expansion(K0, aeskeygenassist_si8x16(K1, 0x01)); const uint8x16_t K3 = aes_256_key_expansion(K1, K2); const uint8x16_t K4 = aes_128_key_expansion(K2, aeskeygenassist_si8x16(K3, 0x02)); const uint8x16_t K5 = aes_256_key_expansion(K3, K4); const uint8x16_t K6 = aes_128_key_expansion(K4, aeskeygenassist_si8x16(K5, 0x04)); const uint8x16_t K7 = aes_256_key_expansion(K5, K6); const uint8x16_t K8 = aes_128_key_expansion(K6, aeskeygenassist_si8x16(K7, 0x08)); const uint8x16_t K9 = aes_256_key_expansion(K7, K8); const uint8x16_t K10 = aes_128_key_expansion(K8, aeskeygenassist_si8x16(K9, 0x10)); const uint8x16_t K11 = aes_256_key_expansion(K9, K10); const uint8x16_t K12 = aes_128_key_expansion(K10, aeskeygenassist_si8x16(K11, 0x20)); const uint8x16_t K13 = aes_256_key_expansion(K11, K12); const uint8x16_t K14 = aes_128_key_expansion(K12, aeskeygenassist_si8x16(K13, 0x40)); uint8x16_t* EK_mm = reinterpret_cast<uint8x16_t*>(encryption_keys); EK_mm[0] = K0; EK_mm[1] = K1; EK_mm[2] = K2; EK_mm[3] = K3; EK_mm[4] = K4; EK_mm[5] = K5; EK_mm[6] = K6; EK_mm[7] = K7; EK_mm[8] = K8; EK_mm[9] = K9; EK_mm[10] = K10; EK_mm[11] = K11; EK_mm[12] = K12; EK_mm[13] = K13; EK_mm[14] = K14; } #undef AES_ENC_4_ROUNDS #undef AES_ENC_4_LAST_ROUNDS #undef AES_DEC_4_ROUNDS #undef AES_DEC_4_LAST_ROUNDS #endif
32.424352
115
0.667162
GeneralZero
2bd79a6efcf241f9c3607775a3638f7dd580c149
20,831
cpp
C++
src/vulkan/memory.cpp
eundersander/bps3D
be0a725f74df8512204628bde8fcf5ba510f8643
[ "MIT" ]
9
2021-04-02T17:16:13.000Z
2022-02-04T19:47:48.000Z
src/vulkan/memory.cpp
eundersander/bps3D
be0a725f74df8512204628bde8fcf5ba510f8643
[ "MIT" ]
1
2021-06-22T22:27:35.000Z
2021-06-26T03:42:07.000Z
src/vulkan/memory.cpp
eundersander/bps3D
be0a725f74df8512204628bde8fcf5ba510f8643
[ "MIT" ]
1
2021-07-26T23:58:53.000Z
2021-07-26T23:58:53.000Z
#include "memory.hpp" #include <vulkan/vulkan_core.h> #include "utils.hpp" #include "config.hpp" #include <cstring> #include <iostream> using namespace std; namespace bps3D { namespace vk { namespace BufferFlags { static constexpr VkBufferUsageFlags commonUsage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; static constexpr VkBufferUsageFlags stageUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; static constexpr VkBufferUsageFlags geometryUsage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT; static constexpr VkBufferUsageFlags shaderUsage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; static constexpr VkBufferUsageFlags paramUsage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; static constexpr VkBufferUsageFlags hostRTUsage = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; static constexpr VkBufferUsageFlags hostUsage = stageUsage | shaderUsage | paramUsage; static constexpr VkBufferUsageFlags indirectUsage = VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; static constexpr VkBufferUsageFlags localUsage = commonUsage | geometryUsage | shaderUsage | indirectUsage; static constexpr VkBufferUsageFlags dedicatedUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; static constexpr VkBufferUsageFlags rtGeometryUsage = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; static constexpr VkBufferUsageFlags rtAccelScratchUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; static constexpr VkBufferUsageFlags rtAccelUsage = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; static constexpr VkBufferUsageFlags localRTUsage = rtGeometryUsage | rtAccelScratchUsage | rtAccelUsage; }; namespace ImageFlags { static constexpr VkFormatFeatureFlags textureReqs = VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; static constexpr VkImageUsageFlags textureUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; static constexpr VkImageUsageFlags colorAttachmentUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; static constexpr VkFormatFeatureFlags colorAttachmentReqs = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_TRANSFER_SRC_BIT; static constexpr VkImageUsageFlags depthAttachmentUsage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; static constexpr VkFormatFeatureFlags depthAttachmentReqs = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_FORMAT_FEATURE_TRANSFER_SRC_BIT; static constexpr VkImageUsageFlags rtStorageUsage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; static constexpr VkFormatFeatureFlags rtStorageReqs = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT; }; template <bool host_mapped> void AllocDeleter<host_mapped>::operator()(VkBuffer buffer) const { if (mem_ == VK_NULL_HANDLE) return; const DeviceState &dev = alloc_.dev; if constexpr (host_mapped) { dev.dt.unmapMemory(dev.hdl, mem_); } dev.dt.freeMemory(dev.hdl, mem_, nullptr); dev.dt.destroyBuffer(dev.hdl, buffer, nullptr); } template <> void AllocDeleter<false>::operator()(VkImage image) const { if (mem_ == VK_NULL_HANDLE) return; const DeviceState &dev = alloc_.dev; dev.dt.freeMemory(dev.hdl, mem_, nullptr); dev.dt.destroyImage(dev.hdl, image, nullptr); } template <bool host_mapped> void AllocDeleter<host_mapped>::clear() { mem_ = VK_NULL_HANDLE; } HostBuffer::HostBuffer(VkBuffer buf, void *p, VkMappedMemoryRange mem_range, AllocDeleter<true> deleter) : buffer(buf), ptr(p), mem_range_(mem_range), deleter_(deleter) {} HostBuffer::HostBuffer(HostBuffer &&o) : buffer(o.buffer), ptr(o.ptr), mem_range_(o.mem_range_), deleter_(o.deleter_) { o.deleter_.clear(); } HostBuffer::~HostBuffer() { deleter_(buffer); } void HostBuffer::flush(const DeviceState &dev) { dev.dt.flushMappedMemoryRanges(dev.hdl, 1, &mem_range_); } void HostBuffer::flush(const DeviceState &dev, VkDeviceSize offset, VkDeviceSize num_bytes) { VkMappedMemoryRange sub_range = mem_range_; sub_range.offset = offset; sub_range.size = num_bytes; dev.dt.flushMappedMemoryRanges(dev.hdl, 1, &sub_range); } LocalBuffer::LocalBuffer(VkBuffer buf, AllocDeleter<false> deleter) : buffer(buf), deleter_(deleter) {} LocalBuffer::LocalBuffer(LocalBuffer &&o) : buffer(o.buffer), deleter_(o.deleter_) { o.deleter_.clear(); } LocalBuffer::~LocalBuffer() { deleter_(buffer); } LocalImage::LocalImage(uint32_t w, uint32_t h, uint32_t mip_levels, VkImage img, AllocDeleter<false> deleter) : width(w), height(h), mipLevels(mip_levels), image(img), deleter_(deleter) {} LocalImage::LocalImage(LocalImage &&o) : width(o.width), height(o.height), mipLevels(o.mipLevels), image(o.image), deleter_(o.deleter_) { o.deleter_.clear(); } LocalImage::~LocalImage() { deleter_(image); } static VkFormatProperties2 getFormatProperties(const InstanceState &inst, VkPhysicalDevice phy, VkFormat fmt) { VkFormatProperties2 props; props.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2; props.pNext = nullptr; inst.dt.getPhysicalDeviceFormatProperties2(phy, fmt, &props); return props; } template <size_t N> static VkFormat chooseFormat(VkPhysicalDevice phy, const InstanceState &inst, VkFormatFeatureFlags required_features, const array<VkFormat, N> &desired_formats) { for (auto fmt : desired_formats) { VkFormatProperties2 props = getFormatProperties(inst, phy, fmt); if ((props.formatProperties.optimalTilingFeatures & required_features) == required_features) { return fmt; } } cerr << "Unable to find required features in given formats" << endl; fatalExit(); } static pair<VkBuffer, VkMemoryRequirements> makeUnboundBuffer( const DeviceState &dev, VkDeviceSize num_bytes, VkBufferUsageFlags usage) { VkBufferCreateInfo buffer_info; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.pNext = nullptr; buffer_info.flags = 0; buffer_info.size = num_bytes; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkBuffer buffer; REQ_VK(dev.dt.createBuffer(dev.hdl, &buffer_info, nullptr, &buffer)); VkMemoryRequirements reqs; dev.dt.getBufferMemoryRequirements(dev.hdl, buffer, &reqs); return pair(buffer, reqs); } static VkImage makeImage(const DeviceState &dev, uint32_t width, uint32_t height, uint32_t mip_levels, VkFormat format, VkImageUsageFlags usage, VkImageCreateFlags img_flags = 0) { VkImageCreateInfo img_info; img_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; img_info.pNext = nullptr; img_info.flags = img_flags; img_info.imageType = VK_IMAGE_TYPE_2D; img_info.format = format; img_info.extent = {width, height, 1}; img_info.mipLevels = mip_levels; img_info.arrayLayers = 1; img_info.samples = VK_SAMPLE_COUNT_1_BIT; img_info.tiling = VK_IMAGE_TILING_OPTIMAL; img_info.usage = usage; img_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; img_info.queueFamilyIndexCount = 0; img_info.pQueueFamilyIndices = nullptr; img_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VkImage img; REQ_VK(dev.dt.createImage(dev.hdl, &img_info, nullptr, &img)); return img; } uint32_t findMemoryTypeIndex(uint32_t allowed_type_bits, VkMemoryPropertyFlags required_props, VkPhysicalDeviceMemoryProperties2 &mem_props) { uint32_t num_mems = mem_props.memoryProperties.memoryTypeCount; for (uint32_t idx = 0; idx < num_mems; idx++) { uint32_t mem_type_bits = (1 << idx); if (!(allowed_type_bits & mem_type_bits)) continue; VkMemoryPropertyFlags supported_props = mem_props.memoryProperties.memoryTypes[idx].propertyFlags; if ((required_props & supported_props) == required_props) { return idx; } } cerr << "Failed to find desired memory type" << endl; fatalExit(); } static VkMemoryRequirements getImageMemReqs(const DeviceState &dev, VkImage img) { VkMemoryRequirements reqs; dev.dt.getImageMemoryRequirements(dev.hdl, img, &reqs); return reqs; } static MemoryTypeIndices findTypeIndices(const DeviceState &dev, const InstanceState &inst, const ResourceFormats &formats) { auto get_generic_buffer_reqs = [&](VkBufferUsageFlags usage_flags) { auto [test_buffer, reqs] = makeUnboundBuffer(dev, 1, usage_flags); dev.dt.destroyBuffer(dev.hdl, test_buffer, nullptr); return reqs; }; auto get_generic_image_reqs = [&](VkFormat format, VkImageUsageFlags usage_flags, VkImageCreateFlags img_flags = 0) { VkImage test_image = makeImage(dev, 1, 1, 1, format, usage_flags, img_flags); VkMemoryRequirements reqs = getImageMemReqs(dev, test_image); dev.dt.destroyImage(dev.hdl, test_image, nullptr); return reqs; }; VkPhysicalDeviceMemoryProperties2 dev_mem_props; dev_mem_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2; dev_mem_props.pNext = nullptr; inst.dt.getPhysicalDeviceMemoryProperties2(dev.phy, &dev_mem_props); VkMemoryRequirements host_generic_reqs = get_generic_buffer_reqs(BufferFlags::hostUsage); uint32_t host_type_idx = findMemoryTypeIndex(host_generic_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, dev_mem_props); VkMemoryRequirements buffer_local_reqs = get_generic_buffer_reqs(BufferFlags::localUsage); VkMemoryRequirements tex_local_reqs = get_generic_image_reqs(formats.texture, ImageFlags::textureUsage); uint32_t local_type_idx = findMemoryTypeIndex( buffer_local_reqs.memoryTypeBits & tex_local_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); VkMemoryRequirements dedicated_reqs = get_generic_buffer_reqs(BufferFlags::dedicatedUsage); uint32_t dedicated_type_idx = findMemoryTypeIndex( dedicated_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); VkMemoryRequirements color_attachment_reqs = get_generic_image_reqs( formats.colorAttachment, ImageFlags::colorAttachmentUsage); uint32_t color_attachment_idx = findMemoryTypeIndex( color_attachment_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); VkMemoryRequirements depth_attachment_reqs = get_generic_image_reqs( formats.depthAttachment, ImageFlags::depthAttachmentUsage); uint32_t depth_attachment_idx = findMemoryTypeIndex( depth_attachment_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); return MemoryTypeIndices { host_type_idx, local_type_idx, dedicated_type_idx, color_attachment_idx, depth_attachment_idx, }; } static Alignments getMemoryAlignments(const InstanceState &inst, VkPhysicalDevice phy) { VkPhysicalDeviceProperties2 props {}; props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; inst.dt.getPhysicalDeviceProperties2(phy, &props); return Alignments { props.properties.limits.minUniformBufferOffsetAlignment, props.properties.limits.minStorageBufferOffsetAlignment}; } MemoryAllocator::MemoryAllocator(const DeviceState &d, const InstanceState &inst) : dev(d), formats_ { chooseFormat(dev.phy, inst, ImageFlags::textureReqs, array {VK_FORMAT_BC7_UNORM_BLOCK}), chooseFormat(dev.phy, inst, ImageFlags::colorAttachmentReqs, array {VK_FORMAT_R8G8B8A8_UNORM}), chooseFormat( dev.phy, inst, ImageFlags::depthAttachmentReqs, array {VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT}), chooseFormat(dev.phy, inst, ImageFlags::colorAttachmentReqs, array {VK_FORMAT_R32_SFLOAT}), }, type_indices_(findTypeIndices(dev, inst, formats_)), alignments_(getMemoryAlignments(inst, dev.phy)), local_buffer_usage_flags_(BufferFlags::localUsage) {} HostBuffer MemoryAllocator::makeHostBuffer(VkDeviceSize num_bytes, VkBufferUsageFlags usage) { auto [buffer, reqs] = makeUnboundBuffer(dev, num_bytes, usage); VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_indices_.host; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindBufferMemory(dev.hdl, buffer, memory, 0)); void *mapped_ptr; REQ_VK(dev.dt.mapMemory(dev.hdl, memory, 0, reqs.size, 0, &mapped_ptr)); VkMappedMemoryRange range; range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range.pNext = nullptr; range.memory = memory, range.offset = 0; range.size = VK_WHOLE_SIZE; return HostBuffer(buffer, mapped_ptr, range, AllocDeleter<true>(memory, *this)); } HostBuffer MemoryAllocator::makeStagingBuffer(VkDeviceSize num_bytes) { return makeHostBuffer(num_bytes, BufferFlags::stageUsage); } HostBuffer MemoryAllocator::makeParamBuffer(VkDeviceSize num_bytes) { return makeHostBuffer(num_bytes, BufferFlags::commonUsage | BufferFlags::shaderUsage | BufferFlags::paramUsage); } optional<LocalBuffer> MemoryAllocator::makeLocalBuffer( VkDeviceSize num_bytes, VkBufferUsageFlags usage) { auto [buffer, reqs] = makeUnboundBuffer(dev, num_bytes, usage); VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_indices_.local; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindBufferMemory(dev.hdl, buffer, memory, 0)); return LocalBuffer(buffer, AllocDeleter<false>(memory, *this)); } optional<LocalBuffer> MemoryAllocator::makeLocalBuffer(VkDeviceSize num_bytes) { return makeLocalBuffer(num_bytes, local_buffer_usage_flags_); } optional<LocalBuffer> MemoryAllocator::makeIndirectBuffer( VkDeviceSize num_bytes) { return makeLocalBuffer(num_bytes, BufferFlags::commonUsage | BufferFlags::shaderUsage | BufferFlags::indirectUsage); } pair<LocalBuffer, VkDeviceMemory> MemoryAllocator::makeDedicatedBuffer( VkDeviceSize num_bytes) { auto [buffer, reqs] = makeUnboundBuffer(dev, num_bytes, BufferFlags::dedicatedUsage); VkMemoryDedicatedAllocateInfo dedicated; dedicated.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; dedicated.pNext = nullptr; dedicated.image = VK_NULL_HANDLE; dedicated.buffer = buffer; VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = &dedicated; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_indices_.dedicatedBuffer; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindBufferMemory(dev.hdl, buffer, memory, 0)); return pair(LocalBuffer(buffer, AllocDeleter<false>(memory, *this)), memory); } pair<LocalTexture, TextureRequirements> MemoryAllocator::makeTexture( uint32_t width, uint32_t height, uint32_t mip_levels) { VkImage texture_img = makeImage(dev, width, height, mip_levels, formats_.texture, ImageFlags::textureUsage); auto reqs = getImageMemReqs(dev, texture_img); return { LocalTexture { width, height, mip_levels, texture_img, }, TextureRequirements { reqs.alignment, reqs.size, }, }; } void MemoryAllocator::destroyTexture(LocalTexture &&texture) { dev.dt.destroyImage(dev.hdl, texture.image, nullptr); } optional<VkDeviceMemory> MemoryAllocator::alloc(VkDeviceSize num_bytes) { VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; alloc.allocationSize = num_bytes; alloc.memoryTypeIndex = type_indices_.local; VkDeviceMemory mem; VkResult res = dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &mem); if (res == VK_ERROR_OUT_OF_DEVICE_MEMORY) { return optional<VkDeviceMemory>(); } return mem; } LocalImage MemoryAllocator::makeDedicatedImage(uint32_t width, uint32_t height, uint32_t mip_levels, VkFormat format, VkImageUsageFlags usage, uint32_t type_idx) { auto img = makeImage(dev, width, height, mip_levels, format, usage); auto reqs = getImageMemReqs(dev, img); VkMemoryDedicatedAllocateInfo dedicated; dedicated.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; dedicated.pNext = nullptr; dedicated.image = img; dedicated.buffer = VK_NULL_HANDLE; VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = &dedicated; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_idx; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindImageMemory(dev.hdl, img, memory, 0)); return LocalImage(width, height, mip_levels, img, AllocDeleter<false>(memory, *this)); } LocalImage MemoryAllocator::makeColorAttachment(uint32_t width, uint32_t height) { return makeDedicatedImage(width, height, 1, formats_.colorAttachment, ImageFlags::colorAttachmentUsage, type_indices_.colorAttachment); } LocalImage MemoryAllocator::makeDepthAttachment(uint32_t width, uint32_t height) { return makeDedicatedImage(width, height, 1, formats_.depthAttachment, ImageFlags::depthAttachmentUsage, type_indices_.depthAttachment); } LocalImage MemoryAllocator::makeLinearDepthAttachment(uint32_t width, uint32_t height) { return makeDedicatedImage(width, height, 1, formats_.linearDepthAttachment, ImageFlags::colorAttachmentUsage, type_indices_.colorAttachment); } VkDeviceSize MemoryAllocator::alignUniformBufferOffset( VkDeviceSize offset) const { return alignOffset(offset, alignments_.uniformBuffer); } VkDeviceSize MemoryAllocator::alignStorageBufferOffset( VkDeviceSize offset) const { return alignOffset(offset, alignments_.storageBuffer); } } }
31.998464
79
0.681052
eundersander
2bda52c3a52f8cc9f8c5e5d7d2099af28122dee2
20,268
hh
C++
graph-tool-2.27/src/graph/inference/blockmodel/graph_blockmodel_partition.hh
Znigneering/CSCI-3154
bc318efc73d2a80025b98f5b3e4f7e4819e952e4
[ "MIT" ]
null
null
null
graph-tool-2.27/src/graph/inference/blockmodel/graph_blockmodel_partition.hh
Znigneering/CSCI-3154
bc318efc73d2a80025b98f5b3e4f7e4819e952e4
[ "MIT" ]
null
null
null
graph-tool-2.27/src/graph/inference/blockmodel/graph_blockmodel_partition.hh
Znigneering/CSCI-3154
bc318efc73d2a80025b98f5b3e4f7e4819e952e4
[ "MIT" ]
null
null
null
// graph-tool -- a general graph modification and manipulation thingy // // Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de> // // 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 3 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU 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/>. #ifndef GRAPH_BLOCKMODEL_PARTITION_HH #define GRAPH_BLOCKMODEL_PARTITION_HH #include "../support/util.hh" #include "../support/int_part.hh" namespace graph_tool { // =============== // Partition stats // =============== constexpr size_t null_group = std::numeric_limits<size_t>::max(); typedef vprop_map_t<std::vector<std::tuple<size_t, size_t, size_t>>>::type degs_map_t; struct simple_degs_t {}; template <class Graph, class Vprop, class Eprop, class F> __attribute__((always_inline)) __attribute__((flatten)) inline void degs_op(size_t v, Vprop& vweight, Eprop& eweight, const simple_degs_t&, Graph& g, F&& f) { f(in_degreeS()(v, g, eweight), out_degreeS()(v, g, eweight), vweight[v]); } template <class Graph, class Vprop, class Eprop, class F> __attribute__((always_inline)) __attribute__((flatten)) inline void degs_op(size_t v, Vprop& vweight, Eprop& eweight, const typename degs_map_t::unchecked_t& degs, Graph& g, F&& f) { auto& ks = degs[v]; if (ks.empty()) { degs_op(v, vweight, eweight, simple_degs_t(), g, std::forward<F>(f)); } else { for (auto& k : ks) f(get<0>(k), get<1>(k), get<2>(k)); } } template <bool use_rmap> class partition_stats { public: typedef gt_hash_map<pair<size_t,size_t>, int> map_t; template <class Graph, class Vprop, class VWprop, class Eprop, class Degs, class Mprop, class Vlist> partition_stats(Graph& g, Vprop& b, Vlist& vlist, size_t E, size_t B, VWprop& vweight, Eprop& eweight, Degs& degs, const Mprop& ignore_degree, std::vector<size_t>& bmap, bool allow_empty) : _bmap(bmap), _N(0), _E(E), _total_B(B), _allow_empty(allow_empty) { if (!use_rmap) { _hist.resize(num_vertices(g)); _total.resize(num_vertices(g)); _ep.resize(num_vertices(g)); _em.resize(num_vertices(g)); } for (auto v : vlist) { if (vweight[v] == 0) continue; auto r = get_r(b[v]); if (v >= _ignore_degree.size()) _ignore_degree.resize(v + 1, 0); _ignore_degree[v] = ignore_degree[v]; degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto kout, auto n) { if (_ignore_degree[v] == 2) kout = 0; if (_ignore_degree[v] != 1) { _hist[r][make_pair(kin, kout)] += n; _em[r] += kin * n; _ep[r] += kout * n; } _total[r] += n; _N += n; }); } _actual_B = 0; for (auto n : _total) { if (n > 0) _actual_B++; } } size_t get_r(size_t r) { if (use_rmap) { constexpr size_t null = std::numeric_limits<size_t>::max(); if (r >= _bmap.size()) _bmap.resize(r + 1, null); size_t nr = _bmap[r]; if (nr == null) nr = _bmap[r] = _hist.size(); r = nr; } if (r >= _hist.size()) { _hist.resize(r + 1); _total.resize(r + 1); _ep.resize(r + 1); _em.resize(r + 1); } return r; } double get_partition_dl() { double S = 0; if (_allow_empty) S += lbinom(_total_B + _N - 1, _N); else S += lbinom(_N - 1, _actual_B - 1); S += lgamma_fast(_N + 1); for (auto nr : _total) S -= lgamma_fast(nr + 1); S += safelog_fast(_N); return S; } template <class Rs, class Ks> double get_deg_dl_ent(Rs&& rs, Ks&& ks) { double S = 0; for (auto r : rs) { r = get_r(r); size_t total = 0; if (ks.empty()) { for (auto& k_c : _hist[r]) { S -= xlogx_fast(k_c.second); total += k_c.second; } } else { auto& h = _hist[r]; for (auto& k : ks) { auto iter = h.find(k); auto k_c = (iter != h.end()) ? iter->second : 0; S -= xlogx(k_c); } total = _total[r]; } S += xlogx_fast(total); } return S; } template <class Rs, class Ks> double get_deg_dl_uniform(Rs&& rs, Ks&&) { double S = 0; for (auto r : rs) { r = get_r(r); S += lbinom(_total[r] + _ep[r] - 1, _ep[r]); S += lbinom(_total[r] + _em[r] - 1, _em[r]); } return S; } template <class Rs, class Ks> double get_deg_dl_dist(Rs&& rs, Ks&& ks) { double S = 0; for (auto r : rs) { r = get_r(r); S += log_q(_ep[r], _total[r]); S += log_q(_em[r], _total[r]); size_t total = 0; if (ks.empty()) { for (auto& k_c : _hist[r]) { S -= lgamma_fast(k_c.second + 1); total += k_c.second; } } else { auto& h = _hist[r]; for (auto& k : ks) { auto iter = h.find(k); auto k_c = (iter != h.end()) ? iter->second : 0; S -= lgamma_fast(k_c + 1); } total = _total[r]; } S += lgamma_fast(total + 1); } return S; } template <class Rs, class Ks> double get_deg_dl(int kind, Rs&& rs, Ks&& ks) { switch (kind) { case deg_dl_kind::ENT: return get_deg_dl_ent(rs, ks); case deg_dl_kind::UNIFORM: return get_deg_dl_uniform(rs, ks); case deg_dl_kind::DIST: return get_deg_dl_dist(rs, ks); default: return numeric_limits<double>::quiet_NaN(); } } double get_deg_dl(int kind) { return get_deg_dl(kind, boost::counting_range(size_t(0), _total_B), std::array<std::pair<size_t,size_t>,0>()); } template <class Graph> double get_edges_dl(size_t B, Graph& g) { size_t BB = (graph_tool::is_directed(g)) ? B * B : (B * (B + 1)) / 2; return lbinom(BB + _E - 1, _E); } template <class VProp> double get_delta_partition_dl(size_t v, size_t r, size_t nr, VProp& vweight) { if (r == nr) return 0; if (r != null_group) r = get_r(r); if (nr != null_group) nr = get_r(nr); int n = vweight[v]; if (n == 0) { if (r == null_group) n = 1; else return 0; } double S_b = 0, S_a = 0; if (r != null_group) { S_b += -lgamma_fast(_total[r] + 1); S_a += -lgamma_fast(_total[r] - n + 1); } if (nr != null_group) { S_b += -lgamma_fast(_total[nr] + 1); S_a += -lgamma_fast(_total[nr] + n + 1); } int dN = 0; if (r == null_group) dN += n; if (nr == null_group) dN -= n; S_b += lgamma_fast(_N + 1); S_a += lgamma_fast(_N + dN + 1); int dB = 0; if (r != null_group && _total[r] == n) dB--; if (nr != null_group && _total[nr] == 0) dB++; if ((dN != 0 || dB != 0) && !_allow_empty) { S_b += lbinom_fast(_N - 1, _actual_B - 1); S_a += lbinom_fast(_N - 1 + dN, _actual_B + dB - 1); } if (dN != 0) { S_b += safelog_fast(_N); S_a += safelog_fast(_N + dN); } return S_a - S_b; } template <class VProp, class Graph> double get_delta_edges_dl(size_t v, size_t r, size_t nr, VProp& vweight, size_t actual_B, Graph& g) { if (r == nr || _allow_empty) return 0; if (r != null_group) r = get_r(r); if (nr != null_group) nr = get_r(nr); double S_b = 0, S_a = 0; int n = vweight[v]; if (n == 0) { if (r == null_group) n = 1; else return 0; } int dB = 0; if (r != null_group && _total[r] == n) dB--; if (nr != null_group && _total[nr] == 0) dB++; if (dB != 0) { S_b += get_edges_dl(actual_B, g); S_a += get_edges_dl(actual_B + dB, g); } return S_a - S_b; } template <class Graph, class VProp, class EProp, class Degs> double get_delta_deg_dl(size_t v, size_t r, size_t nr, VProp& vweight, EProp& eweight, Degs& degs, Graph& g, int kind) { if (r == nr || _ignore_degree[v] == 1 || vweight[v] == 0) return 0; if (r != null_group) r = get_r(r); if (nr != null_group) nr = get_r(nr); auto dop = [&](auto&& f) { if (_ignore_degree[v] == 2) { degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto, auto n) { f(kin, 0, n); }); } else { degs_op(v, vweight, eweight, degs, g, [&](auto... k) { f(k...); }); } }; double dS = 0; switch (kind) { case deg_dl_kind::ENT: if (r != null_group) dS += get_delta_deg_dl_ent_change(r, dop, -1); if (nr != null_group) dS += get_delta_deg_dl_ent_change(nr, dop, +1); break; case deg_dl_kind::UNIFORM: if (r != null_group) dS += get_delta_deg_dl_uniform_change(v, r, dop, -1); if (nr != null_group) dS += get_delta_deg_dl_uniform_change(v, nr, dop, +1); break; case deg_dl_kind::DIST: if (r != null_group) dS += get_delta_deg_dl_dist_change(v, r, dop, -1); if (nr != null_group) dS += get_delta_deg_dl_dist_change(v, nr, dop, +1); break; default: dS = numeric_limits<double>::quiet_NaN(); } return dS; } template <class DegOP> double get_delta_deg_dl_ent_change(size_t r, DegOP&& dop, int diff) { int nr = _total[r]; auto get_Sk = [&](size_t s, pair<size_t, size_t>& deg, int delta) { int nd = 0; auto iter = _hist[s].find(deg); if (iter != _hist[s].end()) nd = iter->second; assert(nd + delta >= 0); return -xlogx_fast(nd + delta); }; double S_b = 0, S_a = 0; int dn = 0; dop([&](size_t kin, size_t kout, int nk) { dn += diff * nk; auto deg = make_pair(kin, kout); S_b += get_Sk(r, deg, 0); S_a += get_Sk(r, deg, diff * nk); }); S_b += xlogx_fast(nr); S_a += xlogx_fast(nr + dn); return S_a - S_b; } template <class DegOP> double get_delta_deg_dl_uniform_change(size_t v, size_t r, DegOP&& dop, int diff) { auto get_Se = [&](int dn, int dkin, int dkout) { double S = 0; S += lbinom_fast(_total[r] + dn + _ep[r] - 1 + dkout, _ep[r] + dkout); S += lbinom_fast(_total[r] + dn + _em[r] - 1 + dkin, _em[r] + dkin); return S; }; double S_b = 0, S_a = 0; int tkin = 0, tkout = 0, n = 0; dop([&](auto kin, auto kout, int nk) { tkin += kin * nk; if (_ignore_degree[v] != 2) tkout += kout * nk; n += nk; }); S_b += get_Se( 0, 0, 0); S_a += get_Se(diff * n, diff * tkin, diff * tkout); return S_a - S_b; } template <class DegOP> double get_delta_deg_dl_dist_change(size_t v, size_t r, DegOP&& dop, int diff) { auto get_Se = [&](int delta, int kin, int kout) { double S = 0; assert(_total[r] + delta >= 0); assert(_em[r] + kin >= 0); assert(_ep[r] + kout >= 0); S += log_q(_em[r] + kin, _total[r] + delta); S += log_q(_ep[r] + kout, _total[r] + delta); return S; }; auto get_Sr = [&](int delta) { assert(_total[r] + delta + 1 >= 0); return lgamma_fast(_total[r] + delta + 1); }; auto get_Sk = [&](pair<size_t, size_t>& deg, int delta) { int nd = 0; auto iter = _hist[r].find(deg); if (iter != _hist[r].end()) nd = iter->second; assert(nd + delta >= 0); return -lgamma_fast(nd + delta + 1); }; double S_b = 0, S_a = 0; int tkin = 0, tkout = 0, n = 0; dop([&](size_t kin, size_t kout, int nk) { tkin += kin * nk; if (_ignore_degree[v] != 2) tkout += kout * nk; n += nk; auto deg = make_pair(kin, kout); S_b += get_Sk(deg, 0); S_a += get_Sk(deg, diff * nk); }); S_b += get_Se( 0, 0, 0); S_a += get_Se(diff * n, diff * tkin, diff * tkout); S_b += get_Sr( 0); S_a += get_Sr(diff * n); return S_a - S_b; } template <class Graph, class VWeight, class EWeight, class Degs> void change_vertex(size_t v, size_t r, bool deg_corr, Graph& g, VWeight& vweight, EWeight& eweight, Degs& degs, int diff) { int vw = vweight[v]; int dv = vw * diff; if (_total[r] == 0 && dv > 0) _actual_B++; if (_total[r] == vw && dv < 0) _actual_B--; _total[r] += dv; _N += dv; assert(_total[r] >= 0); if (deg_corr && _ignore_degree[v] != 1) { degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto kout, auto n) { int dk = diff * n; if (_ignore_degree[v] == 2) kout = 0; auto& h = _hist[r]; auto deg = make_pair(kin, kout); auto iter = h.insert({deg, 0}).first; iter->second += dk; if (iter->second == 0) h.erase(iter); _em[r] += dk * deg.first; _ep[r] += dk * deg.second; }); } } template <class Graph, class VWeight, class EWeight, class Degs> void remove_vertex(size_t v, size_t r, bool deg_corr, Graph& g, VWeight& vweight, EWeight& eweight, Degs& degs) { if (r == null_group || vweight[v] == 0) return; r = get_r(r); change_vertex(v, r, deg_corr, g, vweight, eweight, degs, -1); } template <class Graph, class VWeight, class EWeight, class Degs> void add_vertex(size_t v, size_t nr, bool deg_corr, Graph& g, VWeight& vweight, EWeight& eweight, Degs& degs) { if (nr == null_group || vweight[v] == 0) return; nr = get_r(nr); change_vertex(v, nr, deg_corr, g, vweight, eweight, degs, 1); } void change_k(size_t v, size_t r, bool deg_corr, int vweight, int kin, int kout, int diff) { if (_total[r] == 0 && diff * vweight > 0) _actual_B++; if (_total[r] == vweight && diff * vweight < 0) _actual_B--; _total[r] += diff * vweight; _N += diff * vweight; assert(_total[r] >= 0); if (deg_corr && _ignore_degree[v] != 1) { if (_ignore_degree[v] == 2) kout = 0; auto deg = make_pair(kin, kout); auto iter = _hist[r].insert({deg, 0}).first; iter->second += diff * vweight; if (iter->second == 0) _hist[r].erase(iter); _em[r] += diff * deg.first * vweight; _ep[r] += diff * deg.second * vweight; } } void change_E(int dE) { _E += dE; } size_t get_N() { return _N; } size_t get_E() { return _E; } size_t get_actual_B() { return _actual_B; } void add_block() { _total_B++; } template <class Graph, class VProp, class VWeight, class EWeight, class Degs> bool check_degs(Graph& g, VProp& b, VWeight& vweight, EWeight& eweight, Degs& degs) { vector<map_t> dhist; for (auto v : vertices_range(g)) { degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto kout, auto n) { auto r = get_r(b[v]); if (r >= dhist.size()) dhist.resize(r + 1); dhist[r][{kin, kout}] += n; }); } for (size_t r = 0; r < dhist.size(); ++r) { for (auto& kn : dhist[r]) { auto count = (r >= _hist.size()) ? 0 : _hist[r][kn.first]; if (kn.second != count) { assert(false); return false; } } } for (size_t r = 0; r < _hist.size(); ++r) { for (auto& kn : _hist[r]) { auto count = (r >= dhist.size()) ? 0 : dhist[r][kn.first]; if (kn.second != count) { assert(false); return false; } } } return true; } private: vector<size_t>& _bmap; size_t _N; size_t _E; size_t _actual_B; size_t _total_B; bool _allow_empty; vector<map_t> _hist; vector<int> _total; vector<int> _ep; vector<int> _em; vector<uint8_t> _ignore_degree; }; } //namespace graph_tool #endif // GRAPH_BLOCKMODEL_PARTITION_HH
28.506329
87
0.433886
Znigneering
2bdf37205f44b62d3314760437b00baa263f64ea
5,437
cc
C++
deprected/tests/testUtils.cc
RobertWeber1/cli
5cb67325610be41014403e9342dddbe942511c2b
[ "MIT" ]
null
null
null
deprected/tests/testUtils.cc
RobertWeber1/cli
5cb67325610be41014403e9342dddbe942511c2b
[ "MIT" ]
null
null
null
deprected/tests/testUtils.cc
RobertWeber1/cli
5cb67325610be41014403e9342dddbe942511c2b
[ "MIT" ]
null
null
null
#include "testUtils.h" namespace CLI { std::ostream & operator<<( std::ostream & os, border::Element::Type type ) { switch(type) { case border::Element::NONE: return os << "NONE"; case border::Element::UNUSED_1: return os << "UNUSED_1"; case border::Element::UNUSED_2: return os << "UNUSED_2"; case border::Element::TOP_RIGHT: return os << "TOP_RIGHT"; case border::Element::UNUSED_4: return os << "UNUSED_4"; case border::Element::VERTICAL: return os << "VERTICAL"; case border::Element::BOTTOM_RIGHT: return os << "BOTTOM_RIGHT"; case border::Element::TEE_RIGHT: return os << "TEE_RIGHT"; case border::Element::UNUSED_8: return os << "UNUSED_8"; case border::Element::TOP_LEFT: return os << "TOP_LEFT"; case border::Element::HORIZONTAL: return os << "HORIZONTAL"; case border::Element::TEE_TOP: return os << "TEE_TOP"; case border::Element::BOTTOM_LEFT: return os << "BOTTOM_LEFT"; case border::Element::TEE_LEFT: return os << "TEE_LEFT"; case border::Element::TEE_BOTTOM: return os << "TEE_BOTTOM"; case border::Element::CROSS: return os << "CROSS"; case border::Element::INVERT: return os << "INVERT"; default: return os; } } std::ostream & operator<<( std::ostream & os, util::Color color ) { switch(color) { case util::BLACK: return os << "BLACK"; case util::WHITE: return os << "WHITE"; case util::RED: return os << "RED"; case util::GREEN: return os << "GREEN"; case util::BLUE: return os << "BLUE"; case util::YELLOW: return os << "YELLOW"; case util::CYAN: return os << "CYAN"; case util::MAGENTA: return os << "MAGENTA"; default: return os; } } std::ostream & operator<<( std::ostream & os, util::Attribute attr ) { switch(attr) { case util::NONE: return os << "NONE"; case util::BOLD: return os << "BOLD"; case util::DIM: return os << "DIM"; case util::UNDERSCORE: return os << "UNDERSCORE"; case util::BLINK: return os << "BLINK"; case util::INVERSE: return os << "INVERSE"; case util::HIDDEN: return os << "HIDDEN"; default: return os; } } std::string to_string( util::Point const& point ) { std::stringstream result; result << "P(x: " << point.x() << ", y: " << point.y() << ")"; return result.str(); } std::string to_string( util::Size const& size ) { std::stringstream result; result << "S(w: " << size.width() << ", h: " << size.height() << ")"; return result.str(); } std::string to_string( util::Properties const& prop ) { std::stringstream result; result << "Prop(fg: " << prop.foreground << ", bg: " << prop.background << ", attr: " << prop.attribute << ")"; return result.str(); } std::string to_string( util::SizeConstraint const& constraint ) { std::stringstream result; result << "C(min: " << constraint.min_val() << ", max: " << constraint.max_val() << ", f: " << constraint.factor() << ")"; return result.str(); } std::string to_string( util::SizeHint const& size_hint ) { std::stringstream result; result << "Hwidth: " << to_string(size_hint.width()) << ", Hheight:" << to_string(size_hint.height()); return result.str(); } std::string to_string( border::Buffer & buffer ) { char char_map[16] = { ' ',//NONE = 0b00000, '0',//UNUSED_1 = 0b00001, '0',//UNUSED_2 = 0b00010, '7',//BOTTOM_LEFT = 0b00011, '0',//UNUSED_4 = 0b00100, '|',//VERTICAL = 0b00101, '1',//TOP_LEFT = 0b00110, '8',//TEE_RIGHT = 0b00111, '0',//UNUSED_8 = 0b01000, '5',//BOTTOM_RIGHT = 0b01001, '-',//HORIZONTAL = 0b01010, '6',//TEE_TOP = 0b01011, '3',//TOP_RIGHT = 0b01100, '4',//TEE_LEFT = 0b01101, '2',//TEE_BOTTOM = 0b01110, '+' //CROSS = 0b01111, }; char inv_map[16] = { ' ',//NONE = 0b00000, '0',//UNUSED_1 = 0b00001, '0',//UNUSED_2 = 0b00010, 'G',//BOTTOM_LEFT = 0b00011, '0',//UNUSED_4 = 0b00100, '#',//VERTICAL = 0b00101, 'A',//TOP_LEFT = 0b00110, 'H',//TEE_RIGHT = 0b00111, '0',//UNUSED_8 = 0b01000, 'E',//BOTTOM_RIGHT = 0b01001, '=',//HORIZONTAL = 0b01010, 'F',//TEE_TOP = 0b01011, 'C',//TOP_RIGHT = 0b01100, 'D',//TEE_LEFT = 0b01101, 'B',//TEE_BOTTOM = 0b01110, '%' //CROSS = 0b01111, }; std::stringstream borders; util::Point pos; border::Element *element; while( element = buffer.get( pos ) ) { while( element = buffer.get( pos ) ) { //borders << element->to_char(char_map); if(element->is_inverted()) { borders << element->to_char(inv_map); } else { borders << element->to_char(char_map); } pos.right(); } borders << "\n"; pos.break_line(); } return borders.str(); } }
22.654167
126
0.516093
RobertWeber1
2be0a0591693cedab8027e17ff5eb7b1c8decde3
1,090
cpp
C++
compiler-rt/test/hwasan/TestCases/hwasan-print-shadow.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
605
2019-10-18T01:15:54.000Z
2022-03-31T14:31:04.000Z
compiler-rt/test/hwasan/TestCases/hwasan-print-shadow.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
3,180
2019-10-18T01:21:21.000Z
2022-03-31T23:25:41.000Z
compiler-rt/test/hwasan/TestCases/hwasan-print-shadow.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
275
2019-10-18T05:27:22.000Z
2022-03-30T09:04:21.000Z
// RUN: %clangxx_hwasan -DSIZE=16 -O0 %s -o %t && %run %t 2>&1 | FileCheck %s // REQUIRES: stable-runtime #include <assert.h> #include <stdlib.h> #include <sys/mman.h> #include <sanitizer/hwasan_interface.h> int main() { char *alloc = (char *)malloc(4096); // Simulate short granule tags. alloc[15] = 0x00; alloc[31] = 0xbb; alloc[47] = 0xcc; alloc[63] = 0xdd; alloc[79] = 0xee; alloc[95] = 0xff; // __hwasan_tag_memory expects untagged pointers. char *p = (char *)__hwasan_tag_pointer(alloc, 0); assert(p); // Write tags to shadow. __hwasan_tag_memory(p, 1, 32); __hwasan_tag_memory(p + 32, 16, 16); __hwasan_tag_memory(p + 48, 0, 32); __hwasan_tag_memory(p + 80, 4, 16); char *q = (char *)__hwasan_tag_pointer(p, 7); __hwasan_print_shadow(q + 5, 89 - 5); // CHECK: HWASan shadow map for {{.*}}5 .. {{.*}}9 (pointer tag 7) // CHECK-NEXT: {{.*}}0: 01(00) // CHECK-NEXT: {{.*}}0: 01(bb) // CHECK-NEXT: {{.*}}0: 10 // CHECK-NEXT: {{.*}}0: 00 // CHECK-NEXT: {{.*}}0: 00 // CHECK-NEXT: {{.*}}0: 04(ff) free(alloc); }
25.348837
77
0.588991
LaudateCorpus1
2be19475ad2ab5415710e71a0674f69bf112b811
414
cpp
C++
string/reverse_str.cpp
Nilesh-Das/mustdogfg
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
[ "MIT" ]
null
null
null
string/reverse_str.cpp
Nilesh-Das/mustdogfg
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
[ "MIT" ]
null
null
null
string/reverse_str.cpp
Nilesh-Das/mustdogfg
bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ll long long using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); char s[] = "nilesh"; int n = sizeof(s) / sizeof(s[0]); // n i l e s h \0 // | | // p q char *p = s; char *q = s+n-2; for(int i=0; i<n/2; i++) { char tmp = *p; *p = *q; *q = tmp; p++, q--; } cout << s << '\n'; return 0; }
12.9375
35
0.437198
Nilesh-Das
2be29870fca8eb3477aa9735f905229a84b70bfc
1,028
cpp
C++
SD/examples/SdDemo_DumpFile.cpp
draperlaboratory/hope-FreeRTOS-RISC-V_Galois_demo
8607c3d80a8e3e2e0be2570a09eb1623eff7ec31
[ "Apache-2.0" ]
3
2019-07-29T20:38:15.000Z
2020-11-23T02:02:43.000Z
SD/examples/SdDemo_DumpFile.cpp
draperlaboratory/hope-FreeRTOS-RISC-V_Galois_demo
8607c3d80a8e3e2e0be2570a09eb1623eff7ec31
[ "Apache-2.0" ]
3
2019-02-18T17:38:45.000Z
2020-12-01T22:42:39.000Z
SD/examples/SdDemo_DumpFile.cpp
draperlaboratory/hope-FreeRTOS-RISC-V_Galois_demo
8607c3d80a8e3e2e0be2570a09eb1623eff7ec31
[ "Apache-2.0" ]
8
2019-01-24T01:10:50.000Z
2020-06-03T10:44:39.000Z
#include "SD.h" #include <cstdio> // set up variables using the SD utility library functions: Sd2Card card; SdVolume volume; SdFile root; extern "C" { void sd_demo(void); } void sd_demo() { printf("Initializing SD card...\r\n"); // see if the card is present and can be initialized: if (!SD.begin(0)) { printf("Card failed, or not present\r\n"); // don't do anything more: while (1); } printf("card initialized.\r\n"); // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("busybox.txt"); // if the file is available, write to it: if (dataFile) { uint8_t cnt = 0; while (dataFile.available()) { if (cnt == 0) { printf("\r\n"); } cnt++; printf("%c",dataFile.read()); } printf("\r\nClosing file\r\n"); dataFile.close(); } // if the file isn't open, pop up an error: else { printf("error opening file"); } printf("Done!\r\n"); }
21.87234
66
0.600195
draperlaboratory
2be38001463a315b44133d37b03d640b82b8033a
487
cpp
C++
c/otros/actividad_3.cpp
joseluis8906/tests
df222f4bbef0ed4a3bfb53ebc2d1fd44179551f4
[ "MIT" ]
null
null
null
c/otros/actividad_3.cpp
joseluis8906/tests
df222f4bbef0ed4a3bfb53ebc2d1fd44179551f4
[ "MIT" ]
null
null
null
c/otros/actividad_3.cpp
joseluis8906/tests
df222f4bbef0ed4a3bfb53ebc2d1fd44179551f4
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; double celcius_a_fahrenheit (double celcius) { double fahrenheit = ((celcius * 9.0)/5.0) + 32.0; return fahrenheit; } //función principal int main () { double grados_celcius; cout << "Ingrese los grados celcius para pasarlos a Fahrenheit" << endl; cin >> grados_celcius; cout << "La conversión es: " << grados_celcius << "ºC" << " = " << celcius_a_fahrenheit (grados_celcius) << "ºF." << endl; }
19.48
123
0.679671
joseluis8906
2be4c5c6a09c112e30d6970ea523b989fcfff30f
2,164
cpp
C++
CppSprtPkg/Library/CppSprtLib.cpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
CppSprtPkg/Library/CppSprtLib.cpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
CppSprtPkg/Library/CppSprtLib.cpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
/* ## @file # # Copyright (c) 2018 Loongson Technology Corporation Limited (www.loongson.cn). # All intellectual property rights(Copyright, Patent and Trademark) reserved. # # Any violations of copyright or other intellectual property rights of the Loongson Technology # Corporation Limited will be held accountable in accordance with the law, # if you (or any of your subsidiaries, corporate affiliates or agents) initiate # directly or indirectly any Intellectual Property Assertion or Intellectual Property Litigation: # (i) against Loongson Technology Corporation Limited or any of its subsidiaries or corporate affiliates, # (ii) against any party if such Intellectual Property Assertion or Intellectual Property Litigation arises # in whole or in part from any software, technology, product or service of Loongson Technology Corporation # Limited or any of its subsidiaries or corporate affiliates, or (iii) against any party relating to the Software. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR # 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). # # ## */ extern"C" { #include <Uefi.h> #include <Library/UefiBootServicesTableLib.h> } #undef NULL #define NULL 0 VOID *operator new(UINTN Size) throw() { VOID *RetVal; EFI_STATUS Status; if (Size == 0) { return NULL; } Status = gBS->AllocatePool(EfiLoaderData, (UINTN)Size, &RetVal); if (Status != EFI_SUCCESS) { RetVal = NULL; } return RetVal; } VOID *operator new[](UINTN cb) { VOID *res = operator new(cb); return res; } VOID operator delete(VOID *p) { if (p != NULL) { (VOID)gBS->FreePool(p); } } VOID operator delete[](VOID *p) { operator delete(p); } extern "C" VOID _Unwind_Resume(struct _Unwind_Exception *object) { } #include "CppCrt.cpp"
28.853333
127
0.738447
lvjianmin-loongson
2be9da4048dffd57fe1da32467399d8dd97e9984
428
cc
C++
CommonTools/RecoAlgos/plugins/CaloMETShallowCloneProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
CommonTools/RecoAlgos/plugins/CaloMETShallowCloneProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
CommonTools/RecoAlgos/plugins/CaloMETShallowCloneProducer.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
#include "DataFormats/EgammaCandidates/interface/ElectronFwd.h" #include "DataFormats/METReco/interface/CaloMET.h" #include "DataFormats/METReco/interface/CaloMETCollection.h" #include "CommonTools/CandAlgos/interface/ShallowCloneProducer.h" typedef ShallowCloneProducer<reco::CaloMETCollection> CaloMETShallowCloneProducer; #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(CaloMETShallowCloneProducer);
38.909091
82
0.859813
ckamtsikis
2bea4ce280ffbef1824ab318a8ec6f5b5edd4445
5,537
hxx
C++
Modules/Core/Common/include/itkVector.hxx
khangthk/ITK
f3c12edaf9cef07dbc34107e1a8aec9859204116
[ "Apache-2.0" ]
null
null
null
Modules/Core/Common/include/itkVector.hxx
khangthk/ITK
f3c12edaf9cef07dbc34107e1a8aec9859204116
[ "Apache-2.0" ]
null
null
null
Modules/Core/Common/include/itkVector.hxx
khangthk/ITK
f3c12edaf9cef07dbc34107e1a8aec9859204116
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkVector_hxx #define itkVector_hxx #include "itkMath.h" #include "vnl/vnl_vector.h" #include "itkObject.h" #include "itkNumericTraitsVectorPixel.h" namespace itk { template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension>::Vector(const ValueType & r) : Superclass{ r } {} template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> & Vector<T, TVectorDimension>::operator=(const ValueType r[TVectorDimension]) { BaseArray::operator=(r); return *this; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::operator+=(const Self & vec) -> const Self & { for (unsigned int i = 0; i < TVectorDimension; ++i) { (*this)[i] += vec[i]; } return *this; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::operator-=(const Self & vec) -> const Self & { for (unsigned int i = 0; i < TVectorDimension; ++i) { (*this)[i] -= vec[i]; } return *this; } template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> Vector<T, TVectorDimension>::operator-() const { Self result; for (unsigned int i = 0; i < TVectorDimension; ++i) { result[i] = -(*this)[i]; } return result; } template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> Vector<T, TVectorDimension>::operator+(const Self & vec) const { Self result; for (unsigned int i = 0; i < TVectorDimension; ++i) { result[i] = (*this)[i] + vec[i]; } return result; } template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> Vector<T, TVectorDimension>::operator-(const Self & vec) const { Self result; for (unsigned int i = 0; i < TVectorDimension; ++i) { result[i] = (*this)[i] - vec[i]; } return result; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::GetSquaredNorm() const -> RealValueType { typename NumericTraits<RealValueType>::AccumulateType sum = NumericTraits<T>::ZeroValue(); for (unsigned int i = 0; i < TVectorDimension; ++i) { const RealValueType value = (*this)[i]; sum += value * value; } return sum; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::GetNorm() const -> RealValueType { return RealValueType(std::sqrt(static_cast<double>(this->GetSquaredNorm()))); } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::Normalize() -> RealValueType { const RealValueType norm = this->GetNorm(); if (norm < NumericTraits<RealValueType>::epsilon()) { return norm; // Prevent division by 0 } const RealValueType inversedNorm = 1.0 / norm; for (unsigned int i = 0; i < TVectorDimension; ++i) { (*this)[i] = static_cast<T>(static_cast<RealValueType>((*this)[i] * inversedNorm)); } return norm; } template <typename T, unsigned int TVectorDimension> vnl_vector_ref<T> Vector<T, TVectorDimension>::GetVnlVector() { return vnl_vector_ref<T>(TVectorDimension, this->GetDataPointer()); } template <typename T, unsigned int TVectorDimension> vnl_vector<T> Vector<T, TVectorDimension>::GetVnlVector() const { // Return a vector_ref<>. This will be automatically converted to a // vnl_vector<>. We have to use a const_cast<> which would normally // be prohibited in a const method, but it is safe to do here // because the cast to vnl_vector<> will ultimately copy the data. return vnl_vector_ref<T>(TVectorDimension, const_cast<T *>(this->GetDataPointer())); } template <typename T, unsigned int TVectorDimension> void Vector<T, TVectorDimension>::SetVnlVector(const vnl_vector<T> & v) { for (unsigned int i = 0; i < v.size(); ++i) { (*this)[i] = v(i); } } template <typename T, unsigned int TVectorDimension> std::ostream & operator<<(std::ostream & os, const Vector<T, TVectorDimension> & vct) { os << "["; if (TVectorDimension == 1) { os << vct[0]; } else { for (unsigned int i = 0; i + 1 < TVectorDimension; ++i) { os << vct[i] << ", "; } os << vct[TVectorDimension - 1]; } os << "]"; return os; } template <typename T, unsigned int TVectorDimension> std::istream & operator>>(std::istream & is, Vector<T, TVectorDimension> & vct) { for (unsigned int i = 0; i < TVectorDimension; ++i) { is >> vct[i]; } return is; } template <typename T, unsigned int TVectorDimension> typename Vector<T, TVectorDimension>::ValueType Vector<T, TVectorDimension>::operator*(const Self & other) const { typename NumericTraits<T>::AccumulateType value = NumericTraits<T>::ZeroValue(); for (unsigned int i = 0; i < TVectorDimension; ++i) { value += (*this)[i] * other[i]; } return value; } } // end namespace itk #endif
25.995305
112
0.669135
khangthk
2bed5141d5b0f83313368a1e9bfff1cb8177a4c4
1,948
cpp
C++
Src/Graph/Geometry.cpp
patrickuhlmann/OpenGL-Scenegraph
92c8a6fcadc48b185cf27db00474693916bc4802
[ "MIT" ]
1
2018-12-19T04:34:05.000Z
2018-12-19T04:34:05.000Z
Src/Graph/Geometry.cpp
patrickuhlmann/OpenGL-Scenegraph
92c8a6fcadc48b185cf27db00474693916bc4802
[ "MIT" ]
null
null
null
Src/Graph/Geometry.cpp
patrickuhlmann/OpenGL-Scenegraph
92c8a6fcadc48b185cf27db00474693916bc4802
[ "MIT" ]
null
null
null
#include "Geometry.hpp" /** \brief Initializes a Geometry node visible with a mesh. The node will take the name of the mesh * \param M Mesh to use in this geometry node. It takes ownership of the mesh and takes care of deleting it at the end */ Geometry::Geometry(Mesh* M) : CompositeNode(M->GetName()), Visible(true), _state(0) { SetMesh(M); }; /** \brief Initializes a Geometry node visible with a mesh and a name. * \param M Mesh to use in this geometry node. It takes ownership of the mesh and takes care of deleting it at the end * \param Name of the GeometryNode */ Geometry::Geometry(Mesh* M, const string& Name) : CompositeNode(Name), Visible(true), _state(0) { SetMesh(M); }; /** \brief Destructor deletes mesh */ Geometry::~Geometry() { delete _mesh; delete _state; }; /** \brief Accept method just calls VisitGeometry from Visitor * \param Visitor of the Node */ void Geometry::Accept( NodeVisitor* Visitor ) { Visitor->VisitGeometry( this ); } /** \brief Set a new mesh for this Geometry object * \param M to set */ void Geometry::SetMesh( Mesh* M ) { if (M == 0) LOG(WARNING) << "Try to initialize Geometry with null pointer!" << endl; _mesh = M; } const Mesh* Geometry::GetMesh() const { return _mesh; } /** \brief Set a State for this Geometry. If there was an old state it will be removed. We take control over the state and free it at the end * \param s to use */ void Geometry::SetState(State* s) { delete _state; _state = s; } /** \brief Get the State for this Geometry. Can be zero! */ const State* Geometry::GetState() const { return _state; } /** \brief Decides if the object is visible or not * \param NewStatus is true -> is visible, otherwise not */ void Geometry::SetVisibility(bool NewStatus) { this->Visible = NewStatus; } /** \brief Check if the object is visible * \return true if visible, false otherwise */ bool Geometry::GetVisibility() const { return this->Visible; }
28.647059
141
0.698665
patrickuhlmann
2bede9ee1af5420271b4f1026fd3a0a900f59688
1,911
hpp
C++
src/autonomy/compiler/translator_exceptions.hpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
2
2015-05-31T20:26:51.000Z
2022-02-19T16:11:14.000Z
src/autonomy/compiler/translator_exceptions.hpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
null
null
null
src/autonomy/compiler/translator_exceptions.hpp
medlefsen/autonomy
ed9da86e9be98dd2505a7f02af9cd4db995e6baf
[ "Artistic-2.0" ]
null
null
null
//! \file translator_exceptions.hpp //! \brief Exception classes that may be thrown by the translator. #ifndef AUTONOMY_COMPILER_TRANSLATOR_EXCEPTIONS_HPP #define AUTONOMY_COMPILER_TRANSLATOR_EXCEPTIONS_HPP #include <string> #include <exception> #include <autonomy/compiler/parser_ids.hpp> namespace autonomy { namespace compiler { //! \class translator_exception //! \brief Generic translator exception. class translator_exception : public std::exception { public: translator_exception(std::string const& msg); ~translator_exception() throw () {} virtual const char* what() const throw (); private: std::string _msg; }; //! \class corrupted_parse_tree //! \brief Exception for parse trees recognized as malformed. class corrupted_parse_tree : public translator_exception { public: corrupted_parse_tree(parser_id_t at_node, parser_id_t prev_node); ~corrupted_parse_tree() throw () {} }; //! \class undeclared_variable //! \brief Thrown when attempting to reference an undeclared variable. class undeclared_variable : public translator_exception { public: undeclared_variable(std::string const& symbol); ~undeclared_variable() throw () {} }; //! \class undefined_command //! \brief Thrown when attempting to access an unavailable command. class undefined_command : public translator_exception { public: undefined_command(std::string const& symbol); ~undefined_command() throw () {} }; } } #endif
27.3
81
0.574568
medlefsen
2bf728489b29051f8a13d5dd8d4c4903026421c8
3,332
hpp
C++
Vals.hpp
Galenika/csgo-offsets-finder
5fd13006bb5fe58bed4f0a35a99142fe5a279c72
[ "MIT" ]
2
2021-02-26T08:03:30.000Z
2021-07-14T23:28:41.000Z
Vals.hpp
RequestFX/csgo-offsets-finder
5fd13006bb5fe58bed4f0a35a99142fe5a279c72
[ "MIT" ]
null
null
null
Vals.hpp
RequestFX/csgo-offsets-finder
5fd13006bb5fe58bed4f0a35a99142fe5a279c72
[ "MIT" ]
4
2021-02-03T20:08:55.000Z
2021-07-06T17:13:14.000Z
// Made by RequestFX#1541 #pragma once namespace vals { namespace signatures { static long anim_overlays, clientstate_choked_commands, clientstate_delta_ticks, clientstate_last_outgoing_command, clientstate_net_channel, convar_name_hash_table, dwClientState, dwClientState_GetLocalPlayer, dwClientState_IsHLTV, dwClientState_Map, dwClientState_MapDirectory, dwClientState_MaxPlayer, dwClientState_PlayerInfo, dwClientState_State, dwClientState_ViewAngles, dwEntityList, dwForceAttack, dwForceAttack2, dwForceBackward, dwForceForward, dwForceJump, dwForceLeft, dwForceRight, dwGameDir, dwGameRulesProxy, dwGetAllClasses, dwGlobalVars, dwGlowObjectManager, dwInput, dwInterfaceLinkList, dwLocalPlayer, dwMouseEnable, dwMouseEnablePtr, dwPlayerResource, dwRadarBase, dwSensitivity, dwSensitivityPtr, dwSetClanTag, dwViewMatrix, dwWeaponTable, dwWeaponTableIndex, dwYawPtr, dwZoomSensitivityRatioPtr, dwbSendPackets, dwppDirect3DDevice9, find_hud_element, force_update_spectator_glow, interface_engine_cvar, is_c4_owner, m_bDormant, m_flSpawnTime, m_pStudioHdr, m_pitchClassPtr, m_yawClassPtr, model_ambient_min, set_abs_angles, set_abs_origin; } namespace netvars { static long cs_gamerules_data, m_ArmorValue, m_Collision, m_CollisionGroup, m_Local, m_MoveType, m_OriginalOwnerXuidHigh, m_OriginalOwnerXuidLow, m_SurvivalGameRuleDecisionTypes, m_SurvivalRules, m_aimPunchAngle, m_aimPunchAngleVel, m_angEyeAnglesX, m_angEyeAnglesY, m_bBombPlanted, m_bFreezePeriod, m_bGunGameImmunity, m_bHasDefuser, m_bHasHelmet, m_bInReload, m_bIsDefusing, m_bIsQueuedMatchmaking, m_bIsScoped, m_bIsValveDS, m_bSpotted, m_bSpottedByMask, m_bStartedArming, m_bUseCustomAutoExposureMax, m_bUseCustomAutoExposureMin, m_bUseCustomBloomScale, m_clrRender, m_dwBoneMatrix, m_fAccuracyPenalty, m_fFlags, m_flC4Blow, m_flCustomAutoExposureMax, m_flCustomAutoExposureMin, m_flCustomBloomScale, m_flDefuseCountDown, m_flDefuseLength, m_flFallbackWear, m_flFlashDuration, m_flFlashMaxAlpha, m_flLastBoneSetupTime, m_flLowerBodyYawTarget, m_flNextAttack, m_flNextPrimaryAttack, m_flSimulationTime, m_flTimerLength, m_hActiveWeapon, m_hMyWeapons, m_hObserverTarget, m_hOwner, m_hOwnerEntity, m_hViewModel, m_iAccountID, m_iClip1, m_iCompetitiveRanking, m_iCompetitiveWins, m_iCrosshairId, m_iEntityQuality, m_iFOV, m_iFOVStart, m_iGlowIndex, m_iHealth, m_iItemDefinitionIndex, m_iItemIDHigh, m_iMostRecentModelBoneCounter, m_iObserverMode, m_iShotsFired, m_iState, m_iTeamNum, m_iViewModelIndex, m_lifeState, m_nFallbackPaintKit, m_nFallbackSeed, m_nFallbackStatTrak, m_nForceBone, m_nModelIndex, m_nTickBase, m_rgflCoordinateFrame, m_szCustomName, m_szLastPlaceName, m_thirdPersonViewAngles, m_vecOrigin, m_vecVelocity, m_vecViewOffset, m_viewPunchAngle; } }
21.088608
38
0.722689
Galenika
9200ede01a9fc2f6478b757bfa5a2122e39b645b
9,807
cc
C++
Code/Components/Synthesis/synthesis/current/measurementequation/ImageDFTEquation.cc
rtobar/askapsoft
6bae06071d7d24f41abe3f2b7f9ee06cb0a9445e
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
1
2020-06-18T08:37:43.000Z
2020-06-18T08:37:43.000Z
Code/Components/Synthesis/synthesis/current/measurementequation/ImageDFTEquation.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
Code/Components/Synthesis/synthesis/current/measurementequation/ImageDFTEquation.cc
ATNF/askapsoft
d839c052d5c62ad8a511e58cd4b6548491a6006f
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
null
null
null
/// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution 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, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// #include <askap_synthesis.h> #include <askap/AskapLogging.h> ASKAP_LOGGER(logger, ".measurementequation.imagedftequation"); #include <askap/AskapError.h> #include <dataaccess/SharedIter.h> #include <fitting/Params.h> #include <measurementequation/ImageDFTEquation.h> #include <fitting/GenericNormalEquations.h> #include <fitting/DesignMatrix.h> #include <fitting/Axes.h> #include <casacore/scimath/Mathematics/RigidVector.h> #include <casacore/casa/BasicSL/Constants.h> #include <casacore/casa/BasicSL/Complex.h> #include <casacore/casa/Arrays/Vector.h> #include <casacore/casa/Arrays/Matrix.h> #include <casacore/casa/Arrays/ArrayMath.h> #include <stdexcept> using askap::scimath::Params; using askap::scimath::Axes; using askap::scimath::DesignMatrix; namespace askap { namespace synthesis { ImageDFTEquation::ImageDFTEquation(const askap::scimath::Params& ip, accessors::IDataSharedIter& idi) : scimath::Equation(ip), askap::scimath::GenericEquation(ip), itsIdi(idi) { init(); }; ImageDFTEquation::ImageDFTEquation(accessors::IDataSharedIter& idi) : itsIdi(idi) { reference(defaultParameters().clone()); init(); } ImageDFTEquation::~ImageDFTEquation() { } ImageDFTEquation::ImageDFTEquation(const ImageDFTEquation& other) : Equation(other), GenericEquation(other) { operator=(other); } ImageDFTEquation& ImageDFTEquation::operator=(const ImageDFTEquation& other) { if(this!=&other) { static_cast<askap::scimath::GenericEquation*>(this)->operator=(other); itsIdi=other.itsIdi; } return *this; } void ImageDFTEquation::init() { } askap::scimath::Params ImageDFTEquation::defaultParameters() { Params ip; ip.add("image"); return ip; } /// Clone this into a shared pointer /// @return shared pointer to a copy ImageDFTEquation::ShPtr ImageDFTEquation::clone() const { return ImageDFTEquation::ShPtr(new ImageDFTEquation(*this)); } void ImageDFTEquation::predict() const { vector<string> completions(parameters().completions("image.i")); vector<string>::const_iterator it; if(completions.size()==0) { ASKAPLOG_WARN_STR(logger, "No parameters appropriate for ImageFFTEquation"); return; } // itsIdi.chooseBuffer("model"); for (itsIdi.init();itsIdi.hasMore();itsIdi.next()) { const casa::Vector<double>& freq=itsIdi->frequency(); //const double time=itsIdi->time(); const uint nChan=freq.nelements(); const uint nRow=itsIdi->nRow(); casa::Matrix<double> vis(nRow,2*nChan); vis.set(0.0); for (it=completions.begin();it!=completions.end();it++) { string imageName("image.i"+(*it)); const casa::Array<double> imagePixels(parameters().value(imageName)); const casa::IPosition imageShape(imagePixels.shape()); Axes axes(parameters().axes(imageName)); if(!axes.has("RA")||!axes.has("DEC")) { throw(std::invalid_argument("RA and DEC specification not present for "+imageName)); } double raStart=axes.start("RA"); double raEnd=axes.end("RA"); int raCells=imageShape(axes.order("RA")); double decStart=axes.start("DEC"); double decEnd=axes.end("DEC"); int decCells=imageShape(axes.order("DEC")); casa::Matrix<double> noDeriv(0,0); this->calcVisDFT(imagePixels, raStart, raEnd, raCells, decStart, decEnd, decCells, freq, itsIdi->uvw(), vis, false, noDeriv); for (uint row=0;row<nRow;row++) { for (uint i=0;i<nChan;i++) { itsIdi->rwVisibility()(row,i,0) += casa::Complex(vis(row,2*i), vis(row,2*i+1)); } } } } }; void ImageDFTEquation::calcGenericEquations(askap::scimath::GenericNormalEquations& ne) const { // Loop over all completions i.e. all sources vector<string> completions(parameters().completions("image.i")); vector<string>::iterator it; if(completions.size()==0) { ASKAPLOG_WARN_STR(logger, "No parameters appropriate for ImageFFTEquation"); return; } // itsIdi.chooseOriginal(); for (itsIdi.init();itsIdi.hasMore();itsIdi.next()) { const casa::Vector<double>& freq=itsIdi->frequency(); const uint nChan=freq.nelements(); const uint nRow=itsIdi->nRow(); //const double time=itsIdi->time(); // Set up arrays to hold the output values // Row, Two values (complex) per channel, single pol casa::Vector<double> residual(2*nRow*nChan); casa::Vector<double> weights(2*nRow*nChan); weights.set(1.0); casa::Matrix<double> vis(nRow,2*nChan); vis.set(0.0); for (it=completions.begin();it!=completions.end();it++) { string imageName("image.i"+(*it)); if(parameters().isFree(imageName)) { const casa::Array<double> imagePixels(parameters().value(imageName)); const casa::IPosition imageShape(imagePixels.shape()); Axes axes(parameters().axes(imageName)); if(!axes.has("RA")||!axes.has("DEC")) { throw(std::invalid_argument("RA and DEC specification not present for "+imageName)); } double raStart=axes.start("RA"); double raEnd=axes.end("RA"); int raCells=imageShape(axes.order("RA")); double decStart=axes.start("DEC"); double decEnd=axes.end("DEC"); int decCells=imageShape(axes.order("DEC")); const uint nPixels=imagePixels.nelements(); DesignMatrix designmatrix; //old parameters: parameters(); casa::Matrix<double> imageDeriv(2*nRow*nChan,nPixels); this->calcVisDFT(imagePixels, raStart, raEnd, raCells, decStart, decEnd, decCells, freq, itsIdi->uvw(), vis, true, imageDeriv); for (uint row=0;row<itsIdi->nRow();row++) { for (uint i=0;i<freq.nelements();i++) { residual(nChan*row+2*i)=real(itsIdi->visibility()(row,i,0))-vis(row,2*i); residual(nChan*row+2*i+1)=imag(itsIdi->visibility()(row,i,0))-vis(row,2*i+1); } } // Now we can add the design matrix, residual, and weights designmatrix.addDerivative(imageName, imageDeriv); designmatrix.addResidual(residual, weights); ne.add(designmatrix); } } } }; void ImageDFTEquation::calcVisDFT(const casa::Array<double>& imagePixels, const double raStart, const double raEnd, const int raCells, const double decStart, const double decEnd, const int decCells, const casa::Vector<double>& freq, const casa::Vector<casa::RigidVector<double, 3> >& uvw, casa::Matrix<double>& vis, bool doDeriv, casa::Matrix<double>& imageDeriv) { double raInc=(raStart-raEnd)/double(raCells); double decInc=(decStart-decEnd)/double(decCells); const uint nRow=uvw.nelements(); const uint nChan=freq.nelements(); vis.set(0.0); for (uint row=0;row<nRow;row++) { uint pixel=0; double u=uvw(row)(0); double v=uvw(row)(1); double w=uvw(row)(2); ASKAPDEBUGASSERT(decCells>=0); ASKAPDEBUGASSERT(raCells>=0); for (uint m=0;m<uint(decCells);++m) { double dec = decStart + m * decInc; for (uint l=0;l<uint(raCells);l++) { double ra = raStart + l * raInc; double delay = casa::C::_2pi * (ra * u + dec * v + sqrt(1 - ra * ra - dec * dec) * w)/casa::C::c; double flux = imagePixels(casa::IPosition(2, l, m)); if(doDeriv) { for (uint i=0;i<nChan;i++) { double phase = delay * freq(i); vis(row,2*i) += flux * cos(phase); vis(row,2*i+1) += flux * sin(phase); imageDeriv(nChan*row+2*i,pixel) = cos(phase); imageDeriv(nChan*row+2*i+1,pixel) = sin(phase); } } else { for (uint i=0;i<nChan;i++) { double phase = delay * freq(i); vis(row,2*i) += flux * cos(phase); vis(row,2*i+1) += flux * sin(phase); } } pixel++; } } } } } }
32.47351
109
0.59325
rtobar
92029a07389286914c224acb3a5e43ec29bd7f14
51,507
cxx
C++
src/pn532/pn532.cxx
g-vidal/upm
8115c3b64468f22fb27053ba9dfc952ae0e32633
[ "MIT" ]
2
2017-06-19T13:14:30.000Z
2018-07-12T06:17:49.000Z
src/pn532/pn532.cxx
g-vidal/upm
8115c3b64468f22fb27053ba9dfc952ae0e32633
[ "MIT" ]
1
2018-11-13T18:03:56.000Z
2018-11-14T18:17:57.000Z
src/pn532/pn532.cxx
g-vidal/upm
8115c3b64468f22fb27053ba9dfc952ae0e32633
[ "MIT" ]
4
2017-03-06T14:39:59.000Z
2018-06-28T11:07:41.000Z
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2015 Intel Corporation. * * This code is heavily based on the Adafruit-PN532 library at * https://github.com/adafruit/Adafruit-PN532, which is licensed under * the BSD license. See upm/src/pn532/license.txt * * 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 <unistd.h> #include <math.h> #include <iostream> #include <string> #include <stdexcept> #include "pn532.hpp" using namespace upm; using namespace std; #define PN532_PACKBUFFSIZ 64 static uint8_t pn532_packetbuffer[PN532_PACKBUFFSIZ]; static uint8_t pn532ack[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00}; static uint32_t pn532_firmwarerev = 0x00320106; PN532::PN532(int irq, int reset, int bus, uint8_t address): m_gpioIRQ(irq), m_gpioReset(reset), m_i2c(bus) { m_addr = address; m_uidLen = 0; m_inListedTag = 0; m_SAK = 0; m_ATQA = 0; m_isrInstalled = false; m_irqRcvd = false; memset(m_uid, 0, 7); memset(m_key, 0, 6); // turn off debugging by default pn532Debug(false); mifareDebug(false); mraa::Result rv; if ( (rv = m_i2c.address(m_addr)) != mraa::SUCCESS) { throw std::runtime_error(std::string(__FUNCTION__) + ": I2c.address() failed"); return; } m_gpioIRQ.dir(mraa::DIR_IN); m_gpioReset.dir(mraa::DIR_OUT); } PN532::~PN532() { if (m_isrInstalled) m_gpioIRQ.isrExit(); } bool PN532::init() { m_gpioReset.write(1); m_gpioReset.write(0); usleep(400000); // install an interrupt handler m_gpioIRQ.isr(mraa::EDGE_FALLING, dataReadyISR, this); m_isrInstalled = true; m_gpioReset.write(1); return true; } /**************************************************************************/ /*! @brief Prints a hexadecimal value in plain characters @param data Pointer to the byte data @param numBytes Data length in bytes */ /**************************************************************************/ static void PrintHex(const uint8_t * data, const uint32_t numBytes) { uint32_t szPos; for (szPos=0; szPos < numBytes; szPos++) { fprintf(stderr, "0x%02x ", data[szPos] & 0xff); } fprintf(stderr, "\n"); } /**************************************************************************/ /*! @brief Prints a hexadecimal value in plain characters, along with the char equivalents in the following format 00 00 00 00 00 00 ...... @param data Pointer to the byte data @param numBytes Data length in bytes */ /**************************************************************************/ static void PrintHexChar(const uint8_t * data, const uint32_t numBytes) { uint32_t szPos; for (szPos=0; szPos < numBytes; szPos++) { fprintf(stderr, "0x%02x ", data[szPos] & 0xff); } fprintf(stderr, " "); for (szPos=0; szPos < numBytes; szPos++) { if (data[szPos] <= 0x1F) fprintf(stderr, "."); else fprintf(stderr, "%c ", (char)data[szPos]); } fprintf(stderr, "\n"); } /**************************************************************************/ /*! @brief Checks the firmware version of the PN5xx chip @returns The chip's firmware version and ID */ /**************************************************************************/ uint32_t PN532::getFirmwareVersion() { uint32_t response = 0; pn532_packetbuffer[0] = CMD_GETFIRMWAREVERSION; if (! sendCommandCheckAck(pn532_packetbuffer, 1)) return 0; // read data packet readData(pn532_packetbuffer, 12); int offset = 7; // Skip the ready byte when using I2C response <<= 8; response |= pn532_packetbuffer[offset++]; response <<= 8; response |= pn532_packetbuffer[offset++]; response <<= 8; response |= pn532_packetbuffer[offset++]; if (response != pn532_firmwarerev) fprintf(stderr, "Warning: firmware revision 0x%08x does not match expected rev 0x%08x\n", response, pn532_firmwarerev); return response; } /**************************************************************************/ /*! @brief Sends a command and waits a specified period for the ACK @param cmd Pointer to the command buffer @param cmdlen The size of the command in bytes @param timeout timeout before giving up @returns 1 if everything is OK, 0 if timeout occurred before an ACK was received */ /**************************************************************************/ // default timeout of one second bool PN532::sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen, uint16_t timeout) { // clear any outstanding irq's isReady(); // write the command writeCommand(cmd, cmdlen); // Wait for chip to say its ready! if (!waitForReady(timeout)) { cerr << __FUNCTION__ << ": Not ready, timeout" << endl; return false; } if (m_pn532Debug) cerr << __FUNCTION__ << ": IRQ received" << endl; // read acknowledgement if (!readAck()) { if (m_pn532Debug) cerr << __FUNCTION__ << ": No ACK frame received!" << endl; return false; } return true; // ack'd command } /**************************************************************************/ /*! @brief Configures the SAM (Secure Access Module) */ /**************************************************************************/ bool PN532::SAMConfig(void) { pn532_packetbuffer[0] = CMD_SAMCONFIGURATION; pn532_packetbuffer[1] = 0x01; // normal mode; pn532_packetbuffer[2] = 0x14; // timeout 50ms * 20 = 1 second pn532_packetbuffer[3] = 0x01; // use IRQ pin! if (! sendCommandCheckAck(pn532_packetbuffer, 4)) return false; // read data packet readData(pn532_packetbuffer, 8); int offset = 6; return (pn532_packetbuffer[offset] == 0x15); } /**************************************************************************/ /*! Sets the MxRtyPassiveActivation byte of the RFConfiguration register @param maxRetries 0xFF to wait forever, 0x00..0xFE to timeout after mxRetries @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::setPassiveActivationRetries(uint8_t maxRetries) { pn532_packetbuffer[0] = CMD_RFCONFIGURATION; pn532_packetbuffer[1] = 5; // Config item 5 (MaxRetries) pn532_packetbuffer[2] = 0xFF; // MxRtyATR (default = 0xFF) pn532_packetbuffer[3] = 0x01; // MxRtyPSL (default = 0x01) pn532_packetbuffer[4] = maxRetries; if (m_mifareDebug) cerr << __FUNCTION__ << ": Setting MxRtyPassiveActivation to " << (int)maxRetries << endl; if (! sendCommandCheckAck(pn532_packetbuffer, 5)) return false; // no ACK return true; } /***** ISO14443A Commands ******/ /**************************************************************************/ /*! Waits for an ISO14443A target to enter the field @param cardBaudRate Baud rate of the card @param uid Pointer to the array that will be populated with the card's UID (up to 7 bytes) @param uidLength Pointer to the variable that will hold the length of the card's UID. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::readPassiveTargetID(BAUD_T cardbaudrate, uint8_t * uid, uint8_t * uidLength, uint16_t timeout) { pn532_packetbuffer[0] = CMD_INLISTPASSIVETARGET; pn532_packetbuffer[1] = 1; // max 1 cards at once (we can set this // to 2 later) pn532_packetbuffer[2] = cardbaudrate; if (!sendCommandCheckAck(pn532_packetbuffer, 3, timeout)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": No card(s) read" << endl; return false; // no cards read } // wait for a card to enter the field (only possible with I2C) if (m_pn532Debug) cerr << __FUNCTION__ << ": Waiting for IRQ (indicates card presence)" << endl; if (!waitForReady(timeout)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": IRQ Timeout" << endl; return false; } // read data packet readData(pn532_packetbuffer, 20); // check some basic stuff /* ISO14443A card response should be in the following format: byte Description ------------- ------------------------------------------ b0..6 Frame header and preamble b7 Tags Found b8 Tag Number (only one used in this example) b9..10 SENS_RES b11 SEL_RES b12 NFCID Length b13..NFCIDLen NFCID */ // SENS_RES SEL_RES Manufacturer/Card Type NFCID Len // -------- ------- ----------------------- --------- // 00 04 08 NXP Mifare Classic 1K 4 bytes // 00 02 18 NXP Mifare Classic 4K 4 bytes if (m_mifareDebug) cerr << __FUNCTION__ << ": Found " << (int)pn532_packetbuffer[7] << " tags" << endl; // only one card can be handled currently if (pn532_packetbuffer[7] != 1) return false; uint16_t sens_res = pn532_packetbuffer[9]; sens_res <<= 8; sens_res |= pn532_packetbuffer[10]; // store these for later retrieval, they can be used to more accurately // ID the type of card. m_ATQA = sens_res; m_SAK = pn532_packetbuffer[11]; // SEL_RES if (m_mifareDebug) { fprintf(stderr, "ATQA: 0x%04x\n", m_ATQA); fprintf(stderr, "SAK: 0x%02x\n", m_SAK); } /* Card appears to be Mifare Classic */ // JET: How so? *uidLength = pn532_packetbuffer[12]; if (m_mifareDebug) fprintf(stderr, "UID: "); for (uint8_t i=0; i < pn532_packetbuffer[12]; i++) { uid[i] = pn532_packetbuffer[13+i]; if (m_mifareDebug) fprintf(stderr, "0x%02x ", uid[i]); } if (m_mifareDebug) fprintf(stderr, "\n"); return true; } /**************************************************************************/ /*! @brief Exchanges an APDU with the currently inlisted peer @param send Pointer to data to send @param sendLength Length of the data to send @param response Pointer to response data @param responseLength Pointer to the response data length */ /**************************************************************************/ bool PN532::inDataExchange(uint8_t * send, uint8_t sendLength, uint8_t * response, uint8_t * responseLength) { if (sendLength > PN532_PACKBUFFSIZ-2) { if (m_pn532Debug) cerr << __FUNCTION__ << ": APDU length too long for packet buffer" << endl; return false; } uint8_t i; pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; // 0x40 pn532_packetbuffer[1] = m_inListedTag; for (i=0; i<sendLength; ++i) { pn532_packetbuffer[i+2] = send[i]; } if (!sendCommandCheckAck(pn532_packetbuffer,sendLength+2,1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Could not send ADPU" << endl; return false; } if (!waitForReady(1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Response never received for ADPU..." << endl; return false; } readData(pn532_packetbuffer, sizeof(pn532_packetbuffer)); if (pn532_packetbuffer[0] == 0 && pn532_packetbuffer[1] == 0 && pn532_packetbuffer[2] == 0xff) { uint8_t length = pn532_packetbuffer[3]; if (pn532_packetbuffer[4]!=(uint8_t)(~length+1)) { if (m_pn532Debug) fprintf(stderr, "Length check invalid: 0x%02x != 0x%02x\n", length, (~length)+1); return false; } if (pn532_packetbuffer[5]==PN532_PN532TOHOST && pn532_packetbuffer[6]==RSP_INDATAEXCHANGE) { if ((pn532_packetbuffer[7] & 0x3f)!=0) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Status code indicates an error" << endl; return false; } length -= 3; if (length > *responseLength) { length = *responseLength; // silent truncation... } for (i=0; i<length; ++i) { response[i] = pn532_packetbuffer[8+i]; } *responseLength = length; return true; } else { fprintf(stderr, "Don't know how to handle this command: 0x%02x\n", pn532_packetbuffer[6]); return false; } } else { cerr << __FUNCTION__ << ": Preamble missing" << endl; return false; } } /**************************************************************************/ /*! @brief 'InLists' a passive target. PN532 acting as reader/initiator, peer acting as card/responder. */ /**************************************************************************/ bool PN532::inListPassiveTarget() { m_inListedTag = 0; pn532_packetbuffer[0] = CMD_INLISTPASSIVETARGET; pn532_packetbuffer[1] = 1; pn532_packetbuffer[2] = 0; if (m_pn532Debug) cerr << __FUNCTION__ << ": About to inList passive target" << endl; if (!sendCommandCheckAck(pn532_packetbuffer,3,1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Could not send inlist message" << endl; return false; } if (!waitForReady(30000)) { return false; } readData(pn532_packetbuffer, sizeof(pn532_packetbuffer)); if (pn532_packetbuffer[0] == 0 && pn532_packetbuffer[1] == 0 && pn532_packetbuffer[2] == 0xff) { uint8_t length = pn532_packetbuffer[3]; if (pn532_packetbuffer[4]!=(uint8_t)(~length+1)) { if (m_pn532Debug) fprintf(stderr, "Length check invalid: 0x%02x != 0x%02x\n", length, (~length)+1); return false; } if (pn532_packetbuffer[5]==PN532_PN532TOHOST && pn532_packetbuffer[6]==RSP_INLISTPASSIVETARGET) { if (pn532_packetbuffer[7] != 1) { cerr << __FUNCTION__ << ": Unhandled number of tags inlisted: " << (int)pn532_packetbuffer[7] << endl; return false; } m_inListedTag = pn532_packetbuffer[8]; if (m_pn532Debug) cerr << __FUNCTION__ << ": Tag number: " << (int)m_inListedTag << endl; return true; } else { if (m_pn532Debug) cerr << __FUNCTION__ << ": Unexpected response to inlist passive host" << endl; return false; } } else { if (m_pn532Debug) cerr << __FUNCTION__ << ": Preamble missing" << endl; return false; } return true; } /***** Mifare Classic Functions ******/ /* MIFARE CLASSIC DESCRIPTION ========================== Taken from: https://www.kismetwireless.net/code-old/svn/hardware/kisbee-02/firmware/drivers/rf/pn532/helpers/pn532_mifare_classic.c MIFARE Classic cards come in 1K and 4K varieties. While several varieties of chips exist, the two main chipsets used are described in the following publicly accessible documents: MF1S503x Mifare Classic 1K data sheet: http://www.nxp.com/documents/data_sheet/MF1S503x.pdf MF1S70yyX MIFARE Classic 4K data sheet: http://www.nxp.com/documents/data_sheet/MF1S70YYX.pdf Mifare Classic cards typically have a a 4-byte NUID, though you may find cards with 7 byte IDs as well EEPROM MEMORY ============= Mifare Classic cards have either 1K or 4K of EEPROM memory. Each memory block can be configured with different access conditions, with two seperate authentication keys present in each block. The two main Mifare Classic card types are organised as follows: 1K Cards: 16 sectors of 4 blocks (0..15) 4K Cards: 32 sectors of 4 blocks (0..31) and 8 sectors of 16 blocks (32..39) 4 block sectors =============== Sector Block Bytes Description ------ ----- ----- ----------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 3 [-------KEY A-------] [Access Bits] [-------KEY A-------] Sector Trailer 1 2 [ Data ] Data 1 [ Data ] Data 0 [ Data ] Data 0 3 [-------KEY A-------] [Access Bits] [-------KEY A-------] Sector Trailer 1 2 [ Data ] Data 1 [ Data ] Data 0 [ Manufacturer Data ] Manufacturer Block Sector Trailer (Block 3) ------------------------ The sector trailer block contains the two secret keys (Key A and Key B), as well as the access conditions for the four blocks. It has the following structure: Sector Trailer Bytes -------------------------------------------------------------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [ Key A ] [Access Bits] [ Key B ] For more information in using Keys to access the clock contents, see Accessing Data Blocks further below. Data Blocks (Blocks 0..2) ------------------------- Data blocks are 16 bytes wide and, depending on the permissions set in the access bits, can be read from and written to. You are free to use the 16 data bytes in any way you wish. You can easily store text input, store four 32-bit integer values, a 16 character uri, etc. Data Blocks as "Value Blocks" ----------------------------- An alternative to storing random data in the 16 byte-wide blocks is to configure them as "Value Blocks". Value blocks allow performing electronic purse functions (valid commands are: read, write, increment, decrement, restore, transfer). Each Value block contains a single signed 32-bit value, and this value is stored 3 times for data integrity and security reasons. It is stored twice non-inverted, and once inverted. The last 4 bytes are used for a 1-byte address, which is stored 4 times (twice non-inverted, and twice inverted). Data blocks configured as "Value Blocks" have the following structure: Value Block Bytes -------------------------------------------------------------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [ Value ] [ ~Value ] [ Value ] [A ~A A ~A] Manufacturer Block (Sector 0, Block 0) -------------------------------------- Sector 0 is special since it contains the Manufacturer Block. This block contains the manufacturer data, and is read-only. It should be avoided unless you know what you are doing. 16 block sectors ================ 16 block sectors are identical to 4 block sectors, but with more data blocks. The same structure described in the 4 block sectors above applies. Sector Block Bytes Description ------ ----- ----- ---------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 32 15 [-------KEY A-------] [Access Bits] [-------KEY B-------] Sector Trailer 32 14 [ Data ] Data 13 [ Data ] Data ... 2 [ Data ] Data 1 [ Data ] Data 0 [ Data ] Data ACCESSING DATA BLOCKS ===================== Before you can access the cards, you must following two steps: 1.) You must retrieve the 7 byte UID or the 4-byte NUID of the card. This can be done using pn532_mifareclassic_WaitForPassiveTarget() below, which will return the appropriate ID. 2.) You must authenticate the sector you wish to access according to the access rules defined in the Sector Trailer block for that sector. This can be done using pn532_mifareclassic_AuthenticateBlock(), passing in the appropriate key value. Most new cards have a default Key A of 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF, but some common values worth trying are: 0XFF 0XFF 0XFF 0XFF 0XFF 0XFF 0XD3 0XF7 0XD3 0XF7 0XD3 0XF7 0XA0 0XA1 0XA2 0XA3 0XA4 0XA5 0XB0 0XB1 0XB2 0XB3 0XB4 0XB5 0X4D 0X3A 0X99 0XC3 0X51 0XDD 0X1A 0X98 0X2C 0X7E 0X45 0X9A 0XAA 0XBB 0XCC 0XDD 0XEE 0XFF 0X00 0X00 0X00 0X00 0X00 0X00 0XAB 0XCD 0XEF 0X12 0X34 0X56 3.) Once authenication has succeeded, and depending on the sector permissions, you can then read/write/increment/decrement the contents of the specific block, using one of the helper functions included in this module. */ /**************************************************************************/ /*! Indicates whether the specified block number is the first block in the sector (block 0 relative to the current sector) */ /**************************************************************************/ bool PN532::mifareclassic_IsFirstBlock (uint32_t uiBlock) { // Test if we are in the small or big sectors if (uiBlock < 128) return ((uiBlock) % 4 == 0); else return ((uiBlock) % 16 == 0); } /**************************************************************************/ /*! Indicates whether the specified block number is the sector trailer */ /**************************************************************************/ bool PN532::mifareclassic_IsTrailerBlock (uint32_t uiBlock) { // Test if we are in the small or big sectors if (uiBlock < 128) return ((uiBlock + 1) % 4 == 0); else return ((uiBlock + 1) % 16 == 0); } /**************************************************************************/ /*! Tries to authenticate a block of memory on a MIFARE card using the INDATAEXCHANGE command. See section 7.3.8 of the PN532 User Manual for more information on sending MIFARE and other commands. @param uid Pointer to a byte array containing the card UID @param uidLen The length (in bytes) of the card's UID (Should be 4 for MIFARE Classic) @param blockNumber The block number to authenticate. (0..63 for 1KB cards, and 0..255 for 4KB cards). @param keyNumber Which key type to use during authentication (0 = MIFARE_CMD_AUTH_A, 1 = MIFARE_CMD_AUTH_B) @param keyData Pointer to a byte array containing the 6 byte key value @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_AuthenticateBlock (uint8_t * uid, uint8_t uidLen, uint32_t blockNumber, uint8_t keyNumber, uint8_t * keyData) { uint8_t i; // Hang on to the key and uid data memcpy (m_key, keyData, 6); memcpy (m_uid, uid, uidLen); m_uidLen = uidLen; if (m_mifareDebug) { fprintf(stderr, "Trying to authenticate card "); PrintHex(m_uid, m_uidLen); fprintf(stderr, "Using authentication KEY %c: ", keyNumber ? 'B' : 'A'); PrintHex(m_key, 6); } // Prepare the authentication command // pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; /* Data Exchange Header */ pn532_packetbuffer[1] = 1; /* Max card numbers */ pn532_packetbuffer[2] = (keyNumber) ? MIFARE_CMD_AUTH_B : MIFARE_CMD_AUTH_A; pn532_packetbuffer[3] = blockNumber; /* Block Number (1K = 0..63, 4K = 0..255 */ memcpy (pn532_packetbuffer+4, m_key, 6); for (i = 0; i < m_uidLen; i++) { pn532_packetbuffer[10+i] = m_uid[i]; /* 4 byte card ID */ } if (! sendCommandCheckAck(pn532_packetbuffer, 10+m_uidLen)) return false; if (!waitForReady(1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": timeout waiting auth..." << endl; return false; } // Read the response packet readData(pn532_packetbuffer, 12); // check if the response is valid and we are authenticated??? // for an auth success it should be bytes 5-7: 0xD5 0x41 0x00 // Mifare auth error is technically byte 7: 0x14 but anything other // and 0x00 is not good if (pn532_packetbuffer[7] != 0x00) { if (m_pn532Debug) { fprintf(stderr, "Authentication failed: "); PrintHexChar(pn532_packetbuffer, 12); } return false; } return true; } /**************************************************************************/ /*! Tries to read an entire 16-byte data block at the specified block address. @param blockNumber The block number to authenticate. (0..63 for 1KB cards, and 0..255 for 4KB cards). @param data Pointer to the byte array that will hold the retrieved data (if any) @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t * data) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Trying to read 16 bytes from block " << (int)blockNumber << endl; /* Prepare the command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_CMD_READ; /* Mifare Read command = 0x30 */ pn532_packetbuffer[3] = blockNumber; /* Block Number (0..63 for 1K, 0..255 for 4K) */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 4)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for read command" << endl; return false; } /* Read the response packet */ readData(pn532_packetbuffer, 26); /* If byte 8 isn't 0x00 we probably have an error */ if (pn532_packetbuffer[7] != 0x00) { if (m_mifareDebug) { fprintf(stderr, "Unexpected response: "); PrintHexChar(pn532_packetbuffer, 26); } return false; } /* Copy the 16 data bytes to the output buffer */ /* Block content starts at byte 9 of a valid response */ memcpy (data, pn532_packetbuffer+8, 16); /* Display data for debug if requested */ if (m_mifareDebug) { fprintf(stderr, "Block %d: ", blockNumber); PrintHexChar(data, 16); } return true; } /**************************************************************************/ /*! Tries to write an entire 16-byte data block at the specified block address. @param blockNumber The block number to authenticate. (0..63 for 1KB cards, and 0..255 for 4KB cards). @param data The byte array that contains the data to write. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_WriteDataBlock (uint8_t blockNumber, uint8_t * data) { if (m_mifareDebug) fprintf(stderr, "Trying to write 16 bytes to block %d\n", blockNumber); /* Prepare the first command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_CMD_WRITE; /* Mifare Write command = 0xA0 */ pn532_packetbuffer[3] = blockNumber; /* Block Number (0..63 for 1K, 0..255 for 4K) */ memcpy (pn532_packetbuffer+4, data, 16); /* Data Payload */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 20)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for write command" << endl; return false; } usleep(10000); /* Read the response packet */ readData(pn532_packetbuffer, 26); return true; } /**************************************************************************/ /*! Formats a Mifare Classic card to store NDEF Records @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_FormatNDEF (void) { uint8_t sectorbuffer1[16] = {0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}; uint8_t sectorbuffer2[16] = {0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}; uint8_t sectorbuffer3[16] = {0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0x78, 0x77, 0x88, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // Note 0xA0 0xA1 0xA2 0xA3 0xA4 0xA5 must be used for key A // for the MAD sector in NDEF records (sector 0) // Write block 1 and 2 to the card if (!(mifareclassic_WriteDataBlock (1, sectorbuffer1))) return false; if (!(mifareclassic_WriteDataBlock (2, sectorbuffer2))) return false; // Write key A and access rights card if (!(mifareclassic_WriteDataBlock (3, sectorbuffer3))) return false; // Seems that everything was OK (?!) return true; } /**************************************************************************/ /*! Writes an NDEF URI Record to the specified sector (1..15) Note that this function assumes that the Mifare Classic card is already formatted to work as an "NFC Forum Tag" and uses a MAD1 file system. You can use the NXP TagWriter app on Android to properly format cards for this. @param sectorNumber The sector that the URI record should be written to (can be 1..15 for a 1K card) @param uriIdentifier The uri identifier code (0 = none, 0x01 = "http://www.", etc.) @param url The uri text to write (max 38 characters). @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_WriteNDEFURI (uint8_t sectorNumber, NDEF_URI_T uriIdentifier, const char * url) { if (!url) return false; // Figure out how long the string is uint8_t len = strlen(url); // Make sure we're within a 1K limit for the sector number if ((sectorNumber < 1) || (sectorNumber > 15)) return false; // Make sure the URI payload is between 1 and 38 chars if ((len < 1) || (len > 38)) return false; // Note 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 must be used for key A // in NDEF records // Setup the sector buffer (w/pre-formatted TLV wrapper and NDEF message) uint8_t sectorbuffer1[16] = {0x00, 0x00, 0x03, static_cast<uint8_t>(len+5), 0xD1, 0x01, static_cast<uint8_t>(len+1), 0x55, static_cast<uint8_t>(uriIdentifier), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t sectorbuffer2[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t sectorbuffer3[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t sectorbuffer4[16] = {0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F, 0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; if (len <= 6) { // Unlikely we'll get a url this short, but why not ... memcpy (sectorbuffer1+9, url, len); sectorbuffer1[len+9] = 0xFE; } else if (len == 7) { // 0xFE needs to be wrapped around to next block memcpy (sectorbuffer1+9, url, len); sectorbuffer2[0] = 0xFE; } else if ((len > 7) && (len <= 22)) { // Url fits in two blocks memcpy (sectorbuffer1+9, url, 7); memcpy (sectorbuffer2, url+7, len-7); sectorbuffer2[len-7] = 0xFE; } else if (len == 23) { // 0xFE needs to be wrapped around to final block memcpy (sectorbuffer1+9, url, 7); memcpy (sectorbuffer2, url+7, len-7); sectorbuffer3[0] = 0xFE; } else { // Url fits in three blocks memcpy (sectorbuffer1+9, url, 7); memcpy (sectorbuffer2, url+7, 16); memcpy (sectorbuffer3, url+23, len-24); sectorbuffer3[len-23] = 0xFE; } // Now write all three blocks back to the card if (!(mifareclassic_WriteDataBlock (sectorNumber*4, sectorbuffer1))) return false; if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+1, sectorbuffer2))) return false; if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+2, sectorbuffer3))) return false; if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+3, sectorbuffer4))) return false; // Seems that everything was OK (?!) return true; } /***** NTAG2xx/ultralight Functions ******/ // Ultralight tags are limited to 64 pages max, with ntag2XX tags can // have up to 231 pages. /* MIFARE ULTRALIGHT DESCRIPTION ============================= Taken from: https://www.kismetwireless.net/code-old/svn/hardware/kisbee-02/firmware/drivers/rf/pn532/helpers/pn532_mifare_ultralight.c MIFARE Ultralight cards typically contain 512 bits (64 bytes) of memory, including 4 bytes (32-bits) of OTP (One Time Programmable) memory where the individual bits can be written but not erased. MF0ICU1 Mifare Ultralight Functional Specification: http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf Mifare Ultralight cards have a 7-byte UID EEPROM MEMORY ============= Mifare Ultralight cards have 512 bits (64 bytes) of EEPROM memory, including 4 byte (32 bits) of OTP memory. Unlike Mifare Classic cards, there is no authentication on a per block level, although the blocks can be set to "read-only" mode using Lock Bytes (described below). EEPROM memory is organised into 16 pages of four bytes eachs, in the following order Page Description ---- ------------ 0 Serial Number (4 bytes) 1 Serial Number (4 bytes) 2 Byte 0: Serial Number Byte 1: Internal Memory Byte 2..3: lock bytes 3 One-time programmable memory (4 bytes) 4..15 User memory (4 bytes) Lock Bytes (Page 2) ------------------- Bytes 2 and 3 of page 2 are referred to as "Lock Bytes". Each page from 0x03 and higher can individually locked by setting the corresponding locking bit to "1" to prevent further write access, effectively making the memory read only. For information on the lock byte mechanism, refer to section 8.5.2 of the datasheet (referenced above). OTP Bytes (Page 3) ------------------ Page 3 is the OTP memory, and by default all bits on this page are set to 0. These bits can be bitwise modified using the Mifare WRITE command, and individual bits can be set to 1, but can not be changed back to 0. Data Pages (Pages 4..15) ------------------------ Pages 4 to 15 are can be freely read from and written to, provided there is no conflict with the Lock Bytes described above. After production, the bytes have the following default values: Page Byte Values ---- ---------------------- 0 1 2 3 4 0xFF 0xFF 0xFF 0xFF 5..15 0x00 0x00 0x00 0x00 ACCESSING DATA BLOCKS ===================== Before you can access the cards, you must following two steps: 1.) 'Connect' to a Mifare Ultralight card and retrieve the 7 byte UID of the card. 2.) Memory can be read and written directly once a passive mode connection has been made. No authentication is required for Mifare Ultralight cards. */ /**************************************************************************/ /*! Tries to read an entire 4-byte page at the specified address. @param page The page number (0..63 in most cases) @param buffer Pointer to the byte array that will hold the retrieved data (if any) */ /**************************************************************************/ bool PN532::ntag2xx_ReadPage (uint8_t page, uint8_t * buffer) { // TAG Type PAGES USER START USER STOP // -------- ----- ---------- --------- // NTAG 203 42 4 39 // NTAG 213 45 4 39 // NTAG 215 135 4 129 // NTAG 216 231 4 225 if (page >= 231) { cerr << __FUNCTION__ << ": Page value out of range" << endl; return false; } if (m_mifareDebug) fprintf(stderr, "Reading page %d\n", page); /* Prepare the command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_CMD_READ; /* Mifare Read command = 0x30 */ pn532_packetbuffer[3] = page; /* Page Number (0..63 in most cases) */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 4)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for write command" << endl; return false; } /* Read the response packet */ readData(pn532_packetbuffer, 26); if (m_mifareDebug) { fprintf(stderr, "Received: \n"); PrintHexChar(pn532_packetbuffer, 26); } /* If byte 8 isn't 0x00 we probably have an error */ if (pn532_packetbuffer[7] == 0x00) { /* Copy the 4 data bytes to the output buffer */ /* Block content starts at byte 9 of a valid response */ /* Note that the command actually reads 16 byte or 4 */ /* pages at a time ... we simply discard the last 12 */ /* bytes */ memcpy (buffer, pn532_packetbuffer+8, 4); } else { if (m_mifareDebug) { fprintf(stderr, "Unexpected response reading block: \n"); PrintHexChar(pn532_packetbuffer, 26); } return false; } /* Display data for debug if requested */ if (m_mifareDebug) { fprintf(stderr, "Page %d:\n", page); PrintHexChar(buffer, 4); } // Return OK signal return true; } /**************************************************************************/ /*! Tries to write an entire 4-byte page at the specified block address. @param page The page number to write. (0..63 for most cases) @param data The byte array that contains the data to write. Should be exactly 4 bytes long. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::ntag2xx_WritePage (uint8_t page, uint8_t * data) { // TAG Type PAGES USER START USER STOP // -------- ----- ---------- --------- // NTAG 203 42 4 39 // NTAG 213 45 4 39 // NTAG 215 135 4 129 // NTAG 216 231 4 225 if ((page < 4) || (page > 225)) { cerr << __FUNCTION__ << ": Page value out of range" << endl; return false; } if (m_mifareDebug) fprintf(stderr, "Trying to write 4 byte page %d\n", page); /* Prepare the first command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_ULTRALIGHT_CMD_WRITE; /* Mifare Ultralight Write command = 0xA2 */ pn532_packetbuffer[3] = page; /* Page Number (0..63 for most cases) */ memcpy (pn532_packetbuffer+4, data, 4); /* Data Payload */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 8)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for write command" << endl; // Return Failed Signal return false; } usleep(10000); /* Read the response packet */ readData(pn532_packetbuffer, 26); // Return OK Signal return true; } /**************************************************************************/ /*! Writes an NDEF URI Record starting at the specified page (4..nn) Note that this function assumes that the NTAG2xx card is already formatted to work as an "NFC Forum Tag". @param uriIdentifier The uri identifier code (0 = none, 0x01 = "http://www.", etc.) @param url The uri text to write (null-terminated string). @param dataLen The size of the data area for overflow checks. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::ntag2xx_WriteNDEFURI (NDEF_URI_T uriIdentifier, char * url, uint8_t dataLen) { uint8_t pageBuffer[4] = { 0, 0, 0, 0 }; // Remove NDEF record overhead from the URI data (pageHeader below) uint8_t wrapperSize = 12; // Figure out how long the string is uint8_t len = strlen(url); // Make sure the URI payload will fit in dataLen (include 0xFE trailer) if ((len < 1) || (len+1 > (dataLen-wrapperSize))) return false; // Setup the record header // See NFCForum-TS-Type-2-Tag_1.1.pdf for details uint8_t pageHeader[12] = { /* NDEF Lock Control TLV (must be first and always present) */ 0x01, /* Tag Field (0x01 = Lock Control TLV) */ 0x03, /* Payload Length (always 3) */ 0xA0, /* The position inside the tag of the lock bytes (upper 4 = page address, lower 4 = byte offset) */ 0x10, /* Size in bits of the lock area */ 0x44, /* Size in bytes of a page and the number of bytes each lock bit can lock (4 bit + 4 bits) */ /* NDEF Message TLV - URI Record */ 0x03, /* Tag Field (0x03 = NDEF Message) */ static_cast<uint8_t>(len+5), /* Payload Length (not including 0xFE trailer) */ 0xD1, /* NDEF Record Header (TNF=0x1:Well known record + SR + ME + MB) */ 0x01, /* Type Length for the record type indicator */ static_cast<uint8_t>(len+1), /* Payload len */ 0x55, /* Record Type Indicator (0x55 or 'U' = URI Record) */ static_cast<uint8_t>(uriIdentifier) /* URI Prefix (ex. 0x01 = "http://www.") */ }; // Write 12 byte header (three pages of data starting at page 4) memcpy (pageBuffer, pageHeader, 4); if (!(ntag2xx_WritePage (4, pageBuffer))) return false; memcpy (pageBuffer, pageHeader+4, 4); if (!(ntag2xx_WritePage (5, pageBuffer))) return false; memcpy (pageBuffer, pageHeader+8, 4); if (!(ntag2xx_WritePage (6, pageBuffer))) return false; // Write URI (starting at page 7) uint8_t currentPage = 7; char * urlcopy = url; while (len) { if (len < 4) { memset(pageBuffer, 0, 4); memcpy(pageBuffer, urlcopy, len); pageBuffer[len] = 0xFE; // NDEF record footer if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; // DONE! return true; } else if (len == 4) { memcpy(pageBuffer, urlcopy, len); if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; memset(pageBuffer, 0, 4); pageBuffer[0] = 0xFE; // NDEF record footer currentPage++; if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; // DONE! return true; } else { // More than one page of data left memcpy(pageBuffer, urlcopy, 4); if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; currentPage++; urlcopy+=4; len-=4; } } // Seems that everything was OK (?!) return true; } /**************************************************************************/ /*! @brief Tries to read/verify the ACK packet */ /**************************************************************************/ bool PN532::readAck() { uint8_t ackbuff[6]; readData(ackbuff, 6); return (0 == memcmp((char *)ackbuff, (char *)pn532ack, 6)); } /**************************************************************************/ /*! @brief Return true if the PN532 is ready with a response. */ /**************************************************************************/ bool PN532::isReady() { // ALWAYS clear the m_irqRcvd flag if set. if (m_irqRcvd) { m_irqRcvd = false; return true; } return false; } /**************************************************************************/ /*! @brief Waits until the PN532 is ready. @param timeout Timeout before giving up */ /**************************************************************************/ bool PN532::waitForReady(uint16_t timeout) { uint16_t timer = 0; while(!isReady()) { if (timeout != 0) { timer += 10; if (timer > timeout) { return false; } } usleep(10000); } return true; } /**************************************************************************/ /*! @brief Reads n bytes of data from the PN532 via SPI or I2C. @param buff Pointer to the buffer where data will be written @param n Number of bytes to be read */ /**************************************************************************/ void PN532::readData(uint8_t* buff, uint8_t n) { uint8_t buf[n + 2]; int rv; memset(buf, 0, n+2); usleep(2000); rv = m_i2c.read(buf, n + 2); if (m_pn532Debug) { cerr << __FUNCTION__ << ": read returned " << rv << "bytes" << endl; fprintf(stderr, "(raw) buf (%d) = ", rv); PrintHex(buf, rv); fprintf(stderr, "\n"); } for (int i=0; i<n; i++) buff[i] = buf[i+1]; if (m_pn532Debug) { fprintf(stderr, "(returned) buf (%d) = \n", n); PrintHex(buff, n); fprintf(stderr, "\n"); } } /**************************************************************************/ /*! @brief Writes a command to the PN532, automatically inserting the preamble and required frame details (checksum, len, etc.) @param cmd Pointer to the command buffer @param cmdlen Command length in bytes */ /**************************************************************************/ void PN532::writeCommand(uint8_t* cmd, uint8_t cmdlen) { // I2C command write. cmdlen++; usleep(2000); // 2ms max in case board needs to wake up // command + packet wrapper uint8_t buf[cmdlen + 8]; memset(buf, 0, cmdlen + 8); int offset = 0; if (m_pn532Debug) cerr << __FUNCTION__ << ": Sending: " << endl; uint8_t checksum = PN532_PREAMBLE + PN532_PREAMBLE + PN532_STARTCODE2; buf[offset++] = PN532_PREAMBLE; buf[offset++] = PN532_PREAMBLE; buf[offset++] = PN532_STARTCODE2; buf[offset++] = cmdlen; buf[offset++] = ~cmdlen + 1; buf[offset++] = PN532_HOSTTOPN532; checksum += PN532_HOSTTOPN532; for (uint8_t i=0; i<cmdlen - 1; i++) { buf[offset++] = cmd[i]; checksum += cmd[i]; } buf[offset++] = ~checksum; buf[offset] = PN532_POSTAMBLE; if (m_i2c.write(buf, cmdlen + 8 - 1) != mraa::SUCCESS) { throw std::runtime_error(std::string(__FUNCTION__) + ": mraa_i2c_write() failed"); return; } if (m_pn532Debug) { cerr << __FUNCTION__ << ": cmdlen + 8 = " << cmdlen + 8 <<", offset = " << offset << endl; PrintHex(buf, cmdlen + 8); } } void PN532::dataReadyISR(void *ctx) { upm::PN532 *This = (upm::PN532 *)ctx; // if debugging is enabled, indicate when an interrupt occurred, and // a previously triggered interrupt was still set. if (This->m_pn532Debug) if (This->m_irqRcvd) cerr << __FUNCTION__ << ": INFO: Unhandled IRQ detected." << endl; This->m_irqRcvd = true; } PN532::TAG_TYPE_T PN532::tagType() { // This is really just a guess, ATQA and SAK could in theory be used // to refine the detection. if (m_uidLen == 4) return TAG_TYPE_MIFARE_CLASSIC; else if (m_uidLen == 7) return TAG_TYPE_NFC2; else return TAG_TYPE_UNKNOWN; }
32.723634
138
0.537772
g-vidal
920480b3726dbde0caf825b1285953e6ea6970b6
3,370
cpp
C++
EZOJ/1976.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
6
2019-09-30T16:11:00.000Z
2021-11-01T11:42:33.000Z
BZOJ/2286.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-11-21T08:17:42.000Z
2020-07-28T12:09:52.000Z
EZOJ/1976.cpp
sshockwave/Online-Judge-Solutions
9d0bc7fd68c3d1f661622929c1cb3752601881d3
[ "MIT" ]
4
2017-07-26T05:54:06.000Z
2020-09-30T13:35:38.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> #include <algorithm> using namespace std; typedef long long lint; #define ni (next_num<int>()) #define nl (next_num<lint>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool flag=c=='-'; flag?(c=getchar()):0; while(i=i*10-'0'+c,isdigit(c=getchar())); return flag?-i:i; } inline void apmin(int &a,const int &b){ if(a>b){ a=b; } } const int N=250010,logN=20,INF=0x7f7f7f7f; struct Tree{ static const int E=N*2; int to[E],bro[E],val[E],head[N],etop; }; struct Virtual:Tree{ Virtual(){ memset(tag,0,sizeof(tag)); memset(vis,0,sizeof(vis)); tim=0; } int tag[N],tim; inline void add_edge(int,int); int vis[N]; lint f[N]; void dfs(int x){ f[x]=0; for(int i=head[x],v;~i;i=bro[i]){ if(vis[v=to[i]]==tim){ f[x]+=val[i]; }else{ dfs(v); f[x]+=min(f[v],(lint)val[i]); } } } }V; int dfn[N]; inline bool dfncmp(const int &a,const int &b){ return dfn[a]<dfn[b]; } struct Actual:Tree{ int fa[N][logN],len[N][logN],dep[N],ldep[N]; inline void reset(){ memset(head,-1,sizeof(head)); memset(len,127,sizeof(len)); memset(fa,0,sizeof(fa)); etop=tim=dep[1]=ldep[1]=0; dep[0]=-1; } inline void add_edge(int u,int v,int w){ to[etop]=v; bro[etop]=head[u]; val[etop]=w; head[u]=etop++; } int tim; void dfs(int x,int f){ dfn[x]=++tim; fa[x][0]=f; for(int &j=ldep[x];fa[x][j+1]=fa[fa[x][j]][j];j++){ len[x][j+1]=min(len[x][j],len[fa[x][j]][j]); } for(int i=head[x],v;~i;i=bro[i]){ v=to[i]; if(v!=f){ dep[v]=dep[x]+1; len[v][0]=val[i]; dfs(v,x); } } } inline int lca(int u,int v){ if(dep[u]<dep[v]){ swap(u,v); } for(int j=ldep[u];j>=0;j--){ if(dep[fa[u][j]]>=dep[v]){ u=fa[u][j]; } } if(u==v){ return u; } for(int j=min(ldep[u],ldep[v]);j>=0;j--){ if(fa[u][j]!=fa[v][j]){ u=fa[u][j],v=fa[v][j]; } } assert(fa[u][0]==fa[v][0]); return fa[u][0]; } inline int dist(int u,int v){ int ans=INF; if(dep[u]<dep[v]){ swap(u,v); } for(int j=ldep[u];j>=0;j--){ if(dep[fa[u][j]]>=dep[v]){ apmin(ans,len[u][j]); u=fa[u][j]; } } if(u==v){ return ans; } for(int j=min(ldep[u],ldep[v]);j>=0;j--){ if(fa[u][j]!=fa[v][j]){ apmin(ans,min(len[u][j],len[v][j])); u=fa[u][j],v=fa[v][j]; } } assert(fa[u][0]==fa[v][0]); return ans; } int seq[N],stk[N]; inline lint work(int n){ V.tim++; V.etop=0; for(int i=0;i<n;i++){ V.vis[seq[i]=ni]=V.tim; } sort(seq,seq+n,dfncmp); int stop=0; stk[++stop]=1; for(int i=0;i<n;i++){ int x=seq[i],f=x; for(int v=stk[stop];v!=f&&dep[f=lca(x,v)]<dep[v];v=stk[stop]){ if(dep[f]>dep[stk[--stop]]){ stk[++stop]=f; } V.add_edge(stk[stop],v); } assert(stk[stop]==f); assert(stk[stop]!=x); stk[++stop]=x; } for(;stop>1;stop--){ V.add_edge(stk[stop-1],stk[stop]); } V.dfs(1); return V.f[1]; } }T; inline void Virtual::add_edge(int u,int v){ if(tag[u]<tim){ tag[u]=tim; head[u]=-1; } to[etop]=v; bro[etop]=head[u]; val[etop]=T.dist(u,v); head[u]=etop++; } int main(){ T.reset(); int n=ni; for(int i=1;i<n;i++){ int u=ni,v=ni,w=ni; T.add_edge(u,v,w); T.add_edge(v,u,w); } T.dfs(1,0); for(int tot=ni;tot--;){ printf("%lld\n",T.work(ni)); } }
18.618785
65
0.532938
sshockwave
92054590491ca2f85f42b5fb39592aef33cdc3aa
2,018
cc
C++
L1Trigger/L1TCalorimeter/src/firmware/Stage1Layer2FlowAlgorithm.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
L1Trigger/L1TCalorimeter/src/firmware/Stage1Layer2FlowAlgorithm.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
L1Trigger/L1TCalorimeter/src/firmware/Stage1Layer2FlowAlgorithm.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
/// /// \class l1t::Stage1Layer2FlowAlgorithm /// /// \authors: Maxime Guilbaud /// R. Alex Barbieri /// /// Description: Flow Algorithm HI #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "L1Trigger/L1TCalorimeter/interface/Stage1Layer2HFRingSumAlgorithmImp.h" #include "L1Trigger/L1TCalorimeter/interface/PUSubtractionMethods.h" #include "L1Trigger/L1TCalorimeter/interface/legacyGtHelper.h" l1t::Stage1Layer2FlowAlgorithm::Stage1Layer2FlowAlgorithm(CaloParamsHelper const* params){ //now do what ever initialization is needed //Converting phi to be as it is define at GCT (-pi to pi instead of 0 to 2*pi) for(unsigned int i = 0; i < L1CaloRegionDetId::N_PHI; i++) { if(i < 10){ sinPhi.push_back(sin(2. * 3.1415927 * i * 1.0 / L1CaloRegionDetId::N_PHI)); cosPhi.push_back(cos(2. * 3.1415927 * i * 1.0 / L1CaloRegionDetId::N_PHI)); } else { sinPhi.push_back(sin(-3.1415927 + 2. * 3.1415927 * (i-9) * 1.0 / L1CaloRegionDetId::N_PHI)); cosPhi.push_back(cos(-3.1415927 + 2. * 3.1415927 * (i-9) * 1.0 / L1CaloRegionDetId::N_PHI)); } } } void l1t::Stage1Layer2FlowAlgorithm::processEvent(const std::vector<l1t::CaloRegion> & regions, const std::vector<l1t::CaloEmCand> & EMCands, const std::vector<l1t::Tau> * taus, l1t::CaloSpare * spare) { double q2x = 0; double q2y = 0; double regionET=0.; for(std::vector<CaloRegion>::const_iterator region = regions.begin(); region != regions.end(); region++) { int ieta=region->hwEta(); if (ieta > 3 && ieta < 18) { continue; } int iphi=region->hwPhi(); regionET=region->hwPt(); q2x+= regionET * cosPhi[iphi]; q2y+= regionET * sinPhi[iphi]; } int HFq2 = q2x*q2x+q2y*q2y; //double psi2 = 0.5 * atan(q2y/q2x); // ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > dummy(0,0,0,0); // l1t::CaloSpare V2 (*&dummy,CaloSpare::CaloSpareType::V2,(int)HFq2,0,0,0); // spares->push_back(V2); spare->SetRing(1, HFq2&0x7); }
33.081967
108
0.663528
bisnupriyasahu
9206c163e41e60d403ea2169a7939ceb6df56bd0
1,727
cpp
C++
src/prod/src/Common/ExtendedEventMetadata.cpp
leikong/service-fabric
6b81daab914c8cf02801073fe6b6e5bf97270e9b
[ "MIT" ]
null
null
null
src/prod/src/Common/ExtendedEventMetadata.cpp
leikong/service-fabric
6b81daab914c8cf02801073fe6b6e5bf97270e9b
[ "MIT" ]
null
null
null
src/prod/src/Common/ExtendedEventMetadata.cpp
leikong/service-fabric
6b81daab914c8cf02801073fe6b6e5bf97270e9b
[ "MIT" ]
null
null
null
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" namespace Common { ExtendedEventMetadata::ExtendedEventMetadata(std::string const& publicEventName, std::string const& category) : publicEventName_(publicEventName) , category_(category) { } std::unique_ptr<ExtendedEventMetadata> ExtendedEventMetadata::Create(std::string const& publicEventName, std::string const& category) { return std::make_unique<ExtendedEventMetadata>(publicEventName, category); } std::string ExtendedEventMetadata::AddMetadataFields(TraceEvent & traceEvent, size_t & fieldsCount) { size_t index = 0; traceEvent.AddEventField<std::string>("eventName", index); traceEvent.AddEventField<std::string>("category", index); // Number of appended fields. fieldsCount = index; return std::string(GetMetadataFieldsFormat().begin()); } void ExtendedEventMetadata::AppendFields(TraceEventContext & context) const { context.Write(GetPublicEventNameField()); context.Write(GetCategoryField()); } void ExtendedEventMetadata::AppendFields(StringWriter & writer) const { writer.Write(GetMetadataFieldsFormat(), GetPublicEventNameField(), GetCategoryField()); } StringLiteral const& ExtendedEventMetadata::GetMetadataFieldsFormat() { static StringLiteral const format("EventName: {0} Category: {1} "); return format; } }
35.979167
137
0.649682
leikong
920ebaa82d7448dd16b0f10e1eefa68995698dcc
11,122
cc
C++
third_party/blink/renderer/core/script/script_runner.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/script/script_runner.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/script/script_runner.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
/* * Copyright (C) 2010 Google, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * 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 "third_party/blink/renderer/core/script/script_runner.h" #include <algorithm> #include "base/feature_list.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/script/script_loader.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" #include "third_party/blink/renderer/platform/wtf/casting.h" namespace blink { ScriptRunner::ScriptRunner(Document* document) : ExecutionContextLifecycleStateObserver(document->GetExecutionContext()), document_(document), task_runner_(document->GetTaskRunner(TaskType::kNetworking)) { DCHECK(document); UpdateStateIfNeeded(); } void ScriptRunner::QueueScriptForExecution(PendingScript* pending_script) { DCHECK(pending_script); document_->IncrementLoadEventDelayCount(); switch (pending_script->GetSchedulingType()) { case ScriptSchedulingType::kAsync: pending_async_scripts_.insert(pending_script); break; case ScriptSchedulingType::kInOrder: pending_in_order_scripts_.push_back(pending_script); number_of_in_order_scripts_with_pending_notification_++; break; default: NOTREACHED(); break; } } void ScriptRunner::PostTask(const base::Location& web_trace_location) { task_runner_->PostTask( web_trace_location, WTF::Bind(&ScriptRunner::ExecuteTask, WrapWeakPersistent(this))); } void ScriptRunner::ContextLifecycleStateChanged( mojom::FrameLifecycleState state) { if (!IsExecutionSuspended()) PostTasksForReadyScripts(FROM_HERE); } bool ScriptRunner::IsExecutionSuspended() { return !GetExecutionContext() || GetExecutionContext()->IsContextPaused() || is_force_deferred_; } void ScriptRunner::SetForceDeferredExecution(bool force_deferred) { DCHECK(force_deferred != is_force_deferred_); is_force_deferred_ = force_deferred; if (!IsExecutionSuspended()) PostTasksForReadyScripts(FROM_HERE); } void ScriptRunner::PostTasksForReadyScripts( const base::Location& web_trace_location) { DCHECK(!IsExecutionSuspended()); for (size_t i = 0; i < async_scripts_to_execute_soon_.size(); ++i) { PostTask(web_trace_location); } for (size_t i = 0; i < in_order_scripts_to_execute_soon_.size(); ++i) { PostTask(web_trace_location); } } void ScriptRunner::ScheduleReadyInOrderScripts() { while (!pending_in_order_scripts_.IsEmpty() && pending_in_order_scripts_.front() ->IsReady()) { in_order_scripts_to_execute_soon_.push_back( pending_in_order_scripts_.TakeFirst()); PostTask(FROM_HERE); } } void ScriptRunner::DelayAsyncScriptUntilMilestoneReached( PendingScript* pending_script) { DCHECK(!delay_async_script_milestone_reached_); SECURITY_CHECK(pending_async_scripts_.Contains(pending_script)); pending_async_scripts_.erase(pending_script); // When the ScriptRunner is notified via // |NotifyDelayedAsyncScriptsMilestoneReached()|, the scripts in // |pending_delayed_async_scripts_| will be scheduled for execution. pending_delayed_async_scripts_.push_back(pending_script); } void ScriptRunner::NotifyDelayedAsyncScriptsMilestoneReached() { delay_async_script_milestone_reached_ = true; while (!pending_delayed_async_scripts_.IsEmpty()) { PendingScript* pending_script = pending_delayed_async_scripts_.TakeFirst(); DCHECK_EQ(pending_script->GetSchedulingType(), ScriptSchedulingType::kAsync); async_scripts_to_execute_soon_.push_back(pending_script); PostTask(FROM_HERE); } } bool ScriptRunner::CanDelayAsyncScripts() { static bool flags_enabled = base::FeatureList::IsEnabled(features::kDelayAsyncScriptExecution) || RuntimeEnabledFeatures:: DelayAsyncScriptExecutionUntilFinishedParsingEnabled() || RuntimeEnabledFeatures:: DelayAsyncScriptExecutionUntilFirstPaintOrFinishedParsingEnabled(); return !delay_async_script_milestone_reached_ && flags_enabled; } void ScriptRunner::NotifyScriptReady(PendingScript* pending_script) { SECURITY_CHECK(pending_script); switch (pending_script->GetSchedulingType()) { case ScriptSchedulingType::kAsync: // SECURITY_CHECK() makes us crash in a controlled way in error cases // where the PendingScript is associated with the wrong ScriptRunner // (otherwise we'd cause a use-after-free in ~ScriptRunner when it tries // to detach). SECURITY_CHECK(pending_async_scripts_.Contains(pending_script)); if (pending_script->IsEligibleForDelay() && CanDelayAsyncScripts()) { DelayAsyncScriptUntilMilestoneReached(pending_script); return; } pending_async_scripts_.erase(pending_script); async_scripts_to_execute_soon_.push_back(pending_script); PostTask(FROM_HERE); break; case ScriptSchedulingType::kInOrder: SECURITY_CHECK(number_of_in_order_scripts_with_pending_notification_ > 0); number_of_in_order_scripts_with_pending_notification_--; ScheduleReadyInOrderScripts(); break; default: NOTREACHED(); break; } } bool ScriptRunner::RemovePendingInOrderScript(PendingScript* pending_script) { auto it = std::find(pending_in_order_scripts_.begin(), pending_in_order_scripts_.end(), pending_script); if (it == pending_in_order_scripts_.end()) return false; pending_in_order_scripts_.erase(it); SECURITY_CHECK(number_of_in_order_scripts_with_pending_notification_ > 0); number_of_in_order_scripts_with_pending_notification_--; return true; } void ScriptRunner::MovePendingScript(Document& old_document, Document& new_document, ScriptLoader* script_loader) { Document* new_context_document = new_document.GetExecutionContext() ? To<LocalDOMWindow>(new_document.GetExecutionContext())->document() : &new_document; Document* old_context_document = old_document.GetExecutionContext() ? To<LocalDOMWindow>(old_document.GetExecutionContext())->document() : &old_document; if (old_context_document == new_context_document) return; PendingScript* pending_script = script_loader ->GetPendingScriptIfControlledByScriptRunnerForCrossDocMove(); if (!pending_script) { // The ScriptLoader is not controlled by ScriptRunner. This can happen // because MovePendingScript() is called for all <script> elements // moved between Documents, not only for those controlled by ScriptRunner. return; } old_context_document->GetScriptRunner()->MovePendingScript( new_context_document->GetScriptRunner(), pending_script); } void ScriptRunner::MovePendingScript(ScriptRunner* new_runner, PendingScript* pending_script) { auto it = pending_async_scripts_.find(pending_script); if (it != pending_async_scripts_.end()) { new_runner->QueueScriptForExecution(pending_script); pending_async_scripts_.erase(it); document_->DecrementLoadEventDelayCount(); return; } if (RemovePendingInOrderScript(pending_script)) { new_runner->QueueScriptForExecution(pending_script); document_->DecrementLoadEventDelayCount(); } } bool ScriptRunner::ExecuteInOrderTask() { TRACE_EVENT0("blink", "ScriptRunner::ExecuteInOrderTask"); if (in_order_scripts_to_execute_soon_.IsEmpty()) return false; PendingScript* pending_script = in_order_scripts_to_execute_soon_.TakeFirst(); DCHECK(pending_script); DCHECK_EQ(pending_script->GetSchedulingType(), ScriptSchedulingType::kInOrder) << "In-order scripts queue should not contain any async script."; pending_script->ExecuteScriptBlock(NullURL()); document_->DecrementLoadEventDelayCount(); return true; } bool ScriptRunner::ExecuteAsyncTask() { TRACE_EVENT0("blink", "ScriptRunner::ExecuteAsyncTask"); if (async_scripts_to_execute_soon_.IsEmpty()) return false; // Remove the async script loader from the ready-to-exec set and execute. PendingScript* pending_script = async_scripts_to_execute_soon_.TakeFirst(); DCHECK_EQ(pending_script->GetSchedulingType(), ScriptSchedulingType::kAsync) << "Async scripts queue should not contain any in-order script."; pending_script->ExecuteScriptBlock(NullURL()); document_->DecrementLoadEventDelayCount(); return true; } void ScriptRunner::ExecuteTask() { // This method is triggered by ScriptRunner::PostTask, and runs directly from // the scheduler. So, the call stack is safe to reenter. scheduler::CooperativeSchedulingManager::AllowedStackScope allowed_stack_scope(scheduler::CooperativeSchedulingManager::Instance()); if (IsExecutionSuspended()) return; if (ExecuteAsyncTask()) return; if (ExecuteInOrderTask()) return; } void ScriptRunner::Trace(Visitor* visitor) const { ExecutionContextLifecycleStateObserver::Trace(visitor); visitor->Trace(document_); visitor->Trace(pending_in_order_scripts_); visitor->Trace(pending_async_scripts_); visitor->Trace(pending_delayed_async_scripts_); visitor->Trace(async_scripts_to_execute_soon_); visitor->Trace(in_order_scripts_to_execute_soon_); } } // namespace blink
36.706271
96
0.757957
mghgroup
921031d9c560ad272a69d65fc902e40607d9b70e
617
cpp
C++
Engine/src/Core.cpp
njchensl/ASQUI
285d42a94573457dc7772a6a1d05b06ffb9a6398
[ "MIT" ]
1
2022-02-11T23:14:31.000Z
2022-02-11T23:14:31.000Z
Engine/src/Core.cpp
njchensl/ASQUI
285d42a94573457dc7772a6a1d05b06ffb9a6398
[ "MIT" ]
null
null
null
Engine/src/Core.cpp
njchensl/ASQUI
285d42a94573457dc7772a6a1d05b06ffb9a6398
[ "MIT" ]
null
null
null
#include "Core.h" namespace AsquiEngine { template <> String GetString<float2>(const float2& vec) { return fmt::format("{{x = {}, y = {}}}", vec.x, vec.y); } template <> String GetString<float3>(const float3& vec) { return fmt::format("{{x = {}, y = {}, z = {}}}", vec.x, vec.y, vec.z); } template <> String GetString<float4>(const float4& vec) { return fmt::format("{{x = {}, y = {}, z = {}, w = {}}}", vec.x, vec.y, vec.z, vec.w); } template <> String GetString<Quaternion>(const Quaternion& quat) { return fmt::format("{{x = {}, y = {}, z = {}, w = {}}}", quat.x, quat.y, quat.z, quat.w); } }
20.566667
93
0.554295
njchensl
92105c452e6afe0720afa7153119d93b67dffc75
9,483
cpp
C++
src/engine/logic/entity.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/engine/logic/entity.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
src/engine/logic/entity.cpp
FredTheDino/SpaceCat
e0ac174af72f92994b91480ba20f8d3a6688c29f
[ "MIT" ]
null
null
null
namespace Logic { bool init_entity() { // This limits the memory to one arena, just to keep // tabs on the memory, if you trust this code switch it // to true to have UNLIMITED entities. _fog_es.memory = Util::request_arena(false); _fog_es.next_free = 0; _fog_es.entities = Util::create_list<Entity *>(100), _fog_es.max_entity = -1; _fog_es.num_entities = 0; _fog_es.num_removed = 0; _fog_es.defrag_limit = 100; _fog_global_type_table.arena = Util::request_arena(); return true; } const char *Entity::show() { char *buffer = Util::request_temporary_memory<char>(512); char *ptr = buffer; EMeta meta_info = _fog_global_entity_list[(u32) type()]; auto write = [&ptr](const char *c) { while (*c) *(ptr++) = *(c++); }; auto seek = [&ptr]() { // Seeks until a nullterminated character. while (*ptr) ptr++; }; write(type_name()); write("\n"); u8 *raw_address = (u8 *) this; for (u32 i = 0; i < meta_info.num_fields; i++) { write(" "); // Indentation, might remove later. const ETypeInfo *info = fetch_type(meta_info.fields[i].hash); if (info) write(info->name); else write("????"); write(" "); write(meta_info.fields[i].name); if (info && info->show) { write(" = "); info->show(ptr, raw_address + meta_info.fields[i].offset); seek(); } write("\n"); } *ptr = '\0'; return buffer; } EMeta meta_data_for(EntityType type) { ASSERT((u32) type < (u32) EntityType::NUM_ENTITY_TYPES, "Invalid type"); EMeta meta = _fog_global_entity_list[(u32) type]; ASSERT(meta.registered, "Entity is not registerd."); return _fog_global_entity_list[(u32) type]; } void *_entity_vtable(EntityType type) { meta_data_for(type); return _fog_global_entity_vtable[(u32) type](); } template <typename T> bool contains_type() { return fetch_type(typeid(T).hash_code()); } bool contains_type(u64 hash) { return fetch_type(hash); } void register_type(ETypeInfo info) { ETypeInfo **current = _fog_global_type_table.data + (info.hash % TypeTable::NUM_SLOTS); while (*current) { if ((*current)->hash == info.hash) ERR("Type hash collision (last added ->) '%s' '%s', " "adding the same type twice?", info.name, (*current)->name); current = &(*current)->next; } info.next = nullptr; *current = _fog_global_type_table.arena->push(info); } template <typename T> const ETypeInfo *fetch_type() { return fetch_type(typeid(T).hash_code()); } const ETypeInfo *fetch_entity_type(EntityType type) { return fetch_type(meta_data_for(type).hash); } const ETypeInfo *fetch_type(u64 hash) { ETypeInfo *current = _fog_global_type_table.data[hash % TypeTable::NUM_SLOTS]; while (current) { if (current->hash == hash) return current; current = current->next; } ERR("Invalid entity query %llu", hash); return current; } // ES EntityID generate_entity_id() { EntityID id; _fog_es.num_entities++; if (_fog_es.next_free < 0) { // Reusing id.slot = -_fog_es.next_free - 1; _fog_es.next_free = _fog_es.entities[id.slot]->id.slot; } else { id.slot = _fog_es.next_free++; id.gen = 0; } if ((s32) _fog_es.entities.capacity <= id.slot) { _fog_es.entities.resize(id.slot * 2); } id.gen++; _fog_es.max_entity = MAX(id.slot, _fog_es.max_entity); return id; } template<typename T> EntityID add_entity(T entity) { static_assert(std::is_base_of<Entity, T>(), "You supplied a class that isn't based on Logic::Entity"); EntityID id = generate_entity_id(); entity.id = id; Util::allow_allocation(); _fog_es.entities[id.slot] = _fog_es.memory->push(entity); ASSERT((u64) _fog_es.entities[id.slot] > 1000, "Invalid pointer in entity system."); Util::strict_allocation_check(); return id; } EntityID add_entity_ptr(Entity *entity) { EntityID id = generate_entity_id(); entity->id = id; u32 size = Logic::fetch_entity_type(entity->type())->size; Util::allow_allocation(); Entity *copy = (Entity *) _fog_es.memory->push<u8>(size); Util::strict_allocation_check(); Util::copy_bytes(entity, copy, size); _fog_es.entities[id.slot] = entity; ASSERT((u64) _fog_es.entities[id.slot] > 1000, "Invalid pointer in entity system."); return id; } void clear_entitysystem() { _fog_es.memory->clear(); _fog_es.next_free = 0; _fog_es.entities.clear(); _fog_es.max_entity = 0; _fog_es.num_entities = 0; _fog_es.num_removed = 0; } Entity *fetch_entity(EntityID id) { if (id.slot >= 0) { Entity *entity = _fog_es.entities[id.slot]; if (entity && id == entity->id) return entity; } return nullptr; } template <typename T> T *fetch_entity(EntityID id) { Entity *entity = fetch_entity(id); ASSERT(entity, "Cannot find entity"); //ASSERT(entity->type() == T::st_type(), "Types don't match!"); return (T *) entity; } bool valid_entity(EntityID id) { return fetch_entity(id) != nullptr; } bool remove_entity(EntityID id) { Entity *entity = fetch_entity(id); if (!entity) return false; _fog_es.num_entities--; _fog_es.num_removed++; s32 slot = entity->id.slot; entity->id.slot = _fog_es.next_free; _fog_es.next_free = -slot - 1; if (slot == _fog_es.max_entity) { while (_fog_es.entities[_fog_es.max_entity]->id.slot < 0 && 0 <= _fog_es.max_entity) _fog_es.max_entity--; } return true; } void for_entity_of_type(EntityType type, MapFunc f) { for (s32 i = _fog_es.max_entity; 0 <= i; i--) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (e->type() != type) continue; if (f(e)) break; } } void for_entity(MapFunc f) { for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (f(e)) break; } } EntityID fetch_first_of_type(EntityType type) { for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (e->type() == type) return e->id; } return {-1, 0}; } void update_es() { START_PERF(ENTITY_UPDATE); const f32 delta = Logic::delta(); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; e->update(delta); } STOP_PERF(ENTITY_UPDATE); } void draw_es() { START_PERF(ENTITY_DRAW); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; e->draw(); } STOP_PERF(ENTITY_DRAW); } // TODO(ed): Make this doable across multiple frames, so we // can spend 1ms on it everyframe or something like that... void defragment_entity_memory() { START_PERF(ENTITY_DEFRAG); if (_fog_es.num_removed < _fog_es.defrag_limit) { STOP_PERF(ENTITY_DEFRAG); return; } // This is kinda hacky... Util::allow_allocation(); Util::MemoryArena *target_arena = Util::request_arena(false); u64 memory = 0; ASSERT(offsetof(Entity, id) < 16, "Empty entity is quite large"); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; u32 size; if (e->id.slot != i) { size = offsetof(Entity, id) + sizeof(EntityID); } else { size = fetch_type(meta_data_for(e->type()).hash)->size; } memory += size; Util::allow_allocation(); u8 *target = target_arena->push<u8>(size); Util::copy_bytes(e, target, size); _fog_es.entities[i] = (Entity *) target; ASSERT((u64) _fog_es.entities[i] > 1000, "Invalid pointer in entity system."); } ASSERT(memory < Util::ARENA_SIZE_IN_BYTES, "Too large allocations"); _fog_es.memory->pop(); _fog_es.memory = target_arena; _fog_es.num_removed = 0; // We've not removed any now STOP_PERF(ENTITY_DEFRAG); } };
31.61
92
0.538226
FredTheDino
92139c28276bfcdf47c00612ab639d6050b68b9f
2,906
cpp
C++
src/roseExtensions/qtWidgets/QCodeEditWidget/QCodeEdit/widgets/qlinechangepanel.cpp
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
src/roseExtensions/qtWidgets/QCodeEditWidget/QCodeEdit/widgets/qlinechangepanel.cpp
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
src/roseExtensions/qtWidgets/QCodeEditWidget/QCodeEdit/widgets/qlinechangepanel.cpp
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
/**************************************************************************** ** ** Copyright (C) 2006-2009 fullmetalcoder <fullmetalcoder@hotmail.fr> ** ** This file is part of the Edyuk project <http://edyuk.org> ** ** This file may be used under the terms of the GNU General Public License ** version 3 as published by the Free Software Foundation and appearing in the ** file GPL.txt included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include "qlinechangepanel.h" /*! \file qlinechangepanel.cpp \brief Implementation of the QLineChangePanel class. */ #include "qeditor.h" #include "qdocument.h" #include "qdocumentline.h" #include <QIcon> #include <QMenu> #include <QPainter> #include <QScrollBar> #include <QContextMenuEvent> /*! \ingroup widgets @{ */ /*! \class QLineMarkPanel \brief A specific panel in charge of drawing line numbers of an editor \see QEditorInterface */ QCE_AUTO_REGISTER(QLineChangePanel) /*! \brief Constructor */ QLineChangePanel::QLineChangePanel(QWidget *p) : QPanel(p) { setFixedWidth(4); } /*! \brief Empty destructor */ QLineChangePanel::~QLineChangePanel() { } /*! */ QString QLineChangePanel::type() const { return "Line changes"; } /*! \internal */ void QLineChangePanel::paint(QPainter *p, QEditor *e) { if ( !e || !e->document() ) return; const QFontMetrics fm( e->document()->font() ); int n, posY, maxCount = 0, as = fm.ascent(), ls = fm.lineSpacing(), pageBottom = e->viewport()->height(), contentsY = e->verticalOffset(); QString txt; QDocument *d = e->document(); n = d->lineNumber(contentsY); posY = 2 + d->y(n) - contentsY; for ( ; ; ++n ) { //qDebug("n = %i; pos = %i", n, posY); QDocumentLine line = d->line(n); if ( line.isNull() || ((posY - as) > pageBottom) ) break; if ( line.isHidden() ) continue; int span = line.lineSpan(); if ( d->isLineModified(line) ) { p->fillRect(1, posY, 2, ls * span, Qt::red); } else if ( d->hasLineEverBeenModified(line) ) { p->fillRect(1, posY, 2, ls * span, Qt::green); } posY += ls * span; } } /*! @} */
24.016529
78
0.488644
maurizioabba
92139d134e49a49f1929ba7f1f6b69a7adba6ded
3,311
cpp
C++
labs/lab_02/src/Lab_02.cpp
panda2ici/Computer-Graphics
c1d65004667dfa448856e62e7bf191b8203d77cd
[ "MIT" ]
null
null
null
labs/lab_02/src/Lab_02.cpp
panda2ici/Computer-Graphics
c1d65004667dfa448856e62e7bf191b8203d77cd
[ "MIT" ]
1
2020-02-28T16:23:47.000Z
2020-03-02T15:05:12.000Z
labs/lab_02/src/Lab_02.cpp
panda2ici/Computer-Graphics
c1d65004667dfa448856e62e7bf191b8203d77cd
[ "MIT" ]
1
2020-02-28T16:24:02.000Z
2020-02-28T16:24:02.000Z
//Lab 1 //modified from http://learnopengl.com/ #include "common/stdafx.h" using namespace std; GLFWwindow* window; glm::vec3 c_pos = glm::vec3(0, 0, 2); glm::vec3 c_dir = glm::normalize(glm::vec3(0, 0, -2)); glm::vec3 c_up = glm::vec3(0, 1, 0); glm::mat4 vm; int initWindow(); void update_view(); void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); int main() { if (initWindow() != 0) { return -1; } glClearColor(.7, .7, .7, 0); GLuint shdr = loadShaders("vertex.shader", "fragment.shader"); glUseProgram(shdr); std::vector<glm::vec3> v = { glm::vec3(0, 0, 0), glm::vec3(0, 1, 0), glm::vec3(1, 0, 0) }; GLuint VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*v.size(), &v[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); //------ MODEL MATRIX --------- glm::mat4 mm; glm::mat4 scale; glm::mat4 translate; glm::mat4 rotate; //------ VIEW MATRIX --------- vm = glm::lookAt(c_pos, c_pos + c_dir, c_up); //------ PROJECTION MATRIX ------- glm::mat4 pm = glm::perspective(45.f, 800.f / 600.f, 0.1f, 100.f); GLuint mm_addr = glGetUniformLocation(shdr, "m_m"); GLuint pm_addr = glGetUniformLocation(shdr, "p_m"); GLuint vm_addr = glGetUniformLocation(shdr, "v_m"); glUniformMatrix4fv(mm_addr, 1, false, glm::value_ptr(mm)); glUniformMatrix4fv(pm_addr, 1, false, glm::value_ptr(pm)); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); glUniformMatrix4fv(vm_addr, 1, false, glm::value_ptr(vm)); glm::mat4 anchor = glm::translate(glm::mat4(1.0f), -glm::vec3(0, 0.5, 0)); glm::mat4 _anchor = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0.5, 0)); scale = glm::scale(glm::mat4(1.0f), glm::vec3(.5, .5, .5)); translate = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, 0)); rotate = glm::rotate(glm::mat4(1.0f), glm::radians(0.f), glm::vec3(0, 0, 1)); glm::mat4 mem = translate * _anchor * rotate * anchor; mm = mem * scale; glUniformMatrix4fv(mm_addr, 1, false, glm::value_ptr(mm)); glDrawArrays(GL_TRIANGLES, 0, v.size()); translate = glm::translate(glm::mat4(1.0f), glm::vec3(0.5, -0.5, 0)); rotate = glm::rotate(glm::mat4(1.0f), glm::radians(45.f), glm::vec3(0, 0, 1)); mm = mem * translate * _anchor * rotate * anchor * scale; glUniformMatrix4fv(mm_addr, 1, false, glm::value_ptr(mm)); glDrawArrays(GL_TRIANGLES, 0, v.size()); glfwPollEvents(); glfwSwapBuffers(window); } return 0; } void update_view() { vm = glm::lookAt(c_pos, c_pos + c_dir, c_up); } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if (key == GLFW_KEY_DOWN) { c_pos.z += 1; update_view(); } if (key == GLFW_KEY_UP) { c_pos.z -= 1; update_view(); } } int initWindow() { glfwInit(); window = glfwCreateWindow(800, 600, "First windwo", nullptr, nullptr); glfwSetKeyCallback(window, keyCallback); if (window == nullptr) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (glewInit() != 0) { return -1; } return 0; }
22.834483
83
0.649653
panda2ici
9214dee7c741c7d1c00e28bc79cec4204ad13061
12,366
cpp
C++
Sources/WindowsEmbeddingDemo/WED_main.cpp
GerHobbelt/VisualScriptEngine
f76564d795b08d413a8625edba87dff21837039f
[ "MIT" ]
null
null
null
Sources/WindowsEmbeddingDemo/WED_main.cpp
GerHobbelt/VisualScriptEngine
f76564d795b08d413a8625edba87dff21837039f
[ "MIT" ]
null
null
null
Sources/WindowsEmbeddingDemo/WED_main.cpp
GerHobbelt/VisualScriptEngine
f76564d795b08d413a8625edba87dff21837039f
[ "MIT" ]
null
null
null
#include "NUIE_NodeEditor.hpp" #include "NUIE_NodeTree.hpp" #include "WAS_GdiOffscreenContext.hpp" #include "WAS_WindowsAppUtils.hpp" #include "WAS_HwndEventHandler.hpp" #include "WAS_ParameterDialog.hpp" #include "WAS_NodeTree.hpp" #include "BI_BuiltInNodes.hpp" #include <windows.h> #include <windowsx.h> static void InitNodeTree (NUIE::NodeTree& nodeTree) { size_t inputNodes = nodeTree.AddGroup (L"Input Nodes"); nodeTree.AddItem (inputNodes, L"Boolean", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::BooleanNode (NE::LocString (L"Boolean"), position, true)); }); nodeTree.AddItem (inputNodes, L"Integer", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::IntegerUpDownNode (NE::LocString (L"Integer"), position, 0, 1)); }); nodeTree.AddItem (inputNodes, L"Number", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DoubleUpDownNode (NE::LocString (L"Number"), position, 0.0, 1.0)); }); nodeTree.AddItem (inputNodes, L"Integer Increment", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::IntegerIncrementedNode (NE::LocString (L"Integer Increment"), position)); }); nodeTree.AddItem (inputNodes, L"Number Increment", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DoubleIncrementedNode (NE::LocString (L"Number Increment"), position)); }); nodeTree.AddItem (inputNodes, L"Number Distribution", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DoubleDistributedNode (NE::LocString (L"Number Distribution"), position)); }); nodeTree.AddItem (inputNodes, L"List Builder", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::ListBuilderNode (NE::LocString (L"List Builder"), position)); }); size_t arithmeticNodes = nodeTree.AddGroup (L"Arithmetic Nodes"); nodeTree.AddItem (arithmeticNodes, L"Addition", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::AdditionNode (NE::LocString (L"Addition"), position)); }); nodeTree.AddItem (arithmeticNodes, L"Subtraction", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::SubtractionNode (NE::LocString (L"Subtraction"), position)); }); nodeTree.AddItem (arithmeticNodes, L"Multiplication", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::MultiplicationNode (NE::LocString (L"Multiplication"), position)); }); nodeTree.AddItem (arithmeticNodes, L"Division", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DivisionNode (NE::LocString (L"Division"), position)); }); size_t otherNodes = nodeTree.AddGroup (L"Other Nodes"); nodeTree.AddItem (otherNodes, L"Viewer", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::MultiLineViewerNode (NE::LocString (L"Viewer"), position, 5)); }); } class MyEventHandler : public WAS::HwndEventHandler { public: MyEventHandler () : WAS::HwndEventHandler (), nodeEditor (nullptr), nodeTree () { InitNodeTree (nodeTree); } void SetNodeEditor (NUIE::NodeEditor* nodeEditorPtr) { nodeEditor = nodeEditorPtr; } virtual NUIE::MenuCommandPtr OnContextMenu (NUIE::EventHandler::ContextMenuType type, const NUIE::Point& position, const NUIE::MenuCommandStructure& commands) override { if (type == NUIE::EventHandler::ContextMenuType::EmptyArea) { NUIE::MenuCommandStructure finalCommands = commands; NUIE::AddNodeTreeToMenuStructure (nodeTree, position, nodeEditor, finalCommands); return WAS::SelectCommandFromContextMenu (hwnd, position, finalCommands); } else { return WAS::SelectCommandFromContextMenu (hwnd, position, commands); } } private: NUIE::NodeEditor* nodeEditor; NUIE::NodeTree nodeTree; }; class MyNodeUIEnvironment : public NUIE::NodeUIEnvironment { public: MyNodeUIEnvironment () : NUIE::NodeUIEnvironment (), stringConverter (NE::BasicStringConverter (WAS::GetStringSettingsFromSystem ())), skinParams (NUIE::GetDefaultSkinParams ()), eventHandler (), clipboardHandler (), evaluationEnv (nullptr), drawingContext (new WAS::GdiOffscreenContext ()), nodeEditor (nullptr), editorHandle (nullptr) { } void Init (NUIE::NodeEditor* nodeEditorPtr, HWND editorWindowHandle) { nodeEditor = nodeEditorPtr; editorHandle = editorWindowHandle; drawingContext->Init (editorHandle); eventHandler.Init (editorHandle); eventHandler.SetNodeEditor (nodeEditor); } void OnResize (int width, int height) { drawingContext->Resize (width, height); } void OnPaint () { nodeEditor->Draw (); drawingContext->BlitToWindow (editorHandle); } virtual const NE::StringConverter& GetStringConverter () override { return stringConverter; } virtual const NUIE::SkinParams& GetSkinParams () override { return skinParams; } virtual NUIE::DrawingContext& GetDrawingContext () override { return *drawingContext; } virtual double GetWindowScale () override { return 1.0; } virtual NE::EvaluationEnv& GetEvaluationEnv () override { return evaluationEnv; } virtual void OnEvaluationBegin () override { } virtual void OnEvaluationEnd () override { } virtual void OnValuesRecalculated () override { } virtual void OnRedrawRequested () override { InvalidateRect (editorHandle, NULL, FALSE); } virtual NUIE::EventHandler& GetEventHandler () override { return eventHandler; } virtual NUIE::ClipboardHandler& GetClipboardHandler () override { return clipboardHandler; } virtual void OnSelectionChanged (const NUIE::Selection&) override { } virtual void OnUndoStateChanged (const NUIE::UndoState&) override { } virtual void OnClipboardStateChanged (const NUIE::ClipboardState&) override { } virtual void OnIncompatibleVersionPasted (const NUIE::Version&) override { } private: NE::BasicStringConverter stringConverter; NUIE::BasicSkinParams skinParams; MyEventHandler eventHandler; NUIE::MemoryClipboardHandler clipboardHandler; NE::EvaluationEnv evaluationEnv; NUIE::NativeDrawingContextPtr drawingContext; NUIE::NodeEditor* nodeEditor; HWND editorHandle; }; static MyNodeUIEnvironment uiEnvironment; static NUIE::NodeEditor nodeEditor (uiEnvironment); static LRESULT CALLBACK ApplicationWindowProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: { uiEnvironment.Init (&nodeEditor, hwnd); } break; case WM_SIZE: { int newWidth = LOWORD (lParam); int newHeight = HIWORD (lParam); uiEnvironment.OnResize (newWidth, newHeight); } break; case WM_PAINT: uiEnvironment.OnPaint (); break; case WM_CLOSE: DestroyWindow (hwnd); break; case WM_DESTROY: PostQuitMessage (0); break; case WM_ERASEBKGND: return 0; case WM_LBUTTONDOWN: { WAS::SetWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDown (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Left, x, y); } break; case WM_MBUTTONDOWN: { WAS::SetWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDown (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Middle, x, y); } break; case WM_RBUTTONDOWN: { WAS::SetWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDown (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Right, x, y); } break; case WM_LBUTTONUP: { WAS::ReleaseWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseUp (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Left, x, y); } break; case WM_MBUTTONUP: { WAS::ReleaseWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseUp (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Middle, x, y); } break; case WM_RBUTTONUP: { WAS::ReleaseWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseUp (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Right, x, y); } break; case WM_MOUSEMOVE: { SetFocus (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseMove (WAS::GetModiferKeysFromEvent (wParam), x, y); } break; case WM_MOUSEWHEEL: { POINT mousePos; mousePos.x = GET_X_LPARAM (lParam); mousePos.y = GET_Y_LPARAM (lParam); ScreenToClient (hwnd, &mousePos); int delta = GET_WHEEL_DELTA_WPARAM (wParam); NUIE::MouseWheelRotation rotation = delta > 0 ? NUIE::MouseWheelRotation::Forward : NUIE::MouseWheelRotation::Backward; nodeEditor.OnMouseWheel (WAS::GetModiferKeysFromEvent (wParam), rotation, mousePos.x, mousePos.y); } break; case WM_LBUTTONDBLCLK: { int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDoubleClick (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Left, x, y); } break; case WM_MBUTTONDBLCLK: { int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDoubleClick (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Middle, x, y); } break; case WM_RBUTTONDBLCLK: { int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDoubleClick (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Right, x, y); } break; case WM_KEYDOWN: { NUIE::CommandCode commandCode = NUIE::CommandCode::Undefined; bool isControlPressed = (GetKeyState (VK_CONTROL) < 0); bool isShiftPressed = (GetKeyState (VK_SHIFT) < 0); if (isControlPressed) { switch (wParam) { case 'A': commandCode = NUIE::CommandCode::SelectAll; break; case 'C': commandCode = NUIE::CommandCode::Copy; break; case 'V': commandCode = NUIE::CommandCode::Paste; break; case 'G': if (isShiftPressed) { commandCode = NUIE::CommandCode::Ungroup; } else { commandCode = NUIE::CommandCode::Group; } break; case 'Z': if (isShiftPressed) { commandCode = NUIE::CommandCode::Redo; } else { commandCode = NUIE::CommandCode::Undo; } break; } } else { switch (wParam) { case VK_ESCAPE: commandCode = NUIE::CommandCode::Escape; break; case VK_DELETE: case VK_BACK: commandCode = NUIE::CommandCode::Delete; break; } } if (commandCode != NUIE::CommandCode::Undefined) { nodeEditor.ExecuteCommand (commandCode); } } break; case WM_CANCELMODE: WAS::ReleaseWindowCapture (hwnd); break; } return DefWindowProc (hwnd, msg, wParam, lParam); } #if defined(BUILD_MONOLITHIC) #define wWinMain WED_WinMain #endif int wWinMain (HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPWSTR /*lpCmdLine*/, int /*nCmdShow*/) { WNDCLASSEX windowClass; ZeroMemory (&windowClass, sizeof (WNDCLASSEX)); windowClass.cbSize = sizeof (WNDCLASSEX); windowClass.style = CS_DBLCLKS; windowClass.lpfnWndProc = ApplicationWindowProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = hInstance; windowClass.hIcon = LoadIcon (NULL, IDI_APPLICATION); windowClass.hIconSm = LoadIcon (NULL, IDI_APPLICATION); windowClass.hCursor = LoadCursor (NULL, IDC_ARROW); windowClass.hbrBackground = (HBRUSH) COLOR_WINDOW; windowClass.lpszMenuName = NULL; windowClass.lpszClassName = L"VisualScriptEngineDemo"; if (!RegisterClassEx (&windowClass)) { return 1; } RECT requiredRect = { 0, 0, 900, 500 }; AdjustWindowRect (&requiredRect, WS_OVERLAPPEDWINDOW, false); HWND windowHandle = CreateWindowEx ( WS_EX_WINDOWEDGE | WS_CLIPCHILDREN, windowClass.lpszClassName, L"Visual Script Engine Demo", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, requiredRect.right - requiredRect.left, requiredRect.bottom - requiredRect.top, NULL, NULL, NULL, nullptr ); if (windowHandle == NULL) { return 1; } ShowWindow (windowHandle, SW_SHOW); UpdateWindow (windowHandle); MSG msg; while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg); DispatchMessage (&msg); } return 0; }
28.558891
168
0.703057
GerHobbelt
921a323c58434473c208cf3a837cbb195f53020e
7,058
cpp
C++
system-test/cache_distributed.cpp
ThomasDai/MaxScale
766afedbada386b4402b8dbb21805e7eaba52323
[ "BSD-3-Clause" ]
null
null
null
system-test/cache_distributed.cpp
ThomasDai/MaxScale
766afedbada386b4402b8dbb21805e7eaba52323
[ "BSD-3-Clause" ]
1
2021-02-12T10:08:58.000Z
2021-02-18T02:57:57.000Z
system-test/cache_distributed.cpp
ThomasDai/MaxScale
766afedbada386b4402b8dbb21805e7eaba52323
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2024-11-26 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include <iostream> #include <string> #include <vector> #include <maxbase/string.hh> #include <maxtest/testconnections.hh> // This test checks // - that a failure to connect to redis/memcached does not stall the client and // - that when redis/memcached become available, they are transparently taken into use. using namespace std; namespace { const int PORT_RWS = 4006; const int PORT_RWS_REDIS = 4007; const int PORT_RWS_MEMCACHED = 4008; const int TIMEOUT = 10; // This should be bigger that the cache timeout in the config. bool restart_service(TestConnections& test, const char* zService) { bool rv = test.maxscales->ssh_node_f(0, true, "service %s restart", zService) == 0; sleep(1); // A short sleep to ensure connecting is possible. return rv; } bool start_service(TestConnections& test, const char* zService) { bool rv = test.maxscales->ssh_node_f(0, true, "service %s start", zService) == 0; sleep(1); // A short sleep to ensure connecting is possible. return rv; } bool stop_service(TestConnections& test, const char* zService) { return test.maxscales->ssh_node_f(0, true, "service %s stop", zService) == 0; } bool start_redis(TestConnections& test) { return start_service(test, "redis"); } bool stop_redis(TestConnections& test) { return stop_service(test, "redis"); } bool start_memcached(TestConnections& test) { return start_service(test, "memcached"); } bool stop_memcached(TestConnections& test) { return stop_service(test, "memcached"); } void drop(TestConnections& test) { MYSQL* pMysql = test.maxscales->conn_rwsplit[0]; test.try_query(pMysql, "DROP TABLE IF EXISTS cache_distributed"); test.maxscales->ssh_node_f(0, true, "redis-cli flushall"); restart_service(test, "memcached"); } void create(TestConnections& test) { drop(test); MYSQL* pMysql = test.maxscales->conn_rwsplit[0]; test.try_query(pMysql, "CREATE TABLE cache_distributed (f INT)"); } Connection connect(TestConnections& test, int port) { Connection c = test.maxscales->get_connection(port); bool connected = c.connect(); test.expect(connected, "Could not connect to %d.", port); return c; } void insert(TestConnections& test, Connection& c) { bool inserted = c.query("INSERT INTO cache_distributed values (1)"); test.expect(inserted, "Could not insert value."); } void select(TestConnections& test, const char* zName, Connection& c, size_t n) { Result rows = c.rows("SELECT * FROM cache_distributed"); test.expect(rows.size() == n, "%s: Expected %lu rows, but got %lu.", zName, n, rows.size()); } void install_and_start_redis_and_memcached(Maxscales& maxscales) { setenv("maxscale_000_keyfile", maxscales.sshkey(0), 0); setenv("maxscale_000_whoami", maxscales.user_name.c_str(), 0); setenv("maxscale_000_network", maxscales.ip4(0), 0); string path(test_dir); path += "/cache_install_and_start_storages.sh"; system(path.c_str()); } } int main(int argc, char* argv[]) { TestConnections::skip_maxscale_start(true); TestConnections test(argc, argv); auto maxscales = test.maxscales; install_and_start_redis_and_memcached(*maxscales); maxscales->start(); if (maxscales->connect_rwsplit() == 0) { create(test); sleep(1); Connection none = connect(test, PORT_RWS); insert(test, none); test.tprintf("Connecting with running redis/memcached."); test.set_timeout(TIMEOUT); Connection redis = connect(test, PORT_RWS_REDIS); Connection memcached = connect(test, PORT_RWS_MEMCACHED); // There has been 1 insert so we should get 1 in all cases. As redis and memcached // are running, the caches will be populated as well. test.set_timeout(TIMEOUT); select(test, "none", none, 1); select(test, "redis", redis, 1); select(test, "memcached", memcached, 1); test.stop_timeout(); test.tprintf("Stopping redis/memcached."); stop_redis(test); stop_memcached(test); test.tprintf("Connecting with stopped redis/memcached."); // Using a short timeout at connect-time ensure that if the async connecting // does not work, we'll get a quick failure. test.set_timeout(TIMEOUT); redis = connect(test, PORT_RWS_REDIS); memcached = connect(test, PORT_RWS_MEMCACHED); // There has still been only one insert, so in all cases we should get just one row. // As redis and memcached are not running, the result comes from the backend. test.set_timeout(TIMEOUT); select(test, "none", none, 1); select(test, "redis", redis, 1); select(test, "memcached", memcached, 1); test.stop_timeout(); // Lets add another row. insert(test, none); // There has been two inserts, and as redis/memcached are stopped, we should // get two in all cases. test.set_timeout(TIMEOUT); select(test, "none", none, 2); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); test.stop_timeout(); test.tprintf("Starting redis/memcached."); start_redis(test); start_memcached(test); sleep(1); // To allow things to stabalize. // As the caches are now running, they will now be taken into use. However, that // will be triggered by the fetching and hence the first result will be fetched from // the backend and possibly cached as well, if the connection to the cache is established // faster that what getting the result from the backend is. test.set_timeout(TIMEOUT); select(test, "none", none, 2); select(test, "redis", redis, 2); select(test, "memcache", memcached, 2); test.stop_timeout(); // To make sure the result ends up in the cache, we select again after having slept // for a short while. sleep(2); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); // Add another row, should not be visible from cached alternatives. insert(test, none); select(test, "none", none, 3); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); // Add yet another row, should not be visible from cached alternatives. insert(test, none); select(test, "none", none, 4); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); } else { ++test.global_result; } return test.global_result; }
30.034043
97
0.66081
ThomasDai
9220ba602ed16f5e80dd6083c04c278af0bf33c5
1,087
hpp
C++
include/xul/util/gzip.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
2
2018-03-16T07:06:48.000Z
2018-04-02T03:02:14.000Z
include/xul/util/gzip.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
null
null
null
include/xul/util/gzip.hpp
hindsights/xul
666ce90742a9919d538ad5c8aad618737171e93b
[ "MIT" ]
1
2019-08-12T05:15:29.000Z
2019-08-12T05:15:29.000Z
#pragma once #include "zlib.h" namespace xul { int gzip_uncompress( Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) { z_stream stream; int err; int gzip = 1; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; if (gzip == 1) { err = inflateInit2(&stream, 47); } else { err = inflateInit(&stream); } if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; } }
20.903846
79
0.594296
hindsights
92225a4239d3b912d52bdb714a4e60ea88887894
4,849
cpp
C++
z3/src/Macierz.cpp
KolodziejJakub/UkladRownan
522bec5390ed79c34194cb5b0e18eb2a5f2317c2
[ "MIT" ]
null
null
null
z3/src/Macierz.cpp
KolodziejJakub/UkladRownan
522bec5390ed79c34194cb5b0e18eb2a5f2317c2
[ "MIT" ]
null
null
null
z3/src/Macierz.cpp
KolodziejJakub/UkladRownan
522bec5390ed79c34194cb5b0e18eb2a5f2317c2
[ "MIT" ]
null
null
null
#include "Macierz.hh" Macierz::Macierz(Wektor a1, Wektor a2, Wektor a3) { Wektor a1,a2,a3; } double & Wektor::operator[](int index) { if(index > ROZMIAR || index < 0) { exit(1); } return tab[index]; } const double & Wektor::operator[](int index) const { if(index > ROZMIAR || index < 0) { exit(1); } return tab[index]; } void Macierz::transpozycja() { Macierz pomoc; for (int i=0; i<ROZMIAR; i++) { for(int j=0; j<ROZMIAR; j++) { pomoc[i][j]=tab[i][j]; } } for (int i=0; i<ROZMIAR; i++) { for(int j=0; j<ROZMIAR; j++) { tab[i][j]=pomoc[j][i]; } } } Wektor Macierz::operator *(Wektor W) { Wektor Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i]=Wynik[i] + (tab[i][j]*W[j]); } } return Wynik; } Macierz Macierz::operator *(Macierz W) { Macierz Wynik; W.transpozycja(); for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=Wynik[i][j] + (tab[i][j] * W[i][j]); } } return Wynik; } Macierz Macierz::operator +(Macierz W) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]+W[i][j]; } } return Wynik; } Macierz Macierz::operator -(Macierz W) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]-W[i][j]; } } return Wynik; } Macierz Macierz::operator * (double l) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]*l; } } return Wynik; } double Macierz::wyznacznikSarus () { double Wynik; Wynik = tab[0][0]*tab[1][1]*tab[2][2]+tab[1][0]*tab[2][1]*tab[0][2]+ tab[2][0]*tab[0][1]*tab[0][2]-tab[0][2]*tab[1][1]*tab[2][0]- tab[1][2]*tab[2][1]*tab[0][0]-tab[2][2]*tab[0][1]*tab[1][0]; return Wynik; } void Macierz::odwrotnosc() { int s; Macierz wyzn, pomoc; double mac2x2[4]; double wyznacznik; for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { wyzn[i][j]=tab[i][j]; pomoc[i][j]=tab[i][j]; } } wyznacznik = wyzn.wyznacznikSarus; for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { s=0; for (int k=0; k<ROZMIAR; k++) { for (int l=0; l<ROZMIAR; l++) { if (k != i && l != j) { mac2x2[s]=pomoc[k][l]; s++; } } } if ((i+j)%2 != 0) { wyzn[i][j]=-(Wyznacznik2x2(mac2x2)); } else { wyzn[i][j]=Wyznacznik2x2(mac2x2); } } } wyzn.transpozycja(); for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { tab[i][j]=(1/wyznacznik)*wyzn[i][j]; } } } double Macierz::Wyznacznik2x2 (double mac2x2[4]) { double Wynik; Wynik=mac2x2[0]*mac2x2[2]-mac2x2[1]*mac2x2[3]; return Wynik; } bool Macierz::operator == (const Macierz & W2)const { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { if (abs(tab[i][j]-W2[i][j]) >= 0.000001) { return false; } } } return true; } bool Macierz::operator != (const Macierz & W2)const { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { if (abs(tab[i][j]-W2[i][j]) >= 0.000001) { return true; } } } return false; } const Wektor & Macierz::zwroc_kolumne (int ind) { Wektor Wynik; for (int i=0; i<ROZMIAR; i++) { Wynik[i] = tab[ind][i]; } return Wynik; } void Macierz::zmien_kolumne(int ind, Wektor nowy) { for (int i=0; i<ROZMIAR; i++) { tab[ind][i] = nowy[i]; } } std::istream& operator >> (std::istream &Strm, Macierz &Mac) { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Strm>>Mac[i][j]; return Strm; } } Mac.transpozycja(); } std::ostream& operator << (std::ostream &Strm, Macierz &Mac) { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Strm<<Mac[i][j]; return Strm; } } }
18.026022
72
0.427717
KolodziejJakub
9222aba570462a9eb7727e3e2e65b851a71d1ed8
7,859
cpp
C++
src/engine/luabind/script-lua-core.cpp
septag/darkhammer
dd7e32737059ce6dba0aa79f1ae4a59137db06a7
[ "BSD-2-Clause" ]
68
2015-01-06T08:38:32.000Z
2022-01-20T15:26:17.000Z
src/engine/luabind/script-lua-core.cpp
septag/darkhammer
dd7e32737059ce6dba0aa79f1ae4a59137db06a7
[ "BSD-2-Clause" ]
null
null
null
src/engine/luabind/script-lua-core.cpp
septag/darkhammer
dd7e32737059ce6dba0aa79f1ae4a59137db06a7
[ "BSD-2-Clause" ]
12
2015-10-31T11:30:15.000Z
2020-04-13T18:31:17.000Z
/*********************************************************************************** * Copyright (c) 2012, Sepehr Taghdisian * 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. * ***********************************************************************************/ #include <stdio.h> #include "luacore.i" #include "script.h" #include "dhcore/util.h" /************************************************************************************************* * global funcs */ void printcon(const char* text) { if (text == NULL) { log_printf(LOG_WARNING, "incoming [null] text for 'printcon'"); return; } log_printf(LOG_INFO, "lua: %s", text); } float randFloat(float min, float max) { return rand_getf(min, max); } int randInt(int min, int max) { return rand_geti(min, max); } /************************************************************************************************* * vector funcs */ Vector::Vector() { vec3_setzero(&v_); } Vector::Vector(float x, float y, float z) { vec3_setf(&v_, x, y, z); } Vector::Vector(const Vector& v) { vec3_setv(&this->v_, &v.v_); } const char* Vector::__str__() { static char text[64]; sprintf(text, "Vector: %.3f %.3f %.3f", v_.x, v_.y, v_.z); return text; } Vector& Vector::__eq__(const Vector& v) { vec3_setv(&this->v_, &v.v_); return *this; } Vector Vector::__add__(const Vector& v1) { Vector r; vec3_add(&r.v_, &this->v_, &v1.v_); return r; } Vector Vector::__sub__(const Vector& v1) { Vector r; vec3_sub(&r.v_, &this->v_, &v1.v_); return r; } float Vector::__mul__(const Vector& v1) { return vec3_dot(&this->v_, &v1.v_); } Vector Vector::__mul__(float k) { Vector r; vec3_muls(&r.v_, &this->v_, k); return r; } Vector Vector::__div__(float k) { Vector r; vec3_muls(&r.v_, &this->v_, 1.0f/k); return r; } Vector Vector::cross(const Vector& v) { Vector r; vec3_cross(&r.v_, &this->v_, &v.v_); return r; } float Vector::x() const { return v_.x; } float Vector::y() const { return v_.y; } float Vector::z() const { return v_.z; } void Vector::set(float x, float y, float z) { v_.x = x; v_.y = y; v_.z = z; } void Vector::lerp(const Vector& v1, const Vector& v2, float t) { vec3_lerp(&this->v_, &v1.v_, &v2.v_, t); } void Vector::cubic(const Vector& v0, const Vector& v1, const Vector& v2, const Vector& v3, float t) { vec3_cubic(&this->v_, &v0.v_, &v1.v_, &v2.v_, &v3.v_, t); } void Vector::normalize() { vec3_norm(&v_, &v_); } void Vector::__setitem__(int x, float value) { if (x < 0 || x > 2) { sct_throwerror("Index out of bounds"); return; } v_.f[x] = value; } float Vector::__getitem__(int x) { if (x < 0 || x > 2) { sct_throwerror("Index out of bounds"); return 0.0f; } return v_.f[x]; } /************************************************************************************************* * Quat */ Quat::Quat() { quat_setidentity(&this->q_); } Quat::Quat(float x, float y, float z, float w) { quat_setf(&this->q_, x, y, z, w); } Quat::Quat(const Quat& q) { quat_setq(&this->q_, &q.q_); } const char* Quat::__str__() { static char text[64]; sprintf(text, "Quat: %.3f %.3f %.3f %.3f", q_.x, q_.y, q_.z, q_.w); return text; } Quat& Quat::__eq__(const Quat& q) { quat_setq(&this->q_, &q.q_); return *this; } void Quat::setEuler(float rx, float ry, float rz) { quat_fromeuler(&this->q_, rx, ry, rz); } Vector Quat::getEuler() { float rx; float ry; float rz; quat_geteuler(&rx, &ry, &rz, &this->q_); Vector r; vec3_setf(&r.v_, rx, ry, rz); return r; } Quat& Quat::inverse() { quat_inv(&this->q_, &this->q_); return *this; } void Quat::slerp(const Quat& q1, const Quat& q2, float t) { quat_slerp(&this->q_, &q1.q_, &q2.q_, t); } float Quat::__getitem__(int x) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return 0.0f; } return q_.f[x]; } void Quat::__setitem__(int x, float value) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return; } q_.f[x] = value; } /************************************************************************************************* * Color */ Color::Color() { color_setc(&c_, &g_color_black); } Color::Color(float r, float g, float b, float a) { color_setf(&c_, r, g, b, a); } Color::Color(const Color& c) { color_setc(&c_, &c.c_); } void Color::set(float r, float g, float b, float a) { color_setf(&c_, r, g, b, a); } void Color::setInt(uint r, uint g, uint b, uint a) { color_seti(&c_, (uint8)r, (uint8)g, (uint8)b, (uint8)a); } const char* Color::__str__() { static char text[64]; sprintf(text, "Color: %.3f %.3f %.3f %.3f", c_.r, c_.r, c_.b, c_.a); return text; } Color& Color::__eq__(const Color& c) { color_setc(&c_, &c.c_); return *this; } Color Color::__add__(const Color& c1) { Color r; color_add(&r.c_, &c_, &c1.c_); return r; } Color Color::__mul__(const Color& c1) { Color r; color_mul(&r.c_, &c_, &c1.c_); return r; } Color Color::__mul__(float k) { Color r; color_muls(&r.c_, &c_, k); return r; } float Color::r() const { return c_.r; } float Color::g() const { return c_.g; } float Color::b() const { return c_.b; } float Color::a() const { return c_.a; } void Color::lerp(const Color& c1, const Color& c2, float t) { color_lerp(&c_, &c1.c_, &c2.c_, t); } Color Color::toGamma() { Color r; color_togamma(&r.c_, &c_); return r; } Color Color::toLinear() { Color r; color_tolinear(&r.c_, &c_); return r; } uint Color::toUint() { return color_rgba_uint(&c_); } float Color::__getitem__(int x) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return 0.0f; } return c_.f[x]; } void Color::__setitem__(int x, float value) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return; } c_.f[x] = value; } /************************************************************************************************* * Vector2D */ Vector2D::Vector2D() { vec2i_setzero(&v_); } Vector2D::Vector2D(int x, int y) { vec2i_seti(&v_, x, y); } Vector2D::Vector2D(const Vector2D& v) { vec2i_setv(&v_, &v.v_); } void Vector2D::set(int x, int y) { vec2i_seti(&v_, x, y); } const char* Vector2D::__str() { static char text[64]; sprintf(text, "Vector2D: %d, %d", v_.x, v_.y); return text; } Vector2D& Vector2D::__eq__(const Vector2D& v) { vec2i_setv(&v_, &v.v_); return *this; } Vector2D Vector2D::__add__(const Vector2D& v1) { Vector2D r; vec2i_add(&r.v_, &v_, &v1.v_); return r; } Vector2D Vector2D::__sub__(const Vector2D& v1) { Vector2D r; vec2i_sub(&r.v_, &v_, &v1.v_); return r; } Vector2D Vector2D::__mul__(int k) { Vector2D r; vec2i_muls(&r.v_, &v_, k); return r; } void Vector2D::__setitem__(int x, int value) { if (x < 0 || x > 1) { sct_throwerror("Index out of bounds"); return; } v_.n[x] = value; } int Vector2D::__getitem__(int x) { if (x < 0 || x > 1) { sct_throwerror("Index out of bounds"); return 0; } return v_.n[x]; }
17.621076
99
0.537473
septag
92234105f6f8264a51fffbcf71c5a638f309e984
6,947
hpp
C++
include/pfasst/interfaces.hpp
danielru/PFASST
d74a822f98fc84ae98232a61fed6f47f60341b08
[ "BSD-2-Clause" ]
null
null
null
include/pfasst/interfaces.hpp
danielru/PFASST
d74a822f98fc84ae98232a61fed6f47f60341b08
[ "BSD-2-Clause" ]
null
null
null
include/pfasst/interfaces.hpp
danielru/PFASST
d74a822f98fc84ae98232a61fed6f47f60341b08
[ "BSD-2-Clause" ]
null
null
null
/* * Interfaces for SDC/MLSDC/PFASST algorithms. */ #ifndef _PFASST_INTERFACES_HPP_ #define _PFASST_INTERFACES_HPP_ #include <cassert> #include <deque> #include <exception> #include <iterator> #include <memory> #include <string> #include "globals.hpp" using namespace std; namespace pfasst { using time_precision = double; // forward declare for ISweeper template<typename time> class Controller; /** * not implemented yet exception. * * Used by PFASST to mark methods that are required for a particular algorithm (SDC/MLSDC/PFASST) * that may not be necessary for all others. */ class NotImplementedYet : public exception { string msg; public: NotImplementedYet(string msg) : msg(msg) {} const char* what() const throw() { return (string("Not implemented/supported yet, required for: ") + this->msg).c_str(); } }; /** * value exception. * * Thrown when a PFASST routine is passed an invalid value. */ class ValueError : public exception { string msg; public: ValueError(string msg) : msg(msg) {} const char* what() const throw() { return (string("ValueError: ") + this->msg).c_str(); } }; class ICommunicator { public: virtual ~ICommunicator() { } virtual int size() = 0; virtual int rank() = 0; }; /** * abstract SDC sweeper. * @tparam time time precision * defaults to pfasst::time_precision */ template<typename time = time_precision> class ISweeper { protected: Controller<time>* controller; public: //! @{ virtual ~ISweeper() {} //! @} //! @{ /** * set the sweepers controller. */ void set_controller(Controller<time>* ctrl) { this->controller = ctrl; } Controller<time>* get_controller() { assert(this->controller); return this->controller; } //! @} //! @{ /** * setup (allocate etc) the sweeper. * @param[in] coarse * `true` if this sweeper exists on a coarsened MLSDC or PFASST level. * This implies that space for an FAS correction and "saved" solutions are necessary. */ virtual void setup(bool coarse = false) { UNUSED(coarse); } /** * perform a predictor sweep. * * Compute a provisional solution from the initial condition. * This is typically very similar to a regular SDC sweep, except that integral terms based on * previous iterations don't exist yet. * @param[in] initial * `true` if function values at the first node need to be computed. * `false` if functions values at the first node already exist (usually this is the case * when advancing from one time step to the next). */ virtual void predict(bool initial) = 0; /** * Perform one SDC sweep/iteration. * * Compute a correction and update solution values. Note that this function can assume that * valid function values exist from a previous pfasst::ISweeper::sweep() or * pfasst::ISweeper::predict(). */ virtual void sweep() = 0; /** * Advance from one time step to the next. * * Essentially this means copying the solution and function values from the last node to the * first node. */ virtual void advance() = 0; /** * Save states (and/or function values) at all nodes. * * This is typically done in MLSDC/PFASST immediately after a call to restrict. * The saved states are used to compute deltas during interpolation. * * @note This method must be implemented in derived sweepers. */ virtual void save(bool initial_only=false) { UNUSED(initial_only); throw NotImplementedYet("mlsdc/pfasst"); } virtual void spread() { throw NotImplementedYet("pfasst"); } //! @} //! @{ virtual void post(ICommunicator* comm, int tag) { UNUSED(comm); UNUSED(tag); }; virtual void send(ICommunicator* comm, int tag, bool blocking) { UNUSED(comm); UNUSED(tag); UNUSED(blocking); throw NotImplementedYet("pfasst"); } virtual void recv(ICommunicator* comm, int tag, bool blocking) { UNUSED(comm); UNUSED(tag); UNUSED(blocking); throw NotImplementedYet("pfasst"); } virtual void broadcast(ICommunicator* comm) { UNUSED(comm); throw NotImplementedYet("pfasst"); } //! @} }; /** * abstract time/space transfer (restrict/interpolate) class. * @tparam time time precision * defaults to pfasst::time_precision */ template<typename time = time_precision> class ITransfer { public: //! @{ virtual ~ITransfer() {} //! @} //! @{ /** * Interpolate initial condition from the coarse sweeper to the fine sweeper. */ virtual void interpolate_initial(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) { UNUSED(dst); UNUSED(src); throw NotImplementedYet("pfasst"); } /** * Interpolate, in time and space, from the coarse sweeper to the fine sweeper. * @param[in] interp_initial * `true` if a delta for the initial condtion should also be computed (PFASST). */ virtual void interpolate(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src, bool interp_initial = false) = 0; /** * Restrict initial condition from the fine sweeper to the coarse sweeper. * @param[in] restrict_initial * `true` if the initial condition should also be restricted. */ virtual void restrict_initial(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) { UNUSED(dst); UNUSED(src); throw NotImplementedYet("pfasst"); } /** * Restrict, in time and space, from the fine sweeper to the coarse sweeper. * @param[in] restrict_initial * `true` if the initial condition should also be restricted. */ virtual void restrict(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src, bool restrict_initial = false) = 0; /** * Compute FAS correction between the coarse and fine sweepers. */ virtual void fas(time dt, shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) = 0; //! @} }; } // ::pfasst #endif
25.921642
99
0.579531
danielru
9227a459875871befbe049779c58d71e0167cca8
2,375
cpp
C++
src/SchemaLex.cpp
eXtremal-ik7/config4cpp
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
[ "MIT" ]
null
null
null
src/SchemaLex.cpp
eXtremal-ik7/config4cpp
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
[ "MIT" ]
null
null
null
src/SchemaLex.cpp
eXtremal-ik7/config4cpp
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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's //-------- #include "SchemaLex.h" namespace CONFIG4CPP_NAMESPACE { //-------- // This array must be kept sorted becaue we do a binary search on it. //-------- static LexBase::KeywordInfo keywordInfoArray[] = { //---------------------------------------------------------------------- // spelling symbol //---------------------------------------------------------------------- {"@ignoreEverythingIn", SchemaLex::LEX_IGNORE_EVERYTHING_IN_SYM}, {"@ignoreScopesIn", SchemaLex::LEX_IGNORE_SCOPES_IN_SYM}, {"@ignoreVariablesIn", SchemaLex::LEX_IGNORE_VARIABLES_IN_SYM}, {"@optional", SchemaLex::LEX_OPTIONAL_SYM}, {"@required", SchemaLex::LEX_REQUIRED_SYM}, {"@typedef", SchemaLex::LEX_TYPEDEF_SYM}, }; const static int keywordInfoArraySize = sizeof(keywordInfoArray) / sizeof(keywordInfoArray[0]); SchemaLex::SchemaLex(const char * str) : LexBase(str) { m_keywordInfoArray = keywordInfoArray; m_keywordInfoArraySize = keywordInfoArraySize; } SchemaLex::~SchemaLex() { } }; // namespace CONFIG4CPP_NAMESPACE
33.928571
73
0.633684
eXtremal-ik7
922a63aeb275ce1f99a7af8012a001ed473ee879
1,582
cpp
C++
graphs/dijkstraPqueue.cpp
tkjenll/algorhythm
00c20a1676520a8f34a1be74773faa9903049ce5
[ "MIT" ]
3
2017-10-13T04:08:01.000Z
2021-03-02T10:04:32.000Z
graphs/dijkstraPqueue.cpp
METHLAB-LTD/algorhythm
00c20a1676520a8f34a1be74773faa9903049ce5
[ "MIT" ]
null
null
null
graphs/dijkstraPqueue.cpp
METHLAB-LTD/algorhythm
00c20a1676520a8f34a1be74773faa9903049ce5
[ "MIT" ]
4
2019-02-06T01:22:51.000Z
2020-09-12T16:26:43.000Z
/* Time Complexity : 1. Shortest path by Dijkstra, using a Binary Min-heap as priority queue O(|V| + |E|)*log|V| = O(|E|log|V|) 2. Shortest path by Dijkstra, using a Fibonacci Min-heap as priority queue O(|E| + |V|log|V|) 3. Shortest path by Dijkstra, using an unsorted array as priority queue O(|V|^2) */ #include<cstdio> #include<vector> #include<queue> using namespace std; enum{NIL = -1, MAX = 50, INF = 9999}; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<vii> vvii; vvii G(MAX); vi dist(MAX); vi parent(MAX); int n; void dijkstra(int s) { for(int u = 0; u < n; u++) { dist[u] = INF; parent[u] = NIL; } dist[s] = 0; priority_queue<ii, vector<ii>, greater<ii> > Q; Q.push(ii(dist[s],s)); while(!Q.empty()) { ii top = Q.top(); Q.pop(); int u = top.second; int d = top.first; if(d <= dist[u]) { for(vii::iterator it = G[u].begin(); it != G[u].end(); ++it) { int v = it->first; int w = it->second; if(dist[v] > dist[u] + w) { dist[v] = dist[u] + w; parent[v] = u; Q.push(ii(dist[v],v)); } } } } } void printPath(int s, int t) { if(t == s) printf("%d ",s); else { printPath(s, parent[t]); printf("%d ",t); } } int main() { int m; scanf("%d %d",&n,&m); int u,v,w; for(int i = 0; i < m; i++) { scanf("%d %d %d",&u,&v,&w); G[u].push_back(ii(v,w)); G[v].push_back(ii(u,w)); } int s, t; scanf("%d %d",&s,&t); dijkstra(s); printPath(s,t); printf("\n"); return 0; }
16.652632
63
0.540455
tkjenll
922b4b647d30edb95e8786cac0535805dd0ad0d1
4,312
hpp
C++
src/cpp/ee/cocos/EEDataUtils.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/cocos/EEDataUtils.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
src/cpp/ee/cocos/EEDataUtils.hpp
enrevol/ee-x
60a66ad3dc6e14802a7c5d8d585a8499be13f5b8
[ "MIT" ]
null
null
null
// // EEDataUtils.hpp // ee-library // // Created by Zinge on 7/20/17. // // #ifndef EE_LIBRARY_DATA_UTILS_HPP #define EE_LIBRARY_DATA_UTILS_HPP #ifdef __cplusplus #include <cstddef> #include <string> #include "ee/cocos/EEDataMeta.hpp" namespace ee { namespace detail { /// Globally sets a data value. /// @param[in] dataId The data unique ID. /// @param[in] key The data key. /// @param[in] value The data value. void set0(std::size_t dataId, const std::string& key, const std::string& value); /// Globally gets a data value. /// @param[in] dataId The data unique ID. /// @param]in] key The data key. /// @param[out] result The data value. /// @return True if result is assigned, false otherwise. bool get0(std::size_t dataId, const std::string& key, std::string& result); /// Globally removes a data value. /// @param[in] dataId The data unique ID. /// @param[in] key The data key. void remove0(std::size_t dataId, const std::string& key); } // namespace detail template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Value, class... Keys, EE_REQUIRES(detail::is_data_info_v<DataType>), EE_REQUIRES(detail::can_store_v<Traits, Value>), EE_REQUIRES(detail::is_formattable_v<Formatter, Keys...>)> void set(Value&& value, Keys&&... keys) { detail::set0(DataType::Id, Formatter::createKey(std::forward<Keys>(keys)...), Traits::store(std::forward<Value>(value))); } template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Value = typename DataType::ValueType, class... Keys, EE_REQUIRES(detail::is_data_info_v<DataType>), EE_REQUIRES(detail::can_load_v<Traits, Value>), EE_REQUIRES(detail::is_formattable_v<Formatter, Keys...>)> Value get(Keys&&... keys) { // Return type must not be decltype(auto) because // DataTraits<std::string>::load returns const std::string& would result a // segment fault. std::string result; detail::get0(DataType::Id, Formatter::createKey(std::forward<Keys>(keys)...), result); return Traits::load(result); } template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Value = typename DataType::ValueType, class... Keys, EE_REQUIRES(detail::is_data_info_v<DataType>), EE_REQUIRES(detail::is_formattable_v<Formatter, Keys...>), EE_REQUIRES(detail::is_traits_v<Traits, Value>)> void getAndSet(const typename DataType::SetterType& setter, Keys&&... keys) { auto current = get<DataType, Traits, Formatter>(keys...); setter(current); set<DataType, Traits, Formatter>(current, std::forward<Keys>(keys)...); } template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Function, class... Keys, class = std::enable_if_t< std::is_same<bool, typename DataType::ValueType>::value>> void getAndSetIf(bool conditionalValue, Function&& setter, Keys&&... keys) { auto current = get<DataType, Traits>(keys...); if (current == conditionalValue) { current = not conditionalValue; setter(); set<DataType, Traits>(current, std::forward<Keys>(keys)...); } } template <class DataType, class... Keys> void remove(Keys&&... keys) { detail::remove0(DataType::Id, DataType::createKey(std::forward<Keys>(keys)...)); } class Increment final { public: explicit Increment(std::size_t times = 1) : times_(times) {} template <class T> void operator()(T& value) const { for (std::size_t i = 0; i < times_; ++i) { ++value; } } private: std::size_t times_; }; class Decrement final { public: explicit Decrement(std::size_t times = 1) : times_(times) {} template <class T> void operator()(T& value) const { for (std::size_t i = 0; i < times_; ++i) { --value; } } private: std::size_t times_; }; } // namespace ee #endif // __cplusplus #endif /* EE_LIBRARY_DATA_UTILS_HPP */
31.940741
80
0.6468
enrevol
922ff6beb7920329f72f69393dea8a003173450e
16,776
cpp
C++
test/uitest/test_chart/ui_test_chart_polyline.cpp
openharmony-gitee-mirror/graphic_ui
68abfc8120242a806dd02c400439af2774e6062e
[ "Apache-2.0" ]
null
null
null
test/uitest/test_chart/ui_test_chart_polyline.cpp
openharmony-gitee-mirror/graphic_ui
68abfc8120242a806dd02c400439af2774e6062e
[ "Apache-2.0" ]
null
null
null
test/uitest/test_chart/ui_test_chart_polyline.cpp
openharmony-gitee-mirror/graphic_ui
68abfc8120242a806dd02c400439af2774e6062e
[ "Apache-2.0" ]
1
2021-09-13T12:05:47.000Z
2021-09-13T12:05:47.000Z
/* * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ui_test_chart_polyline.h" #include "common/screen.h" namespace OHOS { namespace { static int16_t g_blank = 20; static int g_curSerialCount = 0; static int g_curArrayCount = 0; static bool g_secondScreenFlag = false; static bool g_addPointsFlag = false; static bool g_hidePointsFlag = false; } // namespace void UITestChartPolyline::SetUp() { if (container_ == nullptr) { container_ = new UIScrollView(); container_->Resize(Screen::GetInstance().GetWidth(), Screen::GetInstance().GetHeight() - BACK_BUTTON_HEIGHT); container_->SetHorizontalScrollState(false); container_->SetThrowDrag(true); } dataSerial_[0] = new UIChartDataSerial(); dataSerial_[0]->SetMaxDataCount(5); // 5: number of data points Point pointArray[5] = {{0, 2478}, {1, 2600}, {2, 3000}, {3, 3200}, {4, 3500}}; dataSerial_[0]->AddPoints(pointArray, 5); // 5: number of data points dataSerial_[0]->SetLineColor(Color::Red()); dataSerial_[0]->SetFillColor(Color::Red()); dataSerial_[0]->EnableGradient(true); dataSerial_[1] = new UIChartDataSerial(); dataSerial_[1]->SetMaxDataCount(5); // 5: number of data points Point pointArray1[5] = {{0, 2000}, {1, 0}, {2, 800}, {3, 700}, {4, 433}}; dataSerial_[1]->AddPoints(pointArray1, 5); // 5: number of data points dataSerial_[1]->SetLineColor(Color::Green()); dataSerial_[1]->SetFillColor(Color::Green()); dataSerial_[1]->EnableGradient(true); dataSerial_[2] = new UIChartDataSerial(); // 2: array index dataSerial_[2]->SetMaxDataCount(5); // 2: array index, 5: number of data points Point pointArray2[5] = {{0, 100}, {1, 200}, {2, 300}, {3, 400}, {4, 500}}; dataSerial_[2]->AddPoints(pointArray2, 5); // 2: array index, 5: number of data points dataSerial_[2]->SetLineColor(Color::Blue()); // 2: array index curDataIndex_ = 0; } void UITestChartPolyline::InnerDeleteChildren(UIView* view) const { if (view == nullptr) { return; } while (view != nullptr) { UIView* tempView = view; view = view->GetNextSibling(); if (tempView->IsViewGroup()) { InnerDeleteChildren(static_cast<UIViewGroup*>(tempView)->GetChildrenHead()); } if (tempView->GetViewType() == UI_AXIS) { return; } if (tempView->GetParent()) { static_cast<UIViewGroup*>(tempView->GetParent())->Remove(tempView); } delete tempView; } } void UITestChartPolyline::TearDown() { ECGAnimator_->Stop(); delete ECGAnimator_; ECGAnimator_ = nullptr; chart_->ClearDataSerial(); for (uint8_t i = 0; i < DATA_NUM; i++) { delete dataSerial_[i]; dataSerial_[i] = nullptr; } InnerDeleteChildren(container_); container_ = nullptr; lastX_ = 0; lastY_ = 0; positionX_ = 0; positionY_ = 0; g_curSerialCount = 0; g_curArrayCount = 0; g_secondScreenFlag = false; g_addPointsFlag = false; g_hidePointsFlag = false; } const UIView* UITestChartPolyline::GetTestView() { UIKit_ChartPolyline_Test_AddDataSerial_001(); UIKit_ChartPolyline_Test_EnableReverse_002(); UIKit_ChartPolyline_Test_SetGradientBottom_003(); UIKit_ChartPolyline_Test_AddPoints_004(); return container_; } void UITestChartPolyline::UIKit_ChartPolyline_Test_AddDataSerial_001() { UILabel* label = new UILabel(); container_->Add(label); lastY_ = TEXT_DISTANCE_TO_TOP_SIDE; // 29: label height label->SetPosition(TEXT_DISTANCE_TO_LEFT_SIDE, lastY_, Screen::GetInstance().GetWidth(), 29); label->SetText("chart添加、删除数据串 "); label->SetFont(DEFAULT_VECTOR_FONT_FILENAME, FONT_DEFAULT_SIZE); chart_ = new UIChartPolyline(); chart_->SetPosition(VIEW_DISTANCE_TO_LEFT_SIDE, VIEW_DISTANCE_TO_TOP_SIDE); chart_->SetWidth(454); // 454: width chart_->SetHeight(250); // 250: height UIXAxis& xAxis = chart_->GetXAxis(); UIYAxis& yAxis = chart_->GetYAxis(); xAxis.SetMarkNum(5); // 5: number of scales xAxis.SetDataRange(0, 5); // 0: minimum value, 5: maximum value yAxis.SetDataRange(0, 5000); // 0: minimum value, 5000: maximum value chart_->SetGradientOpacity(25, 127); // 25: min opacity, 127: max opacity chart_->AddDataSerial(dataSerial_[0]); curDataIndex_++; container_->Add(chart_); SetLastPos(chart_); addDataSerialBtn_ = new UILabelButton(); deleteDataSerialBtn_ = new UILabelButton(); clearDataSerialBtn_ = new UILabelButton(); topPointBtn_ = new UILabelButton(); bottomPointBtn_ = new UILabelButton(); headPointBtn_ = new UILabelButton(); positionX_ = VIEW_DISTANCE_TO_LEFT_SIDE; positionY_ = lastY_ + 10; // 10: increase y-coordinate SetUpButton(addDataSerialBtn_, "添加数据 "); positionX_ = addDataSerialBtn_->GetX() + addDataSerialBtn_->GetWidth() + g_blank; positionY_ = addDataSerialBtn_->GetY(); SetUpButton(deleteDataSerialBtn_, "删除数据 "); positionX_ = deleteDataSerialBtn_->GetX() + deleteDataSerialBtn_->GetWidth() + g_blank; positionY_ = deleteDataSerialBtn_->GetY(); SetUpButton(clearDataSerialBtn_, "清空数据 "); positionX_ = VIEW_DISTANCE_TO_LEFT_SIDE; SetUpButton(topPointBtn_, "最高点 "); positionX_ = topPointBtn_->GetX() + topPointBtn_->GetWidth() + g_blank; positionY_ = topPointBtn_->GetY(); SetUpButton(bottomPointBtn_, "最低点 "); positionX_ = bottomPointBtn_->GetX() + bottomPointBtn_->GetWidth() + g_blank; positionY_ = bottomPointBtn_->GetY(); SetUpButton(headPointBtn_, "最新点 "); } void UITestChartPolyline::UIKit_ChartPolyline_Test_EnableReverse_002() { reverseBtn_ = new UILabelButton(); positionX_ = VIEW_DISTANCE_TO_LEFT_SIDE; SetUpButton(reverseBtn_, "翻转 "); SetLastPos(reverseBtn_); } void UITestChartPolyline::UIKit_ChartPolyline_Test_SetGradientBottom_003() { gradientBottomBtn_ = new UILabelButton(); positionX_ = reverseBtn_->GetX() + reverseBtn_->GetWidth() + g_blank; positionY_ = reverseBtn_->GetY(); SetUpButton(gradientBottomBtn_, "填充底部位置 "); SetLastPos(gradientBottomBtn_); } namespace { const int16_t DATA_COUNT = 480; } /* ECG test data */ static int16_t g_ECGData[DATA_COUNT] = { 68, 70, 73, 83, 95, 107, 118, 127, 118, 103, 90, 77, 66, 61, 57, 58, 60, 61, 62, 62, 63, 64, 64, 65, 67, 69, 70, 71, 73, 75, 76, 78, 78, 79, 80, 80, 80, 80, 80, 80, 79, 78, 77, 76, 75, 73, 72, 71, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 71, 71, 71, 70, 70, 70, 70, 71, 73, 75, 78, 80, 81, 82, 82, 82, 80, 78, 76, 73, 71, 69, 69, 68, 68, 68, 68, 68, 70, 76, 88, 100, 111, 122, 126, 112, 98, 85, 73, 61, 58, 57, 59, 60, 61, 62, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 76, 77, 78, 79, 79, 80, 80, 80, 80, 79, 79, 79, 78, 77, 76, 74, 73, 72, 71, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 74, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 72, 71, 71, 70, 70, 69, 70, 70, 72, 74, 76, 78, 80, 82, 82, 82, 81, 79, 77, 75, 72, 70, 69, 68, 68, 68, 68, 68, 69, 72, 80, 93, 104, 115, 126, 121, 106, 93, 80, 68, 59, 57, 58, 60, 61, 62, 62, 63, 63, 64, 65, 67, 68, 70, 71, 73, 75, 76, 77, 78, 79, 80, 80, 80, 80, 80, 79, 79, 78, 78, 76, 75, 74, 72, 71, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 74, 75, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 72, 71, 71, 70, 70, 69, 70, 71, 72, 75, 77, 79, 81, 82, 82, 82, 80, 79, 76, 74, 71, 70, 69, 68, 68, 68, 68, 69, 70, 75, 85, 97, 109, 120, 127, 115, 101, 88, 75, 64, 57, 56, 58, 60, 61, 62, 62, 63, 64, 65, 66, 67, 69, 71, 72, 74, 75, 77, 78, 79, 79, 80, 80, 80, 80, 80, 79, 79, 78, 77, 76, 74, 73, 72, 71, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 72, 80, 93, 104, 115, 126, 121, 106, 93, 80, 68, 59, 57, 58, 60, 61, 62, 62, 63, 63, 64, 65, 67, 68, 70, 71, 73}; class ImageAnimatorCallbackDemo : public OHOS::AnimatorCallback { public: explicit ImageAnimatorCallbackDemo(UIChartDataSerial* serial) : times_(0), serial_(serial) {} ~ImageAnimatorCallbackDemo() {} virtual void Callback(UIView* view) { if (view == nullptr) { return; } if (!g_addPointsFlag) { return; /* Control the addition of points by button, and automate if commented out */ } if (times_++ != 6) { /* Add 10 points for every 6 ticks */ return; } times_ = 0; if (g_curSerialCount == 0) { view->Invalidate(); } Point pointArray1[10]; for (uint16_t i = 0; i < 10; i++) { // 10: array max index pointArray1[i].x = g_curSerialCount; pointArray1[i].y = g_ECGData[g_curArrayCount]; g_curSerialCount++; g_curArrayCount++; if (g_curArrayCount == DATA_COUNT) { g_curArrayCount = 0; } if (!g_secondScreenFlag) { serial_->AddPoints(&pointArray1[i], 1); } else { serial_->ModifyPoint(g_curSerialCount, pointArray1[i]); if (g_hidePointsFlag) { serial_->HidePoint(g_curSerialCount, 30); // 30: the number of points } } } if (g_curSerialCount > 454) { // 454: max serial count g_curSerialCount = 0; g_secondScreenFlag = true; } UIChart* chart = static_cast<UIChart*>(view); chart->RefreshChart(); g_addPointsFlag = false; } protected: int16_t times_; UIChartDataSerial* serial_; }; void UITestChartPolyline::UIKit_ChartPolyline_Test_AddPoints_004() { UIViewGroup* uiViewGroup = new UIViewGroup(); // 2: x-coordinate, half of screen width; 2: half of screen width; 470: screen height uiViewGroup->SetPosition(Screen::GetInstance().GetWidth() / 2, 0, Screen::GetInstance().GetWidth() / 2, 470); container_->Add(uiViewGroup); UILabel* label = new UILabel(); uiViewGroup->Add(label); label->SetPosition(TEXT_DISTANCE_TO_LEFT_SIDE, TEXT_DISTANCE_TO_TOP_SIDE, Screen::GetInstance().GetWidth() / 2 - TEXT_DISTANCE_TO_LEFT_SIDE, // 2: half of screen width; TITLE_LABEL_DEFAULT_HEIGHT); label->SetText("chart追加点、修改点、平滑化"); label->SetFont(DEFAULT_VECTOR_FONT_FILENAME, FONT_DEFAULT_SIZE); ECGChart_ = new UIChartPolyline(); // 454: new width, 250: new height ECGChart_->SetPosition(VIEW_DISTANCE_TO_LEFT_SIDE, VIEW_DISTANCE_TO_TOP_SIDE, 454, 250); uiViewGroup->Add(ECGChart_); SetLastPos(ECGChart_); ECGChart_->SetStyle(STYLE_LINE_WIDTH, 5); // 5: line width UIXAxis& xAxis = ECGChart_->GetXAxis(); UIYAxis& yAxis = ECGChart_->GetYAxis(); xAxis.SetDataRange(0, 454); // 454: maximum value xAxis.SetMarkNum(10); // 10: number of scales yAxis.SetDataRange(0, 200); // 200: maximum value ECGDataSerial_ = new UIChartDataSerial(); ECGDataSerial_->SetMaxDataCount(454); // 454: number of data points ECGDataSerial_->SetLineColor(Color::Red()); ECGDataSerial_->EnableHeadPoint(true); ECGChart_->AddDataSerial(ECGDataSerial_); ImageAnimatorCallbackDemo* imageAnimCallback = new ImageAnimatorCallbackDemo(ECGDataSerial_); ECGAnimator_ = new OHOS::Animator(imageAnimCallback, ECGChart_, 0, true); ECGAnimator_->Start(); addPointsBtn_ = new UILabelButton(); smoothBtn_ = new UILabelButton(); hidePointsBtn_ = new UILabelButton(); // 2: half of screen width positionX_ = Screen::GetInstance().GetWidth() / 2 + VIEW_DISTANCE_TO_LEFT_SIDE; positionY_ = lastY_ + 10; // 10: increase y-coordinate SetUpButton(addPointsBtn_, "添加点 "); positionX_ = addPointsBtn_->GetX() + addPointsBtn_->GetWidth() + g_blank; positionY_ = addPointsBtn_->GetY(); SetUpButton(smoothBtn_, "平滑化 "); positionX_ = smoothBtn_->GetX() + smoothBtn_->GetWidth() + g_blank; positionY_ = smoothBtn_->GetY(); SetUpButton(hidePointsBtn_, "隐藏点 "); } bool UITestChartPolyline::OnClick(UIView& view, const ClickEvent& event) { UIChartDataSerial::PointStyle pointStyle; pointStyle.fillColor = Color::White(); pointStyle.radius = 5; // 5: Inner radius pointStyle.strokeColor = Color::Red(); pointStyle.strokeWidth = 2; // 2: border width if (&view == addDataSerialBtn_) { if (curDataIndex_ >= DATA_NUM) { return true; } chart_->AddDataSerial(dataSerial_[curDataIndex_]); curDataIndex_++; chart_->Invalidate(); } else if (&view == deleteDataSerialBtn_) { if (curDataIndex_ <= 0) { return true; } chart_->DeleteDataSerial(dataSerial_[curDataIndex_ - 1]); curDataIndex_--; chart_->Invalidate(); } else if (&view == clearDataSerialBtn_) { chart_->ClearDataSerial(); curDataIndex_ = 0; chart_->Invalidate(); } else if (&view == topPointBtn_) { dataSerial_[0]->EnableTopPoint(true); pointStyle.strokeColor = Color::Red(); dataSerial_[0]->SetTopPointStyle(pointStyle); chart_->Invalidate(); } else if (&view == bottomPointBtn_) { dataSerial_[0]->EnableBottomPoint(true); pointStyle.strokeColor = Color::Blue(); dataSerial_[0]->SetBottomPointStyle(pointStyle); chart_->Invalidate(); } else if (&view == headPointBtn_) { dataSerial_[0]->EnableHeadPoint(true); pointStyle.strokeColor = Color::Yellow(); dataSerial_[0]->SetHeadPointStyle(pointStyle); chart_->Invalidate(); } else if (&view == reverseBtn_) { chart_->EnableReverse(true); chart_->Invalidate(); } else { ClickExpand(view, pointStyle); } return true; } bool UITestChartPolyline::ClickExpand(UIView& view, UIChartDataSerial::PointStyle pointStyle) { if (&view == gradientBottomBtn_) { chart_->SetGradientBottom(50); // 50: bottom of the filling range chart_->Invalidate(); } else if (&view == addPointsBtn_) { g_addPointsFlag = true; } else if (&view == smoothBtn_) { ECGDataSerial_->EnableSmooth(true); ECGChart_->Invalidate(); } else if (&view == hidePointsBtn_) { g_hidePointsFlag = true; } return true; } void UITestChartPolyline::SetUpButton(UILabelButton* btn, const char* title) { if (btn == nullptr) { return; } container_->Add(btn); btn->SetPosition(positionX_, positionY_, BUTTON_WIDHT2, BUTTON_HEIGHT2); positionY_ += btn->GetHeight() + 10; // 10: increase height btn->SetText(title); btn->SetFont(DEFAULT_VECTOR_FONT_FILENAME, BUTTON_LABEL_SIZE); btn->SetOnClickListener(this); btn->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_STYLE_BORDER_RADIUS_VALUE, UIButton::RELEASED); btn->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_STYLE_BORDER_RADIUS_VALUE, UIButton::PRESSED); btn->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_STYLE_BORDER_RADIUS_VALUE, UIButton::INACTIVE); btn->SetStyleForState(STYLE_BACKGROUND_COLOR, BUTTON_STYLE_BACKGROUND_COLOR_VALUE, UIButton::RELEASED); btn->SetStyleForState(STYLE_BACKGROUND_COLOR, BUTTON_STYLE_BACKGROUND_COLOR_VALUE, UIButton::PRESSED); btn->SetStyleForState(STYLE_BACKGROUND_COLOR, BUTTON_STYLE_BACKGROUND_COLOR_VALUE, UIButton::INACTIVE); container_->Invalidate(); } void UITestChartPolyline::SetLastPos(UIView* view) { if (view == nullptr) { return; } lastX_ = view->GetX(); lastY_ = view->GetY() + view->GetHeight(); } } // namespace OHOS
40.424096
118
0.638829
openharmony-gitee-mirror
9230829f87b69123fc99c5a7d494560a42caf3a3
1,365
cc
C++
src/PluginLoader.cc
indigo-dc/dynafed
3864f12a82653b34ba9ca4001d968cb27f75c8f5
[ "Apache-2.0" ]
null
null
null
src/PluginLoader.cc
indigo-dc/dynafed
3864f12a82653b34ba9ca4001d968cb27f75c8f5
[ "Apache-2.0" ]
null
null
null
src/PluginLoader.cc
indigo-dc/dynafed
3864f12a82653b34ba9ca4001d968cb27f75c8f5
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) CERN 2013 * * Copyright (c) Members of the EMI Collaboration. 2011-2013 * See http://www.eu-emi.eu/partners for details on the copyright * holders. * * Licensed under the Apache License, Version 2.0 * See the LICENSE file for further information * */ /** @file PluginLoader.hh * @brief A helper class that loads a plugin * @author Fabrizio Furano * @date Oct 2010 */ #include "PluginLoader.hh" #include "SimpleDebug.hh" #include <dlfcn.h> #include <stdlib.h> PluginLoader::~PluginLoader() { if (libHandle) dlclose(libHandle); if (libPath) free((char *)libPath); } // Gets a pointer to the function that instantiates the // main class defined in the plugin. void *PluginLoader::getPlugin(const char *pname, int errok) { void *ep; // Open the plugin library if not already opened // if (!libHandle && !(libHandle = dlopen(libPath, RTLD_NOW | RTLD_GLOBAL))) { Error("PluginLoader::getPlugin", "Unable to open" << libPath << " - dlerror: " << dlerror()); return 0; } // Get the plugin object creator // if (!(ep = dlsym(libHandle, pname)) && !errok) { Error("PluginLoader::getPlugin", "Unable to find " << pname << " in " << pname << " - dlerror: " << dlerror()); return 0; } // All done // return ep; }
23.135593
117
0.615385
indigo-dc
923092eda6175b36a232014efadd28ee45a85db4
1,651
cpp
C++
miscellaneous/MaximalRectangleInGrid_leetcode.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
6
2019-10-06T17:39:42.000Z
2022-03-03T10:57:52.000Z
miscellaneous/MaximalRectangleInGrid_leetcode.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
null
null
null
miscellaneous/MaximalRectangleInGrid_leetcode.cpp
Cobnagi/Competitive-programming
4037e0542350e789a31bf3ebd97896c0d75bea17
[ "MIT" ]
2
2019-10-06T11:09:01.000Z
2019-10-06T17:40:46.000Z
class Solution { public: int hist(vector<int> &h){ int ans=0; stack<int> s; int i=0; for(i=0;i<h.size();i++){ if(s.empty() || h[i]>=h[s.top()]){ s.push(i); } else{ while(!s.empty() && h[i]<h[s.top()]){ int top=s.top(); s.pop(); if(s.empty()){ ans = max(ans, h[top]*i); } else{ ans = max(ans, h[top]*(i-1-s.top())); } } s.push(i); } } while(!s.empty()){ int top=s.top(); s.pop(); if(s.empty()){ ans = max(ans, h[top]*i); } else{ ans = max(ans, h[top]*(i-1-s.top())); } } return ans; } int maximalRectangle(vector<vector<char>>& m) { if(m.size()==0 || m[0].size()==0) return 0; vector<vector<int>> v(m.size(), vector<int> (m[0].size())); for(int i=0;i<m.size();i++){ for(int j=0;j<m[0].size();j++){ v[i][j] = m[i][j]-'0'; } } for(int j=0;j<m[0].size();j++){ for(int i=1;i<m.size();i++){ if(v[i][j]!=0){ v[i][j]+=v[i-1][j]; } } } int ans=0; for(int i=0;i<m.size();i++){ ans = max(ans, hist(v[i])); } return ans; } };
26.629032
67
0.289522
Cobnagi
9233fff7d85eb23b2f0b88dbe412a8a3c93d22e5
163
cpp
C++
src/Scripting/Natives/ScriptGameInstance.cpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
src/Scripting/Natives/ScriptGameInstance.cpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
src/Scripting/Natives/ScriptGameInstance.cpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#ifndef RED4EXT_STATIC_LIB #error Please define 'RED4EXT_STATIC_LIB' to compile this file. #endif #include <RED4ext/Scripting/Natives/ScriptGameInstance-inl.hpp>
27.166667
63
0.828221
jackhumbert
92342fbcef18cd4e327d9019e0b45ad854661895
4,773
cpp
C++
windows/feime/kor/ime2k/tip/editssn.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/feime/kor/ime2k/tip/editssn.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/feime/kor/ime2k/tip/editssn.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// // editssn.cpp // // CEditSession2 // #include "private.h" #include "korimx.h" #include "editssn.h" #include "helpers.h" #define SafeAddRef(x) { if ((x)) { (x)->AddRef(); } } /* C E D I T S E S S I O N 2 */ /*------------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------------*/ CEditSession2::CEditSession2(ITfContext *pic, CKorIMX *ptip, ESSTRUCT *pess, PFNESCALLBACK pfnCallback) { Assert(pic != NULL); Assert(ptip != NULL); Assert(pess != NULL); m_cRef = 1; m_pic = pic; m_ptip = ptip; m_ess = *pess; m_pfnCallback = pfnCallback; // add reference count in the struct SafeAddRef(m_pic); SafeAddRef(m_ptip); SafeAddRef(m_ess.ptim); SafeAddRef(m_ess.pRange); SafeAddRef(m_ess.pEnumRange); SafeAddRef(m_ess.pCandList); SafeAddRef(m_ess.pCandStr); } /* ~ C E D I T S E S S I O N 2 */ /*------------------------------------------------------------------------------ Destructor ------------------------------------------------------------------------------*/ CEditSession2::~CEditSession2( void ) { SafeRelease(m_pic); SafeRelease(m_ptip); SafeRelease(m_ess.ptim); SafeRelease(m_ess.pRange); SafeRelease(m_ess.pEnumRange); SafeRelease(m_ess.pCandList); SafeRelease(m_ess.pCandStr); } /* Q U E R Y I N T E R F A C E */ /*------------------------------------------------------------------------------ Query interface of object (IUnknown method) ------------------------------------------------------------------------------*/ STDAPI CEditSession2::QueryInterface(REFIID riid, void **ppvObj) { *ppvObj = NULL; if (IsEqualIID( riid, IID_IUnknown ) || IsEqualIID(riid, IID_ITfEditSession)) *ppvObj = SAFECAST(this, ITfEditSession*); if (*ppvObj) { AddRef(); return S_OK; } return E_NOINTERFACE; } /* A D D R E F */ /*------------------------------------------------------------------------------ Add reference count (IUnknown method) ------------------------------------------------------------------------------*/ STDAPI_(ULONG) CEditSession2::AddRef() { return ++m_cRef; } /* R E L E A S E */ /*------------------------------------------------------------------------------ Release object (IUnknown method) ------------------------------------------------------------------------------*/ STDAPI_(ULONG) CEditSession2::Release() { long cr; cr = --m_cRef; Assert(cr >= 0); if (cr == 0) delete this; return cr; } /* E D I T S E S S I O N */ /*------------------------------------------------------------------------------ Callback function of edit session (ITfEditSession method) ------------------------------------------------------------------------------*/ STDAPI CEditSession2::DoEditSession(TfEditCookie ec) { return m_pfnCallback(ec, this); } /* I N V O K E */ /*------------------------------------------------------------------------------ ------------------------------------------------------------------------------*/ HRESULT CEditSession2::Invoke(DWORD dwFlag, HRESULT *phrSession) { HRESULT hr; DWORD dwFlagES = 0; if ((m_pic == NULL) || (m_ptip == NULL)) return E_FAIL; // read/readwrite flag switch (dwFlag & ES2_READWRITEMASK) { default: case ES2_READONLY: dwFlagES |= TF_ES_READ; break; case ES2_READWRITE: dwFlagES |= TF_ES_READWRITE; break; } // sync/async flag switch (dwFlag & ES2_SYNCMASK) { default: Assert(fFalse); // fall through case ES2_ASYNC: dwFlagES |= TF_ES_ASYNC; break; case ES2_SYNC: dwFlagES |= TF_ES_SYNC; break; case ES2_SYNCASYNC: dwFlagES |= TF_ES_ASYNCDONTCARE; break; } // invoke m_fProcessed = FALSE; hr = m_pic->RequestEditSession(m_ptip->GetTID(), this, dwFlagES, phrSession); // try ASYNC session when SYNC session failed // NOTE: KOJIW: // How can we know if the edit session has been processed synchronously? // Satori#2409 - do not invoke callback twice // if (!m_fProcessed && ((dwFlag & ES2_SYNCMASK) == ES2_SYNCASYNC)) { // hr = m_pic->EditSession( m_ptip->GetTID(), this, (dwFlagES & ~TF_ES_SYNC), phrSession ); // } return hr; }
23.984925
104
0.426776
npocmaka
9236c7b57f0a5339bc436fa306c201b662c77c32
861
cpp
C++
src/return-several-values-and-structured-bindings/main.cpp
tarodnet/cplusplus-snippets
2866102b53534163c2ebc1aaf6096467dfbdadaf
[ "Apache-2.0" ]
null
null
null
src/return-several-values-and-structured-bindings/main.cpp
tarodnet/cplusplus-snippets
2866102b53534163c2ebc1aaf6096467dfbdadaf
[ "Apache-2.0" ]
null
null
null
src/return-several-values-and-structured-bindings/main.cpp
tarodnet/cplusplus-snippets
2866102b53534163c2ebc1aaf6096467dfbdadaf
[ "Apache-2.0" ]
1
2015-06-06T02:23:20.000Z
2015-06-06T02:23:20.000Z
#include <iostream> class Foo { public: int foo; }; class Bar { public: char bar; }; std::pair<Foo, Bar> f() { std::pair<Foo, Bar> result; auto& foo = result.first; auto& bar = result.second; // fill foo and bar... foo.foo = 0xFF; bar.bar = 'x'; return result; } int main(int argc, char** argv) { /* Structured bindings * A proposal for de-structuring initialization, that would allow writing auto [ x, y, z ] = expr; * where the type of expr was a tuple-like object, whose elements * would be bound to the variables x, y, and z (which this construct declares). * Tuple-like objects include std::tuple, std::pair, std::array, and aggregate structures. */ auto [foo, bar] = f(); std::cout << foo.foo << std::endl; std::cout << bar.bar << std::endl; return 0; }
19.568182
101
0.595819
tarodnet
9236fd69c794a24f6e33d42f38a3082bf486b84c
44,199
cpp
C++
admin/activec/samples/displ2/dsplcomp.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/activec/samples/displ2/dsplcomp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/activec/samples/displ2/dsplcomp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1999 - 1999 // // File: DsplComp.cpp // //-------------------------------------------------------------------------- #include "stdafx.h" #include "displ2.h" #include "DsplMgr2.h" // local proto HRESULT ApplyOption (int nCommandID); extern HINSTANCE g_hinst; // in displ2.cpp HSCOPEITEM g_root_scope_item = 0; CComponent::CComponent() { m_pResultData = NULL; m_pHeaderCtrl = NULL; m_pComponentData = NULL; // the guy who created me m_IsTaskPad = 0; // TODO: should get this from the persisted data m_pConsole = NULL; m_TaskPadCount = 0; m_toggle = FALSE; m_toggleEntry = FALSE; } CComponent::~CComponent() { _ASSERT (m_pResultData == NULL); _ASSERT (m_pHeaderCtrl == NULL); } HRESULT CComponent::Initialize (LPCONSOLE lpConsole) { _ASSERT(lpConsole != NULL); _ASSERT (m_pResultData == NULL); // should be called only once... _ASSERT (m_pHeaderCtrl == NULL); // should be called only once... m_pConsole = lpConsole; // hang onto this HRESULT hresult = lpConsole->QueryInterface(IID_IResultData, (VOID**)&m_pResultData); _ASSERT (m_pResultData != NULL); hresult = lpConsole->QueryInterface(IID_IHeaderCtrl, (VOID**)&m_pHeaderCtrl); _ASSERT (m_pHeaderCtrl != NULL); if (m_pHeaderCtrl) // Give the console the header control interface pointer lpConsole->SetHeader(m_pHeaderCtrl); #ifdef TODO_ADD_THIS_LATER hr = lpConsole->QueryResultImageList(&m_pImageResult); _ASSERT(hr == S_OK); hr = lpConsole->QueryConsoleVerb(&m_pConsoleVerb); _ASSERT(hr == S_OK); // Load the bitmaps from the dll for the results pane m_hbmp16x16 = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_RESULT_16x16)); _ASSERT(m_hbmp16x16); m_hbmp32x32 = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_RESULT_32x32)); _ASSERT(m_hbmp32x32); #endif return hresult; } HRESULT CComponent::Destroy (long cookie) { if (m_pResultData) { m_pResultData->Release (); m_pResultData = NULL; } if (m_pHeaderCtrl) { m_pHeaderCtrl->Release (); m_pHeaderCtrl = NULL; } // hmmm... I wonder if I have to release my IConsole pointer? it doesn't look like it.... return S_OK; } HRESULT CComponent::Notify (LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, long arg, long param) { switch (event) { case MMCN_SHOW: return OnShow (lpDataObject, arg, param); case MMCN_ADD_IMAGES: return OnAddImages (lpDataObject, arg, param); case MMCN_DBLCLICK: return OnDblClick (lpDataObject, arg, param); case MMCN_SELECT: // return OnSelect (lpDataObject, arg, param); break; case MMCN_REFRESH: // return OnRefresh (lpDataObject, arg, param); case MMCN_VIEW_CHANGE: case MMCN_CLICK: case MMCN_BTN_CLICK: case MMCN_ACTIVATE: case MMCN_MINIMIZED: break; case MMCN_LISTPAD: return OnListPad (lpDataObject, arg, param); case MMCN_RESTORE_VIEW: return OnRestoreView (lpDataObject, arg, param); default: return E_UNEXPECTED; } return S_OK; } HRESULT CComponent::GetResultViewType (long cookie, LPOLESTR* ppViewType, long* pViewOptions) { *ppViewType = NULL; *pViewOptions = MMC_VIEW_OPTIONS_NONE; // only allow taskpad when root is selected if (cookie != 0) m_IsTaskPad = 0; // special case for taskpads only if (m_IsTaskPad != 0) { USES_CONVERSION; TCHAR szBuffer[MAX_PATH*2]; // a little extra lstrcpy (szBuffer, _T("res://")); TCHAR * temp = szBuffer + lstrlen(szBuffer); switch (m_IsTaskPad) { case IDM_CUSTOMPAD: // get "res://"-type string for custom taskpad ::GetModuleFileName (g_hinst, temp, MAX_PATH); lstrcat (szBuffer, _T("/default.htm")); break; case IDM_TASKPAD: // get "res://"-type string for custom taskpad ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/default.htm")); break; case IDM_TASKPAD_WALLPAPER_OPTIONS: // get "res://"-type string for custom taskpad ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/default.htm#wallpaper_options")); break; case IDM_TASKPAD_LISTVIEW: // get "res://"-type string for custom taskpad // ::GetModuleFileName (g_hinst, temp, MAX_PATH); // lstrcat (szBuffer, _T("/listview.htm")); ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/horizontal.htm")); break; case IDM_DEFAULT_LISTVIEW: // get "res://"-type string for custom taskpad ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/listpad.htm")); break; default: _ASSERT (0); return S_FALSE; } // return URL *ppViewType = CoTaskDupString (T2OLE(szBuffer)); if (!*ppViewType) return E_OUTOFMEMORY; // or S_FALSE ??? return S_OK; } return S_FALSE; // false for default } HRESULT CComponent::QueryDataObject (long cookie, DATA_OBJECT_TYPES type, LPDATAOBJECT* ppDataObject) { _ASSERT (ppDataObject != NULL); CDataObject *pdo = new CDataObject (cookie, type); *ppDataObject = pdo; if (!pdo) return E_OUTOFMEMORY; return S_OK; } HRESULT CComponent::GetDisplayInfo (RESULTDATAITEM* prdi) { _ASSERT(prdi != NULL); if (prdi) { // Provide strings for scope tree items if (prdi->bScopeItem == TRUE) { if (prdi->mask & RDI_STR) { if (prdi->nCol == 0) { switch (prdi->lParam) { case DISPLAY_MANAGER_WALLPAPER: if (m_toggle == FALSE) prdi->str = (LPOLESTR)L"Wallpaper"; else prdi->str = (LPOLESTR)L"RenamedWallpaper"; break; case DISPLAY_MANAGER_PATTERN: prdi->str = (LPOLESTR)L"Pattern"; break; case DISPLAY_MANAGER_PATTERN_CHILD: prdi->str = (LPOLESTR)L"Pattern child"; break; default: prdi->str = (LPOLESTR)L"Hey! You shouldn't see this!"; break; } } else if (prdi->nCol == 1) prdi->str = (LPOLESTR)L"Display Option"; else prdi->str = (LPOLESTR)L"Error:Should not see this!"; } if (prdi->mask & RDI_IMAGE) prdi->nImage = 0; } else { // listpad uses lparam on -1, anything else is wallpaper if (prdi->lParam == -1) { if (prdi->mask & RDI_STR) if (m_toggleEntry == FALSE) prdi->str = (LPOLESTR)L"here's a listpad entry"; else prdi->str = (LPOLESTR)L"Changed listpad entry"; if (prdi->mask & RDI_IMAGE) prdi->nImage = 0; } else { lParamWallpaper * lpwp = NULL; if (prdi->lParam) lpwp = (lParamWallpaper *)prdi->lParam; if (prdi->mask & RDI_STR) { if (prdi->nCol == 0) { if (lpwp && (!IsBadReadPtr (lpwp, sizeof (lParamWallpaper)))) prdi->str = lpwp->filename; else prdi->str = (LPOLESTR)L"hmm.... error"; } else if (prdi->nCol == 1) prdi->str = (LPOLESTR)L"result pane display name col 1"; else prdi->str = (LPOLESTR)L"Error:Should not see this!"; } if (prdi->mask & RDI_IMAGE) { switch (prdi->lParam) { case DISPLAY_MANAGER_WALLPAPER: case DISPLAY_MANAGER_PATTERN: case DISPLAY_MANAGER_PATTERN_CHILD: prdi->nImage = 0; break; default: prdi->nImage = 3; break; } } } } } return S_OK; } HRESULT CComponent::CompareObjects (LPDATAOBJECT lpDataObjectA, LPDATAOBJECT lpDataObjectB) { return E_NOTIMPL;} // private functions HRESULT CComponent::OnShow(LPDATAOBJECT pDataObject, long arg, long param) { USES_CONVERSION; CDataObject * pcdo = (CDataObject *)pDataObject; if (arg == 0) { // de-selecting: free up resources, if any if (pcdo->GetCookie() == DISPLAY_MANAGER_WALLPAPER) { // enumerate result data items RESULTDATAITEM rdi; ZeroMemory(&rdi, sizeof(rdi)); rdi.mask = RDI_PARAM | RDI_STATE; rdi.nIndex = -1; while (1) { if (m_pResultData->GetNextItem (&rdi) != S_OK) break; if (rdi.lParam) { lParamWallpaper * lpwp = (lParamWallpaper *)rdi.lParam; delete lpwp; } } m_pResultData->DeleteAllRsltItems (); } return S_OK; } // init column headers _ASSERT (m_pHeaderCtrl != NULL); m_pHeaderCtrl->InsertColumn (0, L"Name", 0, 120); if (m_pComponentData) { if (m_pResultData) // use large icons by default m_pResultData->SetViewMode (m_pComponentData->GetViewMode ()); } // add our stuff RESULTDATAITEM rdi; ZeroMemory(&rdi, sizeof(rdi)); rdi.mask = RDI_PARAM | RDI_STR | RDI_IMAGE; rdi.nImage = (int)MMC_CALLBACK; rdi.str = MMC_CALLBACK; if (pcdo->GetCookie () == DISPLAY_MANAGER_WALLPAPER) { // enumerate all .bmp files in "c:\winnt.40\" (windows directory) TCHAR path[MAX_PATH]; GetWindowsDirectory (path, MAX_PATH); lstrcat (path, _T("\\*.bmp")); int i = 0; // first do "(none)" lParamWallpaper * lpwp = new lParamWallpaper; wcscpy (lpwp->filename, L"(none)"); rdi.lParam = reinterpret_cast<LONG>(lpwp); rdi.nImage = i++; m_pResultData->InsertItem (&rdi); WIN32_FIND_DATA fd; ZeroMemory(&fd, sizeof(fd)); HANDLE hFind = FindFirstFile (path, &fd); if (hFind != INVALID_HANDLE_VALUE) { do { if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) || (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ) continue; // files only // new a struct to hold info, and cast to lParam. lParamWallpaper * lpwp = new lParamWallpaper; wcscpy (lpwp->filename, T2OLE(fd.cFileName)); // rdi.str = lpwp->filename; rdi.lParam = reinterpret_cast<LONG>(lpwp); rdi.nImage = i++; m_pResultData->InsertItem (&rdi); } while (FindNextFile (hFind, &fd) == TRUE); FindClose(hFind); } } else { // DISPLAY_MANAGER_PATTERN ; // hard code a few things. } return S_OK; } #include <windowsx.h> inline long LongScanBytes (long bits) { bits += 31; bits /= 8; bits &= ~3; return bits; } void GetBitmaps (TCHAR * fn, HBITMAP * smallbm, HBITMAP * largebm) { *smallbm = *largebm = (HBITMAP)NULL; // in case of error // read bmp file into DIB DWORD dwRead; HANDLE hf = CreateFile (fn, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, (HANDLE) NULL); if (hf != (HANDLE)HFILE_ERROR) { BITMAPFILEHEADER bmfh; ReadFile(hf, &bmfh, sizeof(BITMAPFILEHEADER), &dwRead, (LPOVERLAPPED)NULL); BITMAPINFOHEADER bmih; ReadFile(hf, &bmih, sizeof(BITMAPINFOHEADER), &dwRead, (LPOVERLAPPED)NULL); // Allocate memory for the DIB DWORD dwSize = sizeof(BITMAPINFOHEADER); if (bmih.biBitCount*bmih.biPlanes <= 8) dwSize += (sizeof(RGBQUAD))*(1<<(bmih.biBitCount*bmih.biPlanes)); dwSize += bmih.biHeight*LongScanBytes (bmih.biWidth*(bmih.biBitCount*bmih.biPlanes)); BITMAPINFOHEADER * lpbmih = (BITMAPINFOHEADER *)GlobalAllocPtr(GHND, dwSize); if (lpbmih) { *lpbmih = bmih; RGBQUAD * rgbq = (RGBQUAD *)&lpbmih[1]; char * bits = (char *)rgbq; if (bmih.biBitCount*bmih.biPlanes <= 8) { ReadFile (hf, rgbq, ((1<<(bmih.biBitCount*bmih.biPlanes))*sizeof(RGBQUAD)), &dwRead, (LPOVERLAPPED) NULL); bits += dwRead; } SetFilePointer (hf, bmfh.bfOffBits, NULL, FILE_BEGIN); ReadFile (hf, bits, dwSize - (bits - (char *)lpbmih), &dwRead, (LPOVERLAPPED) NULL); // we should now have a decent DIB HWND hwnd = GetDesktopWindow (); HDC hdc = GetDC (hwnd); HDC hcompdc = CreateCompatibleDC (hdc); // SetStretchBltMode (hcompdc, COLORONCOLOR); // SetStretchBltMode (hcompdc, WHITEONBLACK); SetStretchBltMode (hcompdc, HALFTONE); HGDIOBJ hold; // *smallbm = CreateCompatibleBitmap (hcompdc, 16, 16); *smallbm = CreateCompatibleBitmap (hdc, 16, 16); if (*smallbm) { hold = SelectObject (hcompdc, (HGDIOBJ)(*smallbm)); StretchDIBits (hcompdc, // handle of device context 0, 0, 16, 16, 0, 0, lpbmih->biWidth, lpbmih->biHeight, (CONST VOID *)bits, (CONST BITMAPINFO *)lpbmih, DIB_RGB_COLORS, // usage SRCCOPY // raster operation code ); SelectObject (hcompdc, hold); } // *largebm = CreateCompatibleBitmap (hcompdc, 32, 32); *largebm = CreateCompatibleBitmap (hdc, 32, 32); if (*largebm) { // testing /* HDC nullDC = GetDC (NULL); hold = SelectObject (nullDC, (HGDIOBJ)*largebm); StretchDIBits (nullDC, // handle of device context 0, 0, lpbmih->biWidth, lpbmih->biHeight, 0, 0, lpbmih->biWidth, lpbmih->biHeight, (CONST VOID *)bits, (CONST BITMAPINFO *)lpbmih, DIB_RGB_COLORS, // usage SRCCOPY // raster operation code ); SelectObject (hdc, hold); ReleaseDC (NULL, nullDC); */ // testing hold = SelectObject (hcompdc, (HGDIOBJ)*largebm); StretchDIBits (hcompdc, // handle of device context 0, 0, 32, 32, 0, 0, lpbmih->biWidth, lpbmih->biHeight, (CONST VOID *)bits, (CONST BITMAPINFO *)lpbmih, DIB_RGB_COLORS, // usage SRCCOPY // raster operation code ); SelectObject (hcompdc, hold); } DeleteDC (hcompdc); ReleaseDC (hwnd, hdc); GlobalFreePtr (lpbmih); } CloseHandle(hf); } } HRESULT CComponent::OnAddImages (LPDATAOBJECT pDataObject, long arg, long param) { IImageList * pImageList = (IImageList *)arg; HSCOPEITEM hsi = (HSCOPEITEM)param; _ASSERT (pImageList != NULL); CDataObject * cdo = (CDataObject *)pDataObject; if (cdo->GetCookie () != DISPLAY_MANAGER_WALLPAPER) { if (cdo->GetCookie () == 0) { g_root_scope_item = hsi; if (cdo->GetType () == CCT_RESULT) { // add a custom image HBITMAP hbmSmall, hbmLarge; GetBitmaps (_T("c:\\winnt\\dax.bmp"), &hbmSmall, &hbmLarge); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, 3, RGB(1, 0, 254)); DeleteObject (hbmSmall); DeleteObject (hbmLarge); } } return S_OK; // TODO: for now } // create HBITMAPs from bmp files int i = 0; // create some invisible bitmaps { BYTE bits[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; HBITMAP hbmSmall = CreateBitmap (16, 16, 1, 1, (CONST VOID *)bits); HBITMAP hbmLarge = CreateBitmap (32, 32, 1, 1, (CONST VOID *)bits); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, i++, RGB(1, 0, 254)); DeleteObject (hbmSmall); DeleteObject (hbmLarge); } TCHAR path[MAX_PATH]; GetWindowsDirectory (path, MAX_PATH); TCHAR * pfqfn = path + lstrlen(path) + 1; lstrcat (path, _T("\\*.bmp")); WIN32_FIND_DATA fd; ZeroMemory(&fd, sizeof(fd)); HANDLE hFind = FindFirstFile (path, &fd); if (hFind != INVALID_HANDLE_VALUE) { do { if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) || (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ) continue; // files only lstrcpy (pfqfn, fd.cFileName); HBITMAP hbmSmall, hbmLarge; GetBitmaps (path, &hbmSmall, &hbmLarge); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, i++, RGB(1, 0, 254)); DeleteObject (hbmSmall); DeleteObject (hbmLarge); } while (FindNextFile (hFind, &fd) == TRUE); FindClose(hFind); } return S_OK; } #ifdef TODO_FIGURE_THIS_OUT HRESULT CComponent::OnSelect(LPDATAOBJECT pDataObject, long arg, long param) { if (!HIWORD(arg)) // being de-selected return S_OK; // don't care about this if (LOWORD(arg)) // in scope pane return S_OK; // don't care about this, either CDataObject *cdo = (CDataObject *)pDataObject; if (cdo->GetCookie() != DISPLAY_MANAGER_WALLPAPER) return S_OK; // TODO: do patterns later // // Bail if we couldn't get the console verb interface, or if the // selected item is the root; // if (!m_pConsoleVerb || pdo->GetCookieType() == COOKIE_IS_ROOT) { return S_OK; } // // Use selections and set which verbs are allowed // if (bScope) { if (pdo->GetCookieType() == COOKIE_IS_STATUS) { hr = m_pConsoleVerb->SetVerbState(MMC_VERB_REFRESH, ENABLED, TRUE); _ASSERT(hr == S_OK); } } else { // // Selection is in the result pane // } return S_OK; } #endif HRESULT CComponent::OnDblClick(LPDATAOBJECT pDataObject, long arg, long param) {//see note in CComponent::Command, below !!! _ASSERT (pDataObject); _ASSERT (m_pResultData); // hmmm: no documentation on arg or param.... CDataObject *cdo = (CDataObject *)pDataObject; lParamWallpaper * lpwp = (lParamWallpaper *)cdo->GetCookie(); if (lpwp) if (!IsBadReadPtr (lpwp, sizeof (lParamWallpaper))) { USES_CONVERSION; SystemParametersInfo (SPI_SETDESKWALLPAPER, 0, (void *)OLE2T(lpwp->filename), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); } return S_OK; } HRESULT CComponent::OnListPad (LPDATAOBJECT pDataObject, long arg, long param) { if (arg == TRUE) { // attaching IImageList* pImageList = NULL; m_pConsole->QueryResultImageList (&pImageList); if (pImageList) { HBITMAP hbmSmall, hbmLarge; GetBitmaps (_T("c:\\winnt\\dax.bmp"), &hbmSmall, &hbmLarge); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, 0, RGB(1, 0, 254)); pImageList->Release(); } // m_pResultData->SetViewMode (LVS_ICON); m_pResultData->SetViewMode (LVS_REPORT); m_pHeaderCtrl->InsertColumn (0, L"Name", 0, 170); // populate listview control via IResultData RESULTDATAITEM rdi; ZeroMemory(&rdi, sizeof(rdi)); rdi.mask = RDI_PARAM | RDI_STR | RDI_IMAGE; rdi.nImage = (int)MMC_CALLBACK; rdi.str = MMC_CALLBACK; rdi.lParam = -1; for (int i=0; i<11; i++) m_pResultData->InsertItem (&rdi); } return S_OK; } HRESULT CComponent::OnRestoreView (LPDATAOBJECT pDataObject, long arg, long param) { MMC_RESTORE_VIEW* pmrv = (MMC_RESTORE_VIEW*)arg; BOOL * pb = (BOOL *)param; _ASSERT (pmrv); _ASSERT (pb); // some versioning (not really necessary since this is the new rev.) if (pmrv->dwSize < sizeof(MMC_RESTORE_VIEW)) return E_FAIL; // version too old // maintain my internal state if (pmrv->pViewType) { USES_CONVERSION; // there are going to be two cases: // 1. custom html pages (res in my .dll) // 2. default html pages (res in mmc.exe) // get path to my .dll and compare to pViewType TCHAR szPath[MAX_PATH]; ::GetModuleFileName (g_hinst, szPath, MAX_PATH); if (wcsstr (pmrv->pViewType, T2OLE(szPath))) { // custom html if (wcsstr (pmrv->pViewType, L"/default.htm")) m_IsTaskPad = IDM_CUSTOMPAD; else if (wcsstr (pmrv->pViewType, L"/listview.htm")) m_IsTaskPad = IDM_TASKPAD_LISTVIEW; else { // this will happen when you can get to a taskpad by clicking // on a task, but there is no corresponding view menu option // to select. Therefore do something reasonable. // In my case, I can get to "wallpapr.htm" by either custom // or default routes (which is probably rather unusual). So, // I think I'll just leave the m_IsTaskPad value alone if // it's non-NULL, else pick one. if (m_IsTaskPad == 0) m_IsTaskPad = IDM_TASKPAD; } } else { // default html if (wcsstr (pmrv->pViewType, L"/default.htm#wallpaper_options")) m_IsTaskPad = IDM_TASKPAD_WALLPAPER_OPTIONS; else if (wcsstr (pmrv->pViewType, L"/default.htm")) m_IsTaskPad = IDM_TASKPAD; else if (wcsstr (pmrv->pViewType, L"/listpad.htm")) m_IsTaskPad = IDM_DEFAULT_LISTVIEW; else if (wcsstr (pmrv->pViewType, L"/horizontal.htm")) m_IsTaskPad = IDM_TASKPAD_LISTVIEW; else { _ASSERT (0 && "can't find MMC's resources"); return E_FAIL; } } } else m_IsTaskPad = 0; *pb = TRUE; // I'm handling the new history notify return S_OK; } // IExtendContextMenu HRESULT CComponent::AddMenuItems (LPDATAOBJECT pDataObject, LPCONTEXTMENUCALLBACK pContextMenuCallback, long *pInsertionAllowed) { CDataObject * cdo = (CDataObject *)pDataObject; switch (cdo->GetCookie ()) { case DISPLAY_MANAGER_WALLPAPER: case DISPLAY_MANAGER_PATTERN: return S_OK; case 0: // root // this is when they pull down the view menu if (*pInsertionAllowed & CCM_INSERTIONALLOWED_VIEW) { // add my taskpads and delete thingy CONTEXTMENUITEM m[] = { {L"Custom TaskPad", L"Custom TaskPad", IDM_CUSTOMPAD, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Default TaskPad", L"Default TaskPad", IDM_TASKPAD, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Wallpaper Options TaskPad", L"Wallpaper Options TaskPad", IDM_TASKPAD_WALLPAPER_OPTIONS, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Horizontal ListView", L"ListView TaskPad", IDM_TASKPAD_LISTVIEW, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Default ListPad", L"Default ListPad", IDM_DEFAULT_LISTVIEW, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"DeleteRootChildren", L"just testing", IDM_DELETECHILDREN, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"RenameRoot", L"just testing", IDM_RENAMEROOT, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"RenameWallPaperNode",L"just testing", IDM_RENAMEWALL, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"ChangeIcon", L"just testing", IDM_CHANGEICON, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Pre-Load", L"just testing", IDM_PRELOAD, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Test IConsoleVerb", L"just testing", IDM_CONSOLEVERB, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0} }; if (m_IsTaskPad == IDM_CUSTOMPAD) m[0].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_TASKPAD) m[1].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_TASKPAD_WALLPAPER_OPTIONS) m[2].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_TASKPAD_LISTVIEW) m[3].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_DEFAULT_LISTVIEW) m[4].fFlags = MF_CHECKED; if (m_pComponentData->GetPreload() == TRUE) m[9].fFlags = MF_CHECKED; pContextMenuCallback->AddItem (&m[0]); pContextMenuCallback->AddItem (&m[1]); pContextMenuCallback->AddItem (&m[2]); pContextMenuCallback->AddItem (&m[3]); pContextMenuCallback->AddItem (&m[4]); pContextMenuCallback->AddItem (&m[5]); pContextMenuCallback->AddItem (&m[6]); pContextMenuCallback->AddItem (&m[7]); pContextMenuCallback->AddItem (&m[8]); pContextMenuCallback->AddItem (&m[9]); return pContextMenuCallback->AddItem (&m[10]); } return S_OK; default: break; } // add to context menu, only if in result pane: // this is when they right-click on the result pane. if (cdo->GetType() == CCT_RESULT) { CONTEXTMENUITEM cmi; cmi.strName = L"Center"; cmi.strStatusBarText = L"Center Desktop Wallpaper"; cmi.lCommandID = IDM_CENTER; cmi.lInsertionPointID = CCM_INSERTIONPOINTID_PRIMARY_TOP; cmi.fFlags = 0; cmi.fSpecialFlags = CCM_SPECIAL_DEFAULT_ITEM; pContextMenuCallback->AddItem (&cmi); cmi.strName = L"Tile"; cmi.strStatusBarText = L"Tile Desktop Wallpaper"; cmi.lCommandID = IDM_TILE; cmi.lInsertionPointID = CCM_INSERTIONPOINTID_PRIMARY_TOP; cmi.fFlags = 0; cmi.fSpecialFlags = 0; // CCM_SPECIAL_DEFAULT_ITEM; pContextMenuCallback->AddItem (&cmi); cmi.strName = L"Stretch"; cmi.strStatusBarText = L"Stretch Desktop Wallpaper"; cmi.lCommandID = IDM_STRETCH; cmi.lInsertionPointID = CCM_INSERTIONPOINTID_PRIMARY_TOP; cmi.fFlags = 0; cmi.fSpecialFlags = 0; // CCM_SPECIAL_DEFAULT_ITEM; pContextMenuCallback->AddItem (&cmi); } return S_OK; } HRESULT CComponent::Command (long nCommandID, LPDATAOBJECT pDataObject) { m_IsTaskPad = 0; CDataObject * cdo = reinterpret_cast<CDataObject *>(pDataObject); switch (nCommandID) { case IDM_TILE: case IDM_CENTER: case IDM_STRETCH: // write registry key: { HKEY hkey; HRESULT r = RegOpenKeyEx (HKEY_CURRENT_USER, _T("Control Panel\\Desktop"), 0, KEY_ALL_ACCESS, &hkey); if (r == ERROR_SUCCESS) { // write new value(s) DWORD dwType = REG_SZ; TCHAR szBuffer[2]; // first do "TileWallpaper" if (nCommandID == IDM_TILE) lstrcpy (szBuffer, _T("1")); else lstrcpy (szBuffer, _T("0")); DWORD dwCount = sizeof(TCHAR)*(1+lstrlen (szBuffer)); r = RegSetValueEx (hkey, (LPCTSTR)_T("TileWallpaper"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // then do "WallpaperStyle" if (nCommandID == IDM_STRETCH) lstrcpy (szBuffer, _T("2")); else lstrcpy (szBuffer, _T("0")); r = RegSetValueEx (hkey, (LPCTSTR)_T("WallpaperStyle"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // close up shop RegCloseKey(hkey); _ASSERT(r == ERROR_SUCCESS); /* [HKEY_CURRENT_USER\Control Panel\Desktop] "CoolSwitch"="1" "CoolSwitchRows"="3" "CoolSwitchColumns"="7" "CursorBlinkRate"="530" "ScreenSaveTimeOut"="900" "ScreenSaveActive"="0" "ScreenSaverIsSecure"="0" "Pattern"="(None)" "Wallpaper"="C:\\WINNT\\dax.bmp" "TileWallpaper"="0" "GridGranularity"="0" "IconSpacing"="75" "IconTitleWrap"="1" "IconTitleFaceName"="MS Sans Serif" "IconTitleSize"="9" "IconTitleStyle"="0" "DragFullWindows"="1" "HungAppTimeout"="5000" "WaitToKillAppTimeout"="20000" "AutoEndTasks"="0" "FontSmoothing"="0" "MenuShowDelay"="400" "DragHeight"="2" "DragWidth"="2" "WheelScrollLines"="3" "WallpaperStyle"="0" */ } } break; case IDM_TASKPAD: case IDM_CUSTOMPAD: case IDM_TASKPAD_LISTVIEW: case IDM_DEFAULT_LISTVIEW: case IDM_TASKPAD_WALLPAPER_OPTIONS: if (cdo->GetCookie() == 0) { HSCOPEITEM root = m_pComponentData->GetRoot(); if (root) { // we should now be ready for taskpad "view" m_IsTaskPad = nCommandID; // set before selecting node // cause new view to be "created" m_pConsole->SelectScopeItem (root); } } return S_OK; case IDM_DELETECHILDREN: if (g_root_scope_item != 0) m_pComponentData->myDeleteItem (g_root_scope_item, TRUE); return S_OK; case IDM_RENAMEROOT: if (g_root_scope_item != 0) m_pComponentData->myRenameItem (g_root_scope_item, L"Yippee!"); return S_OK; case IDM_RENAMEWALL: if (m_toggle) m_toggle = FALSE; else m_toggle = TRUE; m_pComponentData->myRenameItem (m_pComponentData->GetWallPaperNode(), NULL); return S_OK; case IDM_CHANGEICON: m_pComponentData->myChangeIcon (); return S_OK; case IDM_PRELOAD: m_pComponentData->myPreLoad(); return S_OK; case IDM_CONSOLEVERB: TestConsoleVerb(); return S_OK; default: return E_UNEXPECTED; } return OnDblClick (pDataObject, NULL, NULL); // note what I'm passing! } long CComponent::GetViewMode () { long vm = LVS_ICON; if (m_pResultData) m_pResultData->GetViewMode (&vm); return vm; } /////////////////////////////////////////////////////////////////////////////// // IExtendTaskPad interface members HRESULT CComponent::TaskNotify (IDataObject * pdo, VARIANT * pvarg, VARIANT * pvparam) { if (pvarg->vt == VT_BSTR) { USES_CONVERSION; OLECHAR * path = pvarg->bstrVal; // replace any '*' with ' ': see enumtask.cpp // hash mechanism can't handle spaces, and // filenames can't have '*'s, so this works out ok. OLECHAR * temp; while (temp = wcschr (path, '*')) *temp = ' '; // now go do it! SystemParametersInfo (SPI_SETDESKWALLPAPER, 0, (void *)OLE2T(path), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); return S_OK; } if (pvarg->vt == VT_I4) { switch (pvarg->lVal) { case 1: if (m_pComponentData->GetWallPaperNode () != (HSCOPEITEM)0) { _ASSERT (m_pConsole != NULL); m_pConsole->SelectScopeItem (m_pComponentData->GetWallPaperNode()); return S_OK; } break; case 2: // Center return ApplyOption (IDM_CENTER); case 3: // Tile return ApplyOption (IDM_TILE); case 4: // Stretch return ApplyOption (IDM_STRETCH); case -1: if (m_toggleEntry == FALSE) m_toggleEntry = TRUE; else m_toggleEntry = FALSE; // empty and repopulate listpad m_pResultData->DeleteAllRsltItems(); m_pHeaderCtrl->DeleteColumn (0); OnListPad (NULL, TRUE, 0); return S_OK; } } ::MessageBox (NULL, _T("unrecognized task notification"), _T("Display Manager"), MB_OK); return S_OK; } HRESULT CComponent::GetTitle (LPOLESTR szGroup, LPOLESTR * pszTitle) { *pszTitle = CoTaskDupString (L"Display Manager TaskPad"); if (!pszTitle) return E_OUTOFMEMORY; return S_OK; } HRESULT CComponent::GetDescriptiveText (LPOLESTR szGroup, LPOLESTR * pszTitle) { *pszTitle = CoTaskDupString (L"Bill's Handy-Dandy Display Manager TaskPad Sample"); if (!pszTitle) return E_OUTOFMEMORY; return S_OK; } HRESULT CComponent::GetBackground (LPOLESTR szGroup, MMC_TASK_DISPLAY_OBJECT * pdo) { USES_CONVERSION; if(NULL==szGroup) return E_FAIL; if (szGroup[0] == 0) { // bitmap case pdo->eDisplayType = MMC_TASK_DISPLAY_TYPE_BITMAP; MMC_TASK_DISPLAY_BITMAP *pdb = &pdo->uBitmap; // fill out bitmap URL TCHAR szBuffer[MAX_PATH*2]; // that should be enough _tcscpy (szBuffer, _T("res://")); ::GetModuleFileName (g_hinst, szBuffer + _tcslen(szBuffer), MAX_PATH); _tcscat (szBuffer, _T("/img\\ntbanner.gif")); pdb->szMouseOverBitmap = CoTaskDupString (T2OLE(szBuffer)); if (pdb->szMouseOverBitmap) return S_OK; return E_OUTOFMEMORY; } else { // symbol case pdo->eDisplayType = MMC_TASK_DISPLAY_TYPE_SYMBOL; MMC_TASK_DISPLAY_SYMBOL *pds = &pdo->uSymbol; // fill out symbol stuff pds->szFontFamilyName = CoTaskDupString (L"Kingston"); // name of font family if (pds->szFontFamilyName) { TCHAR szBuffer[MAX_PATH*2]; // that should be enough _tcscpy (szBuffer, _T("res://")); ::GetModuleFileName (g_hinst, szBuffer + _tcslen(szBuffer), MAX_PATH); _tcscat (szBuffer, _T("/KINGSTON.eot")); pds->szURLtoEOT = CoTaskDupString (T2OLE(szBuffer)); // "res://"-type URL to EOT file if (pds->szURLtoEOT) { pds->szSymbolString = CoTaskDupString (T2OLE(_T("A<BR>BCDEFGHIJKLMNOPQRSTUVWXYZ"))); // 1 or more symbol characters if (pds->szSymbolString) return S_OK; CoTaskFreeString (pds->szURLtoEOT); } CoTaskFreeString (pds->szFontFamilyName); } return E_OUTOFMEMORY; } } HRESULT CComponent::EnumTasks (IDataObject * pdo, LPOLESTR szTaskGroup, IEnumTASK** ppEnumTASK) { HRESULT hresult = S_OK; CEnumTasks * pet = new CEnumTasks; if (!pet) hresult = E_OUTOFMEMORY; else { pet->AddRef (); // make sure release works properly on failure hresult = pet->Init (pdo, szTaskGroup); if (hresult == S_OK) hresult = pet->QueryInterface (IID_IEnumTASK, (void **)ppEnumTASK); pet->Release (); } return hresult; } HRESULT CComponent::GetListPadInfo (LPOLESTR szGroup, MMC_LISTPAD_INFO * pListPadInfo) { pListPadInfo->szTitle = CoTaskDupString (L"Display Manager ListPad Title"); pListPadInfo->szButtonText = CoTaskDupString (L"Change..."); pListPadInfo->nCommandID = -1; return S_OK; } HRESULT ApplyOption (int nCommandID) { switch (nCommandID) { case IDM_TILE: case IDM_CENTER: case IDM_STRETCH: // write registry key: { HKEY hkey; HRESULT r = RegOpenKeyEx (HKEY_CURRENT_USER, _T("Control Panel\\Desktop"), 0, KEY_ALL_ACCESS, &hkey); if (r == ERROR_SUCCESS) { // write new value(s) DWORD dwType = REG_SZ; TCHAR szBuffer[2]; // first do "TileWallpaper" if (nCommandID == IDM_TILE) lstrcpy (szBuffer, _T("1")); else lstrcpy (szBuffer, _T("0")); DWORD dwCount = sizeof(TCHAR)*(1+lstrlen (szBuffer)); r = RegSetValueEx (hkey, (LPCTSTR)_T("TileWallpaper"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // then do "WallpaperStyle" if (nCommandID == IDM_STRETCH) lstrcpy (szBuffer, _T("2")); else lstrcpy (szBuffer, _T("0")); r = RegSetValueEx (hkey, (LPCTSTR)_T("WallpaperStyle"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // close up shop RegCloseKey(hkey); _ASSERT(r == ERROR_SUCCESS); /* [HKEY_CURRENT_USER\Control Panel\Desktop] "CoolSwitch"="1" "CoolSwitchRows"="3" "CoolSwitchColumns"="7" "CursorBlinkRate"="530" "ScreenSaveTimeOut"="900" "ScreenSaveActive"="0" "ScreenSaverIsSecure"="0" "Pattern"="(None)" "Wallpaper"="C:\\WINNT\\dax.bmp" "TileWallpaper"="0" "GridGranularity"="0" "IconSpacing"="75" "IconTitleWrap"="1" "IconTitleFaceName"="MS Sans Serif" "IconTitleSize"="9" "IconTitleStyle"="0" "DragFullWindows"="1" "HungAppTimeout"="5000" "WaitToKillAppTimeout"="20000" "AutoEndTasks"="0" "FontSmoothing"="0" "MenuShowDelay"="400" "DragHeight"="2" "DragWidth"="2" "WheelScrollLines"="3" "WallpaperStyle"="0" */ } if (r == ERROR_SUCCESS) ::MessageBox (NULL, _T("Option set Successfully!"), _T("Display Manager"), MB_OK); return r; } default: break; } return S_FALSE; } void CComponent::TestConsoleVerb(void) { IConsoleVerb* pConsoleVerb = NULL; m_pConsole->QueryConsoleVerb (&pConsoleVerb); _ASSERT (pConsoleVerb != NULL); if (pConsoleVerb) { pConsoleVerb->SetVerbState (MMC_VERB_PASTE, ENABLED, TRUE); pConsoleVerb->Release(); } }
35.673123
150
0.505102
npocmaka
923a66a623dc3654b9b018aaba9c5b2b6d597c56
1,135
cpp
C++
Copy List with Random Pointers.cpp
AMARTYA2020/DSA
54936ce7a63535704f81784ade9af743a68ba419
[ "MIT" ]
3
2021-02-03T10:39:17.000Z
2021-05-28T11:50:01.000Z
Copy List with Random Pointers.cpp
AMARTYA2020/DSA
54936ce7a63535704f81784ade9af743a68ba419
[ "MIT" ]
null
null
null
Copy List with Random Pointers.cpp
AMARTYA2020/DSA
54936ce7a63535704f81784ade9af743a68ba419
[ "MIT" ]
1
2021-02-07T07:19:25.000Z
2021-02-07T07:19:25.000Z
#include<bits/stdc++.h> using namespace std; // COPY LIST WITH RANDOM POINTER: class solution{ public: Node* copyRandomList(Node* head){ // CREATING NORMAL LINKED LIST THAT HAS A DATA FIELD AND ADDRESS FIELD: Node* curr=head; while(curr!=NULL){ Node* next=curr->next; curr->next=new Node(curr->val); curr->next->next=next; curr=next; } // CREATING LINKED LIST THAT HAS A RANDOM ADDRESS FIELD: curr=head; while(curr!=NULL){ if(curr->random!=NULL){ curr->next->random=curr->random->next; }else{ curr->next->random=NULL; } curr=curr->next->next; } // CREATING ANOTHER LINKED LIST: Node* newhead=new Node(0); Node* copycurr=newhead; curr=head; while(curr!=NULL){ copycurr->next=curr->next; curr->next=copycurr->next->next; curr=curr->next; copycurr=copycurr->next; } return newnode->next; } };
28.375
80
0.502203
AMARTYA2020