text
stringlengths 8
6.88M
|
|---|
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define oo 666666666
ll t,n,q,R,mod,mod2,tp;
ll A[200001];
ll powm(ll a, ll deg, ll M)
{
if(deg==0)return 1%M;
if(deg&1)return a*powm(a,deg-1,M)%M;
return powm(a*a%M,deg/2,M);
}
void precalc(int n, vector<ll>&Ri, vector<ll>&RS, vector<ll>&RD, ll M)
{
Ri[0]=RS[0]=1%M;
RD[0]=0;
for(int i=1; i<=n; i++)
Ri[i]=(Ri[i-1]*R)%M;
for(int i=1; i<=n; i++)
RS[i]=(RS[i-1]+Ri[i])%M;
for(int i=1; i<=n; i++)
RD[i]=(RD[i-1] + i*Ri[i])%M;
}
void build(vector<array<ll,3>>&seg, int c, int l, int r, ll M)
{
seg[c][1]=seg[c][2]=0;
if(l==r)
{
seg[c][0]=A[r]%M;
return;
}
int m = (l+r)/2;
build(seg,2*c,l,m,M);
build(seg,2*c+1,m+1,r,M);
seg[c][0]=(seg[2*c][0] + seg[2*c+1][0])%M;
}
void lazy(vector<array<ll,3>>&seg, int c, int l, int r, ll M, vector<ll>&Ri, vector<ll>&RS, vector<ll>&RD)
{
if(seg[c][1]==0 && seg[c][2]==0)return;
ll S = seg[c][1], D = seg[c][2];
ll x = r-l;
seg[c][0] = (seg[c][0] + ((S*RS[x])%M) + ((D*RD[x])%M))%M;
if(l!=r)
{
seg[2*c][1]=(seg[2*c][1]+S)%M;
seg[2*c][2]=(seg[2*c][2]+D)%M;
ll m =(l+r)/2;
ll skip = m-l+1;
S = (S*Ri[skip])%M;
D = (D*Ri[skip])%M;
S = (S+skip*D)%M;
seg[2*c+1][1]=(seg[2*c+1][1]+S)%M;
seg[2*c+1][2]=(seg[2*c+1][2]+D)%M;
}
seg[c][1]=seg[c][2]=0;
}
void change(vector<array<ll,3>>&seg, int c, int l, int r, int pos, ll val, ll M, vector<ll>&Ri, vector<ll>&RS, vector<ll>&RD)
{
lazy(seg,c,l,r,M,Ri,RS,RD);
if(l==r)
{
seg[c][0]=val%M;
return;
}
int m = (l+r)/2;
if(pos<=m)change(seg,2*c,l,m,pos,val,M,Ri,RS,RD);
else change(seg,2*c+1,m+1,r,pos,val,M,Ri,RS,RD);
lazy(seg,2*c,l,m,M,Ri,RS,RD);
lazy(seg,2*c+1,m+1,r,M,Ri,RS,RD);
seg[c][0]=(seg[2*c][0] + seg[2*c+1][0])%M;
}
ll get(vector<array<ll,3>>&seg, int c, int l, int r, int L, int R, ll M, vector<ll>&Ri, vector<ll>&RS, vector<ll>&RD)
{
lazy(seg,c,l,r,M,Ri,RS,RD);
if(l>r || l>R || r<L)return 0;
if(l>=L && r<=R)return seg[c][0];
int m = (l+r)/2;
return (get(seg,2*c,l,m,L,R,M,Ri,RS,RD) + get(seg,2*c+1,m+1,r,L,R,M,Ri,RS,RD))%M;
}
void AGP(vector<array<ll,3>>&seg, int c, int l, int r, int L, int R, ll M, ll S, ll D,
vector<ll>&Ri, vector<ll>&RS, vector<ll>&RD)
{
lazy(seg,c,l,r,M,Ri,RS,RD);
if(l>r || l>R || r<L)return;
if(l>=L && r<=R)
{
ll idx = l-L;
D = (D*Ri[idx])%M;
S = (S*Ri[idx])%M;
S = (S + idx*D)%M;
seg[c][1]=S;
seg[c][2]=D;
lazy(seg,c,l,r,M,Ri,RS,RD);
return;
}
int m = (l+r)/2;
AGP(seg,2*c,l,m,L,R,M,S,D,Ri,RS,RD);
AGP(seg,2*c+1,m+1,r,L,R,M,S,D,Ri,RS,RD);
seg[c][0] = (seg[2*c][0] + seg[2*c+1][0])%M;
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);
cin>>t;
while(t--)
{
cin>>n>>q>>R>>mod>>mod2;
vector<array<ll,3>>seg1(4*n+4); //[sum % mod][lazyS][lazyD]
vector<array<ll,3>>seg2(4*n+4); //[sum % mod2][lazyS][lazyD]
vector<ll>Ri1(n+1);//R[i] = R^i
vector<ll>RS1(n+1);//R[i] = 1 + R + R^2 + ... + R^i
vector<ll>RD1(n+1);//R[i] = 0 + R + 2*R^2 + ... + i*R^i
vector<ll>Ri2(n+1);//R[i] = R^i
vector<ll>RS2(n+1);//R[i] = 1 + R + R^2 + ... + R^i
vector<ll>RD2(n+1);//R[i] = 0 + R + 2*R^2 + ... + i*R^i
for(int i=1; i<=n; i++)
cin>>A[i];
build(seg1,1,1,n,mod);
build(seg2,1,1,n,mod2);
precalc(n,Ri1,RS1,RD1,mod);
precalc(n,Ri2,RS2,RD2,mod2);
while(q--)
{
cin>>tp;
if(tp==0)
{
ll S,D,L,R;
cin>>S>>D>>L>>R;
AGP(seg1,1,1,n,L,R,mod,S,D,Ri1,RS1,RD1);
AGP(seg2,1,1,n,L,R,mod2,S,D,Ri2,RS2,RD2);
// for(int i=1; i<=n; i++)
// cout<<get(seg1,1,1,n,i,i,mod,Ri1,RS1,RD1)<<(i==n?" <-after adding AGP\n":" ");
}
else if(tp==1)
{
ll x,g;
cin>>x>>g;
ll val = get(seg2,1,1,n,x,x,mod2,Ri2,RS2,RD2);
val=powm(val,g,mod2);
change(seg1,1,1,n,x,val,mod,Ri1,RS1,RD1);
change(seg2,1,1,n,x,val,mod2,Ri2,RS2,RD2);
}
else
{
ll L,R;
cin>>L>>R;
cout<<get(seg1,1,1,n,L,R,mod,Ri1,RS1,RD1)<<"\n";
}
}
}
}
|
//------------------------------------------------------------------------------
// <copyright file="wxMainWindow.h" company="UNAM">
// Copyright (c) Universidad Nacional Autónoma de México.
// </copyright>
//------------------------------------------------------------------------------
// Shared memory between threads.
//------------------------------------------------------------------------------
#pragma once
#include "wxRGBACanvas.h"
#include "KinectParams.h"
#include <boost/thread/condition.hpp>
class ProcessingStatus
{
public:
typedef enum KinectStatus {
DISCONNECTION_FAILED = -2,
CONNECTION_FAILED = -1,
DISCONNECTED = 0,
CONNECTING,
CONNECTED
} KinectStatus;
private:
// Kinect connected
KinectStatus m_kinectConnected;
boost::condition m_kinectConnectedCond;
bool m_requestDisconnect;
public:
ProcessingStatus();
void SetKinectConnected(KinectStatus kinectConnected);
KinectStatus GetKinectConnected(void);
boost::condition& GetCondition(void);
void SetRequestDisconnect(bool request);
bool GetRequestDisconnect(void);
};
class Blackboard
{
private:
// Parameters
/// <description>
/// Only thread safe constructor and assingment operators are to be used with this object.
/// </description>
//KinectParams m_currentKinectParams;
/// <description>
/// Object where the GUI can set user choices.
/// </description>
KinectParams m_nextKinectParams;
NuiParams m_nextNuiParams;
ProcessingStatus m_processingStatus;
SurfaceReconstruction m_surfaceReconstruction;
public:
Blackboard(void);
~Blackboard(void);
ProcessingStatus& GetProcessingStatus(void);
/// <summary>
/// Gives access to the parameters that can be set from the user interface.
/// </summary>
KinectParams& GetNextKinectParams(void);
/// <summary>
/// Gives access to the nui parameters that can be set from the user interface.
/// </summary>
NuiParams& GetNextNuiParams(void);
/// <summary>
/// Gives access to image's and volume's information.
/// </summary>
SurfaceReconstruction& GetSurfaceReconstruction(void);
};
|
#pragma once
class Unit
{
protected:
int m_atk;
int m_def;
public:
Unit();
~Unit();
int GetAtk() { return m_atk; }
void SetAtk(int atk) { m_atk = atk; }
int GetDef() { return m_def; }
void SetDef(int def) { m_def = def; }
};
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
const int node_max = 200050;
vector<int> graph[node_max];
int dist[node_max];
int ans[node_max];
bool visited[node_max];
void bfs(int v){
queue<int> q;
q.push(v);
dist[v] = 0;
while(!q.empty()){
int now = q.front(); q.pop();
for(auto next: graph[now]){
if (visited[next]) continue;
dist[next] = dist[now] + 1;
q.push(next);
}
visited[now] = true;
}
}
queue<int> num[3];
bool setdata(int i, int box){
int res = 0;
if (!num[box].empty()) {
ans[i] = num[box].front();
num[box].pop();
return true;
} else {
return false;
}
}
int main()
{
int n;
cin >> n;
vector<P> a(n-1);
rep(i, n-1){
int tmp1, tmp2;
cin >> tmp1 >> tmp2;
tmp1--; tmp2--;
graph[tmp1].push_back(tmp2);
graph[tmp2].push_back(tmp1);
}
bfs(0);
//rep(i, n) cout << dist[i] << endl;
int gu = 0;
int ki = 0;
rep(i, n) {
if(dist[i]%2==0) gu++;
else ki++;
}
rep(i, n){
int id = i+1;
num[id%3].push(id);
}
// 11122200
if (gu <= n/3){
rep(i, n){
if (dist[i]%2==0){
setdata(i, 0);
}else{
setdata(i, 1) || setdata(i, 2) || setdata(i, 0);
}
}
} else if (ki <= n/3){
rep(i, n){
if (dist[i]%2!=0){
setdata(i, 0);
}else{
setdata(i, 1) || setdata(i, 2) || setdata(i, 0);
}
}
} else {
rep(i, n){
if (dist[i]%2==0){
setdata(i, 1) || setdata(i, 0);
}else{
setdata(i, 2) || setdata(i, 0);
}
}
}
rep(i, n){
cout << ans[i] << " ";
}
}
|
#include <JeeLib.h>
#include <Ports.h>
// Joystick values structure
struct Joy_Vals
{
int JoyR_L;
int JoyD_U;
};
Port port1 = Port(1); // Up-Down Value Port
Port port2 = Port(2); // Right-Left Value Port
Port port3 = Port(3); // Vehicle_Status Button
void setup() {
// Begin RF Transmission on Channel 69
rf12_initialize(2, RF12_915MHZ, 69);
// Setting the AIO pin on ports 1 and 2 to input, and setting the DIO pin on port 3 to input (Vehicle_Status Button)
port1.mode2(INPUT);
port2.mode2(INPUT);
port3.mode(INPUT);
}
// Joystick values reader, return a Joy_Vals structure
struct Joy_Vals Joy_Get()
{
// Joystick values temp variables
int JoyD_U=0,JoyR_L=0;
// loop variable
int i=0;
for(;i<20;i++){
// reading in the Joystick values 20 times and finding the sum
JoyD_U += port1.anaRead(); // read from AIO of the “port”
JoyR_L += port2.anaRead(); // read from AIO of the “port"
}
// creating the temporary structure
struct Joy_Vals Joy_Values;
// averaging the read values and saving in the structure
Joy_Values.JoyD_U = (JoyD_U/20);
Joy_Values.JoyR_L = (JoyR_L/20);
// returning the structure
return Joy_Values;
}
/* This function is used in the remote to send data to the vehicle
* This function is not used on the vehicle
*
* vehicle_status: status of the vehicle (1: remote, 0: autonomous)
* AIN1, AIN2, BIN1, BIN2; motor states; forward/backward for motors 1 and 2
* r_motor, l_motor: right and left motor PWM values
*/
void jeenode_send(bool vehicle_status, bool AIN1, bool AIN2, bool BIN1, bool BIN2, byte r_motor,byte l_motor)
{
// array of 3 bytes
byte send_msg[3];
// setting the vehicle_status in the transmission
if (vehicle_status == true)
send_msg[0] = 0xF0;
else
send_msg[0] = 0x00;
send_msg[0] |= AIN2 << 3;
send_msg[0] |= AIN1 << 2;
send_msg[0] |= BIN1 << 1;
send_msg[0] |= BIN2;
// setting the motor PWMs in the transmission
send_msg[1] = r_motor;
send_msg[2] = l_motor;
// checking if sending can be done
while(!rf12_canSend()) // Is the air busy, or can you send?
rf12_recvDone(); //if you cant send, complete any receiving that you
// are doing
// sending the data
rf12_sendStart(0, &send_msg, sizeof(byte) * 3); // give address to payload, and
// the payload size is 5 which is
// the size of the packet
}
void loop() {
// Temporary variables
int JoyD_U=0;
int JoyR_L=0;
bool AN1 = 0;
bool AN2 = 0;
bool BN1 = 0;
bool BN2 = 0;
byte ValueR = 0;
byte ValueL = 0;
bool remote = 0;
// creating a structure, reading the Joystick values and putting them in the temporary variables
struct Joy_Vals values = Joy_Get();
JoyD_U = values.JoyD_U;
JoyR_L = values.JoyR_L;
// reading the vehicle status button (1 for remote, 0 for autonomous)
remote = port3.digiRead();
if(JoyD_U > 550){
// The vehicle has a forward movement
AN1=true;
BN1=true;
}else if(JoyD_U < 474){
// The vehicle has a backward movement
AN2=true;
BN2=true;
}else if(JoyR_L > 550){
// The vehicle is doing a 360 to the left
AN2=true;
BN1=true;
}else if(JoyR_L < 474){
// The vehicle is doing a 360 to the right
AN1=true;
BN2=true;
}
if(JoyR_L > 950){
// The vehicle is doing a hard left turn
ValueL = 110;
ValueR = 255;
}else if(JoyR_L > 850){
// The vehicle is doing a slower left turn
ValueL = 255;
ValueR = 140;
}else if(JoyR_L > 750){
// The vehicle is doing a slower left turn
ValueL = 255;
ValueR = 160;
}else if(JoyR_L > 650){
// The vehicle is doing a slower left turn
ValueL = 255;
ValueR = 180;
}else if(JoyR_L > 550){
// The vehicle is doing slow left turn
ValueL = 255;
ValueR = 210;
}else if(JoyR_L < 74){
// The vehicle is doing a hard right turn
ValueL = 255;
ValueR = 110;
}else if(JoyR_L < 174){
// The vehicle is doing a slower right turn
ValueL = 255;
ValueR = 140;
}else if(JoyR_L < 274){
// The vehicle is doing a slower right turn
ValueL = 255;
ValueR = 160;
}else if(JoyR_L < 374){
// The vehicle is doing a slower right turn
ValueL = 255;
ValueR = 180;
}else if(JoyR_L < 474){
// The vehicle is doing slow right turn
ValueL = 255;
ValueR = 210;
}else{
// The vehicle is not doing any turns, therefore either forward or backward
ValueL = 255;
ValueR = 255;
}
// Transmitting the data to the vehicle
jeenode_send(remote,AN1,AN2,BN1,BN2,ValueR,ValueL);
}
|
#ifndef HW_264_DECODER_H
#define HW_264_DECODER_H
#include "MediaDecoder.h"
#include "HwMediaDecoder.h" //from libhwcodec
#include "SwsScale.h"
//硬解码: h264->YUV[420p]
////////////////////////////////////////////////////////////////////////////////
class CHw264Decoder : public CMediaDecoder
{
public:
CHw264Decoder(AVCodecContext *videoctx, CHwMediaDecoder *pDecode);
virtual ~CHw264Decoder();
public:
virtual CBuffer *Decode(CBuffer *pRawdata/*h264*/);
private:
CHwMediaDecoder *m_pDecode;
CSwsScale *m_pScales;
CLASS_LOG_DECLARE(CHw264Decoder);
};
#endif
|
#include "cutsphere.h"
CutSphere::CutSphere(int _xcenter, int _ycenter, int _zcenter, int _radius )
{
xcenter = _xcenter;
ycenter = _ycenter;
zcenter = _zcenter;
radius = _radius;
}
CutSphere::~CutSphere()
{
}
void CutSphere::draw(Sculptor &t){
for (int i = xcenter-radius; i < xcenter+radius; i++) {
for (int j = ycenter-radius; j < ycenter+radius; j++){
for (int k = zcenter-radius; k < zcenter+radius; k++){
if(((float)pow((i-xcenter),2))+((float)pow((j-ycenter),2))+((float)pow((k-zcenter),2))<=(pow(radius,2))){
t.cutVoxel(i,j,k);
}
}
}
}
}
|
#pragma once
#include <vector>
namespace Utils
{
template<typename T>
bool Remove(std::vector<T>& vec, T item) //is this bad???
{
int index = -1;
for (int i = 0; i < vec.size(); ++i)
{
if (vec[i] == item)
{
index = i;
break;
}
}
if (index != -1)
{
vec.erase(vec.begin() + index);
return true;
}
return false;
}
template<typename T>
void PushFront(std::vector<T>& vec, T item)
{
vec.insert(vec.begin(), item);
}
/*
returns -1 if not found
*/
template<typename T>
int FindIndex(std::vector<T>& vec, T item)
{
int index = -1;
for (int i = 0; i < vec.size(); ++i)
{
if (vec[i] == item)
{
index = i;
break;
}
}
return index;
}
}
|
#ifndef NYUPARSER_H
#define NYUPARSER_H
#include "geom/geometry.h"
#include "geom/transform.h"
#include "glm/glm.hpp"
#include "parse/tokens.h"
class Scene;
class Camera;
class Box;
class Plane;
class Sphere;
class NYUParser{
private:
Tokenizer * tokenizer;
// helper functions
void ParseLeftAngle();
void ParseRightAngle();
double ParseDouble();
void ParseLeftCurly();
void ParseRightCurly();
void ParseComma();
void ParseVector(glm::vec3 & v);
void ParseRGBFColor(glm::vec3 & c, float & f);
void ParseRGBColor(glm::vec3 & c, float & f);
void ParseColor(glm::vec3 & c, float & f);
void PrintColor(glm::vec3 & c, float & f);
void ParseMatrix();
void ParseTransform(Geometry & s);
void ParsePigment(Material & p);
void PrintPigment(Material & p);
void ParseFinish(Material & f);
void PrintFinish(Material & f);
// void ParseInterior( struct Interior* interior);
void ParseInterior(float & ior);
// void InitModifiers(struct ModifierStruct* modifiers);
// void ParseModifiers(struct ModifierStruct* modifiers);
// void PrintModifiers(struct ModifierStruct* modifiers);
void ParseSubtract(Geometry & s);
void ParseIntersect(Geometry & s);
void ParseUnion(Geometry & s);
void ParseModifiers(Geometry & s);
void PrintModifiers(Geometry & s);
Camera ParseCamera();
Sphere * ParseSphere();
Box * ParseBox();
void ParseCylinder();
// Cone * ParseCone();
Plane * ParsePlane(); // added by mbecker
Light * ParseLightSource();
void ParseGlobalSettings();
public:
void parse(std::fstream & input, Scene & s);
// Parse(FILE* infile);
};
#endif
|
#ifndef LEVELCONFIGDIALOG_HPP
#define LEVELCONFIGDIALOG_HPP
#include <QDialog>
#include <QFileDialog>
namespace Ui
{
class LevelConfigDialog;
}
namespace Maint
{
class LevelConfigDialog : public QDialog
{
Q_OBJECT
Ui::LevelConfigDialog *ui;
bool ShowFileDialog(QString& selectedPath, QFileDialog::AcceptMode acceptMode = QFileDialog::AcceptOpen);
public:
explicit LevelConfigDialog(QWidget *parent = 0);
~LevelConfigDialog();
/**
* @return The level path from the level path box.
*/
QString GetLevelPath();
/**
* @return The config path from the config path box.
*/
QString GetConfigPath();
/**
* @return The value in the level width box.
*/
int GetLevelWidth();
/**
* @return The value in the level height box.
*/
int GetLevelHeight();
/**
* @return The value in the tiles wide box.
*/
int GetTilesetTilesWide();
/**
* @return The value in the tiles high box.
*/
int GetTilesetTilesHigh();
private slots:
/**
* @brief Opens a file dialog to browse for a level path, and puts the result in
* the level path box.
*/
void BrowseLevelPath();
/**
* @brief Opens a file dialog to browse for a config path, and puts the result in
* the config path box.
*/
void BrowseConfigPath();
/**
* @brief Opens a file dialog box to browse for a new config path location, and puts
* the result in the config path box.
*/
void BrowseNewConfigPath();
};
}
#endif // LEVELCONFIGDIALOG_HPP
|
/*
* Kaveh Pezeshki and Christopher Ferrarin
* E155 Lab 6
*
* Displays a voltage string sent over UART, printing the button state whenever it is updated
* Much of the basic ESP8266 code adapted from: https://randomnerdtutorials.com/esp8266-web-server/
* RX = D2
* TX = D3
*/
//Loading the ESP8266 library
#include <ESP8266WiFi.h>
#include <SPISlave.h>
#include <SoftwareSerial.h>
//defining response and webpage for client
const char* response[] = {
"HTTP/1.1 200 OK",
"Content-type:text/html",
"Connection: close",
""
};
const char* webpage[] = {
"<!DOCTYPE html><html>",
"<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
"<link rel=\"icon\" href=\"data:,\">",
"<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}",
".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;",
"text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}",
".button2 {background-color: #77878A;}</style></head>",
"<body><h1>E155 Lab6: ESP8266 SPI Slave</h1>",
//button will be displayed here
"</body></html>",
""
};
//Defining network information
const char* networkName = "CINE";
const char* password = NULL;
//Defining the web server and HTTP request variables
WiFiServer server(80);
String request; //storing HTTP request
String currentLine; //storing incoming data from the client
int buttonState = 0; //the data to return in an SPI transaction, current state of webpage button
String voltage; //the voltage data sent from the SPI master
//Defining the softwareSerial implementation
SoftwareSerial NodeMCU(2, 3);
void setup() {
Serial.begin(9600); //keeping a serial connection open for debugging
Serial.setDebugOutput(true);
Serial.println("Connecting to Network");
WiFi.begin(networkName, password);
//waiting until connection to network complete
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Attempting connection...");
}
//At this point we are connected to the network. Printing status information:
Serial.print("Connected to WiFi network with IP: ");
Serial.println(WiFi.localIP());
//Starting server
Serial.println("Starting server");
server.begin();
//Starting a software serial connection
NodeMCU.begin(9600);
/*
SPISlave.onData([](uint8_t * data, size_t len) {
String message = String((char *)data);
(void) len;
Serial.print("Received data from master: ");
Serial.println(message);
voltage = message;
SPISlave.setData(buttonState);
});
// The master has read out outgoing data buffer
// that buffer can be set with SPISlave.setData
SPISlave.onDataSent([]() {
Serial.println("Answer Sent");
});
// status has been received from the master.
// The status register is a special register that bot the slave and the master can write to and read from.
// Can be used to exchange small data or status information
SPISlave.onStatus([](uint32_t data) {
Serial.printf("Status: %u\n", data);
SPISlave.setStatus(millis()); //set next status
});
// The master has read the status register
SPISlave.onStatusSent([]() {
Serial.println("Status Sent");
});
// Setup SPI Slave registers and pins
SPISlave.begin();
// Sets the data registers. Limited to 32 bytes at a time.
// SPISlave.setData(uint8_t * data, size_t len); is also available with the same limitation
SPISlave.setData(buttonState); */
}
void loop() {
//updating buttonState
while(NodeMCU.available()) {
char character = NodeMCU.read();
Serial.print("received from UART: ");
Serial.println(character);
if (character == '/') {voltage = "";}
else voltage.concat(character);
}
//Listening for new connections
WiFiClient webClient = server.available();
//Passing the webpage if a new client connects
if (webClient) {
Serial.println("Client connected");
Serial.println("Button State");
Serial.print(buttonState);
NodeMCU.print(buttonState);
currentLine = "";
while (webClient.connected()) {
if (webClient.available()) { //if there are bytes to read from the client
char byteIn = webClient.read();
Serial.write(byteIn);
request += byteIn;
//if the received line is empty, and a newline characted is received, this is the end of the client HTTP request, so send a response
if (byteIn == '\n') {
if (currentLine.length() == 0) {
//transmitting response
Serial.println("transmitting response...");
for (int i = 0; i < 4; i++) {
webClient.println(response[i]);
Serial.println(response[i]);
}
if (request.indexOf("GET /1/on") >= 0) {
buttonState = 1;
NodeMCU.print(1);
}
if (request.indexOf("GET /1/off") >= 0) {
buttonState = 0;
NodeMCU.print(0);
}
//displaying the webpage
Serial.println("transmitting webpage...");
for (int i = 0; i < 8; i++) { //lines before button press
webClient.println(webpage[i]);
Serial.println(webpage[i]);
}
//displaying SPI input data
webClient.println("<p>Voltage: " + voltage + "</p>");
Serial.println("<p>Voltage: " + voltage + "</p>");
//displaying the button
if (buttonState==0) {
webClient.println("<p><a href=\"/1/on\"><button class=\"button\">ON</button></a></p>");
Serial.println("<p><a href=\"/1/on\"><button class=\"button\">ON</button></a></p>");
} else {
webClient.println("<p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>");
Serial.println("<p><a href=\"/1/off\"><button class=\"button button2\">OFF</button></a></p>");
}
//displaying the remainder of the webpage
for (int i = 8; i < 10; i++) {
webClient.println(webpage[i]);
Serial.println(webpage[i]);
}
//breaking out of the while loop
break;
}
else {
currentLine = "";
}
}
else if (byteIn != '\r') {
currentLine += byteIn;
}
}
}
//ending the transaction
request = "";
webClient.stop();
Serial.println("Client disconnected");
}
}
|
#ifndef WIB_BUILD_H
#define WIB_BUILD_H
#pragma once
#include <vector>
#include <map>
#include <string>
namespace WhatIBuild
{
class Unit
{
public:
Unit(const std::string& filename, const std::string& path);
~Unit();
const std::string& GetFileName() const { return m_Filename; }
const std::string& GetPath() const { return m_Path; }
private:
std::string m_Filename;
std::string m_Path;
};
class Property
{
public:
Property();
Property(const std::string& name, const std::string& value);
~Property();
const std::string& GetName() const { return m_Name; }
const std::string& GetValue() const { return m_Value; }
size_t GetCount() const { return m_Properties.size(); }
const Property& GetProperty(size_t index) const
{
return m_Properties[index];
}
void AddProperty(const Property& property)
{
m_Properties.push_back(property);
}
private:
std::string m_Name;
std::string m_Value;
std::vector<Property> m_Properties;
};
/// Module contains information about project
class Module
{
public:
/// Project properties
enum PropertyEnum
{
e_ProjectConfigurations, /// ItemGroup Label="ProjectConfigurations"
e_Globals, /// PropertyGroup Label="Globals"
e_ConfigurationSettings, /// PropertyGroup Condition="..." Label="Configuration"
e_PropertySheets, /// ImportGroup Label="PropertySheets" Condition="..."
e_PropertiesCount
};
static const size_t INVALID_INDEX;
Module(const std::string& name, const std::string& path);
~Module();
const std::string& GetName() const { return m_Name; }
const std::string& GetPath() const { return m_Path; }
const Unit& GetUnit(size_t index) const { return m_Units[index]; }
size_t GetUnitsCount() const { return m_Units.size(); }
const Property& GetProperty(PropertyEnum propertyId) const
{
return m_Properties[propertyId];
}
size_t Lookup(const std::string& path) const;
void AddUnit(const Unit& unit);
void AddProperty(PropertyEnum propertyId, const Property& property);
private:
std::vector<Unit> m_Units;
std::map<std::string, size_t> m_Lookup;
Property m_Properties[e_PropertiesCount];
std::string m_Name;
std::string m_Path;
};
class Build
{
public:
static const size_t INVALID_INDEX;
Build();
~Build();
const Module& GetModule(size_t index) const { return m_Modules[index]; }
size_t GetModulesCount() const { return m_Modules.size(); }
size_t Lookup(const std::string& name) const;
void AddModule(const Module& module);
private:
std::vector<Module> m_Modules;
std::map<std::string, size_t> m_Lookup;
};
}
#endif // WIB_BUILD_H
|
// Copyright (c) 2015 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// This test case demonstrates the issue described in #1481:
// Sync primitives safe destruction
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <pika/thread.hpp>
#include <chrono>
#include <thread>
void test_safe_destruction()
{
pika::thread t;
pika::future<void> outer;
{
pika::lcos::local::promise<void> p;
pika::shared_future<void> inner = p.get_future().share();
// Delay returning from p.set_value() below to destroy the promise
// before set_value returns.
outer = inner.then([](pika::shared_future<void>&&) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
});
// create a thread which will make the inner future ready
t = pika::thread([&p]() { p.set_value(); });
inner.get();
}
outer.get();
t.join();
}
int pika_main()
{
test_safe_destruction();
return pika::finalize();
}
int main(int argc, char* argv[])
{
PIKA_TEST_EQ_MSG(pika::init(pika_main, argc, argv), 0, "pika main exited with non-zero status");
return 0;
}
|
#include <iostream>
#include <stdio.h>
#include "MinIntStack.h"
using std::cout;
using std::endl;
// does this need "const"?
void pushTest(MinIntStack *m,int val,int min){
cout << endl<<"push "<<val<<endl;
m->push(val);
cout << (m->isEmpty()?"(bad) is empty":" not empty")<<endl;
cout << " length: "<<m->size()<<endl;
int mn = m->getMin();
cout << " min: "<<mn<<(mn==min?"(valid)":"(invalid)")<<endl;
}
void popTest(MinIntStack *m,int test,int min){
try{
int p = m->pop();
int mn = m->getMin();
cout << endl<<"try pop: "<<p<<(p==test?"(valid)":"(invalid)")<<endl;
cout << " new min: "<<mn<<(mn==min?"(valid)":"(invalid)")<<endl;
}catch(int i){
cout << " catch pop(empty)"<<endl;
}
}
int main(){
MinIntStack *min = new MinIntStack();
// puts(min->getHeadPos()+""); // can't handle ints
cout << "base test:"<<endl;
cout << (min->isEmpty()?" is empty":" (bad) not empty")<<endl;
cout << " size: "<<min->size()<<endl;
int pop;
try{
pop = min->pop();
cout <<" (bad) try pop(NULL): "<<pop<<endl;
}catch(int i){
cout <<" catch empty pop."<<endl;
}
pushTest(min,7,7); //7
popTest(min,7,2147483647); //
pushTest(min,100,100); //100
pushTest(min,7,7); //100,7
pushTest(min,-2,-2); //100,7,-2
pushTest(min,0,-2); //100,7,-2,0
popTest(min,0,-2); //100,7,-2
pushTest(min,-1000,-1000); //100,7,-2,-1000
popTest(min,-1000,-2); //100,7,-2
popTest(min,-2,7); //100,7
popTest(min,7,100); //100
popTest(min,100,2147483647); //
popTest(min,0,-2); //catch empty
pushTest(min,7,7); //100,7
pushTest(min,-2,-2); //100,7,-2
pushTest(min,0,-2); //100,7,-2,0
puts("\nemptying (hold breath)");
min->empty();
cout << "new size: "<<min->size()<<endl;
delete min;
getchar();
return 0;
}
|
#include <iostream>
using namespace std;
#include "../Headers/point.hh"
#include <cmath>
double computeArea(Point &p, Point &q, Point &r);
int main()
{
Point myPt1(2,3,8);
Point myPt2(3,4,5);
Point myPt3(4,5,6);
//cout<<myPt1.distanceTo(myPt2)<<endl;
cout<<computeArea(myPt1,myPt2,myPt3)<<endl;
//cout<<"Pt2: ("<<myPt2.getX()<<","<<myPt2.getY()<<","<<myPt2.getZ()<<")"<<endl;
//myPt1.setX(23);
//myPt2.setZ(34);
//cout<<"Pt1: ("<<myPt1.getX()<<","<<myPt1.getY()<<","<<myPt1.getZ()<<")"<<endl;
//cout<<"Pt2: ("<<myPt2.getX()<<","<<myPt2.getY()<<","<<myPt2.getZ()<<")"<<endl;
return 0;
}
double computeArea(Point &p, Point &q, Point &r) {
double a = 0;
double b = 0;
double c = 0;
double s = 0;
double res = 0;
a = p.distanceTo(q);
b = q.distanceTo(r);
c = r.distanceTo(p);
cout<<"a="<<a<<endl;
cout<<"b="<<b<<endl;
cout<<"c="<<c<<endl;
s = (a+b+c)/2;
cout<<"s="<<s<<endl;
if(s<a || s<b || s<c) {
cout<<"Not a triangle";
} else {
res = sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"res="<<res<<endl;
}
return res;
}
|
#include "gameboardsizedialog.h"
#include "ui_gameboardsizedialog.h"
#include "mainwindow.h"
GameBoardSizeDialog::GameBoardSizeDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::GameBoardSizeDialog)
{
ui->setupUi(this);
board_size = lowestBoardSize; //default
}
GameBoardSizeDialog::~GameBoardSizeDialog()
{
delete ui;
}
void GameBoardSizeDialog::on_c_boardsize_currentIndexChanged(int index)
{
board_size = index + lowestBoardSize; //shared.h
}
void GameBoardSizeDialog::on_b_ok_clicked()
{
this->done(QDialog::Accepted);
}
|
#include<iostream>
using namespace std;
const int maxn=/*行列式大小*/
const int mo=/*答案取余*/
int det[maxn][maxn],n,ans;
void make_det()
{
/*构造行列式*/
}
void cal_det()/*转化为阶梯阵求行列式*/
{
int i,j,k,t,swap;
ans=1;
for (i=0; i!=n; ++i)
for (j=0; j!=n; ++j) det[i][j]%=mo;
for (i=0; i!=n; ++i) { /*列*/
for (j=i+1; j!=n; ++j) /*行*/
while (det[j][i]!=0) { /*辗转减消元*/
t=det[i][i]/det[j][i];
ans=-ans; /*交换行后行列式值变负*/
for (k=i; k!=n; ++k) {
det[i][k]-=det[j][k]*t;
/*交换行*/
swap=det[i][k];
det[i][k]=det[j][k];
det[j][k]=swap;
}
}
if (det[i][i]==0) {
ans=0;
break;
} else ans=(ans*det[i][i])%mo;
}
cout << ans << endl;
}
int main()
{
make_det();
cal_det();
}
|
#ifndef PPM_H
#define PPM_H
//references from https://github.com/sol-prog/threads/blob/master/image_processing/ppm.cpp
#include <string>
#include <vector>
class PPM
{
public:
PPM();
//create a PPM object and fill it with data stored in source
PPM(const std::string & fileName);
//create an "empty" PPM image with a given width and height
PPM(const unsigned int width, const unsigned int height);
//free memory when object is destroyed
~PPM();
//read PPM image from filename
void read(const std::string & fileName);
//write PPM image to filename
void write(const std::string & fileName);
unsigned int getHeight() const;
unsigned int getWidth() const;
unsigned int getMaximumColumns() const;
unsigned int getSize() const;
std::vector< unsigned char > getRValue() const;
std::vector< unsigned char > getGValue() const;
std::vector< unsigned char > getBValue() const;
private:
bool isAllocated;
void initialize();
//information about PPM file(height and width)
unsigned int _lineNumber;
unsigned int _columnsNumber;
//arrays for storing R,G,B values
std::vector< unsigned char > _r;
std::vector< unsigned char > _g;
std::vector< unsigned char > _b;
unsigned int _height;
unsigned int _width;
unsigned int _maximumColumn;
//total number of elements(pixels)
unsigned int _size;
};
#endif
|
/*
* @author profgrammer
* @date 17-2-2019
*/
#include <bits/stdc++.h>
using namespace std;
class MyStack{
private:
int top;
int stack[100];
int size;
public:
MyStack(int _size){
top = -1;
size = _size;
}
bool isEmpty(){
return top == -1;
}
bool isFull(){
return top == size - 1;
}
int peek(){
if(isEmpty()) {cout<<"Stack empty..\n"; return -1;}
return stack[top];
}
void push(int x){
if(isFull()) cout<<"Stack full..\n";
else stack[++top] = x;
}
void pop(){
if(isEmpty()) cout<<"Stack empty..\n";
else top--;
}
};
int main(){
MyStack stack(2);
stack.push(1);
stack.push(2);
stack.push(3); // err
cout<<stack.peek()<<endl;
stack.pop();
stack.pop();
stack.pop(); // err
cout<<stack.peek()<<endl;
}
|
#ifndef VnaSweepSegment_H
#define VnaSweepSegment_H
// RsaToolbox
#include "Definitions.h"
// Etc
// Qt
#include <QObject>
#include <QScopedPointer>
namespace RsaToolbox {
class Vna;
class VnaChannel;
class VnaSegmentedSweep;
class VnaSweepSegment : public QObject
{
Q_OBJECT
public:
explicit VnaSweepSegment(QObject *parent = 0);
VnaSweepSegment(VnaSweepSegment &other);
VnaSweepSegment(Vna *vna, VnaChannel *channel, uint index, QObject *parent = 0);
VnaSweepSegment(Vna *vna, uint channelIndex, uint segmentIndex, QObject *parent = 0);
~VnaSweepSegment();
bool isOn();
bool isOff();
void on();
void off();
uint points();
void setPoints(uint numberOfPoints);
double start_Hz();
void setStart(double frequency, SiPrefix prefix = SiPrefix::None);
double stop_Hz();
void setStop(double frequency, SiPrefix prefix = SiPrefix::None);
void setSingleFrequency(double frequency, SiPrefix prefix = SiPrefix::None);
double power_dBm();
void setPower(double power_dBm);
void operator=(VnaSweepSegment const &other);
private:
Vna *_vna;
QScopedPointer<Vna> placeholder;
QScopedPointer<VnaChannel> _channel;
uint _channelIndex;
uint _segmentIndex;
bool isFullyInitialized() const;
};
}
#endif // VnaSweepSegment_H
|
#include <Arduino.h>
#include "a_car.h"
int g_count = 0;
int g_array[3];
int g_flag = 0;
float g_SF[3];
int value[3] = {0};
int choose;
int number;
void TSC_Init()
{
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(VCC, OUTPUT);
pinMode(GND, OUTPUT);
pinMode(LED, OUTPUT);
pinMode(OUT, INPUT);
pinMode(RGB, OUTPUT);
pinMode(Black,OUTPUT);
pinMode(R, OUTPUT);
pinMode(G, OUTPUT);
pinMode(B, OUTPUT);
pinMode(Speak, OUTPUT);
digitalWrite(RGB, LOW);
digitalWrite(R, LOW);
digitalWrite(G, LOW);
digitalWrite(B, LOW);
digitalWrite(Speak, HIGH);
digitalWrite(Black,HIGH);
digitalWrite(VCC, HIGH);
digitalWrite(GND, LOW);
digitalWrite(LED, LOW);
digitalWrite(S0, HIGH);
digitalWrite(S1, HIGH);
g_SF[0] = Balance_R;
g_SF[1] = Balance_G;
g_SF[2] = Balance_B;
}
void TSC_FilterColor(int Level01, int Level02)
{
if (Level01 != 0) // 如果Level01不等于0
Level01 = HIGH; //则Level01为高电平
if (Level02 != 0) // 如果Level02不等于0
Level02 = HIGH; //则Level02为高电平
digitalWrite(S2, Level01); // 将Level01值送给S2
digitalWrite(S3, Level02); // 将Level02值送给S3
}
void TSC_Count()
{
g_count ++ ;
}
void TSC_Callback()
{
switch (g_flag)
{
case 0:
Serial.println("->WB Start");// 串口打印字符串"->WB Start"
TSC_WB(LOW, LOW);// 选择让红色光线通过滤波器的模式
break;
case 1:
// Serial.print("->Frequency R="); // 串口打印字符串"->Frequency R="
//Serial.println(g_count);// 串口打印 0.5s 内的红光通过滤波器时,TCS3200 输出的脉冲个数
g_array[0] = g_count;//储存 0.5s 内的红光通过滤波器时,TCS3200 输出的脉冲个数
TSC_WB(HIGH, HIGH);// 选择让绿色光线通过滤波器的模式
break;
case 2:
//Serial.print("->Frequency G="); // 串口打印字符串"->Frequency G="
// Serial.println(g_count);// 串口打印 0.5s 内的绿光通过滤波器时,TCS3200 输出的脉冲个数
g_array[1] = g_count;//储存 0.5s 内的绿光通过滤波器时,TCS3200 输出的脉冲个数
TSC_WB(LOW, HIGH);//选择让蓝色光线通过滤波器的模式
break;
case 3:
//Serial.print("->Frequency B="); // 串口打印字符串"->Frequency B="
//Serial.println(g_count);// 串口打印 0.5s 内的蓝光通过滤波器时,TCS3200 输出的脉冲个数
//Serial.println("->WB End"); // 串口打印字符串"->WB End"
g_array[2] = g_count;//储存 0.5s 内的蓝光通过滤波器时,TCS3200 输出的脉冲个数
TSC_WB(HIGH, LOW); // 选择无滤波器模式
break;
default:
g_count = 0;//计数器清零
break;
}
}
void TSC_WB(int Level0, int Level1)
{
g_count = 0; //计数值清零
g_flag ++; //输出信号计数标志
TSC_FilterColor(Level0, Level1);//滤波器模式
Timer1.setPeriod(500000); //设置输出信号脉冲计数时长为 0.5s
}
int color_value()
{
//初始化
Timer1.initialize(500000);
Timer1.attachInterrupt(TSC_Callback);
attachInterrupt(0, TSC_Count, RISING);//上升沿计数
Timer1.detachInterrupt();
//每获得一次被测物体RGB颜色值需时2s
delay(2000);
g_flag = 0;
for (int i = 0; i < 3; i++)
{
value[i] = int(g_array[i] * g_SF[i]);
Serial.println(int(g_array[i] * g_SF[i]));
}
if (value[0] + value[1] + value[2] > 1400)
{
//白色
digitalWrite(R, HIGH);
digitalWrite(G, HIGH);
digitalWrite(B, HIGH);
delay(100);
digitalWrite(R, LOW);
digitalWrite(G, LOW);
digitalWrite(B, LOW);
return 2;
}
else
{
choose = 0;
for (int i = 0; i < 3; i++)
{
if (value[i] > choose)
{
choose = value[i];
number = i;
}
}
for (int i = 0; i < 3; i++)
{
if (i != number)
{
choose = choose - value[i];
}
else
{
choose = choose + value[i];
}
}
if (choose < 30)
{
//黑色
digitalWrite(Speak, LOW);
delay(50);
digitalWrite(Speak, HIGH);
return 4;
}
else if (choose > 30)
{
if ((number == 0) && (value[0] + value[1] + value[2] - 3 * 255 > 90))
{
//红色
digitalWrite(R, HIGH);
digitalWrite(G, LOW);
digitalWrite(B, LOW);
delay(100);
digitalWrite(R, LOW);
digitalWrite(G, LOW);
digitalWrite(B, LOW);
return 3;
}
else if ((number == 1) && (value[0] + value[1] + value[2] - 3 * 255 > 50))
{
//绿色
digitalWrite(R, LOW);
digitalWrite(G, HIGH);
digitalWrite(B, LOW);
delay(100);
digitalWrite(R, LOW);
digitalWrite(G, LOW);
digitalWrite(B, LOW);
return 1;
}
else if ((number == 2) && (value[0] + value[1] + value[2] - 3 * 255 > 60))
{
//蓝色
digitalWrite(R, LOW);
digitalWrite(G, LOW);
digitalWrite(B, HIGH);
delay(100);
digitalWrite(R, LOW);
digitalWrite(G, LOW);
digitalWrite(B, LOW);
return 5;
}
else
{
//黑色
digitalWrite(Speak, LOW);
delay(50);
digitalWrite(Speak, HIGH);
return 4;
}
}
else
{
//黑色
digitalWrite(Speak, LOW);
delay(50);
digitalWrite(Speak, HIGH);
return 4;
}
}
}
|
#ifndef ELEVATOR_CC
#define ELEVATOR_CC
#include "elevator.h"
elevator::elevator()
{
elev_lock = new Lock("elevLock");
userLimit = new Semaphore("userL_sem", 20);
}
elevator::~elevator()
{
delete elev_lock;
delete userLimit;
}
void elevator::GoingFromTo(int from, int to)
{
elev_lock->Acquire();
fromFloor[from].Wait(elev_lock);
elev_lock->Release();
userLimit->P();
elev_lock->Acquire();
toFloor[to].Wait(elev_lock);
elev_lock->Release();
userLimit->V();
}
void elevator::stop(int cur_floor)
{
elev_lock->Acquire();
toFloor[cur_floor].Broadcast(elev_lock);
fromFloor[cur_floor].Broadcast(elev_lock);
elev_lock->Release();
}
void elevator::main()
{
while(true)
{
for (int cur_floor = 0; cur_floor < 5; cur_floor++)
{
stop(cur_floor);
}
for (int cur_floor = 5; cur_floor > 0; cur_floor--)
{
stop(cur_floor);
}
}
}
#endif
|
#define MAINPREFIX z
#define PREFIX TF47
#include "script_version.hpp"
#define VERSION MAJOR.MINOR.PATCH.BUILD
#define VERSION_AR MAJOR,MINOR,PATCH,BUILD
#define REQUIRED_VERSION 2.02
|
#ifndef _CCHECK_USERNAME_h_
#define _CCHECK_USERNAME_h_
#include <string>
#include "CHttpRequestHandler.h"
class CCheckUserName : public CHttpRequestHandler
{
public:
CCheckUserName(){}
~CCheckUserName(){}
virtual int do_request(const Json::Value& root, char *client_ip, HttpResult& out);
private:
bool hasUsername(std::string &username);
};
#endif //end for _CCHECK_USERNAME_h_
|
#include <bits/stdc++.h>
using namespace std;
void solve () {
int n;
cin >> n;
map<string, int> db;
map<string, int>::iterator it;
while (n--) {
string user;
cin >> user;
it = db.find(user);
if (it == db.end()) {
db[user] = 0;
cout << "OK\n";
} else {
db[user] = ++db[user];
cout << user << db[user] << "\n";
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
solve();
return 0;
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#include "LinearGroup.h"
#include "util/Exceptions.h"
#include "geometry/Ring.h"
#include "geometry/AffineMatrix.h"
#include "model/static/Box.h"
#include "model/static/Circle.h"
#include "LinearGroupProperties.h"
namespace Model {
using namespace boost::geometry;
namespace G = Geometry;
namespace trans = boost::geometry::strategy::transform;
/****************************************************************************/
void LinearGroup::update (Event::UpdateEvent *e, Util::UpdateContext *uCtx)
{
// TODO to nie powino się updejtować przy każdym odświerzeniu.
updateLayout ();
Group::update (e, uCtx);
}
/****************************************************************************/
void LinearGroup::updateLayout ()
{
float childW = 0, childH = 0;
getChildrenDimensions (&childW, &childH);
// Szerokość i wysokość samej grupy jest tu korygowana na podstawie GroupProperies tej grupy.
adjustMyDimensions (childW, childH);
float actualX = 0;
float actualY = 0;
// Odległość między środkami obiektów jesli mamy gravity na CENTER.
float equalSpace = 0;
if (type == HORIZONTAL) {
if (hGravity == HG_LEFT) {
actualX = margin;
}
else if (hGravity == HG_RIGHT) {
actualX = w - childW - margin;
}
else if (hGravity == HG_CENTER) {
actualX = margin;
if (children.size () > 1) {
IModel *first = children.front ();
IModel *last = children.back ();
float firstW = first->getBoundingBox ().getWidth ();
float lastW = last->getBoundingBox ().getWidth ();
equalSpace = (w - 2 * margin - firstW / 2 - lastW / 2) / (children.size () - 1);
}
}
}
else {
if (vGravity == VG_BOTTOM) {
actualY = margin;
}
else if (vGravity == VG_TOP) {
actualY = h - childH - margin;
}
else if (vGravity == VG_CENTER) {
actualY = margin;
if (children.size () > 1) {
IModel *first = children.front ();
IModel *last = children.back ();
float firstH = first->getBoundingBox ().getHeight ();
float lastH = last->getBoundingBox ().getHeight ();
equalSpace = (h - 2 * margin - firstH / 2 - lastH / 2) / (children.size () - 1);
}
}
}
if (type == HORIZONTAL) {
for (ModelVector::iterator i = children.begin (); i != children.end (); ++i) {
IModel *child = *i;
LinearGroupProperties const *props = ((child->getGroupProps ()) ? (dynamic_cast <LinearGroupProperties const *> (child->getGroupProps ())) : (NULL));
G::Box aabb = child->getBoundingBox ();
float aabbW = aabb.getWidth ();
float aabbH = aabb.getHeight ();
G::Point t = child->getTranslate ();
t.x = actualX;
if (props) {
if (props->vAlign == VA_BOTTOM) {
t.y = margin;
}
else if (props->vAlign == VA_TOP) {
t.y = h - aabbH - margin;
}
else if (props->vAlign == VA_CENTER) {
t.y = (h - aabbH) / 2;
}
}
else {
t.y = (h - aabbH) / 2;
}
if (hGravity == HG_LEFT || hGravity == HG_RIGHT) {
actualX += aabbW + spacing;
}
else if (hGravity == HG_CENTER) {
if (i + 1 != children.end ()) {
IModel *nextChild = *(i + 1);
actualX += equalSpace + (aabbW / 2) - (nextChild->getBoundingBox ().getWidth () / 2);
}
}
child->setTranslate (t);
}
}
// VERTICAL
else {
for (ModelVector::reverse_iterator i = children.rbegin (); i != children.rend (); ++i) {
IModel *child = *i;
LinearGroupProperties const *props = ((child->getGroupProps ()) ? (dynamic_cast <LinearGroupProperties const *> (child->getGroupProps ())) : (NULL));
G::Box aabb = child->getBoundingBox ();
float aabbW = aabb.getWidth ();
float aabbH = aabb.getHeight ();
G::Point t = child->getTranslate ();
t.y = actualY;
if (props) {
if (props->hAlign == HA_LEFT) {
t.x = margin;
}
else if (props->hAlign == HA_RIGHT) {
t.x = w - aabbW - margin;
}
else if (props->hAlign == HA_CENTER) {
t.x = (w - aabbW) / 2;
}
}
else {
t.x = (w - aabbW) / 2;
}
if (vGravity == VG_BOTTOM || vGravity == VG_TOP) {
actualY += aabbH + spacing;
}
else if (vGravity == VG_CENTER) {
if (i + 1 != children.rend ()) {
IModel *nextChild = *(i + 1);
actualY += equalSpace + (aabbH / 2) - (nextChild->getBoundingBox ().getHeight () / 2);
}
}
child->setTranslate (t);
}
}
}
/****************************************************************************/
void LinearGroup::getChildrenDimensions (float *w, float *h)
{
G::Box aabb;
float width = 0;
float height = 0;
for (ModelVector::const_iterator i = children.begin (); i != children.end (); ++i) {
aabb = (*i)->getBoundingBox ();
if (type == HORIZONTAL) {
width += aabb.getWidth ();
height = std::max (height, aabb.getHeight ());
}
else {
width = std::max (width, aabb.getWidth ());
height += aabb.getHeight ();
}
}
*w = width;
if (type == HORIZONTAL) {
*w += spacing * (children.size () - 1);
}
*h = height;
if (type == VERTICAL) {
*h += spacing * (children.size () - 1);
}
}
/****************************************************************************/
void LinearGroup::adjustMyDimensions (float w, float h)
{
if (getWrapContentsW ()) {
this->w = w + 2 * margin;
}
if (getWrapContentsH ()) {
this->h = h + 2 * margin;
}
}
/****************************************************************************/
bool LinearGroup::contains (G::Point const &p) const
{
G::Ring ring;
G::Ring output;
convert (getBox (), ring);
G::AffineMatrixTransformer matrix (getMatrix ());
transform (ring, output, matrix);
// for (G::Ring::const_iterator i = output.begin (); i != output.end (); ++i) {
// G::Point const &p = *i;
// std::cerr << p << ",";
// }
// std::cerr << " p=" << p << ", " << within (p, output) << std::endl;
return within (p, output);
}
/****************************************************************************/
G::Box LinearGroup::getBoundingBoxImpl (Geometry::AffineMatrix const &transformation) const
{
// TODO to nie powino się updejtować przy każdym odświerzeniu.
// TODO To super działa, ale wydajnościowo to jest zabójstwo - trzeba pomyśleć 1) z tymi hashami 2) z keszowaniem bounding boxów (też zależne od hashy).
// TODO co z tym const_cast?
const_cast <LinearGroup *> (this)->updateLayout ();
G::Box aabb;
G::Ring ring;
G::Ring output;
convert (getBox (), ring);
G::AffineMatrixTransformer matrix (transformation);
transform (ring, output, matrix);
envelope (output, aabb);
return aabb;
}
/****************************************************************************/
IModel *LinearGroup::findContains (G::Point const &p)
{
// - Punkt p jest we współrzędnych rodzica.
// A.
// - Weź mój aabb we wsp. rodzica, czyli równoległy do osi układu rodzica.
// -- Przetransformuj ll i ur
// --- Stwórz macierz.
// --- Przemnóż ll i ur przez tą macierz.
// -- Znajdz aabb (max i min x + max i min.y).
Geometry::Box aabb = getBoundingBox ();
// - Sprawdź, czy p jest w aabb
// -- Jeśli nie, zwróć NULL.
if (!aabb.contains (p)) {
return NULL;
}
// -- Jeśli tak, to sprawdź dokładnie, za pomocą inside
if (!this->contains (p)) {
return NULL;
}
// --- Jeśli nie ma dzieci zwróć this.
if (children.empty ()) {
return this;
}
// --- Jeśli są dzieci, to przetransformuj p przez moją macierz i puść w pętli do dzieci.
G::Point copy = p;
// TODO od razu można zwracać odwróconą.
getMatrix ().getInversed ().transform (©);
IModel *ret;
for (ModelVector::reverse_iterator i = children.rbegin (); i != children.rend (); ++i) {
if ((ret = (*i)->findContains (copy))) {
return ret;
}
}
return this;
}
/*--------------------------------------------------------------------------*/
Core::Variant stringToLinearGroupType (std::string const &p)
{
if (p == "horizontal") {
return Core::Variant (static_cast <unsigned int> (LinearGroup::HORIZONTAL));
}
else if (p == "vertical") {
return Core::Variant (static_cast <unsigned int> (LinearGroup::VERTICAL));
}
throw Util::InitException ("stringToLinearGroupType () : worng string literal for LinearGroup::Type : [" + p + "]");
}
} /* namespace Model */
|
//
// Created by kanae on 2019-09-10.
//
#ifndef CMPRO_LEARNING_METHOD_H
#define CMPRO_LEARNING_METHOD_H
#include <dlib/opencv.h>
#include <opencv2/opencv.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/platform/env.h"
#include "configure.h"
#include "shape_processing.h"
#include "deep_process.h"
class LearningMethod {
public:
void loop_process();
bool is_loop_continue;
LearningMethod();
private:
Configure conf;
dlib::frontal_face_detector detector;
dlib::shape_predictor pose_model;
cv::Mat showing_image;
int state;
//position and size of the selected area
long rfleft, rftop, area_width, area_height;
double score;
clock_t clock_weight ;
clock_t clock_time ;
//各种状态的显示消息
const std::vector<std::string> ctmsg = {"未匹配","重度3","中度2","轻度1","正常0","状态异常"};
const std::vector<std::string> show_msg = {" No-Matching","degree-3","degree-2 ","degree-1","degree-0","Alarming"};
};
#endif //CMPRO_LEARNING_METHOD_H
|
// LED Array Testing Code
// Light Integrated Threads
//
//
#include <FFT.h>
#include <SPI.h>
#include <LPD8806.h>
//#include <LEDArray.h>
#include <Grid.h>
Grid myGrid(18,18);
int maxVal = 0;
int maxIndex = 0;
int weights[7] = {5,4,3,3,3,3,2};
int weightedSpectrum[7] = {0,0,0,0,0,0,0};
int *spectrum;
//int color[3];
//FFT fft(fftAnalogPin,fftStrobePin,fftResetPin);
void setup()
{
Serial.begin(9600);
myGrid.strip->begin();
myGrid.update();
delay(2000);
}
void loop()
{
myGrid.allOff();
spectrum = myGrid.freqChip->sample();
Serial.println(spectrum[3]);
/*
for(int i = 0; i < 7; i++)
{
Serial.println(spectrum[i]);
}
Serial.println();
Serial.println();
*/
for(int i = 0; i < 7; i++)
{
int temp1 = spectrum[i];
int temp2 = weights[i];
int temp3 = temp1*temp2;
int a=2;
int b=3;
weightedSpectrum[i] = a*b;
//int poop = temp1*temp2;
//Serial.println(weightedSpectrum[i]);
Serial.print(spectrum[i]);
Serial.print(" ");
Serial.print(weights[i]);
Serial.print(" ");
//Serial.print(weightedSpectrum[i]);
Serial.println();
/*
Serial.print("In band ");
Serial.print(i);
Serial.print(", ");
Serial.print(" spectrum is: ");
Serial.print(spectrum[i]);
Serial.print(" weighted spectrum is: ");
Serial.print(weightedSpectrum[i]);
Serial.println();
//*/
}
Serial.println();
Serial.println();
/*
for(int i = 0; i < 7; i++)
{
weightedSpectrum[i] = spectrum[i]*weights[i];
if(weightedSpectrum[i] > maxVal)
{
maxVal = weightedSpectrum[i];
maxIndex = i+1;
}
Serial.print(i);
Serial.print(" ");
Serial.print(spectrum[i]);
Serial.print(" ");
Serial.print(weightedSpectrum[i]);
Serial.print(" ");
Serial.print(maxVal);
Serial.print(" ");
Serial.println(maxIndex);
}
*/
switch (maxIndex)
{
case 1:
myGrid.allOff();
myGrid.oFace(blue);
myGrid.update();
delay(500);
break;
case 2:
myGrid.allOff();
myGrid.oFace(magenta);
myGrid.update();
delay(500);
break;
case 3:
myGrid.allOff();
myGrid.smiley1(cyan);
myGrid.rightEyeOpen(cyan);
myGrid.leftEyeOpen(cyan);
myGrid.update();
delay(300);
break;
case 4:
myGrid.allOff();
myGrid.smiley1(red);
myGrid.rightEyeOpen(red);
myGrid.leftEyeOpen(red);
myGrid.update();
delay(300);
break;
case 5:
myGrid.allOff();
myGrid.smiley1(green);
myGrid.rightWink(green);
myGrid.leftEyeOpen(green);
myGrid.update();
delay(200);
break;
case 6:
myGrid.allOff();
myGrid.smiley1(yellow);
myGrid.leftWink(yellow);
myGrid.rightEyeOpen(yellow);
myGrid.update();
// delay(200);
break;
case 7:
myGrid.allOff();
myGrid.smiley1(white);
myGrid.leftWink(white);
myGrid.rightWink(white);
myGrid.update();
delay(100);
break;
}
maxIndex = 0;
maxVal = 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef ISO_8859_1_ENCODER_H
#define ISO_8859_1_ENCODER_H
#include "modules/encodings/encoders/outputconverter.h"
class UTF16toISOLatin1Converter : public OutputConverter
{
public:
/** @param asciionly Set to TRUE to only allow US-ASCII output
@param is_x_user_defined Report encoding as "x-user-defined" */
UTF16toISOLatin1Converter(BOOL asciionly = FALSE, BOOL is_x_user_defined = FALSE)
: m_is_x_user_defined(is_x_user_defined)
{ m_high = asciionly ? 128 : 256; }
virtual int Convert(const void *src, int len, void *dest, int maxlen,
int *read);
virtual const char *GetDestinationCharacterSet();
virtual int ReturnToInitialState(void *) { return 0; };
virtual int LongestSelfContainedSequenceForCharacter() { return 1; };
protected:
uni_char m_high; ///< Upper boundary for identity conversion
BOOL m_is_x_user_defined; ///< TRUE if used for "x-user-defined" output
virtual char lookup(uni_char utf16);
};
#endif // ISO_8859_1_ENCODER_H
|
/*
* Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file src/main.cpp
* @author Aleksander Zdyb <a.zdyb@samsung.com>
* @version 1.0
*/
#include <csignal>
#include <cstdlib>
#include <memory>
#include <Audit/Auditctl.h>
#include <Audit/AuditWrapper.h>
#include <Audit/AuparseSourceFeedWrapper.h>
#include <Audit/ErrorException.h>
#include <Audit/Parser.h>
#include <Lad/AuditEventHandler.h>
#include <Lad/AuditRulesPopulator.h>
#include <Lad/Options.h>
#include <Log/log.h>
#include <Utils/Feed.h>
#include <Utils/SignalFd.h>
#include <Utils/WithMessageException.h>
int main(int argc, char **argv) {
using std::placeholders::_1;
using std::placeholders::_2;
init_log();
LOGI("Starting nice-lad");
try {
Audit::AuditWrapper auditApi;
Audit::AuparseSourceFeedWrapper auparseApi;
Audit::Parser auParser(auparseApi);
Audit::Auditctl auditctl(auditApi);
auto &dataProvider = Lad::Options::dataProvider();
auto &dataCollector = Lad::Options::dataCollector();
Lad::AuditRulesPopulator rulesPopulator(auditctl, dataProvider);
int sigFd = Utils::SignalFd::createSignalFd({ SIGHUP, SIGTERM });
Utils::Feed feed(STDIN_FILENO, auditApi.MAX_AUDIT_MESSAGE_LENGTH_CONST(), sigFd);
feed.onData.connect(std::bind(&Audit::Parser::feed, &auParser, _1, _2));
feed.onTimeout.connect(std::bind(&Audit::Parser::flush, &auParser));
feed.onEod.connect([&auParser] (void) {
auParser.flush();
LOGI("End of data. Terminating.");
});
feed.onSignal.connect([&feed] (int sigFd) {
const auto sigNo = Utils::SignalFd::readSignalNo(sigFd);
if (sigNo == SIGTERM) {
LOGI("Got SIGTERM (Terminating)");
feed.stop();
} else if (sigNo == SIGHUP) {
LOGI("Got SIGHUP (Reloading configuration)");
} else {
LOGW("Unexpected signal (" << sigNo << ")");
}
});
Lad::AuditEventHandler eventHandler;
auParser.onEvent.connect(std::bind(&Lad::AuditEventHandler::handleEvent, &eventHandler, _1));
eventHandler.onLogDenial.connect(std::bind(&Lad::DataCollector::log, &dataCollector, _1));
LOGD("nice-lad up and ready");
feed.start();
} catch (const std::exception &ex) {
LOGC(ex.what() << " (Terminating)");
return EXIT_FAILURE;
} catch (...) {
LOGC("Unknown error (Terminating)");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
|
#include "tcp_client.h"
#include "ftp_client.h"
#include "cJSON.h"
#include "proto.h"
SOCKET sclient;
int tcp_client_init()
{
WORD socketVersion = MAKEWORD(2,2);
WSADATA wsaData;
if(WSAStartup(socketVersion, &wsaData) != 0)
{
return 0;
}
sockaddr_in serAddr;
serAddr.sin_family = AF_INET;
serAddr.sin_port = htons(4646);
inet_pton(AF_INET, "192.168.100.1", &serAddr.sin_addr);
// serAddr.sin_addr.s_addr=inet_addr("192.168.100.1");
cout<<"等待无线连接...."<<endl;
sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sclient == INVALID_SOCKET){
printf("invalid socket!");
return 0;
}
if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
{ //连接失败
printf("无线未连接 !\n");
closesocket(sclient);
return 0;
}
cout<<"无线连接成功"<<endl;
ftp_init();
return 0;
}
int tcp_send(int cmd,int val)
{
char *out=NULL;
int ret;
cJSON *root = NULL;
cJSON *param=NULL;
cJSON *item = NULL;
cJSON *found = NULL;
cJSON *vel=NULL;
switch(cmd)
{
case CMD_IMG_LOAD:
root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, "CMD", CMD_IMG_LOAD);
cJSON_AddItemToObject(root, "PARAM", param = cJSON_CreateObject());
cJSON_AddNumberToObject(param,"num",1);
cJSON_AddNumberToObject(param,"delay",0);
out = cJSON_Print(root);
//char *p="{\"CMD\":87,\"PARAM\":{\"num\":1,\"delay\":0}}";
// printf("out:%s\n",out);
cJSON_Delete(root);
break;
case CMD_SAFE_MODE:
root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, "CMD", CMD_SAFE_MODE);
cJSON_AddNumberToObject(root, "PARAM", 1);
out = cJSON_Print(root);
cJSON_Delete(root);
break;
case CMD_TAKEOFF_ALT:
root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, "CMD", CMD_TAKEOFF_ALT);
cJSON_AddNumberToObject(root, "PARAM", val);
out = cJSON_Print(root);
cJSON_Delete(root);
break;
default:
cout<<"命令错误"<<endl;
}
ret=send(sclient, out, strlen(out), 0);
if(ret < 0){
cout<<"命令发送失败"<<endl;
return -1;
}
char recData[255];
ret = recv(sclient, recData, 255, 0);
if (ret > 0) {
recData[ret] = 0x00;
switch(cmd)
{
case CMD_IMG_LOAD:
item =cJSON_Parse(recData);
found=cJSON_GetObjectItem(item, "PARAM");
vel=cJSON_GetObjectItem(found,"photo");
ftp_main(vel->valuestring);
cJSON_Delete(item);
break;
}
}
cout<<"设置完成"<<endl;
return 0;
}
void tcp_quit()
{
closesocket(sclient);
ftp_quit();
WSACleanup();
}
|
//
// Created by root on 25/05/19.
//
#include "Player.h"
Player::Player(sf::Texture* tx, sf::Vector2u imageCount,float switchTime, float speed,float jumpheight):
playerAnimation(tx,imageCount,switchTime),
body(sf::Vector2f(128.0f,80.0f))
{
this->speed = speed;
row=0;
faceRight=true;
this->jumpheight=jumpheight;
//criando um shape de retangulo chamado player, que tera tamanho contido no vector2f que são 128 por 80
body.setOrigin(body.getSize().x / 2,body.getSize().y/2);
body.setPosition(50.0f,50.0f);
//muda a origem do objeto, nesse caso seria o centro dele
body.setTexture(tx);
}
Player::~Player() {
}
void Player::Update(float deltaTime) {
velocity.x *= 0.5f;
if(sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
velocity.x -= speed ;
}
if(sf::Keyboard::isKeyPressed(sf::Keyboard::D)){
velocity.x += speed ;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && canjump){
canjump= false;
velocity.y = -sqrtf(2.0f * (981.0f) * jumpheight);
//sqrt (2.0f * g * jumpheight) 1 metro equivale a 1000px
//o sinal de negativo é para que o objeto possa subir
}
velocity.y += 981.0f *deltaTime;
//velocity contara quanto o objeto deverá se mover
if(velocity.x==0.0f){
row=0; //para ativar a animação de idle
}else{
row =1; //por que será a animação de movimento
if(velocity.x > 0.0f){
faceRight=true; //verifica se o movimento é positivo ou negativo
}else{
faceRight=false;
}
}
playerAnimation.update(row,deltaTime,faceRight);
body.setTextureRect(playerAnimation.uvRect);
body.move(velocity* deltaTime);
}
void Player::Draw(sf::RenderWindow& window) {
window.draw(body);
}
void Player::onCollision(sf::Vector2f direction) {
//a função irá verificar se esta acontecendo uma colisão em alguma das direções, a ideia é fazer o objeto parar quando ocorrer uma colisão
if(direction.x<0.0f){//left
velocity.x=0.0f;
}else if (direction.x<0.0f){ //right
velocity.x=0.0f;
}
if(direction.y > 0.0f){ //colisão encima
velocity.y=0.0f;
}else if (direction.y<0.0f){
canjump=true;
velocity.y=0.0f;
}
}
|
#pragma once
#include <json/Writer.h>
#include <map>
#include "credb/IsolationLevel.h"
#include "credb/Witness.h"
#include "LockHandle.h"
namespace credb
{
namespace trusted
{
struct operation_info_t;
class Ledger;
class OpContext;
/**
* Server-side logic for transaction processing
*/
class Transaction
{
private:
IsolationLevel m_isolation;
/**
* Keep a list of all locks that need to be acquired
* @note this needs to be ordered so we don't deadlock
*/
std::map<shard_id_t, LockType> m_shard_lock_types;
public:
IsolationLevel isolation_level() const
{
return m_isolation;
}
Ledger &ledger;
const OpContext &op_context;
bool generate_witness;
LockHandle lock_handle;
std::string error;
Transaction(IsolationLevel isolation, Ledger &ledger_, const OpContext &op_context_, LockHandle *lock_handle_);
Transaction(bitstream &request, Ledger &ledger_, const OpContext &op_context_);
~Transaction();
/**
* @brief Performs main transaction logic (verification of reads + application of writes)
*
* Returns a witness on success (witness may be empty if generate witness is set to false
* Throws an exception if commit fails
*/
Witness commit();
bool phase_one();
Witness phase_two();
void get_output(bitstream &output);
/**
* Sets a read lock for a shard to read if no lock for it has been set yet
*/
void set_read_lock(shard_id_t sid);
/**
* Sets a write lock for a shard
*/
void set_write_lock(shard_id_t sid);
bool check_repeatable_read(ObjectEventHandle &obj,
const std::string &collection,
const std::string &full_path,
shard_id_t sid,
const event_id_t &eid);
/**
* Add a new operation that is associated with this transaction
*
* @param op
* The operation structure. Memory will be managed by the transaction object from here on
*/
void register_operation(operation_info_t *op);
json::Writer writer;
/**
* Discard transaction and release all locks
*/
void clear();
private:
operation_info_t* new_operation_info_from_req(bitstream &req);
std::vector<operation_info_t*> m_ops;
};
}
}
|
/**
* @brief strinlistgmodel.cpp
* This is the source file which contains the definitions of the functions of the StringListModel class.
*/
#include "stringlistmodel.h"
/**
* @brief StringListModel
* This is the constructor for the StringListModel class
* @return
* none
*/
StringListModel::StringListModel()
{
m_cpuInfoList = new QStringListModel;
}
/**
* @brief getListModel
* This is the get function which reads the property value
* @return
* QStringListModel* : pointer the QStringListModel which acts as the value of property
*/
QStringListModel* StringListModel::getListModel()const
{
return m_cpuInfoList;
}
/**
* @brief fetchCPUInfo
* This is a utility function which reads the "/proc/cpuinfo" file line by line, formats it and stores the contents in the return list
* @param
* fileName: file name to be read to create the resultant list
* @return
* QStringList: list of CPU Info file entries
*/
bool StringListModel::fetchCPUInfoList(QString fileName)
{
bool l_status = true;
QStringList l_listCPUInfo;
QFile l_procCPUInfo(fileName); //file handle for cpuinfo file
if(l_procCPUInfo.open(QIODevice::ReadOnly))
{
QTextStream l_dataStream(&l_procCPUInfo);
QString l_line;
do
{
/*This loop reads each line from cpuinfo file ata a time.
format it by separating it as property of the CPU vs it's value.
Once formatted, it stores it in the listCPUInfo*/
l_line = l_dataStream.readLine(); //read line
QStringList l_lineSplitData = l_line.split(":"); //split each line based on ":" into proerty vs value
QString l_property,l_value;
if(l_lineSplitData.length() == 2)
{
l_property = l_lineSplitData[0].trimmed();
l_value = l_lineSplitData[1].trimmed();
}
else if(l_lineSplitData.length() == 1)
{
l_property = l_lineSplitData[0].trimmed();
l_value = "";
}
if(!l_property.isEmpty())
{
l_property.append(QString("").fill(' ',MAXWIDTH-l_property.length())); //fill the trailing empty spaces for better view
l_listCPUInfo << l_property+"\t"+":"+"\t"+l_value; //Format the display string and insert it in the return list
}
}while(!l_line.isNull());
l_procCPUInfo.close();
}
else
{
l_status = false;
l_listCPUInfo<<"ERROR IN OPENING FILE: " << l_procCPUInfo.errorString();
}
m_cpuInfoList->setStringList(l_listCPUInfo);
return l_status;
}
|
#include<stdio.h>
#define grindsize 8
#define pathsize
int change=0,time=2,b,chess[grindsize][grindsize]={0},a[8][2]={
{2,1},
{2,-1},
{1,2},
{1,-2},
{-1,2},
{-1,-2},
{-2,1},
{-2,-1},
};
int walk=0,i=0,j=0,x0=0,y0=0;
void dfs(int time,int change,int x0,int y0){
int r=0;
for(r=0;r<grindsize;r++){
int x=0,y=0,y2=0,x2=0,change=0;
change=0;
x2=x0+a[r][0];
y2=y0+a[r][1];
if(x2<grindsize&&y2<grindsize&&x2>=0&&y2>=0&&change==0){
if(chess[x2][y2]==0){
change=1;
chess[x2][y2]=time;
time++;
x0=x2;
y0=y2;
r=0;
b=time;
}
}
}
//printf("%d",time);
}
int main(void){
printf("start point\n",x0,y0);
scanf("%d%d",&x0,&y0);
chess[x0][y0]=1;
while(1){
dfs(time,change,x0,y0);
if(change==0){
while(j<grindsize){
for(i=0;i<8;i++){
for(j=0;j<8;j++){
printf("%d\t",chess[i][j]);
}
printf("\n");
}
printf("totally move %d time\n",b);
break;
}
}
}
}
|
void setup() {
pinMode(3, OUTPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void Leader(){
digitalWrite(13, HIGH);
digitalWrite(3, HIGH);
delay(9);
digitalWrite(3, LOW);
delayMicroseconds(4500);
}
void One() {
digitalWrite(3, HIGH);
delayMicroseconds(562);
digitalWrite(3, LOW);
delayMicroseconds(1687);
}
void Zero() {
digitalWrite(3, HIGH);
delayMicroseconds(562);
digitalWrite(3, LOW);
delayMicroseconds(562);
}
void Stop() {
digitalWrite(3, HIGH);
delayMicroseconds(562);
digitalWrite(3, LOW);
digitalWrite(13, LOW);
}
void SendAddress() {
Zero();
Zero();
Zero();
Zero();
Zero();
Zero();
Zero();
Zero();
One();
One();
One();
One();
One();
One();
One();
One();
}
void SetInput1() {
Leader();
SendAddress();
Zero();
Zero();
One();
Zero();
Zero();
Zero();
Zero();
Zero();
One();
One();
Zero();
One();
One();
One();
One();
One();
Stop();
}
void SetInput2() {
Leader();
SendAddress();
Zero();
Zero();
Zero();
One();
Zero();
Zero();
Zero();
Zero();
One();
One();
One();
Zero();
One();
One();
One();
One();
Stop();
}
void SetInput3() {
Leader();
SendAddress();
Zero();
One();
Zero();
One();
Zero();
Zero();
Zero();
Zero();
One();
Zero();
One();
Zero();
One();
One();
One();
One();
Stop();
}
void loop() {
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
if (inChar == '1')
SetInput1();
else if (inChar == '2')
SetInput2();
else if (inChar == '3')
SetInput3();
Serial.print(inChar);
}
}
|
// Created on: 2013-01-28
// Created by: Kirill GAVRILOV
// Copyright (c) 2013-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 Font_FTFont_HeaderFile
#define Font_FTFont_HeaderFile
#include <Font_FontAspect.hxx>
#include <Font_Hinting.hxx>
#include <Font_Rect.hxx>
#include <Font_StrictLevel.hxx>
#include <Font_UnicodeSubset.hxx>
#include <Graphic3d_HorizontalTextAlignment.hxx>
#include <Graphic3d_VerticalTextAlignment.hxx>
#include <Image_PixMap.hxx>
#include <NCollection_String.hxx>
#include <TCollection_AsciiString.hxx>
// forward declarations to avoid including of FreeType headers
typedef struct FT_FaceRec_* FT_Face;
typedef struct FT_Vector_ FT_Vector;
typedef struct FT_Outline_ FT_Outline;
class Font_FTLibrary;
//! Font initialization parameters.
struct Font_FTFontParams
{
unsigned int PointSize; //!< face size in points (1/72 inch)
unsigned int Resolution; //!< resolution of the target device in dpi for FT_Set_Char_Size()
Font_Hinting FontHinting; //!< request hinting (exclude FT_LOAD_NO_HINTING flag), Font_Hinting_Off by default;
//! hinting improves readability of thin text on low-resolution screen,
//! but adds distortions to original font depending on font family and font library version
bool ToSynthesizeItalic; //!< generate italic style (e.g. for font family having no italic style); FALSE by default
bool IsSingleStrokeFont; //!< single-stroke (one-line) font, FALSE by default
//! Empty constructor.
Font_FTFontParams()
: PointSize (0), Resolution (72u),
FontHinting (Font_Hinting_Off),
ToSynthesizeItalic (false),
IsSingleStrokeFont (false) {}
//! Constructor.
Font_FTFontParams (unsigned int thePointSize,
unsigned int theResolution)
: PointSize (thePointSize), Resolution (theResolution),
FontHinting (Font_Hinting_Off),
ToSynthesizeItalic (false),
IsSingleStrokeFont (false) {}
};
DEFINE_STANDARD_HANDLE(Font_FTFont, Standard_Transient)
//! Wrapper over FreeType font.
//! Notice that this class uses internal buffers for loaded glyphs
//! and it is absolutely UNSAFE to load/read glyph from concurrent threads!
class Font_FTFont : public Standard_Transient
{
DEFINE_STANDARD_RTTIEXT(Font_FTFont, Standard_Transient)
public:
//! Find the font Initialize the font.
//! @param theFontName the font name
//! @param theFontAspect the font style
//! @param theParams initialization parameters
//! @param theStrictLevel search strict level for using aliases and fallback
//! @return true on success
Standard_EXPORT static Handle(Font_FTFont) FindAndCreate (const TCollection_AsciiString& theFontName,
const Font_FontAspect theFontAspect,
const Font_FTFontParams& theParams,
const Font_StrictLevel theStrictLevel = Font_StrictLevel_Any);
//! Return TRUE if specified character is within subset of modern CJK characters.
static bool IsCharFromCJK (Standard_Utf32Char theUChar)
{
return (theUChar >= 0x03400 && theUChar <= 0x04DFF)
|| (theUChar >= 0x04E00 && theUChar <= 0x09FFF)
|| (theUChar >= 0x0F900 && theUChar <= 0x0FAFF)
|| (theUChar >= 0x20000 && theUChar <= 0x2A6DF)
|| (theUChar >= 0x2F800 && theUChar <= 0x2FA1F)
// Hiragana and Katakana (Japanese) are NOT part of CJK, but CJK fonts usually include these symbols
|| IsCharFromHiragana (theUChar)
|| IsCharFromKatakana (theUChar);
}
//! Return TRUE if specified character is within subset of Hiragana (Japanese).
static bool IsCharFromHiragana (Standard_Utf32Char theUChar)
{
return (theUChar >= 0x03040 && theUChar <= 0x0309F);
}
//! Return TRUE if specified character is within subset of Katakana (Japanese).
static bool IsCharFromKatakana (Standard_Utf32Char theUChar)
{
return (theUChar >= 0x030A0 && theUChar <= 0x030FF);
}
//! Return TRUE if specified character is within subset of modern Korean characters (Hangul).
static bool IsCharFromKorean (Standard_Utf32Char theUChar)
{
return (theUChar >= 0x01100 && theUChar <= 0x011FF)
|| (theUChar >= 0x03130 && theUChar <= 0x0318F)
|| (theUChar >= 0x0AC00 && theUChar <= 0x0D7A3);
}
//! Return TRUE if specified character is within subset of Arabic characters.
static bool IsCharFromArabic (Standard_Utf32Char theUChar)
{
return (theUChar >= 0x00600 && theUChar <= 0x006FF);
}
//! Return TRUE if specified character should be displayed in Right-to-Left order.
static bool IsCharRightToLeft (Standard_Utf32Char theUChar)
{
return IsCharFromArabic(theUChar);
}
//! Determine Unicode subset for specified character
static Font_UnicodeSubset CharSubset (Standard_Utf32Char theUChar)
{
if (IsCharFromCJK (theUChar))
{
return Font_UnicodeSubset_CJK;
}
else if (IsCharFromKorean (theUChar))
{
return Font_UnicodeSubset_Korean;
}
else if (IsCharFromArabic (theUChar))
{
return Font_UnicodeSubset_Arabic;
}
return Font_UnicodeSubset_Western;
}
public:
//! Create uninitialized instance.
Standard_EXPORT Font_FTFont (const Handle(Font_FTLibrary)& theFTLib = Handle(Font_FTLibrary)());
//! Destructor.
Standard_EXPORT virtual ~Font_FTFont();
//! @return true if font is loaded
inline bool IsValid() const
{
return myFTFace != NULL;
}
//! @return image plane for currently rendered glyph
inline const Image_PixMap& GlyphImage() const
{
return myGlyphImg;
}
//! Initialize the font from the given file path.
//! @param theFontPath path to the font
//! @param theParams initialization parameters
//! @param theFaceId face id within the file (0 by default)
//! @return true on success
bool Init (const TCollection_AsciiString& theFontPath,
const Font_FTFontParams& theParams,
const Standard_Integer theFaceId = 0)
{
return Init (Handle(NCollection_Buffer)(), theFontPath, theParams, theFaceId);
}
//! Initialize the font from the given file path or memory buffer.
//! @param theData memory to read from, should NOT be freed after initialization!
//! when NULL, function will attempt to open theFileName file
//! @param theFileName optional path to the font
//! @param theParams initialization parameters
//! @param theFaceId face id within the file (0 by default)
//! @return true on success
Standard_EXPORT bool Init (const Handle(NCollection_Buffer)& theData,
const TCollection_AsciiString& theFileName,
const Font_FTFontParams& theParams,
const Standard_Integer theFaceId = 0);
//! Find (using Font_FontMgr) and initialize the font from the given name.
//! @param theFontName the font name
//! @param theFontAspect the font style
//! @param theParams initialization parameters
//! @param theStrictLevel search strict level for using aliases and fallback
//! @return true on success
Standard_EXPORT bool FindAndInit (const TCollection_AsciiString& theFontName,
Font_FontAspect theFontAspect,
const Font_FTFontParams& theParams,
Font_StrictLevel theStrictLevel = Font_StrictLevel_Any);
//! Return flag to use fallback fonts in case if used font does not include symbols from specific Unicode subset; TRUE by default.
//! @sa Font_FontMgr::ToUseUnicodeSubsetFallback()
Standard_Boolean ToUseUnicodeSubsetFallback() const { return myToUseUnicodeSubsetFallback; }
//! Set if fallback fonts should be used in case if used font does not include symbols from specific Unicode subset.
void SetUseUnicodeSubsetFallback (Standard_Boolean theToFallback) { myToUseUnicodeSubsetFallback = theToFallback; }
//! Return TRUE if this is single-stroke (one-line) font, FALSE by default.
//! Such fonts define single-line glyphs instead of closed contours, so that they are rendered incorrectly by normal software.
bool IsSingleStrokeFont() const { return myFontParams.IsSingleStrokeFont; }
//! Set if this font should be rendered as single-stroke (one-line).
void SetSingleStrokeFont (bool theIsSingleLine) { myFontParams.IsSingleStrokeFont = theIsSingleLine; }
//! Return TRUE if italic style should be synthesized; FALSE by default.
bool ToSynthesizeItalic() const { return myFontParams.ToSynthesizeItalic; }
//! Release currently loaded font.
Standard_EXPORT virtual void Release();
//! Render specified glyph into internal buffer (bitmap).
Standard_EXPORT bool RenderGlyph (const Standard_Utf32Char theChar);
//! @return maximal glyph width in pixels (rendered to bitmap).
Standard_EXPORT unsigned int GlyphMaxSizeX (bool theToIncludeFallback = false) const;
//! @return maximal glyph height in pixels (rendered to bitmap).
Standard_EXPORT unsigned int GlyphMaxSizeY (bool theToIncludeFallback = false) const;
//! @return vertical distance from the horizontal baseline to the highest character coordinate.
Standard_EXPORT float Ascender() const;
//! @return vertical distance from the horizontal baseline to the lowest character coordinate.
Standard_EXPORT float Descender() const;
//! @return default line spacing (the baseline-to-baseline distance).
Standard_EXPORT float LineSpacing() const;
//! Configured point size
unsigned int PointSize() const
{
return myFontParams.PointSize;
}
//! Return glyph scaling along X-axis.
float WidthScaling() const
{
return myWidthScaling;
}
//! Setup glyph scaling along X-axis.
//! By default glyphs are not scaled (scaling factor = 1.0)
void SetWidthScaling (const float theScaleFactor)
{
myWidthScaling = theScaleFactor;
}
//! Return TRUE if font contains specified symbol (excluding fallback list).
Standard_EXPORT bool HasSymbol (Standard_Utf32Char theUChar) const;
//! Compute horizontal advance to the next character with kerning applied when applicable.
//! Assuming text rendered horizontally.
//! @param theUCharNext the next character to compute advance from current one
Standard_EXPORT float AdvanceX (Standard_Utf32Char theUCharNext) const;
//! Compute horizontal advance to the next character with kerning applied when applicable.
//! Assuming text rendered horizontally.
//! @param theUChar the character to be loaded as current one
//! @param theUCharNext the next character to compute advance from current one
Standard_EXPORT float AdvanceX (Standard_Utf32Char theUChar,
Standard_Utf32Char theUCharNext);
//! Compute vertical advance to the next character with kerning applied when applicable.
//! Assuming text rendered vertically.
//! @param theUCharNext the next character to compute advance from current one
Standard_EXPORT float AdvanceY (Standard_Utf32Char theUCharNext) const;
//! Compute vertical advance to the next character with kerning applied when applicable.
//! Assuming text rendered vertically.
//! @param theUChar the character to be loaded as current one
//! @param theUCharNext the next character to compute advance from current one
Standard_EXPORT float AdvanceY (Standard_Utf32Char theUChar,
Standard_Utf32Char theUCharNext);
//! Return glyphs number in this font.
//! @param theToIncludeFallback if TRUE then the number will include fallback list
Standard_EXPORT Standard_Integer GlyphsNumber (bool theToIncludeFallback = false) const;
//! Retrieve glyph bitmap rectangle
Standard_EXPORT void GlyphRect (Font_Rect& theRect) const;
//! Computes bounding box of the given text using plain-text formatter (Font_TextFormatter).
//! Note that bounding box takes into account the text alignment options.
//! Its corners are relative to the text alignment anchor point, their coordinates can be negative.
Standard_EXPORT Font_Rect BoundingBox (const NCollection_String& theString,
const Graphic3d_HorizontalTextAlignment theAlignX,
const Graphic3d_VerticalTextAlignment theAlignY);
public:
//! Computes outline contour for the symbol.
//! @param theUChar [in] the character to be loaded as current one
//! @param theOutline [out] outline contour
//! @return true on success
Standard_EXPORT const FT_Outline* renderGlyphOutline(const Standard_Utf32Char theChar);
public:
//! Initialize the font.
//! @param theFontPath path to the font
//! @param thePointSize the face size in points (1/72 inch)
//! @param theResolution the resolution of the target device in dpi
//! @return true on success
Standard_DEPRECATED ("Deprecated method, Font_FTFontParams should be used for passing parameters")
bool Init (const NCollection_String& theFontPath,
unsigned int thePointSize,
unsigned int theResolution)
{
Font_FTFontParams aParams;
aParams.PointSize = thePointSize;
aParams.Resolution = theResolution;
return Init (theFontPath.ToCString(), aParams, 0);
}
//! Initialize the font.
//! @param theFontName the font name
//! @param theFontAspect the font style
//! @param thePointSize the face size in points (1/72 inch)
//! @param theResolution the resolution of the target device in dpi
//! @return true on success
Standard_DEPRECATED ("Deprecated method, Font_FTFontParams should be used for passing parameters")
bool Init (const NCollection_String& theFontName,
Font_FontAspect theFontAspect,
unsigned int thePointSize,
unsigned int theResolution)
{
Font_FTFontParams aParams;
aParams.PointSize = thePointSize;
aParams.Resolution = theResolution;
return FindAndInit (theFontName.ToCString(), theFontAspect, aParams);
}
protected:
//! Convert value to 26.6 fixed-point format for FT library API.
template <typename theInput_t>
int32_t toFTPoints (const theInput_t thePointSize) const
{
return (int32_t)thePointSize * 64;
}
//! Convert value from 26.6 fixed-point format for FT library API.
template <typename theReturn_t, typename theFTUnits_t>
inline theReturn_t fromFTPoints (const theFTUnits_t theFTUnits) const
{
return (theReturn_t)theFTUnits / 64.0f;
}
protected:
//! Load glyph without rendering it.
Standard_EXPORT bool loadGlyph (const Standard_Utf32Char theUChar);
//! Wrapper for FT_Get_Kerning - retrieve kerning values.
Standard_EXPORT bool getKerning (FT_Vector& theKern,
Standard_Utf32Char theUCharCurr,
Standard_Utf32Char theUCharNext) const;
//! Initialize fallback font.
Standard_EXPORT bool findAndInitFallback (Font_UnicodeSubset theSubset);
//! Enable/disable load flag.
void setLoadFlag (int32_t theFlag, bool theToEnable)
{
if (theToEnable)
{
myLoadFlags |= theFlag;
}
else
{
myLoadFlags &= ~theFlag;
}
}
protected:
Handle(Font_FTLibrary) myFTLib; //!< handle to the FT library object
Handle(NCollection_Buffer) myBuffer; //!< memory buffer
Handle(Font_FTFont) myFallbackFaces[Font_UnicodeSubset_NB]; //!< fallback fonts
FT_Face myFTFace; //!< FT face object
FT_Face myActiveFTFace; //!< active FT face object (the main of fallback)
TCollection_AsciiString myFontPath; //!< font path
Font_FTFontParams myFontParams; //!< font initialization parameters
Font_FontAspect myFontAspect; //!< font initialization aspect
float myWidthScaling; //!< scale glyphs along X-axis
int32_t myLoadFlags; //!< default load flags
Image_PixMap myGlyphImg; //!< cached glyph plane
Standard_Utf32Char myUChar; //!< currently loaded unicode character
Standard_Boolean myToUseUnicodeSubsetFallback; //!< use default fallback fonts for extended Unicode sub-sets (Korean, CJK, etc.)
};
#endif // _Font_FTFont_H__
|
#include "room.h"
#include "demon.h"
#include "boss.h"
#include "skull.h"
#include <iostream>
int Room::nbRoom = 0;
Room::Room(int a)
{
nbRoom ++;
//Si on appelle le constructeur Room(1), la room créée est celle du Boss, qui ne contient donc aucun autre monstre
if(!a==1)
{ //Positions où apparaitront les ennemis
sf::Vector2f tabPosition[6] = {sf::Vector2f(100,250),
sf::Vector2f(100,400),
sf::Vector2f(300,250),
sf::Vector2f(300,400),
sf::Vector2f(400,250),
sf::Vector2f(400,400)};
//Nombre d'ennemis dans la salle
int rando = sf::Randomizer::Random(1, 6);
int nd = sf::Randomizer::Random(1,rando);
int ns = rando-nd;
for(int i=0;i<nd;i++)
{
listEnemy.push_back(new Demon(tabPosition[i]));
}
for (int i=0;i<ns;i++)
{
listEnemy.push_back(new Skull(tabPosition[i+nd]));
}
}
else
listEnemy.push_back(new Boss());
}
Room::~Room()
{
for(int i=0; i<this->getListEnemy().size(); i++)
delete this->getListEnemy()[i];
}
bool Room::isClear()
{
for(int i=0; i< this->getListEnemy().size(); i++)
{
if(!this->getListEnemy()[i]->IsDead())
return false;
}
return true;
}
|
class Solution {
public:
string reverseString(string s) {
string res = s;
int left = 0;
int right = res.size() - 1;
while(left < right){
swap(res[left++],res[right--]);
}
return res;
}
};
|
/*
* GadgetApplicationListener.h
* Opera
*
* Created by Mateusz Berezecki on 5/13/09.
* Copyright 2009 Opera Software. All rights reserved.
*
*/
#include "core/pch.h"
#ifndef GADGET_APPLICATION_LISTENER
#define GADGET_APPLICATION_LISTENER
#ifdef WIDGET_RUNTIME_SUPPORT
#include "platforms/mac/quick_support/MacApplicationListener.h"
class MacGadgetApplicationListener : public MacApplicationListener
{
virtual void OnStart();
};
#endif
#endif
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <memory>
#include <valarray>
#include <numeric>
#include <functional>
using namespace std;
int main() {
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int N;
scanf("%d", &N);
vector<int> v(N, 0);
for (int i = 0; i < N; i++)
scanf("%d", &v[i]);
sort(v.rbegin(), v.rend());
int m = sqrt(N);
while (N % m != 0)
m++;
int n = N / m;
if (m < n)
swap(m, n);
vector<int> vec(n, 0);
vector<vector<int> > mat(m, vec);
int i = 0, j = 0, cnt = 0;
while (cnt < N) {
while (cnt < N && j < n && mat[i][j] == 0)
mat[i][j++] = v[cnt++];
j--; i++;
while (cnt < N && i < m && mat[i][j] == 0)
mat[i++][j] = v[cnt++];
i--; j--;
while (cnt < N && j >= 0 && mat[i][j] == 0)
mat[i][j--] = v[cnt++];
j++; i--;
while (cnt < N && i >= 0 && mat[i][j] == 0)
mat[i--][j] = v[cnt++];
i++; j++;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (j != 0)
printf(" ");
printf("%d", mat[i][j]);
}
printf("\n");
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef struct node *typeptr;
struct node{
int info;
typeptr next;
typeptr prev;
};
typeptr first, end;
int listKosong()
{
if(first==NULL)
return(true);
else
return(false);
}
void buatListBaru()
{
typeptr list;
list=NULL;
first=list;
end=list;
}
void sisipNode(int new_info)
{
typeptr new_node, helper,helper2;
new_node=(node *) malloc(sizeof(node));
new_node->info=new_info;
new_node->next=NULL;
new_node->prev=NULL;
if (listKosong()){
first=new_node;
end=new_node;
}
else if (new_info <= first->info){
first->prev=new_node;
new_node->next=first;
first=new_node;
}
else{
helper=first;
while (helper->next!=NULL && new_info > helper->next->info)
helper=helper->next;
helper2=helper->next;
new_node->prev=helper;
new_node->next=helper->next; // Sisip di tengah atau di belakang
helper->next=new_node;
if (new_info>end->info){
end=new_node;
} else{
helper2->prev = new_node;
}
}
}
void bacaMundur()
{
typeptr helper;
helper = end;
int i=0;
while (helper!= NULL)
{
if(i==2){
helper = helper->prev;
i=0;
continue;
}
cout << ' ' << helper->info << ' ';
helper = helper->prev;
i++;
}
}
int main(){
buatListBaru();
sisipNode(50);
sisipNode(25);
sisipNode(150);
sisipNode(75);
sisipNode(100);
sisipNode(125);
bacaMundur();
}
|
#ifndef TRAP_H
#define TRAP_H
#include "baseobject.h"
#include "hpreducer.h"
class Trap : public BaseObject, public HPReducer {
Q_OBJECT
public:
Trap(QObject *parent = nullptr);
Trap(int x,
int y,
int width,
int height,
const QString& imgPath,
int _HPReduce,
QObject *parent = nullptr);
};
#endif // TRAP_H
|
#include "SceneManager.h"
namespace FW
{
SceneManager::SceneManager(Application& app)
: app(app)
{
}
void SceneManager::popScene()
{
scenes.pop_back();
}
SceneManager::BaseScene& SceneManager::getCurrentScene()
{
return *scenes.back();
}
}
|
//
// Created by fab on 09/04/2020.
//
#ifndef DUMBERENGINE_GUICOMPONENT_HPP
#define DUMBERENGINE_GUICOMPONENT_HPP
class GuiComponent
{
protected:
bool isActive;
public:
//used to show params in the inspector
virtual void drawInspector() = 0;
virtual ~GuiComponent()= default;
};
#endif //DUMBERENGINE_GUICOMPONENT_HPP
|
class Solution {
public:
bool isPowerOfFour(int num) {
return (num > 0 && ((int)(log10(num)/log10(4)) - log10(num)/log10(4)) == 0);
}
};
|
#include "digitizerTriggerHandler.h"
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <signal.h>
#include "common_defs.h"
extern pthread_mutex_t M_cout;
extern pthread_mutex_t DataReadoutDone;
extern pthread_mutex_t DataReadyReset;
#define BUFFER_LENGTH 260096
#define INCLUDE_ADC
using namespace std;
/**
* digitizerTriggerHandle ctor
* arguements
* string & dcm2partreadoutJsebName ; jseb2 connected to dcm2 partitioner
* string & dcm2deviceName ; dcm2 object name
* string & dcm2datfileName ; dcm2 dat config file name
* string & dcm2Jseb2Name ; jseb2 connected to dcm2 controller
*/
digitizerTriggerHandler::digitizerTriggerHandler( const int eventtype
, xmit_group_modules xmit_groups[]
, const string & dcm2datfileName
, const string & outputDataFileName
, const string & dcm2partreadoutJsebName
, const string & dcm2Jseb2Name
, const string & adcJseb2Name
, const int num_xmitgroups
, const int nevents
)
{
_broken = 0;
partreadoutJseb2Name = dcm2partreadoutJsebName;
dcm2jseb2name = dcm2Jseb2Name;
_adcJseb2Name = adcJseb2Name;
char *dcm2_config_dir = getenv("DCM2_CONFIG_DIR");
if (!dcm2_config_dir) {
configfileDir = "/home/phnxrc/desmond/daq/build/";
} else {
configfileDir = dcm2_config_dir;
}
dcm2configfilename = configfileDir + dcm2datfileName;
cout << __FILE__ << " Using DCM2 config file " << dcm2configfilename.c_str() << endl;
//datafiledirectory = "/data0/phnxrc/buffer_t1044/t1044/";
datafiledirectory = "/data0/phnxrc/ejdtest/";
_outputDataFileName = outputDataFileName;
_num_xmitgroups = num_xmitgroups;
//cout << __LINE__ << " " << __FILE__ << " TriggerHandler - copy " << _num_xmitgroups << " xmit_groups " << endl;
for (int ig = 0; ig < _num_xmitgroups; ig++)
{
//cout << __FILE__ << __LINE__ << " copy xmit group " << ig << " slot " << xmit_groups[ig].slot_nr << endl;
_xmit_groups[ig].slot_nr = xmit_groups[ig].slot_nr;
_xmit_groups[ig].nr_modules = xmit_groups[ig].nr_modules;
_xmit_groups[ig].l1_delay = xmit_groups[ig].l1_delay;
_xmit_groups[ig].n_samples = xmit_groups[ig].n_samples;
}
_nevents = nevents;
//partreadoutJseb2Name = "JSEB2.8.0";
//dcm2jseb2name = "JSEB2.5.0"; // dcm2 controller jseb2 on va095 port 1
//dcm2name = "DCMGROUP.TEST.1";
//dcm2configfilename = "/home/phnxrc/desmond/daq/build/dcm2ADCPar.dat";
jseb2adcportnumber = 2; // default jseb2 port number for digitizer control
_nevents = (unsigned long)nevents;
debugReadout = false;
enable_rearm = false;
initialize();
}
int digitizerTriggerHandler::rearm()
{
if ( enable_rearm == false)
{
enable_rearm = true;
} else
{
pthread_mutex_unlock(&DataReadoutDone ); // continue dma readout
pthread_mutex_lock(&DataReadyReset); // wait for trigger ready is reset
//pthread_mutex_lock(&M_cout);
//cout << __FILE__ << " " << __LINE__ << " TH->rearm LOCKED DataReadyReset ** " << endl;
//pthread_mutex_unlock(&M_cout);
}
return 0;
} // rearm
bool digitizerTriggerHandler::dcm2_getline(ifstream *fin, string *line) {
// needed to parse dat files with and without
// end of line escape characters
string tempstring;
(*line) = "";
// read in all lines until the last char is not a '\'
while (getline(*fin, tempstring)) {
// if no escape character, end of line
int length = tempstring.size();
if (tempstring[length-1] != '\\') {
(*line) += tempstring;
return true;
} else { // continue to next line
tempstring.resize(length-2);
(*line) += tempstring;
}
}
// end of file
return false;
}
/**
* parseDcm2Configfile
* find the name of the dcm in the dat file
* label:ONCS_PARTITIONER, name:DCMGROUP.TEST.1
*/
int digitizerTriggerHandler::parseDcm2Configfile(string dcm2configfilename)
{
int status = 0;
string cfg_line;
// open configuration file
ifstream fin(dcm2configfilename.c_str());
if (!fin) {
return 1;
}
size_t pos = 0;
string tokenholder;
int linecount = 0;
// in dat file name is on line 2 after name:
while (dcm2_getline(&fin, &cfg_line))
{
//cout << "parse search line " << cfg_line.c_str() << endl;
//while(( cfg_line.substr(cfg_line.find("name:"))) != string::npos)
// search for label:ONCS_PARTITIONER
if((pos = cfg_line.find("label:")) != string::npos)
{
tokenholder = cfg_line.substr(pos+6,16);
//cout << __LINE__ << " found label " << tokenholder.c_str() << endl;
}
if (strncmp(tokenholder.c_str(),"ONCS_PARTITION",14) == 0 )
{
//cout << __LINE__ << " found ONCS_PARTITONER label " << endl;
if((pos = cfg_line.find("name:")) != string::npos)
{
// now should be at the position of the name: start after : character
dcm2name = cfg_line.substr(pos+5,15);
cout << __LINE__ << " digitizerTriggerHandler found dcm2name " << dcm2name.c_str() << endl;
break;
} // search for name word
} else {
//cout << __LINE__ << " NOT on ONCS_PARTITONER line - get next line" << endl;
}
linecount++;
if (linecount > 4)
break;
} // search string
return status;
} // parseDcm2Configfile(dcm2configfilename)
int digitizerTriggerHandler::initialize() // called at object creation
{
int partitionNb = 0;
dcm2_tid = 0;
enable_rearm = false;
string _outputDataFileName = "rcdaqadctest.prdf";
parseDcm2Configfile(dcm2configfilename);
pjseb2c = new jseb2Controller();
jseb2Controller::forcexit = false; // signal jseb run end
pjseb2c->Init(partreadoutJseb2Name);
pjseb2c->setNumberofEvents(_nevents);
pjseb2c->setOutputFilename(_outputDataFileName);
return 0;
} // initialize
int digitizerTriggerHandler::init() // called at begin-run
{
int partitionNb = 0;
dcm2_tid = 0;
enable_rearm = false;
string _outputDataFileName = "rcdaqfvtxtest.prdf";
for ( int ig = 0; ig < _num_xmitgroups ; ig++ )
{
cout << __FILE__ << " Create ADC for xmit group " << ig << endl;
pADC[ig] = new ADC();
pADC[ig]->setNumAdcBoards(ig,_xmit_groups[ig].nr_modules);
pADC[ig]->setFirstAdcSlot(ig,_xmit_groups[ig].slot_nr);
pADC[ig]->setJseb2Name(_adcJseb2Name);
pADC[ig]->setL1Delay(_xmit_groups[ig].l1_delay);
pADC[ig]->setSampleSize(ig,_xmit_groups[ig].n_samples);
cout << __LINE__ << " " << __FILE__ << " NUM modules: " << _xmit_groups[ig].nr_modules
<< " slot num: " << _xmit_groups[ig].slot_nr << " adcjseb " << _adcJseb2Name.c_str()
<< " NUM SAMPLES " << _xmit_groups[ig].n_samples << endl;
}
// 11/14/2018 adc is hardcoded to use JSEB2 port 2. This option implements the change
//padc->setJseb2Port(jseb2adcportnumber); // TODO add option to set port number
// create dcm2 control object
pdcm2Object = new dcm2Impl(dcm2name.c_str(),partitionNb );
jseb2Controller::forcexit = false; // signal jseb run end
pjseb2c->setExitRequest(false);
// set up process memory map for exit notificatin
pdcm2Object->setExitMap();
// configure (download) the dcm2
pdcm2Object->download(dcm2name,dcm2configfilename,partitionNb);
pjseb2c->start_read2file(); // start read2file thread
// test if DMA buffer allocation succeeded
if (jseb2Controller::dmaallocationsuccess == false)
{
cerr << "Failed to allocate DMA buffer space - aborting start run " << endl;
delete pdcm2Object;
//pjseb2c->Close();
//delete pjseb2c;
return 1;
}
// initialize adc modules _xmit_groups[ig].nr_modules // num_modules for each xmit group
for (int ixmit = 0 ; ixmit < _num_xmitgroups ; ixmit++)
{
if ( pADC[ixmit]->initialize(_nevents) == false ) {
cout << "Failed to initialize xmit - try restart windriver " << endl;
return 1;
}
/*
if ( pADC[ixmit]->initialize(_nevents) == false ) {
cout << "Failed to initialize xmit - try restart windriver " << endl;
return 1;
}
if ( pADC[ixmit]->initialize(_nevents) == false ) {
cout << "Failed to initialize xmit - try restart windriver " << endl;
return 1;
}
*/
break;
} // init all xmit modules
dcm2_tid = pdcm2Object->startRunThread(dcm2name,_nevents,_outputDataFileName.c_str());
enable_rearm = false;
return 0;
} // init
digitizerTriggerHandler::~digitizerTriggerHandler()
{
pjseb2c->Close();
cout << __FILE__ << " " << __LINE__ << " delete jsebController object " << endl;
delete pjseb2c;
//delete pdcm2Object; // deleted at endrun ; 01/22/2019
// if (hPlx) DIGITIZER_Close( hPlx );
//if (buffer) free(buffer);
}
int digitizerTriggerHandler::wait_for_trigger( const int moreinfo)
{
// const int delayvalue = 10000;
while(jseb2Controller::rcdaqdataready != true)
{
if (debugReadout)
cout << __FILE__ << " " << " wait_for_trigger NO data detected " << endl;
return 0;
}
if (debugReadout) {
cout << __FILE__ << " " << __LINE__ << " wait_for_trigger data detected dataready = "<< jseb2Controller::rcdaqdataready << endl;
}
return 1;
}
int digitizerTriggerHandler::endrun() // called at begin-run
{
cout << __FILE__ << " " << __LINE__ << " endrun - CLOSE jseb " << endl;
// A test for the run completed should be executed. This test is set
// if the specified number of events are collected.
// This test is if (jseb2Controller::runcompleted == false) endrun
#ifdef INCLUDE_ADC
for (int ig = 0; ig < _num_xmitgroups; ig++)
{
cout << __FILE__ << " " << __LINE__ << " delete pADC " << ig << endl;
delete pADC[ig];
}
//delete padc;
#endif
pdcm2Object->stopRun(dcm2name);
// release lock on ReadoutDone so jseb can exit.
pthread_mutex_unlock(&DataReadoutDone );
pthread_mutex_unlock(&DataReadyReset );
//cout << __FILE__ << " " << __LINE__ << " set forcexit to TRUE " << endl;
jseb2Controller::forcexit = true; // signal jseb run end
pjseb2c->setExitRequest(true);
//cout << __FILE__ << " " << __LINE__ << " setExitRequest to TRUE sleep " << endl;
sleep(4); // wait for data to be written
//pjseb2c->Close();
//cout << __FILE__ << " " << __LINE__ << " delete dcm2 object " << endl;
delete pdcm2Object;
return 0;
}
int digitizerTriggerHandler::put_data( int *d, const int max_words)
{
if ( _broken ) return 0;
static long imod,ichip;
static UINT32 i,k,nread,iprint;
iprint = 0;
int *dest = d;
// 8bits for the samples, 8 bits for the delay, 8 bits for slot, 8 bits for _nr_modules
int tempd[10];
int *ptmpd = tempd;
int wordcount = 0; // we have one word so far
nread = pjseb2c->getEventSize();
//cout << __FILE__ << __LINE__ << " Got event data size = " << nread << endl;
// get pointer to data buffer
const UINT32 *peventdataarray = pjseb2c->getEventData();
// sanity check on event size
if (nread <= 6000 )
{
//pthread_mutex_lock(&M_cout);
//cout << __FILE__ << __LINE__ << " Writing event data size = " << nread << " from address " << peventdataarray << " to address " << dest << endl;
//pthread_mutex_unlock(&M_cout);
for (int idata = 0; idata < nread ; idata++ )
{
*dest = *(peventdataarray + idata);
//*tempd = *(peventdataarray + idata);
dest++;
//cout << __FILE__ << " " << __LINE__ << " copied word " << idata << " to buffer " << endl;
}
} // nread sanity check
//pthread_mutex_lock(&M_cout);
//cout << __FILE__ << __LINE__ << " DONE Writing event data size = " << nread << endl;
//pthread_mutex_unlock(&M_cout);
if (debugReadout) {
//cout << __FILE__ << " " << __LINE__ << " put_data: read back " << nread << " event words - sending back words read = " << nread - 8 << endl;
}
wordcount = nread;
// remove discarded dcm2 header in returned word count
return nread - 8;
}
|
#include "_pch.h"
#include "dlg_mkobj_view_Frame.h"
#include "MObjCatalog.h"
#include "PGClsPid.h"
using namespace wh;
using namespace wh::object_catalog::view;
//---------------------------------------------------------------------------
Frame::Frame(wxWindow* parent,
wxWindowID id,
const wxString& title,
const wxPoint& pos,
const wxSize& size,
long style,
const wxString& name)
//: wh::view::DlgBaseOkCancel(parent, id, title, pos, size, style, name)
: wxDialog(parent, id, title, pos, size, style, name)
{
wxSizer* szrMain = new wxBoxSizer(wxVERTICAL);
auto mgr = ResMgr::GetInstance();
this->SetIcon(wxIcon(mgr->m_ico_obj24));
mPropGrid = new wxPropertyGrid(this);
szrMain->Add(mPropGrid, 1, wxALL | wxEXPAND, 1);
wxBoxSizer* msdbSizer = new wxBoxSizer(wxHORIZONTAL);
msdbSizer->Add(0, 0, 1, wxEXPAND, 5);
mbtnOK = new wxButton(this, wxID_OK, "Сохранить и закрыть");
mbtnCancel = new wxButton(this, wxID_CANCEL, "Отмена");
msdbSizer->Add(mbtnCancel, 0, wxALL, 5);
msdbSizer->Add(mbtnOK, 0, wxALL, 5);
szrMain->Add(msdbSizer, 0, wxEXPAND, 10);
Bind(wxEVT_COMMAND_BUTTON_CLICKED, &Frame::OnOk, this, wxID_OK);
this->SetSizer(szrMain);
this->Layout();
auto pg_mainInfo = new wxPropertyCategory("Основные сведения");
mPropGrid->Append(pg_mainInfo);
pg_mainInfo->AppendChild(new wxStringProperty(L"Имя", wxPG_LABEL));
mPGQty = new wxFloatProperty(L"Количество", wxPG_LABEL);
pg_mainInfo->AppendChild(mPGQty);
pg_mainInfo->AppendChild(new wxStringProperty(L"ID", wxPG_LABEL))->Enable(false);
mPGParent = new wxPGPBaseProperty("Местоположение");
mPropGrid->SetPropertyReadOnly(mPGParent, true);
auto parent_obj_cat = std::make_shared<MCat>();
parent_obj_cat->SetCfg(rec::CatCfg(rec::catObj, false, true));
parent_obj_cat->SetFilterClsKind(ClsKind::QtyByOne, foLess, true);
mPGParent->SetCatalog(parent_obj_cat,true);
mPropGrid->Append(mPGParent);
}
//---------------------------------------------------------------------------
void Frame::SetModel(std::shared_ptr<object_catalog::MObjItem>& newModel)
{
if (mObj != newModel)
{
mChangeConnection.disconnect();
mObj = newModel;
if (mObj)
{
auto funcOnChange = std::bind(&Frame::OnChangeModel,
this, std::placeholders::_1, std::placeholders::_2);
mChangeConnection = mObj->DoConnect(moAfterUpdate, funcOnChange);
OnChangeModel(mObj.get(), nullptr);
}//if (mModel)
}//if
}
//---------------------------------------------------------------------------
void Frame::OnChangeModel(const IModel* model, const object_catalog::MObjItem::T_Data* data)
{
if (!mObj || mObj.get() != model)
return;
auto obj_array = mObj->GetParent();
if (!obj_array)
return;
auto cls_model = dynamic_cast<MTypeItem*>(obj_array->GetParent());
if (!cls_model)
return;
auto cls_array = cls_model->GetParent();
if (!cls_array)
return;
auto catalog = dynamic_cast<MObjCatalog*>(cls_array->GetParent());
if (!catalog)
return;
const auto& cls_data = cls_model->GetData();
const auto& obj_data = mObj->GetData();
const auto obj_state = model->GetState();
SetData(obj_data);
if (!cls_data.mType.IsNull())
switch (cls_data.GetClsType())
{
case ClsKind::Single:
mPGQty->SetValueFromString("1");
mPGQty->Enable(false);
break;
case ClsKind::QtyByOne:
case ClsKind::QtyByFloat:
mPGQty->SetValueFromString(obj_data.mQty);
mPGQty->Enable(true);
default:break;
}
switch (obj_state)
{
default: SetTitle("**error**"); break;
case msCreated:
SetTitle("Создание объекта");
mPropGrid->SetPropertyValue(mPGParent,
WXVARIANT(catalog->IsObjTree() ? catalog->GetRoot().mObj : cls_data.mDefaultObj));
break;
case msExist: case msUpdated:
SetTitle("Редактирование объекта");
mPropGrid->SetPropertyValue(mPGParent, WXVARIANT(obj_data.mParent));
break;
}
}
//---------------------------------------------------------------------------
void Frame::GetData(object_catalog::MObjItem::T_Data& data) const
{
mPropGrid->CommitChangesFromEditor();
// значение свойства получается из диалоа
data.mLabel = mPropGrid->GetPropertyByLabel("Имя")->GetValueAsString();
data.mQty = mPGQty->GetValueAsString();
data.mId = mPropGrid->GetPropertyByLabel("ID")->GetValueAsString();
data.mParent = wh_rec_BaseRefFromVariant(mPGParent->GetValue());
}
//---------------------------------------------------------------------------
void Frame::SetData(const object_catalog::MObjItem::T_Data& data)
{
mPropGrid->CommitChangesFromEditor();
mPropGrid->GetPropertyByLabel(L"Имя")->SetValueFromString(data.mLabel);
mPropGrid->GetPropertyByLabel(L"ID")->SetValueFromString(data.mId);
mPropGrid->SetPropertyValueString(mPGQty, data.mQty.toStr());
mPropGrid->SetPropertyValue(mPGParent, WXVARIANT(data.mParent));
}
//---------------------------------------------------------------------------
/*
void Frame::OnClose(wxCloseEvent& evt)
{
}
//---------------------------------------------------------------------------
void Frame::OnCancel(wxCommandEvent& evt )
{
}
*/
//---------------------------------------------------------------------------
void Frame::OnOk(wxCommandEvent& evt )
{
mChangeConnection.disconnect();// нет смысла перед закрытием апдейтить форму
auto data = mObj->GetData();
GetData(data);
mObj->SetData(data);
mObj->Save();
EndModal(wxID_OK);
}
|
#include <stdio.h>
int main(){
int speed;
scanf("%d", &speed);
const char *s = speed > 60 ? "Speeding" : "OK";
printf("Speed: %d - %s", speed, s);
// printf("Speed: %d - %s", speed, speed > 60 ? "Speeding" : "OK");
return 0;
}
|
/**************************************************************************************
* File Name : OpenGLWindow.hpp
* Project Name : Keyboard Warriors
* Primary Author : JeongHak Kim
* Secondary Author :
* Copyright Information :
* "All content 2019 DigiPen (USA) Corporation, all rights reserved."
**************************************************************************************/
#pragma once
#include <memory>
class EventHandler;
class PlatformWindow;
class OpenGLWindow
{
public:
OpenGLWindow() noexcept;
~OpenGLWindow() noexcept;
bool CanCreateWindow(int width, int height, EventHandler* event_handler, const char* title) noexcept;
void SwapBuffers() noexcept;
void PollEvents() noexcept;
void ToggleVSync(bool status) noexcept;
bool IsVSyncOn() noexcept;
void ToggleFullScreen() noexcept;
bool IsFullScreen() noexcept;
void SetWindowTitle(const char* title) const noexcept;
void SetWindowIcon() const noexcept;
int GetWindowWidth() const noexcept;
void SetWindowWidth(int new_width) noexcept;
int GetWindowHeight() const noexcept;
void SetWindowHeight(int new_height) noexcept;
private:
std::unique_ptr<PlatformWindow> platformWindow;
};
|
// Copyright 2018 Benjamin Bader
//
// 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.
#ifndef CPPMETRICS_METRICS_TIMER_H
#define CPPMETRICS_METRICS_TIMER_H
#include <chrono>
#include <memory>
#include <metrics/Clock.h>
#include <metrics/Histogram.h>
#include <metrics/Meter.h>
#include <metrics/Reservoir.h>
namespace cppmetrics {
class Snapshot;
class Timer
{
public:
Timer();
Timer(std::unique_ptr<Reservoir>&& reservoir);
Timer(std::unique_ptr<Reservoir>&& reservoir, Clock* clock);
Timer(Timer&&) = default;
void update(const std::chrono::nanoseconds& nanos);
void update(const std::chrono::milliseconds& millis);
long get_count();
double get_m1_rate();
double get_m5_rate();
double get_m15_rate();
double get_mean_rate();
std::shared_ptr<Snapshot> get_snapshot();
private:
friend class ScopeTimer;
Clock* m_clock;
Histogram m_histogram;
Meter m_meter;
};
class ScopeTimer
{
public:
ScopeTimer(Timer& timer)
: m_timer(timer)
, m_start(m_timer.m_clock->tick())
{
}
~ScopeTimer()
{
auto elapsed = m_timer.m_clock->tick() - m_start;
m_timer.update(elapsed);
}
private:
Timer& m_timer;
std::chrono::nanoseconds m_start;
};
template <typename Function>
auto timed(Timer& timer, Function&& fn) -> decltype(fn())
{
ScopeTimer scopeTimer(timer);
return fn();
}
}
#endif
|
#include "utils.hpp"
#include "common_ptts.hpp"
#include "actor_ptts.hpp"
namespace nora {
namespace config {
system_preview_ptts& system_preview_ptts_instance() {
static system_preview_ptts inst;
return inst;
}
void system_preview_ptts_set_funcs() {
system_preview_ptts_instance().verify_func_ = [] (const auto& ptt) {
if (!PTTS_HAS(actor, ptt.actor())) {
CONFIG_ELOG << ptt.level() << " actor not exist " << ptt.actor();
}
};
}
name_pool_ptts& name_pool_ptts_instance() {
static name_pool_ptts inst;
return inst;
}
void name_pool_ptts_set_funcs() {
}
common_ptts& common_ptts_instance() {
static common_ptts inst;
return inst;
}
void common_ptts_set_funcs() {
common_ptts_instance().verify_func_ = [] (const auto& ptt) {
for (auto i : ptt.forbid_name_actors()) {
if (!PTTS_HAS(actor, i)) {
CONFIG_ELOG << " forbid name actor not exist " << i;
}
}
};
}
}
}
|
//科普连接:https://home.gamer.com.tw/creationDetail.php?sn=4114818
#include<iostream>
#include<sstream>
/*strstream类同时可以支持C++风格的串流的输入输出操作。 *\
是istringstream和ostringstream类的综合,支持<<, >>操作符
\*可以进行字符串到其它类型的快速转换 */
using namespace std;
int main()
{
/****************************************************\
| 重载>>和<<,相当于,以字符串为载体,存储输入输出流 |
| >>代表寫入stringstream中,<<代表從stringstream拿出 |
\****************************************************/
stringstream s1;
int number =1234;
string output;//要把number轉成字串型態的容器
cout<<"number="<<number<<endl;//顯示number=1234;
s1<<number; //將以int宣告的number放入我們的stringstream中
s1>>output;
cout<<"output="<<output<<endl;//顯示output=1234;
/***********************************\
|stringstream也可以將string轉成int: |
\***********************************/
stringstream string_to_int;
string s2="12345";
int n1;
string_to_int<<s2;
//也可以使用string_to_int.str(s2);
//或者 s1=string_to_int.str();
string_to_int>>n1;
cout<<"s2="<<s2<<endl;//s2=12345
cout<<"n1="<<n1<<endl;//n1=12345
/*******************************************************\
|分割字串的範例: |
|這邊我們來一個在網路上看到的簡單例題來說明怎麼分割字串 |
|題目內容:輸入第一行數字N代表接下來有N行資料,接著每行有|
|不定個數的整數(最多20個,每行最大200個字元), |
|請把每行的總和印出來。 |
|輸入:輸出 | :
|4
|1 1 2 3 5 8 13
|1 1 5
|11 557 996 333
|2 4 6
|輸出
|33
|7
|1897
|12
\********************************************************/
stringstream s3;
int N;//代表有幾行
int i1;//用來存放string轉成int的資料
while(cin>>N)
{
cin.ignore();//估计是跳过换行 :https://www.cnblogs.com/ranjiewen/p/5582601.html
string line;//讀入每行的資料
for(int i=0;i<N;i++)
{
getline(cin,line);//讀入每行的資料
int sum=0;//計算總和
s3.clear();//清除緩存
s3<<line;
//也可以使用s3.str(line);
//還可以寫成line=s3.str();
while(true)
{
s3>>i1;
if(s3.fail()) break;//確認stringstream有正常流出,沒有代表空了
sum+=i1;//把每個轉換成int的數字都丟入sum累加
}
cout<<sum<<endl;
}
}
/***********************************************\
針對stringstream類別的初始化 |
這邊要提到一點就是要重複使用一個stringstream的 |
情況,因為宣告stringstream類別的時候其實蠻消耗 |
CPU的時間,在解題目以及應用的時候不太建議重複宣 |
告,而是使用完之後就初始化再次利用。 |
基本就是要以下這兩行: |
\***********************************************/
stringstream s4;
s4.str("");
s4.clear();
}
|
#pragma once
#ifndef _PROJECT_CAMERA_
#define _PROJECT_CAMERA_
#include "../Project.h"
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
using namespace std;
class ProjectCamera : public Project {
private:
const char* vs_path;
const char* fs_path;
Shader myShader;
int show_what;
int parameter;
glm::mat4 cameraView;
bool changeView;
float ortho_left_right[2];
float ortho_bottom_top[2];
float ortho_near_far[2];
float pers_fov;
float pers_near_far[2];
float vertices[216] = {
-2.0f, -2.0f, -2.0f, 0.0f, 0.0f, 1.0f,
2.0f, -2.0f, -2.0f, 0.0f, 0.0f, 1.0f,
2.0f, 2.0f, -2.0f, 0.0f, 0.0f, 1.0f,
2.0f, 2.0f, -2.0f, 0.0f, 0.0f, 1.0f,
-2.0f, 2.0f, -2.0f, 0.0f, 0.0f, 1.0f,
-2.0f, -2.0f, -2.0f, 0.0f, 0.0f, 1.0f,
-2.0f, -2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
2.0f, -2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
2.0f, 2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
2.0f, 2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
-2.0f, 2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
-2.0f, -2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
-2.0f, 2.0f, 2.0f, 0.0f, 1.0f, 0.0f,
-2.0f, 2.0f, -2.0f, 0.0f, 1.0f, 0.0f,
-2.0f, -2.0f, -2.0f, 0.0f, 1.0f, 0.0f,
-2.0f, -2.0f, -2.0f, 0.0f, 1.0f, 0.0f,
-2.0f, -2.0f, 2.0f, 0.0f, 1.0f, 0.0f,
-2.0f, 2.0f, 2.0f, 0.0f, 1.0f, 0.0f,
2.0f, 2.0f, 2.0f, 1.0f, 1.0f, 0.0f,
2.0f, 2.0f, -2.0f, 1.0f, 1.0f, 0.0f,
2.0f, -2.0f, -2.0f, 1.0f, 1.0f, 0.0f,
2.0f, -2.0f, -2.0f, 1.0f, 1.0f, 0.0f,
2.0f, -2.0f, 2.0f, 1.0f, 1.0f, 0.0f,
2.0f, 2.0f, 2.0f, 1.0f, 1.0f, 0.0f,
-2.0f, -2.0f, -2.0f, 1.0f, 0.0f, 1.0f,
2.0f, -2.0f, -2.0f, 1.0f, 0.0f, 1.0f,
2.0f, -2.0f, 2.0f, 1.0f, 0.0f, 1.0f,
2.0f, -2.0f, 2.0f, 1.0f, 0.0f, 1.0f,
-2.0f, -2.0f, 2.0f, 1.0f, 0.0f, 1.0f,
-2.0f, -2.0f, -2.0f, 1.0f, 0.0f, 1.0f,
-2.0f, 2.0f, -2.0f, 0.0f, 1.0f, 1.0f,
2.0f, 2.0f, -2.0f, 0.0f, 1.0f, 1.0f,
2.0f, 2.0f, 2.0f, 0.0f, 1.0f, 1.0f,
2.0f, 2.0f, 2.0f, 0.0f, 1.0f, 1.0f,
-2.0f, 2.0f, 2.0f, 0.0f, 1.0f, 1.0f,
-2.0f, 2.0f, -2.0f, 0.0f, 1.0f, 1.0f,
};
public:
ProjectCamera(GLFWwindow* window_);
GLFWwindow* window;
void draw();
void render();
void updateCameraView(glm::mat4 cameraView_);
void updateCameraPos(glm::vec3 cameraPos_);
void changeShowWhat();
};
#endif
|
//Created by: Mark Marsala and Marshall Farris
//Date: 5/4/2021
//Interface
#ifndef IFILEIO_H
#define IFILEIO_H
/**
* Class that reads and writes the file inputted into the program
*/
class iFileIO{
protected:
/**
* Function that reads the file
*/
virtual void readFile() = 0;
/**
* Function that writes the file
* @param outFileName - writes out the new file name
*/
virtual void writeFile(const std::string &outFileName) = 0;
};
#endif
|
#include "GnMeshPCH.h"
#include "GnGamePCH.h"
#include "GMainGameMove.h"
#include "GMainGameEnvironment.h"
GMainGameMove::GMainGameMove(GActorController* pController) : GActionMove( pController )
{
mBeforeVerticalDirection = MOVE_MAX;
mBeforeHorizontalDirection = MOVE_MAX;
}
void GMainGameMove::Update(float fDeltaTime)
{
GActionMove::Update( fDeltaTime );
SetCurrentLine();
}
void GMainGameMove::SetMove(gtuint uiType)
{
GActionMove::SetMove( uiType );
if( MOVEUP > uiType )
{
if( mBeforeVerticalDirection == uiType )
return;
if( MOVELEFT == uiType )
GetController()->GetMesh()->SetFlipX( true );
else
GetController()->GetMesh()->SetFlipX( false );
mBeforeVerticalDirection = (eMoveType)uiType;
}
else
{
if( GetMoveUp() )
{
GnVector2 movePos = GetController()->GetPosition();
movePos.y += GetMoveVector().y;
GetController()->SetPosition( movePos );
if( GetActorLayer() )
{
GetActorLayer()->reorderChild( GetController()->GetMesh()->GetMesh()
, (gint)(GetGameState()->GetGameHeight() - movePos.y) );
}
}
else
{
GnVector2 movePos = GetController()->GetPosition();
movePos.y += GetMoveVector().y;
GetController()->SetPosition( movePos );
if( GetActorLayer() )
{
GetActorLayer()->reorderChild( GetController()->GetMesh()->GetMesh()
, (gint)(GetGameState()->GetGameHeight() - movePos.y) );
}
}
}
}
void GMainGameMove::SetCurrentLine()
{
GMainGameEnvironment* env = GMainGameEnvironment::GetSingleton();
float lineHeight = env->GetStageInfo()->GetLineHeight();
GnVector2 movePos = GetController()->GetPosition();
for( gtuint i = 0 ; i < env->GetLineCount() ; i++ )
{
float line = env->GetLine( i ) - ( lineHeight / 2 );
if( line <= movePos.y && lineHeight + line >= movePos.y )
{
mNumLine = i;
break;
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef CLIENTSIDE_STORAGE_SUPPORT
#include "modules/dom/src/storage/storageevent.h"
#include "modules/dom/src/storage/storage.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/doc/frm_doc.h"
DOM_StorageEvent::~DOM_StorageEvent()
{
if (m_value_changed_event != NULL)
m_value_changed_event->Release();
}
/* static */ OP_STATUS
DOM_StorageEvent::Make(DOM_StorageEvent *&event, OpStorageValueChangedEvent *event_obj, DOM_Runtime *runtime)
{
event = OP_NEW(DOM_StorageEvent, ());
OP_STATUS status = DOMSetObjectRuntime(event, runtime,
runtime->GetPrototype(DOM_Runtime::STORAGEEVENT_PROTOTYPE), "StorageEvent");
if (OpStatus::IsError(status))
{
if (event_obj != NULL)
event_obj->Release();
return status;
}
event->m_value_changed_event = event_obj;
if (!event_obj->m_context.m_url.IsEmpty())
RETURN_IF_ERROR(event_obj->m_context.m_url.GetAttribute(URL::KUniName_With_Fragment, event->m_origining_url));
event->InitEvent(STORAGE, runtime->GetEnvironment()->GetWindow(), NULL);
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_StorageEvent::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_key:
if (value && m_value_changed_event != NULL)
{
if (m_value_changed_event->IsClearEvent() || m_value_changed_event->m_event_data->m_key == NULL)
DOMSetNull(value);
else
DOMSetStringWithLength(value, &m_string_holder,
m_value_changed_event->m_event_data->m_key,
m_value_changed_event->m_event_data->m_key_length);
}
return GET_SUCCESS;
case OP_ATOM_oldValue:
if (value && m_value_changed_event != NULL)
{
if (m_value_changed_event->IsClearEvent() || m_value_changed_event->m_event_data->m_old_value == NULL)
DOMSetNull(value);
else
DOMSetStringWithLength(value, &m_string_holder,
m_value_changed_event->m_event_data->m_old_value,
m_value_changed_event->m_event_data->m_old_value_length);
}
return GET_SUCCESS;
case OP_ATOM_newValue:
if (value && m_value_changed_event != NULL)
{
if (m_value_changed_event->IsClearEvent() || m_value_changed_event->m_event_data->m_new_value == NULL)
DOMSetNull(value);
else
DOMSetStringWithLength(value, &m_string_holder,
m_value_changed_event->m_event_data->m_new_value,
m_value_changed_event->m_event_data->m_new_value_length);
}
return GET_SUCCESS;
case OP_ATOM_url:
DOMSetString(value, m_origining_url.CStr());
return GET_SUCCESS;
case OP_ATOM_storageArea:
if (m_custom_storage_obj != NULL)
{
DOMSetObject(value, m_custom_storage_obj);
}
else if (m_value_changed_event != NULL)
{
switch (m_value_changed_event->GetType())
{
case WEB_STORAGE_LOCAL:
return GetEnvironment()->GetWindow()->GetName(OP_ATOM_localStorage, value, origining_runtime);
case WEB_STORAGE_SESSION:
return GetEnvironment()->GetWindow()->GetName(OP_ATOM_sessionStorage, value, origining_runtime);
#ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT
case WEB_STORAGE_WGT_PREFS:
{
ES_Value widgets_value;
if (GetEnvironment()->GetWindow()->GetPrivate(DOM_PRIVATE_widget, &widgets_value) == OpBoolean::IS_TRUE &&
widgets_value.type == VALUE_OBJECT)
{
if (DOM_Object *widgets_object = DOM_GetHostObject(widgets_value.value.object))
if (widgets_object->IsA(DOM_TYPE_WIDGET))
return widgets_object->GetName(OP_ATOM_preferences, value, origining_runtime);
}
return GET_FAILED;
}
#endif //WEBSTORAGE_WIDGET_PREFS_SUPPORT
}
OP_ASSERT(!"This should never happen");
}
return GET_SUCCESS;
}
return DOM_Event::GetName(property_name, value, origining_runtime);
}
/* virtual */ void
DOM_StorageEvent::GCTrace()
{
DOM_Event::GCTrace();
GCMark(m_custom_storage_obj);
}
/* static */ int
DOM_StorageEvent::initStorageEvent(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT(event_obj, DOM_TYPE_STORAGEEVENT, DOM_StorageEvent);
DOM_CHECK_ARGUMENTS("sbbZZZso");
//in DOMString typeArg
//in boolean canBubbleArg
//in boolean cancelableArg
//in DOMString keyArg
//in DOMString oldValueArg
//in DOMString newValueArg
//in DOMString urlArg
//in Storage storageAreaArg
int result = initEvent(this_object, argv, argc, return_value, origining_runtime);
if (result != ES_FAILED)
return result;
// storage area
DOM_ARGUMENT_OBJECT_EXISTING(event_obj->m_custom_storage_obj, 7, DOM_TYPE_STORAGE, DOM_Storage);
OP_ASSERT(event_obj->m_custom_storage_obj != NULL);
// url
CALL_FAILED_IF_ERROR(event_obj->m_origining_url.Set(argv[6].value.string));
if (argv[3].type != VALUE_STRING_WITH_LENGTH &&
argv[4].type != VALUE_STRING_WITH_LENGTH &&
argv[5].type != VALUE_STRING_WITH_LENGTH)
{
// clear event
CALL_FAILED_IF_ERROR(OpStorageValueChangedEvent::Create(
event_obj->m_custom_storage_obj->GetStorageType(),
OpStorageEventContext(), event_obj->m_value_changed_event));
}
else
{
const uni_char *key = NULL, *old_value = NULL, *new_value = NULL;
unsigned key_length = 0, old_value_length = 0, new_value_length = 0;
if (argv[3].type == VALUE_STRING_WITH_LENGTH)
{
key = argv[3].value.string_with_length->string;
key_length = argv[3].value.string_with_length->length;
}
if (argv[4].type == VALUE_STRING_WITH_LENGTH)
{
old_value = argv[4].value.string_with_length->string;
old_value_length = argv[4].value.string_with_length->length;
}
if (argv[5].type == VALUE_STRING_WITH_LENGTH)
{
new_value = argv[5].value.string_with_length->string;
new_value_length = argv[5].value.string_with_length->length;
}
CALL_FAILED_IF_ERROR(OpStorageValueChangedEvent::Create(
event_obj->m_custom_storage_obj->GetStorageType(),
key, key_length,
old_value, old_value_length,
new_value, new_value_length,
OpStorageEventContext(), event_obj->m_value_changed_event));
}
OP_ASSERT(event_obj->m_value_changed_event != NULL);
event_obj->m_value_changed_event->IncRefCount();
#undef ARGUMENT
return result;
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_StorageEvent)
DOM_FUNCTIONS_FUNCTION(DOM_StorageEvent, DOM_StorageEvent::initStorageEvent, "initStorageEvent", "sbbZZZsoo-")
DOM_FUNCTIONS_END(DOM_StorageEvent)
#endif // CLIENTSIDE_STORAGE_SUPPORT
|
#include <string>
#include <iostream>
#include <vector>
#include <unistd.h>
#include <algorithm>
#include <queue>
#include "MorseTranslation.h"
//#include "MorseDriver.h"
#include "GPIOclass.h"
using namespace std;
#define TIME_BASE 150000
int channel_clear = 0;
GPIOClass* gpio;
int morse_init(string pin);
int morse_reset(string pin);
void morse_end();
queue<string> morse_bitstream(queue<string> morse);
void morse_write(queue<string> msg);
int main()
{
string pin = {"4"};
MorseTable hash;
string msg;
queue<string> code, stream;
cout << "Please enter a sentence in uppercase: " << endl;
getline(cin, msg);
int length = (int) msg.length();
cout << "string is: " << msg << ", with length of: " << length << endl << endl;
morse_init();
code = hash.stream(msg);
stream = morse_bitstream(code);
// for(int i = 0; i < length; i++)
// {
// cout << code.at(i) << ' ';
// }
// cout << endl << endl;
// for(uint i = 0; i < stream.size(); i++)
// {
// cout << stream.at(i) << ' ';
// }
// cout << endl << endl;
morse_write(code);
morse_end();
//hash.printTable();
return 0;
}
int morse_init(string& pin)
{
gpio = new GPIOClass(pin); //create new GPIO object to be attached to GPIO
if(gpio->export_gpio() == -1)
return -1; //export GPIO
gpio->setdir_gpio("out"); // GPIO17 set to input
channel_clear = 1;
return 1;
}
int morse_reset(string& pin)
{
channel_clear = 0;
gpio->unexport_gpio();
gpio = new GPIOClass(pin); //create new GPIO object to be attached to GPIO
if(gpio->export_gpio() == -1)
return -1;//export GPIO
gpio->setdir_gpio("out"); // GPIO17 set to input
channel_clear = 1;
return 1;
}
void morse_end()
{
gpio->unexport_gpio();
}
queue<string> morse_bitstream(queue<string> morse)
{
queue<string> stream;
string temp;
int length;
while(morse.size())
{
temp = morse.front();
morse.pop();
length = temp.length();
for(int i = 0; i < length; i++)
{
if(temp[i] == 1)
{
stream.push("1");
stream.push("0");
}
else if(temp[i] == 2)
{
stream.push("1");
stream.push("1");
stream.push("0");
}
else if(temp[i] == 0)
{
stream.push("0");
}
else
{
cerr << "error in bitstream \n";
exit(1);
}
}
stream.push("0");
}
return stream;
}
void morse_write(queue<string> msg)
{
queue<string> bits;
bits = morse_bitstream(msg);
string temp;
while(bits.size())
{
if(channel_clear == 1)
{
channel_clear = 0;
temp = bits.front();
bits.pop();
if(temp == "1")
{
gpio->setval_gpio("1");
usleep(TIME_BASE);
channel_clear = 1;
}
else if(temp == "0")
{
gpio->setval_gpio("0");
usleep(TIME_BASE);
channel_clear = 1;
}
else
{
cerr << "error in write \n";
exit(0);
}
}
}
}
|
#ifndef BS_UTILS_HPP
#define BS_UTILS_HPP
#include <bs/defs.hpp>
#include <bs/detail/threshold.hpp>
#include <chrono>
#include <functional>
#include <opencv2/imgproc.hpp>
namespace bs {
namespace detail {
inline cv::Mat
scale_frame (cv::Mat& frame, double factor) {
cv::Mat bw;
cv::cvtColor (frame, bw, cv::COLOR_BGR2GRAY);
cv::Mat tiny;
cv::resize (bw, tiny, cv::Size (), factor, factor, cv::INTER_LINEAR);
return tiny;
}
}
inline double
dot (const cv::Vec3d& x, const cv::Vec3d& y) {
return x [0] * y [0] + x [1] * y [1] + x [2] * y [2];
}
inline double
dot (const cv::Vec3d& x) {
return dot (x, x);
}
inline cv::Mat
border (const cv::Mat& src, size_t n = 1) {
cv::Mat dst;
cv::copyMakeBorder (
src, dst, n, n, n, n, cv::BORDER_CONSTANT, 0);
return dst;
}
inline cv::Mat
unborder (const cv::Mat& src, size_t n = 1) {
return cv::Mat (
src (cv::Rect (n, n, src.cols - 2 * n, src.rows - 2 * n)));
}
inline std::pair< double, double >
minmax (const cv::Mat& src) {
double a, b;
minMaxLoc (src, &a, &b);
return { a, b };
}
inline cv::Mat
convert (const cv::Mat& src, int t, double a = 1, double b = 0) {
cv::Mat dst;
return src.convertTo (dst, t, a, b), dst;
}
inline cv::Mat
float_from (const cv::Mat& src, double scale = 1. / 255, double offset = 0.) {
return convert (src, CV_32F, scale, offset);
}
inline cv::Mat
double_from (const cv::Mat& src, double scale = 1. / 255, double offset = 0.) {
return convert (src, CV_64F, scale, offset);
}
inline cv::Mat
mono_from (const cv::Mat& src, double scale = 255., double offset = 0.) {
return convert (src, CV_8U, scale, offset);
}
inline cv::Mat
median_blur (const cv::Mat& src, int size = 3) {
cv::Mat dst;
return cv::medianBlur (src, dst, size), dst;
}
inline cv::Mat
blur (const cv::Mat& src) {
return bs::median_blur (src);
}
inline cv::Mat
multiply (const cv::Mat& lhs, const cv::Mat& rhs) {
cv::Mat dst;
return cv::multiply (lhs, rhs, dst), dst;
}
inline cv::Mat
convert_ohta (const cv::Mat& src) {
BS_ASSERT (src.type () == CV_8UC3);
cv::Mat dst (src.size (), src.type ());
for (size_t i = 0; i < src.total (); ++i) {
const auto& s = src.at< cv::Vec3b > (i);
auto& d = dst.at< cv::Vec3b > (i);
d [0] = cv::saturate_cast< unsigned char > ((s [0] + s [1] + s [2]) / 3.);
d [1] = cv::saturate_cast< unsigned char > ((s [2] - s [0]) / 2.);
d [2] = cv::saturate_cast< unsigned char > ((2 * s [1] - s [2] + s [0]) / 4.);
}
return dst;
}
constexpr int COLOR_BGR2OHTA = cv::COLOR_COLORCVT_MAX + 1;
inline cv::Mat
convert_color (const cv::Mat& src, int type) {
cv::Mat dst;
if (type == COLOR_BGR2OHTA)
return convert_ohta (src);
else {
cv::cvtColor (src, dst, type);
return dst;
}
}
inline int
gray_from (int r, int g, int b) {
return double (r + g + b) / 3;
}
inline int
gray_from (const cv::Vec3b& arg) {
return gray_from (arg [0], arg [1], arg [2]);
}
inline cv::Mat
gray_from (const cv::Mat& src) {
return convert_color (src, cv::COLOR_BGR2GRAY);
}
inline cv::Mat
power_of (const cv::Mat& src, double power) {
cv::Mat dst;
return cv::pow (src, power, dst), dst;
}
inline cv::Mat
absdiff (const cv::Mat& lhs, const cv::Mat& rhs) {
cv::Mat dst;
return cv::absdiff (lhs, rhs, dst), dst;
}
inline cv::Mat
scale_frame (cv::Mat& src, size_t to = 512) {
return detail::scale_frame (src, double (to) / src.cols);
}
inline cv::Mat
resize_frame (cv::Mat& src, double factor) {
cv::Mat dst;
cv::resize (src, dst, cv::Size (), factor, factor, cv::INTER_LINEAR);
return dst;
}
inline cv::Mat
threshold (const cv::Mat& src, double threshold_ = 1., double maxval = 255.,
int type = cv::THRESH_BINARY) {
cv::Mat dst;
switch (src.type ()) {
case CV_8U:
case CV_32F:
cv::threshold (src, dst, threshold_, maxval, type);
break;
#define T(x, y) case x: \
dst = detail::threshold< y > (src, threshold_, maxval, type); \
break
T (CV_16U, unsigned short int);
T (CV_16S, short int);
T (CV_32S, int);
#undef T
default:
throw std::invalid_argument ("unsupported array type");
}
return dst;
}
struct frame_delay {
frame_delay (size_t value = 40)
: value_ (value),
begin_ (std::chrono::high_resolution_clock::now ())
{ }
bool wait_for_key (int key) const {
using namespace std::chrono;
int passed = duration_cast< milliseconds > (
high_resolution_clock::now () - begin_).count ();
int remaining = value_ - passed;
if (remaining < 1)
remaining = 1;
return key == cv::waitKey (remaining);
}
private:
int value_;
std::chrono::high_resolution_clock::time_point begin_;
};
}
#endif // BS_UTILS_HPP
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// Elly has placed several (possibly none) figurines on a
// rectangular board with several rows and columns. Now
// Kristina wants to remove all figurines from the board. In
// a single move she selects either up to R consecutive rows,
// or up to C consecutive columns and removes all remaining
// figurines that are located there. The girl wonders what is
// the minimal number of moves in which she can clear the
// entire board.
//
// The position of the figurines will be given to you in the
// vector <string> board. The j-th character of the i-th
// element of board will be '.' if the cell is empty, or 'X'
// if it contains a figurine. The maximal number of cleared
// rows in a single move will be given in the int R. The
// maximal number of cleared columns in a single move will be
// given in the int C. Return the minimal number of moves
// that is sufficient to clear the entire board.
//
// DEFINITION
// Class:EllysFigurines
// Method:getMoves
// Parameters:vector <string>, int, int
// Returns:int
// Method signature:int getMoves(vector <string> board, int
// R, int C)
//
//
// NOTES
// -In a single move the girl can only select a consecutive
// group of rows or columns to be cleared. In other words, in
// each move Kristina first decides whether she wants rows or
// columns, then she picks the index i of the first chosen
// row/column, then the number k of chosen rows/columns, and
// finally she removes all figurines from the rows/columns
// with indices i, i+1, i+2, ..., i+k-1.
//
//
// CONSTRAINTS
// -board will contain between 1 and 15 elements, inclusive.
// -Each element of board will contain between 1 and 15
// characters, inclusive.
// -All elements of board will contain the same number of
// characters.
// -Each character of board will be either '.' or 'X'.
// -R will be between 1 and 15, inclusive.
// -C will be between 1 and 15, inclusive.
//
//
// EXAMPLES
//
// 0)
// {".X.X.",
// "XX..X",
// ".XXX.",
// "...X.",
// ".X.XX"}
// 1
// 2
//
// Returns: 3
//
// In this case in a single move Elly can remove all
// figurines from a single row, all figurines from a single
// column or all figurines from two consecutive columns.
// One way to achieve the optimal answer here would be to
// remove the figurines from the first and second column in
// the first move, then the ones from the fourth and fifth
// column in the second move, and finally the remaining ones
// on the third row in the third move.
// Another solution would be to erase only columns, again
// using three moves.
//
// 1)
// {".X.X.",
// "XX..X",
// ".X.X.",
// "...X.",
// ".X.XX"}
// 2
// 2
//
// Returns: 2
//
// Almost the same as the first example, but without the
// figurine in the middle and the number of maximal rows
// removed is increased by one.
// This time, the only optimal solution is to clear the first
// two columns in one move and the last two in another move.
//
// 2)
// {"XXXXXXX"}
// 2
// 3
//
// Returns: 1
//
// The maximal allowed number of cleared rows or columns
// might be greater than the corresponding dimension of the
// board. The optimal solution for this board is to clear the
// only row in one move.
//
// 3)
// {"XXXXX",
// "X....",
// "XXX..",
// "X....",
// "XXXXX"}
// 1
// 1
//
// Returns: 4
//
// Here clearing rows 1, 3 and 5, together with column 1
// yields the best result 4.
//
// 4)
// {"XXX..XXX..XXX.",
// ".X..X....X...X",
// ".X..X....X...X",
// ".X..X....X...X",
// ".X...XXX..XXX.",
// "..............",
// "...XX...XXX...",
// "....X......X..",
// "....X....XXX..",
// "....X......X..",
// "...XXX..XXX..."}
// 1
// 2
//
// Returns: 7
//
// Good luck in TCO 13!
//
// END CUT HERE
#line 139 "EllysFigurines.cc"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
class EllysFigurines {
public:
int r,c;
VS b;
int MR, MC;
int cache[16][16][16][16];
bool isEmpty(int sr, int sc, int mr, int mc) {
f(i, sr, mr)
f(j, sc, mc)
if (b[i][j] == 'X') return false;
return true;
}
int gm(int sr, int sc, int mr, int mc) {
int &ret = cache[sr][sc][mr][mc];
if (ret != -1) return ret;
if (isEmpty(sr, sc, mr, mc)) return ret = 0;
int min = 200;
f (i, sr, mr) {
int lim = std::min(i + MR, mr);
if (!isEmpty(i, sc, lim, mc)) {
min = std::min(min, 1 + gm(sr, sc, i, mc) + gm(lim, sc, mr, mc));
}
}
f (i, sc, mc) {
int lim = std::min(i + MC, mc);
if (!isEmpty(sr, i, mr, lim)) {
min = std::min(min, 1 + gm(sr, sc, mr, i) + gm(sr, lim, mr, mc));
}
}
return ret = min;
}
int getMoves(vector <string> board, int R, int C) {
b = board;
r = b.size();
c = b[0].size();
MR = R;
MC = C;
fi (16)
fj(16)
f(k, 0, 16)
f(m, 0, 16)
cache[i][j][k][m] = -1;
return gm(0, 0, r, c);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {".X.X.",
"XX..X",
".XXX.",
"...X.",
".X.XX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 2; int Arg3 = 3; verify_case(0, Arg3, getMoves(Arg0, Arg1, Arg2)); }
void test_case_1() { string Arr0[] = {".X.X.",
"XX..X",
".X.X.",
"...X.",
".X.XX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 2; int Arg3 = 2; verify_case(1, Arg3, getMoves(Arg0, Arg1, Arg2)); }
void test_case_2() { string Arr0[] = {"XXXXXXX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; int Arg2 = 3; int Arg3 = 1; verify_case(2, Arg3, getMoves(Arg0, Arg1, Arg2)); }
void test_case_3() { string Arr0[] = {"XXXXX",
"X....",
"XXX..",
"X....",
"XXXXX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 1; int Arg3 = 4; verify_case(3, Arg3, getMoves(Arg0, Arg1, Arg2)); }
void test_case_4() { string Arr0[] = {"XXX..XXX..XXX.",
".X..X....X...X",
".X..X....X...X",
".X..X....X...X",
".X...XXX..XXX.",
"..............",
"...XX...XXX...",
"....X......X..",
"....X....XXX..",
"....X......X..",
"...XXX..XXX..."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; int Arg2 = 2; int Arg3 = 7; verify_case(4, Arg3, getMoves(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
EllysFigurines ___test;
___test.run_test(-1);
}
// END CUT HERE
|
// Created on: 2013-01-29
// Created by: Kirill GAVRILOV
// Copyright (c) 2013-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 OpenGl_Vec_HeaderFile
#define OpenGl_Vec_HeaderFile
#include <Graphic3d_Vec.hxx>
typedef Graphic3d_Vec2i OpenGl_Vec2i;
typedef Graphic3d_Vec3i OpenGl_Vec3i;
typedef Graphic3d_Vec4i OpenGl_Vec4i;
typedef Graphic3d_Vec2b OpenGl_Vec2b;
typedef Graphic3d_Vec3b OpenGl_Vec3b;
typedef Graphic3d_Vec4b OpenGl_Vec4b;
typedef Graphic3d_Vec2u OpenGl_Vec2u;
typedef Graphic3d_Vec3u OpenGl_Vec3u;
typedef Graphic3d_Vec4u OpenGl_Vec4u;
typedef Graphic3d_Vec2ub OpenGl_Vec2ub;
typedef Graphic3d_Vec3ub OpenGl_Vec3ub;
typedef Graphic3d_Vec4ub OpenGl_Vec4ub;
typedef Graphic3d_Vec2 OpenGl_Vec2;
typedef Graphic3d_Vec3 OpenGl_Vec3;
typedef Graphic3d_Vec4 OpenGl_Vec4;
typedef Graphic3d_Vec2d OpenGl_Vec2d;
typedef Graphic3d_Vec3d OpenGl_Vec3d;
typedef Graphic3d_Vec4d OpenGl_Vec4d;
typedef Graphic3d_Mat4 OpenGl_Mat4;
typedef Graphic3d_Mat4d OpenGl_Mat4d;
namespace OpenGl
{
//! Tool class for selecting appropriate vector type.
//! \tparam T Numeric data type
template<class T> struct VectorType
{
// Not implemented
};
template<> struct VectorType<Standard_Real>
{
typedef OpenGl_Vec2d Vec2;
typedef OpenGl_Vec3d Vec3;
typedef OpenGl_Vec4d Vec4;
};
template<> struct VectorType<Standard_ShortReal>
{
typedef OpenGl_Vec2 Vec2;
typedef OpenGl_Vec3 Vec3;
typedef OpenGl_Vec4 Vec4;
};
//! Tool class for selecting appropriate matrix type.
//! \tparam T Numeric data type
template<class T> struct MatrixType
{
// Not implemented
};
template<> struct MatrixType<Standard_Real>
{
typedef OpenGl_Mat4d Mat4;
};
template<> struct MatrixType<Standard_ShortReal>
{
typedef OpenGl_Mat4 Mat4;
};
}
#endif // _OpenGl_Vec_H__
|
//
// Single Number.cpp
// interview-algorithm-question-solution
//
// Created by Sun Shijie on 2018/4/26.
// Copyright © 2018年 Shijie. All rights reserved.
//
#include <stdio.h>
class Solution {
public:
int singleNumber(vector<int>& nums) {
int length = nums.size();
int result = 0 ;
for (int i=0; i<length; i++) {
result ^= nums[i];
}
return result;
}
};
|
#pragma warning(disable:4996)
#include <iostream>
#include <fstream>
#include "forbus.h"
#include "Bus.h"
using namespace std;
int main() {
int i;
while (1) {
cout << "\n1.버스 정보 기입\n2.예약\n3.정보 확인\n4.이용 가능한 버스\n5.종료\n\n";
cin >> i;
if (!cin)
IsEnteredNum(i);
else {
switch (i) {
case 1:
bus[o].Install();
break;
case 2:
bus[o].Reservate();
break;
case 3:
bus[o].ShowInform();
break;
case 4:
bus[o].Available();
break;
case 5:
cout << "\n\n*****종료합니다.*****";
exit(0);
}
}
}
return 0;
}
|
#define LED1_PIN 12
#define LED2_PIN 8
#define LED3_PIN 7
#define DELAY 50
#define LED_AMOUNT 3
const int LEDadress[] = {LED1_PIN, LED2_PIN, LED3_PIN};
int LEDnum = 0;
void setup()
{
for (int i = 0; i < LED_AMOUNT; i++)
{
pinMode(LEDadress[i], OUTPUT);
}
}
void loop()
{
digitalWrite(LEDadress[LEDnum % LED_AMOUNT], HIGH);
delay(DELAY);
digitalWrite(LEDadress[LEDnum % LED_AMOUNT], LOW);
delay(DELAY);
LEDnum++;
}
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ListNode *cur = head;
int recent;
if (head != nullptr) {
recent = head->val;
} else {
return nullptr;
}
while (cur != nullptr) {
if (cur->next != nullptr) {
while (cur->next != nullptr && cur->next->val == recent) {
ListNode *t = cur->next;
cur->next = cur->next->next;
delete t;
}
if (cur->next != nullptr)
recent = cur->next->val;
}
cur = cur->next;
}
return head;
}
};
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <boost/bind.hpp>
#include <fwCore/base.hpp>
#include <fwServices/Base.hpp>
#include <fwServices/macros.hpp>
#include <fwServices/registry/ObjectService.hpp>
#include <fwServices/IEditionService.hpp>
#include <fwComEd/PatientDBMsg.hpp>
#include <fwTools/ProgressToLogger.hpp>
#include <fwGui/dialog/PulseProgressDialog.hpp>
#include <fwGui/dialog/MessageDialog.hpp>
#include <fwGui/dialog/LocationDialog.hpp>
#include <fwGui/Cursor.hpp>
#include <fwData/PatientDB.hpp>
#include <fwData/location/Folder.hpp>
#include <io/IReader.hpp>
#include <gdcmIO/reader/DicomPatientDBReader.hpp>
#include "ioGdcm/DicomPatientDBReaderService.hpp"
namespace ioGdcm
{
REGISTER_SERVICE( ::io::IReader , ::ioGdcm::DicomPatientDBReaderService , ::fwData::PatientDB ) ;
//------------------------------------------------------------------------------
DicomPatientDBReaderService::DicomPatientDBReaderService() throw()
{}
//------------------------------------------------------------------------------
DicomPatientDBReaderService::~DicomPatientDBReaderService() throw()
{}
//------------------------------------------------------------------------------
::io::IOPathType DicomPatientDBReaderService::getIOPathType() const
{
return ::io::FOLDER;
}
//------------------------------------------------------------------------------
void DicomPatientDBReaderService::configureWithIHM()
{
static ::boost::filesystem::path _sDefaultPath;
::fwGui::dialog::LocationDialog dialogFile;
dialogFile.setTitle(this->getSelectorDialogTitle());
dialogFile.setDefaultLocation( ::fwData::location::Folder::New(_sDefaultPath) );
dialogFile.setOption(::fwGui::dialog::ILocationDialog::READ);
dialogFile.setType(::fwGui::dialog::LocationDialog::FOLDER);
::fwData::location::Folder::sptr result;
result = ::fwData::location::Folder::dynamicCast( dialogFile.show() );
if (result)
{
_sDefaultPath = result->getFolder();
this->setFolder( _sDefaultPath );
dialogFile.saveDefaultLocation( ::fwData::location::Folder::New(_sDefaultPath) );
}
else
{
this->clearLocations();
}
}
//------------------------------------------------------------------------------
void DicomPatientDBReaderService::starting() throw(::fwTools::Failed)
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void DicomPatientDBReaderService::stopping() throw(::fwTools::Failed)
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
void DicomPatientDBReaderService::info(std::ostream &_sstream )
{
_sstream << "DicomPatientDBReaderService::info" ;
}
//------------------------------------------------------------------------------
std::vector< std::string > DicomPatientDBReaderService::getSupportedExtensions()
{
std::vector< std::string > extensions ;
return extensions ;
}
//------------------------------------------------------------------------------
std::string DicomPatientDBReaderService::getSelectorDialogTitle()
{
return "Choose a directory with DICOM images";
}
//------------------------------------------------------------------------------
::fwData::PatientDB::sptr DicomPatientDBReaderService::createPatientDB( const ::boost::filesystem::path & dicomFile)
{
SLM_TRACE_FUNC();
::gdcmIO::reader::DicomPatientDBReader::NewSptr myLoader;
::fwData::PatientDB::NewSptr dummy;
myLoader->setObject( dummy );
myLoader->setFolder(dicomFile);
try
{
#ifndef __MACOSX__
// NOTE: No exception can be caught
::fwTools::ProgressToLogger progressMeterText("Loading DicomPatientDBReaderService : ");
myLoader->addHandler( progressMeterText );
::fwGui::dialog::PulseProgressDialog::Stuff stuff = ::boost::bind( &::gdcmIO::reader::DicomPatientDBReader::read, myLoader);
::fwGui::dialog::PulseProgressDialog p2("Load Dicom Image", stuff , "Operation in progress");
p2.show();
#else
myLoader->read();
#endif
}
catch (const std::exception & e)
{
std::stringstream ss;
ss << "Warning during loading : " << e.what();
::fwGui::dialog::MessageDialog::showMessageDialog(
"Warning", ss.str(), ::fwGui::dialog::IMessageDialog::WARNING);
}
catch( ... )
{
::fwGui::dialog::MessageDialog::showMessageDialog(
"Warning", "Warning during loading", ::fwGui::dialog::IMessageDialog::WARNING);
}
SLM_TRACE("exit createPatientDB()");
return myLoader->getConcreteObject();
}
//------------------------------------------------------------------------------
void DicomPatientDBReaderService::updating() throw(::fwTools::Failed)
{
SLM_TRACE_FUNC();
if( this->hasLocationDefined() )
{
::fwData::PatientDB::sptr patientDB = createPatientDB( this->getFolder() );
if( patientDB->getNumberOfPatients() > 0 )
{
// Retrieve dataStruct associated with this service
::fwData::PatientDB::sptr associatedPatientDB = this->getObject< ::fwData::PatientDB >();
SLM_ASSERT("associatedPatientDB not instanced", associatedPatientDB);
associatedPatientDB->shallowCopy( patientDB ) ;
::fwGui::Cursor cursor;
cursor.setCursor(::fwGui::ICursor::BUSY);
this->notificationOfDBUpdate();
cursor.setDefaultCursor();
}
else
{
::fwGui::dialog::MessageDialog::showMessageDialog(
"Image Reader","This file can not be read. Retry with another file reader.", ::fwGui::dialog::IMessageDialog::WARNING);
}
}
}
//------------------------------------------------------------------------------
void DicomPatientDBReaderService::notificationOfDBUpdate()
{
SLM_TRACE_FUNC();
::fwData::PatientDB::sptr pDPDB = this->getObject< ::fwData::PatientDB >() ;
SLM_ASSERT("pDPDB not instanced", pDPDB);
::fwComEd::PatientDBMsg::NewSptr msg;
msg->addEvent( ::fwComEd::PatientDBMsg::NEW_PATIENT, pDPDB );
msg->addEvent( ::fwComEd::PatientDBMsg::NEW_LOADED_PATIENT );
::fwServices::IEditionService::notify(this->getSptr(), pDPDB, msg);
}
//------------------------------------------------------------------------------
} // namespace ioGdcm
|
#include <allegro5\allegro.h>
#include <allegro5\allegro_primitives.h>
#include <allegro5\allegro_image.h>
#include <iostream>
#include "Game.h"
#include "Input.h"
#include "VariousColors.h"
#include "Camera.h"
void drawStar(float x, float y, ALLEGRO_COLOR C);
int main(int argc, char *argv[])
{
bool doLogic = false;
bool redraw = false;
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue;
ALLEGRO_TIMER *drawTimer;
ALLEGRO_TIMER *logicTimer;
ALLEGRO_DISPLAY_MODE disp_data;
ALLEGRO_BITMAP *StarBackgroundLayer1;
ALLEGRO_BITMAP *StarBackgroundLayer2;
ALLEGRO_BITMAP *StarBackgroundLayer3;
ALLEGRO_BITMAP *StarBackgroundLayer4;
ALLEGRO_BITMAP *StarBackgroundGalaxy1;
al_init();
al_install_keyboard();
al_install_mouse();
al_init_primitives_addon();
al_init_image_addon();
al_set_new_display_flags(ALLEGRO_FRAMELESS);
al_get_display_mode(al_get_num_display_modes()-1, &disp_data);
display = al_create_display(disp_data.width, disp_data.height);
event_queue = al_create_event_queue();
drawTimer = al_create_timer(1.0/60.0);
logicTimer = al_create_timer(1.0/120.0);
StarBackgroundLayer1 = al_create_bitmap(disp_data.width, disp_data.height);
StarBackgroundLayer2 = al_create_bitmap(disp_data.width, disp_data.height);
StarBackgroundLayer3 = al_create_bitmap(disp_data.width, disp_data.height);
StarBackgroundLayer4 = al_create_bitmap(disp_data.width, disp_data.height);
StarBackgroundGalaxy1 = al_create_bitmap(disp_data.width, disp_data.height);
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_register_event_source(event_queue, al_get_mouse_event_source());
al_register_event_source(event_queue, al_get_timer_event_source(drawTimer));
al_register_event_source(event_queue, al_get_timer_event_source(logicTimer));
al_start_timer(drawTimer);
al_start_timer(logicTimer);
al_set_mouse_xy(display, 500, 500);
al_hide_mouse_cursor(display);
al_set_target_bitmap(StarBackgroundLayer1);
for(int i = 0; i < 200; i++)
{
drawStar(rand() % 1920, rand() % 1080, RANDOM);
};
al_set_target_bitmap(StarBackgroundLayer2);
for(int i = 0; i < 100; i++)
{
drawStar(rand() % 1920, rand() % 1080, RANDOM);
};
al_set_target_bitmap(StarBackgroundLayer3);
for(int i = 0; i < 100; i++)
{
drawStar(rand() % 1920, rand() % 1080, RANDOM);
};
al_set_target_bitmap(StarBackgroundLayer4);
for(int i = 0; i < 100; i++)
{
drawStar(rand() % 1920, rand() % 1080, RANDOM);
};
al_set_target_bitmap(StarBackgroundGalaxy1);
for(int i = 0; i <= 1000; i += 5)
{
drawStar(400 + cos(i) * i/16, 300 + sin(i) * i/16, RANDOM);
};
for(int i = 0; i <= 1000; i += 5)
{
drawStar(800 + cos(i) * i/4, 600 + sin(i) * i/4, RANDOM);
};
al_set_target_backbuffer(display);
Camera cam;
cam.x = disp_data.width/2;
cam.y = disp_data.height/2;
while(Game::gameState == 1){
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
if(ev.type == ALLEGRO_EVENT_TIMER && ev.timer.source == drawTimer){
redraw = true;
}else if(ev.type == ALLEGRO_EVENT_TIMER && ev.timer.source == logicTimer){
doLogic = true;
}else{
Input::input(&ev);
}
if(doLogic && al_is_event_queue_empty(event_queue)){
doLogic = false;
if(Input::keys[0]) cam.y -= 5;
else if(Input::keys[1]) cam.y += 5;
else if(Input::keys[2]) cam.x -= 5;
else if(Input::keys[3]) cam.x += 5;
}
if(redraw && al_is_event_queue_empty(event_queue)){
redraw = false;
al_clear_to_color(BLACK);
al_draw_bitmap(StarBackgroundGalaxy1, 200 - cam.x/128, 200 - cam.y/128, 0);
al_draw_bitmap(StarBackgroundLayer1, 1920 - cam.x/8 + (disp_data.width * ceil((int)cam.x/8 / 1920)), 0 - cam.y/8, 0);
al_draw_bitmap(StarBackgroundLayer1, 0 - cam.x/8 + (disp_data.width * ceil((int)cam.x/8 / 1920)), 0 - cam.y/8, 0);
al_draw_bitmap(StarBackgroundLayer1, 1920 - cam.x/8 + (disp_data.width * ceil((int)cam.x/8 / 1920)), 0 - cam.y/8, 0);
al_draw_bitmap(StarBackgroundLayer1, 0 - cam.x/8, 0 - cam.y/8 + (disp_data.height * ceil((int)cam.y/8 / disp_data.height)), 0);
al_draw_bitmap(StarBackgroundLayer1, 1920 - cam.x/8, 1080 - cam.y/8 + (disp_data.height * ceil((int)cam.y/8 / disp_data.height)), 0);
al_draw_bitmap(StarBackgroundLayer2, -1920 - cam.x/4 + (disp_data.width * ceil((int)cam.x/4 / 1920)), 0 - cam.y/4, 0);
al_draw_bitmap(StarBackgroundLayer2, 0 - cam.x/4 + (disp_data.width * ceil((int)cam.x/4 / 1920)), 0 - cam.y/4, 0);
al_draw_bitmap(StarBackgroundLayer2, 1920 - cam.x/4 + (disp_data.width * ceil((int)cam.x/4 / 1920)), 0 - cam.y/4, 0);
al_draw_bitmap(StarBackgroundLayer3, -1920 - cam.x/2 + (disp_data.width * ceil((int)cam.x/2 / 1920)), 0 - cam.y/2, 0);
al_draw_bitmap(StarBackgroundLayer3, 0 - cam.x/2 + (disp_data.width * ceil((int)cam.x/2 / 1920)), 0 - cam.y/2, 0);
al_draw_bitmap(StarBackgroundLayer3, 1920 - cam.x/2 + (disp_data.width * ceil((int)cam.x/2 / 1920)), 0 - cam.y/2, 0);
al_draw_bitmap(StarBackgroundLayer4, -1920 - cam.x + (disp_data.width * ceil((int)cam.x / 1920)), 0 - cam.y, 0);
al_draw_bitmap(StarBackgroundLayer4, 0 - cam.x + (disp_data.width * ceil((int)cam.x / 1920)), 0 - cam.y, 0);
al_draw_bitmap(StarBackgroundLayer4, 1920 - cam.x + (disp_data.width * ceil((int)cam.x / 1920)), 0 - cam.y, 0);
al_flip_display();
}
}
return 0;
};
void drawFibonnaciCircle(float x, float y, int points)
{
for(int i = 0; i < points; i++)
{
al_draw_arc(x, y, 10, ALLEGRO_PI/4, ALLEGRO_PI/4, GREEN, 5);
};
};
void drawStar(float x, float y, ALLEGRO_COLOR C)
{
al_draw_pixel(x+1, y, C);
al_draw_pixel(x-1, y, C);
al_draw_pixel(x, y+1, C);
al_draw_pixel(x, y-1, C);
al_draw_pixel(x, y, C);
};
|
// Created on: 1991-05-07
// Created by: Laurent PAINNOT
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _math_Matrix_HeaderFile
#define _math_Matrix_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <math_DoubleTab.hxx>
#include <math_Vector.hxx>
#include <Standard_OStream.hxx>
// resolve name collisions with X11 headers
#ifdef Opposite
#undef Opposite
#endif
//! This class implements the real matrix abstract data type.
//! Matrixes can have an arbitrary range which must be defined
//! at the declaration and cannot be changed after this declaration
//! math_Matrix(-3,5,2,4); //a vector with range [-3..5, 2..4]
//! Matrix values may be initialized and
//! retrieved using indexes which must lie within the range
//! of definition of the matrix.
//! Matrix objects follow "value semantics", that is, they
//! cannot be shared and are copied through assignment
//! Matrices are copied through assignment:
//! @code
//! math_Matrix M2(1, 9, 1, 3);
//! ...
//! M2 = M1;
//! M1(1) = 2.0;//the matrix M2 will not be modified.
//! @endcode
//! The exception RangeError is raised when trying to access
//! outside the range of a matrix :
//! @code
//! M1(11, 1)=0.0// --> will raise RangeError.
//! @endcode
//!
//! The exception DimensionError is raised when the dimensions of
//! two matrices or vectors are not compatible.
//! @code
//! math_Matrix M3(1, 2, 1, 2);
//! M3 = M1; // will raise DimensionError
//! M1.Add(M3) // --> will raise DimensionError.
//! @endcode
//! A Matrix can be constructed with a pointer to "c array".
//! It allows to carry the bounds inside the matrix.
//! Example :
//! @code
//! Standard_Real tab1[10][20];
//! Standard_Real tab2[200];
//!
//! math_Matrix A (tab1[0][0], 1, 10, 1, 20);
//! math_Matrix B (tab2[0], 1, 10, 1, 20);
//! @endcode
class math_Matrix
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs a non-initialized matrix of range [LowerRow..UpperRow,
//! LowerCol..UpperCol]
//! For the constructed matrix:
//! - LowerRow and UpperRow are the indexes of the
//! lower and upper bounds of a row, and
//! - LowerCol and UpperCol are the indexes of the
//! lower and upper bounds of a column.
Standard_EXPORT math_Matrix(const Standard_Integer LowerRow, const Standard_Integer UpperRow, const Standard_Integer LowerCol, const Standard_Integer UpperCol);
//! constructs a non-initialized matrix of range [LowerRow..UpperRow,
//! LowerCol..UpperCol]
//! whose values are all initialized with the value InitialValue.
Standard_EXPORT math_Matrix(const Standard_Integer LowerRow, const Standard_Integer UpperRow, const Standard_Integer LowerCol, const Standard_Integer UpperCol, const Standard_Real InitialValue);
//! constructs a matrix of range [LowerRow..UpperRow,
//! LowerCol..UpperCol]
//! Sharing data with a "C array" pointed by Tab.
Standard_EXPORT math_Matrix(const Standard_Address Tab, const Standard_Integer LowerRow, const Standard_Integer UpperRow, const Standard_Integer LowerCol, const Standard_Integer UpperCol);
//! constructs a matrix for copy in initialization.
//! An exception is raised if the matrixes have not the same dimensions.
Standard_EXPORT math_Matrix(const math_Matrix& Other);
//! Initialize all the elements of a matrix to InitialValue.
Standard_EXPORT void Init (const Standard_Real InitialValue);
//! Returns the number of rows of this matrix.
//! Note that for a matrix A you always have the following relations:
//! - A.RowNumber() = A.UpperRow() - A.LowerRow() + 1
//! - A.ColNumber() = A.UpperCol() - A.LowerCol() + 1
//! - the length of a row of A is equal to the number of columns of A,
//! - the length of a column of A is equal to the number of
//! rows of A.returns the row range of a matrix.
Standard_Integer RowNumber() const;
//! Returns the number of rows of this matrix.
//! Note that for a matrix A you always have the following relations:
//! - A.RowNumber() = A.UpperRow() - A.LowerRow() + 1
//! - A.ColNumber() = A.UpperCol() - A.LowerCol() + 1
//! - the length of a row of A is equal to the number of columns of A,
//! - the length of a column of A is equal to the number of
//! rows of A.returns the row range of a matrix.
Standard_Integer ColNumber() const;
//! Returns the value of the Lower index of the row
//! range of a matrix.
Standard_Integer LowerRow() const;
//! Returns the Upper index of the row range
//! of a matrix.
Standard_Integer UpperRow() const;
//! Returns the value of the Lower index of the
//! column range of a matrix.
Standard_Integer LowerCol() const;
//! Returns the value of the upper index of the
//! column range of a matrix.
Standard_Integer UpperCol() const;
//! Computes the determinant of a matrix.
//! An exception is raised if the matrix is not a square matrix.
Standard_EXPORT Standard_Real Determinant() const;
//! Transposes a given matrix.
//! An exception is raised if the matrix is not a square matrix.
Standard_EXPORT void Transpose();
//! Inverts a matrix using Gauss algorithm.
//! Exception NotSquare is raised if the matrix is not square.
//! Exception SingularMatrix is raised if the matrix is singular.
Standard_EXPORT void Invert();
//! Sets this matrix to the product of the matrix Left, and the matrix Right.
//! Example
//! math_Matrix A (1, 3, 1, 3);
//! math_Matrix B (1, 3, 1, 3);
//! // A = ... , B = ...
//! math_Matrix C (1, 3, 1, 3);
//! C.Multiply(A, B);
//! Exceptions
//! Standard_DimensionError if matrices are of incompatible dimensions, i.e. if:
//! - the number of columns of matrix Left, or the number of
//! rows of matrix TLeft is not equal to the number of rows
//! of matrix Right, or
//! - the number of rows of matrix Left, or the number of
//! columns of matrix TLeft is not equal to the number of
//! rows of this matrix, or
//! - the number of columns of matrix Right is not equal to
//! the number of columns of this matrix.
Standard_EXPORT void Multiply (const Standard_Real Right);
void operator*= (const Standard_Real Right)
{
Multiply(Right);
}
//! multiplies all the elements of a matrix by the
//! value <Right>.
Standard_NODISCARD Standard_EXPORT math_Matrix Multiplied (const Standard_Real Right) const;
Standard_NODISCARD math_Matrix operator* (const Standard_Real Right) const
{
return Multiplied(Right);
}
//! Sets this matrix to the product of the
//! transposed matrix TLeft, and the matrix Right.
//! Example
//! math_Matrix A (1, 3, 1, 3);
//! math_Matrix B (1, 3, 1, 3);
//! // A = ... , B = ...
//! math_Matrix C (1, 3, 1, 3);
//! C.Multiply(A, B);
//! Exceptions
//! Standard_DimensionError if matrices are of incompatible dimensions, i.e. if:
//! - the number of columns of matrix Left, or the number of
//! rows of matrix TLeft is not equal to the number of rows
//! of matrix Right, or
//! - the number of rows of matrix Left, or the number of
//! columns of matrix TLeft is not equal to the number of
//! rows of this matrix, or
//! - the number of columns of matrix Right is not equal to
//! the number of columns of this matrix.
Standard_NODISCARD Standard_EXPORT math_Matrix TMultiplied (const Standard_Real Right) const;
friend math_Matrix operator *(const Standard_Real Left,const math_Matrix& Right);
//! divides all the elements of a matrix by the value <Right>.
//! An exception is raised if <Right> = 0.
Standard_EXPORT void Divide (const Standard_Real Right);
void operator/= (const Standard_Real Right)
{
Divide(Right);
}
//! divides all the elements of a matrix by the value <Right>.
//! An exception is raised if <Right> = 0.
Standard_NODISCARD Standard_EXPORT math_Matrix Divided (const Standard_Real Right) const;
Standard_NODISCARD math_Matrix operator/ (const Standard_Real Right) const
{
return Divided(Right);
}
//! adds the matrix <Right> to a matrix.
//! An exception is raised if the dimensions are different.
//! Warning
//! In order to save time when copying matrices, it is
//! preferable to use operator += or the function Add
//! whenever possible.
Standard_EXPORT void Add (const math_Matrix& Right);
void operator+= (const math_Matrix& Right)
{
Add(Right);
}
//! adds the matrix <Right> to a matrix.
//! An exception is raised if the dimensions are different.
Standard_NODISCARD Standard_EXPORT math_Matrix Added (const math_Matrix& Right) const;
Standard_NODISCARD math_Matrix operator+ (const math_Matrix& Right) const
{
return Added(Right);
}
//! sets a matrix to the addition of <Left> and <Right>.
//! An exception is raised if the dimensions are different.
Standard_EXPORT void Add (const math_Matrix& Left, const math_Matrix& Right);
//! Subtracts the matrix <Right> from <me>.
//! An exception is raised if the dimensions are different.
//! Warning
//! In order to avoid time-consuming copying of matrices, it
//! is preferable to use operator -= or the function
//! Subtract whenever possible.
Standard_EXPORT void Subtract (const math_Matrix& Right);
void operator-= (const math_Matrix& Right)
{
Subtract(Right);
}
//! Returns the result of the subtraction of <Right> from <me>.
//! An exception is raised if the dimensions are different.
Standard_NODISCARD Standard_EXPORT math_Matrix Subtracted (const math_Matrix& Right) const;
Standard_NODISCARD math_Matrix operator- (const math_Matrix& Right) const
{
return Subtracted(Right);
}
//! Sets the values of this matrix,
//! - from index I1 to index I2 on the row dimension, and
//! - from index J1 to index J2 on the column dimension,
//! to those of matrix M.
//! Exceptions
//! Standard_DimensionError if:
//! - I1 is less than the index of the lower row bound of this matrix, or
//! - I2 is greater than the index of the upper row bound of this matrix, or
//! - J1 is less than the index of the lower column bound of this matrix, or
//! - J2 is greater than the index of the upper column bound of this matrix, or
//! - I2 - I1 + 1 is not equal to the number of rows of matrix M, or
//! - J2 - J1 + 1 is not equal to the number of columns of matrix M.
Standard_EXPORT void Set (const Standard_Integer I1, const Standard_Integer I2, const Standard_Integer J1, const Standard_Integer J2, const math_Matrix& M);
//! Sets the row of index Row of a matrix to the vector <V>.
//! An exception is raised if the dimensions are different.
//! An exception is raises if <Row> is inferior to the lower
//! row of the matrix or <Row> is superior to the upper row.
Standard_EXPORT void SetRow (const Standard_Integer Row, const math_Vector& V);
//! Sets the column of index Col of a matrix to the vector <V>.
//! An exception is raised if the dimensions are different.
//! An exception is raises if <Col> is inferior to the lower
//! column of the matrix or <Col> is superior to the upper
//! column.
Standard_EXPORT void SetCol (const Standard_Integer Col, const math_Vector& V);
//! Sets the diagonal of a matrix to the value <Value>.
//! An exception is raised if the matrix is not square.
Standard_EXPORT void SetDiag (const Standard_Real Value);
//! Returns the row of index Row of a matrix.
Standard_EXPORT math_Vector Row (const Standard_Integer Row) const;
//! Returns the column of index <Col> of a matrix.
Standard_EXPORT math_Vector Col (const Standard_Integer Col) const;
//! Swaps the rows of index Row1 and Row2.
//! An exception is raised if <Row1> or <Row2> is out of range.
Standard_EXPORT void SwapRow (const Standard_Integer Row1, const Standard_Integer Row2);
//! Swaps the columns of index <Col1> and <Col2>.
//! An exception is raised if <Col1> or <Col2> is out of range.
Standard_EXPORT void SwapCol (const Standard_Integer Col1, const Standard_Integer Col2);
//! Teturns the transposed of a matrix.
//! An exception is raised if the matrix is not a square matrix.
Standard_NODISCARD Standard_EXPORT math_Matrix Transposed() const;
//! Returns the inverse of a matrix.
//! Exception NotSquare is raised if the matrix is not square.
//! Exception SingularMatrix is raised if the matrix is singular.
Standard_EXPORT math_Matrix Inverse() const;
//! Returns the product of the transpose of a matrix with
//! the matrix <Right>.
//! An exception is raised if the dimensions are different.
Standard_EXPORT math_Matrix TMultiply (const math_Matrix& Right) const;
//! Computes a matrix as the product of 2 vectors.
//! An exception is raised if the dimensions are different.
//! <me> = <Left> * <Right>.
Standard_EXPORT void Multiply (const math_Vector& Left, const math_Vector& Right);
//! Computes a matrix as the product of 2 matrixes.
//! An exception is raised if the dimensions are different.
Standard_EXPORT void Multiply (const math_Matrix& Left, const math_Matrix& Right);
//! Computes a matrix to the product of the transpose of
//! the matrix <TLeft> with the matrix <Right>.
//! An exception is raised if the dimensions are different.
Standard_EXPORT void TMultiply (const math_Matrix& TLeft, const math_Matrix& Right);
//! Sets a matrix to the Subtraction of the matrix <Right>
//! from the matrix <Left>.
//! An exception is raised if the dimensions are different.
Standard_EXPORT void Subtract (const math_Matrix& Left, const math_Matrix& Right);
//! Accesses (in read or write mode) the value of index <Row>
//! and <Col> of a matrix.
//! An exception is raised if <Row> and <Col> are not
//! in the correct range.
Standard_Real& Value (const Standard_Integer Row, const Standard_Integer Col) const;
Standard_Real& operator() (const Standard_Integer Row, const Standard_Integer Col) const
{
return Value(Row,Col);
}
//! Matrixes are copied through assignment.
//! An exception is raised if the dimensions are different.
Standard_EXPORT math_Matrix& Initialized (const math_Matrix& Other);
math_Matrix& operator= (const math_Matrix& Other)
{
return Initialized(Other);
}
//! Returns the product of 2 matrices.
//! An exception is raised if the dimensions are different.
Standard_EXPORT void Multiply (const math_Matrix& Right);
void operator*= (const math_Matrix& Right)
{
Multiply(Right);
}
//! Returns the product of 2 matrices.
//! An exception is raised if the dimensions are different.
Standard_NODISCARD Standard_EXPORT math_Matrix Multiplied (const math_Matrix& Right) const;
Standard_NODISCARD math_Matrix operator* (const math_Matrix& Right) const
{
return Multiplied(Right);
}
//! Returns the product of a matrix by a vector.
//! An exception is raised if the dimensions are different.
Standard_NODISCARD Standard_EXPORT math_Vector Multiplied (const math_Vector& Right) const;
Standard_NODISCARD math_Vector operator* (const math_Vector& Right) const
{
return Multiplied(Right);
}
//! Returns the opposite of a matrix.
//! An exception is raised if the dimensions are different.
Standard_EXPORT math_Matrix Opposite();
math_Matrix operator-()
{
return Opposite();
}
//! Prints information on the current state of the object.
//! Is used to redefine the operator <<.
Standard_EXPORT void Dump (Standard_OStream& o) const;
friend class math_Vector;
protected:
//! The new lower row of the matrix is set to <LowerRow>
Standard_EXPORT void SetLowerRow (const Standard_Integer LowerRow);
//! The new lower column of the matrix is set to the column
//! of range <LowerCol>.
Standard_EXPORT void SetLowerCol (const Standard_Integer LowerCol);
//! The new lower row of the matrix is set to <LowerRow>
//! and the new lower column of the matrix is set to the column
//! of range <LowerCol>.
void SetLower (const Standard_Integer LowerRow, const Standard_Integer LowerCol);
private:
Standard_Integer LowerRowIndex;
Standard_Integer UpperRowIndex;
Standard_Integer LowerColIndex;
Standard_Integer UpperColIndex;
math_DoubleTab Array;
};
#include <math_Matrix.lxx>
#endif // _math_Matrix_HeaderFile
|
#include "Control.h"
using namespace Control;
Controler::Controler(){
}
Controler::Controler(ET_Connection::Connector* connector) : connector(connector){
}
Controler::~Controler(){
}
void Controler::async_remote_control(void){
}
void Controler::Control(){
bool forward_key_pressed = keyboard.getKeyState(movement_forward_key);
bool backward_key_pressed = keyboard.getKeyState(movement_backward_key);
bool left_key_pressed = keyboard.getKeyState(movement_left_key);
bool right_key_pressed = keyboard.getKeyState(movement_right_key);
/* shift values bitwise to use them as one variable
* order of shift
* b0 - forward
* b1 - backward
* b2 - left
* b3 - right
*/
short keys = forward_key_pressed |
(backward_key_pressed << 1) |
(left_key_pressed << 2) |
(right_key_pressed << 3);
movement_control controls;
calculate_movement_control(&controls, keys);
send_robot_movement_frame(controls);
}
void Controler::calculate_movement_control(movement_control* controls, short keys){
switch (keys) {
case movement_forward:
controls->left = 100;
controls->right = 100;
break;
case movement_backward:
controls->left = -100;
controls->right = -100;
break;
case movement_left:
controls->left = -100;
controls->right = 100;
break;
case movement_right:
controls->left = 100;
controls->right = -100;
break;
case movement_left_forward:
controls->left = 20;
controls->right = 100;
break;
case movement_right_forward:
controls->left = 100;
controls->right = 20;
break;
case movement_left_backward:
controls->left = -20;
controls->right = -100;
break;
case movement_right_backward:
controls->left = -100;
controls->right = -20;
break;
case movement_stop:
controls->left = 0;
controls->right = 0;
break;
default:
controls->left = 0;
controls->right = 0;
break;
}
}
void Controler::send_robot_movement_frame(movement_control controls){
ET_Connection::frame control_frame;
control_frame.data[0] = ET_Connection::control_frame_character;
control_frame.data[1] = 'W'/*controls.left*/;
control_frame.data[2] = 'W'/*controls.right*/;
control_frame.size = movement_frame_size;
connector->send_data(control_frame);
}
|
// Copyright (c) 2021 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 _RWMesh_TriangulationSource_HeaderFile
#define _RWMesh_TriangulationSource_HeaderFile
#include <Poly_Triangulation.hxx>
class RWMesh_TriangulationReader;
//! Mesh data wrapper for delayed triangulation loading.
//! Class inherits Poly_Triangulation so that it can be put temporarily into TopoDS_Face within assembly structure.
class RWMesh_TriangulationSource : public Poly_Triangulation
{
DEFINE_STANDARD_RTTIEXT(RWMesh_TriangulationSource, Poly_Triangulation)
public:
//! Constructor.
Standard_EXPORT RWMesh_TriangulationSource();
//! Destructor.
Standard_EXPORT virtual ~RWMesh_TriangulationSource();
//! Returns reader allowing to read data from the buffer.
const Handle(RWMesh_TriangulationReader)& Reader() const { return myReader; }
//! Sets reader allowing to read data from the buffer.
void SetReader (const Handle(RWMesh_TriangulationReader)& theReader) { myReader = theReader; }
//! Returns number of degenerated triangles collected during data reading.
//! Used for debug statistic purpose.
Standard_Integer DegeneratedTriNb() const { return myStatisticOfDegeneratedTriNb; }
//! Gets access to number of degenerated triangles to collect them during data reading.
Standard_Integer& ChangeDegeneratedTriNb() { return myStatisticOfDegeneratedTriNb; }
public: //! @name late-load deferred data interface
//! Returns number of nodes for deferred loading.
//! Note: this is estimated values defined in object header, which might be different from actually loaded values
//! (due to broken header or extra mesh processing).
//! Always check triangulation size of actually loaded data in code to avoid out-of-range issues.
virtual Standard_Integer NbDeferredNodes() const Standard_OVERRIDE { return myNbDefNodes; }
//! Sets number of nodes for deferred loading.
void SetNbDeferredNodes (const Standard_Integer theNbNodes) { myNbDefNodes = theNbNodes; }
//! Returns number of triangles for deferred loading.
//! Note: this is estimated values defined in object header, which might be different from actually loaded values
//! (due to broken header or extra mesh processing).
//! Always check triangulation size of actually loaded data in code to avoid out-of-range issues.
virtual Standard_Integer NbDeferredTriangles() const Standard_OVERRIDE { return myNbDefTriangles; }
//! Sets number of triangles for deferred loading.
void SetNbDeferredTriangles (const Standard_Integer theNbTris) { myNbDefTriangles = theNbTris; }
protected:
//! Loads triangulation data from deferred storage using specified shared input file system.
Standard_EXPORT virtual Standard_Boolean loadDeferredData (const Handle(OSD_FileSystem)& theFileSystem,
const Handle(Poly_Triangulation)& theDestTriangulation) const Standard_OVERRIDE;
protected:
Handle(RWMesh_TriangulationReader) myReader;
Standard_Integer myNbDefNodes;
Standard_Integer myNbDefTriangles;
mutable Standard_Integer myStatisticOfDegeneratedTriNb;
};
#endif // _RWMesh_TriangulationSource_HeaderFile
|
/*
Copyright (c) 2021-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#include "TestMacrosFormatter.hpp"
namespace Ishiko
{
bool Internal::UniversalFormatter<char*>::Format(const char* value, std::string& output)
{
output = value;
return true;
}
bool Internal::UniversalFormatter<std::string>::Format(const std::string& value, std::string& output)
{
output = value;
return true;
}
bool Internal::UniversalFormatter<bool>::Format(bool value, std::string& output)
{
if (value)
{
output = "true";
}
else
{
output = "false";
}
return true;
}
}
|
/*
* Реализация паттерна "Посетитель" для построения таблицы символов программы
*/
#pragma once
#include "Visitor.h"
#include "Table.h"
class CSymbolTableBuilder : public IVisitor
{
public:
CSymbolTableBuilder() : isCorrect( true ), currentClass( NULL ), currentMethod( NULL ) { };
bool IsTableCorrect() const { return isCorrect; };
CSymbolsTable::CTable* GetConstructedTable() { return &table; };
void Visit( const CProgram* node );
void Visit( const CMainClassDeclaration* node );
void Visit( const CClassDeclaration* node );
void Visit( const CClassExtendsDeclaration* node );
void Visit( const CClassDeclarationList* node );
void Visit( const CVariableDeclaration* node );
void Visit( const CVariableDeclarationList* node );
void Visit( const CMethodDeclaration* node );
void Visit( const CMethodDeclarationList* node );
void Visit( const CFormalList* node );
void Visit( const CFormalRestList* node );
void Visit( const CBuiltInType* node );
void Visit( const CUserType* node );
void Visit( const CStatementList* node );
void Visit( const CStatementBlock* node );
void Visit( const CIfStatement* node );
void Visit( const CWhileStatement* node );
void Visit( const CPrintStatement* node );
void Visit( const CAssignmentStatement* node );
void Visit( const CArrayElementAssignmentStatement* node );
void Visit( const CBinaryOperatorExpression* node );
void Visit( const CIndexAccessExpression* node );
void Visit( const CLengthExpression* node );
void Visit( const CMethodCallExpression* node );
void Visit( const CIntegerOrBooleanExpression* node );
void Visit( const CIdentifierExpression* node );
void Visit( const CThisExpression* node );
void Visit( const CNewIntegerArrayExpression* node );
void Visit( const CNewObjectExpression* node );
void Visit( const CNegationExpression* node );
void Visit( const CParenthesesExpression* node );
void Visit( const CExpressionList* node );
private:
bool isCorrect; // Флаг, означающий, что таблица символов у нас построена верно
CSymbolsTable::CClassInformation* currentClass; // Текущий класс, в котором находится посетитель
CSymbolsTable::CMethodInformation* currentMethod; // Текущий метод
std::string lastTypeValue; // Переменная состояния
CSymbolsTable::CTable table; // таблица, которую мы строим
};
|
#include "debug.h"
Debug::Debug(){
}
Debug::~Debug(){
}
void Debug::message(std::string msg, termColor color) {
switch (color) {
case 0 : //grey
std::cout << termcolor::grey << msg << std::endl;
std::cout << termcolor::reset;
break;
case 1: //red
std::cout << termcolor::red << msg << std::endl;
std::cout << termcolor::reset;
break;
case 2: //green
std::cout << termcolor::green << msg << std::endl;
std::cout << termcolor::reset;
break;
case 3: //yellow
std::cout << termcolor::yellow<< msg << std::endl;
std::cout << termcolor::reset;
break;
case 4: //blue
std::cout << termcolor::blue << msg << std::endl;
std::cout << termcolor::reset;
break;
case 5: //magenta
std::cout << termcolor::magenta << msg << std::endl;
std::cout << termcolor::reset;
break;
case 6: //cyan
std::cout << termcolor::cyan << msg << std::endl;
std::cout << termcolor::reset;
break;
case 7: //white
std::cout << termcolor::white << msg << std::endl;
std::cout << termcolor::reset;
break;
}
}
|
// Created on: 1997-11-17
// 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 _CDF_MetaDataDriver_HeaderFile
#define _CDF_MetaDataDriver_HeaderFile
#include <Standard_Type.hxx>
class CDM_MetaData;
class TCollection_ExtendedString;
class CDM_Document;
class PCDM_ReferenceIterator;
class Message_Messenger;
class CDF_MetaDataDriver;
DEFINE_STANDARD_HANDLE(CDF_MetaDataDriver, Standard_Transient)
//! this class list the method that must be available for
//! a specific DBMS
class CDF_MetaDataDriver : public Standard_Transient
{
public:
//! returns true if the MetaDataDriver can manage different
//! versions of a Data.
//! By default, returns Standard_False.
Standard_EXPORT virtual Standard_Boolean HasVersionCapability();
//! Creates a "Depends On" relation between two Datas.
//! By default does nothing
Standard_EXPORT virtual void CreateDependsOn (const Handle(CDM_MetaData)& aFirstData, const Handle(CDM_MetaData)& aSecondData);
Standard_EXPORT virtual void CreateReference (const Handle(CDM_MetaData)& aFrom, const Handle(CDM_MetaData)& aTo, const Standard_Integer aReferenceIdentifier, const Standard_Integer aToDocumentVersion);
//! by default return Standard_True.
Standard_EXPORT virtual Standard_Boolean HasVersion (const TCollection_ExtendedString& aFolder, const TCollection_ExtendedString& aName);
Standard_EXPORT virtual TCollection_ExtendedString BuildFileName (const Handle(CDM_Document)& aDocument) = 0;
//! this method is useful if the name of an object --
//! depends on the metadatadriver. For example a Driver
//! -- based on the operating system can choose to add
//! the extension of file to create to the object.
Standard_EXPORT virtual TCollection_ExtendedString SetName (const Handle(CDM_Document)& aDocument, const TCollection_ExtendedString& aName);
//! should indicate whether meta-data exist in the DBMS corresponding
//! to the Data.
//! aVersion may be NULL;
Standard_EXPORT virtual Standard_Boolean Find (const TCollection_ExtendedString& aFolder, const TCollection_ExtendedString& aName, const TCollection_ExtendedString& aVersion) = 0;
Standard_EXPORT virtual Standard_Boolean HasReadPermission (const TCollection_ExtendedString& aFolder, const TCollection_ExtendedString& aName, const TCollection_ExtendedString& aVersion) = 0;
//! should return the MetaData stored in the DBMS with the meta-data
//! corresponding to the Data. If the MetaDataDriver has version management capabilities
//! the version has to be set in the returned MetaData.
//! aVersion may be NULL
//! MetaData is called by GetMetaData
//! If the version is set to NULL, MetaData should return
//! the last version of the metadata
Standard_EXPORT virtual Handle(CDM_MetaData) MetaData (const TCollection_ExtendedString& aFolder, const TCollection_ExtendedString& aName, const TCollection_ExtendedString& aVersion) = 0;
//! by default returns aMetaDATA
//! should return the MetaData stored in the DBMS with the meta-data
//! corresponding to the path. If the MetaDataDriver has version management capabilities
//! the version has to be set in the returned MetaData.
//! MetaData is called by GetMetaData
//! If the version is not included in the path , MetaData should return
//! the last version of the metadata
//! is deferred;
Standard_EXPORT virtual Handle(CDM_MetaData) LastVersion (const Handle(CDM_MetaData)& aMetaData);
//! should create meta-data corresponding to aData and maintaining a meta-link
//! between these meta-data and aFileName
//! CreateMetaData is called by CreateData
//! If the metadata-driver
//! has version capabilities, version must be set in the returned Data.
Standard_EXPORT virtual Handle(CDM_MetaData) CreateMetaData (const Handle(CDM_Document)& aDocument, const TCollection_ExtendedString& aFileName) = 0;
Standard_EXPORT virtual Standard_Boolean FindFolder (const TCollection_ExtendedString& aFolder) = 0;
Standard_EXPORT virtual TCollection_ExtendedString DefaultFolder() = 0;
Standard_EXPORT virtual Handle(PCDM_ReferenceIterator) ReferenceIterator(const Handle(Message_Messenger)& theMessageDriver);
//! calls Find with an empty version
Standard_EXPORT Standard_Boolean Find (const TCollection_ExtendedString& aFolder, const TCollection_ExtendedString& aName);
//! calls MetaData with an empty version
Standard_EXPORT Handle(CDM_MetaData) MetaData (const TCollection_ExtendedString& aFolder, const TCollection_ExtendedString& aName);
DEFINE_STANDARD_RTTIEXT(CDF_MetaDataDriver,Standard_Transient)
protected:
Standard_EXPORT CDF_MetaDataDriver();
private:
};
#endif // _CDF_MetaDataDriver_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Manuela Hutter (manuelah)
*/
#include "core/pch.h"
#include "adjunct/quick_toolkit/creators/QuickWidgetCreator.h"
#include "adjunct/quick_toolkit/creators/QuickGridRowCreator.h"
#include "adjunct/quick_toolkit/readers/UIReader.h"
#include "adjunct/quick_toolkit/widgets/WidgetTypeMapping.h"
#include "adjunct/ui_parser/ParserIterators.h"
#include "adjunct/m2_ui/widgets/RichTextEditor.h"
#include "adjunct/quick/widgets/DesktopFileChooserEdit.h"
#include "adjunct/quick/widgets/OpHotlistView.h"
#include "adjunct/quick_toolkit/widgets/DesktopToggleButton.h"
#include "adjunct/quick_toolkit/widgets/NullWidget.h"
#include "adjunct/quick_toolkit/widgets/QuickAddressDropDown.h"
#include "adjunct/quick_toolkit/widgets/QuickButtonStrip.h"
#include "adjunct/quick_toolkit/widgets/QuickBrowserView.h"
#include "adjunct/quick_toolkit/widgets/QuickButton.h"
#include "adjunct/quick_toolkit/widgets/QuickCheckBox.h"
#include "adjunct/quick_toolkit/widgets/QuickComposeEdit.h"
#include "adjunct/quick_toolkit/widgets/QuickComposite.h"
#include "adjunct/quick_toolkit/widgets/QuickDropDown.h"
#include "adjunct/quick_toolkit/widgets/QuickEdit.h"
#include "adjunct/quick_toolkit/widgets/QuickExpand.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/QuickDynamicGrid.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/QuickStackLayout.h"
#include "adjunct/quick_toolkit/widgets/QuickPagingLayout.h"
#include "adjunct/quick_toolkit/widgets/QuickGroupBox.h"
#include "adjunct/quick_toolkit/widgets/QuickIcon.h"
#include "adjunct/quick_toolkit/widgets/QuickLabel.h"
#include "adjunct/quick_toolkit/widgets/QuickMultilineEdit.h"
#include "adjunct/quick_toolkit/widgets/QuickMultilineLabel.h"
#include "adjunct/quick_toolkit/widgets/QuickNumberEdit.h"
#include "adjunct/quick_toolkit/widgets/QuickOpWidgetWrapper.h"
#include "adjunct/quick_toolkit/widgets/QuickPagingLayout.h"
#include "adjunct/quick_toolkit/widgets/QuickRadioButton.h"
#include "adjunct/quick_toolkit/widgets/QuickRichTextLabel.h"
#include "adjunct/quick_toolkit/widgets/QuickSearchEdit.h"
#include "adjunct/quick_toolkit/widgets/QuickSeparator.h"
#include "adjunct/quick_toolkit/widgets/QuickScrollContainer.h"
#include "adjunct/quick_toolkit/widgets/QuickSkinElement.h"
#include "adjunct/quick_toolkit/widgets/QuickTabs.h"
#include "adjunct/quick_toolkit/widgets/QuickTreeView.h"
#include "adjunct/quick_toolkit/widgets/QuickFlowLayout.h"
#include "adjunct/quick_toolkit/widgets/QuickGrid/QuickCentered.h"
#include "adjunct/quick_toolkit/widgets/QuickWidget.h"
#include "adjunct/quick_toolkit/widgets/QuickWrapLayout.h"
#include "adjunct/desktop_util/adt/typedobjectcollection.h"
#include "adjunct/quick/widgets/OpAddressDropDown.h"
#include "adjunct/quick/widgets/OpBookmarkView.h"
#include "adjunct/quick/widgets/OpComposeEdit.h"
#include "adjunct/quick/widgets/OpFindTextBar.h"
#include "adjunct/quick/widgets/OpStatusField.h"
#include "adjunct/quick/widgets/OpHistoryView.h"
#include "adjunct/quick/widgets/OpLinksView.h"
#include "adjunct/quick/widgets/OpPersonalbar.h"
#include "adjunct/quick/widgets/OpProgressField.h"
#include "adjunct/quick/widgets/OpSearchDropDown.h"
#include "adjunct/quick/widgets/OpSearchEdit.h"
#include "adjunct/quick/widgets/OpTrustAndSecurityButton.h"
#include "adjunct/quick/widgets/OpZoomDropDown.h"
#include "adjunct/quick_toolkit/widgets/OpExpand.h"
#include "adjunct/quick_toolkit/widgets/OpHelptooltip.h"
#include "adjunct/quick_toolkit/widgets/OpIcon.h"
#include "adjunct/quick_toolkit/widgets/OpImageWidget.h"
#include "adjunct/quick_toolkit/widgets/OpProgressbar.h"
#include "adjunct/quick_toolkit/widgets/OpQuickFind.h"
#include "adjunct/quick_toolkit/widgets/OpSeparator.h"
#include "adjunct/quick_toolkit/widgets/OpTabs.h"
#include "adjunct/quick_toolkit/widgets/OpWorkspace.h"
#include "adjunct/desktop_scope/src/scope_desktop_window_manager.h"
#include "modules/widgets/OpEdit.h"
#include "modules/widgets/OpMultiEdit.h"
#include "modules/widgets/OpNumberEdit.h"
#include "modules/widgets/OpSlider.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/scope/src/scope_manager.h"
OP_STATUS
QuickWidgetStateCreator::CreateWidgetStateAttributes(OpString & text, OpAutoPtr<OpInputAction>& action, OpString8 & widget_image, INT32& data)
{
RETURN_IF_ERROR(GetLog().Evaluate(GetTranslatedScalarStringFromMap("string", text), "ERROR retrieving parameter 'string'"));
if (text.IsEmpty())
GetLog().OutputEntry("WARNING: widget needs to specify the 'string' parameter");
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarStringFromMap("skin-image", widget_image), "ERROR retrieving parameter 'skin-image'"));
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarIntFromMap("data", data), "ERROR retrieving parameter 'data'"));
// This one should be last
RETURN_IF_ERROR(GetLog().Evaluate(CreateInputActionFromMap(action), "ERROR creating input action for widget"));
return OpStatus::OK;
}
////////// QuickWidgetCreator
QuickWidgetCreator::QuickWidgetCreator(TypedObjectCollection& widgets, ParserLogger& log, bool dialog_reader)
: QuickUICreator(log)
, m_widgets(&widgets)
, m_has_quick_window(dialog_reader)
{
}
////////// QuickWidgetCreator
QuickWidgetCreator::~QuickWidgetCreator()
{}
////////// CreateWidget
OP_STATUS
QuickWidgetCreator::CreateWidget(OpAutoPtr<QuickWidget>& widget)
{
QuickWidget* created = 0;
OP_STATUS status = ConstructInitializedWidgetForType(created);
widget.reset(created);
return status;
}
////////// ConstructInitializedWidgetForType
OP_STATUS
QuickWidgetCreator::ConstructInitializedWidgetForType(QuickWidget *& widget)
{
OpString8 widget_type_str;
RETURN_IF_ERROR(GetScalarStringFromMap("type", widget_type_str));
if (widget_type_str.IsEmpty())
{
GetLog().OutputEntry("ERROR: widget doesn't have the 'type' attribute specified");
return OpStatus::ERR;
}
OpString8 widget_name;
if (GetLog().IsLogging())
{
RETURN_IF_ERROR(GetScalarStringFromMap("name", widget_name));
if (widget_name.IsEmpty())
RETURN_IF_ERROR(widget_name.Set(widget_type_str));
}
ParserLogger::AutoIndenter indenter(GetLog(), "Reading '%s'", widget_name);
OpTypedObject::Type widget_type = WidgetTypeMapping::FromString(widget_type_str);
switch (widget_type)
{
case OpTypedObject::WIDGET_TYPE_STACK_LAYOUT: RETURN_IF_ERROR(ConstructStackLayout(widget)); break;
case OpTypedObject::WIDGET_TYPE_GRID_LAYOUT: RETURN_IF_ERROR(ConstructInitWidget<QuickGrid>(widget)); break;
case OpTypedObject::WIDGET_TYPE_DYNAMIC_GRID_LAYOUT: RETURN_IF_ERROR(ConstructInitWidget<QuickDynamicGrid>(widget, NeedsTestSupport() ? QuickDynamicGrid::FORCE_TESTABLE : QuickDynamicGrid::NORMAL)); break;
case OpTypedObject::WIDGET_TYPE_PAGING_LAYOUT: RETURN_IF_ERROR(ConstructInitWidget<QuickPagingLayout>(widget)); break;
case OpTypedObject::WIDGET_TYPE_BUTTON: RETURN_IF_ERROR(ConstructInitWidget<QuickButton>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SLIDER: RETURN_IF_ERROR(ConstructInitWidget<QuickSlider>(widget)); break;
case OpTypedObject::WIDGET_TYPE_ZOOM_SLIDER: RETURN_IF_ERROR(ConstructInitWidget<QuickZoomSlider>(widget)); break;
case OpTypedObject::WIDGET_TYPE_ZOOM_MENU_BUTTON: RETURN_IF_ERROR(ConstructInitWidget<QuickZoomMenuButton>(widget)); break;
case OpTypedObject::WIDGET_TYPE_RADIOBUTTON: RETURN_IF_ERROR(ConstructInitWidget<QuickRadioButton>(widget)); break;
case OpTypedObject::WIDGET_TYPE_CHECKBOX: RETURN_IF_ERROR(ConstructInitWidget<QuickCheckBox>(widget)); break;
case OpTypedObject::WIDGET_TYPE_LISTBOX: RETURN_IF_ERROR(ConstructInitWidget<QuickListBox>(widget)); break;
case OpTypedObject::WIDGET_TYPE_TREEVIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickTreeView>(widget)); break;
case OpTypedObject::WIDGET_TYPE_DROPDOWN: RETURN_IF_ERROR(ConstructInitWidget<QuickDropDown>(widget)); break;
case OpTypedObject::WIDGET_TYPE_EDIT: RETURN_IF_ERROR(ConstructInitWidget<QuickEdit>(widget)); break;
case OpTypedObject::WIDGET_TYPE_MULTILINE_EDIT: RETURN_IF_ERROR(ConstructInitWidget<QuickMultilineEdit>(widget)); break;
case OpTypedObject::WIDGET_TYPE_COMPOSE_EDIT: RETURN_IF_ERROR(ConstructInitWidget<QuickComposeEdit>(widget)); break;
case OpTypedObject::WIDGET_TYPE_TRUST_AND_SECURITY_BUTTON: RETURN_IF_ERROR(ConstructInitWidget<QuickTrustAndSecurityButton>(widget)); break;
case OpTypedObject::WIDGET_TYPE_DESKTOP_LABEL: RETURN_IF_ERROR(ConstructInitWidget<QuickLabel>(widget)); break;
case OpTypedObject::WIDGET_TYPE_WEBIMAGE: RETURN_IF_ERROR(ConstructInitWidget<QuickWebImageWidget>(widget)); break;
case OpTypedObject::WIDGET_TYPE_FILECHOOSER_EDIT: RETURN_IF_ERROR(ConstructInitWidget<QuickDesktopFileChooserEdit>(widget)); break;
case OpTypedObject::WIDGET_TYPE_FOLDERCHOOSER_EDIT: RETURN_IF_ERROR(ConstructInitWidget<QuickDesktopFileChooserEdit>(widget)); widget->GetTypedObject<QuickDesktopFileChooserEdit>()->GetOpWidget()->SetSelectorMode(DesktopFileChooserEdit::FolderSelector); break;
case OpTypedObject::WIDGET_TYPE_TOOLBAR: RETURN_IF_ERROR(ConstructInitWidget<QuickToolbar>(widget)); break;
case OpTypedObject::WIDGET_TYPE_FINDTEXTBAR: RETURN_IF_ERROR(ConstructInitWidget<QuickFindTextBar>(widget)); break;
case OpTypedObject::WIDGET_TYPE_BUTTON_STRIP: RETURN_IF_ERROR(ConstructInitWidget<QuickButtonStrip>(widget)); break;
case OpTypedObject::WIDGET_TYPE_GROUP: RETURN_IF_ERROR(ConstructInitWidget<QuickGroup>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SPLITTER: RETURN_IF_ERROR(ConstructInitWidget<QuickSplitter>(widget)); break;
case OpTypedObject::WIDGET_TYPE_BROWSERVIEW:
{
if (m_has_quick_window)
RETURN_IF_ERROR(ConstructInitWidget<QuickDialogBrowserView>(widget));
else
RETURN_IF_ERROR(ConstructInitWidget<QuickOpBrowserView>(widget));
break;
}
case OpTypedObject::WIDGET_TYPE_PROGRESSBAR: RETURN_IF_ERROR(ConstructInitWidget<QuickProgressBar>(widget)); break;
case OpTypedObject::WIDGET_TYPE_PERSONALBAR: RETURN_IF_ERROR(ConstructInitWidget<QuickPersonalbar>(widget)); break;
case OpTypedObject::WIDGET_TYPE_STATUS_FIELD: RETURN_IF_ERROR(ConstructInitWidget<QuickStatusField>(widget)); break;
case OpTypedObject::WIDGET_TYPE_ICON: RETURN_IF_ERROR(ConstructInitWidget<QuickIcon>(widget)); break;
case OpTypedObject::WIDGET_TYPE_EXPAND: RETURN_IF_ERROR(ConstructInitWidget<QuickExpand>(widget)); break;
case OpTypedObject::WIDGET_TYPE_PROGRESS_FIELD: RETURN_IF_ERROR(ConstructInitWidget<QuickProgressField>(widget)); break;
case OpTypedObject::WIDGET_TYPE_ADDRESS_DROPDOWN: RETURN_IF_ERROR(ConstructInitWidget<QuickAddressDropDown>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SEARCH_DROPDOWN: RETURN_IF_ERROR(ConstructInitWidget<QuickSearchDropDown>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SEARCH_EDIT: RETURN_IF_ERROR(ConstructInitWidget<QuickSearchEdit>(widget)); break;
case OpTypedObject::WIDGET_TYPE_ZOOM_DROPDOWN: RETURN_IF_ERROR(ConstructInitWidget<QuickZoomDropDown>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SCROLLBAR: RETURN_IF_ERROR(ConstructInitWidget<QuickScrollbar>(widget)); break;
case OpTypedObject::WIDGET_TYPE_QUICK_FIND: RETURN_IF_ERROR(ConstructInitWidget<QuickQuickFind>(widget)); break;
case OpTypedObject::WIDGET_TYPE_HISTORY_VIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickHistoryView>(widget)); break;
case OpTypedObject::WIDGET_TYPE_BOOKMARKS_VIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickBookmarkView>(widget)); break;
case OpTypedObject::WIDGET_TYPE_GADGETS_VIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickHotlistView>(widget, OpTypedObject::WIDGET_TYPE_GADGETS_VIEW)); break;
#ifdef WEBSERVER_SUPPORT
case OpTypedObject::WIDGET_TYPE_UNITE_SERVICES_VIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickHotlistView>(widget, OpTypedObject::WIDGET_TYPE_UNITE_SERVICES_VIEW)); break;
#endif
case OpTypedObject::WIDGET_TYPE_CONTACTS_VIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickHotlistView>(widget, OpTypedObject::WIDGET_TYPE_CONTACTS_VIEW)); break;
case OpTypedObject::WIDGET_TYPE_NOTES_VIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickHotlistView>(widget, OpTypedObject::WIDGET_TYPE_NOTES_VIEW)); break;
case OpTypedObject::WIDGET_TYPE_LINKS_VIEW: RETURN_IF_ERROR(ConstructInitWidget<QuickLinksView>(widget)); break;
case OpTypedObject::WIDGET_TYPE_NUMBER_EDIT: RETURN_IF_ERROR(ConstructInitWidget<QuickNumberEdit>(widget)); break;
case OpTypedObject::WIDGET_TYPE_MULTILINE_LABEL: RETURN_IF_ERROR(ConstructInitWidget<QuickMultilineLabel>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SEPARATOR: RETURN_IF_ERROR(ConstructInitWidget<QuickSeparator>(widget)); break;
case OpTypedObject::WIDGET_TYPE_RICHTEXT_LABEL: RETURN_IF_ERROR(ConstructInitWidget<QuickRichTextLabel>(widget)); break;
case OpTypedObject::WIDGET_TYPE_RICH_TEXT_EDITOR: RETURN_IF_ERROR(ConstructInitWidget<QuickRichTextEditor>(widget)); break;
case OpTypedObject::WIDGET_TYPE_HELP_TOOLTIP: RETURN_IF_ERROR(ConstructInitWidget<QuickHelpTooltip>(widget)); break;
case OpTypedObject::WIDGET_TYPE_GROUP_BOX: RETURN_IF_ERROR(ConstructInitWidget<QuickGroupBox>(widget)); break;
case OpTypedObject::WIDGET_TYPE_TOGGLE_BUTTON: RETURN_IF_ERROR(ConstructInitWidget<QuickToggleButton>(widget)); break;
case OpTypedObject::WIDGET_TYPE_TABS: RETURN_IF_ERROR(ConstructInitWidget<QuickTabs>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SCROLL_CONTAINER: RETURN_IF_ERROR(ConstructInitWidget<QuickScrollContainer>(widget)); break;
case OpTypedObject::WIDGET_TYPE_SKIN_ELEMENT: RETURN_IF_ERROR(ConstructInitWidget<QuickSkinElement>(widget)); break;
case OpTypedObject::WIDGET_TYPE_COMPOSITE: RETURN_IF_ERROR(ConstructInitWidget<QuickComposite>(widget)); break;
case OpTypedObject::WIDGET_TYPE_FLOW_LAYOUT: RETURN_IF_ERROR(ConstructInitWidget<QuickFlowLayout>(widget, NeedsTestSupport() ? QuickFlowLayout::FORCE_TESTABLE : QuickFlowLayout::NORMAL)); break;
case OpTypedObject::WIDGET_TYPE_CENTERED: RETURN_IF_ERROR(ConstructInitWidget<QuickCentered>(widget)); break;
case OpTypedObject::WIDGET_TYPE_EMPTY: RETURN_IF_ERROR(ConstructInitWidget<NullWidget>(widget)); break;
case OpTypedObject::WIDGET_TYPE_WRAP_LAYOUT: RETURN_IF_ERROR(ConstructInitWidget<QuickWrapLayout>(widget)); break;
default:
{
GetLog().OutputEntry("ERROR: unknown widget type: '%s'", widget_type_str);
return OpStatus::ERR_NOT_SUPPORTED;
}
}
indenter.Done();
return OpStatus::OK;
}
////////// ConstructStackLayout
OP_STATUS
QuickWidgetCreator::ConstructStackLayout(QuickWidget*& layout)
{
// get stack layout orientation first. default: vertical (?)
OpString8 orientation_str;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarStringFromMap("orientation", orientation_str), "ERROR retrieving 'orientation' attribute"));
QuickStackLayout::Orientation orientation = QuickStackLayout::VERTICAL;
if (orientation_str.Compare("horizontal") == 0)
{
orientation = QuickStackLayout::HORIZONTAL;
}
else
{
OP_ASSERT(orientation_str.IsEmpty() || orientation_str.Compare("vertical") == 0);
if (orientation_str.HasContent() && orientation_str.Compare("vertical") != 0)
{
GetLog().OutputEntry("ERROR: attribute 'orientation' needs to be either unspecified, 'vertical' or 'horizontal'. You specified '%s'", orientation_str.CStr());
}
}
OpAutoPtr<QuickStackLayout> new_layout (OP_NEW(QuickStackLayout, (orientation)));
if (!new_layout.get())
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(SetWidgetParameters(new_layout.get()));
RETURN_IF_ERROR(SetWidgetName(new_layout.get()));
RETURN_IF_ERROR(SetGenericWidgetParameters(new_layout.get()));
layout = new_layout.release();
return OpStatus::OK;
}
////////// ConstructInitWidget
template<typename Type>
OP_STATUS
QuickWidgetCreator::ConstructInitWidget(QuickWidget*& widget)
{
OpAutoPtr<Type> new_widget (OP_NEW(Type, ()));
if (!new_widget.get())
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(new_widget->Init());
RETURN_IF_ERROR(SetWidgetParameters(new_widget.get()));
RETURN_IF_ERROR(SetTextWidgetParameters(new_widget.get()));
RETURN_IF_ERROR(SetWidgetName(new_widget.get()));
RETURN_IF_ERROR(SetWidgetSkin(new_widget.get()));
RETURN_IF_ERROR(SetGenericWidgetParameters(new_widget.get()));
widget = new_widget.release();
return OpStatus::OK;
}
////////// ConstructInitWidget
template<typename Type, typename Arg>
OP_STATUS
QuickWidgetCreator::ConstructInitWidget(QuickWidget*& widget, Arg init_argument)
{
OpAutoPtr<Type> new_widget (OP_NEW(Type, ()));
if (!new_widget.get())
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(new_widget->Init(init_argument));
RETURN_IF_ERROR(SetWidgetParameters(new_widget.get()));
RETURN_IF_ERROR(SetTextWidgetParameters(new_widget.get()));
RETURN_IF_ERROR(SetWidgetName(new_widget.get()));
RETURN_IF_ERROR(SetWidgetSkin(new_widget.get()));
RETURN_IF_ERROR(SetGenericWidgetParameters(new_widget.get()));
widget = new_widget.release();
return OpStatus::OK;
}
////////// SetGenericWidgetParameters
OP_STATUS
QuickWidgetCreator::SetGenericWidgetParameters(QuickWidget * widget)
{
UINT32 minwidth = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("minimum-width", minwidth);
if (minwidth != WidgetSizes::UseDefault)
widget->SetMinimumWidth(minwidth);
UINT32 minheight = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("minimum-height", minheight);
if (minheight != WidgetSizes::UseDefault)
widget->SetMinimumHeight(minheight);
UINT32 nomwidth = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("nominal-width", nomwidth);
if (nomwidth != WidgetSizes::UseDefault)
widget->SetNominalWidth(nomwidth);
UINT32 nomheight = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("nominal-height", nomheight);
if (nomheight != WidgetSizes::UseDefault)
widget->SetNominalHeight(nomheight);
UINT32 prefwidth = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("preferred-width", prefwidth);
if (prefwidth != WidgetSizes::UseDefault)
widget->SetPreferredWidth(prefwidth);
UINT32 prefheight = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("preferred-height", prefheight);
if (prefheight != WidgetSizes::UseDefault)
widget->SetPreferredHeight(prefheight);
UINT32 fixedwidth = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("fixed-width", fixedwidth);
if (fixedwidth != WidgetSizes::UseDefault)
widget->SetFixedWidth(fixedwidth);
UINT32 fixedheight = WidgetSizes::UseDefault;
GetWidgetSizeFromMap("fixed-height", fixedheight);
if (fixedheight != WidgetSizes::UseDefault)
widget->SetFixedHeight(fixedheight);
WidgetSizes::Margins margins(WidgetSizes::UseDefault);
GetWidgetSizeFromMap("left-margin", margins.left);
GetWidgetSizeFromMap("right-margin", margins.right);
GetWidgetSizeFromMap("top-margin", margins.top);
GetWidgetSizeFromMap("bottom-margin", margins.bottom);
// Don't overwrite what SetTextWidgetParameter may have done
if (!margins.IsDefault())
widget->SetMargins(margins);
bool hidden = false;
RETURN_IF_ERROR(GetScalarBoolFromMap("hidden", hidden));
if (hidden)
widget->Hide();
return OpStatus::OK;
}
////////// ReadWidgetName
OP_STATUS
QuickWidgetCreator::ReadWidgetName(OpString8& name)
{
RETURN_IF_ERROR(GetScalarStringFromMap("name", name));
if (name.IsEmpty())
{
GetLog().OutputEntry("WARNING: unnamed widget used");
}
return OpStatus::OK;
}
////////// SetWidgetName
template<typename OpWidgetType>
OP_STATUS
QuickWidgetCreator::SetWidgetName(QuickOpWidgetWrapperNoInit<OpWidgetType> * widget)
{
OpString8 name;
RETURN_IF_ERROR(ReadWidgetName(name));
if (name.HasContent())
{
RETURN_IF_ERROR(m_widgets->Put(name, widget));
widget->GetOpWidget()->SetName(name);
}
return OpStatus::OK;
}
template<typename OpWidgetType>
OP_STATUS
QuickWidgetCreator::SetWidgetName(QuickBackgroundWidget<OpWidgetType> * widget)
{
OpString8 name;
RETURN_IF_ERROR(ReadWidgetName(name));
if (name.HasContent())
{
RETURN_IF_ERROR(m_widgets->Put(name, widget));
widget->GetOpWidget()->SetName(name);
}
return OpStatus::OK;
}
OP_STATUS
QuickWidgetCreator::SetWidgetName(QuickWidget * widget)
{
OpString8 name;
RETURN_IF_ERROR(ReadWidgetName(name));
if (name.HasContent())
{
RETURN_IF_ERROR(m_widgets->Put(name, widget));
if (widget->IsOfType<QuickDynamicGrid>())
widget->GetTypedObject<QuickDynamicGrid>()->SetName(name);
else if (widget->IsOfType<QuickExpand>())
widget->GetTypedObject<QuickExpand>()->SetName(name);
else if (widget->IsOfType<QuickGroupBox>())
widget->GetTypedObject<QuickGroupBox>()->SetName(name);
else if (widget->IsOfType<QuickBrowserView>())
widget->GetTypedObject<QuickBrowserView>()->GetOpBrowserView()->SetName(name);
else if (widget->IsOfType<QuickFlowLayout>())
widget->GetTypedObject<QuickFlowLayout>()->SetName(name);
}
return OpStatus::OK;
}
////////// SetTextWidgetParameters
OP_STATUS
QuickWidgetCreator::SetTextWidgetParameters(QuickTextWidget * widget)
{
OpString translated_text;
RETURN_IF_ERROR(GetLog().Evaluate(GetTranslatedScalarStringFromMap("string", translated_text), "ERROR reading node 'string'"));
if (translated_text.HasContent())
RETURN_IF_ERROR(widget->SetText(translated_text));
UINT32 mincharwidth = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("minimum-width", mincharwidth);
if (mincharwidth != WidgetSizes::UseDefault)
widget->SetMinimumCharacterWidth(mincharwidth);
UINT32 mincharheight = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("minimum-height", mincharheight);
if (mincharheight != WidgetSizes::UseDefault)
widget->SetMinimumCharacterHeight(mincharheight);
UINT32 nomcharwidth = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("nominal-width", nomcharwidth);
if (nomcharwidth != WidgetSizes::UseDefault)
widget->SetNominalCharacterWidth(nomcharwidth);
UINT32 nomcharheight = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("nominal-height", nomcharheight);
if (nomcharheight != WidgetSizes::UseDefault)
widget->SetNominalCharacterHeight(nomcharheight);
UINT32 prefcharwidth = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("preferred-width", prefcharwidth);
if (prefcharwidth != WidgetSizes::UseDefault)
widget->SetPreferredCharacterWidth(prefcharwidth);
UINT32 prefcharheight = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("preferred-height", prefcharheight);
if (prefcharheight != WidgetSizes::UseDefault)
widget->SetPreferredCharacterHeight(prefcharheight);
UINT32 fixedcharwidth = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("fixed-width", fixedcharwidth);
if (fixedcharwidth != WidgetSizes::UseDefault)
widget->SetFixedCharacterWidth(fixedcharwidth);
UINT32 fixedcharheight = WidgetSizes::UseDefault;
GetCharacterSizeFromMap("fixed-height", fixedcharheight);
if (fixedcharheight != WidgetSizes::UseDefault)
widget->SetFixedCharacterHeight(fixedcharheight);
WidgetSizes::Margins margins(WidgetSizes::UseDefault);
GetCharacterSizeFromMap("left-margin", margins.left);
GetCharacterSizeFromMap("right-margin", margins.right);
GetCharacterSizeFromMap("top-margin", margins.top);
GetCharacterSizeFromMap("bottom-margin", margins.bottom);
widget->SetCharacterMargins(margins);
int font_rel_size = 100;
RETURN_IF_ERROR(GetScalarIntFromMap("font-rel-size", font_rel_size));
widget->SetRelativeSystemFontSize(font_rel_size);
OpString8 font_weight;
RETURN_IF_ERROR(GetScalarStringFromMap("font-weight", font_weight));
QuickOpWidgetBase::FontWeight quick_font_weight = QuickOpWidgetBase::WEIGHT_NORMAL;
if (font_weight == "bold")
quick_font_weight = QuickOpWidgetBase::WEIGHT_BOLD;
else if (font_weight == "default")
quick_font_weight = QuickOpWidgetBase::WEIGHT_DEFAULT;
widget->SetSystemFontWeight(quick_font_weight);
OpString8 ellipsis;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarStringFromMap("ellipsis", ellipsis),
"ERROR reading node 'ellipsis'"));
if (ellipsis.HasContent())
{
ELLIPSIS_POSITION position = ELLIPSIS_END;
if (ellipsis == "center")
position = ELLIPSIS_CENTER;
else if (ellipsis == "none")
position = ELLIPSIS_NONE;
else if (ellipsis != "end")
GetLog().OutputEntry("WARNING: ellipsis must be set to either 'none', 'center', or 'end'. Assuming value 'end'.");
widget->SetEllipsis(position);
}
return OpStatus::OK;
}
////////// SetWidgetSkin
OP_STATUS
QuickWidgetCreator::SetWidgetSkin(GenericQuickOpWidgetWrapper * widget)
{
OpString8 skin_image;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarStringFromMap("skin-image", skin_image), "ERROR retrieving parameter 'skin-image'"));
if (skin_image.HasContent())
widget->SetSkin(skin_image);
return OpStatus::OK;
}
////////// SetReadOnly
template<typename OpWidgetType>
OP_STATUS
QuickWidgetCreator::SetReadOnly(OpWidgetType * widget)
{
bool read_only = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("read-only", read_only), "ERROR retrieving parameter 'read-only'"));
widget->SetReadOnly(read_only);
return OpStatus::OK;
}
////////// SetGhostText
template<typename OpWidgetType>
OP_STATUS
QuickWidgetCreator::SetGhostText(OpWidgetType * widget)
{
OpString ghost_text;
RETURN_IF_ERROR(GetLog().Evaluate(GetTranslatedScalarStringFromMap("ghost-string", ghost_text), " ERROR reading node 'ghost-string'"));
if (ghost_text.HasContent())
RETURN_IF_ERROR(widget->SetGhostText(ghost_text.CStr()));
return OpStatus::OK;
}
////////// SetContent
template<typename Type>
OP_STATUS
QuickWidgetCreator::SetContent(Type * widget, const OpStringC8& widget_name)
{
OpAutoPtr<QuickWidget> content_widget;
ParserLogger::AutoIndenter indenter(GetLog(), "Reading node 'content'");
RETURN_IF_ERROR(CreateWidgetFromMapNode("content", content_widget, *m_widgets, m_has_quick_window));
if (!content_widget.get())
GetLog().OutputEntry("WARNING: widget without content: ", widget_name);
widget->SetContent(content_widget.release());
indenter.Done();
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickComposite * composite)
{
return SetContent(composite, "Composite");
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickGroupBox * group_box)
{
return SetContent(group_box, "GroupBox");
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickScrollContainer * scroll)
{
return SetContent(scroll, "ScrollContainer");
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickSkinElement * skin_element)
{
bool needs_dynamic_padding = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("dynamic-padding", needs_dynamic_padding), "ERROR reading node 'dynamic-padding'"));
skin_element->SetDynamicPadding(needs_dynamic_padding);
return SetContent(skin_element, "SkinElement");
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickToggleButton * toggle_button)
{
ParserNodeSequence node;
RETURN_IF_ERROR(GetLog().Evaluate(GetNodeFromMap("states", node), "ERROR reading node 'states'"));
ParserLogger::AutoIndenter indenter(GetLog(), "Reading toggle button states");
for (ParserSequenceIterator it(node); it; ++it)
{
ParserNodeMapping item_node;
GetUINode()->GetChildNodeByID(it.Get(), item_node);
QuickWidgetStateCreator item_creator(GetLog());;
RETURN_IF_ERROR(item_creator.Init(&item_node));
OpAutoPtr<OpInputAction> action;
OpString text;
OpString8 skin_image;
INT32 data;
RETURN_IF_ERROR(item_creator.CreateWidgetStateAttributes(text, action, skin_image, data));
OP_ASSERT(action.get() != NULL);
RETURN_IF_ERROR(toggle_button->GetOpWidget()->AddToggleState(action.get(), text, skin_image));
action.release();
}
indenter.Done();
return SetWidgetParameters(static_cast<OpButton*>(toggle_button->GetOpWidget()));;
}
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickRichTextLabel* rich_text_label)
{
bool wrap = FALSE;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("wrap", wrap), "ERROR reading node 'wrap'"));
rich_text_label->GetOpWidget()->SetWrapping(wrap);
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickButton* button)
{
OpAutoPtr<OpInputAction> action;
RETURN_IF_ERROR(CreateInputActionFromMap(action));
button->GetOpWidget()->SetAction(action.release());
bool is_default = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("default", is_default), "ERROR reading node 'default'"));
button->SetDefault(is_default);
return SetWidgetParameters(static_cast<OpButton*>(button->GetOpWidget()));
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(OpButton* button)
{
OpString8 button_style;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarStringFromMap("button-style", button_style), "ERROR retrieving parameter 'button-style'"));
if (button_style.HasContent())
{
if (button_style.Compare("toolbar-image") == 0)
{
button->SetButtonTypeAndStyle(OpButton::TYPE_TOOLBAR, OpButton::STYLE_IMAGE);
}
else if (button_style.Compare("toolbar-text") == 0)
{
button->SetButtonTypeAndStyle(OpButton::TYPE_TOOLBAR, OpButton::STYLE_TEXT);
}
else if (button_style.Compare("toolbar-text-right") == 0)
{
button->SetButtonTypeAndStyle(OpButton::TYPE_TOOLBAR, OpButton::STYLE_IMAGE_AND_TEXT_ON_RIGHT);
}
else
{
RETURN_IF_ERROR(GetLog().OutputEntry("ERROR: button-style not recognized: %s", button_style));
}
}
if (IsScalarInMap(("fixed-image")))
{
bool fixed_image = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("fixed-image", fixed_image), "ERROR reading node 'fixed-image'"));
button->SetFixedImage(fixed_image);
}
OpString8 skin_border_image;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarStringFromMap("skin-border-image", skin_border_image), "ERROR retrieving parameter 'skin-border-image'"));
if (skin_border_image.HasContent())
button->GetBorderSkin()->SetImage(skin_border_image.CStr());
OpString8 skin_foreground_image;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarStringFromMap("skin-foreground-image", skin_foreground_image), "ERROR retrieving parameter 'skin-foreground-image'"));
if (skin_foreground_image.HasContent())
button->GetForegroundSkin()->SetImage(skin_foreground_image.CStr());
bool is_tab_stop = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("tab-stop", is_tab_stop), "ERROR reading node 'tab-stop'"));
button->SetTabStop(is_tab_stop && g_op_ui_info->IsFullKeyboardAccessActive());
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickLabel* label)
{
bool selectable = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("selectable", selectable),
"ERROR reading node 'selectable'"));
label->GetOpWidget()->SetSelectable(selectable);
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickMultilineLabel* label)
{
bool selectable = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("selectable", selectable),
"ERROR reading node 'selectable'"));
label->GetOpWidget()->SetLabelMode(selectable);
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickWrapLayout* layout)
{
INT32 max_visible = 0;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarIntFromMap("max-lines", max_visible), "ERROR reading max-lines"));
if (max_visible != 0)
layout->SetMaxVisibleLines(max_visible, false);
return SetWidgetParameters(static_cast<QuickLayoutBase*>(layout));
}
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickIcon* icon)
{
OpString8 image_name;
RETURN_IF_ERROR(GetScalarStringFromMap("skin-image", image_name));
if (image_name.HasContent())
icon->SetImage(image_name);
bool allow_scaling = false;
RETURN_IF_ERROR(GetScalarBoolFromMap("allow-scaling", allow_scaling));
if (allow_scaling)
icon->SetAllowScaling();
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickButtonStrip * button_strip)
{
OpString8 help_anchor8;
RETURN_IF_ERROR(GetScalarStringFromMap("help_anchor", help_anchor8));
ParserNodeSequence node;
RETURN_IF_ERROR(GetNodeFromMap("buttons", node));
if (node.IsEmpty())
{
GetLog().OutputEntry("ERROR: a button strip needs to specify buttons");
return OpStatus::ERR;
}
ParserLogger::AutoIndenter indenter(GetLog(), "Reading button strip buttons");
for (ParserSequenceIterator it(node); it; ++it)
{
ParserNodeMapping button_node;
GetUINode()->GetChildNodeByID(it.Get(), button_node);
QuickWidgetCreator widget_creator(*m_widgets, GetLog(), m_has_quick_window);
RETURN_IF_ERROR(widget_creator.Init(&button_node));
OpAutoPtr<QuickWidget> button;
RETURN_IF_ERROR(widget_creator.CreateWidget(button));
if (help_anchor8.HasContent())
{
QuickButton* btn = button->GetTypedObject<QuickButton>();
OpInputAction* action = btn ? btn->GetOpWidget()->GetAction() : NULL;
if (action && action->GetAction() == OpInputAction::ACTION_SHOW_HELP)
{
OpString help_anchor;
RETURN_IF_ERROR(help_anchor.Set(help_anchor8));
action->SetActionDataString(help_anchor);
}
}
RETURN_IF_ERROR(button_strip->InsertIntoPrimaryContent(button.release()));
}
indenter.Done();
// TODO: possible enhancement: handle dynamic help anchors?
OpAutoPtr<QuickWidget> special_content;
RETURN_IF_ERROR(GetLog().Evaluate(CreateWidgetFromMapNode("special-content", special_content, *m_widgets, m_has_quick_window), "ERROR reading node 'special-content'"));
if (!special_content.get())
return OpStatus::OK;
return button_strip->SetSecondaryContent(special_content.release());
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickAddressDropDown * drop_down)
{
return SetGhostText(drop_down->GetOpWidget());
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickDropDown * drop_down)
{
RETURN_IF_ERROR(SetGhostText(drop_down->GetOpWidget()));
bool editable = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("editable", editable), "ERROR reading node 'editable'"));
if (editable)
drop_down->GetOpWidget()->SetEditableText();
ParserLogger::AutoIndenter indenter(GetLog(), "Reading dropdown elements");
ParserNodeSequence node;
RETURN_IF_ERROR(GetLog().Evaluate(GetNodeFromMap("elements", node), "ERROR reading node 'elements'"));
for (ParserSequenceIterator it(node); it; ++it)
{
ParserNodeMapping item_node;
GetUINode()->GetChildNodeByID(it.Get(), item_node);
QuickWidgetStateCreator item_creator(GetLog());
RETURN_IF_ERROR(item_creator.Init(&item_node));
OpAutoPtr<OpInputAction> action;
OpString text;
OpString8 skin_image;
INT32 data;
RETURN_IF_ERROR(item_creator.CreateWidgetStateAttributes(text, action, skin_image, data));
RETURN_IF_ERROR(drop_down->AddItem(text, -1, NULL, data, action.get(), skin_image));
action.release();
}
indenter.Done();
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickEdit * edit)
{
bool password_mode = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("password", password_mode), "ERROR reading node 'password'"));
edit->GetOpWidget()->SetPasswordMode(password_mode);
bool force_ltr = false;
RETURN_IF_ERROR(GetLog().Evaluate(GetScalarBoolFromMap("force-ltr", force_ltr), "ERROR reading node 'force-ltr'"));
edit->GetOpWidget()->SetForceTextLTR(force_ltr);
RETURN_IF_ERROR(SetReadOnly(edit->GetOpWidget()));
RETURN_IF_ERROR(SetGhostText(edit->GetOpWidget()));
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickMultilineEdit * edit)
{
return SetReadOnly(edit->GetOpWidget());
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickExpand * expand)
{
OpString translated_text;
RETURN_IF_ERROR(GetLog().Evaluate(GetTranslatedScalarStringFromMap("string", translated_text), "ERROR reading node 'string'"));
if (translated_text.HasContent())
RETURN_IF_ERROR(expand->SetText(translated_text, translated_text));
else
GetLog().OutputEntry("WARNING: text widget has no text set");
return SetContent(expand, "Expand");
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickSelectable * selectable)
{
ParserLogger::AutoIndenter indenter(GetLog(), "Reading content");
OpAutoPtr<OpInputAction> action;
RETURN_IF_ERROR(CreateInputActionFromMap(action));
selectable->GetOpWidget()->SetAction(action.release());
OpAutoPtr<QuickWidget> content_widget;
RETURN_IF_ERROR(CreateWidgetFromMapNode("content", content_widget, *m_widgets, m_has_quick_window));
if (content_widget.get())
selectable->SetChild(content_widget.release());
indenter.Done();
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickDesktopFileChooserEdit * chooser)
{
OpString title;
RETURN_IF_ERROR(GetLog().Evaluate(GetTranslatedScalarStringFromMap("title", title),
"ERROR reading node 'title'"));
RETURN_IF_ERROR(chooser->GetOpWidget()->SetTitle(title.CStr()));
OpString filter;
RETURN_IF_ERROR(GetLog().Evaluate(GetTranslatedScalarStringFromMap("filter-string", filter),
"ERROR reading node 'filter-string'"));
RETURN_IF_ERROR(chooser->GetOpWidget()->SetFilterString(filter.CStr()));
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickStackLayout * stack_layout)
{
// A grid/stack without elements is valid in case it needs to be filled
// in at runtime
ParserNodeSequence node;
RETURN_IF_ERROR(GetNodeFromMap("elements", node));
if (node.IsEmpty())
GetLog().OutputEntry("WARNING: StackLayout doesn't have the 'elements' node specified.");
ParserLogger::AutoIndenter indenter(GetLog(), "Reading stack layout elements");
for (ParserSequenceIterator it(node); it; ++it)
{
ParserNodeMapping child_node;
GetUINode()->GetChildNodeByID(it.Get(), child_node);
QuickWidgetCreator widget_creator(*m_widgets, GetLog(), m_has_quick_window);
RETURN_IF_ERROR(widget_creator.Init(&child_node));
OpAutoPtr<QuickWidget> widget;
RETURN_IF_ERROR(widget_creator.CreateWidget(widget));
RETURN_IF_ERROR(stack_layout->InsertWidget(widget.release()));
}
indenter.Done();
return SetWidgetParameters(static_cast<GenericGrid*>(stack_layout));
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickGrid * grid_layout)
{
// A grid/stack without elements is valid in case it needs to be filled
// in at runtime or a template is used
ParserNodeSequence node;
RETURN_IF_ERROR(GetNodeFromMap("elements", node));
if (node.IsEmpty() && !grid_layout->GetTypedObject<QuickDynamicGrid>())
GetLog().OutputEntry("WARNING: GridLayout doesn't have the 'elements' node specified.");
ParserLogger::AutoIndenter indenter(GetLog(), "Reading grid layout elements");
for (ParserSequenceIterator it(node); it; ++it)
{
ParserLogger::AutoIndenter indenter(GetLog(), "Reading elements of grid row");
ParserNodeMapping row_node;
if (!GetUINode()->GetChildNodeByID(it.Get(), row_node))
{
GetLog().OutputEntry("WARNING: found a node that is not of type MAPPING. Ignoring element.");
indenter.Done();
continue;
}
ParserNodeIDTable table;
RETURN_IF_ERROR(GetLog().Evaluate(row_node.GetHashTable(table), "ERROR: couldn't retrieve hash table from mapping node"));
ParserNodeIDTableData * data;
RETURN_IF_ERROR(GetLog().Evaluate(table.GetData("elements", &data), "ERROR: 'elements' node is not specified in map"));
ParserNodeSequence row_elements_node;
row_node.GetChildNodeByID(data->data_id, row_elements_node);
RETURN_IF_ERROR(grid_layout->AddRow());
for (ParserSequenceIterator row_it(row_elements_node); row_it; ++row_it)
{
ParserNodeMapping child_node;
GetUINode()->GetChildNodeByID(row_it.Get(), child_node);
QuickWidgetCreator widget_creator(*m_widgets, GetLog(), m_has_quick_window);
RETURN_IF_ERROR(widget_creator.Init(&child_node));
OpAutoPtr<QuickWidget> widget;
RETURN_IF_ERROR(widget_creator.CreateWidget(widget));
INT32 colspan = 1;
RETURN_IF_ERROR(GetLog().Evaluate(widget_creator.GetScalarIntFromMap("colspan", colspan), "ERROR reading colspan"));
RETURN_IF_ERROR(grid_layout->InsertWidget(widget.release(), colspan));
}
indenter.Done();
}
indenter.Done();
return SetWidgetParameters(static_cast<GenericGrid*>(grid_layout));
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickDynamicGrid * grid_layout)
{
ParserNodeSequence template_node;
if (OpStatus::IsSuccess(GetNodeFromMap("template", template_node)))
{
QuickGridRowCreator* row_creator = OP_NEW(QuickGridRowCreator, (template_node, GetLog(), m_has_quick_window));
if (!row_creator)
return OpStatus::ERR_NO_MEMORY;
grid_layout->SetTemplateInstantiator(row_creator);
}
return SetWidgetParameters(static_cast<QuickGrid*>(grid_layout));
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(GenericGrid * grid_layout)
{
// Get horizontal centering property (default off)
bool hcenter = false;
RETURN_IF_ERROR(GetScalarBoolFromMap("hcenter", hcenter));
grid_layout->SetCenterHorizontally(hcenter);
// Get vertical centering property (default on)
bool vcenter = true;
RETURN_IF_ERROR(GetScalarBoolFromMap("vcenter", vcenter));
grid_layout->SetCenterVertically(vcenter);
bool uniform_cells = false;
RETURN_IF_ERROR(GetScalarBoolFromMap("uniform-cells", uniform_cells));
RETURN_IF_ERROR(grid_layout->SetUniformCells(uniform_cells));
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickTabs * tabs)
{
ParserNodeSequence node;
RETURN_IF_ERROR(GetNodeFromMap("elements", node));
if (node.IsEmpty())
{
GetLog().OutputEntry("ERROR: Tabs must specify an 'elements' sequence");
return OpStatus::ERR;
}
ParserLogger::AutoIndenter indenter(GetLog(), "Reading tab elements");
for (ParserSequenceIterator it(node); it; ++it)
{
ParserNodeMapping child_node;
GetUINode()->GetChildNodeByID(it.Get(), child_node);
QuickWidgetCreator widget_creator(*m_widgets, GetLog(), m_has_quick_window);
RETURN_IF_ERROR(widget_creator.Init(&child_node));
OpAutoPtr<QuickWidget> widget;
RETURN_IF_ERROR(widget_creator.CreateWidget(widget));
OpString8 name;
RETURN_IF_ERROR(widget_creator.ReadWidgetName(name));
OpString title;
RETURN_IF_ERROR(GetLog().Evaluate(widget_creator.GetTranslatedScalarStringFromMap("title", title), "ERROR: could not retrieve tab title"));
RETURN_IF_ERROR(tabs->InsertTab(widget.release(), title, name));
}
indenter.Done();
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickPagingLayout * paging_layout)
{
ParserNodeSequence node;
RETURN_IF_ERROR(GetNodeFromMap("elements", node));
if (node.IsEmpty())
{
GetLog().OutputEntry("ERROR: Paging Layout must specify an 'elements' sequence");
return OpStatus::ERR;
}
ParserLogger::AutoIndenter indenter(GetLog(), "Reading pages");
for (ParserSequenceIterator it(node); it; ++it)
{
ParserNodeMapping child_node;
GetUINode()->GetChildNodeByID(it.Get(), child_node);
QuickWidgetCreator widget_creator(*m_widgets, GetLog(), m_has_quick_window);
RETURN_IF_ERROR(widget_creator.Init(&child_node));
OpAutoPtr<QuickWidget> widget;
RETURN_IF_ERROR(widget_creator.CreateWidget(widget));
RETURN_IF_ERROR(paging_layout->InsertPage(widget.get()));
widget.release();
}
indenter.Done();
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickLayoutBase * layout)
{
// A grid/stack without elements is valid in case it needs to be filled
// in at runtime
ParserNodeSequence node;
RETURN_IF_ERROR(GetNodeFromMap("elements", node));
if (node.IsEmpty())
GetLog().OutputEntry("WARNING: WrapLayout doesn't have the 'elements' node specified.");
GetLog().OutputEntry("Reading WrapLayout elements...");
GetLog().IncreaseIndentation();
for (ParserSequenceIterator it(node); it; ++it)
{
ParserNodeMapping child_node;
GetUINode()->GetChildNodeByID(it.Get(), child_node);
QuickWidgetCreator widget_creator(*m_widgets, GetLog(), m_has_quick_window);
RETURN_IF_ERROR(widget_creator.Init(&child_node));
OpAutoPtr<QuickWidget> widget;
RETURN_IF_ERROR(widget_creator.CreateWidget(widget));
RETURN_IF_ERROR(layout->InsertWidget(widget.release()));
}
GetLog().DecreaseIndentation();
GetLog().OutputEntry("Done reading WrapLayout elements.");
return OpStatus::OK;
}
////////// SetWidgetParameters
OP_STATUS
QuickWidgetCreator::SetWidgetParameters(QuickCentered * quick_centered)
{
return SetContent(quick_centered, "Centered");
}
bool
QuickWidgetCreator::NeedsTestSupport()
{
return g_scope_manager->desktop_window_manager->IsEnabled() || g_pcui && g_pcui->GetIntegerPref(PrefsCollectionUI::UIPropertyExaminer);
}
|
//convex
//中大资料集数据\二\第二章\2.3_凸边形外壳
#include<stdio.h>
#include<algorithm>
#define MAXN 100010
using namespace std;
struct point
{
int x,y;
point(int ix,int iy):x(ix),y(iy){}
point(){}
int operator*(const point &that)
{
return x*that.y-that.x*y;
}
point operator-(const point &that)
{
return point(x-that.x,y-that.y);
}
bool operator==(const point &that)
{
return x==that.x&&y==that.y;
}
};
int n;
point dot[MAXN];
point stk1[MAXN],stk2[MAXN];
bool cmp(const point &p1,const point &p2)
{
return p1.x<p2.x||p1.x==p2.x&&p1.y<p2.y;
}
void graham_scan()
{
stk1[1]=dot[1]; stk1[2]=dot[2];
stk2[1]=dot[1]; stk2[2]=dot[2];
int top1=2,top2=2;
for (int i=3;i<=n;++i)
{
while (top1>1&&(dot[i]-stk1[top1-1])*(stk1[top1]-stk1[top1-1])<=0)
top1--;
stk1[++top1]=dot[i];
while (top2>1&&(dot[i]-stk2[top2-1])*(stk2[top2]-stk2[top2-1])>=0)
top2--;
stk2[++top2]=dot[i];
}
for (int i=1;i<=top2;++i)
dot[i]=stk2[i];
for (int i=top1-1;i>1;--i)
dot[top2+top1-i]=stk1[i];
n=top2+top1-2;
}
void area()
{
int ans=0;
for (int i=1;i<n;++i)
ans+=dot[i]*dot[i+1];
ans+=dot[n]*dot[1];
printf("%.1lf\n",double(ans)/2);
}
int main()
{
freopen("convex.in","r",stdin);
freopen("convex.out","w",stdout);
int t;
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
for (int i=1;i<=n;++i)
scanf("%d%d",&dot[i].x,&dot[i].y);
sort(dot+1,dot+n+1,cmp);
graham_scan();
area();
}
return 0;
}
|
#ifndef DELETEWORKER_H
#define DELETEWORKER_H
#include<QObject>
#include<QThread>
#include<QString>
#include<QFileInfo>
#include<QDir>
#include<QFile>
#include<iostream>
class DeleteWorker : public QObject
{
Q_OBJECT
public:
DeleteWorker() = default;
~DeleteWorker() = default;
void init(QFileInfo&);
public slots:
void removeFiles();
signals:
void completed();
private:
QString qfi1_;
QString qfi2_;
};
#endif
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#ifndef cmRulePlaceholderExpander_h
#define cmRulePlaceholderExpander_h
#include "cmConfigure.h" // IWYU pragma: keep
#include <map>
#include <string>
class cmOutputConverter;
class cmRulePlaceholderExpander
{
public:
cmRulePlaceholderExpander(
std::map<std::string, std::string> compilers,
std::map<std::string, std::string> variableMappings,
std::string compilerSysroot, std::string linkerSysroot);
void SetTargetImpLib(std::string const& targetImpLib)
{
this->TargetImpLib = targetImpLib;
}
// Create a struct to hold the variables passed into
// ExpandRuleVariables
struct RuleVariables
{
RuleVariables();
const char* CMTargetName;
const char* CMTargetType;
const char* TargetPDB;
const char* TargetCompilePDB;
const char* TargetVersionMajor;
const char* TargetVersionMinor;
const char* Language;
const char* AIXExports;
const char* Objects;
const char* Target;
const char* LinkLibraries;
const char* Source;
const char* AssemblySource;
const char* PreprocessedSource;
const char* Output;
const char* Object;
const char* ObjectDir;
const char* ObjectFileDir;
const char* Flags;
const char* ObjectsQuoted;
const char* SONameFlag;
const char* TargetSOName;
const char* TargetInstallNameDir;
const char* LinkFlags;
const char* Manifests;
const char* LanguageCompileFlags;
const char* Defines;
const char* Includes;
const char* DependencyFile;
const char* FilterPrefix;
const char* SwiftLibraryName;
const char* SwiftModule;
const char* SwiftModuleName;
const char* SwiftOutputFileMap;
const char* SwiftSources;
};
// Expand rule variables in CMake of the type found in language rules
void ExpandRuleVariables(cmOutputConverter* outputConverter,
std::string& string,
const RuleVariables& replaceValues);
// Expand rule variables in a single string
std::string ExpandRuleVariable(cmOutputConverter* outputConverter,
std::string const& variable,
const RuleVariables& replaceValues);
private:
std::string TargetImpLib;
std::map<std::string, std::string> Compilers;
std::map<std::string, std::string> VariableMappings;
std::string CompilerSysroot;
std::string LinkerSysroot;
};
#endif
|
#ifndef __CLIETN_SOCKET_H__
#define __CLIETN_SOCKET_H__
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
class CClientSocket
{
public:
CClientSocket();
CClientSocket(const std::string& host,const int port, const unsigned int nTimeOutMicroSend = 300000, const unsigned int nTimeOutMicroRecv = 300000);
virtual ~CClientSocket();
bool Connect(const std::string& host,const int port, const unsigned int nTimeOutMicroSend = 300000, const unsigned int nTimeOutMicroRecv = 300000);
bool ReConnect();
int Send(char* szBuff, int nLen);
int Recv(char*& szBuffRet);
int Recv(std::string& message);
bool IsValid() const;
private:
void socket_close(int nFd);
int socket_create(const int nAf, const int nType, const int nProtocol, const unsigned int nTimeOutMicroSend, const unsigned int nTimeOutMicroRecv);
int m_sockfd;
std::string m_strSvrIp;
int m_nSvrport;
unsigned int m_nTimeOutMicroSend;
unsigned int m_nTimeOutMicroRecv;
};
#endif
|
/*
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
// This function should rotate list counter-clockwise
// by k and return new head (if changed)
Node* rotate(Node* head, int k)
{
// only gravity will pull me down
// Rotate a Linked List
Node *tmp1 = head, *tmp2 = head;
k--;
while(k) {
tmp2 = tmp2->next;
k--;
}
while(tmp1->next) {
tmp1 = tmp1->next;
}
tmp1->next = head;
head = tmp2->next;
tmp2->next = NULL;
return head;
}
|
#ifndef TIMELINEWIDGET_H
#define TIMELINEWIDGET_H
#include <QFrame>
#include <memory>
#include <Widget/timeline.h>
//--------------------------------------------------------------------------------------------------------------
/// @author Idris Miles
/// @version 1.0
/// @date 01/06/2017
//--------------------------------------------------------------------------------------------------------------
namespace Ui {
class TimeLineWidget;
}
/// @class TimeLineWidget
/// @brief Inherits from QFrame. Custom timeline widget.
class TimeLineWidget : public QFrame
{
Q_OBJECT
public:
/// @brief constructor
explicit TimeLineWidget(QWidget *parent = 0);
/// @brief destructor
~TimeLineWidget();
/// @brief Method to pause timeline
void Pause();
/// @brief Method to play timeline
void Play();
public slots:
/// @brief Slot to handle frame change
void OnFrameChanged(int frame);
/// @brief slot to handle frame cached
void OnFrameCached(int frame);
/// @brief slot to handle frame being finished
void OnFrameFinished(int frame);
/// @brief slot to handle frame range change
void OnFrameRangeChanged(int frameRange);
signals:
/// @brief Qt Signal to communicate a frame change
void FrameChanged(int frame);
/// @brief Qt Signal to communicate a frame being cahced
void FrameCached(int frame);
/// @brief Qt Signal to communicate the cache checkbox state
void CacheChecked(bool checked);
protected:
private:
Ui::TimeLineWidget *ui;
std::unique_ptr<TimeLine> m_timeLine;
};
#endif // TIMELINEWIDGET_H
|
/**
* @copyright (c) 2020, Kartik Venkat, Nidhi Bhojak
*
* @file main.cpp
*
* @authors
* Part 1:
* Kartik Venkat (kartikv97) ---- Driver \n
* Nidhi Bhojak (nbhojak07) ---- Navigator\n
*
* @version 1.0
*
* @section LICENSE
*
* BSD 3-Clause License
*
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @section DESCRIPTION
*
* This is the main function of the PID controller implementation.
*/
#include <iostream>
#include <vector>
#include <lib.hpp>
/**
* @brief main function.
* @param none
* @return none
*/
int main() {
double kp = 10;
double ki = 2;
double kd = 5;
// Create an object of the class.
ComputePID obj(kp, ki, kd);
double TargetVelocity = 25;
double ActualVelocity = 23;
double PreviousError = 3;
double CurrentError;
double PID_Output;
double AccumulatedError;
std::vector <double> AccumulatedErrors = { 7, 5, 3 };
CurrentError = obj.calculateCurrentError(TargetVelocity, ActualVelocity);
AccumulatedError = obj.calculateAccumulatedError(CurrentError,
AccumulatedErrors);
PID_Output = obj.calculatePID(CurrentError, PreviousError,
AccumulatedError);
// Display the results of the implementation.
std::cout << "The target set-point is " << TargetVelocity <<
" and the Actual Velocity is " << ActualVelocity << ".\n";
std::cout << "The current error of the system is :" <<
CurrentError << "\n";
std::cout << "The accumulated error of the system is :" <<
AccumulatedError << "\n";
std::cout << "The output velocity of the PID controller is :" <<
PID_Output << "\n";
return 0;
}
|
/* Runs the motors and solenoid valves on the device.
* This board has support for 4 solenoids (2 independent, 3 & 4 controlled by single pin). Solenoid voltage is controlled by a jumper, which can provide either 12 or 24 volts.
* The solenoids should open when high and closed when low.
*
* The module supports 2 motors. It uses the DRV8704 motor controller, which has an adjustable current limit feature. The current and motor drive direction can remotely be
* controlled. Motor 1 - the winch motor - is setup so that it will only raise while the TOP_TRIP_SENSOR pin is low. Both motors will only operate when the EN pin is active.
*
* Register and register bit functions are described in their enumerations/declarations
*
* Example control sequence is as follows:
* 0) User ensures device is enabled by making sure gate is closed and master device has PI_EN bit set on auxiliary module
* 1) Master device sets current limit on device for trolley motor
* 2) User may switch to manual control mode to raise/lower the winch using the remote control (current code setup may have safety hazard, as this requires that enable signal
* be high to control the motors manually or automatically. Fix may be to allow the user to manually control the winch when device is not enabled until the top trip sensor is
* tripped, since that will be when trolley docks to the magnet, and when lowering the winch places the trolley's load on the magnet. Will have to think about this more... Maybe
* allow user to continue raising winch once docking sensor is tripped, but not lower it, in order to ensure that it is correctly seated on magnet?
* 3) Once trolley is docked, ensure all personnel are clear from area
* 4) Lower winch to release trolley from winch, then raise to clear hook from trolley
* 5) Master device may initiate test, which means activating solenoids immediately after releasing electromagnet. The timing may need to occur on the microcontroller side
* instead of the master side... Something like 15 ms delay will exist.
* 6) De-activate solenoid valves after specified period of time
*
*
*
*/
#include "SPI.h"
#include <SimpleModbusSlave.h>
//Atmega328 Register Adresses
enum { //PINB
P_CTRL_RST,
P_MTR_CTRL_MODE,
P_PB2,
P_MOSI,
P_MISO,
P_SCK,
P_XTAL1,
P_XTAL2
};
enum { //PINC
P_POT_A,
P_POT_B,
P_CTRL_AIN1,
P_CTRL_AIN2,
P_CTRL_BIN1,
P_CTRL_BIN2,
P_RST
};
enum { //PIND
P_RX,
P_TX,
P_EN,
P_TOP_TRIP_SENSOR,
P_DE_RE,
P_SOL_A,
P_SOL_B,
P_SOL_CD
};
//Registers
enum { //STATUS
R_EN, //Global enable signal, active high
R_TOP_TRIP_SENSOR, //Dock sensor, low when docked, high when undocked
R_MTR_CTRL_SW, //Switches between remote control mode (low) and master control mode (high)
R_M_A1, //Motor A-1 pin state
R_M_A2, //Motor A-2 pin state
R_M_B1, //Motor B-1 pin state
R_M_B2, //Motor B-2 pin state
SPI_ERR0, //SPI error code 1 (failed to set ISENSE register)
SPI_ERR1, //SPI error code 2 (failed to set TORQUE)
SPI_ERR2, //SPI error code 3 (inactive)
SPI_ERR3 //SPI error code 4 (inactive)
};
//POTS
//POTA: 0-7 (potentiometer A ADC reading, truncated to 8 bits)
//POTB: 8-15 (potentiometer B ADC reading, truncated to 8 bits)
//CUR_CTRL
//M_CUR: 0-7
enum { //DEV_CTRL
R_M_A_VEL, //Motor A 'velocity' (only works with 0 (don't move) or 1 (fully on)
R_M_A_DIR, //Motor A direction: 1 = forward; 0 = reverse
R_M_B_VEL, //Motor B 'velocity' (only works with 0 (don't move) or 1 (fully on)
R_M_B_DIR, //Motor B direction: 1 = forward; 0 = reverse
R_DEV_CTRL_4, //Unused/spare
R_SOL_A, //keep at 5; Solenoid A control bit (0 = off, 1 = on)
R_SOL_B, //keep at 6; Solenoid B control bit (0 = off, 1 = on)
R_SOL_CD, //keep at 7; Solenoid C & D control bit (0 = off, 1 = on)
R_M1_SAFE // Determines whether the docking sensor prevents M1 from moving in upward direction if tripped. If high, safety enabled
};
enum //Register Addressing
{
STATUS,
POTS,
CUR_CTRL,
TORQUE,
DEV_CTRL,
TIMER,
COUNTER,
DEBUG,
HOLDING_REGS_SIZE // leave this one
// total number of registers for function 3 and 16 share the same register array
// i.e. the same address space
};
//Digital I/O Pins
#define POT_A A0
#define POT_B A1
#define CTRL_AIN1 A2
#define CTRL_AIN2 A3
#define CTRL_BIN1 A4
#define CTRL_BIN2 A5
#define ENABLE 2
#define TOP_TRIP_SENSOR 3
#define DE_REPIN 4
#define SOL_A 5
#define SOL_B 6
#define SOL_CD 7
#define MTR_CTRL_MODE 9
#define SS 10 //Slave select
#define MOSI 11
#define MISO 12
#define SCK 13
#define MODBUS_BAUD_RATE 115200
#define MODBUS_ADDR 0x02
//Motor Control Address Limits
#define ADDR_LOW B000
#define ADDR_HIGH B111
//Initial Motor Current Limits - note can only set one current limit per motor controller
#define M_CUR_INIT 10 //desired current limit in 10ths of an amp (80=8.0 amps)
#define ISGAIN 10 //Hard-coded to be set to 10 V/V
#define RISENSE 0.0075 //Current sense resistor value [ohms] (originally 0.0150)
#define FWD 1 //Forward motor direction
#define REV 0 //Reverse motor direction
#define POT_FWD_TH 200 // Threshold for motor driving forward
#define POT_REV_TH 64 // Threshold for motor in reverse direction
#define SPI_WRITE_DELAY 2 //Write delay between spi writes, ms
#define SPI_SPEED 2500000 //SPI speed in Hz
#define N_CHECK 3 //number of times to read a register
unsigned int holdingRegs[HOLDING_REGS_SIZE]; // function 3 and 16 register array
SPISettings DRV8704Settings (SPI_SPEED, MSBFIRST, SPI_MODE3); //Create SPI object
//Function Prototypes 1
uint16_t ReadReg(uint8_t addr);
uint16_t WriteReg(uint8_t addr, uint16_t data, uint16_t mask);
int RedundantReadReg(uint8_t addr, uint16_t mask);
int RedundantWriteReg(uint8_t addr, uint16_t data, uint16_t mask);
//Motor Class
/*Motor class - contains motor "object" for a single motor controlled through the DRV8704 motor driver
* Motor(M1, M2, top_lim, btm_lim) is constructor that accepts motor A and B pins, and top and bottom limit switch registers. Point to null if not available
*/
class Motor //: public Stream
{
private:
//static uint8_t top_lim, btm_lim; //limit switches, active low
public:
volatile uint8_t M1, M2; //Motor input pins
volatile uint8_t vel, dir; //velocity (0-255) and direction (0=reverse, 1=forward) to command the motor
uint8_t current_lim; //Current limit, in deci-amps (i.e. 105 = 10.5 A)
Motor(uint8_t _M1, uint8_t _M2);
void Drive(uint8_t _vel, uint8_t _dir, uint8_t _fwd_lim, uint8_t _rev_lim);
void SetCurrent(uint8_t _current_lim);
};
Motor::Motor(uint8_t _M1, uint8_t _M2)
{
M1 = _M1;
M2 = _M2;
pinMode(M1, OUTPUT);
pinMode(M2, OUTPUT);
//SetCurrent(M_CUR_INIT); //Set controller to hard-coded current limit
//top_lim = _top_lim;
//btm_lim = _btm_lim;
}
void Motor::Drive(uint8_t _vel, uint8_t _dir, uint8_t _fwd_lim, uint8_t _rev_lim)
{
vel = _vel;
dir = _dir;
//case 1: motor off or has hit limit switch
if (vel == 0 || (vel > 0 && dir == FWD && !_fwd_lim) || (vel > 0 && dir == REV && !_rev_lim)) {
digitalWrite(M1, LOW);
digitalWrite(M2, LOW);
}
//case 2: motor forward
else if (dir == FWD) {
//analogWrite(M1, vel);
digitalWrite(M1, HIGH);
digitalWrite(M2, LOW);
}
//case 3: motor reverse
else if (dir == REV) {
//analogWrite(M2, vel);
digitalWrite(M2, HIGH);
digitalWrite(M1, LOW);
}
}
void Motor::SetCurrent(uint8_t _current_lim)
{
current_lim = _current_lim;
uint8_t Torque = (uint8_t)((((uint32_t)current_lim * 256 * (uint32_t)ISGAIN) * (float)RISENSE) / (27.5) + 0.5); //Apply torque equation, round by adding 0.5
holdingRegs[TORQUE] = Torque; //Assign computed torque
SPI.beginTransaction(DRV8704Settings);
if (RedundantWriteReg(0, 0B000100000001, 0B111111111111)) { //Set ISENSE gain to B01 (10V/V) 000100000001
holdingRegs[STATUS] = (holdingRegs[STATUS] & ~(0x01 << SPI_ERR0)) | (0x01 << SPI_ERR0); //Report error as SPI_ERR0
}
delay(SPI_WRITE_DELAY);
if (RedundantWriteReg(1, Torque, 0xFF)) { //Set TORQUE register to computed torque for desired current
holdingRegs[STATUS] = (holdingRegs[STATUS] & ~(0x01 << SPI_ERR1)) | (0x01 << SPI_ERR1); //Report error as SPI_ERR1
}
//Set current procedure
SPI.endTransaction();
holdingRegs[CUR_CTRL] = _current_lim;
}
//Function Prototypes 2
void UpdateStatus(Motor MA, Motor MB);
void UpdateOutputs(Motor MA, Motor MB);
/** Updates status registers
*
*/
void UpdateStatus(Motor MA, Motor MB)
{
// Update motor status pins
//holdingRegs[STATUS] = (holdingRegs[STATUS] & ~(bit(R_M_A1) | bit(R_M_A2) | bit(R_M_B1) | bit(R_M_B2))) | ( MA.M1 << R_M_A1 | MA.M2 << R_M_A2 | MB.M1 << R_M_B1 | MB.M2 << R_M_B2);
//holdingRegs[STATUS] = (holdingRegs[STATUS] & ~(0x01 << R_MTR_CTRL_SW) | digitalRead(MTR_CTRL_MODE)); //motor control mode (!!!updated in UpdateOutputs()!!!)
//holdingRegs[STATUS] = (MA.M1 << R_M_A1 | MA.M2 << R_M_A2 | MB.M1 << R_M_B1 | MB.M2 << R_M_B2);
//holdingRegs[STATUS] = MB.M2;
//holdingRegs[STATUS] = LOW;
//get motor pin info
//uint8_t mtr_status = (PINC & (bit(P_CTRL_AIN1) | bit(P_CTRL_AIN2) | bit(P_CTRL_BIN1) | bit(P_CTRL_BIN2))) << 1; //Pull from PINC register, leftshift to fit STATUS reg
uint8_t mtr_status = (digitalRead(CTRL_AIN1) << R_M_A1 | digitalRead(CTRL_AIN2) << R_M_A2 | digitalRead(CTRL_BIN1) << R_M_B1 | digitalRead(CTRL_BIN2) << R_M_B2);
holdingRegs[STATUS] = (holdingRegs[STATUS] & ~(bit(R_M_A1) | bit(R_M_A2) | bit(R_M_B1) | bit(R_M_B2))) | mtr_status;
//holdingRegs[STATUS] = mtr_status;
//get top trip sensor status
holdingRegs[STATUS] = ((holdingRegs[STATUS] & ~(0x01 << R_TOP_TRIP_SENSOR)) | digitalRead(TOP_TRIP_SENSOR) << R_TOP_TRIP_SENSOR); // top trip sensor
}
/** Updates the motor and solenoid outputs based on register values each loop
*
*/
void UpdateOutputs(Motor MA, Motor MB)
{
uint8_t drive_velA, drive_dirA, drive_velB, drive_dirB;
uint8_t _potA = (analogRead(POT_A) >> 2); //Truncate pot reading to 8-bit
uint8_t _potB = (analogRead(POT_B) >> 2); //Truncate pot reading to 8-bit
uint8_t _mtr_ctrl_sw = digitalRead(MTR_CTRL_MODE);
uint8_t _enable = digitalRead(ENABLE);
uint8_t _top_trip_sensor = digitalRead(TOP_TRIP_SENSOR);
uint8_t _m1_safe = (holdingRegs[DEV_CTRL] & bit(R_M1_SAFE)) >> R_M1_SAFE;
holdingRegs[POTS] = ((_potA ) | ((uint16_t)(_potB ) << 8)); //concetenate pot inputs, store values in register (should truncate to 8 bits)
//holdingRegs[POTS] = ((_potA);
holdingRegs[STATUS] = (holdingRegs[STATUS] & ~(0x01 << R_MTR_CTRL_SW) | (_mtr_ctrl_sw << R_MTR_CTRL_SW)); //store mtr ctrl sw value in register
holdingRegs[STATUS] = (holdingRegs[STATUS] & ~(0x01 << R_EN)) | (_enable << R_EN); //Store enable status
if ((_mtr_ctrl_sw) && _enable) { //control input switch high and enabled - master control mode
drive_velA = (holdingRegs[DEV_CTRL] & (0x01 << R_M_A_VEL)) >> R_M_A_VEL;
drive_dirA = (holdingRegs[DEV_CTRL] & (0x01 << R_M_A_DIR)) >> R_M_A_DIR;
drive_velB = (holdingRegs[DEV_CTRL] & (0x01 << R_M_B_VEL)) >> R_M_B_VEL;
drive_dirB = (holdingRegs[DEV_CTRL] & (0x01 << R_M_B_DIR)) >> R_M_B_DIR;
}
else if (!_mtr_ctrl_sw) { // potentiometer control mode
//Set motor A direction
if (_potA > POT_FWD_TH) {
drive_velA = 1;
drive_dirA = 1;
}
else if (_potA < POT_REV_TH) {
drive_velA = 1;
drive_dirA = 0;
}
else {
drive_velA = 0;
drive_dirA = 0;
}
//Set motor B direction
if (_potB > POT_FWD_TH) {
drive_velB = 1;
drive_dirB = 1;
}
else if (_potB < POT_REV_TH) {
drive_velB = 1;
drive_dirB = 0;
}
else {
drive_velB = 0;
drive_dirB = 0;
}
}
else {
drive_velA = 0;
drive_velB = 0;
}
//Drive motors
MA.Drive(drive_velA, drive_dirA, (_top_trip_sensor || !_m1_safe), 1);
MB.Drive(drive_velB, drive_dirB, 1, 1);
//Set solenoid states
if (_enable) {
digitalWrite(SOL_A, (holdingRegs[DEV_CTRL] & bit(R_SOL_A)) >> R_SOL_A);
digitalWrite(SOL_B, (holdingRegs[DEV_CTRL] & bit(R_SOL_B)) >> R_SOL_B);
//digitalWrite(6, HIGH); //debugging
digitalWrite(SOL_CD, (holdingRegs[DEV_CTRL] & bit(R_SOL_CD)) >> R_SOL_CD);
}
else {
digitalWrite(SOL_A, 0);
digitalWrite(SOL_B, 0);
digitalWrite(SOL_CD, 0);
}
/*if (_enable) { //For some reason, causes output pin to oscillate with square wave
uint16_t sol_vals = (PIND & ~(bit(P_SOL_A) | bit(P_SOL_B) | bit(P_SOL_CD))) | (holdingRegs[DEV_CTRL] & (bit(R_SOL_A) | bit(R_SOL_B) | (R_SOL_CD))); //set solenoid bits from register
//PIND = (PIND & ~(bit(P_SOL_A) | bit(P_SOL_B) | bit(P_SOL_CD))) | sol_vals;
//PIND = (PIND & ~(bit(P_SOL_A) | bit(P_SOL_B) | bit(P_SOL_CD))) | (holdingRegs[DEV_CTRL] & (bit(R_SOL_A) | bit(R_SOL_B) | (R_SOL_CD))); //set solenoid bits from register
PIND = sol_vals;
}
else {
PIND = (PIND & ~(bit(P_SOL_A) | bit(P_SOL_B) | bit(P_SOL_CD))) | (0x0000 & (bit(R_SOL_A) | bit(R_SOL_B) | (R_SOL_CD))); //clear all solenoid bits
}*/
/*
//if ((PIND & 1 << P_EN) == 1 << P_EN) { //If device enabled
if (_enable) { //If device enabled
//uint8_t sol_vals = holdingRegs[DEV_CTRL] & (bit(R_SOL_A) | bit(R_SOL_B) | (R_SOL_CD))
PIND = (PIND & ~(bit(P_SOL_A) | bit(P_SOL_B) | bit(P_SOL_CD))) | (holdingRegs[DEV_CTRL] & (bit(R_SOL_A) | bit(R_SOL_B) | (R_SOL_CD))); //set solenoid bits
//digitalWrite(SOL_A, holdingRegs[DEV_CTRL] & (0x01 << R_SOL_A)); //Solenoid A on/off
//digitalWrite(SOL_B, holdingRegs[DEV_CTRL] & (0x01 << R_SOL_B)); //Solenoid B on/off
MA.Drive(R_M_A_VEL, R_M_A_DIR, TOP_TRIP_SENSOR, 1);
MB.Drive(R_M_B_VEL, R_M_B_DIR, 1, 1);
}
else { //device not enabled
//digitalWrite(SOL_A, 0);
//digitalWrite(SOL_B, 0);
MA.Drive(0, R_M_A_DIR, TOP_TRIP_SENSOR, 1);
MB.Drive(0, R_M_B_DIR, 1, 1);
}*/
//Update status register with motor output states (done in UpdateStatus() routine, not here!!!!)
//holdingRegs[STATUS] &= (~(bit(R_M_A1) | bit (R_M_A2) | bit(R_M_B1) | bit(R_M_B2)) | (MA.M1 << R_M_A1 | MA.M2 << R_M_A2 | MB.M1 << R_M_B1 | MB.M2 << R_M_B2));
if (MA.current_lim != holdingRegs[CUR_CTRL]) { //Check if current limit needs to be updated
MA.SetCurrent(holdingRegs[CUR_CTRL]); //only need to do this once since MA and MB use same controller
}
}
/* Reads a 12-bit register value at the given address
* @param addr the 3-bit address of the register to read from
* @returns 12-bit value from register
*/
uint16_t ReadReg(uint8_t addr)
{
delay(1);
if ((addr > ADDR_HIGH) || (addr < ADDR_LOW)) {
return 0; //Invalid address - cannot return meaningful data
}
uint8_t msb, lsb, input;
input = (1 << 7) | (addr << 4); // Read byte is in form 0b(Raaa xxxx)where aaa=address
digitalWrite(SS, HIGH);
msb = SPI.transfer(input);
//delay(10);
lsb = SPI.transfer(input);
digitalWrite(SS, LOW);
return (((0x0F & msb) << 8) | lsb);
}
void PrintReg(uint8_t addr)
{
int result = ReadReg(addr);
Serial.print("@(");
Serial.print(addr, HEX);
Serial.print(")\t");
Serial.println(result, BIN);
}
/* Sets a 12-bit register at addresss addr using data. mask specifies which bits to replace.
* @param addr the 3-bit address to write data to
* @param data the 12-bit data to write at address
* @param mask specifies which bits to replace (e.g. B00001111 specifies that last 4 bits are replaced with data)
*/
uint16_t WriteReg(uint8_t addr, uint16_t data, uint16_t mask)
{
uint8_t msb, lsb;
//read in old data
uint16_t oldData = ReadReg(addr);
//Compute new data
//Serial.println(oldData);
//Serial.println(~mask);
//Serial.println(data);
uint16_t newData = (oldData & ~mask) | data; //Apply mask to get value that is pushed
newData = (0 << 15 | addr << 12 | newData);
//Serial.println(newData);
msb = (newData & 0xFF00) >> 8; //Explicitly showing elimination of rightmost bits
lsb = (newData & 0x00FF); //Explicitly showing elimination of leftmost bits
//Serial.println(msb);
//Serial.println(lsb);
//Write data
delay(SPI_WRITE_DELAY);
digitalWrite(SS, HIGH);
SPI.transfer(msb);
SPI.transfer(lsb);
digitalWrite(SS, LOW);
}
/* Reads a register 3 times and repeats up to N times if all 3 reads are not identical. Retuns -1 if all sets of reads fail
*
* @param mask is used for determining which bits matter when comparing successive reads. Useful when it is possible bits will change between reads
*/
int RedundantReadReg(uint8_t addr, uint16_t mask)
{
uint8_t i, j;
//uint8_t success_flag = 0;
int regVal;
for (i = 0; i < N_CHECK; i++) {
//int read_count = 1;
regVal = ReadReg(addr); //First register read
uint8_t success_flag = 1;
for (j = 0; j < 2; j++) {
if ((ReadReg(addr) & mask) != (regVal & mask)) {
success_flag = 0; //read set failed
break; //give up
}
}
if (success_flag == 1) return regVal; //Successful read set, so finished
}
return -1; //all read sets unsuccessful, so failed
}
/* Writes a register then reads it 3 times and repeats up to N times if all 3 reads are not identical. Retuns -1 if all sets of reads fail
* Tries to ensure that a correct register value is written
*/
int RedundantWriteReg(uint8_t addr, uint16_t data, uint16_t mask)
{
int i;
//read in old data
uint16_t oldData = RedundantReadReg(addr, mask);
if (oldData == -1) return -1; //initial read attempt failed
//Compute new data
uint16_t newData = (oldData & ~mask) | data; //Apply mask to get value that is pushed
newData = (0 << 15 | addr << 12 | newData); //Add in address(?)
//Serial.println(newData);
//Split packet
uint16_t msb = (newData & 0xFF00) >> 8; //Explicitly showing elimination of rightmost bits
uint16_t lsb = (newData & 0x00FF); //Explicitly showing elimination of leftmost bits
//Attempt to write data until max number of attempts has been reached or success
for (i = 0; i < N_CHECK; i++) {
//Write attempt
delay(SPI_WRITE_DELAY);
digitalWrite(SS, HIGH);
SPI.transfer(msb);
SPI.transfer(lsb);
digitalWrite(SS, LOW);
//Readback atttempt
if ((RedundantReadReg(addr, mask) & mask) == (newData & mask)) return 0; //done if read successful
holdingRegs[DEBUG]++;
}
return -1; //If all attempts fail, error code
}
uint8_t SPI_addr;
uint8_t stat, val1, val2;
uint16_t result;
//uint32_t i = 0;
Motor MA = Motor(CTRL_AIN1, CTRL_AIN2);
Motor MB = Motor(CTRL_BIN1, CTRL_BIN2);
void setup() {
int i;
for (i = 0; i < HOLDING_REGS_SIZE; i++) { //Clear holdingRegs...
holdingRegs[i] = 0x0000;
}
//holdingRegs[TIMER] = 10000;
// put your setup code here, to run once:
pinMode(SOL_A, OUTPUT);
pinMode(SOL_B, OUTPUT);
pinMode(SOL_CD, OUTPUT);
pinMode(ENABLE, INPUT);
pinMode(CTRL_AIN1, OUTPUT);
pinMode(CTRL_AIN2, OUTPUT);
pinMode(CTRL_BIN1, OUTPUT);
pinMode(CTRL_BIN2, OUTPUT);
SPI.begin();
MA.SetCurrent(M_CUR_INIT); //Set controller to hard-coded current limit
modbus_configure(&Serial, MODBUS_BAUD_RATE, SERIAL_8N2, MODBUS_ADDR, DE_REPIN, HOLDING_REGS_SIZE, holdingRegs);
/**Setup sequence
-Create motor objects
-initialize motor with current setting
-initialize modbus with DIO 4 as DE/RE pin
-set initial values for status registers?
-
*/
}
uint32_t startTime, stopTime, dt;
uint32_t i = 0;
void loop() {
// put your main code here, to run repeatedly:
//Device Update Loop
startTime = millis();
UpdateOutputs(MA, MB); //Updates motors, solenoids, and related registers
UpdateStatus(MA, MB); //Updates the status register
modbus_update();
//if (dt > holdingRegs[TIMER]) holdingRegs[TIMER] = dt;
holdingRegs[COUNTER] = i;
stopTime = millis();
(dt = stopTime - startTime);
holdingRegs[TIMER] = dt;
i++;
}
|
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of Jeremy Salwen nor the name of any other
// contributor may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY Jeremy Salwen AND CONTRIBUTORS ``AS IS'' AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL Jeremy Salwen OR ANY OTHER
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include <fstream>
#include <cstdio>
#include <algorithm>
#include <numeric>
#include <sstream>
#include <queue>
#include <sys/resource.h>
#include <boost/filesystem.hpp>
#include <boost/circular_buffer.hpp>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/program_options.hpp>
#include "common.hpp"
namespace po=boost::program_options;
struct FileCacheEntry;
struct FileCacheEntry {
std::list<FileCacheEntry*>::iterator iterator;
FILE* file=NULL;
bool initialized=false;
};
class CachingFileArray {
public:
CachingFileArray(std::function<std::string (size_t)> f_namer, size_t numFiles, size_t cachesize): cachesize(cachesize), file_namer(f_namer), queuesize(0), entries(numFiles) {
}
FILE* getFile(size_t id) {
FileCacheEntry& e=entries[id];
if(e.file!=NULL) { //cache hit
//Move the current file to the front of the queue
if(e.iterator!=queue.begin()) {
queue.splice(queue.begin(), queue, e.iterator);
}
return e.file;
} else { //cache miss
if(queuesize >= cachesize) {
closeOldestFile();
}
return openFile(id);
}
}
void closeAll() {
while(closeOldestFile());
}
protected:
FILE* openFile(size_t id) {
FileCacheEntry& e=entries[id];
std::string fname=file_namer(id);
e.file = fopen(fname.c_str(), e.initialized?"ab":"wb");
if(e.file==NULL) {
return NULL;
}
queue.push_front(&e);
queuesize++;
e.iterator=queue.begin();
e.initialized=true;
return e.file;
}
bool closeOldestFile() {
if(!queue.empty()) {
FileCacheEntry* e = queue.back();
queue.pop_back();
queuesize--;
fclose(e->file);
e->file=NULL;
return true;
} else {
return false;
}
}
size_t cachesize;
std::function<std::string (size_t)> file_namer;
std::list<FileCacheEntry*> queue;
size_t queuesize;
std::vector<FileCacheEntry> entries;
};
int compute_and_output_context(const boost::circular_buffer<int>& context, const std::vector<float>& idfs, const arma::fmat& origvects, CachingFileArray& outfiles,unsigned int vecdim, unsigned int contextsize, int prune) {
int midid=context[contextsize];
if(midid>=prune) {
return 0;
}
arma::fvec out(vecdim,arma::fill::zeros);
compute_context(context, idfs,origvects,out,vecdim,contextsize);
FILE* fout=outfiles.getFile(midid);
if(fout==NULL) {
std::cerr<<"Error opening file #"<< midid << std::endl;
return 9;
}
//now tot will contain the context representation of the middle vector
size_t n = fwrite(out.memptr(),sizeof(float),vecdim, fout);
if(n != vecdim) {
std::cerr<< "Error writing to file #"<<midid<<std::endl;
return 10;
}
return 0;
}
int extract_contexts(std::ifstream& vocabstream, std::ifstream& tfidfstream, std::ifstream& vectorstream, std::string indir, std::string outdir, int vecdim, unsigned int contextsize, std::string eodmarker, std::string ssmarker, std::string esmarker, bool preindexed, std::string oovtoken, boost::optional<const std::string&> digit_rep, unsigned int prune, unsigned int fcachesize) {
boost::unordered_map<std::string, int> vocabmap;
std::vector<std::string> vocab;
std::vector<float> idfs;
arma::fmat origvects(vecdim,5);
std::string word;
unsigned int index=0;
while(getline(vocabstream,word)) {
vocab.push_back(word);
vocabmap[word]=index;
float tf;
tfidfstream >>tf;
idfs.push_back(tf);
if(index>=origvects.n_cols) {
origvects.resize(origvects.n_rows,origvects.n_cols*2);
}
for(int i=0; i<vecdim; i++) {
vectorstream>>origvects(i,index);
}
index++;
}
vocabstream.close();
tfidfstream.close();
vectorstream.close();
int oovi=0, startdoci, enddoci;
if(!preindexed) {
try {
oovi = vocabmap.at(oovtoken);
} catch(std::out_of_range& e) {
std::cerr<<"Error: OOV Token is not in the vocabulary in indexing mode\n";
return 4;
}
}
try {
startdoci = vocabmap.at(ssmarker);
} catch(std::out_of_range& e) {
std::cerr<<"Error: Start of sentence fill token is not in the vocabulary.\n";
return 5;
}
try {
enddoci = vocabmap.at(esmarker);
} catch(std::out_of_range& e) {
std::cerr<<"Error: End of sentence fill token is not in the vocabulary.\n";
return 6;
}
unsigned int vsize=vocab.size();
if(prune && prune <vsize) {
vsize=prune;
}
if(fcachesize==0) {
fcachesize=vsize;
}
//set limit of open files high enough to open a file for every word in the dictionary.
rlimit lim;
lim.rlim_cur=fcachesize+1024; //1024 extra files just to be safe;
lim.rlim_max=fcachesize+1024;
setrlimit(RLIMIT_NOFILE , &lim);
CachingFileArray outfiles(
[&outdir](size_t i) {
std::ostringstream s;
s<<outdir<<"/"<< i << ".vectors";
return s.str();
},
vsize, fcachesize);
try {
for (boost::filesystem::directory_iterator itr(indir); itr!=boost::filesystem::directory_iterator(); ++itr) {
std::string path=itr->path().string();
if(!boost::algorithm::ends_with(path,".txt")) {
continue;
}
std::ifstream corpusreader(path.c_str());
if(!corpusreader.good()) {
return 7;
}
std::cout << "Reading corpus file " << path << std::endl;
//Keeps track of the accumulated contexts of the previous 5 words, the current word, and the next 5 words
boost::circular_buffer<int> context(2*contextsize+1);
do {
context.clear();
for(unsigned int i=0; i<contextsize; i++) {
context.push_back(startdoci);
}
std::string word;
for(unsigned int i=0; i<contextsize; i++) {
if(getline(corpusreader,word)) {
if(word == eodmarker) goto EOD;
int wind = lookup_word(vocabmap, word, preindexed, oovi, digit_rep);
context.push_back(wind);
}
}
while(getline(corpusreader,word)) {
if(word == eodmarker) goto EOD;
int newind = lookup_word(vocabmap, word, preindexed, oovi, digit_rep);
context.push_back(newind);
int retcode = compute_and_output_context(context, idfs, origvects,outfiles,vecdim,contextsize,vsize);
if(retcode) return retcode;
context.pop_front();
}
EOD:
unsigned int k=0;
while(context.size()<2*contextsize+1) {
context.push_back(enddoci);
k++;
}
for(; k<contextsize; k++) {
int retcode = compute_and_output_context(context, idfs, origvects,outfiles,vecdim,contextsize,vsize);
if(retcode) return retcode;
context.pop_front();
context.push_back(enddoci);
}
} while(!corpusreader.eof());
}
} catch(std::invalid_argument& e) {
std::cerr<<"Error, non-numerical line found in indexed corpus.\n Please make sure your corpus is in the right format.\n";
return 9;
} catch(std::out_of_range& e) {
std::cerr << "Error, found out of bounds index in indexed file.\n";
return 10;
}
std::cout << "Closing files" <<std::endl;
/*
// Not necessary, since exiting properly will clean up anyway (And is much faster)
outfiles.closeAll();
*/
return 0;
}
int main(int argc, char** argv) {
std::string vocabf;
std::string idff;
std::string vecf;
std::string corpusd;
std::string outd;
int dim;
unsigned int contextsize;
std::string ssmarker, esmarker, eod;
std::string oovtoken, digit_rep;
unsigned int prune=0;
unsigned int fcachesize=0;
po::options_description desc("CExtractContexts Options");
desc.add_options()
("help,h", "produce help message")
("vocab,v", po::value<std::string>(&vocabf)->value_name("<filename>")->required(), "vocab file")
("idf,i", po::value<std::string>(&idff)->value_name("<filename>")->required(), "idf file")
("vec,w", po::value<std::string>(&vecf)->value_name("<filename>")->required(), "word vectors file")
("corpus,c", po::value<std::string>(&corpusd)->value_name("<directory>")->required(), "corpus directory")
("outdir,o", po::value<std::string>(&outd)->value_name("<directory>")->required(), "directory to output contexts")
("dim,d", po::value<int>(&dim)->value_name("<number>")->default_value(50),"word vector dimension")
("contextsize,s", po::value<unsigned int>(&contextsize)->value_name("<number>")->default_value(5),"size of context (# of words before and after)")
("prune,p",po::value<unsigned int>(&prune)->value_name("<number>"),"only output contexts for the first N words in the vocab")
("fcachesize,f", po::value<unsigned int>(&fcachesize)->value_name("<number>"), "maximum number of files to open at once")
;
po::options_description markers("Special Token Options");
add_eod_option(markers, &eod);
add_context_options(markers, &ssmarker, &esmarker);
desc.add(markers);
po::options_description indexing("Indexing Options");
indexing.add_options()("preindexed","corpus is already in indexed format");
add_indexing_options(indexing,&oovtoken,&digit_rep);
desc.add(indexing);
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (vm.count("help")) {
std::cout << desc << "\n";
return 0;
}
try {
po::notify(vm);
} catch(po::required_option& exception) {
std::cerr << "Error: " << exception.what() << "\n";
std::cout << desc << "\n";
return 1;
}
std::ifstream vocab(vocabf);
if(!vocab.good()) {
std::cerr << "Vocab file no good" <<std::endl;
return 2;
}
std::ifstream frequencies(idff);
if(!frequencies.good()) {
std::cerr << "Frequencies file no good" <<std::endl;
return 3;
}
std::ifstream vectors(vecf);
if(!vectors.good()) {
std::cerr << "Vectors file no good" <<std::endl;
return 4;
}
if(!boost::filesystem::is_directory(corpusd)) {
std::cerr << "Input directory does not exist" <<std::endl;
return 5;
}
if(!boost::filesystem::is_directory(outd)) {
std::cerr << "Input directory does not exist" <<std::endl;
return 6;
}
boost::optional<const std::string&> digit_rep_arg;
if(!digit_rep.empty()) {
digit_rep_arg=digit_rep;
}
bool preindexed=vm.count("preindexed")>0;
if(preindexed) {
if(vm.count("oovtoken")){
std::cerr <<"Error: --oovtoken is not applicable in preindexed mode\n";
return 7;
}
if(vm.count("digify")) {
std::cerr <<"Error: --digify is not applicable in preindexed mode\n";
return 7;
}
}
return extract_contexts(vocab, frequencies, vectors, corpusd, outd, dim, contextsize, eod, ssmarker, esmarker, preindexed, oovtoken, digit_rep_arg, prune, fcachesize);
}
|
#pragma once
#include "QuestionStateImpl.h"
#include "SequenceQuestionState_fwd.h"
#include "QuestionReview.h"
#include "types.h"
namespace qp
{
class CSequenceQuestionState : CQuestionState
{
public:
LOKI_DEFINE_VISITABLE()
CSequenceQuestionState(CConstSequenceQuestionPtr const& question);
~CSequenceQuestionState();
void SetAnswer(std::vector<std::string> sequence);
const std::vector<std::string> & GetAnswer()const;
CQuestionReview const GetReview()const;
protected:
void DoSubmit() override;
private:
std::unique_ptr<CQuestionReview> m_review;
CConstSequenceQuestionPtr m_question;
std::vector<std::string> m_shuffledSequence;
std::vector<std::string> m_answer;
};
}
|
#pragma once
#ifndef _DISPATCH_H
#define _DISPATCH_H
#include "common.h"
#include <mutex>
/*
* Dispatch Object.
*/
struct DispatchObject {
// Holds everything we need to analyze the data of a stream
// This includes the video fetcher and the video analyzer.
std::shared_ptr<class VideoFetcher> mFetch;
std::shared_ptr<class VideoAnalyzer> mAnalyze;
std::string apiHost;
std::string apiPath;
uint16_t apiPort;
std::string eventId;
std::string gameShorthand;
};
/*
* The dispatcher's job is to act as the mediator between the RESTful API frontend
* and the video analyzer/fetcher backend.
*
* This means that the dispatcher must retain of a map of which stream is being analyzed
* where so we don't have multiple threads running off doing the same thing.
*
* This is a singleton object. It is also forced to be thread-safe.
*/
class Dispatch {
public:
static std::shared_ptr<class Dispatch> Get() { return Singleton; }
~Dispatch();
void BeginNewDispatch(const std::string& eventId, const std::string& game, const std::string& configPath, const std::string& streamUrl, const std::string& apiUrl, uint16_t apiPort, bool bIsDebug);
friend class WebFrontend;
protected:
Dispatch();
static std::shared_ptr<class Dispatch> Singleton;
private:
std::mutex mMappingMutex;
// Mapping from the URL to the dispatch object;
// Game and mode are ignored because a URL can only point to one game/mode anyways.
std::map < std::string, std::shared_ptr<DispatchObject>> mMapping;
// Helper function to create the right analyzer
std::shared_ptr<class VideoAnalyzer> CreateAnalyzer(std::shared_ptr<DispatchObject> newObj, const std::string& eventId, const std::string& game, const std::string& configPath, bool bIsDebug);
// Helper function to create the video fetcher. This also starts the process of pulling the video.
std::shared_ptr<class VideoFetcher> CreateVideoFetcher(const std::string& eventId, const std::string& url, const std::string& game, const std::string& configPath, std::function<void(IMAGE_PATH_TYPE, IMAGE_FRAME_COUNT_TYPE)> cb, bool bIsDebug);
// Helper function to spin up a thread to begin the video analysis
void Thread_StartNewDispatch(std::shared_ptr<DispatchObject> newObj, const std::string& eventId, const std::string& game, const std::string& configPath, const std::string& url, bool bIsDebug);
// Callback Function that gets some JSON information and sends it back out
void SendJSONDataToAPI(std::shared_ptr<DispatchObject> newObj, const std::string& json);
// Config File Constants (Found in general.ini)
const std::string DispatchSection = "Dispatch";
};
#endif
|
#include "WarlockAttack.h"
WarlockAttack::WarlockAttack() { std::cout << " creating WarlockAttack " << std::endl; }
WarlockAttack::~WarlockAttack() { std::cout << " deleting WarlockAttack " << std::endl; }
// void NecromancerAttack::heal(Unit& ally, SpellCaster& healer) {
// ally.takeTreatment(healer.getState().getTreatment() / 2);
// }
|
#include<bits/stdc++.h>
//#include<atcoder/all>
using namespace std;
using ll = long long;
int main()
{
int n;
cin >> n;
vector<ll> inx(n),iny(n),x(n),y(n);
for(int i = 0;i< n;i++){
cin >> inx[i] >> iny[i];
}
for(int i = 0;i<n;i++){
if((abs(inx[i])+abs(iny[i]))%2!=(abs(inx[0])+abs(iny[0]))%2){
cout<<-1<<endl;
return 0;
}
}
vector<ll> d;
for(int i =0;i<39;i++){
d.push_back(1LL<<(38-i));
}
for(int i = 0;i<n;i++){
x[i] = inx[i]+iny[i];
y[i] = inx[i]-iny[i];
}
if(x[0]%2==0)d.push_back(1);
cout<<d.size()<<endl;
for(auto &i:d)cout<<i<<' ';cout<<endl;
for(int i = 0;i<n;i++){
ll nx=0,ny=0;
string ans;
for(auto &j:d){
int p=15;
if(nx-x[i]<0){
nx += j;
p&=3;
}else{
nx -= j;
p&=12;
}
if(ny-y[i]<0){
ny += j;
p &=5;
}
else{
ny -= j;
p &= 10;
}
if(p==1)ans.push_back('R');
if(p==2)ans.push_back('U');
if(p==4)ans.push_back('D');
if(p==8)ans.push_back('L');
}
cout<<ans<<endl;
}
}
|
#include "soda_jacobi2d_2.h"
#include <cstdlib>
#include <cstring>
#include "hw_classes.h"
#include <iostream>
#include "ap_int.h"
#include "jacobi2d_2_kernel.h"
#include "jacobi2d_2.h"
using namespace std;
int main() {
const int ncols = 32;
const int nrows = 32;
const int img_size = ncols*nrows;
ap_uint<64> buf[img_size];
int v = 0;
HWStream<hw_uint<32> > in0, in1;
HWStream<hw_uint<32> > out0, out1;
//for (int i = 0; i < img_size; i++) {
for (int i = 0; i < img_size; i+=2) {
int v = i;
int v1 = i + 1;
buf[i](31, 0) = i;
buf[i](63, 32) = i;
in0.write(v);
in1.write(v1);
}
ap_uint<64> blur_y[img_size];
cout << "starting jacobi2d_2" << endl;
jacobi2d_2(in0, in1, out0, out1);
jacobi2d_2_kernel(blur_y, buf, img_size);
// Discard first two rows
const int row_prefix = ncols*2;
const int col_prefix = 1;
cout << "reading output" << endl;
int start = row_prefix + col_prefix;
for (int i = start; i < img_size; i++) {
cout << "i = " << i << endl;
if ((i - start) % ncols < 30) {
int soda_res_int = (int) blur_y[i];
hw_uint<32> our_res;
if (i % 2 == 0) {
our_res = out0.read();
} else {
our_res = out1.read();
}
auto our_res_int = (int) our_res;
cout << "soda out(" << i - start << ") = " << soda_res_int << endl;
cout << "our out(" << i - start << ") = " << our_res_int << endl;
//assert(our_res_int == soda_res_int);
}
}
cout << "Output is empty: " << out0.is_empty() << endl;
assert(out0.is_empty());
cout << "Done" << endl;
return 0;
}
|
#include "Apple.h"
vector<RECT> Apple::LoadRECT(AppleState::StateName state)
{
vector<RECT> listSourceRect;
RECT rect;
if(Tag == EntityTypes::Bowl)
switch (state)
{
case AppleState::Flying:
rect.left = 15; rect.top = 97; rect.right = rect.left + 28; rect.bottom = rect.top + 20; listSourceRect.push_back(rect);
rect.left = 56; rect.top = 95; rect.right = rect.left + 24; rect.bottom = rect.top + 23; listSourceRect.push_back(rect);
rect.left = 90; rect.top = 95; rect.right = rect.left + 26; rect.bottom = rect.top + 21; listSourceRect.push_back(rect);
rect.left = 127; rect.top = 98; rect.right = rect.left + 26; rect.bottom = rect.top + 15; listSourceRect.push_back(rect);
rect.left = 164; rect.top = 92; rect.right = rect.left + 24; rect.bottom = rect.top + 23; listSourceRect.push_back(rect);
rect.left = 204; rect.top = 94; rect.right = rect.left + 21; rect.bottom = rect.top + 24; listSourceRect.push_back(rect);
break;
case AppleState::Breaking:
rect.left = 235; rect.top = 100; rect.right = rect.left + 37; rect.bottom = rect.top + 14; listSourceRect.push_back(rect);
rect.left = 292; rect.top = 94; rect.right = rect.left + 67; rect.bottom = rect.top + 21; listSourceRect.push_back(rect);
rect.left = 376; rect.top = 94; rect.right = rect.left + 75; rect.bottom = rect.top + 25; listSourceRect.push_back(rect);
rect.left = 472; rect.top = 88; rect.right = rect.left + 85; rect.bottom = rect.top + 33; listSourceRect.push_back(rect);
rect.left = 578; rect.top = 85; rect.right = rect.left + 95; rect.bottom = rect.top + 32; listSourceRect.push_back(rect);
rect.left = 695; rect.top = 83; rect.right = rect.left + 95; rect.bottom = rect.top + 35; listSourceRect.push_back(rect);
rect.left = 814; rect.top = 84; rect.right = rect.left + 101; rect.bottom = rect.top + 35; listSourceRect.push_back(rect);
rect.left = 954; rect.top = 81; rect.right = rect.left + 101; rect.bottom = rect.top + 29; listSourceRect.push_back(rect);
break;
case AppleState::NONE:
break;
default:
break;
}
else
if (Tag == EntityTypes::Meteor)
switch (state)
{
case AppleState::Flying:
rect.left = 171; rect.top = 240; rect.right = rect.left + 74; rect.bottom = rect.top + 213; listSourceRect.push_back(rect);
rect.left = 457; rect.top = 223; rect.right = rect.left + 76; rect.bottom = rect.top + 234; listSourceRect.push_back(rect);
rect.left = 750; rect.top = 250; rect.right = rect.left + 73; rect.bottom = rect.top + 205; listSourceRect.push_back(rect);
rect.left = 1041; rect.top = 229; rect.right = rect.left + 74; rect.bottom = rect.top + 226; listSourceRect.push_back(rect);
rect.left = 169; rect.top = 570; rect.right = rect.left + 74; rect.bottom = rect.top + 174; listSourceRect.push_back(rect);
rect.left = 459; rect.top = 566; rect.right = rect.left + 75; rect.bottom = rect.top + 178; listSourceRect.push_back(rect);
rect.left = 749; rect.top = 518; rect.right = rect.left + 74; rect.bottom = rect.top + 226; listSourceRect.push_back(rect);
rect.left = 1039; rect.top = 595; rect.right = rect.left + 73; rect.bottom = rect.top + 148; listSourceRect.push_back(rect);
rect.left = 170; rect.top = 884; rect.right = rect.left + 76; rect.bottom = rect.top + 149; listSourceRect.push_back(rect);
rect.left = 460; rect.top = 846; rect.right = rect.left + 74; rect.bottom = rect.top + 187; listSourceRect.push_back(rect);
rect.left = 750; rect.top = 814; rect.right = rect.left + 73; rect.bottom = rect.top + 219; listSourceRect.push_back(rect);
rect.left = 1042; rect.top = 802; rect.right = rect.left + 74; rect.bottom = rect.top + 230; listSourceRect.push_back(rect);
break;
case AppleState::Breaking:
rect.left = 56; rect.top = 50; rect.right = rect.left + 47; rect.bottom = rect.top + 49; listSourceRect.push_back(rect);
rect.left = 190; rect.top = 32; rect.right = rect.left + 77; rect.bottom = rect.top + 75; listSourceRect.push_back(rect);
rect.left = 322; rect.top = 18; rect.right = rect.left + 113; rect.bottom = rect.top + 102; listSourceRect.push_back(rect);
rect.left = 497; rect.top = 7; rect.right = rect.left + 140; rect.bottom = rect.top + 125; listSourceRect.push_back(rect);
rect.left = 41; rect.top = 189; rect.right = rect.left + 136; rect.bottom = rect.top + 130; listSourceRect.push_back(rect);
rect.left = 273; rect.top = 183; rect.right = rect.left + 149; rect.bottom = rect.top + 152; listSourceRect.push_back(rect);
rect.left = 744; rect.top = 194; rect.right = rect.left + 126; rect.bottom = rect.top + 113; listSourceRect.push_back(rect);
break;
case AppleState::NONE:
break;
default:
break;
}
else
if (Tag == EntityTypes::AppleThrow)
{
switch (state)
{
case AppleState::Flying:
rect.top = 22;
rect.bottom = 33;
rect.left = 370;
rect.right = rect.left + 12;
listSourceRect.push_back(rect);
rect.top = 23;
rect.bottom = rect.top + 11;
rect.left = 583;
rect.right = rect.left + 10;
listSourceRect.push_back(rect);
rect.top = 25;
rect.bottom = rect.top + 9;
rect.left = 607;
rect.right = rect.left + 8;
listSourceRect.push_back(rect);
rect.top = 25;
rect.bottom = rect.top + 10;
rect.left = 623;
rect.right = rect.left + 10;
listSourceRect.push_back(rect);
rect.top = 24;
rect.bottom = rect.top + 9;
rect.left = 639;
rect.right = rect.left + 10;
listSourceRect.push_back(rect);
rect.top = 25;
rect.bottom = rect.top + 9;
rect.left = 656;
rect.right = rect.left + 8;
listSourceRect.push_back(rect);
rect.top = 23;
rect.bottom = rect.top + 11;
rect.left = 670;
rect.right = rect.left + 8;
listSourceRect.push_back(rect);
rect.top = 41;
rect.bottom = rect.top + 9;
rect.left = 585;
rect.right = rect.left + 11;
listSourceRect.push_back(rect);
break;
case AppleState::Breaking:
rect.top = 20;
rect.bottom = rect.top + 16;
rect.left = 391;
rect.right = rect.left + 13;
listSourceRect.push_back(rect);
rect.top = 18;
rect.bottom = rect.top + 19;
rect.left = 412;
rect.right = rect.left + 24;
listSourceRect.push_back(rect);
rect.top = 15;
rect.bottom = rect.top + 24;
rect.left = 442;
rect.right = rect.left + 32;
listSourceRect.push_back(rect);
rect.top = 14;
rect.bottom = rect.top + 26;
rect.left = 485;
rect.right = rect.left + 32;
listSourceRect.push_back(rect);
rect.top = 12;
rect.bottom = rect.top + 28;
rect.left = 531;
rect.right = rect.left + 32;
listSourceRect.push_back(rect);
break;
case AppleState::NONE:
break;
default:
break;
}
}
else// if (Tag == EntityTypes::KnifeEnemy3)
{
switch (state)
{
case AppleState::Flying:
rect.left = 73; rect.top = 678; rect.right = rect.left + 11; rect.bottom = rect.top + 24; listSourceRect.push_back(rect);
rect.left = 97; rect.top = 680; rect.right = rect.left + 26; rect.bottom = rect.top + 16; listSourceRect.push_back(rect);
rect.left = 130; rect.top = 675; rect.right = rect.left + 13; rect.bottom = rect.top + 25; listSourceRect.push_back(rect);
rect.left = 152; rect.top = 682; rect.right = rect.left + 27; rect.bottom = rect.top + 19; listSourceRect.push_back(rect);
rect.left = 190; rect.top = 677; rect.right = rect.left + 26; rect.bottom = rect.top + 26; listSourceRect.push_back(rect);
rect.left = 225; rect.top = 675; rect.right = rect.left + 24; rect.bottom = rect.top + 22; listSourceRect.push_back(rect);
rect.left = 261; rect.top = 678; rect.right = rect.left + 12; rect.bottom = rect.top + 21; listSourceRect.push_back(rect);
break;
case AppleState::Breaking:
rect.left = 758; rect.top = 31; rect.right = rect.left + 15; rect.bottom = rect.top + 10; listSourceRect.push_back(rect);
rect.left = 756; rect.top = 32; rect.right = rect.left + 24; rect.bottom = rect.top + 18; listSourceRect.push_back(rect);
rect.left = 731; rect.top = 25; rect.right = rect.left + 22; rect.bottom = rect.top + 23; listSourceRect.push_back(rect);
rect.left = 794; rect.top = 23; rect.right = rect.left + 32; rect.bottom = rect.top + 21; listSourceRect.push_back(rect);
rect.left = 0; rect.top = 0; rect.right = rect.left + 0; rect.bottom = rect.top + 0;
listSourceRect.push_back(rect);
listSourceRect.push_back(rect);
listSourceRect.push_back(rect);
listSourceRect.push_back(rect);
listSourceRect.push_back(rect);
listSourceRect.push_back(rect);
break;
case AppleState::NONE:
break;
default:
break;
}
}
return listSourceRect;
}
Apple::Apple(EntityTypes type)
{
Tag = type;
if (Tag == EntityTypes::Bowl)
{
FlyingAnim = new Animation("Resources/civilian.png", 6, LoadRECT(AppleState::Flying), (float)1 / 0.2, D3DXVECTOR2(0.5, 0.5), D3DCOLOR_XRGB(120, 193, 152), Entity::civilian);
BreakingAnim = new Animation("Resources/civilian.png",8, LoadRECT(AppleState::Breaking), (float)1 /10, D3DXVECTOR2(0.5, 0.5), D3DCOLOR_XRGB(120, 193, 152), Entity::civilian);
}
else if (Tag == EntityTypes::AppleThrow)
{
FlyingAnim = new Animation("Resources/Aladdin.png", 8, LoadRECT(AppleState::Flying), (float)1 / 20, D3DXVECTOR2(0.5, 0.5), D3DCOLOR_XRGB(255, 0, 255),Entity::PlayerOne);
BreakingAnim = new Animation("Resources/Aladdin.png", 5, LoadRECT(AppleState::Breaking), (float)1 / 20, D3DXVECTOR2(0.5, 0.5), D3DCOLOR_XRGB(255, 0, 255), Entity::PlayerOne);
}
else
if (Tag == EntityTypes::Meteor)
{
FlyingAnim = new Animation("Resources/meteor.png", 12, LoadRECT(AppleState::Flying), (float)1 / 10, D3DXVECTOR2(0.5,1), D3DCOLOR_XRGB(120, 193, 152));
BreakingAnim = new Animation("Resources/meteor2.png", 7, LoadRECT(AppleState::Breaking), (float)1 / 10, D3DXVECTOR2(0.5,1), D3DCOLOR_XRGB(120, 193, 152));
FlyingAnim->SetScale(D3DXVECTOR2(0.3, 0.3));
BreakingAnim->SetScale(D3DXVECTOR2(0.3, 0.3));
}
else
{
FlyingAnim = new Animation("Resources/guard.png", 7, LoadRECT(AppleState::Flying), (float)1 / 20, D3DXVECTOR2(0.5, 0.5), D3DCOLOR_XRGB(120, 193, 152),Entity::Enemy);
BreakingAnim = new Animation("Resources/Aladdin.png", 10, LoadRECT(AppleState::Breaking), (float)1 / 0.4, D3DXVECTOR2(0.5, 0.5), D3DCOLOR_XRGB(255, 0, 255),Entity::PlayerOne);
BreakingAnim->SetScale(D3DXVECTOR2(2, 2));
}
SetState(AppleState::NONE);
mReverse = false;
}
Apple::~Apple()
{
FlyingAnim->~Animation();
BreakingAnim->~Animation();
}
void Apple::changeAnim(AppleState::StateName state)
{
switch (state)
{
case AppleState::Flying:
mCurrentAnim = FlyingAnim;
BreakingAnim->Reset();
break;
case AppleState::Breaking:
mCurrentAnim = BreakingAnim;
FlyingAnim->Reset();
break;
default:
return;
break;
}
this->width = mCurrentAnim->GetSprite()->GetWidth();
this->height = mCurrentAnim->GetSprite()->GetHeight();
}
void Apple::Update(float dt)
{
if (mCurrentAnim != nullptr)
{
mCurrentAnim->Update(1);
width = mCurrentAnim->GetSprite()->GetWidth();
height = mCurrentAnim->GetSprite()->GetHeight();
if (mCurrentAnim == BreakingAnim)
{
if (mCurrentAnim->GetCurrentFrame() == mCurrentAnim->GetTotalFrame() - 1)
{
this->SetState(AppleState::NONE);
}
}
}
if (curState != nullptr)
{
curState->Update(1);
posX = curState->getPos().x;
posY = curState->getPos().y;
}
}
void Apple::Draw(D3DXVECTOR3 position, RECT sourceRect, D3DXVECTOR2 scale, D3DXVECTOR2 transform, float angle, D3DXVECTOR2 rotationCenter, D3DXCOLOR colorKey)
{
//mCurrentAnimation->GetSprite()->FlipVertical(mCurrentReverse);
if (mCurrentAnim != nullptr)
{
mCurrentAnim->SetPosition(this->GetPosition());
mCurrentAnim->Draw(position, sourceRect, D3DXVECTOR2(), transform, angle, rotationCenter, colorKey);
}
}
RECT Apple::GetBound()
{
RECT rect;
if (Tag != EntityTypes::Meteor)
{
rect.left = this->posX - width / 2;// -mCurrentAnim->GetSprite()->GetWidth() / 2;
rect.right = rect.left + width;// +mCurrentAnim->GetSprite()->GetWidth();
rect.top = this->posY - height / 2;// -mCurrentAnim->GetSprite()->GetHeight() / 2;
rect.bottom = rect.top + height;// +mCurrentAnim->GetSprite()->GetHeight();
}
else
{
rect.left = this->posX - (width*0.3) / 2;// -mCurrentAnim->GetSprite()->GetWidth() / 2;
rect.right = rect.left + width*0.3;// +mCurrentAnim->GetSprite()->GetWidth();
rect.top = this->posY - height*0.3;// -mCurrentAnim->GetSprite()->GetHeight() / 2;
rect.bottom = this->posY;// +mCurrentAnim->GetSprite()->GetHeight();
}
return rect;
}
void Apple::SetState(AppleState::StateName newState)
{
switch (newState)
{
case AppleState::Flying:
curState = new AppleFlyState(D3DXVECTOR3(posX, posY, 0), mReverse,Tag);
break;
case AppleState::Breaking:
curState = new AppleBreakState(D3DXVECTOR3(posX, posY, 0));
break;
case AppleState::NONE:
curState = nullptr;
mCurrentAnim = nullptr;
return;
break;
}
this->changeAnim(newState);
}
void Apple::OnCollision(Entity *impactor, CollisionReturn data, SideCollisions side)
{
if (impactor->Tag == Entity::AppleObject || GetPosition().x==0) return;
if(Tag==Entity::AppleThrow) Sound::getInstance()->play("Apple Splat", false,1);
if (Tag == Entity::Bowl) Sound::getInstance()->play("Clay Pot", false, 1);
SetState(AppleState::Breaking);
}
AppleState::StateName Apple::GetCurrentState()
{
if (curState == nullptr) return AppleState::NONE;
else return curState->GetNameState();
}
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <vespa/vespalib/trace/tracenode.h>
namespace mbus {
typedef vespalib::TraceNode TraceNode;
} // namespace mbus
|
//////////////////////////////////////////////////////////////////////
///Copyright (C) 2011-2012 Benjamin Quach
//
//This file is part of the "Lost Horizons" video game demo
//
//"Lost Horizons" 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
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
//
///////////////////////////////////////////////////////////////////////
//mission.h
//mission class file
//this file is far, far more threadsafe than player.h
#ifndef _MISSION_H_
#define _MISSION_H_
#pragma once
#include "irrlicht.h"
#include "objective.h"
#include "item.h"
#include "vector"
#include "player.h"
#include "alertbox.h"
using namespace irr;
using namespace core;
using namespace video;
class CMission
{
public:
//uses an array as an argument
//to store the objectives
CMission(const wchar_t *title = L"MISS_TITLE", const wchar_t *description=L"MISS_DESC",
std::vector<CObjective*> objectives = (std::vector<CObjective*>)0,
int cash_reward=0,
std::vector<item*> item_reward=(std::vector<item*>)0);
~CMission();
//Looped from the missionmanager object
void loop(irr::IrrlichtDevice *graphics, Player *CPlayer, bool iscurrentmission, std::vector<CShip*> ship_manager, CAlertBox *alertBox);
//deletion function
void drop();
//Used in saving and loading
void setState(int objectivecount);
void save(io::IXMLWriter *writer);
void load(io::IXMLReader *reader);
//changes the title of the mission
void changeTitle(const wchar_t *new_title)
{
mission_title = new_title;
}
//changes the description
void changeDescription(const wchar_t *new_desc)
{
mission_description = new_desc;
}
//returns title of mission
const wchar_t *getTitle()
{
return mission_title;
}
//returns description
const wchar_t *getDesc()
{
return mission_description;
}
//returns objectives in a vector to be read by the mission manager
std::vector<CObjective*> getObjectives()
{
return mission_objectives;
}
//toggled for the missionmanager
bool getMissionComplete()
{
return mission_complete;
}
//used by missionmanager
void setMissionComplete(bool complete)
{
mission_complete = complete;
}
//retrun rewards
int getCashReward()
{
return cash_reward;
}
std::vector<item*> getRewards()
{
return item_reward;
}
//for saving and loading and identfying mission
void setIndex(int index)
{
this->index = index;
}
int getIndex()
{
return index;
}
private:
//important variables
int index; //used for saving and loading
const wchar_t *mission_title;
const wchar_t *mission_description;
std::vector<CObjective*> mission_objectives;
int cash_reward;
bool mission_complete;
std::vector<item*> item_reward;
};
#endif
|
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
using namespace std;
int s[111][111];
int nhang,ncot,size;
int count;
void input(){
scanf("%d %d %d",&nhang,&ncot,&size);
for (int i=0;i<nhang;i++)
for (int j=0;j<ncot;j++)
scanf("%d",&s[i][j]);
}
bool check(int hang,int cot,int size){
for (int i=hang;i<hang+size;i++)
for (int j=cot;j<cot+size;j++)
if (s[i][j] == 0)
return false;
return true;
}
void solve(){
count = 0;
for (int i=0;i<=nhang-size;i++)
for (int j=0;j<=ncot-size;j++)
if ( check(i,j,size) )
count++;
}
void output(){
printf("%d\n",count);
}
int main()
{
int ntest;
freopen("trunghoc7.inp","r",stdin);
scanf("%d",&ntest);
for (int itest=0;itest<ntest;itest++){
input();
solve();
output();
}
return 0;
}
|
#include "gtest/gtest.h"
#include "opennwa/Nwa.hpp"
#include "opennwa/query/language.hpp"
#include "opennwa/construct/quotient.hpp"
#include "opennwa/query/automaton.hpp"
#include "Tests/unit-tests/Source/opennwa/fixtures.hpp"
#include "Tests/unit-tests/Source/opennwa/int-client-info.hpp"
#include "Tests/unit-tests/Source/opennwa/class-NWA/supporting.hpp"
namespace opennwa {
namespace construct {
class opennwa$construct$$quotient$$$EmptyNWA : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
}
Nwa nwa;
};
// The fixture for diamond
class opennwa$construct$$quotient$$$Diamond : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
lab1 = getKey("label1");
lab2 = getKey("label2");
// create nwa
nwa.addInitialState(s1);
nwa.addFinalState(s4);
//Diamond 1
nwa.addInternalTrans(s1, lab1, s2);
nwa.addInternalTrans(s1, lab2, s3);
nwa.addInternalTrans(s2, lab2, s4);
nwa.addInternalTrans(s3, lab1, s4);
}
Nwa nwa;
State s1, s2, s3, s4;
Symbol lab1, lab2;
};
// The fixture for diamond with epsilon transitions
class opennwa$construct$$quotient$$$DiamondEpsilonTransitions : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
lab1 = getKey("label1");
lab2 = getKey("label2");
// create nwa
nwa.addInitialState(s1);
nwa.addFinalState(s4);
//Diamond 1
nwa.addInternalTrans(s1, EPSILON, s2);
nwa.addInternalTrans(s1, lab1, s3);
nwa.addInternalTrans(s2, lab2, s4);
nwa.addInternalTrans(s3, EPSILON, s4);
}
Nwa nwa;
State s1, s2, s3, s4;
Symbol lab1, lab2;
};
// The fixture for diamond with epsilon transitions
class opennwa$construct$$quotient$$$DiamondWildTransitions : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
lab1 = getKey("label1");
lab2 = getKey("label2");
// create nwa
nwa.addInitialState(s1);
nwa.addFinalState(s4);
//Diamond 1
nwa.addInternalTrans(s1, WILD, s2);
nwa.addInternalTrans(s1, lab1, s3);
nwa.addInternalTrans(s2, lab2, s4);
nwa.addInternalTrans(s3, WILD, s4);
}
Nwa nwa;
State s1, s2, s3, s4;
Symbol lab1, lab2;
};
// The fixture for diamond and an isolated loop.
class opennwa$construct$$quotient$$$DiamondIsolatedLoop : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
s5 = getKey("s5");
s6 = getKey("s6");
lab1 = getKey("label1");
lab2 = getKey("label2");
nwa.addInitialState(s1);
nwa.addFinalState(s4);
nwa.addInternalTrans(s1, lab1, s2);
nwa.addInternalTrans(s1, lab2, s3);
nwa.addInternalTrans(s2, lab2, s4);
nwa.addInternalTrans(s3, lab1, s4);
//isolated loop
nwa.addInternalTrans(s5, lab1, s6);
nwa.addInternalTrans(s6, lab2, s5);
}
Nwa nwa;
State s1, s2, s3, s4, s5, s6;
Symbol lab1, lab2;
};
// The fixture for two diamonds having two initial states
class opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStates : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
s5 = getKey("s5");
s6 = getKey("s6");
s7 = getKey("s7");
s8 = getKey("s8");
lab1 = getKey("label1");
lab2 = getKey("label2");
// create nwa
nwa.addInitialState(s1);
nwa.addInitialState(s5);
nwa.addFinalState(s4);
nwa.addFinalState(s8);
//Diamond 1
nwa.addInternalTrans(s1, lab1, s2);
nwa.addInternalTrans(s1, lab2, s3);
nwa.addInternalTrans(s2, lab2, s4);
nwa.addInternalTrans(s3, lab1, s4);
// Diamond 2
nwa.addInternalTrans(s5, lab2, s6);
nwa.addInternalTrans(s5, lab1, s7);
nwa.addInternalTrans(s6, lab1, s8);
nwa.addInternalTrans(s7, lab2, s8);
}
Nwa nwa;
State s1, s2, s3, s4, s5, s6, s7, s8;
Symbol lab1, lab2;
};
// The fixture for two diamonds having two initial states
class opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStatesEpsilonAndWildTransitions : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
s5 = getKey("s5");
s6 = getKey("s6");
s7 = getKey("s7");
s8 = getKey("s8");
lab1 = getKey("label1");
lab2 = getKey("label2");
// create nwa
nwa.addInitialState(s1);
nwa.addInitialState(s5);
nwa.addFinalState(s4);
nwa.addFinalState(s8);
//Diamond 1
nwa.addInternalTrans(s1, EPSILON, s2);
nwa.addInternalTrans(s1, lab1, s3);
nwa.addInternalTrans(s2, lab2, s4);
nwa.addInternalTrans(s3, WILD, s4);
// Diamond 2
nwa.addInternalTrans(s5, lab2, s6);
nwa.addInternalTrans(s5, WILD, s7);
nwa.addInternalTrans(s6, EPSILON, s8);
nwa.addInternalTrans(s7, lab1, s8);
}
Nwa nwa;
State s1, s2, s3, s4, s5, s6, s7, s8;
Symbol lab1, lab2;
};
// The fixture for two diamonds having two initial states and interprocedural
class opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStatesInterprocedural : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
s5 = getKey("s5");
s6 = getKey("s6");
s7 = getKey("s7");
s8 = getKey("s8");
lab1 = getKey("label1");
lab2 = getKey("label2");
// create nwa
nwa.addInitialState(s1);
nwa.addInitialState(s5);
nwa.addFinalState(s4);
//Diamond 1
nwa.addInternalTrans(s1, lab1, s2);
nwa.addInternalTrans(s1, lab2, s3);
// Diamond 2
nwa.addInternalTrans(s5, lab1, s6);
nwa.addInternalTrans(s5, lab2, s7);
nwa.addInternalTrans(s6, lab2, s8);
nwa.addInternalTrans(s7, lab1, s8);
nwa.addCallTrans(s3, lab1, s5);
nwa.addReturnTrans(s8, s3, lab2, s4);
}
Nwa nwa;
State s1, s2, s3, s4, s5, s6, s7, s8;
Symbol lab1, lab2;
};
// The fixture for diamonds in main and callee-2.
class opennwa$construct$$quotient$$$DoubleDiamondNestedInterprocedural : public ::testing::Test {
protected:
// SetUp is called immediately after the constructor (right before each test).
virtual void SetUp() {
// create states
s1 = getKey("s1");
s2 = getKey("s2");
s3 = getKey("s3");
s4 = getKey("s4");
s5 = getKey("s5");
s6 = getKey("s6");
s7 = getKey("s7");
s8 = getKey("s8");
s9 = getKey("s9");
s10 = getKey("s10");
s11 = getKey("s11");
s12 = getKey("s12");
lab1 = getKey("label1");
lab2 = getKey("label2");
// create nwa
nwa.addInitialState(s1);
nwa.addFinalState(s4);
nwa.addFinalState(s6);
//Diamond 1
nwa.addInternalTrans(s1, lab1, s2);
nwa.addInternalTrans(s1, lab2, s3);
nwa.addInternalTrans(s2, lab2, s4);
nwa.addInternalTrans(s3, lab1, s4);
// Diamond 2
nwa.addInternalTrans(s9, lab2, s10);
nwa.addInternalTrans(s9, lab1, s11);
nwa.addInternalTrans(s10, lab1, s12);
nwa.addInternalTrans(s11, lab2, s12);
nwa.addInternalTrans(s7, lab1, s9);
nwa.addInternalTrans(s12, lab2, s8);
// call and return from main to callee-1
nwa.addCallTrans(s3, lab1, s5);
nwa.addReturnTrans(s6, s3, lab2, s4);
// call and return from callee-1 to callee-2
nwa.addCallTrans(s5, lab1, s7);
nwa.addReturnTrans(s8, s5, lab2, s6);
}
Nwa nwa;
State s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12;
Symbol lab1, lab2;
};
// Tests begin ...
TEST(opennwa$construct$$quotientStates, repUniqueKeyMapPrint)
{
wali::util::DisjointSets<State> partition;
State s1 = getKey("s1");
State s2 = getKey("s2");
partition.merge_sets(s1, s2);
State s3 = getKey("s3");
State s4 = getKey("s4");
partition.merge_sets(s3, s4);
State s5 = getKey("s5");
partition.merge_sets(s2, s5);
partition.output(std::cout << "Printing partition : " <<std::endl);
Nwa out;
Nwa nwa;
State resSt;
ClientInfoRefPtr resCI;
std::map<State, State> repUniqueKeyMap;
for( wali::util::DisjointSets<State>::const_iterator outer_iter = partition.begin(); outer_iter != partition.end(); outer_iter++ )
{
std::set<State> equivalenceClass;
for( wali::util::DisjointSets<State>::InnerSet::const_iterator inner_iter = outer_iter->begin(); inner_iter != outer_iter->end(); ++inner_iter ) {
equivalenceClass.insert(*inner_iter);
}
out.statesQuotient(nwa, equivalenceClass, resSt, resCI) ;
repUniqueKeyMap[ partition.representative( *(equivalenceClass.begin()) ) ] = resSt;
}
std::cout << std::endl;
std::cout << partition.representative(s1) << " -> " << repUniqueKeyMap[ partition.representative(s1) ] << std::endl;
std::cout << partition.representative(s3) << " -> " << repUniqueKeyMap[ partition.representative(s3) ] << std::endl;
}
TEST_F(opennwa$construct$$quotient$$$EmptyNWA, EmptyNWA)
{
wali::util::DisjointSets<State> partition;
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageIsEmpty(out) );
}
TEST_F(opennwa$construct$$quotient$$$Diamond, Diamond)
{
wali::util::DisjointSets<State> partition;
partition.insert(s1);
partition.merge_sets(s2, s3);
partition.insert(s4);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state2, lab1, state4);
coalesced.addInternalTrans(state1, lab2, state2);
coalesced.addInternalTrans(state2, lab2, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DiamondEpsilonTransitions, DiamondEpsilonTransitions)
{
wali::util::DisjointSets<State> partition;
partition.insert(s1);
partition.merge_sets(s2, s3);
partition.insert(s4);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
coalesced.addInternalTrans(state1, EPSILON, state2);
coalesced.addInternalTrans(state2, EPSILON, state4);
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state2, lab2, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DiamondWildTransitions, DiamondWildTransitions)
{
wali::util::DisjointSets<State> partition;
partition.insert(s1);
partition.merge_sets(s2, s3);
partition.insert(s4);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
coalesced.addInternalTrans(state1, WILD, state2);
coalesced.addInternalTrans(state2, WILD, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DiamondIsolatedLoop, DiamondIsolatedLoop)
{
wali::util::DisjointSets<State> partition;
partition.insert(s1);
partition.merge_sets(s2, s3);
partition.merge_sets(s2, s5);
partition.merge_sets(s4, s6);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state2, lab1, state4);
coalesced.addInternalTrans(state1, lab2, state2);
coalesced.addInternalTrans(state2, lab2, state4);
coalesced.addInternalTrans(state4, lab2, state2);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStates, DoubleDiamondMultipleInitialStates)
{
wali::util::DisjointSets<State> partition;
partition.merge_sets(s1, s5);
partition.merge_sets(s2, s6);
partition.merge_sets(s3, s7);
partition.merge_sets(s4, s8);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state3 = getKey("state3");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
//Diamond
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state1, lab1, state3);
coalesced.addInternalTrans(state2, lab1, state4);
coalesced.addInternalTrans(state3, lab1, state4);
coalesced.addInternalTrans(state1, lab2, state2);
coalesced.addInternalTrans(state1, lab2, state3);
coalesced.addInternalTrans(state2, lab2, state4);
coalesced.addInternalTrans(state3, lab2, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStatesEpsilonAndWildTransitions, DoubleDiamondMultipleInitialStatesEpsilonAndWildTransitions)
{
wali::util::DisjointSets<State> partition;
partition.merge_sets(s1, s5);
partition.merge_sets(s2, s6);
partition.merge_sets(s3, s7);
partition.merge_sets(s4, s8);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state3 = getKey("state3");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
//Diamond
coalesced.addInternalTrans(state1, EPSILON, state2);
coalesced.addInternalTrans(state1, lab2, state2);
coalesced.addInternalTrans(state1, WILD, state3);
coalesced.addInternalTrans(state2, lab2, state4);
coalesced.addInternalTrans(state2, EPSILON, state4);
coalesced.addInternalTrans(state3, WILD, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStates, DoubleDiamondMultipleInitialStatesSelfLoop)
{
nwa.addInternalTrans(s5, lab2, s1);
wali::util::DisjointSets<State> partition;
partition.merge_sets(s1, s5);
partition.merge_sets(s2, s6);
partition.merge_sets(s3, s7);
partition.merge_sets(s4, s8);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state3 = getKey("state3");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
//Diamond with self loop
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state1, lab1, state3);
coalesced.addInternalTrans(state2, lab1, state4);
coalesced.addInternalTrans(state3, lab1, state4);
coalesced.addInternalTrans(state1, lab2, state2);
coalesced.addInternalTrans(state1, lab2, state3);
coalesced.addInternalTrans(state2, lab2, state4);
coalesced.addInternalTrans(state3, lab2, state4);
coalesced.addInternalTrans(state1, lab2, state1);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStates, DoubleDiamondMultipleInitialStatesUnmatchedCall)
{
nwa.addCallTrans(s5, lab1, s8);
wali::util::DisjointSets<State> partition;
partition.merge_sets(s1, s5);
partition.merge_sets(s2, s6);
partition.merge_sets(s3, s7);
partition.merge_sets(s4, s8);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state3 = getKey("state3");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
//Diamond with self loop
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state1, lab1, state3);
coalesced.addInternalTrans(state2, lab1, state4);
coalesced.addInternalTrans(state3, lab1, state4);
coalesced.addInternalTrans(state1, lab2, state2);
coalesced.addInternalTrans(state1, lab2, state3);
coalesced.addInternalTrans(state2, lab2, state4);
coalesced.addInternalTrans(state3, lab2, state4);
coalesced.addCallTrans(state1, lab1, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DoubleDiamondMultipleInitialStatesInterprocedural, DoubleDiamondMultipleInitialStatesInterprocedural)
{
wali::util::DisjointSets<State> partition;
partition.merge_sets(s1, s5);
partition.merge_sets(s2, s6);
partition.merge_sets(s3, s7);
partition.merge_sets(s4, s8);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state3 = getKey("state3");
State state4 = getKey("state4");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
//Diamond 1
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state1, lab2, state3);
coalesced.addInternalTrans(state2, lab2, state4);
coalesced.addInternalTrans(state3, lab1, state4);
coalesced.addCallTrans(state3, lab1, state1);
coalesced.addReturnTrans(state4, state3, lab2, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
TEST_F(opennwa$construct$$quotient$$$DoubleDiamondNestedInterprocedural, DoubleDiamondNestedInterprocedural)
{
wali::util::DisjointSets<State> partition;
partition.merge_sets(s1, s5);
partition.merge_sets(s1, s9);
partition.merge_sets(s2, s10);
partition.merge_sets(s3, s11);
partition.merge_sets(s4, s12);
partition.merge_sets(s4, s6);
partition.insert(s7);
partition.insert(s8);
Nwa coalesced;
// create states
State state1 = getKey("state1");
State state2 = getKey("state2");
State state3 = getKey("state3");
State state4 = getKey("state4");
State state7 = getKey("state7");
State state8 = getKey("state8");
// create nwa
coalesced.addInitialState(state1);
coalesced.addFinalState(state4);
//Diamond 1
coalesced.addInternalTrans(state1, lab1, state2);
coalesced.addInternalTrans(state1, lab1, state3);
coalesced.addInternalTrans(state2, lab1, state4);
coalesced.addInternalTrans(state3, lab1, state4);
coalesced.addInternalTrans(state1, lab2, state2);
coalesced.addInternalTrans(state1, lab2, state3);
coalesced.addInternalTrans(state2, lab2, state4);
coalesced.addInternalTrans(state3, lab2, state4);
coalesced.addInternalTrans(state7, lab1, state1);
coalesced.addInternalTrans(state4, lab2, state8);
coalesced.addCallTrans(state3, lab1, state1);
coalesced.addCallTrans(state1, lab1, state7);
coalesced.addReturnTrans(state4, state3, lab2, state4);
coalesced.addReturnTrans(state8, state1, lab2, state4);
Nwa out = *quotient( nwa, partition );
EXPECT_TRUE( opennwa::query::languageSubsetEq( nwa ,out ) );
EXPECT_TRUE( opennwa::query::languageEquals( coalesced ,out ) );
EXPECT_FALSE( opennwa::query::statesOverlap(out, nwa) );
}
// Tests end ...
} // end 'namespace opennwa' !!!
} // end 'namespace opennwa' !!!
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
string s;
cin >> s;
int ans_one = 0; //0101
int ans_two = 0; //1010
for(int i = 0; i < s.size(); i++)
{
if (s[i] == '0'){
if ((i % 2) == 0){
ans_two++;
} else {
ans_one++;
}
} else {
if ((i % 2) == 0) {
ans_one++;
} else {
ans_two++;
}
}
}
cout << min(ans_one, ans_two) << endl;
}
|
#include <iostream>
#include <vector>
#include "StrongDataTypes.h"
#include "Utils.h"
using namespace std;
using namespace utils;
template <class Iterator>
void MergeSort(Iterator first, Iterator last) {
if (std::distance(first, last) > 1) {
Iterator middle = first + (last - first) / 2;
MergeSort(first, middle);
MergeSort(middle, last);
std::inplace_merge(first, middle, last);
}
}
int main() {
// simple integer container
std::vector<int> nativeTypeCollection {1, 4, 5, 3, 6, 8, 9, 0, 2, 7};
// custom class type container
std::vector<Integer> userDefinedTypeCollection {
Integer{4},
Integer{2},
Integer{5},
Integer{1},
Integer{6},
Integer{9},
Integer{8},
Integer{7},
Integer{3},
Integer{0}
};
cout << "Collection: ";
PrintCollection(nativeTypeCollection);
cout << "Sorted: ";
MergeSort(nativeTypeCollection.begin(), nativeTypeCollection.end());
PrintCollection(nativeTypeCollection);
cout << "Collection: ";
PrintCollection(userDefinedTypeCollection);
cout << "Sorted: ";
MergeSort(userDefinedTypeCollection.begin(), userDefinedTypeCollection.end());
PrintCollection(userDefinedTypeCollection);
return 0;
}
|
#include <iostream>
using namespace std;
class Circle{
};
class Rectangle{
};
int main(){
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <folly/portability/GMock.h>
#include <quic/QuicException.h>
#include <quic/state/QuicTransportStatsCallback.h>
namespace quic {
class MockQuicStats : public QuicTransportStatsCallback {
public:
MOCK_METHOD(void, onPacketReceived, ());
MOCK_METHOD(void, onDuplicatedPacketReceived, ());
MOCK_METHOD(void, onOutOfOrderPacketReceived, ());
MOCK_METHOD(void, onPacketProcessed, ());
MOCK_METHOD(void, onPacketSent, ());
MOCK_METHOD(void, onDSRPacketSent, (size_t));
MOCK_METHOD(void, onPacketRetransmission, ());
MOCK_METHOD(void, onPacketLoss, ());
MOCK_METHOD(void, onPacketSpuriousLoss, ());
MOCK_METHOD(void, onPersistentCongestion, ());
MOCK_METHOD(void, onPacketDropped, (PacketDropReason));
MOCK_METHOD(void, onPacketForwarded, ());
MOCK_METHOD(void, onForwardedPacketReceived, ());
MOCK_METHOD(void, onForwardedPacketProcessed, ());
MOCK_METHOD(void, onClientInitialReceived, (QuicVersion));
MOCK_METHOD(void, onConnectionRateLimited, ());
MOCK_METHOD(void, onConnectionWritableBytesLimited, ());
MOCK_METHOD(void, onNewConnection, ());
MOCK_METHOD(void, onConnectionClose, (folly::Optional<QuicErrorCode>));
MOCK_METHOD(void, onConnectionCloseZeroBytesWritten, ());
MOCK_METHOD(void, onPeerAddressChanged, ());
MOCK_METHOD(void, onNewQuicStream, ());
MOCK_METHOD(void, onQuicStreamClosed, ());
MOCK_METHOD(void, onQuicStreamReset, (QuicErrorCode));
MOCK_METHOD(void, onConnFlowControlUpdate, ());
MOCK_METHOD(void, onConnFlowControlBlocked, ());
MOCK_METHOD(void, onStatelessReset, ());
MOCK_METHOD(void, onStreamFlowControlUpdate, ());
MOCK_METHOD(void, onStreamFlowControlBlocked, ());
MOCK_METHOD(void, onCwndBlocked, ());
MOCK_METHOD(void, onInflightBytesSample, (uint64_t));
MOCK_METHOD(void, onRttSample, (uint64_t));
MOCK_METHOD(void, onBandwidthSample, (uint64_t));
MOCK_METHOD(void, onNewCongestionController, (CongestionControlType));
MOCK_METHOD(void, onPTO, ());
MOCK_METHOD(void, onRead, (size_t));
MOCK_METHOD(void, onWrite, (size_t));
MOCK_METHOD(void, onUDPSocketWriteError, (SocketErrorType));
MOCK_METHOD(void, onTransportKnobApplied, (TransportKnobParamId));
MOCK_METHOD(void, onTransportKnobError, (TransportKnobParamId));
MOCK_METHOD(void, onTransportKnobOutOfOrder, (TransportKnobParamId));
MOCK_METHOD(void, onServerUnfinishedHandshake, ());
MOCK_METHOD(void, onZeroRttBuffered, ());
MOCK_METHOD(void, onZeroRttBufferedPruned, ());
MOCK_METHOD(void, onZeroRttAccepted, ());
MOCK_METHOD(void, onZeroRttRejected, ());
MOCK_METHOD(void, onDatagramRead, (size_t));
MOCK_METHOD(void, onDatagramWrite, (size_t));
MOCK_METHOD(void, onDatagramDroppedOnWrite, ());
MOCK_METHOD(void, onDatagramDroppedOnRead, ());
MOCK_METHOD(void, onNewTokenReceived, ());
MOCK_METHOD(void, onNewTokenIssued, ());
MOCK_METHOD(void, onTokenDecryptFailure, ());
MOCK_METHOD(void, onShortHeaderPadding, (size_t));
MOCK_METHOD(void, onPacerTimerLagged, ());
MOCK_METHOD(void, onPeerMaxUniStreamsLimitSaturated, ());
MOCK_METHOD(void, onPeerMaxBidiStreamsLimitSaturated, ());
MOCK_METHOD(void, onConnectionIdCreated, (size_t));
};
class MockQuicStatsFactory : public QuicTransportStatsCallbackFactory {
public:
~MockQuicStatsFactory() override = default;
MOCK_METHOD(std::unique_ptr<QuicTransportStatsCallback>, make, ());
};
} // namespace quic
|
#include <fstream>
#include <iostream>
#include <sys/types.h>
#include <inttypes.h>
#include <map>
#include <vector>
#include <list>
#include <set>
#define _STDC_FORMAT_MACROS
#define dMap1MaxSize 512
#define dMap2MaxSize 4096
#define iMap1MaxSize 512
#define iMap2MaxSize 4096
#define OFFCHIP_LATENCY 60
using namespace std;
#ifdef DEBUG
#define DEBUG_MSG(str) do { std::cerr << str << std::endl; } while( false )
#else
#define DEBUG_MSG(str) do { } while ( false )
#endif
/*
* TYPEDEFS
*/
//Map<Branch ID, pair<Branch target ID, Predictor state> >
typedef std::map<uint32_t, std::pair<uint32_t, uint32_t> >branch_pred_map;
typedef std::map<uint32_t, std::pair<uint32_t, uint32_t> >::iterator branch_pred_it;
//Pair<Branch target ID, Predictor state>
typedef std::pair<uint32_t, uint32_t> target_state_pair;
//Pair<Memory address, Instruction ID>
typedef std::pair< uint32_t, uint32_t> EntryPair;
//Linked list of EntryPair
typedef std::list< EntryPair > CacheList;
//Map<Memory address, list iterator>
// typedef std::map< uint32_t, CacheList::iterator > CacheMap;
//Map<Memory address, No.of L1 misses>
typedef std::map<uint32_t, std::pair<uint32_t, uint32_t> > CacheMissMap;
//Map<Branch ID, mispredict count>
typedef std::map<uint32_t, uint32_t> BranchMisMap;
typedef std::map<uint32_t, std::pair<uint32_t, uint32_t> > BBBranchMisMap;
// Branch mispredict counter per basic block
BBBranchMisMap *bb_br_mispr_map = new std::map<uint32_t, std::pair<uint32_t, uint32_t> >();
typedef pair<int, bool> Tag;
typedef pair<Tag, Tag> TagPair;
typedef map<int, TagPair > CacheMap;
typedef map<int, TagPair >::iterator CacheMapIT;
class MLPTuple {
public:
// Memory instruction ID
int mem_inst_id;
// Number of instructions this inst is supposed to wait for
int wait_inst_count;
// Average MLP
int mlp;
// Number of times this instruction is called
int call_count;
MLPTuple(int id) {
mem_inst_id = id;
wait_inst_count = OFFCHIP_LATENCY;
call_count = 1;
mlp = 0;
}
};
typedef std::map<uint32_t, std::list<MLPTuple> > MLPBuffer;
class dcache{
public:
static CacheMap *mcache1Map;
static CacheMap *mcache2Map;
static CacheMissMap *L1miss_map;
static CacheMissMap *L2miss_map;
};
class icache{
public:
static CacheMap *mcache1Map;
static CacheMap *mcache2Map;
static CacheMissMap *L1miss_map;
static CacheMissMap *L2miss_map;
};
// Initialization of static class members
// CacheMap* dcache::mcache1Map = new std::map<uint32_t, CacheList::iterator>();
// CacheMap* dcache::mcache2Map = new std::map<uint32_t, CacheList::iterator>();
CacheMap* dcache::mcache1Map = new CacheMap;
CacheMap* dcache::mcache2Map = new CacheMap;
CacheMissMap* dcache::L1miss_map = new std::map<uint32_t, std::pair<uint32_t, uint32_t> >();
CacheMissMap* dcache::L2miss_map = new std::map<uint32_t, std::pair<uint32_t, uint32_t> >();
//CacheMap* icache::mcache1Map = new std::map<uint32_t, CacheList::iterator>();
//CacheMap* icache::mcache2Map = new std::map<uint32_t, CacheList::iterator>();
CacheMap* icache::mcache1Map = new CacheMap;
CacheMap* icache::mcache2Map = new CacheMap;
CacheMissMap* icache::L1miss_map = new std::map<uint32_t, std::pair<uint32_t, uint32_t> >();
CacheMissMap* icache::L2miss_map = new std::map<uint32_t, std::pair<uint32_t, uint32_t> >();
// Initialization of the global variables
std::list<std::vector<int> > *mlp_list = new std::list<std::vector<int> >;
long mcache1Size = 0 , mcache2Size = 0, l1miss = 0, l2miss = 0;
/*
* Method declarations
*/
void update_br_mispredict(BBBranchMisMap*, uint32_t, uint32_t, int);
int do_cache( CacheMap *mcache1Map,
CacheMap *mcache2Map,
CacheMissMap *L1miss_map,
CacheMissMap *L2miss_map,
uint64_t addr,
uint32_t bb_id,
bool type);
void update_miss_map(CacheMissMap*, uint32_t, int );
bool is_cache_miss(CacheMap* , int, int);
void insertInCache(CacheMap*, int, int);
void print_miss_maps();
void print_miss_map(CacheMissMap* miss_map, string type);
extern "C" void dCacheCounter( const uint32_t bb_id,
const uint32_t inst_id,
const uint64_t addr) {
ofstream mlp_check_file;
bool exists = false;
std::list<std::vector<int> >:: iterator mlp_it;
mlp_check_file.open("mlp_check.txt", ios::app);
if(do_cache(dcache::mcache1Map,
dcache::mcache2Map,
dcache::L1miss_map,
dcache::L2miss_map,
addr,
bb_id,
1) == false) {
mlp_it = mlp_list->begin();
// Increase everyone's MLP
while(mlp_it != mlp_list->end()) {
if((*mlp_it)[0] == bb_id) {
exists = true;
}
(*mlp_it)[1] = (*mlp_it)[1] + 1;
mlp_it++;
}
// If the BB doesn't already exist
if(exists == false) {
std::vector<int> v;
v.push_back(bb_id);
v.push_back(0);
v.push_back(80);
mlp_list->push_back(v);
}
}
return;
}
extern "C" void MLPCounter(uint32_t bb_id,
uint32_t num_insts) {
std::list<std::vector<int> >:: iterator mlp_it;
ofstream mlp_file;
bool bb_exists = false;
mlp_file.open("mlp.txt", ios::app);
mlp_it = mlp_list->begin();
while(mlp_it != mlp_list->end()) {
// Substract the number of instructions executed
(*mlp_it)[2] = (*mlp_it)[2] - num_insts;
if((*mlp_it)[2] <= 0) {
mlp_file << (*mlp_it)[0] <<" " << (*mlp_it)[1] << "\n";
mlp_it = mlp_list->erase(mlp_it);
}
else {
mlp_it++;
}
}
mlp_file.close();
}
extern "C" void iCacheCounter(const uint32_t bb_id, const uint32_t size, const uint64_t start_addr) {
// Assuming every instruction 4 bytes
for(uint64_t inst_addr = start_addr;
inst_addr <= start_addr + size; inst_addr = inst_addr + 4) {
do_cache(icache::mcache1Map,
icache::mcache2Map,
icache::L1miss_map,
icache::L2miss_map,
inst_addr, // Instruction ID
bb_id,
0);
}
return;
}
/*
* The state machine requires the next instruction the branch
* takes to decide whether or not the branch was taken and then
* calculates the number of mispredicts a 2 way saturating predictor
* would have made. It also updates the total branch mispredicts per
* basic block, and the number of mispredicts per branch
*/
extern "C" void branchCounter(uint32_t bb_id, uint32_t branchInstID,
uint32_t branchTargetID){
// 2-way saturating branch prediction map
static branch_pred_map *bp = new std::map<
uint32_t, std::pair<uint32_t, uint32_t> >();
bool flag = false;
int miss = 0;
//2-way saturating Branch predictor
branch_pred_it it = bp->find(branchInstID);
if(it == bp->end()){
// Branch seen for the first time
target_state_pair insertPair = make_pair(branchTargetID, 1);
bp->insert(std::pair<uint32_t, std::pair<uint32_t, uint32_t> >(branchInstID,
insertPair));
}
else{
uint32_t curBrTargetID, curState, nxtState, nextBRTargetID;
target_state_pair existingPair = it->second;
curBrTargetID = existingPair.first;
curState = existingPair.second;
DEBUG_MSG("branchinst " << branchInstID << " branchTarget " << branchTargetID <<
" state " << curState << "\n");
switch(curState) {
case 1: if (curBrTargetID == branchTargetID)
nxtState = 1;
else{
nxtState = 2;
miss = 1;
}
break;
case 2: if(curBrTargetID == branchTargetID)
nxtState = 1;
else{
nxtState = 3;
miss = 1;
flag = true;
}
break;
case 3: if(curBrTargetID == branchTargetID)
nxtState = 4;
else{
nxtState = 2;
miss = 1;
flag = true;
}
break;
case 4: if(curBrTargetID == branchTargetID)
nxtState = 4;
else{
nxtState = 3;
miss = 1;
}
break;
default: nxtState = 1;
cout<<"Incorrect behavior in the branch predictor";
}
update_br_mispredict(bb_br_mispr_map, bb_id, branchInstID, miss);
DEBUG_MSG("branchinst " << branchInstID << " branchTarget " << branchTargetID <<
" next state " << nxtState << "\n");
if(flag)
nextBRTargetID = branchTargetID;
else
nextBRTargetID = curBrTargetID;
// Update predictor
target_state_pair nxtPair = make_pair(nextBRTargetID, nxtState);
it->second = nxtPair;
}
}
void update_br_mispredict(BBBranchMisMap *bb_br_mispr_map,
uint32_t bb_id,
uint32_t branchInstID,
int miss){
DEBUG_MSG("Mispredict for BB " << bb_id);
// BB ID doesn't exist
if (bb_br_mispr_map->find(bb_id) == bb_br_mispr_map->end()) {
if(miss)
(*bb_br_mispr_map)[bb_id] = make_pair(1,1);
else
(*bb_br_mispr_map)[bb_id] = make_pair(0,1);
}
else {
// Increase the miss count
if(miss) {
(((bb_br_mispr_map->find(bb_id))->second).first)++;
}
// Increment the total count
(((bb_br_mispr_map->find(bb_id))->second).second)++;
}
}
extern "C" void branchPrinter(void) {
ofstream branch_mispredict_file;
static bool open_file = false;
if (!open_file)
branch_mispredict_file.open("branch_mispredict.txt", ios::app);
BBBranchMisMap::iterator it;
for(it = bb_br_mispr_map->begin(); it!=bb_br_mispr_map->end(); it++) {
branch_mispredict_file << it->first << " " << (it->second).first \
<< " " << (it->second).second << endl;
}
// branch_mispredict_file.close();
// Clear the whole map for next time
bb_br_mispr_map->clear();
print_miss_maps();
}
/*
* Returns true if the cache request was a hit
* else returns false
*/
int do_cache(CacheMap *mcache1Map,
CacheMap *mcache2Map,
CacheMissMap *L1miss_map,
CacheMissMap *L2miss_map,
uint64_t addr,
uint32_t bb_id,
bool type){
bool is_hit = true;
int l1_Tag, l2_Tag, l1_blk, l2_blk;
addr = addr >> 6; // Removed the offset
if (type == 1) {
// D-cache
l1_Tag = addr >> 9;
l2_Tag = addr >> 12;
l1_blk = dMap1MaxSize-1 & addr; // Get only last 9 bits
l2_blk = dMap2MaxSize-1 & addr; // Get only last 12 bits
}
else if (type == 0) {
// I-cache
l1_Tag = addr >> 9;
l2_Tag = addr >> 12;
l1_blk = iMap1MaxSize-1 & addr; // Get only last 9 bits
l2_blk = iMap2MaxSize-1 & addr; // Get only last 12 bits
}
if (is_cache_miss(mcache1Map, l1_blk, l1_Tag)) {
// Miss in L1
// update_miss_map(L1miss_map, bb_id, 1);
if (is_cache_miss(mcache2Map, l2_blk, l2_Tag)) {
// Miss in both L1 and L2
is_hit = false;
// update_miss_map(L2miss_map, bb_id, 1);
insertInCache(mcache1Map, l1_blk, l1_Tag);
insertInCache(mcache2Map, l2_blk, l2_Tag);
}
else {
// Hit in L2
// update_miss_map(L2miss_map, bb_id, 0);
insertInCache(mcache1Map, l1_blk, l1_Tag);
}
}
else {
// Hit in L1
// update_miss_map(L1miss_map, bb_id, 0);
}
return is_hit;
}
bool is_cache_miss(CacheMap *cacheMap, int blk, int tag) {
CacheMapIT it;
it = cacheMap->find(blk);
if(it == cacheMap->end()) {
return true;
}
else {
TagPair tp = it->second;
// Check Tag and the valid bit
if (tp.first.first == tag && tp.first.second)
return false;
else if (tp.second.first == tag && tp.second.second) {
// LRU in Tags. Refresh the Tag order
Tag tmp = tp.second;
tp.second = tp.first;
tp.first = tmp;
return false;
}
else
return true;
}
}
void insertInCache(CacheMap *cacheMap,
int blk,
int tag) {
CacheMapIT it;
it = cacheMap->find(blk);
Tag t1,t2;
if(it == cacheMap->end()) {
// Block is being inserted for the first time
t1 = make_pair(tag, 1);
t2 = make_pair(0,0);
}
else {
TagPair tp = it->second;
t1 = make_pair(tag, 1);
t2 = tp.first;
}
(*cacheMap)[blk] = make_pair(t1,t2);
}
void update_miss_map(CacheMissMap *miss_map, uint32_t bb_id, int miss){
std::map<uint32_t, std::pair<uint32_t, uint32_t> >::iterator map_it;
map_it = miss_map->find(bb_id);
if(map_it==miss_map->end()){
//Insert a new entry with count = 1 and total = 1
if(miss) {
(*miss_map)[bb_id] = make_pair(1,1);
}
//Insert a new entry with count = 0 and total = 1
else {
(*miss_map)[bb_id] = make_pair(0,1);
}
}
else{
if(miss) {
((map_it->second).first)++;
((map_it->second).second)++;
}
else {
((map_it->second).second)++;
}
}
}
void print_miss_maps() {
print_miss_map(icache::L1miss_map , string("L1-I miss"));
print_miss_map(icache::L2miss_map , string("L2-I miss"));
print_miss_map(dcache::L1miss_map , string("L1-D miss"));
print_miss_map(dcache::L2miss_map , string("L2-D miss"));
}
void print_miss_map(CacheMissMap *miss_map, string type) {
ofstream cache_miss_file;
type.append(".txt");
cache_miss_file.open(type.c_str(), ios::app);
std::map<uint32_t, std::pair<uint32_t, uint32_t> >::iterator map_it;
for(map_it = miss_map->begin(); map_it != miss_map->end(); map_it++) {
cache_miss_file << map_it->first << " " << \
(map_it->second).first << " " << (map_it->second).second << "\n";
}
miss_map->clear();
cache_miss_file.close();
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <quic/server/QuicUDPSocketFactory.h>
namespace quic {
class QuicReusePortUDPSocketFactory : public QuicUDPSocketFactory {
public:
~QuicReusePortUDPSocketFactory() override {}
QuicReusePortUDPSocketFactory(bool reusePort = true, bool reuseAddr = false)
: reusePort_(reusePort), reuseAddr_(reuseAddr) {}
std::unique_ptr<QuicAsyncUDPSocketType> make(folly::EventBase* evb, int)
override {
auto sock = std::make_unique<QuicAsyncUDPSocketType>(evb);
sock->setReusePort(reusePort_);
sock->setReuseAddr(reuseAddr_);
return sock;
}
private:
bool reusePort_;
bool reuseAddr_;
};
} // namespace quic
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.