blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8a19c7d90d6a6e011a66abf73c0208bca25c733d | 75baca02c97360c3e260bc283acbce543d930104 | /7.1.6.5/SDK/PUBG_NetworkNext_structs.hpp | 5e32c3744544c9bf8416ea2599beb6ec38d33938 | [] | no_license | patrickcjk/pubg-sdk | e7336de283cd167df78349f4f3d632ef9b53746b | 7c1b80c2f7c3a87339a9d0b047805ff1399ab27c | refs/heads/main | 2023-02-02T20:58:50.722075 | 2020-12-21T22:15:46 | 2020-12-21T22:15:46 | 323,460,008 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,912 | hpp | #pragma once
// PUBG (7.1.6.5) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_Basic.hpp"
#include "PUBG_Engine_classes.hpp"
#include "PUBG_OnlineSubsystemUtils_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Enums
//---------------------------------------------------------------------------
// Enum NetworkNext.ENetworkNextPlatformType
enum class ENetworkNextPlatformType : uint8_t
{
PlatformType_Unknown = 0,
PlatformType_Windows = 1,
PlatformType_Mac = 2,
PlatformType_Linux = 3,
PlatformType_Switch = 4,
PlatformType_PS4 = 5,
PlatformType_XboxOne = 6,
PlatformType_iOS = 7,
PlatformType_MAX = 8
};
// Enum NetworkNext.ENetworkNextConnectionType
enum class ENetworkNextConnectionType : uint8_t
{
ConnectionType_Unknown = 0,
ConnectionType_Wired = 1,
ConnectionType_Wifi = 2,
ConnectionType_Cellular = 3,
ConnectionType_MAX = 4
};
//---------------------------------------------------------------------------
//Script Structs
//---------------------------------------------------------------------------
// ScriptStruct NetworkNext.NetworkNextServerConfig
// 0x0020
struct FNetworkNextServerConfig
{
struct FString ServerAddress; // 0x0000(0x0010) (Edit, BlueprintVisible, ZeroConstructor)
struct FString Datacenter; // 0x0010(0x0010) (Edit, BlueprintVisible, ZeroConstructor)
};
// ScriptStruct NetworkNext.NetworkNextConfig
// 0x0030
struct FNetworkNextConfig
{
struct FString PublicKeyBase64; // 0x0000(0x0010) (Edit, BlueprintVisible, ZeroConstructor)
struct FString PrivateKeyBase64; // 0x0010(0x0010) (Edit, BlueprintVisible, ZeroConstructor)
int SocketSendBufferSize; // 0x0020(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
int SocketReceiveBufferSize; // 0x0024(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
bool EnableTryBeforeYouBuy; // 0x0028(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
bool EnableHighPriorityServerThread; // 0x0029(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x6]; // 0x002A(0x0006) MISSED OFFSET
};
// ScriptStruct NetworkNext.NetworkNextClientStats
// 0x0034
struct FNetworkNextClientStats
{
ENetworkNextConnectionType ConnectionType; // 0x0000(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
bool OnNetworkNext; // 0x0001(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0x2]; // 0x0002(0x0002) MISSED OFFSET
float NetworkNextMinRtt; // 0x0004(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float NetworkNextMeanRtt; // 0x0008(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float NetworkNextMaxRtt; // 0x000C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float NetworkNextJitter; // 0x0010(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float NetworkNextPacketLoss; // 0x0014(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float DirectMinRtt; // 0x0018(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float DirectMeanRtt; // 0x001C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float DirectMaxRtt; // 0x0020(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float DirectJitter; // 0x0024(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float DirectPacketLoss; // 0x0028(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float KbpsUp; // 0x002C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float KbpsDown; // 0x0030(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"__fastcall@DESKTOP-DVBFFR9"
] | __fastcall@DESKTOP-DVBFFR9 |
351145cc3486c6c14a297b738133d298bcc83cd3 | b28d73d302be24c051176e67c1461c73907462c1 | /Tetris/sshape.h | 59bbffd738b816f1ffeefeefa3b4962dd8ec958b | [] | no_license | WuBinCPP/My_own_project | d2dde93c854152193a8ac552e839a042327072f1 | 898e68526e8743c5ee79c2fb99e0a7f8b108c0cb | refs/heads/master | 2020-04-01T07:20:56.486786 | 2018-10-18T14:14:27 | 2018-10-18T14:14:27 | 152,986,468 | 0 | 0 | null | 2018-10-14T15:05:18 | 2018-10-14T15:05:18 | null | UTF-8 | C++ | false | false | 263 | h | #ifndef SSHAPE_H
#define SSHAPE_H
#include "public.h"
#include "shape.h"
#include "board.h"
class sshape : public shape
{
public:
sshape(cell &, board &);
~sshape();
private:
virtual void compute_rotate_positions() override;
};
#endif // SSHAPE_H
| [
"dailifeng@dailifengdeMacBook-Pro.local"
] | dailifeng@dailifengdeMacBook-Pro.local |
2f553a3637f1da3714240a7a55eefd1e0734e315 | 39e39126faa0bd3c13dcd12e9617c55fc5a7187f | /Oscilloscope/playrecordspeeddialog.h | 15ea50ebdd44d63b74f819e3fb4f551d7b69d026 | [] | no_license | fatumVal1ant/Oscilloscope | 4d1effa5be38d494670acd261baccac7ebab7d66 | bd4fdf15381b82c8b9bb669ec146dda5b40e2df4 | refs/heads/master | 2020-07-08T04:19:37.630417 | 2019-08-21T10:42:05 | 2019-08-21T10:42:05 | 203,562,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,279 | h | #ifndef PLAYRECORDSPEEDDIALOG_H
#define PLAYRECORDSPEEDDIALOG_H
#include <QObject>
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QIntValidator>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include "recordframeparser.h"
namespace oscilloscope {
class PlayRecordSpeedDialog : public QDialog {
Q_OBJECT
private:
RecordFrameParser *_parser;
QLabel *_milliPeriodLabel;
QLineEdit *_milliPeriodEdit;
QIntValidator *_validator;
QGridLayout *_layout;
QHBoxLayout *_mainButtonLayout;
QHBoxLayout *_speedButtonLayout;
QPushButton *_okButton;
QPushButton *_cancelButton;
QPushButton *_strongRightButton;
QPushButton *_weakRightButton;
QPushButton *_strongLeftButton;
QPushButton *_weakLeftButton;
void changeSpeed(int milliDelta);
private slots:
void clickOk();
void clickCancel();
void clickStrongRight();
void clickWeakRight();
void clickStrongLeft();
void clickWeakLeft();
public:
PlayRecordSpeedDialog(RecordFrameParser *parser, QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags());
};
}
#endif // PLAYRECORDSPEEDDIALOG_H
| [
"fatumVal1ant@gmail.com"
] | fatumVal1ant@gmail.com |
49bf509ba82b3daf78d5d15b9aa96e3f415b2cbc | 2540a918953bb0f8909964da3dd17bebca248076 | /CG_4/CG_generator/main.cpp | 42e6a8fb6ad0013a02e0ce17186c88f0967ad120 | [] | no_license | brunocv/CG | 21430c17901a2beb3afecf2d36bc9b4d2551b2f0 | a3ae91f782f03d8bb225905d9591f119c3fd8c7d | refs/heads/master | 2021-02-25T23:30:14.674175 | 2020-03-06T17:14:49 | 2020-03-06T17:14:49 | 245,476,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,807 | cpp |
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <string.h>
#include <iostream>
#include <cmath>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#define BUFF_SIZE 1024
using namespace std;
struct ponto {
float x;
float y;
float z;
} Ponto;
struct pontoText {
float x;
float y;
} PontoText;
struct vetorNormal{
float x;
float y;
float z;
}VetorNormal;
/*Escrever as coordenadas de um ponto numa posição de um dado ficheiro*/
std::string writePoint(ponto point) {
std::stringstream sstm;
sstm << point.x << " " << point.y << " " << point.z;
return sstm.str();
}
std::string writeNormal(vetorNormal point) {
std::stringstream sstm;
sstm << point.x << " " << point.y << " " << point.z;
return sstm.str();
}
std::string writePointTex(pontoText point) {
std::stringstream sstm;
sstm << point.x << " " << point.y;
return sstm.str();
}
/*Indicar os pontos de um triangulo a escrever num dado ficheiro
No final, vai ficar um triangulo representado numa linha do ficheiro*/
std::string formTriangle(ponto pointA, ponto pointB, ponto pointC) {
return writePoint(pointA) + " " + writePoint(pointB) + " " + writePoint(pointC);
}
std::string formLine(ponto pointA, ponto pointB, ponto pointC,pontoText a, pontoText b, pontoText c,vetorNormal na,vetorNormal nb, vetorNormal nc) {
return (writePoint(pointA) + " " + writePoint(pointB) + " " + writePoint(pointC)+ " " + writePointTex(a)+" "+writePointTex(b)+" "+writePointTex(c)+
" "+ writeNormal(na) +" "+writeNormal(nb) +" "+writeNormal(nc));
}
std::string writeValue(float value) {
std::stringstream sstm;
sstm << value;
return sstm.str();
}
std::string writeLineNumber(float value) {
return writeValue(value) + "\n";
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
/*PLANE*/
void drawPlane(char *filename, float tamanho) {
float x = tamanho / 2;
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = -x;
pontoA.y = 0;
pontoA.z = x;
pontoText pontoTexB;
pontoTexB.x = 1;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = x;
pontoB.y = 0;
pontoB.z = x;
pontoText pontoTexC;
pontoTexC.x = 1;
pontoTexC.y = 1;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = x;
pontoC.y = 0;
pontoC.z = -x;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 1;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = -x;
pontoD.y = 0;
pontoD.z = -x;
ofstream ficheiro;
ficheiro.open(filename);
if (ficheiro.is_open()) {
ficheiro.clear();
//para cada plano o ficheiro terá de ter sempre só 2 linhas
ficheiro << writeLineNumber(2.0);
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
ficheiro << formLine(pontoC, pontoD, pontoA,pontoTexC,pontoTexD,pontoTexA,vecNormalC,vecNormalD,vecNormalA) << endl;
ficheiro.close();
}
else
cout << "Unable to open file\n";
}
//-------------------------------------------------------------------------------------------------------------------------------------------------
/*CONE*/
void drawCone(char *filename, float radius, float height, int slices, int stacks) {
// put code to draw cone in here
float ang = (2 * M_PI) / slices;
//número de triângulos que desenham o cone
float value = slices + (stacks * slices * 2);
ofstream ficheiro;
ficheiro.open(filename);
if (ficheiro.is_open()) {
ficheiro.clear();
ficheiro << writeLineNumber(value);
for (int z = 0; z < slices; z++) {
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = radius * sin(z * ang);
pontoA.y = 0;
pontoA.z = radius * cos(z * ang);
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = 0;
pontoB.y = 0;
pontoB.z = 0;
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = radius * sin(ang * (z + 1));
pontoC.y = 0;
pontoC.z = radius * cos(ang * (z + 1));
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
}
for (int i = 0; i < stacks; ++i) {
float raio = radius - i * (radius / stacks);
for (int z = 0; z < slices; z++) {
// Lado1
float raio2 = radius - (i + 1) * (radius / stacks);
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = raio2 * sin(ang * z);
pontoD.y = (i + 1) * (height / stacks);
pontoD.z = raio2 * cos(ang * z);
pontoText pontoTexE;
pontoTexE.x = 0;
pontoTexE.y = 0;
vetorNormal vecNormalE;
vecNormalE.x = 0;
vecNormalE.y = 0;
vecNormalE.z = 0;
ponto pontoE;
pontoE.x = raio * sin(z * ang);
pontoE.y = i * (height / stacks);
pontoE.z = raio * cos(z * ang);
pontoText pontoTexF;
pontoTexF.x = 0;
pontoTexF.y = 0;
vetorNormal vecNormalF;
vecNormalF.x = 0;
vecNormalF.y = 0;
vecNormalF.z = 0;
ponto pontoF;
pontoF.x = raio * sin(ang * (z + 1));
pontoF.y = i * (height / stacks);
pontoF.z = raio * cos(ang * (z + 1));
ficheiro << formLine(pontoD, pontoE, pontoF,pontoTexD,pontoTexE,pontoTexF,vecNormalD,vecNormalE,vecNormalF) << endl;
// Lado2
pontoText pontoTexG;
pontoTexG.x = 0;
pontoTexG.y = 0;
vetorNormal vecNormalG;
vecNormalG.x = 0;
vecNormalG.y = 0;
vecNormalG.z = 0;
ponto pontoG;
pontoG.x = raio2 * sin(z * ang);
pontoG.y = (i + 1) * (height / stacks);
pontoG.z = raio2 * cos(z * ang);
pontoText pontoTexH;
pontoTexH.x = 0;
pontoTexH.y = 0;
vetorNormal vecNormalH;
vecNormalH.x = 0;
vecNormalH.y = 0;
vecNormalH.z = 0;
ponto pontoH;
pontoH.x = raio * sin(ang * (z + 1));
pontoH.y = i * (height / stacks);
pontoH.z = raio * cos(ang * (z + 1));
pontoText pontoTexI;
pontoTexI.x = 0;
pontoTexI.y = 0;
vetorNormal vecNormalI;
vecNormalI.x = 0;
vecNormalI.y = 0;
vecNormalI.z = 0;
ponto pontoI;
pontoI.x = raio2 * sin(ang * (z + 1));
pontoI.y = (i + 1) * (height / stacks);
pontoI.z = raio2 * cos(ang * (z + 1));
ficheiro << formLine(pontoG, pontoH, pontoI,pontoTexG,pontoTexH,pontoTexI,vecNormalG,vecNormalG,vecNormalI) << endl;
}
}
ficheiro.close();
}
else
cout << "Unable to open file\n";
}
//------------------------------------------------------------------------------------------------------------------------------------------------
/*SPHERE*/
void drawSphere(char *filename, float radius, int slices, int stacks) {
//XOZ
float b = (2 * M_PI) / slices;
//XOY
float a = M_PI / stacks;
float value = slices * ((stacks / 2) + 1) * 4;
ofstream ficheiro;
ficheiro.open(filename);
if (ficheiro.is_open()) {
ficheiro.clear();
ficheiro << writeLineNumber(value);
for (int i = 0; i < stacks / 2 + 1; i++) {
for (int j = 0; j < slices; j++) {
float angulo = b * j;
float angulo2 = angulo + b;
float nivel = i * a;
float nivel2 = nivel + a;
//--------------------------------------------------------------------------------------------------
//primeira slice vai ter coordenadas (0, y), onde y vai ser `(stack actual) / (# de stacks)`
pontoText pontoTexA;
pontoTexA.x = (((float) j) / slices);
pontoTexA.y = 0.5 + (((float)i) / stacks);
vetorNormal vecNormalA;
vecNormalA.x = cos(nivel)*sin(angulo);
vecNormalA.y = sin(nivel);
vecNormalA.z = cos(nivel)*cos(angulo);
ponto pontoA;
pontoA.x = radius * cos(nivel)*sin(angulo);
pontoA.y = radius * sin(nivel);
pontoA.z = radius * cos(nivel)*cos(angulo);
pontoText pontoTexB;
pontoTexB.x = ((((float)j) + 1) / slices) ;
pontoTexB.y = 0.5 + (((float)i) / stacks);
vetorNormal vecNormalB;
vecNormalB.x = cos(nivel)*sin(angulo2);
vecNormalB.y = sin(nivel);
vecNormalB.z = cos(nivel)*cos(angulo2);
ponto pontoB;
pontoB.x = radius * cos(nivel)*sin(angulo2);
pontoB.y = radius * sin(nivel);
pontoB.z = radius * cos(nivel)*cos(angulo2);
vetorNormal vecNormalC;
vecNormalC.x = cos(nivel2)*sin(angulo2);
vecNormalC.y = sin(nivel2);
vecNormalC.z = cos(nivel2)*cos(angulo2);
pontoText pontoTexC;
pontoTexC.x = ((((float)j) + 1) / slices);
pontoTexC.y = 0.5 + ((((float)i) + 1) / stacks);
ponto pontoC;
pontoC.x = radius * cos(nivel2)*sin(angulo2);
pontoC.y = radius * sin(nivel2);
pontoC.z = radius * cos(nivel2)*cos(angulo2);
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
//--------------------------------------------------------------------------------------------------
pontoText pontoTexD;
pontoTexD.x = ((((float)j) + 1) / slices);
pontoTexD.y = 0.5 + ((((float)i) + 1) / stacks);
vetorNormal vecNormalD;
vecNormalD.x = cos(nivel2)*sin(angulo2);
vecNormalD.y = sin(nivel2);
vecNormalD.z = cos(nivel2)*cos(angulo2);
ponto pontoD;
pontoD.x = radius * cos(nivel2)*sin(angulo2);
pontoD.y = radius * sin(nivel2);
pontoD.z = radius * cos(nivel2)*cos(angulo2);
pontoText pontoTexE;
pontoTexE.x = (((float)j) / slices);
pontoTexE.y = 0.5 + ((((float)i) + 1) / stacks);
vetorNormal vecNormalE;
vecNormalE.x = cos(nivel2)*sin(angulo);
vecNormalE.y = sin(nivel2);
vecNormalE.z = cos(nivel2)*cos(angulo);
ponto pontoE;
pontoE.x = radius * cos(nivel2)*sin(angulo);
pontoE.y = radius * sin(nivel2);
pontoE.z = radius * cos(nivel2)*cos(angulo);
pontoText pontoTexF;
pontoTexF.x = (((float)j) / slices);
pontoTexF.y = 0.5 + (((float)i) / stacks);
vetorNormal vecNormalF;
vecNormalF.x = cos(nivel)*sin(angulo);
vecNormalF.y = sin(nivel);
vecNormalF.z = cos(nivel)*cos(angulo);
ponto pontoF;
pontoF.x = radius * cos(nivel)*sin(angulo);
pontoF.y = radius * sin(nivel);
pontoF.z = radius * cos(nivel)*cos(angulo);
ficheiro << formLine(pontoD, pontoE, pontoF, pontoTexD, pontoTexE, pontoTexF,vecNormalD,vecNormalE,vecNormalF) << endl;
//---------------------------------------------------------------------------------------------------
pontoText pontoTexG;
pontoTexG.x = 1 - ((((float)j)+1) / slices);
pontoTexG.y = 0.5 - (((float)i) / stacks);
vetorNormal vecNormalG;
vecNormalG.x = cos(-nivel)*sin(-angulo);
vecNormalG.y = sin(-nivel);
vecNormalG.z = cos(-nivel)*cos(-angulo);
ponto pontoG;
pontoG.x = radius * cos(-nivel)*sin(-angulo);
pontoG.y = radius * sin(-nivel);
pontoG.z = radius * cos(-nivel)*cos(-angulo);
pontoText pontoTexH;
pontoTexH.x = 1 - (((float)j) / slices);
pontoTexH.y = 0.5 - (((float)i) / stacks);
vetorNormal vecNormalH;
vecNormalH.x = cos(-nivel)*sin(-angulo2);
vecNormalH.y = sin(-nivel);
vecNormalH.z = cos(-nivel)*cos(-angulo2);
ponto pontoH;
pontoH.x = radius * cos(-nivel)*sin(-angulo2);
pontoH.y = radius * sin(-nivel);
pontoH.z = radius * cos(-nivel)*cos(-angulo2);
pontoText pontoTexI;
pontoTexI.x = 1 - (((float)j) / slices);
pontoTexI.y = 0.5 - ((((float)i)+1) / stacks);
vetorNormal vecNormalI;
vecNormalI.x = cos(-nivel2)*sin(-angulo2);
vecNormalI.y = sin(-nivel2);
vecNormalI.z = cos(-nivel2)*cos(-angulo2);
ponto pontoI;
pontoI.x = radius * cos(-nivel2)*sin(-angulo2);
pontoI.y = radius * sin(-nivel2);
pontoI.z = radius * cos(-nivel2)*cos(-angulo2);
ficheiro << formLine(pontoG, pontoH, pontoI,pontoTexG, pontoTexH, pontoTexI,vecNormalG,vecNormalH,vecNormalI) << endl;
//_--------------------------------------------------------------------------------------------------
pontoText pontoTexJ;
pontoTexJ.x = 1 - (((float)j) / slices);
pontoTexJ.y = 0.5 - ((((float)i)+1) / stacks);
vetorNormal vecNormalJ;
vecNormalJ.x = cos(-nivel2)*sin(-angulo2);
vecNormalJ.y = sin(-nivel2);
vecNormalJ.z = cos(-nivel2)*cos(-angulo2);
ponto pontoJ;
pontoJ.x = radius * cos(-nivel2)*sin(-angulo2);
pontoJ.y = radius * sin(-nivel2);
pontoJ.z = radius * cos(-nivel2)*cos(-angulo2);
pontoText pontoTexK;
pontoTexK.x = 1 - ((((float)j)+1) / slices);
pontoTexK.y = 0.5 - ((((float)i)+1) / stacks);
vetorNormal vecNormalK;
vecNormalK.x = cos(-nivel2)*sin(-angulo);
vecNormalK.y = sin(-nivel2);
vecNormalK.z = cos(-nivel2)*cos(-angulo);
ponto pontoK;
pontoK.x = radius * cos(-nivel2)*sin(-angulo);
pontoK.y = radius * sin(-nivel2);
pontoK.z = radius * cos(-nivel2)*cos(-angulo);
pontoText pontoTexW;
pontoTexW.x = 1 - ((((float)j)+1) / slices);
pontoTexW.y = 0.5 - (((float)i) / stacks);
vetorNormal vecNormalW;
vecNormalW.x = cos(-nivel)*sin(-angulo);
vecNormalW.y = sin(-nivel);
vecNormalW.z = cos(-nivel)*cos(-angulo);
ponto pontoW;
pontoW.x = radius * cos(-nivel)*sin(-angulo);
pontoW.y = radius * sin(-nivel);
pontoW.z = radius * cos(-nivel)*cos(-angulo);
ficheiro << formLine(pontoJ, pontoK, pontoW, pontoTexJ,pontoTexK, pontoTexW,vecNormalJ,vecNormalK,vecNormalW) << endl;
}
}
ficheiro.close();
}
}
//----------------------------------------------------------------------------------------------------------------------------------------------
/*CUBE*/
/*Funcao que desenha uma divisão da face que se encontra na parte negativa do eixo dos ZZ*/
void drawSquareBack(char *filename, float x1, float x2, float x3, float y1, float y2, float y3) {
float z1 = x1, z2 = y2, z3 = x3, w1 = y1, w2 = x2, w3 = y3;
std::ofstream ficheiro;
ficheiro.open(filename, std::ofstream::out | std::ofstream::app); // open file for appending
if (ficheiro.is_open()) {
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = z1;
pontoA.y = z2;
pontoA.z = z3;
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = x1;
pontoB.y = x2;
pontoB.z = x3;
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = y1;
pontoC.y = y2;
pontoC.z = y3;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = w1;
pontoD.y = w2;
pontoD.z = w3;
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
ficheiro << formLine(pontoD, pontoC, pontoB,pontoTexD,pontoTexC,pontoTexB,vecNormalD,vecNormalC,vecNormalB) << endl;
}
ficheiro.close();
}
/*Funcao que desenha uma divisão da face que se encontra na parte positiva do eixo dos ZZ*/
void drawSquareFront(char *filename, float x1, float x2, float x3, float y1, float y2, float y3) {
float z1 = x1, z2 = y2, z3 = x3, w1 = y1, w2 = x2, w3 = y3;
std::ofstream ficheiro;
ficheiro.open(filename, std::ofstream::out | std::ofstream::app); // open file for appending
if (ficheiro.is_open()) {
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = x1;
pontoA.y = x2;
pontoA.z = x3;
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = z1;
pontoB.y = z2;
pontoB.z = z3;
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = y1;
pontoC.y = y2;
pontoC.z = y3;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = w1;
pontoD.y = w2;
pontoD.z = w3;
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
ficheiro << formLine(pontoC, pontoD, pontoA,pontoTexC,pontoTexD,pontoTexA,vecNormalC,vecNormalD,vecNormalA) << endl;
}
ficheiro.close();
}
/*Funcao que desenha uma divisão da face que se encontra na parte positiva do eixo dos YY*/
void drawSquareUp(char *filename, float x1, float x2, float x3, float y1, float y2, float y3) {
float z1 = x1, z2 = y2, z3 = y3, w1 = y1, w2 = x2, w3 = x3;
std::ofstream ficheiro;
ficheiro.open(filename, std::ofstream::out | std::ofstream::app); // open file for appending
if (ficheiro.is_open()) {
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = x1;
pontoA.y = x2;
pontoA.z = x3;
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = z1;
pontoB.y = z2;
pontoB.z = z3;
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = y1;
pontoC.y = y2;
pontoC.z = y3;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = w1;
pontoD.y = w2;
pontoD.z = w3;
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
ficheiro << formLine(pontoC, pontoD, pontoA,pontoTexC,pontoTexD,pontoTexA,vecNormalC,vecNormalD,vecNormalA) << endl;
ficheiro.close();
}
}
/*Funcao que desenha uma divisão da face que se encontra na parte negativa do eixo dos YY*/
void drawSquareBase(char *filename, float x1, float x2, float x3, float y1, float y2, float y3) {
float z1 = x1, z2 = y2, z3 = y3, w1 = y1, w2 = x2, w3 = x3;
std::ofstream ficheiro;
ficheiro.open(filename, std::ofstream::out | std::ofstream::app); // open file for appending
if (ficheiro.is_open()) {
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = z1;
pontoA.y = z2;
pontoA.z = z3;
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = x1;
pontoB.y = x2;
pontoB.z = x3;
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = y1;
pontoC.y = y2;
pontoC.z = y3;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = w1;
pontoD.y = w2;
pontoD.z = w3;
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
ficheiro << formLine(pontoD, pontoC, pontoB,pontoTexD,pontoTexC,pontoTexB,vecNormalD,vecNormalC,vecNormalB) << endl;
ficheiro.close();
}
}
/*Funcao que desenha uma divisão da face que se encontra na parte negativa do eixo dos XX*/
void drawSquareLeft(char *filename, float x1, float x2, float x3, float y1, float y2, float y3) {
float z1 = y1, z2 = y2, z3 = x3, w1 = x1, w2 = x2, w3 = y3;
std::ofstream ficheiro;
ficheiro.open(filename, std::ofstream::out | std::ofstream::app); // open file for appending
if (ficheiro.is_open()) {
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = z1;
pontoA.y = z2;
pontoA.z = z3;
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = x1;
pontoB.y = x2;
pontoB.z = x3;
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = y1;
pontoC.y = y2;
pontoC.z = y3;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = w1;
pontoD.y = w2;
pontoD.z = w3;
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
ficheiro << formLine(pontoD, pontoC, pontoB,pontoTexD,pontoTexC,pontoTexB,vecNormalD,vecNormalC,vecNormalB) << endl;
ficheiro.close();
}
}
/*Funcao que desenha uma divisão da face que se encontra na parte ṕositiva do eixo dos XX*/
void drawSquareRight(char *filename, float x1, float x2, float x3, float y1, float y2, float y3) {
float z1 = y1, z2 = y2, z3 = x3, w1 = x1, w2 = x2, w3 = y3;
std::ofstream ficheiro;
ficheiro.open(filename, std::ofstream::out | std::ofstream::app); // open file for appending
if (ficheiro.is_open()) {
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = x1;
pontoA.y = x2;
pontoA.z = x3;
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = z1;
pontoB.y = z2;
pontoB.z = z3;
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = y1;
pontoC.y = y2;
pontoC.z = y3;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = w1;
pontoD.y = w2;
pontoD.z = w3;
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
ficheiro << formLine(pontoC, pontoD, pontoA,pontoTexC,pontoTexD,pontoTexA,vecNormalC,vecNormalD,vecNormalA) << endl;
ficheiro.close();
}
}
/*Funcao principal que junta as faces da caixa, usando funções auxiliares para construir essas mesmas faces*/
void drawBox(char *filename, float xDimensions, float altura, float comprimento, int divisions) {
//cleanFile(filename);
float deltaa = xDimensions / divisions;
float deltab = altura / divisions;
//conta o número de triângulos que compõe a caixa
float value = (divisions*divisions) * 2 * 6;
float bi = -altura / 2;
float ai = xDimensions / 2;
ofstream ficheiro;
ficheiro.open(filename);
if (ficheiro.is_open()) {
ficheiro.clear();
//escrever no ficheiro o número de triângulos que compôe a caixa
ficheiro << writeLineNumber(value);
}
ficheiro.close();
//desenhar as faces do eixo dos ZZ
for (int i = 1; i <= divisions; i++) {
for (int j = 1; j <= divisions; j++) {
drawSquareBack(filename, ai, bi, -comprimento / 2,
ai - deltaa, bi + deltab, -comprimento / 2);
drawSquareFront(filename, ai, bi, comprimento / 2,
ai - deltaa, bi + deltab, comprimento / 2);
ai = (xDimensions / 2) - j * deltaa;
}
bi = (-altura / 2) + i * deltab;
ai = xDimensions / 2;
}
//--------------------------------------------------------------------------------------------------------------------------
float deltaX = xDimensions / divisions;
float deltaZ = comprimento / divisions;
float auxDimensions = xDimensions / 2;
float auxComprimento = comprimento / 2;
float xi = xDimensions / 2;
float zi = comprimento / 2;
//desenhar as faces do eixo dos YY
for (int i = 1; i <= divisions; i++) {
for (int j = 1; j <= divisions; j++) {
drawSquareBase(filename, xi, -altura / 2, zi,
xi - deltaX, -altura / 2, zi - deltaZ);
drawSquareUp(filename, xi, altura / 2, zi,
xi - deltaX, altura / 2, zi - deltaZ);
xi = (xDimensions / 2) - j * deltaX;
}
zi = (comprimento / 2) - (i * deltaZ);
xi = (xDimensions / 2);
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------
float deltaY1 = altura / divisions;
float deltaZ1 = comprimento / divisions;
float yy = -altura / 2;
float zz = -comprimento / 2;
//desenhar as faces do eixo dos XX
for (int i = 1; i <= divisions; i++) {
for (int j = 1; j <= divisions; j++) {
drawSquareRight(filename, xDimensions / 2, yy, zz,
xDimensions / 2, yy + deltaY1, zz + deltaZ1);
drawSquareLeft(filename, -xDimensions / 2, yy, zz,
-xDimensions / 2, yy + deltaY1, zz + deltaZ1);
zz = -comprimento / 2 + j * deltaZ1;
}
yy = (-altura / 2) + (i * deltaY1);
zz = -comprimento / 2;
}
}
void drawDisk(char* filename, float dist, float raioCentro, int slices) {
float alpha, dAlpha, pAlpha;
float value = 4 * slices;
dAlpha = (2.0f * M_PI) / slices;
ofstream ficheiro;
ficheiro.open(filename);
if (ficheiro.is_open()) {
ficheiro.clear();
ficheiro << writeLineNumber(value);
//em cada iteração do ciclo, são desenhados 2 triângulos
for (int i = 0; i < slices; i++) {
alpha = i * dAlpha;
pAlpha = alpha + dAlpha;
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.x = raioCentro * cosf(alpha);
pontoA.y = 0.0;
pontoA.z = raioCentro * sinf(alpha);
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.x = raioCentro * cosf(pAlpha);
pontoB.y = 0.0;
pontoB.z = raioCentro * sinf(pAlpha);
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.x = (raioCentro + dist) * cosf(pAlpha);
pontoC.y = 0.0;
pontoC.z = (raioCentro + dist) * sinf(pAlpha);
ficheiro << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.x = (raioCentro + dist) * cosf(pAlpha);
pontoD.y = 0.0;
pontoD.z = (raioCentro + dist) * sinf(pAlpha);
pontoText pontoTexE;
pontoTexE.x = 0;
pontoTexE.y = 0;
vetorNormal vecNormalE;
vecNormalE.x = 0;
vecNormalE.y = 0;
vecNormalE.z = 0;
ponto pontoE;
pontoE.x = (raioCentro + dist) * cosf(alpha);
pontoE.y = 0.0;
pontoE.z = (raioCentro + dist) * sinf(alpha);
pontoText pontoTexF;
pontoTexF.x = 0;
pontoTexF.y = 0;
vetorNormal vecNormalF;
vecNormalF.x = 0;
vecNormalF.y = 0;
vecNormalF.z = 0;
ponto pontoF;
pontoF.x = raioCentro * cosf(alpha);
pontoF.y = 0.0;
pontoF.z = raioCentro * sinf(alpha);
ficheiro << formLine(pontoD, pontoE, pontoF,pontoTexD,pontoTexE,pontoTexF,vecNormalD,vecNormalE,vecNormalF) << endl;
}
for (int i = 0; i < slices; i++) {
alpha = i * dAlpha;
pAlpha = alpha + dAlpha;
pontoText pontoTexG;
pontoTexG.x = 0;
pontoTexG.y = 0;
vetorNormal vecNormalG;
vecNormalG.x = 0;
vecNormalG.y = 0;
vecNormalG.z = 0;
ponto pontoG;
pontoG.y = 0.0;
pontoG.x = raioCentro * cosf(-alpha);
pontoG.z = raioCentro * sinf(-alpha);
pontoText pontoTexH;
pontoTexH.x = 0;
pontoTexH.y = 0;
vetorNormal vecNormalH;
vecNormalH.x = 0;
vecNormalH.y = 0;
vecNormalH.z = 0;
ponto pontoH;
pontoH.y = 0.0;
pontoH.x = raioCentro * cosf(-pAlpha);
pontoH.z = raioCentro * sinf(-pAlpha);
pontoText pontoTexI;
pontoTexI.x = 0;
pontoTexI.y = 0;
vetorNormal vecNormalI;
vecNormalI.x = 0;
vecNormalI.y = 0;
vecNormalI.z = 0;
ponto pontoI;
pontoI.y = 0.0;
pontoI.x = (raioCentro + dist) * cosf(-pAlpha);
pontoI.z = (raioCentro + dist) * sinf(-pAlpha);
ficheiro << formLine(pontoG, pontoH, pontoI,pontoTexG,pontoTexH,pontoTexI,vecNormalG,vecNormalH,vecNormalI) << endl;
pontoText pontoTexJ;
pontoTexJ.x = 0;
pontoTexJ.y = 0;
vetorNormal vecNormalJ;
vecNormalJ.x = 0;
vecNormalJ.y = 0;
vecNormalJ.z = 0;
ponto pontoJ;
pontoJ.y = 0.0;
pontoJ.x = (raioCentro + dist) * cosf(-pAlpha);
pontoJ.z = (raioCentro + dist) * sinf(-pAlpha);
pontoText pontoTexK;
pontoTexK.x = 0;
pontoTexK.y = 0;
vetorNormal vecNormalK;
vecNormalK.x = 0;
vecNormalK.y = 0;
vecNormalK.z = 0;
ponto pontoK;
pontoK.y = 0.0;
pontoK.x = (raioCentro + dist) * cosf(-alpha);
pontoK.z = (raioCentro + dist) * sinf(-alpha);
pontoText pontoTexL;
pontoTexL.x = 0;
pontoTexL.y = 0;
vetorNormal vecNormalL;
vecNormalL.x = 0;
vecNormalL.y = 0;
vecNormalL.z = 0;
ponto pontoL;
pontoL.y = 0.0;
pontoL.x = raioCentro * cosf(-alpha);
pontoL.z = raioCentro * sinf(-alpha);
ficheiro << formLine(pontoJ, pontoK, pontoL,pontoTexJ,pontoTexK,pontoTexL,vecNormalJ,vecNormalK,vecNormalL) << endl;
}
ficheiro.close();
}
}
ponto *cpoints; // control points
int **indexes; // indexes of the points for each patch
int patches; // number of patches
int ncpoints; // number of control points
void cross(float *a, float *b, float *res) {
res[0] = a[1] * b[2] - a[2] * b[1];
res[1] = a[2] * b[0] - a[0] * b[2];
res[2] = a[0] * b[1] - a[1] * b[0];
}
float comprimento(float *v) {
float res = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
return res;
}
void normalize(float *a) {
float l = comprimento(a);
if (l == 0.0f)
return;
a[0] = a[0] / l;
a[1] = a[1] / l;
a[2] = a[2] / l;
}
void matrixVector(float *m, float *v, float *res) {
for (int j = 0; j < 4; ++j) {
res[j] = 0;
for (int k = 0; k < 4; ++k) {
res[j] += v[k] * m[j * 4 + k];
}
}
}
void multVectorMatrix(float *v, float *m, float *res) {
for (int i = 0; i < 4; ++i) {
res[i] = 0;
for (int j = 0; j < 4; ++j) {
res[i] += v[j] * m[j * 4 + i];
}
}
}
void multMatrixMatrix(float *m1, float *m2, float *res) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
res[i * 4 + j] = 0.0f;
for (int k = 0; k < 4; ++k)
res[i * 4 + j] += m1[i * 4 + k] * m2[k * 4 + j];
}
}
}
void bezierPoint(float u, float v, ponto *pv, float *res) {
float dU[3];
float dV[3];
float m[4][4] = {
{ -1.0f, 3.0f, -3.0f, 1.0f },
{ 3.0f, -6.0f, 3.0f, 0.0f },
{ -3.0f, 3.0f, 0.0f, 0.0f },
{ 1.0f, 0.0f, 0.0f, 0.0f }
};
float Px[4][4] = {
{ pv[0].x, pv[1].x, pv[2].x, pv[3].x },
{ pv[4].x, pv[5].x, pv[6].x, pv[7].x },
{ pv[8].x, pv[9].x, pv[10].x, pv[11].x },
{ pv[12].x, pv[13].x, pv[14].x, pv[15].x }
};
float Py[4][4] = {
{ pv[0].y, pv[1].y, pv[2].y, pv[3].y },
{ pv[4].y, pv[5].y, pv[6].y, pv[7].y },
{ pv[8].y, pv[9].y, pv[10].y, pv[11].y },
{ pv[12].y, pv[13].y, pv[14].y, pv[15].y }
};
float Pz[4][4] = {
{ pv[0].z, pv[1].z, pv[2].z, pv[3].z },
{ pv[4].z, pv[5].z, pv[6].z, pv[7].z },
{ pv[8].z, pv[9].z, pv[10].z, pv[11].z },
{ pv[12].z, pv[13].z, pv[14].z, pv[15].z }
};
float U[4] = { u * u * u, u * u, u, 1 };
float UD[4] = { 3 * u * u, 2 * u, 1, 0 };
float V[4] = { v * v * v, v * v, v, 1 };
float VD[4] = { 3 * v * v, 2 * v, 1, 0 };
float MdV[4];
float MV[4];
matrixVector((float *)m, V, MV);
matrixVector((float *)m, VD, MdV);
float dUM[4];
float UM[4];
multVectorMatrix(U, (float *)m, UM);
multVectorMatrix(UD, (float *)m, dUM);
float UMP[3][4];
multVectorMatrix(UM, (float *)Px, UMP[0]);
multVectorMatrix(UM, (float *)Py, UMP[1]);
multVectorMatrix(UM, (float *)Pz, UMP[2]);
float dUMP[3][4];
multVectorMatrix(dUM, (float *)Px, dUMP[0]);
multVectorMatrix(dUM, (float *)Py, dUMP[1]);
multVectorMatrix(dUM, (float *)Pz, dUMP[2]);
for (int j = 0; j < 3; j++) {
res[j] = 0.0f;
dU[j] = 0.0f;
dV[j] = 0.0f;
for (int i = 0; i < 4; i++) {
res[j] += MV[i] * UMP[j][i];
dU[j] += MV[i] * dUMP[j][i];
dV[j] += MdV[i] * UMP[j][i];
}
}
}
int geradorBezier(char *outfile, int tesselation) {
int linhas = 0;
ponto pv[16];
int divs = tesselation; // change this to change the tesselation level
ostringstream pontos;
ofstream out;
out.open(outfile);
if (!out.is_open()) {
perror("ofstream.open");
return 1;
}
for (int i = 0; i < patches; i++) {
for (int j = 0; j < 16; j++) {
pv[j] = cpoints[indexes[i][j]];
}
for (int u = 0; u < divs; u++) {
float p1[3];
float p2[3];
float p3[3];
float p4[3];
for (int v = 0; v < divs; v++) {
bezierPoint(u / (float)divs, v / (float)divs, pv, p1);
bezierPoint((u + 1) / (float)divs, v / (float)divs, pv, p2);
bezierPoint(u / (float)divs, (v + 1) / (float)divs, pv, p3);
bezierPoint((u + 1) / (float)divs, (v + 1) / (float)divs, pv, p4);
pontoText pontoTexA;
pontoTexA.x = 0;
pontoTexA.y = 0;
vetorNormal vecNormalA;
vecNormalA.x = 0;
vecNormalA.y = 0;
vecNormalA.z = 0;
ponto pontoA;
pontoA.y = p1[0];
pontoA.x = p1[1];
pontoA.z = p1[2];
pontoText pontoTexB;
pontoTexB.x = 0;
pontoTexB.y = 0;
vetorNormal vecNormalB;
vecNormalB.x = 0;
vecNormalB.y = 0;
vecNormalB.z = 0;
ponto pontoB;
pontoB.y = p3[0];
pontoB.x = p3[1];
pontoB.z = p3[2];
pontoText pontoTexC;
pontoTexC.x = 0;
pontoTexC.y = 0;
vetorNormal vecNormalC;
vecNormalC.x = 0;
vecNormalC.y = 0;
vecNormalC.z = 0;
ponto pontoC;
pontoC.y = p4[0];
pontoC.x = p4[1];
pontoC.z = p4[2];
pontos << formLine(pontoA, pontoB, pontoC,pontoTexA,pontoTexB,pontoTexC,vecNormalA,vecNormalB,vecNormalC) << endl;
pontoText pontoTexD;
pontoTexD.x = 0;
pontoTexD.y = 0;
vetorNormal vecNormalD;
vecNormalD.x = 0;
vecNormalD.y = 0;
vecNormalD.z = 0;
ponto pontoD;
pontoD.y = p2[0];
pontoD.x = p2[1];
pontoD.z = p2[2];
pontoText pontoTexE;
pontoTexE.x = 0;
pontoTexE.y = 0;
vetorNormal vecNormalE;
vecNormalE.x = 0;
vecNormalE.y = 0;
vecNormalE.z = 0;
ponto pontoE;
pontoE.y = p1[0];
pontoE.x = p1[1];
pontoE.z = p1[2];
pontoText pontoTexF;
pontoTexF.x = 0;
pontoTexF.y = 0;
vetorNormal vecNormalF;
vecNormalF.x = 0;
vecNormalF.y = 0;
vecNormalF.z = 0;
ponto pontoF;
pontoF.y = p4[0];
pontoF.x = p4[1];
pontoF.z = p4[2];
pontos << formLine(pontoD, pontoE, pontoF,pontoTexD,pontoTexE,pontoTexF,vecNormalD,vecNormalE,vecNormalF) << endl;
linhas += 2;
}
}
}
out << (to_string(linhas) + "\n" + pontos.str());
out.close();
return 0;
}
int bezierPatch(char *patch) {
int lIndex;
int i, j;
char line[BUFF_SIZE];
FILE *f = fopen(patch, "r");
if (!f)
return 1;
fscanf(f, "%d\n", &lIndex);
patches = lIndex;
printf("%d\n", patches);
indexes = (int **)malloc(sizeof(int *) * lIndex);
if (!indexes)
return 1;
for (i = 0; i < lIndex; i++) {
indexes[i] = (int *)malloc(sizeof(int) * 16);
if (!indexes[i]) {
// free previously allocated memory before returning non zero
for (--i; i >= 0; --i) {
free(indexes[i]);
}
free(indexes);
return 1;
}
memset(line, 0, BUFF_SIZE);
fgets(line, BUFF_SIZE, f);
char* ind = NULL;
for (j = 0, ind = strtok(line, ", "); ind && j < 16; ind = strtok(NULL, ", "), j++)
indexes[i][j] = atoi(ind);
}
fscanf(f, "%d\n", &ncpoints);
cpoints = (ponto *)malloc(sizeof(ponto) * ncpoints);
if (!cpoints) {
for (i = 0; i < lIndex; i++) {
free(indexes[i]);
}
free(indexes);
return 1;
}
for (i = 0; i < ncpoints; i++) {
memset(line, 0, BUFF_SIZE);
fgets(line, BUFF_SIZE, f);
cpoints[i].x = atof(strtok(line, ", "));
cpoints[i].y = atof(strtok(NULL, ", "));
cpoints[i].z = atof(strtok(NULL, ", "));
}
fclose(f);
return 0;
}
int main(int argc, char *argv[]) {
if (argc <= 1) {
cout << "Try one of this words: plane | cone | sphere | box" << endl;
}
//--------------------------------------------------------------------------------------------------------------------------------------
else if (!strcmp(argv[1], "plane")) {
if (argc != 4) {
cout << "Try this: 'generator' plane' <size> <file name>" << endl;
return 0;
}
else {
float tamanho = atof(argv[2]);
drawPlane(argv[3], tamanho);
}
}
//--------------------------------------------------------------------------------------------------------------------------------------
else if (!strcmp(argv[1], "cone")) {
if (argc != 7) {
cout << "Try this: 'generator' 'cone' <radius> <height> <slices> <stacks> <file name>" << endl;
return 0;
}
else {
float radius = atof(argv[2]);
float height = atof(argv[3]);
int slices = atoi(argv[4]);
int stacks = atoi(argv[5]);
drawCone(argv[6], radius, height, slices, stacks);
}
}
//------------------------------------------------------------------------------------------------------------------------------------
else if (!strcmp(argv[1], "sphere")) {
if (argc != 6) {
cout << "Try this: 'generator' 'sphere' <radius> <slices> <stacks> <file name>" << endl;
return 0;
}
else {
float radius = atof(argv[2]);
int slices = atoi(argv[3]);
int stacks = atoi(argv[4]);
drawSphere(argv[5], radius, slices, stacks);
}
}
//-----------------------------------------------------------------------------------------------------------------------------------
else if (!strcmp(argv[1], "box")) {
if (argc != 7) {
cout << "Try this: 'generator' 'box' <xDimensions> <yDimensions> <zDimensions> <divisions> <file name>" << endl;
return 0;
}
else {
float xDimensions = atof(argv[2]);
float altura = atof(argv[3]);
float comprimento = atof(argv[4]);
int divisions = atoi(argv[5]);
drawBox(argv[6], xDimensions, altura, comprimento, divisions);
}
}
//-------------------------------------------------------------------------------------------
else if (!strcmp(argv[1], "disk")) {
if (argc != 6) {
cout << "Try this: 'generator' 'disk' <distance> <radiusCentre> <slices> <file name>" << endl;
return 0;
}
else {
float distancia = atof(argv[2]);
float raioCentro = atof(argv[3]);
int slices = atoi(argv[4]);
drawDisk(argv[5], distancia, raioCentro, slices);
}
}
else if (!strcmp(argv[1], "bezier")) {
if (argc != 5) {
cout << "Try this: 'generator' 'bezier' <tesselation> <patch> <file name>" << endl;
return 0;
}
else {
int res = bezierPatch(argv[3]);
if (!res) res = geradorBezier(argv[4], atoi(argv[2]));
}
}
return 0;
} | [
"brunocveloso@sapo.pt"
] | brunocveloso@sapo.pt |
cfa85c44adabf84a5ccb21eca444245b8c460abb | 0a1be59f55b359866370c2815671af22bd96ff51 | /dependencies/skse64/src/skse64/skse64/Hooks_SaveLoad.cpp | 66763c225c32956b043394176393c0721c80a34d | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | joelday/papyrus-debug-server | ba18b18d313a414daefdf0d3472b60a12ca21385 | f5c3878cd485ba68aaadf39bb830ca88bf53bfff | refs/heads/master | 2023-01-12T14:34:52.919190 | 2019-12-06T18:41:39 | 2019-12-06T18:41:39 | 189,772,905 | 15 | 10 | MIT | 2022-12-27T11:31:04 | 2019-06-01T20:02:31 | C++ | UTF-8 | C++ | false | false | 4,933 | cpp | #include "Hooks_SaveLoad.h"
#include "skse64_common/SafeWrite.h"
#include "skse64_common/Utilities.h"
#include "skse64_common/BranchTrampoline.h"
#include "Serialization.h"
#include "GlobalLocks.h"
#include "GameData.h"
#include "GameMenus.h"
#include "PapyrusVM.h"
#include "PluginManager.h"
void BGSSaveLoadManager::SaveGame_Hook(UInt64 *unk0)
{
const char *saveName = reinterpret_cast<const char *>(unk0[0xBB0 / 8]);
// Game actually does this, we may as well do the same
if (!saveName)
saveName = "";
#ifdef DEBUG
_MESSAGE("Executing BGSSaveLoadManager::SaveGame_Hook. saveName: %s", saveName);
#endif
Serialization::SetSaveName(saveName);
PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_SaveGame, (void*)saveName, strlen(saveName), NULL);
CALL_MEMBER_FN(this, SaveGame_HookTarget)(unk0);
Serialization::SetSaveName(NULL);
#ifdef DEBUG
_MESSAGE("Executed BGSSaveLoadManager::SaveGame_Hook.");
#endif
}
bool BGSSaveLoadManager::LoadGame_Hook(UInt64 *unk0, UInt32 unk1, UInt32 unk2, void *unk3)
{
const char *saveName = reinterpret_cast<const char *>(unk0[0xBB0 / 8]);
// Game actually does this, we may as well do the same
if (!saveName)
saveName = "";
#ifdef DEBUG
_MESSAGE("Executing BGSSaveLoadManager::LoadGame_Hook. saveName: %s", saveName);
#endif
g_loadGameLock.Enter();
Serialization::SetSaveName(saveName);
PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_PreLoadGame, (void*)saveName, strlen(saveName), NULL);
bool result = CALL_MEMBER_FN(this, LoadGame_HookTarget)(unk0, unk1, unk2, unk3);
PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_PostLoadGame, (void*)result, 1, NULL);
Serialization::SetSaveName(NULL);
g_loadGameLock.Leave();
// Clear invalid handles in OnUpdate event registration list
UInt32 enableClearRegs = 0;
if(GetConfigOption_UInt32("General", "ClearInvalidRegistrations", &enableClearRegs))
{
if(enableClearRegs)
{
UInt32 count = (*g_skyrimVM)->ClearInvalidRegistrations();
if (count > 0)
_MESSAGE("ClearInvalidRegistrations: Removed %d invalid OnUpdate registration(s)", count);
}
}
#ifdef DEBUG
_MESSAGE("Executed BGSSaveLoadManager::LoadGame_Hook.");
#endif
return result;
}
bool s_requestedSave = false;
bool s_requestedLoad = false;
std::string s_reqSaveName;
std::string s_reqLoadName;
void BGSSaveLoadManager::RequestSave(const char * name)
{
s_requestedSave = true;
s_reqSaveName = name;
}
void BGSSaveLoadManager::RequestLoad(const char * name)
{
s_requestedLoad = true;
s_reqLoadName = name;
}
void BGSSaveLoadManager::ProcessEvents_Hook(void)
{
CALL_MEMBER_FN(this, ProcessEvents_Internal)();
// wants both? gets nothing.
if(s_requestedSave && s_requestedLoad)
_MESSAGE("BGSSaveLoadManager: save and load requested in the same frame, ignoring both");
else if(s_requestedSave)
Save(s_reqSaveName.c_str());
else if(s_requestedLoad)
Load(s_reqLoadName.c_str());
s_requestedSave = false;
s_requestedLoad = false;
s_reqSaveName.clear();
s_reqLoadName.clear();
}
void BGSSaveLoadManager::DeleteSavegame_Hook(const char * saveNameIn, UInt32 unk1)
{
std::string saveName = saveNameIn;
PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_DeleteGame, (void*)saveName.c_str(), strlen(saveName.c_str()), NULL);
CALL_MEMBER_FN(this, DeleteSavegame)(saveNameIn, unk1);
Serialization::HandleDeleteSave(saveName);
}
UInt8 TESQuest::NewGame_Hook(UInt8 * unk1, UInt8 unk2)
{
UInt8 ret = CALL_MEMBER_FN(this, NewGame_Internal)(unk1, unk2);
PluginManager::Dispatch_Message(0, SKSEMessagingInterface::kMessage_NewGame, (void*)this, sizeof(void*), NULL);
return ret;
}
RelocAddr <uintptr_t> SaveGame_HookTarget_Enter(0x00586DE0 + 0x18B);
RelocAddr <uintptr_t> SaveGame2_HookTarget_Enter(0x005875F0 + 0x138);
RelocAddr <uintptr_t> LoadGame_HookTarget_Enter(0x0058AE30 + 0x26C);
RelocAddr <uintptr_t> ProcessEvents_Enter(0x005B2FF0 + 0x7F);
RelocAddr <uintptr_t> NewGame_Enter(0x008A20E0 + 0x59);
RelocAddr <uintptr_t> DeleteSaveGame_Enter(0x005794C0 + 0x77);
RelocAddr <uintptr_t> DeleteSaveGame_Enter2(0x00579590 + 0x17);
void Hooks_SaveLoad_Commit(void)
{
// Load & Save
g_branchTrampoline.Write5Call(SaveGame_HookTarget_Enter, GetFnAddr(&BGSSaveLoadManager::SaveGame_Hook));
g_branchTrampoline.Write5Call(SaveGame2_HookTarget_Enter, GetFnAddr(&BGSSaveLoadManager::SaveGame_Hook));
g_branchTrampoline.Write5Call(LoadGame_HookTarget_Enter, GetFnAddr(&BGSSaveLoadManager::LoadGame_Hook));
g_branchTrampoline.Write5Call(ProcessEvents_Enter, GetFnAddr(&BGSSaveLoadManager::ProcessEvents_Hook));
// New Game
g_branchTrampoline.Write5Call(NewGame_Enter, GetFnAddr(&TESQuest::NewGame_Hook));
// Delete savegame
g_branchTrampoline.Write5Call(DeleteSaveGame_Enter, GetFnAddr(&BGSSaveLoadManager::DeleteSavegame_Hook));
g_branchTrampoline.Write5Call(DeleteSaveGame_Enter2, GetFnAddr(&BGSSaveLoadManager::DeleteSavegame_Hook));
}
| [
"joelday@gmail.com"
] | joelday@gmail.com |
466c330e80ffdb5c0667fbcbb3ab44e91a4c2811 | ab1fce5113767f53936ef01e6b22a22a543cfa9e | /classifiers/bro-2.1/aux/binpac/binpac-0.34/src/pac_strtype.cc | 48e1eb5ad0f658559c4e5e7df10bcdc0b076c136 | [
"BSD-2-Clause"
] | permissive | kpdyer/dpi-test-suite | 2d7d2f9cff003ac6aa50fbc61f3df3e875466f36 | c9e78f9d7adfc3e3818033192c4486b56b776e6b | refs/heads/master | 2020-06-01T20:07:53.607205 | 2014-06-21T01:54:28 | 2014-06-21T01:54:28 | 21,042,777 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 8,720 | cc | #include "pac_attr.h"
#include "pac_btype.h"
#include "pac_cstr.h"
#include "pac_dataptr.h"
#include "pac_exception.h"
#include "pac_expr.h"
#include "pac_exttype.h"
#include "pac_id.h"
#include "pac_output.h"
#include "pac_regex.h"
#include "pac_strtype.h"
#include "pac_varfield.h"
const char *StringType::kStringTypeName = "bytestring";
const char *StringType::kConstStringTypeName = "const_bytestring";
StringType::StringType(StringTypeEnum anystr)
: Type(STRING), type_(ANYSTR), str_(0), regex_(0)
{
ASSERT(anystr == ANYSTR);
init();
}
StringType::StringType(ConstString *str)
: Type(STRING), type_(CSTR), str_(str), regex_(0)
{
init();
}
StringType::StringType(RegEx *regex)
: Type(STRING), type_(REGEX), str_(0), regex_(regex)
{
ASSERT(regex_);
init();
}
void StringType::init()
{
string_length_var_field_ = 0;
elem_datatype_ = new BuiltInType(BuiltInType::UINT8);
}
StringType::~StringType()
{
// TODO: Unref for Objects
// Question: why Unref?
//
// Unref(str_);
// Unref(regex_);
delete string_length_var_field_;
delete elem_datatype_;
}
Type *StringType::DoClone() const
{
StringType *clone;
switch ( type_ )
{
case ANYSTR:
clone = new StringType(ANYSTR);
break;
case CSTR:
clone = new StringType(str_);
break;
case REGEX:
clone = new StringType(regex_);
break;
default:
ASSERT(0);
return 0;
}
return clone;
}
bool StringType::DefineValueVar() const
{
return true;
}
string StringType::DataTypeStr() const
{
return strfmt("%s",
persistent() ? kStringTypeName : kConstStringTypeName);
}
Type *StringType::ElementDataType() const
{
return elem_datatype_;
}
void StringType::ProcessAttr(Attr *a)
{
Type::ProcessAttr(a);
switch ( a->type() )
{
case ATTR_CHUNKED:
{
if ( type_ != ANYSTR )
{
throw Exception(a,
"&chunked can be applied"
" to only type bytestring");
}
attr_chunked_ = true;
SetBoundaryChecked();
}
break;
case ATTR_RESTOFDATA:
{
if ( type_ != ANYSTR )
{
throw Exception(a,
"&restofdata can be applied"
" to only type bytestring");
}
attr_restofdata_ = true;
// As the string automatically extends to the end of
// data, we do not have to check boundary.
SetBoundaryChecked();
}
break;
case ATTR_RESTOFFLOW:
{
if ( type_ != ANYSTR )
{
throw Exception(a,
"&restofflow can be applied"
" to only type bytestring");
}
attr_restofflow_ = true;
// As the string automatically extends to the end of
// flow, we do not have to check boundary.
SetBoundaryChecked();
}
break;
default:
break;
}
}
void StringType::Prepare(Env* env, int flags)
{
if ( (flags & TO_BE_PARSED) && StaticSize(env) < 0 )
{
ID *string_length_var = new ID(fmt("%s_string_length",
value_var() ? value_var()->Name() : "val"));
string_length_var_field_ = new TempVarField(
string_length_var, extern_type_int->Clone());
string_length_var_field_->Prepare(env);
}
Type::Prepare(env, flags);
}
void StringType::GenPubDecls(Output* out_h, Env* env)
{
Type::GenPubDecls(out_h, env);
}
void StringType::GenPrivDecls(Output* out_h, Env* env)
{
Type::GenPrivDecls(out_h, env);
}
void StringType::GenInitCode(Output* out_cc, Env* env)
{
Type::GenInitCode(out_cc, env);
}
void StringType::GenCleanUpCode(Output* out_cc, Env* env)
{
Type::GenCleanUpCode(out_cc, env);
if ( persistent() )
out_cc->println("%s.free();", env->LValue(value_var()));
}
void StringType::DoMarkIncrementalInput()
{
if ( attr_restofflow_ )
{
// Do nothing
ASSERT(type_ == ANYSTR);
}
else
{
Type::DoMarkIncrementalInput();
}
}
int StringType::StaticSize(Env* env) const
{
switch ( type_ )
{
case CSTR:
// Use length of the unescaped string
return str_->unescaped().length();
case REGEX:
// TODO: static size for a regular expression?
case ANYSTR:
return -1;
default:
ASSERT(0);
return -1;
}
}
const ID *StringType::string_length_var() const
{
return string_length_var_field_ ? string_length_var_field_->id() : 0;
}
void StringType::GenDynamicSize(Output* out_cc, Env* env,
const DataPtr& data)
{
ASSERT(StaticSize(env) < 0);
DEBUG_MSG("Generating dynamic size for string `%s'\n",
value_var()->Name());
if ( env->Evaluated(string_length_var()) )
return;
string_length_var_field_->GenTempDecls(out_cc, env);
switch ( type_ )
{
case ANYSTR:
GenDynamicSizeAnyStr(out_cc, env, data);
break;
case CSTR:
ASSERT(0);
break;
case REGEX:
// TODO: static size for a regular expression?
GenDynamicSizeRegEx(out_cc, env, data);
break;
}
if ( ! incremental_input() && AddSizeVar(out_cc, env) )
{
out_cc->println("%s = %s;",
env->LValue(size_var()),
env->RValue(string_length_var()));
env->SetEvaluated(size_var());
}
}
string StringType::GenStringSize(Output* out_cc, Env* env,
const DataPtr& data)
{
int static_size = StaticSize(env);
if ( static_size >= 0 )
return strfmt("%d", static_size);
GenDynamicSize(out_cc, env, data);
return env->RValue(string_length_var());
}
void StringType::DoGenParseCode(Output* out_cc, Env* env,
const DataPtr& data, int flags)
{
string str_size = GenStringSize(out_cc, env, data);
// Generate additional checking
switch ( type_ )
{
case CSTR:
GenCheckingCStr(out_cc, env, data, str_size);
break;
case REGEX:
case ANYSTR:
break;
}
if ( ! anonymous_value_var() )
{
// Set the value variable
out_cc->println("// check for negative sizes");
out_cc->println("if ( %s < 0 )",
str_size.c_str());
out_cc->println("throw ExceptionInvalidStringLength(\"%s\", %s);",
Location(), str_size.c_str());
out_cc->println("%s.init(%s, %s);",
env->LValue(value_var()),
data.ptr_expr(),
str_size.c_str());
}
if ( parsing_complete_var() )
{
out_cc->println("%s = true;",
env->LValue(parsing_complete_var()));
}
}
void StringType::GenStringMismatch(Output* out_cc, Env* env,
const DataPtr& data, const char *pattern)
{
out_cc->println("throw ExceptionStringMismatch(\"%s\", %s, %s);",
Location(),
pattern,
fmt("string((const char *) (%s), (const char *) %s).c_str()",
data.ptr_expr(),
env->RValue(end_of_data)));
}
void StringType::GenCheckingCStr(Output* out_cc, Env* env,
const DataPtr& data, const string &str_size)
{
// TODO: extend it for dynamic strings
ASSERT(type_ == CSTR);
GenBoundaryCheck(out_cc, env, data);
string str_val = str_->str();
// Compare the string and report error on mismatch
out_cc->println("if ( memcmp(%s, %s, %s) != 0 )",
data.ptr_expr(),
str_val.c_str(),
str_size.c_str());
out_cc->inc_indent();
out_cc->println("{");
GenStringMismatch(out_cc, env, data, str_val.c_str());
out_cc->println("}");
out_cc->dec_indent();
}
void StringType::GenDynamicSizeRegEx(Output* out_cc, Env* env,
const DataPtr& data)
{
// string_length_var =
// matcher.match_prefix(
// begin,
// end);
out_cc->println("%s = ",
env->LValue(string_length_var()));
out_cc->inc_indent();
out_cc->println("%s.%s(",
env->RValue(regex_->matcher_id()),
RegEx::kMatchPrefix);
out_cc->inc_indent();
out_cc->println("%s,",
data.ptr_expr());
out_cc->println("%s - %s);",
env->RValue(end_of_data),
data.ptr_expr());
out_cc->dec_indent();
out_cc->dec_indent();
env->SetEvaluated(string_length_var());
out_cc->println("if ( %s < 0 )",
env->RValue(string_length_var()));
out_cc->inc_indent();
out_cc->println("{");
GenStringMismatch(out_cc, env, data,
fmt("\"%s\"", regex_->str().c_str()));
out_cc->println("}");
out_cc->dec_indent();
}
void StringType::GenDynamicSizeAnyStr(Output* out_cc, Env* env,
const DataPtr& data)
{
ASSERT(type_ == ANYSTR);
if ( attr_restofdata_ || attr_oneline_ )
{
out_cc->println("%s = (%s) - (%s);",
env->LValue(string_length_var()),
env->RValue(end_of_data),
data.ptr_expr());
}
else if ( attr_restofflow_ )
{
out_cc->println("%s = (%s) - (%s);",
env->LValue(string_length_var()),
env->RValue(end_of_data),
data.ptr_expr());
}
else if ( attr_length_expr_ )
{
out_cc->println("%s = %s;",
env->LValue(string_length_var()),
attr_length_expr_->EvalExpr(out_cc, env));
}
else
{
throw Exception(this,
"cannot determine length of bytestring");
}
env->SetEvaluated(string_length_var());
}
bool StringType::DoTraverse(DataDepVisitor *visitor)
{
if ( ! Type::DoTraverse(visitor) )
return false;
switch ( type_ )
{
case ANYSTR:
case CSTR:
case REGEX:
break;
}
return true;
}
void StringType::static_init()
{
Type::AddPredefinedType("bytestring", new StringType(ANYSTR));
}
| [
"kpdyer@gmail.com"
] | kpdyer@gmail.com |
cf95947ffb7a377fad755772d9c9aa952d80ffec | 8b56aa7a8deb23315a6ad687c902e43031f9bdc9 | /PrettyShore_Source/AI/AILifeguard/TaskDriver/AILifeGuardTask_Drinking.cpp | 28a7e266e3c4f34a38155558895b2e885c91f634 | [] | no_license | Tarfax/PortfolioProjects | 6a02b388cfedf51102f94047d52f77235a0242d0 | 2cd4b373f396aec8d56db71cabc04de9c47df9e5 | refs/heads/master | 2023-08-21T17:19:34.532945 | 2021-10-14T07:55:52 | 2021-10-14T07:55:52 | 20,998,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | cpp | #include "AILifeGuardTask_Drinking.h"
#include "Team9Assemble/AI/AILifeguard/AILifeGuard_Controller.h"
void AILifeGuardTask_Drinking::Enter() {
Owner->SetDebugText.Broadcast("Drinking");
Owner->DoingTask = "Drinking";
Owner->OnBeginDrinking.Broadcast(Owner);
Owner->OnBeginDrinkingEvent();
if (Owner->StartInteractWithBuilding() == true) {
BuildingMoodModifier = Owner->InteractingBuilding->GetBuildingMoodModifier();
}
else {
Owner->FailedToExecuteTask(E_AILifeGuard_TaskType::Drinking, 30.0);
}
Reset();
}
void AILifeGuardTask_Drinking::OnTick(float DeltaTime) {
Timer -= DeltaTime;
if (Timer < TaskData->DrinkingMinTime / 2) {
bool NeedToilet = (Need->Toilet > 0.85f && Owner->IsTaskLocked(E_AILifeGuard_TaskType::Excrementing) == false);
if (NeedToilet) {
Owner->MakeDecision();
Reset();
}
}
if (Timer <= 0.0f || Need->Recreation < 0.005f) {
Owner->MakeDecision();
Timer = 2.0f;
}
}
void AILifeGuardTask_Drinking::Exit() {
Owner->StopInteractWithBuilding();
Owner->OnEndDrinking.Broadcast(Owner);
Owner->OnEndDrinkingEvent();
}
void AILifeGuardTask_Drinking::Reset() {
Timer = FMath::RandRange(TaskData->DrinkingMinTime, TaskData->DrinkingMaxTime);
}
| [
"lostmike@gmail.com"
] | lostmike@gmail.com |
19bb796e3739dcf8e7472a59af4c030f1731604d | 50d7e1235573e730b0dc1b9e6a7866249b294cad | /fpoptimizer/optimize_match.cc | 063713f2d661d65526d7c6261b42250ee1bb8043 | [] | no_license | rubund/debian-fparserc- | 1034ccf3648af4fcb3a9b1bb1cad1644747ba686 | a736b8ffa7121f4a416dd7d940af9f7dd5c2e451 | refs/heads/master | 2020-03-24T13:53:20.439830 | 2018-08-25T19:08:46 | 2018-08-25T19:10:59 | 142,753,507 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,625 | cc | #include "fpconfig.hh"
#include "fparser.hh"
#include "extrasrc/fptypes.hh"
#ifdef FP_SUPPORT_OPTIMIZER
#include <algorithm>
#include <assert.h>
#include <cstring>
#include <cmath>
#include <memory> /* for auto_ptr */
#include "grammar.hh"
#include "optimize.hh"
#include "rangeestimation.hh"
#include "consts.hh"
using namespace FUNCTIONPARSERTYPES;
using namespace FPoptimizer_Grammar;
using namespace FPoptimizer_CodeTree;
using namespace FPoptimizer_Optimize;
namespace
{
/* Test the given constraints to a given CodeTree */
template<typename Value_t>
bool TestImmedConstraints(unsigned bitmask, const CodeTree<Value_t>& tree)
{
switch(bitmask & ValueMask)
{
case Value_AnyNum: case ValueMask: break;
case Value_EvenInt:
if(GetEvennessInfo(tree) != IsAlways)
return false;
break;
case Value_OddInt:
if(GetEvennessInfo(tree) != IsNever)
return false;
break;
case Value_IsInteger:
if(GetIntegerInfo(tree) != IsAlways) return false;
break;
case Value_NonInteger:
if(GetIntegerInfo(tree) != IsNever) return false;
break;
case Value_Logical:
if(!IsLogicalValue(tree)) return false;
break;
}
switch(bitmask & SignMask)
{
case Sign_AnySign: /*case SignMask:*/ break;
case Sign_Positive:
if(GetPositivityInfo(tree) != IsAlways) return false;
break;
case Sign_Negative:
if(GetPositivityInfo(tree) != IsNever) return false;
break;
case Sign_NoIdea:
if(GetPositivityInfo(tree) != Unknown) return false;
break;
}
switch(bitmask & OnenessMask)
{
case Oneness_Any: case OnenessMask: break;
case Oneness_One:
if(!tree.IsImmed()) return false;
if(!fp_equal(fp_abs(tree.GetImmed()), Value_t(1))) return false;
break;
case Oneness_NotOne:
if(!tree.IsImmed()) return false;
if(fp_equal(fp_abs(tree.GetImmed()), Value_t(1))) return false;
break;
}
switch(bitmask & ConstnessMask)
{
case Constness_Any: /*case ConstnessMask:*/ break;
case Constness_Const:
if(!tree.IsImmed()) return false;
break;
case Constness_NotConst:
if(tree.IsImmed()) return false;
break;
}
return true;
}
template<unsigned extent, unsigned nbits, typename item_type=unsigned int>
struct nbitmap
{
private:
static const unsigned bits_in_char = 8;
static const unsigned per_item = (sizeof(item_type)*bits_in_char)/nbits;
item_type data[(extent+per_item-1) / per_item];
public:
void inc(unsigned index, int by=1)
{
data[pos(index)] += by * item_type(1 << shift(index));
}
inline void dec(unsigned index) { inc(index, -1); }
int get(unsigned index) const { return (data[pos(index)] >> shift(index)) & mask(); }
static inline unsigned pos(unsigned index) { return index/per_item; }
static inline unsigned shift(unsigned index) { return nbits * (index%per_item); }
static inline unsigned mask() { return (1 << nbits)-1; }
static inline unsigned mask(unsigned index) { return mask() << shift(index); }
};
struct Needs
{
int SubTrees : 8; // This many subtrees
int Others : 8; // This many others (namedholder)
int minimum_need : 8; // At least this many leaves (restholder may require more)
int Immeds : 8; // This many immeds
nbitmap<VarBegin,2> SubTreesDetail; // This many subtrees of each opcode type
Needs()
{
std::memset(this, 0, sizeof(*this));
}
Needs(const Needs& b)
{
std::memcpy(this, &b, sizeof(b));
}
Needs& operator= (const Needs& b)
{
std::memcpy(this, &b, sizeof(b));
return *this;
}
};
template<typename Value_t>
Needs CreateNeedList_uncached(const ParamSpec_SubFunctionData& params)
{
Needs NeedList;
// Figure out what we need
for(unsigned a = 0; a < params.param_count; ++a)
{
const ParamSpec& parampair = ParamSpec_Extract<Value_t>(params.param_list, a);
switch(parampair.first)
{
case SubFunction:
{
const ParamSpec_SubFunction& param = *(const ParamSpec_SubFunction*) parampair.second;
if(param.data.match_type == GroupFunction)
++NeedList.Immeds;
else
{
++NeedList.SubTrees;
assert( param.data.subfunc_opcode < VarBegin );
NeedList.SubTreesDetail.inc(param.data.subfunc_opcode);
}
++NeedList.minimum_need;
break;
}
case NumConstant:
case ParamHolder:
++NeedList.Others;
++NeedList.minimum_need;
break;
}
}
return NeedList;
}
template<typename Value_t>
Needs& CreateNeedList(const ParamSpec_SubFunctionData& params)
{
typedef std::map<const ParamSpec_SubFunctionData*, Needs> needlist_cached_t;
static needlist_cached_t needlist_cached;
needlist_cached_t::iterator i = needlist_cached.lower_bound(¶ms);
if(i != needlist_cached.end() && i->first == ¶ms)
return i->second;
return
needlist_cached.insert(i,
std::make_pair(¶ms, CreateNeedList_uncached<Value_t> (params))
)->second;
}
/* Construct CodeTree from a GroupFunction, hopefully evaluating to a constant value */
template<typename Value_t>
CodeTree<Value_t> CalculateGroupFunction(
const ParamSpec& parampair,
const MatchInfo<Value_t>& info)
{
switch( parampair.first )
{
case NumConstant:
{
const ParamSpec_NumConstant<Value_t>& param = *(const ParamSpec_NumConstant<Value_t>*) parampair.second;
return CodeTreeImmed( param.constvalue ); // Note: calculates hash too.
}
case ParamHolder:
{
const ParamSpec_ParamHolder& param = *(const ParamSpec_ParamHolder*) parampair.second;
return info.GetParamHolderValueIfFound( param.index );
// If the ParamHolder is not defined, it will simply
// return an Undefined tree. This is ok.
}
case SubFunction:
{
const ParamSpec_SubFunction& param = *(const ParamSpec_SubFunction*) parampair.second;
/* Synthesize a CodeTree which will take care of
* constant-folding our expression. It will also
* indicate whether the result is, in fact,
* a constant at all. */
CodeTree<Value_t> result;
result.SetOpcode( param.data.subfunc_opcode );
result.GetParams().reserve(param.data.param_count);
for(unsigned a=0; a<param.data.param_count; ++a)
{
CodeTree<Value_t> tmp(
CalculateGroupFunction
(ParamSpec_Extract<Value_t> (param.data.param_list, a), info)
);
result.AddParamMove(tmp);
}
result.Rehash(); // This will also call ConstantFolding().
return result;
}
}
// Issue an un-calculatable tree. (This should be unreachable)
return CodeTree<Value_t>(); // cNop
}
}
namespace FPoptimizer_Optimize
{
/* Test the list of parameters to a given CodeTree */
/* A helper function which simply checks whether the
* basic shape of the tree matches what we are expecting
* i.e. given number of numeric constants, etc.
*/
template<typename Value_t>
bool IsLogisticallyPlausibleParamsMatch(
const ParamSpec_SubFunctionData& params,
const CodeTree<Value_t>& tree)
{
/* First, check if the tree has any chances of matching... */
/* Figure out what we need. */
Needs NeedList ( CreateNeedList<Value_t> (params) );
size_t nparams = tree.GetParamCount();
if(nparams < size_t(NeedList.minimum_need))
{
// Impossible to satisfy
return false;
}
// Figure out what we have (note: we already assume that the opcode of the tree matches!)
for(size_t a=0; a<nparams; ++a)
{
unsigned opcode = tree.GetParam(a).GetOpcode();
switch(opcode)
{
case cImmed:
if(NeedList.Immeds > 0) --NeedList.Immeds;
else --NeedList.Others;
break;
case VarBegin:
case cFCall:
case cPCall:
--NeedList.Others;
break;
default:
assert( opcode < VarBegin );
if(NeedList.SubTrees > 0
&& NeedList.SubTreesDetail.get(opcode) > 0)
{
--NeedList.SubTrees;
NeedList.SubTreesDetail.dec(opcode);
}
else --NeedList.Others;
}
}
// Check whether all needs were satisfied
if(NeedList.Immeds > 0
|| NeedList.SubTrees > 0
|| NeedList.Others > 0)
{
// Something came short, impossible to satisfy.
return false;
}
if(params.match_type != AnyParams)
{
if(0
//|| NeedList.Immeds < 0 - already checked
|| NeedList.SubTrees < 0
|| NeedList.Others < 0
//|| params.count != nparams - already checked
)
{
// Something was too much.
return false;
}
}
return true;
}
/* Test the given parameter to a given CodeTree */
template<typename Value_t>
MatchResultType TestParam(
const ParamSpec& parampair,
const CodeTree<Value_t>& tree,
const MatchPositionSpecBaseP& start_at,
MatchInfo<Value_t>& info)
{
/*std::cout << "TestParam(";
DumpParam(parampair);
std::cout << ", ";
DumpTree(tree);
std::cout << ")\n";*/
/* What kind of param are we expecting */
switch( parampair.first )
{
case NumConstant: /* A particular numeric value */
{
const ParamSpec_NumConstant<Value_t>& param = *(const ParamSpec_NumConstant<Value_t>*) parampair.second;
if(!tree.IsImmed()) return false;
Value_t imm = tree.GetImmed();
switch(param.modulo)
{
case Modulo_None: break;
case Modulo_Radians:
imm = fp_mod(imm, fp_const_twopi<Value_t>());
if(imm < Value_t(0))
imm += fp_const_twopi<Value_t>();
if(imm > fp_const_pi<Value_t>())
imm -= fp_const_twopi<Value_t>();
break;
}
return fp_equal(imm, param.constvalue);
}
case ParamHolder: /* Any arbitrary node */
{
const ParamSpec_ParamHolder& param = *(const ParamSpec_ParamHolder*) parampair.second;
if(!TestImmedConstraints(param.constraints, tree)) return false;
return info.SaveOrTestParamHolder(param.index, tree);
}
case SubFunction:
{
const ParamSpec_SubFunction& param = *(const ParamSpec_SubFunction*) parampair.second;
if(param.data.match_type == GroupFunction)
{ /* A constant value acquired from this formula */
if(!TestImmedConstraints(param.constraints, tree)) return false;
/* Construct the formula */
CodeTree<Value_t> grammar_func = CalculateGroupFunction(parampair, info);
#ifdef DEBUG_SUBSTITUTIONS
DumpHashes(grammar_func);
std::cout << *(const void**)&grammar_func.GetImmed();
std::cout << "\n";
std::cout << *(const void**)&tree.GetImmed();
std::cout << "\n";
DumpHashes(tree);
std::cout << "Comparing ";
DumpTree(grammar_func);
std::cout << " and ";
DumpTree(tree);
std::cout << ": ";
std::cout << (grammar_func.IsIdenticalTo(tree) ? "true" : "false");
std::cout << "\n";
#endif
/* Evaluate it and compare */
return grammar_func.IsIdenticalTo(tree);
}
else /* A subtree conforming these specs */
{
if(start_at.isnull())
{
if(!TestImmedConstraints(param.constraints, tree)) return false;
if(tree.GetOpcode() != param.data.subfunc_opcode) return false;
}
return TestParams(param.data, tree, start_at, info, false);
}
}
}
return false;
}
template<typename Value_t>
struct PositionalParams_Rec
{
MatchPositionSpecBaseP start_at; /* child's start_at */
MatchInfo<Value_t> info; /* backup of "info" at start */
PositionalParams_Rec(): start_at(), info() { }
};
template<typename Value_t>
class MatchPositionSpec_PositionalParams
: public MatchPositionSpecBase,
public std::vector<PositionalParams_Rec<Value_t> >
{
public:
explicit MatchPositionSpec_PositionalParams(size_t n)
: MatchPositionSpecBase(),
std::vector<PositionalParams_Rec<Value_t> > (n)
{ }
};
struct AnyWhere_Rec
{
MatchPositionSpecBaseP start_at; /* child's start_at */
AnyWhere_Rec() : start_at() { }
};
class MatchPositionSpec_AnyWhere
: public MatchPositionSpecBase,
public std::vector<AnyWhere_Rec>
{
public:
unsigned trypos; /* which param index to try next */
explicit MatchPositionSpec_AnyWhere(size_t n)
: MatchPositionSpecBase(),
std::vector<AnyWhere_Rec> (n),
trypos(0)
{ }
};
template<typename Value_t>
MatchResultType TestParam_AnyWhere(
const ParamSpec& parampair,
const CodeTree<Value_t>& tree,
const MatchPositionSpecBaseP& start_at,
MatchInfo<Value_t>& info,
std::vector<bool>& used,
bool TopLevel)
{
FPOPT_autoptr<MatchPositionSpec_AnyWhere> position;
unsigned a;
if(!start_at.isnull())
{
position = (MatchPositionSpec_AnyWhere*) start_at.get();
a = position->trypos;
goto retry_anywhere_2;
}
else
{
position = new MatchPositionSpec_AnyWhere(tree.GetParamCount());
a = 0;
}
for(; a < tree.GetParamCount(); ++a)
{
if(used[a]) continue;
retry_anywhere:
{ MatchResultType r = TestParam(
parampair,
tree.GetParam(a),
(*position)[a].start_at,
info);
(*position)[a].start_at = r.specs;
if(r.found)
{
used[a] = true; // matched
if(TopLevel) info.SaveMatchedParamIndex(a);
position->trypos = a; // in case of backtrack, try a again
return MatchResultType(true, position.get());
} }
retry_anywhere_2:
if((*position)[a].start_at.get()) // is there another try?
{
goto retry_anywhere;
}
// no, move on
}
return false;
}
template<typename Value_t>
struct AnyParams_Rec
{
MatchPositionSpecBaseP start_at; /* child's start_at */
MatchInfo<Value_t> info; /* backup of "info" at start */
std::vector<bool> used; /* which params are remaining */
explicit AnyParams_Rec(size_t nparams)
: start_at(), info(), used(nparams) { }
};
template<typename Value_t>
class MatchPositionSpec_AnyParams
: public MatchPositionSpecBase,
public std::vector<AnyParams_Rec<Value_t> >
{
public:
explicit MatchPositionSpec_AnyParams(size_t n, size_t m)
: MatchPositionSpecBase(),
std::vector<AnyParams_Rec<Value_t> > (n, AnyParams_Rec<Value_t>(m))
{ }
};
/* Test the list of parameters to a given CodeTree */
template<typename Value_t>
MatchResultType TestParams(
const ParamSpec_SubFunctionData& model_tree,
const CodeTree<Value_t>& tree,
const MatchPositionSpecBaseP& start_at,
MatchInfo<Value_t>& info,
bool TopLevel)
{
/* When PositionalParams or SelectedParams, verify that
* the number of parameters is exactly as expected.
*/
if(model_tree.match_type != AnyParams)
{
if(model_tree.param_count != tree.GetParamCount())
return false;
}
/* Verify that the tree basically conforms the shape we are expecting */
/* This test is not necessary; it may just save us some work. */
if(!IsLogisticallyPlausibleParamsMatch(model_tree, tree))
{
return false;
}
/* Verify each parameter that they are found in the tree as expected. */
switch(model_tree.match_type)
{
case PositionalParams:
{
/* Simple: Test all given parameters in succession. */
FPOPT_autoptr<MatchPositionSpec_PositionalParams<Value_t> > position;
unsigned a;
if(start_at.get())
{
position = (MatchPositionSpec_PositionalParams<Value_t> *) start_at.get();
a = model_tree.param_count - 1;
goto retry_positionalparams_2;
}
else
{
position = new MatchPositionSpec_PositionalParams<Value_t> (model_tree.param_count);
a = 0;
}
for(; a < model_tree.param_count; ++a)
{
(*position)[a].info = info;
retry_positionalparams:
{ MatchResultType r = TestParam(
ParamSpec_Extract<Value_t>(model_tree.param_list, a),
tree.GetParam(a),
(*position)[a].start_at,
info);
(*position)[a].start_at = r.specs;
if(r.found)
{
continue;
} }
retry_positionalparams_2:
// doesn't match
if((*position)[a].start_at.get()) // is there another try?
{
info = (*position)[a].info;
goto retry_positionalparams;
}
// no, backtrack
if(a > 0)
{
--a;
goto retry_positionalparams_2;
}
// cannot backtrack
info = (*position)[0].info;
return false;
}
if(TopLevel)
for(unsigned a = 0; a < model_tree.param_count; ++a)
info.SaveMatchedParamIndex(a);
return MatchResultType(true, position.get());
}
case SelectedParams:
// same as AnyParams, except that model_tree.count==tree.GetParamCount()
// and that there are no RestHolders
case AnyParams:
{
/* Ensure that all given parameters are found somewhere, in any order */
FPOPT_autoptr<MatchPositionSpec_AnyParams<Value_t> > position;
std::vector<bool> used( tree.GetParamCount() );
std::vector<unsigned> depcodes( model_tree.param_count );
std::vector<unsigned> test_order( model_tree.param_count );
for(unsigned a=0; a<model_tree.param_count; ++a)
{
const ParamSpec parampair = ParamSpec_Extract<Value_t>(model_tree.param_list, a);
depcodes[a] = ParamSpec_GetDepCode(parampair);
}
{ unsigned b=0;
for(unsigned a=0; a<model_tree.param_count; ++a)
if(depcodes[a] != 0)
test_order[b++] = a;
for(unsigned a=0; a<model_tree.param_count; ++a)
if(depcodes[a] == 0)
test_order[b++] = a;
}
unsigned a;
if(start_at.get())
{
position = (MatchPositionSpec_AnyParams<Value_t>*) start_at.get();
if(model_tree.param_count == 0)
{
a = 0;
goto retry_anyparams_4;
}
a = model_tree.param_count - 1;
goto retry_anyparams_2;
}
else
{
position = new MatchPositionSpec_AnyParams<Value_t>
(model_tree.param_count, tree.GetParamCount());
a = 0;
if(model_tree.param_count != 0)
{
(*position)[0].info = info;
(*position)[0].used = used;
}
}
// Match all but restholders
for(; a < model_tree.param_count; ++a)
{
if(a > 0) // this test is not necessary, but it saves from doing
{ // duplicate work, because [0] was already saved above.
(*position)[a].info = info;
(*position)[a].used = used;
}
retry_anyparams:
{ MatchResultType r = TestParam_AnyWhere<Value_t>(
ParamSpec_Extract<Value_t>(model_tree.param_list, test_order[a]),
tree,
(*position)[a].start_at,
info,
used,
TopLevel);
(*position)[a].start_at = r.specs;
if(r.found)
{
continue;
} }
retry_anyparams_2:
// doesn't match
if((*position)[a].start_at.get()) // is there another try?
{
info = (*position)[a].info;
used = (*position)[a].used;
goto retry_anyparams;
}
// no, backtrack
retry_anyparams_3:
if(a > 0)
{
--a;
goto retry_anyparams_2;
}
// cannot backtrack
info = (*position)[0].info;
return false;
}
retry_anyparams_4:
// Capture anything remaining in the restholder
if(model_tree.restholder_index != 0)
{
//std::vector<bool> used_backup(used);
//MatchInfo info_backup(info);
if(!TopLevel
|| !info.HasRestHolder(model_tree.restholder_index))
{
std::vector<CodeTree<Value_t> > matches;
matches.reserve(tree.GetParamCount());
for(unsigned b = 0; b < tree.GetParamCount(); ++b)
{
if(used[b]) continue; // Ignore subtrees that were already used
// Save this tree to this restholder
matches.push_back(tree.GetParam(b));
used[b] = true;
if(TopLevel) info.SaveMatchedParamIndex(b);
}
if(!info.SaveOrTestRestHolder(model_tree.restholder_index, matches))
{
// Failure at restholder matching. Backtrack if possible.
//used.swap(used_backup);
//info.swap(info_backup);
goto retry_anyparams_3;
}
//std::cout << "Saved restholder " << model_tree.restholder_index << "\n";
}
else
{
const std::vector<CodeTree<Value_t> >& matches
= info.GetRestHolderValues(model_tree.restholder_index);
//std::cout << "Testing restholder " << model_tree.restholder_index << std::flush;
for(size_t a=0; a<matches.size(); ++a)
{
bool found = false;
for(unsigned b = 0; b < tree.GetParamCount(); ++b)
{
if(used[b]) continue;
if(matches[a].IsIdenticalTo(tree.GetParam(b)))
{
used[b] = true;
if(TopLevel) info.SaveMatchedParamIndex(b);
found = true;
break;
}
}
if(!found)
{
//std::cout << " ... failed\n";
// Failure at restholder matching. Backtrack if possible.
//used.swap(used_backup);
//info.swap(info_backup);
goto retry_anyparams_3;
}
}
//std::cout << " ... ok\n";
}
}
return MatchResultType(true, model_tree.param_count ? position.get() : 0);
}
case GroupFunction: // never occurs
break;
}
return false; // doesn't match
}
}
/* BEGIN_EXPLICIT_INSTANTATION */
#include "instantiate.hh"
namespace FPoptimizer_Optimize
{
#define FP_INSTANTIATE(type) \
template \
MatchResultType TestParams( \
const ParamSpec_SubFunctionData& model_tree, \
const CodeTree<type> & tree, \
const MatchPositionSpecBaseP& start_at, \
MatchInfo<type>& info, \
bool TopLevel); \
template \
bool IsLogisticallyPlausibleParamsMatch( \
const ParamSpec_SubFunctionData& params, \
const CodeTree<type>& tree);
FPOPTIMIZER_EXPLICITLY_INSTANTIATE(FP_INSTANTIATE)
#undef FP_INSTANTIATE
}
/* END_EXPLICIT_INSTANTATION */
#endif
| [
"ruben.undheim@gmail.com"
] | ruben.undheim@gmail.com |
24abbe3b9f9793d81f4418b60f3fbf077126d9a9 | 8aece1b77a0ce389bec432510794689f3f36d871 | /Example10_ShadowMap/Example10_ShadowMap/Example10_ShadowMap/App1.h | 62fea582baf0d4ba7f129840fbabfcfb668fbfe9 | [] | no_license | JanekUchman/CMP301 | d0f7d79cb5f7f7e1f429e3db5a72dc4aec3c2dd5 | 04b0df14d1eb95ddaf984015004055df0281d172 | refs/heads/master | 2020-04-07T06:12:49.875170 | 2018-12-09T16:20:30 | 2018-12-09T16:20:30 | 158,126,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 813 | h | // Application.h
#ifndef _APP1_H
#define _APP1_H
// Includes
#include "DXF.h" // include dxframework
#include "TextureShader.h"
#include "ShadowShader.h"
#include "DepthShader.h"
#include "CubeMesh.h"
#include "SphereMesh.h"
#include "OrthoMesh.h"
class App1 : public BaseApplication
{
public:
App1();
~App1();
void init(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight, Input* in, bool VSYNC, bool FULL_SCREEN);
bool frame();
protected:
bool render();
void depthPass();
void finalPass();
void gui();
private:
TextureShader* textureShader;
PlaneMesh* mesh;
Light* light;
Model* model;
CubeMesh* cubeMesh;
SphereMesh* sphereMesh;
ShadowShader* shadowShader;
DepthShader* depthShader;
OrthoMesh* orthoMesh;
RenderTexture* shadowMap;
float animationChange = 0;
};
#endif | [
"janekuchman@hotmail.co.uk"
] | janekuchman@hotmail.co.uk |
975d1c6da93c285e4d297d319679c51a91123b99 | c64d2795de5b82cec51a74f5f7b6feb4217f34b4 | /QYLiving/sample.cpp | 35b739e88e48af9ef3acbd25c3f09e796fde8423 | [] | no_license | unslur/QYLiving | 017d289235c80129be79b03d885c093791058e70 | bc6b64a09f563c095aae4ff68bf37312a0ed1324 | refs/heads/master | 2020-03-23T17:55:17.458932 | 2018-07-22T09:08:18 | 2018-07-22T09:08:18 | 141,881,287 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 16,858 | cpp | #include <Windows.h>
#include "sample.h"
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include "stdafx.h"
#include "include\nlss_api.h"
#include "Wininet.h"
#pragma comment(lib,"Wininet.lib")
#pragma comment(lib,"ws2_32.lib")
#pragma warning(disable:4996)
//获取建议的输出目标码率供开发者使用,请关注
typedef int(*PFN_THREADPROC)(LPVOID pParam);
BOOL GetRealIpByDomainName(char *szHost, char szIp[50][100], int *nCount);
#define NLSS_720P_BITRATE 800000
//打开设备
int iAppNum = 0;
int CurrentLivingStatus = 0;
int closeLive = 0;
_HNLSSERVICE hNLSService = NULL;
ST_NLSS_INDEVICE_INF *m_pVideoDevices;
_HNLSSCHILDSERVICE hChildVideoService1 = NULL;
ST_NLSS_VIDEOIN_PARAM stChildVInParam;
string cameraPath = "";
bool bThreadRun = false;
HANDLE CreateThreadH(PFN_THREADPROC lpThreadFunc, _HNLSSERVICE hNLSService);
void CloseThreadH(HANDLE hOSThread);
int GetOutBitrate(int iWidth, int iHeight, int iFps)
{
if (iWidth == 0 || iHeight == 0 || iFps == 0)
{
return NLSS_720P_BITRATE; //1280*720 20fps,设置的码率
}
int iOutBitrate = NLSS_720P_BITRATE * iWidth / 1280;
iOutBitrate = iOutBitrate * iHeight / 720;
if (iFps >= 15)
{
iOutBitrate = iOutBitrate * iFps / 20;
}
else if (iFps < 15)
{
iOutBitrate = iOutBitrate * 15 / 20;
}
return iOutBitrate;
}
bool SetVideoOutParam(ST_NLSS_VIDEOOUT_PARAM *pstVideoParam, EN_NLSS_VIDEOQUALITY_LVL enVideoQ, bool bWideScreen)
{
pstVideoParam->enOutCodec = EN_NLSS_VIDEOOUT_CODEC_X264;
pstVideoParam->bHardEncode = false;
pstVideoParam->iOutFps = 20;
switch (enVideoQ)
{
case EN_NLSS_VIDEOQUALITY_SUPER:
pstVideoParam->iOutWidth = 1920;
pstVideoParam->iOutHeight = 1080;
break;
case EN_NLSS_VIDEOQUALITY_HIGH:
pstVideoParam->iOutWidth = 1280;
pstVideoParam->iOutHeight = 720;
break;
case EN_NLSS_VIDEOQUALITY_MIDDLE:
pstVideoParam->iOutWidth = 640;
pstVideoParam->iOutHeight = 480;
break;
case EN_NLSS_VIDEOQUALITY_LOW:
pstVideoParam->iOutWidth = 320;
pstVideoParam->iOutHeight = 240;
break;
default:
return false;
break;
}
if (bWideScreen)
{
pstVideoParam->iOutWidth = pstVideoParam->iOutWidth / 4 * 4;
pstVideoParam->iOutHeight = pstVideoParam->iOutWidth * 9 / 16;
pstVideoParam->iOutHeight = pstVideoParam->iOutHeight / 4 * 4;
}
pstVideoParam->iOutBitrate = GetOutBitrate(pstVideoParam->iOutWidth, pstVideoParam->iOutHeight, pstVideoParam->iOutFps);
return true;
}
bool SetVideoInParam(ST_NLSS_VIDEOIN_PARAM *pstVideoParam, EN_NLSS_VIDEOIN_TYPE mVideoSourceType, const char *pVideoPath, EN_NLSS_VIDEOQUALITY_LVL enLvl)
{
pstVideoParam->enInType = mVideoSourceType;
switch (mVideoSourceType)
{
case EN_NLSS_VIDEOIN_FULLSCREEN:
{
pstVideoParam->iCaptureFps = 10;
}
break;
case EN_NLSS_VIDEOIN_CAMERA:
//获取视频参数
pstVideoParam->iCaptureFps = 20;
if (m_pVideoDevices != NULL)
{
pstVideoParam->u.stInCamera.paDevicePath = (char *)pVideoPath;
}
else
{
return false;
}
pstVideoParam->u.stInCamera.enLvl = enLvl;
break;
case EN_NLSS_VIDEOIN_RECTSCREEN:
pstVideoParam->u.stInRectScreen.iRectLeft = 100;
pstVideoParam->u.stInRectScreen.iRectRight = 500;
pstVideoParam->u.stInRectScreen.iRectTop = 100;
pstVideoParam->u.stInRectScreen.iRectBottom = 500;
pstVideoParam->iCaptureFps = 20;
break;
case EN_NLSS_VIDEOIN_APP:
{
pstVideoParam->iCaptureFps = 20;
pstVideoParam->u.stInApp.paAppPath = (char *)pVideoPath;
}
break;
case EN_NLSS_VIDEOIN_PNG:
//strcpy(pstVideoParam->u.stInPng.paPngPath, "logo.png");
// = "logo.png";
pstVideoParam->iCaptureFps = 20;
break;
case EN_NLSS_VIDEOIN_NONE:
return false;
break;
default:
return false;
break;
}
return true;
}
void SetAudioParam(ST_NLSS_AUDIO_PARAM *pstAudioParam, char *pAudioPath, EN_NLSS_AUDIOIN_TYPE enAudioType)
{
pstAudioParam->stIn.iInSamplerate = 44100;
pstAudioParam->stIn.enInType = enAudioType;
pstAudioParam->stIn.paaudioDeviceName = pAudioPath;
}
bool initLiveStream(_HNLSSERVICE hNLSService, ST_NLSS_PARAM *pstParam, char *paOutUrl)
{
bool have_video_source = true;
bool have_audio_source = false;
if (have_audio_source && have_video_source)
pstParam->enOutContent = EN_NLSS_OUTCONTENT_AV;//默认音视频设备都存在则推流音视频,当然,也可以设置成音频/视频,
else if (have_audio_source && !have_video_source)
pstParam->enOutContent = EN_NLSS_OUTCONTENT_AUDIO;
else if (have_video_source && !have_audio_source)
pstParam->enOutContent = EN_NLSS_OUTCONTENT_VIDEO;
else if (!have_audio_source && !have_video_source)
{
return false;
}
pstParam->paOutUrl = new char[1024];
memset(pstParam->paOutUrl, 0, 1024);
strcpy(pstParam->paOutUrl, paOutUrl);
if (NLSS_OK != Nlss_InitParam(hNLSService, pstParam))
{
delete[]pstParam->paOutUrl;
return false;
}
delete[]pstParam->paOutUrl;
return true;
}
Tool *s;
int flag = 1;
void previewCB(_HNLSSERVICE hNLSService, ST_NLSS_VIDEO_SAMPLER *pstSampler)
{
return;
int width = pstSampler->iWidth;
int height = pstSampler->iHeight;
s->bmp32to24_write(pstSampler->puaData, width, height);
}
void statusCB(_HNLSSERVICE hNLSService, EN_NLSS_STATUS enStatus, EN_NLSS_ERRCODE enErrCode)
{
if (enStatus == EN_NLSS_STATUS_START&&enErrCode== EN_NLSS_ERR_NO) {
printf("Living Start\n");
}
else
{
fprintf(stdout, "Living error:Status=%d,Error=%d\n", enStatus, enErrCode);
}
return;
}
void deleteAllDevices(ST_NLSS_INDEVICE_INF *pstDevices, int iCount)
{
for (int i = 0; i < iCount; i++)
{
delete[]pstDevices[i].paPath;
delete[]pstDevices[i].paFriendlyName;
}
delete pstDevices;
}
void SendImageTimer(void *lpParameter) {
extern int interval;
while (true)
{
Sleep(interval*1000);
s->flag = 1;
}
}
void Sever(void *lpParameter)
{
HANDLE hCheck = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ShitLiving, NULL, 0, NULL);
WSADATA wsaData;
int port = 15554;
char buf[] = "OK";
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
printf("Failed to load Winsock");
return;
}
//创建用于监听的套接字
SOCKET sockSrv = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN addrSrv;
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(port); //1024以上的端口号
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
int retVal = bind(sockSrv, (LPSOCKADDR)&addrSrv, sizeof(SOCKADDR_IN));
if (retVal == SOCKET_ERROR) {
printf("Failed bind:%d\n", WSAGetLastError());
return;
}
if (listen(sockSrv, 10) == SOCKET_ERROR) {
printf("Listen failed:%d", WSAGetLastError());
return;
}
extern int quality;
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
while (1)
{
//等待客户请求到来
SOCKET sockConn = accept(sockSrv, (SOCKADDR *)&addrClient, &len);
if (sockConn == SOCKET_ERROR) {
printf("Accept failed:%d", WSAGetLastError());
break;
}
printf("Accept client IP:[%s]\n", inet_ntoa(addrClient.sin_addr));
char recvBuf[100];
memset(recvBuf, 0, sizeof(recvBuf));
// //接收数据
recv(sockConn, recvBuf, sizeof(recvBuf), 0);
if (strcmp(recvBuf, "chat") == 0) {
printf(" 关闭直播:\n");
Nlss_ChildVideoStopCapture(hChildVideoService1);
Nlss_ChildVideoClose(hChildVideoService1);
closeLive = 1;
//Nlss_StopLiveStream(hNLSService);
Sleep(1000);
}
else if (strcmp(recvBuf, "endchat") == 0)
{
printf(" 开启直播:\n");
closeLive = 1;
SetVideoInParam(&stChildVInParam, EN_NLSS_VIDEOIN_CAMERA, cameraPath.c_str(), EN_NLSS_VIDEOQUALITY_LVL(quality - 1));
hChildVideoService1 = Nlss_ChildVideoOpen(hNLSService, &stChildVInParam);
if (hChildVideoService1 == NULL)\
{printf(" 重启直播失败:\n");
continue; }
ST_NLSS_RECTSCREEN_PARAM stRect = { 0, 1000, 0, 600 };
switch (EN_NLSS_VIDEOQUALITY_LVL(quality - 1))
{
case EN_NLSS_VIDEOQUALITY_SUPER:
stRect = { 0, 1920, 0,1080 };
break;
case EN_NLSS_VIDEOQUALITY_HIGH:
stRect = { 0, 1280, 0, 720 };
break;
case EN_NLSS_VIDEOQUALITY_MIDDLE:
stRect = { 0, 640, 0, 480 };
break;
case EN_NLSS_VIDEOQUALITY_LOW:
stRect = { 0, 320, 0, 240 };
break;
default:
break;
}
////////////720p摄像头只能画质使用到high, xps只能使用到middle
Nlss_ChildVideoSetDisplayRect(hChildVideoService1, &stRect);
NLSS_RET rtn= Nlss_ChildVideoStartCapture(hChildVideoService1);
if (rtn == NLSS_ERR) {
printf(" 重启失败:\n");
}
//Nlss_StartVideoPreview(hNLSService);
//Nlss_StartLiveStream(hNLSService);
//HANDLE hCheck = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ShitLiving, NULL, 0, NULL);
//Nlss_StartLiveStream(hNLSService);
}
printf("接收到命令 :%s\n", recvBuf);
//发送数据
int iSend = send(sockConn, buf, sizeof(buf), 0);
if (iSend == SOCKET_ERROR) {
printf("send failed");
break;
}
closesocket(sockConn);
}
closesocket(sockSrv);
WSACleanup();
system("pause");
}
BOOL GetRealIpByDomainName(char *szHost, char szIp[50][100], int *nCount)
{
WSADATA wsaData;
HOSTENT *pHostEnt;
int nAdapter = 0;
struct sockaddr_in sAddr;
if (WSAStartup(0x0101, &wsaData))
{
printf(" gethostbyname error for host:\n");
return FALSE;
}
pHostEnt = gethostbyname(szHost);
if (pHostEnt)
{
while (pHostEnt->h_addr_list[nAdapter])
{
memcpy(&sAddr.sin_addr.s_addr, pHostEnt->h_addr_list[nAdapter], pHostEnt->h_length);
sprintf_s(szIp[nAdapter], "%s", inet_ntoa(sAddr.sin_addr));
nAdapter++;
}
*nCount = nAdapter;
}
else
{
DWORD dwError = GetLastError();
*nCount = 0;
}
WSACleanup();
return TRUE;
}
void CheckInternetPingTimer(void *lpParameter) {
// 返回的域名对应实际IP的个数
int nIpCount = 0;
// 返回的域名对应实际I列表
char szIpList[50][100];
char szDomain[256] = { 0 };
char szIp[1024] = { 0 };
strcpy_s(szDomain, "www.baidu.com");
GetRealIpByDomainName(szDomain, szIpList, &nIpCount);
BOOL con;
while (true)
{
con = GetRealIpByDomainName(szDomain, szIpList, &nIpCount);
if ( nIpCount>0) {
//std::cout << "Connected!" << std::endl;
if (CurrentLivingStatus == 0) {
Nlss_StartLiveStream(hNLSService);
CurrentLivingStatus = 1;
}
else
{
CurrentLivingStatus = 1;
}
Sleep(2000);
}
else {
std::cout << "Not connected!" << std::endl;
if (CurrentLivingStatus == 1) {
Nlss_StopLiveStream(hNLSService);
CurrentLivingStatus = 0;
}
else
{
CurrentLivingStatus = 0;
}
Sleep(2000);
}
}
}
void getcamera() {
int m_iVideoDeviceNum = 0;
int m_iAudioDeviceNum = 0;
Nlss_GetFreeDevicesNum(&m_iVideoDeviceNum, &m_iAudioDeviceNum);
if (m_iVideoDeviceNum <= 0)
{
return;
}
else
{
m_pVideoDevices = new ST_NLSS_INDEVICE_INF[m_iVideoDeviceNum];
for (int i = 0; i < m_iVideoDeviceNum; i++)
{
m_pVideoDevices[i].paPath = new char[1024];
m_pVideoDevices[i].paFriendlyName = new char[1024];
}
}
Nlss_GetFreeDeviceInf(m_pVideoDevices, m_iVideoDeviceNum, nullptr, 0);
cameraPath = m_pVideoDevices[0].paPath;
return;
}
void ShitLiving(void * lpParameter)
{
return;
extern int quality;
getcamera();
BOOL con;
// 返回的域名对应实际IP的个数
int nIpCount = 0;
// 返回的域名对应实际I列表
char szIpList[50][100];
char szDomain[256] = { 0 };
char szIp[1024] = { 0 };
strcpy_s(szDomain, "www.baidu.com");
GetRealIpByDomainName(szDomain, szIpList, &nIpCount);
while (true)
{
con = GetRealIpByDomainName(szDomain, szIpList, &nIpCount);
if (nIpCount>0) {
//Sleep(2000);
break;
}
else
std::cout << "Not connected!" << std::endl;
Sleep(1000);
}
//s = new Tool();
#ifdef _DEBUG
/*extern char livingurl[0x100];
char paOutUrl[0x100];
memcpy(paOutUrl, livingurl, strlen(livingurl));*/
char paOutUrl[] = "rtmp://p0cc229d3.live.126.net/live/74e2817e136e4b61b79bfe70548c0aa7?wsSecret=181bc2ac8b4b2de62d161973fa102b7f&wsTime=1520843926";
#else
extern char livingurl[0x100];
char paOutUrl[0x100] ;
memcpy(paOutUrl, livingurl, strlen(livingurl));
//char paOutUrl[] = "rtmp://pb9599a7a.live.126.net/live/449a765b771d46ee962c04d835bbb70f?wsSecret=f4abbffb2ba8a521f703d7c42abcc9c6&wsTime=1515057754";
#endif // DEBUG
printf("推流地址:%s\n", paOutUrl);
bool rtn;
int count;
Nlss_Create(NULL, NULL, &hNLSService);
Nlss_SetVideoSamplerCB(hNLSService, previewCB);
Nlss_SetStatusCB(hNLSService, statusCB);
//solo camera
NLSS_RET nrtn = 0;
ST_NLSS_PARAM stParam;
Nlss_GetDefaultParam(hNLSService, &stParam);
rtn=SetVideoOutParam(&stParam.stVideoParam, EN_NLSS_VIDEOQUALITY_LVL(quality-1), true);
rtn = initLiveStream(hNLSService, &stParam, paOutUrl);
//printf("推流地址:%s\n", (char *)m_pVideoDevices[1].paPath);
rtn=SetVideoInParam(&stChildVInParam, EN_NLSS_VIDEOIN_CAMERA, cameraPath.c_str(), EN_NLSS_VIDEOQUALITY_LVL(quality - 1));
hChildVideoService1 = Nlss_ChildVideoOpen(hNLSService, &stChildVInParam);
Nlss_Start(hNLSService);
ST_NLSS_RECTSCREEN_PARAM stRect = { 0, 1000, 0, 600 };
switch (EN_NLSS_VIDEOQUALITY_LVL(quality - 1))
{
case EN_NLSS_VIDEOQUALITY_SUPER:
stRect = { 0, 1920, 0,1080 };
break;
case EN_NLSS_VIDEOQUALITY_HIGH:
stRect = { 0, 1280, 0, 720 };
break;
case EN_NLSS_VIDEOQUALITY_MIDDLE:
stRect = { 0, 640, 0, 480 };
break;
case EN_NLSS_VIDEOQUALITY_LOW:
stRect = { 0, 320, 0, 240 };
break;
default:
break;
}
////////////720p摄像头只能画质使用到high, xps只能使用到middle
Nlss_ChildVideoSetDisplayRect(hChildVideoService1, &stRect);
nrtn = Nlss_ChildVideoStartCapture(hChildVideoService1);
Nlss_StartVideoPreview(hNLSService);
Nlss_StartLiveStream(hNLSService);
CurrentLivingStatus = 1;
//HANDLE hCheck = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CheckInternetStatusTimer, NULL, 0, NULL);
//HANDLE hCheck = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)CheckInternetPingTimer, NULL, 0, NULL);
while (true)
{
// 返回的域名对应实际IP的个数
int nIpCount = 0;
// 返回的域名对应实际I列表
char szIpList[50][100];
char szDomain[256] = { 0 };
char szIp[1024] = { 0 };
strcpy_s(szDomain, "www.baidu.com");
GetRealIpByDomainName(szDomain, szIpList, &nIpCount);
BOOL con;
while (true)
{
/*if (closeLive>0)
{
goto end;
}*/
con = GetRealIpByDomainName(szDomain, szIpList, &nIpCount);
if (nIpCount>0) {
//std::cout << "Connected!" << std::endl;
if (CurrentLivingStatus == 0) {
Nlss_StartLiveStream(hNLSService);
CurrentLivingStatus = 1;
}
else
{
CurrentLivingStatus = 1;
}
Sleep(2000);
}
else {
std::cout << "Not connected!" << std::endl;
if (CurrentLivingStatus == 1) {
Nlss_StopLiveStream(hNLSService);
CurrentLivingStatus = 0;
}
else
{
CurrentLivingStatus = 0;
}
Sleep(2000);
}
}
}
end:
Nlss_ChildVideoClose(hChildVideoService1);
Nlss_StopLiveStream(hNLSService);
Nlss_Stop(hNLSService);
Nlss_UninitParam(hNLSService);
Nlss_Destroy(hNLSService);
}
//int SwitchVideo(LPVOID lpParam)
//{
// int testNum = 0;
// _HNLSSERVICE hNLSService = (_HNLSSERVICE)lpParam;
// if (!hNLSService)
// {
// return -1;
// }
//
// while (bThreadRun)
// {
// if (testNum == 0)
// {
// testNum = 1;
// Nlss_ChildVideoStopCapture(hChildVideoService1);
// Nlss_ChildVideoClose(hChildVideoService1);
// hChildVideoService1 = NULL;
//
// ST_NLSS_VIDEOIN_PARAM stChildVInParam;
// if (rand() % 2 == 0)
// {
// SetVideoInParam(&stChildVInParam, EN_NLSS_VIDEOIN_FULLSCREEN, (char *)m_pVideoDevices[0].paPath, EN_NLSS_VIDEOQUALITY_MIDDLE);
// }
// else {
// SetVideoInParam(&stChildVInParam, EN_NLSS_VIDEOIN_RECTSCREEN, (char *)m_pVideoDevices[0].paPath, EN_NLSS_VIDEOQUALITY_MIDDLE);
// }
//
// hChildVideoService2 = Nlss_ChildVideoOpen(hNLSService, &stChildVInParam);
// Nlss_ChildVideoSetBackLayer(hChildVideoService2);
// Nlss_ChildVideoStartCapture(hChildVideoService2);
// }
// else if (testNum == 1)
// {
// testNum = 0;
// Nlss_ChildVideoStopCapture(hChildVideoService2);
// Nlss_ChildVideoClose(hChildVideoService2);
// hChildVideoService2 = NULL;
//
// ST_NLSS_VIDEOIN_PARAM stChildVInParam;
// SetVideoInParam(&stChildVInParam, EN_NLSS_VIDEOIN_CAMERA, (char *)m_pVideoDevices[0].paPath, EN_NLSS_VIDEOQUALITY_MIDDLE);
// hChildVideoService1 = Nlss_ChildVideoOpen(hNLSService, &stChildVInParam);
// Nlss_ChildVideoSetBackLayer(hChildVideoService1);
// Nlss_ChildVideoStartCapture(hChildVideoService1);
//
// }
// Sleep(1500);
// }
//
// return 0;
//
//}
HANDLE CreateThreadH(PFN_THREADPROC lpThreadFunc, _HNLSSERVICE hNLSService)
{
HANDLE Thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)lpThreadFunc, (LPVOID)hNLSService, 0, NULL);
return Thread;
}
void CloseThreadH(HANDLE hOSThread)
{
CloseHandle(hOSThread);
hOSThread = NULL;
} | [
"cyylogo@163.com"
] | cyylogo@163.com |
a6cb32e065d96fbc122172d3647a649fe3810954 | 9f64bc965b8c677b4005ff53b197bd705083465f | /fgs_ceres_playground/include/fgs_ceres_playground/optimization_context.hpp | 0ca85d48651e2f29d255b87c041684770b615b47 | [
"BSD-3-Clause",
"MIT"
] | permissive | fugashy/fgs_opt | 9ae3610c62e66cbcbd1f582dab2e9763253b6a86 | 912bf033635481792e9fce19f0f1aa4ba474f148 | refs/heads/master | 2021-09-22T18:30:51.748447 | 2021-09-17T14:24:43 | 2021-09-17T14:24:43 | 161,966,641 | 1 | 0 | MIT | 2019-06-22T08:45:16 | 2018-12-16T04:10:10 | C++ | UTF-8 | C++ | false | false | 2,781 | hpp | #ifndef FGS_CERES_PLAYGROUND_OPTIMIZATION_CONTEXT_HPP_
#define FGS_CERES_PLAYGROUND_OPTIMIZATION_CONTEXT_HPP_
#include <memory>
#include <ceres/ceres.h>
#include "fgs_ceres_playground/cv_viz.hpp"
#include "fgs_ceres_playground/data.hpp"
#include "fgs_ceres_playground/bundle_adjustment_in_the_large.hpp"
namespace fgs {
namespace ceres_playground {
class OptimizationContext {
public:
virtual ~OptimizationContext() {}
using Ptr = std::shared_ptr<OptimizationContext>;
virtual void Solve(ceres::Solver::Options& options) = 0;
};
template<class ResidualType>
class FittingContext : public OptimizationContext {
public:
FittingContext(const std::string& cv_storage_path) {
cv::FileStorage fs(cv_storage_path, cv::FileStorage::READ);
cv::Mat data;
fs["data"] >> data;
if (data.empty()) {
throw std::runtime_error("data is empty");
}
param_.Init(100.0);
typename ResidualType::DataArrayType data_array;
ResidualType::DataType::CvToDataArray(data, data_array);
for (auto it = data_array.begin(); it != data_array.end(); ++it) {
problem_.AddResidualBlock(ResidualType::Create(*it), NULL, ¶m_[0]);
}
}
virtual void Solve(ceres::Solver::Options& options) {
std::cout << "Before" << std::endl;
ResidualType::ShowParam(param_);
ceres::Solver::Summary summary;
ceres::Solve(options, &problem_, &summary);
std::cout << "After" << std::endl;
ResidualType::ShowParam(param_);
}
private:
typename ResidualType::ParameterType param_;
ceres::Problem problem_;
};
// opencv vizをインストールするまで封印
//template<class ResidualType>
//class BALContext : public OptimizationContext {
// public:
// BALContext(const std::string& cv_storage_path) :
// problem_source_(new BundleAdjustmentInTheLarge(cv_storage_path)) {
// for (int i = 0; i < problem_source_->observations_num(); ++i) {
// const cv::Mat data = problem_source_->observation_data(i);
// double* camera_parameter = problem_source_->param_associated_with_obs(
// i, BundleAdjustmentInTheLarge::Item::Camera);
// double* point = problem_source_->param_associated_with_obs(
// i, BundleAdjustmentInTheLarge::Item::Point);
// ceres::CostFunction* cf = ResidualType::Create(data);
// problem_.AddResidualBlock(cf, NULL, camera_parameter, point);
// }
// }
//
// virtual void Solve(ceres::Solver::Options& options) {
// CVBALVisualizer viz(problem_source_, "BAL");
// viz.AddNoise(0.0, 0.1);
// viz.Show();
//
// ceres::Solver::Summary summary;
// ceres::Solve(options, &problem_, &summary);
//
// viz.Show();
// }
//
// private:
// std::shared_ptr<BundleAdjustmentInTheLarge> problem_source_;
// ceres::Problem problem_;
//};
}
}
#endif
| [
"fugashy@icloud.com"
] | fugashy@icloud.com |
060c0a7c80c03fc80f445cace39a0afa6ea56038 | 1f32ff1298ee403043799877f99c3f285f05aa86 | /QtUtil/QtalkUtil.cpp | 6effa0c866e39311adbacf171a293c7df5884998 | [
"MIT"
] | permissive | imtalkdemo/startalk_pc | 665d2847b21bf5bd0a06eee205675c925bc28f90 | 86bd3bb1a25af366edca53392dd0eac77e28fcdc | refs/heads/master | 2022-12-16T22:13:19.199917 | 2020-09-24T15:46:43 | 2020-09-24T15:46:43 | 298,324,482 | 0 | 0 | MIT | 2020-09-24T15:47:04 | 2020-09-24T15:47:03 | null | UTF-8 | C++ | false | false | 49 | cpp |
#include "QtalkUtil.h"
namespace QTalk
{
}
| [
"build@qunar.com"
] | build@qunar.com |
08c90efcae4dc29454b6c190cfce6c0e73de5675 | 5e35d49887a0c50d75913ca82d187275e217c4f5 | /Baekjoon/MATH]goldbachpartition.cpp | 57f5a1281d640f977830e5a3116869b5ee050ff5 | [] | no_license | jiun0507/Interview-prep | 4866f0c3d3dd6a407bc7078987aaa373d7111c2c | aeaae8a99dc21f2b11ae50f577a75ff49b56e1b3 | refs/heads/master | 2021-11-14T11:31:03.316564 | 2021-09-11T21:15:25 | 2021-09-11T21:15:25 | 214,645,862 | 0 | 0 | null | 2019-10-12T13:08:09 | 2019-10-12T12:44:57 | null | UTF-8 | C++ | false | false | 795 | cpp | //baekjoon 17103 goldbach partition question
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int ans[500000];
int plength = 0;
int input[101];
int max = 0;
int n;
cin>>n;
for(int i =0;i<n;i++){
int x;
cin>>x;
input[i] = x;
if(max<x){
max = x;
}
}
int check[1000001] = {0};//check size up to you.(arbitrary)
for(int i=2;i<=max;i++){
if(check[i]==0){
ans[plength++]=i;
}
for(int j = i+i;j<=max;j+=i){
check[j] = 1;
}
}
for(int l =0;l<n;l++){
int inp = input[l];
int sum = 0;
for(int i=0; i<plength;i++){
int a = ans[i];
if(a>inp/2){
break;
}
else if(check[inp-a]==0){
sum +=1;
//cout<<"works"<<a<<" "<<inp-a<<"\n";
}
}
cout<<sum<<"\n";
}
return 0;
} | [
"jkim2@bowdoin.edu"
] | jkim2@bowdoin.edu |
eaa61cb568f1d4bb72d84d95ef4c143084949104 | e9f3369247da3435cd63f2d67aa95c890912255c | /problem312.cpp | 7de505fe1397b918ca3e7166902d9ac3b6e6a1ba | [] | no_license | panthitesh6410/problem-solving-C- | 27b31a141669b91eb36709f0126be05f241dfb13 | 24b72fc795b7b5a44e22e5f6ca9faad462a097fb | refs/heads/master | 2021-11-15T21:52:33.523503 | 2021-10-17T16:20:58 | 2021-10-17T16:20:58 | 248,523,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | cpp | // maximum subarra sum - (Kadane's Algorithm)
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int sum = 0, maximum = arr[0];
for(int i=0;i<n;i++){
sum += arr[i];
if(sum < 0)
sum = 0;
else{
if(sum > maximum)
maximum = sum;
}
}
cout<<maximum;
return 0;
} | [
"panthitesh6410@gmail.com"
] | panthitesh6410@gmail.com |
5ca34365c89ab7b6fefa446f7050ad616651108c | 2e5e2b317a2114201b73467093be4f5cedf84f27 | /src/lexer.cpp | 5568444bb911be4f3697377f2003eceee54f9769 | [] | no_license | jayjiahua/AQL-Subset-Compiler | d18cb4f803b1292d516c6725c74ef0d45cc5930e | 1e436bb733e88cf238994106e88c13ab508e88ce | refs/heads/master | 2016-08-10T18:56:37.479514 | 2016-01-02T08:10:02 | 2016-01-02T08:10:02 | 48,903,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,546 | cpp | #include "lexer.h"
#include "token.h"
#include "exception.h"
#include <ctype.h>
#include <iostream>
#include <iomanip>
#include <cstdlib>
using std::cout;
using std::endl;
using std::getline;
using std::setw;
using std::setfill;
Lexer::Lexer(const char *filePath) : filePath(filePath) {
ifs.open(filePath);
this->filePath = string(filePath);
if (!ifs) {
cout << "Fail to open \"" << filePath << "\"" << endl;
throw FileOpenException();
}
// 将下面的关键字保留
reserve(Token(AQLToken::CREATE, "create"));
reserve(Token(AQLToken::VIEW, "view"));
reserve(Token(AQLToken::AS, "as"));
reserve(Token(AQLToken::OUTPUT, "output"));
reserve(Token(AQLToken::SELECT, "select"));
reserve(Token(AQLToken::FROM, "from"));
reserve(Token(AQLToken::EXTRACT, "extract"));
reserve(Token(AQLToken::REGEX, "regex"));
reserve(Token(AQLToken::ON, "on"));
reserve(Token(AQLToken::RETURN, "return"));
reserve(Token(AQLToken::GROUP, "group"));
reserve(Token(AQLToken::AND, "and"));
reserve(Token(AQLToken::TOKEN, "Token"));
reserve(Token(AQLToken::PATTERN, "pattern"));
peek = ' ';
row = 1;
col = 0;
}
Lexer::~Lexer() {
ifs.close();
}
void Lexer::reserve(Token token) {
words[token.getValue()] = token;
}
void Lexer::readch() {
peek = ifs.get();
col++;
}
Token Lexer::scan() {
while (!ifs.eof()) {
if (peek == '\n') {
row++;
col = 0;
}
else if (!(peek == ' ' || peek == '\t' || peek == '\r')) {
break;
}
readch();
}
switch (peek) {
case '.':
readch();
return Token(AQLToken::DOT, ".");
case '(':
readch();
return Token(AQLToken::LEFT_PARENTHESIS, "(");
case ')':
readch();
return Token(AQLToken::RIGHT_PARENTHESIS, ")");
case '<':
readch();
return Token(AQLToken::LEFT_ANGLE_BACKET, "<");
case '>':
readch();
return Token(AQLToken::RIGHT_ANGLE_BACKET, ">");
case '{':
readch();
return Token(AQLToken::LEFT_BRACE, "{");
case '}':
readch();
return Token(AQLToken::RIGHT_BRACE, "}");
case ',':
readch();
return Token(AQLToken::COMMA, ",");
case ';':
readch();
return Token(AQLToken::SEMICOLON, ";");
}
// 匹配正则表达式(形如 /abc/)
if (peek == '/') {
string reg;
while (!ifs.eof()) {
readch();
if (peek == '/') { // 正则表达式的右端
readch();
break;
}
else {
reg += peek;
if (peek == '\\') {
readch();
reg += peek;
}
}
}
return Token(AQLToken::REG, reg);
}
// 匹配数字
if (isdigit(peek)) {
string num;
while (!ifs.eof() && isdigit(peek)) {
num += peek;
readch();
}
return Token(AQLToken::NUM, num);
}
// 匹配ID
if (isalpha(peek) || peek == '_') {
string identity;
while (!ifs.eof() && (isalnum(peek) || peek == '_')) {
identity += peek;
readch();
}
if (words.find(identity) == words.end()) { // 找不到则新建
words[identity] = Token(AQLToken::ID, identity);
}
return words[identity];
}
// 若无匹配则抛出异常
if (!ifs.eof()) {
cout << "Lexical error: In row " << row << " and column " << col << "." << endl;
throw LexicalErrorException();
}
return Token(AQLToken::END, "");
}
void Lexer::printCurrentPosition() {
ifstream fs(filePath.c_str());
int currentRow = 1;
string line;
while (getline(fs, line) && currentRow != this->row) {
currentRow++;
}
cout << "In file \"" << filePath << "\", line " << row << ", col " << col << ":" << endl;
cout << setw(4) << row;
cout << "| " << line << endl;
cout << setfill(' ') << setw(5 + col) << "";
cout << "^" << endl;
cout << endl;
}
| [
"553544693@qq.com"
] | 553544693@qq.com |
ebd843d2e02ba9e2f684cd66e7944eae2770cb0f | 2af943fbfff74744b29e4a899a6e62e19dc63256 | /Slicer30Architecture/DataModelManager/oldvtkMrml/vtkMrmlEndScenesNode.h | e961b009844f6d8c8fe5306dc013cf6c4d653e2c | [] | no_license | lheckemann/namic-sandbox | c308ec3ebb80021020f98cf06ee4c3e62f125ad9 | 0c7307061f58c9d915ae678b7a453876466d8bf8 | refs/heads/master | 2021-08-24T12:40:01.331229 | 2014-02-07T21:59:29 | 2014-02-07T21:59:29 | 113,701,721 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | h | /*=auto=========================================================================
Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $RCSfile: vtkMrmlEndScenesNode.h,v $
Date: $Date: 2005/12/20 22:44:24 $
Version: $Revision: 1.5.16.1 $
=========================================================================auto=*/
#ifndef __vtkMrmlEndScenesNode_h
#define __vtkMrmlEndScenesNode_h
#include "vtkMrmlNode.h"
#include "vtkSlicer.h"
class VTK_SLICER_BASE_EXPORT vtkMrmlEndScenesNode : public vtkMrmlNode
{
public:
static vtkMrmlEndScenesNode *New();
vtkTypeMacro(vtkMrmlEndScenesNode,vtkMrmlNode);
void PrintSelf(ostream& os, vtkIndent indent);
//--------------------------------------------------------------------------
// Utility Functions
//--------------------------------------------------------------------------
// Description:
// Write the node's attributes to a MRML file in XML format
void Write(ofstream& of, int indent);
// Description:
// Copy the node's attributes to this object
void Copy(vtkMrmlNode *node);
};
#endif
| [
"ibanez@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8"
] | ibanez@5e132c66-7cf4-0310-b4ca-cd4a7079c2d8 |
45561f2fb194471657535040467958c7552929c1 | 66d59c42fc88270bed4ce6ab18e7b6b573b4cf1a | /10.9 generate parentheses/main.cpp | b10ccfee6e838cf7c6536b82ac494966625c31b1 | [] | no_license | bluebambu/Leetcode_cpp | 0e749322c5081ee6b61191931c853ab0ce9094f9 | 7a21e391d7a6bde4c202e46047880c30195bb023 | refs/heads/master | 2022-05-28T13:11:06.991523 | 2020-05-03T00:36:13 | 2020-05-03T00:36:13 | 260,799,312 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,620 | cpp | #include <iostream>
#include <stdlib.h>
#include <math.h>
#include <list>
#include <vector>
#include <algorithm> // std::for_each
#include <unordered_map>
#include <queue>
#include <stack>
using namespace std;
inline int exchg(int &a, int &b) {int c=a; a=b; b=c;}
inline int log2(int N){return log10(N)/log10(2);}
inline float min(float a, float b) {return a<b?a:b;}
class Solution2 {
public:
/// lc passed
vector<string> generateParenthesis(int n) {
vector<string> result;
if(!n) return result;
string path;
dfs(n, 0, 0, path, result);
return result;
}
void dfs(int n, int left, int right, string& path, vector<string>& result){
if(left==n && right==n){
result.push_back(path);
return;
}
if(left<=n){
path.push_back('(');
dfs(n, left+1, right, path, result);
path.pop_back();
}
if(right<=n && right<left){
path.push_back(')');
dfs(n, left, right+1, path, result);
path.pop_back();
}
}
};
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> result;
string str("(");
result.push_back(str);
vector<int> left({1});
for(int pos = 1;pos < 2*n;++pos) {
// pos 是现在括号的长度,从1 ~ 5,
int tmp = left.size();
// 也可以是 result.size()
for(int i = 0;i < tmp;++i) {
if(left[i] < n) {
if(pos - left[i] < left[i]) {
// pos - left[i] means that when left[i]<n,
// the number of ')' in the current string.
result.push_back(result[i] + ')');
left.push_back(left[i]);
}
result[i] += '(';
left[i]++;
}
else {
result[i] += ')';
continue; // 多余
}
}
}
return result;
}
///////////////////////////////////////////////////////////////////
vector<string> generateParenthesis2(int n) {
vector<string> res;
dfs(n, n, "", res);
return res;
}
void dfs(int l, int r, string path, vector<string>& res) {
if (l < 0 || r < 0 || l > r)
return;
if (l == 0 && r == 0)
res.push_back(path);
dfs(l-1, r, path+'(', res);
dfs(l, r-1, path+')', res);
}
};
int main()
{
Solution a;
vector<int> intset {1,2,3};
auto b = a.generateParenthesis2(3);
for(auto i:b)
{for(auto j: i)
cout<<j;
cout<<endl;
}
}
| [
"electricitymouse@gmail.com"
] | electricitymouse@gmail.com |
c7e95f52f240afde162ffcb9cbe48fd90e44a4a1 | a0c408b4a38e4fa71398465c4084ab7fe96b2b98 | /VulkanTutorial_09/VulkanTutorial/src/main.cpp | fd623caea06bfd1e31bdf25835aeff70dfed3b04 | [] | no_license | Zandriy/VulkanTutorial | 7079ef17d9ecbb4bcb7791eb93dcb3bfe24177a5 | 9a9ecbbd4261e0c509371ab4ec0ac6e0f63878b8 | refs/heads/master | 2021-01-11T05:54:25.862581 | 2017-01-14T19:23:24 | 2017-01-14T19:23:24 | 69,876,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,745 | cpp | /* main.cpp
* VulkanTutorial project
*
* Created by Andriy Zhabura on 02-Oct-2016.
* Last modified on 08-Oct-2016.
*/
/*
* Copyright © 2016 Andriy Zhabura
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting documentation, and
* that the name of the copyright holders not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no representations
* about the suitability of this software for any purpose. It is provided "as
* is" without express or implied warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include <iostream>
#include "ZVK_Application.h"
int main(int argc, char **argv)
try
{
////// Start VulkanTutorial_01. //////
ZVK_Application app;
std::cout << "Vulkan Application was successfully created.\n";
////// Start VulkanTutorial_02. //////
std::vector<std::string> names = app.get_LayerPropertiesNames();
if (names.size())
{
std::cout << "Available layers:\n";
for (auto name : names)
{
std::cout << " " << name << "\n";
}
}
names = app.get_ExtensionPropertiesNames();
if (names.size())
{
std::cout << "Available layers extensions:\n";
for (auto name : names)
{
std::cout << " " << name << "\n";
}
}
std::cout << "Found " << app.get_PhysicalDevicesQty()
<< " physical device" << (app.get_PhysicalDevicesQty() > 1 ? "s.\n" : ".\n");
////// Start VulkanTutorial_03. //////
std::cout << "Logical Device is "
<< (app.create_LogicalDevice() ? "" : "NOT ") << "created.\n";
////// Start VulkanTutorial_04. //////
std::cout << "Command Buffers are "
<< (app.allocate_CommandBuffers() ? "" : "NOT ") << "allocated.\n";
////// Start VulkanTutorial_05. //////
std::cout << "Swap Chain is "
<< (app.create_Swapchain() ? "" : "NOT ") << "created.\n";
std::cout << "Image Views are "
<< (app.create_ImageViews() ? "" : "NOT ") << "created.\n";
////// Start VulkanTutorial_06. //////
std::cout << "Depth Buffer is "
<< (app.create_DepthBuffer() ? "" : "NOT ") << "created.\n";
////// Start VulkanTutorial_07. //////
std::cout << "Uniform Buffer is "
<< (app.create_UniformBuffer() ? "" : "NOT ") << "created.\n";
////// Start VulkanTutorial_08. //////
std::cout << "Descriptor Set Layout is "
<< (app.create_DescriptorSetLayout() ? "" : "NOT ") << "created.\n";
std::cout << "Pipeline Layout is "
<< (app.create_PipelineLayout() ? "" : "NOT ") << "created.\n";
////// Start VulkanTutorial_09. //////
std::cout << "Descriptor Sets are "
<< (app.allocate_DescriptorSets() ? "" : "NOT ") << "allocated.\n";
app.update_DescriptorSets();
std::cout << "Descriptor Sets are updated.\n";
return 0;
}
catch (std::bad_alloc&)
{
std::cerr << "Problem with Vulkan Application creation\n";
return 1;
}
catch (std::domain_error& err)
{
std::cerr << err.what() << "\n";
return 2;
}
catch (...)
{
std::cout << "Uncaught exception discovered\n";
return -1;
} | [
"andriy@zhabura.com"
] | andriy@zhabura.com |
c85355a0bef5c64095cdeee09d0be6a6cc94b244 | 45e144acd5da6e6eee7e77ebb21e31fb000fd369 | /tests/TestUtils.cpp | 93c17347b0696e43b8f7f9feb446997cbfee42ff | [
"BSD-3-Clause"
] | permissive | ziqings/skia | a46a9528a592555f8e19615b471d73250e727eb1 | 8b5cf82dca3797066e5acc212381a0c8bd3debd9 | refs/heads/master | 2020-06-08T20:51:44.256435 | 2019-06-22T13:35:13 | 2019-06-22T18:36:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,681 | cpp | /*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "tests/TestUtils.h"
#include "include/encode/SkPngEncoder.h"
#include "include/utils/SkBase64.h"
#include "src/core/SkUtils.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrDrawingManager.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrSurfaceContext.h"
#include "src/gpu/GrSurfaceProxy.h"
#include "src/gpu/GrTextureContext.h"
#include "src/gpu/GrTextureProxy.h"
#include "src/gpu/SkGr.h"
void test_read_pixels(skiatest::Reporter* reporter,
GrSurfaceContext* srcContext, uint32_t expectedPixelValues[],
const char* testName) {
int pixelCnt = srcContext->width() * srcContext->height();
SkAutoTMalloc<uint32_t> pixels(pixelCnt);
memset(pixels.get(), 0, sizeof(uint32_t)*pixelCnt);
SkImageInfo ii = SkImageInfo::Make(srcContext->width(), srcContext->height(),
kRGBA_8888_SkColorType, kPremul_SkAlphaType);
bool read = srcContext->readPixels(ii, pixels.get(), 0, 0, 0);
if (!read) {
ERRORF(reporter, "%s: Error reading from texture.", testName);
}
for (int i = 0; i < pixelCnt; ++i) {
if (pixels.get()[i] != expectedPixelValues[i]) {
ERRORF(reporter, "%s: Error, pixel value %d should be 0x%08x, got 0x%08x.",
testName, i, expectedPixelValues[i], pixels.get()[i]);
break;
}
}
}
void test_write_pixels(skiatest::Reporter* reporter,
GrSurfaceContext* dstContext, bool expectedToWork,
const char* testName) {
int pixelCnt = dstContext->width() * dstContext->height();
SkAutoTMalloc<uint32_t> pixels(pixelCnt);
for (int y = 0; y < dstContext->width(); ++y) {
for (int x = 0; x < dstContext->height(); ++x) {
pixels.get()[y * dstContext->width() + x] =
SkColorToPremulGrColor(SkColorSetARGB(2*y, x, y, x + y));
}
}
SkImageInfo ii = SkImageInfo::Make(dstContext->width(), dstContext->height(),
kRGBA_8888_SkColorType, kPremul_SkAlphaType);
bool write = dstContext->writePixels(ii, pixels.get(), 0, 0, 0);
if (!write) {
if (expectedToWork) {
ERRORF(reporter, "%s: Error writing to texture.", testName);
}
return;
}
if (write && !expectedToWork) {
ERRORF(reporter, "%s: writePixels succeeded when it wasn't supposed to.", testName);
return;
}
test_read_pixels(reporter, dstContext, pixels.get(), testName);
}
void test_copy_from_surface(skiatest::Reporter* reporter, GrContext* context,
GrSurfaceProxy* proxy, uint32_t expectedPixelValues[],
const char* testName) {
sk_sp<GrTextureProxy> dstProxy = GrSurfaceProxy::Copy(context, proxy, GrMipMapped::kNo,
SkBackingFit::kExact, SkBudgeted::kYes);
SkASSERT(dstProxy);
sk_sp<GrSurfaceContext> dstContext =
context->priv().makeWrappedSurfaceContext(std::move(dstProxy));
SkASSERT(dstContext.get());
test_read_pixels(reporter, dstContext.get(), expectedPixelValues, testName);
}
void fill_pixel_data(int width, int height, GrColor* data) {
for (int j = 0; j < height; ++j) {
for (int i = 0; i < width; ++i) {
unsigned int red = (unsigned int)(256.f * (i / (float)width));
unsigned int green = (unsigned int)(256.f * (j / (float)height));
data[i + j * width] = GrColorPackRGBA(red - (red >> 8), green - (green >> 8),
0xff, 0xff);
}
}
}
bool create_backend_texture(GrContext* context, GrBackendTexture* backendTex,
const SkImageInfo& ii, GrMipMapped mipMapped, SkColor color,
GrRenderable renderable) {
SkBitmap bm;
bm.allocPixels(ii);
sk_memset32(bm.getAddr32(0, 0), color, ii.width() * ii.height());
SkASSERT(GrMipMapped::kNo == mipMapped);
// TODO: replace w/ the color-init version of createBackendTexture once Metal supports it.
*backendTex = context->priv().createBackendTexture(&bm.pixmap(), 1, renderable);
return backendTex->isValid();
}
void delete_backend_texture(GrContext* context, const GrBackendTexture& backendTex) {
GrFlushInfo flushInfo;
flushInfo.fFlags = kSyncCpu_GrFlushFlag;
context->flush(flushInfo);
context->deleteBackendTexture(backendTex);
}
bool does_full_buffer_contain_correct_color(const GrColor* srcBuffer,
const GrColor* dstBuffer,
int width,
int height) {
const GrColor* srcPtr = srcBuffer;
const GrColor* dstPtr = dstBuffer;
for (int j = 0; j < height; ++j) {
for (int i = 0; i < width; ++i) {
if (srcPtr[i] != dstPtr[i]) {
return false;
}
}
srcPtr += width;
dstPtr += width;
}
return true;
}
bool bitmap_to_base64_data_uri(const SkBitmap& bitmap, SkString* dst) {
SkPixmap pm;
if (!bitmap.peekPixels(&pm)) {
dst->set("peekPixels failed");
return false;
}
// We're going to embed this PNG in a data URI, so make it as small as possible
SkPngEncoder::Options options;
options.fFilterFlags = SkPngEncoder::FilterFlag::kAll;
options.fZLibLevel = 9;
SkDynamicMemoryWStream wStream;
if (!SkPngEncoder::Encode(&wStream, pm, options)) {
dst->set("SkPngEncoder::Encode failed");
return false;
}
sk_sp<SkData> pngData = wStream.detachAsData();
size_t len = SkBase64::Encode(pngData->data(), pngData->size(), nullptr);
// The PNG can be almost arbitrarily large. We don't want to fill our logs with enormous URLs.
// Infra says these can be pretty big, as long as we're only outputting them on failure.
static const size_t kMaxBase64Length = 1024 * 1024;
if (len > kMaxBase64Length) {
dst->printf("Encoded image too large (%u bytes)", static_cast<uint32_t>(len));
return false;
}
dst->resize(len);
SkBase64::Encode(pngData->data(), pngData->size(), dst->writable_str());
dst->prepend("data:image/png;base64,");
return true;
}
#include "src/utils/SkCharToGlyphCache.h"
static SkGlyphID hash_to_glyph(uint32_t value) {
return SkToU16(((value >> 16) ^ value) & 0xFFFF);
}
namespace {
class UnicharGen {
SkUnichar fU;
const int fStep;
public:
UnicharGen(int step) : fU(0), fStep(step) {}
SkUnichar next() {
fU += fStep;
return fU;
}
};
}
DEF_TEST(chartoglyph_cache, reporter) {
SkCharToGlyphCache cache;
const int step = 3;
UnicharGen gen(step);
for (int i = 0; i < 500; ++i) {
SkUnichar c = gen.next();
SkGlyphID glyph = hash_to_glyph(c);
int index = cache.findGlyphIndex(c);
if (index >= 0) {
index = cache.findGlyphIndex(c);
}
REPORTER_ASSERT(reporter, index < 0);
cache.insertCharAndGlyph(~index, c, glyph);
UnicharGen gen2(step);
for (int j = 0; j <= i; ++j) {
c = gen2.next();
glyph = hash_to_glyph(c);
index = cache.findGlyphIndex(c);
if ((unsigned)index != glyph) {
index = cache.findGlyphIndex(c);
}
REPORTER_ASSERT(reporter, (unsigned)index == glyph);
}
}
}
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
8740b1eac018140670e2e06862d8248571588520 | 6d98ac10b5b8909a9eedcf2cd7ab2686e1155542 | /Cocos2d-x/QFLTest/Classes/QFLTestMenu.cpp | 051714dc5d88fa11297b4cd4c4c37e82ff49d9f0 | [] | no_license | qufangliu/MyTest | 926dabc6e12a0fa4020cc96d3a2d1a228ed354a0 | 156e954bcbb624f51e17ce09443d5461f5c0b094 | refs/heads/master | 2020-09-22T20:54:29.697088 | 2016-10-10T23:55:39 | 2016-10-10T23:55:39 | 66,987,202 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,837 | cpp | //
// QFLTestMenu.cpp
// QFLTest
//
// Created by QuFangliu on 16/8/30.
//
//
#include "QFLTestMenu.hpp"
#include "QFLTools/QFLHelper.hpp"
//TestClass
#include "TestBlend/QFLTestBlend.hpp"
#include "TestSimpleAudio/QFLTestSimpleAudio.hpp"
#include "TestMotionStreak/QFLTestStreak.hpp"
#include "TestFSM/QFLTestFSM.hpp"
#include "TestElevator/QFLTestElevator.hpp"
USING_NS_CC;
cocos2d::Scene* QFLTestMenu::createScene()
{
auto pTestScene = Scene::create();
auto pTestMenuLayer = QFLTestMenu::create();
pTestScene->addChild(pTestMenuLayer);
return pTestScene;
}
bool QFLTestMenu::init()
{
if (!Layer::init()) {
return false;
}
else {
this->addUI();
this->addMenus();
return true;
}
}
void QFLTestMenu::addUI()
{
//获取size
auto sizeScreen = Director::getInstance()->getVisibleSize();
//生成列表
m_pListMenu = ui::ListView::create();
m_pListMenu->setContentSize(sizeScreen);
m_pListMenu->setPosition(SCREEN_VISIBLE_ORIGIN);
m_pListMenu->setGravity(cocos2d::ui::ListView::Gravity::CENTER_VERTICAL);
m_pListMenu->setBounceEnabled(true);
m_pListMenu->setDirection(cocos2d::ui::ScrollView::Direction::VERTICAL);
m_pListMenu->setScrollBarEnabled(false);
this->addChild(m_pListMenu);
//初始化菜单计数
m_nItemCounter = 0;
}
void QFLTestMenu::addMenus()
{
//添加菜单项
this->addMenuItem("TestBlend", [=](){
this->addChild(QFLTestBlend::create());
});
this->addMenuItem("TestSimpleAudioEngine", [=](){
this->addChild(QFLTestSimpleAudio::create());
});
this->addMenuItem("TestMotionStreak", [=](){
this->addChild(QFLTestMotionStreak::create());
});
this->addMenuItem("TestFSM", [=](){
this->addChild(QFLTestFSM::create());
});
this->addMenuItem("TestElevator", [=](){
this->addChild(QFLTestElevator::create());
});
}
void QFLTestMenu::addMenuItem(const std::string &strItem, const std::function<void()> &funcCallback)
{
//计数
m_nItemCounter ++;
//生成一个Item
auto pModel = cocos2d::ui::Widget::create();
pModel->setContentSize(Size(SCREEN_VISIBLE_SIZE.width, 50.0f));
//添加Label
auto pLabel = Label::createWithSystemFont(StringUtils::format("%d:%s", m_nItemCounter, strItem.c_str()),
QFLConfig::strSystemFontName,
QFLConfig::nSystemFontSize);
pLabel->setPosition(pModel->getContentSize() * 0.5);
pModel->addChild(pLabel);
//添加事件
pModel->setTouchEnabled(true); //这里很重要
pModel->addClickEventListener([=](Ref* ref){
funcCallback();
});
//添加Item
m_pListMenu->pushBackCustomItem(pModel);
}
| [
"qufl@feiyu.com"
] | qufl@feiyu.com |
a1abeefba2211c9b8bf3cfe0cb958d31867cbbba | 607c4f4497ac2a3b16287cd66262d3decaa30278 | /include/kuibase/Common/List2.h | c5999e1586498b0a1b0d08839fa0251f700259da | [] | no_license | ExpLife0011/kui | 53eed82f1d762bf241f47e989050c6df5f6d9bec | 0d5f45a814429bea3463284b50f849813e97a257 | refs/heads/master | 2020-03-22T08:56:20.740779 | 2018-04-19T08:42:56 | 2018-04-19T08:42:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,172 | h | /*@Author Zeki.Yan*/
#pragma once
#include "../Common.h"
namespace OpenHMI
{
/**
* @class List2
* It is a common list class and its member must be an instance of class T.
* The type T must support "=" operation.
*/
template <typename T>
class List2 : public Object
{
public:// const define
private:// const define
public:// embed class or struct or enum
private:// embed class or struct or enum
struct tagNode
{
T data;
tagNode *pPre;
tagNode *pNext;
tagNode(T tData)
: data(tData)
, pPre(NULL)
, pNext(NULL)
{
;
}
};
public:// method
List2()
: m_pFront(NULL)
, m_pRear(NULL)
, m_pCur(NULL)
, m_ulSize(0)
{
;
}
virtual ~List2(void)
{
clear();
}
/**
* @brief Begin to access to each item of the list2.
* Used with hasMore and next functions together.
* Example:
*
* List2<T> temp;
* temp.resetIterator();
* while (temp.hasMore())
* { T &t = temp.next(); }
*
* @return void
*/
void resetIterator()
{
m_pCur = m_pFront;
}
BOOLEAN hasMore()
{
return m_pCur != NULL ? TRUE : FALSE;
}
T& next()
{
if (m_pCur != NULL)
{
tagNode *pNode = m_pCur;
m_pCur = m_pCur->pNext;
return pNode->data;
}
return m_tTemp;
}
BOOLEAN isExist(const T &data) const
{
tagNode *pNode = m_pFront;
while (pNode != NULL)
{
if (pNode->data == data)
{
return TRUE;
}
pNode = pNode->pNext;
}
return FALSE;
}
BOOLEAN isEmpty(void) const
{
return m_ulSize == 0 ? TRUE : FALSE;
}
ULONG size(void) const
{
return m_ulSize;
}
T& operator [](UINT uiIndex)
{
if (uiIndex >= m_ulSize)
{
return m_tTemp;
}
tagNode *pNode = m_pFront;
for (UINT i = 0; i < uiIndex; i++)
{
pNode = pNode->pNext;
}
return pNode->data;
}
T operator [](UINT uiIndex) const
{
if (uiIndex >= m_ulSize)
{
return m_tTemp;
}
tagNode *pNode = m_pFront;
for (UINT i = 0; i < uiIndex; i++)
{
pNode = pNode->pNext;
}
return pNode->data;
}
LONG getItemIndex(const T &data) const
{
tagNode *pNode = m_pFront;
for (LONG i = 0; i < m_ulSize; i++)
{
if (pNode->data == data)
{
return i;
}
pNode = pNode->pNext;
}
return -1;
}
void addFirst(const T &data)
{
tagNode *pNode = new tagNode(data);
if (pNode != NULL)
{
pNode->pNext = m_pFront;
if (m_pFront != NULL)
{
m_pFront->pPre = pNode;
}
m_pFront = pNode;
m_ulSize ++;
if (m_ulSize == 1)
{
m_pRear = m_pFront;
m_pCur = m_pFront;
}
}
}
void addLast(const T &data)
{
tagNode *pNode = new tagNode(data);
if (pNode != NULL)
{
pNode->pPre = m_pRear;
if (m_pRear != NULL)
{
m_pRear->pNext = pNode;
}
m_pRear = pNode;
m_ulSize ++;
if (m_ulSize == 1)
{
m_pFront = m_pRear;
m_pCur = m_pRear;
}
}
}
void insert(ULONG ulIndex, const T &data)
{
if (ulIndex = 0)
{
addFirst(data);
return;
}
else if (ulIndex >= m_ulSize)
{
addLast(data);
return;
}
else
{
tagNode *pNewNode = new tagNode(data);
if (pNewNode != NULL)
{
tagNode *pNode = m_pFront;
for (ULONG i = 0; i < ulIndex; i++)
{
pNode = pNode->pNext;
}
pNewNode->pPre = pNode->pPre;
pNode->pPre->pNext = pNewNode;
pNode->pPre = pNewNode;
pNewNode->pNext = pNode;
m_ulSize ++;
}
}
}
BOOLEAN deleteItem(const T &data)
{
if (m_ulSize == 0)
{
// do nothing
}
else if (m_ulSize == 1)
{
if (data == m_pFront->data)
{
deleteNode(m_pFront);
m_pFront = m_pRear = m_pCur = NULL;
m_ulSize = 0;
return TRUE;
}
}
else
{
if (data == m_pFront->data)
{
tagNode *pNode = m_pFront;
m_pFront = m_pFront->pNext;
m_pFront->pPre = NULL;
deleteNode(pNode);
m_ulSize--;
return TRUE;
}
else if (data == m_pRear->data)
{
tagNode *pNode = m_pRear;
m_pRear = m_pRear->pPre;
m_pRear->pNext = NULL;
deleteNode(pNode);
m_ulSize--;
return TRUE;
}
else
{
tagNode *pNode = m_pFront;
while (pNode != NULL)
{
if (pNode->data == data)
{
pNode->pNext->pPre = pNode->pPre;
pNode->pPre->pNext = pNode->pNext;
deleteNode(pNode);
m_ulSize --;
return TRUE;
}
pNode = pNode->pNext;
}
}
}
return FALSE;
}
BOOLEAN deleteItemByIndex(UINT uiIndex)
{
if (uiIndex >= m_ulSize)
{
return FALSE;
}
if (m_ulSize == 1)
{
deleteNode(m_pFront);
m_pFront = m_pRear = m_pCur = NULL;
m_ulSize = 0;
return TRUE;
}
else
{
if (uiIndex == 0)
{
tagNode *pNode = m_pFront;
m_pFront = m_pFront->pNext;
m_pFront->pPre = NULL;
deleteNode(pNode);
m_ulSize--;
return TRUE;
}
else if (uiIndex == m_ulSize - 1)
{
tagNode *pNode = m_pRear;
m_pRear = m_pRear->pPre;
m_pRear->pNext = NULL;
deleteNode(pNode);
m_ulSize--;
return TRUE;
}
else
{
tagNode *pNode = m_pFront;
for (UINT i = 0; i < uiIndex; i++)
{
pNode = pNode->pNext;
}
pNode->pNext->pPre = pNode->pPre;
pNode->pPre->pNext = pNode->pNext;
deleteNode(pNode);
m_ulSize --;
return TRUE;
}
}
return FALSE;
}
T popFirst()
{
if (m_ulSize == 0)
{
return NULL;
}
else if (m_ulSize == 1)
{
T data = m_pFront->data;
delete m_pFront;
m_pFront = m_pRear = m_pCur = NULL;
m_ulSize = 0;
return data;
}
else
{
tagNode *pNode = m_pFront;
m_pFront = m_pFront->pNext;
m_pFront->pPre = NULL;
T data = pNode->data;
delete pNode;
m_ulSize--;
return data;
}
}
T popLast()
{
if (m_ulSize == 0)
{
return NULL;
}
else if (m_ulSize == 1)
{
T data = m_pRear->data;
delete m_pRear;
m_pFront = m_pRear = m_pCur = NULL;
m_ulSize = 0;
return data;
}
else
{
tagNode *pNode = m_pRear;
m_pRear = m_pRear->pPre;
m_pRear->pNext = NULL;
T data = pNode->data;
delete pNode;
m_ulSize--;
return data;
}
}
T* getFirst()
{
if (m_pFront != NULL)
{
return m_pFront->data;
}
else
{
return NULL;
}
}
T* getLast()
{
if (m_pRear != NULL)
{
return m_pRear->data;
}
else
{
return NULL;
}
}
void clear()
{
tagNode *pNode = NULL;
while (m_pFront != NULL)
{
pNode = m_pFront;
m_pFront = m_pFront->pNext;
deleteNode(pNode);
}
m_pFront = m_pRear = m_pCur = NULL;
m_ulSize = 0;
}
protected:// method
List2(const List2<T>&){}
List2<T>& operator =(const List2<T>&){return *this;}
private:// method
void deleteNode(tagNode *pNode)
{
delete pNode;
}
protected:// property
private:// property
tagNode *m_pFront;
tagNode *m_pRear;
tagNode *m_pCur;
ULONG m_ulSize;
T m_tTemp;
};
} | [
"yanyan520209@126.com"
] | yanyan520209@126.com |
2777e8112df8621579d70c49730cc66a39300fa6 | cb9bf2843d732e841207f396915d190f908e02ff | /OpenServerCommand.h | 8379a156c30a0d978fe095f78059e92bdf096f97 | [] | no_license | noamschwartz/Algorithmic-Programming---Part-One | 4efab164e171fa67b9cf1cb0e7701506c159bb10 | e8aed4163376ef748d38f23269d54ea084058f31 | refs/heads/master | 2020-05-27T16:13:46.655972 | 2019-05-26T14:59:41 | 2019-05-26T14:59:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | h | #ifndef PROJRCT_OPENSERVERCOMMAND_H
#define PROJRCT_OPENSERVERCOMMAND_H
#include "Command.h"
#include "DefineVarCommand.h"
#include <thread>
#include <stdio.h>
#include <stdlib.h>
#include "DataReaderServer.h"
#include <string>
class OpenServerCommand : public Command {
DefineVarCommand *dfCommand;
thread test_thread;
DataReaderServer *ds;
public:
OpenServerCommand(DefineVarCommand *varCommand);
virtual ~OpenServerCommand();
virtual int doCommand(const vector<string> &vector, int index);
};
#endif | [
"noamschwartz1@gmail.com"
] | noamschwartz1@gmail.com |
9bc01d65c95be0194cec51e635877be9dc518992 | d462de612cb6ce58cbc209b3b161bf97c007d9ad | /Source/ProceduralTerrainGenerator/Public/LandscapeFilterFactory.h | 926d2b9a787e1c76f0f6d911e5770f1e0fac01cf | [
"Apache-2.0"
] | permissive | jjh2v2/procedural-terrain-generator-UE4-plugin | a77fb2df0d61355e9bb265d2235a249997e1688e | bebf4723e86eeeb75b444bef68dbaaf662813165 | refs/heads/master | 2022-03-13T01:09:08.283371 | 2019-08-12T14:17:01 | 2019-08-12T14:17:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "RecipeForTerrain.h"
#include "Factories/Factory.h"
#include "LandscapeFilterFactory.generated.h"
UCLASS()
class ULandscapeFilterFactory : public UFactory
{
GENERATED_UCLASS_BODY()
public:
virtual UObject* FactoryCreateNew(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn) override;
virtual bool ShouldShowInNewMenu() const override {
return true;
};
}; | [
"pmgberm@gmail.com"
] | pmgberm@gmail.com |
d1f152b54b4b22d51799e90331b936de6de47758 | 3f23af2ea246aa743d9feb755db8b873132e20aa | /src/libCUFEM/BaseMaterial.h | d55130d4047892c70b6ea9190484991b8654363e | [] | no_license | hubin8851/FEM_CUDA_Boost_V2 | dd8c8a9d8852fc38247797298db9742d6a7bc795 | 72bc108254109e72a124932a8c52bea700eb26c8 | refs/heads/master | 2022-03-03T07:53:04.083066 | 2019-11-04T14:53:13 | 2019-11-04T14:53:13 | 108,487,365 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 700 | h | #pragma once
#include <string.h>
#include <ExportDef.h>
#include <HbxDefMacro.h>
#include <libCUFEM\InputRecord.h>
namespace HBXFEMDef
{
class Domain;
class InputRecord;
//该类主要实现材料相关的算法
class CUFEM_API BaseMaterial
{
private:
protected:
public:
std::string _myName;
BaseMaterial(Domain* _dm, int _id) {};
BaseMaterial(const BaseMaterial&) {};
virtual ~BaseMaterial() {};
//可能内含时间历程信息
virtual InputFileResult_t InitFrom(InputRecord * _dr);
};
template<typename T> BaseMaterial* MaterialCreator() { return new T(); };
template<typename T> BaseMaterial* MaterialCreator(Domain *_dm, int _id) { return new T(_dm, _id); };
}
| [
"376898978@qq.com"
] | 376898978@qq.com |
c0944062d7e6ee86e524b92d5335a5ded921caad | 7f9a5b9bb4b85d48e958efb078f076c081c6aee2 | /SudoPlacements/Strings/18.ValidateIPAddress.cpp | 4d099cb8c3f8864f7561c8bc46c222b2d86f90be | [] | no_license | anuragroy11/GeeksForGeeks | dd6075df188033f3c740ec98b98c7c12911e1594 | ec9af2d85f1900394be19063ff5196da83c6dc7c | refs/heads/master | 2020-03-22T17:27:45.646008 | 2018-08-16T14:21:49 | 2018-08-16T14:21:49 | 140,396,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 971 | cpp | /*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/
/* The function returns 1 if
IP string is valid else return 0
You are required to complete this method */
int isValid(char *ip) {
string x = ip;
int dots = 0;
for (auto c : x) {
if (c == '.')
dots++;
else if (!isdigit(c))
return 0;
}
if (dots != 3)
return 0;
vector<string> parts(4, "");
int j = 0;
for (int i = 0; i < x.size(); i++) {
if (x[i] != '.')
parts[j].push_back(x[i]);
else if (x[i] == '.')
j++;
}
for (auto p : parts) {
if (p.empty())
return 0;
if ((p.size() > 1) && (p[0] == '0'))
return 0;
if ((stoi(p) < 0) || (stoi(p) > 255))
return 0;
}
return 1;
} | [
"anuragroy11@gmail.com"
] | anuragroy11@gmail.com |
c7a16526c21f2c14bdec55cdb0a405a99c82a814 | 05c3e9966e016c6dda806ce41fa5c7139fe5fdb9 | /src/game/components/ticker.cpp | 08ab0d15267287ec5583916f816869ff4b31b685 | [] | no_license | Bobgy/simple_mc | b541c17dd5eb4341baae4f76c0b28f76a9265235 | 5c09ed547a0d2f8ef6713021f3198aadc6daad24 | refs/heads/master | 2020-12-19T19:19:11.161906 | 2016-08-01T08:46:41 | 2016-08-01T08:46:41 | 26,166,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | cpp | #include "stdafx.h"
#include "ticker.h"
#include "game/entity.h"
Ticker::~Ticker()
{
// do nothing
}
template class TickerBFS<Entity>;
template <typename T>
TickerBFS<T>::~TickerBFS()
{
// do nothing
}
template <typename T>
void TickerBFS<T>::tick(flt delta_time)
{
if (!m_list) return;
m_opened.clear();
while (!m_queue.empty()) m_queue.pop();
for (auto u : *m_list) {
if (!u) continue;
m_queue.push(u);
while (!m_queue.empty()) {
T *a = m_queue.front();
m_queue.pop();
shared_ptr<vector<T*>> exp = a->getController()->tick_bfs(delta_time);
if (!exp) continue;
for (auto b : *exp) {
if (m_opened.find(b) == m_opened.end()) {
m_opened.insert(b);
m_queue.push(b);
}
}
}
}
} | [
"gongyuan94@gmail.com"
] | gongyuan94@gmail.com |
aa29af9b7bbf61319ef707dc72cb03ec668538c7 | 3b1c7561c8d3b9452fc0cdefe299b208e0db1853 | /src/gpu/ganesh/GrTextureResolveRenderTask.cpp | 22b688326d669ea49b8fa1c4915e332e4a698518 | [
"BSD-3-Clause"
] | permissive | NearTox/Skia | dee04fc980bd40c1861c424b5643e7873f656b01 | 4d0cd2b6deca44eb2255651c4f04396963688761 | refs/heads/master | 2022-12-24T02:01:41.138176 | 2022-08-27T14:32:37 | 2022-08-27T14:32:37 | 153,816,056 | 0 | 0 | BSD-3-Clause | 2022-12-13T23:42:44 | 2018-10-19T17:05:47 | C++ | UTF-8 | C++ | false | false | 3,793 | cpp | /*
* Copyright 2019 Google LLC
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/ganesh/GrTextureResolveRenderTask.h"
#include "src/gpu/ganesh/GrGpu.h"
#include "src/gpu/ganesh/GrMemoryPool.h"
#include "src/gpu/ganesh/GrOpFlushState.h"
#include "src/gpu/ganesh/GrRenderTarget.h"
#include "src/gpu/ganesh/GrResourceAllocator.h"
#include "src/gpu/ganesh/GrTexture.h"
void GrTextureResolveRenderTask::addProxy(
GrDrawingManager* drawingMgr, sk_sp<GrSurfaceProxy> proxyRef,
GrSurfaceProxy::ResolveFlags flags, const GrCaps& caps) {
Resolve& resolve = fResolves.emplace_back(flags);
GrSurfaceProxy* proxy = proxyRef.get();
// Ensure the last render task that operated on the proxy is closed. That's where msaa and
// mipmaps should have been marked dirty.
SkASSERT(
!drawingMgr->getLastRenderTask(proxy) || drawingMgr->getLastRenderTask(proxy)->isClosed());
SkASSERT(GrSurfaceProxy::ResolveFlags::kNone != flags);
if (GrSurfaceProxy::ResolveFlags::kMSAA & flags) {
GrRenderTargetProxy* renderTargetProxy = proxy->asRenderTargetProxy();
SkASSERT(renderTargetProxy);
SkASSERT(renderTargetProxy->isMSAADirty());
resolve.fMSAAResolveRect = renderTargetProxy->msaaDirtyRect();
renderTargetProxy->markMSAAResolved();
}
if (GrSurfaceProxy::ResolveFlags::kMipMaps & flags) {
GrTextureProxy* textureProxy = proxy->asTextureProxy();
SkASSERT(GrMipmapped::kYes == textureProxy->mipmapped());
SkASSERT(textureProxy->mipmapsAreDirty());
textureProxy->markMipmapsClean();
}
// Add the proxy as a dependency: We will read the existing contents of this texture while
// generating mipmap levels and/or resolving MSAA.
this->addDependency(drawingMgr, proxy, GrMipmapped::kNo, GrTextureResolveManager(nullptr), caps);
this->addTarget(drawingMgr, GrSurfaceProxyView(std::move(proxyRef)));
}
void GrTextureResolveRenderTask::gatherProxyIntervals(GrResourceAllocator* alloc) const {
// This renderTask doesn't have "normal" ops, however we still need to add intervals so
// fEndOfOpsTaskOpIndices will remain in sync. We create fake op#'s to capture the fact that we
// manipulate the resolve proxies.
auto fakeOp = alloc->curOp();
SkASSERT(fResolves.count() == this->numTargets());
for (const sk_sp<GrSurfaceProxy>& target : fTargets) {
alloc->addInterval(target.get(), fakeOp, fakeOp, GrResourceAllocator::ActualUse::kYes);
}
alloc->incOps();
}
bool GrTextureResolveRenderTask::onExecute(GrOpFlushState* flushState) {
// Resolve all msaa back-to-back, before regenerating mipmaps.
SkASSERT(fResolves.count() == this->numTargets());
for (int i = 0; i < fResolves.count(); ++i) {
const Resolve& resolve = fResolves[i];
if (GrSurfaceProxy::ResolveFlags::kMSAA & resolve.fFlags) {
GrSurfaceProxy* proxy = this->target(i);
// peekRenderTarget might be null if there was an instantiation error.
if (GrRenderTarget* renderTarget = proxy->peekRenderTarget()) {
flushState->gpu()->resolveRenderTarget(renderTarget, resolve.fMSAAResolveRect);
}
}
}
// Regenerate all mipmaps back-to-back.
for (int i = 0; i < fResolves.count(); ++i) {
const Resolve& resolve = fResolves[i];
if (GrSurfaceProxy::ResolveFlags::kMipMaps & resolve.fFlags) {
// peekTexture might be null if there was an instantiation error.
GrTexture* texture = this->target(i)->peekTexture();
if (texture && texture->mipmapsAreDirty()) {
flushState->gpu()->regenerateMipMapLevels(texture);
SkASSERT(!texture->mipmapsAreDirty());
}
}
}
return true;
}
#ifdef SK_DEBUG
void GrTextureResolveRenderTask::visitProxies_debugOnly(const GrVisitProxyFunc&) const {}
#endif
| [
"NearTox@outlook.com"
] | NearTox@outlook.com |
b84ddd2c48fd3c32eef1e33e9ec83bac7b5084f9 | b79b9307f42e99273500629a41492653cabfba9a | /guslib/guslib/common/singletonholder.hpp | 794aed24453969b16b1bd667ef28ea29cd457961 | [
"MIT",
"Zlib"
] | permissive | dezGusty/guslib | ae5a02932ddc1d0ddc4a5df547981a9ffbd03472 | bdc1b9bc204e789862435e1221aa34e2c801704f | refs/heads/master | 2021-01-17T09:22:04.873777 | 2016-11-08T20:50:52 | 2016-11-08T20:50:52 | 23,933,187 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,189 | hpp | #ifndef GUS_LIB_SINGLETONHOLDER_H
#define GUS_LIB_SINGLETONHOLDER_H
// This file is part of the guslib library, licensed under the terms of the MIT License.
//
// The MIT License
// Copyright (C) 2010-2014 Augustin Preda (thegusty999@gmail.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Includes
//
//
// Platform specific definitions and overall build options for the library.
//
#include <guslib/guslibbuildopts.h>
#if GUSLIB_THREAD_SUPPORT == 1
# include <thread>
#endif
#include "guslib/common/simpleexception.h"
namespace guslib
{
// Utility class to encapsulate a singleton.
// This doesn not create the singleton, but holds onto it and CAN destroy it.
// Limitation: This can only handle singletons with public, default constructors.
// Note: a double checked locking is attempted at the object's destruction, if multithreaded
// synchronization is enabled (it will depend on 3rd party libraries for thread utilities, such
// as boost or Poco). To enable the multithreaded synchronization, you MUST define
// GUSLIB_FLAG_MULTITHREAD to 1.
//
// Note on storing these classes in a DLL:
// In order to have an actual singleton, with a single instance, you must export the symbol to the DLL.
// Make sure you do this by defining the flag "GUSLIB_EXP" in the DLL. The calling code must use the
// 'GUSLIB_IMP' preprocessor flag.
template <class T> class SingletonHolder
{
private:
static T * objectPtr_;
protected:
#if GUSLIB_THREAD_SUPPORT == 1
static std::recursive_mutex creationMutex_;
#endif
public:
// Get a pointer to the SingletonHolder instance.
static T * getPtr()
{
// first check if it was created. If the mutex would be placed first, a performance hit would occur, since
// all operations would create and release a lock.
if (nullptr == objectPtr_)
{
throw guslib::SimpleException("SingletonHolder getting nullptr");
}
return objectPtr_;
} // getptr
// Assign the pointer to the singleton instance.
static void setPtr(T * ptr)
{
if (nullptr == ptr)
{
throw guslib::SimpleException("SingletonHolder being assigned nullptr");
}
#if GUSLIB_THREAD_SUPPORT == 1
std::lock_guard<std::recursive_mutex> lg{ creationMutex_ };
#endif
objectPtr_ = ptr;
}
// Destroy the singleton instance. Again, try a double checked lock.
static void destroy()
{
if (objectPtr_)
{
#if GUSLIB_THREAD_SUPPORT == 1
std::lock_guard<std::recursive_mutex> lg{ creationMutex_ };
#endif
if (objectPtr_)
{
delete objectPtr_;
objectPtr_ = nullptr;
}
}
} // destroy
};
#if GUSLIB_FLAG_SINGLETONINST != 0
template <class T> T* SingletonHolder<T>::objectPtr_ = nullptr;
#endif
#if GUSLIB_THREAD_SUPPORT == 1
template <class T> std::recursive_mutex SingletonHolder<T>::creationMutex_;
#endif
} // namespace end
#endif // GUS_LIB_SINGLETONHOLDER_H
| [
"thegusty999@gmail.com"
] | thegusty999@gmail.com |
368d68c720fc7cafd60909b168b047e431942eae | c85cec2934b86ded18047a8e0bd1f97c75a72b0c | /src/qt/test/addressbooktests.h | 55064fb9e2e3b127d7af4da74a519bed8cc598c2 | [
"MIT"
] | permissive | ODUWAX/OduwaUSD | 1668e7e8eb615c60fe5d707284ddc9a57f58e1e0 | 8ba43a760ef85fb2b2679e772af8d2f1a3138b07 | refs/heads/master | 2023-01-08T23:47:01.636172 | 2020-11-04T10:55:27 | 2020-11-04T10:55:27 | 309,887,267 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 293 | h | #ifndef ODUWAUSD_COIN_QT_TEST_ADDRESSBOOKTESTS_H
#define ODUWAUSD_COIN_QT_TEST_ADDRESSBOOKTESTS_H
#include <QObject>
#include <QTest>
class AddressBookTests : public QObject
{
Q_OBJECT
private Q_SLOTS:
void addressBookTests();
};
#endif // ODUWAUSD_COIN_QT_TEST_ADDRESSBOOKTESTS_H
| [
"40502564+ODUWAX@users.noreply.github.com"
] | 40502564+ODUWAX@users.noreply.github.com |
3e7bca846717b4e3200491a9116db98ceef7348d | 8105fa4cb89e62f955580c2dc4ac5614e87b7f87 | /include/MyElementField.hh | b139d1574bb386c7bc64759c754c82aa0a0afaf8 | [] | no_license | alcap-org/g4sim | e6256d4f9455864b8cd6f4f9a17a967de5f3a2d7 | a185e1e9a96bbef7bfaae9ac3101b800543e6295 | refs/heads/R15b | 2021-05-23T20:20:46.010011 | 2019-11-15T09:20:33 | 2019-11-15T09:20:33 | 20,724,338 | 3 | 2 | null | 2019-11-15T09:20:35 | 2014-06-11T12:32:55 | C++ | UTF-8 | C++ | false | false | 6,419 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
//
//
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
#ifndef MyElementField_h
#define MyElementField_h 1
#include "myglobals.hh"
#include "G4Navigator.hh"
#include "G4TransportationManager.hh"
#include "G4UserLimits.hh"
#include "G4VisAttributes.hh"
// class MyElementField - interface for the EM field of one element
// This is the interface class used by GlobalField to compute the field
// value at a given point[].
// An element that represents an element with an EM field will
// derive a class from this one and implement the computation for the
// element. The construct() function will add the derived object into
// GlobalField.
class MyElementField {
private:
MyElementField& operator=(const MyElementField&);
public:
/// Constructor.
MyElementField(const G4ThreeVector, G4LogicalVolume*);
/// the actual implementation constructs the MyElementField
void construct();
/// Destructor.
virtual ~MyElementField() {
if (aNavigator) delete aNavigator;
if (boundingBox) delete boundingBox;
}
// Get center of physical field volume
G4ThreeVector getCenter(){return center;}
// Set center of physical field volume
void setCenter(G4ThreeVector);
// Print Bounding Box
G4double const* getBoundingBox();
/// setMaxStep(G4double) sets the max. step size
void setMaxStep(G4double s) {
maxStep = s;
userLimits->SetMaxAllowedStep(maxStep);
lvolume->SetUserLimits(userLimits);
}
/// getMaxStep() returns the max. step size
G4double getMaxStep() { return maxStep; }
/// setColor(G4String) sets the color
void setColor(G4String c) {
color = c;
lvolume->SetVisAttributes(getVisAttribute(color));
}
/// getColor() returns the color
G4String getColor() { return color; }
/// getVisAttribute() returns the appropriate G4VisAttributes.
static G4VisAttributes* getVisAttribute(G4String color);
/// setGlobalPoint() ensures that the point is within the global
/// bounding box of this ElementField's global coordinates.
/// Normally called 8 times for the corners of the local bounding
/// box, after a local->global coordinate transform.
/// If never called, the global bounding box is infinite.
/// BEWARE: if called only once, the bounding box is just a point.
void setGlobalPoint(const G4double point[4]) {
if(minX == -DBL_MAX || minX > point[0]) minX = point[0];
if(minY == -DBL_MAX || minY > point[1]) minY = point[1];
if(minZ == -DBL_MAX || minZ > point[2]) minZ = point[2];
if(maxX == DBL_MAX || maxX < point[0]) maxX = point[0];
if(maxY == DBL_MAX || maxY < point[1]) maxY = point[1];
if(maxZ == DBL_MAX || maxZ < point[2]) maxZ = point[2];
}
/// isInBoundingBox() returns true if the point is within the
/// global bounding box - global coordinates.
bool isInBoundingBox(const G4double point[4]) const {
if(point[2] < minZ || point[2] > maxZ) return false;
if(point[0] < minX || point[0] > maxX) return false;
if(point[1] < minY || point[1] > maxY) return false;
return true;
}
/// addFieldValue() will add the field value for this element to field[].
/// Implementations must be sure to verify that point[] is within
/// the field region, and do nothing if not.
/// point[] is in global coordinates and geant4 units; x,y,z,t.
/// field[] is in geant4 units; Bx,By,Bz,Ex,Ey,Ez.
/// For efficiency, the caller may (but need not) call
/// isInBoundingBox(point), and only call this function if that
/// returns true.
virtual void
addFieldValue(const G4double point[4], G4double field[6]) const = 0;
// Get dimensions for the bounding box
virtual G4double getMaxLength() = 0;
virtual G4double getMaxWidth() = 0;
virtual G4double getMaxHeight() = 0;
protected:
G4LogicalVolume* lvolume;
G4AffineTransform global2local;
// MyElementField(const MyElementField&);
private:
static G4Navigator* aNavigator;
G4String color;
G4ThreeVector center;
G4double minX, minY, minZ, maxX, maxY,maxZ;
G4double maxStep;
G4UserLimits* userLimits;
G4double* boundingBox;
};
#endif
| [
"wuchen1106@gmail.com"
] | wuchen1106@gmail.com |
3c1050b76f083d1899237850e2dd087f790af519 | 23070dd1ba0a09173e490a75c21df9d6ef0acf12 | /1114/submissions/accepted/309552025_treap.cpp | 018c019c27c51c508efa02f688b0a4b911b46cf7 | [] | no_license | yuhu-k/NCTU-ItoA-2020-Fall | 06336561e7dc476f4a19f24bf70880d65ec90d64 | c7ded10d981b5bd6168ebd308384b25816aa1c28 | refs/heads/master | 2023-02-10T09:57:15.463571 | 2021-01-06T13:11:51 | 2021-01-10T08:06:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,138 | cpp | #include <bits/stdc++.h>
using namespace std;
default_random_engine generator;
uniform_int_distribution<int> distribution(0, INT_MAX);
class treap{
public:
treap():root(nullptr) {}
~treap(){delete(root);}
void insert(int value){
insert(root, value);
}
int find_the_k_th_num(int k){
return find_the_k_th_num(root, k);
}
int size() const{
return root?root->size:0;
}
private:
struct node{
int value;
int key; // random value for heap
int count;
int size;
node *left, *right;
node(int value):value(value), key(distribution(generator)), count(1), size(1), left(nullptr), right(nullptr) {}
~node(){
delete(left);
delete(right);
}
}*root;
void insert(node *&p, int value){
if(!p) p = new node(value);
else if(value == p->value){
p->count++;
p->size++;
}
else if(value < p->value){
insert(p->left, value);
update_size(p);
if(p->key > p->left->key) rotate_right(p);
}
else if(value > p->value){
insert(p->right, value);
update_size(p);
if(p->key > p->right->key) rotate_left(p);
}
}
void rotate_left(node *&p){
node *right = p->right;
p->right = right->left;
right->left = p;
update_size(p);
update_size(right);
p = right;
}
void rotate_right(node *&p){
node *left = p->left;
p->left = left->right;
left->right = p;
update_size(p);
update_size(left);
p = left;
}
void update_size(node *&p){
if(p) p->size = (p->left?p->left->size:0) + (p->right?p->right->size:0) + p->count;
}
int find_the_k_th_num(node *&p, int k){
int left_size = p->left?p->left->size : 0;
if(left_size >= k){
return find_the_k_th_num(p->left, k);
}
else if(left_size + p->count >= k){
return p->value;
}
else{
return find_the_k_th_num(p->right, k - left_size - p->count);
}
}
};
int main(){
int n, k;
treap tr;
scanf("%d %d", &n, &k);
while(n--){
int x;
scanf("%d", &x);
if(x) tr.insert(x);
else{
if(k != 0) printf("%d\n", tr.find_the_k_th_num((int)ceil(k / 100.0 * tr.size())));
else printf("%d\n", tr.find_the_k_th_num(1));
}
}
} | [
"edison1998402@gmail.com"
] | edison1998402@gmail.com |
b708b5c552a4f4852fc9ecabbd1d0c96ed9fd887 | e197af2f3f3a9ca90e1368a049f5dfccfd9e465c | /source/module-gl/src/render.cpp | 529dc75e8a0c0c20c53e2deeb164201a5cc071e1 | [] | no_license | jnterry/xeno-engine | 6f158f08e66e7dd1ef99349663dda2446ffc241a | 8feff9b007df9db33709928d7157b5ce9cc39138 | refs/heads/master | 2023-08-31T21:11:15.356079 | 2023-08-17T20:13:43 | 2023-08-17T20:13:43 | 134,952,501 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,015 | cpp | ////////////////////////////////////////////////////////////////////////////
/// Part of Xeno Engine ///
////////////////////////////////////////////////////////////////////////////
/// \brief Contains implementation of rendering to some target using opengl
///
/// \ingroup module-gl
////////////////////////////////////////////////////////////////////////////
#ifndef XEN_GL_RENDER_CPP
#define XEN_GL_RENDER_CPP
#include "Material.hxx"
#include "Mesh.hxx"
#include "gl_header.hxx"
#include "RenderTarget.hxx"
#include "ModuleGl.hxx"
#include <xen/graphics/GraphicsHandles.hpp>
#include <xen/graphics/RenderCommand3d.hpp>
#include <xen/core/array.hpp>
#include <xen/math/utilities.hpp>
void renderMesh(const xgl::MeshGlData* mesh){
if(mesh == nullptr){
XenLogWarn("Request to render null mesh, skipping");
return;
}
for(u64 i = 0; i < xen::size(mesh->vertex_spec); ++i){
if(mesh->vertex_data[i].buffer){
XEN_CHECK_GL(glBindBuffer(GL_ARRAY_BUFFER, mesh->vertex_data[i].buffer));
XEN_CHECK_GL(glEnableVertexAttribArray(i));
GLint component_count = (
mesh->vertex_spec[i].type & xen::VertexAttribute::Type::ComponentCountMask
);
GLenum component_type;
GLboolean normalized = GL_FALSE;
switch(mesh->vertex_spec[i].type & xen::VertexAttribute::Type::ComponentTypeMask){
case xen::VertexAttribute::Type::Float:
component_type = GL_FLOAT;
break;
case xen::VertexAttribute::Type::Double:
component_type = GL_DOUBLE;
break;
case xen::VertexAttribute::Type::Byte:
component_type = GL_UNSIGNED_BYTE;
normalized = GL_TRUE; // map [0-255] to [0-1]
break;
default:
XenInvalidCodePath("Unhandled vertex attribute type");
break;
}
XEN_CHECK_GL(glVertexAttribPointer(i,
component_count,
component_type,
normalized,
mesh->vertex_data[i].stride,
(void*)mesh->vertex_data[i].offset
)
);
} else {
XEN_CHECK_GL(glDisableVertexAttribArray(i));
switch(mesh->vertex_spec[i].type){
case (xen::VertexAttribute::Type::Float | 3):
XEN_CHECK_GL(glVertexAttrib3fv(i, &mesh->vertex_data[i].vec3f[0]));
break;
case (xen::VertexAttribute::Type::Double | 3):
XEN_CHECK_GL(glVertexAttrib3dv(i, &mesh->vertex_data[i].vec3d[0]));
break;
case (xen::VertexAttribute::Type::Float | 2):
XEN_CHECK_GL(glVertexAttrib2fv(i, &mesh->vertex_data[i].vec2f[0]));
break;
case (xen::VertexAttribute::Type::Double | 2):
XEN_CHECK_GL(glVertexAttrib2dv(i, &mesh->vertex_data[i].vec2d[0]));
break;
case (xen::VertexAttribute::Type::Byte | 4): {
// :TODO: if someone uses custom 4 byte attribute and doesn't want it to
// be mapped in this way, then what?
XenDebugAssert(mesh->vertex_spec[i].aspect == xen::VertexAttribute::Color,
"Expected 4 component byte vector only supports color aspect");
xen::Color color = mesh->vertex_data[i].color4b;
XEN_CHECK_GL(glVertexAttrib4f
(i,
xen::mapToRange<u32, float>(0, 255, 0.0f, 1.0f, color.r),
xen::mapToRange<u32, float>(0, 255, 0.0f, 1.0f, color.g),
xen::mapToRange<u32, float>(0, 255, 0.0f, 1.0f, color.b),
xen::mapToRange<u32, float>(0, 255, 0.0f, 1.0f, color.a)
));
break;
}
default:
XenInvalidCodePath("Unhandled vertex attribute type");
}
}
}
GLenum prim_type;
switch(mesh->primitive_type & xen::PrimitiveType::TypeMask){
case xen::PrimitiveType::Points : prim_type = GL_POINTS; break;
case xen::PrimitiveType::Lines : prim_type = GL_LINES; break;
case xen::PrimitiveType::LineStrip : prim_type = GL_LINE_STRIP; break;
case xen::PrimitiveType::Triangles : prim_type = GL_TRIANGLES; break;
case xen::PrimitiveType::Patch:
prim_type = GL_PATCHES;
glPatchParameteri(GL_PATCH_VERTICES,
mesh->primitive_type & xen::PrimitiveType::PatchCountMask);
break;
default:
XenBreak("Unknown primitive type requested");
break;
}
XEN_CHECK_GL(glDrawArrays(prim_type, 0, mesh->vertex_count));
}
namespace xgl {
void render(xen::RenderTarget render_target,
const xen::Aabb2u& viewport,
const xen::RenderParameters3d& params,
const xen::Array<xen::RenderCommand3d> commands
) {
xgl::RenderTargetImpl* target = getRenderTargetImpl(render_target);
xgl::makeCurrent(target);
Vec2u viewport_size = viewport.max - viewport.min;
glViewport(viewport.min.x, viewport.min.y, viewport_size.x, viewport_size.y);
xen::impl::checkGl(__LINE__, __FILE__);
for(u32 cmd_index = 0; cmd_index < commands.size; ++cmd_index){
const xen::RenderCommand3d* cmd = &commands[cmd_index];
if(cmd->material == nullptr){
xgl::applyMaterial(xgl::state->default_material, *cmd, params, viewport);
} else {
xgl::applyMaterial((xgl::Material*)cmd->material, *cmd, params, viewport);
}
switch(cmd->draw_mode){
case xen::RenderCommand3d::Filled:
XGL_CHECK(glPolygonMode(GL_FRONT_AND_BACK, GL_FILL));
break;
case xen::RenderCommand3d::Wireframe:
XGL_CHECK(glPolygonMode(GL_FRONT_AND_BACK, GL_LINE));
break;
case xen::RenderCommand3d::PointCloud:
XGL_CHECK(glPolygonMode(GL_FRONT_AND_BACK, GL_POINT));
break;
}
switch(cmd->cull_mode){
case xen::RenderCommand3d::CullBack:
XGL_CHECK(glEnable (GL_CULL_FACE ));
XGL_CHECK(glCullFace(GL_BACK ));
break;
case xen::RenderCommand3d::CullFront:
XGL_CHECK(glEnable (GL_CULL_FACE ));
XGL_CHECK(glCullFace(GL_FRONT ));
break;
case xen::RenderCommand3d::CullNone:
XGL_CHECK(glDisable (GL_CULL_FACE ));
break;
}
renderMesh((const xgl::MeshGlData*)cmd->mesh);
}
}
}
#endif
| [
"jnterry@ntlworld.com"
] | jnterry@ntlworld.com |
0f8a29e279faa7b923301634ef39c33af87e7eae | 9b12ed3e576c3d683ec2a024f324210878de3eb5 | /ch11/exercises/stonewt2.cpp | a0a1c9ff3c700116a7208465c472459bc787db29 | [] | no_license | escapetiger/cpp_primer_plus_notes | 6d251486178c112a6b57d9afe4fa460306b94637 | 391c43b2abb0287d134924d27d1313995e4a5dc6 | refs/heads/main | 2023-08-11T15:18:14.004593 | 2021-09-13T09:41:01 | 2021-09-13T09:41:01 | 405,669,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,392 | cpp | // stonewt2.cpp -- Stonewt methods
#include <iostream>
#include "stonewt2.h"
// default construtor, wt = 0
Stonewt::Stonewt()
{
stone = pounds = pds_left = 0;
mode = FPD;
}
// construct Stonewt object from double value
Stonewt::Stonewt(double lbs)
{
stone = int (lbs) / Lbs_per_stn; // integer division
pds_left = int (lbs) % Lbs_per_stn + lbs - int(lbs);
pounds = lbs;
mode = FPD;
}
// construct Stonewt object from stone, double values
Stonewt::Stonewt(int stn, double lbs)
{
stone = stn;
pds_left = lbs;
pounds = stn * Lbs_per_stn + lbs;
mode = FPD;
}
std::ostream & operator<<(std::ostream & os, const Stonewt & obj)
{
switch (obj.mode)
{
case Stonewt::STN:
os << obj.stone << " stone, " << obj.pds_left << " pounds\n";
break;
case Stonewt::IPD:
os << int (obj.pounds) << " pounds\n";
break;
case Stonewt::FPD:
os << obj.pounds << " pounds\n";
}
return os;
}
Stonewt Stonewt::operator*(double n)
{
return Stonewt(pounds * n);
}
Stonewt Stonewt::operator+(Stonewt & st)
{
return Stonewt(pounds + st.pounds);
}
Stonewt Stonewt::operator-(Stonewt & st)
{
return Stonewt(pounds - st.pounds);
}
Stonewt::~Stonewt()
{
}
// conversion functions
Stonewt::operator int() const
{
return (pounds + 0.5);
}
Stonewt::operator double() const
{
return pounds;
}
| [
"cy992236@outlook.com"
] | cy992236@outlook.com |
2900686dc1b27c51841cadaaf60b0794cbf44008 | d1324544b5eec61819071d2847d7940a3c7b56df | /SourceCode/SSRS/LBBML/LBBML/LBBMLGraphics/Stats/StatsSet.cpp | ccc7559338ce3e4ce3f8d54b462eab07114c4a4a | [] | no_license | FrankBATMAN/Soft-Shadows-Rendering-with-Split-screen | 1bc88351ee8761c1a69151283c1090bedff253fa | 9203f2412054d3e75fd70063ede6c4f58fd6934c | refs/heads/master | 2021-01-20T00:34:04.552376 | 2017-03-05T02:38:56 | 2017-03-05T02:38:56 | 83,797,802 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,064 | cpp | #include "StatsSet.h"
#include <iostream>
#include "../../LBBML/Common/LBBMLInterface.h"
CLBBMLGraphicsStats::CLBBMLGraphicsStats()
{
}
CLBBMLGraphicsStats::~CLBBMLGraphicsStats()
{
__writeStats2File();
m_Stats.clear();
}
//*********************************************************************************
//FUNCTION:
void CLBBMLGraphicsStats::addStat(const std::vector<boost::any>& vStat)
{
_ASSERT(vStat.size() > 0, "Stat can not be Empty!");
if (m_Stats.size() == 0)
m_Stats.push_back(vStat);
else if (m_Stats.size() > 0 && vStat.size() == m_Stats[0].size())
m_Stats.push_back(vStat);
else
{
std::cout << "Warning : Size does not match !" << std::endl;
m_Stats.push_back(vStat);
}
}
//*********************************************************************************
//FUNCTION:
void CLBBMLGraphicsStats::__writeStats2File()
{
if (m_StatsFilename.empty()) m_StatsFilename = std::string("StatsData.csv");
if (m_Stats.size() > 0)
{
for (unsigned int i = 0; i < m_Stats.size(); ++i)
LBBML::writeData(m_StatsFilename, m_Stats[i]);
}
} | [
"FrankBATMAN@126.com"
] | FrankBATMAN@126.com |
170c298d2932717fa0927e2b372e202818f1acca | 3fbe1e13c6171a82416b29a82645832b4228c0e7 | /Source/UnderTheCouch/UnderTheCouchGameModeBase.cpp | b1f91671d73992deb18b41f5ecea22ce1691433c | [
"MIT"
] | permissive | codarth/UnderTheCouch | 4280727cd444157861c8b833ae5a5e5ac4f06fc4 | 896aea463cdfa98c846de999c66635ee79900abd | refs/heads/master | 2020-09-06T09:01:08.724348 | 2019-11-22T02:31:03 | 2019-11-22T02:31:03 | 220,380,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "UnderTheCouchGameModeBase.h"
| [
"zimquo@gmail.com"
] | zimquo@gmail.com |
fcb4a85b1e16faddc924709be84364a97dd6b33b | 1d18f9c940462031f12ffe8445f05f51157c9ac1 | /src/util/sound.hpp | 44716c0eeb4440edbefcb17b610fa0bbe6553d66 | [
"MIT"
] | permissive | taylordowns2000/BarbersAndRebarbs | c0f3384b2300f987904fee6bc81c3b51cee346d3 | c75ca19f29b3d2742a1000d9c8d388cb00c418d6 | refs/heads/master | 2023-03-16T08:27:20.376840 | 2017-06-28T05:32:28 | 2017-07-05T02:03:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | hpp | // The MIT License (MIT)
// Copyright (c) 2017 nabijaczleweli
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#pragma once
/// Get output volume [0, 1] scaled exponentially from knob volume [0, 1]
float output_volume(float in);
| [
"nabijaczleweli@gmail.com"
] | nabijaczleweli@gmail.com |
0659cec5b19091913dc89d975659463112849b9c | 39836b7fe5cfc1fc0d4f4411f8781f48a4f301d7 | /old_versions/v1/src/wink/wink-rand32.hpp | 5ea823cb8c3561a9b611c8fdd8792a85dd7ca16a | [] | no_license | BarbaraPriwitzerGitHubRT/neuro-stat | d6e0f8c353e3fb32793bb7d657b615555ee6b9ea | 1596f533bacbfee256f5f7fecc5480d4e1a11bf4 | refs/heads/master | 2023-03-15T00:27:00.216041 | 2016-09-02T13:01:00 | 2016-09-02T13:01:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,230 | hpp | /**
\file
\brief fast RNG
Random number generators for fast permutations,
possibly in parallel
*/
#ifndef WINK_RAND32_INCLUDED
#define WINK_RAND32_INCLUDED 1
#include "wink-os.hpp"
#include <cassert>
#include <cstdlib>
namespace wink
{
//! Marsaglia's 32 bits random number generators
class rand32
{
public:
uint32_t z,w,jsr,jcong,a,b;
uint32_t x,y,bro;
uint8_t c;
uint32_t t[256];
explicit rand32() throw();
virtual ~rand32() throw();
typedef uint32_t (rand32::*generator)();
uint32_t mwc() throw();
uint32_t shr3() throw();
uint32_t cong() throw();
uint32_t fib() throw();
uint32_t kiss() throw();
uint32_t lfib4() throw();
uint32_t swb() throw();
void settable( uint32_t i1, uint32_t i2, uint32_t i3, uint32_t i4, uint32_t i5, uint32_t i6 ) throw();
void reset( uint32_t s ) throw();
//! make a random 0 or 1
template <typename T>
static inline T to_bit( uint32_t u ) throw()
{
static const uint32_t threshold = uint32_t(1) << 31;
static const T __zero(0);
static const T __one(1);
return u >= threshold ? __one : __zero;
}
//! convert to 0:1 exclusive
static inline double to_double( uint32_t u ) throw()
{
return (0.5+double(u))/4294967296.0;
}
//! convert to 0:1 exclusive
static inline float to_float( uint32_t u ) throw()
{
return (0.5f+float(u))/4294967296.0f;
}
//! integer hash, 32 bits
static uint32_t ih32( uint32_t ) throw();
//! should print 7 '0'
void test() throw();
private:
rand32( const rand32 & );
rand32&operator=(const rand32 &);
};
//! integer to type mapping.
template <int v>
struct int2type {
enum
{
value = v //!< a different class for each v.
};
};
//! interface to a 32 bits uniform generator
class urand32
{
public:
virtual ~urand32() throw();
virtual uint32_t next() throw() = 0;
virtual void seed(uint32_t) throw() = 0;
template <typename T> T get() throw(); //!< valid for uin32_t, float, double
inline double alea() throw()
{
return rand32::to_double(next());
}
template <typename T>
inline T full() throw()
{
return __full<T>( int2type<(sizeof(T)>sizeof(uint32_t))>() );
}
//! return random index in 0..n
inline size_t less_than( size_t n ) throw()
{
return full<size_t>() % (++n);
}
//! card desk shuffling algorithm
template <typename T>
inline void shuffle( T *a, size_t n ) throw()
{
assert(!(NULL==a&&n>0));
if( n > 1 )
{
for( size_t i=n-1;i>0;--i)
{
const size_t j = less_than(i); assert(j<=i);
const T tmp(a[i]);
a[i] = a[j];
a[j] = tmp;
}
}
}
void fill_array( double a, double b, double *x, size_t n ) throw();
protected:
explicit urand32() throw();
private:
urand32(const urand32 &);
urand32&operator=(const urand32 &);
template <typename T>
inline T __full( int2type<false> ) throw()
{
assert(sizeof(T)<=sizeof(uint32_t));
return T(next());
}
template <typename T>
inline T __full( int2type<true> ) throw()
{
assert(sizeof(T)>sizeof(uint32_t));
T ans(0);
for( size_t i=sizeof(T)/sizeof(uint32_t);i>0;--i)
{
ans <<= 32;
ans |= T(next());
}
return ans;
}
};
//! generic random number generator
template <rand32::generator G>
class grand32 : public urand32
{
public:
explicit grand32() throw() : urand32(), r() {}
virtual ~grand32() throw() {}
virtual uint32_t next() throw() { return (r.*G)(); }
virtual void seed(uint32_t s) throw() { r.reset(s); }
private:
rand32 r;
grand32(const grand32 & );
grand32&operator=(const grand32 &);
};
//==========================================================================
// available random number generators
//==========================================================================
typedef grand32<&rand32::mwc> rand32_mwc;
typedef grand32<&rand32::shr3> rand32_shr3;
typedef grand32<&rand32::cong> rand32_cong;
typedef grand32<&rand32::fib> rand32_fib;
typedef grand32<&rand32::kiss> rand32_kiss;
typedef grand32<&rand32::lfib4> rand32_lfib4;
typedef grand32<&rand32::swb> rand32_swb;
}
#endif
| [
"yann.bouret@gmail.com@d870e702-db5d-e285-c176-38c699937b0f"
] | yann.bouret@gmail.com@d870e702-db5d-e285-c176-38c699937b0f |
26ef7e29969830fafd33be07cdb851d661032648 | 93d6111bde3911310e6e5d21d1b6872bb3b38a13 | /cocos2d/cocos/2d/CCLayer.cpp | 7795565b24511396dc38da97e2895914ceba7bea | [
"MIT"
] | permissive | ConorHaining/ToTheTrains | 35ce722fd409ce64950d84ca14a303f16d2e7a6a | 6ff294afd1a643e35964601a2cdbb77f4cdd8a4a | refs/heads/master | 2021-01-24T01:00:13.829788 | 2018-05-07T14:19:23 | 2018-05-07T14:19:23 | 122,786,775 | 1 | 0 | MIT | 2018-03-30T12:26:14 | 2018-02-24T22:47:31 | C++ | UTF-8 | C++ | false | false | 33,618 | cpp | /****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include <stdarg.h>
#include "2d/CCLayer.h"
#include "base/CCScriptSupport.h"
#include "platform/CCDevice.h"
#include "renderer/CCRenderer.h"
#include "renderer/ccGLStateCache.h"
#include "renderer/CCGLProgramState.h"
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
#include "base/CCEventListenerTouch.h"
#include "base/CCEventTouch.h"
#include "base/CCEventKeyboard.h"
#include "base/CCEventListenerKeyboard.h"
#include "base/CCEventAcceleration.h"
#include "base/CCEventListenerAcceleration.h"
#include "base/ccUTF8.h"
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC)
#include "platform/desktop/CCGLViewImpl-desktop.h"
#endif
NS_CC_BEGIN
// Layer
Layer::Layer()
: _touchEnabled(false)
, _accelerometerEnabled(false)
, _keyboardEnabled(false)
, _touchListener(nullptr)
, _keyboardListener(nullptr)
, _accelerationListener(nullptr)
, _touchMode(Touch::DispatchMode::ALL_AT_ONCE)
, _swallowsTouches(true)
{
_ignoreAnchorPointForPosition = true;
setAnchorPoint(Vec2(0.5f, 0.5f));
}
Layer::~Layer()
{
}
bool Layer::init()
{
Director * director = Director::getInstance();
setContentSize(director->getWinSize());
return true;
}
Layer *Layer::create()
{
Layer *ret = new (std::nothrow) Layer();
if (ret && ret->init())
{
ret->autorelease();
return ret;
}
else
{
CC_SAFE_DELETE(ret);
return nullptr;
}
}
int Layer::executeScriptTouchHandler(EventTouch::EventCode eventType, Touch* touch, Event* event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
TouchScriptData data(eventType, this, touch, event);
ScriptEvent scriptEvent(kTouchEvent, &data);
return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
}
#else
CC_UNUSED_PARAM(eventType);
CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event);
#endif
return 0;
}
int Layer::executeScriptTouchesHandler(EventTouch::EventCode eventType, const std::vector<Touch*>& touches, Event* event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
TouchesScriptData data(eventType, this, touches, event);
ScriptEvent scriptEvent(kTouchesEvent, &data);
return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
}
#else
CC_UNUSED_PARAM(eventType);
CC_UNUSED_PARAM(touches);
CC_UNUSED_PARAM(event);
#endif
return 0;
}
bool Layer::ccTouchBegan(Touch* /*pTouch*/, Event* /*pEvent*/) {return false;};
void Layer::ccTouchMoved(Touch* /*pTouch*/, Event* /*pEvent*/) {}
void Layer::ccTouchEnded(Touch* /*pTouch*/, Event* /*pEvent*/) {}
void Layer::ccTouchCancelled(Touch* /*pTouch*/, Event* /*pEvent*/) {}
void Layer::ccTouchesBegan(__Set* /*pTouches*/, Event* /*pEvent*/) {}
void Layer::ccTouchesMoved(__Set* /*pTouches*/, Event* /*pEvent*/) {}
void Layer::ccTouchesEnded(__Set* /*pTouches*/, Event* /*pEvent*/) {}
void Layer::ccTouchesCancelled(__Set* /*pTouches*/, Event* /*pEvent*/) {}
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (push)
#pragma warning (disable: 4996)
#endif
/// isTouchEnabled getter
bool Layer::isTouchEnabled() const
{
return _touchEnabled;
}
/// isTouchEnabled setter
void Layer::setTouchEnabled(bool enabled)
{
if (_touchEnabled != enabled)
{
_touchEnabled = enabled;
if (enabled)
{
if (_touchListener != nullptr)
return;
if( _touchMode == Touch::DispatchMode::ALL_AT_ONCE )
{
// Register Touch Event
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(Layer::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(Layer::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(Layer::onTouchesEnded, this);
listener->onTouchesCancelled = CC_CALLBACK_2(Layer::onTouchesCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
_touchListener = listener;
}
else
{
// Register Touch Event
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(_swallowsTouches);
listener->onTouchBegan = CC_CALLBACK_2(Layer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(Layer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(Layer::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(Layer::onTouchCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
_touchListener = listener;
}
}
else
{
_eventDispatcher->removeEventListener(_touchListener);
_touchListener = nullptr;
}
}
}
void Layer::setTouchMode(Touch::DispatchMode mode)
{
if(_touchMode != mode)
{
_touchMode = mode;
if( _touchEnabled)
{
setTouchEnabled(false);
setTouchEnabled(true);
}
}
}
void Layer::setSwallowsTouches(bool swallowsTouches)
{
if (_swallowsTouches != swallowsTouches)
{
_swallowsTouches = swallowsTouches;
if( _touchEnabled)
{
setTouchEnabled(false);
setTouchEnabled(true);
}
}
}
Touch::DispatchMode Layer::getTouchMode() const
{
return _touchMode;
}
bool Layer::isSwallowsTouches() const
{
return _swallowsTouches;
}
/// isAccelerometerEnabled getter
bool Layer::isAccelerometerEnabled() const
{
return _accelerometerEnabled;
}
/// isAccelerometerEnabled setter
void Layer::setAccelerometerEnabled(bool enabled)
{
if (enabled != _accelerometerEnabled)
{
_accelerometerEnabled = enabled;
Device::setAccelerometerEnabled(enabled);
_eventDispatcher->removeEventListener(_accelerationListener);
_accelerationListener = nullptr;
if (enabled)
{
_accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(Layer::onAcceleration, this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(_accelerationListener, this);
}
}
}
void Layer::setAccelerometerInterval(double interval) {
if (_accelerometerEnabled)
{
if (_running)
{
Device::setAccelerometerInterval(interval);
}
}
}
void Layer::onAcceleration(Acceleration* acc, Event* /*unused_event*/)
{
#if CC_ENABLE_SCRIPT_BINDING
if(kScriptTypeNone != _scriptType)
{
BasicScriptData data(this,(void*)acc);
ScriptEvent event(kAccelerometerEvent,&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#else
CC_UNUSED_PARAM(acc);
#endif
}
void Layer::onKeyPressed(EventKeyboard::KeyCode /*keyCode*/, Event* /*unused_event*/)
{
}
void Layer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* /*unused_event*/)
{
#if CC_ENABLE_SCRIPT_BINDING
if(kScriptTypeNone != _scriptType)
{
KeypadScriptData data(keyCode, this);
ScriptEvent event(kKeypadEvent,&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
#else
CC_UNUSED_PARAM(keyCode);
#endif
}
/// isKeyboardEnabled getter
bool Layer::isKeyboardEnabled() const
{
return _keyboardEnabled;
}
/// isKeyboardEnabled setter
void Layer::setKeyboardEnabled(bool enabled)
{
if (enabled != _keyboardEnabled)
{
_keyboardEnabled = enabled;
_eventDispatcher->removeEventListener(_keyboardListener);
_keyboardListener = nullptr;
if (enabled)
{
auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(Layer::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(Layer::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
_keyboardListener = listener;
}
}
}
void Layer::setKeypadEnabled(bool enabled)
{
setKeyboardEnabled(enabled);
}
/// Callbacks
bool Layer::onTouchBegan(Touch *touch, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
return executeScriptTouchHandler(EventTouch::EventCode::BEGAN, touch, event) == 0 ? false : true;
}
#else
CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event);
#endif
CCASSERT(false, "Layer#ccTouchBegan override me");
return true;
}
void Layer::onTouchMoved(Touch *touch, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
executeScriptTouchHandler(EventTouch::EventCode::MOVED, touch, event);
return;
}
#else
CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event);
#endif
}
void Layer::onTouchEnded(Touch *touch, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
executeScriptTouchHandler(EventTouch::EventCode::ENDED, touch, event);
return;
}
#else
CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event);
#endif
}
void Layer::onTouchCancelled(Touch *touch, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
executeScriptTouchHandler(EventTouch::EventCode::CANCELLED, touch, event);
return;
}
#else
CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event);
#endif
}
void Layer::onTouchesBegan(const std::vector<Touch*>& touches, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::BEGAN, touches, event);
return;
}
#else
CC_UNUSED_PARAM(touches);
CC_UNUSED_PARAM(event);
#endif
}
void Layer::onTouchesMoved(const std::vector<Touch*>& touches, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::MOVED, touches, event);
return;
}
#else
CC_UNUSED_PARAM(touches);
CC_UNUSED_PARAM(event);
#endif
}
void Layer::onTouchesEnded(const std::vector<Touch*>& touches, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::ENDED, touches, event);
return;
}
#else
CC_UNUSED_PARAM(touches);
CC_UNUSED_PARAM(event);
#endif
}
void Layer::onTouchesCancelled(const std::vector<Touch*>& touches, Event *event)
{
#if CC_ENABLE_SCRIPT_BINDING
if (kScriptTypeLua == _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::CANCELLED, touches, event);
return;
}
#else
CC_UNUSED_PARAM(touches);
CC_UNUSED_PARAM(event);
#endif
}
std::string Layer::getDescription() const
{
return StringUtils::format("<Layer | Tag = %d>", _tag);
}
__LayerRGBA::__LayerRGBA()
{
CCLOG("LayerRGBA deprecated.");
}
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (pop)
#endif
/// LayerColor
LayerColor::LayerColor()
{
// default blend function
_blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
}
LayerColor::~LayerColor()
{
}
/// blendFunc getter
const BlendFunc &LayerColor::getBlendFunc() const
{
return _blendFunc;
}
/// blendFunc setter
void LayerColor::setBlendFunc(const BlendFunc &var)
{
_blendFunc = var;
}
LayerColor* LayerColor::create()
{
LayerColor* ret = new (std::nothrow) LayerColor();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
LayerColor * LayerColor::create(const Color4B& color, GLfloat width, GLfloat height)
{
LayerColor * layer = new (std::nothrow) LayerColor();
if( layer && layer->initWithColor(color,width,height))
{
layer->autorelease();
return layer;
}
CC_SAFE_DELETE(layer);
return nullptr;
}
LayerColor * LayerColor::create(const Color4B& color)
{
LayerColor * layer = new (std::nothrow) LayerColor();
if(layer && layer->initWithColor(color))
{
layer->autorelease();
return layer;
}
CC_SAFE_DELETE(layer);
return nullptr;
}
bool LayerColor::init()
{
Size s = Director::getInstance()->getWinSize();
return initWithColor(Color4B(0,0,0,0), s.width, s.height);
}
bool LayerColor::initWithColor(const Color4B& color, GLfloat w, GLfloat h)
{
if (Layer::init())
{
// default blend function
_blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_displayedColor.r = _realColor.r = color.r;
_displayedColor.g = _realColor.g = color.g;
_displayedColor.b = _realColor.b = color.b;
_displayedOpacity = _realOpacity = color.a;
for (size_t i = 0; i<sizeof(_squareVertices) / sizeof( _squareVertices[0]); i++ )
{
_squareVertices[i].x = 0.0f;
_squareVertices[i].y = 0.0f;
}
updateColor();
setContentSize(Size(w, h));
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_NAME_POSITION_COLOR_NO_MVP));
return true;
}
return false;
}
bool LayerColor::initWithColor(const Color4B& color)
{
Size s = Director::getInstance()->getWinSize();
return initWithColor(color, s.width, s.height);
}
/// override contentSize
void LayerColor::setContentSize(const Size & size)
{
_squareVertices[1].x = size.width;
_squareVertices[2].y = size.height;
_squareVertices[3].x = size.width;
_squareVertices[3].y = size.height;
Layer::setContentSize(size);
}
void LayerColor::changeWidthAndHeight(GLfloat w ,GLfloat h)
{
this->setContentSize(Size(w, h));
}
void LayerColor::changeWidth(GLfloat w)
{
this->setContentSize(Size(w, _contentSize.height));
}
void LayerColor::changeHeight(GLfloat h)
{
this->setContentSize(Size(_contentSize.width, h));
}
void LayerColor::updateColor()
{
for( unsigned int i=0; i < 4; i++ )
{
_squareColors[i].r = _displayedColor.r / 255.0f;
_squareColors[i].g = _displayedColor.g / 255.0f;
_squareColors[i].b = _displayedColor.b / 255.0f;
_squareColors[i].a = _displayedOpacity / 255.0f;
}
}
void LayerColor::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
_customCommand.init(_globalZOrder, transform, flags);
_customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this, transform, flags);
renderer->addCommand(&_customCommand);
for(int i = 0; i < 4; ++i)
{
Vec4 pos;
pos.x = _squareVertices[i].x; pos.y = _squareVertices[i].y; pos.z = _positionZ;
pos.w = 1;
_modelViewTransform.transformVector(&pos);
_noMVPVertices[i] = Vec3(pos.x,pos.y,pos.z)/pos.w;
}
}
void LayerColor::onDraw(const Mat4& transform, uint32_t /*flags*/)
{
getGLProgram()->use();
getGLProgram()->setUniformsForBuiltins(transform);
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_COLOR );
//
// Attributes
//
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, _noMVPVertices);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_FLOAT, GL_FALSE, 0, _squareColors);
GL::blendFunc( _blendFunc.src, _blendFunc.dst );
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,4);
}
std::string LayerColor::getDescription() const
{
return StringUtils::format("<LayerColor | Tag = %d>", _tag);
}
//
// LayerGradient
//
LayerGradient::LayerGradient()
: _startColor(Color4B::BLACK)
, _endColor(Color4B::BLACK)
, _startOpacity(255)
, _endOpacity(255)
, _alongVector(Vec2(0, -1))
, _compressedInterpolation(true)
{
}
LayerGradient::~LayerGradient()
{
}
LayerGradient* LayerGradient::create(const Color4B& start, const Color4B& end)
{
LayerGradient * layer = new (std::nothrow) LayerGradient();
if( layer && layer->initWithColor(start, end))
{
layer->autorelease();
return layer;
}
CC_SAFE_DELETE(layer);
return nullptr;
}
LayerGradient* LayerGradient::create(const Color4B& start, const Color4B& end, const Vec2& v)
{
LayerGradient * layer = new (std::nothrow) LayerGradient();
if( layer && layer->initWithColor(start, end, v))
{
layer->autorelease();
return layer;
}
CC_SAFE_DELETE(layer);
return nullptr;
}
LayerGradient* LayerGradient::create()
{
LayerGradient* ret = new (std::nothrow) LayerGradient();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
bool LayerGradient::init()
{
return initWithColor(Color4B(0, 0, 0, 255), Color4B(0, 0, 0, 255));
}
bool LayerGradient::initWithColor(const Color4B& start, const Color4B& end)
{
return initWithColor(start, end, Vec2(0, -1));
}
bool LayerGradient::initWithColor(const Color4B& start, const Color4B& end, const Vec2& v)
{
_endColor.r = end.r;
_endColor.g = end.g;
_endColor.b = end.b;
_endOpacity = end.a;
_startOpacity = start.a;
_alongVector = v;
_compressedInterpolation = true;
return LayerColor::initWithColor(Color4B(start.r, start.g, start.b, 255));
}
void LayerGradient::updateColor()
{
LayerColor::updateColor();
float h = _alongVector.getLength();
if (h == 0)
return;
float c = sqrtf(2.0f);
Vec2 u(_alongVector.x / h, _alongVector.y / h);
// Compressed Interpolation mode
if (_compressedInterpolation)
{
float h2 = 1 / ( fabsf(u.x) + fabsf(u.y) );
u = u * (h2 * (float)c);
}
float opacityf = (float)_displayedOpacity / 255.0f;
Color4F S(
_displayedColor.r / 255.0f,
_displayedColor.g / 255.0f,
_displayedColor.b / 255.0f,
_startOpacity * opacityf / 255.0f
);
Color4F E(
_endColor.r / 255.0f,
_endColor.g / 255.0f,
_endColor.b / 255.0f,
_endOpacity * opacityf / 255.0f
);
// (-1, -1)
_squareColors[0].r = E.r + (S.r - E.r) * ((c + u.x + u.y) / (2.0f * c));
_squareColors[0].g = E.g + (S.g - E.g) * ((c + u.x + u.y) / (2.0f * c));
_squareColors[0].b = E.b + (S.b - E.b) * ((c + u.x + u.y) / (2.0f * c));
_squareColors[0].a = E.a + (S.a - E.a) * ((c + u.x + u.y) / (2.0f * c));
// (1, -1)
_squareColors[1].r = E.r + (S.r - E.r) * ((c - u.x + u.y) / (2.0f * c));
_squareColors[1].g = E.g + (S.g - E.g) * ((c - u.x + u.y) / (2.0f * c));
_squareColors[1].b = E.b + (S.b - E.b) * ((c - u.x + u.y) / (2.0f * c));
_squareColors[1].a = E.a + (S.a - E.a) * ((c - u.x + u.y) / (2.0f * c));
// (-1, 1)
_squareColors[2].r = E.r + (S.r - E.r) * ((c + u.x - u.y) / (2.0f * c));
_squareColors[2].g = E.g + (S.g - E.g) * ((c + u.x - u.y) / (2.0f * c));
_squareColors[2].b = E.b + (S.b - E.b) * ((c + u.x - u.y) / (2.0f * c));
_squareColors[2].a = E.a + (S.a - E.a) * ((c + u.x - u.y) / (2.0f * c));
// (1, 1)
_squareColors[3].r = E.r + (S.r - E.r) * ((c - u.x - u.y) / (2.0f * c));
_squareColors[3].g = E.g + (S.g - E.g) * ((c - u.x - u.y) / (2.0f * c));
_squareColors[3].b = E.b + (S.b - E.b) * ((c - u.x - u.y) / (2.0f * c));
_squareColors[3].a = E.a + (S.a - E.a) * ((c - u.x - u.y) / (2.0f * c));
}
const Color3B& LayerGradient::getStartColor() const
{
return _realColor;
}
void LayerGradient::setStartColor(const Color3B& color)
{
setColor(color);
}
void LayerGradient::setEndColor(const Color3B& color)
{
_endColor = color;
updateColor();
}
const Color3B& LayerGradient::getEndColor() const
{
return _endColor;
}
void LayerGradient::setStartOpacity(GLubyte o)
{
_startOpacity = o;
updateColor();
}
GLubyte LayerGradient::getStartOpacity() const
{
return _startOpacity;
}
void LayerGradient::setEndOpacity(GLubyte o)
{
_endOpacity = o;
updateColor();
}
GLubyte LayerGradient::getEndOpacity() const
{
return _endOpacity;
}
void LayerGradient::setVector(const Vec2& var)
{
_alongVector = var;
updateColor();
}
const Vec2& LayerGradient::getVector() const
{
return _alongVector;
}
bool LayerGradient::isCompressedInterpolation() const
{
return _compressedInterpolation;
}
void LayerGradient::setCompressedInterpolation(bool compress)
{
_compressedInterpolation = compress;
updateColor();
}
std::string LayerGradient::getDescription() const
{
return StringUtils::format("<LayerGradient | Tag = %d>", _tag);
}
/**
* LayerRadialGradient
*/
LayerRadialGradient* LayerRadialGradient::create(const Color4B& startColor, const Color4B& endColor, float radius, const Vec2& center, float expand)
{
auto layerGradient = new LayerRadialGradient();
if (layerGradient && layerGradient->initWithColor(startColor, endColor, radius, center, expand))
{
layerGradient->autorelease();
return layerGradient;
}
delete layerGradient;
return nullptr;
}
LayerRadialGradient* LayerRadialGradient::create()
{
auto layerGradient = new LayerRadialGradient();
if (layerGradient && layerGradient->initWithColor(Color4B::BLACK, Color4B::BLACK, 0, Vec2(0,0), 0))
{
layerGradient->autorelease();
return layerGradient;
}
delete layerGradient;
return nullptr;
}
LayerRadialGradient::LayerRadialGradient()
: _startColor(Color4B::BLACK)
, _startColorRend(Color4F::BLACK)
, _endColor(Color4B::BLACK)
, _endColorRend(Color4F::BLACK)
, _radius(0.f)
, _expand(0.f)
, _center(Vec2(0,0))
, _uniformLocationCenter(0)
, _uniformLocationRadius(0)
, _uniformLocationExpand(0)
, _uniformLocationEndColor(0)
, _uniformLocationStartColor(0)
, _blendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED)
{ }
LayerRadialGradient::~LayerRadialGradient()
{}
bool LayerRadialGradient::initWithColor(const cocos2d::Color4B &startColor, const cocos2d::Color4B &endColor, float radius, const Vec2& center, float expand)
{
// should do it before Layer::init()
for (int i = 0; i < 4; ++i)
_vertices[i] = {0.0f, 0.0f};
if (Layer::init())
{
convertColor4B24F(_startColorRend, startColor);
_startColor = startColor;
convertColor4B24F(_endColorRend, endColor);
_endColor = endColor;
_expand = expand;
setRadius(radius);
setCenter(center);
setGLProgramState(GLProgramState::getOrCreateWithGLProgramName(GLProgram::SHADER_LAYER_RADIAL_GRADIENT));
auto program = getGLProgram();
_uniformLocationStartColor = program->getUniformLocation("u_startColor");
_uniformLocationEndColor = program->getUniformLocation("u_endColor");
_uniformLocationExpand = program->getUniformLocation("u_expand");
_uniformLocationRadius = program->getUniformLocation("u_radius");
_uniformLocationCenter = program->getUniformLocation("u_center");
return true;
}
return false;
}
void LayerRadialGradient::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
{
_customCommand.init(_globalZOrder, transform, flags);
_customCommand.func = CC_CALLBACK_0(LayerRadialGradient::onDraw, this, transform, flags);
renderer->addCommand(&_customCommand);
}
void LayerRadialGradient::onDraw(const Mat4& transform, uint32_t /*flags*/)
{
auto program = getGLProgram();
program->use();
program->setUniformsForBuiltins(transform);
program->setUniformLocationWith4f(_uniformLocationStartColor, _startColorRend.r,
_startColorRend.g, _startColorRend.b, _startColorRend.a);
program->setUniformLocationWith4f(_uniformLocationEndColor, _endColorRend.r,
_endColorRend.g, _endColorRend.b, _endColorRend.a);
program->setUniformLocationWith2f(_uniformLocationCenter, _center.x, _center.y);
program->setUniformLocationWith1f(_uniformLocationRadius, _radius);
program->setUniformLocationWith1f(_uniformLocationExpand, _expand);
GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION);
//
// Attributes
//
glBindBuffer(GL_ARRAY_BUFFER, 0);
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, _vertices);
GL::blendFunc(_blendFunc.src, _blendFunc.dst);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1,4);
}
void LayerRadialGradient::setContentSize(const Size& size)
{
_vertices[1].x = size.width;
_vertices[2].y = size.height;
_vertices[3].x = size.width;
_vertices[3].y = size.height;
Layer::setContentSize(size);
}
void LayerRadialGradient::setStartOpacity(GLubyte opacity)
{
_startColorRend.a = opacity / 255.0f;
_startColor.a = opacity;
}
GLubyte LayerRadialGradient::getStartOpacity() const
{
return _startColor.a;
}
void LayerRadialGradient::setEndOpacity(GLubyte opacity)
{
_endColorRend.a = opacity / 255.0f;
_endColor.a = opacity;
}
GLubyte LayerRadialGradient::getEndOpacity() const
{
return _endColor.a;
}
void LayerRadialGradient::setRadius(float radius)
{
_radius = radius;
}
float LayerRadialGradient::getRadius() const
{
return _radius;
}
void LayerRadialGradient::setCenter(const Vec2& center)
{
_center = center;
}
Vec2 LayerRadialGradient::getCenter() const
{
return _center;
}
void LayerRadialGradient::setExpand(float expand)
{
_expand = expand;
}
float LayerRadialGradient::getExpand() const
{
return _expand;
}
void LayerRadialGradient::setStartColor(const Color3B& color)
{
setStartColor(Color4B(color));
}
void LayerRadialGradient::setStartColor(const cocos2d::Color4B &color)
{
_startColor = color;
convertColor4B24F(_startColorRend, _startColor);
}
Color4B LayerRadialGradient::getStartColor() const
{
return _startColor;
}
Color3B LayerRadialGradient::getStartColor3B() const
{
return Color3B(_startColor);
}
void LayerRadialGradient::setEndColor(const Color3B& color)
{
setEndColor(Color4B(color));
}
void LayerRadialGradient::setEndColor(const cocos2d::Color4B &color)
{
_endColor = color;
convertColor4B24F(_endColorRend, _endColor);
}
Color4B LayerRadialGradient::getEndColor() const
{
return _endColor;
}
Color3B LayerRadialGradient::getEndColor3B() const
{
return Color3B(_endColor);
}
void LayerRadialGradient::setBlendFunc(const BlendFunc& blendFunc)
{
_blendFunc = blendFunc;
}
BlendFunc LayerRadialGradient::getBlendFunc() const
{
return _blendFunc;
}
void LayerRadialGradient::convertColor4B24F(Color4F& outColor, const Color4B& inColor)
{
outColor.r = inColor.r / 255.0f;
outColor.g = inColor.g / 255.0f;
outColor.b = inColor.b / 255.0f;
outColor.a = inColor.a / 255.0f;
}
/// MultiplexLayer
LayerMultiplex::LayerMultiplex()
: _enabledLayer(0)
{
}
LayerMultiplex::~LayerMultiplex()
{
for(const auto &layer : _layers) {
layer->cleanup();
}
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
LayerMultiplex * LayerMultiplex::createVariadic(Layer * layer, ...)
{
va_list args;
va_start(args,layer);
LayerMultiplex * multiplexLayer = new (std::nothrow) LayerMultiplex();
if(multiplexLayer && multiplexLayer->initWithLayers(layer, args))
{
multiplexLayer->autorelease();
va_end(args);
return multiplexLayer;
}
va_end(args);
CC_SAFE_DELETE(multiplexLayer);
return nullptr;
}
#else
LayerMultiplex * LayerMultiplex::create(Layer * layer, ...)
{
va_list args;
va_start(args,layer);
LayerMultiplex * multiplexLayer = new (std::nothrow) LayerMultiplex();
if(multiplexLayer && multiplexLayer->initWithLayers(layer, args))
{
multiplexLayer->autorelease();
va_end(args);
return multiplexLayer;
}
va_end(args);
CC_SAFE_DELETE(multiplexLayer);
return nullptr;
}
#endif
LayerMultiplex * LayerMultiplex::createWithLayer(Layer* layer)
{
return LayerMultiplex::create(layer, nullptr);
}
LayerMultiplex* LayerMultiplex::create()
{
LayerMultiplex* ret = new (std::nothrow) LayerMultiplex();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
LayerMultiplex* LayerMultiplex::createWithArray(const Vector<Layer*>& arrayOfLayers)
{
LayerMultiplex* ret = new (std::nothrow) LayerMultiplex();
if (ret && ret->initWithArray(arrayOfLayers))
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
void LayerMultiplex::addLayer(Layer* layer)
{
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->retainScriptObject(this, layer);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
_layers.pushBack(layer);
}
bool LayerMultiplex::init()
{
if (Layer::init())
{
_enabledLayer = 0;
return true;
}
return false;
}
bool LayerMultiplex::initWithLayers(Layer *layer, va_list params)
{
if (Layer::init())
{
_layers.reserve(5);
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->retainScriptObject(this, layer);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
_layers.pushBack(layer);
Layer *l = va_arg(params,Layer*);
while( l ) {
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
if (sEngine)
{
sEngine->retainScriptObject(this, l);
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
_layers.pushBack(l);
l = va_arg(params,Layer*);
}
_enabledLayer = 0;
this->addChild(_layers.at(_enabledLayer));
return true;
}
return false;
}
bool LayerMultiplex::initWithArray(const Vector<Layer*>& arrayOfLayers)
{
if (Layer::init())
{
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
for (const auto &layer : arrayOfLayers)
{
if (layer)
{
sEngine->retainScriptObject(this, layer);
}
}
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
_layers.reserve(arrayOfLayers.size());
_layers.pushBack(arrayOfLayers);
_enabledLayer = 0;
this->addChild(_layers.at(_enabledLayer));
return true;
}
return false;
}
void LayerMultiplex::switchTo(int n)
{
switchTo(n, true);
}
void LayerMultiplex::switchTo(int n, bool cleanup)
{
CCASSERT( n < _layers.size(), "Invalid index in MultiplexLayer switchTo message" );
this->removeChild(_layers.at(_enabledLayer), cleanup);
_enabledLayer = n;
this->addChild(_layers.at(n));
}
void LayerMultiplex::switchToAndReleaseMe(int n)
{
CCASSERT( n < _layers.size(), "Invalid index in MultiplexLayer switchTo message" );
this->removeChild(_layers.at(_enabledLayer), true);
#if CC_ENABLE_GC_FOR_NATIVE_OBJECTS
auto sEngine = ScriptEngineManager::getInstance()->getScriptEngine();
if (sEngine)
{
sEngine->releaseScriptObject(this, _layers.at(_enabledLayer));
}
#endif // CC_ENABLE_GC_FOR_NATIVE_OBJECTS
_layers.replace(_enabledLayer, nullptr);
_enabledLayer = n;
this->addChild(_layers.at(n));
}
std::string LayerMultiplex::getDescription() const
{
return StringUtils::format("<LayerMultiplex | Tag = %d, Layers = %d", _tag, static_cast<int>(_children.size()));
}
NS_CC_END
| [
"conor.haining@gmail.com"
] | conor.haining@gmail.com |
dfb99de4a029de6f5ed6e77e35ec70eb5b75bdd9 | 82fb4b3a5bd3c47603ab97144815643ff2e92610 | /C++/32. Longest Valid Parentheses/solution.h | b933f2aa2952e5b8a325bf1057abadb027864f46 | [
"MIT"
] | permissive | wenqf11/LeetCode | a0f267f21193c1c9710ba4d570ae39f7467afac8 | 27b464044ecca8933127d1e82fa4973318d7c404 | refs/heads/master | 2020-04-18T02:59:01.024339 | 2017-10-10T03:06:28 | 2017-10-10T03:06:28 | 67,712,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | h | #pragma once
#include<vector>
#include<string>
#include<climits>
#include<algorithm>
#include <stack>
using std::string;
using std::vector;
using std::stack;
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int max = 0;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(') {
st.push(i);
}
else if (s[i] == ')') {
int k = st.top();
if (k >= 0 && s[k] == '(') {
st.pop();
if (i - st.top() > max) {
max = i - st.top();
}
} else {
st.push(i);
}
}
}
return max;
}
}; | [
"qingfu.wen@gmail.com"
] | qingfu.wen@gmail.com |
540131cc7e89b63278d9265a2951b1a62a835490 | 81b9b8ae0e9cc6cf320a95cf373594599d81fe12 | /Tools/Delta/Common/Src/DeltaByteCodeTypes.cpp | 23fcb7f636ac6d5f7c5437a347071c24562d99e8 | [] | no_license | mouchtaris/delta-linux | 1041b9dcc549bda2858dcedbc61087bb73817415 | cca8bd3c1646957cb3203191bb03e80d52f30631 | HEAD | 2016-09-01T19:28:43.257785 | 2014-09-02T05:00:54 | 2014-09-02T05:00:54 | 23,297,561 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,215 | cpp | // DeltaByteCodeTypes.cpp
// Some common facilities for manipulattion
// of Delta types.
// ScriptFighter Project.
// A. Savidis, November 1999.
// Last update, February 2005, changing debug information layout.
//
#include "DDebug.h"
#include "DeltaByteCodeTypes.h"
#include "DeltaVersionDefs.h"
#include "DeltaFunc.h"
#include "ustrings.h"
#include "uerrorclass.h"
#include "ufiles.h"
#include <algorithm>
#include <new>
#define ERROR_HANDLER(what, errclass) \
uerror::GetSingleton().post##errclass( \
"Loading %s: error in reading '%s'!", CURR_TYPE, what \
); goto FAIL;
//-----------------------------------------------------------
DeltaFunctionReturnLibraryType* DeltaFunctionReturnLibraryType::Clone (void) const {
DeltaFunctionReturnLibraryType* type = DNEWCLASS(DeltaFunctionReturnLibraryType, (fullPath));
for (BaseList::const_iterator i = baseTypes.begin(); i != baseTypes.end(); ++i)
type->AddBaseType((*i)->Clone());
return type;
}
/////////////////////////////////////////////////////////////
void DeltaFunctionReturnLibraryType::WriteText (FILE* fp) const {
DASSERT(!fullPath.empty());
fprintf(fp, "<%s>", fullPath.c_str());
if (!baseTypes.empty()) {
fputs(":{", fp);
std::for_each(
baseTypes.begin(),
baseTypes.end(),
std::bind2nd(std::mem_fun(&DeltaFunctionReturnLibraryType::WriteText), fp)
);
fputs("}", fp);
}
}
/////////////////////////////////////////////////////////////
#define CURR_TYPE "return library type"
bool DeltaFunctionReturnLibraryType::Read (GenericReader& reader) {
UCHECK_PRIMARY_ERROR(reader.read(fullPath, false), "full path");
util_ui16 total;
UCHECK_PRIMARY_ERROR(reader.read(&total), "total base library types");
for (util_ui16 i = 0; i <total; ++i) {
DeltaFunctionReturnLibraryType* base = DNEW(DeltaFunctionReturnLibraryType);
AddBaseType(base);
UCHECK_DOMINO_ERROR(DPTR(base)->Read(reader), uconstructstr("base library type #%u", i));
}
return true;
FAIL: return false;
}
/////////////////////////////////////////////////////////////
void DeltaFunctionReturnLibraryType::Write (GenericWriter& writer) const {
DASSERT(!fullPath.empty());
writer.write(fullPath);
writer.write((util_ui16) baseTypes.size());
for (BaseList::const_iterator i = baseTypes.begin(); i != baseTypes.end(); ++i)
DPTR(*i)->Write(writer);
}
/////////////////////////////////////////////////////////////
static const char* basicTypeStrings[] = {
"Any", // AnyValue
"...", // AnyValues
"ExternId", // EternId
DELTA_OBJECT_TYPESTRING, // Object
DELTA_BOOL_TYPESTRING, // Bool
DELTA_NUMBER_TYPESTRING, // Number
DELTA_STRING_TYPESTRING, // String
DELTA_PROGRAMFUNC_TYPESTRING, // Function
DELTA_METHODFUNC_TYPESTRING, // Method
DELTA_LIBRARYFUNC_TYPESTRING, // LibFunction
"Callable", // Callable
"Void", // Void
DELTA_UNDEFINED_TYPESTRING, // Undefined
DELTA_NIL_TYPESTRING // Nil
};
/////////////////////////////////////////////////////////////
DeltaFunctionReturnType::DeltaFunctionReturnType (const DeltaFunctionReturnType& r) {
if (r.IsBasicType())
new(this) DeltaFunctionReturnType(r.GetBasicType());
else
new(this) DeltaFunctionReturnType(DPTR(r.GetLibraryType())->Clone());
}
/////////////////////////////////////////////////////////////
const char* DeltaFunctionReturnType::GetBasicTypeString (DeltaFunctionReturnBasicType type) {
DASSERT(type <= DeltaFunctionReturnNil);
return basicTypeStrings[type];
}
bool DeltaFunctionReturnType::GetBasicTypeFromString (const std::string& typeId, DeltaFunctionReturnBasicType* type) {
util_ui32 n = uarraysize(basicTypeStrings);
util_ui32 i = ustrpos(basicTypeStrings, n, typeId.c_str());
if (i == n)
return false;
else {
*type = (DeltaFunctionReturnBasicType) i;
return true;
}
}
/////////////////////////////////////////////////////////////
void DeltaFunctionReturnType::WriteText (FILE* fp) const {
DASSERT(metaType != None);
if (IsBasicType())
fputs(GetBasicTypeString(data.basicType), fp);
else
GetLibraryType()->WriteText(fp);
fputs(".", fp);
}
/////////////////////////////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "return type"
bool DeltaFunctionReturnType::Read (GenericReader& reader) {
util_ui16 val;
UCHECK_PRIMARY_ERROR(reader.read(&val), "meta type");
metaType = (MetaType) val;
UCHECK_PRIMARY_ERROR(IsBasicType() || IsLibraryType(), "meta type (invalid value)");
if (IsBasicType()) {
UCHECK_PRIMARY_ERROR(reader.read(&val), "basic type");
data.basicType = (DeltaFunctionReturnBasicType) val;
UCHECK_PRIMARY_ERROR(GetBasicType() <= DeltaFunctionReturnNil, "basic type (invalid value)");
}
else {
DeltaFunctionReturnLibraryType* type = DNEW(DeltaFunctionReturnLibraryType);
data.libType = type;
UCHECK_DOMINO_ERROR(DPTR(type)->Read(reader), "library type");
}
return true;
FAIL: return false;
}
/////////////////////////////////////////////////////////////
void DeltaFunctionReturnType::Write (GenericWriter& writer) const {
DASSERT(metaType != None);
writer.write((util_ui16) metaType);
if (IsBasicType())
writer.write((util_ui16) GetBasicType());
else
DNULLCHECK(GetLibraryType())->Write(writer);
}
/////////////////////////////////////////////////////////////
void DeltaFunctionReturnTypes::WriteText (FILE* fp) const {
if (!retTypes.empty()) {
fputs("RETURN TYPES:", fp);
std::for_each(
retTypes.begin(),
retTypes.end(),
std::bind2nd(std::mem_fun(&DeltaFunctionReturnType::WriteText), fp)
);
fputs("\n", fp);
}
}
/////////////////////////////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "return types"
bool DeltaFunctionReturnTypes::Read (GenericReader& reader) {
util_ui16 total;
UCHECK_PRIMARY_ERROR(reader.read(&total), "total return types");
for (util_ui16 i = 0; i < total; ++i) {
DeltaFunctionReturnType* type = DNEW(DeltaFunctionReturnType);
UCHECK_DOMINO_ERROR(DPTR(type)->Read(reader), uconstructstr("return type #%u", i));
retTypes.push_back(type);
}
return true;
FAIL: return false;
}
/////////////////////////////////////////////////////////////
DeltaFunctionReturnTypes::DeltaFunctionReturnTypes (const DeltaFunctionReturnTypes& r) {
for (TypeList::const_iterator i = r.retTypes.begin(); i != r.retTypes.end(); ++i)
retTypes.push_back(DNEWCLASS(DeltaFunctionReturnType, (**i)));
}
/////////////////////////////////////////////////////////////
void DeltaFunctionReturnTypes::Write (GenericWriter& writer) const {
writer.write((util_ui16) retTypes.size());
for (TypeList::const_iterator i = retTypes.begin(); i != retTypes.end(); ++i)
DPTR(*i)->Write(writer);
}
//-----------------------------------------------------------
void DeltaStdFuncInfo::Write (GenericWriter& writer) const{
writer.write(name);
writer.write(isAnonymous);
writer.write(isExported);
writer.write(isMethod);
writer.write(isGlobal);
writer.write(addr);
writer.write(hasVarArgs);
// Arguments.
writer.write(GetTotalFormals());
for ( std::list<std::string>::const_iterator i = arguments.begin();
i != arguments.end();
++i )
writer.write(*i);
// Closure.
writer.write((util_ui16) closureVars.size());
for (ClosureVarsInfo::const_iterator i = closureVars.begin();
i != closureVars.end();
++i ) {
writer.write(i->GetOffset());
writer.write((util_ui32) i->GetType());
writer.write(i->GetName());
writer.write(i->GetLine());
}
writer.write(serial);
if (IsGlobal() && IsNamedFunction())
retTypes.Write(writer);
}
/////////////////////////////////////
static const char* closureVarTypes[] = { "local", "formal", "global", "closure" };
void DeltaStdFuncInfo::WriteText (FILE* fp) const {
std::string args;
for ( std::list<std::string>::const_iterator i = arguments.begin();
i != arguments.end();
++i )
args += (i == arguments.begin() ? "" : ",") + *i;
if (HasVarArgs())
args += "...";
fprintf(
fp,
"%s %s %s '%s'(%s), ADDR %u, FORMALS %u, SERIAL %u.\n",
isGlobal ? "GLOBAL" : "NON-GLOBAL",
isMethod ? "METHOD" : "FUNCTION",
isExported ? "EXPORTED" : "NON-EXPORTED",
name.c_str(),
args.c_str(),
addr,
GetTotalFormals(),
serial
);
if (HasClosureVars()) {
args.clear();
for ( ClosureVarsInfo::const_iterator i = closureVars.begin();
i != closureVars.end();
++i )
args += uconstructstr(
"%s%s:%s(offset %u, line %u)",
i == closureVars.begin() ? "" : ",",
i->GetName().c_str(),
closureVarTypes[(util_ui32) i->GetType()],
i->GetOffset(),
i->GetLine()
);
fprintf(fp, "CLOSUREVARS[%s]\n", args.c_str());
}
if (IsGlobal() && IsNamedFunction())
retTypes.WriteText(fp);
}
/////////////////////////////////////
bool DeltaStdFuncInfo::Read(GenericReader& reader) {
DASSERT(arguments.empty());
UCHECK_PRIMARY_ERROR(reader.read(name, false), "name");
UCHECK_PRIMARY_ERROR(reader.read(&isAnonymous), "is anonymous");
UCHECK_PRIMARY_ERROR(reader.read(&isExported), "is exported");
UCHECK_PRIMARY_ERROR(reader.read(&isMethod), "is method");
UCHECK_PRIMARY_ERROR(reader.read(&isGlobal), "is global");
UCHECK_PRIMARY_ERROR(reader.read(&addr), "address");
UCHECK_PRIMARY_ERROR(reader.read(&hasVarArgs), "has var args");
util_ui16 totalArguments;
UCHECK_PRIMARY_ERROR(reader.read(&totalArguments), "total formals");
for (util_ui16 i = 0; i < totalArguments; ++i) {
std::string name;
UCHECK_PRIMARY_ERROR(reader.read(name, false), uconstructstr("formal arg '%u' name", i));
arguments.push_back(name);
}
util_ui16 n;
UCHECK_PRIMARY_ERROR(reader.read(&n), "total closure vars");
for (util_ui16 i = 0; i < n; ++i) {
util_ui16 offset;
util_ui32 type;
std::string name;
util_ui32 line;
UCHECK_PRIMARY_ERROR(reader.read(&offset), uconstructstr("closure var #%u offset", i));
UCHECK_PRIMARY_ERROR(reader.read(&type), uconstructstr("closure var #%u type", i));
UCHECK_PRIMARY_ERROR(DeltaClosureVarInfo::IsValidOperandType((DeltaClosureVarInfo::VarType) type), "closure var type (invalid value)");
UCHECK_PRIMARY_ERROR(reader.read(name, false), uconstructstr("closure var #%u name", i));
UCHECK_PRIMARY_ERROR(!name.empty(), uconstructstr("closure var #%u name (name empty)", i));
UCHECK_PRIMARY_ERROR(reader.read(&line), uconstructstr("closure var #%u line", i));
UCHECK_PRIMARY_ERROR(line != DELTA_CANTBE_A_SOURCE_LINE, uconstructstr("closure var #%u line (line is zero)", i));
closureVars.push_back(DeltaClosureVarInfo(offset, (DeltaClosureVarInfo::VarType) type, name, line));
}
UCHECK_PRIMARY_ERROR(reader.read(&serial), "serial number");
if (IsGlobal() && IsNamedFunction()) {
UCHECK_DOMINO_ERROR(retTypes.Read(reader), "return types");
}
return true;
FAIL: return false;
}
/////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "function table"
DeltaStdFuncInfo* DeltaStdFuncInfo::ReadFunctionTable (GenericReader& reader, util_ui16* total) {
DeltaStdFuncInfo* funcTable = (DeltaStdFuncInfo*) 0;
UCHECK_PRIMARY_ERROR(reader.read(total), "total functions");
if (*total) {
DeltaStdFuncInfo* p = funcTable = DNEWARR(DeltaStdFuncInfo, *total);
for (util_ui16 i = 0; i < *total; ++i, ++p)
UCHECK_DOMINO_ERROR(p->Read(reader), uconstructstr("function #%u", i));
}
return funcTable;
FAIL: if (funcTable) DDELARR(funcTable); return (DeltaStdFuncInfo*) 0;
}
///-----------------------------------------------------------
DeltaDebugProgramInfo::DeltaDebugProgramInfo (void) {
totalFuncs = 0;
unullify(funcs);
isDynamicCode = false;
}
void DeltaDebugProgramInfo::SetDynamicCode (const std::string& src) {
isDynamicCode = true;
dynamicSource = src;
}
/////////////////////////////////////
void DeltaDebugProgramInfo::Clear (void) {
globals.Clear();
openedNamespaces.clear();
numLibraryConsts.clear();
strLibraryConsts.clear();
if (funcs) {
DASSERT(totalFuncs);
DDELARR(funcs);
funcMap.clear();
unullify(funcs);
totalFuncs = 0;
}
else
DASSERT(funcMap.empty() && !funcs);
lines.Clear();
chunks.Clear();
calls.Clear();
isDynamicCode = false;
}
/////////////////////////////////////
void DeltaDebugProgramInfo::SetTotalFuncs (util_ui16 _totalFuncs) {
if ((totalFuncs = _totalFuncs)) // Intentional assignment.
funcs = DNEWARR(DeltaDebugFuncInfo, totalFuncs);
else
funcs = (DeltaDebugFuncInfo*) 0;
}
/////////////////////////////////////
DeltaDebugFuncInfo* DeltaDebugProgramInfo::GetFunc (util_ui16 serial) {
DASSERT(serial < totalFuncs);
return funcs + serial;
}
const DeltaDebugFuncInfo& DeltaDebugProgramInfo::GetFunc (util_ui16 serial) const {
DASSERT(serial < totalFuncs);
return funcs[serial];
}
DeltaDebugFuncInfo* DeltaDebugProgramInfo::GetFuncByAddr (DeltaCodeAddress addr) {
FuncMap::iterator i = funcMap.find(addr);
return i != funcMap.end() ? i->second : (DeltaDebugFuncInfo*) 0;
}
const DeltaDebugFuncInfo* DeltaDebugProgramInfo::GetFuncByAddr (DeltaCodeAddress addr) const {
FuncMap::const_iterator i = funcMap.find(addr);
return i != funcMap.end() ? i->second : (DeltaDebugFuncInfo*) 0;
}
/////////////////////////////////////
bool DeltaDebugProgramInfo::GetUsedLibraryConst (const std::string& name, DeltaNumberValueType* val) const {
NumConsts::const_iterator i = numLibraryConsts.find(name);
if (i != numLibraryConsts.end())
{ *val = i->second; return true; }
else
return false;
}
bool DeltaDebugProgramInfo::GetUsedLibraryConst (const std::string& name, std::string* val) const {
StrConsts::const_iterator i = strLibraryConsts.find(name);
if (i != strLibraryConsts.end())
{ *val = i->second; return true; }
else
return false;
}
/////////////////////////////////////
// Layout:
// |Globals|Opened Namespaces|Used Library Consts|
// |Total Funcs|Funcs|
// |Lines|Chunks|
// |Dynamic Source|
// |Calls|
//
static void WriteStringList (GenericWriter& writer, const std::list<std::string>& l) {
writer.write((util_ui16) l.size());
for (std::list<std::string>::const_iterator i = l.begin(); i != l.end(); ++i)
writer.write(*i);
}
template <class Tval> static void WriteLibConsts (
GenericWriter& writer,
const std::map<std::string, Tval>& m
) {
writer.write((util_ui16) m.size());
for (typename std::map<std::string, Tval>::const_iterator i = m.begin(); i != m.end(); ++i)
{ writer.write(i->first); writer.write(i->second); }
}
/////////////////////////////////////
void DeltaDebugProgramInfo::Write (GenericWriter& writer) const {
globals.Write(writer);
WriteStringList(writer, openedNamespaces);
WriteStringList(writer, byteCodeLibs);
WriteLibConsts(writer, numLibraryConsts);
WriteLibConsts(writer, strLibraryConsts);
writer.write(totalFuncs);
for (util_ui16 i = 0; i < totalFuncs; ++i)
funcs[i].Write(writer);
// Those two are never writen in text mode.
lines.Write(writer);
chunks.Write(writer);
writer.write(IsDynamicCode());
if (IsDynamicCode())
writer.write(GetDynamicCode());
calls.Write(writer);
}
/////////////////////////////////////
void DeltaDebugProgramInfo::WriteText (FILE* fp) const {
fprintf(fp,"\n***GLOBALS***\n");
GetGlobals().WriteText(fp);
if (!openedNamespaces.empty()) {
fprintf(fp,"\n***OPENED NAMESPACES***\n");
for (NameList::const_iterator i = openedNamespaces.begin(); i != openedNamespaces.end(); ++i)
fprintf(fp, "\t%s\n", i->c_str());
}
if (!byteCodeLibs.empty()) {
fprintf(fp,"\n***USED BYTE CODE LIBRARIES***\n");
for (NameList::const_iterator i = byteCodeLibs.begin(); i != byteCodeLibs.end(); ++i)
fprintf(fp, "\t%s\n", i->c_str());
}
if (!numLibraryConsts.empty() || !strLibraryConsts.empty()) {
fprintf(fp,"\n***USED LIBRARY CONSTS***\n");
for (NumConsts::const_iterator i = numLibraryConsts.begin(); i != numLibraryConsts.end(); ++i)
fprintf(fp, "\t%s = %f\n", i->first.c_str(), i->second);
for (StrConsts::const_iterator i = strLibraryConsts.begin(); i != strLibraryConsts.end(); ++i)
fprintf(fp, "\t%s = \"%s\"\n", i->first.c_str(), i->second.c_str());
}
if (GetTotalFuncs()) {
fprintf(fp,"\n***FUNCTION DETAILS***\n");
for (util_ui16 i = 0; i < GetTotalFuncs(); ++i)
GetFunc(i).WriteText(fp);
}
if (calls.GetTotal()) {
fprintf(fp,"\n***STMTS WITH MULTIPLE CALLS***\n");
calls.WriteText(fp);
}
if (IsDynamicCode())
fprintf(fp,"\n***DYNAMIC SOURCE***\n%s\n", GetDynamicCode().c_str());
}
/////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "program debug info"
static bool ReadStringList (
GenericReader& reader,
std::list<std::string>& l,
const char* totalDescr,
const char* itemDescr
) {
util_ui16 total;
UCHECK_PRIMARY_ERROR(reader.read(&total), totalDescr);
for (util_ui16 i = 0; i < total; ++i) {
std::string s;
UCHECK_PRIMARY_ERROR(reader.read(s, false), uconstructstr("%s #%u", itemDescr, i));
l.push_back(s);
}
return true;
FAIL: return false;
}
/////////////////////////////////////
struct StrValReader {
typedef std::string val_type;
std::string s;
std::string& get (void) { return s; }
bool read (GenericReader& r) { return r.read(s, true); }
};
//***********************************
struct NumValReader {
typedef DeltaNumberValueType val_type;
DeltaNumberValueType n;
DeltaNumberValueType& get (void) { return n; }
bool read (GenericReader& r) { return r.read(&n); }
};
//***********************************
template <class Tvalreader> static bool ReadLibConsts (
GenericReader& reader,
std::map<std::string, typename Tvalreader::val_type>& consts
) {
util_ui16 total;
UCHECK_PRIMARY_ERROR(reader.read(&total), "total used library consts");
for (util_ui16 i = 0; i < total; ++i) {
std::string name;
UCHECK_PRIMARY_ERROR(reader.read(name, false), uconstructstr("library const name #%u", i));
Tvalreader val;
UCHECK_PRIMARY_ERROR(val.read(reader), uconstructstr("library const value #%u", i));
consts[name] = val.get();
}
return true;
FAIL: return false;
}
/////////////////////////////////////
bool DeltaDebugProgramInfo::Read (GenericReader& reader) {
UCHECK_DOMINO_ERROR(globals.Read(reader), "globals");
UCHECK_DOMINO_ERROR(
ReadStringList(reader, openedNamespaces, "total opened namespaces", "opened namespace"),
"opened namespaces info"
);
UCHECK_DOMINO_ERROR(
ReadStringList(reader, byteCodeLibs, "total bytecode library names", "bytecode library name"),
"used bytecode libraries info"
);
UCHECK_DOMINO_ERROR(ReadLibConsts<NumValReader>(reader, numLibraryConsts), "used numeric library consts");
UCHECK_DOMINO_ERROR(ReadLibConsts<StrValReader>(reader, strLibraryConsts), "used string library consts");
UCHECK_PRIMARY_ERROR(reader.read(&totalFuncs), "total functions");
if (totalFuncs) {
funcs = DNEWARR(DeltaDebugFuncInfo, totalFuncs);
for (util_ui16 i = 0; i < totalFuncs; ++i) {
UCHECK_DOMINO_ERROR(
funcs[i].Read(reader),
uconstructstr("function #%d", i)
);
funcMap[funcs[i].GetAddress()] = funcs + i;
}
}
UCHECK_DOMINO_ERROR(lines.Read(reader), "source line numbers");
UCHECK_DOMINO_ERROR(chunks.Read(reader), "source line chunks");
UCHECK_DOMINO_ERROR(reader.read(&isDynamicCode), "is dynamic source");
if (IsDynamicCode()) {
UCHECK_DOMINO_ERROR(reader.read(dynamicSource, false), "dynamic source");
}
UCHECK_DOMINO_ERROR(calls.Read(reader), "calls");
return true;
FAIL: Clear(); return false;
}
/////////////////////////////////////
util_ui16 DeltaDebugProgramInfo::GetNextLine (util_ui16 lineNo) const {
const util_ui16* funcSerial = chunks.FindFuncSerialFromLine(lineNo);
return lines.FindNextLine(lineNo, funcSerial ? *funcSerial : DELTA_FUNCSERIAL_OF_GLOBAL_CODE);
}
//-----------------------------------------------------------
void DeltaCodeLineCollection::Write (GenericWriter& writer) const {
writer.write((util_ui16) lines.size());
for (std::list<DeltaCodeLine>::const_iterator i = lines.begin(); i != lines.end(); ++i) {
writer.write(i->line);
writer.write(i->funcSerial);
}
}
/////////////////////////////////////
void DeltaCodeLineCollection::Write (FILE *fp) {
ufwrite((util_ui16) lines.size(), fp);
for ( std::list<DeltaCodeLine>::iterator i = lines.begin();
i != lines.end();
++i ) {
ufwrite(i->line, fp);
ufwrite(i->funcSerial, fp);
}
}
/////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "code lines"
bool DeltaCodeLineCollection::Read (GenericReader& reader) {
lines.clear();
util_ui16 total;
UCHECK_PRIMARY_ERROR(reader.read(&total), "total");
while (total--) {
util_ui16 line;
UCHECK_PRIMARY_ERROR(reader.read(&line), "line");
util_ui16 funcSerial;
UCHECK_PRIMARY_ERROR(reader.read(&funcSerial), "func serial");
lines.push_back(DeltaCodeLine(line, funcSerial));
}
return true;
FAIL: Clear(); return false;
}
/////////////////////////////////////
bool DeltaCodeLineCollection::IsValidLine (util_ui16 lineNo) const {
return std::find_if(
lines.begin(),
lines.end(),
std::bind2nd(
DeltaCodeLineCollection::EqualPred(),
lineNo
)
) != lines.end();
}
/////////////////////////////////////
util_ui16 DeltaCodeLineCollection::FindNextLine (util_ui16 lineNo, util_ui16 funcSerial) const {
std::list<DeltaCodeLine>::const_iterator i = std::find_if(
lines.begin(),
lines.end(),
std::bind2nd(
FindNextPred(),
DeltaCodeLine(lineNo, funcSerial)
)
);
return i != lines.end() ? i->line : 0;
}
//-----------------------------------------------------------
void DeltaCodeLineChunkCollection::Write (GenericWriter& writer) const {
writer.write((util_ui16) chunks.size());
for ( std::list<DeltaCodeLineChunk>::const_iterator i = chunks.begin();
i != chunks.end();
++i ) {
writer.write(i->funcSerial);
writer.write(i->start);
writer.write(i->end);
}
}
/////////////////////////////////////
void DeltaCodeLineChunkCollection::Write (FILE *fp) const {
ufwrite((util_ui16) chunks.size(), fp);
for ( std::list<DeltaCodeLineChunk>::const_iterator i = chunks.begin();
i != chunks.end();
++i ) {
ufwrite(i->funcSerial, fp);
ufwrite(i->start, fp);
ufwrite(i->end, fp);
}
}
/////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "lines chunk"
bool DeltaCodeLineChunkCollection::Read (GenericReader& reader) {
Clear();
util_ui16 total;
UCHECK_PRIMARY_ERROR(reader.read(&total), "total");
while (total--) {
util_ui16 funcSerial, start, end;
UCHECK_PRIMARY_ERROR(reader.read(&funcSerial), "func serial");
UCHECK_PRIMARY_ERROR(reader.read(&start), "start line");
UCHECK_PRIMARY_ERROR(reader.read(&end), "end line");
chunks.push_back(DeltaCodeLineChunk(funcSerial, start, end));
}
return true;
FAIL: Clear(); return false;
}
/////////////////////////////////////
const util_ui16* DeltaCodeLineChunkCollection::FindFuncSerialFromLine (util_ui16 lineNo) const {
std::list<DeltaCodeLineChunk>::const_iterator i = std::find_if(
chunks.begin(),
chunks.end(),
std::bind2nd(
DeltaCodeLineChunk::LineInPred(),
lineNo
)
);
return i != chunks.end() ? &i->funcSerial : (util_ui16*) 0;
}
//-----------------------------------------------------------
// Write firstly the operand type. If the operand is in use,
// write the val.
//
void DeltaOperand::Write (GenericWriter& writer) const {
writer.write(type);
if (type != DeltaOperand_NotUsed)
writer.write(val);
}
void DeltaOperand::Write (FILE* fp) const {
ufwrite(type, fp);
if (type != DeltaOperand_NotUsed)
ufwrite(val, fp);
}
/////////////////////////////////////
// Read the type first. If the operand is in use, read
// the whole structure.
//
#undef CURR_TYPE
#define CURR_TYPE "instruction operand"
bool DeltaOperand::Read (GenericReader& reader) {
UCHECK_PRIMARY_ERROR(reader.read(&type), "type");
UCHECK_PRIMARY_ERROR(IsValidType(), "type (invalid value)");
UCHECK_PRIMARY_ERROR(type == DeltaOperand_NotUsed || reader.read(&val), "val");
return true;
FAIL: return false;
}
//-----------------------------------------------------------
void DeltaInstruction::Write (GenericWriter& writer) const {
writer.write((util_ui32) opcode);
arg1.Write(writer);
arg2.Write(writer);
result.Write(writer);
writer.write(line);
}
void DeltaInstruction::Write (FILE* fp) {
util_ui32 _opcode = (util_ui32) opcode;
fwrite(&_opcode, sizeof(_opcode), 1, fp);
arg1.Write(fp);
arg2.Write(fp);
result.Write(fp);
ufwrite(line, fp);
}
/////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "instruction"
bool DeltaInstruction::Read (GenericReader& reader) {
util_ui32 _opcode;
UCHECK_PRIMARY_ERROR(reader.read(&_opcode), "opcode");
UCHECK_PRIMARY_ERROR(_opcode < DELTA_TOTAL_VMINSTRUCTIONS, "invalid opcode");
opcode = (DeltaVMOpcode) _opcode;
UCHECK_DOMINO_ERROR(arg1.Read(reader), "arg1");
UCHECK_DOMINO_ERROR(arg2.Read(reader), "arg2");
UCHECK_DOMINO_ERROR(result.Read(reader), "result");
UCHECK_PRIMARY_ERROR(reader.read(&line), "line");
return true;
FAIL: return false;
}
//-----------------------------------------------------------
DBYTECODE_FUNC bool DeltaWriteVersionInformation (GenericWriter& writer) {
writer.write((util_ui32) DELTA_MAGIC_NO);
writer.write((util_ui16) DELTA_VERSION_MAJOR_NO);
writer.write((util_ui16) DELTA_VERSION_MINOR_NO);
return true;
}
/////////////////////////////////////
#undef CURR_TYPE
#define CURR_TYPE "version"
DBYTECODE_FUNC bool DeltaReadVersionInformation (GenericReader& reader) {
util_ui32 magic;
UCHECK_PRIMARY_ERROR(reader.read(&magic), "magic number");
UCHECK_PRIMARY_ERROR(DELTA_ISVALID_MAGICNO(magic), "invalid magic number");
util_ui16 major, minor;
UCHECK_PRIMARY_ERROR(reader.read(&major), "version major number");
UCHECK_PRIMARY_ERROR(reader.read(&minor), "version minor number");
UCHECK_PRIMARY_ERROR(!DELTA_IS_OLDER_VERSION(major, minor), "version; older, rebuild scripts");
UCHECK_PRIMARY_ERROR(!DELTA_IS_NEWER_VERSION(major, minor), "version; newer, rebuild compiler");
DASSERT(DELTA_IS_CURRENT_VERSION(major, minor));
return true;
FAIL: return false;
}
//-----------------------------------------------------------
| [
"lilis@09f5c9fd-6ff0-f344-b9e4-4de1b5e69ea1"
] | lilis@09f5c9fd-6ff0-f344-b9e4-4de1b5e69ea1 |
f35a592a87d24368ae5e1c66ab9ee0cd25937c5d | 181dd33159508fa8caee9b8167e0a1524c8ca3eb | /Algo++/Bitmasking/Generate Subsets.cpp | d05ee7c58c43b9148a15372b64b402ba36833dfc | [] | no_license | livesamarthgupta/Programs | 7b560cda802a13cc8ca8d6ded47512c5665037cb | 2d83603224c0af93612828ce9b8640fc1b247dbd | refs/heads/master | 2023-05-02T23:11:15.663848 | 2021-05-22T12:38:52 | 2021-05-22T12:38:52 | 369,803,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | #include<bits/stdc++.h>
using namespace std;
void filterChars(char a[], int i) {
int j = 0;
while(i > 0) {
int last_bit = i & 1;
i = i >> 1;
if(last_bit)
cout<<a[j];
j++;
}
cout<<endl;
}
void printSubsets(char s[]) {
int n = strlen(s);
for(int i = 0; i < (1 << n); i++) {
filterChars(s, i);
}
}
int main() {
char s[1000];
cin>>s;
printSubsets(s);
return 0;
}
| [
"livesamarthgupta@gmail.com"
] | livesamarthgupta@gmail.com |
1caef1ef15cf2795c5a779a38251c20e1d429d94 | 5ffb24c952eb210113390ea61818357d514c4ce7 | /control/m19_comp_control_display/m19_comp_control_display.ino | 9ff1045cf02592a0e2f0baa10b761cf9ba86c525 | [] | no_license | johnhenryfield/ECVT-Control | 7366d995fa8c3dc4c59fc447fa4ee93948a5269a | efba3d478b1d078a94bcbad1e6aecea22048227c | refs/heads/master | 2022-12-05T05:46:54.011585 | 2020-09-01T04:30:55 | 2020-09-01T04:30:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,022 | ino | /* m19_comp_control_display.ino
*
* runs the ECVT using California 2019 competition code with the addition of an I2C display
*
* author: Tyler McCown (tylermccown@engineering.ucla.edu)
* created: 3 October 2019
*/
#include <Servo.h>
#include <Wire.h>
#include <I2C_LCD.h>
// PWM constants
#define PW_STOP 1515
#define PW_MIN 1000
#define PW_MAX 2000
#define U_K_LAUNCH_SLOW -200
#define U_K_LAUNCH_FAST -350
#define U_K_ABS_MIN PW_MIN - PW_STOP
#define U_K_ABS_MAX PW_MAX - PW_STOP
// actuator
Servo Actuator;
const byte actuator_pin = 9;
#define POT_MIN 163
#define POT_MAX 254
#define POT_ENGAGE 245
int pot_lim_out = POT_MAX;
int pot_lim_in = POT_MIN;
int u_k_min = U_K_ABS_MIN;
int u_k_max = U_K_ABS_MAX;
const byte pot_pin = A1;
int current_pos(0);
// reference signals
// ***** ENGINE ***** //
#define EG_IDLE 1750
#define EG_ENGAGE 2100
#define EG_LAUNCH 2600
#define EG_TORQUE 2700
#define EG_POWER 3400
// ***** GB ***** //
#define GB_LAUNCH 80 // ~ 5 mph
#define GB_TORQUE 128 // ~ 8 mph
#define GB_POWER 621.6 // ~ 39 mph
// ***** ON JACK STAND ***** //
//#define RPM_IDLE 67
//#define RPM_2400 93
//#define RPM_FULLTHROTTLE 530
//#define RPM_2800 135
//#define RPM_3200 350
// controller
int r_k = EG_TORQUE;
int e_k(0);
int u_k(0);
const int control_period = 20000; // [us]
const double Kp = 1;
unsigned long last_control_time(0);
// engine sensor
#define HF_HIGH 800
#define HF_LOW 200
const byte engine_pin = A3;
bool engine_state = LOW;
unsigned long engine_trigger_time(0);
unsigned long engine_last_trigger(0);
unsigned int engine_rpm(0);
// gearbox sensor
const byte gb_pin = 3;
bool gb_state = HIGH;
unsigned long gb_trigger_time(0);
unsigned long gb_last_trigger(0);
unsigned int gb_rpm(0);
// moving average filters
const size_t num_readings = 4;
unsigned int engine_rpm_ave(0);
byte engine_index = 0;
unsigned int engine_readings[num_readings];
unsigned int gearbox_rpm_ave(0);
byte gearbox_index = 0;
unsigned int gearbox_readings[num_readings];
// display setup
I2C_LCD LCD;
uint8_t I2C_LCD_ADDRESS = 0x51;
extern GUI_Bitmap_t bmBruinRacing;
extern GUI_Bitmap_t bmBearHead;
const int refreshPeriod = 1e6; // display refresh time [us]
unsigned long last_refresh_time(0);
void setup() {
// arduino is a good boy
bool good_boy = true;
// open serial connection
// Serial.begin(9600);
// init I2C interface
Wire.begin();
LCD.WorkingModeConf(OFF, ON, WM_BitmapMode);
// clear screen and display sweaty bruin
LCD.CleanAll(WHITE);
LCD.DrawScreenAreaAt(&bmBruinRacing, 0, 1);
delay(1000);
// setup actuator
Actuator.attach(actuator_pin);
Actuator.writeMicroseconds(PW_STOP);
pinMode(pot_pin, INPUT);
current_pos = analogRead(pot_pin);
// setup engine sensor
pinMode(engine_pin, INPUT);
init_readings(engine_readings);
// setup gearbox sensor
pinMode(gb_pin, INPUT);
init_readings(gearbox_readings);
// configure LCD to write text
LCD.CleanAll(WHITE);
LCD.DrawScreenAreaAt(&bmBearHead, 0, 0);
LCD.WorkingModeConf(OFF, ON, WM_CharMode);
LCD.FontModeConf(Font_6x8, FM_MNL_AAA, BLACK_NO_BAC);
LCD.DispStringAt("MODE:", 68, 5);
LCD.DispStringAt("RPM:", 68, 35);
LCD.FontModeConf(Font_8x16_2, FM_MNL_AAA, BLACK_BAC);
}
void init_readings(unsigned int* readings) {
for (int i = 0; i < num_readings; i++) {
readings[i] = 0;
}
}
unsigned int rpm_average(const unsigned int* readings) {
unsigned int sum = 0;
for (int i = 0; i < num_readings; i++) {
sum += readings[i];
}
return (sum / num_readings);
}
void control_function() {
// calculate gearboxrpm
gearbox_rpm_ave = rpm_average(gearbox_readings);
// adjust reference
if (gearbox_rpm_ave > GB_POWER) {
r_k = EG_POWER;
} else if (gearbox_rpm_ave > GB_TORQUE) {
r_k = map(gearbox_rpm_ave, GB_LAUNCH, GB_POWER, EG_LAUNCH, EG_POWER);
} else {
r_k = EG_LAUNCH;
}
// calculate engine rpm
engine_rpm_ave = rpm_average(engine_readings);
// compute error
e_k = r_k - engine_rpm_ave;
// compute control signal
u_k = Kp*e_k;
// change pot outer limit
if (engine_rpm_ave <= EG_ENGAGE) {
pot_lim_out = map(engine_rpm_ave, EG_IDLE, EG_ENGAGE, POT_MAX, POT_ENGAGE);
} else {
pot_lim_out = POT_ENGAGE;
}
// constrain control output
// ***** PWM LIMITS ***** //
u_k_min = U_K_ABS_MIN;
u_k_max = U_K_ABS_MAX;
// ***** LAUNCH ***** //
if (gearbox_rpm_ave < GB_LAUNCH) {
// u_k_max = 0;
if (engine_rpm_ave >= EG_TORQUE) {
u_k_min = U_K_LAUNCH_FAST;
} else if (engine_rpm_ave >= EG_ENGAGE) {
u_k_min = U_K_LAUNCH_SLOW;
}
}
// ***** POT LIMITS ***** //
if (current_pos >= pot_lim_out) {
u_k_max = 0;
} else if (current_pos <= pot_lim_in) {
u_k_min = 0;
}
u_k = constrain(u_k, u_k_min, u_k_max);
// write to actuator
Actuator.writeMicroseconds(u_k + PW_STOP);
}
void update_display() {
LCD.WorkingModeConf(OFF, ON, WM_BitmapMode);
LCD.DrawScreenAreaAt(&bmBearHead, 0, 0);
LCD.WorkingModeConf(OFF, ON, WM_CharMode);
LCD.FontModeConf(Font_6x8, FM_MNL_AAA, BLACK_NO_BAC);
LCD.DispStringAt("MODE:", 68, 5);
LCD.DispStringAt("RPM:", 68, 35);
LCD.FontModeConf(Font_8x16_2, FM_MNL_AAA, BLACK_BAC);
LCD.DispStringAt("SEND", 78, 15);
char rpm_str[5];
itoa(engine_rpm, rpm_str, 10);
LCD.DispStringAt(rpm_str, 78, 45);
}
void loop() {
// check time
unsigned long current_micros = micros();
// check engine_rpm
int engine_reading = analogRead(engine_pin);
if (engine_reading > HF_HIGH) {
engine_state = HIGH;
}
if (engine_reading < HF_LOW && engine_state == HIGH) {
engine_trigger_time = current_micros;
engine_rpm = 60000000.0 / (engine_trigger_time - engine_last_trigger);
engine_readings[engine_index] = engine_rpm;
engine_index = (engine_index + 1) % num_readings;
engine_last_trigger = engine_trigger_time;
engine_state = LOW;
} else if (current_micros - engine_last_trigger >= 1000000) {
init_readings(engine_readings);
engine_last_trigger = current_micros;
}
// check gearbox rpm
int gb_reading = digitalRead(gb_pin);
if (digitalRead(gb_pin) == LOW) {
gb_state = LOW;
}
if (gb_reading == HIGH && gb_state == LOW) {
gb_trigger_time = current_micros;
gb_rpm = (11020408.0)/(gb_trigger_time - gb_last_trigger);
gearbox_readings[gearbox_index] = gb_rpm;
gearbox_index = (gearbox_index + 1) % num_readings;
gb_last_trigger = gb_trigger_time;
gb_state = HIGH;
}
// control loop
if (current_micros - last_control_time >= control_period) {
current_pos = analogRead(pot_pin);
control_function();
last_control_time = current_micros;
// Serial.print(r_k);
// Serial.print(" ");
// Serial.print(gearbox_rpm_ave);
// Serial.print(" ");
// Serial.print(engine_rpm_ave);
// Serial.print(" ");
// Serial.print(current_pos);
// Serial.print("\n");
}
// refresh display
if (current_micros - last_refresh_time >= refreshPeriod) {
update_display();
last_refresh_time = current_micros;
}
}
| [
"tylermccown@engineering.ucla.edu"
] | tylermccown@engineering.ucla.edu |
4984f8bc7be576312cf90957adf2e1ad114284b1 | ffef4697f09fb321a04f2b3aad98b688f4669fb5 | /mindspore/ccsrc/utils/context/ms_context.h | e7d8dc769f791d5ce0727fc463270405bc5c01ab | [
"Apache-2.0",
"AGPL-3.0-only",
"BSD-3-Clause-Open-MPI",
"MPL-1.1",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"MPL-2.0",
"LGPL-2.1-only",
"GPL-2.0-only",
"Libpng",
"BSL-1.0",
"MIT",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Z... | permissive | Ewenwan/mindspore | 02a0f1fd660fa5fec819024f6feffe300af38c9c | 4575fc3ae8e967252d679542719b66e49eaee42b | refs/heads/master | 2021-05-19T03:38:27.923178 | 2020-03-31T05:49:10 | 2020-03-31T05:49:10 | 251,512,047 | 1 | 0 | Apache-2.0 | 2020-03-31T05:48:21 | 2020-03-31T05:48:20 | null | UTF-8 | C++ | false | false | 6,720 | h | /**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* 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 MINDSPORE_CCSRC_UTILS_CONTEXT_MS_CONTEXT_H_
#define MINDSPORE_CCSRC_UTILS_CONTEXT_MS_CONTEXT_H_
#include <thread>
#include <memory>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <utility>
#include "transform/graph_runner.h"
#include "utils/log_adapter.h"
namespace mindspore {
enum MsBackendPolicy {
kMsBackendGeOnly = 0,
kMsBackendVmOnly = 1,
kMsBackendGePrior = 2,
kMsBackendVmPrior = 3,
kMsBackendMsPrior = 4,
kMsBackendUnknown = 5,
};
const int kGraphMode = 0;
const int kPynativeMode = 1;
const char kCPUDevice[] = "CPU";
const char kGPUDevice[] = "GPU";
const char kAscendDevice[] = "Ascend";
const char kDavinciDevice[] = "Davinci";
const char KNpuLog[] = "_npu_log";
const std::set<std::string> kTargetSet = {kCPUDevice, kGPUDevice, kAscendDevice, kDavinciDevice};
class MsContext {
public:
~MsContext() = default;
MsContext(const MsContext&) = delete;
MsContext& operator=(const MsContext&) = delete;
static std::shared_ptr<MsContext> GetInstance();
std::string backend_policy() const;
bool set_backend_policy(const std::string& policy);
int execution_mode() const { return execution_mode_; }
void set_execution_mode(int execution_mode);
bool enable_pynative_infer() const { return enable_pynative_infer_; }
void set_enable_pynative_infer(bool enable_pynative_infer) { enable_pynative_infer_ = enable_pynative_infer; }
void set_enable_task_sink(bool enable_task_sink) { enable_task_sink_ = enable_task_sink; }
bool enable_task_sink() const { return enable_task_sink_; }
void set_precompile_only(bool precompile_only) { precompile_only_ = precompile_only; }
bool precompile_only() const { return precompile_only_; }
std::string device_target() const { return device_target_; }
bool set_device_target(const std::string& target);
uint32_t device_id() const { return device_id_; }
bool set_device_id(uint32_t device_id);
bool save_graphs_flag() const { return save_graphs_flag_; }
void set_save_graphs_flag(bool save_graphs_flag) { save_graphs_flag_ = save_graphs_flag; }
std::string save_graphs_path() const { return save_graphs_path_; }
void set_save_graphs_path(const std::string& save_paths) { save_graphs_path_ = save_paths; }
bool OpenTsd();
bool CloseTsd(bool force = false);
bool InitGe();
bool FinalizeGe(bool force = false);
void set_enable_hccl(bool enable_hccl) { enable_hccl_ = enable_hccl; }
bool enable_hccl() const { return enable_hccl_; }
bool PynativeInitGe();
void set_ir_fusion_flag(bool ir_fusion_flag) { ir_fusion_flag_ = ir_fusion_flag; }
bool ir_fusion_flag() const { return ir_fusion_flag_; }
void set_loop_sink_flag(bool loop_sink_flag) { enable_loop_sink_ = loop_sink_flag; }
bool loop_sink_flag() const { return enable_loop_sink_; }
void set_enable_mem_reuse(bool enable_mem_reuse) { enable_mem_reuse_ = enable_mem_reuse; }
bool enable_mem_reuse() const { return enable_mem_reuse_; }
bool save_ms_model_flag() const { return save_ms_model_flag_; }
void set_save_ms_model_flag(bool save_ms_model_flag) { save_ms_model_flag_ = save_ms_model_flag; }
std::string save_ms_model_path() const { return save_ms_model_path_; }
void set_save_ms_model_path(const std::string& save_ms_model_path) { save_ms_model_path_ = save_ms_model_path; }
void set_enable_gpu_summary(bool enable_gpu_summary) { enable_gpu_summary_ = enable_gpu_summary; }
bool enable_gpu_summary() const { return enable_gpu_summary_; }
void set_auto_mixed_precision_flag(bool auto_mixed_precision_flag) {
auto_mixed_precision_flag_ = auto_mixed_precision_flag;
}
bool auto_mixed_precision_flag() const { return auto_mixed_precision_flag_; }
void set_enable_reduce_precision(bool flag) { enable_reduce_precision_ = flag; }
bool enable_reduce_precision() const { return enable_reduce_precision_; }
void set_enable_dump(bool flag) { enable_dump_ = flag; }
bool enable_dump() const { return enable_dump_; }
void set_save_dump_path(const std::string& path) { save_dump_path_ = path; }
std::string save_dump_path() const { return save_dump_path_; }
bool IsTsdOpened() const { return tsd_ref_ > 0; }
bool is_multi_graph_sink() const { return is_multi_graph_sink_; }
void set_is_multi_graph_sink(bool flag) { is_multi_graph_sink_ = flag; }
void set_enable_dynamic_mem_pool(bool enable_dynamic_mem_pool) { enable_dynamic_mem_pool_ = enable_dynamic_mem_pool; }
bool enable_dynamic_mem_pool() const { return enable_dynamic_mem_pool_; }
void set_graph_memory_max_size(const std::string& graph_memory_max_size) {
graph_memory_max_size_ = graph_memory_max_size;
}
void set_variable_memory_max_size(const std::string& variable_memory_max_size) {
variable_memory_max_size_ = variable_memory_max_size;
}
private:
MsContext(const std::string& backend_policy, const std::string& target);
void GetGeOptions(std::map<std::string, std::string>* ge_options) const;
void SetDisableReuseMemoryFlag(std::map<std::string, std::string>* ge_options) const;
void SetHcclOptions(std::map<std::string, std::string>* ge_options) const;
static std::shared_ptr<MsContext> inst_context_;
static std::map<std::string, MsBackendPolicy> policy_map_;
MsBackendPolicy backend_policy_;
std::string device_target_;
uint32_t device_id_;
int execution_mode_;
bool enable_pynative_infer_;
bool save_graphs_flag_;
std::string save_graphs_path_;
uint32_t tsd_ref_;
uint32_t ge_ref_;
bool enable_task_sink_;
bool enable_hccl_;
bool precompile_only_;
bool ir_fusion_flag_;
bool auto_mixed_precision_flag_;
bool enable_reduce_precision_;
bool enable_loop_sink_;
bool enable_mem_reuse_;
std::string save_ms_model_path_;
bool save_ms_model_flag_;
bool enable_gpu_summary_;
bool enable_dump_;
std::string save_dump_path_;
bool is_multi_graph_sink_;
bool is_pynative_ge_init_;
bool enable_dynamic_mem_pool_;
std::string graph_memory_max_size_;
std::string variable_memory_max_size_;
std::thread tdt_print_;
};
} // namespace mindspore
#endif // MINDSPORE_CCSRC_UTILS_CONTEXT_MS_CONTEXT_H_
| [
"leon.wanghui@huawei.com"
] | leon.wanghui@huawei.com |
52b8b568b1e1cacbc6ac1cc7492ea93b7e7842e3 | c04a86e9639d5d234da348e3d7c67557e249fa1c | /SampleCode/projects/RecipeBook/Classes/recipes/Recipe54.h | 355462e3b1fd01b9eaf207bf410f45e593433d3a | [
"MIT"
] | permissive | stanjiang/cocos2dx_recipe | ce0d46cfae50273acf7d665e22bb04d645d0cf81 | 261b6fd0b18ae3145ee839f4027c39cb44c6335a | refs/heads/master | 2020-11-30T23:31:19.718774 | 2013-06-01T07:03:04 | 2013-06-01T07:03:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | h | //
// Recipe54.h
// RecipeBook
//
// Created by FURUKI Eiji on 13/05/30.
//
//
#ifndef __RecipeBook__Recipe54__
#define __RecipeBook__Recipe54__
#include "cocos2d.h"
#include "RecipeBase.h"
class Recipe54 : public RecipeBase
{
private:
public:
Recipe54();
virtual bool init();
static cocos2d::CCScene* scene();
CREATE_FUNC(Recipe54);
virtual void onEnter();
bool getTextFromUrl(const char* url, std::vector<char> *response);
void recipe54_httprequest();
void onHttpRequestCompleted(cocos2d::CCNode *sender, void *data);
};
#endif /* defined(__RecipeBook__Recipe54__) */
| [
"fullfool@gmail.com"
] | fullfool@gmail.com |
db711813a9910e703f02f90af6c27231f197b6e2 | 6737ddc082b7c34468bb519e0135121309535ffa | /week1/2.cpp | a4755ea486cafa50911ed7806ab91b249d5446a1 | [] | no_license | maximumevilcoverage/itmo_i2cpx | 734bd8f468587818cc76fe30ff324dc087243abf | 8f27f5b4e73a4709408534eb43924e8d98b0db59 | refs/heads/master | 2020-03-22T04:14:04.221655 | 2018-07-06T09:58:01 | 2018-07-06T09:58:01 | 139,483,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,771 | cpp | #include <ctime>
#include <cmath>
#include <algorithm>
#include <cstdio>
#include <string>
#include <map>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <fstream>
#include <vector>
#include <utility>
#include <numeric>
#include <iterator>
#include <functional>
#include <cctype>
#include <cstdarg>
#include <deque>
#include <set>
#include <unordered_set>
#include <complex>
#include <cassert>
using std::map;
using std::set;
using std::unordered_set;
using std::deque;
using std::cout;
using std::cin;
using std::sort; //from algorithm
using std::getline; //from string
using std::isalnum; //is alphanumeric
using std::isalpha; //is alphabetic
using std::make_pair;
using std::vector;
using std::ostream;
using std::swap;
using std::string;
using std::complex;
template <typename... Args>
auto gl(Args&&... args) -> decltype(getline(std::forward<Args>(args)...)) {
return getline(std::forward<Args>(args)...);
}
//using std::gcd; //from numeric, C++17 only
//using std::copy; //from algorithm
// Shortcuts for "common" data types in contests
typedef unordered_set<char> sc;
typedef unordered_set<int> si;
typedef std::string str;
typedef long long ll;
typedef unsigned long ul;
typedef unsigned long long ull;
typedef std::pair<int, int> pi;
typedef std::vector<pi> vpi;
typedef std::vector<int> vi;
typedef std::vector<vi> vvi;
typedef std::vector<char> vc;
typedef std::vector<str> vs;
typedef std::map<str,int> msi;
typedef std::map<int,int> mii;
#define MAP(v,op) std::transform(v.begin(), v.end(), v.begin(), op)
//usage: MAP(s, [](char c){return toupper(c);});
#define FOLD(v,op) std::accumulate(v.begin()+1, v.end(), v[0], op) //using FOLD on empty lists is UB!!!
//usage: FOLD(v, [](int result_so_far, int next){return result_so_far + next;});
#define STR(v) std::to_string(v)
#define LOG( msg ) std::cout << __FILE__ << ":" << __LINE__ << ": " << msg
#define PV(v) printv(v,#v,__LINE__)
#define SUM(v) std::accumulate(v.begin(), v.end(), 0) //return type is same as type of init
#define PROD(v) std::accumulate(begin(v), end(v), 1, std::multiplies<>()) // product of the elements
#define XOR(v) std::accumulate(begin(v), end(v), 0, std::bit_xor<>()) //defined in functional
#define MIN(v) (*std::min_element( std::begin(v), std::end(v) ))
#define MIN_INDEX(v) (std::min_element( std::begin(v), std::end(v) ) - v.begin())
#define MAX(v) (*std::max_element( std::begin(v), std::end(v) ))
#define MAX_INDEX(v) (std::max_element( std::begin(v), std::end(v) ) - v.begin())
#define HAS(c,x) ((c).find(x) != (c).end())
#define RSUB(v) std::accumulate(rbegin(v)+1, rend(v), v.back(), std::minus<>()) //minus from right to left
//#define RV(a) vi a; getlineintovi(a) //needs getlineintovi defined
#define INPUT(s, ...) do { std::istringstream iss(s); input(iss, __VA_ARGS__); } while (0)
//usage: INPUT(s, a, b, c)
//the GLI macro reads a line into a variadic list of ints (or something else). You need to declare the variables yourself.
#define GL(s) str s; getline(cin,s);
#define GLI(...) do {str s;getline(cin,s);INPUT(s,__VA_ARGS__);} while(0) //needs the input variadic templates defined
#define GLL(...) ll __VA_ARGS__; gli(__VA_ARGS__);
#define GLUL(var) ul var; gli(var);
#define GLSTR(var) str var; gli(var);
//the SV macro converts a line into a vector of ints. It declares the vector for you.
/*
* Note: SV(s,v) creates a new vector v out of s
* Whereas s2v(s,v) copies s into an existing vector v
* To use s2v you must first create a vector - opposite for SV
* Use of SV may lead to subtle bugs
* Use s2v unless you know what you're doing
*/
#define SVI(s,v) vi v{std::istream_iterator<int>{std::istringstream(s) >> std::skipws}, std::istream_iterator<int>()}; //the >> skipws trick works because the extractor returns an lvalue-reference
#define VCS(v,s) std::string s(v.begin(),v.end()); //s from vc
#define SVC(s,v) vc v{s.begin(), s.end()}; //vc from s
#define INF 1000000000 // 1 billion, safer than 2B for Floyd Warshall’s
#define REPUL(i, a, b) \
for (ul i = ul(a); i < ul(b); ++i)
#define REP(i, begin, end) for (int i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define L(b) \
for (ul TEMP_ = 0; TEMP_ < ul(b); ++TEMP_)
#define L2(b) \
for (ul TEMP__ = 0; TEMP__ < ul(b); ++TEMP__)
#define LR(i,b) \
for (ll i = 0; i < ll(b); ++i)
#define LR1(i,b) \
for (ll i = 1; i <= ll(b); ++i)
#define LRR(i,b) \
for (size_t i = ul(b); i --> 0;)
#define LOOPREAD(c, terminator) while(cin.get(c)){ if (c == terminator) break; //hideously disgusting macro, avoid if possible.
#define BY(x) [](const auto& a, const auto& b) { return a.x < b.x; }
//usage: sort(arr, arr + N, BY(a)); //where arr is an array of objects each containing a field named x
#define F first
#define S second
#define B(x) std::begin(x)
#define E(x) std::end(x)
#define PB push_back
#define PF push_front
#define MP make_pair
#define SZ(a) int((a).size())
#define ODD(num) (num & 1)
#define ISPRF(prefix,s) (s.compare(0, prefix.size(), prefix) == 0)
#define XSWAP(a,b) (a)^=(b); (b)^=(a); (a)^=(b); //xor swap
#define REV(s) std::reverse(begin(s), end(s));
#define ALL(a) a.begin(), a.end()
#define IN(a,b) ( (b).find(a) != (b).end())
#define BITSET(n,b) ( (n >> b) & 1)
// Useful hardware instructions
#define POPCNT __builtin_popcount
#define GCD __gcd
#define DIV(top,bot,q,r) int q = top / bot; int r = top % bot;
//auto [q,r] = div(gift,num); //If only judges supported C++17 :(((
/*
* The MEMO macro creates a memoized function which relies on a helper function
* When the memoized function doesn't have the result stored in cache it calls the helper function
* The helper function can call back to the memoized function with a reduced parameter,
* and the memoized function will simply pass that parameter straight back to the helper function.
*
* Currently MEMO only supports one parameter, and this parameter is bound to the name "x" in the function.
*
* Example usage:
MEMO(fib,int,int){
if (x == 0){return 0;}
if (x == 1 or x == 2){return 1;}
return (fib(x-1)%1000000007) + (fib(x-2)%1000000007);
}
* */
#define MEMO(funcname, parametertype, returntype) \
returntype funcname##_(parametertype); \
returntype funcname(parametertype key){ \
static std::map<parametertype,returntype> cache; \
auto it = cache.find(key); \
if (it != end(cache)){return it->second;} \
auto value = funcname##_(key); \
return cache.emplace(key,value).first->second;} \
returntype funcname##_(parametertype x)
//ios_base::sync_with_stdio(false)
//useful functions
template <typename T, typename F>
size_t count_if(T it, F pred){
return std::count_if(it.begin(), it.end(), pred);
}
template<typename T,typename TT> ostream& operator<<(ostream &s,std::pair<T,TT> t) {return s<<"("<<t.first<<","<<t.second<<")";}
template <typename T>
T psum(T x, T y){ return x + y; }
template <typename T>
T psub(T x, T y){ return x - y; }
template <typename T>
T pdiff(T x, T y){ return abs(x - y); }
//usage: vi v2 = zipreduce(v,v,psub,-1);
template <typename T>
T pprod(T x, T y){ return x * y; }
template <typename T>
T pdiv(T x, T y){ return x / y; }
template <typename T>
T pmax(T x, T y){ if (x > y){ return x; } else { return y; } }
template <typename T>
const deque<T>& pmax(const deque<T>& x, const deque<T>& y){
if (x.size() > y.size()){
return x;
}
return y;
}
template <typename T>
void zero(T& v){
std::fill(v.begin(), v.end(), 0);
}
template <typename T>
void lrot(T& v, ul i){
std::rotate(v.begin(), v.begin() + i, v.end());
}
template <typename T>
void rrot(T& v, ul i){
std::rotate(v.rbegin(), v.rbegin() + i, v.rend());
}
template <typename T>
T pmin(T x, T y){ if (x < y){ return x; } else { return y; } }
template <typename T>
vector<T>& pmin(vector<T>& x, vector<T>& y){
if (x.size() < y.size()){
return x;
}
return y;
}
template <typename T>
T pcomp(T x, T y){ return (x==y); }
ll positive_modulo(ll i, ull n) {
return (i % ll(n) + ll(n)) % ll(n);
}
ll ceil(ll a, ll b){
assert(a>0 && b>0);
return 1 + ((a - 1) / b);
}
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
//we simply change cin and cout to point to files instead of having to pass ostream to the print function
//disgusting global variables, sorry.I promise I won't use this in production code.
static bool debug = false;
#ifdef ENABLE_DEBUG
static bool release = false;
#else
static bool release = true;
#endif
static std::ifstream fin;
static std::ofstream fout;
void print(pi p){
cout << "(" << p.F << "," << p.S << ")";
}
void printtype(str){
cout << "<string>";
}
void printtype(int){
cout << "<int>";
}
void printtype(pi){
cout << "<pair<int,int>>";
}
template <typename T>
void print(const vector<T> v){
cout << "vector";
printtype(v[0]);
cout << " = [\n";
for (auto e:v){
cout << " ";
print(e);
cout << '\n';
}
//print("]\n");
}
template <typename T>
std::ostream& operator<<(std::ostream& out, const vector<T>& v){
if (debug) out << "vector: [";
char delim = debug ? ',' : ' ';
if (v.empty()){
out << "empty";
}
else{
out << v[0];
REP(i,1,v.size()){
out << delim << v[i];
}
}
if (debug) out << "]\n";
return out;
}
void prt(const vpi& v){
//print("vector<pair<int,int>>",s,"on line",STR(linenumber)+": [");
if (v.empty()){
cout << "empty";
}
else{
bool flag = false;
for (auto p:v){
if (flag){
cout << ",";
}
cout << "(" << p.F << "," << p.S << ")";
flag = true;
}
}
//print("]\n");
}
template <typename T, typename X>
void print(std::map<T,X> m){
cout << "map = {\n";
for(auto it = m.begin(); it != m.end(); ++it)
{
cout << " " << it->first << " : " << it->second << "\n";
}
cout << "};\n";
}
template <typename Arg>
void prt(Arg&& arg)
{
cout << std::forward<Arg>(arg);
}
template <typename Arg, typename... Args>
void prt(Arg&& arg, Args&&... args)
{
cout << std::forward<Arg>(arg);
cout << ' ';
prt(std::forward<Args>(args)...);
}
template <typename... Args>
void prtl(Args&&... args) //printline
{
prt(std::forward<Args>(args)...);
prt('\n');
}
/*
*
* Big Integer class for arbitrary precision arithmetic
*
* Originally wrote it to hold 63 bit integers but gave up when implementing shift
*
* This base 10 implementation is a lot less efficient but so much easier to implement.
*
* */
const int big_int_base_digits = 9;
const int big_int_base = 1000000000;
class BigInt{
public:
bool positive = true; //positive by default
deque<long> v; //unsigned char for holding values 0-9
BigInt(long l){ //let's do this properly
v.PF(l);
}
BigInt(const str& s){ //let's do this properly
ul groups = s.size() / big_int_base_digits;
int r = s.size() % big_int_base_digits;
//first read all full groups into the BigInt
for (int i = 0; ul(i) < groups; i++){ //this is 100% correct, don't fuck with it.
auto value = stol(s.substr((groups-i-1)*big_int_base_digits+r,big_int_base_digits));
v.PF(value);
}
if (r){
auto value = stol(s.substr(0,r));
v.PF(value);
}
}
friend ostream& operator<<(ostream &out, const BigInt &b) {
out << b.v[0];
if (b.v.size() > 1){
REP(i,1,b.v.size()){
out << std::setw(big_int_base_digits) << std::setfill('0') << b.v[i];
}
}
return out;
}
void pad(ul p){
L(p){
v.PF(0);
}
}
void truncate(){
while(true){
if (v.front() == 0 && v.size() > 1){
v.pop_front();
}
else{
break;
}
}
}
BigInt& operator<<=(ul i){ // don't change this, it is correct
std::rotate(v.begin(), v.begin() + i, v.end());
return *this;
}
BigInt& operator+=(BigInt bi){
if (v.size() < bi.v.size()){
pad(bi.v.size() - v.size());
}
else if (v.size() > bi.v.size()){
bi.pad(v.size() - bi.v.size());
}
bool carry = 0; long result;
for(long i = v.size()-1; i >= 0; i--){
result = v[i] + bi.v[i] + carry;
carry = result / big_int_base; //see if highest bit is set
result %= big_int_base; //unset highest bit
v[i] = result;
}
if (carry){
v.PF(1);
}
return *this;
}
BigInt operator*(const BigInt& b){
ull carry = 0; ull result = 0;
BigInt runningsum{"0"};
BigInt temp{"0"};
ul templen = v.size() + b.v.size();
temp.v.resize(templen);
auto diff = templen - b.v.size();
int j=0; int pos = 0;
LRR(i,v.size()){ //multiply each digit in v with b
zero(temp.v); carry = 0;
LRR(j,b.v.size()){ //each digit of b
result = v[i] * b.v[j] + carry;
carry = result / big_int_base;
result %= big_int_base;
temp.v[diff+j] = result;
}
if (carry){
temp.v[diff+j-1] = carry;
}
temp <<= pos; pos++;
runningsum += temp;
}
runningsum.truncate();
return runningsum;
}
BigInt& operator*=(const BigInt& b){
BigInt result = *this * b;
positive = result.positive;
v = std::move(result.v); //steal v from result
return *this;
}
};
/*
* Matrix class todo: Make the multiplicand matrix column-major for better CPU caching behavior.
*
* */
class Mat {
public:
vector<ll> v;
ul rows, cols; bool mod = false; ul n = 0;
Mat(ul rows, ul cols):rows(rows), cols(cols){
v.resize(rows * cols);
}
Mat(ul rows, ul cols, ul n):rows(rows), cols(cols), n(n){
if (n != 0){
mod = true;
}
v.resize(rows * cols);
}
ll dot(const Mat& a, const Mat& b, ul arow, ul bcol){
ll result = 0;
if (mod){
LR(i,a.cols){
result = (result + (a.v[arow*a.cols+i] * b.v[b.cols*i+bcol]) % n) % n;
}
}
else{
LR(i,a.cols){
result += a.v[arow*a.cols+i] * b.v[b.cols*i+bcol];
}
}
return result;
}
Mat& inr(const vector<ll>& lls){ //insert row into matrix
assert(lls.size() == cols && "Inserted row is wrong length");
rows++;
for (auto l:lls){
v.PB(l);
}
return *this;
}
Mat& inr(ul row, const vector<ll>& lls){ //insert row into matrix
assert(lls.size() == cols && "Inserted row is wrong length");
assert(row < rows && "Specified row number is out of bounds");
ul start = row * cols;
ul end = (row+1)*cols;
REP(i, start, end){
v[i] = lls[i - start];
}
return *this;
}
ll& operator()(ul i, ul j){
return v[i*cols+j];
}
Mat& operator+=(const Mat& m){
assert(rows == m.rows && cols == m.cols && "Can't add 2 matrices of different size");
if (mod) {
LR(i,v.size()){
v[i] = (v[i] + m.v[i]) % n;
}
}
else{
LR(i,v.size()){
v[i] += m.v[i];
}
}
return *this;
}
Mat& operator-=(const Mat& m){
assert(rows == m.rows && cols == m.cols && "Can't subtract 2 matrices of different size");
LR(i,v.size()){
v[i] -= m.v[i];
}
return *this;
}
void mult(Mat& result, const Mat& m){
LR(i,rows){
LR(j,m.cols){
result(i,j) = dot(*this,m,i,j);
}
}
}
Mat operator*(const Mat& m){
assert(cols == m.rows && "Matrix multiplication requires A.cols = B.rows");
Mat result(rows,m.cols, n);
mult(result, m);
return result;
}
Mat& operator*=(const Mat& m){
assert(cols == m.rows && "Matrix multiplication requires A.cols = B.rows");
Mat result(rows,m.cols);
mult(result, m);
rows = result.rows;
cols = result.cols;
v = std::move(result.v); //move the internal vector of the result matrix to this matrix.
return *this;
}
};
std::ostream& operator<<(std::ostream &out, const Mat& m){
out << "Matrix: {\n";
LR(i,m.rows){
out << " ";
LR(j,m.cols){
out << " " << m.v[i*m.cols + j];
}
out << '\n';
}
return out << "}\n";
}
template <typename T>
void input(std::istringstream& iss, T& arg)
{
iss >> arg;
}
template <typename T>
void input(std::istringstream& iss, vector<T>& v) //thank god for overload resolution
{
v.clear();
std::copy(std::istream_iterator<T>(iss), //s/iss/cin for reading from stdin
std::istream_iterator<T>(),
std::back_inserter(v));
}
template <typename T, typename... Args>
void input(std::istringstream& iss,T& arg, Args&... args) //recursive variadic function
{
iss >> arg;
input(iss, args...);
}
//convert a string of ints to a vector of ints
/*
void s2v(const str& s, vi& v){
v.clear();
std::istringstream iss(s);
std::copy(std::istream_iterator<int>(iss), //s/iss/cin for reading from stdin
std::istream_iterator<int>(),
std::back_inserter(v));
}*/
template <typename T>
void s2v(const str& s, vector<T>& v){
v.clear();
std::istringstream iss(s);
std::copy(std::istream_iterator<T>(iss), //s/iss/cin for reading from stdin
std::istream_iterator<T>(),
std::back_inserter(v));
}
void getlineintovi(vi& v){
std::string line;
getline(cin, line);
s2v(line,v);
}
char change_case (char c) {
if (std::isupper(c))
return char(std::tolower(c));
else
return char(std::toupper(c));
}
void strip_nonalnum(str& s){ //strip non-alphanumeric
s.erase(std::remove_if(s.begin(), s.end(), [](char c) { return !isalnum(c); }), s.end());
//std::not1(std::ptr_fun( (int(*)(int))std::isalnum ))
}
long mismatch_index(const str& s1, const str& s2){
auto p = std::mismatch(std::begin(s1),std::end(s1),std::begin(s2),std::end(s2));
auto it = p.F;
return distance(std::begin(s1), it);
}
//todo: make a variadic template version of this
vpi zip(const vi& a, const vi& b){ //requires a and b to be same length
vpi result;
if (a.size() != b.size()){LOG("size of a and b not equal");}
LR(i,a.size()){
result.emplace_back(a[i],b[i]);
}
return result;
}
//use boost's implementation of zipreduce instead
template <typename T>
vector<T> zipreduce(const vector<T>& a, const vector<T>& b, int d, T (op)(T,T)){ //add more default parameters as needed.
if (a.size() != b.size()){LOG("size of a and b not equal");}
vector<T> result; ul displacement = ul(d); bool flag = true; T arg1, arg2;
if (d < 0) { displacement = ul(-d); flag = false;}
LR(i,a.size()-displacement){
if (flag){ arg1 = a[i]; arg2 = b[i+displacement]; }
else{ arg1 = a[i+displacement]; arg2 = b[i]; }
result.emplace_back(op(arg1,arg2));
}
return result;
}
//usage: vi v = zipreduce(a,b,[](int a, int b){return a+b;});
template <typename T>
void esort(T& v){ //easy sort
sort(v.begin(),v.end());
}
template <typename T>
void rsort(T& v){ //reverse easy sort
sort(v.rbegin(),v.rend());
}
template <typename T, typename V>
long efind(T begin, T end, V value){ //easy find
return std::find(begin,end,value)-begin;
}
template <typename T, typename V>
long efind(T v, V value){ //easy find
return std::find(B(v),E(v),value)-B(v);
}
vi lfreq(const str& s){ //letter frequencies
vi f(26);
for (char c:s){
f[ul(c-'a')]++;
}
return f;
}
vi nfreq(const vi& v){ //number frequencies
int max = v[0];
for (int i:v){
if (i<0){ LOG("Error: vector contains negative numbers, use map instead?"); }
max = pmax(max,i);
if (max > 1000000) { LOG("Error: max of vector larger than 1 million"); }
}
vi result(static_cast<ul>(max+1));
for (int i:v){
result[static_cast<ul>(i)]++;
}
return result;
}
template <typename T>
std::map<T,ul> freq(vector<T> v){
std::map<T,ul> m;
for (auto t:v){
m[t]++;
}
return m;
}
template <typename K, typename V>
class OrderedMap {
public:
std::map<K,V> m;
vector<K> v;
OrderedMap& add(const K& k, V v){
this->v.push_back(k);
m[k] = v;
return *this;
}
V& operator[](const K& k){
return m[k];
}
void prt(){
for (const K& k:v){
cout << k << ' ' << m[k] << '\n';
}
}
};
typedef OrderedMap<str,int> omsi;
int max(vi v){ //no point in using this. Just use MAX instead.
return MAX(v);
}
template <typename K, typename V>
std::pair<K,V> max(std::map<K,V> m){ //find max entry in map by value, MAX finds by key
return *std::max_element(std::begin(m), std::end(m),
[] (const std::pair<K,V> & p1, const std::pair<K,V> & p2) {
return p1.second < p2.second;
});
}
template <typename K, typename V>
std::pair<K,V> min(std::map<K,V> m){ //find min entry in map by value, MIN finds by key
return *std::min_element(std::begin(m), std::end(m),
[] (const std::pair<K,V> & p1, const std::pair<K,V> & p2) {
return p1.second < p2.second;
});
}
template <typename T>
std::pair<T,ul> max(std::map<T,ul> m){
ul max{0};
std::pair<T,ul> result;
for (const auto& p:m){
if (max< p.S){
max = p.S;
result = p;
}
}
return result;
}
template <typename... Args>
bool gli(Args&... args) //read in a variable number of variables on one line
{
str s; bool x = false;
if(gl(cin,s)){x = true;}
std::istringstream iss(s);
input(iss, args...);
return x;
}
bool gline(str& s) //synonym for getline
{
bool x = false;
if(gl(cin,s)){x = true;}
//cout << "gline: " << s << "end gline";
return x;
}
/*
* TODO: Make gln variadic: PipeCalcParams& set(std::initializer_list<ChParam> args)
* */
template <typename Arg>
void gln(Arg& arg) //read in a variable number of variables, each on its own line
{
gli(arg);
}
template <typename Arg, typename... Args>
void gln(Arg& arg, Args&... args) //read in a variable number of variables, each on its own line
{
gli(arg);
gln(args...);
}
vi getbits(ull x){
vi v;
while(x){
v.PB(x&1);
x >>= 1;
}
v.pop_back();
REV(v);
return v;
}
int scan (char& c){
return scanf("%c",&c);
}
/* usage:
*
Mat m(0,2,1000000007);
m.inr({1,1});
m.inr({1,0});
power(m,x);
println(m(0,1));
* */
template <typename T> //exponentiate x to the power of p
void power(T& x, ul p){
vi v = getbits(p);
auto id = x;
for (int i : v){
x *= x;
if (i){
x *= id;
}
}
}
void setio(str infile, str out=""){
if (release){
fin = std::ifstream(infile);
std::cin.rdbuf(fin.rdbuf()); //redirect std::cin to in.txt!
if (out != ""){
fout = std::ofstream(out);
std::cout.rdbuf(fout.rdbuf()); //redirect std::cout to out.txt!
}
}
}
int clamp(int inp, int max, int min){
if (inp > max) return max;
if (inp < min) return min;
return inp;
}
int wheeldiff(int a, int b, int total){ //as per CF731-D2-A
/* old code
int half = total / 2;
int diff = abs(a-b);
if (diff > half){
return total - diff;
}
return diff; */
return pmin(abs(a-b),total-abs(a-b));
}
template <typename T>
int num_unique(T l){ //gets number of elements remaining after removing all consecutive duplicates in list
auto it = std::unique(l.begin(), l.end());
return std::distance(it, l.end());
}
template <typename T>
size_t count_unique(T l){ //gets number of elements remaining after removing all consecutive duplicates in list
std::unordered_set<typename T::value_type> s;
for (auto e:l){
s.insert(e);
}
return s.size();
}
ll gcd(ll a, ll b){
ll t;
while(b){
t = b;
b = a%b;
a = t;
}
return a;
}
const string& get_default(const map<string,string>& m, const string& key, const string& dflt){
auto pos = m.find(key);
return (pos != m.end() ? pos->second : dflt);
}
bool is_perfect_square(ll n) {
if (n < 0)
return false;
ll root(round(sqrt(n)));
return n == root * root;
}
bool is_perfect_cube(int n) {
int root(round(cbrt(n)));
return n == root * root * root;
}
/*
* Types of problem inputs
* */
void input_format_1(){ //EOF terminates input
int a,b; vi v;
while(gli(a,b,v)) {
prt(v);
cout << SUM(v);
}
}
void input_format_2(){ //line of 0s terminates input
int a,b,c;
while(gli(a,b,c), (a || b || c)){
//print(a,b,c);
}
}
void input_format_3(){ //integer n and k followed by n lines of input into separate vectors
int n,k,a,b; vi v;
gli(n,k);
L(n){
gli(a,b,v);
}
}
void input_format_4(){ //integer n, integer k, followed by n lines of input into one vector
int n; gli(n);
str s1, s2; //2 strings representing integers, separated by a space
L(n){
gli(s1, s2);
}
}
void read_individual_chars_including_newline(){
char c;
while(scanf("%c",&c) != EOF){
//do stuff
}
}
void USACO_input_format(){
setio("ride1.in","ride1.out");
int a, b;
gli(a,b);
prt(a*b);
}
// how to create a vector of vectors: vvi matrix(rows, vi(columns));
/* INPUT TYPES
Input:
3 7
4 5 14
int n,h;vi a;
gli(n,h); gli(a);
Input:
3
1 1 0
1 1 1
1 0 0
int n; gli(n); vvi v;
L(n){
vi temp;
gli(temp);
v.PB(temp);
}
Input:
1 5 3 2
11221
vi values; gli(values); char c;int sum=0;
LOOPREAD(c,'\n')
sum += values[c-'1'];
}
*/
// MARK: Section name
/*
* End of boilerplate
* */
//release is false by default, must write release = true; to get it to be true.
int main(){
setio("input.txt","output.txt");
ll a, b;
gli(a,b);
prt(a+b*b);
}
| [
"39001793+maximumevilcoverage@users.noreply.github.com"
] | 39001793+maximumevilcoverage@users.noreply.github.com |
8668197e7baee51844f07e042c3c893dc8c02dd0 | e96add576ce570986db9c3f4ad94a00d971a10d9 | /threads/Promises.cpp | 644af32332a2ba5408acc8ea82c92aceb4e7cd8f | [
"MIT"
] | permissive | mgalushka/cpp-start | 8fb543350d6dc39f03245cf4f46c58d5646495c2 | a7af1668291ffd1c1b606310714880dcbefb3ea5 | refs/heads/master | 2021-07-13T12:14:30.151810 | 2020-06-07T08:49:01 | 2020-06-07T08:49:01 | 43,199,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 556 | cpp | #include <chrono>
#include <future>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
std::promise<int32_t> prom;
void first() {
std::cout << "Thread 1" << std::endl;
prom.set_value(700);
}
void second() {
std::cout << "Thread 2" << std::endl;
auto fut = prom.get_future();
std::cout << "Promise value: " << fut.get() << std::endl;
}
int main() {
using namespace std::chrono_literals;
std::thread t1(second);
std::this_thread::sleep_for(300ms);
std::thread t2(first);
t1.join();
t2.join();
return 0;
}
| [
"mgalushka@fb.com"
] | mgalushka@fb.com |
3090f75f81a38ff51e7988a87cf43cceb0424f35 | a497075296638f3e79210adceed23b0a91e7887f | /src/TimeStamp.hpp | f7769d1acfd9266369986fafbfb6ceeb26bebe8d | [] | no_license | alexismailov2/patchmatch | 8b7712fbe90ea7c62a3af55b4d52452610a16ff3 | a01b9ab13466a14c0501367238107db32f3fef1e | refs/heads/master | 2022-12-30T11:51:01.683348 | 2020-07-17T12:17:46 | 2020-07-17T12:17:46 | 275,668,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | hpp | #pragma once
#include <functional>
#include <chrono>
/**
* Util for time measurement based on RAII principe
*/
template<typename Units>
class TimeMeasuring
{
public:
using TimePoint = std::chrono::time_point<std::chrono::steady_clock>;
using OnFinishedCallback = std::function<void(int64_t)>;
public:
TimeMeasuring(OnFinishedCallback&& onFinished) noexcept
: _onFinished{std::move(onFinished)}
, _startTime{std::chrono::steady_clock::now()}
{
}
~TimeMeasuring()
{
using namespace ::std::chrono;
_onFinished(duration_cast<Units>(steady_clock::now() - _startTime).count());
}
private:
OnFinishedCallback _onFinished;
TimePoint _startTime;
};
#define TAKEN_TIME_NS() auto _ = TimeMeasuring<::std::chrono::nanoseconds>([](uint64_t takenTime){ std::cout << __FILE__ << ":" << __LINE__ << ", taken: " << takenTime << "ns" << std::endl; })
#define TAKEN_TIME_US() auto _ = TimeMeasuring<::std::chrono::microseconds>([](uint64_t takenTime){ std::cout << __FILE__ << ":" << __LINE__ << ", taken: " << takenTime << "us" << std::endl; })
#define TAKEN_TIME_MS() auto _ = TimeMeasuring<::std::chrono::milliseconds>([](uint64_t takenTime){ std::cout << __FILE__ << ":" << __LINE__ << ", taken: " << takenTime << "ms" << std::endl; })
| [
"alexanderismailov@MacBook-Pro-Alexander.local"
] | alexanderismailov@MacBook-Pro-Alexander.local |
083174a612ee08c0eb06c83815d162439f88c9d3 | cb5d1e50b7fb823b8c00b78009d0afb52728cbf0 | /check whether the primitive values crossing the limits or not.cpp | 06c1c678749958239c53fc0ba395a5fe169b8658 | [] | no_license | 9990vk/ideal-happiness | 05db0f7edb29514e5c2d9459247313cf57957895 | b603be021a58f356c04940118ecdd03131a8a570 | refs/heads/main | 2023-04-02T23:09:49.376196 | 2021-04-18T04:32:14 | 2021-04-18T04:32:14 | 345,660,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 855 | cpp | #include <iostream>
using namespace std;
int main()
{
char gender ='F' ;
bool married =1 ;
unsigned short numberofsons = 2 ;
short yearofherappointment = 2009 ;
unsigned int salary = 1500000 ;
double height = 79.48 ;
float gpa = 4.69 ;
long salarydrawn = 12047235 ;
long long balance = 995324987 ;
cout << "The Gender is : " << gender << "\n" ;
cout << "TIs she married? : " << married << "\n";
cout << "Number of sons she has : : " << numberofsons << "\n" ;
cout << "Year of her appointment : : " << yearofherappointment << "\n" ;
cout << "Salary for a year : " << salary << "\n" ;
cout << "Height is : " << height << "\n";
cout << "GPA is : " << gpa << "\n";
cout << "Salary drawn upto : " << salarydrawn << "\n";
cout << "Balance till : " << balance << "\n";
return 0;
} | [
"79957914+9990vk@users.noreply.github.com"
] | 79957914+9990vk@users.noreply.github.com |
3fdf7772ead8274ebfa7d9aea726cd46b0708524 | 194cb1839f41de3e5de30d5ea666c60992d54063 | /GAME1017_Template_W01/WaitBehindCoverState.cpp | 2b914707d9d330354bfb1141c7b2343c80b5af02 | [] | no_license | Delta-Sama/AI-Assignment-3 | faaa84db1fc996d8792a723627c0f7f8e56e161f | fa100988a5d515571583faad2c3015910a239665 | refs/heads/master | 2022-12-03T11:16:33.674513 | 2020-08-17T11:02:55 | 2020-08-17T11:02:55 | 282,143,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | cpp | #include "WaitBehindCoverState.h"
#include "CollisionManager.h"
#include "EnemyManager.h"
WaitBehindCoverState::WaitBehindCoverState(Enemy* enemy) : BehaviorState(enemy)
{
}
WaitBehindCoverState::~WaitBehindCoverState() = default;
void WaitBehindCoverState::Enter()
{
m_frames = WAIT_BEHIND_COVER_TIME;
}
void WaitBehindCoverState::Update()
{
}
void WaitBehindCoverState::Transition()
{
if (m_entity->GetHealth() < m_entity->GetMaxHealth() * 0.25)
{
m_entity->GetAIState()->ChangeState(FLEE);
return;
}
if (--m_frames == 0)
{
m_entity->SetCoveringTime(0);
if (m_entity->GetEnemyType() == MELEETYPE)
m_entity->GetAIState()->ChangeState(MOVETOLOS);
else if (m_entity->GetEnemyType() == RANGETYPE)
m_entity->GetAIState()->ChangeState(MOVETORANGE);
return;
}
if (COMA::TunnelLOSCheck(&m_entity->GetCenter(), &ENMA::GetPlayer()->GetCenter(), TUNNEL_ENTITY_WIDTH))
{
m_entity->GetAIState()->ChangeState(MOVETOCOVER);
return;
}
}
void WaitBehindCoverState::Exit()
{
} | [
"Maxim@DESKTOP-ECH05PF"
] | Maxim@DESKTOP-ECH05PF |
6496756ef4b12d43120880cb20af6d8f385220d1 | d6dde4ca75ebe792e2988411ce0e19a8a7488a70 | /src/isobmf/ContainerBoxParser.cpp | 8d7fbec8f9d0939969e2446c88148cef1891507a | [
"MIT"
] | permissive | ianzag/mp4dump | 1a649b6f8f61bd98197b3fb62a0effbe51c1606b | 11a04400b3f59ba1f6c747bc23f5b4724028cf1d | refs/heads/main | 2023-02-21T04:12:04.354315 | 2021-01-17T14:21:29 | 2021-01-17T14:21:29 | 327,919,750 | 1 | 0 | MIT | 2021-01-14T17:45:39 | 2021-01-08T14:06:01 | C++ | UTF-8 | C++ | false | false | 3,463 | cpp |
#include "ContainerBoxParser.h"
#include <iostream>
#include <sstream>
namespace isobmf {
void ContainerBoxParser::startParse()
{
printIndent(std::cout) << "Box type: '" << getName() << "' size: " << std::dec << getSize() << " {" << std::endl;
switchState(State::CompactSize);
}
void ContainerBoxParser::endParse()
{
// Notify child parser we've finished
if (m_childBoxParser) {
m_childBoxParser->endParse();
m_childBoxParser.reset();
}
printIndent(std::cout) << "}" << std::endl;
}
void ContainerBoxParser::parseChar(std::uint8_t ch)
{
switch (m_state) {
case State::CompactSize:
if (m_parser.putChar(ch) == sizeof(CompactSize)) {
m_childBoxSize = m_parser.getAs<CompactSize>();
if (m_childBoxSize == 1) { // Large size is following
switchState(State::ExtendedSize);
} else if (m_childBoxSize == 0) {
switchState(State::BoxType);
m_dataLeft = 0; // Data spans till the end of file
} else if (m_childBoxSize >= sizeof(CompactSize) + sizeof(BoxType)) {
switchState(State::BoxType);
m_dataLeft = m_childBoxSize - sizeof(CompactSize) - sizeof(BoxType);
} else {
std::ostringstream os;
os << "Failed to parse box (Invalid box size " << m_childBoxSize << ")";
throw std::runtime_error(os.str());
}
}
break;
case State::ExtendedSize:
if (m_parser.putChar(ch) == sizeof(ExtendedSize)) {
m_childBoxSize = m_parser.getAs<ExtendedSize>();
if (m_childBoxSize == 0) {
switchState(State::BoxType);
m_dataLeft = 0; // Data spans till the end of file
} else if (m_childBoxSize >= sizeof(CompactSize) + sizeof(ExtendedSize) + sizeof(BoxType)) {
switchState(State::BoxType);
m_dataLeft = m_childBoxSize - sizeof(CompactSize) - sizeof(ExtendedSize) - sizeof(BoxType);
} else {
std::ostringstream os;
os << "Failed to parse box (Invalid box size " << m_childBoxSize << ")";
throw std::runtime_error(os.str());
}
}
break;
case State::BoxType:
if (m_parser.putChar(ch) == sizeof(BoxType)) {
const auto boxType = m_parser.getAs<BoxType>();
m_childBoxParser = m_boxFactory.createParser(boxType, m_childBoxSize, this);
if (!m_childBoxParser) {
m_childBoxParser = m_boxFactory.createUnknownParser(boxType, m_childBoxSize, this);
}
m_childBoxParser->startParse();
if (!m_childBoxSize || m_dataLeft) {
switchState(State::BoxData);
} else { // No data for this child box
m_childBoxParser->endParse();
m_childBoxParser.reset();
switchState(State::CompactSize);
}
}
break;
case State::BoxData:
// Container should pass all data to its children boxes
if (m_childBoxParser) {
m_childBoxParser->parseChar(ch);
}
if (m_childBoxSize && --m_dataLeft == 0) { // No more data for this child box
m_childBoxParser->endParse();
m_childBoxParser.reset();
switchState(State::CompactSize);
}
break;
}
}
} // namespace
| [
"ianzag@gmail.com"
] | ianzag@gmail.com |
e733ce4f93cc9ab92b5af2b0953610b7f9fd8e6c | 9160d5980d55c64c2bbc7933337e5e1f4987abb0 | /base/src/sgpp/base/operation/hash/OperationEvalHessianFundamentalNakSplineNaive.hpp | d283a5e21670d8d8c8df15a95f4cc7b3a8729eb3 | [
"LicenseRef-scancode-generic-exception",
"BSD-3-Clause"
] | permissive | SGpp/SGpp | 55e82ecd95ac98efb8760d6c168b76bc130a4309 | 52f2718e3bbca0208e5e08b3c82ec7c708b5ec06 | refs/heads/master | 2022-08-07T12:43:44.475068 | 2021-10-20T08:50:38 | 2021-10-20T08:50:38 | 123,916,844 | 68 | 44 | NOASSERTION | 2022-06-23T08:28:45 | 2018-03-05T12:33:52 | C++ | UTF-8 | C++ | false | false | 2,868 | hpp | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#ifndef OPERATIONEVALHESSIANFUNDAMENTALNAKSPLINE_HPP
#define OPERATIONEVALHESSIANFUNDAMENTALNAKSPLINE_HPP
#include <sgpp/globaldef.hpp>
#include <sgpp/base/operation/hash/OperationEvalHessian.hpp>
#include <sgpp/base/grid/GridStorage.hpp>
#include <sgpp/base/operation/hash/common/basis/FundamentalNakSplineBasis.hpp>
#include <sgpp/base/datatypes/DataVector.hpp>
#include <sgpp/base/datatypes/DataMatrix.hpp>
#include <vector>
namespace sgpp {
namespace base {
/**
* Operation for evaluating fundamental not-a-knot spline linear combinations,
* their gradients and their Hessians.
*/
class OperationEvalHessianFundamentalNakSplineNaive : public
OperationEvalHessian {
public:
/**
* Constructor.
*
* @param storage storage of the sparse grid
* @param degree fundamental not-a-knot spline degree
*/
OperationEvalHessianFundamentalNakSplineNaive(GridStorage& storage, size_t degree) :
storage(storage),
base(degree),
pointInUnitCube(storage.getDimension()),
innerDerivative(storage.getDimension()) {
}
/**
* Destructor.
*/
~OperationEvalHessianFundamentalNakSplineNaive() override {
}
/**
* @param alpha coefficient vector
* @param point evaluation point
* @param[out] gradient gradient vector of the linear combination
* @param[out] hessian Hessian matrix of the linear combination
* @return value of the linear combination
*/
double evalHessian(const DataVector& alpha,
const DataVector& point,
DataVector& gradient,
DataMatrix& hessian) override;
/**
* @param alpha coefficient matrix (each column is a coefficient vector)
* @param point evaluation point
* @param[out] value values of the linear combination
* @param[out] gradient Jacobian of the linear combination (each row is a gradient vector)
* @param[out] hessian vector of Hessians of the linear combination
*/
void evalHessian(const DataMatrix& alpha,
const DataVector& point,
DataVector& value,
DataMatrix& gradient,
std::vector<DataMatrix>& hessian) override;
protected:
/// storage of the sparse grid
GridStorage& storage;
/// 1D fundamental not-a-knot spline basis
SFundamentalNakSplineBase base;
/// untransformed evaluation point (temporary vector)
DataVector pointInUnitCube;
/// inner derivative (temporary vector)
DataVector innerDerivative;
};
} // namespace base
} // namespace sgpp
#endif /* OPERATIONEVALHESSIANFUNDAMENTALNAKSPLINE_HPP */
| [
"julian.valentin@ipvs.uni-stuttgart.de"
] | julian.valentin@ipvs.uni-stuttgart.de |
a705bae25e0ea45a59599d398b996cd7cd9509de | 4030b3392718e49131b4bcc875026916628f5fc3 | /C++程序设计/作业/week9/编程题3:Set.cpp | ed145b0fa562c96fa74ebdba2e183238fe3c4c26 | [] | no_license | HaoxuZhang/program-learning | d8508e3f2a7bddf9bdf007f5307c1effef6fb350 | df5b17516fd677f60e9afbfff05c4c7dc93f55bc | refs/heads/master | 2021-01-18T18:42:26.956113 | 2018-01-26T08:17:25 | 2018-01-26T08:17:25 | 86,873,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | cpp | #include<iostream>
#include<set>
using namespace std;
int main()
{
int n;
cin>>n;
string cmd[n];
int cmdInt[n];
for(int i=0;i<n;i++){
cin>>cmd[i]>>cmdInt[i];
}
multiset<int> a,b;
multiset<int>::iterator p;
for(int i=0;i<n;i++){
if(cmd[i]=="add"){
a.insert(cmdInt[i]);
b=a;//每当添加一个元素,就将a赋值给b,因为ask的时候需要看的是曾经是否存在一个元素,所以用b来记录所有曾经出现过的元素
cout<<a.count(cmdInt[i])<<endl;
}
if(cmd[i]=="del"){
cout<<a.count(cmdInt[i])<<endl;
p=a.find(cmdInt[i]);
while(p!=a.end()&&*p==cmdInt[i]){//有可能不存在该元素,就要判断迭代器是否指向了尾端,有可能存在多个元素,所以每次迭代器++,并且判断指向的元素是否还是该元素
a.erase(p);
p++;
}
}
if(cmd[i]=="ask"){
int flag;
p=b.find(cmdInt[i]);
if(p!=a.end()) flag=1;
else flag=0;
int num=a.count(cmdInt[i]);
cout<<flag<<" "<<num<<endl;
}
}
return 0;
}
| [
"www.767322078@qq.com"
] | www.767322078@qq.com |
d31ba607b87f59bf92e885c8a01e94c46b3d0c24 | b6c889936bc593fc80a5dca16f8ddd20fe7a4400 | /trashbin/ping_flow.cpp | 3073d836902c1650e6916257d621a6a375a22a8c | [] | no_license | LiWeiJie/hsmmon | d6479b8aa2f5ee7749b7d571ce6ff164b96a2324 | e3cadf3e6e0668b239cb891701d415127f77cd6b | refs/heads/master | 2021-01-22T03:39:19.542934 | 2015-07-15T11:29:43 | 2015-07-15T11:29:43 | 38,911,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,790 | cpp | /**************************************************************
* Copyright (C) 2006-2015 All rights reserved.
* @Version: 1.0
* @Created: 2015-06-05 15:40
* @Author: liweijie – licatweijie@gmail.com
* @Description:
*
* @History:
**************************************************************/
#include "../include/ping_flow.h"
PingFlow::PingFlow(): ObjectFoundation("pingflow")
{
this->error_message = NULL;
}
PingFlow::PingFlow(int pingId, int sendPackage, int receivePackage, \
int lostPackage, int minTime, int maxTime, int averageTime, \
std::string errorMessage, time_t pingTime): ObjectFoundation("pingflow")
{
this->set_ping_id(pingId);
this->set_send_package(sendPackage);
this->set_receive_package(receivePackage);
this->set_lost_package(lostPackage);
this->set_min_time(minTime);
this->set_max_time(maxTime);
this->set_average_time(averageTime);
this->set_error_message(errorMessage);
this->set_ping_time(pingTime);
this->set_vaild();
}
PingFlow::~PingFlow()
{
if ((this-> error_message) != NULL)
delete this->error_message;
}
int PingFlow::get_average_time()
{
return this->average_time;
}
std::string PingFlow::get_error_message()
{
return this->error_message;
}
int PingFlow::get_lost_package()
{
return this->lost_package;
}
int PingFlow::get_max_time()
{
return this->max_time;
}
int PingFlow::get_min_time()
{
return this->min_time;
}
int PingFlow::get_ping_id()
{
return this->ping_id;
}
int PingFlow::get_receive_package()
{
return this->receive_package;
}
int PingFlow::get_send_package()
{
return this->send_package;
}
time_t PingFlow::get_ping_time()
{
return this->ping_time;
}
bool PingFlow::get_alarm_flag()
{
return this->alarm_flag;
}
int PingFlow::set_average_time(int averageTime)
{
this->average_time = averageTime;
return 0;
}
int PingFlow::set_error_message(std::string errorMessage)
{
this->error_message = new char[errorMessage.length()+1];
std::strcpy(this->error_message, errorMessage.c_str());
return 0;
}
int PingFlow::set_lost_package(int lostPackage)
{
this->lost_package = lostPackage;
return 0;
}
int PingFlow::set_max_time(int maxTime)
{
this->max_time = maxTime;
return 0;
}
int PingFlow::set_min_time(int minTime)
{
this->min_time = minTime;
return 0;
}
int PingFlow::set_ping_id(int pingId)
{
this->ping_id = pingId;
return 0;
}
int PingFlow::set_send_package(int sendPackage)
{
this->send_package = sendPackage;
return 0;
}
int PingFlow::set_ping_time(time_t pingTime)
{
if (pingTime==0)
time(&pingTime);
this->ping_time = pingTime;
return 0;
}
int PingFlow::set_receive_package(int receivePackage)
{
this->receive_package = receivePackage;
return 0;
}
int PingFlow::set_alarm_flag(bool alarmFlag)
{
this->alarm_flag = alarmFlag;
return 0;
}
std::string PingFlow::to_sql()
{
char str[500];
sprintf(str, "(`sendPackage`, `receivePackage`, `lostPackage`, `minTime`, `maxTime`, `averageTime`, `errorMessage`, 'pingTime') VALUES ('%d', '%d', '%d', '%d', '%d', '%d', '%s', 'FROM_UNIXTIME(%ld)')", \
this->send_package, this->receive_package, this->lost_package, this->min_time, this->max_time, this->average_time, this->error_message, this->ping_time);
return str;
}
std::string PingFlow::get_field(unsigned int pos)
{
std::string str;
switch (pos) {
case 0: {
str = this->sql_to_string(this->ping_id);
break;
}
case 1: {
str = this->sql_to_string(this->send_package);
break;
}
case 2: {
str = this->sql_to_string(this->receive_package);
break;
}
case 3: {
str = this->sql_to_string(this->lost_package);
break;
}
case 4: {
str = this->sql_to_string(this->min_time);
break;
}
case 5: {
str = this->sql_to_string(this->max_time);
break;
}
case 6: {
str = this->sql_to_string(this->average_time);
break;
}
case 7: {
str = std::string(this->error_message);
break;
}
case 8: {
str = this->sql_time2string(this->ping_time);
break;
}
case 9: {
str = this->sql_to_string(this->get_alarm_flag());
break;
}
default: {
break;
}
}
return str;
}
bool PingFlow::set_field(std::string str, unsigned int pos)
{
switch (pos ) {
case 0: {
int pingId = std::stoi(str, nullptr);
this->set_ping_id(pingId);
break;
}
case 1: {
this->set_send_package(std::stoi(str, nullptr));
break;
}
case 2: {
this->set_receive_package(std::stoi(str, nullptr));
break;
}
case 3: {
this->set_lost_package(std::stoi(str, nullptr));
break;
}
case 4: {
this->set_min_time(std::stoi(str, nullptr));
break;
}
case 5: {
this->set_max_time(std::stoi(str, nullptr));
break;
}
case 6: {
this->set_average_time(std::stoi(str, nullptr));
break;
}
case 7: {
this->set_error_message(str);
break;
}
case 8: {
this->set_ping_time(this->sql_string2time(str));
break;
}
case 9: {
if (!str.empty())
this->set_alarm_flag(stoi(str));
break;
}
default: {
break;
}
}
return true;
}
bool PingFlow::create(DBManager &dbm)
{
char sql[500];
sprintf(sql, "INSERT INTO %s (`sendPackage`, `receivePackage`, `lostPackage`, `minTime`, `maxTime`, `averageTime`, `errorMessage`, 'pingTime') VALUES \
('%d', '%d', '%d', '%d', '%d', '%d', '%s', 'FROM_UNIXTIME(%ld)')", \
this->get_table_name().c_str(), this->send_package, this->receive_package, this->lost_package, this->min_time, this->max_time, this->average_time, this->error_message, this->ping_time);
dbm.sql_execute(sql);
return true;
}
bool PingFlow::update(DBManager &dbm)
{
char sql[500];
sprintf(sql, "UPDATE %s SET `sendPackage`='%d', `receivePackage`='%d', `lostPackage`='%d', `minTime`='%d', `maxTime`='%d', `averageTime`='%d', `errorMessage`='%s', `pingTime`='FROM_UNIXTIME(%ld)'WHERE `pingId`='%d';",\
this->get_table_name().c_str(), this->send_package, this->receive_package, this->lost_package, this->min_time, this->max_time, this->average_time, this->error_message, this->ping_time, this->ping_id);
dbm.sql_execute(sql);
return true;
}
bool PingFlow::erase(DBManager &dbm)
{
char sql[500];
sprintf(sql, "DELETE FROM %s WHERE `pingId`='%d';", this->get_table_name().c_str(), this->get_ping_id());
dbm.sql_execute(sql);
return true;
}
std::vector<ObjectFoundation*> PingFlow::find_all(DBManager &dbm)
{
char sql[500];
sprintf(sql, "SELECT * FROM %s;", this->get_table_name().c_str());
std::cout << sql << std::endl;
dbm.sql_execute(sql);
m_sql_list sql_list = dbm.get_sql_res();
m_sql_object sql_object;
std::vector<ObjectFoundation*> pfl;
if (sql_list.size()==0) {
std::cout << "Object not found!" << std::endl;
} else {
m_sql_list::iterator iter = sql_list.begin();
for (; iter != sql_list.end(); iter++) {
pfl.push_back(this->to_object(*iter));
}
}
return pfl;
}
ObjectFoundation* PingFlow::find_by_id(unsigned int id, DBManager &dbm)
{
char sql[500];
sprintf(sql, "SELECT * FROM %s WHERE `pingId`='%d';", this->get_table_name().c_str(), id);
dbm.sql_execute(sql);
m_sql_list sql_list = dbm.get_sql_res();
m_sql_object sql_object;
if (sql_list.size()==0) {
std::cout << "Object not found!" << std::endl;
return NULL;
} else {
m_sql_list::iterator iter = sql_list.begin();
return to_object(*iter);
}
}
ObjectFoundation* PingFlow::to_object(m_sql_object &sql_object)
{
m_sql_object::iterator iter = sql_object.begin();
PingFlow *pf = new PingFlow();
unsigned int pos = 0;
for ( ; iter != sql_object.end(); iter++) {
pf->set_field(*iter, pos);
pos++;
}
return pf;
}
std::string PingFlow::to_string()
{
std::string str;
for (unsigned int i=0; i<10; i++) {
str += this->get_field(i)+"\t";
}
return str;
}
| [
"licatweijie@gmail.com"
] | licatweijie@gmail.com |
80f9c27e2157b60b6e94be3b3473ec8789a06fc2 | c42ecbc5bb6bc33acc9833b738996e537d092041 | /pothos-serialization/include/Pothos/serialization/impl/preprocessor/slot/detail/def.hpp | 3ec885456de0dfa49be0a8fdd5a1ae1fec89db92 | [
"BSL-1.0"
] | permissive | lrmodesgh/pothos | abd652bc9b880139fa9fb2016b88cb21e0be1f0a | 542c6cd19e1aa2ee1fda47fbc131431ed351ae31 | refs/heads/master | 2020-12-26T02:10:22.037019 | 2015-07-13T08:28:57 | 2015-07-13T08:28:57 | 39,064,513 | 1 | 0 | null | 2015-07-14T08:56:33 | 2015-07-14T08:56:33 | null | UTF-8 | C++ | false | false | 2,944 | hpp | # /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * 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)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# ifndef POTHOS_PREPROCESSOR_SLOT_DETAIL_DEF_HPP
# define POTHOS_PREPROCESSOR_SLOT_DETAIL_DEF_HPP
#
# /* POTHOS_PP_SLOT_OFFSET_x */
#
# define POTHOS_PP_SLOT_OFFSET_10(x) (x) % 1000000000UL
# define POTHOS_PP_SLOT_OFFSET_9(x) POTHOS_PP_SLOT_OFFSET_10(x) % 100000000UL
# define POTHOS_PP_SLOT_OFFSET_8(x) POTHOS_PP_SLOT_OFFSET_9(x) % 10000000UL
# define POTHOS_PP_SLOT_OFFSET_7(x) POTHOS_PP_SLOT_OFFSET_8(x) % 1000000UL
# define POTHOS_PP_SLOT_OFFSET_6(x) POTHOS_PP_SLOT_OFFSET_7(x) % 100000UL
# define POTHOS_PP_SLOT_OFFSET_5(x) POTHOS_PP_SLOT_OFFSET_6(x) % 10000UL
# define POTHOS_PP_SLOT_OFFSET_4(x) POTHOS_PP_SLOT_OFFSET_5(x) % 1000UL
# define POTHOS_PP_SLOT_OFFSET_3(x) POTHOS_PP_SLOT_OFFSET_4(x) % 100UL
# define POTHOS_PP_SLOT_OFFSET_2(x) POTHOS_PP_SLOT_OFFSET_3(x) % 10UL
#
# /* POTHOS_PP_SLOT_CC_x */
#
# define POTHOS_PP_SLOT_CC_2(a, b) POTHOS_PP_SLOT_CC_2_D(a, b)
# define POTHOS_PP_SLOT_CC_3(a, b, c) POTHOS_PP_SLOT_CC_3_D(a, b, c)
# define POTHOS_PP_SLOT_CC_4(a, b, c, d) POTHOS_PP_SLOT_CC_4_D(a, b, c, d)
# define POTHOS_PP_SLOT_CC_5(a, b, c, d, e) POTHOS_PP_SLOT_CC_5_D(a, b, c, d, e)
# define POTHOS_PP_SLOT_CC_6(a, b, c, d, e, f) POTHOS_PP_SLOT_CC_6_D(a, b, c, d, e, f)
# define POTHOS_PP_SLOT_CC_7(a, b, c, d, e, f, g) POTHOS_PP_SLOT_CC_7_D(a, b, c, d, e, f, g)
# define POTHOS_PP_SLOT_CC_8(a, b, c, d, e, f, g, h) POTHOS_PP_SLOT_CC_8_D(a, b, c, d, e, f, g, h)
# define POTHOS_PP_SLOT_CC_9(a, b, c, d, e, f, g, h, i) POTHOS_PP_SLOT_CC_9_D(a, b, c, d, e, f, g, h, i)
# define POTHOS_PP_SLOT_CC_10(a, b, c, d, e, f, g, h, i, j) POTHOS_PP_SLOT_CC_10_D(a, b, c, d, e, f, g, h, i, j)
#
# define POTHOS_PP_SLOT_CC_2_D(a, b) a ## b
# define POTHOS_PP_SLOT_CC_3_D(a, b, c) a ## b ## c
# define POTHOS_PP_SLOT_CC_4_D(a, b, c, d) a ## b ## c ## d
# define POTHOS_PP_SLOT_CC_5_D(a, b, c, d, e) a ## b ## c ## d ## e
# define POTHOS_PP_SLOT_CC_6_D(a, b, c, d, e, f) a ## b ## c ## d ## e ## f
# define POTHOS_PP_SLOT_CC_7_D(a, b, c, d, e, f, g) a ## b ## c ## d ## e ## f ## g
# define POTHOS_PP_SLOT_CC_8_D(a, b, c, d, e, f, g, h) a ## b ## c ## d ## e ## f ## g ## h
# define POTHOS_PP_SLOT_CC_9_D(a, b, c, d, e, f, g, h, i) a ## b ## c ## d ## e ## f ## g ## h ## i
# define POTHOS_PP_SLOT_CC_10_D(a, b, c, d, e, f, g, h, i, j) a ## b ## c ## d ## e ## f ## g ## h ## i ## j
#
# endif
| [
"josh@joshknows.com"
] | josh@joshknows.com |
729002519ac9e012ae4f028d92ce2e6b582cda6f | faddeba77f6ea72b1f02a8e6426b3244b42e7a07 | /headers/animation.h | 88d4346d9a7240230fd16413259d4deeb5de9d5c | [] | no_license | georgreichert/ascendii | e2ee83365d59086c9e8a8d4e6f13d6969afed4ac | b8c60acdb1e08555ce6b4d8dd614bcad77369316 | refs/heads/main | 2023-04-10T00:08:47.033822 | 2021-04-22T23:36:17 | 2021-04-22T23:36:17 | 352,142,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 156 | h | #include "../ascendii.h"
class Animation {
private:
public:
virtual void draw(Screen* screen, int deltaTime, bool flipHorizontal) = 0;
};
| [
"81485014+georgreichert@users.noreply.github.com"
] | 81485014+georgreichert@users.noreply.github.com |
ae20881e92105ad59933e94fbbf3f027d6eef0a9 | 2c62d7c6a65d13a08720fbdc0f3a990920031ccd | /include/zahlen_helpers.hpp | ad50dc5429c71bed49d8522febd12c87cfa0d2bf | [
"MIT"
] | permissive | ferhatgec/zahlen.cpp | b4c15988af3c7528e18362ab992c06446190035e | 58fd8e3f7b10fcb5445a2723d654119a43933431 | refs/heads/master | 2023-05-04T08:34:26.520290 | 2021-05-24T16:47:46 | 2021-05-24T16:47:46 | 370,372,002 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 532 | hpp | //
// MIT License
//
// Copyright (c) 2021 Ferhat Geçdoğan All Rights Reserved.
// Distributed under the terms of the MIT License.
//
//
#ifndef ZAHLEN_CPP_ZAHLEN_HELPERS_HPP
#define ZAHLEN_CPP_ZAHLEN_HELPERS_HPP
#include "zahlen.hpp"
namespace {
template<typename... Args>
void print(Args... args) noexcept {
((std::cout << args), ...);
}
template<typename... Args>
void println(Args... args) noexcept {
((std::cout << args), ...) << '\n';
}
}
#endif // ZAHLEN_CPP_ZAHLEN_HELPERS_HPP
| [
"ferhat2gecdogan_fix_me5@protonmail.com"
] | ferhat2gecdogan_fix_me5@protonmail.com |
1d37d9b26d42ef81e605a31f6da4de4c4d69002b | fd5d94e86859c7427bf224516b213b2a49ab5dc6 | /tess/tesseract/src/ccstruct/rejctmap.cpp | 9b7be3e09b65061e3c8ba0d8dd6e1e346cf0d0a2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | permissive | tonthatnam/japanese_ocr | 26199ac0eddd5c070b1764720bba100dc24ba8e0 | c78ed95d940fd979bbec1f33bca085e9977cafa4 | refs/heads/master | 2023-04-06T04:00:58.224584 | 2021-04-20T16:10:15 | 2021-04-20T16:10:15 | 342,899,733 | 3 | 1 | MIT | 2021-04-20T16:10:15 | 2021-02-27T16:13:30 | C++ | UTF-8 | C++ | false | false | 10,425 | cpp | /**********************************************************************
* File: rejctmap.cpp (Formerly rejmap.c)
* Description: REJ and REJMAP class functions.
* Author: Phil Cheatle
*
* (C) Copyright 1994, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "rejctmap.h"
#include "params.h"
namespace tesseract {
bool REJ::perm_rejected() { //Is char perm reject?
return (flag (R_TESS_FAILURE) ||
flag (R_SMALL_XHT) ||
flag (R_EDGE_CHAR) ||
flag (R_1IL_CONFLICT) ||
flag (R_POSTNN_1IL) ||
flag (R_REJ_CBLOB) ||
flag (R_BAD_REPETITION) || flag (R_MM_REJECT));
}
bool REJ::rej_before_nn_accept() {
return flag (R_POOR_MATCH) ||
flag (R_NOT_TESS_ACCEPTED) ||
flag (R_CONTAINS_BLANKS) || flag (R_BAD_PERMUTER);
}
bool REJ::rej_between_nn_and_mm() {
return flag (R_HYPHEN) ||
flag (R_DUBIOUS) ||
flag (R_NO_ALPHANUMS) || flag (R_MOSTLY_REJ) || flag (R_XHT_FIXUP);
}
bool REJ::rej_between_mm_and_quality_accept() {
return flag (R_BAD_QUALITY);
}
bool REJ::rej_between_quality_and_minimal_rej_accept() {
return flag (R_DOC_REJ) ||
flag (R_BLOCK_REJ) || flag (R_ROW_REJ) || flag (R_UNLV_REJ);
}
bool REJ::rej_before_mm_accept() {
return rej_between_nn_and_mm () ||
(rej_before_nn_accept () &&
!flag (R_NN_ACCEPT) && !flag (R_HYPHEN_ACCEPT));
}
bool REJ::rej_before_quality_accept() {
return rej_between_mm_and_quality_accept () ||
(!flag (R_MM_ACCEPT) && rej_before_mm_accept ());
}
bool REJ::rejected() { //Is char rejected?
if (flag (R_MINIMAL_REJ_ACCEPT))
return false;
else
return (perm_rejected () ||
rej_between_quality_and_minimal_rej_accept () ||
(!flag (R_QUALITY_ACCEPT) && rej_before_quality_accept ()));
}
bool REJ::accept_if_good_quality() { //potential rej?
return (rejected () &&
!perm_rejected () &&
flag (R_BAD_PERMUTER) &&
!flag (R_POOR_MATCH) &&
!flag (R_NOT_TESS_ACCEPTED) &&
!flag (R_CONTAINS_BLANKS) &&
(!rej_between_nn_and_mm () &&
!rej_between_mm_and_quality_accept () &&
!rej_between_quality_and_minimal_rej_accept ()));
}
void REJ::setrej_tess_failure() { //Tess generated blank
set_flag(R_TESS_FAILURE);
}
void REJ::setrej_small_xht() { //Small xht char/wd
set_flag(R_SMALL_XHT);
}
void REJ::setrej_edge_char() { //Close to image edge
set_flag(R_EDGE_CHAR);
}
void REJ::setrej_1Il_conflict() { //Initial reject map
set_flag(R_1IL_CONFLICT);
}
void REJ::setrej_postNN_1Il() { //1Il after NN
set_flag(R_POSTNN_1IL);
}
void REJ::setrej_rej_cblob() { //Insert duff blob
set_flag(R_REJ_CBLOB);
}
void REJ::setrej_mm_reject() { //Matrix matcher
set_flag(R_MM_REJECT);
}
void REJ::setrej_bad_repetition() { //Odd repeated char
set_flag(R_BAD_REPETITION);
}
void REJ::setrej_poor_match() { //Failed Rays heuristic
set_flag(R_POOR_MATCH);
}
void REJ::setrej_not_tess_accepted() {
//TEMP reject_word
set_flag(R_NOT_TESS_ACCEPTED);
}
void REJ::setrej_contains_blanks() {
//TEMP reject_word
set_flag(R_CONTAINS_BLANKS);
}
void REJ::setrej_bad_permuter() { //POTENTIAL reject_word
set_flag(R_BAD_PERMUTER);
}
void REJ::setrej_hyphen() { //PostNN dubious hyphen or .
set_flag(R_HYPHEN);
}
void REJ::setrej_dubious() { //PostNN dubious limit
set_flag(R_DUBIOUS);
}
void REJ::setrej_no_alphanums() { //TEMP reject_word
set_flag(R_NO_ALPHANUMS);
}
void REJ::setrej_mostly_rej() { //TEMP reject_word
set_flag(R_MOSTLY_REJ);
}
void REJ::setrej_xht_fixup() { //xht fixup
set_flag(R_XHT_FIXUP);
}
void REJ::setrej_bad_quality() { //TEMP reject_word
set_flag(R_BAD_QUALITY);
}
void REJ::setrej_doc_rej() { //TEMP reject_word
set_flag(R_DOC_REJ);
}
void REJ::setrej_block_rej() { //TEMP reject_word
set_flag(R_BLOCK_REJ);
}
void REJ::setrej_row_rej() { //TEMP reject_word
set_flag(R_ROW_REJ);
}
void REJ::setrej_unlv_rej() { //TEMP reject_word
set_flag(R_UNLV_REJ);
}
void REJ::setrej_hyphen_accept() { //NN Flipped a char
set_flag(R_HYPHEN_ACCEPT);
}
void REJ::setrej_nn_accept() { //NN Flipped a char
set_flag(R_NN_ACCEPT);
}
void REJ::setrej_mm_accept() { //Matrix matcher
set_flag(R_MM_ACCEPT);
}
void REJ::setrej_quality_accept() { //Quality flip a char
set_flag(R_QUALITY_ACCEPT);
}
void REJ::setrej_minimal_rej_accept() {
//Accept all except blank
set_flag(R_MINIMAL_REJ_ACCEPT);
}
void REJ::full_print(FILE *fp) {
fprintf (fp, "R_TESS_FAILURE: %s\n", flag (R_TESS_FAILURE) ? "T" : "F");
fprintf (fp, "R_SMALL_XHT: %s\n", flag (R_SMALL_XHT) ? "T" : "F");
fprintf (fp, "R_EDGE_CHAR: %s\n", flag (R_EDGE_CHAR) ? "T" : "F");
fprintf (fp, "R_1IL_CONFLICT: %s\n", flag (R_1IL_CONFLICT) ? "T" : "F");
fprintf (fp, "R_POSTNN_1IL: %s\n", flag (R_POSTNN_1IL) ? "T" : "F");
fprintf (fp, "R_REJ_CBLOB: %s\n", flag (R_REJ_CBLOB) ? "T" : "F");
fprintf (fp, "R_MM_REJECT: %s\n", flag (R_MM_REJECT) ? "T" : "F");
fprintf (fp, "R_BAD_REPETITION: %s\n", flag (R_BAD_REPETITION) ? "T" : "F");
fprintf (fp, "R_POOR_MATCH: %s\n", flag (R_POOR_MATCH) ? "T" : "F");
fprintf (fp, "R_NOT_TESS_ACCEPTED: %s\n",
flag (R_NOT_TESS_ACCEPTED) ? "T" : "F");
fprintf (fp, "R_CONTAINS_BLANKS: %s\n",
flag (R_CONTAINS_BLANKS) ? "T" : "F");
fprintf (fp, "R_BAD_PERMUTER: %s\n", flag (R_BAD_PERMUTER) ? "T" : "F");
fprintf (fp, "R_HYPHEN: %s\n", flag (R_HYPHEN) ? "T" : "F");
fprintf (fp, "R_DUBIOUS: %s\n", flag (R_DUBIOUS) ? "T" : "F");
fprintf (fp, "R_NO_ALPHANUMS: %s\n", flag (R_NO_ALPHANUMS) ? "T" : "F");
fprintf (fp, "R_MOSTLY_REJ: %s\n", flag (R_MOSTLY_REJ) ? "T" : "F");
fprintf (fp, "R_XHT_FIXUP: %s\n", flag (R_XHT_FIXUP) ? "T" : "F");
fprintf (fp, "R_BAD_QUALITY: %s\n", flag (R_BAD_QUALITY) ? "T" : "F");
fprintf (fp, "R_DOC_REJ: %s\n", flag (R_DOC_REJ) ? "T" : "F");
fprintf (fp, "R_BLOCK_REJ: %s\n", flag (R_BLOCK_REJ) ? "T" : "F");
fprintf (fp, "R_ROW_REJ: %s\n", flag (R_ROW_REJ) ? "T" : "F");
fprintf (fp, "R_UNLV_REJ: %s\n", flag (R_UNLV_REJ) ? "T" : "F");
fprintf (fp, "R_HYPHEN_ACCEPT: %s\n", flag (R_HYPHEN_ACCEPT) ? "T" : "F");
fprintf (fp, "R_NN_ACCEPT: %s\n", flag (R_NN_ACCEPT) ? "T" : "F");
fprintf (fp, "R_MM_ACCEPT: %s\n", flag (R_MM_ACCEPT) ? "T" : "F");
fprintf (fp, "R_QUALITY_ACCEPT: %s\n", flag (R_QUALITY_ACCEPT) ? "T" : "F");
fprintf (fp, "R_MINIMAL_REJ_ACCEPT: %s\n",
flag (R_MINIMAL_REJ_ACCEPT) ? "T" : "F");
}
REJMAP &REJMAP::operator=(const REJMAP &source) {
initialise(source.len);
for (int i = 0; i < len; i++) {
ptr[i] = source.ptr[i];
}
return *this;
}
void REJMAP::initialise(int16_t length) {
ptr.reset(new REJ[length]);
len = length;
}
int16_t REJMAP::accept_count() { //How many accepted?
int i;
int16_t count = 0;
for (i = 0; i < len; i++) {
if (ptr[i].accepted ())
count++;
}
return count;
}
bool REJMAP::recoverable_rejects() { //Any non perm rejs?
for (int i = 0; i < len; i++) {
if (ptr[i].recoverable ())
return true;
}
return false;
}
bool REJMAP::quality_recoverable_rejects() { //Any potential rejs?
for (int i = 0; i < len; i++) {
if (ptr[i].accept_if_good_quality ())
return true;
}
return false;
}
void REJMAP::remove_pos( //Cut out an element
int16_t pos //element to remove
) {
ASSERT_HOST (pos >= 0);
ASSERT_HOST (pos < len);
ASSERT_HOST (len > 0);
len--;
for (; pos < len; pos++) ptr[pos] = ptr[pos + 1];
}
void REJMAP::print(FILE *fp) {
int i;
char buff[512];
for (i = 0; i < len; i++) {
buff[i] = ptr[i].display_char ();
}
buff[i] = '\0';
fprintf (fp, "\"%s\"", buff);
}
void REJMAP::full_print(FILE *fp) {
int i;
for (i = 0; i < len; i++) {
ptr[i].full_print (fp);
fprintf (fp, "\n");
}
}
void REJMAP::rej_word_small_xht() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
ptr[i].setrej_small_xht ();
}
}
void REJMAP::rej_word_tess_failure() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
ptr[i].setrej_tess_failure ();
}
}
void REJMAP::rej_word_not_tess_accepted() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_not_tess_accepted();
}
}
void REJMAP::rej_word_contains_blanks() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_contains_blanks();
}
}
void REJMAP::rej_word_bad_permuter() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_bad_permuter ();
}
}
void REJMAP::rej_word_xht_fixup() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_xht_fixup();
}
}
void REJMAP::rej_word_no_alphanums() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_no_alphanums();
}
}
void REJMAP::rej_word_mostly_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_mostly_rej();
}
}
void REJMAP::rej_word_bad_quality() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_bad_quality();
}
}
void REJMAP::rej_word_doc_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_doc_rej();
}
}
void REJMAP::rej_word_block_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_block_rej();
}
}
void REJMAP::rej_word_row_rej() { //Reject whole word
int i;
for (i = 0; i < len; i++) {
if (ptr[i].accepted()) ptr[i].setrej_row_rej();
}
}
} // namespace tesseract
| [
"thatnamdn@gmail.com"
] | thatnamdn@gmail.com |
4819d944701d8cfa65360f8662283f19e72645f8 | b173ceac191918fdd0b6b0b7264ceb816409577d | /spec/cpp_stl_11/test_enum_fancy.cpp | 272b3657d3d9e4d107fccedca6d9e38956c829c7 | [] | no_license | tlindner/kaitai_struct_tests | 61db2f957ae39de2f953297adced858bef86f4ad | 92b4eccf88374d089a7854d3d5a4783f13edf39b | refs/heads/master | 2020-05-17T12:20:47.090278 | 2019-04-26T04:10:26 | 2019-04-26T04:10:26 | 181,816,839 | 0 | 0 | null | 2019-04-17T04:26:09 | 2019-04-17T04:26:07 | null | UTF-8 | C++ | false | false | 443 | cpp | #include <boost/test/unit_test.hpp>
#include <enum_fancy.h>
#include <iostream>
#include <fstream>
#include <vector>
BOOST_AUTO_TEST_CASE(test_enum_fancy) {
std::ifstream ifs("src/enum_0.bin", std::ifstream::binary);
kaitai::kstream ks(&ifs);
enum_fancy_t* r = new enum_fancy_t(&ks);
BOOST_CHECK_EQUAL(r->pet_1(), enum_fancy_t::ANIMAL_CAT);
BOOST_CHECK_EQUAL(r->pet_2(), enum_fancy_t::ANIMAL_CHICKEN);
delete r;
}
| [
"greycat@altlinux.org"
] | greycat@altlinux.org |
36244ef1c6efbf1a8f9fbd598feb2661459ea35c | d8ffda1720b43cde37e935606778d8fa894ee78f | /lib_val.h | ef0cc3e70a1b0bfc13bf0564ba8b485b5384de6b | [] | no_license | SamJonHarper/Astronimical-Body-Simulation | 5f4c482e3c8037c3d4c7c69d4364e68cff5da23d | c68ec5337318164656036553f1b3cbf908d668ce | refs/heads/master | 2020-03-15T05:13:53.166882 | 2018-05-06T19:24:21 | 2018-05-06T19:24:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 | h | //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// lib_val.h
// Assignment 2 - 1422827
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#ifndef lib_valH
#define lib_valH
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#include <string>
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// namespace ValidationFunctions
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
namespace ValidationFunctions
{
bool check_long_range(const long x, const long l, const long u);
bool check_char(std::string, const std::string &);
char * StringToChar(std::string path);
std::string CharToString(const char * nm);
std::string CharToString(const char nm);
std::string DoubleToString(double x);
double StringToDouble(const std::string & s);
double StringToDouble(const std::string & s, bool &);
long StringToLong(const std::string & s);
long StringToLong(const std::string & s, bool &);
bool StringToBool(const std::string & s);
bool StringToBool(const std::string & s, bool &);
std::string BoolToString(bool);
bool IsEven(const long x);
bool IsOdd(const long x);
std::string join(const char *, const char *);
}
namespace lv = ValidationFunctions; //alias
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#endif
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// End Of File
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
| [
"samjonharper@yahoo.com"
] | samjonharper@yahoo.com |
49e3ebdab59e5732b4c05a4ad48ac23ac0e02669 | a4db2aaf797b2cd752e8907e41c1a1ed9b1759cd | /GraphucksLib/Brushes/BrushBase.cpp | 884206377e8e187622ccadd3bb6350a86f523b1a | [] | no_license | holance/GraphucksFork | fec5cd66e85b07903087a1d017dc48b33c490127 | b1cc37e9237bf406561263ec4f02dc6a576e4ba3 | refs/heads/master | 2021-05-09T11:14:55.870324 | 2018-01-26T01:12:48 | 2018-01-26T01:12:48 | 118,986,781 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,051 | cpp | #include "pch.h"
#include "pen.h"
#include "BrushBase.h"
#include "GeometryBase.h"
using namespace Graphucks;
using namespace D2D1;
Brush::Brush() : m_Opacity(1.0f),
m_transform(Matrix3x2F::Identity())
{
}
auto Brush::GetTransformToGeometryBounds(const GeometryPtr& /*geometry*/,
const PenPtr& /*pen*/) -> Matrix3x2F
{
return Matrix3x2F::Identity();
}
auto Brush::GetTransformToBounds(const Graphucks::Rectangle& /*rect*/) -> D2D1::Matrix3x2F
{
return Matrix3x2F::Identity();
}
void Brush::Opacity(const float o)
{
m_Opacity = o;
if(IsResourceValid())
{
GetResourceUnsafe<ID2D1Brush>()->SetOpacity(0);
}
}
void Brush::Transform(const Matrix3x2F& transform)
{
m_transform = transform;
if(IsResourceValid())
{
GetResourceUnsafe<ID2D1Brush>()->SetTransform(transform);
}
}
auto Brush::Transform() const -> const Matrix3x2F&
{
return m_transform;
}
auto Brush::Opacity() const -> float
{
return m_Opacity;
}
| [
"lunci.app@gmail.com"
] | lunci.app@gmail.com |
aa1e019d925e1fe6a304057340134bc3c1cd1f85 | 35edd3baf1dccb9a7352ea0ebf1d323717085db6 | /main.cpp | 758a6bd765a139ad818075b3e540e88561ed72af | [] | no_license | NikitaPozharskyi/Visual-interface-for-DB | 9376ca703de456dfb8145e89982f14a97bbbaa1d | a7309e78faa1ffd7ed3f248919476cc16086827c | refs/heads/master | 2022-09-12T12:38:09.625337 | 2020-06-04T10:11:45 | 2020-06-04T10:11:45 | 269,323,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | #include "test.h"
#include "dataselect.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// dialog->show();
Test t;
t.setWindowTitle("Test");
t.resize(600,400);
t.show();
return a.exec();
}
| [
"cactyr@gmail.com"
] | cactyr@gmail.com |
949d851e471cd049ed91b092b4544ead758e9c39 | 61dd75e1a491bfcf630d95814a4f6b6921448a70 | /Projecte/02-Bubble/Sprite.cpp | f57026eef88f25b56095a58e1f326af6a4fe69a8 | [] | no_license | Joselee2908/BabaIsYou-VJ | 453d4969e269536b5e17739117961e70f500f024 | 6a59123bc67a4477ba743b79017d8a265359d280 | refs/heads/main | 2023-06-10T09:10:09.695116 | 2021-07-02T21:59:36 | 2021-07-02T21:59:36 | 382,452,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,472 | cpp | #include <GL/glew.h>
#include <GL/gl.h>
#include <glm/gtc/matrix_transform.hpp>
#include "Sprite.h"
Sprite::~Sprite()
{
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
glDisableVertexArrayAttrib(GL_TEXTURE_2D, posLocation);
glDisableVertexArrayAttrib(GL_TEXTURE_2D, texCoordLocation);
}
Sprite *Sprite::createSprite(const glm::vec2 &quadSize, const glm::vec2 &sizeInSpritesheet, Texture *spritesheet, ShaderProgram *program)
{
Sprite *quad = new Sprite(quadSize, sizeInSpritesheet, spritesheet, program);
return quad;
}
Sprite::Sprite(const glm::vec2 &quadSize, const glm::vec2 &sizeInSpritesheet, Texture *spritesheet, ShaderProgram *program)
{
float vertices[24] = {0.f, 0.f, 0.f, 0.f,
quadSize.x, 0.f, sizeInSpritesheet.x, 0.f,
quadSize.x, quadSize.y, sizeInSpritesheet.x, sizeInSpritesheet.y,
0.f, 0.f, 0.f, 0.f,
quadSize.x, quadSize.y, sizeInSpritesheet.x, sizeInSpritesheet.y,
0.f, quadSize.y, 0.f, sizeInSpritesheet.y};
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(float), vertices, GL_STATIC_DRAW);
posLocation = program->bindVertexAttribute("position", 2, 4*sizeof(float), 0);
texCoordLocation = program->bindVertexAttribute("texCoord", 2, 4*sizeof(float), (void *)(2*sizeof(float)));
texture = spritesheet;
shaderProgram = program;
currentAnimation = -1;
position = glm::vec2(0.f);
}
void Sprite::update(int deltaTime)
{
if(currentAnimation >= 0)
{
timeAnimation += deltaTime;
while(timeAnimation > animations[currentAnimation].millisecsPerKeyframe)
{
timeAnimation -= animations[currentAnimation].millisecsPerKeyframe;
currentKeyframe = (currentKeyframe + 1) % animations[currentAnimation].keyframeDispl.size();
}
texCoordDispl = animations[currentAnimation].keyframeDispl[currentKeyframe];
}
}
void Sprite::render() const
{
glm::mat4 modelview = glm::translate(glm::mat4(1.0f), glm::vec3(position.x, position.y, 0.f));
shaderProgram->setUniformMatrix4f("modelview", modelview);
shaderProgram->setUniform2f("texCoordDispl", texCoordDispl.x, texCoordDispl.y);
glEnable(GL_TEXTURE_2D);
texture->use();
glBindVertexArray(vao);
glEnableVertexAttribArray(posLocation);
glEnableVertexAttribArray(texCoordLocation);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisable(GL_TEXTURE_2D);
}
void Sprite::free()
{
glDeleteBuffers(1, &vbo);
}
void Sprite::setNumberAnimations(int nAnimations)
{
animations.clear();
animations.resize(nAnimations);
}
void Sprite::setAnimationSpeed(int animId, int keyframesPerSec)
{
if(animId < int(animations.size()))
animations[animId].millisecsPerKeyframe = 1000.f / keyframesPerSec;
}
void Sprite::addKeyframe(int animId, const glm::vec2 &displacement)
{
if(animId < int(animations.size()))
animations[animId].keyframeDispl.push_back(displacement);
}
void Sprite::changeAnimation(int animId)
{
if(animId < int(animations.size()))
{
currentAnimation = animId;
currentKeyframe = 0;
timeAnimation = 0.f;
texCoordDispl = animations[animId].keyframeDispl[0];
}
}
int Sprite::animation() const
{
return currentAnimation;
}
void Sprite::setPosition(const glm::vec2 &pos)
{
position = pos;
}
void Sprite::removeAnimationFrames(int animId)
{
if (animId < int(animations.size())) {
while (animations[animId].keyframeDispl.size() > 0)
animations[animId].keyframeDispl.pop_back();
}
}
| [
"jmartincastro99@gmail.com"
] | jmartincastro99@gmail.com |
a81614e7ac27145f2575fc32c456e41f759e78d7 | 5aa64efe8f940600ecbf1b9356957463632ed258 | /main.cpp | 31fcf7a51cd1cabf8c2f1c78f9532fc534f6cf0b | [] | no_license | dyl2333/EECS-448-Lab-06 | f9bd2572505403b21dcb517f7639df8edb0a377a | b3cda334182a6c6a53651443d283b9cdf201b861 | refs/heads/master | 2021-05-07T19:00:33.812841 | 2017-11-06T18:03:25 | 2017-11-06T18:03:25 | 108,881,725 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | cpp | /**
* @author Dylan Vondracek
* @date 11-6-17
* @file main.cpp
* @brief driver for LinkedList demo
*/
#include <iostream>
#include "theTestClass.h"
#include "LinkedListOfInts.h"
int main(int argc, char** argv)
{
//Example of declaring a LinkedListOfInts
LinkedListOfInts testableList;
//You won't do all the tests in main; that's what your Test class will be for
//Example:
//TestSuite myTester;
//myTester.runTests();
theTestClass theClasser(testableList);
theClasser.runTheTests();
//std::cout << "Running...\nAnd we're done.\nGoodbye.\n";
std::cout<<"Goodbye.\n";
return (0);
}
| [
"d608v440@ku.edu"
] | d608v440@ku.edu |
6baf58735102c60e7e229e3d8d474511aa69f371 | d751dbfec5b0042fd2ff8dae02403fa83e6cf09b | /FAULT_TOLERANT_CASSANDRA_KEY_VALUE_STORE_SIMUATION/Member.cpp | 536b109cff2a3a7eb277941c7f6179b3f8cecd8d | [] | no_license | vishnuramvs/DistributedSystems | 2978b865cdc1081048e0af6e771b3218090a61dd | 29f51c0269a644ff705d47d6bebe9fc9461f1e7c | refs/heads/master | 2020-12-14T09:58:07.551255 | 2014-12-27T07:44:33 | 2014-12-27T07:44:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,789 | cpp | /**********************************
* FILE NAME: Member.cpp
*
* DESCRIPTION: Definition of all Member related class
**********************************/
#include "Member.h"
/**
* Constructor
*/
q_elt::q_elt(void *elt, int size): elt(elt), size(size) {}
/**
* Copy constructor
*/
Address::Address(const Address &anotherAddress) {
// strcpy(addr, anotherAddress.addr);
memcpy(&addr, &anotherAddress.addr, sizeof(addr));
}
/**
* Assignment operator overloading
*/
Address& Address::operator =(const Address& anotherAddress) {
// strcpy(addr, anotherAddress.addr);
memcpy(&addr, &anotherAddress.addr, sizeof(addr));
return *this;
}
/**
* Compare two Address objects
*/
bool Address::operator ==(const Address& anotherAddress) {
return memcmp(this->addr, anotherAddress.addr, sizeof(this->addr));
}
/**
* Constructor
*/
MemberListEntry::MemberListEntry(int id, short port, long heartbeat, long timestamp): id(id), port(port), heartbeat(heartbeat), timestamp(timestamp) {}
/**
* Constuctor
*/
MemberListEntry::MemberListEntry(int id, short port): id(id), port(port) {}
/**
* Copy constructor
*/
MemberListEntry::MemberListEntry(const MemberListEntry &anotherMLE) {
this->heartbeat = anotherMLE.heartbeat;
this->id = anotherMLE.id;
this->port = anotherMLE.port;
this->timestamp = anotherMLE.timestamp;
}
/**
* Assignment operator overloading
*/
MemberListEntry& MemberListEntry::operator =(const MemberListEntry &anotherMLE) {
MemberListEntry temp(anotherMLE);
swap(heartbeat, temp.heartbeat);
swap(id, temp.id);
swap(port, temp.port);
swap(timestamp, temp.timestamp);
return *this;
}
/**
* FUNCTION NAME: getid
*
* DESCRIPTION: getter
*/
int MemberListEntry::getid() {
return id;
}
/**
* FUNCTION NAME: getport
*
* DESCRIPTION: getter
*/
short MemberListEntry::getport() {
return port;
}
/**
* FUNCTION NAME: getheartbeat
*
* DESCRIPTION: getter
*/
long MemberListEntry::getheartbeat() {
return heartbeat;
}
/**
* FUNCTION NAME: gettimestamp
*
* DESCRIPTION: getter
*/
long MemberListEntry::gettimestamp() {
return timestamp;
}
/**
* FUNCTION NAME: setid
*
* DESCRIPTION: setter
*/
void MemberListEntry::setid(int id) {
this->id = id;
}
/**
* FUNCTION NAME: setport
*
* DESCRIPTION: setter
*/
void MemberListEntry::setport(short port) {
this->port = port;
}
/**
* FUNCTION NAME: setheartbeat
*
* DESCRIPTION: setter
*/
void MemberListEntry::setheartbeat(long hearbeat) {
this->heartbeat = hearbeat;
}
/**
* FUNCTION NAME: settimestamp
*
* DESCRIPTION: setter
*/
void MemberListEntry::settimestamp(long timestamp) {
this->timestamp = timestamp;
}
/**
* Copy Constructor
*/
Member::Member(const Member &anotherMember) {
this->addr = anotherMember.addr;
this->inited = anotherMember.inited;
this->inGroup = anotherMember.inGroup;
this->bFailed = anotherMember.bFailed;
this->nnb = anotherMember.nnb;
this->heartbeat = anotherMember.heartbeat;
this->pingCounter = anotherMember.pingCounter;
this->timeOutCounter = anotherMember.timeOutCounter;
this->memberList = anotherMember.memberList;
this->myPos = anotherMember.myPos;
this->mp1q = anotherMember.mp1q;
this->mp2q = anotherMember.mp2q;
}
/**
* Assignment operator overloading
*/
Member& Member::operator =(const Member& anotherMember) {
this->addr = anotherMember.addr;
this->inited = anotherMember.inited;
this->inGroup = anotherMember.inGroup;
this->bFailed = anotherMember.bFailed;
this->nnb = anotherMember.nnb;
this->heartbeat = anotherMember.heartbeat;
this->pingCounter = anotherMember.pingCounter;
this->timeOutCounter = anotherMember.timeOutCounter;
this->memberList = anotherMember.memberList;
this->myPos = anotherMember.myPos;
this->mp1q = anotherMember.mp1q;
this->mp2q = anotherMember.mp2q;
return *this;
}
| [
"rshyam.psg@gmail.com"
] | rshyam.psg@gmail.com |
975c5413e3cf821d51f9d595cf51bd2526ba76e4 | a2eca70a9a7f2dbf586adb9251d8ddc3ed453497 | /src/ETL/cpp/_condition.h | 26a4d2d53d953312bf7e761fee9cf87bfe738e9f | [] | no_license | eshikafe/wxSynfig | 03654379bfc6872cd82bfa2bbb928d4fd9f7a38f | 35573f9c125dc645b1320172bce968a4512fa8f4 | refs/heads/master | 2021-06-15T02:30:59.511757 | 2019-11-20T07:26:19 | 2019-11-20T07:26:19 | 51,330,475 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,902 | h | /*! ========================================================================
** Extended Template and Library
** Mutex Abstraction Class Implementation
** $Id$
**
** Copyright (c) 2002 Robert B. Quattlebaum Jr.
**
** This package is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License as
** published by the Free Software Foundation; either version 2 of
** the License, or (at your option) any later version.
**
** This package 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.
**
** === N O T E S ===========================================================
**
** This is an internal header file, included by other ETL headers.
** You should not attempt to use it directly.
**
** ========================================================================= */
/* === S T A R T =========================================================== */
#ifndef __ETL__CONDITION_H_
#define __ETL__CONDITION_H_
/* === H E A D E R S ======================================================= */
/* === M A C R O S ========================================================= */
/* === C L A S S E S & S T R U C T S ======================================= */
_ETL_BEGIN_NAMESPACE
class condition : private mutex
{
bool flag;
public:
condition()
{ flag=false; }
~condition()
{ }
void operator()()
{ flag=true; }
void wait()
{
mutex::lock lock(*this);
while(!flag)Yield();
flag=false;
}
void wait_next()
{
mutex::lock lock(*this);
flag=false;
while(!flag)Yield();
}
};
_ETL_END_NAMESPACE
/* === E X T E R N S ======================================================= */
/* === E N D =============================================================== */
#endif
| [
"eshikafe@gmail.com"
] | eshikafe@gmail.com |
1b9a01d8ad23f215bb34ba0c1a3c8c735b761133 | 17601c03f36271fc5a7796eb86ae75ef8994ba8b | /project/clientserver/src/protocol/ans_packet.h | 19bab082d23ecb778e0b8be9369b57bc0abaeba5 | [] | no_license | marcusmalmberg/eda031 | eeb6a01a0596de66921313b6c78455209d680dbc | 27dc6e1190b44f49c400215e41f9859ff8fcf64a | refs/heads/master | 2018-12-29T00:34:05.651002 | 2012-04-02T19:04:20 | 2012-04-02T19:04:20 | 3,443,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | h | #ifndef ANS_PACKET_H
#define ANS_PACKET_H
#include "base_packet.h"
namespace protocol {
class AnsPacket : public BasePacket {
public:
size_t ans;
size_t err;
};
}
#endif
| [
"dt07fa4@student.lth.se"
] | dt07fa4@student.lth.se |
7216fd5993f94b83c508907bb7d635ee8c138d22 | a8bc94e8aec232a79a7f62f2c4ca9c11abf30984 | /projet_geomatique/main.cpp | 6666e693fbb4e3dc97019bd5c63d7ffa559bcbd9 | [] | no_license | hbadreddine/projet_geomatique | ba1a7bc1f4a57d34d38361a8cd0246ae352b05f3 | aaf8dc10d17e703948279cafea9760d133cb0762 | refs/heads/master | 2021-01-01T16:55:45.759488 | 2014-12-08T13:51:09 | 2014-12-08T13:51:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | cpp | #include "standardCamera.h"
#include "viewer.h"
#include "cameraViewer.h"
#include <QApplication>
#include <QGLViewer/manipulatedCameraFrame.h>
int main(int argc, char** argv)
{
QApplication application(argc,argv);
StandardCamera* sc = new StandardCamera();
Viewer viewer(sc);
viewer.setWindowTitle("standardCamera");
viewer.show();
return application.exec();
}
| [
"gtsi@localhost.localdomain"
] | gtsi@localhost.localdomain |
8a48098880b9b74a882aaba370628fcb5186cb43 | 03e0f7f2a83323d2de1c919061a98a095a248328 | /2-2.cpp | a99360d129c63612b545b832d4fb5c55079b79aa | [] | no_license | OLI9292/cracking_code_interview | 5a4b54a8397048cbd09bbcdde0c2a784f9f9104a | b273fdba5b21156aa8c54f3398080a38f5783901 | refs/heads/master | 2021-01-21T06:52:08.290344 | 2017-05-17T15:00:02 | 2017-05-17T15:00:02 | 91,589,094 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 985 | cpp | /*
Implement algorithm to find the k to last element of a Linked List.
*/
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
class LinkedList {
struct Node {
int x;
Node *next;
Node *prev;
};
Node *head;
public:
LinkedList() : head(NULL) {}
void addValue(int val) {
Node *n = new Node();
n->x = val;
n->next = head;
head = n;
if (head->next) {
head->next->prev = head;
}
};
int fromLast(int val) {
Node *current = head;
while (current->next) {
current = current->next;
}
for (int i=1; i<val; i++) {
current = current->prev;
}
return current->x;
};
};
int main() {
LinkedList list;
list.addValue(5);
list.addValue(10);
list.addValue(20);
list.addValue(20);
list.addValue(7);
list.addValue(9);
list.addValue(12);
list.addValue(7);
std::cout << list.fromLast(5) << std::endl;
return 0;
}
| [
"otplunkett@gmail.com"
] | otplunkett@gmail.com |
926c98503cd9f72e1c889cfcb96a5b8a41ab5636 | 64d589a01865f531abfcac2d3d3cc87eb68a95ec | /iterator.cpp | 660df1f6f77b7af254f59a21be134228877e0be5 | [
"MIT"
] | permissive | zhanghexie/design-patterns | e992284caba6aea91056737414b74a22a3bcb935 | ff8841dd555116f49da00876f0c68865c916a251 | refs/heads/master | 2022-12-18T15:15:29.165334 | 2020-08-29T02:12:04 | 2020-08-29T02:12:04 | 298,712,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,250 | cpp | #include <iostream>
#include <vector>
using namespace std;
// 迭代抽象类。
template < class T >
class Iterator{
public:
Iterator(){}
Iterator(T(&t)[]){}
virtual T* first(){return nullptr;}
virtual T* next(){return nullptr;}
virtual T* current_item(){return nullptr;}
virtual bool is_end(){return false;}
};
// 聚焦抽象类
template < class T >
class Aggreate{
public:
virtual Iterator<T>* create_iterator()=0;
};
template<class T>
class ConcteteAggragate;
// 具体迭代类。
template < class T >
class ConcteteIterator:public Iterator<T>{
private:
int current;
public:
ConcteteAggragate<T> *aggrate;
ConcteteIterator();
ConcteteIterator(ConcteteAggragate<T> *aggrate);
T* first();
T* next();
bool is_end();
T* current_item();
};
// ConcteteAggragate
template < class T >
class ConcteteAggragate:public Aggreate<T>{
public:
vector<T> items = vector<T>();
public:
Iterator<T>* create_iterator();
int count();
T* operator[](int a);
void add(T n);
};
template < class T >
ConcteteIterator<T>::ConcteteIterator(){
this->aggrate=ConcteteAggragate<T>();
}
template < class T >
ConcteteIterator<T>::ConcteteIterator(ConcteteAggragate<T> *aggrate){
this->aggrate=aggrate;
}
template < class T >
T* ConcteteIterator<T>::first(){
current=0;
return this->current_item();
}
template < class T >
T* ConcteteIterator<T>::next(){
current++;
return this->current_item();
}
template < class T >
bool ConcteteIterator<T>::is_end(){
if (current>=aggrate->count()-1){
return true;
}else{
return false;
}
}
template < class T >
T* ConcteteIterator<T>::current_item(){
return (*(this->aggrate))[current];
}
template<class T>
Iterator<T>* ConcteteAggragate<T>::create_iterator(){
return new ConcteteIterator<T>(this);
}
template<class T>
int ConcteteAggragate<T>::count(){
return items.size();
}
template<class T>
T* ConcteteAggragate<T>::operator[](int a){
return &(this->items[a]);
}
template<class T>
void ConcteteAggragate<T>::add(T i){
this->items.push_back(i);
}
int main(){
ConcteteAggragate<int> a;
for (int i=0;i<10;i++){
a.add(i);
}
Iterator<int>* i = a.create_iterator();
cout<<*(i->first())<<endl;
while(!(i->is_end())){
cout<<*(i->next())<<endl;
}
return 0;
}
| [
"1479406235@qq.com"
] | 1479406235@qq.com |
a92204bb89bd728553a6f5ab5b1d192b1c9d8606 | 581d2d5a28c3d4f905ecd752f14f726ed2fa9966 | /Sort/KthNumber.cpp | 8d920fd6493ebd2fc7b8bfe94a53dc451a931037 | [] | no_license | HelloWoori/AlgorithmStudyWithBaekjoon | ba938def4639e6995af6222ed923153dc204dedd | a7354153f87fdb0e74c5486a526dce57c82b3060 | refs/heads/master | 2021-12-17T22:08:56.551710 | 2021-12-13T14:36:06 | 2021-12-13T14:36:06 | 159,617,860 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 624 | cpp | /*
K번째 수
https://www.acmicpc.net/problem/11004
*/
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)
#include <stdio.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int theNumOfNumbers(0), th(0);
scanf("%d %d", &theNumOfNumbers, &th);
th--; //index와 번째를 맞춰주기 위함
vector<int> numbers;
while (theNumOfNumbers-- > 0)
{
int num(0);
scanf("%d", &num);
numbers.push_back(num);
}
nth_element(numbers.begin(), numbers.begin() + th, numbers.end());
printf("%d\n", numbers[th]);
return 0;
} | [
"myahn0607@gmail.com"
] | myahn0607@gmail.com |
9fa46ed80429bd9583ffef1a7f44f3c22d3893df | 686c8866c52f2aba39152e046b6840c8bcdc981a | /basic_algo/two_sum.cpp | 3b562fba720538326218a28049d175e18692a9e7 | [] | no_license | supr/algorithms-old | 7bf940050228270d3b28c1e2b098ee110f1c5284 | c2f06205cdb1cc98e4bfdc9e06293e2c1b149db2 | refs/heads/master | 2021-05-29T13:09:54.353514 | 2015-07-04T22:52:27 | 2015-07-04T22:52:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,067 | cpp | #include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/*
Question: Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
*/
pair<int, int> two_sum(vector<int> &vec, int sum) {
unordered_map<int, int> hs;
for (int i = 0; i < vec.size(); i++) {
hs.insert(make_pair(sum - vec[i], i));
}
for (int i = 0; i < vec.size(); i++) {
auto it = hs.find(vec[i]);
if (it != hs.end()) {
return pair<int, int>(it->second, i);
}
}
return pair<int, int>(-1, -1);
}
int main() {
vector<int> vec = { 2, 7, 11, 15 };
pair<int, int> p = two_sum(vec, 9);
cout << "index 1: " << p.first << ", index 2: " << p.second << endl;
return 0;
}
| [
"Gerald.Stanje@gmail.com"
] | Gerald.Stanje@gmail.com |
8307590db2dd34a90d75b162b77628aa1eec311f | 28a7710ac9453a5a281cb008e5202ba8bf2bc660 | /src/util.cpp | 9ac59346f8b5f5db265975bf35659ff77ac1a309 | [
"MIT"
] | permissive | Neverhoodcoin/Neverhoodcoin-test | 390b5551edba921c17456ee4b060de6af9f9b2f5 | 39182720fed573aac2b69d4f6974a7c30cd79c6d | refs/heads/master | 2016-09-06T18:53:14.254178 | 2014-08-15T18:49:03 | 2014-08-15T18:49:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,956 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "util.h"
#include "sync.h"
#include "strlcpy.h"
#include "version.h"
#include "ui_interface.h"
#include <boost/algorithm/string/join.hpp>
// Work around clang compilation problem in Boost 1.46:
// /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup
// See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options
// http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION
namespace boost {
namespace program_options {
std::string to_internal(const std::string&);
}
}
#include <boost/program_options/detail/config_file.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <stdarg.h>
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4786)
#pragma warning(disable:4804)
#pragma warning(disable:4805)
#pragma warning(disable:4717)
#endif
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
#define _WIN32_IE 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <io.h> /* for _commit */
#include "shlobj.h"
#elif defined(__linux__)
# include <sys/prctl.h>
#endif
#ifndef WIN32
#include <execinfo.h>
#endif
using namespace std;
map<string, string> mapArgs;
map<string, vector<string> > mapMultiArgs;
bool fDebug = false;
bool fDebugNet = false;
bool fDebugSmsg = false;
bool fNoSmsg = false;
bool fPrintToConsole = false;
bool fPrintToDebugger = false;
bool fRequestShutdown = false;
bool fShutdown = false;
bool fDaemon = false;
bool fServer = false;
bool fCommandLine = false;
string strMiscWarning;
bool fTestNet = false;
bool fNoListen = false;
bool fLogTimestamps = false;
CMedianFilter<int64_t> vTimeOffsets(200,0);
bool fReopenDebugLog = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
void locking_callback(int mode, int i, const char* file, int line)
{
if (mode & CRYPTO_LOCK) {
ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
} else {
LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]);
}
}
LockedPageManager LockedPageManager::instance;
// Init
class CInit
{
public:
CInit()
{
// Init OpenSSL library multithreading support
ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*));
for (int i = 0; i < CRYPTO_num_locks(); i++)
ppmutexOpenSSL[i] = new CCriticalSection();
CRYPTO_set_locking_callback(locking_callback);
#ifdef WIN32
// Seed random number generator with screen scrape and other hardware sources
RAND_screen();
#endif
// Seed random number generator with performance counter
RandAddSeed();
}
~CInit()
{
// Shutdown OpenSSL library multithreading support
CRYPTO_set_locking_callback(NULL);
for (int i = 0; i < CRYPTO_num_locks(); i++)
delete ppmutexOpenSSL[i];
OPENSSL_free(ppmutexOpenSSL);
}
}
instance_of_cinit;
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if (GetTime() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = GetTime();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
unsigned char pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if (ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
printf("RandAddSeed() %lu bytes\n", nSize);
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if (nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
RAND_bytes((unsigned char*)&nRand, sizeof(nRand));
while (nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return GetRand(nMax);
}
uint256 GetRandHash()
{
uint256 hash;
RAND_bytes((unsigned char*)&hash, sizeof(hash));
return hash;
}
static FILE* fileout = NULL;
inline int OutputDebugStringF(const char* pszFormat, ...)
{
int ret = 0;
if (fPrintToConsole)
{
// print to console
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
}
else if (!fPrintToDebugger)
{
// print to debug.log
if (!fileout)
{
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
}
if (fileout)
{
static bool fStartedNewLine = true;
// This routine may be called by global destructors during shutdown.
// Since the order of destruction of static/global objects is undefined,
// allocate mutexDebugLog on the heap the first time this routine
// is called to avoid crashes during shutdown.
static boost::mutex* mutexDebugLog = NULL;
if (mutexDebugLog == NULL) mutexDebugLog = new boost::mutex();
boost::mutex::scoped_lock scoped_lock(*mutexDebugLog);
// reopen the log file, if requested
if (fReopenDebugLog) {
fReopenDebugLog = false;
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL)
setbuf(fileout, NULL); // unbuffered
}
// Debug print useful for profiling
if (fLogTimestamps && fStartedNewLine)
fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
if (pszFormat[strlen(pszFormat) - 1] == '\n')
fStartedNewLine = true;
else
fStartedNewLine = false;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
ret = vfprintf(fileout, pszFormat, arg_ptr);
va_end(arg_ptr);
}
}
#ifdef WIN32
if (fPrintToDebugger)
{
static CCriticalSection cs_OutputDebugStringF;
// accumulate and output a line at a time
{
LOCK(cs_OutputDebugStringF);
static std::string buffer;
va_list arg_ptr;
va_start(arg_ptr, pszFormat);
buffer += vstrprintf(pszFormat, arg_ptr);
va_end(arg_ptr);
int line_start = 0, line_end;
while((line_end = buffer.find('\n', line_start)) != -1)
{
OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str());
line_start = line_end + 1;
}
buffer.erase(0, line_start);
}
}
#endif
return ret;
}
string vstrprintf(const char *format, va_list ap)
{
char buffer[50000];
char* p = buffer;
int limit = sizeof(buffer);
int ret;
while (true)
{
va_list arg_ptr;
va_copy(arg_ptr, ap);
#ifdef WIN32
ret = _vsnprintf(p, limit, format, arg_ptr);
#else
ret = vsnprintf(p, limit, format, arg_ptr);
#endif
va_end(arg_ptr);
if (ret >= 0 && ret < limit)
break;
if (p != buffer)
delete[] p;
limit *= 2;
p = new char[limit];
if (p == NULL)
throw std::bad_alloc();
}
string str(p, p+ret);
if (p != buffer)
delete[] p;
return str;
}
string real_strprintf(const char *format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
return str;
}
string real_strprintf(const std::string &format, int dummy, ...)
{
va_list arg_ptr;
va_start(arg_ptr, dummy);
string str = vstrprintf(format.c_str(), arg_ptr);
va_end(arg_ptr);
return str;
}
bool error(const char *format, ...)
{
va_list arg_ptr;
va_start(arg_ptr, format);
std::string str = vstrprintf(format, arg_ptr);
va_end(arg_ptr);
printf("ERROR: %s\n", str.c_str());
return false;
}
void ParseString(const string& str, char c, vector<string>& v)
{
if (str.empty())
return;
string::size_type i1 = 0;
string::size_type i2;
while (true)
{
i2 = str.find(c, i1);
if (i2 == str.npos)
{
v.push_back(str.substr(i1));
return;
}
v.push_back(str.substr(i1, i2-i1));
i1 = i2+1;
}
}
string FormatMoney(int64_t n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
int64_t n_abs = (n > 0 ? n : -n);
int64_t quotient = n_abs/COIN;
int64_t remainder = n_abs%COIN;
string str = strprintf("%"PRId64".%08"PRId64, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i)
++nTrim;
if (nTrim)
str.erase(str.size()-nTrim, nTrim);
if (n < 0)
str.insert((unsigned int)0, 1, '-');
else if (fPlus && n > 0)
str.insert((unsigned int)0, 1, '+');
return str;
}
bool ParseMoney(const string& str, int64_t& nRet)
{
return ParseMoney(str.c_str(), nRet);
}
bool ParseMoney(const char* pszIn, int64_t& nRet)
{
string strWhole;
int64_t nUnits = 0;
const char* p = pszIn;
while (isspace(*p))
p++;
for (; *p; p++)
{
if (*p == '.')
{
p++;
int64_t nMult = CENT*10;
while (isdigit(*p) && (nMult > 0))
{
nUnits += nMult * (*p++ - '0');
nMult /= 10;
}
break;
}
if (isspace(*p))
break;
if (!isdigit(*p))
return false;
strWhole.insert(strWhole.end(), *p);
}
for (; *p; p++)
if (!isspace(*p))
return false;
if (strWhole.size() > 10) // guard against 63 bit overflow
return false;
if (nUnits < 0 || nUnits > COIN)
return false;
int64_t nWhole = atoi64(strWhole);
int64_t nValue = nWhole*COIN + nUnits;
nRet = nValue;
return true;
}
static const signed char phexdigit[256] =
{ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
bool IsHex(const string& str)
{
BOOST_FOREACH(unsigned char c, str)
{
if (phexdigit[c] < 0)
return false;
}
return (str.size() > 0) && (str.size()%2 == 0);
}
vector<unsigned char> ParseHex(const char* psz)
{
// convert hex dump to vector
vector<unsigned char> vch;
while (true)
{
while (isspace(*psz))
psz++;
signed char c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
unsigned char n = (c << 4);
c = phexdigit[(unsigned char)*psz++];
if (c == (signed char)-1)
break;
n |= c;
vch.push_back(n);
}
return vch;
}
vector<unsigned char> ParseHex(const string& str)
{
return ParseHex(str.c_str());
}
static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet)
{
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
if (name.find("-no") == 0)
{
std::string positive("-");
positive.append(name.begin()+3, name.end());
if (mapSettingsRet.count(positive) == 0)
{
bool value = !GetBoolArg(name);
mapSettingsRet[positive] = (value ? "1" : "0");
}
}
}
void ParseParameters(int argc, const char* const argv[])
{
mapArgs.clear();
mapMultiArgs.clear();
for (int i = 1; i < argc; i++)
{
char psz[10000];
strlcpy(psz, argv[i], sizeof(psz));
char* pszValue = (char*)"";
if (strchr(psz, '='))
{
pszValue = strchr(psz, '=');
*pszValue++ = '\0';
}
#ifdef WIN32
_strlwr(psz);
if (psz[0] == '/')
psz[0] = '-';
#endif
if (psz[0] != '-')
break;
mapArgs[psz] = pszValue;
mapMultiArgs[psz].push_back(pszValue);
}
// New 0.6 features:
BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs)
{
string name = entry.first;
// interpret --foo as -foo (as long as both are not set)
if (name.find("--") == 0)
{
std::string singleDash(name.begin()+1, name.end());
if (mapArgs.count(singleDash) == 0)
mapArgs[singleDash] = entry.second;
name = singleDash;
}
// interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set
InterpretNegativeSetting(name, mapArgs);
}
}
std::string GetArg(const std::string& strArg, const std::string& strDefault)
{
if (mapArgs.count(strArg))
return mapArgs[strArg];
return strDefault;
}
int64_t GetArg(const std::string& strArg, int64_t nDefault)
{
if (mapArgs.count(strArg))
return atoi64(mapArgs[strArg]);
return nDefault;
}
bool GetBoolArg(const std::string& strArg, bool fDefault)
{
if (mapArgs.count(strArg))
{
if (mapArgs[strArg].empty())
return true;
return (atoi(mapArgs[strArg]) != 0);
}
return fDefault;
}
bool SoftSetArg(const std::string& strArg, const std::string& strValue)
{
if (mapArgs.count(strArg))
return false;
mapArgs[strArg] = strValue;
return true;
}
bool SoftSetBoolArg(const std::string& strArg, bool fValue)
{
if (fValue)
return SoftSetArg(strArg, std::string("1"));
else
return SoftSetArg(strArg, std::string("0"));
}
string EncodeBase64(const unsigned char* pch, size_t len)
{
static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
string strRet="";
strRet.reserve((len+2)/3*4);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase64[enc >> 2];
left = (enc & 3) << 4;
mode = 1;
break;
case 1: // we have two bits
strRet += pbase64[left | (enc >> 4)];
left = (enc & 15) << 2;
mode = 2;
break;
case 2: // we have four bits
strRet += pbase64[left | (enc >> 6)];
strRet += pbase64[enc & 63];
mode = 0;
break;
}
}
if (mode)
{
strRet += pbase64[left];
strRet += '=';
if (mode == 1)
strRet += '=';
}
return strRet;
}
string EncodeBase64(const string& str)
{
return EncodeBase64((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid)
{
static const int decode64_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve(strlen(p)*3/4);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode64_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 6
left = dec;
mode = 1;
break;
case 1: // we have 6 bits and keep 4
vchRet.push_back((left<<2) | (dec>>4));
left = dec & 15;
mode = 2;
break;
case 2: // we have 4 bits and get 6, we keep 2
vchRet.push_back((left<<4) | (dec>>2));
left = dec & 3;
mode = 3;
break;
case 3: // we have 2 bits and get 6
vchRet.push_back((left<<6) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 4n base64 characters processed: ok
break;
case 1: // 4n+1 base64 character processed: impossible
*pfInvalid = true;
break;
case 2: // 4n+2 base64 characters processed: require '=='
if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1)
*pfInvalid = true;
break;
case 3: // 4n+3 base64 characters processed: require '='
if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase64(const string& str)
{
vector<unsigned char> vchRet = DecodeBase64(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
string EncodeBase32(const unsigned char* pch, size_t len)
{
static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567";
string strRet="";
strRet.reserve((len+4)/5*8);
int mode=0, left=0;
const unsigned char *pchEnd = pch+len;
while (pch<pchEnd)
{
int enc = *(pch++);
switch (mode)
{
case 0: // we have no bits
strRet += pbase32[enc >> 3];
left = (enc & 7) << 2;
mode = 1;
break;
case 1: // we have three bits
strRet += pbase32[left | (enc >> 6)];
strRet += pbase32[(enc >> 1) & 31];
left = (enc & 1) << 4;
mode = 2;
break;
case 2: // we have one bit
strRet += pbase32[left | (enc >> 4)];
left = (enc & 15) << 1;
mode = 3;
break;
case 3: // we have four bits
strRet += pbase32[left | (enc >> 7)];
strRet += pbase32[(enc >> 2) & 31];
left = (enc & 3) << 3;
mode = 4;
break;
case 4: // we have two bits
strRet += pbase32[left | (enc >> 5)];
strRet += pbase32[enc & 31];
mode = 0;
}
}
static const int nPadding[5] = {0, 6, 4, 3, 1};
if (mode)
{
strRet += pbase32[left];
for (int n=0; n<nPadding[mode]; n++)
strRet += '=';
}
return strRet;
}
string EncodeBase32(const string& str)
{
return EncodeBase32((const unsigned char*)str.c_str(), str.size());
}
vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid)
{
static const int decode32_table[256] =
{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
if (pfInvalid)
*pfInvalid = false;
vector<unsigned char> vchRet;
vchRet.reserve((strlen(p))*5/8);
int mode = 0;
int left = 0;
while (1)
{
int dec = decode32_table[(unsigned char)*p];
if (dec == -1) break;
p++;
switch (mode)
{
case 0: // we have no bits and get 5
left = dec;
mode = 1;
break;
case 1: // we have 5 bits and keep 2
vchRet.push_back((left<<3) | (dec>>2));
left = dec & 3;
mode = 2;
break;
case 2: // we have 2 bits and keep 7
left = left << 5 | dec;
mode = 3;
break;
case 3: // we have 7 bits and keep 4
vchRet.push_back((left<<1) | (dec>>4));
left = dec & 15;
mode = 4;
break;
case 4: // we have 4 bits, and keep 1
vchRet.push_back((left<<4) | (dec>>1));
left = dec & 1;
mode = 5;
break;
case 5: // we have 1 bit, and keep 6
left = left << 5 | dec;
mode = 6;
break;
case 6: // we have 6 bits, and keep 3
vchRet.push_back((left<<2) | (dec>>3));
left = dec & 7;
mode = 7;
break;
case 7: // we have 3 bits, and keep 0
vchRet.push_back((left<<5) | dec);
mode = 0;
break;
}
}
if (pfInvalid)
switch (mode)
{
case 0: // 8n base32 characters processed: ok
break;
case 1: // 8n+1 base32 characters processed: impossible
case 3: // +3
case 6: // +6
*pfInvalid = true;
break;
case 2: // 8n+2 base32 characters processed: require '======'
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1)
*pfInvalid = true;
break;
case 4: // 8n+4 base32 characters processed: require '===='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1)
*pfInvalid = true;
break;
case 5: // 8n+5 base32 characters processed: require '==='
if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1)
*pfInvalid = true;
break;
case 7: // 8n+7 base32 characters processed: require '='
if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1)
*pfInvalid = true;
break;
}
return vchRet;
}
string DecodeBase32(const string& str)
{
vector<unsigned char> vchRet = DecodeBase32(str.c_str());
return string((const char*)&vchRet[0], vchRet.size());
}
bool WildcardMatch(const char* psz, const char* mask)
{
while (true)
{
switch (*mask)
{
case '\0':
return (*psz == '\0');
case '*':
return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask));
case '?':
if (*psz == '\0')
return false;
break;
default:
if (*psz != *mask)
return false;
break;
}
psz++;
mask++;
}
}
bool WildcardMatch(const string& str, const string& mask)
{
return WildcardMatch(str.c_str(), mask.c_str());
}
static std::string FormatException(std::exception* pex, const char* pszThread)
{
#ifdef WIN32
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = "Neverhoodcoin";
#endif
if (pex)
return strprintf(
"EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread);
else
return strprintf(
"UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread);
}
void LogException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n%s", message.c_str());
}
void PrintException(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
throw;
}
void LogStackTrace() {
printf("\n\n******* exception encountered *******\n");
if (fileout)
{
#ifndef WIN32
void* pszBuffer[32];
size_t size;
size = backtrace(pszBuffer, 32);
backtrace_symbols_fd(pszBuffer, size, fileno(fileout));
#endif
}
}
void PrintExceptionContinue(std::exception* pex, const char* pszThread)
{
std::string message = FormatException(pex, pszThread);
printf("\n\n************************\n%s\n", message.c_str());
fprintf(stderr, "\n\n************************\n%s\n", message.c_str());
strMiscWarning = message;
}
boost::filesystem::path GetDefaultDataDir()
{
namespace fs = boost::filesystem;
// Windows < Vista: C:\Documents and Settings\Username\Application Data\Neverhoodcoin
// Windows >= Vista: C:\Users\Username\AppData\Roaming\Neverhoodcoin
// Mac: ~/Library/Application Support/Neverhoodcoin
// Unix: ~/.Neverhoodcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / "Neverhoodcoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
if (pszHome == NULL || strlen(pszHome) == 0)
pathRet = fs::path("/");
else
pathRet = fs::path(pszHome);
#ifdef MAC_OSX
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / "Neverhoodcoin";
#else
// Unix
return pathRet / ".Neverhoodcoin";
#endif
#endif
}
const boost::filesystem::path &GetDataDir(bool fNetSpecific)
{
namespace fs = boost::filesystem;
static fs::path pathCached[2];
static CCriticalSection csPathCached;
static bool cachedPath[2] = {false, false};
fs::path &path = pathCached[fNetSpecific];
// This can be called during exceptions by printf, so we cache the
// value so we don't have to do memory allocations after that.
if (cachedPath[fNetSpecific])
return path;
LOCK(csPathCached);
if (mapArgs.count("-datadir")) {
path = fs::system_complete(mapArgs["-datadir"]);
if (!fs::is_directory(path)) {
path = "";
return path;
}
} else {
path = GetDefaultDataDir();
}
if (fNetSpecific && fTestNet)
path /= "testnet";
fs::create_directory(path);
cachedPath[fNetSpecific]=true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", "Neverhoodcoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
void ReadConfigFile(map<string, string>& mapSettingsRet,
map<string, vector<string> >& mapMultiSettingsRet)
{
boost::filesystem::ifstream streamConfig(GetConfigFile());
if (!streamConfig.good())
return; // No bitcoin.conf file is OK
set<string> setOptions;
setOptions.insert("*");
for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it)
{
// Don't overwrite existing settings so command line settings override bitcoin.conf
string strKey = string("-") + it->string_key;
if (mapSettingsRet.count(strKey) == 0)
{
mapSettingsRet[strKey] = it->value[0];
// interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set)
InterpretNegativeSetting(strKey, mapSettingsRet);
}
mapMultiSettingsRet[strKey].push_back(it->value[0]);
}
}
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", "Neverhoodcoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
#ifndef WIN32
void CreatePidFile(const boost::filesystem::path &path, pid_t pid)
{
FILE* file = fopen(path.string().c_str(), "w");
if (file)
{
fprintf(file, "%d\n", pid);
fclose(file);
}
}
#endif
bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest)
{
#ifdef WIN32
return MoveFileExA(src.string().c_str(), dest.string().c_str(),
MOVEFILE_REPLACE_EXISTING);
#else
int rc = std::rename(src.string().c_str(), dest.string().c_str());
return (rc == 0);
#endif /* WIN32 */
}
void FileCommit(FILE *fileout)
{
fflush(fileout); // harmless if redundantly called
#ifdef WIN32
_commit(_fileno(fileout));
#else
fsync(fileno(fileout));
#endif
}
void ShrinkDebugFile()
{
// Scroll debug.log if it's getting too big
boost::filesystem::path pathLog = GetDataDir() / "debug.log";
FILE* file = fopen(pathLog.string().c_str(), "r");
if (file && boost::filesystem::file_size(pathLog) > 10 * 1000000)
{
// Restart the file with some of the end
char pch[200000];
fseek(file, -sizeof(pch), SEEK_END);
int nBytes = fread(pch, 1, sizeof(pch), file);
fclose(file);
file = fopen(pathLog.string().c_str(), "w");
if (file)
{
fwrite(pch, 1, nBytes, file);
fclose(file);
}
}
}
//
// "Never go to sea with two chronometers; take one or three."
// Our three time sources are:
// - System clock
// - Median of other nodes clocks
// - The user (asking the user to fix the system clock if the first two disagree)
//
static int64_t nMockTime = 0; // For unit testing
int64_t GetTime()
{
if (nMockTime) return nMockTime;
return time(NULL);
}
void SetMockTime(int64_t nMockTimeIn)
{
nMockTime = nMockTimeIn;
}
static int64_t nTimeOffset = 0;
int64_t GetTimeOffset()
{
return nTimeOffset;
}
int64_t GetAdjustedTime()
{
return GetTime() + GetTimeOffset();
}
void AddTimeData(const CNetAddr& ip, int64_t nTime)
{
int64_t nOffsetSample = nTime - GetTime();
// Ignore duplicates
static set<CNetAddr> setKnown;
if (!setKnown.insert(ip).second)
return;
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+"PRId64" (%+"PRId64" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64_t nMedian = vTimeOffsets.median();
std::vector<int64_t> vSorted = vTimeOffsets.sorted();
// Only let other nodes change our time by so much
if (abs64(nMedian) < 70 * 60)
{
nTimeOffset = nMedian;
}
else
{
nTimeOffset = 0;
static bool fDone;
if (!fDone)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
BOOST_FOREACH(int64_t nOffset, vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Neverhoodcoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage+" ", string("Neverhoodcoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION);
}
}
}
if (fDebug) {
BOOST_FOREACH(int64_t n, vSorted)
printf("%+"PRId64" ", n);
printf("| ");
}
printf("nTimeOffset = %+"PRId64" (%+"PRId64" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}
string FormatVersion(int nVersion)
{
if (nVersion%100 == 0)
return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100);
else
return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100);
}
string FormatFullVersion()
{
return CLIENT_BUILD;
}
// Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014)
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
ss << "(" << boost::algorithm::join(comments, "; ") << ")";
ss << "/";
return ss.str();
}
#ifdef WIN32
boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate)
{
namespace fs = boost::filesystem;
char pszPath[MAX_PATH] = "";
if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate))
{
return fs::path(pszPath);
}
printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n");
return fs::path("");
}
#endif
void runCommand(std::string strCommand)
{
int nErr = ::system(strCommand.c_str());
if (nErr)
printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr);
}
void RenameThread(const char* name)
{
#if defined(PR_SET_NAME)
// Only the first 15 characters are used (16 - NUL terminator)
::prctl(PR_SET_NAME, name, 0, 0, 0);
#elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__))
// TODO: This is currently disabled because it needs to be verified to work
// on FreeBSD or OpenBSD first. When verified the '0 &&' part can be
// removed.
pthread_set_name_np(pthread_self(), name);
// This is XCode 10.6-and-later; bring back if we drop 10.5 support:
// #elif defined(MAC_OSX)
// pthread_setname_np(name);
#else
// Prevent warnings for unused parameters...
(void)name;
#endif
}
bool NewThread(void(*pfn)(void*), void* parg)
{
try
{
boost::thread(pfn, parg); // thread detaches when out of scope
} catch(boost::thread_resource_error &e) {
printf("Error creating thread: %s\n", e.what());
return false;
}
return true;
}
| [
"jarda@11tv.cz"
] | jarda@11tv.cz |
7bde06ce866e4af496a05343c014bae5a093db3d | 43523509ac3324883943b52c7d3e0e92cc46ef70 | /renderer/platform/scroll/scrollbar_theme.cc | d45f26cf4b0effebac0155f41b42f8dd294e2a48 | [] | no_license | JDenghui/blink | d935ab9a906c9f95c890549b254b4dec80d93765 | 6732fc88d110451aebda75b8822ba5d9b4f9de04 | refs/heads/master | 2020-03-23T15:55:33.238563 | 2018-07-21T05:26:31 | 2018-07-21T05:26:31 | 141,783,126 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,315 | cc | /*
* Copyright (C) 2011 Apple Inc. All Rights Reserved.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/platform/scroll/scrollbar_theme.h"
#include "build/build_config.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_mouse_event.h"
#include "third_party/blink/public/platform/web_point.h"
#include "third_party/blink/public/platform/web_rect.h"
#include "third_party/blink/public/platform/web_scrollbar_behavior.h"
#include "third_party/blink/renderer/platform/graphics/color.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context_state_saver.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_display_item.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_controller.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar_theme_mock.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar_theme_overlay_mock.h"
#include "third_party/blink/renderer/platform/wtf/optional.h"
#if !defined(OS_MACOSX)
#include "third_party/blink/public/platform/web_theme_engine.h"
#endif
namespace blink {
bool ScrollbarTheme::g_mock_scrollbars_enabled_ = false;
static inline bool ShouldPaintScrollbarPart(const IntRect& part_rect,
const CullRect& cull_rect) {
return (!part_rect.IsEmpty()) || cull_rect.IntersectsCullRect(part_rect);
}
bool ScrollbarTheme::Paint(const Scrollbar& scrollbar,
GraphicsContext& graphics_context,
const CullRect& cull_rect) {
// Create the ScrollbarControlPartMask based on the cullRect
ScrollbarControlPartMask scroll_mask = kNoPart;
IntRect back_button_start_paint_rect;
IntRect back_button_end_paint_rect;
IntRect forward_button_start_paint_rect;
IntRect forward_button_end_paint_rect;
if (HasButtons(scrollbar)) {
back_button_start_paint_rect =
BackButtonRect(scrollbar, kBackButtonStartPart, true);
if (ShouldPaintScrollbarPart(back_button_start_paint_rect, cull_rect))
scroll_mask |= kBackButtonStartPart;
back_button_end_paint_rect =
BackButtonRect(scrollbar, kBackButtonEndPart, true);
if (ShouldPaintScrollbarPart(back_button_end_paint_rect, cull_rect))
scroll_mask |= kBackButtonEndPart;
forward_button_start_paint_rect =
ForwardButtonRect(scrollbar, kForwardButtonStartPart, true);
if (ShouldPaintScrollbarPart(forward_button_start_paint_rect, cull_rect))
scroll_mask |= kForwardButtonStartPart;
forward_button_end_paint_rect =
ForwardButtonRect(scrollbar, kForwardButtonEndPart, true);
if (ShouldPaintScrollbarPart(forward_button_end_paint_rect, cull_rect))
scroll_mask |= kForwardButtonEndPart;
}
IntRect start_track_rect;
IntRect thumb_rect;
IntRect end_track_rect;
IntRect track_paint_rect = TrackRect(scrollbar, true);
scroll_mask |= kTrackBGPart;
bool thumb_present = HasThumb(scrollbar);
if (thumb_present) {
IntRect track = TrackRect(scrollbar);
SplitTrack(scrollbar, track, start_track_rect, thumb_rect, end_track_rect);
if (ShouldPaintScrollbarPart(thumb_rect, cull_rect))
scroll_mask |= kThumbPart;
if (ShouldPaintScrollbarPart(start_track_rect, cull_rect))
scroll_mask |= kBackTrackPart;
if (ShouldPaintScrollbarPart(end_track_rect, cull_rect))
scroll_mask |= kForwardTrackPart;
}
// Paint the scrollbar background (only used by custom CSS scrollbars).
PaintScrollbarBackground(graphics_context, scrollbar);
// Paint the back and forward buttons.
if (scroll_mask & kBackButtonStartPart)
PaintButton(graphics_context, scrollbar, back_button_start_paint_rect,
kBackButtonStartPart);
if (scroll_mask & kBackButtonEndPart)
PaintButton(graphics_context, scrollbar, back_button_end_paint_rect,
kBackButtonEndPart);
if (scroll_mask & kForwardButtonStartPart)
PaintButton(graphics_context, scrollbar, forward_button_start_paint_rect,
kForwardButtonStartPart);
if (scroll_mask & kForwardButtonEndPart)
PaintButton(graphics_context, scrollbar, forward_button_end_paint_rect,
kForwardButtonEndPart);
if (scroll_mask & kTrackBGPart)
PaintTrackBackground(graphics_context, scrollbar, track_paint_rect);
if ((scroll_mask & kForwardTrackPart) || (scroll_mask & kBackTrackPart)) {
// Paint the track pieces above and below the thumb.
if (scroll_mask & kBackTrackPart)
PaintTrackPiece(graphics_context, scrollbar, start_track_rect,
kBackTrackPart);
if (scroll_mask & kForwardTrackPart)
PaintTrackPiece(graphics_context, scrollbar, end_track_rect,
kForwardTrackPart);
PaintTickmarks(graphics_context, scrollbar, track_paint_rect);
}
if (scroll_mask & kThumbPart)
PaintThumbWithOpacity(graphics_context, scrollbar, thumb_rect);
return true;
}
ScrollbarPart ScrollbarTheme::HitTest(const ScrollbarThemeClient& scrollbar,
const IntPoint& position_in_root_frame) {
ScrollbarPart result = kNoPart;
if (!scrollbar.Enabled())
return result;
IntPoint test_position =
scrollbar.ConvertFromRootFrame(position_in_root_frame);
test_position.Move(scrollbar.X(), scrollbar.Y());
if (!scrollbar.FrameRect().Contains(test_position))
return kNoPart;
result = kScrollbarBGPart;
IntRect track = TrackRect(scrollbar);
if (track.Contains(test_position)) {
IntRect before_thumb_rect;
IntRect thumb_rect;
IntRect after_thumb_rect;
SplitTrack(scrollbar, track, before_thumb_rect, thumb_rect,
after_thumb_rect);
if (thumb_rect.Contains(test_position))
result = kThumbPart;
else if (before_thumb_rect.Contains(test_position))
result = kBackTrackPart;
else if (after_thumb_rect.Contains(test_position))
result = kForwardTrackPart;
else
result = kTrackBGPart;
} else if (BackButtonRect(scrollbar, kBackButtonStartPart)
.Contains(test_position)) {
result = kBackButtonStartPart;
} else if (BackButtonRect(scrollbar, kBackButtonEndPart)
.Contains(test_position)) {
result = kBackButtonEndPart;
} else if (ForwardButtonRect(scrollbar, kForwardButtonStartPart)
.Contains(test_position)) {
result = kForwardButtonStartPart;
} else if (ForwardButtonRect(scrollbar, kForwardButtonEndPart)
.Contains(test_position)) {
result = kForwardButtonEndPart;
}
return result;
}
void ScrollbarTheme::PaintScrollCorner(
GraphicsContext& context,
const DisplayItemClient& display_item_client,
const IntRect& corner_rect) {
if (corner_rect.IsEmpty())
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(
context, display_item_client, DisplayItem::kScrollbarCorner))
return;
DrawingRecorder recorder(context, display_item_client,
DisplayItem::kScrollbarCorner);
#if defined(OS_MACOSX)
context.FillRect(corner_rect, Color::kWhite);
#else
Platform::Current()->ThemeEngine()->Paint(
context.Canvas(), WebThemeEngine::kPartScrollbarCorner,
WebThemeEngine::kStateNormal, WebRect(corner_rect), nullptr);
#endif
}
bool ScrollbarTheme::ShouldCenterOnThumb(const ScrollbarThemeClient& scrollbar,
const WebMouseEvent& evt) {
return Platform::Current()->ScrollbarBehavior()->ShouldCenterOnThumb(
evt.button, evt.GetModifiers() & WebInputEvent::kShiftKey,
evt.GetModifiers() & WebInputEvent::kAltKey);
}
void ScrollbarTheme::PaintTickmarks(GraphicsContext& context,
const Scrollbar& scrollbar,
const IntRect& rect) {
// Android paints tickmarks in the browser at FindResultBar.java.
#if !defined(OS_ANDROID)
if (scrollbar.Orientation() != kVerticalScrollbar)
return;
if (rect.Height() <= 0 || rect.Width() <= 0)
return;
// Get the tickmarks for the frameview.
Vector<IntRect> tickmarks;
scrollbar.GetTickmarks(tickmarks);
if (!tickmarks.size())
return;
if (DrawingRecorder::UseCachedDrawingIfPossible(
context, scrollbar, DisplayItem::kScrollbarTickmarks))
return;
DrawingRecorder recorder(context, scrollbar,
DisplayItem::kScrollbarTickmarks);
GraphicsContextStateSaver state_saver(context);
context.SetShouldAntialias(false);
for (Vector<IntRect>::const_iterator i = tickmarks.begin();
i != tickmarks.end(); ++i) {
// Calculate how far down (in %) the tick-mark should appear.
const float percent = static_cast<float>(i->Y()) / scrollbar.TotalSize();
// Calculate how far down (in pixels) the tick-mark should appear.
const int y_pos = rect.Y() + (rect.Height() * percent);
FloatRect tick_rect(rect.X(), y_pos, rect.Width(), 3);
context.FillRect(tick_rect, Color(0xCC, 0xAA, 0x00, 0xFF));
FloatRect tick_stroke(rect.X() + TickmarkBorderWidth(), y_pos + 1,
rect.Width() - 2 * TickmarkBorderWidth(), 1);
context.FillRect(tick_stroke, Color(0xFF, 0xDD, 0x00, 0xFF));
}
#endif
}
bool ScrollbarTheme::ShouldSnapBackToDragOrigin(
const ScrollbarThemeClient& scrollbar,
const WebMouseEvent& evt) {
IntPoint mouse_position = scrollbar.ConvertFromRootFrame(
FlooredIntPoint(evt.PositionInRootFrame()));
mouse_position.Move(scrollbar.X(), scrollbar.Y());
return Platform::Current()->ScrollbarBehavior()->ShouldSnapBackToDragOrigin(
mouse_position, TrackRect(scrollbar),
scrollbar.Orientation() == kHorizontalScrollbar);
}
double ScrollbarTheme::OverlayScrollbarFadeOutDelaySeconds() const {
// On Mac, fading is controlled by the painting code in ScrollAnimatorMac.
return 0.0;
}
double ScrollbarTheme::OverlayScrollbarFadeOutDurationSeconds() const {
// On Mac, fading is controlled by the painting code in ScrollAnimatorMac.
return 0.0;
}
int ScrollbarTheme::ThumbPosition(const ScrollbarThemeClient& scrollbar,
float scroll_position) {
if (scrollbar.Enabled()) {
float size = scrollbar.TotalSize() - scrollbar.VisibleSize();
// Avoid doing a floating point divide by zero and return 1 when
// usedTotalSize == visibleSize.
if (!size)
return 0;
float pos = std::max(0.0f, scroll_position) *
(TrackLength(scrollbar) - ThumbLength(scrollbar)) / size;
return (pos < 1 && pos > 0) ? 1 : pos;
}
return 0;
}
int ScrollbarTheme::ThumbLength(const ScrollbarThemeClient& scrollbar) {
if (!scrollbar.Enabled())
return 0;
float overhang = fabsf(scrollbar.ElasticOverscroll());
float proportion = 0.0f;
float total_size = scrollbar.TotalSize();
if (total_size > 0.0f) {
proportion = (scrollbar.VisibleSize() - overhang) / total_size;
}
int track_len = TrackLength(scrollbar);
int length = round(proportion * track_len);
length = std::max(length, MinimumThumbLength(scrollbar));
if (length > track_len)
length = 0; // Once the thumb is below the track length, it just goes away
// (to make more room for the track).
return length;
}
int ScrollbarTheme::TrackPosition(const ScrollbarThemeClient& scrollbar) {
IntRect constrained_track_rect =
ConstrainTrackRectToTrackPieces(scrollbar, TrackRect(scrollbar));
return (scrollbar.Orientation() == kHorizontalScrollbar)
? constrained_track_rect.X() - scrollbar.X()
: constrained_track_rect.Y() - scrollbar.Y();
}
int ScrollbarTheme::TrackLength(const ScrollbarThemeClient& scrollbar) {
IntRect constrained_track_rect =
ConstrainTrackRectToTrackPieces(scrollbar, TrackRect(scrollbar));
return (scrollbar.Orientation() == kHorizontalScrollbar)
? constrained_track_rect.Width()
: constrained_track_rect.Height();
}
IntRect ScrollbarTheme::ThumbRect(const ScrollbarThemeClient& scrollbar) {
if (!HasThumb(scrollbar))
return IntRect();
IntRect track = TrackRect(scrollbar);
IntRect start_track_rect;
IntRect thumb_rect;
IntRect end_track_rect;
SplitTrack(scrollbar, track, start_track_rect, thumb_rect, end_track_rect);
return thumb_rect;
}
int ScrollbarTheme::ThumbThickness(const ScrollbarThemeClient& scrollbar) {
IntRect track = TrackRect(scrollbar);
return scrollbar.Orientation() == kHorizontalScrollbar ? track.Height()
: track.Width();
}
void ScrollbarTheme::SplitTrack(const ScrollbarThemeClient& scrollbar,
const IntRect& unconstrained_track_rect,
IntRect& before_thumb_rect,
IntRect& thumb_rect,
IntRect& after_thumb_rect) {
// This function won't even get called unless we're big enough to have some
// combination of these three rects where at least one of them is non-empty.
IntRect track_rect =
ConstrainTrackRectToTrackPieces(scrollbar, unconstrained_track_rect);
int thumb_pos = ThumbPosition(scrollbar);
if (scrollbar.Orientation() == kHorizontalScrollbar) {
thumb_rect = IntRect(track_rect.X() + thumb_pos, track_rect.Y(),
ThumbLength(scrollbar), scrollbar.Height());
before_thumb_rect =
IntRect(track_rect.X(), track_rect.Y(),
thumb_pos + thumb_rect.Width() / 2, track_rect.Height());
after_thumb_rect = IntRect(
track_rect.X() + before_thumb_rect.Width(), track_rect.Y(),
track_rect.MaxX() - before_thumb_rect.MaxX(), track_rect.Height());
} else {
thumb_rect = IntRect(track_rect.X(), track_rect.Y() + thumb_pos,
scrollbar.Width(), ThumbLength(scrollbar));
before_thumb_rect =
IntRect(track_rect.X(), track_rect.Y(), track_rect.Width(),
thumb_pos + thumb_rect.Height() / 2);
after_thumb_rect = IntRect(
track_rect.X(), track_rect.Y() + before_thumb_rect.Height(),
track_rect.Width(), track_rect.MaxY() - before_thumb_rect.MaxY());
}
}
ScrollbarTheme& ScrollbarTheme::DeprecatedStaticGetTheme() {
if (ScrollbarTheme::MockScrollbarsEnabled()) {
if (RuntimeEnabledFeatures::OverlayScrollbarsEnabled()) {
DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, overlay_mock_theme, ());
return overlay_mock_theme;
}
DEFINE_STATIC_LOCAL(ScrollbarThemeMock, mock_theme, ());
return mock_theme;
}
return NativeTheme();
}
void ScrollbarTheme::SetMockScrollbarsEnabled(bool flag) {
g_mock_scrollbars_enabled_ = flag;
}
bool ScrollbarTheme::MockScrollbarsEnabled() {
return g_mock_scrollbars_enabled_;
}
DisplayItem::Type ScrollbarTheme::ButtonPartToDisplayItemType(
ScrollbarPart part) {
switch (part) {
case kBackButtonStartPart:
return DisplayItem::kScrollbarBackButtonStart;
case kBackButtonEndPart:
return DisplayItem::kScrollbarBackButtonEnd;
case kForwardButtonStartPart:
return DisplayItem::kScrollbarForwardButtonStart;
case kForwardButtonEndPart:
return DisplayItem::kScrollbarForwardButtonEnd;
default:
NOTREACHED();
return DisplayItem::kScrollbarBackButtonStart;
}
}
DisplayItem::Type ScrollbarTheme::TrackPiecePartToDisplayItemType(
ScrollbarPart part) {
switch (part) {
case kBackTrackPart:
return DisplayItem::kScrollbarBackTrack;
case kForwardTrackPart:
return DisplayItem::kScrollbarForwardTrack;
default:
NOTREACHED();
return DisplayItem::kScrollbarBackTrack;
}
}
} // namespace blink
| [
"Denghui_Jia@Dell.com"
] | Denghui_Jia@Dell.com |
9ecd9913ccd1a8275cec12bf4ca07b0d8c32483e | 46d877808efec0032d96db1542873be270edd57d | /src/Library/Mathematics/Objects/Matrix.cpp | 9216d49928e1b4613115ef2a98f1f72ce4ddfb09 | [
"MPL-2.0",
"BSL-1.0",
"Apache-2.0"
] | permissive | cowlicks/library-mathematics | 44c9fa365595173127807155de5e53d22543e804 | f1ff3257bb2da5371a9eacfcec538b2c00871696 | refs/heads/master | 2020-07-29T03:56:53.933981 | 2019-07-18T19:36:42 | 2019-07-18T19:36:42 | 209,660,751 | 0 | 0 | Apache-2.0 | 2019-09-19T22:44:04 | 2019-09-19T22:44:04 | null | UTF-8 | C++ | false | false | 1,282 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library/Mathematics
/// @file Library/Mathematics/Objects/Matrix.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Mathematics/Objects/Matrix.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace library
{
namespace math
{
namespace obj
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | [
"lucas.bremond@gmail.com"
] | lucas.bremond@gmail.com |
322d104fbf8880e7947aad1cd8f109f1b4a257e6 | df2df473079a400f79eee268a44c04feb4dc6be3 | /Template/Forest.cpp | 71a5a69172712c05602a1491224c682327bb96da | [
"Apache-2.0"
] | permissive | ferenc-schultesz/YokosAdventure | 259b158dc10485f3b6ee7772f0467e550e13bfa8 | 951a91e5881134f0fbdf9968cefc350c6bdc16fd | refs/heads/master | 2020-04-12T03:44:09.705308 | 2018-12-18T11:10:34 | 2018-12-18T11:10:34 | 162,275,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,434 | cpp | #include "Forest.h"
Forest::Forest()
{
bossUp = false;
bossDead = false;
gameover = false;
}
Forest::~Forest() {}
void Forest::Initialise(GameWindow* m_gw)
{
// saving the game window pointer
m_GameWindow = m_gw;
// Creates heiight map terrain
m_hterrian.Create("resources\\Textures\\\\ground\\craterHM.bmp", "resources\\Textures\\ground\\ground.jpg", CVector3f(0.0f, 0.5f, 0.0f), 400.0f, 400.0f, 15.5f);
// camera initialised, positin is behind and above the viewpoint, so we arelokkind down to the player
m_Camera.Set(CVector3f(0.0f, 5.2f + (m_hterrian.ReturnGroundHeight(CVector3f(0.0f, 0.0f, 15.0f)) + 4.2f), 0.0f),
CVector3f(0.0f, (m_hterrian.ReturnGroundHeight(CVector3f(0.0f, 0.0f, 15.0f)) + 4.2f) + 1.2f, -15.0f), CVector3f(0, 1, 0), 5.0f);
// send the reference of heightmap to camera, it will be used to adjust the y coordinates at movement
m_Camera.SetHMap(&m_hterrian);
m_Player.Initialise(&m_Camera, &m_audio);
enemies.push_back(new Imp(CVector3f(54.763634f, -0.002947f, -14.522641f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(74.992393f, 3.863554f, -3.509063f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(92.589241f, 7.287065f, -15.126036f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(76.227982f, 7.042196f, -44.546982f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(53.576378f, 9.426873f, -74.247337f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(33.105793f, 11.121402f, -95.293449f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(1.481516f, 12.285595f, -87.472977f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-31.663607f, 11.564658f, -74.360268f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-60.194042f, 8.785086f, 3.423497f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-37.172146f, 9.629413f, 59.372906f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(34.848740f, 5.888272f, 49.718395f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(65.780533f, 1.709114f, -22.656147f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-33.910851f, 4.514909f, 32.749462f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-31.721424f, 13.019138f, 75.029518f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(82.145302f, 11.397840f, -99.602013f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-77.267227f, 10.340671f, -87.245079f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-105.448288f, 11.405280f, 0.891196f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-43.478420f, 10.892039f, -57.037483f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-55.985806f, 6.060709f, 34.306309f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(70.991096f, 3.507840f, 39.764751f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-17.096870f, 6.390635f, -44.799755f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-71.896240f, 13.421321f, 77.455978f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(53.953480f, 14.533895f, -126.235275f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-91.950783f, 10.567770f, -49.586037f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-55.064411f, 10.871058f, -46.752338f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-62.118118f, 10.843854f, -25.096262f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-3.603154f, 7.604105f, 58.375828f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(94.665833f, 7.724977f, 33.131096f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(81.221504f, 4.859634f, 3.106588f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(4.234109f, 4.113138f, -55.939831f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-27.664459f, 6.076497f, -13.109287f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-68.333450f, 9.917548f, 46.716343f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(7.146554f, 1.878059f, 34.559029f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(76.728989f, 11.055488f, -66.825958f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(24.212160f, 9.023816f, -129.142166f), &m_hterrian, &m_audio));
enemies.push_back(new Imp(CVector3f(-43.569302f, 11.501232f, -115.826073f), &m_hterrian, &m_audio));
// Create a class for rendering text
m_text.Create(m_GameWindow->GetHdc(), "Arial", 35);
// Create the skybox
m_skybox.Create("", 0.0f);
// Initialise audio and play background music
m_audio.Initialise();
vegetation.Initialise(5000, &m_hterrian);
pickUpHandler.Initialise(&m_hterrian);
collisionHandler.Initialise(&m_audio, &m_Player, &vegetation, &m_Camera, &m_hterrian, &pickUpHandler, enemies);
hud.Initialise(&m_Player, m_GameWindow);
m_audio.PlayMusicStream();
m_lighting.InitConstantLights(&m_Player, enemies);
bunny.Load("Resources\\Meshes\\static\\Rabbit\\Rabbit.obj");
RandomPickups.push_back(new Random(CVector3f(1, 3, 1)));
}
void Forest::Update(float dt)
{
if (!bossDead)
{
m_lighting.Update();
}
if (!gameover)
{
m_audio.Update();
collisionHandler.Update(dt);
pickUpHandler.Update(dt);
nova.Update(dt);
unsigned int count = 0;
for each (Enemy* e in enemies)
{
if (e->GetState() == DEAD)
{
++count;
}
}
if (count >= 10 && !bossUp)
{
bossUp = true;
boss = new Boss(CVector3f(0.0f, 0.0f, 0.0f), &m_hterrian, &m_audio);
enemies.push_back(boss);
collisionHandler.UpdateEnemiesVector(enemies);
m_lighting.UpdateEnemiesVector(enemies);
m_fx.ActivateFog(0.005, 0.6, 0.6, 0.6);
}
if (boss != NULL)
{
if (boss->GetState() == DEAD)
{
bossDead = true;
}
}
if (m_Player.Health() < 1.0f)
{
gameover = true;
}
}
}
void Forest::Render(float dt)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Calling look will put the viewing matrix onto the modelview matrix stack
m_Camera.Look();
// Get the camera position and view vector
CVector3f vPos = m_Camera.GetPosition();
CVector3f vView = m_Camera.GetViewPoint();
// sets default material
m_material.SetDefaultMaterial();
glDisable(GL_LIGHTING);
m_skybox.Render(vPos.x, vPos.y + 15.0f, vPos.z, 250, 500, 250); // Render the skybox with same ambient light
glEnable(GL_LIGHTING);
m_hterrian.Render();
if (bossDead && (boss->GetModel()->GetAnimation() == BOSS_STAND))
{
CVector3f bossPos = boss->GetPosition();
CVector3f bunnyPos = CVector3f(bossPos.x - 6.0f, bossPos.y + 1.7f, bossPos.z - 0.5f);
glPushMatrix();
glTranslatef(bunnyPos.x, bunnyPos.y, bunnyPos.z);
glRotatef(180.0f, 0, 1, 0);
glScalef(1.4f, 1.4f, 1.4f);
bunny.Render();
glPopMatrix();
m_lighting.SetTargetLight(bunnyPos);
m_lighting.SetPlayerSpot(m_Player.Position());
if ((bunnyPos - m_Player.Position()).Length() < 2.0f)
{
gameover = true;
}
}
vegetation.Render();
// Primitive based mesh with correct texture and normals, not used at the moment
for (unsigned int i = 0; i < RandomPickups.size(); ++i)
{
glPushMatrix();
glTranslatef(RandomPickups[i]->GetPosition().x, RandomPickups[i]->GetPosition().y, RandomPickups[i]->GetPosition().z);
glRotatef(125.0f, 1, 0, 1);
RandomPickups[i]->Render(dt);
glPopMatrix();
}
pickUpHandler.Render(dt);
if (!gameover)
{
for (unsigned int i = 0; i < enemies.size(); ++i)
{
enemies[i]->Render();
}
m_Player.Render();
}
nova.Render();
DrawHUD();
}
void Forest::DrawHUD()
{
glDisable(GL_LIGHTING);
float h = m_GameWindow->SCREEN_HEIGHT;
float w = m_GameWindow->SCREEN_WIDTH;
if (bossDead && gameover)
{
m_text.Render(w/2 - w*0.07f, h/2 , 1, 1, 1, "Game Over");
m_text.Render(w /2 - w*0.12f, h / 2 + 30, 0, 1, 0, "You got the Bunny!");
}
if (!bossDead && gameover)
{
m_text.Render(w / 2 - w*0.07f, h / 2, 1, 1, 1, "Game Over");
m_text.Render(w / 2 - w*0.12f, h / 2 + 30, 1, 0, 0, "You lost the Bunny!");
}
glColor3f(1, 1, 1);
hud.Render();
glEnable(GL_LIGHTING);
}
Camera * Forest::GetCamera()
{
return &m_Camera;
}
CPlayer * Forest::GetPlayer()
{
return &m_Player;
}
vector<Enemy*> Forest::GetEnemies()
{
return enemies;
}
| [
"ferenc.schultesz@gmail.com"
] | ferenc.schultesz@gmail.com |
466acb5807be3c957bce01a17414f431d1794e6e | 928bcf947b6e05fa52075e5e24e47a7f498e5064 | /Facade/Proxy/proxy.cpp | a63cf9655c94bd71775f0f90703e8fea11779b94 | [] | no_license | Annushka34/Patterns_2020 | 8c5824f237e9a12caa06cee2c9e8ae4e98320dc6 | 090e2915f000b242623789e4443f35d2871d99c9 | refs/heads/master | 2022-12-03T21:03:43.136284 | 2020-08-23T09:07:30 | 2020-08-23T09:07:30 | 274,476,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 794 | cpp | #include<iostream>
using namespace std;
class IMathOper
{
public:
virtual int Sum(int x, int y) = 0;
virtual int Divide(int x, int y) = 0;
};
class ConcreteMath :public IMathOper
{
public:
int Sum(int x, int y)
{
return x + y;
}
int Divide(int x, int y)
{
return x / y;
}
};
class Proxy :public IMathOper
{
ConcreteMath*_math;
public:
Proxy()
{
_math = new ConcreteMath();
}
int Sum(int x, int y)
{
if (x > 0 && y > 0)
return _math->Sum(x, y);
else
{
cout << "\nuncorrect operation\n";
return 0;
}
}
int Divide(int x, int y)
{
if (y != 0)
return _math->Divide(x, y);
else
{
cout << "\nuncorrect operation\n";
return 0;
}
}
};
void main()
{
IMathOper*oper = new Proxy();
cout<<oper->Sum(5, 3);
cout<<oper->Divide(5, 0);
} | [
"annsamoluk82@gmail.com"
] | annsamoluk82@gmail.com |
da578d42ed21cb52f44961d8be92060a5aa230fb | 0b508c21b3a219f0c9f05e7457f34517fd31a119 | /Gym/101853H/21912769_AC_0ms_0kB.cpp | c168ea54ca7a6783df725807891a3c4ab44e8f78 | [] | no_license | shiningflash/Online-Judge-Solutions | fa7402d37f8ca3238012d7cff76255dec3e9e2b0 | fc267f87b6c0551d5bdf41f2e160fce58b136ba9 | refs/heads/master | 2021-06-11T20:52:16.777025 | 2021-03-31T12:52:54 | 2021-03-31T12:52:54 | 164,604,423 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int t, n;
for (scanf("%d", &t); t--; ) {
scanf("%d", &n);
cout << (int) sqrt(n / 6) << "\n";
}
}
| [
"shiningflash007@gmail.com"
] | shiningflash007@gmail.com |
cecf6f67bdc74b8c73c37437cfadfc583478a732 | 9dba7651a0f538b2cb4eb261634c9c4dc8f936b4 | /585B/main.cpp | cba4dcf29243a281a81de26c8966060131078389 | [] | no_license | Hoiy/CodeForces | 54a2e898b6de2c1ce37d87768384b9c6683c0088 | 1718a3f7acfb8ba5b57a27ef8a1e1c216ffc5d16 | refs/heads/master | 2016-09-15T06:08:17.599582 | 2016-04-12T14:51:14 | 2016-04-12T14:51:14 | 42,239,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | cpp | #include <iostream>
#include <algorithm>
#include <cassert>
#include <map>
#include <list>
#include <vector>
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
#define fle(var, start, end) for (ll var = start; var <= end; ++var)
#define fl(var, start, end) for (ll var = start; var < end; ++var)
template <class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
int main() {
ll t;
cin >> t;
fl(T, 0, t) {
ll n, k;
cin >> n >> k;
string row[3];
getline(cin, row[0]);
getline(cin, row[0]);
getline(cin, row[1]);
getline(cin, row[2]);
ll time = 0;
bool pos[3] = {false};
fl(i, 0, 3) if (row[i][0] == 's') pos[i] = true;
while (time < n - 1) {
bool lastpos[3] = {false};
fl(i, 0, 3) {
lastpos[i] = pos[i];
pos[i] = false;
}
time += 1;
// moved right
fl(i, 0, 3) {
if (lastpos[i] && row[i][time] == '.') {
pos[i] = true;
}
}
fl(i, 0, 3) { lastpos[i] = pos[i]; }
// move up down
if (lastpos[0] && row[1][time] == '.') {
pos[1] = true;
}
if (lastpos[1] && row[0][time] == '.') {
pos[0] = true;
}
if (lastpos[1] && row[2][time] == '.') {
pos[2] = true;
}
if (lastpos[2] && row[1][time] == '.') {
pos[1] = true;
}
if (time == n - 1) {
break;
}
if (time == n - 2 || time == n - 3) {
continue;
}
// move train
time += 2;
fl(i, 0, 3) {
if (row[i][time] != '.' || row[i][time - 1] != '.') {
pos[i] = false;
}
}
}
cout << (pos[0] || pos[1] || pos[2] ? "YES" : "NO") << endl;
}
return 0;
}
| [
"hoiy927@gmail.com"
] | hoiy927@gmail.com |
8459fe9fd9352223f28722a90e824d5aaa813ebe | 30b4564dcf0a8a0dd8e2180c36cea62d9712242b | /NylonSock/include/NylonSock.hpp | abbfc02180f411f9a6c5ec6247fecc48436a55cb | [
"MIT"
] | permissive | wileyyugioh/NylonSock | d145ad6a965ef3ce2a882f9c5da2b4964328bec6 | 34aa1f34ec316f0cf24c29fbbef07ff155b4e2a5 | refs/heads/master | 2021-01-15T15:42:34.614833 | 2018-07-17T07:46:18 | 2018-07-17T07:46:18 | 48,404,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | hpp | //
// NylonSock.hpp
// NylonSock
//
// Created by Wiley Yu(AN) on 12/21/15.
// Copyright (c) 2015 Wiley Yu. All rights reserved.
//
#ifndef NylonSock_NylonSock_hpp
#define NylonSock_NylonSock_hpp
#include "Socket.h"
#include "Sustainable.h"
#endif
| [
"nein@nein.nein"
] | nein@nein.nein |
d7c8f4afcafbc729bd90d435948ca9d9be6eb2af | d41fdca1bc40c51dd0a98fff976ff48b05201e6a | /GameMgr.cpp | 710c51c5766e423ebab709d9a3643396f188e0ef | [] | no_license | 1997YJ/Happy-Farm-Game | 1e47f1c2e596971b4e0a8eb64ff87fae6d3a7b75 | 7bb6157ca73066cbfbfa754103b6bb4c9efccab0 | refs/heads/master | 2020-11-27T00:57:45.421980 | 2019-12-20T13:00:32 | 2019-12-20T13:00:32 | 229,249,975 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,355 | cpp |
#include "GameMgr.h"
#include "Texture.h"
#include "AnimalFarm.h"
#include "Music.h"
using namespace std;
int GameMgr::COMPUTER_SETTING = 1;
int GameMgr::TIME_SETTING = 2;
#define GAME_WIDTH 1280
#define GAME_HEIGHT 720
#define UNIT_PIXEL 32
GameMgr::GameMgr()
{
// Game Stat
NowStat = INIT;
this->quitGame = false;
frameCounter = 0;
// SDL
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO);
window = SDL_CreateWindow("Farm", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, GAME_WIDTH, GAME_HEIGHT, SDL_WINDOW_SHOWN);
if (window == NULL) {
quitGame = true;
}
rR = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
mainEvent = new SDL_Event();
// image
initLoadIMG();
// construction
aAchievementArray = new AchievementArray(rR);
aFactory = new Factory(rR);
aFeedFactory = new FeedFactory(rR);
aCondition = new Condition(rR, 5000, 0, 1);
aOrder = new Order(rR);
aStore = new Store(rR);
aFarm = new Farm(aFactory);
aFarm->initFarm(rR);
aAnimalFarm = new AnimalFarm(aFactory,aAchievementArray,aCondition);
aAnimalFarm->loadImage(rR);
// music
initLoadMUS();
}
GameMgr::~GameMgr()
{
delete mainEvent;
SDL_DestroyRenderer(rR);
SDL_DestroyWindow(window);
}
// init
void
GameMgr::initLoadIMG()
{
gmTexture = new Texture[8];
gmTexture->LoadImagePNG("menubg", rR);
gmTexture->LoadImagePNG("StartDown", rR);
gmTexture->LoadImagePNG("StartUp", rR);
gmTexture->LoadImagePNG("CONTINUE", rR);
}
void
GameMgr::initLoadMUS()
{
AchievementArray::muAchievementArray = new Music;
Factory::muFactory = new Music;
FeedFactory::muFeedFactory = new Music;
Order::muOrder = new Music;
Store::muStore = new Music;
Farm::muFarm = new Music;
muMenu = new Music;
AnimalFarm::muAnimalFarm = new Music;
//initalize SDL_mixer
Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048);
//load all the music into aMusic vector
Music::aMusic.push(Music::loadMusic("menu.wav"));
Music::aMusic.push(Music::loadMusic("field.wav"));
Music::aMusic.push(Music::loadMusic("factory.wav"));
Music::aMusic.push(Music::loadMusic("feedfactory.wav"));
Music::aMusic.push(Music::loadMusic("shop.wav"));
Music::aMusic.push(Music::loadMusic("animalfarm.wav"));
Music::aMusic.push(Music::loadMusic("order.wav"));
Music::aMusic.push(Music::loadMusic("achievement.wav"));
//load all the SFX into aChunk vector
Music::aSFX.push(Music::loadChunk("buy.wav"));
Music::aSFX.push(Music::loadChunk("chicken.wav"));
Music::aSFX.push(Music::loadChunk("cow.wav"));
Music::aSFX.push(Music::loadChunk("harvest.wav"));
Music::aSFX.push(Music::loadChunk("notreach.wav"));
Music::aSFX.push(Music::loadChunk("pig.wav"));
Music::aSFX.push(Music::loadChunk("productout.wav"));
Music::aSFX.push(Music::loadChunk("reach.wav"));
Music::aSFX.push(Music::loadChunk("reset.wav"));
Music::aSFX.push(Music::loadChunk("seedset.wav"));
Music::aSFX.push(Music::loadChunk("select.wav"));
Music::aSFX.push(Music::loadChunk("status.wav"));
Music::aSFX.push(Music::loadChunk("wrong.wav"));
Music::aSFX.push(Music::loadChunk("zombie.wav"));
Music::aSFX.push(Music::loadChunk("levelup.wav"));
Music::aSFX.push(Music::loadChunk("exp.wav"));
Music::aSFX.push(Music::loadChunk("getproduct.wav"));
Music::aSFX.push(Music::loadChunk("nofeed.wav"));
}
// Loop
void
GameMgr::mainLoop()
{
while (!quitGame && mainEvent->type != SDL_QUIT)
{
frameTime = SDL_GetTicks(); // 2@?i // = second/1000
// for debug test
cout << frameTime / 1000 << endl;
SDL_PollEvent(mainEvent);
SDL_RenderClear(rR);
// CCFG::getMM()->setBackgroundColor(rR);
SDL_RenderFillRect(rR, NULL);
MouseInput();
Update();
Draw();
SDL_RenderPresent(rR);
++frameCounter;
}
}
void
GameMgr::Update()
{
switch (NowStat)
{
case INIT:
{
// init
muMenu->PlayMusic(Music::mMENU);
NowStat = MENU; // MENU;
// menu = new Menu();
//cout << "INIT -> MENU \n";
break;
}
case MENU:
{
//muMenu->PlayMusic(Music::mMENU);
gmTexture->Draw(rR, 0, 0, 720, 1280, 0, 0, 0);
gmTexture->Draw(rR, 0, 0, 100, 300,490,420, 1);//START
// gmTexture->Draw(rR, 0, 0, 100, 430,425,540, 3);//CONTINUE
if((490 < mouseX) && (790 > mouseX) && (420 < mouseY) && (520 > mouseY) )
{
gmTexture->Draw(rR, 0, 0, 100, 300,490,420, 2);//STARTdown
if(mouseLeftTrigger){
muMenu->PlayChunk(Music::cSELECT);
muMenu->StopMusic();
Farm::muFarm->PlayMusic(Music::mFIELD);
NowStat = FARM;
}
}
break;
}
case FARM:
{
int stat = aFarm->update(mouseX, mouseY, mouseLeftTrigger,aAchievementArray,aCondition);
int ctrl=aCondition->updateCondtion(mouseX, mouseY, mouseLeftTrigger);
if(ctrl==1){
stat=1;
}
switch (stat) {
case 0:
NowStat = INIT;
Farm::muFarm->StopMusic();
break;
case 1:
NowStat = MENU;
Farm::muFarm->StopMusic();
muMenu->PlayMusic(Music::mMENU);
break;
case 2:
NowStat = FARM;
break;
case 3:
NowStat = ANIMALFARM;
Farm::muFarm->StopMusic();
AnimalFarm::muAnimalFarm->PlayMusic(Music::mANIMALFARM);
break;
case 4:
NowStat = ORDER;
Farm::muFarm->StopMusic();
Order::muOrder->PlayMusic(Music::mORDER);
break;
case 5:
NowStat = STORE;
Farm::muFarm->StopMusic();
Store::muStore->PlayMusic(Music::mSHOP);
break;
case 6:
NowStat = ACHIEVEMENT;
Farm::muFarm->StopMusic();
AchievementArray::muAchievementArray->PlayMusic(Music::mACHIEVEMENT);
break;
case 7:
NowStat = FEEDFACTORY;
Farm::muFarm->StopMusic();
FeedFactory::muFeedFactory->PlayMusic(Music::mFEEDFACTORY);
break;
default:
NowStat = FACTORY;
Farm::muFarm->StopMusic();
Factory::muFactory->PlayMusic(Music::mFACTORY);
break;
}
break;
}
case ANIMALFARM:
{
aAnimalFarm->updateAnimalFarm(mouseX, mouseY, mouseLeftTrigger);
int ctrl=aCondition->updateCondtion(mouseX, mouseY,
mouseLeftTrigger);
if(ctrl==1){
NowStat = FARM;
AnimalFarm::muAnimalFarm->StopMusic();
Farm::muFarm->PlayMusic(Music::mFIELD);
}
break;
}
case ORDER:
{
aOrder->updateOrder(mouseX, mouseY, mouseLeftTrigger, aCondition,
aFactory->productList,aAchievementArray);
int ctrl=aCondition->updateCondtion(mouseX, mouseY,
mouseLeftTrigger);
if(ctrl==1){
NowStat = FARM;
Order::muOrder->StopMusic();
Farm::muFarm->PlayMusic(Music::mFIELD);
}
break;
}
case STORE:
{
aStore->updateStore(mouseX, mouseY, mouseLeftTrigger,aAchievementArray, aCondition, aFarm,aAnimalFarm);
int ctrl=aCondition->updateCondtion(mouseX, mouseY,
mouseLeftTrigger);
if(ctrl==1){
NowStat = FARM;
Store::muStore->StopMusic();
Farm::muFarm->PlayMusic(Music::mFIELD);
}
break;
}
case ACHIEVEMENT:
{
int temp = aCondition->updateCondtion(mouseX, mouseY, mouseLeftTrigger);
if (temp == 1){
NowStat = FARM;
AchievementArray::muAchievementArray->StopMusic();
Farm::muFarm->PlayMusic(Music::mFIELD);
}
break;
}
case FEEDFACTORY:
{
int exp2 = aFeedFactory->updateFeedFactory(mouseX, mouseY, mouseLeftTrigger,aCondition,aFactory->productList,aAchievementArray);
aCondition->addExp(exp2);
int temp2 = aCondition->updateCondtion(mouseX, mouseY, mouseLeftTrigger);
if (temp2 == 1){
NowStat = FARM;
FeedFactory::muFeedFactory->StopMusic();
Farm::muFarm->PlayMusic(Music::mFIELD);
}
break;
}
case FACTORY:
{
int exp = aFactory->updateFactory(mouseX, mouseY, mouseLeftTrigger,aAchievementArray,aCondition);
aCondition->addExp(exp);
int temp = aCondition->updateCondtion(mouseX, mouseY, mouseLeftTrigger);
if (temp == 1){
NowStat = FARM;
Factory::muFactory->StopMusic();
Farm::muFarm->PlayMusic(Music::mFIELD);
}
break;
}
default:
break;
}
}
void
GameMgr::Draw()
{
// game mode
if (NowStat == INIT)
{
}
else if (NowStat == MENU)
{
}
else if (NowStat == FARM)
{
aFarm->drawFarm(rR);
aCondition->drawCondition(rR);
}
else if (NowStat == ANIMALFARM)
{
aAnimalFarm->drawAnimalFarm(rR);
aCondition->drawCondition(rR);
}
else if (NowStat == ORDER)
{
aOrder->drawOrder(rR, aFactory->productList);
aCondition->drawCondition(rR);
}
else if (NowStat == STORE)
{
aStore->drawStore(rR);
aCondition->drawCondition(rR);
}
else if (NowStat == ACHIEVEMENT)
{
aAchievementArray->drawAchievement(rR);
aCondition->drawCondition(rR);
}
else if (NowStat == FEEDFACTORY)
{
aFeedFactory->drawFeedFactory(rR, aFactory->productList);
aCondition->drawCondition(rR);
}
else if (NowStat == FACTORY)
{
aFactory->drawFactory(rR, false);
aCondition->drawCondition(rR);
}
if (NowStat == FARM)
{
aFarm->drawFarm(rR);
aCondition->drawCondition(rR);
}
}
void
GameMgr::MouseInput()
{
mouseLeftTrigger = false;
mouseRightTrigger = false;
if (mainEvent->type == SDL_MOUSEBUTTONDOWN)
{
if (mainEvent->button.button == SDL_BUTTON_LEFT && !mouseLeftPressed) { mouseLeftPressed = true; cout << "Mouse L\n"; }
else if (mainEvent->button.button == SDL_BUTTON_RIGHT && !mouseRightPressed) { mouseRightPressed = true; cout << "Mouse R\n"; }
}
else if (mainEvent->type == SDL_MOUSEBUTTONUP)
{
if (mainEvent->button.button == SDL_BUTTON_LEFT && mouseLeftPressed) { mouseLeftPressed = false; mouseLeftTrigger = true; }
else if (mainEvent->button.button == SDL_BUTTON_RIGHT && mouseRightPressed) { mouseRightPressed = false; mouseRightTrigger = false; }
}
else if (mainEvent->type == SDL_MOUSEMOTION)
{
int x = mouseX, y = mouseY;
SDL_GetMouseState(&mouseX, &mouseY);
if (x / 100 != mouseX / 100 || y / 100 != mouseY / 100) cout << mouseX << ", " << mouseY << endl;
//if (x != mouseX || y != mouseY) cout << mouseX <<", " << mouseY << endl;
}
}
| [
"yenyenhsu0709@gmail.com"
] | yenyenhsu0709@gmail.com |
7343c0a1f35a2345f60a2312d751e28ac93d0a40 | 5286798f369775a6607636a7c97c87d2a4380967 | /thirdparty/cgal/CGAL-5.1/include/CGAL/Regular_complex_d.h | d244fe11d354fc458492a75f2d0bc8a5b75f6cbb | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"LGPL-3.0-or-later",
"MIT",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"MIT-0",
"LGPL-3.0-only"
] | permissive | MelvinG24/dust3d | d03e9091c1368985302bd69e00f59fa031297037 | c4936fd900a9a48220ebb811dfeaea0effbae3ee | refs/heads/master | 2023-08-24T20:33:06.967388 | 2021-08-10T10:44:24 | 2021-08-10T10:44:24 | 293,045,595 | 0 | 0 | MIT | 2020-09-05T09:38:30 | 2020-09-05T09:38:29 | null | UTF-8 | C++ | false | false | 26,152 | h | // Copyright (c) 1997-2000 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL: https://github.com/CGAL/cgal/blob/v5.1/Convex_hull_d/include/CGAL/Regular_complex_d.h $
// $Id: Regular_complex_d.h d1a323c 2020-03-26T19:24:14+01:00 Sébastien Loriot
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : Michael Seel <seel@mpi-sb.mpg.de>
//---------------------------------------------------------------------
// file generated by notangle from regl_complex.lw
// please debug or modify LEDA web file
// mails and bugs: Michael.Seel@mpi-sb.mpg.de
// based on LEDA architecture by S. Naeher, C. Uhrig
// coding: K. Mehlhorn, M. Seel
// debugging and templatization: M. Seel
//---------------------------------------------------------------------
#ifndef CGAL_REGULAR_COMPLEX_D_H
#define CGAL_REGULAR_COMPLEX_D_H
#include <CGAL/license/Convex_hull_d.h>
#define CGAL_DEPRECATED_HEADER "<CGAL/Regular_complex_d.h>"
#define CGAL_DEPRECATED_MESSAGE_DETAILS \
"The Triangulation package (see https://doc.cgal.org/latest/Triangulation) should be used instead."
#include <CGAL/internal/deprecation_warning.h>
#include <CGAL/basic.h>
#include <CGAL/Iterator_project.h>
#include <CGAL/Compact_container.h>
#include <vector>
#include <list>
#include <cstddef>
#include <CGAL/Kernel_d/debug.h>
#ifdef CGAL_USE_LEDA
#include <LEDA/system/memory.h>
#endif
namespace CGAL {
template <class R> class RC_simplex_d;
template <class R> class RC_vertex_d;
template <class R> class Regular_complex_d;
template <class R> class Convex_hull_d;
#define forall_rc_vertices(x,RC)\
for(x = (RC).vertices_begin(); x != (RC).vertices_end(); ++x)
#define forall_rc_simplices(x,RC)\
for(x = (RC).simplices_begin(); x != (RC).simplices_end(); ++x)
template <class Refs>
class RC_vertex_d
{ typedef RC_vertex_d<Refs> Self;
typedef typename Refs::Point_d Point_d;
typedef typename Refs::Vertex_handle Vertex_handle;
typedef typename Refs::Simplex_handle Simplex_handle;
typedef typename Refs::R R;
friend class Regular_complex_d<R>;
friend class Convex_hull_d<R>;
friend class RC_simplex_d<Refs>;
Simplex_handle s_;
int index_;
Point_d point_;
void set_simplex(Simplex_handle s) { s_=s; }
void set_index(int i) { index_=i; }
void set_point(const Point_d& p) { point_=p; }
public:
RC_vertex_d(Simplex_handle s, int i, const Point_d& p) :
s_(s), index_(i), point_(p) {}
RC_vertex_d(const Point_d& p) : point_(p), pp(nullptr) {}
RC_vertex_d() : s_(), pp(nullptr) {}
// beware that ass_point was initialized here by nil_point
~RC_vertex_d() {}
Simplex_handle simplex() const { return s_; }
int index() const { return index_; }
const Point_d& point() const { return point_; }
void* pp;
void* for_compact_container() const { return pp; }
void for_compact_container(void *p) { pp = p; }
#ifdef CGAL_USE_LEDA
LEDA_MEMORY(RC_vertex_d)
#endif
};
template <class Refs>
class RC_simplex_d
{ typedef RC_simplex_d<Refs> Self;
typedef typename Refs::Point_d Point_d;
typedef typename Refs::Vertex_handle Vertex_handle;
typedef typename Refs::Simplex_handle Simplex_handle;
typedef typename Refs::R R;
friend class Regular_complex_d<R>;
friend class Convex_hull_d<R>;
protected:
std::vector<Vertex_handle> vertices; // array of vertices
std::vector<Simplex_handle> neighbors; // opposite simplices
std::vector<int> opposite_vertices;
// indices of opposite vertices
//------ only for convex hulls ------------------
typedef typename R::Hyperplane_d Hyperplane_d;
Hyperplane_d h_base; // hyperplane supporting base facet
bool visited_; // visited mark when traversing
//------ only for convex hulls ------------------
Vertex_handle vertex(int i) const { return vertices[i]; }
Simplex_handle neighbor(int i) const { return neighbors[i]; }
int opposite_vertex_index(int i) const { return opposite_vertices[i]; }
void set_vertex(int i, Vertex_handle v) { vertices[i] = v; }
void set_neighbor(int i, Simplex_handle s) { neighbors[i]=s; }
void set_opposite_vertex_index(int i, int index)
{ opposite_vertices[i]=index; }
//------ only for convex hulls ------------------
Hyperplane_d hyperplane_of_base_facet() const { return h_base; }
void set_hyperplane_of_base_facet(const Hyperplane_d& h) { h_base = h; }
bool& visited() { return visited_; }
//------ only for convex hulls ------------------
public:
typedef typename std::vector<Vertex_handle>::const_iterator
VIV_iterator;
struct Point_from_VIV_iterator {
typedef Vertex_handle argument_type;
typedef Point_d result_type;
result_type& operator()(argument_type& x) const
{ return x->point(); }
const result_type& operator()(const argument_type& x) const
{ return x->point(); }
};
typedef CGAL::Iterator_project<VIV_iterator,Point_from_VIV_iterator,
const Point_d&, const Point_d*> Point_const_iterator;
Point_const_iterator points_begin() const
{ return Point_const_iterator(vertices.begin()); }
Point_const_iterator points_end() const
{ return Point_const_iterator(vertices.end()); }
void* pp;
void* for_compact_container() const { return pp; }
void for_compact_container(void *p) { pp = p; }
#if 0
struct Point_const_iterator {
typedef Point_const_iterator self;
typedef std::random_access_iterator_tag iterator_category;
typedef const Point_d& value_type;
typedef std::ptrdiff_t difference_type;
typedef const Point_d* pointer;
typedef const Point_d& reference;
typedef typename std::vector<Vertex_handle>::const_iterator
ra_vertex_iterator;
Point_const_iterator() : _it() {}
Point_const_iterator(ra_vertex_iterator it) : _it(it) {}
value_type operator*() const { return (*_it)->point(); }
pointer operator->() const { return &(operator*()); }
self& operator++() { ++_it; return *this; }
self operator++(int) { self tmp = *this; ++_it; return tmp; }
self& operator--() { --_it; return *this; }
self operator--(int) { self tmp = *this; --_it; return tmp; }
self& operator+=(difference_type i) { _it+=i; return *this; }
self& operator-=(difference_type i) { _it-=i; return *this; }
self operator+(difference_type i) const
{ self tmp=*this; tmp+=i; return tmp; }
self operator-(difference_type i) const
{ self tmp=*this; tmp-=i; return tmp; }
difference_type operator-(self x) const { return _it-x._it; }
reference operator[](difference_type i) { return *(*this + i); }
bool operator==(const self& x) const { return _it==x._it; }
bool operator!=(const self& x) const { return ! (*this==x); }
bool operator<(self x) const { (x - *this) > 0; }
private:
ra_vertex_iterator _it;
}; // Point_const_iterator
Point_const_iterator points_begin() const
{ return Point_const_iterator(vertices.begin()); }
Point_const_iterator points_end() const
{ return Point_const_iterator(vertices.end()); }
#endif
RC_simplex_d() : pp(nullptr) {}
RC_simplex_d(int dmax) :
vertices(dmax+1), neighbors(dmax+1), opposite_vertices(dmax+1), pp(nullptr)
{ for (int i = 0; i <= dmax; i++) {
neighbors[i] = Simplex_handle();
vertices[i] = Vertex_handle();
opposite_vertices[i] = -1;
}
visited_ = false;
}
~RC_simplex_d() {}
void print(std::ostream& O=std::cout) const
{
O << "RC_simplex_d {" ;
for(int i=0;i < int(vertices.size());++i) {
Vertex_handle v = vertices[i];
if ( v != Vertex_handle() ) O << v->point();
else O << "(nil)";
}
O << "}";
}
#ifdef CGAL_USE_LEDA
LEDA_MEMORY(RC_simplex_d)
#endif
};
template <typename R>
std::ostream& operator<<(std::ostream& O, const RC_simplex_d<R>& s)
{ s.print(O); return O; }
/*{\Manpage {Regular_complex_d}{R}{Regular Simplicial Complex}{C}}*/
/*{\Mdefinition
An instance |\Mvar| of type |\Mname| is a regular abstract or concrete
simplicial complex. An abstract simplicial complex is a family |\Mvar|
of subsets of some set $V$, called the vertex set of the complex,
which is closed under the subset relation, i.e., if a set $s$ belongs
to the family then all its subsets do. A set $s$ of cardinality $k +
1$ is called a $k$-simplex and $k$ is called its dimension. If $s$ is
a subset of $t$ then $s$ is called a subsimplex or face of $t$. A
vertex $v$ is called incident to a simplex $s$ if $v$ is an element of
$s$. A simplex is called \emph{maximal} if it is not a face of any
simplex in |\Mvar|. Two simplices of dimension $k$ are called
neighbors if they share $k-1$ vertices. A complex is connected if its
set of maximal simplices forms a connected set under the neighboring
relation. A simplicial complex is called \emph{regular} if all
maximal simplices in the complex have the same dimension and if the
complex is connected.
A concrete simplicial complex is an abstract simplicial complex in
which a point in some ambient space is associated with each vertex.
We use |dim| to denote the dimension of ambient space. Simplices are
now interpreted geometrically as sets of points in ambient space,
namely as the convex hulls of (the points associated with) their
vertices. A $0$-simplex is a point, a $1$-simplex is a line segment, a
$2$-simplex is a triangle, a $3$-simplex is a tetrahedron,
etc.. \emph{The simplices is a concrete simplicial complex must
satisfy the additional conditions that the points associated with the
vertices of any simplex are affinely independet and that the
intersection of any two simplices is a face of both.} We will write
simplicial complex instead of concrete simplicial complex in the
sequel.
All maximal simplices in a regular simplicial complex have the same
dimension, which we denote |dcur|. For each maximal
simplex\cgalFootnote{we drop the adjective maximal in the sequel} in
|\Mvar| there is an item of type |RC_simplex_d| and for each vertex
there is an item of type |rc_vertex|. Each maximal simplex has |1+dcur|
vertices indexed from $0$ to |dcur|. For any simplex $s$ and any
index $i$, |C.vertex_of(s,i)| returns the $i$-th vertex of $s$. There
may or may not be a simplex $t$ opposite to (the vertex with index)
$i$, i.e., a maximal simplex $t$ having
\{|C.vertex_of(s,0)|,|C.vertex_of(s,1)|,\ldots,
|C.vertex_of(s,dcur)|\} - \{|C.vertex_of(s,i)|\} in its vertex
set. The function |C.opposite(s,i)| returns $t$ if it exists and
returns |nil| otherwise. If $t$ exists then $s$ and $t$ share |dcur|
vertices, namely all but vertex $i$ of $s$ and vertex
|C.opposite_vertex(s,i)| of $t$. Assume that $t = |C.opposite(s,i)|$
exists and let |j = C.opposite_vertex(s,i)|. Then |s = C.opposite(t,j)|
and |i = C.opposite_vertex(t,j)| and
\begin{eqnarray*}
\lefteqn{\{|C.vertex_of(s,0)|,|C.vertex_of(s,1)|,\ldots,
|C.vertex_of(s,dcur)|\} - \{|C.vertex_of(s,i)|\} =} \\ & &
\{|C.vertex_of(t,0)|,|C.vertex_of(t,1)|,\ldots,|C.vertex_of(t,dcur)|\}
- \{|C.vertex_of(t,j)|\}. \end{eqnarray*} In general, a
vertex belongs to many simplices. For an |rc_vertex| $v$,
the functions |C.simplex(v)| and |C.index(v)| return a pair $(s,i)$
such that |v = C.vertex_of(s,i)|.
The class |regl_complex| has a static member |nil_point| of type
|Point_d|. This point is different (= not indentical) from any user
defined point and is the point associated with every vertex of an
abstract simplicial complex. It simulates the use of |nil| to denote
an undefined object.
Regular complexes are designed as the base class for triangulations of
convex hulls and Delaunay triangulations in higher dimensional
space. We have not used them yet for any other purpose. Regular
complexes are built by constructing vertices and simplices, by
assigning positions to vertices and vertices to simplices, and by
establishing neighbor relations. The update operations do not check
whether the data structure built actually encodes a simplicial
complex. The class provides a function |is_valid()| that performs a
partial check whether the data structure encodes a simplicial
complex. It is not checked whether two simplices intersect without
sharing a face.
}*/
template <class R_>
class Regular_complex_d
{
typedef Regular_complex_d<R_> Self;
public:
/*{\Mtypes 4}*/
typedef R_ R;
typedef RC_vertex_d<Self> Vertex;
typedef CGAL::Compact_container<Vertex> Vertex_list;
typedef typename Vertex_list::iterator Vertex_handle;
/*{\Mtypemember the handle type for vertices of the complex.}*/
typedef typename Vertex_list::const_iterator Vertex_const_handle;
typedef typename Vertex_list::iterator Vertex_iterator;
/*{\Mtypemember the iterator type for vertices of the complex.}*/
typedef typename Vertex_list::const_iterator Vertex_const_iterator;
typedef RC_simplex_d<Self> Simplex;
typedef CGAL::Compact_container<Simplex> Simplex_list;
typedef typename Simplex_list::iterator Simplex_handle;
/*{\Mtypemember the handle type for simplices of the complex.}*/
typedef typename Simplex_list::const_iterator Simplex_const_handle;
typedef typename Simplex_list::iterator Simplex_iterator;
/*{\Mtypemember the iterator type for simplices of the complex.}*/
typedef typename Simplex_list::const_iterator Simplex_const_iterator;
typedef typename R::Point_d Point_d;
protected:
const R& Kernel_;
int dcur; // dimension of the current complex
int dmax; // dimension of ambient space
Vertex_list vertices_; // list of all vertices
Simplex_list simplices_; // list of all simplices
/* the default copy constructor and assignment operator for class
regl_complex work incorrectly; it is therefore good practice to
either implement them correctly or to make them inaccessible. We do
the latter. */
private:
Regular_complex_d(const Regular_complex_d<R>& );
Regular_complex_d& operator=(const Regular_complex_d<R>& );
void clean_dynamic_memory()
{
vertices_.clear();
simplices_.clear();
}
public:
/*{\Mcreation}*/
Regular_complex_d(int d = 2, const R& Kernel = R())
/*{\Mcreate creates an instance |\Mvar| of type |\Mtype|. The
dimension of the underlying space is $d$ and |\Mvar| is initialized to
the empty regular complex. Thus |dcur| equals $-1$. The traits class
|R| specifies the models of all types and the implementations of
all geometric primitives used by the regular complex class. The
|Kernel| parameter allows you to carry fixed geometric information
into the data type. For the default kernel traits |Homogeneous_d|
the default construction of |Kernel| is enough.
In the following we use further template parameters like the point
type |Point_d=R::Point_d|. At this point, it suffices to say that
|Point_d| represents points in $d$-space. The complete specification of
the traits class is to be found at the end of this manual page.}*/
: Kernel_(Kernel) { dmax = d; dcur = -1; }
~Regular_complex_d() { clean_dynamic_memory(); }
/* In the destructor for |Regular_complex_d|, we have to release the
storage which was allocated for the simplices and the vertices. */
/*{\Mtext The data type |\Mtype| offers neither copy constructor nor
assignment operator.}*/
/*{\Moperations 3 3}*/
/*{\Mtext \headerline{Access Operations}}*/
int dimension() const { return dmax; }
/*{\Mop returns the dimension of ambient space}*/
int current_dimension() const { return dcur; }
/*{\Mop returns the current dimension of the simplices in the
complex.}*/
Vertex_handle vertex(Simplex_handle s, int i) const
/*{\Mop returns the $i$-th vertex of $s$.\\
\precond $0 \leq i \leq |current_dimension|$. }*/
{ CGAL_assertion(0<=i&&i<=dcur);
return s->vertex(i); }
Vertex_const_handle vertex(Simplex_const_handle s, int i) const
{ CGAL_assertion(0<=i&&i<=dcur);
return s->vertex(i); }
Point_d associated_point(Vertex_handle v) const
/*{\Mop returns the point associated with vertex |v|.}*/
{ return v->point(); }
Point_d associated_point(Vertex_const_handle v) const
{ return v->point(); }
int index(Vertex_handle v) const
/*{\Mop returns the index of $v$ in |C.simplex(v)|.}*/
{ return v->index(); }
int index(Vertex_const_handle v) const
{ return v->index(); }
Simplex_handle simplex(Vertex_handle v) const
/*{\Mop returns a simplex of which $v$ is a vertex. Note that this
simplex is not unique. }*/
{ return v->simplex(); }
Simplex_const_handle simplex(Vertex_const_handle v) const
{ return v->simplex(); }
Point_d associated_point(Simplex_handle s, int i) const
/*{\Mop same as |C.associated_point(C.vertex(s,i))|.}*/
{ return associated_point(vertex(s,i)); }
Point_d associated_point(Simplex_const_handle s, int i) const
{ return associated_point(vertex(s,i)); }
Simplex_handle opposite_simplex(Simplex_handle s,int i) const
/*{\Mop returns the simplex opposite to the $i$-th vertex of $s$
(|Simplex_handle()| is there is no such simplex).\\ \precond $0 \leq i \leq |dcur|$. }*/
{ CGAL_assertion(0<=i&&i<=dcur);
return s->neighbor(i); }
Simplex_const_handle opposite_simplex(Simplex_const_handle s,int i) const
{ CGAL_assertion(0<=i&&i<=dcur);
return s->neighbor(i); }
int index_of_opposite_vertex(Simplex_handle s, int i) const
{ CGAL_assertion(0<=i&&i<=dcur);
return s->opposite_vertex_index(i); }
/*{\Mop returns the index of the vertex opposite to the $i$-th vertex
of $s$. \precond $0 \leq i \leq |dcur|$ and there is a
simplex opposite to the $i$-th vertex of $s$.}*/
int index_of_opposite_vertex(Simplex_const_handle s, int i) const
{ CGAL_assertion(0<=i&&i<=dcur);
return s->opposite_vertex_index(i); }
/*{\Mtext \headerline{Update Operations}
We give operations that allow to update a regular complex. They have
to be used with care as they may invalidate the data structure.}*/
void clear(int d = 0)
/*{\Mop reinitializes |\Mvar| to the empty complex in dimension |dim|.}*/
{ clean_dynamic_memory();
dmax = d; dcur = -1;
}
void set_current_dimension(int d) { dcur = d; }
/*{\Mop sets |dcur| to |d|. }*/
Simplex_handle new_simplex()
/*{\Mop adds a new simplex to |\Mvar| and returns it. The new simplex
has no vertices yet.}*/
{
Simplex s(dmax);
Simplex_handle h = simplices_.insert(s);
return h;
}
Vertex_handle new_vertex()
/*{\Mop adds a new vertex to |\Mvar| and returns it. The new vertex
has no associated simplex nor index yet. The associated point
is the point |Regular_complex_d::nil_point| which is a static
member of class |Regular_complex_d.|}*/
{
return vertices_.emplace(nil_point);
}
Vertex_handle new_vertex(const Point_d& p)
/*{\Mop adds a new vertex to |\Mvar| and returns it. The new vertex
has |p| as the associated point, but is has no associated
simplex nor index yet.}*/
{
return vertices_.emplace(p);
}
void associate_vertex_with_simplex(Simplex_handle s, int i, Vertex_handle v)
/*{\Mop sets the $i$-th vertex of |s| to |v| and records this fact in
$v$. The latter occurs only if $v$ is non-nil.}*/
{ s -> set_vertex(i,v);
if ( v != Vertex_handle() ) {
v -> set_simplex(s); v -> set_index(i);
}
}
void associate_point_with_vertex(Vertex_handle v, const Point_d& p)
/*{\Mop sets the point associated with $v$ to $p$.}*/
{ v -> set_point(p); }
void set_neighbor(Simplex_handle s, int i, Simplex_handle s1, int j)
/*{\Mop sets the neihbor opposite to vertex $i$ of |s| to |s1| and
records vertex $j$ of |s1| as the vertex opposite to $i$.}*/
{ s -> set_neighbor(i,s1);
s1 -> set_neighbor(j,s);
s -> set_opposite_vertex_index(i,j);
s1 -> set_opposite_vertex_index(j,i);
}
void check_topology() const;
/*{\Mop Partially checks whether |\Mvar| is an abstract simplicial
complex. This function terminates without error if each vertex is a
vertex of the simplex of which it claims to be a vertex, if the
vertices of all simplices are pairwise distinct, if the neighbor
relationship is symmetric, and if neighboring simplices share exactly
|dcur| vertices. It returns an error message if one of these
conditions is violated. Note that it is not checked whether simplices
that share |dcur| vertices are neighbors in the data structure.}*/
void check_topology_and_geometry() const;
/*{\Mop In addition to the above, this function checks whether all
vertices have an associated point different from
|Regular_complex_d::nil_point| and whether the points associated with the
vertices of any simplex are affinely independent. It returns an error
message otherwise. Note that it is not checked whether the
intersection of any two simplices is a facet of both.}*/
typedef size_t Size_type;
Size_type number_of_vertices() const { return this->vertices_.size();}
Size_type number_of_simplices() const { return this->simplices_.size();}
void print_statistics(std::ostream& os = std::cout) const
{
os << "Regular_complex_d - statistic" << std::endl;
os << "number of vertices = " << number_of_vertices() << std::endl;
os << "number of simplices = " << number_of_simplices() << std::endl;
}
/*{\Mtext \headerline{Lists and Iterators}
\setopdims{4.5cm}{3.5cm}}*/
/*{\Mtext The following operation pairs return iterator ranges in
the style of STL.}*/
Vertex_iterator vertices_begin() { return vertices_.begin(); }
/*{\Mop the first vertex of |\Mvar|.}*/
Vertex_iterator vertices_end() { return vertices_.end(); }
/*{\Mop the beyond vertex of |\Mvar|.}*/
Simplex_iterator simplices_begin() { return simplices_.begin(); }
/*{\Mop the first simplex of |\Mvar|.}*/
Simplex_iterator simplices_end() { return simplices_.end(); }
/*{\Mop the beyond simplex of |\Mvar|.}*/
Vertex_const_iterator vertices_begin() const { return vertices_.begin(); }
Vertex_const_iterator vertices_end() const { return vertices_.end(); }
Simplex_const_iterator simplices_begin() const { return simplices_.begin(); }
Simplex_const_iterator simplices_end() const { return simplices_.end(); }
std::list<Simplex_handle> all_simplices()
/*{\Mop returns the set of all maximal simplices in |\Mvar|.}*/
{ std::list<Simplex_handle> res; Simplex_iterator it;
forall_rc_simplices(it,*this) res.push_back(it);
return res; }
std::list<Simplex_const_handle> all_simplices() const
{ std::list<Simplex_const_handle> res; Simplex_const_iterator it;
forall_rc_simplices(it,*this) res.push_back(it);
return res; }
std::list<Vertex_handle> all_vertices()
/*{\Mop returns the set of all vertices in |\Mvar|.}*/
{ std::list<Vertex_handle> res; Vertex_iterator it;
forall_rc_vertices(it,*this) res.push_back(it);
return res; }
std::list<Vertex_const_handle> all_vertices() const
{ std::list<Vertex_const_handle> res; Vertex_const_iterator it;
forall_rc_vertices(it,*this) res.push_back(it);
return res; }
const R& kernel() const { return Kernel_; }
static const Point_d nil_point;
}; // Regular_complex_d<R>
// init static member:
template <class R>
const typename Regular_complex_d<R>::Point_d Regular_complex_d<R>::nil_point;
template <class R>
void Regular_complex_d<R>::check_topology() const
{
Simplex_const_handle s,t;
Vertex_const_handle v;
int i,j,k;
if (dcur == -1) {
if (!vertices_.empty() || !simplices_.empty() )
CGAL_error_msg( "check_topology: dcur is -1 but there are vertices or simplices");
}
forall_rc_vertices(v,*this) {
if ( v != vertex(simplex(v),index(v)) )
CGAL_error_msg( "check_topology: vertex-simplex relationship corrupted");
}
forall_rc_simplices(s,*this) {
for(i = 0; i <= dcur; i++) {
for (j = i + 1; j <= dcur; j++) {
if (vertex(s,i) == vertex(s,j))
CGAL_error_msg( "check_topology: a simplex with two equal vertices");
}
}
}
forall_rc_simplices(s,*this) {
for(i = 0; i <= dcur; i++) {
if ((t = opposite_simplex(s,i)) != Simplex_const_handle()) {
int l = index_of_opposite_vertex(s,i);
if (s != opposite_simplex(t,l) ||
i != index_of_opposite_vertex(t,l))
CGAL_error_msg( "check_topology: neighbor relation is not symmetric");
for (j = 0; j <= dcur; j++) {
if (j != i) {
// j must also occur as a vertex of t
for (k = 0; k <= dcur &&
( vertex(s,j) != vertex(t,k) || k == l); k++) {}
if (k > dcur)
CGAL_error_msg( "check_topology: too few shared vertices.");
}
}
}
}
}
}
template <class R>
void Regular_complex_d<R>::check_topology_and_geometry() const
{
check_topology();
Vertex_const_handle v;
forall_rc_vertices(v,*this) {
if ( v == Vertex_const_handle() ||
associated_point(v).identical(Regular_complex_d<R>::nil_point) )
CGAL_error_msg("check_topology_and_geometry: \
vertex with nil_point or no associated point.");
}
typename R::Affinely_independent_d affinely_independent =
kernel().affinely_independent_d_object();
Simplex_const_handle s;
forall_rc_simplices(s,*this) {
std::vector<Point_d> A(dcur + 1);
for (int i = 0; i <= dcur; i++)
A[i] = associated_point(s,i);
if ( !affinely_independent(A.begin(),A.end()) )
CGAL_error_msg("check_topology_and_geometry: \
corners of some simplex are not affinely independent");
}
}
/*{\Mtext
\headerline{Iteration Statements}
{\bf forall\_rc\_simplices}($s,C$)
$\{$ ``the simplices of $C$ are successively assigned to $s$'' $\}$
{\bf forall\_rc\_vertices}($v,C$)
$\{$ ``the vertices of $C$ are successively assigned to $v$'' $\}$
}*/
/*{\Mimplementation Each simplex stores its vertices, the adjacent
simplices, and the opposite vertices in arrays. The space requirement
for a simplex is $3 * |dim| * 4$ Bytes for the contents of the arrays
plus the actual space for the points plus the constant space overhead
for the arrays (see the manual pages for arrays).
The class |Regular_complex_d| needs constant space plus space for a list of
simplices (which is about 12 bytes per simplex). The total space
requirement is therefore about $12(|dim| + 2)$ bytes times the number
of simplices. }*/
} //namespace CGAL
#endif // CGAL_REGULAR_COMPLEX_D_H
| [
"huxingyi@msn.com"
] | huxingyi@msn.com |
11fcab659ee71d6b1ff7dd022220c15b947fa8db | b465f88e2dad7012a06252c675db561d6de7f847 | /src/test/governance_validators_tests.cpp | cd50bcbe8f83889659885b6e2053326bf4fd3aa6 | [
"MIT"
] | permissive | bulletcore/xbullet | 750d5125b87d70bce202a64f5318d365fcb0a175 | 450f07709d51b0bbbe1a82c9c72ef9f319a32d1f | refs/heads/master | 2021-04-12T12:02:17.434802 | 2018-03-22T10:27:25 | 2018-03-22T10:27:25 | 126,307,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,358 | cpp | // Copyright (c) 2014-2017 The Bullet Core developers
#include "governance-validators.h"
#include "univalue.h"
#include "utilstrencodings.h"
#include "test/test_bullet.h"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <fstream>
#include <string>
BOOST_FIXTURE_TEST_SUITE(governance_validators_tests, BasicTestingSetup)
UniValue LoadJSON(const std::string& strFilename)
{
UniValue obj(UniValue::VOBJ);
std::ifstream istr(strFilename.c_str());
std::string strData;
std::string strLine;
bool fFirstLine = true;
while(std::getline(istr, strLine)) {
if(!fFirstLine) {
strData += "\n";
}
strData += strLine;
fFirstLine = false;
}
obj.read(strData);
return obj;
}
std::string CreateEncodedProposalObject(const UniValue& objJSON)
{
UniValue innerArray(UniValue::VARR);
innerArray.push_back(UniValue("proposal"));
innerArray.push_back(objJSON);
UniValue outerArray(UniValue::VARR);
outerArray.push_back(innerArray);
std::string strData = outerArray.write();
std::string strHex = HexStr(strData);
return strHex;
}
BOOST_AUTO_TEST_CASE(valid_proposals_test)
{
CProposalValidator validator;
UniValue obj = LoadJSON("src/test/data/proposals-valid.json");
for(size_t i = 0; i < obj.size(); ++i) {
const UniValue& objProposal = obj[i];
std::string strHexData = CreateEncodedProposalObject(objProposal);
validator.SetHexData(strHexData);
BOOST_CHECK(validator.ValidateJSON());
BOOST_CHECK(validator.ValidateName());
BOOST_CHECK(validator.ValidateURL());
BOOST_CHECK(validator.ValidateStartEndEpoch());
BOOST_CHECK(validator.ValidatePaymentAmount());
BOOST_CHECK(validator.ValidatePaymentAddress());
BOOST_CHECK(validator.Validate());
validator.Clear();
}
}
BOOST_AUTO_TEST_CASE(invalid_proposals_test)
{
CProposalValidator validator;
UniValue obj = LoadJSON("src/test/data/proposals-invalid.json");
for(size_t i = 0; i < obj.size(); ++i) {
const UniValue& objProposal = obj[i];
std::string strHexData = CreateEncodedProposalObject(objProposal);
validator.SetHexData(strHexData);
BOOST_CHECK(!validator.Validate());
validator.Clear();
}
}
BOOST_AUTO_TEST_SUITE_END()
| [
"32610984+karanjchavda@users.noreply.github.com"
] | 32610984+karanjchavda@users.noreply.github.com |
e4af72bcaddd8a973c4432ec54be670e4de48723 | a84456db7128c0ba0aa5fc0ed800ef4da27ae379 | /include/sieve/Numbering.hh | d422c0e9a688a10e79ced2161f58312dda35ebab | [] | no_license | rcb547/petsc-3.4.3-vs2013 | 82bfc7a8a484f47b249cfcb29cde920fa436d8dd | 44dac09be8c4ce515b9a7ceef08d9a00cf0f6036 | refs/heads/master | 2021-01-22T02:18:02.302439 | 2017-02-06T05:37:16 | 2017-02-06T05:37:16 | 81,041,078 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,853 | hh | #ifndef included_ALE_Numbering_hh
#define included_ALE_Numbering_hh
#ifndef included_ALE_ParallelMapping_hh
#include <sieve/ParallelMapping.hh>
#endif
namespace ALE {
// We have a dichotomy between \emph{types}, describing the structure of objects,
// and \emph{concepts}, describing the role these objects play in the algorithm.
// Below we identify concepts with potential implementing types.
//
// Concept Type
// ------- ----
// Overlap Sifter
// Atlas ConstantSection, UniformSection
// Numbering UniformSection
// GlobalOrder UniformSection
//
// We will use factory types to create objects which satisfy a given concept.
template<typename Point_, typename Value_ = int, typename Alloc_ = malloc_allocator<Point_> >
class Numbering : public UniformSection<Point_, Value_, 1, Alloc_> {
public:
typedef UniformSection<Point_, Value_, 1, Alloc_> base_type;
typedef typename base_type::point_type point_type;
typedef typename base_type::value_type value_type;
typedef typename base_type::atlas_type atlas_type;
protected:
int _localSize;
int *_offsets;
std::map<int, point_type> _invOrder;
public:
Numbering(MPI_Comm comm, const int debug = 0) : UniformSection<Point_, Value_, 1, Alloc_>(comm, debug), _localSize(0) {
this->_offsets = new int[this->commSize()+1];
this->_offsets[0] = 0;
};
virtual ~Numbering() {
delete [] this->_offsets;
};
public: // Sizes
int getLocalSize() const {return this->_localSize;};
void setLocalSize(const int size) {this->_localSize = size;};
int getGlobalSize() const {return this->_offsets[this->commSize()];};
int getGlobalOffset(const int p) const {return this->_offsets[p];};
const int *getGlobalOffsets() const {return this->_offsets;};
void setGlobalOffsets(const int offsets[]) {
for(int p = 0; p <= this->commSize(); ++p) {
this->_offsets[p] = offsets[p];
}
};
public: // Indices
virtual int getIndex(const point_type& point) {
const value_type& idx = this->restrictPoint(point)[0];
if (idx >= 0) {
return idx;
}
return -(idx+1);
};
virtual void setIndex(const point_type& point, const int index) {this->updatePoint(point, &index);};
virtual bool isLocal(const point_type& point) {return this->restrictPoint(point)[0] >= 0;};
virtual bool isRemote(const point_type& point) {return this->restrictPoint(point)[0] < 0;};
point_type getPoint(const int& index) {return this->_invOrder[index];};
void setPoint(const int& index, const point_type& point) {this->_invOrder[index] = point;};
};
template<typename Point_, typename Value_ = ALE::Point>
class GlobalOrder : public UniformSection<Point_, Value_> {
public:
typedef UniformSection<Point_, Value_> base_type;
typedef typename base_type::point_type point_type;
typedef typename base_type::value_type value_type;
typedef typename base_type::atlas_type atlas_type;
protected:
int _localSize;
int *_offsets;
public:
GlobalOrder(MPI_Comm comm, const int debug = 0) : UniformSection<Point_, Value_>(comm, debug), _localSize(0) {
this->_offsets = new int[this->commSize()+1];
this->_offsets[0] = 0;
};
~GlobalOrder() {
delete [] this->_offsets;
};
public: // Sizes
int getLocalSize() const {return this->_localSize;};
void setLocalSize(const int size) {this->_localSize = size;};
int getGlobalSize() const {return this->_offsets[this->commSize()];};
int getGlobalOffset(const int p) const {return this->_offsets[p];};
const int *getGlobalOffsets() const {return this->_offsets;};
void setGlobalOffsets(const int offsets[]) {
for(int p = 0; p <= this->commSize(); ++p) {
this->_offsets[p] = offsets[p];
}
};
public: // Indices
virtual int getIndex(const point_type& p) {
const int idx = this->restrictPoint(p)[0].prefix;
if (idx >= 0) {
return idx;
}
return -(idx+1);
};
virtual void setIndex(const point_type& p, const int index) {
const value_type idx(index, this->restrictPoint(p)[0].index);
this->updatePoint(p, &idx);
};
virtual bool isLocal(const point_type& p) {return this->restrictPoint(p)[0].prefix >= 0;};
virtual bool isRemote(const point_type& p) {return this->restrictPoint(p)[0].prefix < 0;};
};
template<typename Bundle_, typename Value_ = int, typename Alloc_ = typename Bundle_::alloc_type>
class NumberingFactory : public ALE::ParallelObject {
public:
typedef Bundle_ bundle_type;
typedef Alloc_ alloc_type;
typedef Value_ value_type;
typedef typename bundle_type::sieve_type sieve_type;
typedef typename bundle_type::label_type label_type;
typedef typename bundle_type::point_type point_type;
typedef typename bundle_type::rank_type rank_type;
typedef typename bundle_type::send_overlap_type send_overlap_type;
typedef typename bundle_type::recv_overlap_type recv_overlap_type;
typedef Numbering<point_type, value_type, alloc_type> numbering_type;
typedef typename alloc_type::template rebind<value_type>::other value_alloc_type;
typedef std::map<bundle_type*, std::map<std::string, std::map<int, Obj<numbering_type> > > > numberings_type;
typedef GlobalOrder<point_type> order_type;
typedef typename order_type::value_type oValue_type;
typedef typename alloc_type::template rebind<oValue_type>::other oValue_alloc_type;
typedef std::map<bundle_type*, std::map<std::string, Obj<order_type> > > orders_type;
protected:
numberings_type _localNumberings;
numberings_type _numberings;
orders_type _localOrders;
orders_type _orders;
orders_type _ordersBC;
const value_type _unknownNumber;
const oValue_type _unknownOrder;
protected:
NumberingFactory(MPI_Comm comm, const int debug = 0) : ALE::ParallelObject(comm, debug), _unknownNumber(-1), _unknownOrder(-1, 0) {};
public:
~NumberingFactory() {};
public:
static const Obj<NumberingFactory>& singleton(MPI_Comm comm, const int debug, bool cleanup = false) {
static Obj<NumberingFactory> *_singleton = NULL;
if (cleanup) {
if (debug) {std::cout << "Destroying NumberingFactory" << std::endl;}
if (_singleton) {delete _singleton;}
_singleton = NULL;
} else if (_singleton == NULL) {
if (debug) {std::cout << "Creating new NumberingFactory" << std::endl;}
_singleton = new Obj<NumberingFactory>();
*_singleton = new NumberingFactory(comm, debug);
}
return *_singleton;
};
void clear() {
this->_localNumberings.clear();
this->_numberings.clear();
this->_localOrders.clear();
this->_orders.clear();
this->_ordersBC.clear();
};
public: // Dof ordering
template<typename Section_>
void orderPointNew(const Obj<Section_>& section, const Obj<sieve_type>& sieve, const typename Section_::point_type& point, value_type& offset, value_type& bcOffset, const Obj<send_overlap_type>& sendOverlap = NULL) {
const typename Section_::chart_type& chart = section->getChart();
int& idx = section->getIndex(point);
// If the point does not exist in the chart, throw an error
if (chart.count(point) == 0) {
throw ALE::Exception("Unknown point in ordering");
}
// If the point has not been ordered
if (idx == -1) {
// Recurse to its cover
const Obj<typename sieve_type::coneSequence>& cone = sieve->cone(point);
typename sieve_type::coneSequence::iterator end = cone->end();
for(typename sieve_type::coneSequence::iterator c_iter = cone->begin(); c_iter != end; ++c_iter) {
if (this->_debug > 1) {std::cout << " Recursing to " << *c_iter << std::endl;}
this->orderPoint(section, sieve, *c_iter, offset, bcOffset, sendOverlap);
}
const int dim = section->getFiberDimension(point);
const int cDim = section->getConstraintDimension(point);
const int fDim = dim - cDim;
// If the point has constrained variables
if (cDim) {
if (this->_debug > 1) {std::cout << " Ordering boundary point " << point << " at " << bcOffset << std::endl;}
section->setIndexBC(point, bcOffset);
bcOffset += cDim;
}
// If the point has free variables
if (fDim) {
bool number = true;
// Maybe use template specialization here
if (!sendOverlap.isNull() && sendOverlap->capContains(point)) {
const Obj<typename send_overlap_type::supportSequence>& ranks = sendOverlap->support(point);
for(typename send_overlap_type::supportSequence::iterator r_iter = ranks->begin(); r_iter != ranks->end(); ++r_iter) {
if (this->commRank() > *r_iter) {
number = false;
break;
}
}
}
if (number) {
if (this->_debug > 1) {std::cout << " Ordering point " << point << " at " << offset << std::endl;}
section->setIndex(point, offset);
offset += dim;
} else {
if (this->_debug > 1) {std::cout << " Ignoring ghost point " << point << std::endl;}
}
}
}
}
template<typename Section_>
void orderPoint(const Obj<Section_>& section, const Obj<sieve_type>& sieve, const typename Section_::point_type& point, value_type& offset, value_type& bcOffset, const Obj<send_overlap_type>& sendOverlap = NULL) {
const Obj<typename Section_::atlas_type>& atlas = section->getAtlas();
const Obj<typename sieve_type::coneSequence>& cone = sieve->cone(point);
typename sieve_type::coneSequence::iterator end = cone->end();
typename Section_::index_type idx = section->getAtlas()->restrictPoint(point)[0];
const value_type& dim = idx.prefix;
const typename Section_::index_type defaultIdx(0, -1);
if (atlas->getChart().count(point) == 0) {
idx = defaultIdx;
}
if (idx.index == -1) {
for(typename sieve_type::coneSequence::iterator c_iter = cone->begin(); c_iter != end; ++c_iter) {
if (this->_debug > 1) {std::cout << " Recursing to " << *c_iter << std::endl;}
this->orderPoint(section, sieve, *c_iter, offset, bcOffset, sendOverlap);
}
if (dim > 0) {
bool number = true;
// Maybe use template specialization here
if (!sendOverlap.isNull() && sendOverlap->capContains(point)) {
const Obj<typename send_overlap_type::supportSequence>& ranks = sendOverlap->support(point);
for(typename send_overlap_type::supportSequence::iterator r_iter = ranks->begin(); r_iter != ranks->end(); ++r_iter) {
if (this->commRank() > *r_iter) {
number = false;
break;
}
}
}
if (number) {
if (this->_debug > 1) {std::cout << " Ordering point " << point << " at " << offset << std::endl;}
idx.index = offset;
atlas->updatePoint(point, &idx);
offset += dim;
} else {
if (this->_debug > 1) {std::cout << " Ignoring ghost point " << point << std::endl;}
}
} else if (dim < 0) {
if (this->_debug > 1) {std::cout << " Ordering boundary point " << point << " at " << bcOffset << std::endl;}
idx.index = bcOffset;
atlas->updatePoint(point, &idx);
bcOffset += dim;
}
}
}
template<typename Section_>
void orderPatch(const Obj<Section_>& section, const Obj<sieve_type>& sieve, const Obj<send_overlap_type>& sendOverlap = NULL, const value_type offset = 0, const value_type bcOffset = -2) {
const typename Section_::chart_type& chart = section->getChart();
int off = offset;
int bcOff = bcOffset;
if (this->_debug > 1) {std::cout << "Ordering patch" << std::endl;}
for(typename Section_::chart_type::const_iterator p_iter = chart.begin(); p_iter != chart.end(); ++p_iter) {
if (this->_debug > 1) {std::cout << "Ordering closure of point " << *p_iter << std::endl;}
this->orderPoint(section, sieve, *p_iter, off, bcOff, sendOverlap);
}
for(typename Section_::chart_type::const_iterator p_iter = chart.begin(); p_iter != chart.end(); ++p_iter) {
const int& idx = section->getIndex(*p_iter);
if (idx < 0) {
if (this->_debug > 1) {std::cout << "Correcting boundary offset of point " << *p_iter << std::endl;}
section->setIndex(*p_iter, off - (idx + 2));
}
}
}
public: // Numbering
// Number all local points
// points in the overlap are only numbered by the owner with the lowest rank
template<typename Iterator_>
void constructLocalNumbering(const Obj<numbering_type>& numbering, const Obj<send_overlap_type>& sendOverlap, const Iterator_& pointsBegin, const Iterator_& pointsEnd) {
const int debug = sendOverlap->debug();
int localSize = 0;
if (debug) {std::cout << "["<<numbering->commRank()<<"] Constructing local numbering" << std::endl;}
for(Iterator_ l_iter = pointsBegin; l_iter != pointsEnd; ++l_iter) {
numbering->setFiberDimension(*l_iter, 1);
}
for(Iterator_ l_iter = pointsBegin; l_iter != pointsEnd; ++l_iter) {
value_type val;
if (debug) {std::cout << "["<<numbering->commRank()<<"] Checking point " << *l_iter << std::endl;}
if (sendOverlap->capContains(*l_iter)) {
const Obj<typename send_overlap_type::supportSequence>& sendRanks = sendOverlap->support(*l_iter);
int minRank = sendOverlap->commSize();
for(typename send_overlap_type::supportSequence::iterator p_iter = sendRanks->begin(); p_iter != sendRanks->end(); ++p_iter) {
if (*p_iter < minRank) minRank = *p_iter;
}
if (minRank < sendOverlap->commRank()) {
if (debug) {std::cout << "["<<numbering->commRank()<<"] remote point, on proc " << minRank << std::endl;}
val = this->_unknownNumber;
} else {
if (debug) {std::cout << "["<<numbering->commRank()<<"] local point" << std::endl;}
val = localSize++;
}
} else {
if (debug) {std::cout << "["<<numbering->commRank()<<"] local point" << std::endl;}
val = localSize++;
}
if (debug) {std::cout << "["<<numbering->commRank()<<"] has number " << val << std::endl;}
numbering->updatePoint(*l_iter, &val);
}
if (debug) {std::cout << "["<<numbering->commRank()<<"] local points" << std::endl;}
numbering->setLocalSize(localSize);
}
// Order all local points
// points in the overlap are only ordered by the owner with the lowest rank
template<typename Iterator_, typename Section_>
void constructLocalOrder(const Obj<order_type>& order, const Obj<send_overlap_type>& sendOverlap, const Iterator_& pointsBegin, const Iterator_& pointsEnd, const Obj<Section_>& section, const int space = -1, const bool withBC = false, const Obj<label_type>& label = NULL) {
const int debug = sendOverlap->debug();
int localSize = 0;
if (debug) {std::cout << "["<<order->commRank()<<"] Constructing local ordering" << std::endl;}
for(Iterator_ l_iter = pointsBegin; l_iter != pointsEnd; ++l_iter) {
order->setFiberDimension(*l_iter, 1);
}
for(Iterator_ l_iter = pointsBegin; l_iter != pointsEnd; ++l_iter) {
oValue_type val;
if (debug) {std::cout << "["<<order->commRank()<<"] Checking point " << *l_iter << std::endl;}
if (sendOverlap->capContains(*l_iter)) {
const Obj<typename send_overlap_type::supportSequence>& sendPatches = sendOverlap->support(*l_iter);
int minRank = sendOverlap->commSize();
for(typename send_overlap_type::supportSequence::iterator p_iter = sendPatches->begin(); p_iter != sendPatches->end(); ++p_iter) {
if (*p_iter < minRank) minRank = *p_iter;
}
bool remotePoint = (minRank < sendOverlap->commRank()) || (!label.isNull() && (label->cone(*l_iter)->size() > 0));
if (remotePoint) {
if (debug) {std::cout << "["<<order->commRank()<<"] remote point, on proc " << minRank << std::endl;}
val = this->_unknownOrder;
} else {
if (debug) {std::cout << "["<<order->commRank()<<"] local point" << std::endl;}
val.prefix = localSize;
if (withBC) {
val.index = space < 0 ? section->getFiberDimension(*l_iter) : section->getFiberDimension(*l_iter, space);
} else {
val.index = space < 0 ? section->getConstrainedFiberDimension(*l_iter) : section->getConstrainedFiberDimension(*l_iter, space);
}
}
} else {
if (debug) {std::cout << "["<<order->commRank()<<"] local point" << std::endl;}
val.prefix = localSize;
if (withBC) {
val.index = space < 0 ? section->getFiberDimension(*l_iter) : section->getFiberDimension(*l_iter, space);
} else {
val.index = space < 0 ? section->getConstrainedFiberDimension(*l_iter) : section->getConstrainedFiberDimension(*l_iter, space);
}
}
if (debug) {std::cout << "["<<order->commRank()<<"] has offset " << val.prefix << " and size " << val.index << std::endl;}
localSize += val.index;
order->updatePoint(*l_iter, &val);
}
if (debug) {std::cout << "["<<order->commRank()<<"] local size" << localSize << std::endl;}
order->setLocalSize(localSize);
}
// Calculate process offsets
template<typename Numbering>
void calculateOffsets(const Obj<Numbering>& numbering) {
int localSize = numbering->getLocalSize();
int *offsets = new int[numbering->commSize()+1];
offsets[0] = 0;
MPI_Allgather(&localSize, 1, MPI_INT, &(offsets[1]), 1, MPI_INT, numbering->comm());
for(int p = 2; p <= numbering->commSize(); p++) {
offsets[p] += offsets[p-1];
}
numbering->setGlobalOffsets(offsets);
delete [] offsets;
}
// Update local offsets based upon process offsets
template<typename Numbering, typename Iterator>
void updateOrder(const Obj<Numbering>& numbering, const Iterator& pointsBegin, const Iterator& pointsEnd) {
const typename Numbering::value_type val = numbering->getGlobalOffset(numbering->commRank());
for(Iterator l_iter = pointsBegin; l_iter != pointsEnd; ++l_iter) {
if (numbering->isLocal(*l_iter)) {
numbering->updateAddPoint(*l_iter, &val);
}
}
}
// Communicate numbers in the overlap
void completeNumbering(const Obj<numbering_type>& numbering, const Obj<send_overlap_type>& sendOverlap, const Obj<recv_overlap_type>& recvOverlap, bool allowDuplicates = false) {
#if 1
typedef ALE::UniformSection<ALE::Pair<int, typename send_overlap_type::source_type>, typename numbering_type::value_type> OverlapSection;
typedef typename OverlapSection::point_type overlap_point_type;
Obj<OverlapSection> overlapSection = new OverlapSection(numbering->comm(), numbering->debug());
const int debug = sendOverlap->debug();
if (debug) {std::cout << "["<<numbering->commRank()<<"] Completing numbering" << std::endl;}
ALE::Pullback::SimpleCopy::copy(sendOverlap, recvOverlap, numbering, overlapSection);
if (debug) {overlapSection->view("Overlap Section");}
const typename recv_overlap_type::capSequence::iterator rBegin = recvOverlap->capBegin();
const typename recv_overlap_type::capSequence::iterator rEnd = recvOverlap->capEnd();
for(typename recv_overlap_type::capSequence::iterator r_iter = rBegin; r_iter != rEnd; ++r_iter) {
const int rank = *r_iter;
const typename recv_overlap_type::supportSequence::iterator pBegin = recvOverlap->supportBegin(*r_iter);
const typename recv_overlap_type::supportSequence::iterator pEnd = recvOverlap->supportEnd(*r_iter);
for(typename recv_overlap_type::supportSequence::iterator p_iter = pBegin; p_iter != pEnd; ++p_iter) {
const point_type& localPoint = *p_iter;
const point_type& remotePoint = p_iter.color();
const overlap_point_type oPoint = overlap_point_type(rank, remotePoint);
const int fDim = overlapSection->getFiberDimension(oPoint);
const typename numbering_type::value_type *values = overlapSection->restrictPoint(oPoint);
for(int i = 0; i < fDim; ++i) {
if (debug) {std::cout << "["<<numbering->commRank()<<"] local point " << localPoint << " remote point " << remotePoint << " number " << values[i] << std::endl;}
if (values[i] >= 0) {
if (numbering->isLocal(localPoint) && !allowDuplicates) {
ostringstream msg;
msg << "["<<numbering->commRank()<<"]Multiple indices for local point " << localPoint << " remote point " << remotePoint << " from " << rank << " with index " << values[i];
throw ALE::Exception(msg.str().c_str());
}
if (!numbering->hasPoint(localPoint)) {
ostringstream msg;
msg << "["<<numbering->commRank()<<"]Unexpected local point " << localPoint << " remote point " << remotePoint << " from " << rank << " with index " << values[i];
throw ALE::Exception(msg.str().c_str());
}
int val = -(values[i]+1);
numbering->updatePoint(localPoint, &val);
}
}
}
}
#else
typedef Field<send_overlap_type, int, Section<point_type, value_type, value_alloc_type> > send_section_type;
typedef Field<recv_overlap_type, int, Section<point_type, value_type, value_alloc_type> > recv_section_type;
typedef typename ALE::DiscreteSieve<point_type, alloc_type> dsieve_type;
typedef typename ALE::Topology<int, dsieve_type, alloc_type> dtopology_type;
typedef typename ALE::New::SectionCompletion<dtopology_type, int, alloc_type> completion;
const Obj<send_section_type> sendSection = new send_section_type(numbering->comm(), this->debug());
const Obj<recv_section_type> recvSection = new recv_section_type(numbering->comm(), sendSection->getTag(), this->debug());
const int debug = sendOverlap->debug();
if (debug) {std::cout << "["<<numbering->commRank()<<"] Completing numbering" << std::endl;}
completion::completeSection(sendOverlap, recvOverlap, numbering->getAtlas(), numbering, sendSection, recvSection);
const Obj<typename recv_overlap_type::baseSequence> rPoints = recvOverlap->base();
for(typename recv_overlap_type::baseSequence::iterator p_iter = rPoints->begin(); p_iter != rPoints->end(); ++p_iter) {
const Obj<typename recv_overlap_type::coneSequence>& ranks = recvOverlap->cone(*p_iter);
const typename recv_overlap_type::target_type& localPoint = *p_iter;
for(typename recv_overlap_type::coneSequence::iterator r_iter = ranks->begin(); r_iter != ranks->end(); ++r_iter) {
const typename recv_overlap_type::target_type& remotePoint = r_iter.color();
const int rank = *r_iter;
const Obj<typename recv_section_type::section_type>& section = recvSection->getSection(rank);
const typename recv_section_type::value_type *values = section->restrictPoint(remotePoint);
if (section->getFiberDimension(remotePoint) == 0) continue;
if (debug) {std::cout << "["<<numbering->commRank()<<"] local point " << localPoint << " remote point " << remotePoint << " number " << values[0] << std::endl;}
if (values[0] >= 0) {
if (debug) {std::cout << "["<<numbering->commRank()<<"] local point " << localPoint << " dim " << numbering->getAtlas()->getFiberDimension(localPoint) << std::endl;}
if (numbering->isLocal(localPoint) && !allowDuplicates) {
ostringstream msg;
msg << "["<<numbering->commRank()<<"]Multiple indices for local point " << localPoint << " remote point " << remotePoint << " from " << rank << " with index " << values[0];
throw ALE::Exception(msg.str().c_str());
}
if (numbering->getAtlas()->getFiberDimension(localPoint) == 0) {
ostringstream msg;
msg << "["<<numbering->commRank()<<"]Unexpected local point " << localPoint << " remote point " << remotePoint << " from " << rank << " with index " << values[0];
throw ALE::Exception(msg.str().c_str());
}
int val = -(values[0]+1);
numbering->updatePoint(localPoint, &val);
}
}
}
#endif
}
// Communicate (size,offset)s in the overlap
void completeOrder(const Obj<order_type>& order, const Obj<send_overlap_type>& sendOverlap, const Obj<recv_overlap_type>& recvOverlap, bool allowDuplicates = false) {
#if 1
typedef ALE::UniformSection<ALE::Pair<int, typename send_overlap_type::source_type>, typename order_type::value_type> OverlapSection;
typedef typename OverlapSection::point_type overlap_point_type;
Obj<OverlapSection> overlapSection = new OverlapSection(order->comm(), order->debug());
const int debug = sendOverlap->debug();
if (debug) {std::cout << "["<<order->commRank()<<"] Completing ordering" << std::endl;}
ALE::Pullback::SimpleCopy::copy(sendOverlap, recvOverlap, order, overlapSection);
if (debug) {overlapSection->view("Overlap Section");}
const typename recv_overlap_type::capSequence::iterator rBegin = recvOverlap->capBegin();
const typename recv_overlap_type::capSequence::iterator rEnd = recvOverlap->capEnd();
for(typename recv_overlap_type::capSequence::iterator r_iter = rBegin; r_iter != rEnd; ++r_iter) {
const int rank = *r_iter;
const typename recv_overlap_type::supportSequence::iterator pBegin = recvOverlap->supportBegin(*r_iter);
const typename recv_overlap_type::supportSequence::iterator pEnd = recvOverlap->supportEnd(*r_iter);
for(typename recv_overlap_type::supportSequence::iterator p_iter = pBegin; p_iter != pEnd; ++p_iter) {
const point_type& localPoint = *p_iter;
const point_type& remotePoint = p_iter.color();
const overlap_point_type oPoint = overlap_point_type(rank, remotePoint);
const int fDim = overlapSection->getFiberDimension(oPoint);
const typename order_type::value_type *values = overlapSection->restrictPoint(oPoint);
for(int i = 0; i < fDim; ++i) {
if (debug) {std::cout << "["<<order->commRank()<<"] local point " << localPoint << " remote point " << remotePoint<<"("<<rank<<")" << " offset " << values[i].prefix << " and size " << values[i].index << std::endl;}
if (values[i].index == 0) continue;
if (values[i].prefix >= 0) {
if (order->isLocal(localPoint)) {
if (!allowDuplicates) {
ostringstream msg;
msg << "["<<order->commRank()<<"]Multiple indices for local point " << localPoint << " remote point " << remotePoint << " from " << rank << " with index " << values[i];
throw ALE::Exception(msg.str().c_str());
}
continue;
}
const oValue_type val(-(values[i].prefix+1), values[i].index);
order->updatePoint(localPoint, &val);
} else {
if (order->isLocal(localPoint)) continue;
order->updatePoint(localPoint, &values[i]);
}
}
}
}
#else
typedef Field<send_overlap_type, int, Section<point_type, oValue_type, oValue_alloc_type> > send_section_type;
typedef Field<recv_overlap_type, int, Section<point_type, oValue_type, oValue_alloc_type> > recv_section_type;
typedef ConstantSection<point_type, int, alloc_type> constant_sizer;
typedef typename ALE::DiscreteSieve<point_type, alloc_type> dsieve_type;
typedef typename ALE::Topology<int, dsieve_type, alloc_type> dtopology_type;
typedef typename ALE::New::SectionCompletion<dtopology_type, int, alloc_type> completion;
const Obj<send_section_type> sendSection = new send_section_type(order->comm(), this->debug());
const Obj<recv_section_type> recvSection = new recv_section_type(order->comm(), sendSection->getTag(), this->debug());
const int debug = sendOverlap->debug();
if (debug) {std::cout << "["<<order->commRank()<<"] Completing ordering" << std::endl;}
completion::completeSection(sendOverlap, recvOverlap, order->getAtlas(), order, sendSection, recvSection);
Obj<typename recv_overlap_type::baseSequence> recvPoints = recvOverlap->base();
for(typename recv_overlap_type::baseSequence::iterator p_iter = recvPoints->begin(); p_iter != recvPoints->end(); ++p_iter) {
if (!order->hasPoint(*p_iter)) {
order->setFiberDimension(*p_iter, 1);
order->updatePoint(*p_iter, &this->_unknownOrder);
}
}
for(typename recv_overlap_type::baseSequence::iterator p_iter = recvPoints->begin(); p_iter != recvPoints->end(); ++p_iter) {
const Obj<typename recv_overlap_type::coneSequence>& ranks = recvOverlap->cone(*p_iter);
const typename recv_overlap_type::target_type& localPoint = *p_iter;
for(typename recv_overlap_type::coneSequence::iterator r_iter = ranks->begin(); r_iter != ranks->end(); ++r_iter) {
const typename recv_overlap_type::target_type& remotePoint = r_iter.color();
const int rank = *r_iter;
const Obj<typename recv_section_type::section_type>& section = recvSection->getSection(rank);
const typename recv_section_type::value_type *values = section->restrictPoint(remotePoint);
if (section->getFiberDimension(remotePoint) == 0) continue;
if (debug) {std::cout << "["<<order->commRank()<<"] local point " << localPoint << " remote point " << remotePoint<<"("<<rank<<")" << " offset " << values[0].prefix << " and size " << values[0].index << std::endl;}
if (values[0].index == 0) continue;
if (values[0].prefix >= 0) {
if (order->isLocal(localPoint)) {
if (!allowDuplicates) {
ostringstream msg;
msg << "["<<order->commRank()<<"]Multiple indices for local point " << localPoint << " remote point " << remotePoint << " from " << rank << " with index " << values[0];
throw ALE::Exception(msg.str().c_str());
}
continue;
}
const oValue_type val(-(values[0].prefix+1), values[0].index);
order->updatePoint(localPoint, &val);
} else {
if (order->isLocal(localPoint)) continue;
order->updatePoint(localPoint, values);
}
}
}
#endif
}
// Construct a full global numbering
template<typename Iterator>
void constructNumbering(const Obj<numbering_type>& numbering, const Obj<send_overlap_type>& sendOverlap, const Obj<recv_overlap_type>& recvOverlap, const Iterator& pointsBegin, const Iterator& pointsEnd) {
this->constructLocalNumbering(numbering, sendOverlap, pointsBegin, pointsEnd);
this->calculateOffsets(numbering);
this->updateOrder(numbering, pointsBegin, pointsEnd);
this->completeNumbering(numbering, sendOverlap, recvOverlap);
}
// Construct a full global order
template<typename Iterator, typename Section>
void constructOrder(const Obj<order_type>& order, const Obj<send_overlap_type>& sendOverlap, const Obj<recv_overlap_type>& recvOverlap, const Iterator& pointsBegin, const Iterator& pointsEnd, const Obj<Section>& section, const int space = -1, const Obj<label_type>& label = NULL) {
this->constructLocalOrder(order, sendOverlap, pointsBegin, pointsEnd, section, space, false, label);
this->calculateOffsets(order);
this->updateOrder(order, pointsBegin, pointsEnd);
this->completeOrder(order, sendOverlap, recvOverlap);
}
template<typename Iterator, typename Section>
void constructOrderBC(const Obj<order_type>& order, const Obj<send_overlap_type>& sendOverlap, const Obj<recv_overlap_type>& recvOverlap, const Iterator& pointsBegin, const Iterator& pointsEnd, const Obj<Section>& section, const int space = -1, const Obj<label_type>& label = NULL) {
this->constructLocalOrder(order, sendOverlap, pointsBegin, pointsEnd, section, space, true, label);
this->calculateOffsets(order);
this->updateOrder(order, pointsBegin, pointsEnd);
this->completeOrder(order, sendOverlap, recvOverlap);
}
public:
// Construct the inverse map from numbers to points
// If we really need this, then we should consider using a label
void constructInverseOrder(const Obj<numbering_type>& numbering) {
const typename numbering_type::chart_type& chart = numbering->getChart();
for(typename numbering_type::chart_type::iterator p_iter = chart.begin(); p_iter != chart.end(); ++p_iter) {
numbering->setPoint(numbering->getIndex(*p_iter), *p_iter);
}
}
public: // Real interface
template<typename ABundle_>
const Obj<numbering_type>& getLocalNumbering(const Obj<ABundle_>& bundle, const int depth) {
if ((this->_localNumberings.find(bundle.ptr()) == this->_localNumberings.end()) ||
(this->_localNumberings[bundle.ptr()].find("depth") == this->_localNumberings[bundle.ptr()].end()) ||
(this->_localNumberings[bundle.ptr()]["depth"].find(depth) == this->_localNumberings[bundle.ptr()]["depth"].end())) {
Obj<numbering_type> numbering = new numbering_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = new send_overlap_type(bundle->comm(), bundle->debug());
this->constructLocalNumbering(numbering, sendOverlap, bundle->depthStratum(depth)->begin(), bundle->depthStratum(depth)->end());
if (this->_debug) {std::cout << "Creating new local numbering: ptr " << bundle.ptr() << " depth " << depth << std::endl;}
this->_localNumberings[bundle.ptr()]["depth"][depth] = numbering;
} else {
if (this->_debug) {std::cout << "Using old local numbering: ptr " << bundle.ptr() << " depth " << depth << std::endl;}
}
return this->_localNumberings[bundle.ptr()]["depth"][depth];
}
template<typename ABundle_>
const Obj<numbering_type>& getNumbering(const Obj<ABundle_>& bundle, const int depth) {
if ((this->_numberings.find(bundle.ptr()) == this->_numberings.end()) ||
(this->_numberings[bundle.ptr()].find("depth") == this->_numberings[bundle.ptr()].end()) ||
(this->_numberings[bundle.ptr()]["depth"].find(depth) == this->_numberings[bundle.ptr()]["depth"].end())) {
bundle->constructOverlap();
Obj<numbering_type> numbering = new numbering_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = bundle->getSendOverlap();
Obj<recv_overlap_type> recvOverlap = bundle->getRecvOverlap();
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Creating new numbering: fixed depth value " << depth << std::endl;}
if (depth == -1) {
this->constructNumbering(numbering, sendOverlap, recvOverlap, bundle->getSieve()->getChart().begin(), bundle->getSieve()->getChart().end());
} else {
this->constructNumbering(numbering, sendOverlap, recvOverlap, bundle->depthStratum(depth)->begin(), bundle->depthStratum(depth)->end());
}
this->_numberings[bundle.ptr()]["depth"][depth] = numbering;
} else {
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Using old numbering: fixed depth value " << depth << std::endl;}
}
return this->_numberings[bundle.ptr()]["depth"][depth];
}
template<typename ABundle_>
const Obj<numbering_type>& getNumbering(const Obj<ABundle_>& bundle, const std::string& labelname, const int value) {
if ((this->_numberings.find(bundle.ptr()) == this->_numberings.end()) ||
(this->_numberings[bundle.ptr()].find(labelname) == this->_numberings[bundle.ptr()].end()) ||
(this->_numberings[bundle.ptr()][labelname].find(value) == this->_numberings[bundle.ptr()][labelname].end())) {
bundle->constructOverlap();
Obj<numbering_type> numbering = new numbering_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = bundle->getSendOverlap();
Obj<recv_overlap_type> recvOverlap = bundle->getRecvOverlap();
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Creating new numbering: " << labelname << " value " << value << std::endl;}
this->constructNumbering(numbering, sendOverlap, recvOverlap, bundle->getLabelStratum(labelname, value)->begin(), bundle->getLabelStratum(labelname, value)->end());
this->_numberings[bundle.ptr()][labelname][value] = numbering;
} else {
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Using old numbering: " << labelname << " value " << value << std::endl;}
}
return this->_numberings[bundle.ptr()][labelname][value];
}
template<typename ABundle_, typename Section_>
const Obj<order_type>& getLocalOrder(const Obj<ABundle_>& bundle, const std::string& name, const Obj<Section_>& section, const int space = -1, const Obj<label_type>& label = NULL) {
if ((this->_localOrders.find(bundle.ptr()) == this->_localOrders.end()) ||
(this->_localOrders[bundle.ptr()].find(name) == this->_localOrders[bundle.ptr()].end())) {
Obj<order_type> order = new order_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = bundle->getSendOverlap();
Obj<recv_overlap_type> recvOverlap = bundle->getRecvOverlap();
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Creating new local order: " << name << std::endl;}
this->constructLocalOrder(order, sendOverlap, section->getChart().begin(), section->getChart().end(), section, space, false, label);
this->_localOrders[bundle.ptr()][name] = order;
} else {
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Using old local order: " << name << std::endl;}
}
return this->_localOrders[bundle.ptr()][name];
}
template<typename ABundle_, typename Section_>
const Obj<order_type>& getGlobalOrder(const Obj<ABundle_>& bundle, const std::string& name, const Obj<Section_>& section, const int space = -1, const Obj<label_type>& label = NULL) {
if ((this->_orders.find(bundle.ptr()) == this->_orders.end()) ||
(this->_orders[bundle.ptr()].find(name) == this->_orders[bundle.ptr()].end())) {
bundle->constructOverlap();
Obj<order_type> order = new order_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = bundle->getSendOverlap();
Obj<recv_overlap_type> recvOverlap = bundle->getRecvOverlap();
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Creating new global order: " << name << std::endl;}
this->constructOrder(order, sendOverlap, recvOverlap, section->getChart().begin(), section->getChart().end(), section, space, label);
this->_orders[bundle.ptr()][name] = order;
} else {
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Using old global order: " << name << std::endl;}
}
return this->_orders[bundle.ptr()][name];
}
template<typename ABundle_, typename Iterator_, typename Section_>
const Obj<order_type>& getGlobalOrder(const Obj<ABundle_>& bundle, const std::string& name, const Iterator_& pointsBegin, const Iterator_& pointsEnd, const Obj<Section_>& section, const int space = -1, const Obj<label_type>& label = NULL) {
if ((this->_orders.find(bundle.ptr()) == this->_orders.end()) ||
(this->_orders[bundle.ptr()].find(name) == this->_orders[bundle.ptr()].end())) {
bundle->constructOverlap();
Obj<order_type> order = new order_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = bundle->getSendOverlap();
Obj<recv_overlap_type> recvOverlap = bundle->getRecvOverlap();
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Creating new global order: " << name << std::endl;}
this->constructOrder(order, sendOverlap, recvOverlap, pointsBegin, pointsEnd, section, space, label);
this->_orders[bundle.ptr()][name] = order;
} else {
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Using old global order: " << name << std::endl;}
}
return this->_orders[bundle.ptr()][name];
}
template<typename ABundle_, typename Section_>
const Obj<order_type>& getGlobalOrderWithBC(const Obj<ABundle_>& bundle, const std::string& name, const Obj<Section_>& section, const int space = -1, const Obj<label_type>& label = NULL) {
if ((this->_orders.find(bundle.ptr()) == this->_orders.end()) ||
(this->_orders[bundle.ptr()].find(name) == this->_orders[bundle.ptr()].end())) {
bundle->constructOverlap();
Obj<order_type> order = new order_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = bundle->getSendOverlap();
Obj<recv_overlap_type> recvOverlap = bundle->getRecvOverlap();
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Creating new global order: " << name << std::endl;}
this->constructOrderBC(order, sendOverlap, recvOverlap, section->getChart().begin(), section->getChart().end(), section, space, label);
this->_orders[bundle.ptr()][name] = order;
} else {
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Using old global order: " << name << std::endl;}
}
return this->_orders[bundle.ptr()][name];
}
template<typename ABundle_, typename Iterator_, typename Section_>
const Obj<order_type>& getGlobalOrderWithBC(const Obj<ABundle_>& bundle, const std::string& name, const Iterator_& pointsBegin, const Iterator_& pointsEnd, const Obj<Section_>& section, const int space = -1, const Obj<label_type>& label = NULL) {
if ((this->_ordersBC.find(bundle.ptr()) == this->_ordersBC.end()) ||
(this->_ordersBC[bundle.ptr()].find(name) == this->_ordersBC[bundle.ptr()].end())) {
bundle->constructOverlap();
Obj<order_type> order = new order_type(bundle->comm(), bundle->debug());
Obj<send_overlap_type> sendOverlap = bundle->getSendOverlap();
Obj<recv_overlap_type> recvOverlap = bundle->getRecvOverlap();
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Creating new global order: " << name << std::endl;}
this->constructOrderBC(order, sendOverlap, recvOverlap, pointsBegin, pointsEnd, section, space, label);
this->_orders[bundle.ptr()][name] = order;
} else {
if (this->_debug) {std::cout << "["<<bundle->commRank()<<"]Using old global order: " << name << std::endl;}
}
return this->_orders[bundle.ptr()][name];
}
template<typename ABundle_>
void setGlobalOrder(const Obj<ABundle_>& bundle, const std::string& name, const Obj<order_type>& order) {
this->_orders[bundle.ptr()][name] = order;
}
};
}
#endif
| [
"ross.c.brodie@icloud.com"
] | ross.c.brodie@icloud.com |
21c63c287436c839173bb4e071cea4b357150dbe | 05e1f94ae1a5513a222d38dfe4c3c6737cb84251 | /Mulberry/branches/users/kenneth_porter/msvs10/Sources_Common/Mail/Filtering/CFilterItem.cp | ada76158e6614b90a3de1f76982f57f89aa32238 | [
"Apache-2.0"
] | permissive | eskilblomfeldt/mulberry-svn | 16ca9d4d6ec05cbbbd18045c7b59943b0aca9335 | 7ed26b61244e47d4d4d50a1c7cc2d31efa548ad7 | refs/heads/master | 2020-05-20T12:35:42.340160 | 2014-12-24T18:03:50 | 2014-12-24T18:03:50 | 29,127,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,554 | cp | /*
Copyright (c) 2007 Cyrus Daboo. 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.
*/
// Source for CFilter class
#include "CFilterItem.h"
#include "CActionItem.h"
#include "CFilterManager.h"
#include "CMbox.h"
#include "CPreferences.h"
#include "CStringUtils.h"
#include "char_stream.h"
#include <algorithm>
#include <iterator>
#include <memory>
extern const char* cSpace;
extern const char* cValueBoolTrue;
extern const char* cValueBoolFalse;
static unsigned long sUID_Counter = 1;
CFilterItem::CFilterItem()
{
mUID = sUID_Counter++;
mType = eLocal;
mManual = true;
mUseScript = false;
mCriteria = NULL;
mActions = NULL;
mStop = false;
}
CFilterItem::CFilterItem(EType type)
{
mUID = sUID_Counter++;
mType = type;
mManual = false;
mUseScript = false;
mCriteria = NULL;
mActions = NULL;
mStop = false;
}
void CFilterItem::_copy(const CFilterItem& copy)
{
mUID = copy.mUID;
mType = copy.mType;
mName = copy.mName;
mManual = copy.mManual;
mUseScript = copy.mUseScript;
mCriteria = copy.mCriteria ? new CSearchItem(*copy.mCriteria) : NULL;
mActions = copy.mActions ? new CActionItemList(*copy.mActions) : NULL;
mScript = copy.mScript;
mStop = copy.mStop;
}
void CFilterItem::_tidy()
{
delete mCriteria;
mCriteria = NULL;
delete mActions;
mActions = NULL;
}
void CFilterItem::SetUseScript(bool script)
{
if (mType == eSIEVE)
{
// Convert SIEVE script
if (mUseScript && !script)
{
mScript = cdstring::null_str;
mUseScript = false;
}
else if (!mUseScript && script)
{
// Generate the current script
std::ostrstream out;
GenerateSIEVEScript(out, eEndl_Auto);
out << std::ends;
mScript = out.str();
out.freeze(false);
// Remove items
SetCriteria(NULL);
SetActions(NULL);
mUseScript = true;
}
}
else
mUseScript = false;
}
// Make sure actions are valid
bool CFilterItem::CheckActions() const
{
if (!mActions)
return true;
// Check each action
for(CActionItemList::iterator iter = mActions->begin(); iter != mActions->end(); iter++)
{
// Return false if any one fails
if (!(*iter)->CheckAction())
return false;
}
return true;
}
// Rename account
void CFilterItem::RenameAccount(const cdstring& old_acct, const cdstring& new_acct)
{
if (!mActions)
return;
// Change references to this target
for(CActionItemList::iterator iter = mActions->begin(); iter != mActions->end(); iter++)
(*iter)->RenameAccount(old_acct, new_acct);
}
// Delete account
void CFilterItem::DeleteAccount(const cdstring& old_acct)
{
if (!mActions)
return;
// Change references to this target
for(CActionItemList::iterator iter = mActions->begin(); iter != mActions->end(); )
{
if ((*iter)->DeleteAccount(old_acct))
{
iter = mActions->erase(iter);
continue;
}
iter++;
}
}
// Identity change
void CFilterItem::RenameIdentity(const cdstring& old_id, const cdstring& new_id)
{
if (!mActions)
return;
// Change references to this target
for(CActionItemList::iterator iter = mActions->begin(); iter != mActions->end(); iter++)
(*iter)->RenameIdentity(old_id, new_id);
}
// Identity deleted
void CFilterItem::DeleteIdentity(const cdstring& old_id)
{
if (!mActions)
return;
// Change references to this target
for(CActionItemList::iterator iter = mActions->begin(); iter != mActions->end(); )
{
if ((*iter)->DeleteIdentity(old_id))
{
iter = mActions->erase(iter);
continue;
}
iter++;
}
}
void CFilterItem::Execute(CMbox* mbox, const ulvector* selected, const CSearchItem* andit, ulvector& exclude)
{
// Only if valid
if (!mCriteria || !mActions)
return;
// Log
if (CPreferences::sPrefs->GetFilterManager()->DoLog())
{
cdstring what(" Using filter: ");
what += mName;
CPreferences::sPrefs->GetFilterManager()->Log(what);
}
ulvector uids;
// Look for selected only
if (mCriteria->GetType() == CSearchItem::eSelected)
{
if ((selected == NULL) || selected->empty())
{
// Log
if (CPreferences::sPrefs->GetFilterManager()->DoLog())
CPreferences::sPrefs->GetFilterManager()->Log(" No matching messages");
return;
}
// Use all selected ones
uids = *selected;
}
else if (andit || (mCriteria->GetType() != CSearchItem::eAll) || !selected || !selected->size())
{
// Modified criteria
std::auto_ptr<CSearchItem> criteria;
// Intersect with selected messages
if (selected && selected->size())
{
CSearchItemList* items = new CSearchItemList;
items->push_back(new CSearchItem(CSearchItem::eUID, *selected));
items->push_back(new CSearchItem(*mCriteria));
criteria.reset(new CSearchItem(CSearchItem::eAnd, items));
}
// Intersect with additional criteria
else if (andit)
{
CSearchItemList* items = new CSearchItemList;
items->push_back(new CSearchItem(*andit));
items->push_back(new CSearchItem(*mCriteria));
criteria.reset(new CSearchItem(CSearchItem::eAnd, items));
}
// Do search using criteria
mbox->Search(criteria.get() ? criteria.get() : mCriteria, &uids, true, true);
}
else
// Use all selected ones
uids = *selected;
// Only bother if something found
if (uids.empty())
{
// Log
if (CPreferences::sPrefs->GetFilterManager()->DoLog())
CPreferences::sPrefs->GetFilterManager()->Log(" No matching messages");
return;
}
// Subtract excluded
ulvector process;
std::set_difference(uids.begin(), uids.end(), exclude.begin(), exclude.end(), std::back_inserter<ulvector>(process));
// Only bother if something left
if (process.empty())
{
// Log
if (CPreferences::sPrefs->GetFilterManager()->DoLog())
CPreferences::sPrefs->GetFilterManager()->Log(" No matching messages");
return;
}
else if (CPreferences::sPrefs->GetFilterManager()->DoLog())
{
cdstring what(" Matched messages: ");
what += cdstring((unsigned long) process.size());
CPreferences::sPrefs->GetFilterManager()->Log(what);
what = " Matched message UIDs: ";
for(ulvector::const_iterator iter = process.begin(); iter != process.end(); iter++)
{
if (iter != process.begin())
what += ",";
what += cdstring(*iter);
}
CPreferences::sPrefs->GetFilterManager()->Log(what);
}
// May need to force stop if error occurs
bool stop_it = mStop;
// Execute each action
try
{
for(CActionItemList::const_iterator iter = mActions->begin(); iter != mActions->end(); iter++)
(*iter)->Execute(mbox, process);
}
catch (...)
{
CLOG_LOGCATCH(...);
// Catch all errors and stop further processing
// Really this needs to know which messages suceeded and which failed but that's hard!
stop_it = true;
// Log
if (CPreferences::sPrefs->GetFilterManager()->DoLog())
CPreferences::sPrefs->GetFilterManager()->Log(" Error while processing matched messages");
}
// Stop further processing if matched
if (stop_it)
{
ulvector temp;
std::set_union(uids.begin(), uids.end(), exclude.begin(), exclude.end(), std::back_inserter<ulvector>(temp));
exclude = temp;
// Log
if (CPreferences::sPrefs->GetFilterManager()->DoLog())
CPreferences::sPrefs->GetFilterManager()->Log(" No more processing on matched messages");
}
}
void CFilterItem::GetSIEVEExtensions(CFilterProtocol::EExtension& ext) const
{
if (mUseScript)
{
// Must assume that the user manually inserts the requires line
}
else
{
if (!mCriteria || !mActions)
return;
// Test each action
for(CActionItemList::const_iterator iter = mActions->begin(); iter != mActions->end(); iter++)
(*iter)->GetSIEVEExtensions(ext);
}
}
void CFilterItem::GenerateSIEVEScript(std::ostream& out, EEndl line_end) const
{
if (mUseScript)
{
out << "# Generated from text" << get_endl(line_end);
out << mScript << get_endl(line_end);
}
else
{
if (!mCriteria || !mActions)
return;
out << "# Generated from GUI" << get_endl(line_end);
// Write the criteria
out << "if ";
mCriteria->GenerateSIEVEScript(out);
out << " {" << get_endl(line_end);
for(CActionItemList::const_iterator iter = mActions->begin(); iter != mActions->end(); iter++)
{
out << "\t";
(*iter)->GenerateSIEVEScript(out);
out << get_endl(line_end);
}
if (mStop)
out << "\tstop;" << get_endl(line_end);
out << "}" << get_endl(line_end);
}
}
const char* cTypeDescriptors[] = {"Mulberry", "SIEVE", NULL};
// Get text expansion for prefs
cdstring CFilterItem::GetInfo(void) const
{
cdstring all;
cdstring temp = cTypeDescriptors[mType];
temp.quote();
all += temp;
all += cSpace;
temp = mName;
temp.quote();
temp.ConvertFromOS();
all += temp;
all += cSpace;
all += (mManual ? cValueBoolTrue : cValueBoolFalse);
all += cSpace;
all += (mUseScript ? cValueBoolTrue : cValueBoolFalse);
all += cSpace;
if (mCriteria)
all += mCriteria->GetInfo();
else
all += "";
all += cSpace;
if (mActions)
all += mActions->GetInfo();
else
all += "";
all += cSpace;
temp = mScript;
temp.quote();
temp.ConvertFromOS();
all += temp;
all += cSpace;
all += (mStop ? cValueBoolTrue : cValueBoolFalse);
return all;
}
// Convert text to items
bool CFilterItem::SetInfo(char_stream& txt, NumVersion vers_prefs)
{
char* p = txt.get();
mType = static_cast<EType>(::strindexfind(p, cTypeDescriptors, eLocal));
txt.get(mName, true);
txt.get(mManual);
txt.get(mUseScript);
if (!mUseScript)
{
CSearchItem* criteria = new CSearchItem;
criteria->SetInfo(txt);
SetCriteria(criteria);
}
else
SetCriteria(NULL);
if (!mUseScript)
{
CActionItemList* actions = new CActionItemList;
actions->SetInfo(txt, vers_prefs);
SetActions(actions);
}
else
SetActions(NULL);
txt.get(mScript, true);
txt.get(mStop);
return true;
}
// Replace with details from another filter
void CFilterItem::ReplaceWith(const CFilterItem* replace)
{
if (replace == NULL)
return;
// Copy important bits
SetUseScript(replace->GetUseScript());
SetCriteria(new CSearchItem(*replace->GetCriteria()));
SetActions(new CActionItemList(*replace->GetActions()));
SetScript(replace->GetScript());
SetStop(replace->Stop());
}
| [
"svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132"
] | svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132 |
0b35966ad48c6d1e5e416b0a63ca6f342c31ad42 | ccd61b105ef18ff40ca9e29773c9b63a0d1f95bb | /llvm/tools/clang/tools/libclang/CXCursor.cpp | 22a841f4f54ca144a13ba5c4a864ff9316b68a4c | [
"NCSA"
] | permissive | jeffyouwang/summer2012 | 1a99d992a84be1895369c287e727ff682effcd3f | aef200d2540896ed68feb909a1720b3226a3c417 | refs/heads/master | 2020-04-06T22:56:22.255634 | 2012-05-08T20:55:02 | 2012-05-08T20:55:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,789 | cpp | //===- CXCursor.cpp - Routines for manipulating CXCursors -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines routines for manipulating CXCursors. It should be the
// only file that has internal knowledge of the encoding of the data in
// CXCursor.
//
//===----------------------------------------------------------------------===//
#include "CXTranslationUnit.h"
#include "CXCursor.h"
#include "CXString.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang-c/Index.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
using namespace cxcursor;
CXCursor cxcursor::MakeCXCursorInvalid(CXCursorKind K, CXTranslationUnit TU) {
assert(K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid);
CXCursor C = { K, 0, { 0, 0, TU } };
return C;
}
static CXCursorKind GetCursorKind(const Attr *A) {
assert(A && "Invalid arguments!");
switch (A->getKind()) {
default: break;
case attr::IBAction: return CXCursor_IBActionAttr;
case attr::IBOutlet: return CXCursor_IBOutletAttr;
case attr::IBOutletCollection: return CXCursor_IBOutletCollectionAttr;
case attr::Final: return CXCursor_CXXFinalAttr;
case attr::Override: return CXCursor_CXXOverrideAttr;
case attr::Annotate: return CXCursor_AnnotateAttr;
case attr::AsmLabel: return CXCursor_AsmLabelAttr;
}
return CXCursor_UnexposedAttr;
}
CXCursor cxcursor::MakeCXCursor(const Attr *A, Decl *Parent,
CXTranslationUnit TU) {
assert(A && Parent && TU && "Invalid arguments!");
CXCursor C = { GetCursorKind(A), 0, { Parent, (void*)A, TU } };
return C;
}
CXCursor cxcursor::MakeCXCursor(Decl *D, CXTranslationUnit TU,
SourceRange RegionOfInterest,
bool FirstInDeclGroup) {
assert(D && TU && "Invalid arguments!");
CXCursorKind K = getCursorKindForDecl(D);
if (K == CXCursor_ObjCClassMethodDecl ||
K == CXCursor_ObjCInstanceMethodDecl) {
int SelectorIdIndex = -1;
// Check if cursor points to a selector id.
if (RegionOfInterest.isValid() &&
RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) {
SmallVector<SourceLocation, 16> SelLocs;
cast<ObjCMethodDecl>(D)->getSelectorLocs(SelLocs);
SmallVector<SourceLocation, 16>::iterator
I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin());
if (I != SelLocs.end())
SelectorIdIndex = I - SelLocs.begin();
}
CXCursor C = { K, SelectorIdIndex,
{ D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }};
return C;
}
CXCursor C = { K, 0, { D, (void*)(intptr_t) (FirstInDeclGroup ? 1 : 0), TU }};
return C;
}
CXCursor cxcursor::MakeCXCursor(Stmt *S, Decl *Parent, CXTranslationUnit TU,
SourceRange RegionOfInterest) {
assert(S && TU && "Invalid arguments!");
CXCursorKind K = CXCursor_NotImplemented;
switch (S->getStmtClass()) {
case Stmt::NoStmtClass:
break;
case Stmt::CaseStmtClass:
K = CXCursor_CaseStmt;
break;
case Stmt::DefaultStmtClass:
K = CXCursor_DefaultStmt;
break;
case Stmt::IfStmtClass:
K = CXCursor_IfStmt;
break;
case Stmt::SwitchStmtClass:
K = CXCursor_SwitchStmt;
break;
case Stmt::WhileStmtClass:
K = CXCursor_WhileStmt;
break;
case Stmt::DoStmtClass:
K = CXCursor_DoStmt;
break;
case Stmt::ForStmtClass:
K = CXCursor_ForStmt;
break;
case Stmt::GotoStmtClass:
K = CXCursor_GotoStmt;
break;
case Stmt::IndirectGotoStmtClass:
K = CXCursor_IndirectGotoStmt;
break;
case Stmt::ContinueStmtClass:
K = CXCursor_ContinueStmt;
break;
case Stmt::BreakStmtClass:
K = CXCursor_BreakStmt;
break;
case Stmt::ReturnStmtClass:
K = CXCursor_ReturnStmt;
break;
case Stmt::AsmStmtClass:
K = CXCursor_AsmStmt;
break;
case Stmt::ObjCAtTryStmtClass:
K = CXCursor_ObjCAtTryStmt;
break;
case Stmt::ObjCAtCatchStmtClass:
K = CXCursor_ObjCAtCatchStmt;
break;
case Stmt::ObjCAtFinallyStmtClass:
K = CXCursor_ObjCAtFinallyStmt;
break;
case Stmt::ObjCAtThrowStmtClass:
K = CXCursor_ObjCAtThrowStmt;
break;
case Stmt::ObjCAtSynchronizedStmtClass:
K = CXCursor_ObjCAtSynchronizedStmt;
break;
case Stmt::ObjCAutoreleasePoolStmtClass:
K = CXCursor_ObjCAutoreleasePoolStmt;
break;
case Stmt::ObjCForCollectionStmtClass:
K = CXCursor_ObjCForCollectionStmt;
break;
case Stmt::CXXCatchStmtClass:
K = CXCursor_CXXCatchStmt;
break;
case Stmt::CXXTryStmtClass:
K = CXCursor_CXXTryStmt;
break;
case Stmt::CXXForRangeStmtClass:
K = CXCursor_CXXForRangeStmt;
break;
case Stmt::SEHTryStmtClass:
K = CXCursor_SEHTryStmt;
break;
case Stmt::SEHExceptStmtClass:
K = CXCursor_SEHExceptStmt;
break;
case Stmt::SEHFinallyStmtClass:
K = CXCursor_SEHFinallyStmt;
break;
case Stmt::ArrayTypeTraitExprClass:
case Stmt::AsTypeExprClass:
case Stmt::AtomicExprClass:
case Stmt::BinaryConditionalOperatorClass:
case Stmt::BinaryTypeTraitExprClass:
case Stmt::TypeTraitExprClass:
case Stmt::CXXBindTemporaryExprClass:
case Stmt::CXXDefaultArgExprClass:
case Stmt::CXXScalarValueInitExprClass:
case Stmt::CXXUuidofExprClass:
case Stmt::ChooseExprClass:
case Stmt::DesignatedInitExprClass:
case Stmt::ExprWithCleanupsClass:
case Stmt::ExpressionTraitExprClass:
case Stmt::ExtVectorElementExprClass:
case Stmt::ImplicitCastExprClass:
case Stmt::ImplicitValueInitExprClass:
case Stmt::MaterializeTemporaryExprClass:
case Stmt::ObjCIndirectCopyRestoreExprClass:
case Stmt::OffsetOfExprClass:
case Stmt::ParenListExprClass:
case Stmt::PredefinedExprClass:
case Stmt::ShuffleVectorExprClass:
case Stmt::UnaryExprOrTypeTraitExprClass:
case Stmt::UnaryTypeTraitExprClass:
case Stmt::VAArgExprClass:
case Stmt::ObjCArrayLiteralClass:
case Stmt::ObjCDictionaryLiteralClass:
case Stmt::ObjCBoxedExprClass:
case Stmt::ObjCSubscriptRefExprClass:
K = CXCursor_UnexposedExpr;
break;
case Stmt::OpaqueValueExprClass:
if (Expr *Src = cast<OpaqueValueExpr>(S)->getSourceExpr())
return MakeCXCursor(Src, Parent, TU, RegionOfInterest);
K = CXCursor_UnexposedExpr;
break;
case Stmt::PseudoObjectExprClass:
return MakeCXCursor(cast<PseudoObjectExpr>(S)->getSyntacticForm(),
Parent, TU, RegionOfInterest);
case Stmt::CompoundStmtClass:
K = CXCursor_CompoundStmt;
break;
case Stmt::NullStmtClass:
K = CXCursor_NullStmt;
break;
case Stmt::LabelStmtClass:
K = CXCursor_LabelStmt;
break;
case Stmt::AttributedStmtClass:
K = CXCursor_UnexposedStmt;
break;
case Stmt::DeclStmtClass:
K = CXCursor_DeclStmt;
break;
case Stmt::IntegerLiteralClass:
K = CXCursor_IntegerLiteral;
break;
case Stmt::FloatingLiteralClass:
K = CXCursor_FloatingLiteral;
break;
case Stmt::ImaginaryLiteralClass:
K = CXCursor_ImaginaryLiteral;
break;
case Stmt::StringLiteralClass:
K = CXCursor_StringLiteral;
break;
case Stmt::CharacterLiteralClass:
K = CXCursor_CharacterLiteral;
break;
case Stmt::ParenExprClass:
K = CXCursor_ParenExpr;
break;
case Stmt::UnaryOperatorClass:
K = CXCursor_UnaryOperator;
break;
case Stmt::CXXNoexceptExprClass:
K = CXCursor_UnaryExpr;
break;
case Stmt::ArraySubscriptExprClass:
K = CXCursor_ArraySubscriptExpr;
break;
case Stmt::BinaryOperatorClass:
K = CXCursor_BinaryOperator;
break;
case Stmt::CompoundAssignOperatorClass:
K = CXCursor_CompoundAssignOperator;
break;
case Stmt::ConditionalOperatorClass:
K = CXCursor_ConditionalOperator;
break;
case Stmt::CStyleCastExprClass:
K = CXCursor_CStyleCastExpr;
break;
case Stmt::CompoundLiteralExprClass:
K = CXCursor_CompoundLiteralExpr;
break;
case Stmt::InitListExprClass:
K = CXCursor_InitListExpr;
break;
case Stmt::AddrLabelExprClass:
K = CXCursor_AddrLabelExpr;
break;
case Stmt::StmtExprClass:
K = CXCursor_StmtExpr;
break;
case Stmt::GenericSelectionExprClass:
K = CXCursor_GenericSelectionExpr;
break;
case Stmt::GNUNullExprClass:
K = CXCursor_GNUNullExpr;
break;
case Stmt::CXXStaticCastExprClass:
K = CXCursor_CXXStaticCastExpr;
break;
case Stmt::CXXDynamicCastExprClass:
K = CXCursor_CXXDynamicCastExpr;
break;
case Stmt::CXXReinterpretCastExprClass:
K = CXCursor_CXXReinterpretCastExpr;
break;
case Stmt::CXXConstCastExprClass:
K = CXCursor_CXXConstCastExpr;
break;
case Stmt::CXXFunctionalCastExprClass:
K = CXCursor_CXXFunctionalCastExpr;
break;
case Stmt::CXXTypeidExprClass:
K = CXCursor_CXXTypeidExpr;
break;
case Stmt::CXXBoolLiteralExprClass:
K = CXCursor_CXXBoolLiteralExpr;
break;
case Stmt::CXXNullPtrLiteralExprClass:
K = CXCursor_CXXNullPtrLiteralExpr;
break;
case Stmt::CXXThisExprClass:
K = CXCursor_CXXThisExpr;
break;
case Stmt::CXXThrowExprClass:
K = CXCursor_CXXThrowExpr;
break;
case Stmt::CXXNewExprClass:
K = CXCursor_CXXNewExpr;
break;
case Stmt::CXXDeleteExprClass:
K = CXCursor_CXXDeleteExpr;
break;
case Stmt::ObjCStringLiteralClass:
K = CXCursor_ObjCStringLiteral;
break;
case Stmt::ObjCEncodeExprClass:
K = CXCursor_ObjCEncodeExpr;
break;
case Stmt::ObjCSelectorExprClass:
K = CXCursor_ObjCSelectorExpr;
break;
case Stmt::ObjCProtocolExprClass:
K = CXCursor_ObjCProtocolExpr;
break;
case Stmt::ObjCBoolLiteralExprClass:
K = CXCursor_ObjCBoolLiteralExpr;
break;
case Stmt::ObjCBridgedCastExprClass:
K = CXCursor_ObjCBridgedCastExpr;
break;
case Stmt::BlockExprClass:
K = CXCursor_BlockExpr;
break;
case Stmt::PackExpansionExprClass:
K = CXCursor_PackExpansionExpr;
break;
case Stmt::SizeOfPackExprClass:
K = CXCursor_SizeOfPackExpr;
break;
case Stmt::DeclRefExprClass:
case Stmt::DependentScopeDeclRefExprClass:
case Stmt::SubstNonTypeTemplateParmExprClass:
case Stmt::SubstNonTypeTemplateParmPackExprClass:
case Stmt::UnresolvedLookupExprClass:
K = CXCursor_DeclRefExpr;
break;
case Stmt::CXXDependentScopeMemberExprClass:
case Stmt::CXXPseudoDestructorExprClass:
case Stmt::MemberExprClass:
case Stmt::ObjCIsaExprClass:
case Stmt::ObjCIvarRefExprClass:
case Stmt::ObjCPropertyRefExprClass:
case Stmt::UnresolvedMemberExprClass:
K = CXCursor_MemberRefExpr;
break;
case Stmt::CallExprClass:
case Stmt::CXXOperatorCallExprClass:
case Stmt::CXXMemberCallExprClass:
case Stmt::CUDAKernelCallExprClass:
case Stmt::CXXConstructExprClass:
case Stmt::CXXTemporaryObjectExprClass:
case Stmt::CXXUnresolvedConstructExprClass:
case Stmt::UserDefinedLiteralClass:
K = CXCursor_CallExpr;
break;
case Stmt::LambdaExprClass:
K = CXCursor_LambdaExpr;
break;
case Stmt::ObjCMessageExprClass: {
K = CXCursor_ObjCMessageExpr;
int SelectorIdIndex = -1;
// Check if cursor points to a selector id.
if (RegionOfInterest.isValid() &&
RegionOfInterest.getBegin() == RegionOfInterest.getEnd()) {
SmallVector<SourceLocation, 16> SelLocs;
cast<ObjCMessageExpr>(S)->getSelectorLocs(SelLocs);
SmallVector<SourceLocation, 16>::iterator
I=std::find(SelLocs.begin(), SelLocs.end(),RegionOfInterest.getBegin());
if (I != SelLocs.end())
SelectorIdIndex = I - SelLocs.begin();
}
CXCursor C = { K, 0, { Parent, S, TU } };
return getSelectorIdentifierCursor(SelectorIdIndex, C);
}
case Stmt::MSDependentExistsStmtClass:
K = CXCursor_UnexposedStmt;
break;
}
CXCursor C = { K, 0, { Parent, S, TU } };
return C;
}
CXCursor cxcursor::MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super,
SourceLocation Loc,
CXTranslationUnit TU) {
assert(Super && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_ObjCSuperClassRef, 0, { Super, RawLoc, TU } };
return C;
}
std::pair<ObjCInterfaceDecl *, SourceLocation>
cxcursor::getCursorObjCSuperClassRef(CXCursor C) {
assert(C.kind == CXCursor_ObjCSuperClassRef);
return std::make_pair(static_cast<ObjCInterfaceDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorObjCProtocolRef(const ObjCProtocolDecl *Proto,
SourceLocation Loc,
CXTranslationUnit TU) {
assert(Proto && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_ObjCProtocolRef, 0, { (void*)Proto, RawLoc, TU } };
return C;
}
std::pair<ObjCProtocolDecl *, SourceLocation>
cxcursor::getCursorObjCProtocolRef(CXCursor C) {
assert(C.kind == CXCursor_ObjCProtocolRef);
return std::make_pair(static_cast<ObjCProtocolDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorObjCClassRef(const ObjCInterfaceDecl *Class,
SourceLocation Loc,
CXTranslationUnit TU) {
// 'Class' can be null for invalid code.
if (!Class)
return MakeCXCursorInvalid(CXCursor_InvalidCode);
assert(TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_ObjCClassRef, 0, { (void*)Class, RawLoc, TU } };
return C;
}
std::pair<ObjCInterfaceDecl *, SourceLocation>
cxcursor::getCursorObjCClassRef(CXCursor C) {
assert(C.kind == CXCursor_ObjCClassRef);
return std::make_pair(static_cast<ObjCInterfaceDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorTypeRef(const TypeDecl *Type, SourceLocation Loc,
CXTranslationUnit TU) {
assert(Type && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_TypeRef, 0, { (void*)Type, RawLoc, TU } };
return C;
}
std::pair<TypeDecl *, SourceLocation>
cxcursor::getCursorTypeRef(CXCursor C) {
assert(C.kind == CXCursor_TypeRef);
return std::make_pair(static_cast<TypeDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorTemplateRef(const TemplateDecl *Template,
SourceLocation Loc,
CXTranslationUnit TU) {
assert(Template && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_TemplateRef, 0, { (void*)Template, RawLoc, TU } };
return C;
}
std::pair<TemplateDecl *, SourceLocation>
cxcursor::getCursorTemplateRef(CXCursor C) {
assert(C.kind == CXCursor_TemplateRef);
return std::make_pair(static_cast<TemplateDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorNamespaceRef(const NamedDecl *NS,
SourceLocation Loc,
CXTranslationUnit TU) {
assert(NS && (isa<NamespaceDecl>(NS) || isa<NamespaceAliasDecl>(NS)) && TU &&
"Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_NamespaceRef, 0, { (void*)NS, RawLoc, TU } };
return C;
}
std::pair<NamedDecl *, SourceLocation>
cxcursor::getCursorNamespaceRef(CXCursor C) {
assert(C.kind == CXCursor_NamespaceRef);
return std::make_pair(static_cast<NamedDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorVariableRef(const VarDecl *Var, SourceLocation Loc,
CXTranslationUnit TU) {
assert(Var && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_VariableRef, 0, { (void*)Var, RawLoc, TU } };
return C;
}
std::pair<VarDecl *, SourceLocation>
cxcursor::getCursorVariableRef(CXCursor C) {
assert(C.kind == CXCursor_VariableRef);
return std::make_pair(static_cast<VarDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorMemberRef(const FieldDecl *Field, SourceLocation Loc,
CXTranslationUnit TU) {
assert(Field && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_MemberRef, 0, { (void*)Field, RawLoc, TU } };
return C;
}
std::pair<FieldDecl *, SourceLocation>
cxcursor::getCursorMemberRef(CXCursor C) {
assert(C.kind == CXCursor_MemberRef);
return std::make_pair(static_cast<FieldDecl *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorCXXBaseSpecifier(const CXXBaseSpecifier *B,
CXTranslationUnit TU){
CXCursor C = { CXCursor_CXXBaseSpecifier, 0, { (void*)B, 0, TU } };
return C;
}
CXXBaseSpecifier *cxcursor::getCursorCXXBaseSpecifier(CXCursor C) {
assert(C.kind == CXCursor_CXXBaseSpecifier);
return static_cast<CXXBaseSpecifier*>(C.data[0]);
}
CXCursor cxcursor::MakePreprocessingDirectiveCursor(SourceRange Range,
CXTranslationUnit TU) {
CXCursor C = { CXCursor_PreprocessingDirective, 0,
{ reinterpret_cast<void *>(Range.getBegin().getRawEncoding()),
reinterpret_cast<void *>(Range.getEnd().getRawEncoding()),
TU }
};
return C;
}
SourceRange cxcursor::getCursorPreprocessingDirective(CXCursor C) {
assert(C.kind == CXCursor_PreprocessingDirective);
SourceRange Range = SourceRange(SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t> (C.data[0])),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t> (C.data[1])));
ASTUnit *TU = getCursorASTUnit(C);
return TU->mapRangeFromPreamble(Range);
}
CXCursor cxcursor::MakeMacroDefinitionCursor(MacroDefinition *MI,
CXTranslationUnit TU) {
CXCursor C = { CXCursor_MacroDefinition, 0, { MI, 0, TU } };
return C;
}
MacroDefinition *cxcursor::getCursorMacroDefinition(CXCursor C) {
assert(C.kind == CXCursor_MacroDefinition);
return static_cast<MacroDefinition *>(C.data[0]);
}
CXCursor cxcursor::MakeMacroExpansionCursor(MacroExpansion *MI,
CXTranslationUnit TU) {
CXCursor C = { CXCursor_MacroExpansion, 0, { MI, 0, TU } };
return C;
}
MacroExpansion *cxcursor::getCursorMacroExpansion(CXCursor C) {
assert(C.kind == CXCursor_MacroExpansion);
return static_cast<MacroExpansion *>(C.data[0]);
}
CXCursor cxcursor::MakeInclusionDirectiveCursor(InclusionDirective *ID,
CXTranslationUnit TU) {
CXCursor C = { CXCursor_InclusionDirective, 0, { ID, 0, TU } };
return C;
}
InclusionDirective *cxcursor::getCursorInclusionDirective(CXCursor C) {
assert(C.kind == CXCursor_InclusionDirective);
return static_cast<InclusionDirective *>(C.data[0]);
}
CXCursor cxcursor::MakeCursorLabelRef(LabelStmt *Label, SourceLocation Loc,
CXTranslationUnit TU) {
assert(Label && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
CXCursor C = { CXCursor_LabelRef, 0, { Label, RawLoc, TU } };
return C;
}
std::pair<LabelStmt*, SourceLocation>
cxcursor::getCursorLabelRef(CXCursor C) {
assert(C.kind == CXCursor_LabelRef);
return std::make_pair(static_cast<LabelStmt *>(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
CXCursor cxcursor::MakeCursorOverloadedDeclRef(OverloadExpr *E,
CXTranslationUnit TU) {
assert(E && TU && "Invalid arguments!");
OverloadedDeclRefStorage Storage(E);
void *RawLoc = reinterpret_cast<void *>(E->getNameLoc().getRawEncoding());
CXCursor C = {
CXCursor_OverloadedDeclRef, 0,
{ Storage.getOpaqueValue(), RawLoc, TU }
};
return C;
}
CXCursor cxcursor::MakeCursorOverloadedDeclRef(Decl *D,
SourceLocation Loc,
CXTranslationUnit TU) {
assert(D && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
OverloadedDeclRefStorage Storage(D);
CXCursor C = {
CXCursor_OverloadedDeclRef, 0,
{ Storage.getOpaqueValue(), RawLoc, TU }
};
return C;
}
CXCursor cxcursor::MakeCursorOverloadedDeclRef(TemplateName Name,
SourceLocation Loc,
CXTranslationUnit TU) {
assert(Name.getAsOverloadedTemplate() && TU && "Invalid arguments!");
void *RawLoc = reinterpret_cast<void *>(Loc.getRawEncoding());
OverloadedDeclRefStorage Storage(Name.getAsOverloadedTemplate());
CXCursor C = {
CXCursor_OverloadedDeclRef, 0,
{ Storage.getOpaqueValue(), RawLoc, TU }
};
return C;
}
std::pair<cxcursor::OverloadedDeclRefStorage, SourceLocation>
cxcursor::getCursorOverloadedDeclRef(CXCursor C) {
assert(C.kind == CXCursor_OverloadedDeclRef);
return std::make_pair(OverloadedDeclRefStorage::getFromOpaqueValue(C.data[0]),
SourceLocation::getFromRawEncoding(
reinterpret_cast<uintptr_t>(C.data[1])));
}
Decl *cxcursor::getCursorDecl(CXCursor Cursor) {
return (Decl *)Cursor.data[0];
}
Expr *cxcursor::getCursorExpr(CXCursor Cursor) {
return dyn_cast_or_null<Expr>(getCursorStmt(Cursor));
}
Stmt *cxcursor::getCursorStmt(CXCursor Cursor) {
if (Cursor.kind == CXCursor_ObjCSuperClassRef ||
Cursor.kind == CXCursor_ObjCProtocolRef ||
Cursor.kind == CXCursor_ObjCClassRef)
return 0;
return (Stmt *)Cursor.data[1];
}
Attr *cxcursor::getCursorAttr(CXCursor Cursor) {
return (Attr *)Cursor.data[1];
}
Decl *cxcursor::getCursorParentDecl(CXCursor Cursor) {
return (Decl *)Cursor.data[0];
}
ASTContext &cxcursor::getCursorContext(CXCursor Cursor) {
return getCursorASTUnit(Cursor)->getASTContext();
}
ASTUnit *cxcursor::getCursorASTUnit(CXCursor Cursor) {
CXTranslationUnit TU = static_cast<CXTranslationUnit>(Cursor.data[2]);
if (!TU)
return 0;
return static_cast<ASTUnit *>(TU->TUData);
}
CXTranslationUnit cxcursor::getCursorTU(CXCursor Cursor) {
return static_cast<CXTranslationUnit>(Cursor.data[2]);
}
static void CollectOverriddenMethodsRecurse(CXTranslationUnit TU,
ObjCContainerDecl *Container,
ObjCMethodDecl *Method,
SmallVectorImpl<CXCursor> &Methods,
bool MovedToSuper) {
if (!Container)
return;
// In categories look for overriden methods from protocols. A method from
// category is not "overriden" since it is considered as the "same" method
// (same USR) as the one from the interface.
if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
// Check whether we have a matching method at this category but only if we
// are at the super class level.
if (MovedToSuper)
if (ObjCMethodDecl *
Overridden = Container->getMethod(Method->getSelector(),
Method->isInstanceMethod()))
if (Method != Overridden) {
// We found an override at this category; there is no need to look
// into its protocols.
Methods.push_back(MakeCXCursor(Overridden, TU));
return;
}
for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
PEnd = Category->protocol_end();
P != PEnd; ++P)
CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
return;
}
// Check whether we have a matching method at this level.
if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
Method->isInstanceMethod()))
if (Method != Overridden) {
// We found an override at this level; there is no need to look
// into other protocols or categories.
Methods.push_back(MakeCXCursor(Overridden, TU));
return;
}
if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
PEnd = Protocol->protocol_end();
P != PEnd; ++P)
CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
}
if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
PEnd = Interface->protocol_end();
P != PEnd; ++P)
CollectOverriddenMethodsRecurse(TU, *P, Method, Methods, MovedToSuper);
for (ObjCCategoryDecl *Category = Interface->getCategoryList();
Category; Category = Category->getNextClassCategory())
CollectOverriddenMethodsRecurse(TU, Category, Method, Methods,
MovedToSuper);
if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
return CollectOverriddenMethodsRecurse(TU, Super, Method, Methods,
/*MovedToSuper=*/true);
}
}
static inline void CollectOverriddenMethods(CXTranslationUnit TU,
ObjCContainerDecl *Container,
ObjCMethodDecl *Method,
SmallVectorImpl<CXCursor> &Methods) {
CollectOverriddenMethodsRecurse(TU, Container, Method, Methods,
/*MovedToSuper=*/false);
}
void cxcursor::getOverriddenCursors(CXCursor cursor,
SmallVectorImpl<CXCursor> &overridden) {
assert(clang_isDeclaration(cursor.kind));
Decl *D = getCursorDecl(cursor);
if (!D)
return;
// Handle C++ member functions.
CXTranslationUnit TU = getCursorTU(cursor);
if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
for (CXXMethodDecl::method_iterator
M = CXXMethod->begin_overridden_methods(),
MEnd = CXXMethod->end_overridden_methods();
M != MEnd; ++M)
overridden.push_back(MakeCXCursor(const_cast<CXXMethodDecl*>(*M), TU));
return;
}
ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
if (!Method)
return;
if (ObjCProtocolDecl *
ProtD = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
CollectOverriddenMethods(TU, ProtD, Method, overridden);
} else if (ObjCImplDecl *
IMD = dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
ObjCInterfaceDecl *ID = IMD->getClassInterface();
if (!ID)
return;
// Start searching for overridden methods using the method from the
// interface as starting point.
if (ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
Method->isInstanceMethod()))
Method = IFaceMeth;
CollectOverriddenMethods(TU, ID, Method, overridden);
} else if (ObjCCategoryDecl *
CatD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
ObjCInterfaceDecl *ID = CatD->getClassInterface();
if (!ID)
return;
// Start searching for overridden methods using the method from the
// interface as starting point.
if (ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
Method->isInstanceMethod()))
Method = IFaceMeth;
CollectOverriddenMethods(TU, ID, Method, overridden);
} else {
CollectOverriddenMethods(TU,
dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
Method, overridden);
}
}
std::pair<int, SourceLocation>
cxcursor::getSelectorIdentifierIndexAndLoc(CXCursor cursor) {
if (cursor.kind == CXCursor_ObjCMessageExpr) {
if (cursor.xdata != -1)
return std::make_pair(cursor.xdata,
cast<ObjCMessageExpr>(getCursorExpr(cursor))
->getSelectorLoc(cursor.xdata));
} else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
if (cursor.xdata != -1)
return std::make_pair(cursor.xdata,
cast<ObjCMethodDecl>(getCursorDecl(cursor))
->getSelectorLoc(cursor.xdata));
}
return std::make_pair(-1, SourceLocation());
}
CXCursor cxcursor::getSelectorIdentifierCursor(int SelIdx, CXCursor cursor) {
CXCursor newCursor = cursor;
if (cursor.kind == CXCursor_ObjCMessageExpr) {
if (SelIdx == -1 ||
unsigned(SelIdx) >= cast<ObjCMessageExpr>(getCursorExpr(cursor))
->getNumSelectorLocs())
newCursor.xdata = -1;
else
newCursor.xdata = SelIdx;
} else if (cursor.kind == CXCursor_ObjCClassMethodDecl ||
cursor.kind == CXCursor_ObjCInstanceMethodDecl) {
if (SelIdx == -1 ||
unsigned(SelIdx) >= cast<ObjCMethodDecl>(getCursorDecl(cursor))
->getNumSelectorLocs())
newCursor.xdata = -1;
else
newCursor.xdata = SelIdx;
}
return newCursor;
}
CXCursor cxcursor::getTypeRefCursor(CXCursor cursor) {
if (cursor.kind != CXCursor_CallExpr)
return cursor;
if (cursor.xdata == 0)
return cursor;
Expr *E = getCursorExpr(cursor);
TypeSourceInfo *Type = 0;
if (CXXUnresolvedConstructExpr *
UnCtor = dyn_cast<CXXUnresolvedConstructExpr>(E)) {
Type = UnCtor->getTypeSourceInfo();
} else if (CXXTemporaryObjectExpr *Tmp = dyn_cast<CXXTemporaryObjectExpr>(E)){
Type = Tmp->getTypeSourceInfo();
}
if (!Type)
return cursor;
CXTranslationUnit TU = getCursorTU(cursor);
QualType Ty = Type->getType();
TypeLoc TL = Type->getTypeLoc();
SourceLocation Loc = TL.getBeginLoc();
if (const ElaboratedType *ElabT = Ty->getAs<ElaboratedType>()) {
Ty = ElabT->getNamedType();
ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(TL);
Loc = ElabTL.getNamedTypeLoc().getBeginLoc();
}
if (const TypedefType *Typedef = Ty->getAs<TypedefType>())
return MakeCursorTypeRef(Typedef->getDecl(), Loc, TU);
if (const TagType *Tag = Ty->getAs<TagType>())
return MakeCursorTypeRef(Tag->getDecl(), Loc, TU);
if (const TemplateTypeParmType *TemplP = Ty->getAs<TemplateTypeParmType>())
return MakeCursorTypeRef(TemplP->getDecl(), Loc, TU);
return cursor;
}
bool cxcursor::operator==(CXCursor X, CXCursor Y) {
return X.kind == Y.kind && X.data[0] == Y.data[0] && X.data[1] == Y.data[1] &&
X.data[2] == Y.data[2];
}
// FIXME: Remove once we can model DeclGroups and their appropriate ranges
// properly in the ASTs.
bool cxcursor::isFirstInDeclGroup(CXCursor C) {
assert(clang_isDeclaration(C.kind));
return ((uintptr_t) (C.data[1])) != 0;
}
//===----------------------------------------------------------------------===//
// libclang CXCursor APIs
//===----------------------------------------------------------------------===//
extern "C" {
int clang_Cursor_isNull(CXCursor cursor) {
return clang_equalCursors(cursor, clang_getNullCursor());
}
CXTranslationUnit clang_Cursor_getTranslationUnit(CXCursor cursor) {
return getCursorTU(cursor);
}
int clang_Cursor_getNumArguments(CXCursor C) {
if (clang_isDeclaration(C.kind)) {
Decl *D = cxcursor::getCursorDecl(C);
if (const ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D))
return MD->param_size();
if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
return FD->param_size();
}
return -1;
}
CXCursor clang_Cursor_getArgument(CXCursor C, unsigned i) {
if (clang_isDeclaration(C.kind)) {
Decl *D = cxcursor::getCursorDecl(C);
if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(D)) {
if (i < MD->param_size())
return cxcursor::MakeCXCursor(MD->param_begin()[i],
cxcursor::getCursorTU(C));
} else if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
if (i < FD->param_size())
return cxcursor::MakeCXCursor(FD->param_begin()[i],
cxcursor::getCursorTU(C));
}
}
return clang_getNullCursor();
}
} // end: extern "C"
//===----------------------------------------------------------------------===//
// CXCursorSet.
//===----------------------------------------------------------------------===//
typedef llvm::DenseMap<CXCursor, unsigned> CXCursorSet_Impl;
static inline CXCursorSet packCXCursorSet(CXCursorSet_Impl *setImpl) {
return (CXCursorSet) setImpl;
}
static inline CXCursorSet_Impl *unpackCXCursorSet(CXCursorSet set) {
return (CXCursorSet_Impl*) set;
}
namespace llvm {
template<> struct DenseMapInfo<CXCursor> {
public:
static inline CXCursor getEmptyKey() {
return MakeCXCursorInvalid(CXCursor_InvalidFile);
}
static inline CXCursor getTombstoneKey() {
return MakeCXCursorInvalid(CXCursor_NoDeclFound);
}
static inline unsigned getHashValue(const CXCursor &cursor) {
return llvm::DenseMapInfo<std::pair<void*,void*> >
::getHashValue(std::make_pair(cursor.data[0], cursor.data[1]));
}
static inline bool isEqual(const CXCursor &x, const CXCursor &y) {
return x.kind == y.kind &&
x.data[0] == y.data[0] &&
x.data[1] == y.data[1];
}
};
}
extern "C" {
CXCursorSet clang_createCXCursorSet() {
return packCXCursorSet(new CXCursorSet_Impl());
}
void clang_disposeCXCursorSet(CXCursorSet set) {
delete unpackCXCursorSet(set);
}
unsigned clang_CXCursorSet_contains(CXCursorSet set, CXCursor cursor) {
CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
if (!setImpl)
return 0;
return setImpl->find(cursor) == setImpl->end();
}
unsigned clang_CXCursorSet_insert(CXCursorSet set, CXCursor cursor) {
// Do not insert invalid cursors into the set.
if (cursor.kind >= CXCursor_FirstInvalid &&
cursor.kind <= CXCursor_LastInvalid)
return 1;
CXCursorSet_Impl *setImpl = unpackCXCursorSet(set);
if (!setImpl)
return 1;
unsigned &entry = (*setImpl)[cursor];
unsigned flag = entry == 0 ? 1 : 0;
entry = 1;
return flag;
}
CXCompletionString clang_getCursorCompletionString(CXCursor cursor) {
enum CXCursorKind kind = clang_getCursorKind(cursor);
if (clang_isDeclaration(kind)) {
Decl *decl = getCursorDecl(cursor);
if (NamedDecl *namedDecl = dyn_cast_or_null<NamedDecl>(decl)) {
ASTUnit *unit = getCursorASTUnit(cursor);
CodeCompletionResult Result(namedDecl);
CodeCompletionString *String
= Result.CreateCodeCompletionString(unit->getASTContext(),
unit->getPreprocessor(),
unit->getCodeCompletionTUInfo().getAllocator(),
unit->getCodeCompletionTUInfo());
return String;
}
}
else if (kind == CXCursor_MacroDefinition) {
MacroDefinition *definition = getCursorMacroDefinition(cursor);
const IdentifierInfo *MacroInfo = definition->getName();
ASTUnit *unit = getCursorASTUnit(cursor);
CodeCompletionResult Result(const_cast<IdentifierInfo *>(MacroInfo));
CodeCompletionString *String
= Result.CreateCodeCompletionString(unit->getASTContext(),
unit->getPreprocessor(),
unit->getCodeCompletionTUInfo().getAllocator(),
unit->getCodeCompletionTUInfo());
return String;
}
return NULL;
}
} // end: extern C.
namespace {
struct OverridenCursorsPool {
typedef llvm::SmallVector<CXCursor, 2> CursorVec;
std::vector<CursorVec*> AllCursors;
std::vector<CursorVec*> AvailableCursors;
~OverridenCursorsPool() {
for (std::vector<CursorVec*>::iterator I = AllCursors.begin(),
E = AllCursors.end(); I != E; ++I) {
delete *I;
}
}
};
}
void *cxcursor::createOverridenCXCursorsPool() {
return new OverridenCursorsPool();
}
void cxcursor::disposeOverridenCXCursorsPool(void *pool) {
delete static_cast<OverridenCursorsPool*>(pool);
}
extern "C" {
void clang_getOverriddenCursors(CXCursor cursor,
CXCursor **overridden,
unsigned *num_overridden) {
if (overridden)
*overridden = 0;
if (num_overridden)
*num_overridden = 0;
CXTranslationUnit TU = cxcursor::getCursorTU(cursor);
if (!overridden || !num_overridden || !TU)
return;
if (!clang_isDeclaration(cursor.kind))
return;
OverridenCursorsPool &pool =
*static_cast<OverridenCursorsPool*>(TU->OverridenCursorsPool);
OverridenCursorsPool::CursorVec *Vec = 0;
if (!pool.AvailableCursors.empty()) {
Vec = pool.AvailableCursors.back();
pool.AvailableCursors.pop_back();
}
else {
Vec = new OverridenCursorsPool::CursorVec();
pool.AllCursors.push_back(Vec);
}
// Clear out the vector, but don't free the memory contents. This
// reduces malloc() traffic.
Vec->clear();
// Use the first entry to contain a back reference to the vector.
// This is a complete hack.
CXCursor backRefCursor = MakeCXCursorInvalid(CXCursor_InvalidFile, TU);
backRefCursor.data[0] = Vec;
assert(cxcursor::getCursorTU(backRefCursor) == TU);
Vec->push_back(backRefCursor);
// Get the overriden cursors.
cxcursor::getOverriddenCursors(cursor, *Vec);
// Did we get any overriden cursors? If not, return Vec to the pool
// of available cursor vectors.
if (Vec->size() == 1) {
pool.AvailableCursors.push_back(Vec);
return;
}
// Now tell the caller about the overriden cursors.
assert(Vec->size() > 1);
*overridden = &((*Vec)[1]);
*num_overridden = Vec->size() - 1;
}
void clang_disposeOverriddenCursors(CXCursor *overridden) {
if (!overridden)
return;
// Use pointer arithmetic to get back the first faux entry
// which has a back-reference to the TU and the vector.
--overridden;
OverridenCursorsPool::CursorVec *Vec =
static_cast<OverridenCursorsPool::CursorVec*>(overridden->data[0]);
CXTranslationUnit TU = getCursorTU(*overridden);
assert(Vec && TU);
OverridenCursorsPool &pool =
*static_cast<OverridenCursorsPool*>(TU->OverridenCursorsPool);
pool.AvailableCursors.push_back(Vec);
}
} // end: extern "C"
| [
"seguljac@eecg.toronto.edu"
] | seguljac@eecg.toronto.edu |
7283debf00d5fe8d4552997ffba991b7b953d4f1 | 1351f48d45c2c05e322c29c5f68da0d4590888c1 | /IIUPC/IIUPC 2015CUET_IN_STACK/G.cpp | 035278594d055ef8373bfef7e6f02bcf17bb8856 | [] | no_license | laziestcoder/Problem-Solvings | cd2db049c3f6d1c79dfc9fba9250f4e1d8c7b588 | df487904876c748ad87a72a25d2bcee892a4d443 | refs/heads/master | 2023-08-19T09:55:32.144858 | 2021-10-21T20:32:21 | 2021-10-21T20:32:21 | 114,477,726 | 9 | 2 | null | 2021-06-22T15:46:43 | 2017-12-16T17:18:43 | Python | UTF-8 | C++ | false | false | 403 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<string>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<iomanip>
using namespace std;
#define mem(x,y) memset(x,y,sizeof(x))
#define sn scanf
#define pf printf
#define pb push_back
typedef long long int ll;
int main()
{
return 0;
}
| [
"towfiq.106@gmail.com"
] | towfiq.106@gmail.com |
0d847db55cc0245ce2a66066c71e0980ec567fd4 | 90047daeb462598a924d76ddf4288e832e86417c | /chromeos/components/tether/host_scanner_unittest.cc | b31814c4fa0fce06cc79aa964f75d16069f9e138 | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 22,420 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/components/tether/host_scanner.h"
#include <algorithm>
#include <memory>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
#include "chromeos/components/tether/device_id_tether_network_guid_map.h"
#include "chromeos/components/tether/fake_ble_connection_manager.h"
#include "chromeos/components/tether/fake_host_scan_cache.h"
#include "chromeos/components/tether/fake_notification_presenter.h"
#include "chromeos/components/tether/fake_tether_host_fetcher.h"
#include "chromeos/components/tether/host_scan_device_prioritizer.h"
#include "chromeos/components/tether/host_scanner.h"
#include "chromeos/components/tether/mock_tether_host_response_recorder.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/cryptauth/remote_device_test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace tether {
namespace {
class FakeHostScanDevicePrioritizer : public HostScanDevicePrioritizer {
public:
FakeHostScanDevicePrioritizer() : HostScanDevicePrioritizer(nullptr) {}
~FakeHostScanDevicePrioritizer() override {}
// Simply leave |remote_devices| as-is.
void SortByHostScanOrder(
std::vector<cryptauth::RemoteDevice>* remote_devices) const override {}
};
class FakeHostScannerOperation : public HostScannerOperation {
public:
FakeHostScannerOperation(
const std::vector<cryptauth::RemoteDevice>& devices_to_connect,
BleConnectionManager* connection_manager,
HostScanDevicePrioritizer* host_scan_device_prioritizer,
TetherHostResponseRecorder* tether_host_response_recorder)
: HostScannerOperation(devices_to_connect,
connection_manager,
host_scan_device_prioritizer,
tether_host_response_recorder) {}
~FakeHostScannerOperation() override {}
void SendScannedDeviceListUpdate(
const std::vector<HostScannerOperation::ScannedDeviceInfo>&
scanned_device_list_so_far,
bool is_final_scan_result) {
scanned_device_list_so_far_ = scanned_device_list_so_far;
NotifyObserversOfScannedDeviceList(is_final_scan_result);
}
};
class FakeHostScannerOperationFactory : public HostScannerOperation::Factory {
public:
FakeHostScannerOperationFactory(
const std::vector<cryptauth::RemoteDevice>& test_devices)
: expected_devices_(test_devices) {}
virtual ~FakeHostScannerOperationFactory() {}
std::vector<FakeHostScannerOperation*>& created_operations() {
return created_operations_;
}
protected:
// HostScannerOperation::Factory:
std::unique_ptr<HostScannerOperation> BuildInstance(
const std::vector<cryptauth::RemoteDevice>& devices_to_connect,
BleConnectionManager* connection_manager,
HostScanDevicePrioritizer* host_scan_device_prioritizer,
TetherHostResponseRecorder* tether_host_response_recorder) override {
EXPECT_EQ(expected_devices_, devices_to_connect);
FakeHostScannerOperation* operation = new FakeHostScannerOperation(
devices_to_connect, connection_manager, host_scan_device_prioritizer,
tether_host_response_recorder);
created_operations_.push_back(operation);
return base::WrapUnique(operation);
}
private:
const std::vector<cryptauth::RemoteDevice>& expected_devices_;
std::vector<FakeHostScannerOperation*> created_operations_;
};
std::string GenerateCellProviderForDevice(
const cryptauth::RemoteDevice& remote_device) {
// Return a string unique to |remote_device|.
return "cellProvider" + remote_device.GetTruncatedDeviceIdForLogs();
}
const char kDoNotSetStringField[] = "doNotSetField";
const int kDoNotSetIntField = -100;
// Creates a DeviceStatus object using the parameters provided. If
// |kDoNotSetStringField| or |kDoNotSetIntField| are passed, these fields will
// not be set in the output.
DeviceStatus CreateFakeDeviceStatus(const std::string& cell_provider_name,
int battery_percentage,
int connection_strength) {
// TODO(khorimoto): Once a ConnectedWifiSsid field is added as a property of
// Tether networks, give an option to pass a parameter for that field as well.
WifiStatus wifi_status;
wifi_status.set_status_code(
WifiStatus_StatusCode::WifiStatus_StatusCode_CONNECTED);
wifi_status.set_ssid("Google A");
DeviceStatus device_status;
if (battery_percentage != kDoNotSetIntField) {
device_status.set_battery_percentage(battery_percentage);
}
if (cell_provider_name != kDoNotSetStringField) {
device_status.set_cell_provider(cell_provider_name);
}
if (connection_strength != kDoNotSetIntField) {
device_status.set_connection_strength(connection_strength);
}
device_status.mutable_wifi_status()->CopyFrom(wifi_status);
return device_status;
}
std::vector<HostScannerOperation::ScannedDeviceInfo>
CreateFakeScannedDeviceInfos(
const std::vector<cryptauth::RemoteDevice>& remote_devices) {
// At least 4 ScannedDeviceInfos should be created to ensure that all 4 cases
// described below are tested.
EXPECT_GT(remote_devices.size(), 3u);
std::vector<HostScannerOperation::ScannedDeviceInfo> scanned_device_infos;
for (size_t i = 0; i < remote_devices.size(); ++i) {
// Four field possibilities:
// i % 4 == 0: Field is not supplied.
// i % 4 == 1: Field is below the minimum value (int fields only).
// i % 4 == 2: Field is within the valid range (int fields only).
// i % 4 == 3: Field is above the maximium value (int fields only).
std::string cell_provider_name;
int battery_percentage;
int connection_strength;
switch (i % 4) {
case 0:
cell_provider_name = kDoNotSetStringField;
battery_percentage = kDoNotSetIntField;
connection_strength = kDoNotSetIntField;
break;
case 1:
cell_provider_name = GenerateCellProviderForDevice(remote_devices[i]);
battery_percentage = -1 - i;
connection_strength = -1 - i;
break;
case 2:
cell_provider_name = GenerateCellProviderForDevice(remote_devices[i]);
battery_percentage = (50 + i) % 100; // Valid range is [0, 100].
connection_strength = (1 + i) % 4; // Valid range is [0, 4].
break;
case 3:
cell_provider_name = GenerateCellProviderForDevice(remote_devices[i]);
battery_percentage = 101 + i;
connection_strength = 101 + i;
break;
default:
NOTREACHED();
// Set values for |battery_percentage| and |connection_strength| here to
// prevent a compiler warning which says that they may be unset at this
// point.
battery_percentage = 0;
connection_strength = 0;
break;
}
DeviceStatus device_status = CreateFakeDeviceStatus(
cell_provider_name, battery_percentage, connection_strength);
// Require set-up for odd-numbered device indices.
bool set_up_required = i % 2 == 0;
scanned_device_infos.push_back(HostScannerOperation::ScannedDeviceInfo(
remote_devices[i], device_status, set_up_required));
}
return scanned_device_infos;
}
} // namespace
class HostScannerTest : public testing::Test {
protected:
HostScannerTest()
: test_devices_(cryptauth::GenerateTestRemoteDevices(4)),
test_scanned_device_infos(CreateFakeScannedDeviceInfos(test_devices_)) {
}
void SetUp() override {
scanned_device_infos_so_far_.clear();
fake_tether_host_fetcher_ = base::MakeUnique<FakeTetherHostFetcher>(
test_devices_, false /* synchronously_reply_with_results */);
fake_ble_connection_manager_ = base::MakeUnique<FakeBleConnectionManager>();
fake_host_scan_device_prioritizer_ =
base::MakeUnique<FakeHostScanDevicePrioritizer>();
mock_tether_host_response_recorder_ =
base::MakeUnique<MockTetherHostResponseRecorder>();
fake_notification_presenter_ =
base::MakeUnique<FakeNotificationPresenter>();
device_id_tether_network_guid_map_ =
base::MakeUnique<DeviceIdTetherNetworkGuidMap>();
fake_host_scan_cache_ = base::MakeUnique<FakeHostScanCache>();
fake_host_scanner_operation_factory_ =
base::WrapUnique(new FakeHostScannerOperationFactory(test_devices_));
HostScannerOperation::Factory::SetInstanceForTesting(
fake_host_scanner_operation_factory_.get());
host_scanner_ = base::WrapUnique(new HostScanner(
fake_tether_host_fetcher_.get(), fake_ble_connection_manager_.get(),
fake_host_scan_device_prioritizer_.get(),
mock_tether_host_response_recorder_.get(),
fake_notification_presenter_.get(),
device_id_tether_network_guid_map_.get(), fake_host_scan_cache_.get()));
}
void TearDown() override {
HostScannerOperation::Factory::SetInstanceForTesting(nullptr);
}
// Causes |fake_operation| to receive the scan result in
// |test_scanned_device_infos| vector at the index |test_device_index| with
// the "final result" value of |is_final_scan_result|.
void ReceiveScanResultAndVerifySuccess(
FakeHostScannerOperation& fake_operation,
size_t test_device_index,
bool is_final_scan_result) {
bool already_in_list = false;
for (auto& scanned_device_info : scanned_device_infos_so_far_) {
if (scanned_device_info.remote_device.GetDeviceId() ==
test_devices_[test_device_index].GetDeviceId()) {
already_in_list = true;
break;
}
}
if (!already_in_list) {
scanned_device_infos_so_far_.push_back(
test_scanned_device_infos[test_device_index]);
}
fake_operation.SendScannedDeviceListUpdate(scanned_device_infos_so_far_,
is_final_scan_result);
VerifyScanResultsMatchCache();
if (scanned_device_infos_so_far_.size() == 1) {
EXPECT_EQ(FakeNotificationPresenter::PotentialHotspotNotificationState::
SINGLE_HOTSPOT_NEARBY_SHOWN,
fake_notification_presenter_->potential_hotspot_state());
} else {
EXPECT_EQ(FakeNotificationPresenter::PotentialHotspotNotificationState::
MULTIPLE_HOTSPOTS_NEARBY_SHOWN,
fake_notification_presenter_->potential_hotspot_state());
}
}
void VerifyScanResultsMatchCache() {
ASSERT_EQ(scanned_device_infos_so_far_.size(),
fake_host_scan_cache_->size());
for (auto& scanned_device_info : scanned_device_infos_so_far_) {
std::string tether_network_guid =
device_id_tether_network_guid_map_->GetTetherNetworkGuidForDeviceId(
scanned_device_info.remote_device.GetDeviceId());
const FakeHostScanCache::CacheEntry* cache_item =
fake_host_scan_cache_->GetCacheEntry(tether_network_guid);
ASSERT_TRUE(cache_item);
VerifyScannedDeviceInfoAndCacheEntryAreEquivalent(scanned_device_info,
*cache_item);
}
}
void VerifyScannedDeviceInfoAndCacheEntryAreEquivalent(
const HostScannerOperation::ScannedDeviceInfo& scanned_device_info,
const FakeHostScanCache::CacheEntry& cache_item) {
EXPECT_EQ(scanned_device_info.remote_device.name, cache_item.device_name);
const DeviceStatus& status = scanned_device_info.device_status;
if (!status.has_cell_provider() || status.cell_provider().empty())
EXPECT_EQ("unknown-carrier", cache_item.carrier);
else
EXPECT_EQ(status.cell_provider(), cache_item.carrier);
if (!status.has_battery_percentage() || status.battery_percentage() > 100)
EXPECT_EQ(100, cache_item.battery_percentage);
else if (status.battery_percentage() < 0)
EXPECT_EQ(0, cache_item.battery_percentage);
else
EXPECT_EQ(status.battery_percentage(), cache_item.battery_percentage);
if (!status.has_connection_strength() || status.connection_strength() > 4)
EXPECT_EQ(100, cache_item.signal_strength);
else if (status.connection_strength() < 0)
EXPECT_EQ(0, cache_item.signal_strength);
else
EXPECT_EQ(status.connection_strength() * 25, cache_item.signal_strength);
}
const std::vector<cryptauth::RemoteDevice> test_devices_;
const std::vector<HostScannerOperation::ScannedDeviceInfo>
test_scanned_device_infos;
std::unique_ptr<FakeTetherHostFetcher> fake_tether_host_fetcher_;
std::unique_ptr<FakeBleConnectionManager> fake_ble_connection_manager_;
std::unique_ptr<HostScanDevicePrioritizer> fake_host_scan_device_prioritizer_;
std::unique_ptr<MockTetherHostResponseRecorder>
mock_tether_host_response_recorder_;
std::unique_ptr<FakeNotificationPresenter> fake_notification_presenter_;
// TODO(hansberry): Use a fake for this when a real mapping scheme is created.
std::unique_ptr<DeviceIdTetherNetworkGuidMap>
device_id_tether_network_guid_map_;
std::unique_ptr<FakeHostScanCache> fake_host_scan_cache_;
std::unique_ptr<FakeHostScannerOperationFactory>
fake_host_scanner_operation_factory_;
std::vector<HostScannerOperation::ScannedDeviceInfo>
scanned_device_infos_so_far_;
std::unique_ptr<HostScanner> host_scanner_;
private:
DISALLOW_COPY_AND_ASSIGN(HostScannerTest);
};
TEST_F(HostScannerTest, TestScan_ResultsFromAllDevices) {
EXPECT_FALSE(host_scanner_->IsScanActive());
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
fake_tether_host_fetcher_->InvokePendingCallbacks();
ASSERT_EQ(1u,
fake_host_scanner_operation_factory_->created_operations().size());
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
0u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
1u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
2u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
3u /* test_device_index */, true /* is_final_scan_result */);
EXPECT_FALSE(host_scanner_->IsScanActive());
}
TEST_F(HostScannerTest, TestScan_ResultsFromNoDevices) {
EXPECT_FALSE(host_scanner_->IsScanActive());
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
fake_tether_host_fetcher_->InvokePendingCallbacks();
ASSERT_EQ(1u,
fake_host_scanner_operation_factory_->created_operations().size());
EXPECT_TRUE(host_scanner_->IsScanActive());
fake_host_scanner_operation_factory_->created_operations()[0]
->SendScannedDeviceListUpdate(
std::vector<HostScannerOperation::ScannedDeviceInfo>(),
true /* is_final_scan_result */);
EXPECT_EQ(0u, fake_host_scan_cache_->size());
EXPECT_FALSE(host_scanner_->IsScanActive());
}
TEST_F(HostScannerTest, TestScan_ResultsFromSomeDevices) {
EXPECT_FALSE(host_scanner_->IsScanActive());
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
fake_tether_host_fetcher_->InvokePendingCallbacks();
ASSERT_EQ(1u,
fake_host_scanner_operation_factory_->created_operations().size());
EXPECT_TRUE(host_scanner_->IsScanActive());
// Only receive updates from the 0th and 1st device.
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
0u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
1u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
fake_host_scanner_operation_factory_->created_operations()[0]
->SendScannedDeviceListUpdate(scanned_device_infos_so_far_,
true /* is_final_scan_result */);
EXPECT_EQ(scanned_device_infos_so_far_.size(), fake_host_scan_cache_->size());
EXPECT_FALSE(host_scanner_->IsScanActive());
}
TEST_F(HostScannerTest, TestScan_MultipleScanCallsDuringOperation) {
EXPECT_FALSE(host_scanner_->IsScanActive());
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
// Call StartScan() again before the tether host fetcher has finished. This
// should be a no-op.
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
// No devices should have been received yet.
EXPECT_EQ(0u, fake_host_scan_cache_->size());
fake_tether_host_fetcher_->InvokePendingCallbacks();
ASSERT_EQ(1u,
fake_host_scanner_operation_factory_->created_operations().size());
EXPECT_TRUE(host_scanner_->IsScanActive());
// Call StartScan again after the tether host fetcher has finished but before
// the final scan result has been received. This should be a no-op.
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
// No devices should have been received yet.
EXPECT_EQ(0u, fake_host_scan_cache_->size());
// Receive updates from the 0th device.
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
0u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
// Call StartScan again after a scan result has been received but before
// the final scan result ha been received. This should be a no-op.
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
// The scanned devices so far should be the same (i.e., they should not have
// been affected by the extra call to StartScan()).
EXPECT_EQ(scanned_device_infos_so_far_.size(), fake_host_scan_cache_->size());
// Finally, finish the scan.
fake_host_scanner_operation_factory_->created_operations()[0]
->SendScannedDeviceListUpdate(scanned_device_infos_so_far_,
true /* is_final_scan_result */);
EXPECT_EQ(scanned_device_infos_so_far_.size(), fake_host_scan_cache_->size());
EXPECT_FALSE(host_scanner_->IsScanActive());
}
TEST_F(HostScannerTest, TestScan_MultipleCompleteScanSessions) {
// Start the first scan session.
EXPECT_FALSE(host_scanner_->IsScanActive());
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
fake_tether_host_fetcher_->InvokePendingCallbacks();
ASSERT_EQ(1u,
fake_host_scanner_operation_factory_->created_operations().size());
EXPECT_TRUE(host_scanner_->IsScanActive());
// Receive updates from devices 0-3.
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
0u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
1u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
2u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[0],
3u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
// Finish the first scan.
fake_host_scanner_operation_factory_->created_operations()[0]
->SendScannedDeviceListUpdate(scanned_device_infos_so_far_,
true /* is_final_scan_result */);
EXPECT_EQ(scanned_device_infos_so_far_.size(), fake_host_scan_cache_->size());
EXPECT_FALSE(host_scanner_->IsScanActive());
// Simulate device 0 connecting; it is now considered the active host.
fake_host_scan_cache_->set_active_host_tether_network_guid(
device_id_tether_network_guid_map_->GetTetherNetworkGuidForDeviceId(
test_devices_[0].GetDeviceId()));
// Now, start the second scan session.
EXPECT_FALSE(host_scanner_->IsScanActive());
host_scanner_->StartScan();
EXPECT_TRUE(host_scanner_->IsScanActive());
fake_tether_host_fetcher_->InvokePendingCallbacks();
ASSERT_EQ(2u,
fake_host_scanner_operation_factory_->created_operations().size());
EXPECT_TRUE(host_scanner_->IsScanActive());
// The cache should have been cleared except for the active host. Since the
// active host is device 0, clear |scanned_device_list_so_far_| from device 1
// onward and verify that the cache is equivalent.
scanned_device_infos_so_far_.erase(scanned_device_infos_so_far_.begin() + 1,
scanned_device_infos_so_far_.end());
VerifyScanResultsMatchCache();
// Receive results from devices 0 and 2. This simulates devices 1 and 3 being
// out of range during the second scan.
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[1],
0u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
ReceiveScanResultAndVerifySuccess(
*fake_host_scanner_operation_factory_->created_operations()[1],
2u /* test_device_index */, false /* is_final_scan_result */);
EXPECT_TRUE(host_scanner_->IsScanActive());
// Finish the second scan.
fake_host_scanner_operation_factory_->created_operations()[1]
->SendScannedDeviceListUpdate(scanned_device_infos_so_far_,
true /* is_final_scan_result */);
EXPECT_EQ(scanned_device_infos_so_far_.size(), fake_host_scan_cache_->size());
EXPECT_FALSE(host_scanner_->IsScanActive());
}
} // namespace tether
} // namespace chromeos
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
fdcbbbc739447e0e90c92bb57ba76baaac8ea180 | 6ceb89ac375ed39f517521021f69b7d8983fb092 | /tests/test_ntw_fusion_1u.cpp | dcd059df27a9b8a7a114ab819fbc927447727bc8 | [
"MIT"
] | permissive | vsukhor/mitoSim | 68c420d8057769f8713ca3fb30ea039ab3580cb8 | 66545dd1c9d657104ef2bdee46bc84ba3ea327ba | refs/heads/master | 2023-02-20T05:35:01.521974 | 2023-02-04T20:46:56 | 2023-02-04T20:46:56 | 204,693,530 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,022 | cpp | #include <filesystem>
#include <memory>
#include <string>
#include "gtest/gtest.h"
#include "../config.h"
#include "../definitions.h"
#include "../segment.h"
#include "../network.h"
#include "ntw_fusion1u.h"
namespace ntw_fusion1u_test {
class NtwFusion1UTest
: public testing::Test {
protected:
using Mt = mitosim::Segment<3>;
using Network = mitosim::Network<Mt>;
using RandFactory = mitosim::RandFactory;
using Msgr = mitosim::Msgr;
using Config = mitosim::Config<mitosim::real>;
using real = mitosim::real;
using szt = mitosim::szt;
using NtwFusion1U = mitosim::NtwFusion1U<Network>;
class Ntw : public Network {
public:
using Network::fuse_to_loop;
explicit Ntw(
const Config& cfg,
RandFactory& rnd,
Msgr& msgr
) : Network {cfg, rnd, msgr}
{}
};
static constexpr auto minLL =
mitosim::Structure<typename Network::ST>::minLoopLength;
const std::string workingDir {std::filesystem::current_path()
/ "tests" / "data/"};
const std::string fnameSuffix {"sample"};
const std::string runName {"42"};
NtwFusion1UTest()
: msgr {}
, conf {workingDir, fnameSuffix, runName, msgr}
, rnd {std::make_unique<mitosim::RandFactory>(10, msgr)}
, ntw {conf, *rnd, msgr}
{}
Msgr msgr;
Config conf;
std::unique_ptr<RandFactory> rnd;
Ntw ntw;
};
TEST_F(NtwFusion1UTest, Constructor)
{
NtwFusion1U nf {ntw};
EXPECT_EQ(nf.get_cnd().size(), 0);
}
TEST_F(NtwFusion1UTest, SetProp)
{
// Tests propensity contribution from 11-segments to separate cycles.
constexpr std::array<szt,4> len {4, 8, 3, 5};
for (const auto u : len)
ntw.add_disconnected_segment(u);
ntw.fuse_to_loop(1);
ntw.fuse_to_loop(2);
NtwFusion1U nf {ntw};
ntw.populate_cluster_vectors();
nf.set_prop();
EXPECT_EQ(nf.get_cnd().size(), 8);
}
} // namespace ntw_fusion1u_test
| [
"29120451+vsukhor@users.noreply.github.com"
] | 29120451+vsukhor@users.noreply.github.com |
a913976792cfcdbb9c0c921020fc92f6a24d85c9 | 5e41d0c94ddf924cf590ab094803ee91d3f1843d | /lib/libflatarray/src/detail/short_vec_sse_int_16.hpp | 1972a851edc1d4007ba33f52d561be396dccd44f | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | sithhell/libgeodecomp | 5e26566588ba560702249f24af7ba8f8ae2148f8 | 20930da73d64b7b366ea1a368c9bc35f1723b6fc | refs/heads/master | 2021-01-18T06:41:45.924539 | 2016-06-13T07:55:11 | 2016-06-13T07:55:11 | 51,578,948 | 0 | 0 | null | 2016-02-12T09:49:27 | 2016-02-12T09:49:27 | null | UTF-8 | C++ | false | false | 18,870 | hpp | /**
* Copyright 2016 Andreas Schäfer
* Copyright 2015 Kurt Kanzenbach
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef FLAT_ARRAY_DETAIL_SHORT_VEC_SSE_INT_16_HPP
#define FLAT_ARRAY_DETAIL_SHORT_VEC_SSE_INT_16_HPP
#ifdef __SSE2__
#include <emmintrin.h>
#include <libflatarray/detail/sqrt_reference.hpp>
#include <libflatarray/detail/short_vec_helpers.hpp>
#include <libflatarray/config.h>
#include <iostream>
#ifdef __SSE4_1__
#include <smmintrin.h>
#endif
#ifdef LIBFLATARRAY_WITH_CPP14
#include <initializer_list>
#endif
#ifndef __AVX512F__
#ifndef __AVX2__
#ifndef __CUDA_ARCH__
namespace LibFlatArray {
template<typename CARGO, int ARITY>
class short_vec;
template<typename CARGO, int ARITY>
class sqrt_reference;
#ifdef __ICC
// disabling this warning as implicit type conversion is exactly our goal here:
#pragma warning push
#pragma warning (disable: 2304)
#endif
template<>
class short_vec<int, 16>
{
public:
static const int ARITY = 16;
typedef short_vec_strategy::sse strategy;
template<typename _CharT, typename _Traits>
friend std::basic_ostream<_CharT, _Traits>& operator<<(
std::basic_ostream<_CharT, _Traits>& __os,
const short_vec<int, 16>& vec);
inline
short_vec(const int data = 0) :
val1(_mm_set1_epi32(data)),
val2(_mm_set1_epi32(data)),
val3(_mm_set1_epi32(data)),
val4(_mm_set1_epi32(data))
{}
inline
short_vec(const int *data)
{
load(data);
}
inline
short_vec(const __m128i& val1, const __m128i& val2,
const __m128i& val3, const __m128i& val4) :
val1(val1),
val2(val2),
val3(val3),
val4(val4)
{}
#ifdef LIBFLATARRAY_WITH_CPP14
inline
short_vec(const std::initializer_list<int>& il)
{
const int *ptr = static_cast<const int *>(&(*il.begin()));
load(ptr);
}
#endif
inline
short_vec(const sqrt_reference<int, 16>& other);
inline
void operator-=(const short_vec<int, 16>& other)
{
val1 = _mm_sub_epi32(val1, other.val1);
val2 = _mm_sub_epi32(val2, other.val2);
val3 = _mm_sub_epi32(val3, other.val3);
val4 = _mm_sub_epi32(val4, other.val4);
}
inline
short_vec<int, 16> operator-(const short_vec<int, 16>& other) const
{
return short_vec<int, 16>(
_mm_sub_epi32(val1, other.val1),
_mm_sub_epi32(val2, other.val2),
_mm_sub_epi32(val3, other.val3),
_mm_sub_epi32(val4, other.val4));
}
inline
void operator+=(const short_vec<int, 16>& other)
{
val1 = _mm_add_epi32(val1, other.val1);
val2 = _mm_add_epi32(val2, other.val2);
val3 = _mm_add_epi32(val3, other.val3);
val4 = _mm_add_epi32(val4, other.val4);
}
inline
short_vec<int, 16> operator+(const short_vec<int, 16>& other) const
{
return short_vec<int, 16>(
_mm_add_epi32(val1, other.val1),
_mm_add_epi32(val2, other.val2),
_mm_add_epi32(val3, other.val3),
_mm_add_epi32(val4, other.val4));
}
#ifdef __SSE4_1__
inline
void operator*=(const short_vec<int, 16>& other)
{
val1 = _mm_mullo_epi32(val1, other.val1);
val2 = _mm_mullo_epi32(val2, other.val2);
val3 = _mm_mullo_epi32(val3, other.val3);
val4 = _mm_mullo_epi32(val4, other.val4);
}
inline
short_vec<int, 16> operator*(const short_vec<int, 16>& other) const
{
return short_vec<int, 16>(
_mm_mullo_epi32(val1, other.val1),
_mm_mullo_epi32(val2, other.val2),
_mm_mullo_epi32(val3, other.val3),
_mm_mullo_epi32(val4, other.val4));
}
#else
inline
void operator*=(const short_vec<int, 16>& other)
{
// see: https://software.intel.com/en-us/forums/intel-c-compiler/topic/288768
__m128i tmp1 = _mm_mul_epu32(val1, other.val1);
__m128i tmp2 = _mm_mul_epu32(_mm_srli_si128(val1, 4),
_mm_srli_si128(other.val1, 4));
val1 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
tmp1 = _mm_mul_epu32(val2, other.val2);
tmp2 = _mm_mul_epu32(_mm_srli_si128(val2, 4),
_mm_srli_si128(other.val2, 4));
val2 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
tmp1 = _mm_mul_epu32(val3, other.val3);
tmp2 = _mm_mul_epu32(_mm_srli_si128(val3, 4),
_mm_srli_si128(other.val3, 4));
val3 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
tmp1 = _mm_mul_epu32(val4, other.val4);
tmp2 = _mm_mul_epu32(_mm_srli_si128(val4, 4),
_mm_srli_si128(other.val4, 4));
val4 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
}
inline
short_vec<int, 16> operator*(const short_vec<int, 16>& other) const
{
// see: https://software.intel.com/en-us/forums/intel-c-compiler/topic/288768
__m128i tmp1 = _mm_mul_epu32(val1, other.val1);
__m128i tmp2 = _mm_mul_epu32(_mm_srli_si128(val1, 4),
_mm_srli_si128(other.val1, 4));
__m128i result1 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
tmp1 = _mm_mul_epu32(val2, other.val2);
tmp2 = _mm_mul_epu32(_mm_srli_si128(val2, 4),
_mm_srli_si128(other.val2, 4));
__m128i result2 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
tmp1 = _mm_mul_epu32(val3, other.val3);
tmp2 = _mm_mul_epu32(_mm_srli_si128(val3, 4),
_mm_srli_si128(other.val3, 4));
__m128i result3 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
tmp1 = _mm_mul_epu32(val4, other.val4);
tmp2 = _mm_mul_epu32(_mm_srli_si128(val4, 4),
_mm_srli_si128(other.val4, 4));
__m128i result4 = _mm_unpacklo_epi32(
_mm_shuffle_epi32(tmp1, _MM_SHUFFLE(0,0,2,0)),
_mm_shuffle_epi32(tmp2, _MM_SHUFFLE(0,0,2,0)));
return short_vec<int, 16>(result1, result2, result3, result4);
}
#endif
inline
void operator/=(const short_vec<int, 16>& other)
{
val1 = _mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val1),
_mm_cvtepi32_ps(other.val1)));
val2 = _mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val2),
_mm_cvtepi32_ps(other.val2)));
val3 = _mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val3),
_mm_cvtepi32_ps(other.val3)));
val4 = _mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val4),
_mm_cvtepi32_ps(other.val4)));
}
inline
void operator/=(const sqrt_reference<int, 16>& other);
inline
short_vec<int, 16> operator/(const short_vec<int, 16>& other) const
{
return short_vec<int, 16>(
_mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val1),
_mm_cvtepi32_ps(other.val1))),
_mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val2),
_mm_cvtepi32_ps(other.val2))),
_mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val3),
_mm_cvtepi32_ps(other.val3))),
_mm_cvtps_epi32(_mm_div_ps(_mm_cvtepi32_ps(val4),
_mm_cvtepi32_ps(other.val4))));
}
inline
short_vec<int, 16> operator/(const sqrt_reference<int, 16>& other) const;
inline
short_vec<int, 16> sqrt() const
{
return short_vec<int, 16>(
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(val1))),
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(val2))),
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(val3))),
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(val4))));
}
inline
void load(const int *data)
{
val1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(data + 0));
val2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(data + 4));
val3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(data + 8));
val4 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(data + 12));
}
inline
void load_aligned(const int *data)
{
SHORTVEC_ASSERT_ALIGNED(data, 16);
val1 = _mm_load_si128(reinterpret_cast<const __m128i *>(data + 0));
val2 = _mm_load_si128(reinterpret_cast<const __m128i *>(data + 4));
val3 = _mm_load_si128(reinterpret_cast<const __m128i *>(data + 8));
val4 = _mm_load_si128(reinterpret_cast<const __m128i *>(data + 12));
}
inline
void store(int *data) const
{
_mm_storeu_si128(reinterpret_cast<__m128i *>(data + 0), val1);
_mm_storeu_si128(reinterpret_cast<__m128i *>(data + 4), val2);
_mm_storeu_si128(reinterpret_cast<__m128i *>(data + 8), val3);
_mm_storeu_si128(reinterpret_cast<__m128i *>(data + 12), val4);
}
inline
void store_aligned(int *data) const
{
SHORTVEC_ASSERT_ALIGNED(data, 16);
_mm_store_si128(reinterpret_cast<__m128i *>(data + 0), val1);
_mm_store_si128(reinterpret_cast<__m128i *>(data + 4), val2);
_mm_store_si128(reinterpret_cast<__m128i *>(data + 8), val3);
_mm_store_si128(reinterpret_cast<__m128i *>(data + 12), val4);
}
inline
void store_nt(int *data) const
{
SHORTVEC_ASSERT_ALIGNED(data, 16);
_mm_stream_si128(reinterpret_cast<__m128i *>(data + 0), val1);
_mm_stream_si128(reinterpret_cast<__m128i *>(data + 4), val2);
_mm_stream_si128(reinterpret_cast<__m128i *>(data + 8), val3);
_mm_stream_si128(reinterpret_cast<__m128i *>(data + 12), val4);
}
#ifdef __SSE4_1__
inline
void gather(const int *ptr, const int *offsets)
{
val1 = _mm_insert_epi32(val1, ptr[offsets[ 0]], 0);
val1 = _mm_insert_epi32(val1, ptr[offsets[ 1]], 1);
val1 = _mm_insert_epi32(val1, ptr[offsets[ 2]], 2);
val1 = _mm_insert_epi32(val1, ptr[offsets[ 3]], 3);
val2 = _mm_insert_epi32(val2, ptr[offsets[ 4]], 0);
val2 = _mm_insert_epi32(val2, ptr[offsets[ 5]], 1);
val2 = _mm_insert_epi32(val2, ptr[offsets[ 6]], 2);
val2 = _mm_insert_epi32(val2, ptr[offsets[ 7]], 3);
val3 = _mm_insert_epi32(val3, ptr[offsets[ 8]], 0);
val3 = _mm_insert_epi32(val3, ptr[offsets[ 9]], 1);
val3 = _mm_insert_epi32(val3, ptr[offsets[10]], 2);
val3 = _mm_insert_epi32(val3, ptr[offsets[11]], 3);
val4 = _mm_insert_epi32(val4, ptr[offsets[12]], 0);
val4 = _mm_insert_epi32(val4, ptr[offsets[13]], 1);
val4 = _mm_insert_epi32(val4, ptr[offsets[14]], 2);
val4 = _mm_insert_epi32(val4, ptr[offsets[15]], 3);
}
inline
void scatter(int *ptr, const int *offsets) const
{
ptr[offsets[ 0]] = _mm_extract_epi32(val1, 0);
ptr[offsets[ 1]] = _mm_extract_epi32(val1, 1);
ptr[offsets[ 2]] = _mm_extract_epi32(val1, 2);
ptr[offsets[ 3]] = _mm_extract_epi32(val1, 3);
ptr[offsets[ 4]] = _mm_extract_epi32(val2, 0);
ptr[offsets[ 5]] = _mm_extract_epi32(val2, 1);
ptr[offsets[ 6]] = _mm_extract_epi32(val2, 2);
ptr[offsets[ 7]] = _mm_extract_epi32(val2, 3);
ptr[offsets[ 8]] = _mm_extract_epi32(val3, 0);
ptr[offsets[ 9]] = _mm_extract_epi32(val3, 1);
ptr[offsets[10]] = _mm_extract_epi32(val3, 2);
ptr[offsets[11]] = _mm_extract_epi32(val3, 3);
ptr[offsets[12]] = _mm_extract_epi32(val4, 0);
ptr[offsets[13]] = _mm_extract_epi32(val4, 1);
ptr[offsets[14]] = _mm_extract_epi32(val4, 2);
ptr[offsets[15]] = _mm_extract_epi32(val4, 3);
}
#else
inline
void gather(const int *ptr, const int *offsets)
{
__m128i i2, i3, i4;
val1 = _mm_cvtsi32_si128(ptr[offsets[0]]);
i2 = _mm_cvtsi32_si128(ptr[offsets[1]]);
i3 = _mm_cvtsi32_si128(ptr[offsets[2]]);
i4 = _mm_cvtsi32_si128(ptr[offsets[3]]);
val1 = _mm_unpacklo_epi32(val1, i3);
i3 = _mm_unpacklo_epi32(i2 , i4);
val1 = _mm_unpacklo_epi32(val1, i3);
val2 = _mm_cvtsi32_si128(ptr[offsets[4]]);
i2 = _mm_cvtsi32_si128(ptr[offsets[5]]);
i3 = _mm_cvtsi32_si128(ptr[offsets[6]]);
i4 = _mm_cvtsi32_si128(ptr[offsets[7]]);
val2 = _mm_unpacklo_epi32(val2, i3);
i3 = _mm_unpacklo_epi32(i2 , i4);
val2 = _mm_unpacklo_epi32(val2, i3);
val3 = _mm_cvtsi32_si128(ptr[offsets[ 8]]);
i2 = _mm_cvtsi32_si128(ptr[offsets[ 9]]);
i3 = _mm_cvtsi32_si128(ptr[offsets[10]]);
i4 = _mm_cvtsi32_si128(ptr[offsets[11]]);
val3 = _mm_unpacklo_epi32(val3, i3);
i3 = _mm_unpacklo_epi32(i2 , i4);
val3 = _mm_unpacklo_epi32(val3, i3);
val4 = _mm_cvtsi32_si128(ptr[offsets[12]]);
i2 = _mm_cvtsi32_si128(ptr[offsets[13]]);
i3 = _mm_cvtsi32_si128(ptr[offsets[14]]);
i4 = _mm_cvtsi32_si128(ptr[offsets[15]]);
val4 = _mm_unpacklo_epi32(val4, i3);
i3 = _mm_unpacklo_epi32(i2 , i4);
val4 = _mm_unpacklo_epi32(val4, i3);
}
inline
void scatter(int *ptr, const int *offsets) const
{
ptr[offsets[ 0]] = _mm_cvtsi128_si32(val1);
ptr[offsets[ 1]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val1, _MM_SHUFFLE(0,3,2,1)));
ptr[offsets[ 2]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val1, _MM_SHUFFLE(1,0,3,2)));
ptr[offsets[ 3]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val1, _MM_SHUFFLE(2,1,0,3)));
ptr[offsets[ 4]] = _mm_cvtsi128_si32(val2);
ptr[offsets[ 5]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val2, _MM_SHUFFLE(0,3,2,1)));
ptr[offsets[ 6]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val2, _MM_SHUFFLE(1,0,3,2)));
ptr[offsets[ 7]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val2, _MM_SHUFFLE(2,1,0,3)));
ptr[offsets[ 8]] = _mm_cvtsi128_si32(val3);
ptr[offsets[ 9]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val3, _MM_SHUFFLE(0,3,2,1)));
ptr[offsets[10]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val3, _MM_SHUFFLE(1,0,3,2)));
ptr[offsets[11]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val3, _MM_SHUFFLE(2,1,0,3)));
ptr[offsets[12]] = _mm_cvtsi128_si32(val4);
ptr[offsets[13]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val4, _MM_SHUFFLE(0,3,2,1)));
ptr[offsets[14]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val4, _MM_SHUFFLE(1,0,3,2)));
ptr[offsets[15]] = _mm_cvtsi128_si32(_mm_shuffle_epi32(val4, _MM_SHUFFLE(2,1,0,3)));
}
#endif
private:
__m128i val1;
__m128i val2;
__m128i val3;
__m128i val4;
};
inline
void operator<<(int *data, const short_vec<int, 16>& vec)
{
vec.store(data);
}
template<>
class sqrt_reference<int, 16>
{
public:
template<typename OTHER_CARGO, int OTHER_ARITY>
friend class short_vec;
sqrt_reference(const short_vec<int, 16>& vec) :
vec(vec)
{}
private:
short_vec<int, 16> vec;
};
#ifdef __ICC
#pragma warning pop
#endif
inline
short_vec<int, 16>::short_vec(const sqrt_reference<int, 16>& other) :
val1(
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(other.vec.val1)))),
val2(
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(other.vec.val2)))),
val3(
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(other.vec.val3)))),
val4(
_mm_cvtps_epi32(
_mm_sqrt_ps(_mm_cvtepi32_ps(other.vec.val4))))
{}
inline
void short_vec<int, 16>::operator/=(const sqrt_reference<int, 16>& other)
{
val1 = _mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val1),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val1))));
val2 = _mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val2),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val2))));
val3 = _mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val2),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val3))));
val4 = _mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val2),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val4))));
}
inline
short_vec<int, 16> short_vec<int, 16>::operator/(const sqrt_reference<int, 16>& other) const
{
return short_vec<int, 16>(
_mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val1),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val1)))),
_mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val2),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val2)))),
_mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val3),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val3)))),
_mm_cvtps_epi32(
_mm_mul_ps(_mm_cvtepi32_ps(val4),
_mm_rsqrt_ps(_mm_cvtepi32_ps(other.vec.val4)))));
}
inline
sqrt_reference<int, 16> sqrt(const short_vec<int, 16>& vec)
{
return sqrt_reference<int, 16>(vec);
}
template<typename _CharT, typename _Traits>
std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os,
const short_vec<int, 16>& vec)
{
const int *data1 = reinterpret_cast<const int *>(&vec.val1);
const int *data2 = reinterpret_cast<const int *>(&vec.val2);
const int *data3 = reinterpret_cast<const int *>(&vec.val3);
const int *data4 = reinterpret_cast<const int *>(&vec.val4);
__os << "["
<< data1[0] << ", " << data1[1] << ", " << data1[2] << ", " << data1[3] << ", "
<< data2[0] << ", " << data2[1] << ", " << data2[2] << ", " << data2[3] << ", "
<< data3[0] << ", " << data3[1] << ", " << data3[2] << ", " << data3[3] << ", "
<< data4[0] << ", " << data4[1] << ", " << data4[2] << ", " << data4[3]
<< "]";
return __os;
}
}
#endif
#endif
#endif
#endif
#endif
| [
"gentryx@gmx.de"
] | gentryx@gmx.de |
ba6cc7ccb37f9febabb752eb7100177d88b7300c | 9a7fab070e6acdaf220135351a1baa3a36e5de10 | /log_size_analyzer.cpp | d4aa1c09496271dfe9e22791713e488b29e5abd0 | [] | no_license | jschall/logtools | e23ab9213b663ff4840d76779aa4eb2f53ea02a8 | 71cd1a4e3bf0658fbb3887980466ccd233b606c5 | refs/heads/master | 2023-05-26T23:26:07.429693 | 2023-05-15T14:53:10 | 2023-05-15T14:53:10 | 41,831,595 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,668 | cpp | #include "DFParser.h"
#include <iostream>
#include "json.hpp"
#include <fcntl.h>
#include <sys/mman.h>
#include <iomanip>
#include <sstream>
#include <boost/algorithm/string/join.hpp> // Include for boost::split
using namespace std;
using namespace nlohmann;
int main(int argc, char** argv) {
if (argc < 2) {
cout << "too few arguments" << endl;
return 1;
}
std::ios::sync_with_stdio(false);
int fp = open(argv[1], O_RDONLY, 0);
size_t logdata_len = lseek(fp, 0, SEEK_END);
lseek(fp, 0, SEEK_SET);
uint8_t* logdata = (uint8_t*)mmap(0, logdata_len, PROT_READ, MAP_SHARED, fp, 0);
madvise(logdata, logdata_len, POSIX_MADV_SEQUENTIAL);
DFParser parser(logdata, logdata_len);
uint64_t count=0;
uint8_t type;
DFParser::message_t msg;
json stats;
stats["totalcount"] = 0;
stats["totalbytes"] = 0;
stats["msgs"] = json::object();
while(parser.next_message(msg)) {
auto name = parser.get_message_name(msg);
if (!stats["msgs"].contains(name)) {
stats["msgs"][name]["count"] = 0;
stats["msgs"][name]["bytes"] = 0;
}
stats["msgs"][name]["count"] = (double)stats["msgs"][name]["count"] + 1;
stats["msgs"][name]["bytes"] = (double)stats["msgs"][name]["bytes"] + parser.get_message_size_including_header(msg);
stats["totalcount"] = (double)stats["totalcount"] + 1;
stats["totalbytes"] = (double)stats["totalbytes"] + parser.get_message_size_including_header(msg);
}
for (auto& [key,value] : stats["msgs"].items()) {
cout << key << "," << (int)value["bytes"] << endl;
}
return 0;
}
| [
"mr.challinger@gmail.com"
] | mr.challinger@gmail.com |
699f401d9a07f9fecb62a16782a77de7691b5006 | 573bae2ecbef725f29bff62b05a49a6492f65d70 | /_Common/Source/CPage.cpp | 7a3be346b3565aabf88266132c1bf6bb261660c5 | [] | no_license | Wanghuaichen/SignalProcess | 695760fcf834e9bacac11ee6846d0030b50fc680 | decf9a20fd9c83c2b4e99ca68bc3c74edb732a76 | refs/heads/master | 2020-03-18T21:44:11.218582 | 2014-01-03T09:52:17 | 2014-01-03T09:52:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 78,929 | cpp | #include "stdafx.h"
#include "CPage.h"
////////////////////////////////////////////////////////////////////////////
// Desc: Constructor
// params: RECT ( the area allowed to print to ) CDC* Display context nMapMode the mapping mode
// Returns: nada
///////////////////////////////////////////////////////////////////////////
CPage::CPage(RECT rectDraw, CDC* pDC, int nMapMode)
{
if(nMapMode !=MM_TEXT && nMapMode != MM_ANISOTROPIC)
nMapMode=MM_TEXT;
pDC->SetMapMode(nMapMode );
m_PrtDesc.tm=&tm;
StateInd=-1;
m_PrintMode=GetPrinterMode(pDC);
if(nMapMode==MM_ANISOTROPIC)
{
pDC->SetWindowOrg (0, 0 );
// if you change these numbers you must also change them in maxWidth
// and maxLength for ConvertToMappedUnits() conversion to be correct
pDC->SetWindowExt (1000, 1000 );
pDC->SetViewportOrg (rectDraw.left,rectDraw.top );
pDC->SetViewportExt (rectDraw.right, rectDraw.bottom );
// SEE ABOVE
m_PrtDesc.n_maxWidth=1000;
m_PrtDesc.n_maxLength=1000;
m_PrtDesc.rc.left=0;
m_PrtDesc.rc.top=0;
// SEE ABOVE
m_PrtDesc.rc.right=1000;
m_PrtDesc.rc.bottom=1000;
}
else
{
m_PrtDesc.n_maxWidth=rectDraw.right;
m_PrtDesc.n_maxLength=rectDraw.bottom;
m_PrtDesc.rc.left=rectDraw.left;
m_PrtDesc.rc.top=rectDraw.top;
m_PrtDesc.rc.right=rectDraw.right;
m_PrtDesc.rc.bottom=rectDraw.bottom;
}
// all the textmetrics we need
m_PixPerInchX=pDC->GetDeviceCaps(LOGPIXELSX);
m_PixPerInchY=pDC->GetDeviceCaps(LOGPIXELSY);
// determine how many inches wide and deep the rectangle is
m_WidthInches=rectDraw.right/(double)m_PixPerInchX;
m_LengthInches=rectDraw.bottom/(double)m_PixPerInchY;
m_PrtDesc.pDC=pDC;
// default font stuff
m_PrtDesc.FontName="Times New Roman";
m_PrtDesc.PointSize=10;
m_PrtDesc.m_NextCharPos=0;
// default print flags
m_PrtDesc.uFillFlags=FILL_NONE;
m_PrtDesc.uTextFlags=TEXT_NOCLIP|TEXT_LEFT;
m_PrtDesc.uPenFlags=PEN_SOLID;
// do not change this value
m_PrtDesc.m_MinDisplacement=10;
// modify to increase line spacing but should be no smaller than this
m_Spacing=1.0;
pUserFunc=NULL;
// Test Stuff
m_PrtDesc.MarginOffset=0;
if(m_PrintMode== DMORIENT_LANDSCAPE)
{
if(m_WidthInches > 10.9) // we got a fax driver here
{
double Diff=m_WidthInches-10.5;
Diff=ConvertToMappedUnits(Diff,HORZRES);
m_PrtDesc.MarginOffset=(int) (Diff/2);
}
}
else
{
if(m_WidthInches > 8.0) // we got a fax driver here
{
double Diff=m_WidthInches-8.0;
Diff=ConvertToMappedUnits(Diff,HORZRES);
m_PrtDesc.MarginOffset=(int) (Diff/2);
}
}
////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////
// Desc: Sets the address of the user supplied function to be
// called for the virtual info printing functions
// params: Pointer to a functio of type PF_REMOTE
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::SetUserFunction(PF_REMOTE ptr)
{
pUserFunc=ptr;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Returns the current print mode
// params: The display context* for the output
// Returns: either DMORIENT_LANDSACPE or DMORIENT_PORTRIAT
///////////////////////////////////////////////////////////////////////////
int CPage::GetPrinterMode(CDC* pDC)
{
int Mode;
if(!pDC->IsPrinting())
return 0;
PRINTDLG* pPrintDlg = new PRINTDLG;
AfxGetApp()->GetPrinterDeviceDefaults(pPrintDlg);
DEVMODE* lpDevMode = (DEVMODE*)::GlobalLock(pPrintDlg->hDevMode);
Mode= lpDevMode->dmOrientation;
::GlobalUnlock(pPrintDlg->hDevMode);
delete pPrintDlg;
return Mode;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Destructor deletes the regions from the list if any
// params: None
// Returns: None
///////////////////////////////////////////////////////////////////////////
CPage::~CPage()
{
CPrintRegion* pRegion;
for(int y=0;y < m_RegionList.GetSize();++y)
{
pRegion=(CPrintRegion*)m_RegionList[y];
delete pRegion;
}
m_RegionList.RemoveAll();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Saves the current printer variables to a psuedo stack
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::SaveState()
{
m_SaveState[++StateInd]=m_PrtDesc;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Restores printer variables saved by above
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::RestoreState()
{
if(StateInd==-1)
return;
m_PrtDesc=m_SaveState[StateInd--];
}
////////////////////////////////////////////////////////////////////////////
// PARAMETER ACCESS ROUTINES
////////////////////////////////////////////////////////////////////////////
// Desc: Changes the width of the default allowable printing area
// params: The new right side coordinates in mapping units:If 0 there is no change
// if -1 margin is set to maximum allowable size
// Returns: The previous coordinates
///////////////////////////////////////////////////////////////////////////
int CPage::SetRightMargin(int w)
{
int temp=m_PrtDesc.rc.right;
if(w > 0)
m_PrtDesc.rc.right=w;
if(w==-1)
m_PrtDesc.rc.right=m_PrtDesc.n_maxWidth;
return temp;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Sets new coordinates for allowable printing rectangle depth
// params: The new coordinate in mapping units:If 0 there is no change
// if -1 margin is set to maximum allowable size
// Returns: The old coordinate
///////////////////////////////////////////////////////////////////////////
int CPage::SetBottomMargin(int w)
{
int temp=m_PrtDesc.rc.bottom;
if(w > 0)
m_PrtDesc.rc.bottom=w;
if(w== -1)
m_PrtDesc.rc.right=m_PrtDesc.n_maxLength;
return temp;
}
////////////////////////////////////////////////////////////////////////////
// Desc: See above
// params: Same as above except units are in inches
// Returns: See above
///////////////////////////////////////////////////////////////////////////
double CPage::SetRightMargin(double w)
{
int temp=m_PrtDesc.rc.right;
if(w > 0)
m_PrtDesc.rc.right=ConvertToMappedUnits(w,HORZRES);
if(w==-1)
m_PrtDesc.rc.right=m_PrtDesc.n_maxWidth;
return ConvertToInches(temp,HORZRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: See Above
// params: Same as above except units are in inches: if 0 no change
// Returns: See Above
///////////////////////////////////////////////////////////////////////////
double CPage::SetBottomMargin(double w)
{
int temp=m_PrtDesc.rc.bottom;
if(w > 0)
m_PrtDesc.rc.bottom=ConvertToMappedUnits(w,VERTRES);
if(w==-1)
m_PrtDesc.rc.right=m_PrtDesc.n_maxLength;
return ConvertToInches(temp,VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Changes the space returned for the next logical line
// params: The constant applied to the fontsize to produce the spacing The formula is
// ConvertToMappedUnits(PointSize/72.0,VERTRES)*(m_Spacing-1))
// Returns: The old spacing factor
///////////////////////////////////////////////////////////////////////////
double CPage::SetLineSpacing(double Spacing)
{
double temp=m_Spacing;
if(Spacing > 0)
m_Spacing=Spacing;
return temp;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Changes the font face used for printing
// params: The new face name IE Courier
// Returns: he old font face
///////////////////////////////////////////////////////////////////////////
LPCSTR CPage::SetFont(LPCSTR FontName)
{
static char buff[40];
strcpy(buff,m_PrtDesc.FontName);
if(FontName != NULL)
m_PrtDesc.FontName=FontName;
return buff;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Sets The text Color if the device supports colored text
// params: The color
// Returns:The old color
///////////////////////////////////////////////////////////////////////////
COLORREF CPage::SetColor(COLORREF Color)
{
return m_PrtDesc.pDC->SetTextColor(Color);
}
////////////////////////////////////////////////////////////////////////////
// Desc: changes the default font size
// params: the size
// Returns: the old size
///////////////////////////////////////////////////////////////////////////
int CPage::SetFontSize(int sz)
{
int temp=m_PrtDesc.PointSize;
m_PrtDesc.PointSize=sz;
return temp;
}
////////////////////////////////////////////////////////////////////////////
// Desc: fetch the display context used by this object
// params:
// Returns: a pointer to the display context
///////////////////////////////////////////////////////////////////////////
CDC* CPage::GetDisplayContext()
{
return m_PrtDesc.pDC;
}
////////////////////////////////////////////////////////////////////////////
// Desc: returns the next logical print column. Used in printing continious text that
// may have different text attributes
// params:Convert flag to convert to inches.AddOffset flag add a extra space
// Returns: the logical column offset.double is used so it can handle all mapping units.
// if Convert is true the result is in inches else in device units.
///////////////////////////////////////////////////////////////////////////
double CPage::GetNextLogicalColumn(BOOL Convert,BOOL AddOffset)
{
if(Convert==FALSE)
{
if(AddOffset)
return m_nNextPos+tm.tmMaxCharWidth;
else
return m_nNextPos;
}
else
{
if(AddOffset)
return ConvertToInches(m_nNextPos+tm.tmMaxCharWidth,HORZRES);
else
return ConvertToInches(m_nNextPos,HORZRES);
}
}
////////////////////////////////////////////////////////////////////////////
// UNIT CONVERSION ROUTINES
////////////////////////////////////////////////////////////////////////////
// Desc: Converts inches to physical units based on the mapping mode
// params: dwInch ( the number of inches bWidth either VERTRES or HORTZRES
// Returns: the physical device displacment representing the number of inches
//
// conversion is done as follows:mapmode=MM_TEXT;
// The number of inches are multiplied by the constant for the # of pixels per inch
// in the diminsion requested.The value(s) for the # of pixels are set at creation
// of the object and are retrieved from the GetDevCaps function
// mapmode=MM_ANISOTROPIC:
// The size in inches for the requested diminsion are devided by 1000 to get the
// size in inches for each unit. This value is devided into the requested size
// to return the physical offset, for example
// width of display is 10 in
// 10/1000=.01. So we want to go three inches to the right 3.0/.01=300 logical
// units
// hight of display is 12 in
// 12/1000=.012. To move 5 inches down 5.0/.012=417 logical units
// NOTES:
// These conversion routines attempt to normalize positioning between the two allowed
// mapping modes but are not exact due to cumalitive rounding errors.While in MM_TEXT
// mode the units will be much smaller than in MM_ANISOTROPIC mode and therefore the
// class can position the text with a much finer position. When in ANISOTROPIC mode
// the smallest unit can be as much as 2.8 pixels per unit resulting in small but
// noticable differences in positioning
///////////////////////////////////////////////////////////////////////////
int CPage::ConvertToMappedUnits(double dwInch,int bWidth)
{
double tempx,tempy;
if(dwInch <=0)
return 0;
if(m_PrtDesc.pDC->GetMapMode()==MM_TEXT)
{
if(bWidth==HORZRES)
return (int)(dwInch*m_PixPerInchX);
else
return (int)(dwInch*m_PixPerInchY);
}
tempx=m_WidthInches/m_PrtDesc.n_maxWidth;
tempy=m_LengthInches/m_PrtDesc.n_maxLength;
if(bWidth==HORZRES)
return (int)(dwInch/tempx);
else
return (int)(dwInch/tempy);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Converts physical device units to inches
// params: value ( the # of physical units to convert bWidth HORZRES or VERTRES
// Returns: The number of inches defined by the displacment
///////////////////////////////////////////////////////////////////////////
double CPage::ConvertToInches(int value,int bWidth)
{
double tempx,tempy;
if(value <=0)
return 0;
if(m_PrtDesc.pDC->GetMapMode()==MM_TEXT)
{
if(bWidth==HORZRES)
return ((double)value/(double)m_PixPerInchX);
else
return ((double)value/(double)m_PixPerInchY);
}
tempx=m_WidthInches/(double)m_PrtDesc.n_maxWidth;
tempy=m_LengthInches/(double)m_PrtDesc.n_maxLength;
if(bWidth==HORZRES)
return (double)(value*tempx);
else
return (double)(value*tempy);
}
////////////////////////////////////////////////////////////////////////////
// CONVERSION ROUTINES pixels to inches
////////////////////////////////////////////////////////////////////////////
// Desc: Converts a position in inches to logical units
// params: Row ( same as rect.top) Col ( same as rect.left)
// Returns: none but parameters are changed indirectly
///////////////////////////////////////////////////////////////////////////
void CPage::ConvertPosition(double& Row,double& Col)
{
Row=ConvertToMappedUnits(Row,VERTRES);
Col=ConvertToMappedUnits(Col,HORZRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: same as above but does the whole rectangle at once
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::ConvertArea(double& top,double& left,double& bottom,double& right)
{
top=ConvertToMappedUnits(top,VERTRES);
left=ConvertToMappedUnits(left,HORZRES);
bottom=ConvertToMappedUnits(bottom,VERTRES);
right=ConvertToMappedUnits(right,HORZRES);
}
////////////////////////////////////////////////////////////////////////////
// TEXT PRINT ROUTINES
////////////////////////////////////////////////////////////////////////////
// Desc: Very low level call. All Print Routines end up here. Do not call direct
// params: LPCSTR the text to print StartPos starting column Text flasg and Pointsize
// Returns: The next logical vertical print position
///////////////////////////////////////////////////////////////////////////
int CPage::Print(LPCSTR Text,int StartPos,UINT flags,int PointSize)
{
if(StartPos > SetRightMargin(0))
return m_PrtDesc.rc.top;
if(m_PrtDesc.rc.top > SetBottomMargin(0))
return m_PrtDesc.rc.top;
//m_PrtDesc.rc.left+=MarginOffset;
m_PrtDesc.Text=Text;
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
if(StartPos==-1)
m_PrtDesc.rc.left=m_PrtDesc.m_NextCharPos;
else
m_PrtDesc.rc.left=StartPos;
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
m_nNextPos=m_PrtDesc.m_NextCharPos;
return m_PrtDesc.LastPrintArea.bottom;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints using printf variable length print arguments
// params: Row,Col-Location Coordinates arg list uses current default flags
// Returns:The next logical print line using the current font size and line spacing
///////////////////////////////////////////////////////////////////////////
int CPage::Print(int row,int col,const char* fmt,...)
{
va_list t;
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
m_PrtDesc.rc.top=row;
int res=Print(Buffer,col,m_PrtDesc.uTextFlags,m_PrtDesc.PointSize);
va_end(t);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return res+nLineSpacing;
}
////////////////////////////////////////////////////////////////////////////
// Desc: same as above only position info is in inches, not device units
// params:
// Returns:same as above only in inches, not device units
///////////////////////////////////////////////////////////////////////////
double CPage::Print(double row,double col,const char* fmt,...)
{
va_list t;
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
ConvertPosition(row,col);
m_PrtDesc.rc.top=(int)row;
int res=Print(Buffer,(int)col,m_PrtDesc.uTextFlags,m_PrtDesc.PointSize);
va_end(t);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return ConvertToInches(res+nLineSpacing,VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints using data supplied as return value from user function
// params: Row,Col-Location Coordinates user ID to be supplied to user function
// Returns:The next logical print line using the current font size and line spacing
///////////////////////////////////////////////////////////////////////////
int CPage::Print(int row,int col,int ID)
{
if(pUserFunc==NULL)
return 0;
m_PrtDesc.rc.top=row;
int res=Print(pUserFunc(ID),col,m_PrtDesc.uTextFlags,m_PrtDesc.PointSize);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return res+nLineSpacing;
}
////////////////////////////////////////////////////////////////////////////
// Desc: same as above only position info is in inches, not device units
// params:
// Returns:same as above only in inches, not device units
///////////////////////////////////////////////////////////////////////////
double CPage::Print(double row,double col,int ID)
{
if(pUserFunc==NULL)
return 0;
ConvertPosition(row,col);
m_PrtDesc.rc.top=(int)row;
int res=Print(pUserFunc(ID),(int)col,m_PrtDesc.uTextFlags,m_PrtDesc.PointSize);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return ConvertToInches(res+nLineSpacing,VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints by calling user defined function for data
// params: Row,Col-Location Coordinates TextFlags Point size user id
// Returns:The next logical print line using the current font size and line spacing
///////////////////////////////////////////////////////////////////////////
int CPage::Print(int row,int col,UINT TextFlags,int PointSize,int ID)
{
if(pUserFunc==NULL)
return 0;
m_PrtDesc.rc.top=row;
int res=Print(pUserFunc(ID),col,TextFlags,PointSize);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return res+nLineSpacing;
}
////////////////////////////////////////////////////////////////////////////
// Desc: same as above only position info is in inches, not device units
// params:
// Returns:same as above only in inches, not device units
///////////////////////////////////////////////////////////////////////////
double CPage::Print(double row,double col,UINT TextFlags,int PointSize,int ID)
{
if(pUserFunc==NULL)
return 0;
ConvertPosition(row,col);
m_PrtDesc.rc.top=(int)row;
int res=Print(pUserFunc(ID),(int)col,TextFlags,PointSize);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return ConvertToInches(res+nLineSpacing,VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints using printf variable length print arguments
// params: Row,Col-Location Coordinates TextFlags Point size variable arg list
// Returns:The next logical print line using the current font size and line spacing
///////////////////////////////////////////////////////////////////////////
int CPage::Print(int row,int col,UINT TextFlags,int PointSize,const char* fmt,...)
{
va_list t;
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
m_PrtDesc.rc.top=row;
int res=Print(Buffer,col,TextFlags,PointSize);
va_end(t);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return res+nLineSpacing;
}
////////////////////////////////////////////////////////////////////////////
// Desc: same as above only position info is in inches, not device units
// params:
// Returns:same as above only in inches, not device units
///////////////////////////////////////////////////////////////////////////
double CPage::Print(double row,double col,UINT TextFlags,int PointSize,const char* fmt,...)
{
va_list t;
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
ConvertPosition(row,col);
m_PrtDesc.rc.top=(int)row;
int res=Print(Buffer,(int)col,TextFlags,PointSize);
va_end(t);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return ConvertToInches(res+nLineSpacing,VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Same as above except col is a pointer and is updated to the next locical print column
// params:
// Returns: The next logical print row
///////////////////////////////////////////////////////////////////////////
double CPage::Print(double row,double *col,UINT TextFlags,int PointSize,const char* fmt,...)
{
va_list t;
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
ConvertPosition(row,*col);
m_PrtDesc.rc.top=(int)row;
int res=Print(Buffer,(int)(*col),TextFlags,PointSize);
va_end(t);
*col=GetNextLogicalColumn();
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return ConvertToInches(res+nLineSpacing,VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Same as above except col is updates to the next logical column
// params: See above
// Returns: See above
///////////////////////////////////////////////////////////////////////////
int CPage::Print(int row,int *col,UINT TextFlags,int PointSize,const char* fmt,...)
{
va_list t;
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
m_PrtDesc.rc.top=row;
int res=Print(Buffer,*col,TextFlags,PointSize);
va_end(t);
*col=(int)GetNextLogicalColumn(FALSE);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
return res+nLineSpacing;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints using printf variable length print arguments
// params:
// Returns:The next logical print line using the current font size and line spacing
///////////////////////////////////////////////////////////////////////////
int CPage::Print(CPrintRegion* pRegion,int row,int col,UINT TextFlags,int PointSize,const char* fmt,...)
{
UINT OldMode,OldColor;
va_list t;
SaveState();
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
m_PrtDesc.rc.top=row+pRegion->FirstY;
m_PrtDesc.rc.bottom=pRegion->bottom;
m_PrtDesc.rc.right=pRegion->right;
m_PrtDesc.rc.left=pRegion->FirstX;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
int res=Print(Buffer,col+pRegion->FirstX,TextFlags,PointSize);
va_end(t);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
RestoreState();
return (res-pRegion->FirstY)+nLineSpacing;
}
////////////////////////////////////////////////////////////////////////////
// Desc: same as above only position info is in inches, not device units
// params:
// Returns:same as above only in inches, not device units
///////////////////////////////////////////////////////////////////////////
double CPage::Print(CPrintRegion* pRegion,double row,double col,UINT TextFlags,int PointSize,const char* fmt,...)
{
UINT OldColor,OldMode;
va_list t;
SaveState();
va_start(t,fmt);
vsprintf(Buffer,fmt,t);
ConvertPosition(row,col);
m_PrtDesc.rc.top=(int)row+pRegion->FirstY;
m_PrtDesc.rc.bottom=pRegion->bottom;
m_PrtDesc.rc.right=pRegion->right;
m_PrtDesc.rc.left=pRegion->FirstX;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
int res=Print(Buffer,(int)col+pRegion->FirstX,TextFlags,PointSize);
va_end(t);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
RestoreState();
return ConvertToInches( (int)( (res-pRegion->FirstY)+nLineSpacing),VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints using user defined function for data
// params:
// Returns:The next logical print line using the current font size and line spacing
///////////////////////////////////////////////////////////////////////////
int CPage::Print(CPrintRegion* pRegion,int row,int col,UINT TextFlags,int PointSize,int ID)
{
UINT OldColor,OldMode;
if(pUserFunc==NULL)
return 0;
SaveState();
m_PrtDesc.rc.top=row+pRegion->FirstY;
m_PrtDesc.rc.bottom=pRegion->bottom;
m_PrtDesc.rc.right=pRegion->right;
m_PrtDesc.rc.left=pRegion->FirstX;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
int res=Print(pUserFunc(ID),col+pRegion->FirstX,TextFlags,PointSize);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
RestoreState();
return (res-pRegion->FirstY)+nLineSpacing;
}
////////////////////////////////////////////////////////////////////////////
// Desc: same as above only position info is in inches, not device units
// params:
// Returns:same as above only in inches, not device units
///////////////////////////////////////////////////////////////////////////
double CPage::Print(CPrintRegion* pRegion,double row,double col,UINT TextFlags,int PointSize,int ID)
{
UINT OldColor,OldMode;
if(pUserFunc==NULL)
return 0;
SaveState();
ConvertPosition(row,col);
m_PrtDesc.rc.top=(int)row+pRegion->FirstY;
m_PrtDesc.rc.bottom=pRegion->bottom;
m_PrtDesc.rc.right=pRegion->right;
m_PrtDesc.rc.left=pRegion->FirstX;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
int res=Print(pUserFunc(ID),(int)col+pRegion->FirstX,TextFlags,PointSize);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
int nLineSpacing = m_Spacing > 1 ? (int)(ConvertToMappedUnits(m_PrtDesc.PointSize/72.0,VERTRES)*(m_Spacing-1)):0;
RestoreState();
return ConvertToInches( (int)( (res-pRegion->FirstY)+nLineSpacing),VERTRES);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params: coordinates of the bounding rectangle flags pointsize and text to print
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(int Top,int Left,int Bottom,int Right,UINT flags,int PointSize,LPCSTR Text)
{
if(Left > SetRightMargin(0))
return;
if(Top > SetBottomMargin(0))
return;
SaveState();
m_PrtDesc.Text=Text;
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=Left;
m_PrtDesc.rc.top=Top;
m_PrtDesc.rc.right=Right;
m_PrtDesc.rc.bottom=Bottom;
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(double Top,double Left,double Bottom,double Right,UINT flags,int PointSize,LPCSTR Text)
{
if(Left > SetRightMargin(0.0))
return;
if(Top > SetBottomMargin(0.0))
return;
SaveState();
m_PrtDesc.Text=Text;
ConvertArea(Top,Left,Bottom,Right);
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=(int)Left;
m_PrtDesc.rc.top=(int)Top;
m_PrtDesc.rc.right=(int)Right;
m_PrtDesc.rc.bottom=(int)Bottom;
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params: coordinates of the bounding rectangle flags pointsize and user supplied ID
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(int Top,int Left,int Bottom,int Right,UINT flags,int PointSize,int ID)
{
if(pUserFunc==NULL)
return;
if(Left > SetRightMargin(0))
return;
if(Top > SetBottomMargin(0))
return;
SaveState();
m_PrtDesc.Text=pUserFunc(ID);
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=Left;
m_PrtDesc.rc.top=Top;
m_PrtDesc.rc.right=Right;
m_PrtDesc.rc.bottom=Bottom;
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params: Calls user defined function for data
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(double Top,double Left,double Bottom,double Right,UINT flags,int PointSize,int ID)
{
if(pUserFunc==NULL)
return;
if(Left > SetRightMargin(0.0))
return;
if(Top > SetBottomMargin(0.0))
return;
SaveState();
m_PrtDesc.Text=pUserFunc(ID);
ConvertArea(Top,Left,Bottom,Right);
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=(int)Left;
m_PrtDesc.rc.top=(int)Top;
m_PrtDesc.rc.right=(int)Right;
m_PrtDesc.rc.bottom=(int)Bottom;
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(CPrintRegion* pRegion,int Top,int Left,int Bottom,int Right,UINT flags,int PointSize,LPCSTR Text)
{
UINT OldColor,OldMode;
SaveState();
m_PrtDesc.Text=Text;
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=Left+pRegion->FirstX;
m_PrtDesc.rc.top=Top+pRegion->FirstY;
m_PrtDesc.rc.right=Right+pRegion->FirstX;
m_PrtDesc.rc.bottom=Bottom+pRegion->FirstY;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(CPrintRegion* pRegion,double Top,double Left,double Bottom,double Right,UINT flags,int PointSize,LPCSTR Text)
{
UINT OldColor,OldMode;
SaveState();
m_PrtDesc.Text=Text;
ConvertArea(Top,Left,Bottom,Right);
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=(int)Left+pRegion->FirstX;
m_PrtDesc.rc.top=(int)Top+pRegion->FirstY;
m_PrtDesc.rc.right=(int)Right+pRegion->FirstX;
m_PrtDesc.rc.bottom=(int)Bottom+pRegion->FirstY;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params: Calls user defined function for data
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(CPrintRegion* pRegion,int Top,int Left,int Bottom,int Right,UINT flags,int PointSize,int ID)
{
UINT OldColor,OldMode;
if(pUserFunc==NULL)
return;
SaveState();
m_PrtDesc.Text=pUserFunc(ID);
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=Left+pRegion->FirstX;
m_PrtDesc.rc.top=Top+pRegion->FirstY;
m_PrtDesc.rc.right=Right+pRegion->FirstX;
m_PrtDesc.rc.bottom=Bottom+pRegion->FirstY;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints text clipped to a bounding rectangle. See the header for default
// parameters. Allows for newspaper like columns
// params: Calls user defined function for data
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintColumn(CPrintRegion* pRegion,double Top,double Left,double Bottom,double Right,UINT flags,int PointSize,int ID)
{
UINT OldColor,OldMode;
if(pUserFunc==NULL)
return ;
SaveState();
m_PrtDesc.Text=pUserFunc(ID);
ConvertArea(Top,Left,Bottom,Right);
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=(int)Left+pRegion->FirstX;
m_PrtDesc.rc.top=(int)Top+pRegion->FirstY;
m_PrtDesc.rc.right=(int)Right+pRegion->FirstX;
m_PrtDesc.rc.bottom=(int)Bottom+pRegion->FirstY;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// DRAWING ROUTINES ( SHAPES )
////////////////////////////////////////////////////////////////////////////
// Desc: Draws a line from point top,left to bottom,right
// params: position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Line(int top,int left,int bottom,int right,int LineSize,UINT flag)
{
SaveState();
if(flag != IGNORE_PARAM)
m_PrtDesc.uPenFlags=flag;
m_PrtDesc.rc.top=top;
m_PrtDesc.rc.bottom=bottom;
m_PrtDesc.rc.left=left;
m_PrtDesc.rc.right=right;
ThePrinter.DrawLine(&m_PrtDesc,LineSize);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a line using parameters passed
// params: position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Line(double top,double left,double bottom,double right,int LineSize,UINT flag)
{
SaveState();
if(flag != IGNORE_PARAM)
m_PrtDesc.uPenFlags=flag;
ConvertArea(top,left,bottom,right);
m_PrtDesc.rc.top=(int)top;
m_PrtDesc.rc.bottom=(int)bottom;
m_PrtDesc.rc.left=(int)left;
m_PrtDesc.rc.right=(int)right;
ThePrinter.DrawLine(&m_PrtDesc,LineSize);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a rectangle using parameters passed
// params: position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Box(int top,int left,int bottom,int right,int LineSize,UINT Fillflags,UINT PenFlags)
{
SaveState();
if(Fillflags != IGNORE_PARAM)
m_PrtDesc.uFillFlags=Fillflags;
if(PenFlags != IGNORE_PARAM)
m_PrtDesc.uPenFlags=PenFlags;
m_PrtDesc.rc.top=top;
m_PrtDesc.rc.bottom=bottom;
m_PrtDesc.rc.left=left;
m_PrtDesc.rc.right=right;
ThePrinter.DrawRect(&m_PrtDesc,LineSize);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a rectangle using parameters passed
// params: position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Box(double top,double left,double bottom,double right,int LineSize,UINT Fillflags,UINT PenFlags)
{
SaveState();
if(Fillflags != IGNORE_PARAM)
m_PrtDesc.uFillFlags=Fillflags;
if(PenFlags != IGNORE_PARAM)
m_PrtDesc.uPenFlags=PenFlags;
ConvertArea(top,left,bottom,right);
m_PrtDesc.rc.top=(int)top;
m_PrtDesc.rc.bottom=(int)bottom;
m_PrtDesc.rc.left=(int)left;
m_PrtDesc.rc.right=(int)right;
ThePrinter.DrawRect(&m_PrtDesc,LineSize);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draws a line from point top,left to bottom,right
// params: CPrintRegion*, position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Line(CPrintRegion* pRegion,int top,int left,int bottom,int right,int LineSize,UINT flag)
{
UINT OldColor,OldMode;
SaveState();
if(flag != IGNORE_PARAM)
m_PrtDesc.uPenFlags=flag;
m_PrtDesc.rc.top=(int)top+pRegion->FirstY;
m_PrtDesc.rc.bottom=(int)bottom+pRegion->FirstY;
m_PrtDesc.rc.left=(int)left+pRegion->FirstX;
m_PrtDesc.rc.right=(int)right+pRegion->FirstX;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.DrawLine(&m_PrtDesc,LineSize);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a line using parameters passed
// params:CPrintRegion*, position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Line(CPrintRegion* pRegion,double top,double left,double bottom,double right,int LineSize,UINT flag)
{
UINT OldColor,OldMode;
SaveState();
if(flag != IGNORE_PARAM)
m_PrtDesc.uPenFlags=flag;
ConvertArea(top,left,bottom,right);
m_PrtDesc.rc.top=(int)top+pRegion->FirstY;
m_PrtDesc.rc.bottom=(int)bottom+pRegion->FirstY;
m_PrtDesc.rc.left=(int)left+pRegion->FirstX;
m_PrtDesc.rc.right=(int)right+pRegion->FirstX;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.DrawLine(&m_PrtDesc,LineSize);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a rectangle using parameters passed
// params:CPrintRegion*, position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Box(CPrintRegion* pRegion,int top,int left,int bottom,int right,int LineSize,UINT Fillflags,UINT PenFlags)
{
UINT OldColor,OldMode;
SaveState();
if(Fillflags != IGNORE_PARAM)
m_PrtDesc.uFillFlags=Fillflags;
if(PenFlags != IGNORE_PARAM)
m_PrtDesc.uPenFlags=PenFlags;
m_PrtDesc.rc.top=(int)top+pRegion->FirstY;
m_PrtDesc.rc.bottom=(int)bottom+pRegion->FirstY;
m_PrtDesc.rc.left=(int)left+pRegion->FirstX;
m_PrtDesc.rc.right=(int)right+pRegion->FirstX;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.DrawRect(&m_PrtDesc,LineSize);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a rectangle using parameters passed
// params:CPrintRegion*, position, line size 1--x,flag is pen flags (see header)
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Box(CPrintRegion* pRegion,double top,double left,double bottom,double right,int LineSize,UINT Fillflags,UINT PenFlags)
{
UINT OldColor,OldMode;
SaveState();
if(Fillflags != IGNORE_PARAM)
m_PrtDesc.uFillFlags=Fillflags;
if(PenFlags != IGNORE_PARAM)
m_PrtDesc.uPenFlags=PenFlags;
ConvertArea(top,left,bottom,right);
m_PrtDesc.rc.top=(int)top+pRegion->FirstY;
m_PrtDesc.rc.bottom=(int)bottom+pRegion->FirstY;
m_PrtDesc.rc.left=(int)left+pRegion->FirstX;
m_PrtDesc.rc.right=(int)right+pRegion->FirstX;
if(m_PrtDesc.rc.bottom > pRegion->bottom)
m_PrtDesc.rc.bottom=pRegion->bottom;
if(m_PrtDesc.rc.left > pRegion->right)
m_PrtDesc.rc.left=pRegion->right;
if(m_PrtDesc.rc.top > pRegion->bottom)
m_PrtDesc.rc.top=pRegion->bottom;
if(m_PrtDesc.rc.right > pRegion->right)
m_PrtDesc.rc.right=pRegion->right;
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
ThePrinter.DrawRect(&m_PrtDesc,LineSize);
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a checkbox using parameters passed
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::CheckBox(LPCSTR Caption,BOOL Data,double top,double left,int FontSize,int Direction,int LineSize,UINT FillFlag,UINT PrintFlags)
{
ConvertPosition(top,left);
CheckBox(Caption,Data,(int) top,(int)left,FontSize,Direction,LineSize,FillFlag,PrintFlags);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a checkbox using parameters passed
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::CheckBox(LPCSTR Caption,BOOL Data,int top,int left,int FontSize,int Direction,int LineSize,UINT FillFlag,UINT PrintFlags)
{
SaveState();
if(Direction==LABEL_LEFT)
{
Print(top,left,PrintFlags,FontSize,Caption);
left=(int)GetNextLogicalColumn(FALSE,TRUE);
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
if(Data)
{
if(FillFlag!= FILL_NONE)
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize,FillFlag);
else
{
Line(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
Line(top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left,top,left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
}
}
}
else
{
Print(top,left+(2*ConvertToMappedUnits(FontSize/72.0,HORZRES)),PrintFlags,FontSize,Caption);
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
if(Data)
{
if(FillFlag!= FILL_NONE)
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize,FillFlag);
else
{
Line(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
Line(top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left,top,left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
}
}
}
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a checkbox using parameters passed
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::CheckBox(CPrintRegion* pRegion,LPCSTR Caption,BOOL Data,double top,double left,int FontSize,int Direction,int LineSize,UINT FillFlag,UINT PrintFlags)
{
ConvertPosition(top,left);
CheckBox(pRegion,Caption,Data,(int) top,(int)left,FontSize,Direction,LineSize,FillFlag,PrintFlags);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw a checkbox using parameters passed
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::CheckBox(CPrintRegion* pRegion,LPCSTR Caption,BOOL Data,int top,int left,int FontSize,int Direction,int LineSize,UINT FillFlag,UINT PrintFlags)
{
UINT OldColor,OldMode;
SaveState();
if(pRegion->FillColor > FILL_NONE)
OldMode=m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(pRegion->FillColor > FILL_LTGRAY)
OldColor= SetColor(COLOR_WHITE);
m_PrtDesc.rc.bottom=pRegion->bottom;
m_PrtDesc.rc.right=pRegion->right;
m_PrtDesc.rc.left=pRegion->FirstX;
top+=pRegion->FirstY;
left+=pRegion->FirstX;
if(Direction==LABEL_LEFT)
{
Print(top,left,PrintFlags,FontSize,Caption);
left=(int)GetNextLogicalColumn(FALSE,TRUE);
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
if(Data)
{
if(FillFlag!= FILL_NONE)
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize,FillFlag);
else
{
Line(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
Line(top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left,top,left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
}
}
}
else
{
Print(top,left+(2*ConvertToMappedUnits(FontSize/72.0,HORZRES)),PrintFlags,FontSize,Caption);
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
if(Data)
{
if(FillFlag!= FILL_NONE)
Box(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize,FillFlag);
else
{
Line(top,left,top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
Line(top+ConvertToMappedUnits(FontSize/72.0,VERTRES),left,top,left+ConvertToMappedUnits(FontSize/72.0,HORZRES),LineSize);
}
}
}
if(pRegion->FillColor > FILL_NONE)
m_PrtDesc.pDC->SetBkMode(OldMode);
if(pRegion->FillColor > FILL_LTGRAY)
SetColor(OldColor);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Creates a moveable print region
// params: location of region in 4 points
// Returns: Pointer to the new region or a NULL
///////////////////////////////////////////////////////////////////////////
CPrintRegion* CPage::CreateRegion(double ptop,double pleft,double pbottom, double pright,UINT Fill)
{
ConvertArea(ptop,pleft,pbottom,pright);
return CreateRegion((int) ptop,(int) pleft,(int) pbottom, (int) pright,Fill);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Create a CprintRegion structure and maintain a list of created structures
// to free allocated memory when destructor runs
// params: bounding rectangle for the region
// Returns: pointer to the created structure
///////////////////////////////////////////////////////////////////////////
CPrintRegion* CPage::CreateRegion(int ptop,int pleft,int pbottom, int pright,UINT Fill)
{
CPrintRegion* pRegion= new CPrintRegion;
if(pRegion==NULL)
return pRegion;
pRegion->FillColor=Fill;
if( pRegion->Create(this,ptop,pleft,pright, pbottom,Fill)==FALSE)
{
delete pRegion;
return (CPrintRegion*)0;
}
m_RegionList.Add(pRegion);
return pRegion;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Constructor for a table descriptor class
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
TABLEHEADER::TABLEHEADER()
{
SetSkip=0;
AutoSize=TRUE;
UseInches=FALSE;
PointSize=10;
LineSize=1;
NumColumns=2;
NumRows=2;
Border=TRUE;
VLines=TRUE;
HLines=TRUE;
NoHeader=HeaderOnly=FALSE;
HeaderLines=1;
NumPrintLines=1;
FillFlag=FILL_NONE;
StartRow=EndCol=StartCol=0;
pClsTable=NULL;
}
TABLEHEADER::~TABLEHEADER()
{
if(pClsTable != NULL)
delete pClsTable;
};
////////////////////////////////////////////////////////////////////////////
// Desc: Create and attach a table object to the print object. If the unit
// of measurment is in inches all conversions are done at this point.Once the
// table object is created it is displayed by the call to PrintTable.DO NOT CALL
// PRINTTABLE DIRECTLY ALWAYS USE THIS FUNCTION
// params: The table descriptor for the table
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Table(TABLEHEADER* TheTable)
{
PRTTYPE temp;
if(TheTable->NoHeader==TRUE)
TheTable->HeaderLines=0;
if(TheTable->UseInches)
{
TheTable->StartRow=ConvertToMappedUnits(TheTable->StartRow,VERTRES);
TheTable->StartCol=ConvertToMappedUnits(TheTable->StartCol,HORZRES);
TheTable->EndCol=ConvertToMappedUnits(TheTable->EndCol,HORZRES);
TheTable->EndRow=ConvertToMappedUnits(TheTable->EndRow,VERTRES);
for(int y=0;y < TheTable->NumColumns;++y)
TheTable->ColDesc[y].Width=ConvertToMappedUnits(TheTable->ColDesc[y].Width,HORZRES);
}
// check for horizontal margins
if(TheTable->EndCol > SetRightMargin(0))
return;
// create a table printing object and attach it to the table descriptor
CPrintTable* pTable=new CPrintTable(TheTable,this);
// pTable will be freed when the destructor for Thetable runs
// if you free it early there will be a system crash
TheTable->pClsTable=pTable;
temp=m_PrtDesc;
// print rhe table
pTable->PrintTable();
if(TheTable->UseInches)
TheTable->EndRow=ConvertToInches((int)TheTable->EndRow,VERTRES);
m_PrtDesc=temp;
}
////////////////////////////////////////////////////////////////////////////
// Desc: See CPage::Print () for details
// params: The table row and cloumn to print into, pointsixe textflags and variable arg list
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::Print(TABLEHEADER* TheTable,int row,int col,int PointSize,UINT TextFlags,char* fmt,...)
{
CPrintTable* pTable=TheTable->pClsTable;
if(pTable==NULL)
return;
char* buff=new char[1000];
va_list t;
SaveState();
va_start(t,fmt);
vsprintf(buff,fmt,t);
if(TheTable->HeaderOnly==FALSE)
pTable->InsertItem(buff,row,col,PointSize,TextFlags);
else
pTable->InsertVirtualItem(buff,row,col,PointSize,TextFlags);
va_end(t);
delete[] buff;
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Print a disk based bitmapped imiage to the display
// params: The location in 4 points and full path to the imiage
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintBitMap(int top,int left,int bottom,int right,LPCSTR name)
{
extern BOOL WINAPI PrintTheBitMap(PRTTYPE *ps);
SaveState();
m_PrtDesc.rc.top=top;
m_PrtDesc.rc.bottom=bottom;
m_PrtDesc.rc.left=left;
m_PrtDesc.rc.right=right;
m_PrtDesc.Text=name;
PrintTheBitMap(&m_PrtDesc);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: See above
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintBitMap(double top,double left,double bottom,double right,LPCSTR name)
{
extern BOOL WINAPI PrintTheBitMap(PRTTYPE *ps);
SaveState();
ConvertArea(top,left,bottom,right);
m_PrtDesc.rc.top=(int)top;
m_PrtDesc.rc.bottom=(int)bottom;
m_PrtDesc.rc.left=(int)left;
m_PrtDesc.rc.right=(int)right;
m_PrtDesc.Text=name;
PrintTheBitMap(&m_PrtDesc);
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Helper class CPrintTable here
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Desc: places a value in a cell on the table defined as row,col. Do not call direct
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::InsertItem(LPCSTR Text,int row,int col,int PointSize,UINT TextFlags)
{
int y,SCol,ECol,Row,OldColor,OldMode;
int sz=GetVerticalSpacing();
if(row >= m_pTable->NumRows)
return;
if(PointSize < 1)
PointSize=m_pTable->PointSize;
// vertical displacement is determined by the font used by the column headers. If
// the font used to insert a item is larger it will look funny. So we adjust that
// here by assuring the font for the item is no larger than the column header
if(PointSize > m_pTable->PointSize)
{
if(m_pTable->HLines==TRUE && m_pTable->HeaderOnly==FALSE)
PointSize=m_pTable->PointSize;
}
// determine the bounds of the print rect
// row
Row=m_pTable->NoHeader==FALSE ? (int) (m_pTable->StartRow+(m_pTable->HeaderLines*(GetVerticalSpacing(FALSE)))+( (sz)*row)):
(int) (m_pTable->StartRow+( (sz)*row));
// col
SCol=(int) m_pTable->StartCol;
for(y=0;y < col;++y)
SCol+=(int) m_pTable->ColDesc[y].Width;
ECol=(int)(SCol+m_pTable->ColDesc[col].Width);
m_ps->rc.left=SCol+2;
m_ps->rc.right=ECol-2;
m_ps->rc.top=Row+2;
m_ps->rc.bottom=(Row+sz)-2;
m_ps->Text=Text;
m_ps->uFillFlags=m_pTable->ColDesc[col].FillFlag;
if(m_ps->uFillFlags > FILL_LTGRAY)
{
OldColor= p_Print->SetColor(COLOR_WHITE);
}
if(m_ps->uFillFlags > FILL_NONE)
{
OldMode=p_Print->m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
}
if(m_pTable->NumPrintLines==1)
m_ps->uTextFlags=TextFlags|TEXT_VCENTER|TEXT_SINGLELINE;
else
m_ps->uTextFlags=TextFlags;
m_ps->PointSize=PointSize;
p_Print->ThePrinter.PrintText(m_ps,2);
p_Print->m_nNextPos=m_ps->m_NextCharPos;
if(m_ps->uFillFlags > FILL_NONE)
{
OldMode=p_Print->m_PrtDesc.pDC->SetBkMode(OldMode);
}
if(m_ps->uFillFlags > FILL_LTGRAY)
{
OldColor= p_Print->SetColor(OldColor);
}
}
////////////////////////////////////////////////////////////////////////////
// Desc: places a value in a cell on the table defined as row,col
// used only with tables that are header only type. This routine does no
// checking for valid rows only for columns
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::InsertVirtualItem(LPCSTR Text,int row,int col,int PointSize,UINT TextFlags)
{
int y,SCol,ECol,Row,OldColor,OldMode;
// not Noheader NoHeader means we have a grid with no column descriptors while
// HeaderOnly means we have a header with no table body. With header only we
// will still have the column descriptors to use to set margins for each field
// so we can add fields till we run out of room on the page
int sz=GetVerticalSpacing();
if(m_pTable->HeaderOnly==FALSE)
return;
if(PointSize < 1)
PointSize=m_pTable->PointSize;
// determine the bounds of the print rect
// row .
// The start pos + (the # Header lines * the size of line)+(row# * size)
Row=(int) (m_pTable->StartRow+(m_pTable->HeaderLines*(GetVerticalSpacing(FALSE)))+( (sz)*row));
// col
SCol=(int) m_pTable->StartCol;
for(y=0;y < col;++y)
SCol+=(int) m_pTable->ColDesc[y].Width;
ECol=(int) (SCol+m_pTable->ColDesc[col].Width);
m_ps->rc.left=SCol+1;
m_ps->rc.right=ECol-1;
m_ps->rc.top=Row+1;
m_ps->rc.bottom=Row+(sz)-1;
m_ps->Text=Text;
m_ps->uTextFlags=TextFlags;
m_ps->PointSize=PointSize;
m_ps->uFillFlags=m_pTable->ColDesc[col].FillFlag;
if(m_ps->uFillFlags > FILL_LTGRAY)
{
OldColor= p_Print->SetColor(COLOR_WHITE);
}
if(m_ps->uFillFlags > FILL_NONE)
{
OldMode=p_Print->m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
}
p_Print->ThePrinter.PrintText(m_ps,2);
p_Print->m_nNextPos=m_ps->m_NextCharPos;
if(m_ps->uFillFlags > FILL_NONE)
{
OldMode=p_Print->m_PrtDesc.pDC->SetBkMode(OldMode);
}
if(m_ps->uFillFlags > FILL_LTGRAY)
{
OldColor= p_Print->SetColor(OldColor);
}
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draw horizontal lines for esch item on table
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::PrintHLines()
{
int y,SCol,ECol,Row,SCount=0;
// get out if needed
int sz=GetVerticalSpacing();
if(m_pTable->HLines==FALSE||m_pTable->HeaderOnly==TRUE)
return;
// calc starting column and ending column
SCol=(int) m_pTable->StartCol;
ECol=(int) m_pTable->EndCol;
// if we have a header skip over it else start at start pos
Row=m_pTable->NoHeader==FALSE ? (int) m_pTable->StartRow+ (GetVerticalSpacing(FALSE)*m_pTable->HeaderLines):
(int) m_pTable->StartRow+sz;
// draw a line for each row from one side to the other
for(y=0;y < m_pTable->NumRows;++y)
{
if(m_pTable->SetSkip)
{
++SCount;
if(m_pTable->SetSkip==SCount)
{
p_Print->Line(Row,SCol,Row,ECol,m_pTable->LineSize,PEN_SOLID);
SCount=0;
}
}
else
p_Print->Line(Row,SCol,Row,ECol,m_pTable->LineSize,PEN_SOLID);
Row+=sz;
}
}
////////////////////////////////////////////////////////////////////////////
// Desc: Draws vertical line seperators for column entries
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::PrintVLines()
{
int y,start;
int sz=GetVerticalSpacing();
// get out if needed
if(m_pTable->VLines==FALSE||m_pTable->HeaderOnly==TRUE)
return;
// col to start drawing at
start=(int) m_pTable->StartCol;
int BRow,ERow;
// calc the beginning and ending rows to draw lines the correct length
if(m_pTable->NoHeader==FALSE)
{
// skip header area and calc area under header for x items
BRow=(int) m_pTable->StartRow+(m_pTable->HeaderLines*(GetVerticalSpacing(FALSE)));
ERow=(int) m_pTable->StartRow+(m_pTable->HeaderLines*(GetVerticalSpacing(FALSE))+(sz * m_pTable->NumRows));
}
else
{
// no header so calc only for x items
BRow=(int) m_pTable->StartRow;
ERow=(int) m_pTable->StartRow+( sz*m_pTable->NumRows);
}
// loop through drawing lines on the right margin except the last column
// the last column will have a line drawn by the border
for(y=0;y < m_pTable->NumColumns-1;++y)
{
start+=(int) m_pTable->ColDesc[y].Width;
m_ps->rc.top=BRow;
m_ps->rc.bottom=ERow;
m_ps->rc.left=m_ps->rc.right=start;
p_Print->ThePrinter.DrawLine(m_ps,m_pTable->LineSize);
}
}
////////////////////////////////////////////////////////////////////////////
// Desc: draw the border around the data area of a table. This is not the header
// but the area that will contain the table data
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::PrintBorder()
{
int sz=GetVerticalSpacing();
// check flags and exit if needed
int ERow;
// calc the ending row of the table
if(m_pTable->NoHeader==TRUE)
ERow=(int) m_pTable->StartRow+( sz*m_pTable->NumRows);
else
ERow=(int) m_pTable->StartRow+( (m_pTable->HeaderLines*GetVerticalSpacing(FALSE))+(sz * m_pTable->NumRows));
m_pTable->EndRow=ERow;
if(m_pTable->Border==FALSE || m_pTable->HeaderOnly==TRUE)
return;
// draw a box around the table diminisions
p_Print->Box(
(int)m_pTable->StartRow,
(int)m_pTable->StartCol,
(int)ERow,
(int)m_pTable->EndCol,
m_pTable->LineSize,
FILL_NONE,
PEN_SOLID);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Print the column headers for the table. The member variable HeaderLines
// determines how many text rows are to be in the header (Default=1)
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::PrintHeader()
{
int start,y;
CString s;
int OldMode;
COLORREF OldColor;
// check flag and exit if needed
if(m_pTable->NoHeader==TRUE)
return;
p_Print->SetFontSize(m_pTable->PointSize);
int sz=GetVerticalSpacing(FALSE);
// draw the box the correct size forgetting about the columns right now
p_Print->Box((int)m_pTable->StartRow,
(int)m_pTable->StartCol,
(int)(m_pTable->StartRow+(m_pTable->HeaderLines*( sz))),
(int)m_pTable->EndCol,
m_pTable->LineSize,
FILL_NONE,
PEN_SOLID);
// adjust the width of the last column so it finishes out the header
// if the total of the widths is different from the total width of the
// table
start=(int) m_pTable->StartCol;
for(y=0;y < m_pTable->NumColumns;++y)
start+=(int) m_pTable->ColDesc[y].Width;
if(start < m_pTable->EndCol)
m_pTable->ColDesc[m_pTable->NumColumns-1].Width+=m_pTable->EndCol-start;
if(start > m_pTable->EndCol)
m_pTable->ColDesc[m_pTable->NumColumns-1].Width-=start-m_pTable->EndCol;
// now do the columns drawing a box around each one and centering the text
// and applying and shading if needed also set the font size here
start=(int) m_pTable->StartCol;
for(y=0;y < m_pTable->NumColumns;++y)
{
// the column text
s=m_pTable->ColDesc[y].Text;
// change this to change default behavior for untiltled columns
if(s.IsEmpty())
s.Format("Col %d",y+1);
// create a print rectangle with the diminsions of the table item
m_ps->rc.left=start;
m_ps->rc.right=(int) (m_ps->rc.left+m_pTable->ColDesc[y].Width);
m_ps->rc.top=(int) m_pTable->StartRow;
m_ps->rc.bottom=(int) m_pTable->StartRow+(sz*m_pTable->HeaderLines);
m_ps->Text=s;
m_ps->uTextFlags=TEXT_CENTER|TEXT_BOLD|TEXT_RECT|TEXT_VCENTER;
// if the shading is dark set the color to white so it will show up
if(m_ps->uFillFlags > FILL_NONE)
OldMode=p_Print->m_PrtDesc.pDC->SetBkMode(TRANSPARENT);
if(m_pTable->FillFlag > FILL_LTGRAY)
OldColor= p_Print->SetColor(COLOR_WHITE);
m_ps->uFillFlags=m_pTable->FillFlag;
// print the text
p_Print->ThePrinter.PrintText(m_ps,2);
p_Print->m_nNextPos=m_ps->m_NextCharPos;
// restore the old color scheme
if(m_pTable->FillFlag > FILL_LTGRAY)
p_Print->SetColor(OldColor);
if(m_ps->uFillFlags > FILL_NONE)
p_Print->m_PrtDesc.pDC->SetBkMode(OldMode);
// move to start of next column
start=m_ps->rc.right;
}
}
////////////////////////////////////////////////////////////////////////////
// Desc: places a fill in a cell on the table defined as row,col
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::FillColumn(int row,int col)
{
if(m_pTable->SetSkip)
return;
p_Print->SaveState();
int y,SCol,ECol,Row;
int sz=GetVerticalSpacing();
// determine the bounds of the print rect
// row .
// The start pos + (the # Header lines * the size of line)+(row# * size)
Row=(int) (m_pTable->StartRow+(m_pTable->HeaderLines*(GetVerticalSpacing(FALSE)))+( (sz)*row));
// col
SCol=(int) m_pTable->StartCol;
for(y=0;y < col;++y)
SCol+=(int) m_pTable->ColDesc[y].Width;
ECol=(int) (SCol+m_pTable->ColDesc[col].Width);
m_ps->rc.left=SCol;
m_ps->rc.right=ECol;
m_ps->rc.top=Row;
m_ps->rc.bottom=Row+(sz);
p_Print->m_PrtDesc.uFillFlags=m_pTable->ColDesc[col].FillFlag;
p_Print->ThePrinter.DrawRect(&p_Print->m_PrtDesc,1);
p_Print->RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Returns the # of vertical units to seperate rows in the table. The
// distance is dependant on the selected point size and map mode. The scaling factor
// of 1.5 was determined by trial and error to look best. If space is ata premium
// this can be reduced but should be no smaller than 1.25 or the results are UGLY
// params:
// Returns: the vertical size for a logical row of print to occupy
///////////////////////////////////////////////////////////////////////////
int CPrintTable::GetVerticalSpacing(BOOL Correct)
{
int offset= Correct==TRUE ? m_pTable->NumPrintLines:1;
if(Correct==TRUE)
{
if(p_Print->m_PrtDesc.pDC->GetMapMode()==MM_ANISOTROPIC)
return (int)(m_pTable->PointSize*1.50)* offset;
else
return (int) (((m_pTable->PointSize/72.0)* p_Print->m_PixPerInchY)*1.50)* offset;
}
else
{
if(p_Print->m_PrtDesc.pDC->GetMapMode()==MM_ANISOTROPIC)
{
if(m_pTable->HeaderLines==1)
return (int)(m_pTable->PointSize*1.5);
else
return (int)(m_pTable->PointSize*1.0);
}
else
{
if(m_pTable->HeaderLines==1)
return (int) (((m_pTable->PointSize/72.0)* p_Print->m_PixPerInchY)*1.5);
else
return (int) (((m_pTable->PointSize/72.0)* p_Print->m_PixPerInchY)*1.0);
}
}
}
////////////////////////////////////////////////////////////////////////////
// Desc:
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
CPrintTable::CPrintTable(TABLEHEADER* pTable,CPage* pPrint)
{
m_ps=&pPrint->m_PrtDesc;;
m_pTable=pTable;
p_Print=pPrint;
}
CPrintTable::~CPrintTable()
{
}
////////////////////////////////////////////////////////////////////////////
// Desc: Called to actually display the table on the display
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPrintTable::PrintTable()
{
p_Print->SaveState();
// if autosize calc the size of each column and set the desciptor
if(m_pTable->AutoSize==TRUE)
{
// (end-start) / number of col = average width of each column
// and roundoff errors will be taken care of later
int val=(int) (m_pTable->EndCol-m_pTable->StartCol)/m_pTable->NumColumns;
for(int y=0;y < m_pTable->NumColumns;++y)
m_pTable->ColDesc[y].Width=val;
}
PrintHeader();
PrintBorder();
PrintHLines();
PrintVLines();
for(int xx=0;xx < m_pTable->NumColumns;++xx)
for(int yy=0;yy < m_pTable->NumRows;++yy)
FillColumn(yy,xx);
p_Print->RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Helper class CPrintRegion here
////////////////////////////////////////////////////////////////////////////
CPrintRegion::CPrintRegion()
{
}
CPrintRegion::~CPrintRegion()
{
}
////////////////////////////////////////////////////////////////////////////
// Desc: Qualifies and creates a print region
// params: * to parent page and location in 4 points
// Returns: TRUE=Success
///////////////////////////////////////////////////////////////////////////
BOOL CPrintRegion::Create(CPage * pPage,int ptop,int pleft,int pright, int pbottom,UINT Fill)
{
UNREFERENCED_PARAMETER(Fill);
pOwner=pPage;
top=ptop;
right=pright;
left=pleft;
bottom=pbottom;
if(top < 0 ||
right > (signed)pOwner->m_PrtDesc.n_maxWidth ||
left < 0 ||
bottom > (signed)pOwner->m_PrtDesc.n_maxLength)
return FALSE;
if(bottom > (signed)pOwner->SetBottomMargin(0))
bottom=(signed)pOwner->SetBottomMargin(0);
if(right > (signed)pOwner->SetRightMargin(0))
right=(signed)pOwner->SetRightMargin(0);
FirstX=left+1;
FirstY=top+1;
pOwner->SaveState();
pOwner->m_PrtDesc.rc.top=top;
pOwner->m_PrtDesc.rc.bottom=bottom;
pOwner->m_PrtDesc.rc.right=right;
pOwner->m_PrtDesc.rc.left=left;
pOwner->m_PrtDesc.uFillFlags=FillColor;
pOwner->ThePrinter.FillRect(&pOwner->m_PrtDesc);
pOwner->RestoreState();
return TRUE;
}
///////////////////////////////////////////////////////////////////////////
// Desc: Draws border around the print region
// params:
// returns:
///////////////////////////////////////////////////////////////////////////
void CPrintRegion::DrawBorder()
{
pOwner->SaveState();
pOwner->m_PrtDesc.rc.top=top;
pOwner->m_PrtDesc.rc.bottom=bottom;
pOwner->m_PrtDesc.rc.right=right;
pOwner->m_PrtDesc.rc.left=left;
pOwner->ThePrinter.DrawRect(&pOwner->m_PrtDesc,1);
pOwner->RestoreState();
}
///////////////////////////////////////////////////////////////////////////
// Desc: Draws a title for the print region
// params: The title, the size fomnt to use, the flags
// returns:
///////////////////////////////////////////////////////////////////////////
void CPrintRegion::DrawTitle(LPCSTR Title,int PointSize,UINT TextFlags,UINT FillFlags)
{
pOwner->SaveState();
pOwner->m_PrtDesc.rc.top=top;
pOwner->m_PrtDesc.rc.right=right;
pOwner->m_PrtDesc.rc.left=left;
pOwner->m_PrtDesc.rc.bottom=bottom;
pOwner->m_PrtDesc.Text=Title;
pOwner->m_PrtDesc.PointSize=PointSize;
if( (TextFlags & TEXT_RECT)==TEXT_RECT)
{
pOwner->m_PrtDesc.rc.bottom=0;
pOwner->ThePrinter.GetPrintInfo(&pOwner->m_PrtDesc,1);
pOwner->m_PrtDesc.rc.bottom=pOwner->m_PrtDesc.LastPrintArea.bottom+10;
}
else
{
int temp=pOwner->ConvertToMappedUnits( (PointSize/72.0)*2,VERTRES);
pOwner->m_PrtDesc.rc.bottom=top+temp;
}
pOwner->m_PrtDesc.uTextFlags=TextFlags|TEXT_SINGLELINE|TEXT_VCENTER;
pOwner->m_PrtDesc.uFillFlags=FillFlags;
pOwner->ThePrinter.PrintText(&pOwner->m_PrtDesc,1);
FirstY=pOwner->m_PrtDesc.rc.bottom+1;
pOwner->RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// STATIC MEMBER FUNCTIONS
////////////////////////////////////////////////////////////////////////////
// Desc: static member function for changing print orientation
// params: CDC* to be used and the mode to switch to
// Returns: nada
///////////////////////////////////////////////////////////////////////////
void CPage::SetPrinterMode(CDC* pDC,int Mode)
{
if(Mode !=DMORIENT_LANDSCAPE && Mode != DMORIENT_PORTRAIT)
return;
PRINTDLG* pPrintDlg = new PRINTDLG;
AfxGetApp()->GetPrinterDeviceDefaults(pPrintDlg);
DEVMODE* lpDevMode = (DEVMODE*)::GlobalLock(pPrintDlg->hDevMode);
lpDevMode->dmOrientation = (short)Mode;
pDC->ResetDC(lpDevMode);
::GlobalUnlock(pPrintDlg->hDevMode);
delete pPrintDlg;
}
////////////////////////////////////////////////////////////////////////////
// Desc: static member function to find printer name
// params: CDC* to be used
// Returns: The device name
///////////////////////////////////////////////////////////////////////////
LPCSTR CPage::GetPrinterName(CDC* pDC)
{
static char buff[30];
UNREFERENCED_PARAMETER(pDC);
PRINTDLG* pPrintDlg = new PRINTDLG;
AfxGetApp()->GetPrinterDeviceDefaults(pPrintDlg);
DEVMODE* lpDevMode = (DEVMODE*)::GlobalLock(pPrintDlg->hDevMode);
strcpy(buff,(LPCSTR)lpDevMode->dmDeviceName);
::GlobalUnlock(pPrintDlg->hDevMode);
delete pPrintDlg;
return buff;
}
///////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Desc: Creates a moveable print region
// params: location of region in 4 points
// Returns: Pointer to the new region or a NULL
///////////////////////////////////////////////////////////////////////////
CPrintRegion* CPage::CreateSubRegion(CPrintRegion* pParent,double ptop,double pleft,double pbottom, double pright,UINT Fill)
{
ConvertArea(ptop,pleft,pbottom,pright);
return CreateSubRegion(pParent,(int) ptop,(int) pleft,(int) pbottom, (int) pright,Fill);
}
////////////////////////////////////////////////////////////////////////////
// Desc: Create a CprintRegion structure and maintain a list of created structures
// to free allocated memory when destructor runs
// params: bounding rectangle for the region
// Returns: pointer to the created structure
///////////////////////////////////////////////////////////////////////////
CPrintRegion* CPage::CreateSubRegion(CPrintRegion* pParent,int ptop,int pleft,int pbottom, int pright,UINT Fill)
{
CPrintRegion* pRegion= new CPrintRegion;
if(pRegion==NULL || pParent==NULL)
return NULL;
// adjust boundries to fit within parent region
ptop=ptop+pParent->FirstY;
pleft=pleft+pParent->FirstX;
pright=pright+pParent->FirstX;
if(pright > pParent->right)
pright=pParent->right;
pbottom=pbottom+pParent->top;
if(pbottom > pParent->bottom)
pbottom=pParent->bottom;
if(Fill==FILL_NONE)
Fill=pParent->FillColor;
pRegion->FillColor=Fill;
if( pRegion->Create(this,ptop,pleft,pright, pbottom,Fill)==FALSE)
{
delete pRegion;
return (CPrintRegion*)0;
}
m_RegionList.Add(pRegion);
return pRegion;
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints rotated text
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintRotatedText(int Top,int Left,int Bottom,int Right,UINT flags,int PointSize,LPCSTR Text,int angle)
{
SaveState();
m_PrtDesc.Text=Text;
if(PointSize > 0)
m_PrtDesc.PointSize=PointSize;
if(flags != IGNORE_PARAM)
m_PrtDesc.uTextFlags=flags;
m_PrtDesc.rc.left=(int)Left;
m_PrtDesc.rc.top=(int)Top;
m_PrtDesc.rc.right=(int)Right;
m_PrtDesc.rc.bottom=(int)Bottom;
ThePrinter.RotationAngle=angle;
ThePrinter.PrintText(&m_PrtDesc,m_Spacing);
m_nNextPos=m_PrtDesc.m_NextCharPos;
RestoreState();
}
////////////////////////////////////////////////////////////////////////////
// Desc: Prints rotated text
// params:
// Returns:
///////////////////////////////////////////////////////////////////////////
void CPage::PrintRotatedText(double Top,double Left,double Bottom,double Right,UINT flags,int PointSize,LPCSTR Text,int angle)
{
SaveState();
ConvertArea(Top,Left,Bottom,Right);
PrintRotatedText( (int) Top,(int) Left,(int) Bottom,(int) Right,flags,PointSize,Text,angle);
RestoreState();
}
| [
"yujnln@gmail.com"
] | yujnln@gmail.com |
6ac712d6f5dbb8b89398c6f2ff7322deab00b1c4 | 0d9aaae6ed3676698ae39cc386910bc9c8c6928f | /Public/Ava/Memory/Ref.hpp | 92a14f340e1d20dc8c699d6606c004f00d3d1710 | [
"MIT"
] | permissive | vasama/Ava | 4375a83836f767a019d025d2da35844434797cb9 | c1e6fb87a493dc46ce870220c632069f00875d2c | refs/heads/master | 2020-04-04T13:38:54.691085 | 2019-01-05T20:10:17 | 2019-01-05T20:10:17 | 155,969,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,367 | hpp | #pragma once
#include "Ava/Memory/DefaultDeleter.hpp"
#include "Ava/Memory/RefCount.hpp"
#include "Ava/Meta/EnableIf.hpp"
#include "Ava/Meta/Identity.hpp"
#include "Ava/Meta/Traits.hpp"
#include "Ava/Meta/TypeTraits.hpp"
#include "Ava/Misc.hpp"
#include "Ava/Private/Ebo.hpp"
#include "Ava/Private/Memory/SmartPtr.hpp"
#include "Ava/Utility/Move.hpp"
namespace Ava {
template<typename T, typename TDelete = DefaultDeleter, typename TTraits = RefCountTraits>
class Ref : Ava_EBO(Private::Memory_SmartPtr::Base<T>, TDelete)
{
typedef Private::Memory_SmartPtr::Base<T> Base;
public:
Ava_FORCEINLINE Ref()
: TDelete()
{
Base::m_ptr = nullptr;
}
Ava_FORCEINLINE Ref(decltype(nullptr))
: TDelete()
{
Base::m_ptr = nullptr;
}
Ava_FORCEINLINE Ref(T* ptr)
: TDelete()
{
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
}
explicit Ava_FORCEINLINE Ref(TDelete deleter)
: TDelete(Move(deleter))
{
Base::m_ptr = nullptr;
}
Ava_FORCEINLINE Ref(TDelete deleter, T* ptr)
: TDelete(Move(deleter))
{
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
}
#define Ava_SFINAE EnableIf<IsConvertibleTo<TIn*, T*>>
template<typename TIn, typename = Ava_SFINAE>
Ava_FORCEINLINE Ref(Ref<TIn, TDelete, TTraits>&& other)
: TDelete(static_cast<TDelete&&>(other))
{
Base::m_ptr = other.m_ptr;
other.m_ptr = nullptr;
}
template<typename TIn, typename = Ava_SFINAE>
Ava_FORCEINLINE Ref(const Ref<TIn, TDelete, TTraits>& other)
: TDelete(static_cast<const TDelete&>(other))
{
T* ptr = other.m_ptr;
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
}
#undef Ava_SFINAE
Ava_FORCEINLINE Ref(Ref&& other)
: TDelete(static_cast<TDelete&&>(other))
{
Base::m_ptr = other.m_ptr;
other.m_ptr = nullptr;
}
Ava_FORCEINLINE Ref(const Ref& other)
: TDelete(static_cast<const TDelete&>(other))
{
T* ptr = other.m_ptr;
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
}
Ref& operator=(decltype(nullptr))
{
if (T* old = Base::m_ptr)
if (TTraits::DecrementRefCount(old) == 0)
TDelete::operator()(old);
Base::m_ptr = nullptr;
return *this;
}
Ref& operator=(T* ptr)
{
if (T* old = Base::m_ptr)
if (TTraits::DecrementRefCount(old) == 0)
TDelete::operator()(old);
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
return *this;
}
#define Ava_SFINAE(...) EnableIf<IsConvertibleTo<TIn*, T*>, __VA_ARGS__>
template<typename TIn>
Ava_SFINAE(Ref&) operator=(Ref<TIn, TDelete, TTraits>&& other)
{
if (T* old = Base::m_ptr)
if (TTraits::DecrementRefCount(old) == 0)
TDelete::operator()(old);
static_cast<TDelete&>(*this) =
static_cast<TDelete&&>(other);
Base::m_ptr = other.m_ptr;
other.m_ptr = nullptr;
return *this;
}
template<typename TIn>
Ava_SFINAE(Ref&) operator=(const Ref<TIn, TDelete, TTraits>& other)
{
if (T* old = Base::m_ptr)
if (TTraits::DecrementRefCount(old) == 0)
TDelete::operator()(old);
static_cast<TDelete&>(*this) =
static_cast<const TDelete&>(other);
T* ptr = other.m_ptr;
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
return *this;
}
#undef Ava_SFINAE
Ref& operator=(Ref&& other)
{
if (T* old = Base::m_ptr)
if (TTraits::DecrementRefCount(old) == 0)
TDelete::operator()(old);
static_cast<TDelete&>(*this) =
static_cast<TDelete&&>(other);
Base::m_ptr = other.m_ptr;
other.m_ptr = nullptr;
return *this;
}
Ref& operator=(const Ref& other)
{
if (T* old = Base::m_ptr)
if (TTraits::DecrementRefCount(old) == 0)
TDelete::operator()(old);
static_cast<TDelete&>(*this) =
static_cast<const TDelete&>(other);
T* ptr = other.m_ptr;
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
return *this;
}
Ref& Assign(TDelete deleter, T* ptr)
{
if (T* old = Base::m_ptr)
if (TTraits::DecrementRefCount(old) == 0)
TDelete::operator()(old);
static_cast<TDelete&>(*this) = Move(deleter);
if (ptr) TTraits::IncrementRefCount(ptr);
Base::m_ptr = ptr;
return *this;
}
Ava_FORCEINLINE ~Ref()
{
T* ptr = Base::m_ptr;
if (ptr && TTraits::DecrementRefCount(ptr) == 0)
TDelete::operator()(ptr);
}
Ava_FORCEINLINE T* Get() const
{
return Base::m_ptr;
}
Ava_FORCEINLINE T* Release()
{
T* ptr = Base::m_ptr;
if (ptr)
{
Base::m_ptr = nullptr;
TTraits::DecrementRefCount(ptr);
}
return ptr;
}
Ava_FORCEINLINE void Reset()
{
if (T* ptr = Base::m_ptr)
{
if (TTraits::DecrementRefCount(ptr))
TDelete::operator()(ptr);
Base::m_ptr = nullptr;
}
}
Ava_FORCEINLINE const TDelete& GetDeleter() const
{
return static_cast<const TDelete&>(*this);
}
Ava_FORCEINLINE T& operator*() const
{
return *Base::m_ptr;
}
Ava_FORCEINLINE T* operator->() const
{
return Base::m_ptr;
}
explicit Ava_FORCEINLINE operator bool() const
{
return Base::m_ptr != nullptr;
}
Ava_FORCEINLINE bool operator!() const
{
return Base::m_ptr == nullptr;
}
template<typename, typename, typename>
friend class Ref;
};
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator==(const Ref<T, TDelete, TTraits>& lhs, const Ref<T, TDelete, TTraits>& rhs)
{
return lhs.Get() == rhs.Get();
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator!=(const Ref<T, TDelete, TTraits>& lhs, const Ref<T, TDelete, TTraits>& rhs)
{
return lhs.Get() != rhs.Get();
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator==(const Ref<T, TDelete, TTraits>& lhs, decltype(nullptr))
{
return lhs.Get() == nullptr;
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator==(decltype(nullptr), const Ref<T, TDelete, TTraits>& rhs)
{
return rhs.Get() == nullptr;
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator!=(const Ref<T, TDelete, TTraits>& lhs, decltype(nullptr))
{
return lhs.Get() != nullptr;
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator!=(decltype(nullptr), const Ref<T, TDelete, TTraits>& rhs)
{
return rhs.Get() != nullptr;
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator==(const Ref<T, TDelete, TTraits>& lhs, const Identity<T>* rhs)
{
return lhs.Get() == rhs;
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator==(const Identity<T>* lhs, const Ref<T, TDelete, TTraits>& rhs)
{
return lhs == rhs.Get();
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator!=(const Ref<T, TDelete, TTraits>& lhs, const Identity<T>* rhs)
{
return lhs.Get() != rhs;
}
template<typename T, typename TDelete, typename TTraits>
Ava_FORCEINLINE bool operator!=(const Identity<T>* lhs, const Ref<T, TDelete, TTraits>& rhs)
{
return lhs != rhs.Get();
}
template<typename T, typename TDelete, typename TTraits>
constexpr bool IsTriviallyRelocatable<Ref<T, TDelete, TTraits>> = IsTriviallyRelocatable<TDelete>;
template<typename T, typename TDelete, typename TTraits>
constexpr bool IsTriviallyEquatable<Ref<T, TDelete, TTraits>> = IsEmpty<TDelete>;
template<typename T, typename TDelete, typename TTraits>
constexpr bool IsZeroConstructible<Ref<T, TDelete, TTraits>> = IsZeroConstructible<TDelete>;
} // namespace Ava
| [
"git@vasama.org"
] | git@vasama.org |
ceae288c85931b7460f67b1e34a3410275cdf5d2 | 5bd1f72bacce2f551a10770d83f4d1481dbf08d1 | /CppNewStarter/test_stl/Main.cpp | a5d1b24e302926ff0abed86ac33ccdd3bb20d490 | [] | no_license | jeasonchan/CppExercise | cb9619329738308e1cd6bd9f3ff83f9e19315b72 | a621cc71bd6a8e3b4842f47e9c99513a42d471cc | refs/heads/master | 2023-04-13T00:47:51.691266 | 2021-03-05T15:45:57 | 2021-03-05T15:45:57 | 264,594,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,303 | cpp | //
// Created by jeasconchan on 2020/9/13.
//
#include <array>
#include <iostream>
#include <vector>
int main() {
{
std::array<int, 10> intArray{};
std::array<int, 10>::iterator iterator = intArray.begin();
//auto iterator = intArray.begin();
std::cout << iterator << std::endl;
}
{
//遍历vector容器
std::vector<int> intVector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "第一种遍历方法:通过index" << std::endl;
int size = intVector.size();
for (int i = 0; i < size; ++i) {
//像普通数组一样,通过重载的元算符[]进行访问
std::cout << intVector[i] << " ";
}
std::cout << std::endl;
std::cout << "第二种遍历方法:通过迭代器和迭代器不等于的比较" << std::endl;
std::vector<int>::iterator normalIterator;
//其实,不应该在上面定义,因为下面的=会发生新值覆盖旧值的赋值过程
//不过iterator本质上就是指针,这种性能损耗忽略不计,而且是不可避免的
//此处使用!=来进行迭代器比较
//和java一样,end()是指向最后元素的下一个位置,一个为止类型的地址
for (normalIterator = intVector.begin(); normalIterator != intVector.end(); ++normalIterator) {
std::cout << *normalIterator << " ";
}
std::cout << std::endl;
std::cout << "第三种遍历方法:通过迭代器和迭代器小于号的比较" << std::endl;
for (normalIterator = intVector.begin(); normalIterator < intVector.end(); ++normalIterator) {
std::cout << *normalIterator << " ";
}
std::cout << std::endl;
std::cout << "第四种遍历方法:通过while循环间隔输出" << std::endl;
normalIterator = intVector.begin();
while (normalIterator < intVector.end()) {
std::cout << *normalIterator << " ";
normalIterator += 5;
//跃界后,指向了不属于vector的地址,虽然可以读出int的值,但是其实是无意义的值
std::cout << "地址是:" << &(*normalIterator) << " 值是:" << *normalIterator << std::endl;
}
}
return 0;
} | [
"439994526@qq.com"
] | 439994526@qq.com |
60a5a84b87c89949fb1a631c0f3bd2f9bb9f2855 | 95d08297d9adf55e3010e5f5a92cc6902b0581a3 | /Exercises/memory-leak.cpp | c0d801117d6809ca33a0f268c5cb61267026b090 | [] | no_license | shaquillehinds/CPP-Playground | 9be9b108320ce826d45216b2ce2f12b9c8f3c7ab | 9efac61ddc08e0324b371f373aa46be13175f196 | refs/heads/master | 2023-03-16T18:55:39.200269 | 2021-03-05T12:42:46 | 2021-03-05T12:42:46 | 344,805,416 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 868 | cpp | #include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
class CAT{
public:
CAT(int age) {itsAge= age;}
~CAT(){}
int GetAge()const {return itsAge;}
private:
int itsAge;
};
/*********************BAD CODE**********************/ //the following create a memory leak
// CAT & MakeCat(int age);
// int main(){
// int age = 7;
// CAT Boots = MakeCat(age);
// cout << "Boots is " << Boots.GetAge() << " years old."<<endl;
// return 0;
// }
// CAT & MakeCat(int age){
// CAT * pCat = new CAT(age);
// return *pCat;
// }
CAT * MakeCat(int age);
int main(){
int age = 7;
CAT * Boots = MakeCat(age);
cout << "Boots is " << Boots->GetAge() << " years old."<<endl;
delete Boots;
Boots = 0;
return 0;
}
CAT * MakeCat(int age){
CAT * pCat = new CAT(age);
return pCat;
} | [
"shaqdulove@hotmail.com"
] | shaqdulove@hotmail.com |
319c6a80f49373862ab94fb788929f87aa5d14a6 | 8eb3ed5f98717ac2edcbbb415a76f367cd6ab542 | /src/FTPSettings.h | 0f241376f1318bfb216172a099282f533653a067 | [] | no_license | mkerost/NppFTP | ec437054aab4b26d0ad972284f74f723cb0ed7a7 | af45f73056f50c43181ca6bd8808e61751c753e6 | refs/heads/master | 2021-01-16T21:39:21.576361 | 2015-03-16T17:42:52 | 2015-03-16T17:42:52 | 32,197,811 | 1 | 0 | null | 2015-03-14T05:44:08 | 2015-03-14T05:44:07 | C++ | UTF-8 | C++ | false | false | 2,043 | h | /*
NppFTP: FTP/SFTP functionality for Notepad++
Copyright (C) 2010 Harry (harrybharry@users.sourceforge.net)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(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/>.
*/
#ifndef FTPSETTINGS_H
#define FTPSETTINGS_H
#include "FTPCache.h"
//Container for various (global) settings
class FTPSettings {
public:
FTPSettings();
virtual ~FTPSettings();
const TCHAR* GetGlobalCachePath() const;
int SetGlobalCachePath(const TCHAR * path);
FTPCache* GetGlobalCache();
const char* GetEncryptionKey() const; //array of size 8
int SetEncryptionKey(const char * key); //key must array of size 8
bool GetDebugMode() const;
int SetDebugMode(bool debugMode);
bool GetClearCache() const;
int SetClearCache(bool clearCache);
bool GetClearCachePermanent() const;
int SetClearCachePermanent(bool clearCachePermanent);
bool GetOutputShown() const;
int SetOutputShown(bool showOutput);
double GetSplitRatio() const;
int SetSplitRatio(double splitRatio);
int LoadSettings(const TiXmlElement * settingsElem);
int SaveSettings(TiXmlElement * settingsElem);
private:
TCHAR* m_globalCachePath;
FTPCache m_globalCache;
bool m_clearCache;
bool m_clearCachePermanent;
bool m_showOutput;
double m_splitRatio;
bool m_debugMode;
};
#endif //FTPSETTINGS_H
| [
"mke.rost@gmail.com"
] | mke.rost@gmail.com |
3712664041837bdf68ddc0d96e1726e94de883b5 | f75d94da1288290869f102d33ddf2e18acb2c257 | /src/qt/networkstyle.h | 9c9cd77656afeefd4e1a68acc26a1568543014c1 | [
"MIT"
] | permissive | hashtagcoin/hashtagcoinCORE | af9ec7c1dbaeeb2c87eb169a07788f49f1d2cd9b | 1c7c0dd4aed70364909d4666f150c45e741e6f76 | refs/heads/master | 2021-09-02T06:24:39.986660 | 2017-12-31T01:30:58 | 2017-12-31T01:30:58 | 115,835,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | h | // Copyright (c) 2014 The Hashtagcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef HASHTAGCOIN_QT_NETWORKSTYLE_H
#define HASHTAGCOIN_QT_NETWORKSTYLE_H
#include <QIcon>
#include <QPixmap>
#include <QString>
/* Coin network-specific GUI style information */
class NetworkStyle
{
public:
/** Get style associated with provided BIP70 network id, or 0 if not known */
static const NetworkStyle *instantiate(const QString &networkId);
const QString &getAppName() const { return appName; }
const QIcon &getAppIcon() const { return appIcon; }
const QIcon &getTrayAndWindowIcon() const { return trayAndWindowIcon; }
const QString &getTitleAddText() const { return titleAddText; }
private:
NetworkStyle(const QString &appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *titleAddText);
QString appName;
QIcon appIcon;
QIcon trayAndWindowIcon;
QString titleAddText;
};
#endif // HASHTAGCOIN_QT_NETWORKSTYLE_H
| [
"prime_1@hashtagcoin.org"
] | prime_1@hashtagcoin.org |
b10e939755150998a6dbd449dda2d49d15a85ea7 | be80237960120a669592dac037301e39ee5ef987 | /snakeGame/src/snakeGame.cpp | 0f4af22aa0858897cca65d6f9fd15b0cb4e73cea | [] | no_license | Jongranberg/SnakeGame | dba5244809e708f8adea415dfdff74cf99730b82 | 8809230838df344c6d3d81cce3257808b7e1ecc6 | refs/heads/master | 2021-01-23T00:44:32.078111 | 2017-08-21T14:45:50 | 2017-08-21T14:45:50 | 92,837,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 526 | cpp | //============================================================================
// Name : snakeGame.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <SDL.h>
#undef main
using namespace std;
int main( int argc, char *argv[] ) {
SDL_Init(SDL_INIT_VIDEO);
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
return 0;
}
| [
"jongranberg@hotmail.se"
] | jongranberg@hotmail.se |
08b75d8e39af5fbbf5c7ad3b213c0646b0a69ac1 | d49dba348e70071c00a59a8860db0ea3f8df558d | /worker.h | 4e88d26a163dc5f878b9f430c752b87d42279e3c | [
"BSD-2-Clause"
] | permissive | larrylart/x10ping | a80d59f3b94a2b02a0bc57eff1ad9e41aa4c2f73 | c0f1215cf2e7c7ca05ee391c1f135cf8044af558 | refs/heads/master | 2021-01-17T17:44:05.850738 | 2019-05-05T19:57:03 | 2019-05-05T19:57:03 | 60,771,992 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,695 | h | ////////////////////////////////////////////////////////////////////
// Package: worker definition
// File: worker.h
// Purpose: manage checking, switching tasks
//
// Created by: Larry Lart on 22-Apr-2006
// Updated by:
//
// Copyright: (c) 2006 Larry Lart
// Licence: Digital Entity
////////////////////////////////////////////////////////////////////
#ifndef _WORKER_H
#define _WORKER_H
// local defines
#define MAX_DEV_NUMBER 20
// default values
#define NETWORK_DEFAULT_LOOP_CHECK_DELAY 20000
#define NETWORK_DEFAULT_NO_RETRY 5
// cofig file for net devices
#define NET_DEVICE_CONFIG_FILE_NAME "./x10ping_dev.cfg"
#include "wx/wxprec.h"
#include "wx/thread.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif //precompiled headers
class CX10PingApp;
class CGUIFrame;
class CLogger;
class CConfig;
class CPing;
class CX10;
class CNetDevice;
//////////////////////////////////////////////////
// class: CX10PingWorker
/////////////////////////////////////////////////
class CX10PingWorker : public wxThread
{
// methods
public:
CX10PingWorker( CGUIFrame *pFrame, CLogger *pLogger, CConfig *pConfig, char* strPath );
~CX10PingWorker();
// thread entry point
virtual void *Entry();
virtual void OnExit();
// save load methods
int SaveNetDevices( const char* strNetDevConfigFile );
int LoadNetDevices( const char* strNetDevConfigFile );
// device list handling methods
void DisplayGuiDeviceList( );
void ClearGuiDeviceList( );
int AddDevice( const char *strName,unsigned int nHouseId,
unsigned int nUnitId,
int nCheckMethod, int nFailuresToAction,
int nActionLogic, int nActionFunction,
int nActionNotify,
int nRebootTime, int bCheckTimeFrame,
int nCheckStartTimeH, int nCheckStartTimeM,
int nCheckEndTimeH, int nCheckEndTimeM );
int DeleteDevice( unsigned int nListId );
int EditDevice( unsigned int nListId, const char *strDevName,
unsigned int nHouseId, unsigned int nUnitId,
int nCheckMethod, int nFailuresToAction,
int nActionLogic, int nActionFunction,
int nActionNotify,
int nRebootTime, int bCheckTimeFrame,
int nCheckStartTimeH, int nCheckStartTimeM,
int nCheckEndTimeH, int nCheckEndTimeM );
int GetDeviceData( unsigned int nListId, char* strDevName,
int& nHousId, int& nDevId, int& nCheckMethod,
int& nFailuresToAction, int& nActionLogic,
int& nActionFunction, int& nActionNotify, int& nRebootTime,
int& bCheckTimeFrame, int& nCheckStartTimeH,
int& nCheckStartTimeM, int& nCheckEndTimeH,
int& nCheckEndTimeM );
int UpdateDeviceState( int nDeviceIndex, int nDeviceState );
int CheckDevice( unsigned int nDeviceId );
int ActionDevice( unsigned int nDeviceId );
int IsInTimeFrame( unsigned int nDeviceId );
int TurnDeviceOn( unsigned int nListId );
int TurnDeviceOff( unsigned int nListId );
void UpdateConfig( );
// action methods
void DoStart( );
void DoPause( );
void IsChanged( int nState );
int ActionNotify( unsigned int nDeviceId );
// data
public:
CLogger *m_pLogger;
CX10PingApp *m_pX10PingApp;
CGUIFrame *m_pFrame;
CConfig *m_pConfig;
CPing *m_pPing;
CX10 *m_pX10;
// device list vars
CNetDevice* m_vectNetDevice[MAX_DEV_NUMBER];
// char m_vectDeviceNetName[MAX_DEV_NUMBER][255];
// int m_vectDeviceHouseId[MAX_DEV_NUMBER];
// unsigned int m_vectDeviceUnitId[MAX_DEV_NUMBER];
// int m_vectDeviceUnitState[MAX_DEV_NUMBER];
// int m_vectDeviceCounter[MAX_DEV_NUMBER];
int m_nDevice;
int m_nLoopCheckDelay;
int m_nRetry;
int m_nX10DelayAfterOFF;
int m_nX10DelayAfterON;
int m_bIsMonitorStarted;
int m_bIsPaused;
int m_bPauseLoop;
int m_bChanged;
int m_bIsJustStarted;
int m_bEmailAuth;
int m_bEmailServer;
int m_bAudioNotification;
char m_strEmailServer[255];
char m_strEmailFrom[255];
char m_strEmailTo[255];
char m_strEmailAuthUser[255];
// char m_strEmailPasswd[255];
char m_strEmailAuthPasswd[255];
char m_strNotifyAudioFile[255];
unsigned char m_bLife;
int m_bIsProcessing;
int m_bIsExit;
// device properties
// int m_vectCheckMethod[MAX_DEV_NUMBER];
// int m_vectFailuresToAction[MAX_DEV_NUMBER];
// int m_vectActionLogic[MAX_DEV_NUMBER];
// int m_vectActionFunction[MAX_DEV_NUMBER];
// int m_vectRebootTime[MAX_DEV_NUMBER];
// int m_vectCheckTimeFrame[MAX_DEV_NUMBER];
// int m_vectCheckStartTimeH[MAX_DEV_NUMBER];
// int m_vectCheckStartTimeM[MAX_DEV_NUMBER];
// int m_vectCheckEndTimeH[MAX_DEV_NUMBER];
// int m_vectCheckEndTimeM[MAX_DEV_NUMBER];
// path
char m_strNetDevConfigFile[255];
// private data
private:
// process syncronizer/locker
wxMutex *m_pMutex;
};
#endif
| [
"i@larryo.org"
] | i@larryo.org |
639e240e8e3f011691b0ff6201dc80b6c006ef4e | 49ddf853b13e9231ddaa29e97fe1ab20c81e0622 | /source/scpp/lib/util/siphash.h | a8466b8082c4d6ce9271ebec561a56ab1fbf427d | [
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | linked0/agora | bb3cccffba440265af2133adc4194d35e30b8f5f | 3ad178194ea9694229227e672253815af2701639 | refs/heads/v0.x.x | 2022-06-02T04:20:49.988348 | 2022-04-19T12:09:14 | 2022-04-19T23:30:49 | 207,190,013 | 1 | 0 | MIT | 2021-11-04T07:32:15 | 2019-09-09T00:07:55 | D | UTF-8 | C++ | false | false | 2,406 | h | #pragma once
// Adapted from https://github.com/whitfin/siphash-cpp
// Copyright 2016 Isaac Whitfield
// Licensed under the MIT license
// http://opensource.org/licenses/MIT
#include <cstddef>
#include <cstdint>
class SipHash24
{
private:
// The next byte within m, from LSB to MSB, that update() will write to.
int m_idx;
uint64_t v0, v1, v2, v3, m;
unsigned char input_len;
static uint64_t
rotate_left(uint64_t x, int b)
{
return ((x << b) | (x >> (64 - b)));
}
static uint64_t
load_le_64(uint8_t const* p)
{
// NB: LLVM will boil this down to a single 64bit load on an
// LE target.
return (((uint64_t)((p)[0])) | ((uint64_t)((p)[1]) << 8) |
((uint64_t)((p)[2]) << 16) | ((uint64_t)((p)[3]) << 24) |
((uint64_t)((p)[4]) << 32) | ((uint64_t)((p)[5]) << 40) |
((uint64_t)((p)[6]) << 48) | ((uint64_t)((p)[7]) << 56));
}
void
compress()
{
v0 += v1;
v1 = rotate_left(v1, 13);
v1 ^= v0;
v0 = rotate_left(v0, 32);
v2 += v3;
v3 = rotate_left(v3, 16);
v3 ^= v2;
v0 += v3;
v3 = rotate_left(v3, 21);
v3 ^= v0;
v2 += v1;
v1 = rotate_left(v1, 17);
v1 ^= v2;
v2 = rotate_left(v2, 32);
}
void
digest_block()
{
v3 ^= m;
compress();
compress();
v0 ^= m;
m_idx = 0;
m = 0;
}
public:
SipHash24(uint8_t const key[16]);
~SipHash24();
void
update(uint8_t const* data, size_t len)
{
// If we're starting at the LSB of m (m_idx == 0)
// then we can do an early word-at-a-time loop
// until we get to the remainder.
uint8_t const* end = data + len;
if (m_idx == 0)
{
uint8_t const* end8 = data + (len & ~7);
for (; data != end8; data += 8)
{
input_len += 8;
m = load_le_64(data);
digest_block();
}
}
// Then at the remainder we go byte-at-a-time.
for (; data != end; ++data)
{
input_len++;
m |= (static_cast<uint64_t>(*data) << (m_idx++ * 8));
if (m_idx >= 8)
{
digest_block();
}
}
}
uint64_t digest();
};
| [
"geod24@gmail.com"
] | geod24@gmail.com |
ab6f5d3a2b1cd2fbb3e3c64c79d3526aa4563d24 | e07e3f41c9774c9684c4700a9772712bf6ac3533 | /app/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_g3027994544.h | 736843e33e22127577ac4071700b65a72729c263 | [] | no_license | gdesmarais-gsn/inprocess-mobile-skill-client | 0171a0d4aaed13dbbc9cca248aec646ec5020025 | 2499d8ab5149a306001995064852353c33208fc3 | refs/heads/master | 2020-12-03T09:22:52.530033 | 2017-06-27T22:08:38 | 2017-06-27T22:08:38 | 95,603,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,063 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Int32[]
struct Int32U5BU5D_t3030399641;
// System.Collections.Generic.Link[]
struct LinkU5BU5D_t62501539;
// System.Collections.Generic.KeyValuePair`2<System.String,System.Boolean>[]
struct KeyValuePair_2U5BU5D_t3286339639;
// UnityEngine.Transform[][]
struct TransformU5BU5DU5BU5D_t118925110;
// System.Collections.Generic.IEqualityComparer`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Boolean>>
struct IEqualityComparer_1_t2710331980;
// System.Runtime.Serialization.SerializationInfo
struct SerializationInfo_t228987430;
// System.Collections.Generic.Dictionary`2/Transform`1<System.Collections.Generic.KeyValuePair`2<System.String,System.Boolean>,UnityEngine.Transform[],System.Collections.DictionaryEntry>
struct Transform_1_t2034234467;
#include "mscorlib_System_Object2689449295.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2<System.Collections.Generic.KeyValuePair`2<System.String,System.Boolean>,UnityEngine.Transform[]>
struct Dictionary_2_t3027994544 : public Il2CppObject
{
public:
// System.Int32[] System.Collections.Generic.Dictionary`2::table
Int32U5BU5D_t3030399641* ___table_4;
// System.Collections.Generic.Link[] System.Collections.Generic.Dictionary`2::linkSlots
LinkU5BU5D_t62501539* ___linkSlots_5;
// TKey[] System.Collections.Generic.Dictionary`2::keySlots
KeyValuePair_2U5BU5D_t3286339639* ___keySlots_6;
// TValue[] System.Collections.Generic.Dictionary`2::valueSlots
TransformU5BU5DU5BU5D_t118925110* ___valueSlots_7;
// System.Int32 System.Collections.Generic.Dictionary`2::touchedSlots
int32_t ___touchedSlots_8;
// System.Int32 System.Collections.Generic.Dictionary`2::emptySlot
int32_t ___emptySlot_9;
// System.Int32 System.Collections.Generic.Dictionary`2::count
int32_t ___count_10;
// System.Int32 System.Collections.Generic.Dictionary`2::threshold
int32_t ___threshold_11;
// System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::hcp
Il2CppObject* ___hcp_12;
// System.Runtime.Serialization.SerializationInfo System.Collections.Generic.Dictionary`2::serialization_info
SerializationInfo_t228987430 * ___serialization_info_13;
// System.Int32 System.Collections.Generic.Dictionary`2::generation
int32_t ___generation_14;
public:
inline static int32_t get_offset_of_table_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___table_4)); }
inline Int32U5BU5D_t3030399641* get_table_4() const { return ___table_4; }
inline Int32U5BU5D_t3030399641** get_address_of_table_4() { return &___table_4; }
inline void set_table_4(Int32U5BU5D_t3030399641* value)
{
___table_4 = value;
Il2CppCodeGenWriteBarrier(&___table_4, value);
}
inline static int32_t get_offset_of_linkSlots_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___linkSlots_5)); }
inline LinkU5BU5D_t62501539* get_linkSlots_5() const { return ___linkSlots_5; }
inline LinkU5BU5D_t62501539** get_address_of_linkSlots_5() { return &___linkSlots_5; }
inline void set_linkSlots_5(LinkU5BU5D_t62501539* value)
{
___linkSlots_5 = value;
Il2CppCodeGenWriteBarrier(&___linkSlots_5, value);
}
inline static int32_t get_offset_of_keySlots_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___keySlots_6)); }
inline KeyValuePair_2U5BU5D_t3286339639* get_keySlots_6() const { return ___keySlots_6; }
inline KeyValuePair_2U5BU5D_t3286339639** get_address_of_keySlots_6() { return &___keySlots_6; }
inline void set_keySlots_6(KeyValuePair_2U5BU5D_t3286339639* value)
{
___keySlots_6 = value;
Il2CppCodeGenWriteBarrier(&___keySlots_6, value);
}
inline static int32_t get_offset_of_valueSlots_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___valueSlots_7)); }
inline TransformU5BU5DU5BU5D_t118925110* get_valueSlots_7() const { return ___valueSlots_7; }
inline TransformU5BU5DU5BU5D_t118925110** get_address_of_valueSlots_7() { return &___valueSlots_7; }
inline void set_valueSlots_7(TransformU5BU5DU5BU5D_t118925110* value)
{
___valueSlots_7 = value;
Il2CppCodeGenWriteBarrier(&___valueSlots_7, value);
}
inline static int32_t get_offset_of_touchedSlots_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___touchedSlots_8)); }
inline int32_t get_touchedSlots_8() const { return ___touchedSlots_8; }
inline int32_t* get_address_of_touchedSlots_8() { return &___touchedSlots_8; }
inline void set_touchedSlots_8(int32_t value)
{
___touchedSlots_8 = value;
}
inline static int32_t get_offset_of_emptySlot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___emptySlot_9)); }
inline int32_t get_emptySlot_9() const { return ___emptySlot_9; }
inline int32_t* get_address_of_emptySlot_9() { return &___emptySlot_9; }
inline void set_emptySlot_9(int32_t value)
{
___emptySlot_9 = value;
}
inline static int32_t get_offset_of_count_10() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___count_10)); }
inline int32_t get_count_10() const { return ___count_10; }
inline int32_t* get_address_of_count_10() { return &___count_10; }
inline void set_count_10(int32_t value)
{
___count_10 = value;
}
inline static int32_t get_offset_of_threshold_11() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___threshold_11)); }
inline int32_t get_threshold_11() const { return ___threshold_11; }
inline int32_t* get_address_of_threshold_11() { return &___threshold_11; }
inline void set_threshold_11(int32_t value)
{
___threshold_11 = value;
}
inline static int32_t get_offset_of_hcp_12() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___hcp_12)); }
inline Il2CppObject* get_hcp_12() const { return ___hcp_12; }
inline Il2CppObject** get_address_of_hcp_12() { return &___hcp_12; }
inline void set_hcp_12(Il2CppObject* value)
{
___hcp_12 = value;
Il2CppCodeGenWriteBarrier(&___hcp_12, value);
}
inline static int32_t get_offset_of_serialization_info_13() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___serialization_info_13)); }
inline SerializationInfo_t228987430 * get_serialization_info_13() const { return ___serialization_info_13; }
inline SerializationInfo_t228987430 ** get_address_of_serialization_info_13() { return &___serialization_info_13; }
inline void set_serialization_info_13(SerializationInfo_t228987430 * value)
{
___serialization_info_13 = value;
Il2CppCodeGenWriteBarrier(&___serialization_info_13, value);
}
inline static int32_t get_offset_of_generation_14() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544, ___generation_14)); }
inline int32_t get_generation_14() const { return ___generation_14; }
inline int32_t* get_address_of_generation_14() { return &___generation_14; }
inline void set_generation_14(int32_t value)
{
___generation_14 = value;
}
};
struct Dictionary_2_t3027994544_StaticFields
{
public:
// System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,System.Collections.DictionaryEntry> System.Collections.Generic.Dictionary`2::<>f__am$cacheB
Transform_1_t2034234467 * ___U3CU3Ef__amU24cacheB_15;
public:
inline static int32_t get_offset_of_U3CU3Ef__amU24cacheB_15() { return static_cast<int32_t>(offsetof(Dictionary_2_t3027994544_StaticFields, ___U3CU3Ef__amU24cacheB_15)); }
inline Transform_1_t2034234467 * get_U3CU3Ef__amU24cacheB_15() const { return ___U3CU3Ef__amU24cacheB_15; }
inline Transform_1_t2034234467 ** get_address_of_U3CU3Ef__amU24cacheB_15() { return &___U3CU3Ef__amU24cacheB_15; }
inline void set_U3CU3Ef__amU24cacheB_15(Transform_1_t2034234467 * value)
{
___U3CU3Ef__amU24cacheB_15 = value;
Il2CppCodeGenWriteBarrier(&___U3CU3Ef__amU24cacheB_15, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"gdesmarais@gsngames.com"
] | gdesmarais@gsngames.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.