text
stringlengths
8
6.88M
#ifndef MOON_H #define MOON_H #include <string> #include <vector> class Moon { private: std::vector<int> pos; std::vector<int> initPos; std::vector<int> vel; public: Moon(int x, int y, int z); int GetEnergy(); bool AtStart(); bool AtStart(int dimension); void Move(); void Move(int dimension); void UpdateVel(Moon& otherMoon); void UpdateVel(Moon& otherMoon, int dimension); }; #endif
#include <iostream> #include <cassert> using namespace std; string urlify(char* s, const size_t size){ int count = 0; for(int i=0; i<=size; i++){ if(s[i] == ' '){ count++; } } size_t newStrIndex = size + count * 2; size_t originStrIndex = size; while(count > 0){ if(s[originStrIndex] == ' '){ s[newStrIndex--] = '0'; s[newStrIndex--] = '2'; s[newStrIndex--] = '%'; originStrIndex--; count--; }else{ s[newStrIndex--] = s[originStrIndex--]; } } return s; } int main(void){ char *s = (char*)malloc(100); // new char[100]. strcpy(s, "This is a pen."); // stringでやるなら // string s; // s.reserve(100); // s = "This is a pen."; // s.size(); // s.capacity() == 100; urlify(s, strlen(s) + 1); // 文字列のサイズ+1(文字列の終わりを意味する'/0'の分) cout << s << endl; cout << strcmp(s, "This%20is%20a%20pen.") << endl; assert(strcmp(s, "This%20is%20a%20pen.") == 0); return 0; }
#include <iostream> using namespace std; class TwoStack { public: int n; TwoStack(int size) { n = size; } int *arr = new int[n]; int top1=-1; //init int top2=n; //init int size1() { if (top1 >= 0) { return top1 + 1; } return 0; } int size2() { if (top2 < n) return n - top2; return 0; } void push1(int val) { if (this->size1() + this->size2() < n) { top1++; arr[top1] = val; } else { cout << "OVERFLOW!!!" << endl; } } int pop1() { if (top1 >= 0) { int res = arr[top1]; top1--; return res; } else { cout << "UNDERFLOW!!!"; return -1; } } void push2(int val) { if (this->size1() + this->size2() < n) { top2--; arr[top2] = val; } else { cout << "OVERFLOW!!!" << endl; } } int pop2() { if (top2 < n) { int res = arr[top2]; top2--; return res; } else { cout << "UNDERFLOW!!!" << endl; return -1; } } int t1() { return arr[top1]; } int t2() { return arr[top2]; } void printStack1(){ for(int i=0;i<=top1;i++){ cout<<arr[top1]<<" "; } cout<<endl; } void printStack2(){ for(int i=top2;i<=0;i--){ cout<<arr[top2]<<" "; } cout<<endl; } }; int main(int argc, char const *argv[]) { TwoStack stack(5); stack.push1(1); stack.push1(2); cout<<stack.t1()<<endl; stack.push2(5); stack.push2(4); stack.push2(3); stack.push2(2); stack.pop2(); stack.pop1(); stack.printStack1(); stack.printStack2(); return 0; }
// Created on: 1996-12-11 // Created by: Robert COUBLANC // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _AIS_KindOfInteractive_HeaderFile #define _AIS_KindOfInteractive_HeaderFile //! Declares the type of Interactive Object. //! This type can be used for fast pre-filtering of objects of specific group. enum AIS_KindOfInteractive { AIS_KindOfInteractive_None, //!< object of unknown type AIS_KindOfInteractive_Datum, //!< presentation of construction element (datum) //! such as points, lines, axes and planes AIS_KindOfInteractive_Shape, //!< presentation of topological shape AIS_KindOfInteractive_Object, //!< presentation of group of topological shapes AIS_KindOfInteractive_Relation, //!< presentation of relation (dimensions and constraints) AIS_KindOfInteractive_Dimension, //!< presentation of dimension (length, radius, diameter and angle) AIS_KindOfInteractive_LightSource, //!< presentation of light source // old aliases AIS_KOI_None = AIS_KindOfInteractive_None, AIS_KOI_Datum = AIS_KindOfInteractive_Datum, AIS_KOI_Shape = AIS_KindOfInteractive_Shape, AIS_KOI_Object = AIS_KindOfInteractive_Object, AIS_KOI_Relation = AIS_KindOfInteractive_Relation, AIS_KOI_Dimension = AIS_KindOfInteractive_Dimension }; #endif // _AIS_KindOfInteractive_HeaderFile
#pragma once #include <maya/MPxCommand.h> #include <maya/MDGModifier.h> class MeltCmd : public MPxCommand { public: virtual MStatus doIt(const MArgList&); virtual MStatus redoIt(); virtual MStatus undoIt(); static void *creator() { return new MeltCmd; } private: MDGModifier dgMod; };
#include <iostream> using namespace std; istream & readfile(istream &in) { in.clear(); string str; while (in >> str, !in.eof()) { if(in.bad()) { ;//throw runtime_error("test"); } if(in.fail()) { cerr << "Get input failed,try again!"; in.clear(); continue; } cout << str << endl; } cout << str << endl; in.clear(); return in; } /*int main(int argc, const char *argv[]) { readfile(cin); return 0; }*/
#include <QMessageBox> #include <QDateTime> #include "windows.h" #include "mainwindow.h" #include "ui_mainwindow.h" // this is for solving PSTR conversion problem in GetWindowText #define UNICODE MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { QString display_num; ui->setupUi(this); this->appName = ""; this->min_setting = 25; this->sec_setting = 0; this->init_time(this->min_setting, this->sec_setting); this->update_lcd(this->min_left, this->sec_left); // a timer to update current time this->m_timer = new QTimer(); connect(this->m_timer, SIGNAL(timeout()), this, SLOT(update_ctime())); // start timer button connect(this->ui->pushButton_start, SIGNAL(clicked()), this, SLOT(btn_start())); // stop timer button connect(this->ui->pushButton_stop, SIGNAL(clicked()), this, SLOT(btn_stop())); // the button to show settings dialog connect(this->ui->pushButton_setting, SIGNAL(clicked()), this, SLOT(show_settings())); // the main window receives timer settings from the settings dialog connect(&(this->settings_dialog), SIGNAL(setup(int,int)), this, SLOT(setup(int,int))); } void MainWindow::init_time(int min, int sec){ this->min_left = min; this->sec_left = sec; } // format current time to show on the lcd number widget QString MainWindow::format_time(int min, int sec){ QString str_min; QString str_sec; QString display_num; str_min.setNum(min); if(min < 10){ str_min = "0" + str_min; } str_sec.setNum(sec); if(sec < 10){ str_sec = "0" + str_sec; } display_num = str_min + ":" + str_sec; return display_num; } void MainWindow::btn_start(){ if(this->m_timer->isActive()){ return; } this->ui->textBrowser->setText(""); this->appName = ""; QString display_num; this->init_time(this->min_setting, this->sec_setting); this->update_lcd(this->min_left, this->sec_left); this->m_timer->start(1000); } void MainWindow::btn_stop(){ if(this->m_timer->isActive()){ this->m_timer->stop(); } } void MainWindow::update_lcd(int min, int sec){ QString display_num; display_num = this->format_time(min, sec); this->ui->lcdNumber->display(display_num); } void MainWindow::update_ctime(){ HWND winHandle = GetForegroundWindow(); int cTxtLen = GetWindowTextLength(winHandle); PSTR pszMem = (PSTR) VirtualAlloc((LPVOID) NULL, (DWORD) (cTxtLen + 1), MEM_COMMIT, PAGE_READWRITE); GetWindowText(winHandle, pszMem, cTxtLen + 1); // to save Chinese characters into QString, fromLocal8Bit is needed QString tmpName = QString::fromLocal8Bit(pszMem); if(this->appName != tmpName){ this->appName = tmpName; QDateTime time = QDateTime::currentDateTime(); this->ui->textBrowser->append("\n"); this->ui->textBrowser->append(time.toString("hh:mm:ss")); this->ui->textBrowser->append(this->appName); } VirtualFree(pszMem, 0, MEM_RELEASE); if (this->sec_left == 0){ if (this->min_left == 0){ this->m_timer->stop(); this->setWindowState( (windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); this->activateWindow(); QMessageBox::StandardButton reply; reply = QMessageBox::question(this, tr("Congrats!"), tr("Do you want to restart?"), QMessageBox::Yes | QMessageBox::No); if(reply == QMessageBox::Yes){ this->btn_start(); } return; } this->min_left -= 1; this->sec_left = 59; } else { this->sec_left -= 1; } this->update_lcd(this->min_left, this->sec_left); } void MainWindow::show_settings(){ this->settings_dialog.show(); } void MainWindow::setup(int min, int sec){ if(this->m_timer->isActive()){ this->m_timer->stop(); } this->min_setting = min; this->sec_setting = sec; this->init_time(this->min_setting, this->sec_setting); this->update_lcd(min, sec); } MainWindow::~MainWindow() { if(this->m_timer->isActive()){ this->m_timer->stop(); } delete ui; }
#ifndef RESTREAMSDIALOG_H #define RESTREAMSDIALOG_H #include <iostream> #include <QDialog> #include <QMenu> #include <QModelIndex> #include <QMessageBox> #include <QCloseEvent> #include "vsmongo.h" extern VSMongo* vsmongo; extern bool cerrar; extern std::string exec_id; extern QString icons_folder; struct Restream{ QString name; QString origen; QString destino; }; namespace Ui { class RestreamsDialog; } class RestreamsDialog : public QDialog { Q_OBJECT public: explicit RestreamsDialog(QWidget *parent = 0); ~RestreamsDialog(); public slots: void openMenu(QPoint p); private slots: void on_new_restream_clicked(); void on_accept_clicked(); void closeEvent(QCloseEvent* event); signals: void mongoDisconnected(); private: bool validName(QString name); bool validOrig(QString dir_origen); Ui::RestreamsDialog *ui; std::vector<MRestream *> m_restreams_; void updateTable(); void loadRestreamsFromMongo(); }; #endif // RESTREAMSDIALOG_H
#include <vector> #include <inttypes.h> namespace TerrainGen { extern std::vector<uint8_t> compress( const std::vector<uint8_t>& input, size_t inp_size, size_t pixels_to_compress, size_t out_size, size_t patch_offset_x, size_t patch_offset_y ); };
// // Coins.h // GLWF // // Created by Rodrigo Castro Ramos on 1/28/19. // Copyright © 2019 Rodrigo Castro Ramos. All rights reserved. // #ifndef Coins_h #define Coins_h #include <GL/glew.h> // GLFW #include <GLFW/glfw3.h> // Other Libs #include "SOIL2/SOIL2.h" // GLM Mathematics #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> // Other includes #include "Shader.h" #include "Camera.h" #include "Texture.h" #include <vector> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; class Coin { public: vector<glm::vec3> coinsPositions; vector<bool> gotcha; GLfloat valor; Coin(){ coinsPositions.push_back(glm::vec3( rand()%4-2, 0.0f, -rand()%15)); coinsPositions.push_back(glm::vec3( rand()%4-2, 0.0f, -rand()%15 )); coinsPositions.push_back(glm::vec3( rand()%4-2, 0.0f, -rand()%15 )); coinsPositions.push_back(glm::vec3( rand()%4-2, 0.0f, -rand()%15 )); coinsPositions.push_back(glm::vec3( rand()%4-2, 0.0f, -rand()%15 )); coinsPositions.push_back(glm::vec3( rand()%4-2, 0.0f, -rand()%15 )); gotcha.push_back(false); gotcha.push_back(false); gotcha.push_back(false); gotcha.push_back(false); gotcha.push_back(false); gotcha.push_back(false); valor = 10.0f; } void movement(){ for (int i = 0; i < coinsPositions.size(); i++) { coinsPositions[i].z += 0.001 ; if (coinsPositions[i].z >= 10) { coinsPositions[i].x = rand()%10-1; coinsPositions[i].z = -rand()%10; } } } void updateCoins(){ for (int i = 0; i < coinsPositions.size(); i++) { if (gotcha[i] == true) { coinsPositions[i] = glm::vec3( rand()%10-1, 0.0f, -rand()%10 ); cout<< "Colicionaron conmigo soy moneda"<<endl; } } } }; #endif /* Coins_h */
//Given a no check whether it can be represented as sum of 2020 and 2021 #include <iostream> using namespace std; bool sum(int n) { while(n>=2020) { if(n%2021==0) n=0; if(n%2020==0) n=0; else { if(n>=2021) n=n-2021; if(n>=2020) n=n-2020; } } if(n==0) return true; return false; } int main() { int t,n; cin>>t; while(t--) { cin>>n; if(sum(n)) cout<<"Yes\n"; else cout<<"No\n"; } return 0; }
// // Clock.cpp // Odin.MacOSX // // Created by Daniel on 04/06/15. // Copyright (c) 2015 DG. All rights reserved. // #include "Clock.h" #include <chrono> #include <time.h> namespace odin { namespace core { UI64 Clock::getCycles() { return static_cast<F64>(clock()); } UI64 Clock::secondsToCycles(F64 timeSeconds) { return static_cast<F64>(timeSeconds * CLOCKS_PER_SEC); } F64 Clock::cyclesToSeconds(UI64 timeCycles) { return static_cast<F64>(timeCycles) / CLOCKS_PER_SEC; } F64 Clock::getTimeMillis() { // get time in microseconds in order to have enough floating point precision return std::chrono::duration_cast<std::chrono::microseconds> (std::chrono::system_clock::now().time_since_epoch()).count()/1000.0; } F64 Clock::getTimeSeconds() { return getTimeMillis()/1000.0; } // the clock automatically starts upon creation Clock::Clock(F64 startTimeSeconds) : m_elapsedTime(startTimeSeconds), m_timeScale(1.0f), m_isPaused(false) { m_startTime = getTimeSeconds(); } F64 Clock::getStartTime() const { return m_startTime; } F64 Clock::getElapsedTime() const { if(m_isPaused) { return m_elapsedTime; } else { return m_elapsedTime + (getTimeSeconds() - m_startTime); } } void Clock::add(F64 deltaTimeSeconds) { if (!m_isPaused) { m_elapsedTime += (deltaTimeSeconds * m_timeScale); } } void Clock::pause() { // set paused m_isPaused = true; // update the time elapsed m_elapsedTime += getTimeSeconds() - m_startTime; } void Clock::resume() { // set running m_isPaused = false; // update the start time m_startTime = getTimeSeconds(); } void Clock::restart() { m_elapsedTime = 0.0; m_isPaused = false; m_startTime = getTimeSeconds(); } bool Clock::isPaused() const { return m_isPaused; } void Clock::setTimeScale(F32 scale) { m_timeScale = scale; } F32 Clock::getTimeScale() const { return m_timeScale; } void Clock::singleStep(F32 targetFPS) { if (m_isPaused) { m_elapsedTime += (1.0f/targetFPS) * m_timeScale; } } } }
#include <iostream> #include <vector> #include <map> #include <string> #include <bitset> #include <queue> #include <algorithm> #include <functional> using namespace std; class GogoXBallsAndBinsEasy { public: int solve(vector <int> T) { vector<int> S(T); sort(S.begin(), S.end(), greater<int>()); int ans = 0; int i=0; while (S.at(i) > T.at(i)) { ans += S.at(i) - T.at(i); ++i; } return ans; } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #ifndef _SSL_VER_H_ #define _SSL_VER_H_ #if defined _NATIVE_SSL_SUPPORT_ #include "modules/libssl/base/sslprotver.h" #include "modules/libssl/methods/sslphash.h" class SSL_MAC; class SSL_Record_Base; class SSL_CipherDescriptions; struct Handshake_actions_st; class SSL_CipherSpec; #define SSL_MASTER_SECRET_SIZE 48 enum Handshake_Add_Point{ Handshake_Add_In_Front, // Add at start of list Handshake_Add_Before_ID, // Add immediately before the given ID, if it does not exist use Handshake_Add_At_End Handshake_Add_After_ID, // Add immediately after the given ID, if it does not exist, use Handshake_Add_At_End Handshake_Add_At_End // Add at end of list (default) }; enum Handshake_Remove_Point{ Handshake_Remove_From_ID, Handshake_Remove_Only_ID }; enum Handshake_Queue { Handshake_Send, Handshake_Receive }; struct SSL_DataQueueHead : public SSL_Head { SSL_secure_varvector32 *First() const{ return (SSL_secure_varvector32 *)SSL_Head::First(); }; //pointer SSL_secure_varvector32 *Last() const{ return (SSL_secure_varvector32 *)SSL_Head::Last(); }; //pointer }; class SSL_Version_Dependent : public SSL_Error_Status { protected: enum SSL_V3_handshake_id { SSL_V3_Recv_Hello_Request, SSL_V3_Recv_Server_Hello, SSL_V3_Recv_Certificate, TLS_Recv_CertificateStatus, SSL_V3_Recv_Server_keys, SSL_V3_Recv_Certificate_Request, SSL_V3_Recv_Server_Done, SSL_V3_Send_PreMaster_Key, SSL_V3_Send_Certficate, SSL_V3_Pre_Certficate_Verify, SSL_V3_Send_Certficate_Verify, SSL_V3_Send_No_Certficate, SSL_V3_Post_Certficate, SSL_V3_Send_Change_Cipher, SSL_V3_Recv_Server_Cipher_Change, SSL_V3_Recv_Server_Finished, SSL_V3_Send_Client_Finished, SSL_V3_Send_Handshake_Complete, SSL_V3_Send_Pause, TLS_Send_Next_Protocol, #ifdef LIBSSL_ENABLE_SSL_FALSE_START SSL_V3_Send_False_Start_Application_Data #endif // LIBSSL_ENABLE_SSL_FALSE_START }; private: Head Send_Queue; Head Receive_Queue; SSL_DataQueueHead handshake_queue; protected: SSL_ProtocolVersion version; SSL_Hash_Pointer final_hash; #ifdef _DEBUG SSL_secure_varvector16 handshake; #endif const SSL_CipherDescriptions *cipher_desc; SSL_ConnectionState *conn_state; protected: SSL_Version_Dependent(uint8 ver_major, uint8 ver_minor); void ClearHandshakeActions(Handshake_Queue action_queue); void AddHandshakeAction(Handshake_Queue action_queue , SSL_V3_handshake_id id, SSL_HandShakeType mtyp, SSL_Handshake_Status _mstat, SSL_Handshake_Action actn, Handshake_Add_Point add_policy = Handshake_Add_At_End, SSL_V3_handshake_id add_id = SSL_V3_Recv_Hello_Request); void RemoveHandshakeAction(Handshake_Queue action_queue, int id, Handshake_Remove_Point remove_policy = Handshake_Remove_Only_ID); SSL_Handshake_Status GetHandshakeStatus(Handshake_Queue action_queue, int id); private: Handshake_actions_st *GetHandshakeItem(Handshake_Queue action_queue, int id); void Init(); public: virtual ~SSL_Version_Dependent(); const SSL_ProtocolVersion &Version() const{return version;}; void SetConnState(SSL_ConnectionState *conn){conn_state = conn;} virtual SSL_MAC *GetMAC() const = 0; virtual SSL_Record_Base *GetRecord(SSL_ENCRYPTMODE mode) const; virtual void SetCipher(const SSL_CipherDescriptions *desc); void AddHandshakeHash(SSL_secure_varvector32 *); virtual void GetHandshakeHash(SSL_SignatureAlgorithm alg, SSL_secure_varvector32 &); void GetHandshakeHash(SSL_Hash_Pointer &hasher); virtual void GetFinishedMessage(BOOL client, SSL_varvector32 &target)= 0; virtual void CalculateMasterSecret(SSL_secure_varvector16 &mastersecret, const SSL_secure_varvector16 &premaster)=0; virtual void CalculateKeys(const SSL_varvector16 &mastersecret, SSL_CipherSpec *client, SSL_CipherSpec *server ) /*const */=0; virtual BOOL SendAlert(SSL_Alert &, BOOL cont) const= 0; // If necessary translate passed alert virtual BOOL SendClosure() const; virtual SSL_Handshake_Action HandleHandshakeMessage(SSL_HandShakeType); virtual SSL_Handshake_Action NextHandshakeAction(SSL_HandShakeType &); virtual void SessionUpdate(SSL_SessionUpdate); virtual BOOL ExpectingCipherChange(); }; #endif #endif
#pragma once #ifndef IOMANAGER_H #define IOMANAGER_H #include <vector> #include <fstream> class IOManager { public: static bool realFileToBuffer(std::string filePath, std::vector<unsigned char>& buffer); }; #endif
// Created on: 2014-11-13 // Created by: Maxim YAKUNIN // Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapeFix_FixSmallSolid_HeaderFile #define _ShapeFix_FixSmallSolid_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <ShapeFix_Root.hxx> class TopoDS_Shape; class ShapeBuild_ReShape; class ShapeFix_FixSmallSolid; DEFINE_STANDARD_HANDLE(ShapeFix_FixSmallSolid, ShapeFix_Root) //! Fixing solids with small size class ShapeFix_FixSmallSolid : public ShapeFix_Root { public: //! Construct Standard_EXPORT ShapeFix_FixSmallSolid(); //! Set working mode for operator: //! - theMode = 0 use both WidthFactorThreshold and VolumeThreshold parameters //! - theMode = 1 use only WidthFactorThreshold parameter //! - theMode = 2 use only VolumeThreshold parameter Standard_EXPORT void SetFixMode (const Standard_Integer theMode); //! Set or clear volume threshold for small solids Standard_EXPORT void SetVolumeThreshold (const Standard_Real theThreshold = -1.0); //! Set or clear width factor threshold for small solids Standard_EXPORT void SetWidthFactorThreshold (const Standard_Real theThreshold = -1.0); //! Remove small solids from the given shape Standard_EXPORT TopoDS_Shape Remove (const TopoDS_Shape& theShape, const Handle(ShapeBuild_ReShape)& theContext) const; //! Merge small solids in the given shape to adjacent non-small ones Standard_EXPORT TopoDS_Shape Merge (const TopoDS_Shape& theShape, const Handle(ShapeBuild_ReShape)& theContext) const; DEFINE_STANDARD_RTTIEXT(ShapeFix_FixSmallSolid,ShapeFix_Root) protected: private: Standard_EXPORT Standard_Boolean IsThresholdsSet() const; Standard_EXPORT Standard_Boolean IsSmall (const TopoDS_Shape& theSolid) const; Standard_EXPORT Standard_Boolean IsUsedWidthFactorThreshold() const; Standard_EXPORT Standard_Boolean IsUsedVolumeThreshold() const; Standard_Integer myFixMode; Standard_Real myVolumeThreshold; Standard_Real myWidthFactorThreshold; }; #endif // _ShapeFix_FixSmallSolid_HeaderFile
#ifndef PORT_NEURON_H #define PORT_NEURON_H #include "synfire_constants.h" #ifdef __GPU_BUILD__ #include "cuda_utils.h" #include <cuda_runtime.h> #define CUDA_CALLABLE __host__ __device__ #define INLINE #else #define CUDA_CALLABLE #define INLINE inline #endif class Neuron { public: #ifdef __GPU_BUILD__ friend class CUSynfire; #endif Neuron(); Neuron( int label, double exc_freq, double inh_freq, double exc_amp, double inh_amp, double global_inhibition ); ~Neuron(); bool Update( float dt ); CUDA_CALLABLE bool Update( float dt, float r1, float r2, float r3, float r4 ); CUDA_CALLABLE void neur_dyn( double dt, bool no_volt ); void Reset(); CUDA_CALLABLE void ExciteInhibit( double amp, char p ); CUDA_CALLABLE INLINE double Get( char code ) { if (code == 'e') return _gexc; else if (code == 'i') return _ginh; else if (code == 'v') return _volts; // Error. return 0.0; } CUDA_CALLABLE INLINE double Volts() { return _volts; } CUDA_CALLABLE INLINE double Excitatory() { return _gexc; } CUDA_CALLABLE INLINE double Inhibitory() { return _ginh; } private: void Initialize( int label, double exc_freq, double inh_freq, double exc_amp, double inh_amp, double global_inhibition, double leak ); INLINE void SetSpinFrequency( double excitory, double inhibitory ) { _spfreq_ex = excitory * 0.001; _spfreq_in = inhibitory * 0.001; } //""""""""""""""""""""""""""""""""""""""""""""""""" //~ INTERNAL int _label; // The Neuron's label. double _volts, _gexc, _ginh; // Membrane potential, excitory and inibitory conductances double _global_in; // Global inhibition amplitude. double _spfreq_ex, _spamp_ex; // Spontaneous excitory frequency and amplitude. double _spfreq_in, _spamp_in; // Spontaneous inhibitory frequency and amplitude. double _LEAKREV; // TODO: not sure what this means. // Two factors that limit development of cycles // _cRef - refactory period 25 ms // _cLatent - LTD (longterm depression) 20 ms int _cLatent, _cRef; // Latent and refractory counters. static int _LABEL_COUNTER; }; #endif //PORT_NEURON_H
#include "streamencoder.h" #include "profiler.h" #include "xor.h" #include <memory> #include <iostream> #include <random> #include <set> #include <chrono> #include <iomanip> #include <cstring> #include <omp.h> using namespace std; trevi::StreamEncoder::StreamEncoder(int encodingWindowSize, int numSourceBlockPerCodeBlock, int numCodeBlockPerSourceBlock) :_encodingWindowSize(encodingWindowSize), _numSourceBlockPerCodeBlock(numSourceBlockPerCodeBlock), _numCodeBlockPerSourceBlock(numCodeBlockPerSourceBlock) { init(); } trevi::StreamEncoder::~StreamEncoder() { } void trevi::StreamEncoder::addData(std::shared_ptr<trevi::SourceBlock> cb, uint8_t streamId ) { #ifdef USE_PROFILING rmt_ScopedCPUSample(StreamEncoder_addData, 0); #endif // Add to encoding buffer cb->updateCRC(); pushSourceBlock(cb); omp_set_num_threads(4); if( _encodingWindow.size() > 0 && _curSeqIdx % _numSourceBlockPerCodeBlock == 0 ) { #pragma omp parallel for for( int j = 0; j < _numCodeBlockPerSourceBlock; ++j ) { int threadID = omp_get_thread_num(); // printf( "threadID=%d\n", threadID); auto polbak = createEncodedBlock( pickDegree() ); if( polbak != nullptr ) { polbak->set_stream_id(streamId); { #pragma omp critical _codeBlocks.push_back( polbak ); } } } } // dumpCodeBlocks(); // cerr << "_curSeqIdx=" << _curSeqIdx << endl; } void trevi::StreamEncoder::addData(uint8_t *buffer, int bufferSize) { std::shared_ptr< trevi::SourceBlock > cb = std::make_shared<trevi::SourceBlock>( buffer, bufferSize ); addData( cb ); } void trevi::StreamEncoder::dumpEncodingWindow() { for( int i = 0; i < _encodingWindow.size(); ++i ) { cerr << _encodingWindow[i] << " "; } cerr << endl; } bool trevi::StreamEncoder::hasEncodedBlocks() { return _codeBlocks.size() > 0; } std::shared_ptr<trevi::CodeBlock> trevi::StreamEncoder::getEncodedBlock() { std::shared_ptr< trevi::CodeBlock > ret = nullptr; if( hasEncodedBlocks() ) { ret = _codeBlocks.front(); _codeBlocks.pop_front(); } return ret; } void trevi::StreamEncoder::init() { _curSeqIdx = 0; srand( time(NULL) ); generator.seed(std::chrono::system_clock::now().time_since_epoch().count()); degree_generator.seed(std::chrono::system_clock::now().time_since_epoch().count()); } void trevi::StreamEncoder::pushSourceBlock(std::shared_ptr<trevi::SourceBlock> cb, uint8_t streamId ) { if( _encodingWindow.size() >= _encodingWindowSize ) { _encodingWindow.pop_front(); _sourceBlockBuffer.pop_front(); } _encodingWindow.push_back( _curSeqIdx ); _sourceBlockBuffer.push_back( cb ); // Also output the degree 1 block immediatly std::shared_ptr< trevi::CodeBlock > d1cb = std::make_shared< trevi::CodeBlock >( cb->buffer_size(), (uint8_t*)cb->buffer_ptr(), cb->buffer_size() ); std::set<uint32_t> compoSet; compoSet.insert(0); d1cb->setCompositionField(_curSeqIdx, compoSet ); d1cb->set_stream_id(streamId); _codeBlocks.push_back( d1cb ); _curSeqIdx++; } uint32_t trevi::StreamEncoder::oldestSeqIdx() { return _encodingWindow.front(); } uint32_t trevi::StreamEncoder::latestSeqIdx() { return _encodingWindow.back(); } std::shared_ptr<trevi::CodeBlock> trevi::StreamEncoder::createEncodedBlock(uint16_t degree) { #ifdef USE_PROFILING rmt_ScopedCPUSample(StreamEncoder_createEncodedBlock, 0); #endif std::set<uint32_t> compoSet; std::uniform_int_distribution<int> distribution(0,_encodingWindow.size()-1); while( compoSet.size() != degree ) { // Select a source packet at random int number = distribution(generator); int seqNum = _encodingWindow[ number ]; if( compoSet.find( number ) == compoSet.end() ) { compoSet.insert( number ); } } // Compute MTU for current set of blocks int maxBlockSize = 0; std::set<uint32_t>::iterator it; for (it=compoSet.begin(); it!=compoSet.end(); ++it) { int idx = *it; std::shared_ptr< trevi::SourceBlock > curCb = _sourceBlockBuffer[ idx ]; if( curCb->buffer_size() > maxBlockSize ) { maxBlockSize = curCb->buffer_size(); } } uint8_t tmpBuffer_A[ maxBlockSize ]; uint8_t tmpBuffer_B[ maxBlockSize ]; memset( tmpBuffer_A, 0, maxBlockSize ); // std::cout << "set:" << endl; // printSet( compoSet ); // std::cout << "....." << endl; // std::cout << "set:" << endl; for (it=compoSet.begin(); it!=compoSet.end(); ++it) { int idx = *it; std::shared_ptr< trevi::SourceBlock > curCb = _sourceBlockBuffer[ idx ]; memset( tmpBuffer_B, 0, maxBlockSize ); trevi_memcpy( tmpBuffer_B, curCb->buffer_ptr(), curCb->buffer_size() ); trevi_xor( tmpBuffer_A, tmpBuffer_B, maxBlockSize ); } std::shared_ptr< trevi::CodeBlock > cbcode = std::make_shared<trevi::CodeBlock>( maxBlockSize, (uint8_t*)tmpBuffer_A, (int)maxBlockSize ); cbcode->setCompositionField( oldestSeqIdx(), compoSet ); return cbcode; } std::shared_ptr<trevi::CodeBlock> trevi::StreamEncoder::selectRandomSourceBlock() { return nullptr; } uint16_t trevi::StreamEncoder::pickDegree() { std::uniform_int_distribution<int> distribution(1, min((int)_encodingWindowSize, (int)_encodingWindow.size()) ); uint16_t ret = distribution(degree_generator); return ret; } void trevi::StreamEncoder::dumpCodeBlocks() { cerr << "###### CURRENT COEBLOCKS:" << endl; for( std::shared_ptr< trevi::CodeBlock > cb : _codeBlocks ) { cb->dumpCompositionField(); } cerr << "#########################" << endl; } void trevi::StreamEncoder::setCodeRate(int nsrc, int ncode) { if( nsrc > 0 ) _numSourceBlockPerCodeBlock = nsrc; if( ncode >= 0 ) _numCodeBlockPerSourceBlock = ncode; }
#ifndef TEXT_H #define TEXT_H class Text{ public: void split(std::string s, std::string delimiter, std::string filename); bool checkSame(std::vector<std::string> list, std::string str); }; #endif
/***************************************************************************************************************** * File Name : quantityConversions.h * File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\fun\maths\school\class05\quantityConversions.h * Created on : Dec 26, 2013 :: 11:39:16 PM * Author : AVINASH * Testing Status : TODO * URL : TODO *****************************************************************************************************************/ /************************************************ Namespaces ****************************************************/ using namespace std; using namespace __gnu_cxx; /************************************************ User Includes *************************************************/ #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <cmath> #include <algorithm> #include <ctime> #include <list> #include <map> #include <set> #include <bitset> #include <functional> #include <utility> #include <iostream> #include <fstream> #include <sstream> #include <string.h> #include <hash_map> #include <stack> #include <queue> #include <limits.h> #include <programming/ds/tree.h> #include <programming/ds/linkedlist.h> #include <programming/utils/treeutils.h> #include <programming/utils/llutils.h> /************************************************ User defined constants *******************************************/ #define null NULL #define ML 1 #define LITER 1000 * ML /************************************************* Main code ******************************************************/ #ifndef QUANTITYCONVERSIONS_H_ #define QUANTITYCONVERSIONS_H_ long long int converIntoMilliliters(unsigned int noLiter,unsigned int noMilliliter){ long long int result = 0; result += noLiter * LITER; result += noMilliliter; return result; } hash_map<string,unsigned int> convertIntoUnits(long long int userInputml){ hash_map<string,unsigned int> respectiveUnitsAmounts; unsigned int noLiter = userInputml / LITER; userInputml -= noLiter * LITER; respectiveUnitsAmounts.insert(pair<string,unsigned int>("liters",noLiter)); respectiveUnitsAmounts.insert(pair<string,unsigned int>("milliliter",userInputml)); return respectiveUnitsAmounts; } #endif /* QUANTITYCONVERSIONS_H_ */ /************************************************* End code *******************************************************/
// Lesson 1: //#include <iostream> // int main() // { // std::cout << "Hello World!" << std::endl; // return 0; // } //#include <iostream> // int main() // { // int x=8; // int y=6; // std::cout << std::endl; // std::cout << x - y << " " << x * y << " " << x + y; // std::cout << std::endl; // return 0; // } //#include <iostream> // int main() // { // std::cout << "Hello Buggy World \n" << std::endl; // return 0; // } // Lesson 2: // Listing 2.4 //#include <iostream> // using namespace std; // // Declare a function // int DemoConsoleOutput(); // int main() // { // // Call i.e. invoke the function // DemoConsoleOutput(); // return 0; // } // // Define i.e. implement the previously declared function // int DemoConsoleOutput() // { // cout << "This is a simple string literal" << endl; // cout << "Writing number five: " << 5 << endl; // cout << "Performing division 10 / 5 = " << 10 / 5 << endl; // cout << "Pi when approximated is 22 / 7 = " << 22 / 7 << endl; // cout << "Pi is 22 / 7 = " << 22.0 / 7 << endl; // return 0; // } // Listing 2.5 //#include <iostream> // using namespace std; // // Function declaration and definition // int DemoConsoleOutput() // { // cout << "This is a simple string literal" << endl; // cout << "Writing number five: " << 5 << endl; // cout << "Performing division 10 / 5 = " << 10 / 5 << endl; // cout << "Pi when approximated is 22 / 7 = " << 22 / 7 << endl; // cout << "Pi is 22 / 7 = " << 22.0 / 7 << endl; // return 0; // } // int main() // { // // Function call with return used to exit // return DemoConsoleOutput(); // } // Listing 2.6 // #include <iostream> // #include <string> // using namespace std; // int main() // { // // Declare a variable to store an integer // int inputNumber; // cout << "Enter an integer: "; // // store integer given user input // cin >> inputNumber; // // The same with text i.e. string data // cout << "Enter you name: "; // string inputName; // cin >> inputName; // cout << inputName << " entered " << inputNumber << endl; // return 0; // } // Exercise #include <iostream> int main() { std::cout << "Is there a bug here?" << std::endl; return 0; }
#include <algorithm> #include <cctype> #include <cerrno> #include <cstdlib> #include <fstream> #include <iostream> #include <stdexcept> #include <string> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include "profile_run.h" #include "profile_timer.h" namespace { void dup_fd(int from, int to) { for (;;) { if (dup2(from, to) == -1) { if (errno == EINTR) continue; else throw std::runtime_error("dup failed"); } else { break; } } } std::string read_output(int from, bool echo) { static char buf[256]; std::string res; for (;;) { auto count = read(from, buf, sizeof(buf)); if (count == -1) { if (errno == EINTR) continue; else throw std::runtime_error("read failed"); break; } else if (count == 0) { break; } else { std::string block(buf, buf + count); if (echo) std::cout << block << std::flush; res += block; } } return res; } std::string clean_output(std::string const &output) { std::size_t i = 0u, j = output.size() - 1u; while (std::isspace(output[i])) ++i; while (std::isspace(output[j])) --j; return output.substr(i, j - i + 1u); } } std::string run_gap(std::string const &script, bool hide_output, bool hide_errors, double *t) { // create temporary gap script char ftmp[] = {'X', 'X', 'X', 'X', 'X', 'X'}; if (mkstemp(ftmp) == -1) throw std::runtime_error("failed to create temporary file"); class FileRemover { public: FileRemover(std::string const &f) : _f(f) {} ~FileRemover() { std::remove(_f.c_str()); } private: std::string _f; } file_remover(ftmp); std::ofstream f(ftmp); if (f.fail()) throw std::runtime_error("failed to create temporary file"); f << script; f.flush(); // create pipe for capturing gaps output int fds[2]; if (pipe(fds) == -1) throw std::runtime_error("failed to create pipe"); // run gap in a child process timer_start(); pid_t child; switch ((child = fork())) { case -1: throw std::runtime_error("failed to fork child process"); case 0: { dup_fd(fds[1], STDOUT_FILENO); fcntl(STDOUT_FILENO, F_SETFL, fcntl(STDOUT_FILENO, F_GETFL) | O_DIRECT); close(fds[1]); close(fds[0]); if (hide_errors) { int dev_null = open("/dev/null", O_WRONLY); if (dev_null != -1) dup_fd(dev_null, STDERR_FILENO); } if (execlp("gap", "gap", "--nointeract", "-q", ftmp, nullptr) == -1) _Exit(EXIT_FAILURE); _Exit(EXIT_SUCCESS); } } close(fds[1]); auto output(clean_output(read_output(fds[0], !hide_output))); close(fds[0]); if (t) *t = timer_stop(child); return output; } std::string compress_gap_output(std::string const &gap_output_) { auto res(gap_output_); for (char space : " \n\\") res.erase(std::remove(res.begin(), res.end(), space), res.end()); return res; }
#include "dpdk_metric_interface.h" DPDKMetricInterface::DPDKMetricInterface(){ } DPDKMetricInterface::~DPDKMetricInterface(){ rte_metrics_deinit(); printf("Metric Interface is destroyed\n"); } bool DPDKMetricInterface::initialize_metrics(void *data){ socket_id = *((int *)data); rte_metrics_init(socket_id); return true; } bool DPDKMetricInterface::register_metric(const char *name_str, int &id){ id = rte_metrics_reg_name(name_str); // printf("String is %s and length is %d\n\n", name_str, strlen(name_str)); if(!(id >= 0)){ return false; } //print_metrics(); return true; } bool DPDKMetricInterface::update_metric(int metric_id, int64_t value, bool absolute){ if(absolute){ return (rte_metrics_update_value(socket_id, metric_id, value)) >= 0; }else{ uint64_t current_value; if(get_metric(metric_id, current_value)){ current_value += value; return (rte_metrics_update_value(socket_id, metric_id, value)) >= 0; } return false; } } bool DPDKMetricInterface::get_metric(int metric_id, uint64_t &metric_value){ struct rte_metric_value *metrics; int len; int ret; int i; len = rte_metrics_get_names(NULL, 0); if (len < 0) { printf("Cannot get metrics count\n"); return false; } if (len == 0) { printf("No metrics to display (none have been registered)\n"); return false; } metrics = (struct rte_metric_value*) malloc(sizeof(struct rte_metric_value) * len); if (metrics == NULL) { printf("Cannot allocate memory\n"); free(metrics); return false; } ret = rte_metrics_get_values(socket_id, metrics, len); if (ret < 0 || ret > len) { printf("Cannot get metrics values\n"); free(metrics); return false; } for(i = 0; i < len; i++){ if(metrics[i].key == metric_id){ metric_value = metrics[i].value; break; } } return true; } void DPDKMetricInterface::print_metrics(){ struct rte_metric_value *metrics; struct rte_metric_name *names; int len; int ret; len = rte_metrics_get_names(NULL, 0); if (len < 0) { printf("Cannot get metrics count\n"); return; } if (len == 0) { printf("No metrics to display (none have been registered)\n"); return; } metrics = (struct rte_metric_value*) malloc(sizeof(struct rte_metric_value) * len); names = (struct rte_metric_name*) malloc(sizeof(struct rte_metric_name) * len); if (metrics == NULL || names == NULL) { printf("Cannot allocate memory\n"); free(metrics); free(names); return; } ret = rte_metrics_get_values(socket_id, metrics, len); if (ret < 0 || ret > len) { printf("Cannot get metrics values\n"); free(metrics); free(names); return; } printf("Metrics for port %i is %d units long\n", socket_id, len); // for (int i = 0; i < len; i++) // printf(" %s: %llu -> %zu\n", // names[metrics[i].key].name, metrics[i].value, strlen(names[metrics[i].key].name)); //free(metrics); //free(names); }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "BatteryCollector.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, BatteryCollector, "BatteryCollector" );
#ifndef BDD_NODE_H #define BDD_NODE_H /* * File bdd_node.h * * Created 5/2003 by Karl Rosaen * * Modified 9/22/2004 by Karl Rosaen * - added use of smart pointers * * Contains definition of class Bdd_node and prototypes for * helper functions */ #include <iostream> #include <set> #include "smart_pointer.h" class bdd_node; class bdd_tables; // all pointers to Bdd_nodes will be handeled // with smart pointers typedef smart_pointer<bdd_node> bdd_ptr; // bdd_node // The buiding block for BDDs. Contains a variable that is split on // pointers to Bdd_nodes that are the negative and positive cofactors // w.r.t var, and class methods that act on entire BDDs that are made // up of the Bdd_node and its children // // Two static nodes are declared that are the two unique terminal nodes, // one and zero class bdd_node : public Reference_Counted_Object { public: ~bdd_node(); // the bdd_ctr used to give each created node its unique id static int id_ctr; static std::set<int> free_ids; // the terminal nodes used by every BDD static bdd_ptr one; static bdd_ptr zero; // this node's unique id int get_id() { return id; } // only the terminal nodes (one and zero) will have null children bool is_terminal() { return (neg_cf == 0); } bool is_zero() {return (this == zero); } bool is_one() {return (this == one); } // prints the contents of the BDD by recursively visiting all of the nodes void print(std::ostream& os = std::cout); // read and set print mode static bool print_mode() {return print_verbose;} static void set_print_mode(bool val) {print_verbose = val;} // returns whether or not the tree has a certain variable bool has_var(char thevar); // the var that is split on. irrelevant for static (class wide) nodes one and zero char var; // children = smart pointers to bdd_nodes representing the positive and // negative cofactors with respect to var // both nodes = 0 means this is a leaf node bdd_ptr neg_cf; bdd_ptr pos_cf; float probability; //holds the probability of each node // must be assigned after each node is created friend class bdd_tables; private: // can only be created by Bdd_tables bdd_node(); int id; // the unique id of this node static bool print_verbose; // whether or not to print the node's ids }; // allows a Bdd to be fed into a stream, i.e cout << bdd1 std::ostream& operator<< (std::ostream& os, bdd_ptr bnode); // returns the next var to be split on (used in Apply). Lower value vars // have precedence char find_next_var(bdd_ptr bdd1, bdd_ptr bdd2); #endif
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #ifndef MQ_HPP_ #define MQ_HPP_ #ifndef __link #include <iface/link.h> #include <mqueue.h> #include <fcntl.h> #include <cstring> namespace sys { class Mq; /*! \brief Message Queue Attribute Class */ class MqAttr { friend class Mq; public: MqAttr(){ memset(&m_attr, 0, sizeof(m_attr)); }; MqAttr(long f, long m, long s){ m_attr.mq_flags = f; m_attr.mq_curmsgs = 0; m_attr.mq_maxmsg = m; m_attr.mq_msgsize = s; } /*! \details Message queue attribute flags */ enum flags { NONBLOCK /*! \brief Non-blocking queue */ = LINK_O_NONBLOCK, RDWR /*! \brief Read/write queue */ = LINK_O_RDWR, READWRITE /*! \brief Read/write queue */ = LINK_O_RDWR, RDONLY /*! \brief Read only queue */ = LINK_O_RDONLY, READONLY /*! \brief Read only queue */ = LINK_O_RDONLY }; inline long flags() const { return m_attr.mq_flags; } inline long curmsgs() const { return m_attr.mq_curmsgs; } inline long maxmsg() const { return m_attr.mq_maxmsg; } inline long msgsize() const { return m_attr.mq_msgsize; } inline void set_flags(long v) { m_attr.mq_flags = v; } inline void set_curmsgs(long v) { m_attr.mq_curmsgs = v; } inline void set_maxmsg(long v) { m_attr.mq_maxmsg = v; } inline void set_msgsize(long v) { m_attr.mq_msgsize = v; } private: struct mq_attr m_attr; }; /*! \brief Message Queue Class */ /*! \details This class is a wrapper for POSIX message queues. * */ class Mq { public: Mq(); /*! \details Bitwise flags for open() */ enum flags { CREATE /*! \brief Create a new message queue */ = O_CREAT, EXCL /*! \brief Create exclusively */ = O_EXCL, EXCLUSIVE /*! \brief Create exclusively */ = O_EXCL }; /*! \detailsls This method opens a message queue * * @param name The name of the message queue * @param oflag Open flags * @param mode Access mode * @param attr Pointer to attributes * @return Less than zero for an error (use perror()) */ int open(const char * name, int oflag, mode_t mode = 0, const struct mq_attr * attr = 0); /*! \details This method creates a new message queue. * * @param name The name of the queue * @param oflag EXCLUSIVE or 0 * @param mode Permissions * @param flags Message queue flags * @param maxmsg Max number of messages * @param msgsize Message size * @return Less than zero for an error (use perror()) */ int create(const char * name, int oflag, mode_t mode, long flags, long maxmsg, long msgsize); /*! \brief Close the message queue */ int close(); inline bool is_open() const { return m_handle != -1; } /*! \details Not currently supported */ int notify(const struct sigevent *notification); /*! \details Copy message queue attributes to mqstat */ int get_attr(struct mq_attr *mqstat); /*! \details Return the message queue attributes */ MqAttr get_attr(); int set_attr(const struct mq_attr * mqstat, struct mq_attr * omqstat = 0); int set_attr(const MqAttr & attr); /*! \details Receive a message from the queue */ ssize_t receive(char * msg_ptr, size_t msg_len); /*! \details Receive a message from the queue with a timeout */ ssize_t timedreceive(char * msg_ptr, size_t msg_len, const struct timespec * abs_timeout); ssize_t receive_timed(char * msg_ptr, size_t msg_len, const struct timespec * abs_timeout){ return timedreceive(msg_ptr, msg_len, abs_timeout); } /*! \details Send a message to the queue */ int send(const char * msg_ptr, size_t msg_len, unsigned msg_prio = 0); /*! \details Send a message to the queue with a timeout */ int timedsend(const char * msg_ptr, size_t msg_len, unsigned msg_prio, const struct timespec * abs_timeout); int send_timed(const char * msg_ptr, size_t msg_len, unsigned msg_prio, const struct timespec * abs_timeout){ return timedsend(msg_ptr, msg_len, msg_prio, abs_timeout); } /*! \details Delete a message queue */ static int unlink(const char * name); /*! \details Message priority of last message received */ unsigned msg_prio() const { return m_msg_prio; } private: mqd_t m_handle; unsigned m_msg_prio; }; }; #endif #endif /* MQ_HPP_ */
// Header: // RsaToolbox #include "About.h" using namespace RsaToolbox; bool isAboutMenu(int argc, char *argv[]); // main: if (isAboutMenu(argc, argv)) return 0; // Defined: bool isAboutMenu(int argc, char *argv[]) { if (argc != 2) return false; QString arg(argv[1]); arg = arg.trimmed().toUpper(); if (arg == "-ABOUT" || arg == "--ABOUT") { Q_INIT_RESOURCE(AboutResources); About about; about.setAppName(APP_NAME); about.setVersion(APP_VERSION); about.setDescription(APP_DESCRIPTION); about.setContactInfo(CONTACT_INFO); about.exec(); return true; } return false; } // Settings.h: const QString APP_DESCRIPTION = "..."; const QString CONTACT_INFO = "<html><head/><body><p>Nick Lalic<br/>VNA Software Developer<br/>Cupertino, CA USA<br/>+1 424 200 2846<br/>nick.lalic@rsa.rohde-schwarz.com<br/><a href=\"http://vna.rs-us.net\"><span style=\"text-decoration: underline; color:#0000ff;\">http://vna.rs-us.net</span></a></p></body></html>";
// Aluno Rodrigo Yuji #include <iostream> #include <omp.h> #include <stdio.h> int main(int argc, char* argv[]) { int nthreads, i, tid; float total; #pragma omp parallel shared(nthreads) private(i,tid,total) { tid = omp_get_thread_num(); if (tid == 0) { nthreads = omp_get_num_threads(); printf("Numero de threads = %d\n", nthreads); } printf("Thread %d executando...\n", tid); #pragma omp barrier total = 0.0; #pragma omp for schedule(dynamic,10) for (i = 0; i < 1000000; i++) { total = total + i * 1.0; } printf("Thread %d terminou! Total= %e\n", tid, total); } return 0; }
#include "mnist.h" #include <fstream> #include <opencv2/opencv.hpp> namespace mnist { inline int reverseInt(int i) { unsigned char ch1, ch2, ch3, ch4; ch1 = i & 255; ch2 = (i >> 8) & 255; ch3 = (i >> 16) & 255; ch4 = (i >> 24) & 255; return ((int)ch1 << 24) + ((int)ch2 << 16) + ((int)ch3 << 8) + ch4; } void readMnistImages(std::string filename, std::vector<cv::Mat> &vec) { std::ifstream file(filename, std::ios::binary); if (file.is_open()) { int magic_number = 0; int number_of_images = 0; int n_rows = 0; int n_cols = 0; file.read((char *)&magic_number, sizeof(magic_number)); magic_number = reverseInt(magic_number); file.read((char *)&number_of_images, sizeof(number_of_images)); number_of_images = reverseInt(number_of_images); file.read((char *)&n_rows, sizeof(n_rows)); n_rows = reverseInt(n_rows); file.read((char *)&n_cols, sizeof(n_cols)); n_cols = reverseInt(n_cols); for (int i = 0; i < number_of_images; ++i) { cv::Mat tp = cv::Mat::zeros(n_rows, n_cols, CV_8UC1); for (int r = 0; r < n_rows; ++r) { for (int c = 0; c < n_cols; ++c) { unsigned char temp = 0; file.read((char *)&temp, sizeof(temp)); tp.at<uchar>(r, c) = (int)temp; } } vec.push_back(tp); } } } void readMnistLabels(std::string full_path, std::vector<char> &labels) { int numberOfLabels; std::ifstream file(full_path, std::ios::binary); if (file.is_open()) { int magic_number = 0; file.read((char *)&magic_number, sizeof(magic_number)); magic_number = reverseInt(magic_number); if (magic_number != 2049) throw std::runtime_error("Invalid MNIST label file!"); file.read((char *)&numberOfLabels, sizeof(numberOfLabels)); numberOfLabels = reverseInt(numberOfLabels); labels.resize(numberOfLabels); for (int i = 0; i < numberOfLabels; i++) { file.read((char *)&labels[i], 1); } } else { throw std::runtime_error("Unable to open file `" + full_path + "`!"); } } }
#ifndef _MY_DHCP_H_ #define _MY_DHCP_H_ #pragma once #include "common.h" typedef struct IpAndMac{ ip_addr ip; UINT8 macAddr[6]; struct IpAndMac *pNext; }; typedef struct IpAndMacHead{ UINT16 len; struct IpAndMac *pHead; }; class mydhcp{ private: IpAndMacHead queueHead; static mydhcp *m_instance; public: mydhcp(); ~mydhcp(); static mydhcp *getInstance(){ if (m_instance == NULL){ m_instance = new mydhcp(); } return m_instance; } IpAndMac *getAvailItem(); void insertAvailItem(ip_addr ip); }; #endif
#ifndef MYCANVAS_H #define MYCANVAS_H #include <QWidget> #include <QColor> #include <QPainter> #include <vector> #include <math.h> #include <stack> using namespace std; enum ModeAdd { SIMPLY, HORIZONTAL, }; struct RectangleCutter { QPoint min_point = {-1, -1}; QPoint max_point = {-1, -1}; }; struct Line { QPoint start = {-1, -1}; QPoint end = {-1, -1}; Line(const QPoint& new_start, const QPoint& new_end) { start = new_start; end = new_end; } Line(const QPoint& new_start) { start = new_start; } }; struct CanvasColor { QColor color_line = QColor(Qt::black); QColor color_cut = QColor(Qt::white); QColor color_cutter = QColor(Qt::black); }; struct CanvasScene { QImage main_scene; }; class MyCanvas : public QWidget { Q_OBJECT private: CanvasColor color; vector<Line> lines; CanvasScene scene; RectangleCutter cutter; private: void update_scene(); int sign(const int num); void draw_line(const Line& edge, QPainter& painter, const QColor& color); void draw_all_lines(const QColor& color); void draw_point(const QPoint& point, QPainter& painter, const QColor& color); void draw_cutter(const QColor& color); void cut_lines_middle_point(QPainter& painter); public: explicit MyCanvas(QWidget *parent = nullptr); void set_line_color(const QColor& new_color); void set_cut_color(const QColor& new_color); void set_cutter_color(const QColor& new_color); QColor get_line_color() const; QColor get_cut_color() const; QColor get_cutter_color() const; void add_line(const Line& line); void add_new_line(const QPoint& point, const ModeAdd& mode); void update_rectangle_cutter(const QPoint &point); void clear_scene(); void clear_cutter(); void clear_lines(); void cut_region(float eps); void cut_region_middle_point(float eps, QPainter& painter); void calc_bits(int *arr, const QPointF point); int sum_bits(int *arr); int logic_mult(int *arr_fst, int *arr_sec); double len_line(const QPointF P1, const QPointF P2); bool region_is_empty(); protected: void paintEvent(QPaintEvent* event); }; #endif // MYCANVAS_H
#ifndef __MISC_HH_ #define __MISC_HH_ #include <string> #include <llvm/IR/Type.h> #include <llvm/IR/Value.h> #include <llvm/IR/Module.h> #define UNITS_UNIT(s) \ (s) < 2048 ? "B" : \ (s) / 1024 < 1024 ? "K" : \ (s) / (1024 * 1024) < 1024 ? "M" : "G" #define UNITS_SIZE(s) \ (s) < 2048 ? (s) : \ (s) / 1024 < 1024 ? (s) / 1024 : \ (s) / (1024 * 1024) < 1024 ? (s) / (1024 * 1024) : \ (s) / (size_t) (1024 * 1024 * 1024) std::string fmt (const std::string fmt_str, ...); std::string operator * (std::string lhs, int i); std::string quoted_str (const char * str); void print_type (llvm::Type *t, std::string &s); void print_value (const llvm::Value *v, std::string &s); void print_value_as_operand (llvm::Value *v, std::string &s); void dump_ll (const llvm::Module *m, const char *filename); #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef OP_PROGRESS_H #define OP_PROGRESS_H #include "modules/widgets/OpWidget.h" /** OpProgress is a widget showing progress (just a value on a linear scale). There's no way to change its value by interaction with it. It can be in either progress or meter type (which results in different skin and value sanitation) */ class OpProgress : public OpWidget #ifndef QUICK , public OpWidgetListener #endif // QUICK { protected: OpProgress(); virtual ~OpProgress(); public: static OP_STATUS Construct(OpProgress** obj); enum TYPE { TYPE_PROGRESS, ///< Progress type (the default) TYPE_METER_GOOD_VALUE, ///< Meter with a good value TYPE_METER_BAD_VALUE, ///< Meter with a bad value TYPE_METER_WORST_VALUE ///< Meter with a really bad value }; /** Set which mode to display */ void SetType(TYPE type); /** Set the current progress value (in percent) */ void SetValue(INT32 value) { SetProgress((float)value / 100.0f); } /** Get the current progress value (in percent) */ INT32 GetValue() { return (INT32)(m_progress * 100); } void GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows); /** Set the current progress value. @param val Should be a value from 0 to 1, or -1 (which means that progress bar is indeterminate) */ void SetProgress(float progress); // == OpWidget ====================== virtual void OnPaint(OpWidget *widget, const OpRect &paint_rect) {} // == OpWidgetListener ============== virtual void OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect); private: TYPE m_type; float m_progress; }; #endif // OP_PROGRESS_H
#include "pitch.h" #include <string.h> // for memcpy #include <assert.h> Pitch::Pitch(int window_size, int sample_rate) : window_size_(window_size), sample_rate_(sample_rate) { //ctor init(); } Pitch::~Pitch() { //dtor del_fvec(yin_in); del_fvec(yin_out); del_aubio_pitch(o); aubio_cleanup(); } int Pitch::init() { // From aubio pitch example /* allocate some memory */ uint_t win_s = window_size_; /* window size */ uint_t hop_s = win_s/4; /* hop size */ uint_t samplerate = sample_rate_; /* samplerate */ uint_t channels = 1; /* number of channel */ yin_in = new_fvec (win_s); /* input buffer */ yin_out = new_fvec(1); o = new_aubio_pitch("yin", win_s, hop_s, samplerate); aubio_pitch_set_unit(o, "freq"); is_initialized_ = true; return 0; } float Pitch::getPitch(const float* const audio_frames, int num_frames) { assert( is_initialized_ == true && num_frames == window_size_); yin_in->length = num_frames; /* todo: no need to copy data */ memcpy (yin_in->data, audio_frames, sizeof (float) * num_frames); aubio_pitch_do(o, yin_in, yin_out); return float(yin_out->data[0]); }
#include "Water.h" void Water::Draw(aie::Renderer2D* r) { r->drawBox(position.x, position.y, 200, 200); // Draw }
#pragma once #include <iosfwd> #include <cmath> #include <utility> #include "vector.h" #include "type_traits.h" namespace sbg { template<typename T> struct Vector<2, T> { static_assert(std::is_arithmetic<T>::value, "Vector must be aritmetic"); using MathType = typename std::conditional<std::is_floating_point<T>::value, T, double>::type; constexpr Vector() : x{0}, y{0} {} constexpr explicit Vector(T value) : x{value}, y{value} {} constexpr Vector(T _x, T _y) : x{_x}, y{_y} {} template<typename O, typename std::enable_if<std::is_convertible<T, O>::value, int>::type = 0> constexpr inline operator Vector<2, O> () const { return Vector<2, O>{ static_cast<O>(x), static_cast<O>(y) }; } template<typename O, typename std::enable_if<is_strictly_explicitly_convertible<T, O>::value, int>::type = 0> constexpr explicit inline operator Vector<2, O> () const { return Vector<2, O>{ static_cast<O>(x), static_cast<O>(y) }; } MathType angle() const { auto angle = std::atan2(y, x); if (angle < 0) { angle += static_cast<T>(tau); } return angle; } MathType length() const { return std::sqrt(power<2>(x) + power<2>(y)); } void applyAngle(MathType a) { *this = angle(a); } void applyLenght(MathType lenght) { if (!null()) { auto product = lenght / length(); x *= static_cast<T>(product); y *= static_cast<T>(product); } else { x = static_cast<T>(lenght); } } Vector<2, decltype(std::declval<T>() * std::declval<MathType>())> lenght(MathType lenght) { auto product = lenght / length(); return {x * product, y * product}; } Vector<2, T> project(const Vector<2, T>& other) const { return dot(other.unit()) * other; } constexpr bool null() const { return x == 0 && y == 0; } Vector<2, decltype(std::declval<T>() / std::declval<MathType>())> unit() const { if (!null()) { auto lenght = length(); return {x / lenght, y / lenght}; } else { return {0, 0}; } } Vector<2, T> angle(MathType angle) const { Vector<2, T> temp; if (!null()) { auto lenght = length(); temp.x = static_cast<T>(std::cos(angle) * lenght); temp.y = static_cast<T>(std::sin(angle) * lenght); } return temp; } template<typename U> constexpr auto dot(const Vector<2, U>& vec) const -> decltype((std::declval<T>() * std::declval<U>())) { return (x * vec.x) + (y * vec.y); } template<typename U> constexpr Vector<1, decltype((std::declval<T>() * std::declval<U>()))> cross(const Vector<2, U>& other) const { return {(x * other.y) - (y * other.x)}; } template<typename U> constexpr Vector<2, decltype((std::declval<U>() * std::declval<T>()))> cross(U multiplier) const { return {multiplier * y, -multiplier * x}; } template<typename U> constexpr Vector<2, decltype((std::declval<U>() * std::declval<T>()))> cross(const Vector<1, U>& multiplier) const { return {multiplier * y, -multiplier * x}; } Vector<2, T>& operator=(const Vector<2, T>& other) { x = other.x; y = other.y; return *this; } template<typename U> constexpr bool operator==(const Vector<2, U>& other) const { return x == other.x && y == other.y; } template<typename U> constexpr bool operator!=(const Vector<2, U>& other) const { return !(*this == other); } template<typename U> constexpr bool operator<(const Vector<2, U>& other) const { return (power<2>(x) + power<2>(y)) < ((other.x * other.x) + (other.y * other.y)); } template<typename U> constexpr bool operator>(const Vector<2, U>& other) const { return (power<2>(x) + power<2>(y)) > ((other.x * other.x) + (other.y * other.y)); } T x, y; constexpr static int size = 2; using type = T; }; template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator<(const Vector<2, T>& vec, U length) { return power<2>(vec.x) + power<2>(vec.y) < static_cast<typename Vector<2, T>::MathType>(length * length); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator>(const Vector<2, T>& vec, U length) { return power<2>(vec.x) + power<2>(vec.y) > static_cast<typename Vector<2, T>::MathType>(length * length); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator<(U length, const Vector<2, T>& vec) { return static_cast<typename Vector<2, T>::MathType>(length * length) < power<2>(vec.x) + power<2>(vec.y); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr bool operator>(U length, const Vector<2, T>& vec) { return static_cast<typename Vector<2, T>::MathType>(length * length) > power<2>(vec.x) + power<2>(vec.y); } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<2, decltype(std::declval<T>() / std::declval<U>())> operator/(const Vector<2, T>& vec, U divider) { return {vec.x / divider, vec.y / divider}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<2, decltype(std::declval<T>() / std::declval<U>())> operator/(U divider, const Vector<2, T>& vec) { return {vec.x / divider, vec.y / divider}; } template<typename T, typename U> constexpr Vector<2, decltype(std::declval<T>() / std::declval<U>())> operator/(const Vector<2, T>& vec1, const Vector<2, U>& vec2) { return {vec1.x / vec2.x, vec1.y / vec2.y}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<2, decltype(std::declval<T>() * std::declval<U>())> operator*(const Vector<2, T>& vec, U multiplier) { return {vec.x * multiplier, vec.y * multiplier}; } template<typename T, typename U> constexpr Vector<2, decltype(std::declval<T>() * std::declval<U>())> operator*(const Vector<2, T>& vec1, const Vector<2, U>& vec2) { return {vec1.x * vec2.x, vec1.y * vec2.y}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> constexpr Vector<2, decltype(std::declval<T>() * std::declval<U>())> operator*(U multiplier, const Vector<2, T>& vec) { return {vec.x * multiplier, vec.y * multiplier}; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> Vector<2, T>& operator*=(Vector<2, T>& vec, U multiplier) { vec.x *= multiplier; vec.y *= multiplier; return vec; } template<typename T, typename U> constexpr Vector<2, decltype(std::declval<T>() + std::declval<U>())> operator+(const Vector<2, T>& vec1, const Vector<2, U>& vec2) { return {vec1.x + vec2.x, vec1.y + vec2.y}; } template<typename T, typename U> Vector<2, T>& operator+=(Vector<2, T>& vec1, const Vector<2, U>& vec2) { vec1.x += vec2.x; vec1.y += vec2.y; return vec1; } template<typename T, typename U> constexpr Vector<2, decltype(std::declval<T>() - std::declval<U>())> operator-(const Vector<2, T>& vec1, const Vector<2, U>& vec2) { return {vec1.x - vec2.x, vec1.y - vec2.y}; } template<typename T, typename U> Vector<2, T>& operator-=(Vector<2, T>& vec1, const Vector<2, U>& vec2) { vec1.x -= vec2.x; vec1.y -= vec2.y; return vec1; } template<typename T, typename U, typename std::enable_if<std::is_arithmetic<U>::value, int>::type = 0> Vector<2, T>& operator/= (Vector<2, T>& vec, U divider) { vec.x /= divider; vec.y /= divider; return vec; } template<typename T, typename U> Vector<2, T>& operator/=(Vector<2, T>& vec1, const Vector<2, U>& vec2) { vec1.x /= vec2.x; vec1.y /= vec2.y; return vec1; } template<typename T, typename U> Vector<2, T>& operator*=(Vector<2, T>& vec1, const Vector<2, U>& vec2) { vec1.x *= vec2.x; vec1.y *= vec2.y; return vec1; } template<typename T> constexpr Vector<2, T> operator-(const Vector<2, T>& vec) { return {-vec.x, -vec.y}; } template<typename T> std::ostream& operator<<(std::ostream& out, const Vector<2, T>& vec) { out << vec.x << ", " << vec.y; return out; } extern template struct Vector<2, float>; extern template struct Vector<2, double>; extern template struct Vector<2, long double>; extern template struct Vector<2, int>; extern template struct Vector<2, unsigned int>; extern template struct Vector<2, long>; extern template struct Vector<2, unsigned long>; extern template struct Vector<2, short>; extern template struct Vector<2, unsigned short>; extern template struct Vector<2, char>; extern template struct Vector<2, unsigned char>; using Vector2f = Vector<2, float>; using Vector2d = Vector<2, double>; using Vector2ld = Vector<2, long double>; using Vector2i = Vector<2, int>; using Vector2ui = Vector<2, unsigned int>; using Vector2l = Vector<2, long>; using Vector2ul = Vector<2, unsigned long>; using Vector2s = Vector<2, short>; using Vector2us = Vector<2, unsigned short>; using Vector2c = Vector<2, char>; using Vector2uc = Vector<2, unsigned char>; }
/* * economy.cc * * Created on: May 28, 2015 * Author: arun */ #include "economy.hpp" //static int randSeed = 1; Economy::Economy(int numHouseholds, int seed):myHHs(),econSize(numHouseholds){ myHHs=new Household*[numHouseholds]; distr = uniform_real_distribution<double>(0.0, 1.0); gener = mt19937(seed); // srand(randSeed++); } Economy::~Economy(){ for (unsigned int i = 0; i < econSize; i++){ delete myHHs[i]; } delete[] myHHs; } void Economy::initialize(const EquilFns &pol, const StochProc& proc, const State& p_currentState){ for (unsigned int i = 0; i < econSize; i++){ myHHs[i] = new Household(floor(10*NUMHHS*distr(gener)), pol, proc); // myHHs[i] = new Household(rand(), pol, proc); } for (unsigned int i = 0; i < econSize; i++){ myHHs[i]->setInitialState(p_currentState); } } double Economy::getAverage(unsigned int asset){ double total=0; for (unsigned int i = 0; i < econSize; i++){ total+=myHHs[i]->getCurrentAsset(asset); } return total/econSize; } double Economy::getAverageTest(unsigned int asset) const{ double total = 0; for (unsigned int i = 0; i < econSize; i++) { total += myHHs[i]->getTestAsset(asset); } return total / econSize; } double Economy::getAverageAssets(){ double total = 0; for (unsigned int i = 0; i < econSize; i++){ total += myHHs[i]->getCurrentState(ASTATE); } return total / econSize; } void Economy::simulateOnePeriod(int newPhiState, double r){ phiState = newPhiState; #if OPENMP #pragma omp parallel for schedule(dynamic) num_threads(3) #endif for (int i = 0; i < (int)econSize; i++){ myHHs[i]->iterate(0,newPhiState, r); } } void Economy::testOnePeriod(int newPhiState, double r, double randNum) const{ uniform_real_distribution<double> localdistr = uniform_real_distribution<double>(0.0, 1.0); mt19937 localgener = mt19937(randNum); #if OPENMP #pragma omp parallel for schedule(dynamic) num_threads(3) #endif for (int i = 0; i < (int)econSize; i++) { myHHs[i]->test(0, newPhiState, r, localdistr(localgener)); } } void Economy::testOnePeriod(int newPhiState, double r, double randNum) const{ uniform_real_distribution<double> localdistr = uniform_real_distribution<double>(0.0, 1.0); mt19937 localgener = mt19937(randNum); #if OPENMP #pragma omp parallel for schedule(dynamic) num_threads(3) #endif for (int i = 0; i < (int)econSize; i++) { myHHs[i]->test(0, newPhiState, r, localdistr(localgener)); } } void Economy::printEconomy(std::string fileName){ ofstream out_stream; out_stream.open(fileName.c_str()); out_stream << "hh,z1,z2,wage_shock,k1,k2,b" << endl; for (unsigned int i = 0; i < econSize; i++){ out_stream<<i<<","<<myHHs[i]->toString()<<endl; } out_stream.close(); }
#include "AudioDevice.h" #include "AudioProcessingUnit.h" #include "CartridgeReader.h" #include "CentralProcessingUnit.h" #include "GameController.h" #include "MemoryBus.h" #include "MemoryMapper.h" #include "PictureProcessingUnit.h" #include "RenderingWindow.h" #include <iostream> #define CLOCK_DIVIDER_CPU_NTSC (12u) #define CLOCK_DIVIDER_APU_NTSC (24u) #define CLOCK_DIVIDER_PPU_NTSC (4u) #define CLOCK_DIVIDER_CPU_PAL (16u) #define CLOCK_DIVIDER_APU_PAL (32u) #define CLOCK_DIVIDER_PPU_PAL (5u) #define min(x1, x2) ((x1) < (x2) ? (x1) : (x2)) int main(int argc, char** argv) { if (argc == 2) { std::string path = argv[1]; uint8_t code = 0; if (code = CR::loadFile(path)) { std::cout << "Error loading ROM file. Code: " << (int)code << std::endl; return (1); } } else { std::cout << "One argument expected: path to ROM file" << std::endl; getchar(); return (1); } MM::init(); if (!MM::setMapper(CR::getMapperType())) { std::cout << "Mapper " << (int)CR::getMapperType() << " not supported" << std::endl; getchar(); return (1); } MB::init(); if (!MB::loadMapperInformation()) { std::cout << "An error accured while loading mapper info" << std::endl; getchar(); return (1); } RW::init(); GC::init(); AD::init(); APU::reset(); CPU::reset(); PPU::reset(); uint8_t cpuDivider, apuDivider, ppuDivider; uint8_t cpuCountdown, apuCountdown, ppuCountdown; if (CR::getSystemType() == SYSTEM_NTSC) { cpuDivider = CLOCK_DIVIDER_CPU_NTSC; apuDivider = CLOCK_DIVIDER_APU_NTSC; ppuDivider = CLOCK_DIVIDER_PPU_NTSC; } else { // PAL system cpuDivider = CLOCK_DIVIDER_CPU_PAL; apuDivider = CLOCK_DIVIDER_APU_PAL; ppuDivider = CLOCK_DIVIDER_PPU_PAL; } cpuCountdown = cpuDivider; apuCountdown = apuDivider; ppuCountdown = ppuDivider; for (;;) // program loop { uint8_t windowEvent = RW::pollWindowEvent(); if (windowEvent == EVENT_BUTTON_CLOSE_PRESSED) { break; } /* The audio device is used to keep track of time */ while (AD::bufferFull() == false) { uint8_t step = min(cpuCountdown, apuCountdown); step = min(step, ppuCountdown); cpuCountdown -= step; apuCountdown -= step; ppuCountdown -= step; if (cpuCountdown == 0) { CPU::step(); cpuCountdown = cpuDivider; } if (apuCountdown == 0) { APU::step(); apuCountdown = apuDivider; } if (ppuCountdown == 0) { PPU::step(); ppuCountdown = ppuDivider; } } } RW::dispose(); AD::dispose(); CR::clean(); MB::clean(); return (0); }
//--------------------------------------------------------- // // Project: dada // Module: gl // File: GL.h // Author: Viacheslav Pryshchepa // // Description: // //--------------------------------------------------------- #ifndef DADA_GL_GL_H #define DADA_GL_GL_H #ifdef DADA_WITH_GLEW # include <GL/glew.h> #else // DADA_WITH_GLEW #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # include <windows.h> //# include "GL/gl.h" # include "GLES3/gl3.h" #else # include <GL/gl.h> #endif #ifdef GL_VERSION_1_1 # define DADA_GL_CORE_VERSION_1_1 #endif #ifdef GL_VERSION_1_2 # define DADA_GL_CORE_VERSION_1_2 #endif #ifdef GL_VERSION_1_3 # define DADA_GL_CORE_VERSION_1_3 #endif #ifdef GL_VERSION_1_4 # define DADA_GL_CORE_VERSION_1_4 #endif #ifdef GL_VERSION_1_5 # define DADA_GL_CORE_VERSION_1_5 #endif #ifdef GL_VERSION_2_0 # define DADA_GL_CORE_VERSION_2_0 #endif #ifdef GL_VERSION_2_1 # define DADA_GL_CORE_VERSION_2_1 #endif #ifdef GL_VERSION_3_0 # define DADA_GL_CORE_VERSION_3_0 #endif #ifdef GL_VERSION_3_1 # define DADA_GL_CORE_VERSION_3_1 #endif #ifdef GL_VERSION_3_2 # define DADA_GL_CORE_VERSION_3_2 #endif #ifdef GL_VERSION_3_3 # define DADA_GL_CORE_VERSION_3_3 #endif #ifdef GL_VERSION_4_0 # define DADA_GL_CORE_VERSION_4_0 #endif #ifdef GL_VERSION_4_1 # define DADA_GL_CORE_VERSION_4_1 #endif #ifdef GL_VERSION_4_2 # define DADA_GL_CORE_VERSION_4_2 #endif #ifdef GL_VERSION_4_3 # define DADA_GL_CORE_VERSION_4_3 #endif #ifdef GL_VERSION_4_4 # define DADA_GL_CORE_VERSION_4_4 #endif #ifdef GL_VERSION_4_5 # define DADA_GL_CORE_VERSION_4_5 #endif #ifdef GL_VERSION_4_6 # define DADA_GL_CORE_VERSION_4_6 #endif //#include "GL/glext.h" #include "GLES2/gl2ext.h" // // GL_VERSION_1_0 // //typedef void (APIENTRYP PFNGLCULLFACEPROC) (GLenum mode); //typedef void (APIENTRYP PFNGLFRONTFACEPROC) (GLenum mode); //typedef void (APIENTRYP PFNGLHINTPROC) (GLenum target, GLenum mode); //typedef void (APIENTRYP PFNGLLINEWIDTHPROC) (GLfloat width); //typedef void (APIENTRYP PFNGLPOINTSIZEPROC) (GLfloat size); //typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode); //typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height); //typedef void (APIENTRYP PFNGLTEXPARAMETERFPROC) (GLenum target, GLenum pname, GLfloat param); //typedef void (APIENTRYP PFNGLTEXPARAMETERFVPROC) (GLenum target, GLenum pname, const GLfloat *params); //typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param); //typedef void (APIENTRYP PFNGLTEXPARAMETERIVPROC) (GLenum target, GLenum pname, const GLint *params); //typedef void (APIENTRYP PFNGLTEXIMAGE1DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const void *pixels); //typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); //typedef void (APIENTRYP PFNGLDRAWBUFFERPROC) (GLenum buf); extern PFNGLCLEARPROC glClear; extern PFNGLCLEARCOLORPROC glClearColor; //typedef void (APIENTRYP PFNGLCLEARSTENCILPROC) (GLint s); //typedef void (APIENTRYP PFNGLCLEARDEPTHPROC) (GLdouble depth); //typedef void (APIENTRYP PFNGLSTENCILMASKPROC) (GLuint mask); //typedef void (APIENTRYP PFNGLCOLORMASKPROC) (GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); //typedef void (APIENTRYP PFNGLDEPTHMASKPROC) (GLboolean flag); //typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap); extern PFNGLENABLEPROC glEnable; extern PFNGLFINISHPROC glFinish; //typedef void (APIENTRYP PFNGLFLUSHPROC) (void); //typedef void (APIENTRYP PFNGLBLENDFUNCPROC) (GLenum sfactor, GLenum dfactor); //typedef void (APIENTRYP PFNGLLOGICOPPROC) (GLenum opcode); //typedef void (APIENTRYP PFNGLSTENCILFUNCPROC) (GLenum func, GLint ref, GLuint mask); //typedef void (APIENTRYP PFNGLSTENCILOPPROC) (GLenum fail, GLenum zfail, GLenum zpass); //typedef void (APIENTRYP PFNGLDEPTHFUNCPROC) (GLenum func); //typedef void (APIENTRYP PFNGLPIXELSTOREFPROC) (GLenum pname, GLfloat param); //typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param); //typedef void (APIENTRYP PFNGLREADBUFFERPROC) (GLenum src); //typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); //typedef void (APIENTRYP PFNGLGETBOOLEANVPROC) (GLenum pname, GLboolean *data); //typedef void (APIENTRYP PFNGLGETDOUBLEVPROC) (GLenum pname, GLdouble *data); extern PFNGLGETERRORPROC glGetError; //typedef void (APIENTRYP PFNGLGETFLOATVPROC) (GLenum pname, GLfloat *data); extern PFNGLGETINTEGERVPROC glGetIntegerv; extern PFNGLGETSTRINGPROC glGetString; //typedef void (APIENTRYP PFNGLGETTEXIMAGEPROC) (GLenum target, GLint level, GLenum format, GLenum type, void *pixels); //typedef void (APIENTRYP PFNGLGETTEXPARAMETERFVPROC) (GLenum target, GLenum pname, GLfloat *params); //typedef void (APIENTRYP PFNGLGETTEXPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); //typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERFVPROC) (GLenum target, GLint level, GLenum pname, GLfloat *params); //typedef void (APIENTRYP PFNGLGETTEXLEVELPARAMETERIVPROC) (GLenum target, GLint level, GLenum pname, GLint *params); //typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap); //typedef void (APIENTRYP PFNGLDEPTHRANGEPROC) (GLdouble n, GLdouble f); extern PFNGLVIEWPORTPROC glViewport; // // GL_VERSION_1_1 // //typedef void (APIENTRYP PFNGLDRAWARRAYSPROC) (GLenum mode, GLint first, GLsizei count); extern PFNGLDRAWELEMENTSPROC glDrawElements; //typedef void (APIENTRYP PFNGLGETPOINTERVPROC) (GLenum pname, void **params); //typedef void (APIENTRYP PFNGLPOLYGONOFFSETPROC) (GLfloat factor, GLfloat units); //typedef void (APIENTRYP PFNGLCOPYTEXIMAGE1DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLint border); //typedef void (APIENTRYP PFNGLCOPYTEXIMAGE2DPROC) (GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); //typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); //typedef void (APIENTRYP PFNGLCOPYTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); //typedef void (APIENTRYP PFNGLTEXSUBIMAGE1DPROC) (GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const void *pixels); //typedef void (APIENTRYP PFNGLTEXSUBIMAGE2DPROC) (GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); //typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture); //typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures); //typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures); //typedef GLboolean (APIENTRYP PFNGLISTEXTUREPROC) (GLuint texture); // // GL_VERSION_1_5 // //typedef void (APIENTRYP PFNGLGENQUERIESPROC) (GLsizei n, GLuint *ids); //typedef void (APIENTRYP PFNGLDELETEQUERIESPROC) (GLsizei n, const GLuint *ids); //typedef GLboolean (APIENTRYP PFNGLISQUERYPROC) (GLuint id); //typedef void (APIENTRYP PFNGLBEGINQUERYPROC) (GLenum target, GLuint id); //typedef void (APIENTRYP PFNGLENDQUERYPROC) (GLenum target); //typedef void (APIENTRYP PFNGLGETQUERYIVPROC) (GLenum target, GLenum pname, GLint *params); //typedef void (APIENTRYP PFNGLGETQUERYOBJECTIVPROC) (GLuint id, GLenum pname, GLint *params); //typedef void (APIENTRYP PFNGLGETQUERYOBJECTUIVPROC) (GLuint id, GLenum pname, GLuint *params); //extern PFNGLBINDBUFFERPROC glBindBuffer; //extern PFNGLDELETEBUFFERSPROC glDeleteBuffers; //extern PFNGLGENBUFFERSPROC glGenBuffers; //typedef GLboolean (APIENTRYP PFNGLISBUFFERPROC) (GLuint buffer); //typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage); //typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data); //typedef void (APIENTRYP PFNGLGETBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, void *data); //typedef void *(APIENTRYP PFNGLMAPBUFFERPROC) (GLenum target, GLenum access); //typedef GLboolean (APIENTRYP PFNGLUNMAPBUFFERPROC) (GLenum target); //typedef void (APIENTRYP PFNGLGETBUFFERPARAMETERIVPROC) (GLenum target, GLenum pname, GLint *params); //typedef void (APIENTRYP PFNGLGETBUFFERPOINTERVPROC) (GLenum target, GLenum pname, void **params); // // GL_VERSION_2_0 // //typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha); //typedef void (APIENTRYP PFNGLDRAWBUFFERSPROC) (GLsizei n, const GLenum *bufs); //typedef void (APIENTRYP PFNGLSTENCILOPSEPARATEPROC) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); //typedef void (APIENTRYP PFNGLSTENCILFUNCSEPARATEPROC) (GLenum face, GLenum func, GLint ref, GLuint mask); //typedef void (APIENTRYP PFNGLSTENCILMASKSEPARATEPROC) (GLenum face, GLuint mask); //extern PFNGLATTACHSHADERPROC glAttachShader; //typedef void (APIENTRYP PFNGLBINDATTRIBLOCATIONPROC) (GLuint program, GLuint index, const GLchar *name); //extern PFNGLCOMPILESHADERPROC glCompileShader; //extern PFNGLCREATEPROGRAMPROC glCreateProgram; //extern PFNGLCREATESHADERPROC glCreateShader; //extern PFNGLDELETEPROGRAMPROC glDeleteProgram; //extern PFNGLDELETESHADERPROC glDeleteShader; //typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader); //typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index); //typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index); //typedef void (APIENTRYP PFNGLGETACTIVEATTRIBPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); //typedef void (APIENTRYP PFNGLGETACTIVEUNIFORMPROC) (GLuint program, GLuint index, GLsizei bufSize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); //typedef void (APIENTRYP PFNGLGETATTACHEDSHADERSPROC) (GLuint program, GLsizei maxCount, GLsizei *count, GLuint *shaders); //extern PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; //extern PFNGLGETPROGRAMIVPROC glGetProgramiv; //extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; //extern PFNGLGETSHADERIVPROC glGetShaderiv; //extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; //typedef void (APIENTRYP PFNGLGETSHADERSOURCEPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *source); //extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; //typedef void (APIENTRYP PFNGLGETUNIFORMFVPROC) (GLuint program, GLint location, GLfloat *params); //typedef void (APIENTRYP PFNGLGETUNIFORMIVPROC) (GLuint program, GLint location, GLint *params); //typedef void (APIENTRYP PFNGLGETVERTEXATTRIBDVPROC) (GLuint index, GLenum pname, GLdouble *params); //typedef void (APIENTRYP PFNGLGETVERTEXATTRIBFVPROC) (GLuint index, GLenum pname, GLfloat *params); //typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params); //typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer); //typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program); //typedef GLboolean (APIENTRYP PFNGLISSHADERPROC) (GLuint shader); //extern PFNGLLINKPROGRAMPROC glLinkProgram; //extern PFNGLSHADERSOURCEPROC glShaderSource; //extern PFNGLUSEPROGRAMPROC glUseProgram; //typedef void (APIENTRYP PFNGLUNIFORM1FPROC) (GLint location, GLfloat v0); //typedef void (APIENTRYP PFNGLUNIFORM2FPROC) (GLint location, GLfloat v0, GLfloat v1); //typedef void (APIENTRYP PFNGLUNIFORM3FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2); //typedef void (APIENTRYP PFNGLUNIFORM4FPROC) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); //typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0); //typedef void (APIENTRYP PFNGLUNIFORM2IPROC) (GLint location, GLint v0, GLint v1); //typedef void (APIENTRYP PFNGLUNIFORM3IPROC) (GLint location, GLint v0, GLint v1, GLint v2); //typedef void (APIENTRYP PFNGLUNIFORM4IPROC) (GLint location, GLint v0, GLint v1, GLint v2, GLint v3); //typedef void (APIENTRYP PFNGLUNIFORM1FVPROC) (GLint location, GLsizei count, const GLfloat *value); //typedef void (APIENTRYP PFNGLUNIFORM2FVPROC) (GLint location, GLsizei count, const GLfloat *value); //typedef void (APIENTRYP PFNGLUNIFORM3FVPROC) (GLint location, GLsizei count, const GLfloat *value); //typedef void (APIENTRYP PFNGLUNIFORM4FVPROC) (GLint location, GLsizei count, const GLfloat *value); //typedef void (APIENTRYP PFNGLUNIFORM1IVPROC) (GLint location, GLsizei count, const GLint *value); //typedef void (APIENTRYP PFNGLUNIFORM2IVPROC) (GLint location, GLsizei count, const GLint *value); //typedef void (APIENTRYP PFNGLUNIFORM3IVPROC) (GLint location, GLsizei count, const GLint *value); //typedef void (APIENTRYP PFNGLUNIFORM4IVPROC) (GLint location, GLsizei count, const GLint *value); //typedef void (APIENTRYP PFNGLUNIFORMMATRIX2FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); //typedef void (APIENTRYP PFNGLUNIFORMMATRIX3FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); //typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); //typedef void (APIENTRYP PFNGLVALIDATEPROGRAMPROC) (GLuint program); //typedef void (APIENTRYP PFNGLVERTEXATTRIB1DPROC) (GLuint index, GLdouble x); //typedef void (APIENTRYP PFNGLVERTEXATTRIB1DVPROC) (GLuint index, const GLdouble *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB1FPROC) (GLuint index, GLfloat x); //typedef void (APIENTRYP PFNGLVERTEXATTRIB1FVPROC) (GLuint index, const GLfloat *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB1SPROC) (GLuint index, GLshort x); //typedef void (APIENTRYP PFNGLVERTEXATTRIB1SVPROC) (GLuint index, const GLshort *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB2DPROC) (GLuint index, GLdouble x, GLdouble y); //typedef void (APIENTRYP PFNGLVERTEXATTRIB2DVPROC) (GLuint index, const GLdouble *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB2FPROC) (GLuint index, GLfloat x, GLfloat y); //typedef void (APIENTRYP PFNGLVERTEXATTRIB2FVPROC) (GLuint index, const GLfloat *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB2SPROC) (GLuint index, GLshort x, GLshort y); //typedef void (APIENTRYP PFNGLVERTEXATTRIB2SVPROC) (GLuint index, const GLshort *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB3DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z); //typedef void (APIENTRYP PFNGLVERTEXATTRIB3DVPROC) (GLuint index, const GLdouble *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB3FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z); //typedef void (APIENTRYP PFNGLVERTEXATTRIB3FVPROC) (GLuint index, const GLfloat *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB3SPROC) (GLuint index, GLshort x, GLshort y, GLshort z); //typedef void (APIENTRYP PFNGLVERTEXATTRIB3SVPROC) (GLuint index, const GLshort *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4NBVPROC) (GLuint index, const GLbyte *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4NIVPROC) (GLuint index, const GLint *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4NSVPROC) (GLuint index, const GLshort *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBPROC) (GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUBVPROC) (GLuint index, const GLubyte *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUIVPROC) (GLuint index, const GLuint *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4NUSVPROC) (GLuint index, const GLushort *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4BVPROC) (GLuint index, const GLbyte *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4DPROC) (GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4DVPROC) (GLuint index, const GLdouble *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4FPROC) (GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4FVPROC) (GLuint index, const GLfloat *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4IVPROC) (GLuint index, const GLint *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4SPROC) (GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4SVPROC) (GLuint index, const GLshort *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4UBVPROC) (GLuint index, const GLubyte *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4UIVPROC) (GLuint index, const GLuint *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIB4USVPROC) (GLuint index, const GLushort *v); //typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer); //--------------------------------------------------------- // VERSION_1_3 //--------------------------------------------------------- //#if !defined(DADA_GL_CORE_VERSION_1_3) && defined(GL_VERSION_1_3) // 26 GL_ARB_vertex_program extern PFNGLDISABLEVERTEXATTRIBARRAYPROC glDisableVertexAttribArray; extern PFNGLENABLEVERTEXATTRIBARRAYPROC glEnableVertexAttribArray; extern PFNGLVERTEXATTRIBPOINTERPROC glVertexAttribPointer; /*// 1 GL_ARB_multitexture // void glActiveTexture(GLenum texture); extern PFNGLACTIVETEXTUREPROC glActiveTexture; // 12 GL_ARB_texture_compression // void glCompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); extern PFNGLCOMPRESSEDTEXIMAGE2DPROC glCompressedTexImage2D; // void glCompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); extern PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glCompressedTexSubImage2D;*/ //#endif // VERSION_1_3 //--------------------------------------------------------- // VERSION_1_5 //--------------------------------------------------------- //#if !defined(DADA_GL_CORE_VERSION_1_5) && defined(GL_VERSION_1_5) extern PFNGLBINDBUFFERPROC glBindBuffer; extern PFNGLBUFFERDATAPROC glBufferData; extern PFNGLBUFFERSUBDATAPROC glBufferSubData; extern PFNGLDELETEBUFFERSPROC glDeleteBuffers; extern PFNGLGENBUFFERSPROC glGenBuffers; extern PFNGLGETBUFFERPARAMETERIVPROC glGetBufferParameteriv; extern PFNGLISBUFFERPROC glIsBuffer; //#endif // VERSION_1_5 //--------------------------------------------------------- // VERSION_2_0 //--------------------------------------------------------- //#if !defined(DADA_GL_CORE_VERSION_2_0) && defined(GL_VERSION_2_0) // 30 GL_ARB_shader_objects extern PFNGLATTACHSHADERPROC glAttachShader; extern PFNGLCOMPILESHADERPROC glCompileShader; extern PFNGLCREATEPROGRAMPROC glCreateProgram; extern PFNGLCREATESHADERPROC glCreateShader; extern PFNGLDELETEPROGRAMPROC glDeleteProgram; extern PFNGLDELETESHADERPROC glDeleteShader; extern PFNGLGETATTRIBLOCATIONPROC glGetAttribLocation; extern PFNGLGETPROGRAMIVPROC glGetProgramiv; extern PFNGLGETPROGRAMINFOLOGPROC glGetProgramInfoLog; extern PFNGLGETSHADERIVPROC glGetShaderiv; extern PFNGLGETSHADERINFOLOGPROC glGetShaderInfoLog; extern PFNGLGETUNIFORMLOCATIONPROC glGetUniformLocation; extern PFNGLLINKPROGRAMPROC glLinkProgram; extern PFNGLSHADERSOURCEPROC glShaderSource; extern PFNGLUNIFORM1IPROC glUniform1i; extern PFNGLUNIFORM1FPROC glUniform1f; extern PFNGLUNIFORM3FVPROC glUniform3fv; extern PFNGLUNIFORM4FVPROC glUniform4fv; extern PFNGLUNIFORMMATRIX4FVPROC glUniformMatrix4fv; extern PFNGLUSEPROGRAMPROC glUseProgram; //#endif // VERSION_2_0 //--------------------------------------------------------- // VERSION_3_0 //--------------------------------------------------------- //#if !defined(DADA_GL_CORE_VERSION_3_0) && defined(GL_VERSION_3_0) extern PFNGLBINDVERTEXARRAYPROC glBindVertexArray; extern PFNGLDELETEVERTEXARRAYSPROC glDeleteVertexArrays; extern PFNGLGENVERTEXARRAYSPROC glGenVertexArrays; //#endif // VERSION_3_0 #endif // DADA_WITH_GLEW namespace dada { class GL { public: enum Extension { ARB_vertex_array_object, EXTENSION_END }; static bool init(); static bool isSupported(Extension ext); private: GL(); GL(const GL&); static bool initCore(); static bool initInfo(); static bool initExtensions(); static int m_major; static int m_minor; static const char* m_vendor; static const char* m_renderer; static const char* m_version; static const char* m_glsl_version; static const char* m_extensions; static bool m_exts[EXTENSION_END]; }; inline bool GL::isSupported(GL::Extension ext) { return m_exts[ext]; } } // dada #endif // DADA_GL_GL_H
void recieveUSB() //USB data receive event function { /* * This function: * 1. Reads data from USB in correct format */ char readChar; String numberStr = ""; int i = 0; while (i < RX_SIZE) //waits to end of message or end of space { readChar = ' '; if (SerialUSB.available()) { readChar = SerialUSB.read(); i++; } if (readChar == END_OF_MESSAGE)break; else if (readChar != ' ') { int ascii = (int)readChar; if ((ascii >= 48 && ascii <= 57) || ascii == 45 ) //if char is 0-9 or minus numberStr += readChar;//connect number parts made from single chars else fromUSB.command = readChar; } } fromUSB.argument = numberStr.toInt(); fromUSB.received = true; } bool waitForRaspberry(int waitTime) { /* * This function: * 1. Waits for Raspberry's confirmation * 2. It returns 0 if Raspberry confirmed action and 1 if not */ int wait = 0; while (wait != waitTime) { if (fromUSB.received && fromUSB.command == "w") { clearDataFromUSB(); return 0;//success } else { wait++; delay(1); } } return 1;//failure } void clearDataFromUSB() { /* * This function: * 1. Clears data from USB */ fromUSB.command = ' '; fromUSB.argument = 0; fromUSB.received = false; } void sendConfirmation(String command, String argument)//confirms execution of command { /* * This function: * 1. Sends confirmaton that the action requested by Raspberry was successful or not */ SerialUSB.println(command); SerialUSB.println(argument); SerialUSB.println(END_OF_MESSAGE); }
#include "stdafx.h" #include "ConvolutionalLayer.h" ConvolutionalLayer::~ConvolutionalLayer() { } /* void ConvolutionalLayer::startTrainingOnButch() { } */ void ConvolutionalLayer::applyWeighChanges() { std::vector<std::pair<double, int>> changes; changes.resize(numInOne); for (int i = 0; i < links.size(); i++) { changes[i%numInOne].first += links[i].totalChange; changes[i%numInOne].second += links[i].countOfChanges; } for (int i = 0; i < links.size(); i++) { links[i].weigh += changes[i%numInOne].first / ((double)changes[i%numInOne].second); } } void ConvolutionalLayer::operator<(NetworkLayer * linked) { srand(time(NULL)); linked->nextLayers.push_back(this); this->prevLayers.push_back(linked); std::vector<double> weighs; weighs.resize(numInOne); for (int i = 0; i < weighs.size(); i++) { double w = ((double)rand()) / (RAND_MAX); w /= (double)numInOne; weighs[i] = w; } int prevSize = linked->neurons.size(); int thisSize = neurons.size(); int offset = (numInOne*thisSize - prevSize) / (thisSize - 1); for (int i = 0; i < thisSize; i++) { for (int j = i*(numInOne - offset); j < i*(numInOne - offset) + numInOne; j++) { links.push_back(Link(&((linked)->neurons[j]), &(neurons[i]), weighs[(j-i*(numInOne - offset))%numInOne])); } } return; }
// Created on: 1997-12-01 // Created by: Jean-Louis Frenkel // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _PCDM_ReferenceIterator_HeaderFile #define _PCDM_ReferenceIterator_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <PCDM_SequenceOfReference.hxx> #include <CDM_MetaDataLookUpTable.hxx> class Message_Messenger; class CDM_Document; class CDM_MetaData; class CDM_Application; class PCDM_ReferenceIterator; DEFINE_STANDARD_HANDLE(PCDM_ReferenceIterator, Standard_Transient) class PCDM_ReferenceIterator : public Standard_Transient { public: //! Warning! The constructor does not initialization. Standard_EXPORT PCDM_ReferenceIterator(const Handle(Message_Messenger)& theMessageDriver); Standard_EXPORT void LoadReferences (const Handle(CDM_Document)& aDocument, const Handle(CDM_MetaData)& aMetaData, const Handle(CDM_Application)& anApplication, const Standard_Boolean UseStorageConfiguration); Standard_EXPORT virtual void Init (const Handle(CDM_MetaData)& aMetaData); DEFINE_STANDARD_RTTIEXT(PCDM_ReferenceIterator,Standard_Transient) protected: private: Standard_EXPORT virtual Standard_Boolean More() const; Standard_EXPORT virtual void Next(); Standard_EXPORT virtual Handle(CDM_MetaData) MetaData (CDM_MetaDataLookUpTable& theLookUpTable, const Standard_Boolean UseStorageConfiguration) const; Standard_EXPORT virtual Standard_Integer ReferenceIdentifier() const; //! returns the version of the document in the reference Standard_EXPORT virtual Standard_Integer DocumentVersion() const; private: PCDM_SequenceOfReference myReferences; Standard_Integer myIterator; Handle(Message_Messenger) myMessageDriver; }; #endif // _PCDM_ReferenceIterator_HeaderFile
/**************************************************************************** * AAMLibrary * http://code.google.com/p/aam-library * Copyright (c) 2008-2009 by GreatYao, all rights reserved. ****************************************************************************/ #include <iostream> #include "AAM_MovieAVI.h" //============================================================================ void AAM_MovieAVI::Open(const char* videofile) { capture = cvCaptureFromAVI(videofile); if(!capture) { fprintf(stderr, "could not open video file %s!\n", videofile); exit(0); } cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, 0); capimg = cvQueryFrame( capture ); image = cvCreateImage(cvGetSize(capimg), capimg->depth, capimg->nChannels); } //============================================================================ void AAM_MovieAVI::Close() { cvReleaseCapture(&capture); capture = 0; cvReleaseImage(&image); image = 0; } //============================================================================ IplImage* AAM_MovieAVI:: ReadFrame(int frame_no ) { cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, frame_no); capimg = cvQueryFrame( capture ); if(capimg->origin == 0) cvCopy(capimg, image); else cvFlip(capimg, image); return image; }
#include "ExerciseEquipment.h" #include "textdisp.h" CExerciseEquipment::CExerciseEquipment(int historyLength) : m_historyLength(historyLength), m_totalTickCount(0) { //Preallocate for historyLength while(m_tickHistoryList.GetListSize() < m_historyLength) { m_tickHistoryList.PushBack(0); } m_listCursor = m_tickHistoryList.GetHeadNode(); } CExerciseEquipment::~CExerciseEquipment() { } void CExerciseEquipment::AddTickPeriod(int tickCount) { m_totalTickCount += tickCount; m_listCursor->SetNodeData(tickCount); m_listCursor = m_listCursor->GetNextNode(); } float CExerciseEquipment::GetVelocity(int tickPeriod) { int listSize = m_tickHistoryList.GetListSize(); if(!listSize || !tickPeriod) return 0; if(tickPeriod > listSize) return ((float)GetTickCount(tickPeriod))/(float)listSize; return ((float)GetTickCount(tickPeriod))/(float)tickPeriod; } int CExerciseEquipment::GetTickCount(int tickPeriod) { int tickCount = 0; int i = 0; int listSize = m_tickHistoryList.GetListSize(); CDLLNode<int>* reverseItr = m_listCursor->GetPrevNode(); for(i=0; i<tickPeriod; ++i) { if(i > listSize) break; tickCount += reverseItr->GetNodeData(); reverseItr = reverseItr->GetPrevNode(); } return tickCount; }
#include "Constant.h" #include <Wire.h> #include <Adafruit_PWMServoDriver.h> // Depending on your servo make, the pulse width min and max may vary, you // want these to be as small/large as possible without hitting the hard stop // for max range. You'll have to tweak them as necessary to match the servos you // have! #define SERVOMIN 1000 // this is the 'minimum' pulse length count (out of 4096) #define SERVOMAX 2000 // this is the 'maximum' pulse length count (out of 4096) uint8_t servonum = 0; void setup() { Serial.begin(115200); Serial.println("Servo test!"); ServoA.begin(); ServoA.setPWMFreq(60); // Analog servos run at ~60 Hz updates ServoB.begin(); ServoB.setPWMFreq(60); // Analog servos run at ~60 Hz updates Wire.setClock(400000); setAllServoPulse(1500); } int i = 5; int tmp = 1000; void loop() { // setAllServoPulse(tmp); // tmp += i; // delay(20); // if (tmp > 2000 || tmp < 1000) i = -i; }
#include "GameLayer.h" GameLayer::GameLayer(WindowRef window) { setWindow(window); } GameLayer::GameLayer(sf::Vector2<float> translation) { this->translation = translation; } void GameLayer::drawLayer() { for (GameObject* i : objects) { i->update(); } } void GameLayer::add(GameObject& item) { //std::cout << "tick"; objects.push_back(&item); item.setLayer(*this); } void GameLayer::setWindow(WindowRef window) { this->window = window; } void GameLayer::shiftTranslation(sf::Vector2<float> shift) { translation += shift; }
#pragma once #include "ICommand.h" #include <iostream> #include <fstream> class Sort : public ICommand { private: std::string word; public: Sort() {} Sort(std::string args) {} std::string execute(std::string & text) override; };
//By SCJ //#include<iostream> #include<bits/stdc++.h> using namespace std; #define endl '\n' int main() { ios::sync_with_stdio(0); cin.tie(0); string s; bool fg=0; while(getline(cin,s)) { for(int i=0;i<s.size();++i) { if(s[i]=='"') { if(fg==0) cout<<"``"; else cout<<"''"; fg^=1; } else cout<<s[i]; } cout<<endl; } }
/* * Copyright 2019 LogMeIn * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #include <cassert> #include "asyncly/task/detail/PeriodicTask.h" namespace asyncly { namespace detail { std::shared_ptr<Cancelable> PeriodicTask::create( const clock_type::duration& period, CopyableTask task, const IExecutorPtr& executor) { if (task == nullptr) { throw std::runtime_error("invalid task"); } auto periodicTask = std::make_shared<PeriodicTask>(period, std::move(task), executor, PeriodicTask::Token{}); periodicTask->scheduleTask_(); return periodicTask; } PeriodicTask::PeriodicTask( const clock_type::duration& period, CopyableTask task, const IExecutorPtr& executor, PeriodicTask::Token) : period_(period) , task_(std::move(task)) , executor_(executor) , cancelled_(false) , expiry_(executor->now()) { } void PeriodicTask::cancel() { std::lock_guard<std::mutex> lock{ mutex_ }; cancel_(); } void PeriodicTask::scheduleTask_() { expiry_ += period_; if (auto executor = executor_.lock()) { currentDelayedTask_ = executor->post_at(expiry_, [self = shared_from_this()]() { self->onTimer_(); }); } } void PeriodicTask::cancel_() { if (cancelled_) { return; } cancelled_ = true; cancelAndClean_(); } void PeriodicTask::onTimer_() { std::lock_guard<std::mutex> lock{ mutex_ }; if (cancelled_) { return; } if (auto executor = executor_.lock()) { executor->post([self = shared_from_this()]() { self->execute(); }); } scheduleTask_(); } void PeriodicTask::cancelAndClean_() { if (currentDelayedTask_) { currentDelayedTask_->cancel(); } currentDelayedTask_.reset(); task_ = nullptr; } void PeriodicTask::execute() { if (cancelled_) { return; } task_(); } } // detail namespace } // executor namespace
#include "ShoeMessageWifiPosition.hpp" #include <QDateTime> #include <QDebug> #include <QJsonObject> #include <QJsonDocument> #include <QJsonArray> void ShoeMessageWifiPosition::parseData(QByteArray data) { /* wifi/lbs eg. 7878 03 69 160413031849 1475905BD30E25 001E10BBF7635D 14759006E62656 05 01CC00 28660F2132 28660F1F28 28660EA81E 2866107314 28660F2014 0D0A 03 69 160413031849 1475905BD30E25 001E10BBF7635D 14759006E62656 05 01CC00 28660F2132 28660F1F28 28660EA81E 2866107314 28660F2014 lbs eg. 7878 00 69 160413031849 05 01CC00 28660F2132 28660F1F28 28660EA81E 2866107314 28660F2014 0D0A 00 69 160413031849 05 01CC00 28660F2132 28660F1F28 28660EA81E 2866107314 28660F2014 */ QDataStream in(data); qint8 wifiDataCount = 0; in >> wifiDataCount; qint8 protocalNo = 0x69; in >> protocalNo; in >> dateTime; for(int i=0; i<wifiDataCount; i++) { WifiData wifiData; in >> wifiData; wifiDataList.append(wifiData); } qint8 lbsDataCount = 0; in >> lbsDataCount; if(lbsDataCount > 0) { in >> mccnc; for(int i=0; i<lbsDataCount; i++) { LBSData lbsData; in >> lbsData; lbsDataList.append(lbsData); } } } QString ShoeMessageWifiPosition::jsonString() { QJsonDocument doc(getObject()); return doc.toJson(QJsonDocument::Indented); } QJsonObject ShoeMessageWifiPosition::getObject() { QJsonObject objectWifiPosition; // 1 objectWifiPosition.insert("dateTime", dateTime.dateTime); // 2 QJsonObject mccncObject; mccncObject.insert("mcc", mccnc.mcc); mccncObject.insert("mnc", mccnc.mnc); objectWifiPosition.insert("mccnc", mccncObject); // 3 QJsonArray wifiDataArray; for(int i=0; i<wifiDataList.count(); i++) { WifiData wifiData = wifiDataList[i]; QJsonObject wifiItem; wifiItem.insert("bssid", wifiData.bssid); wifiItem.insert("rssi", wifiData.rssi); wifiDataArray.append(wifiItem); } objectWifiPosition.insert("wifi", wifiDataArray); // 4 QJsonArray lbsDataArray; for(int i=0; i<lbsDataList.count(); i++) { LBSData lbsData = lbsDataList[i]; QJsonObject lbsItem; lbsItem.insert("lac", lbsData.lac); lbsItem.insert("mciss", lbsData.mciss); lbsItem.insert("cellid", lbsData.cellid); lbsDataArray.append(lbsItem); } objectWifiPosition.insert("lbs", lbsDataArray); return objectWifiPosition; } QDataStream &operator>>(QDataStream &in, WifiData &data) { // 1475905BD30E25 前面 6byte 为 bssid,后面 1byte 为 rssi QByteArray bssid; for(int i=0; i<6; i++) { qint8 temp; in >> temp; bssid.append(temp); } data.bssid = bssid.toHex(); QByteArray rssi; for(int i=0; i<1; i++) { qint8 temp; in >> temp; rssi.append(temp); } data.rssi = rssi.toHex(); return in; } QDataStream &operator>>(QDataStream &in, LBSData &data) { /* lac 2byte ; cellid 2byte; mciss 1byte * 2866 0F21 32 lac 10342 ; cellid 3873 ; mciss 50 */ QByteArray lac; for(int i=0; i<2; i++) { qint8 temp; in >> temp; lac.append(temp); } data.lac = lac.toHex(); QByteArray cellid; for(int i=0; i<2; i++) { qint8 temp; in >> temp; cellid.append(temp); } data.cellid = cellid.toHex(); QByteArray mciss; for(int i=0; i<1; i++) { qint8 temp; in >> temp; mciss.append(temp); } data.mciss = mciss.toHex(); return in; } QDataStream &operator>>(QDataStream &in, MCCMNC &data) { /* * http://blog.chinaunix.net/uid-20484604-id-1941290.html * MCC: Mobile Country Code,移动国家码,MCC的资源由国际电联(ITU)统一分配和管理,唯一识别移动用户所属的国家,共3位,中国为460; * MNC: Mobile Network Code,移动网络码,共2位,中国移动TD系统使用00,中国联通GSM系统使用01,中国移动GSM系统使用02,中国电信CDMA系统使用03 */ // 01CC 00 为 460(mcc) 0(mnc) qint8 byte1, byte2, byte3; in >> byte1 >>byte2 >>byte3; QByteArray mccByteArray; mccByteArray.append(byte1); mccByteArray.append(byte2); QString mccString = mccByteArray.toHex(); data.mcc = QString::number(mccString.toInt(0,16)); data.mnc = QString::number(byte3); return in; } QDataStream &operator>>(QDataStream &in, BCDDateTime &data) { // 16 04 13 03 18 49 QByteArray dateTimeByteArray; for(int i=0; i<6; i++) { qint8 temp; in >> temp; dateTimeByteArray.append(temp); } QString dateTimeString = "20"; dateTimeString += dateTimeByteArray.toHex(); QDateTime dateTime = QDateTime::fromString(dateTimeString, "yyyyMMddhhmmss"); if(dateTime.isValid()) data.dateTime = dateTime.toString("yyyyMMddhhmmss"); else data.dateTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmss"); return in; }
#ifndef BSTREE_HPP #define BSTREE_HPP 1 #include "BinaryTree.hpp" namespace cs202 { template <class Key, class Value> class BSTree : public BinaryTree<Key, Value> { /* Inherit as many functions as possible from BinaryTree. * Only override those where you can decrease the time complexity and where you absolutely need to do it. * Also make sure that all inherited functions work correctly in the context of a binary search tree. */ private: int max(const int& a, const int&b) { return a > b ? a : b; } protected: virtual int height_under_node(BinaryNode<Key, Value>* node) { if (node) return 1 + max(height_under_node(node->right), height_under_node(node->left)); else return 0; } virtual int size_under_node(BinaryNode<Key, Value>* node) { if (node) { return 1 + size_under_node(node->left) + size_under_node(node->right); } else { return 0; } } virtual BinaryNode<Key, Value>* has_child_with_key(BinaryNode<Key, Value>* node, Key k) override { if (node->key == k) { return node; } else if (k < node->key) { if (node->left) { return has_child_with_key(node->left, k); } else { return nullptr; } } else if (k > node->key) { if (node->right) { return has_child_with_key(node->right, k); } else { return nullptr; } } else { return nullptr; // This really shouldn't happen btw } } // Returns the newly inserted node virtual BinaryNode<Key, Value>* put_under_node(BinaryNode<Key, Value>* node, const Key& key, const Value& value) { if (key == node->key) { node->val = value; return node; } else if (key > node->key) { if (node->right) { return put_under_node(node->right, key, value); } else { node->right = new BinaryNode<Key, Value> (key, value, this->root, node); return node->right; } } else if (key < node->key) { if (node->left) { return put_under_node(node->left, key, value); } else { node->left = new BinaryNode<Key, Value> (key, value, this->root, node); return node->left; } } else { return nullptr; // something has gone wrong if this happens } } virtual Key find_descendant_with_min_key(BinaryNode<Key, Value>* node) override { Key min = node->key; if (node->left) { min = find_descendant_with_min_key(node->left); } return min; } virtual Key find_descendant_with_max_key(BinaryNode<Key, Value>* node) override { Key max = node->key; if (node->right) { max = find_descendant_with_max_key(node->right); } return max; } virtual BinaryNode<Key, Value>* find_descendant_just_larger_than_key(BinaryNode<Key, Value>* node, Key key) override { BinaryNode<Key, Value>* successor = nullptr; BinaryNode<Key, Value>* current = has_child_with_key(this->root, key); if (!current) { throw std::invalid_argument("Can't find successor to key that doesn't exist."); } if (current->right) { auto temp = current->right; while (temp->left) temp = temp->left; successor = temp; } else { auto temp = current; while (temp->parent && temp->parent->left != temp) { temp = temp->parent; } successor = temp->parent; } return successor; } virtual BinaryNode<Key, Value>* find_descendant_just_smaller_than_key(BinaryNode<Key, Value>* node, Key key) override { BinaryNode<Key, Value>* predecessor = nullptr; BinaryNode<Key, Value>* current = has_child_with_key(this->root, key); if (!current) { throw std::invalid_argument("Can't find successor to key that doesn't exist."); } if (current->left) { auto temp = current->left; while (temp->right) temp = temp->right; predecessor = temp; } else { auto temp = current; while (temp->parent && temp->parent->right != temp) { temp = temp->parent; } predecessor = temp->parent; } return predecessor; } public: virtual void put(const Key& key, const Value& value) override { if (!this->root) { this->root = new BinaryNode<Key, Value> (key, value, nullptr, nullptr); this->root->root = this->root; } else { put_under_node(this->root, key, value); } } virtual void remove(const Key& key) override { auto node_to_remove = has_child_with_key(this->root, key); if (!node_to_remove) { throw std::runtime_error("Can't remove a nonexisting key"); } if (!node_to_remove->left && !node_to_remove->right) { // node is leaf if (node_to_remove->parent) { if (node_to_remove->parent->left == node_to_remove) { node_to_remove->parent->left = nullptr; } else if (node_to_remove->parent->right == node_to_remove) { node_to_remove->parent->right = nullptr; } } else { // node_to_remove must be the root this->root = nullptr; } delete node_to_remove; } else if (node_to_remove->left && node_to_remove->right) { // node has two children auto successor = find_descendant_just_larger_than_key(this->root, node_to_remove->key); node_to_remove->key = successor->key; node_to_remove->val = successor->val; if (successor->parent->left == successor) { successor->parent->left = nullptr; } else { successor->parent->right = nullptr; } delete successor; } else { // node has one child BinaryNode<Key, Value>* child; if (node_to_remove->left) { child = node_to_remove->left; } else { child = node_to_remove->right; } if (node_to_remove->parent) { if (node_to_remove->parent->left == node_to_remove) { node_to_remove->parent->left = child; } else { node_to_remove->parent->right = child; } } else { this->root = child; child->root = child; } delete node_to_remove; } } /* * This method returns the current height of the binary search tree. */ virtual int getHeight() { // TODO implement return height_under_node(this->root); } /* * This method returns the total number of elements in the binary search tree. */ virtual int size() { // TODO implement return size_under_node(this->root); } /* * This method prints the key value pairs of the binary search tree, sorted by * their keys. */ virtual void print() { this->print_in_order(); } }; } #endif /* ifndef BSTREE_HPP */
/********************************************************************** * Polly Scop Profiler Runtime * Copyright (C) 2018 Dominik Adamski * * 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 3 of the License, or * 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, see <http://www.gnu.org/licenses/>. ***********************************************************************/ #include "DatabaseProxy.h" #include "DatabaseManager.h" extern "C" int64_t register_new_scop(uint64_t hashID, const char *scopName) { return DatabaseManager::registerNewScop(hashID, scopName); } extern "C" int64_t set_scop_params(int64_t generalInfoID, int64_t maxLoopDepth, int64_t instructionNumber, int64_t memoryAccess, int64_t readMemoryAccess, int64_t indvarNumber, int64_t scopSize, int64_t sumOfCoeff, int64_t sumOfOffsets, uint64_t *upperPartScopID, uint64_t *lowerPartScopID) { return DatabaseManager::setScopParams( generalInfoID, maxLoopDepth, instructionNumber, memoryAccess, readMemoryAccess, indvarNumber, scopSize, sumOfCoeff, sumOfOffsets, upperPartScopID, lowerPartScopID); } extern "C" int64_t set_scop_loops_params(uint64_t upperPartScopID, uint64_t lowerPartScopID, int64_t paramsNumber, ...) { const int numberParamsTypes = 3; int64_t loopsNumber = paramsNumber / numberParamsTypes; std::vector<int64_t> loopsRange = std::vector<int64_t>(loopsNumber); std::vector<int64_t> loopsDepth = std::vector<int64_t>(loopsNumber); std::vector<int64_t> loopsInstructionNumber = std::vector<int64_t>(loopsNumber); va_list paramsList; va_start(paramsList, paramsNumber); for (int64_t i = 0; i < loopsNumber; i++) { loopsRange[i] = va_arg(paramsList, int); loopsDepth[i] = va_arg(paramsList, int); loopsInstructionNumber[i] = va_arg(paramsList, int); } va_end(paramsList); return DatabaseManager::setScopLoopsParams( upperPartScopID, lowerPartScopID, loopsNumber, loopsRange, loopsDepth, loopsInstructionNumber); } extern "C" int64_t start_scop_profiling(uint64_t upperPartScopID, uint64_t lowerPartScopID) { return DatabaseManager::startScopProfiling(upperPartScopID, lowerPartScopID); }
#include "CookieJar.h" #include <QDebug> #include <QNetworkCookie> #include <QElapsedTimer> namespace wpp { namespace qt { CookieJar::CookieJar(LocalStorage &localStorage) : localStorage(localStorage) { } QList<QNetworkCookie> CookieJar::cookiesForUrl(const QUrl & url) const { //return cookies for attaching to the request header // qDebug() << "CookieJar::cookiesForUrl(): url:" << url; qDebug() << "Calling CookieJar::cookiesForUrl() url=" << url; QElapsedTimer timer; timer.start(); QList<QNetworkCookie> cookies = localStorage.getCookies(); qint64 nanoSec = timer.nsecsElapsed(); qDebug() << "get cookies spent(nano-sec):" << nanoSec; timer.restart(); QListIterator<QNetworkCookie> it(cookies); while ( it.hasNext() ) { QNetworkCookie cookie = it.next(); qDebug() << QString("CookieJar::cookiesForUrl(): Cookie: %1 => %2") .arg(QString(cookie.name())) .arg(QString(cookie.value())); } nanoSec = timer.nsecsElapsed(); qDebug() << "get cookies2 spent(nano-sec):" << nanoSec; return cookies; } bool CookieJar::setCookiesFromUrl(const QList<QNetworkCookie> & cookieList, const QUrl& ) { //save cookies extracted from the response header /* qDebug() << "CookieJar::setCookiesFromUrl(): url:" << url; qDebug() << "CookieJar::setCookiesFromUrl(): cookieList:"; QListIterator<QNetworkCookie> it(cookieList); while ( it.hasNext() ) { QNetworkCookie cookie = it.next(); qDebug() << "Cookie: " << cookie.name() << " => " << cookie.value(); //lstorage->setCookie(cookie.name(), cookie.value()); }*/ localStorage.setCookies(cookieList); qDebug() << "After CookieJar::setCookiesFromUrl(), sqlite:..."; localStorage.dumpDB(); return true; } }//namespace qt }//namespace wpp
#include <bits/stdc++.h> using namespace std ; const int N = (int)2e6 + 5 ; int L[N] ; int R[N] ; int T[N] ; int version ; int root[N] ; int src[N] ; int pos[N] ; void build(int i, int b, int e) { if (b == e) { T[i] = 0 ; return ; } L[i] = ++version ; R[i] = ++version ; int mid = (b + e) >> 1 ; build(L[i], b, mid) ; build(R[i], mid + 1, e) ; } int update(int i, int b, int e, int pos) { if (b > pos or e < pos)return i ; int cur = ++version ; if (b == e) { T[cur] = T[i] + 1 ; return cur ; } int mid = (b + e) >> 1 ; L[cur] = update(L[i], b, mid, pos) ; R[cur] = update(R[i], mid + 1, e, pos) ; T[cur] = T[L[cur]] + T[R[cur]] ; return cur ; } int query(int i, int j, int b, int e, int l) { if (b >= l)return 0 ; if (e < l)return T[i] - T[j] ; int mid = (b + e) >> 1 ; return query(L[i], L[j], b, mid, l) + query(R[i], R[j], mid + 1, e, l) ; } int main() { //cout << N * 4 * LogN<< '\n' ; int test = 1, tc = 0; scanf("%d", &test) ; while (test--) { int n, q ; scanf("%d%d", &n, &q) ; memset(L, 0, sizeof L) ; memset(R, 0, sizeof R) ; memset(T, 0, sizeof T) ; memset(root, 0, sizeof root) ; memset(pos, 0, sizeof pos) ; version = 0 ; int cnt = 0 ; root[0] = 0 ; build(0, 0, n) ; for (int i = 1 ; i <= n ; ++i) { int x ; scanf("%d", &x) ; int k = pos[x] ; root[i] = update(root[i - 1], 0, n, k) ; pos[x] = i ; } printf("Case %d:\n", ++tc); while (q--) { int l, r ; scanf("%d %d", &l, &r) ; int res = query(root[r], root[l - 1], 0, n, l) ; printf("%d\n", res); } } return 0 ; }
#include "Scheme_values/Atom.hpp" #include "Environment.hpp" #include "Scheme_values/Scheme_value.hpp" #include "fmt/format.h" Symbol::Symbol(const std::string& atom) : name(atom) { } std::string Symbol::as_string() const { return name; }
#ifndef ZOMBIE3_H #define ZOMBIE3_H #include <QImage> #include <QRect> #include "zombie.h" class Zombie3:public Zombie { public: Zombie3(); ~Zombie3(); public: void resetState();//spawn location void autoMove(); //handles automatic movement }; #endif
#include<bits/stdc++.h> #define f(i,n) for(int i=0;i<n;i++) #define fr(i,n) for(int i=1;i<=n;i++) #define py printf("YES\n") #define pn printf("NO\n") #define pb push_back #define ll long long #define speed ios_base::sync_with_stdio(false); cin.tie(NUll);cout.tie(NUll); #define D(x) cout << #x " = " << (x) << endl #define endl "\n" #define t(tt,val) printf("Case %d: %d\n",tt,val) #define INF INT_MAX #define MAXN 50000000 using namespace std; const double eps = 1e-8; int a[1000]; void init(){ f(i,105) a[i]=i; } int find(int x) { if(x==a[x]) return x; else return a[x]=find(a[x]); } int unio(int x,int y) { int c=find(x); int d=find(y); if(c!=d) a[c]=d; } int main(void) { int t; cin>>t; fr(i,t) { vector< pair < int , pair< int , int > > >edges; int n,x,y,w,k=2; cin>>n; while(1) { cin>>x>>y>>w; if(x==0&&y==0&&w==0) break; edges.pb(make_pair(w,make_pair(x,y))); } init(); sort(edges.begin(),edges.end()); ll weight1=0,ni=0,ed=0; for(int j=0;j<edges.size();j++) { int a=edges[j].second.first; int b=edges[j].second.second; int c=edges[j].first; if(find(a)!=find(b)) { unio(a,b); weight1+=c;ed++; } ni++; } ll weight2=0; reverse(edges.begin(),edges.end()); init(); for(int j=0;j<edges.size();j++) { int a=edges[j].second.first; int b=edges[j].second.second; int c=edges[j].first; if(find(a)!=find(b)) { unio(a,b); weight2+=c;ed++; } ni++; } if((weight1+weight2)%2==0) printf("Case %d: %lld\n",i,(weight1+weight2)/2); else printf("Case %d: %lld/%d\n",i,weight1+weight2,k); } return 0; }
// stdafx.cpp : 只包括标准包含文件的源文件 // Week1-ex-1.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
// Copyright 2012 Yandex #ifndef LTR_LEARNERS_DECISION_TREE_UTILITY_UTILITY_H_ #define LTR_LEARNERS_DECISION_TREE_UTILITY_UTILITY_H_ #include <vector> #include <string> #include "ltr/data/data_set.h" #include "ltr/learners/decision_tree/condition.h" using std::string; namespace ltr { namespace decision_tree { void split(DataSet<Object> data, std::vector<Condition::Ptr> conditions, std::vector<DataSet<Object> >* datas); /** * Function returns the string name of the given class */ template<class T> string ClassName(); }; }; #endif // LTR_LEARNERS_DECISION_TREE_UTILITY_UTILITY_H_
#include "StdAfx.h" #include "GcPropertyGridFloatSpinProperty.h" #include "GcFloatSpinButtonCtrl.h" #define AFX_PROP_HAS_LIST 0x0001 #define AFX_PROP_HAS_BUTTON 0x0002 #define AFX_PROP_HAS_SPIN 0x0004 GcPropertyGridFloatSpinProperty::GcPropertyGridFloatSpinProperty(const CString& strGroupName, DWORD_PTR dwData, BOOL bIsValueList) : GcPropertyGridProperty(strGroupName, dwData, bIsValueList), mAccumulateDelta(0.0f) { } GcPropertyGridFloatSpinProperty::GcPropertyGridFloatSpinProperty(const CString& strName, const COleVariant& varValue, LPCTSTR lpszDescr, DWORD_PTR dwData, LPCTSTR lpszEditMask, LPCTSTR lpszEditTemplate, LPCTSTR lpszValidChars) : GcPropertyGridProperty(strName, varValue, lpszDescr, dwData, lpszEditMask, lpszEditTemplate, lpszValidChars), mFloatVlaue((float)dwData) { } GcPropertyGridFloatSpinProperty::~GcPropertyGridFloatSpinProperty(void) { } void GcPropertyGridFloatSpinProperty::EnableFloatSpinControl(bool bEnable, int iMin, int iMax) { switch (m_varValue.vt) { case VT_R4: case VT_R8: break; default: GnAssert(FALSE); return; } m_nMinValue = iMin; m_nMaxValue = iMax; if (bEnable) { m_dwFlags |= AFX_PROP_HAS_SPIN; } else { m_dwFlags &= ~AFX_PROP_HAS_SPIN; } } CSpinButtonCtrl* GcPropertyGridFloatSpinProperty::CreateSpinControl(CRect rectSpin) { ASSERT_VALID(this); ASSERT_VALID(m_pWndList); CSpinButtonCtrl* pWndSpin = new GcFloatSpinButtonCtrl; if (!pWndSpin->Create(WS_CHILD | WS_VISIBLE | UDS_ARROWKEYS | UDS_NOTHOUSANDS , rectSpin, m_pWndList, AFX_PROPLIST_ID_INPLACE)) { return NULL; } pWndSpin->SetBuddy(m_pWndInPlace); if (m_nMinValue != 0 || m_nMaxValue != 0) { pWndSpin->SetRange32(m_nMinValue, m_nMaxValue); } return pWndSpin; } BOOL GcPropertyGridFloatSpinProperty::OnUpdateValue() { const float minDelta = 0.0009f; ASSERT_VALID(this); ASSERT_VALID(m_pWndInPlace); ASSERT_VALID(m_pWndList); ASSERT(::IsWindow(m_pWndInPlace->GetSafeHwnd())); CString strText; m_pWndInPlace->GetWindowText(strText); GcFloatSpinButtonCtrl*spin = (GcFloatSpinButtonCtrl*)m_pWndSpin; float delta = spin->GetDelta(); if( delta > minDelta || delta < -minDelta) { mAccumulateDelta += delta; float val = 0.0f; _stscanf_s(strText, m_strFormatFloat, &val); val += delta; if( val <= 0.f ) val = 0.0f; strText.Format(m_strFormatFloat, val); m_pWndInPlace->SetWindowText(strText); } if( TextToVar(strText) || delta > minDelta || delta < -minDelta) { m_pWndList->OnPropertyChanged(this); } spin->SetDelta(0.f); return TRUE; } BOOL GcPropertyGridFloatSpinProperty::OnEndEdit() { float* val; switch (m_varValue.vt) { case VT_R4: val = &m_varValue.fltVal; break; case VT_R8: val = (float*)&m_varValue.dblVal; default: GnAssert(FALSE); return false; } if( *val <= 0.0f ) { *val = 0.0f; } if( CMFCPropertyGridProperty::OnEndEdit() == false ) return false; mAccumulateDelta = 0.0f; return true; }
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e17 // 4倍しても(4回足しても)long longを溢れない #define rep(i,n) for(int i=0; i<n; i++) #define rep_r(i,n,m) for(int i=m; i<n; i++) #define END cout << endl #define MOD 1000000007 #define pb push_back #define sorti(x) sort(x.begin(), x.end()) #define sortd(x) sort(x.begin(), x.end(), std::greater<int>()) ll dp[100010]; int n,k; int main() { cin >> n >> k; vector<ll> h(n); rep(i,n) cin >> h[i]; dp[0] = 0; // loop for (int i = 1; i < n; ++i) { dp[i] = INF; for (int s = 1; s <= k; ++s) { if (i - s >= 0) { dp[i] = min(dp[i], dp[i - s] + abs(h[i] - h[i - s])); } else { break; } } } cout << dp[n-1] << endl; }
// Functions.hpp // MakeVector // Created by Quincy Copeland on 9/10/18. // Copyright © 2018 Quincy Copeland. All rights reserved. #ifndef Functions_hpp #define Functions_hpp #include <stdio.h> #include <vector> #include <iostream> #include <algorithm> using namespace std; template <typename T> class myVector { private: T *arr; int capacity; int size; public: myVector (int initialCapacity) { cout << "Constructor" << endl; //making sure code is running this functions capacity = initialCapacity; arr = new T[capacity]; size = 0; } T* begin(){return arr;} const T* begin()const {return arr;} T* end() {return arr + size;} const T* end()const {return arr + size;} //copy constructor myVector(const myVector& originalVect) { arr = new T[originalVect.capacity]; for(int i = 0; i < originalVect.size; i++) { arr[i] = originalVect.arr[i]; } capacity = originalVect.capacity; size = originalVect.size; } //push back method void pushBack(T value) { cout << "PushBack" << endl; arr[size] = value; size++; } //pop back method void popBack() { cout << "PopBack" << endl; arr[size] = 0; size--; } //get element at index int getElementValue(int indexValue) { return arr[indexValue]; // not working } //set element value at index void setElementValue(int index, int newVal) { arr[index] = newVal; } //grow vector void growVector() { int *newVector = new int(capacity * 2); // creating new vector for(int i = 0; i <= size - 1; i++) { setElementValue(i, arr[i]); //setting newValue } arr = newVector; capacity *= 2; } //overloaded = operator myVector& operator=(const myVector& rhs) { cout << "Op overloaded" << endl; //making sure code is running this functions capacity = rhs.capacity; arr = rhs.arr; size = rhs.size; return *this; } //return value at index T& operator[](int rhsIndex) { return arr[rhsIndex]; } //sort method void sort() { //selection sort for(int i = 1; i <= size; i++) { T temp = arr[i]; for(int j = i; j < size; j++) { if(temp > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } } ~myVector() { delete []arr; arr = nullptr; capacity = 0; size = 0; } //get size method int getSize() { return size; } //get capacity of vector int getCapacity() { return capacity; } //equal operator bool operator==(myVector& rhs) { if(size != rhs.size) return false; for(int i = 0; i < size; i++) { if(arr[i] != rhs.arr[i]) return false; } return true; } bool operator!=(myVector& rhs) { //return *this == rhs.size; not sure how to return with one line if(*this == rhs) { return false; } return true; } bool operator<(myVector& rhs) { if(size < rhs.size) { return true; } int smallestSize = 0; if(size > rhs.size) { smallestSize = rhs.size; } else { smallestSize = size; } for(int i = 0; i < smallestSize; i++) { if(arr[i] > rhs.arr[i]) { return false; } } return false; } bool operator<=(myVector& rhs) { if(*this > rhs.size) { return false; } return true; } bool operator>=(myVector& rhs) { //return *this < rhs.size; how to return in one line?? if(*this < rhs) { return true; } return false; } bool operator>(myVector& rhs) { return size > rhs.size; // if(size > rhs.size) // { // return true; // } // return false; } }; #endif /* Functions_hpp */
// // Created on 21/01/19. // #pragma once #include <armadillo> namespace Algorithms { class IterativeSVD { public: static void recoveryIterativeSVD(arma::mat &X, uint64_t rank); }; } // namespace Algorithms
#pragma once #include <SFML/Graphics.hpp> class VolumeBar { private: public: };
#ifndef __TABLETOOLBAR_H #define __TABLETOOLBAR_H #include "BaseTable.h" #include "MTable.h" namespace wh{ //----------------------------------------------------------------------------- class VTableToolBar: public wxAuiToolBar ,public ctrlWithResMgr { public: VTableToolBar(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxAUI_TB_DEFAULT_STYLE); void SetModel(std::shared_ptr<ITable> model); void BuildToolBar(); void SetEnableFilter(bool enable = true) { mEnableFilter = enable; } void SetEnableLoad(bool enable = true) { mEnableLoad = enable; } void SetEnableSave(bool enable = true) { mEnableSave = enable; } void SetEnableInsert(bool enable = true) { mEnableInsert = enable; } void SetEnableRemove(bool enable = true) { mEnableRemove = enable; } void SetEnableChange(bool enable = true) { mEnableChange = enable; } bool IsEnableFilter()const { return mEnableFilter; } bool IsEnableLoad()const { return mEnableLoad; } bool IsEnableSave()const { return mEnableSave; } bool IsEnableInsert()const { return mEnableInsert; } bool IsEnableRemove()const { return mEnableRemove; } bool IsEnableChange()const { return mEnableChange; } private: wxStaticText* mPageLabel = nullptr; bool mEnableFilter = true; bool mEnableLoad = true; bool mEnableSave = true; bool mEnableInsert = true; bool mEnableRemove = true; bool mEnableChange = true; void OnTableChange(const IModel& vec); sig::scoped_connection mConnAfterInsert; sig::scoped_connection mConnAfterRemove; sig::scoped_connection mConnAfterChange; void OnAfterInsert(const IModel& vec, const std::vector<SptrIModel>& newItems, const SptrIModel& itemBefore); void OnAfterRemove(const IModel& vec, const std::vector<SptrIModel>& remVec); void OnAfterChange(const IModel& vec, const std::vector<unsigned int>& itemVec); //sig::scoped_connection mConnChangePageLimit; //sig::scoped_connection mConnChangePageNo; //void OnChangePageLimit(const IModel& model); //void OnChangePageNo(const IModel& model); }; //----------------------------------------------------------------------------- }//namespace wh #endif //__*_H
#include <cstdio> #define MAX_SIZE 10000 using namespace std; int main() { int n, input; int count[MAX_SIZE + 1] = {}; scanf("%d", &n); for(int i=0; i<n; i++) { scanf("%d", &input); count[input]++; } for(int i=0; i<=MAX_SIZE; i++) { for(int j=0; count[i] > 0 && j<count[i]; j++) { printf("%d\n", i); } } return 0; }
= まえがき あなたは、技術同人誌は好きですか? 「We Love 技術同人誌 -技術書界隈を盛り上げる本-」を手に取っていただきありがとうございます。 この本を手に取っていただいたということは、あなたも技術同人誌に関わっているうちの一人です。 この本は、技術同人誌に関わる人による、技術同人誌に関わる人のための、技術同人誌への「愛」を詰め込んだ本です。 この本には、多数の著者が技術同人誌への関わり方や想いを語っています。 あなたがこの本を読めば、今よりもっと技術同人誌が好きになれること間違いありません。 そして、この本を読み終わったら、SNSなどでこの本の感想や、心が動かされたことについて伝えてみましょう。 (Twitterであれば #技術書界隈を盛り上げる会 で呟いていただけると幸いです) あなたの発信が、技術同人誌に関わる全ての人に勇気を与え、技術同人誌の世界(技術書界隈)に彩りを与えてくれます。 さぁ、あなたも私たちと一緒に技術書界隈を盛り上げていきましょう。 ~「技術書界隈を盛り上げる会」より、愛を込めて~
// Created on: 1995-01-27 // Created by: Marie Jose MARTZ // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepToIGES_BRShell_HeaderFile #define _BRepToIGES_BRShell_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <BRepToIGES_BREntity.hxx> #include <Message_ProgressRange.hxx> class IGESData_IGESEntity; class TopoDS_Shape; class TopoDS_Shell; class TopoDS_Face; //! This class implements the transfer of Shape Entities from Geom //! To IGES. These can be : //! . Vertex //! . Edge //! . Wire class BRepToIGES_BRShell : public BRepToIGES_BREntity { public: DEFINE_STANDARD_ALLOC Standard_EXPORT BRepToIGES_BRShell(); Standard_EXPORT BRepToIGES_BRShell(const BRepToIGES_BREntity& BR); //! Transfert an Shape entity from TopoDS to IGES //! This entity must be a Face or a Shell. //! If this Entity could not be converted, this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferShell (const TopoDS_Shape& start, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Transfert an Shell entity from TopoDS to IGES //! If this Entity could not be converted, this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferShell (const TopoDS_Shell& start, const Message_ProgressRange& theProgress = Message_ProgressRange()); //! Transfert a Face entity from TopoDS to IGES //! If this Entity could not be converted, this member returns a NullEntity. Standard_EXPORT Handle(IGESData_IGESEntity) TransferFace (const TopoDS_Face& start, const Message_ProgressRange& theProgress = Message_ProgressRange()); protected: private: }; #endif // _BRepToIGES_BRShell_HeaderFile
#include <windows.h> #include <stdio.h> #include <time.h> int main() { char buffer[]="Write this text to file"; DWORD dwWritten; // number of bytes written to file HANDLE hFile; hFile=CreateFile(TEXT("C:\\test.txt"),GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); if(hFile==INVALID_HANDLE_VALUE) { return 1; } WriteFile(hFile,buffer,sizeof(buffer),&dwWritten,0); CloseHandle(hFile); return 0; }
#pragma once #ifndef Room_h #define Room_h #include "PuzzleArea.h" #include <list> class Room { struct Wall { char direction; Wall* next; Wall* previous; std::list<PuzzleArea*>puzzles; }; public: Wall* walls; void WeNeedToBuildAWall();//Tworzenie listy scian void AddNewPuzzle(char,int , int , int , int , int , int ,int ); bool CheckClick(int, int,char,Ekwipunek*); }; #endif
#pragma once bool is_zero(float f, float tolerance = 0.0001f) { return (f >= -tolerance) && (f <= tolerance); } bool is_between(float f, float min, float max, float tolerance = 0.0001f) { return (f >= min - tolerance) && (f <= max + tolerance); } template <typename T> struct vec3 { using type = T; using vec3_t = vec3<T>; T x, y, z; vec3(T x, T y, T z) : x{x}, y{y}, z{z} {} vec3_t operator+(const vec3_t &b) const { return {x + b.x, y + b.y, z + b.z}; } vec3_t operator-(const vec3_t &b) const { return {x - b.x, y - b.y, z - b.z}; } T dot(const vec3_t &b) const { return x * b.x + y * b.y + z * b.z; } vec3_t cross(const vec3_t &b) const { return { y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x}; } }; using vec3f = vec3<float>; vec3f operator*(float f, const vec3f &b) { return vec3f{f * b.x, f * b.y, f * b.z}; } template <typename TVec, typename T> TVec barycentric_coords(const T u, const T v, const TVec &a, const TVec &b, const TVec &c) { #ifdef GUARDS ASSERT(u >= 0); ASSERT(v >= 0); ASSERT(u + v <= 1); #endif return (1 - u - v) * a + u * b + v * c; } template <typename T> struct ray_triangle_result { bool ok; T t; T u; T v; }; // http://www.graphics.cornell.edu/pubs/1997/MT97.pdf template <typename TVec> ray_triangle_result<typename TVec::type> intersection_ray_triangle( const TVec &o, const TVec &dir, const TVec &a, const TVec &b, const TVec &c) { auto edge1 = b - a; auto edge2 = c - a; auto pvec = dir.cross(edge2); auto det = edge1.dot(pvec); if (is_zero(det)) return {0}; auto inv_det = (typename TVec::type)1.0 / det; auto tvec = o - a; auto u = tvec.dot(pvec) * inv_det; if (!is_between(u, 0, 1)) return {}; auto qvec = tvec.cross(edge1); auto v = dir.dot(qvec) * inv_det; if (!is_between(u, 0, 1 - v)) return {0}; auto t = edge2.dot(qvec) * inv_det; return ray_triangle_result<typename TVec::type>{true, t, u, v}; }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *head = NULL; int carry = 0; ListNode *prev = head; for (ListNode *pa=l1, *pb=l2; NULL!=pa || NULL!=pb; pa=(NULL==pa)?NULL:pa->next, pb=(NULL==pb)?NULL:pb->next) { int va, vb, val; va = (NULL==pa)?0:pa->val; vb = (NULL==pb)?0:pb->val; val = (va+vb+carry)%10; carry = (va+vb+carry)/10; // tail insertion if (NULL==head) { head = prev = new ListNode(val); } else { prev->next = new ListNode(val); prev = prev->next; } } if (carry > 0) prev->next = new ListNode(carry); return head; } };
#include<bits/stdc++.h> using namespace std; char str[505]; int C; int w[55]; int n; void getc(){ n=0; int len=strlen(str); for(int i=0;i<len;i++){ if(str[i]==' '){ n++; } else{ w[n]=w[n]*32+(str[i]-'a'+1); } } } int judge(){ for(int i=0;i<=n;i++){ for(int j=i+1;j<=n;j++){ if(w[i]==0||w[j]==0) continue; if((C/w[i])%(n+1)==(C/w[j])%(n+1)){ C=min((C/w[i]+1)*w[i],(C/w[j]+1)*w[j]); return 0; } } } return 1; } int main(){ while(gets(str)!=NULL){ memset(w,0,sizeof(w)); getc(); C=100000000; for(int i=0;i<=n;i++){ if(C>w[i]) C=w[i]; } while(judge()==0); printf("%s\n",str); printf("%d\n\n",C); } return 0; }
#include "GnMainPCH.h" #include "GnTransform.h"
#include "checkerHeader.h" #include "menuHeader.h" #include "utilityHeader.h" void verify(int& option, int number, int startRow, string askInput) { while (option < 1 || option > number) { goToXY(0, number + startRow); for (int i = 0; i <= number + startRow + 1; i++) { cout << " \n"; } goToXY(0, number + startRow); cout << askInput << option; goToXY(0, number + startRow + 1); for (int i = 0; i <= number + startRow + 1; i++) { cout << " \n"; } goToXY(0, number + startRow + 1); cout << "Invalid! Try again: "; cin >> option; } } bool compareDate(date a, date b) { //nếu ngày a lớn hơn ngày b thì trả về true if (a.year > b.year) return true; if (a.year == b.year && a.month > b.month) return true; if (a.year == b.year && a.month == b.month && a.day > b.day) return true; return false; } bool checkLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return true; return false; } bool checkValidDate(date a) { if (a.day > 0 && a.day < 30 && a.month == 2 && checkLeapYear(a.year) == true) return true; if (a.day > 0 && a.day < 29 && a.month == 2 && checkLeapYear(a.year) == false) return true; if (a.day > 0 && a.day < 32 && (a.month == 1 || a.month == 3 || a.month == 5 || a.month == 7 || a.month == 8 || a.month == 10 || a.month == 12)) return true; if (a.day > 0 && a.day < 31 && (a.month == 4 || a.month == 6 || a.month == 9 || a.month == 11)) return true; return false; } void valiDate(schoolYear defaultsc, semester defaultsmt, schoolYear tempsc, semester tempsmt, date& startDate, date& endDate) { while (checkValidDate(startDate) == false || checkValidDate(endDate) == false || compareDate(endDate, startDate) == false) { goToXY(0, 4); for (int i = 0; i <= 6; i++) { cout << " \n"; } goToXY(0, 4); cout << "Input a start date of the semester (dd/mm/yyyy): " << setw(2) << setfill('0') << startDate.day << " " << setw(2) << setfill('0') << startDate.month << " " << setw(4) << setfill('0') << startDate.year << "\n"; cout << "Input a end date of the semester (dd/mm/yyyy): " << setw(2) << setfill('0') << endDate.day << " " << setw(2) << setfill('0') << endDate.month << " " << setw(4) << setfill('0') << endDate.year; goToXY(0, 6); for (int i = 0; i <= 6; i++) { cout << " \n"; } goToXY(0, 6); cout << "Invalid! Try again! Start date: "; cin >> startDate.day; switch (startDate.day) { case 0: createASemester(defaultsc, defaultsmt, tempsc, tempsmt); break; default: cin >> startDate.month; switch (startDate.month) { case 0: createASemester(defaultsc, defaultsmt, tempsc, tempsmt); break; default: cin >> startDate.year; switch (startDate.year) { case 0: createASemester(defaultsc, defaultsmt, tempsc, tempsmt); break; default: cout << " End date: "; cin >> endDate.day; switch (endDate.day) { case 0: createASemester(defaultsc, defaultsmt, tempsc, tempsmt); break; default: cin >> endDate.month; switch (endDate.month) { case 0: createASemester(defaultsc, defaultsmt, tempsc, tempsmt); break; default: cin >> endDate.year; switch (endDate.year) { case 0: createASemester(defaultsc, defaultsmt, tempsc, tempsmt); break; } } } } } } } return; } bool checkUnduplicatedSemester(semesterNode* pHead, semester tempsmt) { if (pHead == nullptr) return true; semesterNode* pCur = pHead; while (pCur != nullptr && tempsmt.number != pCur->smt.number) pCur = pCur->pNext; if (pCur != nullptr) return false; return true; } bool checkTimeOrder(semesterNode* pHead, semester tempsmt) { if (pHead == nullptr) return true; if (tempsmt.number < pHead->smt.number && compareDate(pHead->smt.startDate, tempsmt.endDate) == true) return true; semesterNode* pCur = pHead; while (pCur->pNext != nullptr && tempsmt.number > pCur->pNext->smt.number) pCur = pCur->pNext; if (pCur->pNext != nullptr && compareDate(tempsmt.startDate, pCur->smt.endDate) == true && compareDate(pCur->pNext->smt.startDate, tempsmt.endDate) == true) return true; if (pCur->pNext == nullptr && compareDate(tempsmt.startDate, pCur->smt.endDate) == true) return true; return false; } bool checkSemesterExist(semesterNode* pHead, semester tempsmt) { if (pHead == nullptr) return false; semesterNode* pCur = pHead; while (pCur != nullptr && pCur->smt.number != tempsmt.number) pCur = pCur->pNext; if (pCur != nullptr) return true; return false; } bool compareString_Same(string a, string b) { if (a.size() != b.size()) return false; for (int i = 0; i < a.size(); i++) { if (a[i] >= 'A' && a[i] <= 'Z') a[i] += 32; if (b[i] >= 'A' && b[i] <= 'Z') b[i] += 32; if (a[i] != b[i]) return false; } return true; } bool compareString_Alphabet(string a, string b) { for (int i = 0; i < a.size(); i++) if (a[i] >= 'A' && a[i] <= 'Z') a[i] += 32; for (int j = 0; j < b.size(); j++) if (b[j] >= 'A' && b[j] <= 'Z') b[j] += 32; if (a < b) return false; return true; } bool checkCourseInfoFulfill(courseInfo newCourse) { if (newCourse.ID == "0" || newCourse.ID == "\n" || newCourse.name == "0" || newCourse.name == "\n" || newCourse.teacher == "0" || newCourse.teacher == "\n" || newCourse.credit == 0 || newCourse.session[0].dayOfWeek == "0" || newCourse.session[0].dayOfWeek == "\n" || newCourse.session[0].time.hour == 0 || newCourse.session[0].time.minute == 0 || newCourse.session[1].dayOfWeek == "0" || newCourse.session[1].dayOfWeek == "\n" || newCourse.session[1].time.hour == 0 || newCourse.session[1].time.minute == 0) return false; return true; } bool checkUnduplicatedCourse(courseNode* pHead, courseInfo newCourse) { if (pHead == nullptr) return true; courseNode* pCur = pHead; while (pCur != nullptr) { if (compareString_Same(pCur->course.ID, newCourse.ID) == true && compareString_Same(pCur->course.name, newCourse.name) == true && compareString_Same(pCur->course.teacher, newCourse.teacher) == true && pCur->course.credit == newCourse.credit && pCur->course.student == newCourse.student && compareString_Same(pCur->course.session[0].dayOfWeek, newCourse.session[0].dayOfWeek) == true && pCur->course.session[0].time.hour == newCourse.session[0].time.hour && compareString_Same(pCur->course.session[1].dayOfWeek, newCourse.session[1].dayOfWeek) == true && pCur->course.session[1].time.hour == newCourse.session[1].time.hour) return false; pCur = pCur->pNext; } return true; } bool checkFreeTeacher(courseNode* pHead, courseInfo newCourse) { if (pHead == nullptr) return true; courseNode* pCur = pHead; while (pCur != nullptr) { if (compareString_Same(pCur->course.teacher, newCourse.teacher) == true && ((compareString_Same(pCur->course.session[0].dayOfWeek, newCourse.session[0].dayOfWeek) == true && pCur->course.session[0].time.hour == newCourse.session[0].time.hour) || (compareString_Same(pCur->course.session[1].dayOfWeek, newCourse.session[1].dayOfWeek) == true && pCur->course.session[1].time.hour == newCourse.session[1].time.hour))) return false; pCur = pCur->pNext; } return true; }
#include <iostream> #include <vector> using namespace std; template <typename T> class MultiStack { private: struct StackData { int stack_num; T data; bool safe_to_delete = false; }; int num_of_stacks; vector<StackData> data {}; vector<int> tops_index; public: MultiStack(const int c_num_of_stacks) :num_of_stacks{c_num_of_stacks}, tops_index(c_num_of_stacks, -1) {} void push(const T elem, const int stack_num) { int top = tops_index.at(stack_num); int new_top = top + 1; while ((new_top < data.size()) && (!data[new_top].safe_to_delete)) { new_top++; } if (new_top >= data.size()) { data.push_back({stack_num, elem}); } else { data[new_top] = {stack_num, elem}; } tops_index.at(stack_num) = new_top; } void pop(const int stack_num) { int top = tops_index.at(stack_num); data.at(top).safe_to_delete = true; int new_top = top - 1; while ((new_top > -1) && (data[new_top].stack_num != stack_num)) { new_top--; } tops_index.at(stack_num) = new_top; } T& peek(const int stack_num) { int top = tops_index.at(stack_num); return data.at(top).data; } bool isEmpty(const int stack_num) { return (tops_index.at(stack_num) < 0); } }; int main() { MultiStack<int> multiStack {3}; cout << "First stack empty? " << multiStack.isEmpty(0) << endl; for (auto i : {1, 2, 3}) { multiStack.push(i, 0); } cout << "First stack empty? " << multiStack.isEmpty(0) << endl; while (!multiStack.isEmpty(0)) { cout << multiStack.peek(0) << ", "; multiStack.pop(0); } cout << "\n"; cout << "First stack empty? " << multiStack.isEmpty(0) << endl; for (auto i : {1, 2, 3}) { multiStack.push(i, 0); } for (auto i : {4, 5, 6, 7, 8, 9, 10}) { multiStack.push(i, 0); multiStack.push(i, 1); } for (auto i : {11, 12, 13, 14}) { multiStack.push(i, 0); multiStack.push(i, 1); multiStack.push(i, 2); } while (!multiStack.isEmpty(0)) { cout << multiStack.peek(0) << ", "; multiStack.pop(0); } cout << endl; while (!multiStack.isEmpty(1)) { cout << multiStack.peek(1) << ", "; multiStack.pop(1); } cout << endl; for (auto i : {15, 16, 17}) { multiStack.push(i, 2); } while (!multiStack.isEmpty(2)) { cout << multiStack.peek(2) << ", "; multiStack.pop(2); } cout << endl; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Espen Sand */ #ifndef __UNIXUTILS_H__ #define __UNIXUTILS_H__ class OpFile; class DesktopWindow; namespace UnixUtils { /** * Convert 8-bit string to 16-bit target. It is assumed the string * encoded in current locale. Should the initial conversion using * current locale fail, an attempt is made to convert from UTF8 * * @param src 8-bit source string * @param target 16-bit target string * * @return OpStatus::OK on success, otherwise an error code */ OP_STATUS FromNativeOrUTF8(const char* src, OpString *target); /** * Determines the file permission level we shall use when creating files or * directories. Reads the setting from OPERA_STRICT_FILE_PERMISSIONS * environment variable. * * @return TRUE when we shall use a strict setting, otherwise FALSE */ BOOL UseStrictFilePermission(); /** * Creates all path components of a path with filename. Text after * after the last '/' is assumed to be the filename when 'stop_on_last_pathsep' * is TRUE and no directory will be made out of that component. * * @param path The path to be constucted * @param stop_on_last_pathsep Everything after the last PATHSEPCHAR * gets ignored when TRUE. * * @return TRUE on success, otherwise FALSE */ OP_STATUS CreatePath(const uni_char* filename, BOOL stop_on_last_pathsep); OP_STATUS CreatePath(const char* filename, BOOL stop_on_last_pathsep); /** * Split applied path into a directory and a filename. The retuned directory * exists while the file does not have to. * * @param src The path to split * @param directory On successful return, the directory component of the path * @param filename On successful return, the file component of the path * * @return TRUE on success, otherwise FALSE. The returned parameter values can contain random data on FALSE */ BOOL SplitDirectoryAndFilename(const OpString& src, OpString& directory, OpString& filename); /** * Clean and simplify the specified path by removing ".." and * multiple '/' specifiers * * @param candidate Path to purify */ void CanonicalPath(OpString& candidate); /** * Attempts to set a write lock (advisory locking) on the file. * This function will open a file on success. The returned file * descriptor should be closed when no longer needed. The lock is * automatically removed the the process that created it terminates. * * @param filename The file to lock * @param On success the file descriptor is returned if pointer is not NULL * * @return -1: Error, 0: Was already locked, 1: Success */ int LockFile(const OpStringC& filename, int* file_descriptor); BOOL SearchInStandardFoldersL( OpFile &file, const uni_char* filename, BOOL allow_local, BOOL copy_file ); //* Call shortly after g_opera->InitL to get the random animal going. bool BreakfastSSLRandomEntropy(); //* Feed a noisy word to the random animal. void FeedSSLRandomEntropy(UINT32 noise); int CalculateScaledSize(int src, double scale); /** Check whether we should disregard the requested font size. * "Snap" to nearest (presumably) nice-looking size for core X fonts. This * is done to avoid our somewhat ugly (but necessary) core X anti-aliased * font scaling algorithm in cases where the requested size is pretty close * to the size that was found to be the nearest one. Bitmap fonts scaled by * the X server is also quite ugly, so let's try to avoid it. * @param req_size The font size requested by Opera * @param avail_size The nearest font size available * @return The font size to be used. If avail_size is "close enough" to * req_size, avail_size will be returned. Otherwise, req_size will be * returned. */ bool SnapFontSize(int req_size, int avail_size); inline bool IsSurrogate(uni_char ch) { return ch >= 0xd800 && ch <= 0xdfff; } inline uint32_t DecodeSurrogate(uni_char low, uni_char high) { if (low < 0xd800 || low > 0xdbff || high < 0xdc00 || high > 0xdfff) return '?'; return 0x10000 + (((low & 0x03ff) << 10) | (high & 0x03ff)); } inline void MakeSurrogate(uint32_t ucs, uni_char &high, uni_char &low) { OP_ASSERT(ucs >= 0x10000 && ucs <= 0x10ffff); ucs -= 0x10000; high = 0xd800 | uni_char(ucs >> 10); low = 0xdc00 | uni_char(ucs & 0x03ff); } /* Creates a grand-child process. * * A process, when complete, sends SIGCHLD to its parent and becomes defunct * (a.k.a. a zombie) until its parent wait()s for it. If the parent has * died before the child, the child just exits peacefully (in fact because * its parent's death orphaned it, at which point it was adopted by the init * process, pid = 1, which ignores child death). * * This function does a double-fork and waits for the primary child's exit; * the grand-child gets a return of 0 and should do something; the * original process doesn't need to handle SIGCHLD. If the primary fork * fails, or the primary child is unable to perform the secondary fork, the * parent process sees a negative return value; otherwise, a positive one. */ int GrandFork(); /** * Tests the filename to verify if it can be written to or not. The user will * be prompted with a dialog if there is a problem. * * @param parent Parent to dialogs if any. Can be NULL * @param candidate The filename to test * @param ask_replace Allow user to decide if an existing file can be overwritten * * @return TRUE if file can be written, FALSE otherwise */ BOOL CheckFileToWrite(DesktopWindow* parent, const OpStringC& candidate, BOOL ask_replace); /** * Clean up a folder, i.e. if the folder exists, remove the folder and create a new * folder with same name. * * @param path Path to folder * * @return OP_STATUS */ OP_STATUS CleanUpFolder(const OpString &path); /** * Tells user filename is missing * * @param parent Dialog parent. Can be NULL */ void PromptMissingFilename(DesktopWindow* parent); /** * Tells user filename is the same as an existing directory * * @param parent Dialog parent. Can be NULL */ void PromptFilenameIsDirectory(DesktopWindow* parent); /** * Tells user filename can not be written because of lacking access rights. * A test is done on the filename to treat it as a directory if it is. If the * filename is empty a generic message is shown. * * @param parent Dialog parent. Can be NULL * @param filename The filename */ void PromptNoWriteAccess(DesktopWindow* parent, const OpStringC& filename); /** * Tells user filename points to an existing file. * * @param parent Dialog parent. Can be NULL * @param filename The filename * @param ask_continue. If TRUE, the user can decide to overwrite the existing file * * @return TRUE if file can be overwritten, otherwise FALSE */ BOOL PromptFilenameAlreadyExist(DesktopWindow* parent, const OpStringC& filename, BOOL ask_continue); /** * Tests for the existence of an environment variable and returns TRUE * if it is set to "1", "yes" or "true". The "yes" or "true" can be in * any combination of cases * * @param name The environment variable to examine * * @return TRUE on a positive match, otherwise FALSE */ BOOL HasEnvironmentFlag(const char* name); /** * A static implementation of OpSystemInfo::ExpandSystemVariablesInString(). * * @param in Serialized filename string * @param out OpString for storing the result * @return success or failure */ OP_STATUS UnserializeFileName(const uni_char* in, OpString* out); /** Use system variables to re-express a path-name. * * Complementary to UnserializeFileName(). * * @param path Raw (but possibly relative) path to file or directory. * @return NULL on OOM, else a pointer to a freshly allocated string, which * the caller is responsible for delete[]ing when no longer needed. */ uni_char* SerializeFileName(const uni_char *path); } #endif // __UNIXUTILS_H__
#include <Wire.h> #include <LiquidCrystal_I2C.h> #include <SoftwareSerial.h> int sensorVal=0; int mg=0; const int buttonPin=2; int buttonState=0; SoftwareSerial MyBlue(0, 1 ); // RX | TX LiquidCrystal_I2C lcd(0x3F,16,2); int cal; void setup() { lcd.init(); lcd.backlight(); MyBlue.begin(9600); Serial.begin(9600); pinMode(buttonPin,INPUT); pinMode(3,OUTPUT); pinMode(A0,INPUT); pinMode(A1,OUTPUT); cal=callibration(); lcd.begin(16,2); lcd.print("Press and blow"); digitalWrite(3,HIGH); digitalWrite(A1,HIGH); } void loop() { buttonState=digitalRead(buttonPin); if (buttonState==HIGH) { lcd.begin(16,2); lcd.setCursor(0,0); lcd.print("Get Ready to Blow"); delay(1000); lcd.begin(16,2); lcd.setCursor(0,0); lcd.print("Blow"); lcd.setCursor(0,1); delay(5000); lcd.print("Stop"); delay(10000); sensorVal=analogRead(A0); sensorVal=(133.81)+((-7.02)*sensorVal)+((0.19526)*pow(sensorVal,2))+((-0.00174)*pow(sensorVal,3)); lcd.begin(16,2); lcd.setCursor(0,0); lcd.print("Glucose level: "); lcd.setCursor(0,1); lcd.print(int(sensorVal),DEC); Serial.println(int(sensorVal)); lcd.setCursor(5,1); lcd.print("mg/dL"); } else return; } int callibration() //the sensor calliberation part { int s=0; int call=0; lcd.print("Callibrating"); for (int i=0;i<20;i++) { s=analogRead(A0); call=call+s; delay(1000); } call=call/20; return call; }
#include "flashdialog.h" #include <QAxWidget> #include <QLayout> FlashDialog::FlashDialog(QWidget *parent /* = 0 */) { flashwidget = new QAxWidget; flashwidget->setControl(QString::fromUtf8("{d27cdb6e-ae6d-11cf-96b8-444553540000}")); QVBoxLayout *mainlayout = new QVBoxLayout; mainlayout->addWidget( flashwidget); setLayout(mainlayout); } void FlashDialog::Initialise(const QString rtmp) { flashwidget->dynamicCall("LoadMovie(long,string)",0,"http://player.video.qiyi.com/199b369011ea5a40e202290a50fa5a39/0/2184/v_19rrmntgkg.swf"); }
#include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> #include <vector> #include <set> using namespace std; const int maxN = 100000 + 100, maxM = 100000 + 100; bool deleted[maxN]; int loc[maxN], sum[maxN], n, k, m; int main() { #ifndef ONLINE_JUDGE freopen("in", "r", stdin); #endif scanf("%d%d%d", &n, &k, &m); vector<pair<int, int> > seg1, seg2, tmp; for (int i = 0; i < m; ++ i) { int a, b, c; scanf("%d%d%d", &a, &b, &c); if (c) seg2.push_back(make_pair(a - 1, b)); else seg1.push_back(make_pair(a - 1, b)); } sort(seg1.begin(), seg1.end()); for (int i = 0, last = 0; i < seg1.size(); ++ i) if (seg1[i].second > last) { for (int j = max(last, seg1[i].first); j < seg1[i].second; ++ j) deleted[j] = true; last = seg1[i].first; } sum[0] = 0; // sum[i] : how many node remains in [0, i) for (int i = 0, last = -1; i < n; ++ i) { if (! deleted[i]) sum[i + 1] = sum[i] + 1, last = i; else sum[i + 1] = sum[i]; loc[i] = last; // loc[i] : the nearest remaining node that is not right to i } if (sum[n] == k) { for (int i = 0; i < n; ++ i) if (! deleted[i]) printf("%d\n", i + 1); return 0; } sort(seg2.begin(), seg2.end()); for (int i = seg2.size() - 1, last = n + 1; i >= 0; -- i) if (seg2[i].second < last) { // delete those that covers others tmp.push_back(seg2[i]); last = seg2[i].second; } vector<int> ans, f(seg2.size() + 1, 0); for (int i = 0; i < tmp.size(); ++ i) if (sum[tmp[i].second] - sum[tmp[i].first] == 1) { // delete those positions that must be among answers int x = loc[tmp[i].second - 1]; if (! deleted[x]) deleted[x] = true, ans.push_back(x); } sort(ans.begin(), ans.end()); sum[0] = 0; for (int i = 0, last = -1; i < n; ++ i) { if (! deleted[i]) sum[i + 1] = sum[i] + 1, last = i; else sum[i + 1] = sum[i]; loc[i] = last; } seg2.clear(); for (int i = tmp.size() - 1; i >= 0; -- i) { int a = lower_bound(ans.begin(), ans.end(), tmp[i].first) - ans.begin(), b = lower_bound(ans.begin(), ans.end(), tmp[i].second) - ans.begin(); if (a == b) seg2.push_back(tmp[i]); // add if no decided position in the interval } for (int i = seg2.size() - 1; i >= 0; -- i) { int x = loc[seg2[i].second - 1]; int t = lower_bound(seg2.begin(), seg2.end(), make_pair(x + 1, 0)) - seg2.begin(); f[i] = f[t] + 1; // f[i] : minimum positions to ensure seg2[i] ... seg2[n - 1] } k -= ans.size(); for (int i = 0, last = -1, cnt = 0; i < seg2.size(); ++ i) if (seg2[i].first > last) { int x = loc[seg2[i].second - 1], y = loc[x - 1]; int t = lower_bound(seg2.begin(), seg2.end(), make_pair(y + 1, 0)) - seg2.begin(); if (cnt + 1 + f[t] > k) ans.push_back(x); // x is necessary last = x; ++ cnt; } sort(ans.begin(), ans.end()); if (ans.size()) for (int i = 0; i < ans.size(); ++ i) printf("%d\n", ans[i] + 1); else puts("-1"); return 0; }
#include <bits/stdc++.h> using namespace std; int main() { int t, num, tot=0; scanf("%d", &t); while(scanf("%d", &num)!=EOF) if(num==t) tot++; printf("%d\n", tot); return 0; }
#include "EntityCache.h" void CEntityCache::Fill() { if (m_pLocal = GET_ENT_I(LOCAL_IDX)->As<CTFPlayer>()) { int nLocalTeam = m_pLocal->m_iTeamNum(); if (nLocalTeam != TEAM_RED && nLocalTeam != TEAM_BLU) { m_pLocal = nullptr; return; } m_pWeapon = GET_ENT_H(m_pLocal->m_hActiveWeapon())->As<CTFWeaponBase>(); for (int n = 1; n < I::ClientEntityList->GetHighestEntityIndex(); n++) { IClientEntity *pEntity = GET_ENT_I(n); if (!pEntity || pEntity->IsDormant()) continue; switch (pEntity->GetClassId()) { case EClassIds::CTFPlayer: { int nPlayerTeam = pEntity->As<CTFPlayer>()->m_iTeamNum(); if (nPlayerTeam != TEAM_RED && nPlayerTeam != TEAM_BLU) continue; m_Groups[EEntGroup::PLAYERS_ALL].push_back(pEntity); m_Groups[nLocalTeam != nPlayerTeam ? EEntGroup::PLAYERS_ENEMIES : EEntGroup::PLAYERS_TEAMMATES].push_back(pEntity); break; } case EClassIds::CObjectSentrygun: case EClassIds::CObjectDispenser: case EClassIds::CObjectTeleporter: { int nObjectTeam = pEntity->As<CBaseObject>()->m_iTeamNum(); m_Groups[EEntGroup::BUILDINGS_ALL].push_back(pEntity); m_Groups[nLocalTeam != nObjectTeam ? EEntGroup::BUILDINGS_ENEMIES : EEntGroup::BUILDINGS_TEAMMATES].push_back(pEntity); break; } default: break; } } } } void CEntityCache::Clear() { for (auto &Group : m_Groups) Group.second.clear(); m_pLocal = nullptr; m_pWeapon = nullptr; } const std::vector<IClientEntity *> &CEntityCache::GetGroup(EEntGroup Group) { return m_Groups[Group]; } CTFPlayer *CEntityCache::GetLocal() { return m_pLocal; } CTFWeaponBase *CEntityCache::GetWeapon() { return m_pWeapon; }
// MIT License // Copyright (c) 2020 Marnix van den Berg <m.a.vdberg88@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "GUI.h" #include "BodyVec.h" #include "Body.h" #include "Shape.h" #include "DesktopResolution.h" #include "Contact.h" #include "ErrorLogger.h" #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> enum class Color { white, green }; namespace { static bool g_acceptEvent(true); //Used to make sure that mouse moves do not override click events. static void trackBarCallBack(int, void*) {} void mouseCallback(int event, int x, int y, int flags, void* param) { GUI::CVMouseInfo* mInfo = (GUI::CVMouseInfo*)param; if (event == cv::EVENT_LBUTTONUP) //Always accept release. { g_acceptEvent = false; mInfo->event = event; mInfo->x = x; mInfo->y = y; } if (event == cv::EVENT_LBUTTONDOWN && g_acceptEvent) //can't override mouse release. { g_acceptEvent = false; mInfo->event = event; mInfo->x = x; mInfo->y = y; } if (event == cv::EVENT_MOUSEMOVE && g_acceptEvent) //is overwritten by left press or release. { mInfo->event = event; mInfo->x = x; mInfo->y = y; } }; } GUI::GUI(): m_scaling(0.0), m_windowHeight(0), m_windowWidth(0), m_centeringDistH(0), m_centeringDistV(0), m_sliderPosMargin(1000), m_sliderMaxMargin(1000), m_sliderPosDisp(500), m_sliderMaxDisp(1000) {} GUI::~GUI() = default; bool GUI::init(Vector2 domainSize) { if (domainSize.x() < DBL_EPSILON || domainSize.y() < DBL_EPSILON) { ErrLog::log("Error: Domain size cannot be 0."); return false; } int hPix(0), vPix(0); desktopRes::getDesktopResolution(&hPix, &vPix); vPix -= 100; //To make sure bottom of window is not behind task bar. Vector2 size = domainSize*1.01; //Show a bit of the boundary bodies. m_offset = 0.5 * size; //By default domain is from -0.5*size to 0.5*size. cvMat starts at 0. //Check if the height or the with of the desktop is governing for initial window size. double desktopRatio = double(hPix) / double(vPix); double sizeRatio = size.x() / size.y(); if (desktopRatio > sizeRatio) { m_windowHeight = vPix; m_scaling = m_windowHeight / size.y(); m_centeringDistV = 0; m_windowWidth = vPix * int(sizeRatio); m_centeringDistH = (hPix - m_windowWidth) / 2; } else { m_scaling = hPix / size.y(); m_windowWidth = hPix; m_windowHeight = hPix / int(sizeRatio); m_centeringDistV = (vPix - m_windowHeight) / 2; } //Create and center the window: cv::namedWindow("Ice Field Creator", cv::WINDOW_NORMAL); cv::resizeWindow("Ice Field Creator", m_windowHeight, m_windowWidth); cv::moveWindow("Ice Field Creator", m_centeringDistH, m_centeringDistV); //Set mouse callback and create trackbars: cv::setMouseCallback("Ice Field Creator", mouseCallback, &m_cvMouseInfo); cv::createTrackbar("maxDisp", "Ice Field Creator", &m_sliderPosDisp, m_sliderMaxDisp, trackBarCallBack); cv::createTrackbar("colMargin", "Ice Field Creator", &m_sliderPosMargin, m_sliderMaxMargin, trackBarCallBack); return true; } UserInput GUI::draw(const BodyVec& bodies, const std::vector<Contact>& contacts, double maxPenetration, bool penBelowLimit) //, const std::vector<Contact>& contacts { //Init image matrix and set background color to light blue; m_image = std::make_unique<cv::Mat> (cv::Mat::zeros(m_windowHeight, m_windowWidth, CV_8UC3)); m_image->setTo(cv::Scalar(255, 200, 0)); drawBodies(bodies); drawContacts(contacts); //Write maximum penentration to window. Red is above limit set in input file, green if below. std::string str = "Max penetration: " + std::to_string(maxPenetration); cv::String cvstr(str.c_str()); cv::Scalar color; if (penBelowLimit) color = cv::Scalar(0, 255, 0); //green else color = cv::Scalar(0, 0, 255); //red cv::putText(*m_image, cvstr, cv::Point(30, 50), cv::FONT_HERSHEY_SIMPLEX, 1, color, 2, cv::LINE_AA); g_acceptEvent = true; //Accept new mouse click events (see mouseCallBack) //Plot scene: if (cv::getWindowProperty("Ice Field Creator", cv::WND_PROP_VISIBLE)) { cv::imshow("Ice Field Creator", *m_image); cv::waitKey(1); } return simDomainUserInput(); } //Creates userInput struct for output to main simulation. UserInput GUI::simDomainUserInput() { UserInput userInput; UserInputMouse& mouseInput = userInput.mouseInput; //Scale mouse coordinates from pixels to domain, translate to openCV independent enums. if (m_cvMouseInfo.event == cv::EVENT_LBUTTONDOWN) { mouseInput.mouseFlag = MouseEvent::leftDown; double xw = double(m_cvMouseInfo.x) / m_scaling - m_offset.x(); double yw = double(m_cvMouseInfo.y) / m_scaling - m_offset.y(); mouseInput.mouseLocation = Vector2(xw, yw); } if (m_cvMouseInfo.event == cv::EVENT_LBUTTONUP) { mouseInput.mouseFlag = MouseEvent::leftUp; double xw = double(m_cvMouseInfo.x) / m_scaling - m_offset.x(); double yw = double(m_cvMouseInfo.y) / m_scaling - m_offset.y(); mouseInput.mouseLocation = Vector2(xw, yw); } if (m_cvMouseInfo.event == cv::EVENT_MOUSEMOVE) { mouseInput.mouseFlag = MouseEvent::move; double xw = double(m_cvMouseInfo.x) / m_scaling - m_offset.x(); double yw = double(m_cvMouseInfo.y) / m_scaling - m_offset.y(); mouseInput.mouseLocation = Vector2(xw, yw); } userInput.collisionMarginRatio = (double)m_sliderPosMargin /m_sliderMaxMargin; userInput.maxDisplacementRatio = (double)m_sliderPosDisp / m_sliderMaxDisp; if (!cv::getWindowProperty("Ice Field Creator", cv::WND_PROP_VISIBLE)) { userInput.windowClose = true; } return userInput; } void GUI::drawBodies(const BodyVec& bodies) { for (int i = 0; i < bodies.size(); i++) { const Body& body = bodies[i]; Color color; if (body.isStatic()) color = Color::green; else color = Color::white; std::vector<Vector2> globalPoints = body.globalPoints(); drawPoly(globalPoints,&color); } } void GUI::drawContacts(const std::vector<Contact>& contacts) { for (int i = 0; i < contacts.size(); i++) { drawContact(contacts[i]); } } void GUI::drawContact(const Contact& contact) { Vector2 normal = contact.normal(); Vector2 contactPoint = contact.contactPoint(); double halfPenetration = contact.penetration()/2.0; //Plot contact point (where contact impulses are applied) { Vector2 p = contactPoint + m_offset; cv::Point cvP(int(m_scaling * p.x()), int(m_scaling * p.y())); cv::circle(*m_image, cvP, 3, (255, 0, 0)); //blue } //Plot contact normal, with length equal to penetration depth: { std::vector<cv::Point> normLine(2); { Vector2 p = contactPoint - normal* halfPenetration; p += m_offset; cv::Point cvP(int(m_scaling * p.x()), int(m_scaling * p.y())); normLine[0] = cvP; } { Vector2 p = contactPoint + normal* halfPenetration; p += m_offset; cv::Point cvP(int(m_scaling * p.x()), int(m_scaling * p.y())); normLine[1] = cvP; } cv::polylines(*m_image, normLine, true, cv::Scalar(255, 0, 0)); //blue } } void GUI::drawPoly(const std::vector<Vector2>& poly, Color* color) { std::vector<cv::Point> cvPointsVec; for (int i = 0; i < poly.size(); i++) { Vector2 p = poly[i] + m_offset; cv::Point cvP(int(m_scaling*p.x()), int(m_scaling * p.y())); cvPointsVec.push_back(cvP); } int lineType = cv::LINE_8; const cv::Point* ppt[1] = { &cvPointsVec[0] }; size_t npt[] = { cvPointsVec.size() }; cv::Scalar col; if (*color == Color::white) col = cv::Scalar(255, 255, 255); else col = cv::Scalar(0, 255, 0); //green fillConvexPoly(*m_image, cvPointsVec, col, lineType); cv::polylines(*m_image, cvPointsVec, true, cv::Scalar(0, 0, 0)); //black polygon outlines }
#pragma once #include "Keng/GraphicsCommon/FwdDecl.h" #include "Keng/GraphicsCommon/SwapChainParameters.h" namespace keng::graphics { class WindowRenderTargetParameters { public: SwapChainParameters swapChain; }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) Opera Software ASA 2006-2012 * * Web server implementation -- overall server logic */ #include "core/pch.h" #ifdef WEBSERVER_SUPPORT #include "modules/webserver/webserver_filename.h" #include "modules/formats/uri_escape.h" /* FIXME: Use OpString as internal representation instead of an char array */ WebserverFileName::WebserverFileName() : m_isURL(FALSE) { } WebserverFileName::~WebserverFileName() { } const uni_char *WebserverFileName::GetPathAndFileNamePointer() const { return m_filePathAndName.CStr(); } /* static */ OP_STATUS WebserverFileName::SecureURLPathConcat(OpString &safeBasePath, const OpStringC8 &unsafeUrl) { OpString UTF16Url; RETURN_IF_ERROR(UTF16Url.SetFromUTF8(unsafeUrl.CStr())); return WebserverFileName::SecurePathConcat(safeBasePath, UTF16Url, TRUE); } /* static */ OP_STATUS WebserverFileName::SecureURLPathConcat(OpString &safeBasePath, const OpStringC &unsafeUrl) { return WebserverFileName::SecurePathConcat(safeBasePath, unsafeUrl, TRUE); } /* static */ OP_STATUS WebserverFileName::SecurePathConcat(OpString &safeBasePath, const OpStringC &unsafeSubPath, BOOL isURL) { if (safeBasePath.FindI(UNI_L("..")) != KNotFound) { OP_ASSERT(!"this path is not safe"); return OpStatus::ERR; } safeBasePath.Strip(TRUE, TRUE); OpString lsubPath; RETURN_IF_ERROR(lsubPath.Set(unsafeSubPath)); lsubPath.Strip(TRUE, TRUE); RETURN_IF_ERROR(CheckAndFixDangerousPaths(safeBasePath.CStr(), FALSE)); RETURN_IF_ERROR(CheckAndFixDangerousPaths(lsubPath.CStr(), isURL)); int lengthSub = lsubPath.Length(); if ( (safeBasePath.Length() > 0 && safeBasePath[safeBasePath.Length() - 1] != '/') && ((lengthSub > 0 && lsubPath[0] != '/') )) { RETURN_IF_ERROR(safeBasePath.Append("/")); } RETURN_IF_ERROR(safeBasePath.Append(lsubPath)); return OpStatus::OK; } const uni_char *WebserverFileName::GetFileNamePointer() const { if (m_filePathAndName.IsEmpty() == TRUE) return NULL; const uni_char *filePathAndName = m_filePathAndName.CStr(); int i = 0; uni_char *j = NULL; do { j = uni_strstr(&filePathAndName[i], UNI_L("/")); if (j) { i = j - filePathAndName + 1; } } while (j != NULL && filePathAndName[i] != '\0'); return filePathAndName+i; } /* static */ OP_STATUS WebserverFileName::CheckAndFixDangerousPaths(uni_char *filePathAndName, BOOL isURL) { //////////////////////////////////////// //// Known weakness: path less than 3 characters are problematic //// The character '/' can be duplciated //// It seems that '/' is required at the beginning of the path; the code as to be checked //// and, if it is safe, an ASSERT and a return have to be put in place if it does not happen //////////////////////////////////////// int length; if (filePathAndName == NULL || (length = uni_strlen(filePathAndName)) == 0) { return OpStatus::OK; } int i; for (i = 0; i < length; i++) { /* We normalize the path here (all \'s are turned in to /'s). */ if (filePathAndName[i] == '\\') { filePathAndName[i] = '/'; } /* Remove '"' */ if (filePathAndName[i] == '\"') { filePathAndName[i] = ' '; } } if (isURL == TRUE) { //StrReplaceChars(filePathAndName, '+', ' '); #ifdef FORMATS_URI_ESCAPE_SUPPORT UriUnescape::ReplaceChars(filePathAndName, length, UriUnescape::LocalfileUrlUtf8); #else ReplaceEscapedCharsUTF8(filePathAndName, length, OPSTR_LOCALFILE_URL); #endif filePathAndName[length] = '\0'; } for (i = 0; i < length; i++) { if(filePathAndName[i]=='?') break; // After the '?', get parameters start, so a '\\' is fine if (filePathAndName[i] == '\\') { return OpStatus::ERR; } } while ( length > 0 && filePathAndName[length-1] == ' ') { length--; } filePathAndName[length] = '\0'; i = 0; while (i < length && ( filePathAndName[i] == ' ' || filePathAndName[i] == '.')) { i++; } int j; for (j = 0; j < length - i; j++) { filePathAndName[j] = filePathAndName[j+i]; } length -= i; filePathAndName[length] = '\0'; int depth = 0; //the depth in the path tree // Special cases... if(length<=3) { if(!uni_strcmp(filePathAndName, "../") || !uni_strcmp(filePathAndName, "..") || !uni_strcmp(filePathAndName, "/..")) return OpStatus::ERR; } //Checks the path of type /adir/adir2/../.././ and counts the depth for (i = 3; i < length; i++) { if (filePathAndName[i - 3] == '/') { if (filePathAndName[i - 2] != '.') depth++; //if the filePathAndName is "/x" and x is not a "." then depth++ else { if (filePathAndName[i - 1] == '.' && ( filePathAndName[i] == '/' || filePathAndName[i] == ' ' || filePathAndName[i] == '\0' )) //if the filePathAndName is "/../ then depth-- depth--; else { if (filePathAndName[i - 1] != '/') depth++; //if the filePathAndName is "/.x" and x is not a "/" then depth++ } } } if (depth < 0 ) return OpStatus::ERR; //The filePathAndName depth should never try to get below 0, because is dangerous } // if the filePathAndName seems ok, remove all "/../" , "/./" and "//" int k; for (i = 0, j = 0 ; i < length; i++, j++) { filePathAndName[j] = filePathAndName[i]; if ( j > 1 && (i < length) && (uni_strncmp(&filePathAndName[i], "/./", 3) == 0) ) { i += 1; //Just remove the "./" j--; } else if ( j > 1 && (i < length) && (uni_strncmp(&filePathAndName[i], "//", 2) == 0) ) { j --; } else //if ( j > 2 && (i < length) && (uni_strncmp(&filePathAndName[i], "/../", 4) == 0) ) if ( j > 2 && (i < length) && (uni_strncmp(&filePathAndName[i], "/..", 3) == 0) && (filePathAndName[i+3]=='/' || filePathAndName[i+3]==0) ) { i += 2; // remove the "../" k = j - 1; while (filePathAndName[k] != '/' && k > 1) k--; j = k - 1; //and rewind next to the last '/' we passed } } /*if ( j >= 2 && uni_strncmp(&filePathAndName[j - 2], "..", 2) == 0 ) { j -= 2; }*/ if (j < 0) { // OP_ASSERT(!"ERROR IN WebserverFileName::CheckAndFixDangerousPaths"); j = 0; } filePathAndName[j] = '\0'; //OP_ASSERT(uni_strstr(filePathAndName, UNI_L("./")) != filePathAndName && uni_strstr(filePathAndName, UNI_L("/..")) == NULL); if (uni_strstr(filePathAndName, UNI_L("./")) == filePathAndName || uni_strstr(filePathAndName, UNI_L("/../")) != NULL) return OpStatus::ERR; return OpStatus::OK; } OP_STATUS WebserverFileName::Construct(const uni_char *path, int length, BOOL isURL) { if (path == NULL) { return OpStatus::ERR; } const uni_char *localPath = path; if (localPath[0] == '\"') { localPath = &path[1]; length--; } if (path[length] == '\"') { length--; } RETURN_IF_ERROR(m_filePathAndName.Set(path, length)); m_filePathAndName.Strip(TRUE, TRUE); return CheckAndFixDangerousPaths(m_filePathAndName.CStr(), isURL); } OP_STATUS WebserverFileName::Construct(const char *path, int length, BOOL isURL) { if (path == NULL) { return OpStatus::ERR; } const char *localPath = path; if (localPath[0] == '\"') { localPath = &path[1]; length--; } if (path[length] == '\"') { length--; } RETURN_IF_ERROR(m_filePathAndName.SetFromUTF8(localPath, length)); m_filePathAndName.Strip(TRUE, TRUE); return CheckAndFixDangerousPaths(m_filePathAndName.CStr(), isURL); } OP_STATUS WebserverFileName::Construct(const OpStringC &path) { return Construct(path.CStr(), path.Length(), FALSE); } OP_STATUS WebserverFileName::Construct(const OpStringC8 &path) { return Construct(path.CStr(), path.Length(), FALSE); } OP_STATUS WebserverFileName::ConstructFromURL(const OpStringC &path) { return Construct(path.CStr(), path.Length(), TRUE); } OP_STATUS WebserverFileName::ConstructFromURL(const OpStringC8 &path) { return Construct(path.CStr(), path.Length(), TRUE); } #ifdef _DEBUG BOOL WebserverFileName::DebugIsURLAcceptable(const char *filePathAndName, const char *expected) { OpString url; if (OpStatus::IsError(url.Set(filePathAndName))) return FALSE; OP_STATUS ops=CheckAndFixDangerousPaths(url.CStr(), TRUE); if(expected && OpStatus::IsSuccess(ops)) return !url.Compare(expected); return OpStatus::IsSuccess(ops); } BOOL WebserverFileName::DebugIsURLInAcceptable(const char *filePathAndName, const char *expected) { OpString url; if (OpStatus::IsError(url.Set(filePathAndName))) return FALSE; OP_STATUS ops=CheckAndFixDangerousPaths(url.CStr(), TRUE); if(expected && OpStatus::IsError(ops)) return !url.Compare(expected); return OpStatus::IsError(ops); } #endif // _DEBUG #endif //WEBSERVER_SUPPORT
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ // seed srand(time(NULL)); // 이게 선언된 다음 부터는 time(NULL) 안에 들어있는 seed 값에 따라서 난수가 발생한다. for(int i=1; i<=10; i++){ printf("%d\n", rand()%10); } }
#pragma once #include "game.h" #define HEIGHT 6 #define WIDTH 7 #define LENGTH 4 class ConnectXGame : public Game { public: ConnectXGame(void); ~ConnectXGame(void); void initialize(void); };
// Created on: 1993-10-29 // Created by: Christophe MARION // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRAlgo_PolyHidingData_HeaderFile #define _HLRAlgo_PolyHidingData_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Integer.hxx> //! Data structure of a set of Hiding Triangles. class HLRAlgo_PolyHidingData { public: DEFINE_STANDARD_ALLOC struct TriangleIndices { Standard_Integer Index, Min, Max; }; struct PlaneT { PlaneT() : D(0.0) {} gp_XYZ Normal; Standard_Real D; }; HLRAlgo_PolyHidingData() { } void Set ( const Standard_Integer Index, const Standard_Integer Minim, const Standard_Integer Maxim, const Standard_Real A, const Standard_Real B, const Standard_Real C, const Standard_Real D) { myIndices.Index = Index; myIndices.Min = Minim; myIndices.Max = Maxim; myPlane.Normal = gp_XYZ(A, B, C); myPlane.D = D; } TriangleIndices& Indices() { return myIndices; } PlaneT& Plane() { return myPlane; } private: TriangleIndices myIndices; PlaneT myPlane; }; #endif // _HLRAlgo_PolyHidingData_HeaderFile
#ifndef SRC_SAMPLER_H #define SRC_SAMPLER_H #include <algorithm> #include <cstdlib> #include <numeric> #include <random> #include <utility> #include <vector> #include "src/util.h" class BaseSampler { public: BaseSampler( std::vector<std::pair<size_t, double> >& data_weights ); virtual ~BaseSampler(); public: virtual void seed(unsigned val); virtual size_t sampling() = 0; protected: std::default_random_engine rand_generator_; }; class AliasSampler : public BaseSampler { public: AliasSampler( std::vector<std::pair<size_t, double> >& data_weights ); virtual ~AliasSampler(); public: size_t sampling(); protected: bool Init( std::vector<std::pair<size_t, double> >& data_weights ); size_t draw(); private: std::vector<size_t> alias_; std::vector<double> alias_prob_; std::vector<size_t> data_index_; std::uniform_int_distribution<size_t> uniform_int_dist_; std::uniform_real_distribution<double> uniform_real_dist_; }; class MultinomialSampler : public BaseSampler { public: MultinomialSampler( std::vector<std::pair<size_t, double> >& data_weights ); virtual ~MultinomialSampler(); public: size_t sampling(); protected: double random_impl(); protected: std::uniform_real_distribution<double> uniform_dist_; private: std::vector<double> multinomial_dist_; std::vector<size_t> data_index_; }; class RandomSampler : public BaseSampler { public: RandomSampler( std::vector<std::pair<size_t, double> >& data_weights ); virtual ~RandomSampler(); public: virtual size_t sampling(); protected: std::uniform_int_distribution<size_t> uniform_dist_; std::vector<size_t> data_index_; }; #endif // SRC_SAMPLER_H /* vim: set ts=4 sw=4 tw=0 et :*/
#include "stdafx.h" #include "CheckDxccCountry.h" #include "DxccCountryManager.h" #include "DxccCountry.h" #include "StringUtils.h" bool CheckDxccCountry(string arg, DxccCountryManager* dxccCountryManager) { string key; string callsign; string errorMsg; bool status = StringUtils::GetKeyValuePair(arg, key, callsign, errorMsg); if (!status) { printf("Error in CheckDxccCountry: %s\n", errorMsg.c_str()); return false; } string country; status = dxccCountryManager->FindCountryName(callsign, country); if (status) { printf("Callsign '%s' corresponds to DXCC country '%s'\n", callsign.c_str(), country.c_str()); } else { printf("Unable to locate country for callsign '%s'\n", callsign.c_str()); } return status; }
#include "SDL2.hpp" #include<string.h> #include<iostream> #pragma once class Scene { public: Scene(std::string name); std::string getName(void); virtual void events(const float &delta, const Dimension<int> &screen, const SDL_Event& evnt) = 0; virtual void update(const float &delta, const Dimension<int> &screen) = 0; virtual void render(const float &delta, const Dimension<int> &screen) = 0; private: std::string m_name; };
/* Copyright 2021 University of Manchester 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 "simple_plan_evaluator.hpp" #include <set> #include <stdexcept> using orkhestrafs::dbmstodspi::SimplePlanEvaluator; // Naive best plan chooser where just simply the plan with min runs, max nodes // and min configuration overhead is chosen // (TODO:module reuse isn't considered) auto SimplePlanEvaluator::GetBestPlan( int min_run_count, const std::vector<ScheduledModule>& /*last_configuration*/, const std::string /*resource_string*/, double /*utilites_scaler*/, double /*config_written_scaler*/, double /*utility_per_frame_scaler*/, const std::map<std::vector<std::vector<ScheduledModule>>, ExecutionPlanSchedulingData>& plan_metadata, const std::map<char, int>& /*cost_of_columns*/, double /*streaming_speed*/, double /*configuration_speed*/) -> std::tuple<std::vector<std::vector<ScheduledModule>>, std::vector<ScheduledModule>, long, long> { std::tuple<std::vector<std::vector<ScheduledModule>>, std::vector<ScheduledModule>, long, long> best_plan; int max_nodes_in_min_plan = 0; int min_configured_rows_in_min_plan = 0; std::vector<std::vector<std::vector<ScheduledModule>>> all_plans_list; all_plans_list.reserve(plan_metadata.size()); for (const auto& [plan, _] : plan_metadata) { all_plans_list.push_back(plan); } for (auto& plan_index : all_plans_list) { if (plan_index.size() == min_run_count) { int configured_rows = 0; std::set<std::string> unique_node_names; for (int run_index = 0; run_index < plan_index.size(); run_index++) { for (const auto& chosen_module : plan_index.at(run_index)) { unique_node_names.insert(chosen_module.node_name); configured_rows += chosen_module.position.second - chosen_module.position.first + 1; } if (unique_node_names.size() > max_nodes_in_min_plan) { max_nodes_in_min_plan = unique_node_names.size(); min_configured_rows_in_min_plan = configured_rows; best_plan = {plan_index, {}, 0, 0}; } else if (unique_node_names.size() == max_nodes_in_min_plan && configured_rows < min_configured_rows_in_min_plan) { min_configured_rows_in_min_plan = configured_rows; best_plan = {plan_index, {}, 0, 0}; } } } } if (std::get<0>(best_plan).empty()) { throw std::runtime_error("No plan chosen!"); } return best_plan; }
//$$---- Thread CPP ---- //--------------------------------------------------------------------------- #include <vcl.h> #include <math.h> #include <algorith.h> #include <stdio.h> #pragma hdrstop #include "RecordThrd.h" #include "PredStart.h" #include "BuildProtocol.h" #include "CalcParams.h" #include "Gistograms.h" #include "MinorChannel.h" #include "ExperimentNotes.h" #pragma package(smart_init) //--------------------------------------------------------------------------- IADCDevice *r_pADC;//указатель на интерфейс драйвера IADCUtility *r_pUtil;//интерфейс драйвера ADCParametersDMA r_a;//структура параметров устройства trac *rSignals;//структура с сигналами и параметрами trac *rSpntSignals;//структура с сигналами и параметрами bool rAppEndData;//выбрано ли создание файла с возможностью дозаписи __int32 rBlockSize,//размер блока данных rStimPrd,//период стимуляции (миллисекунды) rSpntRecLen,//длина спонтанного сигнала в отсчётах (для режима №4) rTimeBgn,//момент начала сигнала (микросекунды) specK1,//специальная переменная для передачи номера1 //номер сигнала, с которого начинаются неотрисованные сигналы specK2,//специальная переменная для передачи номера2 //количество неотрисованных сигналов rPreTime,//начало пресин. ответа (микросекунды) rPostTime,//начало постсин. ответа (микросекунды) rTotNumOfS,//заданное к сбору число сигналов в эксперименте rRealNumOfS,//действительное число записанных сигналов rCountlm,//счётчик для перебора элементов выборки при расчёте локального среднего rSamps,//количество отсчётов принятых для вычисления локального среднего *rInstr,//массив с инструкцией (протокол стимуляции) rReadOrder[maxChannels];//массив с последовательностью чтения каналов __int64 rNextTic,//момент (в тактах процессора) подачи следующего синхроимпульса rBeginTakt;//такт процессора, при котором начинается вополнение сценария short rTypeOfExp,//тип эксперимента rConstMinus,//вычитание постоянной составляющей rPorog,//пороговое напряжение (отсчёты) rPolarity,//полярность сигнала *rExtractLocMean;//массив выборки (extract) локального среднего double rLocMean[maxChannels],//локальное среднее на всех каналах; 5 - с запасом (нужно для нивелирования постоянной составляющей входного сигнала) *rmGrafik,//график для рисования *rmGrafikM;//график для рисования спонтанных сигналов (в режиме №4) FILE *rDiscontinFile;//хэндл файла, в который сохраняются данные (при прерывистом сборе) //--------------------------------------------------------------------------- __fastcall TRecordThread::TRecordThread(bool CreateSuspended) : TThread(CreateSuspended) { //Graphs->CrntSig->Tag - глобальный счётчик сигналов //PStart->closeWin->Tag - управляет прерыванием сбора и функцией кнопки останова-закрытия rmGrafik = NULL;//график для рисования rmGrafikM = NULL;//график для рисования спонтанных сигналов (в режиме №4) } //--------------------------------------------------------------------------- void TRecordThread::AssignVar(short eTyp, IADCUtility *preUtil, IADCDevice *preADC) { __int32 i, k; rTypeOfExp = eTyp;//тип эксперимента r_pUtil = preUtil;//ссылка на интерфейс r_pADC = preADC;//ссылка на интерфейс r_a = Experiment->a;//структура параметров устройства rStimPrd = StrToInt(Experiment->StimPeriod->Text);//период стимуляции (миллисекунды) rBlockSize = Experiment->dmaBlockSize;//размер блока данных chanls = Experiment->a.m_nChannelNumber;//количество сканируемых каналов discrT = StrToFloat(Experiment->DiscreTime->Text);//время дискретизации (микросекунды) effDT = discrT * (float)chanls;//эффективное время дискретизации if (eTyp == 1)//спонтанные сигналы recLen = (__int32)floor((float(StrToInt(PStart->LenSpont->Text) * 1000) / effDT) + 0.5);//длина развёртки сигнала (отсчёты) else//остальные recLen = (__int32)floor((float(StrToInt(PStart->SignalLen->Text) * 1000) / effDT) + 0.5);//длина развёртки сигнала (отсчёты) multiCh = Experiment->RecMode->Checked;//режим сбора данных (true = многоканальный) ftChan = 1 + (chanls - 1) * (__int32)multiCh;//количество каналов с полными развёртками (full trace channels) sampl2mV = Experiment->maxVoltage / float(Experiment->maxADCAmp * r_a.m_nGain);//коэффициент перевода амплитуд из отсчётов АЦП в (милли)вольты eds = Experiment->eds;//маска для выделения кода цифрового порта (0xF = 15(dec) = 0000000000001111(bin)) bwSh = Experiment->bwSh;//величина побитового сдвига при выделении кода АЦП //копирование атрибутов сигналов (для использования в модулях Graphs) Graphs->multiCh = multiCh;//режим сбора данных (true = многоканальный) Graphs->recLen = recLen;//длина развёртки сигнала (отсчёты) Graphs->discrT = discrT;//время дискретизации (микросекунды) Graphs->chanls = chanls;//количество сканируемых каналов Graphs->ftChan = ftChan;//количество каналов с полными развёртками (full trace channels) Graphs->effDT = effDT;//эффективное время дискретизации = discrT * chanls Graphs->sampl2mV = sampl2mV;//коэффициент перевода амплитуд из отсчётов АЦП в милливольты = maxVoltage/(maxADCAmp * ADCGain) Graphs->gRF[0] = 0;//номер первого отображаемого канала Graphs->gRF[1] = ftChan;//номер последнего отображаемого канала + 1 rConstMinus = (short)PStart->NulMinus->Checked;//вычитание постоянной составляющей rPolarity = -1 + (2 * __int32(!PStart->Invert->Checked));//полярность сигнала k = 0;//задаём порядок чтения каналов (циклический перебор) for (i = Experiment->uiLeadChan->ItemIndex; i < chanls; i++) { rReadOrder[k] = i; k++; } for (i = 0; i < Experiment->uiLeadChan->ItemIndex; i++) { rReadOrder[k] = i; k++; } //выставим множители для "быстрых" графиков for (i = 0; i < maxChannels; i++) { Graphs->curntSigChannls[i]->XValues->Multiplier = double(effDT) / 1000; PStart->exmplChannls[i]->XValues->Multiplier = double(effDT) / 1000; } } //--------------------------------------------------------------------------- void __fastcall TRecordThread::RecSynchroPlotExampl(void) { //вызов прорисовки эталонного сигнала //PlotStandardSignal(double *sData, __int32 sRecLen, __int32 sEffDT, __int32 sIndBgn) PStart->PlotStandardSignal(rmGrafik, recLen, effDT, (rTimeBgn / effDT));//рисование эталонного сигнала PStart->RefreshLines(effDT);//обновление ПРЕ- ПОСТ-линий } //--------------------------------------------------------------------------- void __fastcall TRecordThread::RecSynchroCounter(void) { //выводим номер текущего сигнала Graphs->CrntSig->Text = IntToStr(Graphs->CrntSig->Tag);//счётчик сигналов } //--------------------------------------------------------------------------- void __fastcall TRecordThread::MiniSynchroPlotGraphs(void) { //рисование спонтанных сигналов __int32 j, *mspIndex = NULL;//массив индексов //текущий сигнал Graphs->PlotCurrentSignal(rmGrafik, 0); //создадим массив индексов //specK1 = k - kRefresh;//номер сигнала, с которого начинаются необработанные сигналы //specK2 = kRefresh;//количество неотрисованных сигналов mspIndex = new __int32[specK2]; for (j = 0; j < specK2; j++) mspIndex[j] = j + specK1; //рассчитаем параметры сигналов Calculate(rSignals, specK2, rPorog, rPreTime, rPostTime, mspIndex, rTypeOfExp, false, NULL); Graphs->AddParamsPoints(rSignals, specK2, mspIndex, rTypeOfExp);//вывод параметров, добавляем точки на графиках delete[] mspIndex; mspIndex = NULL; Gists->GistsRefresh(-1);//перерисовываем гистограммы } //--------------------------------------------------------------------------- void __fastcall TRecordThread::InducSynchroPlotter(void) { //рисование вызванных сигналов __int32 j, *ispIndex,//массив индексов shft1,//номер первого элемента для ampls и peakInds shft2;//номер первого элемента для spans ispIndex = NULL; //рисование текущего сигнала if (rmGrafik && (specK2 == 1)) Graphs->PlotCurrentSignal(rmGrafik, (rTimeBgn / effDT)); //создадим массив индексов //specK1 - номер сигнала, с которого начинаются необработанные сигналы //specK2 - количество неотрисованных сигналов ispIndex = new __int32[specK2]; for (j = 0; j < specK2; j++)//добавление нескольких точек сразу ispIndex[j] = j + specK1;// * (__int32)(!rAppEndData); //рассчитаем параметры if (PStart->GetASignal->Tag != 1)//если идёт запись, то рисуем графики { Calculate(rSignals, specK2, rPorog, rPreTime, rPostTime, ispIndex, rTypeOfExp, false, NULL); shft1 = (3 * ftChan * ispIndex[specK2 - 1]) + (3 * 0);//номер первого элемента для ampls и peakInds shft2 = (5 * ftChan * ispIndex[specK2 - 1]) + (5 * 0);//номер первого элемента для spans Graphs->AddParamsPoints(rSignals, specK2, ispIndex, rTypeOfExp);//добавим точки на графики j = Graphs->sigAmpls[Graphs->gRF[0]]->YValues->Count() - 1;//номер последней добавленной на график точки Graphs->HighLightCrnt(&rSignals[ispIndex[specK2 - 1]], shft1, shft2, rTypeOfExp, (rTimeBgn / effDT), j);//подсвечивание } delete[] ispIndex; ispIndex = NULL; } //--------------------------------------------------------------------------- void __fastcall TRecordThread::MiniMd4SynchroPlot(void) { //рисование спонтанных сигналов в режиме №4 Graphs->PlotCurrentSignal(rmGrafikM, 0);//рисование текущего сигнала } //--------------------------------------------------------------------------- void __fastcall TRecordThread::FromMinorChan(void) { //вывод данных со второстепенных каналов __int32 i, j; if ((chanls > 1) && !multiCh)//количество каналов больше одного и не многоканальный режим { j = (Graphs->CrntSig->Tag - 1);//номер сигнала for (i = 0; i < (chanls - 1); i++) SecondChan->MChann[i]->Text = IntToStr((__int32)floor(rSignals[j].s[recLen + i] * sampl2mV)); } } //--------------------------------------------------------------------------- void __fastcall TRecordThread::CallForClearMemor(void) { //защищённое удаление данных из памяти (используется для режима №4) Graphs->ClearMemor(this);//удаление всех старых данных из памяти } //--------------------------------------------------------------------------- void __fastcall TRecordThread::CallForReplotGraphs(void) { //защищённый вызов функций прорисовк после сохранения Graphs->ResetVisibility();//запускаем прорисовку Graphs->FillParamTable();//заполняем таблицу значениями параметров } //--------------------------------------------------------------------------- void __fastcall TRecordThread::Execute() { //сбор данных (запись пробного сигнала или запуск сценария) __int32 i, *index1,//указатель на индексы для Calculate pp,//количество пунктов протокола стимуляции (количество инструкций) totNumOfSpontS,//максимальное число спонтанных сигналов realNumOfSpontS,//количество собранных спонтанных сигналов maxStimPrd,//максимальный период стимуляции в протоколе (для режима №4) inducRecLen;//копия длины вызванного сигнала TDateTime CurrentDateTime;//текущие дата и время AnsiString memoFlNm,//копия имени файла extendFlNm;//расширенное имя файл (для режима №4) SPPanel *panel; sPr *evkPrm;//копия указателя на структуру с параметрами вызванных сигналов while (!Terminated) { //убираем кнопки на время эксперимента PStart->GetASignal->Enabled = false;//пример сигнала PStart->StartRec->Enabled = false;//старт PStart->Invert->Enabled = false;//инверсия сигнала PStart->NulMinus->Enabled = false;//вычет ноль-линии PStart->SignalLen->Enabled = false;//длина сигнала PStart->LenSpont->Enabled = false;//длина спонтанного сигнала PStart->BackTime->Enabled = false;//время назад для спонтанного сигнала PStart->CloseWin->Caption = "Стоп";//меняем "функцию" кнопки PStart->CloseWin->Tag = 0;//меняем функцию кнопки Graphs->SigNumUpDwn->Enabled = false;//также нельзя переключать сигналы Graphs->gphOpen->Enabled = false;//запрет на открытие файлов во вермя записи Experiment->beginFOpen->Enabled = false;//запрет на открытие файлов во вермя записи Experiment->verticalScal->Enabled = false;//запрет на изменение масштаба вертикальной шкалы Experiment->timScal->Enabled = false;//запрет на изменение масштаба горизонтальной шкалы Experiment->DiscreTime->Enabled = false;//время дискретизации нельзя менять во время записи Graphs->SignalTrack->OnMouseDown = NULL;//запрещаем реагировать на клики (meanSignalMouseDown) //определим сколько сигналов нужно собрать if (PStart->GetASignal->Tag == 1)//пример сигнала (делаем протокол по умолчанию) { pp = 1;//количество пунктов протокола стимуляции (количество инструкций) rInstr = new __int32[3 * pp];//массив для инструкций (протокол стимуляции) rTotNumOfS = 1;//один пробный импульс rInstr[0] = 1;//стимуляция rInstr[1] = rTotNumOfS;//один пробный импульс rInstr[2] = rStimPrd; } else { if (ProtoBuild->InstructBox->ComponentCount <= 0)//протокол не задан { pp = 1;//количество пунктов протокола стимуляции (количество инструкций) rInstr = new __int32[3 * pp];//массив для инструкций (протокол стимуляции) rTotNumOfS = StrToInt(Experiment->NumOfsignals->Text); rInstr[0] = 1; rInstr[1] = rTotNumOfS; rInstr[2] = rStimPrd; } else//если задан протокол { pp = ProtoBuild->InstructBox->ComponentCount;//количество пунктов протокола стимуляции (количество инструкций) rInstr = new __int32[3 * pp];//массив для инструкций (протокол стимуляции) rTotNumOfS = 0;//пролистаем протокол стимуляции и подсчитаем общее количество сигналов for (i = 0; i < pp; i++) { panel = (SPPanel*)ProtoBuild->InstructBox->Components[i]; rInstr[(i * 3) + 0] = panel->iType;//тип инструкции rInstr[(i * 3) + 1] = panel->scCount;//количество импульсов или повторений в цикле rInstr[(i * 3) + 2] = panel->period;//период следования импульсов или длительность паузы if (rInstr[(i * 3) + 0] == 1)//если стимул, считаем сколько импульсов rTotNumOfS += rInstr[(i * 3) + 1]; if (rInstr[(i * 3) + 0] == 3)//если цикл, умножаем на кол-во проходов rTotNumOfS = rTotNumOfS * rInstr[(i * 3) + 1]; } } } //определим заранее параметр рисования rTimeBgn rPorog = short((float)StrToInt(PStart->Porog->Text) / sampl2mV);//пороговое напряжение (отсчёты) rPreTime = StrToInt(PStart->PreTime->Text); rPostTime = StrToInt(PStart->PostTime->Text); //выбираем индекс, с которого смотрим (рисуем) сигнал (после синхоимпульса) rTimeBgn = 0; if (rTypeOfExp == 3)//вызванные - внеклеточные rTimeBgn = rPreTime; else if (rTypeOfExp == 2)// (внутриклеточные) или rTypeOfExp = 4 (смешанные) rTimeBgn = rPostTime; PStart->timeOfDrawBgn = (float)rTimeBgn;//передаём значение индекса-начала в модуль PStart //выбран ли режим прерывистого сбора (с возможностью дозаписи) //если получаем пример сигнала, то действуем традиционным образом rAppEndData = ((Experiment->DiscontinWrt->Checked) && (PStart->GetASignal->Tag != 1));//непрерывная запись (не пример сигнала) if (rAppEndData)//способ записи данных CreatExtendFile();//создать или продолжить файл в прерывистом режиме if ((rTypeOfExp != 4) || (PStart->GetASignal->Tag == 1))//любой, кроме вызванные+спонтанные { rSignals = Graphs->CreatStructSignal(rTotNumOfS, recLen);//структура с сигналами и их атрибутами totNumOfSpontS = 0;//количество спонтанных сигналов в режиме №4 } else// if (rTypeOfExp == 4)//одновременный сбор вызванных и спонтанных; в rSignals записываем и вызванные и спонтанные { //создадим дополнительную структуру для хранения спонтанных сигналов if (ProtoBuild->InstructBox->ComponentCount > 0) { maxStimPrd = 0;//наибольший интервал между импульсами стимуляции для расчёта totNumOfSpontS for (i = 0; i < pp; i++) if ((rInstr[(i * 3) + 0] == 1) && (rInstr[(i * 3) + 2] > maxStimPrd)) maxStimPrd = rInstr[(i * 3) + 2];//запоминаем наибольший интервал } else maxStimPrd = StrToInt(Experiment->StimPeriod->Text);//наибольший интервал между импульсами стимуляции inducRecLen = Graphs->recLen;//копия длины вызванного сигнала rSpntRecLen = floor((float(StrToFloat(PStart->LenSpont->Text) * 1000) / effDT) + 0.5);//длина спонтанного сигнала в режиме №4 (отсчёты) rmGrafikM = new double[rSpntRecLen * ftChan];//график для рисования спонтанных сигналов (в режиме №4) //totNumOfSpontS - максимально возможное количество спонтанных сигналов в режиме №4 totNumOfSpontS = rTotNumOfS * (floor(0.5 * maxStimPrd / StrToInt(PStart->LenSpont->Text)) + 1);//(предельное) количество спонтанных сигналов if (totNumOfSpontS > limitSigNum)//ограничение на количество спонтанных сигналов, собираемых в режиме №4 totNumOfSpontS = limitSigNum;//указываем предельное количество спонтанных сигналов rSignals = Graphs->CreatStructSignal(rTotNumOfS, recLen);//структура с вызванными сигналами evkPrm = Graphs->cPrm;//копия указателя на структуру с параметрами вызванных сигналов rSpntSignals = Graphs->CreatStructSignal(totNumOfSpontS, rSpntRecLen);//структура со спонтанными сигналами } rmGrafik = new double[recLen * ftChan];//график для рисования GetLocalMean();//вычисляем начальное среднее //-------------------------------------------------------------------- //--- запуск одного из вариантов сбора данных ------------------------ StartRec(rTotNumOfS, totNumOfSpontS, pp);//запускаем сценарий //-------------------------------------------------------------------- //после сбора данных: сохранение, вывод на экран и т.д. rRealNumOfS = Graphs->CrntSig->Tag;//количество действительно записанных вызванных сигналов realNumOfSpontS = PStart->BackTime->Tag;//количество действительно записанных спонтанных сигналов Graphs->SigNumUpDwn->Tag = rTotNumOfS;//копируем исходное число сигналов (понадобится при удалении) if (rRealNumOfS >= 1)//если сигналы имеются { if (PStart->GetASignal->Tag == 1)//если выбрана запись пробного сигнала { index1 = new __int32[1]; index1[0] = 0; //рассчитаем параметры и покажем их //Calculate(trac *sgnl, __int32 numOfS, short porog, __int32 preTime, __int32 postTime, // __int32 *inds, short expT, bool newNull, sPr *avrP) Calculate(rSignals, rRealNumOfS, rPorog, rPreTime, rPostTime, index1, rTypeOfExp, false, NULL); delete[] index1; index1 = NULL; Synchronize(&RecSynchroPlotExampl);//вывод сигнала в окно предстарта//построение примера } else if (!rAppEndData)//сохранение эксперимента PStart->getASignal->Tag = 2 { if (rTypeOfExp == 4)//вызванные + спонтанные { memoFlNm = Graphs->SaveDlg->FileName;//резервная копия текущего имени //сначала сохраняем спонтанные сигналы if (realNumOfSpontS >= 1)//есть спонтанные сигналы { extendFlNm = memoFlNm;//вновь записываем исходное имя файла extendFlNm.Insert("_Spont", extendFlNm.Length() - 3);//подправляем имя файла, чтобы сохранить спонтанныесигналы Graphs->SaveDlg->FileName = extendFlNm;//окончательное имя файла со спонтанными сигналами Graphs->SigNumUpDwn->Tag = totNumOfSpontS;//копируем исходное число сигналов (понадобится при удалении) Graphs->recLen = rSpntRecLen;//временно указываем длину спонтанного сигнала i = (__int32)Graphs->SaveExpDataToFile(5, rSpntSignals, realNumOfSpontS, true);//тип эксперимента Graphs->recLen = inducRecLen;//вновь указываем длину вызванного сигнала } else//нет спонтанных сигналов Experiment->DevEvents->Text = "нет спонтанных сигналов";//сигналов не обнаружено Graphs->DeleteStructSignal(rSpntSignals, totNumOfSpontS);//освобождаем память, если нет сохранения rSpntSignals = NULL;//структура удалена в модуле Graphs->ClearMemor //сохраняем отдельно вызванные сигналы (считаем их внутриклеточными, №2) extendFlNm = memoFlNm;//резервная копия текущего имени extendFlNm.Insert("_Induced", extendFlNm.Length() - 3);//подправляем имя файла, чтобы сохранить вызванные сигналы Graphs->SaveDlg->FileName = extendFlNm;//окончательное имя файла с вызванными сигналами Graphs->cPrm = evkPrm;//копия указателя на структуру с параметрами вызванных сигналов Graphs->SigNumUpDwn->Tag = rTotNumOfS;//копируем исходное число сигналов (понадобится при удалении) if (Graphs->SaveExpDataToFile(2, rSignals, rRealNumOfS, true))//сохранение прошло нормально Synchronize(&CallForReplotGraphs);//защищённая прорисовка либо вызванных либо спонтанных сигналов Graphs->SaveDlg->FileName = memoFlNm;//восстанавливаем имя файла } else if (Graphs->SaveExpDataToFile(rTypeOfExp, rSignals, rRealNumOfS, true))//сохранение данных Synchronize(&CallForReplotGraphs);//защищённая прорисовка сигналов } } else Experiment->DevEvents->Text = "нет сигналов"; //удаление структуры с сигналами в случаях, когда нет стандартного (pra) сохранения данных if ((rRealNumOfS < 1) || (PStart->GetASignal->Tag == 1) || rAppEndData)//нет сигналов или выбран пример сигнала или непрерывная запись { Graphs->DeleteStructSignal(rSignals, rTotNumOfS);//освобождаем память, если нет сохранения } rSignals = NULL;//обнуляем указатель delete[] rInstr; rInstr = NULL;//удалем массив с инструкциями if (rAppEndData)//прерывистая запись CompleteDisconFile();//закрытие файла прерывистой записи delete[] rmGrafik; rmGrafik = NULL;//удаление графика для рисования if (rmGrafikM) { delete[] rmGrafikM; rmGrafikM = NULL;//удаление графика для рисования спонтанных сигналов (в режиме №4) } delete[] rExtractLocMean; rExtractLocMean = NULL;//удаление массива с локальным средним //восстанавливаем кнопки PStart->GetASignal->Enabled = true;//кнопк апример сигнала PStart->StartRec->Enabled = true;//кнопка старта PStart->Invert->Enabled = true;//кнопка инверсии сигнала PStart->NulMinus->Enabled = true;//вычет ноль-линии PStart->SignalLen->Enabled = true;//длина сигнала PStart->LenSpont->Enabled = true;//длина спонтанного сигнала PStart->BackTime->Enabled = true;//время назад для спонтанного сигнала PStart->CloseWin->Caption = "Закрыть";//меняем "функцию" кнопки PStart->CloseWin->Tag = 1;//меняем функцию кнопки ExpNotes->addUMark->Enabled = true;//разрешаем добавление коментариев (окно ввода текста) Graphs->gphOpen->Enabled = true;//разрешаем открывать файлы Experiment->beginFOpen->Enabled = true;//разрешаем открывать файлы Experiment->verticalScal->Enabled = true;//запрет на изменение масштаба вертикальной шкалы Experiment->timScal->Enabled = true;//запрет на изменение масштаба горизонтальной шкалы Experiment->DiscreTime->Enabled = true;//время дискретизации снова можно менять Graphs->SignalTrack->OnMouseDown = Graphs->SignalTrackMouseDown;//разрешаем реагировать на клики Suspend();//ставим поток на паузу } } //--------------------------------------------------------------------------- void TRecordThread::CreatExtendFile() { //создать или продолжить файл в прерывистом режиме __int32 itemWrtRd,//количество прочитанных единиц (не байт) amountOfBytes,//количество байт, записываемых в данном блоке backTimeMini;//время назад для спонтанных сигналов TDateTime CurrentDateTime;//текущие дата и время AnsiString progDate;//информация о программе и дате создания файла (для прерывистого режима) char lett[3];//символ-маркер (терминальная запись в файл; прерывистый режим) CurrentDateTime = Now();//текущие дата и время //создаём-открываем файл для чтения-записи //rDiscontinFile = CreateFile(Graphs->SaveDlg->FileName.c_str(), FILE_ALL_ACCESS, 0, 0, OPEN_ALWAYS, 0, 0); if ((FileExists(Graphs->SaveDlg->FileName)) && (Experiment->DiscontinWrt->Tag == 1)) //существует ли файл { progDate = "\nED:";//разделитель между сеансами сбора данных (дозапись в существующий файл) progDate += CurrentDateTime.DateTimeString().c_str(); rDiscontinFile = fopen(Graphs->SaveDlg->FileName.c_str(), "ab+");//открываем для чтения и дозаписи itemWrtRd = fseek(rDiscontinFile, 0, SEEK_END);//идём в конец файла } else { //создадим заголовок файла и впишем его progDate = "ElphAcqu v" + progVer + "\nmade";//~18 символов progDate += CurrentDateTime.DateTimeString().c_str();//19 символов progDate += "\nExpandable file"; rDiscontinFile = fopen(Graphs->SaveDlg->FileName.c_str(), "wb");//открываем для записи } amountOfBytes = sizeof(char) * progDate.Length();//количество байт, записываемых в данном блоке amountOfBytes += sizeof(bool) + (3 * sizeof(char)) + (5 * sizeof(__int32)) + sizeof(short) + sizeof(float); //вписываем заголовок или разделитель itemWrtRd = fwrite(progDate.c_str(), sizeof(char), progDate.Length(), rDiscontinFile); amountOfBytes -= itemWrtRd * sizeof(char); lett[0] = 'P'; lett[1] = 'r'; lett[2] = 'M';//указывает на начало блока параметров данного сеанса itemWrtRd = fwrite(&lett, sizeof(char), 3, rDiscontinFile);//вписываем маркер amountOfBytes -= itemWrtRd * sizeof(char); //переменные, уникальные для данного сеанса (т.е. все необходимые параметры) /* последовательность записи обязательных параметров multiCh -------(1) - режим сбора данных (true = многоканальный) recLen --------(2) - длина развёртки сигнала (отсчёты) discrT --------(3) - время дискретизации chanls --------(4) - количество сканируемых каналов E->adcGain ----(5) - коэффициент усиления experimentType (6) - тип эксперимента, глобальный вариант E->maxVoltage -(7) - диапазон напряжений E->maxADCAmp --(8) - максимальная амплитуда (отсчёты) */ itemWrtRd = fwrite(&multiCh, sizeof(bool), 1, rDiscontinFile);//1//режим сбора данных (true = многоканальный) amountOfBytes -= itemWrtRd * sizeof(bool); itemWrtRd = fwrite(&recLen, sizeof(__int32), 1, rDiscontinFile);//2//длина развёртки сигнала в отсчётах amountOfBytes -= itemWrtRd * sizeof(__int32); itemWrtRd = fwrite(&discrT, sizeof(float), 1, rDiscontinFile);//3//время дискретизации amountOfBytes -= itemWrtRd * sizeof(__int32); itemWrtRd = fwrite(&chanls, sizeof(__int32), 1, rDiscontinFile);//4//количество сканируемых каналов amountOfBytes -= itemWrtRd * sizeof(__int32); itemWrtRd = fwrite(&r_a.m_nGain, sizeof(__int32), 1, rDiscontinFile);//5//коэффициент усиления amountOfBytes -= itemWrtRd * sizeof(__int32); itemWrtRd = fwrite(&rTypeOfExp, sizeof(short), 1, rDiscontinFile);//6//тип эксперимента, глобальный вариант amountOfBytes -= itemWrtRd * sizeof(short); itemWrtRd = fwrite(&Experiment->maxVoltage, sizeof(float), 1, rDiscontinFile);//7//диапазон напряжений amountOfBytes -= itemWrtRd * sizeof(float); itemWrtRd = fwrite(&Experiment->maxADCAmp, sizeof(__int32), 1, rDiscontinFile);//8//максимальная амплитуда (в отсчётах) amountOfBytes -= itemWrtRd * sizeof(__int32); if (amountOfBytes != 0) Experiment->DevEvents->Text = "ошибка начальной записи";//аварийный выход, видимо, можно не делать } //--------------------------------------------------------------------------- void TRecordThread::CompleteDisconFile() { //завершить файл в прерывистом режиме __int32 i, j, z, *pMarkNums,//номера точек с метками, которые нужно сохранить lettersNum,//длина текстовой записи amountOfBytes,//количество байт, записываемых в данном блоке itemWrtRd,//количество прочитанных единиц (не байт) comUserMarks;//общее количество меток пользователя AnsiString userText;//информация об эксперименте (вводит пользователь) char lett[3];//символ-маркер (терминальная запись в файл; прерывистый режим) bool *markerVsblt;//видимость меток на каналах //вписываем заметки по ходу эксперимента, если такие были /* последовательность записи в блоке с текстовыми данных lettersNum -(1) - длина текстовой записи comUserMakrs(2) - количество заметок по ходу эксперимента userText ---(3) - текст об эксперименте и заметке по ходу pointNums --(4) - массив с номерами точек с заметками */ //информация об эксперименте (вводит пользователь); userText = ExpNotes->usersNotes->Lines->Text.c_str(); comUserMarks = (ExpNotes->addUMark->Tag) - (ExpNotes->nmInRec);//количество меток, введённых в данном сеансе збора данных if (!userText.IsEmpty() || (comUserMarks > 0))//пользователь вводил текстовую информацию { //вставляем в переменную userText заметки по ходу эксперимента if (comUserMarks > 0)//пользователь вводил метки по ходу эксперимента { pMarkNums = new __int32[comUserMarks];//номера точек с метками, которые нужно сохранить markerVsblt = new bool[comUserMarks * ftChan];//видимость меток на каналах if (userText.IsEmpty()) userText = "\n\n\r\r\n\n";//разделитель else userText += "\n\n\r\r\n\n";//разделитель for (i = 0; i < ExpNotes->addUMark->Tag; i++)// { if (ExpNotes->theMarker->pointOnGraph >= ExpNotes->npNewRec)//метка создана в данном сеансе сбора данных { userText += ExpNotes->theMarker->textMark; userText += "||\n||"; } ExpNotes->theMarker = ExpNotes->theMarker->nextM;//переходим к следующей метке } } lettersNum = userText.Length();//длина текстовой записи amountOfBytes = (userText.Length() * sizeof(char)) + (3 * sizeof(char)) + //текстовая часть (2 * sizeof(__int32)) + //количество символов и меток ((comUserMarks * __int32(comUserMarks > 0)) * sizeof(__int32)) + //номера сигналов с метками ((comUserMarks * ftChan * __int32(comUserMarks > 0)) * sizeof(bool));//видимость меток на каналах lett[0] = 'M'; lett[1] = 'r'; lett[2] = 'k';//указывает на начало пользовательской информации itemWrtRd = fwrite(&lett, sizeof(char), 3, rDiscontinFile);//вписываем разделитель (Mrk) amountOfBytes -= itemWrtRd * sizeof(char); itemWrtRd = fwrite(&lettersNum, sizeof(__int32), 1, rDiscontinFile);//1//длина текстовой записи amountOfBytes -= itemWrtRd * sizeof(__int32); itemWrtRd = fwrite(&comUserMarks, sizeof(__int32), 1, rDiscontinFile);//2//количество заметок amountOfBytes -= itemWrtRd * sizeof(__int32); /* последовательность записи блоков в pra-файле: refToWrite[29] = userText.c_str();//ссылка на блок №1 refToWrite[30] = (__int32*)(ExpNotes->pointNums);//ссылка на блок №16 */ //сначала записываем сам текст, потом номера точек с метками itemWrtRd = fwrite(userText.c_str(), sizeof(char), userText.Length(), rDiscontinFile);//вписываем заметки пользователя amountOfBytes -= itemWrtRd * sizeof(char); //затем номера точек на графике с метками j = 0;//индекс в массиве pMarkNums for (i = 0; i < ExpNotes->addUMark->Tag; i++)//comUserMarks > 0 { if (ExpNotes->theMarker->pointOnGraph >= ExpNotes->npNewRec)//метка создана в данном сеансе сбора данных { pMarkNums[j] = ExpNotes->theMarker->pointOnGraph - ExpNotes->npNewRec; for (z = 0; z < ftChan; z++) markerVsblt[(j * ftChan) + z] = ExpNotes->theMarker->chanN[z];//видимость меток на каналах j++;//увеличиваем индекс в массиве pMarkNums } ExpNotes->theMarker = ExpNotes->theMarker->nextM;//переходим к следующей метке } if (comUserMarks > 0)//пользователь вводил метки по ходу эксперимента { itemWrtRd = fwrite(pMarkNums, sizeof(__int32), comUserMarks, rDiscontinFile);//вписываем номера сигналов с метками amountOfBytes -= itemWrtRd * sizeof(__int32); itemWrtRd = fwrite(markerVsblt, sizeof(bool), (comUserMarks * ftChan), rDiscontinFile);//вписываем видимость меток на каналах amountOfBytes -= itemWrtRd * sizeof(bool); delete[] pMarkNums; pMarkNums = NULL; delete[] markerVsblt; markerVsblt = NULL; } if (amountOfBytes != 0) Experiment->DevEvents->Text = "ошибка конечной записи"; } fclose(rDiscontinFile);//закрываем файл, в который сохраняли в прерывистом режиме rDiscontinFile = NULL; } //--------------------------------------------------------------------------- void TRecordThread::StartRec(__int32 allExcit, __int32 allSpont, __int32 pp) { //запуск сценария стимуляции /* allExcit - общее количество записываемых сигналов (в режимах №1, 2, 3) allSpont - количество собираемых спонтанных сигналов в режиме №4 pp - количество пунктов протокола стимуляции (количество инструкций) */ __int32 i, z, g, errC,//индикатора зависания s_cycls,//количество проходов по циклу в сценарии blockReady,//готовность блока данных notZero,//количество ненулей numOfS,//число сигналов startNum,//начало нумерации сигналов stimPrd;//период стимуляции __int64 curnttic, ticps;//нужно для слежки за временем bool canPlot;//разрешено ли рисовать (большое "свободное" время) clock_t experimBegin;//момент старта сценария (секунд от начала работы программы) unsigned short cH, cM, cS, cmS,//текущее время tH, tM, tS;//целевое время //запускаем сценарий здесь s_cycls = 1;//счётчик циклов (повторение сценария) Graphs->CrntSig->Tag = 0;//нумерация (сквозная) начинается с нуля PStart->BackTime->Tag = 0;//нумерация для спонтанных сигналов также сквозная if ((PStart->GetASignal->Tag != 1) && (ProtoBuild->StarTim->Checked))//не пример сигнала и ждать момента старта { tH = (unsigned short)StrToInt(ProtoBuild->HEdit->Text);//часы tM = (unsigned short)StrToInt(ProtoBuild->MEdit->Text);//минуты tS = (unsigned short)StrToInt(ProtoBuild->SEdit->Text);//секунды Now().DecodeTime(&cH, &cM, &cS, &cmS); while (((tH > cH) || (tM > cM) || (tS > cS)) && (PStart->CloseWin->Tag != 1) && (PStart->NextBlock->Tag != 1)) { Now().DecodeTime(&cH, &cM, &cS, &cmS); Sleep(100);//ждём десятую долу секунды } } z = 0;//индикатора зависания while ((!QueryPerformanceFrequency((LARGE_INTEGER *)&ticps)) && (z <= 2))//частота процессора z++; if (z > 2) { Experiment->DevEvents->Text = "не определена частота процессора"; return; } //rBeginTakt - такт процессора, при котором начинается вополнение сценария z = 0;//индикатора зависания while((!QueryPerformanceCounter((LARGE_INTEGER *)&rBeginTakt)) && (z <= 2)) z++; if (z > 2) { Experiment->DevEvents->Text = "ошибка QPcounter"; return; } experimBegin = clock() / 1000;//момент старта сценария (секунд от начала работы программы) QueryPerformanceCounter((LARGE_INTEGER *)&rNextTic);//момент старта следующего сбора (сразу совпадает с текущим временем) specK1 = Graphs->CrntSig->Tag;//=0//номер сигнала, с которого начинаются неотрисованные сигналы for (i = 0; (i < pp) && (PStart->CloseWin->Tag == 0); i++)//цикл перебора инструкций { if (rInstr[(i * 3) + 0] == 1)//пункт протокола стимуляции { numOfS = rInstr[(i * 3) + 1];//количество импульсов стимуляции (сигналов) stimPrd = rInstr[(i * 3) + 2];//период подачи импульсов стимуляции (миллисекунды) canPlot = bool((stimPrd - __int32(float(recLen * effDT) / 1000)) >= minFreeTime);//разрешено ли рисовать (большое "свободное" время) PStart->NextBlock->Tag = 0;//если устанавливается 1, то выходим из блока //запускаем стимуляцию и сбор данных в зависимости от типа эксперимента if (rTypeOfExp == 1)//спонтанные Spnt_SgnlAcquisition(numOfS, experimBegin);//спонтанные else if ((rTypeOfExp == 2) || (rTypeOfExp == 3))//вызванные { Induced_SgnlAcquisition(numOfS, stimPrd, canPlot);//только вызванные if (!canPlot && (PStart->GetASignal->Tag != 1))//рисовать нельзя и не пример сигнала { if (i < (pp - 1))//не последний блок if (rInstr[((i + 1) * 3) + 0] == 2)//следующий блок - пауза canPlot = bool((rInstr[((i + 1) * 3) + 2] - __int32(float(recLen * effDT) / 1000)) >= minFreeTime); if (canPlot) { specK2 = Graphs->CrntSig->Tag - specK1;//количество неотрисованных сигналов Synchronize(&InducSynchroPlotter);//добавляем точки на график specK1 = Graphs->CrntSig->Tag;//номер сигнала, с которого начинаются неотрисованные сигналы } } } else//(rTypeOfExp == 4)//вызванные + спонтанные Induced_N_Spnt_SgnlAcquis(allSpont, numOfS, stimPrd, canPlot);//вызванные + спонтанные startNum = Graphs->CrntSig->Tag;//продолжаем сквозную нумерацию QueryPerformanceCounter((LARGE_INTEGER *)&rNextTic);//момент (в тактах процессора) подачи следующего синхроимпульса } if (rInstr[(i * 3) + 0] == 2)//пауза (запускаем Sleep) { errC = 0;//индикатора зависания while ((!QueryPerformanceFrequency((LARGE_INTEGER *)&ticps)) && (errC <= 2))//частота процессора errC++; if (errC > 2) { Experiment->DevEvents->Text = "не определена частота процессора"; return; } rNextTic = rBeginTakt + (__int64(rSignals[startNum - 1].appear) * ticps) + (__int64(rInstr[(i * 3) + 2]) * (ticps / 1000));//момент (в тактах процессора) подачи следующего синхроимпульса //вариант с использованием Sleep(Х) до самого момента начала следующего сбора //if (rInstr[(i * 3) + 2] > 1500)//оставляем одну секунду для уточнения момента старта // Sleep(floor((rInstr[(i * 3) + 2] - 1000) + 0.5)); //вариант с циклом, внутри которого Sleep(50) (паузы точно длиннее, чем 5 мс) if (rInstr[(i * 3) + 2] > 1050)//если ждать больше одной секунды { while(!QueryPerformanceCounter((LARGE_INTEGER *)&curnttic)) {}; while((curnttic < (rNextTic - ticps)) && (PStart->CloseWin->Tag == 0))//прекращаем паузу на одну секунду раньше (rNextTic - ticps) { Sleep(50); while(!QueryPerformanceCounter((LARGE_INTEGER *)&curnttic)) {}; } } } if (rInstr[(i * 3) + 0] == 3)//цикл (повторение протокола сначала) if (s_cycls < rInstr[(i * 3) + 1]) { i = -1;//идём на начало списка инструкций (пока так, но можно переходить на заданную инструкцию) s_cycls++; } } } //--------------------------------------------------------------------------- void __fastcall TRecordThread::Induced_SgnlAcquisition(__int32 iNumOfS, __int32 iStimPrd, bool canPlot) { //сбор данных: вызванные, режимы №2 и №3 /* iNumOfS - число собираемых в данном блоке сигналов iStimPrd - период стимуляции в данном блоке (миллисекунды) canPlot - разрешено ли рисовать (большое "свободное" время) */ bool isSynchro;//обнаружен ли синхроимпульс short *drvData, convData[maxChannels];//содержит выделенный код АЦП для всех каналов (каналов не больше, чем maxChannels) unsigned short digitPort4;//значения старших четырёх битов входного цифрового порта (поиск синхроимпульсов) __int32 i, z, j, errC,//счётчик ошибок ik,//количество записанных сигналов kRefresh,//счётчик обновления (обновление гистограмм (для графиков по другому пока)) refreshNum,//период обновления гистограмм startNum,//нумерация сигналов в сложном протоколе продолжается и начинается с startNum stims,//количество выданных синхроимпульсов recorded,//счётчик записанных отсчётов blockReady,//готовность блока данных minorChanMean[maxChannels],//среднее на второстепенном канале во время регистрируемого всплеска impInterv,//нижняя граница значений межимпульсных интервалов (в отсчётах) sampRead;//число записанных отсчётов, начиная с момента возникновения синхроимпульса float waitTime;//длительность паузы (мкс) перед отключением синхроимпульса unsigned int mask;//хранит информацию о наложении данных __int64 *appear,//массив с временами подачи синхроимпульсов (в тактах процессора) totaltic,//общее число тактов процессора, отводимое для текущего сбора (по истечении этого времени выходим из цикла) tpp,//тактов за перод синхроимпульса tp1, curnttic,//текущий такт процессора ticps,//тактов в секунду (частота процессора) ticperiod,//тактов процессора за период стимуляции popravka;//авторегулировка частоты стимуляции drvData = NULL; appear = NULL; refreshNum = iNumOfS + 1;//заведомо период обновления больше числа собираемых сигналов (т.е. нет обновления) if (Experiment->ggRefresh->Checked) refreshNum = StrToInt(Experiment->refreshEvery->Text); recorded = 0;//обнуляем счётчик записанных отсчётов curnttic = 0; stims = 0;//количество выданных синхроимпульсов appear = new __int64[iNumOfS];//массив с временами возникновения сигналов errC = 0;//индикатора зависания while ((!QueryPerformanceFrequency((LARGE_INTEGER *)&ticps)) && (errC <= 2))//частота процессора errC++; if (errC > 2) { Experiment->DevEvents->Text = "ошибка QPFrequency"; return; } ticperiod = (ticps / (__int64)1000) * (__int64)iStimPrd;//тактов процессора за период стимуляции //рассчитаем минимальное число отсчётов между импульсами стимуляции (в отсчётах) impInterv = floor((1000 * iStimPrd) / (2 * effDT));//полуинтервал между импульсами стимуляции (отсчёты) sampRead = impInterv;//чтобы первый сигнал читался без проблем startNum = Graphs->CrntSig->Tag;//номер сигнала, с которого продолжается нумерация ik = startNum;//количество записанных сигналов (сквозная нумерация) kRefresh = 0;//счётчик обновления на ноль waitTime = min(float(500), discrT);//длительность паузы (мкс) перед отключением синхроимпульса tpp = (float)ticps * (waitTime / (float)1e6);//тактов за перод синхроимпульса z = r_pUtil->Start(&r_a, 0);//старт сбора данных if (z != 1) { Experiment->DevEvents->Text = "ошибка ADC_Start"; return; } z = 0; errC = 0;//проверяем начался ли сбор данных while ((z == 0) && (errC <= 200)) { r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 errC++; } if ((errC > 200) && (z == 0)) { Experiment->DevEvents->Text = "нет старта"; return; } z = 0; errC = 0;//устанавливаем НОЛЬ на выходе ЦАП while ((z == 0) && (errC <= 2)) { z = r_pADC->Get(ADC_WRITE_DAC, &stim_out[1]);//устанавливаем НОЛЬ на выходе ЦАП Sleep(1);//ЦАП работает на частоте не более 5 кГц errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка ADC_WRITE_DAC"; return; } for (i = 0; i < 2; i++)//"разминочный" сбор { blockReady = 0; while (blockReady == 0) blockReady = r_pUtil->GetBuffer((void*)drvData, mask); z = 0; errC = 0;//освобождаем захваченный блок памяти (буфер) while ((z == 0) && (errC <= 2)) { z = r_pUtil->FreeBuffer(); errC++; } if (errC > 2) { Experiment->DevEvents->Text = "err FreeBuf (IS r)"; break;//аварийное завершение разминочного сбора } } QueryPerformanceCounter((LARGE_INTEGER *)&curnttic);//текущий такт процессора if (curnttic > rNextTic) totaltic = curnttic + (iNumOfS * ticperiod) + (2 * ticps);//далее totaltic корректируется else totaltic = rNextTic + (iNumOfS * ticperiod) + (2 * ticps);//далее totaltic корректируется while (((ik < (startNum + iNumOfS)) || (recorded > 0)) && (curnttic <= totaltic)) { //блок подачи синхроимпульсов //curnttic = DaiImpuls(&appear[stims], &iNumOfs, ik, startNum);//варинт функции подачи синхроимпульса errC = 0;//индикатора зависания while ((!QueryPerformanceFrequency((LARGE_INTEGER *)&ticps)) && (errC <= 2))//частота процессора errC++; if (errC > 2) { Experiment->DevEvents->Text = "ошибка QPFrequency"; iNumOfS = ik - startNum;//условие выхода из цикла recorded = 0;//условие выхода из цикла } ticperiod = (ticps / (__int64)1000) * (__int64)iStimPrd;//тактов процессора за период стимуляции errC = 0;//индикатора зависания (не даём циклу возможность работать бесконечно) while((!QueryPerformanceCounter((LARGE_INTEGER *)&curnttic)) && (errC <= 2)) errC++; if (errC > 2) { Experiment->DevEvents->Text = "ошибка QPCounter"; iNumOfS = ik - startNum;//условие выхода из цикла recorded = 0;//условие выхода из цикла } popravka = rNextTic - curnttic;//следим за наступлением момента подачи синхроимпульса (расчёт поправок) if ((popravka <= 0) && (stims < iNumOfS))//вывод стимулирующего сигнала { //SetToDAC(); z = 0; errC = 0;//устанавливаем НЕНОЛЬ на выходе ЦАП while ((z == 0) && (errC <= 2)) { z = r_pADC->Get(ADC_WRITE_DAC, &stim_out[0]);//устанавливаем НЕНОЛЬ на выходе ЦАП errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка ADC_WRITE_DAC"; iNumOfS = ik - startNum;//условие выхода из цикла recorded = 0;//условие выхода из цикла } if (((popravka + ticperiod) < 0) || (stims == 0)) rNextTic = curnttic + ticperiod;//момент (в тактах процессора) подачи следующего синхроимпульса else rNextTic = curnttic + ticperiod + popravka;//момент (в тактах процессора) подачи следующего синхроимпульса appear[stims] = curnttic;//запоминаем время возникновения сигнала stims++;//увеличиваем счётчик поданых синхроимпульсов //делаем пауза перед отключением синхроимпульса tp1 = curnttic; while ((curnttic - tp1) < tpp) QueryPerformanceCounter((LARGE_INTEGER *)&curnttic); z = 0; errC = 0;//устанавливаем НОЛЬ на выходе ЦАП while ((z == 0) && (errC <= 2)) { z = r_pADC->Get(ADC_WRITE_DAC, &stim_out[1]);//устанавливаем НОЛЬ на выходе ЦАП errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка ADC_WRITE_DAC"; iNumOfS = ik - startNum;//условие выхода из цикла recorded = 0;//условие выхода из цикла } } //===== окончание блока подачи синхроимпульсов ===== blockReady = r_pUtil->GetBuffer((void*)drvData, mask);//запрашиваем блок данных из буфера DMA if (blockReady != 0)//блок данных получен { if ((PStart->CloseWin->Tag == 1) || (PStart->NextBlock->Tag == 1))//не пора ли остановиться? iNumOfS = ik - startNum;//преждевременный выход (из эксперимента или блока) for (i = 0; i < rBlockSize; i += chanls)//перебираем отсчёты блока данных { for (z = 0; z < chanls; z++) convData[z] = (drvData[i + rReadOrder[z]] >> bwSh);//выделяем код АЦП (старшие 12 (14) бит) sampRead++;//прирост счётчика прочитанных отсчётов //логическое "И" oDrvData[i] & 0000000000001111 - выделяем последние 4 бита //0xF = 15(dec) = 0000000000001111(bin); 0xFFF0 = 65520(dec) = 1111111111110000(bin) digitPort4 = ((unsigned short)drvData[i]) & eds;//(oDrvData[i] << 12) isSynchro = ((digitPort4 > 2) && (sampRead >= impInterv));//обнаружен ли синхроимпульс if (recorded > 0)//дозапись сигнала (обязательно recorded < recLen) { for (z = 0; z < ftChan; z++)//запись данных с всех каналов { rSignals[ik].s[(z * recLen) + recorded] = rPolarity * (convData[z] - (short)rLocMean[z] * rConstMinus); rmGrafik[(z * recLen) + recorded] = (double)rSignals[ik].s[(z * recLen) + recorded] * sampl2mV; } /*else потом впишем локальное среднее*/ recorded++;//увеличиваем счётчик записанных отсчётов для данного сигнала //ВАЖНО! Следим за наложением синхроимпульса на предыдущую запись (нестабильность частоты стимуляции) if (isSynchro && (recorded > impInterv))//синхроимпульс уже появился, а сигнал ещё не записан { recorded = recLen;//считаем сигнал полностью записанным i -= chanls;//шаг назад, чтобы на следующем витке цикла isSynchro тоже было true } if (recorded >= recLen)//сигнал полностью записан { if (!multiCh)//запишем средние для второстепенных каналов for (z = 0; z < chanls - 1; z++) rSignals[ik].s[recLen + z] = (short)rLocMean[z + 1];//ноль-линия на второстепенном канале //rSignals[ik].s[recLen + z] = (short)(minorChanMean[z] / recLen);//вычисляем среднее recorded = 0;//сигнал полностью записан (обнуляем счётчик записанных отсчётов) ik++;//увеличиваем счётчик собранных сигналов Graphs->CrntSig->Tag = ik;//счётчик сигналов Synchronize(&RecSynchroCounter);//счётчик сигналов //========================================== if (rAppEndData)//если выбран прерывистый режим DiscontinWrite();//вписываем полученный сигнал на жёсткий диск //========================================== if (canPlot)//если "медленная" или "редкая" стимуляция { specK1 = Graphs->CrntSig->Tag - 1;//номер сигнала, с которого начинаются неотрисованне сигналы specK2 = 1;//количество неотрисованных сигналов Synchronize(&InducSynchroPlotter);//подрисуем графики Synchronize(&FromMinorChan);//выводим данные со второстепенных каналов (только при редкой стимуляции) kRefresh++; if (kRefresh >= refreshNum) { kRefresh = 0;//счётчик обновления на нуль Gists->GistsRefresh(-1);//перерисовываем гистограммы } /* // ? остановка сбора при больших интервалах между импульсами QueryPerformanceCounter((LARGE_INTEGER *)&popravka); ind_pUtil->FreeBuffer(); ind_pUtil->Stop(); Sleep(sleepTime); if (!QueryPerformanceFrequency((LARGE_INTEGER *)&ticps)) {ticperiod = (__int64)((ticps / 1000) * stimPrd);} ind_pUtil->Start(&ind_a, 0); QueryPerformanceCounter((LARGE_INTEGER *)&curnttic); while (blockReady == 0) {blockReady = ind_pUtil->GetBuffer((void*)drvData, mask);} curntsampl += (dopsampls);//(((curnttic - popravka) / ticps) * 1e6) / iDiscrTime);*/ } if (ik == (startNum + iNumOfS))//все сигналы полностью записаны break;//выходим из цикла for (i = 0; i < rBlockSize; i += chanls) totaltic = curnttic + ((startNum + iNumOfS) - ik) * ticperiod + (10 * ticps);//если сигнал обнаружен, корректируем totaltic } } else//поиск очередного сигнала (при этом recorded = 0) { if (isSynchro)//сигнал обнаружен { rSignals[ik].appear = (float)((double)(appear[ik - startNum] - rBeginTakt) / (double)ticps); for (z = 0; z < ftChan; z++)//запись данных со всех каналов { rSignals[ik].s[(z * recLen) + recorded] = rPolarity * (convData[z] - (short)rLocMean[z] * rConstMinus); rmGrafik[(z * recLen) + recorded] = (double)rSignals[ik].s[(z * recLen) + recorded] * sampl2mV; } /*else потом впишем локальное среднее*/ recorded++;//увеличиваем счётчик записанных отсчётов для данного сигнала sampRead = 0;//обнуляем счётчик прочитанных отсчётов totaltic = curnttic + ((startNum + iNumOfS) - ik) * ticperiod + (10 * ticps);//если сигнал обнаружен, корректируем totaltic } else//коррекция локального среднего только в отсутсвии записи { for (z = 0; z < chanls; z++) { rLocMean[z] += (double(convData[z] - rExtractLocMean[rCountlm * chanls + rReadOrder[z]]) / (double)rSamps); rExtractLocMean[rCountlm * chanls + rReadOrder[z]] = convData[z]; } rCountlm++; if (rCountlm == rSamps) rCountlm = 0; } } } z = 0; errC = 0;//освобождаем захваченный блок памяти (буфер) while ((z == 0) && (errC <= 2)) { z = r_pUtil->FreeBuffer(); errC++; } if (errC > 2) { Experiment->DevEvents->Text = "err FreeBuf (IS r)"; iNumOfS = ik - startNum;//условие выхода из цикла recorded = 0;//условие выхода из цикла } } } z = 1; errC = 0;//стоп сбора данных while ((z == 1) && (errC <= 2)) { r_pUtil->Stop(); r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 errC++; } if (errC > 2) Experiment->DevEvents->Text = "ошибка ADC_Stop"; //указатель rExtractLocMean удаляется в блоке Execute() drvData = NULL; delete[] appear; appear = NULL; } //--------------------------------------------------------------------------- void __fastcall TRecordThread::Induced_N_Spnt_SgnlAcquis(__int32 allMini, __int32 iNumOfS, __int32 iStimPrd, bool canPlot) { //сбор данных: вызванные + спонтанные (режим №4) /* allMini - общее количество собираемых спонтанных сигналов iNumOfS - число собираемых в данном блоке вызванных сигналов iStimPrd - период стимуляции в данном блоке canPlot - разрешено ли рисовать (большое "свободное" время) */ bool isSynchro;//обнаружен ли синхроимпульс short *drvData, convData[maxChannels],//содержит выделенный код АЦП *backBuffer;//содержит ранее записанный блок (спонтанный сигнал) unsigned short digitPort4;//значения старших четырёх битов входного цифрового порта __int32 i, g, z, j, errC,//счётчик ошибок ik,//счётчик записанных взыванных сигналов kr,//счётчик обновления (спонтанный сигнал) startNum,//нумерация сигналов в сложном протоколе продолжается и начинается с startNum mk,//счётчик записанных спонтанных сигналов samplBack,//отчётов назад (рассчитывается из spontanBackTime) bI,//индекс отсчёта в буфере, с которого начать считывание назад stims,//количество выданных синхроимпульсов recordedI,//счётчик записанных отсчётов для вызванного сигнала recordedM,//счётчик записанных отсчётов для спонтанного сигнала blockReady,//готовность блока данных frstIndBack,//первый индекс для бэкБуфера (спонтанный сигнал) //refreshNum,//период обновления графиков (спонтанный сигнал) ost,//остаток (сколько отсчётов читать из буферного блока, спонтаннный сигнал) minorChanMean[maxChannels],//среднее на второстепенном канале impInterv,//нижняя граница значений межимпульсных интервалов (в отсчётах) sampRead;//число записанных отсчётов, начиная с момента возникновения синхроимпульса float waitTime;//длительность паузы (мкс) перед отключением синхроимпульса unsigned int mask;//хранит информацию о наложении данных __int64 *appear,//массив с временами подачи синхроимпульсов (в тактах процессора) totaltic,//общее число тактов процессора, отводимое для текущего сбора (по истечении этого времени выходим из цикла) curnttic,//текущий такт процессора tpp,//тактов за перод синхроимпульса tp1, ticps,//тактов в секунду (частота процессора) ticperiod,//тактов процессора на период стимуляции popravka;//авторегулировка частоты стимуляции bool recMini;//разрешено ли записывать спонтанные сигналы drvData = NULL; backBuffer = NULL; appear = NULL; samplBack = chanls * floor((StrToInt(PStart->BackTime->Text) / effDT) + 0.5);//20% длины спонтанного сигнала (без учёта числа каналов) //refreshNum = iNumOfS + 1;//заведомо период обновления больше числа собираемых сигналов (т.е. нет обновления) //if (Experiment->ggRefresh->Checked)//можно ли обновлять графики параметров // refreshNum = StrToInt(Experiment->refreshEvery->Text); backBuffer = new short[samplBack];//циклический буфер for (i = 0; i < samplBack; i++)//первое заполнение буфера backBuffer (нулями) backBuffer[i] = 0; bI = 0; recordedI = 0;//обнуляем счётчик записанных отсчётов recordedM = 0;//обнуляем счётчик записанных отсчётов stims = 0;//количество выданных синхроимпульсов appear = new __int64[iNumOfS];//массив с временами возникновения сигналов errC = 0;//индикатора зависания while ((!QueryPerformanceFrequency((LARGE_INTEGER *)&ticps)) && (errC <= 2))//частота процессора errC++; if (errC > 2) { Experiment->DevEvents->Text = "не определена частота процессора"; return; } ticperiod = (ticps / (__int64)1000) * (__int64)iStimPrd; //рассчитаем минимальное число отсчётов между импульсами impInterv = floor(recLen / 2) + 1;//floor((1000 * iStimPrd * 1) / (2 * discrT));//полуинтервал между импульсами стимуляции (отсчёты) sampRead = impInterv;//чтобы первый сигнал читался без проблем startNum = Graphs->CrntSig->Tag;//номер сигнала, с которого продолжается нумерация ik = startNum;//количество записанных вызванных сигналов (сквозная нумерация) mk = PStart->BackTime->Tag;//количество записанных спонтанных сигналов (сковзная нумерация) kr = 0;//обнуляем счётчик обновления (пока работаем без обновлений) waitTime = min(float(500), discrT);//длительность паузы (мкс) перед отключением синхроимпульса tpp = (float)ticps * (waitTime / (float)1e6);//тактов за перод синхроимпульса z = r_pUtil->Start(&r_a, 0);//старт сбора данных if (z != 1) { Experiment->DevEvents->Text = (FindErrorStrByCode(z, 0)); Experiment->DevEvents->Text.Insert("Induc ", 1); return; } z = 0; errC = 0;//проверяем начался ли сбор данных while ((z == 0) && (errC <= 200)) { r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 errC++; } if (errC > 200) { Experiment->DevEvents->Text = "ошибка ADC_StatusRun"; return; } z = 0; errC = 0;//устанавливаем НОЛЬ на выходе ЦАП while ((z == 0) && (errC <= 2)) { z = r_pADC->Get(ADC_WRITE_DAC, &stim_out[1]);//устанавливаем НОЛЬ на выходе ЦАП Sleep(1);//ЦАП работает на частоте не более 5 кГц errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка ADC_WRITE_DAC"; return; } for (i = 0; i < 2; i++)//"разминочный" сбор { blockReady = 0; while (blockReady == 0) blockReady = r_pUtil->GetBuffer((void*)drvData, mask); z = 0; errC = 0;//освобождаем захваченный блок памяти (буфер) while ((z == 0) && (errC <= 2)) { z = r_pUtil->FreeBuffer(); errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка FreeBuffer"; break;//аварийное завершение разминочного сбора } } if (errC > 2) return;//"разминка" не прошла QueryPerformanceCounter((LARGE_INTEGER *)&curnttic); if (curnttic > rNextTic) totaltic = curnttic + (iNumOfS * ticperiod) + (2 * ticps);//далее totaltic корректируется else totaltic = rNextTic + (iNumOfS * ticperiod) + (2 * ticps);//далее totaltic корректируется while (((ik < (startNum + iNumOfS)) || (recordedI > 0)) && (curnttic <= totaltic)) { //блок подачи синхроимпульсов errC = 0;//индикатора зависания while ((!QueryPerformanceFrequency((LARGE_INTEGER *)&ticps)) && (errC <= 2))//частота процессора errC++; if (errC > 2) { Experiment->DevEvents->Text = "ошибка QPFrequency"; iNumOfS = ik - startNum;//условие выхода из цикла recordedI = 0;//условие выхода из цикла } ticperiod = (ticps / (__int64)1000) * (__int64)iStimPrd; errC = 0;//индикатора зависания (не даём циклу возможность работать бесконечно) while((!QueryPerformanceCounter((LARGE_INTEGER *)&curnttic)) && (errC <= 2)) errC++; if (errC > 2) { Experiment->DevEvents->Text = "ошибка QPCounter"; iNumOfS = ik - startNum;//условие выхода из цикла recordedI = 0;//условие выхода из цикла } popravka = rNextTic - curnttic; if ((popravka <= 0) && (stims < iNumOfS))//вывод стимулирующего сигнала { //SetToDAC();//устанавливаем НЕНОЛЬ на выходе ЦАП z = 0; errC = 0;//устанавливаем НЕНОЛЬ на выходе ЦАП while ((z == 0) && (errC <= 2)) { z = r_pADC->Get(ADC_WRITE_DAC, &stim_out[0]);//устанавливаем НЕНОЛЬ на выходе ЦАП errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка ADC_WRITE_DAC"; iNumOfS = ik - startNum;//условие выхода из цикла recordedI = 0;//условие выхода из цикла } if (((popravka + ticperiod) < 0) || (stims == 0)) rNextTic = curnttic + ticperiod;//момент (в тактах процессора) подачи следующего синхроимпульса else rNextTic = curnttic + ticperiod + popravka;//момент (в тактах процессора) подачи следующего синхроимпульса appear[stims] = curnttic;//запоминаем время возникновения сигнала stims++;//увеличивем счётчик поданых синхроимпульсов //делаем паузу перед отключением синхроимпульса tp1 = curnttic; while ((curnttic - tp1) < tpp) QueryPerformanceCounter((LARGE_INTEGER *)&curnttic); z = 0; errC = 0;//устанавливаем НОЛЬ на выходе ЦАП while ((z == 0) && (errC <= 2)) { z = r_pADC->Get(ADC_WRITE_DAC, &stim_out[1]);//устанавливаем НОЛЬ на выходе ЦАП errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка ADC_WRITE_DAC"; iNumOfS = ik - startNum;//условие выхода из цикла recordedI = 0;//условие выхода из цикла } } blockReady = r_pUtil->GetBuffer((void*)drvData, mask);//запрашивем блок данных из буфера DMA if (blockReady != 0)//блок данных получен { if ((PStart->CloseWin->Tag == 1) || (PStart->NextBlock->Tag == 1))//не пора ли остановиться? iNumOfS = ik - startNum;//преждевременный выход (из эксперимента или блока) //поиск и запись сигналов (всех в одном цикле) for (i = 0; i < rBlockSize; i += chanls)//перебираем отсчёты в блоке данных { //выделение кода АЦП и заполнение циклического буфера for (z = 0; z < chanls; z++) { convData[z] = (drvData[i + rReadOrder[z]] >> bwSh);//выделяем код АЦП (старшие 12 (14) бит) backBuffer[bI] = convData[z];//запись в буфер bI++;//смещаем метку } if (bI >= samplBack) bI = 0;//возврат на начало циклического буфера sampRead += chanls;//прирост счётчика прочитанных отсчётов recMini = ((mk < allMini) && (PStart->PausSpontan->Tag == 0) && (recordedI == 0));//разрешено ли записывать спонтанные сигналы //логическое "И" oDrvData[i] & 0000000000001111 - выделяем последние 4 бита //0xF = 15(dec) = 0000000000001111(bin) digitPort4 = ((unsigned short)drvData[i]) & eds;//(oDrvData[i] << 12) >> 12; isSynchro = ((digitPort4 > 2) && (sampRead >= impInterv));//обнаружен ли синхроимпульс //--------------------------------- //поиск и запись ВЫЗВАННЫХ сигналов if (recordedI > 0)//дозапись сигнала (обязательно recorded < toRec) { for (z = 0; z < ftChan; z++)//запись данных со всех каналов { rSignals[ik].s[(z * recLen) + recordedI] = rPolarity * (convData[z] - (short)rLocMean[z] * rConstMinus); rmGrafik[(z * recLen) + recordedI] = (double)rSignals[ik].s[(z * recLen) + recordedI] * sampl2mV; } /*else потом впишем локальное среднее*/ recordedI++;//увеличиваем счётчик записанных отсчётов для данного сигнала //ВАЖНО! Следим за наложением синхроимпульса на предыдущую запись (нестабильность частоты стимуляции) if (isSynchro && (recordedI > impInterv))// && (ik < (startNum + iNumOfS))) { recordedI = recLen;//считаем сигнал полностью записанным i -= chanls;//шаг назад, чтобы на следующем витке цикла isSynchro тоже было true } if (recordedI >= recLen)//сигнал полностью записан { if (!multiCh)//запишем средние для второстепенных каналов for (z = 0; z < chanls - 1; z++) rSignals[ik].s[recLen + z] = (short)rLocMean[z + 1];//(short)(minorChanMean[z] / recLen);//вычисляем среднее recordedI = 0;//сигнал записан полностью (обнуляем счётчик записанных отсчётов) ik++;//увеличиваем счётчик собранных сигналов Graphs->CrntSig->Tag = ik;//счётчик сигналов Synchronize(&RecSynchroCounter);//счётчик сигналов //========================================== if (rAppEndData) DiscontinWrite();//вписываем полученный сигнал на жёсткий диск //========================================== if (canPlot)//если "медленная" ("редкая") стимуляция { //подрисуем графики specK1 = Graphs->CrntSig->Tag - 1;//номер сигнала, с которого начинаются неотрисованне сигналы specK2 = 1;//количество неотрисованных сигналов Synchronize(&InducSynchroPlotter);//рисование графиков //выводим данные со второстепенных каналов (только при редкой стимуляции) Synchronize(&FromMinorChan); } if (ik == (startNum + iNumOfS))//все сигналы полностью записаны break;//выходим из цикла for (i = 0; i < rBlockSize; i += chanls) //если сигнал обнаружен, корректируем totaltic totaltic = curnttic + ((startNum + iNumOfS) - ik) * ticperiod + ticps; } } else//поиск очередного сигнала (синхроимпульса, при этом recordedI = 0) { if (isSynchro)//сигнал обнаружен { rSignals[ik].appear = (float)((double)(appear[ik - startNum] - rBeginTakt) / (double)ticps); for (z = 0; z < ftChan; z++)//запись данных со всех каналов { rSignals[ik].s[(z * recLen) + recordedI] = rPolarity * (convData[z] - (short)rLocMean[z] * rConstMinus); rmGrafik[(z * recLen) + recordedI] = (double)rSignals[ik].s[(z * recLen) + recordedI] * sampl2mV; } /*else потом впишем локальное среднее*/ recordedI++;//увеличиваем счётчик записанных отсчётов для данного сигнала sampRead = 0;//обнуляем счётчик прочитанных отсчётов totaltic = curnttic + ((startNum + iNumOfS) - ik) * ticperiod + ticps;//корректируем totaltic } else//между импульсами стимуляции корректируем локальное среднее (несмотря на спонтанные сигналы) { for (z = 0; z < chanls; z++) { rLocMean[z] += (double(convData[z] - rExtractLocMean[rCountlm * chanls + rReadOrder[z]]) / (double)rSamps); rExtractLocMean[rCountlm * chanls + rReadOrder[z]] = convData[z]; } rCountlm++; if (rCountlm == rSamps) rCountlm = 0; } } //----------------------------------- //поиск и запись СПОНТАННЫХ сигналов //запись спонтанных сигналов останавливается, когда: //1) все сигналы собраны (mk >= allMini) //2) нажата кнопка паузы для миниатюрных (PStart->pausMini->Tag == 1) //3) идёт запись вызванного сигнала (recordedI > 0) if (recMini) { if (recordedM == 0)//ищем очередной спонтанный сигнал { if ((rPolarity * (convData[0] - (short)rLocMean[0] * rConstMinus)) >= rPorog) { //сигнал обнаружен (это возможно только после полной записи вызванного сигнала, значит вр. возн-я спонт. сиг...) rSpntSignals[mk].appear = rSignals[ik - 1].appear + (sampRead * discrT * (1e-6));//время возникновения сигнала (в секундах) //записываем из буфера начало спайка for (g = bI; g < samplBack; g += chanls) { for (z = 0; z < ftChan; z++)//записываем данные со всех каналов { rSpntSignals[mk].s[(z * rSpntRecLen) + recordedM] = rPolarity * (backBuffer[g + z] - (short)rLocMean[z] * rConstMinus); //rmGrafikM[(z * rSpntRecLen) + recordedM] = (double)rSignals[ik].s[(z * rSpntRecLen) + recordedM] * sampl2mV; } /*else потом впишем локальное среднее*/ recordedM++;//увеличиваем счётчик записанных отсчётов для данного сигнала } for (g = 0; g < bI; g += chanls)//продолжение записи из буфера { for (z = 0; z < ftChan; z++)//записываем данные со всех каналов { rSpntSignals[mk].s[(z * rSpntRecLen) + recordedM] = rPolarity * (backBuffer[g + z] - (short)rLocMean[z] * rConstMinus); //rmGrafikM[(z * rSpntRecLen) + recordedM] = (double)rSignals[ik].s[(z * rSpntRecLen) + recordedM] * sampl2mV; } /*else потом впишем локальное среднее*/ recordedM++;//увеличиваем счётчик записанных отсчётов для данного сигнала } } else { //корректируем локальное среднее (также при сборе вызванных) for (z = 0; z < chanls; z++) { rLocMean[z] += (double(convData[z] - rExtractLocMean[rCountlm * chanls + rReadOrder[z]]) / (double)rSamps); rExtractLocMean[rCountlm * chanls + rReadOrder[z]] = convData[z]; } rCountlm++; if (rCountlm == rSamps) rCountlm = 0; } } else//дозапись спонтанного сигнала { for (z = 0; z < ftChan; z++)//записываем данные со всех каналов { rSpntSignals[mk].s[(z * rSpntRecLen) + recordedM] = rPolarity * (convData[z] - (short)rLocMean[z] * rConstMinus); //rmGrafikM[(z * rSpntRecLen) + recordedM] = (double)rSignals[ik].s[(z * rSpntRecLen) + recordedM] * sampl2mV; } recordedM++;//увеличиваем счётчик записанных отсчётов для данного сигнала if (recordedM >= rSpntRecLen)//сигнал полностью записан (окончания записи одиночного сигнала) { if (!multiCh)//запишем средние для второстепенных каналов for (z = 0; z < chanls - 1; z++) rSpntSignals[mk].s[rSpntRecLen + z] = (short)rLocMean[z + 1];//(short)(minorChanMean[z] / rSpntRecLen);//вычисляем среднее recordedM = 0;//сигнал полностьюя записан (обнуляем счётчик записанных отсчётов) mk++;//увеличивем счётчик спонтанных сигналов kr++;//счётчик обновления (спонтанный сигнал, пока не обновляется) //========================================== //if (rAppEndData) // DiscontinMiniWrite();//вписываем полученный спонтанный сигнал на жёсткий диск //========================================== PStart->BackTime->Tag = mk;//счётчик сигналов //Synchronize(&RecSynchroCounter);//счётчик сигналов // Synchronize(&MiniMd4SynchroPlot);//сразу же рисуем крайний спонтанный сигнал } } } else if ((recordedI > 0) && (recordedM > 0))//во время записи спонтанного возник вызванный сигнал { //преждевременное завершение записи обнаруженного сигнала recordedM = 0;//сигнал полностью записан (обнуляем счётчик записанных отсчётов) mk++;//счётчик спонтанных сигналов kr++;//счётчик обновления (спонтанный сигнал, пока не обновляется) PStart->BackTime->Tag = mk;//счётчик сигналов } } z = 0; errC = 0;//освобождаем захваченный блок памяти (буфер) while ((z == 0) && (errC <= 2)) { z = r_pUtil->FreeBuffer(); errC++; } if (errC > 2) { Experiment->DevEvents->Text = "ошибка FreeBuffer"; iNumOfS = ik - startNum;//условие выхода из цикла recordedI = 0;//условие выхода из цикла } } } z = 1; errC = 0;//стоп сбора данных while ((z == 1) && (errC <= 2)) { r_pUtil->Stop(); r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 errC++; } if (errC > 2) Experiment->DevEvents->Text = "ошибка ADC_Stop"; //указатель rExtractLocMean удаляется в блоке Execute() drvData = NULL; delete[] backBuffer; backBuffer = NULL; delete[] appear; appear = NULL; } //--------------------------------------------------------------------------- void TRecordThread::Spnt_SgnlAcquisition(__int32 mNumOfS, clock_t experimBegin) { //сбор данных: спонтанные сигналы №1 /* mNumOfS - число собираемых сигналов */ unsigned int mask;// хранит информацию о наложении данных __int32 i, g, z, j,//индексы в циклах k,//счётчик сигналов kRefresh,//счётчик обновления samplBack,//отчётов назад (рассчитывается из spontanBackTime) bI,//индекс отсчёта в буфере, с которого начать считывание назад startNum,//нумерация сигналов в сложном протоколе продолжается и начинается с startNum recorded,//количество записанных отсчётов frstIndBack,//первый индекс для бэкБуфера refreshNum,//период обновления графиков (в сигналах) ost,//остаток (сколько отсчётов читать из буферного блока) blockReady,//готовность блока данных minorChanMean[maxChannels];//среднее на второстепенном канале short *drvData,//содержит записанный сейчас блок convData[maxChannels],//содержит выделенный код АЦП для всех каналов (каналов не больше, чем maxChannels) *backBuffer;//содержит ранее записанный блок unsigned long int allsampls;//абсолютный номер текущего отсчёта clock_t timeMoment;//момент обнаружения сигнала (миллисекунд от начала работы программы) __int64 curnttic;//текущий такт процессора drvData = NULL; backBuffer = NULL; samplBack = chanls * floor(((StrToInt(PStart->BackTime->Text) * 1000) / effDT) + 0.5);//количество отсчётов "назад" для спонтанного сигнала (без учёта числа каналов) refreshNum = mNumOfS + 1;//заведомо период обновления больше числа собираемых сигналов (т.е. нет обновления) if (Experiment->ggRefresh->Checked) refreshNum = StrToInt(Experiment->refreshEvery->Text); backBuffer = new short[samplBack];//циклический буфер; длина буфера равна времени назад в отсчётах (примерно) for (i = 0; i < samplBack; i++)//первое заполнение буфера backBuffer (нулями) backBuffer[i] = 0; bI = 0; allsampls = 0;//обнуляем счётчик отсчётов recorded = 0; QueryPerformanceCounter((LARGE_INTEGER *)&curnttic);//текущий такт процессора while (curnttic < rNextTic) { Sleep(10);//ждём времени начала следующего сеанса сбора спонтанных сигналов QueryPerformanceCounter((LARGE_INTEGER *)&curnttic);//текущий такт процессора } z = r_pUtil->Start(&r_a, 0); if (z != 1) { Experiment->DevEvents->Text = (FindErrorStrByCode(z,0)); return; } z = 0; while (z == 0) r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 for (i = 0; i < 4; i++)//"разминочный" сбор { blockReady = 0; while (blockReady == 0) blockReady = r_pUtil->GetBuffer((void*)drvData, mask); z = 0;//освобождаем захваченный блок памяти (буфер) while (z == 0) z = r_pUtil->FreeBuffer(); } kRefresh = 0;//обнуляем счётчик обновления startNum = Graphs->CrntSig->Tag;//нумерация сигналов в сложном протоколе продолжается и начинается с startNum k = startNum;//количество собранных сигналов while (k < (startNum + mNumOfS)) { if (PStart->CloseWin->Tag == 1)//остановить ли запись mNumOfS = k - startNum;//условие выхода из цикла while (k < (startNum + mNumOfS)) blockReady = 0; while(blockReady == 0) blockReady = r_pUtil->GetBuffer((void*)drvData, mask); for (i = 0; i < rBlockSize; i += chanls) { for (z = 0; z < chanls; z++) { convData[z] = (drvData[i + rReadOrder[z]] >> bwSh);//выделяем код АЦП (старшие 12 (14) бит) backBuffer[bI] = convData[z];//запись в буфер bI++;//смещаем метку } if (bI >= samplBack) bI = 0;//возврат на начало циклического буфера if (recorded == 0)//поиск сигнала { if ((rPolarity * (convData[0] - (short)rLocMean[0] * rConstMinus)) >= rPorog)//сигнал обнаружен { //rSignals[k].appear = (allsampls + i) * discrT * (1e-6);//время возникновения сигнала (в секундах) timeMoment = clock();//момент обнаружения сигнала (миллисекунд от начала работы программы) rSignals[k].appear = ((float)timeMoment / 1000) - (float)experimBegin; //записываем из буфера начало спайка for (g = bI; g < samplBack; g += chanls) { for (z = 0; z < ftChan; z++)//записываем данные со всех каналов { rSignals[k].s[(z * recLen) + recorded] = rPolarity * (backBuffer[g + z] - (short)rLocMean[z] * rConstMinus); rmGrafik[(z * recLen) + recorded] = (double)rSignals[k].s[(z * recLen) + recorded] * sampl2mV; } /*else потом впишем локальное среднее*/ recorded++;//приращение числа записанных отсчётов для данного сигнала } for (g = 0; g < bI; g += chanls)//продолжение записи из буфера { for (z = 0; z < ftChan; z++)//записываем данные со всех каналов { rSignals[k].s[(z * recLen) + recorded] = rPolarity * (backBuffer[g + z] - (short)rLocMean[z] * rConstMinus); rmGrafik[(z * recLen) + recorded] = (double)rSignals[k].s[(z * recLen) + recorded] * sampl2mV; } /*else//одноканальный режим for (z = 1; z < chanls; z++)//среднее в период регистрации сигнала minorChanMean[z - 1] += backBuffer[g + z];//потом подсчитаем среднее*/ recorded++;//приращение числа записанных отсчётов для данного сигнала } } else//дозапись сигнала { for (z = 0; z < chanls; z++)//корректируем локальное среднее { rLocMean[z] += (double(convData[z] - rExtractLocMean[rCountlm * chanls + rReadOrder[z]]) / (double)rSamps); rExtractLocMean[rCountlm * chanls + rReadOrder[z]] = convData[z]; } rCountlm++; if (rCountlm == rSamps) rCountlm = 0; } } else//(recorded > 0) { //дозапись сигнала for (z = 0; z < ftChan; z++)//записываем данные со всех каналов { rSignals[k].s[(z * recLen) + recorded] = rPolarity * (convData[z] - (short)rLocMean[z] * rConstMinus); rmGrafik[(z * recLen) + recorded] = (double)rSignals[k].s[(z * recLen) + recorded] * sampl2mV; } /*else потом впишем локальное среднее*/ recorded++;//приращение числа записанных отсчётов для данного сигнала if (recorded >= recLen)//сигнал полностью записан (окончания записи одиночного сигнала) { if (!multiCh)//запишем средние для второстепенных каналов for (z = 0; z < chanls - 1; z++) rSignals[k].s[recLen + z] = (short)rLocMean[z + 1];//(short)(minorChanMean[z] / recLen);//вычисляем среднее recorded = 0;//сигнал записан полностью (обнуляем счётчик записанных отсчётов) k++; kRefresh++; Graphs->CrntSig->Tag = k;//счётчик сигналов Synchronize(&RecSynchroCounter);//счётчик сигналов //========================================== if (rAppEndData) DiscontinWrite();//вписываем полученный сигнал на жёсткий диск //========================================== Synchronize(&FromMinorChan);//второстепенные каналы if (k == (startNum + mNumOfS))//все сигналы полностью записаны break;//прерываем цикл for (i = 0; i < rBlockSize; i += chanls) } } } allsampls += rBlockSize;//счётчик обработанных отсчётов z = 0;//освобождаем захваченный блок памяти (буфер) while (z == 0) z = r_pUtil->FreeBuffer(); if (((kRefresh == refreshNum) || (k == (startNum + mNumOfS))) && (k > 0))//разрешено ли обновить графики { z = 1; while (z == 1) { r_pUtil->Stop(); r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 } if (PStart->CloseWin->Tag == 1)//остановить ли запись mNumOfS = k - startNum; //обновляем графики recorded = 0; specK1 = (k - kRefresh);//номер сигнала, с которого начинаются неотрисованные сигналы specK2 = kRefresh;//количество неотрисованных сигналов Synchronize(&MiniSynchroPlotGraphs);//рисование графиков z = r_pUtil->Start(&r_a, 0); if (z <= 0) { Experiment->DevEvents->Text = (FindErrorStrByCode(z,0)); return; } z = 0; while (z == 0) r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 blockReady = 0; while(blockReady == 0) blockReady = r_pUtil->GetBuffer((void*)drvData, mask); for (i = 0; i < samplBack; i++) backBuffer[i] = 0;//заполнение буфера backBuffer (нулями) bI = 0; kRefresh = 0;//обнуляем счётчик обновления } } //стоп сбора данных z = 1; while (z == 1) { r_pUtil->Stop(); r_pUtil->Get(ADCUTILITY_STATUS_RUN, &z);//1, если идёт сбор данных, иначе 0 } drvData = NULL; delete[] backBuffer; backBuffer = NULL; } //--------------------------------------------------------------------------- void TRecordThread::DiscontinWrite() { //все типы режимов. Прерывистый сбор данных (сохранение каждого нового сигнала сразу на жёсткий диск) __int32 i, fullSigLen,//полная длина данных со всех каналов (отсчёты) ikNow,//текущий номер сигнала itemWrtRd,//число записанных единиц (как правило пишем по одной единице) amountOfBytes;//количество байт, записываемых данном блоке (инфо + сигнал) char dLett[3];//символ-разделитель между сигналами dLett[0] = 'S'; dLett[1] = 'i'; dLett[2] = 'g';//символ-разделитель между сигналами ikNow = Graphs->CrntSig->Tag - 1;//текущий номер сигнала fullSigLen = (recLen * ftChan) + (chanls - ftChan);//полная длина данных со всех каналов (отсчёты) amountOfBytes = (3 * sizeof(char)) + sizeof(float) + (fullSigLen * sizeof(short));//должно быть записано байт //разделитель - развёртка сигнала itemWrtRd = fwrite(&dLett, sizeof(char), 3, rDiscontinFile);//разделитель 'Sig' amountOfBytes -= itemWrtRd * sizeof(char); //время возникновения itemWrtRd = fwrite(&rSignals[ikNow].appear, sizeof(float), 1, rDiscontinFile);//время возникновения amountOfBytes -= itemWrtRd * sizeof(float); //сам сигнал (данные со всех каналов) itemWrtRd = fwrite(rSignals[ikNow].s, sizeof(short), fullSigLen, rDiscontinFile); amountOfBytes -= itemWrtRd * sizeof(short); if (amountOfBytes != 0) Experiment->DevEvents->Text = "ошибка записи";//аварийный выход, видимо, можно не делать } //--------------------------------------------------------------------------- void TRecordThread::GetLocalMean() { //вычисляем начальное среднее (для нивелирования постоянной составляющей) __int32 i, j; rSamps = (__int32)floor((float(baseLine) / effDT) + 0.5); rExtractLocMean = new short[rSamps * chanls];//массив для вычисления локального среднего удаляется в Execute() Experiment->BeginMean(rExtractLocMean, rSamps * chanls); for (j = 0; j < chanls; j++) { rLocMean[j] = 0;//массив средних значений для всех каналов for (i = 0; i < rSamps; i++) rLocMean[j] += (double)rExtractLocMean[i * chanls + rReadOrder[j]]; rLocMean[j] /= (double)rSamps; } rCountlm = 0; } //--------------------------------------------------------------------------- //void TRecordThread::SetToDAC() //{ // //устанавливаем НЕНОЛЬ-НОЛЬ на выходе ЦАП //} //---------------------------------------------------------------------------
#include "junction_maneuvering/junction_maneuvering_ros.h" JunctionManeuveringROS::JunctionManeuveringROS(ros::NodeHandle& nh): nh_(nh), junction_maneuvering_server_(nh,"/junction_maneuvering_server", boost::bind(&JunctionManeuveringROS::junctionManeuveringExecute, this, _1),false), monitored_heading_(0), monitored_distance_(0) { loadParameters(); // subscribers gateway_detection_subscriber_ = nh_.subscribe(gateway_detection_topic_, 1, &JunctionManeuveringROS::gatewayDetectionCallback, this); distance_monitor_subscriber_ = nh_.subscribe(distance_monitor_topic_, 1, &JunctionManeuveringROS::distanceMonitorCallback, this); heading_monitor_subscriber_ = nh_.subscribe(heading_monitor_topic_, 1, &JunctionManeuveringROS::headingMonitorCallback, this); // publishers desired_heading_publisher_ = nh_.advertise<std_msgs::Float32>(desired_heading_topic_, 1); desired_velocity_publisher_ = nh_.advertise<std_msgs::Float32>(desired_velocity_topic_, 1); // service clients heading_control_switch_service_client_ = nh_.serviceClient<heading_control::Switch>(heading_control_switch_service_); heading_monitor_reset_service_client_ = nh_.serviceClient<robot_heading_monitor::Reset>(reset_heading_monitor_service_); distance_monitor_reset_service_client_ = nh_.serviceClient<robot_distance_monitor::Reset>(reset_distance_monitor_service_); motion_control_switch_service_client_ = nh_.serviceClient<motion_control::Switch>(motion_control_switch_service_); motion_control_params_service_client_ = nh_.serviceClient<motion_control::Params>(motion_control_params_service_); motion_control_drive_mode_service_client_ = nh_.serviceClient<motion_control::DriveMode>(motion_control_drive_mode_service_); } JunctionManeuveringROS::~JunctionManeuveringROS() { } void JunctionManeuveringROS::run() { junction_maneuvering_server_.start(); ROS_INFO("Junction maneuvering action server started"); } void JunctionManeuveringROS::junctionManeuveringExecute(const junction_maneuvering::JunctionManeuveringGoalConstPtr& goal) { reset(); ros::Rate r(controller_frequency_); // messages for publishing desired direction & velocity to controller std_msgs::Float32 desired_direction_msg; std_msgs::Float32 desired_velocity_msg; // action server feedback message junction_maneuvering::JunctionManeuveringFeedback feedback; // enable heading & motion controller enableHeadingController(); enableMotionController(); // set inflation radius to very low value as we are operating only in rotation and heading control mode (no obstacle avoidance) setMotionControllerParams(0.1); // we start in rotation drive mode setMotionControllerDriveMode(1); // set goal received to action server // this goal is then updated when robot is infronr of the door junction_maneuvering_.setGoal(goal->junction, goal->turn_direction, goal->distance, detected_gateways_); while(nh_.ok()) { // if goal is cancelled by the client if(junction_maneuvering_server_.isPreemptRequested()) { reset(); // disable both heading & motion controllers disableHeadingController(); disableMotionController(); // notify the ActionServer that we've successfully preempted ROS_DEBUG_NAMED("junction_maneuvering", "Preempting the current goal"); junction_maneuvering_server_.setPreempted(); return; } else { /** Junction maneuvering state machine -------------------------- State -1: move forward approximately at the center of junction State 0: now turn aligning with the junction wall State 1: align with detected corridor & move desired distance **/ if(junction_maneuvering_.getState() == -1) { if (junction_maneuvering_.computeInitialOrientation(detected_gateways_)) { resetHeadingMonitor(); } desired_direction_msg.data = junction_maneuvering_.getInitialOrientation(); desired_velocity_msg.data = velocity_; if(junction_maneuvering_.isStateChanged(monitored_distance_, monitored_heading_, detected_gateways_)) { // we switch the drive mode to rotation once robot reach infront of door setMotionControllerDriveMode(2); resetHeadingMonitor(); resetDistanceMonitor(); } } else if (junction_maneuvering_.getState() == 0) { desired_direction_msg.data = junction_maneuvering_.getTurnAngle(); desired_velocity_msg.data = velocity_; if(junction_maneuvering_.isStateChanged(monitored_distance_, monitored_heading_, detected_gateways_)) { // we switch the drive mode to heading control once robot is facing towards the door setMotionControllerDriveMode(1); resetHeadingMonitor(); resetDistanceMonitor(); } } else if (junction_maneuvering_.getState() == 1) { // keep updating robot orientation w.r.t the corridor if (junction_maneuvering_.computePassingOrientation(detected_gateways_)) { resetHeadingMonitor(); } desired_direction_msg.data = junction_maneuvering_.getPassingOrientation(); desired_velocity_msg.data = velocity_; if(junction_maneuvering_.isStateChanged(monitored_distance_, monitored_heading_, detected_gateways_)) { // mission successful, now set drive mode to default i.e 0 (obstacle avoidance) setMotionControllerDriveMode(0); disableHeadingController(); disableMotionController(); reset(); junction_maneuvering_server_.setSucceeded(junction_maneuvering::JunctionManeuveringResult(), "Goal reached"); return; } } desired_heading_publisher_.publish(desired_direction_msg); desired_velocity_publisher_.publish(desired_velocity_msg); } feedback.state = junction_maneuvering_.getState(); junction_maneuvering_server_.publishFeedback(feedback); r.sleep(); } } void JunctionManeuveringROS::loadParameters() { // detection std::string gateway_detection_topic; nh_.param<std::string>("gateway_detection_topic", gateway_detection_topic, "/gateways_detected"); gateway_detection_topic_ = gateway_detection_topic; ROS_DEBUG("gateway_detection_topic: %s", gateway_detection_topic_.c_str()); // monitors std::string distance_monitor_topic; nh_.param<std::string>("distance_monitor_topic", distance_monitor_topic, "/monitored_distance"); distance_monitor_topic_ = distance_monitor_topic; ROS_DEBUG("distance_monitor_topic: %s", distance_monitor_topic_.c_str()); std::string heading_monitor_topic; nh_.param<std::string>("heading_monitor_topic", heading_monitor_topic, "/monitored_heading"); heading_monitor_topic_ = heading_monitor_topic; ROS_DEBUG("heading_monitor_topic: %s", heading_monitor_topic_.c_str()); std::string reset_distance_monitor_service; nh_.param<std::string>("reset_distance_monitor_service", reset_distance_monitor_service, "/reset_distance_monitor"); reset_distance_monitor_service_ = reset_distance_monitor_service; ROS_DEBUG("reset_distance_monitor_service: %s", reset_distance_monitor_service_.c_str()); std::string reset_heading_monitor_service; nh_.param<std::string>("reset_heading_monitor_service", reset_heading_monitor_service, "/reset_heading_monitor"); reset_heading_monitor_service_ = reset_heading_monitor_service; ROS_DEBUG("reset_heading_monitor_service: %s", reset_heading_monitor_service_.c_str()); // low level control std::string heading_control_switch_service; nh_.param<std::string>("heading_control_switch_service", heading_control_switch_service, "/heading_control_switch"); heading_control_switch_service_ = heading_control_switch_service ; ROS_DEBUG("heading_control_switch_service service: %s", heading_control_switch_service.c_str()); std::string desired_heading_topic; nh_.param<std::string>("desired_heading_topic", desired_heading_topic, "/desired_heading"); desired_heading_topic_ = desired_heading_topic; ROS_DEBUG("desired_heading_topic: %s", desired_heading_topic_.c_str()); std::string desired_velocity_topic; nh_.param<std::string>("desired_velocity_topic", desired_velocity_topic, "/desired_velocity"); desired_velocity_topic_ = desired_velocity_topic; ROS_DEBUG("desired_velocity_topic: %s", desired_velocity_topic_.c_str()); std::string motion_control_switch_service; nh_.param<std::string>("motion_control_switch_service", motion_control_switch_service, "/motion_control_switch"); motion_control_switch_service_ = motion_control_switch_service ; ROS_DEBUG("motion_control_switch_service: %s", motion_control_switch_service.c_str()); std::string motion_control_params_service; nh_.param<std::string>("motion_control_params_service", motion_control_params_service, "/motion_control_params"); motion_control_params_service_ = motion_control_params_service ; ROS_DEBUG("motion_control_params_service: %s", motion_control_params_service.c_str()); std::string motion_control_drive_mode_service; nh_.param<std::string>("motion_control_drive_mode_service", motion_control_drive_mode_service, "/motion_control_drive_mode"); motion_control_drive_mode_service_ = motion_control_drive_mode_service ; ROS_DEBUG("motion_control_drive_mode_service: %s", motion_control_drive_mode_service.c_str()); // door passing params int controller_frequency; nh_.param<int>("controller_frequency", controller_frequency, 10); controller_frequency_ = controller_frequency; ROS_DEBUG("controller_frequency: %d", controller_frequency); double velocity; nh_.param<double>("velocity", velocity, 0.1); velocity_ = velocity; ROS_DEBUG("velocity: %f", velocity_); } void JunctionManeuveringROS::gatewayDetectionCallback(const gateway_msgs::Gateways::ConstPtr& msg) { detected_gateways_.hallway.left_angle = msg->hallway.left_angle; detected_gateways_.hallway.right_angle = msg->hallway.right_angle; detected_gateways_.hallway.left_range = msg->hallway.left_range; detected_gateways_.hallway.right_range = msg->hallway.right_range; detected_gateways_.t_junction.left_turn_angle = msg->t_junction.left_turn_angle; detected_gateways_.t_junction.left_turn_range = msg->t_junction.left_turn_range; detected_gateways_.t_junction.right_turn_angle = msg->t_junction.right_turn_angle; detected_gateways_.t_junction.right_turn_range = msg->t_junction.right_turn_range; detected_gateways_.t_junction.front_angle = msg->t_junction.front_angle; detected_gateways_.t_junction.front_range = msg->t_junction.front_range; detected_gateways_.x_junction.left_turn_angle = msg->x_junction.left_turn_angle; detected_gateways_.x_junction.left_turn_range = msg->x_junction.left_turn_range; detected_gateways_.x_junction.right_turn_angle = msg->x_junction.right_turn_angle; detected_gateways_.x_junction.right_turn_range = msg->x_junction.right_turn_range; detected_gateways_.x_junction.front_angle = msg->x_junction.front_angle; detected_gateways_.x_junction.front_range_x = msg->x_junction.front_range_x; detected_gateways_.x_junction.front_range_y = msg->x_junction.front_range_y; detected_gateways_.left_door.angle = msg->left_door.angle; detected_gateways_.left_door.range_x = msg->left_door.range_x; detected_gateways_.left_door.range_y = msg->left_door.range_y; detected_gateways_.right_door.angle = msg->right_door.angle; detected_gateways_.right_door.range_x = msg->right_door.range_x; detected_gateways_.right_door.range_y = msg->right_door.range_y; detected_gateways_.front_door.angle = msg->front_door.angle; detected_gateways_.front_door.range_x = msg->front_door.range_x; detected_gateways_.front_door.range_y = msg->front_door.range_y; } void JunctionManeuveringROS::distanceMonitorCallback(const std_msgs::Float32::ConstPtr& msg) { monitored_distance_ = msg->data; } void JunctionManeuveringROS::headingMonitorCallback(const std_msgs::Float32::ConstPtr& msg) { monitored_heading_ = msg->data; } void JunctionManeuveringROS::resetMonitors() { resetHeadingMonitor(); resetDistanceMonitor(); } void JunctionManeuveringROS::resetHeadingMonitor() { robot_heading_monitor::Reset heading_reset_srv; heading_reset_srv.request.reset = true; if (heading_monitor_reset_service_client_.call(heading_reset_srv)) { ROS_DEBUG("Heading monitor successfully reset"); monitored_heading_ = 0; } else { ROS_ERROR("Failed to reset heading monitor"); } } void JunctionManeuveringROS::resetDistanceMonitor() { robot_distance_monitor::Reset distance_reset_srv; distance_reset_srv.request.reset = true; if (distance_monitor_reset_service_client_.call(distance_reset_srv)) { ROS_DEBUG("Distance monitor successfully reset"); monitored_distance_ = 0; } else { ROS_ERROR("Failed to reset distance monitor"); } } void JunctionManeuveringROS::enableHeadingController() { heading_control::Switch heading_control_switch_service_msg; heading_control_switch_service_msg.request.enable = true; if (heading_control_switch_service_client_.call(heading_control_switch_service_msg)) ROS_DEBUG("Heading controller successfully enabled"); else ROS_ERROR("Failed to enable heading controller"); } void JunctionManeuveringROS::disableHeadingController() { heading_control::Switch heading_control_switch_service_msg; heading_control_switch_service_msg.request.enable = false; if (heading_control_switch_service_client_.call(heading_control_switch_service_msg)) ROS_DEBUG("Heading controller successfully disabled"); else ROS_ERROR("Failed to disable heading controller"); } void JunctionManeuveringROS::enableMotionController() { motion_control::Switch motion_control_switch_service_msg; motion_control_switch_service_msg.request.enable = true; if (motion_control_switch_service_client_.call(motion_control_switch_service_msg)) ROS_DEBUG("Motion controller successfully enabled"); else ROS_ERROR("Failed to enable motion controller"); } void JunctionManeuveringROS::disableMotionController() { motion_control::Switch motion_control_switch_service_msg; motion_control_switch_service_msg.request.enable = false; if (motion_control_switch_service_client_.call(motion_control_switch_service_msg)) ROS_DEBUG("Motion controller successfully disabled"); else ROS_ERROR("Failed to disable motion controller"); } void JunctionManeuveringROS::setMotionControllerParams(double inflation_radius) { motion_control::Params motion_control_params_service_msg; motion_control_params_service_msg.request.inflation_radius = inflation_radius; if (motion_control_params_service_client_.call(motion_control_params_service_msg)) ROS_DEBUG("Motion controller params successfully updated"); else ROS_ERROR("Failed to update motion controller params"); } void JunctionManeuveringROS::setMotionControllerDriveMode(int drive_mode) { motion_control::DriveMode motion_control_drive_mode_service_msg; motion_control_drive_mode_service_msg.request.drive_mode = drive_mode; if (motion_control_drive_mode_service_client_.call(motion_control_drive_mode_service_msg)) ROS_DEBUG("Motion controller drive mode successfully updated"); else ROS_ERROR("Failed to update motion controller drive mode"); } void JunctionManeuveringROS::reset() { junction_maneuvering_.reset(); resetMonitors(); }
#include <iostream> #include <map> #include <vector> #include <cmath> #include <algorithm> using namespace std; struct Point { int x; int y; Point() : x(0), y(0) {} Point(int a, int b) : x(a), y(b) {} }; Point reff(0, 1); bool cmp(Point a, Point b){ return atan2(a.y - reff.y, a.x - reff.x) < atan2(b.y - reff.y, b.x - reff.x); } class Solution { public: int maxPoints(vector<Point>& points) { vector<Point> originals; int result = 0; for(int i=0;i<points.size();i++) originals.push_back(points[i]); for(int i=0;i<originals.size();i++){ bool marked[10000] = {}; reff.x = originals[i].x; reff.y = originals[i].y; sort(points.begin(), points.end(), cmp); int samenumber = 0, current = 1; for(int j=0;j<points.size();j++) if(points[j].x == reff.x && points[j].y == reff.y){ samenumber++; marked[j] = true; } result = max(result, samenumber); Point prev; bool prevFlag = true; for(int j=0;j<points.size();j++){ if(marked[j]) continue; if(prevFlag){ prev = points[j]; prevFlag = false; continue; } Point a = points[j]; if(atan2(a.y - reff.y, a.x - reff.x) != atan2(prev.y - reff.y, prev.x - reff.x)){ result = max(result, samenumber + current); current = 1; } else current++; prev = points[j]; } if(samenumber < points.size()) result = max(result, samenumber + current); } return result; } }; int main(){ int N; vector<Point> v; cin >> N; for(int i=0;i<N;i++){ int x,y; cin >> x >> y; Point a(x,y); v.push_back(a); } Solution solution; cout << solution.maxPoints(v) << endl; }
#include"random.h" using namespace std; namespace shady_engine { random::random() { mRandEngine.seed(chrono::steady_clock::now().time_since_epoch().count()); } random::~random() { } void random::update() { mRandEngine.seed(chrono::steady_clock::now().time_since_epoch().count()); } float random::real(float pMin, float pMax) { std::uniform_real_distribution<> distReal(pMin,pMax); return distReal(mRandEngine); } int random::integer(int pMin, int pMax) { std::uniform_int_distribution<> distReal(pMin, pMax); return distReal(mRandEngine); } glm::vec3 random::inside_unit_sphere() { std::uniform_real_distribution<> distReal(0.0f, 1.1f); glm::vec3 point; point.x = distReal(mRandEngine); point.y = distReal(mRandEngine); point.z = distReal(mRandEngine); return point; } } //End of namespace
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * George Refseth, rfz@opera.com */ #ifndef OPERA7IMPORTER_H #define OPERA7IMPORTER_H #include "adjunct/m2/src/import/importer.h" #include "adjunct/m2/src/util/blockfile.h" class OpFile; class Account; class StoreReader; class Opera7Importer : public Importer { public: Opera7Importer(); ~Opera7Importer(); OP_STATUS Init(); OP_STATUS ImportAccounts(); OP_STATUS AddImportFile(const OpStringC& path); BOOL GetContactsFileName(OpString& fileName); void GetDefaultImportFolder(OpString& path); virtual OP_STATUS ImportMessages() { m_should_import_messages = TRUE; return OpStatus::OK; } protected: BOOL OnContinueImport(); void OnCancelImport(); void SetImportItems(const OpVector<ImporterModelItem>& items); private: BOOL GetOperaIni(OpString& fileName); OP_STATUS ImportAccount(const ImporterModelItem * item); OP_STATUS ImportAccountMessages(const ImporterModelItem * item, Account * account); OP_STATUS ImportSingle(); Opera7Importer(const Opera7Importer&); Opera7Importer& operator =(const Opera7Importer&); private: int m_current_block; PrefsFile* m_accounts_ini; INT32 m_treePos; BOOL m_inProgress; OpString m_m2FolderPath; Account* m_account; StoreReader * m_store_reader; int m_import_accountID; // The Opera7Importer by default doesn't import messages, // but will be done if ImportMessages() is called before ImportAccounts() is called BOOL m_should_import_messages; }; #endif//OPERA7IMPORTER_H
#include <bits/stdc++.h> using namespace std; struct tNode{ int data; tNode *left; tNode *right; tNode(int x):data(x),left(NULL),right(NULL){} }; class Solution{ public: //递归转换 tNode* convert_bst_to_dll(tNode *root){ root = sub_convert(root); while(root->left){ root = root->left; } return root; } tNode* sub_convert(tNode* root){ if(!root ||(!root->left && !root->right)){ return root; } tNode *temp = NULL; if(root->left){ temp = sub_convert(root->left); while(temp->right){ temp = temp->right; } temp->right = root; root->left = temp; } if(root->right){ temp = sub_convert(root->right); while(temp->left){ temp = temp->left; } root->right = temp; temp->left = root; } return root; } //非递归转换 tNode* convert2(tNode *root){ if(!root){ return root; } stack<tNode*> node_stack; tNode *cur = root; tNode *old = NULL; tNode *head = NULL; while(true){ while(cur){ node_stack.push(cur); cur = cur->left; } if(node_stack.empty()){ break; } //此时无左孩子,输出栈顶元素 cur = node_stack.top(); node_stack.pop(); if(old){ old->right = cur; cur->left = old; } if(!head){ head = cur; } old = cur; cur = cur->right; } return head; } }; int main(){ return 0; }
#ifndef _POINTBASE_H_ #define _POINTBASE_H_ 1 class PointBase { public: // GETTERS / SETTERS double getX(); void setX( double x ); double getY(); void setY( double y ); double getZ(); void setZ( double z ); double getW(); double* asVector(); protected: // MEMBER VARIABLES double x,y,z,w; }; #endif
#include "utils.hpp" #include "poetry_pool_ptts.hpp" namespace nora { namespace config { poetry_pool_ptts& poetry_pool_ptts_instance() { static poetry_pool_ptts inst; return inst; } void poetry_pool_ptts_set_funcs() { } } }