text
stringlengths
8
6.88M
// CalculateThread.cpp : 实现文件 // #include "stdafx.h" #include "MultiThread1.h" #include "CalculateThread.h" #include "MultiThread1Dlg.h" // CCalculateThread IMPLEMENT_DYNCREATE(CCalculateThread, CWinThread) CCalculateThread::CCalculateThread() { } CCalculateThread::~CCalculateThread() { } BOOL CCalculateThread::InitInstance() { // TODO: 在此执行任意逐线程初始化 return TRUE; } int CCalculateThread::ExitInstance() { // TODO: 在此执行任意逐线程清理 return CWinThread::ExitInstance(); } BEGIN_MESSAGE_MAP(CCalculateThread, CWinThread) ON_THREAD_MESSAGE(WM_CALCULATE,OnCalculate) END_MESSAGE_MAP() // CCalculateThread 消息处理程序 void CCalculateThread::OnCalculate(UINT wParam,LONG lParam) { int nTmpt=0; for(int i=0;i<=(int)wParam;i++) { nTmpt=nTmpt+i; } Sleep(500); //(CMultiThread1Dlg *)GetMainWnd()-> ::PostMessage((HWND)(GetMainWnd()->GetSafeHwnd()),WM_DISPLAY,nTmpt,NULL); }
#ifndef LOGGER_H #define LOGGER_H #include "shoemanagercore_global.h" #include <QString> class SHOEMANAGERCORESHARED_EXPORT Logger { public: enum Verboseness { Normal, ///< 排除 INFO 等级的调试信息, 仅记录 WARN, ERROR, FATAL Detailed, ///< 全部调试信息:INFO, WARN, ERROR, FATAL Exhaustive ///< 除详细信息外,还提供文件名和行号信息 }; public: static Logger* instance(); void init (const QString &name = QString(), // 若不指定记录名称则默认为当前日期时间 Verboseness level = Detailed); void deinit (); // 关闭记录器 信息将不记录于记录文件中 void debug(QString message); void warning(QString messsage); void critical(QString message); public: static const QString infoIdentifier; static const QString warnIdentifier; static const QString errorIdentifier; static const QString fatalIdentifier; private: Logger () { } ~Logger () { deinit (); } }; #endif // LOGGER_H
#include<vector> #include<map> #include<iostream> using namespace std; #define MAX 20 typedef int costtype; typedef char vextype; const int inf = 0x3f3f3f3f; typedef char vextype; typedef int costtype; int n, m, p[MAX][MAX], t[MAX][MAX]; costtype a[MAX][MAX], d[MAX][MAX], dist[MAX]; map<vextype, int> mm; vextype *_mm; void createvex(vextype x) { static int i = 1; if (mm[x]) return; mm[x] = i; _mm[i] = x; //g[i] = new vexnode; ++i; } void input() { vextype x, y; costtype z; cin >> n >> m; _mm = new vextype[n + 1]; memset(a, 0x3f, sizeof(a)); for (int i = 0; i < m; i++) { cin >> x >> y >> z; //edge createvex(x); createvex(y); a[mm[x]][mm[y]] = a[mm[y]][mm[x]] = z; } } void dijk(int A) { memset(p, -1, sizeof(p)); memset(dist, 0x3f, sizeof(dist)); bool vis[MAX] = { false }; dist[A] = 0; for (int i = 1; i <= n; ++i) { int cur = -1; for (int j = 1; j <= n; ++j) { if (vis[j]) continue; if (cur == -1 || dist[j] < dist[cur]) { cur = j; } } vis[cur] = true; for (int j = 1; j <= n; ++j) { if (dist[cur] + a[cur][j] < dist[j]) { dist[j] = dist[cur] + a[cur][j]; if (cur != A) p[A][j] = cur; } } } } void floyd() { int i, j, k; for (i = 1; i<=n; ++i) for (j = 1; j<=n; ++j) { d[i][j] = a[i][j]; p[i][j] = -1; } for (k = 1; k<=n; ++k) for (i = 1; i<=n; ++i) for (j = 1; j<=n; ++j) if (d[i][k] + d[k][j]<d[i][j]) { d[i][j] = d[i][k] + d[k][j]; p[i][j] = k; } } void printway(int x, int y) { if (p[x][y] == -1) cout << "->" << _mm[y]; else { printway(x, p[x][y]); printway(p[x][y], y); } } void test() { vextype x, y; cout << "input A,B: "; cin >> x >> y; floyd(); cout << "Floyd: " << d[mm[x]][mm[y]] << '\n' << x; printway(mm[x], mm[y]); //dijkstra dijk(mm[x]); cout << "\ndijkstra: " << dist[mm[y]] << "\n" << x; printway(mm[x], mm[y]); } void main() { input(); test(); system("pause"); }
/* 更新到点的二维线段树,需要注意的两个地方是: 1.更新到点的时候,第一区间的祖先区间都要进行更新。 2.在更新第二区间时,因为对于该第二区间所属的第一区间而言, 第二区间的一个格子是代表了实际的一行格子 所以更新时是需要进行更优判断的。 */ #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #define N 4000 using namespace std; int m; struct TREE{ int maxLove[4*N]; //二维线段树 }mm[400]; struct POINT{ double data; int pos; }; POINT cord[100000][4]; int instr[1000000]; int n; int tg1,tg2; int ll1,rr1,ll2,rr2; void input() { char task; for(int i=0;i<m;++i) { scanf("%c",&task); if(task=='I'){ instr[i]=1; scanf("%d%lf%lf\n",&cord[i][0].pos,&cord[i][1].data,&cord[i][2].data); cord[i][0].pos-=100; cord[i][1].pos=cord[i][1].data*10; cord[i][2].pos=cord[i][2].data*10; }else{ instr[i]=2; scanf("%d%d%lf%lf\n",&cord[i][0].pos,&cord[i][1].pos,&cord[i][2].data,&cord[i][3].data); cord[i][0].pos-=100; cord[i][1].pos-=100; cord[i][2].pos=cord[i][2].data*10; cord[i][3].pos=cord[i][3].data*10; } } } void insert2(TREE &curT,int x,int l,int r,int keypos) { if(tg2<l || tg2>r) return ; if(l==r){ //这一句相当重要,因为对于第一区间而言,第二区间的一个格子是代表了实际的一行格子 //所以更新时是需要进行判断的。 if(keypos>curT.maxLove[x]) curT.maxLove[x]=keypos; return ; } insert2(curT,x*2,l,(l+r)/2,keypos); insert2(curT,x*2+1,(l+r)/2+1,r,keypos); curT.maxLove[x]=curT.maxLove[x*2]; if(curT.maxLove[x*2+1]>curT.maxLove[x]) curT.maxLove[x]=curT.maxLove[x*2+1]; } void insert1(int x,int l,int r,int key) { if(tg1<l || tg1>r) return ; if(l==r){ insert2(mm[x],1,0,1000,key); return ; } //每一个祖先区间都要进行第二区间更新 insert2(mm[x],1,0,1000,key);//ancestor change insert1(x*2,l,(l+r)/2,key); insert1(x*2+1,(l+r)/2+1,r,key); } int find2(TREE &curT,int x,int l,int r) { if(rr2<l || r<ll2) return -1; if(ll2<=l && r<=rr2){ return curT.maxLove[x]; }else{ int d1=find2(curT,x*2,l,(l+r)/2); int d2=find2(curT,x*2+1,(l+r)/2+1,r); if(d1>d2) return d1; else return d2; } } int find1(int x,int l,int r) { if(rr1<l || r<ll1) return -1; if(ll1<=l && r<=rr1){ return find2(mm[x],1,0,1000); }else{ int d1=find1(x*2,l,(l+r)/2); int d2=find1(x*2+1,(l+r)/2+1,r); if(d1>d2) return d1; else return d2; } } void solve() { int ans; for(int i=0;i<400;++i) memset(mm[i].maxLove,255,sizeof(mm[i].maxLove)); for(int i=0;i<m;++i) { if(instr[i]==1){ tg1=cord[i][0].pos; tg2=cord[i][1].pos; insert1(1,0,100,cord[i][2].pos); }else{ ll1=cord[i][0].pos; rr1=cord[i][1].pos; ll2=cord[i][2].pos; rr2=cord[i][3].pos; if(ll1>rr1) swap(ll1,rr1); if(ll2>rr2) swap(ll2,rr2); ans=find1(1,0,100); if(ans<0) printf("-1\n"); else printf("%.1f\n",ans*1.0/10); } } } int main() { freopen("hdu1823.in","r",stdin); while(scanf("%d\n",&m),m) { input(); solve(); } return 0; }
// Created on: 1991-02-26 // Created by: Isabelle GRIGNON // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Extrema_CCLocFOfLocECC_HeaderFile #define _Extrema_CCLocFOfLocECC_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <gp_Pnt.hxx> #include <gp_Vec.hxx> #include <TColStd_SequenceOfReal.hxx> #include <Extrema_SequenceOfPOnCurv.hxx> #include <math_FunctionSetWithDerivatives.hxx> #include <Standard_Boolean.hxx> #include <math_Vector.hxx> class Standard_OutOfRange; class Adaptor3d_Curve; class Extrema_CurveTool; class Extrema_POnCurv; class gp_Pnt; class gp_Vec; class math_Matrix; class Extrema_CCLocFOfLocECC : public math_FunctionSetWithDerivatives { public: DEFINE_STANDARD_ALLOC Standard_EXPORT Extrema_CCLocFOfLocECC(const Standard_Real thetol = 1.0e-10); Standard_EXPORT Extrema_CCLocFOfLocECC(const Adaptor3d_Curve& C1, const Adaptor3d_Curve& C2, const Standard_Real thetol = 1.0e-10); Standard_EXPORT void SetCurve (const Standard_Integer theRank, const Adaptor3d_Curve& C1); void SetTolerance (const Standard_Real theTol); virtual Standard_Integer NbVariables() const Standard_OVERRIDE; virtual Standard_Integer NbEquations() const Standard_OVERRIDE; //! Calculate Fi(U,V). Standard_EXPORT virtual Standard_Boolean Value (const math_Vector& UV, math_Vector& F) Standard_OVERRIDE; //! Calculate Fi'(U,V). Standard_EXPORT Standard_Boolean Derivatives (const math_Vector& UV, math_Matrix& DF) Standard_OVERRIDE; //! Calculate Fi(U,V) and Fi'(U,V). Standard_EXPORT Standard_Boolean Values (const math_Vector& UV, math_Vector& F, math_Matrix& DF) Standard_OVERRIDE; //! Save the found extremum. Standard_EXPORT virtual Standard_Integer GetStateNumber() Standard_OVERRIDE; //! Return the number of found extrema. Standard_Integer NbExt() const; //! Return the value of the Nth distance. Standard_Real SquareDistance (const Standard_Integer N) const; //! Return the points of the Nth extreme distance. Standard_EXPORT void Points (const Standard_Integer N, Extrema_POnCurv& P1, Extrema_POnCurv& P2) const; //! Returns a pointer to the curve specified in the constructor //! or in SetCurve() method. Standard_Address CurvePtr (const Standard_Integer theRank) const; //! Returns a tolerance specified in the constructor //! or in SetTolerance() method. Standard_Real Tolerance() const; //! Determines of boundaries of subinterval for find of root. Standard_EXPORT void SubIntervalInitialize (const math_Vector& theUfirst, const math_Vector& theUlast); //! Computes a Tol value. If 1st derivative of curve //! |D1|<Tol, it is considered D1=0. Standard_EXPORT Standard_Real SearchOfTolerance (const Standard_Address C); protected: private: Standard_Address myC1; Standard_Address myC2; Standard_Real myTol; Standard_Real myU; Standard_Real myV; gp_Pnt myP1; gp_Pnt myP2; gp_Vec myDu; gp_Vec myDv; TColStd_SequenceOfReal mySqDist; Extrema_SequenceOfPOnCurv myPoints; Standard_Real myTolC1; Standard_Real myTolC2; Standard_Integer myMaxDerivOrderC1; Standard_Integer myMaxDerivOrderC2; Standard_Real myUinfium; Standard_Real myUsupremum; Standard_Real myVinfium; Standard_Real myVsupremum; }; #define Curve1 Adaptor3d_Curve #define Curve1_hxx <Adaptor3d_Curve.hxx> #define Tool1 Extrema_CurveTool #define Tool1_hxx <Extrema_CurveTool.hxx> #define Curve2 Adaptor3d_Curve #define Curve2_hxx <Adaptor3d_Curve.hxx> #define Tool2 Extrema_CurveTool #define Tool2_hxx <Extrema_CurveTool.hxx> #define POnC Extrema_POnCurv #define POnC_hxx <Extrema_POnCurv.hxx> #define Pnt gp_Pnt #define Pnt_hxx <gp_Pnt.hxx> #define Vec gp_Vec #define Vec_hxx <gp_Vec.hxx> #define Extrema_SeqPOnC Extrema_SequenceOfPOnCurv #define Extrema_SeqPOnC_hxx <Extrema_SequenceOfPOnCurv.hxx> #define Extrema_FuncExtCC Extrema_CCLocFOfLocECC #define Extrema_FuncExtCC_hxx <Extrema_CCLocFOfLocECC.hxx> #include <Extrema_FuncExtCC.lxx> #undef Curve1 #undef Curve1_hxx #undef Tool1 #undef Tool1_hxx #undef Curve2 #undef Curve2_hxx #undef Tool2 #undef Tool2_hxx #undef POnC #undef POnC_hxx #undef Pnt #undef Pnt_hxx #undef Vec #undef Vec_hxx #undef Extrema_SeqPOnC #undef Extrema_SeqPOnC_hxx #undef Extrema_FuncExtCC #undef Extrema_FuncExtCC_hxx #endif // _Extrema_CCLocFOfLocECC_HeaderFile
#pragma once #include "../../Toolbox/Toolbox.h" #include "../Vector/Vector3.h" #include "MatrixToolbox.h" #include <string> #include <iostream> #include <array> namespace ae { /// \ingroup math /// <summary>Matrix with 4 lines and 4 columns.</summary> /// <seealso cref="Matrix3x3" /> class AERO_CORE_EXPORT Matrix4x4 { public: /// <summary> /// Enum to help to read access with operator[]. /// Mostly used internally. /// <remarks> /// operator( row, column ) is available for an easy public access. /// R are rows and C the columns. /// For example [R1C0] is equivalent to [1][0]. /// </remarks> /// </summary> enum IndexHelper { R0C0 = 0, R0C1 = 1, R0C2 = 2, R0C3 = 3, R1C0 = 4, R1C1 = 5, R1C2 = 6, R1C3 = 7, R2C0 = 8, R2C1 = 9, R2C2 = 10, R2C3 = 11, R3C0 = 12, R3C1 = 13, R3C2 = 14, R3C3 = 15 }; public: /// <summary>Create an matrix with default elements constructor.</summary> /// <param name="_InitMode">Determine how to fill the value.</param> /// \par Example : /// \snippet UnitTestMatrix4x4/Constructors.cpp Constructor Init example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Constructors.cpp Constructor Init expected output explicit Matrix4x4( MatrixInitMode _InitMode = MatrixInitMode::Default ); /// <summary>Create an matrix with given elements.</summary> /// <param name="_Elements">Elements to fill the new matrix with.</param> /// \par Example : /// \snippet UnitTestMatrix4x4/Constructors.cpp Constructor Elements example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Constructors.cpp Constructor Elements expected output Matrix4x4( const std::initializer_list<float>& _Elements ); /// <summary>Create an matrix with given elements.</summary> /// <param name="_Elements">2D list to fill the new matrix with.</param> /// \par Example : /// \snippet UnitTestMatrix4x4/Constructors.cpp Constructor Elements2D example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Constructors.cpp Constructor Elements2D expected output Matrix4x4( const std::initializer_list<std::initializer_list<float>>& _Elements ); /// <summary>Create an matrix and copy the element from the other matrix. </summary> /// <remarks> /// Copy each element with "=" operator, be sure that this operator /// do what you expect with the objects. /// </remarks> /// <param name="_Copy">Matrix to copy the elements from.</param> /// \par Example : /// \snippet UnitTestMatrix4x4/Constructors.cpp Constructor Copy example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Constructors.cpp Constructor Copy expected output Matrix4x4( const Matrix4x4& _Copy ); /// <summary>Copy operator</summary> /// <param name="_Copy">Matrix to copy the elements from.</param> /// <returns>Matrix with the elements copied.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp CopyOperator example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp CopyOperator expected output Matrix4x4& operator=( const Matrix4x4& _Copy ); /// <summary> /// Negation operator. /// Will multiply with -1 each value of the matrix. /// </summary> /// <returns>The calling matrix negated (not the calling matrix, a copy negated).</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp NegativeOperator example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp NegativeOperator expected output Matrix4x4 operator-() const; /// <summary> /// Sets to identity the matrix. /// The diagonal will be set to 1.0f and other values to 0.0f. /// </summary> /// <returns>The calling matrix set to identity.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetToIdentity example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetToIdentity expected output Matrix4x4& SetToIdentity(); /// <summary> /// Sets to zero the matrix. /// Every values will be set to 0.0f. /// </summary> /// <returns>The calling matrix filled with zeros.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetToZero example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetToZero expected output Matrix4x4& SetToZero(); /// <summary>Get the direction in front of the current transformation.</summary> /// <returns>Forward direction of the transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetForward example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetForward expected output Vector3 GetForward() const; /// <summary>Get the direction to the left of the current transformation.</summary> /// <returns>Left direction of the transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetLeft example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetLeft expected output Vector3 GetLeft() const; /// <summary>Get the direction above the current transformation.</summary> /// <returns>Upward direction of the transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetUp example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetUp expected output Vector3 GetUp() const; /// <summary>Get the direction (normalized) in front of the current transformation.</summary> /// <returns>Forward direction of the transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetForwardUnit example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetForwardUnit expected output Vector3 GetForwardUnit() const; /// <summary>Get the direction (normalized) to the left of the current transformation.</summary> /// <returns>Left direction of the transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetLeftUnit example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetLeftUnit expected output Vector3 GetLeftUnit() const; /// <summary>Get the direction (normalized) above the current transformation.</summary> /// <returns>Upward direction of the transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetUpUnit example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetUpUnit expected output Vector3 GetUpUnit() const; /// <summary> /// Rotate the matrix around an axis. /// Add the rotation to the current one. /// </summary> /// <param name="_Angle">The angle in radians.</param> /// <param name="_Axis">The axis to rotate around.</param> /// <returns>The calling matrix rotated.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Rotations example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Rotations expected output Matrix4x4& Rotate( const float _Angle, const Vector3& _Axis ); /// <summary> /// Rotate the matrix around X axis. /// Add the new rotation to the old one. /// </summary> /// <param name="_Angle">The angle in radians.</param> /// <returns>The calling matrix rotated.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Rotations example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Rotations expected output Matrix4x4& RotateX( const float _Angle ); /// <summary> /// Rotate the matrix around Y axis. /// Add the new rotation to the old one. /// </summary> /// <param name="_Angle">The angle in radians.</param> /// <returns>The calling matrix rotated.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Rotations example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Rotations expected output Matrix4x4& RotateY( const float _Angle ); /// <summary> /// Rotate the matrix around Z axis. /// Add the new rotation to the old one. /// </summary> /// <param name="_Angle">TThe angle in radians.</param> /// <returns>The calling matrix rotated.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Rotations example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Rotations expected output Matrix4x4& RotateZ( const float _Angle ); /// <summary> /// Rotate the matrix around an axis. /// Override the current rotation. /// </summary> /// <param name="_Angle">The angle in radians.</param> /// <param name="_Axis">The axis to rotate around.</param> /// <returns>The calling matrix with the new rotation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetRotation example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetRotation expected output Matrix4x4& SetRotation( const float _Angle, const Vector3& _Axis ); /// <summary> /// Rotate the matrix around X axis. /// Override the old roration. /// </summary> /// <param name="_Angle">The new angle in radians.</param> /// <returns>The calling matrix with the new rotation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetRotationX example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetRotationX expected output Matrix4x4& SetRotationX( const float _Angle ); /// <summary> /// Rotate the matrix around Y axis. /// Override the old roration. /// </summary> /// <param name="_Angle">The new angle in radians.</param> /// <returns>The calling matrix with the new rotation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetRotationY example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetRotationY expected output Matrix4x4& SetRotationY( const float _Angle ); /// <summary> /// Rotate the matrix around Y axis. /// Override the old roration. /// </summary> /// <param name="_Angle">The new angle in radians.</param> /// <returns>The calling matrix with the new rotation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetRotationZ example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetRotationZ expected output Matrix4x4& SetRotationZ( const float _Angle ); /// <summary> /// Scale the matrix. /// Multiply the new scale with the old one. /// </summary> /// <param name="_Scale">The scale factor.</param> /// <returns>The calling matrix scaled.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Scale example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Scale expected output Matrix4x4& Scale( const Vector3& _Scale ); /// <summary> /// Scale the matrix. /// Override the old scale. /// </summary> /// <param name="_Scale">The new scale.</param> /// <returns>The calling matrix with the new scale.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetScale example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetScale expected output Matrix4x4& SetScale( const Vector3& _Scale ); /// <summary> /// Translate the matrix. /// Add the new translation to the old one. /// </summary> /// <param name="_Vector">The offset to apply.</param> /// <returns>The calling matrix translated.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Translate example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Translate expected output Matrix4x4& Translate( const Vector3& _Vector ); /// <summary> /// Translate the matrix. /// </summary> /// <param name="_Vector">The new offset.</param> /// <returns>The calling matrix with the new translation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetTranslation example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetTranslation expected output Matrix4x4& SetTranslation( const Vector3& _Vector ); /// <summary> /// Set the matrix to look at a point. /// Be aware that will be override the current value of the matrix. /// </summary> /// <param name="_Eye">The eye position.</param> /// <param name="_PointToLookAt">The point position to look at.</param> /// <param name="_UpWorld">The up of the world.</param> /// <returns>The calling matrix set to look at the specified point.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp LookAt example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp LookAt expected output Matrix4x4& LookAt( const Vector3& _Eye, const Vector3& _PointToLookAt, const Vector3& _UpWorld ); /// <summary> /// Get the determinant of the matrix. /// </summary> /// <returns>The determinant of the matrix.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetDeterminant example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetDeterminant expected output float GetDeterminant() const; /// <summary> /// Inverse the matrix. /// Can fail due to Determinant = 0. /// </summary> /// <returns>The calling matrix inversed if success, matrix unchanged otherwise.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Inverse example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Inverse expected output Matrix4x4& Inverse(); /// <summary> /// Get the inverse of the calling matrix. /// Can fail due to Determinant = 0. /// </summary> /// <returns>The matrix inversed, if it fail, return the matrix unchanged.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetInverse example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetInverse expected output Matrix4x4 GetInverse() const; /// <summary> /// Switch the last column with the last line of the matrix. /// </summary> /// <returns>The calling matrix with the translation moved.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SwitchVectorPosition example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SwitchVectorPosition expected output Matrix4x4& SwitchVectorPosition(); /// <summary> /// Copy the point, transform then return the copy. /// </summary> /// <param name="_Point">The point to transform.</param> /// <returns>The transformed point.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetTransformedPoint example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetTransformedPoint expected output Vector3 GetTransformedPoint( const Vector3& _Point ) const; /// <summary> /// Transforms the point. /// </summary> /// <param name="_Point">The point to transform.</param> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp TransformPoint example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp TransformPoint expected output void TransformPoint( AE_InOut Vector3& _Point ) const; /// <summary> /// Set the matrix to do a perspective projection. /// </summary> /// <param name="_Fov">The field of view.</param> /// <param name="_Aspect">The aspect ratio.</param> /// <param name="_Near">The near distance.</param> /// <param name="_Far">The far distance.</param> /// <returns>The callind matrix computed to do a perspective projection.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetToPerspectiveMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetToPerspectiveMatrix expected output Matrix4x4& SetToPerspectiveMatrix( const float _Fov, const float _Aspect, const float _Near, const float _Far ); /// <summary> /// Set the matrix to do an orthogonal projection. /// </summary> /// <param name="_Left">The left of the viewport.</param> /// <param name="_Top">The top of the viewport.</param> /// <param name="_Right">The right of the viewport.</param> /// <param name="_Bottom">The botton of the viewport.</param> /// <param name="_Near">The closest distance possible to see objects.</param> /// <param name="_Far">The biggest distance possible to see objects.</param> /// <returns>The calling matrix computed to do a orthogonal projection.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp SetToOrthogonalMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp SetToOrthogonalMatrix expected output Matrix4x4& SetToOrthogonalMatrix( const float _Left, const float _Top, const float _Right, const float _Bottom, const float _Near, const float _Far ); /// <summary> /// Get a matrix which do a perspective projection. /// </summary> /// <param name="_Fov">The field of view.</param> /// <param name="_Aspect">The aspect ratio.</param> /// <param name="_Near">The near distance.</param> /// <param name="_Far">The far distance.</param> /// <returns>The computed perspective matrix.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetPerspectiveMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetPerspectiveMatrix expected output static Matrix4x4 GetPerspectiveMatrix( const float _Fov, const float _Aspect, const float _Near, const float _Far ); /// <summary> /// Get a matrix which do an orthogonal projection. /// </summary> /// <param name="_Left">The left of the viewport.</param> /// <param name="_Top">The top of the viewport.</param> /// <param name="_Right">The right of the viewport.</param> /// <param name="_Bottom">The botton of the viewport.</param> /// <param name="_Near">The closest distance possible to see objects.</param> /// <param name="_Far">The biggest distance possible to see objects.</param> /// <returns>The orthogonal matrix.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetOrthogonalMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetOrthogonalMatrix expected output static Matrix4x4 GetOrthogonalMatrix( const float _Left, const float _Top, const float _Right, const float _Bottom, const float _Near, const float _Far ); /// <summary> /// Do a matrix with the scale transformation. /// </summary> /// <param name="_Scale">The scale factor on each axis.</param> /// <returns>The matrix containing the scale transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetScaleMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetScaleMatrix expected output static Matrix4x4 GetScaleMatrix( const Vector3& _Scale ); /// <summary> /// Do a matrix with the rotation transformation. /// </summary> /// <param name="_Angle">The angle in radians.</param> /// <param name="_Axis">The axis to rotate around.</param> /// <returns>The matrix containing the rotation transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetRotationMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetRotationMatrix expected output static Matrix4x4 GetRotationMatrix( const float _Angle, const Vector3& _Axis ); /// <summary> /// Do a matrix with the translation transformation. /// </summary> /// <param name="_Vector">The translation to apply.</param> /// <returns>The matrix containing the translation transformation.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetTranslationMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetTranslationMatrix expected output static Matrix4x4 GetTranslationMatrix( const Vector3& _Vector ); /// <summary> /// Get a matrix which look at a point. /// </summary> /// <param name="_Eye">The eye position.</param> /// <param name="_PointToLookAt">The point position to look at.</param> /// <param name="_UpWorld">The up of the world.</param> /// <returns>The look at matrix.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetLookAtMatrix example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetLookAtMatrix expected output static Matrix4x4 GetLookAtMatrix( const Vector3& _Eye, const Vector3& _PointToLookAt, const Vector3& _UpWorld ); /// <summary>Tranpose the matrix.</summary> /// <returns>Matrix transposed.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Transpose example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Transpose expected output Matrix4x4& Transpose(); /// <summary>Retrieve the transpose of the calling matrix (without modifying it).</summary> /// <returns>The calling matrix transposed.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetTranspose example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetTranspose expected output Matrix4x4 GetTranspose() const; /// <summary>Apply absolute value to each element of the matrix.</summary> /// <returns>Matrix with all element as absolute value.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp Abs example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp Abs expected output Matrix4x4& Abs(); /// <summary>Apply absolute value to each element of the matrix.</summary> /// <returns>Matrix with all element as absolute value.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetAbs example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetAbs expected output Matrix4x4 GetAbs() const; /// <summary>Process the sum of all diagonal elements.</summary> /// <returns>Sum of diagonal elements.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Functionalities.cpp GetTrace example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Functionalities.cpp GetTrace expected output float GetTrace() const; /// <summary>Multiply each element of the matrix with a scalar value.</summary> /// <param name="_Scalar">The scalar value to multiply the matrix with.</param> /// <returns>Matrix multiplied by the <paramref name="_Scalar"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp MulEqual example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp MulEqual expected output Matrix4x4& operator*=( const float& _Scalar ); /// <summary>Divide each element of the matrix with a scalar value.</summary> /// <param name="_Scalar">The scalar value to divide the matrix with.</param> /// <returns>Matrix divided by the <paramref name="_Scalar"/>.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp DivEqual example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp DivEqual expected output Matrix4x4& operator/=( const float& _Scalar ); /// <summary>Add to each element of the matrix a scalar value.</summary> /// <param name="_Scalar">The scalar value to add to the matrix with.</param> /// <returns>Matrix with the <paramref name="_Scalar"/> added to each elements.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp AddEqual example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp AddEqual expected output Matrix4x4& operator+=( const float& _Scalar ); /// <summary>Subtract to each element of the matrix a scalar value.</summary> /// <param name="_Scalar">The scalar value to add to the matrix with.</param> /// <returns>Matrix with the <paramref name="_Scalar"/> subtracted to each elements.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp SubEqual example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp SubEqual expected output Matrix4x4& operator-=( const float& _Scalar ); /// <summary>Multuply a matrix with another one.</summary> /// <remarks> /// Apply : A * B. Where A is the calling matrix and B is /// <paramref name="_MatB"/> /// </remarks> /// <param name="_MatB">The second matrix to multiply the calling one with.</param> /// <returns>The calling matrix multiplied by <paramref name="_MatB"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp MulEqualMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp MulEqualMat expected output Matrix4x4& operator*=( const Matrix4x4& _MatB ); /// <summary>Divide each element calling matrix with the respective elements of another one.</summary>_MatB"/> /// <remarks> /// Dimensions must be the same. /// This operation is NOT the inverse of multiplication. /// It does an element per element division. /// </remarks> /// <param name="_MatB">The second matrix to divide the calling one with.</param> /// <returns> /// The calling matrix with its elements divided by /// the respective elements of <paramref name="_MatB"/> /// </returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp DivEqualMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp DivEqualMat expected output Matrix4x4& operator/=( const Matrix4x4& _MatB ); /// <summary>Add each elemens the calling matrix with the respective elements of another one.</summary> /// <param name="_MatB">The second matrix to add the calling one with.</param> /// <returns> /// The calling matrix with its elements added with /// the respective elements of <paramref name="_MatB"/> /// </returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp AddEqualMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp AddEqualMat expected output Matrix4x4& operator+=( const Matrix4x4& _MatB ); /// <summary>Subtract each elemens the calling matrix with the respective elements of another one.</summary> /// <param name="_MatB">The second matrix to subtract the calling one with.</param> /// <returns> /// The calling matrix with its elements subtracted with /// the respective elements of <paramref name="_MatB"/> /// </returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp SubEqualMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp SubEqualMat expected output Matrix4x4& operator-=( const Matrix4x4& _MatB ); /// <summary>Raise to power of <paramref name="_Power"/> each elements the calling matrix.</summary> /// <param name="_Power">The power factor.</param> /// <returns> /// The calling matrix with its elements raised to /// power of <paramref name="_Power"/> /// </returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp PowEqual example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp PowEqual expected output Matrix4x4& operator^=( const float& _Power ); /// <summary>Retrieve element with linear index</summary> /// <param name="_Index">Linear index of the element.</param> /// <returns>Value at the index</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Access example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Access expected output float operator[]( const Uint32 _Index ) const; /// <summary>Retrieve element with linear index</summary> /// <param name="_Index">Linear index of the element.</param> /// <returns>Value at the index</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Access example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Access expected output float& operator[]( const Uint32 _Index ); /// <summary>Retrieve element with linear index</summary> /// <param name="_Index">Linear index of the element.</param> /// <returns>Value at the index</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Access example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Access expected output float operator()( const Uint32 _Index ) const; /// <summary>Retrieve element with linear index</summary> /// <param name="_Index">Linear index of the element.</param> /// <returns>Value at the index</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Access example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Access expected output float& operator()( const Uint32 _Index ); /// <summary>Retrieve element with row and column indices</summary> /// <param name="_Row">Row index of the element.</param> /// <param name="_Col">Column index of the element.</param> /// <returns>Value at the row and column indices.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Access example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Access expected output float operator()( const Uint32 _Row, const Uint32 _Col ) const; /// <summary>Retrieve element with row and column indices</summary> /// <param name="_Row">Row index of the element.</param> /// <param name="_Col">Column index of the element.</param> /// <returns>Value at the row and column indices.</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Access example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Access expected output float& operator()( const Uint32 _Row, const Uint32 _Col ); /// <summary>Retrieve raw data of the matrix.</summary> /// <returns>Raw data of the matrix</returns> const float* const GetData() const; /// <summary>Retrieve raw data of the matrix.</summary> /// <returns>Raw data of the matrix</returns> float* const GetData(); public: /// <summary> The zero matrix. All values set to 0. /// <para>0 0 0 0</para> /// <para>0 0 0 0</para> /// <para>0 0 0 0</para> /// <para>0 0 0 0</para> /// </summary> static const Matrix4x4 Zero; /// <summary> The identity matrix. All values set to 0 except diagonal. /// <para>1 0 0 0</para> /// <para>0 1 0 0</para> /// <para>0 0 1 0</para> /// <para>0 0 0 1</para> /// </summary> static const Matrix4x4 Identity; private: /// <summary>Data of the matrix, linearly stored.</summary> float m_Mat[16]; }; /// \relatesalso Matrix4x4 /// <summary>Multiply each element of the matrix <paramref name="_Mat"/> with a scalar value.</summary> /// <param name="_Mat">The matrix value to multiply with <paramref name="_Scalar"/>.</param> /// <param name="_Scalar">The scalar value to multiply the matrix with.</param> /// <returns>Matrix multiplied by the <paramref name="_Scalar"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Mul example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Mul expected output AERO_CORE_EXPORT Matrix4x4 operator*( const Matrix4x4& _Mat, const float& _Scalar ); /// \relatesalso Matrix4x4 /// <summary>Divide each element of the matrix <paramref name="_Mat"/> with a scalar value.</summary> /// <param name="_Mat">The matrix value to divide by <paramref name="_Scalar"/>.</param> /// <param name="_Scalar">The scalar value to divide the matrix with.</param> /// <returns>Matrix divided by the <paramref name="_Scalar"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Div example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Div expected output AERO_CORE_EXPORT Matrix4x4 operator/( const Matrix4x4& _Mat, const float& _Scalar ); /// \relatesalso Matrix4x4 /// <summary>Add each element of the matrix <paramref name="_Mat"/> a scalar value.</summary> /// <param name="_Mat">The matrix value to add <paramref name="_Scalar"/>.</param> /// <param name="_Scalar">The scalar value to add to the matrix.</param> /// <returns>Matrix with <paramref name="_Scalar"/> added to each elements</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Add example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Add expected output AERO_CORE_EXPORT Matrix4x4 operator+( const Matrix4x4& _Mat, const float& _Scalar ); /// \relatesalso Matrix4x4 /// <summary>Subtract each element of the matrix <paramref name="_Mat"/> a scalar value.</summary> /// <param name="_Mat">The matrix value to subtract <paramref name="_Scalar"/>.</param> /// <param name="_Scalar">The scalar value to subtract to the matrix.</param> /// <returns>Matrix with <paramref name="_Scalar"/> subtracted to each elements</returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Sub example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Sub expected output AERO_CORE_EXPORT Matrix4x4 operator-( const Matrix4x4& _Mat, const float& _Scalar ); /// \relatesalso Matrix4x4 /// <summary>Multiply a matrix with another one.</summary> /// <remarks> /// Apply : A * B. Where A is <paramref name="_MatA"/> and B is /// <paramref name="_MatB"/> /// </remarks> /// <param name="_MatA">The matrix to multiply with <paramref name="_MatB"/>.</param> /// <param name="_MatB">The matrix to multiply <paramref name="_MatA"/> with.</param> /// <returns>The result of the multiplication between <paramref name="_MatA"/> and <paramref name="_MatB"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp MulMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp MulMat expected output AERO_CORE_EXPORT Matrix4x4 operator*( const Matrix4x4& _MatA, const Matrix4x4& _MatB ); /// \relatesalso Matrix4x4 /// <summary>Divide a matrix with another one. (Element by element)</summary> /// <param name="_MatA">The matrix to divide with <paramref name="_MatB"/>.</param> /// <param name="_MatB">The matrix to divide <paramref name="_MatA"/> with.</param> /// <returns>The result of the division of <paramref name="_MatA"/> with <paramref name="_MatB"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp DivMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp DivMat expected output AERO_CORE_EXPORT Matrix4x4 operator/( const Matrix4x4& _MatA, const Matrix4x4& _MatB ); /// \relatesalso Matrix4x4 /// <summary>Add a matrix to another one. (Element by element)</summary> /// <param name="_MatA">The matrix to add to <paramref name="_MatB"/>.</param> /// <param name="_MatB">The matrix to add to <paramref name="_MatA"/>.</param> /// <returns>The result of the addition of <paramref name="_MatA"/> and <paramref name="_MatB"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp AddMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp AddMat expected output AERO_CORE_EXPORT Matrix4x4 operator+( const Matrix4x4& _MatA, const Matrix4x4& _MatB ); /// \relatesalso Matrix4x4 /// <summary>Subtract a matrix to another one. (Element by element)</summary> /// <param name="_MatA">The matrix to subtract to <paramref name="_MatB"/>.</param> /// <param name="_MatB">The matrix to subtract to <paramref name="_MatA"/>.</param> /// <returns>The result of the subtraction of <paramref name="_MatA"/> and <paramref name="_MatB"/></returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp SubMat example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp SubMat expected output AERO_CORE_EXPORT Matrix4x4 operator-( const Matrix4x4& _MatA, const Matrix4x4& _MatB ); /// \relatesalso Matrix4x4 /// <summary>Raise to power of <paramref name="_Power"/> each elements of <paramref name="_Mat"/>.</summary> /// <param name="_Mat">The matrix to raised to power of <paramref name="_Power"/>.</param> /// <param name="_Power">The power factor.</param> /// <returns> /// <paramref name="_Mat"/> with its elements raised to /// power of <paramref name="_Power"/> /// </returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Pow example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Pow expected output AERO_CORE_EXPORT Matrix4x4 operator^( const Matrix4x4& _Mat, const float& _Power ); /// \relatesalso Matrix4x4 /// <summary>Test if two matrices are the same.</summary> /// <param name="_MatA">First matrix to compare.</param> /// <param name="_MatB">Seconde matrix to compare</param> /// <returns> /// True if <paramref name="_MatA"/> and <paramref name="_MatB"/> have the same values. /// False otherwise. /// </returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp Equal example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp Equal expected output AERO_CORE_EXPORT Bool operator==( const Matrix4x4& _MatA, const Matrix4x4& _MatB ); /// \relatesalso Matrix4x4 /// <summary>Test if two matrices are different.</summary> /// <param name="_MatA">First matrix to compare.</param> /// <param name="_MatB">Seconde matrix to compare</param> /// <returns> /// True if <paramref name="_MatA"/> and <paramref name="_MatB"/> have NOT the same values. /// False otherwise. /// </returns> /// \par Example : /// \snippet UnitTestMatrix4x4/Operators.cpp NotEqual example /// \par Expected Output : /// \snippetdoc UnitTestMatrix4x4/Operators.cpp NotEqual expected output AERO_CORE_EXPORT Bool operator!=( const Matrix4x4& _MatA, const Matrix4x4& _MatB ); /// <summary> /// Convert a matrix 4x4 to a string. /// </summary> /// <param name="_Color">Matrix 4x4 to convert.</param> /// <returns>Matrix 4x4 as a C++ string. ( Format : x x x x\nx x x x\nx x x x\nx x x x ).</returns> AERO_CORE_EXPORT std::string ToString( const Matrix4x4& _Matrix ); } // ae /// <summary> /// Convert a matrix 4x4 to a string and push it in the out stream. /// </summary> /// <param name="_Color">Matrix 4x4 to convert and push to the out stream.</param> /// <returns>Out stream.</returns> AERO_CORE_EXPORT std::ostream& operator<<( std::ostream& os, const ae::Matrix4x4& _Matrix );
#include "Zork_Def.hpp" #include <vector> #include "Object.hpp" #include "Room.hpp" #include "Container.hpp" #include "Creature.hpp" #include "Item.hpp" #include "Map.hpp" #include "main.hpp" using namespace std; vector<string> WordParser(const string &input) { vector<string> rtvl; size_t found,pre; string tmp; pre = 0; found = input.find_first_of(' '); while(found!=string::npos){ tmp = string(input,pre,found); rtvl.push_back(tmp); pre = found; found = input.find_first_of(' ',found+1); } if(rtvl[0] == "turn"){ rtvl[0] = "turn on"; rtvl.erase(rtvl.begin()+1); } return rtvl; } Action ActionParser(const string& input) { vector<string> str = WordParser(input); Action rtvl; Object& obj = ZorkMap->get(str[1]); reference_wrapper<Object> Obj = ref(obj); if(str[0]=="Update"){ string newstate = str[3]; rtvl = [Obj,newstate](const string& s){ Obj.get().Update(newstate); }; }else if(str[0]=="Add"){ Object& owner = ZorkMap->get(str[3]); reference_wrapper<Object> Owner = ref(owner); rtvl = [Obj,Owner](const string& s){ Owner.get().Add(Obj); }; }else if(str[0]=="Delete"){ rtvl = [Obj](const string& s){ Obj.get().Delete(); }; }else if(str[0]=="Remove"){ Object& owner = ZorkMap->get(str[3]); reference_wrapper<Object> Owner = ref(owner); rtvl = [Obj,Owner](const string& s){ Owner.get().Remove(Obj); }; }else{ rtvl = [Obj,input](const string& s){ Obj.get().React(input); }; } return rtvl; } Condition ConditionParser(const string& obj,const string& status) { reference_wrapper<Object> Obj = ref(ZorkMap->get(obj)); return [Obj,status](){ return (Obj.get().getstatus())==status; }; } Condition ConditionParser(bool has,const string& obj,const string& owner) { reference_wrapper<Object> Obj = ref(ZorkMap->get(obj)); reference_wrapper<Object> Owner = ref(ZorkMap->get(owner)); return [Obj,Owner,has](){ return has^(Owner.get().Has(Obj.get())); }; } void CommandParser(const string& cmd) { vector<string> str = WordParser(cmd); if(str[0]=="n"||str[0]=="s"||str[0]=="e"||str[0]=="w"){ ZorkMap->getCurrentRoom().React(cmd); }else if(str[0]=="i"){ ZorkMap->getInventory().PrintItem(); }else{ ZorkMap->get(str[1]).React(cmd); } }
#include <cstdio> #include <iostream> using namespace std; void shuchu(int a[], int n) { for (int i = 1; i <= n; i++) printf("%d ", a[i]); printf("\n"); } void SelectSort(int a[], int n) { cout << "-------Chosen-------" << endl; int k = 0; int temp; for (int i = 1; i <= n; i++) { temp = a[i]; k = i; for (int j = i; j <= n; j++) { if (a[k] > a[j]) k = j; } a[i] = a[k]; a[k] = temp; shuchu(a, n); } } void InsertSort(int a[], int n) { cout << "-------Insert-------" << endl; for (int i = 2; i <= n; i++) { int temp = a[i], j = i; while (j > 1 && temp < a[j-1]) { a[j] = a[j-1]; j --; } a[j] = temp; shuchu(a, n); } } int main(){ int x; int n = 1; int a[1000] = {0}; char c = '\0'; while (c != '\n') { scanf("%d%c", &x, &c); a[n] = x; n ++; } n --; InsertSort(a, n); return 0; }
//================================================================================================== // Name : lrmain.h // Author : Ken Cheng // Copyright : This work is licensed under the Creative Commons // Attribution-NonCommercial-ShareAlike 4.0 International License. To view a copy of this // license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/. // Description : //================================================================================================== #ifndef LRMAIN_H #define LRMAIN_H #include <cstdlib> #include <iostream> #include <fstream> #include <float.h> #include <math.h> #include <fstream> #include <sstream> #include "Configuration.h" #include "LikelihoodSolver/LikelihoodSolver.h" #include "utils/FileReaderUtil.h" #include "utils/ProbabilityUtil.h" using namespace std; using namespace LabRetriever; void outputData(const set<string>& lociToCheck, const vector<LikelihoodSolver*>& likelihoodSolvers, const map<Race, vector<map<string, double> > >& raceToSolverIndexToLocusLogProb, const map<Race, vector<double> >& raceToSolverIndexToLogProb, const vector<Race> races, const string& outputFileName); map<Race, vector<double> > run(const string& inputFileName, const string& outputFileName, vector<LikelihoodSolver*> likelihoodSolvers); #endif // LRMAIN_H
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #include <algorithm> #include <fwTools/ProgressToLogger.hpp> #include <fwRuntime/EConfigurationElement.hpp> #include <fwData/PatientDB.hpp> #include <fwData/location/Folder.hpp> #include <fwData/location/SingleFile.hpp> #include <fwData/location/MultiFiles.hpp> #include <fwCore/base.hpp> #include <fwServices/Base.hpp> #include <fwServices/macros.hpp> #include <fwServices/registry/ObjectService.hpp> #include <fwServices/IEditionService.hpp> #include <fwComEd/PatientDBMsg.hpp> #include <fwGui/dialog/MessageDialog.hpp> #include <fwGui/dialog/LocationDialog.hpp> #include <fwGui/dialog/ProgressDialog.hpp> #include <fwGui/Cursor.hpp> #include <io/IReader.hpp> // Defined QT_NO_KEYWORDS because of conflict with boost::signals namespace. #ifndef QT_NO_KEYWORDS #define QT_NO_KEYWORDS #define QT_NO_KEYWORDS_FWDEF #endif #include <QApplication> #include "ioGdcmQt/ui/DicomdirEditor.hpp" #include "ioGdcmQt/DicomdirPatientDBReaderService.hpp" #include "vtkGdcmIO/DicomPatientDBReader.hpp" #ifdef QT_NO_KEYWORDS_FWDEF #undef QT_NO_KEYWORDS #undef QT_NO_KEYWORDS_FWDEF #endif namespace ioGdcm { REGISTER_SERVICE( ::io::IReader , ::ioGdcm::DicomdirPatientDBReaderService , ::fwData::PatientDB ) ; //------------------------------------------------------------------------------ DicomdirPatientDBReaderService::DicomdirPatientDBReaderService() throw() : m_bServiceIsConfigured(false), m_dicomdirPath("") { // readerList.insetr(std::make_pair(::ioGdcm::DCMTK, "Dicom Reader (DCMTK)")); // readerList.insetr(std::make_pair(::ioGdcm::GDCM, "Dicom Reader (GDCM)")); // Comming soon // readerList.insert(std::make_pair(::ioGdcm::ITK_GDCM, "Dicom Reader (ITK/gdcm)")); // readerList.insert(std::make_pair(::ioGdcm::IRCAD, "Dicom Reader (Ircad)")); readerList.insert(std::make_pair(::ioGdcm::VTK_GDCM, "Dicom Reader (VTK/gdcm)")); } //------------------------------------------------------------------------------ DicomdirPatientDBReaderService::~DicomdirPatientDBReaderService() throw() {} //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::configureWithIHM() { SLM_TRACE_FUNC(); static ::boost::filesystem::path _sDefaultPath; // Select the DICOMDIR ::fwGui::dialog::LocationDialog dialogFile; dialogFile.setTitle("Choose a DICOMDIR file "); dialogFile.setDefaultLocation( ::fwData::location::Folder::New(_sDefaultPath) ); dialogFile.addFilter("DICOMDIR", "DICOMDIR DICOMDIR.* dicomdir dicomdir.*"); dialogFile.setOption(::fwGui::dialog::ILocationDialog::READ); dialogFile.setOption(::fwGui::dialog::ILocationDialog::FILE_MUST_EXIST); ::fwData::location::SingleFile::sptr result; result= ::fwData::location::SingleFile::dynamicCast( dialogFile.show() ); if (result) { _sDefaultPath = result->getPath(); m_dicomdirPath = result->getPath(); // Open the Dicom dir editor ::ioGdcm::ui::DicomdirEditor editor(qApp->activeWindow(), m_dicomdirPath); editor.setReader(readerList); m_readerAndFilenames = editor.show(); if(!m_readerAndFilenames.second.empty()) { m_bServiceIsConfigured = true; } } } //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::info(std::ostream &_sstream ) { _sstream << "DicomdirPatientDBReaderService::info" ; } //------------------------------------------------------------------------------ std::vector< std::string > DicomdirPatientDBReaderService::getSupportedExtensions() { std::vector< std::string > extensions ; extensions.push_back("DICOMDIR"); extensions.push_back("DICOMDIR."); return extensions ; } //------------------------------------------------------------------------------ std::string DicomdirPatientDBReaderService::getSelectorDialogTitle() { return "Choose a DICOMDIR"; } //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::starting() throw(::fwTools::Failed) { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::stopping() throw(::fwTools::Failed) { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::configuring() throw(::fwTools::Failed) { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::updating( ::boost::shared_ptr< const ::fwServices::ObjectMsg > _msg ) throw(::fwTools::Failed) { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::updating() throw(::fwTools::Failed) { SLM_TRACE_FUNC(); ::fwData::PatientDB::sptr patientDB; if( m_bServiceIsConfigured ) { switch(m_readerAndFilenames.first) { // case ::ioGdcm::DCMTK: // ::dcmtkIO::dcmtkPatientDBReader readerDicomPatientDb; // readerDicomPatientDb.readFiles(m_readerAndFilenames.second); // break; // case ::ioGdcm::GDCM : // // (GDCM) to come // ::gdcmIO::DicomPatientDBReader readerDicomPatientDb; // readerDicomPatientDb.readFiles(m_readerAndFilenames.second); // break; // case ::ioGdcm::ITK_GDCM : // // ITK/GDCM // // Some work is necessary for using itkIO::DicomPatientDBReader with list of files. // patientDB = createPatientDB <::itkIO::DicomPatientDBReader>( m_readerAndFilenames.second); // break; // case ::ioGdcm::IRCAD : // ::dicomIO::DicomPatientDBReader readerDicomPatientDb; // readerDicomPatientDb.readFiles(m_readerAndFilenames.second); break; case ::ioGdcm::VTK_GDCM : //(VTK/GDCM) patientDB = createPatientDB < ::vtkGdcmIO::DicomPatientDBReader > ( m_readerAndFilenames.second); break; } if( patientDB->getNumberOfPatients() > 0 ) { // Retrieve dataStruct associated with this service ::fwData::PatientDB::sptr associatedPatientDB = this->getObject< ::fwData::PatientDB >(); SLM_ASSERT("associatedPatientDB not instanced", associatedPatientDB); associatedPatientDB->shallowCopy( patientDB ) ; ::fwGui::Cursor cursor; cursor.setCursor(::fwGui::ICursor::BUSY); this->notificationOfDBUpdate(); cursor.setDefaultCursor(); } else { ::fwGui::dialog::MessageDialog::showMessageDialog( "Image Reader","This file can not be read. Retry with another file reader.", ::fwGui::dialog::IMessageDialog::WARNING); } } } //------------------------------------------------------------------------------ // Note : Using the template is for adding other readers like itkIO::DicomPatientDBReader // so READER could be for example ::vtkGdcmIO::DicomPatientDBReader or ::itkIO::DicomPatientDBReader template < typename READER> ::fwData::PatientDB::sptr DicomdirPatientDBReaderService::createPatientDB(const std::vector< ::boost::filesystem::path>& filenames) { SLM_TRACE_FUNC(); typename READER::NewSptr reader; ::fwData::PatientDB::NewSptr dummy; reader->setObject( dummy ); reader->setFiles(filenames); try { ::fwGui::dialog::ProgressDialog progressMeterGUI("Loading Dicom Image"); reader->addHandler( progressMeterGUI ); reader->read(); } catch (const std::exception & e) { std::stringstream ss; ss << "Warning during loading : " << e.what(); ::fwGui::dialog::MessageDialog::showMessageDialog( "Warning", ss.str(), ::fwGui::dialog::IMessageDialog::WARNING); } catch( ... ) { ::fwGui::dialog::MessageDialog::showMessageDialog( "Warning", "Warning during loading", ::fwGui::dialog::IMessageDialog::WARNING); } return reader->getConcreteObject(); } //------------------------------------------------------------------------------ void DicomdirPatientDBReaderService::notificationOfDBUpdate() { SLM_TRACE_FUNC(); ::fwData::PatientDB::sptr pDPDB = this->getObject< ::fwData::PatientDB >(); SLM_ASSERT("pDPDB not instanced", pDPDB); ::fwComEd::PatientDBMsg::NewSptr msg; msg->addEvent( ::fwComEd::PatientDBMsg::NEW_PATIENT ); ::fwServices::IEditionService::notify(this->getSptr(), pDPDB, msg); } //------------------------------------------------------------------------------ } // namespace ioGdcm
#include "Scheme_values/Nil.hpp" #include "Environment.hpp" #include "Scheme_values/Scheme_value.hpp" #include <memory> Nil::Nil() { } std::string Nil::as_string() const { return "nil"; }
// Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IntTools_WLineTool_HeaderFile #define _IntTools_WLineTool_HeaderFile #include <GeomAdaptor_Surface.hxx> #include <IntPatch_WLine.hxx> #include <IntPatch_SequenceOfLine.hxx> class TopoDS_Face; class GeomInt_LineConstructor; class IntTools_Context; //! IntTools_WLineTool provides set of static methods related to walking lines. class IntTools_WLineTool { public: DEFINE_STANDARD_ALLOC Standard_EXPORT static Standard_Boolean NotUseSurfacesForApprox(const TopoDS_Face& aF1, const TopoDS_Face& aF2, const Handle(IntPatch_WLine)& WL, const Standard_Integer ifprm, const Standard_Integer ilprm); Standard_EXPORT static Standard_Boolean DecompositionOfWLine(const Handle(IntPatch_WLine)& theWLine, const Handle(GeomAdaptor_Surface)& theSurface1, const Handle(GeomAdaptor_Surface)& theSurface2, const TopoDS_Face& theFace1, const TopoDS_Face& theFace2, const GeomInt_LineConstructor& theLConstructor, const Standard_Boolean theAvoidLConstructor, const Standard_Real theTol, IntPatch_SequenceOfLine& theNewLines, const Handle(IntTools_Context)& ); }; #endif
#include <fstream> #include <sstream> #include <bcm2835.h> #include <signal.h> #include <unistd.h> using namespace std; using u16 = uint16_t; string song; std::string slurp(const char *filename) { std::ifstream in; in.open(filename, std::ifstream::in | std::ifstream::binary); std::stringstream sstr; sstr << in.rdbuf(); in.close(); return sstr.str(); } void dac_write(uint16_t value) { if(value>4095) value=4095; value |= 0b0011000000000000; char buf[2]; buf[0] = value >>8; buf[1] = value & 0xff; bcm2835_spi_writenb(buf, 2); } int i =0; //bool finis = false; void alarm_isr(int sig_num) { if(sig_num != SIGALRM) return; if(i == song.size()) { bcm2835_spi_end(); bcm2835_close(); exit(0); } dac_write((u16) song[i++] << 4); } int main() { //string song{slurp("song.raw")}; song = slurp("song16k.raw"); bcm2835_init(); bcm2835_spi_begin(); bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_64); // ~ 4 MHz bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_16); //bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_1024); bcm2835_spi_chipSelect(BCM2835_SPI_CS0); // The default bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW); // the default signal(SIGALRM, alarm_isr); float freq = 1'000'000 / 16'000; ualarm(freq, freq); /* for(unsigned char c : song) { dac_write((uint16_t) c << 4); bcm2835_delayMicroseconds(125); } */ while(1) sleep(10); bcm2835_spi_end(); bcm2835_close(); return 0; }
#include "FFT_F.h" #include "memory.h" #include <math.h> #include <stdio.h> #define _CRT_FUNCTIONS_REQUIRED extern void fft(double pr[], double pi[], int n, double fr[], double fi[]); //////////////////////////////////////////////////////// // 函数名称: // FFT_fix64 // 函数功能: // FFT运算 // 形参: // 1.RD0:输入序列指针,复数格式 // 2.RD1:输出序列指针,复数格式 // 返回值: // RD0:增益系数 //////////////////////////////////////////////////////// Sub_AutoField FFT_fix64 { double pr[64], pi[64], fr[64], fi[64], x; RA0 = RD0; RA1 = RD1; for (int i = 0; i <= 63; i++) { RD0 = GET_M(RA0 + i * MMU_BASE); x = floor(RD0.m_data / 65536); x = x / 32768; pr[i] = x; x = *(short*)(&RD0.m_data); //低16bit x = x / 32768; pi[i] = x; } fft(pr, pi, 64, fr, fi); //fft //限幅判溢出 int k = RD0.m_data; // double max0 = 0; // double max1 = 0; // for (int i = 0; i < 64; i++) // { // if (fabs(fr[i]) > fabs(max0)) // max0 = fabs(fr[i]); // if (fabs(fi[i]) > fabs(max1)) // max1 = fabs(fi[i]); // } // if (fabs(max0) < fabs(max1)) // max0 = max1; // if (max0 < 1) // { // k = 0; // } // else // { // k = log2(max0) + 1; // } // int l = 1 << k; // for (int i = 0; i < 64; i++) // { // fr[i] = fr[i] / l; // fi[i] = fi[i] / l; // } for (int i = 0; i <= 63; i++) { x = fr[i]; x = x * 32768; RD0 = x; RD0 <<= 16; x = fi[i]; x = x * 32768; RD1 = x; RD0 += RD1; SET_M(RA1 + i * MMU_BASE, RD0); } RD0 = k; Return_AutoField(0); } ////////////////////////////////////////////////////////// //// 函数名称: //// FFT_32X128 //// 函数功能: //// 128点宽位FFT运算 //// 形参: //// 1.RD0:输入序列指针,32bit格式,顺序为R0;I0;R1;I1... //// 返回值: //// RD0:增益系数 ////////////////////////////////////////////////////////// //Sub_AutoField FFT_Fast128 //{ // double pr[128], pi[128], fr[128], fi[128], x; // // RA0 = RD0; // // for (int i = 0; i < 128; i++) // { // RD0 = M[RA0++]; // x = RD0.m_data; // x = x / 32768; // pr[i] = x; // RD0 = M[RA0++]; // x = RD0.m_data; // x = x / 32768; // pi[i] = x; // } // fft(pr, pi, 128, fr, fi); //fft // // //限幅判溢出 // int k = 0; // double max0 = 0; // double max1 = 0; // for (int i = 0; i < 128; i++) // { // if (fabs(fr[i]) > fabs(max0)) // max0 = fabs(fr[i]); // if (fabs(fi[i]) > fabs(max1)) // max1 = fabs(fi[i]); // } // if (fabs(max0) < fabs(max1)) // max0 = max1; // if (max0<65536) // { // k = 0; // } // else // { // k = log2(max0/65536) + 1; // } // // // int l = 1 << k; // for (int i = 0; i < 128; i++) // { // fr[i] = fr[i] / l; // fi[i] = fi[i] / l; // } // // // for (int i = 0; i < 128; i++) // { // x = fr[i]; // x = x * 32768; // RD0 = x; // M[RA1++] = RD0; // // x = fi[i]; // x = x * 32768; // RD0 = x; // M[RA1++] = RD0; // } // RD0 = k; // Return_AutoField(0); // //} //////////////////////////////////////////////////////// // 函数名称: // FFT_Fast128 // 函数功能: // 128点FFT运算,采用128点专用加速器 // 形参: // 1.RD0:输入序列指针,复数格式 // 2.RD1:输出序列指针,复数格式 // 返回值: // RD0:增益系数 //////////////////////////////////////////////////////// Sub_AutoField FFT_Fast128 { double pr[128], pi[128], fr[128], fi[128], x; RA0 = RD0; RA1 = RD1; for (int i = 0; i < 128; i++) { RD0 = GET_M(RA0 + i * MMU_BASE); x = floor(RD0.m_data / 65536); x = floor(x / 2); x = x / 32768; pr[i] = x; x = *(short*)(&RD0.m_data); //低16bit x = floor(x / 2); x = x / 32768; pi[i] = x; } fft(pr, pi, 128, fr, fi); //fft //限幅判溢出 int k = RD0.m_data; double max0 = 0; double max1 = 0; for (int i = 0; i < 128; i++) { if (fabs(fr[i]) > fabs(max0)) max0 = fabs(fr[i]); if (fabs(fi[i]) > fabs(max1)) max1 = fabs(fi[i]); } if (fabs(max0) < fabs(max1)) max0 = max1; if (max0<1) { k = 0; } else { k = log2(max0) + 1; } int l = 1 << k; for (int i = 0; i < 128; i++) { fr[i] = fr[i] / l; fi[i] = fi[i] / l; } for (int i = 0; i < 128; i++) { x = fr[i]; x = x * 32768; RD0 = x; RD0 <<= 16; x = fi[i]; x = x * 32768; RD1 = x; RD1 &= 0xffff; RD0 += RD1; SET_M(RA1 + i * MMU_BASE, RD0); } RD0 = k; Return_AutoField(0); } ///////////////////////////////////////////////////////////////////////////// // 名称: // fft // 功能: // fft计算 // 参数: // double pr[n] 存放n个采样输入的实部,返回离散傅里叶变换的摸 // double pi[n] 存放n个采样输入的虚部 // double fr[n] 返回离散傅里叶变换的n个实部 // double fi[n] 返回离散傅里叶变换的n个虚部 // int n 采样点数 // int k 满足n = 2^k // 返回值值: // 无 ////////////////////////////////////////////////////////////////////////////// void fft(double pr[], double pi[], int n, double fr[], double fi[]) { RD0 = 1; int k = log2(n); int it, m, is, i, j, nv, l0; double p, q, s, vr, vi, poddr, poddi; //FILE* fo = fopen("Out.txt", "w");//打印中间量 for (it = 0; it <= n - 1; it++) //将pr[0]和pi[0]循环赋值给fr[]和fi[] { m = it; is = 0; for (i = 0; i <= k - 1; i++) { j = m / 2; is = 2 * is + (m - 2 * j); m = j; } fr[it] = pr[is]; fi[it] = pi[is]; } // fprintf(fo, "//逆序结果\r"); // for (int qq = 0; qq < 128; qq++) // { // int x = fr[qq] * 32768; // int y = fi[qq] * 32768; //x = (x << 16) + (y & 0xffff); // fprintf(fo, "%08x\r", x); // } pr[0] = 1.0; pi[0] = 0.0; p = 6.283185306 / (1.0 * n); pr[1] = cos(p); //将w=e^-j2pi/n用欧拉公式表示 pi[1] = -sin(p); for (i = 2; i <= n - 1; i++) //计算pr[],系数 { p = pr[i - 1] * pr[1]; q = pi[i - 1] * pi[1]; s = (pr[i - 1] + pi[i - 1]) * (pr[1] + pi[1]); pr[i] = p - q; pi[i] = s - p - q; } //fprintf(fo, "//系数表\r"); //for (int qq = 0; qq < 128; qq++) //{ // int x = pr[qq] * 32768; // int y = pi[qq] * 32768; // x = (x << 16) + (y & 0xffff); // fprintf(fo, "%08x\r", x); //} for (it = 0; it <= n - 2; it = it + 2)//第一轮蝶形 { vr = fr[it]; vi = fi[it]; fr[it] = vr + fr[it + 1]; fi[it] = vi + fi[it + 1]; fr[it + 1] = vr - fr[it + 1]; fi[it + 1] = vi - fi[it + 1]; } //fprintf(fo, "//第一轮蝶形\r"); //for (int qq = 0; qq < 128; qq++) //{ // int x = fr[qq] * 32768; // int y = fi[qq] * 32768; // x = (x << 16) + (y & 0xffff); // fprintf(fo, "%08x\r", x); //} m = n / 2; nv = 2; for (l0 = k - 2; l0 >= 0; l0--) //蝴蝶操作 { m = m / 2; nv = 2 * nv; for (it = 0; it <= (m - 1) * nv; it = it + nv) for (j = 0; j <= (nv / 2) - 1; j++) { p = pr[m * j] * fr[it + j + nv / 2]; int xx = p * 32768;//涉及xx的注释仅用作与硬件机制相同,但会降低精度,同matlab结果验证时注释掉xx p = xx;//xx p = p / 32768;//xx q = pi[m * j] * fi[it + j + nv / 2]; xx = q * 32768;//xx q = xx;//xx q = q / 32768;//xx s = pr[m * j] + pi[m * j]; s = s * (fr[it + j + nv / 2] + fi[it + j + nv / 2]); xx = s * 32768;//xx s = xx;//xx s = s / 32768;//xx poddr = p - q; poddi = s - p - q; fr[it + j + nv / 2] = fr[it + j] - poddr; fi[it + j + nv / 2] = fi[it + j] - poddi; fr[it + j] = fr[it + j] + poddr; fi[it + j] = fi[it + j] + poddi; } //fprintf(fo, "//第%d轮蝶形\r", 7-l0); //for (int qq = 0; qq < 128; qq++) //{ // int x = fr[qq] * 32768; // int y = fi[qq] * 32768; // x = (x << 16) + (y & 0xffff); // fprintf(fo, "%08x\r", x); //} //更符合硬件模式的判溢出机制 // int order = 0; // for (int ii = 0; ii < n; ii++) // { // if (fabs(fr[ii]) >= 0.25) // order = 1; // if (fabs(fi[ii]) >= 0.25) // order = 1; // } // if (order == 1) // { // for (int ii = 0; ii < n; ii++) // { //fr[ii] = fr[ii] / 2; //fi[ii] = fi[ii] / 2; // RD0++; // } // } } for (i = 0; i <= n - 1; i++) { pr[i] = sqrt(fr[i] * fr[i] + fi[i] * fi[i]); //幅值计算 } //fclose(fo); return; }
#ifndef SCENE_SEGMENTATION_NODE_H #define SCENE_SEGMENTATION_NODE_H #include <ros/ros.h> #include <std_msgs/String.h> #include <sensor_msgs/PointCloud2.h> #include <geometry_msgs/PoseStamped.h> #include <geometry_msgs/PoseArray.h> #include <tf/transform_listener.h> #include "mcr_scene_segmentation/clustered_point_cloud_visualizer.h" #include "mcr_scene_segmentation/bounding_box_visualizer.h" #include <mcr_scene_segmentation/label_visualizer.h> #include "mcr_scene_segmentation/cloud_accumulation.h" #include <dynamic_reconfigure/server.h> #include <mcr_scene_segmentation/SceneSegmentationConfig.h> #include <mcr_perception_msgs/ObjectList.h> using mcr::visualization::BoundingBoxVisualizer; using mcr::visualization::ClusteredPointCloudVisualizer; using mcr::visualization::LabelVisualizer; using mcr::visualization::Color; class SceneSegmentationNode { private: ros::NodeHandle nh_; ros::Publisher pub_debug_; ros::Publisher pub_boxes_; ros::Publisher pub_object_list_; ros::Publisher pub_event_out_; ros::Publisher pub_poses_1; ros::Publisher pub_poses_2; ros::Publisher marker_pub; ros::Subscriber sub_cloud_; ros::Subscriber sub_event_in_; ros::ServiceClient recognize_service; dynamic_reconfigure::Server<mcr_scene_segmentation::SceneSegmentationConfig> server_; tf::TransformListener transform_listener_; SceneSegmentation scene_segmentation_; CloudAccumulation::UPtr cloud_accumulation_; BoundingBoxVisualizer bounding_box_visualizer_; ClusteredPointCloudVisualizer cluster_visualizer_; LabelVisualizer label_visualizer_; bool add_to_octree_; //Flag to select the use of OCTREE double threshold; //threshold to compare poses and bag them std::string frame_id_; int object_id_; double octree_resolution_; bool add_new_cloud_; //Flag to add new point cloud PointCloud::Ptr main_cloud; //Pointer to store the point cloud bool get_plane_once_; //Flag to create a plance only once PointCloud::ConstPtr plane_cloud; PointCloud::Ptr circle_cloud; bool perform_segmentation; std::vector< std::vector<geometry_msgs::PoseStamped> > mul_Poses; PointCloud::Ptr test; visualization_msgs::Marker marker; bool create_circles_; private: void pointcloudCallback(const sensor_msgs::PointCloud2::ConstPtr &msg); void eventCallback(const std_msgs::String::ConstPtr &msg); void config_callback(mcr_scene_segmentation::SceneSegmentationConfig &config, uint32_t level); geometry_msgs::PoseArray segment(); void multiple_segmentations(); geometry_msgs::PoseStamped getPose(const BoundingBox &box); std::vector<geometry_msgs::PoseStamped> generateMockupCirclePoses(double cx, double cy, double radius, double start_angle, double end_angle); PointCloud::Ptr pose_to_pointcloud(const PointCloud::Ptr circle_cloud,std::vector<geometry_msgs::PoseStamped> pose_list); std::vector< std::vector<geometry_msgs::PoseStamped> > trackPoses(); // std::vector< std::vector<geometry_msgs::PoseStamped> > trackMultiplePoses(); public: SceneSegmentationNode(); virtual ~SceneSegmentationNode(); }; #endif /* SCENE_SEGMENTATION_NODE_H */
vector<pii> g[maxn]; int v[maxn]; int dis[maxn]; void prim() { memset(v,0,sizeof(v)); for(int i=1; i<=n; i++) { dis[i]=INF; } dis[1]=0; int ans=0; for(int i=1; i<=n; i++) { int mark=-1; for(int j=1; j<=n; j++) { if(!v[j]) { if(mark==-1) mark=j; else if(dis[j]<dis[mark]) mark=j; } } if(mark==-1) break; v[mark]=1; ans+=dis[mark]; for(int j=0; j<g[mark].size(); i++) { if(!v[g[mark][j].first]) { int x=g[mark][j].first; dis[x]=min(dis[x],g[mark][j].second); } } } return ans; }
#ifndef __NewprojectPlugin__ #define __NewprojectPlugin__ #include "plugin.h" #include "NewProjectWizard.h" #include "globals.h" #include "event_notifier.h" #include "dirsaver.h" #include "buildmanager.h" #include "cl_standard_paths.h" #include "clZipReader.h" #include "ZipDialog.h" #include <wx/dir.h> #include <wx/filefn.h> class NewprojectPlugin : public IPlugin { public: NewprojectPlugin(IManager *manager); virtual ~NewprojectPlugin(); //-------------------------------------------- //Abstract methods //-------------------------------------------- virtual void CreateToolBar(clToolBar* toolbar); /** * @brief Add plugin menu to the "Plugins" menu item in the menu bar */ virtual void CreatePluginMenu(wxMenu *pluginsMenu); /** * @brief Unplug the plugin. Perform here any cleanup needed (e.g. unbind events, destroy allocated windows) */ virtual void UnPlug(); void OnWizard(wxCommandEvent& event); void OnUnzip(wxCommandEvent& event); void OnNewProjectUI(wxUpdateUIEvent& event); void CreateProject(ProjectData& data, const wxString& workspaceFolder); }; #endif //NewprojectPlugin
#ifndef LINCOMB_H #define LINCOMB_H #include <iostream> #include <stdlib.h> #include <vector> #include <math.h> #include "dep_gui/matrix.h" #define PI 3.14159265 using namespace std; class timeFunction { public: virtual double out(double time) = 0; virtual string type() = 0; }; class step_: public timeFunction { public: double out(double time){ if (time > t) { return 1.0*A; } else { return 0.0; } } void setParams(double cutoff, double amplitude){ t = cutoff; A = amplitude;} string type(){return "step";} private: double t, A; }; class window_: public timeFunction { public: double out(double time){ return ON.out(time) + OFF.out(time); } void setParams(double t_start, double t_end){ t_on = t_start; t_off = t_end; ON.setParams(t_on, 1.0); OFF.setParams(t_off, -1.0); } string type(){return "window";} private: double t_on, t_off; step_ ON, OFF; }; class ramp_: public timeFunction { public: double out(double time){ return m*(time-phi); } void setParams(double slope, double phase){ m = slope; phi = phase; } string type(){return "ramp";} private: double m, phi; }; class sine_: public timeFunction { public: double out(double time){ return A*sin(2*PI*f*time+phi); } void setParams(double amplitude, double frequency, double phase){ A = amplitude; f = frequency; phi = phase; } string type(){return "sine";} private: double A, f, phi; }; class function_ { public: void setPeriod(double period){ T = period; } double getPeriod(){ return T;} void addStep(step_ s){ steps.push_back(s); //ROS_INFO("%p",&steps[steps.size()-1]); //f.push_back(&steps[steps.size()-1]); //ROS_INFO("%p",f[f.size()-1]); } void addRamp(ramp_ r){ ramps.push_back(r); genF(); } void addSine(sine_ s){ sines.push_back(s); genF(); } void addWindow(window_ win){ w.push_back(win); genF(); } void clear(){ steps.clear(); ramps.clear(); sines.clear(); f.clear(); w.clear(); } void genF(){ f.clear(); for (int i = 0; i < steps.size(); i++){ f.push_back(&steps[i]); } for (int i = 0; i < ramps.size(); i++){ f.push_back(&ramps[i]); } for (int i = 0; i < sines.size(); i++){ f.push_back(&sines[i]); } } double out(double time){ double weight = 0;//, fnc, win; genF(); for (int i = 0; i < f.size(); i++){ //cout << "i: " << i << "\n"; //cout << "f[i]: " << f[i] << "\n"; //cout << "f[i]->out(time): " << f[i]->out(time) << "\n"; //fnc = f[i]->out(fmod(time,T)); //win = w[i].out(fmod(time,T)); //cout << fnc << " " << win << "\n"; weight += (f[i]->out(fmod(time,T)))*(w[i].out(fmod(time,T))); } return weight; } vector<timeFunction*> f; private: double T; vector<step_> steps; vector<ramp_> ramps; vector<sine_> sines; vector<window_> w; }; class linearCombination { public: void addFunction(function_ func){ f.push_back(func); } void addMatrix(matrix::Matrix matr){ m.push_back(matr); } roboy_dep::linear_combination pub(double time){ roboy_dep::linear_combination msg; for (int i = 0; i < m.size(); i++){ msg.weights.push_back(f[i].out(time)); } return msg; } matrix::Matrix out(double time){ matrix::Matrix y = matrix::Matrix(m[0].getM(),m[0].getN()); for (int i = 0; i < m.size(); i++){ y = y + m[i]*f[i].out(time); } return y; } vector<function_> f; vector<matrix::Matrix> m; }; /* int main(){ //create functions and functions vector step_ step; step.setParams(0.4, 1.0); ramp_ ramp; ramp.setParams(1.0,0.0); sin_ sin; sin.setParams(1.0,1.0,0.0); vector<timeFunction*> functions; functions.push_back(&step); functions.push_back(&ramp); functions.push_back(&sin); //create windows for functions and windows vector window_ window1; window1.setParams(0.25, 0.75); window_ window2; window2.setParams(0.25, 0.75); window_ window3; window3.setParams(0.25, 0.75); vector<window_> windows; windows.push_back(window1); windows.push_back(window2); windows.push_back(window3); //create functions function_ f; f.setPeriod(1.0); f.setFunctions(functions); f.setWindows(windows); vector<function_> funcs; funcs.push_back(f); //create matrices matrix::Matrix m = matrix::Matrix(1,1); m.val(0,0) = 1.0; vector<matrix::Matrix> matrices; matrices.push_back(m); //calulate matrix combination at time = 0.6 matrix::Matrix y = matrix::Matrix(1,1); y = linearCombination(matrices,funcs,0.6); cout << y.val(0,0); }*/ #endif
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { string in,ss; cin>>in; bool start=false; long q,i,prev,pos,l; int a; vector <vector<long>> state(52); vector<long>::iterator it; for( i=0; i<in.size();i++) { if(in[i]>=97&&in[i]<=122) state[in[i]-97].push_back(i); if(in[i]>=65&&in[i]<=90) state[in[i]-65+26].push_back(i); } cin>>q; while(q--) { start=false; prev=-1; cin>>ss; for( i=0 ;i<ss.size();i++) { prev++; if(ss[i]>=97&&ss[i]<=122) a=ss[i]-97; else a=ss[i]-65+26; it=lower_bound(state[a].begin(),state[a].end(),prev); pos=*it; if(!start){l=pos;start=true;} if(it!=state[a].end()&&pos>=prev)prev=pos; else break; } if(i==ss.size()) printf("Matched %d %d\n",l,pos); else cout<<"Not matched\n"; } return 0; }
#pragma once #ifndef GAME_H #define GAME_H //static definitions #define WINDOW_HEIGHT 720 #define WINDOW_WIDTH 1440 #include "GameState.h" #include "MenuState.h" #include "StartPageState.h" class Game { private: //Variables sf::RenderWindow* window; sf::VideoMode videoMode; sf::Event sfEvent; sf::Clock dtClock; float dt; std::stack<State*> states; //Initialization void InitWindow(); void InitStates(); public: //Constructors - Destructors Game(); virtual ~Game(); //functions void updateDt(); void updateSFMLEvents(); void update(); void render(); void run(); }; #endif
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _GDCMIO_DICOMFILESREADER_HPP_ #define _GDCMIO_DICOMFILESREADER_HPP_ #include <gdcmReader.h> #include <fwData/macros.hpp> #include "gdcmIO/reader/DicomObjectReader.hxx" namespace gdcmIO { namespace reader { /** * @brief This class contains common members to read DICOM files. * * It has a generic or specific GDCM reader (eg: Reader or ImageReader). * This reader has to be instantiated by a sub-class. All DICOM file reader * in gdcmIO must inherit of this class. * * @class DicomFilesReader. * @author IRCAD (Research and Development Team). * @date 2011. */ template <class DATATYPE> class GDCMIO_CLASS_API DicomFilesReader : public DicomObjectReader< DATATYPE > { public: GDCMIO_API DicomFilesReader() { SLM_TRACE_FUNC(); } GDCMIO_API virtual ~DicomFilesReader() { SLM_TRACE_FUNC(); } /** * @brief Interface which has to be overridden. */ GDCMIO_API virtual void read() = 0; /** * @brief Get the GDCM reader. */ GDCMIO_API ::boost::shared_ptr< ::gdcm::Reader > getReader() const; /** * @brief Set the GDCM reader. */ GDCMIO_API void setReader(::boost::shared_ptr< ::gdcm::Reader > a_gReader); /** * @brief Get the data set of the current file of GDCM reader. */ GDCMIO_API const ::gdcm::DataSet & getDataSet() const; GDCMIO_API fwGettersSettersDocMacro(FileNames, filenames, std::vector< std::string >, A group of file(s) with common fields which have to be written.); private : ::boost::shared_ptr< ::gdcm::Reader > m_gReader; ///< Pointer to the super class of GDCM reader. ///< It could be downcast. std::vector< std::string > m_filenames; ///< List of file names to read. }; //------------------------------------------------------------------------------ template <class DATATYPE> ::boost::shared_ptr< ::gdcm::Reader > DicomFilesReader<DATATYPE>::getReader() const { return this->m_gReader; } //------------------------------------------------------------------------------ template <class DATATYPE> void DicomFilesReader<DATATYPE>::setReader(::boost::shared_ptr< ::gdcm::Reader > a_gReader) { this->m_gReader = a_gReader; } //------------------------------------------------------------------------------ template <class DATATYPE> const ::gdcm::DataSet & DicomFilesReader<DATATYPE>::getDataSet() const { return this->m_gReader->GetFile().GetDataSet(); } } // namespace reader } // namespace gdcmIO #endif /* _GDCMIO_DICOMFILESREADER_HPP_ */
//reverse every k nodes. If the remaining nodes are less than k reverse 'em all #include <iostream> using namespace std; //IDEA: reverse first k nodes. if length of the list is > k then kth node is gonna be head always else the ////last node is gonna be head //after reversing nodes in group of k connect them typedef struct Node { int key; Node *next; Node(int x) { key = x; } } Node; Node *insert(Node *head, int key) { Node *temp = new Node(key); temp->next = head; return temp; } void printList(Node *head) { Node *curr = head; while (curr != NULL) { cout << curr->key << " " << endl; curr = curr->next; } } Node *reverseKNodes(Node *head, int k) { Node* curr=head, *nextn=head->next, *prev=NULL; int count = 0; while (curr != NULL && count < k) { count++; nextn = curr->next; curr->next = prev; prev=curr; curr=nextn; } if(nextn!=NULL){ Node* rest_head=reverseKNodes(curr,k); head->next=rest_head; } return prev; } int main(int argc, char const *argv[]) { Node*head=NULL; head=insert(head,7); head=insert(head,6); head=insert(head,5); head=insert(head,4); head=insert(head,3); head=insert(head,2); head=insert(head,1); cout<<"Orignal List: "<<endl; printList(head); cout<<"Reversing K groups "<<endl; int k=3; head=reverseKNodes(head,k); printList(head); return 0; }
#ifndef CHAPTER8_WEIGHTED_GRAPH_EDGE #define CHAPTER8_WEIGHTED_GRAPH_EDGE #include <ostream> template <typename Weight> class Edge { private: int _vertex1; int _vertex2; Weight _weight; public: Edge(int v1, int v2, Weight w) : _vertex1(v1), _vertex2(v2), _weight(w){}; Edge() {} ~Edge(); int vertex1() const { return _vertex1; } int vertex2() const { return _vertex2; } Weight& weight() const { return _weight; } int other(int x) const { return x == _vertex1 ? _vertex2 : _vertex1; } friend std::ostream& operator<<(std::ostream& os, const Edge& e) { os << e.vertex1() << "-" << e.vertex2() << ": " << e._weight << std::endl; return os; } bool operator<(Edge<Weight>& e) { return _weight < e.weight(); } bool operator>(Edge<Weight>& e) { return _weight > e.weight(); } bool operator==(Edge<Weight>& e) { return _weight == e.weight(); } bool operator<=(Edge<Weight>& e) { return _weight <= e.weight(); } bool operator>=(Edge<Weight>& e) { return _weight >= e.weight(); } }; template <typename Weight> Edge<Weight>::~Edge() {} #endif
 #include "D:\source\repos\algorithms_and_data_structures\laboratory2\List.h" #include <iostream> using namespace std; // hash functions////////////////////////////////////////////////////////////////////////////////////////////////// int HashFunctionMultiplication(int k, int ts) { int N = ts; double A = 0.618033; int h = floor(N * fmod(k * A, 1)); return h; } int HashFunctionDivision(int k, int ts) { return (k % ts); } int HashFunctionRowKeys(const char* ch, int ts) { int a = 29; int M = ts; int result = 0; int size = sizeof(ch); for (int i = 0; i < size; i++) { result += (static_cast<int>(ch[i]) * pow(a, i)); } result = result % M; return result; } int HashFunctionRowKeys(string ch, int ts) { int a = 26; int M = ts; int result = 0; int size = ch.length(); for (int i = 0; i < size; i++) { result += (static_cast<int>(ch[i]) * pow(a, i)); } result = result % M; return result; } struct hashTableEntryInt { int e_key; int e_data; hashTableEntryInt& operator=(const hashTableEntryInt& other) { this->e_data = other.e_data; this->e_key = other.e_key; return *this; } bool operator ==(const hashTableEntryInt& one) { if ((this->e_key == one.e_key && this->e_data == one.e_data)) { return true; }// || (this == NULL && one == NULL) return false; } friend ostream& operator<<(ostream& os, const hashTableEntryInt& dt); }; ostream& operator<<(ostream& os, const hashTableEntryInt& dt) { os << "key: " << dt.e_key << " " << "value: " << dt.e_data; return os; } struct hashTableEntryString { string e_key = "empty"; int e_data; hashTableEntryString() { e_key = "empty"; e_data = 0; } hashTableEntryString& operator=(const hashTableEntryString& other) { this->e_data = other.e_data; this->e_key = other.e_key; return *this; } bool operator ==(const hashTableEntryString& one) { if ((this->e_key == one.e_key && this->e_data == one.e_data)) { return true; }// || (this == NULL && one == NULL) return false; } friend ostream& operator<<(ostream& os, const hashTableEntryString& dt); }; ostream& operator<<(ostream& os, const hashTableEntryString& dt) { os << "key: " << dt.e_key << " " << "value: " << dt.e_data; return os; } class HashTable_open_hashing { private: int T_S; List<hashTableEntryString>* lists; public: HashTable_open_hashing(int size = 3) { T_S = size; lists = new List<hashTableEntryString>[T_S]; for (int i = 0; i < T_S; i++) { //lists[i] = NULL; } } int getTs() { return T_S; } void insert_table_row(string k, hashTableEntryString d) { if (lists[HashFunctionRowKeys(k, T_S)].amount() == 0) { //++count; } lists[HashFunctionRowKeys(k, T_S)].createnode(d); } void delete_table_row(string k) { node<hashTableEntryString>* temp = new node<hashTableEntryString>; if (lists[HashFunctionRowKeys(k, T_S)].amount() != 0) { temp = lists[HashFunctionRowKeys(k, T_S)].get_head(); int c = 0; while (temp != NULL) { ++c; if (temp->data.e_key == k) { lists[HashFunctionRowKeys(k, T_S)].delete_from_n_possition(c); break; } temp = temp->next; } } } hashTableEntryString find_row(string k) { node<hashTableEntryString>* temp = new node<hashTableEntryString>; int t = HashFunctionRowKeys(k, T_S); // if ( t < T_S) { return; } if (lists[t].amount() != 0) { temp = lists[t].get_head(); if (temp->data.e_key != "empty"){ while (temp != NULL) { if (temp->data.e_key == k) { return temp->data; break; } temp = temp->next; } } } return temp->data; } void print_table() { for (int i = 0; i < T_S; i++) { cout << i << ":: "; lists[i].display(); } } // hash functions////////////////////////////////////////////////////////////////////////////////////////////////// friend int HashFunctionRowKeys(string ch, int T_S); }; class HashTable_closed_hashing { private: int T_S = 3; hashTableEntryInt* table; int count; public: HashTable_closed_hashing(int size = 3) { T_S = size; table = new hashTableEntryInt[T_S]; for (int i = 0; i < T_S; i++) { table[i].e_key = -1; } } int getTs() { return T_S; } void resizeTable_division() { if (static_cast<double>(count) / T_S > 0.8) { hashTableEntryInt* tableTemp = new hashTableEntryInt[T_S]; for (int i = 0; i < T_S; i++) {; tableTemp[i].e_data = table[i].e_data; tableTemp[i].e_key = table[i].e_key; } T_S = T_S * 2; delete table; count = 0; table = new hashTableEntryInt[T_S]; for (int i = 0; i < T_S; i++) { table[i].e_key = -1; } for (int i = 0; i < T_S / 2; i++) { //if (tableTemp[i].e_key != -1) { insert_table_division(tableTemp[i].e_key, tableTemp[i]); //} } } } void resizeTable_multiplication() { if (static_cast<double>(count) / T_S > 0.8) { hashTableEntryInt* tableTemp = new hashTableEntryInt[T_S]; for (int i = 0; i < T_S; i++) { ; tableTemp[i].e_data = table[i].e_data; tableTemp[i].e_key = table[i].e_key; } T_S = T_S * 2; delete table; count = 0; table = new hashTableEntryInt[T_S]; for (int i = 0; i < T_S; i++) { table[i].e_key = -1; } for (int i = 0; i < T_S / 2; i++) { insert_table_multiplication(tableTemp[i].e_key, tableTemp[i]); } } } void insert_table_division(int k, hashTableEntryInt d) { int formed_key = HashFunctionDivision(k, T_S); for (int i = formed_key; i < T_S + formed_key; i++) { int j = i; (j >= T_S) ? j = i - T_S : j = i; if (table[j].e_key == -1) { table[j] = d; ++count; break; } } } void insert_table_multiplication(int k, hashTableEntryInt d) { int formed_key = HashFunctionMultiplication(k, T_S); for (int i = formed_key; i < T_S + formed_key; i++) { int j = i; (j >= T_S) ? j = i - T_S : j = i; if (table[j].e_key == -1) { table[j] = d; ++count; break; } } } void delete_table_division(int k) { int formed_key = HashFunctionDivision(k, T_S); for (int i = formed_key; i < T_S + formed_key; i++) { int j = i; (j >= T_S) ? j = i - T_S : j = i; if (table[j].e_key == k) { table[j].e_key = -1; table[j].e_data = NULL; --count; break; } } } void delete_table_multiplication(int k) { int formed_key = HashFunctionMultiplication(k, T_S); for (int i = formed_key; i < T_S + formed_key; i++) { int j = i; (j >= T_S) ? j = i - T_S : j = i; if (table[j].e_key == k) { table[j].e_key = -1; table[j].e_data = NULL; --count; break; } } } hashTableEntryInt find_division(int k) { int formed_key = HashFunctionDivision(k, T_S); for (int i = formed_key; i < T_S + formed_key; i++) { int j = i; (j >= T_S) ? j = i - T_S : j = i; if (table[j].e_key == k) { return table[j]; break; } } hashTableEntryInt h{NULL}; return h; } hashTableEntryInt find_multiplication(int k) { int formed_key = HashFunctionMultiplication(k, T_S); for (int i = formed_key; i < T_S + formed_key; i++) { int j = i; (j >= T_S) ? j = i - T_S : j = i; if (table[j].e_key == k) { return table[j]; break; } } hashTableEntryInt h{NULL}; return h; } void print_table() { for (int i = 0; i < T_S; i++) { //if (table[i].e_key != -1) { cout << i << ":: "; cout << table[i] <<endl; //} } } // hash functions////////////////////////////////////////////////////////////////////////////////////////////////// friend int HashFunctionMultiplication(int k, int T_S); friend int HashFunctionDivision(int k, int T_S); }; int main() { int fpm = 0, thpm = 0, choise = 0; HashTable_open_hashing hash_table_s_i; HashTable_closed_hashing hash_table_i_i_c; hashTableEntryInt hte_i_i; hashTableEntryString hte_s_i; string str_key, str_value; int ind, key, value; while (fpm != 3) { cout << "choose the action" << endl; cout << "1 - HashTable_open_hashing" << endl; cout << "2 - HashTable_closed_hashing" << endl; cout << "3 - exit the menu" << endl; cin >> fpm; switch (fpm) { case 1: cout << "HashTable_open_hashing<string, int> hash_table" << endl; while (thpm != 5) { cout << "choose the action" << endl; cout << "1 - insert key-value" << endl; cout << "2 - delete by key" << endl; cout << "3 - find by key" << endl; cout << "4 - print table" << endl; cout << "5 - exit the menu" << endl; cin >> thpm; switch (thpm) { case 1: cout << "enter key string: not empty and not deleted " << endl; cin >> str_key; cout << "enter value int: " << endl; cin >> value; hte_s_i.e_key = str_key; hte_s_i.e_data = value; hash_table_s_i.insert_table_row(hte_s_i.e_key, hte_s_i); break; case 2: cout << "enter key string: " << endl; cin >> str_key; hash_table_s_i.delete_table_row(str_key); break; case 3: cout << "enter key string: " << endl; cin >> str_key; cout << hash_table_s_i.find_row(str_key) << endl; break; case 4: hash_table_s_i.print_table(); break; } } break; case 2: cout << "HashTable_closed_hashing<int, int> hash_table" << endl; cout << "Division-1 or multiplication-2 method of hashing: " << endl; cin >> choise; while (thpm != 5) { cout << "choose the action" << endl; cout << "1 - insert key-value" << endl; cout << "2 - delete by key" << endl; cout << "3 - find by key" << endl; cout << "4 - print table" << endl; cout << "5 - exit the menu" << endl; cin >> thpm; switch (thpm) { case 1: cout << "enter key int: not -1" << endl; cin >> key; cout << "enter value int: " << endl; cin >> value; hte_i_i.e_key = key; hte_i_i.e_data = value; if (choise == 1) { hash_table_i_i_c.resizeTable_division(); hash_table_i_i_c.insert_table_division(hte_i_i.e_key, hte_i_i); } else if (choise == 2) { hash_table_i_i_c.resizeTable_multiplication(); hash_table_i_i_c.insert_table_multiplication(hte_i_i.e_key, hte_i_i); } break; case 2: cout << "enter key int: " << endl; cin >> key; if (choise == 1) { hash_table_i_i_c.delete_table_division(key); hash_table_i_i_c.resizeTable_division(); } else if (choise == 2) { hash_table_i_i_c.delete_table_multiplication(key); hash_table_i_i_c.resizeTable_multiplication(); } break; case 3: cout << "enter key int: " << endl; cin >> key; if (choise == 1) { cout << hash_table_i_i_c.find_division(key) << endl; } else if (choise == 2) { cout << hash_table_i_i_c.find_multiplication(key) << endl; } break; case 4: hash_table_i_i_c.print_table(); break; } } break; } } }
#ifndef GNCRITICALSECTION_H #define GNCRITICALSECTION_H #include "GnDebug.h" #define GNMULTITHREADED class GNSYSTEM_ENTRY GnCriticalSection { public: GNFORCEINLINE GnCriticalSection(); GNFORCEINLINE ~GnCriticalSection(); GNFORCEINLINE void Lock(); GNFORCEINLINE void Unlock(); protected: #if defined(GNMULTITHREADED) #if defined(WIN32) || defined(_XENON) CRITICAL_SECTION m_kCriticalSection; #elif defined (_PS3) pthread_mutex_t m_kCriticalSection; #else pthread_mutex_t m_kCriticalSection; #endif // #if defined(WIN32) || defined(_XENON) #if defined (GNDEBUG) bool m_bLocked; #endif // #if defined (_DEBUG) #endif // #if defined (NI_MULTITHREADED) }; GNFORCEINLINE GnCriticalSection::GnCriticalSection() { #if defined(GNMULTITHREADED) #if defined(GNDEBUG) m_bLocked = false; #endif //#if defined(_DEBUG) #if defined(WIN32) || defined(_XENON) InitializeCriticalSection(&m_kCriticalSection); #else pthread_mutex_init(&m_kCriticalSection, NULL); #endif #endif // #if !defined(NI_MULTITHREADED) } GNFORCEINLINE GnCriticalSection::~GnCriticalSection() { #if defined(GNMULTITHREADED) #if defined(WIN32) || defined(_XENON) DeleteCriticalSection(&m_kCriticalSection); #else // defined(WIN32) || defined(_XENON) pthread_mutex_destroy(&m_kCriticalSection); #endif // defined(WIN32) || defined(_XENON) #endif // #if !defined(NI_MULTITHREADED) } GNFORCEINLINE void GnCriticalSection::Lock() { #if defined(GNMULTITHREADED) #if defined(GNDEBUG) GnAssert(m_bLocked == false); m_bLocked = true; #endif //#if defined(_DEBUG) #if defined(WIN32) || defined(_XENON) EnterCriticalSection(&m_kCriticalSection); #else // defined(WIN32) || defined(_XENON) pthread_mutex_lock(&m_kCriticalSection); #endif // defined(WIN32) || defined(_XENON) #endif // #if !defined(NI_MULTITHREADED) } GNFORCEINLINE void GnCriticalSection::Unlock() { #if defined(GNMULTITHREADED) #if defined(GNDEBUG) m_bLocked = false; #endif //#if defined(_DEBUG) #if defined(WIN32) || defined(_XENON) LeaveCriticalSection(&m_kCriticalSection); #else // defined(WIN32) || defined(_XENON) pthread_mutex_unlock(&m_kCriticalSection); #endif // defined(WIN32) || defined(_XENON) #endif // #if !defined(NI_MULTITHREADED) } #endif // GNCRITICALSECTION_H
// AnalysisView.cpp : CAnalysisView 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "Analysis.h" #endif #include "AnalysisDoc.h" #include "AnalysisView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAnalysisView IMPLEMENT_DYNCREATE(CAnalysisView, CListView) BEGIN_MESSAGE_MAP(CAnalysisView, CListView) //ON_WM_PAINT() ON_WM_CREATE() //ON_COMMAND(ID_FILE_OPEN, &CAnalysisView::OnFileOpen) ON_WM_CONTEXTMENU() ON_WM_RBUTTONUP() END_MESSAGE_MAP() // CAnalysisView 构造/析构 CAnalysisView::CAnalysisView() { // TODO: 在此处添加构造代码 } CAnalysisView::~CAnalysisView() { } BOOL CAnalysisView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: 在此处通过修改 // CREATESTRUCT cs 来修改窗口类或样式 return CListView::PreCreateWindow(cs); } void CAnalysisView::OnInitialUpdate() { MessageBox(_T("OnInitialUpdateBegin"), _T("OnInitialUpdateBegin"), MB_OK); CListView::OnInitialUpdate(); // TODO: 调用 GetListCtrl() 直接访问 ListView 的列表控件, // 从而可以用项填充 ListView。 CListView::OnInitialUpdate(); //CAnalysisDoc* pDoc = GetDocument(); //CListCtrl* pListCtrl = &GetListCtrl(); CListCtrl* pListCtrl = &listCtrl; pListCtrl->SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT); pListCtrl->InsertColumn(0, _T("error"), LVCFMT_LEFT, 100); UpdateData(FALSE); MessageBox(_T("OnInitialUpdateEnd"), _T("OnInitialUpdateEnd"), MB_OK); } void CAnalysisView::OnRButtonUp(UINT /* nFlags */, CPoint point) { ClientToScreen(&point); OnContextMenu(this, point); } void CAnalysisView::OnContextMenu(CWnd* /* pWnd */, CPoint point) { #ifndef SHARED_HANDLERS theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE); #endif } // CAnalysisView 诊断 #ifdef _DEBUG void CAnalysisView::AssertValid() const { CListView::AssertValid(); } void CAnalysisView::Dump(CDumpContext& dc) const { CListView::Dump(dc); } CAnalysisDoc* CAnalysisView::GetDocument() const // 非调试版本是内联的 { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CAnalysisDoc))); return (CAnalysisDoc*)m_pDocument; } #endif //_DEBUG // CAnalysisView 消息处理程序 int CAnalysisView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CWnd::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here MessageBox(_T("OnCreateBegin"), _T("OnCreateBegin"), MB_OK); CRect rect; GetClientRect(&rect); listCtrl.CreateEx(LVS_EX_GRIDLINES, WS_CHILD | WS_VISIBLE | WS_BORDER | LVS_REPORT, rect, this, 123); listCtrl.SetBkColor(RGB(237, 250, 254)); listCtrl.SetTextBkColor(RGB(0, 255, 0)); listCtrl.SetTextColor(RGB(0, 0, 255)); listCtrl.SetExtendedStyle(LVS_EX_GRIDLINES); CreateListColumns(); UpdateData(FALSE); MessageBox(_T("OnCreateEnd"), _T("OnCreateEnd"), MB_OK); return 0; } void CAnalysisView::CreateListColumns(void) { MessageBox(_T("CreateListColumnsBegin"), _T("CreateListColumnsBegin"), MB_OK); LV_COLUMN lvColumn; //Column 0 lvColumn.mask = LVCF_WIDTH | LVCF_TEXT | LVCF_FMT | LVCF_SUBITEM; lvColumn.fmt = LVCFMT_LEFT; lvColumn.cx = 100; lvColumn.iSubItem = 0; lvColumn.pszText = _T("序号"); listCtrl.InsertColumn(0, &lvColumn); //Column 1 lvColumn.mask = LVCF_WIDTH | LVCF_TEXT | LVCF_FMT | LVCF_SUBITEM; lvColumn.fmt = LVCFMT_RIGHT; lvColumn.cx = 200; lvColumn.iSubItem = 1; lvColumn.pszText = _T("时间/s"); listCtrl.InsertColumn(1, &lvColumn); //Column 2 lvColumn.mask = LVCF_WIDTH | LVCF_TEXT | LVCF_FMT | LVCF_SUBITEM; lvColumn.fmt = LVCFMT_RIGHT; lvColumn.cx = 200; lvColumn.iSubItem = 2; lvColumn.pszText = _T("力量/kgf"); listCtrl.InsertColumn(2, &lvColumn); UpdateData(FALSE); MessageBox(_T("CreateListColumnsEnd"), _T("CreateListColumnsEnd"), MB_OK); }
#include <iostream> using namespace std; int main() { int i, j; int n; cin >> n; int arr[n]; for (i = 0; i < n; i++) cin >> arr[i]; for (j = n-1; j >= 0; j = j -1) cout << arr[j] << ' '; return 0; }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "GameFramework/GameModeBase.h" #include "HypoxiaGameMode.generated.h" UCLASS(minimalapi) class AHypoxiaGameMode : public AGameModeBase { GENERATED_BODY() public: AHypoxiaGameMode(); };
/*#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <algorithm> using namespace std; long long int fun(int n) { if(n <= 50 && n > 1) return n * fun(n - 1); if(n == 1) return } int main() { long long int a[80]; a[1] = 1; for(int i = 50; i >= 1; i--) { a[i] = i * (i + 1); } printf("%lld\n", a[n]); return 0; } #include <stdio.h> #include <stdlib.h> int main() { double i,j=0,jc; for(i=50;i<=50;i++) { j=i; jc=1; do { jc=jc*j; j=j-1; } while(j>0); printf("%.0lf %.0lf\n",i,jc); printf("\n"); } return 0; } */ //#include <iostream> #include <stdio.h> #include <string.h> //using namespace std; const int maxn = 2e5 + 5; int n, tot; int ans[maxn]; //大数的存储 int main() { int s; while(~scanf("%d", &n)) { //计算n! memset(ans, 0, sizeof ans); //对ans数组初始化为0 ans[0] = 1; //从1开始乘 tot = 1; for(int i = 2; i <= n; i++) { int now = 0; int cnt = 0; //进位数值 while(now < tot) { s = ans[now] * i + cnt; ans[now++] = s % 10; //取余 // now ++; cnt = s / 10; if(tot == now && cnt) tot ++; } } for(int i = tot - 1; i >= 0; i --) { printf("%d", ans[i]); } printf("\n"); } return 0; } /* #include <iostream> #include <cstdio> #include <cstring> using namespace std; const int maxn = 2e5 + 5; int n, tot, ans[maxn]; int main() { int t; while(cin >> n) { memset(ans, 0, sizeof ans); ans[0] = 1; tot = 1; int cnt; int now; for(int i = 2; i <= n; i++) { now = 0; cnt = 0; while(now < tot) { t = ans[now] * i + cnt; ans[now] = t % 10; now ++; cnt = t / 10; if(tot == now && cnt) tot ++; } } for(int i = tot - 1; i >= 0; i --) { cout << ans[i]; } cout << endl; } return 0; } */
// // Created by 송지원 on 2020/08/13. // #include <iostream> #include <stack> #include <string> using namespace std; string str; int N; int strLen; int CNT; int main() { ios::sync_with_stdio(0); cin.tie(0); while (true) { stack<char> S; N++; CNT = 0; cin >> str; if (str[0] == '-') { break; } strLen = str.size(); for (int i=0; i<strLen; i++) { char ch = str[i]; if (ch == '{'){ S.push('{'); } else { if (S.size() == 0) { CNT ++; S.push('{'); } else S.pop(); } } if (S.size() > 0) { CNT += (S.size())/2; } cout << N <<". " << CNT << "\n"; } return 0; }
//By SCJ //#include<iostream> #include<bits/stdc++.h> using namespace std; #define endl '\n' void ext_gcd(int a,int b,int& d,int& x,int& y) { if(!b){d=a;x=1;y=0;} else{ext_gcd(b,a%b,d,y,x);y-=x*(a/b);} } int main() { //ios::sync_with_stdio(0); //cin.tie(0); int a,b; while(cin>>a>>b) { int x,y,d; ext_gcd(a,b,d,x,y); printf("d=%d x=%d y=%d a*x+b*y=%d\n",d,x,y,a*x+b*y); } }
#include <iostream> #include <string> class Hash { private: static const int tableSize = 6; struct Item { std::string name; std::string phoneNum; Item* next; }; Item* hashTable[tableSize]; public: int hashFunc(std::string key); Hash(); void addItem(std::string name, std::string phoneNum); int numberOfItemsInIndex(int index); void printTable(); void printItemsInIndex(int index); void findPhoneNum(std::string name); void removeItem(std::string name); }; Hash::Hash() { for (int i = 0; i < tableSize; ++i) { hashTable[i] = new Item; hashTable[i] -> name = "empty"; hashTable[i] -> phoneNum = "empty"; hashTable[i] -> next = NULL; } } int Hash::hashFunc(std::string key) { int hash = 0; int index; for (int i = 0; i < key.length(); ++i) { hash = (hash + (int) key[i]) * 17; } index = hash % tableSize; return index; } void Hash::addItem(std::string name, std::string phoneNum) { int index = hashFunc(name); if (hashTable[index] -> name == "empty") { hashTable[index] -> name = name; hashTable[index] -> phoneNum = phoneNum; } else { Item* ptr = hashTable[index]; Item* n = new Item; n -> name = name; n -> phoneNum = phoneNum; n -> next = NULL; while (ptr -> next != NULL) { ptr = ptr -> next; } ptr -> next = n; } } int Hash::numberOfItemsInIndex(int index) { int count = 0; if (hashTable[index] -> name == "empty") { return count; } else { ++count; Item* ptr = hashTable[index]; while (ptr -> next != NULL) { ++count; ptr = ptr -> next; } } return count; } void Hash::printTable() { int number; for (int i = 0; i < tableSize; ++i) { number = numberOfItemsInIndex(i); std::cout << "------------------\n"; std::cout << "Index = " << i << std::endl; std::cout << hashTable[i] -> name << std::endl; std::cout << hashTable[i] -> phoneNum << std::endl; std::cout << "Number of Items = " << number << std::endl; std::cout << "--------------------\n"; } } void Hash::printItemsInIndex(int index) { Item* ptr = hashTable[index]; if (ptr -> name == "empty") { std::cout << "index = " << index << " is empty" << std::endl; } else { std::cout << "index " << index << "contains the following item\n"; while (ptr != NULL) { std::cout << "--------------------\n"; std::cout << ptr -> name << std::endl; std::cout << ptr -> phoneNum << std::endl; std::cout << "--------------------\n"; ptr = ptr -> next; } } } void Hash::findPhoneNum(std::string name) { int index = hashFunc(name); bool foundName = false; std::string phoneNum; Item* ptr = hashTable[index]; while (ptr != NULL) { if (ptr -> name == name) { foundName = true; phoneNum = ptr -> phoneNum; } ptr = ptr -> next; } if (foundName == true) { std::cout << "Phone Number = " << phoneNum << std::endl; } else { std::cout << name << "'s info was not found in this Hash Table\n"; } } void Hash::removeItem(std::string name) { int index = hashFunc(name); Item* delPtr; Item* p1; Item* p2; //case 0- bucket is empty if (hashTable[index] -> name == "empty" && hashTable[index] -> phoneNum == "empty") { std::cout << name << " was not found in the Hash Table\n"; //case 1- only 1 item contained in the bucket and that item has matching name } else if (hashTable[index] -> name == name && hashTable[index] -> next == NULL) { hashTable[index] -> name = "empty"; hashTable[index] -> phoneNum = "empty"; std::cout << name << " was remove from Hash Table\n"; //case 2- match is located in the first item in the bucket, but there are more items in the bucket } else if (hashTable[index] -> name == name) { delPtr = hashTable[index]; hashTable[index] = hashTable[index] -> next; delete delPtr; std::cout << name << " was remove from Hash Table\n"; //case 3- bucket contains more than 1 item is not a match } else { p1 = hashTable[index] -> next; p2 = hashTable[index]; while (p1 != NULL && p1 -> name != name) { p2 = p1; p1 = p1 -> next; } } //case 3.1- no match if (p1 == NULL) { std::cout << name << " was not found in the Hash Table\n"; //case 3.2- match is found } else { delPtr = p1; p1 = p1 -> next; p2 -> next = p1; delete delPtr; std::cout << name << " was removed from Hash Table\n"; } } int main() { Hash obj; std::string name = ""; obj.addItem("Paul", "1818457982"); obj.addItem("Kim", "18184788999"); obj.addItem("Emma", "1818455548"); obj.addItem("Eva", "18187777789"); obj.addItem("Inna", "1818799956"); obj.addItem("John", "1818456222"); obj.printItemsInIndex(2); while (name != "exit") { std::cout << "Remove "; // for searching name you can change "Remove"-> "Search for" std::cin >> name; if (name != "exit") { obj.removeItem(name); // obj.findPhoneNum(name); } } obj.printTable(); return 0; }
#include <stdio.h> #include <errno.h> #include <iostream> #include <string> //Allows usage of fopen() in MS Visual Studio: #ifdef _MSC_VER #pragma warning(disable:4996) #endif #define MAX_FILE_CHAR 2048 #define BUFFER_SIZE 128 /* COMP-3473 Operating Systems Group Project Ian Cuninghame, Kris Luszczynski Lakehead University 2019 */ /* POFM must perform: 1) Create a new file 2) Delete a file 3) Rename a file 4) Copy a file 5) Move a file from one directory to another 6) Text file operations: i) append text to the end of a file ii) insert text at a specific char position iii) remove all text in a file iv) show the content of a text file, displaying a certain # of lines at once defined by the user. - Must not use any system() calls */ using namespace std; //Function prototypes to be defined later: void testFileCreation(); void testFileDeletion(); void testFileRenaming(); void testFileCopy(); void testFileMove(); void testFileEdit(); void testFileRead(); void testFileAppend(); void testFileInsert(); void testFileEmpty(); void openHelpMenu(); void openEditHelpMenu(); FILE* createFile(char* fileName); void deleteFile(char* fileName); void renameFile(char* fileName, char* newName); void copyFile(char* src, char* dest); void moveFile(char* src, char* dest); void readFile(char* fileName); void appendFile(char* fileName, char dataToAppend[BUFFER_SIZE]); void insertFile(char* fileName, char dataToInsert[BUFFER_SIZE], int pos); void emptyFile(char* fileName); //Main Function to test POFM operations: int main() { //Menu System: string command; cout << " Welcome to LakeheadU Portable File Manager! Please enter one of the commands below to begin." << endl << endl; openHelpMenu(); do { cout << " >> "; cin >> command; cout << endl; if (!command.empty()) { if (command == "create") testFileCreation(); else if (command == "delete") testFileDeletion(); else if (command == "rename") testFileRenaming(); else if (command == "copy") testFileCopy(); else if (command == "move") testFileMove(); else if (command == "edit") testFileEdit(); else if (command == "exit") exit(0); else if (command == "help") openHelpMenu(); else cout << " Unrecognized command. Type 'help' for a list of commands and their usages." << endl; } else { cout << " >> "; } } while (true); return 0; } //Test Run Methods: //1. Test Create a file: void testFileCreation() { FILE* filePointer; char* fileName = (char*)malloc(sizeof(char) * 255); cout << "Please enter the desired name of the file. It will be created in the same directory as this process." << endl; cout << " >> "; cin >> fileName; if (fileName != NULL) { filePointer = createFile(fileName); cout << "File creation complete." << endl; fclose(filePointer); } else cout << "Failed. Please enter a valid file name." << endl; } //2. Test Delete a file: void testFileDeletion() { char* fileName = (char*)malloc(sizeof(char) * 255); cout << "Please enter the filename of the file you wish to delete." << endl; cout << "Note: if the file is not in the same directory as this process, you must specify the full document path." << endl; cout << " >> "; cin >> fileName; deleteFile(fileName); } //3. Test Rename a file: void testFileRenaming() { char* fileName = (char*)malloc(sizeof(char) * 255); char* newName = (char*)malloc(sizeof(char) * 255); cout << " Please enter the current file name of the file you wish to rename." << endl; cout << " Note: if the file is not in the same directory as this process, you must specify the full document path." << endl; cout << " >> "; cin >> fileName; cout << " Please enter the desired new file name for " << fileName << ". " << endl; cout << " >> " << endl; cin >> newName; renameFile(fileName, newName); } //4. Test Copy a file: void testFileCopy() { char* fileSrc = (char*)malloc(sizeof(char) * 255); char* fileDest = (char*)malloc(sizeof(char) * 255); cout << " Please enter the document path of the file you wish to copy: " << endl; cout << " >> "; cin >> fileSrc; cout << " Please enter the destination path including the filename that you want to create: " << endl; cout << " >> "; cin >> fileDest; copyFile(fileSrc, fileDest); } //5. Test Move a file: void testFileMove() { char* fileSrc = (char*)malloc(sizeof(char) * 255); char* fileDest = (char*)malloc(sizeof(char) * 255); cout << " Please enter the document path of the file you wish to move." << endl; cout << " >> "; cin >> fileSrc; cout << " Please enter the desired new location path for " << fileSrc << ". " << endl; cout << " >> " << endl; cin >> fileDest; moveFile(fileSrc, fileDest); } //6: Test Edit a file: void testFileEdit() { string command; //if success (fileName is valid): cout << " Please enter the type of edit you wish to make, or type 'help' for more info: " << endl; cout << "\t 1. read" << endl; cout << "\t 2. append" << endl; cout << "\t 3. insert" << endl; cout << "\t 4. empty" << endl; cout << " >> "; cin >> command; cout << endl; if (!command.empty()) { if (command == "read") testFileRead(); else if (command == "append") testFileAppend(); else if (command == "insert") testFileInsert(); else if (command == "empty") testFileEmpty(); else if (command == "help") openEditHelpMenu(); else cout << " Unrecognized command. Type 'help' for a list of commands and their usages." << endl; } } //6.i: Test Read a File void testFileRead() { char* fileName = (char*)malloc(sizeof(char) * 255); cout << " Please enter the name of the file you wish to be read: " << endl; cout << " >> "; cin >> fileName; readFile(fileName); } //6.ii: Test Append Text to a File void testFileAppend() { char* fileName = (char*)malloc(sizeof(char) * 255); char dataToAppend[BUFFER_SIZE]; cout << " Please enter the name of the file you wish to append text to: " << endl; cout << " Note: this must be a valid .txt file." << endl; cout << " >> "; cin >> fileName; cout << " Please enter the string of text you wish to append to this file: " << endl; cout << " >> "; //Remove any extra whitespace characters that could be in stdin: fflush(stdin); fgetc(stdin); fgets(dataToAppend, BUFFER_SIZE, stdin); appendFile(fileName, dataToAppend); } //6.iii: Test Insert Text in a File: void testFileInsert() { char* fileName = (char*)malloc(sizeof(char) * 255); int pos; char dataToInsert[BUFFER_SIZE]; cout << " Please enter the name of the file you wish to insert text into: " << endl; cout << " Note: this must be a valid .txt file." << endl; cout << " >> "; cin >> fileName; cout << " Please enter the line # that you wish to replace in this file." << endl; cout << " >> "; cin >> pos; cout << " Please enter the string that you would like to insert into this file: " << endl; cout << " >> "; cin >> dataToInsert; insertFile(fileName, dataToInsert, pos); } //6.iv: Test Emptying a File: void testFileEmpty() { char* fileName = (char*)malloc(sizeof(char) * 255); cout << " Please enter the name of the file you wish to empty the text of: " << endl; cout << " Note: this must be a valid .txt file." << endl; cout << " >> "; cin >> fileName; emptyFile(fileName); } //Help Menu Interface: void openHelpMenu() { cout << " Commands:" << endl; cout << "\t 1. create" << "\t - Create a new file" << endl; cout << "\t 2. delete" << "\t - Delete a specific file" << endl; cout << "\t 3. rename" << "\t - Rename a specific file" << endl; cout << "\t 4. copy" << "\t - Copy a file from one directory to another" << endl; cout << "\t 5. move" << "\t - Move a file from one directory to another" << endl; cout << "\t 6. edit" << "\t - Edit a text file (Read, Append, Insert, Remove)" << endl; cout << "\t 7. exit" << "\t - Exit this program" << endl; cout << " Usage:\n\t enter a command word verbatim as above (no parameters), then enter the required info when prompted." << endl << endl; return; } //Edit File Help Menu Interface: void openEditHelpMenu() { cout << " Commands:" << endl; cout << "\t 1. read" << "\t - Read text from a specified file" << endl; cout << "\t 2. append" << "\t - Append text to the end of a specified file" << endl; cout << "\t 3. insert" << "\t - Insert text at certain char position of a specified file" << endl; cout << "\t 4. empty" << "\t - Empty the specified file of all its contents" << endl; cout << " Usage:\n\t enter a command word verbatim as above (no parameters), then enter the required info when prompted." << endl << endl; return; } //Utility Methods: //1. Create a File: FILE* createFile(char* fileName) { if (fileName != NULL) return fopen(fileName, "w"); else return fopen("default.txt", "w"); } //2. Delete a File: void deleteFile(char* fileName) { FILE* tempFilePointer; //Ensure the fileName is valid, not empty: if (fileName != NULL) { //Check to ensure the file exists before trying to delete: tempFilePointer = fopen(fileName, "r"); if (tempFilePointer != NULL) { fclose(tempFilePointer); remove(fileName); cout << "File " << fileName << " was successfully removed." << endl; } else { cout << "Error deleting the file. Check to make sure you spelled the file name correctly." << endl; } } else cout << "You must enter a valid file name to delete." << endl; return; } //3. Rename a File: void renameFile(char* fileName, char* newName) { if (newName != NULL && fileName != NULL) { if (rename(fileName, newName) == 0) cout << " File name successfully changed from " << fileName << " to " << newName << ". " << endl; else cout << "Error: " << strerror(errno) << endl; //cout << " File renaming was unsuccessful. This is probably because you do not have the correct permissions or the filename was misspelled." << endl; } else { cout << " Failed. You must enter valid file names." << endl; } } //4. Copy a File: void copyFile(char* src, char* dest) { FILE *srcPointer, *destPointer; char ch; int pos; srcPointer = fopen(src, "r"); //Ensure the source file exists and is available to copy: if (srcPointer == NULL) { cout << "Error opening " << src << ". Check to make sure the name is spelled correctly." << endl; return; } else cout << "File " << src << " opened for copying." << endl; destPointer = fopen(dest, "w"); if (destPointer == NULL) { cout << "Error opening " << dest << ". Check to make sure the name is spelled correctly." << endl; return; } else { fseek(srcPointer, 0L, SEEK_END); pos = ftell(srcPointer); fseek(srcPointer, 0L, SEEK_SET); while (pos--) { ch = fgetc(srcPointer); fputc(ch, destPointer); } cout << "Finished copying " << src << " to " << dest << ". " << endl; //Close all open file streams fcloseall(); } return; } //5: Move a File: void moveFile(char* fileSrc, char* fileDest) { if (fileSrc != NULL && fileDest != NULL) { if (rename(fileSrc, fileDest) == 0) cout << " File successfully moved from " << fileSrc << " to " << fileDest << ". " << endl; else cout << "Error: " << strerror(errno) << endl; //cout << " File renaming was unsuccessful. This is probably because you do not have the correct permissions or the filename was misspelled." << endl; } else { cout << " Failed. You must enter valid file names." << endl; } } //6: Edit a File: //i. Read a File: void readFile(char* fileName) { FILE* filePointer; char fileString[MAX_FILE_CHAR]; filePointer = fopen(fileName, "r"); if (filePointer == NULL) { cout << "Error reading " << fileName << ". Please try again." << endl; return; } for (int i = 0; fgets(fileString, MAX_FILE_CHAR, filePointer) != NULL; i++) { cout << "Line " << i <<": " << fileString << endl; } fclose(filePointer); return; } //ii. Append text to a file: void appendFile(char* fileName, char dataToAppend[BUFFER_SIZE]) { FILE* filePointer; if (fileName != NULL) { if (!(filePointer = fopen(fileName, "r"))) { cout << "Error opening the file. Ensure the filename and path is spelled correctly, and you have write priveledges." << endl; return; } filePointer = fopen(fileName, "a"); fputs(dataToAppend, filePointer); cout << "Appended text added successfully." << endl; fclose(filePointer); } } //iii. Insert text at specific char position: void insertFile(char* fileName, char newLine[BUFFER_SIZE], int pos) { FILE* filePointer; FILE* tempFilePointer; int lineNum = 0, lineCount = 0; char fileString[MAX_FILE_CHAR], temp[] = "temp.txt"; cout << "Opening file " << fileName << "..." << endl; filePointer = fopen(fileName, "r"); if (filePointer == NULL) { cout << "Unable to open the file. Please ensure you spelled the file name correctly." << endl; return; } tempFilePointer = fopen(temp, "w"); if (tempFilePointer == NULL) { cout << "Error openining the temporary file for writing. Ensure you have the correct permissions. " << endl; fclose(filePointer); return; } //Copy all the contents from the original file to the temporary one, except for the line to be replaced. while (!feof(filePointer)) { strcpy(fileString, "\0"); fgets(fileString, MAX_FILE_CHAR, filePointer); if (!feof(filePointer)) { lineCount++; if (lineCount != lineNum) { fprintf(tempFilePointer, "%s", fileString); } else { fprintf(tempFilePointer, "%s", newLine); } } } //Close the file streams fclose(filePointer); fclose(tempFilePointer); //Remove the original (unedited) file remove(fileName); //Rename the temporary file to be the same as the one its replacing rename(temp, fileName); cout << " Line insertion finished successfully!" << endl; } //iv. Remove data from a file: void emptyFile(char* fileName) { FILE* filePointer; //Ensure the file exists before emptying: filePointer = fopen(fileName, "r"); if (filePointer == NULL) { cout << "File does not exist, so it cannot be emptied. " << endl; return; } //Overwrite the file: filePointer = freopen(fileName, "w", filePointer); fclose(filePointer); cout << " File " << fileName << " emptied of all its contents successfully." << endl; return; }
#include "server.h" #include <qdebug> #include <iostream> #include <QMessageBox> using namespace std; Server::Server(Dirigeable *dir, int port, QObject* parent): QObject(parent) { dirigeable = dir; //on vérifie que le port est valide if(port<1025 || port>65535) port = 9999; // par défaut on utilise 9999 this->port = port; connect(&server, SIGNAL(newConnection()), // en cas de nouvelle connexion on exécutera le slot acceptConnection this, SLOT(acceptConnection())); qDebug() << "en attente de connexion sur le port "<<port; server.listen(QHostAddress::Any, port); } Server::~Server() { // si l'objet est détruit on s'assure que toute les connexions sont fermées socket->close(); server.close(); } int Server::getPort() const { return port; } void Server::acceptConnection() { socket = server.nextPendingConnection(); // configuration de la connexion et de la socket transfert(); // méthode à appliquer lors d'une connexion } ServerSend::ServerSend(Dirigeable *dirigeable, int port):Server(dirigeable, port){} int ServerSend::irand(int a, int b){ return ( qrand()/(double)RAND_MAX ) * (b-a) + a; } void ServerSend::transfert() { char buffer[32] = ""; qDebug() << "Début transfert : "<<endl; // envoi des informations dans l'ordre : l'angle h, l'ange v, l'angle de la direction sprintf(buffer,"%d %d %d", 1000, 50, dirigeable->getDirection()); qDebug() << "direction : "<<dirigeable->getDirection()<<endl; qDebug() << "envoi donnees : "<<buffer<<endl; socket->write(buffer, strlen(buffer)+1); socket->close(); }
#pragma once #include <string> #include "Module.h" #include "../Common/Types.h" namespace OpenALRF { class ISystem : public IModule { protected: OpenALRF::status_t SuggestedStatus; public: virtual OpenALRF::status_t CurrentStatus() const; virtual void ChangeStatus(OpenALRF::status_t ANewStatus); virtual void RebootNow() = 0; virtual bool HasValidActiveNetwork() = 0; virtual void RestartNetworkInterface(const std::string AInterfaceName) = 0; virtual bool ShouldQuit() = 0; }; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #ifdef DATASTREAM_DECOMPRESSION_ENABLED #include "modules/datastream/fl_lib.h" #include "modules/datastream/fl_zip.h" #include "modules/libssl/debug/tstdump2.h" #define FL_ZIP_BUFFER_SIZE 4096 DataStream_Compression::DataStream_Compression(DataStream_Compress_alg _alg, BOOL writing, DataStream *src_trg, BOOL take_over) : DataStream_Pipe(src_trg, take_over), alg(_alg), compressing(writing) { stream.zalloc = Z_NULL; stream.zfree = Z_NULL; stream.opaque = Z_NULL; stream.avail_in = 0; stream.next_in = NULL; stream.avail_out = 0; stream.next_out = NULL; stream.total_in = 0; stream.total_out = 0; stream.state = Z_NULL; stream.msg = NULL; work_buffer.SetIsFIFO(); decompressed_buffer.SetIsFIFO(); } DataStream_Compression::~DataStream_Compression () { if(compressing) deflateEnd(&stream); #ifdef DATASTREAM_COMPRESSION_ENABLED else inflateEnd(&stream); #endif } void DataStream_Compression::InitL() { int ret = Z_OK; if(compressing) { switch(alg) { case DataStream_Deflate: case DataStream_Deflate_No_Header: ret = deflateInit(&stream, Z_DEFAULT_COMPRESSION); break; default: LEAVE(OpStatus::ERR_OUT_OF_RANGE); } } #ifdef DATASTREAM_COMPRESSION_ENABLED else { switch(alg) { case DataStream_Deflate: case DataStream_Deflate_No_Header: ret = inflateInit(&stream); break; default: LEAVE(OpStatus::ERR_OUT_OF_RANGE); } } #endif if(ret != Z_OK) LEAVE(ret == Z_MEM_ERROR ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR); work_buffer1.SetNeedDirectAccess(TRUE); work_buffer1.ResizeL(FL_ZIP_BUFFER_SIZE,TRUE, TRUE); } static const unsigned char deflate_dummyheader[2] = {0x78, 0x9c}; /* dummy deflate header, used if deflate files do not start properly */ unsigned long DataStream_Compression::ReadDataL(unsigned char *buffer, unsigned long len, DataStream::DatastreamCommitPolicy sample) { if(compressing) LEAVE(OpStatus::ERR_OUT_OF_RANGE); work_buffer.AddContentL(AccessStreamSource(), (FL_ZIP_BUFFER_SIZE-512 > work_buffer.GetLength() ? FL_ZIP_BUFFER_SIZE-work_buffer.GetLength() : 512)) ; while(decompressed_buffer.GetLength() < len) { int ret = Z_OK; BOOL data_produced = FALSE; stream.next_in = work_buffer.GetDirectPayload(); stream.avail_in = work_buffer.GetLength(); if(stream.total_in == 0 && stream.next_in && ((((unsigned long) stream.next_in[0]) << 8) + stream.next_in[1]) % 31 != 0) { stream.next_in = (byte *) deflate_dummyheader; stream.avail_in = sizeof(deflate_dummyheader); stream.next_out = work_buffer1.GetDirectPayload(); stream.avail_out = work_buffer1.GetLength(); ret = inflate(&stream, Z_SYNC_FLUSH); if(ret != Z_OK && ret != Z_STREAM_END) LEAVE(ret == Z_MEM_ERROR ? (OP_STATUS) OpRecStatus::ERR_NO_MEMORY : (OP_STATUS) OpRecStatus::DECOMPRESSION_FAILED); continue; } while(stream.avail_in>0 && decompressed_buffer.GetLength() < len) { stream.next_out = work_buffer1.GetDirectPayload(); stream.avail_out = work_buffer1.GetLength(); ret = inflate(&stream, Z_SYNC_FLUSH); if(ret != Z_OK && ret != Z_STREAM_END) LEAVE(ret == Z_MEM_ERROR ? (OP_STATUS) OpRecStatus::ERR_NO_MEMORY : (OP_STATUS) OpRecStatus::DECOMPRESSION_FAILED); if(work_buffer1.GetLength() != stream.avail_out) { data_produced = TRUE; decompressed_buffer.WriteDataL(work_buffer1.GetDirectPayload(), work_buffer1.GetLength() - stream.avail_out); #if 0 DumpTofile(work_buffer1.GetDirectPayload(), work_buffer1.GetLength() - stream.avail_out, "Plaintext block (post-decompression)", "winsck.txt"); #endif } if(ret == Z_STREAM_END) { if(!stream.avail_in && !DataStream_Pipe::GetAttribute(DataStream::KMoreData)) break; // if more data reset decompression, and continue; inflateReset(&stream); } } if(!data_produced && work_buffer.GetLength() == stream.avail_in) break; work_buffer.CommitSampledBytesL(work_buffer.GetLength()-stream.avail_in); if(decompressed_buffer.GetLength() >= len) break; work_buffer.AddContentL(AccessStreamSource(), (FL_ZIP_BUFFER_SIZE-512 > work_buffer.GetLength() ? FL_ZIP_BUFFER_SIZE-work_buffer.GetLength() : 512)) ; } return decompressed_buffer.ReadDataL(buffer, len, sample); } #ifdef DATASTREAM_COMPRESSION_ENABLED void DataStream_Compression::CompressionStepL(const unsigned char *buffer, unsigned long len, int flush) { OP_ASSERT(buffer); #if 0 DumpTofile(buffer, len, "Plaintext block (pre-compression)", "winsck.txt"); #endif stream.next_in = (unsigned char *) buffer; stream.avail_in = len; do { uint32 offset = (alg != DataStream_Deflate_No_Header || stream.total_out ? 0 : 2); stream.next_out = work_buffer1.GetDirectPayload(); stream.avail_out = work_buffer1.GetLength(); int ret = deflate(&stream, flush); if(ret != Z_OK) LEAVE(ret == Z_MEM_ERROR ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR); DataStream_Pipe::WriteDataL(work_buffer1.GetDirectPayload()+offset, work_buffer1.GetLength() - stream.avail_out - offset); } while(stream.avail_in>0 || stream.avail_out == 0); } #endif void DataStream_Compression::WriteDataL(const unsigned char *buffer, unsigned long len) { #ifdef DATASTREAM_COMPRESSION_ENABLED if(!compressing || buffer == NULL || len == 0) return; CompressionStepL(buffer, len, Z_NO_FLUSH); #endif } uint32 DataStream_Compression::GetAttribute(DataStream::DatastreamUIntAttribute attr) { switch(attr) { case DataStream::KMoreData: if(decompressed_buffer.MoreData()) return TRUE; } return DataStream_Pipe::GetAttribute(attr); } void DataStream_Compression::PerformActionL(DataStream::DatastreamAction action, uint32 arg1, uint32 arg2) { #ifdef DATASTREAM_COMPRESSION_ENABLED switch(action) { case DataStream::KFinishedAdding: if(!compressing) return; CompressionStepL((byte *) g_memory_manager->GetTempBuf(), 0, Z_FINISH); } #endif DataStream_Pipe::PerformActionL(action, arg1, arg2); } void DataStream_Compression::FlushL() { #ifdef DATASTREAM_COMPRESSION_ENABLED if(!compressing) return; CompressionStepL((byte *) g_memory_manager->GetTempBuf(), 0, Z_SYNC_FLUSH); #endif } #endif
#include "SettingDeviceAddDialog.hpp" #include <QFormLayout> #include "ShoeManagerNetwork.hpp" #include "ShoeManagerNetworkResult.hpp" #include "QUtilsFramLessMessageBox.hpp" SettingDeviceAddDialog::SettingDeviceAddDialog(QWidget *widget) : QUtilsFramelessForm(widget) { initLayout(); initConnection(); } void SettingDeviceAddDialog::initLayout() { QFormLayout *form = new QFormLayout; { pLableName = new QLabel("名称"); pLabelIMEI = new QLabel("IMEI"); pLineName = new QLineEdit; pLineIMEI = new QLineEdit; form->addRow(pLableName, pLineName); form->addRow(pLabelIMEI, pLineIMEI); setFormLayout(form); setTitleText("添加设备"); } } void SettingDeviceAddDialog::initConnection() { connect(pButtonOK, &QPushButton::clicked, this, &SettingDeviceAddDialog::addDevice); } void SettingDeviceAddDialog::addDevice() { bool checkOK = true; do{ if(pLineName->text().trimmed().isEmpty()) { showPrompt("名称不能为空"); checkOK = false; break; } if(pLineIMEI->text().length() != 15) { showPrompt("IMEI不正确"); checkOK = false; break; } }while(false); if(checkOK == false) return; auto *result = ShoeManagerNetwork::getInstance()->bindDevice(pLineName->text(), pLineIMEI->text()); if(result->oReturnCode == 0) { this->accept(); } else { showPrompt(result->oReturnMessage); } }
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2013-2015 Regents of the University of California. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx 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 copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. * * @author Alexander Afanasyev <http://lasr.cs.ucla.edu/afanasyev/index.html> */ #include "encoder_test.hpp" #include "endian.hpp" namespace ndn { namespace encoding { Encoder::Encoder(size_t firstReserve) : m_wire(new Wire(firstReserve)) { } Encoder::Encodr(const Wire& wire) : m_wire(wire) { } size_t Encoder::appendByte(uint8_t value) { m_wire.reserve(1); m_wire.writeUint8(value); return 1; } size_t Encoder::appendByteArray(const uint8_t* array, size_t length) { m_wire.reserve(length); m_wire.appendArray(array,length); return length; } size_t Encoder::appendVarNumber(uint64_t varNumber) { if (varNumber < 253) { appendByte(static_cast<uint8_t>(varNumber)); return 1; } else if (varNumber <= std::numeric_limits<uint16_t>::max()) { appendByte(253); uint16_t value = htobe16(static_cast<uint16_t>(varNumber)); appendByteArray(reinterpret_cast<const uint8_t*>(&value), 2); return 3; } else if (varNumber <= std::numeric_limits<uint32_t>::max()) { appendByte(254); uint32_t value = htobe32(static_cast<uint32_t>(varNumber)); appendByteArray(reinterpret_cast<const uint8_t*>(&value), 4); return 5; } else { appendByte(255); uint64_t value = htobe64(varNumber); appendByteArray(reinterpret_cast<const uint8_t*>(&value), 8); return 9; } } size_t Encoder::appendNonNegativeInteger(uint64_t varNumber) { if (varNumber <= std::numeric_limits<uint8_t>::max()) { return appendByte(static_cast<uint8_t>(varNumber)); } else if (varNumber <= std::numeric_limits<uint16_t>::max()) { uint16_t value = htobe16(static_cast<uint16_t>(varNumber)); return appendByteArray(reinterpret_cast<const uint8_t*>(&value), 2); } else if (varNumber <= std::numeric_limits<uint32_t>::max()) { uint32_t value = htobe32(static_cast<uint32_t>(varNumber)); return appendByteArray(reinterpret_cast<const uint8_t*>(&value), 4); } else { uint64_t value = htobe64(varNumber); return appendByteArray(reinterpret_cast<const uint8_t*>(&value), 8); } } size_t Encoder::appendByteArrayBlock(uint32_t type, const uint8_t* array, size_t arraySize) { size_t totalLength = appendVarNumber(type); totalLength += appendVarNumber(arraySize); totalLength += appendByteArray(array, arraySize); return totalLength; } size_t Encoder::appendBlock(const BlockN& block) { size_t length = m_wire.appendBlock(block); return length; } } }
#ifndef AWS_NODES_FUNCTIONDEFINITION_H #define AWS_NODES_FUNCTIONDEFINITION_H /* * aws/nodes/functiondefinition.h * AwesomeScript Function Definition * Author: Dominykas Djacenka * Email: Chaosteil@gmail.com */ #include <list> #include <string> #include "statement.h" #include "variable.h" namespace AwS{ namespace Nodes{ class FunctionDefinition : public Statement{ public: FunctionDefinition(const std::string& name, std::list<Variable*>* variables, Statement* content) : Statement(), _name(name), _variables(variables), _content(content){ } virtual ~FunctionDefinition(){ if(_variables){ for(std::list<Variable*>::iterator i = _variables->begin(); i != _variables->end(); ++i){ if(*i)delete *i; } delete _variables; } } const std::string& getName() const { return _name; } const Statement* getContent() const{ return _content; } void translatePhp(std::ostream& output, TranslateSettings& settings) const throw(NodeException){ output << "function " << settings.getFunctionPrefix() << _name << "("; bool begin = true; for(std::list<Variable*>::iterator i = _variables->begin(); i != _variables->end(); ++i){ if(begin == false) output << ", "; (*i)->translatePhp(output, settings); begin = false; } output << "){" << std::endl; _content->translatePhp(output, settings); output << "}" << std::endl << std::endl; } private: const std::string _name; std::list<Variable*>* _variables; const Statement* _content; }; }; }; #endif
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #ifdef _WIN32 #define PUSH_PLATFORM_WINDOWS 1 #elif __APPLE__ #include "TargetConditionals.h" #if TARGET_IPHONE_SIMULATOR #define PUSH_PLATFORM_IOS 1 #elif TARGET_OS_IPHONE #define PUSH_PLATFORM_IOS 1 #elif TARGET_OS_MAC #define PUSH_PLATFORM_MACOS 1 #else #error Unknown platform #endif #else #error Unknown platform #endif
#include "hns-test.h" #include "dns-proto.h" #include <string> #include <vector> namespace hns { namespace test { TEST_F(DefaultChannelTest, GetServers) { std::vector<std::string> servers = GetNameServers(channel_); if (verbose) { for (const std::string& server : servers) { std::cerr << "Nameserver: " << server << std::endl; } } } TEST_F(DefaultChannelTest, GetServersFailures) { EXPECT_EQ(HNS_SUCCESS, hns_set_servers_csv(channel_, "1.2.3.4,2.3.4.5")); struct hns_addr_node* servers = nullptr; SetAllocFail(1); EXPECT_EQ(HNS_ENOMEM, hns_get_servers(channel_, &servers)); SetAllocFail(2); EXPECT_EQ(HNS_ENOMEM, hns_get_servers(channel_, &servers)); EXPECT_EQ(HNS_ENODATA, hns_get_servers(nullptr, &servers)); } TEST_F(DefaultChannelTest, SetServers) { EXPECT_EQ(HNS_SUCCESS, hns_set_servers(channel_, nullptr)); std::vector<std::string> empty; EXPECT_EQ(empty, GetNameServers(channel_)); struct hns_addr_node server1; struct hns_addr_node server2; server1.next = &server2; server1.family = AF_INET; server1.addr.addr4.s_addr = htonl(0x01020304); server2.next = nullptr; server2.family = AF_INET; server2.addr.addr4.s_addr = htonl(0x02030405); EXPECT_EQ(HNS_ENODATA, hns_set_servers(nullptr, &server1)); EXPECT_EQ(HNS_SUCCESS, hns_set_servers(channel_, &server1)); std::vector<std::string> expected = {"1.2.3.4", "2.3.4.5"}; EXPECT_EQ(expected, GetNameServers(channel_)); } TEST_F(DefaultChannelTest, SetServersPorts) { EXPECT_EQ(HNS_SUCCESS, hns_set_servers_ports(channel_, nullptr)); std::vector<std::string> empty; EXPECT_EQ(empty, GetNameServers(channel_)); struct hns_addr_port_node server1; struct hns_addr_port_node server2; server1.next = &server2; server1.family = AF_INET; server1.addr.addr4.s_addr = htonl(0x01020304); server1.udp_port = 111; server1.tcp_port = 111; server2.next = nullptr; server2.family = AF_INET; server2.addr.addr4.s_addr = htonl(0x02030405); server2.udp_port = 0; server2.tcp_port = 0;; EXPECT_EQ(HNS_ENODATA, hns_set_servers_ports(nullptr, &server1)); EXPECT_EQ(HNS_SUCCESS, hns_set_servers_ports(channel_, &server1)); std::vector<std::string> expected = {"1.2.3.4:111", "2.3.4.5"}; EXPECT_EQ(expected, GetNameServers(channel_)); } TEST_F(DefaultChannelTest, SetServersCSV) { EXPECT_EQ(HNS_ENODATA, hns_set_servers_csv(nullptr, "1.2.3.4")); EXPECT_EQ(HNS_ENODATA, hns_set_servers_csv(nullptr, "xyzzy,plugh")); EXPECT_EQ(HNS_ENODATA, hns_set_servers_csv(nullptr, "256.1.2.3")); EXPECT_EQ(HNS_ENODATA, hns_set_servers_csv(nullptr, "1.2.3.4.5")); EXPECT_EQ(HNS_ENODATA, hns_set_servers_csv(nullptr, "1:2:3:4:5")); EXPECT_EQ(HNS_SUCCESS, hns_set_servers_csv(channel_, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5")); std::vector<std::string> expected = {"1.2.3.4", "0102:0304:0506:0708:0910:1112:1314:1516", "2.3.4.5"}; EXPECT_EQ(expected, GetNameServers(channel_)); // Same, with spaces EXPECT_EQ(HNS_EBADSTR, hns_set_servers_csv(channel_, "1.2.3.4 , 0102:0304:0506:0708:0910:1112:1314:1516, 2.3.4.5")); // Same, with ports EXPECT_EQ(HNS_SUCCESS, hns_set_servers_csv(channel_, "1.2.3.4:54,[0102:0304:0506:0708:0910:1112:1314:1516]:80,2.3.4.5:55")); EXPECT_EQ(expected, GetNameServers(channel_)); EXPECT_EQ(HNS_SUCCESS, hns_set_servers_ports_csv(channel_, "1.2.3.4:54,[0102:0304:0506:0708:0910:1112:1314:1516]:80,2.3.4.5:55")); std::vector<std::string> expected2 = {"1.2.3.4:54", "[0102:0304:0506:0708:0910:1112:1314:1516]:80", "2.3.4.5:55"}; EXPECT_EQ(expected2, GetNameServers(channel_)); // Should survive duplication hns_channel channel2; EXPECT_EQ(HNS_SUCCESS, hns_dup(&channel2, channel_)); EXPECT_EQ(expected2, GetNameServers(channel2)); hns_destroy(channel2); // Allocation failure cases for (int fail = 1; fail <= 5; fail++) { SetAllocFail(fail); EXPECT_EQ(HNS_ENOMEM, hns_set_servers_csv(channel_, "1.2.3.4,0102:0304:0506:0708:0910:1112:1314:1516,2.3.4.5")); } // Blank servers EXPECT_EQ(HNS_SUCCESS, hns_set_servers_csv(channel_, "")); std::vector<std::string> none; EXPECT_EQ(none, GetNameServers(channel_)); EXPECT_EQ(HNS_EBADSTR, hns_set_servers_csv(channel_, "2.3.4.5,1.2.3.4:,3.4.5.6")); EXPECT_EQ(HNS_EBADSTR, hns_set_servers_csv(channel_, "2.3.4.5,1.2.3.4:Z,3.4.5.6")); } TEST_F(DefaultChannelTest, TimeoutValue) { struct timeval tinfo; tinfo.tv_sec = 0; tinfo.tv_usec = 0; struct timeval tmax; tmax.tv_sec = 0; tmax.tv_usec = 10; struct timeval* pt; // No timers => get max back. pt = hns_timeout(channel_, &tmax, &tinfo); EXPECT_EQ(&tmax, pt); EXPECT_EQ(0, pt->tv_sec); EXPECT_EQ(10, pt->tv_usec); pt = hns_timeout(channel_, nullptr, &tinfo); EXPECT_EQ(nullptr, pt); HostResult result; hns_gethostbyname(channel_, "www.google.com.", AF_INET, HostCallback, &result); // Now there's a timer running. pt = hns_timeout(channel_, &tmax, &tinfo); EXPECT_EQ(&tmax, pt); EXPECT_EQ(0, pt->tv_sec); EXPECT_EQ(10, pt->tv_usec); tmax.tv_sec = 100; pt = hns_timeout(channel_, &tmax, &tinfo); EXPECT_EQ(&tinfo, pt); pt = hns_timeout(channel_, nullptr, &tinfo); EXPECT_EQ(&tinfo, pt); Process(); } TEST_F(LibraryTest, InetNtoP) { struct in_addr addr; addr.s_addr = htonl(0x01020304); char buffer[256]; EXPECT_EQ(buffer, hns_inet_ntop(AF_INET, &addr, buffer, sizeof(buffer))); EXPECT_EQ("1.2.3.4", std::string(buffer)); } TEST_F(LibraryTest, Mkquery) { byte* p; int len; hns_mkquery("example.com", ns_c_in, ns_t_a, 0x1234, 0, &p, &len); std::vector<byte> data(p, p + len); hns_free_string(p); std::string actual = PacketToString(data); DNSPacket pkt; pkt.set_qid(0x1234).add_question(new DNSQuestion("example.com", ns_t_a)); std::string expected = PacketToString(pkt.data()); EXPECT_EQ(expected, actual); } TEST_F(LibraryTest, CreateQuery) { byte* p; int len; EXPECT_EQ(HNS_SUCCESS, hns_create_query("exam\\@le.com", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0)); std::vector<byte> data(p, p + len); hns_free_string(p); std::string actual = PacketToString(data); DNSPacket pkt; pkt.set_qid(0x1234).add_question(new DNSQuestion("exam@le.com", ns_t_a)); std::string expected = PacketToString(pkt.data()); EXPECT_EQ(expected, actual); } TEST_F(LibraryTest, CreateQueryTrailingEscapedDot) { byte* p; int len; EXPECT_EQ(HNS_SUCCESS, hns_create_query("example.com\\.", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0)); std::vector<byte> data(p, p + len); hns_free_string(p); std::string actual = PacketToString(data); EXPECT_EQ("REQ QRY Q:{'example.com\\.' IN A}", actual); } TEST_F(LibraryTest, CreateQueryNameTooLong) { byte* p; int len; EXPECT_EQ(HNS_EBADNAME, hns_create_query( "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789." "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789." "a1234567890123456789.b1234567890123456789.c1234567890123456789.d1234567890123456789." "x1234567890123456789.y1234567890123456789.", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0)); } TEST_F(LibraryTest, CreateQueryFailures) { byte* p; int len; // RC1035 has a 255 byte limit on names. std::string longname; for (int ii = 0; ii < 17; ii++) { longname += "fedcba9876543210"; } p = nullptr; EXPECT_EQ(HNS_EBADNAME, hns_create_query(longname.c_str(), ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0)); if (p) hns_free_string(p); SetAllocFail(1); p = nullptr; EXPECT_EQ(HNS_ENOMEM, hns_create_query("example.com", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0)); if (p) hns_free_string(p); // 63-char limit on a single label std::string longlabel = "a.a123456789b123456789c123456789d123456789e123456789f123456789g123456789.org"; p = nullptr; EXPECT_EQ(HNS_EBADNAME, hns_create_query(longlabel.c_str(), ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0)); if (p) hns_free_string(p); // Empty non-terminal label p = nullptr; EXPECT_EQ(HNS_EBADNAME, hns_create_query("example..com", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0)); if (p) hns_free_string(p); } TEST_F(DefaultChannelTest, SendFailure) { unsigned char buf[2]; SearchResult result; hns_send(channel_, buf, sizeof(buf), SearchCallback, &result); EXPECT_TRUE(result.done_); EXPECT_EQ(HNS_EBADQUERY, result.status_); } std::string ExpandName(const std::vector<byte>& data, int offset, long *enclen) { char *name = nullptr; int rc = hns_expand_name(data.data() + offset, data.data(), data.size(), &name, enclen); EXPECT_EQ(HNS_SUCCESS, rc); std::string result; if (rc == HNS_SUCCESS) { result = name; } else { result = "<error>"; } hns_free_string(name); return result; } TEST_F(LibraryTest, ExpandName) { long enclen; std::vector<byte> data1 = {1, 'a', 2, 'b', 'c', 3, 'd', 'e', 'f', 0}; EXPECT_EQ("a.bc.def", ExpandName(data1, 0, &enclen)); EXPECT_EQ(data1.size(), enclen); std::vector<byte> data2 = {0}; EXPECT_EQ("", ExpandName(data2, 0, &enclen)); EXPECT_EQ(1, enclen); // Complete name indirection std::vector<byte> data3 = {0x12, 0x23, 3, 'd', 'e', 'f', 0, 0xC0, 2}; EXPECT_EQ("def", ExpandName(data3, 2, &enclen)); EXPECT_EQ(5, enclen); EXPECT_EQ("def", ExpandName(data3, 7, &enclen)); EXPECT_EQ(2, enclen); // One label then indirection std::vector<byte> data4 = {0x12, 0x23, 3, 'd', 'e', 'f', 0, 1, 'a', 0xC0, 2}; EXPECT_EQ("def", ExpandName(data4, 2, &enclen)); EXPECT_EQ(5, enclen); EXPECT_EQ("a.def", ExpandName(data4, 7, &enclen)); EXPECT_EQ(4, enclen); // Two labels then indirection std::vector<byte> data5 = {0x12, 0x23, 3, 'd', 'e', 'f', 0, 1, 'a', 1, 'b', 0xC0, 2}; EXPECT_EQ("def", ExpandName(data5, 2, &enclen)); EXPECT_EQ(5, enclen); EXPECT_EQ("a.b.def", ExpandName(data5, 7, &enclen)); EXPECT_EQ(6, enclen); // Empty name, indirection to empty name std::vector<byte> data6 = {0x12, 0x23, 0, 0xC0, 2}; EXPECT_EQ("", ExpandName(data6, 2, &enclen)); EXPECT_EQ(1, enclen); EXPECT_EQ("", ExpandName(data6, 3, &enclen)); EXPECT_EQ(2, enclen); } TEST_F(LibraryTest, ExpandNameFailure) { std::vector<byte> data1 = {0x03, 'c', 'o', 'm', 0x00}; char *name = nullptr; long enclen; SetAllocFail(1); EXPECT_EQ(HNS_ENOMEM, hns_expand_name(data1.data(), data1.data(), data1.size(), &name, &enclen)); // Empty packet EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data1.data(), data1.data(), 0, &name, &enclen)); // Start beyond enclosing data EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data1.data() + data1.size(), data1.data(), data1.size(), &name, &enclen)); // Length beyond size of enclosing data std::vector<byte> data2a = {0x13, 'c', 'o', 'm', 0x00}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data2a.data(), data2a.data(), data2a.size(), &name, &enclen)); std::vector<byte> data2b = {0x1}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data2b.data(), data2b.data(), data2b.size(), &name, &enclen)); std::vector<byte> data2c = {0xC0}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data2c.data(), data2c.data(), data2c.size(), &name, &enclen)); // Indirection beyond enclosing data std::vector<byte> data3a = {0xC0, 0x02}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data3a.data(), data3a.data(), data3a.size(), &name, &enclen)); std::vector<byte> data3b = {0xC0, 0x0A, 'c', 'o', 'm', 0x00}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data3b.data(), data3b.data(), data3b.size(), &name, &enclen)); // Invalid top bits in label length std::vector<byte> data4 = {0x03, 'c', 'o', 'm', 0x00, 0x80, 0x00}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data4.data() + 5, data4.data(), data4.size(), &name, &enclen)); // Label too long: 64-byte label, with invalid top 2 bits of length (01). std::vector<byte> data5 = {0x40, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 0x00}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data5.data(), data5.data(), data5.size(), &name, &enclen)) << name; // Incomplete indirect length std::vector<byte> data6 = {0x03, 'c', 'o', 'm', 0x00, 0xC0}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data6.data() + 5, data6.data(), data6.size(), &name, &enclen)); // Indirection loops std::vector<byte> data7 = {0xC0, 0x02, 0xC0, 0x00}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data7.data(), data7.data(), data7.size(), &name, &enclen)); std::vector<byte> data8 = {3, 'd', 'e', 'f', 0xC0, 0x08, 0x00, 0x00, 3, 'a', 'b', 'c', 0xC0, 0x00}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data8.data(), data8.data(), data8.size(), &name, &enclen)); std::vector<byte> data9 = {0x12, 0x23, // start 2 bytes in 3, 'd', 'e', 'f', 0xC0, 0x02}; EXPECT_EQ(HNS_EBADNAME, hns_expand_name(data9.data() + 2, data9.data(), data9.size(), &name, &enclen)); } TEST_F(LibraryTest, CreateEDNSQuery) { byte* p; int len; EXPECT_EQ(HNS_SUCCESS, hns_create_query("example.com", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 1280)); std::vector<byte> data(p, p + len); hns_free_string(p); std::string actual = PacketToString(data); DNSPacket pkt; pkt.set_qid(0x1234).add_question(new DNSQuestion("example.com", ns_t_a)) .add_additional(new DNSOptRR(0, 1280)); std::string expected = PacketToString(pkt.data()); EXPECT_EQ(expected, actual); } TEST_F(LibraryTest, CreateRootQuery) { byte* p; int len; hns_create_query(".", ns_c_in, ns_t_a, 0x1234, 0, &p, &len, 0); std::vector<byte> data(p, p + len); hns_free_string(p); std::string actual = PacketToString(data); DNSPacket pkt; pkt.set_qid(0x1234).add_question(new DNSQuestion("", ns_t_a)); std::string expected = PacketToString(pkt.data()); EXPECT_EQ(expected, actual); } TEST_F(LibraryTest, Version) { // Assume linked to same version EXPECT_EQ(std::string(HNS_VERSION_STR), std::string(hns_version(nullptr))); int version; hns_version(&version); EXPECT_EQ(HNS_VERSION, version); } TEST_F(LibraryTest, Strerror) { EXPECT_EQ("Successful completion", std::string(hns_strerror(HNS_SUCCESS))); EXPECT_EQ("DNS query cancelled", std::string(hns_strerror(HNS_ECANCELLED))); EXPECT_EQ("unknown", std::string(hns_strerror(99))); } TEST_F(LibraryTest, ExpandString) { std::vector<byte> s1 = { 3, 'a', 'b', 'c'}; char* result = nullptr; long len; EXPECT_EQ(HNS_SUCCESS, hns_expand_string(s1.data(), s1.data(), s1.size(), (unsigned char**)&result, &len)); EXPECT_EQ("abc", std::string(result)); EXPECT_EQ(1 + 3, len); // amount of data consumed includes 1 byte len hns_free_string(result); result = nullptr; EXPECT_EQ(HNS_EBADSTR, hns_expand_string(s1.data() + 1, s1.data(), s1.size(), (unsigned char**)&result, &len)); EXPECT_EQ(HNS_EBADSTR, hns_expand_string(s1.data() + 4, s1.data(), s1.size(), (unsigned char**)&result, &len)); SetAllocSizeFail(3 + 1); EXPECT_EQ(HNS_ENOMEM, hns_expand_string(s1.data(), s1.data(), s1.size(), (unsigned char**)&result, &len)); } } // namespace test } // namespace hns
#include "MemoryManagement.h" #if defined(OBLIVION) #include "obse_common\SafeWrite.h" static const UInt32 kCreateTextureHook = 0x007610D3; #elif defined(NEWVEGAS) #include "nvse\SafeWrite.h" static const UInt32 kCreateTextureHook = 0x00E68DCD; #endif HRESULT __stdcall CreateTextureHook(LPDIRECT3DDEVICE9 pDevice, LPCVOID pSrcData, UINT SrcDataSize, LPDIRECT3DTEXTURE9* ppTexture) { return D3DXCreateTextureFromFileInMemoryEx(pDevice, pSrcData, SrcDataSize, D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, D3DFMT_UNKNOWN, D3DPOOL_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0, NULL, NULL, ppTexture); } void CreateMemoryManagementHook() { WriteRelCall(kCreateTextureHook, (UInt32)CreateTextureHook); }
#include <algorithm> #include <iterator> #include <memory> #include <regex> #include <sstream> #include <string> #include <tuple> #include <utility> #include <vector> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "arch_graph_automorphisms.h" #include "arch_graph_cluster.h" #include "arch_graph_system.h" #include "arch_uniform_super_graph.h" #include "dump.h" #include "perm.h" #include "perm_set.h" #include "permlib.h" #include "profile_parse.h" #include "profile_util.h" #include "task_allocation.h" namespace { std::vector<std::string> split_generators(std::string const &gen_str) { auto gen_first = gen_str.find('('); auto gen_last = gen_str.rfind(')'); auto gen_str_trimmed(gen_str.substr(gen_first, gen_last - gen_first + 1u)); auto res(split(gen_str_trimmed, "),")); if (res.size() > 0u) { for (auto i = 0u; i < res.size() - 1u; ++i) res[i] += ")"; } return res; } using gen_type = std::vector<std::vector<std::vector<unsigned>>>; std::pair<gen_type, unsigned> parse_generators( std::vector<std::string> const &gen_strs) { gen_type gens; unsigned largest_moved_point = 0u; for (auto const &gen_str : gen_strs) { gen_type::value_type perm; gen_type::value_type::value_type cycle; int n_beg = -1; for (int i = 0; i < static_cast<int>(gen_str.size()); ++i) { char c = gen_str[i]; switch (c) { case '(': cycle.clear(); break; case ',': case ')': { int n = stox<int>(gen_str.substr(n_beg, i - n_beg)); largest_moved_point = std::max(largest_moved_point, static_cast<unsigned>(n)); cycle.push_back(n); if (c == ')') perm.push_back(cycle); n_beg = -1; } break; default: if (n_beg == -1) n_beg = i; } } gens.push_back(perm); } return {gens, largest_moved_point}; } cgtl::PermSet convert_generators_mpsym(unsigned degree, gen_type const &gens) { cgtl::PermSet gens_conv; for (auto const &gen : gens) gens_conv.emplace(degree, gen); return gens_conv; } permlib::PermSet convert_generators_permlib(unsigned degree, gen_type const &gens) { std::vector<permlib::Permutation::ptr> gens_conv(gens.size()); for (auto i = 0u; i < gens.size(); ++i) { auto &gen(gens[i]); std::stringstream gen_str; for (auto j = 0u; j < gen.size(); ++j) { auto &cycle(gens[i][j]); for (auto k = 0u; k < cycle.size(); ++k) { gen_str << cycle[k]; if (k == cycle.size() - 1) { if (j < gen.size() - 1) gen_str << ", "; } else { gen_str << " "; } } } gens_conv[i] = permlib::Permutation::ptr( new permlib::Permutation(degree, gen_str.str())); } return {degree, gens_conv}; } std::tuple<unsigned, unsigned, std::vector<cgtl::TaskAllocation>> split_task_allocations(std::string const &task_allocations_str, std::string const &regex_str, char delim) { unsigned num_tasks = 0u; unsigned min_pe = UINT_MAX; unsigned max_pe = 0u; std::vector<cgtl::TaskAllocation> task_allocations; std::stringstream ss(task_allocations_str); std::regex re_task_allocation(regex_str); std::string line; while (std::getline(ss, line)) { std::smatch m; if (!std::regex_match(line, m, re_task_allocation)) throw std::invalid_argument("malformed task allocation expression"); cgtl::TaskAllocation task_allocation; std::string task_allocation_str(m[1]); std::size_t pos_begin = 0u; std::size_t pos_end; unsigned pe; for (;;) { pos_end = task_allocation_str.find(delim, pos_begin); pe = stox<unsigned>( pos_end == std::string::npos ? task_allocation_str.substr(pos_begin) : task_allocation_str.substr(pos_begin, pos_end - pos_begin)); min_pe = std::min(pe, min_pe); max_pe = std::max(pe, max_pe); task_allocation.push_back(pe); if (pos_end == std::string::npos) break; pos_begin = pos_end + 1u; } if (num_tasks == 0u) { num_tasks = task_allocation.size(); } else if (task_allocation.size() != num_tasks) { throw std::invalid_argument( "currently only equally sized task sets are supported"); } task_allocations.push_back(task_allocation); } return {min_pe, max_pe, task_allocations}; } } // namespace GenericGroup parse_group(std::string const &group_str) { static std::regex re_group("degree:(\\d+),order:(\\d+),gens:(.*)"); static std::string re_perm = R"((\(\)|(\((\d+,)+\d+\))+))"; static std::regex re_generators("\\[(" + re_perm + ",)*(" + re_perm + ")?\\]"); std::smatch m; if (!std::regex_match(group_str, m, re_group)) throw std::invalid_argument("malformed group expression"); unsigned degree = stox<unsigned>(m[1]); unsigned long long order; try { order = stox<unsigned long long>(m[2]); } catch (std::invalid_argument const &) { throw std::invalid_argument("group order too large"); } std::string gen_str = m[3]; if (!std::regex_match(gen_str, re_generators)) throw std::invalid_argument("malformed generator expression"); return {degree, order, gen_str}; } gap::PermSet parse_generators_gap(unsigned degree, std::string const &gen_str) { return {degree, gen_str}; } cgtl::PermSet parse_generators_mpsym(unsigned degree, std::string const &gen_str) { gen_type gen_vect; unsigned largest_moved_point; std::tie(gen_vect, largest_moved_point) = parse_generators(split_generators(gen_str)); return convert_generators_mpsym(degree == 0 ? largest_moved_point : degree, gen_vect); } permlib::PermSet parse_generators_permlib(unsigned degree, std::string const &gen_str) { gen_type gen_vect; unsigned largest_moved_point; std::tie(gen_vect, largest_moved_point) = parse_generators(split_generators(gen_str)); return convert_generators_permlib(degree == 0 ? largest_moved_point : degree, gen_vect); } gap::TaskAllocationVector parse_task_allocations_gap( std::string const &task_allocations_str) { auto task_allocations( split_task_allocations(task_allocations_str, R"((\d+(?: \d+)*))", ' ')); std::stringstream ss; for (auto const &task_allocation : std::get<2>(task_allocations)) ss << DUMP(task_allocation) << ",\n"; return {std::get<0>(task_allocations), std::get<1>(task_allocations), ss.str()}; } cgtl::TaskAllocationVector parse_task_allocations_mpsym( std::string const &task_allocations_str) { auto task_allocations( split_task_allocations(task_allocations_str, R"((\d+(?: \d+)*))", ' ')); return {std::get<0>(task_allocations), std::get<1>(task_allocations), std::get<2>(task_allocations)}; } cgtl::TaskAllocationVector parse_task_allocations_gap_to_mpsym( std::string const &gap_output_str) { static std::regex re_task_allocations( R"(Found \d+ orbit representatives\n((?:.|\n)*))"); std::smatch m; if (!std::regex_search(gap_output_str, m, re_task_allocations)) throw std::invalid_argument("malformed gap output"); auto task_allocations(split_task_allocations( m[1], R"(.*\[ (\d+(?:, \d+)*) \])", ',')); return {std::get<0>(task_allocations), std::get<1>(task_allocations), std::get<2>(task_allocations)}; }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include "Timeline.h" #include "Manager.h" namespace Tween { Timeline *timeline () { return Manager::getMain ()->newTimeline (); } /****************************************************************************/ void Timeline::initExit (bool reverse) { currentRepetition = repetitions; } /****************************************************************************/ void Timeline::finishedExit (bool reverse) { currentRepetition = repetitions; } /****************************************************************************/ void Timeline::runEntry (bool reverse) { current = tweens.begin (); currentr = tweens.rbegin (); } /****************************************************************************/ void Timeline::updateRun (int deltaMs, bool direction) { if (direction) { (*current)->update (deltaMs, !direction); } else { (*currentr)->update (deltaMs, !direction); } } /****************************************************************************/ bool Timeline::checkEnd (bool direction) { // return (direction && (*current)->getState () == FINISHED && ++current == tweens.end ()) || // (!direction && (*currentr)->getState () == INIT && ++currentr == tweens.rend ()); ++current; ++currentr; return ((*current)->getState () == END && current == tweens.end ()); } /****************************************************************************/ Timeline *Timeline::add (ITween *tween) { tweens.push_back (tween); current = tweens.begin (); return this; } } /* namespace Tween */
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); /******************************************************************************** *** @desc: Creating variables used *** *** @param: *** *** @variables: QString strFileList: Saves the path to the file list *** QString strFirmware: Saves the path to the firmware ********************************************************************************/ private: QString strFileList; QString strFirmware; /******************************************************************************** *** @desc: Creating button events *** *** @param: *** *** @functions: void on_btOK_clicked(): Event when OK button is clicked *** void on_btFileList_clicked(): Event when find button next to *** File List ist clicked *** void on_btFirmware_clicked(): Event when find button next to *** Firmware is clicked ********************************************************************************/ private slots: void on_btOK_clicked(); void on_btFileList_clicked(); void on_btFirmware_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
#include <Windows.h> #include <iostream> #include <functional> #include <random> #include <ctime> #include <list> ATOM RegisterCustomClass(HINSTANCE& hInstance); LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam); void StartGame(HWND hWnd); void EndGame(HWND hWnd); LPCTSTR Title = L"Alkanoid"; HINSTANCE g_hInst; HWND hMainWnd; HBITMAP MemBit; int SWidth, SHeight; int NumBall = 1; std::function<int()> RandInt = std::bind(std::uniform_int_distribution<int>{ INT_MIN, INT_MAX }, std::default_random_engine{ (unsigned int(time(0))) }); std::function<double()> RandDbl = std::bind(std::uniform_real_distribution<double>{-1.0,1.0}, std::default_random_engine{ (unsigned int(time(0))) }); struct Vec2D { double x, y; double LengthSQ(){ return x*x + y*y; } double Length(){ return sqrt(LengthSQ());} Vec2D Rotate(double theta){ return{ x*cos(theta) - y*sin(theta), x*sin(theta) + y*cos(theta) }; } Vec2D Normalize(){ return{ x / Length(), y / Length() }; } Vec2D operator+(Vec2D& Other){ return{ x + Other.x, y + Other.y }; } Vec2D& operator+=(Vec2D& Other){ x += Other.x; y += Other.y; return *this; } Vec2D operator-(Vec2D& Other){ return{ x -Other.x, y -Other.y }; } Vec2D& operator-=(Vec2D& Other){ x -= Other.x; y -= Other.y; return *this; } Vec2D operator*(double Mult){ return{ x*Mult, y*Mult }; } Vec2D& operator*=(double Mult){ x *= Mult; y *= Mult; return *this; } Vec2D operator/(double Div){ return{ x / Div, y / Div }; } Vec2D& operator/=(double Div){ x /= Div, y /= Div; return *this; } double DotProduct(Vec2D& Other){ return x*Other.x + y*Other.y; } Vec2D(double x, double y) :x{ x }, y{ y }{}; Vec2D() :x{ 0 }, y{ 0 }{}; }; class Entity { protected: Vec2D Pos; Vec2D Vel; Vec2D Size; double angle; Entity(Vec2D P = Vec2D(), Vec2D V = Vec2D(), Vec2D S = Vec2D(), double angle = 0) :Pos{ P }, Vel{ V }, Size{ S }, angle{ angle }{}; virtual void Move(){ Pos += Vel; } virtual void Print(HDC) = 0; }; class Block : public Entity { HBRUSH myColorBrush; COLORREF Color; public: static std::list<Block*> Blocks; Block(Vec2D P = Vec2D(), Vec2D V = Vec2D(), Vec2D S = Vec2D(50, 50), COLORREF C = RGB(RandInt() % 255, RandInt() % 255, RandInt() % 255)) :Entity(P, V, S), Color{ C } { myColorBrush = CreateSolidBrush(Color); } ~Block() { DeleteObject(myColorBrush); } virtual void Print(HDC hdc) { SelectObject(hdc, GetStockObject(NULL_PEN)); SelectObject(hdc, myColorBrush); Rectangle(hdc, Pos.x - Size.x, Pos.y - Size.y, Pos.x + Size.x, Pos.y + Size.y); } virtual void Move(){} bool isPtOnMe(int ax, int ay) { if (abs(ax - Pos.x) > Size.x || abs(ay - Pos.y) > Size.y) return false; else return true; } }; std::list<Block*> Block::Blocks; enum { ID_CHILDWINDOW = 100 }; class Ball : public Entity { public: bool Alive; enum dir{LEFT,DOWN,RIGHT,UP}; virtual void Print(HDC hdc) { Ellipse(hdc, Pos.x - Size.x, Pos.y - Size.y, Pos.x + Size.x, Pos.y + Size.y); } virtual void Move() { Pos += Vel; if (Pos.x < 0) { Bounce(dir::LEFT); } if (Pos.x > SWidth) { Bounce(dir::RIGHT); } if (Pos.y < 0) { Bounce(dir::UP); } if (Pos.y > SHeight) { Alive = false; } } bool isBlockThere(Block* B) { Vec2D HS = Size / 2; if (B->isPtOnMe(Pos.x-HS.x, Pos.y)) //left { Bounce(dir::LEFT); return true; } if (B->isPtOnMe(Pos.x+HS.x, Pos.y)) //Right { Bounce(dir::RIGHT); return true; } if (B->isPtOnMe(Pos.x, Pos.y-HS.y)) //Up { Bounce(dir::UP); return true; } if (B->isPtOnMe(Pos.x - HS.x, Pos.y+HS.y)) //Down { Bounce(dir::DOWN); return true; } return false; } bool isBallThere(Ball* B) { Vec2D Rel(Pos.x - B->Pos.x, Pos.y- B->Pos.y); if (Rel.LengthSQ() < B->Size.x*B->Size.y + Size.x*Size.y) { Bounce(Rel); return true; //°مؤ§ } else return false; } void Bounce(dir D) { switch (D) { case dir::LEFT: Vel.x = abs(Vel.x); break; case dir::RIGHT: Vel.x = -abs(Vel.x); break; case dir::UP: Vel.y = abs(Vel.y); break; case dir::DOWN: Vel.y = -abs(Vel.y); //DIE break; } } void Bounce(Vec2D Axis) { Vec2D n = Axis.Normalize(); Vel = Vel - n * 2 * (Vel.DotProduct(n)); Vel = (Vel + n*3).Normalize() * Vel.Length(); } public: Ball(Vec2D P = Vec2D(SWidth/2,SHeight*0.9-30), Vec2D V = Vec2D(10*RandDbl(),-10*abs(RandDbl())).Normalize()*3, Vec2D S = Vec2D(20,20), double angle = 0) :Entity(P, V, S, angle) { angle = atan2(-V.y, V.x); } } *Sphere; class Racket : public Ball { public: bool Left, Right, Up, Down; void Impulse(dir D, bool Push) { switch (D) { case dir::LEFT: Left = Push; break; case dir::RIGHT: Right = Push; break; case dir::UP: Up = Push; break; case dir::DOWN: Down = Push; break; } } virtual void Move() { if (Left) Vel.x -= 0.5; if (Right) Vel.x += 0.5; if (Down) Vel.y += 0.5; if (Up) Vel.y -= 0.5; Pos += Vel; if (Pos.x < 0) { Bounce(dir::LEFT); } if (Pos.x > SWidth) { Bounce(dir::RIGHT); } if (Pos.y < 0) { Bounce(dir::UP); } if (Pos.y > SHeight) { Bounce(dir::DOWN); } Vel *= 0.9; } Racket(Vec2D P = Vec2D(SWidth / 2, SHeight*0.9+50), Vec2D V = Vec2D(), Vec2D S = Vec2D(50, 50), double angle = 0):Ball(P, V, S, angle) { Left = Right = Up = Down = false; } } *Me; ATOM RegisterCustomClass(HINSTANCE& hInstance) { WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hInstance = hInstance; wc.lpfnWndProc = WndProc; wc.lpszClassName = Title; wc.lpszMenuName = NULL; wc.style = CS_VREDRAW | CS_HREDRAW; return RegisterClass(&wc); } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) { g_hInst = hInstance; RegisterCustomClass(hInstance); hMainWnd = CreateWindow(Title, Title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ShowWindow(hMainWnd, nCmdShow); MSG msg; while (GetMessage(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hWnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { switch (iMsg) { case WM_CREATE: { StartGame(hWnd); } break; case WM_TIMER: { HDC hdc = GetDC(hWnd); HDC MemDC = CreateCompatibleDC(hdc); HBITMAP OldBit = (HBITMAP)SelectObject(MemDC, MemBit); RECT R{ 0, 0, SWidth, SHeight }; FillRect(MemDC, &R, (HBRUSH)GetStockObject(WHITE_BRUSH)); for (int i = 0; i < 3; ++i) { if (Sphere->isBallThere(Me)) Sphere->Move(); Sphere->Move(); Sphere->Print(MemDC); Me->Move(); Me->Print(MemDC); } for (auto i = Block::Blocks.begin(); i != Block::Blocks.end();) { Block* b = *i++; if (Sphere->isBlockThere(b)) { Block::Blocks.remove(b); delete b; } else { b->Print(MemDC); } } //Draw Stuff if (!Sphere->Alive) { if (--NumBall < 1) { EndGame(hWnd); if (MessageBox(hWnd, L"RESTART?", L"GAME OVER", MB_OKCANCEL) == IDOK) StartGame(hWnd); else DestroyWindow(hWnd); } } SelectObject(MemDC, OldBit); DeleteObject(MemDC); ReleaseDC(hWnd, hdc); InvalidateRect(hWnd, NULL, FALSE); } break; case WM_LBUTTONDOWN: { int x = LOWORD(lParam); int y = HIWORD(lParam); for (auto i = Block::Blocks.begin(); i != Block::Blocks.end();) { Block* b = *i++; if (b->isPtOnMe(x, y)) { Block::Blocks.remove(b); delete b; } } break; } case WM_KEYDOWN: { switch (wParam) { case 'A': case VK_LEFT: Me->Impulse(Ball::dir::LEFT, true); break; case 'D': case VK_RIGHT: Me->Impulse(Ball::dir::RIGHT, true); break; case 'S': case VK_DOWN: Me->Impulse(Ball::dir::DOWN, true); break; case 'W': case VK_UP: Me->Impulse(Ball::dir::UP, true); break; case VK_ESCAPE: EndGame(hWnd); if (MessageBox(hWnd, L"RESTART?", L"GAME OVER", MB_OKCANCEL) == IDOK) StartGame(hWnd); break; } break; } case WM_KEYUP: { switch (wParam) { case 'A': case VK_LEFT: Me->Impulse(Ball::dir::LEFT, false); break; case 'D': case VK_RIGHT: Me->Impulse(Ball::dir::RIGHT, false); break; case 'S': case VK_DOWN: Me->Impulse(Ball::dir::DOWN, false); break; case 'W': case VK_UP: Me->Impulse(Ball::dir::UP, false); break; } break; } case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); HDC MemDC = CreateCompatibleDC(hdc); HBITMAP OldBit = (HBITMAP)SelectObject(MemDC, MemBit); BitBlt(hdc, 0, 0, SWidth, SHeight, MemDC, 0, 0, SRCCOPY); SelectObject(MemDC, OldBit); DeleteObject(MemDC); EndPaint(hWnd, &ps); } break; case WM_SIZE: { RECT R; GetClientRect(hWnd, &R); SHeight = R.bottom - R.top; SWidth = R.right - R.left; } break; case WM_DESTROY: EndGame(hWnd); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, iMsg, wParam, lParam); } return 0; } void StartGame(HWND hWnd) { HDC hdc = GetDC(hWnd); MemBit = CreateCompatibleBitmap(hdc, GetDeviceCaps(hdc, HORZRES), GetDeviceCaps(hdc, VERTRES)); SetTimer(hWnd, 0, 10, NULL); SendMessage(hWnd, WM_SIZE, NULL, NULL); for (int i = 0; i < SHeight / 3; i += 30) { for (int j = 0; j < SWidth; j += 70) { Block::Blocks.push_back(new Block{ { (double)j, (double)i }, { 0, 0 }, { 35, 15 } }); } } Me = new Racket(); Sphere = new Ball(); NumBall = 1; Me->Print(hdc); Sphere->Print(hdc); ReleaseDC(hWnd, hdc); } void EndGame(HWND hWnd) { KillTimer(hWnd, 0); DeleteObject(MemBit); for (auto b : Block::Blocks) delete b; delete Me; Me = nullptr; delete Sphere; Sphere = nullptr; Block::Blocks.clear(); }
#include<iostream> #include<math.h> #include <iomanip> using namespace std; int main(){ int n; float mi = 0; float sigma2 = 0; cout << "Digite um número inteiro: "; cin >> n; float *values = new float[n]; for(int i=0; i < n; i++){ cout << "(" << i+1 << "/" << n << ") " << "Digite um número fracionário: \n"; cin >> values[i]; } for(int i=0; i < n; i++){ mi += values[i]; } mi = mi/n; for(int i=0; i < n; i++){ sigma2 += pow(values[i] - mi, 2); } sigma2 = sigma2/n; cout << "Media: " << setprecision(10) << mi << "\n"; cout << "Variancia: " << setprecision(10) << sigma2 << "\n"; return 0; }
/* book.h */ #ifndef book_h #define book_h #include <unordered_map> #include <assert.h> #include "limit.h" #include "order.h" //forward declaration class Order; class Limit; class Book { public: Book(); void AddOrder(int timestamp,char id, bool isBid, int price, int size); void ReduceOrder(int timestamp,char id, int size); Limit * GetBestOffer(); Limit * GetBestBid(); int GetVolumeAtLimit(int x); int Price(int targetSize); Limit * buyTree; Limit * sellTree; Limit * lowSell; Limit * highBuy; std::unordered_map <char, Order*> orderMap; std::unordered_map <int, Limit*> priceMap; Limit * buyCache; Limit * sellCache; }; #endif
#ifndef RENDER_H # define RENDER_H # include "engine.h" class Render; typedef struct s_thread { int id; FILE *f; // Already at the correct cursor location long count; // In number of particles Render *dad; } t_thread; class Render { public: int width; int height; SDL_Window *win; SDL_Renderer *ren; Camera *cam; long tick; double scale; std::string path; Uint8 *keystate; SDL_mutex *mutex; SDL_cond *start_cond; SDL_cond *done_cond; int num_threads; int running_threads; SDL_Texture *tex; std::vector<unsigned char> pixels; Render(int w = 640, int h = 480, std::string path = "data/test-"); void set_scale(); void draw(); void loop(long start, long end); void wait_for_death(); ~Render(); private: std::vector<t_thread*> threads; void init_threading(); void organize_threads(long par); }; #endif
// Copyright (c) 2007-2021 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <pika/config.hpp> #include <cstddef> #include <cstdint> #include <cstring> // NOLINTBEGIN(bugprone-reserved-identifier) struct ___itt_caller; struct ___itt_string_handle; struct ___itt_domain; struct ___itt_id; using __itt_heap_function = void*; struct ___itt_counter; // NOLINTEND(bugprone-reserved-identifier) /////////////////////////////////////////////////////////////////////////////// #define PIKA_ITT_SYNC_CREATE(obj, type, name) itt_sync_create(obj, type, name) #define PIKA_ITT_SYNC_RENAME(obj, name) itt_sync_rename(obj, name) #define PIKA_ITT_SYNC_PREPARE(obj) itt_sync_prepare(obj) #define PIKA_ITT_SYNC_CANCEL(obj) itt_sync_cancel(obj) #define PIKA_ITT_SYNC_ACQUIRED(obj) itt_sync_acquired(obj) #define PIKA_ITT_SYNC_RELEASING(obj) itt_sync_releasing(obj) #define PIKA_ITT_SYNC_RELEASED(obj) itt_sync_released(obj) #define PIKA_ITT_SYNC_DESTROY(obj) itt_sync_destroy(obj) #define PIKA_ITT_STACK_CREATE(ctx) ctx = itt_stack_create() #define PIKA_ITT_STACK_CALLEE_ENTER(ctx) itt_stack_enter(ctx) #define PIKA_ITT_STACK_CALLEE_LEAVE(ctx) itt_stack_leave(ctx) #define PIKA_ITT_STACK_DESTROY(ctx) itt_stack_destroy(ctx) #define PIKA_ITT_FRAME_BEGIN(frame, id) itt_frame_begin(frame, id) #define PIKA_ITT_FRAME_END(frame, id) itt_frame_end(frame, id) #define PIKA_ITT_MARK_CREATE(mark, name) mark = itt_mark_create(name) #define PIKA_ITT_MARK_OFF(mark) itt_mark_off(mark) #define PIKA_ITT_MARK(mark, parameter) itt_mark(mark, parameter) #define PIKA_ITT_THREAD_SET_NAME(name) itt_thread_set_name(name) #define PIKA_ITT_THREAD_IGNORE() itt_thread_ignore() #define PIKA_ITT_TASK_BEGIN(domain, name) itt_task_begin(domain, name) #define PIKA_ITT_TASK_BEGIN_ID(domain, id, name) itt_task_begin(domain, id, name) #define PIKA_ITT_TASK_END(domain) itt_task_end(domain) #define PIKA_ITT_DOMAIN_CREATE(name) itt_domain_create(name) #define PIKA_ITT_STRING_HANDLE_CREATE(name) itt_string_handle_create(name) #define PIKA_ITT_MAKE_ID(addr, extra) itt_make_id(addr, extra) #define PIKA_ITT_ID_CREATE(domain, id) itt_id_create(domain, id) #define PIKA_ITT_ID_DESTROY(id) itt_id_destroy(id) #define PIKA_ITT_HEAP_FUNCTION_CREATE(name, domain) itt_heap_function_create(name, domain) /**/ #define PIKA_ITT_HEAP_ALLOCATE_BEGIN(f, size, initialized) \ itt_heap_allocate_begin(f, size, initialized) /**/ #define PIKA_ITT_HEAP_ALLOCATE_END(f, addr, size, initialized) \ itt_heap_allocate_end(f, addr, size, initialized) /**/ #define PIKA_ITT_HEAP_FREE_BEGIN(f, addr) itt_heap_free_begin(f, addr) #define PIKA_ITT_HEAP_FREE_END(f, addr) itt_heap_free_end(f, addr) #define PIKA_ITT_HEAP_REALLOCATE_BEGIN(f, addr, new_size, initialized) \ itt_heap_reallocate_begin(f, addr, new_size, initialized) /**/ #define PIKA_ITT_HEAP_REALLOCATE_END(f, addr, new_addr, new_size, initialized) \ itt_heap_reallocate_end(f, addr, new_addr, new_size, initialized) /**/ #define PIKA_ITT_HEAP_INTERNAL_ACCESS_BEGIN() itt_heap_internal_access_begin() #define PIKA_ITT_HEAP_INTERNAL_ACCESS_END() itt_heap_internal_access_end() #define PIKA_ITT_COUNTER_CREATE(name, domain) itt_counter_create(name, domain) /**/ #define PIKA_ITT_COUNTER_CREATE_TYPED(name, domain, type) \ itt_counter_create_typed(name, domain, type) /**/ #define PIKA_ITT_COUNTER_SET_VALUE(id, value_ptr) itt_counter_set_value(id, value_ptr) /**/ #define PIKA_ITT_COUNTER_DESTROY(id) itt_counter_destroy(id) #define PIKA_ITT_METADATA_ADD(domain, id, key, data) itt_metadata_add(domain, id, key, data) /**/ /////////////////////////////////////////////////////////////////////////////// // decide whether to use the ITT notify API if it's available #if PIKA_HAVE_ITTNOTIFY != 0 PIKA_EXPORT extern bool use_ittnotify_api; /////////////////////////////////////////////////////////////////////////////// PIKA_EXPORT void itt_sync_create(void* addr, const char* objtype, const char* objname) noexcept; PIKA_EXPORT void itt_sync_rename(void* addr, const char* name) noexcept; PIKA_EXPORT void itt_sync_prepare(void* addr) noexcept; PIKA_EXPORT void itt_sync_acquired(void* addr) noexcept; PIKA_EXPORT void itt_sync_cancel(void* addr) noexcept; PIKA_EXPORT void itt_sync_releasing(void* addr) noexcept; PIKA_EXPORT void itt_sync_released(void* addr) noexcept; PIKA_EXPORT void itt_sync_destroy(void* addr) noexcept; PIKA_EXPORT ___itt_caller* itt_stack_create() noexcept; PIKA_EXPORT void itt_stack_enter(___itt_caller* ctx) noexcept; PIKA_EXPORT void itt_stack_leave(___itt_caller* ctx) noexcept; PIKA_EXPORT void itt_stack_destroy(___itt_caller* ctx) noexcept; PIKA_EXPORT void itt_frame_begin(___itt_domain const* frame, ___itt_id* id) noexcept; PIKA_EXPORT void itt_frame_end(___itt_domain const* frame, ___itt_id* id) noexcept; PIKA_EXPORT int itt_mark_create(char const*) noexcept; PIKA_EXPORT void itt_mark_off(int mark) noexcept; PIKA_EXPORT void itt_mark(int mark, char const*) noexcept; PIKA_EXPORT void itt_thread_set_name(char const*) noexcept; PIKA_EXPORT void itt_thread_ignore() noexcept; PIKA_EXPORT void itt_task_begin(___itt_domain const*, ___itt_string_handle*) noexcept; PIKA_EXPORT void itt_task_begin(___itt_domain const*, ___itt_id*, ___itt_string_handle*) noexcept; PIKA_EXPORT void itt_task_end(___itt_domain const*) noexcept; PIKA_EXPORT ___itt_domain* itt_domain_create(char const*) noexcept; PIKA_EXPORT ___itt_string_handle* itt_string_handle_create(char const*) noexcept; PIKA_EXPORT ___itt_id* itt_make_id(void*, std::size_t); PIKA_EXPORT void itt_id_create(___itt_domain const*, ___itt_id* id) noexcept; PIKA_EXPORT void itt_id_destroy(___itt_id* id) noexcept; PIKA_EXPORT __itt_heap_function itt_heap_function_create(const char*, const char*) noexcept; PIKA_EXPORT void itt_heap_allocate_begin(__itt_heap_function, std::size_t, int) noexcept; PIKA_EXPORT void itt_heap_allocate_end(__itt_heap_function, void**, std::size_t, int) noexcept; PIKA_EXPORT void itt_heap_free_begin(__itt_heap_function, void*) noexcept; PIKA_EXPORT void itt_heap_free_end(__itt_heap_function, void*) noexcept; PIKA_EXPORT void itt_heap_reallocate_begin(__itt_heap_function, void*, std::size_t, int) noexcept; PIKA_EXPORT void itt_heap_reallocate_end( __itt_heap_function, void*, void**, std::size_t, int) noexcept; PIKA_EXPORT void itt_heap_internal_access_begin() noexcept; PIKA_EXPORT void itt_heap_internal_access_end() noexcept; PIKA_EXPORT ___itt_counter* itt_counter_create(char const*, char const*) noexcept; PIKA_EXPORT ___itt_counter* itt_counter_create_typed(char const*, char const*, int) noexcept; PIKA_EXPORT void itt_counter_destroy(___itt_counter*) noexcept; PIKA_EXPORT void itt_counter_set_value(___itt_counter*, void*) noexcept; PIKA_EXPORT int itt_event_create(char const* name, int namelen) noexcept; PIKA_EXPORT int itt_event_start(int evnt) noexcept; PIKA_EXPORT int itt_event_end(int evnt) noexcept; PIKA_EXPORT void itt_metadata_add(___itt_domain* domain, ___itt_id* id, ___itt_string_handle* key, std::uint64_t const& data) noexcept; PIKA_EXPORT void itt_metadata_add( ___itt_domain* domain, ___itt_id* id, ___itt_string_handle* key, double const& data) noexcept; PIKA_EXPORT void itt_metadata_add( ___itt_domain* domain, ___itt_id* id, ___itt_string_handle* key, char const* data) noexcept; PIKA_EXPORT void itt_metadata_add( ___itt_domain* domain, ___itt_id* id, ___itt_string_handle* key, void const* data) noexcept; /////////////////////////////////////////////////////////////////////////////// namespace pika::detail { struct thread_description; } // namespace pika::detail namespace pika { namespace util { namespace itt { struct stack_context { PIKA_EXPORT stack_context(); PIKA_EXPORT ~stack_context(); stack_context(stack_context const& rhs) = delete; stack_context(stack_context&& rhs) noexcept : itt_context_(rhs.itt_context_) { rhs.itt_context_ = nullptr; } stack_context& operator=(stack_context const& rhs) = delete; stack_context& operator=(stack_context&& rhs) noexcept { if (this != &rhs) { itt_context_ = rhs.itt_context_; rhs.itt_context_ = nullptr; } return *this; } struct ___itt_caller* itt_context_ = nullptr; }; struct caller_context { PIKA_EXPORT caller_context(stack_context& ctx); PIKA_EXPORT ~caller_context(); stack_context& ctx_; }; ////////////////////////////////////////////////////////////////////////// struct domain { PIKA_NON_COPYABLE(domain); domain() = default; PIKA_EXPORT domain(char const*) noexcept; ___itt_domain* domain_ = nullptr; }; struct thread_domain : domain { PIKA_NON_COPYABLE(thread_domain); PIKA_EXPORT thread_domain() noexcept; }; struct id { PIKA_EXPORT id(domain const& domain, void* addr, unsigned long extra = 0) noexcept; PIKA_EXPORT ~id(); id(id const& rhs) = delete; id(id&& rhs) noexcept : id_(rhs.id_) { rhs.id_ = nullptr; } id& operator=(id const& rhs) = delete; id& operator=(id&& rhs) noexcept { if (this != &rhs) { id_ = rhs.id_; rhs.id_ = nullptr; } return *this; } ___itt_id* id_ = nullptr; }; /////////////////////////////////////////////////////////////////////////// struct frame_context { PIKA_EXPORT frame_context(domain const& domain, id* ident = nullptr) noexcept; PIKA_EXPORT ~frame_context(); domain const& domain_; id* ident_ = nullptr; }; struct undo_frame_context { PIKA_EXPORT undo_frame_context(frame_context& frame) noexcept; PIKA_EXPORT ~undo_frame_context(); frame_context& frame_; }; /////////////////////////////////////////////////////////////////////////// struct mark_context { PIKA_EXPORT mark_context(char const* name) noexcept; PIKA_EXPORT ~mark_context(); int itt_mark_; char const* name_ = nullptr; }; struct undo_mark_context { PIKA_EXPORT undo_mark_context(mark_context& mark) noexcept; PIKA_EXPORT ~undo_mark_context(); mark_context& mark_; }; /////////////////////////////////////////////////////////////////////////// struct string_handle { string_handle() noexcept = default; PIKA_EXPORT string_handle(char const* s) noexcept; string_handle(___itt_string_handle* h) noexcept : handle_(h) { } string_handle(string_handle const&) = default; string_handle(string_handle&& rhs) : handle_(rhs.handle_) { rhs.handle_ = nullptr; } string_handle& operator=(string_handle const&) = default; string_handle& operator=(string_handle&& rhs) noexcept { if (this != &rhs) { handle_ = rhs.handle_; rhs.handle_ = nullptr; } return *this; } string_handle& operator=(___itt_string_handle* h) noexcept { handle_ = h; return *this; } explicit constexpr operator bool() const noexcept { return handle_ != nullptr; } ___itt_string_handle* handle_ = nullptr; }; /////////////////////////////////////////////////////////////////////////// struct task { PIKA_EXPORT task(domain const&, string_handle const&, std::uint64_t metadata) noexcept; PIKA_EXPORT task(domain const&, string_handle const&) noexcept; PIKA_EXPORT ~task(); PIKA_EXPORT void add_metadata(string_handle const& name, std::uint64_t val) noexcept; PIKA_EXPORT void add_metadata(string_handle const& name, double val) noexcept; PIKA_EXPORT void add_metadata(string_handle const& name, char const* val) noexcept; PIKA_EXPORT void add_metadata(string_handle const& name, void const* val) noexcept; template <typename T> void add_metadata(string_handle const& name, T const& val) noexcept { add_metadata(name, static_cast<void const*>(&val)); } domain const& domain_; ___itt_id* id_ = nullptr; string_handle sh_; }; /////////////////////////////////////////////////////////////////////////// struct heap_function { PIKA_EXPORT heap_function(char const* name, char const* domain) noexcept; __itt_heap_function heap_function_ = nullptr; }; struct heap_internal_access { PIKA_EXPORT heap_internal_access() noexcept; PIKA_EXPORT ~heap_internal_access(); }; struct heap_allocate { template <typename T> heap_allocate(heap_function& heap_function, T**& addr, std::size_t size, int init) noexcept : heap_function_(heap_function) , addr_(reinterpret_cast<void**&>(addr)) , size_(size) , init_(init) { if (use_ittnotify_api) { PIKA_ITT_HEAP_ALLOCATE_BEGIN(heap_function_.heap_function_, size_, init_); } } ~heap_allocate() { if (use_ittnotify_api) { PIKA_ITT_HEAP_ALLOCATE_END(heap_function_.heap_function_, addr_, size_, init_); } } private: heap_function& heap_function_; void**& addr_; std::size_t size_; int init_; }; struct heap_free { PIKA_EXPORT heap_free(heap_function& heap_function, void* addr) noexcept; PIKA_EXPORT ~heap_free(); private: heap_function& heap_function_; void* addr_; }; /////////////////////////////////////////////////////////////////////////// struct counter { PIKA_EXPORT counter(char const* name, char const* domain) noexcept; PIKA_EXPORT counter(char const* name, char const* domain, int type) noexcept; PIKA_EXPORT ~counter(); template <typename T> void set_value(T const& value) noexcept { if (use_ittnotify_api && id_) { PIKA_ITT_COUNTER_SET_VALUE( id_, const_cast<void*>(static_cast<const void*>(&value))); } } counter(counter const& rhs) = delete; counter(counter&& rhs) noexcept : id_(rhs.id_) { rhs.id_ = nullptr; } counter& operator=(counter const& rhs) = delete; counter& operator=(counter&& rhs) noexcept { if (this != &rhs) { id_ = rhs.id_; rhs.id_ = nullptr; } return *this; } private: ___itt_counter* id_ = nullptr; }; /////////////////////////////////////////////////////////////////////////// struct event { event(char const* name) noexcept : event_(itt_event_create(name, (int) strnlen(name, 256))) { } void start() const noexcept { itt_event_start(event_); } void end() const noexcept { itt_event_end(event_); } private: int event_ = 0; }; struct mark_event { mark_event(event const& e) noexcept : e_(e) { e_.start(); } ~mark_event() { e_.end(); } private: event e_; }; inline void event_tick(event const& e) noexcept { e.start(); } }}} // namespace pika::util::itt #else inline constexpr void itt_sync_create(void*, const char*, const char*) noexcept {} inline constexpr void itt_sync_rename(void*, const char*) noexcept {} inline constexpr void itt_sync_prepare(void*) noexcept {} inline constexpr void itt_sync_acquired(void*) noexcept {} inline constexpr void itt_sync_cancel(void*) noexcept {} inline constexpr void itt_sync_releasing(void*) noexcept {} inline constexpr void itt_sync_released(void*) noexcept {} inline constexpr void itt_sync_destroy(void*) noexcept {} inline constexpr ___itt_caller* itt_stack_create() noexcept { return nullptr; } inline constexpr void itt_stack_enter(___itt_caller*) noexcept {} inline constexpr void itt_stack_leave(___itt_caller*) noexcept {} inline constexpr void itt_stack_destroy(___itt_caller*) noexcept {} inline constexpr void itt_frame_begin(___itt_domain const*, ___itt_id*) noexcept {} inline constexpr void itt_frame_end(___itt_domain const*, ___itt_id*) noexcept {} inline constexpr int itt_mark_create(char const*) noexcept { return 0; } inline constexpr void itt_mark_off(int) noexcept {} inline constexpr void itt_mark(int, char const*) noexcept {} inline constexpr void itt_thread_set_name(char const*) noexcept {} inline constexpr void itt_thread_ignore() noexcept {} inline constexpr void itt_task_begin(___itt_domain const*, ___itt_string_handle*) noexcept {} inline constexpr void itt_task_begin( ___itt_domain const*, ___itt_id*, ___itt_string_handle*) noexcept { } inline constexpr void itt_task_end(___itt_domain const*) noexcept {} inline constexpr ___itt_domain* itt_domain_create(char const*) noexcept { return nullptr; } inline constexpr ___itt_string_handle* itt_string_handle_create(char const*) noexcept { return nullptr; } inline constexpr ___itt_id* itt_make_id(void*, unsigned long) { return nullptr; } inline constexpr void itt_id_create(___itt_domain const*, ___itt_id*) noexcept {} inline constexpr void itt_id_destroy(___itt_id*) noexcept {} inline constexpr __itt_heap_function itt_heap_function_create(const char*, const char*) noexcept { return nullptr; } inline constexpr void itt_heap_allocate_begin(__itt_heap_function, std::size_t, int) noexcept {} inline constexpr void itt_heap_allocate_end(__itt_heap_function, void**, std::size_t, int) noexcept { } inline constexpr void itt_heap_free_begin(__itt_heap_function, void*) noexcept {} inline constexpr void itt_heap_free_end(__itt_heap_function, void*) noexcept {} inline constexpr void itt_heap_reallocate_begin( __itt_heap_function, void*, std::size_t, int) noexcept { } inline constexpr void itt_heap_reallocate_end( __itt_heap_function, void*, void**, std::size_t, int) noexcept { } inline constexpr void itt_heap_internal_access_begin() noexcept {} inline constexpr void itt_heap_internal_access_end() noexcept {} inline constexpr ___itt_counter* itt_counter_create(char const*, char const*) noexcept { return nullptr; } inline constexpr ___itt_counter* itt_counter_create_typed(char const*, char const*, int) noexcept { return nullptr; } inline constexpr void itt_counter_destroy(___itt_counter*) noexcept {} inline constexpr void itt_counter_set_value(___itt_counter*, void*) noexcept {} inline constexpr int itt_event_create(char const*, int) noexcept { return 0; } inline constexpr int itt_event_start(int) noexcept { return 0; } inline constexpr int itt_event_end(int) noexcept { return 0; } inline constexpr void itt_metadata_add( ___itt_domain*, ___itt_id*, ___itt_string_handle*, std::uint64_t const&) noexcept { } inline constexpr void itt_metadata_add( ___itt_domain*, ___itt_id*, ___itt_string_handle*, double const&) noexcept { } inline constexpr void itt_metadata_add( ___itt_domain*, ___itt_id*, ___itt_string_handle*, char const*) noexcept { } inline constexpr void itt_metadata_add( ___itt_domain*, ___itt_id*, ___itt_string_handle*, void const*) noexcept { } ////////////////////////////////////////////////////////////////////////////// namespace pika::detail { struct thread_description; } // namespace pika::detail namespace pika::util::itt { struct stack_context { stack_context() = default; ~stack_context() = default; }; struct caller_context { constexpr caller_context(stack_context&) noexcept {} ~caller_context() = default; }; ////////////////////////////////////////////////////////////////////////// struct domain { PIKA_NON_COPYABLE(domain); constexpr domain(char const*) noexcept {} domain() = default; }; struct thread_domain : domain { PIKA_NON_COPYABLE(thread_domain); thread_domain() = default; }; struct id { constexpr id(domain const&, void*, unsigned long = 0) noexcept {} ~id() = default; }; /////////////////////////////////////////////////////////////////////////// struct frame_context { constexpr frame_context(domain const&, id* = nullptr) noexcept {} ~frame_context() = default; }; struct undo_frame_context { constexpr undo_frame_context(frame_context const&) noexcept {} ~undo_frame_context() = default; }; /////////////////////////////////////////////////////////////////////////// struct mark_context { constexpr mark_context(char const*) noexcept {} ~mark_context() = default; }; struct undo_mark_context { constexpr undo_mark_context(mark_context const&) noexcept {} ~undo_mark_context() = default; }; /////////////////////////////////////////////////////////////////////////// struct string_handle { constexpr string_handle(char const* = nullptr) noexcept {} }; ////////////////////////////////////////////////////////////////////////// struct task { constexpr task(domain const&, string_handle const&, std::uint64_t) noexcept {} constexpr task(domain const&, string_handle const&) noexcept {} ~task() = default; }; /////////////////////////////////////////////////////////////////////////// struct heap_function { constexpr heap_function(char const*, char const*) noexcept {} ~heap_function() = default; }; struct heap_allocate { template <typename T> constexpr heap_allocate(heap_function& /*heap_function*/, T**, std::size_t, int) noexcept { } ~heap_allocate() = default; }; struct heap_free { constexpr heap_free(heap_function& /*heap_function*/, void*) noexcept {} ~heap_free() = default; }; struct heap_internal_access { heap_internal_access() = default; ~heap_internal_access() = default; }; struct counter { constexpr counter(char const* /*name*/, char const* /*domain*/) noexcept {} ~counter() = default; }; struct event { constexpr event(char const*) noexcept {} }; struct mark_event { constexpr mark_event(event const&) noexcept {} ~mark_event() = default; }; inline constexpr void event_tick(event const&) noexcept {} } // namespace pika::util::itt #endif // PIKA_HAVE_ITTNOTIFY
#include <cstdio> #include "parse.h" int digitValue(char c) { if (isdigit(c)) return c - '0'; else return tolower(c) - 'a' + 10; } bool parseInt(string s, int &res) { if (s.length() == 0) return false; int base = 10; if (s.size() >= 2 && s[0] == '0' && tolower(s[1]) == 'x') { base = 16; s = s.substr(2); } else if (s[0] == '0') { base = 8; s = s.substr(1); } long long num = 0; for (string::iterator it = s.begin(); it != s.end(); ++it) { num = num * base + digitValue(*it); // TODO: constant -2^31 (minimum int) fails this test res = num; if (res != num) return false; } res = num; return true; } char getEscaped(char c) { const int N = 6; const char from[N] = {'t', 'n', '0', '\'', '\"', '\\'}; const char to[N] = {'\t', '\n', '\0', '\'', '\"', '\\'}; for (int i = 0; i < N; ++i) { if (c == from[i]) { return to[i]; } } return -1; } bool parseChar(string s, int &res) { if (s.size() < 2) return false; s = s.substr(1, s.size() - 2); if (s.size() == 1) { res = s[0]; return res != '\\'; } else if (s.size() == 2) { res = getEscaped(s[1]); return s[0] == '\\' && res != -1; } else { return false; } } bool parseString(string s, vector<int> &res) { if (s.size() < 2) return false; s = s.substr(1, s.size() - 2); res = vector<int>(); bool esc = false; for (string::iterator it = s.begin(); it != s.end(); ++it) { if (esc) { esc = false; int c = getEscaped(*it); if (c == -1) return false; res.push_back(c); } else if (*it == '\\') { esc = true; } else if (*it == '\"') { return false; } else { res.push_back(*it); } } res.push_back(0); return !esc; }
// Simple test of the NavServerDll. // system includes #include <iostream> // project includes #include "NavServer.h" #include "com_abacogroup_dbmap_wms_tile_NavionicsDriver.h" // private output functions using namespace std; // ------------------------------------------------------------------------------- // MAIN FUNCTION // ------------------------------------------------------------------------------- int main(int argc, char* argv[]) { int i; cout << "\n NavServer version: " << NAVSERVER_VERSION << "\n\n"; //if ( kNSerErr_NoErr != NServ_Init( "conf.txt" ) ) if ( kNSerErr_NoErr != NServ_Init( "X:\\NAV\\conf_x.txt" ) ) //"E:\\Devel\\G7C_3D\\QtGeocore\\Sandbox\\Matteo\\Server\\exe\\conf.txt" ) ) { cout << "Error in NServ_Init\n"; return -1; } // prepare image query NGeoRect bounds; NImage image; bounds.mWest = 1112864; bounds.mSouth = 5417168; bounds.mEast = 1132864; bounds.mNorth = 5437168; image.mSize.mWidth = 512; image.mSize.mHeight = 512; image.mChannelCount = 4; image.mBuffer = (unsigned char* ) malloc (image.mSize.mWidth*image.mSize.mHeight*image.mChannelCount); if ( kNSerErr_NoErr != NServ_GetImage( bounds, &image ) ) cout << "Error in NServ_GetImage\n"; else { FILE* fd = fopen( "test.raw", "wb+"); fwrite( image.mBuffer, 1, image.mChannelCount* image.mSize.mWidth * image.mSize.mHeight, fd); fclose( fd ); } cout << "\nPress Enter to exit\n"; cin >> i; }
#include <iostream> using namespace std; int size(char a[]); int main() { char a[1000]; cin.getline(a, 1000); cout << size(a) << endl; cin.get(); return 0; } //判断是否重复并返回最小索引 int size(char a[]) { int first_index = 0; int j = 0; int temp[26]; for (int i = 'a'; i <= 'z'; i++) { int num_of_char = 0; for (int index = 0; index < 1000; index++) { if (!a[index]) break; if (a[index] == i) { if (num_of_char == 0) first_index = index; num_of_char++; } } if (num_of_char == 1) { temp[j] = first_index; j++; } } if (j == 0) return -1; int min =temp[0]; for (int i = 0; i < j; i++) { if (temp[i] < min) { min = temp[i]; } } return min; }
#include "Pointer.h" #include "hge_test.h" int Pointer::getNumb() { return numb; } void Pointer::setNumb(int numb) { this->numb = numb; } int Pointer::getCurNumb() { return numb_current; } void Pointer::setCurNumb(int numb) { numb_current = numb; } int Pointer::getGoal() { return goal_numb; } void Pointer::setGoal(int numb) { goal_numb = numb; } int Pointer::getGoalColor() { return goal_color; } void Pointer::setGoalColor(int goalcol) { goal_color = goalcol; sprite_goal->SetColor(goalcol); } void Pointer::setSpriteColor(int color) { sprite->SetColor(color); } int Pointer::getSpriteColor() { return sprite->GetColor(); } void Pointer::setColor(int color) { this->color = color; } int Pointer::getColor() { return color; } void Pointer::setMrkColor(int color) { marked_color = color; } int Pointer::getMrkColor() { return marked_color; } Position Pointer::getPosition() { return pos; } Size Pointer::getSize() { return size; } void Pointer::setPosition(Position pos) { this->pos = pos; } void Pointer::setSize(Size size) { sprite->SetTextureRect(0, 0, size.width, size.height); this->size = size; } Size Pointer::getSizeForGoal() { return size_for_goal; } void Pointer::setSizeForGoal(Size size)//размер цели { sprite_goal->SetTextureRect(0, 0, size.width, size.height); size_for_goal = size; } Position Pointer::getPosGoal() { return pos_for_goal; } void Pointer::setPosGoal(Position pos)//установить позицию цели { pos_for_goal = pos; } void Pointer::setBusy(bool isbusy)//установить персечение как занято маркером { this->isbusy = isbusy; } void Pointer::resetRoute()//сбросить пути { find_route = -1; } bool Pointer::isBusy()//пересечение занято { return isbusy; } void Pointer::update() { } void Pointer::draw()//рисование маркеров, линий и целевых маркеров { for (int k = 0; k < ptrs.size(); k++) hge->Gfx_RenderLine(pos.x, pos.y, ptrs[k].lock()->getPosition().x, ptrs[k].lock()->getPosition().y, 0xFF660022, 0.5); sprite->Render(pos.x-size.width/2, pos.y-size.height/2); sprite_goal->Render(pos_for_goal.x - size_for_goal.width / 2, pos_for_goal.y - size_for_goal.height / 2); } void Pointer::recursiveMarked(Pointer * p) { for (int i = 0; i < p->ptrs.size(); i++) { if (!p->ptrs[i].lock()->isBusy() && !p->ptrs[i].lock()->isMarked()) { p->ptrs[i].lock()->setMarked(true); recursiveMarked(p->ptrs[i].lock().get()); } } } void Pointer::recursiveAddToVect(Pointer * p, std::vector<Position>& res, int numb, int findel) //добавляем в список путей допустимые { int max = -1; int maxi = -1; for (int i = 0; i < p->ptrs.size(); i++) { if (p->ptrs[i].lock()->isMarked() && p->ptrs[i].lock()->find_route<=findel && p->ptrs[i].lock()->find_route>=0) { maxi = i; max = p->ptrs[i].lock()->find_route; if (p->ptrs[i].lock()->find_route == findel) break; } } if (max < 0) return; res.push_back(p->ptrs[maxi].lock()->pos); p->ptrs[maxi].lock()->find_route = -1; if (p->ptrs[maxi].lock()->numb != numb) recursiveAddToVect(p->ptrs[maxi].lock().get(), res, numb,findel); } void Pointer::recursiveFind(Pointer * p, int numb, int &find_r, int& findel) //ищем рекурсивно возможные пути { int isin = false; for (int i = 0; i < p->ptrs.size(); i++) { if (p->ptrs[i].lock()->isMarked() && p->ptrs[i].lock()->find_route <0 && !p->ptrs[i].lock()->isBusy()) { isin = true; p->ptrs[i].lock()->find_route = find_r; if (p->ptrs[i].lock()->numb == numb) { findel = find_r; } recursiveFind(p->ptrs[i].lock().get(), numb, find_r, findel); } } if (!isin) find_r++; } void Pointer::addToPosition(float x, float y) { pos.x += x; pos.y += y; } void Pointer::setMarkedPath() { for (int i = 0; i < ptrs.size(); i++) { if (!ptrs[i].lock()->isBusy()) { ptrs[i].lock()->setMarked(true); recursiveMarked(ptrs[i].lock().get()); } } } std::vector<Position> Pointer::findPath(int numb) { int find_r = 0; int findel = -1; recursiveFind(this, numb, find_r, findel); std::vector<Position> res; recursiveAddToVect(this, res, numb, findel); return res; } void Pointer::addPtr(std::weak_ptr<Pointer> p) { for (int i = 0; i < ptrs.size(); i++) if (ptrs[i].lock()->getNumb() == p.lock()->getNumb()) return; ptrs.push_back(p); } void Pointer::setMarked(bool mark) { if (mark) setSpriteColor(marked_color); else setSpriteColor(color); ismarked = mark; } bool Pointer::isMarked() { return ismarked; }
#pragma once #ifndef MAIN_SCREEN_H #define MAIN_SCREEN_h #include "Screen.h" #include "Utils.h" #include "Texture.h" class MainScreen: public Screen { private: Texture *menu[Menu::TOTAL_MENU]; Menu actualOption{Menu::NEW_GAME}; Menu previousOption{Menu::NEW_GAME }; TTF_Font* font; SDL_Color red; SDL_Color selectedColor; public: void updateMenu(SDL_Renderer*); void start(SDL_Renderer*) override; void handleEvents(float&) override; void update(float&) override; void render(SDL_Renderer*) override; void close() override; }; #endif
// Fill out your copyright notice in the Description page of Project Settings. #include "Battipaglia.h" #include "ShipAIController.h" #include "BattipagliaPawn.h" AShipAIController::AShipAIController(const FObjectInitializer & OI) : Super(OI) { PrimaryActorTick.bCanEverTick = true; } void AShipAIController::Possess(APawn* PossessedPawn) { pawn = dynamic_cast<ABattipagliaPawn *>(PossessedPawn); pawn->setTrajectoryTrue(); } void AShipAIController::UnPossess() { } void AShipAIController::Tick(float DeltaTime) { if (pawn == nullptr) { return; } pawn->FireShot(FVector::ForwardVector); }
#pragma once #include "Sprite.hpp" #include <SFML/Graphics.hpp> #include <string> #include <map> #include <set> enum class WallFlags : int { COLLIDE = 0x01, DOOR = 0x02, SECRET = 0x04, }; struct Wall { union { unsigned value; struct { unsigned north : 6; unsigned east : 6; unsigned south : 6; unsigned west : 6; unsigned flags : 8; }; }; Wall() : value(0) {}; Wall(unsigned v) : value(v) {}; }; class Player; class Map { public: Map(const std::string &filename, Player *player); ~Map(); void Tick(float dt); Wall Get(int x, int y) const; Wall Get(int p) const; void Set(int x, int y, Wall value); void Set(int p, Wall value); bool IsWall(int x, int y) const; bool IsWall(int p) const; bool IsDoor(int x, int y) const; bool IsDoor(int p) const; void OpenDoor(int x, int y); void OpenDoor(int p); bool IsOpen(int x, int y) const; bool IsOpen(int p) const; bool IsMoving(int x, int y) const; bool IsMoving(int p) const; bool IsMoving(int x, int y, float &amount) const; bool IsMoving(int p, float &amount) const; bool GetCollide(int x, int y) const; bool GetCollide(int p) const; void SetCollide(int x, int y); void SetCollide(int p); int GetWidth() const; int GetHeight() const; int GetTexWidth() const; int GetTexHeight() const; const sf::Color &GetFloorColor() const; const sf::Color &GetCeilingColor() const; sf::Image *GetWallImage() const; void AddSprite(Sprite *spr); const std::vector<Sprite *> &GetSprites() const; void SortSprites(const sf::Vector2f &pos); void Save(); void Save(const std::string &filename); void Load(const std::string &filename); void Reload(); private: int *m_Array; int m_Width; int m_Height; std::string m_FileName; std::string m_RegionName; std::string m_MapName; std::string m_Texture; int m_TexWidth; int m_TexHeight; sf::Color m_FloorColor; sf::Color m_CeilingColor; Player *m_Player; std::vector<Sprite *> m_Sprites; // unsaved values std::map<int, float> m_MovingDoors; std::set<int> m_OpenDoors; };
#include <iostream> #include <cmath> #include <climits> using namespace std; int main() { static int len1 = 0; cin >> len1; int arr1[len1]; for (int i = 0; i < len1; ++i) { cin >> arr1[i]; } static int minvalue = INT_MAX; if (len1 == 1) { minvalue = 0; } else if (len1 > 0) { static int min = 0; int arrdiferences[len1][len1]; for (int j = 0; j < len1; ++j) { for (int i = 0; i < len1; ++i) { min = abs(arr1[j] - arr1[i]); if (min == 0) { arrdiferences[j][i] = INT_MAX; } else { arrdiferences[j][i] = min; } } } for (int k = 0; k < len1; ++k) { for (int i = 0; i < len1; ++i) { if (arrdiferences[k][i] <= minvalue) { minvalue = arrdiferences[k][i]; } } } } cout << minvalue; return 0; }
#pragma once #include <queue> #include <mutex> #include <GLFW/glfw3.h> #include <glad/glad.h> enum class EventType { Key, MouseMove, MouseButton, WindowClose, WindowResize }; struct Event { EventType category; union { struct Key { int keycode, scancode, action, mods; } Key; struct MouseMove { double x, y; } Mouse; struct MouseButton { int button, action, mods; } MouseButton; struct WindowResize { int width, height; } WindowResize; struct {}; } data; }; class Window { GLFWmonitor* monitor; const GLFWvidmode* mode; GLFWwindow* win = nullptr; std::queue<Event> eventQueue; // std::mutex m; no need since its all done in glfwPollEvents() not in a seperate thread. static void onKeyEvent(GLFWwindow* win, int key, int scancode, int action, int mods) { Event e; e.category = EventType::Key; e.data.Key = { key, scancode, action, mods }; ((Window*)glfwGetWindowUserPointer(win))->eventQueue.push(e); } static void onMouseMove(GLFWwindow* win, double xpos, double ypos) { Event e; e.category = EventType::MouseMove; e.data.Mouse = { xpos, ypos }; ((Window*)glfwGetWindowUserPointer(win))->eventQueue.push(e); } static void onMouseButton(GLFWwindow* win, int button, int action, int mods) { Event e; e.category = EventType::MouseButton; e.data.MouseButton = { button, action, mods }; ((Window*)glfwGetWindowUserPointer(win))->eventQueue.push(e); } static void onResize(GLFWwindow* win, int width, int height) { Event e; e.category = EventType::WindowResize; e.data.WindowResize = { width, height }; ((Window*)glfwGetWindowUserPointer(win))->eventQueue.push(e); } static void onClose(GLFWwindow* win) { Event e = { EventType::WindowClose }; ((Window*)glfwGetWindowUserPointer(win))->eventQueue.push(e); glfwSetWindowShouldClose(win, false); // clear the close bit } public: void create(const char * title) { if (win != nullptr) this->~Window(); // Hints: glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create Window: monitor = glfwGetPrimaryMonitor(); mode = glfwGetVideoMode(monitor); win = glfwCreateWindow(mode->width / 2, mode->height / 2, title, nullptr, nullptr); glfwSetWindowPos(win, (mode->width) / 4, (mode->height) / 4); glfwSetWindowAspectRatio(win, mode->width / 2, mode->height / 2); // locks the aspect ratio glfwSetCursorPos(win, mode->width / 2.0, mode->height / 2.0); glfwMakeContextCurrent(win); glfwSwapInterval(1); gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); glfwSetInputMode(win, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); // Apply Event Hooks: glfwSetWindowUserPointer(win, (void*)this); glfwSetKeyCallback(win, onKeyEvent); glfwSetCursorPosCallback(win, onMouseMove); glfwSetMouseButtonCallback(win, onMouseButton); glfwSetWindowSizeCallback(win, onResize); glfwSetWindowCloseCallback(win, onClose); } ~Window() { glfwDestroyWindow(win); } bool hasEvents() const { return eventQueue.size() != 0; } bool isOpen() const { return !glfwWindowShouldClose(win); } void close() { glfwSetWindowShouldClose(win, true); } Event&& getEvent() { Event e = eventQueue.front(); eventQueue.pop(); return std::move(e); } void swapBuffers() const { glfwSwapBuffers(win); } int isKeyDown(const int& key) { return glfwGetKey(win, key); } glm::dvec2 getMousePos() const { glm::dvec2 ret; glfwGetCursorPos(win, &ret.x, &ret.y); return ret; } glm::ivec2 getWindowSize() const { glm::ivec2 ret; glfwGetWindowSize(win, &ret.x, &ret.y); return ret; } void setWindowSize(const glm::ivec2& res) { glfwSetWindowSize(win, res.x, res.y); glfwSetWindowAspectRatio(win, res.x, res.y); glfwSetWindowPos(win, (mode->width) / 2 - res.x / 2, (mode->height) / 2 - res.y / 2); glfwSetCursorPos(win, mode->width / 2.0, mode->height / 2.0); } void setMousePos(const glm::ivec2& pos) { glfwSetCursorPos(win, pos.x, pos.y); } void setCursorMode(const int& mode) { glfwSetInputMode(win, GLFW_CURSOR, mode); } };
#include "mVector.h" vector<int> buildVector(string in) { auto values = split(in.substr(1, in.length() - 2), ','); vector<int> vec; for (string s : values) { vec.push_back(parseInt(s)); } return vec; } void printVector(vector<int> vec) { cout << "("; if(vec.size()==0){ return ; } cout << vec[0]; for (int i = 1; i < vec.size(); i++) { cout << "," << vec[i]; } cout << ")" << endl; } void printVector(vector<bool> vec) { cout << "("; if(vec.size()==0){ return ; } cout << vec[0]; for (int i = 1; i < vec.size(); i++) { cout << "," << vec[i]; } cout << ")" << endl; }
/****************************************************************************** * * * Copyright 2018 Jan Henrik Weinstock * * * * 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 "vcml/models/arm/pl011uart.h" namespace vcml { namespace arm { SC_HAS_PROCESS(pl011uart); void pl011uart::poll() { if (!is_enabled() || !is_rx_enabled()) { next_trigger(m_enable); return; } u8 val; if (beread(val)) { if (m_fifo.size() < m_fifo_size) m_fifo.push((u16)val); update(); } sc_time cycle = clock_cycle(); sc_time quantum = tlm_global_quantum::instance().get(); next_trigger(max(cycle, quantum)); } void pl011uart::update() { // update flags FR &= ~(FR_RXFE | FR_RXFF | FR_TXFF); FR |= FR_TXFE; // tx FIFO is always empty if (m_fifo.empty()) FR |= FR_RXFE; if (m_fifo.size() >= m_fifo_size) FR |= FR_RXFF; // update interrupts if (m_fifo.empty()) RIS &= ~RIS_RX; else RIS |= RIS_RX; MIS = RIS & IMSC; if (MIS != 0 && !IRQ.read()) log_debug("raising interrupt"); if (MIS == 0 && IRQ.read()) log_debug("clearing interrupt"); IRQ.write(MIS != 0); } u16 pl011uart::read_DR() { u16 val = 0; if (!m_fifo.empty()) { val = m_fifo.front(); m_fifo.pop(); } DR = val; RSR = (val >> RSR_O) & RSR_M; update(); return val; } u16 pl011uart::write_DR(u16 val) { if (!is_tx_enabled()) return DR; // Upper 8 bits of DR are used for encoding transmission errors, but // since those are not simulated, we just set them to zero. u8 val8 = val & 0xFF; bewrite(val8); RIS |= RIS_TX; update(); return val8; } u8 pl011uart::write_RSR(u8 val) { // A write to this register clears the framing, parity, break, // and overrun errors. The data value is not important. return 0; } u16 pl011uart::write_IBRD(u16 val) { return val & LCR_IBRD_M; } u16 pl011uart::write_FBRD(u16 val) { return val & LCR_FBRD_M; } u8 pl011uart::write_LCR(u8 val) { if ((val & LCR_FEN) && !(LCR & LCR_FEN)) log_debug("FIFO enabled"); if (!(val & LCR_FEN) && (LCR & LCR_FEN)) log_debug("FIFO disabled"); m_fifo_size = (val & LCR_FEN) ? FIFOSIZE : 1; return val & LCR_H_M; } u16 pl011uart::write_CR(u16 val) { if (!is_enabled() && (val & CR_UARTEN)) log_debug("device enabled"); if (is_enabled() && !(val & CR_UARTEN)) log_debug("device disabled"); if (!is_tx_enabled() && (val & CR_TXE)) log_debug("transmitter enabled"); if (is_tx_enabled() && !(val & CR_TXE)) log_debug("transmitter disabled"); if (!is_rx_enabled() && (val & CR_RXE)) log_debug("receiver enabled"); if (is_rx_enabled() && !(val & CR_RXE)) log_debug("receiver disabled"); m_enable.notify(SC_ZERO_TIME); return val; } u16 pl011uart::write_IFLS(u16 val) { return val & 0x3F; // TODO implement interrupt FIFO level select } u16 pl011uart::write_IMSC(u16 val) { IMSC = val & RIS_M; update(); return IMSC; } u16 pl011uart::write_ICR(u16 val) { RIS &= ~(val & RIS_M); update(); return 0; } pl011uart::pl011uart(const sc_module_name& nm): peripheral(nm), m_fifo_size(), m_fifo(), m_enable("enable"), DR ("DR", 0x000, 0x0), RSR ("RSR", 0x004, 0x0), FR ("FR", 0x018, FR_TXFE | FR_RXFE), ILPR ("IPLR", 0x020, 0x0), IBRD ("IBRD", 0x024, 0x0), FBRD ("FBRD", 0x028, 0x0), LCR ("LCR", 0x02C, 0x0), CR ("CR", 0x030, CR_TXE | CR_RXE), IFLS ("IFLS", 0x034, 0x0), IMSC ("IMSC", 0x038, 0x0), RIS ("RIS", 0x03C, 0x0), MIS ("MIS", 0x040, 0x0), ICR ("ICR", 0x044, 0x0), DMAC ("DMACR", 0x048, 0x0), PID ("PID", 0xFE0, 0x00000000), CID ("CID", 0xFF0, 0x00000000), IN("IN"), IRQ("IRQ") { DR.sync_always(); DR.allow_read_write(); DR.read = &pl011uart::read_DR; DR.write = &pl011uart::write_DR; RSR.sync_always(); RSR.allow_read_write(); RSR.write = &pl011uart::write_RSR; FR.sync_always(); FR.allow_read(); ILPR.sync_never(); ILPR.allow_read_write(); // not implemented IBRD.sync_always(); IBRD.allow_read_write(); IBRD.write = &pl011uart::write_IBRD; FBRD.sync_always(); FBRD.allow_read_write(); FBRD.write = &pl011uart::write_FBRD; LCR.sync_always(); LCR.allow_read_write(); LCR.write = &pl011uart::write_LCR; CR.sync_always(); CR.allow_read_write(); CR.write = &pl011uart::write_CR; IFLS.sync_always(); IFLS.allow_read_write(); IFLS.write = &pl011uart::write_IFLS; IMSC.sync_always(); IMSC.allow_read_write(); IMSC.write = &pl011uart::write_IMSC; RIS.sync_always(); RIS.allow_read(); MIS.sync_always(); MIS.allow_read(); ICR.sync_always(); ICR.allow_write(); ICR.write = &pl011uart::write_ICR; DMAC.sync_never(); DMAC.allow_read_write(); // not implemented PID.sync_never(); PID.allow_read(); CID.sync_never(); CID.allow_read(); SC_METHOD(poll); reset(); } pl011uart::~pl011uart() { // nothing to do } void pl011uart::reset() { peripheral::reset(); for (unsigned int i = 0; i < PID.count(); i++) PID[i] = (AMBA_PID >> (i * 8)) & 0xFF; for (unsigned int i = 0; i < CID.count(); i++) CID[i] = (AMBA_CID >> (i * 8)) & 0xFF; while (!m_fifo.empty()) m_fifo.pop(); IRQ = false; } }}
#ifndef TABULEIRO_H #define TABULEIRO_H #include "triangulo.h" #include "vertice.h" #include "triangulo.h" #include "plano.h" class Plano; class Tabuleiro { private: Plano *base, *parede_norte, *parede_sul;//, *parede_leste, *parede_oeste; Vertice *pos, vertices_elipse_oeste[15], vertices_elipse_leste[15]; double tam_base, tam_altura, tam_altura_paredes, centro_x_leste, centro_y_leste, centro_x_oeste, centro_y_oeste, raio_x, raio_y; int num_segmentos; void monta_elipses(); void monta_Tabuleiro(); /// funcao para setar os planos do tabuleiro a partir das informacoes do construtor public: /// CONSTRUTOR & DESTRUTOR Tabuleiro(Vertice *posicao_inicial, double p_tam_base, double p_tam_altura, double p_tam_altura_paredes); virtual ~Tabuleiro(); /// GETTERS inline Plano *pega_base() { return base; } inline Plano *pega_parede_norte() { return parede_norte; } // inline Plano *pega_parede_leste() { return parede_leste; } inline Plano *pega_parede_sul() { return parede_sul; } // inline Plano *pega_parede_oeste() { return parede_oeste; } inline Vertice *pega_posicao_inicial() { return pos; } inline double pega_tam_base() { return tam_base; } inline double pega_tam_altura() { return tam_altura; } inline double pega_tam_altura_paredes() { return tam_altura_paredes; } inline Vertice *pega_Vertices_elipse_oeste() { return vertices_elipse_oeste; } inline Vertice *pega_Vertices_elipse_leste() { return vertices_elipse_leste; } inline int pega_Num_segmentos() const { return num_segmentos; } inline double pega_Centro_x_leste() const { return centro_x_leste; } inline double pega_Centro_y_leste() const { return centro_y_leste; } inline double pega_Centro_x_oeste() const { return centro_x_oeste; } inline double pega_Centro_y_oeste() const { return centro_y_oeste; } inline double pega_Raio_x() const { return raio_x; } inline double pega_Raio_y() const { return raio_y; } /// SETTERS inline void define_base(Plano *nova_base) { base = nova_base; }; inline void define_parede_norte(Plano *nova_parede_norte) { parede_norte = nova_parede_norte; } // inline void define_parede_leste(Plano *nova_parede_leste) { parede_leste = nova_parede_leste; } inline void define_parede_sul(Plano *nova_parede_sul) { parede_sul = nova_parede_sul; } // inline void define_parede_oeste(Plano *nova_parede_oeste) { parede_oeste = nova_parede_oeste; } inline void define_posicao(Vertice *nova_posicao) { pos = nova_posicao; } inline void define_tam_base(double novo_tam_base) { tam_base = novo_tam_base; } inline void define_tam_altura(double novo_tam_altura) { tam_altura = novo_tam_altura; } inline void define_tam_altura_paredes(double novo_tam_altura_paredes) { tam_altura_paredes = novo_tam_altura_paredes; } }; #endif // TABULEIRO_H
#ifndef PROPERTYTABLES_H #define PROPERTYTABLES_H #include <vector> struct PropertyTables { std::vector<std::vector<double>> lambda; std::vector<std::vector<double>> density; std::vector<std::vector<double>> capacity; }; void getTable(std::vector<std::vector<double>> &table, const std::string &tableName); PropertyTables getTables(const std::string &fileName); double getValue(const std::vector<std::vector<double>> &table, const double &T); #endif
#ifndef BINARY_DECRYPT_INCLUDED #define BINARY_DECRYPT_INCLUDED #include "aes256.h" extern "C" { extern CryptoPP::byte *Executable; extern unsigned ExecLen; } class BinaryDecrypt { Cipher::AES256_decryptor Dec; public: BinaryDecrypt(const std::string &Psw): Dec(Psw) {} void retrieveBinary() { Dec.decrypt(Executable, ExecLen); } }; #endif
#include <iostream> #include <vpp/vpp.hh> using namespace vpp; template <typename V, typename U> bool equals(image2d<V>& v, image2d<U>& u) { int eq = true; pixel_wise(v, u) | [&] (V& a, U& b) { if (a != b) eq = false; }; return eq; } template <typename V> void print(image2d<V>& v) { for (int r = 0; r < v.nrows(); r++) { for (int c = 0; c < v.ncols(); c++) std::cout << v(r, c) << " "; std::cout << std::endl; } } int main() { image2d<int> img(4,4); vint2 b(2,2); int i = 0; // block_wise(b, img, img, img.domain())//(_col_backward) // | [&] (image2d<int> I, image2d<int> J, box2d d) // { // assert(I.nrows() == b[0]); // assert(I.ncols() == b[1]); // fill(I, i); // i++; // }; // pixel_wise(img.domain(), img) | [&] (vint2 c, int& v) // { // c[0] /= b[0]; // c[1] /= b[1]; // int idx = (b[1] * c[0] + c[1]); // assert(idx == v); // }; auto test_dependency = [&] (int* ref_data, auto dep, int dim) { image2d<int> ref(img.domain(), _data = (int*)ref_data, _pitch = 4 * sizeof(int)); int cols[2] = {1,1}; block_wise(b, img, img, img.domain())(dep) | [&] (image2d<int> I, image2d<int> J, box2d d) { int& cpt = cols[d.p1()[dim] / 2]; fill(I, cpt); cpt++; }; std::cout << "ref: " << std::endl; print(ref); std::cout << "img: " << std::endl; print(img); assert(equals(ref, img)); }; { int ref_data[] = { 1,1,1,1, 1,1,1,1, 2,2,2,2, 2,2,2,2, }; test_dependency(ref_data, _col_forward, 1); } fill(img, 9); { int ref_data[] = { 2,2,2,2, 2,2,2,2, 1,1,1,1, 1,1,1,1, }; test_dependency(ref_data, _col_backward, 1); } fill(img, 9); { int ref_data[] = { 1,1,2,2, 1,1,2,2, 1,1,2,2, 1,1,2,2, }; test_dependency(ref_data, _row_forward, 0); } fill(img, 9); { int ref_data[] = { 2,2,1,1, 2,2,1,1, 2,2,1,1, 2,2,1,1, }; test_dependency(ref_data, _row_backward, 0); } // image2d<int> ref(img.domain(), _data = (int*)ref_data, _pitch = 4 * sizeof(int)); // int cols[2] = {1,1}; // block_wise(b, img, img, img.domain())(_col_forward) // | [&] (image2d<int> I, image2d<int> J, box2d d) // { // int& cpt = cols[d.p1()[1] / 2]; // fill(I, cpt); // cpt++; // }; // std::cout << ref(0,0) << " " << img(0,0) << std::endl; // assert(equals(ref, img)); // } // ref // { // image2d<int> img(4,4); // } }
// ************************************** // File: KLISTVIEW.h // Copyright: Copyright(C) 2013-2017 Wuhan KOTEI Informatics Co., Ltd. All rights reserved. // Website: http://www.nuiengine.com // Description: This code is part of NUI Engine (NUI Graphics Lib) // Comments: // Rev: 2 // Created: 2017/4/12 // Last edit: 2017/4/28 // Author: Chen Zhi // E-mail: cz_666@qq.com // License: APACHE V2.0 (see license file) // *************************************** #ifndef KLISTVIEW_DEFINED #define KLISTVIEW_DEFINED #include "KButtonView.h" #include "KViewGroup.h" #include "AnimationThread.h" #include "KMoveableView.h" #include "boost/thread/recursive_mutex.hpp" #include "KShapeDrawable.h" // 记录鼠标轨迹 struct TrackPoint { kn_int y; // Y坐标 kn_dword ticks; // 时刻 TrackPoint(int); TrackPoint(); }; class NUI_API KListView : public KViewGroup { public: enum { LS_NORMAL, LS_SCROLLING, // 滑动中 LS_ITEMCLICK // 点击item项 }; KListView() ; virtual ~KListView(); virtual void shared_ptr_inited(); // 添加自定义的View void UI_addItemView(KView_PTR pItemView); // 删掉所有Item void UI_clearAllItems(); // 获取ItemView KView_PTR getItemView(kn_int index); // 获取列表总数 kn_int getItemCount(); //void setViewport(RERect rect); // 使位置移动落在可视范围 int adjustInViewport(int iPosY); void bindData(vector<kn_string>& vData); // 带动画的滑动位移 void scrollByOffsetAnimation(int y); // 滑动位移 void scrollByOffset(int y); void scrollByPos(int y); // 根据ItemGroup的位置,计算滚动条的位置 kn_int calcScrollerPos(int iItemsTop); void onKeydown(KMessageKey* pMsg); virtual void onDownDirect(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg); virtual void onMoveDirect(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg); virtual void onUpDirect(kn_int iScreenX, kn_int iScreenY, KMessageMouse* pMsg); virtual void onWheelDirect(KMessageMouseWheel* pMsg); virtual kn_bool Create(kn_int iX, kn_int iY, kn_int iWidth, kn_int iHeight); // 是否显示FastScroll void showFastScroller(kn_bool bShow); // 设置分隔符 void setDivider(KDrawable_PTR pDrawable); // 设置滚动条 void setScroller(); // 动画是否正在运行.此时不建议更新listview kn_bool isAnimationRunning(); // 设置 滚动条移动到底部 void UI_SetToBottom(); // 是否可以拖动 void enableDrag(kn_bool b); protected: void createListView(); KTextView_PTR createListItem(RERect& rect, kn_string& strItem); void dragLastPhyHandler(); // 设置快速滚动条 void setFastScroller(); void onFastScrollerDown(kn_int x, kn_int y, KMessageMouse* pMsg); void onFastScrollerMove(kn_int x, kn_int y, KMessageMouse* pMsg); void onFastScrollerUp(kn_int x, kn_int y, KMessageMouse* pMsg); void onItemClick(KView_PTR pView); void updateFastScrollerPos(kn_float y); // 判断滑动状态 , 滑动/ 点击item项 kn_int judgeScrollState(); // 恢复item group 的初始设置 void resetItemGroup(); protected: vector<kn_string> m_vec_data; CAnimationThread m_ani_thread; // 上次按下的坐标 REPoint m_last_press_point; REPoint m_first_press_point; // 按下时listview的top kn_int m_i_press_top; // listview可以看到的范围, 相对于上级的坐标,同m_rect的坐标 RERect m_rect_viewport; // 操作的坐标点, 只记录Y轴 vector<TrackPoint> m_vec_touchpoints; // 滚动条,仅在滑动时显示 KView_PTR m_p_scroller; // 滚动条 drawable KShapeDrawable_PTR m_drawable_slider; // 快速滚动条 KMoveableView_PTR m_p_fast_scroller; kn_bool m_b_show_scroller; // 列表项的集合,可以超出listview的范围 KViewGroup_PTR m_p_item_groupview; // 滑动状态, 区分 listview 滑动/ Item点击 kn_int m_i_scroll_state; // 分隔符 KDrawable_PTR m_drawable_divider; // 分隔符的高 kn_int m_i_divider_height; // item的高 kn_int m_i_item_height; // 项的总数 kn_int m_i_item_count; // 是否可拖动 kn_bool m_b_enable_drag; }; typedef boost::shared_ptr<KListView> KListView_PTR; #endif // KLISTVIEW_DEFINED
#ifndef _RaseProcess_H_ #define _RaseProcess_H_ #include "IProcess.h" class RaseProcess :public IProcess { public: RaseProcess(); virtual ~RaseProcess(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) ; virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ; }; #endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/////////////*/ int decimalPrecision = 2; // decimal places for all values shown in LED Display & Serial Monitor int ThermistorPin = A2; // The analog input pin for measuring temperature float voltageDividerR1 = 10000; // Resistor value in R1 for voltage devider method float BValue = 3470; // The B Value of the thermistor for the temperature measuring range float RT1 = 10000; // Thermistor resistor rating at based temperature (25 degree celcius) float T1 = 298.15; /* Base temperature T1 in Kelvin (default should be at 25 degree)*/ float R2 ; /* Resistance of Thermistor (in ohm) at Measuring Temperature*/ float T2 ; /* Measurement temperature T2 in Kelvin */ float a ; /* Use for calculation in Temperature*/ float b ; /* Use for calculation in Temperature*/ float c ; /* Use for calculation in Temperature*/ float d ; /* Use for calculation in Temperature*/ float e = 2.718281828 ; /* the value of e use for calculation in Temperature*/ float tempSampleRead = 0; /* to read the value of a sample including currentOffset1 value*/ float tempLastSample = 0; /* to count time for each sample. Technically 1 milli second 1 sample is taken */ float tempSampleSum = 0; /* accumulation of sample readings */ float tempSampleCount = 0; /* to count number of sample. */ float tempMean ; /* to calculate the average value from all samples, in analog values*/ float readTemp(){ /* 1- Temperature Measurement */ float temp; if(millis() >= tempLastSample + 1) /* every 1 milli second taking 1 reading */ { tempSampleRead = analogRead(ThermistorPin); /* read analog value from sensor */ tempSampleSum = tempSampleSum+tempSampleRead; /* add all analog value for averaging later*/ tempSampleCount = tempSampleCount+1; /* keep counting the sample quantity*/ tempLastSample = millis(); /* reset the time in order to repeat the loop again*/ } if(tempSampleCount == 1000) /* after 1000 sample readings taken*/ { tempMean = tempSampleSum / tempSampleCount; /* find the average analog value from those data*/ R2 = (voltageDividerR1*tempMean)/(1023-tempMean); /* convert the average analog value to resistance value*/ a = 1/T1; /* use for calculation */ b = log10(RT1/R2); /* use for calculation */ c = b / log10(e); /* use for calculation */ d = c / BValue ; /* use for calculation */ T2 = 1 / (a- d); temp = T2 - 273.15; /* the measured temperature value based on calculation (in Kelvin) */ tempSampleSum = 0; /* reset all the total analog value back to 0 for the next count */ tempSampleCount = 0; return temp;/* reset the total number of samples taken back to 0 for the next count*/ } return -1; } //************************* User Defined Variables ********************************************************// //################################################################################## //----------- Do not Replace R1 with a resistor lower than 300 ohms ------------ //################################################################################## int R1 = 1000; int Ra = 25; //Resistance of powering Pins int ECPin = A0; int ECGround = A1; int ECPower = A4; float PPMconversion = 0.7; //*************Compensating for temperature ************************************// //The value below will change depending on what chemical solution we are measuring //0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring //********************** Cell Constant For Ec Measurements *********************// //Mine was around 2.9 with plugs being a standard size they should all be around the same //But If you get bad readings you can use the calibration script and fluid to get a better estimate for K float K = 1.16; #define ONE_WIRE_BUS 10 // Data wire For Temp Probe is plugged into pin 10 on the Arduino float Temperature = 10; float EC = 0; float EC25 = 0; int ppm = 0; float raw = 0; float Vin = 5; float Vdrop = 0; float Rc = 0; float buffer = 0; //*********************************Setup - runs Once and sets pins etc ******************************************************// void setup() { Serial.begin(9600); //pinMode(TempProbeNegative , OUTPUT ); //seting ground pin as output for tmp probe //digitalWrite(TempProbeNegative , LOW );//Seting it to ground so it can sink current //pinMode(TempProbePossitive , OUTPUT );//ditto but for positive //digitalWrite(TempProbePossitive , HIGH ); pinMode(ECPin, INPUT); pinMode(ECPower, OUTPUT); //Setting pin for sourcing current pinMode(ECGround, OUTPUT); //setting pin for sinking current digitalWrite(ECGround, LOW); //We can leave the ground connected permanantly delay(100);// gives sensor time to settle //sensors.begin(); delay(100); //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********// // Consule Read-Me for Why, or just accept it as true R1 = (R1 + Ra); // Taking into acount Powering Pin Resitance Serial.println("ElCheapo Arduino EC-PPM measurments"); Serial.println("By: Michael Ratcliffe Mike@MichaelRatcliffe.com"); Serial.println("Free software: you can redistribute it and/or modify it under GNU "); Serial.println(""); Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed"); Serial.println(""); Serial.println("Measurments at 5's Second intervals [Dont read Ec morre than once every 5 seconds]:"); }; //******************************************* End of Setup **********************************************************************// //************************************* Main Loop - Runs Forever ***************************************************************// //Moved Heavy Work To subroutines so you can call them from main loop without cluttering the main loop void loop() { Temperature = readTemp(); if (Temperature != -1){ GetEC(); //Calls Code to Go into GetEC() Loop [Below Main Loop] dont call this more that 1/5 hhz [once every five seconds] or you will polarise the water PrintReadings(); // Cals Print routine [below main loop] } } //************************************** End Of Main Loop **********************************************************************// //************ This Loop Is called From Main Loop************************// void GetEC() { //*********Reading Temperature Of Solution *******************// //sensors.requestTemperatures();// Send the command to get temperatures //Temperature = 20; //Temperature=sensors.getTempCByIndex(0); //Stores Value in Variable //************Estimates Resistance of Liquid ****************// digitalWrite(ECPower, HIGH); raw = analogRead(ECPin); raw = analogRead(ECPin); // This is not a mistake, First reading will be low beause if charged a capacitor digitalWrite(ECPower, LOW); //***************** Converts to EC **************************// Vdrop = (Vin * raw) / 1024.0; Rc = (Vdrop * R1) / (Vin - Vdrop); Rc = Rc - Ra; //acounting for Digital Pin Resitance EC = 1000 / (Rc * K); //*************Compensating For Temperaure********************// EC25 = EC / (1 + TemperatureCoef * (Temperature - 25.0)); ppm = (EC25) * (PPMconversion * 1000); ; } //************************** End OF EC Function ***************************// //***This Loop Is called From Main Loop- Prints to serial usefull info ***// void PrintReadings() { Serial.print("Rc: "); Serial.print(Rc); Serial.print(" EC: "); Serial.print(EC25); Serial.print(" Simens "); Serial.print(ppm); Serial.print(" ppm "); Serial.print(Temperature); Serial.println(" *C "); };
#ifndef SUBSTATE_H #define SUBSTATE_H #include "Globals.h" class SubState { public: virtual void init(sf::RenderWindow &window) = 0; virtual void update(sf::RenderWindow &window, float dt) = 0; virtual void draw(sf::RenderWindow &window) = 0; virtual void handleEvents(sf::RenderWindow &window, sf::Event &event) = 0; virtual void destroy(sf::RenderWindow &window) = 0; }; #endif
#include <bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; #define tests int t; cin >> t; while(t--) #define vll vector<ll> #define vi vector<int> #define pb push_back using namespace std; struct segTree { int size = 1; vll tree; void init(int n) { while(size < n) { size *= 2; } tree.assign(2*size, 0LL); } ll getSum(int l, int r, int x, int lx, int rx) { if(l >= rx || lx >= r) { return 0; } if(l <= lx && rx <= r) { return tree[x]; } int m = (lx+rx)/2; ll s1 = getSum(l, r, 2*x+1, lx, m); ll s2 = getSum(l, r, 2*x+2, m, rx); return s1+s2; } ll getSum(int l, int r) { return getSum(l, r, 0, 0, size); } void add(int i, int x, int lx, int rx) { if(rx-lx == 1) { tree[x] += 1; return; } int m = (lx+rx)/2; if(i < m) { add(i, 2*x+1, lx, m); } else { add(i, 2*x+2, m, rx); } tree[x] = tree[2*x+1]+tree[2*x+2]; } void add(int i) { add(i, 0, 0, size); } }; int search(vll& v, ll x) { int s = 0, e = v.size()-1; while(e >= s) { int m = s+(e-s)/2; if(v[m] == x) { return m; } else if(v[m] < x) { s = m+1; } else { e = m-1; } } return -1; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); tests { int n; cin >> n; set<ll> s; vll a(n); for(int i = 0; i < n; i++) { ll x; cin >> x; a[i] = x; s.insert(x); } vll v(s.begin(), s.end()); int ms = v.size(); segTree st; st.init(ms); ll ans = 0; for(int i = 0; i < n; i++) { int it = search(v, a[i]); ll s1 = st.getSum(0, it); ll s2 = st.getSum(it+1, ms); ans += min(s1, s2); st.add(it); } cout << ans << "\n"; } return 0; }
#pragma once #include <glfw/glfw3.h> #include <glm/glm.hpp> #include <vector> class InputHandler { public: static void update(); static void initCallbacks(GLFWwindow* window); // GET AND SET CURSOR POSITION static glm::vec2 getCursorPosition(); static void setCursorPosition(GLFWwindow* window, glm::vec2 newPosition); // GET AND SET SCROLL OFFSET static float getScrollOffset(); static void setScrollOffset(float offset); // GET ISCURSORLOCKED static bool getLockStatus(); static void setLockedCursorPosition(glm::vec2 lockedPosition); static glm::vec2 getLockedCursorPosition(); static std::vector<int> getKeysPressed(); private: static std::vector<int> keysPressed; static std::vector<int> keysReleased; static std::vector<int> keysHolding; static std::vector<int> buttonsPressed; static std::vector<int> buttonsReleased; static std::vector<int> buttonsHolding; static glm::vec2 cursorPosition; static glm::vec2 lockedCursorPosition; static float scrollOffset; static bool isCursorLocked;; void clear(); static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); static void mouse_button_callback(GLFWwindow* window, int button, int action, int mods); static void cursor_pos_callback(GLFWwindow* window, double x, double y); static void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); };
/* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ #ifndef THUNK_HH #define THUNK_HH #include <string> #include <vector> #include <functional> #include <map> #include <unordered_map> #include <limits> #include <regex> #include <chrono> #include <sys/types.h> #include <crypto++/base64.h> #include <crypto++/files.h> #include "protobufs/thunk.pb.h" #include "protobufs/gg.pb.h" #include "sandbox/sandbox.hh" #include "util/optional.hh" #include "util/path.hh" namespace gg { enum class ObjectType : char { Value = 'V', Thunk = 'T', }; struct ThunkOutput { std::string hash {}; std::string tag {}; ThunkOutput() {} ThunkOutput( const std::string & hash, const std::string & tag ) : hash( hash ), tag( tag ) {} ThunkOutput( std::string && hash, std::string && tag ) : hash( move( hash ) ), tag( move( tag ) ) {} }; namespace thunk { const std::string MAGIC_NUMBER = "##GGTHUNK##"; const std::string BEGIN_REPLACE = "__GG_BEGIN_REPLACE__"; const std::string END_REPLACE = "__GG_END_REPLACE__"; const std::string DATA_PLACEHOLDER_START = "@{GGHASH:"; const std::string DATA_PLACEHOLDER_END = "}"; const std::regex DATA_PLACEHOLDER_REGEX { R"X(@\{GGHASH:([a-zA-Z0-9_.]+)(?:#([^/]+))?\})X" }; std::string data_placeholder( const std::string & hash ); class Function { private: std::string hash_ {}; std::vector<std::string> args_; std::vector<std::string> envars_ {}; public: Function( const std::string & hash, const std::vector<std::string> & args, const std::vector<std::string> & envars ); Function( std::string && hash, std::vector<std::string> && args, std::vector<std::string> && envars ); Function( const gg::protobuf::Function & func_proto ); const std::string & hash() const { return hash_; } const std::vector<std::string> & args() const { return args_; } const std::vector<std::string> & envars() const { return envars_; } std::vector<std::string> & args() { return args_; } std::vector<std::string> & envars() { return envars_; } gg::protobuf::Function to_protobuf() const; bool operator==( const Function & other ) const; bool operator!=( const Function & other ) const { return not operator==( other ); } }; class Thunk { public: /* XXX maybe use unordered_multimap? */ typedef std::multimap<std::string, std::string> DataList; typedef DataList::value_type DataItem; private: Function function_; DataList values_; DataList thunks_; DataList executables_; std::vector<std::string> outputs_; std::chrono::milliseconds timeout_ { 0 }; bool localonly_ { false }; mutable Optional<std::string> hash_ {}; void throw_if_error() const; public: Thunk( const Function & function, const std::vector<DataItem> & data, const std::vector<DataItem> & executables, const std::vector<std::string> & outputs ); Thunk( Function && function, std::vector<DataItem> && data, std::vector<DataItem> && executables, std::vector<std::string> && outputs ); Thunk( Function && function, std::vector<DataItem> && values, std::vector<DataItem> && thunks, std::vector<DataItem> && executables, std::vector<std::string> && outputs ); Thunk( Function && function, DataList && values, DataList && thunks, DataList && executables, std::vector<std::string> && outputs ); Thunk( const gg::protobuf::Thunk & thunk_proto ); int execute() const; static std::string execution_payload( const Thunk & thunk ); static std::string execution_payload( const std::vector<Thunk> & thunks ); static gg::protobuf::RequestItem execution_request( const Thunk & thunk ); const Function & function() const { return function_; } const DataList & values() const { return values_; } const DataList & thunks() const { return thunks_; } const DataList & executables() const { return executables_; } const std::vector<std::string> & outputs() const { return outputs_; } const std::chrono::milliseconds & timeout() const { return timeout_; } void set_timeout( const std::chrono::milliseconds & timeout ); void set_localonly( bool is_localonly ) { localonly_ = is_localonly; } gg::protobuf::Thunk to_protobuf() const; bool operator==( const Thunk & other ) const; bool operator!=( const Thunk & other ) const { return not operator==( other ); } void set_hash( const std::string & hash ) const { hash_.reset( hash ); } std::string hash() const; std::string executable_hash() const; std::string output_hash( const std::string & tag ) const; bool is_localonly() const { return localonly_; } bool can_be_executed() const { return ( thunks_.size() == 0 ); } size_t infiles_size( const bool include_executables = true ) const; void update_data( const std::string & old_hash, const std::vector<ThunkOutput> & outputs ); /* Returns a list of files that can be accessed while executing this thunk. */ std::unordered_map<std::string, Permissions> get_allowed_files() const; static std::pair<const std::string, std::string> string_to_data( const std::string & str ); static bool matches_filesystem( const DataItem & item ); }; } /* namespace thunk */ } /* namespace gg */ #endif /* THUNK_HH */
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <conio.h> #include <iostream> #include "main.h" #include "main-1.h" #include "main-2.h" #define N 100 MON mmm[N]; /* массив-таблица */ int n = 0; /* количество элементов в массиве */ /**** главная функция ****/ int main(void) { setlocale(LC_ALL, "Russian"); int op; /* операция */ int num; /* номер элемента */ char eoj; /* признак конца */ /* */ for (eoj = 0; !eoj; ) { /* выводення меню */ printf("1 - Добавить элемент\n"); printf("2 - Удалить элемент\n"); printf("3 - Показать элемент по номеру\n"); printf("4 - Показать все\n"); printf("0 - Выход\n"); printf("Вводите >"); /* вибор из меню */ scanf("%d", &op); switch (op) { case 0: /* выход */ eoj = 1; break; case 1: /* добавить */ if (!ent_data(mmm + n)) n++; break; case 2: /* удалить */ if (!check_number(num = get_number())) { del_item(num); n--; } break; case 3: /* показать один */ if (!check_number(num = get_number())) show_1(mmm + num - 1); break; case 4: /* показать все */ show_all(); break; default: printf("Неправильная операция\n"); break; } /* switch */ if (op) { printf("Нажмите любую клавишу\n"); } /* if */ } /* for */ return 0; }
#include "AudioMarkupNavigator.h" #include "AudioMarkupNavigatorDialog.h" AudioMarkupNavigator::AudioMarkupNavigator() { } AudioMarkupNavigator::~AudioMarkupNavigator() { } bool AudioMarkupNavigator::requestMarkerId(int& markerId) { AudioMarkupNavigatorDialog audioNavigatorDlg; if (audioNavigatorDlg.exec() == QDialog::Accepted) { markerId = audioNavigatorDlg.markerId(); return true; } return false; }
#ifndef CPP_2020_RANDOM_FOREST_DECISION_TREE_H #define CPP_2020_RANDOM_FOREST_DECISION_TREE_H #include <iostream> #include <fstream> #include <memory> #include <string> #include <utility> #include <vector> #include <map> #include <algorithm> #include <memory> #include <cmath> #include <numeric> #include <cstdlib> #include <random> #include "data.h" double calc_info_entropy(const target_type& targets); double calc_info_gain( double s0, const target_type& left_target, const target_type& right_target ); typedef std::mt19937 random_gen_type; class TreeNode { std::vector<int> objects_m; std::vector<bool> used_features_m; int num_used_features_m = 0; dataset& ds_m; int depth_m; int max_depth_m; double node_entropy = 0.0; double entropy_threshold_m = 0.0; bool use_random_features_m; random_gen_type& random_gen_m; public: std::shared_ptr<TreeNode> left_m; std::shared_ptr<TreeNode> right_m; int ftr_to_split_m{}; TreeNode( dataset& ds, std::vector<int> objects, std::vector<bool> used_features, double entropy_threshold, int depth, int max_depth, random_gen_type& random_gen, bool use_random_features=false ); TreeNode( dataset& ds, double entropy_threshold, int depth, int max_depth, random_gen_type& random_gen, bool use_random_features=false ); bool check_stop_criteria(); std::vector<int> get_leaf_objects(int ftr, bool get_true); target_type get_leaf_targets(std::vector<int>& leaf_objects); void add_leaf(std::shared_ptr<TreeNode>& leaf, bool is_left); std::vector<bool> generate_feature_mask(int n_features, int n_leave); void build(); int get_answer(); }; class Tree { double entropy_threshold_m = 0.0; int max_depth_m = 0.0; std::shared_ptr<TreeNode> root_m; bool use_random_features_m = false; random_gen_type random_gen_m; public: int random_state_m; Tree() = default; Tree(double entropy_threshold, int max_depth, bool use_random_features=false, int random_state=42); void fit(dataset& tr_ds); void fit( dataset& tr_ds, std::vector<int>&& objects, std::vector<bool>&& used_features ); target_type predict(feature_matrix_type& X) const; int predict(feature_type& x) const; }; #endif //CPP_2020_RANDOM_FOREST_DECISION_TREE_H
/**************************************** @_@ Cat Got Bored *_* #_# *****************************************/ #include <bits/stdc++.h> #define loop(i,s,e) for(int i = s;i<=e;i++) //including end point #define pb(a) push_back(a) #define sqr(x) ((x)*(x)) #define CIN ios_base::sync_with_stdio(0); cin.tie(0); #define ll long long #define ull unsigned long long #define SZ(a) int(a.size()) #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) #define ms(a,b) memset(a, b, sizeof(a)) #define all(v) v.begin(), v.end() #define PI acos(-1.0) #define pf printf #define sfi(a) scanf("%d",&a); #define sfii(a,b) scanf("%d %d",&a,&b); #define sfl(a) scanf("%lld",&a); #define sfll(a,b) scanf("%lld %lld",&a,&b); #define mp make_pair #define paii pair<int, int> #define padd pair<dd, dd> #define pall pair<ll, ll> #define fs first #define sc second #define CASE(t) printf("Case %d: ",++t) // t initialized 0 #define INF 1000000000 //10e9 #define EPS 1e-9 using namespace std; int digital_root[1000009]; ll num_dr[10];//How many digital roots with value i int main() { int N; sfi(N); ms(num_dr,0); //Lets first find all digital roots of i for i = 1 to N //There's a O(1) formula for digital root int N_max = 1000005; loop(x,1,N_max) //We need to calculate all digital root up to max possible range as, when in the num_dr[dr*dr2] { //We would need to calculate DR of dr*dr2 which maybe >N so,if we just run this loop up to N we 'll miss some values digital_root[x] = 1 + (x-1)%9 ; //https://en.wikipedia.org/wiki/Digital_root //for base b , 9 can be replaced with (b-1) if(x<=N) num_dr[ digital_root[x] ]++; //We wont add to counter if x is bigger than N } //Now we need to find all such triplets (x,y,z) such that // z != x*y but digital_root(z) = digital_root(digital_root(x)*digital_root(y)) //Try to understand the statement carefully . It seemed a bit confusing to me first /* "Not long ago Billy came across such a problem, where there were given three natural numbers A, B and C from the range [1, N], and it was asked to check whether the equation AB = C is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root d(x) of the number x is the sum s(x) of all the digits of this number, if s(x) ≤ 9, otherwise it is d(s(x)). For example, a digital root of the number 6543 is calculated as follows: d(6543) = d(6 + 5 + 4 + 3) = d(18) = 9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. d(xy) = d(d(x)d(y)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient." */ //So, in brief billy has invented an algorithm he believes that if //for some triplets (A,B,C) it can be showed that DR(A) = DR(DR(B)*DR(C)) //DR for digital_root() //Then , A = B*C //For example , // DR(6) = DR(DR(3)*DR(2)) so, 6 = 3*2 -> Billy's algorithm gives correct result // DR(21) = DR(DR(3)*DR(4)) but, 21 != 3*4 -> Billy's algorithm gives wrong result //You are asked to find the number of triplets (A,B,C) such that Billy's algorithm gives wrong answer //Observe , we can easily apply modular property and see that , from definition of digital root (That we used using %) // If, A = B*C //Then , A%9 = (B%9*C%9)%9 //But,that's the number of correct ans , we are looking for number of wrong answers //So,lets calculate number of all ans for which , DR(A) = DR(DR(B)*DR(C)) both correct ans and wrong ans //This can be easily done //Lets save number of digital_roots with value i ; i= 1 to 9 //As,we know digital root is bounded function [1 to 9] //We use counters where we save this information //Now a bit of combinatorics //A simple example, //You have "m" numbers whose digital root is x .You have "n" numbers whose digital root is y . //and You have "o" numbers whose digital root is DR(x*y) . //and as we know DR(some number) is always >=1 .. <=9 //So, 1=< x <=9 1=< y <=9 1=< DR(x*y) <=9 //(x,y,DR(x*y)) is such a triplet //How many triplets can be made this way //for x we have m possibility ,for y we have n possibility ,for DR(x*y) we have o possibility ll num_all_triplets = 0; loop(dr,1,9) //DR is in this range { loop(dr2,1,9) // We want to find such pairs x,y -> x*y this forms a valid triplet (x,y,xy) { num_all_triplets+= num_dr[dr]*num_dr[dr2]*num_dr[ digital_root[dr*dr2] ]; } } //But now we must subtract all the correct ans //How can we do that , easy by finding all such triplets //A = B*C in the range 1 to N //For example , if we fix N = 5 //such triplets are , (1,1,1) (2,1,2) (4,2,2) (3,1,3) (4,1,4) (5,1,5) //We can show that , this can be calculated this way , //1)number of X <=N which has factor 1 //2)number of X <=N which has factor 2 //3)number of X <=N which has factor 3 ...... //N)number of X <=N which has factor N //Why this works ? 1)-> (1,1,1) (2,1,2) (3,1,3) ..... (N,1,N) //2)-> (2,1,2) (4,2,2) (6,2,3) ..... (N,2,N/2) //..... This way we get all those triplets we are looking for //And we number of X<=N with factor i is just floor(N/i) //For example,1.. N has N numbers with factor 1 , 1.. N has N/2 numbers with factor 2 ...easy to realize ll num_correct_triplets = 0; loop(i,1,N) { num_correct_triplets += (N/i) ; //Works same way as floor function } ll final_ans = num_all_triplets - num_correct_triplets; cout<<final_ans<<endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_TRAVERSAL_H #define DOM_TRAVERSAL_H #ifdef DOM2_TRAVERSAL class DOM_TraversalObject_State; class DOM_Node; class DOM_Runtime; class ES_Object; class ES_Value; class DOM_TraversalObject { public: void GCTrace(); protected: DOM_TraversalObject(); DOM_Node *root; unsigned what_to_show; ES_Object *filter; BOOL entity_reference_expansion; DOM_TraversalObject_State *state; int AcceptNode(DOM_Node *node, DOM_Runtime *origining_runtime, ES_Value &exception); }; #endif // DOM2_TRAVERSAL #endif // DOM_NODEITERATOR_H
#include "mutiplex/InetAddress.h" #include <arpa/inet.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <assert.h> #include <stdexcept> #include "Debug.h" namespace muti { InetAddress::InetAddress(const std::string& addr) { size_t p = addr.find(':'); if (p == std::string::npos) { throw std::runtime_error("invalid addr"); } std::string ip = addr.substr(0, p); std::string port = addr.substr(p + 1); if (inet_pton(AF_INET, ip.c_str(), &ip_) != 1) { LOG_DEBUG("inet_pton error %s", strerror(errno)); throw std::runtime_error("invalid ip"); } port_ = htons(static_cast<uint16_t>(std::atoi(port.c_str()))); } std::string InetAddress::to_string() const { char str[32]; char ipStr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &ip_, ipStr, INET_ADDRSTRLEN); snprintf(str, 32, "%s:%d", ipStr, host_port()); return str; } std::string InetAddress::ip_str() const { char str[INET_ADDRSTRLEN]; return inet_ntop(AF_INET, &ip_, str, INET_ADDRSTRLEN); } uint16_t InetAddress::host_port() const { return ntohs(port_); } bool InetAddress::resolve(const char* name, const char* service, InetAddress& addr) { struct addrinfo hints; struct addrinfo* result; struct addrinfo* rp; bool success = false; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; /* Allow IPv4 */ hints.ai_socktype = SOCK_STREAM; /* tcp */ hints.ai_flags = 0; hints.ai_protocol = 0; int ret = getaddrinfo(name, service, &hints, &result); if (ret != 0) { return false; } for (rp = result; rp != NULL; rp = rp->ai_next) { int fd = ::socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (fd == -1) { continue; } if (connect(fd, rp->ai_addr, rp->ai_addrlen) != -1) { ::close(fd); break; /* Success */ } ::close(fd); } if (rp && rp->ai_family == AF_INET) { success = true; struct sockaddr_in* in_addr = (struct sockaddr_in*) rp->ai_addr; addr = InetAddress(in_addr->sin_addr.s_addr, in_addr->sin_port); } freeaddrinfo(result); return success; } }
#include <iostream> #include <string> int main() { //std::string x,y; int x,y; std::cin >> x; std::cin >> y; //x negativ, y negativ if (x < 0 && y < 0){ std::cout << 3; } //x negativ, y positiv else if (x < 0 && y > 0){ std::cout << 2; } //x positiv, y negativ else if (x > 0 && y < 0){ std::cout << 4; } //x positiv, y positiv else { std::cout << 1; } }
#ifndef ___DEFINE_HPP___ #define ___DEFINE_HPP___ #define FINLINE __forceinline #define MINLINE __inline #define NINLINE #define FCALL __vectorcall #define CCALL __cdecl #define PRIVATE static #define PUBLIC #define RCAST(type, target) reinterpret_cast<type>(target) #define SCAST(type, target) static_cast<type>(target) #define DCAST(type, target) dynamic_cast<type>(target) #define CCAST(type, target) const_cast<type>(target) #endif // !___DEFINE_HPP___
#ifndef HEADER_CURL_HTTP_H #define HEADER_CURL_HTTP_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifndef CURL_DISABLE_HTTP #ifdef USE_NGHTTP2 #include <nghttp2/nghttp2.h> #endif namespace youmecommon { extern const struct Curl_handler Curl_handler_http; #ifdef USE_SSL extern const struct Curl_handler Curl_handler_https; #endif /* Header specific functions */ bool Curl_compareheader(const char *headerline, /* line to check */ const char *header, /* header keyword _with_ colon */ const char *content); /* content string to find */ char *Curl_checkheaders(const struct connectdata *conn, const char *thisheader); char *Curl_copy_header_value(const char *header); char *Curl_checkProxyheaders(const struct connectdata *conn, const char *thisheader); /* ------------------------------------------------------------------------- */ /* * The add_buffer series of functions are used to build one large memory chunk * from repeated function invokes. Used so that the entire HTTP request can * be sent in one go. */ struct Curl_send_buffer { char *buffer; size_t size_max; size_t size_used; }; typedef struct Curl_send_buffer Curl_send_buffer; Curl_send_buffer *Curl_add_buffer_init(void); CURLcode Curl_add_bufferf(Curl_send_buffer *in, const char *fmt, ...); CURLcode Curl_add_buffer(Curl_send_buffer *in, const void *inptr, size_t size); CURLcode Curl_add_buffer_send(Curl_send_buffer *in, struct connectdata *conn, long *bytes_written, size_t included_body_bytes, int socketindex); CURLcode Curl_add_timecondition(struct SessionHandle *data, Curl_send_buffer *buf); CURLcode Curl_add_custom_headers(struct connectdata *conn, bool is_connect, Curl_send_buffer *req_buffer); /* protocol-specific functions set up to be called by the main engine */ CURLcode Curl_http(struct connectdata *conn, bool *done); CURLcode Curl_http_done(struct connectdata *, CURLcode, bool premature); CURLcode Curl_http_connect(struct connectdata *conn, bool *done); CURLcode Curl_http_setup_conn(struct connectdata *conn); /* The following functions are defined in http_chunks.c */ void Curl_httpchunk_init(struct connectdata *conn); CHUNKcode Curl_httpchunk_read(struct connectdata *conn, char *datap, ssize_t length, ssize_t *wrote); /* These functions are in http.c */ void Curl_http_auth_stage(struct SessionHandle *data, int stage); CURLcode Curl_http_input_auth(struct connectdata *conn, bool proxy, const char *auth); CURLcode Curl_http_auth_act(struct connectdata *conn); CURLcode Curl_http_perhapsrewind(struct connectdata *conn); /* If only the PICKNONE bit is set, there has been a round-trip and we selected to use no auth at all. Ie, we actively select no auth, as opposed to not having one selected. The other CURLAUTH_* defines are present in the public curl/curl.h header. */ #define CURLAUTH_PICKNONE (1<<30) /* don't use auth */ /* MAX_INITIAL_POST_SIZE indicates the number of bytes that will make the POST data get included in the initial data chunk sent to the server. If the data is larger than this, it will automatically get split up in multiple system calls. This value used to be fairly big (100K), but we must take into account that if the server rejects the POST due for authentication reasons, this data will always be uncondtionally sent and thus it may not be larger than can always be afforded to send twice. It must not be greater than 64K to work on VMS. */ #ifndef MAX_INITIAL_POST_SIZE #define MAX_INITIAL_POST_SIZE (64*1024) #endif #ifndef TINY_INITIAL_POST_SIZE #define TINY_INITIAL_POST_SIZE 1024 #endif #endif /* CURL_DISABLE_HTTP */ /**************************************************************************** * HTTP unique setup ***************************************************************************/ struct HTTP { struct FormData *sendit; curl_off_t postsize; /* off_t to handle large file sizes */ const char *postdata; const char *p_pragma; /* Pragma: string */ const char *p_accept; /* Accept: string */ curl_off_t readbytecount; curl_off_t writebytecount; /* For FORM posting */ struct Form form; struct back { curl_read_callback fread_func; /* backup storage for fread pointer */ void *fread_in; /* backup storage for fread_in pointer */ const char *postdata; curl_off_t postsize; } backup; enum eSendMENU{ HTTPSEND_NADA, /* init */ HTTPSEND_REQUEST, /* sending a request */ HTTPSEND_BODY, /* sending body */ HTTPSEND_LAST /* never use this */ } sending; void *send_buffer; /* used if the request couldn't be sent in one chunk, points to an allocated send_buffer struct */ }; typedef int(*sending)(void); /* Curl_send */ typedef int(*recving)(void); /* Curl_recv */ struct http_conn { #ifdef USE_NGHTTP2 #define H2_BINSETTINGS_LEN 80 nghttp2_session *h2; uint8_t binsettings[H2_BINSETTINGS_LEN]; size_t binlen; /* length of the binsettings data */ char *mem; /* points to a buffer in memory to store */ size_t len; /* size of the buffer 'mem' points to */ bool bodystarted; sending send_underlying; /* underlying send Curl_send callback */ recving recv_underlying; /* underlying recv Curl_recv callback */ bool closed; /* TRUE on HTTP2 stream close */ uint32_t error_code; /* HTTP/2 error code */ Curl_send_buffer *header_recvbuf; /* store response headers. We store non-final and final response headers into it. */ size_t nread_header_recvbuf; /* number of bytes in header_recvbuf fed into upper layer */ int32_t stream_id; /* stream we are interested in */ const uint8_t *data; /* pointer to data chunk, received in on_data_chunk */ size_t datalen; /* the number of bytes left in data */ char *inbuf; /* buffer to receive data from underlying socket */ /* We need separate buffer for transmission and reception because we may call nghttp2_session_send() after the nghttp2_session_mem_recv() but mem buffer is still not full. In this case, we wrongly sends the content of mem buffer if we share them for both cases. */ const uint8_t *upload_mem; /* points to a buffer to read from */ size_t upload_len; /* size of the buffer 'upload_mem' points to */ size_t upload_left; /* number of bytes left to upload */ int status_code; /* HTTP status code */ #else int unused; /* prevent a compiler warning */ #endif }; CURLcode Curl_http_readwrite_headers(struct SessionHandle *data, struct connectdata *conn, ssize_t *nread, bool *stop_reading); /** * Curl_http_output_auth() setups the authentication headers for the * host/proxy and the correct authentication * method. conn->data->state.authdone is set to TRUE when authentication is * done. * * @param conn all information about the current connection * @param request pointer to the request keyword * @param path pointer to the requested path * @param proxytunnel boolean if this is the request setting up a "proxy * tunnel" * * @returns CURLcode */ CURLcode Curl_http_output_auth(struct connectdata *conn, const char *request, const char *path, bool proxytunnel); /* TRUE if this is the request setting up the proxy tunnel */ } #endif /* HEADER_CURL_HTTP_H */
#pragma once #include"Anyinclude.h" #include"Collider.h" class ObjColli { public: ObjColli(sf::Texture* texture, sf::Vector2f size, sf::Vector2f position); ~ObjColli(); void Draw(sf::RenderWindow& window); sf::Vector2f GetPosition() { return body.getPosition(); } sf::FloatRect GetGlobalbound() { return body.getGlobalBounds(); } Collider GetCollider() { return Collider(body); } sf::Vector2f GetSize() { return body.getSize(); } private: sf::RectangleShape body; };
#include<bits/stdc++.h> using namespace std; #define ll long long int #define fn(i ,st, n) for(int i = st; i < n; i++) ll gcd(ll a, ll b){if(b == 0) return a; return gcd(b, a % b);} ll _power(ll a, ll n, ll mod) {ll p = 1;while (n > 0) {if(n%2) {p = p * a; p %= mod;} n >>= 1;a *= a; a %= mod;} return p % mod;} ll _modI(ll a, ll m){ return _power(a, m - 2, m);} const ll N = 2e5 + 5; const ll sz = 1e6 + 5; const ll mod = 1e9+7; const ll inf = 1e18; void solve() { ll n; cin >> n; ll ans=1; fn(i,1,2*n+1){ (ans *= i) %=mod; } (ans *= _modI(2,mod)) %= mod; cout << ans << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); int tc = 1; cin >> tc; while(tc--) { solve(); } }
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include <cstddef> namespace Push { template<typename T> struct TypeID { static constexpr size_t value() { return reinterpret_cast<size_t>(&TypeID<T>::value); } }; }
#include <algorithm> #include "Log.hpp" #include "CommunicationPair.hh" using namespace boost::asio; CommunicationPair::CommunicationPair() { this->_counter = 0; } CommunicationPair::CommunicationPair(const CommunicationPair &other) { this->_first = other.getPair().first; this->_second = other.getPair().second; this->_states = other.getStates(); this->_usedPorts = other.getPorts(); this->_counter = other.getPacketCounter(); } CommunicationPair::CommunicationPair(ip::address &first, ip::address &second) { this->_counter = 0; this->setPair(first, second); } CommunicationPair::~CommunicationPair() { } void CommunicationPair::operator=(const CommunicationPair &other) { (void)other; } const boost::ptr_vector<State> &CommunicationPair::getStates() const { return this->_states; } boost::ptr_vector<State> CommunicationPair::getSubStates(int nb) { int start = this->_states.size() - nb; boost::ptr_vector<State> sub(this->_states.begin() + start, this->_states.end()); return sub; } boost::ptr_vector<State> CommunicationPair::getSubStates(int nb, const ip::address &ip) { if (this->_first != ip && this->_second != ip) Log::get_mutable_instance().write("Error when getting sub states with: " + ip.to_string()); int start = this->_states.size() - nb; boost::ptr_vector<State> sub = this->getSubStates(nb); boost::ptr_vector<State>::iterator it = sub.begin(); while (it != sub.end()) { if (it->getFrom() != ip) it = sub.erase(it); else it++; } return sub; } bool CommunicationPair::addState(State *state) { this->_mtx.lock(); this->_counter++; if (std::find(this->_usedPorts.begin(), this->_usedPorts.end(), state->getPort()) == this->_usedPorts.end()) { this->_usedPorts.push_back(state->getPort()); } state->id = this->_counter; this->_states.push_back(state); this->_mtx.unlock(); return true; } bool CommunicationPair::checkPair(const ip::address &first, const ip::address &second) const { if ((first == this->_first && second == this->_second) || (first == this->_second && second == this->_first)) return true; return false; } const std::pair<ip::address, ip::address> CommunicationPair::getPair() const { return std::make_pair(this->_first, this->_second); } void CommunicationPair::setPair(ip::address &first, ip::address &second) { this->_first = first; this->_second = second; } void CommunicationPair::setPair(std::pair<ip::address, ip::address> &pair) { this->_first = pair.first; this->_second = pair.second; } const std::list<unsigned short> &CommunicationPair::getPorts() const { return this->_usedPorts; } const unsigned int CommunicationPair::getPacketCounter() const { return this->_states.size(); }
#include "../pch.h" #include "Texture.h" #include <WICTextureLoader.h> #include <DDSTextureLoader.h> Texture::Texture() { } Texture::~Texture() { m_texture.Reset(); } bool Texture::Initialize(std::shared_ptr<Graphics> graphics, wchar_t* fileName) { m_Graphics = graphics; if (!LoadFromFile(fileName)) { return false; } return true; } bool Texture::LoadFromFile(wchar_t* fileName) { auto device = m_Graphics->getRenderer()->getDevice(); DX::ThrowIfFailed(DirectX::CreateWICTextureFromFile(device, fileName, nullptr, m_texture.ReleaseAndGetAddressOf())); //DX::ThrowIfFailed(DirectX::CreateDDSTextureFromFile(device, fileName, nullptr, m_texture.ReleaseAndGetAddressOf())); return true; }
#include <iostream> #include <sstream> #include <cstdlib> #include <cstdio> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <climits> #include <ctime> #include <complex> #include <cmath> #include <string> #include <cctype> #include <cstring> #include <algorithm> using namespace std; #define maxn 105 typedef pair<int,int> pii; int mp[6][6]; pii ans[maxn]; pii tans[maxn]; bool vis[6][6]; int cnt; int dx[]={0,0,-1,1}; int dy[]={1,-1,0,0}; void dfs(int x,int y,int d){ if(x==4&&y==4){ if(d<cnt){ for(int i=0;i<d;i++){ ans[i]=tans[i]; } cnt=d; } return; } for(int k=0;k<4;k++){ int tx=x+dx[k]; int ty=y+dy[k]; if(tx>=0&&tx<5&&ty>=0&&ty<5){ if(mp[tx][ty]==0&&!vis[tx][ty]){ tans[d].first=tx; tans[d].second=ty; vis[tx][ty]=true; dfs(tx,ty,d+1); vis[tx][ty]=false; } } } return; } int main(){ while(cin>>mp[0][0]){ cnt=INT_MAX; memset(tans,0,sizeof(tans)); memset(ans,0,sizeof(ans)); for(int i=1;i<5;i++) cin>>mp[0][i]; for(int i=1;i<5;i++) for(int j=0;j<5;j++) cin>>mp[i][j]; tans[0].first=0; tans[0].second=0; dfs(0,0,1); for(int i=0;i<cnt;i++){ cout<<"("<<ans[i].first<<", "<<ans[i].second<<")\n"; } } return 0; }
// // Created by legen on 06-Jan-20. // #include "stivaString.h" bool SStack::isEmpty() { return first==nullptr; } void SStack::push(std::string val){ if(first==nullptr) { first=new nodeS; first->inf=val; first->next= nullptr; } else { nodeS *p=new nodeS; p->inf=val; p->next=first; first=p; } } void SStack::pop() { if(first->next== nullptr) { delete first; first= nullptr; } else { nodeS *p=first; first=first->next; p->next= nullptr; delete p; } } std::string SStack::top(){ return first->inf; }
// // Clock.h // Odin.MacOSX // // Created by Daniel on 04/06/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef __Odin_MacOSX__Clock__ #define __Odin_MacOSX__Clock__ #include "NumericTypes.h" namespace odin { namespace core { /// \brief Manages the elapsed time from the creation of the Clock class Clock { public: /// \brief Get the processor time consumed by the program /// \return Number of clock ticks since epoch /// \warning Might sum contributions from every core // !!!: Untested! static UI64 getCycles(); /// \brief Convert seconds to clock ticks /// \param timeSeconds The amount of seconds to be converted /// \return Number of clock ticks corresponding to timeSeconds // !!!: Untested! static UI64 secondsToCycles(F64 timeSeconds); /// \brief Convert clock ticks to seconds /// \param timeCycles Number of clock ticks to be converted /// \return Number of seconds corresponding to timeCycles /// \warning Dangerous. Use only to convert small durations to seconds. // !!!: Untested! static F64 cyclesToSeconds(UI64 timeCycles); /// \brief Current time in milliseconds /// \return Number of milliseconds since epoch static F64 getTimeMillis(); /// \brief Current time in seconds /// \return Number of seconds since epoch static F64 getTimeSeconds(); /// \brief Clock constructor /// \param startTimeSeconds Initial time of the clock in seconds Clock(F64 startTimeSeconds = 0.0f); /// \brief Get the start time of the clock /// \return Starting time of the clock since epoch, in seconds F64 getStartTime() const; /// \brief Get the elapsed time /// \return Elapsed time in seconds since the start of the clock F64 getElapsedTime() const; /// \brief Advance the clock by some amount /// \param deltaTimeSeconds Time in seconds to add to the clock void add(F64 deltaTimeSeconds); /// \brief Pause the clock void pause(); /// \brief Resume the clock void resume(); /// \brief Restart the clock void restart(); /// \brief Check if the clock is paused bool isPaused() const; /// \brief Change the time scale of the clock /// \param scale Time scale of the clock (1.0 is normal) void setTimeScale(F32 scale); /// \brief Get the current time scale of the clock /// \return Current time scale of the clock F32 getTimeScale() const; /// \brief Advance the clock by one frame /// \param targetFPS the target FPS of the frame void singleStep(F32 targetFPS); private: F64 m_startTime; F64 m_elapsedTime; F32 m_timeScale; bool m_isPaused; }; } } #endif /* defined(__Odin_MacOSX__Clock__) */
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int l=0, r=nums.size()-1; int mn = -1, mx = -1; while(l<=r){ int m = (l+r) / 2; if(nums[m] == target){ mn = m; r = m - 1; } else if(nums[m] < target) l = m + 1; else r = m - 1; } l = 0; r = nums.size() - 1; while(l<=r){ int m = (l+r) / 2; if(nums[m] == target){ mx = m; l = m + 1; } else if(nums[m] < target) l = m + 1; else r = m - 1; } vector<int> v; v.push_back(mn); v.push_back(mx); return v; } };
#include "Assets.h" std::map<std::string, SpriteInfo> Assets::sprites; void Assets::loadAssets() { sprites["ammocrate"] = SpriteInfo("Content/Textures/ammocrate.png"); sprites["grassblock"] = SpriteInfo("Content/Textures/grass_block.png"); sprites["tilegrassblock"] = SpriteInfo("Content/Textures/grass_block_tileable.png"); sprites["tallrock"] = SpriteInfo("Content/Textures/tall_rock.png"); sprites["ladder"] = SpriteInfo("Content/Textures/ladder.png"); sprites["cloud"] = SpriteInfo("Content/Textures/cloud.png"); sprites["background"] = SpriteInfo("Content/Textures/background.png"); sprites["blackhole"] = SpriteInfo("Content/Textures/blackhole.png"); sprites["bluepeewee"] = SpriteInfo("Content/Textures/bluepeewee.png", 36, 6); sprites["bluepeewee"].mHitBox = sf::FloatRect(20.f, 10.f, 24.f, 44.f); sprites["bridge"] = SpriteInfo("Content/Textures/bridge.png"); sprites["bridge"].mHitBox = sf::FloatRect(6.f, 37.f, 140.f, 6.f); }
#include <iostream> #include "options.h" #include "integrator.h" #include "int_euler.h" #include "int_rungekutta2.h" #include "int_rungekutta4.h" #include "int_rungekutta5.h" #include "int_rungekutta7.h" #include "parameter.h" #include "tbp1D.h" #include "rtbp1D.h" #include "tbp3D.h" #include "rtbp3D.h" #include "redutilcu.h" #include "red_constants.h" #include "red_macro.h" using namespace redutilcu; options::options(int argc, const char** argv) : param(0x0) { create_default(); parse(argc, argv); param = new parameter(dir[DIRECTORY_NAME_IN], in_fn[INPUT_NAME_PARAMETER], print_to_screen); } options::~options() { } void options::create_default() { continue_simulation = false; benchmark = false; test = false; verbose = false; print_to_screen = false; ef = false; info_dt = 5.0; // [sec] dump_dt = 3600.0; // [sec] id_dev = 0; n_change_to_cpu = 100; comp_dev = COMPUTING_DEVICE_CPU; g_disk_model = GAS_DISK_MODEL_NONE; out_fn[OUTPUT_NAME_EVENT] = "event"; out_fn[OUTPUT_NAME_INFO] = "info"; out_fn[OUTPUT_NAME_LOG] = "log"; out_fn[OUTPUT_NAME_DATA] = "result"; out_fn[OUTPUT_NAME_INTEGRAL] = "integral"; out_fn[OUTPUT_NAME_INTEGRAL_EVENT] = "integral_event"; } void options::parse(int argc, const char** argv) { int i = 1; while (i < argc) { string p = argv[i]; if ( p == "--model" || p == "-m") { i++; string value = argv[i]; if ( value == "tbp1D") { dyn_model = DYN_MODEL_TBP1D; } else if (value == "tbp3D") { dyn_model = DYN_MODEL_TBP3D; } else if (value == "rtbp1D") { dyn_model = DYN_MODEL_RTBP1D; } else if (value == "rtbp3D") { dyn_model = DYN_MODEL_RTBP3D; } else { throw string("Invalid dynamical model: " + value + "."); } } else if (p == "--continue" || p == "-c") { continue_simulation = true; } else if (p == "--benchmark" || p == "-b") { benchmark = true; } else if (p == "--test" || p == "-t") { test = true; } else if (p == "--verbose" || p == "-v") { verbose = true; } else if (p == "--print_to_screen" || p == "-pts") { verbose = true; print_to_screen = true; } else if (p == "-ef") { ef = true; } else if (p == "--info-dt" || p == "-i_dt") { i++; if (!tools::is_number(argv[i])) { throw string("Invalid number at: " + p); } info_dt = atof(argv[i]); } else if (p == "--dump-dt" || p == "-d_dt") { i++; if (!tools::is_number(argv[i])) { throw string("Invalid number at: " + p); } dump_dt = atof(argv[i]); } else if (p == "--id_active_device" || p == "-id_dev") { i++; if (!tools::is_number(argv[i])) { throw string("Invalid number at: " + p); } id_dev = atoi(argv[i]); } else if (p == "--n_change_to_cpu" || p == "-n_chg") { i++; if (!tools::is_number(argv[i])) { throw string("Invalid number at: " + p); } n_change_to_cpu = atoi(argv[i]); } else if (p == "--cpu" || p == "-cpu") { comp_dev = COMPUTING_DEVICE_CPU; } else if (p == "--gpu" || p == "-gpu") { comp_dev = COMPUTING_DEVICE_GPU; } else if (p == "--analytic_gas_disk" || p == "-ga") { i++; in_fn[INPUT_NAME_GAS_DISK_MODEL] = argv[i]; g_disk_model = GAS_DISK_MODEL_ANALYTIC; } else if (p == "--fargo_gas_disk" || p == "-gf") { i++; in_fn[INPUT_NAME_GAS_DISK_MODEL] = argv[i]; g_disk_model = GAS_DISK_MODEL_FARGO; } else if (p == "--info-filename" || p == "-info") { i++; out_fn[OUTPUT_NAME_INFO] = argv[i]; } else if (p == "--event-filename" || p == "-event") { i++; out_fn[OUTPUT_NAME_EVENT] = argv[i]; } else if (p == "--log-filename" || p == "-log") { i++; out_fn[OUTPUT_NAME_LOG] = argv[i]; } else if (p == "--result-filename" || p == "-result") { i++; out_fn[OUTPUT_NAME_DATA] = argv[i]; } else if (p == "--initial_conditions" || p == "-ic") { i++; in_fn[INPUT_NAME_DATA] = argv[i]; } else if (p =="--parameters" || p == "-p") { i++; in_fn[INPUT_NAME_PARAMETER] = argv[i]; } else if (p == "--inputDir" || p == "-iDir") { i++; dir[DIRECTORY_NAME_IN] = argv[i]; } else if (p == "--outputDir" || p == "-oDir") { i++; dir[DIRECTORY_NAME_OUT] = argv[i]; } else if (p == "--help" || p == "-h") { print_usage(); exit(EXIT_SUCCESS); } else { throw string("Invalid switch on command-line: " + p + "."); } i++; } if (0 == dir[DIRECTORY_NAME_OUT].length()) { dir[DIRECTORY_NAME_OUT] = dir[DIRECTORY_NAME_IN]; } } ode* options::create_tbp1D() { tbp1D* model = new tbp1D(1, comp_dev); string path = file::combine_path(dir[DIRECTORY_NAME_IN], in_fn[INPUT_NAME_DATA]); model->load(path); model->calc_energy(); model->t = model->h_epoch[0]; model->tout = model->t; param->start_time = model->t; // TODO: transform time variables in opt param->stop_time = param->start_time + param->simulation_length; return model; } ode* options::create_rtbp1D() { rtbp1D* model = new rtbp1D(1, comp_dev); string path = file::combine_path(dir[DIRECTORY_NAME_IN], in_fn[INPUT_NAME_DATA]); model->load(path); model->calc_energy(); model->t = model->h_epoch[0]; model->tout = model->t; param->start_time = model->t; // TODO: transform time variables in opt param->stop_time = param->start_time + param->simulation_length; return model; } ode* options::create_tbp3D() { tbp3D* model = new tbp3D(1, comp_dev); string path = file::combine_path(dir[DIRECTORY_NAME_IN], in_fn[INPUT_NAME_DATA]); model->load(path); // TODO: calc_integrals model->calc_energy(); model->t = model->h_epoch[0]; model->tout = model->t; param->start_time = model->t; // TODO: transform time variables in opt param->stop_time = param->start_time + param->simulation_length; return model; } ode* options::create_rtbp3D() { rtbp3D* model = new rtbp3D(1, comp_dev); string path = file::combine_path(dir[DIRECTORY_NAME_IN], in_fn[INPUT_NAME_DATA]); model->load(path); // TODO: calc_integrals model->calc_energy(); model->t = model->h_epoch[0]; model->tout = model->t; param->start_time = model->t; // TODO: transform time variables in opt param->stop_time = param->start_time + param->simulation_length; return model; } integrator* options::create_integrator(ode& f, ttt_t dt) { integrator* intgr = 0x0; switch (param->int_type) { case INTEGRATOR_EULER: intgr = new euler(f, dt, comp_dev); break; case INTEGRATOR_RUNGEKUTTA2: intgr = new int_rungekutta2(f, dt, comp_dev); break; case INTEGRATOR_RUNGEKUTTA4: intgr = new int_rungekutta4(f, dt, param->adaptive, param->tolerance, comp_dev); break; case INTEGRATOR_RUNGEKUTTAFEHLBERG56: intgr = new int_rungekutta5(f, dt, param->adaptive, param->tolerance, comp_dev); break; case INTEGRATOR_RUNGEKUTTAFEHLBERG78: intgr = new int_rungekutta7(f, dt, param->adaptive, param->tolerance, comp_dev); break; default: throw string("Requested integrator is not implemented."); } if (param->error_check_for_tp) { intgr->error_check_for_tp = true; } return intgr; } void options::print_usage() { cout << "Usage: red.cuda <parameterlist>" << endl; cout << "Parameters:" << endl; cout << " -c | --continue : continue a simulation from a previous run's saved state" << endl; cout << " -b | --benchmark : run benchmark to find out the optimal number of threads per block" << endl; cout << " -t | --test : run tests" << endl; cout << " -v | --verbose : verbose mode (log all event during the execution fo the code to the log file)" << endl; cout << " -pts | --print_to_screen : verbose mode and print everything to the standard output stream too" << endl; cout << " -ef | : use extended file names (use only for debuging purposes)" << endl; cout << " -i_dt | --info-dt <number> : the time interval in seconds between two subsequent information print to the screen (default value is 5 sec)" << endl; cout << " -d_dt | --dump-dt <number> : the time interval in seconds between two subsequent data dump to the hard disk (default value is 3600 sec)" << endl; cout << " -id_dev | --id_active_device <number> : the id of the device which will execute the code (default value is 0)" << endl; cout << " -n_chg | --n_change_to_cpu <number> : the threshold value for the total number of SI bodies to change to the CPU (default value is 100)" << endl; cout << " -gpu | --gpu : execute the code on the graphics processing unit (GPU) (default value is true)" << endl; cout << " -cpu | --cpu : execute the code on the cpu if required by the user or if no GPU is installed (default value is false)" << endl; cout << " -ic | --initial_condition <filename> : the file containing the initial conditions" << endl; cout << " -info | --info-filename <filename> : the name of the file where the runtime output of the code will be stored (default value is info.txt)" << endl; cout << " -event | --event-filename <filename> : the name of the file where the details of each event will be stored (default value is event.txt)" << endl; cout << " -log | --log-filename <filename> : the name of the file where the details of the execution of the code will be stored (default value is log.txt)" << endl; cout << " -result | --result-filename <filename> : the name of the file where the simlation data for a time instance will be stored (default value is result.txt)" << endl; cout << " -iDir | --inputDir <directory> : the directory containing the input files" << endl; cout << " -oDir | --outputDir <directory> : the directory where the output files will be stored (if omitted the input directory will be used)" << endl; cout << " -p | --parameter <filename> : the file containing the parameters of the simulation" << endl; cout << " -ga | --analytic_gas_disk <filename> : the file containing the parameters of an analyticaly prescribed gas disk" << endl; cout << " -gf | --fargo_gas_disk <filename> : the file containing the details of the gas disk resulted from FARGO simulations" << endl; cout << " -nb | --number-of-bodies : set the number of bodies for benchmarking (pattern: n_st n_gp n_rp n_pp n_spl n_pl n_tp)" << endl; cout << " -h | --help : print this help" << endl; }
#ifndef userList_h #define userList_h #include "user.h" const int Max_Users = 50; typedef tUser *tUserPtr; typedef tUserPtr tArrayUsers[Max_Users]; typedef struct { tArrayUsers list; int counter; }tUserList; void initialize(tUserList &users); //Initialize a list of users bool load(tUserList &users, std::string domain); //Load a list of users from a file void save(const tUserList &users, std::string domain); //Save a list of users into a file bool add(tUserList &users, const tUser &user); //Add a new user in the list of users bool findUser(const tUserList &users, std::string id, int &position); //Find a user from the list and return its position void destroy(tUserList &users); //Destroy the list of users #endif
#ifndef apso_h #define apso_h #include <vector> #include <algorithm> #include <iostream> #include "../tiny-dnn/tiny_dnn/tiny_dnn.h" using tiny_dnn::vec_t; class AdaptiveSwarmParameters{ public: unsigned seed; double inirtiaWeight; double maxInirtiaWeight; double minInirtiaWeight; double localVelocityRatio; double globalVelocityRatio; size_t populationSize; size_t dimension; double deltaTau; int maxPSOEpochs; }; template <class FitnessFunction> class AdaptiveParticle { public: vec_t pos; vec_t speed; double currentFitnVal; double inirtiaWeight; double maxInirtiaWeight; double minInirtiaWeight; double localVelocityRatio; double globalVelocityRatio; double deltaTau; double maxPSOEpochs; double curPSOEpoch; double dimension; double localBestFitnVal; vec_t localBestPos; FitnessFunction fitnessFunction; void InitParticle(FitnessFunction fitnessFunction, double dimension, double inirtiaWeight, double maxInirtiaWeight, double minInirtiaWeight, double localVelocityRatio, double globalVelocityRatio, double deltaTau, double maxPSOEpochs, unsigned &seed) { this->inirtiaWeight = inirtiaWeight; this->maxInirtiaWeight = maxInirtiaWeight; this->minInirtiaWeight = minInirtiaWeight; this->localVelocityRatio = localVelocityRatio; this->globalVelocityRatio = globalVelocityRatio; this->deltaTau = deltaTau; this->maxPSOEpochs = maxPSOEpochs; this->curPSOEpoch = 0; this->dimension = dimension; this->fitnessFunction = fitnessFunction; pos.resize(dimension); speed.resize(dimension); double a = -1; double b = 1; std::generate(pos.begin(), pos.end(),[a, b, &seed]{return double(rand_r(&seed)) / RAND_MAX * (b - a) + a;}); a = -0.3; b = 0.3; std::generate(speed.begin(), speed.end(),[a, b, &seed]{return double(rand_r(&seed)) / RAND_MAX * (b - a) + a;}); currentFitnVal = fitnessFunction.f(pos); localBestFitnVal = currentFitnVal; localBestPos = pos; } void NextIteration(const vec_t &globalBestPos, double globalBestFitnVal, unsigned &seed) { double a = 0; double b = 1; vec_t rnd_localBestPosition(pos.size()); vec_t rnd_globalBestPosition(pos.size()); std::generate(rnd_localBestPosition.begin(), rnd_localBestPosition.end(),[a, b, &seed]{return double(rand_r(&seed)) / RAND_MAX * (b - a) + a;}); std::generate(rnd_globalBestPosition.begin(), rnd_globalBestPosition.end(),[a, b, &seed]{return double(rand_r(&seed)) / RAND_MAX * (b - a) + a;}); for(int i = 0; i < speed.size(); i++) { inirtiaWeight = minInirtiaWeight - curPSOEpoch*(maxInirtiaWeight - minInirtiaWeight)/maxPSOEpochs; speed[i] = (inirtiaWeight * speed[i]) + (localVelocityRatio * rnd_localBestPosition[i] * (localBestPos[i] - pos[i])) + (globalVelocityRatio * rnd_globalBestPosition[i] * (globalBestPos[i] - pos[i])); pos[i] += deltaTau * speed[i]; } curPSOEpoch++; currentFitnVal = fitnessFunction.f(pos); if(currentFitnVal < localBestFitnVal) { localBestFitnVal = currentFitnVal; localBestPos = pos; } } }; template <class FitnessFunction> class AdaptiveSwarm { std::vector<AdaptiveParticle<FitnessFunction>> population; double globalBestFitnVal; vec_t globalBestPos; AdaptiveSwarmParameters sParams; public: AdaptiveSwarm(FitnessFunction _fitnessFunction, AdaptiveSwarmParameters _sp) { sParams = _sp; population.resize(sParams.populationSize); globalBestFitnVal = -1; for(int i = 0; i < sParams.populationSize; i++) { unsigned seed = rand_r(&(sParams.seed)); population[i].InitParticle(_fitnessFunction, sParams.dimension, sParams.inirtiaWeight, sParams.maxInirtiaWeight, sParams.minInirtiaWeight, sParams.localVelocityRatio, sParams.globalVelocityRatio, sParams.deltaTau, sParams.maxPSOEpochs, seed); if((population[i].localBestFitnVal < globalBestFitnVal) || (globalBestFitnVal == -1)) { globalBestFitnVal = population[i].localBestFitnVal; globalBestPos = population[i].localBestPos; } } #ifdef LOG std::cout << "\nEpoch: " << 0 << " Best fitn val: " << globalBestFitnVal << std::endl; #endif } void optimize() { int i = 0; while(i < sParams.maxPSOEpochs) { double savedGlobalBestFitnVal = globalBestFitnVal; vec_t savedGlobalBestPos = globalBestPos; for(int i = 0; i < population.size(); i++) { if(population[i].localBestFitnVal < globalBestFitnVal) { globalBestFitnVal = population[i].localBestFitnVal; globalBestPos = population[i].localBestPos; } unsigned seed = rand(); population[i].NextIteration(savedGlobalBestPos, savedGlobalBestFitnVal, seed); } i++; #ifdef LOG std::cout << "\nEpoch: " << i << " Best fitn val: " << globalBestFitnVal << std::endl; #endif } } double getSolution(vec_t &v) { v = globalBestPos; return globalBestFitnVal; } }; #endif /* apso_h */
#include "BuildParser.h" #include "Build.h" #include "ReturnCode.h" #include "Logging.h" #include "File.h" #include <string> #include <tinyxml/tinyxml.h> #include <boost/regex.hpp> #include <boost/filesystem.hpp> #include <boost/format.hpp> //----------------------------------------------------------------------------- namespace { class VSProjectParser { public: VSProjectParser(const char* path); WhatIBuild::ReturnCodeEnum Parse(const std::string& solutionPath, WhatIBuild::Module& module); private: void ParseConfigurations(TiXmlNode* root, WhatIBuild::Module& module); void ParseGlobals(TiXmlNode* root, WhatIBuild::Module& module); void ParseConfigurationSettings(TiXmlNode* root, WhatIBuild::Module& module); void ParsePropertySheets(TiXmlNode* root, WhatIBuild::Module& module); void ParseFileList(TiXmlNode* root, boost::filesystem::path& directory, WhatIBuild::Module& module); void TransferXmlProperties(TiXmlNode* root, WhatIBuild::Property& property); std::string m_Path; }; VSProjectParser::VSProjectParser(const char* path) : m_Path(path) { } WhatIBuild::ReturnCodeEnum VSProjectParser::Parse(const std::string& solutionPath, WhatIBuild::Module& module) { boost::filesystem::path projectPath = boost::filesystem::path(solutionPath).parent_path(); projectPath /= module.GetPath(); boost::filesystem::path directory = projectPath.parent_path(); if (!boost::filesystem::exists(projectPath)) { WIBLOG_ERROR( (boost::format("Project file: \"%s\" not found") % projectPath.string()).str().c_str() ); return WhatIBuild::e_Return_FileNotFound; } TiXmlDocument doc( projectPath.string().c_str() ); if (!doc.LoadFile()) { WIBLOG_ERROR( (boost::format("Not able to parse XML: %s") % projectPath.string()).str().c_str() ); return WhatIBuild::e_Return_ParseError; } TiXmlElement* project = doc.FirstChildElement("Project"); if (project == NULL) { return WhatIBuild::e_Return_ParseError; } for (TiXmlElement* element = project->FirstChildElement("ItemGroup"); element; element = element->NextSiblingElement("ItemGroup")) { if (element->Attribute("Label") == NULL) { ParseFileList(element, directory, module); } else if (strcmp(element->Attribute("Label"), "ProjectConfigurations") == 0) { ParseConfigurations(element, module); } } for (TiXmlElement* element = project->FirstChildElement("PropertyGroup"); element; element = element->NextSiblingElement("PropertyGroup")) { if (element->Attribute("Label") == NULL) { continue; } else if (strcmp(element->Attribute("Label"), "Globals") == 0) { ParseGlobals(element, module); } } for (TiXmlElement* element = project->FirstChildElement("ItemDefinitionGroup"); element; element = element->NextSiblingElement("ItemDefinitionGroup")) { if (element->Attribute("Condition") != NULL) { ParseConfigurationSettings(element, module); } } for (TiXmlElement* element = project->FirstChildElement("ImportGroup"); element; element = element->NextSiblingElement("ImportGroup")) { if (element->Attribute("Label") == NULL) { continue; } else if (strcmp(element->Attribute("Label"), "PropertySheets") == 0) { ParsePropertySheets(element, module); } } return WhatIBuild::e_Return_OK; } void VSProjectParser::ParseConfigurations(TiXmlNode* root, WhatIBuild::Module& module) { for (TiXmlElement* element = root->FirstChildElement("ProjectConfiguration"); element; element = element->NextSiblingElement("ProjectConfiguration")) { WhatIBuild::Property configuration("ProjectConfiguration", element->Attribute("Include")); TransferXmlProperties(element, configuration); module.AddProperty(WhatIBuild::Module::e_ProjectConfigurations, configuration); } } void VSProjectParser::ParseGlobals(TiXmlNode* node, WhatIBuild::Module& module) { WhatIBuild::Property globals("Globals", ""); TransferXmlProperties(node, globals); module.AddProperty(WhatIBuild::Module::e_Globals, globals); } void VSProjectParser::ParseConfigurationSettings(TiXmlNode* node, WhatIBuild::Module& module) { TiXmlElement* element = node->ToElement(); const char* value = element->Attribute("Condition") != NULL ? element->Attribute("Condition") : ""; WhatIBuild::Property settings("Condition", value); TransferXmlProperties(node, settings); module.AddProperty(WhatIBuild::Module::e_ConfigurationSettings, settings); } void VSProjectParser::ParsePropertySheets(TiXmlNode* node, WhatIBuild::Module& module) { TiXmlElement* element = node->ToElement(); const char* value = element->Attribute("Condition") != NULL ? element->Attribute("Condition") : ""; WhatIBuild::Property propertySheet("PropertySheets", value); for (TiXmlElement* element = node->FirstChildElement("Import"); element; element = element->NextSiblingElement("Import")) { const char* path = element->Attribute("Project") != NULL ? element->Attribute("Project") : ""; WhatIBuild::Property import("Import", path); TransferXmlProperties(element, import); propertySheet.AddProperty(import); } module.AddProperty(WhatIBuild::Module::e_PropertySheets, propertySheet); } void VSProjectParser::ParseFileList(TiXmlNode* root, boost::filesystem::path& directory, WhatIBuild::Module& module) { static char SectionNames[][32] = { "ClCompile", "ClInclude", }; static int SECTIONS_COUNT = sizeof(SectionNames) / sizeof(SectionNames[0]); for (int sectionIdx = 0; sectionIdx < SECTIONS_COUNT; ++sectionIdx) { for (TiXmlElement* element = root->FirstChildElement(SectionNames[sectionIdx]); element; element = element->NextSiblingElement(SectionNames[sectionIdx])) { if (element->Attribute("Include")) { boost::filesystem::path filePath = element->Attribute("Include"); boost::filesystem::path completePath = directory; completePath /= filePath; WhatIBuild::Unit unit(filePath.filename().string(), completePath.string()); module.AddUnit(unit); } } } } void VSProjectParser::TransferXmlProperties(TiXmlNode* root, WhatIBuild::Property& property) { for (TiXmlElement* element = root->FirstChildElement(); element; element = element->NextSiblingElement()) { const char* name = element->Value() != NULL ? element->Value() : ""; const char* value = element->GetText() != NULL ? element->GetText() : ""; WhatIBuild::Property child(name, value); TransferXmlProperties(element, child); property.AddProperty(child); } } //----------------------------------------------------------------------------- class VSSolutionParser { public: VSSolutionParser(const char* path); WhatIBuild::ReturnCodeEnum Parse(WhatIBuild::Build& build); private: static const int SUPPORTED_VERSION = 11; WhatIBuild::ReturnCodeEnum ParseInternal(WhatIBuild::Build& build); WhatIBuild::ReturnCodeEnum ParseProject(std::string& name, std::string& path); const std::string& GetCurrentLine() const; void ReadNextLine(); std::string m_Path; std::string m_CurrentLine; File m_File; }; VSSolutionParser::VSSolutionParser(const char* path) : m_Path(path) { } const std::string& VSSolutionParser::GetCurrentLine() const { return m_CurrentLine; } void VSSolutionParser::ReadNextLine() { if (!m_File.EndOfFile()) { m_File.ReadLine(m_CurrentLine); } } WhatIBuild::ReturnCodeEnum VSSolutionParser::Parse(WhatIBuild::Build& build) { if (m_File.Open(m_Path.c_str())) { WIBLOG_INFO( (boost::format("Parsing solution: %s") % m_Path).str().c_str() ); return ParseInternal(build); } else { WIBLOG_ERROR( (boost::format("Solution file not found on path: %s") % m_Path).str().c_str() ); return WhatIBuild::e_Return_FileNotFound; } } WhatIBuild::ReturnCodeEnum VSSolutionParser::ParseInternal(WhatIBuild::Build& build) { enum ParseStateEnum { e_Parse_FileVersion, e_Parse_ProjectSection, e_Parse_GlobalSection, e_Parse_Error, }; WhatIBuild::ReturnCodeEnum resultCode = WhatIBuild::e_Return_OK; ParseStateEnum parseState = e_Parse_FileVersion; std::string line; const char reVersionDefinition[] = "^Microsoft Visual Studio Solution File, Format Version ([\\d\\.]+)$"; boost::regex versionDefinition(reVersionDefinition); while(!m_File.EndOfFile() && parseState != e_Parse_Error) { switch(parseState) { case e_Parse_FileVersion: { ReadNextLine(); boost::match_results<std::string::const_iterator> query; if (regex_match(GetCurrentLine(), query, versionDefinition )) { std::string versionText(query[1].first, query[1].second); int versionNumber = (int) atof(versionText.c_str()); if (versionNumber == SUPPORTED_VERSION) { WIBLOG_INFO( (boost::format("Solution file version: %u is supported") % versionNumber).str().c_str() ); ReadNextLine(); while(GetCurrentLine()[0] == '#') // skip comments { ReadNextLine(); } parseState = e_Parse_ProjectSection; } else { WIBLOG_ERROR( (boost::format("Not supported solution version: %u, expected %u") % versionNumber % SUPPORTED_VERSION).str().c_str() ); parseState = e_Parse_Error; resultCode = WhatIBuild::e_Return_NotSupportedVersion; } } } break; case e_Parse_ProjectSection: { if(GetCurrentLine() != "Global") { std::string name, path; if (ParseProject(name, path) == WhatIBuild::e_Return_OK) { // skip solution folders boost::filesystem::path filename(path); if (!filename.has_extension()) { WIBLOG_INFO( (boost::format("Found solution folder: %s") % name).str().c_str() ); continue; } WIBLOG_INFO( (boost::format("Parsing project: %s on path: %s") % name % m_Path).str().c_str() ); WhatIBuild::Module module(name, path); VSProjectParser projectParser(path.c_str()); WhatIBuild::ReturnCodeEnum returnCode = projectParser.Parse(m_Path, module); if (returnCode == WhatIBuild::e_Return_OK) { WIBLOG_INFO( (boost::format("%u file(s) found") % module.GetUnitsCount()).str().c_str() ); build.AddModule(module); } else { WIBLOG_ERROR( (boost::format("Project parsing error: %d") % returnCode).str().c_str() ); parseState = e_Parse_Error; resultCode = returnCode; } } else { WIBLOG_ERROR( (boost::format("Failed parsing solution file on line: %s") % GetCurrentLine()).str().c_str() ); parseState = e_Parse_Error; resultCode = WhatIBuild::e_Return_ParseError; } } else { WIBLOG_INFO( (boost::format("Solution parsed! %u project(s) found") % build.GetModulesCount()).str().c_str() ); parseState = e_Parse_GlobalSection; } } break; case e_Parse_GlobalSection: { // Not implemented ReadNextLine(); } break; }; } m_File.Close(); return resultCode; } WhatIBuild::ReturnCodeEnum VSSolutionParser::ParseProject(std::string& name, std::string& path) { const char reProjectDefinition[] = "^Project[^=]*=[ ]*\"([^\"]*)\"[ ]*,[ ]*\"([^\"]*)\".*$"; boost::regex projectDefinition(reProjectDefinition); boost::match_results<std::string::const_iterator> query; if (regex_match(GetCurrentLine(), query, projectDefinition)) { name = std::string(query[1].first, query[1].second); path = std::string(query[2].first, query[2].second); } else { WIBLOG_ERROR( (boost::format("Not valid project definition: %s") % GetCurrentLine()).str().c_str() ); WhatIBuild::e_Return_ParseError; } while(!m_File.EndOfFile()) { ReadNextLine(); if (GetCurrentLine() == "EndProject") { ReadNextLine(); return WhatIBuild::e_Return_OK; } } return WhatIBuild::e_Return_ParseError; } } //----------------------------------------------------------------------------- namespace WhatIBuild { int Parser::ParseVSSolution(const char* path, Build& build) { VSSolutionParser parser(path); return parser.Parse(build); } }
#include "../inc/pac.hpp" //#include "../inc/Game.hpp" int main(int argc, char **argv) { std::string line; char *text; int i = 0; int j = 0; std::vector<char*> readed; if (argc == 2 && argv[1]) { int count = 0; std::ifstream map (argv[1]); if (map.is_open()) { while (! map.eof() ) { getline (map,line); char *cstr = new char[line.length() + 1]; strcpy(cstr, line.c_str()); readed.push_back(cstr); if (j == 0) j = line.length(); if (j != line.length()) { std::cout << "BAD MAP" << std::endl; return -1; } i++; } map.close(); Game game(readed, i, j); game.start(); return 0; } else std::cout << "Unable to open file"; } else std::cout<< "usage: ./pac [filename](map)"<< std::endl; return 0; }
#include "IBOR.h" #include "Curve.h" void IBOR::adjustCurveToPriceFairly(Curve& c) const { double marketDF = 1.0/(1.0+m_rate*m_expiry/100); c.setDiscountFactorToLaterPoint(m_expiry,marketDF); }
#pragma once #include "../../../GameComponents/Animation.h" #include "../../Entity.h" #include "../../Apple/Apple.h" class ManThrowBowl:public Entity { public: ManThrowBowl(vector<D3DXVECTOR2> listpos); ~ManThrowBowl(); Animation* ThrowAnimate; Animation* mCurrentAnimate; bool AllowThrow = true; void Update(Entity* player); vector<RECT> LoadRect(); void CheckSite(Entity* player); void Draw(D3DXVECTOR3 position, RECT sourceRect, D3DXVECTOR2 scale, D3DXVECTOR2 transform, float angle, D3DXVECTOR2 rotationCenter, D3DXCOLOR colorKey); void OnCollision(Entity *impactor, CollisionReturn data, SideCollisions side); vector<D3DXVECTOR2> mListPosition; Apple* mApple; Apple* mCurrentApple; };
/** * @file mini_sdp/util.cc * @brief * @version 0.1 * @date 2021-01-07 * * @copyright Copyright (c) 2021 Tencent. All rights reserved. * */ #include <cstring> #include "util.h" namespace mini_sdp { std::vector<StrSlice> StrSplit(const char* data, size_t len, char chr, bool is_remove_space) { std::vector<StrSlice> slices; const char* ppos = nullptr; StrSlice slice; while (len > 0) { ppos = (const char*)memchr(data, chr, len); slice.ptr = data; if (ppos) { slice.len = ppos - data; len -= slice.len + 1; data = ppos + 1; if (is_remove_space) { while (len > 0 && *data == chr) { data++; len--; } } } else { slice.len = len; len = 0; } slices.push_back(slice); } return slices; } std::pair<std::string, const char*> StrGetFirstSplit(const char* data, size_t len, char chr) { const char* pos = (const char*)memchr(data, chr, len); if (pos == nullptr) { return std::make_pair(std::string(data, len), nullptr); } return std::make_pair(std::string(data, pos - data), pos + 1); } std::string& Trim(std::string &str) { if (str.empty()) { return str; } str.erase(0,str.find_first_not_of("\r\t")); str.erase(str.find_last_not_of("\r\t") + 1); return str; } } // namespace mini_sdp
#pragma once #include"stdfax.h" class Barrier_method { private: vector_2d X0; double r, C, eps; void input(string Filename); double F(double X, double Y, double Rk); public: int Num_iteration = 0; int Num_calculation = 0; Barrier_method(string Filename); Barrier_method(vector_2d X, double R, double c, double e); vector_2d Calc(); static double f(double X, double Y); static double P(double X, double Y, double Rk); };