text
stringlengths 8
6.88M
|
|---|
#include "gl_utils.h"
//#if __GUEST
//#include "egl.h"
//#else
//#include "dprint.h"
//#include <GLES/gl.h>
//#include <GLES/glext.h>
//#define //EGL_ABORT ABORT
//#endif
size_t gl_sizeof(GLenum type)
{
size_t retval = 0;
switch(type)
{
case GL_BYTE:
case GL_UNSIGNED_BYTE:
retval = 1;
break;
case GL_SHORT:
case GL_UNSIGNED_SHORT:
//case GL_HALF_FLOAT:
// retval = 2;
// break;
//case GL_INT:
case GL_FLOAT:
case GL_FIXED:
//case GL_BOOL:
retval = 4;
break;
//case GL_DOUBLE:
// retval = 8;
// break;
//case GL_FLOAT_VEC2:
//case GL_INT_VEC2:
//case GL_BOOL_VEC2:
// retval = 8;
// break;
//case GL_INT_VEC3:
//case GL_BOOL_VEC3:
//case GL_FLOAT_VEC3:
// retval = 12;
// break;
//case GL_FLOAT_VEC4:
//case GL_BOOL_VEC4:
//case GL_INT_VEC4:
//case GL_FLOAT_MAT2:
// retval = 16;
// break;
//case GL_FLOAT_MAT3:
// retval = 36;
// break;
//case GL_FLOAT_MAT4:
// retval = 64;
// break;
//case GL_SAMPLER_2D:
//case GL_SAMPLER_CUBE:
// retval = 4;
// break;
default:
return 0;
}
return retval;
}
size_t gl_param_size(GLenum param)
{
size_t s = 0;
switch (param)
{
case GL_DEPTH_FUNC:
case GL_DEPTH_BITS:
case GL_MAX_CLIP_PLANES:
case GL_GREEN_BITS:
case GL_MAX_MODELVIEW_STACK_DEPTH:
case GL_MAX_PROJECTION_STACK_DEPTH:
case GL_MAX_TEXTURE_STACK_DEPTH:
case GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES:
case GL_IMPLEMENTATION_COLOR_READ_TYPE_OES:
case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
case GL_MAX_TEXTURE_SIZE:
case GL_TEXTURE_GEN_MODE_OES:
case GL_TEXTURE_ENV_MODE:
case GL_FOG_MODE:
case GL_FOG_DENSITY:
case GL_FOG_START:
case GL_FOG_END:
case GL_SPOT_EXPONENT:
case GL_CONSTANT_ATTENUATION:
case GL_LINEAR_ATTENUATION:
case GL_QUADRATIC_ATTENUATION:
case GL_SHININESS:
case GL_LIGHT_MODEL_TWO_SIDE:
case GL_POINT_SIZE:
case GL_POINT_SIZE_MIN:
case GL_POINT_SIZE_MAX:
case GL_POINT_FADE_THRESHOLD_SIZE:
case GL_CULL_FACE_MODE:
case GL_FRONT_FACE:
case GL_SHADE_MODEL:
case GL_DEPTH_WRITEMASK:
case GL_DEPTH_CLEAR_VALUE:
case GL_STENCIL_FAIL:
case GL_STENCIL_PASS_DEPTH_FAIL:
case GL_STENCIL_PASS_DEPTH_PASS:
case GL_STENCIL_REF:
case GL_STENCIL_WRITEMASK:
case GL_MATRIX_MODE:
case GL_MODELVIEW_STACK_DEPTH:
case GL_PROJECTION_STACK_DEPTH:
case GL_TEXTURE_STACK_DEPTH:
case GL_ALPHA_TEST_FUNC:
case GL_ALPHA_TEST_REF:
case GL_ALPHA_TEST:
case GL_BLEND_DST:
case GL_BLEND_SRC:
case GL_BLEND:
case GL_LOGIC_OP_MODE:
case GL_SCISSOR_TEST:
case GL_MAX_TEXTURE_UNITS:
case GL_ACTIVE_TEXTURE:
case GL_ALPHA_BITS:
case GL_ARRAY_BUFFER_BINDING:
case GL_BLUE_BITS:
case GL_CLIENT_ACTIVE_TEXTURE:
case GL_CLIP_PLANE0:
case GL_CLIP_PLANE1:
case GL_CLIP_PLANE2:
case GL_CLIP_PLANE3:
case GL_CLIP_PLANE4:
case GL_CLIP_PLANE5:
case GL_COLOR_ARRAY:
case GL_COLOR_ARRAY_BUFFER_BINDING:
case GL_COLOR_ARRAY_SIZE:
case GL_COLOR_ARRAY_STRIDE:
case GL_COLOR_ARRAY_TYPE:
case GL_COLOR_LOGIC_OP:
case GL_COLOR_MATERIAL:
case GL_PACK_ALIGNMENT:
case GL_PERSPECTIVE_CORRECTION_HINT:
case GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES:
case GL_POINT_SIZE_ARRAY_STRIDE_OES:
case GL_POINT_SIZE_ARRAY_TYPE_OES:
case GL_POINT_SMOOTH:
case GL_POINT_SMOOTH_HINT:
case GL_POINT_SPRITE_OES:
case GL_COORD_REPLACE_OES:
case GL_COMBINE_ALPHA:
case GL_SRC0_RGB:
case GL_SRC1_RGB:
case GL_SRC2_RGB:
case GL_OPERAND0_RGB:
case GL_OPERAND1_RGB:
case GL_OPERAND2_RGB:
case GL_SRC0_ALPHA:
case GL_SRC1_ALPHA:
case GL_SRC2_ALPHA:
case GL_OPERAND0_ALPHA:
case GL_OPERAND1_ALPHA:
case GL_OPERAND2_ALPHA:
case GL_RGB_SCALE:
case GL_ALPHA_SCALE:
case GL_COMBINE_RGB:
case GL_POLYGON_OFFSET_FACTOR:
case GL_POLYGON_OFFSET_FILL:
case GL_POLYGON_OFFSET_UNITS:
case GL_RED_BITS:
case GL_RESCALE_NORMAL:
case GL_SAMPLE_ALPHA_TO_COVERAGE:
case GL_SAMPLE_ALPHA_TO_ONE:
case GL_SAMPLE_BUFFERS:
case GL_SAMPLE_COVERAGE:
case GL_SAMPLE_COVERAGE_INVERT:
case GL_SAMPLE_COVERAGE_VALUE:
case GL_SAMPLES:
case GL_STENCIL_BITS:
case GL_STENCIL_CLEAR_VALUE:
case GL_STENCIL_FUNC:
case GL_STENCIL_TEST:
case GL_STENCIL_VALUE_MASK:
//case GL_STENCIL_BACK_FUNC:
//case GL_STENCIL_BACK_VALUE_MASK:
//case GL_STENCIL_BACK_REF:
//case GL_STENCIL_BACK_FAIL:
//case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
//case GL_STENCIL_BACK_PASS_DEPTH_PASS:
//case GL_STENCIL_BACK_WRITEMASK:
case GL_TEXTURE_2D:
case GL_TEXTURE_BINDING_2D:
case GL_TEXTURE_BINDING_CUBE_MAP_OES:
case GL_TEXTURE_BINDING_EXTERNAL_OES:
case GL_TEXTURE_COORD_ARRAY:
case GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING:
case GL_TEXTURE_COORD_ARRAY_SIZE:
case GL_TEXTURE_COORD_ARRAY_STRIDE:
case GL_TEXTURE_COORD_ARRAY_TYPE:
case GL_UNPACK_ALIGNMENT:
case GL_VERTEX_ARRAY:
case GL_VERTEX_ARRAY_BUFFER_BINDING:
case GL_VERTEX_ARRAY_SIZE:
case GL_VERTEX_ARRAY_STRIDE:
case GL_VERTEX_ARRAY_TYPE:
case GL_SPOT_CUTOFF:
case GL_TEXTURE_MIN_FILTER:
case GL_TEXTURE_MAG_FILTER:
case GL_TEXTURE_WRAP_S:
case GL_TEXTURE_WRAP_T:
case GL_GENERATE_MIPMAP:
case GL_GENERATE_MIPMAP_HINT:
case GL_RENDERBUFFER_WIDTH_OES:
case GL_RENDERBUFFER_HEIGHT_OES:
case GL_RENDERBUFFER_INTERNAL_FORMAT_OES:
case GL_RENDERBUFFER_RED_SIZE_OES:
case GL_RENDERBUFFER_GREEN_SIZE_OES:
case GL_RENDERBUFFER_BLUE_SIZE_OES:
case GL_RENDERBUFFER_ALPHA_SIZE_OES:
case GL_RENDERBUFFER_DEPTH_SIZE_OES:
case GL_RENDERBUFFER_STENCIL_SIZE_OES:
case GL_RENDERBUFFER_BINDING_OES:
case GL_FRAMEBUFFER_BINDING_OES:
case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES:
case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES:
case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES:
case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES:
case GL_FENCE_STATUS_NV:
case GL_FENCE_CONDITION_NV:
case GL_TEXTURE_WIDTH_QCOM:
case GL_TEXTURE_HEIGHT_QCOM:
case GL_TEXTURE_DEPTH_QCOM:
case GL_TEXTURE_INTERNAL_FORMAT_QCOM:
case GL_TEXTURE_FORMAT_QCOM:
case GL_TEXTURE_TYPE_QCOM:
case GL_TEXTURE_IMAGE_VALID_QCOM:
case GL_TEXTURE_NUM_LEVELS_QCOM:
case GL_TEXTURE_TARGET_QCOM:
case GL_TEXTURE_OBJECT_VALID_QCOM:
case GL_BLEND_EQUATION_RGB_OES:
case GL_BLEND_EQUATION_ALPHA_OES:
case GL_BLEND_DST_RGB_OES:
case GL_BLEND_SRC_RGB_OES:
case GL_BLEND_DST_ALPHA_OES:
case GL_BLEND_SRC_ALPHA_OES:
case GL_MAX_LIGHTS:
//case GL_SHADER_TYPE:
//case GL_DELETE_STATUS:
//case GL_COMPILE_STATUS:
//case GL_INFO_LOG_LENGTH:
//case GL_SHADER_SOURCE_LENGTH:
//case GL_CURRENT_PROGRAM:
//case GL_LINK_STATUS:
//case GL_VALIDATE_STATUS:
//case GL_ATTACHED_SHADERS:
//case GL_ACTIVE_UNIFORMS:
//case GL_ACTIVE_ATTRIBUTES:
case GL_SUBPIXEL_BITS:
case GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES:
//case GL_NUM_SHADER_BINARY_FORMATS:
//case GL_SHADER_COMPILER:
//case GL_MAX_VERTEX_ATTRIBS:
//case GL_MAX_VERTEX_UNIFORM_VECTORS:
//case GL_MAX_VARYING_VECTORS:
//case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
//case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
//case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
//case GL_MAX_RENDERBUFFER_SIZE:
//case GL_MAX_TEXTURE_IMAGE_UNITS:
//case GL_REQUIRED_TEXTURE_IMAGE_UNITS:
//case GL_FRAGMENT_SHADER_DERIVATIVE_HINT:
case GL_LINE_WIDTH:
s = 1;
break;
case GL_ALIASED_LINE_WIDTH_RANGE:
case GL_ALIASED_POINT_SIZE_RANGE:
case GL_DEPTH_RANGE:
case GL_MAX_VIEWPORT_DIMS:
case GL_SMOOTH_POINT_SIZE_RANGE:
case GL_SMOOTH_LINE_WIDTH_RANGE:
s= 2;
break;
case GL_SPOT_DIRECTION:
case GL_POINT_DISTANCE_ATTENUATION:
case GL_CURRENT_NORMAL:
s = 3;
break;
//case GL_CURRENT_VERTEX_ATTRIB:
case GL_CURRENT_TEXTURE_COORDS:
case GL_CURRENT_COLOR:
case GL_FOG_COLOR:
case GL_AMBIENT:
case GL_DIFFUSE:
case GL_SPECULAR:
case GL_EMISSION:
case GL_POSITION:
case GL_LIGHT_MODEL_AMBIENT:
case GL_TEXTURE_ENV_COLOR:
case GL_SCISSOR_BOX:
case GL_VIEWPORT:
case GL_TEXTURE_CROP_RECT_OES:
case GL_COLOR_CLEAR_VALUE:
case GL_COLOR_WRITEMASK:
case GL_AMBIENT_AND_DIFFUSE:
//case GL_BLEND_COLOR:
s = 4;
break;
case GL_MODELVIEW_MATRIX:
case GL_PROJECTION_MATRIX:
case GL_TEXTURE_MATRIX:
s = 16;
break;
default:
////EGL_PRINTF("gl_param_size: unknown param %x\n", param);
////EGL_ABORT("gl_param_size");
s = 1;
}
return s;
}
size_t gl_pixel_size(GLenum format, GLenum type)
{
int components = 0;
size_t componentsize = 0;
size_t pixelsize = 0;
switch (type)
{
case GL_BYTE:
case GL_UNSIGNED_BYTE:
componentsize = 1;
break;
case GL_SHORT:
case GL_UNSIGNED_SHORT:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
//case GL_RGB565:
//case GL_RGB5_A1:
//case GL_RGBA4:
pixelsize = 2;
break;
//case GL_INT:
case GL_UNSIGNED_INT:
case GL_FLOAT:
case GL_FIXED:
//case GL_UNSIGNED_INT_24_8:
pixelsize = 4;
break;
default:
//EGL_PRINTF("gl_pixel_size: unknown pixel type %x - assuming pixel data 0\n", type);
//EGL_ABORT("gl_Pixel_size");
componentsize = 0;
}
if (pixelsize == 0)
{
switch(format)
{
//case GL_RED:
//case GL_GREEN:
//case GL_BLUE:
case GL_ALPHA:
case GL_LUMINANCE:
//case GL_DEPTH_COMPONENT:
//case GL_DEPTH_STENCIL:
components = 1;
break;
case GL_LUMINANCE_ALPHA:
components = 2;
break;
case GL_RGB:
//case GL_BGR:
components = 3;
break;
case GL_RGBA:
case GL_BGRA_EXT:
components = 4;
break;
default:
//EGL_PRINTF("gl_pixel_size: unknown pixel format %x\n", format);
//EGL_ABORT("gl_pixel_size 2");
components = 0;
}
pixelsize = components * componentsize;
}
return pixelsize;
}
size_t egl_attrib_size(const EGLint* attrib_list)
{
if (!attrib_list)
return 0;
size_t i;
for (i = 0; attrib_list[i] != EGL_NONE; i += 2) ;
return sizeof (EGLint) * (i + 1);
}
EGLBoolean egl_find_attribute(const EGLint *attrib_list, EGLint attrib, EGLint* val)
{
while (*attrib_list != EGL_NONE)
{
if (*attrib_list == attrib)
{
if (val)
*val = attrib_list[1];
return EGL_TRUE;
}
attrib_list += 2;
}
return EGL_FALSE;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "platforms/posix/posix_ua_component_manager.h"
OP_STATUS OpUAComponentManager::Create(OpUAComponentManager **target_pp)
{
OpAutoPtr<PosixUAComponentManager> manager(OP_NEW(PosixUAComponentManager, ()));
RETURN_OOM_IF_NULL(manager.get());
RETURN_IF_ERROR(manager->Construct());
*target_pp = manager.release();
return OpStatus::OK;
}
|
#ifndef HGRAPH_H
#define HGRAPH_H
#include <set>
#include <vector>
#include "Vertex.h"
#include "Edge.h"
#include "Attribute.h"
#include "Mark.h"
#include "VertexPos.h"
namespace graph
{
class HGraph
{
public:
typedef const Vertex* (HGraph::*filterAdjacentVertices)(const Vertex*, const Edge*);
/*constructors*/
HGraph();
/*destructor*/
virtual ~HGraph();
/*vertex methods*/
const Vertex* createVertex(const std::string& name);
const Vertex* createVertexAfterVertex(const Vertex* v, const std::string& name);
const Vertex* createVertexAfterVertexInEdge(const Vertex* v, Edge* e, const std::string& name);
int removeVertex(Vertex* v);
int linkVertices(const Vertex* a, const Vertex* b);
const Vertex* getVertex(const std::string& name);
int countVertices();
int vertexPositionInEdge(const Vertex* v, const Edge* e);
std::set<const Edge*> incidentEdges(const Vertex* v);
const Vertex* nextVertexAfterVertexInEdge(const Vertex* v, const Edge* e);
const Vertex* prevVertexBeforeVertexInEdge(const Vertex* v, const Edge* e);
std::set<const Vertex*> nextAdjacentVertices(const Vertex* v);
std::set<const Vertex*> prevAdjacentVertices(const Vertex* v);
/*attribute and mark methods*/
const Attribute* getAttribute(const std::string& name);
const Vertex* markVertex(const Vertex* v, const std::string& name, double value);
int isVertexMarked(const Vertex* v, const Attribute* a);
/*тут ещё подумать и посмотреть теорию гиперграфов*/
std::set<const Vertex*> filterVertices(const Attribute* a);
HGraph filterHGraph(int (*fun)(const Vertex& v, const Attribute& a));
protected:
private:
const Vertex* getVertexAroundVertexInEdge(const Vertex* v, const Edge* e, int dpos);
std::set<const Vertex*> adjacentVertices ( const Vertex* v, filterAdjacentVertices f);
std::set<Vertex>* vertices;
std::set<Edge>* edges;
std::set<Attribute>* attributes;
std::set<Mark>* marks;
std::set<VertexPos>* positions;
};
}
#endif // HGRAPH_H
|
#include <iostream>
#include <limits>
#include <sstream>
#include <stdlib.h>
#include "claseeee.h"
using namespace std;
istream& operator>>(istream& in, Farmacie& f)
{
string s;
double p;
string nr;
int ang;
cout << "Citeste denumire: ";
getline(in, f.denumire);
do
{
try
{
cout << "Citeste numarul de angajati: ";
getline(in >> ws, nr);
if (nr.find_first_not_of("0123456789") != string::npos)
throw string("Numar invalid");
ang = atoi(nr.c_str());
break;
}
catch (string error)
{
cout << "A aparut o eroare: " << error << endl;
continue;
}
} while(1);
f.numar_angajati = ang;
cout << "Citeste profitul pe toate lunile: " << endl;
for(int i = 0 ; i < 12 ; i++ )
{
do
{
try
{
cout << "Luna " << i+1 << ": " ;
getline(in >> ws, s);
if (s.find_first_not_of("0123456789.-") != string::npos)
throw string("Numar nevalid");
p = atof(s.c_str());
break;
}
catch (string error)
{
cout << "A aparut o eroare: " << error << endl;
continue;
}
} while(1);
f.profit[i] = p;
}
return in;
}
ostream& operator<<( ostream& on, const Farmacie& f )
{
f.Afisare(on);
return on;
}
const Farmacie& Farmacie :: operator=( const Farmacie& a)
{
if(this != &a)
{
denumire = a.denumire;
numar_angajati = a.numar_angajati;
for(int i = 0 ; i < 12 ; i++ )
profit[i] = a.profit[i];
}
return *this;
}
istream& operator>>(istream& in, Farmacie_Online& f)
{
Farmacie far;
in >> far;
f.denumire = far.get_denumire();
f.numar_angajati = far.get_numar_angajati();
for(int i = 0 ; i < 12 ; i++ )
f.profit[i] = far.get_profit(i);
cout << "Adresa web: " ;
getline(in >> ws, f.adresa_web);
string s;
do{
try
{
cout << endl << "Numar vizitatori: ";
getline(in >> ws, s);
if(s.find_first_not_of("0123456789") != string::npos)
throw string("Caracter nevalid!");
f.numarul_de_vizitatori = atoi(s.c_str());
break;
}
catch(string Eroare)
{
cout << endl << "Eroare: " << Eroare << endl;
continue;
}
}while(1);
do
{
try
{
cout << endl << "Discountul utilizat: ";
getline(in >> ws, s);
if(s.find_first_not_of("1234567890.") != string::npos)
throw string("Caracter nevalid!");
f.discountul_utilizat = atof(s.c_str());
if( 0 > f.discountul_utilizat || 75 < f.discountul_utilizat )
throw string("Discount apartine intervalului [0,75]");
break;
}
catch(string Eroare)
{
cout << endl << "Eroare: " << Eroare << endl;
continue;
}
}while(1);
cout << endl;
return in ;
}
ostream& operator<<(ostream& on,const Farmacie_Online& f)
{
f.Afisare(on);
return on;
}
const Farmacie_Online& Farmacie_Online :: operator=( const Farmacie_Online& a )
{
if(this != &a )
{
denumire = a.denumire;
numar_angajati = a.numar_angajati;
for(int i = 0 ; i < 12 ; i++ )
profit[i] = a.profit[i];
adresa_web = a.adresa_web;
numarul_de_vizitatori = a.numarul_de_vizitatori;
discountul_utilizat = a.discountul_utilizat;
}
return *this;
}
template <class T>
int GestionareFarmacie<T>::index = 0;
int main()
{
int i, j;
GestionareFarmacie<Farmacie> F(1);
GestionareFarmacie<unsigned> U;
int n;
do {
try
{
string s;
cout << "Numarul de farmacii: ";
getline(cin >> ws, s);
if(s.find_first_not_of("1234567890") != string::npos)
throw string("Caracter nevalid!");
n = atoi(s.c_str());
if(n <= 0)
throw string("Numar neacceptat!");
break;
}
catch(string eroare)
{
cout << endl << "A aparut o eroare: " << eroare << endl;
continue;
}
}while(1);
i = 0;
while( i < n )
{
do
{
try
{
string s;
cout << endl << "1. Farmacie " << endl << "2. Farmacie Online" << endl;
cout << "Alege optiune: ";
getline(cin >> ws, s);
if (s.find_first_not_of("0123456789") != string::npos)
throw string("Format nevalid al numarului");
j = atoi(s.c_str());
break;
}
catch (string eroare)
{
cout << endl << "A aparut o eroare: " << eroare << endl;
}
}while (1);
cout << endl;
switch(j)
{
case 1 :
{
cout << endl;
Farmacie* M = new Farmacie;
cin >> (*M);
F += (*M);
i++;
break;
}
case 2 :
{
cout << endl;
Farmacie_Online* M = new Farmacie_Online;
cin >> (*M);
F += (*M);
U.set_nr(M->get_numarul_de_vizitatori() + U.get_nr());
i++;
break;
}
default:
{
cout << "Optiune nevalida! Alege din nou optiunea!" << endl;
}
}
}
vector<Farmacie*> v = F.get_vector();
for(i = 0 ; i < v.size() ; i++ )
{
if(Farmacie_Online* N = dynamic_cast<Farmacie_Online*>(v[i]))
{
cout << endl << "Farmacie Online: " << (*N) << endl;
}
else
if(Farmacie* N = dynamic_cast<Farmacie*>(v[i]))
{
cout << endl << "Farmacie: " << (*N) << endl;
}
}
cout << U;
return 0;
}
|
/**************************************************************************/
/* */
/* Copyright (c) 2013-2022 Orbbec 3D Technology, Inc */
/* */
/* PROPRIETARY RIGHTS of Orbbec 3D Technology are involved in the */
/* subject matter of this material. All manufacturing, reproduction, use, */
/* and sales rights pertaining to this subject matter are governed by the */
/* license agreement. The recipient of this software implicitly accepts */
/* the terms of the license. */
/* */
/**************************************************************************/
#include "astra_camera/ob_camera_node.h"
#include <cv_bridge/cv_bridge.h>
#include <boost/algorithm/string.hpp>
#include <utility>
namespace astra_camera {
OBCameraNode::OBCameraNode(ros::NodeHandle& nh, ros::NodeHandle& nh_private,
std::shared_ptr<openni::Device> device, bool use_uvc_camera)
: nh_(nh),
nh_private_(nh_private),
device_(std::move(device)),
use_uvc_camera_(use_uvc_camera) {
init();
}
OBCameraNode::~OBCameraNode() {
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
ROS_INFO_STREAM("OBCameraNode::~OBCameraNode");
clean();
ROS_INFO_STREAM("OBCameraNode::~OBCameraNode done.");
}
void OBCameraNode::clean() {
is_running_.store(false);
ROS_INFO_STREAM("OBCameraNode::clean stop poll frame");
run_poll_frame_thread_ = false;
if (poll_frame_thread_ && poll_frame_thread_->joinable()) {
poll_frame_thread_->join();
}
ROS_INFO_STREAM("OBCameraNode::clean stop poll frame done");
ROS_INFO_STREAM("OBCameraNode::clean stop tf");
if (tf_thread_ != nullptr && tf_thread_->joinable()) {
tf_thread_->join();
}
ROS_INFO_STREAM("OBCameraNode::clean stop tf done.");
stopStreams();
for (const auto& stream_index : IMAGE_STREAMS) {
if (streams_[stream_index]) {
streams_[stream_index]->destroy();
streams_[stream_index].reset();
}
}
ROS_INFO_STREAM("OBCameraNode::clean stop streams done.");
if (uvc_camera_driver_ != nullptr) {
ROS_INFO_STREAM("OBCameraNode::stop uvc camera.");
uvc_camera_driver_.reset();
ROS_INFO_STREAM("OBCameraNode::stop uvc camera done.");
}
if (device_ && device_->isValid()) {
ROS_INFO_STREAM("OBCameraNode::clean close device");
device_->close();
ROS_INFO_STREAM("OBCameraNode::clean close device done.");
}
ROS_INFO("OBCameraNode::clean stop streams done.");
}
void OBCameraNode::init() {
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
is_running_.store(true);
device_info_ = device_->getDeviceInfo();
setupConfig();
setupTopics();
if (enable_d2c_viewer_) {
d2c_filter_ = std::make_unique<D2CViewer>(nh_, nh_private_);
}
setupUVCCamera();
setupD2CConfig();
for (const auto& stream_index : IMAGE_STREAMS) {
if (streams_[stream_index]) {
save_images_[stream_index] = false;
}
}
init_ir_gain_ = getIRGain();
init_ir_exposure_ = getIRExposure();
if (enable_reconfigure_) {
reconfigure_server_ = std::make_unique<ReconfigureServer>(nh_private_);
reconfigure_server_->setCallback([this](const AstraConfig& config, uint32_t level) {
this->reconfigureCallback(config, level);
});
}
if (keep_alive_) {
keep_alive_timer_ =
nh_.createTimer(ros::Duration(keep_alive_interval_), &OBCameraNode::sendKeepAlive, this);
}
if (enable_pointcloud_) {
point_cloud_xyz_node_ = std::make_unique<PointCloudXyzNode>(nh_, nh_private_);
}
if (enable_pointcloud_xyzrgb_) {
point_cloud_xyzrgb_node_ = std::make_unique<PointCloudXyzrgbNode>(nh_, nh_private_);
}
run_poll_frame_thread_ = true;
poll_frame_thread_ = std::make_unique<std::thread>(&OBCameraNode::pollFrame, this);
initialized_ = true;
for (const auto& stream_index : IMAGE_STREAMS) {
if (!enable_[stream_index]) {
continue;
}
if (use_uvc_camera_ && stream_index == COLOR) {
continue;
}
sensor_msgs::CameraInfo camera_info;
if (stream_index == COLOR) {
camera_info = getColorCameraInfo();
} else if (stream_index == DEPTH) {
camera_info = getDepthCameraInfo();
} else {
int width = width_[stream_index];
int height = height_[stream_index];
double f = getFocalLength(stream_index, width);
camera_info = getIRCameraInfo(width, height, f);
}
camera_info.header.stamp = ros::Time::now();
camera_info.header.frame_id = optical_frame_id_[stream_index];
camera_info_publishers_.at(stream_index).publish(camera_info);
}
ROS_INFO_STREAM("OBCameraNode initialized");
}
void OBCameraNode::setupConfig() {
stream_name_[DEPTH] = "depth";
unit_step_size_[DEPTH] = sizeof(uint16_t);
format_[DEPTH] = openni::PIXEL_FORMAT_DEPTH_1_MM;
image_format_[DEPTH] = CV_16UC1;
encoding_[DEPTH] = sensor_msgs::image_encodings::TYPE_16UC1;
stream_name_[COLOR] = "color";
unit_step_size_[COLOR] = 3;
format_[COLOR] = openni::PIXEL_FORMAT_RGB888;
image_format_[COLOR] = CV_8UC3;
encoding_[COLOR] = sensor_msgs::image_encodings::RGB8;
stream_name_[INFRA1] = "ir";
unit_step_size_[INFRA1] = sizeof(uint8_t);
format_[INFRA1] = openni::PIXEL_FORMAT_GRAY8;
image_format_[INFRA1] = CV_8UC1;
encoding_[INFRA1] = sensor_msgs::image_encodings::MONO8;
stream_name_[INFRA2] = "ir2";
unit_step_size_[INFRA2] = sizeof(uint8_t);
format_[INFRA2] = openni::PIXEL_FORMAT_GRAY8;
image_format_[INFRA2] = CV_8UC1;
encoding_[INFRA2] = sensor_msgs::image_encodings::MONO8;
}
void OBCameraNode::setupCameraInfoManager() {
ir_info_manager_ = std::make_unique<camera_info_manager::CameraInfoManager>(
nh_private_, "ir_camera", ir_info_uri_);
if (!use_uvc_camera_ && device_->hasSensor(openni::SENSOR_COLOR)) {
color_info_manager_ = std::make_unique<camera_info_manager::CameraInfoManager>(
nh_, "rgb_camera", color_info_uri_);
}
}
void OBCameraNode::setupDevices() {
for (const auto& stream_index : IMAGE_STREAMS) {
stream_started_[stream_index] = false;
if (enable_[stream_index] && device_->hasSensor(stream_index.first)) {
if (use_uvc_camera_ && stream_index == COLOR) {
continue;
}
auto stream = std::make_shared<openni::VideoStream>();
auto status = stream->create(*device_, stream_index.first);
if (status != openni::STATUS_OK) {
std::stringstream ss;
ss << "OBCameraNode::setupDevices failed to create stream " << stream_name_[stream_index]
<< " with error: " << openni::OpenNI::getExtendedError();
ROS_ERROR_STREAM(ss.str());
throw std::runtime_error(ss.str());
}
streams_[stream_index] = stream;
} else {
if (streams_[stream_index]) {
streams_[stream_index].reset();
}
enable_[stream_index] = false;
}
}
}
void OBCameraNode::setupFrameCallback() {
for (const auto& stream_index : IMAGE_STREAMS) {
if (enable_[stream_index] && device_->hasSensor(stream_index.first)) {
auto frame_callback = [this,
stream_index = stream_index](const openni::VideoFrameRef& frame) {
this->onNewFrameCallback(frame, stream_index);
};
stream_frame_callback_[stream_index] = frame_callback;
}
}
}
void OBCameraNode::setupVideoMode() {
if (!use_uvc_camera_ && enable_[INFRA1] && enable_[COLOR]) {
ROS_WARN_STREAM(
"Infrared and Color streams are enabled. "
"Infrared stream will be disabled.");
enable_[INFRA1] = false;
}
for (const auto& stream_index : IMAGE_STREAMS) {
supported_video_modes_[stream_index] = std::vector<openni::VideoMode>();
if (device_->hasSensor(stream_index.first) && enable_[stream_index]) {
if (use_uvc_camera_ && stream_index == COLOR) {
continue;
}
auto stream = streams_[stream_index];
const auto& sensor_info = stream->getSensorInfo();
const auto& supported_video_modes = sensor_info.getSupportedVideoModes();
int size = supported_video_modes.getSize();
for (int i = 0; i < size; i++) {
supported_video_modes_[stream_index].emplace_back(supported_video_modes[i]);
}
openni::VideoMode video_mode, default_video_mode;
video_mode.setResolution(width_[stream_index], height_[stream_index]);
default_video_mode.setResolution(width_[stream_index], height_[stream_index]);
video_mode.setFps(fps_[stream_index]);
video_mode.setPixelFormat(format_[stream_index]);
default_video_mode.setPixelFormat(format_[stream_index]);
bool is_supported_mode = false;
bool is_default_mode_supported = false;
for (const auto& item : supported_video_modes_[stream_index]) {
if (video_mode == item) {
is_supported_mode = true;
stream_video_mode_[stream_index] = video_mode;
break;
}
if (default_video_mode.getResolutionX() == item.getResolutionX() &&
default_video_mode.getResolutionY() == item.getResolutionY() &&
default_video_mode.getPixelFormat() == item.getPixelFormat()) {
default_video_mode.setFps(item.getFps());
is_default_mode_supported = true;
}
}
if (!is_supported_mode) {
ROS_WARN_STREAM("Video mode " << video_mode << " is not supported. ");
if (is_default_mode_supported) {
ROS_WARN_STREAM("Default video mode " << default_video_mode
<< " is supported. "
"Stream will be enabled.");
stream_video_mode_[stream_index] = default_video_mode;
video_mode = default_video_mode;
is_supported_mode = true;
} else {
ROS_WARN_STREAM("Default video mode " << default_video_mode
<< "is not supported. "
"Stream will be disabled.");
enable_[stream_index] = false;
ROS_WARN_STREAM("Supported video modes: ");
for (const auto& item : supported_video_modes_[stream_index]) {
ROS_WARN_STREAM(item);
}
}
}
if (is_supported_mode) {
ROS_INFO_STREAM("set " << stream_name_[stream_index] << " video mode " << video_mode);
images_[stream_index] = cv::Mat(height_[stream_index], width_[stream_index],
image_format_[stream_index], cv::Scalar(0, 0, 0));
}
}
}
}
void OBCameraNode::setupD2CConfig() {
if (!depth_align_ && !enable_pointcloud_xyzrgb_) {
return;
}
auto color_width = width_[COLOR];
auto color_height = height_[COLOR];
setImageRegistrationMode(depth_align_);
setDepthColorSync(color_depth_synchronization_);
if (depth_align_ || enable_pointcloud_xyzrgb_) {
setDepthToColorResolution(color_width, color_height);
}
}
void OBCameraNode::startStream(const stream_index_pair& stream_index) {
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
if (!enable_[stream_index]) {
ROS_WARN_STREAM("Stream " << stream_name_[stream_index] << " is not enabled.");
return;
}
if (stream_index == COLOR && use_uvc_camera_) {
return;
}
auto pid = device_->getDeviceInfo().getUsbProductId();
if (pid == ASTRA_PRO_DEPTH_PID && stream_index == COLOR) {
return;
}
if (stream_started_[stream_index]) {
ROS_WARN_STREAM("Stream " << stream_name_[stream_index] << " is already started.");
return;
}
ROS_INFO_STREAM("Start " << stream_name_[stream_index] << " stream.");
bool has_subscribers = image_publishers_[stream_index].getNumSubscribers() > 0;
if (!has_subscribers) {
ROS_INFO_STREAM("No subscribers for " << stream_name_[stream_index]
<< " stream. "
"Stream will be disabled.");
return;
}
CHECK(stream_video_mode_.count(stream_index));
auto video_mode = stream_video_mode_.at(stream_index);
CHECK(streams_.count(stream_index));
CHECK(streams_[stream_index].get());
streams_[stream_index]->setVideoMode(video_mode);
streams_[stream_index]->setMirroringEnabled(false);
auto status = streams_[stream_index]->start();
if (status == openni::STATUS_OK) {
stream_started_[stream_index] = true;
ROS_INFO_STREAM(stream_name_[stream_index] << " is started");
} else {
ROS_ERROR_STREAM("openni status " << status);
ROS_ERROR_STREAM("current errno " << errno << " system error string " << strerror(errno));
ROS_ERROR_STREAM(stream_name_[stream_index] << " start failed with ERROR "
<< openni::OpenNI::getExtendedError());
}
}
void OBCameraNode::stopStream(const stream_index_pair& stream_index) {
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
if (!enable_[stream_index]) {
ROS_WARN_STREAM("Stream " << stream_name_[stream_index] << " is not enabled.");
return;
}
if (!stream_started_[stream_index]) {
ROS_WARN_STREAM("Stream " << stream_name_[stream_index] << " is not started.");
return;
}
ROS_INFO_STREAM("Stop " << stream_name_[stream_index] << " stream.");
ROS_INFO_STREAM("OBCameraNode::stopStream stop");
streams_[stream_index]->stop();
ROS_INFO_STREAM("OBCameraNode::stopStream stop");
ROS_INFO_STREAM("Stop stream " << stream_name_[stream_index] << " done.");
stream_started_[stream_index] = false;
}
void OBCameraNode::startStreams() {
for (const auto& stream_index : IMAGE_STREAMS) {
if (enable_[stream_index] && !stream_started_[stream_index]) {
startStream(stream_index);
}
}
}
void OBCameraNode::stopStreams() {
for (const auto& stream_index : IMAGE_STREAMS) {
if (stream_started_[stream_index]) {
stopStream(stream_index);
}
}
}
void OBCameraNode::getParameters() {
camera_name_ = nh_private_.param<std::string>("camera_name", "camera");
base_frame_id_ = camera_name_ + "_link";
for (const auto& stream_index : IMAGE_STREAMS) {
frame_id_[stream_index] = camera_name_ + "_" + stream_name_[stream_index] + "_frame";
optical_frame_id_[stream_index] =
camera_name_ + "_" + stream_name_[stream_index] + "_optical_frame";
}
for (const auto& stream_index : IMAGE_STREAMS) {
std::string param_name = stream_name_[stream_index] + "_width";
width_[stream_index] = nh_private_.param<int>(param_name, IMAGE_WIDTH);
param_name = stream_name_[stream_index] + "_height";
height_[stream_index] = nh_private_.param<int>(param_name, IMAGE_HEIGHT);
param_name = stream_name_[stream_index] + "_fps";
fps_[stream_index] = nh_private_.param<int>(param_name, IMAGE_FPS);
param_name = "enable_" + stream_name_[stream_index];
enable_[stream_index] = nh_private_.param<bool>(param_name, false);
}
for (const auto& stream_index : IMAGE_STREAMS) {
depth_aligned_frame_id_[stream_index] = optical_frame_id_[COLOR];
}
publish_tf_ = nh_private_.param<bool>("publish_tf", true);
color_depth_synchronization_ = nh_private_.param<bool>("color_depth_synchronization", false);
tf_publish_rate_ = nh_private_.param<double>("tf_publish_rate", 10.0);
color_roi_.x = nh_private_.param<int>("color_roi_x", -1);
color_roi_.y = nh_private_.param<int>("color_roi_y", -1);
color_roi_.width = nh_private_.param<int>("color_roi_width", -1);
color_roi_.height = nh_private_.param<int>("color_roi_height", -1);
depth_roi_.x = nh_private_.param<int>("depth_roi_x", -1);
depth_roi_.y = nh_private_.param<int>("depth_roi_y", -1);
depth_roi_.width = nh_private_.param<int>("depth_roi_width", -1);
depth_roi_.height = nh_private_.param<int>("depth_roi_height", -1);
depth_scale_ = nh_private_.param<int>("depth_scale", 1);
enable_reconfigure_ = nh_private_.param<bool>("enable_reconfigure", false);
depth_align_ = nh_private_.param<bool>("depth_align", false);
ir_info_uri_ = nh_private_.param<std::string>("ir_info_uri", "");
color_info_uri_ = nh_private_.param<std::string>("color_info_uri", "");
enable_d2c_viewer_ = nh_private_.param<bool>("enable_d2c_viewer", false);
keep_alive_ = nh_private_.param<bool>("keep_alive", false);
keep_alive_interval_ = nh_private_.param<int>("keep_alive_interval", 15);
enable_pointcloud_ = nh_private_.param<bool>("enable_point_cloud", false);
enable_pointcloud_xyzrgb_ = nh_private_.param<bool>("enable_point_cloud_xyzrgb", false);
enable_publish_extrinsic_ = nh_private_.param<bool>("enable_publish_extrinsic", false);
if (depth_align_ && !device_->hasSensor(openni::SENSOR_COLOR) && !use_uvc_camera_) {
ROS_WARN("No color sensor found, depth align will be disabled");
depth_align_ = false;
}
if (enable_pointcloud_xyzrgb_) {
depth_align_ = true;
}
}
void OBCameraNode::setupTopics() {
getParameters();
setupCameraInfoManager();
setupFrameCallback();
setupDevices();
setupCameraCtrlServices();
setupPublishers();
setupVideoMode();
getCameraParams();
publishStaticTransforms();
}
void OBCameraNode::setupUVCCamera() {
if (use_uvc_camera_) {
ROS_INFO("OBCameraNode::setupUVCCamera");
auto color_camera_info = getColorCameraInfo();
auto serial_number = getSerialNumber();
uvc_camera_driver_ =
std::make_shared<UVCCameraDriver>(nh_, nh_private_, color_camera_info, serial_number);
} else {
uvc_camera_driver_ = nullptr;
}
}
void OBCameraNode::imageSubscribedCallback(const stream_index_pair& stream_index) {
ROS_INFO_STREAM("Image stream " << stream_name_[stream_index] << " subscribed");
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
if (!initialized_) {
ROS_WARN_STREAM("Camera not initialized, subscribing to stream " << stream_name_[stream_index]);
return;
}
if (stream_started_[stream_index]) {
return;
}
startStream(stream_index);
}
void OBCameraNode::imageUnsubscribedCallback(const stream_index_pair& stream_index) {
ROS_INFO_STREAM("Image stream " << stream_name_[stream_index] << " unsubscribed");
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
if (!stream_started_[stream_index]) {
return;
}
auto subscriber_count = image_publishers_[stream_index].getNumSubscribers();
if (subscriber_count == 0) {
stopStream(stream_index);
}
}
void OBCameraNode::setupPublishers() {
for (const auto& stream_index : IMAGE_STREAMS) {
std::string name = stream_name_[stream_index];
camera_info_publishers_[stream_index] =
nh_.advertise<sensor_msgs::CameraInfo>(name + "/camera_info", 1, true);
if (enable_[stream_index] && device_->hasSensor(stream_index.first)) {
ros::SubscriberStatusCallback image_subscribed_cb =
boost::bind(&OBCameraNode::imageSubscribedCallback, this, stream_index);
ros::SubscriberStatusCallback image_unsubscribed_cb =
boost::bind(&OBCameraNode::imageUnsubscribedCallback, this, stream_index);
image_publishers_[stream_index] = nh_.advertise<sensor_msgs::Image>(
name + "/image_raw", 1, image_subscribed_cb, image_unsubscribed_cb);
}
}
}
void OBCameraNode::publishStaticTF(const ros::Time& t, const tf2::Vector3& trans,
const tf2::Quaternion& q, const std::string& from,
const std::string& to) {
geometry_msgs::TransformStamped msg;
msg.header.stamp = t;
msg.header.frame_id = from;
msg.child_frame_id = to;
msg.transform.translation.x = trans[2] / 1000.0;
msg.transform.translation.y = -trans[0] / 1000.0;
msg.transform.translation.z = -trans[1] / 1000.0;
msg.transform.rotation.x = q.getX();
msg.transform.rotation.y = q.getY();
msg.transform.rotation.z = q.getZ();
msg.transform.rotation.w = q.getW();
static_tf_msgs_.push_back(msg);
}
void OBCameraNode::calcAndPublishStaticTransform() {
tf2::Quaternion quaternion_optical, zero_rot;
zero_rot.setRPY(0.0, 0.0, 0.0);
quaternion_optical.setRPY(-M_PI / 2, 0.0, -M_PI / 2);
tf2::Vector3 zero_trans(0, 0, 0);
std::vector<float> rotation, transition;
bool rotation_valid = true, transition_valid = true;
for (float& i : camera_params_->r2l_r) {
rotation.emplace_back(i);
}
for (float& i : camera_params_->r2l_t) {
transition.emplace_back(i);
}
auto Q = rotationMatrixToQuaternion(rotation);
for (int i = 0; i < 9; i++) {
if (std::isnan(rotation[i])) {
Q.setRPY(0, 0, 0);
rotation_valid = false;
break;
}
}
if (!use_uvc_camera_ && !device_->hasSensor(openni::SENSOR_COLOR)) {
Q.setRPY(0, 0, 0);
}
Q = quaternion_optical * Q * quaternion_optical.inverse();
tf2::Vector3 trans(transition[0], transition[1], transition[2]);
if ((!use_uvc_camera_ && !device_->hasSensor(openni::SENSOR_COLOR)) ||
std::isnan(transition[0]) || std::isnan(transition[1]) || std::isnan(transition[2])) {
trans[0] = 0;
trans[1] = 0;
trans[2] = 0;
transition_valid = false;
}
tf2::Transform transform(Q, trans);
transform = transform.inverse();
Q = transform.getRotation();
trans = transform.getOrigin();
auto tf_timestamp = ros::Time::now();
publishStaticTF(tf_timestamp, zero_trans, quaternion_optical, frame_id_[COLOR],
optical_frame_id_[COLOR]);
publishStaticTF(tf_timestamp, zero_trans, quaternion_optical, frame_id_[DEPTH],
optical_frame_id_[DEPTH]);
publishStaticTF(tf_timestamp, zero_trans, quaternion_optical, frame_id_[INFRA1],
optical_frame_id_[INFRA1]);
publishStaticTF(tf_timestamp, zero_trans, zero_rot, base_frame_id_, frame_id_[DEPTH]);
publishStaticTF(tf_timestamp, zero_trans, zero_rot, base_frame_id_, frame_id_[INFRA1]);
publishStaticTF(tf_timestamp, trans, Q, base_frame_id_, frame_id_[COLOR]);
if (enable_publish_extrinsic_ && transition_valid && rotation_valid) {
extrinsics_publisher_ = nh_.advertise<Extrinsics>("extrinsic/depth_to_color", 1, true);
auto ex_msg = obExtrinsicsToMsg(rotation, transition, "depth_to_color");
ex_msg.header.stamp = ros::Time::now();
extrinsics_publisher_.publish(ex_msg);
}
}
void OBCameraNode::publishDynamicTransforms() {
ROS_WARN("Publishing dynamic camera transforms (/tf) at %g Hz", tf_publish_rate_);
static std::mutex mu;
std::unique_lock<std::mutex> lock(mu);
while (ros::ok() && is_running_) {
tf_cv_.wait_for(lock, std::chrono::milliseconds((int)(1000.0 / tf_publish_rate_)),
[this] { return (!(is_running_)); });
{
auto t = ros::Time::now();
for (auto& msg : static_tf_msgs_) {
msg.header.stamp = t;
}
CHECK_NOTNULL(dynamic_tf_broadcaster_.get());
dynamic_tf_broadcaster_->sendTransform(static_tf_msgs_);
}
}
}
void OBCameraNode::publishStaticTransforms() {
if (!publish_tf_) {
return;
}
static_tf_broadcaster_ = std::make_unique<tf2_ros::StaticTransformBroadcaster>();
dynamic_tf_broadcaster_ = std::make_unique<tf2_ros::TransformBroadcaster>();
calcAndPublishStaticTransform();
if (tf_publish_rate_ > 0) {
CHECK(tf_thread_ == nullptr);
tf_thread_ = std::make_shared<std::thread>([this]() { this->publishDynamicTransforms(); });
} else {
CHECK_NOTNULL(static_tf_broadcaster_.get());
static_tf_broadcaster_->sendTransform(static_tf_msgs_);
}
}
void OBCameraNode::setImageRegistrationMode(bool data) {
if (!device_->isImageRegistrationModeSupported(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR)) {
ROS_WARN_STREAM("Current do not support IMAGE_REGISTRATION_DEPTH_TO_COLOR");
return;
}
auto mode = data ? openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR : openni::IMAGE_REGISTRATION_OFF;
auto rc = device_->setImageRegistrationMode(mode);
if (rc != openni::STATUS_OK) {
ROS_ERROR("Enabling image registration mode failed: \n%s\n",
openni::OpenNI::getExtendedError());
}
}
void OBCameraNode::onNewFrameCallback(const openni::VideoFrameRef& frame,
const stream_index_pair& stream_index) {
int width = frame.getWidth();
int height = frame.getHeight();
CHECK(images_.count(stream_index));
auto& image = images_.at(stream_index);
if (image.size() != cv::Size(width, height)) {
image.create(height, width, image.type());
}
image.data = (uint8_t*)frame.getData();
cv::Mat scaled_image;
if (stream_index == DEPTH && depth_scale_ > 1) {
cv::resize(image, scaled_image, cv::Size(width * depth_scale_, height * depth_scale_), 0, 0,
cv::INTER_NEAREST);
}
auto image_msg =
*(cv_bridge::CvImage(std_msgs::Header(), encoding_.at(stream_index),
(stream_index == DEPTH && depth_scale_ > 1) ? scaled_image : image)
.toImageMsg());
auto timestamp = ros::Time::now();
image_msg.header.stamp = timestamp;
image_msg.header.frame_id =
depth_align_ ? depth_aligned_frame_id_[stream_index] : optical_frame_id_[stream_index];
image_msg.width = (stream_index == DEPTH && depth_scale_ > 1) ? width * depth_scale_ : width;
image_msg.height = (stream_index == DEPTH && depth_scale_ > 1) ? height * depth_scale_ : height;
image_msg.step = image_msg.width * unit_step_size_[stream_index];
image_msg.is_bigendian = false;
auto& image_publisher = image_publishers_.at(stream_index);
image_publisher.publish(image_msg);
sensor_msgs::CameraInfo camera_info;
if (stream_index == DEPTH) {
camera_info = getDepthCameraInfo();
} else if (stream_index == COLOR) {
camera_info = getColorCameraInfo();
} else if (stream_index == INFRA1 || stream_index == INFRA2) {
double f = getFocalLength(stream_index, width);
camera_info = getIRCameraInfo(width, height, f);
}
camera_info.header.stamp = timestamp;
camera_info_publishers_.at(stream_index).publish(camera_info);
if (save_images_[stream_index]) {
auto now = std::time(nullptr);
std::stringstream ss;
ss << std::put_time(std::localtime(&now), "%Y%m%d_%H%M%S");
auto current_path = boost::filesystem::current_path().string();
auto fps = stream_video_mode_[stream_index].getFps();
std::string filename = current_path + "/image/" + stream_name_[stream_index] + "_" +
std::to_string(image_msg.width) + "x" +
std::to_string(image_msg.height) + "_" + std::to_string(fps) + "hz_" +
ss.str() + ".jpg";
if (!boost::filesystem::exists(current_path + "/image")) {
boost::filesystem::create_directory(current_path + "/image");
}
ROS_INFO_STREAM("Saving image to " << filename);
if (stream_index != DEPTH && depth_scale_ > 1) {
cv::imwrite(filename, image);
} else {
cv::imwrite(filename, scaled_image);
}
save_images_[stream_index] = false;
}
}
void OBCameraNode::setDepthColorSync(bool data) {
auto rc = device_->setDepthColorSyncEnabled(data);
if (rc != openni::STATUS_OK) {
ROS_ERROR_STREAM(
"Enabling depth color synchronization failed: " << openni::OpenNI::getExtendedError());
}
}
void OBCameraNode::setDepthToColorResolution(int width, int height) {
const auto pid = device_info_.getUsbProductId();
if (pid != DABAI_DCW_DEPTH_PID && pid != GEMINI_E_DEPTH_PID && pid != DABAI_MAX_PID) {
return;
}
if (!depth_align_ && !enable_pointcloud_xyzrgb_) {
return;
}
if (width * 9 == height * 16) {
// 16:9
auto status = device_->setProperty(XN_MODULE_PROPERTY_D2C_RESOLUTION, RGBResolution16_9);
if (status != openni::STATUS_OK) {
ROS_ERROR_STREAM("setProperty XN_MODULE_PROPERTY_D2C_RESOLUTION "
<< openni::OpenNI::getExtendedError());
}
} else if (width * 3 == height * 4) {
// 4:3
auto status = device_->setProperty(XN_MODULE_PROPERTY_D2C_RESOLUTION, RGBResolution4_3);
if (status != openni::STATUS_OK) {
ROS_ERROR_STREAM("setProperty XN_MODULE_PROPERTY_D2C_RESOLUTION "
<< openni::OpenNI::getExtendedError());
}
} else {
ROS_ERROR_STREAM("NOT 16x9 or 4x3 resolution");
}
}
boost::optional<openni::VideoMode> OBCameraNode::lookupVideoModeFromDynConfig(int index) {
auto it = video_modes_lookup_table_.find(index);
if (it != video_modes_lookup_table_.end()) {
return it->second;
}
return {};
}
void OBCameraNode::reconfigureCallback(const AstraConfig& config, uint32_t level) {
(void)level;
ROS_INFO_STREAM("Received configuration");
if (!enable_reconfigure_) {
ROS_WARN_STREAM("Dynamic reconfigure is disabled");
return;
}
auto json_data = nlohmann::json::parse(config.edited_video_modes);
auto edited_video_modes = json_data["enum"].get<std::vector<nlohmann::json>>();
video_modes_lookup_table_.clear();
for (const auto& json_mode : edited_video_modes) {
std::string name = json_mode["name"].get<std::string>();
int value = json_mode["value"].get<int>();
std::vector<std::string> arr;
boost::split(arr, name, boost::is_any_of("_"));
assert(arr.size() == 3);
openni::VideoMode video_mode;
int x_resolution = std::stoi(arr[0]);
int y_resolution = std::stoi(arr[1]);
int fps = std::stoi(arr[2]);
video_mode.setResolution(x_resolution, y_resolution);
video_mode.setFps(fps);
video_modes_lookup_table_[value] = video_mode;
}
auto ir_mode = lookupVideoModeFromDynConfig(config.ir_mode);
if (ir_mode && device_->hasSensor(openni::SENSOR_IR)) {
ROS_INFO_STREAM("Setting IR mode to " << ir_mode->getResolutionX() << "x"
<< ir_mode->getResolutionY() << "@" << ir_mode->getFps()
<< " fps");
width_[INFRA1] = ir_mode->getResolutionX();
height_[INFRA1] = ir_mode->getResolutionY();
fps_[INFRA1] = ir_mode->getFps();
}
auto color_mode = lookupVideoModeFromDynConfig(config.color_mode);
if (color_mode && device_->hasSensor(openni::SENSOR_COLOR)) {
ROS_INFO_STREAM("Setting color mode to " << color_mode->getResolutionX() << "x"
<< color_mode->getResolutionY() << "@"
<< color_mode->getFps() << " fps");
width_[COLOR] = color_mode->getResolutionX();
height_[COLOR] = color_mode->getResolutionY();
fps_[COLOR] = color_mode->getFps();
}
auto depth_mode = lookupVideoModeFromDynConfig(config.depth_mode);
if (depth_mode && device_->hasSensor(openni::SENSOR_DEPTH)) {
ROS_INFO_STREAM("Setting depth mode to " << depth_mode->getResolutionX() << "x"
<< depth_mode->getResolutionY() << "@"
<< depth_mode->getFps() << " fps");
width_[DEPTH] = depth_mode->getResolutionX();
height_[DEPTH] = depth_mode->getResolutionY();
fps_[DEPTH] = depth_mode->getFps();
}
depth_align_ = config.depth_align;
if (depth_align_ && !device_->hasSensor(openni::SENSOR_COLOR) && !use_uvc_camera_) {
ROS_WARN("No color sensor found, depth align will be disabled");
depth_align_ = false;
}
color_depth_synchronization_ = config.color_depth_synchronization;
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
stopStreams();
setupVideoMode();
camera_params_.reset();
getCameraParams();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
startStreams();
ROS_INFO("Configuration applied");
}
void OBCameraNode::sendKeepAlive(const ros::TimerEvent& event) {
(void)event;
ROS_INFO_STREAM("Sending keep alive");
openni::Status status;
std::lock_guard<decltype(device_lock_)> lock(device_lock_);
status = device_->setProperty(XN_MODULE_PROPERTY_LASER_SECURE_KEEPALIVE, nullptr, 0);
if (status != openni::STATUS_OK) {
ROS_ERROR_STREAM("openni status " << status);
ROS_ERROR_STREAM("current errno " << errno << " system error string " << strerror(errno));
ROS_INFO("Sending keep alive Error: %s\n", openni::OpenNI::getExtendedError());
} else {
ROS_INFO("Sending keep alive success\n");
}
}
void OBCameraNode::pollFrame() {
openni::VideoFrameRef frame;
while (run_poll_frame_thread_ && ros::ok()) {
std::unique_lock<decltype(poll_frame_thread_lock_)> lock(poll_frame_thread_lock_);
auto has_stream_started =
poll_frame_thread_cv_.wait_for(lock, std::chrono::milliseconds(1000), [this] {
return std::any_of(
IMAGE_STREAMS.begin(), IMAGE_STREAMS.end(),
[this](const stream_index_pair& stream_index) {
if (stream_started_[stream_index] && streams_[stream_index]->isValid()) {
return true;
}
return false;
});
});
if (!has_stream_started) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
continue;
}
openni::VideoStream* streams[3];
std::map<int, stream_index_pair> idx_map;
int stream_count = 0;
for (const auto& stream_index : IMAGE_STREAMS) {
if (enable_[stream_index] && streams_[stream_index].get()) {
streams[stream_count] = streams_[stream_index].get();
idx_map[stream_count] = stream_index;
stream_count++;
}
}
int ready_stream = -1;
const static int timeout_ms(2000);
auto status =
openni::OpenNI::waitForAnyStream(streams, stream_count, &ready_stream, timeout_ms);
if (status != openni::STATUS_OK) {
continue;
}
CHECK(ready_stream != -1);
auto stream_index = idx_map[ready_stream];
status = streams[ready_stream]->readFrame(&frame);
if (status != openni::STATUS_OK) {
ROS_ERROR_STREAM("read " << stream_name_[stream_index] << " stream failed "
<< openni::OpenNI::getExtendedError());
continue;
}
onNewFrameCallback(frame, stream_index);
}
}
} // namespace astra_camera
|
int MinRepresstation(string S)
{
int i = 0, j = 1, k = 0;
int len = S.length();
S += S;
while(i < len && j < len)
{
k = 0;
while(k < len && S[i + k] == S[j + k])
k++;
if(k >= len)
break;
if(S[i + k] > S[j + k])
i = max(i + k + 1, j + 1);
else
j = max(i + 1, j + k + 1);
}
return min(i ,j); // 返回的是起点
}
|
#include<bits/stdc++.h>
#include<unistd.h>
#include<cmath>
using namespace std;
void findNextFit(vector<int> jobs, vector<int> block) {
system("clear");
cout<<"\n\nNEXT FIT\n";
int intfrag = 0;
int prev = -1;
vector<int> visited(block.size(), 0);
for(int i = 0; i < jobs.size(); i++) {
vector<int> visited1(block.size(), 0);
cout<<"\n";
for(int j = 0; j < block.size(); j++)
cout<<block[j]<<" | ";
int flag = 0;
int res = -1;
int j = (prev + 1) % block.size();
while(visited1[j] == 0) {
if(block[j] >= jobs[i]) {
flag = 1;
res = j;
prev = j;
visited[j] = 1;
block[j] -= jobs[i];
break;
}
visited1[j] = 1;
j = (j + 1) % block.size();
}
cout<<"\n";
if(flag == 0) {
cout<<"\nProcess "<<i + 1<<" cannot be allocated\n";
continue;
}
cout<<"\nProcess "<<i + 1<<" is allocated to block "<<res + 1<<"\n";
for(int k = 0; k < block.size(); k++) {
cout<<block[k]<<" | ";
}
cout<<"\n";
for(int k = 0; k < res; k++) {
cout<<" ";
}
printf("\u2191");
cout<<"\n\nPress Enter to continue\n";
//sleep(2);
cin.ignore();
system("clear");
}
for(int i = 0; i < block.size(); i++) {
if(visited[i] == 1)
intfrag += block[i];
}
cout<<"\nTotal memory wastage is: "<<intfrag<<"\n";
}
int main() {
int n;
cout<<"\nEnter the total number of jobs: ";
cin>>n;
vector<int> jobs(n);
cout<<"\nEnter the jobs: ";
for(int i = 0; i < n; i++)
cin>>jobs[i];
cout<<"\nEnter the number of blocks: ";
int m;
cin>>m;
vector<int> block(m);
cout<<"\nEnter the block size: ";
for(int i = 0; i < m; i++)
cin>>block[i];
cin.ignore();
findNextFit(jobs, block);
return 0;
}
|
//Author: Aishwarya Ketkar
//Date: 02/15/2015
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <vector>
using namespace std;
//Calculates the normal distribution CDF
double NormalCdfCalc (double x)
{
double a1 = 0.2548;
double a2 = -0.2844;
double a3 = 1.4214;
double a4 = -1.4531;
double a5 = 1.0614;
double p = 0.3275;
int sign = 1;
if (x < 0)
sign = -1;
x = fabs(x)/sqrt(2.0);
double t = 1.0/(1.0 + p*x);
double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);
return 0.5*(1.0 + sign*y);
}
//Pricing the Call option
void BlackScholesCall(double StockPriceAt0, double TimeToMaturity, double StrikePrice,
double RiskFreeRate, double Sigma){
double PriceOfCall;
double d1, d2;
d1= (log(StockPriceAt0/StrikePrice)+(RiskFreeRate+(Sigma*Sigma/2)*TimeToMaturity))/
pow(TimeToMaturity,StrikePrice/ 2);
d2= d1- pow(TimeToMaturity,StrikePrice/ 2);
PriceOfCall= StockPriceAt0*NormalCdfCalc(d1) - (NormalCdfCalc(d2)*StrikePrice*exp(-RiskFreeRate*TimeToMaturity));
cout << PriceOfCall << " is the call price" <<endl;
}
//Pricing the Put Option
void BlackScholesPut(double StockPriceAt0, double TimeToMaturity, double StrikePrice,
double RiskFreeRate, double Sigma){
double PriceOfPut;
double d1, d2;
d1= (log(StockPriceAt0/StrikePrice)+(RiskFreeRate+(Sigma*Sigma/2)*TimeToMaturity))/
pow(TimeToMaturity,StrikePrice/ 2);
d2= d1- pow(TimeToMaturity,StrikePrice/ 2);
PriceOfPut= NormalCdfCalc(-d2)*StrikePrice*exp(-RiskFreeRate*TimeToMaturity) - StockPriceAt0*NormalCdfCalc(-d1);
cout << PriceOfPut << " is the put price" <<endl;
}
//Driver function
int main() {
double S0= 18;
double T= 4;
double K= 1.10;
double r= 0.05;
double sigma= 2.43;
BlackScholesCall(S0, T, K, r, sigma);
BlackScholesPut(S0, T, K, r, sigma);
return 0;
}
|
#include <crtdbg.h>
#include "../VFS/IFile.h"
int main()
{
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
IFile* pFile = OpenDiskFile("test.txt", IFile::O_Truncate);
char buffer[] = "123456";
pFile->Write(buffer, offset_type(sizeof(buffer)));
pFile->ReserveSpace(offset_type(10));
delete pFile;
return 0;
}
|
// Nama : Naufal Dean Anugrah
// NIM : 13518123
// Tanggal : 13 Februari 2020
// Topik : Inheritance, Polymorphism, Abstract Base Class
#include "C.hpp"
C::C() : B(), A() {}
void C::sing() {
B::sing();
A::sing();
}
|
/*
* Timer.cpp
*
* Created on: Jun 11, 2017
* Author: root
*/
#include "Timer.h"
namespace CommBaseOut
{
Timer::Timer():m_obj(0),m_type(OnceTimer),m_ID(0),m_interval(0),m_start(0),m_bePoint(0),m_tickPoint(0),m_elapseRound(0),m_delflag(false),m_ticks(0),m_round(0),m_tm(0)
{
}
Timer::~Timer()
{
if(m_obj)
{
delete m_obj;
m_obj = 0;
}
}
int Timer::OnTick(int64 tick)
{
int iTimeout = 0;
if(tick - m_bePoint >= 0 || --m_round <= 0)
{
iTimeout = 1;
OnTimeout();
}
return iTimeout;
}
int Timer::OnTickEx(int64 tick)
{
int iTimeout = 0;
if(tick - m_bePoint >= 0 || --m_round <= 0)
{
iTimeout = 1;
}
return iTimeout;
}
bool Timer::IsDelete()
{
GUARD(CSimLock, obj, &m_delLock);
// printf("\n ------------------ exame timer[%d] this[%p] ------------------\n", m_ID, this);
return m_delflag;
}
void Timer::SetDelete()
{
// printf("\n +++++++++++++++++++++ delete timer[%d] this[%p] ++++++++++++\n", m_ID, this);
GUARD(CSimLock, obj, &m_delLock);
m_delflag = true;
}
void Timer::OnTimeout()
{
(*m_obj)();
}
bool Timer::Cancel()
{
GUARD(CSimLock, obj, &m_delLock);
m_delflag = true;
return true;
}
}
|
/*
===========================================================================
Copyright (C) 2017 waYne (CAM)
===========================================================================
*/
#pragma once
#ifndef ELYSIUM_CORE_DATA_COMMANDTYPE
#define ELYSIUM_CORE_DATA_COMMANDTYPE
namespace Elysium
{
namespace Core
{
namespace Data
{
/// <summary>
///
/// </summary>
enum class CommandType : int
{
Text = 1,
StoredProcedure = 4,
TableDirect = 512
};
}
}
}
#endif
|
#ifndef FORMATTED_TOUCHSTONE_H
#define FORMATTED_TOUCHSTONE_H
// RsaToolbox
#include "Definitions.h"
#include "FormattedComplex.h"
#include "FormattedNetworkData.h"
// Qt
#include <QFile>
#include <QTextStream>
#include <QString>
#include <QStringList>
// C++ std lib
#include <complex>
#include <vector>
// ToDo: Rewrite FormattedTouchstone/FormattedNetworkData to
// not rely on FormattedNetworkData::setNumberOfPorts().
// This is bad form: Should be derived from setData();
namespace RsaToolbox
{
class FormattedTouchstone {
public:
// Actions
static uint ports(QString fileName);
static bool Read(FormattedNetworkData &network, QTextStream &FormattedTouchstone_in, int ports);
static bool Read(FormattedNetworkData &network, QString filename);
static bool Write(FormattedNetworkData &network, QTextStream &FormattedTouchstone_out);
static bool Write(FormattedNetworkData &network, QString filename);
private:
static const QString FormattedTouchstone_FILE_REGEX;
static const int COLUMNWIDTH;
static const int PRECISION;
// Fix 2-port arrangement anomaly
static void Flip2Ports(FormattedNetworkData &network);
/* READ HELPER FUNCTIONS */
// Read Ports and Options line
static bool ReadPorts(FormattedNetworkData &network, QString filename);
static bool ReadOptions(FormattedNetworkData &network, QTextStream &snpFile);
static bool ReadFrequencyPrefix(FormattedNetworkData &network, QString units);
static bool ReadDataType(FormattedNetworkData &network, QString dataType);
static bool ReadFormat(FormattedNetworkData &network, QString format);
// Read data
static bool ReadData(FormattedNetworkData &network, QTextStream &snpFile);
static bool ReadRow(FormattedNetworkData &network, QTextStream &snpFile, FormattedComplexMatrix2D &dataRow, double &frequencyPoint);
static FormattedComplex (*ReadDatum)(double, double);
static FormattedComplex ReadRI(double word1, double word2);
static FormattedComplex ReadMA(double word1, double word2);
static FormattedComplex ReadDB(double word1, double word2);
// Functions to help read a line, ignore comments and parse line into whitespace-delimited words
static bool ReadLine(QTextStream &snpFile, QStringList &words);
static void RemoveComment(QString &line);
/* WRITE HELPER FUNCTIONS */
// Create file to be written
static void CreateFile(QFile &file, QString filename, FormattedNetworkData &network);
// Write comments and options line
static void WriteComments(FormattedNetworkData &network, QTextStream &snpFile);
static void WriteOptions(FormattedNetworkData &network, QTextStream &snpFile);
static QString WriteUnits(FormattedNetworkData &network);
static QString WriteDataType(FormattedNetworkData &network);
static QString WriteFormat(FormattedNetworkData &network);
// Write data
static void WriteData(FormattedNetworkData &network, QTextStream &snpFile);
static void WriteRow(FormattedNetworkData &network, QTextStream &snpFile, FormattedComplexRowVector &row);
static void GetWriteFormat(FormattedNetworkData &network);
static void (*WriteDatum)(QTextStream &, FormattedComplex &);
static void WriteRI(QTextStream &snpFile, FormattedComplex &datum);
static void WriteMA(QTextStream &snpFile, FormattedComplex &datum);
static void WriteDB(QTextStream &snpFile, FormattedComplex &datum);
};
}
#endif // FORMATTED_TOUCHSTONE_H
|
#include <stdio.h>
#include <stdlib.h>
main ()
{ /* ESTA FUNCIONANDO!!!!*/
int quadrante, x, y;
printf ("Informe o valor de X : \n");
scanf ("%d",&x);
printf ("Informe o valor de Y : \n");
scanf ("%d",&y);
if (x>0)
{
/* Pode estar no primeiro ou no quarto quadrante */
if (y>0)
{
/* Para testar se esta no primeiro quadrante */
quadrante = 1;
}
else
/* Ponto esta no quarto quadrante*/
{
quadrante = 4;
}
}
else
{
/* Pode estar no segundo ou no terceiro quadrante*/
if (y>0)
{
/*Para testar se esta no segundo quadrante*/
quadrante = 2;
}
else
{
/*Ponto esta no terceiro quadrante*/
quadrante = 3;
}
}
printf ("Quadrante em que o ponto (X,Y) esta localizado: %d",quadrante);
}
|
#include "FileHandler.h"
#include "Logger.h"
#include <ctime>
FileHandler::FileHandler()
{
m_pLogger = Logger::getLogger();
}
FileHandler::~FileHandler()
{
}
bool FileHandler::createMatrixFromDoc( const char * InputFileName,
map<int, map<int, int>*>* pMatrix,
int& NodeCount)
{
bool Success = true;
mInputFileName = InputFileName;
if (!pMatrix->empty())
{
m_pLogger->LogWarning("FileHandler: Given Matrix was NOT empty. Had to clear it.");
size_t sizeOfMatrix = pMatrix->size();
for (int i = 0; i < sizeOfMatrix; i++)
{
(*pMatrix)[i]->clear();
delete (*pMatrix)[i];
}
pMatrix->clear();
}
TiXmlDocument* doc = new TiXmlDocument(InputFileName);
bool loadOkay = doc->LoadFile();
TiXmlHandle docHandle(doc);
//Check Graph mode
TiXmlElement* GraphElement = docHandle.FirstChild("gexf").FirstChild("graph").ToElement();
/*if (!(GraphElement->Attribute("mode") == "static") ||
!(GraphElement->Attribute("defaultedgetype") == "directed"))
{
m_pLogger->LogError("Graph must be static and edges must be directed. I can't do anything else atm.");
Success &= false;
}*/
//Count Children and check ID/Label
TiXmlNode* NodeParentNode = docHandle.FirstChild("gexf").FirstChild("graph").FirstChild("nodes").ToNode();
if (NodeParentNode && Success)
{
TiXmlNode* currentChildNode;
for (currentChildNode = NodeParentNode->FirstChild("node"); currentChildNode;
currentChildNode = currentChildNode->NextSibling("node"))
{
TiXmlElement* currentChildNodeElement = currentChildNode->ToElement();
if (to_string(NodeCount) == currentChildNodeElement->Attribute("id") &&
to_string(NodeCount) == currentChildNodeElement->Attribute("label"))
{
NodeCount++;
}
else
{
m_pLogger->LogWarning("FileHandler: Issue found: Id or Label of Node Nr." + to_string(NodeCount) +
" did NOT fit the Id or Label. Normalized that. Node is now known under the Nr. " + to_string(NodeCount));
NodeCount++;
}
}
m_pLogger->LogTrace("Found " + to_string(NodeCount) + " Nodes.");
}
else
{
m_pLogger->LogError("FileHandler: Could not find any nodes.");
Success &= false;
}
TiXmlNode* EdgeParentNode = docHandle.FirstChild("gexf").FirstChild("graph").FirstChild("edges").ToNode();
if (EdgeParentNode && Success)
{
//Set the standard values 0 and INF
for (int row = 0; row < NodeCount; row++)
{
map<int, int>* currentRow = new map<int, int>;
for (int col = 0; col < NodeCount; col++)
{
if (row == col)
{
(*currentRow)[col] = 0;
}
else
{
(*currentRow)[col] = INF;
}
}
(*pMatrix)[row] = currentRow;
}
//Set the values of the direct connections
TiXmlNode* currentChildEdge;
int EdgeCount = 0;
for (currentChildEdge = EdgeParentNode->FirstChild("edge"); currentChildEdge;
currentChildEdge = currentChildEdge->NextSibling("edge"))
{
TiXmlElement* currentChildEdgeElement = currentChildEdge->ToElement();
int SourceId = atoi(currentChildEdgeElement->Attribute("source"));
int TargetId = atoi(currentChildEdgeElement->Attribute("target"));
int Weight = atoi(currentChildEdgeElement->Attribute("weight"));
pMatrix->at(SourceId)->at(TargetId) = Weight;
EdgeCount++;
}
m_pLogger->LogTrace("Found " + to_string(EdgeCount) + " Edges.");
}
else
{
m_pLogger->LogError("Could not find any edges.");
Success &= false;
}
delete doc;
return Success;
}
bool FileHandler::writeMatrixToXML(map<int, map<int, int>*>* pMatrix)
{
bool Success = true;
//TODO: Check if doc is open
//Basics
TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "UTF-8", "");
TiXmlElement* rootElement = new TiXmlElement("gexf");
//Meta data
TiXmlElement* metaElement = new TiXmlElement("meta");
metaElement->SetAttribute("lastmodifieddate", " ");
rootElement->LinkEndChild(metaElement);
TiXmlElement* creatorElement = new TiXmlElement("creator");
metaElement->LinkEndChild(creatorElement);
TiXmlElement* descrElement = new TiXmlElement("description");
metaElement->LinkEndChild(descrElement);
//Graph data
TiXmlElement* graphElement = new TiXmlElement("graph");
graphElement->SetAttribute("mode", "static");
graphElement->SetAttribute("defaultedgetype", "directed");
rootElement->LinkEndChild(graphElement);
size_t matrixSize = pMatrix->size();
for (int sourceId = 0; sourceId < matrixSize; sourceId++)
{
TiXmlElement* SourceElement = new TiXmlElement("SourceNode");
SourceElement->SetAttribute("Id", sourceId);
graphElement->LinkEndChild(SourceElement);
for (int targetId = 0; targetId < matrixSize; targetId++)
{
TiXmlElement* TargetElement = new TiXmlElement("TargetNode");
TargetElement->SetAttribute("Id", targetId);
TargetElement->SetAttribute("Weight", pMatrix->at(sourceId)->at(targetId));
SourceElement->LinkEndChild(TargetElement);
}
}
doc.LinkEndChild(decl);
doc.LinkEndChild(rootElement);
//Datetime information for filename
time_t currentTime;
struct tm localTime;
time(¤tTime);
localtime_s(&localTime, ¤tTime);
string Year = to_string(localTime.tm_year + 1900);
string Month = to_string(localTime.tm_mon + 1);
string Day = to_string(localTime.tm_mday);
string Hour = to_string(localTime.tm_hour);
string Min = to_string(localTime.tm_min);
string Sec = to_string(localTime.tm_sec);
string InputName = mInputFileName.substr(0, mInputFileName.find(".", 0));
string FileName = Year + "-" + Month + "-" + Day + "_" +
Hour + "-" + Min + "-" + Sec + "-" + InputName +"-Output.xml";
doc.SaveFile(FileName.c_str());
return Success;
}
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
void increment(vector<short> &a, int k) {
int i = 0;
while (i < k && a[i] == 1) {
a[i++] = 0;
}
if (i < k) {
a[i] = 1;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, k;
cin >> n >> m >> k;
vector<pair<int, int>> net;
for (int i = 0; i < k; i++) {
int cou;
cin >> cou;
for (int j = 0; j < cou; j++) {
int v1, v2;
cin >> v1 >> v2;
net.emplace_back(v1 - 1, v2 - 1);
}
}
vector<short> line(n);
vector<short> oldLine(n);
for (int i = 0; i < n; i++) {
line[i] = 0;
}
int lines = (int) pow(2, n);
for (int i = 0; i < lines; i++) {
oldLine = line;
for (auto &l : net) {
int v1 = l.first;
int v2 = l.second;
if (v2 < v1) {
int temp = v1;
v1 = v2;
v2 = temp;
}
if (line[v1] > line[v2]) {
swap(line[v1], line[v2]);
}
}
for (int j = 0; j < n - 1; j++) {
if (line[j] > line[j + 1]) {
cout << "NO";
exit(0);
}
}
increment(oldLine, n);
line = oldLine;
}
cout << "YES";
return 0;
}
|
/*
* Lanq(Lan Quick)
* Solodov A. N. (hotSAN)
* 2016
* LqHttpAtz... - Make user uthorization.
*/
#include "LqOs.h"
#include "LqHttp.hpp"
#include "LqHttp.h"
#include "LqTime.h"
#include "LqAtm.hpp"
#include "LqHttpAtz.h"
#include "LqHttpMdl.h"
#include "LqStr.hpp"
#include "LqCrypt.h"
#define __METHOD_DECLS__
#include "LqAlloc.hpp"
#include <stdlib.h>
/*
LqHttpAtz... - authorization functions
*/
#define LqCheckedFree(MemReg) (((MemReg) != nullptr)? free(MemReg): void())
static LqTimeSec LastCheck = LqTimeGetLocSec();
static bool ___d = ([] { srand(LastCheck); return true; })();
static uint64_t Random = rand();
static void LqHttpAtzRsp401Basic(LqHttpConn* HttpConn);
static void LqHttpAtzRsp401Digest(LqHttpConn* HttpConn, LqHttpAtz* Authoriz, const char* Nonce, bool IsStyle);
static bool LqHttpAtzGetAuthorizationParametr(const char* Str, const char* NameParametr, const char** Res, size_t* ResLen, bool IsBracketsRequired);
static bool LqHttpAtzGetBasicBase64LoginPassword(const char* Str, const char** Res, size_t* ResLen);
static char* LqHttpAtzGetBasicCode(const char* User, const char* Password);
//*
//* Handler for responce digest nonce
//*/
void LQ_CALL LqHttpMdlHandlersNonce(LqHttpConn* HttpConn, char* MethodBuf, size_t MethodBufSize) {
LqTimeMillisec Ms = LqTimeGetLocMillisec();
LqTimeSec Sec = Ms / 1000;
uint64_t h;
char IpBuf[100];
LqHttpData* HttpData;
HttpData = LqHttpConnGetHttpData(HttpConn);
if((Sec - LastCheck) > HttpData->PeriodChangeDigestNonce) {
LastCheck = Sec;
Random = (((uint64_t)rand() << 32) | (uint64_t)rand()) + Ms % 50000;
}
IpBuf[0] = '\0';
LqHttpConnGetRemoteIpStr(HttpConn, IpBuf, sizeof(IpBuf));
h = Random;
for(const char* k = IpBuf; *k != '\0'; k++)
h = 63 * h + *k;
LqFbuf_snprintf(MethodBuf, MethodBufSize, "%q64x", h);
}
LQ_EXTERN_C bool LQ_CALL LqHttpAtzDo(LqHttpConn* HttpConn, uint8_t AccessMask) {
LqHttpConnData* HttpConnData;
LqHttpData* HttpData;
LqHttpMdl* Mdl;
LqHttpPth* Pth;
LqHttpRcvHdrs* RcvHdr;
const char *HdrVal, *NonceParam, *UsernameParam, *UriParam, *ResponsePraram, *Base64LogPass;
char *t;
size_t LenLogPass, NonceParamLen, i, UsernameParamLen, UriParamLen, ResponsePraramLen;
char Nonce[100];
char HashMethodPath[32 + 1];
char HashBuf[32 + 1];
char h[16];
LqCryptHash ctx;
Mdl = LqHttpConnGetMdl(HttpConn);
HttpConnData = LqHttpConnGetData(HttpConn);
HttpData = LqHttpConnGetHttpData(HttpConn);
RcvHdr = HttpConnData->RcvHdr;
Pth = HttpConnData->Pth;
auto a = LqObPtrGetEx<LqHttpAtz, _LqHttpAtzDelete, true>(Pth->Atz, Pth->AtzPtrLk);
if((Pth->Permissions & AccessMask) == AccessMask)
return true;
if(a == nullptr) {
LqHttpConnRspError(HttpConn, 401);
return false;
}
LqHttpAtzLockRead(a.Get());
if(a->AuthType == LQHTTPATZ_TYPE_BASIC) {
if((HdrVal = LqHttpConnRcvHdrGet(HttpConn, "authorization")) == NULL) {
LqHttpAtzRsp401Basic(HttpConn);
LqHttpAtzUnlock(a.Get());
return false;
}
if(!LqHttpAtzGetBasicBase64LoginPassword(HdrVal, &Base64LogPass, &LenLogPass)) {
LqHttpAtzRsp401Basic(HttpConn);
LqHttpAtzUnlock(a.Get());
return false;
}
for(i = 0; i < a->CountAuthoriz; i++) {
if((LenLogPass == LqStrLen(a->Basic[i].LoginPassword)) && LqStrSameMax(Base64LogPass, a->Basic[i].LoginPassword, LenLogPass)) {
if((a->Basic[i].AccessMask & AccessMask) == AccessMask) {
LqHttpAtzUnlock(a.Get());
return true;
}
}
}
LqHttpAtzRsp401Basic(HttpConn);
} else if(a->AuthType == LQHTTPATZ_TYPE_DIGEST) {
Nonce[0] = '\0';
Mdl->NonceProc(HttpConn, Nonce, sizeof(Nonce) - 1);
if((HdrVal = LqHttpConnRcvHdrGet(HttpConn, "authorization")) == NULL) {
LqHttpAtzRsp401Digest(HttpConn, a.Get(), Nonce, false);
LqHttpAtzUnlock(a.Get());
return false;
}
if(!LqHttpAtzGetAuthorizationParametr(HdrVal, "nonce", &NonceParam, &NonceParamLen, true)) {
LqHttpAtzRsp401Digest(HttpConn, a.Get(), Nonce, false);
LqHttpAtzUnlock(a.Get());
return false;
}
if((NonceParamLen != LqStrLen(Nonce)) || !LqStrSameMax(NonceParam, Nonce, NonceParamLen)) {
LqHttpAtzRsp401Digest(HttpConn, a.Get(), Nonce, true);
LqHttpAtzUnlock(a.Get());
return false;
}
if(!LqHttpAtzGetAuthorizationParametr(HdrVal, "username", &UsernameParam, &UsernameParamLen, true)) {
LqHttpAtzRsp401Digest(HttpConn, a.Get(), Nonce, false);
LqHttpAtzUnlock(a.Get());
return false;
}
if(!LqHttpAtzGetAuthorizationParametr(HdrVal, "uri", &UriParam, &UriParamLen, true)) {
LqHttpAtzRsp401Digest(HttpConn, a.Get(), Nonce, false);
LqHttpAtzUnlock(a.Get());
return false;
}
if(!LqHttpAtzGetAuthorizationParametr(HdrVal, "response", &ResponsePraram, &ResponsePraramLen, true) || (ResponsePraramLen != 32)) {
LqHttpAtzRsp401Digest(HttpConn, a.Get(), Nonce, false);
LqHttpAtzUnlock(a.Get());
return false;
}
LqCryptHashOpen(&ctx, "md5");
LqCryptHashUpdate(&ctx, RcvHdr->Method, LqStrLen(RcvHdr->Method));
LqCryptHashUpdate(&ctx, ":", 1);
LqCryptHashUpdate(&ctx, UriParam, UriParamLen);
LqCryptHashFinal(&ctx, h);
LqFbuf_snprintf(HashMethodPath, 100, "%.*v", 16, h); /* Print hash as HEX string */
for(size_t i = 0; i < a->CountAuthoriz; i++) {
if((UsernameParamLen == LqStrLen(a->Digest[i].UserName)) && LqStrSameMax(UsernameParam, a->Digest[i].UserName, UsernameParamLen)) {
LqCryptHashOpen(&ctx, "md5");
LqCryptHashUpdate(&ctx, a->Digest[i].DigestLoginPassword, 32);
LqCryptHashUpdate(&ctx, ":", 1);
LqCryptHashUpdate(&ctx, Nonce, LqStrLen(Nonce));
LqCryptHashUpdate(&ctx, ":", 1);
LqCryptHashUpdate(&ctx, HashMethodPath, 32);
LqCryptHashFinal(&ctx, h);
LqFbuf_snprintf(HashBuf, 100, "%.*v", 16, h); /* Print hash as HEX string */
if(LqStrSameMax(HashBuf, ResponsePraram, 32) && ((a->Digest[i].AccessMask & AccessMask) == AccessMask)) {
LqHttpAtzUnlock(a.Get());
return true;
}
}
}
LqHttpAtzRsp401Digest(HttpConn, a.Get(), Nonce, false);
}
LqHttpAtzUnlock(a.Get());
return false;
}
static bool LqHttpAtzGetBasicBase64LoginPassword(const char* Str, const char** Res, size_t* ResLen) {
int a = -1, b = -1;
LqFbuf_snscanf(Str, LqStrLen(Str), "%#*{basic}%*[ ]%n%*[a-zA-Z0-9/+=]%n", &a, &b);
if((a != -1) && (b != -1)) {
*Res = Str + a;
*ResLen = b - a;
return true;
}
return false;
}
static bool LqHttpAtzGetAuthorizationParametr(const char* Str, const char* NameParametr, const char** Res, size_t* ResLen, bool IsBracketsRequired) {
size_t i;
size_t npl = LqStrLen(NameParametr);
for(size_t i = 0; Str[i]; i++)
if(LqStrUtf8CmpCaseLen(NameParametr, Str + i, npl)) {
bool b;
auto g = i + npl;
for(; Str[g] == ' '; g++);
if(Str[g++] != '=')
continue;
for(; Str[g] == ' '; g++);
if(Str[g] == '"') {
g++;
b = true;
} else {
if(IsBracketsRequired)
continue;
b = false;
}
*Res = Str + g;
for(; (Str[g] != '"') && (Str[g] != ',') && (Str[g] != '\0'); g++);
if(b && (Str[g] != '"'))
continue;
*ResLen = (Str + g) - *Res;
return true;
}
return false;
}
static void LqHttpAtzRsp401Basic(LqHttpConn* HttpConn) {
char HdrVal[4096];
LqHttpConnData* HttpConnData;
HttpConnData = LqHttpConnGetData(HttpConn);
LqFbuf_snprintf(HdrVal, sizeof(HdrVal) - 1, "Basic realm=\"%s\"", HttpConnData->Pth->Atz->Realm);
LqHttpConnRspHdrInsert(HttpConn, "WWW-Authenticate", HdrVal);
LqHttpConnRspError(HttpConn, 401);
}
static void LqHttpAtzRsp401Digest(LqHttpConn* HttpConn, LqHttpAtz* Authoriz, const char* Nonce, bool IsStale) {
char HdrVal[4096];
LqFbuf_snprintf(HdrVal, sizeof(HdrVal) - 1, "Digest realm=\"%s\", nonce=\"%s\"%s", Authoriz->Realm, Nonce, ((IsStale) ? ", stale=true" : ""));
LqHttpConnRspHdrInsert(HttpConn, "WWW-Authenticate", HdrVal);
LqHttpConnRspError(HttpConn, 401);
}
static char* LqHttpAtzGetBasicCode(const char* User, const char* Password) {
size_t l = LqStrLen(User) + LqStrLen(Password) + 3;
char* Step1Buf = (char*)malloc(l);
if(Step1Buf == nullptr)
return nullptr;
Step1Buf[0] = '\0';
LqFbuf_snprintf(Step1Buf, l, "%s:%s", User, Password);
size_t Step2BufLen = (size_t)((float)l * 1.4f) + 2;
char* Step2Buf = (char*)calloc(Step2BufLen, 1);
if(Step2Buf == nullptr) {
free(Step1Buf);
return nullptr;
}
/* Write base 64*/
LqFbuf_snprintf(Step2Buf, Step2BufLen, "%#b", Step1Buf);
free(Step1Buf);
return Step2Buf;
}
LQ_EXTERN_C LqHttpAtz* LQ_CALL LqHttpAtzCreate(LqHttpAtzTypeEnm AuthType, const char* Realm) {
LqHttpAtz* Atz = LqFastAlloc::New<LqHttpAtz>();
if(Atz == nullptr)
return nullptr;
memset(Atz, 0, sizeof(LqHttpAtz));
Atz->CountPointers = 1;
LqAtmLkInit(Atz->Locker);
Atz->AuthType = AuthType;
Atz->Realm = LqStrDuplicate(Realm);
if(Atz->Realm == nullptr) {
LqHttpAtzRelease(Atz);
return nullptr;
}
return Atz;
}
LQ_EXTERN_C bool LQ_CALL LqHttpAtzAdd(LqHttpAtz* NetAutoriz, uint8_t AccessMask, const char* UserName, const char* Password) {
if(NetAutoriz == nullptr)
return false;
LqHttpAtzLockWrite(NetAutoriz);
if(NetAutoriz->AuthType == LQHTTPATZ_TYPE_BASIC) {
char* c = LqHttpAtzGetBasicCode(UserName, Password);
if(c == nullptr) {
LqHttpAtzUnlock(NetAutoriz);
return false;
}
decltype(NetAutoriz->Basic) m = (decltype(NetAutoriz->Basic))realloc(NetAutoriz->Basic, (NetAutoriz->CountAuthoriz + 1) * sizeof(NetAutoriz->Basic[0]));
if(m == nullptr) {
LqHttpAtzUnlock(NetAutoriz);
free(c);
return false;
}
NetAutoriz->Basic = m;
NetAutoriz->Basic[NetAutoriz->CountAuthoriz].AccessMask = AccessMask;
NetAutoriz->Basic[NetAutoriz->CountAuthoriz].LoginPassword = c;
NetAutoriz->CountAuthoriz++;
} else if(NetAutoriz->AuthType == LQHTTPATZ_TYPE_DIGEST) {
char* un = LqStrDuplicate(UserName);
if(un == nullptr) {
LqHttpAtzUnlock(NetAutoriz);
return false;
}
decltype(NetAutoriz->Digest) m = (decltype(NetAutoriz->Digest))realloc(NetAutoriz->Digest, (NetAutoriz->CountAuthoriz + 1) * sizeof(NetAutoriz->Digest[0]));
if(m == nullptr) {
LqHttpAtzUnlock(NetAutoriz);
free(un);
return false;
}
NetAutoriz->Digest = m;
NetAutoriz->Digest[NetAutoriz->CountAuthoriz].AccessMask = AccessMask;
NetAutoriz->Digest[NetAutoriz->CountAuthoriz].UserName = un;
LqCryptHash ctx;
LqCryptHashOpen(&ctx, "md5");
LqCryptHashUpdate(&ctx, UserName, LqStrLen(UserName));
LqCryptHashUpdate(&ctx, ":", 1);
LqCryptHashUpdate(&ctx, NetAutoriz->Realm, LqStrLen(NetAutoriz->Realm));
LqCryptHashUpdate(&ctx, ":", 1);
LqCryptHashUpdate(&ctx, Password, LqStrLen(Password));
char h[16];
LqCryptHashFinal(&ctx, h);
LqFbuf_snprintf(
NetAutoriz->Digest[NetAutoriz->CountAuthoriz].DigestLoginPassword,
sizeof(NetAutoriz->Digest[NetAutoriz->CountAuthoriz].DigestLoginPassword),
"%.*v", //Print hex string
(int)sizeof(h),
&h
);
NetAutoriz->CountAuthoriz++;
}
LqHttpAtzUnlock(NetAutoriz);
return true;
}
LQ_EXTERN_C bool LQ_CALL LqHttpAtzRemove(LqHttpAtz* NetAutoriz, const char* UserName) {
if(NetAutoriz == nullptr)
return false;
LqHttpAtzLockWrite(NetAutoriz);
if(NetAutoriz->AuthType == LQHTTPATZ_TYPE_BASIC) {
auto l = LqStrLen(UserName);
size_t nc = NetAutoriz->CountAuthoriz;
char Buf[4096];
for(size_t i = 0; i < nc;) {
Buf[0] = '\0';
LqFbuf_snscanf(NetAutoriz->Basic[i].LoginPassword, LqStrLen(NetAutoriz->Basic[i].LoginPassword), "%.4095b", Buf);
if(LqStrSameMax(Buf, UserName, l)) {
LqCheckedFree(NetAutoriz->Basic[i].LoginPassword);
memmove(NetAutoriz->Basic + i, NetAutoriz->Basic + (i + 1), (nc - (i + 1)) * sizeof(NetAutoriz->Basic[0]));
nc--;
continue;
}
i++;
}
NetAutoriz->Basic = (decltype(NetAutoriz->Basic))realloc(NetAutoriz->Basic, nc * sizeof(NetAutoriz->Basic[0]));
NetAutoriz->CountAuthoriz = nc;
} else if(NetAutoriz->AuthType == LQHTTPATZ_TYPE_DIGEST) {
size_t nc = NetAutoriz->CountAuthoriz;
for(size_t i = 0; i < nc;) {
if(LqStrSame(NetAutoriz->Digest[i].UserName, UserName)) {
LqCheckedFree(NetAutoriz->Digest[i].UserName);
memmove(NetAutoriz->Digest + i, NetAutoriz->Digest + (i + 1), (nc - (i + 1)) * sizeof(NetAutoriz->Digest[0]));
nc--;
continue;
}
i++;
}
NetAutoriz->Digest = (decltype(NetAutoriz->Digest))realloc(NetAutoriz->Digest, nc * sizeof(NetAutoriz->Digest[0]));
NetAutoriz->CountAuthoriz = nc;
}
LqHttpAtzUnlock(NetAutoriz);
return true;
}
LQ_EXTERN_C void LQ_CALL LqHttpAtzAssign(LqHttpAtz* NetAutoriz) {
if(NetAutoriz == nullptr)
return;
LqAtmIntrlkInc(NetAutoriz->CountPointers);
}
void _LqHttpAtzDelete(LqHttpAtz* NetAutoriz) {
if(NetAutoriz->AuthType == LQHTTPATZ_TYPE_BASIC) {
if(NetAutoriz->Basic != nullptr) {
for(size_t i = 0, m = NetAutoriz->CountAuthoriz; i < m; i++)
LqCheckedFree(NetAutoriz->Basic[i].LoginPassword);
LqCheckedFree(NetAutoriz->Basic);
}
} else if(NetAutoriz->AuthType == LQHTTPATZ_TYPE_DIGEST) {
if(NetAutoriz->Digest != nullptr) {
for(size_t i = 0, m = NetAutoriz->CountAuthoriz; i < m; i++)
LqCheckedFree(NetAutoriz->Digest[i].UserName);
LqCheckedFree(NetAutoriz->Digest);
}
}
LqCheckedFree(NetAutoriz->Realm);
LqFastAlloc::Delete(NetAutoriz);
}
LQ_EXTERN_C bool LQ_CALL LqHttpAtzRelease(LqHttpAtz* NetAutoriz) {
if(NetAutoriz == nullptr)
return false;
return LqObPtrDereference<LqHttpAtz, _LqHttpAtzDelete>(NetAutoriz);
}
LQ_EXTERN_C void LQ_CALL LqHttpAtzLockWrite(LqHttpAtz* NetAutoriz) {
if(NetAutoriz != nullptr)
LqAtmLkWr(NetAutoriz->Locker);
}
LQ_EXTERN_C void LQ_CALL LqHttpAtzLockRead(LqHttpAtz* NetAutoriz) {
if(NetAutoriz != nullptr)
LqAtmLkRd(NetAutoriz->Locker);
}
LQ_EXTERN_C void LQ_CALL LqHttpAtzUnlock(LqHttpAtz* NetAutoriz) {
if(NetAutoriz != nullptr) {
if(LqAtmLkIsRd(NetAutoriz->Locker))
LqAtmUlkRd(NetAutoriz->Locker);
else
LqAtmUlkWr(NetAutoriz->Locker);
}
}
|
#ifndef _CIRCLE_H
#define _CIRCLE_H
#include "sjfwd.h"
#include "shape.h"
#include "point.h"
class circle : public shape {
public:
double radius;
circle(double cx = 0, double cy = 0, double r = 1, double fl = false) {
this->center = point(cx, cy);
this->radius = r;
this->fill = fl;
}
bool overlaps(const point) const;
bool overlaps(const segment) const;
bool overlaps(const circle) const;
bool overlaps(const rectangle) const;
bool overlaps(const triangle) const;
bool onscreen() const;
void draw() const;
void translade(double, double);
};
#endif
|
#ifndef UTILITEST_H_
#define UTILITEST_H_
#include <Eigen/Core>
#include <Eigen/Cholesky>
#include <Eigen/LU>
#include <cmath>
namespace vct {
template <typename T>
using State = Eigen::Matrix<T, Eigen::Dynamic, 1>;
template<typename T>
using Control = State<T>;
template<typename T>
using Measurement = State<T>;
template <typename T>
using Weights = State<T>;
}
namespace mtx {
template <typename T>
using Matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>;
}
namespace sigma {
template<typename T>
using SigmaPoints = mtx::Matrix<T>;
}
#endif
|
#ifndef FEMAS_SYSTEM_PRINT_FUNCTION_H_
#define FEMAS_SYSTEM_PRINT_FUNCTION_H_
#include <iostream>
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcReqUserLoginField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcReqUserLoginField) ---> TradingDay:" << ftdc_struct.TradingDay
<< " UserID:" << ftdc_struct.UserID
<< " BrokerID:" << ftdc_struct.BrokerID
<< " Password:" << "it is a secret" // ftdc_struct.Password
<< " UserProductInfo:" << ftdc_struct.UserProductInfo
<< " InterfaceProductInfo:" << ftdc_struct.InterfaceProductInfo
<< " ProtocolInfo:" << ftdc_struct.ProtocolInfo
<< " IPAddress:" << ftdc_struct.IPAddress
<< " MacAddress:" << ftdc_struct.MacAddress
<< " DataCenterID:" << ftdc_struct.DataCenterID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspUserLoginField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspUserLoginField) ---> TradingDay:" << ftdc_struct.TradingDay
<< " BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " LoginTime:" << ftdc_struct.LoginTime
<< " MaxOrderLocalID:" << ftdc_struct.MaxOrderLocalID
<< " TradingSystemName:" << ftdc_struct.TradingSystemName
<< " DataCenterID:" << ftdc_struct.DataCenterID
<< " PrivateFlowSize:" << ftdc_struct.PrivateFlowSize
<< " UserFlowSize:" << ftdc_struct.UserFlowSize
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcReqUserLogoutField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcReqUserLogoutField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspUserLogoutField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspUserLogoutField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcForceUserExitField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcForceUserExitField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcUserPasswordUpdateField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcUserPasswordUpdateField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " OldPassword:" << "it is a secret" // ftdc_struct.OldPassword
<< " NewPassword:" << "it is a secret" // ftdc_struct.NewPassword
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcInputOrderField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcInputOrderField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " OrderSysID:" << ftdc_struct.OrderSysID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " UserID:" << ftdc_struct.UserID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " UserOrderLocalID:" << ftdc_struct.UserOrderLocalID
<< " OrderPriceType:" << ftdc_struct.OrderPriceType
<< " Direction:" << ftdc_struct.Direction
<< " OffsetFlag:" << ftdc_struct.OffsetFlag
<< " HedgeFlag:" << ftdc_struct.HedgeFlag
<< " LimitPrice:" << ftdc_struct.LimitPrice
<< " Volume:" << ftdc_struct.Volume
<< " TimeCondition:" << ftdc_struct.TimeCondition
<< " GTDDate:" << ftdc_struct.GTDDate
<< " VolumeCondition:" << ftdc_struct.VolumeCondition
<< " MinVolume:" << ftdc_struct.MinVolume
<< " StopPrice:" << ftdc_struct.StopPrice
<< " ForceCloseReason:" << ftdc_struct.ForceCloseReason
<< " IsAutoSuspend:" << ftdc_struct.IsAutoSuspend
<< " BusinessUnit:" << ftdc_struct.BusinessUnit
<< " UserCustom:" << ftdc_struct.UserCustom
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcOrderActionField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcOrderActionField) ---> ExchangeID:" << ftdc_struct.ExchangeID
<< " OrderSysID:" << ftdc_struct.OrderSysID
<< " BrokerID:" << ftdc_struct.BrokerID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " UserID:" << ftdc_struct.UserID
<< " UserOrderActionLocalID:" << ftdc_struct.UserOrderActionLocalID
<< " UserOrderLocalID:" << ftdc_struct.UserOrderLocalID
<< " ActionFlag:" << ftdc_struct.ActionFlag
<< " LimitPrice:" << ftdc_struct.LimitPrice
<< " VolumeChange:" << ftdc_struct.VolumeChange
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMemDbField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMemDbField) ---> MemTableName:" << ftdc_struct.MemTableName
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspInfoField& ftdc_struct) {
if (&ftdc_struct != NULL) {
os << "ftdc_struct(CUstpFtdcRspInfoField) ---> ErrorID:" << ftdc_struct.ErrorID
<< " ErrorMsg:" << ftdc_struct.ErrorMsg
<< " <--- End";
}
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryOrderField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryOrderField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " OrderSysID:" << ftdc_struct.OrderSysID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryTradeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryTradeField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " TradeID:" << ftdc_struct.TradeID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryInstrumentField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryInstrumentField) ---> ExchangeID:" << ftdc_struct.ExchangeID
<< " ProductID:" << ftdc_struct.ProductID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspInstrumentField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspInstrumentField) ---> ExchangeID:" << ftdc_struct.ExchangeID
<< " ProductID:" << ftdc_struct.ProductID
<< " ProductName:" << ftdc_struct.ProductName
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " InstrumentName:" << ftdc_struct.InstrumentName
<< " DeliveryYear:" << ftdc_struct.DeliveryYear
<< " DeliveryMonth:" << ftdc_struct.DeliveryMonth
<< " MaxLimitOrderVolume:" << ftdc_struct.MaxLimitOrderVolume
<< " MinLimitOrderVolume:" << ftdc_struct.MinLimitOrderVolume
<< " MaxMarketOrderVolume:" << ftdc_struct.MaxMarketOrderVolume
<< " MinMarketOrderVolume:" << ftdc_struct.MinMarketOrderVolume
<< " VolumeMultiple:" << ftdc_struct.VolumeMultiple
<< " PriceTick:" << ftdc_struct.PriceTick
<< " Currency:" << ftdc_struct.Currency
<< " LongPosLimit:" << ftdc_struct.LongPosLimit
<< " ShortPosLimit:" << ftdc_struct.ShortPosLimit
<< " LowerLimitPrice:" << ftdc_struct.LowerLimitPrice
<< " UpperLimitPrice:" << ftdc_struct.UpperLimitPrice
<< " PreSettlementPrice:" << ftdc_struct.PreSettlementPrice
<< " InstrumentStatus:" << ftdc_struct.InstrumentStatus
<< " CreateDate:" << ftdc_struct.CreateDate
<< " OpenDate:" << ftdc_struct.OpenDate
<< " ExpireDate:" << ftdc_struct.ExpireDate
<< " StartDelivDate:" << ftdc_struct.StartDelivDate
<< " EndDelivDate:" << ftdc_struct.EndDelivDate
<< " BasisPrice:" << ftdc_struct.BasisPrice
<< " IsTrading:" << ftdc_struct.IsTrading
<< " UnderlyingInstrID:" << ftdc_struct.UnderlyingInstrID
<< " UnderlyingMultiple:" << ftdc_struct.UnderlyingMultiple
<< " PositionType:" << ftdc_struct.PositionType
<< " StrikePrice:" << ftdc_struct.StrikePrice
<< " OptionsType:" << ftdc_struct.OptionsType
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcInstrumentStatusField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcInstrumentStatusField) ---> ExchangeID:" << ftdc_struct.ExchangeID
<< " ProductID:" << ftdc_struct.ProductID
<< " ProductName:" << ftdc_struct.ProductName
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " InstrumentName:" << ftdc_struct.InstrumentName
<< " DeliveryYear:" << ftdc_struct.DeliveryYear
<< " DeliveryMonth:" << ftdc_struct.DeliveryMonth
<< " MaxLimitOrderVolume:" << ftdc_struct.MaxLimitOrderVolume
<< " MinLimitOrderVolume:" << ftdc_struct.MinLimitOrderVolume
<< " MaxMarketOrderVolume:" << ftdc_struct.MaxMarketOrderVolume
<< " MinMarketOrderVolume:" << ftdc_struct.MinMarketOrderVolume
<< " VolumeMultiple:" << ftdc_struct.VolumeMultiple
<< " PriceTick:" << ftdc_struct.PriceTick
<< " Currency:" << ftdc_struct.Currency
<< " LongPosLimit:" << ftdc_struct.LongPosLimit
<< " ShortPosLimit:" << ftdc_struct.ShortPosLimit
<< " LowerLimitPrice:" << ftdc_struct.LowerLimitPrice
<< " UpperLimitPrice:" << ftdc_struct.UpperLimitPrice
<< " PreSettlementPrice:" << ftdc_struct.PreSettlementPrice
<< " InstrumentStatus:" << ftdc_struct.InstrumentStatus
<< " CreateDate:" << ftdc_struct.CreateDate
<< " OpenDate:" << ftdc_struct.OpenDate
<< " ExpireDate:" << ftdc_struct.ExpireDate
<< " StartDelivDate:" << ftdc_struct.StartDelivDate
<< " EndDelivDate:" << ftdc_struct.EndDelivDate
<< " BasisPrice:" << ftdc_struct.BasisPrice
<< " IsTrading:" << ftdc_struct.IsTrading
<< " UnderlyingInstrID:" << ftdc_struct.UnderlyingInstrID
<< " UnderlyingMultiple:" << ftdc_struct.UnderlyingMultiple
<< " PositionType:" << ftdc_struct.PositionType
<< " StrikePrice:" << ftdc_struct.StrikePrice
<< " OptionsType:" << ftdc_struct.OptionsType
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryInvestorAccountField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryInvestorAccountField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspInvestorAccountField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspInvestorAccountField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " AccountID:" << ftdc_struct.AccountID
<< " PreBalance:" << ftdc_struct.PreBalance
<< " Deposit:" << ftdc_struct.Deposit
<< " Withdraw:" << ftdc_struct.Withdraw
<< " FrozenMargin:" << ftdc_struct.FrozenMargin
<< " FrozenFee:" << ftdc_struct.FrozenFee
<< " FrozenPremium:" << ftdc_struct.FrozenPremium
<< " Fee:" << ftdc_struct.Fee
<< " CloseProfit:" << ftdc_struct.CloseProfit
<< " PositionProfit:" << ftdc_struct.PositionProfit
<< " Available:" << ftdc_struct.Available
<< " LongFrozenMargin:" << ftdc_struct.LongFrozenMargin
<< " ShortFrozenMargin:" << ftdc_struct.ShortFrozenMargin
<< " LongMargin:" << ftdc_struct.LongMargin
<< " ShortMargin:" << ftdc_struct.ShortMargin
<< " ReleaseMargin:" << ftdc_struct.ReleaseMargin
<< " DynamicRights:" << ftdc_struct.DynamicRights
<< " TodayInOut:" << ftdc_struct.TodayInOut
<< " Margin:" << ftdc_struct.Margin
<< " Premium:" << ftdc_struct.Premium
<< " Risk:" << ftdc_struct.Risk
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryUserInvestorField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryUserInvestorField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspUserInvestorField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspUserInvestorField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryTradingCodeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryTradingCodeField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspTradingCodeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspTradingCodeField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " ClientID:" << ftdc_struct.ClientID
<< " ClientRight:" << ftdc_struct.ClientRight
<< " IsActive:" << ftdc_struct.IsActive
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryExchangeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryExchangeField) ---> ExchangeID:" << ftdc_struct.ExchangeID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspExchangeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspExchangeField) ---> ExchangeID:" << ftdc_struct.ExchangeID
<< " ExchangeName:" << ftdc_struct.ExchangeName
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryInvestorPositionField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryInvestorPositionField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspInvestorPositionField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspInvestorPositionField) ---> InvestorID:" << ftdc_struct.InvestorID
<< " BrokerID:" << ftdc_struct.BrokerID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " ClientID:" << ftdc_struct.ClientID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " Direction:" << ftdc_struct.Direction
<< " HedgeFlag:" << ftdc_struct.HedgeFlag
<< " UsedMargin:" << ftdc_struct.UsedMargin
<< " Position:" << ftdc_struct.Position
<< " PositionCost:" << ftdc_struct.PositionCost
<< " YdPosition:" << ftdc_struct.YdPosition
<< " YdPositionCost:" << ftdc_struct.YdPositionCost
<< " FrozenMargin:" << ftdc_struct.FrozenMargin
<< " FrozenPosition:" << ftdc_struct.FrozenPosition
<< " FrozenClosing:" << ftdc_struct.FrozenClosing
<< " FrozenPremium:" << ftdc_struct.FrozenPremium
<< " LastTradeID:" << ftdc_struct.LastTradeID
<< " LastOrderLocalID:" << ftdc_struct.LastOrderLocalID
<< " Currency:" << ftdc_struct.Currency
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryComplianceParamField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryComplianceParamField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcRspComplianceParamField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcRspComplianceParamField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " ClientID:" << ftdc_struct.ClientID
<< " DailyMaxOrder:" << ftdc_struct.DailyMaxOrder
<< " DailyMaxOrderAction:" << ftdc_struct.DailyMaxOrderAction
<< " DailyMaxErrorOrder:" << ftdc_struct.DailyMaxErrorOrder
<< " DailyMaxOrderVolume:" << ftdc_struct.DailyMaxOrderVolume
<< " DailyMaxOrderActionVolume:" << ftdc_struct.DailyMaxOrderActionVolume
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryUserField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryUserField) ---> StartUserID:" << ftdc_struct.StartUserID
<< " EndUserID:" << ftdc_struct.EndUserID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcUserField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcUserField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " Password:" << "it is a secret" // ftdc_struct.Password
<< " IsActive:" << ftdc_struct.IsActive
<< " UserName:" << ftdc_struct.UserName
<< " UserType:" << ftdc_struct.UserType
<< " Department:" << ftdc_struct.Department
<< " GrantFuncSet:" << ftdc_struct.GrantFuncSet
<< " SetUserID:" << ftdc_struct.SetUserID
<< " CommandDate:" << ftdc_struct.CommandDate
<< " CommandTime:" << ftdc_struct.CommandTime
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryInvestorFeeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryInvestorFeeField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcInvestorFeeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcInvestorFeeField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " ClientID:" << ftdc_struct.ClientID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " ProductID:" << ftdc_struct.ProductID
<< " OpenFeeRate:" << ftdc_struct.OpenFeeRate
<< " OpenFeeAmt:" << ftdc_struct.OpenFeeAmt
<< " OffsetFeeRate:" << ftdc_struct.OffsetFeeRate
<< " OffsetFeeAmt:" << ftdc_struct.OffsetFeeAmt
<< " OTFeeRate:" << ftdc_struct.OTFeeRate
<< " OTFeeAmt:" << ftdc_struct.OTFeeAmt
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcQryInvestorMarginField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcQryInvestorMarginField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcInvestorMarginField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcInvestorMarginField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " ClientID:" << ftdc_struct.ClientID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " ProductID:" << ftdc_struct.ProductID
<< " LongMarginRate:" << ftdc_struct.LongMarginRate
<< " LongMarginAmt:" << ftdc_struct.LongMarginAmt
<< " ShortMarginRate:" << ftdc_struct.ShortMarginRate
<< " ShortMarginAmt:" << ftdc_struct.ShortMarginAmt
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcTradeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcTradeField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " TradingDay:" << ftdc_struct.TradingDay
<< " ParticipantID:" << ftdc_struct.ParticipantID
<< " SeatID:" << ftdc_struct.SeatID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " ClientID:" << ftdc_struct.ClientID
<< " UserID:" << ftdc_struct.UserID
<< " TradeID:" << ftdc_struct.TradeID
<< " OrderSysID:" << ftdc_struct.OrderSysID
<< " UserOrderLocalID:" << ftdc_struct.UserOrderLocalID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " Direction:" << ftdc_struct.Direction
<< " OffsetFlag:" << ftdc_struct.OffsetFlag
<< " HedgeFlag:" << ftdc_struct.HedgeFlag
<< " TradePrice:" << ftdc_struct.TradePrice
<< " TradeVolume:" << ftdc_struct.TradeVolume
<< " TradeTime:" << ftdc_struct.TradeTime
<< " ClearingPartID:" << ftdc_struct.ClearingPartID
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcOrderField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcOrderField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " ExchangeID:" << ftdc_struct.ExchangeID
<< " OrderSysID:" << ftdc_struct.OrderSysID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " UserID:" << ftdc_struct.UserID
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " UserOrderLocalID:" << ftdc_struct.UserOrderLocalID
<< " OrderPriceType:" << ftdc_struct.OrderPriceType
<< " Direction:" << ftdc_struct.Direction
<< " OffsetFlag:" << ftdc_struct.OffsetFlag
<< " HedgeFlag:" << ftdc_struct.HedgeFlag
<< " LimitPrice:" << ftdc_struct.LimitPrice
<< " Volume:" << ftdc_struct.Volume
<< " TimeCondition:" << ftdc_struct.TimeCondition
<< " GTDDate:" << ftdc_struct.GTDDate
<< " VolumeCondition:" << ftdc_struct.VolumeCondition
<< " MinVolume:" << ftdc_struct.MinVolume
<< " StopPrice:" << ftdc_struct.StopPrice
<< " ForceCloseReason:" << ftdc_struct.ForceCloseReason
<< " IsAutoSuspend:" << ftdc_struct.IsAutoSuspend
<< " BusinessUnit:" << ftdc_struct.BusinessUnit
<< " UserCustom:" << ftdc_struct.UserCustom
<< " TradingDay:" << ftdc_struct.TradingDay
<< " ParticipantID:" << ftdc_struct.ParticipantID
<< " ClientID:" << ftdc_struct.ClientID
<< " SeatID:" << ftdc_struct.SeatID
<< " InsertTime:" << ftdc_struct.InsertTime
<< " OrderLocalID:" << ftdc_struct.OrderLocalID
<< " OrderSource:" << ftdc_struct.OrderSource
<< " OrderStatus:" << ftdc_struct.OrderStatus
<< " CancelTime:" << ftdc_struct.CancelTime
<< " CancelUserID:" << ftdc_struct.CancelUserID
<< " VolumeTraded:" << ftdc_struct.VolumeTraded
<< " VolumeRemain:" << ftdc_struct.VolumeRemain
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcFlowMessageCancelField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcFlowMessageCancelField) ---> SequenceSeries:" << ftdc_struct.SequenceSeries
<< " TradingDay:" << ftdc_struct.TradingDay
<< " DataCenterID:" << ftdc_struct.DataCenterID
<< " StartSequenceNo:" << ftdc_struct.StartSequenceNo
<< " EndSequenceNo:" << ftdc_struct.EndSequenceNo
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcDisseminationField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcDisseminationField) ---> SequenceSeries:" << ftdc_struct.SequenceSeries
<< " SequenceNo:" << ftdc_struct.SequenceNo
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcInvestorAccountDepositResField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcInvestorAccountDepositResField) ---> BrokerID:" << ftdc_struct.BrokerID
<< " UserID:" << ftdc_struct.UserID
<< " InvestorID:" << ftdc_struct.InvestorID
<< " AccountID:" << ftdc_struct.AccountID
<< " AccountSeqNo:" << ftdc_struct.AccountSeqNo
<< " Amount:" << ftdc_struct.Amount
<< " AmountDirection:" << ftdc_struct.AmountDirection
<< " Available:" << ftdc_struct.Available
<< " Balance:" << ftdc_struct.Balance
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataBaseField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataBaseField) ---> TradingDay:" << ftdc_struct.TradingDay
<< " SettlementGroupID:" << ftdc_struct.SettlementGroupID
<< " SettlementID:" << ftdc_struct.SettlementID
<< " PreSettlementPrice:" << ftdc_struct.PreSettlementPrice
<< " PreClosePrice:" << ftdc_struct.PreClosePrice
<< " PreOpenInterest:" << ftdc_struct.PreOpenInterest
<< " PreDelta:" << ftdc_struct.PreDelta
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataStaticField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataStaticField) ---> OpenPrice:" << ftdc_struct.OpenPrice
<< " HighestPrice:" << ftdc_struct.HighestPrice
<< " LowestPrice:" << ftdc_struct.LowestPrice
<< " ClosePrice:" << ftdc_struct.ClosePrice
<< " UpperLimitPrice:" << ftdc_struct.UpperLimitPrice
<< " LowerLimitPrice:" << ftdc_struct.LowerLimitPrice
<< " SettlementPrice:" << ftdc_struct.SettlementPrice
<< " CurrDelta:" << ftdc_struct.CurrDelta
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataLastMatchField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataLastMatchField) ---> LastPrice:" << ftdc_struct.LastPrice
<< " Volume:" << ftdc_struct.Volume
<< " Turnover:" << ftdc_struct.Turnover
<< " OpenInterest:" << ftdc_struct.OpenInterest
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataBestPriceField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataBestPriceField) ---> BidPrice1:" << ftdc_struct.BidPrice1
<< " BidVolume1:" << ftdc_struct.BidVolume1
<< " AskPrice1:" << ftdc_struct.AskPrice1
<< " AskVolume1:" << ftdc_struct.AskVolume1
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataBid23Field& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataBid23Field) ---> BidPrice2:" << ftdc_struct.BidPrice2
<< " BidVolume2:" << ftdc_struct.BidVolume2
<< " BidPrice3:" << ftdc_struct.BidPrice3
<< " BidVolume3:" << ftdc_struct.BidVolume3
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataAsk23Field& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataAsk23Field) ---> AskPrice2:" << ftdc_struct.AskPrice2
<< " AskVolume2:" << ftdc_struct.AskVolume2
<< " AskPrice3:" << ftdc_struct.AskPrice3
<< " AskVolume3:" << ftdc_struct.AskVolume3
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataBid45Field& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataBid45Field) ---> BidPrice4:" << ftdc_struct.BidPrice4
<< " BidVolume4:" << ftdc_struct.BidVolume4
<< " BidPrice5:" << ftdc_struct.BidPrice5
<< " BidVolume5:" << ftdc_struct.BidVolume5
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataAsk45Field& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataAsk45Field) ---> AskPrice4:" << ftdc_struct.AskPrice4
<< " AskVolume4:" << ftdc_struct.AskVolume4
<< " AskPrice5:" << ftdc_struct.AskPrice5
<< " AskVolume5:" << ftdc_struct.AskVolume5
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcMarketDataUpdateTimeField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcMarketDataUpdateTimeField) ---> InstrumentID:" << ftdc_struct.InstrumentID
<< " UpdateTime:" << ftdc_struct.UpdateTime
<< " UpdateMillisec:" << ftdc_struct.UpdateMillisec
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcDepthMarketDataField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcDepthMarketDataField) ---> TradingDay:" << ftdc_struct.TradingDay
<< " SettlementGroupID:" << ftdc_struct.SettlementGroupID
<< " SettlementID:" << ftdc_struct.SettlementID
<< " PreSettlementPrice:" << ftdc_struct.PreSettlementPrice
<< " PreClosePrice:" << ftdc_struct.PreClosePrice
<< " PreOpenInterest:" << ftdc_struct.PreOpenInterest
<< " PreDelta:" << ftdc_struct.PreDelta
<< " OpenPrice:" << ftdc_struct.OpenPrice
<< " HighestPrice:" << ftdc_struct.HighestPrice
<< " LowestPrice:" << ftdc_struct.LowestPrice
<< " ClosePrice:" << ftdc_struct.ClosePrice
<< " UpperLimitPrice:" << ftdc_struct.UpperLimitPrice
<< " LowerLimitPrice:" << ftdc_struct.LowerLimitPrice
<< " SettlementPrice:" << ftdc_struct.SettlementPrice
<< " CurrDelta:" << ftdc_struct.CurrDelta
<< " LastPrice:" << ftdc_struct.LastPrice
<< " Volume:" << ftdc_struct.Volume
<< " Turnover:" << ftdc_struct.Turnover
<< " OpenInterest:" << ftdc_struct.OpenInterest
<< " BidPrice1:" << ftdc_struct.BidPrice1
<< " BidVolume1:" << ftdc_struct.BidVolume1
<< " AskPrice1:" << ftdc_struct.AskPrice1
<< " AskVolume1:" << ftdc_struct.AskVolume1
<< " BidPrice2:" << ftdc_struct.BidPrice2
<< " BidVolume2:" << ftdc_struct.BidVolume2
<< " BidPrice3:" << ftdc_struct.BidPrice3
<< " BidVolume3:" << ftdc_struct.BidVolume3
<< " AskPrice2:" << ftdc_struct.AskPrice2
<< " AskVolume2:" << ftdc_struct.AskVolume2
<< " AskPrice3:" << ftdc_struct.AskPrice3
<< " AskVolume3:" << ftdc_struct.AskVolume3
<< " BidPrice4:" << ftdc_struct.BidPrice4
<< " BidVolume4:" << ftdc_struct.BidVolume4
<< " BidPrice5:" << ftdc_struct.BidPrice5
<< " BidVolume5:" << ftdc_struct.BidVolume5
<< " AskPrice4:" << ftdc_struct.AskPrice4
<< " AskVolume4:" << ftdc_struct.AskVolume4
<< " AskPrice5:" << ftdc_struct.AskPrice5
<< " AskVolume5:" << ftdc_struct.AskVolume5
<< " InstrumentID:" << ftdc_struct.InstrumentID
<< " UpdateTime:" << ftdc_struct.UpdateTime
<< " UpdateMillisec:" << ftdc_struct.UpdateMillisec
<< " <--- End";
return os;
}
inline std::ostream& operator << (std::ostream& os, const CUstpFtdcSpecificInstrumentField& ftdc_struct) {
os << "ftdc_struct(CUstpFtdcSpecificInstrumentField) ---> InstrumentID:" << ftdc_struct.InstrumentID
<< " <--- End";
return os;
}
#endif // FEMAS_SYSTEM_PRINT_FUNCTION_H_
|
#include "SwapChain.h"
#include "GdiException.h"
import "GDIPlusManager.h";
GDIPlusManager gdipm;
VSwapChain::VFrame::VFrame(int width, int height, HWND hwnd, bool ICCColorAdjustment)
: frameArea(0, 0, width, height)
{
if (ICCColorAdjustment)
{
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipCreateFromHWNDICM(hwnd, &pGfx));
}
else
{
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipCreateFromHWND(hwnd, &pGfx));
}
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipCreateBitmapFromGraphics(width,
height,
pGfx.get(),
&image));
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipGetImagePixelFormat(image.get(), reinterpret_cast<Gdiplus::PixelFormat*>(&format)));
}
void VSwapChain::VFrame::LockImage(VRTV_DESC& _out_view, Gdiplus::Rect lockArea, Gdiplus::ImageLockMode mode)
{
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipBitmapLockBits(
image.get(),
&lockArea,
mode | Gdiplus::ImageLockModeUserInputBuf,
format,
(Gdiplus::BitmapData*) & _out_view));
}
void VSwapChain::VFrame::LockFullImage(VRTV_DESC& _out_view, Gdiplus::ImageLockMode mode)
{
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipBitmapLockBits(
image.get(),
&frameArea,
mode | Gdiplus::ImageLockModeUserInputBuf,
format,
(Gdiplus::BitmapData*) & _out_view));
}
void VSwapChain::VFrame::UnlockImage(VRTV_DESC& view)
{
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipBitmapUnlockBits(
image.get(),
(Gdiplus::BitmapData*) & view));
}
void VSwapChain::VFrame::Draw() const
{
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipCreateCachedBitmap(
image.get(),
pGfx.get(),
&output
));
GDI_CALL_EXCEPT(Gdiplus::DllExports::GdipDrawCachedBitmap(
pGfx.get(),
output.get(),
0, 0
));
}
VPIXEL_FORMAT VSwapChain::VFrame::GetPixelFormat() const noexcept
{
return format;
}
VSwapChain::VSwapChain(const VSWAP_CHAIN_DESC* desc, IVDevice* gfx, HWND hwnd)
:Frame(desc->Width, desc->Height, hwnd)
{
VTEXTURE_DESC vtx;
vtx.Width = desc->Width;
vtx.Height = desc->Height;
vtx.BindFlags = VBIND_FLAG::RENDER_TARGET;
vtx.PixelFormat = Frame.GetPixelFormat();
gfx->CreateTexture2D(&vtx, &RenderBuffer);
gfx->CreateRenderTargetView(RenderBuffer.Get(), &BackBuffer);
Frame.LockFullImage(BackBuffer, Gdiplus::ImageLockModeWrite);
}
void VSwapChain::GetRenderTarget(uint32_t number, VRTV_DESC* _out_buf)
{
*_out_buf = BackBuffer;
}
void VSwapChain::Present()
{
Frame.UnlockImage(BackBuffer);
Frame.Draw();
Frame.LockFullImage(BackBuffer, Gdiplus::ImageLockModeWrite);
}
HRESULT __stdcall VFCreateSwapChain(const VSWAP_CHAIN_DESC* descriptor, IVDevice* device, HWND window, IVSwapChain** _out_swapchain)
{
return wrl::Make<VSwapChain>(descriptor, device, window).CopyTo(_out_swapchain);
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define MAX 100
#define MOD 1000000007
#define pb push_back
typedef pair<ll,ll> pl;
int main() {
ll n,m;
cin >> n >> m;
vector<pl> p;
rep(i,m) {
ll a,b; cin >> a >> b;
p.pb(make_pair(a,b));
}
sort(p.begin(), p.end(), [](const pl& x, pl& y) {return x.second < y.second;});
ll tmp = 0, ans = 0;
rep(i,m) {
if (p[i].first >= tmp) {
tmp = p[i].second;
ans++;
}
}
cout << ans << endl;
}
|
#pragma once
#include "ofMain.h"
#include "ofxFTGLFont.h"
#include "ofxFaceTracker.h"
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofImage logo;
float nextLetterTime;
int lineCount;
int letterCount;
string str;
ofTrueTypeFont franklin;
ofxFTGLFont font;
vector <string> seussLines;
bool bFirst;
string typeStr;
string savedString;
int state;
ofVideoGrabber vidGrabber;
ofTexture videoTexture;
int camWidth;
int camHeight;
ofxFaceTracker tracker;
ExpressionClassifier classifier;
};
|
#ifndef TIPOVIEWER_H
#define TIPOVIEWER_H
#include "tipoqueue.h"
class TipoViewer
{
public:
TipoViewer();
virtual ~TipoViewer();
int menu();
void listar(TipoQueue*);
int buscar();
void mostrar(Tipo*);
void cargar(Tipo*, string);
void mensaje(string);
protected:
private:
};
#endif // TIPOVIEWER_H
|
#include <math.h>
#include <gl\glut.h>
#include <gl\gl.h>
#include <gl\glu.h>
#include <string.h>
#include <stdlib.h>
float angle = 0.0, deltaAngle = 0.0;
float x = 0.0f, y = 1.75f, z = 5.0f; // tao do dung
float lx = 0.0f, ly = 0.0f, lz = -1.0f; // huong nhin
int deltaMove = 0;
int font = (int)GLUT_BITMAP_8_BY_13;
// Xu ly su kien khi thay doi kich thuoc man hinh.
void changeSize(int w, int h) {
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if(h == 0)
h = 1;
float ratio = 1.0f*w/h;
// Reset the coordinate system before modifying
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the clipping volume
gluPerspective(45, ratio, 0.1, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(x, y, z, x+lx, y+ly, z+lz, 0.0f, 1.0f, 0.0f);
}
// Ham khoi tao.
void initScene() {
glEnable(GL_DEPTH_TEST);
}
// Xoay huong nhin.
void orientMe(float ang) {
lx = sin(ang);
lz = -cos(ang);
glLoadIdentity();
gluLookAt(x, y, z, x+lx, y+ly, z+lz, 0.0f, 1.0f, 0.0f);
}
// Di chuyen.
void moveMeFlat(int i) {
x = x+i*(lx)*0.01;
z = z+i*(lz)*0.01;
glLoadIdentity();
gluLookAt(x, y, z, x+lx, y+ly, z+lz, 0.0f, 1.0f, 0.0f);
}
// Ve xau <string> tai toa do <x, y, z>, font chu la <font>.
void renderBitmapCharacher(float x, float y, float z, void *font,char *string) {
/*
char *c;
glRasterPos3f(x, y, z);
for(c = string; *c != '\0'; c++) {
glutBitmapCharacter(font, *c);
}
*/
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0,640,0,480,-1,1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glTranslated(x,y,z);
char *c;
glRasterPos3f(x, y, z);
for(c = string; *c != '\0'; c++) {
glutBitmapCharacter(font, *c);
}
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
}
// Ve hinh.
void renderScene(void) {
if(deltaMove)
moveMeFlat(deltaMove);
if(deltaAngle) {
angle += deltaAngle;
orientMe(angle);
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
renderBitmapCharacher(200, 30, 0, (void *)font, "Dien dan tin hoc");
//renderBitmapCharacher(3, 3.7, 0, (void *)font, "RedSun");
glPopMatrix();
glutSwapBuffers();
}
// Xu ly su kien ban phim.
void pressKey(int key, int x, int y) {
switch (key) {
case GLUT_KEY_LEFT:
deltaAngle = -0.01f;
break;
case GLUT_KEY_RIGHT:
deltaAngle = 0.01f;
break;
case GLUT_KEY_UP:
deltaMove = 1;
break;
case GLUT_KEY_DOWN:
deltaMove = -1;
break;
}
}
// Xu ly su kien ban phim.
void releaseKey(int key, int x, int y) {
switch (key) {
case GLUT_KEY_LEFT:
case GLUT_KEY_RIGHT:
deltaAngle = 0.0f;
break;
case GLUT_KEY_UP:
case GLUT_KEY_DOWN:
deltaMove = 0;
break;
}
}
// Xu ly su kien khi nhan menu.
void processMenuEvents(int option) {
font = option;
}
// Tao menu, khi nhan chuot phai.
void createMenus() {
int menu = glutCreateMenu(processMenuEvents);
glutAddMenuEntry("8 by 13", (int)GLUT_BITMAP_8_BY_13);
glutAddMenuEntry("9 by 15", (int)GLUT_BITMAP_9_BY_15);
glutAddMenuEntry("Times Roman 10", (int)GLUT_BITMAP_TIMES_ROMAN_10);
glutAddMenuEntry("Times Roman 24", (int)GLUT_BITMAP_TIMES_ROMAN_24);
glutAddMenuEntry("Helvetica 10", (int)GLUT_BITMAP_HELVETICA_10);
glutAddMenuEntry("Helvetica 12", (int)GLUT_BITMAP_HELVETICA_12);
glutAddMenuEntry("Helvetica 18", (int)GLUT_BITMAP_HELVETICA_18);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
// Xu ly su kien ban phim binh thuong.
void processNormalKeys(unsigned char key, int x, int y) {
if(key == 27)
exit(0);
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(640,360);
glutCreateWindow("GV");
initScene();
glutKeyboardFunc(processNormalKeys);
glutIgnoreKeyRepeat(1);
glutSpecialFunc(pressKey);
glutSpecialUpFunc(releaseKey);
createMenus();
glutDisplayFunc(renderScene);
glutIdleFunc(renderScene);
glutReshapeFunc(changeSize);
glutMainLoop();
return(0);
}
|
/**
* @file test_fkbdb.cpp
*
* @author Fan Kai(fk), Peking University
* @date 09/25/2008 09:15:43 AM CST
*
*/
#include <fkbdb.h>
#include <iostream>
using namespace std;
int main() {
fk::BDB db("fkbdb.db");
cout <<db.exists(1) <<endl;
db.put(1, 2);
db.put(2, 4.5);
db.put<double, char>(3.3, 'j');
db.put(4, "hello");
db.put("joke", "fine");
db.put(4, "world");
string s("pkucs");
db.put(s, s);
cout <<db.exists(2) <<endl;
cout <<db.exists(3) <<endl;
cout <<db.exists(s) <<endl;
cout <<db.get<int>(1) <<endl;
cout <<db.get<double>(2) <<endl;
cout <<db.get<char>(3.3) <<endl;
cout <<db.gets(4) <<endl;
cout <<db.gets("joke") <<endl;
cout <<db.gets(s) <<endl;
return 0;
}
|
#include <iostream>
#include <cstring>
#include <vector>
#include <stack>
#include <set>
int n, m, ID[41], ID_cnt, group[41], indegree[41];
bool finished[41];
std::set<int> link[41];
std::vector<std::vector<int>> SCC;
std::stack<int> stk;
int dfs(int idx)
{
ID[idx] = ++ID_cnt;
stk.push(idx);
int parent = ID[idx];
for(auto next : link[idx])
{
if(ID[next] == 0)
{
parent = std::min(parent, dfs(next));
}
else if(!finished[next])
{
parent = std::min(parent, ID[next]);
}
}
if(parent == ID[idx])
{
std::vector<int> scc;
int gidx = SCC.size();
while(!stk.empty())
{
int top = stk.top();
stk.pop();
finished[top] = 1;
group[top] = gidx;
scc.push_back(top);
if(top == idx)
{
break;
}
}
SCC.push_back(scc);
}
return parent;
}
void make_link(int xi, int xj)
{
if(xi < 0)
{
xi = -xi + n;
}
if(xj < 0)
{
xj = -xj + n;
}
link[xi].insert(xj);
}
bool check()
{
for(int i = 1; i <= n; i++)
{
if(group[i] == group[i + n])
{
return 1;
}
}
return 0;
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::cin >> n >> m;
for(int i = 0; i < m; i++)
{
int xi, xj;
std::cin >> xi >> xj;
make_link(-xi, xj);
make_link(-xj, xi);
}
for(int i = 1; i <= n * 2; i++)
{
if(ID[i] == 0)
{
dfs(i);
}
}
if(check())
{
std::cout << "0\n";
}
else
{
std::cout << "1\n";
int table[n + 1];
std::memset(table, -1, sizeof(table));
for(auto rbgn = SCC.rbegin(); rbgn != SCC.rend(); rbgn++)
{
for(auto node : *rbgn)
{
int boolean = 0;
if(node > n)
{
node -= n;
boolean++;
}
if(table[node] == -1)
{
table[node] = boolean;
}
}
}
for(int i = 1; i <= n; i++)
{
std::cout << table[i] << ' ';
}
}
return 0;
}
|
#ifndef OBJECT2ALIASED_HPP
#define OBJECT2ALIASED_HPP
#include "CustomMacros.hpp"
// Test Qt object macro hidden in a macro (AUTOMOC_MACRO_NAMES)
class Object2Aliased : public QObject
{
QO2_ALIAS
public:
Object2Aliased();
signals:
void aSignal();
public slots:
void aSlot();
};
#endif
|
// Copyright (c) 2007-2017 Hartmut Kaiser
// Copyright (c) 2011 Bryce Lelbach
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <pika/config.hpp>
#include <pika/affinity/affinity_data.hpp>
#include <pika/assert.hpp>
#include <pika/functional/function.hpp>
#include <pika/modules/errors.hpp>
#include <pika/modules/logging.hpp>
#include <pika/schedulers/deadlock_detection.hpp>
#include <pika/schedulers/lockfree_queue_backends.hpp>
#include <pika/schedulers/thread_queue.hpp>
#include <pika/threading_base/scheduler_base.hpp>
#include <pika/threading_base/thread_data.hpp>
#include <pika/threading_base/thread_num_tss.hpp>
#include <pika/threading_base/thread_queue_init_parameters.hpp>
#include <pika/topology/topology.hpp>
#include <fmt/format.h>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <exception>
#include <memory>
#include <mutex>
#include <string>
#include <type_traits>
#include <vector>
#include <pika/config/warnings_prefix.hpp>
// TODO: add branch prediction and function heat
///////////////////////////////////////////////////////////////////////////////
namespace pika::threads::detail {
///////////////////////////////////////////////////////////////////////////
#if defined(PIKA_HAVE_CXX11_STD_ATOMIC_128BIT)
using default_local_queue_scheduler_terminated_queue = lockfree_lifo;
#else
using default_local_queue_scheduler_terminated_queue = lockfree_fifo;
#endif
///////////////////////////////////////////////////////////////////////////
/// The local_queue_scheduler maintains exactly one queue of work
/// items (threads) per OS thread, where this OS thread pulls its next work
/// from.
template <typename Mutex = std::mutex, typename PendingQueuing = lockfree_fifo,
typename StagedQueuing = lockfree_fifo,
typename TerminatedQueuing = default_local_queue_scheduler_terminated_queue>
class PIKA_EXPORT local_queue_scheduler : public scheduler_base
{
public:
using has_periodic_maintenance = std::false_type;
using thread_queue_type =
thread_queue<Mutex, PendingQueuing, StagedQueuing, TerminatedQueuing>;
struct init_parameter
{
init_parameter(std::size_t num_queues, pika::detail::affinity_data const& affinity_data,
thread_queue_init_parameters thread_queue_init = {},
char const* description = "local_queue_scheduler")
: num_queues_(num_queues)
, thread_queue_init_(thread_queue_init)
, affinity_data_(affinity_data)
, description_(description)
{
}
init_parameter(std::size_t num_queues, pika::detail::affinity_data const& affinity_data,
char const* description)
: num_queues_(num_queues)
, thread_queue_init_()
, affinity_data_(affinity_data)
, description_(description)
{
}
std::size_t num_queues_;
thread_queue_init_parameters thread_queue_init_;
pika::detail::affinity_data const& affinity_data_;
char const* description_;
};
using init_parameter_type = init_parameter;
local_queue_scheduler(init_parameter_type const& init, bool deferred_initialization = true)
: scheduler_base(init.num_queues_, init.description_, init.thread_queue_init_)
, queues_(init.num_queues_)
, curr_queue_(0)
, affinity_data_(init.affinity_data_)
, steals_in_numa_domain_()
, steals_outside_numa_domain_()
, numa_domain_masks_(init.num_queues_,
::pika::threads::detail::get_topology().get_machine_affinity_mask())
, outside_numa_domain_masks_(init.num_queues_,
::pika::threads::detail::get_topology().get_machine_affinity_mask())
{
::pika::threads::detail::resize(
steals_in_numa_domain_, threads::detail::hardware_concurrency());
::pika::threads::detail::resize(
steals_outside_numa_domain_, threads::detail::hardware_concurrency());
if (!deferred_initialization)
{
PIKA_ASSERT(init.num_queues_ != 0);
for (std::size_t i = 0; i < init.num_queues_; ++i)
queues_[i] = new thread_queue_type(i, thread_queue_init_);
}
}
virtual ~local_queue_scheduler()
{
for (std::size_t i = 0; i != queues_.size(); ++i) delete queues_[i];
}
static std::string get_scheduler_name() { return "local_queue_scheduler"; }
#ifdef PIKA_HAVE_THREAD_CREATION_AND_CLEANUP_RATES
std::uint64_t get_creation_time(bool reset) override
{
std::uint64_t time = 0;
for (std::size_t i = 0; i != queues_.size(); ++i)
time += queues_[i]->get_creation_time(reset);
return time;
}
std::uint64_t get_cleanup_time(bool reset) override
{
std::uint64_t time = 0;
for (std::size_t i = 0; i != queues_.size(); ++i)
time += queues_[i]->get_cleanup_time(reset);
return time;
}
#endif
#ifdef PIKA_HAVE_THREAD_STEALING_COUNTS
std::int64_t get_num_pending_misses(std::size_t num_thread, bool reset) override
{
std::int64_t num_pending_misses = 0;
if (num_thread == std::size_t(-1))
{
for (std::size_t i = 0; i != queues_.size(); ++i)
num_pending_misses += queues_[i]->get_num_pending_misses(reset);
return num_pending_misses;
}
num_pending_misses += queues_[num_thread]->get_num_pending_misses(reset);
return num_pending_misses;
}
std::int64_t get_num_pending_accesses(std::size_t num_thread, bool reset) override
{
std::int64_t num_pending_accesses = 0;
if (num_thread == std::size_t(-1))
{
for (std::size_t i = 0; i != queues_.size(); ++i)
num_pending_accesses += queues_[i]->get_num_pending_accesses(reset);
return num_pending_accesses;
}
num_pending_accesses += queues_[num_thread]->get_num_pending_accesses(reset);
return num_pending_accesses;
}
std::int64_t get_num_stolen_from_pending(std::size_t num_thread, bool reset) override
{
std::int64_t num_stolen_threads = 0;
if (num_thread == std::size_t(-1))
{
for (std::size_t i = 0; i != queues_.size(); ++i)
num_stolen_threads += queues_[i]->get_num_stolen_from_pending(reset);
return num_stolen_threads;
}
num_stolen_threads += queues_[num_thread]->get_num_stolen_from_pending(reset);
return num_stolen_threads;
}
std::int64_t get_num_stolen_to_pending(std::size_t num_thread, bool reset) override
{
std::int64_t num_stolen_threads = 0;
if (num_thread == std::size_t(-1))
{
for (std::size_t i = 0; i != queues_.size(); ++i)
num_stolen_threads += queues_[i]->get_num_stolen_to_pending(reset);
return num_stolen_threads;
}
num_stolen_threads += queues_[num_thread]->get_num_stolen_to_pending(reset);
return num_stolen_threads;
}
std::int64_t get_num_stolen_from_staged(std::size_t num_thread, bool reset) override
{
std::int64_t num_stolen_threads = 0;
if (num_thread == std::size_t(-1))
{
for (std::size_t i = 0; i != queues_.size(); ++i)
num_stolen_threads += queues_[i]->get_num_stolen_from_staged(reset);
return num_stolen_threads;
}
num_stolen_threads += queues_[num_thread]->get_num_stolen_from_staged(reset);
return num_stolen_threads;
}
std::int64_t get_num_stolen_to_staged(std::size_t num_thread, bool reset) override
{
std::int64_t num_stolen_threads = 0;
if (num_thread == std::size_t(-1))
{
for (std::size_t i = 0; i != queues_.size(); ++i)
num_stolen_threads += queues_[i]->get_num_stolen_to_staged(reset);
return num_stolen_threads;
}
num_stolen_threads += queues_[num_thread]->get_num_stolen_to_staged(reset);
return num_stolen_threads;
}
#endif
///////////////////////////////////////////////////////////////////////
void abort_all_suspended_threads() override
{
for (std::size_t i = 0; i != queues_.size(); ++i)
queues_[i]->abort_all_suspended_threads();
}
///////////////////////////////////////////////////////////////////////
bool cleanup_terminated(bool delete_all) override
{
bool empty = true;
for (std::size_t i = 0; i != queues_.size(); ++i)
empty = queues_[i]->cleanup_terminated(delete_all) && empty;
return empty;
}
bool cleanup_terminated(std::size_t num_thread, bool delete_all) override
{
return queues_[num_thread]->cleanup_terminated(delete_all);
}
///////////////////////////////////////////////////////////////////////
// create a new thread and schedule it if the initial state is equal to
// pending
void create_thread(threads::detail::thread_init_data& data,
threads::detail::thread_id_ref_type* id, error_code& ec) override
{
std::size_t num_thread =
data.schedulehint.mode == execution::thread_schedule_hint_mode::thread ?
data.schedulehint.hint :
std::size_t(-1);
std::size_t queue_size = queues_.size();
if (std::size_t(-1) == num_thread) { num_thread = curr_queue_++ % queue_size; }
else if (num_thread >= queue_size) { num_thread %= queue_size; }
std::unique_lock<pu_mutex_type> l;
num_thread = select_active_pu(l, num_thread);
PIKA_ASSERT(num_thread < queue_size);
queues_[num_thread]->create_thread(data, id, ec);
LTM_(debug)
.format("local_queue_scheduler::create_thread: pool({}), scheduler({}), "
"worker_thread({}), thread({})",
*this->get_parent_pool(), *this, num_thread,
id ? *id : threads::detail::invalid_thread_id)
#ifdef PIKA_HAVE_THREAD_DESCRIPTION
.format(", description({})", data.description)
#endif
;
}
/// Return the next thread to be executed, return false if none is
/// available
virtual bool get_next_thread(std::size_t num_thread, bool running,
threads::detail::thread_id_ref_type& thrd,
bool /*scheduler_mode::enable_stealing*/) override
{
std::size_t queues_size = queues_.size();
{
PIKA_ASSERT(num_thread < queues_size);
thread_queue_type* q = queues_[num_thread];
bool result = q->get_next_thread(thrd);
q->increment_num_pending_accesses();
if (result) return true;
q->increment_num_pending_misses();
bool have_staged = q->get_staged_queue_length(std::memory_order_relaxed) != 0;
// Give up, we should have work to convert.
if (have_staged) return false;
}
if (!running) { return false; }
bool numa_stealing = has_scheduler_mode(scheduler_mode::enable_stealing_numa);
if (!numa_stealing)
{
// steal work items: first try to steal from other cores in
// the same NUMA node
std::size_t pu_number = affinity_data_.get_pu_num(num_thread);
if (::pika::threads::detail::test(steals_in_numa_domain_,
pu_number)) //-V600 //-V111
{
::pika::threads::detail::mask_cref_type this_numa_domain =
numa_domain_masks_[num_thread];
// steal thread from other queue
for (std::size_t i = 1; i != queues_size; ++i)
{
// FIXME: Do a better job here.
std::size_t const idx = (i + num_thread) % queues_size;
PIKA_ASSERT(idx != num_thread);
std::size_t pu_num = affinity_data_.get_pu_num(idx);
if (!::pika::threads::detail::test(this_numa_domain,
pu_num)) //-V560 //-V600 //-V111
continue;
thread_queue_type* q = queues_[idx];
if (q->get_next_thread(thrd, running))
{
q->increment_num_stolen_from_pending();
queues_[num_thread]->increment_num_stolen_to_pending();
return true;
}
}
}
// if nothing found, ask everybody else
if (::pika::threads::detail::test(steals_outside_numa_domain_,
pu_number)) //-V600 //-V111
{
::pika::threads::detail::mask_cref_type numa_domain =
outside_numa_domain_masks_[num_thread];
// steal thread from other queue
for (std::size_t i = 1; i != queues_size; ++i)
{
// FIXME: Do a better job here.
std::size_t const idx = (i + num_thread) % queues_size;
PIKA_ASSERT(idx != num_thread);
std::size_t pu_num = affinity_data_.get_pu_num(idx);
if (!::pika::threads::detail::test(numa_domain,
pu_num)) //-V560 //-V600 //-V111
continue;
thread_queue_type* q = queues_[idx];
if (q->get_next_thread(thrd, running))
{
q->increment_num_stolen_from_pending();
queues_[num_thread]->increment_num_stolen_to_pending();
return true;
}
}
}
}
else // not NUMA-sensitive - numa stealing ok
{
for (std::size_t i = 1; i != queues_size; ++i)
{
// FIXME: Do a better job here.
std::size_t const idx = (i + num_thread) % queues_size;
PIKA_ASSERT(idx != num_thread);
thread_queue_type* q = queues_[idx];
if (q->get_next_thread(thrd, running))
{
q->increment_num_stolen_from_pending();
queues_[num_thread]->increment_num_stolen_to_pending();
return true;
}
}
}
return false;
}
/// Schedule the passed thread
void schedule_thread(threads::detail::thread_id_ref_type thrd,
execution::thread_schedule_hint schedulehint, bool allow_fallback,
execution::thread_priority /* priority */ = execution::thread_priority::normal) override
{
// NOTE: This scheduler ignores NUMA hints.
std::size_t num_thread = std::size_t(-1);
if (schedulehint.mode == execution::thread_schedule_hint_mode::thread)
{
num_thread = schedulehint.hint;
}
else { allow_fallback = false; }
std::size_t queue_size = queues_.size();
if (std::size_t(-1) == num_thread) { num_thread = curr_queue_++ % queue_size; }
else if (num_thread >= queue_size) { num_thread %= queue_size; }
std::unique_lock<pu_mutex_type> l;
num_thread = select_active_pu(l, num_thread, allow_fallback);
PIKA_ASSERT(get_thread_id_data(thrd)->get_scheduler_base() == this);
PIKA_ASSERT(num_thread < queues_.size());
LTM_(debug).format("local_queue_scheduler::schedule_thread: pool({}), scheduler({}), "
"worker_thread({}), thread({}), description({})",
*this->get_parent_pool(), *this, num_thread,
get_thread_id_data(thrd)->get_thread_id(),
get_thread_id_data(thrd)->get_description());
queues_[num_thread]->schedule_thread(thrd);
}
void schedule_thread_last(threads::detail::thread_id_ref_type thrd,
execution::thread_schedule_hint schedulehint, bool allow_fallback,
execution::thread_priority /* priority */ = execution::thread_priority::normal) override
{
// NOTE: This scheduler ignores NUMA hints.
std::size_t num_thread = std::size_t(-1);
if (schedulehint.mode == execution::thread_schedule_hint_mode::thread)
{
num_thread = schedulehint.hint;
}
else { allow_fallback = false; }
std::size_t queue_size = queues_.size();
if (std::size_t(-1) == num_thread) { num_thread = curr_queue_++ % queue_size; }
else if (num_thread >= queue_size) { num_thread %= queue_size; }
std::unique_lock<pu_mutex_type> l;
num_thread = select_active_pu(l, num_thread, allow_fallback);
PIKA_ASSERT(get_thread_id_data(thrd)->get_scheduler_base() == this);
PIKA_ASSERT(num_thread < queues_.size());
queues_[num_thread]->schedule_thread(thrd, true);
}
/// Destroy the passed thread as it has been terminated
void destroy_thread(threads::detail::thread_data* thrd) override
{
PIKA_ASSERT(thrd->get_scheduler_base() == this);
thrd->get_queue<thread_queue_type>().destroy_thread(thrd);
}
///////////////////////////////////////////////////////////////////////
// This returns the current length of the queues (work items and new items)
std::int64_t get_queue_length(std::size_t num_thread = std::size_t(-1)) const override
{
// Return queue length of one specific queue.
std::int64_t count = 0;
if (std::size_t(-1) != num_thread)
{
PIKA_ASSERT(num_thread < queues_.size());
return queues_[num_thread]->get_queue_length();
}
for (std::size_t i = 0; i != queues_.size(); ++i)
count += queues_[i]->get_queue_length();
return count;
}
///////////////////////////////////////////////////////////////////////
// Queries the current thread count of the queues.
std::int64_t get_thread_count(threads::detail::thread_schedule_state state =
threads::detail::thread_schedule_state::unknown,
execution::thread_priority priority = execution::thread_priority::default_,
std::size_t num_thread = std::size_t(-1), bool /* reset */ = false) const override
{
// Return thread count of one specific queue.
std::int64_t count = 0;
if (std::size_t(-1) != num_thread)
{
PIKA_ASSERT(num_thread < queues_.size());
switch (priority)
{
case execution::thread_priority::default_:
case execution::thread_priority::low:
case execution::thread_priority::normal:
case execution::thread_priority::boost:
case execution::thread_priority::high:
case execution::thread_priority::high_recursive:
return queues_[num_thread]->get_thread_count(state);
default:
case execution::thread_priority::unknown:
{
PIKA_THROW_EXCEPTION(pika::error::bad_parameter,
"local_queue_scheduler::get_thread_count",
"unknown thread priority value (execution::thread_priority::unknown)");
return 0;
}
}
}
// Return the cumulative count for all queues.
switch (priority)
{
case execution::thread_priority::default_:
case execution::thread_priority::low:
case execution::thread_priority::normal:
case execution::thread_priority::boost:
case execution::thread_priority::high:
case execution::thread_priority::high_recursive:
{
for (std::size_t i = 0; i != queues_.size(); ++i)
count += queues_[i]->get_thread_count(state);
break;
}
default:
case execution::thread_priority::unknown:
{
PIKA_THROW_EXCEPTION(pika::error::bad_parameter,
"local_queue_scheduler::get_thread_count",
"unknown thread priority value (execution::thread_priority::unknown)");
return 0;
}
}
return count;
}
// Queries whether a given core is idle
bool is_core_idle(std::size_t num_thread) const override
{
return queues_[num_thread]->get_queue_length() == 0;
}
///////////////////////////////////////////////////////////////////////
// Enumerate matching threads from all queues
bool enumerate_threads(
util::detail::function<bool(threads::detail::thread_id_type)> const& f,
threads::detail::thread_schedule_state state =
threads::detail::thread_schedule_state::unknown) const override
{
bool result = true;
for (std::size_t i = 0; i != queues_.size(); ++i)
{
result = result && queues_[i]->enumerate_threads(f, state);
}
return result;
}
#ifdef PIKA_HAVE_THREAD_QUEUE_WAITTIME
///////////////////////////////////////////////////////////////////////
// Queries the current average thread wait time of the queues.
std::int64_t get_average_thread_wait_time(
std::size_t num_thread = std::size_t(-1)) const override
{
// Return average thread wait time of one specific queue.
std::uint64_t wait_time = 0;
std::uint64_t count = 0;
if (std::size_t(-1) != num_thread)
{
PIKA_ASSERT(num_thread < queues_.size());
wait_time += queues_[num_thread]->get_average_thread_wait_time();
return wait_time / (count + 1);
}
for (std::size_t i = 0; i != queues_.size(); ++i)
{
wait_time += queues_[i]->get_average_thread_wait_time();
++count;
}
return wait_time / (count + 1);
}
///////////////////////////////////////////////////////////////////////
// Queries the current average task wait time of the queues.
std::int64_t get_average_task_wait_time(
std::size_t num_thread = std::size_t(-1)) const override
{
// Return average task wait time of one specific queue.
std::uint64_t wait_time = 0;
std::uint64_t count = 0;
if (std::size_t(-1) != num_thread)
{
PIKA_ASSERT(num_thread < queues_.size());
wait_time += queues_[num_thread]->get_average_task_wait_time();
return wait_time / (count + 1);
}
for (std::size_t i = 0; i != queues_.size(); ++i)
{
wait_time += queues_[i]->get_average_task_wait_time();
++count;
}
return wait_time / (count + 1);
}
#endif
/// This is a function which gets called periodically by the thread
/// manager to allow for maintenance tasks to be executed in the
/// scheduler. Returns true if the OS thread calling this function
/// has to be terminated (i.e. no more work has to be done).
virtual bool wait_or_add_new(std::size_t num_thread, bool running,
std::int64_t& idle_loop_count, bool /* scheduler_mode::enable_stealing */,
std::size_t& added) override
{
std::size_t queues_size = queues_.size();
PIKA_ASSERT(num_thread < queues_.size());
added = 0;
bool result = true;
result = queues_[num_thread]->wait_or_add_new(running, added) && result;
if (0 != added) return result;
// Check if we have been disabled
if (!running) { return true; }
bool numa_stealing_ = has_scheduler_mode(scheduler_mode::enable_stealing_numa);
// limited or no stealing across domains
if (!numa_stealing_)
{
// steal work items: first try to steal from other cores in
// the same NUMA node
std::size_t pu_number = affinity_data_.get_pu_num(num_thread);
if (::pika::threads::detail::test(steals_in_numa_domain_,
pu_number)) //-V600 //-V111
{
::pika::threads::detail::mask_cref_type numa_domain_mask =
numa_domain_masks_[num_thread];
for (std::size_t i = 1; i != queues_size; ++i)
{
// FIXME: Do a better job here.
std::size_t const idx = (i + num_thread) % queues_size;
PIKA_ASSERT(idx != num_thread);
if (!::pika::threads::detail::test(numa_domain_mask,
affinity_data_.get_pu_num(idx))) //-V600
{
continue;
}
result =
queues_[num_thread]->wait_or_add_new(running, added, queues_[idx]) &&
result;
if (0 != added)
{
queues_[idx]->increment_num_stolen_from_staged(added);
queues_[num_thread]->increment_num_stolen_to_staged(added);
return result;
}
}
}
// if nothing found, ask everybody else
if (::pika::threads::detail::test(steals_outside_numa_domain_,
pu_number)) //-V600 //-V111
{
::pika::threads::detail::mask_cref_type numa_domain_mask =
outside_numa_domain_masks_[num_thread];
for (std::size_t i = 1; i != queues_size; ++i)
{
// FIXME: Do a better job here.
std::size_t const idx = (i + num_thread) % queues_size;
PIKA_ASSERT(idx != num_thread);
if (!::pika::threads::detail::test(numa_domain_mask,
affinity_data_.get_pu_num(idx))) //-V600
{
continue;
}
result =
queues_[num_thread]->wait_or_add_new(running, added, queues_[idx]) &&
result;
if (0 != added)
{
queues_[idx]->increment_num_stolen_from_staged(added);
queues_[num_thread]->increment_num_stolen_to_staged(added);
return result;
}
}
}
}
else // not NUMA-sensitive : numa stealing ok
{
for (std::size_t i = 1; i != queues_size; ++i)
{
// FIXME: Do a better job here.
std::size_t const idx = (i + num_thread) % queues_size;
PIKA_ASSERT(idx != num_thread);
result = queues_[num_thread]->wait_or_add_new(running, added, queues_[idx]) &&
result;
if (0 != added)
{
queues_[idx]->increment_num_stolen_from_staged(added);
queues_[num_thread]->increment_num_stolen_to_staged(added);
return result;
}
}
}
#ifdef PIKA_HAVE_THREAD_DEADLOCK_DETECTION
// no new work is available, are we deadlocked?
if (PIKA_UNLIKELY(get_deadlock_detection_enabled() && LPIKA_ENABLED(error)))
{
bool suspended_only = true;
for (std::size_t i = 0; suspended_only && i != queues_.size(); ++i)
{
suspended_only =
queues_[i]->dump_suspended_threads(i, idle_loop_count, running);
}
if (PIKA_UNLIKELY(suspended_only))
{
if (running)
{
LTM_(warning).format("pool({}), scheduler({}), queue({}): no new work "
"available, are we deadlocked?",
*this->get_parent_pool(), *this, num_thread);
}
else
{
LPIKA_CONSOLE_(pika::util::logging::level::warning)
.format(" [TM] pool({}), scheduler({}), queue({}): no new work "
"available, are we deadlocked?\n",
*this->get_parent_pool(), *this, num_thread);
}
}
}
#else
PIKA_UNUSED(idle_loop_count);
#endif
return result;
}
///////////////////////////////////////////////////////////////////////
void on_start_thread(std::size_t num_thread) override
{
pika::threads::detail::set_local_thread_num_tss(num_thread);
pika::threads::detail::set_thread_pool_num_tss(parent_pool_->get_pool_id().index());
if (nullptr == queues_[num_thread])
{
queues_[num_thread] = new thread_queue_type(num_thread, thread_queue_init_);
}
queues_[num_thread]->on_start_thread(num_thread);
auto const& topo = ::pika::threads::detail::get_topology();
// pre-calculate certain constants for the given thread number
std::size_t num_pu = affinity_data_.get_pu_num(num_thread);
::pika::threads::detail::mask_cref_type machine_mask = topo.get_machine_affinity_mask();
::pika::threads::detail::mask_cref_type core_mask =
topo.get_thread_affinity_mask(num_pu);
::pika::threads::detail::mask_cref_type node_mask =
topo.get_numa_node_affinity_mask(num_pu);
if (::pika::threads::detail::any(core_mask) && ::pika::threads::detail::any(node_mask))
{
::pika::threads::detail::set(steals_in_numa_domain_, num_pu);
numa_domain_masks_[num_thread] = node_mask;
}
// we allow the thread on the boundary of the NUMA domain to steal
::pika::threads::detail::mask_type first_mask = ::pika::threads::detail::mask_type();
::pika::threads::detail::resize(
first_mask, ::pika::threads::detail::mask_size(core_mask));
std::size_t first = ::pika::threads::detail::find_first(node_mask);
if (first != std::size_t(-1))
::pika::threads::detail::set(first_mask, first);
else
first_mask = core_mask;
bool numa_stealing = has_scheduler_mode(scheduler_mode::enable_stealing_numa);
if (numa_stealing && ::pika::threads::detail::any(first_mask & core_mask))
{
::pika::threads::detail::set(steals_outside_numa_domain_, num_pu);
outside_numa_domain_masks_[num_thread] =
::pika::threads::detail::not_(node_mask) & machine_mask;
}
}
void on_stop_thread(std::size_t num_thread) override
{
queues_[num_thread]->on_stop_thread(num_thread);
}
void on_error(std::size_t num_thread, std::exception_ptr const& e) override
{
queues_[num_thread]->on_error(num_thread, e);
}
protected:
std::vector<thread_queue_type*> queues_;
std::atomic<std::size_t> curr_queue_;
pika::detail::affinity_data const& affinity_data_;
::pika::threads::detail::mask_type steals_in_numa_domain_;
::pika::threads::detail::mask_type steals_outside_numa_domain_;
std::vector<::pika::threads::detail::mask_type> numa_domain_masks_;
std::vector<::pika::threads::detail::mask_type> outside_numa_domain_masks_;
};
} // namespace pika::threads::detail
template <typename Mutex, typename PendingQueuing, typename StagedQueuing,
typename TerminatedQueuing>
struct fmt::formatter<pika::threads::detail::local_queue_scheduler<Mutex, PendingQueuing,
StagedQueuing, TerminatedQueuing>> : fmt::formatter<pika::threads::detail::scheduler_base>
{
template <typename FormatContext>
auto format(pika::threads::detail::scheduler_base const& scheduler, FormatContext& ctx)
{
return fmt::formatter<pika::threads::detail::scheduler_base>::format(scheduler, ctx);
}
};
#include <pika/config/warnings_suffix.hpp>
|
#include <KNoTThing.h>
#include <SoftwareSerial.h>
#define OPENING_SENSOR_PIN 2
#define OPENING_SENSOR_NAME "Opening Sensor"
#define OPENING_SENSOR_ID 69
#define BLUETOOTH_SENSOR_PIN 3
#define BLUETOOTH_POWER_PIN 4
#define BLUETOOTH_AT_PIN 5
#define BLUETOOTH_TX_PIN A0
#define BLUETOOTH_RX_PIN A1
#define BLUETOOTH_SENSOR_NAME "Bluetooth Sensor"
#define BLUETOOTH_SENSOR_ID 96
bool BTConnectionStatus;
bool previousBTConnectionStatus;
bool BTATStatus;
/*
String SerialString;
SoftwareSerial BTSerial(BLUETOOTH_TX_PIN, BLUETOOTH_RX_PIN); //Arduino (RX, TX) - Bluetooth (TX, RX)
*/
KNoTThing thing;
static int open_sensor_read(uint8_t *val)
{
*val = digitalRead(OPENING_SENSOR_PIN);
Serial.print("Sensor Status: ");
if(*val)
Serial.println(F("Closed"));
else
Serial.println(F("Open"));
return 0;
}
static int bluetooth_sensor_read(uint8_t *val)
{
*val = !digitalRead(BLUETOOTH_SENSOR_PIN);
Serial.print("Bluetooth Status: ");
if(*val)
Serial.println(F("Disconnected"));
else
Serial.println(F("Connected"));
return 0;
}
/*
String getStringFromSerial()
{
String str;
if(Serial.available() > 0)
{
str = Serial.readStringUntil('\n');
Serial.println(str);
}
str.trim();
return str;
}
void enterATMode(){
BTSerial.begin(38400);
delay(250);
digitalWrite(BLUETOOTH_SENSOR_PIN, LOW);
delay(250);
digitalWrite(BLUETOOTH_AT_PIN, HIGH);
delay(250);
digitalWrite(BLUETOOTH_SENSOR_PIN, HIGH);
delay(250);
Serial.println("BT on AT Mode");
BTATStatus = true;
}
void exitATMode(){
BTSerial.end();
delay(250);
digitalWrite(BLUETOOTH_SENSOR_PIN, LOW);
delay(250);
digitalWrite(BLUETOOTH_AT_PIN, LOW);
delay(250);
digitalWrite(BLUETOOTH_SENSOR_PIN, HIGH);
delay(250);
Serial.println("BT out of AT Mode");
BTATStatus = false;
}
void BTConnectionCheck(){
BTConnectionStatus = !digitalRead(BLUETOOTH_SENSOR_PIN);
if(BTConnectionStatus == !previousBTConnectionStatus){
if(BTConnectionStatus == HIGH){
Serial.println("Container conectado");
}
else{
Serial.println("Container desconectado");
}
}
previousBTConnectionStatus = BTConnectionStatus;
delay(250);
}
*/
void setup(){
Serial.begin(9600);
while(!Serial);
pinMode(OPENING_SENSOR_PIN, INPUT);
pinMode(BLUETOOTH_SENSOR_PIN, INPUT);
pinMode(BLUETOOTH_POWER_PIN, OUTPUT);
pinMode(BLUETOOTH_AT_PIN, OUTPUT);
digitalWrite(BLUETOOTH_POWER_PIN, HIGH);
digitalWrite(BLUETOOTH_AT_PIN, LOW);
//BTConnectionStatus = digitalRead(BLUETOOTH_SENSOR_PIN);
//previousBTConnectionStatus = BTConnectionStatus;
BTATStatus = false;
Serial.println("Bluetooth ready!");
thing.init("Container");
thing.registerBoolData(OPENING_SENSOR_NAME, OPENING_SENSOR_ID, KNOT_TYPE_ID_SWITCH,
KNOT_UNIT_NOT_APPLICABLE, open_sensor_read, NULL);
thing.registerBoolData(BLUETOOTH_SENSOR_NAME, BLUETOOTH_SENSOR_ID, KNOT_TYPE_ID_SWITCH,
KNOT_UNIT_NOT_APPLICABLE, bluetooth_sensor_read, NULL);
thing.registerDefaultConfig(OPENING_SENSOR_ID, KNOT_EVT_FLAG_TIME, 1, 0, 0, 0, 0);
thing.registerDefaultConfig(BLUETOOTH_SENSOR_ID, KNOT_EVT_FLAG_TIME, 1, 0, 0, 0, 0);
Serial.println(F("Remote Opening Sensor KNoT"));
}
void loop(){
thing.run();
/*if(BTSerial.available()){
Serial.write(BTSerial.read());
}
SerialString = getStringFromSerial();
if(SerialString == "ATMode"){
enterATMode();
}
if(BTATStatus == true){
if(SerialString == "exitATMode"){
exitATMode();
}
if(SerialString != ""){
BTSerial.println(SerialString);
}
}
else{
digitalWrite(BLUETOOTH_RX_PIN, LOW);
BTConnectionCheck();
}*/
}
|
// Created on: 2017-02-16
// Created by: Sergey NIKONOV
// Copyright (c) 2008-2017 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XmlMXCAFDoc_AssemblyItemRefDriver_HeaderFile
#define _XmlMXCAFDoc_AssemblyItemRefDriver_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <XmlMDF_ADriver.hxx>
#include <XmlObjMgt_RRelocationTable.hxx>
#include <XmlObjMgt_SRelocationTable.hxx>
class Message_Messenger;
class TDF_Attribute;
class XmlObjMgt_Persistent;
class XmlMXCAFDoc_AssemblyItemRefDriver;
DEFINE_STANDARD_HANDLE(XmlMXCAFDoc_AssemblyItemRefDriver, XmlMDF_ADriver)
//! Attribute Driver.
class XmlMXCAFDoc_AssemblyItemRefDriver : public XmlMDF_ADriver
{
public:
Standard_EXPORT XmlMXCAFDoc_AssemblyItemRefDriver(const Handle(Message_Messenger)& theMessageDriver);
Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE;
Standard_EXPORT Standard_Boolean Paste(const XmlObjMgt_Persistent& theSource,
const Handle(TDF_Attribute)& theTarget,
XmlObjMgt_RRelocationTable& theRelocTable) const Standard_OVERRIDE;
Standard_EXPORT void Paste(const Handle(TDF_Attribute)& theSource,
XmlObjMgt_Persistent& theTarget,
XmlObjMgt_SRelocationTable& theRelocTable) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(XmlMXCAFDoc_AssemblyItemRefDriver, XmlMDF_ADriver)
};
#endif // _XmlMXCAFDoc_AssemblyItemRefDriver_HeaderFile
|
/********************************************************************************
** Form generated from reading UI file 'dimensionement.ui'
**
** Created: Tue 16. Apr 16:14:38 2013
** by: Qt User Interface Compiler version 4.8.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DIMENSIONEMENT_H
#define UI_DIMENSIONEMENT_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_dimensionement
{
public:
QVBoxLayout *verticalLayout_2;
QVBoxLayout *verticalLayout_3;
QLabel *label;
QHBoxLayout *horizontalLayout;
QHBoxLayout *horizontalLayout_3;
QLabel *label_3;
QHBoxLayout *horizontalLayout_6;
QLineEdit *lineEdit_pseudo;
QHBoxLayout *horizontalLayout_5;
QLabel *label_2;
QHBoxLayout *horizontalLayout_2;
QLineEdit *lineEdit_simulation;
QHBoxLayout *horizontalLayout_4;
QHBoxLayout *horizontalLayout_10;
QLabel *label_4;
QHBoxLayout *horizontalLayout_9;
QLineEdit *lineEdit_societe;
QHBoxLayout *horizontalLayout_11;
QPushButton *pushButton;
QHBoxLayout *horizontalLayout_8;
QHBoxLayout *horizontalLayout_7;
QPushButton *pushButton_2;
void setupUi(QWidget *dimensionement)
{
if (dimensionement->objectName().isEmpty())
dimensionement->setObjectName(QString::fromUtf8("dimensionement"));
dimensionement->resize(1280, 800);
dimensionement->setMaximumSize(QSize(1280, 803));
QFont font;
font.setPointSize(14);
dimensionement->setFont(font);
verticalLayout_2 = new QVBoxLayout(dimensionement);
verticalLayout_2->setContentsMargins(0, 0, 0, 0);
verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2"));
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setSpacing(0);
verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3"));
label = new QLabel(dimensionement);
label->setObjectName(QString::fromUtf8("label"));
label->setMaximumSize(QSize(1280, 800));
label->setStyleSheet(QString::fromUtf8("QLabel{\n"
" border-radius: 20px;\n"
" background-color: lightgray}"));
label->setPixmap(QPixmap(QString::fromUtf8(":/images/dirigeable2.png")));
label->setScaledContents(true);
label->setAlignment(Qt::AlignJustify|Qt::AlignTop);
verticalLayout_3->addWidget(label);
verticalLayout_2->addLayout(verticalLayout_3);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3"));
label_3 = new QLabel(dimensionement);
label_3->setObjectName(QString::fromUtf8("label_3"));
QFont font1;
font1.setPointSize(10);
label_3->setFont(font1);
label_3->setAlignment(Qt::AlignCenter);
horizontalLayout_3->addWidget(label_3);
horizontalLayout->addLayout(horizontalLayout_3);
horizontalLayout_6 = new QHBoxLayout();
horizontalLayout_6->setObjectName(QString::fromUtf8("horizontalLayout_6"));
lineEdit_pseudo = new QLineEdit(dimensionement);
lineEdit_pseudo->setObjectName(QString::fromUtf8("lineEdit_pseudo"));
lineEdit_pseudo->setMaximumSize(QSize(1280, 800));
lineEdit_pseudo->setAcceptDrops(false);
lineEdit_pseudo->setStyleSheet(QString::fromUtf8("QLineEdit {\n"
" border: 2px solid blue;\n"
" border-radius: 20px;\n"
" padding: 0 8px;\n"
" background: lightblue;\n"
" selection-background-color: darkgray;\n"
" }"));
horizontalLayout_6->addWidget(lineEdit_pseudo);
horizontalLayout->addLayout(horizontalLayout_6);
horizontalLayout_5 = new QHBoxLayout();
horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5"));
label_2 = new QLabel(dimensionement);
label_2->setObjectName(QString::fromUtf8("label_2"));
label_2->setFont(font1);
label_2->setAlignment(Qt::AlignCenter);
horizontalLayout_5->addWidget(label_2);
horizontalLayout->addLayout(horizontalLayout_5);
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
lineEdit_simulation = new QLineEdit(dimensionement);
lineEdit_simulation->setObjectName(QString::fromUtf8("lineEdit_simulation"));
lineEdit_simulation->setMaximumSize(QSize(1280, 800));
lineEdit_simulation->setStyleSheet(QString::fromUtf8("QLineEdit {\n"
" border: 2px solid blue;\n"
" border-radius: 20px;\n"
" padding: 0 8px;\n"
" background: lightblue;\n"
" selection-background-color: darkgray;\n"
" }"));
horizontalLayout_2->addWidget(lineEdit_simulation);
horizontalLayout->addLayout(horizontalLayout_2);
horizontalLayout->setStretch(0, 25);
horizontalLayout->setStretch(1, 25);
horizontalLayout->setStretch(2, 25);
horizontalLayout->setStretch(3, 25);
verticalLayout_2->addLayout(horizontalLayout);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4"));
horizontalLayout_10 = new QHBoxLayout();
horizontalLayout_10->setObjectName(QString::fromUtf8("horizontalLayout_10"));
label_4 = new QLabel(dimensionement);
label_4->setObjectName(QString::fromUtf8("label_4"));
label_4->setFont(font1);
label_4->setAlignment(Qt::AlignCenter);
horizontalLayout_10->addWidget(label_4);
horizontalLayout_4->addLayout(horizontalLayout_10);
horizontalLayout_9 = new QHBoxLayout();
horizontalLayout_9->setObjectName(QString::fromUtf8("horizontalLayout_9"));
lineEdit_societe = new QLineEdit(dimensionement);
lineEdit_societe->setObjectName(QString::fromUtf8("lineEdit_societe"));
lineEdit_societe->setMaximumSize(QSize(1280, 800));
lineEdit_societe->setStyleSheet(QString::fromUtf8("QLineEdit {\n"
" border: 2px solid blue;\n"
" border-radius: 20px;\n"
" padding: 0 8px;\n"
" background: lightblue;\n"
" selection-background-color: darkgray;\n"
" }"));
horizontalLayout_9->addWidget(lineEdit_societe);
horizontalLayout_4->addLayout(horizontalLayout_9);
horizontalLayout_11 = new QHBoxLayout();
horizontalLayout_11->setObjectName(QString::fromUtf8("horizontalLayout_11"));
pushButton = new QPushButton(dimensionement);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
pushButton->setMinimumSize(QSize(0, 0));
pushButton->setMaximumSize(QSize(1280, 800));
pushButton->setFont(font1);
pushButton->setAutoFillBackground(false);
pushButton->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" border-radius: 20px;\n"
" background-color: lightgray}"));
pushButton->setCheckable(false);
horizontalLayout_11->addWidget(pushButton);
horizontalLayout_4->addLayout(horizontalLayout_11);
horizontalLayout_8 = new QHBoxLayout();
horizontalLayout_8->setObjectName(QString::fromUtf8("horizontalLayout_8"));
horizontalLayout_7 = new QHBoxLayout();
horizontalLayout_7->setObjectName(QString::fromUtf8("horizontalLayout_7"));
pushButton_2 = new QPushButton(dimensionement);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
pushButton_2->setMinimumSize(QSize(0, 0));
pushButton_2->setMaximumSize(QSize(1280, 800));
pushButton_2->setFont(font1);
pushButton_2->setAutoFillBackground(false);
pushButton_2->setStyleSheet(QString::fromUtf8("QPushButton{\n"
" border-radius: 20px;\n"
" background-color: lightgray}"));
horizontalLayout_7->addWidget(pushButton_2);
horizontalLayout_8->addLayout(horizontalLayout_7);
horizontalLayout_4->addLayout(horizontalLayout_8);
horizontalLayout_4->setStretch(0, 25);
horizontalLayout_4->setStretch(1, 25);
horizontalLayout_4->setStretch(2, 25);
horizontalLayout_4->setStretch(3, 25);
verticalLayout_2->addLayout(horizontalLayout_4);
verticalLayout_2->setStretch(0, 80);
verticalLayout_2->setStretch(1, 10);
verticalLayout_2->setStretch(2, 10);
retranslateUi(dimensionement);
QMetaObject::connectSlotsByName(dimensionement);
} // setupUi
void retranslateUi(QWidget *dimensionement)
{
dimensionement->setWindowTitle(QApplication::translate("dimensionement", "Form", 0, QApplication::UnicodeUTF8));
label->setText(QString());
label_3->setText(QApplication::translate("dimensionement", "Pseudo de l'utilisateur:", 0, QApplication::UnicodeUTF8));
label_2->setText(QApplication::translate("dimensionement", "Nom de la simulation:", 0, QApplication::UnicodeUTF8));
label_4->setText(QApplication::translate("dimensionement", "Nom de la soci\303\251t\303\251:", 0, QApplication::UnicodeUTF8));
pushButton->setText(QApplication::translate("dimensionement", "Simulation", 0, QApplication::UnicodeUTF8));
pushButton_2->setText(QApplication::translate("dimensionement", "Quitter", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class dimensionement: public Ui_dimensionement {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DIMENSIONEMENT_H
|
// Copyright (c) 2015 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _ShapePersistent_BRep_HeaderFile
#define _ShapePersistent_BRep_HeaderFile
#include <ShapePersistent_TopoDS.hxx>
#include <ShapePersistent_Geom2d.hxx>
#include <ShapePersistent_Poly.hxx>
#include <StdObjMgt_TransientPersistentMap.hxx>
#include <StdObject_Location.hxx>
#include <StdObject_gp_Vectors.hxx>
#include <BRep_ListOfPointRepresentation.hxx>
#include <BRep_ListOfCurveRepresentation.hxx>
#include <gp_Pnt.hxx>
#include <gp_Pnt2d.hxx>
class BRep_PointRepresentation;
class BRep_CurveRepresentation;
class TopoDS_Vertex;
class TopoDS_Edge;
class TopoDS_Face;
class ShapePersistent_BRep : public ShapePersistent_TopoDS
{
public:
class PointRepresentation : public StdObjMgt_Persistent
{
friend class ShapePersistent_BRep;
public:
//! Empty constructor.
PointRepresentation()
: myParameter(0.0)
{
}
//! Read persistent data from a file.
Standard_EXPORT virtual void Read (StdObjMgt_ReadData& theReadData);
//! Write persistent data to a file.
Standard_EXPORT virtual void Write(StdObjMgt_WriteData& theWriteData) const;
//! Gets persistent child objects
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
//! Returns persistent type name
virtual Standard_CString PName() const { return "PBRep_PointRepresentation"; }
//! Import transient object from the persistent data.
Standard_EXPORT void Import (BRep_ListOfPointRepresentation& thePoints) const;
protected:
virtual Handle(BRep_PointRepresentation) import() const;
protected:
StdObject_Location myLocation;
Standard_Real myParameter;
private:
Handle(PointRepresentation) myNext;
};
class PointOnCurve : public PointRepresentation
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_PointOnCurve"; }
virtual Handle(BRep_PointRepresentation) import() const;
private:
Handle(ShapePersistent_Geom::Curve) myCurve;
};
class PointsOnSurface : public PointRepresentation
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_PointsOnSurface"; }
protected:
Handle(ShapePersistent_Geom::Surface) mySurface;
};
class PointOnCurveOnSurface : public PointsOnSurface
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_PointOnCurveOnSurface"; }
virtual Handle(BRep_PointRepresentation) import() const;
private:
Handle(ShapePersistent_Geom2d::Curve) myPCurve;
};
class PointOnSurface : public PointsOnSurface
{
friend class ShapePersistent_BRep;
public:
PointOnSurface()
: myParameter2(0.0)
{
}
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual Standard_CString PName() const { return "PBRep_PointOnSurface"; }
virtual Handle(BRep_PointRepresentation) import() const;
private:
Standard_Real myParameter2;
};
class CurveRepresentation : public StdObjMgt_Persistent
{
friend class ShapePersistent_BRep;
public:
//! Read persistent data from a file.
Standard_EXPORT virtual void Read (StdObjMgt_ReadData& theReadData);
//! Write persistent data from a file.
Standard_EXPORT virtual void Write (StdObjMgt_WriteData& theWriteData) const;
//! Gets persistent child objects
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
//! Returns persistent type name
virtual Standard_CString PName() const { return "PBRep_CurveRepresentation"; }
//! Import transient object from the persistent data.
Standard_EXPORT void Import (BRep_ListOfCurveRepresentation& theCurves) const;
protected:
virtual Handle(BRep_CurveRepresentation) import() const;
protected:
StdObject_Location myLocation;
private:
Handle(CurveRepresentation) myNext;
};
class GCurve : public CurveRepresentation
{
friend class ShapePersistent_BRep;
public:
GCurve()
: myFirst(0.0),
myLast(0.0)
{
}
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual Standard_CString PName() const { return "PBRep_GCurve"; }
protected:
Standard_Real myFirst;
Standard_Real myLast;
};
class Curve3D : public GCurve
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_Curve3D"; }
virtual Handle(BRep_CurveRepresentation) import() const;
private:
Handle(ShapePersistent_Geom::Curve) myCurve3D;
};
class CurveOnSurface : public GCurve
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_CurveOnSurface"; }
virtual Handle(BRep_CurveRepresentation) import() const;
protected:
Handle(ShapePersistent_Geom2d::Curve) myPCurve;
Handle(ShapePersistent_Geom::Surface) mySurface;
gp_Pnt2d myUV1;
gp_Pnt2d myUV2;
};
class CurveOnClosedSurface : public CurveOnSurface
{
friend class ShapePersistent_BRep;
public:
CurveOnClosedSurface()
: myContinuity(0)
{
}
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_CurveOnClosedSurface"; }
virtual Handle(BRep_CurveRepresentation) import() const;
private:
Handle(ShapePersistent_Geom2d::Curve) myPCurve2;
Standard_Integer myContinuity;
gp_Pnt2d myUV21;
gp_Pnt2d myUV22;
};
class Polygon3D : public CurveRepresentation
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_Polygon3D"; }
virtual Handle(BRep_CurveRepresentation) import() const;
private:
Handle(ShapePersistent_Poly::Polygon3D) myPolygon3D;
};
class PolygonOnTriangulation : public CurveRepresentation
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_PolygonOnTriangulation"; }
virtual Handle(BRep_CurveRepresentation) import() const;
protected:
Handle(ShapePersistent_Poly::PolygonOnTriangulation) myPolygon;
Handle(ShapePersistent_Poly::Triangulation) myTriangulation;
};
class PolygonOnClosedTriangulation : public PolygonOnTriangulation
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_PolygonOnClosedTriangulation"; }
virtual Handle(BRep_CurveRepresentation) import() const;
private:
Handle(ShapePersistent_Poly::PolygonOnTriangulation) myPolygon2;
};
class PolygonOnSurface : public CurveRepresentation
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_PolygonOnSurface"; }
virtual Handle(BRep_CurveRepresentation) import() const;
protected:
Handle(ShapePersistent_Poly::Polygon2D) myPolygon2D;
Handle(ShapePersistent_Geom::Surface) mySurface;
};
class PolygonOnClosedSurface : public PolygonOnSurface
{
friend class ShapePersistent_BRep;
public:
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_PolygonOnClosedSurface"; }
virtual Handle(BRep_CurveRepresentation) import() const;
private:
Handle(ShapePersistent_Poly::Polygon2D) myPolygon2;
};
class CurveOn2Surfaces : public CurveRepresentation
{
friend class ShapePersistent_BRep;
public:
CurveOn2Surfaces()
: myContinuity(0)
{
}
virtual void Read (StdObjMgt_ReadData& theReadData);
virtual void Write (StdObjMgt_WriteData& theWriteData) const;
virtual void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const;
virtual Standard_CString PName() const { return "PBRep_CurveOn2Surfaces"; }
virtual Handle(BRep_CurveRepresentation) import() const;
private:
Handle(ShapePersistent_Geom::Surface) mySurface;
Handle(ShapePersistent_Geom::Surface) mySurface2;
StdObject_Location myLocation2;
Standard_Integer myContinuity;
};
private:
class pTVertex : public pTBase
{
friend class ShapePersistent_BRep;
public:
pTVertex()
: myTolerance(0.0)
{
}
inline void Read (StdObjMgt_ReadData& theReadData)
{
pTBase::Read (theReadData);
theReadData >> myTolerance >> myPnt >> myPoints;
}
inline void Write (StdObjMgt_WriteData& theWriteData) const
{
pTBase::Write (theWriteData);
theWriteData << myTolerance << myPnt << myPoints;
}
inline void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const
{
pTBase::PChildren(theChildren);
theChildren.Append(myPoints);
}
inline Standard_CString PName() const
{ return "PBRep_TVertex"; }
private:
virtual Handle(TopoDS_TShape) createTShape() const;
private:
Standard_Real myTolerance;
gp_Pnt myPnt;
Handle(PointRepresentation) myPoints;
};
class pTEdge : public pTBase
{
friend class ShapePersistent_BRep;
public:
pTEdge()
: myTolerance(0.0),
myFlags(0)
{
}
inline void Read (StdObjMgt_ReadData& theReadData)
{
pTBase::Read (theReadData);
theReadData >> myTolerance >> myFlags >> myCurves;
}
inline void Write (StdObjMgt_WriteData& theWriteData) const
{
pTBase::Write (theWriteData);
theWriteData << myTolerance << myFlags << myCurves;
}
inline void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const
{
pTBase::PChildren(theChildren);
theChildren.Append(myCurves);
}
inline Standard_CString PName() const
{ return "PBRep_TEdge"; }
private:
virtual Handle(TopoDS_TShape) createTShape() const;
private:
Standard_Real myTolerance;
Standard_Integer myFlags;
Handle(CurveRepresentation) myCurves;
};
class pTFace : public pTBase
{
friend class ShapePersistent_BRep;
public:
pTFace()
: myTolerance(0.0),
myNaturalRestriction(Standard_False)
{
}
inline void Read (StdObjMgt_ReadData& theReadData)
{
pTBase::Read (theReadData);
theReadData >> mySurface >> myTriangulation >> myLocation;
theReadData >> myTolerance >> myNaturalRestriction;
}
inline void Write (StdObjMgt_WriteData& theWriteData) const
{
pTBase::Write (theWriteData);
theWriteData << mySurface << myTriangulation << myLocation;
theWriteData << myTolerance << myNaturalRestriction;
}
inline void PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const
{
pTBase::PChildren(theChildren);
theChildren.Append(mySurface);
theChildren.Append(myTriangulation);
myLocation.PChildren(theChildren);
}
inline Standard_CString PName() const
{ return "PBRep_TFace"; }
private:
virtual Handle(TopoDS_TShape) createTShape() const;
private:
Handle(ShapePersistent_Geom::Surface) mySurface;
Handle(ShapePersistent_Poly::Triangulation) myTriangulation;
StdObject_Location myLocation;
Standard_Real myTolerance;
Standard_Boolean myNaturalRestriction;
};
public:
typedef tObject <pTVertex> TVertex;
typedef tObject <pTEdge> TEdge;
typedef tObject <pTFace> TFace;
typedef tObject1 <pTVertex> TVertex1;
typedef tObject1 <pTEdge> TEdge1;
typedef tObject1 <pTFace> TFace1;
public:
//! Create a persistent object for a vertex
Standard_EXPORT static Handle(TVertex::pTObjectT) Translate (const TopoDS_Vertex& theVertex,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for an edge
Standard_EXPORT static Handle(TEdge::pTObjectT) Translate (const TopoDS_Edge& theEdge,
StdObjMgt_TransientPersistentMap& theMap,
ShapePersistent_TriangleMode theTriangleMode);
//! Create a persistent object for a face
Standard_EXPORT static Handle(TFace::pTObjectT) Translate (const TopoDS_Face& theFace,
StdObjMgt_TransientPersistentMap& theMap,
ShapePersistent_TriangleMode theTriangleMode);
//! Create a persistent object for a point on a 3D curve
Standard_EXPORT static Handle(PointOnCurve) Translate(Standard_Real theParam,
const Handle(Geom_Curve)& theCurve,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a point on a 3D curve on a surface
Standard_EXPORT static Handle(PointOnCurveOnSurface) Translate (Standard_Real theParam,
const Handle(Geom2d_Curve)& theCurve,
const Handle(Geom_Surface)& theSurf,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a point on a surface
Standard_EXPORT static Handle(PointOnSurface) Translate (Standard_Real theParam,
Standard_Real theParam2,
const Handle(Geom_Surface)& theSurf,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a curve on a surface
Standard_EXPORT static Handle(CurveOnSurface) Translate (const Handle(Geom2d_Curve)& theCurve,
const Standard_Real theFirstParam,
const Standard_Real theLastParam,
const Handle(Geom_Surface)& theSurf,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a curve on a closed surface
Standard_EXPORT static Handle(CurveOnClosedSurface) Translate (const Handle(Geom2d_Curve)& theCurve,
const Handle(Geom2d_Curve)& theCurve2,
const Standard_Real theFirstParam,
const Standard_Real theLastParam,
const Handle(Geom_Surface)& theSurf,
const TopLoc_Location& theLoc,
const GeomAbs_Shape theContinuity,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a curve on two surfaces
Standard_EXPORT static Handle(CurveOn2Surfaces) Translate (const Handle(Geom_Surface)& theSurf,
const Handle(Geom_Surface)& theSurf2,
const TopLoc_Location& theLoc,
const TopLoc_Location& theLoc2,
const GeomAbs_Shape theContinuity,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a 3D curve
Standard_EXPORT static Handle(Curve3D) Translate (const Handle(Geom_Curve)& theCurve,
const Standard_Real theFirstParam,
const Standard_Real theLastParam,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a 3D polygon
Standard_EXPORT static Handle(Polygon3D) Translate (const Handle(Poly_Polygon3D)& thePoly,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a polygon on a closed surface
Standard_EXPORT static Handle(PolygonOnClosedSurface) Translate (const Handle(Poly_Polygon2D)& thePoly,
const Handle(Poly_Polygon2D)& thePoly2,
const Handle(Geom_Surface)& theSurf,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a polygon on a surface
Standard_EXPORT static Handle(PolygonOnSurface) Translate (const Handle(Poly_Polygon2D)& thePoly,
const Handle(Geom_Surface)& theSurf,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a polygon on a surface
Standard_EXPORT static Handle(PolygonOnClosedTriangulation) Translate (const Handle(Poly_PolygonOnTriangulation)& thePolyOnTriang,
const Handle(Poly_PolygonOnTriangulation)& thePolyOnTriang2,
const Handle(Poly_Triangulation)& thePolyTriang,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
//! Create a persistent object for a polygon on a surface
Standard_EXPORT static Handle(PolygonOnTriangulation) Translate (const Handle(Poly_PolygonOnTriangulation)& thePolyOnTriang,
const Handle(Poly_Triangulation)& thePolyTriang,
const TopLoc_Location& theLoc,
StdObjMgt_TransientPersistentMap& theMap);
};
#endif
|
// Created on: 1992-02-04
// Created by: Christian CAILLET
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Interface_UndefinedContent_HeaderFile
#define _Interface_UndefinedContent_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <Interface_HArray1OfHAsciiString.hxx>
#include <Interface_EntityList.hxx>
#include <Standard_Transient.hxx>
#include <Interface_ParamType.hxx>
class TCollection_HAsciiString;
class Interface_CopyTool;
class Interface_UndefinedContent;
DEFINE_STANDARD_HANDLE(Interface_UndefinedContent, Standard_Transient)
//! Defines resources for an "Undefined Entity" : such an Entity
//! is used to describe an Entity which complies with the Norm,
//! but of an Unknown Type : hence it is kept under a literal
//! form (avoiding to loose data). UndefinedContent offers a way
//! to store a list of Parameters, as literals or references to
//! other Entities
//!
//! Each Interface must provide one "UndefinedEntity", which must
//! have same basic description as all its types of entities :
//! the best way would be double inheritance : on the Entity Root
//! of the Norm and on an general "UndefinedEntity"
//!
//! While it is not possible to do so, the UndefinedEntity of each
//! Interface can define its own UndefinedEntity by INCLUDING
//! (in a field) this UndefinedContent
//!
//! Hence, for that UndefinedEntity, define a Constructor which
//! creates this UndefinedContent, plus access methods to it
//! (or to its data, calling methods defined here).
//!
//! Finally, the Protocols of each norm have to Create and
//! Recognize Unknown Entities of this norm
class Interface_UndefinedContent : public Standard_Transient
{
public:
//! Defines an empty UndefinedContent
Standard_EXPORT Interface_UndefinedContent();
//! Gives count of recorded parameters
Standard_EXPORT Standard_Integer NbParams() const;
//! Gives count of Literal Parameters
Standard_EXPORT Standard_Integer NbLiterals() const;
//! Returns data of a Parameter : its type, and the entity if it
//! designates en entity ("ent") or its literal value else ("str")
//! Returned value (Boolean) : True if it is an Entity, False else
Standard_EXPORT Standard_Boolean ParamData (const Standard_Integer num, Interface_ParamType& ptype, Handle(Standard_Transient)& ent, Handle(TCollection_HAsciiString)& val) const;
//! Returns the ParamType of a Param, given its rank
//! Error if num is not between 1 and NbParams
Standard_EXPORT Interface_ParamType ParamType (const Standard_Integer num) const;
//! Returns True if a Parameter is recorded as an entity
//! Error if num is not between 1 and NbParams
Standard_EXPORT Standard_Boolean IsParamEntity (const Standard_Integer num) const;
//! Returns Entity corresponding to a Param, given its rank
Standard_EXPORT Handle(Standard_Transient) ParamEntity (const Standard_Integer num) const;
//! Returns literal value of a Parameter, given its rank
Standard_EXPORT Handle(TCollection_HAsciiString) ParamValue (const Standard_Integer num) const;
//! Manages reservation for parameters (internal use)
//! (nb : total count of parameters, nblit : count of literals)
Standard_EXPORT void Reservate (const Standard_Integer nb, const Standard_Integer nblit);
//! Adds a literal Parameter to the list
Standard_EXPORT void AddLiteral (const Interface_ParamType ptype, const Handle(TCollection_HAsciiString)& val);
//! Adds a Parameter which references an Entity
Standard_EXPORT void AddEntity (const Interface_ParamType ptype, const Handle(Standard_Transient)& ent);
//! Removes a Parameter given its rank
Standard_EXPORT void RemoveParam (const Standard_Integer num);
//! Sets a new value for the Parameter <num>, to a literal value
//! (if it referenced formerly an Entity, this Entity is removed)
Standard_EXPORT void SetLiteral (const Standard_Integer num, const Interface_ParamType ptype, const Handle(TCollection_HAsciiString)& val);
//! Sets a new value for the Parameter <num>, to reference an
//! Entity. To simply change the Entity, see the variant below
Standard_EXPORT void SetEntity (const Standard_Integer num, const Interface_ParamType ptype, const Handle(Standard_Transient)& ent);
//! Changes the Entity referenced by the Parameter <num>
//! (with same ParamType)
Standard_EXPORT void SetEntity (const Standard_Integer num, const Handle(Standard_Transient)& ent);
//! Returns globally the list of param entities. Note that it can
//! be used as shared entity list for the UndefinedEntity
Standard_EXPORT Interface_EntityList EntityList() const;
//! Copies contents of undefined entities; deigned to be called by
//! GetFromAnother method from Undefined entity of each Interface
//! (the basic operation is the same regardless the norm)
Standard_EXPORT void GetFromAnother (const Handle(Interface_UndefinedContent)& other, Interface_CopyTool& TC);
DEFINE_STANDARD_RTTIEXT(Interface_UndefinedContent,Standard_Transient)
protected:
private:
Standard_Integer thenbparams;
Standard_Integer thenbstr;
Handle(TColStd_HArray1OfInteger) theparams;
Handle(Interface_HArray1OfHAsciiString) thevalues;
Interface_EntityList theentities;
};
#endif // _Interface_UndefinedContent_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** @author Yngve Pettersen
** @author Alexei Khlebnikov
**
*/
#include "core/pch.h"
#if defined _SSL_SUPPORT_ && defined _NATIVE_SSL_SUPPORT_ || defined WIC_USE_SSL_LISTENER
#include "modules/windowcommander/src/SSLSecurtityPasswordCallbackImpl.h"
#include "modules/dochand/winman.h"
#include "modules/windowcommander/src/WindowCommanderManager.h"
#include "modules/network/src/op_request_impl.h"
#include "modules/url/url_ds.h"
class ListOfMessages : public Link
{
private:
TwoWayPointer<MessageHandler> mh;
OpMessage finished_message;
MH_PARAM_1 finished_id;
public:
ListOfMessages(MessageHandler *msg_handler, OpMessage fin_message, MH_PARAM_1 fin_id):
mh(msg_handler), finished_message(fin_message), finished_id(fin_id) {};
~ListOfMessages(){if(InList()) Out();}
void PostMessage(MH_PARAM_2 par2){if(mh.get() != NULL) mh->PostMessage(finished_message,finished_id, par2);}
};
SSLSecurtityPasswordCallbackImpl::SSLSecurtityPasswordCallbackImpl(PasswordDialogMode md, PasswordRequestReason reason, Str::LocaleString titl, Str::LocaleString msg, SSL_dialog_config& conf)
: title(titl)
, message(msg)
, mode(md)
, reason(reason)
, window(conf.window)
, mh(conf.msg_handler)
, finished_message(conf.finished_message)
, finished_id(conf.finished_id)
, is_finished(FALSE)
, url(conf.url)
{
}
SSLSecurtityPasswordCallbackImpl::~SSLSecurtityPasswordCallbackImpl()
{
//TODO: connect to Windowcommander, abort dialog
new_password.Wipe();
old_password.Wipe();
}
void SSLSecurtityPasswordCallbackImpl::OnSecurityPasswordDone(BOOL ok, const char* old_passwd, const char* new_passwd)
{
if(ok)
{
if (OpStatus::IsError(old_password.Set(old_passwd)) ||
OpStatus::IsError(new_password.Set(new_passwd)))
// Simulate cancellation on OOM.
ok = FALSE;
}
FinishedDialog(ok ? IDOK : IDCANCEL);
}
OP_STATUS SSLSecurtityPasswordCallbackImpl::AddMessage(SSL_dialog_config& config)
{
ListOfMessages* item = OP_NEW(ListOfMessages, (config.msg_handler, config.finished_message, config.finished_id));
if(!item)
return OpStatus::ERR_NO_MEMORY;
item->Into(&messages_to_post);
return OpStatus::OK;
}
OP_STATUS SSLSecurtityPasswordCallbackImpl::StartDialog()
{
// fixme, use a wic if possible, otherwise fallback on windowcommanderManager
Window* win;
WindowCommander* wic = NULL;
for(win = g_windowManager->FirstWindow(); win; win = win->Suc())
{
if (win->GetOpWindow() == window)
{
wic = win->GetWindowCommander();
break;
}
}
OpRequestImpl *request = NULL;
if (url.GetRep()->GetDataStorage())
request = url.GetRep()->GetDataStorage()->GetOpRequestImpl();
if (!url.GetAttribute(URL::KUseGenericAuthenticationHandling) && request)
{
request->SecurityPasswordRequired(this);
}
else
{
if (wic)
wic->GetSSLListener()->OnSecurityPasswordNeeded(wic, this);
else
g_windowCommanderManager->GetSSLListener()->OnSecurityPasswordNeeded(NULL, this);
}
return OpStatus::OK;
}
void SSLSecurtityPasswordCallbackImpl::FinishedDialog(MH_PARAM_2 status)
{
(mh.get() != NULL ? mh.get() : g_main_message_handler)->PostMessage(finished_message, finished_id, status);
ListOfMessages* item = (ListOfMessages *) messages_to_post.First();
while(item)
{
item->PostMessage(status);
item = (ListOfMessages *) item->Suc();
}
is_finished = TRUE;
}
#endif // defined _SSL_SUPPORT_ && defined _NATIVE_SSL_SUPPORT_ || defined WIC_USE_SSL_LISTENER
|
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QPainter>
#include <QStatusBar>
#include <QLabel>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowIcon(QIcon("://app.ico"));
label = new QLabel(this);
ui->statusBar->addWidget(label);
#ifdef Q_OS_WIN
QtWin::extendFrameIntoClientArea(this, -1, -1, -1, -1);
buttonTaskBar = new QWinTaskbarButton(this);
buttonTaskBar->setWindow(windowHandle());
progressTaskBar = buttonTaskBar->progress();
progressTaskBar->setRange(0, 999);
progressTaskBar->show();
#endif
startTimer(100);
}
void MainWindow::timerEvent(QTimerEvent *)
{
static int count = 0;
QPixmap pixmap("://ellipse.png");
if(count) {
QPainter painter(&pixmap);
QFont font;
QRect rect;
rect.setRect(0, 0, pixmap.width(), pixmap.height());
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setRenderHint(QPainter::TextAntialiasing, true);
font = painter.font();
if (count < 100) {
font.setPixelSize(10);
} else {
font.setPixelSize(8);
if (count >= 1000) {
count = 999;
}
}
painter.setFont(font);
painter.setPen(Qt::white);
painter.drawText(rect, Qt::AlignCenter, QString::number(count));
#ifdef Q_OS_WIN
buttonTaskBar->setOverlayIcon(QIcon(pixmap));
#endif
label->setPixmap(pixmap);
}
else {
#ifdef Q_OS_WIN
buttonTaskBar->clearOverlayIcon();
label->setPixmap(pixmap);
#endif
}
#ifdef Q_OS_WIN
progressTaskBar->setValue(count);
#endif
count++;
}
MainWindow::~MainWindow()
{
delete ui;
}
|
/*
* ofAppAndroidWindow.h
*
* Created on: 24/05/2010
* Author: arturo
*/
#pragma once
#include "ofAppBaseWindow.h"
#include "ofEvents.h"
#include "ofConstants.h"
#include "ofTypes.h"
class ofAppAndroidWindow: public ofAppBaseGLESWindow {
public:
ofAppAndroidWindow();
virtual ~ofAppAndroidWindow();
static bool doesLoop(){ return true; }
static void loop(){ }
static bool needsPolling(){ return false; }
static void pollEvents(){}
static bool allowsMultiWindow(){ return false; }
static bool isSurfaceDestroyed();
using ofAppBaseWindow::setup;
void setup(const ofGLESWindowSettings & settings);
void update();
void draw();
void hideCursor() {}
void showCursor() {}
void setWindowPosition(int x, int y) {}
void setWindowShape(int w, int h) {}
glm::vec2 getWindowPosition() {return glm::vec2(); }
glm::vec2 getWindowSize();
glm::vec2 getScreenSize(){return getWindowSize(); }
int getWidth();
int getHeight();
bool doesHWOrientation(){return true;}
void setWindowTitle(std::string title){}
ofWindowMode getWindowMode() {return OF_WINDOW;}
void setFullscreen(bool fullscreen);
void toggleFullscreen();
void enableSetupScreen();
void disableSetupScreen();
void setOrientation(ofOrientation orientation);
ofOrientation getOrientation();
ofCoreEvents & events();
std::shared_ptr<ofBaseRenderer> & renderer();
void setThreadedEvents(bool threadedEvents);
void setAccumulateTouchEvents(bool accumEvents);
int getGlesVersion();
private:
ofCoreEvents coreEvents;
std::shared_ptr<ofBaseRenderer> currentRenderer;
int glesVersion;
};
|
#pragma once
#include <stdio.h>
#include <ctime>
#include <conio.h>
#include <windows.h>
#include "time.h"
#include <string>
#include "webClock.h"
#include <iomanip>
#include <iostream>
#include "clockMenus.h"
#include "cursorSet.h"
using namespace std;
class webClock
{
public:
int h, m, s, mh;
string tod = "";
webClock(int h, int m, int s, int mh) {
this->h = h;
this->m = m;
this->s = s;
this->mh = mh;
}
int getHours() {
return h;
}
int getMHours() {
return mh;
}
void setHours(int h) {
if (h > 23) {
this->h = 0;
}
else {
this->h = h;
}
}
void setMHours(int h) {
if (h > 12) {
mh = h - 12;
tod = "PM";
}
else if (h == 0) {
mh = 12;
tod = "AM";
}
else {
mh = h;
tod = "AM";
}
}
int getMinutes() {
return m;
}
void setMinutes(int m) {
if (m > 59) {
this->m = 0;
}
else {
this->m = m;
}
}
int getSeconds() {
return s;
}
void setSeconds(int s) {
if (s > 59) {
this->s = 0;
}
else {
this->s = s;
}
}
string getTOD() {
return tod;
}
void runClock() {
s++;
if (s > 59) {
m++;
s = 0;
if (m > 59) {
h++;
mh++;
m = 0;
}
}
}
webClock changeTime(webClock newTimer, cursorSet newCursorLoc);
};
|
#ifndef WALI_TEST_DOMAINS_KEYED_SEM_ELEM_SET_FIXTURES_HPP
#define WALI_TEST_DOMAINS_KEYED_SEM_ELEM_SET_FIXTURES_HPP
#include <string>
#include <vector>
#include "wali/domains/KeyedSemElemSet.hpp"
#include "wali/ShortestPathSemiring.hpp"
namespace {
using wali::ref_ptr;
using std::string;
using wali::sem_elem_t;
using wali::domains::PositionKey;
}
struct PKFixtures {
ref_ptr<PositionKey<int> > i_empty, i_id, i00, i01, i10, i11, i10copy;
ref_ptr<PositionKey<string> > s_empty, s_id, s00, s01, s10, s11, s10copy;
// Don't really use these, they're just to make the initialization list
// readable
typedef PositionKey<int> Pki;
typedef PositionKey<string> Pks;
PKFixtures()
: i_empty(new Pki(PositionKey<int>::makeZero()))
, i_id(new Pki(PositionKey<int>::makeOne()))
, i00(new Pki(0, 0))
, i01(new Pki(0, 1))
, i10(new Pki(1, 0))
, i11(new Pki(1, 1))
, i10copy(new Pki(*i10))
, s_empty(new Pks(PositionKey<string>::makeZero()))
, s_id(new Pks(PositionKey<string>::makeOne()))
, s00(new Pks("zero", "zero"))
, s01(new Pks("zero", "one"))
, s10(new Pks("one", "zero"))
, s11(new Pks("one", "one"))
, s10copy(new Pks(*s10))
{}
};
struct PKLists {
std::vector<sem_elem_t> ints;
std::vector<sem_elem_t> strings;
PKLists() {
PKFixtures f;
ints.push_back(f.i_empty);
ints.push_back(f.i_id);
ints.push_back(f.i00);
ints.push_back(f.i01);
ints.push_back(f.i10);
ints.push_back(f.i11);
strings.push_back(f.s_empty);
strings.push_back(f.s_id);
strings.push_back(f.s00);
strings.push_back(f.s01);
strings.push_back(f.s10);
strings.push_back(f.s11);
}
};
struct ShortestPathLengths
{
sem_elem_t ten, twenty, thirty, fourty, fifty;
ShortestPathLengths()
: ten(new wali::ShortestPathSemiring(10))
, twenty(new wali::ShortestPathSemiring(20))
, thirty(new wali::ShortestPathSemiring(30))
, fourty(new wali::ShortestPathSemiring(40))
, fifty(new wali::ShortestPathSemiring(50))
{}
};
#endif /* WALI_TEST_DOMAINS_KEYED_SEM_ELEM_SET_FIXTURES_HPP */
|
#include "bilinear_form.hpp"
#include <cmath>
#include <cstdlib>
#include <set>
#include <unordered_map>
#include "bases.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "integration.hpp"
#include "linear_operator.hpp"
int bsd_rnd() {
static unsigned int seed = 0;
int a = 1103515245;
int c = 12345;
unsigned int m = 2147483648;
return (seed = (a * seed + c) % m);
}
namespace Time {
using datastructures::TreeVector;
using ::testing::ElementsAre;
template <template <typename, typename> class Operator, typename WaveletBasisIn,
typename WaveletBasisOut>
void TestLinearity(const TreeVector<WaveletBasisIn>& vec_in,
const TreeVector<WaveletBasisOut>& vec_out) {
// Create two random vectors.
auto vec_in_1 = vec_in.DeepCopy();
auto vec_in_2 = vec_in.DeepCopy();
for (auto nv : vec_in_1.Bfs()) nv->set_random();
for (auto nv : vec_in_2.Bfs()) nv->set_random();
// Also calculate a lin. comb. of this vector
double alpha = 1.337;
auto vec_in_comb = vec_in_1.DeepCopy();
vec_in_comb *= alpha;
vec_in_comb += vec_in_2;
// Apply this weighted comb. by hand
CreateBilinearForm<Operator>(vec_in_1, vec_out).Apply();
auto vec_out_test = vec_out.DeepCopy();
vec_out_test *= alpha;
CreateBilinearForm<Operator>(vec_in_2, vec_out).Apply();
vec_out_test += vec_out;
// Do it using the lin comb.
CreateBilinearForm<Operator>(vec_in_comb, vec_out).Apply();
auto vec_out_comb = vec_out.DeepCopy();
// Now check the results!
auto nodes_comb = vec_out_comb.Bfs();
auto nodes_test = vec_out_test.Bfs();
ASSERT_GT(nodes_comb.size(), 0);
ASSERT_EQ(nodes_comb.size(), nodes_test.size());
for (int i = 0; i < nodes_comb.size(); ++i)
ASSERT_NEAR(nodes_comb[i]->value(), nodes_test[i]->value(), 1e-10);
}
template <template <typename, typename> class Operator, typename WaveletBasisIn,
typename WaveletBasisOut>
void TestUppLow(const TreeVector<WaveletBasisIn>& vec_in,
const TreeVector<WaveletBasisOut>& vec_out) {
// Checks that BilForm::Apply() == BilForm::ApplyUpp() + BilForm::ApplyLow().
for (int i = 0; i < 20; i++) {
for (auto nv : vec_in.Bfs()) nv->set_random();
CreateBilinearForm<Operator>(vec_in, vec_out).Apply();
auto vec_out_full = vec_out.DeepCopy();
CreateBilinearForm<Operator>(vec_in, vec_out).ApplyUpp();
auto vec_out_upplow = vec_out.DeepCopy();
CreateBilinearForm<Operator>(vec_in, vec_out).ApplyLow();
vec_out_upplow += vec_out;
// Now check the results!
auto nodes_full = vec_out_full.Bfs();
auto nodes_upplow = vec_out_upplow.Bfs();
ASSERT_GT(nodes_full.size(), 0);
ASSERT_EQ(nodes_full.size(), nodes_upplow.size());
for (int i = 0; i < nodes_full.size(); ++i)
ASSERT_NEAR(nodes_full[i]->value(), nodes_upplow[i]->value(), 1e-10);
}
}
template <template <typename, typename> class Operator, typename WaveletBasisIn,
typename WaveletBasisOut>
void CheckMatrixQuadrature(const TreeVector<WaveletBasisIn>& vec_in,
bool deriv_in, TreeVector<WaveletBasisOut>& vec_out,
bool deriv_out) {
TestLinearity<Operator>(vec_in, vec_out);
TestUppLow<Operator>(vec_in, vec_out);
auto bil_form = CreateBilinearForm<Operator>(vec_in, vec_out);
auto mat = bil_form.ToMatrix();
auto nodes_in = vec_in.Bfs();
auto nodes_out = vec_out.Bfs();
for (int j = 0; j < nodes_in.size(); ++j)
for (int i = 0; i < nodes_out.size(); ++i) {
auto f = nodes_in[j]->node();
auto g = nodes_out[i]->node();
auto support = f->support();
if (g->level() > f->level()) support = g->support();
double ip = 0;
for (auto elem : support)
ip += Integrate(
[f, deriv_in, g, deriv_out](const double& t) {
return f->Eval(t, deriv_in) * g->Eval(t, deriv_out);
},
*elem, /*degree*/ 2);
ASSERT_NEAR(mat(i, j), ip, 1e-10);
}
// Check that its transpose equals the matrix transpose.
auto tmat = bil_form.Transpose().ToMatrix();
ASSERT_TRUE(mat.transpose().isApprox(tmat));
}
TEST(BilinearForm, FullTest) {
// Reset the persistent trees.
Bases B;
int ml = 7;
B.three_point_tree.UniformRefine(ml);
B.ortho_tree.UniformRefine(ml);
for (size_t j = 0; j < 20; ++j) {
// Set up three-point tree.
auto three_vec_in =
TreeVector<ThreePointWaveletFn>(B.three_point_tree.meta_root());
auto three_vec_out =
TreeVector<ThreePointWaveletFn>(B.three_point_tree.meta_root());
three_vec_in.DeepRefine(
/* call_filter */ [](auto&& nv) {
return nv->level() <= 0 || bsd_rnd() % 3 != 0;
});
three_vec_out.DeepRefine(
/* call_filter */ [](auto&& nv) {
return nv->level() <= 0 || bsd_rnd() % 3 != 0;
});
ASSERT_GT(three_vec_in.Bfs().size(), 0);
ASSERT_GT(three_vec_out.Bfs().size(), 0);
// Set up orthonormal tree.
auto ortho_vec_in =
TreeVector<OrthonormalWaveletFn>(B.ortho_tree.meta_root());
auto ortho_vec_out =
TreeVector<OrthonormalWaveletFn>(B.ortho_tree.meta_root());
ortho_vec_in.DeepRefine(
/* call_filter */ [](auto&& nv) {
return nv->level() <= 0 || bsd_rnd() % 3 == 0;
});
ortho_vec_out.DeepRefine(
/* call_filter */ [](auto&& nv) {
return nv->level() <= 0 || bsd_rnd() % 3 == 0;
});
ASSERT_GT(ortho_vec_in.Bfs().size(), 0);
ASSERT_GT(ortho_vec_out.Bfs().size(), 0);
// Set up hierarhical tree.
auto hierarch_vec_in =
TreeVector<HierarchicalWaveletFn>(B.hierarch_tree.meta_root());
auto hierarch_vec_out =
TreeVector<HierarchicalWaveletFn>(B.hierarch_tree.meta_root());
hierarch_vec_in.DeepRefine(
/* call_filter */ [](auto&& nv) {
return nv->level() <= 0 || bsd_rnd() % 3 == 0;
});
hierarch_vec_out.DeepRefine(
/* call_filter */ [](auto&& nv) {
return nv->level() <= 0 || bsd_rnd() % 3 == 0;
});
ASSERT_GT(hierarch_vec_in.Bfs().size(), 0);
ASSERT_GT(hierarch_vec_out.Bfs().size(), 0);
TestLinearity<ZeroEvalOperator>(three_vec_in, three_vec_out);
TestUppLow<ZeroEvalOperator>(three_vec_in, three_vec_out);
// Test linearity and validate the result using quadrature on a matrix.
CheckMatrixQuadrature<MassOperator, ThreePointWaveletFn,
ThreePointWaveletFn>(three_vec_in, false,
three_vec_out, false);
CheckMatrixQuadrature<MassOperator, OrthonormalWaveletFn,
OrthonormalWaveletFn>(ortho_vec_in, false,
ortho_vec_out, false);
CheckMatrixQuadrature<MassOperator, OrthonormalWaveletFn,
ThreePointWaveletFn>(ortho_vec_in, false,
three_vec_out, false);
CheckMatrixQuadrature<MassOperator, ThreePointWaveletFn,
OrthonormalWaveletFn>(three_vec_in, false,
ortho_vec_out, false);
CheckMatrixQuadrature<TransportOperator, ThreePointWaveletFn,
OrthonormalWaveletFn>(three_vec_in, true,
ortho_vec_out, false);
CheckMatrixQuadrature<MassOperator, HierarchicalWaveletFn,
HierarchicalWaveletFn>(hierarch_vec_in, false,
hierarch_vec_out, false);
CheckMatrixQuadrature<MassOperator, HierarchicalWaveletFn,
OrthonormalWaveletFn>(hierarch_vec_in, false,
ortho_vec_out, false);
}
}
} // namespace Time
|
#include <iostream>
#include <string>
using namespace std;
#include "PlayingCard.h"
PlayingCard::PlayingCard() {
}
PlayingCard::PlayingCard(int value, string suit) {
this->value = value;
this->suit = suit;
}
ostream& operator<<(ostream &os, const PlayingCard &card) {
string names[] = {"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"};
string output = "(" + names[card.value - 2] + card.suit + ")";
os << output;
return os;
}
bool PlayingCard::operator==(const PlayingCard &card) {
return this->value == card.value;
}
bool PlayingCard::operator>(const PlayingCard &card) {
return this->value > card.value;
}
bool PlayingCard::operator<(const PlayingCard &card) {
return this->value < card.value;
}
|
#ifndef INC_GPENGINE_GPMATH_TRANSFORM_HPP
#define INC_GPENGINE_GPMATH_TRANSFORM_HPP
#include"Mat4.hpp"
#include"Vec4.hpp"
namespace GPEngine
{
namespace GPMath
{
Mat4 translate(const Mat4& other,const Vec4 &direction);
Mat4 scale(const Mat4& other,const Vec4 &units);
Mat4 rotate(const Mat4& other,float angleInRadians,const Vec4 & axisOfRotation);
Mat4 ortho(float left,float right,float bottom,float top,float near,float far);
Mat4 frustum(float left,float right,float bottom,float top,float near,float far);
Mat4 perspective(float fieldOfView,float aspectRatio,float near,float far);
Mat4 lookAt(const Vec4& position,const Vec4& direction,const Vec4& up);
}
}
#endif
|
#include "GetChatInfo.h"
boost::property_tree::ptree GetChatInfo::execute(std::shared_ptr<Controller> controller) {
return controller->getChatInfo(commandParams);
}
GetChatInfo::GetChatInfo(boost::property_tree::ptree ¶ms) : BaseCommand("GetSelectChatRoom") {
commandParams = params;
}
|
#include <ros/ros.h>
#include <ros/package.h>
#include <memory>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <exception>
#include <io_lib/io_utils.h>
#include <dmp_lib/DMP/DMP_pos.h>
#include <dmp_lib/GatingFunction/LinGatingFunction.h>
#include <dmp_lib/GatingFunction/ExpGatingFunction.h>
#include <dmp_lib/GatingFunction/SigmoidGatingFunction.h>
#include <kf_lib/EKF.h>
#include <math_lib/quaternions.h>
#include <dmp_kf_test/utils.h>
#include <dmp_lib/KalmanFilter/DMPpEKFa.h>
#include <plot_lib/qt_plot.h>
using namespace as64_;
double dt;
arma::vec Y0_offset;
arma::vec pg_offset;
double time_offset;
arma::mat Qn;
arma::mat Rn;
arma::mat Rn_hat;
arma::mat P0;
double a_p;
arma::mat Mr;
arma::mat Dr;
arma::mat Kr;
void loadParams()
{
ros::NodeHandle nh_("~");
if (!nh_.getParam("dt",dt)) throw std::runtime_error("Failed to load param \"dt\"...");
std::vector<double> temp;
if (!nh_.getParam("Y0_offset",temp)) throw std::runtime_error("Failed to load param \"Y0_offset\"...");
Y0_offset = arma::vec(temp);
if (!nh_.getParam("pg_offset",temp)) throw std::runtime_error("Failed to load param \"pg_offset\"...");
pg_offset = arma::vec(temp);
if (!nh_.getParam("time_offset",time_offset)) throw std::runtime_error("Failed to load param \"time_offset\"...");
if (!nh_.getParam("Qn",temp)) throw std::runtime_error("Failed to load param \"Qn\"...");
Qn = arma::diagmat(arma::vec(temp));
if (!nh_.getParam("Rn",temp)) throw std::runtime_error("Failed to load param \"Rn\"...");
Rn = arma::diagmat(arma::vec(temp));
if (!nh_.getParam("Rn_hat",temp)) throw std::runtime_error("Failed to load param \"Rn_hat\"...");
Rn_hat = arma::diagmat(arma::vec(temp));
if (!nh_.getParam("P0",temp)) throw std::runtime_error("Failed to load param \"P0\"...");
P0 = arma::diagmat(arma::vec(temp));
if (!nh_.getParam("a_p",a_p)) throw std::runtime_error("Failed to load param \"a_p\"...");
if (!nh_.getParam("Mr",temp)) throw std::runtime_error("Failed to load param \"Mr\"...");
Mr = arma::diagmat(arma::vec(temp));
if (!nh_.getParam("Dr",temp)) throw std::runtime_error("Failed to load param \"Dr\"...");
Dr = arma::diagmat(arma::vec(temp));
if (!nh_.getParam("Kr",temp)) throw std::runtime_error("Failed to load param \"Kr\"...");
Kr = arma::diagmat(arma::vec(temp));
}
int main(int argc, char** argv)
{
// =========== Initialize the ROS node ===============
ros::init(argc, argv, "DMPpEKFa_test_node");
ros::NodeHandle nh_("~");
std::string path = ros::package::getPath("dmp_kf_test");
arma::arma_rng::set_seed(0);
loadParams();
// =========== load DMP data ===============
std::string dmp_data_file = path + "/matlab/data/model/dmp_pos_data.bin";
std::ifstream in(dmp_data_file, std::ios::in | std::ios::binary);
if (!in) throw std::runtime_error("Failed to open file \"" + dmp_data_file + "\"...");
std::shared_ptr<dmp_::DMP_pos> dmp_p;
arma::vec Pg0;
arma::vec P0d;
double tau0;
dmp_p = dmp_::DMP_pos::importFromFile(in);
io_::read_mat(Pg0, in);
io_::read_mat(P0d, in);
io_::read_scalar(tau0, in);
in.close();
// ===========================================
std::shared_ptr<dmp_::CanonicalClock> can_clock_ptr = dmp_p->can_clock_ptr;
can_clock_ptr->setTau(tau0);
// DMP simulation
// set initial values
int Dim = 3;
double t = 0.0;
double x = 0.0;
double dx = 0.0;
arma::vec p0 = P0d + Y0_offset;
arma::vec p = p0;
arma::vec p_dot = arma::vec().zeros(Dim);
arma::vec p_ddot = arma::vec().zeros(Dim);
arma::vec F_ext = arma::vec().zeros(Dim);
arma::rowvec Time;
arma::mat p_data, p_dot_data, p_ddot_data;
arma::mat p_hat_data, p_dot_hat_data, p_ddot_hat_data;
arma::rowvec x_data;
arma::mat pg_data;
arma::rowvec tau_data;
arma::mat F_data;
arma::mat Sigma_theta_data;
arma::vec pg = Pg0 + pg_offset;
double t_end = tau0 + time_offset;
double tau = t_end;
can_clock_ptr->setTau(tau);
double tau_hat = tau0;
arma::vec pg_hat = Pg0;
double x_hat = t/tau_hat;
arma::vec p_hat = p;
arma::vec p_dot_hat = p_dot;
arma::vec p_ddot_hat = arma::vec().zeros(3,1);
arma::vec theta(10);
theta.subvec(0,2) = p_dot_hat;
theta.subvec(3,5) = p_hat;
theta.subvec(6,8) = pg_hat;
theta(9) = tau_hat;
arma::mat P_theta = P0;
arma::mat Sigma_vn = arma::sqrt(Rn);
int N_out = 6;
// Set up EKF object
dmp_::DMPpEKFa ekf(dmp_p, dt);
ekf.setProcessNoiseCov(Qn);
ekf.setMeasureNoiseCov(Rn_hat);
ekf.setFadingMemoryCoeff(a_p);
ekf.theta = theta;
ekf.P = P_theta;
dmp_p->setY0(p0);
arma::wall_clock ekf_timer;
arma::rowvec ekf_time;
std::cout << "DMP-EKF (discrete) Pos simulation...\n";
arma::wall_clock timer;
timer.tic();
while (true)
{
// data logging
Time = arma::join_horiz(Time, arma::vec({t}));
p_data = arma::join_horiz(p_data, p);
p_dot_data = arma::join_horiz(p_dot_data, p_dot);
p_ddot_data = arma::join_horiz(p_ddot_data, p_ddot);
p_hat_data = arma::join_horiz(p_hat_data, p_hat);
p_dot_hat_data = arma::join_horiz(p_dot_hat_data, p_dot_hat);
p_ddot_hat_data = arma::join_horiz(p_ddot_hat_data, p_ddot_hat);
pg_data = arma::join_horiz(pg_data, pg_hat);
tau_data = arma::join_horiz(tau_data, arma::vec({tau_hat}));
x_data = arma::join_horiz(x_data, arma::vec({x}));
F_data = arma::join_horiz(F_data, F_ext);
Sigma_theta_data = arma::join_horiz(Sigma_theta_data, arma::sqrt(arma:: diagvec(P_theta)));
// DMP simulation
dmp_p->setTau(tau_hat);
arma::vec p_ddot_hat = dmp_p->calcYddot(x_hat, p_hat, p_dot_hat, pg_hat);
dmp_p->setTau(tau);
p_ddot = dmp_p->calcYddot(x, p, p_dot, pg);
F_ext = Mr*(p_ddot - p_ddot_hat) + Dr*(p_dot - p_dot_hat) + Kr*(p-p_hat);
arma::vec Y_out = arma::join_vert(p_dot, p); // + Sigma_vn*arma::vec().randn(N_out);
// Y_out_hat = p_ddot_hat;
// Update phase variable
dx = can_clock_ptr->getPhaseDot(x);
// Stopping criteria
double err_p = arma::norm(pg-p)/norm(pg);
if (err_p <= 0.5e-2 & t>=t_end) break;
if (t>=t_end)
{
std::cerr << "Time limit reached. Stopping simulation...\n";
break;
}
ekf_timer.tic();
// ======== KF measurement update ========
ekf.correct(Y_out);
// ======== KF time update ========
dmp_::DMPpEKFa::StateTransCookie state_cookie(t,p0);
ekf.predict(static_cast<void *>(&state_cookie));
ekf_time = arma::join_horiz( ekf_time, arma::vec({ekf_timer.toc()}) );
theta = ekf.theta;
P_theta = ekf.P;
// Numerical integration
t = t + dt;
x = x + dx*dt;
p = p + p_dot*dt;
p_dot = p_dot + p_ddot*dt;
p_dot_hat = theta.subvec(0,2);
p_hat = theta.subvec(3,5);
pg_hat = theta.subvec(6,8);
tau_hat = theta(9);
x_hat = t/tau_hat;
}
std::cout << "Elapsed time: " << timer.toc() << " sec\n";
double ekf_mean_time = arma::mean(ekf_time) * 1000;
double ekf_std_time = arma::stddev(ekf_time) * 1000;
double ekf_max_time = arma::max(ekf_time) * 1000;
std::cerr << "ekf_mean_time = " << ekf_mean_time << " ms\n";
std::cerr << "ekf_std_time = " << ekf_std_time << " ms\n";
std::cerr << "ekf_max_time = " << ekf_max_time << " ms\n";
// =========== write results ===============
std::string sim_data_file = path + "/matlab/data/sim/sim_DMPpEKFa_results.bin";
std::ofstream out(sim_data_file, std::ios::out | std::ios::binary);
if (!out) throw std::runtime_error("Failed to create file \"" + sim_data_file + "\"...");
io_::write_mat(Time, out);
io_::write_mat(pg, out);
io_::write_mat(pg_data, out);
io_::write_scalar(tau, out);
io_::write_mat(tau_data, out);
io_::write_mat(Sigma_theta_data, out);
io_::write_mat(F_data, out);
io_::write_mat(p_data, out);
io_::write_mat(p_dot_data, out);
io_::write_mat(p_hat_data, out);
io_::write_mat(p_dot_hat_data, out);
out.close();
// =========== Shutdown ROS node ==================
ros::shutdown();
return 0;
}
|
// Created on: 1995-10-12
// Created by: Bruno DUMORTIER
// Copyright (c) 1995-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepOffset_HeaderFile
#define _BRepOffset_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BRepOffset_Status.hxx>
class Geom_Surface;
class TopoDS_Face;
//! Auxiliary tools for offset algorithms
class BRepOffset
{
public:
//! returns the Offset surface computed from the
//! surface <Surface> at an OffsetDistance <Offset>.
//!
//! If possible, this method returns the real type of
//! the surface ( e.g. An Offset of a plane is a plane).
//!
//! If no particular case is detected, the returned
//! surface will have the Type Geom_OffsetSurface.
//! Parameter allowC0 is then passed as last argument to
//! constructor of Geom_OffsetSurface.
Standard_EXPORT static Handle(Geom_Surface) Surface (const Handle(Geom_Surface)& Surface,
const Standard_Real Offset,
BRepOffset_Status& theStatus,
Standard_Boolean allowC0 = Standard_False);
//! Preprocess surface to be offset (bspline, bezier, or revolution based on
//! bspline or bezier curve), by collapsing each singular side to single point.
//!
//! This is to avoid possible flipping of normal at the singularity
//! of the surface due to non-zero distance between the poles that
//! logically should be in one point (singularity).
//!
//! The (parametric) side of the surface is considered to be singularity if face
//! has degenerated edge whose vertex encompasses (by its tolerance) all points on that side,
//! or if all poles defining that side fit into sphere with radius thePrecision.
//!
//! Returns either original surface or its modified copy (if some poles have been moved).
Standard_EXPORT static Handle(Geom_Surface) CollapseSingularities (const Handle(Geom_Surface)& theSurface,
const TopoDS_Face& theFace,
Standard_Real thePrecision);
};
#endif // _BRepOffset_HeaderFile
|
#include "myvertexwidget.h"
MyVertexWidget::MyVertexWidget(QWidget *parent) : QListWidget(parent)
{
setSortingEnabled(true);
}
void MyVertexWidget::addVertexItem(QListWidgetItem *item)
{
this->addItem(item);
}
void MyVertexWidget::sharedVertexToEdge()
{
if (selectedItems().size() == 1) {
Vertex *temp = (Vertex*) selectedItems()[0];
emit sendVertex(temp);
}
}
void MyVertexWidget::removeVertex()
{
if (selectedItems().size() == 1) {
Vertex *temp = (Vertex*) selectedItems()[0];
emit sendVertex(temp);
}
}
void MyVertexWidget::moveVertex()
{
if (selectedItems().size() == 1) {
float x = QInputDialog::getDouble(this, "X", "Enter new X Value");
float y = QInputDialog::getDouble(this, "Y", "Enter new Y Value");
float z = QInputDialog::getDouble(this, "Z", "Enter new Z Value");
Vertex *temp = (Vertex*) selectedItems()[0];
temp->assignCoordinates(glm::vec4(x, y, z, 1));
}
}
void MyVertexWidget::clearItems()
{
for (int i = 0; i < this->count(); i++) {
this->takeItem(i);
}
}
void MyVertexWidget::editText()
{
if (!selectedItems().empty()) {
QDialog dialog(this);
dialog.setWindowTitle("Rename Vertex");
QFormLayout form(&dialog);
QLineEdit *newText = new QLineEdit(this);
form.addRow("Vertex name:", newText);
QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
form.addRow(&buttonBox);
QObject::connect(&buttonBox, SIGNAL(accepted()), &dialog, SLOT(accept()));
QObject::connect(&buttonBox, SIGNAL(rejected()), &dialog, SLOT(reject()));
dialog.exec();
this->selectedItems()[0]->setText(newText->text());
}
}
void MyVertexWidget::sortItems()
{
QListWidget::sortItems(Qt::AscendingOrder);
}
|
constexpr int maxn = 262144;
constexpr int mod = 998244353;
constexpr int imgunit = 86583718; /* sqrt(-1) = sqrt(998233452) */
using i64 = long long;
using poly_t = int[maxn];
using poly = int *const;
void polytri(const poly &h, const int n, poly &sin_t, poly &cos_t) {
/* sin(f) = (exp(i * f) - exp(- i * f)) / 2i */
/* cos(f) = (exp(i * f) + exp(- i * f)) / 2 */
/* tan(f) = sin(f) / cos(f) */
assert(h[0] == 0);
static poly_t tri1_t, tri2_t;
for (int i = 0; i != n; ++i) tri2_t[i] = (i64)h[i] * imgunit % mod;
polyexp(tri2_t, n, tri1_t);
polyinv(tri1_t, n, tri2_t);
if (sin_t != nullptr) {
const int invi = fpow(pls(imgunit, imgunit), mod - 2);
for (int i = 0; i != n; ++i)
sin_t[i] = (i64)(tri1_t[i] - tri2_t[i] + mod) * invi % mod;
}
if (cos_t != nullptr) {
for (int i = 0; i != n; ++i) cos_t[i] = div2(pls(tri1_t[i], tri2_t[i]));
}
}
void polyarcsin(const poly &h, const int n, poly &f) {
/* arcsin(f) = ∫ f' / sqrt(1 - f^2) dx */
static poly_t arcsin_t;
const int t = n << 1;
std::copy(h, h + n, arcsin_t);
std::fill(arcsin_t + n, arcsin_t + t, 0);
DFT(arcsin_t, t);
for (int i = 0; i != t; ++i) arcsin_t[i] = sqr(arcsin_t[i]);
IDFT(arcsin_t, t);
arcsin_t[0] = sub(1, arcsin_t[0]);
for (int i = 1; i != n; ++i)
arcsin_t[i] = arcsin_t[i] ? mod - arcsin_t[i] : 0;
polysqrt(arcsin_t, n, f);
polyinv(f, n, arcsin_t);
derivative(h, n, f);
DFT(f, t);
DFT(arcsin_t, t);
for (int i = 0; i != t; ++i) arcsin_t[i] = (i64)f[i] * arcsin_t[i] % mod;
IDFT(arcsin_t, t);
integrate(arcsin_t, n, f);
}
void polyarccos(const poly &h, const int n, poly &f) {
/* arccos(f) = - ∫ f' / sqrt(1 - f^2) dx */
polyarcsin(h, n, f);
for (int i = 0; i != n; ++i) f[i] = f[i] ? mod - f[i] : 0;
}
void polyarctan(const poly &h, const int n, poly &f) {
/* arctan(f) = ∫ f' / (1 + f^2) dx */
static poly_t arctan_t;
const int t = n << 1;
std::copy(h, h + n, arctan_t);
std::fill(arctan_t + n, arctan_t + t, 0);
DFT(arctan_t, t);
for (int i = 0; i != t; ++i) arctan_t[i] = sqr(arctan_t[i]);
IDFT(arctan_t, t);
inc(arctan_t[0], 1);
std::fill(arctan_t + n, arctan_t + t, 0);
polyinv(arctan_t, n, f);
derivative(h, n, arctan_t);
DFT(f, t);
DFT(arctan_t, t);
for (int i = 0; i != t; ++i) arctan_t[i] = (i64)f[i] * arctan_t[i] % mod;
IDFT(arctan_t, t);
integrate(arctan_t, n, f);
}
|
// Copyright (c) 2007-2021 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <pika/config.hpp>
#include <pika/modules/errors.hpp>
#include <pika/threading_base/thread_init_data.hpp>
#include <pika/threading_base/threading_base_fwd.hpp>
namespace pika::threads::detail {
PIKA_EXPORT thread_id_ref_type create_work(
scheduler_base* scheduler, thread_init_data& data, error_code& ec = throws);
} // namespace pika::threads::detail
|
// Created on: 1994-06-03
// Created by: Christian CAILLET
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESSelect_Activator_HeaderFile
#define _IGESSelect_Activator_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_Activator.hxx>
#include <IFSelect_ReturnStatus.hxx>
#include <Standard_Integer.hxx>
class IFSelect_SessionPilot;
class IGESSelect_Activator;
DEFINE_STANDARD_HANDLE(IGESSelect_Activator, IFSelect_Activator)
//! Performs Actions specific to IGESSelect, i.e. creation of
//! IGES Selections and Dispatches, plus dumping specific to IGES
class IGESSelect_Activator : public IFSelect_Activator
{
public:
Standard_EXPORT IGESSelect_Activator();
//! Executes a Command Line for IGESSelect
Standard_EXPORT IFSelect_ReturnStatus Do (const Standard_Integer number, const Handle(IFSelect_SessionPilot)& pilot) Standard_OVERRIDE;
//! Sends a short help message for IGESSelect commands
Standard_EXPORT Standard_CString Help (const Standard_Integer number) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IGESSelect_Activator,IFSelect_Activator)
protected:
private:
};
#endif // _IGESSelect_Activator_HeaderFile
|
// SpewFilter.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
//============================================================================
// Name : SpewFilter.cpp
// Author : Tom Haley
// Version : v1.0
// Copyright :
// Description : Filter WinCE Debug Spews for Specific Types of Debug Messages
//============================================================================
#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED 1
#endif
#include <iostream>
#include "SpewFiltering.hpp"
#include <strsafe.h>
#include <windows.h>
#include <system_error>
int main(int argc, char * argv[]) {
using namespace SpewFilteringSpace;
SpewFiltering sfFiltering;
SpewFiltering::SpewFilteringParams FilterParams;
int iRetval = 1;
std::size_t Configured = sfFiltering.ConfigureFilteringParams(argc, argv, FilterParams);
if ((SUCCESS == Configured) || (HELP_SUCCESSFUL == Configured)) {
if (sfFiltering.ProduceFilteredSpewFiles(FilterParams)) {
iRetval = 0;
}
}
else if (ERROR_IN_COMMAND_LINE == Configured) {
std::cerr << "Command Line Entry Error" << std::endl;
}
else if (ERROR_UNHANDLED_EXCEPTION == Configured) {
std::cerr << "Unhandled Exception Error" << std::endl;
}
else {
std::cerr << "Unknown Error" << std::endl;
}
return iRetval;
}
|
/*
* @author: aaditkamat
* @date: 26/12/2018
*/
#include <iostream>
using namespace std;
void eighth_pattern(int num) {
string result = "";
int bound = 2 * num, ctr = 1;
for (int i = 1; i <= bound; i++) {
for (int j = 1; j <= bound; j++) {
if (j <= ctr || j > bound - ctr) {
cout << "* ";
} else {
cout << " ";
}
}
if (i < num) {
ctr++;
}
if (i > num) {
ctr--;
}
cout << "\n";
}
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
eighth_pattern(num);
return 0;
}
|
#pragma once
#include <vector>
class ProbalityHandle
{
public:
//We don't need default constructor in this case, so delete it
ProbalityHandle() = delete;
//Template for array reference at constructor
template<class _Type, unsigned int _Size>
explicit ProbalityHandle(const _Type(&_ArrayRef)[_Size]) noexcept;
//Virtual destructor, nothign special
virtual ~ProbalityHandle() = default;
//PrintInfWeight() methode defined at ProbalityHandle.cpp
void PrintInfWeigth();
private:
//Private vector<float> for Probality of each letter
std::vector<float> ProbalityOfEachLetter;
};
template<class _Type, unsigned int _Size>
ProbalityHandle::ProbalityHandle(const _Type(&_ArrayRef)[_Size]) noexcept
{
//Add each probality to vector<float>
for (auto i : _ArrayRef)
{
ProbalityOfEachLetter.push_back(i);
}
}
|
#include<stdint.h>
uint8_t val1_8bit = (uint8_t)random(32);
uint8_t val2_8bit = (uint8_t)random(32);
uint16_t val1_16bit = (uint16_t)random(65536);
uint16_t val2_16bit =(uint16_t) random(65536);
uint32_t val1_32bit = (uint32_t)random(4294996);
uint32_t val2_32bit = (uint32_t)random(4294966);
float t = 3.5431;
float u = 4.8431;
uint16_t startTime = 0;
uint16_t endTime = 0;
void setup() {
pinMode(2,OUTPUT);
digitalWrite(2,HIGH);
Serial.begin(9600);
Serial.println(val1_8bit);
Serial.println(val2_8bit);
Serial.println(val1_16bit);
Serial.println(val2_16bit);
Serial.println(val1_32bit);
Serial.println(val2_32bit);
Serial.println(t);
Serial.println(u);
//Init counter1
TCCR1A = 0; //Normal mode 0xffff top, rolls over
TCCR1B &= ~(7);
TCCR1B |= (0 << CS12) | (1 << CS10); //Clock prescaler 1024
// put your setup code here, to run once:
uint8_t result8 = findDiff_8(val1_8bit,val2_8bit);
Serial.println("result8");
Serial.println(result8);
uint16_t result16 = findDiff_16(val1_16bit,val2_16bit);
Serial.println("result16");
Serial.println(result16);
uint32_t result32 = findDiff_32(val1_32bit,val2_32bit);
Serial.println("result32");
Serial.println(result32);
float res_float = findFloatSubTime(t,u);
Serial.println(res_float);
res_float = findFloatDivTime(t,u);
Serial.println(res_float);
}
uint8_t findDiff_8(uint8_t val1, uint8_t val2){
uint8_t diff = 0;
startTime = micros();
diff = val1 / val2;
endTime = micros();
Serial.println("8 bit time");
Serial.println(endTime-startTime);
return diff;
}
uint16_t findDiff_16(uint16_t val1, uint16_t val2){
uint16_t diff = 0;
startTime = micros();
diff = val1 / val2;
endTime = micros();
Serial.println("16 bit time");
Serial.println(endTime-startTime);
return diff;
}
uint32_t findDiff_32(uint32_t val1, uint32_t val2){
uint32_t diff = 0;
startTime = micros();
diff = val1 / val2;
endTime = micros();
Serial.println("32 bit time");
Serial.println(endTime-startTime);
return diff;
}
float findFloatSubTime(float x,float y){
float z = 0;
startTime = micros();
z = x - y;
endTime = micros();
Serial.println("float sub time");
Serial.println(endTime-startTime);
return z;
}
float findFloatDivTime(float x,float y){
float z = 0;
startTime= 0;
TCNT1 = 0;
z = x / y;
endTime = TCNT1;
Serial.println("float div time");
Serial.println(endTime-startTime);
return z;
}
void loop() {
/*
// put your main code here, to run repeatedly:
uint8_t result8 = findDiff_8(val1_8bit,val2_8bit);
result8 = result8 * 78;
uint16_t result16 = findDiff_16(val1_16bit,val2_16bit);
result16 = result16 + 100;
uint32_t result32 = findDiff_32(val1_32bit,val2_32bit);
result32 = result32 + 80;
*/
}
|
//
// University of California, San Diego
// Data Structures and Algorithms: Algorithmic Toolbox
//
// Created by Dulio Denis on 2/17/16.
// Copyright (c) 2016 ddApps. Licensed under the MIT License.
// ------------------------------------------------
// Problem: Given two digits a and b, find a+b.
// Compile: g++ -pipe -O2 -std=c++11 APlusB.cpp
#include <iostream>
int main(){
int a = 0;
int b = 0;
int sum = 0;
std::cin >> a;
std::cin >> b;
sum = a + b;
std::cout << sum << "\n";
return 0;
}
|
#include <iostream>
#include <winsock2.h>
#include <WS2tcpip.h>
#include <string>
#include <sstream>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib,"wsock32.lib")
#pragma warning(disable:4996)
using namespace std;
int num_of_ex = 4;
string get_source(string _requete)
{
WSADATA WSAData; // здесь инфа о производителе библиотеки
WSAStartup(MAKEWORD(2, 0), &WSAData); // подг. к раб. библ. Winsock
SOCKET sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN sin; // адрес и порт удаленного узла с которым устанавливается соединение
string srequete = _requete; // доформировываем запрос
srequete += "Host: mydomain\r\n";
srequete += "Connection: close\r\n";
srequete += "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
srequete += "Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3\r\n";
srequete += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
srequete += "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3\r\n";
srequete += "\r\n";
if (num_of_ex == 4) srequete += "message=Hello,%20world!\r\n\r\n";
char crequete[512];
strncpy(crequete, srequete.c_str(), srequete.size() + 1); // преобр. строку в массив символов
sin.sin_addr.s_addr = inet_addr("192.168.56.101"); // задали адрес
sin.sin_family = AF_INET; // через интернет
sin.sin_port = htons(80); // задали порт HTTP
connect(sock, (SOCKADDR *)&sin, 256); // установка соединения с удаленным узлом
send(sock, crequete, strlen(crequete), 0); // отправили запрос
string out = "", source = "", Con_len = "Content-Length: ", end_ = "\r\n\r\n"; // source - ответ
char buffer[1], ret[512];
int i = 0, pos = 0, start_ = 0, start_2 = 0;
bool b = false; // признак считываемости Content-Length
do
{
i = recv(sock, buffer, sizeof(buffer), 0); // прием данных
source = source + buffer[0];
if (buffer[0] == Con_len[start_]) start_++;
else start_ = 0;
if (start_ == Con_len.length())
{
b = true;
}
if (b) // если считали Content-Length
{
if (buffer[0] == '\r') b = false; // если числа нет, то не нашли
else
{
if (buffer[0] != ':' && buffer[0] != ' ')
{
out += buffer[0]; // формируем строку сост. из размера ответа
}
}
}
if (buffer[0] == end_[start_2])
{
start_2++;
if (start_2 == end_.length()) break;
}
else start_2 = 0;
} while (true);
i = recv(sock, ret, atoi(out.c_str()), 0); // получаем ответ в найденном размере
int size = min(atoi(out.c_str()), 2000);
// добавляем сколько нужно символов из массива ret
for (int j = 0; j < size; ++j)
source += ret[j];
closesocket(sock); // закрытие соединения и уничтожение сокета
WSACleanup(); // деинициализация библиотеки и освобождение ресурсов
return source;
}
int main(){
string s = "";
switch (num_of_ex){
case 1: s = get_source("GET /4/fragment.php HTTP/1.1\r\n"); break;
case 2: s = get_source("HEAD /4/file.tar.gz HTTP/1.1\r\n"); break;
case 3: s = get_source("HEAD /4/image.png HTTP/1.1\r\n"); break;
case 4: s = get_source("POST /4/index1.php HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 23\r\n"); break; // message=Hello,%20world!\r\n
case 5: s = get_source("GET /4/file.tar.gz HTTP/1.1\r\nRange: bytes=0-99\r\n"); break;
case 6: s = get_source("HEAD /4/index1.php HTTP/1.1\r\n"); break;
}
cout << s << endl;
system("pause");
return 0;
}
|
#include <iostream>
#include <algorithm>
#define REP(i, a, n) for(int i = ((int) a); i < ((int) n); i++)
using namespace std;
template <class BI>
bool next_partial_permutation(BI first, BI middle, BI last) {
reverse(middle, last);
return next_permutation(first, last);
}
int main(void) {
int a[5];
REP(i, 0, 5) a[i] = i;
do {
REP(i, 0, 3) cout << a[i] << " ";
cout << endl;
} while(next_partial_permutation(a, a + 3, a + 5));
return 0;
}
|
#include <stack>
#include <queue>
#include <tuple>
#include <algorithm>
using grid = vector<vector<char>>;
bool dfs(grid &g, uint64_t i, uint64_t j)
{
if (g[i][j] == '0')
return false;
std::queue<std::tuple<uint64_t, uint64_t>> q{};
q.push({i, j});
while (q.size() > 0)
{
auto [i, j] = q.front();
q.pop();
if (i < 0)
continue;
if (j < 0)
continue;
if (i >= g.size())
continue;
if (j >= g[i].size())
continue;
if (g[i][j] == '0')
continue;
g[i][j] = '0';
q.push({i - 1, j + 0});
q.push({i + 0, j - 1});
q.push({i + 1, j + 0});
q.push({i + 0, j + 1});
}
return true;
}
class DisjointSet
{
std::vector<int> root;
uint64_t width;
uint64_t height;
uint64_t find_root(uint64_t idx) const
{
auto v = root[idx];
if (v == idx)
return idx;
if (v == -2)
return idx;
if (v == -1)
return idx;
else
return find_root(v);
}
public:
DisjointSet(grid &g) : root(g.size() * g[0].size(), -2),
width(g[0].size()),
height(g.size())
{
}
void set(uint64_t i, uint64_t j)
{
if (i >= width)
return;
if (j >= height)
return;
auto idx = j * width + i;
if (root[idx] == -2)
root[j * width + i] = j * width + i;
}
void unite(grid &g, uint64_t ia, uint64_t ja, uint64_t ib, uint64_t jb)
{
if (ia >= width)
return;
if (ja >= height)
return;
if (ib >= width)
return;
if (jb >= height)
return;
if (g[jb][ib] == '0')
return;
auto aroot = find_root(ja * width + ia);
auto broot = find_root(jb * width + ib);
root[aroot] = broot;
}
uint64_t count_roots() const
{
auto count = 0;
for (auto i = 0; i < root.size(); ++i)
{
if (root[i] == i)
++count;
}
return count;
}
};
class Solution
{
public:
int numIslands(vector<vector<char>> &g)
{
if (g.size() == 0)
return 0;
if (g[0].size() == 0)
return 0;
DisjointSet sets{g};
for (auto j = 0; j < g.size(); ++j)
{
auto &row = g[j];
for (auto i = 0; i < row.size(); ++i)
{
if (g[j][i] == '0')
continue;
sets.set(i, j);
sets.unite(g, i, j, i - 1, j + 0);
sets.unite(g, i, j, i + 0, j - 1);
sets.unite(g, i, j, i + 1, j + 0);
sets.unite(g, i, j, i + 0, j + 1);
}
}
return sets.count_roots();
}
};
|
#include "stdafx.h"
#include "AutoHandle.h"
#include <exception>
#include <Windows.h>
AutoHandle::AutoHandle(HANDLE h)
: m_handle(h)
{
}
AutoHandle::~AutoHandle()
{
try {
BOOL res = FALSE;
res = CloseHandle(m_handle);
if (0 == res) {
// This function fails. handling error.
DWORD err = 0;
err = GetLastError();
throw std::exception("error in CloseHandle");
}
} catch (...) {
}
}
|
/*
Copyright (c) 2015-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#ifndef _ISHIKO_TESTS_TESTS_CORE_TESTTEARDOWNACTIONSTESTS_DIRECTORIESTEARDOWNACTIONTESTS_H_
#define _ISHIKO_TESTS_TESTS_CORE_TESTTEARDOWNACTIONSTESTS_DIRECTORIESTEARDOWNACTIONTESTS_H_
#include <Ishiko/TestFramework/Core.hpp>
class DirectoriesTeardownActionTests : public Ishiko::TestSequence
{
public:
DirectoriesTeardownActionTests(const Ishiko::TestNumber& number, const Ishiko::TestContext& context);
private:
static void CreationTest1(Ishiko::Test& test);
static void TeardownTest1(Ishiko::Test& test);
};
#endif
|
#ifndef PERSON
#define PERSON
#include <string>
using std::string;
// функция возвращает переданное количество лет в правильной форме
string age_in_correct_form(const uint8_t age)
{
if ((age == 1) || ((age > 20) && ((age % 10) == 1)))
return std::to_string(age) + " год";
if ((age < 5) || ((age > 20) && ((age % 10) > 0) && ((age % 10) < 5)))
return std::to_string(age) + " года";
return std::to_string(age) + " лет";
}
// класс Личность с виртуальными функциями, требующими переопределения
class Person
{
protected:
string name_;
uint8_t age_;
public:
Person(const string& name, uint8_t age) : name_(name), age_(age)
{}
string get_name()
{
return name_;
}
uint8_t get_age()
{
return age_;
}
virtual string say_hello(Person* other_person) = 0;
virtual string tell_about_myself()
{
return ("- Меня зовут " + name_ + ", мне " + age_in_correct_form(age_));
}
virtual ~Person() {}
};
// класс Формалист, наследующий Личность
class Formalist : public Person
{
public:
Formalist (const string& name, uint8_t age): Person(name, age)
{}
virtual string say_hello(Person* other_person)
{
const string hello = "Здравствуй, "+ other_person->get_name() + "!\n";
return hello;
}
virtual string tell_about_myself()
{
const string intro = Person::tell_about_myself() + ", и я формалист.\n";
return intro;
}
};
// класс Неформал, наследующий Личность
class Informal : public Person
{
public:
Informal(const string& name, uint8_t age) : Person(name, age)
{}
virtual string say_hello(Person* other_person)
{
const string hello = "Привет, " + other_person->get_name() + "!\n";
return hello;
}
virtual string tell_about_myself()
{
const string intro = Person::tell_about_myself() + ", и я неформал.\n";
return intro;
}
};
// класс Реалист, наследующий Личность
class Realist : public Person
{
private:
// функция возвращает положительную разницу в возрасте
uint8_t difference_in_age(const uint8_t age1, const uint8_t age2)
{
if (age1 >= age2)
return (age1 - age2);
return (age2 - age1);
}
public:
Realist(const string& name, uint8_t age) : Person(name, age)
{}
virtual string say_hello(Person* other_person)
{
string hello;
if (difference_in_age(age_, other_person->get_age()) <= 5)
hello = "Привет, " + other_person->get_name() + "!\n";
else
hello = "Здравствуй, " + other_person->get_name() + "!\n";
return hello;
}
virtual string tell_about_myself()
{
const string intro = Person::tell_about_myself() + ", и я реалист.\n";
return intro;
}
};
#endif
|
#include<cstdio>
#include<algorithm>
#include<memory.h>
using namespace std;
char a[1111];
int main(){
//freopen("input.txt","r",stdin);// freopen("output.txt","w",stdout);
scanf("%s",&a);
int n = strlen(a);
reverse(a,a+n);
a[n++] = '0';
for(int i=0;i<n;++i) if(a[i]!='9'){
++a[i];
for(int j=0;j<i;++j) a[j] = '0';
break;
}
while(n&& a[n-1]=='0') --n;
a[n]=0;
reverse(a,a+n);
puts(a);
return 0;
}
|
#include<cstdio>
#include<cstring>
#include<algorithm>
#define lowbit(i) i&-i
using namespace std;
const int M = 1030;
int a[M][M];
int n;
void upd(int x,int y,int d)
{
for(int i=x;i<=n;i+=lowbit(i))
for(int j=y;j<=n;j+=lowbit(j))
a[i][j] += d;
}
int sum(int x,int y)
{
int res = 0;
for(int i=x;i>0;i-=lowbit(i))
for(int j=y;j>0;j-=lowbit(j))
res += a[i][j];
return res;
}
int main()
{
int s;
int x1,y1,x2,y2,d;
while(scanf("%d%d",&s,&n)!=EOF){
memset(a,0,sizeof(a));
while(scanf("%d",&s) && s!=3){
if(s==1){
scanf("%d%d%d",&x1,&y1,&d);
upd(++x1,++y1,d);
}else{
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
++x1,++y1,++x2,++y2;
int ans = sum(x2,y2)-sum(x1-1,y2)-sum(x2,y1-1)+sum(x1-1,y1-1);
printf("%d\n",ans);
}
}
}
return 0;
}
|
#pragma once
#include <math.h>
#include <cmath>
#define _USE_MATH_DEFINES
#include "vec2.h"
#include "vec3.h"
#include "vec4.h"
#include "mat4.h"
#define PI 3.14159265358f
namespace sge{ namespace math {
inline float toRadians(float degrees) {
return degrees * (M_PI / 180.0f);
}
inline float toDegrees(float radians) {
return (float)(radians * (180.0f / PI));
}
inline int sign(float value) {
return (value > 0) - (value < 0);
}
inline float sin(float angle) {
return ::sin(angle);
}
inline float cos(float angle) {
return ::cos(angle);
}
inline float tan(float angle) {
return ::tan(angle);
}
inline float sqrt(float value) {
return ::sqrt(value);
}
inline float rsqrt(float value) {
return 1.0f / ::sqrt(value);
}
inline float asin(float value) {
return ::asin(value);
}
inline float acos(float value) {
return ::acos(value);
}
inline float atan(float value) {
return ::atan(value);
}
inline float atan2(float y, float x) {
return ::atan2(y, x);
}
inline float _min(float value, float minimum) {
return (value < minimum) ? minimum : value;
}
inline float _max(float value, float maximum) {
return (value > maximum) ? maximum : value;
}
inline float clamp(float value, float minimum, float maximum) {
return (value > minimum) ? (value < maximum) ? value : maximum : minimum;
}
} }
|
/**
* @file Game.cpp
* @author Jan Zarsky (xzarsk03@stud.fit.vutbr.cz)
* Andrei Paplauski (xpapla00@stud.fit.vutbr.cz)
* @brief Implementation of main class Game representing the whole game
*/
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <iomanip>
#include <string>
#include <functional>
#include <time.h>
#include "Game.hpp"
namespace solitaire
{
/**
Print vector of cards to standart output (debug function)
@param st Cards vector to be printed
*/
void PrintCards(vector<card> st)
{
for (card c : st)
{
cout << setiosflags(ios::left)<< flush;
switch (c.getSuit())
{
case CLUBS:
cout<< "CLUBS" << flush;
break;
case DIAMONDS:
cout << "DIAMONDS" << flush;
break;
case HEARTS:
cout << "HEARTS" << flush;
break;
case SPADES:
cout << "SPADES" << flush;
break;
default:
cout << "UNKNOWN" << flush;
break;
}
cout << ":" << flush;
switch (c.getValue())
{
case 11:
cout << setw(3) << "J";
break;
case 12:
cout << setw(3) << "Q";
break;
case 13:
cout << setw(3) << "K";
break;
case 1:
cout << setw(3) << "A";
break;
default:
cout << setw(3) << c.getValue();
break;
}
}
cout << endl;
}
/**
Print one card to standart output (debug function)
@param c Card to be printed
*/
void PrintCards(card c)
{
cout << setiosflags(ios::left)<< flush;
switch (c.getSuit())
{
case CLUBS:
cout <<"CLUBS" << flush;
break;
case DIAMONDS:
cout <<"DIAMONDS" << flush;
break;
case HEARTS:
cout <<"HEARTS" << flush;
break;
case SPADES:
cout <<"SPADES" << flush;
break;
default:
cout <<"UNKNOWN" << flush;
break;
}
cout << ":" << flush;
switch (c.getValue())
{
case 11:
cout <<"J " << endl;
break;
case 12:
cout <<"Q " << endl;
break;
case 13:
cout <<"K " << endl;
break;
case 1:
cout <<"A " << endl;
break;
default:
cout <<c.getValue() << " "<< endl;
break;
}
}
/**
Slice vector to a vector from pos begin to end of the original one
@param base Input vector
@param begin Start position
@param end End position
@return Sliced vector
*/
template<class T>
vector<T> VecSlice(vector<T> base, int begin, int end )
{
if(base.size() == 0) {
return vector<T>{};
}
if (end < 0) {
end = base.size() + end ;
}
else if (end == 0) {
end = base.size()-1;
}
if (begin < 0) {
begin = base.size() + begin;
}
if ( begin <= end)
{
return vector<T>(base.begin() + begin, base.begin() + 1 + end);
}
else
{
return vector<T>{};
}
}
/**
Move card from STACK to vector of cards
@param pos Position in stack of all cards
@param[out] tempVector Vector to put in cards
*/
void GAME::construct_card_vector(int pos, vector<card>& tempVector)
{
tempVector.push_back(cardStack[pos]);
cardStack.erase(cardStack.begin() + pos);
};
/**
Move cards in TUI version of game
@return Success or not
*/
int GAME::MoveCard()
{
int from = -1,to = -1 , count= -1;
cout << "Choose pile: " << flush;
cin >> from;
//Control you choose from target pile or stack
if ((from < 1 || from > 7) && (from != NUM_OF_COLUMNS + NUM_OF_HOMES+1)) {
cerr << "\nWrong pile choosen" << endl;
return -1;
}
cout << "Choose amount of cards: " << flush;
cin >> count;
//Control you choose allowed amount of cards
if (static_cast<unsigned int> (count) > piles[from-1]->shownCards || count < 1) {
cerr << "\nWrong amount choosen" << endl;
return -1;
}
cout << "Choose another pile to place: " << flush;
cin >> to;
//Control you choose right pile to place cards
if (to < 1 || to > (NUM_OF_COLUMNS + NUM_OF_HOMES) || to == from) {
cerr << "\nWrong pile choosen" << endl;
return -1;
}
if (to > 7 && count > 1) {
cerr << "\nCan't place more then one card to this piles" << endl;
return -1;
}
//detection if were chosen right amount of cards
vector<card> temp_vect = VecSlice(piles[from-1]->GetPile(), -count);
if (temp_vect.size() < 1) {
cerr << "\nYou must choose pile with cards" << endl;
return -1;
}
if(piles[from - 1]->shownCards == static_cast<unsigned>(count) && static_cast<unsigned>(count) != piles[from - 1]->size) currentCmd.revealed = true;
else currentCmd.revealed = false;
if(!piles[to - 1]->AddCard(temp_vect)){
for (int i = 0; i < count; i++) {
piles[from - 1]->PopCard();
}
currentCmd.type = solitaire::move;
currentCmd.from = from;
currentCmd.to = to;
currentCmd.count = count;
return 0;
}
else{
return -1;
}
}
/**
Move cards in GUI version of game
@param cmd Structure which contains command
@return Success or not
*/
int GAME::MoveCard(solitaire::Command cmd)
{
int from = cmd.from,to = cmd.to , count= cmd.count;
//Control you choose from target pile or stack
if ((from < 1 || from > 7) && (from != NUM_OF_COLUMNS + NUM_OF_HOMES+1)) {
cerr << "\nWrong pile choosen" << endl;
return -1;
}
//Control you choose allowed amount of cards
if (static_cast<unsigned int> (count) > piles[from-1]->shownCards || count < 1) {
cerr << "\nWrong amount choosen" << endl;
return -1;
}
//Control you choose right pile to place cards
if (to < 1 || to > (NUM_OF_COLUMNS + NUM_OF_HOMES) || to == from) {
cerr << "\nWrong pile choosen" << endl;
return -1;
}
if (to > 7 && count > 1) {
cerr << "\nCan't place more then one card to this piles" << endl;
return -1;
}
//detection if were chosen right amount of cards
vector<card> temp_vect = VecSlice(piles[from-1]->GetPile(), -count);
if (temp_vect.size() < 1) {
cerr << "\nYou must choose pile with cards" << endl;
return -1;
}
//add all choosen cards from source pile to target pile
if(!piles[to - 1]->AddCard(temp_vect)){
for (int i = 0; i < count; i++) {
piles[from - 1]->PopCard();
}
return 0;
}
else{
return -1;
}
}
/**
Reversive move cards function for backsteps implementation
*/
void GAME::rev_MoveCard()
{
vector<card> vec;
vec = VecSlice(piles[currentCmd.to-1]->GetPile(),-currentCmd.count);
piles[currentCmd.from-1]->AddCard(vec,piles[currentCmd.from-1]->INSERT_ONLY);
for(int i =0;i<currentCmd.count;i++)piles[currentCmd.to-1]->PopCard();
if(currentCmd.from != NUM_OF_COLUMNS + NUM_OF_HOMES + 1){
if(currentCmd.from <= NUM_OF_COLUMNS){
piles[currentCmd.from-1]->shownCards+=currentCmd.count;
if(currentCmd.revealed)piles[currentCmd.from-1]->shownCards--;
}
else{
piles[currentCmd.from-1]->shownCards = 1;
}
}
}
/**
Rotate stack of cards
*/
void GAME::RotateStack()
{
if(piles[11]->IsEmpty()){
cerr << "ERROR: deck is empty" << endl;
return;
}
rotate(piles[11]->GetPile().begin(), piles[11]->GetPile().begin()+1, piles[11]->GetPile().end());
}
/**
Reversive rotate stack of cards for backsteps implementation
*/
void GAME::rev_RotateStack()
{
rotate(piles[11]->GetPile().begin(), piles[11]->GetPile().end()-1, piles[11]->GetPile().end());
}
/**
Run appropriate command for reversing last action in game
*/
void GAME::Backward()
{
if(!history.empty()){
currentCmd = history.back();
history.pop_back();
switch(currentCmd.type){
case solitaire::move:
rev_MoveCard();
break;
case solitaire::turn:
rev_RotateStack();
break;
default:
cerr<<"Unknown command in history\n";
}
}
else{
cerr<<"You can't do more backsteps\n";
}
}
/**
Implements help in game
@param[out] one Reference to the first returned pile
@param[out] two Reference to the second returned pile
*/
void GAME::Help(int &one, int &two) const
{
//pass through targer piles and storage
for(one =1; one<= NUM_OF_COLUMNS+NUM_OF_HOMES+1;one++){
if(one == 8){
one = 11;
continue;
}
auto spl = piles[one-1];
if(spl->IsEmpty()) continue;
card fcd = *(spl->GetPile().end() - spl->shownCards);
card lcd = *(spl->GetPile().end() - 1);
for(two = 1;two <= NUM_OF_COLUMNS+NUM_OF_HOMES;two++){
auto dpl = piles[two-1];
//trying placing to HOME pile
if(two > NUM_OF_COLUMNS && two <= NUM_OF_COLUMNS+NUM_OF_HOMES ){
if(dpl->IsEmpty()){
if(lcd.getValue() == A){
return;
}
continue;
}
else{
int Dtemp_suit = dpl->GetPile().back().getSuit();
int Dtemp_value = dpl->GetPile().back().getValue();
if( (lcd.getValue() - 1 == static_cast<unsigned>(Dtemp_value)) && (Dtemp_suit == lcd.getSuit()) ) {
return;
}
}
}
//trying placing to TARGET piles
else{
if(dpl->IsEmpty()){
if(fcd.getValue() == K && spl->shownCards != spl->size){
return;
}
continue;
}
else{
int Dtemp_suit = dpl->GetPile().back().getSuit();
int Dtemp_value = dpl->GetPile().back().getValue();
switch (fcd.getSuit()) {
case DIAMONDS:
case HEARTS:
if( (fcd.getValue() + 1 == static_cast<unsigned>(Dtemp_value)) &&(static_cast<unsigned>(Dtemp_suit) == SPADES || Dtemp_suit == CLUBS) ) {
return;
}
break;
default:
if( (fcd.getValue() + 1 == static_cast<unsigned>(Dtemp_value)) && (static_cast<unsigned>(Dtemp_suit) == DIAMONDS || Dtemp_suit == HEARTS) ) {
return;
}
}
}
}
}
}
one =12;two = 12;
}
/**
Implements saving in game
@param[out] path_to_save Path to save file
*/
void GAME::Save(string path_to_save)
{
ofstream ofile;
ofile.open(path_to_save.c_str());
if(ofile.fail()){
throw std::invalid_argument("Can't open file for writing.\n");
return;
}
for(auto pl : piles){
ofile<<pl->str()<<"\n";
}
ofile.close();
}
/**
Check if game is ended
@return 1 if its ended 0 otherwise
*/
int GAME::IsEnd(){
int win = 0;
for(auto home : homes){
if(home->size == 13) win++;
}
if(win == 4){
End = true;
return 1;
}
return 0;
}
/**
Main function which controls flow of TUI game version
*/
void GAME::Play()
{
char choose;
cout << "m-move cards n-new card x-exit b-step backward h-help"<<endl;
cout << "Choose what you want to do: "<<flush;
cin >> choose;
switch (choose)
{
case 'm':
if(MoveCard() == 0){
//add current command to history if it's move command
if(history.size() == MAX_RETURNS){
history.pop_front();
history.push_back(currentCmd);
}
else{
history.push_back(currentCmd);
}
IsEnd();
}
break;
case 'n':
currentCmd.type = solitaire::turn;
RotateStack();
//add current command to history if it's next_card command
if(history.size() == MAX_RETURNS){
history.pop_front();
history.push_back(currentCmd);
}
else{
history.push_back(currentCmd);
}
break;
case 'x':
exit(1);
break;
case 'b':
Backward();
break;
case 'h':
int from,to;
Help(from,to);
cout<<"HELP: "<<from<<"--"<<to<<endl;
break;
default:
cerr << "unknown command "<<endl;
break;
}
}
/**
Main function which controls flow of GUI game version
@param command Command structure taken from GUI
*/
void GAME::Play(solitaire::Command command)
{
if (command.type == solitaire::move) {
if(piles[command.from - 1]->shownCards == static_cast<unsigned>(command.count) && static_cast<unsigned>(command.count) != piles[command.from - 1]->size) command.revealed = true;
else command.revealed = false;
}
switch (command.type)
{
case solitaire::move:
if(MoveCard(command) == 0){
//add current command to history
if(history.size() == MAX_RETURNS){
history.pop_front();
history.push_back(command);
}
else{
history.push_back(command);
}
IsEnd();
}
break;
case solitaire::turn:
RotateStack();
//add current command to history
if(history.size() == MAX_RETURNS){
history.pop_front();
history.push_back(command);
}
else{
history.push_back(command);
}
break;
// case backward:
// Backward();
// break;
// case help:
// Help();
// break;
default:
cerr << "unknown command "<<endl;
break;
}
}
/**
Show table in TUI version of game (debug version)
*/
void GAME::ShowTable() {
for (int i = 1; i <= NUM_OF_HOMES + NUM_OF_COLUMNS + 1;i++) {
cout <<setw(3)<< i <<"[si:"<<piles[i-1]->size<<" sh:"<<piles[i-1]->shownCards<<']'<< ") " << flush;
PrintCards( VecSlice(piles[i-1]->GetPile(),-static_cast<int>(piles[i-1]->shownCards)));
}
}
}
|
#include<stdio.h>
#include<math.h>
int main()
{
int tc = 0 ;
scanf("%d",&tc);
int loop, n ;
double R,intermediateP;
double pi_times_2 = 2*acos(-1);
for(loop = 0; loop < tc ; loop++)
{
scanf("%lf %d",&R,&n);
intermediateP = sqrt(2*(1-cos(pi_times_2/n)));
printf("Case %d: %.9lf\n",loop+1,intermediateP*R/(2+intermediateP));
}
return 0;
}
|
#include "string_operations.hpp"
#include <algorithm>
#include <set>
#include <string>
#include <vector>
// trim from start (in place)
void ltrim(std::string& s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
void rtrim(std::string& s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
void trim(std::string& s) {
ltrim(s);
rtrim(s);
}
// trim from start (copying)
std::string ltrim_copy(std::string s) {
ltrim(s);
return s;
}
// trim from end (copying)
std::string rtrim_copy(std::string s) {
rtrim(s);
return s;
}
// trim from both ends (copying)
std::string trim_copy(std::string s) {
trim(s);
return s;
}
// Convert the contents of a string to lowercase.
void toLowerCase(std::string s)
{
std::for_each(s.begin(), s.end(), [](char& c) {
c = ::tolower(c);
});
}
// Convert the contents of a string to uppercase.
void toUpperCase(std::string s)
{
std::for_each(s.begin(), s.end(), [](char& c) {
c = ::toupper(c);
});
}
// Break down a full path to its components
std::vector<std::string> splitpath(const std::string& str, const std::set<char> delimiters)
{
std::vector<std::string> result;
char const* pch = str.c_str();
char const* start = pch;
for (; *pch; ++pch)
{
if (delimiters.find(*pch) != delimiters.end())
{
if (start != pch)
{
std::string str(start, pch);
result.push_back(str);
}
else
result.push_back("");
start = pch + 1;
}
}
result.push_back(start);
return result;
}
// Replace the extension of a file to use elsewhere.
void replaceExtension(std::string& str, const std::string ext)
{
size_t pos = str.find_last_of('.');
if (pos > str.length())
str.append("." + ext);
else if (pos == str.length() - 1)
str.append(ext);
else
str = str.substr(0, pos + 1) + ext;
}
|
//
// 15. 3Sum.cpp
// leetcode
//
// Created by xujian chen on 6/1/20.
// Copyright © 2020 xujian chen. All rights reserved.
//
/*
15. 3Sum
Medium
6543
785
Add to List
Share
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
Accepted
878,368
Submissions
3,353,690
*/
class Solution {
void twoSum(vector<int>& nums, int index, int target, vector<vector<int>>& rslt){
int l = index;
int r = nums.size()-1;
while(l < r){
if(nums[l]+nums[r]== target){
if (!rslt.empty()){
if (nums[l] == rslt.back()[1] && -target == rslt.back()[0]) {
++l;
--r;
continue;
}
}
rslt.push_back({-target, nums[l], nums[r]});
++l;
--r;
}
else if (nums[l]+nums[r] < target){
++l;
}
else{
--r;
}
}
}
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
vector<vector<int>> rslt;
int previous;
for(int i = 0; i < n-2; ++i){
if (nums[i] > 0) break;
if (!rslt.empty()){
if (nums[i] == rslt.back()[0]) continue;
}
twoSum(nums, i+1, -nums[i], rslt);
}
return rslt;
}
};
|
#pragma once
#include <string>
#include <vector>
#include <tuple>
#include "Environment.h"
#include "ZLibDecompressor.h"
class DebUnpacker
{
public:
DebUnpacker(Environment& env);
bool run(const std::string& inputFilePath, const std::string& outputFolderPath);
private:
Environment& env;
ZLibDecompressor zlibDecompress;
unsigned int packageFileSize;
unsigned int controlFileSize;
unsigned int dataFileSize;
bool packageFileInflate;
bool controlFileInflate;
bool dataFileInflate;
const short sectionLength = 60;
std::tuple<std::string, unsigned int, bool> checkCommonBytes(const std::vector<char>& section, const std::vector<std::string>& identifier) const;
bool checkArchiveFileSignature(std::ifstream& input) const;
bool checkSection(std::ifstream& input, unsigned int& fileSize, bool& inflate, const std::vector<std::string>& identifier, const std::string& sectionName) const;
bool extractFile(std::ifstream& input, unsigned int size, bool inflate, const std::string& outputPath);
void logStatus(bool ok, std::stringstream& ss, const std::string& error = "") const;
};
|
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <fstream>
#include <map>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
enum class State {
off_hook,
connecting,
connected,
on_hold,
on_hook
};
inline ostream& operator<<(ostream &os, State const& s) {
switch (s) {
case State::off_hook:
os << "off the hook";
break;
case State::connecting:
os << "connecting";
break;
case State::connected:
os << "connected";
break;
case State::on_hold:
os << "on hold";
break;
case State::on_hook:
os << "on hook";
break;
}
return os;
}
enum class Trigger {
call_dialed,
hung_up,
call_connected,
placed_on_hold,
taken_off_hold,
left_message,
stop_using_phone
};
inline ostream& operator<<(ostream &os, Trigger const& t) {
switch(t) {
case Trigger::call_dialed:
os << "call_dialed";
break;
case Trigger::hung_up:
os << "hung_up";
break;
case Trigger::call_connected:
os << "call_connected";
break;
case Trigger::placed_on_hold:
os << "placed_on_hold";
break;
case Trigger::taken_off_hold:
os << "taken_off_hold";
break;
case Trigger::left_message:
os << "left_message";
break;
case Trigger::stop_using_phone:
os << "stop_using_phone";
break;
}
return os;
}
int main() {
std::map<State, std::vector<std::pair<Trigger, State>>> rules;
rules[State::off_hook] = {
{Trigger::call_dialed, State::connecting},
{Trigger::stop_using_phone, State::on_hook}
};
rules[State::connecting] = {
{Trigger::hung_up, State::off_hook},
{Trigger::call_connected, State::connected}
};
rules[State::connected] = {
{Trigger::left_message, State::off_hook},
{Trigger::hung_up, State::off_hook},
{Trigger::placed_on_hold, State::on_hold}
};
rules[State::on_hold] = {
{Trigger::taken_off_hold, State::connected},
{Trigger::hung_up, State::off_hook}
};
State currentState{State::off_hook}, exitState{State::on_hook};
while(true) {
std::cout << "the phone is currently in " << currentState << "\n";
select_trigger:
std::cout << "select a trigger\n";
int i = 0;
for (auto item : rules[currentState]) {
std::cout << i++ << ". " << item.first << "\n";
}
int input;
cin >> input;
if (input < 0 or (input+1) > rules[currentState].size()) {
std::cout << "incorrect option. please try again\n";
goto select_trigger;
}
currentState = rules[currentState][input].second;
if (currentState == exitState)
break;
}
std::cout << "done using the phone" << std::endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
**
** Espen Sand
*/
#ifndef _UNIX_OPWINDOW_H_
#define _UNIX_OPWINDOW_H_
#include "modules/pi/OpWindow.h"
class UnixOpWindow : public OpWindow
{
public:
UnixOpWindow( bool is_x11 )
: m_is_x11(is_x11)
{
}
bool isX11() const { return m_is_x11; }
private:
bool m_is_x11;
};
#endif
|
#include "RPCClient.hpp"
#include "TxManager.hpp"
RPCClient::RPCClient(Configuration *_conf, RdmaSocket *_socket, MemoryManager *_mem, uint64_t _mm)
:conf(_conf), socket(_socket), mem(_mem), mm(_mm) {
isServer = true;
taskID = 1;
}
RPCClient::RPCClient() {
isServer = false;
taskID = 1;
mm = (uint64_t)malloc(sizeof(char) * (1024 * 4 + 1024 * 1024 * 4));
conf = new Configuration();
socket = new RdmaSocket(1, mm, (1024 * 4 + 1024 * 1024 * 4), conf, false, 0);
socket->RdmaConnect();
}
RPCClient::~RPCClient() {
Debug::notifyInfo("Stop RPCClient.");
if (!isServer) {
delete conf;
delete socket;
free((void *)mm);
}
Debug::notifyInfo("RPCClient is closed successfully.");
}
RdmaSocket* RPCClient::getRdmaSocketInstance() {
return socket;
}
Configuration* RPCClient::getConfInstance() {
return conf;
}
bool RPCClient::RdmaCall(uint16_t DesNodeID, char *bufferSend, uint64_t lengthSend, char *bufferReceive, uint64_t lengthReceive) {
uint32_t ID = __sync_fetch_and_add( &taskID, 1 ), temp;
uint64_t sendBuffer, receiveBuffer, remoteRecvBuffer;
uint16_t offset = 0;
uint32_t imm = (uint32_t)socket->getNodeID();
// struct timeval startt, endd;
// unsigned long diff, tempCount = 0;
GeneralSendBuffer *send = (GeneralSendBuffer*)bufferSend;
lengthReceive -= ContractSendBuffer(send);
send->taskID = ID;
send->sourceNodeID = socket->getNodeID();
send->sizeReceiveBuffer = lengthReceive;
if (isServer) {
offset = mem->getServerSendAddress(DesNodeID, &sendBuffer);
// printf("offset = %d\n", offset);
receiveBuffer = mem->getServerRecvAddress(socket->getNodeID(), offset);
remoteRecvBuffer = receiveBuffer - mm;
} else {
sendBuffer = mm;
receiveBuffer = mm;
remoteRecvBuffer = (socket->getNodeID() - conf->getServerCount() - 1) * CLIENT_MESSAGE_SIZE;
}
GeneralReceiveBuffer *recv = (GeneralReceiveBuffer*)receiveBuffer;
if (isServer)
recv->message = MESSAGE_INVALID;
memcpy((void *)sendBuffer, (void *)bufferSend, lengthSend);
_mm_clflush(recv);
asm volatile ("sfence\n" : : );
temp = (uint32_t)offset;
imm = imm + (temp << 16);
Debug::debugItem("sendBuffer = %lx, receiveBuffer = %lx, remoteRecvBuffer = %lx, ReceiveSize = %d",
sendBuffer, receiveBuffer, remoteRecvBuffer, lengthReceive);
if (send->message == MESSAGE_DISCONNECT
|| send->message == MESSAGE_UPDATEMETA
|| send->message == MESSAGE_EXTENTREADEND) {
// socket->_RdmaBatchWrite(DesNodeID, sendBuffer, remoteRecvBuffer, lengthSend, imm, 1);
// socket->PollCompletion(DesNodeID, 1, &wc);
return true;
}
// socket->RdmaWrite(DesNodeID,sendBuffer,remoteRecvBuffer,lengthSend,imm,1);
socket->_RdmaBatchWrite(DesNodeID, sendBuffer, remoteRecvBuffer, lengthSend, imm, 1);
if (isServer) {
while (recv->message == MESSAGE_INVALID || recv->message != MESSAGE_RESPONSE)
;
} else {
// gettimeofday(&startt,NULL);
while (recv->message != MESSAGE_RESPONSE) {
;
/* gettimeofday(&endd,NULL);
diff = 1000000 * (endd.tv_sec - startt.tv_sec) + endd.tv_usec - startt.tv_usec;
if (diff > 1000000) {
Debug::debugItem("Send the Fucking Message Again.");
ExtentWriteSendBuffer *tempsend = (ExtentWriteSendBuffer *)sendBuffer;
tempsend->offset = (uint64_t)tempCount;
tempCount += 1;
socket->_RdmaBatchWrite(DesNodeID, sendBuffer, remoteRecvBuffer, lengthSend, imm, 1);
gettimeofday(&startt,NULL);
diff = 0;
}*/
}
}
memcpy((void*)bufferReceive, (void *)receiveBuffer, lengthReceive);
return true;
}
uint64_t RPCClient::ContractSendBuffer(GeneralSendBuffer *send) {
uint64_t length = 0;
switch (send->message) {
case MESSAGE_MKNODWITHMETA: {
MakeNodeWithMetaSendBuffer *bufferSend =
(MakeNodeWithMetaSendBuffer *)send;
length = (MAX_FILE_EXTENT_COUNT - bufferSend->metaFile.size) * sizeof(FileMetaTuple);
length = 0;
break;
}
default: {
length = 0;
break;
}
}
// printf("contract length = %d", (int)length);
return length;
}
|
#include "fftoperation.h"
FFTOperation::FFTOperation()
{
}
void FFTOperation::run()
{
fftwf_complex *in, *out;
fftwf_plan p;
int N= 8;
int i;
int j;
in = (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex) * N);
out = (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex) * N);
for( i=0; i < N; i++)
{
in[i][0] = 1.0;
in[i][1] = 0.0;
printf("%6.2f ",in[i][0]);
}
printf("\n");
p=fftwf_plan_dft_1d(N,in,out, FFTW_FORWARD, FFTW_ESTIMATE);
fftwf_execute(p); /* repeat as needed*/
for(j = 0;j < N;j++)
{
printf("%6.2f ",out[j][0]);
}
printf("\n");
fftwf_destroy_plan(p);
fftwf_free(in);
fftwf_free(out);
sleep(5);
return ;
// fftw_complex *in,*out;
// fftw_plan p;
// int N=8;
// int i;
// int j;
// in=(fftw_complex*)fftw_malloc(sizeof(fftw_complex)*N);
// out=(fftw_complex*)fftw_malloc(sizeof(fftw_complex)*N);
// for(i=0;i<N;i++)
// {
// in[i][0]=1.0;
// in[i][1]=0.0;
// printf("%6.2f ",in[i][0]);
// }
// printf("\n");
// p=fftw_plan_dft_1d(N,in,out,FFTW_FORWARD,FFTW_ESTIMATE);
// fftw_execute(p);
// for(j=0;j<N;j++)
// {
// printf("%6.2f ",out[j][0]);
// }
// printf("\n");
// fftw_destroy_plan(p);
// fftw_free(in);
// fftw_free(out);
// sleep(5);
// return ;
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow){
ui->setupUi(this);
initializeOcr();
createMenuBar();
this->ui->takePhotoButton->setHidden(true);
connect(newFileAction, &QAction::triggered, this, &MainWindow::openFileAction);
connect(newPhotoAction, &QAction::triggered, this, &MainWindow::openCameraAction);
photoPath = "/Users/budakf/Qt_Projects/ImageToText/image.jpg";
}
void MainWindow::openFileAction(){
fileName = QFileDialog::getOpenFileName(this, "Open File",
"/Users/budakf/Desktop", "Images (*.png *.jpg)" );
std::cout<<"Open File Action "<<fileName.toStdString()<<std::endl;
this->setImage(fileName);
this->ui->readTextButton->setEnabled(true);
}
void MainWindow::openCameraAction(){
std::cout<<"Open Photo Action"<<std::endl;
if(!camera) camera = new QCamera{this};
connect(camera, QOverload<QCamera::Error>::of(&QCamera::error),
[](QCamera::Error value){
std::cout<<"QCamera::Error::Value: "<<value;
});
camera->setCaptureMode(QCamera::CaptureStillImage);
camera->start();
imageCapture = new QCameraImageCapture(camera, this);
connect(imageCapture, QOverload<int, QCameraImageCapture::Error, const QString &>::of(&QCameraImageCapture::error),
[=](int id, QCameraImageCapture::Error error, const QString &errorString){
qDebug()<<errorString;
});
connect(camera, &QCamera::statusChanged, [this](QCamera::Status status){
if(status == QCamera::Status::ActiveStatus){
this->ui->takePhotoButton->setVisible(true);
}
});
connect(imageCapture, &QCameraImageCapture::imageSaved, [&](int id, const QString & file){
qDebug()<<id << " "<<file;
camera->stop();
fileName = ""; //
this->setImage(file);
});
}
void MainWindow::on_readTextButton_clicked(){
cv::Mat image = cv::imread( fileName.isEmpty() ? photoPath.toStdString() : fileName.toStdString() );
//ocr->SetImage(image.data, image.cols, image.rows, 3, (size_t) image.step);
//this->ui->textBrowser->setText(QString(ocr->GetUTF8Text()));
this->ui->translateTextButton->setEnabled(true);
}
void MainWindow::on_translateTextButton_clicked(){
networkAccessManager = new QNetworkAccessManager{this};
connect(networkAccessManager, &QNetworkAccessManager::finished, this, &MainWindow::onResultOfTranslation);
QUrlQuery query;
query.addQueryItem("key", "trnsl.1.1.20190416T190417Z.02410a818d6cab2d.2ab97f8a6f23c3b45d7459d0dfc448d4f38f75a2");
query.addQueryItem("lang", "en-tr");
query.addQueryItem("text", this->ui->textBrowser->toPlainText());
QUrl url("https://translate.yandex.net/api/v1.5/tr.json/translate");
//QUrl url("https://translate.yandex.net/api/v1.5/tr.json/detect");
url.setQuery(query);
qDebug()<< "url: "<< url.toString(QUrl::FullyEncoded);
//QNetworkReply * reply = networkAccessManager->get( QNetworkRequest{url} );
networkAccessManager->get( QNetworkRequest{url} );
}
void MainWindow::onResultOfTranslation(QNetworkReply *reply){
if(reply->error() == QNetworkReply::NoError){
QByteArray result = reply->readAll();
QJsonDocument jsonResponse = QJsonDocument::fromJson(result);
QJsonObject obj = jsonResponse.object();
qDebug()<<"code: " << obj["code"].toInt();
qDebug()<<"lang: " << obj["lang"].toString();
QJsonArray array = obj["text"].toArray();
QString resultText{""};
for(const QJsonValue value : array) {
qDebug()<< "text: " <<value.toString();
resultText += value.toString();
}
this->ui->textBrowser->setText(resultText);
}
else
qDebug() << "ERROR";
reply->deleteLater();
}
void MainWindow::on_takePhotoButton_clicked(){
imageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
camera->searchAndLock();
imageCapture->capture(photoPath);
camera->unlock();
this->ui->takePhotoButton->setHidden(true);
this->ui->readTextButton->setEnabled(true);
}
void MainWindow::setImage(QString imageName){
if(scene)
delete scene;
if(pixmap)
delete pixmap;
scene = new QGraphicsScene(this);
pixmap = new QPixmap(imageName);
scene->addPixmap(*pixmap);
ui->graphicsView->setScene(scene);
ui->graphicsView->show();
}
void MainWindow::createMenuBar(){
menuBar = new QMenuBar(this);
menuBar->setNativeMenuBar(false); // just for Macos
fileMenu = new QMenu("File");
newFileAction = new QAction("New Image", fileMenu);
newPhotoAction = new QAction("Open Camera", fileMenu);
fileMenu->addAction(newFileAction);
fileMenu->addAction(newPhotoAction);
menuBar->addMenu(fileMenu);
}
void MainWindow::initializeOcr(){
ocr = new tesseract::TessBaseAPI();
ocr->Init(nullptr, "eng", tesseract::OEM_LSTM_ONLY); //OEM_TESSERACT_CUBE_COMBINED
ocr->SetPageSegMode(tesseract::PSM_AUTO);
}
MainWindow::~MainWindow(){
if(scene) delete scene;
if(pixmap) delete pixmap;
if(ocr) delete ocr;
delete ui;
}
|
/*
* Context.cpp
*
* Created on: Jun 11, 2017
* Author: root
*/
#include "Context.h"
#include "AcceptManager.h"
#include "Service_Handler.h"
#include "EpollMain.h"
#include "DispatchMessage.h"
#include "ConnManager.h"
#include "Session.h"
#include "../util.h"
#include "GroupSession.h"
#include "MessageManager.h"
#include "NetWorkConfig.h"
namespace CommBaseOut
{
Context::Context():m_accMgr(0),m_connMgr(0), m_epoll(0),//m_messageRecv(0),
m_connHandler(0),m_handlerMgr(0),m_blockThread(1),m_ioThread(1)
{
m_accMgr = NEW CAcceptorMgr(this);
m_connMgr = NEW CConnMgr(this);
m_epoll = NEW CEpollMain(this);
m_dispatchMgr = NEW DispatchMgr(this);
m_handlerMgr = NEW HandlerManager(this);
m_groupSession = NEW GroupSession(this);
}
Context::~Context()
{
m_connAdded.clear();
m_acceptAdded.clear();
if(m_accMgr)
{
delete m_accMgr;
m_accMgr = 0;
}
if(m_connMgr)
{
m_connMgr->End();
delete m_connMgr;
m_connMgr = 0;
}
if(m_epoll)
{
delete m_epoll;
m_epoll = 0;
}
if(m_dispatchMgr)
{
delete m_dispatchMgr;
m_dispatchMgr = 0;
}
if(m_handlerMgr)
{
delete m_handlerMgr;
m_handlerMgr = 0;
}
if(m_groupSession)
{
delete m_groupSession;
m_groupSession = 0;
}
}
int Context::Init(Message_Service_Handler *mh, int blockThread, int ioThread)
{
m_blockThread = blockThread;
if(m_blockThread <= 0)
m_blockThread = 1;
m_ioThread = ioThread;
m_connHandler = mh;
return eNetSuccess;
}
void Context::AddAcceptor(AcceptorConfig &conf)
{
m_acceptAdded.push_back(conf);
}
void Context::AddConnector(ConnectionConfig &conf)
{
m_connAdded.push_back(conf);
}
int Context::Start()
{
int i=0;
int res = -1;
m_dispatchMgr->Init(m_blockThread);
for(i=0; i<m_ioThread; ++i)
{
if((res=m_epoll->AddEpollLoop(i)) != eNetSuccess)
{
return res;
}
}
vector<AcceptorConfig>::iterator itAcc = m_acceptAdded.begin();
for(; itAcc!=m_acceptAdded.end(); ++itAcc)
{
if((res=m_accMgr->AddAccept(*itAcc)) != eNetSuccess)
{
return res;
}
}
if((res=m_connMgr->Init()) != eNetSuccess)
{
return res;
}
if(m_connAdded.size() > 0)
{
if((res=m_connMgr->Start(1)) != eNetSuccess)
{
return res;
}
}
return eNetSuccess;
}
int Context::Stop()
{
m_connMgr->Close();
m_accMgr->DeleteAll();
m_epoll->DeleteAll();
m_dispatchMgr->DeleteAll();
return eNetSuccess;
}
void Context::SystemErr(int fd, int lid, int ltype, int rid, int rtype, int err, string ip, int port)
{
int id = -1;
switch(err)
{
case eConnErr:
case eAddSeTimeoutErr:
case eGetSocketErr:
case eSetSocketErr:
case eCtlEpollErr:
case eSessionAdded:
case eNotTimeOut:
{
id = eConnFailMessage;
break;
}
case eEpollClose:
case eEpollNull:
case eConMessageErr:
case eConnPacketErr:
case eSessionTimeout:
case eSocketClose:
{
id = eConnErrMessage;
break;
}
case eNetSuccess:
{
id = eConnBuildSuccess;
break;
}
}
Safe_Smart_Ptr<Message> message = NEW Message();
char con[128] = {0};
SystemMessageCon content;
bzero(&content, sizeof(content));
content.channel = fd;
content.lid = lid;
content.ltype = ltype;
content.rid = rid;
content.rtype = rtype;
content.err = err;
CUtil::SafeMemmove(content.ip, 16, ip.c_str(), ip.size());
content.port = port;
CUtil::SafeMemmove(con, 128, &content, sizeof(content));
message->SetMessageID(id);
message->SetContent(con, sizeof(content));
message->SetMessageType(SystemMessage);
// CEpollLoop * loop = m_epoll->GetEpollLoop(0);
// if(loop == 0)
// return;
//
// loop->GetDispatch()->AddMessage(message);
m_dispatchMgr->GetDispatch(fd)->AddMessage(message);
}
}
|
//
// Created by Lee on 2019-04-23.
//
#ifndef UBP_CLIENT_CPP_VER_VIEWERVIEW_H
#define UBP_CLIENT_CPP_VER_VIEWERVIEW_H
#include "PhotoViewer.h"
#include <QWidget>
#include <QPushButton>
#include "Photo.h"
#include "PhotoManager.h"
class ViewerView : public QWidget {
Q_OBJECT
public:
explicit ViewerView(QWidget * parent = nullptr,
std::vector<Photo> *photoList = nullptr,
PhotoManager * photoManager = nullptr);
void updatePhotoList(std::vector<Photo> *photoList);
private slots:
void handlePrevButton();
void handleNextButton();
void handleHomeButton();
void handleModifyButton();
void handleDeleteButton();
private:
int now = 0;
Photo nowPhoto;
std::vector<Photo> * photoList;
QPushButton * prevButton;
QPushButton * nextButton;
QPushButton * homeButton;
QPushButton * modifyButton;
QPushButton * deleteButton;
PhotoViewer * photoViewer;
PhotoManager * photoManager;
};
#endif //UBP_CLIENT_CPP_VER_VIEWERVIEW_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domglobaldata.h"
#include "modules/dom/src/domcore/implem.h"
#include "modules/dom/src/domcore/domxmldocument.h"
#include "modules/dom/src/domhtml/htmldoc.h"
#include "modules/dom/src/domload/lsinput.h"
#include "modules/dom/src/domload/lsparser.h"
#include "modules/dom/src/domsave/lsserializer.h"
#include "modules/dom/src/domsave/lsoutput.h"
#include "modules/dom/src/opera/domhttp.h"
#ifdef SVG_DOM
# include "modules/svg/svg_dominterfaces.h"
#endif // SVG_DOM
#include "modules/logdoc/htm_elm.h"
#include "modules/xmlutils/xmlutils.h"
/* static */ void
DOM_DOMImplementation::ConstructDOMImplementationL(ES_Object *object, DOM_Runtime *runtime)
{
AddFunctionL(object, runtime, accessFeature, 0, "hasFeature", "sS-");
AddFunctionL(object, runtime, createDocument, "createDocument", "SZ-");
AddFunctionL(object, runtime, createDocumentType, "createDocumentType", "zzs-");
AddFunctionL(object, runtime, accessFeature, 1, "getFeature", "s-");
#ifdef DOM3_LOAD
AddFunctionL(object, runtime, createLSParser, "createLSParser", "ns-");
AddFunctionL(object, runtime, createLSInput, "createLSInput");
PutNumericConstantL(object, "MODE_SYNCHRONOUS", DOM_LSParser::MODE_SYNCHRONOUS, runtime);
PutNumericConstantL(object, "MODE_ASYNCHRONOUS", DOM_LSParser::MODE_ASYNCHRONOUS, runtime);
#endif // DOM3_LOAD
#ifdef DOM3_SAVE
AddFunctionL(object, runtime, createLSSerializer, "createLSSerializer");
AddFunctionL(object, runtime, createLSOutput, "createLSOutput");
#endif // DOM3_SAVE
#ifdef DOM_HTTP_SUPPORT
AddFunctionL(object, runtime, createHTTPRequest, "createHTTPRequest", "ss-");
#endif // DOM_HTTP_SUPPORT
}
/* static */ OP_STATUS
DOM_DOMImplementation::Make(DOM_DOMImplementation *&implementation, DOM_EnvironmentImpl *environment)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
RETURN_IF_ERROR(DOM_Object::DOMSetObjectRuntime(implementation = OP_NEW(DOM_DOMImplementation, ()), runtime, runtime->GetObjectPrototype(), "DOMImplementation"));
return ConstructDOMImplementation(*implementation, runtime);
}
#ifdef DOM_NO_COMPLEX_GLOBALS
# define DOM_FEATURES_START() void DOM_featureList_Init(DOM_GlobalData *global_data) { DOM_FeatureInfo *featureList = global_data->featureList;
# define DOM_FEATURES_ITEM(name_, version_) featureList->name = name_; featureList->version = version_; ++featureList;
# define DOM_FEATURES_END() featureList->name = NULL; }
#else // DOM_NO_COMPLEX_GLOBALS
# define DOM_FEATURES_START() const DOM_FeatureInfo g_DOM_featureList[] = {
# define DOM_FEATURES_ITEM(name_, version_) { name_, version_ },
# define DOM_FEATURES_END() { NULL, DOM_FeatureInfo::VERSION_NONE } };
#endif // DOM_NO_COMPLEX_GLOBALS
/* Remember to update selftest/core/domimplementation.ot and the affected
tests in testsuite/DOM-regression (run them and modify those that fail
in expected ways) when you change anything in this table. */
// This list must be synced with the list named DOM_FeatureInfo in implem.h
DOM_FEATURES_START()
DOM_FEATURES_ITEM("CORE", DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("XML", DOM_FeatureInfo::VERSION_1_0 | DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("HTML", DOM_FeatureInfo::VERSION_1_0 | DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("XHTML", DOM_FeatureInfo::VERSION_1_0 | DOM_FeatureInfo::VERSION_2_0)
#ifdef DOM3_EVENTS
DOM_FEATURES_ITEM("EVENTS", DOM_FeatureInfo::VERSION_2_0 | DOM_FeatureInfo::VERSION_3_0)
DOM_FEATURES_ITEM("UIEVENTS", DOM_FeatureInfo::VERSION_2_0 | DOM_FeatureInfo::VERSION_3_0)
DOM_FEATURES_ITEM("MOUSEEVENTS", DOM_FeatureInfo::VERSION_2_0 | DOM_FeatureInfo::VERSION_3_0)
#ifdef DOM2_MUTATION_EVENTS
DOM_FEATURES_ITEM("MUTATIONEVENTS", DOM_FeatureInfo::VERSION_2_0 | DOM_FeatureInfo::VERSION_3_0)
#endif // DOM2_MUTATION_EVENTS
DOM_FEATURES_ITEM("HTMLEVENTS", DOM_FeatureInfo::VERSION_2_0 | DOM_FeatureInfo::VERSION_3_0)
#else // DOM3_EVENTS
DOM_FEATURES_ITEM("EVENTS", DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("UIEVENTS", DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("MOUSEEVENTS", DOM_FeatureInfo::VERSION_2_0)
#ifdef DOM2_MUTATION_EVENTS
DOM_FEATURES_ITEM("MUTATIONEVENTS", DOM_FeatureInfo::VERSION_2_0)
#endif // DOM2_MUTATION_EVENTS
DOM_FEATURES_ITEM("HTMLEVENTS", DOM_FeatureInfo::VERSION_2_0)
#endif // DOM3_EVENTS
DOM_FEATURES_ITEM("VIEWS", DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("STYLESHEETS", DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("CSS", DOM_FeatureInfo::VERSION_2_0)
DOM_FEATURES_ITEM("CSS2", DOM_FeatureInfo::VERSION_2_0)
#ifdef DOM2_RANGE
DOM_FEATURES_ITEM("RANGE", DOM_FeatureInfo::VERSION_2_0)
#endif // DOM2_RANGE
#ifdef DOM2_TRAVERSAL
DOM_FEATURES_ITEM("TRAVERSAL", DOM_FeatureInfo::VERSION_2_0)
#endif // DOM2_TRAVERSAL
#if defined DOM3_LOAD || defined DOM3_SAVE
DOM_FEATURES_ITEM("LS", DOM_FeatureInfo::VERSION_3_0)
DOM_FEATURES_ITEM("LS-ASYNC", DOM_FeatureInfo::VERSION_3_0)
#endif // DOM3_LOAD || DOM3_SAVE
#ifdef DOM3_XPATH
DOM_FEATURES_ITEM("XPATH", DOM_FeatureInfo::VERSION_3_0)
#endif // DOM3_XPATH
#ifdef DOM_SELECTORS_API
DOM_FEATURES_ITEM("SELECTORS-API", DOM_FeatureInfo::VERSION_1_0)
#endif // DOM_SELECTORS_API
DOM_FEATURES_END()
/* static */ int
DOM_DOMImplementation::accessFeature(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
/* NOTE: this_object is NULL when called as Node.isSupported or Node.getFeature. */
if (this_object)
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_DOMIMPLEMENTATION);
DOM_CHECK_ARGUMENTS("sS");
const uni_char *name = argv[0].value.string;
unsigned version = DOM_FeatureInfo::VERSION_ANY;
BOOL supported = FALSE;
#ifdef SVG_DOM
BOOL found = FALSE;
#endif
if (name[0] == '+')
++name;
if (argv[1].type == VALUE_STRING)
{
const uni_char *version_string = argv[1].value.string;
if (*version_string)
if (uni_str_eq(version_string, "1.0"))
version = DOM_FeatureInfo::VERSION_1_0;
else if (uni_str_eq(version_string, "2.0"))
version = DOM_FeatureInfo::VERSION_2_0;
else if (uni_str_eq(version_string, "3.0"))
version = DOM_FeatureInfo::VERSION_3_0;
else
version = DOM_FeatureInfo::VERSION_NONE;
}
const DOM_FeatureInfo *features = g_DOM_featureList;
if (version != DOM_FeatureInfo::VERSION_NONE)
for (int index = 0; features[index].name; ++index)
if (uni_stri_eq(name, features[index].name))
{
#ifdef SVG_DOM
found = TRUE;
#endif
if ((features[index].version & version) != 0)
supported = TRUE;
break;
}
#ifdef SVG_DOM
if(!found)
{
const uni_char *version_string = NULL;
if (argv[1].type == VALUE_STRING)
version_string = argv[1].value.string;
SVGDOM::HasFeature(name, version_string, supported);
}
#endif // SVG_DOM
if (data == 0)
DOMSetBoolean(return_value, supported);
else
{
/* this_object==NULL if called from DOM_Node::isSupported, but it calls
with data==0, so we should never have no this object here. */
OP_ASSERT(this_object);
DOMSetObject(return_value, supported ? this_object : NULL);
}
return ES_VALUE;
}
/* static */ int
DOM_DOMImplementation::createDocument(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(implementation, DOM_TYPE_DOMIMPLEMENTATION, DOM_DOMImplementation);
DOM_CHECK_ARGUMENTS("SZO");
DOM_ARGUMENT_OBJECT(doctype, 2, DOM_TYPE_DOCUMENTTYPE, DOM_DocumentType);
DOM_Document *document;
BOOL is_html = FALSE;
TempBuffer qname_buffer;
qname_buffer.SetCachedLengthPolicy(TempBuffer::UNTRUSTED);
const uni_char *qname = NULL;
if (argv[1].type == VALUE_STRING_WITH_LENGTH)
{
qname = argv[1].value.string_with_length->string;
if (uni_strlen(qname) != argv[1].value.string_with_length->length)
/* Embedded null characters: not a valid character in element names: */
return implementation->CallDOMException(INVALID_CHARACTER_ERR, return_value);
}
if (qname && argv[0].type == VALUE_STRING && uni_str_eq(argv[0].value.string, "http://www.w3.org/1999/xhtml") && uni_str_eq(qname, "html"))
is_html = TRUE;
if (is_html)
{
DOM_HTMLDocument *htmldocument;
CALL_FAILED_IF_ERROR(DOM_HTMLDocument::Make(htmldocument, implementation, TRUE, TRUE));
document = htmldocument;
}
else
CALL_FAILED_IF_ERROR(DOM_XMLDocument::Make(document, implementation, TRUE));
if (doctype)
{
if (doctype->GetThisElement()->Parent())
return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR);
if (doctype->GetRuntime() != document->GetRuntime())
doctype->DOMChangeRuntime(document->GetRuntime());
doctype->DOMChangeOwnerDocument(document);
ES_Value arguments[2];
DOMSetObject(&arguments[0], doctype);
DOMSetNull(&arguments[1]);
int result = DOM_Node::insertBefore(document, arguments, 2, return_value, origining_runtime);
/* There couldn't possibly be any Mutation Events handlers involved here. */
OP_ASSERT(result != (ES_SUSPEND | ES_RESTART));
if (result != ES_VALUE)
return result;
}
if (qname && *qname)
{
int result = DOM_Document::createNode(document, argv, 2, return_value, origining_runtime, 1);
if (result != ES_VALUE)
return result;
ES_Value arguments[2];
arguments[0] = *return_value;
DOMSetNull(&arguments[1]);
result = DOM_Node::insertBefore(document, arguments, 2, return_value, origining_runtime);
/* There couldn't possibly be any Mutation Events handlers involved here. */
OP_ASSERT(result != (ES_SUSPEND | ES_RESTART));
if (result != ES_VALUE)
return result;
}
DOMSetObject(return_value, document);
return ES_VALUE;
}
/* static */ int
DOM_DOMImplementation::createDocumentType(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(implementation, DOM_TYPE_DOMIMPLEMENTATION, DOM_DOMImplementation);
DOM_CHECK_ARGUMENTS("zzs");
const uni_char *qualifiedName = argv[0].value.string_with_length->string;
if (uni_strlen(qualifiedName) != argv[0].value.string_with_length->length)
/* Embedded null characters: not a valid character in element names: */
return implementation->CallDOMException(INVALID_CHARACTER_ERR, return_value);
const uni_char *publicId = argv[1].value.string_with_length->string;
if (uni_strlen(publicId) != argv[1].value.string_with_length->length)
/* Embedded null characters: not a valid character in a public ID literal: */
return implementation->CallDOMException(INVALID_CHARACTER_ERR, return_value);
const uni_char *systemId = argv[2].value.string;
if (*qualifiedName && !XMLUtils::IsValidName(XMLVERSION_1_0, qualifiedName))
return DOM_CALL_DOMEXCEPTION(INVALID_CHARACTER_ERR);
else if (!XMLUtils::IsValidQName (XMLVERSION_1_0, qualifiedName))
return DOM_CALL_DOMEXCEPTION(NAMESPACE_ERR);
DOM_DocumentType *doctype;
CALL_FAILED_IF_ERROR(DOM_DocumentType::Make(doctype, implementation->GetEnvironment(), qualifiedName, publicId, systemId));
doctype->SetIsSignificant();
DOMSetObject(return_value, doctype);
return ES_VALUE;
}
#ifdef DOM3_LOAD
/* static */ int
DOM_DOMImplementation::createLSParser(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(implementation, DOM_TYPE_DOMIMPLEMENTATION, DOM_DOMImplementation);
DOM_CHECK_ARGUMENTS("ns");
DOM_LSParser *parser;
CALL_FAILED_IF_ERROR(DOM_LSParser::Make(parser, implementation->GetEnvironment(), argv[0].value.number == DOM_LSParser::MODE_ASYNCHRONOUS));
DOMSetObject(return_value, parser);
return ES_VALUE;
}
/* static */ int
DOM_DOMImplementation::createLSInput(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(implementation, DOM_TYPE_DOMIMPLEMENTATION, DOM_DOMImplementation);
ES_Object *input;
CALL_FAILED_IF_ERROR(DOM_LSInput::Make(input, implementation->GetEnvironment()));
DOMSetObject(return_value, input);
return ES_VALUE;
}
#endif // DOM3_LOAD
#ifdef DOM3_SAVE
/* static */ int
DOM_DOMImplementation::createLSSerializer(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(implementation, DOM_TYPE_DOMIMPLEMENTATION, DOM_DOMImplementation);
DOM_LSSerializer *serializer;
CALL_FAILED_IF_ERROR(DOM_LSSerializer::Make(serializer, implementation->GetEnvironment()));
DOMSetObject(return_value, serializer);
return ES_VALUE;
}
/* static */ int
DOM_DOMImplementation::createLSOutput(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(implementation, DOM_TYPE_DOMIMPLEMENTATION, DOM_DOMImplementation);
ES_Object *output;
CALL_FAILED_IF_ERROR(DOM_LSOutput::Make(output, implementation->GetEnvironment()));
DOMSetObject(return_value, output);
return ES_VALUE;
}
#endif // DOM3_SAVE
#ifdef DOM_HTTP_SUPPORT
/* static */ int
DOM_DOMImplementation::createHTTPRequest(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(implementation, DOM_TYPE_DOMIMPLEMENTATION, DOM_DOMImplementation);
DOM_CHECK_ARGUMENTS("ss");
DOM_HTTPRequest *request;
CALL_FAILED_IF_ERROR(DOM_HTTPRequest::Make(request, implementation->GetEnvironment(), argv[0].value.string, argv[1].value.string));
DOMSetObject(return_value, request);
return ES_VALUE;
}
#endif // DOM_HTTP_SUPPORT
|
#include <conio.h>
#include <stdio.h>
void sort(int *A){
int b;
printf("\nBefore Sorting\n\n");
for(int j=0; j<5; j++)
printf("A[%d] = %d\n",j,A[j]);
printf("\n\n");
for(int i=1; i<=5; i++)
for(j=0; j<5-1; j++){
if(A[j+1]<A[j]){
b=A[j];
A[j]=A[j+1];
A[j+1]=b;
} // End of if
} // End of Inner for
printf("\nAfter Ascending Sort\n\n");
for(j=0; j<5; j++)
printf("A[%d] = %d\n",j,A[j]);
printf("\n\n");
for(i=1; i<=5; i++)
for(j=0; j<5-1; j++){
if(A[j+1]>A[j]){
b=A[j];
A[j]=A[j+1];
A[j+1]=b;
} // End of if
} // End of Inner for
printf("\nAfter Descending Sort\n\n");
for(j=0; j<5; j++)
printf("A[%d] = %d\n",j,A[j]);
}
void main () {
// ASCENDING AND DESCENDING SORTING
clrscr();
int A[10];
int b;
printf("\t\tSORTING PROGRAM");
printf("\n\nEnter 5 values:\n");
for(int i=0; i<5; i++){
printf("A[%d] = ",i);
scanf("%d",&A[i]);
}
sort(A);
getche();
}
|
/**
*** Copyright (c) 1995, 1996, 1997, 1998, 1999, 2000 by
*** The Board of Trustees of the University of Illinois.
*** All rights reserved.
**/
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#ifndef RANDOM_H
#define RANDOM_H
#ifdef _MSC_VER
#define INT64_LITERAL(X) X ## i64
#else
#define INT64_LITERAL(X) X ## LL
#endif
#define RAND48_SEED INT64_LITERAL(0x00001234abcd330e)
#define RAND48_MULT INT64_LITERAL(0x00000005deece66d)
#define RAND48_ADD INT64_LITERAL(0x000000000000000b)
#define RAND48_MASK INT64_LITERAL(0x0000ffffffffffff)
typedef __int64 int64;
class Random {
private:
double second_gaussian;
int64 second_gaussian_waiting;
int64 rand48_seed;
int64 rand48_mult;
int64 rand48_add;
public:
// default constructor
Random(void) {
init(0);
rand48_seed = RAND48_SEED;
}
// constructor with seed
Random(unsigned long seed) {
init(seed);
}
// reinitialize with seed
void init(unsigned long seed) {
second_gaussian = 0;
second_gaussian_waiting = 0;
rand48_seed = seed & INT64_LITERAL(0x00000000ffffffff);
rand48_seed = rand48_seed << 16;
rand48_seed |= RAND48_SEED & INT64_LITERAL(0x0000ffff);
rand48_mult = RAND48_MULT;
rand48_add = RAND48_ADD;
}
// advance generator by one (seed = seed * mult + add, to 48 bits)
void skip(void) {
rand48_seed = ( rand48_seed * rand48_mult + rand48_add ) & RAND48_MASK;
}
// split into numStreams different steams and take stream iStream
void split(int iStream, int numStreams) {
int i;
// make sure that numStreams is odd to ensure maximum period
numStreams |= 1;
// iterate to get to the correct stream
for ( i = 0; i < iStream; ++i ) skip();
// save seed and add so we can use skip() for our calculations
int64 save_seed = rand48_seed;
// calculate c *= ( 1 + a + ... + a^(numStreams-1) )
rand48_seed = rand48_add;
for ( i = 1; i < numStreams; ++i ) skip();
int64 new_add = rand48_seed;
// calculate a = a^numStreams
rand48_seed = rand48_mult;
rand48_add = 0;
for ( i = 1; i < numStreams; ++i ) skip();
rand48_mult = rand48_seed;
rand48_add = new_add;
rand48_seed = save_seed;
second_gaussian = 0;
second_gaussian_waiting = 0;
}
// return a number uniformly distributed between 0 and 1
double uniform(void) {
skip();
const double exp48 = ( 1.0 / (double)(INT64_LITERAL(1) << 48) );
return ( (double) rand48_seed * exp48 );
}
// return a number from a standard gaussian distribution
double gaussian(void) {
double fac, r, v1, v2;
if (second_gaussian_waiting) {
second_gaussian_waiting = 0;
return second_gaussian;
} else {
r = 2.; // r >= 1.523e-8 ensures abs result < 6
while (r >=1. || r < 1.523e-8) { // make sure we are within unit circle
v1 = 2.0 * uniform() - 1.0;
v2 = 2.0 * uniform() - 1.0;
r = v1*v1 + v2*v2;
}
fac = sqrt(-2.0 * log(r)/r);
// now make the Box-Muller transformation to get two normally
// distributed random numbers. Save one and return the other.
second_gaussian_waiting = 1;
second_gaussian = v1 * fac;
return v2 * fac;
}
}
// return a vector of gaussian random numbers
// return a random long
int64 integer(void) {
skip();
return ( ( rand48_seed >> 17 ) & INT64_LITERAL(0x000000007fffffff) );
}
// randomly order an array of whatever
template <class Elem> void reorder(Elem *a, int n) {
for ( int i = 0; i < (n-1); ++i ) {
int ie = i + ( integer() % (n-i) );
if ( ie == i ) continue;
const Elem e = a[ie];
a[ie] = a[i];
a[i] = e;
}
}
};
#endif // RANDOM_H
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* 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 <skland/graphic/canvas.hpp>
#include <skland/graphic/paint.hpp>
#include <skland/graphic/path.hpp>
#include "SkBitmap.h"
#include "SkCanvas.h"
namespace skland {
Canvas::Canvas(unsigned char *pixel, int width, int height, int format) {
size_t stride = (size_t) width * 4;
// TODO: support more pixel format
switch (format) {
case kPixelFormatABGR8888:
default:break;
}
SkBitmap bitmap;
if (!bitmap.installPixels(SkImageInfo::MakeN32Premul(width, height), pixel, stride)) {
throw std::runtime_error("ERROR! Invalid bitmap format for Canvas!");
}
metadata_.reset(new SkCanvas(bitmap));
}
Canvas::~Canvas() {
}
void Canvas::SetOrigin(float x, float y) {
metadata_->translate(x - origin_.x, y - origin_.y);
origin_.x = x;
origin_.y = y;
}
void Canvas::DrawLine(float x0, float y0, float x1, float y1, const Paint &paint) {
metadata_->drawLine(x0, y0, x1, y1, *paint.sk_paint());
}
void Canvas::DrawRect(const Rect &rect, const Paint &paint) {
metadata_->drawRect(*reinterpret_cast<const SkRect *>(&rect), *paint.sk_paint());
}
void Canvas::DrawRoundRect(const Rect &rect, float rx, float ry, const Paint &paint) {
metadata_->drawRoundRect(*reinterpret_cast<const SkRect *>(&rect), rx, ry, *paint.sk_paint());
}
void Canvas::DrawCircle(float x, float y, float radius, const Paint &paint) {
metadata_->drawCircle(x, y, radius, *paint.sk_paint());
}
void Canvas::DrawArc(const Rect &oval, float start_angle, float sweep_angle, bool use_center, const Paint &paint) {
metadata_->drawArc(*reinterpret_cast<const SkRect *>(&oval), start_angle, sweep_angle, use_center, *paint.sk_paint());
}
void Canvas::DrawPath(const Path &path, const Paint &paint) {
metadata_->drawPath(*path.sk_path(), *paint.sk_paint());
}
void Canvas::DrawText(const void *text, size_t byte_length, float x, float y, const Paint &paint) {
metadata_->drawText(text, byte_length, x, y, *paint.sk_paint());
}
void Canvas::Translate(float dx, float dy) {
metadata_->translate(dx, dy);
}
void Canvas::ResetMatrix() {
metadata_->resetMatrix();
metadata_->translate(origin_.x, origin_.y);
}
void Canvas::Clear(uint32_t color) {
metadata_->clear(color);
}
void Canvas::Clear(const Color &color) {
metadata_->clear(color.argb());
}
void Canvas::ClipRect(const Rect &rect, ClipOperation op, bool antialias) {
metadata_->clipRect(reinterpret_cast<const SkRect &>(rect), static_cast<SkClipOp >(op), antialias);
}
void Canvas::ClipRect(const Rect &rect, bool antialias) {
metadata_->clipRect(reinterpret_cast<const SkRect &>(rect), antialias);
}
void Canvas::ClipPath(const Path &path, ClipOperation op, bool antialias) {
metadata_->clipPath(*path.sk_path(), static_cast<SkClipOp >(op), antialias);
}
void Canvas::ClipPath(const Path &path, bool antilias) {
metadata_->clipPath(*path.sk_path(), antilias);
}
void Canvas::Save() {
metadata_->save();
}
void Canvas::Restore() {
metadata_->restore();
}
void Canvas::Flush() {
metadata_->flush();
}
}
|
#include <QDebug>
// RsaTolbox
#include "General.h"
#include "GenericInstrument.h"
#include "VisaBus.h"
#include "TcpBus.h"
#include "NoBus.h"
using namespace RsaToolbox;
/*!
* \defgroup InstrumentGroup Instrument
* Rohde \& Schwarz instrument driver
* classes
*/
/*!
* \defgroup GenericInstrumentGroup GenericInstrument
* \ingroup InstrumentGroup
*/
/*!
* \class RsaToolbox::GenericInstrument
* \ingroup GenericInstrumentGroup
* \brief The %GenericInstrument class serves as a base class for all instruments.
*
* %GenericInstrument provides basic functionality. It can manage an instrument
* connection via a GenericBus subclass, it can connect to a Log, it can read,
* write and query, and it implements a subset of the required SCPI commands
* (such as *RST).
*
* This functionality can be extended to a specific instrument by subclassing
* %GenericInstrument and building on it.
*/
/*!
* \brief Default constructor
* \param parent Optional parent QObject
*/
GenericInstrument::GenericInstrument(QObject *parent) :
QObject(parent)
{
init();
}
GenericInstrument::GenericInstrument(ConnectionType type, QString address, QObject *parent) :
QObject(parent)
{
init();
open(type, address);
}
bool GenericInstrument::open(ConnectionType type, const QString &address) {
const uint bufferSize = 500;
const uint timeout_ms = 1000;
setBus(new VisaBus(type, address,
bufferSize, timeout_ms,
this));
return isOpen();
}
void GenericInstrument::close() {
const bool connected = isOpen();
_bus->disconnect ();
_bus->deleteLater();
_bus = new NoBus(this);
if (connected) {
emit disconnected();
}
}
void GenericInstrument::setBus(GenericBus *bus) {
close();
_bus = bus;
QObject::connect(_bus, SIGNAL(error()), this, SIGNAL(busError()));
QObject::connect(_bus, SIGNAL(print(QString)), _log, SLOT(print(QString)));
if (isOpen()) {
emit connected();
}
}
/*!
* \brief Checks for an instrument connection
* \return \c true if an instrument is connected,
* \c false otherwise
*/
bool GenericInstrument::isOpen() const {
return _bus->isOpen();
}
bool GenericInstrument::isResponding() {
return isOpen() && !idString().isEmpty();
}
bool GenericInstrument::isLogging() const {
return _log->isOpen();
}
bool GenericInstrument::startLog(QString filename, QString application, QString version) {
stopLog();
_log = new Log(filename, application, version, this);
connect(_bus, SIGNAL(print(QString)), _log, SLOT(print(QString)));
printInfo();
return isLogging();
}
void GenericInstrument::stopLog() {
_log->close();
_log->deleteLater();
_log = new Log(this);
}
void GenericInstrument::print(QString text) {
_log->print(text);
}
void GenericInstrument::init() {
_log = new Log (this);
_bus = new NoBus(this);
}
void GenericInstrument::printInfo() {
if (!isLogging()) {
return;
}
const bool blocked = _bus->blockSignals(true);
print(info());
_bus->blockSignals(blocked);
}
QString GenericInstrument::info() {
QString info;
QTextStream stream(&info);
stream << "INSTRUMENT INFO" << endl;
stream << "Connection: " << toString(_bus->connectionType()) << endl;
stream << "Address: " << _bus->address() << endl;
if (isOpen()) {
if (isRohdeSchwarz())
stream << "Make: Rohde & Schwarz" << endl;
else
stream << "Make: Unknown" << endl;
stream << "Id string: " << idString() << endl;
}
else {
stream << "Error: Instrument not found!" << endl;
}
stream << endl << endl;
stream.flush();
return info;
}
ConnectionType GenericInstrument::connectionType() const {
return _bus->connectionType();
}
QString GenericInstrument::address() const {
return _bus->address();
}
/*!
* \brief GenericInstrument::read
* \param buffer
* \param bufferSize_B
* \param timeout_ms
* \return
*/
bool GenericInstrument::read(char *buffer, uint bufferSize_B, uint timeout_ms) {
uint previousTimeout = _bus->timeout_ms();
_bus->setTimeout(timeout_ms);
bool success = _bus->read(buffer, bufferSize_B);
_bus->setTimeout(previousTimeout);
return(success);
}
/*!
* \brief Reads data from the instrument into \c buffer
*
* The action and result is printed to a log file, if connected.
*
* It is important to property set the \c bufferSize of \c buffer.
* If more than \c bufferSize bytes are waiting to be read
* by the instrument, an error may result and/or subsequent
* calls to \c %read() may be necessary.
*
* It is also important to make sure that the instrument
* is expecting to be read; calling %read() without having
* any data to be read will result in an instrument error.
*
* \note Make sure that a valid instrument connection is
* present before calling this method, otherwise
* unintended behavior may result.
*
* \param bufferSize_B Buffer for read
* \param timeout_ms Time until timeout, in milliseconds
* \return \c true if successful, \c false otherwise
* \sa write(), query(), isConnected(), useLog()
*/
QString GenericInstrument::read(uint bufferSize_B, uint timeout_ms) {
uint previousBufferSize = _bus->bufferSize_B();
uint previousTimeout = _bus->timeout_ms();
_bus->setBufferSize(bufferSize_B);
_bus->setTimeout(timeout_ms);
QString result = _bus->read();
_bus->setBufferSize(previousBufferSize);
_bus->setTimeout(previousTimeout);
return(result);
}
/*!
* \brief Writes \c scpiCommand to the instrument
*
* The action and result is printed to a log file, if connected.
*
* See query() for SCPI commands that elicit a response
* from the instrument; query() can handle both the read
* and write in one method call.
*
* \note Make sure that a valid instrument connection is
* present before calling this method, otherwise
* unintended behavior may result.
* \param scpiCommand Command to be written to the instrument
* \sa read(), query(), isConnected(), useLog()
*/
void GenericInstrument::write(QString scpiCommand) {
_bus->write(scpiCommand);
}
/*!
* \brief Writes \c scpiCommand to the instrument, then
* immediately reads the result to \c buffer
*
* This method is provided for convenience: it calls
* write() and then read(), then returns the result. See
* write() and read() for more information.
*
* The action and result is printed to a log file, if connected.
*
*\note Make sure that a valid instrument connection is
* present before calling this method, otherwise
* unintended behavior may result.
*
* \param scpiCommand Command to be written to the instrument
* \param bufferSize_B Buffer for data to be read into
* \param timeout_ms Time until timeout, in milliseconds
* \return
* \sa write(), read(), isConnected(), useLog()
*/
QString GenericInstrument::query(QString scpiCommand, uint bufferSize_B, uint timeout_ms) {
uint previousBufferSize = _bus->bufferSize_B();
uint previousTimeout = _bus->timeout_ms();
_bus->setBufferSize(bufferSize_B);
_bus->setTimeout(timeout_ms);
QString result = _bus->query(scpiCommand);
_bus->setBufferSize(previousBufferSize);
_bus->setTimeout(previousTimeout);
return(result);
}
/*!
* \brief GenericInstrument::binaryRead
* \param buffer
* \param bufferSize_B
* \param bytesRead
* \param timeout_ms
* \return
*/
bool GenericInstrument::binaryRead(char *buffer, uint bufferSize_B, uint &bytesRead, uint timeout_ms) {
uint previousTimeout = _bus->timeout_ms();
_bus->setTimeout(timeout_ms);
bool success = _bus->binaryRead(buffer, bufferSize_B, bytesRead);
_bus->setTimeout(previousTimeout);
return(success);
}
QByteArray GenericInstrument::binaryRead(uint bufferSize_B, uint timeout_ms)
{
uint previousBufferSize = _bus->bufferSize_B();
uint previousTimeout = _bus->timeout_ms();
_bus->setBufferSize(bufferSize_B);
_bus->setTimeout(timeout_ms);
QByteArray result = _bus->binaryRead();
_bus->setBufferSize(previousBufferSize);
_bus->setTimeout(previousTimeout);
return(result);
}
void GenericInstrument::binaryWrite(QByteArray scpiCommand) {
_bus->binaryWrite(scpiCommand);
}
/*!
* \brief Queries binary response from the
* instrument
*
* The data contained in scpiCommand is written
* to the instrument as-is; no null-terminations
* or assumentions are made. The returned binary
* data is treated in a similar manner.
*
* This is appropriate
* when standard string formatting would interfere
* with the query operation, such as when
* transferring the raw binary contents of a file.
*
* \note bufferSize_B() must be equal to or
* greater than the amount of data to be read,
* otherwise a partial read will occur.
*
* \param scpiCommand
* \param bufferSize_B
* \param timeout_ms
* \return Query result
*/
QByteArray GenericInstrument::binaryQuery(QByteArray scpiCommand,
uint bufferSize_B, uint timeout_ms)
{
uint previousBufferSize = _bus->bufferSize_B();
uint previousTimeout = _bus->timeout_ms();
_bus->setBufferSize(bufferSize_B);
_bus->setTimeout(timeout_ms);
QByteArray result = _bus->binaryQuery(scpiCommand);
_bus->setBufferSize(previousBufferSize);
_bus->setTimeout(previousTimeout);
return(result);
}
/*!
* \brief Locks the instrument for exclusive access
*
* This method calls the \c GenericBus::lock() method
* of the underlying connection bus. Note that
* Not all instrument busses support locking the instrument.
*
* \return \c true if operation is successful, \c false otherwise
* \sa GenericBus::lock(), unlock()
*/
bool GenericInstrument::lock() {
if (isOpen())
return(_bus->lock());
// else
return(false);
}
/*!
* \brief Unlocks the instrument for access by other applications
*
* This method calls the \c GenericBus::unlock() method
* of the underlying connection bus. Note that
* Not all instrument busses support locking the instrument.
*
* \return \c true if operation is successful, \c false otherwise
* \sa GenericBus::unlock(), lock()
*/
bool GenericInstrument::unlock() {
if (isOpen())
return(_bus->unlock());
// else
return(false);
}
/*!
* \brief Puts the instrument into local mode
* via the current bus protocol
*
* This method calls the \c GenericBus::local()
* method of the current bus object. Note that
* not all busses support putting the instrument
* into local mode. If a bus-level method is not provided,
* check the instrument documentation for an equivalent
* device-specific SCPI commands.
*
* \return \c true if successful, \c false otherwise
* \sa GenericBus::remote(), local()
*/
bool GenericInstrument::local() {
if (isOpen())
return(_bus->local());
// else
return(false);
}
/*!
* \brief Puts the instrument into remote mode
* via the current bus protocol
*
* This method calls the \c GenericBus::remote()
* method of the current bus object. Note that
* not all busses support putting the instrument
* into remote mode. If a bus-level method is not provided,
* check the instrument documentation for an equivalent
* device-specific SCPI commands.
*
* \return \c true if successful, \c false otherwise
* \sa GenericBus::remote(), local()
*/
bool GenericInstrument::remote() {
if (isOpen())
return(_bus->remote());
// else
return(false);
}
/*!
* \brief Determines if the instrument is a Rohde \&
* Schwarz instrument
*
* This method uses the \c idString(). If the
* \c idString() contains the string "Rohde",
* this method returns true.
*
* \return \c true if instrument is Rohde \& Schwarz,
* \c false otherwise
*/
bool GenericInstrument::isRohdeSchwarz() {
return(idString().contains("Rohde", Qt::CaseInsensitive));
}
// General SCPI commands (*)
/*!
* \brief Returns the identification string
*
* This method uses the "*IDN?" SCPI
* command to query the id string
* of the instrument.
*
* \return Identification string
*/
QString GenericInstrument::idString() {
return(_bus->query("*IDN?\n").trimmed());
}
/*!
* \brief Returns the options string
*
* This method uses the "*OPT?"
* SCPI command.
*
* \return Options string
* \sa idString()
*/
QString GenericInstrument::optionsString() {
return(_bus->query("*OPT?\n").trimmed());
}
/*!
* \brief Presets the instrument
*
* This method sends the "*RST"
* SCPI command.
*/
void GenericInstrument::preset() {
_bus->write("*RST\n");
}
/*!
* \brief Sends the "*WAI" SCPI command
*
* *WAI is used to synchonize SCPI commands.
* *WAI commands the instrument to process all
* preceeding commands and allow all sweeps to
* finish before processing any subsequent SCPI
* commands. This method immediately returns,
* although any subsequent read/write operations
* may be held up while *WAI is being processed.
*
* For a gentle introduction to synchronous
* instrument programming, see Application Note
* <a href="http://www.rohde-schwarz.de/file/1GP79_1E_SCPI_Programming_Guide_SigGens.pdf">
* 1GP79-1E: Top Ten SCPI Programming Tips for
* Signal Generators</a>. Although the App Note is
* specifically for Signal Generators, many of
* the concepts apply equally well to all
* instruments.
*
*\note Make sure that a valid instrument connection is
* present before calling this method, otherwise
* unintended behavior may result.
*/
void GenericInstrument::wait() {
_bus->write("*WAI\n");
}
/*!
* \brief Pauses until previous commands are completed.
*
* Use this method to synchronize your application
* with the SCPI command queue of the instrument.
*
* This method sends the "*OPC?" SCPI command
* to the instrument. Upon receiving this query,
* the instrument will complete all previous
* SCPI commands before returning the string "1".
* \c Pause waits for this return value before
* returning to the caller.
*
* This command is used for synchronous
* measurement sweeps.
*
* For a gentle introduction to synchronous
* instrument programming, see Application Note
* <a href="http://www.rohde-schwarz.de/file/1GP79_1E_SCPI_Programming_Guide_SigGens.pdf">
* 1GP79-1E: Top Ten SCPI Programming Tips for
* Signal Generators</a>. Although the App Note is
* specifically for Signal Generators, many of
* the concepts apply equally well to all
* instruments.
*
* \note This command has a timeout of
* \c GenericBus::timeout_ms() milliseconds.
*
* \return \c true if operation(s) completed.
* \c false otherwise.
* \sa pause(uint timeout_ms), GenericBus::timeout_ms()
*/
bool GenericInstrument::pause() {
return _bus->query("*OPC?\n").toUInt() == 1;
}
/*!
* \brief Pauses until previous commands are completed
* or for \c timeout_ms, whichever comes first.
* \param timeout_ms
* \return \c true if operation(s) completed.
* \c false otherwise
* \sa pause()
*/
bool GenericInstrument::pause(uint timeout_ms) {
uint oldTime = _bus->timeout_ms();
_bus->setTimeout(timeout_ms);
bool isOperationComplete = pause();
_bus->setTimeout(oldTime);
return isOperationComplete;
}
/*!
* \brief Initialize poll-and-loop synchronization
*
* This command sets the Operation Complete
* bit (bit 0) of the Event Status Register (ESR)
* to zero. Call this command immediately after
* the operation you want to synchronize to.
*
* When the instrument completes the current operation,
* it will set the Operation Complete bit to
* 1. Use the \c isOperationComplete() method
* to check for this.
*
* For a gentle introduction to synchronous
* instrument programming, see Application Note
* <a href="http://www.rohde-schwarz.de/file/1GP79_1E_SCPI_Programming_Guide_SigGens.pdf">
* 1GP79-1E: Top Ten SCPI Programming Tips for
* Signal Generators</a>. Although the App Note is
* specifically for Signal Generators, many of
* the concepts apply equally well to all
* instruments.
* \sa isOperationComplete()
*/
void GenericInstrument::initializePolling() {
_bus->write("*OPC\n");
}
/*!
* \brief Polls instrument for operation status
*
* When used with \c initializePolling(),
* this method returns \c true when the current
* operation is complete.
*
* For a gentle introduction to synchronous
* instrument programming, see Application Note
* <a href="http://www.rohde-schwarz.de/file/1GP79_1E_SCPI_Programming_Guide_SigGens.pdf">
* 1GP79-1E: Top Ten SCPI Programming Tips for
* Signal Generators</a>. Although the App Note is
* specifically for Signal Generators, many of
* the concepts apply equally well to all
* instruments.
* \return \c true if operation is complete,
* \c false otherwise
* \sa initializePolling()
*/
bool GenericInstrument::isOperationComplete() {
const uint opcBit = 0x1;
uint esr = _bus->query("*ESR?\n").toUInt();
return (esr & opcBit) == 1;
}
/*!
* \brief Clears all errors
*
* Sends the "*CLS" SCPI command to
* the instrument, which clears
* all errors from the
* error queue. These errors are
* discarded without being read
* or handled.
*/
void GenericInstrument::clearStatus() {
_bus->write("*CLS\n");
}
|
#pragma once
#include "bricks/core/object.h"
#include "bricks/core/exception.h"
#include "bricks/core/copypointer.h"
#include "bricks/io/filesystem.h"
struct zip;
struct zip_file;
namespace Bricks { namespace IO { class Stream; } }
namespace Bricks { namespace Compression {
#if BRICKS_CONFIG_COMPRESSION_LIBZIP
class LibZipException : public Exception
{
protected:
int error;
int systemError;
public:
LibZipException(int error, const String& message = String::Empty) : Exception(message), error(error), systemError(0) { }
LibZipException(struct zip* zipfile);
LibZipException(struct zip_file* file);
int GetErrorCode() const { return error; }
int GetSystemErrorCode() const { return systemError; }
};
class ZipFilesystem : public IO::Filesystem, public NoCopy
{
protected:
struct zip* zipfile;
String currentDirectory;
String TransformPath(const String& path) const;
String TransformPathReverse(const String& path) const;
public:
ZipFilesystem(IO::Stream* stream);
ZipFilesystem(const String& filepath);
~ZipFilesystem();
IO::FileHandle Open(
const String& path,
IO::FileOpenMode::Enum createmode = IO::FileOpenMode::Create,
IO::FileMode::Enum mode = IO::FileMode::ReadWrite,
IO::FilePermissions::Enum permissions = IO::FilePermissions::OwnerReadWrite
);
size_t Read(IO::FileHandle fd, void* buffer, size_t size);
size_t Write(IO::FileHandle fd, const void* buffer, size_t size);
u64 Tell(IO::FileHandle fd) const;
void Seek(IO::FileHandle fd, s64 offset, IO::SeekType::Enum whence);
void Flush(IO::FileHandle fd);
void Truncate(IO::FileHandle fd, u64 length);
void Close(IO::FileHandle fd);
IO::FileHandle Duplicate(IO::FileHandle fd);
IO::FileHandle OpenDirectory(const String& path);
ReturnPointer<IO::FileNode> ReadDirectory(IO::FileHandle fd);
size_t TellDirectory(IO::FileHandle fd);
void SeekDirectory(IO::FileHandle fd, size_t offset);
void CloseDirectory(IO::FileHandle fd);
IO::FileInfo Stat(const String& path);
IO::FileInfo FileStat(IO::FileHandle fd);
bool IsFile(const String& path) const;
bool IsDirectory(const String& path) const;
bool Exists(const String& path) const;
void DeleteFile(const String& path);
void DeleteDirectory(const String& path, bool recursive);
String GetCurrentDirectory() const;
void ChangeCurrentDirectory(const String& path);
void CreateFile(const String& path, IO::FilePermissions::Enum permissions);
void CreateDirectory(const String& path, IO::FilePermissions::Enum permissions);
};
#endif
} }
|
#pragma once
#include "IUnaryOperationNodesFactory.hpp"
#include "Nodes/UnaryOperations/TanhUnaryOperation.hpp"
template<class Type>
struct TanhNodeFactory : IUnaryOperationNodesFactory<Type>
{
TanhNodeFactory(Type beta)
: m_beta(beta)
{
}
std::unique_ptr<UnaryOperationNode<Type> > create(NotNull<ComputationNode<Type>> input) override
{
return std::make_unique<TanhUnaryOperationNode<Type>>(input, m_beta);
}
private:
Type m_beta;
};
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 2000-2011 Opera Software ASA. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Yngve Pettersen
//
//
#ifndef _MIME_CS_H
#define _MIME_CS_H
#ifdef _MIME_SUPPORT_
#include "modules/datastream/fl_lib.h"
#include "modules/cache/url_cs.h"
class MIME_Decoder;
class MIME_attach_element_url : public ListElement<MIME_attach_element_url>
{
public:
URL_InUse attachment;
BOOL displayed;
BOOL is_icon;
MIME_attach_element_url(URL &url, BOOL disp, BOOL isicon);
virtual ~MIME_attach_element_url();
};
#ifndef RAMCACHE_ONLY
class Decode_Storage
: public Persistent_Storage
{
protected:
MIME_ScriptEmbedSourcePolicyType script_embed_policy;
#ifdef MHTML_ARCHIVE_REDIRECT_SUPPORT
BOOL valid_mhtml_archive;
#endif
public:
Decode_Storage(URL_Rep *url_rep);
/**
* Second phase constructor. You must call this method prior to using the
* Decode_Storage object, unless it was created using the Create() method.
*
* @return OP_STATUS Status of the construction, always check this.
*/
OP_STATUS Construct(URL_Rep *url_rep);
/**
* OOM safe creation of a Decode_Storage object.
*
* @return Decode_Storage* The created object if successful and NULL otherwise.
*/
static Decode_Storage* Create(URL_Rep *url_rep);
virtual BOOL IsProcessed(){return TRUE;}
CACHE_STORAGE_DESC("Decode");
};
#else
class Decode_Storage
: public Memory_Only_Storage
{
protected:
MIME_ScriptEmbedSourcePolicyType script_embed_policy;
#ifdef MHTML_ARCHIVE_REDIRECT_SUPPORT
BOOL valid_mhtml_archive;
#endif
public:
Decode_Storage(URL_Rep *url_rep);
virtual BOOL IsProcessed(){return TRUE;}
CACHE_STORAGE_DESC("Decode")
};
#endif
class DecodedMIME_Storage
: public Decode_Storage
{
private:
AutoDeleteList<MIME_attach_element_url> attached_urls;
MIME_Decoder *decoder;
BOOL writing_to_self;
BOOL prefer_plain;
BOOL ignore_warnings;
int body_part_count;
DataStream_FIFO_Stream data;
BOOL decode_only;
#ifdef URL_SEPARATE_MIME_URL_NAMESPACE
URL_CONTEXT_ID context_id;
#endif
protected:
BOOL GetWritingToSelf(){return writing_to_self;}
virtual void SetBigAttachmentIcons(BOOL isbig);
virtual void SetPreferPlaintext(BOOL plain) {prefer_plain=plain;}
virtual void SetIgnoreWarnings(BOOL ignore) {ignore_warnings=ignore;}
void WriteToDecoder(const unsigned char *src, unsigned long src_len);
virtual void ProcessData()=0;
private:
void CreateDecoder(const unsigned char *src, unsigned long src_len);
public:
DecodedMIME_Storage(URL_Rep *url_rep);
virtual ~DecodedMIME_Storage();
OP_STATUS Construct(URL_Rep *url_rep);
//static DecodedMIME_Storage* Create(URL_Rep *url_rep);
void AddMIMEAttachment(URL &associate_url, BOOL displayed, BOOL isicon=FALSE, BOOL isbodypart=FALSE);
virtual BOOL GetAttachment(int i, URL &url);
virtual BOOL IsMHTML() const;
virtual URL GetMHTMLRootPart();
//virtual void StoreData(const char *buffer, unsigned long buf_len); // Unused
virtual unsigned long RetrieveData(URL_DataDescriptor *desc,BOOL &more);
virtual void SetFinished(BOOL force);
virtual BOOL Purge();
virtual BOOL Flush();
virtual URLCacheType GetCacheType() const { return URL_CACHE_MHTML;}
//virtual const uni_char *FileName() const;
//virtual const uni_char *FilePathName() const;
virtual URL_DataDescriptor *GetDescriptor(MessageHandler *mh=NULL, BOOL get_raw_data = FALSE, BOOL get_decoded_data=TRUE, Window *window = NULL,
URLContentType override_content_type = URL_UNDETERMINED_CONTENT, unsigned short override_charset_id = 0, BOOL get_original_content=FALSE, unsigned short parent_charset_id = 0);
BOOL GetDecodeOnly() {return decode_only;}
void SetDecodeOnly(BOOL dec_only) {decode_only=dec_only;}
int GetBodyPartCount() {return body_part_count;}
CACHE_STORAGE_DESC("DecodeMIME");
};
/**
* @brief Created by URL for MIME documents
*
* Creates MIME_Decoders during a data loading, which in turn create MIME_Decoders for each MIME part.
* MIME part contains data will create a new temporary URL.
*/
class MIME_DecodeCache_Storage
: public DecodedMIME_Storage
{
private:
Cache_Storage *source;
URL_DataDescriptor *desc;
protected:
virtual void ProcessData();
public:
MIME_DecodeCache_Storage(URL_Rep *url_rep, Cache_Storage *src);
virtual ~MIME_DecodeCache_Storage();
OP_STATUS Construct(URL_Rep *url_rep, Cache_Storage *src);
//static MIME_DecodeCache_Storage* Create(URL_Rep *url_rep, Cache_Storage *src);
virtual OP_STATUS StoreData(const unsigned char *buffer, unsigned long buf_len, OpFileLength start_position = FILE_LENGTH_NONE);
//virtual unsigned long RetrieveData(URL_DataDescriptor *desc,BOOL &more);
virtual void SetFinished(BOOL force);
virtual BOOL Purge();
virtual BOOL Flush();
virtual const OpStringC FileName(OpFileFolder &folder, BOOL get_original_body = TRUE) const;
virtual OP_STATUS FilePathName(OpString &name, BOOL get_original_body = TRUE) const;
//virtual URL_DataDescriptor *GetDescriptor(MessageHandler *mh=NULL, BOOL get_raw_data = FALSE, BOOL get_decoded_data=TRUE, Window *window = NULL);
virtual unsigned long SaveToFile(const OpStringC &);
virtual URL_DataDescriptor *GetDescriptor(MessageHandler *mh=NULL, BOOL get_raw_data = FALSE, BOOL get_decoded_data=TRUE, Window *window = NULL, URLContentType override_content_type = URL_UNDETERMINED_CONTENT, unsigned short override_charset_id = 0, BOOL get_original_content=FALSE, unsigned short parent_charset_id = 0);
virtual void TakeOverContentEncoding(OpStringS8 &enc){if(source) source->TakeOverContentEncoding(enc);}
CACHE_STORAGE_DESC("MIME_DecodeCache");
};
#endif
#endif // !_MIME_CS_H_
|
#include "rvplane.h"
RVPlane::RVPlane(int lenX, int lenZ)
:RVBody()
{
this->lenX = lenX;
this->lenZ = lenZ;
m_VSFileName = ":/shaders/VS_simpler.vsh";
m_FSFileName = ":/shaders/FS_plan.fsh";
}
void RVPlane::initializeBuffer()
{
QVector3D A(0, 0, 0);
QVector3D B(lenX, 0, 0);
QVector3D C(lenX, 0, lenZ);
QVector3D D(0, 0 ,lenZ);
QVector3D vertexData[] = {
A, B, C, D,
};
//Initialisation du Vertex Buffer Object
m_vbo = QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);
//Création du VBO
m_vbo.create();
//Lien du VBO avec le contexte de rendu OpenG
m_vbo.bind();
//Allocation des données dans le VBO
m_vbo.allocate(vertexData, sizeof (vertexData));
m_vbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
//Libération du VBO
m_vbo.release();
}
void RVPlane::draw()
{
m_program.bind();
m_vao.bind();
//Définition de la variable uniforme
QMatrix4x4 matrix;
matrix = m_camera->projectionMatrix() * m_camera->viewMatrix() * this->modelMatrix();
m_program.setUniformValue("u_ModelViewProjectionMatrix", matrix);
m_program.setUniformValue("u_Opacity", m_opacity);
m_program.setUniformValue("u_Color", m_globalColor);
if(m_wireframe)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
if(m_culling)
glEnable(GL_CULL_FACE);
else
glDisable(GL_CULL_FACE);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
m_vao.release();
m_program.release();
}
void RVPlane::initializeVAO()
{
//Initialisation du VAO
m_vao.bind();
m_vbo.bind();
//Définition des attributs
m_program.setAttributeBuffer("rv_Position", GL_FLOAT, 0, 3);
m_program.enableAttributeArray("rv_Position");
//Libération
m_vao.release();
m_program.release();
}
QMatrix4x4 RVPlane::modelMatrix()
{
QMatrix4x4 model;
model.translate((float)(-lenX / 2.0f), 0, (float)(-lenZ / 2.0f));
return RVBody::modelMatrix() * model;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 2000-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Kajetan Switalski
**
*/
#include "core/pch.h"
#include "modules/url/url_man.h"
#include "modules/idna/idna.h"
#include "modules/unicode/unicode_stringiterator.h"
// Exception table
struct Exception_st
{
UnicodePoint codepoint;
IDNALabelValidator::IDNAProperty value;
};
#include "modules/idna/tables/exceptions.inl"
BOOL IDNALabelValidator::IsInExceptions(UnicodePoint codepoint, IDNAProperty &exception_value)
{
// Binary search the code point in the exceptions_table
int low = 0;
int high = ARRAY_SIZE(exceptions_table)-1;
int middle;
while (low<=high)
{
middle = (high+low) >> 1;
if (exceptions_table[middle].codepoint == codepoint)
{
exception_value = exceptions_table[middle].value;
return TRUE;
}
if (exceptions_table[middle].codepoint < codepoint)
low = middle+1;
else
high = middle-1;
}
return FALSE;
}
BOOL IDNALabelValidator::IsInBackwardCompatible(UnicodePoint codepoint, IDNAProperty &exception_value)
{
/**
* This category includes the code points that property values in
* versions of Unicode after 5.2 have changed in such a way that the
* derived property value would no longer be PVALID or DISALLOWED. If
* changes are made to future versions of Unicode so that code points
* might change the property value from PVALID or DISALLOWED, then this
* table can be updated and keep special exception values so that the
* property values for code points stay stable. This set that is at release of
* rfc5892 document is empty.
*/
return FALSE;
}
BOOL IDNALabelValidator::IsUnassigned(UnicodePoint codepoint)
{
BOOL non_character = codepoint >= 0xFDD0 && codepoint <= 0xFDEF || ((codepoint & 0xFFFE) == 0xFFFE);
return !non_character && Unicode::GetCharacterClass(codepoint) == CC_Unknown;
}
BOOL IDNALabelValidator::IsUnstable_L(UnicodePoint codepoint)
{
#ifdef SUPPORT_UNICODE_NORMALIZE
if (codepoint == 0x0000)
return FALSE;
uni_char s[2]; /* ARRAY OK 2012-02-07 peter */
uni_char *normalized =
Unicode::Normalize(s, Unicode::WriteUnicodePoint(s, codepoint), TRUE, TRUE);
if (!normalized)
LEAVE(OpStatus::ERR_NO_MEMORY);
uni_char *casefolded = Unicode::ToCaseFoldFull(normalized);
OP_DELETEA(normalized);
if (!casefolded)
LEAVE(OpStatus::ERR_NO_MEMORY);
uni_char *renormalized = Unicode::Normalize(casefolded, uni_strlen(casefolded), TRUE, TRUE);\
OP_DELETEA(casefolded);
if (!renormalized)
LEAVE(OpStatus::ERR_NO_MEMORY);
BOOL result = Unicode::GetUnicodePoint(renormalized, uni_strlen(renormalized)) != codepoint;
OP_DELETEA(renormalized);
return result;
#else
return FALSE;
#endif
}
BOOL IDNALabelValidator::IsLDH(UnicodePoint codepoint)
{
return codepoint==0x002D || codepoint>=0x0030 && codepoint<=0x0039 || codepoint>=0x0061 && codepoint<=0x007A;
}
BOOL IDNALabelValidator::IsIgnorableProperties(UnicodePoint codepoint)
{
BOOL non_character = codepoint >= 0xFDD0 && codepoint <= 0xFDEF || ((codepoint & 0xFFFE) == 0xFFFE);
return non_character
|| Unicode::CheckPropertyValue(codepoint, PROP_White_Space)
|| Unicode::CheckDerivedPropertyValue(codepoint, DERPROP_Default_Ignorable_Code_Point);
}
BOOL IDNALabelValidator::IsIgnorableBlocks(UnicodePoint codepoint)
{
UnicodeBlockType blockType = Unicode::GetUnicodeBlockType(codepoint);
return blockType==BLK_CombiningDiacriticalMarksforSymbols || blockType==BLK_MusicalSymbols || blockType==BLK_AncientGreekMusicalNotation;
}
BOOL IDNALabelValidator::IsOldHangulJamo(UnicodePoint codepoint)
{
HangulSyllableType type = Unicode::GetHangulSyllableType(codepoint);
return type==Hangul_L || type==Hangul_V || type==Hangul_T;
}
BOOL IDNALabelValidator::IsLetterDigit(UnicodePoint codepoint)
{
CharacterClass cc = Unicode::GetCharacterClass(codepoint);
return cc==CC_Ll || cc==CC_Lu || cc==CC_Lo || cc==CC_Nd || cc==CC_Lm || cc==CC_Mn || cc==CC_Mc;
}
IDNALabelValidator::IDNAProperty IDNALabelValidator::GetIDNAProperty_L(UnicodePoint codepoint)
{
IDNAProperty result;
if (IsInExceptions(codepoint, result))
return result;
else if (IsInBackwardCompatible(codepoint, result))
return result;
else if (IsUnassigned(codepoint))
return IDNA_UNASSIGNED;
else if (IsLDH(codepoint))
return IDNA_PVALID;
else if (Unicode::CheckPropertyValue(codepoint, PROP_Join_Control) )
return IDNA_CONTEXTJ;
else if (IsUnstable_L(codepoint) || IsIgnorableProperties(codepoint) || IsIgnorableBlocks(codepoint) || IsOldHangulJamo(codepoint))
return IDNA_DISALLOWED;
else if (IsLetterDigit(codepoint))
return IDNA_PVALID;
return IDNA_DISALLOWED;
}
BOOL IDNALabelValidator::CheckContextualRules(const UnicodeStringIterator &it)
{
if (*it >= 0x0660 && *it <= 0x0669) // ARABIC-INDIC DIGITS
{
for (UnicodeStringIterator it2 = it.FromBeginning(); !it2.IsAtEnd(); ++it2)
if (*it2 >= 0x06f0 && *it2 <= 0x06f9)
return FALSE;
return TRUE;
}
if (*it >= 0x06f0 && *it <= 0x06f9) // EXTENDED ARABIC-INDIC DIGITS
{
for (UnicodeStringIterator it2 = it.FromBeginning(); !it2.IsAtEnd(); ++it2)
if (*it2 >= 0x0660 && *it2 <= 0x0669)
return FALSE;
return TRUE;
}
UnicodeStringIterator before = it, after = it;
++after;
bool isAfter = !after.IsAtEnd();
bool isBefore = !before.IsAtBeginning();
if (isBefore)
--before;
//implements contextual rules defined by document rfc5892 for particular codepoints
switch (*it)
{
case 0x200c: // ZERO WIDTH NON-JOINER
{
#ifdef SUPPORT_UNICODE_NORMALIZE
if (isBefore && Unicode::GetCombiningClassFromCodePoint(*before)==9) // "Virama"
return TRUE;
#endif // SUPPORT_UNICODE_NORMALIZE
if (!isBefore || !isAfter)
return FALSE;
UnicodeStringIterator it2 = before;
while (!it2.IsAtBeginning() && Unicode::GetUnicodeJoiningType(*it2) == JT_T)
--it2;
if (Unicode::GetUnicodeJoiningType(*it2) != JT_L && Unicode::GetUnicodeJoiningType(*it2) != JT_D)
return FALSE;
it2 = after;
while (!it2.IsAtEnd() && Unicode::GetUnicodeJoiningType(*it2) == JT_T)
++it2;
if (it2.IsAtEnd() || Unicode::GetUnicodeJoiningType(*it2) != JT_R && Unicode::GetUnicodeJoiningType(*it2) != JT_D)
return FALSE;
return TRUE;
}
case 0x200d: // ZERO WIDTH JOINER
#ifdef SUPPORT_UNICODE_NORMALIZE
if (isBefore && Unicode::GetCombiningClassFromCodePoint(*before)==9) // "Virama"
return TRUE;
#else
return FALSE;
#endif
case 0x00b7: // MIDDLE DOT
return isBefore && isAfter && *before == 0x006c && *after == 0x006c;
#ifdef USE_UNICODE_SCRIPT
case 0x0375: // GREEK LOWER NUMERAL SIGN (KERAIA)
return isAfter && Unicode::GetScriptType(*after) == SC_Greek;
case 0x05f3: // HEBREW PUNCTUATION GERESH
case 0x05f4: // HEBREW PUNCTUATION GERSHAYIM
return isBefore && Unicode::GetScriptType(*before) == SC_Hebrew;
case 0x30fb: // KATAKANA MIDDLE DOT
{
for (UnicodeStringIterator it2 = it.FromBeginning(); !it2.IsAtEnd(); ++it2)
{
ScriptType st = Unicode::GetScriptType(*it2);
if (st == SC_Hiragana || st == SC_Katakana || st == SC_Han)
return TRUE;
}
return FALSE;
}
#endif // USE_UNICODE_SCRIPT
default:
return FALSE;
}
}
BOOL IDNALabelValidator::IsCodePointIDNAValid_L(const UnicodeStringIterator &it)
{
IDNAProperty idnaproperty = GetIDNAProperty_L(*it);
switch (idnaproperty)
{
case IDNA_PVALID:
return TRUE;
case IDNA_DISALLOWED:
case IDNA_UNASSIGNED:
return FALSE;
case IDNA_CONTEXTJ:
case IDNA_CONTEXTO:
return CheckContextualRules(it);
}
return FALSE;
}
#ifdef SUPPORT_TEXT_DIRECTION
BOOL IDNALabelValidator::CheckBidiRule(const uni_char *label, int len)
{
// implementation of rfc5893
UnicodeStringIterator first(label, 0, len);
UnicodeStringIterator last = first;
while (!last.IsAtEnd())
++last;
--last;
BidiCategory bidi = Unicode::GetBidiCategory(*first);
if (bidi != BIDI_L && bidi != BIDI_R && bidi != BIDI_AL)
return FALSE;
BOOL RTL = bidi != BIDI_L;
if (RTL)
{
BOOL an_present = FALSE, en_present = FALSE;
for (UnicodeStringIterator it=first; !it.IsAtEnd(); ++it)
{
bidi = Unicode::GetBidiCategory(*it);
if (bidi != BIDI_R && bidi != BIDI_AL && bidi != BIDI_AN && bidi != BIDI_EN && bidi != BIDI_ES &&
bidi != BIDI_CS && bidi != BIDI_ET && bidi != BIDI_ON && bidi != BIDI_BN && bidi != BIDI_NSM)
return FALSE;
an_present = an_present || bidi == BIDI_AN;
en_present = en_present || bidi == BIDI_EN;
if (an_present && en_present)
return FALSE;
}
BOOL wasFirst = FALSE;
for (UnicodeStringIterator it = last; !wasFirst; --it)
{
bidi = Unicode::GetBidiCategory(*it);
if (bidi == BIDI_R || bidi == BIDI_AL || bidi == BIDI_EN || bidi == BIDI_AN)
break;
if (bidi != BIDI_NSM)
return FALSE;
wasFirst = it.IsAtBeginning();
}
}
else
{
for (UnicodeStringIterator it=first; !it.IsAtEnd(); ++it)
{
bidi = Unicode::GetBidiCategory(*it);
if (bidi != BIDI_L && bidi != BIDI_EN && bidi != BIDI_ES && bidi != BIDI_CS && bidi != BIDI_ET &&
bidi != BIDI_ET && bidi != BIDI_ON && bidi != BIDI_BN && bidi != BIDI_NSM)
return FALSE;
}
BOOL wasFirst = FALSE;
for (UnicodeStringIterator it = last; wasFirst; --it)
{
bidi = Unicode::GetBidiCategory(*it);
if (bidi == BIDI_L || bidi == BIDI_EN)
break;
if (bidi != BIDI_NSM)
return FALSE;
wasFirst = it.IsAtBeginning();
}
}
return TRUE;
}
#endif // SUPPORT_TEXT_DIRECTION
BOOL IDNALabelValidator::IsBlockedAdditionally(UnicodePoint cp)
{
if (
cp>=0x0250 && cp<=0x02AF || //IPA Extensions
cp>=0x1680 && cp<=0x169f || //Ogham
cp>=0x16a0 && cp<=0x16ff //Runic
)
return TRUE;
else
return FALSE;
}
BOOL IDNALabelValidator::IsDomainNameIDNAValid_L(const uni_char *domainname, BOOL additionalBlocking)
{
#ifdef SUPPORT_TEXT_DIRECTION
size_t domainname_len = uni_strlen(domainname);
BOOL bidiDomain = FALSE;
for (UnicodeStringIterator it(domainname, 0, domainname_len); !it.IsAtEnd(); ++it)
{
BidiCategory bc = Unicode::GetBidiCategory(*it);
bidiDomain |= bc == BIDI_R || bc == BIDI_AL || bc == BIDI_AN;
}
#endif // SUPPORT_TEXT_DIRECTION
const uni_char *comp_end;
do{
comp_end = uni_strchr(domainname, '.');
int label_len = comp_end ? (comp_end - domainname) : uni_strlen(domainname);
if (label_len)
{
if (!IsLabelIDNAValid_L(domainname, label_len, additionalBlocking))
return FALSE;
#ifdef SUPPORT_TEXT_DIRECTION
if (label_len && bidiDomain && !CheckBidiRule(domainname, label_len))
return FALSE;
#endif // SUPPORT_TEXT_DIRECTION
}
if (comp_end)
domainname = comp_end + 1;
} while (comp_end);
return TRUE;
}
BOOL IDNALabelValidator::IsLabelIDNAValid_L(const uni_char *label, int len, BOOL additionalBlocking)
{
UnicodeStringIterator it(label, 0, len);
while (!it.IsAtEnd() && (IsLDH(*it) || *it == '_')) // Microsoft Windows systems often use underscores in hostnames so we must allow it ascii labels
++it;
if (it.IsAtEnd())
return TRUE;
for (; !it.IsAtEnd(); ++it)
if (!IDNALabelValidator::IsCodePointIDNAValid_L(it)
|| additionalBlocking && IsBlockedAdditionally(*it))
return FALSE;
return TRUE;
}
|
#define WHITE 0
#define BLACK 1
#include <iostream>
#include <algorithm>
using namespace std;
int nMap[101][101];
int nCheck[101][101];
int M, N, K;
int nResult = 0;
int nCntOfSector[101];
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0, -1, 1 };
void DFS(int x, int y, int Depth)
{
nCheck[x][y] = 1;
nCntOfSector[Depth]++;
for (int i = 0; i < 4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if (nx >= 0 && nx < N && ny >= 0 && ny < M)
{
if (WHITE == nMap[nx][ny] && 0 == nCheck[nx][ny])
{
DFS(nx, ny, Depth);
}
}
}
}
int main(void)
{
cin >> M >> N >> K;
for (int i = 0; i < K; i++)
{
int xMin, yMin, xMax, yMax;
cin >> xMin >> yMin >> xMax >> yMax;
for (int x = xMin; x < xMax; x++)
{
for (int y = yMin; y < yMax; y++)
{
nMap[x][y] = BLACK;
}
}
}
for (int x = N-1; x >= 0; x--)
{
for (int y = M-1; y >= 0; y--)
{
if (WHITE == nMap[x][y] && 0 == nCheck[x][y] )
{
DFS(x, y, nResult);
nResult++;
}
}
}
cout << nResult << endl;
sort(nCntOfSector, nCntOfSector + nResult);
for (int i = 0; i < nResult; i++)
{
cout << nCntOfSector[i] << " ";
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
main (){
int t;
cin >> t;
while (t>0){
long n;
cin >> n;
long long a[n];
for (long long i=0;i<n;i++){
a[i]=-1;
}
long long b;
for (long long i=0;i<n;i++){
cin >>b;
if (b < n && b>=0 ) a[b]=b;
}
for (long long i=0;i<n;i++){
cout << a[i]<< " ";
}
cout << endl;
t--;
}
}
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#include "Core/Resource.hpp"
#include <cassert>
namespace Push
{
Resource::Resource(const Path& resource, size_t type)
: m_resource(resource)
, m_state(Resource::State::Initialized)
, m_uses(1)
, m_hash(0)
, m_type(type)
{
}
Resource::~Resource()
{
assert(m_state == Resource::State::Released);
}
const Path& Resource::GetPath() const
{
return m_resource;
}
Resource::State Resource::GetState() const
{
return m_state;
}
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e17 // 4倍しても(4回足しても)long longを溢れない
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto itr : x) { debug(itr); }
const ll MAX = 510000;
ll fac[MAX], finv[MAX], inv[MAX];
void init() {
fac[0] = fac[1] = 1;
finv[0] = finv[1] = 1;
inv[1] = 1;
for(int i = 2; i < MAX; i++){
fac[i] = fac[i-1] * i % MOD;
inv[i] = MOD - inv[MOD%i] * (MOD/i) % MOD;
finv[i] = finv[i-1] * inv[i] % MOD;
}
}
// n!! * k!^(-1) * ((n - k)!)^(-1)
ll comb(ll n, ll k) {
if (n < k) return 0;
if (n < 0 || k < 0) return 0;
return fac[n] * (finv[k]* finv[n - k] % MOD) % MOD;
}
int main() {
init();
ll n, m;
cin >> n >> m;
ll ans = 0;
for (int k = 1; k <= min(n,m); ++k) {
ans += comb(k, n - k) * comb(m - 1, k - 1) % MOD;
ans %= MOD;
}
cout << (comb(n + m - 2, m - 1) - ans + MOD) % MOD << endl;
}
|
#pragma once
template <class T>
class Node
{
public:
T region;
Node<T> *child1;
Node<T> *child2;
Node<T> *child3;
Node<T> *child4;
public:
Node(T region_);
~Node();
};
template <class T>
Node<T>::Node(T region_) : region(region_)
{
child1 = nullptr;
child2 = nullptr;
child3 = nullptr;
child4 = nullptr;
}
template <class T>
Node<T>::~Node()
{
delete child1;
delete child2;
delete child3;
delete child4;
child1 = nullptr;
child2 = nullptr;
child3 = nullptr;
child4 = nullptr;
}
|
#include <iostream>
#include <pybind11/embed.h>
#include <pybind11/stl.h>
namespace py = pybind11;
using namespace py::literals;
int main() {
// start the interpreter and keep it alive
py::scoped_interpreter guard{};
// use the Python API
py::print("Hello, World!");
// executing code from string
py::exec(R"(
kwargs = dict(name="World", number=42)
message = "Hello, {name}! The answer is {number}".format(**kwargs)
print(message)
my_variable = 20
)");
// evaluating expressions in python
// (you can also use py::eval_file("script.py");)
int result = py::eval("my_variable + 10").cast<int>();
py::print(result);
// use python with the API
auto locals = py::dict("name"_a="World", "number"_a=42);
py::exec(R"(
message = "Hello, {name}! The answer is {number}".format(**locals())
)", py::globals(), locals);
auto message = locals["message"].cast<std::string>();
py::print(message);
// importing modules
py::module sys = py::module::import("sys");
py::print(sys.attr("path"));
// importing local file as module
// (the add function is seen as an attribute of the module)
py::module calc = py::module::import("calc");
py::object add_function = calc.attr("add");
py::object add_result = add_function(1, 2);
int n = add_result.cast<int>();
assert(n == 3);
py::print(add_result.cast<int>());
// plotting with python
// https://matplotlib.org/gallery/lines_bars_and_markers/simple_plot.html#sphx-glr-gallery-lines-bars-and-markers-simple-plot-py
// import modules
py::module matplotlib = py::module::import("matplotlib");
py::module plt = py::module::import("matplotlib.pyplot");
py::module np = py::module::import("numpy");
std::cout << py::str(matplotlib) << std::endl;
// failing to find a module
try {
py::module fail_module = py::module::import("fake_module_name_that_doesnt_exist");
} catch (...) {
std::cout << "You can't import any name you want" << std::endl;
}
// create data we want to plot
// t = [0.00, 0.01, 0.02, ..., 2.00]
std::vector<double> t(static_cast<size_t>(2.0/0.01));
std::generate(t.begin(), t.end(), [range = 0.0] () mutable { return range += 0.01; });
// s = 1 + sin(pi * 2 * t)
std::vector<double> s(t.size());
// get pi from python
// (just as an example - of course we could use C++ for that)
auto pi = np.attr("pi").cast<double>();
// get the sin function from python
// (just as an example - of course we could use C++ for that
auto sin = [&np](double x) {
static py::object py_sin = np.attr("sin");
return py_sin(x).cast<double>();
};
// s = 1 + sin(pi * 2 * t)
std::transform(t.begin(),t.end(),s.begin(),[&sin,&pi](double x){return 1 + sin(pi * 2 * x);});
// use the plotting library (subplot returns a tuple of return values)
py::tuple pytuple = plt.attr("subplots")();
py::object fig = pytuple[0];
py::object ax = pytuple[1];
// interactive mode
plt.attr("ion")();
// plot t and s (pybind automatically converts t and s to python types)
ax.attr("plot")(t, s);
// set labels
ax.attr("set")("xlabel"_a="time (s)", "ylabel"_a="voltage (mV)", "title"_a="About as simple as it gets, folks");
// put grid behind plot
ax.attr("grid")();
// save a file with the figure
fig.attr("savefig")("test.png");
// draw on screen
plt.attr("draw")();
plt.attr("pause")(0.0001);
for (int i = 0; i < s.size(); ++i) {
// change values and plot again a few times
std::rotate(s.begin(),s.begin()+1,s.end());
plt.attr("cla")();
ax.attr("plot")(t, s);
ax.attr("set")("xlabel"_a="time (s)", "ylabel"_a="voltage (mV)", "title"_a="About as simple as it gets, folks");
plt.attr("draw")();
plt.attr("pause")(0.0001);
}
plt.attr("show")();
return 0;
}
|
/*
* PerfectForwardingFail.cpp
*
* Created on: May 25, 2016
* Author: bakhvalo
*/
#include "gtest/gtest.h"
#include <type_traits>
#include <vector>
#include <chrono>
#include <set>
namespace
{
void f(int)
{
}
void f(const std::vector<int>&)
{
}
template<typename... Ts>
void fwd(Ts&&... params)
{
f(std::forward<Ts>(params)...);
}
}
TEST(PerfectForwardingFailuresUnitTest, braced_init)
{
f({1, 2, 3});
//fwd({1, 2, 3}); // not compiles. Compiler can't deduce std::intializer_list for calling fwd.
fwd(std::vector<int>({1, 2, 3}));
auto il = { 1, 2, 3 };
fwd(il); // now fine, because there is no need to deduce the type
}
namespace
{
struct A
{
static const int val = 18;
};
struct B
{
static const int val = 18;
};
const int B::val;
}
TEST(PerfectForwardingFailuresUnitTest, static_int_consts)
{
//fwd(A::val); //not links. Because A::val declaration is missing. Address of A::val couldn't be retrieved.
fwd(B::val);
}
namespace
{
void fp(int pf(int))
{
(void)pf;
}
int processVal(int value) {return 0;}
int processVal(int value, int priority) {return 0;}
template<typename T>
T workOnVal(T param)
{ return T{}; }
template<typename... Ts>
void fwdtoFunc(Ts&&... params)
{
fp(std::forward<Ts>(params)...);
}
}
TEST(PerfectForwardingFailuresUnitTest, function_pointers_and_template_funcs)
{
(void)processVal(5,5);
fp(processVal);
//fwdtoFunc(processVal); // not compiles. Which processval to call?
fp(workOnVal);
//fwdtoFunc(workOnVal); //not compiles. Which instanstiation?
using ProcessFuncType = int (*)(int);
ProcessFuncType func_pointer = processVal;
fwdtoFunc(func_pointer);
fwdtoFunc(static_cast<ProcessFuncType>(workOnVal));
}
namespace
{
struct BitField
{
char c:4;
};
void foo(int)
{
}
template<typename... Ts>
void fwdBitField(Ts&&... params)
{
foo(std::forward<Ts>(params)...);
}
}
TEST(PerfectForwardingFailuresUnitTest, bitfields)
{
BitField bf {0};
foo(bf.c);
// fwdBitField(bf.c); //not compiles. References to bitfields are forbidden.
}
|
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
int a[7] = {2,4,1,3,7,9,5};
int temp = 0;
for(int i = 0; i < 7; i++)
{
for(int j = 0; j < 7-i-1; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for(int m = 0; m < 7; m++)
{
cout << a[m]<<endl;
}
}
|
#include "MyView.h"
MY_IMPLEMENT_DYNAMIC(CMyView, CMyWnd)
CMyView::CMyView()
{
}
CMyView::~CMyView()
{
}
|
#include "trail.h"
#include <limits>
using namespace std;
void Trail::Run()
{
printf("begin trail, threshold %lf, number of file %d\n",e,n);
int *trail_set = (int *)malloc(sizeof(int) * n);
memset(trail_set,0,n);
for(int i = 0; i < n; i++)
trail_set[i] = 0;
float prev_min = dist_matrix[0][1];
int start = 0, current = 1;
for(int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
{
if( dist_matrix[i][j] < prev_min )
{
start = i;
current = j;
prev_min = dist_matrix[i][j];
}
}
}
trail_set[start] = 1;
trail_set[current] = 1;
// int start_max = FindMin(start,trail_set);
// int cur_max = FindMin(current,trail_set);
// //printf("test: %.4f %.4f\n",w_matrix[start][start_max],w_matrix[current][cur_max]);
// if ( dist_matrix[start][start_max] < dist_matrix[current][cur_max] )
// {
// int buffer = start;
// start = current;
// current = buffer;
// }
group *cur_group = (group *)malloc(sizeof(group));
kv_init(*cur_group);
kv_push(int, *cur_group, start);
kv_push(int, *cur_group, current);
int count = 2;
vector <int> test_result;
test_result.push_back(start);
test_result.push_back(current);
float average_dist = 0.0;
for (int i = 0; i < n-1; i++)
{
for(int j = i+1; j < n; j++)
average_dist += dist_matrix[i][j];
}
//printf("test dist %.4f, test trail %d\n",dist_matrix[60][82],trail_set[82]);
dist_threshold = 0.5*average_dist/(n*(n-1));
printf("distance: %d,%d,%lf\n",start,current,dist_matrix[start][current]);
while (count < n)
{
int next = FindMin(current,trail_set);
printf("distance: %d,%d,%lf\n",current,next,dist_matrix[current][next]);
trail_set[next] = 1;
if( dist_matrix[current][next] <= e * (0.9+2/(cur_group->n+9))* prev_min ||
(dist_matrix[current][next] < 1.2*dist_threshold && cur_group->n <=4) )
{
kv_push(int, *cur_group, next);
}
else
{
groups.push_back(cur_group);
cur_group = (group *)malloc(sizeof(group));
kv_init(*cur_group);
kv_push(int, *cur_group, next);
}
test_result.push_back(next);
prev_min = dist_matrix[current][next];
current = next;
count++;
}
groups.push_back(cur_group);
printf("test result:\n");
for(int i = 0; i < n; i++)
printf("%d ", test_result[i]);
printf("\n");
free(trail_set);
return;
}
int Trail::FindMin(int id, int *trail_set)
{
float min = numeric_limits<float>::max();
int result = -1;
if(id == 60)
{
for(int i = 0 ; i < n; i++)
printf("%d ",trail_set[i]);
printf("\n");
for(int i = 0 ; i < n; i++)
{
if( trail_set[i] != 1 )
printf("remaining point:%d,%.4lf",i,dist_matrix[id][i]);
}
}
for(int i = 0 ; i < n; i++)
{
if( dist_matrix[id][i] < min)
{
if( i != id && trail_set[i] != 1 )
{
result = i;
min = dist_matrix[id][i];
}
}
}
return result;
}
void Trail::WriteResult(char *file_name)
{
printf("result write to %s\n",file_name);
ofstream fp;
fp.open(file_name);
printf("begin split, number of groups: %d\n", groups.size());
int total = 0;
for(int i = 0; i < groups.size(); i++)
{
total += groups[i]->n;
printf("start %d, group size:%d\n",groups[i]->a[0],groups[i]->n);
float prev_dist = numeric_limits<float>::max();
int count = 0, cur_num = 0;
while( count < (groups[i]->n)-2 && groups[i]->n > 3)
{
//printf("step %d ",count);
int cur = groups[i]->a[count], next = groups[i]->a[count+1];
float cur_dist = dist_matrix[cur][next];
double threshold = 1 + 0.25*(4-cur_num);
if(cur_num <= 2 && (cur_dist <= threshold * prev_dist || cur_dist <1.2*dist_threshold))
{
//printf("a, count %d\n",count);
fp << cur << " ";
cur_num++;
}
else
{
//printf("b, count %d\n",count);
fp << "\n" << cur << " ";
cur_num = 1;
}
count++;
prev_dist = dist_matrix[cur][next];
if(cur_num >=2 && count >= ((groups[i]->n)-2) )
fp << "\n";
}
for(int j = count; j < groups[i]->n; j++ )
fp << groups[i]->a[j] << " ";
fp << "\n";
}
printf("included file %d\n",total);
fp.close();
return;
}
void Trail::Split(group *g)
{
}
|
#pragma once
#include "graph.hpp"
#include "response.hpp"
#include "layout.hpp"
extern "C" void inject(char const * const);
extern "C" void load(char const * const url);
extern "C" void scale(const double depth, const double breadth);
extern "C" void setPhysics(void);
extern "C" void iterate(const unsigned int count);
extern "C" void renderSvg(unsigned int root);
extern "C" void stop(void);
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
std::ios::sync_with_stdio(false);
string N;
int carry;
while(!cin.eof())
{
N="0";
cin>>N;
if(N=="0")
continue;
if(N=="1")
cout<<"1"<<endl;
else
{
for(int i=N.length()-1;i>=0;i--)
{
if(N[i]=='0')
{
N[i]='9';
}
else
{
N[i]--;
break;
}
}
carry=0;
for(int i=N.length()-1;i>=0;i--)
{
switch(N[i])
{
case '1': N[i]='2'+carry;
carry=0;
break;
case '2': N[i]='4'+carry;
carry=0;
break;
case '3': N[i]='6'+carry;
carry=0;
break;
case '4': N[i]='8'+carry;
carry=0;
break;
case '5': N[i]='0'+carry;
carry=1;
break;
case '6': N[i]='2'+carry;
carry=1;
break;
case '7': N[i]='4'+carry;
carry=1;
break;
case '8': N[i]='6'+carry;
carry=1;
break;
case '9': N[i]='8'+carry;
carry=1;
break;
case '0': N[i]='0'+carry;
carry=0;
break;
}
}
if(carry==1)
cout<<"1";
cout<<N<<endl;
}
}
return 0;
}
|
#pragma once
#include <string.h>
#include <iostream>
using namespace std;
#include <stdio.h>
|
/*********************************************************************
** Author: Christopher Matian
** Date: July 5th, 2017
** Description: A small program that converts celsius to fahrenheit
*********************************************************************/
#include <iostream>
using namespace std;
int main() {
double celsius;
// Prompts user
cout << "Please enter a Celsius Temperature." << endl;
// Stores input into Celsius variable
cin >> celsius;
// Display store temperature in celsius
cout << celsius << endl;
// Calculate and display temperature in fahrenheit
cout << "The Equivalent Fahrenheit temperature is:" << endl << (celsius * 9/5) + 32;
return 0;
}
|
#include "DFA.h"
DFA::DFA()
{
}
DFA::~DFA()
{
}
bool DFA :: addTokenItem(int key, tokenItem i) {
if (tokenDict.find(key) == tokenDict.end())
{
tokenDict.insert({ key, i });
return true; //如果存在边的话返回true
}
else {
return false;
}
}
bool DFA::addTokenItem(int key, int token_id, string token_name) {
tokenItem i = tokenItem(token_id, token_name);
if (tokenDict.find(key) == tokenDict.end())
{
tokenDict.insert({ key, i });
return true; //如果存在边的话返回true
}
else {
return false;
}
}
bool DFA :: removeTokenItem(int key, tokenItem i) {
auto iter = tokenDict.find(key);
if (iter != tokenDict.end())
{
tokenDict.erase(iter);
return true; //如果存在边的话返回true
}
else {
return false;
}
}
bool DFA::addKeepWord(string keyword, int token_id) {
auto iter = keepWords.find(keyword);
if (iter == keepWords.end())
{
token t = token(token_id, keyword, "_"); //关键词的token没有值
keepWords.insert({ keyword,t });
return true;
}
else {
return false;
}
}
void DFA::addState(State s) //添加状态
{
states.push_back(s);
}
void DFA::initStates(const int stateNum, vector<int>** stateMatrix, const string edgeList[]) {
//初始化state
// stateMatrix 矩阵 ,其中 从状态 i -> j 的边 的值为 edgeList[i][j]<<
for (int i = 0; i < stateNum; i++) {
states.push_back(State(i));
}
for (int i = 0; i < stateNum; i++) {
for (int j = 0; j < stateNum; j++) {
vector<int> v = *(*(stateMatrix + i) + j);
//vector<int> v = stateMatrix[i][j];
if (v.size()<=0) {
continue; // edge vector里没有数据
}
else {
for (int p = 0; int(p < v.size()); p++) {
states[i].addPtrs(edgeList[v[p]], &states[j]);
}
}
}
}
}
State& DFA::getState(int i) {
return (states[i]);
}
token DFA::isKeepWord(string keyword) {
auto iter = keepWords.find(keyword);
if (iter != keepWords.end())
{
return (*iter).second;
}
else {
token t = token(-1, "no key word", "_");
return t;
}
}
token DFA::scan(string str, string(*inputConvert)(char c)) {
// 扫描字符串,字符串的结尾必须是结束符 end, DFA的 states 0 是初始状态,第二个参数是一个函数指针,指向一个将字符映射为字符串边的函数,默认将字符直接转化为string
// 先判断是不是关键字
token t = isKeepWord(str);
if (t.getTokenID() != -1) {
return t;
}
State* state = &(states[0]); // 获得初始状态的指针
int index = 0;
while (state != nullptr) {
char c = str[index];
string ch = inputConvert(c);
if (index>=int(str.length())) {
//如果是终结符
int key = state->getStateID();
auto iter = tokenDict.find(key); //查找
if (iter != tokenDict.end()) {
//如果找到了
tokenItem ti = (*iter).second;
token t = token(ti.token_id, ti.token_name, str);
return t;
}
else {
cout << "lexical_error\n"; //词法错误
token t = token(-1, "lexical_error", str);
cout << t << endl;
return t;
}
}
//如果不是终结符,查找下一个状态
state = state->transfer(ch);
if (state == nullptr) {
//如果找不到的话,报错
cout << "lexical_error\n";
str.pop_back();
token t = token(-1, "lexical_error", str);
cout << t << endl;
return t;
}
index++; //读取下一个字符
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.