hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
77k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
68881e7d66e313cd139022a82a3a89cbcf64aefe
2,911
cpp
C++
deps/vision/src/vca_sample_echostring_server/vca_sample_echostring_server.cpp
MichaelJCaruso/vision-xa-nodejs-connect
ef13ccc2730bf1db07cb44106dfcfd020d843d82
[ "BSD-3-Clause" ]
30
2016-10-07T15:23:35.000Z
2020-03-25T20:01:30.000Z
src/vca_sample_echostring_server/vca_sample_echostring_server.cpp
MichaelJCaruso/vision-software-src-master
12b1b4f12a7531fe6e3cbb6861b40ac8e1985b92
[ "BSD-3-Clause" ]
30
2016-10-31T19:48:08.000Z
2021-04-28T01:31:53.000Z
software/src/master/src/vca_sample_echostring_server/vca_sample_echostring_server.cpp
c-kuhlman/vision
46b25f7c0da703c059acc8f0a2eac1d5badf9f6d
[ "BSD-3-Clause" ]
15
2016-10-07T16:44:13.000Z
2021-06-21T18:47:55.000Z
/***** Vca Sample Server *****/ /******************** ***** System ***** ********************/ #include "Vk.h" /****************** ***** Self ***** ******************/ /************************ ***** Supporting ***** ************************/ #include "Vca_VOneAppMain_.h" #include "Vca_VServerApplication.h" #include "vca_samples_iechostring.h" /********************************* ********************************* ***** ***** ***** VcaSamples::ThisApp ***** ***** ***** ********************************* *********************************/ namespace VcaSamples { class ThisApp : public Vca::VServerApplication { DECLARE_CONCRETE_RTT (ThisApp, Vca::VServerApplication); // Construction public: ThisApp (Context *pContext); // Destruction private: ~ThisApp (); // Roles public: using BaseClass::getRole; //---> IEchoString Role private: Vca::VRole<ThisClass,IEchoString> m_pIEchoString; public: void getRole (IEchoString::Reference &rpRole) { m_pIEchoString.getRole (rpRole); } // Role Callbacks //---> IEchoString public: void Echo ( IEchoString *pRole, IVReceiver<VString const&> *pClient, VString const &rString ); // Startup private: virtual bool start_() OVERRIDE; }; } /*************************** *************************** ***** Run Time Type ***** *************************** ***************************/ DEFINE_CONCRETE_RTT (VcaSamples::ThisApp); /************************** ************************** ***** Construction ***** ************************** **************************/ VcaSamples::ThisApp::ThisApp (Context *pContext) : BaseClass (pContext), m_pIEchoString (this) { } /************************* ************************* ***** Destruction ***** ************************* *************************/ VcaSamples::ThisApp::~ThisApp () { } /*********************** *********************** ***** Callbacks ***** *********************** ***********************/ void VcaSamples::ThisApp::Echo ( IEchoString *pRole, IVReceiver<VString const&> *pClient, VString const &rString ) { if (pClient) pClient->OnData (rString); } /********************* ********************* ***** ***** ***** Startup ***** ***** ***** ********************* *********************/ bool VcaSamples::ThisApp::start_() { if (BaseClass::start_() && !offerSelf ()) { fprintf (stderr, "Usage: No address to offer object.\n"); setExitStatus (ErrorExitValue); } return isStarting (); } /************************** ************************** ***** Main Program ***** ************************** **************************/ int main (int argc, char *argv[]) { Vca::VOneAppMain_<VcaSamples::ThisApp> iMain (argc, argv); return iMain.processEvents (); }
21.248175
96
0.40055
68899bb54200e7df5bcd9314f946c07d8e684b49
684
hpp
C++
508 - A4-spbspu-labs-2020-904-3/2/common/shape.hpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
5
2020-02-08T20:57:21.000Z
2021-12-23T06:24:41.000Z
508 - A4-spbspu-labs-2020-904-3/2/common/shape.hpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
2
2020-03-02T14:44:55.000Z
2020-11-11T16:25:33.000Z
508 - A4-spbspu-labs-2020-904-3/2/common/shape.hpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
4
2020-09-27T17:30:03.000Z
2022-02-16T09:48:23.000Z
#ifndef SHAPE_H #define SHAPE_H #include <memory> namespace gadzhiev { struct point_t; struct rectangle_t; class Shape { public: typedef std::shared_ptr<const Shape> ConstShapePtr; typedef std::shared_ptr<Shape> ShapePtr; virtual ~Shape() = default; virtual double getArea() const = 0; virtual rectangle_t getFrameRect() const = 0; virtual void move(const point_t& point) = 0; virtual void move(double dx, double dy) = 0; virtual void scale(double coefficient) = 0; virtual void rotate(double degrees) = 0; virtual point_t getCenter() const = 0; virtual void printNameAndParametersOfShape() const = 0; }; } #endif
21.375
59
0.685673
688a49523e06e10ee9fc273c7239431b67069106
911
cpp
C++
Libraries/plist/Sources/Format/ABPCommon.cpp
kolinkrewinkel/xcbuild
05ac2e574d96a3edff08df4d87b49f39931043f1
[ "BSD-2-Clause-NetBSD" ]
null
null
null
Libraries/plist/Sources/Format/ABPCommon.cpp
kolinkrewinkel/xcbuild
05ac2e574d96a3edff08df4d87b49f39931043f1
[ "BSD-2-Clause-NetBSD" ]
null
null
null
Libraries/plist/Sources/Format/ABPCommon.cpp
kolinkrewinkel/xcbuild
05ac2e574d96a3edff08df4d87b49f39931043f1
[ "BSD-2-Clause-NetBSD" ]
null
null
null
/** Copyright (c) 2015-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. */ #include <plist/Format/ABPCoderPrivate.h> #include <cstring> size_t ABPGetObjectsCount(ABPContext *context) { return (context != NULL ? context->trailer.objectsCount : 0); } void _ABPContextFree(ABPContext *context) { if (context->objects != NULL) { for (size_t n = 0; n < context->trailer.objectsCount; n++) { if (context->objects[n] != NULL) { context->objects[n]->release(); } } delete[] context->objects; } if (context->offsets != NULL) { delete[] context->offsets; } memset(context, 0, sizeof(*context)); }
23.973684
76
0.641054
688bad96be36f936d263c3eba93553365283e53f
4,767
hpp
C++
src/controller/DualAdvancedRunner.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
1
2021-09-25T18:18:14.000Z
2021-09-25T18:18:14.000Z
src/controller/DualAdvancedRunner.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
null
null
null
src/controller/DualAdvancedRunner.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
null
null
null
#ifndef DUALADVANCEDRUNNER_HPP #define DUALADVANCEDRUNNER_HPP #include <math.h> #include <iostream> #include <memory> #include <sstream> #include <string> #include "GameIO.hpp" #include "IPlayer.hpp" #include "NeuralNetwork.hpp" #include "Vec2.hpp" class DualAdvancedRunner : public IPlayer { public: static unsigned int const kNextCheckpoints = 2; struct PodTracker { PodData input = PodData(); unsigned int last_checkpoint = 0; unsigned int laps = 0; }; struct InputCheckpoint { double distance; double direction; }; struct InputVelocity { double magnitude; double direction; }; struct InputOtherPod { InputCheckpoint relative_position; InputVelocity relative_velocity; // InputCheckpoint next_checkpoints[kNextCheckpoints]; }; struct InputPod { InputCheckpoint next_checkpoints[kNextCheckpoints]; InputVelocity velocity; // InputOtherPod ally_pod; // InputOtherPod leading_enemy_pod; // InputOtherPod trailing_enemy_pod; }; struct NetworkInput { InputPod pod; }; struct OutputPod { double thrust; double direction; double should_shield; double should_boost; }; struct NetworkOutput { OutputPod pod; }; static unsigned int const kInputCount = sizeof(NetworkInput) / sizeof(double); static unsigned int const kOutputCount = sizeof(NetworkOutput) / sizeof(double); DualAdvancedRunner(NeuralNetwork& core) : boosts_left_(1), network_(core) {} void SetStreams(std::istream& input, std::ostream& output) override { input_ = &input; output_ = &output; }; void Setup() override { map_data_ = std::make_unique<MapData>(*input_); } void Turn() override { ReadInput(); std::vector<PodTracker const*> me = {&pods_[0], &pods_[1]}; std::vector<PodTracker const*> op = {&pods_[2], &pods_[3]}; unsigned int lead_op_pod = GetLeadPod(op); PodTracker const& op_lead = lead_op_pod == 0 ? pods_[2] : pods_[3]; PodTracker const& op_trail = lead_op_pod == 1 ? pods_[2] : pods_[3]; NeuralNetwork::Activations in(kInputCount); NetworkInput* input = reinterpret_cast<NetworkInput*>(in.data()); GetNetworkInput(*input, pods_[0].input, pods_[1].input, op_lead.input, op_trail.input); network_.SetInput(in); NeuralNetwork::Activations const* out0 = &network_.GetOutput(); NetworkOutput const* output = reinterpret_cast<NetworkOutput const*>(out0->data()); WriteNetworkOutput(*output, &me[0]->input); input = reinterpret_cast<NetworkInput*>(in.data()); GetNetworkInput(*input, pods_[1].input, pods_[0].input, op_lead.input, op_trail.input); network_.SetInput(in); out0 = &network_.GetOutput(); output = reinterpret_cast<NetworkOutput const*>(out0->data()); WriteNetworkOutput(*output, &me[1]->input); EndInput(); } private: void ReadInput() { pods_[0].input = PodData(*input_, 0, Owner::Me); pods_[1].input = PodData(*input_, 1, Owner::Me); pods_[2].input = PodData(*input_, 0, Owner::Opponent); pods_[3].input = PodData(*input_, 1, Owner::Opponent); for (auto& pod : pods_) { if (pod.input.next_checkpoint_id < static_cast<int>(pod.last_checkpoint)) { pod.last_checkpoint++; } } } void EndInput() { for (auto& pod : pods_) { pod.last_checkpoint = pod.input.next_checkpoint_id; } first_turn_latch_ = false; } static double constexpr kMaxDistance = 16000.0; static double constexpr kMaxSpeed = 1300.0; void GetNetworkInput(NetworkInput& input, PodData const& pod, PodData const& ally, PodData const& lead, PodData const& trail); void GetPodInput(InputPod& input, PodData const& pod, PodData const& ally, std::vector<PodData const*> const& op); static double constexpr kAbilityThresh = 0.0; void WriteNetworkOutput(NetworkOutput const& output, PodData const* pod); void WritePodOutput(OutputPod const& output, PodData const& pod); static double NormalizeAngle(double angle); double PodAngle(PodData const& pod); void GetNextCheckpoints(InputCheckpoint* checkpoints, PodData const& from, PodData const& perspective); void GetNextCheckpoint(InputCheckpoint& checkpoint, Vec2 const& next, PodData const& from); void GetVelocity(InputVelocity& velocity, PodData const& of, Vec2 const& ref_velocity, double ref_angle); void GetOtherPod(InputOtherPod& output, PodData const& perspective, PodData const& other); unsigned int GetLeadPod(std::vector<PodTracker const*> pods); int boosts_left_; bool first_turn_latch_ = true; PodTracker pods_[4]; std::unique_ptr<MapData> map_data_; std::istream* input_; std::ostream* output_; NeuralNetwork& network_; }; #endif
32.428571
93
0.696665
68932b764c381906b5d31e306e63332ed7f38ca8
10,499
cpp
C++
drishti/camerapathnode.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
118
2016-11-01T06:01:44.000Z
2022-03-30T05:20:19.000Z
drishti/camerapathnode.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
56
2016-09-30T09:29:36.000Z
2022-03-31T17:15:32.000Z
drishti/camerapathnode.cpp
shouhengli/drishti
46558d12adcc1d365b7e2125d28190e3be2181c3
[ "MIT" ]
28
2016-07-31T23:48:51.000Z
2021-05-25T05:32:47.000Z
#include "camerapathnode.h" CameraPathNode::CameraPathNode(Vec pos, Quaternion rot) { m_mf = new ManipulatedFrame(); // disable camera manipulation by mouse m_mf->removeFromMouseGrabberPool(); m_mf->setPosition(pos); m_mf->setOrientation(rot); m_constraints = new LocalConstraint(); m_constraints->setTranslationConstraintType(AxisPlaneConstraint::FREE); m_mf->setConstraint(m_constraints); m_markForDelete = false; connect(m_mf, SIGNAL(modified()), this, SLOT(nodeModified())); } void CameraPathNode::nodeModified() { emit modified(); } bool CameraPathNode::markedForDeletion() { return m_markForDelete; } Vec CameraPathNode::position() { return m_mf->position(); } void CameraPathNode::setPosition(Vec pos) { m_mf->setPosition(pos); } Quaternion CameraPathNode::orientation() { return m_mf->orientation(); } void CameraPathNode::setOrientation(Quaternion rot) { m_mf->setOrientation(rot); } int CameraPathNode::keyPressEvent(QKeyEvent *event, bool &lookFrom) { lookFrom = false; if (m_mf->grabsMouse()) { if (event->key() == Qt::Key_Space) { lookFrom = true; return 1; } else if (event->modifiers() & Qt::ShiftModifier) { // set rotational constraints if (event->key() == Qt::Key_X) { m_constraints->setRotationConstraintType(AxisPlaneConstraint::AXIS); m_constraints->setRotationConstraintDirection(Vec(1,0,0)); m_mf->setConstraint(m_constraints); return 1; } else if (event->key() == Qt::Key_Y) { m_constraints->setRotationConstraintType(AxisPlaneConstraint::AXIS); m_constraints->setRotationConstraintDirection(Vec(0,1,0)); m_mf->setConstraint(m_constraints); return 1; } else if (event->key() == Qt::Key_Z) { m_constraints->setRotationConstraintType(AxisPlaneConstraint::AXIS); m_constraints->setRotationConstraintDirection(Vec(0,0,1)); m_mf->setConstraint(m_constraints); return 1; } else if (event->key() == Qt::Key_W) { m_constraints->setRotationConstraintType(AxisPlaneConstraint::FREE); m_mf->setConstraint(m_constraints); return 1; } } else if (event->modifiers() == Qt::NoModifier) { // set translational constraints if (event->key() == Qt::Key_Delete || event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Backtab) { m_markForDelete = true; } else if (event->key() == Qt::Key_X) { m_constraints->setTranslationConstraintType(AxisPlaneConstraint::AXIS); m_constraints->setTranslationConstraintDirection(Vec(1,0,0)); m_mf->setConstraint(m_constraints); return 1; } else if (event->key() == Qt::Key_Y) { m_constraints->setTranslationConstraintType(AxisPlaneConstraint::AXIS); m_constraints->setTranslationConstraintDirection(Vec(0,1,0)); m_mf->setConstraint(m_constraints); return 1; } else if (event->key() == Qt::Key_Z) { m_constraints->setTranslationConstraintType(AxisPlaneConstraint::AXIS); m_constraints->setTranslationConstraintDirection(Vec(0,0,1)); m_mf->setConstraint(m_constraints); return 1; } else if (event->key() == Qt::Key_W) { m_constraints->setTranslationConstraintType(AxisPlaneConstraint::FREE); m_mf->setConstraint(m_constraints); return 1; } } } return 0; } void CameraPathNode::draw(float widgetSize) { glPushMatrix(); glMultMatrixd(m_mf->matrix()); float scale = widgetSize; if (m_mf->grabsMouse()) scale = widgetSize * 1.5; glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glLineWidth(1); if (m_mf->grabsMouse()) glColor3f(1, 1, 0); else glColor3f(0.6f, 1, 1); glBegin(GL_LINES); glVertex3f(0, 0, 0); glVertex3f(-scale, -scale, -scale); glVertex3f(0, 0, 0); glVertex3f(-scale, scale, -scale); glVertex3f(0, 0, 0); glVertex3f(scale, scale, -scale); glVertex3f(0, 0, 0); glVertex3f(scale, -scale, -scale); glEnd(); glBegin(GL_LINE_STRIP); glVertex3f(-scale, -scale, -scale); glVertex3f(-scale, scale, -scale); glVertex3f(scale, scale, -scale); glVertex3f(scale, -scale, -scale); glVertex3f(-scale, -scale, -scale); glEnd(); //glLineWidth(3); if (m_mf->grabsMouse()) glColor3f(0.5, 1, 0.5f); else glColor3f(1, 1, 0.8f); glBegin(GL_LINES); glVertex3f(0, 0, 0); glVertex3f(-scale, -scale, -scale); glVertex3f(0, 0, 0); glVertex3f(-scale, scale, -scale); glVertex3f(0, 0, 0); glVertex3f(scale, scale, -scale); glVertex3f(0, 0, 0); glVertex3f(scale, -scale, -scale); glEnd(); glBegin(GL_LINE_STRIP); glVertex3f(-scale, -scale, -scale); glVertex3f(-scale, scale, -scale); glVertex3f(scale, scale, -scale); glVertex3f(scale, -scale, -scale); glVertex3f(-scale, -scale, -scale); glEnd(); // draw lookup vector float arrowscale = scale/3; glBegin(GL_QUADS); glVertex3f(-arrowscale/2, scale, -scale); glVertex3f(-arrowscale/2, scale+arrowscale/2, -scale); glVertex3f( arrowscale/2, scale+arrowscale/2, -scale); glVertex3f( arrowscale/2, scale, -scale); glEnd(); glBegin(GL_TRIANGLES); glVertex3f(-arrowscale/2, scale+arrowscale/2, -scale); glVertex3f( arrowscale/2, scale+arrowscale/2, -scale); glVertex3f( 0, scale+arrowscale, -scale); glEnd(); glEnable(GL_LIGHTING); glColor3f(1.0f, 0.5f, 0.2f); if (m_constraints->translationConstraintType() == AxisPlaneConstraint::AXIS) { Vec dir = m_constraints->translationConstraintDirection(); if (dir.norm() > 0) dir.normalize(); if ((dir-Vec(0,0,1)).norm() < 0.001) { dir *= scale; QGLViewer::drawArrow(Vec(0,0,-scale), dir*0.5f+Vec(0,0,-scale), 0.5f, 12); QGLViewer::drawArrow(Vec(0,0,-scale), -dir*0.5f+Vec(0,0,-scale), 0.5f, 12); } else { dir *= scale; QGLViewer::drawArrow(dir+Vec(0,0,-scale), dir*1.3f+Vec(0,0,-scale), 0.5f, 12); QGLViewer::drawArrow(-dir+Vec(0,0,-scale), -dir*1.3f+Vec(0,0,-scale), 0.5f, 12); } } else if (m_constraints->translationConstraintType() == AxisPlaneConstraint::FREE) { Vec Xaxis, Yaxis, Zaxis; Xaxis = scale*Vec(1,0,0); Yaxis = scale*Vec(0,1,0); Zaxis = scale*Vec(0,0,1); QGLViewer::drawArrow( Xaxis+Vec(0,0,-scale), Xaxis*1.3f+Vec(0,0,-scale), 0.5f, 12); QGLViewer::drawArrow(-Xaxis+Vec(0,0,-scale), -Xaxis*1.3f+Vec(0,0,-scale), 0.5f, 12); QGLViewer::drawArrow( Yaxis+Vec(0,0,-scale), Yaxis*1.3f+Vec(0,0,-scale), 0.5f, 12); QGLViewer::drawArrow(-Yaxis+Vec(0,0,-scale), -Yaxis*1.3f+Vec(0,0,-scale), 0.5f, 12); QGLViewer::drawArrow(Vec(0,0,0)+Vec(0,0,-scale), Zaxis*0.3f+Vec(0,0,-scale), 0.5f, 12); QGLViewer::drawArrow(Vec(0,0,0)+Vec(0,0,-scale), -Zaxis*0.3f+Vec(0,0,-scale), 0.5f, 12); } glDisable(GL_LIGHTING); glColor3f(0.3f, 0.8f, 0.6f); if (m_constraints->rotationConstraintType() == AxisPlaneConstraint::AXIS) { Vec a1, a2; Vec dir = m_constraints->rotationConstraintDirection(); if (dir.norm() > 0) dir.normalize(); a1 = dir.orthogonalVec(); a2 = dir^a1; dir *= scale; a1 *= 0.2f*scale; a2 *= 0.2f*scale; int nticks; float angle, astep; nticks = 50; astep = 6.28f/nticks; Vec vp[100]; angle = 0.0f; for(int t=0; t<=nticks; t++) { vp[t] = a1*cos(angle) + a2*sin(angle); angle += astep; } Vec shift = Vec(0,0,-scale); shift += 0.2f*dir; //---------------------------- glColor3f(1, 1, 1); glLineWidth(1); glBegin(GL_LINE_STRIP); for(int t=0; t<=nticks; t++) { Vec v = vp[t] + shift; glVertex3f(v.x, v.y, v.z); } glEnd(); glLineWidth(3); glBegin(GL_LINE_STRIP); for(int t=0; t<=nticks; t++) { float frc = (float)t/(float)nticks; Vec v = vp[t] + shift; glColor3f(1-frc, 0.5-0.5*frc, 1); glVertex3f(v.x, v.y, v.z); } glEnd(); // draw arrows glColor3f(0.9f, 0.8f, 0.6f); Vec v0, v1, v2; glBegin(GL_TRIANGLES); for(int t=0; t<nticks-4; t+=5) { v0 = vp[t]+shift; v1 = vp[t+2]+shift+0.02f*dir; v2 = vp[t+2]+shift-0.02f*dir; glVertex3f(v0.x, v0.y, v0.z); glVertex3f(v1.x, v1.y, v1.z); glVertex3f(v2.x, v2.y, v2.z); } glEnd(); //---------------------------- shift = Vec(0,0,-scale); shift -= 0.2f*dir; //---------------------------- glColor3f(1, 1, 1); glLineWidth(1); glBegin(GL_LINE_STRIP); for(int t=0; t<=nticks; t++) { Vec v = vp[t] + shift; glVertex3f(v.x, v.y, v.z); } glEnd(); glLineWidth(3); glBegin(GL_LINE_STRIP); for(int t=0; t<=nticks; t++) { float frc = (float)t/(float)nticks; Vec v = vp[t] + shift; glColor3f(1-frc, 0.5-0.5*frc, 1); glVertex3f(v.x, v.y, v.z); } glEnd(); // draw arrows glColor3f(0.9f, 0.8f, 0.6f); glBegin(GL_TRIANGLES); for(int t=0; t<nticks-4; t+=5) { v0 = vp[t+2]+shift; v1 = vp[t]+shift+0.02f*dir; v2 = vp[t]+shift-0.02f*dir; glVertex3f(v0.x, v0.y, v0.z); glVertex3f(v1.x, v1.y, v1.z); glVertex3f(v2.x, v2.y, v2.z); } glEnd(); //---------------------------- } else if (m_constraints->rotationConstraintType() == AxisPlaneConstraint::FREE) { int nticks; float angle, astep; nticks = 50; astep = 6.28f/nticks; angle = 0.0f; glLineWidth(1); glColor3f(0.7f, 0.7f, 0.7f); glBegin(GL_LINE_STRIP); for(int t=0; t<=nticks; t++) { float frc = (float)t/(float)nticks; Vec v, v1, v2; v = Vec(cos(angle),sin(angle), 0); v *= 0.5f*scale; angle += astep; glVertex3f(v.x, v.y, v.z); } glEnd(); glBegin(GL_LINE_STRIP); for(int t=0; t<=nticks; t++) { float frc = (float)t/(float)nticks; Vec v, v1, v2; v = Vec(cos(angle),sin(angle), 0); v *= 0.5f*scale; angle += astep; glVertex3f(v.x, v.z, v.y); } glEnd(); glBegin(GL_LINE_STRIP); for(int t=0; t<=nticks; t++) { float frc = (float)t/(float)nticks; Vec v, v1, v2; v = Vec(cos(angle),sin(angle), 0); v *= 0.5f*scale; angle += astep; glVertex3f(v.z, v.x, v.y); } glEnd(); } glLineWidth(1); glPopMatrix(); }
25.057279
83
0.590151
689f57399ac5c28a6bed7bbb043bcacfc45adc8d
1,023
cpp
C++
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.36.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.36.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
CppPrimer/CppPrimer-Exercises/CppPrimer-Ch03/Exercise3.36.cpp
alaxion/Learning
4b12b1603419252103cd933fdbfc4b2faffb6d00
[ "MIT" ]
null
null
null
// Exercise3.36.cpp // Ad // Write a program to compare two arrays for equality, then write a similar to compare vectors. #include <iostream> #include <vector> #include <iterator> using std::cin; using std::cout; using std::endl; int main() { // to compare two arrays int arr1[10]{}, arr2[10]{}; int *pa1{arr1}, *pa2{arr2}; for (; pa1 != std::end(arr1) && pa2 != std::end(arr2); ++pa1, ++pa2) { if (*pa1 != *pa2) break; } if (pa1 != std::end(arr1)) { if (*pa1 > *pa2) cout << "arr1 > arr2" << endl; else cout << "arr1 < arr2" << endl; } else { cout << "arr1 == arr2" << endl; } // to compare two vectors std::vector<int> vec1{}, vec2{}; if (vec1 > vec2) { cout << "vec1 > vec2" << endl; } else if (vec1 < vec2) { cout << "vec1 < vec2" << endl; } else { cout << "vec1 == vec2" << endl; } // pause cin.get(); return 0; }
20.058824
96
0.475073
68a223fcb0bad703e33b65855153863e1d03fe20
542
cpp
C++
test/main.cpp
chenxu2048/DockerClientpp
81792fb0d84028b059983e1a08f12edf6e8c6b32
[ "MIT" ]
5
2017-05-23T16:32:15.000Z
2019-02-16T14:27:51.000Z
test/main.cpp
chenxu2048/DockerClientpp
81792fb0d84028b059983e1a08f12edf6e8c6b32
[ "MIT" ]
5
2019-07-13T23:14:52.000Z
2019-07-16T20:46:53.000Z
test/main.cpp
fedemengo/DockerClientpp
a83a1a992f081b5d25dccc2b9530308105e5c9c4
[ "MIT" ]
4
2017-11-14T14:00:58.000Z
2020-07-23T07:16:01.000Z
#include "gtest/gtest.h" class GlobalEnv : public ::testing::Environment { public: virtual void SetUp() { if (std::system("docker pull busybox:1.26")) { throw std::runtime_error("Cannot pull busybox"); } std::system("docker run -dt --name test busybox:1.26 > /dev/null 2>&1"); } virtual void TearDown() { std::system("docker rm -f test > /dev/null 2>&1"); } }; int main(int argc, char *argv[]) { AddGlobalTestEnvironment(new GlobalEnv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.809524
76
0.645756
68a49f934efc4cfdc2f5e354471ec32d42b79391
10,418
cpp
C++
crud-example/request_processor.cpp
Stiffstream/restinio-crud-example
3e3e3a859b9743a870b20dda7da14360ccdae3ce
[ "BSD-3-Clause" ]
4
2019-10-07T21:23:55.000Z
2020-02-05T16:10:57.000Z
crud-example/request_processor.cpp
Stiffstream/restinio-crud-example
3e3e3a859b9743a870b20dda7da14360ccdae3ce
[ "BSD-3-Clause" ]
1
2020-02-04T05:14:23.000Z
2020-02-04T09:45:17.000Z
crud-example/request_processor.cpp
Stiffstream/restinio-crud-example
3e3e3a859b9743a870b20dda7da14360ccdae3ce
[ "BSD-3-Clause" ]
1
2020-02-05T16:11:00.000Z
2020-02-05T16:11:00.000Z
#include "request_processor.hpp" #include <restinio/helpers/http_field_parsers/content-type.hpp> #include <restinio/helpers/file_upload.hpp> #include <fmt/format.h> #include <stdexcept> namespace crud_example { namespace errors { const int unknow_error = -1; const int json_dto_error = 1; const int sqlite_error = 2; const int invalid_pet_id = 3; const int invalid_request = 4; } /* namespace errors */ // Type of object to be returned in a HTTP-response for a failed request. struct failure_description_t { int m_error_code; std::string m_description; template<typename Json_Io> void json_io(Json_Io & io) { io & json_dto::mandatory("code", m_error_code) & json_dto::mandatory("description", m_description); } }; // A type of exception to be thrown in the case of some failure // during processing of a request. // // NOTE: this error is related to some business-logic problem. class request_processing_failure_t : public std::runtime_error { restinio::http_status_line_t m_response_status; failure_description_t m_failure_description; public: request_processing_failure_t( restinio::http_status_line_t response_status, failure_description_t failure_description) : std::runtime_error("request processing failure") , m_response_status{std::move(response_status)} , m_failure_description{std::move(failure_description)} {} const auto & response_status() const noexcept { return m_response_status; } const auto & failure_description() const noexcept { return m_failure_description; } }; namespace { // Helper function for wrapping request processing routine and making // the response in dependency of processing result. template<typename F> void wrap_request_processing( const restinio::request_handle_t & req, F && functor) { std::string response_body; auto response_status = restinio::status_ok(); try { response_body = json_dto::to_json(functor()); } catch(const request_processing_failure_t & x) { response_status = x.response_status(); response_body = json_dto::to_json(x.failure_description()); } catch(...) { response_status = restinio::status_internal_server_error(); response_body = json_dto::to_json( failure_description_t{ errors::unknow_error, "unexpected application failure"}); } req->create_response(response_status) .append_header_date_field() .append_header(restinio::http_field::content_type, "application/json") .set_body(response_body) .done(); } // Helper function for wrapping actual business-logic code and intercept // errors related to JSON-processing, interactions with DB and so on. // All such errors are converted into request_processing_failure_t. template<typename F> auto wrap_business_logic_action(F && functor) { try { return functor(); } catch(const json_dto::ex_t & x) { throw request_processing_failure_t( restinio::status_bad_request(), failure_description_t{ errors::json_dto_error, fmt::format("json-related-error: {}", x.what()) }); } catch(const SQLite::Exception & x) { throw request_processing_failure_t( restinio::status_internal_server_error(), failure_description_t{ errors::sqlite_error, fmt::format("sqlite-related-error: error_code={}, " "ext_error_code={}, desc='{}'", x.getErrorCode(), x.getExtendedErrorCode(), x.getErrorStr()) }); } } enum class create_new_mode_t { single, batch }; restinio::expected_t<create_new_mode_t, request_processing_failure_t> detect_create_new_mode( const restinio::request_handle_t & req) { const auto unexpected = [](const char * msg) { return restinio::make_unexpected(request_processing_failure_t{ restinio::status_bad_request(), failure_description_t{errors::invalid_request, msg} }); }; // Content-Type HTTP-field should be present. const auto content_type_raw = req->header().opt_value_of( restinio::http_field::content_type); if(!content_type_raw) return unexpected("Content-Type HTTP-field is absent"); // Content-Type should have right format. namespace hfp = restinio::http_field_parsers; const auto content_type = hfp::content_type_value_t::try_parse(*content_type_raw); if(!content_type) return unexpected("unable to parse Content-Type HTTP-field"); // If Content-Type is "application/json" then we assume that it is // a request for addition of single pet. if("application" == content_type->media_type.type && "json" == content_type->media_type.subtype) return create_new_mode_t::single; // If Content-Type if "multipart/form-data" then we assume that it is // a request for batch addition of new pets. if("multipart" == content_type->media_type.type && "form-data" == content_type->media_type.subtype) return create_new_mode_t::batch; return unexpected("unsupported value of Content-Type"); } } /* namespace anonymous */ request_processor_t::request_processor_t(db_layer_t & db) : m_db{db} { } void request_processor_t::on_create_new_pet( const restinio::request_handle_t & req) { auto mode = detect_create_new_mode(req); if(mode) { switch(*mode) { case create_new_mode_t::single: wrap_request_processing(req, [&] { return create_new_pet(req); }); break; case create_new_mode_t::batch: wrap_request_processing(req, [&] { return batch_create_new_pets(req); }); break; } } else { const auto & error = mode.error(); req->create_response(error.response_status()) .append_header_date_field() .append_header(restinio::http_field::content_type, "application/json") .set_body(json_dto::to_json(error.failure_description())) .done(); } } void request_processor_t::on_get_all_pets( const restinio::request_handle_t & req) { wrap_request_processing(req, [&] { return get_all_pets(); }); } void request_processor_t::on_get_specific_pet( const restinio::request_handle_t & req, pet_id_t pet_id) { wrap_request_processing(req, [&] { return get_specific_pet(pet_id); }); } void request_processor_t::on_patch_specific_pet( const restinio::request_handle_t & req, pet_id_t pet_id) { wrap_request_processing(req, [&] { return patch_specific_pet(req, pet_id); }); } void request_processor_t::on_delete_specific_pet( const restinio::request_handle_t & req, pet_id_t pet_id) { wrap_request_processing(req, [&] { return delete_specific_pet(pet_id); }); } void request_processor_t::on_make_batch_upload_form( const restinio::request_handle_t & req) { req->create_response() .append_header_date_field() .append_header(restinio::http_field::content_type, "text/html; charset=utf-8") .set_body( R"---( <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Select file with batch info of new pets</title> </head> <body> <p>Please select file to be uploaded to server.</p> <form method="post" action="http://localhost:8080/all/v1/pets" enctype="multipart/form-data"> <p><input type="file" name="file" id="file"></p> <p><button type="submit">Submit</button></p> </form> </body> </html> )---" ) .done(); } model::pet_identity_t request_processor_t::create_new_pet( const restinio::request_handle_t & req) { return wrap_business_logic_action([&] { return model::pet_identity_t{ m_db.create_new_pet( json_dto::from_json<model::pet_without_id_t>(req->body())) }; }); } model::bunch_of_pet_ids_t request_processor_t::batch_create_new_pets( const restinio::request_handle_t & req) { using namespace restinio::file_upload; return wrap_business_logic_action([&]() { // Content of file with new pets should be found in // the request's body. // // NOTE: it's safe to store reference to uploaded file's content // as string_view because uploaded_content won't outlive the // request object with the actual uploaded data. // restinio::string_view_t uploaded_content; const auto result = enumerate_parts_with_files(*req, [this, &uploaded_content](part_description_t part) { if("file" == part.name) { uploaded_content = part.body; return handling_result_t::stop_enumeration; } else return handling_result_t::continue_enumeration; }); if(!result || uploaded_content.empty()) // There is no uploaded file or request's body has invalid format. throw request_processing_failure_t( restinio::status_bad_request(), failure_description_t{ errors::invalid_request, "no file with new pets found" }); // The content of uploaded file should be parsed. const auto pets = json_dto::from_json<model::bunch_of_pets_without_id_t>( json_dto::make_string_ref( uploaded_content.data(), uploaded_content.size())); return m_db.create_bunch_of_pets(pets); }); } model::all_pets_t request_processor_t::get_all_pets() { return wrap_business_logic_action([&] { return m_db.get_all_pets(); }); } model::pet_with_id_t request_processor_t::get_specific_pet( pet_id_t pet_id) { return wrap_business_logic_action([&] { auto pet = m_db.get_pet(pet_id); if(!pet) throw request_processing_failure_t( restinio::status_not_found(), failure_description_t{ errors::invalid_pet_id, fmt::format("pet with this ID not found, ID={}", pet_id) }); return std::move(*pet); }); } model::pet_identity_t request_processor_t::patch_specific_pet( const restinio::request_handle_t & req, pet_id_t pet_id) { return wrap_business_logic_action([&] { const auto update_result = m_db.update_pet( pet_id, json_dto::from_json<model::pet_without_id_t>(req->body())); if(db_layer_t::update_result_t::updated != update_result) throw request_processing_failure_t( restinio::status_not_found(), failure_description_t{ errors::invalid_pet_id, fmt::format("pet with this ID not found, ID={}", pet_id) }); return model::pet_identity_t{pet_id}; }); } model::pet_identity_t request_processor_t::delete_specific_pet( pet_id_t pet_id) { return wrap_business_logic_action([&] { const auto delete_result = m_db.delete_pet(pet_id); if(db_layer_t::delete_result_t::deleted != delete_result) throw request_processing_failure_t( restinio::status_not_found(), failure_description_t{ errors::invalid_pet_id, fmt::format("pet with this ID not found, ID={}", pet_id) }); return model::pet_identity_t{pet_id}; }); } } /* namespace crud_example */
25.98005
93
0.727683
68a4dc075d7caec1988290fd3a4cc07c184c3c83
862
cpp
C++
Regex/Problem27/main.cpp
akaseon/ModernCppChallengeStudy
1630f8cf5b3656171ee656738a908619cee6e718
[ "MIT" ]
null
null
null
Regex/Problem27/main.cpp
akaseon/ModernCppChallengeStudy
1630f8cf5b3656171ee656738a908619cee6e718
[ "MIT" ]
null
null
null
Regex/Problem27/main.cpp
akaseon/ModernCppChallengeStudy
1630f8cf5b3656171ee656738a908619cee6e718
[ "MIT" ]
null
null
null
//#include <gsl/gsl> #include <vector> #include <string> #include <iostream> std::vector<std::string> splittingString( std::string aFrom, std::string aDelimiter ) { std::vector<std::string> sTo; char * sToken = NULL; sToken = std::strtok( const_cast<char*>( aFrom.c_str() ), aDelimiter.c_str() ); while( sToken != NULL ) { sTo.push_back( sToken ); sToken = std::strtok( NULL, aDelimiter.c_str() ); } return sTo; } int main(int argc, char* argv[]) { std::string sString( "this,is.a sample!!" ); std::string sDelimiter( ",.! "); std::vector<std::string> sResult; sResult = splittingString( sString, sDelimiter ); for( auto sToken: sResult ) std::cout << sToken << "\n"; return 0; }
23.297297
68
0.533643
68a4e871e0fe4dbd179de98e9eb77f3df31dcdd0
795
cpp
C++
Game/Sources/State/PausedState.cpp
YvesHenri/Chico
e583a9995cd6e26fe198b21b9c7996c3199c4ff3
[ "MIT" ]
6
2017-01-09T13:19:56.000Z
2021-11-15T11:18:35.000Z
Game/Sources/State/PausedState.cpp
YvesHenri/Chico
e583a9995cd6e26fe198b21b9c7996c3199c4ff3
[ "MIT" ]
null
null
null
Game/Sources/State/PausedState.cpp
YvesHenri/Chico
e583a9995cd6e26fe198b21b9c7996c3199c4ff3
[ "MIT" ]
null
null
null
#include "../../Includes/State/PausedState.h" PausedState::PausedState() { overlap = sf::RectangleShape(sf::Vector2f(800.f, 600.f)); overlap.setFillColor(sf::Color(0, 0, 0, 185)); } void PausedState::onEnter() { WARN("-----> Paused"); } void PausedState::onLeave() { WARN("<----- Paused"); } void PausedState::draw(sf::RenderTarget& target, sf::RenderStates states) const { /* // Draw the previous state first if (m_previous) { m_previous->draw(target, states); } */ // The overlap rectangle has to be drawn using the fixed view sf::View fixed = target.getDefaultView(); sf::View active = target.getView(); target.setView(fixed); target.draw(overlap, states); target.setView(active); } sts::StateResult PausedState::update(float dt) { return sts::StateResult::Running; }
19.875
79
0.68805
68ae2dba87fdef7d2b77799274d10e9e024b8dd3
1,280
cpp
C++
Onegin/sorting.cpp
Great1ng/Huawei_Tasks
21f855f30df9806f81d5cedf8cd314a633174be1
[ "CC0-1.0" ]
null
null
null
Onegin/sorting.cpp
Great1ng/Huawei_Tasks
21f855f30df9806f81d5cedf8cd314a633174be1
[ "CC0-1.0" ]
null
null
null
Onegin/sorting.cpp
Great1ng/Huawei_Tasks
21f855f30df9806f81d5cedf8cd314a633174be1
[ "CC0-1.0" ]
null
null
null
#include "sorting.h" void mergesort(void *base, size_t count, size_t type, comparator comp) { if (count == 1) return; char *bt_base = (char *) base; size_t lcount = count / 2; size_t rcount = count - lcount; mergesort(bt_base, lcount, type, comp); mergesort(bt_base + lcount * type, rcount, type, comp); merge_arrays(base, lcount, bt_base + lcount * type, rcount, type, comp); } void merge_arrays(void *lbase, size_t lcnt, void *rbase, size_t rcnt, size_t type, comparator comp) { char *tmp = (char *) calloc(lcnt + rcnt, type); char *bt_lbase = (char *) lbase; char *bt_rbase = (char *) rbase; char *lptr = bt_lbase; char *rptr = bt_rbase; size_t sorted_cnt = 0; while (lptr < bt_lbase + lcnt * type) { while (rptr < bt_rbase + rcnt * type && comp(rptr, lptr) < 0) { memcpy(tmp + sorted_cnt * type, rptr, type); rptr += type; sorted_cnt++; } memcpy(tmp + sorted_cnt * type, lptr, type); lptr += type; sorted_cnt++; } while (rptr < bt_rbase + rcnt * type) { memcpy(tmp + sorted_cnt * type, rptr, type); rptr += type; sorted_cnt++; } memcpy(bt_lbase, tmp, (lcnt + rcnt) * type); free(tmp); }
26.122449
101
0.575781
68b7fb59d66d1da145b5b6fb694765973d6465ee
607
hpp
C++
src/Missile.hpp
michal-tangri/sgd-game
aa4cf5704a9ca75b7b9c06b6096ae707607a8539
[ "MIT" ]
null
null
null
src/Missile.hpp
michal-tangri/sgd-game
aa4cf5704a9ca75b7b9c06b6096ae707607a8539
[ "MIT" ]
null
null
null
src/Missile.hpp
michal-tangri/sgd-game
aa4cf5704a9ca75b7b9c06b6096ae707607a8539
[ "MIT" ]
null
null
null
#ifndef __MISSILE_CLASS_HPP__ #define __MISSILE_CLASS_HPP__ #include "GameObject.hpp" #include "Tile.hpp" #include <array> class Missile : public GameObject { public: enum MissileOrigin { MISSILE_ORIGIN_PLAYER, MISSILE_ORIGIN_ENEMY }; Missile(MissileOrigin origin); void update(double dt, Tile level[24][30]); void render(SDL_Renderer* r) override; void initialize(double pos_x, double pos_y, double acceleration_x, SDL_Renderer* r);\ ObjectType type = ObjectType::LIGUNIA_MISSILE; MissileOrigin origin; private: double acceleration_x; }; #endif
19.580645
89
0.723229
68b9e96bc998aa6ee10b2b90ee56dcf8bcade8f1
3,436
cpp
C++
src/homie.cpp
dgomes/homie
9f92756be5c2b95933d31780c9a9608d4ec5a2b0
[ "MIT" ]
4
2018-08-23T11:35:28.000Z
2020-11-19T00:25:19.000Z
src/homie.cpp
dgomes/homie
9f92756be5c2b95933d31780c9a9608d4ec5a2b0
[ "MIT" ]
null
null
null
src/homie.cpp
dgomes/homie
9f92756be5c2b95933d31780c9a9608d4ec5a2b0
[ "MIT" ]
1
2020-03-22T22:09:14.000Z
2020-03-22T22:09:14.000Z
#include "homie.h" Homie::Homie(PubSubClient &client, String deviceID) { this->_mqttClient = &client; this->deviceID = deviceID; this->nodes = NULL; this->nodes_size = 0; } Homie::Homie(PubSubClient &client, String deviceID, const char *nodes[], size_t nodes_size) { this->_mqttClient = &client; this->deviceID = deviceID; this->nodes = nodes; this->nodes_size = nodes_size; } String IPaddress2String(byte *address) { return String(address[0]) + "." + String(address[1]) + "." + String(address[2]) + "." + String(address[3]); } void Homie::setup(byte *localip, MQTT_CALLBACK_SIGNATURE) { String localip_str = IPaddress2String(localip); setup(localip_str, callback); } void Homie::setup(String localip, MQTT_CALLBACK_SIGNATURE) { this->localip = localip; this->callback = callback; this->_mqttClient->setCallback(callback); this->_setupCalled = true; this->connect(); } void Homie::setBrand(String name) { this->brandname = name; } void Homie::setFirmware(String name, String version) { this->firmware_name = name; this->firmaware_version = version; } bool Homie::publish_property(String property, String value) { String prop = String(F(MQTT_BASE_TOPIC)) + deviceID + String("/") + property; return this->_mqttClient->publish(prop.c_str(), value.c_str(), true); } bool Homie::subscribe_property(String property) { String prop = String(F(MQTT_BASE_TOPIC)) + deviceID + String("/") + property; return this->_mqttClient->subscribe(prop.c_str()); } String Homie::base_topic() { return String(MQTT_BASE_TOPIC) + deviceID + String("/"); } bool Homie::connect() { if(!this->_setupCalled) return false; String online = String(MQTT_BASE_TOPIC) + deviceID + String(F("/$online")); if(!this->_mqttClient->connect(this->deviceID.c_str(), NULL, NULL, online.c_str(), 0, true, "false")) return false; publish_property(String(F("$online")), "true"); publish_property(String(F("$name")), this->brandname); publish_property(String(F("$localip")), this->localip); publish_property(String(F("$fwname")), this->firmware_name); publish_property(String(F("$fwversion")), this->firmaware_version); unsigned i = 0; if (this->nodes_size > 0) { String nodes_str; for (; i< this->nodes_size-1; i++) { nodes_str += String(nodes[i])+ String(","); subscribe_property(String(nodes[i]) + "/set"); } nodes_str += String(this->nodes[i]); subscribe_property(String(nodes[i]) + "/set"); if(!publish_property(String("$nodes"), nodes_str)) { publish_property(String("$nodes"), F("error: too many")); } publish_property(String("$debug"), String(F("#nodes subscribed: "))+String(i+1)); } return true; } bool Homie::loop() { if(!this->_mqttClient->connected()) { long now = millis(); if (now - this->lastReconnectAttempt > RECONNECT_DELAY) { this->lastReconnectAttempt = now; // Attempt to reconnect if (this->connect()) { this->lastReconnectAttempt = 0; return false; } } } if ((millis()/UPTIME_REPORT_PERIOD) != time) { time = millis()/UPTIME_REPORT_PERIOD; publish_property(String(F("$uptime")), String(millis()/1000)); } this->_mqttClient->loop(); return true; }
30.40708
105
0.630384
68ba56c90c62dc771c66c7fe4bfea2ed7d3a1b5a
8,576
cpp
C++
src/hyposystem.cpp
HypoModel/HypoModBase
29572f98202780c9a8b25cffe80761fedb35aa1a
[ "MIT" ]
null
null
null
src/hyposystem.cpp
HypoModel/HypoModBase
29572f98202780c9a8b25cffe80761fedb35aa1a
[ "MIT" ]
null
null
null
src/hyposystem.cpp
HypoModel/HypoModBase
29572f98202780c9a8b25cffe80761fedb35aa1a
[ "MIT" ]
null
null
null
#include "hypomodel.h" //#include "hypomain.h" //#include "hypopanels.h" OptionPanel::OptionPanel(HypoMain *main, const wxString & title) : wxDialog(NULL, -1, title, wxDefaultPosition, wxSize(450, 450), wxFRAME_FLOAT_ON_PARENT | wxFRAME_TOOL_WINDOW | wxCAPTION | wxSYSTEM_MENU | wxCLOSE_BOX | wxRESIZE_BORDER) { int i, modindex; int nummods = 9; mainwin = main; ToolPanel *panel = new ToolPanel(this, wxDefaultPosition, wxDefaultSize); wxRadioButton *modrad[20]; wxString text; wxFont confont; wxButton *button; if(mainwin->ostype == Mac) confont = wxFont(wxFontInfo(11).FaceName("Tahoma")); else confont = wxFont(wxFontInfo(8).FaceName("Tahoma")); wxBoxSizer *mainbox = new wxBoxSizer(wxVERTICAL); wxBoxSizer *panelbox = new wxBoxSizer(wxVERTICAL); wxBoxSizer *panelhbox = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer *prefbox = new wxBoxSizer(wxVERTICAL); wxBoxSizer *pathbox = new wxBoxSizer(wxVERTICAL); wxBoxSizer *buttonbox = new wxBoxSizer(wxHORIZONTAL); wxStaticBoxSizer *startbox = new wxStaticBoxSizer(wxVERTICAL, panel, "Start Model"); numdrawcon = new ParamNum(panel, "numdraw", "Num Draw", mainwin->numdraw); viewheightcon = new ParamNum(panel, "viewheight", "View Height", mainwin->viewheight); ylabelcon = new ParamNum(panel, "ylabels", "Y Labels", mainwin->ylabels); datsamplecon = new ParamNum(panel, "datsample", "Data Sample Rate", mainwin->datsample); // Project wxBoxSizer *projectbox = new wxBoxSizer(wxHORIZONTAL); projecttag = new TagBox(mainwin, panel, wxID_ANY, "", wxDefaultPosition, wxSize(200, 23), "projectbox", ""); projectbox->Add(projecttag, 0, wxALIGN_CENTRE_HORIZONTAL|wxALIGN_CENTRE_VERTICAL|wxALL, 2); //projecttag->SetLabel(mainwin->project->protag); button = new wxButton(panel, ID_ProjectStore, "Store", wxDefaultPosition, wxSize(40, 25)); button->SetFont(confont); projectbox->Add(button, 0, wxALIGN_CENTRE_HORIZONTAL|wxALIGN_CENTRE_VERTICAL|wxTOP|wxBOTTOM); projectbox->AddSpacer(2); button = new wxButton(panel, ID_ProjectLoad, "Load", wxDefaultPosition, wxSize(40, 25)); button->SetFont(confont); projectbox->Add(button, 0, wxALIGN_CENTRE_HORIZONTAL|wxALIGN_CENTRE_VERTICAL|wxTOP|wxBOTTOM); // Paths datapathcon = new ParamText(panel, "datapath", "Data", mainwin->datapath, 30, 320); datapathcon->AddButton("Path", ID_DataBrowse, 40); outpathcon = new ParamText(panel, "outpath", "Out", mainwin->outpath, 30, 320); outpathcon->AddButton("Path", ID_OutputBrowse, 40); parampathcon = new ParamText(panel, "browsepath", "Param", mainwin->parampath, 30, 320); parampathcon->AddButton("Path", ID_ParamBrowse, 40); modpathcon = new ParamText(panel, "modpath", "Mod", mainwin->modpath, 30, 320); modpathcon->AddButton("Path", ID_ModBrowse, 40); //nummods = mainwin->moddex - 1; nummods = mainwin->modset.modcount; //modrad[0] = new wxRadioButton(panel, 0, "Blank", wxDefaultPosition, wxDefaultSize, wxRB_GROUP); //startbox->Add(modrad[0], 1, wxTOP | wxBOTTOM, 3); for(i=0; i<nummods; i++) { modrad[i+1] = new wxRadioButton(panel, mainwin->modset.modeldat[i].index, mainwin->modset.modeldat[i].title); mainwin->diagbox->Write(text.Format("button %d %s\n", mainwin->modset.modeldat[i].index, mainwin->modset.modeldat[i].title)); startbox->Add(modrad[i+1], 1, wxTOP | wxBOTTOM, 3); } modindex = mainwin->modset.GetDex(mainwin->startmod); if(modindex != -1) modrad[modindex + 1]->SetValue(true); mainwin->diagbox->Write(text.Format("startmod %d button %d\n", mainwin->startmod, mainwin->modset.GetDex(mainwin->startmod) + 1)); prefbox->AddSpacer(10); prefbox->Add(numdrawcon, 1); prefbox->Add(viewheightcon, 1); prefbox->Add(ylabelcon, 1); prefbox->Add(datsamplecon, 1); panelhbox->Add(startbox, 0); panelhbox->AddSpacer(20); panelhbox->Add(prefbox, 0); pathbox->Add(datapathcon, 1); pathbox->Add(parampathcon, 1); pathbox->Add(outpathcon, 1); pathbox->Add(modpathcon, 1); panelbox->Add(panelhbox, 0); panelbox->AddStretchSpacer(5); panelbox->Add(projectbox, 0, wxALIGN_CENTRE); panelbox->AddStretchSpacer(5); panelbox->Add(pathbox, 0); panel->SetSizer(panelbox); panel->Layout(); wxButton *okButton = new wxButton(this, wxID_OK, "Ok", wxDefaultPosition, wxSize(70, 30)); wxButton *closeButton = new wxButton(this, wxID_CANCEL, "Close", wxDefaultPosition, wxSize(70, 30)); buttonbox->Add(okButton, 1); buttonbox->Add(closeButton, 1, wxLEFT, 5); mainbox->Add(panel, 1, wxALL, 10); mainbox->Add(buttonbox, 0, wxALIGN_CENTRE | wxTOP | wxBOTTOM, 10); SetSizer(mainbox); Layout(); Connect(wxEVT_COMMAND_RADIOBUTTON_SELECTED, wxCommandEventHandler(OptionPanel::OnModRadio)); Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnOK)); Connect(wxEVT_COMMAND_TEXT_ENTER, wxCommandEventHandler(OptionPanel::OnEnter)); Connect(ID_DataBrowse, ID_ModBrowse, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnBrowse)); //Connect(ID_OutputBrowse, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnBrowse)); Connect(ID_ProjectStore, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnProjectStore)); Connect(ID_ProjectLoad, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(OptionPanel::OnProjectLoad)); //ShowModal(); //Destroy(); } void OptionPanel::OnProjectStore(wxCommandEvent& event) { wxString tag, filepath; filepath = projecttag->StoreTag(mainwin->project->path, "-prefs.ini"); if(filepath.IsEmpty()) return; tag = projecttag->GetValue(); mainwin->project->Init(tag); mainwin->project->Store(); } void OptionPanel::OnProjectLoad(wxCommandEvent& event) { wxString tag, filepath; filepath = projecttag->LoadTag(mainwin->project->path, "-prefs.ini"); if(filepath.IsEmpty()) return; projecttag->HistStore(); // store updated tag list before project load tag = projecttag->GetValue(); mainwin->project->Init(tag); mainwin->project->Load(); this->Raise(); } void OptionPanel::OnModRadio(wxCommandEvent& event) { //if(event.GetId() == ID_BlankPanel) mainwin->startmod = 0; //if(event.GetId() == ID_IGFPanel) mainwin->startmod = 1; //if(event.GetId() == ID_VasoPanel) mainwin->startmod = 2; //if(event.GetId() == ID_VMHPanel) mainwin->startmod = 3; //if(event.GetId() == ID_CortPanel) mainwin->startmod = 4; //if(event.GetId() == ID_OsmoPanel) mainwin->startmod = 5; //if(event.GetId() == ID_HeatMod) mainwin->startmod = modHeat; //if(event.GetId() == ID_GHMod) mainwin->startmod = modGH; //if(event.GetId() == ID_LysisMod) mainwin->startmod = modLysis; //if(event.GetId() == ID_AgentMod) mainwin->startmod = modAgent; mainwin->startmod = event.GetId(); } void OptionPanel::OnEnter(wxCommandEvent& event) { long stringnum; wxString snum; numdrawcon->numbox->GetValue().ToLong(&stringnum); mainwin->numdraw_set = stringnum; if(mainwin->mod) mainwin->mod->prefstore["numdraw"] = mainwin->numdraw_set; viewheightcon->numbox->GetValue().ToLong(&stringnum); mainwin->viewheight = stringnum; ylabelcon->numbox->GetValue().ToLong(&stringnum); mainwin->ylabels = stringnum; datsamplecon->numbox->GetValue().ToLong(&stringnum); mainwin->datsample = stringnum; mainwin->parampath = parampathcon->GetValue(); mainwin->datapath = datapathcon->GetValue(); mainwin->outpath = outpathcon->GetValue(); mainwin->modpath = modpathcon->GetValue(); //snum.Printf("ok numdraw %d", mainwin->numdraw); //mainwin->SetStatus(snum); mainwin->GraphPanelsUpdate(); } void OptionPanel::OnOK(wxCommandEvent& event) { OnEnter(event); Close(); } void OptionPanel::OnClose(wxCloseEvent& event) { mainwin->OptionStore(); Show(false); } void OptionPanel::OnBrowse(wxCommandEvent& event) { if(event.GetId() == ID_DataBrowse) { wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->datapath, 0, wxDefaultPosition); if(d->ShowModal() == wxID_OK) datapathcon->textbox->SetLabel(d->GetPath()); } if(event.GetId() == ID_OutputBrowse) { wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->outpath, 0, wxDefaultPosition); if(d->ShowModal() == wxID_OK) outpathcon->textbox->SetLabel(d->GetPath()); } if(event.GetId() == ID_ParamBrowse) { wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->parampath, 0, wxDefaultPosition); if(d->ShowModal() == wxID_OK) parampathcon->textbox->SetLabel(d->GetPath()); } if(event.GetId() == ID_ModBrowse) { wxDirDialog *d = new wxDirDialog(this, "Choose a directory", mainwin->modpath, 0, wxDefaultPosition); if(d->ShowModal() == wxID_OK) modpathcon->textbox->SetLabel(d->GetPath()); } }
35.585062
131
0.731343
68be163aad621d1fd1d5c3538565f5f8d5c1430c
122,962
cpp
C++
CELLULARDlg.cpp
yantis/amps-cellular-interceptor
fff85cf5e4ba01a916a20f75a29d7ce8cc4a3df0
[ "MIT" ]
4
2018-02-12T15:18:43.000Z
2021-03-08T21:35:31.000Z
CELLULARDlg.cpp
yantis/amps-cellular-interceptor
fff85cf5e4ba01a916a20f75a29d7ce8cc4a3df0
[ "MIT" ]
null
null
null
CELLULARDlg.cpp
yantis/amps-cellular-interceptor
fff85cf5e4ba01a916a20f75a29d7ce8cc4a3df0
[ "MIT" ]
null
null
null
// CELLULARDlg.cpp : implementation file // #include "stdafx.h" #include "CELLULAR.h" #include "CELLULARDlg.h" #include <sys/types.h> #include <sys/stat.h> /* #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif */ #include "supercom\supercom.h" #include "area.h" #include "phonelst.h" #include "manufact.h" #include "smrtheap.hpp" #define OK 0 #define CLOSED 0 #define OPEN 1 // #define RECORD /////////////////////////// int iCommPortOS456; int iCommPortDDI; long int iMaxCallTime; bool bReverseChannel; int iBufferCounter; char dateis[15]; char timeis[15]; char d_timeis[12]; char chDDIdataBuffer[60]; char chPhoneNumber[15]; char chRegistration[2]; char chArea[38]; char chChannel[5]; char chGoFrequency[8]; char chAllRegistrations[4]; char chAllPaging[4]; char chRegistrationType[2]; char chAreaCode[4]; char chWhereErrorOccured[100]; int endnum; int stanum; bool bRegistration = false; bool bDisconnect = false; bool bPaging = false; bool bReorder = false; bool bLockOut = false; bool bGoto = false; bool bVoiceGoto = false; bool bAllPaging = false; bool bAllRegistration = false; bool bNewTest; bool bNewNumber; bool bAmend; char chChannelBand[2]; char chSCMstring[50]; ////////////// ISAM dfAREA areabase; dfPHONELST phonelst; dfMANUFACT manufact; //////////////////// bool bCancelCall; char chSignalStrength[100]; time_t start_time; int squelch; bool bHoldCall; int iCallCounter_0; int iCallCounter_1; int iCallCounter_2; int iCallCounter_3; int iCallCounter_4; int iCallCounter_5; int iCallCounter_6; int iCallCounter_7; int iCallCounter_8; int iCallCounter_9; int iCallCounter_total; int iCallCounter_record; int iCallCounter_fax; int iCallCounter_modem; int iWaveFileNumber; UINT wDeviceID; bool bMonitor; bool bAquire; bool bGoReverseVoice; bool bGoForwardVoice; bool bVoiceForward; char chChannelType[50]; char chFrequency[50]; char chReverseChannel[50]; char chForwardChannel[50]; ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCELLULARDlg dialog CCELLULARDlg::CCELLULARDlg(CWnd* pParent /*=NULL*/) : CDialog(CCELLULARDlg::IDD, pParent) { //{{AFX_DATA_INIT(CCELLULARDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CCELLULARDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CCELLULARDlg) DDX_Control(pDX, IDC_PROGRESS_SIGNAL, m_ProgressSignal); DDX_Control(pDX, IDC_BUTTON_CONTROL_TYPE, m_ButtonSwitchControlType); DDX_Control(pDX, IDC_BUTTON_SWITCHVOICE, m_ButtonSwitchVoice); DDX_Control(pDX, IDC_EDIT_CALLS, m_EditCallList); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL9, m_Text_CallsLevel9); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL8, m_Text_CallsLevel8); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL7, m_Text_CallsLevel7); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL6, m_Text_CallsLevel6); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL5, m_Text_CallsLevel5); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL4, m_Text_CallsLevel4); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL3, m_Text_CallsLevel3); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL2, m_Text_CallsLevel2); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL1, m_Text_CallsLevel1); DDX_Control(pDX, IDC_TEXT_CALLSLEVEL0, m_Text_CallsLevel0); DDX_Control(pDX, IDC_TEXT_TOTALCALL, m_Text_CallsTotal); DDX_Control(pDX, IDC_TEXT_CALLSRECORD, m_Text_CallsRecorded); DDX_Control(pDX, IDC_TEXT_CALLSMODEM, m_Text_CallsModem); DDX_Control(pDX, IDC_TEXT_CALLSFAX, m_Text_CallsFax); DDX_Control(pDX, IDC_EDIT_TOTALCALLS, m_Edit_TotalCalls); DDX_Control(pDX, IDC_EDIT_SUBJECT, m_EditSubject); DDX_Control(pDX, IDC_EDIT_SIGNALSTR, m_EditSignalStrength); DDX_Control(pDX, IDC_EDIT_SCM, m_EditSCM); DDX_Control(pDX, IDC_EDIT_RECORDCALL, m_EditRecordCall); DDX_Control(pDX, IDC_EDIT_PHONETYPE, m_EditPhoneType); DDX_Control(pDX, IDC_EDIT_PHONEMODEL, m_EditPhoneModel); DDX_Control(pDX, IDC_EDIT_PHONE, m_EditPhone); DDX_Control(pDX, IDC_EDIT_OCCUPATION, m_EditOccupation); DDX_Control(pDX, IDC_EDIT_NAME2, m_EditName2); DDX_Control(pDX, IDC_EDIT_NAME, m_EditName); DDX_Control(pDX, IDC_EDIT_MODEMCALL, m_EditModemCalls); DDX_Control(pDX, IDC_EDIT_LINKEDFILE, m_EditLinkedFile); DDX_Control(pDX, IDC_EDIT_LASTCALL, m_EditLastCall); DDX_Control(pDX, IDC_EDIT_LANGUAGE, m_EditLanguage); DDX_Control(pDX, IDC_EDIT_INFO3, m_EditInfo3); DDX_Control(pDX, IDC_EDIT_INFO2, m_EditInfo2); DDX_Control(pDX, IDC_EDIT_INFO1, m_EditInfo1); DDX_Control(pDX, IDC_EDIT_GENDER, m_EditGender); DDX_Control(pDX, IDC_EDIT_FAXCALLS, m_EditFaxCalls); DDX_Control(pDX, IDC_EDIT_ESN, m_EditESN); DDX_Control(pDX, IDC_EDIT_DTMF, m_EditDtmf); DDX_Control(pDX, IDC_EDIT_DIALEDNUMBER, m_EditDialedNumber); DDX_Control(pDX, IDC_EDIT_CHANNELAB, m_EditChannelAB); DDX_Control(pDX, IDC_EDIT_CALLTIME, m_EditCallTime); DDX_Control(pDX, IDC_EDIT_CALLSTART, m_EditStart); DDX_Control(pDX, IDC_EDIT_CALLEND, m_EditCallEnd); DDX_Control(pDX, IDC_EDIT_AREA, m_EditArea); DDX_Control(pDX, IDC_EDIT_ALERTLEVEL, m_EditAlertLevel); DDX_Control(pDX, IDC_EDIT_STATUS, m_Edit_Status); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CCELLULARDlg, CDialog) //{{AFX_MSG_MAP(CCELLULARDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_EN_ERRSPACE(IDC_EDIT_STATUS, OnErrspaceEditStatus) ON_BN_CLICKED(IDC_BUTTON_SKIPVOICECALL, OnButtonSkipvoicecall) ON_BN_CLICKED(IDC_BUTTON_SAVE_DATA, OnButtonSaveData) ON_BN_CLICKED(IDC_BUTTON_FIND_PHONE, OnButtonFindPhone) ON_BN_CLICKED(IDC_CHECK_HOLDCALL, OnCheckHoldcall) ON_WM_CTLCOLOR() ON_BN_CLICKED(IDC_CHECK_AQUIRE, OnCheckAquire) ON_BN_CLICKED(IDC_CHECK_MONITOR, OnCheckMonitor) ON_BN_CLICKED(IDC_BUTTON_SWITCHVOICE, OnButtonSwitchvoice) ON_BN_CLICKED(IDC_BUTTON_CONTROL_TYPE, OnButtonControlType) ON_BN_CLICKED(IDC_BUTTON_CONTROLSCAN, OnButtonControlscan) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCELLULARDlg message handlers BOOL CCELLULARDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here ReadIniFile(); phonelst.rew(); phonelst.clear_buf(); areabase.rew(); areabase.clear_buf(); manufact.rew(); manufact.clear_buf(); m_EditPhone.LimitText(14); m_EditName.LimitText(30); m_EditName2.LimitText(30); m_EditArea.LimitText(30); m_EditOccupation.LimitText(30); m_EditSubject.LimitText(30); m_EditLanguage.LimitText(10); m_EditGender.LimitText(1); m_EditInfo1.LimitText(30); m_EditInfo2.LimitText(30); m_EditInfo3.LimitText(30); m_EditLinkedFile.LimitText(12); m_EditModemCalls.LimitText(1); m_EditFaxCalls.LimitText(1); m_EditAlertLevel.LimitText(1); m_EditRecordCall.LimitText(1); m_EditDtmf.LimitText(30); m_EditESN.LimitText(8); m_EditSCM.LimitText(2); bHoldCall = false; iCallCounter_0 = 0; iCallCounter_1 = 0; iCallCounter_2 = 0; iCallCounter_3 = 0; iCallCounter_4 = 0; iCallCounter_5 = 0; iCallCounter_6 = 0; iCallCounter_7 = 0; iCallCounter_8 = 0; iCallCounter_9 = 0; iCallCounter_total = 0; iCallCounter_record = 0; iCallCounter_fax = 0; iCallCounter_modem =0; iWaveFileNumber = 0; bMonitor = false; bAquire = false; bGoReverseVoice = false; bGoForwardVoice = false; bVoiceForward = true; m_ProgressSignal.SetRange(0,25); // m_ProgressSignal.SetStep(1); m_Edit_Status.SetWindowText(" "); which_channel(); bCancelThread=true; bThreadClosed=true; return TRUE; // return true unless you set the focus to a control } void CCELLULARDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CCELLULARDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CCELLULARDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CCELLULARDlg::WriteToStatusBox(char *pchString) { static int iCount = 0; iCount ++; char chTempString[50]; char *pchTempString = chTempString; sprintf(pchTempString, "%d",iCount); SetDlgItemText(IDC_STATUS_TEXT,pchTempString); if(iCount >= 400) { iCount = 0; m_Edit_Status.SetWindowText(" "); m_Edit_Status.Clear(); } m_Edit_Status.ReplaceSel(pchString,false); char chNewLine[3]; chNewLine[0]= 0x0D; chNewLine[1]= 0x0A; chNewLine[2]= 0x00; char *pchNewLine = chNewLine; m_Edit_Status.ReplaceSel(pchNewLine,false); } void CCELLULARDlg::WriteToCallBox(char *pchString) { m_EditCallList.ReplaceSel(pchString,false); char chNewLine[3]; chNewLine[0]= 0x0D; chNewLine[1]= 0x0A; chNewLine[2]= 0x00; char *pchNewLine = chNewLine; m_EditCallList.ReplaceSel(pchNewLine,false); } void CCELLULARDlg::MyError(char *s) { WriteDebugLog(s); MessageBeep(MB_ICONEXCLAMATION); MessageBox(s,"Program Error",MB_OK | MB_ICONHAND | MB_SETFOREGROUND); } void CCELLULARDlg::WriteDebugLog(char *chLogText) { FILE *log; if((log=fopen("DEBUG.LOG","a+"))==NULL) { // Error("Error opening DEBUG.LOG"); (No Error or infinate loop ..) return; } else { fprintf(log,"%s\n",chLogText); fclose(log); } } void CCELLULARDlg::OnOK() { CreateMyThread(); } void CCELLULARDlg::InitalizeDDI(void) { WriteToStatusBox(" Initalizing DDI"); // Set to 9600 BPS and Send DDI command to switch to 19200 ComInit(iCommPortDDI); if(ComValid(iCommPortDDI)) { ComSetState(iCommPortDDI,9600,8,1,'N',SIGNAL_NONE); ComBufClear(iCommPortDDI,DIR_INC); ComBufClear(iCommPortDDI,DIR_OUT); WriteToStatusBox(" DDI Comm Port Initalized @ 9600 BPS"); } else { char chTempString[250]; char *pchTempString = chTempString; sprintf(pchTempString,"Com Port %d is not available or is in use",iCommPortDDI+1); MyError(pchTempString); return; } ComDTROn(iCommPortDDI); // set DTR ComRTSOn(iCommPortDDI); // set RTS // Reset DDI WriteToStatusBox(" Sending DDI Reset Command (1X)"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'Y'); // Reset DDI WriteToStatusBox(" Sending DDI Reset Command (2X)"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'Y'); // Reset DDI WriteToStatusBox(" Sending DDI Reset Command (3X)"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'Y'); // Switch DDI to 19200 bps WriteToStatusBox(" Sending DDI Command to increase BPS to 19200"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'F'); WriteToStatusBox(" Switching DDI Comm Port to 19200 BPS"); ComSetBaudRate(iCommPortDDI, 19200); // ComBufClear(iCommPortDDI,DIR_INC); // ComBufClear(iCommPortDDI,DIR_OUT); // WriteToStatusBox(" Sending DDI Command to display all control data"); // ComWrite(iCommPortDDI,'-'); // ComWrite(iCommPortDDI,'D'); // All Control Data WriteToStatusBox(" Sending DDI Command to display all control data changes only"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'d'); // Changes only WriteToStatusBox(" Sending DDI Command to show Channel on Goto"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'K'); SetDDItoControlChannel(); if(bReverseChannel == true) { SetDDItoReverse(); } else { SetDDItoForward(); } } void CCELLULARDlg::OnCancel() { #ifdef RECORD mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL); #endif bCancelThread=true; if(bThreadClosed==false) { SetDlgItemText(IDC_STATUS_TEXT,"Please wait while closing multithreaded engine."); Sleep(3000); } if(bThreadClosed==false) { DWORD dwExitCode; if(GetExitCodeThread(hThread,&dwExitCode)==false) { MyError("Error in GetExitCodeThread(hThread)"); } else { TerminateThread(hThread,dwExitCode); } } hThread = NULL; ComReset(iCommPortDDI); ComReset(iCommPortOS456); CDialog::OnCancel(); } void CCELLULARDlg::CreateMyThread(void) { #ifdef _DEBUG TRACE("CreateMyThread START\n"); #endif DWORD dwThreadId; hThread = CreateThread((LPSECURITY_ATTRIBUTES) NULL, 0, (LPTHREAD_START_ROUTINE) ThreadProc,this,0,&dwThreadId); if(hThread == NULL) { char chTempString[75]; char *pchTempString = chTempString; sprintf(pchTempString,"Error %ld Creating Thread",GetLastError()); MyError(pchTempString); } else { if(SetThreadPriority( hThread, THREAD_PRIORITY_NORMAL ) == 0) { MyError("Cound Not set thread to THREAD_PRIORITY_NORMAL"); } } #ifdef _DEBUG TRACE("CreateMyThread END\n"); #endif } DWORD CCELLULARDlg::ThreadProc(CCELLULARDlg *s) { s->ProcessThread(); return 0; } void CCELLULARDlg::ProcessThread(void) { #ifdef _DEBUG TRACE("ProcessThread START\n"); #endif bCancelThread=false; bThreadClosed=false; InitalizeOS456(); InitalizeDDI(); start: if(bCancelThread==true) { bThreadClosed=true; return; } if(bHoldCall == false) { GetDDIdata(); } goto start; } void CCELLULARDlg::whattime(void) { struct tm *today; time_t timer; timer = time(NULL); today = localtime( &timer ); char timestatus[3]; // am/pm int hour1; if (today->tm_hour<12) { strcpy(timestatus,"am"); hour1=today->tm_hour; if (today->tm_hour==0){hour1=12;} } if (today->tm_hour>=12) { strcpy(timestatus,"pm"); hour1=today->tm_hour - 12; if (today->tm_hour==12){hour1=12;} } sprintf(timeis,"%02d:%02d:%02d%s",hour1,today->tm_min,today->tm_sec,timestatus); sprintf(dateis,"%02d-%02d-%02d",today->tm_mon+1,today->tm_mday,today->tm_year); sprintf(d_timeis,"%02d:%02d%c",hour1,today->tm_min,timestatus[0]); } void CCELLULARDlg::ZeroMemVariables(void) { ::ZeroMemory (chDDIdataBuffer, sizeof (chDDIdataBuffer)); ::ZeroMemory (chArea, sizeof (chArea)); } void CCELLULARDlg::GetDDIdata(void) { char i; if(ComRead(iCommPortDDI,&i)==TRUE) { if(i==0x0D) { char chTempBuffer[500]; char *pchTempBuffer = chTempBuffer; iBufferCounter=-1; whattime(); AnalyzeDDIdata(); if((chDDIdataBuffer[0]>=0x30) && (chDDIdataBuffer[0]<=0x39)) // Is first character a number ? { if((bRegistration==true) &&(bReverseChannel==false)) { sprintf(pchTempBuffer," %s %s\tRegistration [%c]\t%s",timeis,chPhoneNumber,chRegistration[0],chArea); WriteToStatusBox(pchTempBuffer); /* if(logit==true) { fprintf(log," %s %s Registration [%c] %s\n",timeis,chPhoneNumber,chRegistration[0],chArea); } */ } if(bDisconnect==true) { sprintf(pchTempBuffer," %s %s\tDisconnect\t%s",timeis,chPhoneNumber,chArea); WriteToStatusBox(pchTempBuffer); /* if(logit==true) { fprintf(log," %s %s Disconnect %s\n",timeis,chPhoneNumber,chArea); } */ } if(bPaging==true) { sprintf(pchTempBuffer," %s %s\tPaging\t\t%s",timeis,chPhoneNumber,chArea); WriteToStatusBox(pchTempBuffer); /* if(logit==true) { fprintf(log," %s %s Paging %s\n",timeis,chPhoneNumber,chArea); } */ } if((bReorder==true)&&(bLockOut==false)) { sprintf(pchTempBuffer," %s %s\tReorder\t\t%s",timeis,chPhoneNumber,chArea); WriteToStatusBox(pchTempBuffer); /* if(logit==true) { fprintf(log," %s %s Reorder System to busy - Try later.\n",timeis,chPhoneNumber); } */ } if((bGoto ==true)&&(bLockOut==true)) { sprintf(pchTempBuffer," %s %s\tLocked Out Goto\t%s",timeis,chPhoneNumber,chArea); WriteToStatusBox(pchTempBuffer); } if((bGoto ==true)&&(bLockOut==false)) { sprintf(pchTempBuffer," %s %s\tGoto %s\t%s",timeis,chPhoneNumber,chGoFrequency,chArea); WriteToStatusBox(pchTempBuffer); switch_to_voice(); } } // End if (is it a number ?) if(((chDDIdataBuffer[0]<0x30)||(chDDIdataBuffer[0]>0x39)) || (bReverseChannel==true) ) // Is first character NOT a number ? { if((bAllPaging==false)&&(bAllRegistration==false)&&(chDDIdataBuffer[0] != 0x00)&&(chDDIdataBuffer[1] != 0x00)&&(chDDIdataBuffer[0] != 0x20)) { sprintf(pchTempBuffer," %s",chDDIdataBuffer); WriteToStatusBox(pchTempBuffer); /* if(logit==true) { fprintf(log," %s\n",chDDIdataBuffer); } */ } } // end if (if first character NOT a number?) ZeroMemVariables(); } // End if (i>1) if((i>=0x20) && (i <=0x7A)) { iBufferCounter++; chDDIdataBuffer[iBufferCounter] = (char) i;; } } } void CCELLULARDlg::AnalyzeDDIdata(void) { ossignalstr(); bRegistration = false; // reset registration flag bDisconnect = false; // reset disconnect flag bPaging = false; // reset paging flag bGoto = false; // reset Goto flag bVoiceGoto = false; // reset voice GoTo Flag bReorder = false; // reset bReorder flag bLockOut = false; // reset bLockOut flag /* personal = false; // reset personal flag */ bAllRegistration = false; // reset all registration flag bAllPaging = false; // reset all paging flag char chTempBuffer[500]; char *pchTempBuffer = chTempBuffer; if((chDDIdataBuffer[0]<0x30) || (chDDIdataBuffer[0]>0x39)) // Is first character NOT a number ? { // Check if Goto Command from Voice Channel(check for "GoT") if ((chDDIdataBuffer[0]=='G')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='T') ) { bVoiceGoto = true; // Jump to which channel chChannel[0] = chDDIdataBuffer[5]; chChannel[1] = chDDIdataBuffer[6]; chChannel[2] = chDDIdataBuffer[7]; chChannel[3] = chDDIdataBuffer[8]; // Jump to which frequency chGoFrequency[0] = chDDIdataBuffer[10];// 8 chGoFrequency[1] = chDDIdataBuffer[11];// 8 chGoFrequency[2] = chDDIdataBuffer[12];// 0 chGoFrequency[3] = chDDIdataBuffer[13];// . chGoFrequency[4] = chDDIdataBuffer[14];// 5 chGoFrequency[5] = chDDIdataBuffer[15];// 0 chGoFrequency[6] = chDDIdataBuffer[16];// 0 WriteToStatusBox(" At Goto2 Subroutine "); /* if(logit==true) { fprintf(log,"At Goto2 Subroutine \n"); } */ goto END; } // Check if "?" or ">" if((chDDIdataBuffer[0]==0x3F)||(chDDIdataBuffer[0]==0x3E) ) { ZeroMemVariables(); goto END; } // Check if Voice if((chDDIdataBuffer[0]=='V')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='i') ) { WriteToStatusBox(" DDI Successfully set to Voice Mode"); ZeroMemVariables(); goto END; } // Check if E1 thru EE but not E0 (Reserved, Ignore) if((chDDIdataBuffer[0]=='E')&&(chDDIdataBuffer[1]!='0')) { ZeroMemVariables(); goto END; } // Check if F1 thru FF but not F0 (Reserved, Ignore) if((chDDIdataBuffer[0]=='E')&&(chDDIdataBuffer[1]!='0')) { ZeroMemVariables(); goto END; } // Check if D2 thru DB but not any other Dx (Reserved, Ignore) if((chDDIdataBuffer[0]=='D')&&(chDDIdataBuffer[1]=='2' || '3' || '4' || '5' || '6'|| '7' || '8' || '9' || 'A' || 'B')) { ZeroMemVariables(); goto END; } // Check if System Requested Registration if((chDDIdataBuffer[6]=='R')&&(chDDIdataBuffer[7]=='e')&&(chDDIdataBuffer[8]=='g') ) { bAllRegistration = true; // All registration of Which area code chAllRegistrations[0]=chDDIdataBuffer[1]; chAllRegistrations[1]=chDDIdataBuffer[2]; chAllRegistrations[2]=chDDIdataBuffer[3]; // What type of registration chRegistrationType[0]=chDDIdataBuffer[19]; goto END; } // Check if System Page if((chDDIdataBuffer[6]=='P')&&(chDDIdataBuffer[7]=='a')&&(chDDIdataBuffer[8]=='g')) { bAllPaging = true; // All Page of Which area code chAllPaging[0]=chDDIdataBuffer[1]; chAllPaging[1]=chDDIdataBuffer[2]; chAllPaging[2]=chDDIdataBuffer[3]; goto END; } // Check if Control if((chDDIdataBuffer[0]=='C')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='n') ) { WriteToStatusBox(" DDI Successfully set to Control Mode"); ZeroMemVariables(); goto END; } // Check if Forward if((chDDIdataBuffer[0]=='F')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='r')) { WriteToStatusBox(" DDI Successfully set to Forward Mode"); ZeroMemVariables(); goto END; } // Check if Reverse if((chDDIdataBuffer[0]=='R')&&(chDDIdataBuffer[1]=='e')&&(chDDIdataBuffer[2]=='v') ) { WriteToStatusBox(" DDI Successfully set to Reverse Mode"); ZeroMemVariables(); goto END; } // Check if System ID & DCC on Control Channel if((chDDIdataBuffer[0]=='S')&&(chDDIdataBuffer[1]=='I')&&(chDDIdataBuffer[2]=='D')) { char chSID[5]; ::ZeroMemory (chSID, sizeof (chSID)); char chDCC[2]; ::ZeroMemory (chDCC, sizeof (chDCC)); chSID[0]=chDDIdataBuffer[4]; chSID[1]=chDDIdataBuffer[5]; chSID[2]=chDDIdataBuffer[6]; chSID[3]=chDDIdataBuffer[7]; SetDlgItemText(IDC_TEXT_SID,chSID); if((chDDIdataBuffer[9]=='D')&&(chDDIdataBuffer[10]=='C')&&(chDDIdataBuffer[11]=='C') ) { chDCC[0]=chDDIdataBuffer[4]; SetDlgItemText(IDC_TEXT_DCC,chDCC); } /* UpdateChannelStats(); */ ZeroMemVariables(); goto END; } // Check for NPC=xx on Control Channel if((chDDIdataBuffer[0]=='N')&&(chDDIdataBuffer[1]=='P')&&(chDDIdataBuffer[2]=='C')) { char chNPC[3]; ::ZeroMemory (chNPC, sizeof (chNPC)); chNPC[0]=chDDIdataBuffer[4]; chNPC[1]=chDDIdataBuffer[5]; SetDlgItemText(IDC_TEXT_NPC,chNPC); ZeroMemVariables(); goto END; } // Check for NAC=xx on Control Channel if((chDDIdataBuffer[0]=='N')&&(chDDIdataBuffer[1]=='A')&&(chDDIdataBuffer[2]=='C')) { char chNAC[3]; ::ZeroMemory (chNAC, sizeof (chNAC)); chNAC[0]=chDDIdataBuffer[4]; chNAC[1]=chDDIdataBuffer[5]; SetDlgItemText(IDC_TEXT_NAC,chNAC); ZeroMemVariables(); goto END; } // Check if RegInc=xxxx on Control Channel if((chDDIdataBuffer[0]=='R')&&(chDDIdataBuffer[1]=='e')&&(chDDIdataBuffer[2]=='g')&&(chDDIdataBuffer[3]=='I') ) { char chRegInc[6]; ::ZeroMemory (chRegInc, sizeof (chRegInc)); chRegInc[0]=chDDIdataBuffer[7]; chRegInc[1]=chDDIdataBuffer[8]; chRegInc[2]=chDDIdataBuffer[9]; chRegInc[3]=chDDIdataBuffer[10]; SetDlgItemText(IDC_TEXT_REGINC,chRegInc); ZeroMemVariables(); goto END; } // Check if Modes=XXXXXXX on Control Channel if((chDDIdataBuffer[0]=='M')&&(chDDIdataBuffer[1]=='o')&&(chDDIdataBuffer[2]=='d')) { if((chDDIdataBuffer[6]=='S')|| (chDDIdataBuffer[7]=='S')||(chDDIdataBuffer[8]=='S')||(chDDIdataBuffer[9]=='S')|| (chDDIdataBuffer[10]=='S')|| (chDDIdataBuffer[11]=='S')|| (chDDIdataBuffer[12]=='S')) { SetDlgItemText(IDC_TEXT_MODES_S,"YES"); } else { SetDlgItemText(IDC_TEXT_MODES_S,"NO"); } if((chDDIdataBuffer[6]=='E')|| (chDDIdataBuffer[7]=='E')||(chDDIdataBuffer[8]=='E')||(chDDIdataBuffer[9]=='E')|| (chDDIdataBuffer[10]=='E')|| (chDDIdataBuffer[11]=='E')|| (chDDIdataBuffer[12]=='E')) { SetDlgItemText(IDC_TEXT_MODES_E,"YES"); } else { SetDlgItemText(IDC_TEXT_MODES_E,"NO"); } if((chDDIdataBuffer[6]=='H')|| (chDDIdataBuffer[7]=='H')||(chDDIdataBuffer[8]=='H')||(chDDIdataBuffer[9]=='H')|| (chDDIdataBuffer[10]=='H')|| (chDDIdataBuffer[11]=='H')|| (chDDIdataBuffer[12]=='H')) { SetDlgItemText(IDC_TEXT_MODES_H,"YES"); } else { SetDlgItemText(IDC_TEXT_MODES_H,"NO"); } if((chDDIdataBuffer[6]=='R')|| (chDDIdataBuffer[7]=='R')||(chDDIdataBuffer[8]=='R')||(chDDIdataBuffer[9]=='R')|| (chDDIdataBuffer[10]=='R')|| (chDDIdataBuffer[11]=='R')|| (chDDIdataBuffer[12]=='R')) { SetDlgItemText(IDC_TEXT_MODES_R,"YES"); } else { SetDlgItemText(IDC_TEXT_MODES_R,"NO"); } if((chDDIdataBuffer[6]=='D')|| (chDDIdataBuffer[7]=='D')||(chDDIdataBuffer[8]=='D')||(chDDIdataBuffer[9]=='D')|| (chDDIdataBuffer[10]=='D')|| (chDDIdataBuffer[11]=='D')|| (chDDIdataBuffer[12]=='D')) { SetDlgItemText(IDC_TEXT_MODES_D,"YES"); } else { SetDlgItemText(IDC_TEXT_MODES_D,"NO"); } if((chDDIdataBuffer[6]=='F')|| (chDDIdataBuffer[7]=='F')||(chDDIdataBuffer[8]=='F')||(chDDIdataBuffer[9]=='F')|| (chDDIdataBuffer[10]=='F')|| (chDDIdataBuffer[11]=='F')|| (chDDIdataBuffer[12]=='F')) { SetDlgItemText(IDC_TEXT_MODES_F,"YES"); } else { SetDlgItemText(IDC_TEXT_MODES_F,"NO"); } if((chDDIdataBuffer[6]=='C')|| (chDDIdataBuffer[7]=='C')||(chDDIdataBuffer[8]=='C')||(chDDIdataBuffer[9]=='C')|| (chDDIdataBuffer[10]=='C')|| (chDDIdataBuffer[11]=='C')|| (chDDIdataBuffer[12]=='C')) { SetDlgItemText(IDC_TEXT_MODES_C,"YES"); } else { SetDlgItemText(IDC_TEXT_MODES_C,"NO"); } ZeroMemVariables(); goto END; } //check for Ring Phone on Voice Channel if((chDDIdataBuffer[0]=='R')&&(chDDIdataBuffer[1]=='i')&&(chDDIdataBuffer[2]=='n') ) { // ring = true; WriteToStatusBox(" Incoming Ring on Voice Channel"); ZeroMemVariables(); goto END; } } if((chDDIdataBuffer[0]>=0x30) && (chDDIdataBuffer[0]<=0x39)) // Is first character a number ? { // Change phone number to (xxx) xxx-xxxx format & save in chPhoneNumber array chPhoneNumber[0] =chDDIdataBuffer[9]; // Area Code chPhoneNumber[1] =chDDIdataBuffer[10];// 6 chPhoneNumber[2] =chDDIdataBuffer[11];// 1 chPhoneNumber[3] =chDDIdataBuffer[12];// 9 chPhoneNumber[4] =chDDIdataBuffer[13]; chPhoneNumber[5] =chDDIdataBuffer[8]; // Space chPhoneNumber[6] =chDDIdataBuffer[0]; // prefix chPhoneNumber[7] =chDDIdataBuffer[1]; chPhoneNumber[8] =chDDIdataBuffer[2]; chPhoneNumber[9] =chDDIdataBuffer[3]; // - chPhoneNumber[10]=chDDIdataBuffer[4]; // suffix chPhoneNumber[11]=chDDIdataBuffer[5]; chPhoneNumber[12]=chDDIdataBuffer[6]; chPhoneNumber[13]=chDDIdataBuffer[7]; chAreaCode[0] = chDDIdataBuffer[10]; chAreaCode[1] = chDDIdataBuffer[11]; chAreaCode[2] = chDDIdataBuffer[12]; strcpy(phonelst.Dphone,chPhoneNumber); search(); areabase.Anumber[0] =chPhoneNumber[1];// 6 areabase.Anumber[1] =chPhoneNumber[2];// 1 areabase.Anumber[2] =chPhoneNumber[3];// 9 areabase.Anumber[3] =chPhoneNumber[6]; // prefix areabase.Anumber[4] =chPhoneNumber[7]; areabase.Anumber[5] = 0x00; areabase.Anumber[6] = 0x00; areabase.Anumber[7] = 0x00; areabase.Anumber[8] = 0x00; areabase.Anumber[9] = 0x00; areabase.Anumber[10] = 0x00; areabase.Anumber[11] = 0x00; areabase.Anumber[12] = 0x00; areabase.Anumber[13] = 0x00; if((areabase.find()== IM_OK)) { strcpy(chArea,areabase.Aarea); goto OK1; } else { areabase.Anumber[0] =chPhoneNumber[1];// 6 areabase.Anumber[1] =chPhoneNumber[2];// 1 areabase.Anumber[2] =chPhoneNumber[3];// 9 areabase.Anumber[3] =chPhoneNumber[6]; // prefix areabase.Anumber[4] = 0x00; areabase.Anumber[5] = 0x00; areabase.Anumber[6] = 0x00; areabase.Anumber[7] = 0x00; areabase.Anumber[8] = 0x00; areabase.Anumber[9] = 0x00; areabase.Anumber[10] = 0x00; areabase.Anumber[11] = 0x00; areabase.Anumber[12] = 0x00; areabase.Anumber[13] = 0x00; if((areabase.find()== IM_OK)) { strcpy(chArea,areabase.Aarea); goto OK1; } else { areabase.Anumber[0] =chPhoneNumber[1];// 6 areabase.Anumber[1] =chPhoneNumber[2];// 1 areabase.Anumber[2] =chPhoneNumber[3];// 9 areabase.Anumber[3] = 0x00; areabase.Anumber[4] = 0x00; areabase.Anumber[5] = 0x00; areabase.Anumber[6] = 0x00; areabase.Anumber[7] = 0x00; areabase.Anumber[8] = 0x00; areabase.Anumber[9] = 0x00; areabase.Anumber[10] = 0x00; areabase.Anumber[11] = 0x00; areabase.Anumber[12] = 0x00; areabase.Anumber[13] = 0x00; if((areabase.find()== IM_OK)) { strcpy(chArea,areabase.Aarea); goto OK1; } else { areabase.Anumber[0] =chPhoneNumber[1];// 6 areabase.Anumber[1] =chPhoneNumber[2];// 1 areabase.Anumber[2] = 0x00; areabase.Anumber[3] = 0x00; areabase.Anumber[4] = 0x00; areabase.Anumber[5] = 0x00; areabase.Anumber[6] = 0x00; areabase.Anumber[7] = 0x00; areabase.Anumber[8] = 0x00; areabase.Anumber[9] = 0x00; areabase.Anumber[10] = 0x00; areabase.Anumber[11] = 0x00; areabase.Anumber[12] = 0x00; areabase.Anumber[13] = 0x00; if((areabase.find()== IM_OK)) { strcpy(chArea,areabase.Aarea); goto OK1; } else { strcpy(chArea,"Not Found"); } } } } OK1: // Check if Registration (check for "Reg") if((chDDIdataBuffer[15]==0x52) && (chDDIdataBuffer[16]=='e') && (chDDIdataBuffer[17]==0x67) ) { chRegistration[0] = chDDIdataBuffer[28]; if(bReverseChannel==false) { bRegistration = true; } if((chDDIdataBuffer[32]=='S') && (chDDIdataBuffer[33]=='C') && (chDDIdataBuffer[34]=='M')) { phonelst.Dscm[0]=chDDIdataBuffer[36]; phonelst.Dscm[1]=chDDIdataBuffer[37]; phonelst.Desn[0]=chDDIdataBuffer[43]; phonelst.Desn[1]=chDDIdataBuffer[44]; phonelst.Desn[2]=chDDIdataBuffer[45]; phonelst.Desn[3]=chDDIdataBuffer[46]; phonelst.Desn[4]=chDDIdataBuffer[47]; phonelst.Desn[5]=chDDIdataBuffer[48]; phonelst.Desn[6]=chDDIdataBuffer[49]; phonelst.Desn[7]=chDDIdataBuffer[50]; if(phonelst.Darea[0]==0x00) { strcpy(phonelst.Darea,chArea); } if(phonelst.Dtype[0]==0x00) { phonelst.Dtype[0]=chChannelBand[0]; } if(phonelst.Dphone[0]==0x00) { strcpy(phonelst.Dphone,chPhoneNumber); insert_record(); bNewTest=false; bNewNumber=true; } if(bNewNumber==false) { strcpy(chWhereErrorOccured,"Line 2150"); amend_record(); bAmend=false; bNewTest=false; } char chTempString[400]; char *pchTempString = chTempString; sprintf(pchTempString," [%s] [SC = %s] [ESN = %s]",chPhoneNumber,phonelst.Dscm,phonelst.Desn); WriteToCallBox(pchTempString); } goto END; //} } // Check if Reorder (check for "Reo") if((chDDIdataBuffer[15]=='R') && (chDDIdataBuffer[16]=='e') && (chDDIdataBuffer[17]=='o')) { TRACE("REORDER\n"); bReorder = true; goto END; } // Check if Control channel Disconnect (check for "Di") if((chDDIdataBuffer[15]=='D') && (chDDIdataBuffer[16]=='i') ) { TRACE("DISCONNECT\n"); bDisconnect = true; goto END; } // Check if Paging (check for "Pa") if((chDDIdataBuffer[15]=='P')&&(chDDIdataBuffer[16]=='a')) { TRACE("PAGING\n"); bPaging = true; goto END; } // Check if Goto Command (check for "Go") if((chDDIdataBuffer[15]=='G')&&(chDDIdataBuffer[16]=='o')) { bGoto = true; // Jump to which channel chChannel[0] = chDDIdataBuffer[20]; chChannel[1] = chDDIdataBuffer[21]; chChannel[2] = chDDIdataBuffer[22]; chChannel[3] = chDDIdataBuffer[23]; // Jump to which frequency chGoFrequency[0] = chDDIdataBuffer[25];// 8 chGoFrequency[1] = chDDIdataBuffer[26];// 8 chGoFrequency[2] = chDDIdataBuffer[27];// 0 chGoFrequency[3] = chDDIdataBuffer[28];// . chGoFrequency[4] = chDDIdataBuffer[29];// 5 chGoFrequency[5] = chDDIdataBuffer[30];// 0 chGoFrequency[6] = '0'; if(bMonitor == true) { /* if((phonelst.DRecordCall[0]!='Y')) { bLockOut=true; } */ if((phonelst.Dalert[0]=='5')) { WriteToStatusBox(" Monitor Mode: Locked Out Level 4 Call"); bLockOut=true; } if((phonelst.Dalert[0]=='3')) { WriteToStatusBox(" Monitor Mode: Locked Out Level 3 Call"); bLockOut=true; } if((phonelst.Dalert[0]=='2')) { WriteToStatusBox(" Monitor Mode: Locked Out Level 2 Call"); bLockOut=true; } if((phonelst.Dalert[0]=='1')) { WriteToStatusBox(" Monitor Mode: Locked Out Level 1 Call"); bLockOut=true; } if((phonelst.Dalert[0]=='0')) { WriteToStatusBox(" Monitor Mode: Locked Out Level 0 Call"); bLockOut=true; } if((phonelst.Dalert[0]== 0x00)) { WriteToStatusBox(" Monitor Mode: Locked Out Level 0 Call"); bLockOut=true; } } if(bAquire == true) { if((phonelst.Dalert[0]=='3')) { bLockOut=true; } if((phonelst.Dalert[0]=='2')) { bLockOut=true; } if((phonelst.Dalert[0]=='1')) { bLockOut=true; } } } } END: TRACE("%s\n",chDDIdataBuffer); return; } void CCELLULARDlg::OnErrspaceEditStatus() { m_Edit_Status.Clear(); WriteToStatusBox(" Status Edit Box Out of Memory"); } void CCELLULARDlg::amend_record(void) { show_database(); if((phonelst.amend())!= IM_OK) { if((phonelst.amend())!= IM_OK) { if((phonelst.amend())!= IM_OK) { char chTempstring[500]; char *pchTempstring = chTempstring; sprintf(pchTempstring,"ERROR : In phonelst.amend routine\nWhere : %s\n" "number = %s\n phonelst.number = %s\n",chWhereErrorOccured,chPhoneNumber,phonelst.Dphone); MyError(pchTempstring); // WriteDebugLog(pchTempstring); } } } } void CCELLULARDlg::insert_record(void) { show_database(); if((phonelst.insert())!= IM_OK) { if((phonelst.insert())!= IM_OK) { if((phonelst.insert())!= IM_OK) { char chTempstring[500]; char *pchTempstring = chTempstring; sprintf(pchTempstring,"ERROR : In phonelst.insert routine\n" "number = %s\nphonelst.number = %s\n",chPhoneNumber,phonelst.Dphone); MyError(pchTempstring); } } } } void CCELLULARDlg::show_database(void) { m_EditPhone.SetWindowText(phonelst.Dphone); m_EditName.SetWindowText(phonelst.Dname); m_EditName2.SetWindowText(phonelst.Dname2); m_EditArea.SetWindowText(phonelst.Darea); m_EditOccupation.SetWindowText(phonelst.Doccupation); m_EditSubject.SetWindowText(phonelst.Dsubject); m_EditGender.SetWindowText(phonelst.Dgender); m_EditLanguage.SetWindowText(phonelst.Dlanguage); m_EditDtmf.SetWindowText(phonelst.DDtmfDigits); m_EditESN.SetWindowText(phonelst.Desn); m_EditSCM.SetWindowText(phonelst.Dscm); char chTempString[250]; char *pchTempString = chTempString; sprintf(pchTempString,"%s %s",phonelst.DLastCallDate, phonelst.DLastCallTime); m_EditLastCall.SetWindowText(pchTempString); sprintf(pchTempString,"%d",phonelst.DTotalCalls); m_Edit_TotalCalls.SetWindowText(pchTempString); m_EditInfo1.SetWindowText(phonelst.Dinfo1); m_EditInfo2.SetWindowText(phonelst.Dinfo2); m_EditInfo3.SetWindowText(phonelst.Dinfo3); m_EditLinkedFile.SetWindowText(phonelst.DLinkedFile); if(phonelst.Dscm[1]=='0'||'1'||'2'||'3'||'4'||'5'||'6'||'7'||'8'||'9'||'A'||'B'||'C'||'D'||'E'||'F') { show_scm(); m_EditPhoneModel.SetWindowText(chSCMstring); } if(phonelst.Desn[0]!=0x00) { manufact.hex[0]=phonelst.Desn[0]; manufact.hex[1]=phonelst.Desn[1]; if((manufact.find()== IM_OK)) { m_EditPhoneType.SetWindowText(manufact.man); } if((manufact.find()!= IM_OK)) { m_EditPhoneType.SetWindowText("Unknown Phone Manufacture"); } } else { m_EditPhoneType.SetWindowText(" "); } m_EditModemCalls.SetWindowText(phonelst.Dmodem); m_EditFaxCalls.SetWindowText(phonelst.Dfax); m_EditAlertLevel.SetWindowText(phonelst.Dalert); m_EditRecordCall.SetWindowText(phonelst.DRecordCall); m_EditChannelAB.SetWindowText(phonelst.Dtype); } void CCELLULARDlg::search(void) { if((phonelst.find()== IM_OK)) { bNewNumber=false; show_database(); /* if(phonelst.DLinkedFile[0]!=0x00) { get_linkfile(); } */ } else { if(bNewTest==true) { bNewNumber = true; return; } phonelst.clear_buf(); bAmend=false; } } void CCELLULARDlg::which_channel(void) { bool bOK = false; TRACE("which_channel chFrequency = %s\n",chFrequency); strcpy(chGoFrequency,chFrequency); ConvertGoFrequency(); //// BAND 'A' ////////////////////////////////// //////////////////////////////////////////////// if(strcmp(chFrequency,"879.990")==0) // FORWARD { chChannelBand[0]='A'; bReverseChannel = false; strcpy(chChannel,"333"); strcpy(chReverseChannel,"834.990"); bOK = true; } if(strcmp(chFrequency,"834.990")==0) //REVERSE { chChannelBand[0]='A'; bReverseChannel = true; strcpy(chChannel,"333"); strcpy(chForwardChannel,"879.990"); bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.960")==0) // FORWARD { chChannelBand[0]='A'; bReverseChannel = false; strcpy(chChannel,"332"); strcpy(chReverseChannel,"834.960"); bOK = true; } if(strcmp(chFrequency,"834.960")==0)//REVERSE { chChannelBand[0]='A'; bReverseChannel = true; strcpy(chChannel,"332"); strcpy(chForwardChannel,"879.960"); bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.930")==0) // FORWARD { chChannelBand[0]='A'; bReverseChannel = false; strcpy(chChannel,"331"); strcpy(chReverseChannel,"834.930"); bOK = true; } if(strcmp(chFrequency,"834.930")==0)//REVERSE { chChannelBand[0]='A'; bReverseChannel = true; strcpy(chChannel,"331"); strcpy(chForwardChannel,"879.930"); bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.900")==0) // FORWARD { strcpy(chChannel,"330"); strcpy(chReverseChannel,"834.900"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.900")==0)//REVERSE { strcpy(chChannel,"330"); strcpy(chForwardChannel,"879.900"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.870")==0) // FORWARD { strcpy(chChannel,"329"); strcpy(chReverseChannel,"834.870"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.870")==0)//REVERSE { strcpy(chChannel,"329"); strcpy(chForwardChannel,"879.870"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.840")==0) // FORWARD { strcpy(chChannel,"328"); strcpy(chReverseChannel,"834.840"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.840")==0)//REVERSE { strcpy(chChannel,"328"); strcpy(chForwardChannel,"879.840"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.810")==0) // FORWARD { strcpy(chChannel,"327"); strcpy(chReverseChannel,"834.810"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.810")==0)//REVERSE { strcpy(chChannel,"327"); strcpy(chForwardChannel,"879.810"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.780")==0) // FORWARD { strcpy(chChannel,"326"); strcpy(chReverseChannel,"834.780"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.780")==0)//REVERSE { strcpy(chChannel,"326"); strcpy(chForwardChannel,"879.780"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.750")==0) // FORWARD { strcpy(chChannel,"325"); strcpy(chReverseChannel,"834.750"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.750")==0)//REVERSE { strcpy(chChannel,"325"); strcpy(chForwardChannel,"879.750"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.720")==0) // FORWARD { strcpy(chChannel,"324"); strcpy(chReverseChannel,"834.720"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.720")==0)//REVERSE { strcpy(chChannel,"324"); strcpy(chForwardChannel,"879.720"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.690")==0) // FORWARD { strcpy(chChannel,"323"); strcpy(chReverseChannel,"834.690"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.690")==0)//REVERSE { strcpy(chChannel,"323"); strcpy(chForwardChannel,"879.690"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.660")==0) // FORWARD { strcpy(chChannel,"322"); strcpy(chReverseChannel,"834.660"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.660")==0)//REVERSE { strcpy(chChannel,"322"); strcpy(chForwardChannel,"879.660"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.630")==0) // FORWARD { strcpy(chChannel,"321"); strcpy(chReverseChannel,"834.630"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.630")==0)//REVERSE { strcpy(chChannel,"321"); strcpy(chForwardChannel,"879.630"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.600")==0) // FORWARD { strcpy(chChannel,"320"); strcpy(chReverseChannel,"834.600"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.600")==0)//REVERSE { strcpy(chChannel,"320"); strcpy(chForwardChannel,"879.600"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.570")==0) // FORWARD { strcpy(chChannel,"319"); strcpy(chReverseChannel,"834.570"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.570")==0)//REVERSE { strcpy(chChannel,"319"); strcpy(chForwardChannel,"879.570"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.540")==0) // FORWARD { strcpy(chChannel,"318"); strcpy(chReverseChannel,"834.540"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.540")==0)//REVERSE { strcpy(chChannel,"318"); strcpy(chForwardChannel,"879.540"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.510")==0) // FORWARD { strcpy(chChannel,"317"); strcpy(chReverseChannel,"834.510"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.510")==0)//REVERSE { strcpy(chChannel,"317"); strcpy(chForwardChannel,"879.510"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.480")==0) // FORWARD { strcpy(chChannel,"316"); strcpy(chReverseChannel,"834.480"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.480")==0)//REVERSE { strcpy(chChannel,"316"); strcpy(chForwardChannel,"879.480"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.450")==0) // FORWARD { strcpy(chChannel,"315"); strcpy(chReverseChannel,"834.450"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.450")==0)//REVERSE { strcpy(chChannel,"315"); strcpy(chForwardChannel,"879.450"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.420")==0) // FORWARD { strcpy(chChannel,"314"); strcpy(chReverseChannel,"834.420"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.420")==0)//REVERSE { strcpy(chChannel,"314"); strcpy(chForwardChannel,"879.420"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"879.390")==0) // FORWARD { strcpy(chChannel,"313"); strcpy(chReverseChannel,"834.390"); bReverseChannel = false; chChannelBand[0]='A'; bOK = true; } if(strcmp(chFrequency,"834.390")==0)//REVERSE { strcpy(chChannel,"313"); strcpy(chForwardChannel,"879.390"); bReverseChannel = true; chChannelBand[0]='A'; bOK = true; } ///////////// Band 'B' ///////////////////////// //////////////////////////////////////////////// if(strcmp(chFrequency,"880.020")==0) // FORWARD { strcpy(chChannel,"334"); strcpy(chReverseChannel,"835.020"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.020")==0)//REVERSE { strcpy(chChannel,"334"); strcpy(chForwardChannel,"880.020"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.050")==0) // FORWARD { strcpy(chChannel,"335"); strcpy(chReverseChannel,"835.050"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.050")==0)//REVERSE { strcpy(chChannel,"335"); strcpy(chForwardChannel,"880.050"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.080")==0) // FORWARD { strcpy(chChannel,"336"); strcpy(chReverseChannel,"835.080"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.080")==0)//REVERSE { strcpy(chChannel,"336"); strcpy(chForwardChannel,"880.080"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.110")==0) // FORWARD { strcpy(chChannel,"337"); strcpy(chReverseChannel,"835.110"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.110")==0)//REVERSE { strcpy(chChannel,"337"); strcpy(chForwardChannel,"880.110"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.140")==0) // FORWARD { strcpy(chChannel,"338"); strcpy(chReverseChannel,"835.140"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.140")==0)//REVERSE { strcpy(chChannel,"338"); strcpy(chForwardChannel,"880.140"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.170")==0) // FORWARD { strcpy(chChannel,"339"); strcpy(chReverseChannel,"835.170"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.170")==0)//REVERSE { strcpy(chChannel,"339"); strcpy(chForwardChannel,"880.170"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.200")==0) // FORWARD { strcpy(chChannel,"340"); strcpy(chReverseChannel,"835.200"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.200")==0)//REVERSE { strcpy(chChannel,"340"); strcpy(chForwardChannel,"880.200"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.230")==0) // FORWARD { strcpy(chChannel,"341"); strcpy(chReverseChannel,"835.230"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.230")==0)//REVERSE { strcpy(chChannel,"341"); strcpy(chForwardChannel,"880.230"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.260")==0) // FORWARD { strcpy(chChannel,"342"); strcpy(chReverseChannel,"835.260"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.260")==0)//REVERSE { strcpy(chChannel,"342"); strcpy(chForwardChannel,"880.260"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.290")==0) // FORWARD { strcpy(chChannel,"343"); strcpy(chReverseChannel,"835.290"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.290")==0)//REVERSE { strcpy(chChannel,"343"); strcpy(chForwardChannel,"880.290"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.320")==0) // FORWARD { strcpy(chChannel,"344"); strcpy(chReverseChannel,"835.320"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.320")==0)//REVERSE { strcpy(chChannel,"344"); strcpy(chForwardChannel,"880.320"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.350")==0) // FORWARD { strcpy(chChannel,"345"); strcpy(chReverseChannel,"835.350"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.350")==0)//REVERSE { strcpy(chChannel,"345"); strcpy(chForwardChannel,"880.350"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.380")==0) // FORWARD { strcpy(chChannel,"346"); strcpy(chReverseChannel,"835.380"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.380")==0)//REVERSE { strcpy(chChannel,"346"); strcpy(chForwardChannel,"880.380"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.410")==0) // FORWARD { strcpy(chChannel,"347"); strcpy(chReverseChannel,"835.410"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.410")==0)//REVERSE { strcpy(chChannel,"347"); strcpy(chForwardChannel,"880.410"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.440")==0) // FORWARD { strcpy(chChannel,"348"); strcpy(chReverseChannel,"835.440"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.440")==0)//REVERSE { strcpy(chChannel,"348"); strcpy(chForwardChannel,"880.440"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.470")==0) // FORWARD { strcpy(chChannel,"349"); strcpy(chReverseChannel,"835.470"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.470")==0)//REVERSE { strcpy(chChannel,"349"); strcpy(chForwardChannel,"880.470"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.500")==0) // FORWARD { strcpy(chChannel,"350"); strcpy(chReverseChannel,"835.500"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.500")==0)//REVERSE { strcpy(chChannel,"350"); strcpy(chForwardChannel,"880.500"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.530")==0) // FORWARD { strcpy(chChannel,"351"); strcpy(chReverseChannel,"835.530"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.530")==0)//REVERSE { strcpy(chChannel,"351"); strcpy(chForwardChannel,"880.530"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.560")==0) // FORWARD { strcpy(chChannel,"352"); strcpy(chReverseChannel,"835.560"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.560")==0)//REVERSE { strcpy(chChannel,"352"); strcpy(chForwardChannel,"880.560"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.590")==0) // FORWARD { strcpy(chChannel,"353"); strcpy(chReverseChannel,"835.590"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.590")==0)//REVERSE { strcpy(chChannel,"353"); strcpy(chForwardChannel,"880.590"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } //////////////////////////////////////////////// if(strcmp(chFrequency,"880.620")==0) // FORWARD { strcpy(chChannel,"354"); strcpy(chReverseChannel,"835.620"); bReverseChannel = false; chChannelBand[0]='B'; bOK = true; } if(strcmp(chFrequency,"835.620")==0)//REVERSE { strcpy(chChannel,"354"); strcpy(chForwardChannel,"880.620"); bReverseChannel = true; chChannelBand[0]='B'; bOK = true; } if(bOK != true) { MyError("This is not a valid Control Channel Frequency\nPlease choose a different one"); return; } if(bReverseChannel == false) { m_ButtonSwitchControlType.SetWindowText("Switch To Reverse Control"); strcpy(chChannelType,"Forward Control"); } else { m_ButtonSwitchControlType.SetWindowText("Switch To Forward Control"); strcpy(chChannelType,"Reverse Control"); } /* if (iWhichcontrolChannel == 1) { stanum=0x80; endnum=0x50; //strcpy(name,"TELCEL"); strcpy(chChannelType,"Forward Control"); strcpy(chGoFrequency,"880.500"); // strcpy(chChannel,"0350"); chChannelBand[0]='B'; } if (iWhichcontrolChannel == 2) { //strcpy(name,"Baja Cellular"); strcpy(chChannelType,"Forward Control"); // Most of the time this one stanum=0x79; endnum=0x54; strcpy(chGoFrequency,"879.540"); // strcpy(chChannel,"0318"); // But sometimes this one //stanum=0x79; endnum=0x42; //strcpy(chGoFrequency,"879.420"); //strcpy(chChannel,"0314"); chChannelBand[0]='A'; } if (iWhichcontrolChannel == 3) { stanum=0x35; endnum=0x50; //strcpy(name,"TELCEL"); strcpy(chChannelType,"Reverse Control"); strcpy(chGoFrequency,"835.500"); // strcpy(chChannel,"0350"); chChannelBand[0]='B'; } if (iWhichcontrolChannel == 4) { stanum=0x34; endnum=0x54; //strcpy(name,"Baja Cellular"); strcpy(chChannelType,"Reverse Control"); strcpy(chGoFrequency,"834.540"); // strcpy(chChannel,"0318"); // But sometimes this one // stanum=0x34; endnum=0x42; // strcpy(chGoFrequency,"834.420"); // strcpy(chChannel,"0314"); chChannelBand[0]='A'; } */ UpdateChannelStats(); } void CCELLULARDlg::InitalizeOS456(void) { WriteToStatusBox(" Initalizing OS456"); ComInit(iCommPortOS456); if(ComValid(iCommPortOS456)) { ComSetState(iCommPortOS456,9600,8,1,'N',SIGNAL_NONE); ComBufClear(iCommPortOS456,DIR_INC); ComBufClear(iCommPortOS456,DIR_OUT); WriteToStatusBox(" OS456 Comm Port Initalized @ 9600 BPS"); } else { char chTempString[250]; char *pchTempString = chTempString; sprintf(pchTempString,"Com Port %d is not available or is in use",iCommPortOS456+1); MyError(pchTempString); return; } ComDTROn(iCommPortOS456); // set DTR ComRTSOn(iCommPortOS456); // set RTS osremote(); osmode(); osspeakeroff(); osfreq(endnum,stanum); } // OS456 General access Commands void CCELLULARDlg::os456(void) { // Sleep(100); Sleep(30); ComWrite(iCommPortOS456,(char)0xFE); ComWrite(iCommPortOS456,(char)0xFE); ComWrite(iCommPortOS456,(char)0x80); ComWrite(iCommPortOS456,(char)0xE0); } // Switch OS456 transfer mode to FM-narrowband void CCELLULARDlg::osmode(void) { os456(); ComWrite(iCommPortOS456,(char)0x01); ComWrite(iCommPortOS456,(char)0x05); ComWrite(iCommPortOS456,(char)0xFD); } // Switch OS456 to Local Control void CCELLULARDlg::oslocal(void) { os456(); ComWrite(iCommPortOS456,(char)0x7F); ComWrite(iCommPortOS456,(char)0x01); ComWrite(iCommPortOS456,(char)0xFD); } // Switch OS456 to Remote Control void CCELLULARDlg::osremote(void) { os456(); ComWrite(iCommPortOS456,(char)0x7F); ComWrite(iCommPortOS456,(char)0x02); ComWrite(iCommPortOS456,(char)0xFD); } // Switch OS456 Frequency void CCELLULARDlg::osfreq(int endnum,int stanum) { int iTest = 1; again: os456(); ComWrite(iCommPortOS456,(char)0x00); // always ComWrite(iCommPortOS456,(char)0x00); // always ComWrite(iCommPortOS456,(char)0x00); // always ComWrite(iCommPortOS456,(char)endnum); // 880.XX00 0x50 ComWrite(iCommPortOS456,(char)stanum); // 8XX.5000 0x80 ComWrite(iCommPortOS456,(char)0x08); // X80.5000 (always 8 for 800 band cellular) ComWrite(iCommPortOS456,(char)0xFD); // always if(iTest==5) { WriteToStatusBox(" Error : in fuction [osfreqcheck] (5 Tries!)"); return; } iTest ++; if (osfreqcheck()== 1){ goto again;} // signal strength // Sleep(100); ossignalstr(); UpdateChannelStats(); } int CCELLULARDlg::osfreqcheck(void) { /* Sleep(250); ComBufClear(iCommPortOS456,DIR_INC); osreadfreq(); Sleep(250); char ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15,ch16; if(ComRead(iCommPortOS456,&ch1)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 1"); } if(ComRead(iCommPortOS456,&ch2)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 2"); } if(ComRead(iCommPortOS456,&ch3)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 3"); } if(ComRead(iCommPortOS456,&ch4)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 4"); } if(ComRead(iCommPortOS456,&ch5)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 5"); } if(ComRead(iCommPortOS456,&ch6)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 6"); } if(ComRead(iCommPortOS456,&ch7)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 7"); } if(ComRead(iCommPortOS456,&ch8)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 8"); } if(ComRead(iCommPortOS456,&ch9)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 9"); } if(ComRead(iCommPortOS456,&ch10)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 10"); } if(ComRead(iCommPortOS456,&ch11)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 11"); } if(ComRead(iCommPortOS456,&ch12)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 12"); } if(ComRead(iCommPortOS456,&ch13)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 13"); } if(ComRead(iCommPortOS456,&ch14)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 14"); } if(ComRead(iCommPortOS456,&ch15)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 15"); } if(ComRead(iCommPortOS456,&ch16)==FALSE) { WriteToStatusBox(" ERROR: OS456 Frequency reading byte 16"); } char chTempString[500]; char *pchTempString = chTempString; TRACE("FREQ DATA: 1[%2X] 2[%2X] 3[%2X] 4[%2X] 5[%2X] 6[%2X] 7[%2X] 8[%2X] 9[%2X] 10[%2X] 11[%2X] 12[%2X] 13[%2X] 14[%2X] 15[%2X] 16[%2X]\n", ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15,ch16); TRACE("FREQ2 DATA: endnum[%2X] stanum[%2X] \n",endnum,stanum); if ((ch12!=0x00)|| (ch13!=0x00) || (ch14!=endnum) || (ch15!=stanum) || (ch16!=0x08)) //&& ((ch14!=0x00)|| (ch15!=0x00) || (ch16!=endnum) || (ch17!=stanum) || (ch18!=0x08)) // && ((ch15!=0x00)|| (ch16!=0x00) || (ch17!=endnum) || (ch18!=stanum) || (ch19!=0x08)) ) { WriteToStatusBox(" ERROR: OS456 Frequency Check Failed so trying again"); TRACE("FREQ ERROR\n"); // char chTempString[250]; //char *pchTempString = chTempString; //sprintf(pchTempString," [%c][%c][%c]",ch17,ch18,ch19); //WriteToStatusBox(pchTempString); return 1; } */ return OK; } void CCELLULARDlg::osreadfreq(void) { os456(); ComWrite(iCommPortOS456,(char)0x03); ComWrite(iCommPortOS456,(char)0xFD); } // Switch OS456 Speaker OFF void CCELLULARDlg::osspeakeroff(void) { int iTest=1; again: ComBufClear(iCommPortOS456,DIR_INC); os456(); ComWrite(iCommPortOS456,(char)0x7F); ComWrite(iCommPortOS456,(char)0x0B); ComWrite(iCommPortOS456,(char)0xFD); iTest++; if(iTest==5) { MyError("Error : in fuction [osspeakercheck (osspeakeroff)] (5 Tries!)"); } iTest++; if(osspeakercheck()== 1){ goto again;} } // Switch OS456 Speaker ON void CCELLULARDlg::osspeakeron(void) { int iTest=1; again: ComBufClear(iCommPortOS456,DIR_INC); os456(); ComWrite(iCommPortOS456,(char)0x7F); ComWrite(iCommPortOS456,(char)0x0A); ComWrite(iCommPortOS456,(char)0xFD); iTest++; if(iTest==5) { MyError("Error : in fuction [osspeakercheck (osspeakeron)] (5 Tries!)"); } iTest++; if (osspeakercheck()== 1){ goto again;} } int CCELLULARDlg::osspeakercheck(void) { char ch1=0,ch2=0,ch3=0,ch4=0,ch5=0,ch6=0,ch7=0,ch8=0,ch9=0,ch10=0,ch11=0,ch12=0,ch13=0; Sleep(250); // Sleep(30); // TRYAGAIN: // if(ComBufCount(iCommPortOS456,DIR_INC) >= 15) { if(ComRead(iCommPortOS456,&ch1)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 1"); } if(ComRead(iCommPortOS456,&ch2)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 2"); } if(ComRead(iCommPortOS456,&ch3)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 3"); } if(ComRead(iCommPortOS456,&ch4)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 4"); } if(ComRead(iCommPortOS456,&ch5)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 5"); } if(ComRead(iCommPortOS456,&ch6)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 6"); } if(ComRead(iCommPortOS456,&ch7)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 7"); } if(ComRead(iCommPortOS456,&ch8)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 8"); } if(ComRead(iCommPortOS456,&ch9)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 9"); } if(ComRead(iCommPortOS456,&ch10)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 10"); } if(ComRead(iCommPortOS456,&ch11)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 11"); } if(ComRead(iCommPortOS456,&ch12)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 12"); } if(ComRead(iCommPortOS456,&ch13)==FALSE) { WriteToStatusBox(" ERROR: OS456 osspeakercheck reading byte 13"); } } /* else { Sleep(100); char chTempString[100]; char *pchTempString = chTempString; sprintf(pchTempString," OS456 Buffercount = %d ",ComBufCount(iCommPortOS456,DIR_INC) ); WriteToStatusBox(pchTempString); goto TRYAGAIN; } */ char chTempString[500]; char *pchTempString = chTempString; TRACE("SPEAKER DATA:1[%2X] 2[%2X] 3[%2X] 4[%2X] 5[%2X] 6[%2X] 7[%2X] 8[%2X] 9[%2X] 10[%2X] 11[%2X] 12[%2X] 13[%2X]\n", ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13); if((ch10!=0xFFFFFFE0)|| (ch11!=0xFFFFFF80) || (ch12!=0xFFFFFFFB) || (ch13!=0xFFFFFFFD)) // if(((ch10!=0xE0)|| (ch11!=0x80) || (ch12!=0xFB)) // &&((ch12!=0xE0)|| (ch13!=0x80) || (ch14!=0xFB)) // &&((ch13!=0xE0)|| (ch14!=0x80) || (ch15!=0xFB))) { WriteToStatusBox(" ERROR: OS456 Speaker Check Failed!"); return 1; } else { // WriteToStatusBox(" OS456 Speaker Check Returned OK"); return OK; } } void CCELLULARDlg::ossignalstr(void) { ComBufClear(iCommPortOS456,DIR_INC); os456(); ComWrite(iCommPortOS456,(char)0x15); ComWrite(iCommPortOS456,(char)0x02); ComWrite(iCommPortOS456,(char)0xFD); Sleep(30); char ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15; if(ComRead(iCommPortOS456,&ch1)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 1"); } if(ComRead(iCommPortOS456,&ch2)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 2"); } if(ComRead(iCommPortOS456,&ch3)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 3"); } if(ComRead(iCommPortOS456,&ch4)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 4"); } if(ComRead(iCommPortOS456,&ch5)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 5"); } if(ComRead(iCommPortOS456,&ch6)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 6"); } if(ComRead(iCommPortOS456,&ch7)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 7"); } if(ComRead(iCommPortOS456,&ch8)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 8"); } if(ComRead(iCommPortOS456,&ch9)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 9"); } if(ComRead(iCommPortOS456,&ch10)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 10"); } if(ComRead(iCommPortOS456,&ch11)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 11"); } if(ComRead(iCommPortOS456,&ch12)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 12"); } if(ComRead(iCommPortOS456,&ch13)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 13"); } if(ComRead(iCommPortOS456,&ch14)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 14"); } if(ComRead(iCommPortOS456,&ch15)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossignalstr reading byte 15"); } // sprintf(chSignalStrength,"-%X.%X dBm",ch14,ch15); if(ch14 == 0x00) { if(ch15 == 0x00) { sprintf(chSignalStrength,"- 0 dBm",ch15); } else if(ch15 == 0x01) { sprintf(chSignalStrength,"- 1 dBm",ch15); } else if(ch15 == 0x02) { sprintf(chSignalStrength,"- 2 dBm",ch15); } else if(ch15 == 0x03) { sprintf(chSignalStrength,"- 3 dBm",ch15); } else if(ch15 == 0x04) { sprintf(chSignalStrength,"- 4 dBm",ch15); } else if(ch15 == 0x05) { sprintf(chSignalStrength,"- 5 dBm",ch15); } else if(ch15 == 0x06) { sprintf(chSignalStrength,"- 6 dBm",ch15); } else if(ch15 == 0x07) { sprintf(chSignalStrength,"- 7 dBm",ch15); } else if(ch15 == 0x08) { sprintf(chSignalStrength,"- 8 dBm",ch15); } else if(ch15 == 0x09) { sprintf(chSignalStrength,"- 9 dBm",ch15); } else if(ch15 >= 0x10) { sprintf(chSignalStrength,"- %X dBm",ch15); } } if(ch14 == 0x01) { if(ch15 == 0x00) { sprintf(chSignalStrength,"- 100 dBm",ch15); } else if(ch15 == 0x01) { sprintf(chSignalStrength,"- 101 dBm",ch15); } else if(ch15 == 0x02) { sprintf(chSignalStrength,"- 102 dBm",ch15); } else if(ch15 == 0x03) { sprintf(chSignalStrength,"- 103 dBm",ch15); } else if(ch15 == 0x04) { sprintf(chSignalStrength,"- 104 dBm",ch15); } else if(ch15 == 0x05) { sprintf(chSignalStrength,"- 105 dBm",ch15); } else if(ch15 == 0x06) { sprintf(chSignalStrength,"- 106 dBm",ch15); } else if(ch15 == 0x07) { sprintf(chSignalStrength,"- 107 dBm",ch15); } else if(ch15 == 0x08) { sprintf(chSignalStrength,"- 108 dBm",ch15); } else if(ch15 == 0x09) { sprintf(chSignalStrength,"- 109 dBm",ch15); } else if(ch15 >= 0x10) { sprintf(chSignalStrength,"- 1%X dBm",ch15); } } m_EditSignalStrength.SetWindowText(chSignalStrength); char chTempString[100]; char *pchTempString = chTempString; sprintf(pchTempString,"%X%X",ch14,ch15); int iSignal = atoi(pchTempString); if(iSignal <= 125) { if(iSignal <= 100) { m_ProgressSignal.SetPos(25); } else if(iSignal == 101) { m_ProgressSignal.SetPos(24); } else if(iSignal == 102) { m_ProgressSignal.SetPos(23); } else if(iSignal == 103) { m_ProgressSignal.SetPos(22); } else if(iSignal == 104) { m_ProgressSignal.SetPos(21); } else if(iSignal == 105) { m_ProgressSignal.SetPos(20); } else if(iSignal == 106) { m_ProgressSignal.SetPos(19); } else if(iSignal == 107) { m_ProgressSignal.SetPos(18); } else if(iSignal == 108) { m_ProgressSignal.SetPos(17); } else if(iSignal == 109) { m_ProgressSignal.SetPos(16); } else if(iSignal == 110) { m_ProgressSignal.SetPos(15); } else if(iSignal == 111) { m_ProgressSignal.SetPos(14); } else if(iSignal == 112) { m_ProgressSignal.SetPos(13); } else if(iSignal == 113) { m_ProgressSignal.SetPos(12); } else if(iSignal == 114) { m_ProgressSignal.SetPos(11); } else if(iSignal == 115) { m_ProgressSignal.SetPos(10); } else if(iSignal == 116) { m_ProgressSignal.SetPos(9); } else if(iSignal == 117) { m_ProgressSignal.SetPos(8); } else if(iSignal == 118) { m_ProgressSignal.SetPos(7); } else if(iSignal == 119) { m_ProgressSignal.SetPos(6); } else if(iSignal == 120) { m_ProgressSignal.SetPos(5); } else if(iSignal == 121) { m_ProgressSignal.SetPos(4); } else if(iSignal == 122) { m_ProgressSignal.SetPos(3); } else if(iSignal == 123) { m_ProgressSignal.SetPos(2); } else if(iSignal == 124) { m_ProgressSignal.SetPos(1); } else if(iSignal == 125) { m_ProgressSignal.SetPos(0); } } } void CCELLULARDlg::ossquelch(void) { ComBufClear(iCommPortOS456,DIR_INC); os456(); ComWrite(iCommPortOS456,(char)0x15); ComWrite(iCommPortOS456,(char)0x01); ComWrite(iCommPortOS456,(char)0xFD); Sleep(250); // Sleep(30); char ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14; if(ComRead(iCommPortOS456,&ch1)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 1"); } if(ComRead(iCommPortOS456,&ch2)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 2"); } if(ComRead(iCommPortOS456,&ch3)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 3"); } if(ComRead(iCommPortOS456,&ch4)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 4"); } if(ComRead(iCommPortOS456,&ch5)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 5"); } if(ComRead(iCommPortOS456,&ch6)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 6"); } if(ComRead(iCommPortOS456,&ch7)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 7"); } if(ComRead(iCommPortOS456,&ch8)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 8"); } if(ComRead(iCommPortOS456,&ch9)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 9"); } if(ComRead(iCommPortOS456,&ch10)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 10"); } if(ComRead(iCommPortOS456,&ch11)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 11"); } if(ComRead(iCommPortOS456,&ch12)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 12"); } if(ComRead(iCommPortOS456,&ch13)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 13"); } if(ComRead(iCommPortOS456,&ch14)==FALSE) { WriteToStatusBox(" ERROR: OS456 ossquelch reading byte 14"); } char chTempString[500]; char *pchTempString = chTempString; TRACE("SQUELCH DATA: 1[%2X] 2[%2X] 3[%2X] 4[%2X] 5[%2X] 6[%2X] 7[%2X] 8[%2X] 9[%2X] 10[%2X] 11[%2X] 12[%2X] 13[%2X] 14[%2X]\n", ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14); if (ch14==0x00) { WriteToStatusBox(" OS456 reports Squelch is CLOSED"); squelch = CLOSED; } if (ch14==0x01) { TRACE("OS456 reports Squelch is OPEN"); squelch = OPEN; } } void CCELLULARDlg::SetDDIvoiceMode(void) { WriteToStatusBox(" Sending DDI Command to switch to VOICE mode."); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'V'); } void CCELLULARDlg::SetDDItoControlChannel(void) { WriteToStatusBox(" Sending DDI Command to switch to Control Channel"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'C'); } void CCELLULARDlg::SetDDItoForward(void) { WriteToStatusBox(" Sending DDI Command to switch to Forward Channel Mode"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'r'); bReverseChannel = false; } void CCELLULARDlg::SetDDItoReverse(void) { WriteToStatusBox(" Sending DDI Command to switch to Reverse Channel Mode"); ComWrite(iCommPortDDI,'-'); ComWrite(iCommPortDDI,'R'); bReverseChannel = true; } void CCELLULARDlg::check_call_time(void) { time_t current_time; current_time=time(NULL); if(current_time>=start_time+iMaxCallTime) { squelch=CLOSED; } } void CCELLULARDlg::switch_to_voice(void) { MessageBeep(MB_OK); /* if(logit==TRUE) { fprintf(log," \n"); } */ ConvertGoFrequency(); SetDDIvoiceMode(); strcpy(chChannelType,"Forward Voice"); osfreq(endnum,stanum); ComBufClear(iCommPortDDI,DIR_INC); osspeakeron(); /* for(j=0;j < BUFFERSIZE2 ;j++) { for(k=0;k < BUFFERLENGTH ;k++) {voicebuffer[j][k] =(char) 0x00;} } whichbuffer2=1; noofrings=0; ring=FALSE; */ // call started m_EditStart.SetWindowText(timeis); m_EditCallEnd.SetWindowText(" "); start_time=time(NULL); // Start Second Timer for iMaxCallTime Function if(phonelst.Darea[0]==0x00) { strcpy(phonelst.Darea,chArea); } if(phonelst.Dtype[0]==0x00) { phonelst.Dtype[0]=chChannelBand[0]; } if(phonelst.DLastCallDate[0]==0x00) { strcpy(phonelst.DLastCallDate,dateis); } if(phonelst.DLastCallTime[0]==0x00) { strcpy(phonelst.DLastCallTime,d_timeis); } if(phonelst.Dphone[0]==0x00) { strcpy(phonelst.Dphone,chPhoneNumber); phonelst.Dphone[14]=0x00; insert_record(); } show_database(); // Increment Total Call Counter char chTempString[50]; char *pchTempString = chTempString; iCallCounter_total++; sprintf(pchTempString,"%d",iCallCounter_total); m_Text_CallsTotal.SetWindowText(pchTempString); if(phonelst.Dalert[0]==0x00||phonelst.Dalert[0]=='0') { iCallCounter_0++; sprintf(pchTempString,"%d",iCallCounter_0); m_Text_CallsLevel0.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='1') { iCallCounter_1++; sprintf(pchTempString,"%d",iCallCounter_1); m_Text_CallsLevel1.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='2') { iCallCounter_2++; sprintf(pchTempString,"%d",iCallCounter_2); m_Text_CallsLevel2.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='3') { iCallCounter_3++; sprintf(pchTempString,"%d",iCallCounter_3); m_Text_CallsLevel3.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='4') { iCallCounter_4++; sprintf(pchTempString,"%d",iCallCounter_4); m_Text_CallsLevel4.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='5') { iCallCounter_5++; sprintf(pchTempString,"%d",iCallCounter_5); m_Text_CallsLevel5.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='6') { iCallCounter_6++; sprintf(pchTempString,"%d",iCallCounter_6); m_Text_CallsLevel6.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='7') { iCallCounter_7++; sprintf(pchTempString,"%d",iCallCounter_7); m_Text_CallsLevel7.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='8') { iCallCounter_8++; sprintf(pchTempString,"%d",iCallCounter_8); m_Text_CallsLevel8.SetWindowText(pchTempString); } if(phonelst.Dalert[0]=='9') { iCallCounter_9++; sprintf(pchTempString,"%d",iCallCounter_9); m_Text_CallsLevel9.SetWindowText(pchTempString); } if(phonelst.Dmodem[0]=='Y') { iCallCounter_modem++; sprintf(pchTempString,"%d",iCallCounter_modem); m_Text_CallsModem.SetWindowText(pchTempString); } if(phonelst.Dfax[0]=='Y') { iCallCounter_fax++; sprintf(pchTempString,"%d",iCallCounter_fax); m_Text_CallsFax.SetWindowText(pchTempString); } /* if(logit==TRUE) { fprintf(log,"\n %s %s (%s)\n" ,timeis,number,area); fprintf(log," Changing to Voice Channel %s at %s MHz\n" ,chChannel,chGoFrequency); fprintf(log," %s\n",chSignalStrength); } */ bCancelCall = false; // rev = FALSE; /* if(((phonelst.DRecordCall[0]==Y)||(bRecordAll==TRUE))&&(bRecording==FALSE)) { rec_raw(); bRecording = TRUE; record_on_box(); iCallCounter_record++; sprintf(pchTempString,"%04d",iCallCounter_record); m_Text_CallsRecorded.SetWindowText(pchTempString); } */ Sleep(250); // This is to give the MCI Device time to respond //////////////////////////////////////////////////////////////////////// #ifdef RECORD DWORD dwReturn; MCI_OPEN_PARMS mciOpenParms; MCI_RECORD_PARMS mciRecordParms; // Open a waveform-audio device with a new file for recording. mciOpenParms.lpstrDeviceType = "waveaudio"; mciOpenParms.lpstrElementName = ""; if(dwReturn = mciSendCommand(0, MCI_OPEN,MCI_OPEN_ELEMENT | MCI_OPEN_TYPE,(DWORD)(LPVOID) &mciOpenParms)) { MyError("Failed to open MCI device;"); return; } // The device opened successfully; get the device ID. wDeviceID = mciOpenParms.wDeviceID; // Begin recording and record for the specified number of // milliseconds. Wait for recording to complete before continuing. // Assume the default time format for the waveform-audio device // (milliseconds). //mciRecordParms.dwTo = dwMilliSeconds; if(dwReturn = mciSendCommand(wDeviceID, MCI_RECORD,MCI_TO , (DWORD)(LPVOID) &mciRecordParms)) { mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL); MyError("Failed to to tell MCI device to record."); return; } //////////////////////////////////////////////////////////////////////// #endif char chTotalTime[30]; char *pchTotalTime = chTotalTime; strcpy(pchTotalTime,"NONE"); char chTempBuffer[500]; char *pchTempBuffer = chTempBuffer; sprintf(pchTempBuffer," %s %s\tGoto Voice Chann\t%s",timeis,chPhoneNumber,chArea); WriteToStatusBox(pchTempBuffer); ossquelch(); for(int i=0; i < 5; i++) { if(squelch==CLOSED) { Sleep(100); ossquelch(); } else { break; } } while(squelch==OPEN) { ossignalstr(); if(bGoReverseVoice == true) { bGoReverseVoice = false; GoReverseVoice(); } if(bGoForwardVoice == true) { bGoForwardVoice = false; GoForwardVoice(); } if(bHoldCall==false) { ossquelch(); check_call_time(); } if(bCancelCall==true) { bCancelCall=false; WriteToStatusBox(" GOT SKIPPED VOICE COMMAND FROM MAIN FORWARD VOICE"); break; } time_t current_time; current_time=time(NULL); double fSeconds = difftime(current_time,start_time); if(fSeconds < 60) { sprintf(pchTotalTime,"%.0f Seconds",fSeconds); } else { double fMinutes = fSeconds / 60; sprintf(pchTotalTime,"%.2f Minutes",fMinutes); } m_EditCallTime.SetWindowText(pchTotalTime); char i; if(ComRead(iCommPortDDI,&i)==TRUE) { if(i==0x0D) { char chTempBuffer[500]; char *pchTempBuffer = chTempBuffer; iBufferCounter=-1; whattime(); AnalyzeDDIdata(); if(bGoto ==true) { ZeroMemVariables(); } else if(bVoiceGoto ==true) { sprintf(pchTempBuffer," %s %s\tGoto in Voice Function %s\t%s",timeis,chPhoneNumber,chGoFrequency,chArea); WriteToStatusBox(pchTempBuffer); ZeroMemVariables(); ConvertGoFrequency(); squelch=OPEN; osfreq(endnum,stanum); Sleep(100); squelch=OPEN; } } // End if (i>1) if((i>=0x20) && (i <=0x7A)) { iBufferCounter++; chDDIdataBuffer[iBufferCounter] = (char) i;; } } } // End While m_ButtonSwitchVoice.SetWindowText("Reverse Voice"); bVoiceForward = true; // call ended whattime(); m_EditCallEnd.SetWindowText(timeis); strcpy(phonelst.DLastCallDate,dateis); strcpy(phonelst.DLastCallTime,d_timeis); phonelst.DTotalCalls++; //////////////////////////////////////////////////////////////////////// iWaveFileNumber++; WriteWhoFile(iWaveFileNumber,pchTotalTime); UpdateCallList(iWaveFileNumber,pchTotalTime); #ifdef RECORD sprintf(chTempBuffer,"RECORD\\%d.WAV",iWaveFileNumber); MCI_SAVE_PARMS mciSaveParms; mciSaveParms.lpfilename = chTempBuffer; // mciSaveParms.lpfilename = "tempfile.wav"; if(dwReturn = mciSendCommand(wDeviceID, MCI_SAVE,MCI_SAVE_FILE | MCI_WAIT, (DWORD)(LPVOID) &mciSaveParms)) { mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL); MyError("Failed to SAVE MCI device wavefile;"); return; } //////////////////////////////////////////////////////////////////////// mciSendCommand(wDeviceID, MCI_CLOSE, 0, NULL); #endif CopyEditFieldsToDataBase(); strcpy(chWhereErrorOccured,"switch_to_voice"); amend_record(); // Error Because of this Amend Routine ComBufClear(iCommPortDDI,DIR_INC); // Flush DDI Recieve Port so extra stuff doesnt appear when finished ZeroMemVariables(); osspeakeroff(); SetDDItoControlChannel(); SetDDItoForward(); which_channel(); osfreq(endnum,stanum); // UpdateChannelStats(); /* if(logit==TRUE) { fprintf(log,"\n %s %s @ %s [%s]\n",name,type,chChannel,chGoFrequency); fprintf(log," %s\n\n",chSignalStrength); } */ } /* m_EditPhone.LimitText(14); m_EditName.LimitText(30); m_EditName2.LimitText(30); m_EditArea.LimitText(30); m_EditOccupation.LimitText(30); m_EditSubject.LimitText(30); m_EditLanguage.LimitText(10); m_EditGender.LimitText(1); m_EditInfo1.LimitText(30); m_EditInfo2.LimitText(30); m_EditInfo3.LimitText(30); m_EditLinkedFile.LimitText(12); m_EditModemCalls.LimitText(1); m_EditFaxCalls.LimitText(1); m_EditAlertLevel.LimitText(1); m_EditRecordCall.LimitText(1); m_EditDtmf.LimitText(30); m_EditESN.LimitText(8); m_EditSCM.LimitText(2); */ void CCELLULARDlg::OnButtonSkipvoicecall() { WriteToStatusBox(" Skip voice call button pressed"); bCancelCall=true; } void CCELLULARDlg::CopyEditFieldsToDataBase(void) { m_EditPhone.GetWindowText(phonelst.Dphone,15); m_EditName.GetWindowText(phonelst.Dname,31); m_EditName2.GetWindowText(phonelst.Dname2,31); m_EditArea.GetWindowText(phonelst.Darea,31); m_EditOccupation.GetWindowText(phonelst.Doccupation,31); m_EditSubject.GetWindowText(phonelst.Dsubject,31); m_EditLanguage.GetWindowText(phonelst.Dlanguage,11); m_EditGender.GetWindowText(phonelst.Dgender,2); m_EditInfo1.GetWindowText(phonelst.Dinfo1,31); m_EditInfo2.GetWindowText(phonelst.Dinfo2,31); m_EditInfo3.GetWindowText(phonelst.Dinfo3,31); m_EditLinkedFile.GetWindowText(phonelst.DLinkedFile,13); m_EditModemCalls.GetWindowText(phonelst.Dmodem,2); m_EditFaxCalls.GetWindowText(phonelst.Dfax,2); m_EditAlertLevel.GetWindowText(phonelst.Dalert,2); m_EditRecordCall.GetWindowText(phonelst.DRecordCall,2); m_EditDtmf.GetWindowText(phonelst.DDtmfDigits,31); m_EditESN.GetWindowText(phonelst.Desn,9); m_EditSCM.GetWindowText(phonelst.Dscm,3); } void CCELLULARDlg::OnButtonSaveData() { phonelst.clear_buf(); m_EditPhone.GetWindowText(phonelst.Dphone,15); if((phonelst.find()== IM_OK)) { CopyEditFieldsToDataBase(); strcpy(chWhereErrorOccured,"OnButtonSaveData"); amend_record(); } else { MyError("Could not append record in fuction OnButtonSaveData"); } } void CCELLULARDlg::OnButtonFindPhone() { phonelst.clear_buf(); m_EditPhone.GetWindowText(phonelst.Dphone,15); search(); if((bNewNumber == true)||(bAmend==false)) { phonelst.clear_buf(); return; } } void CCELLULARDlg::OnCheckHoldcall() { if(bHoldCall==false) { bHoldCall = true; return; } else { bHoldCall = false; return; } } void CCELLULARDlg::UpdateCallList(int iWaveFileNumber,char *pchTotalTime) { char chTempBuffer[500]; char *pchTempBuffer = chTempBuffer; if(phonelst.Dalert[0]==0x00) { phonelst.Dalert[0] = '0'; } if(phonelst.Dname[0]==0x00) { sprintf(pchTempBuffer," %04d %s [%s] [%s] [%s] %s %s %s",iWaveFileNumber,timeis,chPhoneNumber,phonelst.Dalert,pchTotalTime,phonelst.Doccupation,phonelst.Dsubject,phonelst.Darea); } else { sprintf(pchTempBuffer," %04d %s [%s] [%s] [%s] (%s) %s %s",iWaveFileNumber,timeis, chPhoneNumber,phonelst.Dalert,pchTotalTime,phonelst.Dname,phonelst.Doccupation,phonelst.Dsubject); } WriteToCallBox(pchTempBuffer); } void CCELLULARDlg::WriteWhoFile(int iFilenum,char *pchTotalTime) { char chTempFileName[100]; char *pchTempFileName = chTempFileName; sprintf(chTempFileName,"RECORD\\%d.TXT",iFilenum); FILE *whofile; if((whofile=fopen(chTempFileName,"wt"))==0) { MyError("Opening Whofile for write"); } else { fprintf(whofile,"\n"); fprintf(whofile,"TIME : %s %s\n",dateis,timeis); fprintf(whofile,"CALL TIME : %s\n",pchTotalTime); fprintf(whofile,"NUMBER : %s\n",phonelst.Dphone); fprintf(whofile,"AREA : %s\n",phonelst.Darea); fprintf(whofile,"NAME : %s\n",phonelst.Dname); fprintf(whofile,"NAME #2 : %s\n",phonelst.Dname2); fprintf(whofile,"OCCUPATION : %s\n",phonelst.Doccupation); fprintf(whofile,"SUBJECT : %s\n",phonelst.Dsubject); fprintf(whofile,"GENDER : %s\n",phonelst.Dgender); fprintf(whofile,"LANGUAGE : %s\n",phonelst.Dlanguage); fprintf(whofile,"DTMF DIGITS: %s\n",phonelst.DDtmfDigits); fprintf(whofile,"INFO #1 : %s\n",phonelst.Dinfo1); fprintf(whofile,"INFO #2 : %s\n",phonelst.Dinfo2); fprintf(whofile,"INFO #3 : %s\n",phonelst.Dinfo3); fprintf(whofile,"LINKED FILE: %s\n",phonelst.DLinkedFile); fprintf(whofile,"ESN : %s\n",phonelst.Desn); fprintf(whofile,"SCM : %s\n",phonelst.Dscm); fprintf(whofile,"LAST CALL : %s %s\n",phonelst.DLastCallDate,phonelst.DLastCallTime); fprintf(whofile,"TOTAL CALLS: %d\n",phonelst.DTotalCalls); fprintf(whofile,"MODEM : %s\n",phonelst.Dmodem); fprintf(whofile,"FAX : %s\n",phonelst.Dfax); fprintf(whofile,"ALERT LEVEL: %s\n",phonelst.Dalert); fprintf(whofile,"RECORD CALL: %s\n",phonelst.DRecordCall); fprintf(whofile,"SYSTEM TYPE: %s\n",phonelst.Dtype); fprintf(whofile,"\n"); fclose(whofile); } } #define BRIGHT_RED RGB(255, 0, 0) #define BRIGHT_GREEN RGB(0, 255, 0) #define PURPLE RGB(255, 0, 255) #define BRIGHT_BLUE RGB(0, 0, 255) #define BLUE RGB(0, 0, 100) #define BLACK RGB(0,0,0) HBRUSH CCELLULARDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); int nCtrl = pWnd->GetDlgCtrlID(); switch (nCtrl) { case IDC_EDIT_STATUS: pDC->SetTextColor(BRIGHT_BLUE); break; case IDC_EDIT_CALLS: pDC->SetTextColor(BRIGHT_RED); break; case IDC_TEXT_TOTALCALL: case IDC_TEXT_CALLSLEVEL6: case IDC_TEXT_CALLSLEVEL5: case IDC_TEXT_CALLSLEVEL4: case IDC_TEXT_CALLSLEVEL3: case IDC_TEXT_CALLSLEVEL2: case IDC_TEXT_CALLSLEVEL1: case IDC_TEXT_CALLSLEVEL0: pDC->SetTextColor(BLUE); break; case IDC_TEXT_CALLSLEVEL7: case IDC_TEXT_CALLSLEVEL8: case IDC_TEXT_CALLSLEVEL9: case IDC_TEXT_CALLSRECORD: case IDC_TEXT_CALLSMODEM: case IDC_TEXT_CALLSFAX: pDC->SetTextColor(BRIGHT_RED); break; default: break; } return hbr; } void CCELLULARDlg::OnCheckAquire() { if(bAquire==false) { bAquire = true; return; } else { bAquire = false; return; } } void CCELLULARDlg::OnCheckMonitor() { if(bMonitor==false) { bMonitor = true; return; } else { bMonitor = false; return; } } void CCELLULARDlg::GoForwardVoice(void) { Sleep(250); SetDDItoForward(); if(stanum ==0x54) stanum = 0x99; if(stanum ==0x53) stanum = 0x98; if(stanum ==0x52) stanum = 0x97; if(stanum ==0x51) stanum = 0x96; if(stanum ==0x50) stanum = 0x95; if(stanum ==0x49) stanum = 0x94; if(stanum ==0x48) stanum = 0x93; if(stanum ==0x47) stanum = 0x92; if(stanum ==0x46) stanum = 0x91; if(stanum ==0x45) stanum = 0x90; if(stanum ==0x44) stanum = 0x89; if(stanum ==0x43) stanum = 0x88; if(stanum ==0x42) stanum = 0x87; if(stanum ==0x41) stanum = 0x86; if(stanum ==0x40) stanum = 0x85; if(stanum ==0x39) stanum = 0x84; if(stanum ==0x38) stanum = 0x83; if(stanum ==0x37) stanum = 0x82; if(stanum ==0x36) stanum = 0x81; if(stanum ==0x35) stanum = 0x80; if(stanum ==0x34) stanum = 0x79; if(stanum ==0x33) stanum = 0x78; if(stanum ==0x32) stanum = 0x77; if(stanum ==0x31) stanum = 0x76; if(stanum ==0x30) stanum = 0x75; if(stanum ==0x29) stanum = 0x74; if(stanum ==0x28) stanum = 0x73; if(stanum ==0x27) stanum = 0x72; if(stanum ==0x26) stanum = 0x71; if(stanum ==0x25) stanum = 0x70; strcpy(chChannelType,"Forward Voice"); osfreq(endnum,stanum); squelch=OPEN; while(squelch==OPEN) { if(bCancelCall==true) { bCancelCall=false; WriteToStatusBox(" GOT SKIPPED VOICE COMMAND FROM SECONDARY FORWARD VOICE"); break; } } } void CCELLULARDlg::GoReverseVoice(void) { Sleep(250); SetDDItoReverse(); if(stanum ==0x99) stanum = 0x54; if(stanum ==0x98) stanum = 0x53; if(stanum ==0x97) stanum = 0x52; if(stanum ==0x96) stanum = 0x51; if(stanum ==0x95) stanum = 0x50; if(stanum ==0x94) stanum = 0x49; if(stanum ==0x93) stanum = 0x48; if(stanum ==0x92) stanum = 0x47; if(stanum ==0x91) stanum = 0x46; if(stanum ==0x90) stanum = 0x45; if(stanum ==0x89) stanum = 0x44; if(stanum ==0x88) stanum = 0x43; if(stanum ==0x87) stanum = 0x42; if(stanum ==0x86) stanum = 0x41; if(stanum ==0x85) stanum = 0x40; if(stanum ==0x84) stanum = 0x39; if(stanum ==0x83) stanum = 0x38; if(stanum ==0x82) stanum = 0x37; if(stanum ==0x81) stanum = 0x36; if(stanum ==0x80) stanum = 0x35; if(stanum ==0x79) stanum = 0x34; if(stanum ==0x78) stanum = 0x33; if(stanum ==0x77) stanum = 0x32; if(stanum ==0x76) stanum = 0x31; if(stanum ==0x75) stanum = 0x30; if(stanum ==0x74) stanum = 0x29; if(stanum ==0x73) stanum = 0x28; if(stanum ==0x72) stanum = 0x27; if(stanum ==0x71) stanum = 0x26; if(stanum ==0x70) stanum = 0x25; strcpy(chChannelType,"Reverse Voice"); osfreq(endnum,stanum); squelch=OPEN; while(squelch==OPEN) { if(bHoldCall==false) { ossquelch(); check_call_time(); } if(bCancelCall==true) { bCancelCall=false; WriteToStatusBox(" GOT SKIPPED VOICE COMMAND FROM REVERSE VOICE"); break; } } GoForwardVoice(); squelch=OPEN; } void CCELLULARDlg::UpdateChannelStats(void) { char chTempString[25]; char *pchTempString = chTempString; sprintf(pchTempString,"8%x.%x0 Mhz",stanum,endnum); SetDlgItemText(IDC_TEXT_FREQUENCY,pchTempString); SetDlgItemText(IDC_TEXT_CHANNELTYPE,chChannelType); } void CCELLULARDlg::show_scm(void) { ::ZeroMemory(chSCMstring, sizeof(chSCMstring)); if (phonelst.Dscm[1]=='0') {sprintf(chSCMstring,"666 Chan, Continuous, 3.0 Wts");} if (phonelst.Dscm[1]=='1') {sprintf(chSCMstring,"666 Chan, Continuous, 1.2 Wts");} if (phonelst.Dscm[1]=='2') {sprintf(chSCMstring,"666 Chan, Continuous, 0.6 Wts");} if (phonelst.Dscm[1]=='3') {sprintf(chSCMstring,"666 Chan, Continuous, Resv Wts");} if (phonelst.Dscm[1]=='4') {sprintf(chSCMstring,"666 Channels, VOX, 3.0 Watts");} if (phonelst.Dscm[1]=='5') {sprintf(chSCMstring,"666 Channels, VOX, 1.2 Watts");} if (phonelst.Dscm[1]=='6') {sprintf(chSCMstring,"666 Channels, VOX, 0.6 Watts");} if (phonelst.Dscm[1]=='7') {sprintf(chSCMstring,"666 Channels, VOX, Resv Watts");} if (phonelst.Dscm[1]=='8') {sprintf(chSCMstring,"832 Chan, Continuous, 3.0 Wts");} if (phonelst.Dscm[1]=='9') {sprintf(chSCMstring,"832 Chan, Continuous, 1.2 Wts");} if (phonelst.Dscm[1]=='A') {sprintf(chSCMstring,"832 Chan, Continuous, 0.6 Wts");} if (phonelst.Dscm[1]=='B') {sprintf(chSCMstring,"832 Chan, Continuous, Resv Wts");} if (phonelst.Dscm[1]=='C') {sprintf(chSCMstring,"832 Channels, VOX, 3.0 Watts");} if (phonelst.Dscm[1]=='D') {sprintf(chSCMstring,"832 Channels, VOX, 1.2 Watts");} if (phonelst.Dscm[1]=='E') {sprintf(chSCMstring,"832 Channels, VOX, 0.6 Watts");} if (phonelst.Dscm[1]=='F') {sprintf(chSCMstring,"832 Channels, VOX, Resv Watts");} } void CCELLULARDlg::ConvertGoFrequency(void) { if(chGoFrequency[1] == '0') { if(chGoFrequency[2] == '0') {stanum=0x00;} if(chGoFrequency[2] == '1') {stanum=0x01;} if(chGoFrequency[2] == '2') {stanum=0x02;} if(chGoFrequency[2] == '3') {stanum=0x03;} if(chGoFrequency[2] == '4') {stanum=0x04;} if(chGoFrequency[2] == '5') {stanum=0x05;} if(chGoFrequency[2] == '6') {stanum=0x06;} if(chGoFrequency[2] == '7') {stanum=0x07;} if(chGoFrequency[2] == '8') {stanum=0x08;} if(chGoFrequency[2] == '9') {stanum=0x09;} } if(chGoFrequency[1] == '1') { if(chGoFrequency[2] == '0') {stanum=0x10;} if(chGoFrequency[2] == '1') {stanum=0x11;} if(chGoFrequency[2] == '2') {stanum=0x12;} if(chGoFrequency[2] == '3') {stanum=0x13;} if(chGoFrequency[2] == '4') {stanum=0x14;} if(chGoFrequency[2] == '5') {stanum=0x15;} if(chGoFrequency[2] == '6') {stanum=0x16;} if(chGoFrequency[2] == '7') {stanum=0x17;} if(chGoFrequency[2] == '8') {stanum=0x18;} if(chGoFrequency[2] == '9') {stanum=0x19;} } if(chGoFrequency[1] == '2') { if(chGoFrequency[2] == '0') {stanum=0x20;} if(chGoFrequency[2] == '1') {stanum=0x21;} if(chGoFrequency[2] == '2') {stanum=0x22;} if(chGoFrequency[2] == '3') {stanum=0x23;} if(chGoFrequency[2] == '4') {stanum=0x24;} if(chGoFrequency[2] == '5') {stanum=0x25;} if(chGoFrequency[2] == '6') {stanum=0x26;} if(chGoFrequency[2] == '7') {stanum=0x27;} if(chGoFrequency[2] == '8') {stanum=0x28;} if(chGoFrequency[2] == '9') {stanum=0x29;} } if(chGoFrequency[1] == '3') { if(chGoFrequency[2] == '0') {stanum=0x30;} if(chGoFrequency[2] == '1') {stanum=0x31;} if(chGoFrequency[2] == '2') {stanum=0x32;} if(chGoFrequency[2] == '3') {stanum=0x33;} if(chGoFrequency[2] == '4') {stanum=0x34;} if(chGoFrequency[2] == '5') {stanum=0x35;} if(chGoFrequency[2] == '6') {stanum=0x36;} if(chGoFrequency[2] == '7') {stanum=0x37;} if(chGoFrequency[2] == '8') {stanum=0x38;} if(chGoFrequency[2] == '9') {stanum=0x39;} } if(chGoFrequency[1] == '4') { if(chGoFrequency[2] == '0') {stanum=0x40;} if(chGoFrequency[2] == '1') {stanum=0x41;} if(chGoFrequency[2] == '2') {stanum=0x42;} if(chGoFrequency[2] == '3') {stanum=0x43;} if(chGoFrequency[2] == '4') {stanum=0x44;} if(chGoFrequency[2] == '5') {stanum=0x45;} if(chGoFrequency[2] == '6') {stanum=0x46;} if(chGoFrequency[2] == '7') {stanum=0x47;} if(chGoFrequency[2] == '8') {stanum=0x48;} if(chGoFrequency[2] == '9') {stanum=0x49;} } if(chGoFrequency[1] == '5') { if(chGoFrequency[2] == '0') {stanum=0x50;} if(chGoFrequency[2] == '1') {stanum=0x51;} if(chGoFrequency[2] == '2') {stanum=0x52;} if(chGoFrequency[2] == '3') {stanum=0x53;} if(chGoFrequency[2] == '4') {stanum=0x54;} if(chGoFrequency[2] == '5') {stanum=0x55;} if(chGoFrequency[2] == '6') {stanum=0x56;} if(chGoFrequency[2] == '7') {stanum=0x57;} if(chGoFrequency[2] == '8') {stanum=0x58;} if(chGoFrequency[2] == '9') {stanum=0x59;} } if(chGoFrequency[1] == '6') { if(chGoFrequency[2] == '0') {stanum=0x60;} if(chGoFrequency[2] == '1') {stanum=0x61;} if(chGoFrequency[2] == '2') {stanum=0x62;} if(chGoFrequency[2] == '3') {stanum=0x63;} if(chGoFrequency[2] == '4') {stanum=0x64;} if(chGoFrequency[2] == '5') {stanum=0x65;} if(chGoFrequency[2] == '6') {stanum=0x66;} if(chGoFrequency[2] == '7') {stanum=0x67;} if(chGoFrequency[2] == '8') {stanum=0x68;} if(chGoFrequency[2] == '9') {stanum=0x69;} } if(chGoFrequency[1] == '7') { if(chGoFrequency[2] == '0') {stanum=0x70;} if(chGoFrequency[2] == '1') {stanum=0x71;} if(chGoFrequency[2] == '2') {stanum=0x72;} if(chGoFrequency[2] == '3'){stanum=0x73;} if(chGoFrequency[2] == '4') {stanum=0x74;} if(chGoFrequency[2] == '5') {stanum=0x75;} if(chGoFrequency[2] == '6') {stanum=0x76;} if(chGoFrequency[2] == '7'){stanum=0x77;} if(chGoFrequency[2] == '8'){stanum=0x78;} if(chGoFrequency[2] == '9') {stanum=0x79;} } if(chGoFrequency[1] == '8') { if (chGoFrequency[2] == '0'){stanum=0x80;} if (chGoFrequency[2] == '1') {stanum=0x81;} if (chGoFrequency[2] == '2') {stanum=0x82;} if (chGoFrequency[2] == '3'){stanum=0x83;} if (chGoFrequency[2] == '4') {stanum=0x84;} if (chGoFrequency[2] == '5') {stanum=0x85;} if (chGoFrequency[2] == '6') {stanum=0x86;} if (chGoFrequency[2] == '7'){stanum=0x87;} if (chGoFrequency[2] == '8'){stanum=0x88;} if (chGoFrequency[2] == '9') {stanum=0x89;} } if(chGoFrequency[1] == '9') { if (chGoFrequency[2] == '0') {stanum=0x90;} if (chGoFrequency[2] == '1') {stanum=0x91;} if (chGoFrequency[2] == '2') {stanum=0x92;} if (chGoFrequency[2] == '3'){stanum=0x93;} if (chGoFrequency[2] == '4') {stanum=0x94;} if (chGoFrequency[2] == '5') {stanum=0x95;} if (chGoFrequency[2] == '6') {stanum=0x96;} if (chGoFrequency[2] == '7'){stanum=0x97;} if (chGoFrequency[2] == '8'){stanum=0x98;} if (chGoFrequency[2] == '9') {stanum=0x99;} } if(chGoFrequency[4] == '0') { if (chGoFrequency[5] == '0') {endnum=0x00;} if (chGoFrequency[5] == '1') {endnum=0x01;} if (chGoFrequency[5] == '2') {endnum=0x02;} if (chGoFrequency[5] == '3'){endnum=0x03;} if (chGoFrequency[5] == '4') {endnum=0x04;} if (chGoFrequency[5] == '5') {endnum=0x05;} if (chGoFrequency[5] == '6') {endnum=0x06;} if (chGoFrequency[5] == '7'){endnum=0x07;} if (chGoFrequency[5] == '8'){endnum=0x08;} if (chGoFrequency[5] == '9') {endnum=0x09;} } if(chGoFrequency[4] == '1') { if (chGoFrequency[5] == '0') {endnum=0x10;} if (chGoFrequency[5] == '1') {endnum=0x11;} if (chGoFrequency[5] == '2') {endnum=0x12;} if (chGoFrequency[5] == '3'){endnum=0x13;} if (chGoFrequency[5] == '4') {endnum=0x14;} if (chGoFrequency[5] == '5') {endnum=0x15;} if (chGoFrequency[5] == '6') {endnum=0x16;} if (chGoFrequency[5] == '7'){endnum=0x17;} if (chGoFrequency[5] == '8'){endnum=0x18;} if (chGoFrequency[5] == '9') {endnum=0x19;} } if(chGoFrequency[4] == '2') { if (chGoFrequency[5] == '0') {endnum=0x20;} if (chGoFrequency[5] == '1') {endnum=0x21;} if (chGoFrequency[5] == '2') {endnum=0x22;} if (chGoFrequency[5] == '3'){endnum=0x23;} if (chGoFrequency[5] == '4') {endnum=0x24;} if (chGoFrequency[5] == '5') {endnum=0x25;} if (chGoFrequency[5] == '6') {endnum=0x26;} if (chGoFrequency[5] == '7'){endnum=0x27;} if (chGoFrequency[5] == '8'){endnum=0x28;} if (chGoFrequency[5] == '9') {endnum=0x29;} } if(chGoFrequency[4] == '3') { if (chGoFrequency[5] == '0') {endnum=0x30;} if (chGoFrequency[5] == '1') {endnum=0x31;} if (chGoFrequency[5] == '2') {endnum=0x32;} if (chGoFrequency[5] == '3'){endnum=0x33;} if (chGoFrequency[5] == '4') {endnum=0x34;} if (chGoFrequency[5] == '5') {endnum=0x35;} if (chGoFrequency[5] == '6') {endnum=0x36;} if (chGoFrequency[5] == '7'){endnum=0x37;} if (chGoFrequency[5] == '8'){endnum=0x38;} if (chGoFrequency[5] == '9') {endnum=0x39;} } if(chGoFrequency[4] == '4') { if (chGoFrequency[5] == '0') {endnum=0x40;} if (chGoFrequency[5] == '1') {endnum=0x41;} if (chGoFrequency[5] == '2') {endnum=0x42;} if (chGoFrequency[5] == '3'){endnum=0x43;} if (chGoFrequency[5] == '4') {endnum=0x44;} if (chGoFrequency[5] == '5') {endnum=0x45;} if (chGoFrequency[5] == '6') {endnum=0x46;} if (chGoFrequency[5] == '7'){endnum=0x47;} if (chGoFrequency[5] == '8'){endnum=0x48;} if (chGoFrequency[5] == '9') {endnum=0x49;} } if(chGoFrequency[4] == '5') { if (chGoFrequency[5] == '0') {endnum=0x50;} if (chGoFrequency[5] == '1') {endnum=0x51;} if (chGoFrequency[5] == '2') {endnum=0x52;} if (chGoFrequency[5] == '3'){endnum=0x53;} if (chGoFrequency[5] == '4') {endnum=0x54;} if (chGoFrequency[5] == '5') {endnum=0x55;} if (chGoFrequency[5] == '6') {endnum=0x56;} if (chGoFrequency[5] == '7'){endnum=0x57;} if (chGoFrequency[5] == '8'){endnum=0x58;} if (chGoFrequency[5] == '9') {endnum=0x59;} } if(chGoFrequency[4] == '6') { if (chGoFrequency[5] == '0') {endnum=0x60;} if (chGoFrequency[5] == '1') {endnum=0x61;} if (chGoFrequency[5] == '2') {endnum=0x62;} if (chGoFrequency[5] == '3'){endnum=0x63;} if (chGoFrequency[5] == '4') {endnum=0x64;} if (chGoFrequency[5] == '5') {endnum=0x65;} if (chGoFrequency[5] == '6') {endnum=0x66;} if (chGoFrequency[5] == '7'){endnum=0x67;} if (chGoFrequency[5] == '8'){endnum=0x68;} if (chGoFrequency[5] == '9') {endnum=0x69;} } if(chGoFrequency[4] == '7') { if (chGoFrequency[5] == '0') {endnum=0x70;} if (chGoFrequency[5] == '1') {endnum=0x71;} if (chGoFrequency[5] == '2') {endnum=0x72;} if (chGoFrequency[5] == '3'){endnum=0x73;} if (chGoFrequency[5] == '4') {endnum=0x74;} if (chGoFrequency[5] == '5') {endnum=0x75;} if (chGoFrequency[5] == '6') {endnum=0x76;} if (chGoFrequency[5] == '7'){endnum=0x77;} if (chGoFrequency[5] == '8'){endnum=0x78;} if (chGoFrequency[5] == '9') {endnum=0x79;} } if(chGoFrequency[4] == '8') { if (chGoFrequency[5] == '0') {endnum=0x80;} if (chGoFrequency[5] == '1') {endnum=0x81;} if (chGoFrequency[5] == '2') {endnum=0x82;} if (chGoFrequency[5] == '3'){endnum=0x83;} if (chGoFrequency[5] == '4') {endnum=0x84;} if (chGoFrequency[5] == '5') {endnum=0x85;} if (chGoFrequency[5] == '6') {endnum=0x86;} if (chGoFrequency[5] == '7'){endnum=0x87;} if (chGoFrequency[5] == '8'){endnum=0x88;} if (chGoFrequency[5] == '9') {endnum=0x89;} } if(chGoFrequency[4] == '9') { if (chGoFrequency[5] == '0') {endnum=0x90;} if (chGoFrequency[5] == '1') {endnum=0x91;} if (chGoFrequency[5] == '2') {endnum=0x92;} if (chGoFrequency[5] == '3'){endnum=0x93;} if (chGoFrequency[5] == '4') {endnum=0x94;} if (chGoFrequency[5] == '5') {endnum=0x95;} if (chGoFrequency[5] == '6') {endnum=0x96;} if (chGoFrequency[5] == '7'){endnum=0x97;} if (chGoFrequency[5] == '8'){endnum=0x98;} if (chGoFrequency[5] == '9') {endnum=0x99;} } } void CCELLULARDlg::ReadIniFile(void) { char chDirectoryName[MAX_PATH+100]; char *pchDirectoryName = chDirectoryName; ::GetCurrentDirectory(MAX_PATH,pchDirectoryName); strcat(pchDirectoryName,"\\CELLULAR.INI"); TRACE("INI Filename = %s\n",pchDirectoryName); char chTextString[255]; char *pchTextString = chTextString; DDICOM: GetPrivateProfileString("SETTINGS","DDI COMM PORT","Not Found",pchTextString,17,pchDirectoryName); if(strcmp("Not Found",pchTextString)==0) { WritePrivateProfileString("SETTINGS","DDI COMM PORT","2",pchDirectoryName); goto DDICOM; } else { iCommPortDDI = atoi(pchTextString); iCommPortDDI = iCommPortDDI - 1; TRACE("iCommPortDDI = %d\n",iCommPortDDI); } OS456COM: GetPrivateProfileString("SETTINGS","OS456 COMM PORT","Not Found",pchTextString,17,pchDirectoryName); if(strcmp("Not Found",pchTextString)==0) { WritePrivateProfileString("SETTINGS","OS456 COMM PORT","1",pchDirectoryName); goto OS456COM; } else { iCommPortOS456 = atoi(pchTextString); iCommPortOS456 = iCommPortOS456 - 1; TRACE("iCommPortOS456 = %d\n",iCommPortOS456); } FREQUENCY: GetPrivateProfileString("SETTINGS","FREQUENCY","Not Found",pchTextString,17,pchDirectoryName); if(strcmp("Not Found",pchTextString)==0) { WritePrivateProfileString("SETTINGS","FREQUENCY","879.540",pchDirectoryName); goto FREQUENCY; } else { strcpy(chFrequency,pchTextString); TRACE1("chFrequency = %s\n",chFrequency); strcpy(chGoFrequency,chFrequency); ConvertGoFrequency(); } /* REVERSE: bReverseChannel = false; GetPrivateProfileString("SETTINGS","REVERSE CHANNEL","Not Found",pchTextString,17,pchDirectoryName); if(strcmp("Not Found",pchTextString)==0) { WritePrivateProfileString("SETTINGS","REVERSE CHANNEL","NO",pchDirectoryName); goto REVERSE; } else { if(strcmpi(pchTextString,"YES")==0) { bReverseChannel = true; } if(strcmpi(pchTextString,"Y")==0) { bReverseChannel = true; } if(strcmpi(pchTextString,"ENABLED")==0) { bReverseChannel = true; } if(strcmpi(pchTextString,"ENABLE")==0) { bReverseChannel = true; } if(strcmpi(pchTextString,"ON")==0) { bReverseChannel = true; } } */ MAXCALLTIME: GetPrivateProfileString("SETTINGS","MAX CALL TIME","Not Found",pchTextString,17,pchDirectoryName); if(strcmp("Not Found",pchTextString)==0) { WritePrivateProfileString("SETTINGS","MAX CALL TIME","1200",pchDirectoryName); goto MAXCALLTIME; } else { iMaxCallTime = atoi(pchTextString); TRACE("iMaxCallTime = %d\n",iMaxCallTime); } } void CCELLULARDlg::OnButtonControlType() { m_EditCallList.SetWindowText(" "); m_EditCallList.Clear(); if(bReverseChannel == false) { m_ButtonSwitchControlType.SetWindowText("Switch To Reverse Control"); strcpy(chFrequency,chReverseChannel); TRACE("chReverseChannel = %s\n",chReverseChannel); } else { m_ButtonSwitchControlType.SetWindowText("Switch To Forward Control"); strcpy(chFrequency,chForwardChannel); TRACE("chForwardChannel = %s\n",chForwardChannel); } which_channel(); if(bReverseChannel == true) { SetDDItoReverse(); } else { SetDDItoForward(); } osfreq(endnum,stanum); } void CCELLULARDlg::OnButtonSwitchvoice() { if(bVoiceForward == true) { m_ButtonSwitchVoice.SetWindowText("Forward Voice"); bVoiceForward = false; bGoReverseVoice = true; } else { m_ButtonSwitchVoice.SetWindowText("Reverse Voice"); bVoiceForward = true; bGoForwardVoice = true; } } void CCELLULARDlg::OnButtonControlscan() { InitalizeOS456(); InitalizeDDI(); char chOriginalFrequency[50]; strcpy(chOriginalFrequency,chFrequency); SetDDItoForward(); WriteToCallBox("FORWARD CONTROL CHANNEL SCAN (BAND 'A')"); WriteToCallBox("[ACTIVE] [CHANNEL] [FREQUENCY] [SIGNAL STRENGTH]"); ScanControlChannel("879.990"); ScanControlChannel("879.960"); ScanControlChannel("879.930"); ScanControlChannel("879.900"); ScanControlChannel("879.870"); ScanControlChannel("879.840"); ScanControlChannel("879.810"); ScanControlChannel("879.780"); ScanControlChannel("879.750"); ScanControlChannel("879.720"); ScanControlChannel("879.690"); ScanControlChannel("879.660"); ScanControlChannel("879.630"); ScanControlChannel("879.600"); ScanControlChannel("879.570"); ScanControlChannel("879.540"); ScanControlChannel("879.510"); ScanControlChannel("879.480"); ScanControlChannel("879.450"); ScanControlChannel("879.420"); ScanControlChannel("879.390"); WriteToCallBox(" "); WriteToCallBox("FORWARD CONTROL CHANNEL SCAN (BAND 'B')"); WriteToCallBox("[ACTIVE] [CHANNEL] [FREQUENCY] [SIGNAL STRENGTH]"); ScanControlChannel("835.020"); ScanControlChannel("835.050"); ScanControlChannel("835.080"); ScanControlChannel("835.110"); ScanControlChannel("835.140"); ScanControlChannel("835.170"); ScanControlChannel("835.200"); ScanControlChannel("835.230"); ScanControlChannel("835.260"); ScanControlChannel("835.290"); ScanControlChannel("835.320"); ScanControlChannel("835.350"); ScanControlChannel("835.380"); ScanControlChannel("835.410"); ScanControlChannel("835.440"); ScanControlChannel("835.470"); ScanControlChannel("835.500"); ScanControlChannel("835.530"); ScanControlChannel("835.560"); ScanControlChannel("835.590"); ScanControlChannel("835.620"); WriteToCallBox(" "); WriteToCallBox(" Channels mark with an X are active control channels."); WriteToCallBox(" The lower the signal strength number is the better the signal"); WriteToCallBox(" 0 is a perfect signal. - 125 is the worst signal."); osspeakeroff(); strcpy(chFrequency,chOriginalFrequency); which_channel(); osfreq(endnum,stanum); } void CCELLULARDlg::ScanControlChannel(char *chFreq) { char chActive[5]; char chTempString[250]; char *pchTempString = chTempString; strcpy(chFrequency,chFreq); which_channel(); osfreq(endnum,stanum); osspeakeron(); Sleep(250); ossignalstr(); if(strcmp(chSignalStrength,"- 125 dBm")==0) { strcpy(chActive," "); } else { strcpy(chActive,"X"); } sprintf(pchTempString," [%s] [%s] [%s] [%s]",chActive,chChannel,chFrequency,chSignalStrength); WriteToCallBox(pchTempString); }
26.806627
190
0.587279
68c3732c72577fd424f41c28144aca72ff4e6b24
1,950
cpp
C++
src/Elements/emitter.cpp
attilabibok/epanet-dev
91d87377b8462cf0a12cb55ea0554951fb586993
[ "MIT" ]
1
2017-12-21T19:40:35.000Z
2017-12-21T19:40:35.000Z
src/Elements/emitter.cpp
attilabibok/epanet-dev
91d87377b8462cf0a12cb55ea0554951fb586993
[ "MIT" ]
null
null
null
src/Elements/emitter.cpp
attilabibok/epanet-dev
91d87377b8462cf0a12cb55ea0554951fb586993
[ "MIT" ]
null
null
null
/* EPANET 3 * * Copyright (c) 2016 Open Water Analytics * Distributed under the MIT License (see the LICENSE file for details). * */ #include "emitter.h" #include "junction.h" #include "pattern.h" #include "Core/network.h" #include <cmath> using namespace std; //----------------------------------------------------------------------------- // Emitter Constructor Emitter::Emitter() : flowCoeff(0), expon(0.0), timePattern(0) {} //----------------------------------------------------------------------------- // Emitter Destructor Emitter::~Emitter() {} //----------------------------------------------------------------------------- // Adds or edits a junction's emitter. bool Emitter::addEmitter(Junction* junc, double c, double e, Pattern* p) { if ( junc->emitter == nullptr ) { junc->emitter = new Emitter(); if ( junc->emitter == nullptr ) return false; } junc->emitter->flowCoeff = c; junc->emitter->expon = e; junc->emitter->timePattern = p; return true; } //----------------------------------------------------------------------------- // Converts an emitter's properties from user units to internal units. void Emitter::convertUnits(Network* network) { // ... get units conversion factors double qUcf = network->ucf(Units::FLOW); double pUcf = network->ucf(Units::PRESSURE); // ... convert flowCoeff from user flow units per psi (or meter) // to cfs per foot of head flowCoeff *= pow(pUcf, expon) / qUcf; } //----------------------------------------------------------------------------- // Finds the outflow and its derivative from an emitter at a given pressure head. double Emitter::findFlowRate(double h, double& dqdh) { dqdh = 0.0; if ( h <= 0.0 ) return 0.0; double a = flowCoeff; if (timePattern) a *= timePattern->currentFactor(); double q = a * pow(h, expon); dqdh = expon * q / h; return q; }
24.375
82
0.507692
68c4415146bf139aac80e5779108f3bd23f4fefa
10,585
cpp
C++
src/arboretum/stPartitionNode.cpp
marcosivni/arboretum
329147b2d147903bc8e527fc3dcfe2349141725a
[ "Apache-2.0" ]
null
null
null
src/arboretum/stPartitionNode.cpp
marcosivni/arboretum
329147b2d147903bc8e527fc3dcfe2349141725a
[ "Apache-2.0" ]
null
null
null
src/arboretum/stPartitionNode.cpp
marcosivni/arboretum
329147b2d147903bc8e527fc3dcfe2349141725a
[ "Apache-2.0" ]
null
null
null
/* Copyright 2003-2017 GBDI-ICMC-USP <caetano@icmc.usp.br> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * * This file implements the blocks of Partition. * * @version 1.0 * @author Enzo Seraphim(seraphim@icmc.usp.br) */ #include <arboretum/stPartitionNode.h> //------------------------------------------------------------------------------ // class stPartitionRegionDesc //------------------------------------------------------------------------------ int stPartitionRegionDesc::GetFirstDigit(){ return (int)(Desc.Region / pow (Desc.NumberRep, (long double)(Desc.NumberRep - 1))); }//end stPartitionRegionDesc::GetFirstDigit //------------------------------------------------------------------------------ void stPartitionRegionDesc::ConvertToBins(unsigned char base, unsigned char *result){ u_int32_t long res = Desc.Region; int i = 0; u_int32_t long powbase; for (int i =0; i < base; i++){ powbase = (u_int32_t long) pow (Desc.NumberRep, (long double)(base - i - 1)); result[i] = (unsigned char)(res / powbase); res = res - (powbase * result[i]); }//end while } //end stPartitionRegionDesc::ConvertToBins //----------------------------------------------------------------------------- // Class stPartitionListRegionDesc //----------------------------------------------------------------------------- stPartitionListRegionDesc::~stPartitionListRegionDesc(){ IdActual = 0; for (;IdActual < NumberItem;IdActual++){ Actual = Root; Root = Actual->Next; delete Actual; IdActual++; }//end for }//end stPartitionListRegionDesc::~stPartitionRegionDesc //------------------------------------------------------------------------------ stPartitionRegionDesc stPartitionListRegionDesc::GetRegionDesc(int id){ #ifdef __stDEBUG__ if ((id < 0) && (id >= NumberItem)){ throw invalid_argument("id value is out of range."); }//end if #endif //__stDEBUG__ //if index is the first if(id == 0){ return Root->RegionDesc; } //if index is the last if(id == NumberItem){ return Last->RegionDesc; } //otherwise if (IdActual > id){ Actual = Root; for (IdActual=0;IdActual<id;IdActual++){ Actual = Actual->Next; }//end for }else{ for (;IdActual<id;IdActual++){ Actual = Actual->Next; }//end for }//end if return Actual->RegionDesc; }//end stPartitionListRegionDesc::GetRegionDesc //------------------------------------------------------------------------------ int stPartitionListRegionDesc::Add(stPartitionRegionDesc regDesc){ //locating previous item to insered position stItemRegionDesc * ant; stItemRegionDesc * aux = Root; IdActual = 0; while((IdActual < NumberItem) && (aux->RegionDesc.GetRegion() < regDesc.GetRegion())){ ant = aux; aux = aux->Next; IdActual++; }//end while //inserting item Actual = new stItemRegionDesc; Actual->RegionDesc = regDesc; Actual->Next = aux; //if change the last item if (IdActual == NumberItem){ Last = Actual; }//end if //if change the root if (IdActual == 0){ Root = Actual; }else{ ant->Next = Actual; }//end if //update number of representatives NumberItem++; return IdActual; }//end stPartitionListRegionDesc::Add //------------------------------------------------------------------------------ // class stPartitionNode //------------------------------------------------------------------------------ stPartitionNode * stPartitionNode::CreateBucket(stPage * page){ stPartitionNode::stPartitionNodeHeader * header; header = (stPartitionNodeHeader *)(page->GetData()); switch (header->Type){ case INDEX: // Create an index page return new stPartitionIndexBucket(page, false); case LEAF: // Create a leaf page return new stPartitionLeafBucket(page, false); default: return NULL; }//end switch }//end stPartitionNode::CreateBucket() //------------------------------------------------------------------------------ // class stPartitionIndexBucket //------------------------------------------------------------------------------ stPartitionIndexBucket::stPartitionIndexBucket(stPage * page, bool create): stPartitionNode(page){ // Attention to this manouver! It is the brain of this // implementation. Entries = (stPartitionIndexEntry*)(page->GetData() + sizeof(stPartitionNodeHeader)); // Initialize page if (create){ #ifdef __stDEBUG__ Page->Clear(); #endif //__stDEBUG__ Header->Type = INDEX; Header->Occupation = 0; Header->NextBucket = 0; }//end if }//end stPartitionIndexBucket::stPartitionIndexBucket() //------------------------------------------------------------------------------ u_int32_t stPartitionIndexBucket::GetFree(){ u_int32_t usedsize; // Fixed size usedsize = sizeof(stPartitionNodeHeader); // Entries if (GetNumberOfEntries() > 0){ usedsize += // Total size of entries (sizeof(stPartitionIndexEntry) * GetNumberOfEntries()); }//end if return Page->GetPageSize() - usedsize; }//end stPartitionIndexBucket::GetFree() //------------------------------------------------------------------------------ // class stPartitionLeafBucket //------------------------------------------------------------------------------ stPartitionLeafBucket::stPartitionLeafBucket(stPage * page, bool create): stPartitionNode(page){ Entries = (stPartitionLeafEntry*)(page->GetData() + sizeof(stPartitionNodeHeader)); // Initialize page if (create){ #ifdef __stDEBUG__ Page->Clear(); #endif //__stDEBUG__ Header->Type = LEAF; Header->Occupation = 0; Header->NextBucket = 0; }//end if }//end stPartitionLeafBucket::stPartitionLeafBucket() //------------------------------------------------------------------------------ u_int32_t stPartitionLeafBucket::GetObjectSize(int id){ #ifdef __stDEBUG__ if ((id < 0) && (id >= GetNumberOfEntries())){ throw invalid_argument("id value is out of range."); }//end if #endif //__stDEBUG__ if (id == 0){ // First object return Page->GetPageSize() - Entries[0].Offset; }else{ // Any other return Entries[id - 1].Offset - Entries[id].Offset; }//end if }//end stPartitionLeafBucket::GetObjectSize() //------------------------------------------------------------------------------ u_int32_t stPartitionLeafBucket::GetFree(){ u_int32_t usedsize; // Fixed size usedsize = sizeof(stPartitionNodeHeader); // Entries if (GetNumberOfEntries() > 0){ usedsize += // Total size of entries (sizeof(stPartitionLeafEntry) * GetNumberOfEntries()) + // Total object size (Page->GetPageSize() - Entries[GetNumberOfEntries() - 1].Offset); }//end if return Page->GetPageSize() - usedsize; }//end stPartitionLeafBucket::GetFree() //----------------------------------------------------------------------------- // Class stPartitionRepresentativesNode //----------------------------------------------------------------------------- stPartitionRepresentativesNode::stPartitionRepresentativesNode( stPage * page, bool create):stPartitionNode(page){ // Attention to this manouver! It is the brain of this // implementation. Entries = (u_int32_t *)((this->Page->GetData())+ sizeof(stPartitionNodeHeader)); // Initialize page if (create){ #ifdef __stDEBUG__ Page->Clear(); #endif //__stDEBUG__ Header->Type = REPRESENT; Header->Occupation = 0; Header->NextBucket = 0; }//end if }//end stPartitionRepresentativesNode::stPartitionRepresentativesNode() //----------------------------------------------------------------------------- int stPartitionRepresentativesNode::AddEntry(u_int32_t size, const unsigned char * object){ u_int32_t entrysize; #ifdef __stDEBUG__ if (size == 0){ throw invalid_argument("The object size is 0."); }//end if #endif //__stDEBUG__ // Does it fit ? entrysize = size + sizeof(u_int32_t); if (entrysize > this->GetFree()){ // No, it doesn't. return -1; }//end if // Ok. I can put it. Lets put it in the last position. // Adding the object. Take care with these pointers or you will destroy the // node. The idea is to put the object of an entry in the reverse order // in the data array. if (Header->Occupation == 0){ Entries[Header->Occupation] = Page->GetPageSize() - size; }else{ Entries[Header->Occupation] = Entries[Header->Occupation - 1] - size; }//end if memcpy((void*)(Page->GetData() + Entries[Header->Occupation]), (void*)object, size); // Update # of entries Header->Occupation++; // One more! return Header->Occupation - 1; }//end stPartitionRepresentativesNode::AddEntry() //------------------------------------------------------------------------------ u_int32_t stPartitionRepresentativesNode::GetObjectSize(int id){ #ifdef __stDEBUG__ if ((id < 0) && (id >= GetNumberOfEntries())){ throw invalid_argument("id value is out of range."); }//end if #endif //__stDEBUG__ if (id == 0){ // First object return Page->GetPageSize() - Entries[0]; }else{ // Any otherstPartitionLeafBucket return Entries[id - 1] - Entries[id]; }//end if }//end stPartitionRepresentativesNode::GetObjectSize() //------------------------------------------------------------------------------ u_int32_t stPartitionRepresentativesNode::GetFree(){ u_int32_t usedsize; // Fixed size usedsize = sizeof(stPartitionNodeHeader); // Entries if (GetNumberOfEntries() > 0){ usedsize += // Total size of entries (sizeof(u_int32_t) * GetNumberOfEntries()) + // Total object size (Page->GetPageSize() - Entries[GetNumberOfEntries() - 1]); }//end if return Page->GetPageSize() - usedsize; }//end stPartitionRepresentativesNode::GetFree()
32.469325
91
0.559565
68c503a54d6a500daeb69a026d88a4463a5e20eb
6,845
cpp
C++
src/PinholePCLCam.cpp
HWiese1980/merge_depth_cam
974008b6b1f84d516a0f74dfd3832bfa55ef163d
[ "BSD-3-Clause" ]
16
2019-01-23T10:35:27.000Z
2022-03-10T16:21:34.000Z
src/PinholePCLCam.cpp
mmiles19/merge_depth_cam
7bd00a7d2baabdb9c4a8afc6a4eb516898f995b0
[ "BSD-3-Clause" ]
3
2019-02-26T16:48:08.000Z
2022-01-24T18:16:15.000Z
src/PinholePCLCam.cpp
mmiles19/merge_depth_cam
7bd00a7d2baabdb9c4a8afc6a4eb516898f995b0
[ "BSD-3-Clause" ]
4
2019-10-27T10:45:41.000Z
2021-01-23T08:44:37.000Z
// #include <pluginlib/class_list_macros.h> #include "PinholePCLCam.hpp" #include <opencv2/opencv.hpp> #include <pcl/range_image/range_image_planar.h> #include <cassert> #include <cmath> using namespace sensor_msgs; using namespace std_msgs; namespace ap34 { void store_image(std::string fname, cv::Mat& img) { ROS_INFO_STREAM("Storing image"); std::stringstream ss_yml, ss_png; ss_yml << fname << ".yml"; ss_png << fname << ".png"; cv::FileStorage file(ss_yml.str().c_str(), cv::FileStorage::WRITE); file << "depth_image" << img; std::vector<int> compression_params; compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); cv::Mat write_image; cv::normalize(img, write_image, 0, 255, cv::NORM_MINMAX, CV_8UC1); cv::imwrite(ss_png.str().c_str(), write_image, compression_params); } void PinholePCLCam::PCL2Mat(const PointCloud::ConstPtr& ptr_cld, cv::Mat& depth_image, int original_width, int original_height) { int blob_offset_u = (blob_size - (blob_size%2)) / 2; int blob_offset_v = (blob_size - (blob_size%2)) / 2; std::vector<cv::Point2f> projectedPoints; std::vector<cv::Point3f> cv_points; for(const auto& point : ptr_cld->points) { cv_points.push_back(cv::Point3f(point.x, point.y, point.z)); } cv::projectPoints(cv_points, rvecR, T, K, distCoeffs, projectedPoints); cv::Rect valid_range(blob_offset_u, blob_offset_v, original_width - (2*blob_offset_u), original_height - (2*blob_offset_v)); int mid_x = original_width/2; int mid_y = original_height/2; #pragma omp parallel for for(int i = 0; i < ptr_cld->points.size(); i += stride) { auto point2d = projectedPoints[i]; int u = (int)(point2d.x + mid_x); int v = (int)(point2d.y + mid_y); cv::Point p(u, v); if(!valid_range.contains(p)) continue; float z = ptr_cld->points[i].z; float new_val = (float)(z * 1000.0); float current_val = depth_image.at<float>(v, u); if(current_val < std::numeric_limits<float>::epsilon() || new_val < current_val) // only set depth value if current pixel is unset or the new value is closer to the cam (z-buffer) // depth_image(cv::Rect(u-blob_offset_u,v-blob_offset_v,2*blob_offset_u,2*blob_offset_v)).setTo(new_val); cv::circle(depth_image, p, blob_size/2, new_val, -1); } } void PinholePCLCam::dynconf_cb(merged_depth_cam::PinholePCLCamConfig &config, uint32_t level) { ROS_INFO("[PinholePCLCam] Reconfiguring"); ROS_INFO(" Stride : %d", config.stride); ROS_INFO(" Blob Size : %d", config.blob_size); ROS_INFO(" Focal Length : %3.3f", config.focal_length); ROS_INFO(" Rescale Factor : %3.3f", config.rescale_factor); stride = config.stride; blob_size = config.blob_size; focal_length = config.focal_length; rescale_factor = config.rescale_factor; float _upscale_factor_internal = (float)target_width / diw; ROS_INFO("[Pinhole Cam] Internal upscale factor : %3.3f", _upscale_factor_internal); _downscale_factor = rescale_factor; _upscale_factor = _upscale_factor_internal / _downscale_factor; P.at<float>(0,0) = focal_length / 2; P.at<float>(1,1) = focal_length / 2; P.at<float>(2,2) = 1; cv::decomposeProjectionMatrix(P, K, rvec, Thomogeneous); cv::Rodrigues(rvec, rvecR); } PinholePCLCam::PinholePCLCam(ros::NodeHandle& nh) { this->nh = nh; image_transport::ImageTransport it(this->nh); pcl_sub = nh.subscribe("input_pcl", 1, &PinholePCLCam::IncomingPCL, this); depth_pub = it.advertise("output_merged_depth", 1); P = cv::Mat(3, 4, cv::DataType<float>::type, cv::Scalar(0.)); K = cv::Mat(3, 3, cv::DataType<float>::type, cv::Scalar(0.)); rvec = cv::Mat(3, 3, cv::DataType<float>::type, cv::Scalar(0.)); Thomogeneous = cv::Mat(4, 1, cv::DataType<float>::type, cv::Scalar(0.)); T = cv::Mat(3, 1, cv::DataType<float>::type, cv::Scalar(0.)); distCoeffs = cv::Mat(4, 1, cv::DataType<float>::type, cv::Scalar(0.)); rvecR = cv::Mat(3, 1, cv::DataType<float>::type, cv::Scalar(0.)); usleep(500000); nh.param<std::string>("virtual_cam_frame", virtual_cam_frame, "virtual_cam_link"); nh.param<int>("depth_image_width", diw, 640); nh.param<int>("depth_image_height", dih, 960); nh.param<int>("stride", stride, 1); nh.param<int>("target_width", target_width, 320); nh.param<int>("blob_size", blob_size, 1); nh.param<float>("focal_length", focal_length, 1000.0); nh.param<float>("rescale_factor", rescale_factor, 1.0); float _upscale_factor_internal = (float)target_width / diw; ROS_INFO("[Pinhole Cam] Internal upscale factor : %3.3f", _upscale_factor_internal); _downscale_factor = rescale_factor; _upscale_factor = _upscale_factor_internal / _downscale_factor; ROS_INFO("[Pinhole Cam] Downscale Factor : %3.3f", _downscale_factor); ROS_INFO("[Pinhole Cam] Upscale Factor : %3.3f", _upscale_factor); ROS_INFO("[Pinhole Cam] Blob Size : %d", blob_size); cb_type = boost::bind(&PinholePCLCam::dynconf_cb, this, _1, _2); server.setCallback(cb_type); } void PinholePCLCam::IncomingPCL(const PointCloud::ConstPtr& pcl) { if(diw <= 0 || dih <= 0) return; cv::Mat depth_image(dih, diw, CV_32FC1, cv::Scalar(0.0)); PCL2Mat(pcl, depth_image, diw, dih); cv::Mat resized_image; if(fabs(1.0F - _upscale_factor) >= std::numeric_limits<float>::epsilon()) { cv::resize(depth_image, resized_image, cv::Size(), _downscale_factor, _downscale_factor, CV_INTER_AREA); cv::resize(resized_image, resized_image, cv::Size(), _upscale_factor, _upscale_factor, CV_INTER_AREA); } else{ ROS_INFO_ONCE("No rescaling necessary"); resized_image = depth_image; } sensor_msgs::Image msg; std_msgs::Header header; pcl_conversions::fromPCL(pcl->header, header); // header.frame_id = virtual_cam_frame; // header.seq = seq++; // header.stamp = ros::Time(pcl->header.stamp); auto img_bridge = cv_bridge::CvImage(header, sensor_msgs::image_encodings::TYPE_32FC1, resized_image); img_bridge.toImageMsg(msg); depth_pub.publish(msg); depth_image.release(); resized_image.release(); } }
41.737805
132
0.622498
68c5c2ec21cf1af2560c0717b4118df93f520b17
4,866
cc
C++
gpu/command_buffer/service/transfer_buffer_manager_unittest.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
gpu/command_buffer/service/transfer_buffer_manager_unittest.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
gpu/command_buffer/service/transfer_buffer_manager_unittest.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/command_buffer/service/transfer_buffer_manager.h" #include "base/memory/scoped_ptr.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/gmock/include/gmock/gmock.h" using base::SharedMemory; namespace gpu { const static size_t kBufferSize = 1024; class TransferBufferManagerTest : public testing::Test { protected: virtual void SetUp() { for (size_t i = 0; i < arraysize(buffers_); ++i) { buffers_[i].CreateAnonymous(kBufferSize); buffers_[i].Map(kBufferSize); } TransferBufferManager* manager = new TransferBufferManager(); transfer_buffer_manager_.reset(manager); ASSERT_TRUE(manager->Initialize()); } base::SharedMemory buffers_[3]; scoped_ptr<TransferBufferManagerInterface> transfer_buffer_manager_; }; TEST_F(TransferBufferManagerTest, ZeroHandleMapsToNull) { EXPECT_TRUE(NULL == transfer_buffer_manager_->GetTransferBuffer(0).ptr); } TEST_F(TransferBufferManagerTest, NegativeHandleMapsToNull) { EXPECT_TRUE(NULL == transfer_buffer_manager_->GetTransferBuffer(-1).ptr); } TEST_F(TransferBufferManagerTest, OutOfRangeHandleMapsToNull) { EXPECT_TRUE(NULL == transfer_buffer_manager_->GetTransferBuffer(1).ptr); } TEST_F(TransferBufferManagerTest, CanRegisterTransferBuffer) { EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1, &buffers_[0], kBufferSize)); Buffer registered = transfer_buffer_manager_->GetTransferBuffer(1); // Distinct memory range and shared memory handle from that originally // registered. EXPECT_NE(static_cast<void*>(NULL), registered.ptr); EXPECT_NE(buffers_[0].memory(), registered.ptr); EXPECT_EQ(kBufferSize, registered.size); EXPECT_NE(&buffers_[0], registered.shared_memory); // But maps to the same physical memory. *static_cast<int*>(registered.ptr) = 7; *static_cast<int*>(buffers_[0].memory()) = 8; EXPECT_EQ(8, *static_cast<int*>(registered.ptr)); } TEST_F(TransferBufferManagerTest, CanDestroyTransferBuffer) { EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1, &buffers_[0], kBufferSize)); transfer_buffer_manager_->DestroyTransferBuffer(1); Buffer registered = transfer_buffer_manager_->GetTransferBuffer(1); EXPECT_EQ(static_cast<void*>(NULL), registered.ptr); EXPECT_EQ(0U, registered.size); EXPECT_EQ(static_cast<base::SharedMemory*>(NULL), registered.shared_memory); } TEST_F(TransferBufferManagerTest, CannotRegregisterTransferBufferId) { EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1, &buffers_[0], kBufferSize)); EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(1, &buffers_[0], kBufferSize)); EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(1, &buffers_[1], kBufferSize)); } TEST_F(TransferBufferManagerTest, CanReuseTransferBufferIdAfterDestroying) { EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1, &buffers_[0], kBufferSize)); transfer_buffer_manager_->DestroyTransferBuffer(1); EXPECT_TRUE(transfer_buffer_manager_->RegisterTransferBuffer(1, &buffers_[1], kBufferSize)); } TEST_F(TransferBufferManagerTest, DestroyUnusedTransferBufferIdDoesNotCrash) { transfer_buffer_manager_->DestroyTransferBuffer(1); } TEST_F(TransferBufferManagerTest, CannotRegisterNullTransferBuffer) { EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(0, &buffers_[0], kBufferSize)); } TEST_F(TransferBufferManagerTest, CannotRegisterNegativeTransferBufferId) { EXPECT_FALSE(transfer_buffer_manager_->RegisterTransferBuffer(-1, &buffers_[0], kBufferSize)); } } // namespace gpu
41.948276
78
0.606658
68c7a487e962bab969ab40a56ea58e555a3defc7
1,848
cpp
C++
tests/src/main.cpp
nemu-cpp/web-server
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
[ "MIT" ]
null
null
null
tests/src/main.cpp
nemu-cpp/web-server
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
[ "MIT" ]
null
null
null
tests/src/main.cpp
nemu-cpp/web-server
353ba231bc42c72e69f82ddbb7ae2ffbb5cbb97f
[ "MIT" ]
null
null
null
/* Copyright (c) 2019-2022 Xavier Leclercq Released under the MIT License See https://github.com/nemu-cpp/web-framework/blob/main/LICENSE.txt */ #include "DebugTemplateEngineProfileTests.hpp" #include "DebugTemplateEngineTests.hpp" #include "FileSystemWebRequestHandlerTests.hpp" #include "FunctionWebRequestHandlerTests.hpp" #include "HardcodedWebRequestHandlerTests.hpp" #include "MapViewContextTests.hpp" #include "RouteTests.hpp" #include "RoutesTests.hpp" #include "SingleConnectionWebServerTests.hpp" #include "ViewsTests.hpp" #include "ViewWebRequestHandlerTests.hpp" #include "WebApplicationTests.hpp" #include "WebRequestTests.hpp" #include "WebResponseBuilderTests.hpp" #include "Nemu/WebFramework/linkoptions.hpp" #include <Ishiko/TestFramework.hpp> using namespace Ishiko; int main(int argc, char* argv[]) { TestHarness theTestHarness("NemuWebFramework"); theTestHarness.context().setTestDataDirectory("../../data"); theTestHarness.context().setTestOutputDirectory("../../output"); theTestHarness.context().setReferenceDataDirectory("../../reference"); TestSequence& theTests = theTestHarness.tests(); theTests.append<MapViewContextTests>(); theTests.append<ViewsTests>(); theTests.append<DebugTemplateEngineTests>(); theTests.append<DebugTemplateEngineProfileTests>(); theTests.append<SingleConnectionWebServerTests>(); theTests.append<WebRequestTests>(); theTests.append<WebResponseBuilderTests>(); theTests.append<RouteTests>(); theTests.append<RoutesTests>(); theTests.append<HardcodedWebRequestHandlerTests>(); theTests.append<FunctionWebRequestHandlerTests>(); theTests.append<FileSystemWebRequestHandlerTests>(); theTests.append<ViewWebRequestHandlerTests>(); theTests.append<WebApplicationTests>(); return theTestHarness.run(); }
35.538462
74
0.77381
68c7f065cffccfaa24d72f7e637a04addbf03f30
5,053
cpp
C++
src/main_void_MPI_bitvec.cpp
rapastranac/gempba
3b50f9809af95e2001615ab704bb055db68f50c8
[ "MIT" ]
1
2021-07-08T13:52:06.000Z
2021-07-08T13:52:06.000Z
src/main_void_MPI_bitvec.cpp
rapastranac/gempba
3b50f9809af95e2001615ab704bb055db68f50c8
[ "MIT" ]
2
2021-07-31T14:58:02.000Z
2021-09-07T01:55:06.000Z
src/main_void_MPI_bitvec.cpp
rapastranac/gempba
3b50f9809af95e2001615ab704bb055db68f50c8
[ "MIT" ]
null
null
null
#ifdef BITVECTOR_VC #include "../include/main.h" #include "../include/Graph.hpp" #include "../MPI_Modules/MPI_Scheduler.hpp" #include "../include/VC_void_MPI_bitvec.hpp" #include "../include/resultholder/ResultHolder.hpp" #include "../include/BranchHandler.hpp" #include "../include/DLB_Handler.hpp" #include <chrono> #include <filesystem> #include <fstream> #include <iostream> #include <istream> #include <sstream> #include <iterator> #include <string> #include <vector> #include <unistd.h> int main_void_MPI_bitvec(int numThreads, int prob, std::string &filename) { auto &branchHandler = GemPBA::BranchHandler::getInstance(); // parallel library auto &mpiScheduler = GemPBA::MPI_Scheduler::getInstance(); int rank = mpiScheduler.rank_me(); branchHandler.passMPIScheduler(&mpiScheduler); cout << "NUMTHREADS= " << numThreads << endl; VC_void_MPI_bitvec cover; auto function = std::bind(&VC_void_MPI_bitvec ::mvcbitset, &cover, _1, _2, _3, _4, _5); // target algorithm [all arguments] // initialize MPI and member variable linkin /* this is run by all processes, because it is a bitvector implementation, all processes should know the original graph ******************************************************/ Graph graph; graph.readEdges(filename); cover.init(graph, numThreads, filename, prob); cover.setGraph(graph); int gsize = graph.adj.size() + 1; //+1 cuz some files use node ids from 1 to n (instead of 0 to n - 1) gbitset allzeros(gsize); gbitset allones = ~allzeros; branchHandler.setRefValue(gsize); // thus, all processes know the best value so far branchHandler.setRefValStrategyLookup("minimise"); int zero = 0; int solsize = graph.size(); cout << "solsize=" << solsize << endl; std::string buffer = serializer(zero, allones, zero); std::cout << "Starting MPI node " << branchHandler.rank_me() << std::endl; int pid = getpid(); // for debugging purposes fmt::print("rank {} is process ID : {}\n", rank, pid); // for debugging purposes if (rank == 0) { // center process mpiScheduler.runCenter(buffer.data(), buffer.size()); } else { /* worker process main thread will take care of Inter-process communication (IPC), dedicated core numThreads could be the number of physical cores managed by this process - 1 */ branchHandler.initThreadPool(numThreads); auto bufferDecoder = branchHandler.constructBufferDecoder<void, int, gbitset, int>(function, deserializer); auto resultFetcher = branchHandler.constructResultFetcher(); mpiScheduler.runNode(branchHandler, bufferDecoder, resultFetcher, serializer); } mpiScheduler.barrier(); // ***************************************************************************************** // this is a generic way of getting information from all the other processes after execution retuns auto world_size = mpiScheduler.getWorldSize(); std::vector<double> idleTime(world_size); std::vector<size_t> threadRequests(world_size); std::vector<int> nTasksRecvd(world_size); std::vector<int> nTasksSent(world_size); double idl_tm = 0; size_t rqst = 0; int taskRecvd; int taskSent; if (rank != 0) { //rank 0 does not run the main function idl_tm = branchHandler.getPoolIdleTime(); rqst = branchHandler.number_thread_requests(); taskRecvd = mpiScheduler.tasksRecvd(); taskSent = mpiScheduler.tasksSent(); } // here below, idl_tm is the idle time of the other ranks, which is gathered by .allgather() and stored in // a contiguos array mpiScheduler.allgather(idleTime.data(), &idl_tm, MPI_DOUBLE); mpiScheduler.allgather(threadRequests.data(), &rqst, MPI_UNSIGNED_LONG_LONG); mpiScheduler.gather(&taskRecvd, 1, MPI_INT, nTasksRecvd.data(), 1, MPI_INT, 0); mpiScheduler.gather(&taskSent, 1, MPI_INT, nTasksSent.data(), 1, MPI_INT, 0); // ***************************************************************************************** if (rank == 0) { auto solutions = mpiScheduler.fetchResVec(); mpiScheduler.printStats(); //print sumation of refValGlobal int solsize; std::stringstream ss; std::string buffer = mpiScheduler.fetchSolution(); // returns a stringstream ss << buffer; deserializer(ss, solsize); fmt::print("Cover size : {} \n", solsize); double sum = 0; for (int i = 1; i < world_size; i++) { sum += idleTime[i]; } fmt::print("\nGlobal pool idle time: {0:.6f} seconds\n\n\n", sum); // ************************************************************************** for (int rank = 1; rank < world_size; rank++) { fmt::print("tasks sent by rank {} = {} \n", rank, nTasksSent[rank]); } fmt::print("\n"); for (int rank = 1; rank < world_size; rank++) { fmt::print("tasks received by rank {} = {} \n", rank, nTasksRecvd[rank]); } fmt::print("\n"); for (int rank = 1; rank < world_size; rank++) { fmt::print("rank {}, thread requests: {} \n", rank, threadRequests[rank]); } fmt::print("\n\n\n"); // ************************************************************************** } return 0; } #endif
30.624242
124
0.64338
68c845b9335cdf764e208c6c9a498556a8478c7c
16,778
hh
C++
include/click/flow/flowelement.hh
MassimoGirondi/fastclick
71b9a3392c2e847a22de3c354be1d9f61216cb5b
[ "BSD-3-Clause-Clear" ]
1
2021-01-22T16:51:37.000Z
2021-01-22T16:51:37.000Z
include/click/flow/flowelement.hh
nic-bench/fastclick
2812f0684050cec07e08f30d643ed121871cf25d
[ "BSD-3-Clause-Clear" ]
null
null
null
include/click/flow/flowelement.hh
nic-bench/fastclick
2812f0684050cec07e08f30d643ed121871cf25d
[ "BSD-3-Clause-Clear" ]
null
null
null
// -*- c-basic-offset: 4 -*- #ifndef CLICK_FLOWELEMENT_HH #define CLICK_FLOWELEMENT_HH #include <click/glue.hh> #include <click/vector.hh> #include <click/string.hh> #include <click/batchelement.hh> #include <click/routervisitor.hh> #include <click/pair.hh> #include "flow.hh" CLICK_DECLS #ifdef HAVE_FLOW # if HAVE_CTX class CTXManager; # endif class VirtualFlowManager; enum FlowType { FLOW_NONE = 0, FLOW_ETHER, FLOW_ARP, FLOW_IP, FLOW_TCP, FLOW_UDP, FLOW_ICMP, FLOW_HTTP }; class FlowElement : public BatchElement { public: FlowElement(); ~FlowElement(); # if HAVE_CTX virtual FlowNode* get_table(int iport, Vector<FlowElement*> contextStack); virtual FlowNode* resolveContext(FlowType, Vector<FlowElement*> stack); # endif virtual FlowType getContext(int port); virtual bool stopClassifier() { return false; }; }; /** * Element that needs FCB space */ class VirtualFlowSpaceElement : public FlowElement { public: VirtualFlowSpaceElement(); virtual const size_t flow_data_size() const = 0; virtual const int flow_data_index() const { return -1; } inline void set_flow_data_offset(int offset) {_flow_data_offset = offset; } inline int flow_data_offset() {return _flow_data_offset; } int configure_phase() const { return CONFIGURE_PHASE_DEFAULT + 5; } void *cast(const char *name) override; #if HAVE_FLOW_DYNAMIC inline void fcb_acquire(int count = 1) { fcb_stack->acquire(count); } inline void fcb_update(int count) { if (count > 0) fcb_stack->acquire(count); else if (count < 0) fcb_stack->release(-count); } inline void fcb_release(int count = 1) { fcb_stack->release(count); } #else inline void fcb_acquire(int count = 1) { (void)count; } inline void fcb_update(int) {} inline void fcb_release(int count = 1) { (void)count; } #endif #if HAVE_FLOW_RELEASE_SLOPPY_TIMEOUT inline void fcb_acquire_timeout(int nmsec) { //Do not set a smaller timeout if ((fcb_stack->flags & FLOW_TIMEOUT) && (nmsec <= (int)(fcb_stack->flags >> FLOW_TIMEOUT_SHIFT))) { #if DEBUG_CLASSIFIER_TIMEOUT > 1 click_chatter("Acquiring timeout of %p, not changing it, flag %d",this,fcb_stack->flags); #endif return; } #if DEBUG_CLASSIFIER_TIMEOUT > 1 click_chatter("Acquiring timeout of %p to %d, flag %d",this,nmsec,fcb_stack->flags); #endif fcb_stack->flags = (nmsec << FLOW_TIMEOUT_SHIFT) | FLOW_TIMEOUT | ((fcb_stack->flags & FLOW_TIMEOUT_INLIST) ? FLOW_TIMEOUT_INLIST : 0); } inline void fcb_release_timeout() { #if DEBUG_CLASSIFIER_TIMEOUT > 1 click_chatter("Releasing timeout of %p",this); #endif //If the timeout is in list, we must not put it back in the pool if (fcb_stack->flags & FLOW_TIMEOUT_INLIST) assert(fcb_stack->flags & FLOW_TIMEOUT); if ((fcb_stack->flags & FLOW_TIMEOUT) && (fcb_stack->flags & FLOW_TIMEOUT_INLIST)) fcb_stack->flags = 0 | FLOW_TIMEOUT | FLOW_TIMEOUT_INLIST; else fcb_stack->flags = 0; } #else inline void fcb_acquire_timeout(int nmsec) { //TODO : use a local timer fcb_acquire(); } inline void fcb_release_timeout() { fcb_release(); } #endif #if HAVE_DYNAMIC_FLOW_RELEASE_FNT inline void fcb_set_release_fnt(struct FlowReleaseChain* fcb_chain, SubFlowRealeaseFnt fnt) { fcb_chain->previous_fnt = fcb_stack->release_fnt; fcb_chain->previous_thunk = fcb_stack->thunk; fcb_stack->release_fnt = fnt; fcb_stack->thunk = this; #if DEBUG_CLASSIFIER_RELEASE click_chatter("Release fnt set to %p, was %p",fcb_stack->release_fnt,fcb_chain->previous_fnt); #endif } inline void fcb_remove_release_fnt(struct FlowReleaseChain* fcb_chain, SubFlowRealeaseFnt fnt) { debug_flow("Release fnt remove %p",fnt); if (likely(fcb_stack->release_fnt == fnt)) { //Normally it will call the chain in the same order fcb_stack->release_fnt = fcb_chain->previous_fnt; fcb_stack->thunk = fcb_chain->previous_thunk; debug_flow("Release removed is now to %p",fcb_stack->release_fnt); } else { SubFlowRealeaseFnt chain_fnt = fcb_stack->release_fnt; VirtualFlowSpaceElement* fe = static_cast<VirtualFlowSpaceElement*>(fcb_stack->thunk); FlowReleaseChain* frc; do { if (fe == 0) { click_chatter("BAD ERROR : Trying to remove a timeout flow function that is not set..."); return; } frc = reinterpret_cast<FlowReleaseChain*>(&fcb_stack->data[fe->_flow_data_offset]); chain_fnt = frc->previous_fnt; if (chain_fnt == 0) { click_chatter("ERROR : Trying to remove a timeout flow function that is not set..."); return; } fe = static_cast<VirtualFlowSpaceElement*>(frc->previous_thunk); } while (chain_fnt != fnt); frc->previous_fnt = fcb_chain->previous_fnt; frc->previous_thunk = fcb_chain->previous_thunk; } } #else inline void fcb_set_release_fnt(struct FlowReleaseChain* fcb, SubFlowRealeaseFnt fnt) { click_chatter("ERROR: YOU MUST HAVE DYNAMIC FLOW RELEASE FNT fct setted !"); assert(false); } #endif virtual PacketBatch* pull_batch(int port, unsigned max) override final { click_chatter("ERROR : Flow Elements do not support pull"); return 0; } int initialize(ErrorHandler *errh) override CLICK_COLD { //The element itself is automatically posted by build_fcb via fcb_builded_init_future return 0; } protected: int _flow_data_offset; friend class FlowBufferVisitor; friend class VirtualFlowManager; }; /** * This future will only trigger once it is called N times. * N is increased by calling add(). The typical usage is a future * that will only trigger when all parents have called. To do this, * you call add() in the constructor of the parents. */ class CounterInitFuture : public Router::ChildrenFuture { public: CounterInitFuture(String name, std::function<int(ErrorHandler*)> on_reached); CounterInitFuture(String name, std::function<void(void)> on_reached); virtual void notifyParent(InitFuture* future) override; virtual int solve_initialize(ErrorHandler* errh) override; virtual int completed(ErrorHandler* errh) override; private: int _n; String _name; std::function<int(ErrorHandler*)> _on_reached; }; /** * Element that allocates some FCB Space */ class VirtualFlowManager : public FlowElement { public: VirtualFlowManager(); static CounterInitFuture* fcb_builded_init_future() { return &_fcb_builded_init_future; } static CounterInitFuture _fcb_builded_init_future; protected: int _reserve; typedef Pair<Element*,int> EDPair; Vector<EDPair> _reachable_list; static Vector<VirtualFlowManager*> _entries; void find_children(int verbose = 0); static void _build_fcb(int verbose, bool ordered); static void build_fcb(); virtual void fcb_built() { } bool stopClassifier() { return true; }; friend class CTXElement; }; template<typename T> class FlowSpaceElement : public VirtualFlowSpaceElement { public : FlowSpaceElement() CLICK_COLD; void fcb_set_init_data(FlowControlBlock* fcb, const T data) CLICK_COLD; virtual const size_t flow_data_size() const override { return sizeof(T); } /** * Return the T type for a given FCB */ inline T* fcb_data_for(FlowControlBlock* fcb) { T* flowdata = static_cast<T*>((void*)&fcb->data[_flow_data_offset]); return flowdata; } /** * Return the T type in the current FCB on the stack */ inline T* fcb_data() { return fcb_data_for(fcb_stack); } void push_batch(int port, PacketBatch* head) final { push_flow(port, fcb_data(), head); }; virtual void push_flow(int port, T* flowdata, PacketBatch* head) = 0; }; /** * FlowStateElement is like FlowSpaceElement but handle a timeout and a release functions * * The child must implement : * static const int timeout; //Timeout in msec for a flow * bool new_flow(T*, Packet*); * void push_batch(int port, T*, Packet*); * void release_flow(T*); * * close_flow() can be called to release the flow now, remove timer etc It will not call your release_flow(); automatically, do it before. A packet coming for the same flow after close_flow() is called will be considered from a new flow (seen flag is reset). */ template<class Derived, typename T> class FlowStateElement : public VirtualFlowSpaceElement { struct AT : public FlowReleaseChain { T v; bool seen; }; public : typedef FlowStateElement<Derived, T> derived; FlowStateElement() CLICK_COLD; virtual const size_t flow_data_size() const { return sizeof(AT); } /** * CRTP virtual */ inline bool new_flow(T*, Packet*) { return true; } /** * Return the T type for a given FCB */ inline T* fcb_data_for(FlowControlBlock* fcb) { AT* flowdata = static_cast<AT*>((void*)&fcb->data[_flow_data_offset]); return &flowdata->v; } /** * Return the T type in the current FCB on the stack */ inline T* fcb_data() { return fcb_data_for(fcb_stack); } static void release_fnt(FlowControlBlock* fcb, void* thunk ) { Derived* derived = static_cast<Derived*>(thunk); AT* my_fcb = reinterpret_cast<AT*>(&fcb->data[derived->_flow_data_offset]); derived->release_flow(&my_fcb->v); if (my_fcb->previous_fnt) my_fcb->previous_fnt(fcb, my_fcb->previous_thunk); } void push_batch(int port, PacketBatch* head) { auto my_fcb = my_fcb_data(); if (!my_fcb->seen) { if (static_cast<Derived*>(this)->new_flow(&my_fcb->v, head->first())) { my_fcb->seen = true; if (Derived::timeout > 0) this->fcb_acquire_timeout(Derived::timeout); #if HAVE_DYNAMIC_FLOW_RELEASE_FNT this->fcb_set_release_fnt(my_fcb, &release_fnt); #endif } else { //TODO set early drop? head->fast_kill(); return; } } static_cast<Derived*>(this)->push_flow(port, &my_fcb->v, head); }; void close_flow() { if (Derived::timeout > 0) { this->fcb_release_timeout(); } #if HAVE_DYNAMIC_FLOW_RELEASE_FNT this->fcb_remove_release_fnt(my_fcb_data(), &release_fnt); #endif my_fcb_data()->seen = false; } private: inline AT* my_fcb_data() { return static_cast<AT*>((void*)&fcb_stack->data[_flow_data_offset]); } }; template<typename T, int index> class FlowSharedBufferElement : public FlowSpaceElement<T> { public : FlowSharedBufferElement() : FlowSpaceElement<T>() { } const size_t flow_data_size() const final { return sizeof(T); } const int flow_data_index() const final { return index; } }; #define DefineFlowSharedBuffer(name,type,index) class FlowSharedBuffer ## name ## Element : public FlowSharedBufferElement<type,index>{ }; DefineFlowSharedBuffer(Paint,int,0); #define NR_SHARED_FLOW 1 class FlowElementVisitor : public RouterVisitor { public: Element* origin; FlowElementVisitor(Element* e) : origin(e) { } struct inputref { FlowElement* elem; int iport; }; Vector<struct inputref> dispatchers; bool visit(Element *e, bool isoutput, int port, Element *from_e, int from_port, int distance) { FlowElement* dispatcher = dynamic_cast<FlowElement*>(e); if (dispatcher != NULL) { if (dispatcher == origin) return false; struct inputref ref = {.elem = dispatcher, .iport = port}; dispatchers.push_back(ref); return false; } else { } /*if (v.dispatchers[i] == (FlowElement*)e) { click_chatter("Classification loops are unsupported, place another CTXManager before reinjection of the packets."); e->router()->please_stop_driver(); return 0; }*/ return true; } static FlowNode* get_downward_table(Element* e, int output, Vector<FlowElement*> context, bool resolve_context = false); }; /** * FlowSpaceElement */ template<typename T> FlowSpaceElement<T>::FlowSpaceElement() : VirtualFlowSpaceElement() { } # if HAVE_CTX template<typename T> void FlowSpaceElement<T>::fcb_set_init_data(FlowControlBlock* fcb, const T data) { for (int i = 0; i < sizeof(T); i++) { if (fcb->data[FCBPool::init_data_size() + _flow_data_offset + i] && fcb->data[_flow_data_offset + i] != ((uint8_t*)&data)[i]) { click_chatter("In %p{element} for offset %d :",this, _flow_data_offset+i); click_chatter("Index [%d] : Cannot set data to %d, as it is already %d",i,*((T*)(&fcb->data[_flow_data_offset])),data); click_chatter("Is marked as set : %d", fcb->data[FCBPool::init_data_size() + _flow_data_offset + i]); fcb->reverse_print(); click_chatter("It generally means your graph is messed up"); assert(false); } fcb->data[FCBPool::init_data_size() + _flow_data_offset + i] = 0xff; } *((T*)(&fcb->data[_flow_data_offset])) = data; } # endif /** * FlowSpaceElement */ template<class Derived, typename T> FlowStateElement<Derived, T>::FlowStateElement() : VirtualFlowSpaceElement() { } /** * Macro to define context * * In practice it will overwrite get_table */ # if HAVE_CTX #define DEFAULT_4TUPLE "12/0/ffffffff:HASH-3 16/0/ffffffff:HASH-3 20/0/ffffffff:HASH-3" //Those should not be used anymore, as the FLOW_CONTEXT is a much better alternative that assuming the top session is IP... #define TCP_SESSION "9/06! 12/0/ffffffff:HASH-3 16/0/ffffffff:HASH-3 20/0/ffffffff:HASH-3" #define UDP_SESSION "9/11! 12/0/ffffffff:HASH-3 16/0/ffffffff:HASH-3 20/0/ffffffff:HASH-3" //Use only one of the 3 following macros /** * Define a context (such as FLOW_IP) but no rule/session */ #define FLOW_ELEMENT_DEFINE_CONTEXT(ft) \ FlowNode* get_table(int iport, Vector<FlowElement*> context) override CLICK_COLD {\ context.push_back(this);\ return FlowElement::get_table(iport, context);\ }\ virtual FlowType getContext(int) override {\ return ft;\ }\ /** * Define a context (such as FLOW_TCP) and a rule/session definition */ #define FLOW_ELEMENT_DEFINE_SESSION_CONTEXT(rule,ft) \ FlowNode* get_table(int iport, Vector<FlowElement*> contextStack) override CLICK_COLD {\ if (ft)\ contextStack.push_back(this);\ FlowNode* down = FlowElement::get_table(iport,contextStack); \ FlowNode* my = FlowClassificationTable::parse(this,rule).root;\ return my->combine(down, true, true, true, this);\ }\ virtual FlowType getContext(int) override {\ return ft;\ }\ /** * Define only a rule/session definition but no context */ #define FLOW_ELEMENT_DEFINE_SESSION(rule) \ FLOW_ELEMENT_DEFINE_SESSION_CONTEXT(rule,FLOW_NONE) /** * Defin two rules/sessions but no context */ #define FLOW_ELEMENT_DEFINE_SESSION_DUAL(ruleA,ruleB) \ FlowNode* get_table(int iport, Vector<FlowElement*> context) override CLICK_COLD {\ return FlowClassificationTable::parse(this,ruleA).root->combine(FlowClassificationTable::parse(this,ruleB).root,false,false,true,this)->combine(FlowElement::get_table(iport,context), true, true, true, this);\ } /** * Define the context no matter the input port, and a rule but only for one specific port */ #define FLOW_ELEMENT_DEFINE_PORT_SESSION_CONTEXT(port_num,rule,ft) \ FlowNode* get_table(int iport, Vector<FlowElement*> contextStack) override {\ if (iport == port_num) {\ return FlowClassificationTable::parse(this,rule).root->combine(FlowElement::get_table(iport,contextStack), true, true, true, this);\ }\ if (ft)\ contextStack.push_back(this);\ return FlowElement::get_table(iport,contextStack);\ }\ virtual FlowType getContext(int) override {\ return ft;\ } #endif #else //Not even HAVE_FLOW typedef BatchElement FlowElement; #endif #if !defined(HAVE_CTX) #define FLOW_ELEMENT_DEFINE_SESSION(rule,context) #define FLOW_ELEMENT_DEFINE_PORT_CONTEXT(port,rule,context) #define FLOW_ELEMENT_DEFINE_SESSION_DUAL(ruleA,ruleB) #define FLOW_ELEMENT_DEFINE_SESSION_CONTEXT(rule,context) #define FLOW_ELEMENT_DEFINE_PORT_SESSION_CONTEXT(port,rule,context) #endif CLICK_ENDDECLS #endif
30.672761
258
0.671355
68c88971ef4e0dc763be19d3efed1264cdbf02af
4,475
cpp
C++
arangod/Scheduler/JobQueue.cpp
pjesudhas/ArangoDB
76684f84ee34f1fff25fc9bf2f4cee7a5abd03cc
[ "BSL-1.0", "Zlib", "ICU", "Apache-2.0" ]
null
null
null
arangod/Scheduler/JobQueue.cpp
pjesudhas/ArangoDB
76684f84ee34f1fff25fc9bf2f4cee7a5abd03cc
[ "BSL-1.0", "Zlib", "ICU", "Apache-2.0" ]
null
null
null
arangod/Scheduler/JobQueue.cpp
pjesudhas/ArangoDB
76684f84ee34f1fff25fc9bf2f4cee7a5abd03cc
[ "BSL-1.0", "Zlib", "ICU", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "JobQueue.h" #include "Basics/ConditionLocker.h" #include "GeneralServer/RestHandler.h" #include "Logger/Logger.h" #include "Scheduler/Scheduler.h" #include "Scheduler/SchedulerFeature.h" using namespace arangodb; namespace { class JobQueueThread final : public Thread { public: JobQueueThread(JobQueue* server, boost::asio::io_service* ioService) : Thread("JobQueueThread"), _jobQueue(server), _ioService(ioService) {} ~JobQueueThread() { shutdown(); } void beginShutdown() { Thread::beginShutdown(); _jobQueue->wakeup(); } public: void run() { int idleTries = 0; auto jobQueue = _jobQueue; // iterate until we are shutting down while (!isStopping()) { ++idleTries; for (size_t i = 0; i < JobQueue::SYSTEM_QUEUE_SIZE; ++i) { LOG_TOPIC(TRACE, Logger::THREADS) << "size of queue #" << i << ": " << _jobQueue->queueSize(i); while (_jobQueue->tryActive()) { Job* job = nullptr; if (!_jobQueue->pop(i, job)) { _jobQueue->releaseActive(); break; } LOG_TOPIC(TRACE, Logger::THREADS) << "starting next queued job, number currently active " << _jobQueue->active(); idleTries = 0; _ioService->dispatch([jobQueue, job]() { std::unique_ptr<Job> guard(job); job->_callback(std::move(job->_handler)); jobQueue->releaseActive(); jobQueue->wakeup(); }); } } // we need to check again if more work has arrived after we have // aquired the lock. The lockfree queue and _nrWaiting are accessed // using "memory_order_seq_cst", this guarantees that we do not // miss a signal. if (idleTries >= 2) { LOG_TOPIC(TRACE, Logger::THREADS) << "queue manager going to sleep"; _jobQueue->waitForWork(); } } } private: JobQueue* _jobQueue; boost::asio::io_service* _ioService; }; } // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- JobQueue::JobQueue(size_t queueSize, boost::asio::io_service* ioService) : _queueAql(queueSize), _queueRequeue(queueSize), _queueStandard(queueSize), _queueUser(queueSize), _queues{&_queueRequeue, &_queueAql, &_queueStandard, &_queueUser}, _active(0), _ioService(ioService), _queueThread(new JobQueueThread(this, _ioService)) { for (size_t i = 0; i < SYSTEM_QUEUE_SIZE; ++i) { _queuesSize[i].store(0); } } // ----------------------------------------------------------------------------- // --SECTION-- public methods // ----------------------------------------------------------------------------- void JobQueue::start() { _queueThread->start(); } void JobQueue::beginShutdown() { _queueThread->beginShutdown(); } bool JobQueue::tryActive() { if (!SchedulerFeature::SCHEDULER->tryBlocking()) { return false; } ++_active; return true; } void JobQueue::releaseActive() { SchedulerFeature::SCHEDULER->unworkThread(); --_active; } void JobQueue::wakeup() { CONDITION_LOCKER(guard, _queueCondition); guard.signal(); } void JobQueue::waitForWork() { static uint64_t WAIT_TIME = 1000 * 1000; CONDITION_LOCKER(guard, _queueCondition); guard.wait(WAIT_TIME); }
28.685897
80
0.56
68c90335118c25cb4852515593eb2d7fe6f87ffe
13,005
cc
C++
xvcSrv/src/xvcDrvAxisTmem.cc
paulscherrerinstitute/xvcSupport
62aa062cd9126c71fcc556f547abdd1fa8823eff
[ "BSD-3-Clause-LBNL" ]
6
2020-12-23T16:46:26.000Z
2022-02-11T14:42:32.000Z
xvcSrv/src/xvcDrvAxisTmem.cc
paulscherrerinstitute/xvcSupport
62aa062cd9126c71fcc556f547abdd1fa8823eff
[ "BSD-3-Clause-LBNL" ]
null
null
null
xvcSrv/src/xvcDrvAxisTmem.cc
paulscherrerinstitute/xvcSupport
62aa062cd9126c71fcc556f547abdd1fa8823eff
[ "BSD-3-Clause-LBNL" ]
2
2020-09-18T14:34:25.000Z
2021-07-22T16:14:58.000Z
//----------------------------------------------------------------------------- // Title : JTAG Support //----------------------------------------------------------------------------- // File : xvcDrvAxisFifo.cc // Author : Till Straumann <strauman@slac.stanford.edu> // Company : SLAC National Accelerator Laboratory // Created : 2017-12-05 // Last update: 2017-12-05 // Platform : // Standard : VHDL'93/02 //----------------------------------------------------------------------------- // Description: //----------------------------------------------------------------------------- // This file is part of 'SLAC Firmware Standard Library'. // It is subject to the license terms in the LICENSE.txt file found in the // top-level directory of this distribution and at: // https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html. // No part of 'SLAC Firmware Standard Library', including this file, // may be copied, modified, propagated, or distributed except according to // the terms contained in the LICENSE.txt file. //----------------------------------------------------------------------------- #include <xvcDrvAxisTmem.h> #include <unistd.h> #include <stdlib.h> #include <toscaApi.h> #include <fcntl.h> #define SDES_PROBEVAL (0xa<<(SDES_CSR_LENS)) JtagDriverTmemFifo::JtagDriverTmemFifo(int argc, char *const argv[], const char *devnam) : JtagDriverAxisToJtag( argc, argv ), toscaSpace_ ( TOSCA_USER2 ), toscaBase_ ( 0x200000 ), maxVec_ ( 128 ), wrdSiz_ ( sizeof(uint32_t) ), irqFd_ ( - 1 ), bitBang_ ( false ), logBscn_ ( false ), doSleep_ ( false ), measure_ ( 100 ), maxPollDelayUs_ ( 0 ) { uint32_t csrVal, csrSdes; unsigned long maxBytes; unsigned long maxWords = 512; int opt; const char *basp; char *endp; const char *irqfn = 0; toscaSpace_ = toscaStrToAddrSpace(devnam, &basp); toscaBase_ = strtoul(basp, &endp, 0); if ( ! toscaSpace_ || (endp == basp) ) { fprintf(stderr, "Invalid <target>: must be '<tosca_addr_space>:<numerical_base_address>'\n"); throw std::runtime_error("Invalid <target>"); } if ( MAGIC != i32( FIFO_MAGIC_IDX ) ) { fprintf( stderr, "No magic firmware ID found; please verify address-space and base-address\n" ); throw std::runtime_error("TMEM Device not found"); } while ( (opt = getopt(argc, argv, "i:bl")) > 0 ) { switch ( opt ) { case 'b': bitBang_ = true; break; case 'l': logBscn_ = true; break; case 'i': irqfn = optarg; break; default: fprintf( stderr,"Unknown driver option -%c\n", opt ); throw std::runtime_error("Unknown driver option"); } } csrVal = i32( FIFO_CSR_IDX ); version_ = ((csrVal & FIFO_CSR_VERSM) >> FIFO_CSR_VERSS); switch ( version_ ) { case VERSION_0: if ( bitBang_ || logBscn_ ) { fprintf( stderr, "Bit-banging not supported for FW interface; disabling\n"); bitBang_ = false; logBscn_ = false; } break; case VERSION_1: csrSdes = i32( SDES_CSR_IDX ) & ~SDES_CSR_LRMSK; o32( SDES_CSR_IDX, (csrSdes | SDES_PROBEVAL ) ); if ( (i32(SDES_CSR_IDX) & SDES_CSR_LRMSK) == SDES_PROBEVAL ) { useSdes_ = true; printf("JtagSerDes raw interface detected\n"); } break; default: fprintf( stderr, "Firmware interface version not supported by this driver\n"); throw std::runtime_error("TMEM Device wrong FW version"); } if ( logBscn_ ) { bitBang_ = true; } if ( bitBang_ || ~useSdes_ ) { measure_ = 0; } if ( bitBang_ || useSdes_ ) { if ( irqfn ) { fprintf(stderr, "Interrupts not supported (sdes or bit-bang)\n"); } irqfn = 0; } maxWords = (((csrVal & FIFO_CSR_MAXWM) >> FIFO_CSR_MAXWS) << 10 ) / wrdSiz_; // one header word; two vectors must fit maxBytes = (maxWords - 1) * wrdSiz_; maxVec_ = maxBytes/2; if ( irqfn && ( (irqFd_ = open(irqfn, O_RDWR)) < 0 ) ) { perror("WARNING: Interrupt descriptor not found -- using polled mode"); } // one header word; two vectors must fit maxBytes = (maxWords - 1) * wrdSiz_; maxVec_ = maxBytes/2; reset(); } JtagDriverTmemFifo::~JtagDriverTmemFifo() { if ( irqFd_ >= 0 ) { close( irqFd_ ); } } void JtagDriverTmemFifo::o32(unsigned idx, uint32_t v) { if ( debug_ > 2 ) { fprintf(stderr, "r[%d]:=0x%08x\n", idx, v); } toscaWrite( toscaSpace_, toscaBase_ + (idx << 2), v ); } uint32_t JtagDriverTmemFifo::i32(unsigned idx) { uint32_t v = toscaRead( toscaSpace_, toscaBase_ + (idx << 2) ); if ( debug_ > 2 ) { fprintf(stderr, "r[%d]=>0x%08x\n", idx, v); } return v; } uint32_t JtagDriverTmemFifo::wait() { uint32_t evs = 0; if ( irqFd_ >= 0 ) { evs = 1; if ( sizeof(evs) != write( irqFd_, &evs, sizeof(evs) ) ) { throw SysErr("Unable to write to IRQ descriptor"); } if ( sizeof(evs) != read( irqFd_, &evs, sizeof(evs) ) ) { throw SysErr("Unable to read from IRQ descriptor"); } } else if ( doSleep_ ) { nanosleep( &pollTime_, 0 ); } // else busy wait return evs; } void JtagDriverTmemFifo::reset() { int set = 0; uint32_t csr; /* Do this first; resets the internal registers, too! */ if ( ! useSdes_ ) { o32( FIFO_CSR_IDX, FIFO_CSR_RST ); o32( FIFO_CSR_IDX, 0 ); if ( irqFd_ >= 0 ) { o32( FIFO_CSR_IDX, FIFO_CSR_IENI ); } } if ( version_ == VERSION_1 ) { /* Have bitbang */ csr = i32( SDES_CSR_IDX ); // reset bit-banging interface csr &= ~ SDES_CSR_BBMSK; // must pull TMS high; TMS on jtag is bb-TMS AND serdes-TMS // TCK and TDI must be low (ORed) csr |= SDES_CSR_BB_TMS; csr &= ~ SDES_CSR_BB_TDI; csr &= ~ SDES_CSR_BB_TCK; csr &= ~ SDES_CSR_BB_ENA; o32( SDES_CSR_IDX, csr ); if ( useSdes_ ) { // reset TAP and leave with TMS asserted (in fact; TMS seems deasserted due to a bug?), TDI deasserted xfer32sdes( 0xff, 0x00, 8, 0 ); } } if ( bitBang_ ) { o32( SDES_CSR_IDX, csr | SDES_CSR_BB_ENA ); } } uint32_t JtagDriverTmemFifo::xfer32bb(uint32_t tms, uint32_t tdi, unsigned nbits) { uint32_t m; uint32_t csr, tdo, csrrb; unsigned i; tdo = 0; csr = i32( SDES_CSR_IDX ) & ~SDES_CSR_BBMSK; for ( i = 0, m = 1; i < nbits; i++, m <<= 1 ) { if ( (tms & m ) ) csr |= SDES_CSR_BB_TMS; else csr &= ~ SDES_CSR_BB_TMS; if ( (tdi & m ) ) csr |= SDES_CSR_BB_TDI; else csr &= ~ SDES_CSR_BB_TDI; o32( SDES_CSR_IDX, csr ); bbsleep(); if ( (csrrb = i32( SDES_CSR_IDX )) & SDES_CSR_BB_TDO ) { tdo |= m; } if ( logBscn_ ) { fprintf(stderr, "BSCNL: 0x%08x\n", (unsigned long)csrrb); } csr |= SDES_CSR_BB_TCK; o32( SDES_CSR_IDX, csr ); bbsleep(); if ( logBscn_ ) { csrrb = i32( SDES_CSR_IDX ); fprintf(stderr, "BSCNH: 0x%08x\n", (unsigned long)csrrb); } csr &= ~SDES_CSR_BB_TCK; } // o32( SDES_CSR_IDX, csr ); return tdo; } void JtagDriverTmemFifo::bbsleep() { struct timespec t; t.tv_sec = 0; t.tv_nsec = 1000; nanosleep( &t, 0 ); } uint32_t JtagDriverTmemFifo::xfer32sdes(uint32_t tms, uint32_t tdi, unsigned nbits, struct timespec *then) { uint32_t csr, tdo; csr = i32( SDES_CSR_IDX ) & ~ SDES_CSR_LRMSK; csr |= (nbits - 1) << SDES_CSR_LENS; o32( SDES_TMS_IDX, tms ); o32( SDES_TDI_IDX, tdi ); o32( SDES_CSR_IDX, csr | SDES_CSR_RUN ); if ( then && measure_ ) { doSleep_ = false; clock_gettime( CLOCK_MONOTONIC, then ); } while ( i32(SDES_CSR_IDX) & SDES_CSR_BSY ) { wait(); } tdo = i32( SDES_TDO_IDX ); tdo >>= (32 - nbits); return tdo; } void JtagDriverTmemFifo::init() { reset(); JtagDriverAxisToJtag::init(); // have now the target word size -- verify: if ( getWordSize() != wrdSiz_ ) { throw std::runtime_error("ERROR: firmware misconfigured -- FIFO word size /= JTAG stream word size"); } } unsigned long JtagDriverTmemFifo::getMaxVectorSize() { return maxVec_; } int JtagDriverTmemFifo::xfer( uint8_t *txb, unsigned txBytes, uint8_t *hdbuf, unsigned hsize, uint8_t *rxb, unsigned size ) { if ( bitBang_ || useSdes_ ) { return xferSdes( txb, txBytes, hdbuf, hsize, rxb, size ); } else { return xferFifo( txb, txBytes, hdbuf, hsize, rxb, size ); } } int JtagDriverTmemFifo::xferFifo( uint8_t *txb, unsigned txBytes, uint8_t *hdbuf, unsigned hsize, uint8_t *rxb, unsigned size ) { unsigned txWords = (txBytes + 3)/4; uint32_t lastBytes = txBytes - 4*(txWords - 1); unsigned i; unsigned got, min, minw, rem; uint32_t w; uint32_t csr; if ( hsize % 4 != 0 ) { throw std::runtime_error("AXIS2TMEM FIFO only supports word-lengths that are a multiple of 4"); } if ( lastBytes ) { txWords--; } for ( i=0; i<txWords; i++ ) { memcpy( &w, &txb[4*i], 4 ); o32( FIFO_DAT_IDX, __builtin_bswap32( w ) ); } if ( lastBytes ) { w = 0; memcpy( &w, &txb[4*i], lastBytes ); o32( FIFO_DAT_IDX, __builtin_bswap32( w ) ); } o32( FIFO_CSR_IDX, i32( FIFO_CSR_IDX ) | FIFO_CSR_EOFO ); while ( ( (csr = i32( FIFO_CSR_IDX )) & FIFO_CSR_EMPI ) ) { wait(); } got = ( (csr >> FIFO_CSR_NWRDS) & FIFO_CSR_NWRDM ) * wrdSiz_; if ( 0 == got ) { throw ProtoErr("Didn't receive enough data for header"); } for ( i=0; i<hsize; i+= 4 ) { w = i32( FIFO_DAT_IDX ); if ( got < 4 ) { throw ProtoErr("Didn't receive enough data for header"); } w = __builtin_bswap32( w ); memcpy( hdbuf + i, &w, 4 ); got -= 4; } min = got; if ( size < min ) { min = size; } minw = min/4; for ( i=0; i<4*minw; i+=4 ) { w = i32( FIFO_DAT_IDX ); w = __builtin_bswap32( w ); memcpy( &rxb[i], &w, 4 ); } if ( (rem = (min - i)) ) { w = i32( FIFO_DAT_IDX ); w = __builtin_bswap32( w ); memcpy( &rxb[i], &w, rem ); i += 4; } /* Discard excess */ while ( i < got ) { i32( FIFO_DAT_IDX ); i += 4; } if ( drEn_ && 0 == ((++drop_) & 0xff) ) { fprintf(stderr, "Drop\n"); fflush(stderr); throw TimeoutErr(); } return min; } int JtagDriverTmemFifo::xferSdes( uint8_t *txb, unsigned txBytes, uint8_t *hdbuf, unsigned hsize, uint8_t *rxb, unsigned size ) { Header hdr; unsigned nbits, l, lb; uint8_t *pi, *po; int min; unsigned nbytes; unsigned nwords; unsigned wsz = hsize; uint32_t tms, tdi, tdo; struct timespec then, now; /* This firmware does not expect a stream in our usual format, so we must handle the header here */ pi = txb; po = rxb; /* Header is in little-endian format */ hdr = getHdr( txb ); pi += wsz; if ( getVrs(hdr) != PVER0 ) { throw std::runtime_error("AxiDbgBridgeIP driver: xfer() found unexpected version"); } if ( hsize != sizeof(uint32_t) ) { throw std::runtime_error("AxiDbgBridgeIP driver: xfer() found unexpected header size"); } switch ( getCmd(hdr) ) { case CMD_S: /* normal/main case */ break; case CMD_Q: hdr = mkQueryReply( PVER0, sizeof(uint32_t), 0, UNKNOWN_PERIOD ); setHdr( hdbuf, hdr ); po += sizeof(hdr); return sizeof(uint32_t); default: printf("%08x\n", (unsigned long)hdr); throw std::runtime_error("AxiDbgBridgeIP driver: xfer() found unexpected command"); } if ( wsz != sizeof(tms) ) { throw std::runtime_error("AXI-DebugBridge IP only supports word-lengths of 4"); } nbits = getLen( hdr ); nbytes = (nbits + 7)/8; nwords = (nbytes + wsz - 1)/wsz; if ( txBytes < nwords * 2 * wsz ) { throw std::runtime_error("AXI-DebugBridge IP: not enough input data"); } if ( size < nbytes ) { throw std::runtime_error("AXI-DebugBridge IP: output buffer too small"); } setHdr( hdbuf, hdr ); lb = sizeof(tms); l = 8*lb; while ( nbits > 0 ) { tms = getw32( pi ); pi += sizeof(tms); tdi = getw32( pi ); pi += sizeof(tms); if (nbits < 8*sizeof(tms)) { l = nbits; lb = (l + 7)/8; } tdo = bitBang_ ? xfer32bb( tms, tdi, l ) : xfer32sdes( tms, tdi, l, &then ); setw32( po, tdo, lb ); po += lb; if ( measure_ ) { unsigned long diffNs, diffUs; clock_gettime( CLOCK_MONOTONIC, &now ); diffNs = (now.tv_sec - then.tv_sec ) * 1000000000UL; diffNs += (now.tv_nsec - then.tv_nsec); if ( diffNs >= MIN_SLEEP_NS ) { pollTime_.tv_sec = 0; pollTime_.tv_nsec = diffNs; measure_ = 0; doSleep_ = true; } else { measure_--; } diffUs = diffNs/1000UL; if ( diffUs > maxPollDelayUs_ ) { maxPollDelayUs_ = diffUs; if ( getDebug() ) { printf("axiDebugBridgeIP Driver max poll delay %lu us so far...\n", maxPollDelayUs_); } } } nbits -= l; } return nbytes; } void JtagDriverTmemFifo::usage() { printf(" Axi Stream <-> TMEM Fifo Driver options: [-i]\n"); printf(" -t <aspace>:<base_address>, e.g., -t USER2:0x200000\n"); printf(" -i <irq_file_name> , e.g., -i /dev/toscauserevent1.13 (defaults to polled mode)\n"); printf(" -b use bit-bang interface (for debugging)\n"); printf(" -l use bit-bang interface and log BSCAN signals\n"); } static DriverRegistrar<JtagDriverTmemFifo> r("tmem");
24.308411
123
0.599846
68d06c4cee3563eb2780bc7480f894d15594a007
1,066
hpp
C++
src/ipc/ipc.hpp
imaphatduc/Hypr
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
[ "BSD-3-Clause" ]
277
2021-11-19T20:15:18.000Z
2022-03-29T12:07:59.000Z
src/ipc/ipc.hpp
imaphatduc/Hypr
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
[ "BSD-3-Clause" ]
46
2021-11-21T10:25:58.000Z
2022-03-23T15:04:51.000Z
src/ipc/ipc.hpp
imaphatduc/Hypr
1528659eebf2f41fcfde6ab514a956f5dd51cdfc
[ "BSD-3-Clause" ]
28
2021-12-07T02:49:16.000Z
2022-03-22T05:26:07.000Z
#pragma once #include "../defines.hpp" std::string readFromIPCChannel(const std::string); int writeToIPCChannel(const std::string, std::string); #define IPC_END_OF_FILE (std::string)"HYPR_END_OF_FILE" #define IPC_MESSAGE_SEPARATOR std::string("\t") #define IPC_MESSAGE_EQUALITY std::string("=") struct SIPCMessageMainToBar { std::vector<int> openWorkspaces; uint64_t activeWorkspace; std::string lastWindowName; std::string lastWindowClass; bool fullscreenOnBar; }; struct SIPCMessageBarToMain { uint64_t windowID; }; struct SIPCPipe { std::string szPipeName = ""; uint64_t iPipeFD = 0; }; // /tmp/ is RAM so the speeds will be decent, if anyone wants to implement // actual pipes feel free. void IPCSendMessage(const std::string, SIPCMessageMainToBar); void IPCSendMessage(const std::string, SIPCMessageBarToMain); void IPCRecieveMessageB(const std::string); void IPCRecieveMessageM(const std::string);
31.352941
74
0.666979
68d34d564ceb53f0ebc5b1a17bfa5928436ccd5e
2,009
cpp
C++
Engine/Model.cpp
kristofe/VolumeRenderer
653976ef8c80d05fd1059ebc0b3d3542649879fc
[ "MIT" ]
null
null
null
Engine/Model.cpp
kristofe/VolumeRenderer
653976ef8c80d05fd1059ebc0b3d3542649879fc
[ "MIT" ]
null
null
null
Engine/Model.cpp
kristofe/VolumeRenderer
653976ef8c80d05fd1059ebc0b3d3542649879fc
[ "MIT" ]
null
null
null
/* * Model.cpp * XPlatformGL * * Created by Kristofer Schlachter on 1/2/09. * Copyright 2009 __MyCompanyName__. All rights reserved. * */ #include "Model.h" #include "Platform.h" #include "Globals.h" #include "Mesh.h" #include <stdlib.h> //#include <stdio.h> #include <math.h> //////////////////////////////////////////////////////////////////////////////// Model::Model(){ mRendererMesh = 0; // mDisplayModel = NULL; // mChangeBufferModel = NULL; // mUpdatesArePending = false; } //////////////////////////////////////////////////////////////////////////////// /* Model::Model(Mesh* md){ Model::Model(); mDisplayModel = md; } //////////////////////////////////////////////////////////////////////////////// Model::~Model() { SAFE_DELETE(mDisplayModel); SAFE_DELETE(mChangeBufferModel); Threading::MutexDestroy(mMutex); } //////////////////////////////////////////////////////////////////////////////// void Model::Update(Mesh* updatedModel){ Threading::MutexLock(mMutex); mUpdatesArePending = true; mChangeBufferModel = updatedModel; Threading::MutexUnlock(mMutex); }; //////////////////////////////////////////////////////////////////////////////// void Model::ForceSyncOfModelData(){ Threading::MutexLock(mMutex); if(mUpdatesArePending){ SyncModelData(); mUpdatesArePending = false; } Threading::MutexUnlock(mMutex); } //////////////////////////////////////////////////////////////////////////////// void Model::SyncModelData(){ if(mChangeBufferModel == NULL) return; Threading::MutexLock(mMutex); if(mDisplayModel == NULL){ mDisplayModel = new Mesh(); } mDisplayModel->Sync(mChangeBufferModel); mChangeBufferModel->SetDirtyFlags(MESH_STATE_CLEAN); mDisplayModel->SetDirtyFlags(MESH_STATE_CLEAN); Threading::MutexUnlock(mMutex); } //////////////////////////////////////////////////////////////////////////////// bool Model::HasPendingUpdates(){ Threading::MutexLock(mMutex); return mUpdatesArePending; Threading::MutexUnlock(mMutex); } */
22.573034
80
0.520159
68d4601f864810d0ecc2a731fa03496616a82c2b
8,737
hpp
C++
include/metrics/pu_encode_data.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/metrics/pu_encode_data.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/metrics/pu_encode_data.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_METRICS_PU_ENCODE_DATA_HPP #define PIC_METRICS_PU_ENCODE_DATA_HPP #include <math.h> #include "../base.hpp" #include "../image.hpp" #include "../util/array.hpp" namespace pic { float C_PU_x[256] = { -5.000000f, -4.882784f, -4.765568f, -4.706960f, -4.648352f, -4.589744f, -4.531136f, -4.472527f, -4.413919f, -4.355311f, -4.296703f, -4.238095f, -4.179487f, -4.120879f, -4.062271f, -4.003663f, -3.945055f, -3.886447f, -3.827839f, -3.769231f, -3.710623f, -3.652015f, -3.593407f, -3.534799f, -3.476190f, -3.417582f, -3.358974f, -3.300366f, -3.241758f, -3.183150f, -3.124542f, -3.065934f, -3.007326f, -2.948718f, -2.890110f, -2.831502f, -2.772894f, -2.743590f, -2.714286f, -2.684982f, -2.655678f, -2.626374f, -2.597070f, -2.567766f, -2.538462f, -2.509158f, -2.479853f, -2.450549f, -2.421245f, -2.391941f, -2.362637f, -2.333333f, -2.304029f, -2.274725f, -2.245421f, -2.216117f, -2.186813f, -2.157509f, -2.128205f, -2.098901f, -2.069597f, -2.040293f, -2.010989f, -1.981685f, -1.952381f, -1.923077f, -1.893773f, -1.864469f, -1.835165f, -1.805861f, -1.776557f, -1.747253f, -1.717949f, -1.688645f, -1.659341f, -1.630037f, -1.600733f, -1.571429f, -1.542125f, -1.512821f, -1.483516f, -1.454212f, -1.424908f, -1.395604f, -1.366300f, -1.336996f, -1.307692f, -1.278388f, -1.249084f, -1.219780f, -1.190476f, -1.161172f, -1.131868f, -1.102564f, -1.073260f, -1.043956f, -1.014652f, -0.985348f, -0.956044f, -0.926740f, -0.897436f, -0.868132f, -0.838828f, -0.809524f, -0.780220f, -0.750916f, -0.736264f, -0.721612f, -0.706960f, -0.692308f, -0.677656f, -0.663004f, -0.648352f, -0.633700f, -0.619048f, -0.604396f, -0.589744f, -0.575092f, -0.560440f, -0.545788f, -0.531136f, -0.516484f, -0.501832f, -0.487179f, -0.472527f, -0.457875f, -0.443223f, -0.428571f, -0.413919f, -0.399267f, -0.384615f, -0.369963f, -0.355311f, -0.340659f, -0.326007f, -0.311355f, -0.296703f, -0.282051f, -0.267399f, -0.252747f, -0.238095f, -0.223443f, -0.208791f, -0.194139f, -0.179487f, -0.164835f, -0.150183f, -0.135531f, -0.120879f, -0.106227f, -0.091575f, -0.076923f, -0.062271f, -0.047619f, -0.032967f, -0.018315f, -0.003663f, 0.010989f, 0.025641f, 0.040293f, 0.054945f, 0.069597f, 0.084249f, 0.098901f, 0.113553f, 0.128205f, 0.142857f, 0.157509f, 0.172161f, 0.186813f, 0.201465f, 0.216117f, 0.230769f, 0.245421f, 0.267399f, 0.285714f, 0.300366f, 0.315018f, 0.329670f, 0.344322f, 0.358974f, 0.373626f, 0.388278f, 0.402930f, 0.417582f, 0.432234f, 0.446886f, 0.461538f, 0.476190f, 0.490842f, 0.505495f, 0.520147f, 0.534799f, 0.549451f, 0.564103f, 0.578755f, 0.593407f, 0.608059f, 0.622711f, 0.637363f, 0.652015f, 0.666667f, 0.681319f, 0.695971f, 0.710623f, 0.725275f, 0.739927f, 0.754579f, 0.769231f, 0.783883f, 0.798535f, 0.813187f, 0.827839f, 0.842491f, 0.857143f, 0.871795f, 0.886447f, 0.915751f, 0.945055f, 0.974359f, 1.003663f, 1.032967f, 1.062271f, 1.091575f, 1.120879f, 1.150183f, 1.179487f, 1.208791f, 1.238095f, 1.267399f, 1.296703f, 1.326007f, 1.355311f, 1.384615f, 1.413919f, 1.443223f, 1.472527f, 1.501832f, 1.531136f, 1.589744f, 1.648352f, 1.706960f, 1.765568f, 1.824176f, 1.882784f, 1.930403f, 2.007326f, 2.095238f, 2.186813f, 2.307692f, 2.399267f, 2.567766f, 2.725275f, 2.871795f, 3.260073f, 10.000000f }; float C_PU_y[256] = { 0.000000f, 0.025875f, 0.055091f, 0.071086f, 0.088082f, 0.106142f, 0.125333f, 0.145726f, 0.167397f, 0.190424f, 0.214893f, 0.240894f, 0.268524f, 0.297884f, 0.329082f, 0.362234f, 0.397462f, 0.434897f, 0.474675f, 0.516944f, 0.561860f, 0.609589f, 0.660307f, 0.714201f, 0.771470f, 0.832325f, 0.896991f, 0.965706f, 1.038724f, 1.116315f, 1.198765f, 1.286377f, 1.379476f, 1.478406f, 1.583530f, 1.695237f, 1.813939f, 1.876050f, 1.940075f, 2.006075f, 2.074110f, 2.144242f, 2.216537f, 2.291062f, 2.367884f, 2.447076f, 2.528709f, 2.612859f, 2.699604f, 2.789024f, 2.881201f, 2.976220f, 3.074169f, 3.175139f, 3.279222f, 3.386514f, 3.497114f, 3.611125f, 3.728651f, 3.849802f, 3.974687f, 4.103424f, 4.236130f, 4.372927f, 4.513943f, 4.659307f, 4.809153f, 4.963618f, 5.122847f, 5.286985f, 5.456184f, 5.630599f, 5.810392f, 5.995728f, 6.186778f, 6.383718f, 6.586730f, 6.796000f, 7.011722f, 7.234093f, 7.463319f, 7.699611f, 7.943187f, 8.194270f, 8.453091f, 8.719889f, 8.994909f, 9.278403f, 9.570633f, 9.871866f, 10.182379f, 10.502456f, 10.832392f, 11.172488f, 11.523055f, 11.884415f, 12.256896f, 12.640840f, 13.036596f, 13.444523f, 13.864993f, 14.298387f, 14.745097f, 15.205526f, 15.680088f, 16.169211f, 16.419369f, 16.673331f, 16.931156f, 17.192899f, 17.458619f, 17.728376f, 18.002228f, 18.280235f, 18.562459f, 18.848962f, 19.139806f, 19.435055f, 19.734773f, 20.039023f, 20.347873f, 20.661388f, 20.979636f, 21.302683f, 21.630599f, 21.963452f, 22.301312f, 22.644250f, 22.992336f, 23.345643f, 23.704242f, 24.068207f, 24.437610f, 24.812526f, 25.193029f, 25.579193f, 25.971094f, 26.368808f, 26.772409f, 27.181974f, 27.597580f, 28.019302f, 28.447218f, 28.881403f, 29.321934f, 29.768887f, 30.222337f, 30.682362f, 31.149035f, 31.622432f, 32.102627f, 32.589692f, 33.083700f, 33.584723f, 34.092830f, 34.608091f, 35.130574f, 35.660343f, 36.197464f, 36.741998f, 37.294006f, 37.853546f, 38.420673f, 38.995440f, 39.577897f, 40.168091f, 40.766065f, 41.371860f, 41.985513f, 42.607056f, 43.236517f, 43.873922f, 44.519290f, 45.172636f, 46.167636f, 47.010542f, 47.693856f, 48.385150f, 49.084410f, 49.791614f, 50.506734f, 51.229738f, 51.960586f, 52.699233f, 53.445627f, 54.199709f, 54.961417f, 55.730679f, 56.507418f, 57.291553f, 58.082994f, 58.881648f, 59.687414f, 60.500187f, 61.319857f, 62.146308f, 62.979420f, 63.819070f, 64.665127f, 65.517461f, 66.375935f, 67.240411f, 68.110747f, 68.986801f, 69.868426f, 70.755476f, 71.647801f, 72.545254f, 73.447684f, 74.354943f, 75.266880f, 76.183346f, 77.104195f, 78.029279f, 78.958452f, 79.891572f, 80.828498f, 82.713208f, 84.611499f, 86.522330f, 88.444709f, 90.377696f, 92.320405f, 94.272002f, 96.231710f, 98.198806f, 100.172619f, 102.152530f, 104.137968f, 106.128409f, 108.123375f, 110.122427f, 112.125165f, 114.131226f, 116.140281f, 118.152030f, 120.166201f, 122.182551f, 124.200857f, 128.242559f, 132.289936f, 136.341877f, 140.397483f, 144.456030f, 148.516935f, 151.817830f, 157.152166f, 163.251012f, 169.605996f, 177.996740f, 184.354479f, 196.054275f, 206.992126f, 217.167385f, 244.132872f, 712.224440f }; } // end namespace pic #endif /* PIC_METRICS_PU_ENCODE_DATA_HPP */
15.856624
67
0.550418
68d512e62f9c1e8496242c297e03eb8efe4f94de
1,478
cpp
C++
src/environment/model/ModelContainer.cpp
tobiaskohlbau/IPPP
91432f00b49ea5a83648e3294ad5b4b661dcd284
[ "Apache-2.0" ]
null
null
null
src/environment/model/ModelContainer.cpp
tobiaskohlbau/IPPP
91432f00b49ea5a83648e3294ad5b4b661dcd284
[ "Apache-2.0" ]
null
null
null
src/environment/model/ModelContainer.cpp
tobiaskohlbau/IPPP
91432f00b49ea5a83648e3294ad5b4b661dcd284
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------// // // Copyright 2017 Sascha Kaden // // 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 <ippp/util/Logging.h> #include <ippp/environment/model/ModelContainer.h> namespace ippp { /*! * \brief Standard destructor of the ModelContainer * \author Sascha Kaden * \date 2017-02-19 */ ModelContainer::~ModelContainer() = default; /*! * \brief Standard constructor of ModelContainer * \author Sascha Kaden * \date 2017-02-19 */ ModelContainer::ModelContainer(const std::string &name, const AABB &boundingBox) : Identifier(name) { m_mesh.aabb = boundingBox; } /*! * \brief Return AABB of the model. * \param[out] AABB * \author Sascha Kaden * \date 2017-02-19 */ AABB ModelContainer::getAABB() const { return m_mesh.aabb; } } /* namespace ippp */
28.980392
101
0.621786
68d6a5ca027ce4152a2eb01862726e28dd603b9c
19,968
hpp
C++
atto/atto/math/geometry/algebra.hpp
ubikoo/libfish
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
[ "MIT" ]
null
null
null
atto/atto/math/geometry/algebra.hpp
ubikoo/libfish
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
[ "MIT" ]
null
null
null
atto/atto/math/geometry/algebra.hpp
ubikoo/libfish
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
[ "MIT" ]
null
null
null
/* * algebra.hpp * * Copyright (c) 2020 Carlos Braga * * This program is free software; you can redistribute it and/or modify * it under the terms of the MIT License. * * See accompanying LICENSE.md or https://opensource.org/licenses/MIT. */ #ifndef ATTO_MATH_GEOMETRY_ALGEBRA_H_ #define ATTO_MATH_GEOMETRY_ALGEBRA_H_ #include "atto/math/geometry/vec2.hpp" #include "atto/math/geometry/vec3.hpp" #include "atto/math/geometry/vec4.hpp" #include "atto/math/geometry/mat2.hpp" #include "atto/math/geometry/mat3.hpp" #include "atto/math/geometry/mat4.hpp" namespace atto { namespace math { /** --------------------------------------------------------------------------- * dot * @brief Return the 2-dimensional dot product. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml */ template<typename Type> core_inline Type dot(const vec2<Type> &a, const vec2<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a(0) * b(0) + a(1) * b(1)); } template<typename Type> core_inline vec2<Type> dot(const mat2<Type> &a, const vec2<Type> &v) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec2<Type>( a(0,0) * v(0) + a(0,1) * v(1), a(1,0) * v(0) + a(1,1) * v(1)); } template<typename Type> core_inline mat2<Type> dot(const mat2<Type> &a, const mat2<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat2<Type>( a(0,0) * b(0,0) + a(0,1) * b(1,0), a(0,0) * b(0,1) + a(0,1) * b(1,1), a(1,0) * b(0,0) + a(1,1) * b(1,0), a(1,0) * b(0,1) + a(1,1) * b(1,1)); } /** * dot * @brief Return the 3-dimensional dot product. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml */ template<typename Type> core_inline Type dot(const vec3<Type> &a, const vec3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a(0) * b(0) + a(1) * b(1) + a(2) * b(2)); } template<typename Type> core_inline vec3<Type> dot(const mat3<Type> &a, const vec3<Type> &v) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec3<Type>( a(0,0) * v(0) + a(0,1) * v(1) + a(0,2) * v(2), a(1,0) * v(0) + a(1,1) * v(1) + a(1,2) * v(2), a(2,0) * v(0) + a(2,1) * v(1) + a(2,2) * v(2)); } template<typename Type> core_inline mat3<Type> dot(const mat3<Type> &a, const mat3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat3<Type>( a(0,0) * b(0,0) + a(0,1) * b(1,0) + a(0,2) * b(2,0), a(0,0) * b(0,1) + a(0,1) * b(1,1) + a(0,2) * b(2,1), a(0,0) * b(0,2) + a(0,1) * b(1,2) + a(0,2) * b(2,2), a(1,0) * b(0,0) + a(1,1) * b(1,0) + a(1,2) * b(2,0), a(1,0) * b(0,1) + a(1,1) * b(1,1) + a(1,2) * b(2,1), a(1,0) * b(0,2) + a(1,1) * b(1,2) + a(1,2) * b(2,2), a(2,0) * b(0,0) + a(2,1) * b(1,0) + a(2,2) * b(2,0), a(2,0) * b(0,1) + a(2,1) * b(1,1) + a(2,2) * b(2,1), a(2,0) * b(0,2) + a(2,1) * b(1,2) + a(2,2) * b(2,2)); } /** * dot * @brief Return the 4-dimensional dot product. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml */ template<typename Type> core_inline Type dot(const vec4<Type> &a, const vec4<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a(0) * b(0) + a(1) * b(1) + a(2) * b(2) + a(3) * b(3)); } template<typename Type> core_inline vec4<Type> dot(const mat4<Type> &a, const vec4<Type> &v) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec4<Type>( a(0,0) * v(0) + a(0,1) * v(1) + a(0,2) * v(2) + a(0,3) * v(3), a(1,0) * v(0) + a(1,1) * v(1) + a(1,2) * v(2) + a(1,3) * v(3), a(2,0) * v(0) + a(2,1) * v(1) + a(2,2) * v(2) + a(2,3) * v(3), a(3,0) * v(0) + a(3,1) * v(1) + a(3,2) * v(2) + a(3,3) * v(3)); } template<typename Type> core_inline mat4<Type> dot(const mat4<Type> &a, const mat4<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat4<Type>( a(0,0) * b(0,0) + a(0,1) * b(1,0) + a(0,2) * b(2,0) + a(0,3) * b(3,0), a(0,0) * b(0,1) + a(0,1) * b(1,1) + a(0,2) * b(2,1) + a(0,3) * b(3,1), a(0,0) * b(0,2) + a(0,1) * b(1,2) + a(0,2) * b(2,2) + a(0,3) * b(3,2), a(0,0) * b(0,3) + a(0,1) * b(1,3) + a(0,2) * b(2,3) + a(0,3) * b(3,3), a(1,0) * b(0,0) + a(1,1) * b(1,0) + a(1,2) * b(2,0) + a(1,3) * b(3,0), a(1,0) * b(0,1) + a(1,1) * b(1,1) + a(1,2) * b(2,1) + a(1,3) * b(3,1), a(1,0) * b(0,2) + a(1,1) * b(1,2) + a(1,2) * b(2,2) + a(1,3) * b(3,2), a(1,0) * b(0,3) + a(1,1) * b(1,3) + a(1,2) * b(2,3) + a(1,3) * b(3,3), a(2,0) * b(0,0) + a(2,1) * b(1,0) + a(2,2) * b(2,0) + a(2,3) * b(3,0), a(2,0) * b(0,1) + a(2,1) * b(1,1) + a(2,2) * b(2,1) + a(2,3) * b(3,1), a(2,0) * b(0,2) + a(2,1) * b(1,2) + a(2,2) * b(2,2) + a(2,3) * b(3,2), a(2,0) * b(0,3) + a(2,1) * b(1,3) + a(2,2) * b(2,3) + a(2,3) * b(3,3), a(3,0) * b(0,0) + a(3,1) * b(1,0) + a(3,2) * b(2,0) + a(3,3) * b(3,0), a(3,0) * b(0,1) + a(3,1) * b(1,1) + a(3,2) * b(2,1) + a(3,3) * b(3,1), a(3,0) * b(0,2) + a(3,1) * b(1,2) + a(3,2) * b(2,2) + a(3,3) * b(3,2), a(3,0) * b(0,3) + a(3,1) * b(1,3) + a(3,2) * b(2,3) + a(3,3) * b(3,3)); } /** --------------------------------------------------------------------------- * norm * @brief Return the norm product of two vectors. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/length.xhtml */ template<typename Type> core_inline Type norm(const vec2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return std::sqrt(dot(a,a)); } template<typename Type> core_inline Type norm(const vec3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return std::sqrt(dot(a,a)); } template<typename Type> core_inline Type norm(const vec4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return std::sqrt(dot(a,a)); } /** --------------------------------------------------------------------------- * normalize * @brief Return the normalize product of two vectors. * @see * https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/normalize.xhtml */ template<typename Type> core_inline vec2<Type> normalize(const vec2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a / norm(a)); } template<typename Type> core_inline vec3<Type> normalize(const vec3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a / norm(a)); } template<typename Type> core_inline vec4<Type> normalize(const vec4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a / norm(a)); } /** --------------------------------------------------------------------------- * distance * @brief Return the distance product of two vectors. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/distance.xhtml */ template<typename Type> core_inline Type distance(const vec2<Type> &a, const vec2<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return norm(a-b); } template<typename Type> core_inline Type distance(const vec3<Type> &a, const vec3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return norm(a-b); } template<typename Type> core_inline Type distance(const vec4<Type> &a, const vec4<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return norm(a-b); } /** --------------------------------------------------------------------------- * cross * @brief Return the cross product of two vectors. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/cross.xhtml */ template<typename Type> core_inline vec3<Type> cross(const vec3<Type> &a, const vec3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec3<Type>( a(1)*b(2) - a(2)*b(1), a(2)*b(0) - a(0)*b(2), a(0)*b(1) - a(1)*b(0)); } /** --------------------------------------------------------------------------- * transpose * @brief Return the transpose of the matrix. */ template<typename Type> core_inline mat2<Type> transpose(const mat2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat2<Type>( a(0,0), a(1,0), a(0,1), a(1,1)); } template<typename Type> core_inline mat3<Type> transpose(const mat3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat3<Type>( a(0,0), a(1,0), a(2,0), a(0,1), a(1,1), a(2,1), a(0,2), a(1,2), a(2,2)); } template<typename Type> core_inline mat4<Type> transpose(const mat4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat4<Type>( a(0,0), a(1,0), a(2,0), a(3,0), a(0,1), a(1,1), a(2,1), a(3,1), a(0,2), a(1,2), a(2,2), a(3,2), a(0,3), a(1,3), a(2,3), a(3,3)); } /** --------------------------------------------------------------------------- * determinant * @brief Return the determinant of the matrix. */ template<typename Type> core_inline Type determinant(const mat2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * M = {m0, m1, * m2, m3} * * det(M) = +m0 * m3 * -m1 * m2 */ Type det = a(0,0)*a(1,1) - a(0,1)*a(1,0); return det; } template<typename Type> core_inline Type determinant(const mat3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * M = {m0, m1, m2, * m3, m4, m5, * m6, m7, m8} * * det(M) = +m0 * m4 * m8 * -m0 * m5 * m7 * -m1 * m3 * m8 * +m1 * m5 * m6 * +m2 * m3 * m7 * -m2 * m4 * m6 */ Type minor0 = a(1,1)*a(2,2) - a(1,2)*a(2,1); Type minor1 = a(1,2)*a(2,0) - a(1,0)*a(2,2); Type minor2 = a(1,0)*a(2,1) - a(1,1)*a(2,0); Type det = a(0,0)*minor0 + a(0,1)*minor1 + a(0,2)*minor2; return det; } template<typename Type> core_inline Type determinant(const mat4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * M = {m0, m1, m2, m3, * m4, m5, m6, m7, * m8, m9, m10, m11, * m12, m13, m14, m15} * * det(M) = -m0 * m10 * m13 * m7 * +m0 * m10 * m15 * m5 * +m0 * m11 * m13 * m6 * -m0 * m11 * m14 * m5 * +m0 * m14 * m7 * m9 * -m0 * m15 * m6 * m9 * +m1 * m10 * m12 * m7 * -m1 * m10 * m15 * m4 * -m1 * m11 * m12 * m6 * +m1 * m11 * m14 * m4 * -m1 * m14 * m7 * m8 * +m1 * m15 * m6 * m8 * -m10 * m12 * m3 * m5 * +m10 * m13 * m3 * m4 * +m11 * m12 * m2 * m5 * -m11 * m13 * m2 * m4 * -m12 * m2 * m7 * m9 * +m12 * m3 * m6 * m9 * +m13 * m2 * m7 * m8 * -m13 * m3 * m6 * m8 * -m14 * m3 * m4 * m9 * +m14 * m3 * m5 * m8 * +m15 * m2 * m4 * m9 * -m15 * m2 * m5 * m8 */ Type minor0 = a(2,2)*a(3,3) - a(2,3)*a(3,2); Type minor1 = a(2,3)*a(3,1) - a(2,1)*a(3,3); Type minor2 = a(2,1)*a(3,2) - a(2,2)*a(3,1); Type minor3 = a(2,3)*a(3,2) - a(2,2)*a(3,3); Type minor4 = a(2,0)*a(3,3) - a(2,3)*a(3,0); Type minor5 = a(2,2)*a(3,0) - a(2,0)*a(3,2); Type minor6 = a(2,1)*a(3,3) - a(2,3)*a(3,1); Type minor7 = a(2,3)*a(3,0) - a(2,0)*a(3,3); Type minor8 = a(2,0)*a(3,1) - a(2,1)*a(3,0); Type minor9 = a(2,2)*a(3,1) - a(2,1)*a(3,2); Type minor10 = a(2,0)*a(3,2) - a(2,2)*a(3,0); Type minor11 = a(2,1)*a(3,0) - a(2,0)*a(3,1); Type det = a(0,0) * (a(1,1) * minor0 + a(1,2) * minor1 + a(1,3) * minor2) + a(0,1) * (a(1,0) * minor3 + a(1,2) * minor4 + a(1,3) * minor5) + a(0,2) * (a(1,0) * minor6 + a(1,1) * minor7 + a(1,3) * minor8) + a(0,3) * (a(1,0) * minor9 + a(1,1) * minor10 + a(1,2) * minor11); return det; } /** --------------------------------------------------------------------------- * inverse * @brief Return the inverse of the matrix. */ template<typename Type> core_inline mat2<Type> inverse(const mat2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * Compute the inverse matrix from the corresponding adjugate: * inv(M) = adj(M) / det(M) * adj(M) = { m3, -m1, * -m2, m0} */ mat2<Type> adj( a(1,1), -a(0,1), -a(1,0), a(0,0)); /* Compute determinant from Laplace's expansion */ double det = a(0,0) * adj(0,0) + a(0,1) * adj(1,0); det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0; return (adj *= det); } template<typename Type> core_inline mat3<Type> inverse(const mat3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * Compute the inverse matrix from the corresponding adjugate: * inv(M) = adj(M) / det(M) * adj(M) = {+m4*m8 - m5*m7, * +m2*m7 - m1*m8, * +m1*m5 - m2*m4 * +m5*m6 - m3*m8, * +m0*m8 - m2*m6, * +m2*m3 - m0*m5, * +m3*m7 - m4*m6, * +m1*m6 - m0*m7, * +m0*m4 - m1*m3} */ mat3<Type> adj( a(1,1) * a(2,2) - a(1,2) * a(2,1), a(0,2) * a(2,1) - a(0,1) * a(2,2), a(0,1) * a(1,2) - a(0,2) * a(1,1), a(1,2) * a(2,0) - a(1,0) * a(2,2), a(0,0) * a(2,2) - a(0,2) * a(2,0), a(0,2) * a(1,0) - a(0,0) * a(1,2), a(1,0) * a(2,1) - a(1,1) * a(2,0), a(0,1) * a(2,0) - a(0,0) * a(2,1), a(0,0) * a(1,1) - a(0,1) * a(1,0)); /* Compute determinant from Laplace's expansion */ double det = a(0,0) * adj(0,0) + a(0,1) * adj(1,0) + a(0,2) * adj(2,0); det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0; return (adj *= det); } template<typename Type> core_inline mat4<Type> inverse(const mat4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * Compute the inverse matrix from the corresponding adjugate: * inv(M) = adj(M) / det(M) * adj(M) = * { * -m11*m14*m5 +m10*m15*m5 +m11*m13*m6 * -m10*m13*m7 -m15*m6 *m9 +m14*m7 *m9, * * +m1 *m11*m14 -m3 *m9 *m14 -m1 *m10*m15 * -m11*m13*m2 +m10*m13*m3 +m15*m2 *m9, * * -m15*m2 *m5 +m14*m3 *m5 +m1 *m15*m6 * -m13*m3 *m6 -m1 *m14*m7 +m13*m2 *m7, * * +m11*m2 *m5 -m10*m3 *m5 -m1 *m11*m6 * +m1 *m10*m7 +m3 *m6 *m9 -m2 *m7 *m9, * * +m11*m14*m4 -m10*m15*m4 -m11*m12*m6 * +m10*m12*m7 +m15*m6 *m8 -m14*m7 *m8, * * -m0 *m11*m14 +m3 *m8 *m14 +m0 *m10*m15 * +m11*m12*m2 -m10*m12*m3 -m15*m2 *m8, * * +m15*m2 *m4 -m14*m3 *m4 -m0 *m15*m6 * +m12*m3 *m6 +m0 *m14*m7 -m12*m2 *m7, * * -m11*m2 *m4 +m10*m3 *m4 +m0 *m11*m6 * -m0 *m10*m7 -m3 *m6 *m8 +m2 *m7 *m8, * * -m11*m13*m4 +m15*m9 *m4 +m11*m12*m5 * -m15*m5 *m8 +m13*m7 *m8 -m12*m7 *m9, * * -m1 *m11*m12 +m3 *m9 *m12 +m0 *m11*m13 * +m1 *m15*m8 -m13*m3 *m8 -m0 *m15*m9, * * -m1 *m15*m4 +m13*m3 *m4 +m0 *m15*m5 * -m12*m3 *m5 +m1 *m12*m7 -m0 *m13*m7, * * +m1 *m11*m4 -m3 *m9 *m4 -m0 *m11*m5 * +m3 *m5 *m8 -m1 *m7 *m8 +m0 *m7 *m9, * * +m10*m13*m4 -m14*m9 *m4 -m10*m12*m5 * +m14*m5 *m8 -m13*m6 *m8 +m12*m6 *m9, * * +m1 *m10*m12 -m2 *m9 *m12 -m0 *m10*m13 * -m1 *m14*m8 +m13*m2 *m8 +m0 *m14*m9, * * +m1 *m14*m4 -m13*m2 *m4 -m0 *m14*m5 * +m12*m2 *m5 -m1 *m12*m6 +m0 *m13*m6, * * -m1 *m10*m4 +m2 *m9 *m4 +m0 *m10*m5 * -m2 *m5 *m8 +m1 *m6 *m8 -m0 *m6 *m9 * } */ mat4<Type> adj( a(1,1) * (a(2,2) * a(3,3) - a(2,3) * a(3,2)) + a(1,2) * (a(2,3) * a(3,1) - a(2,1) * a(3,3)) + a(1,3) * (a(2,1) * a(3,2) - a(2,2) * a(3,1)), a(0,1) * (a(2,3) * a(3,2) - a(2,2) * a(3,3)) + a(0,2) * (a(2,1) * a(3,3) - a(2,3) * a(3,1)) + a(0,3) * (a(2,2) * a(3,1) - a(2,1) * a(3,2)), a(1,1) * (a(0,3) * a(3,2) - a(0,2) * a(3,3)) + a(1,2) * (a(0,1) * a(3,3) - a(0,3) * a(3,1)) + a(1,3) * (a(0,2) * a(3,1) - a(0,1) * a(3,2)), a(1,1) * (a(0,2) * a(2,3) - a(2,2) * a(0,3)) + a(1,2) * (a(0,3) * a(2,1) - a(0,1) * a(2,3)) + a(1,3) * (a(0,1) * a(2,2) - a(0,2) * a(2,1)), a(1,0) * (a(2,3) * a(3,2) - a(2,2) * a(3,3)) + a(1,2) * (a(2,0) * a(3,3) - a(2,3) * a(3,0)) + a(1,3) * (a(2,2) * a(3,0) - a(2,0) * a(3,2)), a(0,0) * (a(2,2) * a(3,3) - a(2,3) * a(3,2)) + a(0,2) * (a(2,3) * a(3,0) - a(2,0) * a(3,3)) + a(0,3) * (a(2,0) * a(3,2) - a(2,2) * a(3,0)), a(0,0) * (a(1,3) * a(3,2) - a(1,2) * a(3,3)) + a(0,2) * (a(1,0) * a(3,3) - a(1,3) * a(3,0)) + a(0,3) * (a(1,2) * a(3,0) - a(1,0) * a(3,2)), a(0,0) * (a(1,2) * a(2,3) - a(1,3) * a(2,2)) + a(0,2) * (a(1,3) * a(2,0) - a(1,0) * a(2,3)) + a(0,3) * (a(1,0) * a(2,2) - a(1,2) * a(2,0)), a(1,0) * (a(2,1) * a(3,3) - a(2,3) * a(3,1)) + a(1,1) * (a(2,3) * a(3,0) - a(2,0) * a(3,3)) + a(1,3) * (a(2,0) * a(3,1) - a(2,1) * a(3,0)), a(0,0) * (a(2,3) * a(3,1) - a(2,1) * a(3,3)) + a(0,1) * (a(2,0) * a(3,3) - a(2,3) * a(3,0)) + a(0,3) * (a(2,1) * a(3,0) - a(2,0) * a(3,1)), a(0,0) * (a(1,1) * a(3,3) - a(1,3) * a(3,1)) + a(0,1) * (a(1,3) * a(3,0) - a(1,0) * a(3,3)) + a(0,3) * (a(1,0) * a(3,1) - a(1,1) * a(3,0)), a(0,0) * (a(1,3) * a(2,1) - a(1,1) * a(2,3)) + a(0,1) * (a(1,0) * a(2,3) - a(1,3) * a(2,0)) + a(0,3) * (a(1,1) * a(2,0) - a(2,1) * a(1,0)), a(1,0) * (a(2,2) * a(3,1) - a(2,1) * a(3,2)) + a(1,1) * (a(2,0) * a(3,2) - a(2,2) * a(3,0)) + a(1,2) * (a(2,1) * a(3,0) - a(2,0) * a(3,1)), a(0,0) * (a(2,1) * a(3,2) - a(2,2) * a(3,1)) + a(0,1) * (a(2,2) * a(3,0) - a(2,0) * a(3,2)) + a(0,2) * (a(2,0) * a(3,1) - a(2,1) * a(3,0)), a(0,0) * (a(1,2) * a(3,1) - a(1,1) * a(3,2)) + a(0,1) * (a(1,0) * a(3,2) - a(1,2) * a(3,0)) + a(0,2) * (a(1,1) * a(3,0) - a(1,0) * a(3,1)), a(0,0) * (a(1,1) * a(2,2) - a(1,2) * a(2,1)) + a(0,1) * (a(1,2) * a(2,0) - a(1,0) * a(2,2)) + a(0,2) * (a(1,0) * a(2,1) - a(1,1) * a(2,0))); /* Compute inverse matrix using Laplace's expansion */ double det = a(0,0) * adj(0,0) + a(0,1) * adj(1,0) + a(0,2) * adj(2,0) + a(0,3) * adj(3,0); det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0; return (adj *= det); } } /* namespace math */ } /* namespace atto */ /** --------------------------------------------------------------------------- * @brief Enable simd vectorized instructions. */ #ifdef ATTO_MATH_SIMD #include "atto/math/geometry/algebra-simd.hpp" #endif #endif /* ATTO_MATH_GEOMETRY_ALGEBRA */
31.796178
80
0.455629
68d7c6a7182e36cfd4e148b2297d38ea46c3c128
3,313
cpp
C++
src/SceneMonitor.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2021-12-17T17:35:07.000Z
2022-01-11T12:38:00.000Z
src/SceneMonitor.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
null
null
null
src/SceneMonitor.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2018-01-15T06:10:07.000Z
2021-07-08T19:40:49.000Z
/* * SceneMonitor.cpp * * Created on: Jul 27, 2015 * Author: richard * * Copyright 2017 Richard Stilborn * Licensed under the MIT License */ #include "SceneMonitor.h" #include <boost/asio/io_service.hpp> #include <boost/bind/bind.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/ptr_container/detail/associative_ptr_container.hpp> #include <boost/ptr_container/detail/reversible_ptr_container.hpp> #include <boost/ptr_container/ptr_map_adapter.hpp> #include <boost/thread/lock_guard.hpp> #include <iostream> #include <list> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include "GUI/GUI_Interface.h" SceneMonitor::SceneMonitor(boost::asio::io_service& io_service, GUI_Interface& gui) : io_service_(io_service), gui_(gui), scenes_(), scenes_mtx_() { // gui_.createRoom("cameras", boost::bind<const std::string>(&SceneMonitor::get_scene_names, this)); } SceneMonitor::~SceneMonitor() { boost::lock_guard<boost::mutex> guard(scenes_mtx_); for (boost::ptr_map<std::string, Scene>::iterator it = scenes_.begin(); it != scenes_.end(); ++it) scenes_.erase(it); } void SceneMonitor::start_monitoring(const std::string& name, const std::string& url, const double realtime_factor) { // Check if we already have this name boost::ptr_map<std::string, Scene>::iterator it = scenes_.find(name); if (it != this->scenes_.end()) throw std::invalid_argument("A scene with this name already exists: " + name); // Create the scene { Scene* scene = new Scene(name, url, io_service_, gui_, realtime_factor); boost::lock_guard<boost::mutex> guard(scenes_mtx_); // TODO(richard): Fix this silliness! std::string foo(name); this->scenes_.insert(foo, scene); } } void SceneMonitor::stop_monitoring(const std::string& name) { std::cout << "SceneMonitor.stopMonitoring() - enter" << std::endl; boost::ptr_map<std::string, Scene>::iterator it = scenes_.find(name); if (it != this->scenes_.end()) { boost::lock_guard<boost::mutex> guard(scenes_mtx_); it->second->shutdown(); } } void SceneMonitor::stop_all_monitoring() { std::cout << "SceneMonitor.stopAllMonitoring() - enter" << std::endl; for (auto scene : this->scenes_) scene.second->shutdown(); std::this_thread::sleep_for(std::chrono::seconds(2)); } const std::string SceneMonitor::get_scene_names() const { std::stringstream list; const char* separator = ""; list << '['; for (auto name : this->scenes_) { list << separator << name.first; separator = ","; } list << ']'; return list.str(); } // std::vector<scene_details> SceneMonitor::getSceneDetails(){ // std::vector<scene_details> details; // for(auto entry: this->scenes){ // scene_details detail; // detail.name = entry.second->getName(); // detail.height = entry.second->getCamera().getHeight(); // detail.width = entry.second->getCamera().getWidth(); // details.push_back(detail); // } // return details; //} void SceneMonitor::toggle_pause() { for (auto scene : this->scenes_) scene.second->toggle_pause(); } void SceneMonitor::set_realtime_factor(const double realtime_factor) { for (auto scene : this->scenes_) scene.second->set_realtime_factor(realtime_factor); }
29.061404
116
0.686991
68d9deed1f22ec03ee368305b88181ee84a5347d
1,854
cpp
C++
m4cpp/src/uart.cpp
matheusmb/smep-gateway
c32ff83cf48488404a5c094137b33be09d84581c
[ "MIT" ]
null
null
null
m4cpp/src/uart.cpp
matheusmb/smep-gateway
c32ff83cf48488404a5c094137b33be09d84581c
[ "MIT" ]
null
null
null
m4cpp/src/uart.cpp
matheusmb/smep-gateway
c32ff83cf48488404a5c094137b33be09d84581c
[ "MIT" ]
null
null
null
#include "uart.h" #include "board.h" #include "WString.h" #define UARTx_IRQn USART0_IRQn void UART_Init( const uint32_t baud ) { Board_UART_Init( LPC_UART ); Chip_UART_Init( LPC_UART ); Chip_UART_SetBaud( LPC_UART, baud ); Chip_UART_TXEnable( LPC_UART ); } void UART_IRQ_Init() { UART_IntEnable(); Chip_UART_SetupFIFOS( LPC_UART, UART_FCR_FIFO_EN | UART_FCR_TRG_LEV2 | UART_FCR_RX_RS ); NVIC_SetPriority(UARTx_IRQn, 1); NVIC_EnableIRQ(UARTx_IRQn); } void UART_IntEnable() { Chip_UART_IntEnable( LPC_UART, (UART_IER_RBRINT | UART_IER_RLSINT) ); } void UART_IntDisable() { Chip_UART_IntDisable( LPC_UART, (UART_IER_RBRINT | UART_IER_RLSINT) ); } void UART_Send(const void * data, int numBytes ) { Chip_UART_SendBlocking( LPC_UART, data, numBytes ); } void UART_Send( String cmd ) { UART_Send( cmd.c_str(), cmd.length() ); } uint8_t UART_Read() { return Chip_UART_ReadByte( LPC_UART ); } bool UART_Available() { return Chip_UART_ReadLineStatus( LPC_UART ) & UART_LSR_RDR; } #define MAX_BUFFER_SIZE 1500 String receiveBuffer; void UARTx_IRQHandler(void) { String out; uint32_t IIR = LPC_UART->IIR & UART_IIR_BITMASK; uint32_t INTID = IIR & UART_IIR_INTID_MASK; uint32_t LSR = 0; bool recv = false; switch(INTID) { case UART_IIR_INTID_CTI: case UART_IIR_INTID_RDA: recv = true; if( receiveBuffer.length() > MAX_BUFFER_SIZE ) receiveBuffer = receiveBuffer.substring( MAX_BUFFER_SIZE / 2); // Discard half of the contents while( UART_Available() ) { receiveBuffer += (char) UART_Read(); } break; case UART_IIR_INTID_RLS: LSR = Chip_UART_ReadLineStatus(LPC_UART) & UART_LSR_BITMASK; // Clear RLS interrupt printf("RLS %d", LSR); break; default: printf("Unkown %d", INTID); } /*if( recv ) { printf("UART_IRQ:"); printf( receiveBuffer ); receiveBuffer = ""; }*/ }
20.373626
98
0.718986
68da56c8bbc6797e2daedc237bef5589843c7f6e
328
cpp
C++
SPiCall/example.cpp
MoePus/SPiCall
4b0331d6ec456aff55b0b6080246d917ead900c3
[ "MIT" ]
15
2020-10-14T06:22:19.000Z
2022-03-12T00:59:03.000Z
SPiCall/example.cpp
c3358/SPiCall
4b0331d6ec456aff55b0b6080246d917ead900c3
[ "MIT" ]
null
null
null
SPiCall/example.cpp
c3358/SPiCall
4b0331d6ec456aff55b0b6080246d917ead900c3
[ "MIT" ]
9
2020-07-29T12:37:50.000Z
2021-08-16T13:57:07.000Z
#include <iostream> #include "SPiCall/SPiCall.h" int main() { SPiCall::init(); #ifdef _MSC_VER const auto funcNameHash = SPiCall::syscall::fnv1a_32("NtTerminateProcess"); SPiCall::syscall::nt_syscall(funcNameHash, ~0, 0); #else SPiCall::syscall::nt_syscall("NtTerminateProcess", ~0, 0); #endif return 0; }
21.866667
79
0.692073
68dadb09346cfe63541bc35f3e22509be8a45b89
1,970
cpp
C++
llarp/service/info.cpp
KeeJef/loki-network
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
[ "Zlib" ]
null
null
null
llarp/service/info.cpp
KeeJef/loki-network
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
[ "Zlib" ]
null
null
null
llarp/service/info.cpp
KeeJef/loki-network
f5dbbaf832d11b88d351e3de7ab584465a28f6bf
[ "Zlib" ]
null
null
null
#include <buffer.hpp> #include <service/Info.hpp> #include <service/address.hpp> #include <cassert> #include <sodium/crypto_generichash.h> namespace llarp { namespace service { bool ServiceInfo::DecodeKey(llarp_buffer_t key, llarp_buffer_t* val) { bool read = false; if(!BEncodeMaybeReadDictEntry("e", enckey, read, key, val)) return false; if(!BEncodeMaybeReadDictEntry("s", signkey, read, key, val)) return false; if(!BEncodeMaybeReadDictInt("v", version, read, key, val)) return false; if(!BEncodeMaybeReadDictEntry("x", vanity, read, key, val)) return false; return read; } bool ServiceInfo::BEncode(llarp_buffer_t* buf) const { if(!bencode_start_dict(buf)) return false; if(!BEncodeWriteDictEntry("e", enckey, buf)) return false; if(!BEncodeWriteDictEntry("s", signkey, buf)) return false; if(!BEncodeWriteDictInt("v", LLARP_PROTO_VERSION, buf)) return false; if(!vanity.IsZero()) { if(!BEncodeWriteDictEntry("x", vanity, buf)) return false; } return bencode_end(buf); } std::string ServiceInfo::Name() const { if(m_CachedAddr.IsZero()) { Address addr; CalculateAddress(addr.data()); return addr.ToString(); } return m_CachedAddr.ToString(); } bool ServiceInfo::CalculateAddress(std::array< byte_t, 32 >& data) const { byte_t tmp[256] = {0}; auto buf = llarp::StackBuffer< decltype(tmp) >(tmp); if(!BEncode(&buf)) return false; return crypto_generichash_blake2b(data.data(), data.size(), buf.base, buf.cur - buf.base, nullptr, 0) != -1; } bool ServiceInfo::UpdateAddr() { return CalculateAddress(m_CachedAddr.data()); } } // namespace service } // namespace llarp
25.25641
76
0.591371
68dd0fd03a89896af9cefc24fd2642e92fc94ade
22,627
cpp
C++
framework/areg/component/private/ComponentLoader.cpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
framework/areg/component/private/ComponentLoader.cpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
framework/areg/component/private/ComponentLoader.cpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
/************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/component/private/ComponentLoader.cpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform, Component Loader singleton object. * ************************************************************************/ #include "areg/component/ComponentLoader.hpp" #include "areg/component/Component.hpp" #include "areg/component/ComponentThread.hpp" #include "areg/component/private/ServiceManager.hpp" #include "areg/base/NECommon.hpp" ////////////////////////////////////////////////////////////////////////// // ModelDataCreator class implementation ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // ModelDataCreator class, constructor / destructor ////////////////////////////////////////////////////////////////////////// ModelDataCreator::ModelDataCreator( FuncInitLoaderItem funtCreateModelData, const char * modelName ) { ASSERT( funtCreateModelData != nullptr ); NERegistry::Model newModel = funtCreateModelData(modelName); VERIFY( ComponentLoader::getInstance().addModel( newModel ) ); } ModelDataCreator::ModelDataCreator( const NERegistry::Model & newModel ) { VERIFY( ComponentLoader::getInstance().addModel( newModel ) ); } ////////////////////////////////////////////////////////////////////////// // ComponentLoader class implementation ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // ComponentLoader class, static functions ////////////////////////////////////////////////////////////////////////// ComponentLoader & ComponentLoader::getInstance( void ) { static ComponentLoader _componentLoader; return _componentLoader; } bool ComponentLoader::loadComponentModel( const char * modelName /*= nullptr*/ ) { bool result = ComponentLoader::getInstance().loadModel( modelName ); if ( result == false) ComponentLoader::getInstance().unloadModel( modelName ); return result; } void ComponentLoader::unloadComponentModel( const char * modelName /*= nullptr*/ ) { ComponentLoader::getInstance( ).unloadModel( modelName ); } const NERegistry::ComponentList& ComponentLoader::getComponentList( const char* threadName ) { const NERegistry::ComponentList* result = nullptr; ComponentLoader& loader = getInstance(); Lock lock(loader.mLock); for ( int i = 0; result == nullptr && i < loader.mModelList.getSize(); ++ i ) { const NERegistry::Model & model = loader.mModelList.getAt(i); if ( model.isModelLoaded() ) { const NERegistry::ComponentThreadList & threadList = model.getThreadList(); for ( int j = 0; result == nullptr && j < threadList.getSize(); ++ j ) { const NERegistry::ComponentThreadEntry & thrEntry = threadList.getAt(j); if (thrEntry.mThreadName == threadName) result = &thrEntry.mComponents; } } } return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_LIST); } const NERegistry::ComponentEntry& ComponentLoader::findComponentEntry( const char* roleName, const char* threadName ) { const NERegistry::ComponentEntry* result = nullptr; const NERegistry::ComponentList& comList = getComponentList(threadName); if (comList.isValid()) { for (int i = 0; result == nullptr && i < comList.getSize(); ++ i) { const NERegistry::ComponentEntry& entry = comList[i]; result = entry.mRoleName == roleName ? &entry : nullptr; } } return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_ENTRY); } const NERegistry::ComponentEntry& ComponentLoader::findComponentEntry( const char* roleName ) { const NERegistry::ComponentEntry* result = nullptr; ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock(loader.mLock); for ( int i = 0; result == nullptr && i < loader.mModelList.getSize(); ++ i ) { const NERegistry::ComponentThreadList & threadList = loader.mModelList.getAt(i).getThreadList(); for ( int j = 0; result == nullptr && j < threadList.getSize(); ++ j ) { const NERegistry::ComponentThreadEntry & threadEntry = threadList.getAt(j); for ( int k = 0; result == nullptr && k < threadEntry.mComponents.getSize(); ++ k ) result = threadEntry.mComponents.getAt(k).mRoleName == roleName ? &threadEntry.mComponents.getAt(k) : nullptr; } } return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_ENTRY); } bool ComponentLoader::isModelLoaded( const char * modelName ) { bool result = false; if ( NEString::isEmpty<char>(modelName) == false ) { ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock(loader.mLock); for ( int i = 0; i < loader.mModelList.getSize(); ++ i ) { const NERegistry::Model & model = loader.mModelList.getAt(i); if ( model.getModelName() == modelName ) { result = model.isModelLoaded(); break; } } } return result; } bool ComponentLoader::existModel( const char * modelName ) { bool result = false; if ( NEString::isEmpty<char>( modelName ) == false ) { ComponentLoader & loader = ComponentLoader::getInstance( ); Lock lock( loader.mLock ); for ( int i = 0; i < loader.mModelList.getSize( ); ++ i ) { const NERegistry::Model & model = loader.mModelList.getAt( i ); if ( model.getModelName( ) == modelName ) { result = true; break; } } } return result; } bool ComponentLoader::setComponentData( const char * roleName, NEMemory::uAlign compData ) { bool result = false; ComponentLoader & loader = ComponentLoader::getInstance( ); Lock lock( loader.mLock ); for ( int i = 0; i < loader.mModelList.getSize( ); ++ i ) { NERegistry::Model & model = loader.mModelList.getAt( i ); if ( model.setComponentData( roleName, compData ) ) { result = true; break; } } return result; } bool ComponentLoader::addModelUnique(const NERegistry::Model & newModel) { ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock( loader.mLock ); return loader.addModel(newModel); } void ComponentLoader::removeComponentModel(const char * modelName /*= nullptr */) { OUTPUT_WARN("Removing components and model [ %s ]", modelName != nullptr ? modelName : "ALL MODELS"); ComponentLoader::unloadComponentModel(modelName); ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock( loader.mLock ); if ( NEString::isEmpty<char>(modelName) == false ) { for ( int i = 0; i < loader.mModelList.getSize(); ++ i ) { NERegistry::Model & model = loader.mModelList[i]; if ( model.getModelName() == modelName ) { loader.mModelList.removeAt(i); break; } } } else { loader.mModelList.removeAll(); } } ////////////////////////////////////////////////////////////////////////// // ComponentLoader class, constructor / destructor ////////////////////////////////////////////////////////////////////////// ComponentLoader::ComponentLoader( void ) : mModelList ( ) , mDefaultModel ( NEString::EmptyStringA.data( ) ) , mLock ( ) { } ComponentLoader::~ComponentLoader( void ) { mModelList.removeAll(); mDefaultModel = NEString::EmptyStringA.data( ); } ////////////////////////////////////////////////////////////////////////// // ComponentLoader class, methods ////////////////////////////////////////////////////////////////////////// bool ComponentLoader::addModel( const NERegistry::Model & newModel ) { Lock lock(mLock); OUTPUT_DBG("Registering model with name [ %s ]", newModel.getModelName().getString()); bool hasError = newModel.getModelName().isEmpty() || newModel.isModelLoaded() ? true : false; // the new model name cannot be empty and it should be unique, and it cannot be marked as loaded. ASSERT(hasError == false); // search if model with the same name exists for (int i = 0; hasError == false && i < mModelList.getSize(); ++ i ) { const NERegistry::Model & regModel = mModelList.getAt(i); if ( newModel.getModelName() != regModel.getModelName() ) { const NERegistry::ComponentThreadList & regThreadList = regModel.getThreadList(); for ( int j = 0; hasError == false && j < regThreadList.getSize(); ++ j ) { const NERegistry::ComponentThreadEntry & regThreadEntry = regThreadList.getAt(j); if ( newModel.findThread(regThreadEntry) < 0 ) { const NERegistry::ComponentList & regComponentList = regThreadEntry.mComponents; for ( int k = 0; hasError == false && k < regComponentList.getSize(); ++ k ) { const NERegistry::ComponentEntry & regComponentEntry = regComponentList.getAt(k); if ( newModel.hasRegisteredComponent(regComponentEntry) ) { OUTPUT_ERR("The component with role name [ %s ] is already registered in thread [ %s ] of model [ %s ], cannot add new model!" , regComponentEntry.mRoleName.getString() , regThreadEntry.mThreadName.getString() , regModel.getModelName().getString() ); hasError = true; ASSERT(false); } else { ; // is OK, continue checking } } // end of for ( int k = 0; hasError == false && k < newComponentList.GetSize(); k ++ ) } else { OUTPUT_ERR("The thread with name [ %s ] is already registered in model [ %s ], cannot add new model!" , regThreadEntry.mThreadName.getString() , regModel.getModelName().getString()); hasError = true; ASSERT(false); } } // end of for ( int j = 0; hasError == false && j < newThreadList.GetSize(); j ++ ) } else { OUTPUT_ERR("The model with name [ %s ] is already registered, cannot add new model!", regModel.getModelName().getString()); hasError = true; ASSERT(false); } } if ( hasError == false ) { OUTPUT_DBG("The model [ %s ] is defined correct, adding in the list.", newModel.getModelName().getString()); mModelList.add(newModel); if ( mDefaultModel.isEmpty() ) { mDefaultModel = newModel.getModelName().getString(); } } return (hasError == false); } bool ComponentLoader::loadModel( const char * modelName /*= nullptr*/ ) { Lock lock(mLock); bool result = false; OUTPUT_DBG("Requested to start load model [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName); if ( NEString::isEmpty<char>(modelName) ) { result = mModelList.getSize() > 0; for ( int i = 0; result && i < mModelList.getSize(); ++ i ) { NERegistry::Model & model = mModelList[i]; if ( model.isModelLoaded() == false ) result = loadModel( model ); ASSERT( model.isModelLoaded() ); } } else { OUTPUT_DBG("Searching model [ %s ] in the list with size [ %d ]", modelName, mModelList.getSize() ); int index = -1; for ( int i = 0; (index == -1) && (i < mModelList.getSize()); ++ i ) { NERegistry::Model & model = mModelList[i]; OUTPUT_DBG("Checking the name, the entry [ %d ] has name [ %s ]", i, model.getModelName().getString()); if ( model.getModelName() == modelName ) { OUTPUT_DBG("Found model with name [ %s ] at position [ %d ]", modelName, i); index = i; result = loadModel(model); } } } OUTPUT_DBG("Model [ %s ] loaded with [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName, result ? "SUCCESS" : "ERROR"); return result; } bool ComponentLoader::loadModel( NERegistry::Model & whichModel ) const { bool result = false; if ( whichModel.isValid() && (whichModel.isModelLoaded( ) == false) ) { const NERegistry::ComponentThreadList& thrList = whichModel.getThreadList( ); OUTPUT_DBG( "Starting to load model [ %s ]. There are [ %d ] component threads to start. Component loader is going to load objects and start Service Manager" , whichModel.getModelName( ).getString( ) , thrList.getSize( ) ); whichModel.markModelLoaded( true ); result = true; for ( int i = 0; result && i < thrList.getSize( ); ++ i ) { Lock lock( mLock ); const NERegistry::ComponentThreadEntry& entry = thrList[i]; if ( entry.isValid( ) && Thread::findThreadByName( entry.mThreadName.getString( ) ) == nullptr ) { ComponentThread* thrObject = DEBUG_NEW ComponentThread( entry.mThreadName.getString( ) ); if ( thrObject != nullptr ) { OUTPUT_DBG( "Starting thread [ %s ] and loading components.", thrObject->getName( ).getString( ) ); if ( thrObject->createThread( NECommon::WAIT_INFINITE ) == false ) { OUTPUT_ERR( "Failed to create and start thread [ %s ], going to delete and unload components.", thrObject->getName( ).getString( ) ); thrObject->destroyThread( NECommon::DO_NOT_WAIT ); delete thrObject; result = false; } } else { OUTPUT_ERR( "Failed instantiate component thread object with name [ %s ]", entry.mThreadName.getString( ) ); result = false; } } else { result = entry.isValid( ); OUTPUT_ERR( "Either Thread [ %s ] is already created or it is invalid: is valid [ %s ], already exists [ %s ]." , entry.mThreadName.getString( ) , entry.isValid( ) ? "TRUE" : "FALSE" , Thread::findThreadByName( entry.mThreadName) != nullptr ? "EXISTS" : "DOES NOT EXIST" ); } } } else { OUTPUT_WARN( "The model [ %s ] is already loaded. Ignoring loading model", whichModel.getModelName( ).getString( ) ); result = true; } return result; } void ComponentLoader::unloadModel( const char * modelName /*= nullptr*/ ) { Lock lock(mLock); OUTPUT_DBG("Requested to unload model [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName); if ( NEString::isEmpty<char>(modelName) ) { for ( int i = 0; i < mModelList.getSize(); ++ i ) { NERegistry::Model & model = mModelList[i]; lock.unlock(); unloadModel(model); lock.lock(); ASSERT( model.isModelLoaded() == false ); } } else { int index = -1; for ( int i = 0; index == -1 && i < mModelList.getSize(); ++ i ) { NERegistry::Model & model = mModelList[i]; if ( model.getModelName() == modelName ) { index = i; lock.unlock(); unloadModel(model); lock.lock(); } } } } void ComponentLoader::unloadModel( NERegistry::Model & whichModel ) const { Lock lock(mLock); OUTPUT_WARN("Requested to unload components. Going to unload model [ %s ]!", static_cast<const char *>(whichModel.getModelName().getString())); if (whichModel.isModelLoaded() ) { const NERegistry::ComponentThreadList & threadList = whichModel.getThreadList(); shutdownThreads( threadList ); lock.unlock(); waitThreadsCompletion( threadList ); lock.lock(); destroyThreads( threadList ); whichModel.markModelLoaded( false ); } else { OUTPUT_WARN("The model [ %s ] marked as unloaded. Ignoring request to unload model.", static_cast<const char *>(whichModel.getModelName().getString())); } } void ComponentLoader::shutdownThreads( const NERegistry::ComponentThreadList & whichThreads ) const { OUTPUT_INFO("Starting First Level model shutdown. Shutdown Threads and Components"); for (int i = 0; i < whichThreads.getSize(); ++ i ) { const NERegistry::ComponentThreadEntry& entry = whichThreads[i]; Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString()); if (thrObject != nullptr) { ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr); OUTPUT_WARN("Shutdown thread [ %s ] and all its components", thrObject->getName().getString()); thrObject->shutdownThread(); } else { OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString()); } } OUTPUT_INFO("Shuts down Service Manager thread!"); } void ComponentLoader::waitThreadsCompletion( const NERegistry::ComponentThreadList & whichThreads ) const { OUTPUT_INFO("Starting Second Level model shutdown. Wait for Threads completion!"); for ( int i = 0; i < whichThreads.getSize(); ++ i ) { const NERegistry::ComponentThreadEntry& entry = whichThreads[i]; Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString()); if (thrObject != nullptr) { ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr); OUTPUT_WARN("Waiting thread [ %s ] completion", thrObject->getName().getString()); thrObject->completionWait(NECommon::WAIT_INFINITE); } else { OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString()); } } } void ComponentLoader::destroyThreads( const NERegistry::ComponentThreadList & whichThreads ) const { OUTPUT_INFO("Starting Third Level model shutdown. Destroy threads and components!"); for ( int i = 0; i < whichThreads.getSize(); ++ i ) { const NERegistry::ComponentThreadEntry& entry = whichThreads[i]; Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString()); if (thrObject != nullptr) { ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr); OUTPUT_WARN("Stopping and deleting thread [ %s ] and deleting components", thrObject->getName().getString()); thrObject->destroyThread(NECommon::WAIT_INFINITE); delete thrObject; } else { OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString()); } } } const NERegistry::Model * ComponentLoader::findModelByName( const char * modelName ) const { const NERegistry::Model * result = nullptr; if ( NEString::isEmpty<char>(modelName) == false ) { for ( int i = 0; (result == nullptr) && (i < mModelList.getSize( )); ++i ) { const NERegistry::Model & model = mModelList[i]; result = model.getModelName( ) == modelName ? &model : nullptr; } } return result; } const NERegistry::ComponentThreadEntry * ComponentLoader::findThreadEntryByName( const char * threadName ) const { const NERegistry::ComponentThreadEntry * result = nullptr; if ( NEString::isEmpty<char>(threadName) == false ) { for ( int i = 0; (result == nullptr) && (i < mModelList.getSize()); ++i ) { const NERegistry::Model & model = mModelList[i]; int index = model.findThread(threadName); if ( index != NECommon::INVALID_INDEX ) { const NERegistry::ComponentThreadEntry & entry = model.getThreadList().getAt(index); result = &entry; } } } return result; } const NERegistry::ComponentEntry * ComponentLoader::findComponentEntryByName( const char * roleName ) const { const NERegistry::ComponentEntry * result = nullptr; if ( NEString::isEmpty<char>(roleName) == false ) { for ( int i = 0; (result == nullptr) && (i < mModelList.getSize()); ++i ) { const NERegistry::Model & model = mModelList[i]; const NERegistry::ComponentThreadList & threadList= model.getThreadList(); for ( int j = 0; (result == nullptr) && (i < threadList.getSize()); ++i ) { const NERegistry::ComponentThreadEntry & thread = threadList.getAt(j); int index = thread.findComponentEntry(roleName); if ( index != NECommon::INVALID_INDEX ) { const NERegistry::ComponentEntry & entry = thread.mComponents.getAt(index); result = & entry; } } } } return result; }
38.878007
165
0.557431
68e3ef0f200b918d322171a0dec5379e2df62dde
18,478
hpp
C++
third_party/omr/compiler/x/codegen/OMRRegisterDependency.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/compiler/x/codegen/OMRRegisterDependency.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/compiler/x/codegen/OMRRegisterDependency.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2000, 2019 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #ifndef OMR_X86_REGISTER_DEPENDENCY_INCL #define OMR_X86_REGISTER_DEPENDENCY_INCL /* * The following #define and typedef must appear before any #includes in this file */ #ifndef OMR_REGISTER_DEPENDENCY_CONNECTOR #define OMR_REGISTER_DEPENDENCY_CONNECTOR namespace OMR { namespace X86 { class RegisterDependencyConditions; } } namespace OMR { typedef OMR::X86::RegisterDependencyConditions RegisterDependencyConditionsConnector; } #else #error OMR::X86::RegisterDependencyConditions expected to be a primary connector, but a OMR connector is already defined #endif #include "compiler/codegen/OMRRegisterDependency.hpp" #include <stddef.h> #include <stdint.h> #include <stdio.h> #include "codegen/CodeGenerator.hpp" #include "codegen/RealRegister.hpp" #include "codegen/Register.hpp" #include "codegen/RegisterConstants.hpp" #include "codegen/RegisterDependencyStruct.hpp" #include "env/TRMemory.hpp" #include "infra/Assert.hpp" namespace TR { class Instruction; } namespace TR { class Node; } namespace TR { class RegisterDependencyConditions; } template <typename ListKind> class List; #define UsesGlobalDependentFPRegister (UsesDependentRegister | GlobalRegisterFPDependency) #define NUM_DEFAULT_DEPENDENCIES 1 typedef uint16_t depsize_t; class TR_X86RegisterDependencyGroup { bool _mayNeedToPopFPRegisters; bool _needToClearFPStack; TR::RegisterDependency _dependencies[NUM_DEFAULT_DEPENDENCIES]; TR_ALLOC_WITHOUT_NEW(TR_Memory::RegisterDependencyGroup) // Use TR_X86RegisterDependencyGroup::create to allocate an object of this type // void * operator new(size_t s, int32_t numDependencies, TR_Memory * m) { TR_ASSERT(numDependencies > 0, "operator new called with numDependencies == 0"); if (numDependencies > NUM_DEFAULT_DEPENDENCIES) { s += (numDependencies-NUM_DEFAULT_DEPENDENCIES)*sizeof(TR::RegisterDependency); } return m->allocateHeapMemory(s); } void operator delete(void *p, int32_t numDependencies, TR_Memory * m) { m->freeMemory(p, TR_AllocationKind::heapAlloc); } public: TR_X86RegisterDependencyGroup() {_mayNeedToPopFPRegisters = false; _needToClearFPStack = false;} static TR_X86RegisterDependencyGroup * create(int32_t numDependencies, TR_Memory * m) { return numDependencies ? new (numDependencies, m) TR_X86RegisterDependencyGroup : 0; } TR::RegisterDependency *getRegisterDependency(TR_X86RegisterDependencyIndex index) { return &_dependencies[index]; } void setDependencyInfo(TR_X86RegisterDependencyIndex index, TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag = UsesDependentRegister, bool isAssocRegDependency = false); TR::RegisterDependency *findDependency(TR::Register *vr, TR_X86RegisterDependencyIndex stop) { TR::RegisterDependency *result = NULL; for (TR_X86RegisterDependencyIndex i=0; !result && (i < stop); i++) if (_dependencies[i].getRegister() == vr) result = _dependencies+i; return result; } TR::RegisterDependency *findDependency(TR::RealRegister::RegNum rr, TR_X86RegisterDependencyIndex stop) { TR::RegisterDependency *result = NULL; for (TR_X86RegisterDependencyIndex i=0; !result && (i < stop); i++) if (_dependencies[i].getRealRegister() == rr) result = _dependencies+i; return result; } void assignRegisters(TR::Instruction *currentInstruction, TR_RegisterKinds kindsToBeAssigned, TR_X86RegisterDependencyIndex numberOfRegisters, TR::CodeGenerator *cg); void assignFPRegisters(TR::Instruction *currentInstruction, TR_RegisterKinds kindsToBeAssigned, TR_X86RegisterDependencyIndex numberOfRegisters, TR::CodeGenerator *cg); void orderGlobalRegsOnFPStack(TR::Instruction *cursor, TR_RegisterKinds kindsToBeAssigned, TR_X86RegisterDependencyIndex numberOfRegisters, List<TR::Register> *poppedRegisters, TR::CodeGenerator *cg); void blockRegisters(TR_X86RegisterDependencyIndex numberOfRegisters) { for (TR_X86RegisterDependencyIndex i = 0; i < numberOfRegisters; i++) { if (_dependencies[i].getRegister()) { _dependencies[i].getRegister()->block(); } } } void unblockRegisters(TR_X86RegisterDependencyIndex numberOfRegisters) { for (uint32_t i = 0; i < numberOfRegisters; i++) { if (_dependencies[i].getRegister()) { _dependencies[i].getRegister()->unblock(); } } } void setMayNeedToPopFPRegisters(bool b) {_mayNeedToPopFPRegisters = b;} bool getMayNeedToPopFPRegisters() {return _mayNeedToPopFPRegisters;} void setNeedToClearFPStack(bool b) {_needToClearFPStack = b;} bool getNeedToClearFPStack() {return _needToClearFPStack;} void blockRealDependencyRegisters(TR_X86RegisterDependencyIndex numberOfRegisters, TR::CodeGenerator *cg); void unblockRealDependencyRegisters(TR_X86RegisterDependencyIndex numberOfRegisters, TR::CodeGenerator *cg); }; namespace OMR { namespace X86 { class RegisterDependencyConditions: public OMR::RegisterDependencyConditions { TR_X86RegisterDependencyGroup *_preConditions; TR_X86RegisterDependencyGroup *_postConditions; TR_X86RegisterDependencyIndex _numPreConditions; TR_X86RegisterDependencyIndex _addCursorForPre; TR_X86RegisterDependencyIndex _numPostConditions; TR_X86RegisterDependencyIndex _addCursorForPost; TR_X86RegisterDependencyIndex unionDependencies(TR_X86RegisterDependencyGroup *deps, TR_X86RegisterDependencyIndex cursor, TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag, bool isAssocRegDependency); TR_X86RegisterDependencyIndex unionRealDependencies(TR_X86RegisterDependencyGroup *deps, TR_X86RegisterDependencyIndex cursor, TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag, bool isAssocRegDependency); public: TR_ALLOC(TR_Memory::RegisterDependencyConditions) RegisterDependencyConditions() : _preConditions(NULL), _postConditions(NULL), _numPreConditions(0), _addCursorForPre(0), _numPostConditions(0), _addCursorForPost(0) {} RegisterDependencyConditions(TR_X86RegisterDependencyIndex numPreConds, TR_X86RegisterDependencyIndex numPostConds, TR_Memory * m) : _preConditions(TR_X86RegisterDependencyGroup::create(numPreConds, m)), _postConditions(TR_X86RegisterDependencyGroup::create(numPostConds, m)), _numPreConditions(numPreConds), _addCursorForPre(0), _numPostConditions(numPostConds), _addCursorForPost(0) {} RegisterDependencyConditions(TR::Node *node, TR::CodeGenerator *cg, TR_X86RegisterDependencyIndex additionalRegDeps = 0, List<TR::Register> * = 0); void unionNoRegPostCondition(TR::Register *reg, TR::CodeGenerator *cg); TR::RegisterDependencyConditions *clone(TR::CodeGenerator *cg, TR_X86RegisterDependencyIndex additionalRegDeps = 0); TR_X86RegisterDependencyGroup *getPreConditions() {return _preConditions;} void setMayNeedToPopFPRegisters(bool b) { if (_preConditions) _preConditions->setMayNeedToPopFPRegisters(b); if (_postConditions) _postConditions->setMayNeedToPopFPRegisters(b); } void setNeedToClearFPStack(bool b) { if (_preConditions) _preConditions->setNeedToClearFPStack(b); else { if (_postConditions) _postConditions->setNeedToClearFPStack(b); } } TR_X86RegisterDependencyIndex getNumPreConditions() {return _numPreConditions;} TR_X86RegisterDependencyIndex setNumPreConditions(TR_X86RegisterDependencyIndex n, TR_Memory * m) { if (_preConditions == NULL) { _preConditions = TR_X86RegisterDependencyGroup::create(n, m); } return (_numPreConditions = n); } TR_X86RegisterDependencyIndex getNumPostConditions() {return _numPostConditions;} TR_X86RegisterDependencyIndex setNumPostConditions(TR_X86RegisterDependencyIndex n, TR_Memory * m) { if (_postConditions == NULL) { _postConditions = TR_X86RegisterDependencyGroup::create(n, m); } return (_numPostConditions = n); } TR_X86RegisterDependencyIndex getAddCursorForPre() {return _addCursorForPre;} TR_X86RegisterDependencyIndex setAddCursorForPre(TR_X86RegisterDependencyIndex a) {return (_addCursorForPre = a);} TR_X86RegisterDependencyIndex getAddCursorForPost() {return _addCursorForPost;} TR_X86RegisterDependencyIndex setAddCursorForPost(TR_X86RegisterDependencyIndex a) {return (_addCursorForPost = a);} void addPreCondition(TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag = UsesDependentRegister, bool isAssocRegDependency = false) { TR_X86RegisterDependencyIndex newCursor = unionRealDependencies(_preConditions, _addCursorForPre, vr, rr, cg, flag, isAssocRegDependency); TR_ASSERT(newCursor <= _numPreConditions, "Too many dependencies"); if (newCursor == _addCursorForPre) _numPreConditions--; // A vmThread/ebp dependency was displaced, so there is now one less condition. else _addCursorForPre = newCursor; } void unionPreCondition(TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag = UsesDependentRegister, bool isAssocRegDependency = false) { TR_X86RegisterDependencyIndex newCursor = unionDependencies(_preConditions, _addCursorForPre, vr, rr, cg, flag, isAssocRegDependency); TR_ASSERT(newCursor <= _numPreConditions, "Too many dependencies"); if (newCursor == _addCursorForPre) _numPreConditions--; // A union occurred, so there is now one less condition else _addCursorForPre = newCursor; } TR_X86RegisterDependencyGroup *getPostConditions() {return _postConditions;} void addPostCondition(TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag = UsesDependentRegister, bool isAssocRegDependency = false) { TR_X86RegisterDependencyIndex newCursor = unionRealDependencies(_postConditions, _addCursorForPost, vr, rr, cg, flag, isAssocRegDependency); TR_ASSERT(newCursor <= _numPostConditions, "Too many dependencies"); if (newCursor == _addCursorForPost) _numPostConditions--; // A vmThread/ebp dependency was displaced, so there is now one less condition. else _addCursorForPost = newCursor; } void unionPostCondition(TR::Register *vr, TR::RealRegister::RegNum rr, TR::CodeGenerator *cg, uint8_t flag = UsesDependentRegister, bool isAssocRegDependency = false) { TR_X86RegisterDependencyIndex newCursor = unionDependencies(_postConditions, _addCursorForPost, vr, rr, cg, flag, isAssocRegDependency); TR_ASSERT(newCursor <= _numPostConditions, "Too many dependencies"); if (newCursor == _addCursorForPost) _numPostConditions--; // A union occurred, so there is now one less condition else _addCursorForPost = newCursor; } TR::RegisterDependency *findPreCondition (TR::Register *vr){ return _preConditions ->findDependency(vr, _addCursorForPre ); } TR::RegisterDependency *findPostCondition(TR::Register *vr){ return _postConditions->findDependency(vr, _addCursorForPost); } TR::RegisterDependency *findPreCondition (TR::RealRegister::RegNum rr){ return _preConditions ->findDependency(rr, _addCursorForPre ); } TR::RegisterDependency *findPostCondition(TR::RealRegister::RegNum rr){ return _postConditions->findDependency(rr, _addCursorForPost); } void assignPreConditionRegisters(TR::Instruction *currentInstruction, TR_RegisterKinds kindsToBeAssigned, TR::CodeGenerator *cg) { if (_preConditions != NULL) { if ((kindsToBeAssigned & TR_X87_Mask)) { _preConditions->assignFPRegisters(currentInstruction, kindsToBeAssigned, _numPreConditions, cg); } else { cg->clearRegisterAssignmentFlags(); cg->setRegisterAssignmentFlag(TR_PreDependencyCoercion); _preConditions->assignRegisters(currentInstruction, kindsToBeAssigned, _numPreConditions, cg); } } } void assignPostConditionRegisters(TR::Instruction *currentInstruction, TR_RegisterKinds kindsToBeAssigned, TR::CodeGenerator *cg) { if (_postConditions != NULL) { if ((kindsToBeAssigned & TR_X87_Mask)) { _postConditions->assignFPRegisters(currentInstruction, kindsToBeAssigned, _numPostConditions, cg); } else { cg->clearRegisterAssignmentFlags(); cg->setRegisterAssignmentFlag(TR_PostDependencyCoercion); _postConditions->assignRegisters(currentInstruction, kindsToBeAssigned, _numPostConditions, cg); } } } void blockPreConditionRegisters() { _preConditions->blockRegisters(_numPreConditions); } void unblockPreConditionRegisters() { _preConditions->unblockRegisters(_numPreConditions); } void blockPostConditionRegisters() { _postConditions->blockRegisters(_numPostConditions); } void unblockPostConditionRegisters() { _postConditions->unblockRegisters(_numPostConditions); } void blockPostConditionRealDependencyRegisters(TR::CodeGenerator *cg) { _postConditions->blockRealDependencyRegisters(_numPostConditions, cg); } void unblockPostConditionRealDependencyRegisters(TR::CodeGenerator *cg) { _postConditions->unblockRealDependencyRegisters(_numPostConditions, cg); } void blockPreConditionRealDependencyRegisters(TR::CodeGenerator *cg) { _preConditions->blockRealDependencyRegisters(_numPreConditions, cg); } void unblockPreConditionRealDependencyRegisters(TR::CodeGenerator *cg) { _preConditions->unblockRealDependencyRegisters(_numPreConditions, cg); } // All conditions are added - set the number of conditions to be the number // currently added // void stopAddingPreConditions() { _numPreConditions = _addCursorForPre; } void stopAddingPostConditions() { _numPostConditions = _addCursorForPost; } void stopAddingConditions() { stopAddingPreConditions(); stopAddingPostConditions(); } void createRegisterAssociationDirective(TR::Instruction *instruction, TR::CodeGenerator *cg); TR::RealRegister *getRealRegisterFromVirtual(TR::Register *virtReg, TR::CodeGenerator *cg); bool refsRegister(TR::Register *r); bool defsRegister(TR::Register *r); bool usesRegister(TR::Register *r); void useRegisters(TR::Instruction *instr, TR::CodeGenerator *cg); #if defined(DEBUG) || defined(PROD_WITH_ASSUMES) uint32_t numReferencedGPRegisters(TR::CodeGenerator *); uint32_t numReferencedFPRegisters(TR::CodeGenerator *); void printFullRegisterDependencyInfo(FILE *pOutFile); void printDependencyConditions(TR_X86RegisterDependencyGroup *conditions, TR_X86RegisterDependencyIndex numConditions, char *prefix, FILE *pOutFile); #endif }; } } //////////////////////////////////////////////////// // Generate Routines //////////////////////////////////////////////////// TR::RegisterDependencyConditions * generateRegisterDependencyConditions(TR::Node *, TR::CodeGenerator *, TR_X86RegisterDependencyIndex = 0, List<TR::Register> * = 0); TR::RegisterDependencyConditions * generateRegisterDependencyConditions(TR_X86RegisterDependencyIndex, TR_X86RegisterDependencyIndex, TR::CodeGenerator *); #endif
40.700441
241
0.669391
68e7b53a748c7f1204bdbd44a08745d63ee42e9e
4,874
cpp
C++
jit.cpp
c3sr/go-pytorch
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
[ "Apache-2.0" ]
14
2018-11-26T18:33:27.000Z
2021-12-17T11:14:33.000Z
jit.cpp
c3sr/go-pytorch
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
[ "Apache-2.0" ]
7
2019-04-02T16:46:01.000Z
2020-06-10T02:02:33.000Z
jit.cpp
c3sr/go-pytorch
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
[ "Apache-2.0" ]
3
2019-07-16T16:47:07.000Z
2021-12-29T07:47:59.000Z
#ifdef ENABLE_PYTROCH_JIT #include "error.hpp" #include "predictor.hpp" #include <algorithm> #include <iosfwd> #include <iostream> #include <memory> #include <string> #include <typeinfo> #include <utility> #include <vector> extern Torch_IValue Torch_ConvertIValueToTorchIValue(torch::IValue value); struct Torch_JITModule { std::shared_ptr<torch::jit::script::Module> module; }; struct Torch_JITModule_Method { torch::jit::script::Method& run; }; Torch_JITModuleContext Torch_CompileTorchScript(char* cstring_script, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string script(cstring_script); auto mod = new Torch_JITModule(); mod->module = torch::jit::compile(script); return (void*)mod; END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL) } Torch_JITModuleContext Torch_LoadJITModule(char* cstring_path, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string module_path(cstring_path); auto mod = new Torch_JITModule(); mod->module = torch::jit::load(module_path); return (void*)mod; END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL) } void Torch_ExportJITModule(Torch_JITModuleContext ctx, char* cstring_path, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string module_path(cstring_path); auto mod = (Torch_JITModule*)ctx; mod->module->save(module_path); END_HANDLE_TH_ERRORS(Torch_GlobalError, ) } Torch_JITModuleMethodContext Torch_JITModuleGetMethod(Torch_JITModuleContext ctx, char* cstring_method, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string method_name(cstring_method); auto mod = (Torch_JITModule*)ctx; auto met = new Torch_JITModule_Method{mod->module->get_method(method_name)}; return (void*)met; END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL) } char** Torch_JITModuleGetMethodNames(Torch_JITModuleContext ctx, size_t* len) { auto mod = (Torch_JITModule*)ctx; auto size = mod->module->get_methods().size(); *len = size; auto result = (char**)malloc(sizeof(char*) * size); int i = 0; for (auto& method : mod->module->get_methods()) { auto key = method.value()->name(); auto ckey = new char[key.length() + 1]; strcpy(ckey, key.c_str()); *(result + i) = ckey; i++; } return result; } Torch_IValue Torch_JITModuleMethodRun(Torch_JITModuleMethodContext ctx, Torch_IValue* inputs, size_t input_size, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); auto met = (Torch_JITModule_Method*)ctx; std::vector<torch::IValue> inputs_vec; for (int i = 0; i < input_size; i++) { auto ival = *(inputs + i); inputs_vec.push_back(Torch_ConvertTorchIValueToIValue(ival)); } auto res = met->run(inputs_vec); return Torch_ConvertIValueToTorchIValue(res); END_HANDLE_TH_ERRORS(Torch_GlobalError, Torch_IValue{}) } Torch_ModuleMethodArgument* Torch_JITModuleMethodArguments(Torch_JITModuleMethodContext ctx, size_t* res_size) { auto met = (Torch_JITModule_Method*)ctx; auto schema = met->run.getSchema(); auto arguments = schema.arguments(); auto result = (Torch_ModuleMethodArgument*)malloc(sizeof(Torch_ModuleMethodArgument) * arguments.size()); *res_size = arguments.size(); for (std::vector<torch::Argument>::size_type i = 0; i != arguments.size(); i++) { auto name = arguments[i].name(); char* cstr_name = new char[name.length() + 1]; strcpy(cstr_name, name.c_str()); auto type = arguments[i].type()->str(); char* cstr_type = new char[type.length() + 1]; strcpy(cstr_type, type.c_str()); *(result + i) = Torch_ModuleMethodArgument{ .name = cstr_name, .typ = cstr_type, }; } return result; } Torch_ModuleMethodArgument* Torch_JITModuleMethodReturns(Torch_JITModuleMethodContext ctx, size_t* res_size) { auto met = (Torch_JITModule_Method*)ctx; auto schema = met->run.getSchema(); auto arguments = schema.returns(); auto result = (Torch_ModuleMethodArgument*)malloc(sizeof(Torch_ModuleMethodArgument) * arguments.size()); *res_size = arguments.size(); for (std::vector<torch::Argument>::size_type i = 0; i != arguments.size(); i++) { auto name = arguments[i].name(); char* cstr_name = new char[name.length() + 1]; strcpy(cstr_name, name.c_str()); auto type = arguments[i].type()->str(); char* cstr_type = new char[type.length() + 1]; strcpy(cstr_type, type.c_str()); *(result + i) = Torch_ModuleMethodArgument{ .name = cstr_name, .typ = cstr_type, }; } return result; } void Torch_DeleteJITModuleMethod(Torch_JITModuleMethodContext ctx) { auto med = (Torch_JITModule_Method*)ctx; delete med; } void Torch_DeleteJITModule(Torch_JITModuleContext ctx) { auto mod = (Torch_JITModule*)ctx; delete mod; } #endif // ENABLE_PYTROCH_JIT
29.539394
112
0.708863
68eeb54c52b1f098da02acc840a138117e18e72c
2,191
cpp
C++
src/stereo_ugv/image_source.cpp
yunhao-qian/stereo_ugv
23480a8b93918fc2bc44e16416ac0b4e0598788b
[ "BSD-2-Clause" ]
null
null
null
src/stereo_ugv/image_source.cpp
yunhao-qian/stereo_ugv
23480a8b93918fc2bc44e16416ac0b4e0598788b
[ "BSD-2-Clause" ]
null
null
null
src/stereo_ugv/image_source.cpp
yunhao-qian/stereo_ugv
23480a8b93918fc2bc44e16416ac0b4e0598788b
[ "BSD-2-Clause" ]
null
null
null
#include "stereo_ugv/image_source.h" namespace stereo_ugv { /** * @brief Creates an ImageSource. * @details The function determines the concrete subclass of the layout to be created by looking up the "type" key, and * calls the corresponding initialization function. Currently, "camera", "images" and "video" are supported. * @param context The context containing initialization parameters. * @return A unique pointer to the created image source. */ std::unique_ptr<ImageSource> ImageSource::create(const Context& context) { nlohmann::json internal_json; const auto internal_context{ openInternalContext(&internal_json, context) }; std::string type; internal_context.getParameter("type", &type); if (type == "camera") { auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::CAMERA>>() }; initialize(source.get(), internal_context); return source; } if (type == "images") { auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::IMAGES>>() }; initialize(source.get(), internal_context); return source; } if (type == "video") { auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::VIDEO>>() }; initialize(source.get(), internal_context); return source; } throw InvalidParameter{ fmt::format(R"(Unknown ImageSource type "{}")", type) }; } /** * @brief Finds the character device file of a camera device given the prefix of its device name. * @warning This function has not been implemented, and calling it will always cause a RuntimeError. * @param device_name_prefix The prefix of its device name. Due to the limits of the V4L2 API, device names longer than * 31 characters are truncated. Therefore, the length of the given prefix should not be longer than 31 characters. * Otherwise, no matching camera can be found. * @return The full path to the character device file. If multiple matching cameras are detected, the function issues a * warning and returns any one among them. */ std::string findCameraCharacterDeviceFile(const std::string&) { throw RuntimeError{ "This function has not been implemented" }; } } // namespace stereo_ugv
37.135593
119
0.740758
68f10e810d3722fa4aaf268cea3e77e0684a346c
2,325
cpp
C++
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #include "foedus/storage/sequential/sequential_partitioner_impl.hpp" #include <cstring> #include <ostream> namespace foedus { namespace storage { namespace sequential { SequentialPartitioner::SequentialPartitioner(Partitioner* parent) : engine_(parent->get_engine()), id_(parent->get_storage_id()), metadata_(PartitionerMetadata::get_metadata(engine_, id_)) { } ErrorStack SequentialPartitioner::design_partition( const Partitioner::DesignPartitionArguments& /*args*/) { // no data required for SequentialPartitioner metadata_->data_offset_ = 0; metadata_->data_size_ = 0; metadata_->valid_ = true; return kRetOk; } void SequentialPartitioner::partition_batch( const Partitioner::PartitionBatchArguments& args) const { // all local for (uint32_t i = 0; i < args.logs_count_; ++i) { args.results_[i] = args.local_partition_; } } void SequentialPartitioner::sort_batch(const Partitioner::SortBatchArguments& args) const { // no sorting needed. std::memcpy( args.output_buffer_, args.log_positions_, sizeof(snapshot::BufferPosition) * args.logs_count_); *args.written_count_ = args.logs_count_; } std::ostream& operator<<(std::ostream& o, const SequentialPartitioner& /*v*/) { o << "<SequentialPartitioner>" << "</SequentialPartitioner>"; return o; } } // namespace sequential } // namespace storage } // namespace foedus
33.695652
91
0.744946
190387dff2ca8b91b790b2a534eec90c398aa606
3,683
hpp
C++
PhantomEngine/Common/Value.hpp
restary/Phantom
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
[ "MIT" ]
null
null
null
PhantomEngine/Common/Value.hpp
restary/Phantom
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
[ "MIT" ]
null
null
null
PhantomEngine/Common/Value.hpp
restary/Phantom
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <Define.hpp> using namespace std; namespace PhantomEngine { namespace DataTypes { static const uint8_t UNDEFINED = 255; static const uint8_t INTEGER = 0; static const uint8_t FLOAT = 1; static const uint8_t VECTOR2 = 2; static const uint8_t VECTOR3 = 3; static const uint8_t SHORT_STRING = 4; static const uint8_t STRING = 5; static const uint8_t OBJECT = 6; static const uint8_t ARRAY = 7; union DataPointer { void* pointer; uint32_t offset; }; struct Integer { int64_t value; uint8_t reserved[7]; uint8_t type; }; struct Float { float value; uint8_t reserved[11]; uint8_t type; }; struct Vector2 { float x; float y; uint8_t reserved[7]; uint8_t type; }; struct Vector3 { float x; float y; float z; uint8_t reserved[3]; uint8_t type; }; struct ShortString { const static uint32_t MAX_SIZE = 14; char content[MAX_SIZE]; uint8_t length; uint8_t type; }; struct String { DataPointer data; uint32_t size; uint8_t reserved[3]; uint8_t type; }; struct Object { DataPointer data; uint32_t size; uint8_t reserved[3]; uint8_t type; }; struct Array { DataPointer data; uint32_t size; uint8_t reserved[3]; uint8_t type; }; union Data { Integer integer; Float number; Vector2 vector2; Vector3 vector3; ShortString shortString; String string; Object object; Array array; void operator=(int i) { integer.type = INTEGER; integer.value = i; } void operator=(float f) { number.type = FLOAT; number.value = f; } void operator=(Vector2 v2) { vector2 = v2; } void operator=(Vector3 v3) { vector3 = v3; } void operator=(std::string s); uint8_t GetType() { return integer.type; } bool IsReference() { return integer.type > SHORT_STRING; } }; } template<typename T> struct Value { uint8_t GetType() { return DataTypes::UNDEFINED; } }; template<> struct Value<int> { Value() { data = 0; } uint8_t GetType() { return DataTypes::INTEGER; } void operator=(int i) { data = i; } private: DataTypes::Data data; }; template<> struct Value<float> { Value() { data = 0.0f; } uint8_t GetType() { return DataTypes::FLOAT; } void operator=(float f) { data = f; } private: DataTypes::Data data; }; template<> struct Value<string> { Value() { data = ""; } uint8_t GetType() { return DataTypes::FLOAT; } void operator=(string s) { data = s; } private: DataTypes::Data data; }; template<typename T> struct Field { Value<string> name; Value<T> value; Field(std::string fieldName); }; }
23.01875
80
0.472984
1903fb7b9a2da957750f0a1fd043519c6fc9c0b3
8,239
cpp
C++
src/StockExchange/StockExchange.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
17
2018-01-08T13:38:28.000Z
2022-01-21T05:39:26.000Z
src/StockExchange/StockExchange.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
null
null
null
src/StockExchange/StockExchange.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
1
2018-01-08T13:39:00.000Z
2018-01-08T13:39:00.000Z
/* Copyright 2017 - BSD-3-Clause * * Copyright Holder (alphabetical): * * Beikirch, Maximilian * Cramer, Simon * Frank, Martin * Otte, Philipp * Pabich, Emma * Trimborn, Torsten * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * @author Beikirch, Cramer, Pabich * @date 08 Nov 2017 * @brief This file belongs to the SABCEMM projekt. See github.com/SABCEMM/SABCEMM */ #include <cassert> #include <vector> #include "StockExchange.h" #include <cstddef> //for std::size_t #include <algorithm> #include <random> #include <boost/core/ignore_unused.hpp> #include <limits> #include "../DataCollector/DataCollector.h" /** Setter method for the DataCollector composite * \param newDataCollector Pointer to the new DataCollector composite */ void StockExchange::setDataCollector(DataCollector* newDataCollector) { dataCollector = newDataCollector; } /** Setter method for the agents vector * \param newAgents Pointer to the new vector of agents. */ void StockExchange::setAgents(std::vector<Agent*>* newAgents){ agents = newAgents; setNumAgents(); } /** Setter method for the RandomGenerator * \param newRandomGenerator Pointer to a RandomGenerator */ void StockExchange::setRandomGenerator(RandomGenerator* newRandomGenerator) { randomGenerator = newRandomGenerator; } /** Setter method for the PriceCalculator * \param newPriceCalculator Pointer to the PriceCalculator */ void StockExchange::setPriceCalculator(PriceCalculator* newPriceCalculator) { priceCalculator = newPriceCalculator; } /** Setter method for the ExcessDemandCalculator * \param newExcessDemandCalculator Pointer to the ExcessDemandCalculator */ void StockExchange::setExcessDemandCalculator(ExcessDemandCalculator* newExcessDemandCalculator) { excessDemandCalculator = newExcessDemandCalculator; } /** Setter method for the number of agents. The number is not taken as a paramter but from the array of agents. */ void StockExchange::setNumAgents() { if (agents!=nullptr){ numAgents = agents->size(); }else{ numAgents = 0; } } /** StandardConstructor of the StockExchange */ StockExchange::StockExchange(): StockExchange(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) { } /** Constructor of the StockExchange. * \param newDataCollector Pointer to a DataCollector composite * \param newAgents Pointer to a vector of agents * \param newRandomGenerator Pointer to a RandomGenerator * \param newPriceCalculator Pointer to a PriceCalculator * \param newExcessDemandCalculator Pointer to an ExcessDemandCalculator */ StockExchange::StockExchange(DataCollector* newDataCollector, std::vector<Agent*>* newAgents, RandomGenerator* newRandomGenerator, PriceCalculator* newPriceCalculator, ExcessDemandCalculator* newExcessDemandCalculator, ShareCalculator* newShareCalculator, Dividend* newDividend, GlobalNews* newGlobalNews){ numAgents = 0; agents = newAgents; dataCollector = newDataCollector; randomGenerator = newRandomGenerator; priceCalculator = newPriceCalculator; excessDemandCalculator = newExcessDemandCalculator; shareCalculator = newShareCalculator; dividend = newDividend; setNumAgents(); agentIndex.clear(); globalNews = newGlobalNews; } /** Destructor */ StockExchange::~StockExchange() = default; /** Check if the object is fully configured and ready to be used. */ void StockExchange::checkInitilisation() { assert(agents != nullptr); assert(dataCollector != nullptr); assert(randomGenerator != nullptr); assert(priceCalculator != nullptr); assert(excessDemandCalculator != nullptr); assert(numAgents == agents->size()); } void StockExchange::setDividend(Dividend* newDividend){ assert(newDividend != nullptr); dividend = newDividend; } /** Setter method for the GlobalNews container * \param newGlobalNews Pointer to a GlobalNews container */ void StockExchange::setGlobalNews(GlobalNews* newGlobalNews){ this->globalNews = newGlobalNews; } /** PreStep: Execute all calls that are required before a new update of the price and the agents can be triggered. * Generates new GlobalNews. */ void StockExchange::preStep() { assert(priceCalculator != nullptr); if(globalNews!=nullptr){ globalNews->generateNewGlobalNews(); } if(dividend!= nullptr){ dividend->calculateDividend(); } if(excessDemandCalculator != nullptr) excessDemandCalculator->preStepCalculate(); priceCalculator->preStepCalculate(); for (auto &agent : *agents) { agent->preStepUpdate(); } } /** Step: Calculate a new Price and update all agents. * The agents are updated in a random order. */ void StockExchange::step(){ assert(agents!=nullptr); assert(priceCalculator!=nullptr); assert(randomGenerator != nullptr); //Random over all Agents priceCalculator->stepCalculate(); if(agentIndex.size() != agents->size()){ agentIndex.clear(); for(std::size_t j=0;j<agents->size();j++) { agentIndex.push_back(j); } } // shuffling needs to be coupled to the RNG to ensure reproducability for // equal seeds. int seed=0; randomGenerator->getUniformRandomInt(0, std::numeric_limits<int>::max(), &seed); std::mt19937 g(static_cast<unsigned int>(seed)); std::shuffle(agentIndex.begin(),agentIndex.end(),g); for(std::size_t j=0;j<agents->size();j++) { agents->at(agentIndex[j])->stepUpdate(); } } /** PostStep. * Calls the DataCollector. */ void StockExchange::postStep(){ // ED-postInfo (the correction terms for the price) must be available // before price correction. /// @todo this, however, is not general. Can we specify a rule that will /// likely hold for future models? if(excessDemandCalculator != nullptr) excessDemandCalculator->postStepCalculate(); priceCalculator->postStepCalculate(); for (auto &agent : *agents) { agent->postStepUpdate(); } if(shareCalculator != nullptr) shareCalculator->updateShares(); dataCollector->collect(); } StockExchange* StockExchange::factory() { return new StockExchange(); } StockExchange* StockExchange::factory(DataCollector* newDataCollector, std::vector<Agent*>* newAgents, RandomGenerator* newRandomGenerator, PriceCalculator* newPriceCalculator, ExcessDemandCalculator* newExcessDemandCalculator, ShareCalculator* newShareCalculator, Dividend* newDividend, GlobalNews* newGlobalNews) { return new StockExchange(newDataCollector, newAgents, newRandomGenerator, newPriceCalculator, newExcessDemandCalculator, newShareCalculator, newDividend, newGlobalNews); }
28.908772
125
0.73237
1905c4166233cc8b835b80f27c0aa834ce68fb80
933
cpp
C++
src/world/abilities/blink.cpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
7
2015-01-28T09:17:08.000Z
2020-04-21T13:51:16.000Z
src/world/abilities/blink.cpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
null
null
null
src/world/abilities/blink.cpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
1
2020-07-11T09:20:25.000Z
2020-07-11T09:20:25.000Z
#include <world/abilities/blink.hpp> #include <world/works/blink_work.hpp> #include <world/entity.hpp> #include <logging/logging.hpp> #include <memory> using namespace std::chrono_literals; template<> const std::string NamedAbility<Blink>::name = "Blink"; template<> const AbilityType NamedAbility<Blink>::ability_type = AbilityType::Blink; Blink::Blink(): ActiveAbility(TargetType::Point) { log_debug("Creating a blink instance"); this->cooldown.set_max(0s); log_debug(this->cooldown.get_max_in_ticks()); } void Blink::cast(Entity* entity, World* world, const Position& position, const bool queue) { // Check mana, cooldown etc etc log_debug("CASTING blink for entity" << entity->get_id() << " to pos " << position); auto work = std::make_unique<BlinkWork>(world, entity, position); if (queue) entity->queue_work(std::move(work)); else entity->set_work(std::move(work)); this->cooldown.start(); }
25.916667
90
0.719185
19061669c719a818d8563f9c8f75664fb79d9bf7
1,004
hpp
C++
tests/messaging/sock/networkcommon.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
61
2015-01-08T08:05:28.000Z
2022-01-07T16:47:47.000Z
tests/messaging/sock/networkcommon.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
30
2015-04-06T21:41:18.000Z
2021-08-18T13:24:51.000Z
tests/messaging/sock/networkcommon.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
64
2015-02-23T20:01:11.000Z
2022-03-14T13:31:20.000Z
#pragma once #ifndef _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP #define _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP #include <algorithm> #include <random> #include <boost/lexical_cast.hpp> /// @file /// Contains functions and types used by socket tests. /// Precondition: With p = reinterpret_cast<unsigned char*>(t), /// writable_counted_range(p, sizeof(T)) template<typename T> void overwrite(T* t) { auto p = reinterpret_cast<unsigned char*>(t); std::fill(p, p + sizeof(T), '\xFF'); } /// Expects a string with the format: /// error_code: error_message /// where error_code is an integer. inline int code(const std::string& s) { std::string c{begin(s), std::find(begin(s), end(s), ':')}; return boost::lexical_cast<int>(c); } // Distribution D, Generator G, BasicLockable L template<typename D, typename G, typename L> auto syncRand(D& dist, G& gen, L& lockable) -> decltype(dist(gen)) { std::lock_guard<L> lock{lockable}; return dist(gen); } #endif // _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP
26.421053
66
0.718127
1907555a950fd68d43b118706ee986f0fe711c7a
3,089
cpp
C++
worker/callback_runner_test.cpp
tkwong/parameter_server
ef8424f341f3b4c4e1088b72d88930fac8b78daf
[ "Apache-2.0" ]
null
null
null
worker/callback_runner_test.cpp
tkwong/parameter_server
ef8424f341f3b4c4e1088b72d88930fac8b78daf
[ "Apache-2.0" ]
null
null
null
worker/callback_runner_test.cpp
tkwong/parameter_server
ef8424f341f3b4c4e1088b72d88930fac8b78daf
[ "Apache-2.0" ]
null
null
null
#include "glog/logging.h" #include "gtest/gtest.h" #include "worker/callback_runner.cpp" namespace csci5570 { class TestCallbackRunner: public testing::Test { protected: void SetUp() {} void TearDown() {} }; // class TestCallbackRunner TEST_F(TestCallbackRunner, Init) { CallbackRunner runner; } TEST_F(TestCallbackRunner, AddResponse) { CallbackRunner runner; std::map<Key,float> reply; bool finished = false; runner.RegisterRecvHandle(0, 0,[&reply](Message& msg){ auto re_keys = third_party::SArray<Key>(msg.data[0]); auto re_vals = third_party::SArray<float>(msg.data[1]); for (int i=0; i<re_keys.size(); i++) reply.insert(std::make_pair(re_keys[i], re_vals[i])); }); runner.RegisterRecvFinishHandle(0, 0, [&finished]{finished=true;}); runner.NewRequest(0, 0, 2); Message r1, r2; third_party::SArray<Key> r1_keys{3}; third_party::SArray<float> r1_vals{0.1}; r1.AddData(r1_keys); r1.AddData(r1_vals); third_party::SArray<Key> r2_keys{4, 5, 6}; third_party::SArray<float> r2_vals{0.4, 0.2, 0.3}; r2.AddData(r2_keys); r2.AddData(r2_vals); runner.AddResponse(0, 0, r1); runner.AddResponse(0, 0, r2); runner.WaitRequest(0, 0); EXPECT_EQ(reply.size(), 4); std::map<Key, float> expected { {3, 0.1}, {4, 0.4}, {5, 0.2}, {6, 0.3} }; EXPECT_EQ(reply, expected); EXPECT_EQ(finished, true); } TEST_F(TestCallbackRunner, AddResponseTwoWorkers) { CallbackRunner runner; std::map<Key,float> reply; float sum = 0; // Register for first worker runner.RegisterRecvHandle(0, 0,[&reply](Message& msg){ auto re_keys = third_party::SArray<Key>(msg.data[0]); auto re_vals = third_party::SArray<float>(msg.data[1]); for (int i=0; i<re_keys.size(); i++) reply.insert(std::make_pair(re_keys[i], re_vals[i])); }); runner.RegisterRecvFinishHandle(0, 0, []{}); runner.NewRequest(0, 0, 2); // Register for second worker runner.RegisterRecvHandle(1, 0,[&sum](Message& msg){ auto re_vals = third_party::SArray<float>(msg.data[1]); for (int i=0; i<re_vals.size(); i++) sum += re_vals[i]; }); runner.RegisterRecvFinishHandle(1, 0, []{}); runner.NewRequest(1, 0, 2); // Respond to both worker Message r1, r2; third_party::SArray<Key> r1_keys{3}; third_party::SArray<float> r1_vals{0.1}; r1.AddData(r1_keys); r1.AddData(r1_vals); third_party::SArray<Key> r2_keys{4, 5, 6}; third_party::SArray<float> r2_vals{0.4, 0.2, 0.3}; r2.AddData(r2_keys); r2.AddData(r2_vals); runner.AddResponse(0, 0, r1); runner.AddResponse(0, 0, r2); runner.AddResponse(1, 0, r1); runner.AddResponse(1, 0, r2); runner.WaitRequest(0, 0); EXPECT_EQ(reply.size(), 4); std::map<Key, float> expected { {3, 0.1}, {4, 0.4}, {5, 0.2}, {6, 0.3} }; EXPECT_EQ(reply, expected); runner.WaitRequest(1, 0); EXPECT_EQ(sum, 1.0); } } // namespace csci5570
27.336283
98
0.616381
190ee3f87e869fae0d4deb4a480c1b36a6b936b3
3,141
cpp
C++
src/blackboard_entry.cpp
robotics-upo/BehaviorTree.CPP
320e61711f75604a23726fbf16fd2660e8c68efe
[ "MIT" ]
null
null
null
src/blackboard_entry.cpp
robotics-upo/BehaviorTree.CPP
320e61711f75604a23726fbf16fd2660e8c68efe
[ "MIT" ]
null
null
null
src/blackboard_entry.cpp
robotics-upo/BehaviorTree.CPP
320e61711f75604a23726fbf16fd2660e8c68efe
[ "MIT" ]
null
null
null
#include "behaviortree_cpp_v3/blackboard_entry.h" namespace BT { Entry::Entry(const Entry& _other_entry, const TypesConverter& _converter) : converter_ ( _converter ) { input_types_ = _other_entry.input_types_; output_types_ = _other_entry.output_types_; checkTypesCompatible(input_types_, output_types_); } Entry::Entry(const PortInfo& _port_info, const TypesConverter& _converter) : converter_ ( _converter ) { addPortInfo(_port_info); } Entry::Entry(Any&& other_any, const TypesConverter& _converter): value_ (std::move(other_any)), converter_ (_converter) {} Entry::Entry(Any&& other_any, const PortInfo& _port_info, const TypesConverter& _converter): value_ (std::move(other_any)), converter_ (_converter) { addPortInfo(value_.type(), _port_info.direction()); } Entry::Entry(Any&& other_any, const PortDirection _direction, const TypesConverter& _converter): value_ (std::move(other_any)), converter_ (_converter) { addPortInfo(value_.type(), _direction); } template<> void Entry::setValue(Any&& _other_any) { addPortInfo(_other_any.type(), PortDirection::OUTPUT); value_ = _other_any; } template<> Any Entry::getValue() { return value_; } void Entry::addPortInfo(const PortInfo& _port_info) { if(!_port_info.type()) { return; } addPortInfo(*_port_info.type(), _port_info.direction()); } void Entry::addPortInfo(const std::type_info& _type, const PortDirection _direction) { std::pair<Types::iterator, bool> insert_result {}; switch(_direction) { case PortDirection::INPUT: insert_result = input_types_.insert(_type); break; case PortDirection::OUTPUT: insert_result = output_types_.insert(_type); break; case PortDirection::INOUT: { insert_result = input_types_.insert(_type); if(insert_result.second) { output_types_.insert(_type); } else { insert_result = output_types_.insert(_type); } } break; } //Check for type compatibility only if there has been changes in the type if(insert_result.second) { checkTypesCompatible(output_types_, input_types_); } } // Private void Entry::checkTypesCompatible(const Types& _output_types, const Types& _input_types) { for(const std::type_index& output_type : _output_types) { for(const std::type_index& input_type : _input_types) { if(!converter_.isConvertible(output_type, input_type)) { throw LogicError { "Incompatible entry types. No known conversion from ", demangle(output_type), " to ", demangle(input_type) }; } } } } } // end namespace BT
30.201923
100
0.589621
190f6fb15793fc116a783933ffddd3c33e11ddd0
502
cpp
C++
beta versions/Processor.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
[ "MIT" ]
null
null
null
beta versions/Processor.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
[ "MIT" ]
null
null
null
beta versions/Processor.cpp
tec-csf/tc2017-pf-primavera-2020-equipo-4-1
111f53acb1c7f3e0bebd112ed0bdda9ab0df5174
[ "MIT" ]
null
null
null
#include "Processor.hpp" using namespace std; void Processor::setEverything(int anID, int amountOfCores, float alpha, float beta, float delta, float gamma, float c){ id = anID; cores = amountOfCores; failureP = 1 / gamma; probRc = c; probRb = 1 - c; TRc = 1 / beta; TRb = 1 / alpha; TRepair = 1 / delta; } int Processor::calculatePoisson(int x){ srand(time(0)); float r = rand() / INT_MAX; int xPoisson = (1 / x) * log(1 - r); return xPoisson; }
21.826087
72
0.605578
190fc0414b47b91ff40165dcabf6f578c9737971
18,167
cpp
C++
admin/cmdline/scheduledtasks/end.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/cmdline/scheduledtasks/end.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/cmdline/scheduledtasks/end.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/****************************************************************************** Copyright(c) Microsoft Corporation Module Name: end.cpp Abstract: This module terminates the schedule task which is currently running in the system Author: Venu Gopal Choudary 12-Mar-2001 Revision History: Venu Gopal Choudary 12-Mar-2001 : Created it ******************************************************************************/ //common header files needed for this file #include "pch.h" #include "CommonHeaderFiles.h" // Function declaration for the Usage function. VOID DisplayEndUsage(); /***************************************************************************** Routine Description: This routine terminates the scheduled task(s) Arguments: [ in ] argc : Number of command line arguments [ in ] argv : Array containing command line arguments Return Value : A DWORD value indicating EXIT_SUCCESS on success else EXIT_FAILURE on failure *****************************************************************************/ DWORD TerminateScheduledTask( IN DWORD argc, IN LPCTSTR argv[] ) { // Variables used to find whether End option, Usage option // are specified or not BOOL bEnd = FALSE; BOOL bUsage = FALSE; BOOL bFlag = FALSE; // Set the TaskSchduler object as NULL ITaskScheduler *pITaskScheduler = NULL; // Return value HRESULT hr = S_OK; // Initialising the variables that are passed to TCMDPARSER structure LPWSTR szServer = NULL; WCHAR szTaskName[ MAX_JOB_LEN ] = L"\0"; LPWSTR szUser = NULL; LPWSTR szPassword = NULL; // Dynamic Array contaning array of jobs TARRAY arrJobs = NULL; BOOL bNeedPassword = FALSE; BOOL bResult = FALSE; BOOL bCloseConnection = TRUE; //buffer for displaying error message WCHAR szMessage[2 * MAX_STRING_LENGTH] = L"\0"; TCMDPARSER2 cmdEndOptions[MAX_END_OPTIONS]; BOOL bReturn = FALSE; DWORD dwCheck = 0; DWORD dwPolicy = 0; // /run sub-options const WCHAR szEndnOpt[] = L"end"; const WCHAR szEndHelpOpt[] = L"?"; const WCHAR szEndServerOpt[] = L"s"; const WCHAR szEndUserOpt[] = L"u"; const WCHAR szEndPwdOpt[] = L"p"; const WCHAR szEndTaskNameOpt[] = L"tn"; // set all the fields to 0 SecureZeroMemory( cmdEndOptions, sizeof( TCMDPARSER2 ) * MAX_END_OPTIONS ); // // fill the commandline parser // // /delete option StringCopyA( cmdEndOptions[ OI_END_OPTION ].szSignature, "PARSER2\0", 8 ); cmdEndOptions[ OI_END_OPTION ].dwType = CP_TYPE_BOOLEAN; cmdEndOptions[ OI_END_OPTION ].pwszOptions = szEndnOpt; cmdEndOptions[ OI_END_OPTION ].dwCount = 1; cmdEndOptions[ OI_END_OPTION ].dwFlags = 0; cmdEndOptions[ OI_END_OPTION ].pValue = &bEnd; // /? option StringCopyA( cmdEndOptions[ OI_END_USAGE ].szSignature, "PARSER2\0", 8 ); cmdEndOptions[ OI_END_USAGE ].dwType = CP_TYPE_BOOLEAN; cmdEndOptions[ OI_END_USAGE ].pwszOptions = szEndHelpOpt; cmdEndOptions[ OI_END_USAGE ].dwCount = 1; cmdEndOptions[ OI_END_USAGE ].dwFlags = CP2_USAGE; cmdEndOptions[ OI_END_USAGE ].pValue = &bUsage; // /s option StringCopyA( cmdEndOptions[ OI_END_SERVER ].szSignature, "PARSER2\0", 8 ); cmdEndOptions[ OI_END_SERVER ].dwType = CP_TYPE_TEXT; cmdEndOptions[ OI_END_SERVER].pwszOptions = szEndServerOpt; cmdEndOptions[ OI_END_SERVER ].dwCount = 1; cmdEndOptions[ OI_END_SERVER ].dwFlags = CP2_ALLOCMEMORY| CP2_VALUE_TRIMINPUT|CP2_VALUE_NONULL ; // /u option StringCopyA( cmdEndOptions[ OI_END_USERNAME ].szSignature, "PARSER2\0", 8 ); cmdEndOptions[ OI_END_USERNAME ].dwType = CP_TYPE_TEXT; cmdEndOptions[ OI_END_USERNAME ].pwszOptions = szEndUserOpt; cmdEndOptions[ OI_END_USERNAME ].dwCount = 1; cmdEndOptions[ OI_END_USERNAME ].dwFlags = CP2_ALLOCMEMORY| CP2_VALUE_TRIMINPUT|CP2_VALUE_NONULL ; // /p option StringCopyA( cmdEndOptions[ OI_END_PASSWORD ].szSignature, "PARSER2\0", 8 ); cmdEndOptions[ OI_END_PASSWORD ].dwType = CP_TYPE_TEXT; cmdEndOptions[ OI_END_PASSWORD ].pwszOptions = szEndPwdOpt; cmdEndOptions[ OI_END_PASSWORD ].dwCount = 1; cmdEndOptions[ OI_END_PASSWORD ].dwActuals = 0; cmdEndOptions[ OI_END_PASSWORD ].dwFlags = CP2_ALLOCMEMORY | CP2_VALUE_OPTIONAL; // /tn option StringCopyA( cmdEndOptions[ OI_END_TASKNAME ].szSignature, "PARSER2\0", 8 ); cmdEndOptions[ OI_END_TASKNAME ].dwType = CP_TYPE_TEXT; cmdEndOptions[ OI_END_TASKNAME ].pwszOptions = szEndTaskNameOpt; cmdEndOptions[ OI_END_TASKNAME ].dwCount = 1; cmdEndOptions[ OI_END_TASKNAME ].dwFlags = CP2_MANDATORY; cmdEndOptions[ OI_END_TASKNAME ].pValue = szTaskName; cmdEndOptions[ OI_END_TASKNAME ].dwLength = MAX_JOB_LEN; //parse command line arguments bReturn = DoParseParam2( argc, argv, 0, SIZE_OF_ARRAY(cmdEndOptions), cmdEndOptions, 0); if( FALSE == bReturn) // Invalid commandline { //display an error message ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_INTERNAL ); ReleaseGlobals(); return EXIT_FAILURE; } // get the buffer pointers allocated by command line parser szServer = (LPWSTR)cmdEndOptions[ OI_RUN_SERVER ].pValue; szUser = (LPWSTR)cmdEndOptions[ OI_RUN_USERNAME ].pValue; szPassword = (LPWSTR)cmdEndOptions[ OI_RUN_PASSWORD ].pValue; if ( (argc > 3) && (bUsage == TRUE) ) { ShowMessage ( stderr, GetResString (IDS_ERROR_ENDPARAM) ); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } // Displaying end usage if user specified -? with -run option if( bUsage == TRUE ) { DisplayEndUsage(); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_SUCCESS; } // check for invalid user name if( ( cmdEndOptions[OI_END_SERVER].dwActuals == 0 ) && ( cmdEndOptions[OI_END_USERNAME].dwActuals == 1 ) ) { ShowMessage(stderr, GetResString(IDS_END_USER_BUT_NOMACHINE)); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return RETVAL_FAIL; } // check for invalid username if ( cmdEndOptions[ OI_END_USERNAME ].dwActuals == 0 && cmdEndOptions[ OI_END_PASSWORD ].dwActuals == 1 ) { // invalid syntax ShowMessage(stderr, GetResString(IDS_EPASSWORD_BUT_NOUSERNAME)); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return RETVAL_FAIL; // indicate failure } // check for the length of the taskname if( ( StringLength( szTaskName, 0 ) > MAX_JOB_LEN ) ) { ShowMessage(stderr, GetResString(IDS_INVALID_TASKLENGTH)); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return RETVAL_FAIL; } //for holding values of parameters in FormatMessage() WCHAR* szValues[1] = {NULL}; // check whether the password (-p) specified in the command line or not // and also check whether '*' or empty is given for -p or not // check whether the password (-p) specified in the command line or not // and also check whether '*' or empty is given for -p or not // check whether the password (-p) specified in the command line or not // and also check whether '*' or empty is given for -p or not // check the remote connectivity information if ( szServer != NULL ) { // // if -u is not specified, we need to allocate memory // in order to be able to retrive the current user name // // case 1: -p is not at all specified // as the value for this switch is optional, we have to rely // on the dwActuals to determine whether the switch is specified or not // in this case utility needs to try to connect first and if it fails // then prompt for the password -- in fact, we need not check for this // condition explicitly except for noting that we need to prompt for the // password // // case 2: -p is specified // but we need to check whether the value is specified or not // in this case user wants the utility to prompt for the password // before trying to connect // // case 3: -p * is specified // user name if ( szUser == NULL ) { szUser = (LPWSTR) AllocateMemory( MAX_STRING_LENGTH * sizeof( WCHAR ) ); if ( szUser == NULL ) { SaveLastError(); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return RETVAL_FAIL; } } // password if ( szPassword == NULL ) { bNeedPassword = TRUE; szPassword = (LPWSTR)AllocateMemory( MAX_STRING_LENGTH * sizeof( WCHAR ) ); if ( szPassword == NULL ) { SaveLastError(); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return RETVAL_FAIL; } } // case 1 if ( cmdEndOptions[ OI_END_PASSWORD ].dwActuals == 0 ) { // we need not do anything special here } // case 2 else if ( cmdEndOptions[ OI_END_PASSWORD ].pValue == NULL ) { StringCopy( szPassword, L"*", GetBufferSize(szPassword)/sizeof(WCHAR)); } // case 3 else if ( StringCompareEx( szPassword, L"*", TRUE, 0 ) == 0 ) { if ( ReallocateMemory( (LPVOID*)&szPassword, MAX_STRING_LENGTH * sizeof( WCHAR ) ) == FALSE ) { SaveLastError(); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return RETVAL_FAIL; } // ... bNeedPassword = TRUE; } } if( ( IsLocalSystem( szServer ) == FALSE ) || ( cmdEndOptions[OI_END_USERNAME].dwActuals == 1 )) { bFlag = TRUE; // Establish the connection on a remote machine bResult = EstablishConnection(szServer,szUser,GetBufferSize(szUser)/sizeof(WCHAR),szPassword,GetBufferSize(szPassword)/sizeof(WCHAR), bNeedPassword); if (bResult == FALSE) { ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_INTERNAL ); //ShowMessage( stderr, GetResString(IDS_ERROR_STRING) ); //ShowMessage( stderr, GetReason()); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE ; } else { // though the connection is successfull, some conflict might have occured switch( GetLastError() ) { case I_NO_CLOSE_CONNECTION: bCloseConnection = FALSE; break; case E_LOCAL_CREDENTIALS: case ERROR_SESSION_CREDENTIAL_CONFLICT: { bCloseConnection = FALSE; ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_INTERNAL ); //ShowMessage( stderr, GetResString(IDS_ERROR_STRING) ); //ShowMessage( stderr, GetReason()); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } default : bCloseConnection = TRUE; } } //release memory for password FreeMemory((LPVOID*) &szPassword); } // Get the task Scheduler object for the machine. pITaskScheduler = GetTaskScheduler( szServer ); // If the Task Scheduler is not defined then give the error message. if ( pITaskScheduler == NULL ) { if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } // check whether the task scheduler service is running or not. if ( TRUE == CheckServiceStatus(szServer, &dwCheck, FALSE) ) { ShowMessage ( stderr, GetResString (IDS_SERVICE_NOT_RUNNING) ); } // Validate the Given Task and get as TARRAY in case of taskname arrJobs = ValidateAndGetTasks( pITaskScheduler, szTaskName); if( arrJobs == NULL ) { StringCchPrintf( szMessage , SIZE_OF_ARRAY(szMessage), GetResString(IDS_TASKNAME_NOTEXIST), _X( szTaskName )); ShowMessage(stderr, szMessage ); if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } // check whether the group policy prevented user from running or not. if ( FALSE == GetGroupPolicy( szServer, szUser, TS_KEYPOLICY_DENY_EXECUTION, &dwPolicy ) ) { if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } if ( dwPolicy > 0 ) { ShowMessage ( stdout, GetResString (IDS_PREVENT_END)); if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_SUCCESS; } IPersistFile *pIPF = NULL; ITask *pITask = NULL; StringConcat ( szTaskName, JOB, SIZE_OF_ARRAY(szTaskName) ); // return an pITask inteface for szTaskName hr = pITaskScheduler->Activate(szTaskName,IID_ITask, (IUnknown**) &pITask); if (FAILED(hr)) { SetLastError ((DWORD) hr); ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_SYSTEM ); if( pIPF ) pIPF->Release(); if( pITask ) pITask->Release(); if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } //WCHAR szBuffer[2 * MAX_STRING_LENGTH] = L"\0"; if ( ParseTaskName( szTaskName ) ) { if( pIPF ) pIPF->Release(); if( pITask ) pITask->Release(); if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } // terminate the scheduled task hr = pITask->Terminate(); if ( FAILED(hr) ) { SetLastError ((DWORD) hr); ShowLastErrorEx ( stderr, SLE_TYPE_ERROR | SLE_SYSTEM ); if( pIPF ) pIPF->Release(); if( pITask ) pITask->Release(); if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_FAILURE; } else { szValues[0] = (WCHAR*) (szTaskName); StringCchPrintf ( szMessage, SIZE_OF_ARRAY(szMessage), GetResString(IDS_END_SUCCESSFUL), _X(szTaskName)); ShowMessage(stdout, _X(szMessage)); } if( pIPF ) pIPF->Release(); if( pITask ) pITask->Release(); if ( (TRUE == bFlag) && (bCloseConnection == TRUE) ) { CloseConnection( szServer ); } Cleanup(pITaskScheduler); FreeMemory((LPVOID*) &szServer); FreeMemory((LPVOID*) &szUser); FreeMemory((LPVOID*) &szPassword); return EXIT_SUCCESS; } /***************************************************************************** Routine Description: This routine displays the usage of -end option Arguments: None Return Value : VOID ******************************************************************************/ VOID DisplayEndUsage() { // Displaying run option usage DisplayUsage( IDS_END_HLP1, IDS_END_HLP17); }
32.499106
158
0.565641
1914208c93fcd9ad93a53e72ac939974f736e864
2,202
cc
C++
net/tools/transport_security_state_generator/spki_hash_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
net/tools/transport_security_state_generator/spki_hash_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
net/tools/transport_security_state_generator/spki_hash_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/tools/transport_security_state_generator/spki_hash.h" #include "base/strings/string_number_conversions.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace net { namespace transport_security_state { namespace { TEST(SPKIHashTest, FromString) { SPKIHash hash; // Valid SHA256. EXPECT_TRUE( hash.FromString("sha256/1111111111111111111111111111111111111111111=")); std::vector<uint8_t> hash_vector(hash.data(), hash.data() + hash.size()); EXPECT_THAT( hash_vector, testing::ElementsAreArray( {0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D, 0x75, 0xD7, 0x5D})); SPKIHash hash2; EXPECT_TRUE( hash2.FromString("sha256/4osU79hfY3P2+WJGlT2mxmSL+5FIwLEVxTQcavyBNgQ=")); std::vector<uint8_t> hash_vector2(hash2.data(), hash2.data() + hash2.size()); EXPECT_THAT( hash_vector2, testing::ElementsAreArray( {0xE2, 0x8B, 0x14, 0xEF, 0xD8, 0x5F, 0x63, 0x73, 0xF6, 0xF9, 0x62, 0x46, 0x95, 0x3D, 0XA6, 0xC6, 0x64, 0x8B, 0xFB, 0x91, 0x48, 0xC0, 0xB1, 0x15, 0xC5, 0x34, 0x1C, 0x6A, 0xFC, 0x81, 0x36, 0x04})); SPKIHash hash3; // Valid SHA1 should be rejected. EXPECT_FALSE(hash3.FromString("sha1/111111111111111111111111111=")); EXPECT_FALSE(hash3.FromString("sha1/gzF+YoVCU9bXeDGQ7JGQVumRueM=")); // SHA1 disguised as SHA256. EXPECT_FALSE(hash3.FromString("sha256/111111111111111111111111111=")); // SHA512 disguised as SHA256. EXPECT_FALSE( hash3.FromString("sha256/ns3smS51SK/4P7uSVhSlCIMNAxkD+r6C/ZZA/" "07vac0uyMdRS4jKfqlvk3XxLFP1v5aMIxM5cdTM7FHNwxagQg==")); // Invalid BASE64. EXPECT_FALSE(hash3.FromString("sha256/hsts-preload")); EXPECT_FALSE(hash3.FromString("sha256/1. 2. 3. security!=")); } } // namespace } // namespace transport_security_state } // namespace net
33.876923
79
0.701635
191a6c446228ac19142afb92a40c92586a351358
1,350
cpp
C++
src/plugins/blasq/plugins/rappor/rappor.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/blasq/plugins/rappor/rappor.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/blasq/plugins/rappor/rappor.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "rappor.h" #include <QIcon> #include <util/util.h> #include "vkservice.h" namespace LC { namespace Blasq { namespace Rappor { void Plugin::Init (ICoreProxy_ptr proxy) { Util::InstallTranslator ("blasq_rappor"); Service_ = new VkService (proxy); } void Plugin::SecondInit () { } QByteArray Plugin::GetUniqueID () const { return "org.LeechCraft.Blasq.Rappor"; } void Plugin::Release () { } QString Plugin::GetName () const { return "Blasq Rappor"; } QString Plugin::GetInfo () const { return tr ("VKontakte support module for Blasq."); } QIcon Plugin::GetIcon () const { return QIcon (); } QSet<QByteArray> Plugin::GetPluginClasses () const { QSet<QByteArray> result; result << "org.LeechCraft.Blasq.ServicePlugin"; return result; } QList<IService*> Plugin::GetServices () const { return { Service_ }; } } } } LC_EXPORT_PLUGIN (leechcraft_blasq_rappor, LC::Blasq::Rappor::Plugin);
19.014085
83
0.622222
191a7076b71459404f6bfe86cc3f97fd5cd82611
4,088
cpp
C++
src/optimizer/ind_var.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
null
null
null
src/optimizer/ind_var.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
null
null
null
src/optimizer/ind_var.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
null
null
null
#include "pass.hpp" void ind_var_discovery(NormalFunc *f) { // TODO: debug dbg << "## ind var discovery: " << f->name << "\n"; auto S = build_dom_tree(f); auto defs = build_defs(f); auto i2bb = build_in2bb(f); std::unordered_set<Reg> la; std::unordered_map<Reg, Reg> mp_reg; dom_tree_dfs(S, [&](BB *w) { w->for_each([&](Instr *i) { Case(LoadAddr, i0, i) { la.insert(i0->d1); } else Case(BinaryOpInstr, i0, i) { if (la.count(i0->s1) || la.count(i0->s2)) la.insert(i0->d1); } }); }); dom_tree_dfs(S, [&](BB *w) { auto &sw = S[w]; if (sw.loop_rt) { auto get_BB = [&](Reg r) { return i2bb[defs[r]]; }; auto is_c = [&](Reg r) { return r.id && S[get_BB(r)].sdom(sw); }; std::unordered_map<Reg, IndVarInfo> indvar; for (auto it = w->instrs.begin(); it != w->instrs.end(); ++it) { Instr *i = it->get(); Case(PhiInstr, phi, i) { if (phi->uses.size() != 2) continue; auto u1 = phi->uses[0]; auto u2 = phi->uses[1]; if (!is_c(u1.first)) std::swap(u1, u2); if (!is_c(u1.first)) continue; Case(BinaryOpInstr, bop, defs[u2.first]) { auto op = bop->op.type; if (op == BinaryOp::ADD || op == BinaryOp::SUB) if (bop->s1 == phi->d1 && is_c(bop->s2)) { // phi.d1 = u1.first + k * bop.s2 auto &s = indvar[phi->d1]; s.base = u1.first; s.step = bop->s2; s.op = op; BB *bb1 = get_BB(s.base); BB *bb2 = get_BB(s.step); s.bb = S[bb1].dom(S[bb2]) ? bb2 : bb1; auto &iv2 = s; dbg << "basic ind var " << f->get_name(iv2.base) << "," << f->get_name(iv2.step) << " : " << f->get_name(bop->d1) << "\n"; } } } else Case(BinaryOpInstr, bop, i) { if (bop->op.type == BinaryOp::MUL || bop->op.type == BinaryOp::ADD) { auto ind = bop->s1, step = bop->s2; if (!(indvar.count(ind) && is_c(step))) std::swap(ind, step); if (!(indvar.count(ind) && is_c(step))) continue; if (bop->op.type == BinaryOp::ADD) { // only rewrite as indvar for array index compute if (!la.count(bop->s1) && !la.count(bop->s2)) continue; } auto &iv1 = indvar[ind]; auto &iv2 = indvar[bop->d1]; iv2.base = f->new_Reg(); iv2.op = iv1.op; Reg base1 = f->new_Reg(); Reg base2 = f->new_Reg(); mp_reg[bop->d1] = base1; BB *bb = iv2.bb = iv1.bb; if (bop->op.type == BinaryOp::MUL) { iv2.step = f->new_Reg(); iv1.bb->push1( new BinaryOpInstr(iv2.base, iv1.base, step, BinaryOp::MUL)); // base = base0 * step iv1.bb->push1( new BinaryOpInstr(iv2.step, iv1.step, step, BinaryOp::MUL)); // step = step0 * step } else { iv2.step = iv1.step; iv1.bb->push1( new BinaryOpInstr(iv2.base, iv1.base, step, BinaryOp::ADD)); // base = base0 + step } dbg << "ind var " << f->get_name(iv2.base) << "," << f->get_name(iv2.step) << " : " << f->get_name(base1) << "," << f->get_name(base2) << "\n"; PhiInstr *phi = new PhiInstr(base1); w->push_front(phi); for (BB *u : sw.in) { phi->add_use(sw.dom(S[u]) ? base2 : iv2.base, u); } *it = std::unique_ptr<Instr>(new BinaryOpInstr( base2, base1, iv2.step, iv2.op)); // base += step } } } } }); map_use(f, mp_reg); remove_unused_def(f); }
37.163636
80
0.429305
191cddd5415bab0a4e1557200a8ec1ed88edf626
17,000
cpp
C++
libpvkernel/src/rush/PVFormatVersion.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/rush/PVFormatVersion.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/rush/PVFormatVersion.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
// // MIT License // // © ESI Group, 2015 // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include <pvkernel/rush/PVFormatVersion.h> #include <pvkernel/rush/PVFormat_types.h> #include <cassert> #include <QChar> #include <QDomNode> #include <QString> #include <QStringList> // Utility function to convert pre 7 format to 7 format.for mapping/type/plotting static QString const get_type_from_format(QString const& type_attr, QString const& mapped_attr) { if (type_attr == "integer" and mapped_attr == "unsigned") return "number_uint32"; else if (type_attr == "integer" and mapped_attr == "hexadecimal") return "number_uint32"; else if (type_attr == "integer" and mapped_attr == "octal") return "number_uint32"; else if (type_attr == "integer" and mapped_attr == "default") return "number_int32"; else if (type_attr == "host" and mapped_attr == "default") return "string"; else if (type_attr == "enum" and mapped_attr == "default") return "string"; else if (type_attr == "float") return "number_float"; return type_attr; } static QString const get_mapped_from_format(QString const& type_attr, QString const& mapped_attr) { if (type_attr == "integer" and mapped_attr == "unsigned") return "default"; else if (type_attr == "integer" and mapped_attr == "hexadecimal") return "default"; else if (type_attr == "integer" and mapped_attr == "octal") return "default"; else if (type_attr == "integer" and mapped_attr == "default") return "default"; else if (type_attr == "host" and mapped_attr == "default") return "host"; else if (type_attr == "enum" and mapped_attr == "default") return "default"; else if (type_attr == "string" and mapped_attr == "default") return "string"; else if (type_attr == "ipv4" and mapped_attr == "uniform") return "default"; return mapped_attr; } static QString const get_plotted_from_format(QString const& type_attr, QString const& mapped_attr, QString const& plotted_attr) { if (type_attr == "enum") return "enum"; else if (type_attr == "ipv4" and mapped_attr == "uniform") return "enum"; else if (plotted_attr == "minmax") return "default"; return plotted_attr; } QString PVRush::PVFormatVersion::__impl::get_version(QDomDocument const& doc) { return doc.documentElement().attribute("version", "0"); } void PVRush::PVFormatVersion::to_current(QDomDocument& doc) { QString version = __impl::get_version(doc); if (version == "0") { __impl::from0to1(doc); version = "1"; } if (version == "1") { __impl::from1to2(doc); version = "2"; } if (version == "2") { __impl::from2to3(doc); version = "3"; } if (version == "3") { __impl::from3to4(doc); version = "4"; } if (version == "4") { __impl::from4to5(doc); version = "5"; } if (version == "5") { __impl::from5to6(doc); version = "6"; } if (version == "6") { __impl::from6to7(doc); version = "7"; } if (version == "7") { __impl::from7to8(doc); version = "8"; } if (version == "8") { __impl::from8to9(doc); version = "9"; } if (version == "9") { __impl::from9to10(doc); version = "10"; } } void PVRush::PVFormatVersion::__impl::from0to1(QDomDocument& doc) { _rec_0to1(doc.documentElement()); doc.documentElement().setAttribute("version", "1"); } void PVRush::PVFormatVersion::__impl::from1to2(QDomDocument& doc) { _rec_1to2(doc.documentElement()); doc.documentElement().setAttribute("version", "2"); } void PVRush::PVFormatVersion::__impl::from2to3(QDomDocument& doc) { _rec_2to3(doc.documentElement()); doc.documentElement().setAttribute("version", "3"); } void PVRush::PVFormatVersion::__impl::from3to4(QDomDocument& doc) { _rec_3to4(doc.documentElement()); doc.documentElement().setAttribute("version", "4"); } void PVRush::PVFormatVersion::__impl::from4to5(QDomDocument& doc) { _rec_4to5(doc.documentElement()); doc.documentElement().setAttribute("version", "5"); } void PVRush::PVFormatVersion::__impl::from5to6(QDomDocument& doc) { _rec_5to6(doc.documentElement()); doc.documentElement().setAttribute("version", "6"); } void PVRush::PVFormatVersion::__impl::from7to8(QDomDocument& doc) { QDomNodeList splitter = doc.documentElement().elementsByTagName("splitter"); for (int i = 0; i < splitter.size(); i++) { QDomElement ax = splitter.at(i).toElement(); // Update type value QString type = ax.attribute("type"); if (type != "url") { continue; } std::vector<int> pos(10, -1); auto fields = ax.childNodes(); for (int j = 0; j < fields.size(); j++) { QDomElement axis = fields.at(j).namedItem("axis").toElement(); if (axis.isNull()) { // Field without axis is like "no field" in url splitter continue; } QString tag = axis.attribute("tag"); if (tag.contains("protocol")) { pos[j] = 0; } else if (tag.contains("subdomain")) { pos[j] = 1; } else if (tag.contains("host")) { pos[j] = 2; } else if (tag.contains("domain")) { pos[j] = 3; } else if (tag.contains("tld")) { pos[j] = 4; } else if (tag.contains("port")) { pos[j] = 5; } else if (tag.contains("url-variables")) { pos[j] = 7; } else if (tag.contains("url-credentials")) { pos[j] = 9; } else if (tag.contains("url-anchor")) { pos[j] = 8; } else { assert(tag == "url"); // CHeck it at the end to avoid mismatch with variables, cred... pos[j] = 6; } } QDomElement new_splitter = ax.ownerDocument().createElement("splitter"); new_splitter.setAttribute("type", "url"); for (int p : pos) { if (p == -1) { QDomElement new_field = ax.ownerDocument().createElement("field"); new_splitter.appendChild(new_field); } else { new_splitter.appendChild(fields.at(p).cloneNode()); } } splitter.at(i).parentNode().replaceChild(new_splitter, splitter.at(i)); } QDomNodeList axis = doc.documentElement().elementsByTagName("axis"); for (int i = 0; i < axis.size(); i++) { QDomElement ax = axis.at(i).toElement(); ax.removeAttribute("tag"); ax.removeAttribute("key"); ax.removeAttribute("group"); } doc.documentElement().setAttribute("version", "8"); } void PVRush::PVFormatVersion::__impl::from8to9(QDomDocument& doc) { QDomNodeList converters = doc.documentElement().elementsByTagName("converter"); for (int i = 0; i < converters.size(); i++) { QDomElement converter = converters.at(i).toElement(); if (converter.attribute("type") != "substitution") { continue; } converter.setAttribute("modes", 1); converter.setAttribute("substrings_map", ""); converter.setAttribute("invert_order", false); } doc.documentElement().setAttribute("version", "9"); } void PVRush::PVFormatVersion::__impl::from9to10(QDomDocument& doc) { QDomNodeList axis = doc.documentElement().elementsByTagName("axis"); for (int i = 0; i < axis.size(); i++) { QDomElement ax = axis.at(i).toElement(); // Limit the choice of port plotting to uint16 QDomElement plotted = ax.namedItem("plotting").toElement(); QString plotting = plotted.attribute("mode"); if (plotting == "port") { ax.setAttribute("type", "number_uint16"); } } doc.documentElement().setAttribute("version", "10"); } void PVRush::PVFormatVersion::__impl::from6to7(QDomDocument& doc) { QDomNodeList axis = doc.documentElement().elementsByTagName("axis"); for (int i = 0; i < axis.size(); i++) { QDomElement ax = axis.at(i).toElement(); // Update type value QString type = ax.attribute("type"); if (type.isNull()) { type = "string"; } // Update mapping value QDomElement mapped = ax.namedItem("mapping").toElement(); QString mapping = mapped.attribute("mode"); if (mapping.isNull()) { mapping = "default"; } // Update plotting value QDomElement plotted = ax.namedItem("plotting").toElement(); QString plotting = plotted.attribute("mode"); if (plotting.isNull()) { plotting = "default"; } plotted.toElement().setAttribute("mode", get_plotted_from_format(type, mapping, plotting)); mapped.toElement().setAttribute("mode", get_mapped_from_format(type, mapping)); ax.setAttribute("type", get_type_from_format(type, mapping)); // Update type_format if (mapping == "hexadecimal") { ax.toElement().setAttribute("type_format", "%#x"); } else if (mapping == "octal") { ax.toElement().setAttribute("type_format", "%#o"); } // Remove extra mapped node auto mappings = ax.elementsByTagName("mapping"); for (int j = 1; j < mappings.count(); j++) { ax.removeChild(mappings.at(j)); } // Remove extra plotted node auto plottings = ax.elementsByTagName("plotting"); for (int j = 1; j < plottings.count(); j++) { ax.removeChild(plottings.at(j)); } // Remove time-sample attribute ax.removeAttribute("time-sample"); } doc.documentElement().setAttribute("version", "7"); } void PVRush::PVFormatVersion::__impl::_rec_0to1(QDomElement elt) { QString const& tag_name = elt.tagName(); if (tag_name == "RegEx") { elt.setTagName("splitter"); elt.setAttribute("type", "regexp"); elt.setAttribute("regexp", elt.attribute("expression")); elt.removeAttribute("expression"); } else if (tag_name == "url") { elt.setTagName("splitter"); elt.setAttribute("type", "url"); } else if (tag_name == "csv") { elt.setTagName("splitter"); elt.setAttribute("type", "csv"); elt.setAttribute("sep", elt.attribute("delimiter")); elt.removeAttribute("delimiter"); } else if (tag_name == "filter") { if (elt.attribute("type") == "include") { elt.setAttribute("reverse", "0"); } else { elt.setAttribute("reverse", "1"); } elt.setAttribute("type", "regexp"); elt.setAttribute("regexp", elt.attribute("expression")); elt.removeAttribute("expression"); elt.removeAttribute("type"); } QDomNodeList children = elt.childNodes(); for (int i = 0; i < children.size(); i++) { _rec_0to1(children.at(i).toElement()); } } void PVRush::PVFormatVersion::__impl::_rec_1to2(QDomElement elt) { QString const& tag_name = elt.tagName(); static QStringList tags = QStringList() << "protocol" << "domain" << "tld" << "port" << "url" << "url-variables"; static QStringList plottings = QStringList() << "default" << "default" << "default" << "port" << "minmax" << "minmax"; if (tag_name == "splitter") { QString type = elt.attribute("type", ""); if (type == "url") { // Set default axes tags and plottings QDomNodeList children = elt.childNodes(); for (unsigned int i = 0; i < 6; i++) { QDomElement c_elt = children.at(i).toElement(); if (c_elt.tagName() == "field") { // Take the axis QDomElement axis = c_elt.firstChildElement("axis"); // and set the default tag axis.setAttribute("tag", tags[i]); axis.setAttribute("plotting", plottings[i]); } } } else if (type == "regexp") { // Default dehavioru was to match the regular expression somewhere in the line elt.setAttribute("full-line", "false"); } } else if (tag_name == "axis") { bool is_key = elt.attribute("key", "false") == "true"; if (is_key) { QString cur_tag = elt.attribute("tag"); if (!cur_tag.isEmpty()) { cur_tag += QString(QChar(':')) + "key"; } else { cur_tag = "key"; } elt.setAttribute("tag", cur_tag); } elt.removeAttribute("key"); } QDomNodeList children = elt.childNodes(); for (int i = 0; i < children.size(); i++) { _rec_1to2(children.at(i).toElement()); } } void PVRush::PVFormatVersion::__impl::_rec_2to3(QDomElement elt) { QString const& tag_name = elt.tagName(); if (tag_name == "axis") { QString plotting = elt.attribute("plotting", ""); QString type = elt.attribute("type", ""); if (type != "time" && type != "ipv4" && plotting == "minmax") { // minmax is now default. if default was not minmax, it was only relevant for the time // and ipv4 elt.setAttribute("plotting", "default"); } } QDomNodeList children = elt.childNodes(); for (int i = 0; i < children.size(); i++) { _rec_2to3(children.at(i).toElement()); } } void PVRush::PVFormatVersion::__impl::_rec_3to4(QDomNode node) { if (node.isElement()) { QDomElement elt = node.toElement(); if (elt.tagName() == "axis") { QString mapping = elt.attribute("mapping", ""); QString plotting = elt.attribute("plotting", ""); QString type = elt.attribute("type", ""); QDomElement elt_mapping = elt.ownerDocument().createElement(PVFORMAT_XML_TAG_MAPPING); elt_mapping.setAttribute(PVFORMAT_MAP_PLOT_MODE_STR, mapping); if (type == "time") { elt_mapping.setAttribute("time-format", QLatin1String("@PVTimeFormat(") + elt.attribute("time-format", "") + QLatin1String(")")); elt.removeAttribute("time-format"); } elt.appendChild(elt_mapping); QDomElement elt_plotting = elt.ownerDocument().createElement(PVFORMAT_XML_TAG_PLOTTING); elt_plotting.setAttribute(PVFORMAT_MAP_PLOT_MODE_STR, plotting); elt.appendChild(elt_plotting); elt.removeAttribute("mapping"); elt.removeAttribute("plotting"); } } QDomNode child = node.firstChild(); while (!child.isNull()) { _rec_3to4(child); child = child.nextSibling(); } } void PVRush::PVFormatVersion::__impl::_rec_4to5(QDomNode node) { if (node.isElement()) { QDomElement elt = node.toElement(); if (elt.tagName() == "mapping") { QString tf = elt.attribute("time-format", QString()); if (tf.size() > 0 && tf.startsWith("@PVTimeFormat(")) { tf = tf.mid(14, tf.size() - 15); elt.setAttribute("time-format", tf); } QString cl = elt.attribute("convert-lowercase", QString()); if (cl.size() > 0 && cl.startsWith("@Bool(")) { cl = cl.mid(6, cl.size() - 7); elt.setAttribute("convert-lowercase", cl); } } if (elt.tagName() == "splitter") { QString sep = elt.attribute("sep", QString()); if (sep.size() > 0 && sep.startsWith("@Char(")) { sep = sep.mid(6, sep.size() - 7); elt.setAttribute("sep", sep); } } } QDomNode child = node.firstChild(); while (!child.isNull()) { _rec_4to5(child); child = child.nextSibling(); } } void PVRush::PVFormatVersion::__impl::_rec_5to6(QDomNode node) { if (node.isElement()) { QDomElement elt = node.toElement(); if (elt.tagName() == "mapping") { QString tf = elt.attribute("time-format", QString()); if (tf.size() > 0) { QDomElement axis_node = node.parentNode().toElement(); axis_node.setAttribute("type_format", tf); elt.removeAttribute("time-format"); } } else if (elt.tagName() == "axis") { // Move mapping from attribute to node QString mapping = elt.attribute("mapping", QString()); QDomElement mapping_node = node.ownerDocument().createElement("mapping"); mapping_node.setAttribute("mode", mapping); elt.appendChild(mapping_node); elt.removeAttribute("mapping"); // Move plotting from attribute to node QString plotting = elt.attribute("plotting", QString()); QDomElement plotting_node = node.ownerDocument().createElement("plotting"); plotting_node.setAttribute("mode", plotting); elt.appendChild(plotting_node); elt.removeAttribute("plotting"); // Move axis/time-format to axis/mapping/type_format QString tf = elt.attribute("time-format", QString()); if (tf.size() > 0) { QDomElement axis_node = node.toElement(); axis_node.setAttribute("type_format", tf); } elt.removeAttribute("time-format"); } } QDomNode child = node.firstChild(); while (!child.isNull()) { _rec_5to6(child); child = child.nextSibling(); } }
31.25
97
0.644059
191f35d1a71135b003818c6fa2e94660e7bac8ad
2,089
cpp
C++
lab4/code/main_mpi.cpp
ankurshaswat/COL380
5c54f629d3709214f9e082aa5cd9449d14848e1c
[ "MIT" ]
null
null
null
lab4/code/main_mpi.cpp
ankurshaswat/COL380
5c54f629d3709214f9e082aa5cd9449d14848e1c
[ "MIT" ]
null
null
null
lab4/code/main_mpi.cpp
ankurshaswat/COL380
5c54f629d3709214f9e082aa5cd9449d14848e1c
[ "MIT" ]
null
null
null
#include "lab4_io.h" #include "lab4_mpi.h" #include <stdlib.h> #include "mpi.h" /* Arguments: arg: input filename (consist text, pattern_set) */ int main(int argc, char *argv[]) { if (argc < 2) { printf("\nLess Arguments\n"); return 0; } if (argc > 2) { printf("\nTOO many Arguments\n"); return 0; } //--------------------------------------------------------------------- int n; // length of text (input) char *text; // text (input) int num_patterns; // #patterns to be searched in the text (input) int *m_set; // lengths of patterns in pattern_set (input) int *p_set; // periods of patterns in pattern_set (input) char **pattern_set; // set of patterns to be searched (input) int *match_counts; // #match of pattern_i in text (to be computed) int *matches; // set of all match of each pattern_i in text (to be computed) //--------------------------------------------------------------------- double start_time, computation_time, total_time; int id; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &id); /* -- Pre-defined function -- reads input text and patterns from input file and creats array text, m_set, p_set and pattern_set see lab4_io.h for details */ // if (id == 0) read_data(argv[1], &n, &text, &num_patterns, &m_set, &p_set, &pattern_set); start_time = MPI_Wtime(); // /* // ***************************************************** // TODO -- You must implement this two function // ***************************************************** // */ periodic_pattern_matching( n, text, num_patterns, m_set, p_set, pattern_set, &match_counts, &matches); computation_time = MPI_Wtime() - start_time; MPI_Reduce(&computation_time, &total_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (id == 0) { /* --Pre-defined function -- checks for correctness of results computed by periodic_pattern_matching and outputs the results */ write_result(match_counts, matches, total_time); format_checker(num_patterns, match_counts, matches); } MPI_Finalize(); return 0; }
24.011494
99
0.594064
191fe62fb000c162bdae37ea3e70df3729d30c11
9,164
cpp
C++
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
1
2021-11-23T00:31:46.000Z
2021-11-23T00:31:46.000Z
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
null
null
null
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
1
2021-12-18T12:50:46.000Z
2021-12-18T12:50:46.000Z
#include "PlayerWeaponManager.h" #include "qpang/Game.h" #include "qpang/room/session/RoomSession.h" #include "qpang/room/tnl/net_events/client/cg_weapon.hpp" #include "qpang/room/tnl/net_events/server/gc_weapon.hpp" #include "qpang/room/tnl/net_events/server/gc_respawn.hpp" #include "qpang/room/tnl/net_events/server/gc_game_item.hpp" #include "qpang/room/tnl/net_events/server/gc_essence.hpp" constexpr auto RIFLE_INDEX = 0; PlayerWeaponManager::PlayerWeaponManager() : m_selectedWeaponIndex(0), m_previousSelectedWeaponIndex(0), m_hasEquippedMachineGun(false), m_equippedMachineGunSeqId(0) { } void PlayerWeaponManager::initialize(const std::shared_ptr<RoomSessionPlayer>& player) { m_player = player; auto* equipmentManager = player->getPlayer()->getEquipmentManager(); const auto itemIds = equipmentManager->getWeaponItemIdsByCharacter(player->getCharacter()); const auto isMeleeOnly = player->getRoomSession()->getRoom()->isMeleeOnly(); for (int i = 0; i < itemIds.size(); i++) { const auto weapon = Game::instance()->getWeaponManager()->get(itemIds[i]); if (isMeleeOnly) { // melee weapon if (i == 3) { m_weapons[3] = weapon; } } else { m_weapons[i] = weapon; } auto& [first, second] = m_defaultAmmo[weapon.itemId]; first = weapon.clipCount + equipmentManager->getExtraAmmoForWeaponIndex(i); second = weapon.clipSize; } m_selectedWeaponIndex = 3; } Weapon PlayerWeaponManager::getSelectedWeapon() { return m_weapons[m_selectedWeaponIndex]; } void PlayerWeaponManager::selectTagWeapon() { m_previousSelectedWeaponIndex = m_selectedWeaponIndex; m_selectedWeaponIndex = RIFLE_INDEX; m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex]; const auto chainLightWeapon = Game::instance()->getWeaponManager()->get(WEAPON_PREY_CHAIN_LIGHT); m_weapons[RIFLE_INDEX] = chainLightWeapon; auto& [first, second] = m_defaultAmmo[chainLightWeapon.itemId]; first = chainLightWeapon.clipCount; second = chainLightWeapon.clipSize; refillCurrentWeapon(); switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); } void PlayerWeaponManager::deselectTagWeapon() { m_weapons[RIFLE_INDEX] = m_currentRifleWeapon; m_selectedWeaponIndex = m_previousSelectedWeaponIndex; switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); reset(); } void PlayerWeaponManager::reset() { const auto player = m_player.lock(); if (player == nullptr) return; // ReSharper disable once CppUseStructuredBinding for (auto& weapon : m_weapons) { const auto [first, second] = m_defaultAmmo[weapon.itemId]; weapon.clipCount = first; weapon.clipSize = second; player->post(new GCGameItem(14, { {1191182337, 1} }, weapon.itemId)); } } void PlayerWeaponManager::reload(const uint32_t seqId) { m_weapons[m_selectedWeaponIndex].clipCount--; m_weapons[m_selectedWeaponIndex].clipSize = m_defaultAmmo[getSelectedWeapon().itemId].second; if (const auto player = m_player.lock(); player != nullptr) player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), 3, m_weapons[m_selectedWeaponIndex].itemId, seqId); } void PlayerWeaponManager::shoot(uint32_t entityId) { m_weapons[m_selectedWeaponIndex].clipSize--; } bool PlayerWeaponManager::canReload() { return m_weapons[m_selectedWeaponIndex].clipCount > 0; } bool PlayerWeaponManager::canShoot() { if (isHoldingMelee()) { return true; } return m_weapons[m_selectedWeaponIndex].clipSize > 0; } bool PlayerWeaponManager::hasWeapon(uint32_t weaponId) const { return std::find_if(m_weapons.cbegin(), m_weapons.cend(), [weaponId](const Weapon& weapon) { return weapon.itemId == weaponId; } ) != m_weapons.cend(); } void PlayerWeaponManager::switchWeapon(uint32_t weaponId, bool isReloadGlitchEnabled) { if (!isReloadGlitchEnabled) { if (m_weapons[m_selectedWeaponIndex].itemId == weaponId) { // already chose this weapon return; } } for (size_t i = 0; i < m_weapons.size(); i++) { if (m_weapons[i].itemId == weaponId) { m_selectedWeaponIndex = i; break; } } if (const auto player = m_player.lock(); player != nullptr) { player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), 0, m_weapons[m_selectedWeaponIndex].itemId, 0); player->post(new GCWeapon(player->getPlayer()->getId(), 5, m_weapons[m_selectedWeaponIndex].itemId, 0)); } } void PlayerWeaponManager::refillWeapon(const uint32_t weaponId) { const auto [first, second] = m_defaultAmmo[weaponId]; m_weapons[m_selectedWeaponIndex].clipCount = first; m_weapons[m_selectedWeaponIndex].clipSize = second; if (const auto player = m_player.lock(); player != nullptr) { player->post(new GCGameItem( 14, std::vector({ GCGameItem::Item{1191182337, 0x01, 0x00, 0x00, 0x00} }), weaponId )); } } void PlayerWeaponManager::refillCurrentWeapon() { const auto itemId = getSelectedWeapon().itemId; refillWeapon(itemId); } std::array<uint32_t, 4> PlayerWeaponManager::getWeaponIds() { std::array<uint32_t, 4> weaponIds{}; for (size_t i = 0; i < m_weapons.size(); i++) { weaponIds[i] = m_weapons[i].itemId; } return weaponIds; } std::array<Weapon, 4> PlayerWeaponManager::getWeapons() const { return m_weapons; } bool PlayerWeaponManager::hasEquippedMachineGun() const { return m_hasEquippedMachineGun; } uint64_t PlayerWeaponManager::getEquippedMachineGunSeqId() const { return m_equippedMachineGunSeqId; } void PlayerWeaponManager::equipMachineGun(const uint64_t seqId) { // If the player attempts to equip the machine gun whilst already equipping a machine gun, disallow it. if (m_hasEquippedMachineGun) { return; } // Check if the seqId is a valid sequence id. if (seqId < 1 || seqId > 4) { return; } // TODO: Perhaps check if the player is "in range" of the machine gun (by seq id). // TODO: Check if the machine gun with the seq id is already taken by another player. if (const auto player = m_player.lock(); player != nullptr) { if (player->getSkillManager()->hasActiveSkill()) { return; } // Disallow the machine gun in public enemy mode for now. if (player->getRoomSession()->getGameMode()->isPublicEnemyMode()) { player->getPlayer()->broadcast(u"The machine gun is disabled in the public enemy gamemode."); return; } // Let client know the player is shooting with ground zero gun. player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::EQUIP_MACHINE_GUN, WEAPON_MACHINE_GUN, seqId); // Allow client to shoot. player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::ENABLE_SHOOTING, WEAPON_MACHINE_GUN, seqId); // Save the currently selected weapon index. m_previousSelectedWeaponIndex = m_selectedWeaponIndex; // Set the currently selected weapon index to gun. m_selectedWeaponIndex = 0; // Set the current gun weapon to the current weapon. m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex]; const auto machineGunWeapon = Game::instance()->getWeaponManager()->get(WEAPON_MACHINE_GUN); m_weapons[0] = machineGunWeapon; auto& [first, second] = m_defaultAmmo[machineGunWeapon.itemId]; first = machineGunWeapon.clipCount; second = machineGunWeapon.clipSize; refillCurrentWeapon(); switchWeapon(machineGunWeapon.itemId, false); m_hasEquippedMachineGun = true; m_equippedMachineGunSeqId = seqId; } } void PlayerWeaponManager::unequipMachineGun() { // If the player does not have a machine gun equipped, do not allow them to unequip one. if (!m_hasEquippedMachineGun) { return; } if (const auto player = m_player.lock(); player != nullptr) { // Disallow the machine gun in public enemy mode for now. if (player->getRoomSession()->getGameMode()->isPublicEnemyMode()) { player->getPlayer()->broadcast(u"The machine gun is disabled in the public enemy gamemode."); return; } player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::UNEQUIP_MACHINE_GUN, WEAPON_MACHINE_GUN, m_equippedMachineGunSeqId); m_weapons[0] = m_currentRifleWeapon; m_selectedWeaponIndex = m_previousSelectedWeaponIndex; switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); m_hasEquippedMachineGun = false; m_equippedMachineGunSeqId = 0; } } void PlayerWeaponManager::equipRainbowSkillCardWeapon(uint32_t weaponId) { m_previousSelectedWeaponIndex = m_selectedWeaponIndex; m_selectedWeaponIndex = RIFLE_INDEX; m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex]; const auto weapon = Game::instance()->getWeaponManager()->get(weaponId); m_weapons[RIFLE_INDEX] = weapon; auto& [first, second] = m_defaultAmmo[weapon.itemId]; first = weapon.clipCount; second = weapon.clipSize; refillCurrentWeapon(); switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); } void PlayerWeaponManager::unequipRainbowSkillCardWeapon() { m_weapons[RIFLE_INDEX] = m_currentRifleWeapon; m_selectedWeaponIndex = m_previousSelectedWeaponIndex; switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); reset(); } bool PlayerWeaponManager::isHoldingMelee() const { return m_selectedWeaponIndex == 3; }
25.669468
164
0.748691
19202436500c1a6eb406fc35dc9d3f49f8601c6d
6,361
cpp
C++
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-15T01:14:15.000Z
2019-07-15T01:14:15.000Z
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
76
2018-10-27T16:59:36.000Z
2022-03-30T17:40:39.000Z
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-29T02:02:08.000Z
2019-07-29T02:02:08.000Z
#include "../../include/graphics/animation/CMeshAnimatorComponent.h" #include <tuple> namespace TDEngine2 { static const std::string ComponentTypeName = "mesh_animator"; const std::string CMeshAnimatorComponent::mPositionJointChannelPattern = "joint_{0}.position"; const std::string CMeshAnimatorComponent::mRotationJointChannelPattern = "joint_{0}.rotation"; const std::string& CMeshAnimatorComponent::GetPositionJointChannelPattern() { return mPositionJointChannelPattern; } const std::string& CMeshAnimatorComponent::GetRotationJointChannelPattern() { return mRotationJointChannelPattern; } const std::string& CMeshAnimatorComponent::GetComponentTypeName() { return ComponentTypeName; } CMeshAnimatorComponent::CMeshAnimatorComponent() : CBaseComponent() { } E_RESULT_CODE CMeshAnimatorComponent::Init() { if (mIsInitialized) { return RC_FAIL; } mIsDirty = true; mIsInitialized = true; return RC_OK; } E_RESULT_CODE CMeshAnimatorComponent::Load(IArchiveReader* pReader) { if (!pReader) { return RC_FAIL; } return RC_OK; } E_RESULT_CODE CMeshAnimatorComponent::Save(IArchiveWriter* pWriter) { if (!pWriter) { return RC_FAIL; } pWriter->BeginGroup("component"); { pWriter->SetUInt32("type_id", static_cast<U32>(CMeshAnimatorComponent::GetTypeId())); } pWriter->EndGroup(); return RC_OK; } void CMeshAnimatorComponent::SetDirtyFlag(bool value) { mIsDirty = value; } bool CMeshAnimatorComponent::IsDirty() const { return mIsDirty; } CMeshAnimatorComponent::TJointsMap& CMeshAnimatorComponent::GetJointsTable() { return mJointsTable; } CMeshAnimatorComponent::TJointPose& CMeshAnimatorComponent::GetCurrAnimationPose() { return mCurrAnimationPose; } const std::vector<TVector3>& CMeshAnimatorComponent::GetJointPositionsArray() const { return mJointsCurrPositions; } const std::vector<TQuaternion>& CMeshAnimatorComponent::GetJointRotationsArray() const { return mJointsCurrRotation; } enum class E_JOINT_PROPERTY_TYPE : U8 { POSITION, ROTATION }; static std::tuple<std::string, E_JOINT_PROPERTY_TYPE> GetJointInfoFromProperty(const std::string& propertyId) { auto p0 = propertyId.find_first_of('_') + 1; auto p1 = propertyId.find_first_of('.'); return { propertyId.substr(p0, p1 - p0), propertyId.substr(p1 + 1) == "position" ? E_JOINT_PROPERTY_TYPE::POSITION : E_JOINT_PROPERTY_TYPE::ROTATION }; } IPropertyWrapperPtr CMeshAnimatorComponent::GetProperty(const std::string& propertyName) { auto&& properties = GetAllProperties(); if (std::find_if(properties.cbegin(), properties.cend(), [&propertyName](const std::string& id) { return propertyName == id; }) == properties.cend()) { return CBaseComponent::GetProperty(propertyName); } std::string jointId; E_JOINT_PROPERTY_TYPE propertyType; std::tie(jointId, propertyType) = GetJointInfoFromProperty(propertyName); switch (propertyType) { case E_JOINT_PROPERTY_TYPE::POSITION: return IPropertyWrapperPtr(CBasePropertyWrapper<TVector3>::Create([this, jointId](const TVector3& pos) { _setPositionForJoint(jointId, pos); return RC_OK; }, nullptr)); case E_JOINT_PROPERTY_TYPE::ROTATION: return IPropertyWrapperPtr(CBasePropertyWrapper<TQuaternion>::Create([this, jointId](const TQuaternion& rot) { _setRotationForJoint(jointId, rot); return RC_OK; }, nullptr)); } return CBaseComponent::GetProperty(propertyName); } const std::vector<std::string>& CMeshAnimatorComponent::GetAllProperties() const { static std::vector<std::string> properties; if (properties.size() / 2 == mJointsTable.size()) { return properties; } properties.clear(); for (auto&& currJointEntity : mJointsTable) { properties.push_back(Wrench::StringUtils::Format(CMeshAnimatorComponent::mPositionJointChannelPattern, currJointEntity.first)); properties.push_back(Wrench::StringUtils::Format(CMeshAnimatorComponent::mRotationJointChannelPattern, currJointEntity.first)); } return properties; } const std::string& CMeshAnimatorComponent::GetTypeName() const { return ComponentTypeName; } void CMeshAnimatorComponent::_setPositionForJoint(const std::string& jointId, const TVector3& position) { auto it = mJointsTable.find(jointId); if (it == mJointsTable.cend()) { TDE2_ASSERT(false); return; } if (static_cast<U32>(mJointsCurrPositions.size()) <= it->second) { mJointsCurrPositions.resize(it->second + 1); } mJointsCurrPositions[it->second] = position; mIsDirty = true; } void CMeshAnimatorComponent::_setRotationForJoint(const std::string& jointId, const TQuaternion& rotation) { auto it = mJointsTable.find(jointId); if (it == mJointsTable.cend()) { TDE2_ASSERT(false); return; } if (static_cast<U32>(mJointsCurrRotation.size()) <= it->second) { mJointsCurrRotation.resize(it->second + 1); } mJointsCurrRotation[it->second] = rotation; mIsDirty = true; } IComponent* CreateMeshAnimatorComponent(E_RESULT_CODE& result) { return CREATE_IMPL(IComponent, CMeshAnimatorComponent, result); } CMeshAnimatorComponentFactory::CMeshAnimatorComponentFactory() : CBaseObject() { } E_RESULT_CODE CMeshAnimatorComponentFactory::Init() { if (mIsInitialized) { return RC_FAIL; } mIsInitialized = true; return RC_OK; } E_RESULT_CODE CMeshAnimatorComponentFactory::Free() { if (!mIsInitialized) { return RC_FAIL; } mIsInitialized = false; delete this; return RC_OK; } IComponent* CMeshAnimatorComponentFactory::Create(const TBaseComponentParameters* pParams) const { if (!pParams) { return nullptr; } const TMeshAnimatorComponentParameters* pAnimatorParams = static_cast<const TMeshAnimatorComponentParameters*>(pParams); E_RESULT_CODE result = RC_OK; return CreateMeshAnimatorComponent(result); } IComponent* CMeshAnimatorComponentFactory::CreateDefault(const TBaseComponentParameters& params) const { E_RESULT_CODE result = RC_OK; return CreateMeshAnimatorComponent(result); } TypeId CMeshAnimatorComponentFactory::GetComponentTypeId() const { return CMeshAnimatorComponent::GetTypeId(); } IComponentFactory* CreateMeshAnimatorComponentFactory(E_RESULT_CODE& result) { return CREATE_IMPL(IComponentFactory, CMeshAnimatorComponentFactory, result); } }
23.047101
178
0.748782
1921e6547eacf6dd5f124f74def4dd1d03fa4150
1,602
cpp
C++
19A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
19A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
19A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; typedef struct{string name;int poin,scored,missed;} team; string tim[111]; char mska[50],mskb[50],dummy; int N,x,ida,idb,a,b; team ans[111]; bool cfscore(team i,team j) { if(i.poin!=j.poin) return(i.poin>j.poin); if(i.scored-i.missed!=j.scored-j.missed) return(i.scored-i.missed>j.scored-j.missed); if(i.scored!=j.scored) return(i.scored>j.scored); return(i.name<j.name); } bool cfname(team i,team j) { return(i.name<j.name); } int main() { scanf("%d",&N); for(x=0;x<N;x++) { scanf("%s",mska); tim[x]=mska; } sort(tim,tim+N); for(x=0;x<N;x++) ans[x]=(team){tim[x],0,0,0}; for(x=1;2*x<=N*(N-1);x++) { getchar(); scanf("%[^-]%c%s %d:%d",mska,&dummy,mskb,&a,&b); ida=lower_bound(tim,tim+N,mska)-tim; idb=lower_bound(tim,tim+N,mskb)-tim; ans[ida].scored+=a,ans[ida].missed+=b; ans[idb].scored+=b,ans[idb].missed+=a; if(a==b) ans[ida].poin++,ans[idb].poin++; else if(a>b) ans[ida].poin+=3; else ans[idb].poin+=3; } sort(ans,ans+N,cfscore); sort(ans,ans+(N/2),cfname); for(x=0;2*x<N;x++) printf("%s\n",ans[x].name.c_str()); return 0; }
20.805195
87
0.615481
19246af50a74c6b82cb1838f92e719733b72179a
2,215
cpp
C++
cpp/main.cpp
adtalos/AITM-torch
9e8d4665ccd302e02ca0eba334419fbf3f5b7ba7
[ "Apache-2.0" ]
9
2021-08-19T05:44:11.000Z
2022-03-17T14:31:39.000Z
cpp/main.cpp
adtalos/AITM-torch
9e8d4665ccd302e02ca0eba334419fbf3f5b7ba7
[ "Apache-2.0" ]
2
2022-03-18T01:18:16.000Z
2022-03-25T06:21:03.000Z
cpp/main.cpp
adtalos/AITM-torch
9e8d4665ccd302e02ca0eba334419fbf3f5b7ba7
[ "Apache-2.0" ]
2
2021-08-19T04:43:40.000Z
2022-01-17T08:01:00.000Z
#include "aitm.h" #include <chrono> #include <iostream> #include <torch/script.h> int main() { std::unordered_map<std::string, torch::Tensor> inputs; inputs.insert({"101", torch::tensor({56460, 56460})}); inputs.insert({"121", torch::tensor({15, 15})}); inputs.insert({"122", torch::tensor({4, 4})}); inputs.insert({"124", torch::tensor({1, 1})}); inputs.insert({"125", torch::tensor({4, 4})}); inputs.insert({"126", torch::tensor({0, 0})}); inputs.insert({"127", torch::tensor({2, 2})}); inputs.insert({"128", torch::tensor({2, 2})}); inputs.insert({"129", torch::tensor({2, 2})}); inputs.insert({"205", torch::tensor({303798, 25006})}); inputs.insert({"206", torch::tensor({38, 5973})}); inputs.insert({"207", torch::tensor({133408, 101467})}); inputs.insert({"216", torch::tensor({23965, 51505})}); inputs.insert({"508", torch::tensor({2342, 1493})}); inputs.insert({"509", torch::tensor({0, 0})}); inputs.insert({"702", torch::tensor({0, 0})}); inputs.insert({"853", torch::tensor({2707, 4062})}); inputs.insert({"301", torch::tensor({3, 3})}); std::unordered_map<std::string, int64_t> feature_vocabulary = { {"101", 238635}, {"121", 98}, {"122", 14}, {"124", 3}, {"125", 8}, {"126", 4}, {"127", 4}, {"128", 3}, {"129", 5}, {"205", 467298}, {"206", 6929}, {"207", 263942}, {"216", 106399}, {"508", 5888}, {"509", 104830}, {"702", 51878}, {"853", 37148}, {"301", 4}, }; std::string modelfile ="../../python/out/AITM.model.pt"; torch::NoGradGuard no_grad; std::shared_ptr<AITM> model = std::make_shared<AITM>(feature_vocabulary, 5); loadAITM(model, modelfile); model->eval(); auto s = model->forward(inputs); std::cout << s.first << " second: " << s.second << "\n"; auto start = std::chrono::high_resolution_clock::now(); for (int i = 0; i < 10; i++) { auto res = model->forward(inputs); } auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); std::cout << "Predict Cost: " << duration.count() << " microseconds" << std::endl; std::cout << "finish \n"; return 0; }
39.553571
78
0.579684
192792ac79a3b689427d4827807f3490eaf2a12b
1,443
cc
C++
raytracing/geometry.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
1
2019-04-14T11:40:28.000Z
2019-04-14T11:40:28.000Z
raytracing/geometry.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
5
2018-04-18T13:54:29.000Z
2019-08-22T20:04:17.000Z
raytracing/geometry.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
1
2018-12-24T03:45:47.000Z
2018-12-24T03:45:47.000Z
#include "geometry.hh" namespace raytrace { using Vec2 = Eigen::Vector2d; double cross2d(const Vec2 &a, const Vec2 &b) { return (a(0) * b(1)) - (a(1) * b(0)); } bool ray_line_intersection(const Ray &ray, const Line &line, Out<Vec2> intersection) { Eigen::Matrix2d A; A.col(0) = ray.direction; A.col(1) = -line.direction; const Vec2 b = line.point - ray.origin; const Eigen::ColPivHouseholderQR<Eigen::Matrix2d> qr = A.colPivHouseholderQr(); // This takes FOREVER to compile (I guess Eigen inlines the whole operation?) // Lines are parallel if (qr.absDeterminant() < 1e-3) { return false; } const Vec2 soln = qr.solve(b); *intersection = soln(0) * ray.direction + ray.origin; // Ray pointing the wrong direction if (soln(0) < 0.0) { return false; } return true; } bool ray_line_segment_intersection(const Ray &ray, const LineSegment &segment, Out<Vec2> intersection) { const Line temp_line(segment.start, segment.end - segment.start); const bool valid_intersection = ray_line_intersection(ray, temp_line, intersection); if (valid_intersection) { const double half_space_start = (*intersection - segment.start).dot(temp_line.direction); const double half_space_end = (*intersection - segment.end).dot(temp_line.direction); if ((half_space_start > 0.0) && (half_space_end < 0.0)) { return true; } } return false; } }
28.294118
104
0.668053
192db529428201d58d905a62921de0c632fa449b
1,927
cc
C++
cpp/src/arrow/compute/exec/accumulation_queue.cc
AlvinJ15/arrow
095179f8a38f99e2eb10a59ad7e71252d8491e8f
[ "Apache-2.0" ]
1
2021-11-24T04:43:52.000Z
2021-11-24T04:43:52.000Z
cpp/src/arrow/compute/exec/accumulation_queue.cc
AlvinJ15/arrow
095179f8a38f99e2eb10a59ad7e71252d8491e8f
[ "Apache-2.0" ]
null
null
null
cpp/src/arrow/compute/exec/accumulation_queue.cc
AlvinJ15/arrow
095179f8a38f99e2eb10a59ad7e71252d8491e8f
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/compute/exec/accumulation_queue.h" #include <iterator> namespace arrow { namespace util { using arrow::compute::ExecBatch; AccumulationQueue::AccumulationQueue(AccumulationQueue&& that) { this->batches_ = std::move(that.batches_); this->row_count_ = that.row_count_; that.Clear(); } AccumulationQueue& AccumulationQueue::operator=(AccumulationQueue&& that) { this->batches_ = std::move(that.batches_); this->row_count_ = that.row_count_; that.Clear(); return *this; } void AccumulationQueue::Concatenate(AccumulationQueue&& that) { this->batches_.reserve(this->batches_.size() + that.batches_.size()); std::move(that.batches_.begin(), that.batches_.end(), std::back_inserter(this->batches_)); this->row_count_ += that.row_count_; that.Clear(); } void AccumulationQueue::InsertBatch(ExecBatch batch) { row_count_ += batch.length; batches_.emplace_back(std::move(batch)); } void AccumulationQueue::Clear() { row_count_ = 0; batches_.clear(); } ExecBatch& AccumulationQueue::operator[](size_t i) { return batches_[i]; } } // namespace util } // namespace arrow
32.661017
75
0.737416
192ee663eb16a798a38f768cb86e6c158d838f2a
88
cpp
C++
problemsets/Codeforces/C++/C1360.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codeforces/C++/C1360.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codeforces/C++/C1360.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */
12.571429
38
0.625
192fa1261098731268c3405b3a731b39d25d8a31
847
cpp
C++
clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.grammar/p2-1z.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 -std=c++1z -verify %s [[disable_tail_calls, noduplicate]] void f() {} // expected-warning {{unknown attribute 'disable_tail_calls'}} expected-warning {{unknown attribute 'noduplicate'}} [[using clang: disable_tail_calls, noduplicate]] void g() {} // ok [[using]] extern int n; // expected-error {{expected identifier}} [[using foo ] // expected-error {{expected ':'}} ] extern int n; [[using 42:]] extern int n; // expected-error {{expected identifier}} [[using clang:]] extern int n; // ok [[using blah: clang::optnone]] extern int n; // expected-error {{attribute with scope specifier cannot follow}} expected-warning {{only applies to functions}} [[using clang: unknown_attr]] extern int n; // expected-warning {{unknown attribute}} [[using unknown_ns: something]] extern int n; // expected-warning {{unknown attribute}}
49.823529
163
0.707202
1930b9cdd5fdfc4442f2e9abf0c26280cc8f2787
196
cpp
C++
10.10-span0/main.cpp
andreasfertig/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
107
2021-04-13T12:43:06.000Z
2022-03-30T05:07:16.000Z
10.10-span0/main.cpp
jessesimpson/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
1
2021-04-13T12:59:30.000Z
2021-04-13T13:02:55.000Z
10.10-span0/main.cpp
jessesimpson/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
29
2021-04-13T18:07:03.000Z
2022-03-28T13:44:01.000Z
// Copyright (c) Andreas Fertig. // SPDX-License-Identifier: MIT #include <cstddef> template<typename T> class Span { T* mData; size_t mSize; public: // constructors }; int main() {}
13.066667
32
0.658163
1931129329fd5b84da776098dce6603e6732fe41
20,685
cpp
C++
vtkdiff.cpp
ufz/vtkdiff
8b7bfce2f2302263c9fdc0201f765e375c8a8a36
[ "BSD-4-Clause" ]
1
2021-03-08T00:35:07.000Z
2021-03-08T00:35:07.000Z
vtkdiff.cpp
ufz/vtkdiff
8b7bfce2f2302263c9fdc0201f765e375c8a8a36
[ "BSD-4-Clause" ]
3
2015-06-05T13:09:05.000Z
2016-09-26T19:50:16.000Z
vtkdiff.cpp
ufz/vtkdiff
8b7bfce2f2302263c9fdc0201f765e375c8a8a36
[ "BSD-4-Clause" ]
5
2016-06-01T15:32:56.000Z
2022-03-20T04:22:30.000Z
/** * \copyright * Copyright (c) 2015-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license */ #include <algorithm> #include <cmath> #include <cstdlib> #include <iomanip> #include <ios> #include <iterator> #include <sstream> #include <tuple> #include <type_traits> #include <tclap/CmdLine.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkCommand.h> #include <vtkDataArray.h> #include <vtkDoubleArray.h> #include <vtkPointData.h> #include <vtkSmartPointer.h> #include <vtkUnstructuredGrid.h> #include <vtkVersion.h> #include <vtkXMLUnstructuredGridReader.h> template <typename T> auto float_to_string(T const& v) -> std::string { static_assert(std::is_floating_point<T>::value, "float_to_string requires a floating point input type."); std::stringstream double_eps_sstream; double_eps_sstream << std::scientific << std::setprecision(16) << v; return double_eps_sstream.str(); } bool stringEndsWith(std::string const& str, std::string const& ending) { if (str.length() < ending.length()) return false; // now the difference is non-negative, no underflow possible. auto const string_end_length = str.length() - ending.length(); return str.compare(string_end_length, ending.length(), ending) == 0; } template <typename T> std::ostream& operator<<(std::ostream& os, std::vector<T> const& vector) { if (vector.empty()) { return os << "[]"; } // print first n-1 elements os << "["; std::size_t const size = vector.size(); for (std::size_t i = 0; i < size - 1; ++i) { os << vector[i] << ", "; } return os << vector.back() << "]"; } struct Args { bool const quiet; bool const verbose; bool const meshcheck; double const abs_err_thr; double const rel_err_thr; std::string const vtk_input_a; std::string const vtk_input_b; std::string const data_array_a; std::string const data_array_b; }; auto parseCommandLine(int argc, char* argv[]) -> Args { TCLAP::CmdLine cmd( "VtkDiff software.\n" "Copyright (c) 2015-2021, OpenGeoSys Community " "(http://www.opengeosys.org) " "Distributed under a Modified BSD License. " "See accompanying file LICENSE.txt or " "http://www.opengeosys.org/project/license", ' ', "0.1"); TCLAP::UnlabeledValueArg<std::string> vtk_input_a_arg( "input-file-a", "Path to the VTK unstructured grid input file.", true, "", "VTK FILE"); cmd.add(vtk_input_a_arg); TCLAP::UnlabeledValueArg<std::string> vtk_input_b_arg( "input-file-b", "Path to the second VTK unstructured grid input file.", false, "", "VTK FILE"); cmd.add(vtk_input_b_arg); TCLAP::ValueArg<std::string> data_array_a_arg( "a", "first_data_array", "First data array name for comparison", true, "", "NAME"); TCLAP::ValueArg<std::string> data_array_b_arg( "b", "second_data_array", "Second data array name for comparison", false, "", "NAME"); cmd.add(data_array_b_arg); TCLAP::SwitchArg meshcheck_arg( "m", "mesh_check", "Compare mesh geometries using absolute tolerance."); cmd.xorAdd(data_array_a_arg, meshcheck_arg); TCLAP::SwitchArg quiet_arg("q", "quiet", "Suppress all but error output."); cmd.add(quiet_arg); TCLAP::SwitchArg verbose_arg("v", "verbose", "Also print which values differ."); cmd.add(verbose_arg); auto const double_eps_string = float_to_string(std::numeric_limits<double>::epsilon()); TCLAP::ValueArg<double> abs_err_thr_arg( "", "abs", "Tolerance for the absolute error in the maximum norm (" + double_eps_string + ")", false, std::numeric_limits<double>::epsilon(), "FLOAT"); cmd.add(abs_err_thr_arg); TCLAP::ValueArg<double> rel_err_thr_arg( "", "rel", "Tolerance for the componentwise relative error (" + double_eps_string + ")", false, std::numeric_limits<double>::epsilon(), "FLOAT"); cmd.add(rel_err_thr_arg); cmd.parse(argc, argv); return Args{quiet_arg.getValue(), verbose_arg.getValue(), meshcheck_arg.getValue(), abs_err_thr_arg.getValue(), rel_err_thr_arg.getValue(), vtk_input_a_arg.getValue(), vtk_input_b_arg.getValue(), data_array_a_arg.getValue(), data_array_b_arg.getValue()}; } template <typename T> class ErrorCallback : public vtkCommand { public: vtkTypeMacro(ErrorCallback, vtkCommand); static ErrorCallback<T>* New() { return new ErrorCallback<T>; } void Execute(vtkObject* caller, unsigned long vtkNotUsed(eventId), void* callData) override { auto* reader = static_cast<T*>(caller); std::cerr << "Error reading file `" << reader->GetFileName() << "'\n" << static_cast<char*>(callData) << "\nAborting." << std::endl; std::exit(2); } }; vtkSmartPointer<vtkUnstructuredGrid> readMesh(std::string const& filename) { if (filename.empty()) { return nullptr; } if (!stringEndsWith(filename, ".vtu")) { std::cerr << "Error: Expected a file with .vtu extension." << "File '" << filename << "' not read."; return nullptr; } vtkSmartPointer<ErrorCallback<vtkXMLUnstructuredGridReader>> errorCallback = vtkSmartPointer<ErrorCallback<vtkXMLUnstructuredGridReader>>::New(); vtkSmartPointer<vtkXMLUnstructuredGridReader> reader = vtkSmartPointer<vtkXMLUnstructuredGridReader>::New(); reader->AddObserver(vtkCommand::ErrorEvent, errorCallback); reader->SetFileName(filename.c_str()); reader->Update(); return reader->GetOutput(); } std::tuple<vtkSmartPointer<vtkUnstructuredGrid>, vtkSmartPointer<vtkUnstructuredGrid>> readMeshes(std::string const& file_a_name, std::string const& file_b_name) { return {readMesh(file_a_name), readMesh(file_b_name)}; } std::tuple<bool, vtkSmartPointer<vtkDataArray>, vtkSmartPointer<vtkDataArray>> readDataArraysFromMeshes( std::tuple<vtkSmartPointer<vtkUnstructuredGrid>, vtkSmartPointer<vtkUnstructuredGrid>> const& meshes, std::string const& data_array_a_name, std::string const& data_array_b_name) { if (std::get<0>(meshes) == nullptr) { std::cerr << "First mesh was not read correctly and is a nullptr.\n"; return {false, nullptr, nullptr}; } bool point_data(false); if (std::get<0>(meshes)->GetPointData()->HasArray( data_array_a_name.c_str())) { point_data = true; } else if (std::get<0>(meshes)->GetCellData()->HasArray( data_array_a_name.c_str())) { point_data = false; } else { std::cerr << "Error: Scalars data array " << "\'" << data_array_a_name.c_str() << "\'" << " neither found in point data nor in cell data.\n"; return std::make_tuple(false, nullptr, nullptr); } // Get arrays vtkSmartPointer<vtkDataArray> a; if (point_data) { a = vtkSmartPointer<vtkDataArray>{ std::get<0>(meshes)->GetPointData()->GetScalars( data_array_a_name.c_str())}; } else { a = vtkSmartPointer<vtkDataArray>{ std::get<0>(meshes)->GetCellData()->GetScalars( data_array_a_name.c_str())}; } // Check arrays' validity if (!a) { std::cerr << "Error: Scalars data array " << "\'" << data_array_a_name.c_str() << "\'" << " could not be read.\n"; return std::make_tuple(false, nullptr, nullptr); } vtkSmartPointer<vtkDataArray> b; if (std::get<1>(meshes) == nullptr) { if (data_array_a_name == data_array_b_name) { std::cerr << "Error: You are trying to compare data array `" << data_array_a_name << "' from first file to itself. Aborting.\n"; std::exit(3); } if (point_data) { b = vtkSmartPointer<vtkDataArray>{ std::get<0>(meshes)->GetPointData()->GetScalars( data_array_b_name.c_str())}; } else { b = vtkSmartPointer<vtkDataArray>{ std::get<0>(meshes)->GetCellData()->GetScalars( data_array_b_name.c_str())}; } } else { if (point_data) { b = vtkSmartPointer<vtkDataArray>{ std::get<1>(meshes)->GetPointData()->GetScalars( data_array_b_name.c_str())}; } else { b = vtkSmartPointer<vtkDataArray>{ std::get<1>(meshes)->GetCellData()->GetScalars( data_array_b_name.c_str())}; } } if (!b) { std::cerr << "Error: Scalars data array " << "\'" << data_array_b_name.c_str() << "\'" << " not found.\n"; return std::make_tuple(false, nullptr, nullptr); } return std::make_tuple(true, a, b); } bool compareCellTopology(vtkCellArray* const cells_a, vtkCellArray* const cells_b) { vtkIdType const n_cells_a{cells_a->GetNumberOfCells()}; vtkIdType const n_cells_b{cells_b->GetNumberOfCells()}; if (n_cells_a != n_cells_b) { std::cerr << "Number of cells in the first mesh is " << n_cells_a << " and differs from the number of cells in the second " "mesh, which is " << n_cells_b << "\n"; return false; } vtkIdType n_cell_points_a, n_cell_points_b; #if (VTK_MAJOR_VERSION > 8 || VTK_MINOR_VERSION == 90) const vtkIdType *cell_points_a, *cell_points_b; #else vtkIdType *cell_points_a, *cell_points_b; #endif cells_a->InitTraversal(); cells_b->InitTraversal(); int get_next_cell_a = cells_a->GetNextCell(n_cell_points_a, cell_points_a); int get_next_cell_b = cells_b->GetNextCell(n_cell_points_b, cell_points_b); int cell_number = 0; while (get_next_cell_a == 1 && get_next_cell_b == 1) { if (n_cell_points_a != n_cell_points_b) { std::cerr << "Cell " << cell_number << " in first input has " << n_cell_points_a << " points but in the second input " << n_cell_points_b << " points.\n"; } for (vtkIdType i = 0; i < n_cell_points_a; ++i) { if (cell_points_a[i] != cell_points_b[i]) { std::cerr << "Point " << i << " of cell " << cell_number << " has id " << cell_points_a[i] << " in the first input but id " << cell_points_b[i] << " in the second input.\n"; return false; } } get_next_cell_a = cells_a->GetNextCell(n_cell_points_a, cell_points_a); get_next_cell_b = cells_b->GetNextCell(n_cell_points_b, cell_points_b); cell_number++; } if (get_next_cell_a != 0) { std::cerr << "Unexpected return value (" << get_next_cell_a << ") for cells_a->GetNextCell() call. Expected 0 for " "end-of-list or 1 for no error.\n"; return false; } if (get_next_cell_b != 0) { std::cerr << "Unexpected return value (" << get_next_cell_b << ") for cells_b->GetNextCell() call. Expected 0 for " "end-of-list or 1 for no error.\n"; return false; } return true; } bool comparePoints(vtkPoints* const points_a, vtkPoints* const points_b, double const eps_squared) { vtkIdType const n_points_a{points_a->GetNumberOfPoints()}; vtkIdType const n_points_b{points_b->GetNumberOfPoints()}; if (n_points_a != n_points_b) { std::cerr << "Number of points in the first mesh is " << n_points_a << " and differst from the number of point in the second " "mesh, which is " << n_points_b << "\n"; return false; } for (vtkIdType p = 0; p < n_points_a; ++p) { auto const a = points_a->GetPoint(p); auto const b = points_b->GetPoint(p); double const distance2 = vtkMath::Distance2BetweenPoints(a, b); if (distance2 >= eps_squared) { std::cerr << "Point " << p << " with coordinates (" << a[0] << ", " << a[1] << ", " << a[2] << ") from the first mesh is significantly different " "from the same point in the second mesh, which " "has coordinates (" << b[0] << ", " << b[1] << ", " << b[2] << ") with distance between them " << std::sqrt(distance2) << "\n"; return false; } } return true; } int main(int argc, char* argv[]) { auto const digits10 = std::numeric_limits<double>::digits10; auto const args = parseCommandLine(argc, argv); // Setup the standard output and error stream numerical formats. std::cout << std::scientific << std::setprecision(digits10); std::cerr << std::scientific << std::setprecision(digits10); auto meshes = readMeshes(args.vtk_input_a, args.vtk_input_b); if (args.meshcheck) { if (args.vtk_input_a == args.vtk_input_b) { std::cout << "Will not compare meshes from same input file.\n"; return EXIT_SUCCESS; } if (!comparePoints(std::get<0>(meshes)->GetPoints(), std::get<1>(meshes)->GetPoints(), args.abs_err_thr * args.abs_err_thr)) { std::cerr << "Error in mesh points' comparison occured.\n"; return EXIT_FAILURE; } if (!compareCellTopology(std::get<0>(meshes)->GetCells(), std::get<1>(meshes)->GetCells())) { std::cerr << "Error in cells' topology comparison occured.\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } // Read arrays from input file. bool read_successful; vtkSmartPointer<vtkDataArray> a; vtkSmartPointer<vtkDataArray> b; std::tie(read_successful, a, b) = readDataArraysFromMeshes(meshes, args.data_array_a, args.data_array_b); if (!read_successful) return EXIT_FAILURE; if (!args.quiet) std::cout << "Comparing data array `" << args.data_array_a << "' from file `" << args.vtk_input_a << "' to data array `" << args.data_array_b << "' from file `" << args.vtk_input_b << "'.\n"; // Check similarity of the data arrays. // Is numeric if (!a->IsNumeric()) { std::cerr << "Data in data array a is not numeric:\n" << "data type is " << a->GetDataTypeAsString() << "\n"; return EXIT_FAILURE; } if (!b->IsNumeric()) { std::cerr << "Data in data array b is not numeric.\n" << "data type is " << b->GetDataTypeAsString() << "\n"; return EXIT_FAILURE; } auto const num_tuples = a->GetNumberOfTuples(); // Number of components if (num_tuples != b->GetNumberOfTuples()) { std::cerr << "Number of tuples differ:\n" << num_tuples << " in data array a and " << b->GetNumberOfTuples() << " in data array b\n"; return EXIT_FAILURE; } auto const num_components = a->GetNumberOfComponents(); // Number of components if (num_components != b->GetNumberOfComponents()) { std::cerr << "Number of components differ:\n" << num_components << " in data array a and " << b->GetNumberOfComponents() << " in data array b\n"; return EXIT_FAILURE; } // Calculate difference of the data arrays. // Absolute error and norms. std::vector<double> abs_err_norm_l1(num_components); std::vector<double> abs_err_norm_2_2(num_components); std::vector<double> abs_err_norm_max(num_components); // Relative error and norms. std::vector<double> rel_err_norm_l1(num_components); std::vector<double> rel_err_norm_2_2(num_components); std::vector<double> rel_err_norm_max(num_components); for (auto tuple_idx = 0; tuple_idx < num_tuples; ++tuple_idx) { for (auto component_idx = 0; component_idx < num_components; ++component_idx) { auto const a_comp = a->GetComponent(tuple_idx, component_idx); auto const b_comp = b->GetComponent(tuple_idx, component_idx); auto const abs_err = std::abs(a_comp - b_comp); abs_err_norm_l1[component_idx] += abs_err; abs_err_norm_2_2[component_idx] += abs_err * abs_err; abs_err_norm_max[component_idx] = std::max(abs_err_norm_max[component_idx], abs_err); // relative error and its norms: double rel_err; if (abs_err == 0.0) { rel_err = 0.0; } else if (a_comp == 0.0 || b_comp == 0.0) { rel_err = std::numeric_limits<double>::infinity(); } else { rel_err = abs_err / std::min(std::abs(a_comp), std::abs(b_comp)); } rel_err_norm_l1[component_idx] += rel_err; rel_err_norm_2_2[component_idx] += rel_err * rel_err; rel_err_norm_max[component_idx] = std::max(rel_err_norm_max[component_idx], rel_err); if (abs_err > args.abs_err_thr && rel_err > args.rel_err_thr && args.verbose) { std::cout << "tuple: " << std::setw(4) << tuple_idx << "component: " << std::setw(2) << component_idx << ": abs err = " << std::setw(digits10 + 7) << abs_err << ", rel err = " << std::setw(digits10 + 7) << rel_err << "\n"; } } } // Error information if (!args.quiet) { std::cout << "Computed difference between data arrays:\n"; std::cout << "abs l1 norm = " << abs_err_norm_l1 << "\n"; std::cout << "abs l2-norm^2 = " << abs_err_norm_2_2 << "\n"; // temporary squared norm vector for output. std::vector<double> abs_err_norm_2; std::transform(std::begin(abs_err_norm_2_2), std::end(abs_err_norm_2_2), std::back_inserter(abs_err_norm_2), [](double x) { return std::sqrt(x); }); std::cout << "abs l2-norm = " << abs_err_norm_2 << "\n"; std::cout << "abs maximum norm = " << abs_err_norm_max << "\n"; std::cout << "\n"; std::cout << "rel l1 norm = " << rel_err_norm_l1 << "\n"; std::cout << "rel l2-norm^2 = " << rel_err_norm_2_2 << "\n"; // temporary squared norm vector for output. std::vector<double> rel_err_norm_2; std::transform(std::begin(rel_err_norm_2_2), std::end(rel_err_norm_2_2), std::back_inserter(rel_err_norm_2), [](double x) { return std::sqrt(x); }); std::cout << "rel l2-norm = " << rel_err_norm_2_2 << "\n"; std::cout << "rel maximum norm = " << rel_err_norm_max << "\n"; } if (*std::max_element(abs_err_norm_max.begin(), abs_err_norm_max.end()) > args.abs_err_thr && *std::max_element(rel_err_norm_max.begin(), rel_err_norm_max.end()) > args.rel_err_thr) { if (!args.quiet) std::cout << "Absolute and relative error (maximum norm) are larger" " than the corresponding thresholds " << args.abs_err_thr << " and " << args.rel_err_thr << ".\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; }
33.096
80
0.562388
19312e28c17a1befa02f080f5fd4c09660436f0f
209
cpp
C++
src/algorithm_list.cpp
GoncaloFDS/Lift
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
[ "BSD-3-Clause" ]
30
2019-07-24T09:58:22.000Z
2021-09-03T08:20:22.000Z
src/algorithm_list.cpp
GoncaloFDS/Lift
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
[ "BSD-3-Clause" ]
15
2020-06-20T13:20:50.000Z
2021-04-26T16:05:33.000Z
src/algorithm_list.cpp
GoncaloFDS/Lift
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
[ "BSD-3-Clause" ]
5
2020-06-17T08:38:34.000Z
2021-09-08T22:14:02.000Z
#include "algorithm_list.h" const std::vector<std::pair<std::string, Algorithm>> AlgorithmList::all_algorithms = { {"Path Tracing", Algorithm::PT}, {"Bidirectional Path Tracing", Algorithm::BDPT}, };
29.857143
86
0.703349
193544cc9f9e2b529c13ba814c29132be07d032b
2,331
hpp
C++
src/cpu/rtweekend.hpp
DveloperY0115/ray-tracing-in-one-weekend-cpp
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
[ "MIT" ]
1
2021-02-18T08:38:21.000Z
2021-02-18T08:38:21.000Z
src/cpu/rtweekend.hpp
DveloperY0115/ray-tracing-in-one-weekend-cpp
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
[ "MIT" ]
1
2021-02-13T04:42:01.000Z
2021-02-13T04:42:01.000Z
src/cpu/rtweekend.hpp
DveloperY0115/ray-tracing-in-one-weekend-cpp
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
[ "MIT" ]
null
null
null
// // Created by 유승우 on 2020/05/15. // #ifndef FIRSTRAYTRACER_RTWEEKEND_HPP #define FIRSTRAYTRACER_RTWEEKEND_HPP #include <cmath> #include <cstdlib> #include <limits> #include <memory> #include <random> #include <time.h> // using statements to make codes more simple using std::shared_ptr; using std::make_shared; using std::sqrt; // Constants const double infinity = std::numeric_limits<double>::infinity(); const double pi = 3.1415926535897932385; // Utility Functions /** * Clamps the value 'x' to the interval specified by ['min', 'max'] * * If 'x' is smaller than the lower bound 'min', it's clamped to the value 'min' * else if 'x' is greater than the upper bound 'max', it's clamped to the value 'max', * otherwise 'x' retains its own value since it doesn't needed to be clamped * * @param x a double type value that is needed to be clamped * @param min the lower bound of the interval * @param max the upper bound of the interval * @return clamped value */ inline double clamp(double x, double min, double max) { if (x < min) return min; if (x > max) return max; return x; } /** * Generates a double type random number whose value lies between 0.0 and 1.0. * @return a double type value between 0.0 and 1.0 */ inline double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } /* inline double random_double() { // Returns a random real number in [0, 1). return rand() / (RAND_MAX + 1.0); } */ /** * Generates a double type random number whose value lies between 'min' and 'max' * * @param min the lower bound for a desired random number * @param max the upper bound for a desired random number * @return a double type randomly generated number within the interval ['min', 'max'] */ inline double random_double(double min, double max) { // Returns a random real number in [min, max) return min + (max-min)*random_double(); } /** * Converts the angle represented in degrees to radian * * @param degrees an angle in degrees * @return same angle but in radian */ inline double degress_to_radians(double degrees) { return degrees * (pi / 180); } // Common Headers #include "ray.hpp" #include "vector3.hpp" #endif //FIRSTRAYTRACER_RTWEEKEND_HPP
24.536842
86
0.703561
19362a415c4f270b9dd8242a379cd7cd98c7e858
564
cpp
C++
main.cpp
mmarszik/01ToBin
9a1b0a792385b3f051cf462564dfebc2a391ae62
[ "MIT" ]
null
null
null
main.cpp
mmarszik/01ToBin
9a1b0a792385b3f051cf462564dfebc2a391ae62
[ "MIT" ]
null
null
null
main.cpp
mmarszik/01ToBin
9a1b0a792385b3f051cf462564dfebc2a391ae62
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #define SIZE_OUT (1<<12) #define SIZE_INP (SIZE_OUT*8) int main() { char buff_out[SIZE_OUT]; char buff_inp[SIZE_INP]; while( fread(buff_inp,SIZE_INP,1,stdin) == 1 ) { for( int i=0 ; i<SIZE_INP ; i++ ) { if( buff_inp[i] != '0' && buff_inp[i] != '1' ) { abort(); } buff_out[i/8] <<= 1; buff_out[i/8] |= buff_inp[i] == '1'; } if( fwrite(buff_out,SIZE_OUT,1,stdout) != 1 ) { break; } } return 0; }
20.888889
60
0.473404
1937294b0fbbd690599e20cd5d73e9c10dce5c45
1,839
tpp
C++
include/Sirius/Math/Matrix/Matrix2.tpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
1
2021-07-12T11:53:06.000Z
2021-07-12T11:53:06.000Z
include/Sirius/Math/Matrix/Matrix2.tpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
null
null
null
include/Sirius/Math/Matrix/Matrix2.tpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
1
2021-07-12T11:51:53.000Z
2021-07-12T11:51:53.000Z
#include "Matrix2.hpp" namespace Sirius { template<typename T> constexpr Matrix<2, T> operator+(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2) { return Matrix<2, T>(mat1[0] + mat2[0], mat1[1] + mat2[1]); } template<typename T> constexpr Matrix<2, T> operator-(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2) { return Matrix<2, T>(mat1[0] - mat2[0], mat1[1] - mat2[1]); } template<typename T> constexpr Matrix<2, T> operator*(const Matrix<2, T>& mat, T scalar) { return { mat[0] * scalar, mat[1] * scalar }; } template<typename T> constexpr Matrix<2, T> operator*(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2) { return { mat1[0][0] * mat2[0][0] + mat1[1][0] * mat2[0][1], mat1[0][1] * mat2[0][0] + mat1[1][1] * mat2[0][1], mat1[0][0] * mat2[1][0] + mat1[1][0] * mat2[1][1], mat1[0][1] * mat2[1][0] + mat1[1][1] * mat2[1][1] }; } template<typename T> constexpr Vector<2, T> operator*(const Matrix<2, T>& mat, const Vector<2, T>& vec) { return { mat[0][0] * vec.x + mat[1][0] * vec.y, mat[0][1] * vec.x + mat[1][1] * vec.y }; } } template <typename T> struct fmt::formatter<Sirius::Matrix<2, T>> { constexpr auto parse(format_parse_context& ctx) { return ctx.end(); } template <typename Context> auto format(const Sirius::Matrix<2, T>& mat, Context& ctx) { return format_to(ctx.out(), "\n\t[{} {}]\n\t[{} {}]", mat[0][0], mat[1][0], mat[0][1], mat[1][1]); } }; template<typename T> std::ostream& operator<<(std::ostream& out, const Sirius::Matrix<2, T>& mat) { return out << "[" << mat[0][0] << " " << mat[1][0] << "]\n[" << mat[0][1] << " " << mat[1][1] << "]"; }
29.66129
106
0.516041
193898f97013de96c717a848897f6a54e2d1b516
17,785
cpp
C++
co-op/CmdVector.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
co-op/CmdVector.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
co-op/CmdVector.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//---------------------------------- // (c) Reliable Software 1997 - 2008 //---------------------------------- #include "precompiled.h" #include "CmdVector.h" #include "Commander.h" // Code Co-op Commands namespace Cmd { const Cmd::Item<Commander> Table [] = { { "Program_Update", &Commander::Program_Update, 0, "Check for Co-op updates on the Internet" }, { "Program_Options", &Commander::Program_Options, 0, "View/Change program options" }, { "Program_Dispatching", &Commander::Program_Dispatching, 0, "View/Change script dispatching options" }, { "Program_Licensing", &Commander::Program_Licensing, 0, "Go to Web site to purchase license(s)" }, { "Program_About", &Commander::Program_About, 0, "About this program" }, { "Program_Exit", &Commander::Program_Exit, 0, "Exit program" }, { "Project_Visit", &Commander::Project_Visit, &Commander::can_Project_Visit, "Visit another project on this machine" }, { "Project_Move", &Commander::Project_Move, &Commander::can_Project_Move, "Move project tree to another location" }, { "Project_Repair", &Commander::Project_Repair, &Commander::can_Project_Repair, "Repair project file(s)" }, { "Project_RequestVerification", &Commander::Project_RequestVerification, &Commander::can_Project_RequestVerification, "Request project verification data from some other project member" }, { "Project_VerifyRootPaths",&Commander::Project_VerifyRootPaths,0, "Check if all projects have a valid root path" }, { "Project_Join", &Commander::Project_Join, 0, "Join an existing project" }, { "Project_Invite", &Commander::Project_Invite, &Commander::can_Project_Invite, "Invite someone to join your project" }, { "Project_OpenInvitation", &Commander::Project_OpenInvitation, 0, "Download project invitation" }, { "Project_New", &Commander::Project_New, 0, "Start a new project" }, { "Project_Branch", &Commander::Project_Branch, &Commander::can_Project_Branch, "Start a branch project" }, { "Project_Export", &Commander::Project_Export, &Commander::can_Project_Export, "Export project files and folders" }, { "Project_Members", &Commander::Project_Members, &Commander::can_Project_Members, "List/Edit project members' info" }, { "Project_Defect", &Commander::Project_Defect, &Commander::can_Project_Defect, "Rescind your membership in this project" }, { "Project_Admin", &Commander::Project_Admin, &Commander::can_Project_Admin, "Emergency project administrator election" }, { "Project_Options", &Commander::Project_Options, &Commander::can_Project_Options, "View/Change project options" }, { "Project_AddMoreFiles", &Commander::Project_AddMoreFiles, &Commander::can_Project_AddMoreFiles,"Add more files to the project" }, { "Project_NewFromHistory", &Commander::Project_NewFromHistory, &Commander::can_Project_NewFromHistory,"Start a new project from previously exported history" }, { "History_Export", &Commander::History_ExportHistory, &Commander::can_History_Export, "Export project history" }, { "History_Import", &Commander::History_ImportHistory, &Commander::can_History_Import, "Import project history" }, { "History_AddLabel", &Commander::History_AddLabel, &Commander::can_History_AddLabel, "Label project version" }, { "View_Back", &Commander::View_Back, &Commander::can_View_Back, "Navigate back" }, { "View_Forward", &Commander::View_Forward, &Commander::can_View_Forward, "Navigate forward" }, { "View_Home", &Commander::View_Home, &Commander::can_View_Home, "Navigate home" }, { "View_Refresh", &Commander::View_Refresh, &Commander::can_View_Refresh, "Update displayed information" }, { "View_ApplyFileFilter", &Commander::View_ApplyFileFilter, &Commander::can_View_ApplyFileFilter,"Apply file filter" }, { "View_ChangeFileFilter", &Commander::View_ChangeFileFilter, &Commander::can_View_ChangeFileFilter,"Change file filter" }, { "View_Browser", &Commander::View_Browser, &Commander::can_View_Browser, "View web page" }, { "View_Files", &Commander::View_Files, &Commander::can_View_Files, "Browse through files in the project" }, { "View_Mailbox", &Commander::View_Mailbox, &Commander::can_View_Mailbox, "Look at outgoing/incoming scripts" }, { "View_CheckIn", &Commander::View_CheckIn, &Commander::can_View_CheckIn, "Look at checked-out files" }, { "View_Synch", &Commander::View_Synch, &Commander::can_View_Synch, "Look at files changed by the sync" }, { "View_History", &Commander::View_History, &Commander::can_View_History, "Look at the history of the project" }, { "View_Projects", &Commander::View_Projects, &Commander::can_View_Projects, "Look at projects present on this machine" }, { "View_MergeProjects", &Commander::View_MergeProjects, &Commander::can_View_MergeProjects, "Open project merge view" }, { "View_Project_Folders", &Commander::View_Hierarchy, &Commander::can_View_Hierarchy, "Show a hierarchical view panel for the current list" }, { "View_Active_Projects", &Commander::View_Active_Projects, &Commander::can_View_Active_Projects,"Show active projects (projects with checked out files or incoming scripts)" }, { "View_Next", &Commander::View_Next, 0, "" }, { "View_Previous", &Commander::View_Previous, 0, "" }, { "View_ClosePage", &Commander::View_ClosePage, &Commander::can_View_ClosePage, "Close page" }, { "ChangeFilter", &Commander::ChangeFilter, 0, "" }, { "GoBack", &Commander::GoBack, 0, "" }, { "Folder_GoUp", &Commander::Folder_GoUp, &Commander::can_Folder_GoUp, "Go to parent folder" }, { "Folder_GotoRoot", &Commander::Folder_GotoRoot, &Commander::can_Folder_GotoRoot, "Go to project's root folder" }, { "Folder_NewFile", &Commander::Folder_NewFile, &Commander::can_Folder_NewFile, "Create a new file in the project" }, { "Folder_NewFolder", &Commander::Folder_NewFolder, &Commander::can_Folder_NewFolder, "Create a new folder in the project" }, { "Folder_AddMoreFiles", &Commander::Folder_AddMoreFiles, &Commander::can_Folder_AddMoreFiles,"Add more files to the project from the current folder" }, { "Folder_Wikify", &Commander::Folder_Wikify, &Commander::can_Folder_Wikify, "Turn current folder into a wiki site" }, { "Folder_ExportHtml", &Commander::Folder_ExportHtml, &Commander::can_Folder_ExportHtml, "Export wiki folder as HTML web site" }, { "All_CheckIn", &Commander::All_CheckIn, &Commander::can_All_CheckIn, "Check-in all files" }, { "All_CheckOut", &Commander::All_CheckOut, &Commander::can_All_CheckOut, "Check-out all files in current view" }, { "All_DeepCheckOut", &Commander::All_DeepCheckOut, &Commander::can_All_DeepCheckOut, "Check-out all files including sub-folders" }, { "All_Uncheckout", &Commander::All_Uncheckout, &Commander::can_All_Uncheckout, "Un-Checkout all checked-out files" }, { "All_AcceptSynch", &Commander::All_AcceptSynch, &Commander::can_All_AcceptSynch, "Accept this sync in full" }, { "All_Synch", &Commander::All_Synch, &Commander::can_All_Synch, "Execute and accept all sync scripts" }, { "All_Report", &Commander::All_Report, &Commander::can_All_Report, "Create report from all view items" }, { "All_Select", &Commander::All_Select, &Commander::can_All_Select, "Select all view items" }, { "All_SaveFileVersion", &Commander::All_SaveFileVersion, &Commander::can_All_SaveFileVersion, "Save version of file(s)" }, { "Selection_CheckOut", &Commander::Selection_CheckOut, &Commander::can_Selection_CheckOut, "Check-out selected files" }, { "Selection_DeepCheckOut", &Commander::Selection_DeepCheckOut,&Commander::can_Selection_DeepCheckOut, "Check-out selected files including sub-folders" }, { "Selection_CheckIn", &Commander::Selection_CheckIn, &Commander::can_Selection_CheckIn, "Check-in selected files" }, { "Selection_Uncheckout", &Commander::Selection_Uncheckout, &Commander::can_Selection_Uncheckout,"Un-Checkout selected files" }, { "Selection_Properties", &Commander::Selection_Properties, &Commander::can_Selection_Properties,"Selected item properties" }, { "Selection_Open", &Commander::Selection_Open, &Commander::can_Selection_Open, "Open selected files for viewing/editing" }, { "Selection_OpenWithShell",&Commander::Selection_OpenWithShell,&Commander::can_Selection_OpenWithShell,"Open selected files for viewing/editing using Windows Shell" }, { "Selection_SearchWithShell",&Commander::Selection_SearchWithShell,&Commander::can_Selection_SearchWithShell,"Search selected folder using Windows Shell" }, { "Selection_Add", &Commander::Selection_Add, &Commander::can_Selection_Add, "Add selected file(s) to project" }, { "Selection_Remove", &Commander::Selection_Remove, &Commander::can_Selection_Remove, "Remove selected file(s) from project (don't delete!)" }, { "Selection_Delete", &Commander::Selection_Delete, &Commander::can_Selection_Delete, "Delete selected file(s)" }, { "Selection_DeleteFile", &Commander::Selection_DeleteFile, 0, "" }, { "Selection_DeleteScript", &Commander::Selection_DeleteScript, 0, "" }, { "Selection_Rename", &Commander::Selection_Rename, &Commander::can_Selection_Rename, "Rename selected file" }, { "Selection_Move", &Commander::Selection_MoveFiles, &Commander::can_Selection_MoveFiles,"Move selected file(s)" }, { "Selection_ChangeFileType",&Commander::Selection_ChangeFileType, &Commander::can_Selection_ChangeFileType, "Change type" }, { "Selection_Cut", &Commander::Selection_Cut, &Commander::can_Selection_Cut, "Cut selected file(s) (to be pasted into another folder)" }, { "Selection_Copy", &Commander::Selection_Copy, &Commander::can_Selection_Copy, "Copy selected file(s) to Windows clipboard" }, { "Selection_Paste", &Commander::Selection_Paste, &Commander::can_Selection_Paste, "Move file(s) that have been cut or copied to current folder" }, { "Selection_AcceptSynch", &Commander::Selection_AcceptSynch, &Commander::can_Selection_AcceptSynch,"Accept sync changes for selected file(s)" }, { "Selection_Synch", &Commander::Selection_Synch, &Commander::can_Selection_Synch, "Execute and accept next sync script" }, { "Selection_EditSync", &Commander::Selection_EditSync, &Commander::can_Selection_EditSync, "Execute next sync script and edit its result" }, { "Selection_SendScript", &Commander::Selection_SendScript, &Commander::can_Selection_SendScript,"Re-send script to project members" }, { "Selection_RequestResend",&Commander::Selection_RequestResend,&Commander::can_Selection_RequestResend,"Request script to be re-send to you" }, { "Selection_ShowHistory", &Commander::Selection_ShowHistory, &Commander::can_Selection_ShowHistory,"Show history of file(s)" }, { "Selection_Blame", &Commander::Selection_Blame, &Commander::can_Selection_Blame, "Who did it?" }, { "Selection_Report", &Commander::Selection_Report, &Commander::can_Selection_Report, "Create report from selected view item(s)" }, { "Selection_Compare", &Commander::Selection_Compare, &Commander::can_Selection_Compare, "Compare old versions of file(s) " }, { "Selection_CompareWithPrevious",&Commander::Selection_CompareWithPrevious, &Commander::can_Selection_CompareWithPrevious, "Compare with previous version of file(s) " }, { "Selection_CompareWithCurrent",&Commander::Selection_CompareWithCurrent, &Commander::can_Selection_CompareWithCurrent, "Compare with current version of file(s) " }, { "Selection_Revert", &Commander::Selection_Revert, &Commander::can_Selection_Revert, "Restore old version of file(s)" }, { "Selection_MergeBranch", &Commander::Selection_MergeBranch, &Commander::can_Selection_MergeBranch, "Merge change from the branch into the current project version" }, { "Selection_Branch", &Commander::Selection_Branch, &Commander::can_Selection_Branch, "Create project branch starting from this version" }, { "Selection_VersionExport",&Commander::Selection_VersionExport,&Commander::can_Selection_VersionExport,"Export old version of file(s)" }, { "Selection_Archive", &Commander::Selection_Archive, &Commander::can_Selection_Archive, "Archive all versions before selection" }, { "Selection_UnArchive", &Commander::Selection_UnArchive, &Commander::can_Selection_UnArchive, "Open archive" }, { "Selection_Add2FileFilter",&Commander::Selection_Add2FileFilter, &Commander::can_Selection_Add2FileFilter,"Don't show files with the selected extension(s)" }, { "Selection_RemoveFromFileFilter", &Commander::Selection_RemoveFromFileFilter, &Commander::can_Selection_RemoveFromFileFilter, "Remove the selected file extension(s) from the file filter" }, { "Selection_HistoryFilterAdd", &Commander::Selection_HistoryFilterAdd, &Commander::can_Selection_HistoryFilterAdd, "Filter history by selected files" }, { "Selection_HistoryFilterRemove", &Commander::Selection_HistoryFilterRemove, &Commander::can_Selection_HistoryFilterRemove, "Clear history filter" }, { "Selection_SaveFileVersion", &Commander::Selection_SaveFileVersion, &Commander::can_Selection_SaveFileVersion, "Save version of file(s)" }, { "Selection_RestoreFileVersion", &Commander::Selection_RestoreFileVersion, &Commander::can_Selection_RestoreFileVersion, "Restores version of file(s)" }, { "Selection_MergeFileVersion", &Commander::Selection_MergeFileVersion, &Commander::can_Selection_MergeFileVersion, "Merges version of file(s) into the current project version" }, { "Selection_AutoMergeFileVersion", &Commander::Selection_AutoMergeFileVersion, &Commander::can_Selection_AutoMergeFileVersion, "Automatically merges version of file(s) into the current project version" }, { "Selection_CopyList", &Commander::Selection_CopyList, &Commander::can_Selection_CopyList, "Copy Select List To Clipboard" }, { "Selection_Edit", &Commander::Selection_Edit, &Commander::can_Selection_Edit, "Edit File" }, { "Selection_Next", &Commander::Selection_Next, &Commander::can_Selection_Next, "Next Page" }, { "Selection_Previous", &Commander::Selection_Previous, &Commander::can_Selection_Previous, "Previous Page" }, { "Selection_Home", &Commander::Selection_Home, &Commander::can_Selection_Home, "Browse Home" }, { "Selection_Reload", &Commander::Selection_Reload, &Commander::can_Selection_Reload, "Reload Page" }, { "Selection_CopyScriptComment", &Commander::Selection_CopyScriptComment, &Commander::can_Selection_CopyScriptComment, "Copy Script Comment To Clipboard" }, { "Tools_Differ", &Commander::Tools_Differ, 0, "Configure Differ Tool" }, { "Tools_Merger", &Commander::Tools_Merger, 0, "Configure Merger Tool" }, { "Tools_Editor", &Commander::Tools_Editor, 0, "Configure Editor Tool" }, { "Tools_CreateBackup", &Commander::Tools_CreateBackup, &Commander::can_Tools_CreateBackup, "Backup all projects" }, { "Tools_RestoreFromBackup",&Commander::Tools_RestoreFromBackup,&Commander::can_Tools_RestoreFromBackup, "Restore all projects from backup" }, { "Tools_MoveToMachine", &Commander::Tools_MoveToMachine, 0, "Move Code Co-op to a new machine" }, { "Help_Contents", &Commander::Help_Contents, 0, "Display Help" }, { "Help_Index", &Commander::Help_Index, 0, "Display Help Index" }, { "Help_Tutorial", &Commander::Help_Tutorial, 0, "Step-by-step tutorial" }, { "Help_Support", &Commander::Help_Support, 0, "On-line support" }, { "Help_SaveDiagnostics", &Commander::Help_SaveDiagnostics, 0, "Save diagnostic information to file" }, { "Help_RestoreOriginal", &Commander::Help_RestoreOriginal, &Commander::can_Help_RestoreOriginal, "Uninstall the current temporary version and restore the original version" }, { "Help_BeginnerMode", &Commander::Help_BeginnerMode, &Commander::can_Help_BeginnerMode, "Display helpful hints for the inexperienced user" }, // Commands triggered by control notification handlers { "DoNewFolder", &Commander::DoNewFolder, 0, "" }, { "DoRenameFile", &Commander::DoRenameFile, 0, "" }, { "DoDrag", &Commander::DoDrag, &Commander::can_Drag, "" }, { "DoDrop", &Commander::DoDrop, 0, "" }, { "SetCurrentFolder", &Commander::SetCurrentFolder, 0, "" }, { "DoNewFile", &Commander::DoNewFile, 0, "" }, { "DoDeleteFile", &Commander::DoDeleteFile, 0, "" }, { "Project_SelectMergeTarget", &Commander::Project_SelectMergeTarget, 0, "" }, { "Project_SetMergeType", &Commander::Project_SetMergeType, 0, "" }, { "Selection_OpenHistoryDiff", &Commander::Selection_OpenHistoryDiff, 0, "" }, // Commands not associated with any menu item, but used by SccDll or others { "GoBrowse", &Commander::GoBrowse, 0, "" }, { "OnBrowse", &Commander::OnBrowse, 0, "" }, { "Navigate", &Commander::Navigate, 0, "" }, { "OpenFile", &Commander::OpenFile, 0, "" }, { "CreateRange", &Commander::CreateRange, 0, "" }, { "Selection_OpenCheckInDiff", &Commander::Selection_OpenCheckInDiff, 0, "" }, { "RefreshMailbox", &Commander::RefreshMailbox, 0, "" }, { "RestoreVersion", &Commander::RestoreVersion, 0, "" }, { "Maintenance", &Commander::Maintenance, 0, "" }, { "ReCreateFile", &Commander::ReCreateFile, 0, "" }, { "MergeAttributes", &Commander::MergeAttributes, 0, "" }, #if !defined (NDEBUG) { "RestoreOneVersion", &Commander::RestoreOneVersion, 0, "" }, #endif { 0, 0, 0 } }; }
94.100529
207
0.721001
193b13954156d2292b272b4c13f84bb937a3810a
1,820
cpp
C++
Algorithms/0023.MergeKSortedLists/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0023.MergeKSortedLists/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0023.MergeKSortedLists/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <queue> #include <vector> #include "ListNode.h" #include "ListNodeUtils.h" #include "gtest/gtest.h" using CommonLib::ListNode; namespace { class Solution { public: ListNode* mergeKLists(std::vector<ListNode*> const &lists) { auto comp = [](ListNode* left, ListNode* right){ return left->val > right->val; }; std::priority_queue<ListNode*, std::vector<ListNode*>, decltype(comp)> queue(comp); for (ListNode* head : lists) { while (head != nullptr) { queue.push(head); head = head->next; } } ListNode* head = nullptr; ListNode* current = nullptr; while (!queue.empty()) { if (current == nullptr) head = current = queue.top(); else { current->next = queue.top(); current = current->next; } queue.pop(); } if (current != nullptr) current->next = nullptr; return head; } }; } using CommonLib::createLinkedList; using CommonLib::checkAndDeleteLinkedList; namespace MergeKSortedListsTask { TEST(ReorderListTaskTests, Examples) { Solution solution; checkAndDeleteLinkedList({1, 1, 2, 3, 4, 4, 5, 6}, solution.mergeKLists({createLinkedList({1, 4, 5}, false).get(), createLinkedList({1, 3, 4}, false).get(), createLinkedList({2, 6}, false).get()})); } TEST(ReorderListTaskTests, FromWrongAnswers) { Solution solution; checkAndDeleteLinkedList({}, solution.mergeKLists({})); checkAndDeleteLinkedList({}, solution.mergeKLists({nullptr})); } }
25.633803
118
0.52967
193b65c74c6443443efd2c4733991672729e7e86
1,433
hpp
C++
minimal_sdk/public/containers/utldict.hpp
vocweb/cso2-launcher
abc144acaa3dfb5b0c9acd61cd75970cac012617
[ "MIT" ]
55
2018-09-01T17:52:17.000Z
2019-09-23T10:30:49.000Z
minimal_sdk/public/containers/utldict.hpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
70
2018-08-22T05:53:34.000Z
2019-09-23T15:11:39.000Z
minimal_sdk/public/containers/utldict.hpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
39
2018-09-01T21:42:50.000Z
2019-09-23T18:38:07.000Z
#pragma once #include <cstring> #include "containers/utlmap.hpp" #ifdef _WIN32 #define stricmp _stricmp #else #define stricmp strcasecmp #endif inline bool CaselessStringLessThan( const char* const& lhs, const char* const& rhs ) { if ( !lhs ) return false; if ( !rhs ) return true; return ( stricmp( lhs, rhs ) < 0 ); } inline char* UtlDict_DupStr( const char* inStr ) { const size_t len = std::strlen( inStr ) + 1; char* newStr = new char[len]; memcpy_s( newStr, len, inStr, len ); return newStr; } template <class T, class I = int> class CUtlDict { public: using DictElementMap_t = CUtlMap<const char*, T, I>; DictElementMap_t m_Elements; CUtlDict( int growSize = 0, int initSize = 0 ) : m_Elements( growSize, initSize ) { m_Elements.SetLessFunc( CaselessStringLessThan ); } ~CUtlDict() { Purge(); } void Purge() { RemoveAll(); } void RemoveAll() { typename DictElementMap_t::IndexType_t index = m_Elements.FirstInorder(); while ( index != m_Elements.InvalidIndex() ) { delete m_Elements.Key( index ); index = m_Elements.NextInorder( index ); } m_Elements.RemoveAll(); } I Insert( const char* pName, const T& element ) { return m_Elements.Insert( UtlDict_DupStr( pName ), element ); } };
22.046154
69
0.598046
193baa28349a290947ae28e4780acc661b713584
709
cpp
C++
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
61
2019-04-12T18:49:57.000Z
2022-03-19T22:23:16.000Z
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
127
2019-04-09T00:55:50.000Z
2022-03-21T15:35:41.000Z
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
10
2019-04-02T18:25:40.000Z
2022-02-15T07:11:37.000Z
// REQUIRES: xocc // RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %s -o %t.out // RUN: %ACC_RUN_PLACEHOLDER %t.out // TODO should be a Sema test #include <CL/sycl.hpp> #include "../utilities/device_selectors.hpp" using namespace cl::sycl; class add_2; int main() { selector_defines::CompiledForDeviceSelector selector; queue q {selector}; q.submit([&] (handler &cgh) { cgh.single_task<add_2>([=] () { }); }); q.submit([&] (handler &cgh) { cgh.single_task<add_2>([=] () { }); }); q.submit([&] (handler &cgh) { cgh.single_task<class add>([=] () { }); }); q.submit([&] (handler &cgh) { cgh.single_task<class add>([=] () { }); }); return 0; }
16.880952
64
0.57969
193feff6c0408370500518f0e617c3b5ca13178c
1,929
cpp
C++
SDK/BP_WheelInterface_functions.cpp
alxalx14/Sea-Of-Thieves-SDK
f56a0340eb33726c98fc53eb0678fa2d59aa8294
[ "MIT" ]
3
2021-03-27T08:30:37.000Z
2021-04-18T19:32:53.000Z
SDK/BP_WheelInterface_functions.cpp
alxalx14/Sea-Of-Thieves-SDK
f56a0340eb33726c98fc53eb0678fa2d59aa8294
[ "MIT" ]
null
null
null
SDK/BP_WheelInterface_functions.cpp
alxalx14/Sea-Of-Thieves-SDK
f56a0340eb33726c98fc53eb0678fa2d59aa8294
[ "MIT" ]
1
2021-06-01T03:05:50.000Z
2021-06-01T03:05:50.000Z
// Name: SeaOfThieves, Version: 2.0.23 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_WheelInterface.BP_WheelInterface_C.Receive Animation State // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // struct FRotator WheelRotation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) // float WheelAnimationTime (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) // TEnumAsByte<EWheel_EWheel> EWheel (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) // float Direction (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) // float WheelRate (Parm, ZeroConstructor, IsPlainOldData, NoDestructor) void UBP_WheelInterface_C::Receive_Animation_State(const struct FRotator& WheelRotation, float WheelAnimationTime, TEnumAsByte<EWheel_EWheel> EWheel, float Direction, float WheelRate) { static auto fn = UObject::FindObject<UFunction>("Function BP_WheelInterface.BP_WheelInterface_C.Receive Animation State"); UBP_WheelInterface_C_Receive_Animation_State_Params params; params.WheelRotation = WheelRotation; params.WheelAnimationTime = WheelAnimationTime; params.EWheel = EWheel; params.Direction = Direction; params.WheelRate = WheelRate; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } void UBP_WheelInterface_C::AfterRead() { UInterface::AfterRead(); } void UBP_WheelInterface_C::BeforeDelete() { UInterface::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
29.676923
183
0.641265
1943e504d831c8eac0d1a9ed4fd33283c4ceb1ea
2,860
hpp
C++
bsengine/src/bstorm/logger.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/logger.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/logger.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
#pragma once #include <bstorm/source_map.hpp> #include <string> #include <memory> #include <vector> #include <mutex> namespace bstorm { class LogParam { public: enum class Tag { TEXT, TEXTURE, SOUND, MESH, PLAYER_SHOT_DATA, ENEMY_SHOT_DATA, ITEM_DATA, SCRIPT, RENDER_TARGET, SHADER }; LogParam(Tag tag, const std::string& text); LogParam(Tag tag, const std::wstring& text); LogParam(Tag tag, std::string&& text); Tag GetTag() const { return tag_; } const std::string& GetText() const { return text_; } private: Tag tag_; std::string text_; // utf8 }; enum class LogLevel { LV_INFO, LV_WARN, LV_ERROR, LV_SUCCESS, LV_DEBUG, LV_USER }; class Log { public: static const char* GetLevelName(LogLevel level); Log(); Log(LogLevel level); Log& Msg(const std::string& text); Log& Msg(const std::wstring& text); Log& Msg(std::string&& text); const std::string& Msg() const { return msg_; } Log& Param(const LogParam& param); Log& Param(LogParam&& param); const std::shared_ptr<LogParam>& Param() const { return param_; } Log& Level(LogLevel level); LogLevel Level() const { return level_; } Log& AddSourcePos(const std::shared_ptr<SourcePos>& srcPos); const std::vector<SourcePos>& GetSourcePosStack() const { return srcPosStack_; } std::string ToString() const; Log&& move() { return std::move(*this); } private: LogLevel level_; std::string msg_; // utf8 std::shared_ptr<LogParam> param_; // Nullable std::vector<SourcePos> srcPosStack_; // add = push_back }; Log LogInfo(const std::wstring& msg); Log LogInfo(const std::string& msg); Log LogInfo(std::string&& msg); Log LogWarn(const std::wstring& msg); Log LogWarn(const std::string& msg); Log LogWarn(std::string&& msg); Log LogError(const std::wstring& msg); Log LogError(const std::string& msg); Log LogError(std::string&& msg); Log LogDebug(const std::wstring& msg); Log LogDebug(const std::string& msg); Log LogDebug(std::string&& msg); class Logger { public: static void Init(const std::shared_ptr<Logger>& logger); static void Write(Log& lg); static void Write(Log&& lg); static void Write(LogLevel level, const std::string& text); static void Write(LogLevel level, const std::wstring& text); static void Write(LogLevel level, std::string&& text); static void Shutdown(); virtual ~Logger() {} virtual void log(Log& lg) noexcept(false) = 0; virtual void log(Log&& lg) noexcept(false) = 0; void log(LogLevel level, const std::string& text); void log(LogLevel level, const std::wstring& text); void log(LogLevel level, std::string&& text); private: static std::shared_ptr<Logger> logger; static std::mutex mutex; }; }
26
84
0.654196
1944823fef65060394f79ec527543ef0dc6f84af
14,712
cpp
C++
examples/hxhim/cli.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
2
2020-11-25T17:45:58.000Z
2021-12-21T02:01:16.000Z
examples/hxhim/cli.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
null
null
null
examples/hxhim/cli.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
1
2021-10-11T19:54:05.000Z
2021-10-11T19:54:05.000Z
#include <cstring> #include <ios> #include <iostream> #include <list> #include <map> #include <sstream> #include "hxhim/hxhim.hpp" #include "print_results.h" #include "utils/Blob.hpp" // private header #include "utils/memory.hpp" enum HXHIM_OP { PUT, GET, GETOP, DEL, BPUT, BGET, BGETOP, BDEL, FLUSHPUTS, FLUSHGETS, FLUSHDELS, FLUSH, }; const std::map<HXHIM_OP, std::string> FORMAT = { std::make_pair(HXHIM_OP::PUT, "PUT <SUBJECT> <PREDICATE> <OBJECT>"), std::make_pair(HXHIM_OP::GET, "GET <SUBJECT> <PREDICATE> <OBJECT_TYPE>"), std::make_pair(HXHIM_OP::GETOP, "GETOP <SUBJECT> <PREDICATE> <OBJECT_TYPE> <NUM_RECS> <OP>"), std::make_pair(HXHIM_OP::DEL, "DEL <SUBJECT> <PREDICATE>"), std::make_pair(HXHIM_OP::BPUT, "BPUT N <SUBJECT_1> <PREDICATE_1> <OBJECT_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_N>"), std::make_pair(HXHIM_OP::BGET, "BGET N <SUBJECT_1> <PREDICATE_1> <OBJECT_TYPE_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_TYPE_N>"), std::make_pair(HXHIM_OP::BGETOP, "BGETOP <SUBJECT_1> <PREDICATE_1> <OBJECT_TYPE_1> <NUM_RECS_1> <OP_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_TYPE_N> <NUM_RECS_N> <OP_N>"), std::make_pair(HXHIM_OP::BDEL, "BDEL N <SUBJECT_1> <PREDICATE_1> ... <SUBJECT_N> <PREDICATE_N>"), std::make_pair(HXHIM_OP::FLUSHPUTS, "FLUSHPUTS"), std::make_pair(HXHIM_OP::FLUSHGETS, "FLUSHGETS"), std::make_pair(HXHIM_OP::FLUSHDELS, "FLUSHDELS"), std::make_pair(HXHIM_OP::FLUSH, "FLUSH"), }; const std::map<std::string, HXHIM_OP> USER2OP = { std::make_pair("PUT", HXHIM_OP::PUT), std::make_pair("BPUT", HXHIM_OP::BPUT), std::make_pair("GET", HXHIM_OP::GET), std::make_pair("BGET", HXHIM_OP::BGET), std::make_pair("GETOP", HXHIM_OP::GETOP), std::make_pair("BGETOP", HXHIM_OP::BGETOP), std::make_pair("DEL", HXHIM_OP::DEL), std::make_pair("BDEL", HXHIM_OP::BDEL), std::make_pair("FLUSHPUTS", HXHIM_OP::FLUSHPUTS), std::make_pair("FLUSHGETS", HXHIM_OP::FLUSHGETS), std::make_pair("FLUSHDELS", HXHIM_OP::FLUSHDELS), std::make_pair("FLUSH", HXHIM_OP::FLUSH), }; const std::map<std::string, hxhim_data_t> USER2OT = { std::make_pair("INT32", HXHIM_DATA_INT32), std::make_pair("INT64", HXHIM_DATA_INT64), std::make_pair("UINT32", HXHIM_DATA_UINT32), std::make_pair("UINT64", HXHIM_DATA_UINT64), std::make_pair("FLOAT", HXHIM_DATA_FLOAT), std::make_pair("DOUBLE", HXHIM_DATA_DOUBLE), std::make_pair("BYTE", HXHIM_DATA_BYTE), }; const std::map<std::string, hxhim_getop_t> USER2GETOP = { std::make_pair("EQ", HXHIM_GETOP_EQ), std::make_pair("NEXT", HXHIM_GETOP_NEXT), std::make_pair("PREV", HXHIM_GETOP_PREV), std::make_pair("FIRST", HXHIM_GETOP_FIRST), std::make_pair("LAST", HXHIM_GETOP_LAST), // std::make_pair("PRIMARY_EQ", HXHIM_GETOP_PRIMARY_EQ), }; std::ostream &help(char *self, std::ostream &stream = std::cout) { stream << "Syntax: " << self << " [-h | --help] [--ds <name>]" << std::endl << std::endl << "--ds implies a single rank. Running multiple MPI ranks will error." << std::endl << std::endl << "Input is passed in through the stdin of rank 0, delimited with newlines, in the following formats:" << std::endl; for(decltype(FORMAT)::value_type const &format : FORMAT) { stream << " " << format.second << std::endl; } stream << "Where <SUBJECT>, <PREDICATE>, and <OBJECT> are pairs of <type, data>" << std::endl << "<OBJECT_TYPE> is only the type" << std::endl << std::endl << "Available Types:" << std::endl; for(decltype(USER2OT)::value_type const &type : USER2OT) { stream << " " << type.first << std::endl; } stream << std::endl << "The <OP> argument to (B)GETOP can be one of the following:" << std::endl; for(decltype(USER2GETOP)::value_type const &op : USER2GETOP) { stream << " " << op.first << std::endl; } return stream; } std::istream &operator>>(std::istream &stream, hxhim_data_t &type) { std::string str; if ((stream >> str)) { const decltype(USER2OT)::const_iterator it = USER2OT.find(str); if (it == USER2OT.end()) { stream.setstate(std::ios::failbit); } else { type = it->second; } } return stream; } std::istream &operator>>(std::istream &stream, Blob &input) { hxhim_data_t type; if (!(stream >> type)) { return stream; } void *data = nullptr; std::size_t size = 0; switch (type) { case HXHIM_DATA_INT32: size = sizeof(int32_t); data = alloc(size); stream >> * (int32_t *) data; break; case HXHIM_DATA_INT64: size = sizeof(int64_t); data = alloc(size); stream >> * (int64_t *) data; break; case HXHIM_DATA_UINT32: size = sizeof(uint32_t); data = alloc(size); stream >> * (uint32_t *) data; break; case HXHIM_DATA_UINT64: size = sizeof(uint64_t); data = alloc(size); stream >> * (uint64_t *) data; break; case HXHIM_DATA_FLOAT: size = sizeof(float); data = alloc(size); stream >> * (float *) data; break; case HXHIM_DATA_DOUBLE: size = sizeof(double); data = alloc(size); stream >> * (double *) data; break; case HXHIM_DATA_BYTE: { std::string str; if ((stream >> str)) { size = str.size(); data = alloc(size); memcpy(data, str.c_str(), str.size()); } } break; default: stream.setstate(std::ios::failbit); break; } // on error, will be deallocated automatically input = RealBlob(data, size, type); return stream; } struct UserInput { HXHIM_OP hxhim_op; Blob subject; Blob predicate; Blob object; // data field is only used by (B)PUT // only used by (B)GETOP std::size_t num_recs; hxhim_getop_t op; }; using UserInputs = std::list<UserInput>; // A quick and dirty cleanup function void cleanup(hxhim_t *hx) { hxhim::Close(hx); MPI_Finalize(); } // serialize user input // B* becomes individual operations std::size_t parse_commands(std::istream &stream, UserInputs &commands) { std::string line; while (std::getline(stream, line)) { std::stringstream command(line); // empty line std::string op_str; if (!(command >> op_str)) { continue; } const decltype(USER2OP)::const_iterator op_it = USER2OP.find(op_str); if (op_it == USER2OP.end()) { std::cerr << "Error: Bad operation: " << op_str << std::endl; continue; } const HXHIM_OP hxhim_op = op_it->second; std::size_t count = 1; // bulk, so get count first if (op_str[0] == 'B') { if (!(command >> count)) { std::cerr << "Error: Bad count: " << line << std::endl; continue; } } // read input for(std::size_t i = 0; i < count; i++) { UserInput input; bool ok = true; switch ((input.hxhim_op = hxhim_op)) { case HXHIM_OP::PUT: case HXHIM_OP::BPUT: { if (!(command >> input.subject >> input.predicate >> input.object)) { ok = false; } } break; case HXHIM_OP::GET: case HXHIM_OP::BGET: { hxhim_data_t object_type; if (!(command >> input.subject >> input.predicate >> object_type)) { ok = false; } else { input.object.set_type(object_type); } } break; case HXHIM_OP::GETOP: case HXHIM_OP::BGETOP: { hxhim_data_t object_type; std::string op; if (!(command >> input.subject >> input.predicate >> object_type >> input.num_recs >> op)) { ok = false; } else { input.object.set_type(object_type); } const decltype(USER2GETOP)::const_iterator getop_it = USER2GETOP.find(op); if (getop_it == USER2GETOP.end()) { ok = false; } else { input.op = getop_it->second; } } break; case HXHIM_OP::DEL: case HXHIM_OP::BDEL: if (!(command >> input.subject >> input.predicate)) { ok = false; } break; case HXHIM_OP::FLUSHPUTS: case HXHIM_OP::FLUSHGETS: case HXHIM_OP::FLUSHDELS: case HXHIM_OP::FLUSH: break; } if (!ok) { std::cerr << "Error: Could not parse line \"" << line << "\"." << std::endl << "Expected: " << FORMAT.at(hxhim_op) << std::endl; break; } commands.emplace_back(std::move(input)); } } return commands.size(); } std::size_t run_commands(hxhim_t *hx, const UserInputs &commands) { std::size_t successful = 0; for(UserInputs::value_type const &cmd : commands) { int rc = HXHIM_SUCCESS; hxhim_results *res = nullptr; switch (cmd.hxhim_op) { case HXHIM_OP::PUT: case HXHIM_OP::BPUT: rc = hxhimPut(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(), (void *) cmd.object.data(), cmd.object.size(), cmd.object.data_type(), HXHIM_PUT_ALL); break; case HXHIM_OP::GET: case HXHIM_OP::BGET: rc = hxhimGet(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(), cmd.object.data_type()); break; case HXHIM_OP::GETOP: case HXHIM_OP::BGETOP: rc = hxhimGetOp(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(), cmd.object.data_type(), cmd.num_recs, cmd.op); break; case HXHIM_OP::DEL: case HXHIM_OP::BDEL: rc = hxhimDelete(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type()); break; case HXHIM_OP::FLUSHPUTS: res = hxhimFlushPuts(hx); break; case HXHIM_OP::FLUSHGETS: res = hxhimFlushGets(hx); break; case HXHIM_OP::FLUSHDELS: res = hxhimFlushDeletes(hx); break; case HXHIM_OP::FLUSH: res = hxhimFlush(hx); break; } print_results(hx, 0, res); hxhim_results_destroy(res); if (rc == HXHIM_ERROR) { std::cerr << "Error" << std::endl; } else { successful++; } } // do not implicity flush return successful; } int main(int argc, char *argv[]) { int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int size; MPI_Comm_size(MPI_COMM_WORLD, &size); char * ds = nullptr; for(int i = 1; i < argc;) { const std::string args(argv[i]); if ((args == "-h")|| (args == "--help")) { if (rank == 0) { help(argv[0], std::cerr); } MPI_Finalize(); return 0; } if (args == "--ds") { // --ds implies a single rank, but a single rank does not imply --ds if (size != 1) { std::cerr << "Error: The --ds flag implies 1 rank. Have " << size << std::endl; MPI_Finalize(); return 1; } ds = argv[++i]; } i++; } // read the config hxhim_t hx; if (hxhimInit(&hx, MPI_COMM_WORLD) != HXHIM_SUCCESS) { if (rank == 0) { std::cout << "Error: Failed to read configuration" << std::endl; } cleanup(&hx); return 1; } // initialize hxhim context if (ds) { if (hxhimOpenOne(&hx, ds, strlen(ds)) != HXHIM_SUCCESS) { if (rank == 0) { std::cerr << "Failed to initialize hxhim" << std::endl; } cleanup(&hx); return 1; } } else { if (hxhimOpen(&hx) != HXHIM_SUCCESS) { if (rank == 0) { std::cerr << "Failed to initialize hxhim" << std::endl; } cleanup(&hx); return 1; } } // parse and run input if (rank == 0) { UserInputs cmds; const std::size_t valid_count = parse_commands(std::cin, cmds); std::cout << "Read " << valid_count << " valid commands" << std::endl; run_commands(&hx, cmds); } MPI_Barrier(MPI_COMM_WORLD); cleanup(&hx); return 0; }
32.548673
178
0.494562
1946511e9585cbaf319a9816fa1f3de02358c68f
1,085
cc
C++
creational/src/prototype/maze_prototype_factory.cc
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
9
2016-08-03T16:15:57.000Z
2021-11-08T13:15:46.000Z
creational/src/prototype/maze_prototype_factory.cc
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
null
null
null
creational/src/prototype/maze_prototype_factory.cc
rachwal/DesignPatterns
0645544706c915a69e1ca64addba5cc14453f64c
[ "MIT" ]
4
2016-08-03T16:16:01.000Z
2017-12-27T05:14:55.000Z
// Based on "Design Patterns: Elements of Reusable Object-Oriented Software" // book by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm // // Created by Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan. #include "maze_prototype_factory.h" namespace creational { namespace prototype { MazePrototypeFactory::MazePrototypeFactory(commons::Maze* m, commons::Wall* w, commons::Room* r, commons::Door* d) { prototype_maze_ = m; prototype_wall_ = w; prototype_room_ = r; prototype_door_ = d; } commons::Room *MazePrototypeFactory::MakeRoom(const int&) const { auto room = prototype_room_->Clone(); return room; } commons::Maze *MazePrototypeFactory::MakeMaze() const { return prototype_maze_->Clone(); } commons::Wall *MazePrototypeFactory::MakeWall() const { return prototype_wall_->Clone(); } commons::Door *MazePrototypeFactory::MakeDoor(const commons::Room& first_room, const commons::Room& second_room) const { auto door = prototype_door_->Clone(); door->Initialize(first_room, second_room); return door; } } }
24.111111
118
0.758525
19479dd6b3bc0d9adfe49819ccb09e8be6112570
1,120
cpp
C++
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
#include "../../../PrecompiledHeaders/stdafx.h" #include "IndexBuffer.h" namespace dx11 { // Constructors and Destructor: IndexBuffer::IndexBuffer(RenderSystem& renderSystem, const std::vector<uint16>& indices) : count( UINT( indices.size() ) ) { D3D11_BUFFER_DESC index_buffer_desc = {}; index_buffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER; index_buffer_desc.Usage = D3D11_USAGE_DEFAULT; index_buffer_desc.CPUAccessFlags = 0u; index_buffer_desc.MiscFlags = 0u; index_buffer_desc.ByteWidth = UINT( count * sizeof( uint16 ) ); index_buffer_desc.StructureByteStride = sizeof( uint16 ); D3D11_SUBRESOURCE_DATA index_subresource_data = {}; index_subresource_data.pSysMem = indices.data(); Bindable::GetDevice( renderSystem )->CreateBuffer( &index_buffer_desc, &index_subresource_data, &m_pIndexBuffer ); } // Functions: void IndexBuffer::Bind(RenderSystem& renderSystem) noexcept { Bindable::GetContext( renderSystem )->IASetIndexBuffer( m_pIndexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0u ); } // Accessors: const UINT& IndexBuffer::GetCount() const noexcept { return count; } }
26.046512
116
0.755357
194edcd60b676d2b702caf68ea5608d0ad8ce143
4,462
cpp
C++
src/main.cpp
tsaarni/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
27
2017-08-15T05:45:21.000Z
2022-03-27T21:32:46.000Z
src/main.cpp
AA6KL/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
1
2022-01-10T19:43:12.000Z
2022-01-10T19:43:12.000Z
src/main.cpp
AA6KL/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
11
2017-08-15T16:28:41.000Z
2021-04-26T11:52:54.000Z
// // BSD 3-Clause License // // Copyright (c) 2017, Tero Saarni // // // This software re-programs ATtiny85 fuses using the high-voltage // serial programming method. // // // References // // * ATtiny85 datasheet - // http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf // // * Online fuse value calculator - // http://www.engbedded.com/fusecalc/ // // // High-voltaga serial programming instruction set (from ATtiny85 datasheet) // // Write Fuse Low Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_A987_6543_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0110_0100_00 0_0110_1100_00 goes high. Write A - 3 = “0” to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // // Write Fuse High Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_IHGF_EDCB_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0111_0100_00 0_0111_1100_00 goes high. Write I - B = “0” to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // // Write Fuse Extended Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_0000_000J_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0110_0110_00 0_0110_1110_00 goes high. Write J = “0” to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // #include <Arduino.h> // ATtiny85 pin mapaping at Arduino nano programmer #define SDI_PIN 9 // serial data input #define SII_PIN 10 // serial instruction input #define SDO_PIN 11 // serial data output #define SCI_PIN 12 // serial clock input #define RESET_PIN 13 // reset void avr_hvsp_write(uint8_t sdi, uint8_t sii) { digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); for (uint8_t i = 0; i < 8; i++) { digitalWrite(SDI_PIN, (sdi & (1 << (7-i)))); digitalWrite(SII_PIN, (sii & (1 << (7-i)))); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); } digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); } void avr_hvsp_write_lfuse(uint8_t lfuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(lfuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01100100); avr_hvsp_write(0b00000000, 0b01101100); while (digitalRead(SDO_PIN) == LOW) { }; } void avr_hvsp_write_hfuse(uint8_t hfuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(hfuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01110100); avr_hvsp_write(0b00000000, 0b01111100); while (digitalRead(SDO_PIN) == LOW) { }; } void avr_hvsp_write_efuse(uint8_t efuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(efuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01100110); avr_hvsp_write(0b00000000, 0b01101110); while (digitalRead(SDO_PIN) == LOW) { }; } void setup() { Serial.begin(9600); // setup pin modes pinMode(SDI_PIN, OUTPUT); pinMode(SII_PIN, OUTPUT); pinMode(SDO_PIN, OUTPUT); pinMode(SCI_PIN, OUTPUT); pinMode(RESET_PIN, OUTPUT); // enter programming mode digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SDO_PIN, LOW); digitalWrite(RESET_PIN, HIGH); // pull attiny85 reset pin to ground delayMicroseconds(20); digitalWrite(RESET_PIN, LOW); // attiny85 reset pin to 12V delayMicroseconds(10); pinMode(SDO_PIN, INPUT); delayMicroseconds(300); // write default fuse values avr_hvsp_write_lfuse(0x62); avr_hvsp_write_hfuse(0xdf); avr_hvsp_write_efuse(0xff); // exit programming mode digitalWrite(RESET_PIN, HIGH); // pull attiny85 reset pin to ground (arduino nano LED will be on) } void loop() { Serial.print("Programming done"); while (true) { delay(1000); Serial.print("."); } }
30.353741
112
0.680861
195296a7835c174b6c4a11ca841e1547ca0eb41e
1,861
cc
C++
Dragon/src/operators/activation/tanh_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
212
2015-07-05T07:57:17.000Z
2022-02-27T01:55:35.000Z
Dragon/src/operators/activation/tanh_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
6
2016-07-07T14:31:56.000Z
2017-12-12T02:21:15.000Z
Dragon/src/operators/activation/tanh_op.cc
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
[ "BSD-2-Clause" ]
71
2016-03-24T09:02:41.000Z
2021-06-03T01:52:41.000Z
#include "operators/activation/tanh_op.h" #include "utils/math_functions.h" #include "utils/op_kernel.h" namespace dragon { template <class Context> template <typename T> void TanhOp<Context>::RunWithType() { auto* Xdata = input(0).template data<T, Context>(); auto* Ydata = output(0)->template mutable_data<T, Context>(); kernel::Tanh<T, Context>(output(0)->count(), Xdata, Ydata); } template <class Context> void TanhOp<Context>::RunOnDevice() { output(0)->ReshapeLike(input(0)); if (input(0).template IsType<float>()) RunWithType<float>(); else LOG(FATAL) << "Unsupported input types."; } DEPLOY_CPU(Tanh); #ifdef WITH_CUDA DEPLOY_CUDA(Tanh); #endif OPERATOR_SCHEMA(Tanh).NumInputs(1).NumOutputs(1).Inplace({ { 0, 0 } }); template <class Context> template <typename T> void TanhGradientOp<Context>::RunWithType() { auto* Ydata = input(0).template data<T, Context>(); auto* dYdata = input(1).template data<T, Context>(); auto* dXdata = output(0)->template mutable_data<T, Context>(); kernel::TanhGrad<T, Context>(output(0)->count(), dYdata, Ydata, dXdata); } template <class Context> void TanhGradientOp<Context>::RunOnDevice() { output(0)->ReshapeLike(input(0)); if (input(0).template IsType<float>()) RunWithType<float>(); else LOG(FATAL) << "Unsupported input types."; } DEPLOY_CPU(TanhGradient); #ifdef WITH_CUDA DEPLOY_CUDA(TanhGradient); #endif OPERATOR_SCHEMA(TanhGradient).NumInputs(2).NumOutputs(1).Inplace({ { 1, 0 } }); class GetTanhGradient final : public GradientMakerBase { public: GRADIENT_MAKER_CTOR(GetTanhGradient); vector<OperatorDef> MakeDefs() override { return SingleDef(def.type() + "Gradient", "", vector<string> {O(0), GO(0)}, vector<string> {GI(0)}); } }; REGISTER_GRADIENT(Tanh, GetTanhGradient); } // namespace dragon
30.508197
79
0.686728
195329a53a2f3d353f9bee89b37a3cf2abb3426d
435
cpp
C++
circle_area.cpp
KhaledMahm0vd/cppexamples
c1ed91fb08a3924bd2c03dc293759dfdff8e8a55
[ "MIT" ]
null
null
null
circle_area.cpp
KhaledMahm0vd/cppexamples
c1ed91fb08a3924bd2c03dc293759dfdff8e8a55
[ "MIT" ]
null
null
null
circle_area.cpp
KhaledMahm0vd/cppexamples
c1ed91fb08a3924bd2c03dc293759dfdff8e8a55
[ "MIT" ]
null
null
null
//find the area of a circle. //circlearea.cpp //Khaled Mahmoud, 2021. #include <iostream> using namespace std; int main() { float rad; //float type. const float pi = 3.14159F; //const float type. cout<<"Enter the radius of a circle: "; //message display. cin>>rad; //get radius. float area = pi * rad * rad; //calculate the area. cout<<"The area is: "<<area <<endl; //display result. return 0; }
27.1875
61
0.618391
19555fe091d99443665ad7fd7a8d939577780fcb
4,925
cpp
C++
src/image_widget.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/image_widget.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
src/image_widget.cpp
gamobink/anura
410721a174aae98f32a55d71a4e666ad785022fd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2003-2014 by David White <davewx7@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Canvas.hpp" #include "DisplayDevice.hpp" #include "image_widget.hpp" #include <iostream> namespace gui { ImageWidget::ImageWidget(const std::string& fname, int w, int h) : texture_(KRE::Texture::createTexture(fname)), rotate_(0.0f), image_name_(fname) { setEnvironment(); init(w, h); } ImageWidget::ImageWidget(KRE::TexturePtr tex, int w, int h) : texture_(tex), rotate_(0.0) { setEnvironment(); init(w, h); } ImageWidget::ImageWidget(const variant& v, game_logic::FormulaCallable* e) : Widget(v, e) { if(v.has_key("area")) { area_ = rect(v["area"]); } texture_ = KRE::Texture::createTexture(v); rotate_ = v.has_key("rotation") ? v["rotation"].as_float() : 0.0f; init(v["image_width"].as_int(-1), v["image_height"].as_int(-1)); setClaimMouseEvents(v["claim_mouse_events"].as_bool(false)); } void ImageWidget::init(int w, int h) { if(w < 0) { if(area_.w()) { w = area_.w()*2; } else { w = texture_->width(); } } if(h < 0) { if(area_.h()) { h = area_.h()*2; } else { h = texture_->height(); } } setDim(w,h); } void ImageWidget::handleDraw() const { if(area_.w() == 0) { KRE::Canvas::getInstance()->blitTexture(texture_, rotate_, rect(x(), y(), width(), height())); } else { KRE::Canvas::getInstance()->blitTexture(texture_, area_, rotate_, rect(x(), y(), width(), height())); } } WidgetPtr ImageWidget::clone() const { return WidgetPtr(new ImageWidget(*this)); } BEGIN_DEFINE_CALLABLE(ImageWidget, Widget) DEFINE_FIELD(image, "string") return variant(obj.image_name_); DEFINE_SET_FIELD_TYPE("string|map") if(value.is_string()) { obj.image_name_ = value.as_string(); obj.texture_ = KRE::Texture::createTexture(obj.image_name_); } else { obj.texture_ = KRE::Texture::createTexture(value); } DEFINE_FIELD(area, "[int,int,int,int]") return obj.area_.write(); DEFINE_SET_FIELD obj.area_ = rect(value); DEFINE_FIELD(rotation, "decimal") return variant(obj.rotate_); DEFINE_SET_FIELD obj.rotate_ = value.as_float(); DEFINE_FIELD(width, "int") return variant(obj.texture_->width()); DEFINE_FIELD(height, "int") return variant(obj.texture_->height()); DEFINE_FIELD(image_width, "int") return variant(obj.texture_->width()); DEFINE_FIELD(image_height, "int") return variant(obj.texture_->height()); DEFINE_FIELD(image_wh, "[int,int]") std::vector<variant> v; v.emplace_back(variant(obj.area_.w())); v.emplace_back(variant(obj.area_.h())); return variant(&v); DEFINE_SET_FIELD obj.init(value[0].as_int(), value[1].as_int()); END_DEFINE_CALLABLE(ImageWidget) GuiSectionWidget::GuiSectionWidget(const std::string& id, int w, int h, int scale) : section_(GuiSection::get(id)), scale_(scale) { setEnvironment(); if(section_ && w == -1) { setDim((section_->width()/2)*scale_, (section_->height()/2)*scale_); } else { setDim(w,h); } } GuiSectionWidget::GuiSectionWidget(const variant& v, game_logic::FormulaCallable* e) : Widget(v,e), section_(GuiSection::get(v)), scale_(v["scale"].as_int(1)) { if(!v.has_key("width") && section_) { setDim((section_->width()/2)*scale_, (section_->height()/2)*scale_); } } void GuiSectionWidget::setGuiSection(const std::string& id) { section_ = GuiSection::get(id); } void GuiSectionWidget::handleDraw() const { if(section_) { section_->blit(x(), y(), width(), height()); } } WidgetPtr GuiSectionWidget::clone() const { return WidgetPtr(new GuiSectionWidget(*this)); } BEGIN_DEFINE_CALLABLE(GuiSectionWidget, Widget) DEFINE_FIELD(name, "string") return variant(); DEFINE_SET_FIELD obj.setGuiSection(value.as_string()); DEFINE_FIELD(scale, "decimal") return variant(obj.scale_); DEFINE_SET_FIELD if(obj.section_) { obj.setDim((obj.section_->width()/2)*obj.scale_, (obj.section_->height()/2)*obj.scale_); } END_DEFINE_CALLABLE(GuiSectionWidget) }
25.651042
104
0.675533
1958ce79e96fc3c2e4c92e2e5427e6916560a676
8,696
cpp
C++
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
#include "richtext.hpp" #include <SFML/Graphics.hpp> #include <sstream> static std::map<sf::String, sf::Color> colors; // same as sf::Text styles // define them locally to redefine them for a child class for example #define Regular 0 #define Bold 1 #define Italic 2 #define Underlined 4 // TextChunk functions TextChunk::TextChunk() { style = Regular; color = sf::Color::White; endsInNewline = false; } void TextChunk::add(std::vector<TextChunk*>& chunks, TextChunk*& current, TextChunk* last) { chunks.push_back(new TextChunk()); current = chunks.back(); if(chunks.size() > 2) { current->style = last->style; current->color = last->color; } } void TextChunk::format(TextChunk*& current, TextChunk* last, int32_t style) { if((last->style & style) >= 0) current->style ^= style; else current->style |= style; } // RichText functions RichText::RichText() { nlratio = 1.5; csize = 20; // default parameters font = nullptr; } RichText::RichText(const sf::String& source, const sf::Font& font, uint32_t csize) { nlratio = 1.5; this->csize = csize; this->font = &font; setString(source); // update the displayed string } RichText::~RichText() { clear(); } sf::String RichText::getString() const { return string; } sf::String RichText::getSource() const { return source; } void RichText::setString(const sf::String& source) { this->source = source; if(!font) return; // nothing to display, return clear(); if(source.getSize() == 0) return; chunks.push_back(new TextChunk()); TextChunk* current = chunks[0]; TextChunk* last = nullptr; bool escaped = false; // create the chunks for(uint32_t i = 0; i < source.getSize(); ++i) { last = current; if(escaped) { current->text += source[i]; escaped = false; continue; } switch(source[i]) { case '~': // italics { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Italic); current->color = last->color; break; } case '*': // bold { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Bold); current->color = last->color; break; } case '_': // underline { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Underlined); current->color = last->color; break; } case '#': // color { int32_t length = 0; int32_t start = i + 1; // seek forward until the next whitespace while(!isspace(source[++i])) ++length; TextChunk::add(chunks, current, last); bool isValid; sf::Color c = getColor(source.toWideString().substr(start, length), isValid); if(isValid) current->color = c; break; } case '\\': // escape sequence for escaping formatting characters { if(escaped) { current->text += source[i]; escaped = false; break; } if (i + 1 < source.getSize()) { switch (source[i + 1]) { case '~': case '*': case '_': case '#': { escaped = true; break; } default: break; } } if (!escaped) current->text += source[i]; break; } case '\n': // make a new chunk in the case of a newline { current->endsInNewline = true; TextChunk::add(chunks, current, last); break; } default: { escaped = false; current->text += source[i]; // append the character break; } } } build(); } void RichText::build() { float boundY = csize*nlratio; sf::Text* t = nullptr; sf::Vector2f partPos(0, 0); // still forced to clear here for(size_t i = 0; i < parts.size(); ++i) if(parts[i] != nullptr) delete parts[i]; parts.clear(); bounds.left = 0; bounds.top = 0; bounds.width = 0; bounds.height = 0; for(size_t i = 0; i < chunks.size(); ++i) { if(chunks[i]->text.getSize() != 0) { t = new sf::Text(); t->setFillColor(chunks[i]->color); t->setString(chunks[i]->text); t->setStyle(chunks[i]->style); t->setCharacterSize(csize); if(font) t->setFont(*font); t->setPosition(partPos); } if(t) partPos.x += t->getLocalBounds().width; if(partPos.x >= bounds.width) bounds.width = partPos.x; if(chunks[i]->endsInNewline) { partPos.y += boundY; partPos.x = 0; bounds.height += boundY; } else if(i == chunks.size()-1) { bounds.height += boundY; } if(t) { parts.push_back((sf::Drawable*)t); t = nullptr; } } } void RichText::clear() { for(size_t i = 0; i < chunks.size(); ++i) delete chunks[i]; chunks.clear(); for(size_t i = 0; i < parts.size(); ++i) if(parts[i] != nullptr) delete parts[i]; parts.clear(); bounds.left = 0; bounds.top = 0; bounds.width = 0; bounds.height = 0; } uint32_t RichText::getCharacterSize() const { return csize; } void RichText::setCharacterSize(uint32_t size) { csize = (size < 1) ? 1 : size; build(); } float RichText::getNewLineSize() const { return nlratio; } void RichText::setNewLineSize(float size) { nlratio = (size <= 0) ? 1.5 : size; build(); } const sf::Font* RichText::getFont() const { return font; } void RichText::setFont(const sf::Font& font) { this->font = &font; build(); } void RichText::setFont(const sf::Font* font) { this->font = font; build(); } sf::FloatRect RichText::getLocalBounds() const { return bounds; } sf::FloatRect RichText::getGlobalBounds() const { return getTransform().transformRect(getLocalBounds()); } void RichText::addColor(const sf::String& name, const sf::Color& color) { colors[name] = color; } void RichText::addColor(const sf::String& name, uint32_t argbHex) { colors[name] = getColor(argbHex); } void RichText::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); for(size_t i = 0; i < parts.size(); ++i) if(parts[i]) target.draw(*parts[i], states); } void RichText::initializeColors() { colors["default"] = sf::Color::White; colors["black"] = sf::Color::Black; colors["blue"] = sf::Color::Blue; colors["cyan"] = sf::Color::Cyan; colors["green"] = sf::Color::Green; colors["magenta"] = sf::Color::Magenta; colors["red"] = sf::Color::Red; colors["white"] = sf::Color::White; colors["yellow"] = sf::Color::Yellow; } sf::Color RichText::getColor(const sf::String& source, bool& isValid) { std::map<sf::String, sf::Color>::const_iterator result = colors.find(source); if(result == colors.end()) { // basic hexadecimal check for(size_t i = 0; i < source.getSize(); ++i) { if((source[i] < 'a' || source [i] > 'f') && (source[i] < 'A' || source[i] > 'F') && (source[i] < '0' || source[i] > '9')) { isValid = false; return sf::Color::White; } } uint32_t hex = 0x0; if(!(std::istringstream(source) >> std::hex >> hex)) { // Error parsing; return default isValid = false; return sf::Color::White; } isValid = true; return getColor(hex); } isValid = true; return result->second; } sf::Color RichText::getColor(uint32_t argbHex) { argbHex |= 0xff000000; return sf::Color(argbHex >> 16 & 0xFF, argbHex >> 8 & 0xFF, argbHex >> 0 & 0xFF, argbHex >> 24 & 0xFF); }
24.426966
133
0.504715
1959a87e2e79912fef60d33de6eec1fc1d807a5b
17,024
cc
C++
L1Trigger/L1TMuonEndCap/src/EMTFTrack2016Tools.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TMuonEndCap/src/EMTFTrack2016Tools.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
L1Trigger/L1TMuonEndCap/src/EMTFTrack2016Tools.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "L1Trigger/L1TMuonEndCap/interface/EMTFTrack2016Tools.h" namespace l1t { void EMTFTrack2016::ImportSP( const emtf::SP _SP, int _sector) { EMTFTrack2016::set_sector ( _sector ); EMTFTrack2016::set_sector_GMT ( calc_sector_GMT(_sector) ); EMTFTrack2016::set_mode ( _SP.Mode() ); EMTFTrack2016::set_quality ( _SP.Quality_GMT() ); EMTFTrack2016::set_bx ( _SP.TBIN() - 3 ); EMTFTrack2016::set_pt_GMT ( _SP.Pt_GMT() ); EMTFTrack2016::set_pt_LUT_addr ( _SP.Pt_LUT_addr() ); EMTFTrack2016::set_eta_GMT ( _SP.Eta_GMT() ); EMTFTrack2016::set_phi_loc_int ( _SP.Phi_full() ); EMTFTrack2016::set_phi_GMT ( _SP.Phi_GMT() ); EMTFTrack2016::set_charge ( (_SP.C() == 1) ? -1 : 1 ); // uGMT uses opposite of physical charge (to match pdgID) EMTFTrack2016::set_charge_GMT ( _SP.C() ); EMTFTrack2016::set_charge_valid ( _SP.VC() ); EMTFTrack2016::set_pt ( calc_pt( pt_GMT ) ); EMTFTrack2016::set_eta ( calc_eta( eta_GMT ) ); EMTFTrack2016::set_phi_loc_deg ( calc_phi_loc_deg( phi_loc_int ) ); EMTFTrack2016::set_phi_loc_rad ( calc_phi_loc_rad( phi_loc_int ) ); EMTFTrack2016::set_phi_glob_deg ( calc_phi_glob_deg( phi_loc_deg, _sector ) ); EMTFTrack2016::set_phi_glob_rad ( calc_phi_glob_rad( phi_loc_rad, _sector ) ); } // End EMTFTrack2016::ImportSP // Calculates special chamber ID for track address sent to uGMT, using CSC_ID, subsector, neighbor, and station int calc_uGMT_chamber( int _csc_ID, int _subsector, int _neighbor, int _station) { if (_station == 1) { if ( _csc_ID == 3 && _neighbor == 1 && _subsector == 2 ) return 1; else if ( _csc_ID == 6 && _neighbor == 1 && _subsector == 2 ) return 2; else if ( _csc_ID == 9 && _neighbor == 1 && _subsector == 2 ) return 3; else if ( _csc_ID == 3 && _neighbor == 0 && _subsector == 2 ) return 4; else if ( _csc_ID == 6 && _neighbor == 0 && _subsector == 2 ) return 5; else if ( _csc_ID == 9 && _neighbor == 0 && _subsector == 2 ) return 6; else return 0; } else { if ( _csc_ID == 3 && _neighbor == 1 ) return 1; else if ( _csc_ID == 9 && _neighbor == 1 ) return 2; else if ( _csc_ID == 3 && _neighbor == 0 ) return 3; else if ( _csc_ID == 9 && _neighbor == 0 ) return 4; else return 0; } } // Unpacks pT LUT address into dPhi, dTheta, CLCT, FR, eta, and mode // Based on L1Trigger/L1TMuonEndCap/interface/PtAssignment.h // "Mode" here is the true mode, not the inverted mode used in PtAssignment.h void EMTFTrack2016::ImportPtLUT(int _mode, unsigned long _address) { if (_mode == 12) { // mode_inv == 3 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_12 (dPhi_12 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_12 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_2 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 10) { // mode_inv == 5 EMTFTrack2016::set_dPhi_13 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_13 (dPhi_13 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_13 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_3 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_3 (clct_3 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_3 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 9) { // mode_inv == 9 EMTFTrack2016::set_dPhi_14 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_14 (dPhi_14 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_14 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_4 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_4 (clct_4 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_4 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 6) { // mode_inv = 6 EMTFTrack2016::set_dPhi_23 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_23 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_3 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_3 (clct_3 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_2 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_3 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 5) { // mode_inv == 10 EMTFTrack2016::set_dPhi_24 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_24 (dPhi_24 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_24 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_4 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_4 (clct_4 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_2 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_4 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 3) { // mode_inv == 12 EMTFTrack2016::set_dPhi_34 ( ( _address >> (0) ) & ( (1 << 9) - 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+9) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_34 ( ( _address >> (0+9+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_3 ( ( _address >> (0+9+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_3 (clct_3 * ( ( ( _address >> (0+9+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_clct_4 ( ( _address >> (0+9+1+3+2+1) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_4 (clct_4 * ( ( ( _address >> (0+9+1+3+2+1+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_3 ( ( _address >> (0+9+1+3+2+1+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_fr_4 ( ( _address >> (0+9+1+3+2+1+2+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+9+1+3+2+1+2+1+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 14) { // mode_inv == 7 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_23 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_12 (dPhi_12 * (( ( _address >> (0+7+5) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+7+5+1) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_13 ( ( _address >> (0+7+5+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+7+5+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+1+1+3+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 13) { // mode_inv == 11 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_24 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_12 (dPhi_12 * (( ( _address >> (0+7+5) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_24 (dPhi_24 * (( ( _address >> (0+7+5+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_14 ( ( _address >> (0+7+5+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+7+5+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+1+1+3+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 11) { EMTFTrack2016::set_dPhi_13 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_34 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_13 (dPhi_13 * (( ( _address >> (0+7+5) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+7+5+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_14 ( ( _address >> (0+7+5+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_1 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_1 (clct_1 * ( ( ( _address >> (0+7+5+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+1+1+3+2+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+1+1+3+2+1+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 7) { // mode_inv == 14 EMTFTrack2016::set_dPhi_23 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_34 ( ( _address >> (0+7) ) & ( (1 << 6) - 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+7+6) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+7+6+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dTheta_24 ( ( _address >> (0+7+6+1+1) ) & ( (1 << 3) - 1) ); EMTFTrack2016::set_clct_2 ( ( _address >> (0+7+5+1+1+3) ) & ( (1 << 2) - 1) ); EMTFTrack2016::set_clct_2 (clct_2 * ( ( ( _address >> (0+7+6+1+1+3+2) ) & ( (1 << 1) - 1) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+6+1+1+3+2+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+6+1+1+3+2+1+5) ) & ( (1 << 4) - 1) ); } else if (_mode == 15) { // mode_inv == 15 EMTFTrack2016::set_dPhi_12 ( ( _address >> (0) ) & ( (1 << 7) - 1) ); EMTFTrack2016::set_dPhi_23 ( ( _address >> (0+7) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_dPhi_34 ( ( _address >> (0+7+5) ) & ( (1 << 6) - 1) ); EMTFTrack2016::set_dPhi_23 (dPhi_23 * (( ( _address >> (0+7+5+6) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_dPhi_34 (dPhi_34 * (( ( _address >> (0+7+5+6+1) ) & ( (1 << 1) - 1 ) ) == 0 ? -1 : 1) ); EMTFTrack2016::set_fr_1 ( ( _address >> (0+7+5+6+1+1) ) & ( (1 << 1) - 1) ); EMTFTrack2016::set_eta_LUT ( ( _address >> (0+7+5+6+1+1+1) ) & ( (1 << 5) - 1) ); EMTFTrack2016::set_mode_LUT ( ( _address >> (0+7+5+6+1+1+1+5) ) & ( (1 << 4) - 1) ); } } // End function: void EMTFTrack2016::ImportPtLUT EMTFTrack2016 EMTFTrack2016Extra::CreateEMTFTrack2016() { EMTFTrack2016 thisTrack; for (int iHit = 0; iHit < NumHitsExtra(); iHit++) { thisTrack.push_Hit( _HitsExtra.at(iHit).CreateEMTFHit2016() ); } thisTrack.set_endcap ( Endcap() ); thisTrack.set_sector ( Sector() ); thisTrack.set_sector_GMT ( Sector_GMT() ); thisTrack.set_sector_index ( Sector_index() ); thisTrack.set_mode ( Mode() ); thisTrack.set_mode_LUT ( Mode_LUT() ); thisTrack.set_quality ( Quality() ); thisTrack.set_bx ( BX() ); thisTrack.set_pt ( Pt() ); thisTrack.set_pt_GMT ( Pt_GMT() ); thisTrack.set_pt_LUT_addr ( Pt_LUT_addr() ); thisTrack.set_eta ( Eta() ); thisTrack.set_eta_GMT ( Eta_GMT() ); thisTrack.set_eta_LUT ( Eta_LUT() ); thisTrack.set_phi_loc_int ( Phi_loc_int() ); thisTrack.set_phi_loc_deg ( Phi_loc_deg() ); thisTrack.set_phi_loc_rad ( Phi_loc_rad() ); thisTrack.set_phi_GMT ( Phi_GMT() ); thisTrack.set_phi_glob_deg ( Phi_glob_deg() ); thisTrack.set_phi_glob_rad ( Phi_glob_rad() ); thisTrack.set_charge ( Charge() ); thisTrack.set_charge_GMT ( Charge_GMT() ); thisTrack.set_charge_valid ( Charge_valid() ); thisTrack.set_dPhi_12 ( DPhi_12() ); thisTrack.set_dPhi_13 ( DPhi_13() ); thisTrack.set_dPhi_14 ( DPhi_14() ); thisTrack.set_dPhi_23 ( DPhi_23() ); thisTrack.set_dPhi_24 ( DPhi_24() ); thisTrack.set_dPhi_34 ( DPhi_34() ); thisTrack.set_dTheta_12 ( DTheta_12() ); thisTrack.set_dTheta_13 ( DTheta_13() ); thisTrack.set_dTheta_14 ( DTheta_14() ); thisTrack.set_dTheta_23 ( DTheta_23() ); thisTrack.set_dTheta_24 ( DTheta_24() ); thisTrack.set_dTheta_34 ( DTheta_34() ); thisTrack.set_clct_1 ( CLCT_1() ); thisTrack.set_clct_2 ( CLCT_2() ); thisTrack.set_clct_3 ( CLCT_3() ); thisTrack.set_clct_4 ( CLCT_4() ); thisTrack.set_fr_1 ( FR_1() ); thisTrack.set_fr_2 ( FR_2() ); thisTrack.set_fr_3 ( FR_3() ); thisTrack.set_fr_4 ( FR_4() ); thisTrack.set_track_num ( Track_num() ); thisTrack.set_has_neighbor ( Has_neighbor() ); thisTrack.set_all_neighbor ( All_neighbor() ); return thisTrack; } // End EMTFTrack2016Extra::CreateEMTFTrack2016 } // End namespace l1t
67.288538
122
0.490954
195a845d8e8e2cc67adee07d0846fa4e01e7a053
169
cpp
C++
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
1
2015-11-05T06:07:12.000Z
2015-11-05T06:07:12.000Z
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
null
null
null
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
null
null
null
#include "test.h" #include "runtime/RegEx.h" using namespace snow; TEST_SUITE(RegEx); TEST_CASE(simple_match) { PENDING(); } TEST_CASE(simple_search) { PENDING(); }
13
26
0.721893
195bf2eed8dbab9b50896977c600a3caebae6cab
4,047
hpp
C++
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-2019 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "sched/entry/entry.hpp" #include "sched/queue/queue.hpp" class write_entry : public sched_entry, public postponed_fields<write_entry, ccl_sched_entry_field_src_mr, ccl_sched_entry_field_dst_mr> { public: static constexpr const char* class_name() noexcept { return "WRITE"; } write_entry() = delete; write_entry(ccl_sched* sched, ccl_buffer src_buf, atl_mr_t* src_mr, size_t cnt, ccl_datatype_internal_t dtype, size_t dst, atl_mr_t* dst_mr, size_t dst_buf_off) : sched_entry(sched), src_buf(src_buf), src_mr(src_mr), cnt(cnt), dtype(dtype), dst(dst), dst_mr(dst_mr), dst_buf_off(dst_buf_off) { } ~write_entry() { if (status == ccl_sched_entry_status_started) { LOG_DEBUG("cancel WRITE entry dst ", dst, ", req ", &req); atl_comm_cancel(sched->bin->get_comm_ctx(), &req); } } void start() override { update_fields(); LOG_DEBUG("WRITE entry dst ", dst, ", req ", &req); CCL_THROW_IF_NOT(src_buf && src_mr && dst_mr, "incorrect values"); if (!cnt) { status = ccl_sched_entry_status_complete; return; } size_t bytes = cnt * ccl_datatype_get_size(dtype); atl_status_t atl_status = atl_comm_write(sched->bin->get_comm_ctx(), src_buf.get_ptr(bytes), bytes, src_mr, (uint64_t)dst_mr->buf + dst_buf_off, dst_mr->r_key, dst, &req); update_status(atl_status); } void update() override { int req_status; atl_status_t atl_status = atl_comm_check(sched->bin->get_comm_ctx(), &req_status, &req); if (unlikely(atl_status != atl_status_success)) { CCL_THROW("WRITE entry failed. atl_status: ", atl_status_to_str(atl_status)); } if (req_status) { LOG_DEBUG("WRITE entry done, dst ", dst); status = ccl_sched_entry_status_complete; } } const char* name() const override { return class_name(); } atl_mr_t*& get_field_ref(field_id_t<ccl_sched_entry_field_src_mr> id) { return src_mr; } atl_mr_t*& get_field_ref(field_id_t<ccl_sched_entry_field_dst_mr> id) { return dst_mr; } protected: void dump_detail(std::stringstream& str) const override { ccl_logger::format(str, "dt ", ccl_datatype_get_name(dtype), ", cnt ", cnt, ", src_buf ", src_buf, ", src_mr ", src_mr, ", dst ", dst, ", dst_mr ", dst_mr, ", dst_off ", dst_buf_off, ", comm_id ", sched->coll_param.comm->id(), ", req %p", &req, "\n"); } private: ccl_buffer src_buf; atl_mr_t* src_mr; size_t cnt; ccl_datatype_internal_t dtype; size_t dst; atl_mr_t* dst_mr; size_t dst_buf_off; atl_req_t req{}; };
29.540146
100
0.547072
19603e37219f2defe3844bb292c7f5ef815118a0
10,569
cpp
C++
src/domain.cpp
egdaub/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
12
2017-10-05T22:04:40.000Z
2020-08-31T08:32:17.000Z
src/domain.cpp
jhsa26/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
3
2020-05-06T16:48:32.000Z
2020-09-18T11:41:41.000Z
src/domain.cpp
jhsa26/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
12
2017-03-24T19:15:27.000Z
2020-08-31T08:32:18.000Z
#include <iostream> #include <fstream> #include <cassert> #include <string> #include "block.hpp" #include "cartesian.hpp" #include "domain.hpp" #include "fd.hpp" #include "fields.hpp" #include "friction.hpp" #include "interface.hpp" #include "rk.hpp" #include "slipweak.hpp" #include "stz.hpp" #include <mpi.h> using namespace std; domain::domain(const char* filename) { // constructor, no default as need to allocate memory int sbporder; string* iftype; int** nx_block; int** xm_block; nx_block = new int* [3]; xm_block = new int* [3]; // open input file, find appropriate place and read in parameters string line; ifstream paramfile(filename, ifstream::in); if (paramfile.is_open()) { // scan to start of domain list while (getline(paramfile,line)) { if (line == "[fdfault.domain]") { break; } } if (paramfile.eof()) { cerr << "Error reading domain from input file\n"; MPI_Abort(MPI_COMM_WORLD,-1); } else { // read domain variables paramfile >> ndim; paramfile >> mode; for (int i=0; i<3; i++) { paramfile >> nx[i]; } for (int i=0; i<3; i++) { paramfile >> nblocks[i]; } for (int i=0; i<3; i++) { nx_block[i] = new int [nblocks[i]]; xm_block[i] = new int [nblocks[i]]; } for (int i=0; i<3; i++) { for (int j=0; j<nblocks[i]; j++) { paramfile >> nx_block[i][j]; } } paramfile >> nifaces; iftype = new string [nifaces]; for (int i=0; i<nifaces; i++) { paramfile >> iftype[i]; } paramfile >> sbporder; paramfile >> material; } } else { cerr << "Error opening input file in domain.cpp\n"; MPI_Abort(MPI_COMM_WORLD,-1); } paramfile.close(); // check validity of input parameters assert(ndim == 2 || ndim == 3); assert(mode == 2 || mode == 3); assert(material == "elastic" || material == "plastic"); if (ndim == 2) { assert(nx[2] == 1); } for (int i=0; i<3; i++) { assert(nx[i] > 0); assert(nblocks[i] > 0); int sum = 0; for (int j=0; j<nblocks[i]; j++) { sum += nx_block[i][j]; } assert(sum == nx[i]); } // set other domain parameters if (material == "elastic") { is_plastic = false; } else { is_plastic = true; } nblockstot = nblocks[0]*nblocks[1]*nblocks[2]; for (int i=0; i<3; i++) { for (int j=0; j<nblocks[i]; j++) { if (j==0) { xm_block[i][j] = 0; } else { xm_block[i][j] = xm_block[i][j-1]+nx_block[i][j-1]; } } } // allocate memory for fd coefficients fd = new fd_type(sbporder); // set up cartesian type to hold domain decomposition information cart = new cartesian(filename, ndim, nx, nblocks, nx_block, xm_block, sbporder); f = new fields(filename, ndim, mode, material, *cart); // allocate memory and create blocks allocate_blocks(filename, nx_block, xm_block); // exchange neighbors to fill in ghost cells f->exchange_neighbors(); f->exchange_grid(); // allocate memory and create interfaces allocate_interfaces(filename, iftype); // set interface variables to match boundary conditions for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(0., 0., *f, true); } for (int i=0; i<3; i++) { delete[] nx_block[i]; delete[] xm_block[i]; } delete[] nx_block; delete[] xm_block; } domain::~domain() { // destructor, no default as need to deallocate memory deallocate_blocks(); deallocate_interfaces(); delete fd; delete cart; delete f; } int domain::get_ndim() const { // returns number of spatial dimensions return ndim; } int domain::get_mode() const { // returns mode return mode; } int domain::get_nblocks(const int index) const { // returns number of blocks assert(index >= 0 && index < 3); return nblocks[index]; } int domain::get_nblockstot() const { return nblockstot; } int domain::get_nifaces() const { return nifaces; } double domain::get_min_dx() const { // get min grid spacing divided by shear wave speed over all blocks double dxmin = 0., dxmintest, dxmin_all; for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { dxmintest = blocks[i][j][k]->get_min_dx(*f); if (dxmintest > 1.e-14) { // block has data if (dxmin <= 1.e-14 || dxmintest < dxmin) { dxmin = dxmintest; } } } } } if (dxmin <= 1.e-14) { cerr << "Error in domain.cpp get_min_dx -- a process does not have any grid spacing values\n"; MPI_Abort(MPI_COMM_WORLD,1); } MPI_Allreduce(&dxmin, &dxmin_all, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD); return dxmin_all; } void domain::do_rk_stage(const double dt, const int stage, const double t, rk_type& rk) { // advances domain fields for one RK stage of one time step // scale df by RK coefficient f->scale_df(rk.get_A(stage)); for (int i=0; i<nifaces; i++) { interfaces[i]->scale_df(rk.get_A(stage)); } // calculate df for blocks for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { blocks[i][j][k]->calc_df(dt,*f,*fd); // blocks[i][j][k]->set_mms(dt, t+rk.get_C(stage)*dt, *f); blocks[i][j][k]->set_boundaries(dt,*f); } } } // apply interface conditions for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(dt,t+rk.get_C(stage)*dt,*f,false); } // calculate df for interfaces for (int i=0; i<nifaces; i++) { interfaces[i]->calc_df(dt); } // update interfaces for (int i=0; i<nifaces; i++) { interfaces[i]->update(rk.get_B(stage)); } // update fields f->update(rk.get_B(stage)); // if last stage and response is plastic, solve plasticity equations if (stage+1 == rk.get_nstages() && is_plastic) { // set absolute stress f->set_stress(); for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { blocks[i][j][k]->calc_plastic(dt,*f); } } } // subtract stress f->remove_stress(); // apply interface conditions to correctly set slip rates (needed for correct output) for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(dt,t+rk.get_C(stage)*dt,*f,true); } } // exchange neighbors f->exchange_neighbors(); } void domain::free_exchange() { // frees MPI datatypes for ghost cell exchange f->free_exchange(); } void domain::set_stress() { // sets absolute stress f->set_stress(); } void domain::remove_stress() { // subtracts initial stress f->remove_stress(); } void domain::allocate_blocks(const char* filename, int** nx_block, int** xm_block) { // allocate memory for blocks and initialize int nxtmp[3]; int xmtmp[3]; int coords[3]; blocks = new block*** [nblocks[0]]; for (int i=0; i<nblocks[0]; i++) { blocks[i] = new block** [nblocks[1]]; } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { blocks[i][j] = new block* [nblocks[2]]; } } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { nxtmp[0] = nx_block[0][i]; nxtmp[1] = nx_block[1][j]; nxtmp[2] = nx_block[2][k]; xmtmp[0] = xm_block[0][i]; xmtmp[1] = xm_block[1][j]; xmtmp[2] = xm_block[2][k]; coords[0] = i; coords[1] = j; coords[2] = k; blocks[i][j][k] = new block(filename, ndim, mode, material, coords, nxtmp, xmtmp, *cart, *f, *fd); } } } } void domain::allocate_interfaces(const char* filename, string* iftype) { // allocate memory for interfaces for (int i=0; i<nifaces; i++) { assert(iftype[i] == "locked" || iftype[i] == "frictionless" || iftype[i] == "slipweak" || iftype[i] == "stz"); } interfaces = new interface* [nifaces]; for (int i=0; i<nifaces; i++) { if (iftype[i] == "locked") { interfaces[i] = new interface(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "frictionless") { interfaces[i] = new friction(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "slipweak") { interfaces[i] = new slipweak(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "stz") { interfaces[i] = new stz(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } } } void domain::deallocate_blocks() { // deallocate memory for blocks for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { delete blocks[i][j][k]; } } } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { delete[] blocks[i][j]; } } for (int i=0; i<nblocks[0]; i++) { delete[] blocks[i]; } delete[] blocks; } void domain::deallocate_interfaces() { // deallocate memory for interfaces for (int i=0; i<nifaces; i++) { delete interfaces[i]; } delete[] interfaces; }
25.40625
118
0.504589
19615eb2b58a87deb7d55a47659c83c59f8acfb8
937
hh
C++
ImageSampleMap/imagesamplemap.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
ImageSampleMap/imagesamplemap.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
ImageSampleMap/imagesamplemap.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
#pragma once #include <functional> #include <Eigen/Core> typedef unsigned short ushort; typedef unsigned char uchar; namespace bold { /** Produces a map used in sub-sampling image data. * * A granularity function allows processing fewer than all pixels * in the image. * * Granularity is calculated based on y-value, and is specified in * both x and y dimensions. */ class ImageSampleMap { public: ImageSampleMap(std::function<Eigen::Matrix<uchar,2,1>(ushort)> granularityFunction, ushort width, ushort height); unsigned getPixelCount() const { return d_pixelCount; } ushort getSampleRowCount() const { return static_cast<ushort>(d_granularities.size()); } std::vector<Eigen::Matrix<uchar,2,1>>::const_iterator begin() const { return d_granularities.begin(); } private: std::vector<Eigen::Matrix<uchar,2,1>> d_granularities; unsigned d_pixelCount; ushort d_width; }; }
26.027778
117
0.712914
19637585ea01d69d75a6ce0307360b900e55b8fd
1,431
cpp
C++
aws-cpp-sdk-lakeformation/source/model/BatchPermissionsFailureEntry.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-lakeformation/source/model/BatchPermissionsFailureEntry.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-lakeformation/source/model/BatchPermissionsFailureEntry.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T12:02:58.000Z
2021-11-09T12:02:58.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lakeformation/model/BatchPermissionsFailureEntry.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace LakeFormation { namespace Model { BatchPermissionsFailureEntry::BatchPermissionsFailureEntry() : m_requestEntryHasBeenSet(false), m_errorHasBeenSet(false) { } BatchPermissionsFailureEntry::BatchPermissionsFailureEntry(JsonView jsonValue) : m_requestEntryHasBeenSet(false), m_errorHasBeenSet(false) { *this = jsonValue; } BatchPermissionsFailureEntry& BatchPermissionsFailureEntry::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("RequestEntry")) { m_requestEntry = jsonValue.GetObject("RequestEntry"); m_requestEntryHasBeenSet = true; } if(jsonValue.ValueExists("Error")) { m_error = jsonValue.GetObject("Error"); m_errorHasBeenSet = true; } return *this; } JsonValue BatchPermissionsFailureEntry::Jsonize() const { JsonValue payload; if(m_requestEntryHasBeenSet) { payload.WithObject("RequestEntry", m_requestEntry.Jsonize()); } if(m_errorHasBeenSet) { payload.WithObject("Error", m_error.Jsonize()); } return payload; } } // namespace Model } // namespace LakeFormation } // namespace Aws
19.08
90
0.742837
1963f5b09d876859feb4f7a7147f97955500b5fb
2,013
hpp
C++
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
10
2016-10-26T13:36:18.000Z
2020-03-16T02:19:40.000Z
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
null
null
null
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
5
2016-10-07T12:28:59.000Z
2022-03-22T14:16:53.000Z
#ifndef qd_simple_locked_queue_hpp #define qd_simple_locked_queue_hpp qd_simple_locked_queue_hpp #include<array> #include<cassert> #include<mutex> #include<queue> class simple_locked_queue { std::mutex lock; std::queue<std::array<char, 128>> queue; typedef std::lock_guard<std::mutex> scoped_guard; typedef void(*ftype)(char*); /* some constants */ static const bool CLOSED = false; static const bool SUCCESS = true; void forwardall(char*, long i) { assert(i <= 120); if(i > 120) throw "up"; }; template<typename P, typename... Ts> void forwardall(char* buffer, long offset, P&& p, Ts&&... ts) { assert(offset <= 120); auto ptr = reinterpret_cast<P*>(&buffer[offset]); new (ptr) P(std::forward<P>(p)); forwardall(buffer, offset+sizeof(p), std::forward<Ts>(ts)...); } public: void open() { /* TODO this function should not even be here */ /* no-op as this is an "infinite" queue that always accepts more data */ } /** * @brief enqueues an entry * @tparam P return type of associated function * @param op wrapper function for associated function * @return SUCCESS on successful storing in queue, CLOSED otherwise */ template<typename... Ps> bool enqueue(ftype op, Ps*... ps) { std::array<char, 128> val; scoped_guard l(lock); queue.push(val); forwardall(queue.back().data(), 0, std::move(op), std::move(*ps)...); return SUCCESS; } /** execute all stored operations */ void flush() { scoped_guard l(lock); while(!queue.empty()) { auto operation = queue.front(); char* ptr = operation.data(); ftype* fun = reinterpret_cast<ftype*>(ptr); ptr += sizeof(ftype*); (*fun)(ptr); queue.pop(); } } /** execute one stored operation */ void flush_one() { scoped_guard l(lock); if(!queue.empty()) { char* ptr = queue.front().data(); ftype* fun = reinterpret_cast<ftype*>(ptr); ptr += sizeof(ftype); (*fun)(ptr); queue.pop(); } } }; #endif /* qd_simple_locked_queue_hpp */
26.142857
75
0.646299
1967025b038338dffdebb29e92ee55902368b726
6,878
cpp
C++
Tools/NodeParticleSystem2Port/Port.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
Tools/NodeParticleSystem2Port/Port.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
Tools/NodeParticleSystem2Port/Port.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
/* Port.cpp (c)2005 Palestar, Richard Lyle */ #define NODEPARTICLESYSTEM2PORT_DLL #include "stdafx.h" #include "Port.h" #include "Math/Helpers.h" #include "Tools/ScenePort/ChildFrame.h" #include "Tools/ResourcerDoc/Port.h" //---------------------------------------------------------------------------- IMPLEMENT_FACTORY( NodeParticleSystem2Port, NodePort ); REGISTER_FACTORY_KEY( NodeParticleSystem2Port, 4017674422569680758 ); BEGIN_PROPERTY_LIST( NodeParticleSystem2Port, NodePort ); ADD_PROPERTY( m_Seed ); ADD_PROPERTY( m_ParticleCount ); ADD_ENUM_PROPERTY( m_OriginType ); ADD_ENUM_OPTION( m_OriginType, BOX ); ADD_ENUM_OPTION( m_OriginType, SPHERE ); ADD_ENUM_OPTION( m_OriginType, LINE ); ADD_ENUM_OPTION( m_OriginType, CIRCLE ); ADD_PROPERTY( m_MinOrigin ); ADD_PROPERTY( m_MaxOrigin ); ADD_PROPERTY( m_MinVelocity ); ADD_PROPERTY( m_MaxVelocity ); ADD_PROPERTY( m_MinAcceleration ); ADD_PROPERTY( m_MaxAcceleration ); ADD_PROPERTY( m_MinLife ); ADD_PROPERTY( m_MaxLife ); ADD_PROPERTY( m_ReverseTime ); ADD_PROPERTY( m_bLocalSpace ); ADD_PROPERTY( m_Life ); ADD_PORT_PROPERTY( m_MaterialPort, MaterialPort ); ADD_PROPERTY( m_Visible ); ADD_PROPERTY( m_VisibleV ); ADD_PROPERTY( m_VisibleA ); ADD_PROPERTY( m_Scale ); ADD_PROPERTY( m_ScaleV ); ADD_PROPERTY( m_ScaleA ); ADD_PROPERTY( m_ScaleVar ); ADD_PROPERTY( m_Alpha ); ADD_PROPERTY( m_AlphaV ); ADD_PROPERTY( m_AlphaA ); END_PROPERTY_LIST(); NodeParticleSystem2Port::NodeParticleSystem2Port() : NodePort() { m_Class = m_Type = CLASS_KEY(NodeParticleSystem2); m_Seed = rand(); m_ParticleCount = 100; m_OriginType = BOX; m_Life = 10.0f; m_Visible = 1.0f; m_VisibleV = m_VisibleA = 0.0f; m_Scale = 1.0f; m_ScaleV = m_ScaleA = 0.0f; m_ScaleVar = 0.0f; m_Alpha = 1.0f; m_AlphaV = m_AlphaA = 0.0f; m_bLocalSpace = false; m_MinOrigin = m_MinVelocity = m_MinAcceleration = Vector3(-1,-1,-1); m_MaxOrigin = m_MaxVelocity = m_MaxAcceleration = Vector3(1,1,1); m_MinLife = m_MaxLife = 1.0f; m_ReverseTime = false; } //------------------------------------------------------------------------------- const int VERSION_082399 = 82399; const int VERSION_020200 = 020200; const int VERSION_102201 = 102201; bool NodeParticleSystem2Port::read( const InStream & input ) { if (! NodePort::read( input ) ) { int version; input >> version; switch( version ) { case VERSION_102201: input >> m_Seed; input >> m_ParticleCount; input >> m_OriginType; input >> m_MinOrigin; input >> m_MaxOrigin; input >> m_MinVelocity; input >> m_MaxVelocity; input >> m_MinAcceleration; input >> m_MaxAcceleration; input >> m_MinLife; input >> m_MaxLife; input >> m_ReverseTime; input >> m_Life; input >> m_MaterialPort; input >> m_Visible; input >> m_VisibleV; input >> m_VisibleA; input >> m_Scale; input >> m_ScaleV; input >> m_ScaleA; input >> m_ScaleV; input >> m_ScaleVar; input >> m_Alpha; input >> m_AlphaV; input >> m_AlphaA; break; case VERSION_020200: input >> m_ParticleCount; input >> m_OriginType; input >> m_MinOrigin; input >> m_MaxOrigin; input >> m_MinVelocity; input >> m_MaxVelocity; input >> m_MinAcceleration; input >> m_MaxAcceleration; input >> m_MinLife; input >> m_MaxLife; input >> m_ReverseTime; input >> m_Life; input >> m_MaterialPort; input >> m_Visible; input >> m_VisibleV; input >> m_VisibleA; input >> m_Scale; input >> m_ScaleV; input >> m_ScaleA; input >> m_ScaleV; input >> m_ScaleVar; input >> m_Alpha; input >> m_AlphaV; input >> m_AlphaA; m_Seed = rand(); break; case VERSION_082399: input >> m_ParticleCount; input >> m_MinOrigin; input >> m_MaxOrigin; input >> m_MinVelocity; input >> m_MaxVelocity; input >> m_MinAcceleration; input >> m_MaxAcceleration; input >> m_MinLife; input >> m_MaxLife; input >> m_Life; input >> m_MaterialPort; input >> m_Visible; input >> m_VisibleV; input >> m_VisibleA; input >> m_Scale; input >> m_ScaleV; input >> m_ScaleA; input >> m_ScaleV; input >> m_Alpha; input >> m_AlphaV; input >> m_AlphaA; m_Seed = rand(); m_OriginType = BOX; m_ScaleVar = 0.0f; m_ReverseTime = false; break; } } return true; } //------------------------------------------------------------------------------- void NodeParticleSystem2Port::dependencies( DependentArray & dep ) { dep.push( m_MaterialPort ); } CFrameWnd * NodeParticleSystem2Port::createView() { return NodePort::createView(); } BaseNode * NodeParticleSystem2Port::createNode() { return NodePort::createNode(); } void NodeParticleSystem2Port::initializeNode( BaseNode * pNode ) { NodePort::initializeNode( pNode ); NodeParticleSystem2 * pSystem = dynamic_cast<NodeParticleSystem2 *>( pNode ); if ( pSystem != NULL ) { srand( m_Seed ); // create all the particles for(int i=0;i<m_ParticleCount;i++) { Particle newParticle; switch( m_OriginType ) { case BOX: newParticle.origin = RandomVector( m_MinOrigin, m_MaxOrigin ); break; case SPHERE: { float minRadius = m_MinOrigin.magnitude(); float maxRadius = m_MaxOrigin.magnitude(); float radius = RandomFloat( minRadius, maxRadius ); Vector3 direction( RandomFloat( -1.0f, 1.0f ), RandomFloat( -1.0f, 1.0f ), RandomFloat( -1.0f, 1.0f) ); direction.normalize(); newParticle.origin = direction * radius; } break; case LINE: { Vector3 delta( m_MinOrigin - m_MaxOrigin ); float distance = delta.magnitude(); float d = RandomFloat( 0.0f, distance ); newParticle.origin = m_MaxOrigin + (delta * d); } break; case CIRCLE: { float minRadius = m_MinOrigin.magnitude(); float maxRadius = m_MaxOrigin.magnitude(); float radius = RandomFloat( minRadius, maxRadius ); Vector3 direction( RandomFloat( -1.0f, 1.0f ), 0, RandomFloat( -1.0f, 1.0f) ); direction.normalize(); newParticle.origin = direction * radius; } break; } newParticle.velocity = RandomVector( m_MinVelocity, m_MaxVelocity ); newParticle.acceleration = RandomVector( m_MinAcceleration, m_MaxAcceleration ); newParticle.life = RandomFloat( m_MinLife, m_MaxLife ); newParticle.scale = RandomFloat( -m_ScaleVar, m_ScaleVar ); pSystem->addParticle( newParticle ); } pSystem->setLife( m_Life ); pSystem->setMaterial( WidgetCast<Material>( Port::portResource( m_MaterialPort ) ) ); pSystem->setVisible( m_Visible, m_VisibleV, m_VisibleA ); pSystem->setScale( m_Scale, m_ScaleV, m_ScaleA ); pSystem->setAlpha( m_Alpha, m_AlphaV, m_AlphaA ); pSystem->setReverseTime( m_ReverseTime ); pSystem->setLocalSpace( m_bLocalSpace ); } } //------------------------------------------------------------------------------- // EOF
25.664179
108
0.658476
19675ab5730b5e672335d8c569df4766e88cfe3f
3,883
cc
C++
src/ssl_info_action.cc
jeff-cn/doogie
1b4ed74adecbae773b51e674d298e3d5b09e4244
[ "MIT" ]
291
2017-07-19T22:32:25.000Z
2022-02-16T03:03:21.000Z
charts/doogie-0.7.8/src/ssl_info_action.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
81
2017-09-06T15:46:27.000Z
2020-11-30T14:12:11.000Z
charts/doogie-0.7.8/src/ssl_info_action.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
29
2017-09-18T19:14:50.000Z
2022-01-24T06:03:17.000Z
#include "ssl_info_action.h" namespace doogie { SslInfoAction::SslInfoAction(const Cef& cef, BrowserWidget* browser_widg) : QWidgetAction(browser_widg), cef_(cef), browser_widg_(browser_widg) { } QWidget* SslInfoAction::createWidget(QWidget* parent) { auto errored_ssl_info = browser_widg_->ErroredSslInfo(); auto errored_ssl_callback = browser_widg_->ErroredSslCallback(); auto ssl_status = browser_widg_->SslStatus(); auto layout = new QVBoxLayout; // SSL notes cef_cert_status_t status = CERT_STATUS_NONE; if (errored_ssl_info) { status = errored_ssl_info->GetCertStatus(); } else if (ssl_status) { status = ssl_status->GetCertStatus(); } auto status_strings = CertStatuses(status); if (!status_strings.isEmpty()) { auto status_layout = new QHBoxLayout; status_layout->addWidget(new QLabel("SSL Notes:"), 0, Qt::AlignTop); status_layout->addWidget(new QLabel(status_strings.join("\n")), 1); layout->addLayout(status_layout); } // Version and insecure content if (ssl_status) { auto version_layout = new QHBoxLayout; version_layout->addWidget(new QLabel("SSL Version:")); version_layout->addWidget( new QLabel(CertSslVersion(ssl_status->GetSSLVersion())), 1); layout->addLayout(version_layout); if (ssl_status->GetContentStatus() != SSL_CONTENT_NORMAL_CONTENT) { layout->addWidget(new QLabel("Displayed or ran insecure content")); } } // TODO(cretz): allow bypass // The button to view OS-level dialog auto details_button = new QPushButton("View Certificate Details"); connect(details_button, &QPushButton::clicked, [=](bool) { bool ok = false; if (errored_ssl_info) { ok = cef_.ShowCertDialog(errored_ssl_info->GetX509Certificate()); } else if (ssl_status) { ok = cef_.ShowCertDialog(ssl_status->GetX509Certificate()); } if (!ok) qWarning() << "Failed to show native cert dialog"; }); layout->addWidget(details_button, 0, Qt::AlignCenter); layout->addStretch(1); auto widg = new QWidget(parent); widg->setLayout(layout); return widg; } QStringList SslInfoAction::CertStatuses(cef_cert_status_t status) { const QHash<cef_cert_status_t, QString> strings = { { CERT_STATUS_COMMON_NAME_INVALID, "Common Name Invalid" }, { CERT_STATUS_DATE_INVALID, "Date Invalid" }, { CERT_STATUS_AUTHORITY_INVALID, "Authority Invalid" }, { CERT_STATUS_NO_REVOCATION_MECHANISM, "No Revocation Mechanism" }, { CERT_STATUS_UNABLE_TO_CHECK_REVOCATION, "Unable to Check Revocation" }, { CERT_STATUS_REVOKED, "Revoked" }, { CERT_STATUS_INVALID, "Invalid" }, { CERT_STATUS_WEAK_SIGNATURE_ALGORITHM, "Weak Signature Algorithm" }, { CERT_STATUS_NON_UNIQUE_NAME, "Non-Unique Name" }, { CERT_STATUS_WEAK_KEY, "Weak Key" }, { CERT_STATUS_PINNED_KEY_MISSING, "Pinned Key Missing" }, { CERT_STATUS_NAME_CONSTRAINT_VIOLATION, "Name Constraint Violation" }, { CERT_STATUS_VALIDITY_TOO_LONG, "Validity Too Long" }, { CERT_STATUS_IS_EV, "Extended Validation Certificate" }, { CERT_STATUS_REV_CHECKING_ENABLED, "Revocation Checking Enabled" }, { CERT_STATUS_SHA1_SIGNATURE_PRESENT, "SHA1 Signature Present" }, { CERT_STATUS_CT_COMPLIANCE_FAILED, "CT Compliance Failed" } }; QStringList ret; for (auto key : strings.keys()) { if (status & key) ret << strings[key]; } return ret; } QString SslInfoAction::CertSslVersion(cef_ssl_version_t ssl_version) { switch (ssl_version) { case SSL_CONNECTION_VERSION_SSL2: return "SSL 2.0"; case SSL_CONNECTION_VERSION_SSL3: return "SSL 3.0"; case SSL_CONNECTION_VERSION_TLS1: return "TLS 1.0"; case SSL_CONNECTION_VERSION_TLS1_1: return "TLS 1.1"; case SSL_CONNECTION_VERSION_TLS1_2: return "TLS 1.2"; case SSL_CONNECTION_VERSION_QUIC: return "QUIC"; default: return "(unknown)"; } } } // namespace doogie
37.699029
77
0.722637
1967fc2cfe2e1f1dc101872396eb1497aa847e97
501
hpp
C++
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
#ifndef COMPARETORFACTORY_HPP #define COMPARETORFACTORY_HPP #include "comparetor.hpp" #include "QPointer" /** * @brief The deckType enum,定义了各种牌型的枚举 */ enum deckType{undefined,high_card,one_pair,two_pairs,three_of_a_kind,straight,flush,full_house,four_of_a_kind,straight_flush,royal_flush}; /** * @brief The comparetorFactory class,比较器的工厂类,返回需要的比较器 */ class comparetorFactory { public: static QSharedPointer<comparetor> getComparetor(const deckType type); }; #endif // COMPARETORFACTORY_HPP
23.857143
138
0.802395
196de25f738ff244d1313b7e80e870f003bcbaa7
2,804
cpp
C++
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UWorkerTooltipStatsWidget_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Construct"); UWorkerTooltipStatsWidget_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Tick // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // float* InDeltaTime (Parm, ZeroConstructor, IsPlainOldData) void UWorkerTooltipStatsWidget_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime) { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Tick"); UWorkerTooltipStatsWidget_C_Tick_Params params; params.MyGeometry = MyGeometry; params.InDeltaTime = InDeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.On Worker Preview State Changed // (BlueprintCallable, BlueprintEvent) void UWorkerTooltipStatsWidget_C::On_Worker_Preview_State_Changed() { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.On Worker Preview State Changed"); UWorkerTooltipStatsWidget_C_On_Worker_Preview_State_Changed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.ExecuteUbergraph_WorkerTooltipStatsWidget // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UWorkerTooltipStatsWidget_C::ExecuteUbergraph_WorkerTooltipStatsWidget(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.ExecuteUbergraph_WorkerTooltipStatsWidget"); UWorkerTooltipStatsWidget_C_ExecuteUbergraph_WorkerTooltipStatsWidget_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
29.208333
155
0.731455
196edfd0541a5114a81b67144dfa7bcf5ddb8c42
1,220
cpp
C++
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
136
2015-07-15T12:49:36.000Z
2022-03-24T12:30:25.000Z
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
59
2015-12-28T21:40:37.000Z
2022-03-31T13:11:50.000Z
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
33
2015-12-04T08:00:07.000Z
2022-01-28T23:39:25.000Z
#include <boost/python.hpp> #include <boost/cstdint.hpp> #include <Magick++/Drawable.h> #include <Magick++.h> using namespace boost::python; namespace { struct Magick_DrawableMatte_Wrapper: Magick::DrawableMatte { Magick_DrawableMatte_Wrapper(PyObject* py_self_, double p0, double p1, Magick::PaintMethod p2): Magick::DrawableMatte(p0, p1, p2), py_self(py_self_) {} PyObject* py_self; }; } void __DrawableMatte() { class_< Magick::DrawableMatte, bases<Magick::DrawableBase>, boost::noncopyable, Magick_DrawableMatte_Wrapper >("DrawableMatte", init< double, double, Magick::PaintMethod >()) .def("x", (void (Magick::DrawableMatte::*)(double) )&Magick::DrawableMatte::x) .def("x", (double (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::x) .def("y", (void (Magick::DrawableMatte::*)(double) )&Magick::DrawableMatte::y) .def("y", (double (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::y) .def("paintMethod", (void (Magick::DrawableMatte::*)(Magick::PaintMethod) )&Magick::DrawableMatte::paintMethod) .def("paintMethod", (Magick::PaintMethod (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::paintMethod) ; }
34.857143
178
0.688525
196f7e48086742ca2f3d80e64272b0f92a8f4057
4,298
cpp
C++
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
2
2021-04-19T11:42:07.000Z
2021-04-21T10:26:04.000Z
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2021 Jihoon Lee <jhoon.it.lee@samsung.com> * * @file unittest_interpreter.cpp * @date 02 April 2021 * @brief interpreter test * @see https://github.com/nnstreamer/nntrainer * @author Jihoon Lee <jhoon.it.lee@samsung.com> * @bug No known bugs except for NYI items */ #include <functional> #include <gtest/gtest.h> #include <memory> #include <app_context.h> #include <ini_interpreter.h> #include <interpreter.h> #include <layer.h> #include <nntrainer_test_util.h> using LayerReprentation = std::pair<std::string, std::vector<std::string>>; auto &ac = nntrainer::AppContext::Global(); static std::shared_ptr<nntrainer::GraphRepresentation> makeGraph(const std::vector<LayerReprentation> &layer_reps) { auto graph = std::make_shared<nntrainer::GraphRepresentation>(); for (const auto &layer_representation : layer_reps) { std::shared_ptr<ml::train::Layer> layer = ac.createObject<ml::train::Layer>( layer_representation.first, layer_representation.second); graph->addLayer(std::static_pointer_cast<nntrainer::Layer>(layer)); } return graph; } const std::string pathResolver(const std::string &path) { return getResPath(path, {"test", "test_models", "models"}); } auto ini_interpreter = std::make_shared<nntrainer::IniGraphInterpreter>(ac, pathResolver); /** * @brief nntrainer Interpreter Test setup * * @note Proposing an evolutional path of current test * 1. A reference graph vs given paramter * 2. A reference graph vs list of models * 3. A reference graph vs (pick two models) a -> b -> a graph, b -> a -> b * graph */ class nntrainerInterpreterTest : public ::testing::TestWithParam< std::tuple<std::shared_ptr<nntrainer::GraphRepresentation>, const char *, std::shared_ptr<nntrainer::GraphInterpreter>>> { protected: virtual void SetUp() { auto params = GetParam(); reference = std::get<0>(params); file_path = pathResolver(std::get<1>(params)); interpreter = std::move(std::get<2>(params)); } std::shared_ptr<nntrainer::GraphRepresentation> reference; std::shared_ptr<nntrainer::GraphInterpreter> interpreter; std::string file_path; }; /** * @brief Check two compiled graph is equal * @note later this will be more complicated (getting N graph and compare each * other) * */ TEST_P(nntrainerInterpreterTest, graphEqual) { std::cerr << "testing " << file_path << '\n'; int status = reference->compile(nntrainer::LossType::LOSS_NONE); EXPECT_EQ(status, ML_ERROR_NONE); auto g = interpreter->deserialize(file_path); /// @todo: change this to something like graph::finalize status = g->compile(nntrainer::LossType::LOSS_NONE); EXPECT_EQ(status, ML_ERROR_NONE); /// @todo: make a graph equal /// 1. having same number of nodes /// 2. layer name is identical (this is too strict though) /// 3. attributes of layer is identical // EXPECT_EQ(*graph, *interpreter->deserialize(file_path)); auto layers = g->getLayers(); auto ref_layers = reference->getLayers(); EXPECT_EQ(layers.size(), ref_layers.size()); if (layers.size() == ref_layers.size()) { for (auto &layer : layers) { std::shared_ptr<nntrainer::Layer> ref_layer; EXPECT_NO_THROW(ref_layer = reference->getLayer(layer->getName())); /// @todo: layer->getProperties() and do check on each properties } } } auto fc0 = LayerReprentation("fully_connected", {"name=fc0", "unit=1", "input_shape=1:1:100"}); auto flatten = LayerReprentation("flatten", {"name=flat"}); /** * @brief make ini test case from given parameter */ static std::tuple<std::shared_ptr<nntrainer::GraphRepresentation>, const char *, std::shared_ptr<nntrainer::GraphInterpreter>> mkTc(std::shared_ptr<nntrainer::GraphRepresentation> graph, const char *file, std::shared_ptr<nntrainer::GraphInterpreter> interpreter) { return std::make_tuple(graph, file, interpreter); } // clang-format off INSTANTIATE_TEST_CASE_P(nntrainerAutoInterpreterTest, nntrainerInterpreterTest, ::testing::Values( mkTc(makeGraph({fc0, flatten}), "simple_fc.ini", ini_interpreter), mkTc(makeGraph({fc0, flatten}), "simple_fc_backbone.ini", ini_interpreter) )); // clang-format on
31.837037
80
0.701489
197055abf1559514dd02c0f191b0e2957efbd748
2,495
cpp
C++
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
// // Renderer.cpp // // // Created by Narendra Umate on 9/7/13. // // #include "Renderer.h" Renderer::Renderer(const int& width, const int& height) : m_width(width) , m_height(height) , m_clearColor(Color4f(0.5f, 0.5f, 0.5f, 1.0f)) , m_clearDepth(1.0f) , m_clearStencil(1) { } Renderer::~Renderer() { m_width = 0; m_height = 0; } void Renderer::setNdcMatrix(const Mat4& matrix) { m_ndcMatrix = matrix; } Mat4 Renderer::getNdcMatrix() { return m_ndcMatrix; } void Renderer::setProjectionRange(const ProjectionRange& range) { m_projectionRange = range; } ProjectionRange Renderer::getProjectionRange() { return m_projectionRange; } void Renderer::setWidth(const int& width) { m_width = width; } int Renderer::getWidth() { return m_width; } void Renderer::setHeight(const int& height) { m_height = height; } int Renderer::getHeight() { return m_height; } void Renderer::draw(Bvh* bvh, VisualEffect* visualEffect, VisualMaterial* visualMaterial, const Mat4& worldMatrix, const Mat4& viewMatrix, const Mat4& viewProjectionMatrix, const Vec3& lightCoefficients, const Vec3& lightColor, const Vec3& lightPosition, const Vec3& eyePosition) { // Draw your self. draw(bvh->getBoundingBox(), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); // Draw your children. int childCount = bvh->getChildCount(); if (childCount) { for (int childIndex = 0; childIndex < childCount; ++childIndex) { draw(bvh->getChild(childIndex), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); } } } void Renderer::draw(Octree* octree, VisualEffect* visualEffect, VisualMaterial* visualMaterial, const Mat4& worldMatrix, const Mat4& viewMatrix, const Mat4& viewProjectionMatrix, const Vec3& lightCoefficients, const Vec3& lightColor, const Vec3& lightPosition, const Vec3& eyePosition) { // Draw your self. draw(octree->getBoundingBox(), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); // Draw your children. int childCount = octree->getChildCount(); if (childCount) { for (int childIndex = 0; childIndex < childCount; ++childIndex) { draw(octree->getChild(childIndex), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); } } }
30.802469
287
0.755511
19739d11d88c922729740fe17fd0519600b431f7
2,759
cpp
C++
src/mupnp/soap/SOAP.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
src/mupnp/soap/SOAP.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
src/mupnp/soap/SOAP.cpp
cybergarage/CyberLink4CC
ccbda234b920ec88a36392102c1d5247c074a734
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************** * * mUPnP for C++ * * Copyright (C) Satoshi Konno 2002 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <string> #include <sstream> #include <string.h> #include <mupnp/soap/SOAP.h> #include <uhttp/util/StringUtil.h> //////////////////////////////////////////////// // CreateEnvelopeBodyNode //////////////////////////////////////////////// mupnp_shared_ptr<uXML::Node> uSOAP::SOAP::CreateEnvelopeBodyNode() { // <Envelope> std::string envNodeName; envNodeName += XMLNS; envNodeName += DELIM; envNodeName += ENVELOPE; uXML::Node *envNode = new uXML::Node(envNodeName.c_str()); std::string xmlNs; xmlNs += "xmlns"; xmlNs += DELIM; xmlNs += XMLNS; envNode->setAttribute(xmlNs.c_str(), XMLNS_URL); std::string encStyle; encStyle += XMLNS; encStyle += DELIM; encStyle += "encodingStyle"; envNode->setAttribute(encStyle.c_str(), ENCSTYLE_URL); // <Body> std::string bodyNodeName; bodyNodeName += XMLNS; bodyNodeName += DELIM; bodyNodeName += BODY; uXML::Node *bodyNode = new uXML::Node(bodyNodeName.c_str()); envNode->addNode(bodyNode); return mupnp_shared_ptr<uXML::Node>(envNode); } //////////////////////////////////////////////// // Header //////////////////////////////////////////////// const char *uSOAP::SOAP::GetHeader(const std::string &content, std::string &header) { header = ""; if (content.length() <= 0) return header.c_str(); std::string::size_type gtIdx = content.find(">"); if (gtIdx == std::string::npos) return header.c_str(); header = content.substr(0, gtIdx+1); return header.c_str(); } //////////////////////////////////////////////// // Encoding //////////////////////////////////////////////// const char *uSOAP::SOAP::GetEncording(const std::string &content, std::string &encording) { encording = ""; std::string header; SOAP::GetHeader(content, header); if (header.size() <= 0) return encording.c_str(); std::string::size_type encIdx = header.find(uSOAP::SOAP::ENCORDING); if (encIdx == std::string::npos) return encording.c_str(); std::string::size_type startIdx = header.find('\"', encIdx+strlen(uSOAP::SOAP::ENCORDING)+1); if (startIdx == std::string::npos) return encording.c_str(); std::string::size_type endIdx = header.find('\"', startIdx+1); encording = header.substr(startIdx+1, (endIdx-startIdx-1)); return encording.c_str(); } bool uSOAP::SOAP::IsEncording(const std::string &content, const std::string &encType) { std::string enc; SOAP::GetEncording(content, enc); uHTTP::String encStr(enc); return encStr.equalsIgnoreCase(encType); }
29.666667
95
0.576296
1973bcacdaee75bfcb4d0c30016fb6726d29e884
4,990
cpp
C++
_midynet/tests/test_randomgraph/test_erdosrenyi.cpp
charlesmurphy1/fast-midynet
22071d49077fce9d5f99a4664f36767b27edea64
[ "MIT" ]
null
null
null
_midynet/tests/test_randomgraph/test_erdosrenyi.cpp
charlesmurphy1/fast-midynet
22071d49077fce9d5f99a4664f36767b27edea64
[ "MIT" ]
null
null
null
_midynet/tests/test_randomgraph/test_erdosrenyi.cpp
charlesmurphy1/fast-midynet
22071d49077fce9d5f99a4664f36767b27edea64
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include <list> #include <algorithm> #include <string> #include "FastMIDyNet/prior/sbm/edge_count.h" #include "FastMIDyNet/random_graph/erdosrenyi.h" #include "FastMIDyNet/types.h" #include "FastMIDyNet/utility/functions.h" #include "BaseGraph/types.h" #include "fixtures.hpp" using namespace std; using namespace FastMIDyNet; static const int NUM_EDGES = 50; static const int NUM_VERTICES = 50; class TestErdosRenyiFamily: public::testing::Test{ public: EdgeCountPoissonPrior edgeCountPrior = {NUM_EDGES}; ErdosRenyiFamily randomGraph = ErdosRenyiFamily(NUM_VERTICES, edgeCountPrior); void SetUp() { randomGraph.sample(); } }; TEST_F(TestErdosRenyiFamily, randomGraph_hasCorrectBlockSequence){ auto blocks = randomGraph.getBlocks(); for (auto b : blocks) EXPECT_EQ(b, 0); } TEST_F(TestErdosRenyiFamily, sample_getGraphWithCorrectNumberOfEdges){ randomGraph.sample(); EXPECT_EQ(randomGraph.getGraph().getTotalEdgeNumber(), randomGraph.getEdgeCount()); } TEST_F(TestErdosRenyiFamily, getLogLikelihoodRatioFromBlockMove_returnMinusInfinity){ BlockMove move = {0, 0, 1, 1}; double dS = randomGraph.getLogPriorRatioFromBlockMove(move); EXPECT_EQ(dS, -INFINITY); } TEST_F(TestErdosRenyiFamily, applyBlockMove_throwConsistencyError){ #if DEBUG BlockMove move = {0, 0, 1, 1}; EXPECT_THROW(randomGraph.applyBlockMove(move), ConsistencyError); #endif } TEST_F(TestErdosRenyiFamily, isCompatible_forGraphSampledFromSBM_returnTrue){ randomGraph.sample(); auto g = randomGraph.getGraph(); EXPECT_TRUE(randomGraph.isCompatible(g)); } TEST_F(TestErdosRenyiFamily, isCompatible_forEmptyGraph_returnFalse){ MultiGraph g(0); EXPECT_FALSE(randomGraph.isCompatible(g)); } TEST_F(TestErdosRenyiFamily, isCompatible_forGraphWithOneEdgeMissing_returnFalse){ randomGraph.sample(); auto g = randomGraph.getGraph(); for (auto vertex: g){ for (auto neighbor: g.getNeighboursOfIdx(vertex)){ g.removeEdgeIdx(vertex, neighbor.vertexIndex); break; } } EXPECT_FALSE(randomGraph.isCompatible(g)); } class TestSimpleErdosRenyiFamily: public::testing::Test{ public: EdgeCountDeltaPrior edgeCountPrior = {NUM_EDGES}; SimpleErdosRenyiFamily randomGraph = SimpleErdosRenyiFamily(NUM_VERTICES, edgeCountPrior); void SetUp() { randomGraph.samplePriors(); randomGraph.sample(); } }; TEST_F(TestSimpleErdosRenyiFamily, randomGraph_hasCorrectBlockSequence){ auto blocks = randomGraph.getBlocks(); for (auto b : blocks) EXPECT_EQ(b, 0); } TEST_F(TestSimpleErdosRenyiFamily, sample_getGraphWithCorrectNumberOfEdges){ randomGraph.sample(); EXPECT_EQ(randomGraph.getGraph().getTotalEdgeNumber(), randomGraph.getEdgeCount()); } TEST_F(TestSimpleErdosRenyiFamily, getLogLikelihoodRatioFromGraphMove_forAddedEdge_returnCorrectLogLikelihoodRatio){ auto graph = randomGraph.getGraph(); GraphMove move = {}; for (auto vertex: graph){ if (graph.getEdgeMultiplicityIdx(0, vertex) == 0) { move.addedEdges.push_back({0, vertex}); break; } } double actualLogLikelihoodRatio = randomGraph.getLogLikelihoodRatioFromGraphMove(move); double logLikelihoodBefore = randomGraph.getLogLikelihood(); randomGraph.applyGraphMove(move); double logLikelihoodAfter = randomGraph.getLogLikelihood(); EXPECT_NEAR(actualLogLikelihoodRatio, logLikelihoodAfter - logLikelihoodBefore, 1E-6); } TEST_F(TestSimpleErdosRenyiFamily, getLogLikelihoodRatioFromGraphMove_forRemovedEdge_returnCorrectLogLikelihoodRatio){ auto graph = randomGraph.getGraph(); GraphMove move = {}; for (auto neighbor: graph.getNeighboursOfIdx(0)){ move.removedEdges.push_back({0, neighbor.vertexIndex}); break; } double actualLogLikelihoodRatio = randomGraph.getLogLikelihoodRatioFromGraphMove(move); double logLikelihoodBefore = randomGraph.getLogLikelihood(); randomGraph.applyGraphMove(move); double logLikelihoodAfter = randomGraph.getLogLikelihood(); EXPECT_NEAR(actualLogLikelihoodRatio, logLikelihoodAfter - logLikelihoodBefore, 1E-6); } TEST_F(TestSimpleErdosRenyiFamily, isCompatible_forGraphSampledFromSBM_returnTrue){ randomGraph.sample(); auto g = randomGraph.getGraph(); EXPECT_TRUE(randomGraph.isCompatible(g)); } TEST_F(TestSimpleErdosRenyiFamily, isCompatible_forEmptyGraph_returnFalse){ MultiGraph g(0); EXPECT_FALSE(randomGraph.isCompatible(g)); } TEST_F(TestSimpleErdosRenyiFamily, isCompatible_forGraphWithOneEdgeMissing_returnFalse){ randomGraph.sample(); auto g = randomGraph.getGraph(); for (auto vertex: g){ for (auto neighbor: g.getNeighboursOfIdx(vertex)){ g.removeEdgeIdx(vertex, neighbor.vertexIndex); break; } } EXPECT_FALSE(randomGraph.isCompatible(g)); }
32.402597
118
0.742285
1973c4eb8fbedd8255e7445a74b3b77d35326f97
411
cpp
C++
inv_pend_walk/test/check_foot_step_planner.cpp
AD58-3104/bipedal_training
f7bca20e12f65ed4be2a9ba93198286682642fca
[ "MIT" ]
null
null
null
inv_pend_walk/test/check_foot_step_planner.cpp
AD58-3104/bipedal_training
f7bca20e12f65ed4be2a9ba93198286682642fca
[ "MIT" ]
null
null
null
inv_pend_walk/test/check_foot_step_planner.cpp
AD58-3104/bipedal_training
f7bca20e12f65ed4be2a9ba93198286682642fca
[ "MIT" ]
null
null
null
#include "foot_step_planner.hpp" #include <iostream> #include <fstream> #include <vector> #include <cmath> #include <Eigen/Dense> #include <Eigen/Geometry> using namespace Eigen; int main(int argc, char const *argv[]) { footStepPlanner(2.0,2.0,0.30); planAlongSpline(); system("sleep 0.1"); system("gnuplot-x11 -persist show.plt"); system("gnuplot-x11 -persist spline.plt"); return 0; }
22.833333
46
0.688564
197bac971e6f7d5e47fce66bdb276fe36a3542d7
930
cpp
C++
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
1
2016-01-09T09:57:55.000Z
2016-01-09T09:57:55.000Z
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
null
null
null
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
null
null
null
#include "gtfo/algorithm/count_if.hpp" #include "gtfo_testing/runtime/runtime_tests.hpp" using namespace gtfo::runtime_test_helpers; namespace { struct Foo { int x; Foo() : x(42) { } explicit Foo(int x) : x(x) { } }; class Bool { private: bool _value; public: explicit Bool(bool value) : _value(value) { } operator bool() const { return _value; } }; class Pred { private: int _x; public: explicit Pred(int x) : _x(x) { } Bool operator()(const Foo & foo) const { return Bool(foo.x == _x); } }; } using gtfo::count_if; GTFO_TEST_FUN_BEGIN Foo arr[10]; arr[3].x = 10; arr[5].x = 10; arr[8].x = 10; // two iterators + value GTFO_TEST_ASSERT_EQ(count_if(arr, arr + 10, Pred(42)), 7) // range + value GTFO_TEST_ASSERT_EQ(count_if(rev(arr), Pred(10)), 3) GTFO_TEST_FUN_END
19.375
76
0.569892
197cc9254e92cdc7eba34a5f8fddbec0df721dc9
32,594
cxx
C++
private/inet/mshtml/src/site/print/headfoot.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/mshtml/src/site/print/headfoot.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/mshtml/src/site/print/headfoot.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
//+--------------------------------------------------------------------------- // // Microsoft Forms // Copyright (C) Microsoft Corporation, 1992 - 1996. // // File: headfoot.cxx // // Contents: CHeaderFooterInfo // //---------------------------------------------------------------------------- #include "headers.hxx" #ifndef X_HEADFOOT_HXX_ #define X_HEADFOOT_HXX_ #include "headfoot.hxx" #endif #ifndef X_FPRINT_HXX_ #define X_FPRINT_HXX_ #include "fprint.hxx" #endif #ifndef X_HEDELEMS_HXX_ #define X_HEDELEMS_HXX_ #include "hedelems.hxx" #endif #ifndef X__FONTLNK_H_ #define X__FONTLNK_H_ #include "_fontlnk.h" #endif MtDefine(CHeaderFooterInfo, Printing, "CHeaderFooterInfo") MtDefine(CHeaderFooterInfo_aryParts_pv, CHeaderFooterInfo, "CHeaderFooterInfo::_aryParts::_pv") MtDefine(CHeaderFooterInfo_pURL, CHeaderFooterInfo, "CHeaderFooterInfo::_pURL") MtDefine(CHeaderFooterInfo_pHeaderFooter, CHeaderFooterInfo, "CHeaderFooterInfo::_pHeaderFooter") MtDefine(CHeaderFooterInfo_pTitle, CHeaderFooterInfo, "CHeaderFooterInfo::_pTitle") MtDefine(CHeaderFooterInfoConvertNum_ppChars, Printing, "CHeaderFooterInfo::ConvertNum *ppChars") MtDefine(CDescr, Printing, "CDescr") MtDefine(CDescr_pPart, Printing, "CDescr::_pPart") #define NUMNOTSET -1 enum PartKindType { pkText,pkPageNum,pkMultipleBlank }; //--------------------------------------------------------------------------- // // Class: CDescr // // Synopsis: Describes one element in the Header or Footer // One element can be a text string or a Page number or MultipleBlank // if it is not a textstring then pPart is NULL. // // //--------------------------------------------------------------------------- class CDescr { public: DECLARE_MEMALLOC_NEW_DELETE(Mt(CDescr)) CDescr(void); ~CDescr(); TCHAR* pPart; PartKindType PartKind; int xPos; int iPixelLen; }; //--------------------------------------------------------------------------- // // Member: CDescr::CDescr // // Synopsis: Constructor of CDescr // // Arguments: None // //--------------------------------------------------------------------------- CDescr::CDescr(void) { pPart = NULL; }; //--------------------------------------------------------------------------- // // Member: CDescr::~CDescr // // Synopsis: Destructor of CDescr // Deletes allocated string containing part of Header or Footer // // Arguments: None // //--------------------------------------------------------------------------- CDescr::~CDescr() { // because we do not store the whole text, only the pointer if it is // a pagenumber, therefore we should not delete it if (PartKind != pkPageNum) delete [] pPart; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::CHeaderFooterInfo // // Synopsis: Constructor of CHeaderFooterInfo // Initializes the pointers of the original (user typed) header of footer, // the title and the URL address. // Moves NUMNOTSET value into number members. // // Arguments: None // //--------------------------------------------------------------------------- CHeaderFooterInfo::CHeaderFooterInfo(CPrintDoc* pPrintDoc) : _aryParts(Mt(CHeaderFooterInfo_aryParts_pv)) { Assert(pPrintDoc); _pHeaderFooter = NULL; _iLastPageNum = NUMNOTSET; _iTotalPages = NUMNOTSET; _pTitle = NULL; _iNrOfMultipleBlanks = 0; _bParsed = FALSE; _pURL = NULL; _tcscpy(_PageNumChars,_T("")); if (pPrintDoc->_pPrimaryMarkup->GetTitleElement()) { SetTitle(&(pPrintDoc->_pPrimaryMarkup->GetTitleElement()->_cstrTitle)); } _pPrintDoc = pPrintDoc; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::~CHeaderFooterInfo // // Synopsis: Destructor of CHeaderFooterInfo // Deletes the original (user typed) header of footer, // the parsed and assembled string, the title and the URL address. // Deletes the array containing parts of the header or footer. // // Arguments: None // //--------------------------------------------------------------------------- CHeaderFooterInfo::~CHeaderFooterInfo() { delete [] _pHeaderFooter; delete [] _pTitle; delete [] _pURL; DeleteArray(); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::DeleteArray // // Synopsis: Deletes the array containing parts of the header or footer // // Arguments: None // //--------------------------------------------------------------------------- void CHeaderFooterInfo::DeleteArray(void) { CDescr* pDescr; for (int i=0;i<_aryParts.Size();i++) { pDescr = _aryParts[i]; delete pDescr; }; _aryParts.DeleteAll(); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::SetHeaderFooterURL // // Synopsis: Set the URL address of the Document // // Arguments: pURL address of URL string // //--------------------------------------------------------------------------- void CHeaderFooterInfo::SetHeaderFooterURL(TCHAR* pURL) { delete _pURL; _pURL = NULL; if (!pURL) return; int iLen = _tcslen(pURL); if (iLen < 1) return; _pURL = new(Mt(CHeaderFooterInfo_pURL)) TCHAR[iLen+1]; Assert(_pURL); if (!_pURL) return; _tcscpy(_pURL,pURL); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::ConvertNum // // Synopsis: Converts a number to a string. Allocates string.If number is not set // gives back an empty string. // // Arguments: iNum integer number to be converted into string // ppChars string the number will be converted into (max 8 chars) // //--------------------------------------------------------------------------- void CHeaderFooterInfo::ConvertNum(int iNum,TCHAR** ppChars) { *ppChars = new(Mt(CHeaderFooterInfoConvertNum_ppChars)) TCHAR[8]; if (*ppChars) { if (iNum == NUMNOTSET) { _tcscpy(*ppChars,_T("")); } else { _itot(iNum,*ppChars,10); }; }; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::ConvertPageNum // // Synopsis: Convert the last page number by calling ConvertNum // // Arguments: ppNumChars string the page number will be converted into (max 8 chars) // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::ConvertPageNum(void) { _itot(_iLastPageNum,(TCHAR*)&_PageNumChars,10); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTextDescr // // Synopsis: Allocates a new CDescr object, allocates memory inside the object to store // the new Text and sets the PartKind member to pkText // Append the new CDescr object to _aryParts collection. // // Arguments: pText text to be stored in a CDescr object // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddTextDescr(TCHAR* pText) { if (!pText) return; if (_tcslen(pText) < 1) return; CDescr* pDescr; pDescr = new CDescr; Assert(pDescr); if (!pDescr) return; pDescr->pPart = new(Mt(CDescr_pPart)) TCHAR[_tcslen(pText)+1]; Assert(pDescr->pPart); if (!pDescr->pPart) { delete pDescr; return; }; _tcscpy(pDescr->pPart,pText); pDescr->PartKind = pkText; _aryParts.Append(pDescr); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTotalPages // // Synopsis: Converts the total pages into a string and add the new string into // _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddTotalPages(void) { TCHAR* pTotalPagesChars; ConvertNum(_iTotalPages,&pTotalPagesChars); AddTextDescr(pTotalPagesChars); delete pTotalPagesChars; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTime // // Synopsis: Converts the current time into a string and adds // it to the _aryParts collection. // // Arguments: dFlag 0 or TIME_FORCE24HOURFORMAT // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddTime(DWORD dFlag) { TCHAR TimeStr[DATE_STR_LENGTH]; SYSTEMTIME currentSysTime; GetLocalTime(&currentSysTime); #ifndef WIN16 if (GetTimeFormat(LOCALE_USER_DEFAULT,dFlag,&currentSysTime,NULL, (TCHAR*)&TimeStr,DATE_STR_LENGTH)) { AddTextDescr((TCHAR*)&TimeStr); }; #else // BUGWIN16 mblain--we currently always use the US C format for time! int cchResult; struct tm *LocalTm; LocalTm = localtime(&currentSysTime); if (TIME_FORCE24HOURFORMAT == dFlag) { cchResult = wsprintf(TimeStr, "%2d:%2d:%2d", LocalTm->tm_hour, LocalTm->tm_min, LocalTm->tm_sec ); } else { cchResult = wsprintf(TimeStr, "%2d:%2d:%2d %s", LocalTm->tm_hour % 12, LocalTm->tm_min, LocalTm->tm_sec, LocalTm->tm_hour < 12 ? "AM" : "PM" ); } Assert(cchResult <= DATE_STR_LENGTH); AddTextDescr((TCHAR*)&TimeStr); #endif // ndef WIN16 else }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddShortTime // // Synopsis: Converts the current time (short format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddShortTime(void) { AddTime(0); // zero means no 24 hour format }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddLongTime // // Synopsis: Converts the current time (long format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddLongTime(void) { AddTime(TIME_FORCE24HOURFORMAT); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddShortDate // // Synopsis: Converts the current date into a string and adds // it to the _aryParts collection. // // // Arguments: dFlag DATE_SHORTDATE or DATE_LONGDATE // //--------------------------------------------------------------------------- void CHeaderFooterInfo::AddDate(DWORD dFlag) { TCHAR DateStr[DATE_STR_LENGTH]; SYSTEMTIME currentSysTime; GetLocalTime(&currentSysTime); #ifndef WIN16 if (GetDateFormat(LOCALE_USER_DEFAULT,dFlag,&currentSysTime,NULL, (TCHAR*)&DateStr,DATE_STR_LENGTH)) { AddTextDescr((TCHAR*)&DateStr); }; #else // BUGWIN16 mblain--we currently always use the US C format for date! // we also always use 'short' format -- 18feb97 int cchResult; struct tm *LocalTm; LocalTm = localtime(&currentSysTime); //if (DATE_SHORTDATE == dFlag) { cchResult = wsprintf(DateStr, "%2d/%2d/%2d", LocalTm->tm_mon +1, LocalTm->tm_mday, LocalTm->tm_year % 100 ); } // else // do long format. Assert(cchResult <= DATE_STR_LENGTH); AddTextDescr((TCHAR*)&DateStr); #endif // ndef WIN16 else }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddShortDate // // Synopsis: Converts the current date (short format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddShortDate(void) { AddDate(DATE_SHORTDATE); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddLongDate // // Synopsis: Converts the current date (long format) into a string and adds // it to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddLongDate(void) { AddDate(DATE_LONGDATE); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddTitle // // Synopsis: Add the title from CDoc to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddTitle(void) { AddTextDescr(_pTitle); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::AddURL // // Synopsis: Add the URL address from CDoc to the _aryParts collection. // // Arguments: None // //--------------------------------------------------------------------------- inline void CHeaderFooterInfo::AddURL(void) { AddTextDescr(_pURL); }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::ParseIt // // Synopsis: Parses the user typed _pHeaderFooter string and builds up // _aryParts collection. // // Special characters : // &p page number // &P total pages // &b multiple blank // &t time, short format // &T time, 24 hour format // &d date, short format // &D date, long format // &w title // &u URL address // // Arguments: None // //--------------------------------------------------------------------------- void CHeaderFooterInfo::ParseIt(void) { Assert(_pHeaderFooter); if (!_pHeaderFooter) return; if (_bParsed) return; DeleteArray(); int iLen = _tcslen(_pHeaderFooter); if (iLen > 0) { TCHAR* pO = _pHeaderFooter; TCHAR* pP = NULL; TCHAR SaveChar; _iNrOfMultipleBlanks = 0; while (*pO) { pP = _tcschr(pO,_T('&')); if (!pP) { AddTextDescr(pO); return; }; *pP = '\0'; AddTextDescr(pO); *pP = _T('&'); pP++; #ifdef UNIX pO = pP - 1; if (_tcslen(pP) < 1) { AddTextDescr(pO); return; } #endif pO = pP; pO++; switch(*pP) { case _T('b') : case _T('p') : CDescr* pDescr; pDescr = new CDescr; Assert(pDescr); if (pDescr) { pDescr->pPart = NULL; if (*pP == _T('p')) { pDescr->PartKind = pkPageNum; } else { pDescr->PartKind = pkMultipleBlank; _iNrOfMultipleBlanks++; }; _aryParts.Append(pDescr); }; break; case _T('P') : AddTotalPages(); break; case _T('d') : AddShortDate(); break; case _T('D') : AddLongDate(); break; case _T('t') : AddShortTime(); break; case _T('T') : AddLongTime(); break; case _T('w') : AddTitle(); break; case _T('u') : AddURL(); break; default : SaveChar = *pO; *pO = '\0'; AddTextDescr(pP); *pO = SaveChar; break; }; }; }; _bParsed = TRUE; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::SetHeaderFooter // // Synopsis: Stores the used typed Header or Footer and starts the parsing process // // Arguments: pHeaderFooter user typed string // //--------------------------------------------------------------------------- HRESULT CHeaderFooterInfo::SetHeaderFooter(TCHAR* pHeaderFooter) { delete [] _pHeaderFooter; _pHeaderFooter = NULL; if (!pHeaderFooter) { _pHeaderFooter = new(Mt(CHeaderFooterInfo_pHeaderFooter)) TCHAR[1]; if (_pHeaderFooter) _tcscpy(_pHeaderFooter,_T("")); } else { int iLen = _tcslen(pHeaderFooter); _pHeaderFooter = new(Mt(CHeaderFooterInfo_pHeaderFooter)) TCHAR[iLen+1]; Assert(_pHeaderFooter); if (_pHeaderFooter) _tcscpy(_pHeaderFooter,pHeaderFooter); }; return S_OK; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::SetTitle // // Synopsis: Stores the document title into the _aryParts collection // // Arguments: pTitle document title // //--------------------------------------------------------------------------- void CHeaderFooterInfo::SetTitle(CStr* pTitle) { LPTSTR pStr; if (!pTitle) return; pStr = LPTSTR(*pTitle); delete [] _pTitle; _pTitle = NULL; int iLen = pTitle->Length(); if (iLen > 0) { _pTitle = new(Mt(CHeaderFooterInfo_pTitle)) TCHAR[iLen + 1]; Assert(_pTitle); if (_pTitle) _tcscpy(_pTitle,pStr); }; }; //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::CalcXPos // // Synopsis: Goes through the parts collection (_aryParts) and calculates the // x position of them // // Arguments: pDI CDrawInfo // hFont font handle // //--------------------------------------------------------------------------- void CHeaderFooterInfo::CalcXPos(CDrawInfo* pDI) { int iPixelLen = 0; // length of header or footer in pixels int iPixelFree; // remaining pixels after calculating iPixelLen int iPixelMultipleBlank = 0; // pixels for 1 multiple blank SIZE size; int xPos; ConvertPageNum(); int iPageNumLen = _tcslen((TCHAR*)&_PageNumChars); // length of page number in chars int iPixelPageNum = 0; // length of page number in pixels int i; CDescr* pDescr; GetTextExtentPoint32(pDI->_hdc,(TCHAR*)&_PageNumChars,iPageNumLen,&size); iPixelPageNum = size.cx; // we do it only once // calculate the length of parts in pixels for (i=0;i<_aryParts.Size();i++) { pDescr = _aryParts[i]; if (pDescr->PartKind == pkText) { GetTextExtentPoint32(pDI->_hdc,pDescr->pPart,_tcslen(pDescr->pPart),&size); pDescr->iPixelLen = size.cx; iPixelLen += size.cx; } else { if (pDescr->PartKind == pkPageNum) { pDescr->pPart = (TCHAR*)&_PageNumChars; pDescr->iPixelLen = iPixelPageNum; iPixelLen += iPixelPageNum; }; } } int iTabStopPos; int iMultipleBlankCounter = 0; // calculate complete width of page iPixelFree = _pPrintDoc->_rcClip.right - _pPrintDoc->_rcClip.left; xPos = iTabStopPos = _pPrintDoc->_rcClip.left; if (_iNrOfMultipleBlanks && (iPixelFree > 0)) { iPixelMultipleBlank = iPixelFree / _iNrOfMultipleBlanks; } // calculate the x position of every part for (i=0;i<_aryParts.Size();i++) { pDescr = _aryParts[i]; pDescr->xPos = xPos; if (pDescr->PartKind == pkMultipleBlank) { xPos += iPixelMultipleBlank; iTabStopPos += iPixelMultipleBlank; iMultipleBlankCounter++; } else { xPos += pDescr->iPixelLen; if (i > 0) { CDescr* pPrevDescr = _aryParts[i-1]; if (pPrevDescr->PartKind == pkMultipleBlank) { // previous element was a multipleblank // now try to center align the text part BOOL bTextCanBeCentered = (iTabStopPos + (pDescr->iPixelLen/2)) <= iPixelFree; BOOL bRemainingPartsFit = (iTabStopPos - (pDescr->iPixelLen/2) + iPixelLen) <= iPixelFree; if (bTextCanBeCentered && bRemainingPartsFit) { pDescr->xPos = iTabStopPos - (pDescr->iPixelLen / 2); xPos = pDescr->xPos + pDescr->iPixelLen; } else { // try to right align if ((iTabStopPos + iPixelLen) <= iPixelFree) { pDescr->xPos = iTabStopPos; xPos = iTabStopPos + pDescr->iPixelLen; } else { // we have to left align xPos = iTabStopPos - iPixelLen + pDescr->iPixelLen; pDescr->xPos = iTabStopPos - iPixelLen; // we have to make room for the other // parts as well } } } } iPixelLen -= pDescr->iPixelLen; // now it contains the length of the remaining parts } } } //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::DrawIt // // Synopsis: Goes through the parts collection (_aryParts) and draws the text parts // // Arguments: hdc device context handle // y the vertical position to draw at // //--------------------------------------------------------------------------- void CHeaderFooterInfo::DrawIt( CDrawInfo * pDI, const CCharFormat * pCF, int y, BOOL fHeader) { CDescr* pDescr; CDescr* pNextDescr; SIZE spaceSize; int nParts = _aryParts.Size(); int j; int nLen; GetTextExtentPoint32(pDI->_hdc,_T(" "),1,&spaceSize); for (int i=0;i<nParts;i++) { pDescr = _aryParts[i]; if (pDescr->pPart) { SIZE textsize; pNextDescr = NULL; int yPos; GetTextExtentPoint(pDI->_hdc,pDescr->pPart,_tcslen(pDescr->pPart),&textsize); if ((i < _aryParts.Size()-1) && (pDescr->PartKind != pkPageNum)) { pNextDescr = NULL; for (j=i+1;j<nParts;j++) { if (_aryParts[j]->pPart) { pNextDescr = _aryParts[j]; break; } } if (pNextDescr) { // Instead of doing >= I do > because if the user puts a space at the end // of the text we do not want to truncate it. // We do not know the user intentions wheather he/she wants to touch the next // part or not. if ((pDescr->xPos + textsize.cx ) > pNextDescr->xPos) { if (_tcslen(pDescr->pPart) < MAX_PATH) { // PathCompactPath assumes that the text at least MAX_PATH long // otherwise it overwrite the memory behind it. It is a bug in that code // BUGBUG if PathCompactPath will be fixed we do not need this whole if // statement. TCHAR* pNew = new(Mt(CDescr_pPart)) TCHAR[MAX_PATH+1]; if (pNew) { _tcscpy(pNew,pDescr->pPart); delete [] pDescr->pPart; pDescr->pPart = pNew; PathCompactPath(pDI->_hdc,pDescr->pPart,pNextDescr->xPos-pDescr->xPos-spaceSize.cx); } } else { PathCompactPath(pDI->_hdc,pDescr->pPart,pNextDescr->xPos-pDescr->xPos-spaceSize.cx); } if ((pDescr->xPos + textsize.cx ) > pNextDescr->xPos) { // because if the last part (after the rightmost slash) is too long // PathCompactPath does not truncate it right, therefore we have to // truncate it ourselves. nLen = _tcslen(pDescr->pPart); pDescr->pPart[nLen-1] = 0; while (nLen > 0) { GetTextExtentPoint(pDI->_hdc,pDescr->pPart,nLen-1,&textsize); if ((pDescr->xPos + textsize.cx ) > pNextDescr->xPos) { nLen--; pDescr->pPart[nLen] = 0; } else { break; } } } } } } // If we are drawing the footer, move the top of the text into the printable range. // To be sure that everything is visible, move up the footer by 120% of the text height: // MulDivQuick(spaceSize.cy, 6, 5). One of many PCL drivers that have a problem with this // mainly on Win95 is HP LaserJet 4Si MX. yPos = y - (fHeader ? 0 : MulDivQuick(spaceSize.cy, 6, 5)); // add 20% to the text height if (pCF) { FontLinkTextOut(pDI->_hdc, pDescr->xPos, yPos, 0, NULL, pDescr->pPart, _tcslen(pDescr->pPart), pDI, pCF, FLTO_TEXTOUTONLY); } else { TextOut(pDI->_hdc, pDescr->xPos, yPos, pDescr->pPart, _tcslen(pDescr->pPart)); } } } } //--------------------------------------------------------------------------- // // Member: CHeaderFooterInfo::Draw // // Synopsis: Draws the stored _pParsed string into the top or the bottom margin // // Arguments: pDI pointer to DrawInfo // bHeader True if it is a header, false if it is a footer // hFont font handle //--------------------------------------------------------------------------- void CHeaderFooterInfo::Draw( CDrawInfo* pDI, const CCharFormat * pCF, BOOL bHeader, HFONT hFont) { if (!_pHeaderFooter) return; if (_tcslen(_pHeaderFooter) < 1) return; HRGN hrgn = CreateRectRgn(0, 0, 0, 0); if (hrgn == NULL) return; if (SaveDC(pDI->_hdc)) { int y = 0; HFONT hFontOld = NULL; COLORREF oldColor = SetTextColor(pDI->_hdc,RGB(0,0,0)); // black COLORREF oldBkColor = SetBkColor(pDI->_hdc,RGB(255,255,255)); // white if (GetClipRgn(pDI->_hdc,hrgn) != -1) { SelectClipRgn(pDI->_hdc, NULL); if (hFont) hFontOld = (HFONT)SelectObject(pDI->_hdc,hFont); if (!_bParsed) ParseIt(); CalcXPos(pDI); if (bHeader) { IntersectClipRect(pDI->_hdc, pDI->_ptDst.x, 0, pDI->_ptDst.x + pDI->_sizeDst.cx, pDI->_ptDst.y); } else { IntersectClipRect(pDI->_hdc, pDI->_ptDst.x, pDI->_ptDst.y + pDI->_sizeDst.cy, pDI->_ptDst.x + pDI->_sizeDst.cx, #ifdef WIN16 //BUGWIN16: we don't have the GetDeviceCaps for PHYSICALHEIGHT, so turning this // back to the old code pDI->_ptDst.y + pDI->_sizeDst.cy + _pPrintDoc->_PrintInfoBag.rtMargin.bottom); y = pDI->_ptDst.y+pDI->_sizeDst.cy; #else GetDeviceCaps(pDI->_hic, PHYSICALHEIGHT)); // set the footer y to the end of the print range. if not in clip-rect, we clip. y = MulDivQuick(100*GetDeviceCaps(pDI->_hic, VERTSIZE), GetDeviceCaps(pDI->_hic, LOGPIXELSY), 2540); #endif }; #ifdef UNIX //currently mainwin doesn't support initialization of hdcDesktop // try to find a temprary patch { if (!bHeader){ SIZE spaceSize; GetTextExtentPoint32(pDI->_hdc, _T(" "),1,&spaceSize); if (spaceSize.cy == 0) y = pDI->_ptDst.y + pDI->_sizeDst.cy; } } #endif //unix DrawIt(pDI, pCF, y, bHeader); SelectClipRgn(pDI->_hdc,hrgn); DeleteObject(hrgn); if (hFontOld) SelectObject(pDI->_hdc,hFontOld); }; if (oldColor != CLR_INVALID) SetTextColor(pDI->_hdc,oldColor); if (oldBkColor != CLR_INVALID) SetBkColor(pDI->_hdc,oldBkColor); RestoreDC(pDI->_hdc,-1); } };
30.604695
117
0.437289
1987a2b4d96cf43b2be6d2b61e9ee7692691c499
9,723
cpp
C++
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
#include "stdafx_u.h" #include "StageSelect.h" #include "ParentSelectPanel.h" #include "InputManager.h" #include "SelectScreen.h" #include "ShakeComponent.h" #include "SelectPlayer.h" #include "SceneChangeAnimation.h" #include "GameSettings.h" #include"PauseManager.h" #include"Header/GameObjects/DefaultGameComponent/OutlineDrawComponent.h" int ButiEngine::StageSelect::stageNum = 0; int ButiEngine::StageSelect::maxStageNum = 19; //LastStageNum - 1 std::string ButiEngine::StageSelect::removeStageName = "none"; bool ButiEngine::StageSelect::isAnimation; int count=0; const float angle = 360.0f / (float)(ButiEngine::StageSelect::maxStageNum + 1) * 2.0f; void ButiEngine::StageSelect::OnUpdate() { Onece(); const auto childAngle = 180.0f / (ButiEngine::StageSelect::maxStageNum + 1) * 2.0f; auto parentSelectPanel = wkp_parentSelectPanel.lock()->GetGameComponent<ParentSelectPanel>(); if (intervalFrame > 20 && !isAnimation) { if (InputManager::OnPushRightKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushRight(); parentSelectPanel->ChildRotation(-childAngle,stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum<10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)), 0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } else if (InputManager::OnPushLeftKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushLeft(); parentSelectPanel->ChildRotation(childAngle,stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)),0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } if (InputManager::OnSkipKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushSkip(); parentSelectPanel->ChildRotation(-childAngle * ((maxStageNum + 1) / 2),stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)),0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } } else { intervalFrame++; } DecisionAnimation(); SelectRotation(); } void ButiEngine::StageSelect::OnSet() { } void ButiEngine::StageSelect::Start() { shp_pauseManager = GetManager().lock()->GetGameObject("PauseManager").lock()->GetGameComponent<PauseManager>(); GameSettings::isStageSelect = true; isOnece = false; isAnimation = false; animationFrame = 90; intervalFrame = 0; fadeCount = 0; wkp_parentSelectPanel = GetManager().lock()->GetGameObject("ParentSelectPanel"); wkp_animationPlayer = GetManager().lock()->AddObjectFromCereal("AnimationPlayer"); wkp_fadeObject = GetManager().lock()->AddObjectFromCereal("FadeObject", ObjectFactory::Create<Transform>(Vector3(0, 0, -0.01), Vector3::Zero, Vector3(2112, 1188, 1))); preParentRotation = stageNum * angle; auto sceneManager = gameObject.lock()->GetApplication().lock()->GetSceneManager(); if (stageNum <= 0) { std::string sceneName = "Stage" + std::to_string(maxStageNum); sceneManager->RemoveScene(sceneName); } else { int preStageNum = stageNum - 1; std::string sceneName = "Stage" + std::to_string(preStageNum); sceneManager->RemoveScene(sceneName); } se_enter = SoundTag("Sound/Enter.wav"); se_select = SoundTag("Sound/Select-Click.wav"); se_dash = SoundTag("Sound/Rat_Dash.wav"); se_hit = SoundTag("Sound/Rat_Hit.wav"); se_start = SoundTag("Sound/Rat_Start.wav"); bgm = SoundTag("Sound/BGM2.wav"); GetManager().lock()->GetApplication().lock()->GetSoundManager()->StopBGM(); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlayBGM(bgm, GameSettings::masterVolume + 0.5f); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)), 0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); GetManager().lock()->GetApplication().lock() ->GetGraphicDevice()->SetClearColor(Vector4((250.0f / 255.0f), (254.0f / 255.0f), (255.0f / 255.0f), 1.0f)); } void ButiEngine::StageSelect::OnShowUI() { } void ButiEngine::StageSelect::ShowGUI() { GUI::Begin("AnimationFrame"); GUI::Text(animationFrame); GUI::End(); GUI::Begin("StageNum"); GUI::BulletText("StageNum"); GUI::Text(stageNum); GUI::BulletText("Count"); GUI::Text(count); GUI::End(); } void ButiEngine::StageSelect::OnCollision(std::weak_ptr<GameObject> arg_other) { } std::shared_ptr<ButiEngine::GameComponent> ButiEngine::StageSelect::Clone() { return ObjectFactory::Create<StageSelect>(); } void ButiEngine::StageSelect::SetStageNum(int arg_stageNum) { stageNum = arg_stageNum; if (stageNum > maxStageNum) { stageNum = 0; } } void ButiEngine::StageSelect::SetRemoveStageName(std::string arg_removeStageName) { removeStageName = arg_removeStageName; } void ButiEngine::StageSelect::OnPushRight() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum++; if (stageNum > maxStageNum) { stageNum = 0; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnPushLeft() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum--; if (stageNum < 0) { stageNum = maxStageNum; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnPushSkip() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum += (maxStageNum + 1) / 2; if (stageNum > maxStageNum) { stageNum = stageNum - maxStageNum - 1; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnDecision() { GameSettings::isStageSelect = false; isAnimation = false; auto sceneManager = gameObject.lock()->GetApplication().lock()->GetSceneManager(); std::string sceneName = "Stage" + std::to_string(stageNum); sceneManager->RemoveScene(sceneName); sceneManager->LoadScene(sceneName); sceneManager->ChangeScene(sceneName); } void ButiEngine::StageSelect::DecisionAnimation() { if (InputManager::OnTriggerDecisionKey() && !isAnimation && !shp_pauseManager->IsPause()) { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_enter, GameSettings::masterVolume); isAnimation = true; } if (!isAnimation) return; if (animationFrame == screenRotateFrame) { GetManager().lock()->GetGameObject("SelectScreen").lock()->GetGameComponent<SelectScreen>()->StartAnimation(); } const int START_FRAME = 89; const int ZANZO_FRAME = 60; const int FLASH_FRAME = 40; const int AWAY_FRAME = 35; if (animationFrame == START_FRAME) { wkp_animationPlayer.lock()->GetGameComponent<SelectPlayer>()->Decision(); } else if (animationFrame == ZANZO_FRAME) { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_dash, GameSettings::masterVolume); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_start, GameSettings::masterVolume); GetManager().lock()->AddObjectFromCereal("SelectZanzo"); } else if (animationFrame == FLASH_FRAME) { GetManager().lock()->AddObjectFromCereal("SelectFlash"); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_hit, GameSettings::masterVolume); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_dash, GameSettings::masterVolume); } else if (animationFrame == AWAY_FRAME) { wkp_animationPlayer.lock()->GetGameComponent<SelectPlayer>()->Away(); } if (animationFrame <= 0) { isNext = true; } if (isNext) { fadeCount++; } if (fadeCount == 1) { GetManager().lock()->AddObjectFromCereal("FadeObject", ObjectFactory::Create<Transform>(Vector3(0, 1134, -0.01), Vector3::Zero, Vector3(2112, 1188, 1))); } const int NEXT_SCENE_COUNT = 30; if (fadeCount > NEXT_SCENE_COUNT) { OnDecision(); } if (animationFrame > 0) { animationFrame--; } } void ButiEngine::StageSelect::SelectRotation() { auto anim = wkp_parentSelectPanel.lock()->GetGameComponent<TransformAnimation>(); if (!anim) { anim = wkp_parentSelectPanel.lock()->AddGameComponent<TransformAnimation>(); anim->SetTargetTransform(wkp_parentSelectPanel.lock()->transform->Clone()); anim->GetTargetTransform()->SetLocalRotation(Matrix4x4::RollY(MathHelper::ToRadian( preParentRotation))); anim->SetSpeed(0.1f); anim->SetEaseType(Easing::EasingType::EaseOut); } } void ButiEngine::StageSelect::Onece() { if (isOnece) return; isOnece = true; auto parentSelectPanel = wkp_parentSelectPanel.lock()->GetGameComponent<ParentSelectPanel>(); auto childAngle = 180.0f / (maxStageNum + 1) * 2.0f; float rotate = childAngle * stageNum; preParentRotation = stageNum * angle; parentSelectPanel->ChildRotation(-rotate,stageNum); }
30.28972
168
0.724673
198a5018ac5a706b5c257b0944f7ef607a993788
88
cpp
C++
src/util/Cancellable.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
null
null
null
src/util/Cancellable.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
null
null
null
src/util/Cancellable.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
1
2019-01-08T14:48:29.000Z
2019-01-08T14:48:29.000Z
#include "util/Cancellable.h" using namespace BeeeOn; Cancellable::~Cancellable() { }
11
29
0.738636