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
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
455680b9155630f3e6d96be1a8de3c27928d49c0
517
hpp
C++
src/Exceptions/Exception.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
src/Exceptions/Exception.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
src/Exceptions/Exception.hpp
pokorj54/Command-line-calendar
de2c8a89917bd4cb69547427a6ec1bced218c5ad
[ "MIT" ]
null
null
null
#ifndef Exception_785a62ec3213411cb4e442ee734c00cb #define Exception_785a62ec3213411cb4e442ee734c00cb #include <iostream> /** * @brief Abstract class providing genereal interface to exceptions * */ class Exception: public std::exception { public: /** * @brief Message that can be printed to the end user * * @param[out] o here it will be printed */ virtual void Message(std::ostream & o) const = 0; }; #endif //Exception_785a62ec3213411cb4e442ee734c00cb
24.619048
67
0.686654
4558774323aa65b0256e5a57988556294f5c1ef0
2,982
cxx
C++
src/Cxx/Visualization/ProjectSphere.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/Visualization/ProjectSphere.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/Visualization/ProjectSphere.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkActor.h> #include <vtkCamera.h> #include <vtkElevationFilter.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkParametricFunctionSource.h> #include <vtkParametricSuperEllipsoid.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProjectSphereFilter.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> int main(int, char*[]) { vtkNew<vtkNamedColors> colors; vtkNew<vtkParametricSuperEllipsoid> surface; surface->SetN1(2.0); surface->SetN2(0.5); vtkNew<vtkParametricFunctionSource> source; source->SetParametricFunction(surface); vtkNew<vtkElevationFilter> elevationFilter; elevationFilter->SetInputConnection(source->GetOutputPort()); elevationFilter->SetLowPoint(0.0, 0.0, -4.0); elevationFilter->SetHighPoint(0.0, 0.0, 4.0); elevationFilter->Update(); // Deep copy the point data since in some versions of VTK, // the ProjectSphereFilter modifies the input point data vtkNew<vtkPolyData> pd1; pd1->DeepCopy(elevationFilter->GetOutput()); vtkNew<vtkProjectSphereFilter> sphereProject1; sphereProject1->SetInputConnection(elevationFilter->GetOutputPort()); sphereProject1->Update(); vtkNew<vtkPolyDataMapper> mapper1; mapper1->SetInputConnection(sphereProject1->GetOutputPort()); mapper1->SetScalarRange( sphereProject1->GetOutput()->GetPointData()->GetScalars()->GetRange()); vtkNew<vtkActor> actor1; actor1->SetMapper(mapper1); vtkNew<vtkPolyDataMapper> mapper2; mapper2->SetInputData(pd1); mapper2->SetScalarRange(pd1->GetPointData()->GetScalars()->GetRange()); vtkNew<vtkActor> actor2; actor2->SetMapper(mapper2); // A render window vtkNew<vtkRenderWindow> renderWindow; // Define viewport ranges // (xmin, ymin, xmax, ymax) double leftViewport[4] = {0.0, 0.0, 0.5, 1.0}; double rightViewport[4] = {0.5, 0.0, 1.0, 1.0}; // Setup both renderers vtkNew<vtkRenderer> leftRenderer; renderWindow->AddRenderer(leftRenderer); leftRenderer->SetViewport(leftViewport); leftRenderer->SetBackground(colors->GetColor3d("RosyBrown").GetData()); vtkNew<vtkRenderer> rightRenderer; renderWindow->AddRenderer(rightRenderer); rightRenderer->SetViewport(rightViewport); rightRenderer->SetBackground(colors->GetColor3d("CadetBlue").GetData()); leftRenderer->AddActor(actor2); rightRenderer->AddActor(actor1); // An interactor vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); leftRenderer->GetActiveCamera()->Azimuth(30); leftRenderer->GetActiveCamera()->Elevation(-30); leftRenderer->ResetCamera(); // Render an image (lights and cameras are created automatically) renderWindow->SetSize(640, 480); renderWindow->SetWindowName("ProjectSphere"); renderWindow->Render(); // Begin mouse interaction renderWindowInteractor->Start(); return EXIT_SUCCESS; }
30.742268
77
0.757881
455878b48a2ef154a4e5242dc0e51a7aee92a867
898
cpp
C++
src/util/TexShare.cpp
pharpend/Oscilloscope
e2598c559302bd91747b73a251d614eeb4dea663
[ "MIT" ]
460
2015-03-18T18:59:49.000Z
2022-03-19T19:11:09.000Z
src/util/TexShare.cpp
pharpend/Oscilloscope
e2598c559302bd91747b73a251d614eeb4dea663
[ "MIT" ]
78
2015-05-10T07:23:55.000Z
2022-03-09T13:58:51.000Z
src/util/TexShare.cpp
pharpend/Oscilloscope
e2598c559302bd91747b73a251d614eeb4dea663
[ "MIT" ]
64
2015-06-13T01:45:54.000Z
2022-01-14T17:38:19.000Z
// // SharedTex.cpp // Oscilloscope // // Created by Hansi on 27/06/19. // // #include "TexShare.h" #include "ofMain.h" #ifdef TARGET_OSX #include "ofxSyphon.h" class TexShareImpl{ public: ofxSyphonServer server; void setup(string name){ server.setName(name); } void update(ofTexture &tex){ server.publishTexture(&tex); } }; #elif defined TARGET_WIN32 #include "ofxSpout.h" class TexShareImpl{ public: ofxSpout::Sender spoutSender; void setup(string name){ spoutSender.init(name); } void update(ofTexture &tex){ spoutSender.send(tex); } }; #else class TexShareImpl{ public: void setup(string name){} void update(ofTexture & tex){}; }; #endif TexShare::TexShare(){ impl = make_unique<TexShareImpl>(); } TexShare::~TexShare() = default; void TexShare::setup(string name){ impl->setup(name); } void TexShare::update(ofTexture &tex){ impl->update(tex); }
14.483871
38
0.690423
455a9f22c0c56eeceee8a943903882aa281ccc0d
20,389
hxx
C++
main/writerfilter/source/ooxml/OOXMLFastContextHandler.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/writerfilter/source/ooxml/OOXMLFastContextHandler.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/writerfilter/source/ooxml/OOXMLFastContextHandler.hxx
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. * *************************************************************/ #ifndef INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX #define INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX #include <com/sun/star/xml/sax/XFastShapeContextHandler.hpp> #include <string> #include <set> #include "sal/config.h" #include "com/sun/star/uno/XComponentContext.hpp" #include "cppuhelper/implbase1.hxx" #include "com/sun/star/xml/sax/XFastContextHandler.hpp" #include "OOXMLParserState.hxx" #include "OOXMLPropertySetImpl.hxx" #include "OOXMLDocumentImpl.hxx" #include "RefAndPointer.hxx" #include <ooxml/OOXMLFastTokens.hxx> namespace writerfilter { namespace ooxml { using namespace ::std; using namespace ::com::sun::star; using namespace ::com::sun::star::xml::sax; typedef boost::shared_ptr<Stream> StreamPointer_t; class OOXMLFastContextHandler: public ::cppu::WeakImplHelper1< xml::sax::XFastContextHandler> { public: typedef RefAndPointer<XFastContextHandler, OOXMLFastContextHandler> RefAndPointer_t; typedef boost::shared_ptr<OOXMLFastContextHandler> Pointer_t; enum ResourceEnum_t { UNKNOWN, STREAM, PROPERTIES, TABLE, SHAPE }; OOXMLFastContextHandler(); explicit OOXMLFastContextHandler( uno::Reference< uno::XComponentContext > const & context ); explicit OOXMLFastContextHandler( OOXMLFastContextHandler * pContext ); virtual ~OOXMLFastContextHandler(); // ::com::sun::star::xml::sax::XFastContextHandler: virtual void SAL_CALL startFastElement (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void SAL_CALL startUnknownElement (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void SAL_CALL endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual void SAL_CALL endUnknownElement (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name) throw (uno::RuntimeException, xml::sax::SAXException); virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL createFastChildContext (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL createUnknownChildContext (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void SAL_CALL characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException); static const uno::Sequence< sal_Int8 > & getUnoTunnelId(); virtual sal_Int64 SAL_CALL getSomething(const uno::Sequence<sal_Int8> & rId) throw (uno::RuntimeException); // local void setStream(Stream * pStream); /** Return value of this context(element). @return the value */ virtual OOXMLValue::Pointer_t getValue() const; /** Returns a string describing the type of the context. This is the name of the define normally. @return type string */ virtual string getType() const { return "??"; } virtual ResourceEnum_t getResource() const { return STREAM; } virtual void attributes (const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void newProperty(const Id & rId, OOXMLValue::Pointer_t pVal); virtual void setPropertySet(OOXMLPropertySet::Pointer_t pPropertySet); virtual OOXMLPropertySet::Pointer_t getPropertySet() const; virtual void setToken(Token_t nToken); virtual Token_t getToken() const; void mark(const Id & rId, OOXMLValue::Pointer_t pVal); void resolveFootnote( const sal_Int32 nIDForXNoteStream ); void resolveEndnote( const sal_Int32 nIDForXNoteStream ); void resolveComment( const sal_Int32 nIDForXNoteStream ); void resolvePicture(const rtl::OUString & rId); void resolveHeader(const sal_Int32 type, const rtl::OUString & rId); void resolveFooter(const sal_Int32 type, const rtl::OUString & rId); void resolveOLE(const rtl::OUString & rId); ::rtl::OUString getTargetForId(const ::rtl::OUString & rId); uno::Reference < xml::sax::XFastContextHandler > createFromStart (sal_uInt32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs); void setDocument(OOXMLDocument * pDocument); OOXMLDocument * getDocument(); void setIDForXNoteStream(OOXMLValue::Pointer_t pValue); void setForwardEvents(bool bForwardEvents); bool isForwardEvents() const; virtual void setParent(OOXMLFastContextHandler * pParent); virtual void setId(Id nId); virtual Id getId() const; void setDefine(Id nDefine); Id getDefine() const; OOXMLParserState::Pointer_t getParserState() const; void sendTableDepth() const; void setHandle(); void startSectionGroup(); void setLastParagraphInSection(); void endSectionGroup(); void startParagraphGroup(); void endParagraphGroup(); void startCharacterGroup(); void endCharacterGroup(); void startField(); void fieldSeparator(); void endField(); void ftnednref(); void ftnedncont(); void ftnednsep(); void pgNum(); void tab(); void cr(); void noBreakHyphen(); void softHyphen(); void handleLastParagraphInSection(); void endOfParagraph(); void text(const ::rtl::OUString & sText); virtual void propagateCharacterProperties(); virtual void propagateCharacterPropertiesAsSet(const Id & rId); virtual void propagateTableProperties(); virtual void propagateRowProperties(); virtual void propagateCellProperties(); virtual bool propagatesProperties() const; void sendPropertiesWithId(const Id & rId); void sendPropertiesToParent(); void sendCellProperties(); void sendRowProperties(); void sendTableProperties(); void clearTableProps(); void clearProps(); virtual void setDefaultBooleanValue(); virtual void setDefaultIntegerValue(); virtual void setDefaultHexValue(); virtual void setDefaultStringValue(); void sendPropertyToParent(); #ifdef DEBUG static XMLTag::Pointer_t toPropertiesTag(OOXMLPropertySet::Pointer_t); virtual XMLTag::Pointer_t toTag() const; virtual string toString() const; #endif protected: OOXMLFastContextHandler * mpParent; Id mId; Id mnDefine; Token_t mnToken; // the stream to send the stream events to. Stream * mpStream; // the current global parser state OOXMLParserState::Pointer_t mpParserState; // the table depth of this context unsigned int mnTableDepth; virtual void lcl_startFastElement (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual uno::Reference< xml::sax::XFastContextHandler > lcl_createFastChildContext (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException); void startAction(sal_Int32 Element); virtual void lcl_startAction(sal_Int32 Element); void endAction(sal_Int32 Element); virtual void lcl_endAction(sal_Int32 Element); // Returns string for resource of this context. (debug) string getResourceString() const; virtual OOXMLPropertySet * getPicturePropSet (const ::rtl::OUString & rId); virtual void resolvePropertySetAttrs(); uno::Reference< uno::XComponentContext > getComponentContext(); sal_uInt32 mnInstanceNumber; sal_uInt32 mnRefCount; private: void operator =(OOXMLFastContextHandler &); // not defined uno::Reference< uno::XComponentContext > m_xContext; static sal_uInt32 mnInstanceCount; }; class OOXMLFastContextHandlerStream : public OOXMLFastContextHandler { public: OOXMLFastContextHandlerStream(OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerStream(); virtual ResourceEnum_t getResource() const { return STREAM; } OOXMLPropertySet::Pointer_t getPropertySetAttrs() const; virtual void newProperty(const Id & rId, OOXMLValue::Pointer_t pVal); virtual void sendProperty(Id nId); virtual OOXMLPropertySet::Pointer_t getPropertySet() const; void handleHyperlink(); protected: virtual void resolvePropertySetAttrs(); private: mutable OOXMLPropertySet::Pointer_t mpPropertySetAttrs; }; class OOXMLFastContextHandlerProperties : public OOXMLFastContextHandler { public: OOXMLFastContextHandlerProperties(OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerProperties(); virtual OOXMLValue::Pointer_t getValue() const; virtual ResourceEnum_t getResource() const { return PROPERTIES; } virtual void newProperty(const Id & nId, OOXMLValue::Pointer_t pVal); void handleXNotes(); void handleHdrFtr(); void handleComment(); void handlePicture(); void handleBreak(); void handleOLE(); virtual void setPropertySet(OOXMLPropertySet::Pointer_t pPropertySet); virtual OOXMLPropertySet::Pointer_t getPropertySet() const; #ifdef DEBUG virtual XMLTag::Pointer_t toTag() const; #endif protected: /// the properties OOXMLPropertySet::Pointer_t mpPropertySet; virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual void setParent(OOXMLFastContextHandler * pParent); private: bool mbResolve; }; class OOXMLFastContextHandlerPropertyTable : public OOXMLFastContextHandlerProperties { public: OOXMLFastContextHandlerPropertyTable(OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerPropertyTable(); protected: OOXMLTableImpl mTable; virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); }; class OOXMLFastContextHandlerValue : public OOXMLFastContextHandler { public: OOXMLFastContextHandlerValue (OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerValue(); virtual void setValue(OOXMLValue::Pointer_t pValue); virtual OOXMLValue::Pointer_t getValue() const; virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual string getType() const { return "Value"; } virtual void setDefaultBooleanValue(); virtual void setDefaultIntegerValue(); virtual void setDefaultHexValue(); virtual void setDefaultStringValue(); protected: OOXMLValue::Pointer_t mpValue; }; class OOXMLFastContextHandlerTable : public OOXMLFastContextHandler { public: OOXMLFastContextHandlerTable(OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerTable(); virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL createFastChildContext (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void newPropertySet(OOXMLPropertySet::Pointer_t pPropertySet); protected: OOXMLTableImpl mTable; RefAndPointer_t mCurrentChild; virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual ResourceEnum_t getResource() const { return TABLE; } virtual string getType() const { return "Table"; } void addCurrentChild(); }; class OOXMLFastContextHandlerXNote : public OOXMLFastContextHandlerProperties { public: OOXMLFastContextHandlerXNote(OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerXNote(); void checkId(OOXMLValue::Pointer_t pValue); virtual string getType() const { return "XNote"; } private: bool mbForwardEventsSaved; sal_Int32 mnMyXNoteId; virtual void lcl_startFastElement (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual ResourceEnum_t getResource() const { return STREAM; } }; class OOXMLFastContextHandlerTextTableCell : public OOXMLFastContextHandler { public: OOXMLFastContextHandlerTextTableCell (OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerTextTableCell(); virtual string getType() const { return "TextTableCell"; } void startCell(); void endCell(); }; class OOXMLFastContextHandlerTextTableRow : public OOXMLFastContextHandler { public: OOXMLFastContextHandlerTextTableRow (OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerTextTableRow(); virtual string getType() const { return "TextTableRow"; } void startRow(); void endRow(); }; class OOXMLFastContextHandlerTextTable : public OOXMLFastContextHandler { public: OOXMLFastContextHandlerTextTable (OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerTextTable(); virtual string getType() const { return "TextTable"; } protected: virtual void lcl_startFastElement (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); }; class OOXMLFastContextHandlerShape: public OOXMLFastContextHandlerProperties { private: bool m_bShapeSent; bool m_bShapeStarted; public: explicit OOXMLFastContextHandlerShape (OOXMLFastContextHandler * pContext); virtual ~OOXMLFastContextHandlerShape(); virtual string getType() const { return "Shape"; } // ::com::sun::star::xml::sax::XFastContextHandler: virtual void SAL_CALL startUnknownElement (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void SAL_CALL endUnknownElement (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name) throw (uno::RuntimeException, xml::sax::SAXException); virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL createUnknownChildContext (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void setToken(Token_t nToken); virtual ResourceEnum_t getResource() const { return SHAPE; } void sendShape( Token_t Element ); protected: typedef uno::Reference<XFastShapeContextHandler> ShapeContextRef; ShapeContextRef mrShapeContext; virtual void lcl_startFastElement (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual uno::Reference< xml::sax::XFastContextHandler > lcl_createFastChildContext (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException); }; /** OOXMLFastContextHandlerWrapper wraps an OOXMLFastContextHandler. The method calls for the interface ::com::sun::star::xml::sax::XFastContextHandler are forwarded to the wrapped OOXMLFastContextHandler. */ class OOXMLFastContextHandlerWrapper : public OOXMLFastContextHandler { public: explicit OOXMLFastContextHandlerWrapper (OOXMLFastContextHandler * pParent, uno::Reference<XFastContextHandler> xContext); virtual ~OOXMLFastContextHandlerWrapper(); // ::com::sun::star::xml::sax::XFastContextHandler: virtual void SAL_CALL startUnknownElement (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void SAL_CALL endUnknownElement (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name) throw (uno::RuntimeException, xml::sax::SAXException); virtual uno::Reference< xml::sax::XFastContextHandler > SAL_CALL createUnknownChildContext (const ::rtl::OUString & Namespace, const ::rtl::OUString & Name, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void attributes (const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual ResourceEnum_t getResource() const; void addNamespace(const Id & nId); void addToken( Token_t Element ); virtual void newProperty(const Id & rId, OOXMLValue::Pointer_t pVal); virtual void setPropertySet(OOXMLPropertySet::Pointer_t pPropertySet); virtual OOXMLPropertySet::Pointer_t getPropertySet() const; virtual string getType() const; protected: virtual void lcl_startFastElement (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_endFastElement(sal_Int32 Element) throw (uno::RuntimeException, xml::sax::SAXException); virtual uno::Reference< xml::sax::XFastContextHandler > lcl_createFastChildContext (sal_Int32 Element, const uno::Reference< xml::sax::XFastAttributeList > & Attribs) throw (uno::RuntimeException, xml::sax::SAXException); virtual void lcl_characters(const ::rtl::OUString & aChars) throw (uno::RuntimeException, xml::sax::SAXException); virtual void setId(Id nId); virtual Id getId() const; virtual void setToken(Token_t nToken); virtual Token_t getToken() const; private: uno::Reference<XFastContextHandler> mxContext; set<Id> mMyNamespaces; set<Token_t> mMyTokens; OOXMLPropertySet::Pointer_t mpPropertySet; OOXMLFastContextHandler * getFastContextHandler() const; }; }} #endif // INCLUDED_OOXML_FAST_CONTEXT_HANDLER_HXX
32.261076
80
0.71568
4568b8382c54da544c4c3ba3095eb7ec6c41ecac
4,872
cpp
C++
convertxml/native_module_convertxml.cpp
openharmony-gitee-mirror/js_api_module
2c3d4cf53a81d4b68933cdeec74e4c3e3da7f46d
[ "Apache-2.0" ]
null
null
null
convertxml/native_module_convertxml.cpp
openharmony-gitee-mirror/js_api_module
2c3d4cf53a81d4b68933cdeec74e4c3e3da7f46d
[ "Apache-2.0" ]
null
null
null
convertxml/native_module_convertxml.cpp
openharmony-gitee-mirror/js_api_module
2c3d4cf53a81d4b68933cdeec74e4c3e3da7f46d
[ "Apache-2.0" ]
1
2021-09-13T11:21:19.000Z
2021-09-13T11:21:19.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "utils/log.h" #include "js_convertxml.h" #include "napi/native_api.h" #include "napi/native_node_api.h" extern const char _binary_js_convertxml_js_start[]; extern const char _binary_js_convertxml_js_end[]; extern const char _binary_convertxml_abc_start[]; extern const char _binary_convertxml_abc_end[]; namespace OHOS::Xml { static napi_value ConvertXmlConstructor(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; void *data = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, &data); auto objectInfo = new ConvertXml(env); napi_wrap( env, thisVar, objectInfo, [](napi_env env, void *data, void *hint) { auto obj = (ConvertXml*)data; if (obj != nullptr) { delete obj; } }, nullptr, nullptr); return thisVar; } static napi_value Convert(napi_env env, napi_callback_info info) { napi_value thisVar = nullptr; size_t requireMaxArgc = 2; // 2:MaxArgc size_t requireMinArgc = 1; size_t argc = 2; napi_value args[2] = {nullptr}; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); NAPI_ASSERT(env, argc <= requireMaxArgc, "Wrong number of arguments(Over)"); NAPI_ASSERT(env, argc >= requireMinArgc, "Wrong number of arguments(Less)"); std::string strXml; napi_valuetype valuetype; ConvertXml *object = nullptr; NAPI_CALL(env, napi_unwrap(env, thisVar, reinterpret_cast<void**>(&object))); if (args[0] == nullptr) { NAPI_CALL(env, napi_throw_error(env, "", "parameter is empty")); } else { NAPI_CALL(env, napi_typeof(env, args[0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument typr. String expected."); object->DealNapiStrValue(args[0], strXml); } if (args[1] != nullptr) { object->DealOptions(args[1]); } napi_value result = object->Convert(strXml); return result; } static napi_value ConvertXmlInit(napi_env env, napi_value exports) { const char *convertXmlClassName = "ConvertXml"; napi_value convertXmlClass = nullptr; static napi_property_descriptor convertXmlDesc[] = { DECLARE_NAPI_FUNCTION("convert", Convert) }; NAPI_CALL(env, napi_define_class(env, convertXmlClassName, strlen(convertXmlClassName), ConvertXmlConstructor, nullptr, sizeof(convertXmlDesc) / sizeof(convertXmlDesc[0]), convertXmlDesc, &convertXmlClass)); static napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("ConvertXml", convertXmlClass) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); return exports; } extern "C" __attribute__((visibility("default"))) void NAPI_convertxml_GetJSCode(const char **buf, int *bufLen) { if (buf != nullptr) { *buf = _binary_js_convertxml_js_start; } if (bufLen != nullptr) { *bufLen = _binary_js_convertxml_js_end - _binary_js_convertxml_js_start; } } extern "C" __attribute__((visibility("default"))) void NAPI_convertxml_GetABCCode(const char** buf, int* buflen) { if (buf != nullptr) { *buf = _binary_convertxml_abc_start; } if (buflen != nullptr) { *buflen = _binary_convertxml_abc_end - _binary_convertxml_abc_start; } } static napi_module convertXmlModule = { .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = ConvertXmlInit, .nm_modname = "ConvertXML", .nm_priv = ((void*)0), .reserved = { 0 }, }; extern "C" __attribute__ ((constructor)) void RegisterModule() { napi_module_register(&convertXmlModule); } } // namespace
38.362205
119
0.609811
456984dafd290502cd6b7fbbd63266164f802149
202
cpp
C++
Backbone/UserManager/XMLManager/main.cpp
ed-quiroga-2103/OdisseyC
cf7ec95c574bfd4b2581f9af092dae50803dcebb
[ "Apache-2.0" ]
null
null
null
Backbone/UserManager/XMLManager/main.cpp
ed-quiroga-2103/OdisseyC
cf7ec95c574bfd4b2581f9af092dae50803dcebb
[ "Apache-2.0" ]
null
null
null
Backbone/UserManager/XMLManager/main.cpp
ed-quiroga-2103/OdisseyC
cf7ec95c574bfd4b2581f9af092dae50803dcebb
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "pugixml.hpp" #include "string" #include "XMLParts.h" #include "XMLManager.h" using document = pugi::xml_document; using string = std::string; int main() { return 0; }
16.833333
36
0.70297
456ce2aad5fd617a5ed86fc8916b091e371316e3
423
cpp
C++
cph/modbus/mbqueue.cpp
Loggi-pro/cph-lib
4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67
[ "MIT" ]
null
null
null
cph/modbus/mbqueue.cpp
Loggi-pro/cph-lib
4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67
[ "MIT" ]
null
null
null
cph/modbus/mbqueue.cpp
Loggi-pro/cph-lib
4109dd1d3cc780c9f76aa54c2322bbdcbfdfea67
[ "MIT" ]
null
null
null
#include "mbqueue.h" void ModbusEventQueue::init() { _isEventInQueue = false; } bool ModbusEventQueue::postEvent(MBEventType eEvent) { _isEventInQueue = true; _queuedEvent = eEvent; return true; } bool ModbusEventQueue::getEvent(MBEventType* eEvent) { bool isEventHappened = false; if (_isEventInQueue) { *eEvent = _queuedEvent; _isEventInQueue = false; isEventHappened = true; } return isEventHappened; }
19.227273
54
0.747045
456cee28cc1d1ab23a90b671f5ab734025642346
1,778
cpp
C++
examples/HelloWorld/HelloWorld.cpp
SteveDeFacto/ovgl
879899f63f0dc399e2823dd84bb715fda3aafb78
[ "Apache-2.0" ]
3
2019-02-24T23:17:49.000Z
2020-05-03T09:05:49.000Z
examples/HelloWorld/HelloWorld.cpp
SteveDeFacto/ovgl
879899f63f0dc399e2823dd84bb715fda3aafb78
[ "Apache-2.0" ]
null
null
null
examples/HelloWorld/HelloWorld.cpp
SteveDeFacto/ovgl
879899f63f0dc399e2823dd84bb715fda3aafb78
[ "Apache-2.0" ]
null
null
null
/** * @file HelloWorld.cpp * Copyright 2011 Steven Batchelor * * 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. * @brief None. */ #include <Ovgl.h> Ovgl::Context* context; Ovgl::RenderTarget* render_target; Ovgl::Window* window; Ovgl::ResourceManager* resources; Ovgl::Texture* texture1; Ovgl::Interface* interface1; Ovgl::Font* font1; int main() { // Create Main Context context = new Ovgl::Context( 0 ); // Create Window window = new Ovgl::Window( context, "Hello World!", 320, 240); // Create Render Target render_target = new Ovgl::RenderTarget( context, window, Ovgl::URect( 0.0f, 0.0f, 1.0f, 1.0f ), 0 ); // Create Resource Manager resources = new Ovgl::ResourceManager(context, ""); // Create an interface interface1 = new Ovgl::Interface( render_target, Ovgl::URect( 0.0f, 0.0f, 1.0f, 1.0f ) ); // Load a font font1 = new Ovgl::Font(resources, "../../media/fonts/ArchitectsDaughter.ttf", 48); // Set interface font interface1->font = font1; // Set the interface text interface1->setText("Hello World!"); // Start main loop context->start(); // Release all delete context; // No errors happend so return zero return 0; }
27.78125
105
0.663105
456d9b8f021d8459aaea5b9c07ffd93e2d8a506f
738
hpp
C++
src/cpp/iir-filter-node.hpp
node-3d/waa-raub
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
17
2018-10-03T00:44:33.000Z
2022-03-17T06:40:15.000Z
src/cpp/iir-filter-node.hpp
raub/node-waa
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
7
2019-07-16T08:22:31.000Z
2021-11-29T21:45:06.000Z
src/cpp/iir-filter-node.hpp
raub/node-waa
e458d76f290b1e12ef2a0adc063b521816337f04
[ "MIT" ]
2
2019-08-05T20:00:42.000Z
2020-03-15T13:25:41.000Z
#ifndef _IIR_FILTER_NODE_HPP_ #define _IIR_FILTER_NODE_HPP_ #include "common.hpp" class IIRFilterNode : public CommonNode { DECLARE_ES5_CLASS(IIRFilterNode, IIRFilterNode); public: ~IIRFilterNode(); explicit IIRFilterNode(const Napi::CallbackInfo &info); static void init(Napi::Env env, Napi::Object exports); static bool isIIRFilterNode(Napi::Object obj); // Destroy an instance from C++ land void _destroy(); protected: IIRFilterNode(); static Napi::FunctionReference _constructor; bool _isDestroyed; private: JS_DECLARE_METHOD(IIRFilterNode, destroy); JS_DECLARE_GETTER(IIRFilterNode, isDestroyed); JS_DECLARE_METHOD(IIRFilterNode, getFrequencyResponse); }; #endif // _IIR_FILTER_NODE_HPP_
17.571429
56
0.768293
456fba303c64e745bee06e191b15a89f770516b4
15,915
cpp
C++
Lambda-Lib-C++/LambdaCalc_SampleExec.cpp
jrandleman/Lambda-Calc-Compilation
488c6d1fbc92d00429aa7eb772df3fd6e0dd92c5
[ "MIT" ]
1
2020-09-14T19:47:13.000Z
2020-09-14T19:47:13.000Z
Lambda-Lib-C++/LambdaCalc_SampleExec.cpp
jrandleman/Lambda-Calc-Compiler
488c6d1fbc92d00429aa7eb772df3fd6e0dd92c5
[ "MIT" ]
null
null
null
Lambda-Lib-C++/LambdaCalc_SampleExec.cpp
jrandleman/Lambda-Calc-Compiler
488c6d1fbc92d00429aa7eb772df3fd6e0dd92c5
[ "MIT" ]
null
null
null
// Author: Jordan Randleman -- LambdaCalc_SampleExec.cpp // => Demo File to Illustrate LambdaCalc.hpp's Capabilities #include <iostream> #include "LambdaCalc.hpp" /** * -:- NAMESPACE LambdaCalc LAMBDAS -:- * => ALL DATA IS IMMUTABLE (CONST) * => ALL LAMBDAS ARE CURRIED ( IE Add(ox1, ox2) => Add(ox1)(ox2) ) * => CAPTURE SCOPE BY _VALUE_ (using [=]) FOR INNER - CURRIED! - LAMBDAS * * !!!!! GENERATE A LIST OF ARBITRARY LENGTH W/O MEMORY ALLOCATION (Push) !!!!! * * NOTATION: * => let N = Church Numeral, B = Fcnal Bool, F1 = Unary Fcn, F2 = Binary Fcn, * F = arbitrary fcn, X = arbitrary data, * L = Fcnal List Data Structure (See More Below) * * ---------------------------------------------------------------------------- * - VISUALIZATION: * ---------------------------------------------------------------------------- * * show(X) => print arbitrary data x to screen + newline * print(X) => print arbitrary data x to screen * * bshow(B) => print fcnal boolean as boolean boolean + newline * bprint(B) => print fcnal boolean as boolean boolean * * nshow(N) => print church numeral as unsigned long long + newline * nprint(N) => print church numeral as unsigned long long * * ---------------------------------------------------------------------------- * - FCNAL BOOLEANS: * ---------------------------------------------------------------------------- * * EXPLANATION: * Fcnal Booleans are Binary Fcns, acting like C++'s Ternary '?:' operator: * => Fcnal 'True' chooses arg1, 'False' chooses arg2 * * BOOLEANS: * => True * => False * * BOOLEAN OPERATIONS: * => Not (B) * => And (B1)(B2) * => Or (B1)(B2) * => Xor (B1)(B2) * => Beq (B1)(B2) => 'B'oolean 'eq'uality, ie xnor * * ---------------------------------------------------------------------------- * - CHURCH-NUMERAL NUMERIC FCNS: * ---------------------------------------------------------------------------- * * EXPLANATION: * N-Fold Compositions of a Fcn (!!! ALL >= Zero Integers !!!): * => IE Zero = a, Once = f(a), Twice = f(f(a)), Thrice = f(f(f(a))), etc * * NUMERALS: * => Zero, Once, Twice, Thrice, Fourfold, Fivefold * => ox0,ox1,ox2,ox3,ox4,ox5,ox6,ox7,ox8,ox9,oxa,oxb,oxc,oxd,oxe,oxf * * COMPARATIVE BOOLEANS: * => Is0 (N) => Equal to 'Zero' * * => Eq (N1)(N2) => Equal-to * => Lt (N1)(N2) => Less Than * => Gt (N1)(N2) => Greater Than * => Leq (N1)(N2) => Less Than Or Equal-to * => Geq (N1)(N2) => Greater Than Or Equal-to * * => IsFactor (N1)(N2) => N1 is a factor of N2 * => Evenp (N) => N is even * => Oddp (N) => N is odd * * ARITHMETIC: * => Add (N1)(N2) => N1 + N2 * => Sub (N1)(N2) => N1 - N2 * => Mult (N1)(N2) => N1 * N2 * => Pow (N1)(N2) => N1 ** N2 * => Div (N1)(N2) => N1 / N2 * => Log (N1)(N2) => log N1 (N2) * * => Succ (N) => Succesor of N, N+1 * => Pred (N) => Predecessor of N, N-1 * * => Factorial (N) => N! (w/o Loops, Recursion, or Mutability!!!) * => NumericSum (N) => Sum (0,N) * => NumericSumRange (N1)(N2) => Sum (N1,N2) * * ---------------------------------------------------------------------------- * - PURELY-FCNAL LIST DATA-STRUCTURE FCNS: * ---------------------------------------------------------------------------- * * CONSTRUCTION (Given List Size): * => ListN(N) (N1) (N2) (N3) (NN) => Returns List size N of the trailing elts * * BASIC ANALYSIS: * => Length (L) => Returns length of L * => Nullp (L) => "Null" 'p'redicate: List is EMPTY * => Pairp (L) => "Pair" 'p'redicate: List is __NOT__ EMPTY * * GETTERS: * => Head (L) => Return L's 1st cell value * => Last (L) => Return L's last cell value * => Nth (N)(L) => Returns L's 'N'th elt (starting from 'ox1') * * SETTERS: * => Insert (N)(X)(L) => Returns List w/ X inserted in L AFTER nth position * => Erase (N)(L) => Returns List w/ L's nth value erased * => Push (X)(L) => Returns List w/ X in front of L * => Pop (L) => Returns List w/o L's Head * => NOTE: "_back" versions may be self-implemented via "Backward" fcn (More Below) * * FILTER/MAP/VOIDMAP: * => Filter (F1)(L) => Returns List having filtered out elts from L __NOT__ passing F1 * => Map (F1)(L) => Returns List having mapped F1 across all of L's elts * => VoidMap (F1)(L) => Returns Void & F1 Must be void => Applie Fcn to each elt in L * (useful for passing a "printer" fcn (ie nshow) to print each elt) * * REVERSED LIST & FCN APPLICATION: * => Reverse (L) => Returns List of L in reverse * => FlipArgs (F2) => Flips args for a Binary Fcn * => Backward (F1)(L) => Returns List having applied F on Reverse(L) * => BackwardAtomic (F1)(L) => Returns Atom (ie Non-List Fcn, such as a * Church Numeral) having applied F on Reverse(L) * ACCUMULATORS: * => Foldl (F2)(X)(L) => Applies F2 on L from 'l'eft to right, * starting w/ 'X' & Head(L) * => Foldr (F2)(X)(L) => Applies F2 on L from 'r'ight to left, * starting w/ 'X' & Last(L) * MAX/MIN: * => Max (L) => Returns Greatest value in List * => Min (L) => Returns Smallest value in List * * LISP-STYLE ACCESS: * => car (L) => Returns Current Cell Value ( IE Head(L) ) * => cdr (L) => Returns Next Cell ( IE Pop(L) ) * => cadr (L) => Head(Pop(L)) * => caddr (L) => Head(Pop(Pop(L))) * => cadddr (L) => Head(Pop(Pop(Pop(L)))) * => ANY combo of 1-4 'a's & 'd's btwn 'c' & 'r' for nested list access! * * ---------------------------------------------------------------------------- * - IF YOU'VE GOTTEN THIS FAR ... * ---------------------------------------------------------------------------- * * You may genuinely enjoy the 2 JS Lambda Calculus videos below, found at: * => Part 1: https://www.youtube.com/watch?v=3VQ382QG-y4&feature=youtu.be * => Part 2: https://www.youtube.com/watch?v=pAnLQ9jwN-E * * In Summary: * => Identity/Once, Idiot: I := \a.a * => First/True/Const, Kestrel: K := \ab.a * => Flip/LogicalNot, Cardinal: C := \fab.fba * => Unary Compose, Bluebird: B := \fga.f(ga) * * => Self-Replication, Mockingbird M := \f.f(f) => IMPOSSIBLE IN HASKELL (Infinite Data Struct) * * => Second/False/Zero, Kite: KI := \ab.b = K I = C K * => Binary Compose, Blackbird: B1 := \fgab.f(gab) = B B B * => Hold An Arg, Thrush: Th := \af.fa = C I * => Hold Arg Pair, Vireo: V := \abf.fab = B C Th = B C (C I) */ /****************************************************************************** * CURRIED FUNCTIONS & LAMBDA CALCULUS EXECUTION C++ ******************************************************************************/ int main() { using namespace LambdaCalc; show("\nUsing Fcnal Booleans:"); print(" => Not(True): "); bshow(Not(True)); print(" => Not(False): "); bshow(Not(False)); print(" => And(True)(False): "); bshow(And(True)(False)); print(" => And(True)(True): "); bshow(And(True)(True)); print(" => And(False)(False): "); bshow(And(False)(False)); print(" => Or(True)(False): "); bshow(Or(True)(False)); print(" => Or(False)(False): "); bshow(Or(False)(False)); print(" => Or(True)(True): "); bshow(Or(True)(True)); print(" => Xor(False)(True): "); bshow(Xor(False)(True)); print(" => Xor(True)(True): "); bshow(Xor(True)(True)); print(" => Xor(False)(False): "); bshow(Xor(False)(False)); print(" => Beq(True)(False): "); bshow(Beq(True)(False)); print(" => Beq(True)(True): "); bshow(Beq(True)(True)); print(" => Beq(False)(False): "); bshow(Beq(False)(False)); show("\n\n\nUsing Church Numerals (0-15 shown as Hex w/ 'o' prefix):"); print(" => Is0(ox5): "); bshow(Is0(ox5)); print(" => Is0(ox0): "); bshow(Is0(ox0)); show(""); print(" => Eq(ox2)(ox8): "); bshow(Eq(ox2)(ox8)); print(" => Eq(ox2)(ox2): "); bshow(Eq(ox2)(ox2)); print(" => Lt(ox2)(ox8): "); bshow(Lt(ox2)(ox8)); print(" => Lt(ox8)(ox2): "); bshow(Lt(ox8)(ox2)); print(" => Lt(ox8)(ox8): "); bshow(Lt(ox8)(ox8)); print(" => Gt(ox2)(ox8): "); bshow(Gt(ox2)(ox8)); print(" => Gt(ox8)(ox2): "); bshow(Gt(ox8)(ox2)); print(" => Gt(ox8)(ox8): "); bshow(Gt(ox8)(ox8)); print(" => Leq(ox2)(ox8): "); bshow(Leq(ox2)(ox8)); print(" => Leq(ox8)(ox2): "); bshow(Leq(ox8)(ox2)); print(" => Leq(ox8)(ox8): "); bshow(Leq(ox8)(ox8)); print(" => Geq(ox2)(ox8): "); bshow(Geq(ox2)(ox8)); print(" => Geq(ox8)(ox2): "); bshow(Geq(ox8)(ox2)); print(" => Geq(ox8)(ox8): "); bshow(Geq(ox8)(ox8)); show(""); print(" => IsFactor(ox3)(oxc): "); bshow(IsFactor(ox2)(ox4)); print(" => IsFactor(ox3)(oxd): "); bshow(IsFactor(ox2)(ox7)); print(" => Evenp(ox6): "); bshow(Evenp(ox6)); print(" => Evenp(ox9): "); bshow(Evenp(ox9)); print(" => Oddp(ox6): "); bshow(Oddp(ox6)); print(" => Oddp(ox9): "); bshow(Oddp(ox9)); show(""); print(" => Add(oxf)(oxa): "); nshow(Add(oxf)(oxa)); print(" => Sub(oxb)(ox6): "); nshow(Sub(oxb)(ox6)); print(" => Mult(ox3)(ox7): "); nshow(Mult(ox3)(ox7)); print(" => Pow(ox2)(ox5): "); nshow(Pow(ox2)(ox5)); print(" => Div(Mult(ox2)(oxa))(ox4): "); nshow(Div(Mult(ox2)(oxa))(ox4)); print(" => Log(ox2)(ox8): "); nshow(Log(ox2)(ox8)); show(""); print(" => Succ(ox8): "); nshow(Succ(ox8)); print(" => Pred(ox8): "); nshow(Pred(ox8)); show(""); print(" => Factorial(ox5): "); nshow(Factorial(ox5)); print(" => NumericSum(oxa): "); nshow(NumericSum(oxa)); print(" => NumericSumRange(ox5)(oxa): "); nshow(NumericSumRange(ox5)(oxa)); show("\n\n\nUsing The Purely-Fcnal \"ListN\" Data Structure:"); show(" => We have defined 2 lists:"); show(" (1) List of 5 Church Numerals:"); show(" List1 = ListN(ox5) (ox9) (ox4) (ox7) (ox3) (oxa);"); const auto List1 = ListN(ox5) (ox9) (ox4) (ox7) (ox3) (oxa); show(" (2) Empty List:"); show(" List2 = ListN(ox0);"); const auto List2 = ListN(ox0); show("\nBASIC ANALYSIS:"); print(" => Length(List1): "); nshow(Length(List1)); print(" => Length(List2): "); nshow(Length(List2)); show(" => Whether list IS or IS NOT empty:"); print(" - Nullp(List1): "); bshow(Nullp(List1)); print(" - Nullp(List2): "); bshow(Nullp(List2)); print(" - Pairp(List1): "); bshow(Pairp(List1)); print(" - Pairp(List2): "); bshow(Pairp(List2)); show("\nGETTERS:"); print(" => Head(List1): "); nshow(Head(List1)); print(" => Last(List1): "); nshow(Last(List1)); print(" => Nth(ox1)(List1): "); nshow(Nth(ox1)(List1)); print(" => Nth(ox2)(List1): "); nshow(Nth(ox2)(List1)); print(" => Nth(ox3)(List1): "); nshow(Nth(ox3)(List1)); print(" => Nth(ox4)(List1): "); nshow(Nth(ox4)(List1)); print(" => Nth(ox5)(List1): "); nshow(Nth(ox5)(List1)); show("\nSETTERS:"); print(" => Length(Push(oxd)(List1)): "); nshow(Length(Push(oxd)(List1))); print(" => Head(Push(oxd)(List1)): "); nshow(Head(Push(oxd)(List1))); print(" => Length(Pop(List1)): "); nshow(Length(Pop(List1))); print(" => Head(Pop(List1)): "); nshow(Head(Pop(List1))); print(" => Length(Push(oxf)(List2)): "); nshow(Length(Push(oxf)(List2))); print(" => Head(Push(oxf)(List2)): "); nshow(Head(Push(oxf)(List2))); print(" => Length(Pop(Push(oxf)(List2))): "); nshow(Length(Pop(Push(oxf)(List2)))); print(" => Erase(ox3)(List1) = "); VoidMap(nprint)(Erase(ox3)(List1)); print("\n => Insert(ox3)(oxc)(List1) = "); VoidMap(nprint)(Insert(ox3)(oxc)(List1)); show(""); show("\nFILTER/MAP/VOIDMAP:"); show(" => We have defined more 2 lists:"); show(" (1) List of odd Church Numerals from List1:"); show(" OnlyOdds = Filter(Oddp)(List1);"); const auto OnlyOdds = Filter(Oddp)(List1); show(" (2) List of 2 raised to each value in List1:"); show(" PowersOf2 = Map(Pow(ox2))(List1);\n"); const auto PowersOf2 = Map(Pow(ox2))(List1); show(" => Using \"VoidMap\" to map a Void printer fcn across these Lists:"); show(" (*) NOTE: \"nprint()\" = void lambda to print Church Numerals as ints!"); print(" (1) VoidMap(nprint)(OnlyOdds) = "); VoidMap(nprint)(OnlyOdds); show(""); print(" (2) VoidMap(nprint)(PowersOf2) = "); VoidMap(nprint)(PowersOf2); show("\n\nREVERSED LIST & REVERSED FCN APPLICATION:"); print(" => List1 = "); VoidMap(nprint)(List1); print("\n => Reverse(List1) = "); VoidMap(nprint)(Reverse(List1)); print("\n => Pow(ox2)(ox3) = "); nshow(Pow(ox2)(ox3)); print(" => FlipArgs(Pow)(ox2)(ox3) = "); nshow(FlipArgs(Pow)(ox2)(ox3)); print(" => Push(oxf)(List1) = "); VoidMap(nprint)(Push(oxf)(List1)); print("\n => Backward(Push(oxf))(List1) = "); VoidMap(nprint)(Backward(Push(oxf))(List1)); show("\n => We have defined 1 more List: List3 = ListN(ox2) (ox2)(ox3);"); const auto List3 = ListN(ox2) (ox2)(ox3); print(" -> Foldl(Pow)(ox1)(List3) = "); nprint(Foldl(Pow)(ox1)(List3)); print("\n -> BackwardAtomic(Foldl(Pow)(ox1))(List3) = "); nshow(BackwardAtomic(Foldl(Pow)(ox1))(List3)); show("\nACCUMULATORS:"); show(" => Both Accumulators have already been shown, 1 more subtly so:"); print(" -> Foldl(Pow)(ox1)(List3) = "); nshow(Foldl(Pow)(ox1)(List3)); print(" -> Foldr(Pow)(ox1)(List3) = "); nprint(Foldr(Pow)(ox1)(List3)); show(" // \"Foldr\" = \"BackwardAtomic\" . \"Foldl\"!"); show("\nMAX/MIN:"); print(" => Max(List1) = "); nshow(Max(List1)); print(" => Min(List1) = "); nshow(Min(List1)); show("\nLISP-STYLE ACCESS:"); print(" => List1 = "); VoidMap(nprint)(List1); print("\n => car(List1) = "); nshow(car(List1)); print(" => cdr(List1) = "); VoidMap(nprint)(cdr(List1)); print("\n => cadr(List1) = "); nshow(cadr(List1)); print(" => caddr(List1) = "); nshow(caddr(List1)); print(" => cadddr(List1) = "); nshow(cadddr(List1)); show("\nLISTS OF LISTS:"); const auto SuperList1 = ListN(ox3) (ListN(ox2) (ox4) (ox5)) (ListN(ox3) (oxa) (ox2) (ox3)) (ListN(ox1) (ox8)); show(" => We have defined a list of 3 lists:"); show(" (*) // SuperList1 = [ [4, 5], [10, 2, 3], [8] ]"); show(" (0) SuperList1 = ListN(ox3) (ListN(ox2) (ox4) (ox5)) (ListN(ox3) (oxa) (ox2) (ox3)) (ListN(ox1) (ox8));\n"); print(" => Head(Head(SuperList1)) = "); nshow(Head(Head(SuperList1))); print(" => Last(Last(SuperList1)) = "); nshow(Last(Last(SuperList1))); print(" => Nth(ox1)(Nth(ox2)(SuperList1)) = "); nshow(Nth(ox1)(Nth(ox2)(SuperList1))); show(" => Using LISP Notation:"); print(" -> caar(SuperList1) = "); nshow(caar(SuperList1)); print(" -> caaddr(SuperList1) = "); nshow(caaddr(SuperList1)); print(" -> caadr(SuperList1) = "); nshow(caadr(SuperList1)); show("\nLIST OF MULTIPLE-TYPED ELTS:"); show(" => We have defined a list w/ a float, String, & Church Numeral:"); show(" (0) multi_type_list = ListN(ox3) (3.14159) (\"Talk about dynamic!\") (oxd);"); const auto multi_type_list = ListN(ox3) (3.14159) ("Talk about dynamic!") (oxd); print("\n => car(multi_type_list) = "); show(car(multi_type_list)); print(" => cadr(multi_type_list) = "); show(cadr(multi_type_list)); print(" => caddr(multi_type_list) = "); nshow(caddr(multi_type_list)); show("\nBye!\n"); return 0; }
35.13245
121
0.507823
45718afe4218efca271bb3f57bd98b4aa166ec63
503
cpp
C++
src/format.cpp
zyntop2014/CppND-System-Monitor-yananzhang-solution
57a6173e73a23646b697da45f7bec2823300a8f7
[ "MIT" ]
null
null
null
src/format.cpp
zyntop2014/CppND-System-Monitor-yananzhang-solution
57a6173e73a23646b697da45f7bec2823300a8f7
[ "MIT" ]
null
null
null
src/format.cpp
zyntop2014/CppND-System-Monitor-yananzhang-solution
57a6173e73a23646b697da45f7bec2823300a8f7
[ "MIT" ]
null
null
null
#include <string> #include "format.h" using std::string; using std::to_string; // TODO: Complete this helper function // INPUT: Long int measuring seconds // OUTPUT: HH:MM:SS // REMOVE: [[maybe_unused]] once you define the function string Format::ElapsedTime(long seconds) { int hour = seconds / 3600; int rest_seconds = seconds % 3600; int minutes = rest_seconds / 60; int secs = rest_seconds % 60; return to_string(hour) + ":" + to_string(minutes) + ":" + to_string(secs); }
26.473684
79
0.677932
45774a243eba9339b1d84de55198c4399b64d3f2
954
hpp
C++
main/inou_rand_api.hpp
tamim-asif/lgraph-private
733bbcd9e14a9850580b51c011e33785ab758b9d
[ "BSD-3-Clause" ]
null
null
null
main/inou_rand_api.hpp
tamim-asif/lgraph-private
733bbcd9e14a9850580b51c011e33785ab758b9d
[ "BSD-3-Clause" ]
null
null
null
main/inou_rand_api.hpp
tamim-asif/lgraph-private
733bbcd9e14a9850580b51c011e33785ab758b9d
[ "BSD-3-Clause" ]
null
null
null
#include "inou_rand.hpp" #include "main_api.hpp" class Inou_rand_api { protected: static void tolg(Eprp_var &var) { Inou_rand rand; for(const auto &l:var.dict) { rand.set(l.first,l.second); } std::vector<LGraph *> lgs = rand.tolg(); if (lgs.empty()) { Main_api::warn(fmt::format("inou.rand could not create a random {} lgraph in {} path", var.get("name"), var.get("path"))); }else{ assert(lgs.size()==1); // rand only generated one graph at a time var.add(lgs[0]); } } public: static void setup(Eprp &eprp) { Eprp_method m1("inou.rand", "generate a random lgraph", &Inou_rand_api::tolg); m1.add_label_optional("path","lgraph path"); m1.add_label_required("name","lgraph name"); m1.add_label_optional("seed","random seed"); m1.add_label_optional("size","lgraph size"); m1.add_label_optional("eratio","edge ratio for random"); eprp.register_method(m1); } };
24.461538
128
0.638365
457799f6c60e7d7a5d1685b8781ec801a174ca43
3,127
hpp
C++
GameEngine/Systems/ButtonSystem.hpp
Epitech-Tek2/superBonobros2
525ab414215f5b67829bf200797c2055141cb7b9
[ "MIT" ]
null
null
null
GameEngine/Systems/ButtonSystem.hpp
Epitech-Tek2/superBonobros2
525ab414215f5b67829bf200797c2055141cb7b9
[ "MIT" ]
null
null
null
GameEngine/Systems/ButtonSystem.hpp
Epitech-Tek2/superBonobros2
525ab414215f5b67829bf200797c2055141cb7b9
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2020 ** B-CPP-501-STG-5-1-rtype-romuald1.soultan ** File description: ** ButtonSystem */ #ifndef BUTTONSYSTEM_HPP_ #define BUTTONSYSTEM_HPP_ #include "ASystem.hpp" #include "ECS.hpp" #include "AScene.hpp" #include "AGame.hpp" #include "ASystem.hpp" #include "ClickableComponent.hpp" #include "ShapeComponent.hpp" #include "Transform2DComponent.hpp" #include "BaseColorComponent.hpp" #include "TextureComponent.hpp" #include "ButtonActionComponent.hpp" namespace gameEngine { class ButtonSystem : public gameEngine::ASystem { public: ButtonSystem(gameEngine::ECS *ecs) : gameEngine::ASystem(ecs) {} void init(gameEngine::ECS *ecs) { ecs->systemAddDependances<gameEngine::ClickableComponent>(this); ecs->systemAddDependances<gameEngine::TextureComponent>(this); ecs->systemAddDependances<gameEngine::ShapeComponent>(this); ecs->systemAddDependances<gameEngine::Transform2DComponent>(this); ecs->systemAddDependances<gameEngine::BaseColorComponent>(this); ecs->systemAddDependances<gameEngine::ButtonActionComponent>(this); } ~ButtonSystem(void) = default; private: void action(std::shared_ptr<gameEngine::AEntity> entity, float) { Color const &baseColor = _ecs->getEntityComponent<gameEngine::BaseColorComponent>(entity)._color; Color &color = _ecs->getEntityComponent<gameEngine::TextureComponent>(entity)._color; ClickableComponent::MouseState const state = _ecs->getEntityComponent<gameEngine::ClickableComponent>(entity).state; ButtonActionComponent &action = _ecs->getEntityComponent<gameEngine::ButtonActionComponent>(entity); short red = 0; short green = 0; short blue = 0; switch (state) { case ClickableComponent::MouseState::OnButton: red = baseColor.red - 30; green = baseColor.green - 30; blue = baseColor.blue - 30; color.red = (red < 0 ? 0:red); color.green = (green < 0 ? 0:green); color.blue = (blue < 0 ? 0:blue); break; case ClickableComponent::MouseState::HoldClick: red = baseColor.red - 60; green = baseColor.green - 60; blue = baseColor.blue - 60; color.red = (red < 0 ? 0:red); color.green = (green < 0 ? 0:green); color.blue = (blue < 0 ? 0:blue); break; case ClickableComponent::MouseState::Released: action._action(); break; default: color = baseColor; break; } } }; } #endif /* !BUTTONSYSTEM_HPP_ */
39.582278
132
0.549089
4577c52083767b5b1ed8420cedc7326e012220ed
875
cpp
C++
coast/modules/Renderer/SubStringRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Renderer/SubStringRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Renderer/SubStringRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "SubStringRenderer.h" RegisterRenderer(SubStringRenderer); void SubStringRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config) { StartTrace(SubStringRenderer.RenderAll); String str; Renderer::RenderOnString(str, ctx, config["String"]); if (str.Length()) { long start = RenderToString(ctx, config["Start"]).AsLong(0L); long len = RenderToString(ctx, config["Length"]).AsLong(-1L); String ret(str.SubString(start, len)); Trace("SubString(" << start << "," << len << ")-->" << ret); reply << ret; } }
38.043478
102
0.718857
4578b38a6b3f01fa80365cd43053e30c3d4c7513
65
cpp
C++
cpp_data_structure_and_algorithm/day9/IndexMaxHeap.cpp
xcyi2017/Agorithm
bae9918b0758624ecd1f94a3ca1692050c193a29
[ "Apache-2.0" ]
1
2020-11-15T09:40:47.000Z
2020-11-15T09:40:47.000Z
cpp_data_structure_and_algorithm/day9/IndexMaxHeap.cpp
xcyi2017/Agorithm
bae9918b0758624ecd1f94a3ca1692050c193a29
[ "Apache-2.0" ]
null
null
null
cpp_data_structure_and_algorithm/day9/IndexMaxHeap.cpp
xcyi2017/Agorithm
bae9918b0758624ecd1f94a3ca1692050c193a29
[ "Apache-2.0" ]
null
null
null
// // Created by xcy on 2020/10/5. // #include "IndexMaxHeap.h"
10.833333
31
0.630769
457bc8521fdebe0808d93f1cd867ad9f31f5b80e
835
cpp
C++
CameraShake/MyCameraShake.cpp
H4DC0R3/unrealcpp
b0f5667cb20711d740a6fb0cb5064efc6873c948
[ "MIT" ]
765
2018-01-03T14:58:37.000Z
2022-03-29T16:03:13.000Z
CameraShake/MyCameraShake.cpp
shyaZhou/unrealcpp
e998d89ce6c8d5484c084f395d2eca5e247b88bf
[ "MIT" ]
1
2019-09-26T09:33:50.000Z
2020-12-11T05:17:13.000Z
CameraShake/MyCameraShake.cpp
shyaZhou/unrealcpp
e998d89ce6c8d5484c084f395d2eca5e247b88bf
[ "MIT" ]
166
2018-02-20T07:36:12.000Z
2022-03-25T07:49:03.000Z
// Harrison McGuire // UE4 Version 4.20.2 // https://github.com/Harrison1/unrealcpp // https://severallevels.io // https://harrisonmcguire.com #include "MyCameraShake.h" // Helpful Links // http://api.unrealengine.com/INT/API/Runtime/Engine/Camera/UCameraShake/index.html // // Great explanation of camera shake values // https://www.youtube.com/watch?v=Oice8gdpX6s #include "MyCameraShake.h" // Sets default values UMyCameraShake::UMyCameraShake() { OscillationDuration = 0.25f; OscillationBlendInTime = 0.05f; OscillationBlendOutTime = 0.05f; RotOscillation.Pitch.Amplitude = FMath::RandRange(5.0f, 10.0f); RotOscillation.Pitch.Frequency = FMath::RandRange(25.0f, 35.0f); RotOscillation.Yaw.Amplitude = FMath::RandRange(5.0f, 10.0f); RotOscillation.Yaw.Frequency = FMath::RandRange(25.0f, 35.0f); }
27.833333
84
0.731737
457bd37fec85e9482385200325361d5c389ea414
10,188
cpp
C++
src/main.cpp
cabletie/Ugo-ESP32
6fde7568cbf2c388661a71e07b7887e5e9744b9d
[ "Apache-2.0" ]
7
2020-07-10T21:00:22.000Z
2022-02-21T07:55:02.000Z
src/main.cpp
cabletie/Ugo-ESP32
6fde7568cbf2c388661a71e07b7887e5e9744b9d
[ "Apache-2.0" ]
16
2020-04-05T00:02:59.000Z
2020-08-15T17:16:48.000Z
src/main.cpp
cabletie/Ugo-ESP32
6fde7568cbf2c388661a71e07b7887e5e9744b9d
[ "Apache-2.0" ]
2
2020-08-16T10:57:09.000Z
2022-01-23T18:04:53.000Z
/* Copyright 2020 Marco Massarelli 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 <Arduino.h> #include <TinyPICO.h> #include "main.h" // Initialise the TinyPICO library TinyPICO tp = TinyPICO(); uint8_t deviceMode = NORMAL_MODE; uint8_t button; bool otaModeStarted = false; volatile bool ledState = false; // TIMERS unsigned long otaMillis, ledMillis, configTimer, otaTimer; byte mac[6]; AsyncWebServer server(80); byte dnsPort = 53; DNSServer dnsServer; WiFiClient espClientInsecure; PubSubClient mqttClientInsecure(espClientInsecure); WiFiClientSecure espClientSecure; PubSubClient mqttClientSecure(espClientSecure); DynamicJsonDocument json(2048); // config buffer /* You only need to format SPIFFS the first time you run a test or else use the SPIFFS plugin to create a partition https://github.com/me-no-dev/arduino-esp32fs-plugin */ #define FORMAT_SPIFFS_IF_FAILED false // false //#define BUTTON_PIN_BITMASK 0x300000000 // 2^33 in hex // 10 // Pin 4 // 4000 // Pin 14 // 8000 // Pin 15 // 2000000 // Pin 25 // 4000000 // Pin 26 // 8000000 // Pin 27 // 100000000 // Pin 32 // 200000000 // Pin 33 //#define BUTTON_PIN_BITMASK 0x00800C010 // 4 + 14 + 15 + 27 //#define BUTTON_PIN_BITMASK 0x308000010 // 4 + 33 + 32 + 27 #define BUTTON_PIN_BITMASK 0x00E000010 // 4 + 25 + 26 + 27 #include "actions.h" #include "config_portal.h" #include "ota.h" #include "hass_register.h" void setup() { Serial.begin(115200); Serial.println(""); #if CORE_DEBUG_LEVEL == 5 printWakeupReason(); printResetReason(); batteryPercentage(); #endif #if ENABLE_PCB_LED ledcSetup(RED_LED_PWM_CHANNEL, PWM_FREQUENCY, PWM_RESOLUTION); ledcAttachPin(RED_LED_PIN, RED_LED_PWM_CHANNEL); GPIO.func_out_sel_cfg[RED_LED_PIN].inv_sel = INVERT_LED_PWM_SENSE; #ifdef ENABLE_V_0_2_PCB_LED_FIX pinMode(COMMON_ANODE_PIN, OUTPUT); digitalWrite(COMMON_ANODE_PIN, LOW); // Power off #else ledcSetup(GREEN_LED_PWM_CHANNEL, PWM_FREQUENCY, PWM_RESOLUTION); ledcAttachPin(GREEN_LED_PIN, GREEN_LED_PWM_CHANNEL); GPIO.func_out_sel_cfg[GREEN_LED_PIN].inv_sel = INVERT_LED_PWM_SENSE; #endif ledcSetup(BLUE_LED_PWM_CHANNEL, PWM_FREQUENCY, PWM_RESOLUTION); ledcAttachPin(BLUE_LED_PIN, BLUE_LED_PWM_CHANNEL); GPIO.func_out_sel_cfg[BLUE_LED_PIN].inv_sel = INVERT_LED_PWM_SENSE; #endif // Go to sleep immediately if woke up for something not related to deep sleep if (esp_reset_reason() != ESP_RST_DEEPSLEEP) { Serial.println("Skipping button detection."); blinkResetReason(); goToSleep(); } // Prepare the pins pinMode(button1_pin, INPUT); pinMode(button2_pin, INPUT); pinMode(button3_pin, INPUT); pinMode(button4_pin, INPUT); // This small delay is required for correct button detection delay(10); button = readButtons(); if (!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)) { if (!SPIFFS.begin()) { Serial.println("SPIFFS Mount Failed :: Needs formatting?"); return; } if (FORMAT_SPIFFS_IF_FAILED) { Serial.println("SPIFFS Mount Failed :: FORMATTING"); } } WiFi.macAddress(mac); readConfig(); const char *ssid = json["id"].as<const char *>(); const char *pass = json["pw"].as<const char *>(); const char *ip = json["ip"].as<const char *>(); const char *gw = json["gw"].as<const char *>(); const char *sn = json["sn"].as<const char *>(); const char *d1 = json["d1"].as<const char *>(); const char *d2 = json["d2"].as<const char *>(); if (json["id"] != "" && json["pw"] != "") { WiFi.mode(WIFI_STA); IPAddress ip_address, gateway_ip, subnet_mask, dns_address_1, dns_address_2; if (ip[0] != '\0' && ip_address.fromString(String(ip)) && gw[0] != '\0' && gateway_ip.fromString(String(gw)) && sn[0] != '\0' && subnet_mask.fromString(String(sn))) { if (d1[0] != '\0' && dns_address_1.fromString(String(d1))) { if (d2[0] != '\0' && dns_address_2.fromString(String(d2))) { if (WiFi.config(ip_address, gateway_ip, subnet_mask, dns_address_1, dns_address_2)) { Serial.println("STA successfully configured with IP, Gateway, Subnet, Primary DNS, Secondary DNS."); } else { Serial.println("STA failed to configure with IP, Gateway, Subnet, Primary DNS, Secondary DNS. Using auto config instead."); Serial.println("[ip]: " + String(ip)); Serial.println("[gw]: " + String(gw)); Serial.println("[sn]: " + String(sn)); Serial.println("[d1]: " + String(d1)); Serial.println("[d2]: " + String(d2)); } } else { if (WiFi.config(ip_address, gateway_ip, subnet_mask, dns_address_1)) { Serial.println("STA successfully configured with IP, Gateway, Subnet, Primary DNS."); } else { Serial.println("STA failed to configure with IP, Gateway, Subnet, Primary DNS. Using auto config instead."); Serial.println("[ip]: " + String(ip)); Serial.println("[gw]: " + String(gw)); Serial.println("[sn]: " + String(sn)); Serial.println("[d1]: " + String(d1)); } } } else { if (WiFi.config(ip_address, gateway_ip, subnet_mask)) { Serial.println("STA successfully configured with IP, Gateway, Subnet."); } else { Serial.println("STA failed to configure with IP, Gateway, Subnet. Using auto config instead."); Serial.println("[ip]: " + String(ip)); Serial.println("[gw]: " + String(gw)); Serial.println("[sn]: " + String(sn)); } } } else { Serial.println("Failed to configure static IP."); Serial.println("[ip]: " + String(ip)); Serial.println("[gw]: " + String(gw)); Serial.println("[sn]: " + String(sn)); } WiFi.begin(ssid, pass); for (int i = 0; i < 50; i++) { if (WiFi.status() != WL_CONNECTED) { if (i > 40) { deviceMode = CONFIG_MODE; Serial.print("Failed to connect to: "); Serial.println(ssid); break; } delay(100); } else { Serial.println("Wifi connected..."); Serial.print("SSID: "); Serial.println(WiFi.SSID()); Serial.print("Mac address: "); Serial.println(WiFi.macAddress()); Serial.print("IP: "); Serial.println(WiFi.localIP()); break; } } } else { deviceMode = CONFIG_MODE; Serial.println("No credentials set, going to config mode"); } String ota_name = OTA_NAME + macLastThreeSegments(mac); ArduinoOTA.setHostname(ota_name.c_str()); ArduinoOTA.onStart([]() { Serial.println("OTA UPLOAD STARTED..."); setLedColor(0, 0, 255); }); } void loop() { // Detect button combo to enter config mode toggleConfigMode(); if (deviceMode == CONFIG_MODE) { Serial.println("STARTING CONFIG ACCESS POINT..."); setLedColor(255, 255, 0); startConfigPortal(); Serial.println("RETURNING TO NORMAL MODE..."); deviceMode = NORMAL_MODE; return; } // Detect button combo to enter Hass.io register mode toggleHassRegisterMode(); if (deviceMode == HASS_REGISTER_MODE) { Serial.println("REGISTERING WITH HASS.IO..."); setLedColor(255, 0, 255); startHassRegister(); Serial.println("RETURNING TO NORMAL MODE..."); deviceMode = NORMAL_MODE; return; } // Detect button combo to enter OTA mode toggleOTAMode(); if (deviceMode == OTA_MODE) { Serial.println("WAITING FOR OTA UPDATE..."); setLedColor(0, 255, 255); startOTA(); Serial.println("RETURNING TO NORMAL MODE..."); deviceMode = NORMAL_MODE; return; } if (deviceMode != NORMAL_MODE) return; handleButtonAction(); switch (button) { case 1: setLedColor(255, 0, 0); break; case 2: setLedColor(0, 255, 0); break; case 3: setLedColor(0, 0, 255); break; case 4: setLedColor(0, 255, 255); break; case 5: setLedColor(255, 0, 255); break; case 6: setLedColor(255, 255, 0); break; case 7: setLedColor(255, 255, 255); break; default: break; } if (json["ha_enabled"].as<bool>()) { publishDeviceState(); } goToSleep(); }
30.872727
147
0.550452
4584d9705bc128ecf32ee9da4ab82849fdd83607
2,241
hpp
C++
falcon/mpl/placeholders.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
2
2018-02-02T14:19:59.000Z
2018-05-13T02:48:24.000Z
falcon/mpl/placeholders.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
falcon/mpl/placeholders.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
#ifndef FALCON_MPL_PLACEHOLDERS_HPP #define FALCON_MPL_PLACEHOLDERS_HPP #include <falcon/mpl/arg.hpp> namespace falcon { namespace mpl { namespace placeholders { using _1 = arg<1>; using _2 = arg<2>; using _3 = arg<3>; using _4 = arg<4>; using _5 = arg<5>; using _6 = arg<6>; using _7 = arg<7>; using _8 = arg<8>; using _9 = arg<9>; using _10 = arg<10>; using _11 = arg<11>; using _12 = arg<12>; using _13 = arg<13>; using _14 = arg<14>; using _15 = arg<15>; using _16 = arg<16>; using _17 = arg<17>; using _18 = arg<18>; using _19 = arg<19>; using _20 = arg<20>; using _21 = arg<21>; using _22 = arg<22>; using _23 = arg<23>; using _24 = arg<24>; using _25 = arg<25>; using _26 = arg<26>; using _27 = arg<27>; using _28 = arg<28>; using _29 = arg<29>; using _30 = arg<30>; using _31 = arg<31>; using _32 = arg<32>; using _33 = arg<33>; using _34 = arg<34>; using _35 = arg<35>; using _36 = arg<36>; using _37 = arg<37>; using _38 = arg<38>; using _39 = arg<39>; using _40 = arg<40>; using _41 = arg<41>; using _42 = arg<42>; using _43 = arg<43>; using _44 = arg<44>; using _45 = arg<45>; using _46 = arg<46>; using _47 = arg<47>; using _48 = arg<48>; using _49 = arg<49>; using _50 = arg<50>; using _51 = arg<51>; using _52 = arg<52>; using _53 = arg<53>; using _54 = arg<54>; using _55 = arg<55>; using _56 = arg<56>; using _57 = arg<57>; using _58 = arg<58>; using _59 = arg<59>; using _60 = arg<60>; using _61 = arg<61>; using _62 = arg<62>; using _63 = arg<63>; using _64 = arg<64>; using _65 = arg<65>; using _66 = arg<66>; using _67 = arg<67>; using _68 = arg<68>; using _69 = arg<69>; using _70 = arg<70>; using _71 = arg<71>; using _72 = arg<72>; using _73 = arg<73>; using _74 = arg<74>; using _75 = arg<75>; using _76 = arg<76>; using _77 = arg<77>; using _78 = arg<78>; using _79 = arg<79>; using _80 = arg<80>; using _81 = arg<81>; using _82 = arg<82>; using _83 = arg<83>; using _84 = arg<84>; using _85 = arg<85>; using _86 = arg<86>; using _87 = arg<87>; using _88 = arg<88>; using _89 = arg<89>; using _90 = arg<90>; using _91 = arg<91>; using _92 = arg<92>; using _93 = arg<93>; using _94 = arg<94>; using _95 = arg<95>; using _96 = arg<96>; using _97 = arg<97>; using _98 = arg<98>; using _99 = arg<99>; } } } #endif
19.486957
35
0.629183
4586a2f0f7b631495373c018c934fe3720aeba6d
2,998
cc
C++
sieve2015/src/presieved_primes.cc
mhdeleglise/Gh
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
[ "MIT" ]
null
null
null
sieve2015/src/presieved_primes.cc
mhdeleglise/Gh
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
[ "MIT" ]
null
null
null
sieve2015/src/presieved_primes.cc
mhdeleglise/Gh
21a0b9bd53ae9de17f8b99040cac95cd6e1897e4
[ "MIT" ]
null
null
null
#include<mylib.h> namespace presieved_primes{ long32 presieve_base; long32 number_of_presieve_primes; long32 sum_of_presieve_primes; long32 small_primes[5] = {2, 3, 5, 7, 11}; int primes_initialized = 0; long* Sp; void init_presieve(int nbps) { switch (nbps) { case 2: presieve_base = 6; number_of_presieve_primes = 2; sum_of_presieve_primes = 5; number_of_presieve_primes = 2; break; case 3: presieve_base = 30; number_of_presieve_primes = 3; sum_of_presieve_primes = 10; number_of_presieve_primes = 3; break; case 4: presieve_base = 210; number_of_presieve_primes = 4; sum_of_presieve_primes = 17; number_of_presieve_primes = 4; break; case 5: presieve_base = 2310; number_of_presieve_primes = 5; sum_of_presieve_primes = 28; number_of_presieve_primes = 5; break; } } prime_table<sieve_by_slice<bit_table_cnte, long> > T; long32 prime(long32 i) { return T.prime(i);} long32 piB(long32 i) { return T.piB(i); } long32 number_of_primes() { return T.get_number_of_primes(); } long32 max_prime() {return prime(T.get_number_of_primes());} long32 index_of_first_prime_bigger_than(long32 x) { return T.index_of_first_prime_bigger_than(x); } void init_prime_table(long32 upto, int nbps) { if (nbps > 5) { cout << "init_prime_table error called with upto = " << upto << " and nbps = " << nbps << endl\ << "nbps, the number_of_presieved primes must be less or equal to 5\n"; error(); } init_presieve(nbps); //cout << "init_prime_table : presieve_base set to " << presieved_primes::presieve_base << endl; T.create(upto, presieved_primes::presieve_base); primes_initialized = 1; #ifdef DEBUG_PRIMES cout << "\nprime_table::is_created first non presieved prime = " << presieved_primes::prime(1) << endl;; cout << "presieved_primes::number_of_primes() = " << presieved_primes::number_of_primes() << endl; cout << "presieved_primes::max_prime() = " << presieved_primes::max_prime() << endl << endl; #endif } void display() { cout << "\nPrime_table created\n"; cout << " number of presieved primes = " << presieved_primes::number_of_presieve_primes << endl; cout << " first non presieved prime = " << presieved_primes::prime(1) << endl;; cout << " presieved_primes::number_of_primes() = " << presieved_primes::number_of_primes() << endl; cout << " presieved_primes::max_prime() = " << presieved_primes::max_prime() << endl << endl; } void display_prime_table() { T.display();} void init_sum_primes() { Sp= new long[1+number_of_primes()]; long sum=0; for (int i=1; i <= number_of_primes(); i++) { sum+=T.prime(i); Sp[i]=sum; } } }
29.106796
110
0.616077
4586e007716ddb33e39503120febcfcd9f469dcd
2,706
cpp
C++
checks/rng.cpp
vster/OpenCL
fb29aead4e6345e23f3f7ba5fb038fa1fd217e10
[ "BSD-2-Clause" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
checks/rng.cpp
vster/OpenCL
fb29aead4e6345e23f3f7ba5fb038fa1fd217e10
[ "BSD-2-Clause" ]
null
null
null
checks/rng.cpp
vster/OpenCL
fb29aead4e6345e23f3f7ba5fb038fa1fd217e10
[ "BSD-2-Clause" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* This file is in the public domain */ #include <string> #include <opencl/filters.h> #include <opencl/square.h> #include <opencl/randpool.h> #include <opencl/x917.h> #if defined(OPENCL_EXT_ENTROPY_SRC_DEVRANDOM) #include <opencl/devrand.h> #endif #if defined(OPENCL_EXT_ENTROPY_SRC_PTHREAD) #include <opencl/pthr_ent.h> #endif using namespace OpenCL; /*************************************************/ /* This is the global RNG used in various spots. Seems to make most sense to declare it here. */ OpenCL::X917<OpenCL::Square> local_rng; OpenCL::RandomNumberGenerator& rng = local_rng; /*************************************************/ /* Not too useful generally; just dumps random bits */ template<typename R> class RNG_Filter : public Filter { public: void write(const byte[], u32bit); private: static const u32bit BUFFERSIZE = OpenCL::DEFAULT_BUFFERSIZE; R rng; SecureBuffer<byte, BUFFERSIZE> buffer; u32bit position; }; template<typename B> void RNG_Filter<B>::write(const byte input[], u32bit length) { buffer.copy(position, input, length); if(position + length >= BUFFERSIZE) { rng.randomize(buffer, BUFFERSIZE); send(buffer, BUFFERSIZE); input += (BUFFERSIZE - position); length -= (BUFFERSIZE - position); while(length >= BUFFERSIZE) { /* This actually totally ignores the input, but it doesn't matter, because this is only for benchmark purposes and we just want to test speed. Anyway, if the RNG is good you can't tell the diff */ rng.randomize(buffer, BUFFERSIZE); send(buffer, BUFFERSIZE); input += BUFFERSIZE; length -= BUFFERSIZE; } buffer.copy(input, length); position = 0; } position += length; } /* A wrappr class to convert an EntropySource into a psudoe-RNG */ template<typename E> class ES_TO_RNG { public: void randomize(byte buf[], u32bit size) { u32bit need = size; while(need) need -= es.slow_poll(buf + size - need, need); } private: E es; }; Filter* lookup_rng(const std::string& algname) { if(algname == "X917<Square>") return new RNG_Filter< X917<Square> >; else if(algname == "Randpool") return new RNG_Filter<Randpool>; #if defined(OPENCL_EXT_ENTROPY_SRC_DEVRANDOM) else if(algname == "EntropySrc_DevRandom") return new RNG_Filter< ES_TO_RNG<DevRandom_EntropySource> >; #endif #if defined(OPENCL_EXT_ENTROPY_SRC_PTHREAD) else if(algname == "EntropySrc_Pthread") return new RNG_Filter< ES_TO_RNG<Pthread_EntropySource> >; #endif else return 0; }
26.271845
77
0.636364
4588b724efd0ce0f13cef267f2da3c49f709e55c
8,657
cpp
C++
intro/messageworld/messageworld.cpp
return/BeOSSampleCode
ca5a319fecf425a69e944f3c928a85011563a932
[ "BSD-3-Clause" ]
5
2018-09-09T21:01:57.000Z
2022-03-27T10:01:27.000Z
intro/messageworld/messageworld.cpp
return/BeOSSampleCode
ca5a319fecf425a69e944f3c928a85011563a932
[ "BSD-3-Clause" ]
null
null
null
intro/messageworld/messageworld.cpp
return/BeOSSampleCode
ca5a319fecf425a69e944f3c928a85011563a932
[ "BSD-3-Clause" ]
5
2018-04-03T01:45:23.000Z
2021-05-14T08:23:01.000Z
// // Menu World // // A sample program demonstrating the basics of using // the BMessage and BMessenger classes. // // Written by: Eric Shepherd // /* Copyright 1999, Be Incorporated. All Rights Reserved. This file may be used under the terms of the Be Sample Code License. */ #include <Application.h> #include <Messenger.h> #include <Message.h> #include <Roster.h> #include <Window.h> #include <View.h> #include <MenuBar.h> #include <Menu.h> #include <MenuItem.h> #include <string.h> #include <stdio.h> // Application's signature const char *APP_SIGNATURE = "application/x-vnd.Be-MessageWorld"; // Messages for window registry with application const uint32 WINDOW_REGISTRY_ADD = 'WRad'; const uint32 WINDOW_REGISTRY_SUB = 'WRsb'; const uint32 WINDOW_REGISTRY_ADDED = 'WRdd'; // Messages for menu commands const uint32 MENU_FILE_NEW = 'MFnw'; const uint32 MENU_FILE_OPEN = 'MFop'; const uint32 MENU_FILE_CLOSE = 'MFcl'; const uint32 MENU_FILE_SAVE = 'MFsv'; const uint32 MENU_FILE_SAVEAS = 'MFsa'; const uint32 MENU_FILE_PAGESETUP = 'MFps'; const uint32 MENU_FILE_PRINT = 'MFpr'; const uint32 MENU_FILE_QUIT = 'MFqu'; const uint32 MENU_OPT_HELLO = 'MOhl'; const char *STRING_HELLO = "Hello World!"; const char *STRING_GOODBYE = "Goodbye World!"; // // HelloView class // // This class defines the view in which the "Hello World" // message will be drawn. // class HelloView : public BView { public: HelloView(BRect frame); virtual void Draw(BRect updateRect); void SetString(const char *s); private: char message[128]; }; // // HelloView::HelloView // // Constructs the view we'll be drawing in. // As you see, it doesn't do much. // HelloView::HelloView(BRect frame) : BView(frame, "HelloView", B_FOLLOW_ALL_SIDES, B_WILL_DRAW) { SetString(STRING_HELLO); } // // HelloView::SetString // // Sets the message to draw in the view. // void HelloView::SetString(const char *s) { if (strlen(s) < 127) { strcpy(message, s); } } // // HelloView::Draw // // This function is called whenever our view // needs to be redrawn. This happens only because // we specified B_WILL_DRAW for the flags when // we created the view (see the constructor). // // The updateRect is the rectangle that needs to be // redrawn. We're ignoring it, but you can use it to // speed up your refreshes for more complex programs. // void HelloView::Draw(BRect updateRect) { MovePenTo(BPoint(20,75)); // Move pen DrawString(message); } // // HelloWindow class // // This class defines the hello world window. // class HelloWindow : public BWindow { public: HelloWindow(BRect frame); ~HelloWindow(); virtual bool QuitRequested(); virtual void MessageReceived(BMessage *message); private: void Register(bool need_id); void Unregister(void); BMenuBar *menubar; HelloView *helloview; }; // // HelloWindow::HelloWindow // // Constructs the window we'll be drawing into. // HelloWindow::HelloWindow(BRect frame) : BWindow(frame, "Untitled ", B_TITLED_WINDOW, B_NOT_RESIZABLE|B_NOT_ZOOMABLE) { BRect r; BMenu *menu; BMenuItem *item; // Add the menu bar r = Bounds(); menubar = new BMenuBar(r, "menu_bar"); AddChild(menubar); // Add File menu to menu bar menu = new BMenu("File"); menu->AddItem(new BMenuItem("New", new BMessage(MENU_FILE_NEW), 'N')); menu->AddItem(new BMenuItem("Open" B_UTF8_ELLIPSIS, new BMessage(MENU_FILE_OPEN), 'O')); menu->AddItem(new BMenuItem("Close", new BMessage(MENU_FILE_CLOSE), 'W')); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem("Save", new BMessage(MENU_FILE_SAVE), 'S')); menu->AddItem(new BMenuItem("Save as" B_UTF8_ELLIPSIS, new BMessage(MENU_FILE_SAVEAS))); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem("Page Setup" B_UTF8_ELLIPSIS, new BMessage(MENU_FILE_PAGESETUP))); menu->AddItem(new BMenuItem("Print" B_UTF8_ELLIPSIS, new BMessage(MENU_FILE_PRINT), 'P')); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem("Quit", new BMessage(MENU_FILE_QUIT), 'Q')); menubar->AddItem(menu); // Add Options menu to menu bar menu = new BMenu("Options"); item=new BMenuItem("Say Hello", new BMessage(MENU_OPT_HELLO)); item->SetMarked(true); menu->AddItem(item); menubar->AddItem(menu); // Add the drawing view r.top = menubar->Bounds().bottom+1; AddChild(helloview = new HelloView(r)); // Tell the application that there's one more window // and get the number for this untitled window. Register(true); Show(); } // // HelloWindow::~HelloWindow // // Destruct the window. This calls Unregister(). // HelloWindow::~HelloWindow() { Unregister(); } // // HelloWindow::MessageReceived // // Called when a message is received by our // application. // void HelloWindow::MessageReceived(BMessage *message) { switch(message->what) { case WINDOW_REGISTRY_ADDED: { char s[22]; int32 id = 0; if (message->FindInt32("new_window_number", &id) == B_OK) { sprintf(s, "Untitled %ld", id); SetTitle(s); } } break; case MENU_FILE_NEW: { BRect r; r = Frame(); r.OffsetBy(20,20); new HelloWindow(r); } break; case MENU_FILE_CLOSE: Quit(); break; case MENU_FILE_QUIT: be_app->PostMessage(B_QUIT_REQUESTED); break; case MENU_OPT_HELLO: { BMenuItem *item; const char *s; bool mark; message->FindPointer("source", (void **) &item); if (item->IsMarked()) { s = STRING_GOODBYE; mark = false; } else { s = STRING_HELLO; mark = true; } helloview->SetString(s); item->SetMarked(mark); helloview->Invalidate(); } break; default: BWindow::MessageReceived(message); break; } } // // HelloWindow::Register // // Since MessageWorld can have multiple windows and // we need to know when there aren't any left so the // application can be shut down, this function is used // to tell the application that a new window has been // opened. // // If the need_id argument is true, we'll specify true // for the "need_id" field in the message we send; this // will cause the application to send back a // WINDOW_REGISTRY_ADDED message containing the window's // unique ID number. If this argument is false, we won't // request an ID. // void HelloWindow::Register(bool need_id) { BMessenger messenger(APP_SIGNATURE); BMessage message(WINDOW_REGISTRY_ADD); message.AddBool("need_id", need_id); messenger.SendMessage(&message, this); } // // HelloWindow::Unregister // // Unregisters a window. This tells the application that // one fewer windows are open. The application will // automatically quit if the count goes to zero because // of this call. // void HelloWindow::Unregister(void) { BMessenger messenger(APP_SIGNATURE); messenger.SendMessage(new BMessage(WINDOW_REGISTRY_SUB)); } // // HelloWindow::QuitRequested // // Here we just give permission to close the window. // bool HelloWindow::QuitRequested() { return true; } // // HelloApp class // // This class, derived from BApplication, defines the // Hello World application itself. // class HelloApp : public BApplication { public: HelloApp(); virtual void MessageReceived(BMessage *message); private: int32 window_count; int32 next_untitled_number; }; // // HelloApp::HelloApp // // The constructor for the HelloApp class. This // will create our window. // HelloApp::HelloApp() : BApplication(APP_SIGNATURE) { BRect windowRect; windowRect.Set(50,50,349,399); window_count = 0; // No windows yet next_untitled_number = 1; // Next window is "Untitled 1" new HelloWindow(windowRect); } // // HelloApp::MessageReceived // // Handle incoming messages. In particular, handle the // WINDOW_REGISTRY_ADD and WINDOW_REGISTRY_SUB messages. // void HelloApp::MessageReceived(BMessage *message) { switch(message->what) { case WINDOW_REGISTRY_ADD: { bool need_id = false; if (message->FindBool("need_id", &need_id) == B_OK) { if (need_id) { BMessage reply(WINDOW_REGISTRY_ADDED); reply.AddInt32("new_window_number", next_untitled_number); message->SendReply(&reply); next_untitled_number++; } window_count++; } break; } case WINDOW_REGISTRY_SUB: window_count--; if (!window_count) { Quit(); } break; default: BApplication::MessageReceived(message); break; } } // // main // // The main() function's only real job in a basic BeOS // application is to create the BApplication object // and run it. // int main(void) { HelloApp theApp; // The application object theApp.Run(); return 0; }
21.696742
75
0.688922
458900190893fa28482feb5dd9be4cf587142595
5,591
cpp
C++
aoc2018_day21.cpp
bluespeck/aoc_2018
d847613516bd1e0a6c1a7a0c32cc093a3f558dd4
[ "MIT" ]
null
null
null
aoc2018_day21.cpp
bluespeck/aoc_2018
d847613516bd1e0a6c1a7a0c32cc093a3f558dd4
[ "MIT" ]
null
null
null
aoc2018_day21.cpp
bluespeck/aoc_2018
d847613516bd1e0a6c1a7a0c32cc093a3f558dd4
[ "MIT" ]
1
2018-12-15T11:50:33.000Z
2018-12-15T11:50:33.000Z
#include <algorithm> #include <array> #include <cassert> #include <cstdint> #include <iostream> #include <map> #include <queue> #include <set> #include <string> #include <vector> #include <sstream> #include <utility> using Registers = std::array<int64_t, 6>; struct Instruction { int opcode; int a, b, c; }; using Program = std::vector<Instruction>; void addr(int a, int b, int c, Registers& reg) { reg[c] = reg[a] + reg[b]; } void addi(int a, int b, int c, Registers&reg) { reg[c] = reg[a] + b; } void mulr(int a, int b, int c, Registers&reg) { reg[c] = reg[a] * reg[b]; } void muli(int a, int b, int c, Registers&reg) { reg[c] = reg[a] * b; } void banr(int a, int b, int c, Registers&reg) { reg[c] = reg[a] & reg[b]; } void bani(int a, int b, int c, Registers&reg) { reg[c] = reg[a] & b; } void borr(int a, int b, int c, Registers&reg) { reg[c] = reg[a] | reg[b]; } void bori(int a, int b, int c, Registers&reg) { reg[c] = reg[a] | b; } void setr(int a, int b, int c, Registers&reg) { reg[c] = reg[a]; } void seti(int a, int b, int c, Registers&reg) { reg[c] = a; } void gtir(int a, int b, int c, Registers&reg) { reg[c] = (a > reg[b]) ? 1 : 0; } void gtri(int a, int b, int c, Registers&reg) { reg[c] = (reg[a] > b) ? 1 : 0; } void gtrr(int a, int b, int c, Registers&reg) { reg[c] = (reg[a] > reg[b]) ? 1 : 0; } void eqir(int a, int b, int c, Registers&reg) { reg[c] = (a == reg[b]) ? 1 : 0; } void eqri(int a, int b, int c, Registers&reg) { reg[c] = (reg[a] == b) ? 1 : 0; } void eqrr(int a, int b, int c, Registers&reg) { reg[c] = (reg[a] == reg[b]) ? 1 : 0; } using PossibleOpcodeSets = std::array<std::set<int>, 16>; using Op = void(*)(int, int, int, Registers&); using OpcodeTranslationTable = std::array<int, 16>; std::array<Op, 16> operations{ addr, addi, mulr, muli, banr, bani, borr, bori, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr }; int64_t RunProgram(const Program& program, Registers& regs, int ipr, int maxNumSteps = 0) { int64_t numSteps = 0; while (regs[ipr] < program.size()) { auto& instruction = program[regs[ipr]]; { std::cout << "ip=" << regs[ipr]; std::cout << " ["; for (int i = 0; i < 5; i++) std::cout << regs[i] << ", "; std::cout << regs[5] << "] " << instruction.opcode << " " << instruction.a << " " << instruction.b << " " << instruction.c << " "; } operations[instruction.opcode](instruction.a, instruction.b, instruction.c, regs); { std::cout << " ["; for (int i = 0; i < 5; i++) std::cout << regs[i] << ", "; std::cout << regs[5] << "]\n"; } regs[ipr] ++; numSteps++; } return numSteps; } void ReadInput(Program& program, int& ip) { std::cin.ignore(4); std::cin >> ip; std::map<std::string, int> nameToOpcode; nameToOpcode["addr"] = 0; nameToOpcode["addi"] = 1; nameToOpcode["mulr"] = 2; nameToOpcode["muli"] = 3; nameToOpcode["banr"] = 4; nameToOpcode["bani"] = 5; nameToOpcode["borr"] = 6; nameToOpcode["bori"] = 7; nameToOpcode["setr"] = 8; nameToOpcode["seti"] = 9; nameToOpcode["gtir"] = 10; nameToOpcode["gtri"] = 11; nameToOpcode["gtrr"] = 12; nameToOpcode["eqir"] = 13; nameToOpcode["eqri"] = 14; nameToOpcode["eqrr"] = 15; while (std::cin) { std::string instructionName; Instruction instruction; std::cin >> instructionName >> instruction.a >> instruction.b >> instruction.c; if (std::cin) { instruction.opcode = nameToOpcode[instructionName]; program.push_back(instruction); } } } using Regs25Vec = std::vector<std::pair<int64_t, int64_t>>; Regs25Vec SimulateReg2AndReg5() { int64_t reg2 = 15608036; int64_t reg5 = 65536; Regs25Vec regPairs; while (true) { if (reg5 < 256) { regPairs.push_back(std::make_pair(reg2, reg5)); } if (reg5 < 256) { reg5 = reg2 | 65536; reg2 = (5234604 + (reg5 & 255)) & 0x00ff'ffff; reg2 = (reg2 * 65899) & 0x00ff'ffff; } else { reg5 /= 256; // bani 5 255 3 // addr 2 3 2 // bani 2 16777215 2 // muli 2 65899 2 // bani 2 16777215 2 reg2 = (reg2 + (reg5 & 255)) & 0x00ff'ffff; reg2 = (reg2 * 65899) & 0x00ff'ffff; } auto it = std::find_if(regPairs.begin(), regPairs.end(), [reg2, reg5](auto& elem) { return elem.first == reg2 && elem.second == reg5; }); if (it != regPairs.end()) { break; } } return regPairs; } int main() { //Program program; //int ipr = 0; //ReadInput(program, ipr); // //{ // Registers regs = { 0, 0, 0, 0, 0, 0 }; // int64_t steps = RunProgram(program, regs, ipr); // std::cout << "\n" << steps << "\n"; //} auto regPairs = SimulateReg2AndReg5(); std::cout << regPairs[0].first << "\n"; for (int i = regPairs.size() - 1; i >= 0; --i) { auto current = regPairs[i].first; auto it = std::find_if(regPairs.begin(), regPairs.begin() + i, [current](const std::pair<int64_t, int64_t>& elem) { return elem.first == current; }); if (it == regPairs.begin() + i) { std::cout << regPairs[i].first << "\n"; break; } } return 0; }
21.670543
152
0.524235
458bf6d617a44dfd03bbc2a44d0c4749251feb4d
801
cpp
C++
DEngine/Physics/cdCollisionWorld.cpp
norrischiu/DEngine
acea553f110b8d10fc7386ff0941b84f6d7ebce7
[ "MIT", "Unlicense" ]
8
2016-05-23T03:08:08.000Z
2020-03-02T06:15:16.000Z
DEngine/Physics/cdCollisionWorld.cpp
norrischiu/DEngine
acea553f110b8d10fc7386ff0941b84f6d7ebce7
[ "MIT", "Unlicense" ]
8
2016-06-01T17:00:58.000Z
2021-07-21T13:53:41.000Z
DEngine/Physics/cdCollisionWorld.cpp
norrischiu/DEngine
acea553f110b8d10fc7386ff0941b84f6d7ebce7
[ "MIT", "Unlicense" ]
1
2017-09-25T03:39:34.000Z
2017-09-25T03:39:34.000Z
#include "cdCollisionWorld.h" /** void CollisionWorld::addObject(const CollidableObject & object) { m_pObjects.push_back(object); } void CollisionWorld::addCollide(const Collide & collide) { m_pCollide.push_back(collide); } void CollisionWorld::computeCollision() { bool value = false; Collide collide; for (int i = 0; i < m_pObjects.size(); i++) { for (int j = i + 1; j < m_pObjects.size(); j++) { collide.collision(&m_pObjects[i], &m_pObjects[j]); // collide.getCollide() returns a boolean value, true means collide, false means not collide if (collide.getCollide()) addCollide(collide); //value = true; } } //return value; } */ CollisionWorld * CollisionWorld::GetInstance() { if (!m_pInstance) { m_pInstance = new CollisionWorld(); } return m_pInstance; }
19.536585
95
0.68789
458c004d2710be6d40ca18beea5ef17f8842f0f1
8,708
cxx
C++
MITK/Plugins/uk.ac.ucl.cmic.igiultrasoundoverlayeditor/src/internal/niftkIGIUltrasoundOverlayEditorPreferencePage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Plugins/uk.ac.ucl.cmic.igiultrasoundoverlayeditor/src/internal/niftkIGIUltrasoundOverlayEditorPreferencePage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Plugins/uk.ac.ucl.cmic.igiultrasoundoverlayeditor/src/internal/niftkIGIUltrasoundOverlayEditorPreferencePage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "niftkIGIUltrasoundOverlayEditorPreferencePage.h" #include "niftkIGIUltrasoundOverlayEditor.h" #include <QLabel> #include <QPushButton> #include <QFormLayout> #include <QRadioButton> #include <QColorDialog> #include <QCheckBox> #include <ctkPathLineEdit.h> #include <berryIPreferencesService.h> #include <berryPlatform.h> namespace niftk { const QString IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_STYLE_SHEET("first background color style sheet"); const QString IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_STYLE_SHEET("second background color style sheet"); const QString IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_COLOUR("first background color"); const QString IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_COLOUR("second background color"); const QString IGIUltrasoundOverlayEditorPreferencePage::CLIP_TO_IMAGE_PLANE("clip to imae plane"); //----------------------------------------------------------------------------- IGIUltrasoundOverlayEditorPreferencePage::IGIUltrasoundOverlayEditorPreferencePage() : m_MainControl(0) , m_ColorButton1(NULL) , m_ColorButton2(NULL) , m_ClipToImagePlane(NULL) { } //----------------------------------------------------------------------------- void IGIUltrasoundOverlayEditorPreferencePage::Init(berry::IWorkbench::Pointer ) { } //----------------------------------------------------------------------------- void IGIUltrasoundOverlayEditorPreferencePage::CreateQtControl(QWidget* parent) { berry::IPreferencesService* prefService = berry::Platform::GetPreferencesService(); m_IGIUltrasoundOverlayEditorPreferencesNode = prefService->GetSystemPreferences()->Node(IGIUltrasoundOverlayEditor::EDITOR_ID); m_MainControl = new QWidget(parent); QFormLayout *formLayout = new QFormLayout; m_ClipToImagePlane = new QCheckBox(); formLayout->addRow("clipping planes", m_ClipToImagePlane); // gradient background QLabel* gBName = new QLabel; gBName->setText("gradient background"); formLayout->addRow(gBName); // color m_ColorButton1 = new QPushButton; m_ColorButton1->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); m_ColorButton2 = new QPushButton; m_ColorButton2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); QPushButton* resetButton = new QPushButton; resetButton->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); resetButton->setText("reset"); QLabel* colorLabel1 = new QLabel("first color : "); colorLabel1->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); QLabel* colorLabel2 = new QLabel("second color: "); colorLabel2->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum); QHBoxLayout* colorWidgetLayout = new QHBoxLayout; colorWidgetLayout->setContentsMargins(4,4,4,4); colorWidgetLayout->addWidget(colorLabel1); colorWidgetLayout->addWidget(m_ColorButton1); colorWidgetLayout->addWidget(colorLabel2); colorWidgetLayout->addWidget(m_ColorButton2); colorWidgetLayout->addWidget(resetButton); QWidget* colorWidget = new QWidget; colorWidget->setLayout(colorWidgetLayout); // spacer QSpacerItem *spacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); QVBoxLayout* vBoxLayout = new QVBoxLayout; vBoxLayout->addLayout(formLayout); vBoxLayout->addWidget(colorWidget); vBoxLayout->addSpacerItem(spacer); m_MainControl->setLayout(vBoxLayout); QObject::connect( m_ColorButton1, SIGNAL( clicked() ) , this, SLOT( FirstColorChanged() ) ); QObject::connect( m_ColorButton2, SIGNAL( clicked() ) , this, SLOT( SecondColorChanged() ) ); QObject::connect( resetButton, SIGNAL( clicked() ) , this, SLOT( ResetColors() ) ); this->Update(); } //----------------------------------------------------------------------------- QWidget* IGIUltrasoundOverlayEditorPreferencePage::GetQtControl() const { return m_MainControl; } //----------------------------------------------------------------------------- bool IGIUltrasoundOverlayEditorPreferencePage::PerformOk() { m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_STYLE_SHEET, m_FirstColorStyleSheet); m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_STYLE_SHEET, m_SecondColorStyleSheet); m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_COLOUR, m_FirstColor); m_IGIUltrasoundOverlayEditorPreferencesNode->Put(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_COLOUR, m_SecondColor); m_IGIUltrasoundOverlayEditorPreferencesNode->PutBool(IGIUltrasoundOverlayEditorPreferencePage::CLIP_TO_IMAGE_PLANE, m_ClipToImagePlane->isChecked()); return true; } //----------------------------------------------------------------------------- void IGIUltrasoundOverlayEditorPreferencePage::PerformCancel() { } //----------------------------------------------------------------------------- void IGIUltrasoundOverlayEditorPreferencePage::Update() { m_FirstColorStyleSheet = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_STYLE_SHEET, ""); m_SecondColorStyleSheet = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_STYLE_SHEET, ""); m_FirstColor = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::FIRST_BACKGROUND_COLOUR, ""); m_SecondColor = m_IGIUltrasoundOverlayEditorPreferencesNode->Get(IGIUltrasoundOverlayEditorPreferencePage::SECOND_BACKGROUND_COLOUR, ""); if (m_FirstColorStyleSheet=="") { m_FirstColorStyleSheet = "background-color:rgb(0,0,0)"; } if (m_SecondColorStyleSheet=="") { m_SecondColorStyleSheet = "background-color:rgb(0,0,0)"; } if (m_FirstColor=="") { m_FirstColor = "#000000"; } if (m_SecondColor=="") { m_SecondColor = "#000000"; } m_ColorButton1->setStyleSheet(m_FirstColorStyleSheet); m_ColorButton2->setStyleSheet(m_SecondColorStyleSheet); m_ClipToImagePlane->setChecked(m_IGIUltrasoundOverlayEditorPreferencesNode->GetBool(IGIUltrasoundOverlayEditorPreferencePage::CLIP_TO_IMAGE_PLANE, true)); } //----------------------------------------------------------------------------- void IGIUltrasoundOverlayEditorPreferencePage::FirstColorChanged() { QColor color = QColorDialog::getColor(); m_ColorButton1->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_ColorButton1->setStyleSheet(styleSheet); m_FirstColorStyleSheet = styleSheet; QStringList firstColor; firstColor << color.name(); m_FirstColor = firstColor.replaceInStrings(";","\\;").join(";"); } //----------------------------------------------------------------------------- void IGIUltrasoundOverlayEditorPreferencePage::SecondColorChanged() { QColor color = QColorDialog::getColor(); m_ColorButton2->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(color.red())); styleSheet.append(","); styleSheet.append(QString::number(color.green())); styleSheet.append(","); styleSheet.append(QString::number(color.blue())); styleSheet.append(")"); m_ColorButton2->setStyleSheet(styleSheet); m_SecondColorStyleSheet = styleSheet; QStringList secondColor; secondColor << color.name(); m_SecondColor = secondColor.replaceInStrings(";","\\;").join(";"); } //----------------------------------------------------------------------------- void IGIUltrasoundOverlayEditorPreferencePage::ResetColors() { m_FirstColorStyleSheet = "background-color:rgb(0,0,0)"; m_SecondColorStyleSheet = "background-color:rgb(0,0,0)"; m_FirstColor = "#000000"; m_SecondColor = "#000000"; m_ColorButton1->setStyleSheet(m_FirstColorStyleSheet); m_ColorButton2->setStyleSheet(m_SecondColorStyleSheet); } } // end namespace
37.373391
156
0.706821
45916e18b70b1ba2bd94f6b171cfa3caaa03cbf6
12,415
hpp
C++
include/Lodtalk/Collections.hpp
ronsaldo/lodtalk
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
[ "MIT" ]
3
2017-02-10T18:18:58.000Z
2019-02-21T02:35:29.000Z
include/Lodtalk/Collections.hpp
ronsaldo/lodtalk
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
[ "MIT" ]
null
null
null
include/Lodtalk/Collections.hpp
ronsaldo/lodtalk
4668e8923f508c8a9e87a00242ab67b26fb0c9a4
[ "MIT" ]
null
null
null
#ifndef LODTALK_COLLECTIONS_HPP_ #define LODTALK_COLLECTIONS_HPP_ #include <stddef.h> #include <string> #include "Lodtalk/Object.hpp" namespace Lodtalk { /** * Collection */ class LODTALK_VM_EXPORT Collection: public Object { public: static SpecialNativeClassFactory Factory; }; /** * SequenceableCollection */ class LODTALK_VM_EXPORT SequenceableCollection: public Collection { public: static SpecialNativeClassFactory Factory; }; /** * ArrayedCollection */ class LODTALK_VM_EXPORT ArrayedCollection: public SequenceableCollection { public: static SpecialNativeClassFactory Factory; }; /** * Array */ class LODTALK_VM_EXPORT Array: public ArrayedCollection { public: static SpecialNativeClassFactory Factory; static Array *basicNativeNew(VMContext *context, size_t indexableSize); }; /** * ByteArray */ class LODTALK_VM_EXPORT ByteArray: public ArrayedCollection { public: static SpecialNativeClassFactory Factory; }; /** * FloatArray */ class LODTALK_VM_EXPORT FloatArray: public ArrayedCollection { public: static SpecialNativeClassFactory Factory; }; /** * WordArray */ class LODTALK_VM_EXPORT WordArray: public ArrayedCollection { public: static SpecialNativeClassFactory Factory; }; /** * IntegerArray */ class LODTALK_VM_EXPORT IntegerArray: public ArrayedCollection { public: static SpecialNativeClassFactory Factory; }; /** * String */ class LODTALK_VM_EXPORT String: public ArrayedCollection { public: static SpecialNativeClassFactory Factory; }; /** * ByteString */ class LODTALK_VM_EXPORT ByteString: public String { public: static SpecialNativeClassFactory Factory; static ByteString *basicNativeNew(VMContext *context, size_t indexableSize); static ByteString *fromNativeRange(VMContext *context, const char *start, size_t size); static ByteString *fromNativeReverseRange(VMContext *context, const char *start, ptrdiff_t size); static Ref<ByteString> fromNative(VMContext *context, const std::string &native); static Oop splitVariableNames(VMContext *context, const std::string &string); std::string getString(); static int stSplitVariableNames(InterpreterProxy *interpreter); }; /** * WideString */ class LODTALK_VM_EXPORT WideString: public String { public: static SpecialNativeClassFactory Factory; }; /** * Symbol */ class LODTALK_VM_EXPORT Symbol: public String { public: static SpecialNativeClassFactory Factory; }; /** * ByteSymbol */ class LODTALK_VM_EXPORT ByteSymbol: public Symbol { public: static SpecialNativeClassFactory Factory; static Object *basicNativeNew(VMContext *context, size_t indexableSize); static Oop fromNative(VMContext *context, const std::string &native); static Oop fromNativeRange(VMContext *context, const char *star, size_t size); std::string getString(); }; /** * WideSymbol */ class LODTALK_VM_EXPORT WideSymbol: public Symbol { public: static SpecialNativeClassFactory Factory; }; /** * HashedCollection */ class LODTALK_VM_EXPORT HashedCollection: public Collection { public: static SpecialNativeClassFactory Factory; void initialize() { capacityObject = Oop::encodeSmallInteger(0); tallyObject = Oop::encodeSmallInteger(0); keyValues = (Array*)&NilObject; } size_t getCapacity() const { return capacityObject.decodeSmallInteger(); } size_t getTally() const { return tallyObject.decodeSmallInteger(); } Oop *getHashTableKeyValues() const { assert(keyValues); return reinterpret_cast<Oop*> (keyValues->getFirstFieldPointer()); } protected: void setKeyCapacity(VMContext *context, size_t keyCapacity) { keyValues = Array::basicNativeNew(context, keyCapacity); } template<typename KF, typename HF, typename EF> ptrdiff_t findKeyPosition(Oop key, const KF &keyFunction, const HF &hashFunction, const EF &equals) { auto capacity = getCapacity(); if(capacity == 0) return -1; auto keyHash = hashFunction(key); auto startPosition = keyHash % capacity; auto keyValuesArray = getHashTableKeyValues(); // Search from the hash position to the end. for(size_t i = startPosition; i < capacity; ++i) { // Check no association auto keyValue = keyValuesArray[i]; if(isNil(keyValue)) return i; // Check the key auto slotKey = keyFunction(keyValue); if(equals(key, slotKey)) return i; } // Search from the start to the hash position. for(size_t i = 0; i < startPosition; ++i) { // Check no association auto keyValue = keyValuesArray[i]; if(isNil(keyValue)) return i; // Check the key auto slotKey = keyFunction(keyValuesArray[i]); if(equals(key, slotKey)) return i; } // Not found. return -1; } template<typename KF, typename HF, typename EF> void increaseSize(VMContext *context, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction) { tallyObject.intValue += 2; // Do not use more than 80% of the capacity if(tallyObject.intValue > capacityObject.intValue*4/5) increaseCapacity(context, keyFunction, hashFunction, equalityFunction); } template<typename KF, typename HF, typename EF> void increaseCapacity(VMContext *context, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction) { size_t newCapacity = getCapacity()*2; if(!newCapacity) newCapacity = 16; setCapacity(context, newCapacity, keyFunction, hashFunction, equalityFunction); } template<typename KF, typename HF, typename EF> Oop internalKeyValueAtOrNil(Oop key, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction) { // If a slot was not found, try to increase the capacity. auto position = findKeyPosition(key, keyFunction, hashFunction, equalityFunction); if(position < 0) return nilOop(); auto oldKeyValue = getHashTableKeyValues()[position]; if(isNil(oldKeyValue)) return nilOop(); return oldKeyValue; } template<typename KF, typename HF, typename EF> void internalPutKeyValue(VMContext *context, Oop keyValue, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction) { // If a slot was not found, try to increase the capacity. auto position = findKeyPosition(keyFunction(keyValue), keyFunction, hashFunction, equalityFunction); if(position < 0) { OopRef keyValueRef(context, keyValue); increaseCapacity(context, keyFunction, hashFunction, equalityFunction); return internalPutKeyValue(context, keyValueRef.oop, keyFunction, hashFunction, equalityFunction); } // Put the key and value. auto keyValueArray = getHashTableKeyValues(); auto oldKeyValue = keyValueArray[position]; keyValueArray[position] = keyValue; // Increase the size. if(isNil(oldKeyValue)) increaseSize(context, keyFunction, hashFunction, equalityFunction); } template<typename KF, typename HF, typename EF> void setCapacity(VMContext *context, size_t newCapacity, const KF &keyFunction, const HF &hashFunction, const EF &equalityFunction) { // Store temporarily the data. auto oldKeyValues = Oop::fromPointer(keyValues); size_t oldCapacity = capacityObject.decodeSmallInteger(); // Create the new capacity. capacityObject = Oop::encodeSmallInteger(newCapacity); tallyObject = Oop::encodeSmallInteger(0); setKeyCapacity(context, newCapacity); // Add back the old objects. if(!oldKeyValues.isNil()) { Oop *oldKeyValuesOops = reinterpret_cast<Oop *> (oldKeyValues.getFirstFieldPointer()); for(size_t i = 0; i < oldCapacity; ++i) { auto oldKeyValue = oldKeyValuesOops[i]; if(!isNil(oldKeyValue)) internalPutKeyValue(context, oldKeyValue, keyFunction, hashFunction, equalityFunction); } } } Oop capacityObject; Oop tallyObject; Array* keyValues; }; /** * Dictionary */ class LODTALK_VM_EXPORT Dictionary: public HashedCollection { public: static SpecialNativeClassFactory Factory; }; /** * MethodDictionary */ class LODTALK_VM_EXPORT MethodDictionary: public Dictionary { public: static SpecialNativeClassFactory Factory; static MethodDictionary* basicNativeNew(VMContext *context); Oop atOrNil(Oop key) { return internalAtOrNil(key); } Oop atPut(VMContext *context, Oop key, Oop value) { internalAtPut(context, key, value); return value; } Oop *getHashTableKeys() const { assert(keyValues); return reinterpret_cast<Oop*> (keyValues->getFirstFieldPointer()); } Oop *getHashTableValues() const { assert(values); return reinterpret_cast<Oop*> (values->getFirstFieldPointer()); } static int stAtOrNil(InterpreterProxy *interpreter); static int stAtPut(InterpreterProxy *interpreter); protected: MethodDictionary() { object_header_ = ObjectHeader::specialNativeClass(generateIdentityHash(this), SCI_MethodDictionary, 4); values = (Array*)&NilObject; } void increaseSize(VMContext *context) { tallyObject.intValue += 2; // Do not use more than 80% of the capacity if(tallyObject.intValue > capacityObject.intValue*4/5) increaseCapacity(context); } void increaseCapacity(VMContext *context) { size_t newCapacity = getCapacity()*2; if(!newCapacity) newCapacity = 16; setCapacity(context, newCapacity); } Oop internalAtOrNil(Oop key) { // If a slot was not found, try to increase the capacity. auto position = findKeyPosition(key, identityFunction<Oop>, identityHashOf, identityOopEquals); if(position < 0) return nilOop(); auto oldKey = getHashTableKeys()[position]; if(isNil(oldKey)) return nilOop(); return getHashTableValues()[position]; } void internalAtPut(VMContext *context, Oop key, Oop value) { // If a slot was not found, try to increase the capacity. auto position = findKeyPosition(key, identityFunction<Oop>, identityHashOf, identityOopEquals); if(position < 0) { OopRef keyRef(context, key); OopRef valueRef(context, value); increaseCapacity(context); return internalAtPut(context, keyRef.oop, valueRef.oop); } // Put the key and value. auto keyArray = getHashTableKeys(); auto valueArray = getHashTableValues(); auto oldKey = keyArray[position]; keyArray[position] = key; valueArray[position] = value; // Increase the size. if(isNil(oldKey)) increaseSize(context); } void setCapacity(VMContext *context, size_t newCapacity) { // Store temporarily the data. auto oldKeys = Oop::fromPointer(keyValues); auto oldValues = Oop::fromPointer(values); size_t oldCapacity = capacityObject.decodeSmallInteger(); // Create the new capacity. capacityObject = Oop::encodeSmallInteger(newCapacity); tallyObject = Oop::encodeSmallInteger(0); setKeyCapacity(context, newCapacity); setValueCapacity(context, newCapacity); // Add back the old objects. if(!oldKeys.isNil()) { Oop *oldKeysOops = reinterpret_cast<Oop *> (oldKeys.getFirstFieldPointer()); Oop *oldValuesOops = reinterpret_cast<Oop *> (oldValues.getFirstFieldPointer()); for(size_t i = 0; i < oldCapacity; ++i) { auto oldKey = oldKeysOops[i]; if(!isNil(oldKey)) internalAtPut(context, oldKey, oldValuesOops[i]); } } } void setValueCapacity(VMContext *context, size_t valueCapacity) { values = Array::basicNativeNew(context, valueCapacity); } Array* values; }; /** * IdentityDictionary */ class LODTALK_VM_EXPORT IdentityDictionary: public Dictionary { public: static SpecialNativeClassFactory Factory; Oop putAssociation(VMContext *context, Oop assoc) { internalPutKeyValue(context, assoc, getLookupKeyKey, identityHashOf, identityOopEquals); return assoc; } Oop getAssociationOrNil(Oop key) { return internalKeyValueAtOrNil(key, getLookupKeyKey, identityHashOf, identityOopEquals); } void putNativeAssociation(VMContext *context, Association *assoc) { putAssociation(context, Oop::fromPointer(assoc)); } Association *getNativeAssociationOrNil(Oop key) { return reinterpret_cast<Association *> (getAssociationOrNil(key).pointer); } static int stPutAssociation(InterpreterProxy *interpreter); static int stAssociationAtOrNil(InterpreterProxy *interpreter); }; /** * SystemDictionary */ class LODTALK_VM_EXPORT SystemDictionary: public IdentityDictionary { public: static SpecialNativeClassFactory Factory; static SystemDictionary *create(VMContext *context); }; } // End of namespace Lodtalk #endif //LODTALK_COLLECTIONS_HPP_
23.829175
134
0.737898
4593f57d4d81656f516d9deaca99f02bef8d2f98
1,610
cpp
C++
codechef/aug17/6.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
codechef/aug17/6.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
codechef/aug17/6.cpp
AadityaJ/Spoj
61664c1925ef5bb072a3fe78fb3dac4fb68d77a1
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; void printArr(vector<string> &v){ for(int i=0;i<v.size();i++){ cout<<v[i]<<endl; } } long long int f(vector<string> &v,string str){ for(int i=0;i<str.length();i++){ bool is=0; char c=str[i]; for(int j=0;j<v.size();j++){ if(v[j][i]==c){is=1;break;} } if(!is){v.push_back(str);return str.length()-i;} } return 0; } string con2bits(int c,int n){ string str=""; for(int i=0;i<(n-c-1);i++) str.push_back('0'); str.push_back('1'); for(int i=0;i<c;i++) str.push_back('0'); return str; } string add(string a,string b){ int ca=0; string c=""; for(int i=a.length()-1;i>=0;i--){ int ax=a[i]-'0'; int bx=b[i]-'0'; int cx=(ax+bx+ca)%2; ca=(ax+bx+ca)/2; c.push_back(cx+'0'); } reverse(c.begin(),c.end()); return c; } int main(int argc, char const *argv[]) { int t; cin>>t; while(t--){ int n,q; cin>>n>>q; long long int ans=0; string x=""; for(int i=0;i<n;i++) x.push_back('0'); vector<string> v; for(int i=0;i<q;i++){ char ch; cin>>ch; if(ch=='?'){cout<<ans<<endl;} else{ int c; cin>>c; string str=con2bits(c,n); x=add(x,str); ans+=f(v,x); cout<<i<<" :: "<<x<<endl; printArr(v); cout<<endl; } } } return 0; }
22.676056
56
0.445342
459410b8db4d34750797b8d22906e62fa7952018
72,861
cpp
C++
src/zgemmtune.cpp
codedivine/raijinclv2
e4c50b757e3fe6d1fa5d09c135f1156b31c08fab
[ "Apache-2.0" ]
null
null
null
src/zgemmtune.cpp
codedivine/raijinclv2
e4c50b757e3fe6d1fa5d09c135f1156b31c08fab
[ "Apache-2.0" ]
null
null
null
src/zgemmtune.cpp
codedivine/raijinclv2
e4c50b757e3fe6d1fa5d09c135f1156b31c08fab
[ "Apache-2.0" ]
null
null
null
/**Copyright 2012, Rahul Garg and McGill University 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 <iostream> #include <string> #include <cstdlib> #include <fstream> #include <sstream> #include "raijin_complex.hpp" #include "rtimer.hpp" #include <CL/cl.h> using namespace std; using namespace RaijinCL; struct GemmCsingle{ typedef cl_float2 ctype; typedef cl_float basetype; static bool isDouble(){return false;} static string gemmName(){return "cgemm";} static string name(){return "float";} }; struct GemmCdouble{ typedef cl_double2 ctype; typedef cl_double basetype; static bool isDouble(){return true;} static string gemmName(){return "zgemm";} static string name(){return "double";} }; static bool genCkernelTNOff(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype, int simdwidth, bool storea, bool storeb, int maxLocalMemElems, int padding, string& kernel, bool useImageA = false, bool useImageB = false){ //cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll; //cout<<" "<<maxLocalMemElems<<" "<<endl; bool isDouble = (dtype.compare("double")==0) ? true:false; if(isDouble && simdwidth>1 && (useImageA || useImageB)) return false; if(!isDouble && simdwidth>2 && (useImageA || useImageB)) return false; //const int unroll = ktile; if(storea){ /*Number of rows of A per workgroup = ktile. Has to be divisble by lsizey. */ if(ktile%lsizex!=0) return false; /*Number of columns of A per workgroup = htile*lsizex*/ if((htile*lsizex)%(simdwidth*lsizey)!=0) return false; }else{ if(htile%simdwidth!=0) return false; } if(storeb){ /*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*simdwidth */ if(ktile%lsizex!=0) return false; if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false; }else{ if(wtile%simdwidth!=0) return false; } //cout<<"Check 2 passed"<<endl; if(wtile%simdwidth!=0 || htile%simdwidth!=0) return false; int numLocalMemElems = 0; if(storea) numLocalMemElems += ktile*(htile*lsizex+padding); if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding); if(numLocalMemElems>maxLocalMemElems) return false; //cout<<"Check 3 passed"<<endl; //if(ktile%unroll!=0) return false; //cout<<"Check 4 passed"<<endl; stringstream ss; ss<<"("; if(useImageA){ ss<<"__read_only image2d_t A,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,"; } if(useImageB){ ss<<"__read_only image2d_t B,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,"; } ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl; ss<<"const int htile ="<<htile<<";\n"; ss<<"const int wtile ="<<wtile<<";\n"; ss<<"const int ktile ="<<ktile<<";\n"; ss<<"const int simdwidth="<<simdwidth<<";\n"; ss<<"const int lx = "<<lsizex<<";\n"; ss<<"const int ly = "<<lsizey<<";\n"; ss<<"const int i = get_global_id(1);"<<endl; ss<<"const int j = get_global_id(0);"<<endl; //ss<<"const int unroll = "<<unroll<<";\n"; //ss<<"const int unsigned flat = get_local_id(0)+get_local_id(1)*ly;"<<endl; ss<<"const unsigned int lidx = get_local_id(1);"<<endl; ss<<"const unsigned int lidy = get_local_id(0);"<<endl; /*ss<<"const unsigned int lidx = flat%lx;"<<endl; ss<<"const unsigned int lidy = (get_local_id(0)+get_local_id(1))%ly;"<<endl;*/ ss<<"int k;"<<endl; if(storea){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(ktile)<<"]["<<((htile/simdwidth)*lsizex+padding)<<"];"<<endl; } if(storeb){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl; } for(int x=0;x<htile;x++){ for(int y=0;y<wtile/simdwidth;y++){ ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n"; } } ss<<"for(k=0;k<K;k+=ktile){"<<endl; if(storea){ ss<<"const int gstartxA = get_group_id(1)*(htile/simdwidth)*lx;\n"; for(int y=0;y<(ktile/lsizex);y++){ for(int x=0;x<((htile*lsizex)/(simdwidth*lsizey));x++){ ss<<" ldsA["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = "; if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx )))"; }else{ ss<<"(myread_imagef(A,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(k+"<<y<<"*lx+lidx)*(lda/simdwidth)+ gstartxA + lidy + "<<x<<"*ly];\n"; } } } } if(storeb){ ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n"; for(int y=0;y<(ktile/lsizex);y++){ for(int x=0;x<((wtile*lsizey)/(simdwidth*lsizey));x++){ ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = "; if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))"; }else{ ss<<"(myread_imagef(B,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; //ss<<" for(kk=0;kk<ktile;kk+=unroll){\n"; ss<<"const int kk = 0;\n"; for (int y = 0; y < ktile; y++) { for (int x = 0; x < wtile/simdwidth; x++) { ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << y << " = "; if(storeb){ ss << "ldsB[kk+"<<y<<"][ly*"<<x<<"+lidy];\n"; }else{ if(useImageB){ if(isDouble){ ss<<"as_double2( read_imagei(B,sampler,(int2)((get_group_id(0)*(wtile/simdwidth)+"<<x<<")*ly + lidy,k+kk+"<<y<<")))"; }else{ ss<<"( myread_imagef(B,(int2)((get_group_id(0)*(wtile/simdwidth)+"<<x<<")*ly + lidy,k+kk+"<<y<<")))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss << "B[(k+kk+"<<y<<")*(ldb/simdwidth)+ (get_group_id(0)*(wtile/simdwidth)+"<<x<<")*ly + lidy];\n"; } } } } for (int y = 0; y < ktile; y++){ for (int x = 0; x < htile/simdwidth; x++) { ss << " const " << dtype << (simdwidth*2) << " a" << x << "_" << y << " = "; if(storea){ ss << "ldsA[kk+"<<y<<"][lx*"<<x<<"+lidx];\n"; }else{ if(useImageA){ if(isDouble) { ss<<"as_double2(read_imagei(A,sampler,(int2)((get_group_id(1)*(htile/simdwidth)+"<<x<<")*lx + lidx,k+kk+"<<y<<")))"; }else{ ss<<"(myread_imagef(A,(int2)((get_group_id(1)*(htile/simdwidth)+"<<x<<")*lx + lidx,k+kk+"<<y<<")))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss << "A[(k+kk+"<<y<<")*(lda/simdwidth)+ (get_group_id(1)*(htile/simdwidth)+"<<x<<")*lx + lidx];"<<endl; } } //for(int x=0;x<htile/simdwidth;x++){ for(int xoff=0;xoff<simdwidth;xoff++){ int row = x*simdwidth + xoff; for(int w=0;w<wtile/simdwidth; w++){ ss<<" sum"<<row<<"_"<<w; ss<<" = fmaComplex"<<simdwidth; ss<<"(a"<<x<<"_"<<y<<".s"; for(int m=0;m<simdwidth;m++){ ss<<(2*xoff); ss<<(2*xoff+1); } ss<<",b"<<w<<"_"<<y<<","; ss<<" sum"<<row<<"_"<<w; ss<<");\n"; } } } } //ss<<" }\n"; if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; ss<<"}"<<endl; for (int i = 0; i < htile/simdwidth; i++) { for(int ii=0;ii<simdwidth;ii++){ for (int j = 0; j < wtile/simdwidth; j++) { for(int jj=0;jj<simdwidth;jj++){ ss << "C[( (get_group_id(1)*htile+"<<i<<"*simdwidth)*lx + lidx*simdwidth+ "<<ii<<")*ldc + (get_group_id(0)*wtile + " << j << "*simdwidth)*ly + lidy*simdwidth+" << jj << "]"; ss << "= mulComplex1(alpha,sum"<<(i*simdwidth+ii)<<"_"<<j; if(simdwidth>1){ ss<<".s"<<(2*jj)<<(2*jj+1); } ss<<") + mulComplex1(beta,"; ss << "C[( (get_group_id(1)*htile+"<<i<<"*simdwidth)*lx + lidx*simdwidth+ "<<ii<<")*ldc + (get_group_id(0)*wtile + " << j << "*simdwidth)*ly + lidy*simdwidth+" << jj << "]"; //ss << "C[(i*" << htile << "+ " << i << ")*ldc + (get_group_id(0)*wtile + " << j << "*simdwidth)*ly + lidy*simdwidth+" << jj << "]"; ss << ");" << endl; } } } } ss<<"}"<<endl; kernel = ss.str(); return true; } static bool genCkernelNTCons(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype,int simdwidth, bool storea, bool storeb, int maxLocalMemElems, int padding,string& kernel, bool useImageA,bool useImageB){ //cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll; //cout<<" "<<maxLocalMemElems<<" "<<endl; if(storea){ /*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */ /*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */ if(ktile%(simdwidth*lsizey)!=0) return false; } if(storeb){ /*Number of columns of B per workgroup = ktile. Has to be divisble by lsizey*simdwidth */ if(ktile%(lsizey*simdwidth)!=0) return false; /*Number of rows of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*/ if((wtile*lsizey)%lsizex!=0) return false; } //cout<<"Check 2 passed"<<endl; bool isDouble = (dtype.compare("double")==0); if(ktile%simdwidth!=0) return false; int numLocalMemElems = 0; if(storea) numLocalMemElems += htile*lsizex*(ktile+padding); if(storeb) numLocalMemElems += wtile*lsizey*(ktile+padding); if(numLocalMemElems>maxLocalMemElems) return false; //cout<<"Check 3 passed"<<endl; //cout<<"Check 4 passed"<<endl; stringstream ss; ss<<"("; if(useImageA){ ss<<"__read_only image2d_t A,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,"; } if(useImageB){ ss<<"__read_only image2d_t B,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,"; } ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl; ss<<"const int htile ="<<htile<<";\n"; ss<<"const int wtile ="<<wtile<<";\n"; ss<<"const int ktile ="<<ktile<<";\n"; ss<<"const int simdwidth="<<simdwidth<<";\n"; ss<<"const int lx = "<<lsizex<<";\n"; ss<<"const int ly = "<<lsizey<<";\n"; ss<<"const int i = get_global_id(1);\n"; ss<<"const int j = get_global_id(0);\n"; ss<<"const unsigned int lidx = get_local_id(1);"<<endl; ss<<"const unsigned int lidy = get_local_id(0);"<<endl; ss<<"unsigned int k;"<<endl; if(storea){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl; } if(storeb){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(wtile*lsizey)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl; } for(int x=0;x<htile;x++){ for(int y=0;y<wtile;y++){ ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n"; } } ss<<"const unsigned int ldbs = ldb/simdwidth;\n"; ss<<"const unsigned int ldas = lda/simdwidth;\n"; ss<<"for(k=0;k<K/simdwidth;k+=(ktile/simdwidth)){"<<endl; if(storea){ ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n"; for(int rowA=0;rowA<htile;rowA++){ for(int colA=0;colA<(ktile/(lsizey*simdwidth));colA++){ ss<<" ldsA["<<rowA<<"*lx + lidx]["<<colA<<"*ly + lidy] = "; if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(gstartxA+"<<rowA<<"*lx + lidx)*(lda/simdwidth) + k + "<<colA<<"*ly + lidy];\n"; } } } } if(storeb){ ss<<"const int gstartxB = get_group_id(0)*wtile*ly;\n"; for(int rowB=0;rowB<(wtile*lsizey)/lsizex;rowB++){ for(int colB=0;colB<(ktile/(lsizey*simdwidth));colB++){ ss<<" ldsB["<<rowB<<"*lx + lidx]["<<colB<<"*ly + lidy] = "; if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(gstartxB+"<<rowB<<"*lx + lidx)*(ldb/simdwidth) + k + "<<colB<<"*ly + lidy];\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; for(int rowB =0;rowB<wtile;rowB++){ for(int colB = 0;colB<ktile/simdwidth;colB++){ ss<<" const "<<dtype<<(simdwidth*2)<<" b"<<rowB<<"_"<<colB<<" = "; if(storeb){ ss<<"ldsB["<<rowB<<"+lidy*wtile]["<<colB<<"];\n"; }else{ if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<",j*wtile+"<<rowB<<")))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<",j*wtile+"<<rowB<<")))"; } ss<<".s"; for(int s=0;s<simdwidth;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(j*wtile+"<<rowB<<")*ldbs + k + "<<colB<<"];\n"; } } } } for(int rowA=0;rowA<htile;rowA++){ for(int colA =0;colA<ktile/simdwidth;colA++){ ss<<" const "<<dtype<<(simdwidth*2)<<" a"<<rowA<<"_"<<colA<<" = "; if(storea){ ss<<"ldsA["<<rowA<<"+lidx*htile]["<<colA<<"];\n"; }else{ if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<",i*htile+"<<rowA<<")))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<",i*htile+"<<rowA<<")))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(i*htile+"<<rowA<<")*ldas +k + "<<colA<<"];\n"; } } } for(int colA =0;colA<ktile/simdwidth;colA++){ const int colB = colA; for(int rowB=0;rowB<wtile;rowB++){ ss<<" sum"<<rowA<<"_"<<rowB; ss<<" = fmaComplex"<<simdwidth<<"(a"<<rowA<<"_"<<colA<<",b"<<rowB<<"_"<<colB<<","; ss<<" sum"<<rowA<<"_"<<rowB; ss<<");\n"; } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; ss<<"}"<<endl; for (int i = 0; i < htile; i++) { for (int j = 0; j < wtile; j++) { ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]"; ss << "= mulComplex1(alpha,("; for(int s=0;s<simdwidth;s++){ ss<<"sum"<<i<<"_"<<j<<".s"; ss<<(2*s)<<(2*s+1); if(s<(simdwidth-1)) ss<<"+"; } ss<<"))+ mulComplex1(beta,"; ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]"; ss<<");\n"; } } //ss<<"}"<<endl; ss<<"}"<<endl; kernel = ss.str(); return true; } static bool genCkernelTNCons(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype, int simdwidth, bool storea, bool storeb, int maxLocalMemElems, int padding, string& kernel, bool useImageA = false, bool useImageB = false){ //cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll; //cout<<" "<<maxLocalMemElems<<" "<<endl; bool isDouble = (dtype.compare("double")==0) ? true:false; if(isDouble && simdwidth!=2 && (useImageA || useImageB)) return false; if(!isDouble && simdwidth!=4 && (useImageA || useImageB)) return false; //const int unroll = ktile; if(storea){ /*Number of rows of A per workgroup = ktile. Has to be divisble by lsizey. */ if(ktile%lsizex!=0) return false; /*Number of columns of A per workgroup = htile*lsizex*/ if((htile*lsizex)%(simdwidth*lsizey)!=0) return false; }else{ if(htile%simdwidth!=0) return false; } if(storeb){ /*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*simdwidth */ if(ktile%lsizex!=0) return false; if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false; }else{ if(wtile%simdwidth!=0) return false; } //cout<<"Check 2 passed"<<endl; if(wtile%simdwidth!=0 || htile%simdwidth!=0) return false; int numLocalMemElems = 0; if(storea) numLocalMemElems += ktile*(htile*lsizex+padding); if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding); if(numLocalMemElems>maxLocalMemElems) return false; //cout<<"Check 3 passed"<<endl; //if(ktile%unroll!=0) return false; //cout<<"Check 4 passed"<<endl; stringstream ss; ss<<"("; if(useImageA){ ss<<"__read_only image2d_t A,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,"; } if(useImageB){ ss<<"__read_only image2d_t B,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,"; } ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl; ss<<"const int htile ="<<htile<<";\n"; ss<<"const int wtile ="<<wtile<<";\n"; ss<<"const int ktile ="<<ktile<<";\n"; ss<<"const int simdwidth="<<simdwidth<<";\n"; ss<<"const int lx = "<<lsizex<<";\n"; ss<<"const int ly = "<<lsizey<<";\n"; ss<<"const int i = get_global_id(1);"<<endl; ss<<"const int j = get_global_id(0);"<<endl; //ss<<"const int unroll = "<<unroll<<";\n"; ss<<"const unsigned int lidx = get_local_id(1);"<<endl; ss<<"const unsigned int lidy = get_local_id(0);"<<endl; ss<<"int k;"<<endl; if(storea){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(ktile)<<"]["<<((htile/simdwidth)*lsizex+padding)<<"];"<<endl; } if(storeb){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl; } for(int x=0;x<htile;x++){ for(int y=0;y<wtile/simdwidth;y++){ ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n"; } } ss<<"for(k=0;k<K;k+=ktile){"<<endl; if(storea){ ss<<"const int gstartxA = get_group_id(1)*(htile/simdwidth)*lx;\n"; for(int y=0;y<(ktile/lsizex);y++){ for(int x=0;x<((htile*lsizex)/(simdwidth*lsizey));x++){ ss<<" ldsA["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = "; if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx )))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(lidy+"<<x<<"*ly+gstartxA,k+"<<y<<"*lx + lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(k+"<<y<<"*lx+lidx)*(lda/simdwidth)+ gstartxA + lidy + "<<x<<"*ly];\n"; } } } } if(storeb){ ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n"; for(int y=0;y<(ktile/lsizex);y++){ for(int x=0;x<((wtile*lsizey)/(simdwidth*lsizey));x++){ ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = "; if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(lidy + "<<x<<"*ly+gstartxB,k+"<<y<<"*lx +lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; //ss<<" for(kk=0;kk<ktile;kk+=unroll){\n"; ss<<"const int kk = 0;\n"; for(int y =0; y < ktile; y++){ for (int x = 0; x < wtile/simdwidth; x++) { ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << y << " = "; if(storeb){ ss << "ldsB[kk+"<<y<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n"; }else{ if(useImageB){ if(isDouble){ ss<<"as_double2( read_imagei(B,sampler,(int2)(j*(wtile/simdwidth)+"<<x<<",k+kk+"<<y<<")))"; }else{ ss<<"( read_imagef(B,sampler,(int2)(j*(wtile/simdwidth)+"<<x<<",k+kk+"<<y<<")))"; } ss<<".s"; for(int s=0;s<simdwidth;s++) ss<<s; ss<<";\n"; }else{ ss << "B[(k+kk+"<<y<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n"; } } } for (int x = 0; x < htile/simdwidth; x++) { ss << " const " << dtype << (simdwidth*2) << " a" << x << "_" << y << " = "; if(storea){ ss << "ldsA[kk+"<<y<<"]["<<"lidx*(htile/simdwidth)+"<<x<<"];\n"; }else{ if(useImageA){ if(isDouble) { ss<<"as_double2(read_imagei(A,sampler,(int2)(i*(htile/simdwidth)+"<<x<<",k+kk+"<<y<<")))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(i*(htile/simdwidth)+"<<x<<",k+kk+"<<y<<")))"; } ss<<".s"; for(int s=0;s<simdwidth;s++) ss<<s; ss<<";\n"; }else{ ss << "A[(k+kk+"<<y<<")*(lda/simdwidth)+i*(htile/simdwidth)+"<<x<<"];"<<endl; } } for(int xoff=0;xoff<simdwidth;xoff++){ int row = x*simdwidth + xoff; for(int w=0;w<wtile/simdwidth; w++){ ss<<" sum"<<row<<"_"<<w; ss<<" = fmaComplex"<<simdwidth<<"(a"<<x<<"_"<<y; if(simdwidth>1){ ss<<".s"; for(int m=0;m<simdwidth;m++) { ss<<(2*xoff)<<(2*xoff+1); } } ss<<",b"<<w<<"_"<<y<<","; ss<<" sum"<<row<<"_"<<w<<");\n"; } } } } //ss<<" }\n"; if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; ss<<"}"<<endl; for (int i = 0; i < htile; i++) { for (int j = 0; j < wtile; j++) { ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]"; ss << "= mulComplex1(alpha,sum"<<i<<"_"<<(j/simdwidth); if(simdwidth>1) ss<<".s"<<(2*(j%simdwidth))<<(2*(j%simdwidth)+1); ss<<") + "; ss << "mulComplex1(beta,C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]"; //ss<<"C[(i*"<<htile<<"+ i)*N + j*"<<wtile<<"+"<<offset<<"]"; ss << ");" << endl; } } ss<<"}"<<endl; kernel = ss.str(); return true; } static bool genCkernelNTOff(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype,int simdwidth, bool storea, bool storeb, int maxLocalMemElems, int padding,string& kernel, bool useImageA,bool useImageB){ //cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll; //cout<<" "<<maxLocalMemElems<<" "<<endl; if(storea){ /*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */ /*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */ if(ktile%(simdwidth*lsizey)!=0) return false; } if(storeb){ /*Number of columns of B per workgroup = ktile. Has to be divisble by lsizey*simdwidth */ if(ktile%(lsizey*simdwidth)!=0) return false; /*Number of rows of B per workgroup = wtile*lsizey. Has to be divisble by lsizex*/ if((wtile*lsizey)%lsizex!=0) return false; } //cout<<"Check 2 passed"<<endl; bool isDouble = (dtype.compare("double")==0); if(ktile%simdwidth!=0) return false; int numLocalMemElems = 0; if(storea) numLocalMemElems += htile*lsizex*(ktile+padding); if(storeb) numLocalMemElems += wtile*lsizey*(ktile+padding); if(numLocalMemElems>maxLocalMemElems) return false; //cout<<"Check 3 passed"<<endl; //cout<<"Check 4 passed"<<endl; stringstream ss; ss<<"("; if(useImageA){ ss<<"__read_only image2d_t A,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,"; } if(useImageB){ ss<<"__read_only image2d_t B,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,"; } ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl; ss<<"const int htile ="<<htile<<";\n"; ss<<"const int wtile ="<<wtile<<";\n"; ss<<"const int ktile ="<<ktile<<";\n"; ss<<"const int simdwidth="<<simdwidth<<";\n"; ss<<"const int lx = "<<lsizex<<";\n"; ss<<"const int ly = "<<lsizey<<";\n"; ss<<"const int i = get_global_id(1);\n"; ss<<"const int j = get_global_id(0);\n"; ss<<"const unsigned int lidx = get_local_id(1);"<<endl; ss<<"const unsigned int lidy = get_local_id(0);"<<endl; ss<<"unsigned int k;"<<endl; if(storea){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl; } if(storeb){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(wtile*lsizey)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl; } for(int x=0;x<htile;x++){ for(int y=0;y<wtile;y++){ ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n"; } } ss<<"const unsigned int ldbs = ldb/simdwidth;\n"; ss<<"const unsigned int ldas = lda/simdwidth;\n"; ss<<"for(k=0;k<K/simdwidth;k+=(ktile/simdwidth)){"<<endl; if(storea){ ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n"; for(int rowA=0;rowA<htile;rowA++){ for(int colA=0;colA<(ktile/(lsizey*simdwidth));colA++){ ss<<" ldsA["<<rowA<<"*lx + lidx]["<<colA<<"*ly + lidy] = "; if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<"*ly+lidy,gstartxA+"<<rowA<<"*lx+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(gstartxA+"<<rowA<<"*lx + lidx)*(lda/simdwidth) + k + "<<colA<<"*ly + lidy];\n"; } } } } if(storeb){ ss<<"const int gstartxB = get_group_id(0)*wtile*ly;\n"; for(int rowB=0;rowB<(wtile*lsizey)/lsizex;rowB++){ for(int colB=0;colB<(ktile/(lsizey*simdwidth));colB++){ ss<<" ldsB["<<rowB<<"*lx + lidx]["<<colB<<"*ly + lidy] = "; if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<"*ly+lidy,gstartxB+"<<rowB<<"*lx+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(gstartxB+"<<rowB<<"*lx + lidx)*(ldb/simdwidth) + k + "<<colB<<"*ly + lidy];\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; for(int rowB =0;rowB<wtile;rowB++){ for(int colB = 0;colB<ktile/simdwidth;colB++){ ss<<" const "<<dtype<<(simdwidth*2)<<" b"<<rowB<<"_"<<colB<<" = "; if(storeb){ ss<<"ldsB["<<rowB<<"*ly+lidy]["<<colB<<"];\n"; }else{ if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(k+"<<colB<<",get_group_id(0)*wtile*ly+"<<rowB<<"*ly+lidy)))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(k+"<<colB<<",get_group_id(0)*wtile*ly+"<<rowB<<"*ly+lidy)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(get_group_id(0)*wtile*ly + "<<rowB<<"*ly + lidy)*ldbs + k + "<<colB<<"];\n"; } } } } for(int rowA=0;rowA<htile;rowA++){ for(int colA =0;colA<ktile/simdwidth;colA++){ ss<<" const "<<dtype<<(simdwidth*2)<<" a"<<rowA<<"_"<<colA<<" = "; if(storea){ ss<<"ldsA["<<rowA<<"*lx+lidx]["<<colA<<"];\n"; }else{ if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k+"<<colA<<",get_group_id(1)*htile*lx+"<<rowA<<"*lx+lidx)))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k+"<<colA<<",get_group_id(1)*htile*lx+"<<rowA<<"*lx+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(get_group_id(1)*htile*lx+ "<<rowA<<"*lx+lidx )*ldas +k + "<<colA<<"];\n"; } } const int colB = colA; for(int rowB=0;rowB<wtile;rowB++){ ss<<" sum"<<rowA<<"_"<<rowB; ss<<" = fmaComplex"<<simdwidth<<"(a"<<rowA<<"_"<<colA<<",b"<<rowB<<"_"<<colB<<","; ss<<" sum"<<rowA<<"_"<<rowB; ss<<");\n"; } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; ss<<"}"<<endl; ss<<"const unsigned int Cx = get_group_id(1)*htile*lx;"<<endl; ss<<"const unsigned int Cy = get_group_id(0)*wtile*ly;"<<endl; for (int i = 0; i < htile; i++) { for (int j = 0; j < wtile; j++) { ss << "C[(Cx + " << i<< "*lx + lidx)*ldc + Cy + " << j << "*ly + lidy]"; ss << "= mulComplex1(alpha,("; for(int s=0;s<simdwidth;s++){ ss<<"sum"<<i<<"_"<<j; ss<<".s"<<(2*s)<<(2*s+1); if(s<(simdwidth-1)) ss<<"+"; } ss<<"))+ mulComplex1(beta,("; ss << "C[(Cx + " << i<< "*lx + lidx)*ldc + Cy + " << j << "*ly + lidy]"; ss<<"));\n"; } } //ss<<"}"<<endl; ss<<"}"<<endl; kernel = ss.str(); return true; } static bool genCkernelNNCons(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype, int simdwidth, bool storea, bool storeb, int maxLocalMemElems, int padding, string& kernel,bool useImageA,bool useImageB){ bool isDouble = (dtype.compare("double")==0); //cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll; //cout<<" "<<maxLocalMemElems<<" "<<endl; if(storea){ /*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */ /*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */ if(ktile%(simdwidth*lsizey)!=0) return false; } if(storeb){ /*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizey*simdwidth */ if(ktile%lsizex!=0) return false; if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false; } //cout<<"Check 2 passed"<<endl; if(wtile%simdwidth!=0 || ktile%simdwidth!=0) return false; if(!storea && !storeb && ktile>simdwidth) return false; int numLocalMemElems = 0; if(storea) numLocalMemElems += htile*lsizex*(ktile+padding); if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding); if(numLocalMemElems>maxLocalMemElems) return false; //cout<<"Check 3 passed"<<endl; //cout<<"Check 4 passed"<<endl; stringstream ss; ss<<"("; if(useImageA){ ss<<"__read_only image2d_t A,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,"; } if(useImageB){ ss<<"__read_only image2d_t B,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,"; } ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl; ss<<"const int htile ="<<htile<<";\n"; ss<<"const int wtile ="<<wtile<<";\n"; ss<<"const int ktile ="<<ktile<<";\n"; ss<<"const int simdwidth="<<simdwidth<<";\n"; ss<<"const int lx = "<<lsizex<<";\n"; ss<<"const int ly = "<<lsizey<<";\n"; ss<<"const int i = get_global_id(1);"<<endl; ss<<"const int j = get_global_id(0);"<<endl; ss<<"const unsigned int lidx = get_local_id(1);"<<endl; ss<<"const unsigned int lidy = get_local_id(0);"<<endl; ss<<"int k;"<<endl; if(storea){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl; } if(storeb){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl; } for(int x=0;x<htile;x++){ for(int y=0;y<wtile/simdwidth;y++){ ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n"; } } ss<<"for(k=0;k<K;k+=ktile){"<<endl; if(storea){ ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n"; for(int x=0;x<htile;x++){ for(int y=0;y<(ktile/(lsizey*simdwidth));y++){ ss<<" ldsA["<<x<<"*lx + lidx]["<<y<<"*ly + lidy] = "; if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth +"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(gstartxA+"<<x<<"*lx + lidx)*(lda/simdwidth) + k/simdwidth + "<<y<<"*ly + lidy];\n"; } } } } if(storeb){ ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n"; for(int x=0;x<(wtile/simdwidth);x++){ for(int y=0;y<(ktile/lsizex);y++){ ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = "; if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; /*for (int x = 0; x < wtile/simdwidth; x++) { for (int y = 0; y < ktile; y++) { ss << " const " << dtype << simdwidth << " b" << x << "_" << y << " = "; if(storeb){ ss << "ldsB["<<y<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n"; }else{ ss << "B[(k+"<<y<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n"; } } }*/ for (int k = 0; k < ktile/simdwidth; k++) { for (int koff = 0; koff < simdwidth; koff++) { for (int x = 0; x < wtile/simdwidth; x++) { int rowB = k*simdwidth+koff; ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << rowB << " = "; if(storeb){ ss << "ldsB["<<rowB<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n"; }else{ if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(j*(wtile/simdwidth) + "<<x<<",k+"<<rowB<<")))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(j*(wtile/simdwidth) + "<<x<<",k+"<<rowB<<")))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss << "B[(k+"<<rowB<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n"; } } } } for(int y =0; y < htile; y++){ ss << " const " << dtype << (simdwidth*2) << " a" << k << "_" << y << " = "; if(storea){ ss << "ldsA["<<y<<"+lidx*htile]["<<k<<"];\n"; }else{ if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth +"<<k<<",i*htile+"<<y<<")))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<k<<",i*htile + "<<y<<")))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss << "A[(i*htile + "<<y<<")*(lda/simdwidth) + k/simdwidth+"<<k<<"];"<<endl; } } for(int koff=0;koff<simdwidth;koff++){ int rowB = (k*simdwidth+koff); for(int x = 0;x<(wtile/simdwidth);x++){ ss<<"sum"<<y<<"_"<<x<<" = fmaComplex"<<simdwidth<<"(a"<<k<<"_"<<y; ss<<".s"; for(int t=0;t<simdwidth;t++) ss<<(2*koff)<<(2*koff+1); ss<<",b"<<x<<"_"<<rowB<<","; ss<<"sum"<<y<<"_"<<x<<");\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; ss<<"}"<<endl; for (int i = 0; i < htile; i++) { for (int j = 0; j < wtile; j++) { ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "]"; ss << "= mulComplex1(alpha,sum"<<i<<"_"<<(j/simdwidth); ss<<".s"<<2*(j%simdwidth)<<(2*(j%simdwidth)+1); ss<<") + mulComplex1(beta,"; ss << "C[(i*" << htile << "+ " << i << ")*ldc + j*" << wtile << "+" << j << "])"; ss << ";" << endl; } } ss<<"}"<<endl; kernel = ss.str(); return true; } static bool genCkernelNNOff(int lsizex, int lsizey, int htile, int wtile, int ktile, string dtype, int simdwidth, bool storea, bool storeb, int maxLocalMemElems, int padding, string& kernel,bool useImageA,bool useImageB){ bool isDouble = (dtype.compare("double")==0); //cout<<"StoreA "<<storea<<" "<<"StoreB "<<storeb<<" "<<htile<<" "<<wtile<<" "<<" "<<ktile<<" "<<simdwidth<<" "<<lsizex<<" "<<lsizey<<" "<<unroll; //cout<<" "<<maxLocalMemElems<<" "<<endl; if(storea){ /*Number of rows of A per workgroup = htile*lsizex. Has to be divisble by lsizex. Trivially satisfied */ /*Number of columns of A per workgroup = ktile. Has to be divisble by lsizey*simdwidth */ if(ktile%(simdwidth*lsizey)!=0) return false; } if(storeb){ /*Number of columns of B per workgroup = wtile*lsizey. Has to be divisble by lsizey*simdwidth */ if(ktile%lsizex!=0) return false; if(((wtile*lsizey)%(lsizey*simdwidth))!=0) return false; } //cout<<"Check 2 passed"<<endl; if(wtile%simdwidth!=0 || ktile%simdwidth!=0) return false; if(!storea && !storeb && ktile>simdwidth) return false; int numLocalMemElems = 0; if(storea) numLocalMemElems += htile*lsizex*(ktile+padding); if(storeb) numLocalMemElems += ktile*(wtile*lsizey+padding); if(numLocalMemElems>maxLocalMemElems) return false; //cout<<"Check 3 passed"<<endl; //cout<<"Check 4 passed"<<endl; stringstream ss; ss<<"("; if(useImageA){ ss<<"__read_only image2d_t A,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict A,"; } if(useImageB){ ss<<"__read_only image2d_t B,"; }else{ ss<<"const __global "<<dtype<<(simdwidth*2)<<" *restrict B,"; } ss<<"__global "<<dtype<<"2 *restrict C,unsigned int lda,unsigned int ldb,unsigned int ldc,unsigned int K,"<<dtype<<"2 alpha,"<<dtype<<"2 beta){"<<endl; ss<<"const int htile ="<<htile<<";\n"; ss<<"const int wtile ="<<wtile<<";\n"; ss<<"const int ktile ="<<ktile<<";\n"; ss<<"const int simdwidth="<<simdwidth<<";\n"; ss<<"const int lx = "<<lsizex<<";\n"; ss<<"const int ly = "<<lsizey<<";\n"; ss<<"const int i = get_global_id(1);"<<endl; ss<<"const int j = get_global_id(0);"<<endl; ss<<"const unsigned int lidx = get_local_id(1);"<<endl; ss<<"const unsigned int lidy = get_local_id(0);"<<endl; ss<<"int k;"<<endl; if(storea){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsA["<<(htile*lsizex)<<"]["<<((ktile/simdwidth)+padding)<<"];"<<endl; } if(storeb){ ss<<"__local "<<dtype<<(simdwidth*2)<<" ldsB["<<(ktile)<<"]["<<((wtile/simdwidth)*lsizey+padding)<<"];"<<endl; } for(int x=0;x<htile;x++){ for(int y=0;y<wtile/simdwidth;y++){ ss<<dtype<<(simdwidth*2)<<" sum"<<x<<"_"<<y<<" = ("<<dtype<<(simdwidth*2)<<")(0);\n"; } } ss<<"for(k=0;k<K;k+=ktile){"<<endl; if(storea){ ss<<"const int gstartxA = get_group_id(1)*htile*lx;\n"; for(int x=0;x<htile;x++){ for(int y=0;y<(ktile/(lsizey*simdwidth));y++){ ss<<" ldsA["<<x<<"*lx + lidx]["<<y<<"*ly + lidy] = "; if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth +"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<y<<"*ly+lidy,gstartxA+"<<x<<"*lx+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"A[(gstartxA+"<<x<<"*lx + lidx)*(lda/simdwidth) + k/simdwidth + "<<y<<"*ly + lidy];\n"; } } } } if(storeb){ ss<<"const int gstartxB = get_group_id(0)*(wtile/simdwidth)*ly;\n"; for(int x=0;x<(wtile/simdwidth);x++){ for(int y=0;y<(ktile/lsizex);y++){ ss<<" ldsB["<<y<<"*lx + lidx]["<<x<<"*ly + lidy] = "; if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(gstartxB + lidy + "<<x<<"*ly,k+"<<y<<"*lx +lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss<<"B[(k+"<<y<<"*lx+lidx)*(ldb/simdwidth)+ gstartxB + lidy + "<<x<<"*ly];\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; /*for (int x = 0; x < wtile/simdwidth; x++) { for (int y = 0; y < ktile; y++) { ss << " const " << dtype << simdwidth << " b" << x << "_" << y << " = "; if(storeb){ ss << "ldsB["<<y<<"][lidy*(wtile/simdwidth)+"<<x<<"];\n"; }else{ ss << "B[(k+"<<y<<")*(ldb/simdwidth)+j*(wtile/simdwidth)+"<<x<<"];\n"; } } }*/ for (int k = 0; k < ktile/simdwidth; k++) { for (int koff = 0; koff < simdwidth; koff++) { for (int x = 0; x < wtile/simdwidth; x++) { int rowB = k*simdwidth+koff; ss << " const " << dtype << (simdwidth*2) << " b" << x << "_" << rowB << " = "; if(storeb){ ss << "ldsB["<<rowB<<"][lidy+ly*"<<x<<"];\n"; }else{ if(useImageB){ if(isDouble){ ss<<"as_double2(read_imagei(B,sampler,(int2)(get_group_id(0)*(wtile/simdwidth)*ly + lidy+"<<x<<"*ly,k+"<<rowB<<")))"; }else{ ss<<"(read_imagef(B,sampler,(int2)(get_group_id(0)*(wtile/simdwidth)*ly + lidy+"<<x<<"*ly,k+"<<rowB<<")))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss << "B[(k+"<<rowB<<")*(ldb/simdwidth)+get_group_id(0)*(wtile/simdwidth)*ly + lidy+"<<x<<"*ly];\n"; } } } } for(int y =0; y < htile; y++){ ss << " const " << dtype << (simdwidth*2) << " a" << k << "_" << y << " = "; if(storea){ ss << "ldsA["<<y<<"*lx+lidx]["<<k<<"];\n"; }else{ if(useImageA){ if(isDouble){ ss<<"as_double2(read_imagei(A,sampler,(int2)(k/simdwidth+"<<k<<",get_group_id(1)*htile*lx + lx*"<<y<<"+lidx)))"; }else{ ss<<"(read_imagef(A,sampler,(int2)(k/simdwidth+"<<k<<",get_group_id(1)*htile*lx + lx*"<<y<<"+lidx)))"; } ss<<".s"; for(int s=0;s<simdwidth*2;s++) ss<<s; ss<<";\n"; }else{ ss << "A[(get_group_id(1)*htile*lx + lx*"<<y<<"+lidx)*(lda/simdwidth) + k/simdwidth+"<<k<<"];"<<endl; } } for(int koff=0;koff<simdwidth;koff++){ int rowB = (k*simdwidth+koff); for(int x = 0;x<(wtile/simdwidth);x++){ ss<<"sum"<<y<<"_"<<x<<" = fmaComplex"<<simdwidth<<"(a"<<k<<"_"<<y; ss<<".s"; for(int t=0;t<simdwidth;t++) ss<<(2*koff)<<(2*koff+1); ss<<",b"<<x<<"_"<<rowB<<","; ss<<"sum"<<y<<"_"<<x<<");\n"; } } } } if(storea || storeb) ss<<" barrier(CLK_LOCAL_MEM_FENCE);"<<endl; ss<<"}"<<endl; ss<<"const unsigned int Cx = get_group_id(1)*htile*lx;"<<endl; ss<<"const unsigned int Cy = get_group_id(0)*wtile*ly;"<<endl; for (int i = 0; i < htile; i++) { for (int j = 0; j < wtile; j++) { ss << "C[( Cx+ lidx+lx*"<< i << ")*ldc + Cy + simdwidth*lidy + simdwidth*ly*" << j/simdwidth << "+"<<(j%simdwidth)<<"]"; ss << "= mulComplex1(alpha,sum"<<i<<"_"<<(j/simdwidth); const int off = j%simdwidth; ss<<".s"<<(2*off)<<(2*off+1); ss<<") + mulComplex1(beta,"; ss << "C[( Cx+ lidx+lx*"<< i << ")*ldc + Cy + simdwidth*lidy + simdwidth*ly*" << j/simdwidth << "+"<<(j%simdwidth)<<"])"; //ss<<"C[(i*"<<htile<<"+ i)*N + j*"<<wtile<<"+"<<offset<<"]"; ss << ";" << endl; } } ss<<"}"<<endl; kernel = ss.str(); return true; } template <typename T> static double testGemmComplex(unsigned int N,cl_device_id dvc,cl_context ctx,cl_kernel krnl, RaijinGemmOptKernel& optkernel, RaijinTranspose *transObj, RaijinCopy *copyObj, RaijinScale *scaleObj,bool verify=true){ typedef typename T::ctype ctype; typedef typename T::basetype basetype; size_t size = sizeof(ctype) * N * N; cl_mem bufA, bufB, bufC; ctype *ptrA = new ctype[N * N]; ctype *ptrB = new ctype[N * N]; ctype *ptrC = new ctype[N * N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { if(optkernel.transA){ ptrA[i * N + j].s[0] = 0.002 * j; ptrA[i*N +j].s[1] = 1; }else{ ptrA[i*N + j].s[0] = 0.002*i; ptrA[i*N+j].s[1] = 1; } if(optkernel.transB){ ptrB[i * N + j].s[0] = 0.002 * i; ptrB[i*N+j].s[1] = 1; }else{ ptrB[i*N + j].s[0] = 0.002*j; ptrB[i*N+j].s[1] = 1; } ptrC[i * N + j].s[0] = 0; ptrC[i*N+j].s[1] = 0; } } cl_command_queue q = clCreateCommandQueue(ctx,dvc,0,NULL); cl_int errcode; bufA = clCreateBuffer(ctx, CL_MEM_READ_ONLY, size, NULL, &errcode); bufB = clCreateBuffer(ctx, CL_MEM_READ_ONLY, size, NULL, &errcode); bufC = clCreateBuffer(ctx, CL_MEM_READ_WRITE, size, NULL, &errcode); clEnqueueWriteBuffer(q, bufA, CL_TRUE, 0, size, ptrA, 0, NULL, NULL); clEnqueueWriteBuffer(q, bufB, CL_TRUE, 0, size, ptrB, 0, NULL, NULL); clEnqueueWriteBuffer(q, bufC, CL_TRUE, 0, size, ptrC, 0, NULL, NULL); clFlush( q); const int niters = 3; double tdiff = 0; for(int i=0;i<niters;i++){ RTimer rt; rt.start(); ctype alpha; alpha.s[0] = 1; alpha.s[1] = 0; ctype beta; beta.s[0] = 0; beta.s[1] = 0; RaijinCleaner *cleaner = new RaijinCleaner; cl_event evt = raijinApplyOpt<ctype>(q,cleaner,krnl,optkernel,ctx,dvc,RaijinCL::RaijinRowMajor,optkernel.transA,optkernel.transB,N,N,N, alpha,bufA,N,bufB,N,beta,bufC,N,transObj,copyObj,scaleObj); clFinish(q); delete cleaner; rt.stop(); if(i>0){ tdiff += rt.getDiff(); cout<<rt.getDiff()<<endl; } } tdiff /= (niters-1); if(verify){ clEnqueueReadBuffer(q, bufC, CL_TRUE, 0, size, ptrC, 0, NULL, NULL); double totalerror = 0.0; for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ basetype calc = ptrC[i*N+j].s[0]; basetype expected = N*((0.002*i)*(0.002*j)-1); double val = calc - expected; if(val<0) val = -val; //if(val>1) cout<<"Real: "<<i<<" "<<j<<" "<<calc<<" "<<expected<<endl; //if(val>1) exit(-1); basetype calcimg = ptrC[i*N+j].s[1]; basetype expimg = N*(0.002*i+0.002*j); double valimg = calcimg - expimg; if(valimg<0) valimg *= -1; totalerror += (val+valimg); } } double avgerror = (totalerror)/(N*N); cout<<"Avg absolute error "<<(totalerror/(N*N))<<endl; //if(avgerror>1.0) exit(-1); } clReleaseMemObject(bufA); clReleaseMemObject(bufB); clReleaseMemObject(bufC); delete[] ptrA; delete[] ptrB; delete[] ptrC; clReleaseCommandQueue(q); return 8.0e-9*N*(1.0*N)*(1.0*N)/tdiff; } string genCmulFuncs(bool isDouble){ string dtype = (isDouble)? "double":"float"; stringstream ss; //mulComplex1 if(isDouble){ ss<<"#ifdef cl_khr_fp64\n"<<endl; ss<<"#pragma OPENCL EXTENSION cl_khr_fp64 : enable"<<endl; ss<<"#else"<<endl; ss<<"#pragma OPENCL EXTENSION cl_amd_fp64 : enable"<<endl; ss<<"#endif"<<endl; } ss<<dtype<<"2 mulComplex1("<<dtype<<"2 a,"<<dtype<<"2 b){"<<endl; ss<<dtype<<"2 c;"<<endl; //if(isDouble) ss<<"#ifndef FP_FAST_FMAF"<<endl; //ss<<"c.x = a.x*b.x - a.y*b.y;"<<endl; //if(isDouble){ //ss<<"#else"<<endl; ss<<dtype<<" temp = -a.y*b.y;"<<endl; ss<<"c.x = fma(a.x,b.x,temp);"<<endl; //ss<<"#endif"<<endl; //} //if(isDouble) ss<<"#ifndef FP_FAST_FMAF"<<endl; //ss<<"c.y = a.x*b.y + a.y*b.x;"<<endl; //if(isDouble){ //ss<<"#else"<<endl; ss<<dtype<<" temp2 = a.y*b.x;"<<endl; ss<<"c.y = fma(a.x,b.y,temp2);"<<endl; //ss<<"#endif"<<endl; //} ss<<"return c;\n}"<<endl; //mulComplex2 ss<<dtype<<"4 mulComplex2("<<dtype<<"4 a,"<<dtype<<"4 b){"<<endl; ss<<dtype<<"4 c;"<<endl; ss<<"c.s01 = mulComplex1(a.s01,b.s01); c.s23 = mulComplex1(a.s23,b.s23);"<<endl; ss<<"return c;\n}"<<endl; //fmaComplex1 ss<<dtype<<"2 fmaComplex1("<<dtype<<"2 a,"<<dtype<<"2 b,"<<dtype<<"2 c){"<<endl; ss<<" "<<dtype<<"2 res;"<<endl; if(isDouble) ss<<"#ifndef FP_FAST_FMAF"<<endl; ss<<" res.x = a.x*b.x + c.x;"<<endl; ss<<" res.y = a.x*b.y + c.y;"<<endl; ss<<" res.x = -a.y*b.y + res.x;"<<endl; ss<<" res.y = a.y*b.x + res.y;"<<endl; if(isDouble){ ss<<"#else"<<endl; ss<<" res.x = fma(-a.y,b.y,c.x);"<<endl; ss<<" res.y = fma(a.y,b.x,c.y);"<<endl; ss<<" res.x = fma(a.x,b.x,res.x);"<<endl; ss<<" res.y = fma(a.x,b.y,res.y);"<<endl; ss<<"#endif"<<endl; } ss<<" return res;"<<endl; ss<<"}"<<endl; //fmaComplex2 ss<<dtype<<"4 fmaComplex2("<<dtype<<"4 a,"<<dtype<<"4 b,"<<dtype<<"4 c){"<<endl; ss<<dtype<<"4 res;"<<endl; ss<<"res.s01 = fmaComplex1(a.s01,b.s01,c.s01); res.s23 = fmaComplex1(a.s23,b.s23,c.s23);"<<endl; ss<<"return res;\n}"<<endl; /*ss<<dtype<<"2 are = a.s02,aim =a.s13;\n"; ss<<dtype<<"2 bre = b.s02,bim= b.s13;\n"; ss<<dtype<<"2 cre = c.s02,cim =c.s13;\n"; ss<<dtype<<"2 rre = are*bre+cre; rre = -aim*bim+rre;\n"; ss<<dtype<<"2 rim = are*bim+cim; rim = bre*aim+rim;\n"; ss<<"rre = -aim*bim + rre;\n"<<endl; ss<<"rim = bre*aim + rim;\n"; ss<<dtype<<"4 res; res.s02 = rre; res.s13 = rim;\n"; ss<<"return res;\n}";*/ return ss.str(); } template <typename T> static void tuneGemmComplex(cl_context ctx, cl_device_id dvc,RaijinGemmOptKernel *optparams,unsigned int N,double *gflopbest){ cout<<"Inside tuneGemmCache"<<endl; cout<<"Tuning "<<T::gemmName()<<endl; cl_int errcode; cl_command_queue q = clCreateCommandQueue(ctx,dvc,0,&errcode); if(errcode!=CL_SUCCESS) cout<<"Error creating queue"<<endl; typedef typename T::ctype ctype; size_t size = sizeof(ctype)*N*N; int htiles[] = {2,4,4,8,4}; int wtiles[] = {4,2,4,4,8}; int ktiles[] = {1,2,4,8,16,32}; int simdwidths[] = {1,2,4,8}; int lsizesX[] = {4,8,8,4,16,16}; int lsizesY[] = {8,4,8,16,4,16}; int unrolls[] = {1,2,4,8}; bool storeA[] = {true, false}; bool storeB[] = {true, false}; bool useImageA[] = {true,false}; bool useImageB[] = {true,false}; bool initialized = false; //double tbest = 0.0; string prgmbest; *gflopbest = 0.0; cl_device_type dvctype; cl_ulong lmemSize; cl_device_local_mem_type ltype; clGetDeviceInfo(dvc,CL_DEVICE_TYPE,sizeof(dvctype),&dvctype,NULL); clGetDeviceInfo(dvc,CL_DEVICE_LOCAL_MEM_SIZE,sizeof(lmemSize),&lmemSize,NULL); clGetDeviceInfo(dvc,CL_DEVICE_LOCAL_MEM_TYPE,sizeof(ltype),&ltype,NULL); RaijinTranspose transObj(dvc,ctx); RaijinCopy copyObj(ctx,dvc); RaijinScale scaleObj(ctx,dvc); cl_uint vecWidth; if(T::isDouble()) clGetDeviceInfo(dvc,CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE,sizeof(cl_uint),&vecWidth,NULL); else clGetDeviceInfo(dvc,CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT,sizeof(cl_uint),&vecWidth,NULL); bool imgA[] = {true,false}; bool imgB[] = {true,false}; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { for (int simdidx = 0; simdidx < 2;simdidx++) { for (int ktileidx = 0; ktileidx < 5; ktileidx++) { for(int sa = 0 ; sa<1; sa++){ for(int sb = 0; sb <1 ; sb++){ for(int imgAidx=0;imgAidx<2;imgAidx++){ for(int imgBidx=0;imgBidx<2;imgBidx++){ //if(T::isDouble() && simdidx>0) continue; int ktile = ktiles[ktileidx]; const int unr = ktile; //cout<<s<<" "<<bfidx<<" "<<splits[s]<<" "<<bfirsts[bfidx]<<endl; bool isAggregate = false; bool storec = false; int htile = htiles[i]; int wtile = wtiles[i]; bool useImageA = imgA[imgAidx]; bool useImageB = imgB[imgBidx]; bool transA = true; bool transB = false; if(dvctype!=CL_DEVICE_TYPE_GPU && (useImageA || useImageB)) continue; if(ltype!=CL_LOCAL && (storeA[sa] || storeB[sb])) continue; string body; const int simd = simdwidths[simdidx]; //if(dvctype==CL_DEVICE_TYPE_CPU && simd!=vecWidth) continue; if(dvctype==CL_DEVICE_TYPE_GPU){ if(T::isDouble() && simd>2) continue; else if(!(T::isDouble()) && simd>4) continue; } int regest = 2*(htile * wtile + htile * simd + wtile * simd); if(regest>128) continue; string dtype = T::name(); int lx, ly; lx = lsizesX[j]; ly = lsizesY[j]; unsigned int nVecRegs = htile*wtile; nVecRegs += (htile>wtile) ? (wtile/simd) : (htile/simd); //if(dvctype==CL_DEVICE_TYPE_CPU && nVecRegs>16) continue; bool kernSuc = genCkernelTNOff(lx,ly,htile, wtile, ktile,dtype, simd, storeA[sa],storeB[sb],lmemSize/(sizeof(ctype)) ,1,body,useImageA,useImageB); /*unsigned int nVecRegs = htile*wtile/simd; nVecRegs += (htile>wtile) ? (wtile/simd) : (htile/simd); if(dvctype==CL_DEVICE_TYPE_CPU && nVecRegs>16) continue; bool kernSuc = genKernelTNCons(lx,ly,htile, wtile, ktile,dtype, simd, storeA[sa],storeB[sb],lmemSize/(sizeof(realtype)) ,1,body,useImageA,useImageB);*/ if(!kernSuc) continue; //cout<<body<<endl; stringstream kernelstream; stringstream namestream; namestream << T::gemmName() << i << "_" << j << "_" << simdidx << "_" << ktileidx << "_" << sa << "_" <<sb<<"_"<<imgAidx<<"_"<<imgBidx; string kname = namestream.str(); kernelstream<<genCmulFuncs(T::isDouble())<<endl; if(useImageA || useImageB){ kernelstream<<"__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;"<<endl; kernelstream<<"float4 myread_imagef(__read_only image2d_t img,int2 pos){ return read_imagef(img,sampler,pos);\n}"<<endl; } kernelstream<<"__kernel "; if(isAggregate){ kernelstream<<"__attribute__((reqd_work_group_size(1,1,1))) "<<endl; }else{ kernelstream<<"__attribute__((reqd_work_group_size("<<ly<<","<<lx<<",1))) "<<endl; } kernelstream <<"void " << kname; kernelstream << body; string kernelsrc = kernelstream.str(); string klogname = kname +".cl"; ofstream klog(klogname.c_str()); klog<<kernelsrc<<endl; klog.close(); const size_t len = kernelsrc.length(); cl_int errcode1, errcode2; RTimer rt1, rt2, rt3; rt1.start(); const char *srcbuf = kernelsrc.c_str(); cl_program prg = clCreateProgramWithSource(ctx, 1, &srcbuf, (const size_t*) &len, &errcode1); cl_int bldcode = clBuildProgram(prg, 1, &dvc, "", NULL, NULL); cl_kernel krnl = clCreateKernel(prg, kname.c_str(), &errcode2); rt1.stop(); cout<<"Compile time "<<rt1.getDiff()<<endl; if (errcode1 != CL_SUCCESS || errcode2 != CL_SUCCESS || bldcode != CL_SUCCESS) { /*cl::Program prgmcpp(prg); const cl::Device dvccpp(dvc); string buildlog = prgmcpp.getBuildInfo<CL_PROGRAM_BUILD_LOG>(dvccpp); cout<<buildlog<<endl;*/ size_t retbytes; cout << "Error creating program from source " << errcode1 << " " << errcode2 << " " << bldcode << endl; clGetProgramBuildInfo(prg, dvc, CL_PROGRAM_BUILD_LOG, 0, NULL, &retbytes); char *buildlog = new char[retbytes+1]; clGetProgramBuildInfo(prg,dvc,CL_PROGRAM_BUILD_LOG,retbytes,buildlog,NULL); cout << "Buildlog " << retbytes<<" "<<buildlog << endl; //cout << "Error creating program from source " << errcode1 << " " << errcode2 << " " << bldcode << endl; cout << kernelsrc << endl; exit(-1); continue; } else { //string fname = kname+".cl"; //ofstream of(fname.c_str()); //of<<kernelsrc<<endl; //of.close(); //cout<<"Time taken to compile "<<rt1.getDiff()<<endl; RaijinGemmOptKernel candidate; candidate.transA = transA; candidate.transB = transB; candidate.simdwidth = simd; candidate.htile = htile; candidate.wtile = wtile; candidate.ktile = ktile; candidate.lsizex = lx; candidate.lsizey = ly; candidate.kernel = kernelsrc; candidate.kname = kname; candidate.imageA = useImageA; candidate.imageB = useImageB; double gflops; size_t tuneSize = 2048; gflops = testGemmComplex<T>(tuneSize, dvc, ctx, krnl,candidate,&transObj,&copyObj,&scaleObj,true); clReleaseKernel(krnl); clReleaseProgram(prg); double bwidth = (htile+wtile)*gflops*sizeof(ctype)/(8*htile*wtile); cout<<"htile "<<htile<<" wtile "<<wtile<<" ktile "<<(ktile); cout<<" lx "<<lx<<" ly "<<ly<<" simd "<<simd<<" storeA? "<<storeA[sa]<<" storeB? "<<storeB[sb]; cout<<" ImageA? "<<useImageA<<" ImageB? "<<useImageB<<endl; if (!initialized || (gflops > (*gflopbest)) && (gflops < 2500)) { *optparams = candidate; *gflopbest = gflops; initialized = true; } cout << "Gflops " << gflops << " Bwidth "<< bwidth<<" Best So Far "<<(*gflopbest)<<" "<<kname<<endl; } } } } } } } } } clReleaseCommandQueue(q); } template <typename T> bool tuneGemmComplex(cl_platform_id platform, cl_device_id dvc,RaijinGemmOptKernel *optkernel,unsigned int N=1024){ cout<<"Inside tuneGemm"<<endl; cl_context_properties conprop[3]; conprop[0] = CL_CONTEXT_PLATFORM; conprop[1] = (cl_context_properties)platform; conprop[2] = (cl_context_properties)0; cl_int errcode; cl_context ctx = clCreateContext(conprop,1,&dvc,NULL,NULL,&errcode); if(errcode==CL_SUCCESS){ double gflopbest=0.0; tuneGemmComplex<T>(ctx,dvc,optkernel,N,&gflopbest); }else{ cout<<"Could not successfully create context for this device"<<endl; return false; } clReleaseContext(ctx); return true; } void RaijinCL::raijinTuneZgemm(cl_device_id dvc){ RaijinGemmOptKernel zgemmParams; cl_platform_id platform; clGetDeviceInfo(dvc,CL_DEVICE_PLATFORM,sizeof(cl_platform_id),&platform,NULL); string zpath = raijinGetProfileFileName(dvc,"zgemm"); ofstream zfile(zpath.c_str()); tuneGemmComplex<GemmCdouble>(platform,dvc,&zgemmParams); zfile<<zgemmParams<<endl; zfile.close(); } void RaijinCL::raijinTuneCgemm(cl_device_id dvc){ RaijinGemmOptKernel cgemmParams; cl_platform_id platform; clGetDeviceInfo(dvc,CL_DEVICE_PLATFORM,sizeof(cl_platform_id),&platform,NULL); string cpath = raijinGetProfileFileName(dvc,"cgemm"); ofstream cfile(cpath.c_str()); tuneGemmComplex<GemmCsingle>(platform,dvc,&cgemmParams); cfile<<cgemmParams<<endl; cfile.close(); }
44.319343
193
0.447427
459c85c986e46de885a11a2a0a52ad2704918e44
1,840
cpp
C++
hyperplatform_log_parser/hyperplatform_log_parser.cpp
tandasat/hyperplatform_log_parser
7a7eba3c8c582fa43ba2a47372a363080796d2d4
[ "MIT" ]
17
2016-04-08T10:59:03.000Z
2021-12-11T07:09:31.000Z
hyperplatform_log_parser/hyperplatform_log_parser.cpp
c3358/hyperplatform_log_parser
7a7eba3c8c582fa43ba2a47372a363080796d2d4
[ "MIT" ]
null
null
null
hyperplatform_log_parser/hyperplatform_log_parser.cpp
c3358/hyperplatform_log_parser
7a7eba3c8c582fa43ba2a47372a363080796d2d4
[ "MIT" ]
11
2016-07-02T15:23:57.000Z
2021-01-08T19:27:36.000Z
// Copyright (c) 2015-2016, tandasat. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. // // This module implements an entry point of the driver. // #include "stdafx.h" #include "log_parser.h" #include "utility.h" //////////////////////////////////////////////////////////////////////////////// // // macro utilities // //////////////////////////////////////////////////////////////////////////////// // // constants and macros // //////////////////////////////////////////////////////////////////////////////// // // types // //////////////////////////////////////////////////////////////////////////////// // // prototypes // bool AppMain(_In_ const std::vector<std::basic_string<TCHAR>> &args); //////////////////////////////////////////////////////////////////////////////// // // variables // //////////////////////////////////////////////////////////////////////////////// // // implementations // // int _tmain(int argc, TCHAR *argv[]) { auto exit_code = EXIT_FAILURE; try { std::vector<std::basic_string<TCHAR>> args; for (auto i = 0; i < argc; ++i) { args.push_back(argv[i]); } if (AppMain(args)) { exit_code = EXIT_SUCCESS; } } catch (std::exception &e) { std::cout << e.what() << std::endl; } catch (...) { std::cout << "Unhandled exception occurred." << std::endl; } return exit_code; } // A main application loop _Use_decl_annotations_ bool AppMain( const std::vector<std::basic_string<TCHAR>> &args) { if (args.size() == 1) { std::cout << "Usage:\n" << " >this.exe <log_file_path>\n" << std::endl; return false; } LogParser log_parser(args.at(1)); for (;;) { std::this_thread::sleep_for(std::chrono::seconds(1)); log_parser.ParseFile(); } }
23.291139
80
0.448913
459d3fd808aba1dfd91a27a8763c89bd4d83aae4
61
hpp
C++
addons/interrogation/functions/script_component.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
6
2018-05-05T22:28:57.000Z
2019-07-06T08:46:51.000Z
addons/interrogation/functions/script_component.hpp
Schwaggot/kellerkompanie-mods
7a389e49e3675866dbde1b317a44892926976e9d
[ "MIT" ]
107
2018-04-11T19:42:27.000Z
2019-09-13T19:05:31.000Z
addons/interrogation/functions/script_component.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
3
2018-10-03T11:54:46.000Z
2019-02-28T13:30:16.000Z
#include "\x\keko\addons\interrogation\script_component.hpp"
30.5
60
0.819672
45a0d5b4a59c688e301f8a5f78f412956f5d1494
1,603
cpp
C++
SystemResource/Source/Compression/ZLIB/ZLIBCompressionLevel.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
5
2021-10-19T18:30:43.000Z
2022-03-19T22:02:02.000Z
SystemResource/Source/Compression/ZLIB/ZLIBCompressionLevel.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
12
2022-03-09T13:40:21.000Z
2022-03-31T12:47:48.000Z
SystemResource/Source/Compression/ZLIB/ZLIBCompressionLevel.cpp
BitPaw/BitFireEngine
2c02a4eae19276bf60ac925e4393966cec605112
[ "MIT" ]
null
null
null
#include "ZLIBCompressionLevel.h" BF::ZLIBCompressionLevel BF::ConvertCompressionLevel(unsigned char compressionLevel) { switch (compressionLevel) { case 0u: return BF::ZLIBCompressionLevel::Fastest; case 1u: return BF::ZLIBCompressionLevel::Fast; case 2u: return BF::ZLIBCompressionLevel::Default; case 3u: return BF::ZLIBCompressionLevel::Slowest; default: return BF::ZLIBCompressionLevel::InvalidCompressionLevel; } } unsigned char BF::ConvertCompressionLevel(ZLIBCompressionLevel compressionLevel) { switch (compressionLevel) { default: case BF::ZLIBCompressionLevel::InvalidCompressionLevel: return -1; case BF::ZLIBCompressionLevel::Default: return 2u; case BF::ZLIBCompressionLevel::Slowest: return 3u; case BF::ZLIBCompressionLevel::Fast: return 1u; case BF::ZLIBCompressionLevel::Fastest: return 0u; } } const char* BF::CompressionLevelToString(ZLIBCompressionLevel compressionLevel) { switch (compressionLevel) { default: case BF::ZLIBCompressionLevel::InvalidCompressionLevel: return "Invalid"; case BF::ZLIBCompressionLevel::Default: return "Default"; case BF::ZLIBCompressionLevel::Slowest: return "Slowest"; case BF::ZLIBCompressionLevel::Fast: return "Fast"; case BF::ZLIBCompressionLevel::Fastest: return "Fastest"; } }
23.925373
84
0.625702
45a0dc71972c48dd43d07afd55f00e8ee349c216
15,185
cpp
C++
src/Conversion.cpp
markvilar/Sennet-ZED
2b761ed4f3fefa93f5e37e3b5f283eb0934146d3
[ "Apache-2.0" ]
null
null
null
src/Conversion.cpp
markvilar/Sennet-ZED
2b761ed4f3fefa93f5e37e3b5f283eb0934146d3
[ "Apache-2.0" ]
null
null
null
src/Conversion.cpp
markvilar/Sennet-ZED
2b761ed4f3fefa93f5e37e3b5f283eb0934146d3
[ "Apache-2.0" ]
null
null
null
#include "Sennet-ZED/Conversion.hpp" sl::VIEW SennetToStereolabs(const Sennet::ZED::View& view) { switch (view) { case Sennet::ZED::View::Left: return sl::VIEW::LEFT; case Sennet::ZED::View::Right: return sl::VIEW::RIGHT; case Sennet::ZED::View::LeftGray: return sl::VIEW::LEFT_GRAY; case Sennet::ZED::View::RightGray: return sl::VIEW::RIGHT_GRAY; case Sennet::ZED::View::LeftUnrectified: return sl::VIEW::LEFT_UNRECTIFIED; case Sennet::ZED::View::RightUnrectified: return sl::VIEW::RIGHT_UNRECTIFIED; case Sennet::ZED::View::LeftUnrectifiedGray: return sl::VIEW::LEFT_UNRECTIFIED_GRAY; case Sennet::ZED::View::RightUnrectifiedGray: return sl::VIEW::RIGHT_UNRECTIFIED_GRAY; case Sennet::ZED::View::SideBySide: return sl::VIEW::SIDE_BY_SIDE; default: return sl::VIEW::LAST; } } sl::RESOLUTION SennetToStereolabs(const Sennet::ZED::Resolution& resolution) { switch (resolution) { case Sennet::ZED::Resolution::HD2K: return sl::RESOLUTION::HD2K; case Sennet::ZED::Resolution::HD1080: return sl::RESOLUTION::HD1080; case Sennet::ZED::Resolution::HD720: return sl::RESOLUTION::HD720; case Sennet::ZED::Resolution::VGA: return sl::RESOLUTION::VGA; default: return sl::RESOLUTION::LAST; } } sl::VIDEO_SETTINGS SennetToStereolabs( const Sennet::ZED::VideoSettings& videoSettings) { switch (videoSettings) { case Sennet::ZED::VideoSettings::Brightness: return sl::VIDEO_SETTINGS::BRIGHTNESS; case Sennet::ZED::VideoSettings::Contrast: return sl::VIDEO_SETTINGS::CONTRAST; case Sennet::ZED::VideoSettings::Hue: return sl::VIDEO_SETTINGS::HUE; case Sennet::ZED::VideoSettings::Saturation: return sl::VIDEO_SETTINGS::SATURATION; case Sennet::ZED::VideoSettings::Sharpness: return sl::VIDEO_SETTINGS::SHARPNESS; case Sennet::ZED::VideoSettings::Gain: return sl::VIDEO_SETTINGS::GAIN; case Sennet::ZED::VideoSettings::Exposure: return sl::VIDEO_SETTINGS::EXPOSURE; case Sennet::ZED::VideoSettings::AECAGC: return sl::VIDEO_SETTINGS::AEC_AGC; case Sennet::ZED::VideoSettings::WhitebalanceTemperature: return sl::VIDEO_SETTINGS::WHITEBALANCE_TEMPERATURE; case Sennet::ZED::VideoSettings::WhitebalanceAuto: return sl::VIDEO_SETTINGS::WHITEBALANCE_AUTO; case Sennet::ZED::VideoSettings::LEDStatus: return sl::VIDEO_SETTINGS::LED_STATUS; default: return sl::VIDEO_SETTINGS::LAST; } } sl::DEPTH_MODE SennetToStereolabs(const Sennet::ZED::DepthMode& depthMode) { switch (depthMode) { case Sennet::ZED::DepthMode::Performance: return sl::DEPTH_MODE::PERFORMANCE; case Sennet::ZED::DepthMode::Quality: return sl::DEPTH_MODE::QUALITY; case Sennet::ZED::DepthMode::Ultra: return sl::DEPTH_MODE::ULTRA; default: return sl::DEPTH_MODE::LAST; } } sl::FLIP_MODE SennetToStereolabs(const Sennet::ZED::FlipMode& flipMode) { switch (flipMode) { case Sennet::ZED::FlipMode::Off: return sl::FLIP_MODE::OFF; case Sennet::ZED::FlipMode::On: return sl::FLIP_MODE::ON; case Sennet::ZED::FlipMode::Auto: return sl::FLIP_MODE::AUTO; default: return sl::FLIP_MODE::OFF; } } sl::UNIT SennetToStereolabs(const Sennet::ZED::Unit& unit) { switch (unit) { case Sennet::ZED::Unit::Millimeter: return sl::UNIT::MILLIMETER; case Sennet::ZED::Unit::Centimeter: return sl::UNIT::CENTIMETER; case Sennet::ZED::Unit::Meter: return sl::UNIT::METER; case Sennet::ZED::Unit::Inch: return sl::UNIT::INCH; case Sennet::ZED::Unit::Foot: return sl::UNIT::FOOT; default: return sl::UNIT::LAST; } } sl::SVO_COMPRESSION_MODE SennetToStereolabs( const Sennet::ZED::SVOCompressionMode& compressionMode) { switch (compressionMode) { case Sennet::ZED::SVOCompressionMode::Lossless: return sl::SVO_COMPRESSION_MODE::LOSSLESS; case Sennet::ZED::SVOCompressionMode::H264: return sl::SVO_COMPRESSION_MODE::H264; case Sennet::ZED::SVOCompressionMode::H265: return sl::SVO_COMPRESSION_MODE::H265; default: return sl::SVO_COMPRESSION_MODE::LAST; } } sl::SENSING_MODE SennetToStereolabs(const Sennet::ZED::SensingMode& sensingMode) { switch (sensingMode) { case Sennet::ZED::SensingMode::Standard: return sl::SENSING_MODE::STANDARD; case Sennet::ZED::SensingMode::Fill: return sl::SENSING_MODE::FILL; default: return sl::SENSING_MODE::LAST; } } sl::REFERENCE_FRAME SennetToStereolabs( const Sennet::ZED::ReferenceFrame& referenceFrame) { switch (referenceFrame) { case Sennet::ZED::ReferenceFrame::World: return sl::REFERENCE_FRAME::WORLD; case Sennet::ZED::ReferenceFrame::Camera: return sl::REFERENCE_FRAME::CAMERA; default: return sl::REFERENCE_FRAME::LAST; } } sl::COORDINATE_SYSTEM SennetToStereolabs( const Sennet::ZED::CoordinateSystem& coordinateSystem) { switch (coordinateSystem) { case Sennet::ZED::CoordinateSystem::Image: return sl::COORDINATE_SYSTEM::IMAGE; case Sennet::ZED::CoordinateSystem::LeftHandedYUp: return sl::COORDINATE_SYSTEM::LEFT_HANDED_Y_UP; case Sennet::ZED::CoordinateSystem::RightHandedYUp: return sl::COORDINATE_SYSTEM::RIGHT_HANDED_Y_UP; case Sennet::ZED::CoordinateSystem::RightHandedZUp: return sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP; case Sennet::ZED::CoordinateSystem::LeftHandedZUp: return sl::COORDINATE_SYSTEM::LEFT_HANDED_Z_UP; case Sennet::ZED::CoordinateSystem::RightHandedZUpXForward: return sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP_X_FWD; default: return sl::COORDINATE_SYSTEM::LAST; } } sl::InitParameters SennetToStereolabs( const Sennet::ZED::InitParameters& initParameters) { sl::InitParameters params; params.depth_mode = SennetToStereolabs( initParameters.depthMode); params.coordinate_units = SennetToStereolabs( initParameters.coordinateUnits); params.coordinate_system = SennetToStereolabs(initParameters.coordinateSystem); params.depth_stabilization = (int)initParameters.enableDepthStabilization; params.depth_minimum_distance = initParameters.minDepth; params.depth_maximum_distance = initParameters.maxDepth; params.enable_right_side_measure = initParameters.enableRightSideDepth; params.camera_resolution = SennetToStereolabs( initParameters.resolution); params.camera_image_flip = SennetToStereolabs(initParameters.flipMode); params.camera_fps = initParameters.cameraFPS; params.enable_image_enhancement = initParameters.enableImageEnhancement; params.camera_disable_self_calib = initParameters.disableSelfCalibration; params.sdk_verbose = initParameters.enableVerboseSDK; params.sensors_required = initParameters.requireSensors; return params; } sl::RecordingParameters SennetToStereolabs( const Sennet::ZED::RecordingParameters& recordingParameters) { sl::RecordingParameters params; params.video_filename = sl::String(recordingParameters.filename.c_str()); params.compression_mode = SennetToStereolabs(recordingParameters.compressionMode); return params; } sl::RuntimeParameters SennetToStereolabs( const Sennet::ZED::RuntimeParameters& runtimeParameters) { sl::RuntimeParameters params; params.sensing_mode = SennetToStereolabs(runtimeParameters.sensingMode); params.measure3D_reference_frame = SennetToStereolabs(runtimeParameters.referenceFrame); params.enable_depth = runtimeParameters.enableDepth; params.confidence_threshold = runtimeParameters.confidenceThreshold; params.texture_confidence_threshold = runtimeParameters.textureConfidenceThreshold; return params; } /////////////////////////////////////////////////////////////////////////////// // Sennet conversion functions //////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Sennet::ZED::View StereolabsToSennet(const sl::VIEW& view) { switch (view) { case sl::VIEW::LEFT: return Sennet::ZED::View::Left; case sl::VIEW::RIGHT: return Sennet::ZED::View::Right; case sl::VIEW::LEFT_GRAY: return Sennet::ZED::View::LeftGray; case sl::VIEW::RIGHT_GRAY: return Sennet::ZED::View::RightGray; case sl::VIEW::LEFT_UNRECTIFIED: return Sennet::ZED::View::LeftUnrectified; case sl::VIEW::RIGHT_UNRECTIFIED: return Sennet::ZED::View::RightUnrectified; case sl::VIEW::LEFT_UNRECTIFIED_GRAY: return Sennet::ZED::View::LeftUnrectifiedGray; case sl::VIEW::RIGHT_UNRECTIFIED_GRAY: return Sennet::ZED::View::RightUnrectifiedGray; case sl::VIEW::SIDE_BY_SIDE: return Sennet::ZED::View::SideBySide; default: return Sennet::ZED::View::None; } } Sennet::ZED::Resolution StereolabsToSennet(const sl::RESOLUTION& resolution) { switch (resolution) { case sl::RESOLUTION::HD2K: return Sennet::ZED::Resolution::HD2K; case sl::RESOLUTION::HD1080: return Sennet::ZED::Resolution::HD1080; case sl::RESOLUTION::HD720: return Sennet::ZED::Resolution::HD720; case sl::RESOLUTION::VGA: return Sennet::ZED::Resolution::VGA; default: return Sennet::ZED::Resolution::None; } } Sennet::ZED::VideoSettings StereolabsToSennet( const sl::VIDEO_SETTINGS& videoSettings) { switch (videoSettings) { case sl::VIDEO_SETTINGS::BRIGHTNESS: return Sennet::ZED::VideoSettings::Brightness; case sl::VIDEO_SETTINGS::CONTRAST: return Sennet::ZED::VideoSettings::Contrast; case sl::VIDEO_SETTINGS::HUE: return Sennet::ZED::VideoSettings::Hue; case sl::VIDEO_SETTINGS::SATURATION: return Sennet::ZED::VideoSettings::Saturation; case sl::VIDEO_SETTINGS::SHARPNESS: return Sennet::ZED::VideoSettings::Sharpness; case sl::VIDEO_SETTINGS::GAIN: return Sennet::ZED::VideoSettings::Gain; case sl::VIDEO_SETTINGS::EXPOSURE: return Sennet::ZED::VideoSettings::Exposure; case sl::VIDEO_SETTINGS::AEC_AGC: return Sennet::ZED::VideoSettings::AECAGC; case sl::VIDEO_SETTINGS::WHITEBALANCE_TEMPERATURE: return Sennet::ZED::VideoSettings::WhitebalanceTemperature; case sl::VIDEO_SETTINGS::WHITEBALANCE_AUTO: return Sennet::ZED::VideoSettings::WhitebalanceAuto; case sl::VIDEO_SETTINGS::LED_STATUS: return Sennet::ZED::VideoSettings::LEDStatus; default: return Sennet::ZED::VideoSettings::None; } } Sennet::ZED::DepthMode StereolabsToSennet(const sl::DEPTH_MODE& depthMode) { switch (depthMode) { case sl::DEPTH_MODE::PERFORMANCE: return Sennet::ZED::DepthMode::Performance; case sl::DEPTH_MODE::QUALITY: return Sennet::ZED::DepthMode::Quality; case sl::DEPTH_MODE::ULTRA: return Sennet::ZED::DepthMode::Ultra; default: return Sennet::ZED::DepthMode::None; } } Sennet::ZED::FlipMode StereolabsToSennet(const int flipMode) { switch (flipMode) { case sl::FLIP_MODE::OFF: return Sennet::ZED::FlipMode::Off; case sl::FLIP_MODE::ON: return Sennet::ZED::FlipMode::On; case sl::FLIP_MODE::AUTO: return Sennet::ZED::FlipMode::Auto; default: return Sennet::ZED::FlipMode::None; } } Sennet::ZED::Unit StereolabsToSennet(const sl::UNIT& unit) { switch (unit) { case sl::UNIT::MILLIMETER: return Sennet::ZED::Unit::Millimeter; case sl::UNIT::CENTIMETER: return Sennet::ZED::Unit::Centimeter; case sl::UNIT::METER: return Sennet::ZED::Unit::Meter; case sl::UNIT::INCH: return Sennet::ZED::Unit::Inch; case sl::UNIT::FOOT: return Sennet::ZED::Unit::Foot; default: return Sennet::ZED::Unit::None; } } Sennet::ZED::SVOCompressionMode StereolabsToSennet( const sl::SVO_COMPRESSION_MODE& compressionMode) { switch (compressionMode) { case sl::SVO_COMPRESSION_MODE::LOSSLESS: return Sennet::ZED::SVOCompressionMode::Lossless; case sl::SVO_COMPRESSION_MODE::H264: return Sennet::ZED::SVOCompressionMode::H264; case sl::SVO_COMPRESSION_MODE::H265: return Sennet::ZED::SVOCompressionMode::H265; default: return Sennet::ZED::SVOCompressionMode::None; } } Sennet::ZED::SensingMode StereolabsToSennet(const sl::SENSING_MODE& sensingMode) { switch (sensingMode) { case sl::SENSING_MODE::STANDARD: return Sennet::ZED::SensingMode::Standard; case sl::SENSING_MODE::FILL: return Sennet::ZED::SensingMode::Fill; default: return Sennet::ZED::SensingMode::None; } } Sennet::ZED::ReferenceFrame StereolabsToSennet( const sl::REFERENCE_FRAME& referenceFrame) { switch (referenceFrame) { case sl::REFERENCE_FRAME::WORLD: return Sennet::ZED::ReferenceFrame::World; case sl::REFERENCE_FRAME::CAMERA: return Sennet::ZED::ReferenceFrame::Camera; default: return Sennet::ZED::ReferenceFrame::None; } } Sennet::ZED::CoordinateSystem StereolabsToSennet( const sl::COORDINATE_SYSTEM& coordinateSystem) { typedef Sennet::ZED::CoordinateSystem CoordinateSystem; switch (coordinateSystem) { case sl::COORDINATE_SYSTEM::IMAGE: return CoordinateSystem::Image; case sl::COORDINATE_SYSTEM::LEFT_HANDED_Y_UP: return CoordinateSystem::LeftHandedYUp; case sl::COORDINATE_SYSTEM::RIGHT_HANDED_Y_UP: return CoordinateSystem::RightHandedYUp; case sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP: return CoordinateSystem::RightHandedZUp; case sl::COORDINATE_SYSTEM::LEFT_HANDED_Z_UP: return CoordinateSystem::LeftHandedZUp; case sl::COORDINATE_SYSTEM::RIGHT_HANDED_Z_UP_X_FWD: return CoordinateSystem::RightHandedZUpXForward; default: return CoordinateSystem::None; } } Sennet::ZED::InitParameters StereolabsToSennet( const sl::InitParameters& initParameters) { Sennet::ZED::InitParameters params; params.depthMode = StereolabsToSennet(initParameters.depth_mode); params.coordinateUnits = StereolabsToSennet( initParameters.coordinate_units); params.coordinateSystem = StereolabsToSennet( initParameters.coordinate_system); params.enableDepthStabilization = (bool)initParameters.depth_stabilization; params.minDepth = initParameters.depth_minimum_distance; params.maxDepth = initParameters.depth_maximum_distance; params.enableRightSideDepth = initParameters.enable_right_side_measure; params.resolution = StereolabsToSennet(initParameters.camera_resolution); params.flipMode = StereolabsToSennet(initParameters.camera_image_flip); params.cameraFPS = initParameters.camera_fps; params.enableImageEnhancement = initParameters.enable_image_enhancement; params.disableSelfCalibration = initParameters.camera_disable_self_calib; params.enableVerboseSDK = initParameters.sdk_verbose; params.requireSensors = initParameters.sensors_required; return params; } Sennet::ZED::RecordingParameters StereolabsToSennet( const sl::RecordingParameters& recordingParameters) { Sennet::ZED::RecordingParameters params; params.filename = std::string(recordingParameters.video_filename.get()); params.compressionMode = StereolabsToSennet(recordingParameters.compression_mode); return params; } Sennet::ZED::RuntimeParameters StereolabsToSennet( const sl::RuntimeParameters& runtimeParameters) { Sennet::ZED::RuntimeParameters params; params.sensingMode = StereolabsToSennet(runtimeParameters.sensing_mode); params.referenceFrame = StereolabsToSennet(runtimeParameters.measure3D_reference_frame); params.enableDepth = runtimeParameters.enable_depth; params.confidenceThreshold = runtimeParameters.confidence_threshold; params.textureConfidenceThreshold = runtimeParameters.texture_confidence_threshold; return params; }
30.989796
80
0.753309
45a55d2ac83ad14f7d75e5bef293e0e05bf1b121
19
cpp
C++
src/Type.cpp
phiwen96/ph_image
282bdd835d721a561c4f3afcbb76af5f9bda87ba
[ "Apache-2.0" ]
1
2021-09-05T08:38:39.000Z
2021-09-05T08:38:39.000Z
src/Type.cpp
phiwen96/ph_image
282bdd835d721a561c4f3afcbb76af5f9bda87ba
[ "Apache-2.0" ]
null
null
null
src/Type.cpp
phiwen96/ph_image
282bdd835d721a561c4f3afcbb76af5f9bda87ba
[ "Apache-2.0" ]
2
2021-12-04T14:39:52.000Z
2022-03-04T21:12:02.000Z
#include "Type.hpp"
19
19
0.736842
45aa1cc56e96bcf62894efe1c61d5d3ed75c0841
238
cpp
C++
Course Experiment/C Language Course Course Exp/Homework/No.7 Homework/5.空格处理.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
4
2019-04-01T17:33:38.000Z
2022-01-08T04:07:52.000Z
Course Experiment/C Language Course Course Exp/Homework/No.7 Homework/5.空格处理.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
null
null
null
Course Experiment/C Language Course Course Exp/Homework/No.7 Homework/5.空格处理.cpp
XJDKC/University-Code-Archive
2dd9c6edb2164540dc50db1bb94940fe53c6eba0
[ "MIT" ]
1
2021-01-06T11:04:31.000Z
2021-01-06T11:04:31.000Z
#include<stdio.h> int main() { int n; scanf("%d",&n); getchar(); while (n--) { char a='0',b; while ((b=getchar())!='\n') { if (a!='0'&&a==' '&&b==' ') continue; a=b; printf("%c",a); } printf("\n"); } return 0; }
11.9
40
0.432773
45b1eec24e6fbb6c79c985d3859420b22890719f
2,353
cpp
C++
Projects/Library/Source/Translator/Token.cpp
kalineh/KAI
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
[ "MIT" ]
1
2018-06-16T17:53:43.000Z
2018-06-16T17:53:43.000Z
Projects/Library/Source/Translator/Token.cpp
kalineh/KAI
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
[ "MIT" ]
null
null
null
Projects/Library/Source/Translator/Token.cpp
kalineh/KAI
43ab555bcbad1886715cd00b2cdac89e12d5cfe5
[ "MIT" ]
null
null
null
#include "KAI/KAI.h" #include "KAI/Translator/Token.h" #include "KAI/Translator/Lexer.h" KAI_BEGIN Token::Token(Type type, const Lexer &lexer, int ln, Slice slice) : type(type), lexer(&lexer), lineNumber(ln), slice(slice) { } char Token::operator[](int n) const { return lexer->input[slice.Start + n]; } std::string Token::Text() const { if (lexer == 0) return ""; return std::move(lexer->lines[lineNumber].substr(slice.Start, slice.Length())); } const char * Token::ToString(Type t) { switch (t) { case None: return "None"; case Whitespace: return ""; case Semi: return "Semi"; case Int: return "Int"; case Float: return "Float"; case String: return "String"; case Ident: return "Ident"; case Dot: return "Dot"; case If: return "If"; case Else: return "Else"; case For: return "For"; case While: return "While"; case OpenParan: return "OpenParan"; case CloseParan: return "CloseParan"; case Plus: return "Plus"; case Minus: return "Minus"; case Mul: return "Mul"; case Divide: return "Divide"; case Assign: return "Assign"; case Less: return "Less"; case Equiv: return "Equiv"; case Greater: return "Greater"; case LessEquiv: return "LessEquiv"; case GreaterEquiv: return "GreaterEqiv"; case Return: return "Return"; case OpenBrace: return "OpenBrace"; case CloseBrace: return "CloseBrace"; case Not: return "Not"; case NotEquiv: return "NotEquiv"; case And: return "And"; case Or: return "Or"; case Comma: return "Comma"; case OpenSquareBracket: return "OpenSquareBracket"; case CloseSquareBracket: return "CloseSquareBracket"; case Increment: return "++"; case Decrement: return "--"; case Self: return "Self"; case Lookup: return "Lookup"; case Fun: return "Fun"; case Tab: return "Tab"; case NewLine: return "NewLine"; case Comment: return "Comment"; case PlusAssign: return "PlusAssign"; case MinusAssign: return "MinusAssign"; case MulAssign: return "MulAssign"; case DivAssign: return "DivAssign"; case Yield: return "Yield"; } static char b[100]; _itoa_s(t, b, 100, 10); return b; } std::ostream &operator<<(std::ostream &out, Token const &node) { if (node.type == Token::None) return out; out << Token::ToString(node.type); switch (node.type) { case Token::Int: case Token::String: case Token::Ident: out << "=" << node.Text(); } return out; } KAI_END
23.29703
80
0.686783
45b23114090b3dc841c5f936a8868d223511c6af
521
cpp
C++
Interview-preparation-resources/Usual-C++-interview-question/algorithmic-solutions/possible_combination_of_a_given_string.cpp
Ajay-Embed/dataStructure-implementations
03638b9bc34a7e1ef5fa450be6c660c223608eff
[ "BSD-3-Clause" ]
null
null
null
Interview-preparation-resources/Usual-C++-interview-question/algorithmic-solutions/possible_combination_of_a_given_string.cpp
Ajay-Embed/dataStructure-implementations
03638b9bc34a7e1ef5fa450be6c660c223608eff
[ "BSD-3-Clause" ]
4
2021-01-23T15:24:39.000Z
2021-02-07T05:14:14.000Z
Interview-preparation-resources/Usual-C++-interview-question/algorithmic-solutions/possible_combination_of_a_given_string.cpp
Ajay-Embed/dataStructure-implementations
03638b9bc34a7e1ef5fa450be6c660c223608eff
[ "BSD-3-Clause" ]
2
2020-11-17T20:40:39.000Z
2021-01-30T17:12:33.000Z
//code to find all possible combinations of a given string #include <iostream> #include <bits/stdc++.h> using namespace std; void permut(string s, int i, int n) { // Recursion end case if (i == n) cout << s << " "; else { for (int j = i; j <= n; j++) { swap(s[i], s[j]); permut(s, i + 1, n); //backtracking swap(s[i], s[j]); } } } int main() { string s = "def"; permut(s, 0, s.size() - 1); return 0; }
15.323529
58
0.452975
45b5656d99ec73a5687a9c57e0255033950efb59
863
hpp
C++
HexDumper.hpp
jancarlsson/snarkfront
7f90a4181721f758f114497382aa462185e71dae
[ "MIT" ]
60
2015-01-02T12:28:40.000Z
2021-04-13T01:40:07.000Z
HexDumper.hpp
artree222/snarkfront
7f90a4181721f758f114497382aa462185e71dae
[ "MIT" ]
8
2015-03-05T13:12:39.000Z
2018-07-03T07:17:45.000Z
HexDumper.hpp
artree222/snarkfront
7f90a4181721f758f114497382aa462185e71dae
[ "MIT" ]
17
2015-01-22T03:10:49.000Z
2020-12-27T12:22:17.000Z
#ifndef _SNARKFRONT_HEX_DUMPER_HPP_ #define _SNARKFRONT_HEX_DUMPER_HPP_ #include <cstdint> #include <istream> #include <ostream> #include <vector> #include <cryptl/ASCII_Hex.hpp> #include <cryptl/DataPusher.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // print messages in hexdump format // class HexDumper { public: HexDumper(std::ostream&); void print(const std::vector<std::uint8_t>&); void print(std::istream&); private: // print as text characters class PrintText { public: PrintText(std::ostream&); void pushOctet(const std::uint8_t); private: std::ostream& m_os; }; cryptl::DataPusher<cryptl::PrintHex<true>> m_hex; cryptl::DataPusher<PrintText> m_text; std::ostream& m_os; }; } // namespace snarkfront #endif
19.177778
80
0.618772
45b6bb571b5dcd870ad59efbb29989e5fc5dfa59
1,278
hpp
C++
Siv3D/include/Siv3D/Base64.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
1
2018-05-23T10:57:32.000Z
2018-05-23T10:57:32.000Z
Siv3D/include/Siv3D/Base64.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
null
null
null
Siv3D/include/Siv3D/Base64.hpp
Fuyutsubaki/OpenSiv3D
4370f6ebe28addd39bfdd75915c5a18e3e5e9273
[ "MIT" ]
1
2019-10-06T17:09:26.000Z
2019-10-06T17:09:26.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Fwd.hpp" namespace s3d { /// <summary> /// Base64 /// </summary> /// <remarks> /// Base64 エンコード/デコードの機能を提供します。 /// </remarks> namespace Base64 { /// <summary> /// データを Base64 エンコードします。 /// </summary> /// <param name="data"> /// エンコードするデータの先頭ポインタ /// </param> /// <param name="size"> /// エンコードするデータのサイズ(バイト) /// </param> /// <returns> /// エンコードされたテキストデータ、エンコードに失敗した場合空の文字列 /// </returns> [[nodiscard]] String Encode(const void* data, size_t size); /// <summary> /// データを Base64 エンコードします。 /// </summary> /// <param name="view"> /// エンコードするデータ /// </param> /// <returns> /// エンコードされたテキストデータ、エンコードに失敗した場合空の文字列 /// </returns> [[nodiscard]] String Encode(ByteArrayView view); /// <summary> /// テキストを Base64 でデコードします。 /// </summary> /// <param name="view"> /// デコードするテキスト /// </param> /// <returns> /// デコードされたバイナリデータ、デコードに失敗した場合空のバイナリデータ /// </returns> [[nodiscard]] ByteArray Decode(StringView view); }; }
20.612903
61
0.553991
45b73eca1940d922653a5d22e172df165ef4f990
824
cpp
C++
superneurons/testing/test_malloc_free_speed.cpp
Phaeton-lang/baselines
472c248047fbb55b5fa0e620758047b7f0a1d041
[ "MIT" ]
null
null
null
superneurons/testing/test_malloc_free_speed.cpp
Phaeton-lang/baselines
472c248047fbb55b5fa0e620758047b7f0a1d041
[ "MIT" ]
null
null
null
superneurons/testing/test_malloc_free_speed.cpp
Phaeton-lang/baselines
472c248047fbb55b5fa0e620758047b7f0a1d041
[ "MIT" ]
null
null
null
// // Created by ay27 on 8/15/17. // #include <superneurons.h> using namespace std; using namespace SuperNeurons; int main(int argc, char** argv) { const int T = 100; const size_t MB = 1024*1024; double ts; double t1 = 0, t2 = 0; size_t size; //------------------------------------------------ for (size_t size = 128; size <= 5*1024; size += 128) { t1 = 0; t2 = 0; float *ptr; for (int i = 0; i < T; ++i) { ts = get_cur_time(); cudaMalloc(&ptr, size * MB); t1 += get_cur_time() - ts; ts = get_cur_time(); cudaFree(ptr); t2 += get_cur_time() - ts; } t1 = t1 / (double)T; t2 = t2 / (double)T; printf("- %f\n", t1); printf("+ %f\n", t2); } }
20.097561
58
0.433252
45bf2301b27fdcb7361443a3e2f34a32713aedeb
563
cpp
C++
week3/Math/main.cpp
iustina0/CommandDefense
47044018be774b09d135bda82f1abdd5289237ea
[ "MIT" ]
null
null
null
week3/Math/main.cpp
iustina0/CommandDefense
47044018be774b09d135bda82f1abdd5289237ea
[ "MIT" ]
null
null
null
week3/Math/main.cpp
iustina0/CommandDefense
47044018be774b09d135bda82f1abdd5289237ea
[ "MIT" ]
null
null
null
#include "Math.h" int main() { int a = 23, b=645, c=633; double x = 132.45, y = 43.546, z = 89.476; char *p, *q; p = new char[4]; q = new char[4]; strcpy(p, "qwer"); strcpy(q, "asdf"); cout << Math::Add(a,b) << "\n"; cout << Math::Add(a,b,c) << "\n"; cout << Math::Add(x,y) << "\n"; cout << Math::Add(x,y,z) << "\n"; cout << Math::Mul(a,b) << "\n"; cout << Math::Mul(a,b,c) << "\n"; cout << Math::Mul(x,y) << "\n"; cout << Math::Mul(x,y,z) << "\n"; cout << Math::Add(p, q) << "\n"; return 0; }
24.478261
46
0.426288
45c0d698f2da891f8e4c70ef14a9883932ed1004
1,492
cpp
C++
GeeksForGeeks/Strongly Connected Components (Kosaraju's Algo).cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
GeeksForGeeks/Strongly Connected Components (Kosaraju's Algo).cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
GeeksForGeeks/Strongly Connected Components (Kosaraju's Algo).cpp
tanishq1g/cp_codes
80b8ccc9e195a66d6d317076fdd54a02cd21275b
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <locale> #include <algorithm> #include <cmath> #include <unordered_map> #include <bitset> #include <climits> #include <queue> #include <stack> using namespace std; // GRAPH void dfs(vector<int> adj[], vector<bool> &vis, stack<int> &st, int ind){ vis[ind] = true; int sadj = adj[ind].size(); for(int i = 0; i < sadj; i++){ if(vis[adj[ind][i]] == false){ dfs(adj, vis, st, adj[ind][i]); } } st.push(ind); } void dfs2(vector<int> adj[], vector<bool> &vis, int ind){ vis[ind] = true; int sadj = adj[ind].size(); for(int i = 0; i < sadj; i++){ if(vis[adj[ind][i]] == false){ dfs2(adj, vis, adj[ind][i]); } } // st.push(ind); } int kosaraju(int V, vector<int> adj[]){ if(V==0) return 0; vector<bool> vis(V, false); stack<int> st; for(int i = 0; i < V; i++){ if(vis[i] == false){ dfs(adj, vis, st, i); } } vis = vector<bool> (V, false); vector<int> adj2[V]; int sadj; for(int i = 0; i < V; i++){ sadj = adj[i].size(); for(int j = 0; j < sadj; j++){ adj2[adj[i][j]].push_back(i); } } delete adj; int count = 0; while(!st.empty()){ int i = st.top(); st.pop(); if(vis[i] == false){ dfs2(adj2, vis, i); count++; } } return count; }
19.893333
72
0.476542
45c1f7f43093cf219183eba6c6043dbd56ca7db3
1,532
cpp
C++
CWin/CWin/events/event_trigger_condition.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/events/event_trigger_condition.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
CWin/CWin/events/event_trigger_condition.cpp
benbraide/CWin
0441b48a71fef0dbddabf61033d7286669772c1e
[ "MIT" ]
null
null
null
#include "event_trigger_condition.h" cwin::events::trigger_condition::~trigger_condition() = default; cwin::events::trigger_condition::operator m_callback_type() const{ return get(); } cwin::events::trigger_condition::m_callback_type cwin::events::trigger_condition::get() const{ return nullptr; } cwin::events::external_trigger_condition::external_trigger_condition(const m_callback_type &value) : value_(value){} cwin::events::external_trigger_condition::~external_trigger_condition() = default; cwin::events::trigger_condition::m_callback_type cwin::events::external_trigger_condition::get() const{ return value_; } cwin::events::odd_count_trigger_condition::~odd_count_trigger_condition() = default; cwin::events::trigger_condition::m_callback_type cwin::events::odd_count_trigger_condition::get() const{ return [](std::size_t count){ return ((count % 2u) == 1u); }; } cwin::events::even_count_trigger_condition::~even_count_trigger_condition() = default; cwin::events::trigger_condition::m_callback_type cwin::events::even_count_trigger_condition::get() const{ return [](std::size_t count){ return ((count % 2u) == 0u); }; } cwin::events::max_count_trigger_condition::max_count_trigger_condition(std::size_t value) : value_(value){} cwin::events::max_count_trigger_condition::~max_count_trigger_condition() = default; cwin::events::trigger_condition::m_callback_type cwin::events::max_count_trigger_condition::get() const{ return [value = value_](std::size_t count){ return (count <= value); }; }
31.916667
105
0.772846
45c4ff283f1bd510f5089c454c2a348f353c0a08
3,347
cpp
C++
12_TIM1_PWM_input/main.cpp
AVilezhaninov/STM32F429VG
cb77fb53235ffd4cdf000749e4857108bc96c2cb
[ "MIT" ]
null
null
null
12_TIM1_PWM_input/main.cpp
AVilezhaninov/STM32F429VG
cb77fb53235ffd4cdf000749e4857108bc96c2cb
[ "MIT" ]
null
null
null
12_TIM1_PWM_input/main.cpp
AVilezhaninov/STM32F429VG
cb77fb53235ffd4cdf000749e4857108bc96c2cb
[ "MIT" ]
null
null
null
/* CMSIS */ #include "CMSIS\Device\stm32f4xx.h" /* User */ #include "user\RCC.h" /******************************************************************************/ /* Private definitions ********************************************************/ /******************************************************************************/ #define TIM1_PSC 0u /* TIM1 clock: (180 MHz / 1) = 180 MHz */ #define TIM1_ARR 65535u /* TIM1 maximum clock value */ #define TIM1_IRQ_PRIORITY 5u /******************************************************************************/ /* Private function prototypes ************************************************/ /******************************************************************************/ static void InitTim1(); /******************************************************************************/ /* Interrupts *****************************************************************/ /******************************************************************************/ extern "C" { /** * TIM1 capture compare interrupt handler */ void TIM1_CC_IRQHandler() { uint16_t period; uint16_t width; if ((TIM1->SR & TIM_SR_CC2IF) == TIM_SR_CC2IF) { period = TIM1->CCR2; /* Get pulse period */ width = TIM1->CCR1; /* Get pulse width */ } TIM1->SR &= ~TIM_SR_CC1OF; /* Clear overcapture 1 flag */ TIM1->SR &= ~TIM_SR_CC2OF; /* Clear overcapture 2 flag */ } } /* extern "C" */ /******************************************************************************/ /* Main ***********************************************************************/ /******************************************************************************/ int main(void) { InitSystemClock(); InitTim1(); while (1) { ; } } /******************************************************************************/ /* Private functions **********************************************************/ /******************************************************************************/ void InitTim1() { RCC->AHB1ENR |= RCC_AHB1ENR_GPIOEEN; /* Enable PORTE clock */ GPIOE->MODER |= GPIO_MODER_MODER11_1; /* PE11 alternate mode */ GPIOE->AFR[1u] |= (1u << 12u); /* PE11 in AF1 */ RCC->APB2ENR |= RCC_APB2ENR_TIM1EN; /* Enable TIM1 clock */ TIM1->PSC = TIM1_PSC; /* Set TIM1 prescaler */ TIM1->ARR = TIM1_ARR; /* Set TIM1 auto reload value */ TIM1->CCMR1 |= TIM_CCMR1_CC1S_1; /* IC1 mapped on TI2 */ TIM1->CCER |= TIM_CCER_CC1P; /* Falling edge on TI1 */ TIM1->CCMR1 |= TIM_CCMR1_CC2S_0; /* IC2 mapped on TI1 */ TIM1->SMCR |= TIM_SMCR_TS_2 | TIM_SMCR_TS_1; /* Filtered timer input 2 */ TIM1->SMCR |= TIM_SMCR_SMS_2; /* "Reset" slave mode */ TIM1->DIER |= TIM_DIER_CC2IE; /* Capture 2 interrupt enable */ TIM1->CCER |= TIM_CCER_CC2E; /* Caputre 2 output enbale */ TIM1->CCER |= TIM_CCER_CC1E; /* Caputre 1 output enbale */ NVIC_SetPriority(TIM1_CC_IRQn, TIM1_IRQ_PRIORITY); /* Set TIM1 interrupt * priority */ NVIC_EnableIRQ(TIM1_CC_IRQn); /* Enable TIM1 capture interrupt */ TIM1->CR1 |= TIM_CR1_CEN; /* Enable TIM1 timer */ }
42.367089
80
0.380042
45c88d8e96e32d7e9ca06903b231e840b90406f2
836
cxx
C++
src/engine/ivp/ivp_collision/ivp_clustering_lrange_hash.cxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/ivp/ivp_collision/ivp_clustering_lrange_hash.cxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/ivp/ivp_collision/ivp_clustering_lrange_hash.cxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved. #include <ivp_physics.hxx> #include <ivu_vhash.hxx> #include <ivp_clustering_longrange.hxx> #include <ivp_clustering_lrange_hash.hxx> IVP_ov_tree_hash::~IVP_ov_tree_hash() { ; } int IVP_ov_tree_hash::node_to_index(IVP_OV_Node *node) { return hash_index((char *) &node->data, sizeof(node->data)); } IVP_BOOL IVP_ov_tree_hash::compare(void *elem0, void *elem1) const { IVP_OV_Node *node0 = (IVP_OV_Node *) elem0; IVP_OV_Node *node1 = (IVP_OV_Node *) elem1; if (node0->data.rasterlevel != node1->data.rasterlevel) return (IVP_FALSE); if (node0->data.x != node1->data.x) return (IVP_FALSE); if (node0->data.y != node1->data.y) return (IVP_FALSE); if (node0->data.z != node1->data.z) return (IVP_FALSE); return (IVP_TRUE); }
24.588235
79
0.697368
68f7074b50725b6a6363ef2a3ca8ae00111b5899
19,721
cpp
C++
components/sound/manager/sources/manager/sound_manager.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/sound/manager/sources/manager/sound_manager.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/sound/manager/sources/manager/sound_manager.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include <stl/algorithm> #include <stl/hash_map> #include <stl/list> #include <stl/stack> #include <stl/string> #include <xtl/bind.h> #include <xtl/common_exceptions.h> #include <xtl/function.h> #include <xtl/intrusive_ptr.h> #include <xtl/iterator.h> #include <xtl/shared_ptr.h> #include <xtl/signal.h> #include <common/log.h> #include <common/time.h> #include <sound/device.h> #include <sound/driver.h> #include <sound/manager.h> #include <media/sound.h> #include <media/sound_declaration.h> using namespace sound; using namespace sound::low_level; using namespace stl; using namespace xtl; using namespace common; using namespace media; #ifdef _MSC_VER #pragma warning (disable : 4355) //'this' : used in base member initializer list #endif namespace { const float EPS = 0.001f; const char* LOG_NAME = "sound::SoundManager"; //имя потока протоколирования SeekMode get_seek_mode (bool looping) { if (looping) return SeekMode_Repeat; else return SeekMode_Clamp; } typedef stl::list<SoundDeclarationLibrary> SoundDeclarationLibraryList; typedef xtl::com_ptr<ISample> SamplePtr; } /* Описание реализации SoundManager */ struct SoundManagerEmitter { int channel_number; //номер канала проигрывания (-1 - отсечён или не проигрывается) float cur_position; //текущая позиция проигрывания в секундах size_t play_start_time; //время начала проигрывания bool is_playing; //статус проигрывания SoundDeclaration sound_declaration; //описание звука SamplePtr sound_sample; //сэмпл звука double duration; //длительность звука float sound_declaration_gain; //громкость, заданная в описании звука (установка громкости производится относительно этого значения) bool sample_chosen; //эммитер ещё не проигрывался Source source; //излучатель звука string source_name; //имя источника size_t sample_index; //индекс сэмпла auto_connection update_volume_connection; //соединение события изменения громкости auto_connection update_properties_connection; //соединение события изменения свойств SoundManagerEmitter (connection in_update_volume_connection, connection in_update_properties_connection) : channel_number (-1), is_playing (false), sample_chosen (false), sample_index (0), update_volume_connection (in_update_volume_connection), update_properties_connection (in_update_properties_connection) {} }; typedef xtl::shared_ptr<SoundManagerEmitter> SoundManagerEmitterPtr; typedef stl::hash_map<Emitter*, SoundManagerEmitterPtr> EmitterSet; typedef xtl::com_ptr<low_level::IDevice> DevicePtr; typedef xtl::com_ptr<low_level::IDriver> DriverPtr; typedef stl::stack<unsigned short> ChannelsSet; struct SoundManager::Impl : public xtl::trackable { DevicePtr device; //устройство воспроизведения float volume; //добавочная громкость bool is_muted; //флаг блокировки проигрывания звука sound::Listener listener; //параметры слушателя EmitterSet emitters; //излучатели звука ChannelsSet free_channels; //номера свободных каналов Capabilities capabilities; //возможности устройства SoundDeclarationLibraryList sound_declaration_libraries; //библиотека описаний звуков common::Log log; //протокол xtl::trackable trackable; Impl (const char* driver_mask, const char* device_mask, const char* init_string) : volume (1.f), log (LOG_NAME) { try { device = DevicePtr (DriverManager::CreateDevice (driver_mask, device_mask, init_string), false); device->GetCapabilities (capabilities); for (unsigned short i = 0; i < capabilities.channels_count; i++) free_channels.push (i); } catch (xtl::exception& exception) { exception.touch ("sound::low_level::SoundManager::SoundManager"); throw; } } /////////////////////////////////////////////////////////////////////////////////////////////////// ///Блокировка проигрывания звука /////////////////////////////////////////////////////////////////////////////////////////////////// void SetMute (bool state) { is_muted = state; device->SetMute (state); } /////////////////////////////////////////////////////////////////////////////////////////////////// ///Обновление свойств эмиттеров /////////////////////////////////////////////////////////////////////////////////////////////////// void UpdateEmitterVolume (Emitter& emitter, EmitterEvent event) { EmitterSet::iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) return; emitter_iter->second->source.gain = emitter_iter->second->sound_declaration_gain * emitter_iter->first->Volume (); if (emitter_iter->second->channel_number != -1) device->SetSource (emitter_iter->second->channel_number, emitter_iter->second->source); } void UpdateEmitterProperties (Emitter& emitter, EmitterEvent event) { EmitterSet::iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) return; emitter_iter->second->source.position = emitter_iter->first->Position (); emitter_iter->second->source.direction = emitter_iter->first->Direction (); emitter_iter->second->source.velocity = emitter_iter->first->Velocity (); if (emitter_iter->second->channel_number != -1) device->SetSource (emitter_iter->second->channel_number, emitter_iter->second->source); } /////////////////////////////////////////////////////////////////////////////////////////////////// ///Проигрывание звуков /////////////////////////////////////////////////////////////////////////////////////////////////// void PlaySound (Emitter& emitter, float offset) { try { emitter.Activate (); EmitterSet::iterator emitter_iter = emitters.find (&emitter); SoundManagerEmitterPtr manager_emitter; if (emitter_iter == emitters.end ()) manager_emitter = SoundManagerEmitterPtr (new SoundManagerEmitter (emitter.RegisterEventHandler (EmitterEvent_OnUpdateVolume, xtl::bind (&SoundManager::Impl::UpdateEmitterVolume, this, _1, _2)), emitter.RegisterEventHandler (EmitterEvent_OnUpdateProperties, xtl::bind (&SoundManager::Impl::UpdateEmitterProperties, this, _1, _2)))); //создаем эмиттер, в карту добавляем позже, если найдем описание звука else manager_emitter = emitter_iter->second; if (strcmp (manager_emitter->source_name.c_str (), emitter.Source ())) { SoundDeclaration *emitter_sound_declaration = 0; for (SoundDeclarationLibraryList::iterator iter = sound_declaration_libraries.begin (), end = sound_declaration_libraries.end (); iter != end; ++iter) { emitter_sound_declaration = iter->Find (emitter.Source ()); if (emitter_sound_declaration) break; } if (!emitter_sound_declaration) { log.Printf ("Can't find sound declaration for id '%s'.", emitter.Source ()); StopSound (emitter); return; } manager_emitter->sound_declaration = *emitter_sound_declaration; manager_emitter->sound_declaration_gain = manager_emitter->sound_declaration.Param (SoundParam_Gain); manager_emitter->source.gain = emitter.Volume() * manager_emitter->sound_declaration_gain; manager_emitter->source.minimum_gain = manager_emitter->sound_declaration.Param (SoundParam_MinimumGain); manager_emitter->source.maximum_gain = manager_emitter->sound_declaration.Param (SoundParam_MaximumGain); manager_emitter->source.inner_angle = manager_emitter->sound_declaration.Param (SoundParam_InnerAngle); manager_emitter->source.outer_angle = manager_emitter->sound_declaration.Param (SoundParam_OuterAngle); manager_emitter->source.outer_gain = manager_emitter->sound_declaration.Param (SoundParam_OuterGain); manager_emitter->source.reference_distance = manager_emitter->sound_declaration.Param (SoundParam_ReferenceDistance); manager_emitter->source.maximum_distance = manager_emitter->sound_declaration.Param (SoundParam_MaximumDistance); manager_emitter->source_name = emitter.Source (); if (emitter_iter == emitters.end ()) emitters.insert_pair (&emitter, manager_emitter); } if (!manager_emitter->sample_chosen || manager_emitter->sample_index != emitter.SampleIndex ()) { manager_emitter->sample_index = emitter.SampleIndex (); manager_emitter->sound_sample = SamplePtr (device->CreateSample (manager_emitter->sound_declaration.Sample (manager_emitter->sample_index % manager_emitter->sound_declaration.SamplesCount ())), false); SampleDesc sample_desc; manager_emitter->sound_sample->GetDesc (sample_desc); manager_emitter->duration = sample_desc.samples_count / (double)sample_desc.frequency; manager_emitter->sample_chosen = true; } if (!manager_emitter->sound_declaration.Looping () && offset > manager_emitter->duration - EPS) //ignore attempts to play sound beyond end return; if (!manager_emitter->is_playing || manager_emitter->channel_number == -1) { manager_emitter->is_playing = true; if (!free_channels.empty ()) { unsigned short channel_to_use = free_channels.top (); free_channels.pop (); manager_emitter->channel_number = channel_to_use; } else { log.Printf ("Can't play sound %s, no free channels", manager_emitter->sound_sample->GetName ()); manager_emitter->channel_number = -1; } } manager_emitter->play_start_time = milliseconds (); manager_emitter->cur_position = offset; UpdateEmitterProperties (emitter, EmitterEvent_OnUpdateProperties); if (manager_emitter->channel_number != -1) { device->Stop (manager_emitter->channel_number); device->SetSample (manager_emitter->channel_number, manager_emitter->sound_sample.get ()); device->SetSource (manager_emitter->channel_number, manager_emitter->source); device->Seek (manager_emitter->channel_number, manager_emitter->cur_position, get_seek_mode (manager_emitter->sound_declaration.Looping ())); device->Play (manager_emitter->channel_number, manager_emitter->sound_declaration.Looping ()); } } catch (xtl::exception& e) { log.Printf ("Can't play sound. Exception: '%s'", e.what ()); StopSound (emitter); throw; } catch (...) { log.Printf ("Can't play sound. Unknown exception"); StopSound (emitter); throw; } } void PauseSound (Emitter& emitter) { EmitterSet::iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) return; if (emitter_iter->second->is_playing) { float offset = (milliseconds () - emitter_iter->second->play_start_time) / 1000.f + emitter_iter->second->cur_position; if (emitter_iter->second->sound_declaration.Looping ()) emitter_iter->second->cur_position = fmod (offset, (float)emitter_iter->second->duration); else emitter_iter->second->cur_position = offset < emitter_iter->second->duration ? offset : 0.0f; StopPlaying (emitter_iter); } } void StopSound (Emitter& emitter) { EmitterSet::iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) { emitter.Deactivate (); return; } if (emitter_iter->second->is_playing) StopPlaying (emitter_iter); emitter.Deactivate (); emitters.erase (emitter_iter); } void StopPlaying (EmitterSet::iterator emitter_iter) { emitter_iter->second->is_playing = false; if (emitter_iter->second->channel_number != -1) { device->Stop (emitter_iter->second->channel_number); free_channels.push (emitter_iter->second->channel_number); emitter_iter->second->channel_number = -1; } } float Tell (Emitter& emitter) { EmitterSet::iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) return 0.f; if (emitter_iter->second->is_playing) { float offset = (milliseconds () - emitter_iter->second->play_start_time) / 1000.f + emitter_iter->second->cur_position; if (emitter_iter->second->sound_declaration.Looping ()) return fmod (offset, (float)emitter_iter->second->duration); else return offset < emitter_iter->second->duration ? offset : 0.0f; } else return emitter_iter->second->cur_position; } float Duration (Emitter& emitter) const { EmitterSet::const_iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) return 0.f; return (float)emitter_iter->second->duration; } bool IsLooping (Emitter& emitter) const { EmitterSet::const_iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) return false; return emitter_iter->second->sound_declaration.Looping (); } bool IsPlaying (Emitter& emitter) const { EmitterSet::const_iterator emitter_iter = emitters.find (&emitter); if (emitter_iter == emitters.end ()) return false; return emitter_iter->second->is_playing; } }; /* Конструктор / деструктор */ SoundManager::SoundManager (const char* driver_mask, const char* device_mask, const char* init_string) : impl (new Impl (driver_mask, device_mask, init_string)) { } SoundManager::~SoundManager () { } /* Уровень громкости */ void SoundManager::SetVolume (float volume) { if (volume < 0.0f) volume = 0.0f; if (volume > 1.0f) volume = 1.0f; impl->volume = volume; impl->device->SetVolume (volume); } float SoundManager::Volume () const { return impl->volume; } /* Блокировка проигрывания звука */ void SoundManager::SetMute (bool state) { impl->SetMute (state); } bool SoundManager::IsMuted () const { return impl->is_muted; } /* Проигрывание звуков */ void SoundManager::PlaySound (Emitter& emitter, float offset) { impl->PlaySound (emitter, offset); } void SoundManager::StopSound (Emitter& emitter) { impl->StopSound (emitter); } float SoundManager::Tell (Emitter& emitter) const { return impl->Tell (emitter); } float SoundManager::Duration (Emitter& emitter) const { return impl->Duration (emitter); } bool SoundManager::IsLooping (Emitter& emitter) const { return impl->IsLooping (emitter); } bool SoundManager::IsPlaying (Emitter& emitter) const { return impl->IsPlaying (emitter); } /* Применение операции ко всем слушателям */ void SoundManager::ForEachEmitter (const EmitterHandler& emitter_handler) { for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i) emitter_handler (*(i->first)); } void SoundManager::ForEachEmitter (const ConstEmitterHandler& emitter_handler) const { for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i) emitter_handler (*(i->first)); } /* Применение операции ко всем слушателям c заданным типом */ void SoundManager::ForEachEmitter (const char* type, const EmitterHandler& emitter_handler) { if (!type) throw xtl::make_null_argument_exception ("sound::SoundManager::ForEachEmitter", "type"); for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i) if (!strcmp (type, i->second->sound_declaration.Type ())) emitter_handler (*(i->first)); } void SoundManager::ForEachEmitter (const char* type, const ConstEmitterHandler& emitter_handler) const { if (!type) throw xtl::make_null_argument_exception ("sound::SoundManager::ForEachEmitter", "type"); for (EmitterSet::iterator i = impl->emitters.begin (); i != impl->emitters.end (); ++i) if (!strcmp (type, i->second->sound_declaration.Type ())) emitter_handler (*(i->first)); } /* Регистрация обработчиков события удаления объекта */ xtl::connection SoundManager::RegisterDestroyHandler (xtl::trackable::slot_type& handler) { return impl->connect_tracker (handler); } xtl::connection SoundManager::RegisterDestroyHandler (const xtl::trackable::function_type& handler) { return impl->connect_tracker (handler); } xtl::connection SoundManager::RegisterDestroyHandler (const xtl::trackable::function_type& handler, xtl::trackable& trackable) { return impl->connect_tracker (handler, trackable); } /* Установка слушателя */ void SoundManager::SetListener (const sound::Listener& listener) { impl->listener = listener; impl->device->SetListener (listener); } const sound::Listener& SoundManager::Listener () const { return impl->listener; } /* Загрузка/выгрузка библиотек звуков */ void SoundManager::LoadSoundLibrary (const char* file_name) { impl->sound_declaration_libraries.push_front (SoundDeclarationLibrary (file_name)); for (SoundDeclarationLibraryList::iterator iter = ++impl->sound_declaration_libraries.begin (), end = impl->sound_declaration_libraries.end (); iter != end; ++iter) { if (!xtl::xstrcmp (file_name, iter->Name ())) { impl->sound_declaration_libraries.erase (iter); impl->log.Printf ("Warning: sound declaration library '%s' was reloaded", file_name); break; } } SoundDeclarationLibrary& new_library = impl->sound_declaration_libraries.front (); for (SoundDeclarationLibrary::Iterator iter = new_library.CreateIterator (); iter; ++iter) { const char* item_id = new_library.ItemId (iter); for (SoundDeclarationLibraryList::iterator library_iter = ++impl->sound_declaration_libraries.begin (), end = impl->sound_declaration_libraries.end (); library_iter != end; ++library_iter) { if (library_iter->Find (item_id)) { impl->log.Printf ("Warning: ignoring already loaded sound declaration with id '%s' - redefinition in library '%s'", item_id, file_name); continue; } } } } void SoundManager::UnloadSoundLibrary (const char* file_name) { if (!file_name) return; for (SoundDeclarationLibraryList::iterator iter = impl->sound_declaration_libraries.begin (), end = impl->sound_declaration_libraries.end (); iter != end; ++iter) { if (!xtl::xstrcmp (file_name, iter->Name ())) { impl->sound_declaration_libraries.erase (iter); break; } } }
33.539116
221
0.637341
68f869732418d1de819ccec3d477502ec2a8e751
2,715
cpp
C++
vkconfig/widget_preset.cpp
johnzupin/VulkanTools
4a4d824b43984d29902f7c8246aab99f0909151d
[ "Apache-2.0" ]
null
null
null
vkconfig/widget_preset.cpp
johnzupin/VulkanTools
4a4d824b43984d29902f7c8246aab99f0909151d
[ "Apache-2.0" ]
null
null
null
vkconfig/widget_preset.cpp
johnzupin/VulkanTools
4a4d824b43984d29902f7c8246aab99f0909151d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Valve Corporation * Copyright (c) 2020 LunarG, 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. * * Authors: * - Christophe Riccio <christophe@lunarg.com> */ #include "widget_preset.h" #include <cassert> PresetWidget::PresetWidget(QTreeWidgetItem* item, const Layer& layer, Parameter& parameter) : layer(layer), parameter(parameter) { assert(item); assert(&layer); assert(&parameter); this->blockSignals(true); this->addItem("User Defined Settings"); preset_indexes.push_back(Layer::NO_PRESET); for (std::size_t i = 0, n = layer.presets.size(); i < n; ++i) { const LayerPreset& layer_preset = layer.presets[i]; if (!(layer_preset.platform_flags & (1 << VKC_PLATFORM))) { continue; } this->addItem((layer_preset.label + " Preset").c_str()); preset_indexes.push_back(layer_preset.preset_index); } this->blockSignals(false); this->UpdateCurrentIndex(); connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPresetChanged(int))); } void PresetWidget::UpdateCurrentIndex() { int preset_index = layer.FindPresetIndex(parameter.settings); this->blockSignals(true); this->setCurrentIndex(GetComboBoxIndex(preset_index)); this->blockSignals(false); if (preset_index == Layer::NO_PRESET) return; const LayerPreset* preset = GetPreset(layer.presets, preset_index); assert(preset != nullptr); this->setToolTip(preset->description.c_str()); } int PresetWidget::GetComboBoxIndex(const int preset_index) const { for (std::size_t i = 0, n = preset_indexes.size(); i < n; ++i) { if (preset_indexes[i] == preset_index) return static_cast<int>(i); } assert(0); return -1; } void PresetWidget::OnPresetChanged(int combox_preset_index) { assert(combox_preset_index >= 0 && static_cast<std::size_t>(combox_preset_index) < preset_indexes.size()); const int preset_index = preset_indexes[combox_preset_index]; if (preset_index == Layer::NO_PRESET) return; const LayerPreset* preset = GetPreset(layer.presets, preset_index); assert(preset != nullptr); parameter.ApplyPresetSettings(*preset); }
31.569767
130
0.698343
68ff22d8df3673d6303576f88fc3fa40888fd4de
1,947
cpp
C++
network/src/network/loopPrivate.cpp
yandaomin/network
fd88844116d77639c7a76ec61fb352f2710f47a8
[ "Apache-2.0" ]
null
null
null
network/src/network/loopPrivate.cpp
yandaomin/network
fd88844116d77639c7a76ec61fb352f2710f47a8
[ "Apache-2.0" ]
null
null
null
network/src/network/loopPrivate.cpp
yandaomin/network
fd88844116d77639c7a76ec61fb352f2710f47a8
[ "Apache-2.0" ]
null
null
null
#include "loopPrivate.h" #include "async.h" #include "loop.h" // LoopPrivate::LoopPrivate() // : LoopPrivate(false) // { // isRunning_ = false; // } LoopPrivate::LoopPrivate(bool isDefault) { isRunning_ = false; if (isDefault) { loop_ = uv_default_loop(); } else { loop_ = new uv_loop_t(); ::uv_loop_init(loop_); } } LoopPrivate::~LoopPrivate() { if (!isDefaultLoop()) { uv_loop_close(loop_); delete async_; delete loop_; } } // LoopPrivate* LoopPrivate::defaultLoop() { // static LoopPrivate defaultLoop(true); // return &defaultLoop; // } uv_loop_t* LoopPrivate::handle() { return loop_; } bool LoopPrivate::isDefaultLoop() { return (loop_ == uv_default_loop()); } void LoopPrivate::init() { async_ = new Async((Loop*)parent_); } int LoopPrivate::run() { if (!isRunning_) { async_->init(); threadId_ = std::this_thread::get_id(); isRunning_ = true; auto rlt = ::uv_run(loop_, UV_RUN_DEFAULT); isRunning_ = false; return rlt; } return -1; } int LoopPrivate::runNoWait(){ if (!isRunning_) { async_->init(); threadId_ = std::this_thread::get_id(); isRunning_ = true; auto rst = ::uv_run(loop_, UV_RUN_NOWAIT); isRunning_ = false; return rst; } return -1; } int LoopPrivate::stop() { if (isRunning_){ async_->close([](Async* ptr) { ::uv_stop((uv_loop_t*)(ptr->loop()->handle())); }); return 0; } return -1; } bool LoopPrivate::isRunning() { return isRunning_; } bool LoopPrivate::isSameThread() { return std::this_thread::get_id() == threadId_; } void LoopPrivate::runInLoop(const ActionCallback func) { if (nullptr == func) return; if (isSameThread() || !isRunning()) { func(); return; } async_->run(func); } std::string LoopPrivate::getErrorMessage(int status) { if (WriteResult::result_disconnected == status) return "the connection is closed"; const char* msg = uv_strerror(status); std::string errMsg(msg); //delete[] msg; return errMsg; }
17.7
56
0.662044
ec026418b10f1e3f3595a30148bc55aec6ed70ab
21,184
cpp
C++
src/decifer/cpp/solver.cpp
brian-arnold/decifer
35be17f44988f55eb2a1cf71dc27ad2041c7d044
[ "BSD-3-Clause" ]
22
2019-05-04T10:50:41.000Z
2021-12-30T06:17:16.000Z
src/decifer/cpp/solver.cpp
brian-arnold/decifer
35be17f44988f55eb2a1cf71dc27ad2041c7d044
[ "BSD-3-Clause" ]
15
2019-07-23T09:13:03.000Z
2022-03-20T22:19:35.000Z
src/decifer/cpp/solver.cpp
brian-arnold/decifer
35be17f44988f55eb2a1cf71dc27ad2041c7d044
[ "BSD-3-Clause" ]
8
2019-07-24T12:56:02.000Z
2021-09-21T14:05:34.000Z
/* * solver.cpp * * Created on: 12-nov-2017 * Author: M. El-Kebir */ #include "solver.h" #include "stategraph.h" #include <iomanip> Solver::Solver(const ReadMatrix& R, int k, int nrSegments, double precisionBetaBin) : _R(R) , _k(k) , _nrSegments(nrSegments) , _precisionBetaBin(precisionBetaBin) , _logFactorial(1, 0) , _scriptT(R.getNrCharacters()) , _x() , _hatG() , _dOverallLB() , _dOverallUB() , _dLB(R.getNrCharacters()) , _dUB(R.getNrCharacters()) , _denominator(R.getNrCharacters(), DoubleVector(R.getNrSamples(), 0)) , _numerator(R.getNrCharacters()) , _xyStar(R.getNrCharacters()) , _logBinomCoeff(R.getNrSamples(), DoubleVector(R.getNrCharacters(), 0)) , _solD(_k, DoubleVector(R.getNrSamples(), 0)) , _solPi(_k, 1. / _k) , _solZ(R.getNrCharacters(), 0) , _logLikelihood(-std::numeric_limits<double>::max()) { // init binomial coefficient const int maxDepth = _R.getMaxReadDepth(); for (int i = 1; i <= maxDepth; ++i) { _logFactorial.push_back(_logFactorial.back() + log(i)); } } void Solver::initPWLA() { const int n = _R.getNrCharacters(); const int m = _R.getNrSamples(); // compute coord DoubleVector coord(_nrSegments); coord[0] = g_tol.epsilon(); coord[_nrSegments - 1] = 1; const double delta = 1. / (_nrSegments - 1); for (int alpha = 1; alpha < _nrSegments - 1; ++alpha) { coord[alpha] = delta * alpha; } // initialize segments const double infeasible_log = -1e300; _hatG = Double5Matrix(n); for (int i = 0; i < n; ++i) { const int scriptT_i_size = _scriptT[i].size(); _hatG[i] = Double4Matrix(scriptT_i_size); for (int t = 0; t < scriptT_i_size; ++t) { _hatG[i][t] = DoubleTensor(_k); for (int j = 0; j < _k; ++j) { _hatG[i][t][j] = DoubleMatrix(m); for (int p = 0; p < m; ++p) { _hatG[i][t][j][p] = DoubleVector(_nrSegments, 0); const int var_ip = _R.getVar(p, i); const int ref_ip = _R.getRef(p, i); for (int alpha = 0; alpha < _nrSegments; ++alpha) { double h = (coord[alpha] - _numerator[i][t][p]) / _denominator[i][p]; if (!g_tol.nonZero(h)) { h = 0; } else if (!g_tol.different(h, 1)) { h = 1; } // if (var_ip > 0 && (h <= 0 || !g_tol.nonZero(h))) // { // _hatG[i][t][j][p][alpha] = infeasible_log;//log(g_tol.epsilon()); // } // else if (ref_ip > 0 && (h >= 1 || g_tol.less(1, h))) // { // _hatG[i][t][j][p][alpha] = infeasible_log;//log(g_tol.epsilon()); // } // else { double likelihood = getLogLikelihood(var_ip, ref_ip, h); // assert(!isinf(likelihood)); // assert(!isnan(likelihood)); if (likelihood < infeasible_log || isnan(likelihood) || isinf(likelihood)) { _hatG[i][t][j][p][alpha] = infeasible_log;//log(g_tol.epsilon()); } else { _hatG[i][t][j][p][alpha] = likelihood; } } } } } } } } StateTree Solver::convertToStateTreeFromSNVF(const ReadMatrix& R, const StateEdgeSet& T_it, const DoubleVector& f_i, const int i) { assert(R.getNrSamples() == f_i.size()); IntVector pi; std::map<StateGraph::CnaTriple, int> vertices; StateGraph::CnaTripleSet verticesPreMut, verticesPostMut; StateGraph::CnaTriple mutationVertex; StateGraph::partition(T_it, verticesPreMut, verticesPostMut, mutationVertex); assert(mutationVertex._x != -1); assert(mutationVertex._y != -1); vertices[StateGraph::CnaTriple(1, 1, 0)] = 0; pi.push_back(-1); for (const StateGraph::StateEdge& edge : T_it) { if (vertices.count(edge.first) == 0) { vertices[edge.first] = pi.size(); pi.push_back(-1); } if (vertices.count(edge.second) == 0) { vertices[edge.second] = pi.size(); pi.push_back(vertices[edge.first]); } pi[vertices[edge.second]] = vertices[edge.first]; } StateTree S_it(pi); for (int p = 0; p < f_i.size(); ++p) { double muTotal = 0; for (const ReadMatrix::CopyNumberState& cnState : R.getCopyNumberStates(p, i)) { muTotal += (cnState._x + cnState._y) * cnState._mu; } double muMut = 0; for (const auto& kv : vertices) { if (kv.first._x != mutationVertex._x || kv.first._y != mutationVertex._y) { muMut += kv.first._z * R.getMu(p, i, kv.first._x, kv.first._y); } } double muStar = R.getMu(p, i, mutationVertex._x, mutationVertex._y); const double h_ip = f_i[p]; for (const auto& kv : vertices) { if (p == 0) { S_it.setCnState(kv.second, kv.first._x, kv.first._y, kv.first._z); } if (kv.first._x != mutationVertex._x || kv.first._y != mutationVertex._y) { S_it.setMixtureProportion(kv.second, R.getMu(p, i, kv.first._x, kv.first._y)); } else if (kv.first._x == mutationVertex._x && kv.first._y == mutationVertex._y && kv.first._z == 1) { double s_mut = h_ip * muTotal - muMut; S_it.setMixtureProportion(kv.second, s_mut); } else { assert(kv.first._x == mutationVertex._x && kv.first._y == mutationVertex._y && kv.first._z == 0); double s_nonMut = muStar - (h_ip * muTotal - muMut); S_it.setMixtureProportion(kv.second, s_nonMut); } } } return S_it; } StateTree Solver::convertToStateTreeFromDCF(const ReadMatrix& R, const StateEdgeSet& T_it, const DoubleVector& d_i, const int i) { assert(R.getNrSamples() == d_i.size()); // parent vector IntVector pi; std::map<StateGraph::CnaTriple, int> vertices; StateGraph::CnaTripleSet verticesPreMut, verticesPostMut; StateGraph::CnaTriple mutationVertex; StateGraph::partition(T_it, verticesPreMut, verticesPostMut, mutationVertex); assert(mutationVertex._x != -1); assert(mutationVertex._y != -1); vertices[StateGraph::CnaTriple(1, 1, 0)] = 0; pi.push_back(-1); for (const StateGraph::StateEdge& edge : T_it) { if (vertices.count(edge.first) == 0) { vertices[edge.first] = pi.size(); pi.push_back(-1); } if (vertices.count(edge.second) == 0) { vertices[edge.second] = pi.size(); pi.push_back(vertices[edge.first]); } pi[vertices[edge.second]] = vertices[edge.first]; } StateTree S_it(pi); for (int p = 0; p < d_i.size(); ++p) { for (const auto& kv : vertices) { if (p == 0) { S_it.setCnState(kv.second, kv.first._x, kv.first._y, kv.first._z); } } double massPreMut = 0, massPostMut = 0, massMut = 0; for (int idx = 0; idx < S_it.numVertices(); ++idx) { int x = S_it.x(idx); int y = S_it.y(idx); int z = S_it.z(idx); if (S_it.isPresent(idx)) { if (x == mutationVertex._x && y == mutationVertex._y && z == mutationVertex._z) { massMut = R.getMu(p, i, x, y); } else if (verticesPreMut.count(StateGraph::CnaTriple(x, y, z)) == 1) { massPreMut += R.getMu(p, i, x, y); } else { assert(verticesPostMut.count(StateGraph::CnaTriple(x, y, z)) == 1); massPostMut += R.getMu(p, i, x, y); } } } double muTotal = 0; for (const ReadMatrix::CopyNumberState& cnState : R.getCopyNumberStates(p, i)) { muTotal += (cnState._x + cnState._y) * cnState._mu; } // add all mu's that are not (x*,y*) double muMut = 0; for (const auto& kv : vertices) { if (kv.first._x != mutationVertex._x || kv.first._y != mutationVertex._y) { muMut += kv.first._z * R.getMu(p, i, kv.first._x, kv.first._y); } } const double d_ip = d_i[p]; for (const auto& kv : vertices) { if (p == 0) { S_it.setCnState(kv.second, kv.first._x, kv.first._y, kv.first._z); } if (kv.first._x != mutationVertex._x || kv.first._y != mutationVertex._y) { S_it.setMixtureProportion(kv.second, R.getMu(p, i, kv.first._x, kv.first._y)); } else if (kv.first._x == mutationVertex._x && kv.first._y == mutationVertex._y && kv.first._z == 1) { double s_mut = d_ip - massPostMut; S_it.setMixtureProportion(kv.second, s_mut); } else { assert(kv.first._x == mutationVertex._x && kv.first._y == mutationVertex._y && kv.first._z == 0); double s_nonMut = massMut - (d_ip - massPostMut); S_it.setMixtureProportion(kv.second, s_nonMut); } } } return S_it; } void Solver::init(int i) { const int n = _R.getNrCharacters(); const int m = _R.getNrSamples(); assert(0 <= i && i < n); // 0. obtain L const ReadMatrix::CopyNumberStateVector& cnStates = _R.getCopyNumberStates(0, i); // + 1 is done on purpose, allowing the following state tree for instance // (1,1,0) -> (2,2,0) -> (2,2,1) -> (2,0,1) const int maxCopies = _R.getMaxCopies(i) + 1; IntPairSet L; for (const ReadMatrix::CopyNumberState& cnState : cnStates) { L.insert(IntPair(cnState._x, cnState._y)); } // 1. enumerate all state trees const auto& res = StateGraph::getStateTrees(L, maxCopies); _scriptT[i] = StateEdgeSetVector(res.begin(), res.end()); // 2. initialize D for (int p = 0; p < m; ++p) { const ReadMatrix::CopyNumberStateVector& cnStates_p = _R.getCopyNumberStates(p, i); for (const ReadMatrix::CopyNumberState& cnState : cnStates_p) { _denominator[i][p] += (cnState._x + cnState._y) * cnState._mu; } } // 3. initialize C, _xyStar, _gamma, f_LB and _fUB _numerator[i] = DoubleMatrix(_scriptT[i].size(), DoubleVector(m, 0)); _xyStar[i] = IntPairVector(_scriptT[i].size(), IntPair(-1, -1)); _dLB[i] = DoubleMatrix(_scriptT[i].size(), DoubleVector(m, 0)); _dUB[i] = DoubleMatrix(_scriptT[i].size(), DoubleVector(m, 1)); for (int t = 0; t < _scriptT[i].size(); ++t) { StateGraph::StateEdgeSet& T_it = _scriptT[i][t]; StateGraph::CnaTripleSet verticesPreMut, verticesPostMut; StateGraph::CnaTriple mutationVertex; StateGraph::partition(T_it, verticesPreMut, verticesPostMut, mutationVertex); _xyStar[i][t].first = mutationVertex._x; _xyStar[i][t].second = mutationVertex._y; for (int p = 0; p < m; ++p) { for (const auto& xyz : verticesPostMut) { if (xyz == mutationVertex) continue; // switch (_statType) // { // case CLUSTER_DCF: _dLB[i][t][p] += _R.getMu(p, i, xyz._x, xyz._y); _numerator[i][t][p] += (1 - xyz._z) * _R.getMu(p, i, xyz._x, xyz._y); // break; // case CLUSTER_CCF: // if (xyz._z > 0) // { _dLB[i][t][p] += _R.getMu(p, i, xyz._x, xyz._y); _numerator[i][t][p] += (1 - xyz._z) * _R.getMu(p, i, xyz._x, xyz._y); // } // break; // } } _dUB[i][t][p] = _dLB[i][t][p] + _R.getMu(p, i, mutationVertex._x, mutationVertex._y); if (!g_tol.different(_dLB[i][t][p], _dUB[i][t][p])) { _dUB[i][t][p] = _dLB[i][t][p]; } // const double h_lb = (_dLB[i][t][p] - _numerator[i][t][p]) / _denominator[i][p]; // if ((h_lb <= 0 || !g_tol.nonZero(h_lb)) && _R.getVar(p, i) != 0) // { // _dLB[i][t][p] += 1e-2; // } // const double h_ub = (_dUB[i][t][p] - _numerator[i][t][p]) / _denominator[i][p]; // if ((h_ub >= 1 || g_tol.less(1, h_ub)) && _R.getRef(p, i) != 0) // { // _dUB[i][t][p] -= 1e-2; // } } } // 4. initialize _logBinomCoeff for (int p = 0; p < m; ++p) { int var_pi = _R.getVar(p, i); int ref_pi = _R.getRef(p, i); int tot_pi = var_pi + ref_pi; _logBinomCoeff[p][i] = _logFactorial[tot_pi] - (_logFactorial[var_pi] + _logFactorial[ref_pi]); } } void Solver::init() { const int n = _R.getNrCharacters(); for (int i = 0; i < n; ++i) { init(i); } return; } double Solver::getLogLikelihood(int var, int ref, double f) const { if (!g_tol.nonZero(f)) { f = 1e-3; } if (!g_tol.different(1, f)) { f = 1 - 1e-3; } if (!g_tol.nonZero(f) && var == 0) { return 0; } if (!g_tol.different(1, f) && ref == 0) { return 0; } if (_precisionBetaBin > 0) { double val = lgamma(var + ref + 1) + lgamma(var + _precisionBetaBin * f) + lgamma(ref + _precisionBetaBin * (1-f)) + lgamma(_precisionBetaBin); val -= (lgamma(var + 1) + lgamma(ref + 1) + lgamma(var + ref + _precisionBetaBin) + lgamma(_precisionBetaBin*f) + lgamma(_precisionBetaBin*(1-f))); return val; } else { return lgamma(var + ref + 1) - lgamma(var + 1) - lgamma(ref + 1) + var * log(f) + ref * log(1 - f); } } double Solver::getLogLikelihood(int i) const { const int n = _R.getNrCharacters(); const int m = _R.getNrSamples(); assert(0 <= i && i < n); const int maxCopyNumber = _R.getMaxCopies(i); double sum_i = 0; const StateEdgeSetVector& scriptT_i = _scriptT[i]; const int size_scriptT_i = scriptT_i.size(); for (int t = 0; t < size_scriptT_i; ++t) { const StateEdgeSet& T_it = scriptT_i[t]; for (int j = 0; j < _k; ++j) { if (_solPi[j] == 0) continue; if (!isEnabled(i, t, j)) continue; double prod = _solPi[j] / size_scriptT_i; double log_prod = log(prod); for (int p = 0; p < m; ++p) { const ReadMatrix::CopyNumberStateVector& cnStates_pi = _R.getCopyNumberStates(p, i); const int var_pi = _R.getVar(p, i); const int ref_pi = _R.getRef(p, i); if (isFeasible(_solD[j][p], _xyStar[i][t], cnStates_pi, T_it, maxCopyNumber)) { const double h = (_solD[j][p] - _numerator[i][t][p]) / _denominator[i][p]; // assert(_denominator[i][p] != 0); // if (!((!(h <= 0 || !g_tol.nonZero(h)) || var_pi == 0) && (!(h >= 1 || g_tol.less(1, h)) || ref_pi == 0))) // { // prod = 0; // break; // } // else { const double val = getLogLikelihood(var_pi, ref_pi, h); log_prod += val; // prod *= exp(val); // prod = std::max(std::numeric_limits<double>::min(), prod); } } else { prod = 0; break; } } if (prod != 0) { //sum_i += prod; prod = exp(log_prod); prod = std::max(std::numeric_limits<double>::min(), prod); sum_i += prod; } } } return log(sum_i); } double Solver::updateLogLikelihood() { const int n = _R.getNrCharacters(); double oldLogLikelihood = _logLikelihood; _logLikelihood = 0; for (int i = 0; i < n; ++i) { double L_i = getLogLikelihood(i); _logLikelihood += L_i; // std::cout << i << ": " << L_i << std::endl; } // std::cout << std::endl; return _logLikelihood - oldLogLikelihood; } bool Solver::isFeasible(const double f_pj, const IntPair& xyStar, const ReadMatrix::CopyNumberStateVector& cnStates, const StateEdgeSet& T_it, const int maxCopyNumber) const { DoubleTensor s(maxCopyNumber + 1, DoubleMatrix(maxCopyNumber + 1, DoubleVector(maxCopyNumber + 1, 0))); // 2a. get vertices of state tree StateGraph::CnaTripleSet vertices; vertices.insert(StateGraph::CnaTriple(1,1,0)); StateGraph::StateEdge mutEdge; for (const StateGraph::StateEdge& st : T_it) { vertices.insert(st.first); vertices.insert(st.second); // check whether st is a mutation edge if (st.second._x == xyStar.first && st.second._y == xyStar.second && st.second._x == st.first._x && st.second._y == st.first._y) { assert(st.second._z > 0); mutEdge = st; } } StateGraph::CnaTripleSet verticesPreMutS, verticesPostMutS; StateGraph::CnaTriple mutationVertex; StateGraph::partition(T_it, verticesPreMutS, verticesPostMutS, mutationVertex); // 2b. compute mass pre mutation, and mass post mut double massPreMut = 0, massPostMut = 0, massMut = 0; for (const ReadMatrix::CopyNumberState& cnState : cnStates) { if (cnState._x == xyStar.first && cnState._y == xyStar.second) { massMut = cnState._mu; } } for (const StateGraph::CnaTriple& xyz : vertices) { if (xyz != mutationVertex) { for (const ReadMatrix::CopyNumberState& cnState : cnStates) { if (cnState._x == xyz._x && cnState._y == xyz._y) { if (verticesPostMutS.count(xyz) == 1) { // if (_statType == CLUSTER_DCF || xyz._z > 0) { massPostMut += cnState._mu; } s[xyz._x][xyz._y][xyz._z] = massPostMut; } else { assert(verticesPreMutS.count(xyz) == 1); assert(xyz._z == 0); massPreMut += cnState._mu; s[xyz._x][xyz._y][xyz._z] = massPreMut; } } } } } if (g_tol.less(f_pj, massPostMut)) { return false; } double slack = f_pj - massPostMut; if (g_tol.less(massMut, slack)) { return false; } s[mutEdge.second._x][mutEdge.second._y][mutEdge.second._z] = slack; s[mutEdge.first._x][mutEdge.first._y][mutEdge.first._z] = massMut - slack; return true; } void Solver::writeSolution(std::ostream& out) const { const int m = _R.getNrSamples(); out << _k << " #clusters" << std::endl; out << m << " #samples" << std::endl; for (int j = 0; j < _k; ++j) { for (int p = 0; p < m; ++p) { if (p != 0) { out << " "; } out << _solD[j][p]; } out << std::endl; } for (int j = 0; j < _k; ++j) { out << _solPi[j] << std::endl; } } void Solver::readSolution(std::istream& in, DoubleMatrix& outF, DoubleVector& outPi) { g_lineNumber = 0; int k = -1; int m = -1; g_lineNumber = 0; std::string line; getline(in, line); std::stringstream ss(line); ss >> k; getline(in, line); ss.clear(); ss.str(line); ss >> m; DoubleMatrix f(k, DoubleVector(m, -1)); for (int j = 0; j < k; ++j) { getline(in, line); ss.clear(); ss.str(line); for (int p = 0; p < m; ++p) { ss >> f[j][p]; if (!(0 <= f[j][p] && f[j][p] <= 1)) { throw std::runtime_error(getLineNumber() + "Error: Invalid DCF"); } } } DoubleVector pi(k, -1); for (int j = 0; j < k; ++j) { getline(in, line); ss.clear(); ss.str(line); ss >> pi[j]; if (!(0 <= pi[j] && pi[j] <= 1)) { throw std::runtime_error(getLineNumber() + "Error: Invalid pi."); } } outF = f; outPi = pi; } bool Solver::readSolution(std::istream& in) { DoubleMatrix f; DoubleVector pi; try { readSolution(in, f, pi); if (f.size() != _k) { std::cerr << "Error: Invalid k" << std::endl; return false; } if (f[0].size() != _R.getNrSamples()) { std::cerr << "Error: Invalid m" << std::endl; return false; } _solD = f; _solPi = pi; updateLogLikelihood(); return true; } catch (std::runtime_error& e) { std::cerr << e.what() << std::endl; return false; } } void Solver::writeClustering(std::ostream& out) const { const int n = _R.getNrCharacters(); for (int i = 0; i < n; ++i) { out << i << "\t" << _R.indexToCharacter(i) << "\t" << _solZ[i] << std::endl; } } void Solver::writeMutationProperties(std::ostream& out) const { const int m = _R.getNrSamples(); const int n = _R.getNrCharacters(); out << "SNV"; out << "\tcluster"; for (int p = 0; p < m; ++p) { // if (_statType == CLUSTER_DCF) { out << "\tdcf" << p; } // else // { // out << "\tccf" << p; // } } out << std::endl; for (int i = 0; i < n; ++i) { out << i; out << "\t" << _solZ[i]; for (int p = 0; p < m; ++p) { out << "\t" << std::setprecision(2) << _solD[_solZ[i]][p]; } out << std::endl; } }
26.381071
151
0.527898
ec087b40fc0aeb9bb7862421ed3d0a0427b72406
170
hpp
C++
dfg/dataAnalysisAll.hpp
tc3t/dfglib
7157973e952234a010da8e9fbd551a912c146368
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
1
2017-08-01T04:42:29.000Z
2017-08-01T04:42:29.000Z
dfg/dataAnalysisAll.hpp
tc3t/dfglib
7157973e952234a010da8e9fbd551a912c146368
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
128
2018-04-06T23:01:51.000Z
2022-03-31T20:19:38.000Z
dfg/dataAnalysisAll.hpp
tc3t/dfglib
7157973e952234a010da8e9fbd551a912c146368
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
3
2018-03-21T01:11:05.000Z
2021-04-05T19:20:31.000Z
#pragma once #include "dataAnalysis/correlation.hpp" #include "dataAnalysis/smoothWithNeighbourAverages.hpp" #include "dataAnalysis/smoothWithNeighbourMedians.hpp"
28.333333
56
0.823529
ec0ecae6922b038f7a8c11091a6209d1259ba087
1,271
cpp
C++
week08/lesson/743-network-delay-time-Dijkstra.cpp
MiracleWong/algorithm-learning-camp
aa5bee8f12dc25992aaebd46647537633bf1207f
[ "MIT" ]
null
null
null
week08/lesson/743-network-delay-time-Dijkstra.cpp
MiracleWong/algorithm-learning-camp
aa5bee8f12dc25992aaebd46647537633bf1207f
[ "MIT" ]
null
null
null
week08/lesson/743-network-delay-time-Dijkstra.cpp
MiracleWong/algorithm-learning-camp
aa5bee8f12dc25992aaebd46647537633bf1207f
[ "MIT" ]
null
null
null
class Solution { public: int networkDelayTime(vector<vector<int>>& times, int n, int k) { // 建立图 vector<vector<int>> ver(n+1, vector<int>()); vector<vector<int>> edge(n+1, vector<int>()); for (auto& e: times) { int x = e[0], y = e[1], z = e[2]; ver[x].push_back(y); edge[x].push_back(z); } vector<int> dist(n+1, 1e9); vector<bool> v(n+1, false); // expand是否扩展过 dist[k] = 0; // dist 编号 priority_queue<pair<int,int>> q; q.push(make_pair(-dist[k], k)); // Dijkstra 算法 while (!q.empty()) { int x = q.top().second; q.pop(); if (v[x]) continue; v[x] = true; for (int i = 0; i < ver[x].size(); i++) { int y = ver[x][i]; int z = edge[x][i]; if (dist[x] + z < dist[y]) { dist[y] = dist[x] + z; q.push(make_pair(-dist[y], y)); } } } int ans = 0; for (int i=1; i <= n; i++) { cout << "dist[i]" << dist[i] << endl; ans = max(ans, dist[i]); } if (ans == 1e9) ans = -1; return ans; } };
28.886364
68
0.389457
ec0eef56d74c1c6cc4dae12c44f81b1e0cf72c91
689
cpp
C++
benchmarks/clean_shared_memory.cpp
MaximilienNaveau/shared_memory
1440454759cdd19e0d898753d86b8714c1aefa84
[ "BSD-3-Clause" ]
2
2020-09-08T04:01:02.000Z
2021-01-28T15:02:11.000Z
benchmarks/clean_shared_memory.cpp
MaximilienNaveau/shared_memory
1440454759cdd19e0d898753d86b8714c1aefa84
[ "BSD-3-Clause" ]
13
2019-09-24T17:21:49.000Z
2021-03-02T10:09:03.000Z
benchmarks/clean_shared_memory.cpp
MaximilienNaveau/shared_memory
1440454759cdd19e0d898753d86b8714c1aefa84
[ "BSD-3-Clause" ]
2
2019-05-06T08:25:35.000Z
2020-04-14T11:49:02.000Z
/** * @file clean_shared_memory.cpp * @author Vincent Berenz * @license License BSD-3-Clause * @copyright Copyright (c) 2019, New York University and Max Planck * Gesellschaft. * @date 2019-05-22 * * @brief Clean the shared memory of the benchmark, the unnittests, ... */ #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/sync/named_mutex.hpp> #include "shared_memory/benchmarks/benchmark_common.hh" int main() { boost::interprocess::named_mutex::remove(SHM_NAME.c_str()); boost::interprocess::shared_memory_object::remove(SHM_OBJECT_NAME.c_str()); boost::interprocess::shared_memory_object::remove("main_memory"); return 0; }
29.956522
79
0.744557
ec1575753c7539cdf739067f1dad2f0a0b145d89
1,263
cpp
C++
solutions/partition_to_k_equal_sum_subsets.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/partition_to_k_equal_sum_subsets.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
solutions/partition_to_k_equal_sum_subsets.cpp
kmykoh97/My-Leetcode
0ffdea16c3025805873aafb6feffacaf3411a258
[ "Apache-2.0" ]
null
null
null
// Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. // Example 1: // Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 // Output: True // Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums. // Note: // 1 <= k <= len(nums) <= 16. // 0 < nums[i] < 10000. // solution: dfs class Solution { public: bool dfs(const vector<int>& nums, int target, int cur, int k, int used) { if (k == 0) return (used == (1 << nums.size())-1); for (int i = 0; i < nums.size(); ++i) { if (used & (1 << i)) continue; int t = cur+nums[i]; if (t > target) break; int new_used = used | (1 << i); if (t == target && dfs(nums, target, 0, k-1, new_used)) return true; else if (dfs(nums, target, t, k, new_used)) return true; } return false; } bool canPartitionKSubsets(vector<int>& nums, int k) { const int sum = accumulate(nums.begin(), nums.end(), 0); if (sum % k != 0) return false; sort(nums.begin(), nums.end()); return dfs(nums, sum/k, 0, k, 0); } };
29.372093
159
0.524941
ec1b25669f107c859b42ff23c246f036309fd584
961
cc
C++
third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
#include "third_party/blink/renderer/modules/peerconnection/rtc_encoded_audio_receiver_sink_optimizer.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" namespace blink { RtcEncodedAudioReceiverSinkOptimizer::RtcEncodedAudioReceiverSinkOptimizer( UnderlyingSinkSetter set_underlying_sink, scoped_refptr<blink::RTCEncodedAudioStreamTransformer::Broker> transformer) : set_underlying_sink_(std::move(set_underlying_sink)), transformer_(std::move(transformer)) {} UnderlyingSinkBase* RtcEncodedAudioReceiverSinkOptimizer::PerformInProcessOptimization( ScriptState* script_state) { auto* new_sink = MakeGarbageCollected<RTCEncodedAudioUnderlyingSink>( script_state, std::move(transformer_)); std::move(set_underlying_sink_).Run(WrapCrossThreadPersistent(new_sink)); return new_sink; } } // namespace blink
38.44
104
0.825182
ec1df7964614a4d7c573d595175c61fd57240122
3,463
cpp
C++
Queries/LanguageQuery.cpp
garmin/ActiveCaptainCommunitySDK-common
a7574a3b85b77771ceb47e5fc9a99fd31a10d47a
[ "Apache-2.0" ]
null
null
null
Queries/LanguageQuery.cpp
garmin/ActiveCaptainCommunitySDK-common
a7574a3b85b77771ceb47e5fc9a99fd31a10d47a
[ "Apache-2.0" ]
null
null
null
Queries/LanguageQuery.cpp
garmin/ActiveCaptainCommunitySDK-common
a7574a3b85b77771ceb47e5fc9a99fd31a10d47a
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------------ Copyright 2021 Garmin Ltd. or its subsidiaries. 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 Class to represent a specific set of queries Copyright 2017-2020 by Garmin Ltd. or its subsidiaries. */ #define DBG_MODULE "ACDB" #define DBG_TAG "LanguageQuery" #include "ACDB_pub_types.h" #include "Acdb/Queries/LanguageQuery.hpp" #include "DBG_pub.h" #include "SQLiteCpp/Column.h" namespace Acdb { static const std::string ReadSql{"SELECT id, isoCode FROM languageType;"}; static const std::string WriteSql{ "INSERT OR REPLACE INTO languageType (id, isoCode) VALUES (?, ?)"}; //---------------------------------------------------------------- //! //! @public //! @detail Create Language query object. //! //---------------------------------------------------------------- LanguageQuery::LanguageQuery(SQLite::Database& aDatabase) { try { mRead.reset(new SQLite::Statement{aDatabase, ReadSql}); mWrite.reset(new SQLite::Statement{aDatabase, WriteSql}); } catch (const SQLite::Exception& e) { DBG_W("SQLite Exception: %i %s", e.getErrorCode(), e.getErrorStr()); mRead.reset(); mWrite.reset(); } } // End of LanguageQuery //---------------------------------------------------------------- //! //! @public //! @detail Get all objects from database //! //---------------------------------------------------------------- bool LanguageQuery::GetAll(std::vector<LanguageTableDataType>& aResultOut) { enum Columns { Id = 0, IsoCode }; if (!mRead) { return false; } bool success = false; try { while (mRead->executeStep()) { LanguageTableDataType result; result.mId = mRead->getColumn(Columns::Id).getInt(); result.mIsoCode = mRead->getColumn(Columns::IsoCode).getText(); aResultOut.push_back(std::move(result)); } success = !aResultOut.empty(); mRead->reset(); } catch (const SQLite::Exception& e) { DBG_W("SQLite Exception: %i %s", e.getErrorCode(), e.getErrorStr()); success = false; } return success; } // End of GetAll //---------------------------------------------------------------- //! //! @public //! @brief Write language to database //! //---------------------------------------------------------------- bool LanguageQuery::Write(LanguageTableDataType&& aLanguageTableData) { enum Parameters { Id = 1, IsoCode }; if (!mWrite) { return false; } bool success = false; try { mWrite->bind(Parameters::Id, aLanguageTableData.mId); mWrite->bind(Parameters::IsoCode, aLanguageTableData.mIsoCode); success = mWrite->exec(); mWrite->reset(); } catch (const SQLite::Exception& e) { DBG_W("SQLite Exception: %i %s", e.getErrorCode(), e.getErrorStr()); success = false; } return success; } // End of Write } // end of namespace Acdb
28.619835
80
0.574646
ec1f214e9a1c35cd7ee04a0109985f1a428a2937
2,473
hpp
C++
third-party/Empirical/include/emp/io/ascii_utils.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/include/emp/io/ascii_utils.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/include/emp/io/ascii_utils.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
/** * @note This file is part of Empirical, https://github.com/devosoft/Empirical * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2020 * * @file ascii_utils.hpp * @brief Tools for working with ascii output. * @note Status: ALPHA * */ #ifndef EMP_ASCII_UTILS_H #define EMP_ASCII_UTILS_H #include <iostream> #include <ostream> #include "../base/assert.hpp" #include "../base/vector.hpp" #include "../datastructs/vector_utils.hpp" namespace emp { /// The following function prints an ascii bar graph on to the screen (or provided stream). template <typename T> void AsciiBarGraph( emp::vector<T> data, size_t max_width=80, ///< What's the widest bars allowed? bool show_scale=true, ///< Should we show the scale at bottom. bool max_scale_1=true, ///< Should we limit scaling to 1:1? std::ostream & os=std::cout) ///< Where to output the bar graph? { T min_size = emp::FindMin(data); T max_size = emp::FindMax(data); double scale = ((double) max_width) / ((double) max_size); if (max_scale_1 && scale > 1.0) scale = 1.0; for (T datum : data) { double bar_width = datum * scale; while (bar_width >= 1.0) { os << '='; bar_width -= 1.0; } if (bar_width > 0.0) os << '~'; os << " (" << datum << ")\n"; } if (show_scale) { os << "SCALE: = -> " << (1.0 / scale) << std::endl; } } /// Take the input data, break it into bins, and print it as a bar graph. template <typename T> void AsciiHistogram(emp::vector<T> data, size_t num_bins=40, ///< How many bins in histogram? size_t max_width=80, ///< What's the widest bars allowed? bool show_scale=true, ///< Should we show the scale at bottom? std::ostream & os=std::cout) ///< Where to output the bar graph? { T min_val = emp::FindMin(data); T max_val = emp::FindMax(data); T val_range = max_val - min_val; T bin_width = val_range / (T) num_bins; emp::vector<size_t> bins(num_bins, 0); for (T d : data) { size_t bin_id = (size_t) ( (d - min_val) / bin_width ); if (bin_id == num_bins) bin_id--; bins[bin_id]++; } AsciiBarGraph<size_t>(bins, max_width, show_scale, true, os); } } #endif
33.418919
96
0.57501
ec1f273a78a9da8364d7fbaac6258d91b67b5c61
341
cc
C++
relative_path.cc
dancerj/gitlstreefs
f5eca366643a47814d3a12bc458e64a6a093e315
[ "BSD-3-Clause" ]
2
2015-10-05T10:30:14.000Z
2018-09-10T05:35:04.000Z
relative_path.cc
dancerj/gitlstreefs
f5eca366643a47814d3a12bc458e64a6a093e315
[ "BSD-3-Clause" ]
1
2015-10-04T16:58:10.000Z
2015-10-18T08:53:04.000Z
relative_path.cc
dancerj/gitlstreefs
f5eca366643a47814d3a12bc458e64a6a093e315
[ "BSD-3-Clause" ]
1
2015-09-28T04:25:20.000Z
2015-09-28T04:25:20.000Z
#include "relative_path.h" #include <assert.h> #include <string> using std::string; string GetRelativePath(const char* path) { // Input is /absolute/path/below // convert to a relative path. assert(*path != 0); if (path[1] == 0) { // special-case / ? "" isn't a good relative path. return "./"; } return path + 1; }
17.05
54
0.615836
ec213f9231c8fb1d202eee73c015179b132f8df4
5,346
cpp
C++
01_Develop/libXMCocos2D/Source/extensions/CCScrollView/CCSorting.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMCocos2D/Source/extensions/CCScrollView/CCSorting.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMCocos2D/Source/extensions/CCScrollView/CCSorting.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* -------------------------------------------------------------------------- * * File CCSorting.cpp * Author Y.H Mun * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 cocos2d-x.org * Copyright (c) 2010 Sangwoo Im * * http://www.cocos2d-x.org * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. All rights reserved. * * Contact Email: xmsoft77@gmail.com * * -------------------------------------------------------------------------- * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 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 in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "extensions/CCScrollView/CCSorting.h" #include "cocoa/CCString.h" NS_CC_BEGIN class CCSortedObject : public CCObject, public CCSortableObject { public : CCSortedObject ( KDvoid ) { m_uObjectID = 0; } virtual KDvoid setObjectID ( KDuint uObjectID ) { m_uObjectID = uObjectID; } virtual KDuint getObjectID ( KDvoid ) { return m_uObjectID; } private : KDuint m_uObjectID; }; CCArrayForObjectSorting::CCArrayForObjectSorting ( KDvoid ) : CCArray ( ) { } KDvoid CCArrayForObjectSorting::insertSortedObject ( CCSortableObject* pObject ) { KDuint uIdx; CCObject* pObj = dynamic_cast<CCObject*> ( pObject ); CCAssert ( pObj, "Invalid parameter." ); uIdx = this->indexOfSortedObject ( pObject ); this->insertObject ( pObj, uIdx ); } KDvoid CCArrayForObjectSorting::removeSortedObject ( CCSortableObject* pObject ) { if ( this->count ( ) == 0 ) { return; } KDuint uIdx; CCSortableObject* pFoundObj; uIdx = this->indexOfSortedObject ( pObject ); if ( uIdx < this->count ( ) && uIdx != CC_INVALID_INDEX ) { pFoundObj = dynamic_cast<CCSortableObject*> ( this->objectAtIndex ( uIdx ) ); if ( pFoundObj->getObjectID ( ) == pObject->getObjectID ( ) ) { this->removeObjectAtIndex ( uIdx ); } } } KDvoid CCArrayForObjectSorting::setObjectID_ofSortedObject ( KDuint uTag, CCSortableObject* pObject ) { CCSortableObject* pFoundObj; KDuint uIdx; uIdx = this->indexOfSortedObject ( pObject ); if ( uIdx < this->count ( ) && uIdx != CC_INVALID_INDEX ) { pFoundObj = dynamic_cast<CCSortableObject*> ( this->objectAtIndex ( uIdx ) ); CCObject* pObj = dynamic_cast<CCObject*> ( pFoundObj ); pObj->retain ( ); if ( pFoundObj->getObjectID ( ) == pObject->getObjectID ( ) ) { this->removeObjectAtIndex ( uIdx ); pFoundObj->setObjectID ( uTag ); this->insertSortedObject ( pFoundObj ); pObj->release ( ); } else { pObj->release ( ); } } } CCSortableObject* CCArrayForObjectSorting::objectWithObjectID ( KDuint uTag ) { if ( this->count ( ) == 0 ) { return KD_NULL; } KDuint uIdx; CCSortableObject* pFoundObj; pFoundObj = new CCSortedObject ( ); pFoundObj->setObjectID ( uTag ); uIdx = this->indexOfSortedObject ( pFoundObj ); ( (CCSortedObject*) pFoundObj )->release ( ); pFoundObj = KD_NULL; if ( uIdx < this->count ( ) && uIdx != CC_INVALID_INDEX ) { pFoundObj = dynamic_cast<CCSortableObject*> ( this->objectAtIndex ( uIdx ) ); if ( pFoundObj->getObjectID ( ) != uTag ) { pFoundObj = KD_NULL; } } return pFoundObj; } KDuint CCArrayForObjectSorting::indexOfSortedObject ( CCSortableObject* pObject ) { KDuint uIdx = 0; if ( pObject ) { // FIXME: need to use binary search to improve performance CCObject* pObj = KD_NULL; KDuint uPrevObjectID = 0; KDuint uOfSortObjectID = pObject->getObjectID ( ); CCARRAY_FOREACH ( this, pObj ) { CCSortableObject* pSortableObj = dynamic_cast<CCSortableObject*> ( pObj ); KDuint uCurObjectID = pSortableObj->getObjectID ( ); if ( ( uOfSortObjectID == uCurObjectID ) || ( uOfSortObjectID >= uPrevObjectID && uOfSortObjectID < uCurObjectID ) ) { break; } uPrevObjectID = uCurObjectID; uIdx++; } } else { uIdx = CC_INVALID_INDEX; } return uIdx; } NS_CC_END
27.415385
128
0.559858
ec222a29a646a72b53ac2d8de9038785177f1c42
14,945
cpp
C++
riptide_teleop/src/ps3_controller.cpp
noahl1/riptide_software
1b380889c063b8866bc356f586752b63b1a429f8
[ "BSD-2-Clause" ]
1
2020-07-17T23:57:58.000Z
2020-07-17T23:57:58.000Z
riptide_teleop/src/ps3_controller.cpp
noahl1/riptide_software
1b380889c063b8866bc356f586752b63b1a429f8
[ "BSD-2-Clause" ]
null
null
null
riptide_teleop/src/ps3_controller.cpp
noahl1/riptide_software
1b380889c063b8866bc356f586752b63b1a429f8
[ "BSD-2-Clause" ]
null
null
null
#include "riptide_teleop/ps3_controller.h" #define GRAVITY 9.81 // [m/s^2] #define WATER_DENSITY 1000 // [kg/m^3] bool IS_ATTITUDE_RESET = false; bool IS_DEPTH_RESET = false; int main(int argc, char **argv) { ros::init(argc, argv, "ps3_controller"); PS3Controller ps3; ps3.Loop(); } PS3Controller::PS3Controller() : nh("ps3_controller") { joy_sub = nh.subscribe<sensor_msgs::Joy>("/joy", 1, &PS3Controller::JoyCB, this); depth_sub = nh.subscribe<riptide_msgs::Depth>("/state/depth", 1, &PS3Controller::DepthCB, this); imu_sub = nh.subscribe<riptide_msgs::Imu>("/state/imu", 1, &PS3Controller::ImuCB, this); roll_pub = nh.advertise<riptide_msgs::AttitudeCommand>("/command/roll", 1); pitch_pub = nh.advertise<riptide_msgs::AttitudeCommand>("/command/pitch", 1); yaw_pub = nh.advertise<riptide_msgs::AttitudeCommand>("/command/yaw", 1); moment_pub = nh.advertise<geometry_msgs::Vector3Stamped>("/command/moment", 1); x_force_pub = nh.advertise<std_msgs::Float64>("/command/force_x", 1); y_force_pub = nh.advertise<std_msgs::Float64>("/command/force_y", 1); z_force_pub = nh.advertise<std_msgs::Float64>("/command/force_z", 1); depth_pub = nh.advertise<riptide_msgs::DepthCommand>("/command/depth", 1); reset_pub = nh.advertise<riptide_msgs::ResetControls>("/controls/reset", 1); plane_pub = nh.advertise<std_msgs::Int8>("/command/ps3_plane", 1); pneumatics_pub = nh.advertise<riptide_msgs::Pneumatics>("/command/pneumatics", 1); PS3Controller::LoadParam<bool>("enable_depth", enableDepth); // Is depth sensor working? PS3Controller::LoadParam<bool>("enable_attitude", enableAttitude); // Is IMU sensor working? PS3Controller::LoadParam<double>("rate", rt); // [Hz] PS3Controller::LoadParam<double>("max_roll_limit", MAX_ROLL); // [m/s^2] PS3Controller::LoadParam<double>("max_pitch_limit", MAX_PITCH); // [m/s^2] PS3Controller::LoadParam<double>("max_x_force", MAX_X_FORCE); // [m/s^2] PS3Controller::LoadParam<double>("max_y_force", MAX_Y_FORCE); // [m/s^2] PS3Controller::LoadParam<double>("max_z_force", MAX_Z_FORCE); // [m/s^2] PS3Controller::LoadParam<double>("max_x_moment", MAX_X_MOMENT); // [rad/s^2] PS3Controller::LoadParam<double>("max_y_moment", MAX_Y_MOMENT); // [rad/s^2] PS3Controller::LoadParam<double>("max_z_moment", MAX_Z_MOMENT); // [rad/s^2] PS3Controller::LoadParam<double>("max_depth", MAX_DEPTH); // [m] PS3Controller::LoadParam<double>("cmd_roll_rate", CMD_ROLL_RATE); // [deg/s] PS3Controller::LoadParam<double>("cmd_pitch_rate", CMD_PITCH_RATE); // [deg/s] PS3Controller::LoadParam<double>("cmd_yaw_rate", CMD_YAW_RATE); // [deg/s] PS3Controller::LoadParam<double>("cmd_depth_rate", CMD_DEPTH_RATE); // [deg/s] PS3Controller::LoadParam<double>("boost", boost); // Factor to multiply pressed button/axis for faster rate // When using the boost factor, you must subtract one from its value for it // to have the desired effect. See below for implementation isReset = true; isStarted = false; isR2Init = false; isL2Init = false; isDepthInit = false; current_depth = 0; euler_rpy.x = 0; euler_rpy.y = 0; euler_rpy.z = 0; alignment_plane = (bool)riptide_msgs::Constants::PLANE_YZ; publish_pneumatics = false; roll_factor = CMD_ROLL_RATE / rt; pitch_factor = CMD_PITCH_RATE / rt; yaw_factor = CMD_YAW_RATE / rt; depth_factor = CMD_DEPTH_RATE / rt; axes_rear_R2 = 0; axes_rear_L2 = 0; publishedIMUDisable = false; PS3Controller::InitMsgs(); ROS_INFO("PS3 Controller Reset. Press Start to begin."); ROS_INFO("PS3: Press Triangle to begin depth command."); } void PS3Controller::InitMsgs() { reset_msg.reset_pwm = true; euler_rpy.x = 0; euler_rpy.y = 0; euler_rpy.z = 0; PS3Controller::DisableControllers(); } // Load parameter from namespace template <typename T> void PS3Controller::LoadParam(string param, T &var) { try { if (!nh.getParam(param, var)) { throw 0; } } catch (int e) { string ns = nh.getNamespace(); ROS_ERROR("PS3 Controller Namespace: %s", ns.c_str()); ROS_ERROR("Critical! Param \"%s/%s\" does not exist or is not accessed correctly. Shutting down.", ns.c_str(), param.c_str()); ros::shutdown(); } } void PS3Controller::DepthCB(const riptide_msgs::Depth::ConstPtr &depth_msg) { current_depth = depth_msg->depth; } // Create rotation matrix from IMU orientation void PS3Controller::ImuCB(const riptide_msgs::Imu::ConstPtr &imu_msg) { euler_rpy = imu_msg->rpy_deg; } void PS3Controller::JoyCB(const sensor_msgs::Joy::ConstPtr &joy) { // Disable/Re-enable Depth Controller and Attitude Controller if (joy->buttons[BUTTON_REAR_L1]) { enableAttitude = !enableAttitude; if (enableAttitude) ROS_INFO("PS3: Re-enabling Attitude Controller"); else ROS_INFO("PS3: Disabling Attitude Controller"); } if (joy->buttons[BUTTON_REAR_R1]) { enableDepth = !enableDepth; if (enableDepth) ROS_INFO("PS3: Re-enabling Depth Controller"); else ROS_INFO("PS3: Disabling Depth Controller"); } // For some reason, R2 and L2 are initialized to 0 if (!isR2Init && (joy->axes[AXES_REAR_R2] != 0)) isR2Init = true; if (!isL2Init && (joy->axes[AXES_REAR_L2] != 0)) isL2Init = true; if (isR2Init) { axes_rear_R2 = 0.5 * (1 - joy->axes[AXES_REAR_R2]); } else { axes_rear_R2 = 0; } if (isL2Init) { axes_rear_L2 = 0.5 * (1 - joy->axes[AXES_REAR_L2]); } else { axes_rear_L2 = 0; } if (!isReset && joy->buttons[BUTTON_SHAPE_X]) { // Reset Vehicle (The "X" button) isReset = true; isStarted = false; isDepthInit = false; PS3Controller::DisableControllers(); ROS_INFO("PS3 Controller Reset. Press Start to begin."); ROS_INFO("PS3: Press Triangle to begin depth command."); } else if (isReset) { // If reset, must wait for Start button to be pressed if (joy->buttons[BUTTON_START]) { isStarted = true; isReset = false; reset_msg.reset_pwm = false; reset_pub.publish(reset_msg); cmd_euler_rpy.z = (int)euler_rpy.z; cmd_depth.depth = current_depth; } } else if (isStarted) { // Update Roll and Pitch if (joy->buttons[BUTTON_SHAPE_CIRCLE]) { // Set both roll and pitch to 0 [deg] cmd_euler_rpy.x = 0; cmd_euler_rpy.y = 0; delta_attitude.x = 0; delta_attitude.y = 0; cmd_moment.vector.x = 0; // For when IMU sin't working, do NOT change roll or pitch cmd_moment.vector.y = 0; // For when IMU sin't working, do NOT change roll or pitch } else { // Update roll/pitch angles with CROSS if (enableAttitude) { // Roll if (joy->buttons[BUTTON_CROSS_RIGHT]) delta_attitude.x = roll_factor * (1 + (boost - 1) * joy->buttons[BUTTON_SHAPE_SQUARE]); // Right -> inc roll else if (joy->buttons[BUTTON_CROSS_LEFT]) delta_attitude.x = -roll_factor * (1 + (boost - 1) * joy->buttons[BUTTON_SHAPE_SQUARE]); // Left -> dec roll else { delta_attitude.x = 0; // ROS_INFO("FALSE FROM ENABLE"); } // Pitch if (joy->buttons[BUTTON_CROSS_UP]) delta_attitude.y = pitch_factor * (1 + (boost - 1) * joy->buttons[BUTTON_SHAPE_SQUARE]); // Up -> inc pitch (Nose points upward) else if (joy->buttons[BUTTON_CROSS_DOWN]) delta_attitude.y = -pitch_factor * (1 + (boost - 1) * joy->buttons[BUTTON_SHAPE_SQUARE]); //Down -> dec pitch (Nose points downward) else delta_attitude.y = 0; // Yaw delta_attitude.z = joy->axes[AXES_STICK_LEFT_LR] * yaw_factor * (1 + (boost - 1) * joy->buttons[BUTTON_SHAPE_SQUARE]); } } if (!enableAttitude) { delta_attitude.x = 0; delta_attitude.y = 0; delta_attitude.z = 0; cmd_euler_rpy.z = (int)euler_rpy.z; // XY Moment if (abs(joy->axes[AXES_STICK_LEFT_UD]) < 0.5) { cmd_moment.vector.x = -joy->axes[AXES_STICK_LEFT_LR] * MAX_X_MOMENT; cmd_moment.vector.y = 0; } else { cmd_moment.vector.y = joy->axes[AXES_STICK_LEFT_UD] * MAX_Y_MOMENT; cmd_moment.vector.x = 0; } // Z Moment - USE CROSS (not the left joystick) //cmd_ang_accel.z = -joy->axes[AXES_STICK_LEFT_LR] * MAX_Z_MOMENT; // CW is positive if (joy->buttons[BUTTON_CROSS_RIGHT]) cmd_moment.vector.z = -0.25 * MAX_Z_MOMENT; // CW is positive else if (joy->buttons[BUTTON_CROSS_LEFT]) cmd_moment.vector.z = 0.25 * MAX_Z_MOMENT; else cmd_moment.vector.z = 0; } // Update Depth/Z-accel if (joy->buttons[BUTTON_SHAPE_TRIANGLE]) { // Enable depth controller isDepthInit = true; //reset_msg.reset_depth = false; cmd_force_z.data = 0; } else if (isDepthInit && enableDepth) { delta_depth = axes_rear_R2 * depth_factor * (1 + (boost - 1) * joy->buttons[BUTTON_SHAPE_SQUARE]); // Up -> dec depth, Down -> inc depth delta_depth -= axes_rear_L2 * depth_factor * (1 + (boost - 1) * joy->buttons[BUTTON_SHAPE_SQUARE]); //cmd_force_z.data = -joy->axes[AXES_STICK_LEFT_UD] * MAX_Z_FORCE; // For when depth sensor isn't working } else if (isDepthInit && !enableDepth) { cmd_force_z.data = axes_rear_R2 * MAX_Z_FORCE; cmd_force_z.data -= axes_rear_L2 * MAX_Z_FORCE; cmd_depth.depth = current_depth; } else { delta_depth = 0; cmd_force_z.data = 0; cmd_depth.depth = current_depth; } /*// Code for using R2 and L2 if (isR2Init && (1 - joy->axes[AXES_REAR_R2] != 0)) // If pressed at all, inc z-accel cmd_force_z.data = 0.5 * (1 - joy->axes[AXES_REAR_R2]) * MAX_Z_FORCE; // Multiplied by 0.5 to scale axes value from 0 to 1 else if (isL2Init && (1 - joy->axes[AXES_REAR_L2] != 0)) // If pressed at all, dec z-accel cmd_force_z.data = 0.5 * (1 - joy->axes[AXES_REAR_L2]) * MAX_Z_FORCE; // Multiplied by 0.5 to scale axes value from 0 to 1*/ } // Update Linear XY Accel cmd_force_x.data = joy->axes[AXES_STICK_RIGHT_UD] * MAX_X_FORCE; // Surge (X) positive forward cmd_force_y.data = -joy->axes[AXES_STICK_RIGHT_LR] * MAX_Y_FORCE; // Sway (Y) positive left if (joy->buttons[BUTTON_SELECT]) alignment_plane = !alignment_plane; /*if (joy->buttons[BUTTON_REAR_L1]) { pneumatics_cmd.torpedo_port = true; publish_pneumatics = true; ROS_INFO("port"); } if (joy->buttons[BUTTON_REAR_R1]) { pneumatics_cmd.torpedo_stbd = true; publish_pneumatics = true; ROS_INFO("stbd"); } if (joy->buttons[BUTTON_PAIRING]) { pneumatics_cmd.markerdropper = true; publish_pneumatics = true; ROS_INFO("marker"); }*/ } // Run when Reset button is pressed void PS3Controller::DisableControllers() { reset_msg.reset_pwm = true; PS3Controller::DisableAttitude(); delta_attitude.x = 0; delta_attitude.y = 0; delta_attitude.z = 0; cmd_moment.vector.x = 0; cmd_moment.vector.y = 0; cmd_moment.vector.z = 0; PS3Controller::DisableDepth(); delta_depth = 0; cmd_force_x.data = 0; cmd_force_y.data = 0; cmd_force_z.data = 0; reset_pub.publish(reset_msg); pneumatics_cmd.torpedo_port = false; pneumatics_cmd.torpedo_stbd = false; pneumatics_cmd.manipulator = false; pneumatics_cmd.markerdropper = false; pneumatics_cmd.duration = 250; PS3Controller::PublishCommands(); } void PS3Controller::DisableAttitude() { if (!IS_ATTITUDE_RESET) { riptide_msgs::AttitudeCommand roll_cmd; riptide_msgs::AttitudeCommand pitch_cmd; riptide_msgs::AttitudeCommand yaw_cmd; roll_cmd.value = 0; pitch_cmd.value = 0; yaw_cmd.value = 0; roll_cmd.mode = roll_cmd.MOMENT; pitch_cmd.mode = pitch_cmd.MOMENT; yaw_cmd.mode = yaw_cmd.MOMENT; IS_ATTITUDE_RESET = true; roll_pub.publish(roll_cmd); pitch_pub.publish(pitch_cmd); yaw_pub.publish(yaw_cmd); } } void PS3Controller::DisableDepth() { if (!IS_DEPTH_RESET) { cmd_depth.active = false; cmd_depth.depth = 0; IS_DEPTH_RESET = true; depth_pub.publish(cmd_depth); } } double PS3Controller::Constrain(double current, double max) { if (current > max) return max; else if (current < -1 * max) return -1 * max; return current; } void PS3Controller::UpdateCommands() { if (enableAttitude) { IS_ATTITUDE_RESET = false; cmd_euler_rpy.x += delta_attitude.x; cmd_euler_rpy.y += delta_attitude.y; cmd_euler_rpy.z += delta_attitude.z; cmd_euler_rpy.x = PS3Controller::Constrain(cmd_euler_rpy.x, MAX_ROLL); cmd_euler_rpy.y = PS3Controller::Constrain(cmd_euler_rpy.y, MAX_PITCH); if (cmd_euler_rpy.z > 180) cmd_euler_rpy.z -= 360; if (cmd_euler_rpy.z < -180) cmd_euler_rpy.z += 360; } else { PS3Controller::DisableAttitude(); } if (enableDepth) { IS_DEPTH_RESET = false; cmd_depth.active = true; cmd_depth.depth += delta_depth; cmd_depth.depth = PS3Controller::Constrain(cmd_depth.depth, MAX_DEPTH); if (cmd_depth.depth < 0) cmd_depth.depth = 0; } else { PS3Controller::DisableDepth(); } plane_msg.data = (int)alignment_plane; } void PS3Controller::PublishCommands() { if (enableAttitude && !IS_ATTITUDE_RESET) { riptide_msgs::AttitudeCommand roll_cmd; riptide_msgs::AttitudeCommand pitch_cmd; riptide_msgs::AttitudeCommand yaw_cmd; roll_cmd.value = cmd_euler_rpy.x; pitch_cmd.value = cmd_euler_rpy.y; yaw_cmd.value = cmd_euler_rpy.z; roll_cmd.mode = roll_cmd.POSITION; pitch_cmd.mode = pitch_cmd.POSITION; yaw_cmd.mode = yaw_cmd.POSITION; roll_pub.publish(roll_cmd); pitch_pub.publish(pitch_cmd); yaw_pub.publish(yaw_cmd); } else { cmd_moment.header.stamp = ros::Time::now(); moment_pub.publish(cmd_moment); } x_force_pub.publish(cmd_force_x); y_force_pub.publish(cmd_force_y); if (enableDepth && !IS_DEPTH_RESET) depth_pub.publish(cmd_depth); else z_force_pub.publish(cmd_force_z); plane_pub.publish(plane_msg); /*if (publish_pneumatics) pneumatics_pub.publish(pneumatics_cmd); pneumatics_cmd.torpedo_port = false; pneumatics_cmd.torpedo_stbd = false; pneumatics_cmd.manipulator = false; pneumatics_cmd.markerdropper = false; publish_pneumatics = false;*/ } // This loop function is critical because it allows for different command rates void PS3Controller::Loop() { ros::Rate rate(rt); // MUST have this rate in here, since all factors are based on it while (ros::ok()) { if (isStarted) { PS3Controller::UpdateCommands(); PS3Controller::PublishCommands(); } ros::spinOnce(); rate.sleep(); } }
30.131048
142
0.661559
ec29a544d9100b3387e11d9bc03102fb43674314
329
hh
C++
src/UsageEnvironment/include/UsageEnvironment_version.hh
RayanWang/Live555
3a8b2998e5872326e4edb96e6e7dc46dc1d16af4
[ "MIT" ]
5
2018-04-09T02:03:33.000Z
2022-03-26T16:17:52.000Z
src/UsageEnvironment/include/UsageEnvironment_version.hh
RayanWang/Live555
3a8b2998e5872326e4edb96e6e7dc46dc1d16af4
[ "MIT" ]
null
null
null
src/UsageEnvironment/include/UsageEnvironment_version.hh
RayanWang/Live555
3a8b2998e5872326e4edb96e6e7dc46dc1d16af4
[ "MIT" ]
null
null
null
// Version information for the "UsageEnvironment" library // Copyright (c) 1996-2014 Live Networks, Inc. All rights reserved. #ifndef _USAGEENVIRONMENT_VERSION_HH #define _USAGEENVIRONMENT_VERSION_HH #define USAGEENVIRONMENT_LIBRARY_VERSION_STRING "2014.12.17" #define USAGEENVIRONMENT_LIBRARY_VERSION_INT 1418774400 #endif
29.909091
68
0.835866
ec2bc096ac8d02bf32f1e3d46ed2a7005d6d0383
3,663
cpp
C++
Builds/vs2013/Task2/unittest1.cpp
AJ-Moore/AIStates
b2bc31d7d3cbec25b4efacbe9ae6c9940e8e68e4
[ "MIT" ]
null
null
null
Builds/vs2013/Task2/unittest1.cpp
AJ-Moore/AIStates
b2bc31d7d3cbec25b4efacbe9ae6c9940e8e68e4
[ "MIT" ]
null
null
null
Builds/vs2013/Task2/unittest1.cpp
AJ-Moore/AIStates
b2bc31d7d3cbec25b4efacbe9ae6c9940e8e68e4
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include <AI.h> #include <FSM.h> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace Task2 { TEST_CLASS(UnitTest1) { public: //Test that the AI Starting State is Idle TEST_METHOD(StartState) { AI ai(false, 0, 0); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle); } //Check Idle to Observe Transition. TEST_METHOD(IdleToObserve) { //create the AI -> Sets Can See Player to true AI ai(true, 0, 0); //check that the current state is in idle Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle); //check after the update that the state has changed to Observe ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe); } //Checks the transition between the Observe and Idle states. TEST_METHOD(ObserveToIdle) { AI ai(true, 0, 0); ai.update(); ai.canSeePlayer = false; ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle); } //Observe to Combat Test TEST_METHOD(ObserveToCombat){ AI ai(true, 70, 0); ai.update();//state should now be observe. ai.update();//state should still be observe. Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe); //change health to 71 and ammo to 1 ai.health = 71; ai.ammunition = 1; ai.update();//state should now be combat Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat); } //Combat to Retreat Test. TEST_METHOD(CombatToRetreat){ AI ai(true, 71, 1); ai.update();//state should now be observe. Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe); ai.update();//state should now be combat Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat); ai.ammunition = 0; ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Retreat); } //Combat to Retreat Test. TEST_METHOD(CombatToDead){ AI ai(true, 71, 1); ai.update();//state should now be observe. Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe); ai.update();//state should now be combat Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat); ai.health = 0; ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Dead); } //Combat to Retreat Test. TEST_METHOD(RetreatToDead){ AI ai(true, 71, 1); ai.update();//state should now be observe. Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe); ai.update();//state should now be combat Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat); ai.ammunition = 0; ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Retreat); ai.health = 0; ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Dead); } TEST_METHOD(RetreatToIdle){ AI ai(true, 71, 1); ai.update();//state should now be observe. Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Observe); ai.update();//state should now be combat Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Combat); ai.ammunition = 0; ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Retreat); ai.canSeePlayer = false; ai.update(); Assert::AreEqual((int)ai.fsm->getCurrentState()->state, (int)AIStates::Idle); } }; }
31.577586
83
0.670762
ec2c9e529ef42d3a903fcae5273beb2dec55545d
276
cpp
C++
Char.cpp
RafelNunes/ifsc-programacao
40622fb1a5496e09f4800220e293385468fef323
[ "MIT" ]
null
null
null
Char.cpp
RafelNunes/ifsc-programacao
40622fb1a5496e09f4800220e293385468fef323
[ "MIT" ]
null
null
null
Char.cpp
RafelNunes/ifsc-programacao
40622fb1a5496e09f4800220e293385468fef323
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> int main(void){ char letra1, letra2; printf("Digite um caracter: "); scanf("%c", &letra1); while(letra1 != 'X') {printf("Digite um caracter: "); scanf(" %c", &letra1); } printf("Letra1: %c Letra2: %c\n", letra1, letra2); }
16.235294
51
0.605072
ec2cac1e7551ff2e16b4369eae9e355be031b373
3,361
cpp
C++
tests/isqrt_test.cpp
aladur/primes
1db3050af466da367daeac4f98fc3b05153385ac
[ "BSD-3-Clause" ]
null
null
null
tests/isqrt_test.cpp
aladur/primes
1db3050af466da367daeac4f98fc3b05153385ac
[ "BSD-3-Clause" ]
null
null
null
tests/isqrt_test.cpp
aladur/primes
1db3050af466da367daeac4f98fc3b05153385ac
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2021 Wolfgang Schwotzer Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <gtest/gtest.h> #include <primes.h> class primes_wrapper : public primes { public: primes_wrapper(uint64_t number = 0U) : primes(number) { } uint64_t get_isqrt(uint64_t number) { return isqrt(number); } }; TEST(isqrt_test, isqrt) { auto pw = primes_wrapper(); EXPECT_EQ(1, pw.get_isqrt(3)); EXPECT_EQ(2, pw.get_isqrt(4)); EXPECT_EQ(2, pw.get_isqrt(5)); EXPECT_EQ(2, pw.get_isqrt(6)); EXPECT_EQ(2, pw.get_isqrt(7)); EXPECT_EQ(2, pw.get_isqrt(8)); EXPECT_EQ(3, pw.get_isqrt(9)); EXPECT_EQ(3, pw.get_isqrt(10)); EXPECT_EQ(3, pw.get_isqrt(11)); EXPECT_EQ(3, pw.get_isqrt(12)); EXPECT_EQ(3, pw.get_isqrt(13)); EXPECT_EQ(3, pw.get_isqrt(14)); EXPECT_EQ(3, pw.get_isqrt(15)); EXPECT_EQ(4, pw.get_isqrt(16)); EXPECT_EQ(4, pw.get_isqrt(24)); EXPECT_EQ(5, pw.get_isqrt(25)); EXPECT_EQ(5, pw.get_isqrt(35)); EXPECT_EQ(6, pw.get_isqrt(36)); EXPECT_EQ(6, pw.get_isqrt(48)); EXPECT_EQ(7, pw.get_isqrt(49)); EXPECT_EQ(7, pw.get_isqrt(63)); EXPECT_EQ(8, pw.get_isqrt(64)); EXPECT_EQ(8, pw.get_isqrt(80)); EXPECT_EQ(9, pw.get_isqrt(81)); EXPECT_EQ(9, pw.get_isqrt(99)); EXPECT_EQ(10, pw.get_isqrt(100)); EXPECT_EQ(10, pw.get_isqrt(120)); EXPECT_EQ(126, pw.get_isqrt(16127)); EXPECT_EQ(1022, pw.get_isqrt(1046527)); EXPECT_EQ(4094, pw.get_isqrt(16769023)); EXPECT_EQ(32766, pw.get_isqrt(1073676287)); EXPECT_EQ(262142, pw.get_isqrt(68718952447)); EXPECT_EQ(524286, pw.get_isqrt(274876858367)); EXPECT_EQ(2097150, pw.get_isqrt(4398042316799)); EXPECT_EQ(33554430, pw.get_isqrt(1125899839733759)); EXPECT_EQ(134217726, pw.get_isqrt(18014398241046527)); EXPECT_EQ(1054092553, pw.get_isqrt(1111111111111111111)); }
33.949495
141
0.712883
ec2ec73f474fa18945883ea8e2f68b90c16505c2
1,645
hpp
C++
libcaf_net/caf/net/http/v1.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_net/caf/net/http/v1.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_net/caf/net/http/v1.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/byte_span.hpp" #include "caf/detail/net_export.hpp" #include "caf/net/http/header_fields_map.hpp" #include "caf/net/http/status.hpp" #include <string_view> #include <utility> namespace caf::net::http::v1 { /// Tries splitting the given byte span into an HTTP header (`first`) and a /// remainder (`second`). Returns an empty `string_view` as `first` for /// incomplete HTTP headers. CAF_NET_EXPORT std::pair<std::string_view, byte_span> split_header(byte_span bytes); /// Writes an HTTP header to the buffer. CAF_NET_EXPORT void write_header(status code, const header_fields_map& fields, byte_buffer& buf); /// Writes a complete HTTP response to the buffer. Automatically sets /// Content-Type and Content-Length header fields. CAF_NET_EXPORT void write_response(status code, std::string_view content_type, std::string_view content, byte_buffer& buf); /// Writes a complete HTTP response to the buffer. Automatically sets /// Content-Type and Content-Length header fields followed by the user-defined /// @p fields. CAF_NET_EXPORT void write_response(status code, std::string_view content_type, std::string_view content, const header_fields_map& fields, byte_buffer& buf); } // namespace caf::net::http::v1
40.121951
79
0.68997
ec30e5ce0bcc57fc07b313ca33ef1b05123d8737
2,089
cpp
C++
lib-dmxserial/src/serial/serialspi.cpp
vanvught/rpidmx512
b56bb2db406247b4fd4c56aa372952939f4a3290
[ "MIT" ]
328
2015-02-26T09:54:16.000Z
2022-03-31T11:04:00.000Z
lib-dmxserial/src/serial/serialspi.cpp
vanvught/rpidmx512
b56bb2db406247b4fd4c56aa372952939f4a3290
[ "MIT" ]
195
2016-07-13T10:43:37.000Z
2022-03-20T19:14:55.000Z
lib-dmxserial/src/serial/serialspi.cpp
vanvught/rpidmx512
b56bb2db406247b4fd4c56aa372952939f4a3290
[ "MIT" ]
113
2015-06-08T04:54:23.000Z
2022-02-15T09:06:10.000Z
/** * @file serialspi.cpp * */ /* Copyright (C) 2020-2021 by Arjan van Vught mailto:info@orangepi-dmx.nl * * 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 <cstdint> #include <cstdio> #include <cassert> #include "serial.h" #include "hal_spi.h" #include "debug.h" using namespace serial; void Serial::SetSpiSpeedHz(uint32_t nSpeedHz) { DEBUG_PRINTF("nSpeedHz=%d", nSpeedHz); if (nSpeedHz == 0) { return; } m_SpiConfiguration.nSpeed = nSpeedHz; } void Serial::SetSpiMode(uint32_t nMode) { DEBUG_PRINTF("tMode=%d", nMode); if (nMode > 3) { return; } m_SpiConfiguration.nMode = static_cast<uint8_t>(nMode); } bool Serial::InitSpi() { DEBUG_ENTRY FUNC_PREFIX (spi_begin()); FUNC_PREFIX (spi_set_speed_hz(m_SpiConfiguration.nSpeed)); FUNC_PREFIX (spi_chipSelect(SPI_CS0)); FUNC_PREFIX (spi_setDataMode(m_SpiConfiguration.nMode)); DEBUG_EXIT return true; } void Serial::SendSpi(const uint8_t *pData, uint32_t nLength) { DEBUG_ENTRY FUNC_PREFIX (spi_writenb(reinterpret_cast<const char *>(pData), nLength)); DEBUG_EXIT }
26.782051
80
0.748205
ec33e1506d3394794f2a6196eef9fa94d4dc6e6e
32,278
cpp
C++
Engine/Source/Runtime/Core/Private/Linux/LinuxPlatformProcess.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Core/Private/Linux/LinuxPlatformProcess.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Core/Private/Linux/LinuxPlatformProcess.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "CorePrivatePCH.h" #include "LinuxPlatformRunnableThread.h" #include "EngineVersion.h" #include <spawn.h> #include <sys/wait.h> #include <sys/resource.h> #include <sys/ioctl.h> // ioctl #include <asm/ioctls.h> // FIONREAD #include "LinuxApplication.h" // FLinuxApplication::IsForeground() void* FLinuxPlatformProcess::GetDllHandle( const TCHAR* Filename ) { check( Filename ); FString AbsolutePath = FPaths::ConvertRelativePathToFull(Filename); int DlOpenMode = RTLD_LAZY; if (AbsolutePath.EndsWith(TEXT("libsteam_api.so"))) { DlOpenMode |= RTLD_GLOBAL; //Global symbol resolution when loading shared objects - Needed for Steam to work when its library is loaded by a plugin } else { DlOpenMode |= RTLD_LOCAL; //Local symbol resolution when loading shared objects - Needed for Hot-Reload } void *Handle = dlopen( TCHAR_TO_UTF8(*AbsolutePath), DlOpenMode ); if (!Handle) { UE_LOG(LogLinux, Warning, TEXT("dlopen failed: %s"), ANSI_TO_TCHAR(dlerror()) ); } return Handle; } void FLinuxPlatformProcess::FreeDllHandle( void* DllHandle ) { check( DllHandle ); dlclose( DllHandle ); } void* FLinuxPlatformProcess::GetDllExport( void* DllHandle, const TCHAR* ProcName ) { check(DllHandle); check(ProcName); return dlsym( DllHandle, TCHAR_TO_ANSI(ProcName) ); } int32 FLinuxPlatformProcess::GetDllApiVersion( const TCHAR* Filename ) { check(Filename); return GCompatibleWithEngineVersion.GetChangelist(); } const TCHAR* FLinuxPlatformProcess::GetModulePrefix() { return TEXT("lib"); } const TCHAR* FLinuxPlatformProcess::GetModuleExtension() { return TEXT("so"); } const TCHAR* FLinuxPlatformProcess::GetBinariesSubdirectory() { return TEXT("Linux"); } namespace PlatformProcessLimits { enum { MaxComputerName = 128, MaxBaseDirLength= MAX_PATH + 1, MaxArgvParameters = 256 }; }; const TCHAR* FLinuxPlatformProcess::ComputerName() { static bool bHaveResult = false; static TCHAR CachedResult[ PlatformProcessLimits::MaxComputerName ]; if (!bHaveResult) { struct utsname name; const char * SysName = name.nodename; if(uname(&name)) { SysName = "Linux Computer"; } FCString::Strcpy(CachedResult, ARRAY_COUNT(CachedResult) - 1, ANSI_TO_TCHAR(SysName)); CachedResult[ARRAY_COUNT(CachedResult) - 1] = 0; bHaveResult = true; } return CachedResult; } void FLinuxPlatformProcess::CleanFileCache() { bool bShouldCleanShaderWorkingDirectory = true; #if !(UE_BUILD_SHIPPING && WITH_EDITOR) // Only clean the shader working directory if we are the first instance, to avoid deleting files in use by other instances // @todo - check if any other instances are running right now bShouldCleanShaderWorkingDirectory = GIsFirstInstance; #endif if (bShouldCleanShaderWorkingDirectory && !FParse::Param( FCommandLine::Get(), TEXT("Multiprocess"))) { // get shader path, and convert it to the userdirectory FString ShaderDir = FString(FPlatformProcess::BaseDir()) / FPlatformProcess::ShaderDir(); FString UserShaderDir = IFileManager::Get().ConvertToAbsolutePathForExternalAppForWrite(*ShaderDir); FPaths::CollapseRelativeDirectories(ShaderDir); // make sure we don't delete from the source directory if (ShaderDir != UserShaderDir) { IFileManager::Get().DeleteDirectory(*UserShaderDir, false, true); } FPlatformProcess::CleanShaderWorkingDir(); } } const TCHAR* FLinuxPlatformProcess::BaseDir() { static bool bHaveResult = false; static TCHAR CachedResult[ PlatformProcessLimits::MaxBaseDirLength ]; if (!bHaveResult) { char SelfPath[ PlatformProcessLimits::MaxBaseDirLength ] = {0}; if (readlink( "/proc/self/exe", SelfPath, ARRAY_COUNT(SelfPath) - 1) == -1) { int ErrNo = errno; UE_LOG(LogHAL, Fatal, TEXT("readlink() failed with errno = %d (%s)"), ErrNo, StringCast< TCHAR >(strerror(ErrNo)).Get()); // unreachable return CachedResult; } SelfPath[ARRAY_COUNT(SelfPath) - 1] = 0; FCString::Strcpy(CachedResult, ARRAY_COUNT(CachedResult) - 1, ANSI_TO_TCHAR(dirname(SelfPath))); CachedResult[ARRAY_COUNT(CachedResult) - 1] = 0; FCString::Strcat(CachedResult, ARRAY_COUNT(CachedResult) - 1, TEXT("/")); bHaveResult = true; } return CachedResult; } const TCHAR* FLinuxPlatformProcess::UserDir() { // The UserDir is where user visible files (such as game projects) live. // On Linux (just like on Mac) this corresponds to $HOME/Documents. // To accomodate localization requirement we use xdg-user-dir command, // and fall back to $HOME/Documents if setting not found. static TCHAR Result[MAX_PATH] = TEXT(""); if (!Result[0]) { char DocPath[MAX_PATH]; FILE* FilePtr = popen("xdg-user-dir DOCUMENTS", "r"); if(fgets(DocPath, MAX_PATH, FilePtr) == NULL) { char* Home = secure_getenv("HOME"); if (!Home) { UE_LOG(LogHAL, Warning, TEXT("Unable to read the $HOME environment variable")); } else { FCString::Strcpy(Result, ANSI_TO_TCHAR(Home)); FCString::Strcat(Result, TEXT("/Documents/")); } } else { size_t DocLen = strlen(DocPath) - 1; DocPath[DocLen] = '\0'; FCString::Strcpy(Result, ANSI_TO_TCHAR(DocPath)); FCString::Strcat(Result, TEXT("/")); } pclose(FilePtr); } return Result; } const TCHAR* FLinuxPlatformProcess::UserSettingsDir() { // Like on Mac we use the same folder for UserSettingsDir and ApplicationSettingsDir // $HOME/.config/Epic/ return ApplicationSettingsDir(); } const TCHAR* FLinuxPlatformProcess::ApplicationSettingsDir() { // The ApplicationSettingsDir is where the engine stores settings and configuration // data. On linux this corresponds to $HOME/.config/Epic static TCHAR Result[MAX_PATH] = TEXT(""); if (!Result[0]) { char* Home = secure_getenv("HOME"); if (!Home) { UE_LOG(LogHAL, Warning, TEXT("Unable to read the $HOME environment variable")); } else { FCString::Strcpy(Result, ANSI_TO_TCHAR(Home)); FCString::Strcat(Result, TEXT("/.config/Epic/")); } } return Result; } bool FLinuxPlatformProcess::SetProcessLimits(EProcessResource::Type Resource, uint64 Limit) { rlimit NativeLimit; NativeLimit.rlim_cur = Limit; NativeLimit.rlim_max = Limit; int NativeResource = RLIMIT_AS; switch(Resource) { case EProcessResource::VirtualMemory: NativeResource = RLIMIT_AS; break; default: UE_LOG(LogHAL, Warning, TEXT("Unknown resource type %d"), Resource); return false; } if (setrlimit(NativeResource, &NativeLimit) != 0) { UE_LOG(LogHAL, Warning, TEXT("setrlimit() failed with error %d (%s)\n"), errno, ANSI_TO_TCHAR(strerror(errno))); return false; } return true; } const TCHAR* FLinuxPlatformProcess::ExecutableName(bool bRemoveExtension) { static bool bHaveResult = false; static TCHAR CachedResult[ PlatformProcessLimits::MaxBaseDirLength ]; if (!bHaveResult) { char SelfPath[ PlatformProcessLimits::MaxBaseDirLength ] = {0}; if (readlink( "/proc/self/exe", SelfPath, ARRAY_COUNT(SelfPath) - 1) == -1) { int ErrNo = errno; UE_LOG(LogHAL, Fatal, TEXT("readlink() failed with errno = %d (%s)"), ErrNo, StringCast< TCHAR >(strerror(ErrNo)).Get()); return CachedResult; } SelfPath[ARRAY_COUNT(SelfPath) - 1] = 0; FCString::Strcpy(CachedResult, ARRAY_COUNT(CachedResult) - 1, ANSI_TO_TCHAR(basename(SelfPath))); CachedResult[ARRAY_COUNT(CachedResult) - 1] = 0; bHaveResult = true; } return CachedResult; } FString FLinuxPlatformProcess::GenerateApplicationPath( const FString& AppName, EBuildConfigurations::Type BuildConfiguration) { FString PlatformName = GetBinariesSubdirectory(); FString ExecutablePath = FString::Printf(TEXT("../%s/%s"), *PlatformName, *AppName); if (BuildConfiguration != EBuildConfigurations::Development && BuildConfiguration != EBuildConfigurations::DebugGame) { ExecutablePath += FString::Printf(TEXT("-%s-%s"), *PlatformName, EBuildConfigurations::ToString(BuildConfiguration)); } return ExecutablePath; } FString FLinuxPlatformProcess::GetApplicationName( uint32 ProcessId ) { FString Output = TEXT(""); const int32 ReadLinkSize = 1024; char ReadLinkCmd[ReadLinkSize] = {0}; FCStringAnsi::Sprintf(ReadLinkCmd, "/proc/%d/exe", ProcessId); char ProcessPath[ PlatformProcessLimits::MaxBaseDirLength ] = {0}; int32 Ret = readlink(ReadLinkCmd, ProcessPath, ARRAY_COUNT(ProcessPath) - 1); if (Ret != -1) { Output = ANSI_TO_TCHAR(ProcessPath); } return Output; } FPipeHandle::~FPipeHandle() { close(PipeDesc); } FString FPipeHandle::Read() { const int kBufferSize = 4096; ANSICHAR Buffer[kBufferSize]; FString Output; int BytesAvailable = 0; if (ioctl(PipeDesc, FIONREAD, &BytesAvailable) == 0) { if (BytesAvailable > 0) { int BytesRead = read(PipeDesc, Buffer, kBufferSize - 1); if (BytesRead > 0) { Buffer[BytesRead] = 0; Output += StringCast< TCHAR >(Buffer).Get(); } } } else { UE_LOG(LogHAL, Fatal, TEXT("ioctl(..., FIONREAD, ...) failed with errno=%d (%s)"), errno, StringCast< TCHAR >(strerror(errno)).Get()); } return Output; } bool FPipeHandle::ReadToArray(TArray<uint8> & Output) { int BytesAvailable = 0; if (ioctl(PipeDesc, FIONREAD, &BytesAvailable) == 0) { if (BytesAvailable > 0) { Output.SetNumUninitialized(BytesAvailable); int BytesRead = read(PipeDesc, Output.GetData(), BytesAvailable); if (BytesRead > 0) { if (BytesRead < BytesAvailable) { Output.SetNum(BytesRead); } return true; } else { Output.Empty(); } } } return false; } void FLinuxPlatformProcess::ClosePipe( void* ReadPipe, void* WritePipe ) { if (ReadPipe) { FPipeHandle * PipeHandle = reinterpret_cast< FPipeHandle* >(ReadPipe); delete PipeHandle; } if (WritePipe) { FPipeHandle * PipeHandle = reinterpret_cast< FPipeHandle* >(WritePipe); delete PipeHandle; } } bool FLinuxPlatformProcess::CreatePipe( void*& ReadPipe, void*& WritePipe ) { int PipeFd[2]; if (-1 == pipe(PipeFd)) { int ErrNo = errno; UE_LOG(LogHAL, Warning, TEXT("pipe() failed with errno = %d (%s)"), ErrNo, StringCast< TCHAR >(strerror(ErrNo)).Get()); return false; } ReadPipe = new FPipeHandle(PipeFd[ 0 ]); WritePipe = new FPipeHandle(PipeFd[ 1 ]); return true; } FString FLinuxPlatformProcess::ReadPipe( void* ReadPipe ) { if (ReadPipe) { FPipeHandle * PipeHandle = reinterpret_cast< FPipeHandle* >(ReadPipe); return PipeHandle->Read(); } return FString(); } bool FLinuxPlatformProcess::ReadPipeToArray(void* ReadPipe, TArray<uint8> & Output) { if (ReadPipe) { FPipeHandle * PipeHandle = reinterpret_cast<FPipeHandle*>(ReadPipe); return PipeHandle->ReadToArray(Output); } return false; } bool FLinuxPlatformProcess::WritePipe(void* WritePipe, const FString& Message, FString* OutWritten) { // if there is not a message or WritePipe is null if ((Message.Len() == 0) || (WritePipe == nullptr)) { return false; } // convert input to UTF8CHAR uint32 BytesAvailable = Message.Len(); UTF8CHAR* Buffer = new UTF8CHAR[BytesAvailable + 1]; if (!FString::ToBlob(Message, Buffer, BytesAvailable)) { return false; } // write to pipe uint32 BytesWritten = write(*(int*)WritePipe, Buffer, BytesAvailable); if (OutWritten != nullptr) { OutWritten->FromBlob(Buffer, BytesWritten); } return (BytesWritten == BytesAvailable); } FRunnableThread* FLinuxPlatformProcess::CreateRunnableThread() { return new FRunnableThreadLinux(); } void FLinuxPlatformProcess::LaunchURL(const TCHAR* URL, const TCHAR* Parms, FString* Error) { // @todo This ignores params and error; mostly a stub pid_t pid = fork(); UE_LOG(LogHAL, Verbose, TEXT("FLinuxPlatformProcess::LaunchURL: '%s'"), URL); if (pid == 0) { exit(execl("/usr/bin/xdg-open", "xdg-open", TCHAR_TO_UTF8(URL), (char *)0)); } } /** * This class exists as an imperfect workaround to allow both "fire and forget" children and children about whose return code we actually care. * (maybe we could fork and daemonize ourselves for the first case instead?) */ struct FChildWaiterThread : public FRunnable { /** Global table of all waiter threads */ static TArray<FChildWaiterThread *> ChildWaiterThreadsArray; /** Lock guarding the acess to child waiter threads */ static FCriticalSection ChildWaiterThreadsArrayGuard; /** Pid of child to wait for */ int ChildPid; FChildWaiterThread(pid_t InChildPid) : ChildPid(InChildPid) { // add ourselves to thread array ChildWaiterThreadsArrayGuard.Lock(); ChildWaiterThreadsArray.Add(this); ChildWaiterThreadsArrayGuard.Unlock(); } virtual ~FChildWaiterThread() { // remove ChildWaiterThreadsArrayGuard.Lock(); ChildWaiterThreadsArray.RemoveSingle(this); ChildWaiterThreadsArrayGuard.Unlock(); } virtual uint32 Run() { for(;;) // infinite loop in case we get EINTR and have to repeat { siginfo_t SignalInfo; if (waitid(P_PID, ChildPid, &SignalInfo, WEXITED)) { if (errno != EINTR) { int ErrNo = errno; UE_LOG(LogHAL, Fatal, TEXT("FChildWaiterThread::Run(): waitid for pid %d failed (errno=%d, %s)"), static_cast< int32 >(ChildPid), ErrNo, ANSI_TO_TCHAR(strerror(ErrNo))); break; // exit the loop if for some reason Fatal log (above) returns } } else { check(SignalInfo.si_pid == ChildPid); break; } } return 0; } virtual void Exit() { // unregister from the array delete this; } }; /** See FChildWaiterThread */ TArray<FChildWaiterThread *> FChildWaiterThread::ChildWaiterThreadsArray; /** See FChildWaiterThread */ FCriticalSection FChildWaiterThread::ChildWaiterThreadsArrayGuard; FProcHandle FLinuxPlatformProcess::CreateProc(const TCHAR* URL, const TCHAR* Parms, bool bLaunchDetached, bool bLaunchHidden, bool bLaunchReallyHidden, uint32* OutProcessID, int32 PriorityModifier, const TCHAR* OptionalWorkingDirectory, void* PipeWrite) { // @TODO bLaunchHidden bLaunchReallyHidden are not handled // We need an absolute path to executable FString ProcessPath = URL; if (*URL != TEXT('/')) { ProcessPath = FPaths::ConvertRelativePathToFull(ProcessPath); } if (!FPaths::FileExists(ProcessPath)) { return FProcHandle(); } FString Commandline = ProcessPath; Commandline += TEXT(" "); Commandline += Parms; UE_LOG(LogHAL, Log, TEXT("FLinuxPlatformProcess::CreateProc: '%s'"), *Commandline); TArray<FString> ArgvArray; int Argc = Commandline.ParseIntoArray(ArgvArray, TEXT(" "), true); char* Argv[PlatformProcessLimits::MaxArgvParameters + 1] = { NULL }; // last argument is NULL, hence +1 struct CleanupArgvOnExit { int Argc; char** Argv; // relying on it being long enough to hold Argc elements CleanupArgvOnExit( int InArgc, char *InArgv[] ) : Argc(InArgc) , Argv(InArgv) {} ~CleanupArgvOnExit() { for (int Idx = 0; Idx < Argc; ++Idx) { FMemory::Free(Argv[Idx]); } } } CleanupGuard(Argc, Argv); // make sure we do not lose arguments with spaces in them due to Commandline.ParseIntoArray breaking them apart above // @todo this code might need to be optimized somehow and integrated with main argument parser below it TArray<FString> NewArgvArray; if (Argc > 0) { if (Argc > PlatformProcessLimits::MaxArgvParameters) { UE_LOG(LogHAL, Warning, TEXT("FLinuxPlatformProcess::CreateProc: too many (%d) commandline arguments passed, will only pass %d"), Argc, PlatformProcessLimits::MaxArgvParameters); Argc = PlatformProcessLimits::MaxArgvParameters; } FString MultiPartArg; for (int32 Index = 0; Index < Argc; Index++) { if (MultiPartArg.IsEmpty()) { if ((ArgvArray[Index].StartsWith(TEXT("\"")) && !ArgvArray[Index].EndsWith(TEXT("\""))) // check for a starting quote but no ending quote, excludes quoted single arguments || (ArgvArray[Index].Contains(TEXT("=\"")) && !ArgvArray[Index].EndsWith(TEXT("\""))) // check for quote after =, but no ending quote, this gets arguments of the type -blah="string string string" || ArgvArray[Index].EndsWith(TEXT("=\""))) // check for ending quote after =, this gets arguments of the type -blah=" string string string " { MultiPartArg = ArgvArray[Index]; } else { if (ArgvArray[Index].Contains(TEXT("=\""))) { FString SingleArg = ArgvArray[Index]; SingleArg = SingleArg.Replace(TEXT("=\""), TEXT("=")); NewArgvArray.Add(SingleArg.TrimQuotes(NULL)); } else { NewArgvArray.Add(ArgvArray[Index].TrimQuotes(NULL)); } } } else { MultiPartArg += TEXT(" "); MultiPartArg += ArgvArray[Index]; if (ArgvArray[Index].EndsWith(TEXT("\""))) { if (MultiPartArg.StartsWith(TEXT("\""))) { NewArgvArray.Add(MultiPartArg.TrimQuotes(NULL)); } else { NewArgvArray.Add(MultiPartArg); } MultiPartArg.Empty(); } } } } // update Argc with the new argument count Argc = NewArgvArray.Num(); if (Argc > 0) // almost always, unless there's no program name { if (Argc > PlatformProcessLimits::MaxArgvParameters) { UE_LOG(LogHAL, Warning, TEXT("FLinuxPlatformProcess::CreateProc: too many (%d) commandline arguments passed, will only pass %d"), Argc, PlatformProcessLimits::MaxArgvParameters); Argc = PlatformProcessLimits::MaxArgvParameters; } for (int Idx = 0; Idx < Argc; ++Idx) { FTCHARToUTF8 AnsiBuffer(*NewArgvArray[Idx]); const char* Ansi = AnsiBuffer.Get(); size_t AnsiSize = FCStringAnsi::Strlen(Ansi) + 1; // will work correctly with UTF-8 check(AnsiSize); Argv[Idx] = reinterpret_cast< char* >( FMemory::Malloc(AnsiSize) ); check(Argv[Idx]); FCStringAnsi::Strncpy(Argv[Idx], Ansi, AnsiSize); // will work correctly with UTF-8 } // last Argv should be NULL check(Argc <= PlatformProcessLimits::MaxArgvParameters + 1); Argv[Argc] = NULL; } extern char ** environ; // provided by libc pid_t ChildPid = -1; posix_spawn_file_actions_t FileActions; posix_spawn_file_actions_init(&FileActions); if (PipeWrite) { const FPipeHandle* PipeWriteHandle = reinterpret_cast< const FPipeHandle* >(PipeWrite); posix_spawn_file_actions_adddup2(&FileActions, PipeWriteHandle->GetHandle(), STDOUT_FILENO); } int PosixSpawnErrNo = posix_spawn(&ChildPid, TCHAR_TO_UTF8(*ProcessPath), &FileActions, nullptr, Argv, environ); posix_spawn_file_actions_destroy(&FileActions); if (PosixSpawnErrNo != 0) { UE_LOG(LogHAL, Fatal, TEXT("FLinuxPlatformProcess::CreateProc: posix_spawn() failed (%d, %s)"), PosixSpawnErrNo, ANSI_TO_TCHAR(strerror(PosixSpawnErrNo))); return FProcHandle(); // produce knowingly invalid handle if for some reason Fatal log (above) returns } // renice the child (subject to race condition). // Why this instead of posix_spawn_setschedparam()? // Because posix_spawnattr priority is unusable under Linux due to min/max priority range being [0;0] for the default scheduler if (PriorityModifier != 0) { errno = 0; int TheirCurrentPrio = getpriority(PRIO_PROCESS, ChildPid); if (errno != 0) { int ErrNo = errno; UE_LOG(LogHAL, Warning, TEXT("FLinuxPlatformProcess::CreateProc: could not get child's priority, errno=%d (%s)"), ErrNo, ANSI_TO_TCHAR(strerror(ErrNo)) ); // proceed anyway... TheirCurrentPrio = 0; } rlimit PrioLimits; int MaxPrio = 0; if (getrlimit(RLIMIT_NICE, &PrioLimits) == -1) { int ErrNo = errno; UE_LOG(LogHAL, Warning, TEXT("FLinuxPlatformProcess::CreateProc: could not get priority limits (RLIMIT_NICE), errno=%d (%s)"), ErrNo, ANSI_TO_TCHAR(strerror(ErrNo)) ); // proceed anyway... } else { MaxPrio = PrioLimits.rlim_cur; } int NewPrio = TheirCurrentPrio; if (PriorityModifier > 0) { // decrease the nice value - will perhaps fail, it's up to the user to run with proper permissions NewPrio -= 10; } else { NewPrio += 10; } // cap to [RLIMIT_NICE, 19] NewPrio = FMath::Min(19, NewPrio); NewPrio = FMath::Max(MaxPrio, NewPrio); // MaxPrio is actually the _lowest_ numerically priority if (setpriority(PRIO_PROCESS, ChildPid, NewPrio) == -1) { int ErrNo = errno; UE_LOG(LogHAL, Warning, TEXT("FLinuxPlatformProcess::CreateProc: could not change child's priority (nice value) from %d to %d, errno=%d (%s)"), TheirCurrentPrio, NewPrio, ErrNo, ANSI_TO_TCHAR(strerror(ErrNo)) ); } else { UE_LOG(LogHAL, Log, TEXT("Changed child's priority (nice value) to %d (change from %d)"), NewPrio, TheirCurrentPrio); } } else { UE_LOG(LogHAL, Log, TEXT("FLinuxPlatformProcess::CreateProc: spawned child %d"), ChildPid); } if (OutProcessID) { *OutProcessID = ChildPid; } // [RCL] 2015-03-11 @FIXME: is bLaunchDetached usable when determining whether we're in 'fire and forget' mode? This doesn't exactly match what bLaunchDetached is used for. return FProcHandle(new FProcState(ChildPid, bLaunchDetached)); } /** Initialization constructor. */ FProcState::FProcState(pid_t InProcessId, bool bInFireAndForget) : ProcessId(InProcessId) , bIsRunning(true) // assume it is , bHasBeenWaitedFor(false) , ReturnCode(-1) , bFireAndForget(bInFireAndForget) { } FProcState::~FProcState() { if (!bFireAndForget) { // If not in 'fire and forget' mode, try to catch the common problems that leave zombies: // - We don't want to close the handle of a running process as with our current scheme this will certainly leak a zombie. // - Nor we want to leave the handle unwait()ed for. if (bIsRunning) { // Warn the users before going into what may be a very long block UE_LOG(LogHAL, Warning, TEXT("Closing a process handle while the process (pid=%d) is still running - we will block until it exits to prevent a zombie"), GetProcessId() ); } else if (!bHasBeenWaitedFor) // if child is not running, but has not been waited for, still communicate a problem, but we shouldn't be blocked for long in this case. { UE_LOG(LogHAL, Warning, TEXT("Closing a process handle of a process (pid=%d) that has not been wait()ed for - will wait() now to reap a zombie"), GetProcessId() ); } Wait(); // will exit immediately if everything is Ok } else if (IsRunning()) { // warn about leaking a thread ;/ UE_LOG(LogHAL, Warning, TEXT("Process (pid=%d) is still running - we will reap it in a waiter thread, but the thread handle is going to be leaked."), GetProcessId() ); FChildWaiterThread * WaiterRunnable = new FChildWaiterThread(GetProcessId()); // [RCL] 2015-03-11 @FIXME: do not leak FRunnableThread * WaiterThread = FRunnableThread::Create(WaiterRunnable, *FString::Printf(TEXT("waitpid(%d)"), GetProcessId(), 32768 /* needs just a small stack */, TPri_BelowNormal)); } } bool FProcState::IsRunning() { if (bIsRunning) { check(!bHasBeenWaitedFor); // check for the sake of internal consistency // check if actually running int KillResult = kill(GetProcessId(), 0); // no actual signal is sent check(KillResult != -1 || errno != EINVAL); bIsRunning = (KillResult == 0 || (KillResult == -1 && errno == EPERM)); // additional check if it's a zombie if (bIsRunning) { for(;;) // infinite loop in case we get EINTR and have to repeat { siginfo_t SignalInfo; SignalInfo.si_pid = 0; // if remains 0, treat as child was not waitable (i.e. was running) if (waitid(P_PID, GetProcessId(), &SignalInfo, WEXITED | WNOHANG | WNOWAIT)) { if (errno != EINTR) { int ErrNo = errno; UE_LOG(LogHAL, Fatal, TEXT("FLinuxPlatformProcess::WaitForProc: waitid for pid %d failed (errno=%d, %s)"), static_cast< int32 >(GetProcessId()), ErrNo, ANSI_TO_TCHAR(strerror(ErrNo))); break; // exit the loop if for some reason Fatal log (above) returns } } else { bIsRunning = ( SignalInfo.si_pid != GetProcessId() ); break; } } } // If child is a zombie, wait() immediately to free up kernel resources. Higher level code // (e.g. shader compiling manager) can hold on to handle of no longer running process for longer, // which is a dubious, but valid behavior. We don't want to keep zombie around though. if (!bIsRunning) { UE_LOG(LogHAL, Log, TEXT("Child %d is no more running (zombie), Wait()ing immediately."), GetProcessId() ); Wait(); } } return bIsRunning; } bool FProcState::GetReturnCode(int32* ReturnCodePtr) { check(!bIsRunning || !"You cannot get a return code of a running process"); if (!bHasBeenWaitedFor) { Wait(); } if (ReturnCode != -1) { if (ReturnCodePtr != NULL) { *ReturnCodePtr = ReturnCode; } return true; } return false; } void FProcState::Wait() { if (bHasBeenWaitedFor) { return; // we could try waitpid() another time, but why } for(;;) // infinite loop in case we get EINTR and have to repeat { siginfo_t SignalInfo; if (waitid(P_PID, GetProcessId(), &SignalInfo, WEXITED)) { if (errno != EINTR) { int ErrNo = errno; UE_LOG(LogHAL, Fatal, TEXT("FLinuxPlatformProcess::WaitForProc: waitid for pid %d failed (errno=%d, %s)"), static_cast< int32 >(GetProcessId()), ErrNo, ANSI_TO_TCHAR(strerror(ErrNo))); break; // exit the loop if for some reason Fatal log (above) returns } } else { check(SignalInfo.si_pid == GetProcessId()); ReturnCode = (SignalInfo.si_code == CLD_EXITED) ? SignalInfo.si_status : -1; bHasBeenWaitedFor = true; bIsRunning = false; // set in advance break; } } } bool FLinuxPlatformProcess::IsProcRunning( FProcHandle & ProcessHandle ) { FProcState * ProcInfo = ProcessHandle.GetProcessInfo(); return ProcInfo ? ProcInfo->IsRunning() : false; } void FLinuxPlatformProcess::WaitForProc( FProcHandle & ProcessHandle ) { FProcState * ProcInfo = ProcessHandle.GetProcessInfo(); if (ProcInfo) { ProcInfo->Wait(); } } void FLinuxPlatformProcess::CloseProc(FProcHandle & ProcessHandle) { // dispose of both handle and process info FProcState * ProcInfo = ProcessHandle.GetProcessInfo(); ProcessHandle.Reset(); delete ProcInfo; } void FLinuxPlatformProcess::TerminateProc( FProcHandle & ProcessHandle, bool KillTree ) { if (KillTree) { // TODO: enumerate the children STUBBED("FLinuxPlatformProcess::TerminateProc() : Killing a subtree is not implemented yet"); } FProcState * ProcInfo = ProcessHandle.GetProcessInfo(); if (ProcInfo) { int KillResult = kill(ProcInfo->GetProcessId(), SIGTERM); // graceful check(KillResult != -1 || errno != EINVAL); } } uint32 FLinuxPlatformProcess::GetCurrentProcessId() { return getpid(); } FString FLinuxPlatformProcess::GetCurrentWorkingDirectory() { // get the current directory ANSICHAR CurrentDir[MAX_PATH] = { 0 }; getcwd(CurrentDir, sizeof(CurrentDir)); return UTF8_TO_TCHAR(CurrentDir); } bool FLinuxPlatformProcess::GetProcReturnCode(FProcHandle& ProcHandle, int32* ReturnCode) { if (IsProcRunning(ProcHandle)) { return false; } FProcState * ProcInfo = ProcHandle.GetProcessInfo(); return ProcInfo ? ProcInfo->GetReturnCode(ReturnCode) : false; } bool FLinuxPlatformProcess::Daemonize() { if (daemon(1, 1) == -1) { int ErrNo = errno; UE_LOG(LogHAL, Warning, TEXT("daemon(1, 1) failed with errno = %d (%s)"), ErrNo, StringCast< TCHAR >(strerror(ErrNo)).Get()); return false; } return true; } bool FLinuxPlatformProcess::IsApplicationRunning( uint32 ProcessId ) { errno = 0; getpriority(PRIO_PROCESS, ProcessId); return errno == 0; } bool FLinuxPlatformProcess::IsThisApplicationForeground() { extern FLinuxApplication* LinuxApplication; return (LinuxApplication != nullptr) ? LinuxApplication->IsForeground() : true; } bool FLinuxPlatformProcess::IsApplicationRunning( const TCHAR* ProcName ) { FString Commandline = TEXT("pidof '"); Commandline += ProcName; Commandline += TEXT("' > /dev/null"); return !system(TCHAR_TO_UTF8(*Commandline)); } bool FLinuxPlatformProcess::ExecProcess( const TCHAR* URL, const TCHAR* Params, int32* OutReturnCode, FString* OutStdOut, FString* OutStdErr ) { FString CmdLineParams = Params; FString ExecutableFileName = URL; int32 ReturnCode = -1; FString DefaultError; if (!OutStdErr) { OutStdErr = &DefaultError; } void* PipeRead = nullptr; void* PipeWrite = nullptr; verify(FPlatformProcess::CreatePipe(PipeRead, PipeWrite)); bool bInvoked = false; const bool bLaunchDetached = true; const bool bLaunchHidden = false; const bool bLaunchReallyHidden = bLaunchHidden; FProcHandle ProcHandle = FPlatformProcess::CreateProc(*ExecutableFileName, *CmdLineParams, bLaunchDetached, bLaunchHidden, bLaunchReallyHidden, NULL, 0, NULL, PipeWrite); if (ProcHandle.IsValid()) { while (FPlatformProcess::IsProcRunning(ProcHandle)) { FString NewLine = FPlatformProcess::ReadPipe(PipeRead); if (NewLine.Len() > 0) { if (OutStdOut != nullptr) { *OutStdOut += NewLine; } } FPlatformProcess::Sleep(0.5); } // read the remainder for(;;) { FString NewLine = FPlatformProcess::ReadPipe(PipeRead); if (NewLine.Len() <= 0) { break; } if (OutStdOut != nullptr) { *OutStdOut += NewLine; } } FPlatformProcess::Sleep(0.5); bInvoked = true; bool bGotReturnCode = FPlatformProcess::GetProcReturnCode(ProcHandle, &ReturnCode); check(bGotReturnCode); *OutReturnCode = ReturnCode; FPlatformProcess::CloseProc(ProcHandle); } else { bInvoked = false; *OutReturnCode = -1; *OutStdOut = ""; UE_LOG(LogHAL, Warning, TEXT("Failed to launch Tool. (%s)"), *ExecutableFileName); } FPlatformProcess::ClosePipe(PipeRead, PipeWrite); return bInvoked; } void FLinuxPlatformProcess::LaunchFileInDefaultExternalApplication( const TCHAR* FileName, const TCHAR* Parms, ELaunchVerb::Type Verb ) { // TODO This ignores parms and verb pid_t pid = fork(); if (pid == 0) { exit(execl("/usr/bin/xdg-open", "xdg-open", TCHAR_TO_UTF8(FileName), (char *)0)); } } void FLinuxPlatformProcess::ExploreFolder( const TCHAR* FilePath ) { // TODO This is broken, not an explore action but should be fine if called on a directory FLinuxPlatformProcess::LaunchFileInDefaultExternalApplication(FilePath, NULL, ELaunchVerb::Edit); } /** * Private struct to store implementation specific data. */ struct FProcEnumData { // Array of processes. TArray<FLinuxPlatformProcess::FProcEnumInfo> Processes; // Current process id. uint32 CurrentProcIndex; }; FLinuxPlatformProcess::FProcEnumerator::FProcEnumerator() { Data = new FProcEnumData; Data->CurrentProcIndex = -1; TArray<uint32> PIDs; class FPIDsCollector : public IPlatformFile::FDirectoryVisitor { public: FPIDsCollector(TArray<uint32>& InPIDsToCollect) : PIDsToCollect(InPIDsToCollect) { } bool Visit(const TCHAR* FilenameOrDirectory, bool bIsDirectory) { FString StrPID = FPaths::GetBaseFilename(FilenameOrDirectory); if (bIsDirectory && FCString::IsNumeric(*StrPID)) { PIDsToCollect.Add(FCString::Atoi(*StrPID)); } return true; } private: TArray<uint32>& PIDsToCollect; } PIDsCollector(PIDs); IPlatformFile::GetPlatformPhysical().IterateDirectory(TEXT("/proc"), PIDsCollector); for (auto PID : PIDs) { Data->Processes.Add(FProcEnumInfo(PID)); } } FLinuxPlatformProcess::FProcEnumerator::~FProcEnumerator() { delete Data; } FLinuxPlatformProcess::FProcEnumInfo FLinuxPlatformProcess::FProcEnumerator::GetCurrent() const { return Data->Processes[Data->CurrentProcIndex]; } bool FLinuxPlatformProcess::FProcEnumerator::MoveNext() { if (Data->CurrentProcIndex + 1 == Data->Processes.Num()) { return false; } ++Data->CurrentProcIndex; return true; } FLinuxPlatformProcess::FProcEnumInfo::FProcEnumInfo(uint32 InPID) : PID(InPID) { } uint32 FLinuxPlatformProcess::FProcEnumInfo::GetPID() const { return PID; } uint32 FLinuxPlatformProcess::FProcEnumInfo::GetParentPID() const { char Buf[256]; uint32 DummyNumber; char DummyChar; uint32 ParentPID; sprintf(Buf, "/proc/%d/stat", GetPID()); FILE* FilePtr = fopen(Buf, "r"); fscanf(FilePtr, "%d %s %c %d", &DummyNumber, Buf, &DummyChar, &ParentPID); fclose(FilePtr); return ParentPID; } FString FLinuxPlatformProcess::FProcEnumInfo::GetFullPath() const { return GetApplicationName(GetPID()); } FString FLinuxPlatformProcess::FProcEnumInfo::GetName() const { return FPaths::GetCleanFilename(GetFullPath()); }
26.875937
253
0.707045
ec349105626f6ef1b4acc73abbf21be54516c61e
4,545
cpp
C++
LaalMathEngine/src/Shape/SvgShape.cpp
vijayshankarkumar/LME
6483d893a8902cec4959936220656fcab2b72d4f
[ "MIT" ]
1
2022-02-18T10:38:42.000Z
2022-02-18T10:38:42.000Z
LaalMathEngine/src/Shape/SvgShape.cpp
vijayshankarkumar/LME
6483d893a8902cec4959936220656fcab2b72d4f
[ "MIT" ]
1
2021-09-03T21:20:38.000Z
2021-09-03T21:20:38.000Z
LaalMathEngine/src/Shape/SvgShape.cpp
vijayshankarkumar/LME
6483d893a8902cec4959936220656fcab2b72d4f
[ "MIT" ]
null
null
null
#include "Shape/SvgShape.h" namespace laal { SvgShape::SvgShape() { } SvgShape::SvgShape(const std::string& fileName) { InitChildShapes(fileName); } SvgShape::~SvgShape() { for (Shape* shape : m_ChildShapes) { delete shape; } } void SvgShape::InitChildShapes(const std::string& fileName) { NSVGimage* image; image = nsvgParseFromFile(fileName.c_str(), "px", 96); //std::cout << "after the image init..." << std::endl; for (NSVGshape* shape = image->shapes; shape != NULL; shape = shape->next) { //std::cout << "In ther loop..." << std::endl; Shape* childShape = new Shape(); SetFillStyle(shape, childShape); SetStrokeStyle(shape, childShape); SetPath(shape, childShape); Add(childShape); } nsvgDelete(image); } void SvgShape::SetFillStyle(NSVGshape* fromShape, Shape* toShape) { Style fillStyle; switch (fromShape->fill.type) { case NSVG_PAINT_NONE: fillStyle.StyleType(STYLE_NONE); break; case NSVG_PAINT_COLOR: { unsigned int color = fromShape->fill.color; double r = (double)(color & 255) / 255.0; color >>= 8; double g = (double)(color & 255) / 255.0; color >>= 8; double b = (double)(color & 255) / 255.0; color >>= 8; double a = (double)(color) / 255.0; fillStyle.SetColor(Color(r, g, b, a)); //std::cout << "fill color => " << r << " " << g << " " << b << " " << a << std::endl; break; } case NSVG_PAINT_LINEAR_GRADIENT: break; case NSVG_PAINT_RADIAL_GRADIENT: break; default: break; } switch (fromShape->fillRule) { case NSVG_FILLRULE_EVENODD: fillStyle.FillRule(FILL_RULE_EVENODD); break; case NSVG_FILLRULE_NONZERO: fillStyle.FillRule(FILL_RULE_NONEZERO); break; default: break; } fillStyle.Opacity(fromShape->opacity); toShape->SetFillStyle(fillStyle); } void SvgShape::SetStrokeStyle(NSVGshape* fromShape, Shape* toShape) { /*switch (fromShape->stroke.type) { case NSVG_PAINT_NONE: toShape->FillType(FILL_NONE); break; case NSVG_PAINT_COLOR: toShape->StrokeColor(fromShape->fill.color); break; case NSVG_PAINT_LINEAR_GRADIENT: break; case NSVG_PAINT_RADIAL_GRADIENT: break; default: break; } switch (fromShape->fillRule) { case NSVG_FILLRULE_EVENODD: toShape->FillRule(FILL_RULE_EVENODD); break; case NSVG_FILLRULE_NONZERO: toShape->FillRule(FILL_RULE_NONEZERO); break; default: break; }*/ if (fromShape->fill.type == NSVG_PAINT_COLOR) { unsigned int color = fromShape->fill.color; double r = (double)(color & 255) / 255.0; color >>= 8; double g = (double)(color & 255) / 255.0; color >>= 8; double b = (double)(color & 255) / 255.0; color >>= 8; double a = (double)(color) / 255.0; toShape->StrokeColor(Color(r, g, b, a)); //std::cout << "stroke color => " << r << " " << g << " " << b << " " << a << std::endl; } toShape->StrokeOpacity(fromShape->opacity); toShape->StrokeWidth(fromShape->strokeWidth); //std::cout << "stroke type => " << fromShape->stroke.type << std::endl; //std::cout << "stroke width => " << fromShape->strokeWidth << std::endl; } void SvgShape::SetPath(NSVGshape* fromShape, Shape* toShape) { for (NSVGpath* path = fromShape->paths; path != NULL; path = path->next) { toShape->StartNewPath(Point(path->pts[0], path->pts[1], 0.0)); for (int i = 0; i < path->npts - 1; i += 3) { float* p = &path->pts[i * 2]; toShape->LastPath()->AddPoint(Point(p[2], p[3], 0.0)); toShape->LastPath()->AddPoint(Point(p[4], p[5], 0.0)); toShape->LastPath()->AddPoint(Point(p[6], p[7], 0.0)); } toShape->LastPath()->MiterLimit(fromShape->miterLimit); switch (fromShape->strokeLineJoin) { case NSVG_JOIN_BEVEL: toShape->LastPath()->LineJoin(JOIN_BAVEL); break; case NSVG_JOIN_MITER: toShape->LastPath()->LineJoin(JOIN_MITER); break; case NSVG_JOIN_ROUND: toShape->LastPath()->LineJoin(JOIN_ROUND); break; default: break; } switch (fromShape->strokeLineCap) { case NSVG_CAP_BUTT: toShape->LastPath()->LineCap(CAP_BUTT); break; case NSVG_CAP_ROUND: toShape->LastPath()->LineCap(CAP_ROUND); break; case NSVG_CAP_SQUARE: toShape->LastPath()->LineCap(CAP_SQUARE); break; default: break; } //std::cout << "path closed flag => " << (int)path->closed << std::endl; if ((int)path->closed == 0) { toShape->LastPath()->Close(); //std::cout << "path is closed...." << std::endl; } } } }
22.5
91
0.626843
ec360c64fc078ef775cec6f7c9475b9ced8fe411
1,343
cc
C++
src/leveldb/db/version_edit_test.cc
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
src/leveldb/db/version_edit_test.cc
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
src/leveldb/db/version_edit_test.cc
moorecoin/MooreCoinMiningAlgorithm
fe6a153e1392f6e18110b1e69481aa5c3c8b4a1d
[ "MIT" ]
null
null
null
// copyright (c) 2011 the leveldb authors. all rights reserved. // use of this source code is governed by a bsd-style license that can be // found in the license file. see the authors file for names of contributors. #include "db/version_edit.h" #include "util/testharness.h" namespace leveldb { static void testencodedecode(const versionedit& edit) { std::string encoded, encoded2; edit.encodeto(&encoded); versionedit parsed; status s = parsed.decodefrom(encoded); assert_true(s.ok()) << s.tostring(); parsed.encodeto(&encoded2); assert_eq(encoded, encoded2); } class versionedittest { }; test(versionedittest, encodedecode) { static const uint64_t kbig = 1ull << 50; versionedit edit; for (int i = 0; i < 4; i++) { testencodedecode(edit); edit.addfile(3, kbig + 300 + i, kbig + 400 + i, internalkey("foo", kbig + 500 + i, ktypevalue), internalkey("zoo", kbig + 600 + i, ktypedeletion)); edit.deletefile(4, kbig + 700 + i); edit.setcompactpointer(i, internalkey("x", kbig + 900 + i, ktypevalue)); } edit.setcomparatorname("foo"); edit.setlognumber(kbig + 100); edit.setnextfile(kbig + 200); edit.setlastsequence(kbig + 1000); testencodedecode(edit); } } // namespace leveldb int main(int argc, char** argv) { return leveldb::test::runalltests(); }
28.574468
77
0.676098
ec3dedc1db72bb18c98c72b2040a10eee84a5009
62,323
cpp
C++
Analysis/Calibration/LinearCalibrationModel.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
125
2015-01-22T05:43:23.000Z
2022-03-22T17:15:59.000Z
Analysis/Calibration/LinearCalibrationModel.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
59
2015-02-10T09:13:06.000Z
2021-11-11T02:32:38.000Z
Analysis/Calibration/LinearCalibrationModel.cpp
konradotto/TS
bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e
[ "Apache-2.0" ]
98
2015-01-17T01:25:10.000Z
2022-03-18T17:29:42.000Z
/* Copyright (C) 2015 Life Technologies Corporation, a part of Thermo Fisher Scientific, Inc. All Rights Reserved. */ //! @file LinearCalibrationModel.cpp //! @ingroup Calibration //! @brief LinearCalibrationModel. Algorithms for adjusting the predicted signal by homopolymer. //! @brief During model training we collect pairs of measured and predicted signals by homopolymer //! @brief and determine offset and gain coefficients. //! @brief During model application we adjust the predicted signal using the model parameters. #include <math.h> #include <SystemMagicDefines.h> #include "LinearCalibrationModel.h" #include "FlowAlignment.h" // ========================================================================== // A general word of caution: // The module LinearCalibrationModel uses closed intervals in its json representation. // Expect for "max_hp_calibrated", which is exclusive. void LinearCalibrationModel::PrintHelp_Training() { cout << "LinearCalibrationModel Training Options:" << endl; cout << " --model-calibration BOOL Turn training for this module on/off [true]" << endl; cout << " --model-training-style STR Train using {common-offset, old-style} [common-offset]" << endl; cout << " --model-calib-min-hp INT Min homopolymer length to be trained [0]" << endl; cout << " --model-calib-min-samples INT Min required number of samples per HP [50]" << endl; cout << " --model-calib-min-inphase FLOAT Minimum fraction of in-phase molecules [0.1]" << endl; cout << " --model-calib-max-residual FLOAT Maximum accepted value for scaled residual [1.5]" << endl; cout << " --model-calib-max-gain-shift FLOAT Max shift in slope between adjacent lengths [0.1]" << endl; cout << " --model-multi-train BOOL Train adjacent homopolymers using same data [false]" << endl; cout << " --multi-weight INT Weight of target homopolymer compared to adjacent ones [10]" << endl; cout << " --model-training-stats BOOL Switch to output training statistics [false]" << endl; // These option only have an effect on the model training portion of the code } // ========================================================================== // Structure to accumulate statistics for an atomic calibration unit LinearFitCell::LinearFitCell() { Reset(); }; // -------------------------------------------------------------------------- void LinearFitCell::Reset() { mean_pred_ = 0.0; mean_measured_ = 0.0; M2pred_ = 0.0; M2meas_ = 0.0; Cn_ = 0.0; nsamples_ = 0; nreads_ = 0; }; // set a flat prior at '1,0' void LinearFitCell::Prior(float center, float var, int xamples) { mean_pred_ = center; mean_measured_ = center; M2pred_ = var; M2meas_ = var; Cn_ = var; nsamples_ = xamples; }; //discount void LinearFitCell::ReduceStrength(int xamples) { if (xamples<(int)nsamples_){ float super_ratio = (xamples*1.0f)/(nsamples_*1.0f); M2pred_ *= super_ratio; M2meas_ *= super_ratio; Cn_ *= super_ratio; nsamples_ = xamples; } } // -------------------------------------------------------------------------- // Update for adding one more data point void LinearFitCell::AddDataPoint(float prediction, float measured) { ++nsamples_; double delta_p = prediction - mean_pred_; mean_pred_ += delta_p / (double)nsamples_; double delta_m = measured - mean_measured_; mean_measured_ += delta_m / (double)nsamples_; M2pred_ += delta_p * (prediction - mean_pred_); M2meas_ += delta_m * (measured - mean_measured_); Cn_ += delta_p * (measured - mean_measured_); if (active_){ nreads_++; active_ = false; // ate this read already } }; // -------------------------------------------------------------------------- // Add data from one cell to a master cell void LinearFitCell::AccumulateTrainingData(const LinearFitCell& other) { if (other.nsamples_ == 0) return; // Nothing to do if (nsamples_ == 0){ nsamples_ = other.nsamples_; mean_pred_ = other.mean_pred_; mean_measured_ = other.mean_measured_; M2pred_ = other.M2pred_; M2meas_ = other.M2meas_; Cn_ = other.Cn_; nreads_ = other.nreads_; return; } // We have data in both the master as well as the input cell and have to combine them unsigned long total_samples = other.nsamples_ + nsamples_; double delta_mean_p = other.mean_pred_ - mean_pred_; mean_pred_ += (delta_mean_p * (double)other.nsamples_) / (double)total_samples; M2pred_ += other.M2pred_ + (delta_mean_p * (double)nsamples_ / (double)total_samples * delta_mean_p * (double)other.nsamples_) ; double delta_mean_m = other.mean_measured_ - mean_measured_; mean_measured_ += (delta_mean_m * (double)other.nsamples_) / (double)total_samples; M2meas_ += other.M2meas_ + (delta_mean_m * (double)nsamples_ / (double)total_samples * delta_mean_m * (double)other.nsamples_) ; Cn_ += other.Cn_ + (delta_mean_p * (double)nsamples_ / (double)total_samples * delta_mean_m * (double)other.nsamples_); nsamples_ = total_samples; nreads_ = other.nreads_ + nreads_; }; // -------------------------------------------------------------------------- void LinearFitCell::GetSlopeOnlyFit(double &gain) const { gain = (Cn_ / (double)(nsamples_-1) + (mean_pred_ * mean_measured_)) / (M2pred_ / (double)(nsamples_-1) + (mean_pred_ * mean_pred_)); }; // -------------------------------------------------------------------------- void LinearFitCell::GetSlopeAndInterceptFit(double &gain, double &offset) const { gain = Cn_ / M2pred_; offset = mean_measured_ - (gain * mean_pred_); }; void LinearFitCell::GetSafeSlopeAndInterceptFit(double &gain, double &offset, double safety_frac) const { GetSlopeAndInterceptFit(gain, offset); double valid_offset = mean_measured_ * safety_frac; if (offset>valid_offset){ offset = valid_offset; } if (offset<(-valid_offset)){ offset = -valid_offset; } gain = GetSlopeOnlyFitWithOffset(offset); }; // -------------------------------------------------------------------------- double LinearFitCell::GetSlopeOnlyFitWithOffset(double offset) const { double new_mean_pred = mean_pred_ + offset; // We store centered sums of squares and now we un-center them with the new mean return ((Cn_ / (double)(nsamples_-1) + (new_mean_pred * mean_measured_)) / (M2pred_ / (double)(nsamples_-1) + (new_mean_pred * new_mean_pred))); } // -------------------------------------------------------------------------- double LinearFitCell::GetOffsetOnly() const { return (mean_measured_ - mean_pred_); } // -------------------------------------------------------------------------- Json::Value LinearFitCell::DataToJson() const { Json::Value my_value(Json::objectValue); my_value["num_samples"] = (Json::UInt64)nsamples_; my_value["mean_predicted"] = mean_pred_; my_value["mean_measured"] = mean_measured_; if (nsamples_ > 1){ my_value["var_predicted"] = M2pred_ / (double)(nsamples_-1); my_value["var_measured"] = M2meas_ / (double)(nsamples_-1); my_value["covariance"] = Cn_ / (double)(nsamples_-1); } else{ my_value["var_predictions"] = 0.0f; my_value["var_measured"] = 0.0f; my_value["covariance"] = 0.0f; } return my_value; } // ========================================================================== // gain and offset stratified by <flow><nucleotide><called_hp length> void LinCalModelRegion::Initialize(int num_flow_windows) { gain_values.resize(num_flow_windows); offset_values.resize(num_flow_windows); for (int iWindow=0; iWindow < num_flow_windows; ++iWindow){ gain_values.at(iWindow).resize(4); offset_values.at(iWindow).resize(4); for (int iNuc=0; iNuc < 4; ++iNuc){ gain_values.at(iWindow).at(iNuc).assign(MAX_HPXLEN+1, 1.0); offset_values.at(iWindow).at(iNuc).assign(MAX_HPXLEN+1, 0.0); } } } // -------------------------------------------------------------------------- // This function exists because in the future we want to do something smarter // than just copying the values void LinCalModelRegion::SetModelGainsAndOffsets(int num_flows, int flow_window_size) { gains.resize(num_flows); offsets.resize(num_flows); int my_flow_window = 0; for (int iFlow=0; iFlow<num_flows; ++iFlow){ gains.at(iFlow).resize(4); offsets.at(iFlow).resize(4); my_flow_window = iFlow / flow_window_size; for (int iNuc=0; iNuc < 4; ++iNuc) { gains.at(iFlow).at(iNuc).resize(MAX_HPXLEN+1); offsets.at(iFlow).at(iNuc).resize(MAX_HPXLEN+1); for (int iHP=0; iHP <= MAX_HPXLEN; ++iHP) { gains.at(iFlow).at(iNuc).at(iHP) = gain_values.at(my_flow_window).at(iNuc).at(iHP); offsets.at(iFlow).at(iNuc).at(iHP) = offset_values.at(my_flow_window).at(iNuc).at(iHP); } } } } // -------------------------------------------------------------------------- void LinCalModelRegion::InitializeTrainingData(int num_flow_windows) { training_data.resize(num_flow_windows); for (int iWindow=0; iWindow < num_flow_windows; ++iWindow){ training_data.at(iWindow).resize(4); for (int iNuc=0; iNuc < 4; ++iNuc) { training_data.at(iWindow).at(iNuc).resize(MAX_HPXLEN+1); for (int iHP=0; iHP <= MAX_HPXLEN; ++iHP) { training_data.at(iWindow).at(iNuc).at(iHP).Reset(); } } } } // data points come from fresh read, as opposed to additional data within same read void LinCalModelRegion::FreshReadData() { for (unsigned int iWindow=0; iWindow < training_data.size(); ++iWindow){ for (unsigned int iNuc=0; iNuc < training_data.at(iWindow).size(); ++iNuc) { for (unsigned int iHP=0; iHP < training_data.at(iWindow).at(iNuc).size(); ++iHP) { training_data.at(iWindow).at(iNuc).at(iHP).SetActive(true); } } } } // -------------------------------------------------------------------------- void LinCalModelRegion::AccumulateTrainingData(const LinCalModelRegion& other) { for (unsigned int iWindow=0; iWindow < training_data.size(); ++iWindow){ for (unsigned int iNuc=0; iNuc < training_data.at(iWindow).size(); ++iNuc) { for (unsigned int iHP=0; iHP < training_data.at(iWindow).at(iNuc).size(); ++iHP) { training_data.at(iWindow).at(iNuc).at(iHP).AccumulateTrainingData(other.training_data.at(iWindow).at(iNuc).at(iHP)); } } } } // -------------------------------------------------------------------------- // Single line function??? // because caller should not know internal data structure of lincalmodelregion void LinCalModelRegion::AddDataPoint(int flow_window, int nuc, int hp, float prediction, float measured) { training_data.at(flow_window).at(nuc).at(hp).AddDataPoint(prediction, measured); } // -------------------------------------------------------------------------- // We take training data and turn it into a calibration model // This is a different approach than the one in the calibrate module int LinCalModelRegion::CreateCalibrationModel(int region_idx, unsigned long min_nsamples, float max_gain_shift, bool verbose) { // Initialize data structures to hold model parameters Initialize(training_data.size()); double offset_zero, gain_value; int max_hp_calibrated = 0; vector<int> max_hps_calibrated(4,0); // Iterate over atomic elements for (unsigned int iWindow=0; iWindow < training_data.size(); ++iWindow){ max_hps_calibrated.assign(4,0); for (unsigned int iNuc=0; iNuc < 4; ++iNuc) { //cout << " -- Computing model for window " << iWindow << " nuc " << ion::FlowOrder::IntToNuc(iNuc) << endl; // Compute a common offset from the zero-mer values if (training_data.at(iWindow).at(iNuc).at(0).NumSamples() >= min_nsamples) { offset_zero = training_data.at(iWindow).at(iNuc).at(0).GetOffsetOnly(); offset_values.at(iWindow).at(iNuc).at(0) = offset_zero; } else offset_zero = 0; //cout << " -> Offset: " << offset_zero << "Gains: "; for (int iHP=1; iHP <= MAX_HPXLEN; ++iHP) { offset_values.at(iWindow).at(iNuc).at(iHP) = offset_zero; if (training_data.at(iWindow).at(iNuc).at(iHP).NumSamples() >= min_nsamples) { gain_values.at(iWindow).at(iNuc).at(iHP) = training_data.at(iWindow).at(iNuc).at(iHP).GetSlopeOnlyFitWithOffset(offset_zero); // it may be helpful to restrain this // ((a*HP-b)-(a'*HP-b)) vs k*HP -> abs(a-a')<k float last_gain = gain_values.at(iWindow).at(iNuc).at(iHP-1); float cur_gain = gain_values.at(iWindow).at(iNuc).at(iHP); if ((last_gain-cur_gain)>max_gain_shift){ cur_gain=last_gain-max_gain_shift; } if ((cur_gain-last_gain)>max_gain_shift){ cur_gain = last_gain+max_gain_shift; } gain_values.at(iWindow).at(iNuc).at(iHP)=cur_gain; max_hp_calibrated = max(max_hp_calibrated, iHP); max_hps_calibrated.at(iNuc) = max(max_hps_calibrated.at(iNuc), iHP); //cout << gain_values.at(iWindow).at(iNuc).at(iHP) << ", "; } else { // Zero order interpolation if we don't have enough training data gain_values.at(iWindow).at(iNuc).at(iHP) = gain_values.at(iWindow).at(iNuc).at(iHP-1); //cout << gain_values.at(iWindow).at(iNuc).at(iHP) << "(" << training_data.at(iWindow).at(iNuc).at(iHP).GetNSamples()<< "), "; } } } // Print maximum calibrated hp lengths by region, window, and nucleotide to log file. if (verbose) { if (iWindow == 0) cout << "LinearModelCalibration: Max HP calibrated, region " << region_idx; cout << "; window " << iWindow << ": " << max_hps_calibrated.at(0) << ion::FlowOrder::IntToNuc(0); for (unsigned int iNuc=1; iNuc < 4; ++iNuc) { cout << "," << max_hps_calibrated.at(iNuc) << ion::FlowOrder::IntToNuc(iNuc); } if (iWindow == training_data.size()-1) cout << endl; } } return max_hp_calibrated; } // ----------------------------------------------------------- // free-form can soak up issues with phasing int LinCalModelRegion::CreateOldStyleCalibrationModel(int region_idx, unsigned long min_nsamples, bool verbose) { // Initialize data structures to hold model parameters Initialize(training_data.size()); double offset_zero, gain_value; int max_hp_calibrated = 0; vector<int> max_hps_calibrated(4,0); // Iterate over atomic elements for (unsigned int iWindow=0; iWindow < training_data.size(); ++iWindow){ max_hps_calibrated.assign(4,0); for (unsigned int iNuc=0; iNuc < 4; ++iNuc) { //cout << " -- Computing model for window " << iWindow << " nuc " << ion::FlowOrder::IntToNuc(iNuc) << endl; // Compute a common offset from the zero-mer values if (training_data.at(iWindow).at(iNuc).at(0).NumSamples() >= min_nsamples) { offset_zero = training_data.at(iWindow).at(iNuc).at(0).GetOffsetOnly(); offset_values.at(iWindow).at(iNuc).at(0) = offset_zero; } else offset_zero = 0; //cout << " -> Offset: " << offset_zero << "Gains: "; double last_good_gain = 1.0; for (int iHP=1; iHP <= MAX_HPXLEN; ++iHP) { offset_values.at(iWindow).at(iNuc).at(iHP) = offset_zero; if (training_data.at(iWindow).at(iNuc).at(iHP).NumSamples() >= min_nsamples) { double tmp_gain, tmp_offset; //old-style free-form any slope/intercept combination // safety: not more than 30% of the mean measurement for offset training_data.at(iWindow).at(iNuc).at(iHP).GetSafeSlopeAndInterceptFit(tmp_gain, tmp_offset,0.3); gain_values.at(iWindow).at(iNuc).at(iHP) = tmp_gain; offset_values.at(iWindow).at(iNuc).at(iHP) = tmp_offset; // track what we would see with a simple model with offset last_good_gain = training_data.at(iWindow).at(iNuc).at(iHP).GetSlopeOnlyFitWithOffset(offset_zero); max_hp_calibrated = max(max_hp_calibrated, iHP); max_hps_calibrated.at(iNuc) = max(max_hps_calibrated.at(iNuc), iHP); //cout << gain_values.at(iWindow).at(iNuc).at(iHP) << ", "; } else { // Zero order interpolation if we don't have enough training data // extrapolate with the last good gain - effectively with near-zero intercept to be good gain_values.at(iWindow).at(iNuc).at(iHP) = last_good_gain; //cout << gain_values.at(iWindow).at(iNuc).at(iHP) << "(" << training_data.at(iWindow).at(iNuc).at(iHP).GetNSamples()<< "), "; // old-style requires explicit tables with extrapolation done beforehand } } } // Print maximum calibrated hp lengths by region, window, and nucleotide to log file. if (verbose) { if (iWindow == 0) cout << "LinearModelCalibration: Max HP calibrated, region " << region_idx; cout << "; window " << iWindow << ": " << max_hps_calibrated.at(0) << ion::FlowOrder::IntToNuc(0); for (unsigned int iNuc=1; iNuc < 4; ++iNuc) { cout << "," << max_hps_calibrated.at(iNuc) << ion::FlowOrder::IntToNuc(iNuc); } if (iWindow == training_data.size()-1) cout << endl; } } return max_hp_calibrated+1; // include a gain-only for extrapolation to work properly } // -------------------------------------------------------------------------- void LinCalModelRegion::CoefficientZeroOrderHold(int hold_hp) { int start_hp = hold_hp+1; for (unsigned int iWindow=0; iWindow < gain_values.size(); ++iWindow){ for (unsigned int iNuc=0; iNuc < gain_values.at(iWindow).size(); ++iNuc) { for (unsigned int iHP=start_hp; iHP < gain_values.at(iWindow).at(iNuc).size(); ++iHP) { offset_values.at(iWindow).at(iNuc).at(iHP) = offset_values.at(iWindow).at(iNuc).at(hold_hp); gain_values.at(iWindow).at(iNuc).at(iHP) = gain_values.at(iWindow).at(iNuc).at(hold_hp); } } } } // ========================================================================== // multiple constructors need a certain amount of common information void LinearCalibrationModel::Defaults(){ do_training_ = false; is_enabled_ = false; verbose_ = false; debug_ = false; output_training_stats_ = false; min_num_samples_ = 50; min_num_reads_ = 250; hp_threshold_ = 0; flow_window_size_ = 0; num_flow_windows_ = 0; num_flows_ = 0; min_state_inphase_ = 0.1; max_scaled_residual_ = 1.5; training_mode_ = 1; multi_weight_ = 10; multi_train_ = false; max_gain_shift_ = 0.1f; // really quite large! training_method_ = "common-offset"; max_hp_calibrated_ = MAX_HPXLEN; spam_debug_ = false; } // -------------------------------------------------------------------------- LinearCalibrationModel::LinearCalibrationModel() { Defaults(); } // -------------------------------------------------------------------------- // Constructor for use in BaseCaller - we do not deviate from generated model LinearCalibrationModel::LinearCalibrationModel(OptArgs& opts, vector<string> &bam_comments, const string & run_id, const ion::ChipSubset & chip_subset, const ion::FlowOrder * flow_order) { Defaults(); verbose_ = true; bool diagonal_state_prog = opts.GetFirstBoolean('-', "diagonal-state-prog", false); if (diagonal_state_prog) return; string legacy_file_name = opts.GetFirstString ('s', "model-file", ""); string calibration_file_name = opts.GetFirstString ('s', "calibration-json", ""); num_flows_ = flow_order->num_flows(); // Preferentially load json if both options are provided if (not calibration_file_name.empty()) { ifstream calibration_file(calibration_file_name.c_str(), ifstream::in); if (not calibration_file.good()){ cerr << "LinearCalibrationModel WARNING: Cannot open file " << calibration_file_name << endl; } else { Json::Value temp_calibraiton_file; calibration_file >> temp_calibraiton_file; if (temp_calibraiton_file.isMember("LinearModel")){ InitializeModelFromJson(temp_calibraiton_file["LinearModel"]); } else { cerr << "LinearCalibrationModel WARNING: Cannot find json member <LinearCalibrationModel>" << endl; } } calibration_file.close(); if (not is_enabled_) cerr << "LinearCalibrationModel WARNING: Unable to load calibration model from json file " << calibration_file_name << endl; } // Load HP model from file if provided and we don't have a json model if ((not is_enabled_) and (not legacy_file_name.empty())) { InitializeModelFromTxtFile(legacy_file_name, hp_threshold_); } if (not is_enabled_){ cout << "LinearCalibrationModel: Disabled." << endl; } else{ // TODO: Check chip parameters like offset and and size for consistency // If we use a calibration model we are going to write in into the BAM header to avoid model mismatches SaveModelFileToBamComments(bam_comments, run_id); } } // -------------------------------------------------------------------------- // Constructor for calibration module LinearCalibrationModel::LinearCalibrationModel(OptArgs& opts, const CalibrationContext& calib_context) : chip_subset_(calib_context.chip_subset) { Defaults(); max_hp_calibrated_ = 0; is_enabled_ = false; flow_window_size_ = calib_context.flow_window_size; num_flow_windows_ = (calib_context.max_num_flows + flow_window_size_ -1) / flow_window_size_; verbose_ = (calib_context.verbose_level > 0); debug_ = calib_context.debug; num_flows_ = calib_context.max_num_flows; training_method_ = opts.GetFirstString ('-', "model-training-style", "common-offset"); if (training_method_ == "common-offset") training_mode_ = 1; else if (training_method_ == "old-style") training_mode_ = 2; else { cerr << "HistogramCalibration ERROR: unknown training method " << training_method_ << endl; exit(EXIT_FAILURE); } min_num_samples_ = opts.GetFirstInt ('-', "model-calib-min-samples", min_num_samples_); do_training_ = opts.GetFirstBoolean('-', "model-calibration", true); hp_threshold_ = opts.GetFirstInt ('-', "model-calib-min-hp", hp_threshold_); min_state_inphase_ = opts.GetFirstDouble ('-', "model-calib-min-inphase", min_state_inphase_); max_scaled_residual_ = opts.GetFirstDouble ('-', "model-calib-max-residual", max_scaled_residual_); max_gain_shift_ = opts.GetFirstDouble ('-', "model-calib-max-gain-shift", max_gain_shift_); output_training_stats_= opts.GetFirstBoolean('-', "model-training-stats", output_training_stats_); multi_train_ = opts.GetFirstBoolean('-', "model-multi-train", multi_train_); multi_weight_ = opts.GetFirstInt ('-', "model-multi-weight", multi_weight_); spam_debug_ = opts.GetFirstBoolean('-', "model-spam-debug", spam_debug_); if (multi_train_){ min_num_samples_ *= multi_weight_; // increase weight to deal with increased weighting } // Size calibration structures region_data.resize(chip_subset_.NumRegions()); for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { //region_data.at(iRegion).Initialize(num_flow_windows_); // We don't need those until we create the model region_data.at(iRegion).InitializeTrainingData(num_flow_windows_); } if (do_training_ and (calib_context.verbose_level > 0)){ cout << "LinearCalibrationModel Training Options:" << endl; cout << " model-training-style : " << training_method_ << endl; cout << " model-calib-min-hp : " << hp_threshold_ << endl; cout << " model-calib-min-samples : " << min_num_samples_ << endl; cout << " model-calib-min-inphase : " << min_state_inphase_ << endl; cout << " model-calib-max-residual : " << max_scaled_residual_ << endl; cout << " model-calib-max-gain-shift : " << max_gain_shift_ << endl; cout << " model-multi-train : " << (multi_train_ ? "on" : "off") << endl; cout << " multi-weight : " << multi_weight_ << endl; cout << " model-training-stats : " << (output_training_stats_ ? "on" : "off") << endl; } } // -------------------------------------------------------------------------- const vector<vector<vector<float> > > * LinearCalibrationModel::getGains(int x, int y) const { if (not is_enabled_) return NULL; int my_region = chip_subset_.CoordinatesToRegionIdx(x, y); if (my_region < 0) { if (verbose_) cerr << "LinearCalibrationModel::getGains ERROR: Cannot find region for for well x=" << x << " y=" << y << endl; return NULL; } else return region_data.at(my_region).getGains(); }; // -------------------------------------------------------------------------- const vector<vector<vector<float> > > * LinearCalibrationModel::getOffsets(int x, int y) const { if (not is_enabled_) return NULL; int my_region = chip_subset_.CoordinatesToRegionIdx(x, y); if (my_region < 0) { if (verbose_) cerr << "LinearCalibrationModel::getGains ERROR: Cannot find region for for well x=" << x << " y=" << y << endl; return NULL; } else return region_data.at(my_region).getOffsets(); }; // -------------------------------------------------------------------------- void LinearCalibrationModel::getAB(MultiAB &multi_ab, int x, int y) const { if (not is_enabled_){ multi_ab.Null(); return; } int my_region = chip_subset_.CoordinatesToRegionIdx(x, y); if (my_region < 0){ if (verbose_) cerr << "LinearCalibrationModel::getGains ERROR: Cannot find region for for well x=" << x << " y=" << y << endl; multi_ab.Null(); } else { multi_ab.aPtr = region_data.at(my_region).getGains(); multi_ab.bPtr = region_data.at(my_region).getOffsets(); } }; // return local step size for adding/subtracting a base float LinearCalibrationModel::ReturnLocalInterval(float original_step, float local_prediction, float called_hp, float finish_hp, int my_region, int my_flow_window, int my_nuc_idx){ float local_interval = original_step; // only if we calibrated in the first place do we return a different value if (called_hp>=hp_threshold_){ float local_sign = finish_hp-called_hp; // find endpoints of interval float local_gain_start =region_data.at(my_region).gain_values.at(my_flow_window).at(my_nuc_idx).at(called_hp); float local_gain_finish = region_data.at(my_region).gain_values.at(my_flow_window).at(my_nuc_idx).at(finish_hp); float local_offset_start =region_data.at(my_region).offset_values.at(my_flow_window).at(my_nuc_idx).at(called_hp); float local_offset_finish = region_data.at(my_region).offset_values.at(my_flow_window).at(my_nuc_idx).at(finish_hp); // in the awful case of doubly calibrating // the interval needs to be modified to account for the linear calibration local_interval = original_step*local_gain_finish+ local_sign*(local_gain_finish-local_gain_start)*(local_prediction-local_offset_start)/local_gain_start + local_sign*(local_offset_finish-local_offset_start); } return(local_interval); } // -------------------------------------------------------------------------- // This function retains the original (rather wasteful) json structure that we put into bam headers void LinearCalibrationModel::ExportModelToJson(Json::Value &json, string run_id) const { if (not is_enabled_) return; // Add a (legacy) hash code to identify json objects corresponding to linear calibration models. // MD5 hash of "This uniquely identifies json comments for recalibration." json["MagicCode"] = "6d5b9d29ede5f176a4711d415d769108"; // Keep 5 character ID to not upset all the hard coded methods if (run_id.empty()) run_id = "NORID"; std::stringstream block_id_stream; block_id_stream << run_id << ".block_X" << chip_subset_.GetOffsetX() << "_Y" << chip_subset_.GetOffsetY(); string block_id = block_id_stream.str(); // Run global information json["MasterKey"] = block_id; json["MasterCol"] = (Json::UInt64)chip_subset_.GetColOffset(); json["MasterRow"] = (Json::UInt64)chip_subset_.GetRowOffset(); // Store information about how Calibration executable was run json["CalibrationParameters"]["model_training_style"] = (Json::UInt64)min_num_samples_; json["CalibrationParameters"]["model_calib_min_inphase"] = min_state_inphase_; json["CalibrationParameters"]["model_calib_max_residual"] = max_scaled_residual_; json["CalibrationParameters"]["model-calib-max-gain-shift"] = max_gain_shift_; json["CalibrationParameters"]["model-multi-train"] = multi_train_; json["CalibrationParameters"]["multi-weight"] = (Json::Int)multi_weight_; // Global block information -- CLOSED INTERVALS json[block_id]["flowStart"] = 0; json[block_id]["flowEnd"] = num_flows_ -1; json[block_id]["flowSpan"] = flow_window_size_; json[block_id]["xMin"] = chip_subset_.GetOffsetX(); json[block_id]["xMax"] = chip_subset_.GetOffsetX() + chip_subset_.GetChipSizeX() -1; json[block_id]["xSpan"] = chip_subset_.GetRegionSizeX(); json[block_id]["yMin"] = chip_subset_.GetOffsetY(); json[block_id]["yMax"] = chip_subset_.GetOffsetY() + chip_subset_.GetChipSizeY() -1; json[block_id]["ySpan"] = chip_subset_.GetRegionSizeY(); json[block_id]["max_hp_calibrated"] = max_hp_calibrated_+1; // The json value is exclusive json[block_id]["min_hp_calibrated"] = hp_threshold_; // Now write the information of the individual regions json[block_id]["modelParameters"] = Json::arrayValue; int start_x, start_y, start_flow, element_id = 0; for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion){ chip_subset_.GetRegionStart(iRegion, start_x, start_y); for (int iWindow=0; iWindow < num_flow_windows_; ++iWindow){ start_flow = iWindow * flow_window_size_; for (int iNuc = 0; iNuc < 4; ++iNuc){ // To be compatible with the legacy BAM format we write the char value into the json as an integer char base = ion::FlowOrder::IntToNuc(iNuc); for (int iHP=hp_threshold_; iHP<= max_hp_calibrated_; ++iHP) { json[block_id]["modelParameters"][element_id]["flowBase"] = (Json::Int)base; json[block_id]["modelParameters"][element_id]["flowStart"] = (Json::Int)start_flow; json[block_id]["modelParameters"][element_id]["flowEnd"] = (Json::Int)(start_flow + flow_window_size_ -1); json[block_id]["modelParameters"][element_id]["xMin"] = (Json::Int)start_x; json[block_id]["modelParameters"][element_id]["xMax"] = (Json::Int)min((start_x+chip_subset_.GetRegionSizeX()-1), (chip_subset_.GetOffsetX()+chip_subset_.GetChipSizeX()-1)); json[block_id]["modelParameters"][element_id]["yMin"] = (Json::Int)start_y; json[block_id]["modelParameters"][element_id]["yMax"] = (Json::Int)min((start_y+chip_subset_.GetRegionSizeY()-1), (chip_subset_.GetOffsetY()+chip_subset_.GetChipSizeY()-1)); json[block_id]["modelParameters"][element_id]["refHP"] = (Json::Int)iHP; // Here we assume that the model parameters are constant over one element json[block_id]["modelParameters"][element_id]["paramA"] = region_data.at(iRegion).gain_values.at(iWindow).at(iNuc).at(iHP); json[block_id]["modelParameters"][element_id]["paramB"] = region_data.at(iRegion).offset_values.at(iWindow).at(iNuc).at(iHP); // Optionally output training data if (output_training_stats_){ json[block_id]["modelParameters"][element_id]["TrainingData"] = region_data.at(iRegion).training_data.at(iWindow).at(iNuc).at(iHP).DataToJson(); } ++element_id; } } } } }; // -------------------------------------------------------------------------- void LinearCalibrationModel::SaveModelFileToBamComments(vector<string> &comments, const string &run_id) const { if (not is_enabled_) return; Json::Value json; ExportModelToJson(json, run_id); Json::FastWriter writer; string comment_str = writer.write(json); // trim unwanted newline added by writer int last_char = comment_str.size()-1; if ((last_char>=0) and (comment_str.at(last_char) == '\n')) { comment_str.erase(last_char,1); } comments.push_back(comment_str); } // -------------------------------------------------------------------------- // We only load data for HPs that are above a desired threshold // The internally stored data structures reflect that so that we put accurate // information about what we did into the BAM header bool LinearCalibrationModel::InitializeModelFromJson(Json::Value &json, const int num_flows) { is_enabled_ = false; if (num_flows > 0) num_flows_ = num_flows; // Check if we have a json object corresponding to a histogram calibration model. if ((not json.isMember("MagicCode")) or (json["MagicCode"].asString() != "6d5b9d29ede5f176a4711d415d769108")){ cerr << "LinearCalibrationModel::InitializeModelFromJson WARNING: Cannot find appropriate magic code." << endl; return false; } // Json structure uses -- CLOSED INTERVALS -- (mostly) // We now assume that the json is correctly formatted and skip checks string block_id = json["MasterKey"].asString(); int block_offset_x = json["MasterCol"].asInt(); int block_offset_y = json["MasterRow"].asInt(); // Check number of flows int num_flows_json = json[block_id]["flowEnd"].asInt() +1; if (num_flows_json != num_flows_){ cerr << "LinearCalibrationModel::InitializeModelFromJson WARNING: Number of flows in json " << num_flows_json << " does not match number of flows in run " << num_flows_ << endl; return false; } flow_window_size_ = json[block_id]["flowSpan"].asInt(); if (not (flow_window_size_ > 0)){ cerr << "LinearCalibrationModel::InitializeModelFromJson WARNING: Flow window is zero." << endl; return false; } num_flow_windows_ = (num_flows_ + flow_window_size_ -1) / flow_window_size_; // Load region information int block_size_x = json[block_id]["xMax"].asInt() - block_offset_x +1; int block_size_y = json[block_id]["yMax"].asInt() - block_offset_y +1; int region_size_x = json[block_id]["xSpan"].asInt(); int region_size_y = json[block_id]["ySpan"].asInt(); int num_regions_x = (block_size_x + region_size_x - 1) / region_size_x; int num_regions_y = (block_size_y + region_size_y - 1) / region_size_y; chip_subset_.InitializeCalibrationRegions(block_offset_x, block_offset_y, block_size_x, block_size_y, num_regions_x, num_regions_y); // Check number and range of elements int json_size = json[block_id]["modelParameters"].size(); max_hp_calibrated_ = json[block_id]["max_hp_calibrated"].asInt() -1; // The json value is exclusive // The purpose of this block is to prevent double calibration in TVC when loading the headers from <TS5.0 BAM files int min_hp = 4; // Hard coded to legacy default; no need to ever change that. if (json[block_id].isMember("min_hp_calibrated")) min_hp = json[block_id]["min_hp_calibrated"].asInt(); // BAM files created before TS 5.0 will not have this json entry hp_threshold_ = max(hp_threshold_, min_hp); // This will avoid doubly calibrating old BAM files in TVC // new json file have min_hp_calibrated=0 and so can be doubly calibrated if we've trained that way // Iterate over model parameters in json and fill in class data region_data.resize(chip_subset_.NumRegions()); for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { region_data.at(iRegion).Initialize(num_flow_windows_); } int xMin, yMin, my_region, my_flow_window, nuc_idx, my_hp; for (int i_item=0; i_item<json_size; i_item++) { // We only load calibration data for HPs above the threshold and keep the parameters of the others at default my_hp = json[block_id]["modelParameters"][i_item]["refHP"].asInt(); if ((my_hp < hp_threshold_) or (my_hp > MAX_HPXLEN)) continue; xMin = json[block_id]["modelParameters"][i_item]["xMin"].asInt(); yMin = json[block_id]["modelParameters"][i_item]["yMin"].asInt(); my_region = chip_subset_.CoordinatesToRegionIdx(xMin, yMin); if (my_region < 0){ cerr << "LinearCalibrationModel::InitializeModelFromJson WARNING: Cannot resolve region for coordinates x=" << xMin << " y=" << yMin << endl; return false; } my_flow_window = json[block_id]["modelParameters"][i_item]["flowStart"].asInt() / flow_window_size_; char base = (char)json[block_id]["modelParameters"][i_item]["flowBase"].asInt(); nuc_idx = ion::FlowOrder::NucToInt(base); region_data.at(my_region).gain_values.at(my_flow_window).at(nuc_idx).at(my_hp) = json[block_id]["modelParameters"][i_item]["paramA"].asFloat(); region_data.at(my_region).offset_values.at(my_flow_window).at(nuc_idx).at(my_hp) = json[block_id]["modelParameters"][i_item]["paramB"].asFloat(); } // Now that we have calibration data we build the class output data structures for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { region_data.at(iRegion).CoefficientZeroOrderHold(max_hp_calibrated_); region_data.at(iRegion).SetModelGainsAndOffsets(num_flows_, flow_window_size_); } if (verbose_) cout << "LinearCalibrationModel: enabled for HPs >=" << hp_threshold_ << " (using block id " << block_id << ") in a " << chip_subset_.GetNumRegionsX() << 'x' << chip_subset_.GetNumRegionsY() << 'x' << num_flow_windows_ << " grid." <<endl << endl; //PrintModelParameters(); is_enabled_ = true; return true; }; void LinearCalibrationModel::SetModelGainsAndOffsets(){ for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { region_data.at(iRegion).SetModelGainsAndOffsets(num_flows_, flow_window_size_); } } // -------------------------------------------------------------------------- bool LinearCalibrationModel::InitializeModelFromTxtFile(string model_file_name, int hp_threshold, const int num_flows) { is_enabled_ = false; if (num_flows > 0) num_flows_ = num_flows; ifstream calibration_file; calibration_file.open(model_file_name.c_str()); if (not calibration_file.good()) { cerr << "LinearCalibrationModel WARNING: Cannot open legacy model in file " << model_file_name << endl; calibration_file.close(); return false; } string comment_line; getline(calibration_file, comment_line); // Read global block info from header line int flowStart, flowEnd, flowSpan, xMin, xMax, xSpan, yMin, yMax, ySpan, max_hp_calibrated; calibration_file >> flowStart >> flowEnd >> flowSpan >> xMin >> xMax >> xSpan >> yMin >> yMax >> ySpan >> max_hp_calibrated; // Check number of flows int num_flows_json = flowEnd+1; if (num_flows_json != num_flows_){ cerr << "LinearCalibrationModel::InitializeModelFromTxtFile WARNING: Number of flows in file " << num_flows_json << " does not match number of flows in run " << num_flows_ << endl; calibration_file.close(); return false; } flow_window_size_ = flowSpan; num_flow_windows_ = (flowEnd + flow_window_size_) / flow_window_size_; // Load region information int block_size_x = xMax-xMin+1; int block_size_y = yMax-yMin+1; int num_regions_x = (block_size_x + xSpan - 1) / xSpan; int num_regions_y = (block_size_y + ySpan - 1) / ySpan; chip_subset_.InitializeCalibrationRegions(xMin, yMin, block_size_x, block_size_y, num_regions_x, num_regions_y); // Initialize region data and set defaults region_data.resize(chip_subset_.NumRegions()); for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { region_data.at(iRegion).Initialize(num_flow_windows_); } // Read lines of text file - one line per parameter pair float paramA, paramB; int my_region, my_flow_window, nuc_idx, my_hp; char flowBase; while (calibration_file.good()) { calibration_file >> flowBase >> flowStart >> flowEnd >> xMin >> xMax >> yMin >> yMax >> my_hp >> paramA >> paramB; if ((my_hp < hp_threshold) or (my_hp > MAX_HPXLEN)) continue; my_region = chip_subset_.CoordinatesToRegionIdx(xMin, yMin); if (my_region < 0){ cerr << "LinearCalibrationModel::InitializeModelFromTxtFile WARNING: Cannot resolve region for coordinates x=" << xMin << " y=" << yMin << endl; calibration_file.close(); return false; } my_flow_window = flowStart / flow_window_size_; nuc_idx = ion::FlowOrder::NucToInt(flowBase); region_data.at(my_region).gain_values.at(my_flow_window).at(nuc_idx).at(my_hp) = paramA; region_data.at(my_region).offset_values.at(my_flow_window).at(nuc_idx).at(my_hp) = paramB; } calibration_file.close(); // Now that we have calibration data we build the class output data structures for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { region_data.at(iRegion).SetModelGainsAndOffsets(num_flows_, flow_window_size_); } if (verbose_) cout << "LinearCalibrationModel: enabled for HPs >=" << hp_threshold << " (from text file " << model_file_name << ") in a " << chip_subset_.GetNumRegionsX() << 'x' << chip_subset_.GetNumRegionsY() << 'x' << num_flow_windows_ << " grid." <<endl << endl; is_enabled_ = true; return is_enabled_; } // -------------------------------------------------------------------------- void LinearCalibrationModel::CleanSlate() { for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { region_data.at(iRegion).InitializeTrainingData(num_flow_windows_); } } // -------------------------------------------------------------------------- void LinearCalibrationModel::AccumulateTrainingData(const LinearCalibrationModel& other) { if (not do_training_) return; for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { region_data.at(iRegion).AccumulateTrainingData(other.region_data.at(iRegion)); } } // -------------------------------------------------------------------------- // direct copy to update the model XXX void LinearCalibrationModel::CopyTrainingData(const LinearCalibrationModel &other){ if (not do_training_) return; region_data = other.region_data; } // -------------------------------------------------------------------------- bool LinearCalibrationModel::FilterTrainingReads(const ReadAlignmentInfo& read_alignment, LinearCalibrationModel &linear_model_cal_sim, int my_region, int iHP, float &yobs, float &xobs, int &governing_hp){ bool res_train = true; int my_flow_idx = read_alignment.align_flow_index.at(iHP); int my_flow_window = my_flow_idx / flow_window_size_; int my_nuc_idx = ion::FlowOrder::NucToInt(read_alignment.aln_flow_order.at(iHP)); float local_interval = read_alignment.state_inphase.at(my_flow_idx); float local_measurement = read_alignment.measurements.at(my_flow_idx); float local_prediction = read_alignment.predictions_ref.at(my_flow_idx); // should be 'as-simulated with model int original_hp = read_alignment.aligned_tHPs.at(iHP); // original prediction int finish_hp = (local_measurement-local_prediction)>0.0f ? min(MAX_HPXLEN,(original_hp+1)): max(0,(original_hp-1)); // one-liner version if (linear_model_cal_sim.is_enabled()) linear_model_cal_sim.ReturnLocalInterval(local_interval, local_prediction, original_hp, finish_hp, my_region, my_flow_window, my_nuc_idx); // Reject outlier measurements if (local_interval < min_state_inphase_){ if (debug_) cout << "Ignoring HP " << iHP << ": state_inphase too small " << local_interval << endl; res_train=false; } float residual_predictor = fabs(local_measurement - local_prediction) / local_interval; if (residual_predictor > max_scaled_residual_) { if (debug_) cout << "Ignoring HP " << iHP << ": residual too high " << residual_predictor << endl; res_train =false; } // And finally add the data point to the training set yobs = local_measurement; // this must be the predictions without applying the linear model // for the governing_hp xobs = local_prediction; governing_hp = min(original_hp, MAX_HPXLEN); if ((governing_hp>4) and spam_debug_){ int called_hp=read_alignment.aligned_qHPs.at(iHP); // called float cal_prediction = read_alignment.predictions_as_called.at(my_flow_idx); float alt_residual_predictor = fabs(local_measurement-cal_prediction)/local_interval; stringstream my_diagnostic; my_diagnostic << "TAXES:\t" << governing_hp << "\t" << original_hp <<"\t" << finish_hp << "\t" << called_hp <<"\t" << "V:\t" << local_prediction << "\t" << cal_prediction <<"\t" << local_measurement << "\t" << "P:\t" << residual_predictor << "\t" << alt_residual_predictor << "\t" << "I:\t" << local_interval << "\t" << (res_train?1:0) <<endl; cout << my_diagnostic.str(); } return(res_train); } // -------------------------------------------------------------------------- bool LinearCalibrationModel::AddTrainingRead(const ReadAlignmentInfo& read_alignment, LinearCalibrationModel &linear_model_cal_sim) { if (read_alignment.is_filtered or (not do_training_)) return false; int my_nuc_idx, my_flow_idx, my_flow_window; double residual_predictor; int my_region = chip_subset_.CoordinatesToRegionIdx(read_alignment.well_xy.at(0), read_alignment.well_xy.at(1)); if (my_region < 0){ if (debug_) cout << "Ignoring read " << read_alignment.alignment->Name << ": coordinates of bounds; region idx " << my_region << endl; return false; } // a little uncertain about too much training per one read region_data.at(my_region).FreshReadData(); // Step through flow alignment and extract info for (unsigned int iHP=0; iHP < read_alignment.pretty_flow_align.size(); ++iHP){ // Ignore Flow InDels if (IsInDelAlignSymbol(read_alignment.pretty_flow_align.at(iHP))) { if (debug_) cout << "Ignoring HP " << iHP << ": Flow alignment symbol is InDel." << endl; continue; } // Ignore HPs that are too large if (read_alignment.aligned_tHPs.at(iHP) > MAX_HPXLEN) { if (debug_) cout << "Ignoring HP " << iHP << ": HP size out of bounds, " << read_alignment.aligned_tHPs.at(iHP) << endl; continue; } my_nuc_idx = ion::FlowOrder::NucToInt(read_alignment.aln_flow_order.at(iHP)); if (my_nuc_idx < 0){ if (debug_) cout << "Ignoring HP " << iHP << ": nuc idx out of bounds, " << my_nuc_idx << endl; continue; } my_flow_idx = read_alignment.align_flow_index.at(iHP); my_flow_window = my_flow_idx / flow_window_size_; float xobs,yobs; int governing_hp; bool res_train = FilterTrainingReads(read_alignment,linear_model_cal_sim, my_region, iHP, yobs, xobs, governing_hp); if (res_train){ region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, governing_hp, xobs, yobs); // integer values because of weighting methodology if (multi_train_){ int false_hp = max(governing_hp-1,0); region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, false_hp, xobs, yobs); false_hp = min(governing_hp+1,MAX_HPXLEN); region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, false_hp, xobs, yobs); // pseudo-weight for (int xxi=0; xxi<multi_weight_; xxi++){ region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, governing_hp, xobs, yobs); } } } } return true; } bool LinearCalibrationModel::FilterBlindReads(const ReadAlignmentInfo& read_alignment, LinearCalibrationModel &linear_model_cal_sim, int my_region, int iHP, float &yobs, float &xobs, int &governing_hp){ // at the main flow for iHP // filter out data points by 'recalling' the read // conditional on the current calibration model bool res_train = true; int my_flow_idx = read_alignment.align_flow_index.at(iHP); int my_flow_window = my_flow_idx / flow_window_size_; int my_nuc_idx = ion::FlowOrder::NucToInt(read_alignment.aln_flow_order.at(iHP)); float local_measurement = read_alignment.measurements.at(my_flow_idx); // now the basecaller logic float original_interval = read_alignment.state_inphase.at(my_flow_idx); // when first we basecalled, we came as close as possible given that we had no calibration model float original_prediction = read_alignment.predictions_ref.at(my_flow_idx); int original_hp = read_alignment.aligned_qHPs.at(iHP); // original prediction // Reject measurement if the interval is too narrow to be trusted if (original_interval < min_state_inphase_){ if (debug_) cout << "Ignoring HP " << iHP << ": state_inphase too small " << original_interval << endl; return(false); // do not use me at all } float original_predictor = fabs(local_measurement-original_prediction)/original_interval; // reject measurement if there was too much interference from other flows leading the basecaller to put the call somewhere strange if (original_predictor > max_scaled_residual_) { res_train=false; } // Now we need to generate the correct >call< given that we know calibration is happening for high HPs, so the original prediction is wrong float cal_prediction = read_alignment.predictions_as_called.at(my_flow_idx); // int finish_hp = (local_measurement-cal_prediction)>0.0f ? min(MAX_HPXLEN,(original_hp+1)): max(0,(original_hp-1)); // one-liner version float local_interval=original_interval; // how large is the step size if (linear_model_cal_sim.is_enabled()) linear_model_cal_sim.ReturnLocalInterval(local_interval, cal_prediction, original_hp, finish_hp, my_region, my_flow_window, my_nuc_idx); int ref_hp = original_hp; float ref_prediction=original_prediction; float alt_prediction = cal_prediction; float alt_residual_predictor = fabs(local_measurement-alt_prediction)/local_interval; float final_residual_predictor = alt_residual_predictor; float ref_residual_predictor = 1.0f; float finish_prediction=alt_prediction; // possibility to improve fit-to-data by changing call if (alt_residual_predictor>0.5){ // if we take a step towards the data we may improve the fit ref_hp = finish_hp; // we take one step towards reclassified values float ref_predict_delta = (finish_hp-original_hp)*original_interval; // delta >for this flow< in predictions without model shift ref_prediction = original_prediction+ref_predict_delta; // update prediction float call_predict_delta = (finish_hp-original_hp)*local_interval; // prediction after change alt_prediction = cal_prediction+call_predict_delta; finish_prediction=alt_prediction; ref_residual_predictor = fabs(alt_prediction-original_prediction)/original_interval; if (ref_residual_predictor>1.5){ // reject step: if the basecaller could have done this it would have originally ref_hp = original_hp; ref_prediction = original_prediction; alt_prediction = cal_prediction; } final_residual_predictor = fabs(local_measurement-alt_prediction)/local_interval; } // need to be finally close to the data // to have confidence we are not 'leaking' float dynamic_threshold=min(0.5f,2.0f/(original_hp+ref_hp+0.5f)); // higher HPs have more overlap, need careful attention dynamic_threshold = 0.5f; if (final_residual_predictor>dynamic_threshold){ res_train=false; } // transfer data out xobs=ref_prediction; yobs=local_measurement; governing_hp = ref_hp; if ((governing_hp>4) and spam_debug_){ stringstream my_diagnostic; my_diagnostic << "TAXES:\t" << governing_hp << "\t" << original_hp <<"\t" << finish_hp << "\t" << "V:\t" << original_prediction<< "\t" << cal_prediction <<"\t" << finish_prediction <<"\t" << alt_prediction << "\t" << local_measurement << "\t" << "P:\t" << original_predictor << "\t" << alt_residual_predictor << "\t" << ref_residual_predictor << "\t" << final_residual_predictor << "\t" << "I:\t" << original_interval <<"\t" << local_interval << "\t" << (res_train?1:0) <<endl; cout << my_diagnostic.str(); } return(res_train); } bool LinearCalibrationModel::FilterBlindReadsOld(const ReadAlignmentInfo& read_alignment, LinearCalibrationModel &linear_model_cal_sim, int my_region, int iHP, float &yobs, float &xobs, int &governing_hp){ bool res_train = true; int my_flow_idx = read_alignment.align_flow_index.at(iHP); int my_flow_window = my_flow_idx / flow_window_size_; int my_nuc_idx = ion::FlowOrder::NucToInt(read_alignment.aln_flow_order.at(iHP)); float local_interval = read_alignment.state_inphase.at(my_flow_idx); float local_measured = read_alignment.measurements.at(my_flow_idx); float local_prediction = read_alignment.predictions_as_called.at(my_flow_idx); // should be 'as-simulated with model int called_hp = read_alignment.aligned_qHPs.at(iHP); // original prediction int finish_hp = (local_measured-local_prediction)>0.0f ? min(MAX_HPXLEN,(called_hp+1)): max(0,(called_hp-1)); // one-liner version if (linear_model_cal_sim.is_enabled()) linear_model_cal_sim.ReturnLocalInterval(local_interval, local_prediction, called_hp, finish_hp, my_region, my_flow_window, my_nuc_idx); // Reject outlier measurements if (local_interval < min_state_inphase_){ if (debug_) cout << "Ignoring HP " << iHP << ": state_inphase too small " << local_interval << endl; res_train=false; } float residual_predictor = fabs(local_measured - local_prediction) / local_interval; float alt_residual_predictor = residual_predictor; // too large a step: only allow to correct by one from the original called, // 1.25-1 = 0.25 meaning we're almost certainly correct in classification // because we're blind, we need a narrower range of success if (residual_predictor > max_scaled_residual_) { if (debug_) cout << "Ignoring HP " << iHP << ": residual too high " << residual_predictor << endl; res_train=false; } // update the model // what base am I really, and how should it have been predicted? float ref_predict_delta = 0.0f; float call_predict_delta = 0.0f; int ref_hp = called_hp; if (residual_predictor>0.5f){ // adjust predictions and 'reference' ref_hp = finish_hp; // we take one step towards reclassified values ref_predict_delta = (finish_hp-called_hp)*read_alignment.state_inphase.at(my_flow_idx); // delta >for this flow< in predictions without model shift float step_delta = local_prediction-read_alignment.predictions_ref.at(my_flow_idx); // if positive, local predictions have been bumped up call_predict_delta = (finish_hp-called_hp)*local_interval; // prediction after change alt_residual_predictor = fabs(local_measured-(local_prediction+call_predict_delta))/local_interval; // if we're correcting the data, it had better be in the correct direction for the current model // the effect is to shift the interval of 'good calls' in the direction we want if (step_delta*ref_predict_delta>0){ ref_hp = called_hp; ref_predict_delta = 0.0f; // only if we go in the opposite direction do we change the call res_train = false; } } if (alt_residual_predictor>0.5) // train only on central tendency of data where our probability of being correct is highest res_train = false; yobs = read_alignment.measurements.at(my_flow_idx); // this must be the predictions without applying the linear model // for the governing_hp xobs = read_alignment.predictions_ref.at(my_flow_idx)+ref_predict_delta; // assume hps are rare, don't affect neighbors too much governing_hp = ref_hp; // blinded return(res_train); } bool LinearCalibrationModel::AddBlindTrainingRead(const ReadAlignmentInfo& read_alignment, LinearCalibrationModel &linear_model_cal_sim) { if (read_alignment.is_filtered or (not do_training_)) return false; int my_nuc_idx, my_flow_idx, my_flow_window; double residual_predictor; double alt_residual_predictor; int my_region = chip_subset_.CoordinatesToRegionIdx(read_alignment.well_xy.at(0), read_alignment.well_xy.at(1)); if (my_region < 0){ if (debug_) cout << "Ignoring read " << read_alignment.alignment->Name << ": coordinates of bounds; region idx " << my_region << endl; return false; } // a little uncertain about too much training per one read // data points now added note a fresh read is coming region_data.at(my_region).FreshReadData(); // Step through flow alignment and extract info for (unsigned int iHP=0; iHP < read_alignment.pretty_flow_align.size(); ++iHP){ // Ignore Flow InDels if (IsInDelAlignSymbol(read_alignment.pretty_flow_align.at(iHP))) { if (debug_) cout << "Ignoring HP " << iHP << ": Flow alignment symbol is InDel." << endl; continue; } // Ignore HPs that are too large if (read_alignment.aligned_tHPs.at(iHP) > MAX_HPXLEN) { if (debug_) cout << "Ignoring HP " << iHP << ": HP size out of bounds, " << read_alignment.aligned_tHPs.at(iHP) << endl; continue; } my_nuc_idx = ion::FlowOrder::NucToInt(read_alignment.aln_flow_order.at(iHP)); if (my_nuc_idx < 0){ if (debug_) cout << "Ignoring HP " << iHP << ": nuc idx out of bounds, " << my_nuc_idx << endl; continue; } my_flow_idx = read_alignment.align_flow_index.at(iHP); my_flow_window = my_flow_idx / flow_window_size_; float xobs, yobs; int governing_hp=0; // complex like the tax code: find what the basecaller would have called, if it knew the current calibration model // you cannot use Form BaseCallerEZ bool res_train = FilterBlindReads(read_alignment,linear_model_cal_sim, my_region, iHP, yobs, xobs, governing_hp); // now finally train int my_hp; // 'able to predict next 2 slots adequately' - my_hp = max(0,governing_hp-1); // only unlock training when we have enough training data - 'accurate calls' // data coming from >separate reads<, not just from one read // 0,1,2 assumed generally accurate without training if ((linear_model_cal_sim.region_data.at(my_region).training_data.at(my_flow_window).at(my_nuc_idx).at(my_hp).NumReads() < min_num_reads_) and my_hp>2) // allow training only when enough found res_train=false; if (res_train){ region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, governing_hp, xobs, yobs); // integer values because of weighting methodology if (multi_train_){ int false_hp = max(governing_hp-1,0); region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, false_hp, xobs, yobs); false_hp = min(governing_hp+1,MAX_HPXLEN); region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, false_hp, xobs, yobs); // pseudo-weight for (int xxi=0; xxi<multi_weight_; xxi++){ region_data.at(my_region).AddDataPoint(my_flow_window, my_nuc_idx, governing_hp, xobs, yobs); } } } } return true; } // -------------------------------------------------------------------------- bool LinearCalibrationModel::CreateCalibrationModel(bool verbose) { if (not do_training_) return false; max_hp_calibrated_ = 0; for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { if (training_mode_==1) max_hp_calibrated_ = max(max_hp_calibrated_, region_data.at(iRegion).CreateCalibrationModel(iRegion, min_num_samples_, max_gain_shift_, verbose)); if (training_mode_==2) max_hp_calibrated_ = max(max_hp_calibrated_, region_data.at(iRegion).CreateOldStyleCalibrationModel(iRegion, min_num_samples_, verbose)); } is_enabled_ = true; //PrintModelParameters(); return is_enabled_; } // -------------------------------------------------------------------------- void LinearCalibrationModel::PrintModelParameters() { cout << "Calibration model parameters: min_hp=" << hp_threshold_ << " max_hp_calibrated=" << max_hp_calibrated_ << endl; for (int iRegion=0; iRegion<chip_subset_.NumRegions(); ++iRegion) { cout << "Calibration Model for region " << iRegion; // Iterate over atomic elements for (unsigned int iWindow=0; iWindow < region_data.at(iRegion).gain_values.size(); ++iWindow) { cout << " flow window " << iWindow; for (unsigned int iNuc=0; iNuc < 4; ++iNuc) { cout << "Nucleotide " << ion::FlowOrder::IntToNuc(iNuc) << endl; cout << "-- Offset: "; for (int iHP=0; iHP <= MAX_HPXLEN; ++iHP) cout << region_data.at(iRegion).offset_values.at(iWindow).at(iNuc).at(iHP) << " "; cout << endl; cout << "-- Gains : "; for (int iHP=0; iHP <= MAX_HPXLEN; ++iHP) cout << region_data.at(iRegion).gain_values.at(iWindow).at(iNuc).at(iHP) << " "; cout << endl; cout << "-- Samples : "; for (int iHP=0; iHP <= MAX_HPXLEN; ++iHP) cout << region_data.at(iRegion).training_data.at(iWindow).at(iNuc).at(iHP).NumSamples() << " "; cout << endl; } } } }
41.355674
196
0.656194
ec3f65192e715686735d0cc87c5ef7837a149342
6,837
cpp
C++
SimSpark/rcssserver3d/plugin/soccer/gamestateaspect/gamestateitem.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/gamestateaspect/gamestateitem.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
SimSpark/rcssserver3d/plugin/soccer/gamestateaspect/gamestateitem.cpp
IllyasvielEin/Robocup3dInstaller
12e91d9372dd08a92feebf98e916c98bc2242ff4
[ "MIT" ]
null
null
null
/* -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ 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; version 2 of the License. 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "gamestateitem.h" #include "gamestateaspect.h" #include <soccerbase/soccerbase.h> using namespace oxygen; using namespace std; GameStateItem::GameStateItem() : MonitorItem() { ResetSentFlags(); } GameStateItem::~GameStateItem() { } void GameStateItem::ResetSentFlags() { mSentLeftTeamname = false; mSentRightTeamname = false; mLastHalf = GH_NONE; mLastLeftScore = -1; mLastRightScore = -1; mLastPlayMode = PM_NONE; mSentFlags = false; } void GameStateItem::PutFloatParam(const string& name, PredicateList& pList) { float value; if (! SoccerBase::GetSoccerVar(*this,name,value)) { return; } Predicate& pred = pList.AddPredicate(); pred.name = name; pred.parameter.AddValue(value); } void GameStateItem::GetInitialPredicates(PredicateList& pList) { ResetSentFlags(); // field geometry parameter PutFloatParam("FieldLength",pList); PutFloatParam("FieldWidth",pList); PutFloatParam("FieldHeight",pList); PutFloatParam("GoalWidth",pList); PutFloatParam("GoalDepth",pList); PutFloatParam("GoalHeight",pList); PutFloatParam("BorderSize",pList); PutFloatParam("FreeKickDistance",pList); PutFloatParam("WaitBeforeKickOff",pList); // agent parameter // PutFloatParam("AgentMass",pList); PutFloatParam("AgentRadius",pList); // PutFloatParam("AgentMaxSpeed",pList); // ball parameter PutFloatParam("BallRadius",pList); PutFloatParam("BallMass",pList); // soccer rule parameters PutFloatParam("RuleGoalPauseTime",pList); PutFloatParam("RuleKickInPauseTime",pList); PutFloatParam("RuleHalfTime",pList); PutFloatParam("PassModeMinOppBallDist",pList); PutFloatParam("PassModeDuration",pList); // play modes Predicate& pred = pList.AddPredicate(); pred.name = "play_modes"; for (int i=0; i<PM_NONE; ++i) { pred.parameter.AddValue (SoccerBase::PlayMode2Str(static_cast<TPlayMode>(i))); } GetPredicates(pList); } void GameStateItem::GetPredicates(PredicateList& pList) { if (mGameState.get() == 0) { return; } Predicate& timePred = pList.AddPredicate(); timePred.name = "time"; timePred.parameter.AddValue(mGameState->GetTime()); if (! mSentLeftTeamname) { // team names string name = mGameState->GetTeamName(TI_LEFT); if (! name.empty()) { Predicate& teamPredLeft = pList.AddPredicate(); teamPredLeft.name = "team_left"; teamPredLeft.parameter.AddValue(name); mSentLeftTeamname = true; } } if (! mSentRightTeamname) { // team names string name = mGameState->GetTeamName(TI_RIGHT); if (! name.empty()) { Predicate& teamPredRight = pList.AddPredicate(); teamPredRight.name = "team_right"; teamPredRight.parameter.AddValue(name); mSentRightTeamname = true; } } // game half TGameHalf half = mGameState->GetGameHalf(); if (half != mLastHalf) { mLastHalf = half; Predicate& halfPred = pList.AddPredicate(); halfPred.name = "half"; halfPred.parameter.AddValue(static_cast<int>(half)); } // scores int left_score = mGameState->GetScore(TI_LEFT); if (left_score != mLastLeftScore) { mLastLeftScore = left_score; Predicate& scoreLeftPred = pList.AddPredicate(); scoreLeftPred.name = "score_left"; scoreLeftPred.parameter.AddValue(left_score); } int right_score = mGameState->GetScore(TI_RIGHT); if (right_score != mLastRightScore) { mLastRightScore = right_score; Predicate& scoreRightPred = pList.AddPredicate(); scoreRightPred.name = "score_right"; scoreRightPred.parameter.AddValue(right_score); } // gamestate TPlayMode play_mode = mGameState->GetPlayMode(); if (play_mode != mLastPlayMode) { mLastPlayMode = play_mode; Predicate& modePred = pList.AddPredicate(); modePred.name = "play_mode"; modePred.parameter.AddValue(static_cast<int>(play_mode)); } //pass mode score wait time left team if (mGameState->GetPlayMode() == PM_PlayOn && mGameState->GetTime()-mGameState->GetLastTimeInPassMode(TI_LEFT) < mPassModeScoreWaitTime && !mGameState->GetPassModeClearedToScore(TI_LEFT)) { float wait_time = mPassModeScoreWaitTime - (mGameState->GetTime()-mGameState->GetLastTimeInPassMode(TI_LEFT)); Predicate& passModeScoreWaitLeftPred = pList.AddPredicate(); passModeScoreWaitLeftPred.name = "pass_mode_score_wait_left"; passModeScoreWaitLeftPred.parameter.AddValue(wait_time); } //pass mode score wait time right team if (mGameState->GetPlayMode() == PM_PlayOn && mGameState->GetTime()-mGameState->GetLastTimeInPassMode(TI_RIGHT) < mPassModeScoreWaitTime && !mGameState->GetPassModeClearedToScore(TI_RIGHT)) { float wait_time = mPassModeScoreWaitTime - (mGameState->GetTime()-mGameState->GetLastTimeInPassMode(TI_RIGHT)); Predicate& passModeScoreWaitRightPred = pList.AddPredicate(); passModeScoreWaitRightPred.name = "pass_mode_score_wait_right"; passModeScoreWaitRightPred.parameter.AddValue(wait_time); } } void GameStateItem::OnLink() { SoccerBase::GetGameState(*this,mGameState); mPassModeScoreWaitTime = 10.0; SoccerBase::GetSoccerVar(*this,"PassModeScoreWaitTime",mPassModeScoreWaitTime); } void GameStateItem::OnUnlink() { mGameState.reset(); }
31.506912
124
0.64853
ec411e41e5e7f00fd5988a99752d7abb2b69a426
4,490
cpp
C++
3DShootingGame/Framework/Physics/Rigidbody.cpp
ydeagames/3DShootingGame
f93e15179452810bd55fbfcedb6c162698296ec4
[ "MIT" ]
2
2020-03-30T05:11:51.000Z
2022-01-30T09:04:40.000Z
3DShootingGame/Framework/Physics/Rigidbody.cpp
ydeagames/3DShootingGame
f93e15179452810bd55fbfcedb6c162698296ec4
[ "MIT" ]
null
null
null
3DShootingGame/Framework/Physics/Rigidbody.cpp
ydeagames/3DShootingGame
f93e15179452810bd55fbfcedb6c162698296ec4
[ "MIT" ]
2
2020-03-30T05:11:52.000Z
2020-10-28T02:06:35.000Z
// Copyright (c) 2019-2020 ydeagames // Released under the MIT license // https://github.com/ydeagames/3DShootingGame/blob/master/LICENSE // // Author: ${ydeagames} // Created: 2019-07-22 06:12:28 +0900 // Modified: 2020-01-17 11:44:41 +0900 #include "pch.h" #include "Rigidbody.h" #include "Collidable.h" #include <Framework/ECS/GameContext.h> #include <Framework/ECS/GameObject.h> #include <Framework/ECS/Scene.h> #include <Framework/Context/SceneManager.h> #include <Framework/PhysX/PhysXManager.h> #include <Framework/PhysX/PhysXScene.h> #include <Framework/Tags/Tags.h> void Rigidbody::Start() { gameObject.FindGameObjectWithTag<Tag::PhysXSceneTag>().ifPresent([&](GameObject& obj) { if (obj.HasComponent<PhysXScene>()) { auto& manager = GameContext::Get<PhysXManager>(); auto trans = physx::PxTransform(physx::toPhysX(gameObject.GetComponent<Transform>().position), physx::toPhysX(gameObject.GetComponent<Transform>().rotation)); if (gameObject.GetComponent<Transform>().isStatic) rigid = manager.GetPhysics()->createRigidStatic(trans); else { auto dynamic = manager.GetPhysics()->createRigidDynamic(trans); dynamic->setRigidBodyFlags(lockFlags); rigid = dynamic; } auto& reg = *gameObject.registry; auto& e = gameObject.entity; std::vector<entt::entity> src; auto rec0 = [&](auto& e, auto& rec) mutable -> void { src.push_back(e); reg.view<Transform>().each([&](auto entity, Transform& component) { if (component.parent == e) rec(entity, rec); }); }; rec0(e, rec0); Collidable::AddCollider(reg, src, std::forward<physx::PxRigidActor>(*rigid)); obj.GetComponent<PhysXScene>().CreateObject(*rigid); if (rigid && rigid->is<physx::PxRigidBody>()) { auto dynamic = rigid->is<physx::PxRigidBody>(); dynamic->setLinearVelocity(preVelocity); dynamic->addForce(preForce); } } }); } void Rigidbody::Update() { if (rigid) { auto trans = rigid->getGlobalPose(); gameObject.GetComponent<Transform>().position = physx::fromPhysX(trans.p); gameObject.GetComponent<Transform>().rotation = physx::fromPhysX(trans.q); } } void Rigidbody::OnDestroy() { if (rigid) { auto scene = rigid->getScene(); if (scene) scene->removeActor(*rigid); px_release(rigid); } } void Rigidbody::AddForce(const DirectX::SimpleMath::Vector3& force) { preForce = physx::toPhysX(force); if (rigid && rigid->is<physx::PxRigidBody>()) rigid->is<physx::PxRigidBody>()->addForce(physx::toPhysX(force)); } void Rigidbody::SetVelocity(const DirectX::SimpleMath::Vector3& velocity) { preVelocity = physx::toPhysX(velocity); if (rigid && rigid->is<physx::PxRigidBody>()) rigid->is<physx::PxRigidBody>()->setLinearVelocity(physx::toPhysX(velocity)); } DirectX::SimpleMath::Vector3 Rigidbody::GetVelocity() const { if (rigid && rigid->is<physx::PxRigidBody>()) return physx::fromPhysX(rigid->is<physx::PxRigidBody>()->getLinearVelocity()); return DirectX::SimpleMath::Vector3(); } Transform& Rigidbody::Fetch() { auto& t = gameObject.GetComponent<Transform>(); if (rigid) { auto trans = rigid->getGlobalPose(); t.position = physx::fromPhysX(trans.p); t.rotation = physx::fromPhysX(trans.q); } return t; } void Rigidbody::Apply() { if (rigid) { auto& t = gameObject.GetComponent<Transform>(); physx::PxTransform trans; trans.p = physx::toPhysX(t.position); trans.q = physx::toPhysX(t.rotation); rigid->setGlobalPose(trans); } } void Rigidbody::EditorGui() { { uint32_t flags = lockFlags; ImGui::CheckboxFlags("Kinematic", &flags, physx::PxRigidBodyFlag::eKINEMATIC); ImGui::CheckboxFlags("Use Kinematic Target for Scene Queries", &flags, physx::PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES); ImGui::CheckboxFlags("Enable CCD", &flags, physx::PxRigidBodyFlag::eENABLE_CCD); ImGui::CheckboxFlags("Enable CCD Friction", &flags, physx::PxRigidBodyFlag::eENABLE_CCD_FRICTION); ImGui::CheckboxFlags("Enable Pose Integration Preview", &flags, physx::PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW); ImGui::CheckboxFlags("Enable Speculative CCD", &flags, physx::PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD); ImGui::CheckboxFlags("Enable CCD Max Contact Impulse", &flags, physx::PxRigidBodyFlag::eENABLE_CCD_MAX_CONTACT_IMPULSE); ImGui::CheckboxFlags("Return Accelerations", &flags, physx::PxRigidBodyFlag::eRETAIN_ACCELERATIONS); lockFlags = physx::PxRigidBodyFlags(physx::PxU8(flags)); } }
30.753425
162
0.710022
ec41db944c5ccf4371e9f02f77f4024f1882087c
754
cpp
C++
source/native-backend/parsing/TextProcessor.cpp
batburger/Native-Backend
aaed26851e09f9e110061025fb2140aed1b4f9b5
[ "Apache-2.0" ]
null
null
null
source/native-backend/parsing/TextProcessor.cpp
batburger/Native-Backend
aaed26851e09f9e110061025fb2140aed1b4f9b5
[ "Apache-2.0" ]
null
null
null
source/native-backend/parsing/TextProcessor.cpp
batburger/Native-Backend
aaed26851e09f9e110061025fb2140aed1b4f9b5
[ "Apache-2.0" ]
null
null
null
// // Created by albert on 3/17/18. // #include "native-backend/parsing/TextProcessor.h" /*!\brief Finds the value specified as key in \c replacement_map in the \c input_string and replaces it with the value for the key.*/ void nvb::TextProcessor::process(std::string *input_string, std::unordered_map<std::string, std::string> &replacement_map) { for(auto replacement_pair : replacement_map){ while(input_string->find(replacement_pair.first, 0) != input_string->npos){ size_t position = input_string->find(replacement_pair.first, 0); *input_string = input_string->erase(position, replacement_pair.first.size()); *input_string = input_string->insert(position, replacement_pair.second); } } }
41.888889
133
0.706897
ec452340961e1d815ad437430988dbeaa16cbb3d
1,234
cpp
C++
daolib/CommonQueries.cpp
mfranceschi/SQLiteDao
447da25d15f6332e454f151fb71aa232665d8506
[ "MIT" ]
null
null
null
daolib/CommonQueries.cpp
mfranceschi/SQLiteDao
447da25d15f6332e454f151fb71aa232665d8506
[ "MIT" ]
null
null
null
daolib/CommonQueries.cpp
mfranceschi/SQLiteDao
447da25d15f6332e454f151fb71aa232665d8506
[ "MIT" ]
null
null
null
#include "CommonQueries.hpp" #include <algorithm> #include "magic_enum.hpp" #include <fmt/core.h> #include <fmt/format.h> std::string enquote(const std::string &text) { return fmt::format("`{}`", text); }; namespace CommonQueries { std::string dropTableIfExists(const std::string &tableName) { return fmt::format("DROP TABLE IF EXISTS {}; ", enquote(tableName)); } std::string createTable(const std::string &tableName, const ColumnList_t &columnList) { std::vector<std::string> columnDeclarations(columnList.size()); std::transform(columnList.cbegin(), columnList.cend(), columnDeclarations.begin(), [](const ColumnData &columnData) { return fmt::format("{} {}", columnData.name, magic_enum::enum_name(columnData.type)); }); return fmt::format("CREATE TABLE {} ({}); ", tableName, fmt::join(columnDeclarations, ", ")); } std::string selectAll(const std::string &tableName) { return fmt::format("SELECT * FROM {}; ", enquote(tableName)); } std::string listTables() { return "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY NAME; "; } } // namespace CommonQueries
30.85
79
0.628849
ec4c7360f6ec7ae840e22bc6ba95fe901cc59e4a
186
cpp
C++
test/test-bits.cpp
mbeutel/slowmath
d09967d168433814896e83af2fbc92bc36e6c4fb
[ "BSL-1.0" ]
1
2021-09-02T07:03:53.000Z
2021-09-02T07:03:53.000Z
test/test-bits.cpp
mbeutel/slowmath
d09967d168433814896e83af2fbc92bc36e6c4fb
[ "BSL-1.0" ]
8
2019-12-03T21:11:07.000Z
2020-02-05T18:44:31.000Z
test/test-bits.cpp
mbeutel/slowmath
d09967d168433814896e83af2fbc92bc36e6c4fb
[ "BSL-1.0" ]
null
null
null
#include <tuple> #include <catch2/catch.hpp> #include <slowmath/arithmetic.hpp> // TODO: add comprehensive tests for shift_left() // TODO: add comprehensive tests for shift_right()
16.909091
50
0.741935
ec4cf730a3c860d1d316407b9f40218bc5535f56
4,644
cpp
C++
cafebazaar-iap/src/iapc_private.cpp
dev-masih/cafebazaar-iap
765fd6c2dacf687c09cf7585003c0d3437e4748e
[ "MIT" ]
3
2019-10-26T05:55:50.000Z
2021-03-30T12:30:33.000Z
cafebazaar-iap/src/iapc_private.cpp
dev-masih/cafebazaar-iap
765fd6c2dacf687c09cf7585003c0d3437e4748e
[ "MIT" ]
null
null
null
cafebazaar-iap/src/iapc_private.cpp
dev-masih/cafebazaar-iap
765fd6c2dacf687c09cf7585003c0d3437e4748e
[ "MIT" ]
null
null
null
#if defined(DM_PLATFORM_ANDROID) #include <dmsdk/sdk.h> #include "iapc.h" #include "iapc_private.h" #include <string.h> #include <stdlib.h> IAPCListener::IAPCListener() { IAPC_ClearCallback(this); } void IAPC_ClearCallback(IAPCListener* callback) { callback->m_L = 0; callback->m_Callback = LUA_NOREF; callback->m_Self = LUA_NOREF; } void IAPC_RegisterCallback(lua_State* L, int index, IAPCListener* callback) { luaL_checktype(L, index, LUA_TFUNCTION); lua_pushvalue(L, index); callback->m_Callback = dmScript::Ref(L, LUA_REGISTRYINDEX); dmScript::GetInstance(L); callback->m_Self = dmScript::Ref(L, LUA_REGISTRYINDEX); callback->m_L = L; } void IAPC_UnregisterCallback(IAPCListener* callback) { if (LUA_NOREF != callback->m_Callback) dmScript::Unref(callback->m_L, LUA_REGISTRYINDEX, callback->m_Callback); if (LUA_NOREF != callback->m_Self) dmScript::Unref(callback->m_L, LUA_REGISTRYINDEX, callback->m_Self); callback->m_Callback = LUA_NOREF; callback->m_Self = LUA_NOREF; callback->m_L = 0; } bool IAPC_SetupCallback(IAPCListener* callback) { lua_State* L = callback->m_L; lua_rawgeti(L, LUA_REGISTRYINDEX, callback->m_Callback); // Setup self lua_rawgeti(L, LUA_REGISTRYINDEX, callback->m_Self); lua_pushvalue(L, -1); dmScript::SetInstance(L); if (!dmScript::IsInstanceValid(L)) { dmLogError("Could not run callback because the instance has been deleted."); lua_pop(L, 2); return false; } return true; } bool IAPC_CallbackIsValid(IAPCListener* callback) { return callback != 0 && callback->m_L != 0 && callback->m_Callback != LUA_NOREF && callback->m_Self != LUA_NOREF; } // Creates a comma separated string, given a table where all values are strings (or numbers) // Returns a malloc'ed string, which the caller must free char* IAPC_List_CreateBuffer(lua_State* L) { int top = lua_gettop(L); luaL_checktype(L, 1, LUA_TTABLE); lua_pushnil(L); int length = 0; while (lua_next(L, 1) != 0) { if (length > 0) { ++length; } const char* p = lua_tostring(L, -1); if(!p) { luaL_error(L, "IAPC: Failed to get value (string) from table"); } length += strlen(p); lua_pop(L, 1); } char* buf = (char*)malloc(length+1); if( buf == 0 ) { dmLogError("Could not allocate buffer of size %d", length+1); assert(top == lua_gettop(L)); return 0; } buf[0] = '\0'; int i = 0; lua_pushnil(L); while (lua_next(L, 1) != 0) { if (i > 0) { dmStrlCat(buf, ",", length+1); } const char* p = lua_tostring(L, -1); if(!p) { luaL_error(L, "IAPC: Failed to get value (string) from table"); } dmStrlCat(buf, p, length+1); lua_pop(L, 1); ++i; } assert(top == lua_gettop(L)); return buf; } void IAPC_PushError(lua_State* L, const char* error, int reason) { if (error != 0) { lua_newtable(L); lua_pushstring(L, "error"); lua_pushstring(L, error); lua_rawset(L, -3); lua_pushstring(L, "reason"); lua_pushnumber(L, reason); lua_rawset(L, -3); } else { lua_pushnil(L); } } void IAPC_PushConstants(lua_State* L) { #define SETCONSTANT(name) \ lua_pushnumber(L, (lua_Number) name); \ lua_setfield(L, -2, #name);\ SETCONSTANT(TRANS_STATE_PURCHASING) SETCONSTANT(TRANS_STATE_PURCHASED) SETCONSTANT(TRANS_STATE_FAILED) SETCONSTANT(TRANS_STATE_RESTORED) SETCONSTANT(TRANS_STATE_UNVERIFIED) SETCONSTANT(REASON_UNSPECIFIED) SETCONSTANT(REASON_USER_CANCELED) #undef SETCONSTANT } void IAPC_Queue_Create(IAPCCommandQueue* queue) { queue->m_Mutex = dmMutex::New(); } void IAPC_Queue_Destroy(IAPCCommandQueue* queue) { dmMutex::Delete(queue->m_Mutex); } void IAPC_Queue_Push(IAPCCommandQueue* queue, IAPCCommand* cmd) { DM_MUTEX_SCOPED_LOCK(queue->m_Mutex); if(queue->m_Commands.Full()) { queue->m_Commands.OffsetCapacity(2); } queue->m_Commands.Push(*cmd); } void IAPC_Queue_Flush(IAPCCommandQueue* queue, IAPCCommandFn fn, void* ctx) { assert(fn != 0); if (queue->m_Commands.Empty()) { return; } DM_MUTEX_SCOPED_LOCK(queue->m_Mutex); for(uint32_t i = 0; i != queue->m_Commands.Size(); ++i) { fn(&queue->m_Commands[i], ctx); } queue->m_Commands.SetSize(0); } #endif // DM_PLATFORM_ANDROID
24.062176
117
0.623385
ec4de22693fbd85ce1682b86960c25b1d8fde467
1,614
cpp
C++
HW06/src/utils.cpp
petegerhat/cuda
671c244276828baeeb66e2c4e0e2f9881b666716
[ "Apache-2.0" ]
null
null
null
HW06/src/utils.cpp
petegerhat/cuda
671c244276828baeeb66e2c4e0e2f9881b666716
[ "Apache-2.0" ]
null
null
null
HW06/src/utils.cpp
petegerhat/cuda
671c244276828baeeb66e2c4e0e2f9881b666716
[ "Apache-2.0" ]
null
null
null
/* * File: main.cpp * Author: peter * * Created on March 25, 2012, 1:36 AM */ #ifndef UTILS_H #define UTILS_H #include <cstdlib> #include <iostream> #include <iomanip> #include <math.h> using namespace std; DT& getDistance(DT* distances, int n, int i, int j) { #ifdef DIS1 return distances[i * n + j]; #else throw "Missing DIS"; #endif } DT *genEmptyMatrix(const int n) { DT *ptr; //cudaMallocHost(&ptr, n * sizeof (DT)); ptr = new DT[n]; return ptr; } unsigned int *genEmptyColMatrix(const int n) { unsigned int *ptr; //cudaMallocHost(&ptr, n * sizeof (DT)); ptr = new unsigned int[n]; return ptr; } DT *genMatrix(const int n) { DT *ptr; ptr = genEmptyMatrix(n); for (int i = 0; i < n; i++) { ptr[i] = ((DT) rand()) / RAND_MAX; } return ptr; } DT **genMatrix(const int n, const int m) { DT **ptr; //ptr = (DT**)malloc(n*sizeof(DT*)); //cudaMallocHost((void**)&ptr, n*sizeof(DT*)); ptr = new DT*[n]; for (int i = 0; i < n; i++) { ptr[i] = genEmptyMatrix(m); for (int j = 0; j < m; j++) { ptr[i][j] = ((DT) rand()) / RAND_MAX; } } return ptr; } void cudaRelease(int n, DT** array) { for (int i = 0; i < n; i++) { cudaFree(array[i]); } cudaFree(array); } void cudaRelease(DT* array) { cudaFree(array); } void cudaRelease(unsigned int* array) { cudaFree(array); } void release(int n, DT** array) { for (int i = 0; i < n; i++) { free(array[i]); } free(array); } void release(DT* array) { free(array); } #endif
17.543478
53
0.545229
ec5adc5a9c03b8a2411a07904d972c0b0913191d
2,437
cpp
C++
GLEngine/Program.cpp
TheMysticLynx/GLEngine
b0c696941d6bbdb5d8fd9d556fc70cf975497153
[ "Apache-2.0" ]
null
null
null
GLEngine/Program.cpp
TheMysticLynx/GLEngine
b0c696941d6bbdb5d8fd9d556fc70cf975497153
[ "Apache-2.0" ]
null
null
null
GLEngine/Program.cpp
TheMysticLynx/GLEngine
b0c696941d6bbdb5d8fd9d556fc70cf975497153
[ "Apache-2.0" ]
null
null
null
#include "Program.h" #include <glad/glad.h> #include <iostream> #include <glm/ext/matrix_float4x4.hpp> #include <glm/gtc/type_ptr.hpp> Program::Program(std::vector<Shader> shaders) { id = glCreateProgram(); std::vector<Shader>::iterator itt = shaders.begin(); do { glAttachShader(id, (*itt).id); itt++; } while (itt != shaders.end()); glLinkProgram(id); int success; glGetProgramiv(id, GL_LINK_STATUS, &success); if (!success) { char infoLog[512]; glGetProgramInfoLog(id, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } } Program::~Program() { glDeleteProgram(id); } void Program::Use() { glUseProgram(id); } void Program::setB1(const std::string& name, bool a) { glUniform1i(glGetUniformLocation(id, name.c_str()), a); } void Program::setF1(const std::string& name, float a) { glUniform1f(glGetUniformLocation(id, name.c_str()), a); } void Program::setI1(const std::string& name, int a) { glUniform1i(glGetUniformLocation(id, name.c_str()), a); } void Program::setB2(const std::string& name, bool a, bool b) { glUniform2i(glGetUniformLocation(id, name.c_str()), a, b); } void Program::setF2(const std::string& name, float a, float b) { glUniform2f(glGetUniformLocation(id, name.c_str()), a, b); } void Program::setI2(const std::string& name, int a, int b) { glUniform2i(glGetUniformLocation(id, name.c_str()), a, b); } void Program::setB3(const std::string& name, bool a, bool b, bool c) { glUniform3i(glGetUniformLocation(id, name.c_str()), a, b, c); } void Program::setF3(const std::string& name, float a, float b, float c) { glUniform3f(glGetUniformLocation(id, name.c_str()), a, b, c); } void Program::setI3(const std::string& name, int a, int b, int c) { glUniform3i(glGetUniformLocation(id, name.c_str()), a, b, c); } void Program::setB4(const std::string& name, bool a, bool b, bool c, bool d) { glUniform4i(glGetUniformLocation(id, name.c_str()), a, b, c, d); } void Program::setF4(const std::string& name, float a, float b, float c, float d) { glUniform4f(glGetUniformLocation(id, name.c_str()), a, b, c, d); } void Program::setI4(const std::string& name, int a, int b, int c, int d) { glUniform4i(glGetUniformLocation(id, name.c_str()), a, b, c, d); } void Program::setM4(const std::string& name, glm::mat4 matrix) { glUniformMatrix4fv(glGetUniformLocation(id, name.c_str()), 1, GL_FALSE, glm::value_ptr(matrix)); }
23.892157
97
0.691014
ec5c747a65793612ebb73d5af99470d314af928a
1,235
cc
C++
common/iterator_test.cc
disktnk/chainer-compiler
5cfd027b40ea6e4abf73eb42be70b4fba74d1cde
[ "MIT" ]
116
2019-01-25T03:54:44.000Z
2022-03-08T00:11:14.000Z
common/iterator_test.cc
disktnk/chainer-compiler
5cfd027b40ea6e4abf73eb42be70b4fba74d1cde
[ "MIT" ]
431
2019-01-25T10:18:44.000Z
2020-06-17T05:28:55.000Z
common/iterator_test.cc
disktnk/chainer-compiler
5cfd027b40ea6e4abf73eb42be70b4fba74d1cde
[ "MIT" ]
26
2019-01-25T07:21:09.000Z
2021-11-26T04:24:35.000Z
#include <gtest/gtest.h> #include <set> #include <vector> #include <common/iterator.h> namespace chainer_compiler { namespace { TEST(IteratorTest, Zip) { std::set<int> ints = {3, 4, 5}; std::vector<std::string> strs = {"a", "b", "c"}; std::vector<std::tuple<int, std::string>> results; for (const auto& p : Zip(ints, strs)) { results.push_back(p); } ASSERT_EQ(3, results.size()); EXPECT_EQ(3, std::get<0>(results[0])); EXPECT_EQ("a", std::get<1>(results[0])); EXPECT_EQ(4, std::get<0>(results[1])); EXPECT_EQ("b", std::get<1>(results[1])); EXPECT_EQ(5, std::get<0>(results[2])); EXPECT_EQ("c", std::get<1>(results[2])); } TEST(IteratorTest, Enumerator) { std::vector<std::string> strs = {"a", "b", "c"}; std::vector<std::pair<size_t, std::string>> results; for (const auto& e : Enumerate(strs)) { results.emplace_back(e.index, e.value); } ASSERT_EQ(3, results.size()); EXPECT_EQ(0, results[0].first); EXPECT_EQ("a", results[0].second); EXPECT_EQ(1, results[1].first); EXPECT_EQ("b", results[1].second); EXPECT_EQ(2, results[2].first); EXPECT_EQ("c", results[2].second); } } // namespace } // namespace chainer_compiler
28.068182
56
0.604858
ec5f0a1e909552fb2848eaa8bea0b5b849b68c16
575
cpp
C++
Algorithms/1269.Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1269.Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1269.Number_of_Ways_to_Stay_in_the_Same_Place_After_Some_Steps.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
class Solution { public: const int MOD = (int) 1e9 + 7; int numWays(int steps, int n) { n = min(n,steps+1); vector<vector<int>> dp(steps+1,vector<int>(n,0)); dp[0][0] = 1; for( int s = 1 ; s <= steps ; s++ ) for( int i = 0 ; i < n ; i++ ) { dp[s][i] = dp[s-1][i]; if(i-1 >= 0) dp[s][i] = ( dp[s][i] + dp[s-1][i-1] ) % MOD; if(i+1 <= n-1) dp[s][i] = ( dp[s][i] + dp[s-1][i+1] ) % MOD; } return dp[steps][0]; } };
31.944444
65
0.353043
ec626a878b49aeca2f8c8eb34f81b11e7ba0e81b
46,255
cpp
C++
net/tapi/skywalker/terminals/frecord/recordingtrackterminal.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/tapi/skywalker/terminals/frecord/recordingtrackterminal.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/tapi/skywalker/terminals/frecord/recordingtrackterminal.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// RecordingTrackTerminal.cpp: implementation of the CRecordingTrackTerminal class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "RecordingTrackTerminal.h" #include "FileRecordingTerminal.h" #include "..\storage\RendPinFilter.h" #include <formats.h> // {9DB520FD-CF2D-40dc-A4C9-5570630A7E2B} const CLSID CLSID_FileRecordingTrackTerminal = {0x9DB520FD, 0xCF2D, 0x40DC, 0xA4, 0xC9, 0x55, 0x70, 0x63, 0x0A, 0x7E, 0x2B}; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CRecordingTrackTerminal::CRecordingTrackTerminal() :m_pParentTerminal(NULL), m_pEventSink(NULL) { LOG((MSP_TRACE, "CRecordingTrackTerminal::CRecordingTrackTerminal[%p] - enter", this)); // // the actual terminal name will be set in InitializeDynamic // m_szName[0] = _T('\0'); m_TerminalType = TT_DYNAMIC; LOG((MSP_TRACE, "CRecordingTrackTerminal::CRecordingTrackTerminal - finish")); } ////////////////////////////////////////////////////////////////////////////// CRecordingTrackTerminal::~CRecordingTrackTerminal() { LOG((MSP_TRACE, "CRecordingTrackTerminal::~CRecordingTrackTerminal[%p] - enter", this)); // // if we have an event sink, release it // if( NULL != m_pEventSink ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::~CRecordingTrackTerminal releasing sink %p", m_pEventSink)); m_pEventSink->Release(); m_pEventSink = NULL; } LOG((MSP_TRACE, "CRecordingTrackTerminal::~CRecordingTrackTerminal - finish")); } ////////////////////////////////////////////////////////////////////////////// // // IDispatch implementation // typedef IDispatchImpl<ITFileTrackVtblFRT<CRecordingTrackTerminal> , &IID_ITFileTrack, &LIBID_TAPI3Lib> CTFileTrackFRT; typedef IDispatchImpl<ITTerminalVtblBase<CBaseTerminal>, &IID_ITTerminal, &LIBID_TAPI3Lib> CTTerminalFRT; ///////////////////////////////////////////////////////////////////////// // // CRecordingTrackTerminal::GetIDsOfNames // // STDMETHODIMP CRecordingTrackTerminal::GetIDsOfNames(REFIID riid, LPOLESTR* rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::GetIDsOfNames[%p] - enter. Name [%S]", this, *rgszNames)); HRESULT hr = DISP_E_UNKNOWNNAME; // // See if the requsted method belongs to the default interface // hr = CTTerminalFRT::GetIDsOfNames(riid, rgszNames, cNames, lcid, rgdispid); if (SUCCEEDED(hr)) { LOG((MSP_TRACE, "CRecordingTrackTerminal::GetIDsOfNames - found %S on ITTerminal", *rgszNames)); rgdispid[0] |= 0; return hr; } // // If not, then try the ITFileTrack interface // hr = CTFileTrackFRT::GetIDsOfNames(riid, rgszNames, cNames, lcid, rgdispid); if (SUCCEEDED(hr)) { LOG((MSP_TRACE, "CRecordingTrackTerminal::GetIDsOfNames - found %S on ITFileTrack", *rgszNames)); rgdispid[0] |= IDISPFILETRACK; return hr; } LOG((MSP_TRACE, "CRecordingTrackTerminal::GetIDsOfNames - finish. didn't find %S on our iterfaces", *rgszNames)); return hr; } ///////////////////////////////////////////////////////////////////////// // // CRecordingTrackTerminal::Invoke // // STDMETHODIMP CRecordingTrackTerminal::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::Invoke[%p] - enter. dispidMember %lx", this, dispidMember)); HRESULT hr = DISP_E_MEMBERNOTFOUND; DWORD dwInterface = (dispidMember & INTERFACEMASK); // // Call invoke for the required interface // switch (dwInterface) { case 0: { hr = CTTerminalFRT::Invoke(dispidMember, riid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr ); LOG((MSP_TRACE, "CRecordingTrackTerminal::Invoke - ITTerminal")); break; } case IDISPFILETRACK: { hr = CTFileTrackFRT::Invoke(dispidMember, riid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr ); LOG((MSP_TRACE, "CRecordingTrackTerminal::Invoke - ITFileTrack")); break; } } // end switch (dwInterface) LOG((MSP_TRACE, "CRecordingTrackTerminal::Invoke - finish. hr = %lx", hr)); return hr; } ///////////////////////////////////// // // CRecordingTrackTerminal::SetFilter // // configures the track terminal with a filter to use // // if filter pointer is null, this uninitializes the treack // HRESULT CRecordingTrackTerminal::SetFilter(IN CBRenderFilter *pRenderingFilter) { LOG((MSP_TRACE, "CRecordingTrackTerminal::SetFilter[%p] - enter. " "pFilter = [%p]", this, pRenderingFilter)); // // check arguments // if ( ( pRenderingFilter != NULL ) && ( IsBadReadPtr( pRenderingFilter, sizeof(CBRenderFilter ) ) ) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::SetFilter - bad filter passed in.")); return E_POINTER; } // // accessing data members -- lock // CLock lock(m_CritSec); // // temporaries for new filter and pin // IBaseFilter *pNewFilter = NULL; IPin *pNewPin = NULL; // // if a new filter was passed in, gets its IBaseFilter interface and its pin // if (NULL != pRenderingFilter) { // // get filter's IBaseFilter interface. // HRESULT hr = pRenderingFilter->QueryInterface(IID_IBaseFilter, (void**)&pNewFilter); if( FAILED(hr) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::SetFilter - QI for IBaseFilter failed. " "hr = %lx", hr)); return hr; } // // get filter's pin // pNewPin = pRenderingFilter->GetPin(0); if (FAILED(hr)) { LOG((MSP_ERROR, "CRecordingTrackTerminal::SetFilter - failed to get pin. " "hr = %lx", hr)); // // cleanup // pNewFilter->Release(); pNewFilter = NULL; return hr; } } // // keep the new filter and pin (or NULLs if a NULL was passed for a filter) // the smart pointers will take care of addrefing. // m_pIPin = pNewPin; m_pIFilter = pNewFilter; // // release filter to compensate for the outstanding refcount from qi // if (NULL != pNewFilter) { pNewFilter->Release(); pNewFilter = NULL; } LOG((MSP_TRACE, "CRecordingTrackTerminal::SetFilter - finish")); return S_OK; } ////////////////////////////////////////////////////////////////////////////// HRESULT CRecordingTrackTerminal::GetFilter(OUT CBRenderFilter **ppRenderingFilter) { LOG((MSP_TRACE, "CRecordingTrackTerminal::GetFilter[%p] - enter.", this)); // // check arguments // if ( ( IsBadWritePtr( ppRenderingFilter, sizeof(CBRenderFilter *) ) ) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::SetFilter - bad filter passed in.")); return E_POINTER; } // // accessing data members -- lock // CLock lock(m_CritSec); *ppRenderingFilter = NULL; // // if we have a filter pointer that is not null, return it // if (m_pIFilter != NULL) { // // get a pointer to the filter object from a <smart> interface pointer // *ppRenderingFilter = static_cast<CBRenderFilter *>(m_pIFilter.p); // // return an extra reference // (*ppRenderingFilter)->AddRef(); } LOG((MSP_TRACE, "CRecordingTrackTerminal::GetFilter - finish")); return S_OK; } ////////////////////////////////////////////////////////////////////////////// HRESULT CRecordingTrackTerminal::AddFiltersToGraph() { LOG((MSP_TRACE, "CRecordingTrackTerminal::AddFiltersToGraph - enter")); // USES_CONVERSION; CLock lock(m_CritSec); // // Validates m_pGraph // if ( m_pGraph == NULL) { LOG((MSP_ERROR, "CRecordingTrackTerminal::AddFiltersToGraph - " "we have no graph - returning E_UNEXPECTED")); return E_UNEXPECTED; } // // Validates m_pIFilter // if ( m_pIFilter == NULL) { LOG((MSP_ERROR, "CRecordingTrackTerminal::AddFiltersToGraph - " "we have no filter - returning E_UNEXPECTED")); return E_UNEXPECTED; } // // AddFilter returns VFW_S_DUPLICATE_NAME if name is duplicate; still succeeds // HRESULT hr = m_pGraph->AddFilter(m_pIFilter, T2CW(m_szName)); if ( FAILED(hr) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::AddFiltersToGraph() - " "Can't add filter. hr = %lx", hr)); return hr; } LOG((MSP_TRACE, "CRecordingTrackTerminal::AddFiltersToGraph - exit S_OK")); return S_OK; } ////////////////////////////////////////////////////////////////////////////// HRESULT STDMETHODCALLTYPE CRecordingTrackTerminal::InitializeDynamic( IN IID iidTerminalClass, IN DWORD dwMediaType, IN TERMINAL_DIRECTION Direction, IN MSP_HANDLE htAddress ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::InitializeDynamic[%p] - enter", this)); // // make sure the direction is correct // if (TD_RENDER != Direction) { LOG((MSP_ERROR, "CRecordingTrackTerminal::InitializeDynamic - bad direction [%d] requested. returning E_INVALIDARG", Direction)); return E_INVALIDARG; } // // make sure the mediatype is correct (multitrack or (audio but nothing else)) // DWORD dwMediaTypesOtherThanVideoAndAudio = dwMediaType & ~(TAPIMEDIATYPE_AUDIO); // | TAPIMEDIATYPE_VIDEO); if ( (TAPIMEDIATYPE_MULTITRACK != dwMediaType) && (0 != dwMediaTypesOtherThanVideoAndAudio) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::InitializeDynamic - bad media type [%d] requested. returning E_INVALIDARG", dwMediaType)); return E_INVALIDARG; } CLock lock(m_CritSec); // // set track's name for ITTerminal::get_Name // // load string from resources BSTR bstrTrackName = SafeLoadString(IDS_FR_TRACK_NAME); // calculate the size of the array we have at our disposal size_t nStringMaxSize = sizeof(m_szName)/sizeof(TCHAR); if (NULL != bstrTrackName ) { _tcsncpy(m_szName, bstrTrackName, nStringMaxSize); } else { LOG((MSP_ERROR, "CRecordingTrackTerminal::InitializeDynamic - failed to load terminal name resource")); return E_OUTOFMEMORY; } SysFreeString(bstrTrackName); bstrTrackName = NULL; // in case string copy did not append with a zero, do it by hand m_szName[nStringMaxSize-1] = 0; LOG((MSP_TRACE, "CRecordingTrackTerminal::InitializeDynamic - Track Name [%S]", m_szName)); // // keep the address handle -- will need it when creating track terminals // m_htAddress = htAddress; // // keep direction // m_TerminalDirection = Direction; // // keep media type // m_dwMediaType = dwMediaType; // // keep terminal class // m_TerminalClassID = iidTerminalClass; LOG((MSP_TRACE, "CRecordingTrackTerminal::InitializeDynamic - finish")); return S_OK; } ////////////////////////////////////////////////////////////////////////////// DWORD CRecordingTrackTerminal::GetSupportedMediaTypes() { LOG((MSP_TRACE, "CRecordingTrackTerminal::GetSupportedMediaTypes[%p] - finish", this)); CLock lock(m_CritSec); DWORD dwMediaType = m_dwMediaType; LOG((MSP_TRACE, "CRecordingTrackTerminal::GetSupportedMediaTypes - finish. MediaType = [0x%lx]", dwMediaType)); return dwMediaType; } // // ITFileTrack methods // ////////////////////////////////////////////////////////////////////////////// HRESULT STDMETHODCALLTYPE CRecordingTrackTerminal::get_Format(OUT AM_MEDIA_TYPE **ppmt) { LOG((MSP_TRACE, "CRecordingTrackTerminal::get_Format[%p] - enter.", this)); // // check the argument // if (IsBadWritePtr(ppmt, sizeof(AM_MEDIA_TYPE*))) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_Format - bad pointer ppmt passed in")); return E_POINTER; } // // no garbage out // *ppmt = NULL; CLock lock(m_CritSec); // // we need a pin to know format // if (m_pIPin == NULL) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_Format - no pin. the terminal was not initialized. " "TAPI_E_NOT_INITIALIZED")); return TAPI_E_NOT_INITIALIZED; } // // get a pointer to the pin object // CBRenderPin *pPinObject = GetCPin(); if (NULL == pPinObject) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_Format - the pins is not CBRenderPin")); TM_ASSERT(FALSE); return E_UNEXPECTED; } // // ask pin for its media type // CMediaType MediaTypeClass; HRESULT hr = pPinObject->GetMediaType(0, &MediaTypeClass); if (FAILED(hr)) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_Format - failed to get pin's format. hr = %lx", hr)); return hr; } // // fail if the format was not yet set. // if ( VFW_S_NO_MORE_ITEMS == hr ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_Format - format not yet set. TAPI_E_NOFORMAT")); return TAPI_E_NOFORMAT; } // // allocate am_media_type to be returned // *ppmt = CreateMediaType(&MediaTypeClass); if (NULL == *ppmt) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_Format - the pins is not CBRenderPin")); return E_OUTOFMEMORY; } LOG((MSP_TRACE, "CRecordingTrackTerminal::get_Format - finish")); return S_OK; } ////////////////////////////////////////////////////////////////////////////// HRESULT STDMETHODCALLTYPE CRecordingTrackTerminal::put_Format(IN const AM_MEDIA_TYPE *pmt) { LOG((MSP_TRACE, "CRecordingTrackTerminal::put_Format[%p] - enter.", this)); // // check the argument // if (IsBadReadPtr(pmt, sizeof(AM_MEDIA_TYPE))) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_Format - bad pointer pmt passed in")); return E_POINTER; } CLock lock(m_CritSec); // // we need a pin to know format // if (m_pIFilter == NULL) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_Format - no filter -- the terminal not uninitilized")); return TAPI_E_NOT_INITIALIZED; } // // make sure supplied format matches track's type // if ( IsEqualGUID(pmt->majortype, MEDIATYPE_Audio) ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::put_Format - MEDIATYPE_Audio")); // // audio format, the track should be audio too // if (TAPIMEDIATYPE_AUDIO != m_dwMediaType) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_Format - trying to put audio format on a non-audio track. " "VFW_E_INVALIDMEDIATYPE" )); return VFW_E_INVALIDMEDIATYPE; } } else if ( IsEqualGUID(pmt->majortype, MEDIATYPE_Video) ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::put_Format - MEDIATYPE_Video")); // // audio format, the track should be audio too // if (TAPIMEDIATYPE_VIDEO != m_dwMediaType) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_Format - trying to put video format on a non-video track. " "VFW_E_INVALIDMEDIATYPE" )); return VFW_E_INVALIDMEDIATYPE; } } else { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_Format - major type not recognized or supported. " "VFW_E_INVALIDMEDIATYPE" )); return VFW_E_INVALIDMEDIATYPE; } // // get a pointer to the filter object // CBRenderFilter *pFilter = static_cast<CBRenderFilter *>(m_pIFilter.p); // // allocate a CMediaType object to pass to the filer // HRESULT hr = E_FAIL; CMediaType *pMediaTypeObject = NULL; try { // // constructor allocates memory, do inside try/catch // pMediaTypeObject = new CMediaType(*pmt); } catch(...) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_Format - exception. failed to allocate media format")); return E_OUTOFMEMORY; } // // no memory for the object // if (NULL == pMediaTypeObject) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_Format - failed to allocate media format")); return E_OUTOFMEMORY; } // // pass format to the filter // hr = pFilter->put_MediaType(pMediaTypeObject); delete pMediaTypeObject; pMediaTypeObject = NULL; LOG((MSP_(hr), "CRecordingTrackTerminal::put_Format - finish.. hr = %lx", hr)); return hr; } STDMETHODIMP CRecordingTrackTerminal::CompleteConnectTerminal() { LOG((MSP_TRACE, "CRecordingTrackTerminal::CompleteConnectTerminal[%p] - enter.", this)); // // pointers to be used outside the lock // CFileRecordingTerminal *pParentTerminal = NULL; CBRenderFilter *pFilter = NULL; { CLock lock(m_CritSec); // // we should have a parent // if (NULL == m_pParentTerminal) { LOG((MSP_ERROR, "CRecordingTrackTerminal::CompleteConnectTerminal - no parent")); return E_FAIL; } // // we should have a filter // if (m_pIFilter == NULL) { LOG((MSP_ERROR, "CRecordingTrackTerminal::CompleteConnectTerminal - no filter")); return E_FAIL; } // // cast filter interface pointer to a filter obejct pointer // pFilter = static_cast<CBRenderFilter *>(m_pIFilter.p); // // addref the filter and parent terminal so we can use outside the lock // pFilter->AddRef(); pParentTerminal = m_pParentTerminal; pParentTerminal->AddRef(); } // // notify the parent that the terminal connected // HRESULT hr = pParentTerminal->OnFilterConnected(pFilter); pFilter->Release(); pFilter = NULL; pParentTerminal->Release(); pParentTerminal = NULL; LOG((MSP_(hr), "CRecordingTrackTerminal::CompleteConnectTerminal - finish. hr = %lx", hr)); return hr; } // // a helper method used by file recording terminal to let us know who the parent is // // the method returns current track's refcount // // note that tracks don't keep refcounts to the parents. // HRESULT CRecordingTrackTerminal::SetParent(IN CFileRecordingTerminal *pParentTerminal, LONG *pCurrentRefCount) { LOG((MSP_TRACE, "CRecordingTrackTerminal::SetParent[%p] - enter. " "pParentTerminal = [%p]", this, pParentTerminal)); // // check argument // if (IsBadWritePtr(pCurrentRefCount, sizeof(LONG))) { LOG((MSP_ERROR, "CRecordingTrackTerminal::SetParent - bad pointer passed in pCurrentRefCount[%p]", pCurrentRefCount)); TM_ASSERT(FALSE); return E_POINTER; } CLock lock(m_CritSec); // // if we already have a parent, release it // if (NULL != m_pParentTerminal) { LOG((MSP_TRACE, "CRecordingTrackTerminal::SetParent - releasing existing new parent [%p]", m_pParentTerminal)); m_pParentTerminal = NULL; } // // keep the new parent // if (NULL != pParentTerminal) { LOG((MSP_TRACE, "CRecordingTrackTerminal::SetParent - keeping the new parent.")); m_pParentTerminal = pParentTerminal; } // // return our current reference count // *pCurrentRefCount = m_dwRef; LOG((MSP_TRACE, "CRecordingTrackTerminal::SetParent - finish.")); return S_OK; } ///////////////////////////////////////////////////////////////////////////// ULONG CRecordingTrackTerminal::InternalAddRef() { // LOG((MSP_TRACE, "CRecordingTrackTerminal::InternalAddRef[%p] - enter.", this)); // // attempt to notify a parent // CLock lock(m_CritSec); if (NULL != m_pParentTerminal) { LOG((MSP_TRACE, "CRecordingTrackTerminal::InternalAddRef - notifying the parent.")); // // notify the parent of an addref, thus causing it to update its total refcount // m_pParentTerminal->ChildAddRef(); } m_dwRef++; ULONG ulReturnValue = m_dwRef; // LOG((MSP_TRACE, "CRecordingTrackTerminal::InternalAddRef - finish. ulReturnValue %lu", ulReturnValue)); return ulReturnValue; } ///////////////////////////////////////////////////////////////////////////// ULONG CRecordingTrackTerminal::InternalRelease() { // LOG((MSP_TRACE, "CRecordingTrackTerminal::InternalRelease[%p] - enter.", this)); // // attempt to notify a parent // CLock lock(m_CritSec); if (NULL != m_pParentTerminal) { LOG((MSP_TRACE, "CRecordingTrackTerminal::InternalRelease - notifying the parent.")); // // propagate release to the parent // m_pParentTerminal->ChildRelease(); // // if the parent is going away, the parent will set my parent pointer to null, and call release on me again. // that is ok -- i will not go away until the first call to release completes // } m_dwRef--; ULONG ulReturnValue = m_dwRef; // LOG((MSP_TRACE, "CRecordingTrackTerminal::InternalRelease - finish. ulReturnValue %lu", ulReturnValue)); return ulReturnValue; } CBRenderPin *CRecordingTrackTerminal::GetCPin() { // // nothing to do if the pin is null // if (m_pIPin == NULL) { return NULL; } CBRenderPin *pCPin = static_cast<CBRenderPin*>(m_pIPin.p); return pCPin; } HRESULT STDMETHODCALLTYPE CRecordingTrackTerminal::get_ControllingTerminal( OUT ITTerminal **ppControllingTerminal ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::get_ControllingTerminal[%p] - enter.", this)); if (IsBadWritePtr(ppControllingTerminal, sizeof(ITTerminal*))) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_ControllingTerminal - bad pointer passed in.")); return E_POINTER; } // // no garbage out // *ppControllingTerminal = NULL; CLock lock(m_CritSec); HRESULT hr = S_OK; // // if i have a parent i will addref it and return a pointer to its ITTerminal interface // if (NULL == m_pParentTerminal) { *ppControllingTerminal = NULL; LOG((MSP_TRACE, "CRecordingTrackTerminal::get_ControllingTerminal - this track has no parent.")); } else { // // get parent's ITTerminal // hr = m_pParentTerminal->_InternalQueryInterface(IID_ITTerminal, (void**)ppControllingTerminal); if (FAILED(hr)) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_ControllingTerminal - querying parent for ITTerminal failed hr = %lx", hr)); // // just to be safe // *ppControllingTerminal = NULL; } } LOG((MSP_TRACE, "CRecordingTrackTerminal::get_ControllingTerminal - finish. hr = %lx", hr)); return hr; } HRESULT CRecordingTrackTerminal::get_AudioFormatForScripting( OUT ITScriptableAudioFormat** ppAudioFormat ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::get_AudioFormatForScripting[%p] - enter.", this)); // // Validates argument // if( IsBadWritePtr( ppAudioFormat, sizeof( ITScriptableAudioFormat*)) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - " "bad ITScriptableAudioFormat* pointer - returning E_POINTER")); return E_POINTER; } // // Mediatype audio? // if( TAPIMEDIATYPE_AUDIO != m_dwMediaType) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - " "invalid media type - returning TAPI_E_INVALIDMEDIATYPE")); return TAPI_E_INVALIDMEDIATYPE; } // // accessing data members -- lock // CLock lock(m_CritSec); // // need to have a pin // if(m_pIPin == NULL) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - " "no pin - returning TAPI_E_NOT_INITIALIZED")); return TAPI_E_NOT_INITIALIZED; } // // get a pointer to the pin object // CBRenderPin *pRenderPinObject = GetCPin(); if (NULL == pRenderPinObject) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - the pins is not CBRenderPin")); TM_ASSERT(FALSE); return E_UNEXPECTED; } // // Create the object object // CComObject<CTAudioFormat> *pAudioFormat = NULL; HRESULT hr = CComObject<CTAudioFormat>::CreateInstance(&pAudioFormat); if( FAILED(hr) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - " "CreateInstance failed - returning 0x%08x", hr)); return hr; } // // Get the interface // hr = pAudioFormat->QueryInterface( IID_ITScriptableAudioFormat, (void**)ppAudioFormat ); if( FAILED(hr) ) { delete pAudioFormat; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - " "QueryInterface failed - returning 0x%08x", hr)); return hr; } // // Get audio format // // ask the pin for its format CMediaType MediaTypeObject; hr = pRenderPinObject->GetMediaType(0, &MediaTypeObject); if( FAILED(hr) ) { (*ppAudioFormat)->Release(); *ppAudioFormat = NULL; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - " "get_Format failed - returning 0x%08x", hr)); return hr; } // // make sure we have an audio format // if( MediaTypeObject.formattype != FORMAT_WaveFormatEx) { (*ppAudioFormat)->Release(); *ppAudioFormat = NULL; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - " "formattype is not WAVEFORMATEX - Returning TAPI_E_INVALIDMEDIATYPE")); return TAPI_E_INVALIDMEDIATYPE; } // // Get WAVEFORMATEX // pAudioFormat->Initialize( (WAVEFORMATEX*)(MediaTypeObject.pbFormat)); LOG((MSP_TRACE, "CRecordingTrackTerminal::get_AudioFormatForScripting - finish")); return S_OK; } HRESULT CRecordingTrackTerminal::put_AudioFormatForScripting( IN ITScriptableAudioFormat* pAudioFormat ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::put_AudioFormatForScripting[%p] - enter.", this)); // // Validate argument // if( IsBadReadPtr( pAudioFormat, sizeof(ITScriptableAudioFormat)) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_AudioFormatForScripting - " "bad ITScriptableAudioFormat* pointer - returning E_POINTER")); return E_POINTER; } // // Create a WAVEFORMATEX structure // WAVEFORMATEX wfx; long lValue = 0; pAudioFormat->get_FormatTag( &lValue ); wfx.wFormatTag = (WORD)lValue; pAudioFormat->get_Channels( &lValue ); wfx.nChannels = (WORD)lValue; pAudioFormat->get_SamplesPerSec( &lValue ); wfx.nSamplesPerSec = (DWORD)lValue; pAudioFormat->get_AvgBytesPerSec( &lValue ); wfx.nAvgBytesPerSec = (DWORD)lValue; pAudioFormat->get_BlockAlign( &lValue ); wfx.nBlockAlign = (WORD)lValue; pAudioFormat->get_BitsPerSample(&lValue); wfx.wBitsPerSample = (WORD)lValue; wfx.cbSize = 0; // // accessing data members -- lock // CLock lock(m_CritSec); // // have a pin? // if( m_pIPin == NULL ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - no pin. " "returning TAPI_E_NOT_INITIALIZED")); return TAPI_E_NOT_INITIALIZED; } // // get a pointer to the pin object // CBRenderPin *pRenderPinObject = GetCPin(); if (NULL == pRenderPinObject) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - the pins is not CBRenderPin")); TM_ASSERT(FALSE); return E_UNEXPECTED; } // // Create AM_MEDIA_TYPE structure // CMediaType MediaFormatObject; HRESULT hr = CreateAudioMediaType(&wfx, &MediaFormatObject, TRUE); if( FAILED(hr) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_AudioFormatForScripting - " "CreateAudioMediaType failed - returning 0x%08x", hr)); return hr; } // // Set format on the pin // hr = pRenderPinObject->SetMediaType(&MediaFormatObject); LOG((MSP_(hr), "CRecordingTrackTerminal::put_AudioFormatForScripting - finish 0x%08x", hr)); return hr; } /* HRESULT CRecordingTrackTerminal::get_VideoFormatForScripting( OUT ITScriptableVideoFormat** ppVideoFormat ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::get_VideoFormatForScripting[%p] - enter.", this)); // // Validates argument // if( IsBadWritePtr( ppVideoFormat, sizeof( ITScriptableVideoFormat*)) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_VideoFormatForScripting - " "bad ITScriptableVideoFormat* pointer - returning E_POINTER")); return E_POINTER; } // // Mediatype video? // if( TAPIMEDIATYPE_VIDEO != m_dwMediaType) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_VideoFormatForScripting - " "invalid media type - returning TAPI_E_INVALIDMEDIATYPE")); return TAPI_E_INVALIDMEDIATYPE; } // // accessing data members -- lock // CLock lock(m_CritSec); // // have a pin? // if( m_pIPin == NULL ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_VideoFormatForScripting - " "no pin - returning TAPI_E_NOT_INITIALIZED")); return TAPI_E_NOT_INITIALIZED; } // // get a pointer to the pin object // CBRenderPin *pRenderPinObject = GetCPin(); if (NULL == pRenderPinObject) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - the pins is not CBRenderPin")); TM_ASSERT(FALSE); return E_UNEXPECTED; } // // Create the object // CComObject<CTVideoFormat> *pVideoFormat = NULL; HRESULT hr = CComObject<CTVideoFormat>::CreateInstance(&pVideoFormat); if( FAILED(hr) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_VideoFormatForScripting - " "CreateInstance failed - returning 0x%08x", hr)); return hr; } // // Get the interface // hr = pVideoFormat->QueryInterface( IID_ITScriptableVideoFormat, (void**)ppVideoFormat ); if( FAILED(hr) ) { delete pVideoFormat; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_VideoFormatForScripting - " "QueryInterface failed - returning 0x%08x", hr)); return hr; } // // Get video format // CMediaType MediaTypeObject; hr = pRenderPinObject->GetMediaType(0, &MediaTypeObject); if( FAILED(hr) ) { (*ppVideoFormat)->Release(); *ppVideoFormat = NULL; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_VideoFormatForScripting - " "get_Format failed - returning 0x%08x", hr)); return hr; } // // make sure the format actually is video // if( MediaTypeObject.formattype != FORMAT_VideoInfo) { (*ppVideoFormat)->Release(); *ppVideoFormat = NULL; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_VideoFormatForScripting - " "formattype is not VIDEOINFOHEADER - Returning TAPI_E_INVALIDMEDIATYPE")); return TAPI_E_INVALIDMEDIATYPE; } // // Get VIDEOINFOHEADER // pVideoFormat->Initialize( (VIDEOINFOHEADER*)(MediaTypeObject.pbFormat)); LOG((MSP_TRACE, "CRecordingTrackTerminal::get_VideoFormatForScripting - finish S_OK")); return S_OK; } HRESULT CRecordingTrackTerminal::put_VideoFormatForScripting( IN ITScriptableVideoFormat* pVideoFormat ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::put_VideoFormatForScripting[%p] - enter.", this)); // // Validate argument // if( IsBadReadPtr( pVideoFormat, sizeof(ITScriptableVideoFormat)) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_VideoFormatForScripting - " "bad ITScriptableVideoFormat* pointer - returning E_POINTER")); return E_POINTER; } // // accessing data members -- lock // CLock lock(m_CritSec); // // have a pin? // if( m_pIPin == NULL ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_VideoFormatForScripting - no pin. " "returning TAPI_E_NOT_INITIALIZED")); return TAPI_E_NOT_INITIALIZED; } // // get a pointer to the pin object // CBRenderPin *pRenderPinObject = GetCPin(); if (NULL == pRenderPinObject) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_AudioFormatForScripting - the pins is not CBRenderPin")); TM_ASSERT(FALSE); return E_UNEXPECTED; } // // Create a WAVEFORMATEX structure // VIDEOINFOHEADER vih; long lValue = 0; double dValue = 0; memset( &vih.rcTarget, 0, sizeof(vih.rcTarget)); memset( &vih.rcTarget, 0, sizeof(vih.rcSource)); pVideoFormat->get_BitRate( &lValue ); vih.dwBitRate = (DWORD)lValue; pVideoFormat->get_BitErrorRate( &lValue ); vih.dwBitErrorRate = (DWORD)lValue; pVideoFormat->get_AvgTimePerFrame( &dValue ); vih.AvgTimePerFrame = (REFERENCE_TIME)dValue; vih.bmiHeader.biSize = sizeof( BITMAPINFOHEADER); pVideoFormat->get_Width( &lValue ); vih.bmiHeader.biWidth = lValue; pVideoFormat->get_Height( &lValue ); vih.bmiHeader.biHeight = lValue; vih.bmiHeader.biPlanes = 1; pVideoFormat->get_BitCount( &lValue ); vih.bmiHeader.biBitCount = (WORD)lValue; pVideoFormat->get_Compression( &lValue ); vih.bmiHeader.biCompression = (DWORD)lValue; pVideoFormat->get_SizeImage( &lValue ); vih.bmiHeader.biSizeImage = (DWORD)lValue; vih.bmiHeader.biXPelsPerMeter = 0; vih.bmiHeader.biYPelsPerMeter = 0; vih.bmiHeader.biClrUsed= 0; vih.bmiHeader.biClrImportant = 0; // // Create AM_MEDIA_TYPE structure // VIDEOINFOHEADER* pvih = new VIDEOINFOHEADER(vih); if( pvih == NULL ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::put_VideoFormatForScripting - " "new allocation failed - returning E_OUTOFMEMORY")); return E_OUTOFMEMORY; } // // prepare a cmediatype object to pass to the pin // CMediaType mt; mt.majortype = MEDIATYPE_Video; mt.subtype = CLSID_NULL; mt.bFixedSizeSamples = TRUE; mt.bTemporalCompression = FALSE; mt.lSampleSize = 0; mt.formattype = FORMAT_VideoInfo; mt.pUnk = NULL; mt.cbFormat = sizeof(vih); mt.pbFormat = (unsigned char *)pvih; // // Set format on the pin // HRESULT hr = pRenderPinObject->SetMediaType(&mt); // // Clean-up // delete pvih; LOG((MSP_(hr), "CRecordingTrackTerminal::get_VideoFormatForScripting - finish 0x%08x", hr)); return hr; } */ HRESULT CRecordingTrackTerminal::get_EmptyAudioFormatForScripting( OUT ITScriptableAudioFormat** ppAudioFormat ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::get_EmptyAudioFormatForScripting - enter")); // // Validate argument // if( IsBadReadPtr( ppAudioFormat, sizeof(ITScriptableAudioFormat*)) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_EmptyAudioFormatForScripting - " "bad ITScriptableAudioFormat* pointer - returning E_POINTER")); return E_POINTER; } // // Create the object // CComObject<CTAudioFormat> *pAudioFormat = NULL; HRESULT hr = CComObject<CTAudioFormat>::CreateInstance(&pAudioFormat); if( FAILED(hr) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_EmptyAudioFormatForScripting - " "CreateInstance failed - returning 0x%08x", hr)); return hr; } // // Get the interface // hr = pAudioFormat->QueryInterface( IID_ITScriptableAudioFormat, (void**)ppAudioFormat ); if( FAILED(hr) ) { delete pAudioFormat; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_EmptyAudioFormatForScripting - " "QueryInterface failed - returning 0x%08x", hr)); return hr; } LOG((MSP_TRACE, "CRecordingTrackTerminal::get_EmptyAudioFormatForScripting - exit S_OK")); return S_OK; } /* HRESULT CRecordingTrackTerminal::get_EmptyVideoFormatForScripting( OUT ITScriptableVideoFormat** ppVideoFormat ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::get_EmptyVideoFormatForScripting - enter")); // // Validate argument // if( IsBadReadPtr( ppVideoFormat, sizeof(ITScriptableVideoFormat*)) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_EmptyVideoFormatForScripting - " "bad ITScriptableVideoFormat* pointer - returning E_POINTER")); return E_POINTER; } // // Create the object // CComObject<CTVideoFormat> *pVideoFormat = NULL; HRESULT hr = CComObject<CTVideoFormat>::CreateInstance(&pVideoFormat); if( FAILED(hr) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::get_EmptyVideoFormatForScripting - " "CreateInstance failed - returning 0x%08x", hr)); return hr; } // // Get the interface // hr = pVideoFormat->QueryInterface( IID_ITScriptableVideoFormat, (void**)ppVideoFormat ); if( FAILED(hr) ) { delete pVideoFormat; LOG((MSP_ERROR, "CRecordingTrackTerminal::get_EmptyVideoFormatForScripting - " "QueryInterface failed - returning 0x%08x", hr)); return hr; } LOG((MSP_TRACE, "CRecordingTrackTerminal::get_EmptyVideoFormatForScripting - exit S_OK")); return S_OK; } */ ////////////////////////////////////////////////////////////////////// // // ITPluggableTerminalEventSinkRegistration - Methods implementation // ////////////////////////////////////////////////////////////////////// HRESULT CRecordingTrackTerminal::RegisterSink( IN ITPluggableTerminalEventSink *pSink ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::RegisterSink - enter [%p]", this)); // // Critical section // CLock lock(m_CritSec); // // Validates argument // if( IsBadReadPtr( pSink, sizeof(ITPluggableTerminalEventSink)) ) { LOG((MSP_ERROR, "CRecordingTrackTerminal::RegisterSink - exit " "ITPluggableTerminalEventSink invalid pointer. Returns E_POINTER")); return E_POINTER; } // // Release the old event sink // if( NULL != m_pEventSink ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::RegisterSink - releasing sink %p", m_pEventSink)); m_pEventSink->Release(); m_pEventSink = NULL; } // // Set the new event sink // LOG((MSP_TRACE, "CRecordingTrackTerminal::RegisterSink - keeping new sink %p", pSink)); m_pEventSink = pSink; m_pEventSink->AddRef(); LOG((MSP_TRACE, "CRecordingTrackTerminal::RegisterSink - exit S_OK")); return S_OK; } HRESULT CRecordingTrackTerminal::UnregisterSink() { // // Critical section // LOG((MSP_TRACE, "CRecordingTrackTerminal::UnregisterSink - enter [%p]", this)); CLock lock(m_CritSec); // // Release the old event sink // if( m_pEventSink ) { LOG((MSP_TRACE, "CRecordingTrackTerminal::UnregisterSink - releasing sink %p", m_pEventSink)); m_pEventSink->Release(); m_pEventSink = NULL; } LOG((MSP_TRACE, "CRecordingTrackTerminal::UnregisterSink - exit S_OK")); return S_OK; } HRESULT CRecordingTrackTerminal::FireEvent(TERMINAL_MEDIA_STATE tmsState, FT_STATE_EVENT_CAUSE ftecEventCause, HRESULT hrErrorCode) { LOG((MSP_TRACE, "CRecordingTrackTerminal::FireEvent - enter [%p]", this)); // // we need a synk before we can fire an event // CLock lock(m_CritSec); if (NULL == m_pEventSink) { LOG((MSP_WARN, "CRecordingTrackTerminal::FireEvent - no sink")); return E_FAIL; } // // initilize the structure // MSP_EVENT_INFO mspEventInfo; mspEventInfo.dwSize = sizeof(MSP_EVENT_INFO); mspEventInfo.Event = ME_FILE_TERMINAL_EVENT; mspEventInfo.hCall = NULL; mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.TerminalMediaState = tmsState; mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.ftecEventCause = ftecEventCause; mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.hrErrorCode = hrErrorCode; // // keep the pointer to our ITTerminal interface in the structure // HRESULT hr = _InternalQueryInterface(IID_ITFileTrack, (void**)&(mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack)); if (FAILED(hr)) { LOG((MSP_ERROR, "CRecordingTrackTerminal::FireEvent - failed to get ITFileTrack interface")); return hr; } // // get a pointer to the parent terminal // hr = get_ControllingTerminal(&(mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal)); if (FAILED(hr)) { mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack->Release(); mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack = NULL; LOG((MSP_ERROR, "CRecordingTrackTerminal::FireEvent - failed to get controlling terminal")); return hr; } // // pass event to the msp // hr = m_pEventSink->FireEvent(&mspEventInfo); if (FAILED(hr)) { // // release all interfaces that we are holding. // fire event failed so no one else will release then for us. // mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack->Release(); mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pFileTrack = NULL; mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal->Release(); mspEventInfo.MSP_FILE_TERMINAL_EVENT_INFO.pParentFileTerminal = NULL; LOG((MSP_ERROR, "CRecordingTrackTerminal::FireEvent - FireEvent on sink failed. hr = %lx", hr)); return hr; } // // event fired // LOG((MSP_TRACE, "CRecordingTrackTerminal::FireEvent - finish")); return S_OK; }
22.955335
141
0.575224
ec62ea93f7707080935e94c530290dd834411df5
23,401
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowEnergyTransfer_HeatExEarthToWater_Surface.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowEnergyTransfer_HeatExEarthToWater_Surface.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimFlowEnergyTransfer_HeatExEarthToWater_Surface.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimFlowEnergyTransfer_HeatExEarthToWater_Surface.hxx" namespace schema { namespace simxml { namespace MepModel { // SimFlowEnergyTransfer_HeatExEarthToWater_Surface // const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_HydronicTubingsideDiam_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubingsideDiam () const { return this->SimFlowEnergyTrans_HydronicTubingsideDiam_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_HydronicTubingsideDiam_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubingsideDiam () { return this->SimFlowEnergyTrans_HydronicTubingsideDiam_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubingsideDiam (const SimFlowEnergyTrans_HydronicTubingsideDiam_type& x) { this->SimFlowEnergyTrans_HydronicTubingsideDiam_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubingsideDiam (const SimFlowEnergyTrans_HydronicTubingsideDiam_optional& x) { this->SimFlowEnergyTrans_HydronicTubingsideDiam_ = x; } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_FluidInletNodeName_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidInletNodeName () const { return this->SimFlowEnergyTrans_FluidInletNodeName_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_FluidInletNodeName_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidInletNodeName () { return this->SimFlowEnergyTrans_FluidInletNodeName_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidInletNodeName (const SimFlowEnergyTrans_FluidInletNodeName_type& x) { this->SimFlowEnergyTrans_FluidInletNodeName_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidInletNodeName (const SimFlowEnergyTrans_FluidInletNodeName_optional& x) { this->SimFlowEnergyTrans_FluidInletNodeName_ = x; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidInletNodeName (::std::auto_ptr< SimFlowEnergyTrans_FluidInletNodeName_type > x) { this->SimFlowEnergyTrans_FluidInletNodeName_.set (x); } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_FluidOutletNodeName_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidOutletNodeName () const { return this->SimFlowEnergyTrans_FluidOutletNodeName_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_FluidOutletNodeName_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidOutletNodeName () { return this->SimFlowEnergyTrans_FluidOutletNodeName_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidOutletNodeName (const SimFlowEnergyTrans_FluidOutletNodeName_type& x) { this->SimFlowEnergyTrans_FluidOutletNodeName_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidOutletNodeName (const SimFlowEnergyTrans_FluidOutletNodeName_optional& x) { this->SimFlowEnergyTrans_FluidOutletNodeName_ = x; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_FluidOutletNodeName (::std::auto_ptr< SimFlowEnergyTrans_FluidOutletNodeName_type > x) { this->SimFlowEnergyTrans_FluidOutletNodeName_.set (x); } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_NumTubingCircuits_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_NumTubingCircuits () const { return this->SimFlowEnergyTrans_NumTubingCircuits_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_NumTubingCircuits_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_NumTubingCircuits () { return this->SimFlowEnergyTrans_NumTubingCircuits_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_NumTubingCircuits (const SimFlowEnergyTrans_NumTubingCircuits_type& x) { this->SimFlowEnergyTrans_NumTubingCircuits_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_NumTubingCircuits (const SimFlowEnergyTrans_NumTubingCircuits_optional& x) { this->SimFlowEnergyTrans_NumTubingCircuits_ = x; } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_ConstructionName_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_ConstructionName () const { return this->SimFlowEnergyTrans_ConstructionName_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_ConstructionName_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_ConstructionName () { return this->SimFlowEnergyTrans_ConstructionName_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_ConstructionName (const SimFlowEnergyTrans_ConstructionName_type& x) { this->SimFlowEnergyTrans_ConstructionName_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_ConstructionName (const SimFlowEnergyTrans_ConstructionName_optional& x) { this->SimFlowEnergyTrans_ConstructionName_ = x; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_ConstructionName (::std::auto_ptr< SimFlowEnergyTrans_ConstructionName_type > x) { this->SimFlowEnergyTrans_ConstructionName_.set (x); } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_HydronicTubeSpacing_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubeSpacing () const { return this->SimFlowEnergyTrans_HydronicTubeSpacing_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_HydronicTubeSpacing_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubeSpacing () { return this->SimFlowEnergyTrans_HydronicTubeSpacing_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubeSpacing (const SimFlowEnergyTrans_HydronicTubeSpacing_type& x) { this->SimFlowEnergyTrans_HydronicTubeSpacing_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_HydronicTubeSpacing (const SimFlowEnergyTrans_HydronicTubeSpacing_optional& x) { this->SimFlowEnergyTrans_HydronicTubeSpacing_ = x; } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_SurfLength_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfLength () const { return this->SimFlowEnergyTrans_SurfLength_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_SurfLength_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfLength () { return this->SimFlowEnergyTrans_SurfLength_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfLength (const SimFlowEnergyTrans_SurfLength_type& x) { this->SimFlowEnergyTrans_SurfLength_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfLength (const SimFlowEnergyTrans_SurfLength_optional& x) { this->SimFlowEnergyTrans_SurfLength_ = x; } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_SurfWidth_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfWidth () const { return this->SimFlowEnergyTrans_SurfWidth_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_SurfWidth_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfWidth () { return this->SimFlowEnergyTrans_SurfWidth_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfWidth (const SimFlowEnergyTrans_SurfWidth_type& x) { this->SimFlowEnergyTrans_SurfWidth_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_SurfWidth (const SimFlowEnergyTrans_SurfWidth_optional& x) { this->SimFlowEnergyTrans_SurfWidth_ = x; } const SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_LowSurfEnvironment_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_LowSurfEnvironment () const { return this->SimFlowEnergyTrans_LowSurfEnvironment_; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface::SimFlowEnergyTrans_LowSurfEnvironment_optional& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_LowSurfEnvironment () { return this->SimFlowEnergyTrans_LowSurfEnvironment_; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_LowSurfEnvironment (const SimFlowEnergyTrans_LowSurfEnvironment_type& x) { this->SimFlowEnergyTrans_LowSurfEnvironment_.set (x); } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_LowSurfEnvironment (const SimFlowEnergyTrans_LowSurfEnvironment_optional& x) { this->SimFlowEnergyTrans_LowSurfEnvironment_ = x; } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTrans_LowSurfEnvironment (::std::auto_ptr< SimFlowEnergyTrans_LowSurfEnvironment_type > x) { this->SimFlowEnergyTrans_LowSurfEnvironment_.set (x); } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace MepModel { // SimFlowEnergyTransfer_HeatExEarthToWater_Surface // SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTransfer_HeatExEarthToWater_Surface () : ::schema::simxml::MepModel::SimFlowEnergyTransfer_HeatExEarthToWater (), SimFlowEnergyTrans_HydronicTubingsideDiam_ (this), SimFlowEnergyTrans_FluidInletNodeName_ (this), SimFlowEnergyTrans_FluidOutletNodeName_ (this), SimFlowEnergyTrans_NumTubingCircuits_ (this), SimFlowEnergyTrans_ConstructionName_ (this), SimFlowEnergyTrans_HydronicTubeSpacing_ (this), SimFlowEnergyTrans_SurfLength_ (this), SimFlowEnergyTrans_SurfWidth_ (this), SimFlowEnergyTrans_LowSurfEnvironment_ (this) { } SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTransfer_HeatExEarthToWater_Surface (const RefId_type& RefId) : ::schema::simxml::MepModel::SimFlowEnergyTransfer_HeatExEarthToWater (RefId), SimFlowEnergyTrans_HydronicTubingsideDiam_ (this), SimFlowEnergyTrans_FluidInletNodeName_ (this), SimFlowEnergyTrans_FluidOutletNodeName_ (this), SimFlowEnergyTrans_NumTubingCircuits_ (this), SimFlowEnergyTrans_ConstructionName_ (this), SimFlowEnergyTrans_HydronicTubeSpacing_ (this), SimFlowEnergyTrans_SurfLength_ (this), SimFlowEnergyTrans_SurfWidth_ (this), SimFlowEnergyTrans_LowSurfEnvironment_ (this) { } SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTransfer_HeatExEarthToWater_Surface (const SimFlowEnergyTransfer_HeatExEarthToWater_Surface& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimFlowEnergyTransfer_HeatExEarthToWater (x, f, c), SimFlowEnergyTrans_HydronicTubingsideDiam_ (x.SimFlowEnergyTrans_HydronicTubingsideDiam_, f, this), SimFlowEnergyTrans_FluidInletNodeName_ (x.SimFlowEnergyTrans_FluidInletNodeName_, f, this), SimFlowEnergyTrans_FluidOutletNodeName_ (x.SimFlowEnergyTrans_FluidOutletNodeName_, f, this), SimFlowEnergyTrans_NumTubingCircuits_ (x.SimFlowEnergyTrans_NumTubingCircuits_, f, this), SimFlowEnergyTrans_ConstructionName_ (x.SimFlowEnergyTrans_ConstructionName_, f, this), SimFlowEnergyTrans_HydronicTubeSpacing_ (x.SimFlowEnergyTrans_HydronicTubeSpacing_, f, this), SimFlowEnergyTrans_SurfLength_ (x.SimFlowEnergyTrans_SurfLength_, f, this), SimFlowEnergyTrans_SurfWidth_ (x.SimFlowEnergyTrans_SurfWidth_, f, this), SimFlowEnergyTrans_LowSurfEnvironment_ (x.SimFlowEnergyTrans_LowSurfEnvironment_, f, this) { } SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: SimFlowEnergyTransfer_HeatExEarthToWater_Surface (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::MepModel::SimFlowEnergyTransfer_HeatExEarthToWater (e, f | ::xml_schema::flags::base, c), SimFlowEnergyTrans_HydronicTubingsideDiam_ (this), SimFlowEnergyTrans_FluidInletNodeName_ (this), SimFlowEnergyTrans_FluidOutletNodeName_ (this), SimFlowEnergyTrans_NumTubingCircuits_ (this), SimFlowEnergyTrans_ConstructionName_ (this), SimFlowEnergyTrans_HydronicTubeSpacing_ (this), SimFlowEnergyTrans_SurfLength_ (this), SimFlowEnergyTrans_SurfWidth_ (this), SimFlowEnergyTrans_LowSurfEnvironment_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::MepModel::SimFlowEnergyTransfer_HeatExEarthToWater::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // SimFlowEnergyTrans_HydronicTubingsideDiam // if (n.name () == "SimFlowEnergyTrans_HydronicTubingsideDiam" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowEnergyTrans_HydronicTubingsideDiam_) { this->SimFlowEnergyTrans_HydronicTubingsideDiam_.set (SimFlowEnergyTrans_HydronicTubingsideDiam_traits::create (i, f, this)); continue; } } // SimFlowEnergyTrans_FluidInletNodeName // if (n.name () == "SimFlowEnergyTrans_FluidInletNodeName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowEnergyTrans_FluidInletNodeName_type > r ( SimFlowEnergyTrans_FluidInletNodeName_traits::create (i, f, this)); if (!this->SimFlowEnergyTrans_FluidInletNodeName_) { this->SimFlowEnergyTrans_FluidInletNodeName_.set (r); continue; } } // SimFlowEnergyTrans_FluidOutletNodeName // if (n.name () == "SimFlowEnergyTrans_FluidOutletNodeName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowEnergyTrans_FluidOutletNodeName_type > r ( SimFlowEnergyTrans_FluidOutletNodeName_traits::create (i, f, this)); if (!this->SimFlowEnergyTrans_FluidOutletNodeName_) { this->SimFlowEnergyTrans_FluidOutletNodeName_.set (r); continue; } } // SimFlowEnergyTrans_NumTubingCircuits // if (n.name () == "SimFlowEnergyTrans_NumTubingCircuits" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowEnergyTrans_NumTubingCircuits_) { this->SimFlowEnergyTrans_NumTubingCircuits_.set (SimFlowEnergyTrans_NumTubingCircuits_traits::create (i, f, this)); continue; } } // SimFlowEnergyTrans_ConstructionName // if (n.name () == "SimFlowEnergyTrans_ConstructionName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowEnergyTrans_ConstructionName_type > r ( SimFlowEnergyTrans_ConstructionName_traits::create (i, f, this)); if (!this->SimFlowEnergyTrans_ConstructionName_) { this->SimFlowEnergyTrans_ConstructionName_.set (r); continue; } } // SimFlowEnergyTrans_HydronicTubeSpacing // if (n.name () == "SimFlowEnergyTrans_HydronicTubeSpacing" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowEnergyTrans_HydronicTubeSpacing_) { this->SimFlowEnergyTrans_HydronicTubeSpacing_.set (SimFlowEnergyTrans_HydronicTubeSpacing_traits::create (i, f, this)); continue; } } // SimFlowEnergyTrans_SurfLength // if (n.name () == "SimFlowEnergyTrans_SurfLength" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowEnergyTrans_SurfLength_) { this->SimFlowEnergyTrans_SurfLength_.set (SimFlowEnergyTrans_SurfLength_traits::create (i, f, this)); continue; } } // SimFlowEnergyTrans_SurfWidth // if (n.name () == "SimFlowEnergyTrans_SurfWidth" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { if (!this->SimFlowEnergyTrans_SurfWidth_) { this->SimFlowEnergyTrans_SurfWidth_.set (SimFlowEnergyTrans_SurfWidth_traits::create (i, f, this)); continue; } } // SimFlowEnergyTrans_LowSurfEnvironment // if (n.name () == "SimFlowEnergyTrans_LowSurfEnvironment" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel") { ::std::auto_ptr< SimFlowEnergyTrans_LowSurfEnvironment_type > r ( SimFlowEnergyTrans_LowSurfEnvironment_traits::create (i, f, this)); if (!this->SimFlowEnergyTrans_LowSurfEnvironment_) { this->SimFlowEnergyTrans_LowSurfEnvironment_.set (r); continue; } } break; } } SimFlowEnergyTransfer_HeatExEarthToWater_Surface* SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimFlowEnergyTransfer_HeatExEarthToWater_Surface (*this, f, c); } SimFlowEnergyTransfer_HeatExEarthToWater_Surface& SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: operator= (const SimFlowEnergyTransfer_HeatExEarthToWater_Surface& x) { if (this != &x) { static_cast< ::schema::simxml::MepModel::SimFlowEnergyTransfer_HeatExEarthToWater& > (*this) = x; this->SimFlowEnergyTrans_HydronicTubingsideDiam_ = x.SimFlowEnergyTrans_HydronicTubingsideDiam_; this->SimFlowEnergyTrans_FluidInletNodeName_ = x.SimFlowEnergyTrans_FluidInletNodeName_; this->SimFlowEnergyTrans_FluidOutletNodeName_ = x.SimFlowEnergyTrans_FluidOutletNodeName_; this->SimFlowEnergyTrans_NumTubingCircuits_ = x.SimFlowEnergyTrans_NumTubingCircuits_; this->SimFlowEnergyTrans_ConstructionName_ = x.SimFlowEnergyTrans_ConstructionName_; this->SimFlowEnergyTrans_HydronicTubeSpacing_ = x.SimFlowEnergyTrans_HydronicTubeSpacing_; this->SimFlowEnergyTrans_SurfLength_ = x.SimFlowEnergyTrans_SurfLength_; this->SimFlowEnergyTrans_SurfWidth_ = x.SimFlowEnergyTrans_SurfWidth_; this->SimFlowEnergyTrans_LowSurfEnvironment_ = x.SimFlowEnergyTrans_LowSurfEnvironment_; } return *this; } SimFlowEnergyTransfer_HeatExEarthToWater_Surface:: ~SimFlowEnergyTransfer_HeatExEarthToWater_Surface () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace MepModel { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
41.271605
164
0.718345
ec65139c14c4f006ab838c4f734336557e3ed9e9
5,705
hpp
C++
runtime/src/Plugin.hpp
KungRaseri/Onsharp
84edac81c184a1c5c40af915ac4c70e1ee27982e
[ "MIT" ]
11
2020-06-26T07:51:34.000Z
2020-10-31T13:36:57.000Z
runtime/src/Plugin.hpp
KungRaseri/Onsharp
84edac81c184a1c5c40af915ac4c70e1ee27982e
[ "MIT" ]
1
2021-01-13T20:05:11.000Z
2021-01-13T20:05:11.000Z
runtime/src/Plugin.hpp
KungRaseri/Onsharp
84edac81c184a1c5c40af915ac4c70e1ee27982e
[ "MIT" ]
5
2020-07-14T20:46:26.000Z
2021-05-18T01:07:05.000Z
#pragma once #include <vector> #include <tuple> #include <map> #include <functional> #include <PluginSDK.h> #include "Singleton.hpp" #include "NetBridge.hpp" class Plugin : public Singleton<Plugin> { friend class Singleton<Plugin>; private: Plugin(); ~Plugin() = default; std::map<std::string, lua_State*> packageStates; std::map<lua_State*, std::string> statePackages; NetBridge bridge; lua_State* MainScriptVM; private: using FuncInfo_t = std::tuple<const char *, lua_CFunction>; std::vector<FuncInfo_t> _func_list; private: inline void Define(const char * name, lua_CFunction func) { _func_list.emplace_back(name, func); } public: enum class NTYPE { NONE = 0, STRING = 1, DOUBLE = 2, INTEGER = 3, BOOLEAN = 4, TABLE = 5 }; struct NValue { NTYPE type = NTYPE::NONE; int iVal = 0; double dVal = 0; bool bVal = false; std::string sVal; Lua::LuaTable_t tVal; void AddAsArg(Lua::LuaArgs_t* args) { if(type == NTYPE::STRING) { args->emplace_back(sVal); return; } if(type == NTYPE::INTEGER) { args->emplace_back(iVal); return; } if(type == NTYPE::DOUBLE) { args->emplace_back(dVal); return; } if(type == NTYPE::BOOLEAN) { args->emplace_back(bVal); return; } if(type == NTYPE::TABLE) { args->emplace_back(tVal); return; } } Lua::LuaValue GetLuaValue() { if(type == NTYPE::STRING) { return new Lua::LuaValue(sVal); } if(type == NTYPE::INTEGER) { return new Lua::LuaValue(iVal); } if(type == NTYPE::DOUBLE) { return new Lua::LuaValue(dVal); } if(type == NTYPE::BOOLEAN) { return new Lua::LuaValue(bVal); } if(type == NTYPE::TABLE) { return new Lua::LuaValue(tVal); } return new Lua::LuaValue(); } void Debug() const { if(type == NTYPE::STRING) { Onset::Plugin::Get()->Log("nval STR : %s \n", sVal.c_str()); return; } if(type == NTYPE::INTEGER) { Onset::Plugin::Get()->Log("nval INT : %d \n", iVal); return; } if(type == NTYPE::DOUBLE) { Onset::Plugin::Get()->Log("nval DBL : %f \n", dVal); return; } if(type == NTYPE::BOOLEAN) { Onset::Plugin::Get()->Log("nval BLD : %s \n", bVal ? "true" : "false"); return; } Onset::Plugin::Get()->Log("nval NULL\n"); } }; decltype(_func_list) const &GetFunctions() const { return _func_list; } void AddPackage(std::string name, lua_State* state) { this->packageStates[name] = state; this->statePackages[state] = name; } void RemovePackage(std::string name) { this->statePackages[this->packageStates[name]] = nullptr; this->packageStates[name] = nullptr; } lua_State* GetPackageState(std::string name) { return this->packageStates[name]; } std::string GetStatePackage(lua_State* L) { return this->statePackages[L]; } void Setup(lua_State* L) { this->MainScriptVM = L; } void InitDelegates() { } Plugin::NValue* CallBridge(const char* key, void** args, int len) { return (Plugin::NValue*) this->bridge.CallBridge(key, args, len); } NetBridge GetBridge() { return this->bridge; } NValue* CreatNValueByString(std::string val){ NValue* nVal = new NValue; nVal->type = NTYPE::STRING; nVal->sVal = std::move(val); return nVal; } NValue* CreateNValueByLua(Lua::LuaValue lVal) { if(lVal.IsString()) { NValue* nVal = new NValue; nVal->type = NTYPE::STRING; auto str = lVal.GetValue<std::string>(); const char* cstr = str.c_str(); nVal->sVal = std::string(cstr); return nVal; } if(lVal.IsBoolean()) { NValue* nVal = new NValue; nVal->type = NTYPE::BOOLEAN; nVal->bVal = lVal.GetValue<bool>(); return nVal; } if(lVal.IsInteger()) { NValue* nVal = new NValue; nVal->type = NTYPE::INTEGER; nVal->iVal = lVal.GetValue<int>(); return nVal; } if(lVal.IsNumber()) { NValue* nVal = new NValue; nVal->type = NTYPE::DOUBLE; nVal->dVal = lVal.GetValue<double>(); return nVal; } if(lVal.IsTable()) { NValue* nVal = new NValue; nVal->type = NTYPE::TABLE; nVal->tVal = lVal.GetValue<Lua::LuaTable_t>(); return nVal; } NValue* nVal = new NValue; nVal->type = NTYPE::NONE; return nVal; } Lua::LuaArgs_t CallLuaFunction(const char* LuaFunctionName, Lua::LuaArgs_t* Arguments); void ClearLuaStack(); };
24.590517
91
0.474847
ec6550f7f9b7351b4b82ef1fc9ffef8244d19ad7
5,809
hpp
C++
my_vulkan/command_buffer.hpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
my_vulkan/command_buffer.hpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
3
2019-02-25T10:13:57.000Z
2020-11-11T14:46:14.000Z
my_vulkan/command_buffer.hpp
pixelwise/my_vulkan
f1c139ed8f95380186905d77cb8e81008f48bc95
[ "CC0-1.0" ]
null
null
null
#pragma once #include <vulkan/vulkan.h> #include <vector> #include "utils.hpp" namespace my_vulkan { struct command_buffer_t { struct scope_t { scope_t( VkCommandBuffer command_buffer, VkCommandBufferUsageFlags flags ); scope_t(const scope_t&) = delete; scope_t(scope_t&& other) noexcept; scope_t& operator=(const scope_t&) = delete; scope_t& operator=(scope_t&& other) noexcept; struct buffer_binding_t { VkBuffer buffer; VkDeviceSize offset; }; void begin_render_pass( VkRenderPass renderPass, VkFramebuffer framebuffer, VkRect2D render_area, std::vector<VkClearValue> clear_values = {}, VkSubpassContents contents = VK_SUBPASS_CONTENTS_INLINE ); void next_subpass( VkSubpassContents contents = VK_SUBPASS_CONTENTS_INLINE ); void set_viewport( std::vector<VkViewport> viewports, uint32_t first = 0 ); void set_scissor( std::vector<VkRect2D> scissors, uint32_t first = 0 ); void clear( std::vector<VkClearAttachment> attachements, std::vector<VkClearRect> rects ); void bind_pipeline( VkPipelineBindPoint bind_point, VkPipeline pipeline, std::optional<VkRect2D> target_rect = std::nullopt ); void bind_vertex_buffers( std::vector<buffer_binding_t> bindings, uint32_t offset = 0 ); void bind_index_buffer( VkBuffer buffer, VkIndexType type, size_t offset = 0 ); void bind_descriptor_set( VkPipelineBindPoint bind_point, VkPipelineLayout layout, std::vector<VkDescriptorSet> descriptors, uint32_t offset = 0, std::vector<uint32_t> dynamic_offset = {} ); void draw_indexed( index_range_t index_range, uint32_t vertex_offset = 0, index_range_t instance_range = {0, 1} ); void draw( index_range_t index_range, index_range_t instance_range = {0, 1} ); void end_render_pass(); void pipeline_barrier( VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask, std::vector<VkMemoryBarrier> barriers, VkDependencyFlags dependency_flags = 0 ); void pipeline_barrier( VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask, std::vector<VkBufferMemoryBarrier> barriers, VkDependencyFlags dependency_flags = 0 ); void pipeline_barrier( VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask, std::vector<VkImageMemoryBarrier> barriers, VkDependencyFlags dependency_flags = 0 ); void pipeline_barrier( VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask, std::vector<VkMemoryBarrier> memory_barriers, std::vector<VkBufferMemoryBarrier> buffer_barriers, std::vector<VkImageMemoryBarrier> image_barriers, VkDependencyFlags dependency_flags = 0 ); void copy( VkBuffer src, VkBuffer dst, std::vector<VkBufferCopy> operations ); void copy( VkBuffer src, VkImage dst, VkImageLayout dst_layout, std::vector<VkBufferImageCopy> operations ); void copy( VkImage src, VkBuffer dst, VkImageLayout src_layout, std::vector<VkBufferImageCopy> operations ); void copy( VkImage src, VkImageLayout src_layout, VkImage dst, VkImageLayout dst_layout, std::vector<VkImageCopy> operations ); void blit( VkImage src, VkImageLayout src_layout, VkImage dst, VkImageLayout dst_layout, std::vector<VkImageBlit> operations, VkFilter filter = VK_FILTER_NEAREST ); VkCommandBuffer end(); ~scope_t(); private: VkCommandBuffer _command_buffer{0}; }; command_buffer_t( VkDevice device, VkCommandPool command_pool, VkCommandBufferLevel level = VK_COMMAND_BUFFER_LEVEL_PRIMARY ); command_buffer_t(const command_buffer_t&) = delete; command_buffer_t(command_buffer_t&& other) noexcept; command_buffer_t& operator=(const command_buffer_t&) = delete; command_buffer_t& operator=(command_buffer_t&& other) noexcept; ~command_buffer_t(); VkCommandBuffer get(); VkDevice device(); scope_t begin(VkCommandBufferUsageFlags flags); void reset(); private: void cleanup(); VkDevice _device; VkCommandPool _command_pool; VkCommandBuffer _command_buffer; }; }
33.773256
72
0.531589
ec669e2811f8c3832ac24e4ccb6ea55c1716d7e3
2,325
cpp
C++
leetcode/stack and queue/Implement Stack using Queues225/Implement Stack using Queues/Implement Stack using Queues/main.cpp
mingyuefly/leetcode
b1af0b715ac6ef15a1321057bbd9e6f8bddbbcf8
[ "MIT" ]
null
null
null
leetcode/stack and queue/Implement Stack using Queues225/Implement Stack using Queues/Implement Stack using Queues/main.cpp
mingyuefly/leetcode
b1af0b715ac6ef15a1321057bbd9e6f8bddbbcf8
[ "MIT" ]
null
null
null
leetcode/stack and queue/Implement Stack using Queues225/Implement Stack using Queues/Implement Stack using Queues/main.cpp
mingyuefly/leetcode
b1af0b715ac6ef15a1321057bbd9e6f8bddbbcf8
[ "MIT" ]
null
null
null
// // main.cpp // Implement Stack using Queues // /** Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. empty() -- Return whether the stack is empty. Example: MyStack stack = new MyStack(); stack.push(1); stack.push(2); stack.top(); // returns 2 stack.pop(); // returns 2 stack.empty(); // returns false Notes: You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid. Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue. You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack). */ // Created by mingyue on 2020/8/8. // Copyright © 2020 Gmingyue. All rights reserved. // #include <iostream> #include <queue> using namespace std; class MyStack { public: /** Initialize your data structure here. */ queue<int> queueOne; queue<int> queueTwo; //queue<int> queueThree; MyStack() { } /** Push element x onto stack. */ void push(int x) { queueOne.push(x); } /** Removes the element on top of the stack and returns that element. */ int pop() { int result = queueOne.back(); while (queueOne.size() != 1) { queueTwo.push(queueOne.front()); queueOne.pop(); } queueOne.pop(); swap(queueOne, queueTwo); return result; } /** Get the top element. */ int top() { return queueOne.back();; } /** Returns whether the stack is empty. */ bool empty() { return queueOne.empty(); } }; int main(int argc, const char * argv[]) { MyStack stack = MyStack(); stack.push(1); stack.push(2); int top = stack.top(); // returns 2 cout << top << endl; int pop = stack.pop(); // returns 2 cout << pop << endl; bool empty = stack.empty(); // returns false if (empty) { cout << "empty" << endl; } else { cout << "not empty" << endl; } return 0; }
25.833333
193
0.603011
ec68e4787edb502ad2d5e52c90b00576688b9711
1,373
cpp
C++
src/core/main.cpp
Opticalp/instrumentall
f952c1cd54f375dc4cb258fec5af34d14c2b8044
[ "MIT" ]
1
2020-05-19T02:06:55.000Z
2020-05-19T02:06:55.000Z
src/core/main.cpp
Opticalp/instrumentall
f952c1cd54f375dc4cb258fec5af34d14c2b8044
[ "MIT" ]
16
2015-11-18T13:25:30.000Z
2018-05-17T19:25:46.000Z
src/core/main.cpp
Opticalp/instrumentall
f952c1cd54f375dc4cb258fec5af34d14c2b8044
[ "MIT" ]
null
null
null
/** * @file src/core/main.cpp * @date nov. 2015 * @author PhRG / opticalp.fr * * Entry point for the Instrumentall software. * * Using POCO (pocoproject.org) Util Application feature. */ /* Copyright (c) 2015 Ph. Renaud-Goud / Opticalp 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 "Poco/Util/Application.h" #include "MainApplication.h" POCO_APP_MAIN(MainApplication)
36.131579
77
0.778587
ec69358fa56dcbd1b4a63769bb58639a33809df3
762
hpp
C++
matlab/src/bits/nnsimpooling.hpp
taigw/matconvnet-dermoscopy
14429a9f66a116cabafaae252f23bd88f0b910a5
[ "BSD-2-Clause" ]
39
2017-06-15T19:34:26.000Z
2021-12-10T23:25:13.000Z
matlab/src/bits/nnsimpooling.hpp
taigw/matconvnet-dermoscopy
14429a9f66a116cabafaae252f23bd88f0b910a5
[ "BSD-2-Clause" ]
2
2018-06-05T20:34:50.000Z
2019-02-10T19:35:21.000Z
matlab/src/bits/nnsimpooling.hpp
igondia/matconvnet-dermoscopy
038cc2f023d464520517ca6a5fedf95bc09a9edc
[ "BSD-2-Clause" ]
21
2017-06-02T13:00:12.000Z
2021-01-02T11:14:42.000Z
// @file nnpooling.hpp // @brief Pooling block // @author Andrea Vedaldi /* Copyright (C) 2014-16 Andrea Vedaldi and Karel Lenc. All rights reserved. This file is part of the VLFeat library and is made available under the terms of the BSD license (see the COPYING file). */ #ifndef __vl__nnsimpooling__ #define __vl__nnsimpooling__ #include "data.hpp" #include <stdio.h> namespace vl { vl::ErrorCode nnsimpooling_forward(vl::Context& context, vl::Tensor output, vl::Tensor data) ; vl::ErrorCode nnsimpooling_backward(vl::Context& context, vl::Tensor derData, vl::Tensor data, vl::Tensor derOutput) ; } #endif /* defined(__vl__nnpooling__) */
21.771429
67
0.641732
ec6c1797585f179110d25ad63d2a5108246f8356
2,142
cpp
C++
Source/SimpleBattle/Pawns/BattlePlayerPawn.cpp
mrthunder/Simple-Battle
cc104c29314619875007e6596f6090691e3ec465
[ "MIT" ]
null
null
null
Source/SimpleBattle/Pawns/BattlePlayerPawn.cpp
mrthunder/Simple-Battle
cc104c29314619875007e6596f6090691e3ec465
[ "MIT" ]
null
null
null
Source/SimpleBattle/Pawns/BattlePlayerPawn.cpp
mrthunder/Simple-Battle
cc104c29314619875007e6596f6090691e3ec465
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Unit.h" #include "BattlePlayerPawn.h" // Sets default values ABattlePlayerPawn::ABattlePlayerPawn() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void ABattlePlayerPawn::BeginPlay() { Super::BeginPlay(); for (size_t i = 0; i < PlayerUnits.Num();i++) { PlayerUnits[i]->StartTurn.AddDynamic(this, &ABattlePlayerPawn::StartSelectingAction); } } // Called every frame void ABattlePlayerPawn::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // Called to bind functionality to input void ABattlePlayerPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void ABattlePlayerPawn::StartSelectingAction(AUnit* unit) { if(IsValid(unit)) { int32 indexOf = PlayerUnits.IndexOfByKey(unit); if (indexOf != INDEX_NONE) { IndexofCurrentUnit = indexOf; } else { UE_LOG(LogTemp, Error, TEXT("The playable unit is not known by the BPP.")); } } } void ABattlePlayerPawn::AppendActionString(FString action, bool bWithPrefix) { if (IndexofCurrentUnit == INDEX_NONE) return; if (bWithPrefix) { ActionBuilder.Append(" > " + action); } else { ActionBuilder.Append(action); } } void ABattlePlayerPawn::RemoveActionFromString(FString action) { if (IndexofCurrentUnit == INDEX_NONE) return; int32 StartIndex = ActionBuilder.Find(" > " + action); if (ActionBuilder.IsValidIndex(StartIndex)) { // 3 is from the " > " ActionBuilder.RemoveAt(StartIndex, action.Len() + 3); } else { StartIndex = ActionBuilder.Find(action); if (ActionBuilder.IsValidIndex(StartIndex)) { ActionBuilder.RemoveAt(StartIndex, action.Len()); } } } void ABattlePlayerPawn::SendActionToUnit() { PlayerUnits[IndexofCurrentUnit]->SetAction(ActionBuilder); IndexofCurrentUnit = INDEX_NONE; ActionBuilder = ""; } bool ABattlePlayerPawn::CanAct() { return IndexofCurrentUnit != INDEX_NONE; }
21.636364
114
0.736228
ec6dac3adc0af9a1ab1733e9ef7655065611ac44
6,494
cpp
C++
utils/TauReflectionGenerator/src/reflection/attribs/GetAttribute.cpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
1
2020-04-22T04:07:01.000Z
2020-04-22T04:07:01.000Z
utils/TauReflectionGenerator/src/reflection/attribs/GetAttribute.cpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
utils/TauReflectionGenerator/src/reflection/attribs/GetAttribute.cpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
#include <llvm/Support/raw_ostream.h> #include "reflection/attribs/GetAttribute.hpp" #include "reflection/Class.hpp" namespace tau { namespace reflection { namespace attribs { AttributeData GetPropertyAttribute::parseAttribute(const DynString& attribName, const ::clang::MacroArgs*, const ::clang::Token*& currentToken) const noexcept { currentToken = getNextToken(currentToken); return AttributeData(this, nullptr, attribName); } void GetPropertyAttribute::generateBaseTauClass(::llvm::raw_fd_ostream& base) const noexcept { base << "public:\n" " template<typename _T>\n" " [[nodiscard]] const _T* getProperty(const void* const object, const char* const propName) const noexcept\n" " { return reinterpret_cast<const _T*>(_getProperty(object, propName)); }\n" "\n" " template<typename _T>\n" " [[nodiscard]] const _T* getProperty(const void* const object, const int propIndex) const noexcept\n" " { return reinterpret_cast<const _T*>(_getProperty(object, propIndex)); }\n" "protected:\n" " [[nodiscard]] virtual const void* _getProperty(const void* object, const char* propName) const noexcept = 0;\n" " [[nodiscard]] virtual const void* _getProperty(const void* object, unsigned propIndex) const noexcept = 0;\n"; } void GetPropertyAttribute::generateImplTauClass(::llvm::raw_fd_ostream& base, const Ref<Class>& clazz) const noexcept { base << " public: \\\n" " template<typename _T> \\\n" " [[nodiscard]] const _T* getProperty(const " << clazz->name() << "* const object, const char* const propName) const noexcept \\\n" " { return reinterpret_cast<const _T*>(getPropertyImpl(object, propName)); } \\\n" " \\\n" " template<typename _T> \\\n" " [[nodiscard]] const _T* getProperty(const " << clazz->name() << "* const object, const unsigned propIndex) const noexcept \\\n" " { return reinterpret_cast<const _T*>(getPropertyImpl(object, propIndex)); } \\\n" " protected: \\\n" " [[nodiscard]] const void* _getProperty(const void* const object, const char* const propName) const noexcept override \\\n" " { return getPropertyImpl(reinterpret_cast<const " << clazz->name() << "*>(object), propName); } \\\n" " \\\n" " [[nodiscard]] const void* _getProperty(const void* const object, const unsigned propIndex) const noexcept override \\\n" " { return getPropertyImpl(reinterpret_cast<const " << clazz->name() << "*>(object), propIndex); } \\\n" " \\\n" " [[nodiscard]] const void* getPropertyImpl(const " << clazz->name() << "* const object, const char* const propName) const noexcept \\\n" " { \\\n"; for(uSys i = 0; i < clazz->properties().size(); ++i) { if(!clazz->properties()[i]->declaration()->hasAttribute("get")) { continue; } base << " if(::std::strcmp(propName, \"" << clazz->properties()[i]->name() << "\") == 0) \\\n" " { return &object->" << clazz->properties()[i]->name() << "; } \\\n"; } base << " return nullptr; \\\n" " } \\\n" " \\\n" " [[nodiscard]] const void* getPropertyImpl(const " << clazz->name() << "* const object, const unsigned propIndex) const noexcept \\\n" " { \\\n" " switch(propIndex) \\\n" " { \\\n"; for(uSys i = 0; i < clazz->properties().size(); ++i) { if(!clazz->properties()[i]->declaration()->hasAttribute("get")) { continue; } base << " case " << i << ": return &object->" << clazz->properties()[i]->name() << "; \\\n"; } base << " default: return nullptr; \\\n" " } \\\n" " } \\\n"; } } } }
74.643678
158
0.345088
ec7446fc4af36d64c68344b4d9619a9098c878d8
3,468
cpp
C++
cpp/godot-cpp/src/gen/TextureLayered.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/TextureLayered.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/TextureLayered.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "TextureLayered.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" #include "Image.hpp" namespace godot { TextureLayered::___method_bindings TextureLayered::___mb = {}; void TextureLayered::___init_method_bindings() { ___mb.mb__get_data = godot::api->godot_method_bind_get_method("TextureLayered", "_get_data"); ___mb.mb__set_data = godot::api->godot_method_bind_get_method("TextureLayered", "_set_data"); ___mb.mb_create = godot::api->godot_method_bind_get_method("TextureLayered", "create"); ___mb.mb_get_depth = godot::api->godot_method_bind_get_method("TextureLayered", "get_depth"); ___mb.mb_get_flags = godot::api->godot_method_bind_get_method("TextureLayered", "get_flags"); ___mb.mb_get_format = godot::api->godot_method_bind_get_method("TextureLayered", "get_format"); ___mb.mb_get_height = godot::api->godot_method_bind_get_method("TextureLayered", "get_height"); ___mb.mb_get_layer_data = godot::api->godot_method_bind_get_method("TextureLayered", "get_layer_data"); ___mb.mb_get_width = godot::api->godot_method_bind_get_method("TextureLayered", "get_width"); ___mb.mb_set_data_partial = godot::api->godot_method_bind_get_method("TextureLayered", "set_data_partial"); ___mb.mb_set_flags = godot::api->godot_method_bind_get_method("TextureLayered", "set_flags"); ___mb.mb_set_layer_data = godot::api->godot_method_bind_get_method("TextureLayered", "set_layer_data"); } Dictionary TextureLayered::_get_data() const { return ___godot_icall_Dictionary(___mb.mb__get_data, (const Object *) this); } void TextureLayered::_set_data(const Dictionary data) { ___godot_icall_void_Dictionary(___mb.mb__set_data, (const Object *) this, data); } void TextureLayered::create(const int64_t width, const int64_t height, const int64_t depth, const int64_t format, const int64_t flags) { ___godot_icall_void_int_int_int_int_int(___mb.mb_create, (const Object *) this, width, height, depth, format, flags); } int64_t TextureLayered::get_depth() const { return ___godot_icall_int(___mb.mb_get_depth, (const Object *) this); } int64_t TextureLayered::get_flags() const { return ___godot_icall_int(___mb.mb_get_flags, (const Object *) this); } Image::Format TextureLayered::get_format() const { return (Image::Format) ___godot_icall_int(___mb.mb_get_format, (const Object *) this); } int64_t TextureLayered::get_height() const { return ___godot_icall_int(___mb.mb_get_height, (const Object *) this); } Ref<Image> TextureLayered::get_layer_data(const int64_t layer) const { return Ref<Image>::__internal_constructor(___godot_icall_Object_int(___mb.mb_get_layer_data, (const Object *) this, layer)); } int64_t TextureLayered::get_width() const { return ___godot_icall_int(___mb.mb_get_width, (const Object *) this); } void TextureLayered::set_data_partial(const Ref<Image> image, const int64_t x_offset, const int64_t y_offset, const int64_t layer, const int64_t mipmap) { ___godot_icall_void_Object_int_int_int_int(___mb.mb_set_data_partial, (const Object *) this, image.ptr(), x_offset, y_offset, layer, mipmap); } void TextureLayered::set_flags(const int64_t flags) { ___godot_icall_void_int(___mb.mb_set_flags, (const Object *) this, flags); } void TextureLayered::set_layer_data(const Ref<Image> image, const int64_t layer) { ___godot_icall_void_Object_int(___mb.mb_set_layer_data, (const Object *) this, image.ptr(), layer); } }
41.783133
154
0.789792
ec749757eb5106520231af244b31d13744d49a66
2,431
cpp
C++
isis/src/base/objs/AtmosModelFactory/AtmosModelFactory.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/src/base/objs/AtmosModelFactory/AtmosModelFactory.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/src/base/objs/AtmosModelFactory/AtmosModelFactory.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "AtmosModelFactory.h" #include "AtmosModel.h" #include "Plugin.h" #include "IException.h" #include "FileName.h" namespace Isis { /** * Create an AtmosModel object using a PVL specification. * An example of the PVL required for this is: * * @code * Object = AtmosphericModel * Group = Algorithm * # Use 'AtmName' instead of 'Name' if using the Gui combo box * # for unique Pvl keyword in DefFile * AtmName/Name = Isotropic1 * Tau = 0.7 * Tauref = 0.0 * Wha = 0.5 * Hnorm = 0.003 * Nulneg = NO * EndGroup * EndObject * @endcode * * There are many other options that can be set via the pvl and are * described in other documentation (see below). * * @param pvl The pvl object containing the specification * @param pmodel The PhotoModel objects contining the data * * @return A pointer to the new AtmosModel * * @see atmosphericModels.doc **/ AtmosModel *AtmosModelFactory::Create(Pvl &pvl, PhotoModel &pmodel) { // Get the algorithm name to create PvlGroup &algo = pvl.findObject("AtmosphericModel") .findGroup("Algorithm", Pvl::Traverse); QString algorithm = ""; if(algo.hasKeyword("AtmName")) { algorithm = QString(algo["AtmName"]); } else if(algo.hasKeyword("Name")) { algorithm = QString(algo["Name"]); } else { QString msg = "Keyword [Name] or keyword [AtmName] must "; msg += "exist in [Group = Algorithm]"; throw IException(IException::User, msg, _FILEINFO_); } // Open the factory plugin file Plugin *p = new Plugin; FileName f("AtmosModel.plugin"); if(f.fileExists()) { p->read("AtmosModel.plugin"); } else { p->read("$ISISROOT/lib/AtmosModel.plugin"); } // Get the algorithm specific plugin and return it AtmosModel * (*plugin)(Pvl & pvl, PhotoModel & pmodel); plugin = (AtmosModel * ( *)(Pvl & pvl, PhotoModel & pmodel)) p->GetPlugin(algorithm); return (*plugin)(pvl, pmodel); } } // end namespace isis
30.3875
75
0.63513
3f3c5d302aa9fcea024c627020f5f72bb25c5f8b
2,518
cpp
C++
RenderSystem/Cpu/rtCpuRenderSystem.cpp
CharlesCarley/Raytracer
63f4926846195e45b3620aeea007094857a709d9
[ "MIT" ]
null
null
null
RenderSystem/Cpu/rtCpuRenderSystem.cpp
CharlesCarley/Raytracer
63f4926846195e45b3620aeea007094857a709d9
[ "MIT" ]
null
null
null
RenderSystem/Cpu/rtCpuRenderSystem.cpp
CharlesCarley/Raytracer
63f4926846195e45b3620aeea007094857a709d9
[ "MIT" ]
null
null
null
/* ------------------------------------------------------------------------------- Copyright (c) Charles Carley. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ------------------------------------------------------------------------------- */ #include "rtCpuRenderSystem.h" #include <cstdio> #include <thread> #include "RenderSystem/rtCamera.h" #include "RenderSystem/rtScene.h" #include "RenderSystem/rtTarget.h" #include "rtTileManager.h" rtCpuRenderSystem::rtCpuRenderSystem() : m_tiles(nullptr) { } rtCpuRenderSystem::~rtCpuRenderSystem() { delete m_tiles; } void rtCpuRenderSystem::initialize(rtScene* scene) { m_scene = scene; if (!m_scene) { printf("Invalid supplied scene.\n"); return; } if (!m_target) { printf("No target was specified.\n"); return; } rtCameras& cameras = m_scene->getCameras(); if (cameras.empty()) { printf("No cameras were found in the scene.\n"); return; } // Cache any persistent per frame variables before spiting into tiles. // Any render method / sub method must be immutable. m_camera = cameras.at(0); rtSceneType* sc = m_scene->getPtr(); rtCameraType* ca = m_camera->getPtr(); updatePixelOffset(); ca->offset = { m_iPixelOffset.x, m_iPixelOffset.y, m_iPixelOffset.z, m_iPixelOffset.w, }; sc->camera = ca; delete m_tiles; m_tiles = new rtTileManager(this, m_target->getFrameBufferInfo()); m_tiles->initialize(); m_dirty = false; } void rtCpuRenderSystem::render(rtScene* scene) { if (m_dirty) initialize(scene); m_scene->updateCaches(); m_tiles->synchronize(); }
26.787234
79
0.639793
3f404a701ec0e6c5ef9feb354a41640bc9ef5dd3
1,966
cc
C++
cpp/shared/tflite_micro/mltk_tflite_micro_recorded_data.cc
SiliconLabs/mltk
56b19518187e9d1c8a0d275de137fc9058984a1f
[ "Zlib" ]
null
null
null
cpp/shared/tflite_micro/mltk_tflite_micro_recorded_data.cc
SiliconLabs/mltk
56b19518187e9d1c8a0d275de137fc9058984a1f
[ "Zlib" ]
1
2021-11-19T20:10:09.000Z
2021-11-19T20:10:09.000Z
cpp/shared/tflite_micro/mltk_tflite_micro_recorded_data.cc
sldriedler/mltk
d82a60359cf875f542a2257f1bc7d8eb4bdaa204
[ "Zlib" ]
null
null
null
#if TFLITE_MICRO_RECORDER_ENABLED #include <cstring> #include <cassert> #include "mltk_tflite_micro_recorded_data.hpp" namespace mltk { static TfliteMicroRecordedData _recorded_data; /*************************************************************************************************/ TfliteMicroRecordedData& TfliteMicroRecordedData::instance() { return _recorded_data; } /*************************************************************************************************/ TfliteMicroRecordedTensor::TfliteMicroRecordedTensor(const TfLiteTensor* tensor) { if(tensor == nullptr) { this->data = nullptr; this->length = 0; } else { this->data = (uint8_t*)malloc(tensor->bytes); assert(this->data != nullptr); memcpy(this->data, tensor->data.raw, tensor->bytes); this->length = tensor->bytes; } } /*************************************************************************************************/ void TfliteMicroRecordedTensor::clear() { if(this->data != nullptr) { free(this->data); this->data = nullptr; this->length = 0; } } /*************************************************************************************************/ void TfliteMicroRecordedLayer::clear() { for(auto& i : this->inputs) { i.clear(); } this->inputs.clear(); for(auto& i : this->outputs) { i.clear(); } this->outputs.clear(); } /*************************************************************************************************/ TfliteMicroRecordedData::~TfliteMicroRecordedData() { clear(); } /*************************************************************************************************/ void TfliteMicroRecordedData::clear(void) { for(auto& i : *this) { i.clear(); } cpputils::TypedList<TfliteMicroRecordedLayer>::clear(); } } // namespace mltk #endif // TFLITE_MICRO_RECORDER_ENABLED
22.860465
99
0.437436
3f47a80f400cd1cc69732af1e9dec95d15ed7b12
954
cpp
C++
src/receptor-bridge/receptors/TiltReceptor.cpp
bistanovski/ShiftEmitter
000f14e3501bfb5d0b65cf2d9bbe8c150c66f391
[ "MIT" ]
null
null
null
src/receptor-bridge/receptors/TiltReceptor.cpp
bistanovski/ShiftEmitter
000f14e3501bfb5d0b65cf2d9bbe8c150c66f391
[ "MIT" ]
3
2018-05-05T19:51:14.000Z
2018-05-06T22:25:41.000Z
src/receptor-bridge/receptors/TiltReceptor.cpp
bistanovski/ShiftEmitter
000f14e3501bfb5d0b65cf2d9bbe8c150c66f391
[ "MIT" ]
null
null
null
#include "TiltReceptor.hpp" #include <QDebug> TiltReceptor::TiltReceptor(QObject *parent) : Receptor(parent) { qDebug() << "TiltReceptor"; } TiltReceptor::~TiltReceptor() { qDebug() << "~TiltReceptor"; } void TiltReceptor::connectReceptor() { QObject::connect(&m_tiltSensor, SIGNAL(readingChanged()), this, SLOT(onReadingChanged())); setConnectedToBackend(m_tiltSensor.connectToBackend()); qDebug() << "Connected to Backend:" << (isConnectedToBackend() ? "true" : "false"); } void TiltReceptor::startListening() { setIsListening(m_tiltSensor.start()); qDebug() << "Tilt Listening:" << (isListening() ? "true" : "false"); } void TiltReceptor::stopListening() { m_tiltSensor.stop(); setIsListening(false); } void TiltReceptor::onReadingChanged() { qDebug() << "Reading Changed"; const auto tiltReading = m_tiltSensor.reading(); emit tiltDetected(tiltReading->xRotation(), tiltReading->yRotation()); }
23.85
94
0.691824
3f4b62d952232e291a04c2a3b2fb320970ea9535
1,063
cpp
C++
src/btr/native_io.nix.cpp
vector-of-bool/batteries
8be07c729e0461e8e0b50c89c5ac9b90e48452a8
[ "BSL-1.0" ]
2
2021-08-02T15:04:33.000Z
2021-08-10T05:07:46.000Z
src/btr/native_io.nix.cpp
vector-of-bool/batteries
8be07c729e0461e8e0b50c89c5ac9b90e48452a8
[ "BSL-1.0" ]
null
null
null
src/btr/native_io.nix.cpp
vector-of-bool/batteries
8be07c729e0461e8e0b50c89c5ac9b90e48452a8
[ "BSL-1.0" ]
null
null
null
#include "./native_io.hpp" #include "./syserror.hpp" using namespace btr; #if !_WIN32 #include <unistd.h> void posix_fd_traits::close(int fd) noexcept { ::close(fd); } std::size_t posix_fd_traits::write(int fd, const_buffer cbuf) { neo_assert(expects, fd != null_handle, "Attempted to write data to a closed file descriptor", std::string_view(cbuf), cbuf.size()); auto nwritten = ::write(fd, cbuf.data(), cbuf.size()); if (nwritten < 0) { throw_current_error("::write() on file descriptor failed"); } return static_cast<std::size_t>(nwritten); } std::size_t posix_fd_traits::read(int fd, mutable_buffer buf) { neo_assert(expects, fd != null_handle, "Attempted to read data from a closed file descriptor", buf.size()); auto nread = ::read(fd, buf.data(), buf.size()); if (nread < 0) { throw_current_error("::read() on file descriptor failed"); } return static_cast<std::size_t>(nread); } #endif
27.25641
70
0.605833
3f4ece7a59eb5f75bc51e55c851b7c331440f617
3,081
hpp
C++
include/codegen/include/Valve/VR/IVRScreenshots__GetScreenshotPropertyFilename.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Valve/VR/IVRScreenshots__GetScreenshotPropertyFilename.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Valve/VR/IVRScreenshots__GetScreenshotPropertyFilename.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:15 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: Valve.VR.IVRScreenshots #include "Valve/VR/IVRScreenshots.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: Valve::VR namespace Valve::VR { // Forward declaring type: EVRScreenshotPropertyFilenames struct EVRScreenshotPropertyFilenames; // Forward declaring type: EVRScreenshotError struct EVRScreenshotError; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Completed forward declares // Type namespace: Valve.VR namespace Valve::VR { // Autogenerated type: Valve.VR.IVRScreenshots/_GetScreenshotPropertyFilename class IVRScreenshots::_GetScreenshotPropertyFilename : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x16B3ABC static IVRScreenshots::_GetScreenshotPropertyFilename* New_ctor(::Il2CppObject* object, System::IntPtr method); // public System.UInt32 Invoke(System.UInt32 screenshotHandle, Valve.VR.EVRScreenshotPropertyFilenames filenameType, System.Text.StringBuilder pchFilename, System.UInt32 cchFilename, Valve.VR.EVRScreenshotError pError) // Offset: 0x16B3AD0 uint Invoke(uint screenshotHandle, Valve::VR::EVRScreenshotPropertyFilenames filenameType, System::Text::StringBuilder* pchFilename, uint cchFilename, Valve::VR::EVRScreenshotError& pError); // public System.IAsyncResult BeginInvoke(System.UInt32 screenshotHandle, Valve.VR.EVRScreenshotPropertyFilenames filenameType, System.Text.StringBuilder pchFilename, System.UInt32 cchFilename, Valve.VR.EVRScreenshotError pError, System.AsyncCallback callback, System.Object object) // Offset: 0x16B3DB4 System::IAsyncResult* BeginInvoke(uint screenshotHandle, Valve::VR::EVRScreenshotPropertyFilenames filenameType, System::Text::StringBuilder* pchFilename, uint cchFilename, Valve::VR::EVRScreenshotError& pError, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.UInt32 EndInvoke(Valve.VR.EVRScreenshotError pError, System.IAsyncResult result) // Offset: 0x16B3EA0 uint EndInvoke(Valve::VR::EVRScreenshotError& pError, System::IAsyncResult* result); }; // Valve.VR.IVRScreenshots/_GetScreenshotPropertyFilename } DEFINE_IL2CPP_ARG_TYPE(Valve::VR::IVRScreenshots::_GetScreenshotPropertyFilename*, "Valve.VR", "IVRScreenshots/_GetScreenshotPropertyFilename"); #pragma pack(pop)
54.052632
286
0.776696
3f4fd94e8e029a3067bf411c49d6eb736c47a204
2,650
cpp
C++
src/lowestindexbranchingscheme.cpp
sraaphorst/nibac
288fcc4012065cf8b15dab4fc5f0c829b2b4a65c
[ "Apache-2.0" ]
null
null
null
src/lowestindexbranchingscheme.cpp
sraaphorst/nibac
288fcc4012065cf8b15dab4fc5f0c829b2b4a65c
[ "Apache-2.0" ]
9
2018-05-06T20:27:49.000Z
2018-10-24T23:28:24.000Z
src/lowestindexbranchingscheme.cpp
sraaphorst/nibac
288fcc4012065cf8b15dab4fc5f0c829b2b4a65c
[ "Apache-2.0" ]
null
null
null
/** * lowestindexbranchingscheme.cpp * * By Sebastian Raaphorst, 2003 - 2018. */ #include <map> #include <set> #include <sstream> #include <string> #include "common.h" #include "lowestindexbranchingscheme.h" #include "nibacexception.h" #include "node.h" namespace vorpal::nibac { int LowestIndexBranchingScheme::getBranchingVariableIndex(Node &n) { return n.getLowestFreeVariableIndex(); } std::map <std::string, std::pair<std::string, std::string>> LowestIndexBranchingSchemeCreator::getOptionsMap(void) { std::map <std::string, std::pair<std::string, std::string>> optionsMap; return optionsMap; } bool LowestIndexBranchingSchemeCreator::processOptionsString(const char *options) { char ch, eqls; // We must explicitly check for empty string prior to processing, since an empty string does // not generate an EOF status. if (strlen(options) == 0) return true; std::istringstream stream(options); while (!stream.eof()) { stream >> ch; if (stream.fail()) throw IllegalParameterException("LowestIndexBranchingScheme::ConfigurationString", options, "could not process string"); stream >> eqls; if (stream.fail() || eqls != '=') throw IllegalParameterException("LowestIndexBranchingScheme::ConfigurationString", options, "could not process string"); // TODO: Again, what was I thinking here?!? switch (ch) { default: std::ostringstream outputstream; outputstream << ch; throw IllegalParameterException("LowestIndexBranchingScheme::ConfigurationString", outputstream.str().c_str(), "not a supported option"); } if (!stream.eof()) { stream >> ch; if (!stream || ch != ':') throw IllegalParameterException("LowestIndexBranchingScheme::ConfigurationString", options, "could not process string"); } } return true; } BranchingScheme *LowestIndexBranchingSchemeCreator::create(void) const { return new LowestIndexBranchingScheme(); } };
35.810811
120
0.526038
3f50c9431e2adc2e41c156e9fac5231e218f41c7
651
hpp
C++
include/haz/Tools/SourceInfo.hpp
Hazurl/Framework-haz
370348801cd969ce8521264653069923a255e0b0
[ "MIT" ]
null
null
null
include/haz/Tools/SourceInfo.hpp
Hazurl/Framework-haz
370348801cd969ce8521264653069923a255e0b0
[ "MIT" ]
null
null
null
include/haz/Tools/SourceInfo.hpp
Hazurl/Framework-haz
370348801cd969ce8521264653069923a255e0b0
[ "MIT" ]
null
null
null
#ifndef __HAZ_SOURCE_INF #define __HAZ_SOURCE_INF #include <haz/Tools/Macro.hpp> BEG_NAMESPACE_HAZ #define SOURCE_INFO_LIST __LINE__, __PRETTY_FUNCTION__, __FILE__ #define SOURCE_INFO ::haz::SourceInfo(SOURCE_INFO_LIST) struct SourceInfo { inline SourceInfo(unsigned int line, const char* func, const char* file) : file(file), func(func), line(line) {} const char* const file; const char* const func; const unsigned int line; }; std::ostream& operator << (std::ostream& os, SourceInfo const& s) { return os << "in " << s.func << " from " << s.file << " at " << s.line; } END_NAMESPACE_HAZ #endif
22.448276
78
0.674347
3f5150feae066afa27501536c9e4d4ecb09eae86
171
hpp
C++
cpp/Autogarden/include/pins/interfaces/output.hpp
e-dang/Autogarden
b15217e5d4755fc028b8dc4255cbdcb77ead80f4
[ "MIT" ]
null
null
null
cpp/Autogarden/include/pins/interfaces/output.hpp
e-dang/Autogarden
b15217e5d4755fc028b8dc4255cbdcb77ead80f4
[ "MIT" ]
null
null
null
cpp/Autogarden/include/pins/interfaces/output.hpp
e-dang/Autogarden
b15217e5d4755fc028b8dc4255cbdcb77ead80f4
[ "MIT" ]
null
null
null
#pragma once #include <pins/interfaces/pin.hpp> class IOutputPin : virtual public IPin { public: virtual ~IOutputPin() = default; virtual void connect() = 0; };
17.1
40
0.690058
3f51813b9ca97a9e20f84b41c6663a2d08d07cd1
3,225
hh
C++
include/introvirt/windows/kernel/nt/types/objects/FILE_OBJECT.hh
srpape/IntroVirt
fe553221c40b8ef71f06e79c9d54d9e123a06c89
[ "Apache-2.0" ]
null
null
null
include/introvirt/windows/kernel/nt/types/objects/FILE_OBJECT.hh
srpape/IntroVirt
fe553221c40b8ef71f06e79c9d54d9e123a06c89
[ "Apache-2.0" ]
null
null
null
include/introvirt/windows/kernel/nt/types/objects/FILE_OBJECT.hh
srpape/IntroVirt
fe553221c40b8ef71f06e79c9d54d9e123a06c89
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Assured Information Security, 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. */ #pragma once #include "OBJECT.hh" #include <introvirt/windows/kernel/nt/fwd.hh> #include <string> namespace introvirt { namespace windows { namespace nt { class FileObjectFlags { public: bool FO_FILE_OPEN() const; bool FO_SYNCHRONOUS_IO() const; bool FO_ALERTABLE_IO() const; bool FO_NO_INTERMEDIATE_BUFFERING() const; bool FO_WRITE_THROUGH() const; bool FO_SEQUENTIAL_ONLY() const; bool FO_CACHE_SUPPORTED() const; bool FO_NAMED_PIPE() const; bool FO_STREAM_FILE() const; bool FO_MAILSLOT() const; bool FO_GENERATE_AUDIT_ON_CLOSE() const; bool FO_QUEUE_IRP_TO_THREAD() const; bool FO_DIRECT_DEVICE_OPEN() const; bool FO_FILE_MODIFIED() const; bool FO_FILE_SIZE_CHANGED() const; bool FO_CLEANUP_COMPLETE() const; bool FO_TEMPORARY_FILE() const; bool FO_DELETE_ON_CLOSE() const; bool FO_OPENED_CASE_SENSITIVE() const; bool FO_HANDLE_CREATED() const; bool FO_FILE_FAST_IO_READ() const; bool FO_RANDOM_ACCESS() const; bool FO_FILE_OPEN_CANCELLED() const; bool FO_VOLUME_OPEN() const; bool FO_REMOTE_ORIGIN() const; bool FO_SKIP_COMPLETION_PORT() const; bool FO_SKIP_SET_EVENT() const; bool FO_SKIP_SET_FAST_IO() const; uint32_t value() const { return value_; } FileObjectFlags(uint32_t value) : value_(value) {} private: const uint32_t value_; }; class FILE_OBJECT : public OBJECT { public: virtual const DEVICE_OBJECT* DeviceObject() const = 0; virtual std::string FileName() const = 0; virtual bool DeletePending() const = 0; virtual void DeletePending(bool value) = 0; virtual FileObjectFlags Flags() const = 0; virtual void Flags(FileObjectFlags flags) = 0; virtual bool DeleteAccess() const = 0; virtual void DeleteAccess(bool value) = 0; virtual bool SharedDelete() const = 0; virtual void SharedDelete(bool value) = 0; /** * @brief Get the drive letter of the file object */ virtual std::string drive_letter() const = 0; /** * @brief Get the full path, drive letter included */ virtual std::string full_path() const = 0; static std::shared_ptr<FILE_OBJECT> make_shared(const NtKernel& kernel, const GuestVirtualAddress& gva); static std::shared_ptr<FILE_OBJECT> make_shared(const NtKernel& kernel, std::unique_ptr<OBJECT_HEADER>&& object_header); virtual ~FILE_OBJECT() = default; }; } /* namespace nt */ } /* namespace windows */ } /* namespace introvirt */
30.714286
100
0.688372
3f53f83a723c80a9ba3a98b0c76669d871de493e
1,342
cpp
C++
src/Collection.cpp
fatehmtd/QtPexelsLib
f38bc62b43444c98935c72164f87aeb9a4021a44
[ "MIT" ]
3
2021-11-19T21:37:41.000Z
2021-12-09T21:20:17.000Z
src/Collection.cpp
fatehmtd/QtPexelsLib
f38bc62b43444c98935c72164f87aeb9a4021a44
[ "MIT" ]
null
null
null
src/Collection.cpp
fatehmtd/QtPexelsLib
f38bc62b43444c98935c72164f87aeb9a4021a44
[ "MIT" ]
null
null
null
#include "../include/Collection.h" qtpexels::Collection::Collection(QObject* parent) : FetchableResource(parent) { } bool qtpexels::Collection::processJSON(const QJsonObject& jsonObject) { _id = jsonObject["id"].toString(); _title = jsonObject["title"].toString(); _description = jsonObject["description"].toString(); _private = jsonObject["private"].toBool(); _mediaCount = jsonObject["media_count"].toInt(); _photosCount = jsonObject["photos_count"].toInt(); _videosCount = jsonObject["videos_count"].toInt(); return true; } const QString& qtpexels::Collection::id() const { return _id; } const QString& qtpexels::Collection::title() const { return _title; } const QString& qtpexels::Collection::description() const { return _description; } bool qtpexels::Collection::isPrivate() const { return _private; } int qtpexels::Collection::mediaCount() const { return _mediaCount; } int qtpexels::Collection::photosCount() const { return _photosCount; } int qtpexels::Collection::videosCount() const { return _videosCount; } const QList<qtpexels::Photo*>& qtpexels::Collection::photos() const { return _photos; } const QList<qtpexels::Video*>& qtpexels::Collection::videos() const { return _videos; }
20.96875
70
0.672131
3f54e3856c78df42fcc6af14574621d6ea764a36
1,342
cpp
C++
src/plane.cpp
Twinklebear/micro-packet
24a35b4ecde7bc0283abba3b03eefe497fb1f138
[ "MIT" ]
12
2015-03-21T01:43:46.000Z
2020-08-05T01:55:37.000Z
src/plane.cpp
Twinklebear/micro-packet
24a35b4ecde7bc0283abba3b03eefe497fb1f138
[ "MIT" ]
null
null
null
src/plane.cpp
Twinklebear/micro-packet
24a35b4ecde7bc0283abba3b03eefe497fb1f138
[ "MIT" ]
null
null
null
#include "plane.h" Plane::Plane(Vec3f pos, Vec3f normal, int material_id) : pos(pos), normal(normal.normalized()), material_id(material_id){} __m256 Plane::intersect(Ray8 &ray, DiffGeom8 &dg) const { const auto vpos = Vec3f_8{pos}; const auto vnorm = Vec3f_8{normal}; const auto t = _mm256_div_ps((vpos - ray.o).dot(vnorm), ray.d.dot(vnorm)); auto hits = _mm256_and_ps(_mm256_cmp_ps(t, ray.t_min, _CMP_GT_OQ), _mm256_cmp_ps(t, ray.t_max, _CMP_LT_OQ)); hits = _mm256_and_ps(hits, ray.active); // Check if all rays miss the sphere if (_mm256_movemask_ps(hits) == 0){ return hits; } // Update t values for rays that did hit ray.t_max = _mm256_blendv_ps(ray.t_max, t, hits); const auto point = ray.at(ray.t_max); dg.point.x = _mm256_blendv_ps(dg.point.x, point.x, hits); dg.point.y = _mm256_blendv_ps(dg.point.y, point.y, hits); dg.point.z = _mm256_blendv_ps(dg.point.z, point.z, hits); dg.normal.x = _mm256_blendv_ps(dg.normal.x, vnorm.x, hits); dg.normal.y = _mm256_blendv_ps(dg.normal.y, vnorm.y, hits); dg.normal.z = _mm256_blendv_ps(dg.normal.z, vnorm.z, hits); // There's no blendv_epi32 in AVX/AVX2 so we have to resort to some hacky casting dg.material_id = _mm256_castps_si256(_mm256_blendv_ps(_mm256_castsi256_ps(dg.material_id), _mm256_castsi256_ps(_mm256_set1_epi32(material_id)), hits)); return hits; }
44.733333
122
0.732489
3f5538f21dc87bc5c7ac85ae5d1c154a908cade1
8,538
cpp
C++
src/cdcarduino.cpp
gdsports/cdcarduino_uhs2
40e39265a1009cff53d85460939066d87b917866
[ "MIT" ]
3
2020-06-04T11:31:10.000Z
2021-10-03T03:03:50.000Z
src/cdcarduino.cpp
gdsports/cdcarduino_uhs2
40e39265a1009cff53d85460939066d87b917866
[ "MIT" ]
null
null
null
src/cdcarduino.cpp
gdsports/cdcarduino_uhs2
40e39265a1009cff53d85460939066d87b917866
[ "MIT" ]
null
null
null
/* * Arduino board serial console port USB CDC ACM. * This adds to the generic CDC ACM class, Arduino board detection and * board reset. Works for Uno and Mega/Mega2560. Includes experimental * code for Leonardo(32u4) and Nano Every (4809) but they are not supported. */ /* * MIT License * * Copyright (c) 2019 gdsports625@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "cdcarduino.h" ARD::ARD(USB *p, CDCAsyncOper *pasync) : ACM(p, pasync), vid(0), pid(0), targetBaudRate(0), targetResetMsec(0) { } uint8_t ARD::reset_dtr_rts(int resetLowMsec) { uint8_t rcode; // Set DTR=RTS=0 rcode = ACM::SetControlLineState(0); if (rcode) { ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode); return rcode; } delay(resetLowMsec); // Set DTR=RTS=1 rcode = ACM::SetControlLineState(3); if (rcode) { ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode); return rcode; } return 0; } uint8_t ARD::reset_touch_1200bps() { uint8_t rcode; // Set DTR=1, RTS=1 rcode = ACM::SetControlLineState(0x03); if (rcode) { ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode); return rcode; } delay(4); // 1200 baud, 8 data bits, no parity, 1 stop bit LINE_CODING lc; lc.dwDTERate = 1200; lc.bCharFormat = 0; lc.bParityType = 0; lc.bDataBits = 8; rcode = ACM::SetLineCoding(&lc); if (rcode) { ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode); return rcode; } delay(4); // Set DTR=0, RTS=1 rcode = ACM::SetControlLineState(0x02); if (rcode) { ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode); return rcode; } delay(4); // Set DTR=0, RTS=0 rcode = ACM::SetControlLineState(0); if (rcode) { ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode); return rcode; } return 0; } bool ARD::reset_target() { if (targetResetMsec) { reset_dtr_rts(targetResetMsec); } else { //reset_touch_1200bps(); } } bool ARD::find_target(uint16_t vid, uint16_t pid) { for (int i = 0; i < sizeof(Boards)/sizeof(Boards[0]); i++) { if ((vid == Boards[i].vendorID) && (pid == Boards[i].productID)) { targetBaudRate = BoardActions[Boards[i].board_actions].baudRate; targetResetMsec = BoardActions[Boards[i].board_actions].resetMsec; return true; } } targetBaudRate = 115200; targetResetMsec = 250; return false; } uint8_t ARD::Init(uint8_t parent, uint8_t port, bool lowspeed) { const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); uint8_t buf[constBufSize]; USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf); uint8_t rcode; UsbDevice *p = NULL; EpInfo *oldep_ptr = NULL; uint8_t num_of_conf; // number of configurations AddressPool &addrPool = pUsb->GetAddressPool(); USBTRACE("ARD Init\r\n"); if(bAddress) return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; // Get pointer to pseudo device with address 0 assigned p = addrPool.GetUsbDevicePtr(0); if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; if(!p->epinfo) { USBTRACE("epinfo\r\n"); return USB_ERROR_EPINFO_IS_NULL; } // Save old pointer to EP_RECORD of address 0 oldep_ptr = p->epinfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence p->epinfo = epInfo; p->lowspeed = lowspeed; // Get device descriptor rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); USBTRACE2("getDevDescr ", rcode); // Restore p->epinfo p->epinfo = oldep_ptr; if(rcode) goto FailGetDevDescr; // Allocate new address according to device class bAddress = addrPool.AllocAddress(parent, false, port); USBTRACE2("bAddress=", bAddress); if(!bAddress) return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; // Assign new address to the device rcode = pUsb->setAddr(0, 0, bAddress); if(rcode) { p->lowspeed = false; addrPool.FreeAddress(bAddress); bAddress = 0; USBTRACE2("setAddr:", rcode); return rcode; } USBTRACE2("Addr:", bAddress); p->lowspeed = false; // Get device descriptor rcode = pUsb->getDevDescr(bAddress, 0, constBufSize, (uint8_t*)buf); USBTRACE2("getDevDescr ", rcode); vid = udd->idVendor; pid = udd->idProduct; // Extract Max Packet Size from the device descriptor epInfo[0].maxPktSize = udd->bMaxPacketSize0; p = addrPool.GetUsbDevicePtr(bAddress); if(!p) return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; p->lowspeed = lowspeed; num_of_conf = udd->bNumConfigurations; // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); if(rcode) goto FailSetDevTblEntry; USBTRACE("VID:"), D_PrintHex(vid, 0x80); USBTRACE(" PID:"), D_PrintHex(pid, 0x80); USBTRACE2(" NC:", num_of_conf); for(uint8_t i = 0; i < num_of_conf; i++) { ConfigDescParser< USB_CLASS_COM_AND_CDC_CTRL, CDC_SUBCLASS_ACM, 0, CP_MASK_COMPARE_CLASS | CP_MASK_COMPARE_SUBCLASS > CdcControlParser(this); ConfigDescParser<USB_CLASS_CDC_DATA, 0, 0, CP_MASK_COMPARE_CLASS> CdcDataParser(this); rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcControlParser); if(rcode) goto FailGetConfDescr; rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcDataParser); if(rcode) goto FailGetConfDescr; if(bNumEP > 1) break; } // for if(bNumEP < 4) return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Assign epInfo to epinfo pointer rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); USBTRACE2("Conf:", bConfNum); // Set Configuration Value rcode = pUsb->setConf(bAddress, 0, bConfNum); if(rcode) goto FailSetConfDescr; // Set up features status _enhanced_status = enhanced_features(); half_duplex(false); autoflowRTS(false); autoflowDSR(false); autoflowXON(false); wide(false); // Always false, because this is only available in custom mode. find_target(vid, pid); USBTRACE2("Baud=", targetBaudRate); USBTRACE2("Reset (ms)=", targetResetMsec); if (targetResetMsec) { // Set DTR = 1 RTS=1 rcode = ACM::SetControlLineState(3); if (rcode) goto FailOnInit; } LINE_CODING lc; lc.dwDTERate = targetBaudRate; lc.bCharFormat = 0; lc.bParityType = 0; lc.bDataBits = 8; rcode = ACM::SetLineCoding(&lc); if (rcode) goto FailOnInit; rcode = pAsync->OnInit(this); if(rcode) goto FailOnInit; USBTRACE("ARD configured\r\n"); ready = true; return 0; FailGetDevDescr: #ifdef DEBUG_USB_HOST NotifyFailGetDevDescr(); goto Fail; #endif FailSetDevTblEntry: #ifdef DEBUG_USB_HOST NotifyFailSetDevTblEntry(); goto Fail; #endif FailGetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailGetConfDescr(); goto Fail; #endif FailSetConfDescr: #ifdef DEBUG_USB_HOST NotifyFailSetConfDescr(); goto Fail; #endif FailOnInit: #ifdef DEBUG_USB_HOST USBTRACE("OnInit:"); #endif #ifdef DEBUG_USB_HOST Fail: NotifyFail(rcode); #endif Release(); return rcode; }
26.030488
97
0.656711