text stringlengths 8 6.88M |
|---|
#ifndef GETMODELITEMICONFACTORY_H
#define GETMODELITEMICONFACTORY_H
#include <QIcon>
namespace FastCAEDesigner
{
class GetModelItemIconFactory
{
public:
static QIcon Get(int modelItemType);
};
}
#endif
|
#include "graphics.h"
#include <cassert>
using namespace graphics;
Graphics::~Graphics() {
}
std::vector<float> Graphics::relativePos(const float x, const float y, const float xp, const float yp) const {
std::vector<float> vec = {
(-0.5f + x - xp)/VIEW_WIDTH,
-(0.5f + y - yp)/VIEW_HEIGHT
};
assert(vec.size() == 2);
return vec;
}
|
//#include <windows.h>
//#include <math.h>
//#include <gl/gl.h>
//#include <gl/glut.h> // (or others, depending on the system in use)
//
//#define PI 3.1415926
//
//int Width = 800;
//int Height = 800;
//
//float sun_radius = 50.0;
//
//float earthRotation = 0.0, moonRotation = 0.0;
//
//float earth_rotation_speed = 0.2;
//float moon_rotation_speed = 2;
//
//
//void init(void) {
// glMatrixMode(GL_PROJECTION);
// glLoadIdentity();
// gluOrtho2D(-1.0*Width/2.0, Width/2.0, -1.0*Height/2.0, Height/2.0);
//}
//
//
//void Draw_Circle(float c_radius) {
// float delta;
// int num = 36;
//
// delta = 2 * PI / num;
// glBegin(GL_POLYGON);
// for (int i = 0; i < num; i++)
// glVertex2f(c_radius*cos(delta*i), c_radius*sin(delta*i));
// glEnd();
//}
//
//
//
//void RenderScene(void) {
// glClear(GL_COLOR_BUFFER_BIT);
// glClearColor(0.0, 0.0, 0.0, 0.0); // Set display-window color to black.
//
// earthRotation += earth_rotation_speed;
// moonRotation += moon_rotation_speed;
//
// /***********코드 작성하기 ***************/
// // 태양 : 빨간색의 구
// glColor3f(1.0, 0.0, 0.0);
// Draw_Circle(sun_radius);
//
// // 지구 : 초록색의 구
// // 달 : 노랑색의 구
//
// glFlush();
// glutSwapBuffers();
//}
//
//
//void main(int argc, char** argv) {
// glutInit(&argc, argv);
// glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
// glutInitWindowPosition(100, 100);
// glutInitWindowSize(Width, Height);
// glutCreateWindow("Solar System");
// init();
// glutDisplayFunc(RenderScene);
// glutIdleFunc(RenderScene);
// glutMainLoop();
//}
//
|
#ifndef ___ROBOTTHREAD_H___
#define ___ROBOTTHREAD_H___
#include <QThread>
#include <QObject>
#include <QStringList>
#include <QFile>
#include <QTextStream>
#include <stdlib.h>
#include <iostream>
#include "assert.h"
#include <ros/ros.h>
#include <ros/network.h>
#include <sensor_msgs/LaserScan.h>
#include <std_msgs/String.h>
#include <nav_msgs/Odometry.h>
#include "Shape.h"
namespace data_server {
struct LaserPoint
{
double range;
double bearing;
double px;
double py;
};
class RobotThread : public QThread {
Q_OBJECT
public:
RobotThread(int argc, char **pArgv);
virtual ~RobotThread();
bool init();
//void callback(nav_msgs::Odometry msg);
void scanCallBack(sensor_msgs::LaserScan scan);
void callback(nav_msgs::Odometry msg);
void run();
private:
int m_Init_argc;
char** m_pInit_argv;
bool m_isFirstMessage;
QList<LaserPoint> m_scanData;
void extractCurves(QList<LaserPoint> scan_data, std_msgs::Header scanTime);
void publishRunData(QList<Shape> scan);
QList<Shape> m_shapes;
double m_xPos;
double m_yPos;
double m_aPos;
ros::Subscriber scan_listener;
ros::Subscriber pose_listener;
ros::Publisher cloud_pcl;
ros::Publisher data_Output;
};
}//end namespace
#endif
|
#include <iostream>
using namespace std;
int leftrepeat(string s)
{
int res=INT_MAX,index[256];
for(int i=0;i<256;i++)
{
index[i]=-1;
}
for(int i=s.length()-1;i>=0;i--)
{
if(index[s[i]]==-1)
index[s[i]]=i;
else
res=i;
}
return ((res==INT_MAX)?-1:res);
}
int main()
{
int r;
r=leftrepeat("abccb");
cout<<r;
return 0;
}
|
#include <cstddef>
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode *res = new ListNode(0);
ListNode *pl = res;
while (head && head->next) {
pl->next = new ListNode(head->next->val);
pl = pl->next;
pl->next = new ListNode(head->val);
pl = pl->next;
head = head->next->next;
}
if (head) {
pl->next = new ListNode(head->val);
pl = pl->next;
}
return res->next;
}
};
|
#include "System.h"
#include "GPIO.h"
#include "mini_modbus_tables.h"
|
#include <iostream>
using namespace std;
#include "solution.h"
int main() {
int ival1 = 234;
int ival2 = 4421;
Solution sol;
cout << sol.subtractProductAndSum(ival1) << endl;
cout << sol.subtractProductAndSum(ival2) << endl;
return 0;
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TESTMUTABLEMESHREMESH_HPP_
#define TESTMUTABLEMESHREMESH_HPP_
#include <cxxtest/TestSuite.h>
#include <cmath>
#include "MutableMesh.hpp"
#include "TrianglesMeshReader.hpp"
#include "PetscSetupAndFinalize.hpp"
//Jonathan Shewchuk's triangle
#define REAL double
#define VOID void
#include "triangle.h"
#undef REAL
#undef VOID
//Hang Si's tetgen
#include "tetgen.h"
class TestMutableMeshRemesh : public CxxTest::TestSuite
{
public:
/**
* Test 3D remesh replaces TestOperationOfTetgenMoveNodes which called the tetgen binary directly.
*/
void TestRemesh3dMoveNodes()
{
TrianglesMeshReader<3,3> mesh_reader2("mesh/test/data/cube_1626_elements");
TetrahedralMesh<3,3> old_mesh;
old_mesh.ConstructFromMeshReader(mesh_reader2);
TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/cube_1626_elements");
MutableMesh<3,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
ChastePoint<3> point = mesh.GetNode(i)->GetPoint();
ChastePoint<3> old_mesh_point = old_mesh.GetNode(i)->GetPoint();
for (int j=0; j<3; j++)
{
if (fabs(point[j]-0.0) >1e-6 && fabs(point[j]-1.0) >1e-6)
{
point.SetCoordinate(j, point[j]+9e-2);
old_mesh_point.SetCoordinate(j, old_mesh_point[j]+9e-2);
}
}
mesh.GetNode(i)->SetPoint(point);
old_mesh.GetNode(i)->SetPoint(old_mesh_point);
}
mesh.RefreshMesh();
old_mesh.RefreshMesh();
double old_volume = mesh.GetVolume();
TS_ASSERT_DELTA(1, old_volume, 1e-7);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 375u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 1626u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 390u);
for (MutableMesh<3,3>::BoundaryNodeIterator node_iter = mesh.GetBoundaryNodeIteratorBegin();
node_iter != mesh.GetBoundaryNodeIteratorEnd();
++node_iter)
{
TS_ASSERT_EQUALS((*node_iter)->IsBoundaryNode(), true);
}
NodeMap map(mesh.GetNumNodes());
mesh.ReMesh(map);
for (MutableMesh<3,3>::BoundaryNodeIterator node_iter = mesh.GetBoundaryNodeIteratorBegin();
node_iter != mesh.GetBoundaryNodeIteratorEnd();
++node_iter)
{
TS_ASSERT_EQUALS((*node_iter)->IsBoundaryNode(), true);
}
TS_ASSERT_EQUALS(map.GetSize(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumNodes(), old_mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumBoundaryNodes(), old_mesh.GetNumBoundaryNodes());
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), old_mesh.GetNumBoundaryElements());
TS_ASSERT_EQUALS(mesh.GetNumElements()+1, old_mesh.GetNumElements());
// Test to see whether triangle/ tetgen is renumbering the nodes
for (unsigned i=0; i<mesh.GetNumNodes(); i++)
{
// The map turns out to be the identity map in this test
TS_ASSERT_EQUALS(map.GetNewIndex(i), i);
const c_vector<double, 3> node_loc1 = mesh.GetNode(map.GetNewIndex(i))->rGetLocation();
const c_vector<double, 3> node_loc2 = old_mesh.GetNode(i)->rGetLocation();
for (int j=0; j<3; j++)
{
TS_ASSERT_DELTA(node_loc1[j], node_loc2[j], 1e-6);
}
}
double new_volume = mesh.GetVolume();
TS_ASSERT_DELTA(old_volume, new_volume, 1e-7);
}
void TestRemeshWithMethod1D()
{
// Create 1D mesh
MutableMesh<1,1> mesh;
mesh.ConstructLinearMesh(10);
double area = mesh.GetVolume();
unsigned num_nodes_before = mesh.GetNumNodes();
unsigned num_elements_before = mesh.GetNumElements();
unsigned num_boundary_elements_before = mesh.GetNumBoundaryElements();
for (unsigned elem_index=0; elem_index<mesh.GetNumElements(); elem_index++)
{
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index);
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index+1);
}
for (MutableMesh<1,1>::BoundaryNodeIterator node_iter = mesh.GetBoundaryNodeIteratorBegin();
node_iter != mesh.GetBoundaryNodeIteratorEnd();
++node_iter)
{
TS_ASSERT_EQUALS((*node_iter)->IsBoundaryNode(), true);
}
// Merge two nodes
mesh.MoveMergeNode(7, 6);
for (unsigned elem_index=0; elem_index<mesh.GetNumElements(); elem_index++)
{
if (elem_index == 7)
{
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index-1);
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index+1);
}
else
{
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index);
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index+1);
}
}
for (MutableMesh<1,1>::BoundaryNodeIterator node_iter = mesh.GetBoundaryNodeIteratorBegin();
node_iter != mesh.GetBoundaryNodeIteratorEnd();
++node_iter)
{
TS_ASSERT_EQUALS((*node_iter)->IsBoundaryNode(), true);
}
TS_ASSERT_DELTA(area, mesh.GetVolume(), 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements()+1);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), mesh.GetNumNodes()+1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
NodeMap map(1);
mesh.ReMesh(map);
for (unsigned elem_index=0; elem_index<mesh.GetNumElements(); elem_index++)
{
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index);
TS_ASSERT_EQUALS(mesh.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index+1);
}
TS_ASSERT_EQUALS(map.GetSize(), mesh.GetNumNodes()+1); // one node removed during remesh
for (unsigned i=0; i<7; i++)
{
// These are unchanged
TS_ASSERT_EQUALS(map.GetNewIndex(i), i);
}
// This one has gone
TS_ASSERT(map.IsDeleted(7));
TS_ASSERT_THROWS_THIS(map.GetNewIndex(7),"Node has been deleted");
for (unsigned i=8; i<map.GetSize(); i++)
{
// These have shuffled down
TS_ASSERT_EQUALS(map.GetNewIndex(i), i-1);
}
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements());
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(),mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), num_elements_before-1);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), num_nodes_before-1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), num_boundary_elements_before);
TS_ASSERT_DELTA(mesh.GetVolume(), area, 1e-6);
// Create another mesh
MutableMesh<1,1> mesh2;
mesh2.ConstructLinearMesh(10);
TS_ASSERT_EQUALS(mesh2.GetNumElements(), 10u);
TS_ASSERT_EQUALS(mesh2.GetNumNodes(), 11u);
for (unsigned node_index=0; node_index<mesh2.GetNumNodes(); node_index++)
{
TS_ASSERT_DELTA(mesh2.GetNode(node_index)->rGetLocation()[0], (double) node_index, 1e-6);
}
for (unsigned elem_index=0; elem_index<mesh2.GetNumElements(); elem_index++)
{
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index);
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index+1);
}
// Add a node
c_vector<double,1> point;
point[0] = 2.5;
Node<1>* p_node = new Node<1>(10u, point);
unsigned new_index = mesh2.AddNode(p_node);
TS_ASSERT_EQUALS(new_index, 11u);
TS_ASSERT_DELTA(mesh2.GetNode(11u)->rGetLocation()[0], 2.5, 1e-7);
TS_ASSERT_EQUALS(mesh2.GetNumElements(), 10u);
TS_ASSERT_EQUALS(mesh2.GetNumNodes(), 12u);
for (unsigned node_index=0; node_index<mesh2.GetNumNodes(); node_index++)
{
if (node_index == 11)
{
TS_ASSERT_DELTA(mesh2.GetNode(node_index)->rGetLocation()[0], 2.5, 1e-6);
}
else
{
TS_ASSERT_DELTA(mesh2.GetNode(node_index)->rGetLocation()[0], (double) node_index, 1e-6);
}
}
for (MutableMesh<1,1>::BoundaryNodeIterator node_iter = mesh2.GetBoundaryNodeIteratorBegin();
node_iter != mesh2.GetBoundaryNodeIteratorEnd();
++node_iter)
{
TS_ASSERT_EQUALS((*node_iter)->IsBoundaryNode(), true);
}
// Now remesh and check that elements are correctly updated
mesh2.ReMesh();
TS_ASSERT_EQUALS(mesh2.GetNumElements(), 11u);
TS_ASSERT_EQUALS(mesh2.GetNumNodes(), 12u);
for (unsigned node_index=0; node_index<mesh2.GetNumNodes(); node_index++)
{
if (node_index == 11)
{
TS_ASSERT_DELTA(mesh2.GetNode(node_index)->rGetLocation()[0], 2.5, 1e-6);
}
else
{
TS_ASSERT_DELTA(mesh2.GetNode(node_index)->rGetLocation()[0], (double) node_index, 1e-6);
}
}
for (unsigned elem_index=0; elem_index<mesh2.GetNumElements(); elem_index++)
{
if (elem_index < 2)
{
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index);
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index+1);
}
else if (elem_index == 2)
{
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index);
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(1), 11u);
}
else if (elem_index == 3)
{
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(0), 11u);
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index);
}
else
{
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(0), elem_index-1);
TS_ASSERT_EQUALS(mesh2.GetElement(elem_index)->GetNodeGlobalIndex(1), elem_index);
}
}
}
void TestRemeshWithMethod2D()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_984_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double area = mesh.GetVolume();
const int node_index = 432;
const int target_index = 206;
unsigned num_nodes_before = mesh.GetNumNodes();
unsigned num_elements_before = mesh.GetNumElements();
unsigned num_boundary_elements_before = mesh.GetNumBoundaryElements();
mesh.MoveMergeNode(node_index, target_index);
TS_ASSERT_DELTA(area, mesh.GetVolume(), 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements()+2);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), mesh.GetNumNodes()+1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
for (MutableMesh<2,2>::BoundaryNodeIterator node_iter = mesh.GetBoundaryNodeIteratorBegin();
node_iter != mesh.GetBoundaryNodeIteratorEnd();
++node_iter)
{
TS_ASSERT_EQUALS((*node_iter)->IsBoundaryNode(), true);
}
NodeMap map(1);
mesh.ReMesh(map);
for (MutableMesh<2,2>::BoundaryNodeIterator node_iter = mesh.GetBoundaryNodeIteratorBegin();
node_iter != mesh.GetBoundaryNodeIteratorEnd();
++node_iter)
{
TS_ASSERT_EQUALS((*node_iter)->IsBoundaryNode(), true);
}
TS_ASSERT_EQUALS(map.GetSize(), mesh.GetNumNodes()+1);//one node removed during remesh
for (unsigned i=0; i<431; i++)
{
// These are unchanged
TS_ASSERT_EQUALS(map.GetNewIndex(i), i);
}
// This one has gone
TS_ASSERT(map.IsDeleted(432));
TS_ASSERT_THROWS_THIS(map.GetNewIndex(432),"Node has been deleted");
for (unsigned i=433; i<map.GetSize(); i++)
{
// These have shuffled down
TS_ASSERT_EQUALS(map.GetNewIndex(i), i-1);
}
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements());
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(),mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), num_elements_before-2);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), num_nodes_before-1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), num_boundary_elements_before);
TS_ASSERT_DELTA(mesh.GetVolume(), area, 1e-6);
}
void TestRemeshWithMethod3D()
{
// Create mutable tetrahedral mesh which is Delaunay
std::vector<Node<3> *> nodes;
nodes.push_back(new Node<3>(0, true, 0.0, 0.0, 0.0));
nodes.push_back(new Node<3>(1, true, 1.0, 1.0, 0.0));
nodes.push_back(new Node<3>(2, true, 1.0, 0.0, 1.0));
nodes.push_back(new Node<3>(3, true, 0.0, 1.0, 1.0));
nodes.push_back(new Node<3>(4, false, 0.5, 0.5, 0.5));
MutableMesh<3,3> mesh(nodes);
double area = mesh.GetVolume();
unsigned num_nodes_before = mesh.GetNumNodes();
unsigned num_elements_before = mesh.GetNumElements();
unsigned num_boundary_elements_before = mesh.GetNumBoundaryElements();
mesh.DeleteNode(4);
TS_ASSERT_DELTA(area, mesh.GetVolume(), 1e-6);
NodeMap map(1);
mesh.ReMesh(map);
TS_ASSERT_EQUALS(map.GetSize(), mesh.GetNumNodes()+1);//one node removed during remesh
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements());
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(),mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), num_elements_before-3);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), num_nodes_before-1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), num_boundary_elements_before);
TS_ASSERT_DELTA(mesh.GetVolume(), area, 1e-6);
mesh.DeleteNode(3);
TS_ASSERT_THROWS_THIS(mesh.ReMesh(map),"The number of nodes must exceed the spatial dimension.");
}
void TestNodeMap()
{
NodeMap map(10);
TS_ASSERT_EQUALS(map.GetSize(), 10u);
TS_ASSERT_EQUALS(map.IsIdentityMap(), true);
TS_ASSERT_EQUALS(map.GetNewIndex(1u), 1u); // This is unsafe since the contents of the map have not been set
map.ResetToIdentity();
TS_ASSERT_EQUALS(map.IsIdentityMap(), true);
map.SetNewIndex(0,1);
map.SetNewIndex(1,0);
TS_ASSERT_EQUALS(map.GetNewIndex(0), 1u);
TS_ASSERT_EQUALS(map.GetNewIndex(1), 0u);
TS_ASSERT_EQUALS(map.GetNewIndex(2), 2u);
TS_ASSERT_EQUALS(map.IsIdentityMap(), false);
map.ResetToIdentity();
map.SetDeleted(4);
TS_ASSERT_EQUALS(map.IsDeleted(4), true);
TS_ASSERT_EQUALS(map.IsDeleted(5), false);
TS_ASSERT_EQUALS(map.IsIdentityMap(), false);
}
void Test1DReMeshFailsAfterEnoughDeletions()
{
// Construct mesh
MutableMesh<1,1> mesh;
mesh.ConstructLinearMesh(2);
NodeMap map(3);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 3u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 3u);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), 2u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 2u);
mesh.ReMesh(map);
mesh.DeleteNodePriorToReMesh(2);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 3u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 2u);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), 2u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 2u);
mesh.ReMesh(map);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 2u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 2u);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), 1u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 1u);
mesh.DeleteNodePriorToReMesh(1);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 2u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 1u);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), 1u);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 1u);
TS_ASSERT_THROWS_THIS(mesh.ReMesh(map),"The number of nodes must exceed the spatial dimension.");
}
void Test2DReMeshFailsAfterEnoughDeletions()
{
MutableMesh<2,2> mesh;
mesh.ConstructRectangularMesh(1,1);
NodeMap map(1);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 4u);
mesh.ReMesh(map);
mesh.DeleteNodePriorToReMesh(3);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 3u);
mesh.ReMesh(map);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 3u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 3u);
mesh.DeleteNodePriorToReMesh(2);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), 3u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 2u);
TS_ASSERT_THROWS_THIS(mesh.ReMesh(map),"The number of nodes must exceed the spatial dimension.");
}
void TestRawTriangleLibraryCall()
{
struct triangulateio in, out;
/* Define input points. */
in.numberofpoints = 5;
in.numberofpointattributes = 0;
in.pointlist = (double *) malloc(in.numberofpoints * 2 * sizeof(double));
in.pointlist[0] = 0.0;
in.pointlist[1] = 0.0;
in.pointlist[2] = 1.0;
in.pointlist[3] = 0.0;
in.pointlist[4] = 1.0;
in.pointlist[5] = 10.0;
in.pointlist[6] = 0.0;
in.pointlist[7] = 10.0;
in.pointlist[8] = 0.5;
in.pointlist[9] = 7.0;
in.pointmarkerlist = NULL;
in.numberofsegments = 0;
in.numberofholes = 0;
in.numberofregions = 0;
out.pointlist = NULL;
out.pointattributelist = (double *) NULL;
out.pointmarkerlist = (int *) NULL;
out.trianglelist = (int *) NULL;
out.triangleattributelist = (double *) NULL;
out.edgelist = (int *) NULL;
out.edgemarkerlist = (int *) NULL;
triangulate((char*)"Qze", &in, &out, NULL);
TS_ASSERT_EQUALS(out.numberofpoints, 5);
TS_ASSERT_EQUALS(out.numberofpointattributes, 0);
TS_ASSERT_EQUALS(out.numberoftriangles, 4);
TS_ASSERT_EQUALS(out.numberofcorners, 3);
TS_ASSERT_EQUALS(out.numberoftriangleattributes, 0);
TS_ASSERT_EQUALS(out.numberofedges, 8);
// Free all allocated arrays, including those allocated by Triangle
free(in.pointlist);
free(out.pointlist);
free(out.pointattributelist);
free(out.pointmarkerlist);
free(out.trianglelist);
free(out.triangleattributelist);
free(out.edgelist);
free(out.edgemarkerlist);
}
void TestRawTetgenLibraryCall()
{
tetgen::tetgenio in, out;
in.numberofpointattributes = 0;
in.numberofpoints = 8;
in.pointlist = new REAL[in.numberofpoints * 3];//tetgenio's destructor will automatically free this.
in.pointlist[0] = 0;
in.pointlist[1] = 0;
in.pointlist[2] = 0;
in.pointlist[3] = 1;
in.pointlist[4] = 0;
in.pointlist[5] = 0;
in.pointlist[6] = 0;
in.pointlist[7] = 1;
in.pointlist[8] = 0;
in.pointlist[9] = 0;
in.pointlist[10] = 0;
in.pointlist[11] = 1;
in.pointlist[12] = 1;
in.pointlist[13] = 1;
in.pointlist[14] = 0;
in.pointlist[15] = 1;
in.pointlist[16] = 0;
in.pointlist[17] = 1;
in.pointlist[18] = 0;
in.pointlist[19] = 1;
in.pointlist[20] = 1;
in.pointlist[21] = 1;
in.pointlist[22] = 1;
in.pointlist[23] = 1;
tetgen::tetrahedralize((char*)"Q", &in, &out);
TS_ASSERT_EQUALS(out.numberofpoints, 8); // As in original
TS_ASSERT_EQUALS(out.numberofpointattributes,0);
TS_ASSERT_EQUALS(out.numberofcorners, 4); // Vertices per tet
TS_ASSERT_EQUALS(out.numberofedges, 0);
TS_ASSERT_EQUALS(out.numberoftetrahedra, 6); // Elements
TS_ASSERT_EQUALS(out.numberofedges, 0);
TS_ASSERT_EQUALS(out.numberoftrifaces, 12); // 2 triangles on each die face
}
void TestRemeshWithLibraryMethodSimple()
{
// Same data as previous 2d test
std::vector<Node<2> *> nodes;
nodes.push_back(new Node<2>(0, true, 0.0, 0.0));
nodes.push_back(new Node<2>(1, true, 1.0, 0.0));
nodes.push_back(new Node<2>(2, true, 1.0, 10.0));
nodes.push_back(new Node<2>(3, true, 0.0, 10.0));
nodes.push_back(new Node<2>(4, true, 0.5, 7.0));
MutableMesh<2,2> mesh(nodes);
TS_ASSERT_DELTA(mesh.GetVolume(), 10.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetSurfaceArea(), 22.0, 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 5u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryNodes(), 4u);
NodeMap map(1);
mesh.ReMesh(map);
TS_ASSERT_EQUALS(map.GetSize(), mesh.GetNumNodes());
TS_ASSERT_DELTA(mesh.GetVolume(), 10.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetSurfaceArea(), 22.0, 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 5u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryNodes(), 4u);
}
void TestRemeshWithLibraryMethod2D()
{
TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_984_elements");
MutableMesh<2,2> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double area = mesh.GetVolume();
const int node_index = 432;
const int target_index = 206;
unsigned num_nodes_before = mesh.GetNumNodes();
unsigned num_elements_before = mesh.GetNumElements();
unsigned num_boundary_elements_before = mesh.GetNumBoundaryElements();
mesh.MoveMergeNode(node_index, target_index);
TS_ASSERT_DELTA(area, mesh.GetVolume(), 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements()+2);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), mesh.GetNumNodes()+1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
NodeMap map(1);
mesh.ReMesh(map);
TS_ASSERT_EQUALS(map.GetSize(), mesh.GetNumNodes()+1); //one node removed during remesh
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements());
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), num_elements_before-2);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), num_nodes_before-1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), num_boundary_elements_before);
TS_ASSERT_DELTA(mesh.GetVolume(), area, 1e-6);
}
void TestRemeshWithLibraryMethod3D()
{
TrianglesMeshReader<3,3> mesh_reader("mesh/test/data/cube_136_elements");
MutableMesh<3,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
double volume = mesh.GetVolume();
const int node_index = 17;
const int target_index = 9;
unsigned num_nodes_before = mesh.GetNumNodes();
unsigned num_elements_before = mesh.GetNumElements();
unsigned num_boundary_elements_before = mesh.GetNumBoundaryElements();
mesh.MoveMergeNode(node_index, target_index);
TS_ASSERT_DELTA(volume, mesh.GetVolume(), 1e-6);
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements()+4);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), mesh.GetNumNodes()+1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements()+2);
NodeMap map(1);
mesh.ReMesh(map);
TS_ASSERT_EQUALS(map.GetSize(), mesh.GetNumNodes()+1); //one node removed during remesh
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), mesh.GetNumElements());
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), mesh.GetNumNodes());
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), mesh.GetNumBoundaryElements());
TS_ASSERT_EQUALS(mesh.GetNumAllElements(), num_elements_before-4);
TS_ASSERT_EQUALS(mesh.GetNumAllNodes(), num_nodes_before-1);
TS_ASSERT_EQUALS(mesh.GetNumAllBoundaryElements(), num_boundary_elements_before-2);
TS_ASSERT_DELTA(mesh.GetVolume(), volume, 1e-6);
}
void TestSplitLongEdges()
{
{
TrianglesMeshReader<2,3> mesh_reader("mesh/test/data/square_in_3d");
MutableMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
// Check position of nodes
TS_ASSERT_DELTA(mesh.GetNode(0)->rGetLocation()[0], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(0)->rGetLocation()[1], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(1)->rGetLocation()[0], 1.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(1)->rGetLocation()[1], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(2)->rGetLocation()[0], 1.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(2)->rGetLocation()[1], 1.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(3)->rGetLocation()[0], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(3)->rGetLocation()[1], 1.0, 1e-6);
std::vector<c_vector<unsigned, 5> > changeHistory;
// Split central edge
changeHistory = mesh.SplitLongEdges(1.1);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 4u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 5u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 4u);
// Check position of new node
TS_ASSERT_DELTA(mesh.GetNode(4)->rGetLocation()[0], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(4)->rGetLocation()[1], 0.5, 1e-6);
// Check Elements
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(0), 0u);
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(1), 1u);
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(2), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(1)->GetNodeGlobalIndex(0), 0u);
TS_ASSERT_EQUALS(mesh.GetElement(1)->GetNodeGlobalIndex(1), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(1)->GetNodeGlobalIndex(2), 3u);
TS_ASSERT_EQUALS(mesh.GetElement(2)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(2)->GetNodeGlobalIndex(1), 1u);
TS_ASSERT_EQUALS(mesh.GetElement(2)->GetNodeGlobalIndex(2), 2u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(1), 2u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(2), 3u);
// Check changeHistory
TS_ASSERT_EQUALS(changeHistory.size(), 1u);
TS_ASSERT_EQUALS(changeHistory[0][0], 4u);
TS_ASSERT_EQUALS(changeHistory[0][1], 0u);
TS_ASSERT_EQUALS(changeHistory[0][2], 2u);
// Split 4 sides
changeHistory = mesh.SplitLongEdges(0.9);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 8u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 9u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 4u); // todo should be 8
// Check position of new nodes
TS_ASSERT_DELTA(mesh.GetNode(5)->rGetLocation()[0], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(5)->rGetLocation()[1], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(6)->rGetLocation()[0], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(6)->rGetLocation()[1], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(7)->rGetLocation()[0], 1.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(7)->rGetLocation()[1], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(8)->rGetLocation()[0], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(8)->rGetLocation()[1], 1.0, 1e-6);
// Check Elements
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(0), 0u);
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(1), 5u);
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(2), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(1)->GetNodeGlobalIndex(0), 0u);
TS_ASSERT_EQUALS(mesh.GetElement(1)->GetNodeGlobalIndex(1), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(1)->GetNodeGlobalIndex(2), 6u);
TS_ASSERT_EQUALS(mesh.GetElement(2)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(2)->GetNodeGlobalIndex(1), 1u);
TS_ASSERT_EQUALS(mesh.GetElement(2)->GetNodeGlobalIndex(2), 7u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(1), 2u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(2), 8u);
TS_ASSERT_EQUALS(mesh.GetElement(4)->GetNodeGlobalIndex(0), 5u);
TS_ASSERT_EQUALS(mesh.GetElement(4)->GetNodeGlobalIndex(1), 1u);
TS_ASSERT_EQUALS(mesh.GetElement(4)->GetNodeGlobalIndex(2), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(5)->GetNodeGlobalIndex(0), 6u);
TS_ASSERT_EQUALS(mesh.GetElement(5)->GetNodeGlobalIndex(1), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(5)->GetNodeGlobalIndex(2), 3u);
TS_ASSERT_EQUALS(mesh.GetElement(6)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(6)->GetNodeGlobalIndex(1), 7u);
TS_ASSERT_EQUALS(mesh.GetElement(6)->GetNodeGlobalIndex(2), 2u);
TS_ASSERT_EQUALS(mesh.GetElement(7)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(7)->GetNodeGlobalIndex(1), 8u);
TS_ASSERT_EQUALS(mesh.GetElement(7)->GetNodeGlobalIndex(2), 3u);
// Check changeHistory
TS_ASSERT_EQUALS(changeHistory.size(), 4u);
TS_ASSERT_EQUALS(changeHistory[0][0], 5u);
TS_ASSERT_EQUALS(changeHistory[0][1], 0u);
TS_ASSERT_EQUALS(changeHistory[0][2], 1u);
TS_ASSERT_EQUALS(changeHistory[1][0], 6u);
TS_ASSERT_EQUALS(changeHistory[1][1], 0u);
TS_ASSERT_EQUALS(changeHistory[1][2], 3u);
TS_ASSERT_EQUALS(changeHistory[2][0], 7u);
TS_ASSERT_EQUALS(changeHistory[2][1], 1u);
TS_ASSERT_EQUALS(changeHistory[2][2], 2u);
TS_ASSERT_EQUALS(changeHistory[3][0], 8u);
TS_ASSERT_EQUALS(changeHistory[3][1], 2u);
TS_ASSERT_EQUALS(changeHistory[3][2], 3u);
}
{
// Here we split all sides at once and because of this we get a different resulting mesh
TrianglesMeshReader<2,3> mesh_reader("mesh/test/data/square_in_3d");
MutableMesh<2,3> mesh;
mesh.ConstructFromMeshReader(mesh_reader);
std::vector<c_vector<unsigned, 5> > changeHistory;
// Split ALL sides
changeHistory = mesh.SplitLongEdges(0.9);
TS_ASSERT_EQUALS(mesh.GetNumElements(), 8u);
TS_ASSERT_EQUALS(mesh.GetNumNodes(), 9u);
TS_ASSERT_EQUALS(mesh.GetNumBoundaryElements(), 4u); // todo should be 8
// Check position of new nodes
TS_ASSERT_DELTA(mesh.GetNode(4)->rGetLocation()[0], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(4)->rGetLocation()[1], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(5)->rGetLocation()[0], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(5)->rGetLocation()[1], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(6)->rGetLocation()[0], 0.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(6)->rGetLocation()[1], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(7)->rGetLocation()[0], 1.0, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(7)->rGetLocation()[1], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(8)->rGetLocation()[0], 0.5, 1e-6);
TS_ASSERT_DELTA(mesh.GetNode(8)->rGetLocation()[1], 1.0, 1e-6);
// Check some Elements
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(0), 0u);
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(1), 5u);
TS_ASSERT_EQUALS(mesh.GetElement(0)->GetNodeGlobalIndex(2), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(1), 2u);
TS_ASSERT_EQUALS(mesh.GetElement(3)->GetNodeGlobalIndex(2), 8u);
TS_ASSERT_EQUALS(mesh.GetElement(7)->GetNodeGlobalIndex(0), 4u);
TS_ASSERT_EQUALS(mesh.GetElement(7)->GetNodeGlobalIndex(1), 8u);
TS_ASSERT_EQUALS(mesh.GetElement(7)->GetNodeGlobalIndex(2), 3u);
// Check changeHistory
TS_ASSERT_EQUALS(changeHistory.size(), 5u);
TS_ASSERT_EQUALS(changeHistory[0][0], 4u);
TS_ASSERT_EQUALS(changeHistory[0][1], 0u);
TS_ASSERT_EQUALS(changeHistory[0][2], 2u);
TS_ASSERT_EQUALS(changeHistory[0][3], 1u);
TS_ASSERT_EQUALS(changeHistory[0][4], 3u);
TS_ASSERT_EQUALS(changeHistory[1][0], 5u);
TS_ASSERT_EQUALS(changeHistory[1][1], 0u);
TS_ASSERT_EQUALS(changeHistory[1][2], 1u);
TS_ASSERT_EQUALS(changeHistory[1][3], 4u);
TS_ASSERT_EQUALS(changeHistory[1][4], UNSIGNED_UNSET);
TS_ASSERT_EQUALS(changeHistory[2][0], 6u);
TS_ASSERT_EQUALS(changeHistory[2][1], 0u);
TS_ASSERT_EQUALS(changeHistory[2][2], 3u);
TS_ASSERT_EQUALS(changeHistory[2][3], 4u);
TS_ASSERT_EQUALS(changeHistory[2][4], UNSIGNED_UNSET);
TS_ASSERT_EQUALS(changeHistory[3][0], 7u);
TS_ASSERT_EQUALS(changeHistory[3][1], 1u);
TS_ASSERT_EQUALS(changeHistory[3][2], 2u);
TS_ASSERT_EQUALS(changeHistory[3][3], 4u);
TS_ASSERT_EQUALS(changeHistory[3][4], UNSIGNED_UNSET);
TS_ASSERT_EQUALS(changeHistory[4][0], 8u);
TS_ASSERT_EQUALS(changeHistory[4][1], 2u);
TS_ASSERT_EQUALS(changeHistory[4][2], 3u);
TS_ASSERT_EQUALS(changeHistory[4][3], 4u);
TS_ASSERT_EQUALS(changeHistory[4][4], UNSIGNED_UNSET);
}
}
};
#endif /*TESTMUTABLEMESHREMESH_HPP_*/
|
#include "헤더2.h"
int myValue = 100;
void add() {
myValue++;
}
|
#ifndef __ENTITY_H__
#define __ENTITY_H__
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC;
class Entity: public cocos2d::CCNode
{
public:
Entity();
~Entity();
CCSprite* getSprite(); /*get sprite object*/
void setSpriteAsNULL(); /*set sprite object*/
void bindSprite(CCSprite* sprite); /*bind sprite object*/
private:
CCSprite* m_sprite;
};
#endif // __ENTITY_H__ |
#include "shadermanager.h"
#include "d3dclass.h"
ShaderManager::ShaderManager()
{
phongShadering = 0;
lightShader = 0;
}
ShaderManager::ShaderManager(const ShaderManager&)
{
}
ShaderManager::~ShaderManager()
{
}
bool ShaderManager::InitializeAll(ID3D11Device* device, HWND hwnd)
{
bool result;
phongShadering = new PhongShadering();
result = phongShadering->Initialize(device, hwnd);
if (!phongShadering) {
return result;
}
lightShader = new LightShaderClass();
result = lightShader->Initialize(device, hwnd);
if (!lightShader) {
return result;
}
return result;
}
bool ShaderManager::ShutDownAll()
{
phongShadering->Shutdown();
lightShader->Shutdown();
return true;
}
bool ShaderManager::RenderLightShader(ID3D11DeviceContext* context, int indexCount, D3DXMATRIX worldMatrix, D3DXMATRIX viewMatrix,
D3DXMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, D3DXVECTOR4 lightColors[], D3DXVECTOR4 lightPositions[])
{
return lightShader->Render(context, indexCount, worldMatrix, viewMatrix, projectionMatrix, texture, lightColors, lightPositions);
}
bool ShaderManager::RenderPhongShader(RenderData* renderData)
{
return phongShadering->Render(renderData);
} |
#include "core/InputManager.h"
#include "core/Debug.h"
#include "io/AInput.h"
using namespace de;
using namespace de::io;
InputManager* InputManager::sInstance = nullptr;
void InputManager::init()
{
sInstance = new InputManager();
}
//***********************************
void InputManager::update()
{
std::map<std::string, io::AInput*>::iterator it = sInstance->mInputs.begin();
while(it != sInstance->mInputs.end())
{
it->second->update();
it++;
}
}
//***********************************
io::AInput* InputManager::getInputFromType(const std::string& pType)
{
std::map<std::string, io::AInput*>::iterator it = sInstance->mInputs.begin();
while(it != sInstance->mInputs.end())
{
if(it->second->mType == pType)
{
return it->second;
}
it++;
}
return nullptr;
}
//***********************************
io::AInput* InputManager::getInputFromName(const std::string& pName)
{
if(sInstance->mInputs.count(pName) > 0)
return sInstance->mInputs[pName];
return nullptr;
}
//***********************************
io::AInput* InputManager::addInputSource(io::AInput* pInput)
{
if(sInstance->mInputs.count(pInput->mName) > 0)
{
Debug::Log(std::string("There is already an input called : ") + pInput->mName + ". This input wasn't added to the list.");
return pInput;
}
sInstance->mInputs[pInput->mName] = pInput;
return pInput;
}
//***********************************
void InputManager::removeInputSource(io::AInput* pInput)
{
if(sInstance->mInputs.count(pInput->mName) > 0)
{
sInstance->mInputs.erase(pInput->mName);
}
} |
#pragma once
class MultiplicationResult
{
public:
MultiplicationResult(unsigned row, unsigned column, unsigned result);
~MultiplicationResult();
unsigned row, column, result;
};
|
/*Event.cpp
Event
copyright Vixac Ltd. All Rights Reserved
*/
#include "Event.h"
#include "Name.h"
#include "CommentThread.h"
#include "VoteList.h"
#include <iostream>
#include <string>
namespace VI = vixac;
namespace IN = VI::inout;
IN::Event::Event(IN::NodeStore * store)
:IN::Phenode(store->newNode(), store),
isValid_(true)
{
{
IN::Name name(store);
name.beTheNameFor(this->root()->nodeId());
}
//TODO generalise this, much?
{
IN::CommentThread thread(store);
IN::TieType mainChatType("main_chat");
store->addTie(this->root()->nodeId(), IN::Tie(mainChatType, thread.root()->nodeId(), store->now()));
}
{
IN::VoteList whatList(store);
IN::TieType whatListType("what_list");
store->addTie(this->root()->nodeId(), IN::Tie(whatListType, whatList.root()->nodeId(), store->now()));
}
{
IN::VoteList whereList(store);
IN::TieType whereListType("where_list");
store->addTie(this->root()->nodeId(), IN::Tie(whereListType, whereList.root()->nodeId(), store->now()));
}
{
IN::VoteList whatList(store);
IN::TieType whatListType("when_list");
store->addTie(this->root()->nodeId(), IN::Tie(whatListType, whatList.root()->nodeId(), store->now()));
}
}
//TODO use it i guess
IN::Event::Event(IN::NodeId existingId, IN::NodeStore * store)
: IN::Phenode(store->getNode(existingId), store),
isValid_(true)
{
}
IN::Node * IN::Event::getTitleNode() const
{
return store_->getNode(this->root()->getPrimary(IN::TieType("name")));
}
void IN::Event::setTitle(std::string const& title)
{
IN::Name name(this->root()->getPrimary(IN::TieType("name")), store_);
name.setName(title);
}
std::string IN::Event::title() const
{
return IN::Name(this->root()->getPrimary(IN::TieType("name")), store_).name();
}
IN::Node * IN::Event::getChatNode() const
{
return store_->getNode(this->root()->getPrimary(IN::TieType("main_chat")));
}
IN::Node * IN::Event::getPeopleNode() const
{
return NULL;
}
IN::Node * IN::Event::getDateSpaceSuggestionNode() const
{
return NULL;
}
IN::Node * IN::Event::getWhatList() const
{
return store_->getNode(this->root()->getPrimary(IN::TieType("what_list")));
}
IN::Node * IN::Event::getWhereList() const
{
return store_->getNode(this->root()->getPrimary(IN::TieType("where_list")));
}
IN::Node * IN::Event::getWhenList() const
{
return store_->getNode(this->root()->getPrimary(IN::TieType("when_list")));
}
IN::Node * IN::Event::getNullableWhatNode() const
{
return (IN::VoteList(store_->getNode(this->root()->getPrimary(IN::TieType("what_list")))->nodeId(), store_).topVoteeNullable());
}
|
#include<bits/stdc++.h>
using namespace std;
int sum(int n)
{
int sum1=0;
while(n>0)
{
sum1+=n%10;
n/=10;
}
return sum1;
}
int main()
{
int a;
cin>>a;
for(int i=a;;i++)
{
if(sum(i)%4==0)
{
cout<<i<<"\n";
break;
}
}
}
|
#include "iostream"
#include "cmath"
#include "fstream"
#include "string.h"
#include "operatii.h"
#include "stdlib.h"
using namespace std;
ifstream p("prior.txt");
int tipOperator;
float opd[100];
int lung,topOpr=0,topOpd=0,ok=0;
struct stivaOperatori{
char c[10]; }opr[100];
//returneaza prioritatea operatorului o utilizand fisierul p
int prioritate(char o[10],int i)
{
char s[100],*q;
p.clear();
p.seekg(0);
while(!p.eof())
{
p.getline(s,100);
q=strstr(s,o);
if(q!=NULL && *(q-1)==' ' && *(q+strlen(o))==' ' )
return int(s[0]-48);
}
cout<<"Eroare de sintaxa: "<<o<<" de pe pozitia "<<i-strlen(o)+1<<" nu reprezinta un operand sau un operator.";
exit(0);
}
float aplicOper(float termen1,float termen2,char o[10])
{
if(strcmp(o,"(")==0||strcmp(o,")")==0) return termen1;
//operatori binari
if(strcmp(o,"+")==0) return adunare(termen1,termen2);
if(strcmp(o,"-")==0) return diferenta(termen1,termen2);
if(strcmp(o,"*")==0) return inmultire(termen1,termen2);
if(strcmp(o,"/")==0) return impartire(termen1,termen2);
if(strcmp(o,"mod")==0) return int(termen1)%int(termen2);
if(strcmp(o,"=")==0) return termen1==termen2;
if(strcmp(o,"#")==0) return !(termen1==termen2);
if(strcmp(o,">=")==0) return termen1>=termen2;
if(strcmp(o,"<=")==0) return termen1<=termen2;
if(strcmp(o,">")==0) return termen1>termen2;
if(strcmp(o,"<")==0) return termen1<termen2;
if(strcmp(o,"and")==0) return termen1&&termen2;
if(strcmp(o,"or")==0) return termen1||termen2;
if(strcmp(o,"xor")==0) return (termen1!=termen2)&&(termen1==0||termen2==0);
if(strcmp(o,"min")==0) return min(termen1,termen2);
if(strcmp(o,"max")==0) return max(termen1,termen2);
if(strcmp(o,"^")==0) return ridicare_la_putere(termen1,termen2);
//operatori unari
tipOperator=1;
if(strcmp(o,"sin")==0) return sin(termen2);
if(strcmp(o,"cos")==0) return cos(termen2);
if(strcmp(o,"tan")==0) return tangenta(termen2);
if(strcmp(o,"cot")==0) return cotangenta(termen2);
if(strcmp(o,"asin")==0) return arcsin(termen2);
if(strcmp(o,"acos")==0) return arccos(termen2);
if(strcmp(o,"atan")==0) return atan(termen2);
if(strcmp(o,"acot")==0) return PI/2-atan(termen2);
if(strcmp(o,"ln")==0) return logaritm(termen2);
if(strcmp(o,"sqrt")==0) return radical(termen2);
if(strcmp(o,"abs")==0) return abs(termen2);
if(strcmp(o,"floor")==0) return floor(termen2);
if(strcmp(o,"ceil")==0) return ceil(termen2);
if(strcmp(o,"round")==0) return round(termen2);
if(strcmp(o,"exp")==0) return exponentiala(termen2);
}
//aplica operatorul din varful stivei de operatori pe operanzi
void aplicaOpTop(int i)
{
float rez;
tipOperator=2;
if(topOpd>1)
rez=aplicOper(opd[topOpd-1],opd[topOpd],opr[topOpr].c);
else
{
rez=aplicOper(0,opd[topOpd],opr[topOpr].c);
if(tipOperator==2)
{
if(opr[topOpr].c[0]!='(')
{
cout<<"Expresie gresita. Operatorul de pe pozitia "<<i-1<<" necesita mai multe variabile/constante";
exit(0);
}
if (opr[topOpr].c[0]=='(')
{
cout<<"Expresie gresita. Este nevoie de mai multe paranteze.";
exit(0);
}
}
}
topOpd--;
topOpr--;
if(tipOperator==2)
topOpd--;
topOpd++;
opd[topOpd]=rez;
}
/* opr stiva operatorilor cu topOpr
opd stiva operanzilor cu topOpd
*/
//functia comp verifica daca incepand de pe pozitia i se gaseste numele unei variabile
bool comp(char v[25],char fun[100], int &i)
{
int j;
if(lung<i+strlen(v)) return 0;
for(j=i; j<strlen(v)+i; j++) if(v[j-i]!=fun[j]) return 0;
if(j<lung && ((fun[j]>='0' && fun[j]<='9') || (fun[j]>='a' && fun[j]<='z') || (fun[j]>='A' && fun[j]<='Z'))) return 0;
i=i+strlen(v)-1;
return 1;
}
float prelucrare(int nrVal, char v1[25],char v2[25],char fct[100],float val1,float val2)
{
int i,j,par[100],topPar=-1;
char o[10];
lung=strlen(fct);
strcpy(opr[0].c,"(");
topOpd=0;
topOpr=0;
i=0;
do
{
while(i<lung&&topOpr>=0)
{ //adaugam in stiva cu paranteze daca este cazul
if(i!=lung-1)
{
if(fct[i]=='(')
{
topPar++;
par[topPar]=i;
}
else
{
if(fct[i]==')')
topPar--;
if(topPar<-1)
{
cout<<"Eroare de sintaxa.Sunt mai multe paranteze inchise decat deschise, prima in plus fiind pe pozitia "<<i;
exit(0);
}
}
}
//verificam daca este inchidere de paranteza
if(fct[i]==')')
{
while(strcmp(opr[topOpr].c,"(")!=0)
aplicaOpTop(i);
topOpr--;
}
//verificam daca e operand si adaugam in stiva opd valorile pt operanzi
else if(comp(v1,fct,i))
{
topOpd++;
opd[topOpd]=val1;
}
else if(nrVal==2&& comp(v2,fct,i))
{
topOpd++;
opd[topOpd]=val2;
}
//verificam daca e numar si adougam valoarea in stiva de operanzi
else if(fct[i]>='0'&&fct[i]<='9')
{
topOpd++;
float num=0,num2=0,pow=1;
while (fct[i]>='0'&& fct[i]<='9' && i<lung)
{
num=num*10+fct[i]-'0';
i++;
}
if(fct[i]=='.')
{
i++;
while (fct[i]>='0'&& fct[i]<='9' && i<lung)
{
num2=num2*10+fct[i]-'0';
i++;
pow*=10;
}
num=num+num2/pow;
}
i--;
opd[topOpd]=num;
}
//daca e operator updatam stiva op
else
{
//verificam daca avem operator de tip sin,cos,sqrt,tg,etc.
o[0]=fct[i];
//verificam daca intalnim numar cu semn
if((o[0]=='+' || o[0]=='-') && (fct[i-1]=='(' || i==0))
opd[++topOpd]=0;
j=1;
if(fct[i]>='a'&&fct[i]<='z')
{
ok=1;
while(ok==1&&i<lung)
{
i++;
if(fct[i]>='a'&&fct[i]<='z')
{
o[j]=fct[i];
j++;
}
else ok=0;
}
i--;
}
if((fct[i]=='>'||fct[i]=='<')&&fct[i+1]=='='&&i+1<lung)
{
o[j]='=';
i++;
j++;
}
o[j]=NULL;
if(o[0]!=' ')
{
//in o stocam valoarea operatorului curent
if(prioritate(o,i)>prioritate(opr[topOpr].c,i)||strcmp(o,"(")==0)
{
//daca prioritatea operatorului curent > proritatea operatorului din varful stivei atunci il putem adauga in stiva
//la fel si daca avem deschidere de paranteza
topOpr++;
strcpy(opr[topOpr].c,o);
}
else
{
//altfel trebuie aplicat operatorul din varful stivei
while(prioritate(o,i)<=prioritate(opr[topOpr].c,i)&&topOpr>0)
aplicaOpTop(i);
topOpr++;
strcpy(opr[topOpr].c,o);
}
}
}
i++;
}
if(topOpr>0) aplicaOpTop(i);
} while(topOpr>0);
if(topPar>-1)
{
cout<<"Eroare de sintaxa.Sunt mai multe paranteze deschise decat inchise, ultima in plus fiind pe pozitia "<<par[topPar];
exit(0);
}
if(opd[topOpd]>inf) opd[topOpd]=inf;
if(opd[topOpd]<-inf) opd[topOpd]=-inf;
return opd[topOpd];
}
/*citirea datelor de la tastatura
nrVal -numarul de variabile (1 sau 2)
v1,v2-numele variabilelor
val1,val2-valorile variabilelor v1,v2
*/
void verifica_nume_variabila (string &v)
{
bool ok=0;
while(!ok)
{
ok=1;
if(v.length()>20)
{
cout<<"Numele variabilei este prea lung. Va rugam indroduceti alt nume: ";
cin>>v;
ok=0;
}
else if(v[0]>='0' && v[0]<='9')
{
cout<<"Numele variabilei nu poate incepe cu o cifra. Va rugam introduceti alt nume: ";
cin>>v;
ok=0;
}
else
{
for(int i=0; i<v.length(); i++)
{
if((v[i]<'0'||v[i]>'9')&&(v[i]<'a' || v[i]>'z') && (v[i]<'A' || v[i]>'Z'))
{
cout<<"Numele variabilei poate contine doar litere si cifre. Va rugam introduceti alt nume: ";
cin>>v;
ok=0;
i=v.length();
}
}
}
}
}
void verifica_interval (float &val1, float &val2)
{
bool ok=0;
while(ok==0)
{
ok=1;
if(val1>val2)
{
cout<<"Interval gresit. Capatul stang al intervalului trebuie sa fie mai mic decat cel drept.\nVa rugam introduceti alte doua valori:";
cin>>val1>>val2;
ok=0;
}
}
}
void verifica_nr_pcte (int &n)
{
while(n<=0)
{
cout<<"Numarul de puncte trebuie sa fie un numar pozitiv. Va rugam introduceti alt numar: ";
cin>>n;
}
}
float precizie (float a, float b, int nr)
{
if(nr==1) return 0;
else return (b-a)/(nr-1);
}
struct sol
{
float fun[5000];
};
sol eval_citire()
{
sol vec;
int nrVal=0;
int l;
string v;
char v1[25],v2[25],fct[100];
float val1,val2, val3, val4;
while(nrVal!=1 && nrVal!=2)
{
cout<<"Dati numarul de variabile (1 sau 2):";
cin>>nrVal;
}
cout<<"Dati numele variabilei 1:";
cin>>v;
verifica_nume_variabila(v);
for(l=0; l<v.length(); l++) v1[l]=v[l];
v1[v.length()]='\0';
if(nrVal==2)
{
cout<<"Dati numele variabilei 2:";
cin>>v;
verifica_nume_variabila(v);
for(l=0; l<v.length(); l++) v2[l]=v[l];
v2[v.length()]='\0';
}
cout<<"Dati functia:";
cin.get();
cin.get(fct,100);
cout<<"Dati intervalul de valori pentru "<<v1<<". Introduceti doua valori pentru interval: ";
cin>>val1>>val2;
verifica_interval(val1,val2);
if(nrVal==2)
{
cout<<"Dati intervalul de valori pentru "<<v2<<". Introduceti doua valori pentru interval: ";
cin>>val3>>val4;
verifica_interval(val3,val4);
}
int nr_puncte;
cout<<"Dati numarul de puncte: ";
cin>>nr_puncte;
verifica_nr_pcte(nr_puncte);
float precizie1, precizie2,i,j;
int lung;
lung=strlen(fct);
fct[lung]=')';
lung++;
fct[lung]='\0';
vec.fun[0]=nr_puncte;
int k;
precizie1=precizie(val1,val2,nr_puncte);
if(nrVal==1)
{
for(k=1, i=val1; k<=nr_puncte; i+=precizie1,k++)
{
vec.fun[k]=prelucrare(nrVal,v1,v2,fct,i,0);
cout<<k<<". f("<<i<<") = "<<vec.fun[k]<<endl;
topOpr=0;
topOpd=0;
}
}
else
{
precizie2=precizie(val3,val4,nr_puncte);
for(k=1, i=val1,j=val3; k<=nr_puncte; i+=precizie1,j+=precizie2,k++)
{
vec.fun[k]=prelucrare(nrVal,v1,v2,fct,i,j);
cout<<k<<". f("<<i<<","<<j<<") = "<<vec.fun[k]<<endl;
topOpr=0;
topOpd=0;
}
}
}
int main()
{
sol valori_functie;
valori_functie=eval_citire();
return 0;
}
|
#include "stdafx.h"
#include "RBoneHierarchy.h"
bool RBone::Access(AAccessor& Accessor) {
__super::Access(Accessor);
Accessor << BoneName;
Accessor << TM;
Accessor << InvTM;
Accessor << BoneIndex;
Accessor << SkinBoneIndex;
Accessor << ParentIndex;
return true;
}
bool RBoneHierarchy::Access(AAccessor& Accessor) {
__super::Access(Accessor);
Accessor << Bones;
return true;
}
RBone* RBoneHierarchy::FindBone(TString& name) {
for (unsigned int i = 0; i < Bones.Size(); ++i) {
if (Bones(i)->BoneName == name) {
return Bones(i);
}
}
return 0;
}
|
#ifndef COMPLEMENTARYFILTER_H
#define COMPLEMENTARYFILTER_H
class ComplementaryFilter
{
public:
explicit ComplementaryFilter();
explicit ComplementaryFilter(double coefficient);
void setCoefficient(double coefficient);
double process(double accel, double gyro);
private:
double m_coefficient = 0.0;
double m_prevoiusResult = 0.0;
};
#endif // COMPLEMENTARYFILTER_H
|
#include "..\inc\exec.h"
inline void lui(RV32_reg rd, uint32_t imm)
{
*(RV32_REG_BASE + rd) = (uint32_t)hart.pc + imm;
}
inline void auipc(RV32_reg rd, uint32_t imm)
{
*(RV32_REG_BASE + rd) = imm;
}
inline void jal(RV32_reg rd, uint32_t imm)
{
uint32_t x = imm >> 21;
uint32_t y = ((x << 21) ^ imm) >> 12;
uint32_t offset = x * y;
*(RV32_REG_BASE + rd) = (uint32_t)hart.pc + 4;
hart.pc = (uint32_t *)((uint32_t)hart.pc + offset);
}
inline void jalr(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void beq(uint32_t imm, RV32_reg rs1, RV32_reg rs2);
inline void bne(uint32_t imm, RV32_reg rs1, RV32_reg rs2);
inline void blt(uint32_t imm, RV32_reg rs1, RV32_reg rs2);
inline void bge(uint32_t imm, RV32_reg rs1, RV32_reg rs2);
inline void bltu(uint32_t imm, RV32_reg rs1, RV32_reg rs2);
inline void bgeu(uint32_t imm, RV32_reg rs1, RV32_reg rs2);
inline void lb(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void lh(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void lw(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void lbu(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void lhu(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void sb(RV32_reg rs1, RV32_reg rs2, uint32_t imm);
inline void sh(RV32_reg rs1, RV32_reg rs2, uint32_t imm);
inline void sw(RV32_reg rs1, RV32_reg rs2, uint32_t imm);
inline void addi(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void slti(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void sltiu(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void xori(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void ori(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void andi(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void slli(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void srli(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void srai(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void add(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void sub(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void sll(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void slt(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void sltu(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void xor(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void srl(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void sra(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void or (RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void and(RV32_reg rd, RV32_reg rs1, RV32_reg rs2);
inline void fence(uint32_t imm);
inline void fence_i(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void ecall(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void ebreak(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void csrrw(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void csrrs(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void csrrc(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void csrrwi(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void csrrsi(RV32_reg rd, RV32_reg rs1, uint32_t imm);
inline void csrrci(RV32_reg rd, RV32_reg rs1, uint32_t imm); |
#include <stdio.h>
#include <iostream>
#include <windows.h>
using namespace std;
void main()
{
#define n 1000
int g = 0;
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
char s[n];
puts("Введите строку (после окончания ввода нажмите ENTER): ");
gets_s(s);
g = strlen(s);
for (g; g != -1; g--)
{
cout <<s[g];
}
}
|
/**
* Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved.
*
*
* 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 <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <multimedia/webrtc/video_decode_plugin.h>
#include "native_surface_help.h"
//using namespace YunOS;
#ifndef MM_LOG_OUTPUT_V
#define MM_LOG_OUTPUT_V
#endif
#include "multimedia/mm_debug.h"
MM_LOG_DEFINE_MODULE_NAME("webrtc_dec_test");
using namespace woogeen::base;
using namespace YUNOS_MM;
static const float ENC_FRAMERATE = 25.0;
static const int ENC_INTERVAL = 1000000 / ENC_FRAMERATE;
static const char * ENC_FILE_NAME = "/data/webrtc_enc.dump";
static woogeen::base::VideoDecoderInterface* s_g_decoder = NULL;
WindowSurface* ws = NULL;
uint32_t g_surface_width = 1280;
uint32_t g_surface_height = 720;
#define DO_NOT_CREATE_SURFACE 1
static bool createDecoder()
{
MMLOGI("+\n");
s_g_decoder = VideoDecodePlugin::create(ws);
if (!s_g_decoder) {
MMLOGE("failed to create decoder\n");
return false;
}
if (!s_g_decoder->InitDecodeContext(woogeen::base::MediaCodec::H264)) {
MMLOGE("failed to InitDecodeContext\n");
return false;
}
MMLOGI("+\n");
return true;
}
static void destroyDecoder()
{
MMLOGI("+\n");
if (!s_g_decoder) {
MMLOGI("not created\n");
return;
}
s_g_decoder->Release();
VideoDecodePlugin::destroy(s_g_decoder);
s_g_decoder = NULL;
MMLOGI("-\n");
}
static bool createSurface()
{
MMLOGI("+\n");
#if DO_NOT_CREATE_SURFACE
return true;
#else
NativeSurfaceType surfaceType = NST_SimpleWindow;
ws = createSimpleSurface(ENC_WIDTH, ENC_HEIGHT);
//WINDOW_API(set_buffers_offset)(ws, 0, 0);
//ret = WINDOW_API(set_scaling_mode)(ws, SCALING_MODE_PREF(SCALE_TO_WINDOW));
MMLOGI("-\n");
return ws != NULL;
#endif
}
static void destroySurface()
{
#if !DO_NOT_CREATE_SURFACE
destroySimpleSurface(ws);
ws = NULL;
#endif
}
class VideoDecodeFrame : public woogeen::base::VideoFrame {
public:
VideoDecodeFrame() {}
virtual ~VideoDecodeFrame() {}
virtual bool CleanUp();
};
bool VideoDecodeFrame::CleanUp()
{
uint8_t* data = NULL;
size_t data_size = 0;
int64_t time_stamp = -1;
static int releaseFrameCount = 0;
if (GetFrameInfo(data, data_size, time_stamp)) {
DEBUG("releaseFrameCount: %03d, data: %p, data_size: %zu, time_stamp: %" PRId64, releaseFrameCount, data, data_size, time_stamp);
free(data);
releaseFrameCount++;
}
SetFrameInfo(NULL, 0, -1);
return true;
}
int main(int argc, char * argv[])
{
MMLOGI("hello webrtc plugins\n");
FILE * f = NULL;
int32_t frameCount;
if (!createSurface()) {
goto out;
}
if (!createDecoder()) {
goto out;
}
MMLOGI("extract frame\n");
f = fopen(ENC_FILE_NAME, "rb");
if (!f) {
MMLOGE("Failed to open %s\n", ENC_FILE_NAME);
goto out;
}
if (fread(&frameCount, 1, 4, f) != 4) {
MMLOGE("failed to read\n");
goto out;
}
MMLOGI("frame count: %d\n", frameCount);
for (int32_t i = 0; i < frameCount; ++i) {
size_t frameSize;
uint8_t * frameBuf;
bool ret;
int64_t timeStamp;
int32_t isKeyFrame;
if (fread(&frameSize, 1, 4, f) != 4) {
MMLOGE("failed to read framesize\n");
goto out;
}
if (fread(&timeStamp, 1, 8, f) != 8) {
MMLOGE("failed to read timeStamp\n");
goto out;
}
if (fread(&isKeyFrame, 1, 4, f) != 4) {
MMLOGE("failed to read timeStamp\n");
goto out;
}
MMLOGI("size: %zu, ts: %" PRId64 "\n", frameSize, timeStamp);
frameBuf = (uint8_t*)malloc(frameSize);
if (!frameBuf)
goto out;
if (fread(frameBuf, 1, frameSize, f) != frameSize) {
MMLOGE("failed to read\n");
free(frameBuf);
frameBuf = NULL;
goto out;
}
hexDump(frameBuf, 64, 32);
VideoDecodeFrame *frame = new VideoDecodeFrame();
DEBUG("i: %03d, frame: %p, frameBuf: %p", i, frame, frameBuf);
if (frame && frame->SetFrameInfo(frameBuf, frameSize, timeStamp) ){
if (isKeyFrame)
frame->SetFlag(woogeen::base::VideoFrame::VFF_KeyFrame);
ret = s_g_decoder->OnFrame(frame);
MMLOGV("dec ret: %d\n", ret);
}
frame = NULL;
usleep(ENC_INTERVAL);
timeStamp += ENC_INTERVAL;
}
out:
destroyDecoder();
destroySurface();
if (f) {
fclose(f);
}
MMLOGI("bye\n");
return 0;
}
|
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n;
int c[10] = { 0 };
cin >> n;
while (1) {
c[n % 10]++;
if (n / 10 == 0) break;
n /= 10;
}
int m = 0;
int num = (c[6] + c[9] + 1) / 2;
for (int i = 0; i <= 9; i++) {
if(i!=6 && i!=9) m = max(m, c[i]);
}
cout << max(m,num) << endl;
return 0;
} |
#ifndef BBBBB
#define BBBBB
#include <iostream>
#include <sstream>
using namespace std;
#define PosNula nullptr
class Posicion {
private:
Posicion* sucesor;
int valor;
public:
Posicion() : sucesor(nullptr) {}
Posicion(int valor) : valor(valor), sucesor(nullptr) {}
Posicion(Posicion*siguiente, int valor) : sucesor(siguiente), valor(valor) {}
int recuperar() {return this->valor;}
void modificar(int valor) {this->valor = valor; }
Posicion* siguiente() {return this->sucesor; }
void establecerSiguiente(Posicion* siguiente) {this->sucesor = siguiente; }
};
typedef Posicion* Pos;
class Lista_Pos {
private:
int numero_elementos;
Posicion* primera_posicion;
Posicion* ultima_posicion;
public:
Lista_Pos();
// Lista_Pos(int);
void iniciar(); //O.B
void iniciar(int);
Posicion* siguiente(Posicion* posicion); //O.B
Posicion* anterior(Posicion* posicion); //0.B
void modificar(Posicion* posicion, int valor); //O.B
int recuperar(Posicion* posicion); //O.B
void insertar(Posicion* posicion, int valor); //O.B
void agregarAlFinal(int valor); //O.B
void borrar(Posicion * posicion); //0.B
Posicion* primera(); //0.B
Posicion* ultima(); //O.B
bool vacia(); //0.B
void vaciar(); //O.B
void destruir(); //O.B
int NumElem(); //O.B
void intercambiar(Posicion* p_1, Posicion* p_2); //O.B
string imprimirLista(); //Algoritmo.
Posicion* traducir(int indice); //Algoritmo.
};
#endif
|
#include<iostream>
#include<climits>
using namespace std;
int mincoins(int *coins,int n,int amount)
{
if(amount==0)
{
return 0;
}
int ans=INT_MAX;
int smallans;
for(int i=0;i<n;i++)
{
if(amount-coins[i]>=0)
{
smallans=mincoins(coins,n,amount-coins[i])+1;
}
if(smallans!=INT_MAX)
{
ans=min(ans,smallans);
}
}
return ans;
}
int bottomup(int *coins,int n,int amount)
{
int dp[1000];
dp[0]=0;
for(int i=1;i<=amount;i++)
{
dp[i]=INT_MAX;
}
for(int Amount=1;Amount<=amount;Amount++)
{
for(int i=0;i<n;i++)
{
if(Amount-coins[i]>=0)
{
dp[Amount]=min(dp[Amount],1+dp[Amount-coins[i]]);
}
}
}
for(int Amount=0;Amount<=amount;Amount++)
{
cout<<dp[Amount]<<" ";
}
cout<<endl;
return dp[amount];
}
int main()
{
int coins[]={1,7,10};
int n=sizeof(coins)/sizeof(int);
int amount;
cin>>amount;
cout<<bottomup(coins,n,amount)<<endl;
cout<<mincoins(coins,n,amount)<<endl;
return 0;
} |
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
using pi = pair<int, int>;
#define f first
#define s second
#define mp make_pair
int main() {
setIO();
vector<int> ps;
ps.pb(0);
int n; cin >> n;
vector<int> flowers;
for (int i = 0; i < n; ++i) {
int a; cin >> a;
ps.pb(ps[i] + a);
flowers.push_back(a);
}
int ans = 0;
for (int i = 0; i <= n; ++i) {
for (int j = i + 1; j <= n; ++j) {
if ((ps[j] - ps[i]) % (j - i) == 0) {
int avg = (ps[j] - ps[i]) / (j - i);
for (int k = i; k < j; ++k) {
if (flowers[k] == avg) {
++ans;
goto next;
}
}
}
next:;
}
}
cout << ans << endl;
}
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> cur_solutions;
int* songs;
int cur_max;
bool ans;
int sol_sum(vector<int> solutions){
int sum = 0;
for(int i = 0; i < solutions.size(); i++){
sum += solutions[i];
}
return sum;
}
void print_solution(){
for(int i = 0; i < cur_solutions.size(); i++){
cout << cur_solutions[i] << ' ';
}
cout << "sum:" << cur_max << endl;
}
void erase_0(){
for(int i = 0; i < cur_solutions.size(); i++){
if (cur_solutions[i] == 0){
cur_solutions.erase(cur_solutions.begin() + i);
i--;
}
}
}
void solution(int pos, int n, int N, vector<int> solutions){
if (pos > n){
if (sol_sum(solutions) > cur_max){
cur_max = sol_sum(solutions);
cur_solutions.clear();
cur_solutions = solutions;
}
return;
}
solutions.push_back(songs[pos]);
int cur_sum = sol_sum(solutions);
if (cur_sum > N){
solutions.erase(solutions.end() - 1); //erasing last inserted element
solution(pos+1, n, N, solutions);
print_solution();
}
else if (cur_sum == N){
ans = 1;
cur_max = sol_sum(solutions);
cur_solutions.clear();
cur_solutions = solutions;
return;
}
for(int i = pos+1; i < n; i++){
solution(i, n, N, solutions);
}
// solution(pos+1, n, N);
}
void real_solutions(int n, int N){
for(int i = 0; i < n; i++){
vector<int> s;
solution(i, n, N, s);
if (ans){
ans = 0;
break;
}
}
}
int main(int argc, char *argv[]) {
while(1){
cur_solutions.clear();
ans = 0;
int N, n;
cin >> N >> n;
songs = new int[n];
for(int i = 0; i < n; i++){
cin >> songs[i];
}
cur_max = -1;
//solution(0, n, N);
real_solutions(n, N);
erase_0();
print_solution();
delete[] songs;
}
return 0;
}
|
#include "DynamicFunctionWrapper.h"
#include <iostream>
#include <string>
#include <dlfcn.h>
int DynamicFunctionWrapper::load_external_symbol(const std::string &symbol){
if(!handle)
return -1;
// clear errors
dlerror();
*(void**) (&dyn_print_hello) = dlsym(handle, symbol.c_str());
const char* error = dlerror();
if(error != NULL) {
std::cerr << error << "\n";
return -1;
}
return 0;
}
// public interface to use
void DynamicFunctionWrapper::print_hello(const std::string& name)
{
std::cout << "DynamicFunctionWrapper: ";
dyn_print_hello(name);
}
|
/*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* 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 <test/CollidingShapesTestFramework.hh>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
/////////////////////////////////////////////////
int main(int argc, char **argv)
{
std::vector<std::string> selectedEngines;
std::vector<std::string> unitShapes;
std::vector<std::string> sdfModels;
std::string configFile;
// Read command line parameters
// ----------------------
// description for engine options as stream so line doesn't go over 80 chars.
std::stringstream descEngines;
descEngines << "Specify one or several physics engines. " <<
"Can contain [ode, bullet, dart, simbody]. Default is [ode].";
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Produce help message")
("shape,s",
po::value<std::vector<std::string> >(&unitShapes)->multitoken(),
"Unit shape specification, can be any of [sphere, cylinder, cube]")
("model,m",
po::value<std::vector<std::string> >(&sdfModels)->multitoken(),
std::string(std::string("Model specification, can be either the ") +
std::string("name of a model in the gazebo model paths, or a ") +
std::string("path to a SDF file")).c_str())
("config,c",
po::value<std::string>(&configFile),
"load from configuration file");
po::options_description desc_hidden("Positional options");
desc_hidden.add_options()
("engines,e",
po::value<std::vector<std::string> >(&selectedEngines)->multitoken(),
descEngines.str().c_str());
po::variables_map vm;
po::positional_options_description p;
// positional arguments default to "engines" argument
p.add("engines", -1);
po::options_description desc_composite;
desc_composite.add(desc).add(desc_hidden);
po::command_line_parser parser(argc, argv);
parser.options(desc_composite).positional(p);
po::parsed_options parsedOpt = parser.run();
po::store(parsedOpt, vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << argv[0] <<" <list of engines> " << std::endl;
std::cout << desc << std::endl;
return 1;
}
if (vm.count("engines"))
{
std::cout << "Engines to load: " << std::endl;
for (std::vector<std::string>::iterator it = selectedEngines.begin();
it != selectedEngines.end(); ++it)
{
std::cout << *it << std::endl;
}
}
else
{
std::cout << "No engines were specified, so using 'ode'" << std::endl;
selectedEngines.push_back("ode");
}
/* if (vm.count("shape"))
{
std::cout << "Shapes specified " << vm.count("shape") << std::endl;
for (std::vector<std::string>::iterator it = unitShapes.begin();
it != unitShapes.end(); ++it)
{
std::cout << *it << std::endl;
}
}
if (vm.count("model"))
{
std::cout << "Models specified " << vm.count("model") << std::endl;
for (std::vector<std::string>::iterator it = sdfModels.begin();
it != sdfModels.end(); ++it)
{
std::cout << *it << std::endl;
}
}
*/
collision_benchmark::test::CollidingShapesTestFramework csTest;
bool success = false;
float modelsGap = -1;
bool modelsGapIsFactor = false;
if (!configFile.empty())
{
std::cout << "Loading from configuration file " << configFile << std::endl;
success = csTest.Run(selectedEngines, configFile,
modelsGap, modelsGapIsFactor);
}
else
{
success = csTest.Run(selectedEngines, unitShapes, sdfModels,
modelsGap, modelsGapIsFactor);
}
std::cout << "Bye, bye." << std::endl;
return success ? 0 : 1;
}
|
#include "Board.hpp"
#include "City.hpp"
#include "Player.hpp"
#include "Virologist.hpp"
using namespace pandemic;
Virologist::Virologist(Board &board, enum City a){
CurrentCity = a;
theBorad = &board;
}
Player& Virologist::treat(enum City a){
if(CurrentCity!=a){
if(!(Cards.at(size_t(a)))){
throw invalid_argument("you are not in this city");
}
}
if(getMap()[a].cube == 0){
throw invalid_argument("there are no cubes in this city");
}
if(getCures()[getMap()[a].colorOfCity]){
getMap()[a].cube=0;
}
else{
getMap()[a].cube--;
}
return *this;
}
string Virologist::role(){
return "Virologist";
} |
#include "boxspawn.h"
Point BoxSpawn::get_location() const {
return spawn_location;
}
BoxSpawn::BoxSpawn(Point a_spawn_location, std::vector<std::string> a_weapons_to_choose, int a_ticks_until_first_spawn, int a_ticks_respawn, int a_index) :
spawn_location(a_spawn_location),
weapons_to_choose(std::move(a_weapons_to_choose)),
ticks_until_first_spawn(a_ticks_until_first_spawn),
ticks_respawn(a_ticks_respawn),
index(a_index) {} |
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define ok() puts(ok?"Yes":"No");
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef set<int> si;
typedef map<string, int> msi;
typedef greater<int> gt;
typedef priority_queue<int, vector<int>, gt> minq;
typedef long long ll;
typedef pair<ll,ll> pll;
const ll LINF = 1e18L + 1;
const int INF = 1e9 + 1;
//clang++ -std=c++11 -stdlib=libc++
ll gcd(ll a, ll b) { return b?gcd(b,a%b):a;}
ll lcm(ll a, ll b) { return a/gcd(a,b)*b;}
int main() {
ll a,b,c,d; cin >> a>> b>>c>>d;
ll ans = b-a+1;
ll LCM = lcm(c,d);
ll c_mul = b/c - (a-1)/c;
ll d_mul = b/d - (a-1)/d;
ll c_d_mul = b/LCM - (a-1)/LCM;
ans -= c_mul;
ans -= d_mul;
ans += c_d_mul;
printf("%lld\n", ans);
return 0;
} |
#include <cmath>
#include "pybind11/eigen.h"
#include "pybind11/functional.h"
#include "pybind11/pybind11.h"
#include "pybind11/stl.h"
#include "drake/bindings/pydrake/pydrake_pybind.h"
#include "drake/math/barycentric.h"
#include "drake/math/rigid_transform.h"
#include "drake/math/roll_pitch_yaw.h"
#include "drake/math/rotation_matrix.h"
#include "drake/math/wrap_to.h"
namespace drake {
namespace pydrake {
PYBIND11_MODULE(math, m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::math;
m.doc() = "Bindings for //math.";
py::module::import("pydrake.util.eigen_geometry");
// TODO(eric.cousineau): At present, we only bind doubles.
// In the future, we will bind more scalar types, and enable scalar
// conversion.
using T = double;
m.def("wrap_to", &wrap_to<T, T>, py::arg("value"), py::arg("low"),
py::arg("high"));
py::class_<BarycentricMesh<T>>(m, "BarycentricMesh")
.def(py::init<BarycentricMesh<T>::MeshGrid>())
.def("get_input_grid", &BarycentricMesh<T>::get_input_grid)
.def("get_input_size", &BarycentricMesh<T>::get_input_size)
.def("get_num_mesh_points", &BarycentricMesh<T>::get_num_mesh_points)
.def("get_num_interpolants", &BarycentricMesh<T>::get_num_interpolants)
.def("get_mesh_point", overload_cast_explicit<VectorX<T>, int>(
&BarycentricMesh<T>::get_mesh_point))
.def("get_all_mesh_points", &BarycentricMesh<T>::get_all_mesh_points)
.def("EvalBarycentricWeights",
[](const BarycentricMesh<T>* self,
const Eigen::Ref<const VectorX<T>>& input) {
const int n = self->get_num_interpolants();
Eigen::VectorXi indices(n);
VectorX<T> weights(n);
self->EvalBarycentricWeights(input, &indices, &weights);
return std::make_pair(indices, weights);
})
.def("Eval", overload_cast_explicit<VectorX<T>,
const Eigen::Ref<const MatrixX<T>>&,
const Eigen::Ref<const VectorX<T>>&>(
&BarycentricMesh<T>::Eval))
.def("MeshValuesFrom", &BarycentricMesh<T>::MeshValuesFrom);
py::class_<RigidTransform<T>>(m, "RigidTransform")
.def(py::init())
.def(py::init<const RotationMatrix<T>&, const Vector3<T>&>(),
py::arg("R"), py::arg("p"))
.def(py::init<const RotationMatrix<T>&>(), py::arg("R"))
.def(py::init<const Vector3<T>&>(), py::arg("p"))
.def(py::init<const Isometry3<T>&>(), py::arg("pose"))
.def("set", &RigidTransform<T>::set, py::arg("R"), py::arg("p"))
.def("SetFromIsometry3", &RigidTransform<T>::SetFromIsometry3,
py::arg("pose"))
.def_static("Identity", &RigidTransform<T>::Identity)
.def("rotation", &RigidTransform<T>::rotation, py_reference_internal)
.def("set_rotation", &RigidTransform<T>::set_rotation, py::arg("R"))
.def("translation", &RigidTransform<T>::translation,
py_reference_internal)
.def("set_translation", &RigidTransform<T>::set_translation, py::arg("p"))
.def("GetAsMatrix4", &RigidTransform<T>::GetAsMatrix4)
.def("GetAsMatrix34", &RigidTransform<T>::GetAsMatrix34)
.def("GetAsIsometry3", &RigidTransform<T>::GetAsIsometry3)
.def("SetIdentity", &RigidTransform<T>::SetIdentity)
// .def("IsExactlyIdentity", ...)
// .def("IsIdentityToEpsilon", ...)
.def("inverse", &RigidTransform<T>::inverse)
// TODO(eric.cousineau): Use `matmul` operator once we support Python3.
.def("multiply", [](
const RigidTransform<T>* self, const RigidTransform<T>& other) {
return *self * other;
}, py::arg("other"))
.def("multiply", [](
const RigidTransform<T>* self, const Vector3<T>& p_BoQ_B) {
return *self * p_BoQ_B;
}, py::arg("p_BoQ_B"));
// .def("IsNearlyEqualTo", ...)
// .def("IsExactlyEqualTo", ...)
py::class_<RollPitchYaw<T>>(m, "RollPitchYaw")
.def(py::init<const Vector3<T>>(), py::arg("rpy"))
.def(py::init<const T&, const T&, const T&>(),
py::arg("roll"), py::arg("pitch"), py::arg("yaw"))
.def(py::init<const RotationMatrix<T>&>(), py::arg("R"))
.def(py::init<const Eigen::Quaternion<T>&>(), py::arg("quaternion"))
.def("vector", &RollPitchYaw<T>::vector)
.def("roll_angle", &RollPitchYaw<T>::roll_angle)
.def("pitch_angle", &RollPitchYaw<T>::pitch_angle)
.def("yaw_angle", &RollPitchYaw<T>::yaw_angle)
.def("ToQuaternion", &RollPitchYaw<T>::ToQuaternion)
.def("ToRotationMatrix", &RollPitchYaw<T>::ToRotationMatrix);
py::class_<RotationMatrix<T>>(m, "RotationMatrix")
.def(py::init())
.def(py::init<const Matrix3<T>&>(), py::arg("R"))
.def(py::init<Eigen::Quaternion<T>>(), py::arg("quaternion"))
.def(py::init<const RollPitchYaw<T>&>(), py::arg("rpy"))
.def("matrix", &RotationMatrix<T>::matrix)
// Do not define an operator until we have the Python3 `@` operator so
// that operations are similar to those of arrays.
.def("multiply",
[](const RotationMatrix<T>& self, const RotationMatrix<T>& other) {
return self * other;
})
.def("inverse", &RotationMatrix<T>::inverse)
.def("ToQuaternion",
overload_cast_explicit<Eigen::Quaternion<T>>(
&RotationMatrix<T>::ToQuaternion))
.def_static("Identity", &RotationMatrix<T>::Identity);
// General math overloads.
// N.B. Additional overloads will be added for autodiff, symbolic, etc, by
// those respective modules.
// TODO(eric.cousineau): If possible, delegate these to NumPy UFuncs, either
// using __array_ufunc__ or user dtypes.
// N.B. The ordering in which the overloads are resolved will change based on
// when modules are loaded. However, there should not be ambiguous implicit
// conversions between autodiff and symbolic, and double overloads should
// always occur first, so it shouldn't be a problem.
// See `math_overloads_test`, which tests this specifically.
m
.def("log", [](double x) { return log(x); })
.def("abs", [](double x) { return fabs(x); })
.def("exp", [](double x) { return exp(x); })
.def("sqrt", [](double x) { return sqrt(x); })
.def("pow", [](double x, double y) { return pow(x, y); })
.def("sin", [](double x) { return sin(x); })
.def("cos", [](double x) { return cos(x); })
.def("tan", [](double x) { return tan(x); })
.def("asin", [](double x) { return asin(x); })
.def("acos", [](double x) { return acos(x); })
.def("atan", [](double x) { return atan(x); })
.def("atan2", [](double y, double x) { return atan2(y, x); },
py::arg("y"), py::arg("x"))
.def("sinh", [](double x) { return sinh(x); })
.def("cosh", [](double x) { return cosh(x); })
.def("tanh", [](double x) { return tanh(x); })
.def("min", [](double x, double y) { return fmin(x, y); })
.def("max", [](double x, double y) { return fmax(x, y); })
.def("ceil", [](double x) { return ceil(x); })
.def("floor", [](double x) { return floor(x); });
}
} // namespace pydrake
} // namespace drake
|
#ifndef __PRIMITIVES_DEMO_H__
#define __PRIMITIVES_DEMO_H__
#include "application.h"
#include "physics.h"
using namespace physics;
class PrimitivesDemo : public Application
{
public:
PrimitivesDemo(const char *title, int width, int height);
~PrimitivesDemo();
public:
virtual void onDisplay();
virtual void onKeyboardDown(unsigned char key);
virtual void onKeyboardUp(unsigned char key);
virtual void onFixedUpdate(double duration);
virtual void onMousePress(int button, int state, int x, int y);
virtual void onMouseMove(int x, int y);
private:
void render();
void initTest();
Sphere * initOneSphere(const ffloat &radius, const Vector3 &pos, const ffloat &mass);
Plane * initOnePlane(const Vector3 &dir, const Vector3 &extents, const ffloat &offset);
Box * initOneBox(const Vector3 &pos, const Vector3 &extents, const Vector3 &angles, const ffloat &mass);
Polyhedron * initOnePolyHedron(const Vector3 &pos, const ffloat &mass, const Vector3 &angles);
Capsule * initOneCapsule(const Vector3 &pos, const ffloat &radius, const ffloat &halfHeight, const ffloat &mass, const Vector3 &angles);
void setMoveAcc(unsigned char key);
void setCameraPos(unsigned char key);
void setMoveVelocity(unsigned char key);
GravityForce * genGravityForce();
private:
bool simulate;
bool started;
World *world;
typedef struct point
{
int x;
int y;
} Point;
Point lastPoint;
bool lBtnDown;
float cameraStep;
float radY;
float radP;
float lookDist;
float eX, eY, eZ;
float dX, dY, dZ;
enum WASD_MODE
{
CAMERA = 0,
MOVE = 1,
VELOCITY = 2,
};
WASD_MODE wasdMode;
Sphere *moveSphere;
unsigned int moveID;
ffloat acc;
ffloat velocity;
ffloat deltaTime;
};
#endif |
#include<stdio.h>
int main()
{
double x[3],y[3],z[3],c[3],d,dx,dy,dz,valueX,valueY,valueZ;
printf("Equation Format\n");
printf("x1+y1+z1=c1\nx2+y2+z2=c2\nx3+y3+z3=c3\n");
for(int i=0; i<3; i++)
{
printf("for equation %d\n",i+1);
printf("Enter the value of x%d,y%d,z%d,c%d\n",i+1,i+1,i+1,i+1);
scanf("%lf %lf %lf %lf",&x[i],&y[i],&z[i],&c[i]);
}
//using cramer's rule
d = ( x[0]*( ( y[1]*z[2] )-( y[2]*z[1] ) ) ) - ( y[0]*( (x[1]*z[2] ) - ( x[2]*z[1] ) ) ) + ( z[0]*( (x[1]*y[2] ) - ( x[2]*y[1] ) ) );
dx = ( c[0]*( ( y[1]*z[2] )-( y[2]*z[1] ) ) ) - ( y[0]*( (c[1]*z[2] ) - ( c[2]*z[1] ) ) ) + ( z[0]*( (c[1]*y[2] ) - ( c[2]*y[1] ) ) );
dy = ( x[0]*( ( c[1]*z[2] )-( c[2]*z[1] ) ) ) - ( c[0]*( (x[1]*z[2] ) - ( x[2]*z[1] ) ) ) + ( z[0]*( (x[1]*c[2] ) - ( x[2]*c[1] ) ) );
dz = ( x[0]*( ( y[1]*c[2] )-( y[2]*c[1] ) ) ) - ( y[0]*( (x[1]*c[2] ) - ( x[2]*c[1] ) ) ) + ( c[0]*( (x[1]*y[2] ) - ( x[2]*y[1] ) ) );
valueX=dx/d;
valueY=dy/d;
valueZ=dz/d;
printf("value of x,y,z are: %lf %lf %lf: ",valueX,valueY,valueZ);
return 0;
}
|
#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
const int MX = 100, UNVISITED = -1, VISITED = 1;
vector< vector<int> > graph;
vector<int> dfs_num, ans;
int cont;
map<string, int> encode;
vector<string> decode;
void topologicalSort(int u) {
dfs_num[u] = VISITED;
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
if (dfs_num[v] == UNVISITED)
topologicalSort(v);
}
ans.push_back(u);
}
int main() {
ifstream cin("topoSort.in");
cont = 0;
graph.resize(MX);
string a, b; char c;
while (cin >> a >> c >> b) {
int id_a, id_b;
if (encode.count(a)) id_a = encode[a];
else {
encode[a] = id_a = cont++;
decode.push_back(a);
}
if (encode.count(b)) id_b = encode[b];
else {
encode[b] = id_b = cont++;
decode.push_back(b);
}
graph[id_b].push_back(id_a);
}
dfs_num.assign(cont, UNVISITED);
for (int i = 0; i < cont; i++)
if (dfs_num[i] == UNVISITED)
topologicalSort(i);
for (int i = 0; i < ans.size(); i++)
cout << i + 1 << ". " << decode[ans[i]] << endl;
return 0;
} |
//
// Created by wqy on 19-11-28.
//
#include "Vertex.h"
namespace esc {
void Vertex::setName(string _name) {
this->name = _name;
}
} |
#ifndef _ROTATION_HPP_
#define _ROTATION_HPP_
class StaticRotation {
public:
static void rotate
(float* r /*[4]*/, float* x /*[3]*/, float* y /*[3]*/);
static void vectorToMatrix
(float ang_deg, float u0, float u1, float u2, float* R /*[16]*/);
static void vectorToMatrix
(float* r /*[4]*/, float* R /*[16]*/);
static void matrixToVector
(float* R /*[16]*/, float* r /*[4]*/);
static void multiplyMatrices
(float* A /*[16]*/, float* B /*[16]*/, float* C /* C[16]=A*B */);
static void multiplyMatricesLeft
(float* A /*[16]*/, float* B /*[16]*/);
static void vectorMultiplyLeft
(float ang_deg, float u0, float u1, float u2, float* r /*[4]*/);
static void crossProduct
(double* x /*[3]*/, double* y /*[3]*/, double* z /*[3]*/);
};
#endif // _ROTATION_HPP_
|
/*
* @FilePath : /root/hirain/note/cpp/refer.cpp
* @Description : 引用reference
* @Author : Xjzer
* @Date : 2021-04-23 16:34:24
* @Email : xjzer2020@163.com
* @Others : empty
* @LastEditTime : 2021-05-02 14:21:05
*/
#include <iostream>
using namespace std;
/* 引用 */
void Refer(void){
int a = 99;
int b = 101;
int &r = a; //必须在声明引用变量时进行初始化,且不可被修改
r = b; //不是修改引用的目标,而是赋值
cout << a << " " << r << endl; // 101 101
a++;
cout << a << " " << r << endl; // 102 102
r++;
cout << a << " " << r << endl; // 103 103
cout << &a << " " << &r << endl; //地址相同
//由结果可知,a和b的值和地址都相同,++操作可以理解为:将一个有两个名称的变量加1
//注意:虽然地址相同,但实质上引用和被引用的变量占用的不是同一块内存。引用本质上还是一个指针,之所以不能获取引用的地址,是因为编译器进行了内部转换。
}
/* 常引用 */
void ConstRefer(void){
int a = 1000;
int const &r1 = a;
const int &r2 = a;
//r1 = 2; //不可以通过const修饰的引用类型的变量修改引用的目标
a = 2; //可以通过引用目标的自身修改值
cout << "常引用 = " << a << endl;
/*
* 回顾C语言指针:
* int *const p;
* int const *p;
* const int *p;
*/
}
/* 返回引用 */
int bb = 10;
int & ReturnRefer(void){
/**
* 1.适用:返回复杂结构的引用,这样效率更高
* 比如 结构体a = 函数b( );
* 当函数b返回的是一个结构时,则需要将返回值复制到一个临时变量中,再将这个临时变量复制到结构体a。
* 当函数b返回的是一个结构的引用时,则相当于给返回值起了一个别名,再将这个返回值 复制到结构体a。
* 少了一次复制的过程,所以效率更高
* 2.注意
* 1>避免返回局部变量的引用
* 2>返回引用的函数实际上是被引用的变量的别名,所以引用类型的返回是一个左值,
* 要避免像main函数中的操作1时,可以返回一个常引用。
* 3>常规函数的返回值都是右值
*/
cout << "bb = " << bb << endl;
return bb;
}
/* 引用作为函数参数 */
int Arg(int a){
a *= a;
return a;
}
int RefArg(int &a){
a *= a;
return a;
}
int RefConstArg(int const &a){
//a *= a;
return a;
}
void ReferArg(void){
int a = 3;
Arg(a);
Arg(2);
RefArg(a); //正确
/* RefArg(2); //错误
* 报错:cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
* 不能将' int& '类型的非const左值引用绑定到' int '类型的右值
* 通俗理解就是,2虽然是一个int类型,但2是一个右值,此处的参数类型是左值引用
*/
RefConstArg(2); //不报错,但此时实参已经不可修改
/**
* 当实参与引用参数不匹配,并且参数为const引用时,C++将生成临时变量,适用于:
* 实参的类型正确,但不是左值;
* 实参的类型不正确,但可以转换为正确的类型。
* 临时变量只在函数调用期间有效
*/
RefConstArg(a);
/**
* 引用参数适用场合
* 1. 当数据对象是基本类型或小型结构时,直接按值传递或使用指针
* 2. 当数据对象是数组时,只能使用指针
* 3. 当数据对象是较大的结构时,使用指针或引用。
* 4. 当数据对象是类对象时,只能使用引用。
* 5. 再根据是否需要修改数据来添加const
*/
}
/* 右值引用 rvalue reference */
void RvalueRefer(void){
// 右值引用是C++11中新增的,这种引用可以指向右值,使用&&声明
int a = 1;
int && b = 1;
// 待补充:右值引用实现移动语义
}
int main(int argc, char *argv[]){
Refer();
ConstRefer();
/* 引用返回值 */
ReturnRefer() = 114; //操作1
cout << "bb = " << bb << endl;
/* 引用参数 */
ReferArg();
/* 右值引用 */
RvalueRefer();
return 0;
}
|
#include "stdafx.h"
Przedmiot::Przedmiot() {
//Stworzony na potrzeby wczytywania danych z pliku binarnego
}
Przedmiot::Przedmiot(std::string nazwa_przedmiotu, std::string poziom, int cena) : cena(cena) {
//Funkcja sprintf_s zostala uzyta w celu konwersji z typu std::string na typ char
sprintf_s(this->nazwa_przedmiotu, "%s", nazwa_przedmiotu.c_str());
sprintf_s(this->poziom, "%s", poziom.c_str());
//Nadajemy rekordowi w bazie unikalny numer ID
id_przedmiotu = ++ostatnie_id;
}
/* Domyslna wartosc pola ostatnie_id
Przy wczytywaniu danych z pliku wartosc jest zastepowana numerem ID ostatniego rekordu w bazie danych przedmiotow */
int Przedmiot::ostatnie_id = 0;
|
//二维数组
// 数据类型 数组名[行数][列数];
// 数据类型 数组名[行数][列数] = {{数据1,数据2},{数据3,数据4}....};
// 数据类型 数组名[行数][列数] = {数据1,数据2,数据3,数据4....};
// 数据类型 数组名[][列数] = {数据1,数据2,数据3,数据4....};
#include <iostream>
using namespace std;
void print2array(int array[2][3])
{
for(int i = 0;i < 2;i++)
{
for(int j = 0;j < 3;j++)
{
cout<<array[i][j]<<" ";
}
cout<<endl;
}
}
int main(int argc, const char * argv[])
{
int arry1[2][3];
arry1[0][0] = 1;
arry1[0][1] = 2;
arry1[0][2] = 3;
arry1[1][0] = 4;
arry1[1][1] = 5;
arry1[1][2] = 6;
print2array(arry1);
cout<<endl;
int arry2[2][3] = {{1,2,3},
{4,5,6}};
print2array(arry2);
cout<<endl;
int arry3[2][3] = {1,2,3,4,5,6};
print2array(arry3);
cout<<endl;
int arry4[][3] = {1,2,3,4,5,6};
print2array(arry4);
return 0;
} |
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <cstdlib>
using namespace std;
int main()
{
int *P_Bt, *P_Wt, *P_Tat;
float avg_wt=0.0, avg_tat=0.0;
ifstream file("Q1.txt");
string str;
int num, count=0;
file >> num;
P_Bt = new int[num];
P_Wt = new int[num];
P_Tat = new int[num];
while(!file.eof()){
for(int i=0;i<num;++i)
{
file >> str;
P_Bt[i] = atoi(str.c_str());
//cout << "Burst " << i << ":" << P_Bt[i] << "\n";
}
/*cout << file.peek() << "\n";
if (file.peek() == '\r'){
file.ignore(2);
}*/
}
P_Wt[0] = 0;
// calculate waiting time
for (int i = 1 ; i < num ; ++i)
{
P_Wt[i] = 0;
for (int j = 0 ; j < i ; ++j)
{
P_Wt[i] += P_Bt[j];
}
}
// calculate turnaround time
for (int i = 0 ; i < num ; ++i)
{
P_Tat[i] = P_Wt[i] + P_Bt[i];
}
cout<<"Process\tWaiting Time\tTurnaround Time";
for (int i = 0; i < num ; i++)
{
avg_wt+=P_Wt[i];
avg_tat+=P_Tat[i];
cout<<"\nP["<<i+1<<"]"<<"\t"<<P_Wt[i]<<"\t\t"<<P_Tat[i];
}
avg_wt /= (float)num;
avg_tat/= (float)num;
cout<<"\n\nAverage Waiting Time:"<<avg_wt;
cout<<"\nAverage Turnaround Time:"<<avg_tat<<"\n";
}
|
#include <iostream>
using namespace std;
void Input(int &x, int &y) {
cin >> x;
do
{
cin >> y;
} while (y < 0);
}
int Power(int x, int y)
{
if (y == 0) {
return 1;
}
else if (y % 2 == 0) {
return Power(x, y / 2) * Power(x, y / 2);
}
else {
return x * Power(x, y / 2) * Power(x, y / 2);
}
}
int main()
{
int x;
int y;
Input(x, y);
// Divide & Conquer
cout << Power(x, y);
return 0;
}
|
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <vector>
#include <string>
#include <math.h>
using namespace cv;
using namespace std;
Mat src; Mat src_HSV;
Mat src2; Mat src2_gray;
RNG rng(12345);
void drawCircles(Mat red_hue_image, Mat green_hue_image, Mat white_hue_image, Mat yellow_hue_image, Mat blue_hue_image, Mat orig_image);
void thresh_callback(int, void*);
int main( int argc, char** argv )
{
/// Load source image
src = imread( argv[1], 1 );
src2 = imread( argv[2], 1);
cvtColor(src2, src2_gray, CV_BGR2GRAY);
blur(src2_gray, src2, Size(3,3));
thresh_callback(0, 0);
Mat copy_image = src.clone();
medianBlur(src, src, 3);
/// Convert image to HSV and blur it
cvtColor( src, src_HSV, CV_BGR2HSV );
/// Threshold the HSV image, keep only red pixels
Mat red_hue_image;
inRange(src_HSV, Scalar(1,100,100), Scalar(8,255,255), red_hue_image);
// Threshold the HSV image, keep only green pixels
Mat green_hue_image;
inRange(src_HSV, Scalar(50,100,100), Scalar(70,255,255), green_hue_image);
// Threshold the HSV image, keep only white pixels
Mat white_hue_image;
inRange(src_HSV, Scalar(0,0,200), Scalar(179,100,255), white_hue_image);
// Threshold the HSV image, keep only yellow pixels
Mat yellow_hue_image;
inRange(src_HSV, Scalar(20,100,100), Scalar(30,255,255), yellow_hue_image);
// Threshold the HSV image, keep only blue pixels
Mat blue_hue_image;
inRange(src_HSV, Scalar(90,50,50), Scalar(100,255,255), blue_hue_image);
GaussianBlur(red_hue_image, red_hue_image, Size(9, 9), 2, 2);
GaussianBlur(green_hue_image, green_hue_image, Size(9, 9), 2, 2);
GaussianBlur(white_hue_image, white_hue_image, Size(9, 9), 2, 2);
GaussianBlur(yellow_hue_image, yellow_hue_image, Size(9, 9), 2, 2);
GaussianBlur(blue_hue_image, blue_hue_image, Size(9, 9), 2, 2);
drawCircles(red_hue_image, green_hue_image, white_hue_image, yellow_hue_image, blue_hue_image, copy_image);
waitKey(0);
return(0);
}
void drawCircles(Mat red_hue_image, Mat green_hue_image, Mat white_hue_image, Mat yellow_hue_image, Mat blue_hue_image, Mat orig_image)
{
ofstream outputFile;
outputFile.open ("QuestionTwo_Output.txt");
// Use the Hough transform to detect circles in the combined threshold image
vector<Vec3f> circles;
// Red
HoughCircles(red_hue_image, circles, CV_HOUGH_GRADIENT, 1, red_hue_image.rows/20, 10, 20, 30, 60);
// Loop over all detected circles and outline them on the original image
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
// Circle outline
circle(orig_image, center, radius, Scalar(0, 0, 255), 5);
}
cout << "There are " << circles.size() << " red chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " red chocolate eggs. \n" <<
endl;
// Green
HoughCircles(green_hue_image, circles, CV_HOUGH_GRADIENT, 1, green_hue_image.rows/11, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(0, 255, 0), 5);
}
cout << "There are " << circles.size() << " green chocolate eggs" << endl;
outputFile << "\nThere are " << circles.size() << " green chocolate eggs. \n" << endl;
// White
HoughCircles(white_hue_image, circles, CV_HOUGH_GRADIENT, 1, white_hue_image.rows/15, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(255, 255, 255), 5);
}
cout << "There are " << circles.size() << " white chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " white chocolate eggs. \n" << endl;
// Yellow
HoughCircles(yellow_hue_image, circles, CV_HOUGH_GRADIENT, 1, yellow_hue_image.rows/11, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(0, 255, 255), 5);
}
cout << "There are " << circles.size() << " yellow chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " yellow chocolate eggs. \n" << endl;
// Blue
HoughCircles(blue_hue_image, circles, CV_HOUGH_GRADIENT, 1, blue_hue_image.rows/11, 10, 20, 0, 100);
for(size_t i = 0; i < circles.size(); ++i) {
Point center(round(circles[i][0]), round(circles[i][1]));
int radius = round(circles[i][2]);
circle(orig_image, center, radius, Scalar(255, 0, 0), 5);
}
cout << "There are " << circles.size() << " blue chocolate eggs" << endl;
outputFile << "There are " << circles.size() << " blue chocolate eggs. \n" << endl;
outputFile.close();
namedWindow("chocolate_eggs_marked", WINDOW_AUTOSIZE);
imshow("chocolate_eggs_marked", orig_image);
/// Save as JPG image file in the current directory
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(95);
imwrite("chocolate_eggs_marked.jpg", orig_image, compression_params );
}
void thresh_callback(int, void* )
{
Mat threshold_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Detect edges using Threshold
threshold( src2, threshold_output, 100, 255, THRESH_BINARY );
/// Find contours
findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
/// Find the rotated rectangles and ellipses for each contour
vector<RotatedRect> minRect( contours.size() );
vector<RotatedRect> minEllipse( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ minRect[i] = minAreaRect( Mat(contours[i]) );
// cout << minRect[i].points() "\n"<< endl;
if( contours[i].size() > 5 )
{ minEllipse[i] = fitEllipse( Mat(contours[i]) ); }
}
/// Draw contours + rotated rects + ellipses
Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
int width;
int hundred_pixels=(45000/450);
int good_eggs = 0;
int bad_eggs = 0;
for( int i = 0; i< contours.size(); i++ )
{
Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
// contour
drawContours( drawing, contours, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
// ellipse
ellipse( drawing, minEllipse[i], color, 2, 8 );
// rotated rectangle
Point2f rect_points[4];
minRect[i].points( rect_points );
for( int j = 0; j < 4; j++ )
{
line( drawing, rect_points[j], rect_points[(j+1)%4], color, 1, 8 );
// cout << rect_points[j].x << "," << rect_points[j].y << endl;
width = sqrt(pow(rect_points[(j+1)%4].x - rect_points[j].x, 2) + pow(rect_points[(j+1)%4].y - rect_points[j].y, 2));
// cout << width << endl;
// height = sqrt(pow(rect_points[(j+2)%4].x - rect_points[(j+1)%4].x, 2) + pow(rect_points[(j+2)%4].y - rect_points[(j+1)%4].y, 2));
if (width < hundred_pixels)
{
bad_eggs++;
}
else
{
good_eggs++;
}
}
}
cout << "There are "<< good_eggs <<" good eggs and " << bad_eggs << " bad_eggs" << endl;
char const* source_window = "Sorting objects by size";
namedWindow( source_window, CV_WINDOW_AUTOSIZE );
imshow( source_window, drawing);
}
|
/*
Project: AltaLux plugin for IrfanView
Author: Stefano Tommesani
Website: http://www.tommesani.com
Microsoft Public License (MS-PL) [OSI Approved License]
This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
*/
#ifdef ENABLE_LOGGING
#include "easylogging++.h"
#endif // ENABLE_LOGGING
void SetupLogging()
{
#ifdef ENABLE_LOGGING
el::Configurations defaultConf;
defaultConf.setToDefault();
defaultConf.setGlobally(el::ConfigurationType::Format, "%datetime{%H:%m:%s,%g} %msg");
TCHAR lpTempPathBuffer[MAX_PATH];
DWORD dwRetVal = GetTempPath(MAX_PATH, // length of the buffer
lpTempPathBuffer); // buffer for path
if (dwRetVal > MAX_PATH || (dwRetVal == 0))
{
// failed to get temp directory
}
else {
TCHAR szTempFileName[MAX_PATH];
wsprintf(szTempFileName, L"%s%s", lpTempPathBuffer, L"AltaLuxLog.txt");
defaultConf.setGlobally(el::ConfigurationType::ToFile, "true");
std::wstring strTempFileName((TCHAR*)szTempFileName);
defaultConf.setGlobally(el::ConfigurationType::Filename, std::string(strTempFileName.begin(), strTempFileName.end()));
}
el::Loggers::reconfigureAllLoggers(defaultConf);
el::Loggers::setDefaultConfigurations(defaultConf, true);
LOG(INFO) << "Log enabled";
#endif // ENABLE_LOGGING
}
|
#include <gtest/gtest.h>
#include <incbin.h>
#include <xmorphy/morph/DictMorphAnalyzer.h>
#include <xmorphy/morph/SuffixDictAnalyzer.h>
#include <xmorphy/morph/HyphenAnalyzer.h>
using namespace X;
bool hasSP(const std::vector<ParsedPtr> & data, UniSPTag sp)
{
for (size_t i = 0; i < data.size(); ++i)
if (data[i]->sp == sp)
return true;
return false;
}
bool hasNF(const std::vector<ParsedPtr> & data, const utils::UniString & nf)
{
for (size_t i = 0; i < data.size(); ++i)
if (data[i]->normalform == nf)
return true;
return false;
}
bool hasWF(const std::vector<ParsedPtr> & data, const utils::UniString & nf)
{
for (size_t i = 0; i < data.size(); ++i)
if (data[i]->wordform == nf)
return true;
return false;
}
TEST(TestDictAnalyze, TestDict) {
DictMorphAnalyzer proc;
std::vector<ParsedPtr> result = proc.analyze(utils::UniString("АККОМПАНИРУЕМ"));
EXPECT_EQ(result[0]->normalform, utils::UniString("АККОМПАНИРОВАТЬ"));
EXPECT_EQ(result[0]->wordform, utils::UniString("АККОМПАНИРУЕМ"));
EXPECT_TRUE(hasSP(result, UniSPTag::VERB));
std::vector<ParsedPtr> result1 = proc.analyze(utils::UniString("СТАЛИ"));
EXPECT_TRUE(hasNF(result1, utils::UniString("СТАЛЬ")));
EXPECT_TRUE(hasNF(result1, utils::UniString("СТАТЬ")));
EXPECT_TRUE(hasSP(result1, UniSPTag::NOUN));
EXPECT_TRUE(hasSP(result1, UniSPTag::VERB));
std::vector<ParsedPtr> lyd = proc.analyze(utils::UniString("ЛЮДИ"));
EXPECT_TRUE(hasNF(lyd, utils::UniString("ЧЕЛОВЕК")));
EXPECT_TRUE(hasSP(lyd, UniSPTag::NOUN));
std::vector<ParsedPtr> synt = proc.synthesize(utils::UniString("ИНТЕРЕСНЫЙ"), UniMorphTag::Fem | UniMorphTag::Nom);
EXPECT_TRUE(hasWF(synt, utils::UniString("ИНТЕРЕСНАЯ")));
std::vector<ParsedPtr> synt1 = proc.synthesize(utils::UniString("СТАЛИ"), UniMorphTag::Fem | UniMorphTag::Nom | UniMorphTag::Sing);
EXPECT_TRUE(hasWF(synt1, utils::UniString("СТАЛЬ")));
std::vector<ParsedPtr> stal = proc.synthesize(utils::UniString("СТАЛ"), UniMorphTag::Fem);
EXPECT_TRUE(hasWF(stal, utils::UniString("СТАЛА")));
}
TEST(TestDictAnalyze, TestSuffixDict) {
SuffixDictAnalyzer proc;
std::vector<ParsedPtr> result = proc.analyze(utils::UniString("КУЗЯВАЯ"));
EXPECT_TRUE(hasNF(result, utils::UniString("КУЗЯВЫЙ")));
EXPECT_TRUE(hasSP(result, UniSPTag::ADJ));
EXPECT_TRUE(hasSP(result, UniSPTag::NOUN));
std::vector<ParsedPtr> result1 = proc.analyze(utils::UniString("СЕПЕЛИВКИ"));
EXPECT_TRUE(hasNF(result1, utils::UniString("СЕПЕЛИВКА")));
EXPECT_TRUE(hasSP(result1, UniSPTag::NOUN));
std::vector<ParsedPtr> result2 = proc.analyze(utils::UniString("СКРИШОЛЬНУЛАСЬ"));
EXPECT_TRUE(hasNF(result2, utils::UniString("СКРИШОЛЬНУТЬСЯ")));
EXPECT_TRUE(hasSP(result2, UniSPTag::VERB));
std::vector<ParsedPtr> result3 = proc.analyze(utils::UniString("ДЕФАЛЬСИФИКАЦИЕЙ"));
EXPECT_TRUE(hasNF(result3, utils::UniString("ДЕФАЛЬСИФИКАЦИЯ")));
EXPECT_TRUE(hasSP(result3, UniSPTag::NOUN));
std::vector<ParsedPtr> result4 = proc.analyze(utils::UniString("ДЕФАЛЬСИФИЦИРОВАЛА"));
EXPECT_TRUE(hasNF(result4, utils::UniString("ДЕФАЛЬСИФИЦИРОВАТЬ")));
EXPECT_TRUE(hasSP(result4, UniSPTag::VERB));
std::vector<ParsedPtr> synt = proc.synthesize(utils::UniString("ИНТЕРЛИВЫЙ"), UniMorphTag::Fem | UniMorphTag::Nom);
EXPECT_TRUE(hasWF(synt, utils::UniString("ИНТЕРЛИВАЯ")));
std::vector<ParsedPtr> synt1 = proc.synthesize(utils::UniString("ВКЛЕТАЛИ"), UniMorphTag::Fem | UniMorphTag::Nom | UniMorphTag::Sing);
EXPECT_TRUE(hasWF(synt1, utils::UniString("ВКЛЕТАЛЬ")));
std::vector<ParsedPtr> stal = proc.synthesize(utils::UniString("ШМЕНЕКАЛ"), UniMorphTag::Fem);
EXPECT_TRUE(hasWF(stal, utils::UniString("ШМЕНЕКАЛА")));
}
TEST(TestDictAnalyze, TestHyphDict)
{
HyphenAnalyzer proc;
std::vector<ParsedPtr> result = proc.analyze(utils::UniString("ЧЕЛОВЕК-ГОРА"));
EXPECT_TRUE(hasWF(result, utils::UniString("ЧЕЛОВЕК-ГОРА")));
EXPECT_TRUE(hasNF(result, utils::UniString("ЧЕЛОВЕК-ГОРА")));
EXPECT_TRUE(hasSP(result, UniSPTag::NOUN));
std::vector<ParsedPtr> result1 = proc.analyze(utils::UniString("ЧЕЛОВЕКОМ-ГОРОЙ"));
EXPECT_TRUE(hasWF(result1, utils::UniString("ЧЕЛОВЕКОМ-ГОРОЙ")));
EXPECT_TRUE(hasNF(result1, utils::UniString("ЧЕЛОВЕК-ГОРА")));
EXPECT_TRUE(hasSP(result1, UniSPTag::NOUN));
std::vector<ParsedPtr> result2 = proc.analyze(utils::UniString("ПО-СТАРИКОВСКИ"));
EXPECT_TRUE(hasWF(result2, utils::UniString("ПО-СТАРИКОВСКИ")));
EXPECT_TRUE(hasNF(result2, utils::UniString("ПО-СТАРИКОВСКИ")));
EXPECT_TRUE(hasSP(result2, UniSPTag::ADV));
std::vector<ParsedPtr> result3 = proc.analyze(utils::UniString("ИНЖЕНЕРНО-ТЕХНИЧЕСКОМУ"));
EXPECT_TRUE(hasWF(result3, utils::UniString("ИНЖЕНЕРНО-ТЕХНИЧЕСКОМУ")));
EXPECT_TRUE(hasNF(result3, utils::UniString("ИНЖЕНЕРНО-ТЕХНИЧЕСКИЙ")));
EXPECT_TRUE(hasSP(result3, UniSPTag::ADJ));
std::vector<ParsedPtr> result4 = proc.analyze(utils::UniString("ЧАК-ЧАКА"));
EXPECT_TRUE(hasWF(result4, utils::UniString("ЧАК-ЧАКА")));
EXPECT_TRUE(hasNF(result4, utils::UniString("ЧАК-ЧАК")));
EXPECT_TRUE(hasSP(result4, UniSPTag::NOUN));
std::vector<ParsedPtr> result5 = proc.analyze(utils::UniString("КОНТР-АДМИРАЛ-ИНЖЕНЕРУ"));
EXPECT_TRUE(hasWF(result5, utils::UniString("КОНТР-АДМИРАЛ-ИНЖЕНЕРУ")));
EXPECT_TRUE(hasNF(result5, utils::UniString("КОНТР-АДМИРАЛ-ИНЖЕНЕР")));
EXPECT_TRUE(hasSP(result5, UniSPTag::NOUN));
}
|
/***************************************************************************
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**************************************************************************/
#include "stdafx.h"
#include "Material.h"
#include "Core/Program/GraphicsProgram.h"
#include "Core/Program/ProgramVars.h"
#include "Utils/Color/ColorHelpers.slang"
namespace Falcor
{
static_assert(sizeof(MaterialData) % 16 == 0, "Material::MaterialData size should be a multiple of 16");
Material::UpdateFlags Material::sGlobalUpdates = Material::UpdateFlags::None;
Material::Material(const std::string& name) : mName(name)
{
}
Material::SharedPtr Material::create(const std::string& name)
{
Material* pMaterial = new Material(name);
return SharedPtr(pMaterial);
}
Material::~Material() = default;
bool Material::renderUI(Gui::Widgets& widget)
{
// We're re-using the material's update flags here to track changes.
// Cache the previous flag so we can restore it before returning.
UpdateFlags prevUpdates = mUpdates;
mUpdates = UpdateFlags::None;
widget.text("Shading model:");
if (getShadingModel() == ShadingModelMetalRough) widget.text("MetalRough", true);
else if (getShadingModel() == ShadingModelSpecGloss) widget.text("SpecGloss", true);
else if (getShadingModel() == ShadingModelHairChiang16) widget.text("HairChiang16", true);
else should_not_get_here();
if (const auto& tex = getBaseColorTexture(); tex != nullptr)
{
widget.text("Base color: " + tex->getSourceFilename());
widget.text("Texture info: " + std::to_string(tex->getWidth()) + "x" + std::to_string(tex->getHeight()) + " (" + to_string(tex->getFormat()) + ")");
widget.image("Base color", tex, float2(100.f));
if (widget.button("Remove texture##BaseColor")) setBaseColorTexture(nullptr);
}
else
{
float4 baseColor = getBaseColor();
if (widget.var("Base color", baseColor, 0.f, 1.f, 0.01f)) setBaseColor(baseColor);
}
if (const auto& tex = getSpecularTexture(); tex != nullptr)
{
widget.text("Specular params: " + tex->getSourceFilename());
widget.text("Texture info: " + std::to_string(tex->getWidth()) + "x" + std::to_string(tex->getHeight()) + " (" + to_string(tex->getFormat()) + ")");
widget.image("Specular params", tex, float2(100.f));
if (widget.button("Remove texture##Specular")) setSpecularTexture(nullptr);
}
else
{
float4 specularParams = getSpecularParams();
if (widget.var("Specular params", specularParams, 0.f, 1.f, 0.01f)) setSpecularParams(specularParams);
widget.tooltip("The encoding depends on the shading model:\n\n"
"MetalRough:\n"
" occlusion (R), roughness (G), metallic (B)\n\n"
"SpecGloss:\n"
" specular color(RGB) and glossiness(A)", true);
if (getShadingModel() == ShadingModelMetalRough)
{
float roughness = getRoughness();
if (widget.var("Roughness", roughness, 0.f, 1.f, 0.01f)) setRoughness(roughness);
float metallic = getMetallic();
if (widget.var("Metallic", metallic, 0.f, 1.f, 0.01f)) setMetallic(metallic);
}
}
if (const auto& tex = getNormalMap(); tex != nullptr)
{
widget.text("Normal map: " + tex->getSourceFilename());
widget.text("Texture info: " + std::to_string(tex->getWidth()) + "x" + std::to_string(tex->getHeight()) + " (" + to_string(tex->getFormat()) + ")");
widget.image("Normal map", tex, float2(100.f));
if (widget.button("Remove texture##NormalMap")) setNormalMap(nullptr);
}
if (const auto& tex = getDisplacementMap(); tex != nullptr)
{
widget.text("Displacement map: " + tex->getSourceFilename());
widget.text("Texture info: " + std::to_string(tex->getWidth()) + "x" + std::to_string(tex->getHeight()) + " (" + to_string(tex->getFormat()) + ")");
widget.image("Displacement map", tex, float2(100.f));
if (widget.button("Remove texture##DisplacementMap")) setDisplacementMap(nullptr);
}
if (const auto& tex = getEmissiveTexture(); tex != nullptr)
{
widget.text("Emissive color: " + tex->getSourceFilename());
widget.text("Texture info: " + std::to_string(tex->getWidth()) + "x" + std::to_string(tex->getHeight()) + " (" + to_string(tex->getFormat()) + ")");
widget.image("Emissive color", tex, float2(100.f));
if (widget.button("Remove texture##Emissive")) setEmissiveTexture(nullptr);
}
else
{
float3 emissiveColor = getEmissiveColor();
if (widget.var("Emissive color", emissiveColor, 0.f, 1.f, 0.01f)) setEmissiveColor(emissiveColor);
}
float emissiveFactor = getEmissiveFactor();
if (widget.var("Emissive factor", emissiveFactor, 0.f, std::numeric_limits<float>::max(), 0.01f)) setEmissiveFactor(emissiveFactor);
if (const auto& tex = getSpecularTransmissionTexture(); tex != nullptr)
{
widget.text("Specular transmission: " + tex->getSourceFilename());
widget.text("Texture info: " + std::to_string(tex->getWidth()) + "x" + std::to_string(tex->getHeight()) + " (" + to_string(tex->getFormat()) + ")");
widget.image("Specular transmission", tex, float2(100.f));
if (widget.button("Remove texture##Transmission")) setSpecularTransmissionTexture(nullptr);
}
else
{
float specTransmission = getSpecularTransmission();
if (widget.var("Specular transmission", specTransmission, 0.f, 1.f, 0.01f)) setSpecularTransmission(specTransmission);
}
float IoR = getIndexOfRefraction();
if (widget.var("Index of refraction", IoR, 1.f, std::numeric_limits<float>::max(), 0.01f)) setIndexOfRefraction(IoR);
bool doubleSided = isDoubleSided();
if (widget.checkbox("Double-sided", doubleSided)) setDoubleSided(doubleSided);
// Restore update flags.
bool changed = mUpdates != UpdateFlags::None;
markUpdates(prevUpdates | mUpdates);
return changed;
}
void Material::setShadingModel(uint32_t model)
{
setFlags(PACK_SHADING_MODEL(mData.flags, model));
}
void Material::setAlphaMode(uint32_t alphaMode)
{
setFlags(PACK_ALPHA_MODE(mData.flags, alphaMode));
}
void Material::setDoubleSided(bool doubleSided)
{
setFlags(PACK_DOUBLE_SIDED(mData.flags, doubleSided ? 1 : 0));
}
void Material::setAlphaThreshold(float alpha)
{
if (mData.alphaThreshold != alpha)
{
mData.alphaThreshold = alpha;
markUpdates(UpdateFlags::DataChanged);
}
}
void Material::setIndexOfRefraction(float IoR)
{
if (mData.IoR != IoR)
{
mData.IoR = IoR;
markUpdates(UpdateFlags::DataChanged);
}
}
void Material::setNestedPriority(uint32_t priority)
{
const uint32_t maxPriority = (1U << NESTED_PRIORITY_BITS) - 1;
if (priority > maxPriority)
{
logWarning("Requested nested priority " + std::to_string(priority) + " for material '" + mName + "' is out of range. Clamping to " + std::to_string(maxPriority) + ".");
priority = maxPriority;
}
setFlags(PACK_NESTED_PRIORITY(mData.flags, priority));
}
void Material::setSampler(Sampler::SharedPtr pSampler)
{
if (pSampler != mResources.samplerState)
{
mResources.samplerState = pSampler;
markUpdates(UpdateFlags::ResourcesChanged);
}
}
void Material::setTexture(TextureSlot slot, Texture::SharedPtr pTexture)
{
if (pTexture == getTexture(slot)) return;
switch (slot)
{
case TextureSlot::BaseColor:
mResources.baseColor = pTexture;
updateBaseColorType();
updateAlphaMode();
break;
case TextureSlot::Specular:
mResources.specular = pTexture;
updateSpecularType();
break;
case TextureSlot::Emissive:
mResources.emissive = pTexture;
updateEmissiveType();
break;
case TextureSlot::Normal:
mResources.normalMap = pTexture;
updateNormalMapMode();
break;
case TextureSlot::Occlusion:
mResources.occlusionMap = pTexture;
updateOcclusionFlag();
break;
case TextureSlot::Displacement:
mResources.displacementMap = pTexture;
updateDisplacementFlag();
break;
case TextureSlot::SpecularTransmission:
mResources.specularTransmission = pTexture;
updateSpecularTransmissionType();
break;
default:
should_not_get_here();
}
markUpdates(UpdateFlags::ResourcesChanged);
}
Texture::SharedPtr Material::getTexture(TextureSlot slot) const
{
switch (slot)
{
case TextureSlot::BaseColor:
return mResources.baseColor;
case TextureSlot::Specular:
return mResources.specular;
case TextureSlot::Emissive:
return mResources.emissive;
case TextureSlot::Normal:
return mResources.normalMap;
case TextureSlot::Occlusion:
return mResources.occlusionMap;
case TextureSlot::Displacement:
return mResources.displacementMap;
case TextureSlot::SpecularTransmission:
return mResources.specularTransmission;
default:
should_not_get_here();
}
return nullptr;
}
uint2 Material::getMaxTextureDimensions() const
{
uint2 dim = uint2(0);
for (uint32_t i = 0; i < (uint32_t)TextureSlot::Count; i++)
{
const auto& t = getTexture((TextureSlot)i);
if (t) dim = max(dim, uint2(t->getWidth(), t->getHeight()));
}
return dim;
}
void Material::setTextureTransform(const Transform& textureTransform)
{
mTextureTransform = textureTransform;
}
void Material::loadTexture(TextureSlot slot, const std::string& filename, bool useSrgb)
{
std::string fullpath;
if (findFileInDataDirectories(filename, fullpath))
{
auto texture = Texture::createFromFile(fullpath, true, useSrgb && isSrgbTextureRequired(slot));
if (texture)
{
setTexture(slot, texture);
// Flush and sync in order to prevent the upload heap from growing too large. Doing so after
// every texture creation is overly conservative, and will likely lead to performance issues
// due to the forced CPU/GPU sync.
gpDevice->flushAndSync();
}
}
}
void Material::clearTexture(TextureSlot slot)
{
setTexture(slot, nullptr);
}
bool Material::isSrgbTextureRequired(TextureSlot slot)
{
uint32_t shadingModel = getShadingModel();
switch (slot)
{
case TextureSlot::Specular:
return (shadingModel == ShadingModelSpecGloss);
case TextureSlot::BaseColor:
case TextureSlot::Emissive:
case TextureSlot::Occlusion:
return true;
case TextureSlot::Normal:
case TextureSlot::Displacement:
return false;
default:
should_not_get_here();
return false;
}
}
void Material::setBaseColor(const float4& color)
{
if (mData.baseColor != color)
{
mData.baseColor = color;
markUpdates(UpdateFlags::DataChanged);
updateBaseColorType();
}
}
void Material::setSpecularParams(const float4& color)
{
if (mData.specular != color)
{
mData.specular = color;
markUpdates(UpdateFlags::DataChanged);
updateSpecularType();
}
}
void Material::setRoughness(float roughness)
{
if (getShadingModel() != ShadingModelMetalRough)
{
logWarning("Ignoring setRoughness(). Material '" + mName + "' does not use the metallic/roughness shading model.");
return;
}
if (mData.specular.g != roughness)
{
mData.specular.g = roughness;
markUpdates(UpdateFlags::DataChanged);
updateSpecularType();
}
}
void Material::setMetallic(float metallic)
{
if (getShadingModel() != ShadingModelMetalRough)
{
logWarning("Ignoring setMetallic(). Material '" + mName + "' does not use the metallic/roughness shading model.");
return;
}
if (mData.specular.b != metallic)
{
mData.specular.b = metallic;
markUpdates(UpdateFlags::DataChanged);
updateSpecularType();
}
}
void Material::setSpecularTransmission(float specularTransmission)
{
if (mData.specularTransmission != specularTransmission)
{
mData.specularTransmission = specularTransmission;
markUpdates(UpdateFlags::DataChanged);
updateSpecularTransmissionType();
}
}
void Material::setVolumeAbsorption(const float3& volumeAbsorption)
{
if (mData.volumeAbsorption != volumeAbsorption)
{
mData.volumeAbsorption = volumeAbsorption;
markUpdates(UpdateFlags::DataChanged);
}
}
void Material::setEmissiveColor(const float3& color)
{
if (mData.emissive != color)
{
mData.emissive = color;
markUpdates(UpdateFlags::DataChanged);
updateEmissiveType();
}
}
void Material::setEmissiveFactor(float factor)
{
if (mData.emissiveFactor != factor)
{
mData.emissiveFactor = factor;
markUpdates(UpdateFlags::DataChanged);
updateEmissiveType();
}
}
bool Material::operator==(const Material& other) const
{
#define compare_field(_a) if (mData._a != other.mData._a) return false
compare_field(baseColor);
compare_field(specular);
compare_field(emissive);
compare_field(emissiveFactor);
compare_field(alphaThreshold);
compare_field(IoR);
compare_field(specularTransmission);
compare_field(flags);
compare_field(volumeAbsorption);
#undef compare_field
#define compare_texture(_a) if (mResources._a != other.mResources._a) return false
compare_texture(baseColor);
compare_texture(specular);
compare_texture(emissive);
compare_texture(normalMap);
compare_texture(occlusionMap);
compare_texture(specularTransmission);
compare_texture(displacementMap);
#undef compare_texture
if (mResources.samplerState != other.mResources.samplerState) return false;
if (mTextureTransform.getMatrix() != other.mTextureTransform.getMatrix()) return false;
if (mOcclusionMapEnabled != other.mOcclusionMapEnabled) return false;
return true;
}
void Material::markUpdates(UpdateFlags updates)
{
mUpdates |= updates;
sGlobalUpdates |= updates;
}
void Material::setFlags(uint32_t flags)
{
if (mData.flags != flags)
{
mData.flags = flags;
markUpdates(UpdateFlags::DataChanged);
}
}
template<typename vec>
static uint32_t getChannelMode(bool hasTexture, const vec& color)
{
if (hasTexture) return ChannelTypeTexture;
if (luminance(color) == 0) return ChannelTypeUnused;
return ChannelTypeConst;
}
void Material::updateBaseColorType()
{
setFlags(PACK_DIFFUSE_TYPE(mData.flags, getChannelMode(mResources.baseColor != nullptr, mData.baseColor)));
}
void Material::updateSpecularType()
{
setFlags(PACK_SPECULAR_TYPE(mData.flags, getChannelMode(mResources.specular != nullptr, mData.specular)));
}
void Material::updateEmissiveType()
{
setFlags(PACK_EMISSIVE_TYPE(mData.flags, getChannelMode(mResources.emissive != nullptr, mData.emissive * mData.emissiveFactor)));
}
void Material::updateSpecularTransmissionType()
{
setFlags(PACK_SPEC_TRANS_TYPE(mData.flags, getChannelMode(mResources.specularTransmission != nullptr, mData.specularTransmission)));
}
void Material::updateAlphaMode()
{
bool hasAlpha = mResources.baseColor && doesFormatHasAlpha(mResources.baseColor->getFormat());
setAlphaMode(hasAlpha ? AlphaModeMask : AlphaModeOpaque);
}
void Material::updateNormalMapMode()
{
uint32_t normalMode = NormalMapUnused;
if (mResources.normalMap)
{
switch(getFormatChannelCount(mResources.normalMap->getFormat()))
{
case 2:
normalMode = NormalMapRG;
break;
case 3:
case 4: // Some texture formats don't support RGB, only RGBA. We have no use for the alpha channel in the normal map.
normalMode = NormalMapRGB;
break;
default:
should_not_get_here();
logWarning("Unsupported normal map format for material " + mName);
}
}
setFlags(PACK_NORMAL_MAP_TYPE(mData.flags, normalMode));
}
void Material::updateOcclusionFlag()
{
bool hasMap = false;
switch (EXTRACT_SHADING_MODEL(mData.flags))
{
case ShadingModelMetalRough:
hasMap = (mResources.specular != nullptr);
break;
case ShadingModelSpecGloss:
hasMap = (mResources.occlusionMap != nullptr);
break;
default:
should_not_get_here();
}
bool shouldEnable = mOcclusionMapEnabled && hasMap;
setFlags(PACK_OCCLUSION_MAP(mData.flags, shouldEnable ? 1 : 0));
}
void Material::updateDisplacementFlag()
{
bool hasMap = (mResources.occlusionMap != nullptr);
setFlags(PACK_DISPLACEMENT_MAP(mData.flags, hasMap ? 1 : 0));
}
SCRIPT_BINDING(Material)
{
pybind11::enum_<Material::TextureSlot> textureSlot(m, "MaterialTextureSlot");
textureSlot.value("BaseColor", Material::TextureSlot::BaseColor);
textureSlot.value("Specular", Material::TextureSlot::Specular);
textureSlot.value("Emissive", Material::TextureSlot::Emissive);
textureSlot.value("Normal", Material::TextureSlot::Normal);
textureSlot.value("Occlusion", Material::TextureSlot::Occlusion);
textureSlot.value("SpecularTransmission", Material::TextureSlot::SpecularTransmission);
textureSlot.value("Displacement", Material::TextureSlot::Displacement);
pybind11::class_<Material, Material::SharedPtr> material(m, "Material");
material.def_property("name", &Material::getName, &Material::setName);
material.def_property("baseColor", &Material::getBaseColor, &Material::setBaseColor);
material.def_property("specularParams", &Material::getSpecularParams, &Material::setSpecularParams);
material.def_property("roughness", &Material::getRoughness, &Material::setRoughness);
material.def_property("metallic", &Material::getMetallic, &Material::setMetallic);
material.def_property("specularTransmission", &Material::getSpecularTransmission, &Material::setSpecularTransmission);
material.def_property("volumeAbsorption", &Material::getVolumeAbsorption, &Material::setVolumeAbsorption);
material.def_property("indexOfRefraction", &Material::getIndexOfRefraction, &Material::setIndexOfRefraction);
material.def_property("emissiveColor", &Material::getEmissiveColor, &Material::setEmissiveColor);
material.def_property("emissiveFactor", &Material::getEmissiveFactor, &Material::setEmissiveFactor);
material.def_property("alphaMode", &Material::getAlphaMode, &Material::setAlphaMode);
material.def_property("alphaThreshold", &Material::getAlphaThreshold, &Material::setAlphaThreshold);
material.def_property("doubleSided", &Material::isDoubleSided, &Material::setDoubleSided);
material.def_property("nestedPriority", &Material::getNestedPriority, &Material::setNestedPriority);
material.def_property("textureTransform", pybind11::overload_cast<void>(&Material::getTextureTransform, pybind11::const_), &Material::setTextureTransform);
material.def(pybind11::init(&Material::create), "name"_a);
material.def("loadTexture", &Material::loadTexture, "slot"_a, "filename"_a, "useSrgb"_a = true);
material.def("clearTexture", &Material::clearTexture, "slot"_a);
}
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ELLIPTICPDEWITHLINEARSOURCECYLINDRICAL_HPP_
#define ELLIPTICPDEWITHLINEARSOURCECYLINDRICAL_HPP_
#include "AbstractLinearEllipticPde.hpp"
/**
* The pde Div.(Grad u) + au + b = 0;
*
* Formulated to work in finite element method for axisymmetric cylindrical polars
* where the integrals become dxdy = rdrdz, so we need to multiply everything by r.
* rX[0] = r
* rX[1] = z
*/
class EllipticPdeWithLinearSourceCylindrical : public AbstractLinearEllipticPde<2u,2u>
{
private:
double mCoeffOfU;
double mConstant;
public:
EllipticPdeWithLinearSourceCylindrical(double coeffOfU, double constant)
{
mCoeffOfU = coeffOfU;
mConstant = constant;
}
double ComputeConstantInUSourceTerm(const ChastePoint<2u>& rX, Element<2u,2u>*)
{
return rX[0]*mConstant;
}
double ComputeLinearInUCoeffInSourceTerm(const ChastePoint<2u>& rX, Element<2u,2u>*)
{
return rX[0]*mCoeffOfU;
}
c_matrix<double, 2u, 2u> ComputeDiffusionTerm(const ChastePoint<2u>& rX)
{
return rX[0]*identity_matrix<double>(2u);
}
};
#endif /*ELLIPTICPDEWITHLINEARSOURCECYLINDRICAL_HPP_*/
|
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "Shader.h"
#include "MTLWriter.h"
#include "TXTWriter.h"
#include "OBJWriter.h"
using namespace std;
const float ALTERNANCE = 3.14159265359;
const float HALF_ALTERNANCE = ALTERNANCE / 2.0;
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
vector<glm::vec3*>* selection = new vector<glm::vec3*>();
vector<glm::vec3*>* rawCurve = new vector<glm::vec3*>();
vector<glm::vec3*>* externalCurve = new vector<glm::vec3*>();
vector<glm::vec3*>* internalCurve = new vector<glm::vec3*>();
vector<glm::vec3*>* finalCurve = new vector<glm::vec3*>();
vector<GLfloat>* finalFloat = new vector<GLfloat>();
int internalLength = 0, externalLength = 0, faces = 0;
bool shouldDraw = false;
Shader* mainShader;
GLFWwindow* window;
GLuint vao, vbo;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods);
void normalizeAxes(double& x, double& y);
int getQuadrant(float x, float y);
float calculateLineX(vector<glm::vec3*>* refil, float t, int index);
float calculateLineY(vector<glm::vec3*>* refil, float t, int index);
vector<glm::vec3*>* getLine(vector<glm::vec3*>* points);
vector<glm::vec3*>* getCurve(vector<glm::vec3*>* points, bool external);
vector<glm::vec3*>* getFinal(vector<glm::vec3*>* internal, vector<glm::vec3*>* external);
vector<GLfloat>* getFloat(std::vector<glm::vec3*>* points);
int main() {
if (!glfwInit()) {
fprintf(stderr, "ERROR: could not start GLFW3\n");
return 1;
}
window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Teste de versão OpenGL", NULL, NULL);
if (!window) {
fprintf(stderr, "Error while opening window with GLFW3\n");
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
glewExperimental = GL_TRUE;
glewInit();
glfwSetMouseButtonCallback(window, mouse_button_callback);
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
mainShader = new Shader("vs.glsl", "fs.glsl");
mainShader->use();
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
MtlWriter MtlW;
MtlW.open();
ObjWriter ObjW;
ObjW.create();
while (!glfwWindowShouldClose(window)) {
glClearColor(0.6f, 0.6f, 0.6f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
if (shouldDraw == true) {
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, finalFloat->size());
}
glfwPollEvents();
glfwSwapBuffers(window);
}
}
vector<GLfloat>* getFloat(std::vector<glm::vec3*>* points) {
vector<GLfloat>* converted = new std::vector<GLfloat>();
for (int i = 0; i < points->size(); i++) {
converted->push_back(points->at(i)->x);
converted->push_back(points->at(i)->y);
converted->push_back(points->at(i)->z);
}
return converted;
}
void normalizeAxes(double& x, double& y) {
if (x > (SCR_WIDTH / 2)) {
x = x - (SCR_WIDTH / 2);
x = x / (SCR_WIDTH / 2);
}
else if (x == (SCR_WIDTH / 2))
x = 0;
else
x = -(((SCR_WIDTH / 2) - x) / (SCR_WIDTH / 2));
if (y > (SCR_HEIGHT / 2)) {
y = y - (SCR_HEIGHT / 2);
y = y / (SCR_HEIGHT / 2);
y = y * (-1);
}
else if (y == (SCR_HEIGHT / 2))
y = 0;
else {
y = -(((SCR_HEIGHT / 2) - y) / (SCR_HEIGHT / 2));
y = y * (-1);
}
}
int getQuadrant(float x, float y) {
if (x > 0.0 && y > 0.0)
return 1;
else if (x < 0.0 && y > 0.0)
return 2;
else if (x < 0.0 && y < 0.0)
return 3;
else
return 4;
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
normalizeAxes(xpos, ypos);
glm::vec3* point = new glm::vec3(xpos, ypos, 0.0);
selection->push_back(point);
int quadrant = getQuadrant(xpos, ypos);
if (quadrant == 1) {
xpos += 0.5;
ypos += 0.5;
}
else if (quadrant == 2) {
xpos -= 0.5;
ypos += 0.5;
}
else if (quadrant == 3) {
xpos -= 0.5;
ypos -= 0.5;
}
else if (quadrant == 4) {
xpos += 0.5;
ypos -= 0.5;
}
}
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
rawCurve = getLine(selection);
externalCurve = getCurve(rawCurve, true);
internalCurve = getCurve(rawCurve, false);
externalLength = externalCurve->size() / 2.0;
internalLength = internalCurve->size() / 2.0;
finalCurve = getFinal(internalCurve, externalCurve);
finalFloat = getFloat(finalCurve);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * finalFloat->size(), &finalFloat->at(0), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
ObjWriter objW;
objW.saveTexture();
shouldDraw = true;
}
}
vector<glm::vec3*>* getLine(vector<glm::vec3*>* points) {
vector<glm::vec3*>* curve = new vector<glm::vec3*>();
vector<glm::vec3*>* refil = new vector<glm::vec3*>();
glm::vec3* point;
TxtWriter txtW;
txtW.open();
for (int i = 0; i < points->size(); i++) {
refil->push_back(new glm::vec3(points->at(i)->x, points->at(i)->y, 0));
}
refil->push_back(points->at(0));
refil->push_back(points->at(1));
refil->push_back(points->at(2));
for (int i = 0; i < (refil->size() - 3); i++) {
for (int j = 0; j < 500; ++j) {
float t = static_cast<float>(j) / 499.0;
GLfloat x = calculateLineX(refil, t, i);
GLfloat y = calculateLineY(refil, t, i);
point = new glm::vec3(x, y, 0.0);
curve->push_back(point);
txtW.addPoint(point->x, point->y, point->z);
curve->push_back(new glm::vec3(1.0, 0.0, 1.0));
}
}
txtW.close();
return curve;
}
float calculateLineX(vector<glm::vec3*>* refil, float t, int index){
return (((-1 * pow(t, 3) + 3 * pow(t, 2) - 3 * t + 1) * refil->at(index)->x +
(3 * pow(t, 3) - 6 * pow(t, 2) + 0 * t + 4) * refil->at(index + 1)->x +
(-3 * pow(t, 3) + 3 * pow(t, 2) + 3 * t + 1) * refil->at(index + 2)->x +
(1 * pow(t, 3) + 0 * pow(t, 2) + 0 * t + 0) * refil->at(index + 3)->x) / 6);
}
float calculateLineY(vector<glm::vec3*>* refil, float t, int index) {
return (((-1 * pow(t, 3) + 3 * pow(t, 2) - 3 * t + 1) * refil->at(index)->y +
(3 * pow(t, 3) - 6 * pow(t, 2) + 0 * t + 4) * refil->at(index + 1)->y +
(-3 * pow(t, 3) + 3 * pow(t, 2) + 3 * t + 1) * refil->at(index + 2)->y +
(1 * pow(t, 3) + 0 * pow(t, 2) + 0 * t + 0) * refil->at(index + 3)->y) / 6);
}
vector<glm::vec3*>* getCurve(vector<glm::vec3*>* points, bool external) {
vector<glm::vec3*>* curve = new vector<glm::vec3*>();
ObjWriter ObjW;
for (int j = 0; j < points->size() - 1; j += 2) {
GLfloat angle, distanceX, distanceY, offsetX, offsetY;
glm::vec3* fPoint = points->at(j);
glm::vec3* lPoint;
if (j == points->size() - 2)
lPoint = points->at(0);
else
lPoint = points->at(j + 2);
distanceX = lPoint->x - fPoint->x;
distanceY = lPoint->y - fPoint->y;
if (distanceX == 0 || distanceY == 0) {
distanceX = lPoint->x - points->at(j - 2)->x;
distanceY = lPoint->y - points->at(j - 2)->y;
}
angle = glm::atan(distanceY, distanceX);
if (external)
angle += HALF_ALTERNANCE;
else
angle -= HALF_ALTERNANCE;
offsetX = glm::cos(angle) * 0.09;
offsetY = glm::sin(angle) * 0.09;
glm::vec3* curvePoints = new glm::vec3(fPoint->x + offsetX, fPoint->y + offsetY, 0.0);
curve->push_back(curvePoints);
ObjW.addPoints(curvePoints->x, curvePoints->y, curvePoints->z);
curve->push_back(new glm::vec3(1.0, 0.0, 1.0));
}
return curve;
}
vector<glm::vec3*>* getFinal(vector<glm::vec3*>* internal, vector<glm::vec3*>* external) {
ObjWriter ObjW;
int i = 0;
int index = 1;
for (; i < internal->size() - 2; i += 2) {
finalCurve->push_back(internal->at(i));
finalCurve->push_back(internal->at(i + 1));
glm::vec3* fPointInt = internal->at(i);
finalCurve->push_back(internal->at(i + 2));
finalCurve->push_back(internal->at(i + 3));
glm::vec3* lPointInt = internal->at(i + 2);
finalCurve->push_back(external->at(i));
finalCurve->push_back(external->at(i + 1));
glm::vec3* fPointExt = external->at(i);
ObjW.addFaces(index, externalLength, ++faces, 1);
finalCurve->push_back(internal->at(i + 2));
finalCurve->push_back(internal->at(i + 3));
finalCurve->push_back(external->at(i + 2));
finalCurve->push_back(external->at(i + 3));
glm::vec3* lPointExt = external->at(i + 2);
finalCurve->push_back(external->at(i));
finalCurve->push_back(external->at(i + 1));
ObjW.addFaces(index, externalLength, ++faces, 2);
glm::vec3 ab = glm::vec3(lPointInt->x - fPointInt->x, lPointInt->z - fPointInt->z, lPointInt->y - fPointInt->y);
glm::vec3 ac = glm::vec3(fPointExt->x - fPointInt->x, fPointExt->z - fPointInt->z, fPointExt->y - fPointInt->y);
glm::vec3 dc = glm::vec3(fPointExt->x - lPointExt->x, fPointExt->z - lPointExt->z, fPointExt->y - lPointExt->y);
glm::vec3 db = glm::vec3(lPointInt->x - lPointExt->x, lPointInt->z - lPointExt->z, lPointInt->y - lPointExt->y);
glm::vec3 internalNormal = glm::cross(ac, ab);
glm::vec3 externalNormal = glm::cross(db, dc);
ObjW.addNormals(internalNormal, externalNormal);
index++;
}
finalCurve->push_back(internal->at(i));
finalCurve->push_back(internal->at(i + 1));
glm::vec3* fPointInt = internal->at(i);
finalCurve->push_back(internal->at(0));
finalCurve->push_back(internal->at(1));
glm::vec3* lPointInt = internal->at(0);
finalCurve->push_back(external->at(i));
finalCurve->push_back(external->at(i + 1));
glm::vec3* fPointExt = external->at(i);
ObjW.addFaces(index, externalLength, ++faces, 3);
finalCurve->push_back(internal->at(0));
finalCurve->push_back(internal->at(1));
finalCurve->push_back(external->at(0));
finalCurve->push_back(external->at(1));
glm::vec3* lPointExt = external->at(0);
finalCurve->push_back(external->at(i));
finalCurve->push_back(external->at(i + 1));
ObjW.addFaces(index, externalLength, ++faces, 4);
glm::vec3 ab = glm::vec3(fPointInt->x - lPointInt->x, fPointInt->z - lPointInt->z, fPointInt->y - lPointInt->y);
glm::vec3 ac = glm::vec3(fPointInt->x - fPointExt->x, fPointInt->z - fPointExt->z, fPointInt->y - fPointExt->y);
glm::vec3 dc = glm::vec3(lPointExt->x - fPointExt->x, lPointExt->z - fPointExt->z, lPointExt->y - fPointExt->y);
glm::vec3 db = glm::vec3(lPointExt->x - lPointInt->x, lPointExt->z - lPointInt->z, lPointExt->y - lPointInt->y);
glm::vec3 internalNormal = glm::cross(ab, ac);
glm::vec3 externalNormal = glm::cross(db, dc);
ObjW.addNormals(internalNormal, externalNormal);
return finalCurve;
}
|
//
// Created by gadi on 14/01/2020.
//
#ifndef EX4_SEARCHALGORITHMS_PRIORITYQUEUESTATE_H_
#define EX4_SEARCHALGORITHMS_PRIORITYQUEUESTATE_H_
#include <vector>
#include <functional>
#include <queue>
#include "State.h"
/**
* comparator class ,compare by trail cost value.
* @tparam T kind of state
*/
template<class T>
class CompByCost {
public:
bool operator()(State<T> *state, State<T> *comp) {
bool b = (state->getTrail() > comp->getTrail());
return b;
}
};
/**
* implementation of priority_queueState by all the regular options
* @tparam T
*/
template<class T>
class priority_queueState {
private:
std::priority_queue<State<T> *, std::vector<State<T> *>, CompByCost<T>> priority_queue_;
public:
/**
* pop one element
*/
void Pop() {
this->priority_queue_.pop();
}
/**
* top option
* @return the first element in the stack
*/
State<T> *Top() {
return this->priority_queue_.top();
}
/**
* push state to the stack
* @param s
*/
void Push(State<T> *s) {
this->priority_queue_.push(s);
}
/**
* is empty method
* @return True=is empty ,false else
*/
bool IsEmpty() {
return this->priority_queue_.empty();
}
/**
* find if state exist in the implementation of priority_queueState
* @param state
* @return true =exist ,else nor
*/
bool findState(State<T> *state) {
std::priority_queue<State<T> *, std::vector<State<T> *>, CompByCost<T>> priority_queue_tmp{};
while (!priority_queue_.empty()) {
State<T> *tmp = priority_queue_.top();
priority_queue_.pop();
if (tmp == state) {
priority_queue_.push(tmp);
while (!priority_queue_tmp.empty()) {
State<T> *move_back = priority_queue_tmp.top();
priority_queue_tmp.pop();
priority_queue_.push(move_back);
}
return true;
}
priority_queue_tmp.push(tmp);
}
while (!priority_queue_tmp.empty()) {
State<T> *tmp2 = priority_queue_tmp.top();
priority_queue_tmp.pop();
priority_queue_.push(tmp2);
}
return false;
}
/**
* remove the s element from the priority_queueState
* @param s = the state we want to remove
*/
void remove(State<T> *s) {
std::vector<State<T> *> tmp;
while (!priority_queue_.empty()) {
State<T> *t = priority_queue_.top();
priority_queue_.pop();
if (t == s) {
break;
}
tmp.emplace_back(t);
}
for (State<T> *b: tmp) {
priority_queue_.push(b);
}
}
};
#endif //EX4_SEARCHALGORITHMS_PRIORITYQUEUESTATE_H_
|
#include <iostream>
#include <cstdlib>
#include "MAXHEAP.h"
using namespace std;
bool heaptype::HEAP_FULL(heaptype *h)
{
if(h->n == MAX_ELEMENTS-1)
return true;
else
return false;
}
bool heaptype::HEAP_EMPTY(heaptype *h)
{
if(h->n <= 0)
return true;
else
return false;
}
// 8,6,4,2,5,3을 가지는 heap을 만든다 //
void heaptype::creat_maxheap(heaptype *h)
{
element temp_item[6] = {8,6,4,2,5,3};
for(int i=0; i<6; i++)
{
insert_maxheap(&temp_item[i] , h);
}
}
void heaptype::insert_maxheap(element *item, heaptype *h)
{
int i;
i = ++h->n;
while ((i!=1) && (item->key > h->heap[i/2].key))
{
h->heap[i] = h->heap[i/2];
i /= 2;
}
h->heap[i] = *item;
}
element heaptype::delete_maxheap(heaptype *h)
{
int parent, child;
element item, temp;
item = h->heap[1];
temp = h->heap[h->n--];
parent = 1;
child = 2;
while (child <= h->n)
{
if (child < h->n && h->heap[child].key < h->heap[child+1].key)
child++;
if (temp.key >= h->heap[child].key)
break;
h->heap[parent] = h->heap[child];
parent = child;
child *= 2;
}
h->heap[parent] = temp;
return item;
}
void heaptype::print_maxheap(heaptype *h)
{
for(int i=1; i<=h->n; i++)
{
cout<<h->heap[i].key<<" ";
}
} |
#pragma once
class PIDcontroller
{
public:
PIDcontroller();
PIDcontroller(double Kp_in, double Ki_in, double Kd_in, double dT_in, double e_prev_in = 0.0, double e_int_in = 0.0);
void setGains(double Kp_in, double Ki_in, double Kd_in, double dT_in);
double calcControl(double e_now);
double calcControl(double e_now, double dT_new);
~PIDcontroller();
private:
double Kp, Ki, Kd;
double dT;
double e_prev;
double e_int;
};
|
#include "stdafx.h"
#include "Person.h"
Person::Person(string firstname, string lastname, int age) :fname(firstname), lname(lastname), age(age)
{
}
Person::~Person()
{
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "VertexMeshReader.hpp"
#include "Exception.hpp"
#include <sstream>
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::VertexMeshReader(std::string pathBaseName)
: mFilesBaseName(pathBaseName),
mIndexFromZero(false), // initially assume that nodes are not numbered from zero
mNumNodes(0),
mNumElements(0),
mNodesRead(0),
mElementsRead(0),
mNumElementAttributes(0)
{
OpenFiles();
ReadHeaders();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNumElements() const
{
return mNumElements;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNumNodes() const
{
return mNumNodes;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNumElementAttributes() const
{
return mNumElementAttributes;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNumFaces() const
{
/// \todo Implement this method (#1076)
return 0;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
ElementData VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNextFaceData()
{
/// \todo Implement this method (#1076, #1377)
ElementData ret;
ret.NodeIndices = std::vector<unsigned>();
ret.AttributeValue = 0;
return ret;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
unsigned VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNumEdges() const
{
/// \todo Implement this method (#1076)
return 0;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::Reset()
{
CloseFiles();
OpenFiles();
ReadHeaders();
mNodesRead = 0;
mElementsRead = 0;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
std::vector<double> VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNextNode()
{
std::vector<double> node_data;
std::string buffer;
GetNextLineFromStream(mNodesFile, buffer);
std::stringstream buffer_stream(buffer);
unsigned index;
buffer_stream >> index;
unsigned offset = mIndexFromZero ? 0 : 1;
if (index != mNodesRead + offset)
{
EXCEPTION("Data for node " << mNodesRead << " missing");
}
double node_value;
for (unsigned i=0; i<SPACE_DIM+1; i++)
{
buffer_stream >> node_value;
node_data.push_back(node_value);
}
mNodesRead++;
return node_data;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
ElementData VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNextElementData()
{
// Create data structure for this element
ElementData element_data;
std::string buffer;
GetNextLineFromStream(mElementsFile, buffer);
std::stringstream buffer_stream(buffer);
unsigned element_index;
buffer_stream >> element_index;
unsigned offset = mIndexFromZero ? 0 : 1;
if (element_index != mElementsRead + offset)
{
EXCEPTION("Data for element " << mElementsRead << " missing");
}
unsigned num_nodes_in_element;
buffer_stream >> num_nodes_in_element;
// Store node indices owned by this element
unsigned node_index;
for (unsigned i=0; i<num_nodes_in_element; i++)
{
buffer_stream >> node_index;
element_data.NodeIndices.push_back(node_index - offset);
}
if (mNumElementAttributes > 0)
{
assert(mNumElementAttributes == 1);
buffer_stream >> element_data.AttributeValue;
}
else
{
element_data.AttributeValue = 0;
}
mElementsRead++;
return element_data;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
VertexElementData VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNextElementDataWithFaces()
{
// Create data structure for this element
VertexElementData element_data;
std::string buffer;
GetNextLineFromStream(mElementsFile, buffer);
std::stringstream buffer_stream(buffer);
unsigned element_index;
buffer_stream >> element_index;
unsigned offset = mIndexFromZero ? 0 : 1;
if (element_index != mElementsRead + offset)
{
EXCEPTION("Data for element " << mElementsRead << " missing");
}
// Get number of nodes owned by this element
unsigned num_nodes_in_element;
buffer_stream >> num_nodes_in_element;
// Store node indices owned by this element
for (unsigned i=0; i<num_nodes_in_element; i++)
{
unsigned node_index;
buffer_stream >> node_index;
element_data.NodeIndices.push_back(node_index - offset);
}
// Get number of faces owned by this element
unsigned num_faces_in_element;
buffer_stream >> num_faces_in_element;
element_data.Faces.resize(num_faces_in_element);
for (unsigned j=0; j<num_faces_in_element; j++)
{
// Create data structure for this face
ElementData face_data;
// Get face index
unsigned face_index;
buffer_stream >> face_index;
face_data.AttributeValue = face_index;
// Get number of nodes owned by this face
unsigned num_nodes_in_face;
buffer_stream >> num_nodes_in_face;
// Store node indices owned by this face
for (unsigned i=0; i<num_nodes_in_face; i++)
{
unsigned node_index_face;
buffer_stream >> node_index_face;
face_data.NodeIndices.push_back(node_index_face - offset);
}
///\todo Store face orientations? (#1076/#1377)
element_data.Faces[j] = face_data;
}
//For back compatibility (we always store attributes on elements now)
element_data.AttributeValue = 0;
if (mNumElementAttributes > 0)
{
assert(mNumElementAttributes==1);
buffer_stream >> element_data.AttributeValue;
}
mElementsRead++;
return element_data;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::OpenFiles()
{
OpenNodeFile();
OpenElementsFile();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::OpenNodeFile()
{
// Nodes definition
std::string file_name = mFilesBaseName + ".node";
mNodesFile.open(file_name.c_str());
if (!mNodesFile.is_open())
{
EXCEPTION("Could not open data file: " + file_name);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::OpenElementsFile()
{
// Elements definition
std::string file_name;
file_name = mFilesBaseName + ".cell";
mElementsFile.open(file_name.c_str());
if (!mElementsFile.is_open())
{
EXCEPTION("Could not open data file: " + file_name);
}
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::ReadHeaders()
{
std::string buffer;
GetNextLineFromStream(mNodesFile, buffer);
std::stringstream buffer_stream(buffer);
buffer_stream >> mNumNodes >> mNumNodeAttributes;
// Get the next line to see if nodes are indexed from zero or not
GetNextLineFromStream(mNodesFile, buffer);
std::stringstream node_buffer_stream(buffer);
unsigned first_index;
node_buffer_stream >> first_index;
assert(first_index == 0 || first_index == 1);
mIndexFromZero = (first_index == 0);
// Close, reopen, skip header
mNodesFile.close();
OpenNodeFile();
GetNextLineFromStream(mNodesFile, buffer);
GetNextLineFromStream(mElementsFile, buffer);
std::stringstream element_buffer_stream(buffer);
element_buffer_stream >> mNumElements >> mNumElementAttributes;
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::CloseFiles()
{
mNodesFile.close();
mElementsFile.close();
}
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
void VertexMeshReader<ELEMENT_DIM, SPACE_DIM>::GetNextLineFromStream(std::ifstream& fileStream, std::string& rawLine)
{
bool line_is_blank;
do
{
getline(fileStream, rawLine);
if (fileStream.eof())
{
EXCEPTION("Cannot get the next line from node or element file due to incomplete data");
}
// Get rid of any comment
rawLine = rawLine.substr(0,rawLine.find('#', 0));
line_is_blank = (rawLine.find_first_not_of(" \t", 0) == std::string::npos);
}
while (line_is_blank);
}
///////// Explicit instantiation///////
template class VertexMeshReader<1,1>;
template class VertexMeshReader<1,2>;
template class VertexMeshReader<1,3>;
template class VertexMeshReader<2,2>;
template class VertexMeshReader<2,3>;
template class VertexMeshReader<3,3>;
|
// github.com/andy489
// https://www.hackerrank.com/challenges/is-binary-search-tree/problem
vector<int> vec;
void inorder(Node *root) {
if (root == nullptr) return;
inorder(root->left);
vec.emplace_back(root->data);
inorder(root->right);
}
bool checkBST(Node *root) {
vec.reserve(100);
inorder(root);
int SIZE = vec.size(), i(1);
for (; i < SIZE; ++i)
if (vec[i] <= vec[i - 1])
return false;
return true;
}
|
#include "CppUTest/TestHarness.h"
#include "CRC.h"
TEST_GROUP(TestString)
{
BitString str;
GeneratorPolynomials gp;
void setup()
{
gp.set("1011");
}
};
TEST(TestString, divide)
{
str="1101001110100000";
STRCMP_EQUAL("100",str.divide(gp).toString().c_str());
}
TEST(TestString,isDivisible)
{
str="11010011101100100";
CHECK_TRUE(str.isDivisible(gp));
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "DynamicVentilationProblem.hpp"
#include "ProgressReporter.hpp"
DynamicVentilationProblem::DynamicVentilationProblem(AbstractAcinarUnitFactory* pAcinarFactory,
const std::string& rMeshDirFilePath,
unsigned rootIndex) : mpAcinarFactory(pAcinarFactory),
mVentilationProblem(rMeshDirFilePath, rootIndex),
mrMesh(mVentilationProblem.rGetMesh()),
mDt(0.01),
mSamplingTimeStepMultiple(1u),
mCurrentTime(0.0),
mRootIndex(rootIndex),
mWriteVtkOutput(false)
{
mVentilationProblem.SetOutflowPressure(0.0);
mpAcinarFactory->SetMesh(&mrMesh);
for (AbstractTetrahedralMesh<1,3>::BoundaryNodeIterator iter = mrMesh.GetBoundaryNodeIteratorBegin();
iter != mrMesh.GetBoundaryNodeIteratorEnd();
++iter )
{
if ((*iter)->GetIndex() != rootIndex)
{
mAcinarMap[(*iter)->GetIndex()] = mpAcinarFactory->CreateAcinarUnitForNode((*iter));
}
}
}
DynamicVentilationProblem::~DynamicVentilationProblem()
{
for (std::map<unsigned, AbstractAcinarUnit*>::iterator iter = mAcinarMap.begin();
iter != mAcinarMap.end();
++iter )
{
delete iter->second;
}
}
MatrixVentilationProblem& DynamicVentilationProblem::rGetMatrixVentilationProblem()
{
return mVentilationProblem;
}
std::map<unsigned, AbstractAcinarUnit*>& DynamicVentilationProblem::rGetAcinarUnitMap()
{
return mAcinarMap;
}
void DynamicVentilationProblem::SetTimeStep(double timeStep)
{
mDt = timeStep;
}
void DynamicVentilationProblem::SetSamplingTimeStepMultiple(unsigned timeStep)
{
mSamplingTimeStepMultiple = timeStep;
}
void DynamicVentilationProblem::SetEndTime(double time)
{
mEndTime = time;
}
void DynamicVentilationProblem::SetOutputDirectory(const std::string directory)
{
mOutputDirectory = directory;
}
void DynamicVentilationProblem::SetOutputFilenamePrefix(const std::string prefix)
{
mOutputFileNamePrefix = prefix;
}
void DynamicVentilationProblem::SetWriteVtkOutput(bool writeVtkOutput)
{
mWriteVtkOutput = writeVtkOutput;
}
void DynamicVentilationProblem::Solve()
{
TimeStepper time_stepper(mCurrentTime, mEndTime, mDt);
#ifdef CHASTE_VTK
VtkMeshWriter<1, 3> vtk_writer(mOutputDirectory, mOutputFileNamePrefix, false);
#endif //CHASTE_VTK
ProgressReporter progress_reporter(mOutputDirectory, mCurrentTime, mEndTime);
std::vector<double> pressures(mrMesh.GetNumNodes(), -1);
std::vector<double> fluxes(mrMesh.GetNumNodes() - 1, -1);
std::vector<double> volumes(mrMesh.GetNumNodes(), -1);
while (!time_stepper.IsTimeAtEnd())
{
//Solve coupled problem
for (AbstractTetrahedralMesh<1,3>::BoundaryNodeIterator iter = mrMesh.GetBoundaryNodeIteratorBegin();
iter != mrMesh.GetBoundaryNodeIteratorEnd();
++iter )
{
if ((*iter)->GetIndex() != mRootIndex)
{
double pleural_pressure = mpAcinarFactory->GetPleuralPressureForNode(time_stepper.GetNextTime(), (*iter));
mAcinarMap[(*iter)->GetIndex()]->SetPleuralPressure(pleural_pressure);
mAcinarMap[(*iter)->GetIndex()]->ComputeExceptFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
mVentilationProblem.SetPressureAtBoundaryNode(*(*iter), mAcinarMap[(*iter)->GetIndex()]->GetAirwayPressure());
}
}
mVentilationProblem.Solve();
mVentilationProblem.GetSolutionAsFluxesAndPressures(fluxes, pressures);
for (AbstractTetrahedralMesh<1,3>::BoundaryNodeIterator iter = mrMesh.GetBoundaryNodeIteratorBegin();
iter != mrMesh.GetBoundaryNodeIteratorEnd();
++iter )
{
if ((*iter)->GetIndex() != 0u)
{
unsigned boundary_element_index = (*(*iter)->rGetContainingElementIndices().begin());
mAcinarMap[(*iter)->GetIndex()]->SetFlow(fluxes[boundary_element_index]);
double resistance = 0.0;
if (fluxes[boundary_element_index] != 0.0)
{
resistance = std::fabs(pressures[(*iter)->GetIndex()]/fluxes[boundary_element_index]);
}
mAcinarMap[(*iter)->GetIndex()]->SetTerminalBronchioleResistance(resistance);
mAcinarMap[(*iter)->GetIndex()]->UpdateFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
}
}
if ((time_stepper.GetTotalTimeStepsTaken() % mSamplingTimeStepMultiple) == 0u)
{
progress_reporter.Update(time_stepper.GetNextTime());
#ifdef CHASTE_VTK
if (mWriteVtkOutput)
{
std::ostringstream suffix_name;
suffix_name << "_" << std::setw(6) << std::setfill('0') << time_stepper.GetTotalTimeStepsTaken()/mSamplingTimeStepMultiple;
vtk_writer.AddCellData("Flux"+suffix_name.str(), fluxes);
vtk_writer.AddPointData("Pressure"+suffix_name.str(), pressures);
for (AbstractTetrahedralMesh<1,3>::BoundaryNodeIterator iter = mrMesh.GetBoundaryNodeIteratorBegin();
iter != mrMesh.GetBoundaryNodeIteratorEnd();
++iter )
{
if ((*iter)->GetIndex() != mRootIndex)
{
volumes[(*iter)->GetIndex()] = mAcinarMap[(*iter)->GetIndex()]->GetVolume();
}
}
vtk_writer.AddPointData("Volume"+suffix_name.str(), volumes);
}
#endif //CHASTE_VTK
}
mCurrentTime = time_stepper.GetNextTime();
time_stepper.AdvanceOneTimeStep();
}
#ifdef CHASTE_VTK
if (mWriteVtkOutput)
{
vtk_writer.WriteFilesUsingMesh(mrMesh);
}
#endif //CHASTE_VTK
}
|
#pragma once
#include "../../../HydraCore/hydra_drv/IBVHBuilderAPI.h"
#include "../common/tutorial/tutorial_device.h"
using namespace embree;
namespace EarlySplit
{
struct Box3f
{
Box3f() : vmin(1e38f, 1e38f, 1e38f), vmax(-1e38f, -1e38f, -1e38f) {}
float3 vmin;
float3 vmax;
inline float3 center() const { return 0.5f*(vmin + vmax); }
inline bool axisAligned(int axis, float split) const
{
float amin[3] = { vmin.x, vmin.y, vmin.z };
float amax[3] = { vmax.x, vmax.y, vmax.z };
return (amin[axis] == amax[axis]) && (amin[axis] == split);
}
inline void include(const float3 in_v)
{
vmin.x = fminf(vmin.x, in_v.x);
vmin.y = fminf(vmin.y, in_v.y);
vmin.z = fminf(vmin.z, in_v.z);
vmax.x = fmaxf(vmax.x, in_v.x);
vmax.y = fmaxf(vmax.y, in_v.y);
vmax.z = fmaxf(vmax.z, in_v.z);
}
inline void intersect(const Box3f& in_box)
{
vmin.x = fmaxf(vmin.x, in_box.vmin.x);
vmin.y = fmaxf(vmin.y, in_box.vmin.y);
vmin.z = fmaxf(vmin.z, in_box.vmin.z);
vmax.x = fminf(vmax.x, in_box.vmax.x);
vmax.y = fminf(vmax.y, in_box.vmax.y);
vmax.z = fminf(vmax.z, in_box.vmax.z);
}
};
struct Triangle
{
Triangle() {}
float4 A;
float4 B;
float4 C;
};
struct TriRef
{
ALIGNED_STRUCT
Box3f box;
int triId;
float metric;
unsigned int dummy1;
unsigned int dummy2;
unsigned int dummy3;
unsigned int geomID;
};
static void TriRefBoundsFunc(const TriRef* spheres, size_t item, RTCBounds* bounds_o)
{
const TriRef& tr = spheres[item];
bounds_o->lower_x = tr.box.vmin.x;
bounds_o->lower_y = tr.box.vmin.y;
bounds_o->lower_z = tr.box.vmin.z;
bounds_o->upper_x = tr.box.vmax.x;
bounds_o->upper_y = tr.box.vmax.y;
bounds_o->upper_z = tr.box.vmax.z;
}
static inline Box3f TriBounds(const Triangle& a_tri)
{
Box3f res;
res.vmin.x = fminf(a_tri.A.x, fminf(a_tri.B.x, a_tri.C.x));
res.vmin.y = fminf(a_tri.A.y, fminf(a_tri.B.y, a_tri.C.y));
res.vmin.z = fminf(a_tri.A.z, fminf(a_tri.B.z, a_tri.C.z));
res.vmax.x = fmaxf(a_tri.A.x, fmaxf(a_tri.B.x, a_tri.C.x));
res.vmax.y = fmaxf(a_tri.A.y, fmaxf(a_tri.B.y, a_tri.C.y));
res.vmax.z = fmaxf(a_tri.A.z, fmaxf(a_tri.B.z, a_tri.C.z));
return res;
}
static inline float SurfaceArea(const Box3f& a_box)
{
float a = a_box.vmax.x - a_box.vmin.x;
float b = a_box.vmax.y - a_box.vmin.y;
float c = a_box.vmax.z - a_box.vmin.z;
return 2.0f * (a*b + a*c + b*c);
}
static inline float SurfaceAreaOfTriangle(const Triangle& tri) { return length(cross(to_float3(tri.C) - to_float3(tri.A), to_float3(tri.B) - to_float3(tri.A))); }
static inline float SurfaceAreaOfTriangle(const float3 v[3]) { return length(cross(v[2] - v[0], v[1] - v[0])); }
static const float SubdivMetric(const Triangle& a_tri, const Box3f& a_box)
{
float triSA = SurfaceAreaOfTriangle(a_tri);
float boxSA = SurfaceArea(a_box);
return (boxSA*boxSA) / fmaxf(triSA, 1e-6f);
}
static inline float& f3_at(float3& a_f, const int a_index)
{
float* pArr = &a_f.x;
return pArr[a_index];
}
};
|
//
// Created by ori294 on 1/10/20.
//
#ifndef EX4_SEARCHALGORITHMS_MATRIXBUILDER_H_
#define EX4_SEARCHALGORITHMS_MATRIXBUILDER_H_
#include "Matrix.h"
#include <string.h>
/**
* MatrixBuilder: builds a Matrix from string.
*/
class MatrixBuilder {
public:
/**
* buildMatrix: builds a matrix from a list of strings.
* @param lineList: list of strings
* @param size: the matrix size (n)
* @return a Matrix
*/
static Matrix *buildMatrix(std::list<std::string> lineList, int size) {
int sourceFlag = 0;
int rowNum = 0, colNum = 0;
double sourceX = 0, sourceY = 0, targetX = 0, targetY = 0;
std::vector<std::vector<double>> matrix;
auto iter = lineList.begin();
while (iter != lineList.end()) {
char char_array[iter->length()];
strcpy(char_array, iter->c_str());
if (rowNum < size) {
std::vector<double> tempVector;
char *token = strtok(char_array, ",");
while (token != nullptr) {
tempVector.emplace_back(std::stod(token));
token = strtok(nullptr, ",");
}
matrix.emplace_back(tempVector);
} else {
if (sourceFlag) {
char *token = strtok(char_array, ",");
targetX = atoi(token);
token = strtok(nullptr, ",");
targetY = atoi(token);
} else {
sourceFlag = 1;
char *token = strtok(char_array, ",");
sourceX = atoi(token);
token = strtok(nullptr, ",");
sourceY = atoi(token);
}
}
rowNum++;
iter++;
}
/**
* create Matrix and add by loop row by row , send the cost vector ,and the num of row
* to method of matrix class to create the matrix of state<point>
*/
Matrix *newMatrix = new Matrix(size);
auto vectorIter = matrix.begin();
int numberOfRow = 0;
while (vectorIter != matrix.end()) {
newMatrix->addRow(*vectorIter, numberOfRow);
vectorIter++;
numberOfRow++;
}
/**
* set the trg and src state point for the matrix by sending 2 state src , trg and 2 cost
*/
newMatrix->setSource(sourceX, sourceY);
newMatrix->setTarget(targetX,targetY);
return newMatrix;
}
/**
* parser_the_message: parse the string to a list of strings, than uses the buildMatrix method to build the
* matrix.
* @param basic_string a string
* @return a Matrix
*/
static Matrix *parser_the_message(std::string basic_string) {
int size = 0;
std::list<std::string> tempList;
char char_array[basic_string.length()];
strcpy(char_array, basic_string.c_str());
char* token = strtok(char_array, "\n");
tempList.emplace_back(token);
while (token != nullptr) {
token = strtok(nullptr, "\n");
if (token != nullptr) {
tempList.emplace_back(token);
size++;
}
}
size-=2;
auto iter = tempList.end();
iter--;
tempList.erase(iter);
return buildMatrix(tempList, size);
}
};
#endif //EX4_SEARCHALGORITHMS_MATRIXBUILDER_H_
|
//---------------------------------------------------------------------------
#ifndef CalcResTableH
#define CalcResTableH
//---------------------------------------------------------------------------
#include "..\..\..\Common\sitHoldem.h"
class clCalcResTable
{
public:
void operator = (clSitHoldem &sit);
void StartTable();
void EndGame();
void WinPlayer(int nbPl);
void Win2Player(int nbPl1, int nbPl2);
void Win3Player(int nbPl1, int nbPl2, int nbPl3);
clDoubleCP CalcMoney(clCalcResTable *StartTable);
int CnPlayersIsCard();
clStacks GetStacks();
int PlMoney(int nb) { return _money[nb] + _bet[nb]; }
bool _isCard[CN_PLAYER];
int _bb, _cnPl, _money[CN_PLAYER], _bet[CN_PLAYER], _nbHAll[CN_PLAYER];
};
//---------------------------------------------------------------------------
#endif
|
/**
* Copyright 2016-2017 MICRORISC s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "JsonUtils.h"
#include "PrfPulseMeter.h"
#include "IService.h"
#include "ISerializer.h"
#include "IMessaging.h"
#include "IScheduler.h"
#include "TaskQueue.h"
#include <string>
#include <chrono>
#include <vector>
#include <memory>
class IDaemon;
typedef std::basic_string<unsigned char> ustring;
template <typename T>
class ScheduleDpaTask
{
public:
ScheduleDpaTask() = delete;
ScheduleDpaTask(const T& dpt, IScheduler* schd)
:m_scheduler(schd)
, m_dpa(dpt)
, m_sync(false)
{}
ScheduleDpaTask(const ScheduleDpaTask& other)
: m_taskHandle(other.m_taskHandle)
, m_scheduler(other.m_scheduler)
, m_dpa(other.m_dpa)
, m_sync((bool)other.m_sync)
{
}
virtual ~ScheduleDpaTask() {};
bool isSync() const { return m_sync; }
void setSync(bool val) { m_sync = val; }
void scheduleTaskPeriodic(const std::string& clientId, const std::string& task, const std::chrono::seconds& sec,
const std::chrono::system_clock::time_point& tp = std::chrono::system_clock::now())
{
removeSchedule(clientId);
m_taskHandle = m_scheduler->scheduleTaskPeriodic(clientId, task, sec, tp);
}
bool isScheduled()
{
return m_taskHandle != IScheduler::TASK_HANDLE_INVALID;
}
void removeSchedule(const std::string& clientId)
{
m_scheduler->removeTask(clientId, m_taskHandle);
m_taskHandle = IScheduler::TASK_HANDLE_INVALID;
}
T& getDpa() { return m_dpa; }
private:
std::atomic_bool m_sync{false};
IScheduler::TaskHandle m_taskHandle = IScheduler::TASK_HANDLE_INVALID;
IScheduler* m_scheduler;
T m_dpa;
};
typedef ScheduleDpaTask<PrfPulseMeterJson> PrfPulseMeterSchd;
class ClientServicePm : public IService
{
public:
ClientServicePm() = delete;
ClientServicePm(const std::string& name);
virtual ~ClientServicePm();
void updateConfiguration(const rapidjson::Value& cfg);
void setDaemon(IDaemon* daemon) override;
virtual void setSerializer(ISerializer* serializer) override;
virtual void setMessaging(IMessaging* messaging) override;
const std::string& getName() const override {
return m_name;
}
void update(const rapidjson::Value& cfg) override;
void start() override;
void stop() override;
private:
void handleMsgFromMessaging(const ustring& msg);
void handleTaskFromScheduler(const std::string& task);
void processFrcFromScheduler(const std::string& task);
void processPulseMeterFromTaskQueue(PrfPulseMeterSchd& pm);
void processPulseMeterFromScheduler(const std::string& task);
bool getFrc() { return m_frcActive; }
void setFrc(bool val);
std::string m_name;
uint16_t m_frcPeriod = 5;
uint16_t m_sleepPeriod = 60;
IMessaging* m_messaging;
IDaemon* m_daemon;
ISerializer* m_serializer;
std::vector<PrfPulseMeterSchd> m_watchedPm;
IScheduler::TaskHandle m_frcHandle;
bool m_frcActive = false;
std::unique_ptr<TaskQueue<PrfPulseMeterSchd*>> m_taskQueue;
rapidjson::Value m_dpaRequestJsonPattern;
};
|
/**
*@file Ant-pluto.cc
*@brief Pluto generator forntend.
*
* Two modes available: Single reaction mode and Random Gun
*
* Random gun:
* Run with --gun to shoot particles of a selected type uniformly
* in all directions.
*
* Reaction Mode:
* Generate physics using pluto by specifiying a reaction string.
* Run with --pluto --reaction "...."
* Where "...." is a Pluto reaction string, for example "p omega [ pi0 g ]":
* for omega production followed by a decay into pi0 gamma.
*
* To further decay the particles use --enableBulk. Then all instable particles
* decay according to the database.
**/
#include "base/CmdLine.h"
#include "base/detail/tclap/ValuesConstraintExtra.h"
#include "base/Logger.h"
#include "base/std_ext/math.h"
#include "base/std_ext/memory.h"
#include "base/std_ext/string.h"
#include "base/WrapTFile.h"
#include "base/vec/vec3.h"
#include "simulation/mc/PlutoExtensions.h"
// pluto++
#include "PParticle.h"
#include "PBeamSmearing.h"
#include "PReaction.h"
#include "PPlutoBulkDecay.h"
#include "PDataBase.h"
// ROOT
#include "TTree.h"
#include "TClonesArray.h"
#include "TMath.h"
#include "TRandom.h"
#include <string>
#include <memory>
using namespace std;
using namespace ant;
using namespace ant::std_ext;
const constexpr auto GeV = 1000.0;
const constexpr auto me = 0.000510999; // mass electron [GeV]
/**
* @brief thetaCrit
* @return
*/
inline constexpr Double_t thetaCrit(const double Egmax) noexcept {
return me / Egmax;
}
struct Action {
unsigned nEvents;
string outfile;
double Emin;
double Emax;
virtual void Run() const =0;
virtual ~Action() = default;
};
struct PlutoAction : Action {
string reaction;
bool saveIntermediate;
bool enableBulk;
virtual void Run() const override;
};
struct GunAction : Action {
std::vector<string> particles;
unsigned nPerEvents;
double thetaMin;
double thetaMax;
virtual void Run() const override;
const static std::map<string,int> available_particles;
};
// these are the allowed particles for the gun with their pluto IDs
const std::map<string,int> GunAction::available_particles = {
{"p", 14},
{"g", 1},
{"e-", 3},
{"e+", 4},
{"pi+",8},
{"pi-",9}
};
/**
*@breif get a randomly choosen element from a vector
*@param v the vetor to draw from
*@return const reference to the element
*/
template <typename T>
const T& getRandomFrom(const std::vector<T>& v) {
const size_t index = floor(gRandom->Uniform(v.size()));
return v.at(index);
}
/**
*@brief get all keys of a map in a vector
*@param m the map to extract keys from
*@return vector of copies of the keys
*/
template <typename T, typename U>
std::vector<T> getKeys(const std::map<T,U>& m) {
vector<T> keys;
keys.reserve(m.size());
for(const auto& e : m) {
keys.emplace_back(e.first);
}
return keys;
}
int main( int argc, char** argv ) {
SetupLogger();
gRandom->SetSeed(); // Initialize ROOT's internal rng. Used for TF1s.
TCLAP::CmdLine cmd("Ant-pluto - Pluto single reaction generator for A2 Physics", ' ', "0.1");
// common options
auto cmd_numEvents = cmd.add<TCLAP::ValueArg<unsigned>> ("n", "numEvents", "Number of generated events", true, 0, "unsigned int");
auto cmd_outfile = cmd.add<TCLAP::ValueArg<string>> ("o", "outfile", "Output file", true, "pluto.root", "string");
auto cmd_Emin = cmd.add<TCLAP::ValueArg<double>> ("", "Emin", "Minimal incident energy [MeV]", false, 0.0, "double [MeV]");
auto cmd_Emax = cmd.add<TCLAP::ValueArg<double>> ("", "Emax", "Maximal incident energy [MeV]", false, 1.6*GeV, "double [MeV]");
auto cmd_verbose = cmd.add<TCLAP::ValueArg<int>> ("v", "verbose","Verbosity level (0..9)", false, 0,"int");
// reaction simulation options
// auto cmd_usePluto = cmd.add<TCLAP::SwitchArg> ("", "pluto", "Use pluto", false);
auto cmd_reaction = cmd.add<TCLAP::ValueArg<string>> ("", "reaction", "Reaction string in PLUTO notation", false, "", "string (Pluto Rection)");
auto cmd_noUnstable = cmd.add<TCLAP::SwitchArg>("", "no-unstable", "Don't unstable particles", false);
auto cmd_noBulk = cmd.add<TCLAP::SwitchArg> ("", "no-bulk", "Disable bulk decay of particles", false);
// random gun options
auto cmd_useGun = cmd.add<TCLAP::SwitchArg> ("", "gun", "Use random gun", false);
TCLAP::ValuesConstraintExtra<vector<string>> allowed_particles(getKeys(GunAction::available_particles));
auto cmd_randomparticles = cmd.add<TCLAP::MultiArg<string>> ("p", "particle", "Particle type to shoot", false, &allowed_particles);
auto cmd_numParticles = cmd.add<TCLAP::ValueArg<unsigned>> ("N", "particles-event", "Paricles per event", false, 1, "unsigned int");
auto cmd_thetaMin = cmd.add<TCLAP::ValueArg<double>> ("", "theta-min", "Minimal theta angle [deg]", false, 0.0, "double [deg]");
auto cmd_thetaMax = cmd.add<TCLAP::ValueArg<double>> ("", "theta-max", "Maximal theta angle [deg]", false, 180.0, "double [deg]");
cmd.parse(argc, argv);
if(cmd_verbose->isSet()) {
el::Loggers::setVerboseLevel(cmd_verbose->getValue());
}
if(cmd_useGun->isSet() && cmd_reaction->isSet()) {
LOG(ERROR) << "Can't use Pluto and random gun at the same time!";
return EXIT_FAILURE;
}
if(!cmd_useGun->isSet() && !cmd_reaction->isSet()) {
LOG(ERROR) << "Require one of --pluto , --gun";
return EXIT_FAILURE;
}
unique_ptr<Action> action;
if(cmd_useGun->isSet()) {
unique_ptr<GunAction> gunaction = std_ext::make_unique<GunAction>();
if(cmd_randomparticles->getValue().empty()) {
LOG(ERROR) << "Need particles for random gun! (--particle xxx)";
return EXIT_FAILURE;
}
gunaction->particles = cmd_randomparticles->getValue();
gunaction->nPerEvents = cmd_numParticles->getValue();
gunaction->thetaMin = degree_to_radian(cmd_thetaMin->getValue());
gunaction->thetaMax = degree_to_radian(cmd_thetaMax->getValue());
action = move(gunaction);
} else if(cmd_reaction->isSet()){
auto plutoaction = std_ext::make_unique<PlutoAction>();
plutoaction->reaction = cmd_reaction->getValue();
plutoaction->saveIntermediate = !(cmd_noUnstable->getValue());
plutoaction->enableBulk = !(cmd_noBulk->getValue());
action = move(plutoaction);
}
assert(action);
action->nEvents = cmd_numEvents->getValue();
action->outfile = cmd_outfile->getValue();
action->Emin = cmd_Emin->getValue();
action->Emax = cmd_Emax->getValue();
VLOG(2) << "gRandom is a " << gRandom->ClassName();
gRandom->SetSeed();
VLOG(2) << "gRandom initialized";
action->Run();
cout << "Simulation finished." << endl;
// Do not delete the reaction, otherwise: infinite loop somewhere in ROOT...
//delete reactrion;
return 0;
}
void PlutoAction::Run() const
{
VLOG(1) << "Running PlutoGun";
VLOG(1) << "number of Events: " << nEvents;
VLOG(1) << "Reaction: " << reaction;
VLOG(1) << "Photon Beam E min: " << Emin << " MeV";
VLOG(1) << "Photon Beam E max: " << Emax << " MeV";
VLOG(1) << "Save Intermediate: " << saveIntermediate;
VLOG(1) << "Enable bulk decays: " << enableBulk;
PBeamSmearing *smear = new PBeamSmearing(strdup("beam_smear"), strdup("Beam smearing"));
smear->SetReaction(strdup("g + p"));
TF1* tagger_spectrum = new TF1("bremsstrahlung","(1.0/x)", Emin/GeV, Emax/GeV);
smear->SetMomentumFunction( tagger_spectrum );
TF1* theta_smear = new TF1( "angle", "x / ( x*x + [0] )^2", 0.0, 5.0 * thetaCrit(Emax/GeV) );
theta_smear->SetParameter( 0, thetaCrit(Emax/GeV) * thetaCrit(Emax/GeV) );
smear->SetAngularSmearing( theta_smear );
makeDistributionManager()->Add(smear);
ant::simulation::mc::UpdatePluteDataBase();
// remove file ending because pluto attaches a ".root"...
string outfile_clean(outfile);
if(string_ends_with(outfile_clean, ".root")) {
outfile_clean = outfile_clean.substr(0,outfile_clean.size()-5);
}
/// @note: not using unique_ptr here because deleting the PReaction crashes. Leeking on purpose here.
PReaction* Pluto_reaction = new PReaction(Emax/GeV, strdup("g"), strdup("p"),
strdup(reaction.c_str()), strdup(outfile_clean.c_str()),
saveIntermediate, 0, 0, 0);
if( enableBulk ) {
PPlutoBulkDecay* p1 = new PPlutoBulkDecay();
p1->SetRecursiveMode(1);
p1->SetTauMax(0.001);
Pluto_reaction->AddBulk(p1);
}
Pluto_reaction->Print(); //The "Print()" statement is optional
Pluto_reaction->Loop(nEvents);
//Pluto_reaction->Close(); // no using -> crashes
}
void GunAction::Run() const
{
VLOG(1) << "Running RandomGun";
VLOG(1) << "number of Events: " << nEvents;
VLOG(1) << "number of particles: " << nPerEvents;
VLOG(1) << "Particles: " << particles;
VLOG(1) << "E min: " << Emin << " MeV";
VLOG(1) << "E max: " << Emax << " MeV";
VLOG(1) << "Theta min: " << radian_to_degree(thetaMin) << " degree";
VLOG(1) << "Theta max: " << radian_to_degree(thetaMax) << " degree";
auto db = makeStaticData();
WrapTFileOutput file(outfile, WrapTFileOutput::mode_t::recreate, false);
TTree* tree = file.CreateInside<TTree>("data","Random Particles");
TClonesArray* particles_array = new TClonesArray("PParticle", nPerEvents);
particles_array->SetOwner(kTRUE);
tree->Branch("Particles", particles_array);
std::vector<int> ids;
ids.reserve(particles.size());
for(const auto& p : particles) {
ids.push_back(available_particles.at(p));
}
for( unsigned i=0; i< nEvents; ++i ) {
particles_array->Clear();
for( unsigned j=0; j<nPerEvents; ++j ) {
const int pID = ids.size()==1 ? ids[0] : getRandomFrom(ids);
const double m = db->GetParticleMass(pID);
const double E = gRandom->Uniform(Emax/GeV)+m;
const double p = sqrt(E*E - m*m);
ant::vec3 dir;
do {
gRandom->Sphere(dir.x, dir.y, dir.z, p);
} while (dir.Theta() > thetaMax || dir.Theta() < thetaMin);
PParticle* part = new PParticle( pID, dir);
(*particles_array)[j] = part;
}
tree->Fill();
}
}
|
#ifndef ANNUAIRE
#define ANNUAIRE
#include <iostream>
#include <vector>
#include <fstream>
#include "contact.h"
using namespace std;
class Annuaire
{
public:
Annuaire(){}
void lister();
void ajout_debut(Contact contact);
void ajout_fin(Contact contact);
void rechercher();
void charger(string fichier);
void enregistrer(string fichier);
void modifier();
void supprimer(); //rechercher et supprimer
void effecteur(int choix);
private:
std::vector<Contact> contacts;
};
#endif |
#include "stdafx.h"
// From http://rosettacode.org/wiki/Color_quantization/C
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
//#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
typedef struct {
int w, h;
unsigned char *pix;
} image_t, *image;
image img_new(int w, int h)
{
image im = (image)malloc(sizeof(image_t) + h * w * 3);
im->w = w; im->h = h;
im->pix = (unsigned char *)(im + 1);
return im;
}
#define ON_INHEAP 1
typedef struct oct_node_t oct_node_t, *oct_node;
struct oct_node_t{
int64_t r, g, b; /* sum of all child node colors */
int count, heap_idx;
unsigned char n_kids, kid_idx, flags, depth;
oct_node kids[8], parent;
};
typedef struct {
int alloc, n;
oct_node* buf;
} node_heap;
inline int cmp_node(oct_node a, oct_node b)
{
if (a->n_kids < b->n_kids) return -1;
if (a->n_kids > b->n_kids) return 1;
int ac = a->count >> a->depth;
int bc = b->count >> b->depth;
return ac < bc ? -1 : ac > bc;
}
void down_heap(node_heap *h, oct_node p)
{
int n = p->heap_idx, m;
while (1) {
m = n * 2;
if (m >= h->n) break;
if (m + 1 < h->n && cmp_node(h->buf[m], h->buf[m + 1]) > 0) m++;
if (cmp_node(p, h->buf[m]) <= 0) break;
h->buf[n] = h->buf[m];
h->buf[n]->heap_idx = n;
n = m;
}
h->buf[n] = p;
p->heap_idx = n;
}
void up_heap(node_heap *h, oct_node p)
{
int n = p->heap_idx;
oct_node prev;
while (n > 1) {
prev = h->buf[n / 2];
if (cmp_node(p, prev) >= 0) break;
h->buf[n] = prev;
prev->heap_idx = n;
n /= 2;
}
h->buf[n] = p;
p->heap_idx = n;
}
void heap_add(node_heap *h, oct_node p)
{
if ((p->flags & ON_INHEAP)) {
down_heap(h, p);
up_heap(h, p);
return;
}
p->flags |= ON_INHEAP;
if (!h->n) h->n = 1;
if (h->n >= h->alloc) {
while (h->n >= h->alloc) h->alloc += 1024;
h->buf = (oct_node*)realloc(h->buf, sizeof(oct_node) * h->alloc);
}
p->heap_idx = h->n;
h->buf[h->n++] = p;
up_heap(h, p);
}
oct_node pop_heap(node_heap *h)
{
if (h->n <= 1) return 0;
oct_node ret = h->buf[1];
h->buf[1] = h->buf[--h->n];
h->buf[h->n] = 0;
h->buf[1]->heap_idx = 1;
down_heap(h, h->buf[1]);
return ret;
}
static oct_node pool = 0;
static int len = 0;
oct_node node_new(unsigned char idx, unsigned char depth, oct_node p)
{
if (len <= 1) {
oct_node p = (oct_node)calloc(sizeof(oct_node_t), 2048);
p->parent = pool;
pool = p;
len = 2047;
}
oct_node x = pool + len--;
x->kid_idx = idx;
x->depth = depth;
x->parent = p;
if (p) p->n_kids++;
return x;
}
void node_free()
{
oct_node p;
while (pool) {
p = pool->parent;
free(pool);
pool = p;
}
}
oct_node node_insert(oct_node root, unsigned char *pix)
{
unsigned char i, bit, depth = 0;
for (bit = 1 << 7; ++depth < 8; bit >>= 1) {
i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
if (!root->kids[i])
root->kids[i] = node_new(i, depth, root);
root = root->kids[i];
}
root->r += pix[0];
root->g += pix[1];
root->b += pix[2];
root->count++;
return root;
}
oct_node node_fold(oct_node p)
{
if (p->n_kids) abort();
oct_node q = p->parent;
q->count += p->count;
q->r += p->r;
q->g += p->g;
q->b += p->b;
q->n_kids--;
q->kids[p->kid_idx] = 0;
return q;
}
void color_replace(oct_node root, unsigned char *pix, uint8_t *sciPix)
{
unsigned char i, bit;
for (bit = 1 << 7; bit; bit >>= 1) {
i = !!(pix[1] & bit) * 4 + !!(pix[0] & bit) * 2 + !!(pix[2] & bit);
if (!root->kids[i]) break;
root = root->kids[i];
}
pix[0] = (unsigned char) root->r;
pix[1] = (unsigned char)root->g;
pix[2] = (unsigned char)root->b;
assert(root->heap_idx <= 256);
*sciPix = (uint8_t)(root->heap_idx - 1);
}
oct_node nearest_color(int *v, node_heap *h) {
int i;
int diff, max = 100000000;
oct_node o = 0;
for (i = 1; i < h->n; i++) {
diff = (int)( 3 * abs(h->buf[i]->r - v[0])
+ 5 * abs(h->buf[i]->g - v[1])
+ 2 * abs(h->buf[i]->b - v[2]));
if (diff < max) {
max = diff;
o = h->buf[i];
}
}
return o;
}
#define POS(i, j) (3 * ((i) * im->w + (j)))
#define C10 7
#define C01 5
#define C11 2
#define C00 1
#define CTOTAL (C00 + C11 + C10 + C01)
#define clamp(x, i) if (x[i] > 255) x[i] = 255; if (x[i] < 0) x[i] = 0
void error_diffuse(image im, node_heap *h)
{
int i, j;
int *npx = (int*)calloc(sizeof(int), im->h * im->w * 3), *px;
int v[3];
unsigned char *pix = im->pix;
oct_node nd;
for (px = npx, i = 0; i < im->h; i++) {
for (j = 0; j < im->w; j++, pix += 3, px += 3) {
px[0] = (int)pix[0] * CTOTAL;
px[1] = (int)pix[1] * CTOTAL;
px[2] = (int)pix[2] * CTOTAL;
}
}
pix = im->pix;
for (px = npx, i = 0; i < im->h; i++) {
for (j = 0; j < im->w; j++, pix += 3, px += 3) {
px[0] /= CTOTAL;
px[1] /= CTOTAL;
px[2] /= CTOTAL;
clamp(px, 0); clamp(px, 1); clamp(px, 2);
nd = nearest_color(px, h);
v[0] = (int)(px[0] - nd->r);
v[1] = (int)(px[1] - nd->g);
v[2] = (int)(px[2] - nd->b);
pix[0] = (unsigned char)nd->r;
pix[1] = (unsigned char)nd->g;
pix[2] = (unsigned char)nd->b;
if (j < im->w - 1) {
npx[POS(i, j + 1) + 0] += v[0] * C10;
npx[POS(i, j + 1) + 1] += v[1] * C10;
npx[POS(i, j + 1) + 2] += v[2] * C10;
}
if (i >= im->h - 1) continue;
npx[POS(i + 1, j) + 0] += v[0] * C01;
npx[POS(i + 1, j) + 1] += v[1] * C01;
npx[POS(i + 1, j) + 2] += v[2] * C01;
if (j < im->w - 1) {
npx[POS(i + 1, j + 1) + 0] += v[0] * C11;
npx[POS(i + 1, j + 1) + 1] += v[1] * C11;
npx[POS(i + 1, j + 1) + 2] += v[2] * C11;
}
if (j) {
npx[POS(i + 1, j - 1) + 0] += v[0] * C00;
npx[POS(i + 1, j - 1) + 1] += v[1] * C00;
npx[POS(i + 1, j - 1) + 2] += v[2] * C00;
}
}
}
free(npx);
}
void color_quant(image im, int n_colors, int dither, uint8_t *sciBits, RGBQUAD *tempPalette)
{
int i;
unsigned char *pix = im->pix;
node_heap heap = { 0, 0, 0 };
oct_node root = node_new(0, 0, 0), got;
for (i = 0; i < im->w * im->h; i++, pix += 3)
heap_add(&heap, node_insert(root, pix));
while (heap.n > n_colors + 1)
heap_add(&heap, node_fold(pop_heap(&heap)));
double c;
for (i = 1; i < heap.n; i++) {
got = heap.buf[i];
c = got->count;
got->r = (int64_t)(got->r / c + .5);
got->g = (int64_t)(got->g / c + .5);
got->b = (int64_t)(got->b / c + .5);
// Red and blue are inverted.
tempPalette[i - 1].rgbRed = (BYTE)got->b;
tempPalette[i - 1].rgbGreen = (BYTE)got->g;
tempPalette[i - 1].rgbBlue = (BYTE)got->r;
}
if (dither) error_diffuse(im, &heap);
else
for (i = 0, pix = im->pix; i < im->w * im->h; i++, pix += 3, sciBits++)
color_replace(root, pix, sciBits);
node_free();
free(heap.buf);
// pfortier: added to work around crappy code:
free(pool);
len = 0;
pool = nullptr;
}
// Returns a 24bit RGB bitmap from an input bitmap. *pDIBBits points to the resulting bits.
HBITMAP BitmapToRGB32Bitmap(const BITMAPINFO *pbmi, int desiredWidth, int desiredHeight, void **pDIBBits32)
{
HBITMAP bmpReturn = nullptr;
void *pDIBBits = _GetBitsPtrFromBITMAPINFO(pbmi);
if (pDIBBits)
{
CDC dc;
if (dc.CreateCompatibleDC(nullptr))
{
BITMAPINFO bitmapInfo;
bitmapInfo.bmiHeader.biSize = sizeof(bitmapInfo.bmiHeader);
bitmapInfo.bmiHeader.biWidth = desiredWidth;
bitmapInfo.bmiHeader.biHeight = desiredHeight;
bitmapInfo.bmiHeader.biPlanes = 1;
bitmapInfo.bmiHeader.biBitCount = 32;
bitmapInfo.bmiHeader.biCompression = BI_RGB;
bitmapInfo.bmiHeader.biSizeImage = 0; // 0 is ok for BI_RGB
bitmapInfo.bmiHeader.biXPelsPerMeter = 0; // ???
bitmapInfo.bmiHeader.biYPelsPerMeter = 0; // ???
bitmapInfo.bmiHeader.biClrUsed = 0; // ???
bitmapInfo.bmiHeader.biClrImportant = 0; // ???
bmpReturn = CreateDIBSection((HDC)dc, &bitmapInfo, DIB_RGB_COLORS, pDIBBits32, nullptr, 0);
if (bmpReturn)
{
// Select our new HBITMAP into the DC
HGDIOBJ hgdiObjOld = SelectObject((HDC)dc, bmpReturn);
StretchDIBits((HDC)dc,
0, 0, desiredWidth, desiredHeight,
0, 0, pbmi->bmiHeader.biWidth, pbmi->bmiHeader.biHeight,
pDIBBits, pbmi, DIB_RGB_COLORS, SRCCOPY);
SelectObject((HDC)dc, hgdiObjOld);
}
}
}
return bmpReturn;
}
// globalPalette needs to have empty slots.
// data has no specific stride
// data's alpha should have been stripped (either on or off)
std::unique_ptr<uint8_t[]> QuantizeImage(const RGBQUAD *data, int width, int height, const RGBQUAD *globalPalette, RGBQUAD *imagePaletteResult, int transparentIndex, bool excludeTransparentColorFromPalette)
{
RGBQUAD black = {};
int outStride = CX_ACTUAL(width);
// REVIEW: We will have to do this for views.
size_t bitmapLength = width * height;
std::unique_ptr<uint8_t[]> sciBits = std::make_unique<uint8_t[]>(bitmapLength);
std::unique_ptr<bool[]> opaqueMask = std::make_unique<bool[]>(bitmapLength);
std::vector<uint8_t> unusedIndices;
// 1) count the number of colors we can use by looking at empty palette slots
int colorCount = 0;
for (int i = 0; i < 256; i++)
{
if (
(!excludeTransparentColorFromPalette || (i != transparentIndex)) &&
(!globalPalette || (globalPalette[i].rgbReserved == 0x0)))
{
colorCount++;
unusedIndices.push_back((uint8_t)i);
}
else
{
// Copy it over but mark it as unused.
imagePaletteResult[i] = globalPalette ? globalPalette[i] : black;
imagePaletteResult[i].rgbReserved = 0x1;
}
}
if (colorCount > 0)
{
// Now our pDIBBits32 should point to the raw bitmap data.
image img = img_new(width, height);
// Copy our data into img used by the algorithm, which is 3 bytes per pixel.
for (int y = 0; y < height; y++)
{
unsigned char* dest = img->pix + (y * width * 3);
for (int x = 0; x < width; x++)
{
const RGBQUAD *src = data + (y * width) + x;
// The 4th source byte is alpha.
bool isOpaque = (src->rgbReserved == 0xff);
opaqueMask[y * width + x] = isOpaque;
// Note: for transparent pixels, we'll still evaluate colors. Oh well. Hopefully they'll be all black.
// Let's make them black
// TODO/REVIEW: We should modify our quantization algorithm so it doesn't pay attention to the transparent colors. i.e. make image be one dimensional
RGBQUAD toUse = *src;
if (!isOpaque)
{
toUse.rgbBlue = 0;
toUse.rgbGreen = 0;
toUse.rgbRed = 0;
}
*dest++ = toUse.rgbBlue;
*dest++ = toUse.rgbGreen;
*dest++ = toUse.rgbRed;
}
}
RGBQUAD usedColors[256];
color_quant(img, colorCount, 0, sciBits.get(), usedColors);
// sciBits will now contain values from 0 to colorCount (exclusive), and usedColors will contain the RGB values for those indices.
// unusedIndices contains the real palette indices where we want to put these things.
for (int i = 0; i < (int)bitmapLength; i++)
{
if (opaqueMask[i])
{
sciBits[i] = unusedIndices[sciBits[i]];
}
else
{
sciBits[i] = (uint8_t)transparentIndex;
}
}
for (int i = 0; i < colorCount; i++)
{
imagePaletteResult[unusedIndices[i]] = usedColors[i];
imagePaletteResult[unusedIndices[i]].rgbReserved = 0x3;
}
free(img);
}
if (outStride != width)
{
// An extra copy when stride doesn't match width
std::unique_ptr<uint8_t[]> sciBitsReturn = std::make_unique<uint8_t[]>(outStride * height);
for (int y = 0; y < height; y++)
{
memcpy(sciBitsReturn.get() + y * outStride, sciBits.get() + y * width, width);
}
return sciBitsReturn;
}
else
{
return sciBits;
}
}
|
#include <chrono>
#include <iostream>
#include <thread>
using namespace std;
void fun()
{
this_thread::sleep_for(chrono::seconds(3));
cout << "fun thread id = " << this_thread::get_id() << endl;
}
int main(int argc, char *argv[])
{
thread t(fun);
cout << "t thread id = " << t.get_id() << endl;
cout << "main thread id = " << this_thread::get_id() << endl;
cout << "cpu count = " << thread::hardware_concurrency() << endl;
t.join();
return 0;
} |
#include <mpi.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <list>
#include <random>
using namespace std;
#define DEBUG
# define T 4
void uso(string nombre_prog);
void obt_args(char* argv[], int& numeroPersonas, double& infeccion, double& recuperacion, int& duracion, double& infectadas, int& size);
void iniciar(int *matriz, int& nPersonas, int& nInicialInfectados, int &size)
{
default_random_engine generator;
uniform_int_distribution <int> distributionXY(0, size - 1);
uniform_int_distribution <int> distribution12(1, 2);
//aqui estamos llenando el vector con los enfermos que se tienen como parametro
for (int iter = 0; iter < nInicialInfectados * T; iter += T)
{
*(matriz + iter) = 3; //Estado 3 (Infectado)
*(matriz + iter + 1) = 0; //Dias infectados
*(matriz + iter + 2) = distributionXY(generator); //Posición en Eje-X
*(matriz + iter + 3) = distributionXY(generator); //Posición en Eje-Y
}
//llenamos el vector con la demas cantidad de personas que no estan infectadas, se hace un random que decide si es inmune o sano
for (int iter = nInicialInfectados * 4; iter<nPersonas * T; iter += T)
{
*(matriz + iter) = distribution12(generator); //Estado 1 (Inmune) o 2 (Sano)
*(matriz + iter + 1) = 0; //Dias infectados
*(matriz + iter + 2) = distributionXY(generator); //Posición en Eje-X
*(matriz + iter + 3) = distributionXY(generator); //Posición en Eje-Y
}
}
//metodo que imprime el vector
void imprimir(int const *matriz, int& nPersonas)
{
for (int iter = 0; iter < nPersonas * T; iter += T)
{
cout << *(matriz + iter)
<< " " << *(matriz + iter + 1)
<< " X " << *(matriz + iter + 2)
<< " Y " << *(matriz + iter + 3)
<< "\t\t";
}
}
//Método que verifica si una persona se puede contagiar y dependiendo de cuantos enfermos esten en esa posicion aumenta la posibilidad de enfermarse de los sanos
//void validar(int *arreglito, int *matriz, int& nPersonas, int& cnt_proc, int& iter, int& duracion, double& recuperacion, double& infeccion, int& nInfectados, int& tCuradas, int& tMuertas, int& tSanas)
void validar(int *matriz, int& nPersonas, int& cnt_proc, int& mid, int& iter, int& duracion, double& recuperacion, double& infeccion, int& nInfectados, int& tCuradas, int& tMuertas, int& tSanas)
{
/*NOTA: los enfermosRestantes se pueden estar contando doble, mejor hacer un solo ciclo que busque cuántos enfermos hay, incluso se pdoria hacer en otro método*/
default_random_engine generator;
uniform_real_distribution <double> proba(0, 1);
//int enfermosRestantes=0;
//enfermosRestantes=0;
int posicionEnfermos=1, contador=mid*(nPersonas / cnt_proc)*T;
for (contador; contador < (mid*(nPersonas / cnt_proc)*T+ (nPersonas / cnt_proc)*T); contador += T)
{
/*cout<<"ARREGLITO\n" << *(arreglito + iter)
<< " " << *(arreglito + iter + 1)
<< " X " << *(arreglito + iter + 2)
<< " Y " << *(arreglito + iter + 3)
<< "\t\t";*/
//if (*(arreglito + contador) == 2) //Persona sana
if(*(matriz+contador)==2)
++tSanas;
else
{
posicionEnfermos = 1;
//if (*(arreglito + contador) == 3) //Si está infectado:
if(*(matriz + contador) == 3)
{ // 1-Busca infectar a los que pueda
//++enfermosRestantes;
//cout << "Infectado\n";
for (int i = 0; i < nPersonas*T; i += T) //Busca los enfermos en la misma posición que el enfermo actual
{
/*if (*(arreglito + contador + 2) == *(matriz + i + 2) &&
*(arreglito + contador + 3) == *(matriz + i + 3) &&
*(matriz + i) == 3)*/
if (*(matriz + contador + 2) == *(matriz + i + 2) &&
*(matriz + contador + 3) == *(matriz + i + 3) &&
*(matriz + i) == 3)
{
++posicionEnfermos;
}
}
for (int i = 0; i < nPersonas*T; i += T)
{
//if (*(arreglito + contador + 2) == *(matriz + i + 2) && //Si el enfermo está en la misma celda que el enfermo y además está sano
// *(arreglito + contador + 3) == *(matriz + i + 3) &&
// *(matriz + i) == 2)
if (*(matriz + contador + 2) == *(matriz + i + 2) && //Si el enfermo está en la misma celda que el enfermo y además está sano
*(matriz + contador + 3) == *(matriz + i + 3) &&
*(matriz + i) == 2)
{
//Hacer el calculo de la probabilidad y asignar el nuevo estado en caso de darse el contagio
if (proba(generator)*posicionEnfermos < infeccion)
{
cout << "\t INFECTA" << endl;
//cout << *(arreglito + contador)<<" ";
*(matriz + i) = 3;
//++enfermosRestantes;
++nInfectados;
--tSanas;
/*cout << *(arreglito + contador)
<< " " << *(arreglito + contador + 1)
<< " X " << *(arreglito + contador + 2)
<< " Y " << *(arreglito + contador +3)
<< "\t\t";*/
}
}
}
// 2-Verifica si ya es tiempo de morir o de recuperarse
//if (*(arreglito + contador + 1) == duracion)
if (*(matriz + contador + 1) == duracion)
{
if (proba(generator) < recuperacion)//Calcular probabilidad de recuperacion o de muerte de acuerdo a @recuperacion
{
//*(arreglito + contador + 1) = 0; //Se actualiza el estado a Muerto=0
*(matriz + contador) = 0; //Se actualiza el estado a Muerto=0
cout << "\t MUERE" << endl; //Incrementar muertos totales (tMuertas)
++tMuertas;
}
else
{
//*(arreglito + contador + 1) = 1; //Se convierte a Inmune i.e. se sana
*(matriz + contador) = 1; //Se convierte a Inmune i.e. se sana
cout << "\t CURA" << endl; //Actualizar el contador de Curadas
++tCuradas;
}
//--enfermosRestantes;
}
}
}
}
//return enfermosRestantes;
}
//Mueve a la persona si no está muerta; en caso de estar infectada, aumenta el tiempo que ha estado infectado
//void simulacion(int *arreglito, int *matriz, int& nPersonas, int& cnt_proc, int& nInfectados, int& size, int inicio)
void simulacion(int *matriz, int& nPersonas, int& cnt_proc, int& mid, int& nInfectados, int& size, int inicio)
{
default_random_engine generator;
uniform_int_distribution <int> distributionXY(0, 1);
//for (int iter = 0; iter < nPersonas/cnt_proc*T; iter += T)
for (int iter = mid * (nPersonas / cnt_proc)*T; iter < mid*(nPersonas / cnt_proc)*T+ (nPersonas / cnt_proc)*T; iter += T)
{
//if (*(arreglito + iter) == 3) //Estado 3 (Infectado)
if (*(matriz + iter) == 3)
matriz[iter + 1] = matriz[iter + 1] + 1; //Dias infectados
//if (*(arreglito + iter) != 0) //Si la persona no está muerta (Estado 0) se desplaza por el espacio
if (*(matriz + iter) != 0)
{
if (!distributionXY(generator)) //se moverá un espacio a la derecha
{
//*(arreglito + iter + 2) = (*(arreglito + iter + 2) -1); //Movimiento en Eje-X
*(matriz + iter + 2) = (*(matriz + iter + 2) - 1); //Movimiento en Eje-X
/*if (*(arreglito + iter + 2) < 0)
*(arreglito + iter + 2) = size - 1;*/
if (*(matriz + iter + 2) < 0)
*(matriz + iter + 2) = size - 1;
}
else //Movimiento hacia la izquierda
//*(arreglito + iter + 2) = (*(arreglito + iter + 2) + 1) % size;
*(matriz + iter + 2) = (*(matriz + iter + 2) + 1) % size;
if (!distributionXY(generator)) //se moverá un espacio hacia abajo
{
//*(arreglito + iter + 3) = (*(arreglito + iter + 3) -1); //Movimiento en Eje-Y
*(matriz + iter + 3) = (*(matriz + iter + 3) - 1); //Movimiento en Eje-Y
/*if (*(arreglito + iter + 3) < 0)
*(arreglito + iter + 3) = size - 1;*/
if (*(matriz + iter + 3) < 0)
*(matriz + iter + 3) = size - 1;
}
else //se moverá un espacio hacia arriba
//*(arreglito + iter + 3) = (*(arreglito + iter + 3) +1) % size;
*(matriz + iter + 3) = (*(matriz + iter + 3) + 1) % size;
}
}
/*cout << "\n\n MOVIMIENTO\n\n";
for (int iter = 0; iter < nPersonas/cnt_proc * T; iter += T)
{
cout << *(arreglito + iter)
<< " " << *(arreglito + iter + 1)
<< " X " << *(arreglito + iter + 2)
<< " Y " << *(arreglito + iter + 3)
<< "\t\t";
}*/
}
//int cuentaInfectados(int *arreglito, int& nPersonas, int& cnt_proc)
int cuentaInfectados(int *matriz, int& nPersonas, int& cnt_proc, int& mid)
{
int enfermosRestantes = 0;
//for (int i=0; i < (nPersonas / cnt_proc) *T; i += T)
for (int i = mid * (nPersonas / cnt_proc)*T; i < mid * (nPersonas / cnt_proc)*T+(nPersonas / cnt_proc)*T; i += T)
{
//if (*(arreglito + i) == 3)
if (*(matriz + i) == 3)
++enfermosRestantes;
}
return enfermosRestantes;
}
int main(int argc, char* argv[]) {
int mid;
int cnt_proc;
MPI_Status mpi_status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mid);
MPI_Comm_size(MPI_COMM_WORLD, &cnt_proc);
#ifdef debug
if (mid == 0)
cin.ignore();
MPI_Barrier(MPI_COMM_WORLD);
#endif
//aqui va el codigo
int nPersonas, duracion, size, tics=0;
int tInfectadas, tSanas, tCuradas, tInmunes, tMuertas; //Contadores para las estadísticas de cada tic
int infectadasT=0, sanasT=0, curadasT=0, inmunesT=0, muertasT=0; //Contadores para las estadísticas finales
double infeccion, recuperacion, infectadas;
double tPared; //t=tiempo
int veces; //Será el numero de personas entre la cantidad de procesos
obt_args(argv, nPersonas, infeccion, recuperacion, duracion, infectadas, size);
int *matriz = new int[nPersonas*4]; //puntero al a un arreglo que simula dos dimensiones por donde se van a desplazar las personas
//int *matriz2 = new int[nPersonas * 4];
int nInicialInfectados = nPersonas * infectadas;
//int *matrizTemporal = (int*)calloc(tamanio, sizeof(int));
if (mid == 0) //Creación de la matriz en el proceso principal
{
cout << "\t MATRIZ INICIAL" << endl << endl;
iniciar(matriz, nPersonas, nInicialInfectados, size); //Comienza la simulación
imprimir(matriz, nPersonas);
}
int enfermosRestantes = 0, enfermosTic = 0;
do
{
enfermosTic = 0; tInfectadas = 0, tCuradas=0, tSanas=0, tMuertas=0; //Establece los valores para las estadisticas de cada tic
cout << "Enfermos Tic: " << enfermosTic <<" @ "<<mid<<endl<<endl;
MPI_Bcast(matriz, nPersonas - 1, MPI_INT, 0, MPI_COMM_WORLD); //Comparte el espacio (matriz) con todos los procesos
// int *temp = new int[nPersonas*T];
//int *arreglito = new int[(nPersonas / cnt_proc) *T];
//temp=matriz;
//MPI_Scatter(matriz, nPersonas/cnt_proc*T, MPI_INT, arreglito, nPersonas / cnt_proc * T, MPI_INT, 0, MPI_COMM_WORLD); //Se separa el espacio total entre los procesos para realizar las verificaciones correspondientes
//Se elimina el scatter porque en caso de dejarlo, se debe volver a compartir los datos, lo mejor es trabajar solo sobre matriz
//VALIDAR: Realiza los contagios, sanaciones o muertes de cada persona
int inicio = (int)((nPersonas / cnt_proc) * mid*T);
//validar(arreglito, matriz, nPersonas, cnt_proc, inicio, duracion, recuperacion, infeccion, tInfectadas, tCuradas, tMuertas, tSanas);
validar(matriz, nPersonas, cnt_proc, mid, inicio, duracion, recuperacion, infeccion, tInfectadas, tCuradas, tMuertas, tSanas);
/*
Llamar a la función cuentaInfectados
//al descomentar esto debería de correr
enfermosTic=cuentaInfectados(int *arreglito, int& nPersonas, int& cnt_proc);
*/
//SIMULAR: realiza los movimientos
//simulacion(arreglito,matriz, nPersonas, cnt_proc, nInicialInfectados, size, inicio);
simulacion(matriz, nPersonas, cnt_proc, mid, nInicialInfectados, size, inicio);
if (mid == 0)
{
cout << "\nIMPRESION MATRIZ @" <<tics<< endl;
imprimir(matriz, nPersonas);
}
//enfermosTic = cuentaInfectados(arreglito, nPersonas, cnt_proc);
enfermosTic = cuentaInfectados(matriz, nPersonas, cnt_proc, mid);
//Provoca que se encicle, ver nota al final (Ver. 4-12, no se encicla)
MPI_Allreduce(&enfermosTic, &enfermosRestantes, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); //Reduce al contador de enfermos restantes por el espacio
//Se incrementa el acumulador total de personas infectadas
cout << "Enfermos restantes: " <<enfermosTic<<" / "<< enfermosRestantes << " @ " << mid << endl;
/* hacer un barrier; Acá sería crear una submatriz que copie un rango dado por el rango y la cantidad de personas, luego hacer un free
al puntero de matriz, para luego paro medio de un gather reunir en el proceso 0 todas las submatrices y compartirlas en el Bcast al inicio del ciclo */
//MPI_Allgather(arreglito, (nPersonas / cnt_proc) *T, MPI_INT, matriz, (nPersonas / cnt_proc) *T, MPI_INT, MPI_COMM_WORLD);
/*if (mid == 0)
{
cout << "Enfermos restantes luego del Allgather: " << enfermosRestantes<<endl;
}*/
//Actualización de la cantidad de personas que se han infectado, curado o muerto y la cantidad de sanos que hay en el tic actual
infectadasT += tInfectadas;
curadasT += tCuradas;
muertasT += tMuertas;
sanasT += tSanas;
++tics; //Se incrementa el contador que indica la cantidad de tics
/*
OTRA POSIBLE SOLUCION:
crear un arreglo temporal que tenga toda la matriz para poder ir comparando
con un scatter, distribuir la matriz entre los procesos y recorrerla como en validar
finalizar con un allgather a matriz
*/
/*if (mid == 0)
{
MPI_Gather(arreglito, (nPersonas / cnt_proc) *T, MPI_INT, temp, (nPersonas / cnt_proc) *T, MPI_INT,0, MPI_COMM_WORLD);
}
else
{
MPI_Gather(arreglito, (nPersonas / cnt_proc) *T, MPI_INT, temp, (nPersonas / cnt_proc) *T, MPI_INT, 0, MPI_COMM_WORLD);
}
MPI_Barrier(MPI_COMM_WORLD);*/
//matriz = temp;
// free(temp);
//free(arreglito);
//enviar al archivo de salida y al buffer los resultados de la TIC actual
} while (enfermosRestantes !=0);
//Camabiar los parametros de entrada y salida, hacer para muertas, inmunes, infectadas y sanas
MPI_Barrier(MPI_COMM_WORLD);
//Reducción de la cantidad de personas que se han infectado, curado o muerto a lo largo de la simulación, así como la cantidad de sanos restantes
int sanos=0, muertos = 0, infectados = 0, curados = 0;
MPI_Reduce(&infectadasT, &infectados, MPI_INT, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); //Reduce el total de infectados
MPI_Reduce(&sanasT, &sanos, MPI_INT, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); //Reduce el total de sanos
MPI_Reduce(&muertasT, &muertos, MPI_INT, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); //Reduce el total de muertos
MPI_Reduce(&tCuradas, &curados, MPI_INT, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); //Reduce el total de curados
#ifdef DEBUG //Impresion en otro proceso par acomprobar el Bcast
if (mid == 1)
{
cout << "MATRIZ DESDE PROCESO FINAL" << endl;
imprimir(matriz, nPersonas);
}
#endif
free(matriz); //Liberación de la memoria ocupada
int n;
MPI_Allreduce(&tics, &n, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
if (mid == 0)
{
//cout << endl << endl << "Time: " << elapsed << "s" << endl;
cout << endl << "TICS totales: " <<tics<< endl;
cin.ignore();
}
MPI_Finalize();
return 0;
}
void uso(string nombre_prog) {
cerr << nombre_prog.c_str() << " secuencia de parametros de entrada " << endl;
exit(0);
}
void obt_args(char* argv[], int& numeroPersonas, double& infeccion, double& recuperacion, int& duracion, double& infectadas, int& size) {
numeroPersonas = strtol(argv[1], NULL, 10);
infeccion = stod(argv[2]);
recuperacion = stod(argv[3]);
duracion = strtol(argv[4], NULL, 10);
infectadas = stod(argv[5]);
size = strtol(argv[6], NULL, 10);
if (numeroPersonas < 0)
{
do {
cout << "\t Numero de personas invalido, digite otra cifra [0, 10.000.000]: ";
cin >> numeroPersonas;
} while (numeroPersonas < 0);
}
if (infeccion < 0 || infeccion>1)
{
do {
cout << "\t Probabilidad infecciosa invalida, digite otra cifra [0, 1]: ";
cin >> infeccion;
} while (infeccion < 0 || infeccion>1);
}
if (recuperacion < 0 || recuperacion>1)
{
do {
cout << "\t Probabilidad de recuperacion invalida, digite otra cifra [0, 1]: ";
cin >> recuperacion;
} while (recuperacion < 0 || recuperacion>1);
}
if (duracion < 5 || duracion>50)
{
do {
cout << "\t Duracion infecciosa maxima invalida, digite otra cifra [0, 50]: ";
cin >> duracion;
} while (duracion < 5 || duracion>50);
}
if (infectadas < 0 || infectadas>1)
{
do {
cout << "\t Porcentaje personas incialmente infectadas invalido, digite otra cifra [0, 10]: ";
cin >> infectadas;
} while (infectadas < 0 || infectadas>1);
}
if (size < 1 || size>3)
{
do {
cout << "\t Tamano invalido, digite otra cifra: \n"
<< "\t 1) 100x100" << endl
<< "\t 2) 500x500" << endl
<< "\t 3) 1000x1000" << endl;
cin >> size;
} while (size < 1 || size>3);
}
switch (size)
{
case 1: size = 6/*100*/; break;
case 2: size = 500; break;
case 3: size = 1000; break;
}
} |
#pragma once
#include <iostream>
#include <vector>
#include "Map.h"
#include "SaveLoadFormat.h"
using namespace std;
class SaveLoadAdapter: SaveLoadFormat
{
public:
static Map SaveLoadAdapter::readMap(string);
static void SaveLoadAdapter::saveMap(string, Map);
}; |
/**
*
* This file contains code snippets from the documentation as a reference.
*
* Please do not change this file unless you change the corresponding snippets
* in the documentation as well!
*
**/
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <tudocomp/Algorithm.hpp>
using namespace tdc;
// Base class, merely required for the Registry example
class MyAlgorithmBase : public Algorithm {
public:
using Algorithm::Algorithm; // inherit the default constructor
// make the destructor virtual, and define copy and move constructors
virtual ~MyAlgorithmBase() = default;
MyAlgorithmBase(MyAlgorithmBase const&) = default;
MyAlgorithmBase(MyAlgorithmBase&&) = default;
MyAlgorithmBase& operator=(MyAlgorithmBase const&) = default;
MyAlgorithmBase& operator=(MyAlgorithmBase&&) = default;
// mark this as having the meta type "example"
static string_ref meta_type() { return "example"_v; };
virtual int execute() = 0;
};
// Implement an Algorithm with a strategy
template<typename strategy_t>
class MyAlgorithm : public MyAlgorithmBase {
public:
inline static Meta meta() {
// define the algorithm's meta information
Meta m(TypeDesc("example"), "my_algorithm", "An example algorithm");
m.param("param1").primitive("default_value");
m.param("number").primitive(147);
m.param("strategy").strategy<strategy_t>(TypeDesc("my_strategy_t"));
return m;
}
using MyAlgorithmBase::MyAlgorithmBase; // inherit the default constructor
inline std::string param1() {
// read param1 option as a string
return config().param("param1").as_string();
}
inline virtual int execute() override {
// read number option as an integer
auto number = config().param("number").as_int();
// instantiate strategy with sub environment
strategy_t strategy(config().sub_config("strategy"));
// use strategy to determine result
return strategy.result(number);
}
};
// Strategy to compute the square of the input parameter
class SquareStrategy : public Algorithm {
public:
inline static Meta meta() {
// define the algorithm's meta information
Meta m(TypeDesc("my_strategy_t"), "sqr", "Computes the square");
return m;
}
using Algorithm::Algorithm; // inherit the default constructor
inline int result(int x) {
return x * x;
}
};
// Strategy to compute the product of the input parameter and another number
class MultiplyStrategy : public Algorithm {
public:
inline static Meta meta() {
// define the algorithm's meta information
Meta m(TypeDesc("my_strategy_t"), "mul", "Computes a product");
m.param("factor").primitive(); // no default
return m;
}
using Algorithm::Algorithm; // inherit the default constructor
inline int result(int x) {
return x * config().param("factor").as_int();
}
};
TEST(doc_algorithm_impl, algo_instantiate) {
// Execute the algorithm with the square strategy
auto algo_sqr = Algorithm::instance<MyAlgorithm<SquareStrategy>>("number=7");
ASSERT_EQ(49, algo_sqr->execute());
// Execute the algorithm with the multiply strategy
auto algo_mul5 = Algorithm::instance<MyAlgorithm<MultiplyStrategy>>("number=7,strategy=mul(5)");
ASSERT_EQ(35, algo_mul5->execute());
// param1 was not passed and should be "default_value" for both
ASSERT_EQ("default_value", algo_sqr->param1());
ASSERT_EQ("default_value", algo_mul5->param1());
}
#include <tudocomp/meta/RegistryOf.hpp>
TEST(doc_algorithm_impl, algo_registry) {
// Create a registry for algorithms of type "example"
RegistryOf<MyAlgorithmBase> registry(TypeDesc("example"));
// Register two specializations of the algorithm
registry.register_algorithm<MyAlgorithm<SquareStrategy>>();
registry.register_algorithm<MyAlgorithm<MultiplyStrategy>>();
// Execute the algorithm with the square strategy
auto algo_sqr = registry.select("my_algorithm(number=5, strategy=sqr)");
ASSERT_EQ(25, algo_sqr->execute());
// Execute the algorithm with the multiply strategy
auto algo_mul = registry.select("my_algorithm(number=5, strategy=mul(8))");
ASSERT_EQ(40, algo_mul->execute());
}
|
#include<iostream>
#include"myQueue.h"
using namespace std;
template <class T>
myQueue <T> reverseQueue(myQueue<T>& q)
{
if (!q.isEmpty())
{
T d=q.dequeue();
reverseQueue(q);
q.enqueue(d);
}
return q;
}
int main()
{
cout << "\n\n---------- Best of Luck for the Exam ---------\n\n";
myQueue<char> q1;
q1.enqueue('D');
q1.enqueue('S');
q1.enqueue('A');
q1.enqueue(' ');
q1.enqueue('L');
q1.enqueue('A');
q1.enqueue('B');
q1.display();
myQueue<char> reverseQ1 = reverseQueue(q1);
reverseQ1.display();
return 0;
}
|
#ifndef books_hpp
#define books_hpp
#include <cstdio>
#include "tstring.hpp"
using namespace std;
class book {
private:
tstring<20> isbn;
tstring<40> name, auth, keywd;
double pri;
int quan = 0;
public:
void setIsbn(tstring<20> _isbn) {
isbn = _isbn;
}
void setName(tstring<40> _name) {
name = _name;
}
void setAuth(tstring<40> _auth) {
auth = _auth;
}
void setKeywd(tstring<40> _keywd) {
keywd = _keywd;
}
void setPri(double _pri) {
pri = _pri;
}
void setQuan(int _quan) {
quan = _quan;
}
double getPri() {
return pri;
}
int getQuan() {
return quan;
}
tstring<20> getIsbn() {
return isbn;
}
tstring<40> getAuth() {
return auth;
}
tstring<40> getName() {
return name;
}
tstring<40> getKeywd() {
return keywd;
}
void print() {
if (!isbn) return;
isbn.print();
printf("\t");
name.print();
printf("\t");
auth.print();
printf("\t");
keywd.print();
printf("\t");
printf("%.2lf", pri);
printf("\t%d±¾\n", quan);
}
operator bool() const {
return isbn;
}
};
#endif
|
#pragma once
#include <graphene/chain/evaluator.hpp>
namespace graphene { namespace chain {
class trust_node_pledge_helper
{
public:
static void do_evaluate(database& db, const witness_create_operation& op);
static void do_apply(database& db, const witness_create_operation& op);
static void do_evaluate(database& db, const witness_update_operation& op);
static void do_apply(database& db, const witness_update_operation& op);
static void do_evaluate(database& db, const trust_node_pledge_withdraw_operation& op);
static void do_apply(database& db, const trust_node_pledge_withdraw_operation& op);
static void do_evaluate(database& db, const committee_member_create_operation& op);
static void do_apply(database& db, const committee_member_create_operation& op);
static void do_evaluate(database& db, const committee_member_update_operation& op);
static void do_apply(database& db, const committee_member_update_operation& op);
private:
static void reset();
static void do_evaluate(database& db, const account_id_type& account_id);
static void do_apply(database& db, const account_id_type& account_id);
private:
static bool pledge_object_exist;
static trust_node_pledge_object* pledge_obj_ptr;
static witness_object* witness_obj_ptr;
static committee_member_object* committee_obj_ptr;
static asset pledge_to_charge;
};
} }
|
#ifndef TEMPORALLY_EXTENDED_MODEL_H_
#define TEMPORALLY_EXTENDED_MODEL_H_
#include <vector>
#include <set>
#include <map>
#include <lbfgs.h>
#ifndef DEBUG
#define ARMA_NO_DEBUG
#endif
#include <armadillo>
/**
* Learn a feature set and predictive Conditional Random Field model.
*
* We learn a model of the form
*
* \f{align}
* p(\mathbf{y}|\mathbf{x}) &= \frac{1}{Z(\mathbf{x})} \exp \sum_{f\in\mathcal{F}} \theta_{f} f(\mathbf{x},\mathbf{y}) \\
* Z(\mathbf{x}) &= \sum_{\mathbf{y}} \exp \sum_{f\in\mathcal{F}} \theta_{f} f(\mathbf{x},\mathbf{y})~,
* \f}
*
* where \f$\mathbf{x}\f$ are past observations and the next action, while
* \f$\mathbf{y}\f$ are the next obervation and reward that are to be predicted.
* Given data
* \f$\{(\mathbf{x}^{(1)},\mathbf{y}^{(1)}),\ldots,(\mathbf{x}^{(N)},\mathbf{y}^{(N)})\}\f$
* we need to maximize the log-likelihood
*
* \f{align}
* \ell(\boldsymbol{\mathbf{\theta}}) &= \log \prod_{n=1}^N p(\mathbf{y}^{(n)}|\mathbf{x}^{(n)}) \\
* &= \sum_{n=1}^N \sum_{f\in\mathcal{F}} \theta_{f} f(\mathbf{x}^{(n)},\mathbf{y}^{(n)}) -
* \sum_{n=1}^N \log \sum_{\mathbf{y}} \exp \sum_{f\in\mathcal{F}} \theta_{f} f(\mathbf{x}^{(n)},\mathbf{y})
* \f}
*
* with the gradient
*
* \f{align}
* \frac{\partial\ell(\boldsymbol{\mathbf{\theta}})}{\partial\theta_{g}}
* &= \sum_{n=1}^N \left[
* g(\mathbf{x}^{(n)},\mathbf{y}^{(n)})
* -
* \frac{1}{Z(\mathbf{x}^{(n)})}
* \sum_{\mathbf{y}}
* g(\mathbf{x}^{(n)},\mathbf{y}) \,
* \exp \sum_{f\in\mathcal{F}} \theta_{f} f(\mathbf{x}^{(n)},\mathbf{y})
* \right]~.
* \f}
*
* <b>Writing the Objective and Gradient in Matrix Form</b>
*
* If \f$\boldsymbol{\mathbf{\theta}}\f$ is the the vector of feature weights
* and \f$\mathbf{f}(\mathbf{x},\mathbf{y})\f$ is the vector of feature values
* for a given \f$\mathbf{x}\f$ and \f$\mathbf{y}\f$ we can write the linear
* combination \f$\sum_{f\in\mathcal{F}} \theta_{f} f(\mathbf{x},\mathbf{y})\f$
* as dot product of these vectors
*
* \f{align}
* \sum_{f\in\mathcal{F}} \theta_{f} f(\mathbf{x},\mathbf{y}) &= \boldsymbol{\mathbf{\theta}}^{\top}\mathbf{f}(\mathbf{x},\mathbf{y})~.
* \f}
*
* If we write the vectors \f$\mathbf{f}(\mathbf{x},\mathbf{y}_i)\f$ for all
* possible values of \f$\mathbf{y}_i\f$ in a matrix
*
* \f{align}
* \mathbf{F}(\mathbf{x})
* &= \Big( \mathbf{f}(\mathbf{x},\mathbf{y}_{1}), \mathbf{f}(\mathbf{x},\mathbf{y}_{2}), \ldots \Big) \\
* \text{or equivalently} \qquad \mathbf{F}(\mathbf{x})_{ij}
* &= \mathbf{f}_{i}(\mathbf{x},\mathbf{y}_{j})
* \f}
*
* the product \f$\boldsymbol{\mathbf{\theta}}^{\top}\mathbf{F}(\mathbf{x})\f$
* is a row vector containing the linear combinations of features for all
* possible values of \f$\mathbf{y}\f$ for a given specific value of
* \f$\mathbf{x}\f$.
*
* In the partial derivative of the objective \f$\ell\f$ with respect to the
* \f$i^{th}\f$ feature, the sum over \f$\mathbf{y}\f$ for
* \f$\mathbf{x}^{(n)}\f$ can then be written as
*
* \f{align}
* \ldots &= \sum_{k}
* f_{i}(\mathbf{x}^{(n)},\mathbf{y}_{k}) \,
* \exp \sum_{j} \theta_{j} f_{j}(\mathbf{x}^{(n)},\mathbf{y}_{k}) \\
* &= \sum_{k} \mathbf{F}(\mathbf{x}^{(n)})_{ik} \, \exp\! \left[\,
* \boldsymbol{\mathbf{\theta}}^{\top} \mathbf{F}(\mathbf{x}^{(n)})_{k}
* \,\right] \\
* &= \left[
* \mathbf{F}(\mathbf{x}^{(n)})
* \exp\! \left[\,
* \boldsymbol{\mathbf{\theta}}^{\top} \mathbf{F}(\mathbf{x}^{(n)})
* \,\right]^{\top}
* \right]_{i}~,
* \f}
*
* where the \f$\exp\f$ is to be taken elementwise and
* \f$\left(\mathbf{F}^{\top}\right)_{i}\f$ denotes the \f$i^{th}\f$ column of
* \f$\mathbf{F}\f$. We can compute
* \f$\mathbf{F}=\mathbf{F}(\mathbf{x}^{(n)})\f$ for any given data point
* \f$(\mathbf{x}^{(n)},\mathbf{y}^{(n)})\f$, further \f$i^{*}\f$ be the index
* of \f$\mathbf{y}^{(n)}\f$. We can then compute
* \f$\ell(\boldsymbol{\mathbf{\theta}})\f$ and
* \f$\nabla\ell(\boldsymbol{\mathbf{\theta}})\f$ as follows
*
* \f{align}
* \mathtt{lin} &= \boldsymbol{\mathbf{\theta}}^{\top}\mathbf{F} \\
* \mathtt{explin} &= \exp \left( \mathtt{lin} \right) \\
* \mathtt{z} &= \sum_{i} \mathtt{explin}_{\,i} \\
* \ell(\boldsymbol{\mathbf{\theta}}) &= \mathtt{lin}_{\,i^{*}} - \log(\mathtt{z}) \\
* \nabla\ell(\boldsymbol{\mathbf{\theta}}) &= \left(\mathbf{F}^{\top}\right)_{i^{*}} -
* \frac{
* \mathbf{F} \,
* \mathtt{explin}^{\top}
* }{
* \mathtt{z}
* }~.
* \f}
*
* The sum over data points can then be computed in parallel.
*
* <b>Predictions</b>
*
* In order to compute a prediction \f$p(\mathbf{y}|\mathbf{x})\f$ we first
* compute \f$\mathbf{F}(\mathbf{x})\f$ and \f$i^{*}\f$ and then compute the
* prediction as
*
* \f{align}
* p(\mathbf{y}|\mathbf{x}) &= \frac{\mathtt{explin}_{\,i^{*}}}{\mathtt{z}}~.
* \f}
*
* <b>Partial Derivatives of New Features</b>
*
* \f$\widetilde{\mathcal{F}}\f$ be the newly included candidate features that,
* at that point, have zero-weight. The vector \f$\mathtt{lin} =
* \boldsymbol{\mathbf{\theta}}^{\top}\mathbf{F}\f$ (containing all linear
* combinations for the different values of \f$\mathbf{y}\f$) thus does not
* change. Correspondingly, \f$\mathtt{explin}\f$ and \f$\mathtt{z}\f$ do not
* change either. To compute the gradient for the new features only, the
* candidate feature matrix
*
* \f{align}
* \widetilde{\mathbf{F}}(\mathbf{x})_{ij} &= \widetilde{\mathbf{f}}_{i}(\mathbf{x},\mathbf{y}_{j})
* \f}
*
* has to be calculated (excluding the old features). The gradient then is (as
* above)
*
* \f{align}
* \nabla\ell(\boldsymbol{\mathbf{\theta}}_{new}) &= \left(\widetilde{\mathbf{F}}^{\top}\right)_{i^{*}} -
* \frac{
* \widetilde{\mathbf{F}} \,
* \mathtt{explin}^{\top}
* }{
* \mathtt{z}
* }
* \f}
*
* where \f$\widetilde{\mathbf{F}}\f$ is computed from the new
* features and \f$\mathtt{explin}\f$ and \f$\mathtt{z}\f$ are computed from
* the old features.
*/
class TemporallyExtendedModel {
// for unit tests
friend class TemporallyExtendedModelTest_FeatureTest_Test;
//----typdefs/classes----//
public:
typedef int action_t;
typedef int observation_t;
typedef double reward_t;
struct DataPoint {
DataPoint(action_t action, observation_t observation, reward_t reward);
bool operator<(const DataPoint & other) const;
friend std::ostream& operator<<(std::ostream & out, const DataPoint & point) {
out << "(" << point.action << "," << point.observation << "," << point.reward << ")";
return out;
}
action_t action;
observation_t observation;
reward_t reward;
};
typedef std::vector<DataPoint> data_t;
enum FEATURE_TYPE { ACTION, OBSERVATION, REWARD };
typedef std::tuple<FEATURE_TYPE,int,double> basis_feature_t;
typedef std::set<basis_feature_t> feature_t;
typedef std::map<feature_t,double> feature_set_t;
typedef arma::Mat<double> mat_t;
typedef arma::Col<double> col_vec_t;
typedef arma::Row<double> row_vec_t;
//----members----//
protected:
// PULSE parameters
double regularization = 0; ///< L1-regularization
int horizon_extension = 1; ///< Extension of horizon in each
///out-loop iteration
int maximum_horizon = -1; ///< Maximum extension of horizon
double gradient_threshold = 1e-6; ///< Threshold on ||g||/max(1,||x||) as
///stopping criterion for inner loop
///(default 1e-5)
double parameter_threshold = 1e-5; ///< Not used so far!
int max_inner_loop_iterations = 0; ///< Maximum number of iterations for
///weight optimization (0 for infinite)
int max_outer_loop_iterations = 0; ///< Maximum number of iterations for
///feature set expansion (0 for
///infinite)
double likelihood_threshold = 0; ///< Threshold on (f-f')/f as stopping
///criterion for inner and outer loop
///(separately)
// other stuff
data_t data;
std::set<int> unique_actions;
std::set<int> unique_observations;
std::set<double> unique_rewards;
feature_set_t feature_set;
std::vector<int> outcome_indices;
std::vector<mat_t> F_matrices;
//----methods----//
public:
TemporallyExtendedModel(){};
virtual ~TemporallyExtendedModel(){};
virtual TemporallyExtendedModel & set_regularization(double d) {regularization=d;return *this;}
virtual TemporallyExtendedModel & set_data(const data_t &);
virtual TemporallyExtendedModel & set_horizon_extension(int n) {horizon_extension=n;return *this;}
virtual TemporallyExtendedModel & set_maximum_horizon(int n) {maximum_horizon=n;return *this;}
virtual double optimize();
virtual double get_prediction(const data_t & data) const;
virtual TemporallyExtendedModel & set_gradient_threshold(double d) {gradient_threshold=d;return *this;}
virtual TemporallyExtendedModel & set_parameter_threshold(double d) {parameter_threshold=d;return *this;}
virtual TemporallyExtendedModel & set_max_inner_loop_iterations(int n) {max_inner_loop_iterations=n;return *this;}
virtual TemporallyExtendedModel & set_max_outer_loop_iterations(int n) {max_outer_loop_iterations=n;return *this;}
virtual TemporallyExtendedModel & set_likelihood_threshold(double d) {likelihood_threshold=d;return *this;}
double optimize_weights();
const feature_set_t & get_feature_set() const {return feature_set;}
bool check_derivatives();
void expand_feature_set();
void shrink_feature_set();
void print_feature_set();
protected:
void update_F_matrices();
static void fill_F_matrix(const feature_set_t & feature_set,
const std::set<int> & unique_actions,
const std::set<int> & unique_observations,
const std::set<double> & unique_rewards,
const data_t & data,
const int & data_idx,
mat_t & F_matrix,
int & outcome_index);
static lbfgsfloatval_t neg_log_likelihood(void * instance,
const lbfgsfloatval_t * weights,
lbfgsfloatval_t * gradient,
const int n,
const lbfgsfloatval_t step = lbfgsfloatval_t());
static int progress(void * instance,
const lbfgsfloatval_t * weights,
const lbfgsfloatval_t * gradient,
const lbfgsfloatval_t objective_value,
const lbfgsfloatval_t xnorm,
const lbfgsfloatval_t gnorm,
const lbfgsfloatval_t step,
int nr_variables,
int iteration_nr,
int ls);
};
#endif /* TEMPORALLY_EXTENDED_MODEL_H_ */
|
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
class MedianTwoSortedArrays
{
public:
float findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2);
int Main();
~MedianTwoSortedArrays() {};
}; |
#include "menu.h"
#include <string>
Menu::Menu()
{
}
bool Menu::containsFood(Food* _food){
if(static_cast<Food*>(_food)){
for(std::pair<int, Food*> f : foods){
if(f.second == _food){
return true;
}
}
}
return false;
}
bool Menu::containsDrink(Drink* _drink){
if(static_cast<Drink*>(_drink)){
for(std::pair<int, Drink*> d : drinks){
if(d.second == _drink){
return true;
}
}
}
return false;
}
bool Menu::add(Food* _food){
if(co)){
}
}
bool Menu::remove(Food* _food){
}
|
#include <bits/stdc++.h>
using namespace std;
int const N = 4010;
int main(){
ios::sync_with_stdio(0); cin.tie(0);
int t;
cin >> t;
while(t--){
int n;
cin >> n;
vector<int> v(2*n);
for(int i = 0; i < 2*n; i++) cin >> v[i] ;
vector<int> imp;
imp.push_back(0);
int mx = v[0];
for(int i = 1; i < 2 * n;i++) {
if( v[i] > mx ) mx = v[i], imp.push_back(i);
}
map <int, int > cnt;
for(int i = 1; i < imp.size(); i++) cnt[imp[i]-imp[i-1]]++;
vector<int> need(2*n+5, 0), vis(2*n+5, 0);
vis[0] = true;
for(auto x : cnt){
int val = x.first , q = x.second;
fill(need.begin(),need.end(), 0);
for(int i = 0; i <= 2*n; i++){
if(!vis[i] and i >= val and vis[i - val] and need[i-val] < q)
vis[i] = true, need[i] = need[i-val] + 1;
}
}
cout << (vis[n] ? "YES":"NO") << '\n';
}
} |
#include "opencv.hpp"
using namespace cv;
using namespace std;
Rect selection;
bool bLButtonDown = false;
typedef enum { INIT, CALC_HIST, TRACKING } STATUS;
STATUS trackingMode = INIT;
void Convex_Hull(Mat srcImage)
{
Mat dstImage = srcImage.clone();
GaussianBlur(srcImage, srcImage, Size(3, 3), 0.0);
Mat hsvImage;
cvtColor(srcImage, hsvImage, COLOR_BGR2HSV);
//imshow("hsvImage", hsvImage);
Mat bImage;
Scalar lowerb(0, 40, 0);
Scalar upperb(20, 180, 255);
inRange(hsvImage, lowerb, upperb, bImage);
// imshow("bImage", bImage);
erode(bImage, bImage, Mat());
dilate(bImage, bImage, cv::Mat(), Point(-1, -1), 2);
//imshow("bImage", bImage);
vector<vector<Point> > contours;
findContours(bImage, contours, noArray(),
RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
cout << "contours.size()=" << contours.size() << endl;
if (contours.size()<1)
return;
int maxK = 0;
double maxArea = contourArea(contours[0]);
for (int k = 1; k<contours.size(); k++)
{
double area = contourArea(contours[k]);
if (area > maxArea)
{
maxK = k;
maxArea = area;
}
}
vector<Point> handContour = contours[maxK];
// vector<Point> handContour(contours[maxK].size());
// copy(contours[maxK].begin(),contours[maxK].end(),handContour.begin());
vector<int> hull;
convexHull(handContour, hull);
cout << " hull.size()=" << hull.size() << endl;
vector<Point> ptsHull;
for (int k = 0; k<hull.size(); k++)
{
int i = hull[k];
ptsHull.push_back(handContour[i]);
}
drawContours(dstImage, vector<vector<Point>>(1, ptsHull), 0,
Scalar(255, 0, 0), 2);
vector<Vec4i> defects;
convexityDefects(handContour, hull, defects);
for (int k = 0; k<defects.size(); k++)
{
Vec4i v = defects[k];
Point ptStart = handContour[v[0]];
Point ptEnd = handContour[v[1]];
Point ptFar = handContour[v[2]];
float depth = v[3] / 256.0;
if (depth > 10)
{
line(dstImage, ptStart, ptFar, Scalar(0, 255, 0), 2);
line(dstImage, ptEnd, ptFar, Scalar(0, 255, 0), 2);
circle(dstImage, ptStart, 6, Scalar(0, 0, 255), 2);
circle(dstImage, ptEnd, 6, Scalar(0, 0, 255), 2);
circle(dstImage, ptFar, 6, Scalar(255, 0, 255), 2);
}
}
cout << " defects.size()=" << defects.size() << endl;
imshow("ConvexHull", dstImage);
//waitKey(0);
}
void onMouse(int mevent, int x, int y, int flags, void* param)
{
static Point origin;
Mat *pMat = (Mat *)param;
Mat image = Mat(*pMat);
if (bLButtonDown)
{
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = selection.x + abs(x - origin.x);
selection.height = selection.y + abs(y - origin.y);
selection.x = MAX(selection.x, 0);
selection.y = MAX(selection.y, 0);
selection.width = MIN(selection.width, image.cols);
selection.height = MIN(selection.height, image.rows);
selection.width -= selection.x;
selection.height -= selection.y;
}
switch (mevent)
{
case EVENT_LBUTTONDOWN:
origin = Point(x, y);
selection = Rect(x, y, 0, 0);
bLButtonDown = true;
break;
case EVENT_LBUTTONUP:
bLButtonDown = false;
if (selection.width > 0 && selection.height > 0)
trackingMode = CALC_HIST;
break;
}
}
void apricot(Mat rgbImage)
{
//rgbImage = imread("hand.jpg");
// Mat rgbImage = imread("flower.jpg");
//imshow("rgbImage", rgbImage);
Mat hsvImage;
cvtColor(rgbImage, hsvImage, COLOR_BGR2HSV);
//imshow("hsvImage", hsvImage);
// hand.jpg
Scalar lowerb(0, 40, 0);
Scalar upperb(20, 180, 255);
// flower.jpg
// Scalar lowerb(150, 100, 100);
// Scalar upperb(180, 255, 255);
Mat dstImage;
inRange(hsvImage, lowerb, upperb, dstImage);
//imshow("dstImage1", dstImage);
// check HSV range in object hand
vector<Mat> planes;
split(hsvImage, planes);
// imshow("planes[0]", planes[0]);
// imshow("planes[1]", planes[1]);
// imshow("planes[2]", planes[2]);
double minH, maxH;
minMaxLoc(planes[0], &minH, &maxH, NULL, NULL, dstImage);
cout << "minH =" << minH << ", maxH =" << maxH << endl;
double minS, maxS;
minMaxLoc(planes[1], &minS, &maxS, NULL, NULL, dstImage);
cout << "minS =" << minS << ", maxS =" << maxS << endl;
double minV, maxV;
minMaxLoc(planes[2], &minV, &maxV, NULL, NULL, dstImage);
cout << "minV =" << minV << ", maxV =" << maxV << endl;
}
int main()
{
// VideoCapture inputVideo(0);
VideoCapture inputVideo(0);
if (!inputVideo.isOpened())
{
cout << " Can not open inputVideo !!!" << endl;
return 0;
}
Size size = Size((int)inputVideo.get(CV_CAP_PROP_FRAME_WIDTH),
(int)inputVideo.get(CV_CAP_PROP_FRAME_HEIGHT));
int fps = (int)(inputVideo.get(CV_CAP_PROP_FPS));
if (fps <= 0) fps = 24; // for camera
Mat dstImage;
namedWindow("dstImage");
setMouseCallback("dstImage", onMouse, (void *)&dstImage);
int histSize = 8;
float valueRange[] = { 0, 180 }; //hue's maximum is 180.
const float* ranges[] = { valueRange };
int channels = 0;
Mat hist, backProject;
int fourcc = CV_FOURCC('D', 'I', 'V', 'X'); //CV_FOURCC
bool isColor = true;
VideoWriter outputVideo("trackingRect.avi", fourcc, fps, size, isColor);
if (!outputVideo.isOpened())
{
cout << " Can not open outputVideo !!!" << endl;
return 0;
}
if (fourcc != -1)
{
// for waiting for ready the camera
imshow("dstImage", NULL);
waitKey(100);// not working because of no window
}
TermCriteria criteria = TermCriteria(TermCriteria::COUNT
+ TermCriteria::EPS, 10, 2);
Rect trackWindow;
int delay = 1000 / fps;
Mat frame, hImage, hsvImage, mask;
for (;;)
{
inputVideo >> frame;
if (frame.empty())
break;
flip(frame, frame, 1);
cvtColor(frame, hsvImage, COLOR_BGR2HSV);
frame.copyTo(dstImage);
if (bLButtonDown && 0<selection.width && 0<selection.height)
{
Mat dstROI = dstImage(selection);
bitwise_xor(dstROI, Scalar::all(255), dstROI);
}
if (trackingMode) // CALC_HIST or TRACKING
{
// create mask image
int vmin = 50, vmax = 256, smin = 50;
inRange(hsvImage, Scalar(0, smin, MIN(vmin, vmax)),
Scalar(180, 256, MAX(vmin, vmax)), mask);
// imshow("mask", mask);
int ch[] = { 0, 0 };
hImage.create(hsvImage.size(), CV_8U);
mixChannels(&hsvImage, 1, &hImage, 1, ch, 1);
// imshow("hImage", hImage);
if (trackingMode == CALC_HIST)
{
Mat hImageROI(hImage, selection), maskROI(mask, selection);
calcHist(&hImageROI, 1, &channels, maskROI, hist, 1, &histSize, ranges);
normalize(hist, hist, 0, 255, NORM_MINMAX);//CV_MINMAX
trackWindow = selection;
trackingMode = TRACKING;
}
// TRACKING:
calcBackProject(&hImage, 1, &channels, hist, backProject, ranges);
backProject &= mask;
// bitwise_and(backProject, mask, backProject);
// imshow("backProject", backProject);
meanShift(backProject, trackWindow, criteria);
Point pt1 = Point(trackWindow.x, trackWindow.y);
Point pt2 = Point(pt1.x + trackWindow.width,
pt1.y + trackWindow.height);
rectangle(dstImage, pt1, pt2, Scalar(0, 0, 255), 2);
}
imshow("dstImage", dstImage);
Convex_Hull(dstImage);
// Match(dstImage);
// apricot(dstImage);
outputVideo << dstImage;
int ckey = waitKey(delay);
if (ckey == 27) break;`
}
return 0;
} |
#include <iostream>
#include <bitset>
using namespace std;
int main(void) {
unsigned short int val;
bool ispalindrome = true;
cout << "value = ";
cin >> val;
int counter = 15;
unsigned short a = 1, b = 1;
for (int i = 0; i < counter; i++) {
a = a << i;
b = b << counter;
if (((val & a) && (val & b)) || (!(val & a) && !(val & b))) {
a = 1;
b = 1;
counter--;
}
else {
ispalindrome = false;
break;
}
}
if (ispalindrome)
cout << val << " is a bitwise palindrome" << endl;
else
cout << val << " is not a bitwise palindrome" << endl;
system("pause");
return 0;
}
//a = 1; b = 1;
//a = a << 1;
//bitset<16> bitset3{ a }; // the bitset representation of 4
//cout << bitset3 << endl;
//b = b << 14;
//bitset<16> bitset4{ b }; // the bitset representation of 4
//cout << bitset4 << endl << endl;
//a = 1; b = 1;
//a = a << 2;
//bitset<16> bitset5{ a }; // the bitset representation of 4
//cout << bitset5 << endl;
//b = b << 13;
//bitset<16> bitset6{ b }; // the bitset representation of 4
//cout << bitset6 << endl << endl;
//a = 1; b = 1;
//a = a << 3;
//bitset<16> bitset7{ a }; // the bitset representation of 4
//cout << bitset7 << endl;
//b = b << 12;
//bitset<16> bitset8{ b }; // the bitset representation of 4
//cout << bitset8 << endl << endl;
//a = 1; b = 1;
//a = a << 4;
//bitset<16> bitset9{ a }; // the bitset representation of 4
//cout << bitset9 << endl;
//b = b << 11;
//bitset<16> bitset10{ b }; // the bitset representation of 4
//cout << bitset10 << endl << endl;
//a = 1; b = 1;
//a = a << 5;
//bitset<16> bitset11{ a }; // the bitset representation of 4
//cout << bitset11 << endl;
//b = b << 10;
//bitset<16> bitset12{ b }; // the bitset representation of 4
//cout << bitset12 << endl << endl;
//a = 1; b = 1;
//a = a << 6;
//bitset<16> bitset13{ a }; // the bitset representation of 4
//cout << bitset13 << endl;
//b = b << 9;
//bitset<16> bitset14{ b }; // the bitset representation of 4
//cout << bitset14 << endl << endl;
//a = 1; b = 1;
//a = a << 7;
//bitset<16> bitset15{ a }; // the bitset representation of 4
//cout << bitset15 << endl;
//b = b << 8;
//bitset<16> bitset16{ b }; // the bitset representation of 4
//cout << bitset16 << endl << endl;
//a = 1; b = 1;
//a = a << 8;
//bitset<16> bitset17{ a }; // the bitset representation of 4
//cout << bitset17 << endl;
//b = b << 7;
//bitset<16> bitset18{ b }; // the bitset representation of 4
//cout << bitset18 << endl << endl;
|
#include <ProtocolManagers/vdlocalfile.h>
VDLocalFile::VDLocalFile(QString filename, VDFileItem * vdfitem)
{
this->filename = filename;
this->file = new QFile(filename);
this->vditem = vdfitem;
this->fileinfo = QFileInfo(filename);
this->dir = new QDir(this->filename);
qDebug() << "Constr. file. ex.:" << this->dir->exists() << "filename:" << filename << "isDir" <<this->fileinfo.isDir();
}
void VDLocalFile::fillVDItem(){
QStringList props;
QFileIconProvider qfip;
this->vditem->setFileName(this->fileinfo.fileName());
this->vditem->setPropertyList(this->fileinfo.size(),
this->fileinfo.created(),
this->fileinfo.lastModified(),
this->fileinfo.isDir(),
this->getStandardUrl(),
this->fileinfo.path());
bool root = this->fileinfo.isRoot();
if (root) { this->vditem->setRootFlag(root); }
this->vditem->setIcon(qfip.icon(fileinfo)); // na erre kíváncsi leszek
//qDebug() << this->filename << "finished update";
this->vditem->finishedUpdate();
}
QStringList VDLocalFile::getContentList(){
//qDebug() << "contentlist req for" << this->fileinfo.fileName();
if (this->fileinfo.isDir()){
//qDebug() << "EntryList:" << this->dir->entryList(QDir::NoFilter , QDir::DirsFirst);
return this->dir->entryList(QDir::AllEntries | QDir::NoDot,QDir::DirsFirst);
}
else return QStringList();
}
QList<QFileInfo> VDLocalFile::getContentInfoList(){
return this->dir->entryInfoList(QDir::NoDot,QDir::DirsFirst);
}
QString VDLocalFile::getFullPath(){
return this->fileinfo.absolutePath(); // ezt lehetne szedni a standardurlbol is
}
void VDLocalFile::generateList(QString properties,MainWindow *mw,int panel){
QFileInfoList qfilist = this->dir->entryInfoList(
QDir::AllEntries |QDir::NoDot,QDir::DirsFirst
);
qDebug() << "Path: "<< this->dir->path();
unsigned int count = qfilist.count();
for (unsigned int i=0;i<count;i++){
VDFileItem item(qfilist[i].fileName());
item.setPropertyList(qfilist[i].size(),
qfilist[i].created(),
qfilist[i].lastModified(),
qfilist[i].isDir(),
this->getStandardUrl(qfilist[i].fileName()),
qfilist[i].path());
item.setItemIndex(panel,0);
mw->itemIsReadyToDisplay(&item);
}
}
void VDLocalFile::changePath(QString newPath){
this->dir->setPath(newPath);
this->filename = dir->path();
this->file = new QFile(this->filename);
this->fileinfo = QFileInfo(this->filename);
}
void VDLocalFile::cdUp(){
this->dir->cdUp();
this->changePath(this->dir->path());
}
void VDLocalFile::cd(QString newDir){
this->dir->cd(newDir);
this->changePath(this->dir->path());
}
QString VDLocalFile::getStandardUrl(QString filename){
QString lofasz;
if (filename!="") filename = "/"+filename;
lofasz = this->fileinfo.path()+"/"+this->fileinfo.fileName()+filename;
while (lofasz.contains("//")) lofasz = lofasz.replace(QString("//"),QString("/"));
return "file://"+lofasz;
}
|
#ifndef MENU_ITEMS_TACOBELL
#define MENU_ITEMS_TACOBELL
#include "../../menu_component.hpp"
class menu_items_tacobell : public menu_component
{
private:
string item_name_tacobell;
string item_description_tacobell;
double item_price_tacobell;
int item_number_tacobell;
public:
menu_items_tacobell(int item_number_tacobell, string item_name_tacobell, string item_description_tacobell, double item_price_tacobell) : menu_component()
{
this->item_number_tacobell = item_number_tacobell;
this->item_name_tacobell = item_name_tacobell;
this->item_description_tacobell = item_description_tacobell;
this->item_price_tacobell = item_price_tacobell;
}
string get_name()
{
return this->item_name_tacobell;
}
string get_description()
{
return this->item_description_tacobell;
}
double get_item_price()
{
return this->item_price_tacobell;
}
int get_item_number()
{
return this->item_number_tacobell;
}
void print()
{
cout << "Item Number: " << this->item_number_tacobell << endl
<< "Item Name: " << this->item_name_tacobell << endl
<< "Item Description: " << this->item_description_tacobell << endl
<< "Item Price: " << this->item_price_tacobell << endl
<< endl;
}
};
#endif /* MENU_ITEMS_TACOBELL */
|
#include<iostream>
#include<algorithm>
#include<math.h>
#include<stdio.h>
using namespace std;
struct Dot { // µã
double x, y;
int index;
double getDistance(Dot d1) { // È¡Á½µã
double ans = (d1.x - x) * (d1.x - x) + (d1.y - y) * (d1.y - y);
ans = sqrt(ans);
return ans;
}
}dot[120];
struct Edge { // ±ß
int p, q;
double cost;
}edge[5200];
int tree[120];
double sum;
int findRoot(int p) {
if (tree[p] == p) {
return p;
}
else {
int tmp = findRoot(tree[p]);
tree[p] = tmp;
return tmp;
}
}
void unions(Edge e) {
int pRoot = findRoot(e.p);
int qRoot = findRoot(e.q);
if (pRoot != qRoot) {
tree[pRoot] = qRoot;
sum += e.cost;
}
}
bool compare(Edge e1, Edge e2) {
return e1.cost <= e2.cost;
}
void func() {
int n;
while (cin >> n) {
for (int i = 1;i <= n;i++) {
cin >> dot[i].x >> dot[i].y;
dot[i].index = i;
}
int len = 0;
for (int i = 1;i <= n;i++) {
for (int j =i+1 ;j <= n;j++) {
edge[len].cost = dot[i].getDistance(dot[j]);
edge[len].p = i;
edge[len].q = j;
len++;
}
}
sort(edge, edge + len, compare);
for (int i = 1;i <= n;i++) {
tree[i] = i;
}
sum = 0;
for (int i = 0;i < len;i++) {
unions(edge[i]);
}
printf("%.2f",sum);
}
}
int main() {
func();
return 0;
}
|
#ifndef __FSTREAMs_TO_END_ALL_FSTREAMTs__
#define __FSTREAMs_TO_END_ALL_FSTREAMTs__
#include <fstream>
#if defined(_WIN32) || defined(WIN32)
typedef std::wifstream ifstream_t;
#else
typedef std::ifstream ifstream_t;
#endif
#endif //__FSTREAMs_TO_END_ALL_FSTREAMTs__ |
///////////////////////////////////////////////////////////////////////////////
//
#ifndef __NUMERIC_TIMESERIES_MAP_HPP_
#define __NUMERIC_TIMESERIES_MAP_HPP_
#include <jflib/timeseries/timeseries_map.hpp>
#include <jflib/datetime/date.hpp>
namespace jflib { namespace timeseries { namespace numeric {
template<class> class tsoper;
template<class> class NewPair;
/** \breif Base class for timeseries operators
* \ingroup timeseries
*
* This class define the interfaces for handling timeseries operators
*/
template<class TS>
class tsOperBase {
public:
typedef TS tstype;
typedef typename tstype::key_type key_type;
typedef typename tstype::mapped_type numtype;
typedef typename tstype::value_type value_type;
typedef typename tstype::const_iterator const_iterator;
typedef typename tstype::iterator iterator;
typedef NewPair<tstype> pairtype;
typedef pairtype* pairptr;
virtual ~tsOperBase(){}
virtual pairptr find(const key_type& key) const = 0;
protected:
virtual void fill(tstype& ts) const = 0;
};
template<class TS>
class NewPair {
public:
typedef TS tstype;
typedef typename tstype::key_type key_type;
typedef typename tstype::mapped_type numtype;
NewPair(){}
NewPair* available(const key_type& key, numtype v) {
first = key;
second = v;
return this;
}
key_type first;
numtype second;
private:
NewPair(const NewPair& rhs);
NewPair& operator = (const NewPair& rhs);
};
namespace {
template<class TS>
class tsOperImpl: public tsOperBase<TS> {
public:
typedef tsOperBase<TS> tsoperbase;
typedef typename tsoperbase::pairtype pairtype;
typedef typename tsoperbase::pairptr pairptr;
tsOperImpl():m_pair(new pairtype){}
~tsOperImpl() {delete m_pair;}
protected:
mutable pairptr m_pair;
};
template<class TS, class L, template<class,class> class Op, class R> class tsoperator;
}
/** \brief Timeseries operator class
*
*/
template<class TS>
class tsoper: public tsOperBase<TS> {
public:
typedef TS tstype;
typedef tsOperBase<tstype> tsoperbase;
typedef boost::shared_ptr<tsoperbase> operptr;
typedef typename tsoperbase::key_type key_type;
typedef typename tsoperbase::pairtype pairtype;
typedef typename tsoperbase::pairptr pairptr;
tsoper(const tsoper& rhs):m_oper(rhs.m_oper),m_eval(rhs.m_eval){}
tsoper& operator = (const tsoper& rhs) {m_oper = rhs.m_oper; return *this;}
/// \brief Template constructor
template<class L, template<class,class> class Op, class R>
static tsoper make(const L& lhs, const R& rhs) {
typedef tsoperator<tstype,L,Op,R> tsimpl;
operptr oper(new tsimpl(lhs,rhs));
tsoper ts(oper);
return ts;
}
pairptr find(const key_type& key) const {
return m_oper->find(key);
}
const tstype& apply() const {
if(m_eval) {
return m_ts;
}
else {
tsoper& op = this->noConst();
op.fill(op.m_ts);
op.m_eval = true;
return m_ts;
}
}
protected:
tsoper();
explicit tsoper(const operptr& oper):m_oper(oper){}
operptr m_oper;
tstype m_ts;
bool m_eval;
tsoper& noConst() const { return const_cast<tsoper&>(*this); }
void fill(tstype& ts) const {m_oper->fill(ts);}
};
}}}
#include <jflib/timeseries/impl/numericts_impl.hpp>
#endif // __NUMERIC_TIMESERIES_MAP_HPP_
|
#pragma once
#include <dtl/dtl.hpp>
#include "filter_base.hpp"
namespace dtl {
//===----------------------------------------------------------------------===//
// PImpl wrapper to reduce compilation time.
//===----------------------------------------------------------------------===//
class zbbf_32 : public dtl::filter::filter_base {
class impl;
std::unique_ptr<impl> pimpl;
public:
using key_t = $u32;
using word_t = $u64; // internally, 32-bit words are used
//===----------------------------------------------------------------------===//
// The API functions.
//===----------------------------------------------------------------------===//
$u1
insert(word_t* __restrict filter_data, key_t key);
$u1
batch_insert(word_t* __restrict filter_data, const key_t* keys, u32 key_cnt);
$u1
contains(const word_t* __restrict filter_data, key_t key) const;
$u64
batch_contains(const word_t* __restrict filter_data,
const key_t* __restrict keys, u32 key_cnt,
$u32* __restrict match_positions, u32 match_offset) const;
std::string
name() const;
std::size_t
size_in_bytes() const;
std::size_t
size() const;
static void
calibrate(u64 filter_size_bits = 4ull * 1024 * 8);
static void
force_unroll_factor(u32 u);
//===----------------------------------------------------------------------===//
zbbf_32(std::size_t m, u32 k, u32 word_cnt_per_block = 4, u32 zone_cnt = 2);
~zbbf_32() override;
zbbf_32(zbbf_32&&) noexcept;
zbbf_32(const zbbf_32&) = delete;
zbbf_32& operator=(zbbf_32&&);
zbbf_32& operator=(const zbbf_32&) = delete;
};
} // namespace dtl
|
char *today=__DATE__;
|
#include "wine.h"
void Wine::GetBottles()
{
int y, b; // year, bottle
std::cout << "Enter " << Label() << " data for " << years << " year(s)" << std::endl;
for (int i = 0; i < years; ++i)
{
std::cout << "Enter year:";
std::cin >> y;
PairInt::first()[i] = y;
std::cout << "Enter bottles for that year: ";
std::cin >> b;
PairInt::second()[i] = b;
}
}
void Wine::Show() const
{
std::cout << "Wine: " << Label() << std::endl;
std::cout << "Year " << " Bottles" << std::endl;
for (int i = 0; i < years; ++i)
{
std::cout << PairInt::second()[i] << " ";
std::cout << PairInt::first()[i] << std::endl;
}
}
|
/***
* Copyright (C) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
*
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* constructor_tests.cpp
*
* Tests for constructors of the uri class.
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
using namespace web;
using namespace utility;
namespace tests
{
namespace functional
{
namespace uri_tests
{
SUITE(constructor_tests)
{
TEST(parsing_constructor_char)
{
uri u(uri::encode_uri(__U("net.tcp://steve:@testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(__U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(__U("steve:"), u.user_info());
VERIFY_ARE_EQUAL(__U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(__U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(__U("qstring"), u.query());
VERIFY_ARE_EQUAL(__U("goo"), u.fragment());
}
TEST(parsing_constructor_encoded_string)
{
uri u(uri::encode_uri(__U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(__U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(__U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(__U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(__U("qstring"), u.query());
VERIFY_ARE_EQUAL(__U("goo"), u.fragment());
}
TEST(parsing_constructor_string_string)
{
uri u(uri::encode_uri(__U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(__U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(__U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(__U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(__U("qstring"), u.query());
VERIFY_ARE_EQUAL(__U("goo"), u.fragment());
}
TEST(empty_strings)
{
VERIFY_IS_TRUE(uri(__U("")).is_empty());
VERIFY_IS_TRUE(uri(__U("")).is_empty());
VERIFY_IS_TRUE(uri(uri::encode_uri(__U(""))).is_empty());
}
TEST(default_constructor) { VERIFY_IS_TRUE(uri().is_empty()); }
TEST(relative_ref_string)
{
uri u(uri::encode_uri(__U("first/second#boff")));
VERIFY_ARE_EQUAL(__U(""), u.scheme());
VERIFY_ARE_EQUAL(__U(""), u.host());
VERIFY_ARE_EQUAL(0, u.port());
VERIFY_ARE_EQUAL(__U("first/second"), u.path());
VERIFY_ARE_EQUAL(__U(""), u.query());
VERIFY_ARE_EQUAL(__U("boff"), u.fragment());
}
TEST(absolute_ref_string)
{
uri u(uri::encode_uri(__U("/first/second#boff")));
VERIFY_ARE_EQUAL(__U(""), u.scheme());
VERIFY_ARE_EQUAL(__U(""), u.host());
VERIFY_ARE_EQUAL(0, u.port());
VERIFY_ARE_EQUAL(__U("/first/second"), u.path());
VERIFY_ARE_EQUAL(__U(""), u.query());
VERIFY_ARE_EQUAL(__U("boff"), u.fragment());
}
TEST(copy_constructor)
{
uri original(__U("http://st:pass@localhost:456/path1?qstring#goo"));
uri new_uri(original);
VERIFY_ARE_EQUAL(original, new_uri);
}
TEST(move_constructor)
{
const utility::string_t uri_str(__U("http://localhost:456/path1?qstring#goo"));
uri original(uri_str);
uri new_uri = std::move(original);
VERIFY_ARE_EQUAL(uri_str, new_uri.to_string());
VERIFY_ARE_EQUAL(uri(uri_str), new_uri);
}
TEST(assignment_operator)
{
uri original(__U("http://localhost:456/path?qstring#goo"));
uri new_uri = original;
VERIFY_ARE_EQUAL(original, new_uri);
}
// Tests invalid URI being passed in constructor.
TEST(parsing_constructor_invalid)
{
VERIFY_THROWS(uri(__U("123http://localhost:345/")), uri_exception);
VERIFY_THROWS(uri(__U("h*ttp://localhost:345/")), uri_exception);
VERIFY_THROWS(uri(__U("http://localhost:345/\"")), uri_exception);
VERIFY_THROWS(uri(__U("http://localhost:345/path?\"")), uri_exception);
VERIFY_THROWS(uri(__U("http://local\"host:345/")), uri_exception);
}
// Tests a variety of different URIs using the examples in RFC 2732
TEST(RFC_2732_examples_string)
{
// The URI parser will make characters lower case
uri http1(__U("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"));
VERIFY_ARE_EQUAL(__U("http"), http1.scheme());
VERIFY_ARE_EQUAL(__U("[fedc:ba98:7654:3210:fedc:ba98:7654:3210]"), http1.host());
VERIFY_ARE_EQUAL(80, http1.port());
VERIFY_ARE_EQUAL(__U("/index.html"), http1.path());
VERIFY_ARE_EQUAL(__U(""), http1.query());
uri http2(__U("http://[1080:0:0:0:8:800:200C:417A]/index.html"));
VERIFY_ARE_EQUAL(__U("http"), http2.scheme());
VERIFY_ARE_EQUAL(__U("[1080:0:0:0:8:800:200c:417a]"), http2.host());
VERIFY_ARE_EQUAL(0, http2.port());
VERIFY_ARE_EQUAL(__U("/index.html"), http2.path());
VERIFY_ARE_EQUAL(__U(""), http2.query());
uri http3(__U("https://[3ffe:2a00:100:7031::1]"));
VERIFY_ARE_EQUAL(__U("https"), http3.scheme());
VERIFY_ARE_EQUAL(__U("[3ffe:2a00:100:7031::1]"), http3.host());
VERIFY_ARE_EQUAL(0, http3.port());
VERIFY_ARE_EQUAL(__U("/"), http3.path());
VERIFY_ARE_EQUAL(__U(""), http3.query());
uri http4(__U("http://[::192.9.5.5]/ipng"));
VERIFY_ARE_EQUAL(__U("http"), http4.scheme());
VERIFY_ARE_EQUAL(__U("[::192.9.5.5]"), http4.host());
VERIFY_ARE_EQUAL(0, http4.port());
VERIFY_ARE_EQUAL(__U("/ipng"), http4.path());
VERIFY_ARE_EQUAL(__U(""), http4.query());
uri http5(__U("http://[1080::8:800:200C:417A]/foo"));
VERIFY_ARE_EQUAL(__U("http"), http5.scheme());
VERIFY_ARE_EQUAL(__U("[1080::8:800:200c:417a]"), http5.host());
VERIFY_ARE_EQUAL(0, http5.port());
VERIFY_ARE_EQUAL(__U("/foo"), http5.path());
VERIFY_ARE_EQUAL(__U(""), http5.query());
uri http6(__U("http://[::FFFF:129.144.52.38]:80/index.html"));
VERIFY_ARE_EQUAL(__U("http"), http6.scheme());
VERIFY_ARE_EQUAL(__U("[::ffff:129.144.52.38]"), http6.host());
VERIFY_ARE_EQUAL(80, http6.port());
VERIFY_ARE_EQUAL(__U("/index.html"), http6.path());
VERIFY_ARE_EQUAL(__U(""), http6.query());
uri http7(__U("http://[2010:836B:4179::836B:4179]"));
VERIFY_ARE_EQUAL(__U("http"), http7.scheme());
VERIFY_ARE_EQUAL(__U("[2010:836b:4179::836b:4179]"), http7.host());
VERIFY_ARE_EQUAL(0, http7.port());
VERIFY_ARE_EQUAL(__U("/"), http7.path());
VERIFY_ARE_EQUAL(__U(""), http7.query());
}
// Tests a variety of different URIs using the examples in RFC 3986.
TEST(RFC_3968_examples_string)
{
uri ftp(__U("ftp://ftp.is.co.za/rfc/rfc1808.txt"));
VERIFY_ARE_EQUAL(__U("ftp"), ftp.scheme());
VERIFY_ARE_EQUAL(__U(""), ftp.user_info());
VERIFY_ARE_EQUAL(__U("ftp.is.co.za"), ftp.host());
VERIFY_ARE_EQUAL(0, ftp.port());
VERIFY_ARE_EQUAL(__U("/rfc/rfc1808.txt"), ftp.path());
VERIFY_ARE_EQUAL(__U(""), ftp.query());
VERIFY_ARE_EQUAL(__U(""), ftp.fragment());
// TFS #371892
// uri ldap(__U("ldap://[2001:db8::7]/?c=GB#objectClass?one"));
// VERIFY_ARE_EQUAL(__U("ldap"), ldap.scheme());
// VERIFY_ARE_EQUAL(__U(""), ldap.user_info());
// VERIFY_ARE_EQUAL(__U("2001:db8::7"), ldap.host());
// VERIFY_ARE_EQUAL(0, ldap.port());
// VERIFY_ARE_EQUAL(__U("/"), ldap.path());
// VERIFY_ARE_EQUAL(__U("c=GB"), ldap.query());
// VERIFY_ARE_EQUAL(__U("objectClass?one"), ldap.fragment());
// We don't support anything scheme specific like in C# so
// these common ones don't have a great experience yet.
uri mailto(__U("mailto:John.Doe@example.com"));
VERIFY_ARE_EQUAL(__U("mailto"), mailto.scheme());
VERIFY_ARE_EQUAL(__U(""), mailto.user_info());
VERIFY_ARE_EQUAL(__U(""), mailto.host());
VERIFY_ARE_EQUAL(0, mailto.port());
VERIFY_ARE_EQUAL(__U("John.Doe@example.com"), mailto.path());
VERIFY_ARE_EQUAL(__U(""), mailto.query());
VERIFY_ARE_EQUAL(__U(""), mailto.fragment());
uri tel(__U("tel:+1-816-555-1212"));
VERIFY_ARE_EQUAL(__U("tel"), tel.scheme());
VERIFY_ARE_EQUAL(__U(""), tel.user_info());
VERIFY_ARE_EQUAL(__U(""), tel.host());
VERIFY_ARE_EQUAL(0, tel.port());
VERIFY_ARE_EQUAL(__U("+1-816-555-1212"), tel.path());
VERIFY_ARE_EQUAL(__U(""), tel.query());
VERIFY_ARE_EQUAL(__U(""), tel.fragment());
uri telnet(__U("telnet://192.0.2.16:80/"));
VERIFY_ARE_EQUAL(__U("telnet"), telnet.scheme());
VERIFY_ARE_EQUAL(__U(""), telnet.user_info());
VERIFY_ARE_EQUAL(__U("192.0.2.16"), telnet.host());
VERIFY_ARE_EQUAL(80, telnet.port());
VERIFY_ARE_EQUAL(__U("/"), telnet.path());
VERIFY_ARE_EQUAL(__U(""), telnet.query());
VERIFY_ARE_EQUAL(__U(""), telnet.fragment());
}
TEST(user_info_string)
{
uri ftp(__U("ftp://johndoe:testname@ftp.is.co.za/rfc/rfc1808.txt"));
VERIFY_ARE_EQUAL(__U("ftp"), ftp.scheme());
VERIFY_ARE_EQUAL(__U("johndoe:testname"), ftp.user_info());
VERIFY_ARE_EQUAL(__U("ftp.is.co.za"), ftp.host());
VERIFY_ARE_EQUAL(0, ftp.port());
VERIFY_ARE_EQUAL(__U("/rfc/rfc1808.txt"), ftp.path());
VERIFY_ARE_EQUAL(__U(""), ftp.query());
VERIFY_ARE_EQUAL(__U(""), ftp.fragment());
}
// Test query component can be separated with '&' or ';'.
TEST(query_seperated_with_semi_colon)
{
uri u(__U("http://localhost/path1?key1=val1;key2=val2"));
VERIFY_ARE_EQUAL(__U("key1=val1;key2=val2"), u.query());
}
} // SUITE(constructor_tests)
} // namespace uri_tests
} // namespace functional
} // namespace tests
|
#ifndef QTL_NET_URL_URL_H_
#define QTL_NET_URL_URL_H_
#include <string>
#include <boost/shared_ptr.hpp>
#include "qtl/errors/error.h"
namespace qtl {
namespace net {
namespace url {
// The general form represented is:
// scheme://[userinfo@]host/path[?query][#fragment]
// url encoding is not taken into consideration yet
struct URL {
typedef std::string string;
string scheme;
string host;
string path;
string query;
string fragment;
};
boost::shared_ptr<URL> Parse(const std::string& rawurl, qtl::errors::Error& err);
} // namespace url
} // namespace net
} // namespace qtl
#endif // QTL_NET_URL_URL_H
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// recursion version
// void largestValuesHelp(TreeNode * root, int level, vector<int> &res) {
// if(root == nullptr) return;
// if(int(res.size()) == level) {
// res.push_back(root -> val);
// }
// // have element in this level
// else {
// if(res[level] < root -> val) {
// res[level] = root -> val;
// }
// }
// largestValuesHelp(root -> left, level + 1, res);
// largestValuesHelp(root -> right, level + 1, res);
// }
vector<int> largestValues(TreeNode* root) {
// vector<int> res;
// largestValuesHelp(root, 0, res);
// return res;
// breath first method
queue<TreeNode *> q;
vector<int> res;
if(root == nullptr) return res;
q.push(root);
int count = 1;
int new_count = 0;
int max = std::numeric_limits<int>::min();
while(!q.empty()) {
while(count != 0) {
TreeNode* f = q.front();
if(f -> val > max) {
max = f -> val;
}
q.pop();
if(f -> left) {
q.push(f -> left);
new_count++;
}
if(f -> right) {
q.push(f -> right);
new_count++;
}
count--;
}
res.push_back(max);
count = new_count;
new_count = 0;
max = std::numeric_limits<int>::min();
}
return res;
}
}; |
#pragma once
class VideoCameraStreamer : public IVideoFrameSink
{
public:
VideoCameraStreamer(
const winrt::Windows::Perception::Spatial::SpatialCoordinateSystem& coordSystem,
std::wstring portName);
void Send(
winrt::Windows::Media::Capture::Frames::MediaFrameReference pFrame,
long long pTimestamp);
// void StreamingToggle();
public:
bool isConnected = false;
private:
winrt::Windows::Foundation::IAsyncAction StartServer();
void OnConnectionReceived(
winrt::Windows::Networking::Sockets::StreamSocketListener /* sender */,
winrt::Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs args);
void WriteMatrix4x4(
_In_ winrt::Windows::Foundation::Numerics::float4x4 matrix);
//bool m_streamingEnabled = true;
TimeConverter m_converter;
winrt::Windows::Perception::Spatial::SpatialCoordinateSystem m_worldCoordSystem = nullptr;
winrt::Windows::Networking::Sockets::StreamSocketListener m_streamSocketListener;
winrt::Windows::Networking::Sockets::StreamSocket m_streamSocket = nullptr;
winrt::Windows::Storage::Streams::DataWriter m_writer = nullptr;
bool m_writeInProgress = false;
std::wstring m_portName;
}; |
#include <IRremote.h>
int motor1pin1 = 2;
int motor1pin2 = 3;
int motor2pin1 = 4;
int motor2pin2 = 5;
const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;
unsigned long key_value = 0;
void setup(){
Serial.begin(9600);
irrecv.enableIRIn();
//irrecv.blink13(true);
// put your setup code here, to run once:
pinMode(motor1pin1, OUTPUT);
pinMode(motor1pin2, OUTPUT);
pinMode(motor2pin1, OUTPUT);
pinMode(motor2pin2, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}
void loop(){
//analogWrite(9, 100); //ENA pin
//analogWrite(10, 100); //ENB pin
if (irrecv.decode(&results)){
if (results.value == 0XFFFFFFFF)
results.value = key_value;
switch(results.value){
case 0xFFA25D:
Serial.println("CH-");
break;
case 0xFF629D:
Serial.println("CH");
break;
case 0xFFE21D:
Serial.println("CH+");
break;
case 0xFF22DD:
Serial.println("|<<");
break;
case 0xFF02FD:
Serial.println(">>|");
break ;
case 0xFFC23D:
Serial.println(">|");
break ;
case 0xFFE01F:
Serial.println("-");
break ;
case 0xFFA857:
Serial.println("+");
break ;
case 0xFF906F:
Serial.println("EQ");
break ;
case 0xFF6897:
Serial.println("0");
break ;
case 0xFF9867:
Serial.println("100+");
break ;
case 0xFFB04F:
Serial.println("200+");
break ;
case 0xFF30CF:
Serial.println("1");
break ;
case 0xFF18E7:
Serial.println("2");
break ;
case 0xFF7A85:
Serial.println("3");
break ;
case 0xFF10EF:
Serial.println("4");
break ;
case 0xFF38C7:
Serial.println("5");
break ;
case 0x574355AA:
Serial.println("Stop");
analogWrite(9, 0); //ENA pin
analogWrite(10, 0); //ENB pin
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
break ;
case 0x57437986:
Serial.println("Left");
analogWrite(9, 0); //ENA pin
analogWrite(10, 100); //ENB pin
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
break ;
case 0x5743B54A:
Serial.println("Right");
analogWrite(9, 100); //ENA pin
analogWrite(10, 0); //ENB pin
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
break ;
case 0x5743CD32:
Serial.println("Backwards");
analogWrite(9, 100); //ENA pin
analogWrite(10, 100); //ENB pin
digitalWrite(motor1pin1, LOW);
digitalWrite(motor1pin2, HIGH);
digitalWrite(motor2pin1, LOW);
digitalWrite(motor2pin2, HIGH);
break ;
case 0x57439966:
Serial.println("Forward");
analogWrite(9, 100); //ENA pin
analogWrite(10, 100); //ENB pin
digitalWrite(motor1pin1, HIGH);
digitalWrite(motor1pin2, LOW);
digitalWrite(motor2pin1, HIGH);
digitalWrite(motor2pin2, LOW);
break ;
}
key_value = results.value;
irrecv.resume();
}
}
|
#include "stdafx.h"
#include "base/nextai_file_system.h"
#include "base/nextai_string.h"
#define FILE_EXIST_FLAG 0 /* Check for file existence */
#define FILE_EXE_FLAG 1 /* Check for execute permission. */
#define FILE_WRITE_FLAG 2 /* Check for write permission */
#define FILE_READ_FLAG 4 /* Check for read permission */
namespace NextAI
{
bool waccess(const std::wstring& wpath, int32 openmode)
{
std::string path = StringUtil::ws2s(wpath);
#ifdef SYSTEM_LINUX
return access(path.c_str(), openmode) == 0 ? true : false;
#else
return _access(path.c_str(), openmode) == 0 ? true : false;
#endif
}
void wgetcwd(std::wstring& wpath, size_t wpathLengh)
{
char path[MAX_PATH] = {0};
#ifdef SYSTEM_LINUX
getcwd(path, element_of(path));
#else
GetCurrentDirectory(element_of(path), path);
#endif
wpath = StringUtil::s2ws(path);
return;
}
std::wstring FileSystem::m_currentDirectory = L"";
bool FileSystem::isExist(const std::wstring& path)
{
return waccess(path.c_str(), FILE_READ_FLAG);
}
FileSystem::ACCESS_MODE FileSystem::getAccessMode(const std::wstring& path)
{
if (!waccess(path, FILE_EXIST_FLAG))
{ return FileSystem::ACCESS_MODE_NO_EXIST; }
bool readable = waccess(path, FILE_READ_FLAG);
bool writeable = waccess(path, FILE_WRITE_FLAG);
if (readable == true && writeable == false)
{ return FileSystem::ACCESS_MODE_READ_ONLY; }
else if (readable == false && writeable == true)
{ return FileSystem::ACCESS_MODE_WRITE_ONLY; }
else if (readable == true && writeable == true)
{ return FileSystem::ACCESS_MODE_READ_WRITE; }
return FileSystem::ACCESS_MODE_DENIED;
}
bool FileSystem::isAbsolute(const std::wstring& path)
{
#if defined(SYSTEM_WINDOWS)
return (path[1] == ':');
#else
return (path[0] == '/');
#endif
}
const std::wstring FileSystem::getCurrentDirectory()
{
m_currentDirectory = L"";
wgetcwd(m_currentDirectory, element_of(m_currentDirectory));
uint32 pathLength = m_currentDirectory.size();
if (pathLength > 1 && (pathLength < element_of(m_currentDirectory) - 2) && (m_currentDirectory[pathLength - 1] != '/' || m_currentDirectory[pathLength - 1] != '\\'))
{
m_currentDirectory += L"/";
}
return m_currentDirectory;
}
File::File()
{
}
File::~File()
{
}
static std::ios::openmode _FileAccessMode2iosMode(FileAccessMode mode)
{
const std::ios::openmode modeTable[] =
{
std::ios::in,
std::ios::out,
std::ios::in | std::ios::out,
std::ios::app,
std::ios::in | std::ios::binary,
std::ios::out | std::ios::binary,
std::ios::app | std::ios::binary
};
return modeTable[(int32)mode];
}
bool File::open(const std::wstring& wpath, FileAccessMode mode)
{
NEXTAI_TRACE_LOG(L"wpath[{}] mode[{}]", wpath, mode);
#ifdef SYSTEM_LINUX
char path[PATH_LENGTH_MAX] = { 0 };
wcstombs(path, wpath, element_of(path));
m_file.open(path, _FileAccessMode2iosMode(mode));
#else
m_file.open(wpath, _FileAccessMode2iosMode(mode));
#endif
return isOpen();
}
bool File::isOpen()
{
return m_file.is_open() ? true : false;
}
FileStatus File::close()
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
m_file.close();
return FileStatus::OK;
}
FileStatus File::write(const std::wstring& string)
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
return FileStatus::OK;
}
FileStatus File::writeLine(const std::wstring& string)
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
m_file << string << std::endl;
return FileStatus::OK;
}
FileStatus File::write(const BIT_DATA* buffer, uint32 bufferSize)
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
m_file.write((const WCHAR *)buffer, bufferSize);
return FileStatus::OK;
}
#if 0 /* TODO */
FileStatus File::read(std::wstring& string)
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
m_file.read(string, size);
return FileStatus::OK;
}
FileStatus File::readLine(std::wstring& string)
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
m_file.read(string, size);
return FileStatus::OK;
}
#endif
FileStatus File::read(BIT_DATA* buffer, uint32 bufferSize)
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
m_file.read((WCHAR *)buffer, bufferSize);
return FileStatus::OK;
}
bool File::EndOfFile()
{
return m_file.eof() ? true : false;
}
FileStatus File::flush()
{
if (!m_file.is_open())
{
return FileStatus::NotOpen;
}
m_file.flush();
return FileStatus::OK;
}
}
std::wostream& operator<<(std::wostream& os, NextAI::FileAccessMode mode)
{
switch (mode)
{
OUT_STREAM_ENUM_CLASS_CASE(FileAccessMode::Read);
OUT_STREAM_ENUM_CLASS_CASE(FileAccessMode::Write);
OUT_STREAM_ENUM_CLASS_CASE(FileAccessMode::ReadWrite);
OUT_STREAM_ENUM_CLASS_CASE(FileAccessMode::Append);
OUT_STREAM_ENUM_CLASS_CASE(FileAccessMode::ReadBinary);
OUT_STREAM_ENUM_CLASS_CASE(FileAccessMode::WriteBinary);
OUT_STREAM_ENUM_CLASS_CASE(FileAccessMode::AppendBinary);
}
return os << L"FileAccessMode::Unknown";
}
std::wostream& operator<<(std::wostream& os, NextAI::FileStatus mode)
{
switch (mode)
{
OUT_STREAM_ENUM_CLASS_CASE(FileStatus::OK);
OUT_STREAM_ENUM_CLASS_CASE(FileStatus::NotOpen);
}
return os << L"FileStatus::Unknown";
} |
#ifndef ACTION_H
#define ACTION_H
enum Decision
{
FOLD,
CHECK,
CALL,
BET,
RAISE,
BET_ALLIN,
RAISE_ALLIN,
SMALLBLIND,
BIGBLIND,
N_ACTIONS
};
struct Action
{
Decision decision;
int amount;
Action() : decision{Decision::CHECK}, amount{0} {}
Action(Decision d, int a = 0) : decision{d}, amount{a} {}
friend bool operator==(Action& a1, Action& a2);
};
#endif
|
/**************************************************************************/
/**************************************************************************/
/* */
/* Ce programme permet de creer un processus serveur et des clients */
/* */
/* */
/**************************************************************************/
/**************************************************************************/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <iostream>
#include <signal.h>
#include <iostream>
#include <fstream>
#define PORT_NUM 5000
#define NUM_CLIENTS 50
typedef void Sigfunc(int);
//Sigfunc *signal(int,Sigfunc *);
void doprocessing (int sock)
{
int n;
char buffer[256];
memset(buffer,0,256);
n = read(sock,buffer,255);
if (n < 0)
{
exit(1);
}
printf("[SERVER] Request Received: %s\n",buffer);
std::ifstream myfile (buffer);
std::string line;
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
n = write(sock,line.c_str(),line.size());
}
myfile.close();
}
n = write(sock,"[[file.txt]]",12);
if (n < 0)
{
printf("printf writing to socket");
exit(1);
}
}
int sock_server, new_sock_server;
void *Server(void *threadid)
{
int no_de_port;
socklen_t clilen;
char buffer[256];
struct sockaddr_in adresse_serveur, adresse_client;
int n;
sock_server = socket(AF_INET, SOCK_STREAM, 0);
if (sock_server < 0)
printf("Impossible d'ouvrir la socket \n");
//Remplir de zero
memset((char *) &adresse_serveur,0, sizeof(adresse_serveur));
no_de_port = PORT_NUM;
adresse_serveur.sin_family = AF_INET;
adresse_serveur.sin_addr.s_addr = INADDR_ANY;
adresse_serveur.sin_port = htons(no_de_port);
//Binder la socket
if (bind(sock_server, (struct sockaddr *) &adresse_serveur,
sizeof(adresse_serveur)) < 0)
printf("Impossible de binder la socket \n");
listen(sock_server,5);
clilen = sizeof(adresse_client);
while (1) //Pour toujours
{
//ACCEPT
new_sock_server = accept(sock_server,
(struct sockaddr *) &adresse_client, &clilen);
if (new_sock_server < 0)
{
printf("ERROR on accept");
exit(1);
}
/* Créer un enfant */
pid_t pid = fork();
if (pid < 0)
{
printf("ERROR on fork");
exit(1);
}
if (pid == 0)
{
/* C'est le client */
close(sock_server);
doprocessing(new_sock_server);
exit(0);
}
else
{
//fermeture des sockets
close(new_sock_server);
}
} /* end of while */
}
int sockfd_client;
void *Client(void *threadid)
{
int no_de_port,n;
struct sockaddr_in adresse_serveur;
struct hostent *server;
std::ofstream myfile;
char buffer[256];
no_de_port = PORT_NUM;
/** INIT **/
sockfd_client = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd_client < 0)
printf("Impossible de créer la socket");
server = gethostbyname("localhost");
if (server == NULL)
{
fprintf(stderr,"impossible de contacter l'host \n");
exit(0);
}
memset((char *) &adresse_serveur,0, sizeof(adresse_serveur));
adresse_serveur.sin_family = AF_INET;
memcpy((char *)&adresse_serveur.sin_addr.s_addr,
(char *)server->h_addr,
server->h_length);
adresse_serveur.sin_port = htons(no_de_port);
/** CONNECT **/
if (connect(sockfd_client,(struct sockaddr *) &adresse_serveur,sizeof(adresse_serveur)) < 0)
printf("printf connecting");
memset(buffer,0,256);
/** WRITE **/
n = write(sockfd_client,"file.txt",8);
if (n < 0)
printf("Impossible d'envoyer la request");
n = read(sockfd_client,buffer,255);
if (n < 0)
printf("Impossible de lire la reponse de la socket");
printf("[CLIENT] I received: %s\n",buffer);
myfile.open("received.txt");
//Écriture dans le fichier
myfile << buffer;
myfile.close();
close(sockfd_client);
return 0;
pthread_exit(NULL);
}
void cleanExit(int code)
{
printf(" \n Kill signal received... closing sockets \n");
close(sock_server);
close(new_sock_server);
//close(sockfd_client);
exit(0);
}
main()
{
//***** Création des thread ****//
pthread_t serveur;
pthread_t clients[NUM_CLIENTS];
//***Enregistrement des handler de signals***//
signal(SIGINT,cleanExit);
int rc;
int t;
rc = pthread_create(&serveur, NULL, Server, (void *)t);
if (rc)
{
printf(" Impossible de démarer le serveur: %d\n", rc);
exit(-1);
}
printf("Server is started \n");
for(t=0; t<NUM_CLIENTS; t++)
{
rc = pthread_create(&clients[t], NULL, Client, (void *)t);
if (rc)
{
printf(" Impossible de créer le client: %d\n", rc);
exit(-1);
}
printf("Client is started: %ld\n", t+1);
}
pthread_exit(NULL);
}
|
#include <cmath>
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 5;
int n, cnt[maxn] = { 0 };
// #define DEBUG
int main() {
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
cin >> n;
int tmp;
for (int i = 0; i < n; ++i) {
cin >> tmp;
int sq = sqrt(tmp);
for (int j = 1; j <= sq; ++j)
if (tmp % j == 0) {
++cnt[j];
if (j * j != tmp)
++cnt[tmp / j];
}
}
int idx = maxn;
for (int i = 1; i <= n; ++i) {
while (cnt[idx] < i)
--idx;
cout << idx << endl;
}
return 0;
} |
// Fig. 19.1: fig19_01.cpp
// Demonstrating string assignment and concatenation
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
string s1( "cat" ), s2, s3;
s2 = s1; // assign s1 to s2 with =
s3.assign( s1 ); // assign s1 to s3 with assign()
cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: "
<< s3 << "\n\n";
// modify s2 and s3
s2[ 0 ] = s3[ 2 ] = 'r';
cout << "After modification of s2 and s3:\n"
<< "s1: " << s1 << "\ns2: " << s2 << "\ns3: ";
// demonstrating member function at()
int len = s3.length();
for ( int x = 0; x < len; ++x )
cout << s3.at( x );
// concatenation
string s4( s1 + "apult" ), s5; // declare s4 and s5
// overloaded +=
s3 += "pet"; // create "carpet"
s1.append( "acomb" ); // create "catacomb"
// append subscript locations 4 thru the end of s1 to
// create the string "comb" (s5 was initially empty)
s5.append( s1, 4, s1.size() );
cout << "\n\nAfter concatcenation:\n" << "s1: " << s1
<< "\ns2: " << s2 << "\ns3: " << s3 << "\ns4: " << s4
<< "\ns5: " << s5 << endl;
return 0;
}
/**************************************************************************
* (C) Copyright 2000 by Deitel & Associates, Inc. and Prentice Hall. *
* All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/
|
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> m;
for (auto c : s) {
if (!m.count(c))
m[c] = 1;
else
++m[c];
}
for (auto c : t) {
if (!m.count(c))
return false;
else
--m[c];
}
for (auto elem : m) {
if (elem.second != 0) return false;
}
return true;
}
}; |
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
bool cmp(const std::string &a, const std::string &b)
{
return (a.size() >= b.size());
}
int main(int argc, char **argv)
{
if (argc != 2) {
return 1;
}
std::ifstream f(argv[1]);
std::string line;
int iter = 0;
int num_to_print;
f >> num_to_print;
std::vector<std::string> s;
while (true) {
std::getline(f, line);
if (f.fail()) {
break;
}
if (line.size() == 0) {
continue;
}
if (iter != 0) {
std::cout << '\n';
}
s.push_back(line);
}
std::sort(s.begin(), s.end(), cmp);
if (num_to_print > 0) {
std::cout << s[0];
}
for (int i = 1; i < num_to_print; i++) {
std::cout << '\n' << s[i];
}
return 0;
}
|
/*
* Copyright (c) 2012 Joey Yore
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef AHRS_H
#define AHRS_H
#include "quaternion.h"
#include "vector3.h"
#include <math.h>
class AHRS {
private:
double period;
double beta;
Quaternion q;
public:
AHRS(double oPeriod=1.0/512.0,double oBeta=0.1) :
period(oPeriod), beta(oBeta) {
q = Quaternion(1,Vector3(0,0,0));
}
void update(Vector3 gyro, Vector3 accel, Vector3 magn) {
if((magn[0]==0.0) && (magn[1]==0.0) && (magn[2]==0.0)) {
this->update(gyro,accel);
return;
}
Quaternion qDot(
0.5*(-q[1]*gyro[0] - q[2]*gyro[1] - q[3]*gyro[2]),
Vector3(
0.5*( q[0]*gyro[0] + q[2]*gyro[2] - q[3]*gyro[1]),
0.5*( q[0]*gyro[1] - q[1]*gyro[2] + q[3]*gyro[0]),
0.5*( q[0]*gyro[2] + q[1]*gyro[1] - q[2]*gyro[0])
)
);
if(!((accel[0]==0.0) && (accel[1]==0.0) && (accel[2]==0.0))) {
accel = accel.normalize();
magn = magn.normalize();
//TODO: Finish this
}
}
void update(Vector3 gyro, Vector3 accel) {
Quaternion qDot(
0.5*(-q[1]*gyro[0] - q[2]*gyro[1] - q[3]*gyro[2]),
Vector3(
0.5*( q[0]*gyro[0] + q[2]*gyro[2] - q[3]*gyro[1]),
0.5*( q[0]*gyro[1] - q[1]*gyro[2] + q[3]*gyro[0]),
0.5*( q[0]*gyro[2] + q[1]*gyro[1] - q[2]*gyro[0])
)
);
if(!((accel[0]==0.0) && (accel[1]==0.0) && (accel[2]==0.0))) {
accel = accel.normalize();
double _2q0 = 2.0*q[0];
double _2q1 = 2.0*q[1];
double _2q2 = 2.0*q[2];
double _2q3 = 2.0*q[3];
double _4q0 = 2.0*q[0];
double _4q1 = 2.0*q[1];
double _4q2 = 2.0*q[2];
double _8q1 = 2.0*q[1];
double _8q2 = 2.0*q[2];
double q0q0 = q[0]*q[0];
double q1q1 = q[1]*q[1];
double q2q2 = q[2]*q[2];
double q3q3 = q[3]*q[3];
Quaternion s(
_4q0*q2q2 + _2q2*accel[0] + _4q0*q1q1 - _2q1*accel[1],
Vector3(
_4q1*q3q3 - _2q3*accel[0] + 4.0*q0q0*q[1] - _2q0*accel[1] - _4q1 + _8q1*q1q1 + _8q1*q2q2 + _4q1*accel[2],
4.0*q0q0*q[2] + _2q0*accel[0] + _4q2*q3q3 - _2q3*accel[1] - _4q2 + _8q2*q1q1 + _8q2*q2q2 + _4q2*accel[2],
4.0*q1q1*q[3] - _2q1*accel[0] + 4.0*q2q2*q[3] - _2q2*accel[1]
)
);
s.normalize();
qDot = qDot + -1.0*(beta*s);
}
q = q + (qDot*period);
q.normalize();
}
Vector3 get_angles() {
return ((q.conjugate()).Euler_ZYX()) * (180.0/M_PI);
}
};
#endif
|
#include <iostream>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <string>
#include <queue>
#include <algorithm>
#include <unordered_map>
#include <numeric>
using namespace std;
//递归:
void quicksort_dg(vector<int>& data, int i, int j)
{
int l = i, r = j;
int x = data[l];
if (l >= r) return;
while (l < r) {
while (l < r && data[r] > x) r--;
if (l < r) {
data[l] = data[r];
l++;
}
while (l < r && data[l] < x) l++;
if (l < r) {
data[r] = data[l];
r--;
}
}
data[l] = x;
quicksort_dg(data, i, l - 1);
quicksort_dg(data, l + 1, j);
return;
}
//非递归: 所有迭代都可以用栈来模拟
int partition(vector<int>& data, int l, int r)
{
int x = data[l];
if (l >= r) return l;
while (l < r && data[r] > x) r--;
if (l < r) {
data[l] = data[r];
l++;
}
while (l < r && data[l] < x) l++;
if (l < r) {
data[r] = data[l];
r--;
}
data[l] = x;
return l;
}
void quicksort_stk(vector<int>& data, int l, int r)
{
stack<int> st;
if (l < r) {
int tmp = partition(data, l, r);
if (tmp - 1 > l) // 左边不止一个元素
{
st.push(tmp - 1);//push右边界
st.push(l);//push左边界
}
if (tmp + 1 < r) // 右边不止一个元素
{
st.push(r);
st.push(tmp + 1);
}
}
while (!st.empty())
{
int start = st.top();
st.pop();
int end = st.top();
st.pop();
int tmp = partition(data, start, end);
if (tmp - 1 > start) {
st.push(tmp - 1);
st.push(start);
}
if (tmp + 1 < end) // 右边不止一个元素
{
st.push(end);
st.push(tmp + 1);
}
}
return;
}
void printNum(vector<int>& data)
{
for (int i = 0; i < data.size(); i++)
{
cout << data[i] << ' ';
}
cout << endl;
return ;
}
int main()
{
vector<int> num{ 4,2,1,5,6,7,3,0,9 };
vector<int> num1 = num;
quicksort_dg(num, 0, num.size() - 1);
quicksort_stk(num1, 0, num1.size() - 1);
printNum(num);
printNum(num1);
return 0;
}
|
#include "EndConversation.hpp"
#include "ConversationControl.hpp"
#include "FileHandling.hpp"
EndConversation::EndConversation(std::string command, std::shared_ptr<ChatInformation> chatInfo) :
TerminalCommand(command)
, _chatInfo(chatInfo)
{
_log.function("EndConversation() C-TOR");
}
bool EndConversation::doCommand() const
{
_log.function("EndConversation::doCommand() start");
ConversationControl::isConversationRunning_ = false;
auto chatFolder = *FileInterface::Accesor::getFolderName(_chatInfo->_chatPath);
if (FileInterface::Managment::isFileExist(chatFolder + "/END"))
{
_log.info("EndConversation::doCommand() remove chat folder");
_log.info(chatFolder);
std::string command = "rm -rf " + chatFolder;
return system(command.c_str());
}
_log.info("EndConversation::doCommand() create END flag");
return FileInterface::Managment::createFile(chatFolder + "/END");
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.