text
stringlengths
8
6.88M
/*1074*/ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cassert> #include <vector> #include <string> #include <cmath> #include <algorithm> #include <list> #include <queue> #include <set> #include <cstdlib> #include <cmath> using namespace std; typedef vector<string> VString; typedef vector<unsigned> VUnsigned; class State { public: State() { time_cost = 0; score = UINT32_MAX; last_state = 0x0; } State(unsigned time_cost, unsigned score, unsigned last_state) :time_cost(time_cost), score(score), last_state(last_state){ } unsigned time_cost, score, last_state; }; int main() { int T; cin >> T; vector<State> dp; dp.reserve(0x1<<15 - 1); // 2^15 - 1 while (T--) { int N; cin >> N; VString S(N); VUnsigned C(N); VUnsigned D(N); dp.resize(1 << N); for (int i = 0; i < N; i++) { cin >> S[i] >> D[i] >> C[i]; } dp[0].score = 0; for (unsigned state = 0x1; state < (1 << N); state++) { // enum all the task that can be done to get to this state for (int id = 0; id < N; id++) { unsigned now_time; if (state & (0x1 << id)) // task id has been done, namely, state can transform from last state { unsigned last_state = state & ~(0x1 << id); now_time = dp[last_state].time_cost + C[id]; // all tasks over deadline should have score unsigned score_this_time = 0; for (unsigned task = 0; task < N; task++) { if (D[task] < now_time && (~last_state & (0x1 << task))) // task has not been done and over the deadline { unsigned tmp = now_time - D[task]; if (tmp > C[id]) tmp = C[id]; score_this_time += tmp; } } if (dp[state].score >= dp[last_state].score + score_this_time) // find a more fast path { dp[state].last_state = last_state; dp[state].score = score_this_time + dp[last_state].score; dp[state].time_cost = now_time; } } } } cout << dp.back().score << endl; unsigned state = (1 << N) - 1; vector<string> state_list; while (state) { unsigned i = 0; while ((0x1 << i++) != (state ^ dp[state].last_state)) ; state_list.push_back(S[i - 1]); state = dp[state].last_state; } for (vector<string>::reverse_iterator r_iter = state_list.rbegin(); r_iter != state_list.rend(); r_iter++) { cout << *r_iter << endl; } dp.clear(); } }
#include <LedControl.h> #define VrX A0 #define VrY A1 #define SW 2 #define BUZZER 7 /* pin CLK = 10; pin CS = 9; pin DIN = 8; */ LedControl lc = LedControl(10, 8, 9, 1); int YemX, YemY; int Sutun[64], Satir[64]; int posX = 0, posY = 0, a = 0; int xPozisyon = 0, yPozisyon = 0; int BaslangicX = 4, BaslangicY = 4; const short messageSpeed = 5; int bayrak = 1; int Hiz = 300; void setup() { lc.shutdown(0, false); lc.setIntensity(0, 8); lc.clearDisplay(0); pinMode(VrX, INPUT); pinMode(VrY, INPUT); pinMode(SW, INPUT_PULLUP); pinMode(BUZZER, OUTPUT); //attachInterrupt(digitalPinToInterrupt(SW), Restart, FALLING); showSnakeMessage(); } void loop() { Yilan(); } void Yilan() { if (bayrak == 0)//Bayrak değerimiz 0 olursa döngünün içine girip değişkenlerimizi sıfırladıgımız yer. { posX = 0; posY = 0; a = 0; xPozisyon = 0; yPozisyon = 0; BaslangicX = 4; BaslangicY = 4; Hiz = 300; for (int i = 0; i < 64; i++) { Satir[i] = NULL; Sutun[i] = NULL; } for (int j = 0; j < 8; j++) { for (int k = 0; k < 8; k++) { lc.setLed(0, j, k, 0); } } bayrak = 1; return Yilan();//Değişkenleri sıfırladıktan sonra tekrardan Hareket fonksiyonumuzu döndürüyoruz. } xPozisyon = analogRead(VrX);//Joystick hareketlerini aldığımız yer. yPozisyon = analogRead(VrY); if (xPozisyon < 20) { //aşağı posY = -1; posX = 0; } else if (xPozisyon > 850) { //yukarı posY = 1; posX = 0; } else if (yPozisyon < 20) { //sola posX = 1; posY = 0; } else if (yPozisyon > 850) { //sağa posX = -1; posY = 0; } BaslangicX = BaslangicX + posX; BaslangicY = BaslangicY + posY; if (BaslangicX > 7) { BaslangicX = 0; } else if (BaslangicX < 0) { BaslangicX = 7; } else if (BaslangicY > 7) { BaslangicY = 0; } else if (BaslangicY < 0) { BaslangicY = 7; } Sutun[0] = BaslangicX; Satir[0] = BaslangicY; for (int i = 1; i <= a; i++) { if (BaslangicX == Sutun[i] && BaslangicY == Satir[i]) { delay(1000); showGameOverMessage(); bayrak = 0; } } lc.setLed(0, BaslangicX, BaslangicY, 1); for (int i = 0; i <= a; i++) { lc.setLed(0, Sutun[i], Satir[i], 1); } if (BaslangicX == YemX && BaslangicY == YemY)//Yem koordinatlarıyla yılanın koordinatlarının kesişip kesişmediğini kontrol edildiği yer. { Hiz = Hiz - 5; digitalWrite(BUZZER, HIGH); delay(100); digitalWrite(BUZZER, LOW); Yem();//Yem yenilmişse yeni yem için X ve Y koordinatları belirlediğimizyer a++; } lc.setLed(0, YemX, YemY, 1);//Yeni yem için X ve Y koordinatlarını ekranda gösterdiğimiz yer. delay(Hiz); lc.setLed(0, BaslangicX, BaslangicY, 0); for (int i = 0; i <= a; i++) { lc.setLed(0, Sutun[i], Satir[i], 0); } for (int i = a; i > 0; i--) { Sutun[i] = Sutun[i - 1]; Satir[i] = Satir[i - 1]; } } void Yem() {//Rastgele yemler oluşturuyoruz //srand((NULL)); YemX = rand() % 8; YemY = rand() % 8; } const PROGMEM bool snejkMessage[8][56] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; void showSnakeMessage() {//ekrana yazdıran bu iki fonksiyonu hazır aldım. for (int d = 0; d < sizeof(snejkMessage[0]) - 7; d++) { for (int col = 7; col >= 0; col--) { delay(messageSpeed); for (int row = 7; row >= 0 ; row--) { // this reads the byte from the PROGMEM and displays it on the screen lc.setLed(0, col, row, pgm_read_byte(&(snejkMessage[row][col + d ]))); } } } } const PROGMEM bool gameOverMessage[8][90] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} }; void showGameOverMessage() {//ekrana yazdıran bu iki fonksiyonu hazır aldım. for (int d = 0; d < sizeof(gameOverMessage[0]) - 7; d++) { for (int col = 7; col >= 0; col--) { delay(messageSpeed); for (int row = 7; row >= 0 ; row--) { // this reads the byte from the PROGMEM and displays it on the screen lc.setLed(0, col, row, pgm_read_byte(&(gameOverMessage[row][col + d ]))); } } } }
//Armed Boats class Category_48 { class RHIB_DZE {type = "trade_any_boat";buy[] = {4000,"worth"};sell[] = {2000,"worth"};}; class RHIB_DZ {type = "trade_any_boat";buy[] = {-1,"worth"};sell[] = {2000,"worth"};}; class RHIB2Turret_DZE {type = "trade_any_boat";buy[] = {8000,"worth"};sell[] = {4000,"worth"};}; class RHIB2Turret_DZ {type = "trade_any_boat";buy[] = {-1,"worth"};sell[] = {4000,"worth"};}; }; //Unarmed Boats class Category_49 { class Smallboat_1_DZE {type = "trade_any_boat";buy[] = {2000,"worth"};sell[] = {1000,"worth"};}; class Smallboat_2_DZE {type = "trade_any_boat";buy[] = {2000,"worth"};sell[] = {1000,"worth"};}; class Fishing_Boat_DZE {type = "trade_any_boat";buy[] = {4000,"worth"};sell[] = {2000,"worth"};}; class PBX_DZE {type = "trade_any_boat";buy[] = {600,"worth"};sell[] = {300,"worth"};}; class Zodiac_DZE {type = "trade_any_boat";buy[] = {600,"worth"};sell[] = {300,"worth"};}; class JetSkiYanahui_Case_Red {type = "trade_any_boat";buy[] = {600,"worth"};sell[] = {300,"worth"};}; class JetSkiYanahui_Case_Yellow {type = "trade_any_boat";buy[] = {600,"worth"};sell[] = {300,"worth"};}; class JetSkiYanahui_Case_Green {type = "trade_any_boat";buy[] = {600,"worth"};sell[] = {300,"worth"};}; class JetSkiYanahui_Case_Blue {type = "trade_any_boat";buy[] = {600,"worth"};sell[] = {300,"worth"};}; };
#include "aeMath.h" namespace aeEngineSDK { /*************************************************************************************************/ /* Constructors */ /*************************************************************************************************/ aeMatrix4::aeMatrix4() { } aeMatrix4::aeMatrix4(const aeMatrix4& M) { *this = M; } aeMatrix4::aeMatrix4( const aeVector4& V0, const aeVector4& V1, const aeVector4& V2, const aeVector4& V3) { v4[0] = V0; v4[1] = V1; v4[2] = V2; v4[3] = V3; } aeMatrix4::aeMatrix4( float _00, float _01, float _02, float _03, float _10, float _11, float _12, float _13, float _20, float _21, float _22, float _23, float _30, float _31, float _32, float _33) { f00 = _00; f01 = _01; f02 = _02; f03 = _03; f10 = _10; f11 = _11; f12 = _12; f13 = _13; f20 = _20; f21 = _21; f22 = _22; f23 = _23; f30 = _30; f31 = _31; f32 = _32; f33 = _33; } aeMatrix4::~aeMatrix4() { } /*************************************************************************************************/ /* Vectors inside the matrix related functions. */ /*************************************************************************************************/ void aeMatrix4::SetCol(const aeVector4 & V, const uint8& nCol) { aeMatrix4 M = ~*this; M.v4[nCol] = V; *this = ~M; } void aeMatrix4::SetRow(const aeVector4 & V, const uint8& nRow) { v4[nRow] = V; } aeVector4 aeMatrix4::GetCol(const uint8& nCol) const { aeMatrix4 M = ~*this; return M.v4[nCol]; } aeVector4 aeMatrix4::GetRow(const uint8& nRow) const { return v4[nRow]; } /*************************************************************************************************/ /* Implementation of arithmetic operators */ /*************************************************************************************************/ aeMatrix4 aeMatrix4::operator+(const aeMatrix4 & M) const { aeMatrix4 T = ~M; return aeMatrix4(v4[0] + T.v4[0], v4[1] + T.v4[1], v4[2] + T.v4[2], v4[3] + T.v4[3]); } aeMatrix4 aeMatrix4::operator-(const aeMatrix4 & M) const { aeMatrix4 T = ~M; return aeMatrix4(v4[0] - T.v4[0], v4[1] - T.v4[1], v4[2] - T.v4[2], v4[3] - T.v4[3]); } aeMatrix4 aeMatrix4::operator*(const aeMatrix4 & M) const { aeMatrix4 T = ~M; return aeMatrix4(v4[0] * M.v4[0], v4[1] * M.v4[1], v4[2] * M.v4[2], v4[3] * M.v4[3]); } aeMatrix4 aeMatrix4::operator*(const float& S) const { return aeMatrix4(v4[0] * S, v4[1] * S, v4[2] * S, v4[3] * S); } aeMatrix4 aeMatrix4::operator/(const float& S) const { float Inv = 1.0f / S; return *this*Inv; } aeVector4 aeMatrix4::operator*(const aeVector4& V) const { aeMatrix4 M = ~*this; M.v4[0] *= V.x; M.v4[1] *= V.y; M.v4[2] *= V.z; M.v4[3] *= V.w; M = ~M; return aeVector4(+M.v4[0], +M.v4[1], +M.v4[2], +M.v4[3]); } /*************************************************************************************************/ /* Functions Implementation */ /*************************************************************************************************/ float aeMatrix4::Det() const { return f00*(f11*(f22*f33 - f23*f32) - f12*(f21*f33 - f23*f31) + f13*(f21*f32 - f22*f31)) - f01*(f10*(f22*f33 - f23*f32) - f12*(f20*f33 - f23*f30) + f13*(f20*f32 - f22*f30)) + f02*(f10*(f21*f33 - f23*f31) - f11*(f20*f33 - f23*f30) + f13*(f20*f31 - f21*f30)) - f03*(f10*(f21*f32 - f22*f31) - f11*(f20*f32 - f22*f30) + f12*(f20*f31 - f21*f30)); } aeMatrix4 aeMatrix4::Cofactor() const { aeMatrix4 B; B.f00 = (f11*(f22*f33 - f23*f32) - f12*(f21*f33 - f23*f31) + f13*(f21*f32 - f22*f31)); B.f01 = -(f10*(f22*f33 - f23*f32) - f12*(f20*f33 - f23*f30) + f13*(f20*f32 - f22*f30)); B.f02 = (f10*(f21*f33 - f23*f31) - f11*(f20*f33 - f23*f30) + f13*(f20*f31 - f21*f30)); B.f03 = -(f10*(f21*f32 - f22*f31) - f11*(f20*f32 - f22*f30) + f12*(f20*f31 - f21*f30)); B.f10 = -(f01*(f22*f33 - f23*f32) - f02*(f21*f33 - f23*f31) + f03*(f21*f32 - f22*f31)); B.f11 = (f00*(f22*f33 - f23*f32) - f02*(f20*f33 - f23*f30) + f03*(f20*f32 - f22*f30)); B.f12 = -(f00*(f21*f33 - f23*f31) - f01*(f20*f33 - f23*f30) + f03*(f20*f31 - f21*f30)); B.f13 = (f00*(f21*f32 - f22*f31) - f01*(f20*f32 - f22*f30) + f02*(f20*f31 - f21*f30)); B.f20 = (f01*(f12*f33 - f13*f32) - f02*(f11*f33 - f13*f31) + f03*(f11*f32 - f12*f31)); B.f21 = -(f00*(f12*f33 - f13*f32) - f02*(f10*f33 - f13*f30) + f03*(f10*f32 - f12*f30)); B.f22 = (f00*(f11*f33 - f13*f31) - f01*(f10*f33 - f13*f30) + f03*(f10*f31 - f11*f30)); B.f23 = -(f00*(f11*f32 - f12*f31) - f01*(f10*f32 - f12*f30) + f02*(f10*f31 - f11*f30)); B.f30 = -(f01*(f12*f23 - f13*f22) - f02*(f11*f23 - f13*f21) + f03*(f11*f22 - f12*f21)); B.f31 = (f00*(f12*f23 - f13*f22) - f02*(f10*f23 - f13*f20) + f03*(f10*f22 - f12*f20)); B.f32 = -(f00*(f11*f23 - f13*f21) - f01*(f10*f23 - f13*f20) + f03*(f10*f21 - f11*f20)); B.f33 = (f00*(f11*f22 - f12*f21) - f01*(f10*f22 - f12*f20) + f02*(f10*f21 - f11*f20)); return B; } aeMatrix4 aeMatrix4::Inverse() const { float DetA = (+*this); if (DetA != 0) { aeMatrix4 B = Adjunct(); B = B / DetA; return B; } return aeMatrix4{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; } aeVector4 aeMatrix4::Cramer(const aeVector4& V) const { float DetM = (+*this); if (DetM != 0) { aeMatrix4 D0 = { V.x, f01, f02, f03, V.y, f11, f12, f13, V.z, f21, f22, f23, V.w, f31, f32, f33 }; aeMatrix4 D1 = { f00, V.x, f02, f03, f10, V.y, f12, f13, f20, V.z, f22, f23, f30, V.w, f32, f33 }; aeMatrix4 D2 = { f00, f01, V.x, f03, f10, f11, V.y, f13, f20, f21, V.z, f23, f30, f31, V.w, f33 }; aeMatrix4 D3 = { f00, f01, f02, V.x, f10, f11, f12, V.y, f20, f21, f22, V.z, f30, f31, f32, V.w }; float d0 = (+D0); float d1 = (+D1); float d2 = (+D2); float d3 = (+D3); return aeVector4{ d0 / DetM, d1 / DetM, d2 / DetM, d3 / DetM }; } return aeVector4{ -1,-1,-1,-1 }; } inline aeMatrix4 aeMatrix4::TranslationMatrix(const aeVector3& V) { return aeMatrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, V.x, V.y, V.z, 1); } inline aeMatrix4 aeMatrix4::TranslationMatrix(const float& x, const float& y, const float& z) { return aeMatrix4( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1); } inline aeMatrix4 aeMatrix4::ScalingMatrix(const float& ScaleFactor) { return aeMatrix4( ScaleFactor, 0, 0, 0, 0, ScaleFactor, 0, 0, 0, 0, ScaleFactor, 0, 0, 0, 0, 1); } inline aeMatrix4 aeMatrix4::ScalingMatrix(const float& x, const float& y, const float& z) { return aeMatrix4( x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); } inline aeMatrix4 aeMatrix4::ScalingMatrix(const aeVector3& V) { return aeMatrix4( V.x, 0, 0, 0, 0, V.y, 0, 0, 0, 0, V.z, 0, 0, 0, 0, 1); } aeMatrix4 aeMatrix4::RotationX(const float& theta) { aeMatrix4 R(1); R.f00 = R.f22 = aeMath::Cos(theta); R.f12 = -aeMath::Sin(theta); R.f21 = -R.f12; return R; } aeMatrix4 aeMatrix4::RotationY(const float& theta) { aeMatrix4 R(1); R.f00 = R.f22 = aeMath::Cos(theta); R.f20 = -aeMath::Sin(theta); R.f02 = -R.f20; return R; } aeMatrix4 aeMatrix4::RotationZ(const float& theta) { aeMatrix4 R(1); R.f11 = R.f00 = aeMath::Cos(theta); R.f01 = -aeMath::Sin(theta); R.f10 = -R.f01; return R; } inline aeMatrix4 aeMatrix4::RotationMatrix(const aeVector3 & V) { return RotationMatrix(V.x, V.y, V.z); } aeMatrix4 aeMatrix4::LookAtLH(aeVector3 & EyePos, aeVector3 & Target, aeVector3 & Up) { aeVector3 xDir, yDir, zDir; zDir = Target - EyePos; zDir.Normalize(); xDir = Up.Cross(zDir); xDir.Normalize(); yDir = zDir.Cross(xDir); yDir.Normalize(); return aeMatrix4(xDir.x, yDir.x, zDir.x, 0, xDir.y, yDir.y, zDir.y, 0, xDir.z, yDir.z, zDir.z, 0, xDir.Dot(EyePos), -yDir.Dot(EyePos), -zDir.Dot(EyePos), 1); } aeMatrix4 aeMatrix4::PerspectiveFOVLH(float zNear, float zFar, float FOV, float AspectRatio) { float yScale = 1.0f / aeMath::Tan(FOV * 0.5f); float xScale = yScale / AspectRatio; return aeMatrix4( xScale, 0, 0, 0, 0, yScale, 0, 0, 0, 0, zFar*zNear / (zFar - zNear), 1, 0, 0, -zNear*zFar / (zFar - zNear), 0); } aeMatrix4 aeMatrix4::MatrixOrthoLH(float w, float h, float zNear, float zFar) { return aeMatrix4(2.0f / w, 0, 0, 0, 0, 2.0f / h, 0, 0, 0, 0, zFar*zNear / (zFar - zNear), 1, 0, 0, -zNear*zFar / (zFar - zNear), 0); } aeMatrix4 aeMatrix4::RotationMatrix(float roll, float pitch, float yaw) { aeMatrix4 out = { 0 }; out.f00 = (aeMath::Cos(roll) * aeMath::Cos(yaw)) + (aeMath::Sin(roll) * aeMath::Sin(pitch) * aeMath::Sin(yaw)); out.f01 = (aeMath::Sin(roll) * aeMath::Cos(pitch)); out.f02 = (aeMath::Cos(roll) * -aeMath::Sin(yaw)) + (aeMath::Sin(roll) * aeMath::Sin(pitch) * aeMath::Cos(yaw)); out.f10 = (-aeMath::Sin(roll) * aeMath::Cos(yaw)) + (aeMath::Cos(roll) * aeMath::Sin(pitch) * aeMath::Sin(yaw)); out.f11 = (aeMath::Cos(roll) * aeMath::Cos(pitch)); out.f12 = (aeMath::Sin(roll) * aeMath::Sin(yaw)) + (aeMath::Cos(roll) * aeMath::Sin(pitch) * aeMath::Cos(yaw)); out.f20 = (aeMath::Cos(pitch) * aeMath::Sin(yaw)); out.f21 = -aeMath::Sin(pitch); out.f22 = (aeMath::Cos(pitch) * aeMath::Cos(yaw)); out.f33 = 1; return out; } aeMatrix4 aeMatrix4::TransformationMatrix(const aeQuaternion & Rotation, const aeVector3 & Translation, const aeVector3 & Scale) { return TranslationMatrix(Translation) * Rotation.GetMatrix() * ScalingMatrix(Scale); } aeMatrix4 aeMatrix4::TransformationMatrix(const aeVector3 & Rotation, const aeVector3 & Translation, const aeVector3 & Scale) { return TranslationMatrix(Translation) * RotationMatrix(Rotation) * ScalingMatrix(Scale);; } inline aeMatrix4 aeMatrix4::Zero() { return aeMatrix4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);; } inline aeMatrix4 aeMatrix4::Identity() { return aeMatrix4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } }
// Project 5 int redPin = 4; int yellowPin = 3; int greenPin = 2; int buttonPin = 5; int state = 0; void setup() { pinMode(redPin, OUTPUT); pinMode(yellowPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(buttonPin, INPUT_PULLUP); } void loop() { if (digitalRead(buttonPin) == LOW) { if (state == 0) { setLights(HIGH, LOW, LOW); state = 1; } else if (state == 1) { setLights(HIGH, HIGH, LOW); state = 2; } else if (state == 2) { setLights(LOW, LOW, HIGH); state = 3; } else if (state == 3) { setLights(LOW, HIGH, LOW); state = 0; } delay(1000); } } void setLights(int red, int yellow, int green) { digitalWrite(redPin, red); digitalWrite(yellowPin, yellow); digitalWrite(greenPin, green); }
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "mpi.h" const int CIRCLE1 = 2; const int CIRCLE2 = 3; const int SIZE = 16; const int EXIT_SIZE = 4; struct ComplexMatrix { int real[16][16]; int imaginary[16][16]; int size; }; void printMatrix(ComplexMatrix cm) { for (int i = 0; i < cm.size; i++) { for (int j = 0; j < cm.size; j++) { printf("%d+%di ", cm.real[i][j], cm.imaginary[i][j]); } printf("\n"); } } ComplexMatrix Sum(ComplexMatrix cm1, ComplexMatrix cm2) { struct ComplexMatrix ans; ans.size = cm1.size; for (int i = 0; i < ans.size; i++) { for (int j = 0; j < ans.size; j++) { ans.real[i][j] = cm1.real[i][j] + cm2.real[i][j]; ans.imaginary[i][j] = cm1.imaginary[i][j] + cm2.imaginary[i][j]; } } return ans; }; ComplexMatrix Substract(ComplexMatrix cm1, ComplexMatrix cm2) { struct ComplexMatrix ans; ans.size = cm1.size; for (int i = 0; i < ans.size; i++) { for (int j = 0; j < ans.size; j++) { ans.real[i][j] = cm1.real[i][j] - cm2.real[i][j]; ans.imaginary[i][j] = cm1.imaginary[i][j] - cm2.imaginary[i][j]; } } return ans; }; ComplexMatrix Multiply(ComplexMatrix cm1, ComplexMatrix cm2) { struct ComplexMatrix ans; ans.size = cm1.size; for (int i = 0; i < ans.size; i++) { for (int j = 0; j < ans.size; j++) { ans.real[i][j] = 0; ans.imaginary[i][j] = 0; } } if (ans.size <= EXIT_SIZE) { for (int i = 0; i < ans.size; i++) { for (int j = 0; j < ans.size; j++) { for (int r = 0; r < ans.size; r++) { ans.real[i][j] += cm1.real[i][r] * cm2.real[r][j]; ans.real[i][j] += -1 * cm1.imaginary[i][r] * cm2.imaginary[r][j]; ans.imaginary[i][j] += cm1.real[i][r] * cm2.imaginary[r][j]; ans.imaginary[i][j] += cm1.imaginary[i][r] * cm2.real[r][j]; } } } return ans; } else { ComplexMatrix** a = new ComplexMatrix* [2]; ComplexMatrix** b = new ComplexMatrix * [2]; ComplexMatrix** c = new ComplexMatrix * [2]; for (int i = 0; i < 2; i++) { a[i] = new ComplexMatrix[2]; b[i] = new ComplexMatrix[2]; c[i] = new ComplexMatrix[2]; for (int j = 0; j < 2; j++) { a[i][j].size = cm1.size / 2; b[i][j].size = cm1.size / 2; c[i][j].size = cm1.size / 2; for (int k = 0; k < a[i][j].size; k++) { for (int l = 0; l < a[i][j].size; l++) { a[i][j].real[k][l] = cm1.real[i * cm1.size / 2 + k][j * cm1.size / 2 + l]; b[i][j].real[k][l] = cm2.real[i * cm2.size / 2 + k][j * cm2.size / 2 + l]; a[i][j].imaginary[k][l] = cm1.imaginary[i * cm1.size / 2 + k][j * cm1.size / 2 + l]; b[i][j].imaginary[k][l] = cm2.imaginary[i * cm2.size / 2 + k][j * cm2.size / 2 + l]; } } } } ComplexMatrix p1 = Multiply(Sum(a[0][0], a[1][1]), Sum(b[0][0], b[1][1])); ComplexMatrix p2 = Multiply(Sum(a[1][0], a[1][1]), b[0][0]); ComplexMatrix p3 = Multiply(a[0][0], Substract(b[0][1], b[1][1])); ComplexMatrix p4 = Multiply(a[1][1], Substract(b[1][0], b[0][0])); ComplexMatrix p5 = Multiply(Sum(a[0][0], a[0][1]), b[1][1]); ComplexMatrix p6 = Multiply(Substract(a[1][0], a[0][0]), Sum(b[0][0], b[0][1])); ComplexMatrix p7 = Multiply(Substract(a[0][1], a[1][1]), Sum(b[1][0], b[1][1])); c[0][0] = Substract(Sum(Sum(p1, p4), p7), p5); c[0][1] = Sum(p3, p5); c[1][0] = Sum(p2, p4); c[1][1] = Substract(Sum(Sum(p1, p3), p6), p2); for (int i = 0; i < c[0][0].size; i++) { for (int j = 0; j < c[0][0].size; j++) { ans.real[i][j] = c[0][0].real[i][j]; ans.imaginary[i][j] = c[0][0].imaginary[i][j]; ans.real[i + ans.size / 2][j] = c[1][0].real[i][j]; ans.imaginary[i + ans.size / 2][j] = c[1][0].imaginary[i][j]; ans.real[i][j + ans.size / 2] = c[0][1].real[i][j]; ans.imaginary[i][j + ans.size / 2] = c[0][1].imaginary[i][j]; ans.real[i + ans.size / 2][j + ans.size / 2] = c[1][1].real[i][j]; ans.imaginary[i + ans.size / 2][j + ans.size / 2] = c[1][1].imaginary[i][j]; } } return ans; } }; int main(int argc, char* argv[]) { MPI_Init(&argc, &argv); MPI_Datatype MPI_COMPLEX_MATRIX; MPI_Type_contiguous(513, MPI_INT, &MPI_COMPLEX_MATRIX); MPI_Type_commit(&MPI_COMPLEX_MATRIX); int ProcNum, ProcRank; MPI_Status Status; MPI_Comm_size(MPI_COMM_WORLD, &ProcNum); MPI_Comm_rank(MPI_COMM_WORLD, &ProcRank); MPI_Group WorldGr1; MPI_Group ZeroToOne; MPI_Comm ZtoComm; MPI_Comm_group(MPI_COMM_WORLD, &WorldGr1); int* ztoRank = new int[3]{ 0, 1, 2 }; MPI_Group_incl(WorldGr1, 3, ztoRank, &ZeroToOne); MPI_Comm_create(MPI_COMM_WORLD, ZeroToOne, &ZtoComm); ComplexMatrix complexMatrix; complexMatrix.size = SIZE; if (ProcRank == 0) { for (int i = 0; i < complexMatrix.size; i++) { for (int j = 0; j < complexMatrix.size; j++) { complexMatrix.real[i][j] = i % CIRCLE1 + j % CIRCLE2; complexMatrix.imaginary[i][j] = i % CIRCLE2 + j % CIRCLE1; } } MPI_Send(&complexMatrix, 1, MPI_COMPLEX_MATRIX, 1, 1, ZtoComm); } if (ProcRank == 1) { MPI_Recv(&complexMatrix, 1, MPI_COMPLEX_MATRIX, 0, 1, ZtoComm, &Status); printf("data:\n"); printMatrix(complexMatrix); complexMatrix = Multiply(complexMatrix, complexMatrix); MPI_Send(&complexMatrix, 1, MPI_COMPLEX_MATRIX, 2, 0, ZtoComm); } if(ProcRank == 2) { MPI_Recv(&complexMatrix, 1, MPI_COMPLEX_MATRIX, 1, 0, ZtoComm, &Status); printf("result:\n"); printMatrix(complexMatrix); } MPI_Finalize(); return 0; }
/* * NodeController.cpp * * Created on: Jan 27, 2016 * Author: emad6932 */ #include "NodeController.h" using namespace std; NodeController::NodeController() { // this->myNode.setValue(5); // this->stringArrayNode.setValue("words are fun"); notHipsterInts = new CTECArray<int>(5); numbers = new CtecList<int>(); } NodeController::~NodeController() { // TODO Auto-generated destructor stub } void NodeController :: testsLists() { numbers->addToFront(3); numbers->addToEnd(8); cout << "End should be 8 and is: " << numbers->getEnd() << endl; } void NodeController :: start() { tryTree(); testHashTable(); testsLists(); tryGraphs(); } void NodeController::checkSorts() { /* Create an array and list Fill each with random data sort and time rept with ordered data print results */ CTECArray<int> numbersInArray(5); CtecList<int> numbersInList; for(int spot = 0; spot < 5000; spot++) { int randomValue = rand(); numbersInArray.set(spot, randomValue); numbersInList.addToEnd(randomValue); } } void NodeController::doMergeSort() { mergeData = new int[500000]; for(int spot = 0; spot < 500000; spot++) { int myRandom = rand(); mergeData[spot] = myRandom; } for (int spot = 0; spot < 5000; spot++) { cout << mergeData[spot] << ", " ; } Timer mergeTimer; mergeTimer.startTimer(); mergesort(mergeData, 500000); mergeTimer.startTimer(); mergeTimer.displayTimerInformation(); for (int spot = 0; spot < 50; spot++) { cout << mergeData[spot] << ", " ; } delete [] mergeData; } void NodeController::mergesort(int data[], int size) { int sizeOne; int sizeTwo; if(size > 1) { sizeOne = size/2; sizeTwo = size - sizeOne; mergesort(data, sizeOne); mergesort((data + sizeOne), sizeTwo); merge(data, sizeOne, sizeTwo); } } void NodeController::merge(int data[], int sizeOne, int sizeTwo) { int * temp; //Link for a temporary array int copied = 0; int copied1 = 0; int copied2 = 0; int index; temp = new int[sizeOne + sizeTwo]; while((copied1 < sizeOne) &&(copied2 < sizeTwo)) { if(data[copied] < (data + sizeOne)[copied2]) { temp[copied++] = data[copied1++]; } else { temp[copied++] = (data + sizeOne)[copied2++]; } } while(copied1 < sizeOne) { temp[copied++] = data[copied1++]; } while(copied2 < sizeTwo) { temp[copied++] = (data + sizeOne)[copied2++]; } for(index = 0; index < sizeOne + sizeTwo; index++) { data[index] = temp[index]; } delete [] temp; } void NodeController::quickSort(int first, int size) { int pivotIndex; if(size > 1) { pivotIndex = partition(first, size); quickSort(first, pivotIndex-1); quickSort(pivotIndex+1, size); } } void NodeController :: tryTree() { CTECBinaryTree<int> testTree; testTree.insert(7); testTree.insert(10); testTree.insert(-5); } int NodeController::partition(int first, int last) { int pivot; int index, smallIndex; swap(first, (first + last)/2); pivot = mergeData[first]; smallIndex = first; for(index = first + 1; index <= last; index++) { if(mergeData[index] < pivot) { smallIndex++; swap(smallIndex, index); } } swap(first, smallIndex); return smallIndex; } void NodeController::swap(int first, int second) { int temp = mergeData[first]; mergeData[first] = mergeData[second]; mergeData[second] = temp; } void NodeController::doQuick() { mergeData = new int[100000000]; for(int spot = 0; spot < 100000000; spot++) { int myRandom = rand(); mergeData[spot] = myRandom; } Timer mergeTime; mergeTime.startTimer(); quickSort(0, 100000000); mergeTime.stopTimer(); mergeTime.displayTimerInformation(); delete [] mergeData; } void NodeController::tryGraphs() { } void NodeController::testHashTable() { HashTable<int> tempTable; HashNode<int> tempArray[10]; for(int spot = 0; spot < 10; spot++) { int randomValue = rand(); int randomKey = rand(); HashNode<int> temp = HashNode<int>(randomKey, randomValue); tempTable.add(temp); tempArray[spot] = temp; } bool test = tempTable.contains(tempArray[0]); string result; if(test) { result = "it's there"; } else { result = "it's not there"; } cout << result << endl; }
#include <iostream> using namespace std; struct CTPYKTYPA { int data; CTPYKTYPA* next; }; /*void joker(CTPYKTYPA* head, int v) { CTPYKTYPA *Current = head; auto *Item = new (CTPYKTYPA); Item->data = v; Item->next = nullptr; if (head->data % 2 == 0) { Item->next = head; head = Item; // это легко, поэтому я это не делал. } else { while (Current->next != nullptr) // смотрим на то , чтобы ссылка была не пустой, в противном случа выполняется оставшееся... Current = Current->next; Item->data = v; Item->next = nullptr; Current->next = Item; } }*/ /*void Finder(CTPYKTYPA* head, int data, int n) { CTPYKTYPA* toDelete; CTPYKTYPA* Current = head; while (Current != NULL) { toDelete = Current->next; if (Current->data == data) { Current->data = toDelete->data; Current->next = toDelete->next; delete toDelete; } Current = Current->next; } }*/ /*void poisk (int k, CTPYKTYPA* head){ CTPYKTYPA* current = head; while (current->next != k) if (current != NULL) { current = current->next; if (current->data == k); pishy_chto_hochu(head->next); } };*/ void pishy_chto_hochu(CTPYKTYPA * head) { if (head != nullptr) { cout << head->data << "\t"; pishy_chto_hochu(head->next); } else cout << "\n"; } /*int pishy_chto_hochu(CTPYKTYPA* head) { if (head != NULL) { if (head->data != 0) int s += head->data; pishy_chto_hochu(head->next); } return s; }*/ int main() { int n=0, s=0; setlocale(LC_ALL, "RUS"); CTPYKTYPA *head = nullptr; head = new CTPYKTYPA; head->data = rand()%1000-500; head->next = nullptr; CTPYKTYPA* k = head; cout << "Введите длинну списка : "; cin >> n; for (int i = 0; i < n-1; i++) { k->next = new CTPYKTYPA; k = k->next; k->data = rand()%1000-500; k->next = nullptr; /*if (head->data != 0) s += k->data;*/ } pishy_chto_hochu(head); cout << "\n" << "Введите желаемое число : "; cin >> s; //joker(head, s); CTPYKTYPA* Current = head; auto* Item = new CTPYKTYPA; Item->data = s; Item->next = nullptr; if (s % 2 == 0) { Item->next = head; head = Item; // это легко, поэтому я это не делал. } else { while (Current->next != nullptr) // смотрим на то , чтобы ссылка была не пустой, в противном случа выполняется оставшееся... Current = Current->next; Current->next = Item; } pishy_chto_hochu(head); /*cout << "\n"<<"Введите ненужное число : "; cin >> s; Finder(head,s,n); pishy_chto_hochu(head);*/ /*cout << "\n" << "\n" << "\n" << s <<" Сумма не нулевых элементов."<< "\n" << "\n" << "\n";*/ }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 111111 #define THRE 1111 int n, m, q; LL a[N]; vector<int> V[N]; int big[N], bn = 0, isbig[N]; int mc[N][N / THRE]; LL sum[N], add[N]; inline void getint(int& x) { char ch; while ( (ch = getchar()) < '-' ); if (ch == '-') { x = 0; while ( (ch = getchar()) >= '0' ) x = x * 10 + ch - 48; x = -x; } else { x = ch - 48; while ( (ch = getchar()) >= '0' ) x = x * 10 + ch - 48; } } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%d%d%d", &n, &m, &q); for (int i = 1; i <= n; ++i) { int x; getint(x); // scanf("%d", &x); a[i] = x; } int sk = 0; for (int i = 0; i < m; ++i) { int k; getint(k); // scanf("%d", &k); vector<int>& v = V[i]; v.resize(k); for (int j = 0; j < k; ++j) { getint(v[j]); // scanf("%d", &v[j]); sum[i] += a[v[j]]; } sort(v.begin(), v.end()); sk += k; if (k > THRE) { big[bn++] = i; isbig[i] = 1; } } scanf("\n"); //cerr << sk << endl; //cerr << clock() << endl; for (int j = 0; j < bn; ++j) { const vector<int>& vj = V[big[j]]; for (int i = 0; i < m; ++i) { const vector<int>& vi = V[i]; int& c = mc[i][j] = 0; vector<int>::const_iterator ii = vi.begin(), jj = vj.begin(); while (ii != vi.end() && jj != vj.end()) if (*ii == *jj) { ++c; ++ii; ++jj; } else if (*ii < *jj) { ++ii; } else { ++jj; } } } //cerr << clock() << endl; while (q--) { int k, x; char ch; scanf("%c %d", &ch, &k); --k; if (ch == '?') { if (isbig[k]) { printf("%I64d\n", sum[k]); } else { LL ans = 0; for (int i = 0; i < V[k].size(); ++i) { ans += a[ V[k][i] ]; } for (int i = 0; i < bn; ++i) { ans += add[big[i]] * mc[k][i]; } printf("%I64d\n", ans); } } else { scanf("%d", &x); if (isbig[k]) { add[k] += x; } else { for (int i = 0; i < V[k].size(); ++i) { a[ V[k][i] ] += x; } } for (int i = 0; i < bn; ++i) { sum[big[i]] += LL(x) * mc[k][i]; } } scanf("\n"); } cerr << clock() << endl; return 0; }
/* * Copyright 2019 LogMeIn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include <exception> #include <mutex> #include <utility> #include <function2/function2.hpp> namespace asyncly { namespace detail { enum class SubscriptionState { /// Active means there is a subscriber and values can be pushed Active, /// Unsubscribed means the subscription has been cancelled Unsubscribed, /// Completed means either pushError or complete has been called, /// which means no further value nor error nor completion callbacks /// must be called, according to the contract Completed, }; /// SharedSubscriptionContext is shared between threads of producer and consumer of values, that's /// why the mutex is necessary template <typename T> struct SharedSubscriptionContext { SharedSubscriptionContext( fu2::unique_function<void(T)> cvalueFunction, fu2::unique_function<void(std::exception_ptr e)> cerrorFunction, fu2::unique_function<void()> ccompletionFunction) : state{ SubscriptionState::Active } , valueFunction{ std::move(cvalueFunction) } , errorFunction{ std::move(cerrorFunction) } , completionFunction{ std::move(ccompletionFunction) } { } void onSubscriptionCancelled() { std::lock_guard<std::mutex> lock{ mutex }; state = SubscriptionState::Unsubscribed; } void onValue(T value) { std::lock_guard<std::mutex> lock{ mutex }; if (state != SubscriptionState::Active || valueFunction == nullptr) { return; } valueFunction(std::move(value)); } void onCompleted() { std::lock_guard<std::mutex> lock{ mutex }; if (state != SubscriptionState::Active || completionFunction == nullptr) { return; } state = SubscriptionState::Completed; completionFunction(); } void onError(std::exception_ptr e) { std::lock_guard<std::mutex> lock{ mutex }; if (state != SubscriptionState::Active || errorFunction == nullptr) { return; } state = SubscriptionState::Completed; errorFunction(e); } private: SubscriptionState state; fu2::unique_function<void(T)> valueFunction; fu2::unique_function<void(std::exception_ptr e)> errorFunction; fu2::unique_function<void()> completionFunction; std::mutex mutex; }; template <> struct SharedSubscriptionContext<void> { SharedSubscriptionContext( fu2::unique_function<void()> cvalueFunction, fu2::unique_function<void(std::exception_ptr e)> cerrorFunction, fu2::unique_function<void()> ccompletionFunction) : state{ SubscriptionState::Active } , valueFunction{ std::move(cvalueFunction) } , errorFunction{ std::move(cerrorFunction) } , completionFunction{ std::move(ccompletionFunction) } { } void onSubscriptionCancelled() { std::lock_guard<std::mutex> lock{ mutex }; state = SubscriptionState::Unsubscribed; } void onValue() { std::lock_guard<std::mutex> lock{ mutex }; if (state != SubscriptionState::Active || valueFunction == nullptr) { return; } valueFunction(); } void onCompleted() { std::lock_guard<std::mutex> lock{ mutex }; if (state != SubscriptionState::Active || completionFunction == nullptr) { return; } state = SubscriptionState::Completed; completionFunction(); } void onError(std::exception_ptr e) { std::lock_guard<std::mutex> lock{ mutex }; if (state != SubscriptionState::Active || errorFunction == nullptr) { return; } state = SubscriptionState::Completed; errorFunction(e); } private: SubscriptionState state; fu2::unique_function<void()> valueFunction; fu2::unique_function<void(std::exception_ptr e)> errorFunction; fu2::unique_function<void()> completionFunction; std::mutex mutex; }; } }
#include <QDir> #include <QFile> #include <QFileInfo> #include <QStandardPaths> #include "appcore.h" AppCore::AppCore(QObject *parent) : QObject(parent) { this->dataLocation = QStandardPaths::standardLocations(QStandardPaths::DataLocation)[0]; this->config = new AppConfig(); QDir dataDir(this->dataLocation); if (!dataDir.exists()) { dataDir.mkdir(this->dataLocation); } QMap<QString, QString> files; files["db.sqlite"] = this->dataLocation; this->copyFiles(files); this->initDataBase(); this->initActuals(); } void AppCore::copyFiles(QMap<QString, QString> files) { QString filename = ""; QString distFolder = ""; QMap<QString, QString>::const_iterator i = files.constBegin(); while (i != files.constEnd()) { filename = i.key(); distFolder = i.value(); QFileInfo dataDirInfo(distFolder); if (!dataDirInfo.isWritable()) { qDebug() << "Have not premissions to write to " + distFolder; return; } QString filePath = distFolder + "/" + filename; QFileInfo fileInfo(filePath); if (!fileInfo.exists()) { QFile::copy(":/" + filename, filePath); QFile::setPermissions(filePath, QFileDevice::ReadOwner | QFileDevice::WriteOwner); } ++i; } } void AppCore::initDataBase() { QSqlDatabase sdb = QSqlDatabase::addDatabase("QSQLITE"); sdb.setDatabaseName(this->dataLocation + "/db.sqlite"); if (!sdb.open()) { qDebug() << sdb.lastError().text(); } } void AppCore::initActuals() { qDebug() << "AppCore::initActuals -"; this->setState(State::START); User * user = User::getActiveUser(); if (user) { this->setUser(user); this->setInstance(Instance::getByUserId(user->getId())); } if (isLoggedIn()) { this->setState(State::DASHBOARD); } } AppCore::State AppCore::getState() { qDebug() << "AppCore::getState -" + this->appState; return this->appState; } Instance * AppCore::getInstance() { qDebug() << "AppCore::getInstance -"; return this->instance; } User * AppCore::getUser() { qDebug() << "AppCore::getUser -"; return this->user; } void AppCore::setState(State state) { qDebug() << "AppCore::setState " + state; if (this->appState != state) { this->appState = state; emit stateChanged(this->appState); qDebug() << "AppCore::stateChanged " + this->appState; } } void AppCore::setInstance(Instance * instance) { qDebug() << "AppCore::setInstance -" << instance->getId(); this->instance = instance; } void AppCore::setUser(User * user) { qDebug() << "AppCore::setUser -" << user->getId(); this->user = user; } Currency *AppCore::getCurrency() const { return currency; } void AppCore::setCurrency(Currency *currency) { this->currency = currency; } CustomizeCore *AppCore::getCustomizeCore() const { return customizeCore; } void AppCore::setCustomizeCore(CustomizeCore *value) { customizeCore = value; } bool AppCore::isLoggedIn() { qDebug() << "AppCore::isLoggedIn -"; return user != NULL; } void AppCore::configureInstance() { qDebug() << "AppCore::configureInstance -"; // Create user with temp name User * user = customizeCore->getUser(); user->save(); // Create instance Instance * instance = new Instance(); instance->save(); instance->addUser(user); // Set currency Currency *currency = customizeCore->getCurrency(); this->setCurrency(currency); // Create accounts Account::createFromList(instance, user, currency, customizeCore->getAccountList()); // Create expense categories from customize page ExpenseCategory::createFromList(instance, customizeCore->getCategoryList()); this->setInstance(instance); this->setUser(user); this->setState(State::DASHBOARD); } QList<QObject*> AppCore::getCategoryList() { qDebug() << "AppCore::getCategoryList -"; QList<ExpenseCategory*> categories = ExpenseCategory::getByInstanceId(this->getInstance()->getId()); QList<QObject*> categoryList; foreach (ExpenseCategory* ctg, categories) { categoryList.append(ctg); } return categoryList; } QList<QObject *> AppCore::getAccountList() { qDebug() << "AppCore::getAccountList -"; QList<Account*> accounts = Account::getByInstanceId(this->getInstance()->getId()); QList<QObject*> accountList; foreach (Account* acc, accounts) { accountList.append(acc); } return accountList; } QList<QObject *> AppCore::getCurrencyList() { qDebug() << "AppCore::getCurrencyList -"; QList<Currency *> currencies = Currency::getAll(); QList<QObject*> currencyList; foreach (Currency* cur, currencies) { currencyList.append(cur); } return currencyList; }
#include <iostream> #include "ShortBufferContainer.h" int main(void){ short data[1024]; for(int i=0; i<1024; i++){ data[i] = i; } ShortBufferContainer ct(2); ct.addBuffer(data, 122); std::cout << ct.getCurrentBufferIndex() << ", " << ct.getCurrentBuffer()->getIndex() << std::endl; ct.addBuffer(data, 200); std::cout << ct.getCurrentBufferIndex() << ", " << ct.getCurrentBuffer()->getIndex() << std::endl; ct.addBuffer(data, 300); std::cout << ct.getCurrentBufferIndex() << ", " << ct.getCurrentBuffer()->getIndex() << std::endl; ct.addBuffer(data, 1024); std::cout << ct.getCurrentBufferIndex() << ", " << ct.getCurrentBuffer()->getIndex() << std::endl; return 0; }
#pragma once #include "basecombatcharacter.h" class CBaseObject : public CBaseCombatCharacter { public: NETVAR(m_iHealth, int, "CBaseObject", "m_iHealth"); NETVAR(m_iMaxHealth, int, "CBaseObject", "m_iMaxHealth"); NETVAR(m_bHasSapper, bool, "CBaseObject", "m_bHasSapper"); NETVAR(m_iObjectType, int, "CBaseObject", "m_iObjectType"); NETVAR(m_bBuilding, bool, "CBaseObject", "m_bBuilding"); NETVAR(m_bPlacing, bool, "CBaseObject", "m_bPlacing"); NETVAR(m_bCarried, bool, "CBaseObject", "m_bCarried"); NETVAR(m_bCarryDeploy, bool, "CBaseObject", "m_bCarryDeploy"); NETVAR(m_bMiniBuilding, bool, "CBaseObject", "m_bMiniBuilding"); NETVAR(m_flPercentageConstructed, float, "CBaseObject", "m_flPercentageConstructed"); NETVAR(m_fObjectFlags, int, "CBaseObject", "m_fObjectFlags"); NETVAR(m_hBuiltOnEntity, int, "CBaseObject", "m_hBuiltOnEntity"); NETVAR(m_bDisabled, bool, "CBaseObject", "m_bDisabled"); NETVAR(m_hBuilder, int, "CBaseObject", "m_hBuilder"); NETVAR(m_vecBuildMaxs, Vec3, "CBaseObject", "m_vecBuildMaxs"); NETVAR(m_vecBuildMins, Vec3, "CBaseObject", "m_vecBuildMins"); NETVAR(m_iDesiredBuildRotations, int, "CBaseObject", "m_iDesiredBuildRotations"); NETVAR(m_bServerOverridePlacement, bool, "CBaseObject", "m_bServerOverridePlacement"); NETVAR(m_iUpgradeLevel, int, "CBaseObject", "m_iUpgradeLevel"); NETVAR(m_iUpgradeMetal, int, "CBaseObject", "m_iUpgradeMetal"); NETVAR(m_iUpgradeMetalRequired, int, "CBaseObject", "m_iUpgradeMetalRequired"); NETVAR(m_iHighestUpgradeLevel, int, "CBaseObject", "m_iHighestUpgradeLevel"); NETVAR(m_iObjectMode, int, "CBaseObject", "m_iObjectMode"); NETVAR(m_bDisposableBuilding, bool, "CBaseObject", "m_bDisposableBuilding"); NETVAR(m_bWasMapPlaced, bool, "CBaseObject", "m_bWasMapPlaced"); NETVAR(m_bPlasmaDisable, bool, "CBaseObject", "m_bPlasmaDisable"); }; class CObjectSentrygun : public CBaseObject { public: NETVAR(m_iAmmoShells, int, "CObjectSentrygun", "m_iAmmoShells"); NETVAR(m_iAmmoRockets, int, "CObjectSentrygun", "m_iAmmoRockets"); NETVAR(m_iState, int, "CObjectSentrygun", "m_iState"); NETVAR(m_bPlayerControlled, bool, "CObjectSentrygun", "m_bPlayerControlled"); NETVAR(m_nShieldLevel, int, "CObjectSentrygun", "m_nShieldLevel"); NETVAR(m_bShielded, bool, "CObjectSentrygun", "m_bShielded"); NETVAR(m_hEnemy, int, "CObjectSentrygun", "m_hEnemy"); NETVAR(m_hAutoAimTarget, int, "CObjectSentrygun", "m_hAutoAimTarget"); NETVAR(m_iKills, int, "CObjectSentrygun", "m_iKills"); NETVAR(m_iAssists, int, "CObjectSentrygun", "m_iAssists"); }; class CObjectDispenser : public CBaseObject { public: NETVAR(m_iState, int, "CObjectDispenser", "m_iState"); NETVAR(m_iAmmoMetal, int, "CObjectDispenser", "m_iAmmoMetal"); NETVAR(m_iMiniBombCounter, int, "CObjectDispenser", "m_iMiniBombCounter"); }; class CObjectTeleporter : public CBaseObject { public: NETVAR(m_iState, int, "CObjectTeleporter", "m_iState"); NETVAR(m_flRechargeTime, float, "CObjectTeleporter", "m_flRechargeTime"); NETVAR(m_flCurrentRechargeDuration, float, "CObjectTeleporter", "m_flCurrentRechargeDuration"); NETVAR(m_iTimesUsed, int, "CObjectTeleporter", "m_iTimesUsed"); NETVAR(m_flYawToExit, float, "CObjectTeleporter", "m_flYawToExit"); NETVAR(m_bMatchBuilding, bool, "CObjectTeleporter", "m_bMatchBuilding"); };
#include "CImg.h" #include <iostream> #include <cstdlib> #include <cmath> using namespace cimg_library; using namespace std; /* * CImgProcessor is the class for Exercise One */ class CImgProcessor{ public: // Input the image path, load the target image CImgProcessor(string path_){ img.load(path_.c_str()); } void display(){ img.display(); } // Change white area into red, black area into green void changeColor(){ cimg_forXY(img, x, y){ // White color's RGB is (255, 255, 255), Red's RGB is(255, 0, 0) if(img(x, y, 0) >= 200 && img(x, y, 1) >= 200 && img(x, y, 2) >= 200){ img(x, y, 0) = 255; img(x, y, 1) = 0; img(x, y, 2) = 0; } // Black color's RGB is (0, 0, 0), Green's RGB is(0, 255, 0) if(!img(x, y, 0) && !img(x, y, 1) && !img(x, y, 2)){ img(x, y, 1) = 255; } } } void drawBlueCircle(pair<int, int> center, int radius){ cimg_forXY(img, x, y){ if(getDistance(center, make_pair(x, y)) <= radius){ img(x, y, 0) = img(x, y, 1) = 0; img(x, y, 2) = 255; } } } void drawYellowCircle(pair<int, int> center, int radius){ cimg_forXY(img, x, y){ if(getDistance(center, make_pair(x, y)) <= radius){ img(x, y, 0) = img(x, y, 1) = 255; img(x, y, 2) = 0; } } } void drawBlueLine(pair<int, int> center, double angle, int length){ for(int i=1; i<=100; i++){ double x_ = center.first + i * cos(angle/180 * cimg::PI), y_ = center.second + i * sin(angle/180 * cimg::PI); // Tansform double into int, with round-up(四舍五入) int x = x_ + 0.5, y = y_ + 0.5; img(x, y, 0) = img(x, y, 1) = 0; img(x, y, 2) = 255; } } void storeImg(string path_){ img.save(path_.c_str()); } private: CImg<unsigned char> img; inline int getDistance(pair<int, int> x, pair<int, int> y){ return sqrt(pow(x.first - y.first, 2) + pow(x.second - y.second, 2)); } }; int main(){ CImgProcessor temp("1.bmp"); temp.changeColor(); temp.drawBlueCircle(make_pair(50, 50), 30); temp.drawYellowCircle(make_pair(50, 50), 3); temp.drawBlueLine(make_pair(0, 0), 35, 100); temp.storeImg("2.bmp"); temp.display(); }
#include "tipo.h" #include <sstream> Tipo::Tipo() { tipID = 0; nombre = ""; } Tipo::Tipo(sql::ResultSet* rs) { this->fillObject(rs); } Tipo::~Tipo() { } void Tipo::setNombre(string nombre) { this->nombre = nombre; } string Tipo::getNombre() { return this->nombre; } void Tipo::setTipID(int tipID) { this->tipID = tipID; } int Tipo::getTipID() { return this->tipID; } void Tipo::fillObject(sql::ResultSet* rs) { this->setTipID(rs->getInt("tip_id")); this->setNombre(rs->getString("tip_nombre")); } string Tipo::toString() { stringstream ss; ss << this->getTipID(); return ss.str() + "\t" + this->getNombre(); }
/* -*- coding: utf-8 -*- !@time: 2019/11/21 20:59 !@author: superMC @email: 18758266469@163.com !@fileName: 0000_main.cpp */ #include "findIf_func.cpp" int main(int argc, char *argv[]) { fun(argc, argv); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** \file * * \brief Declare internal structures for mmap * * This functionality is used e.g. by lea_malloc to simplify porting * to a platform where virtual memory is available and implemented. It * may also be used for other things. * * \author Morten Rolland, mortenro@opera.com */ #ifndef MEMORY_MMAP_H #define MEMORY_MMAP_H #ifdef ENABLE_OPERA_MMAP_SEGMENT #include "modules/pi/system/OpMemory.h" #include "modules/memory/src/memory_state.h" #include "modules/memory/src/memory_manager.h" /** * \brief Structure to identify a single memory page. * * This structure is allocated in an array, so that it covers all * memory pages of an \c OpMmapSegment. There are a numbe of * "administrative handles" in the array: * * Anchors for reserved memory blocks, and anchors for unused * memory blocks * * The anchors are the "head" for doubly linked lists of various * size classes for each of allocated and reserved memory blocks. * * Reserved memory blocks are those that does not (yet) hold any * memory, and is thus inexpensive from a memory consumption * perspective. * * Unused memory blocks holds physical memory, and can thus be * used, but they are currently not allocated. Threshold limiters * will keep the ammount of unused memory blocks below certain * limits. * * After the ancors, there is a sentinel handle, before the first * handle that has an associated memory page attached to it. * A second sentinel is placed after all the handles. There is * typically 56 anchors (2 * 28 size classes) and the two sentinels * (See \c OP_MMAP_SIZECLASSES_COUNT and \c OP_MMAP_ANCHOR_COUNT). * * Handles will be unused when the mmap'ed allocation is two or more * memory pages in size, but the benefit is very quick lookup and * manipulation of free-lists and consolidation. Another benefit is * that no meta-data is allocated alongside the allocation itself, * which makes it possible to allocate e.g. a full 16K block that can * be given back entirely (except the handle overhead). * * The overhead is 8 bytes per memory page, which is 0.2% overhead * with a memory page size of 4K. */ struct OpMemPageHandle { /** * \brief Size in number of page blocks * * This allocated or reserved block of memory consists of \c size * number of memory pages. This is a value between 1 and the * maximum of slightly less than 65535 (16-bit value, minus the * anchors and sentinels). */ UINT16 size; /** * \brief Flags identifying this handle * * The state of the page handle is encoded in this variable. * The state is one of: \c OP_MMAP_FLAG_ALLOCATED, * \c OP_MMAP_FLAG_UNUSED, \c OP_MMAP_FLAG_RESERVED and * \c OP_MMAP_FLAG_SENTINEL. */ UINT8 flag; /** * \brief Memory allocation class type (enum OpMemoryClass) * * The allocation type class is encoded into the allocation. * This type info is used for accounting purposes, and upon * deallocation, the corresponding allocation class type * is decremented with the size of the deallocation. */ UINT8 type; /** * \brief The index of the previous page handle * * The first page handle of all blocks of reserved or unused * memory are linked into doubly linked lists. The \c prev * variable holds the index of the page handle in the list * previous to this one (of the same size-class). */ UINT16 prev; /** * \brief The index of the next page handle * * The first page handle of all blocks of reserved or unused * memory are linked into doubly linked lists. The \c next * variable holds the index of the page handle in the list * that follows this one (of the same size-class). */ UINT16 next; }; /** * \name Page allocation types * * The following page allocation types are used to define the * layout and status of the memory pages in the OpMmapSegment. * * @{ */ /** * \brief Allocated and used memory * * The page(s) are allocated and handed out for use. The memory is * being used for holding data. */ #define OP_MMAP_FLAG_ALLOCATED 1 /** * \brief Unused memory * * The page(s) are obtained from the Operating System, and are * present (so they can hold data right away if needed), but is * currently not used for holding data. * * This typically happens when an allocation is released, but it * is not given back to the OS right away in case it will be needed * again soon. A threshold determines how much unused memory can * stay around before given back to the OS. */ #define OP_MMAP_FLAG_UNUSED 2 /** * \brief Reserved memory * * This is the initial state which signals that there is no memory * associated with the page handle. It is thus not possible to use * the memory for holding data. * * The Operating System will have to be asked to populate the memory * page before it can be used to hold data. */ #define OP_MMAP_FLAG_RESERVED 3 /** * \brief Sentinel handle for simplifying fencepost logic * * There is a sentinel page-handle before and after all * usable page-handles, to simplify merging of memory blocks * during memory release and consolidation operations. * * The sentinel will not join with any other page handle type, * and thus prevent joining at the upper and lower borders. */ #define OP_MMAP_FLAG_SENTINEL 4 /** @} */ /** * \brief The number of size-classes for mmap allocations * * When administrating the free-lists of the memory blocks used to * provide 'mmap' functionality, there are 29 size classes. These * classes are 0-16 (1 to 17 memory pages, which is 4-68K in 4K * steps when the pagesize is 4K), and 17-28 (18 to 65536 pages in * increasing powers of two, which is 68K+1 to 256M when the pagesize * is 4K). * * Larger size-classes are not needed, since 16-bit page-indexing will * never provide more than 65536 accessible memory pages, minus the * anchors. Slightly less than 256M is thus the maximum OpMmapSegment * size with 4K memory pages. */ #define OP_MMAP_SIZECLASSES_COUNT 29 /** * \brief The total ammount of page-handle anchors * * The anchors are only used for "anchoring" a doubly linked list, * and does not have any associated memory page. The anchors are * located in the \c page_handle array, from index 0 onwards. */ #define OP_MMAP_ANCHOR_COUNT (2*OP_MMAP_SIZECLASSES_COUNT) /** * \brief The UNUSED memory pages anchor index base * * The memory pages with unused status are located in the size-classes * from \c OP_MMAP_UNUSED_SIZECLASS and onwards in the page_handle * array <code>page_handle[OP_MMAP_UNUSED_SIZECLASS]</code> to * <code>page_handle[OP_MMAP_UNUSED_SIZECLASS + * OP_MMAP_SIZECLASSES_COUNT - 1]</code> */ #define OP_MMAP_UNUSED_SIZECLASS 0 /** * \brief The RESERVED memory pages anchor index base * * The memory pages with reserved status are located in the size-classes * from \c OP_MMAP_RESERVED_SIZECLASS and onwards in the page_handle * array <code>page_handle[OP_MMAP_RESERVED_SIZECLASS]</code> to * <code>page_handle[OP_MMAP_RESERVED_SIZECLASS + * OP_MMAP_SIZECLASSES_COUNT - 1]</code> */ #define OP_MMAP_RESERVED_SIZECLASS OP_MMAP_SIZECLASSES_COUNT #ifdef SELFTEST #define OP_MMAP_MAX_TESTABLE_BLOCKS 64 #endif /** * \brief Class to administrate the mappings of a virtual memory segment * * This class is responsible for keeping track of MMAP-style allocations * inside the virtual OpMemSegment provided during construction. * */ class OpMmapSegment { public: #ifdef MEMORY_USE_LOCKING /** * \brief Create an OpMmapSegment from an OpMemSegment * * The only way to create an \c OpMmapSegment is to have a virtual * \c OpMemory::OpMemSegment created by \c * OpMemory_CreateVirtualSegment() (which in turn calls the \c * OpMemory::CreateVirtualSegment() porting interface to get the * job done). * * \b Note: The memory segment \c mseg must not be used for * anything else. * * \b Note: This method does only have the \c memlock parameter * for builds where \c MEMORY_USE_LOCKING is defined, so any code * that calls this method should either not specify the memlock * parameter (and use locking if enabled through the default TRUE * value), or test on \c MEMORY_USE_LOCKING to provide \c FALSE * for the \c memlock parameter when memory locking is enabled. * * \b Note: The \c memlock parameter should \b only be specified * as FALSE when the memory-lock is already held, for instance * when the call-chain goes through lea_malloc, which grabs this * lock for itself. * * \param mseg A virtual memory segment * \param hdr The memory accounting class for headers/metadata * \param unused The memory accounting class for unused memory * \param memlock Call OpMemory::MallocLock()/Unlock() when TRUE * \return A OpMmapSegment or NULL */ static OpMmapSegment* Create(const OpMemory::OpMemSegment* mseg, OpMemoryClass hdr = MEMCLS_MMAP_HEADER, OpMemoryClass unused = MEMCLS_MMAP_UNUSED, BOOL memlock = TRUE); /** * \brief Allocate memory in an OpMmapSegment * * Allocate a number of memory pages in an \c OpMmapSegment. The * allocation will be placed on a memory page boundary. The size * will be rounded up to the nearest page size to accomodate the * allocation. * * \b Note: The \c memlock parameter must be treated like * described for \c OpMmapSegment::Create(). * * \param size The number of bytes to be allocated * \param type The memory type class for allocation accounting purposes * \param memlock Call OpMemory::MallocLock()/Unlock() when TRUE * \return Pointer to allocated memory or NULL */ void* mmap(size_t size, OpMemoryClass type, BOOL memlock = TRUE); /** * \brief Deallocate memory in an OpMmapSegment * * Deallocate a previous allocation. The \c ptr parameter must be * the non-NULL result of a previous call to * OpMmapSegment::mmap(). * * \b Note: The \c memlock parameter must be treated like * described for \c OpMmapSegment::Create(). * * \b Note: This API differs from the typical UNIX 'mmap' API in * that deallocations does not have to specify the size of the * region to be deallocated. This API is thus more of an * allocator, than a memory page administrator API. If * administrating individual memory pages is needed, the porting * interface in OpMemory can be used directly (Or preferably the thin * layer in \c modules/memory/src/memory_pilayer.h) * * \param ptr Pointer to allocation * \param memlock Call OpMemory::MallocLock()/Unlock() when TRUE */ void munmap(void* ptr, BOOL memlock = TRUE); /** * \brief Release all unused memory from an OpMmapSegment * * Unused memory is memory that is present physically, awaiting * possible reuse or release back to the Operating System * (Depending on thresholds and usage pattern). * * This method will release all unused memory regardless of * any thresholds. This method can be used when we want to * be nice and give back as much as possible, or when we expect * no large quantities of allocations to happen for a while. */ void ReleaseAllUnused(BOOL memlock = TRUE); #else static OpMmapSegment* Create(const OpMemory::OpMemSegment* mseg, OpMemoryClass hdr = MEMCLS_MMAP_HEADER, OpMemoryClass unused = MEMCLS_MMAP_UNUSED); void* mmap(size_t size, OpMemoryClass type); void munmap(void* ptr); void ReleaseAllUnused(void); #endif /** * \brief Brutally release all memory allocated in OpMmapSegment * * If, for some reason, an OpMmapSegment needs to be "cleaned" * of all its allocations (possibly for reuse), this method * will do just that. * * \b Note: Any lingering allocations would be forcibly deallocated, * causing memory access errors until the page (by chance) was * reallocated again, at which point a corruption is more likely. * * So, don't use this method unless you know what you are doing, * like when using OpMmapSegment for "Arena" type of allocations * (where bulk releasing is needed at the end). */ void ForceReleaseAll(void); /** * \brief Set the threshold for how much can be cached when deallocating * * Whenever a deallocation is performed, the deallocated memory is * kept around in case it is needed again soon. The ammount of memory * to be kept around is controlled through the unused threshold * setting, which can be changed through this method. * * Setting it to '0' will cause all released memory to be freed back * to the operating system immediately. * * \param pgs The maximum number of memory pages to keep around */ void SetUnusedThreshold(unsigned int pgs) { unused_pages_threshold = pgs; } /** * \brief Get the underlying memory segment handle * * Can be useful at times. */ const OpMemory::OpMemSegment* GetOpMemSegment(void) { return mseg; } /** * \brief Check if an allocation is from within this segment */ BOOL Contains(void* ptr) { return (char*)ptr >= address_first_usable && (char*)ptr < address_last_usable; } #if defined(DEBUG_ENABLE_OPASSERT) || defined(SELFTEST) size_t SizeofAlloc(void* ptr); #endif #ifdef SELFTEST void* Test_mmap(size_t size, OpMemoryClass type); BOOL Test_munmap(void* ptr); void* TestGetAddressFirstUsable(void) { return address_first_usable; } void* TestGetAddressLastUsable(void) { return address_last_usable; } int TestGetUnusedPagesCount(void) { return unused_pages; } int TestGetUnusedThreshold(void) { return unused_pages_threshold; } int TestGetAllocatedPagesCount(void) { return allocated_pages; } OpMemPageHandle* TestGetPageHandle(UINT16 idx) { return page_handle + idx; } static unsigned int TestComputeSizeClass(unsigned int pages); static unsigned int TestComputeUsablePages(unsigned int pages, size_t pagesize); int TestState(int flag, ...); static int Corruption(int id); int TestCollectBlockinfo(void); #endif private: OpMmapSegment(OpMemory::OpMemSegment* mseg); void Link(UINT16 anchor, UINT16 page); void Unlink(UINT16 page); void SetDetails(UINT16 page, UINT16 pages, UINT8 flags); BOOL AllocateHandles(UINT16 index); unsigned int CalculatePageOfHandle(UINT16 index); void* AllocateUnused(UINT16 idx, UINT16 pages, OpMemoryClass type); void* AllocateReserved(UINT16 idx, UINT16 pages, OpMemoryClass type); void Merge(UINT8 flag, UINT8 type, UINT16 idx); void ReleaseUnused(void); static unsigned int ComputeSizeClass(UINT16 pages); static unsigned int ComputeUsablePages(unsigned int pages, size_t pagesize); // // The variables. NOTE: The size of this class must be a // multiple of 8, as long as sizeof(OpMemPageHandle) == 8. // // If this is not the case, we run the risk of having the // last handle straddle a memory page boundary. // char* base; ///< Address of (imaginary) page whose handle-index == 0 const OpMemory::OpMemSegment* mseg; ///< The underlying memory segment char* address_first_usable; ///< Address of first usable page char* address_last_usable; ///< First byte past the very last usable page void* address_upper_handles; ///< Address of first page with upper handles #ifdef ENABLE_MEMORY_MANAGER OpMemoryManager* mm; ///< Cached pointer to memory manager #else void* unused1; ///< Padding to get size to multiple of 8 #endif unsigned int pagesize; ///< Memory page size in bytes unsigned int pagesize_shift; ///< Cached log2(pagesize) unsigned int highest_index; ///< Highest indexed page seen so far (*) unsigned int header_pages; ///< Number of pages for header unsigned int header_max_pages; /// Size of dynamically allocatable header unsigned int size_upper_handles; ///< Size of upper handles unsigned int hdrtype; ///< Memory class type for header data only unsigned int unusedtype; ///< Memory class type for unused data unsigned int max_size_class; ///< Highest possible size-class unsigned int allocated_pages; ///< Number of allocated pages unsigned int unused_pages_threshold; ///< Limit unused pages unsigned int unused_pages; ///< Number of unused pages /** * \brief Try keep track of the maximum sized block in a sizeclass * * This information is not always correct, but it can be used to * improve searching performance. It will not be correct in that * it may hold a too large number, being too optimistic about what * allocations can be made. When this happens, a search will fail * for the sizeclass. The maximum sizeed block info will be updated * on a failed search, so future searches will have more accurate * information. * * When a free operation makes more data available than what is * currently logged, the max-size is updated. An allocation should * thus never fail because of incorrect max-size information. * * \b Note: This array *must* be a multiple of 4 elements in size * to satisfy the size requirements outlined above. */ UINT16 max_size[OP_MMAP_ANCHOR_COUNT]; #ifdef SELFTEST /** * \brief Helper array used by the TestState() method * * The TestState() method will collect the individual blocks * in the segment (regardless of type), and compare them * with a given "original" as part of selftests. * * The blockinfo[] array holds the distilled information * on the blocks while the TestState() metod is running. */ UINT16 blockinfo[2*OP_MMAP_MAX_TESTABLE_BLOCKS+4]; #endif /** * \brief Padding to get sizeof(OpMmapSegment) % 8 == 0 * * Each \c OpMemPageHandle in the \c page_handle needs to * fit entirely inside a memory page, to simplify allocation * logic. * * This padding makes sure this is always the case. */ UINT16 padding[2]; /** * \brief The array of OpMemPageHandle handles * * This array holds the first few handles of the OpMmapSegment. * The handles are the ones used as "anchors" for the various * allocation size classes (for both unused and reserved memory * regions). * * The low-address sentinel will follow right after this class, * and then the page handle for the first usable memory page will * follow and then so on, until the page handle for the last * usable memory page, and finally the high-address sentinel. * * \b Note: This array must be last in this class declaration * since it will extend past the end of the contining class, and * continue into the dynamically allocated memory in the virtual * \c OpMemSegment. */ OpMemPageHandle page_handle[OP_MMAP_ANCHOR_COUNT]; ///< The handles }; #if 0 // This is TBD class OpMmapManager { public: OpMmapManager(void); void* mmap(size_t size, BOOL executable); void munmap(void* ptr); private: OpMmapSegment* mmapseg; }; #endif // 0 #endif // ENABLE_OPERA_MMAP_SEGMENT #endif // MEMORY_MMAP_H
#include<iostream> #include<cstdio> #include<string> using namespace std; int count_difference(int a){ int hash[15] = {0}; int result = 0; for(int i=0;i<4;++i){ if(a==0){ ++hash[0]; }else{ int temp = a - a/10*10; ++hash[temp]; a /= 10; } } for(int i=0;i<10;++i){ if(hash[i]>0){ ++result; } } return result; } int main(){ //input int year; int number; cin>>year>>number; int now_year = year; while(count_difference(now_year)!=number){ ++now_year; } printf("%d %04d",now_year-year,now_year); return 0; } //1. 1 2 this case was forgot
#include <iostream> #include <random> #include <vector> #include <algorithm> #include <chrono> using namespace std::chrono; using namespace std; #ifndef _GLIBCXX_MAP_H #define _GLIBCXX_MAP_H enum blocks{ EXIT = 17, ENTRY, VENDING, DROP }; enum maps{ BUILDING = 0, HOSPITAL, LABYRINTH}; class Map{ double roomX, roomY; mt19937 pattern; uint32_t curr_seed; enum walls{ LEFT, DOWN, UP, RIGHT }; bool last_entry = false; double offsetx = 0, offsety = 0; int map_type; long long int last_room = 1, curr_room = 1; public: static const int xsize = 16, ysize = 16; struct Coord{ double x; double y; char type; Coord(){} Coord(double x, double y, char type) : x(x), y(y), type(type){} }; Map(); double alterBeingPosX(double absoluteX); double alterBeingPosY(double absoluteY); void loadMap(time_t seed); const vector<Coord>& getMapObjects() const; const vector<vector<char>>& getMapIndex() const; Coord getMapEntry(); bool tryRoomChange(int x, int y); bool updateInternalMapState(); int getMapType(); int getMaxMonsters(); int getSpawnRate(); void getRoomSize(double& x, double& y); long long int getLastExploredRoom(); long long int getCurrentRoomNumber(); void addLoot(int xtile, int ytile); private: vector<Coord> blocks; vector<vector<char>> room; int room_entry_x, room_entry_y, room_exit_x, room_exit_y; void generateRoom(uint32_t seed, bool exited); }; #endif
#include<cstdio> #include<stdlib.h> #include<malloc.h> #include<queue> #include<iostream> #include<stack> #include<conio.h> using namespace std; struct node { int a; struct node *left; struct node *right; }; void insert(struct node **ptr,int data) { if((*ptr) == NULL) { (*ptr) = (struct node *)malloc(sizeof(struct node)); (*ptr)->a = data; (*ptr)->left = (*ptr)->right = NULL; return; } if(data < (*ptr)->a) { insert(&((*ptr)->left),data); } if(data > (*ptr)->a) { insert(&((*ptr)->right),data); } else {return; } } int findmin(struct node *ptr) { while(ptr->left != NULL) { ptr = ptr->left; } return (ptr->a); } void inorder(struct node *ptr) { while(ptr != NULL) { inorder((ptr->left)); printf("%d",ptr->a); inorder((ptr->right)); } } void deletetree(struct node **ptr) { while((*ptr) != NULL) { deletetree(&(*ptr)->left); deletetree(&(*ptr)->right); (*ptr) = NULL; delete(*ptr); } } void delete1(struct node **ptr,int data) { if((*ptr) == NULL) { return ; } if(data < (*ptr)->a) { delete1(&((*ptr)->left),data); } else if(data > (*ptr)->a) { delete1(&((*ptr)->right),data); } else { if((*ptr)->left != NULL && (*ptr)->right != NULL) { int res = findmin((*ptr)->right); (*ptr)->a = res; delete1(&((*ptr)->right),res); } else { struct node *temp = (*ptr); if((*ptr)->left != NULL) { (*ptr) = (*ptr)->left; } else if((*ptr)->right != NULL) { (*ptr) = (*ptr)->right; } else { (*ptr) = NULL; } temp = NULL; delete(temp); } } } int main() { struct node *tree = NULL; insert(&tree,10); insert(&tree,12); insert(&tree,7); insert(&tree,4); insert(&tree,5); insert(&tree,22); insert(&tree,11); insert(&tree,21); insert(&tree,3); insert(&tree,5); inorder(tree); printf("\n"); getch(); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; int main() { LL b,d,s; scanf("%I64d%I64d%I64d",&b,&d,&s); LL com = min(min(b,d),s),ans = 0; b -= com;d -= com;s -= com; LL m = max(max(b,d),s); LL d1 = b+d+s-m; if (b > 0) b -= d1; if (d > 0) d -= d1; if (s > 0) s -= d1; LL d2 = b+d+s; if (d2 > 0) d2--; else if (d1 > 0) d1--; printf("%I64d\n",d2*2+d1); return 0; }
//Name: Dan Haub //Student ID#: 2315346 //Chapman Email: haub@chapman.edu //Course Number and Section: CPSC 350-01 //Assignment: 4 - Registrar Simulation #ifndef GEN_DOUBLE_LIST_NODE_H #define GEN_DOUBLE_LIST_NODE_H template<class T> class GenDoubleListNode{ public: GenDoubleListNode(); GenDoubleListNode(T d); //Overloaded constructor ~GenDoubleListNode(); T data; GenDoubleListNode *next; GenDoubleListNode *prev; }; template<class T> GenDoubleListNode<T>::GenDoubleListNode(){ data = nullptr; next = nullptr; prev = nullptr; } template<class T> GenDoubleListNode<T>::GenDoubleListNode(T d){ data = d; next = nullptr; prev = nullptr; } template<class T> GenDoubleListNode<T>::~GenDoubleListNode(){ next = nullptr; prev = nullptr; } #endif //GEN_DOUBLE_LIST_NODE_H
#include "animal.h" #include "tiger.h" #include "sea_lion.h" #include "bear.h" #include "zoo.h" #include <iostream> #include <cstdlib> using namespace std; Zoo::Zoo(){ //TODO// Finish this constructor bank_balance = 100000; tiger_count = 0; sea_lion_count = 0; bear_count = 0; cout << "Welcome to your new zoo! You are starting out with $100000 dollars; good luck!" << endl; } Zoo::~Zoo(){ //TODO// Finish this destructor delete [] tigers; delete [] bears; delete [] sealions; } void Zoo::compute_revenue(){ //TODO// Code for potential sea lion extra income for(int i = 0; i < tiger_count; i++){ if(tigers[i].get_age() < 6){ bank_balance = bank_balance + 2400; }else{ bank_balance = bank_balance + 1200; } }for(int i = 0; i < bear_count; i++){ if(bears[i].get_age() < 6){ bank_balance = bank_balance + 1000; }else{ bank_balance = bank_balance + 500; } }for(int i = 0; i < sea_lion_count; i++){ if(attendance_boom == false){ if(sealions[i].get_age() < 6){ bank_balance = bank_balance + 280; }else{ bank_balance = bank_balance + 140; } }else if(attendance_boom == true){ if(sealions[i].get_age() < 6){ bank_balance = bank_balance + 2 * (140 + rand() % 251 + 150); }else{ bank_balance = bank_balance + 140 + rand() % 251 + 150; } } } } void Zoo::compute_food_cost(){ srand(time(NULL)); float cost_adjustment = (rand() % 5 + 8) / 10.0; base_cost = base_cost * cost_adjustment; cout << "Current base cost of food: " << base_cost << endl; for(int i = 0; i < tiger_count; i++){ float temp1 = 5 * base_cost; bank_balance = bank_balance - temp1; } for(int i = 0; i < sea_lion_count; i++){ float temp2 = base_cost; bank_balance = bank_balance - temp2; } for(int i = 0; i < bear_count; i++){ float temp3 = 3 * base_cost; bank_balance = bank_balance - temp3; } } void Zoo::count_animals(int & baby_tiger_count, int & adult_tiger_count, int & baby_bear_count, int & adult_bear_count, int & baby_sealion_count, int & adult_sealion_count){ int temp_baby = 0; int temp_adult = 0; for(int i = 0; i < tiger_count; i++){ if(tigers[i].get_age() < 6){ temp_baby = temp_baby + 1; }else if(tigers[i].get_age() >= 48){ temp_adult = temp_adult + 1; } } baby_tiger_count = temp_baby; adult_tiger_count = temp_adult; temp_baby = 0; temp_adult = 0; for(int i = 0; i < bear_count; i++){ if(bears[i].get_age() < 6){ temp_baby = temp_baby + 1; }else if(bears[i].get_age() >= 48){ temp_adult = temp_adult + 1; } } baby_bear_count = temp_baby; adult_bear_count = temp_adult; temp_baby = 0; temp_adult = 0; for(int i = 0; i < sea_lion_count; i++){ if(sealions[i].get_age() < 6){ temp_baby = temp_baby + 1; }else if(sealions[i].get_age() >= 48){ temp_adult = temp_adult + 1; } } baby_sealion_count = temp_baby; adult_sealion_count = temp_adult; } void Zoo::turn_hub_function(){ //TODO// Code the special event function. cout << "Your current bank balance is: $" << bank_balance << endl; increment_ages(); //Special event occurs special_event(); //Monthy revenue compute_revenue(); int baby_tiger_count, adult_tiger_count, baby_bear_count, adult_bear_count, baby_sealion_count, adult_sealion_count; count_animals(baby_tiger_count, adult_tiger_count, baby_bear_count, adult_bear_count, baby_sealion_count, adult_sealion_count); cout << "You currently have:" << endl << "\tTigers: " << endl << "\t\tBabies: " << baby_tiger_count << endl << "\t\tAdults: " << adult_tiger_count << endl; cout << endl << "\tBears: " << endl << "\t\tBabies: " << baby_bear_count << endl << "\t\tAdults: " << adult_bear_count << endl; cout << endl << "\tSea Lions: " << endl << "\t\tBabies: " << baby_sealion_count << endl << "\t\tAdults: " << adult_sealion_count << endl; //Purchase animals animal_purchase_choice(); system("clear"); //Pay for animal feeding compute_food_cost(); } void Zoo::special_event(){ srand(time(NULL)); int event = rand() % 4; if(event == 0){ sick(); } else if(event == 1){ birth(); } else if(event == 2){ cout << "There was a boom in attendence this month! Hope you bought some sea lions!" << endl; attendance_boom = true; } else if(event == 3){ return; } } bool Zoo::is_loss(){ if(bank_balance < 0){ return true; } return false; } void Zoo::birth(){ bool sealion_valid = true; bool tiger_valid = true; bool bear_valid = true; while(sealion_valid == true || tiger_valid == true || bear_valid == true){ int mother = rand() % 3; if(mother == 0 && tiger_valid == true){ for(int i = 0; i < tiger_count; i++){ if(tigers[i].get_age() >= 48){ purchase_tiger(3, 0); cout << "One of your tigers gave birth to three babies!" << endl; return; } } tiger_valid = false; } else if(mother == 1 && bear_valid == true){ for(int i = 0; i < bear_count; i++){ if(bears[i].get_age() >= 48){ purchase_bear(2, 0); cout << "One of your bears gave birth to two babies!" << endl; return; } } bear_valid = false; } else if(mother == 2 && sealion_valid == true){ for(int i = 0; i < sea_lion_count; i++){ if(sealions[i].get_age() >= 48){ purchase_sea_lion(1, 0); cout << "One of your sea lions gave birth to a baby!" << endl; return; } } sealion_valid = false; } } } void Zoo::sick_tiger(){ int species2 = rand() % tiger_count; if(tigers[species2].get_age() < 6){ if(bank_balance < 12000){ cout << "Uh oh! You didn't have enough money to heal one of your baby tigers! They passed." << endl; kill_tiger(species2); } cout << "Uh oh! One of your baby tigers got sick! It cost $12000 to heal them." << endl; bank_balance = bank_balance - 12000; return; }else{ if(bank_balance < 6000){ cout << "Uh oh! You didn't have enough money to heal one of your tigers! They passed." << endl; kill_tiger(species2); } cout << "Uh oh! One of your tigers got sick! It cost $6000 to heal them." << endl; bank_balance = bank_balance - 6000; return; } } void Zoo::kill_tiger(int species2){ Tiger * temp; temp = new Tiger[tiger_count - 1]; for(int i = 0; i < species2; i++){ temp[i].set_age(tigers[i].get_age()); } for(int i = species2; i < tiger_count - 1; i++){ temp[i].set_age(tigers[i + 1].get_age()); } delete [] tigers; tigers = temp; tiger_count = tiger_count - 1; } void Zoo::sick_bear(){ int species2 = rand() % bear_count; if(bears[species2].get_age() < 6){ cout << "Uh oh! One of your baby bears got sick! It cost $5000 to heal them." << endl; bank_balance = bank_balance - 5000; return; }else{ cout << "Uh oh! One of your bears got sick! It cost $2500 to heal them." << endl; bank_balance = bank_balance - 2500; return; } } void Zoo::kill_bear(int species2){ Bear * temp; temp = new Bear[bear_count - 1]; for(int i = 0; i < species2; i++){ temp[i].set_age(bears[i].get_age()); } for(int i = species2; i < bear_count - 1; i++){ temp[i].set_age(bears[i + 1].get_age()); } delete [] bears; bears = temp; bear_count = bear_count - 1; } void Zoo::sick_sealion(){ int species2 = rand() % sea_lion_count; if(sealions[species2].get_age() < 6){ cout << "Uh oh! One of your baby sea lions got sick! It cost $700 to heal them." << endl; bank_balance = bank_balance - 700; return; }else{ cout << "Uh oh! One of your sea lions got sick! It cost $350 to heal them." << endl; bank_balance = bank_balance - 350; return; } } void Zoo::kill_sealion(int species2){ SeaLion * temp; temp = new SeaLion[sea_lion_count - 1]; for(int i = 0; i < species2; i++){ temp[i].set_age(sealions[i].get_age()); } for(int i = species2; i < sea_lion_count - 1; i++){ temp[i].set_age(sealions[i + 1].get_age()); } delete [] sealions; sealions = temp; sea_lion_count = sea_lion_count - 1; } bool Zoo::apply_sick(bool tiger_valid, bool bear_valid, bool sealion_valid){ int species1 = rand() % 3; if(species1 == 0 && tiger_valid == true){ sick_tiger(); return true; }else if(species1 == 1 && bear_valid == true){ sick_bear(); return true; }else if(species1 == 2 && sealion_valid == true){ sick_sealion(); return true; } return false; } void Zoo::sick(){ ////srand(time(NULL)); bool tiger_valid = true; bool bear_valid = true; bool sealion_valid = true; bool complete = false; if(tiger_count == 0){ tiger_valid = false; }if(bear_count == 0){ bear_valid = false; }if(sea_lion_count == 0){ sealion_valid = false; } while((tiger_valid == true || bear_valid == true || sealion_valid == true) && complete == false){ complete = apply_sick(tiger_valid, bear_valid, sealion_valid); } return; } void Zoo::animal_purchase_choice(){ string count; string purchase_choice; string species_choice; cout << "Would you like to purchase animals this turn? (yes or no)" << endl << "Choice: "; getline(cin, purchase_choice); while(purchase_choice != "yes" && purchase_choice != "no"){ cout << "Invalid choice! Please input a 'yes' or a 'no'." << endl << "Choice: "; getline(cin, purchase_choice); } if(purchase_choice == "yes"){ cout << "Which species of animal would you like to purchase (tiger, bear, or sea lion)?" << endl << "Choice: "; getline(cin, species_choice); //TODO Error handle this input. while(species_choice != "tiger" && species_choice != "bear" && species_choice != "sea lion"){ cout << "Invalid choice! Please input one of the following options: 'tiger' 'bear' 'sea lion': "; getline(cin, species_choice); } cout << "How many would you like to buy? (1 or 2)" << endl << "Count: "; getline(cin, count); //TODO// Error handle this input. while(count != "1" && count != "2"){ cout << "Invalid input, you must choose to buy only 1 or 2: "; getline(cin, count); } if(species_choice == "Tiger" || species_choice == "tiger"){ purchase_tiger(stoi(count), 48); }else if(species_choice == "Sea Lion" || species_choice == "sea lion"){ purchase_sea_lion(stoi(count), 48); }else if(species_choice == "Bear" || species_choice == "bear"){ purchase_bear(stoi(count), 48); } }else if(purchase_choice == "no"){ return; } } void Zoo::purchase_tiger(int count, int new_age){ if(tiger_count == 0){ tigers = new Tiger[count]; for(int i = 0; i < count; i++){ tigers[i].set_age(new_age); } }else{ Tiger * temp; temp = new Tiger[tiger_count + count]; for(int i = 0; i < tiger_count; i++){ temp[i].set_age(tigers[i].get_age()); } delete [] tigers; tigers = temp; for(int i = 0; i < count; i++){ tigers[tiger_count + i].set_age(new_age); } } tiger_count = tiger_count + count; if(new_age == 48){ bank_balance = bank_balance - 12000 * count; } } void Zoo::purchase_bear(int count, int new_age){ if(bear_count == 0){ bears = new Bear[count]; for(int i = 0; i < count; i++){ bears[i].set_age(new_age); } }else{ Bear * temp; temp = new Bear[bear_count + count]; for(int i = 0; i < bear_count; i++){ temp[i].set_age(bears[i].get_age()); } delete [] bears; bears = temp; for(int i = 0; i < count; i++){ bears[bear_count + i].set_age(new_age); } } bear_count = bear_count + count; bank_balance = bank_balance - 5000 * count; } void Zoo::purchase_sea_lion(int count, int new_age){ if(sea_lion_count == 0){ sealions = new SeaLion[count]; for(int i = 0; i < count; i++){ sealions[i].set_age(new_age); } }else{ SeaLion * temp; temp = new SeaLion[sea_lion_count + count]; for(int i = 0; i < sea_lion_count; i++){ temp[i].set_age(sealions[i].get_age()); } delete [] sealions; sealions = temp; for(int i = 0; i < count; i++){ sealions[sea_lion_count + i].set_age(new_age); } } sea_lion_count = sea_lion_count + count; bank_balance = bank_balance - 700 * count; } void Zoo::increment_ages(){ for(int i = 0; i < tiger_count; i++){ tigers[i].set_age(tigers[i].get_age() + 1); } for(int i = 0; i < sea_lion_count; i++){ sealions[i].set_age(sealions[i].get_age() + 1); } for(int i = 0; i < bear_count; i++){ bears[i].set_age(bears[i].get_age() + 1); } } int Zoo::get_tiger_count(){ return tiger_count; } int Zoo::get_sea_lion_count(){ return sea_lion_count; } int Zoo::get_bear_count(){ return bear_count; } int Zoo::get_bank_balance(){ return bank_balance; } void Zoo::set_bank_balance(int new_balance){ bank_balance = new_balance; }
/** Kabuki SDK @file /.../Source/Kabuki_SDK-Impl/include/_App/WindowGroup.h @author Cale McCollough @copyright Copyright 2016 Cale McCollough © @license http://www.apache.org/licenses/LICENSE-2.0 */ #pargma once #include <vector> #include namespace _App { /** Class that stores a group of _App.Window objects. */ class WindowGroup { public: static const int DefaultMaxWindows = 1024; /** Default constructor. **/ WindowGroup (); /** Constructor initializes with a single window. */ WindowGroup (Window& thisWindow); /** Constructor initializes with an array of windows. */ WindowGroup (vector<Window> initWindows); /** Returns the UID of this Group. */ long GetUID (); /** Gets and sets the maximum number of windows in this group */ int GetMaxWindows (); void SetMaxWindows (int Value); /** */ int Select (int windowNumber); /** Returns the number of windows in this group. */ int GetNumWindows (); /** Adds a newWindow to the group. */ void AddWindow (Window newWindow); /** Returns a string representation of this object. */ string ToString (); private: long uID; //< The UID of this Group. int numWindows, //< The number of windows in this group. maxWindows; //< The maximum number of windows allowed in a group. vector<Window> windows; //< The Window (s) in this group. }; }
// // Created by danl on 19.06.2020. // #include <iostream> #include "Physics.h" btRigidBody* Physics::createRigidBody(float mass, const btTransform& startTransform, btCollisionShape* shape) { bool isDynamic = (mass != 0.f); btVector3 localInertia(0, 0, 0); if (isDynamic) shape->calculateLocalInertia(mass, localInertia); btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform); btRigidBody::btRigidBodyConstructionInfo cInfo(mass, myMotionState, shape, localInertia); btRigidBody* body = new btRigidBody(cInfo); body->setUserIndex(-1); world->addRigidBody(body); return body; } Physics::Physics() { auto collisionConfiguration = new btDefaultCollisionConfiguration(); auto dispatcher = new btCollisionDispatcher(collisionConfiguration); auto broadphase = new btDbvtBroadphase(); auto solver = new btSequentialImpulseConstraintSolver; world = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration); world->setGravity(btVector3(0, -10, 0)); } btDiscreteDynamicsWorld *Physics::getWorld() const { return world; }
/* * @Description: voxel filter 模块实现 * @Author: Ren Qian * @Date: 2020-02-09 19:53:20 */ #include "lidar_localization/models/cloud_filter/voxel_filter.hpp" #include "glog/logging.h" namespace lidar_localization { VoxelFilter::VoxelFilter(const YAML::Node& node) { float leaf_size_x = node["leaf_size"][0].as<float>(); float leaf_size_y = node["leaf_size"][1].as<float>(); float leaf_size_z = node["leaf_size"][2].as<float>(); SetFilterParam(leaf_size_x, leaf_size_y, leaf_size_z); } VoxelFilter::VoxelFilter(float leaf_size_x, float leaf_size_y, float leaf_size_z) { SetFilterParam(leaf_size_x, leaf_size_y, leaf_size_z); } bool VoxelFilter::SetFilterParam(float leaf_size_x, float leaf_size_y, float leaf_size_z) { voxel_filter_.setLeafSize(leaf_size_x, leaf_size_y, leaf_size_z); std::cout << "Voxel Filter 的参数为:" << std::endl << leaf_size_x << ", " << leaf_size_y << ", " << leaf_size_z << std::endl << std::endl; return true; } bool VoxelFilter::Filter(const CloudData::CLOUD_PTR& input_cloud_ptr, CloudData::CLOUD_PTR& filtered_cloud_ptr) { voxel_filter_.setInputCloud(input_cloud_ptr); voxel_filter_.filter(*filtered_cloud_ptr); return true; } }
#pragma unmanaged #include <stddef.h> #pragma managed #include "Position.h" #include "TilePosition.h" #include "WalkPosition.h" namespace BroodWar { namespace Api { BWAPI::Position ConvertPosition(Position^ position) { if (position == nullptr) return BWAPI::Positions::None; return *(position->instance); } Position^ ConvertPosition(BWAPI::Position position) { return gcnew Position(position); } Position^ ConvertPosition(BWAPI::Position* position) { if (position == NULL) return nullptr; return gcnew Position(position, false); } Position::Position(BWAPI::Position *position, bool takeOwnership) { instance = position; dispose = takeOwnership; } Position::Position(BWAPI::Position position) { instance = new BWAPI::Position(position); dispose = true; } Position::~Position() { if (dispose) delete instance; } Position::!Position() { if (dispose) delete instance; } Position::Position() { instance = new BWAPI::Position(); dispose = true; } Position::Position(Position^ copy) { instance = new BWAPI::Position(*(copy->instance)); dispose = true; } Position::Position(int x, int y) { instance = new BWAPI::Position(x, y); dispose = true; } int Position::X::get() { return instance->x; } int Position::Y::get() { return instance->y; } bool Position::IsValid::get() { return instance->isValid(); } double Position::CalcDistance(Position^ position) { return instance->getDistance(*(position->instance)); } int Position::CalcApproximateDistance(Position^ position) { return instance->getApproxDistance(*(position->instance)); } double Position::CalcLength() { return instance->getLength(); } void Position::MakeValid() { instance->makeValid(); } bool Position::IsInvalid::get() { return *instance == BWAPI::Positions::Invalid; } bool Position::IsNone::get() { return *instance == BWAPI::Positions::None; } bool Position::IsUnknown::get() { return *instance == BWAPI::Positions::Unknown; } int Position::GetHashCode() { return instance->x * 397 ^ instance->y; } bool Position::Equals(Object^ o) { Position^ other = dynamic_cast<Position^>(o); return this->Equals(other); } bool Position::Equals(Position^ other) { if (ReferenceEquals(nullptr, other)) return false; if (ReferenceEquals(this, other)) return true; return this->instance->x == other->instance->x && this->instance->y == other->instance->y; } bool Position::operator == (Position^ first, Position^ second) { if (ReferenceEquals(first, second)) return true; if (ReferenceEquals(nullptr, first) || ReferenceEquals(nullptr, second)) return false; return *(first->instance) == *(second->instance); } bool Position::operator != (Position^ first, Position^ second) { if (ReferenceEquals(first, second)) return false; if (ReferenceEquals(nullptr, first) || ReferenceEquals(nullptr, second)) return true; return *(first->instance) != *(second->instance); } bool Position::operator < (Position^ first, Position^ second) { return *(first->instance) < *(second->instance); } Position^ Position::operator + (Position^ first, Position^ second) { return ConvertPosition(*(first->instance) + *(second->instance)); } Position^ Position::operator - (Position^ first, Position^ second) { return ConvertPosition(*(first->instance) - *(second->instance)); } Position^ Position::operator * (Position^ first, int second) { return ConvertPosition(*(first->instance) * second); } Position^ Position::operator / (Position^ first, int second) { return ConvertPosition(*(first->instance) / second); } Position^ Position::operator += (Position^ first, Position^ second) { *(first->instance) += *(second->instance); return first; } Position^ Position::operator -= (Position^ first, Position^ second) { *(first->instance) -= *(second->instance); return first; } Position^ Position::operator *= (Position^ first, int second) { *(first->instance) *= second; return first; } Position^ Position::operator /= (Position^ first, int second) { *(first->instance) /= second; return first; } Position^ Position::Rescale(TilePosition^ position) { return gcnew Position(new BWAPI::Position(*(position->instance)), true); } Position^ Position::Rescale(WalkPosition^ position) { return gcnew Position(new BWAPI::Position(*(position->instance)), true); } } }
#include "Linked_List.h" #ifndef SIMPLE_LIST_H #define SIMPLE_LIST_H template <typename T> class Simple_List { public: //Constructor Simple_List() { head_ptr = nullptr; } //Copy constructor Simple_List(const Simple_List& other) { //copy the junk over head_ptr = copy_list(other.head_ptr); } //Destructor ~Simple_List() { clear_list(head_ptr); } //Assignment operator --erroneous Simple_List& operator=(const Simple_List& RHS) { //self-check if (head_ptr == RHS.head_ptr) { return *this; } //clean up the dynamic memory of LHS clear_list(head_ptr); //instantiate the LHS again head_ptr = nullptr; //copy the junk over head_ptr = copy_list(RHS.head_ptr); //return return *this; } node<T>* insert_head(const T& item) { return::insert_head(head_ptr, item); } node<T>* insert_before(node<T>* mark, const T& item) { return::insert_before(head_ptr, mark, item); } node<T>* insert_after(node<T>* mark, const T& item) { return::insert_after(head_ptr, mark, item); } //If I keep both--error: fxns only differ in return type cannot be overloaded //insert item. Assume sorted list node<T>* InsertSorted(T item) { return::InsertSorted(head_ptr, item); } //delete node pointed to by iMarker T Delete(node<T>* iMarker) { return::delete_head(head_ptr); // return::delete_node(head_ptr, iMarker); //for polynomial, but not for stack class } //print the list void Print() const { return print_list(head_ptr); } //return pointer to node containing key. NULL if not there node<T>* Search(const T &key) { return search_list(head_ptr, key); } //get the previous node to iMarker node<T>* Prev(node<T>* iMarker) { return PreviousNode(head_ptr, iMarker); } //return the item at index T& operator[](int index) { return At(head_ptr, index); } //return the head of the list node<T>* Begin() const { //cout << this->head_ptr->_item << endl; return head_ptr; } //return the tail of the list: if you ever have to use this, you're screwed node<T>* End() const { return LastNode(head_ptr); } //NOT YET IMPLEMENTED //insertion operator for list /* template <class U> friend ostream& operator<<(ostream& outs, const Simple_List<U>& l) { node<U>* walker = l.head_ptr; while (walker != nullptr) { outs << " [" << walker->_item << "] -->"; walker = walker->_next; } outs << "|||" << endl; return outs; } */ private: node<T>* head_ptr; }; #endif /* SIMPLE_LIST_H */
// // Created by payaln on 27.02.2019. // #include "StepAction.h" StepAction::StepAction(TrackAction* tr) : track(tr) {} void StepAction::UserSteppingAction(const G4Step *step) { if (step->GetPostStepPoint()->GetPhysicalVolume() != nullptr) { if (step->GetPostStepPoint()->GetPhysicalVolume()->GetName() == "anode_PV") { track->AddLostEnergy( step->GetPreStepPoint()->GetKineticEnergy() - step->GetPostStepPoint()->GetKineticEnergy() ); } } }
#include <iostream> #include <string> using namespace std; int main() { int n,i,a,b,count; cout<<"enter the limits"; cin>>a>>b; for(i=a;i<b;i++) { count=0; for(n=2;n<i;n++) { if(i%n==0) count++; } if(count==0) cout<<i<<endl; } return 0; }
/* Copyright (C) 2018, Accelize 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. */ #ifdef NOGUI #include "common.h" #else #include "gui.h" #endif /* * HAL Sanity Check */ int32_t halSanityCheck(void) { return 0; } /* * DRMLib Read Callback Function */ int32_t my_read_drm(uint32_t slotID, uint32_t addr, uint32_t * value) { return 0; } /* * DRMLib Write Callback Function */ int32_t my_write_drm(uint32_t slotID, uint32_t addr, uint32_t value) { return 0; } /* * User IP Register Read */ int32_t my_read_userip(uint32_t slotID, uint32_t addr, uint32_t * value) { if(slotID==3) *value=0; else if(slotID==4) *value=1; else if(slotID==5) *value=2; else *value = 3; return 0; } /* * Program_FPGA */ int32_t progFPGA(uint32_t slotID) { return 0; } /** * Init FPGA */ int32_t initFPGA(uint32_t slotID) { addToRingBuffer(slotID, std::string("[INFO] Programming FPGA ...")); addToRingBuffer(slotID, std::string("[INFO] Initit FPGA successfull ...")); return 0; } /** * Uninit FPGA */ void uninitFPGA(uint32_t slotID) { addToRingBuffer(slotID, std::string("[INFO] Uninit FPGA ...")); gDashboard.slot[slotID].appState = STATE_IDLE; } /* * sanity_check */ int sanity_check(uint32_t slot_id) { return 0; } /** * DRMLib quick MOCK */ typedef std::function<int/*errcode*/ (uint32_t /*register offset*/, uint32_t* /*returned data*/)> ReadRegisterCallback; typedef std::function<int/*errcode*/ (uint32_t /*register offset*/, uint32_t /*data to write*/)> WriteRegisterCallback; typedef std::function<void (const std::string&/*error message*/)> AsynchErrorCallback; class DrmManager { public: enum ParameterKey { SESSION_ID=0, METERING_DATA, NUM_ACTIVATORS }; DrmManager() = delete; //!< No default constructor inline DrmManager(const std::string& conf_file_path, const std::string& cred_file_path, ReadRegisterCallback f_drm_read32, WriteRegisterCallback f_drm_write32, AsynchErrorCallback f_error_cb){}; inline ~DrmManager() {}; //!< Destructor inline void activate(){}; inline void deactivate(){}; inline void get( ParameterKey keyId, std::string& json_string ){json_string=std::string("42");}; inline void set( std::string& json_string ){}; };
#include <Dot++/lexer/TokenizerStatesPack.hpp> #include <Dot++/Exceptions.hpp> #include <Dot++/lexer/TokenizerState.hpp> namespace dot_pp { namespace lexer { const TokenizerStateInterface& TokenizerStatesPack::operator[](const TokenizerState state) const { // ordered by frequency of use switch(state) { case TokenizerState::Init: return init_; case TokenizerState::StringLiteral: return stringLiteral_; case TokenizerState::StringLiteralEscape: return stringLiteralEscape_; case TokenizerState::HashLineComment: return hashLineComment_; case TokenizerState::BeginSlashLineComment: return beginSlashLine_; case TokenizerState::SlashLineComment: return slashLineComment_; case TokenizerState::MultiLineComment: return multiLineComment_; case TokenizerState::EndMultiLineComment: return endMultiLineComment_; case TokenizerState::MultiLineEscape: return multiLineEscape_; case TokenizerState::Error: return error_; default: break; }; throw UnknownTokenizerState(state); } }}
/* * IOBuffer.cpp * * Created on: 29 Mar 2011 * Author: two */ #include "IOBuffer.h" #include <iostream> using namespace std; int ioBufferWriteFunc(void *opaque, uint8_t *buf, int buf_size) { /* * Copy and write the buffer into the list! */ ioBufferContext* bufcon = (ioBufferContext*)opaque; uint8_t* bufcopy; //Copy the buffer bufcopy = (uint8_t*)malloc(buf_size); memcpy(bufcopy, buf, buf_size); pthread_mutex_lock( &(bufcon->lock) ); //Check where we are to write next, reset to 0 if reached end if(bufcon->writeIndex >= bufcon->packetListSize) { //Reset to 0 bufcon->writeIndex = 0; } //Free up the memory that's allocated if (bufcon->packetList[bufcon->writeIndex] != NULL) { //It's not null, Free free(bufcon->packetList[bufcon->writeIndex]); } //Write over the pointer! :) bufcon->packetList[bufcon->writeIndex] = bufcopy; bufcon->packetLength[bufcon->writeIndex] = buf_size; if(bufcon->currentPos == bufcon->totalWritten) { //at the end! bufcon->packetPosition[bufcon->writeIndex] = -1; } else { //not at the end :( bufcon->packetPosition[bufcon->writeIndex] = bufcon->currentPos; } bufcon->writeIndex = 1 + bufcon->writeIndex; //Is this the first set? if(bufcon->firstWriteEnabled && bufcon->firstWriteIndex < bufcon->firstPacketListSize) { bufcopy = (uint8_t*)malloc(buf_size); memcpy(bufcopy, buf, buf_size); bufcon->firstPacketList[bufcon->firstWriteIndex] = bufcopy; bufcon->firstPacketLength[bufcon->firstWriteIndex] = buf_size; bufcon->writeIndex += 1; } bufcon->currentPos += buf_size; if (bufcon->currentPos > bufcon->totalWritten) bufcon->totalWritten = bufcon->currentPos; pthread_mutex_unlock( &(bufcon->lock) ); return 0; } int ioBufferReadFunc(void *opaque, uint8_t *buf, int buf_size) { return 0; } int64_t ioBufferSeekFunc(void *opaque, int64_t offset, int whence) { /* * this is mostly used to debug. Not real interesting stuff here :( */ ioBufferContext* bufcon = (ioBufferContext*)opaque; cout << "Seek W:"<< whence << " offset: " << offset << endl; if(SEEK_SET == whence) cout << "SEEKSET" << endl; if(SEEK_CUR == whence) cout << "SEEKCUR" << endl; if(SEEK_END == whence) cout << "SEEKEND" << endl; pthread_mutex_lock( &(bufcon->lock) ); bufcon->printWrites = 0x01; // true! if(SEEK_SET == whence) { bufcon->currentPos = offset; } pthread_mutex_unlock( &(bufcon->lock) ); return 0; } IOBuffer::IOBuffer() { // TODO Auto-generated constructor stub m_pByteIOContext = NULL; m_nBufferSize = 1024*1024*8; //8 MB m_pBuffer = (uint8_t*) malloc(m_nBufferSize); m_pIOBufferContext = (ioBufferContext*) malloc(sizeof(ioBufferContext)); //Alloc IOBufferContext //Initilise the IOBufferContext :) m_pIOBufferContext->packetListSize = 100; // insane! D: m_pIOBufferContext->packetList = (uint8_t**) malloc( sizeof(uint8_t*) * m_pIOBufferContext->packetListSize ); m_pIOBufferContext->packetLength = (int*) malloc( sizeof(int) * m_pIOBufferContext->packetListSize ); m_pIOBufferContext->packetPosition = (int*) malloc( sizeof(int) * m_pIOBufferContext->packetListSize ); m_pIOBufferContext->writeIndex = 0; m_pIOBufferContext->lock = PTHREAD_MUTEX_INITIALIZER; //Fill up packet lists with NULL/0 for(int i=0; i< m_pIOBufferContext->packetListSize; i++) { m_pIOBufferContext->packetList[i] = NULL; m_pIOBufferContext->packetLength[i] = 0; } //Going to store first 20 packets! m_pIOBufferContext->firstPacketListSize = 10; m_pIOBufferContext->firstPacketList = (uint8_t**) malloc( sizeof(uint8_t*) * m_pIOBufferContext->firstPacketListSize ); m_pIOBufferContext->firstPacketLength = (int*) malloc( sizeof(int) * m_pIOBufferContext->firstPacketListSize ); m_pIOBufferContext->firstWriteEnabled = 0; m_pIOBufferContext->firstWriteIndex = 0; m_pIOBufferContext->totalWritten = 0; m_pIOBufferContext->currentPos = 0; m_pIOBufferContext->printWrites = 0x00; // false. m_pByteIOContext = av_alloc_put_byte(m_pBuffer, m_nBufferSize, 1, (void*)m_pIOBufferContext, ioBufferReadFunc, ioBufferWriteFunc, ioBufferSeekFunc); /* init_put_byte( ByteIOContext * s, unsigned char * buffer, int buffer_size, int write_flag, void * opaque, int(*)(void *opaque, uint8_t *buf, int buf_size) read_packet, int(*)(void *opaque, uint8_t *buf, int buf_size) write_packet, int64_t(*)(void *opaque, int64_t offset, int whence) seek ) */ } ByteIOContext * IOBuffer::getByteIOContext() { return m_pByteIOContext; } void IOBuffer::copyPresentBufferToFirst() { /* * Does what it says on the tin. Copies all the buffers * and replaces them into the first one. */ //No freeing of current stuff, Shouldn't be allocated and shouldn't // auto fill to end. int i; int size = m_pIOBufferContext->writeIndex -1; if(size < 0) size = m_pIOBufferContext->packetListSize; size += 1; //Allocate the pointer list :) m_pIOBufferContext->firstPacketList = (uint8_t**)malloc(size*sizeof(uint8_t*)); m_pIOBufferContext->firstPacketLength = (int*)malloc(size*sizeof(int)); //Fill them up for(i = 0; i< size ;i++) { uint8_t * buf = (uint8_t*)malloc(m_pIOBufferContext->packetLength[i]); memcpy(buf, m_pIOBufferContext->packetList[i], m_pIOBufferContext->packetLength[i]); m_pIOBufferContext->firstPacketList[i] = buf; m_pIOBufferContext->firstPacketLength[i] = m_pIOBufferContext->packetLength[i]; } m_pIOBufferContext->firstPacketListSize = size; } IOBuffer::~IOBuffer() { // TODO Auto-generated destructor stub } /* * * IOBufferReader! * */ IOBufferReader::IOBufferReader(ioBufferContext * ioBufCon) { /* * Will set up the reading index as the latest packet */ m_pIOBufferContext = ioBufCon; pthread_mutex_lock( &(m_pIOBufferContext->lock) ); m_nReadIndex = m_pIOBufferContext->writeIndex - 1; pthread_mutex_unlock( &(m_pIOBufferContext->lock) ); } IOBufferReader::~IOBufferReader() { }
#ifndef UTILS_HPP_ #define UTILS_HPP_ std::unique_ptr<std::string> get_file_contents(const char *filename); std::unique_ptr<std::string> get_gl_error_str(const char *function_name); #endif // UTILS_HPP_
#include <iostream> #include <queue> using namespace std; int w, h; int matrix[51][51]; bool visited[51][51] = { false, }; queue<pair<int, int>> q; int ans; /* 시계방향 회전 */ const int dir_i[8] = {-1, -1, 0, 1, 1, 1, 0, -1}; const int dir_j[8] = {0, 1, 1, 1, 0, -1, -1, -1}; int main() { ios_base::sync_with_stdio(false); cin.tie(0); while (true) { cin >> w >> h; if (w == 0 && h == 0) break; ans = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { cin >> matrix[i][j]; visited[i][j] = false; } } for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { if (!visited[i][j] && matrix[i][j] == 1) { ans++; q.push(make_pair(i, j)); visited[i][j] = true; while (!q.empty()) { pair<int, int> curPoint = q.front(); q.pop(); for (int dir = 0; dir < 8; dir++) { int next_i = curPoint.first + dir_i[dir]; int next_j = curPoint.second + dir_j[dir]; if(next_i < 0 || next_i >= h || next_j < 0 || next_j >= w) continue; if (!visited[next_i][next_j] && matrix[next_i][next_j] == 1) { visited[next_i][next_j] = true; q.push(make_pair(next_i, next_j)); } } } } } } cout << ans << '\n'; } return 0; }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #include <boost/algorithm/string/trim.hpp> #include <fwTools/dateAndTime.hpp> #include <fwTools/fromIsoExtendedString.hpp> #include <gdcmDirectory.h> #include <gdcmScanner.h> #include <gdcmAttribute.h> #include "gdcmIO/reader/DicomPatientReader.hpp" #include "gdcmIO/reader/DicomStudyReader.hpp" #include "gdcmIO/helper/GdcmHelper.hpp" namespace gdcmIO { namespace reader { //------------------------------------------------------------------------------ DicomPatientReader::DicomPatientReader() { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ DicomPatientReader::~DicomPatientReader() { SLM_TRACE_FUNC(); } //------------------------------------------------------------------------------ void DicomPatientReader::readPatient() { SLM_TRACE_FUNC(); // List of tag use in this method // const ::gdcm::Tag pNameTag(0x0010,0x0010); // Patient's name // const ::gdcm::Tag pIdTag(0x0010,0x0020); // Patient's ID // const ::gdcm::Tag pBdTag(0x0010,0x0030); // Patient's birth date // const ::gdcm::Tag pSexTag(0x0010,0x0040); // Patient's sex ::fwData::Patient::sptr patient = this->getConcreteObject(); const ::gdcm::DataSet & gDsRoot = this->getDataSet(); // Patient's name & first name { // Patient's Name std::string dicomName = ::fwTools::toStringWithoutAccent( helper::GdcmData::getTagValue<0x0010,0x0010>(gDsRoot) ); std::string name = "", firstname = ""; std::string::size_type sizeBase = std::string::npos; std::string::size_type sizeIndex = dicomName.find('^'); // name and first name are separated by '^' if (sizeIndex == sizeBase) {// If no separator name = dicomName; firstname = ""; assert( name.length() == dicomName.length() ); } else { name = dicomName.substr(0, sizeIndex); firstname = dicomName.substr(sizeIndex+1, dicomName.size()); assert( name.length() + firstname.length() + 1 == dicomName.length() ); } patient->setFirstname(firstname); patient->setName(name); OSLM_TRACE("Patient's name & first name : "<<name<<" "<<firstname); } // Patient's ID std::string patientID = helper::GdcmData::getTagValue<0x0010,0x0020>(gDsRoot); ::boost::algorithm::trim(patientID); // Delete binary space padding patient->setIDDicom( ::fwTools::toStringWithoutAccent(patientID) ); OSLM_TRACE("Patient's ID : "<<patient->getIDDicom()); // Patient's birth date patient->setBirthdate(::fwTools::strToBoostDateAndTime( helper::GdcmData::getTagValue<0x0010,0x0030>(gDsRoot) ) ); OSLM_TRACE("Patient's birth date : "<<patient->getBirthdate()); // Patient's sex patient->setIsMale( (helper::GdcmData::getTagValue<0x0010,0x0040>(gDsRoot)[0] == 'F')?false:true); OSLM_TRACE("Patient is male : "<<patient->getIsMale()); } //------------------------------------------------------------------------------ void DicomPatientReader::read() throw(::fwTools::Failed) { SLM_TRACE_FUNC(); ::fwData::Patient::sptr patient = this->getConcreteObject(); SLM_ASSERT("::fwData::Patient not set", patient); //***** Get all file names *****// std::vector< std::string > patientFiles = this->getFileNames(); // files which contain a common patient OSLM_TRACE("Number of files for a patient : " << patientFiles.size()); //***** Get group of file names for each study *****// const ::gdcm::Tag gTagSUID(0x0020,0x000d); // Study UID gdcm::Scanner gScanner; gScanner.AddTag(gTagSUID); // Scan patient files if( !gScanner.Scan( patientFiles ) ) { throw ::fwTools::Failed("No study found"); } ::gdcm::Directory::FilenamesType keys = gScanner.GetKeys(); ::gdcm::Directory::FilenamesType::const_iterator it = keys.begin(); ::gdcm::Directory::FilenamesType::const_iterator itEnd = keys.end(); // Create a map to associate each study with its files. std::map< std::string, std::vector< std::string > > studyMap; // Key : studyUID ; Value : filenames found for(; it != itEnd; ++it) { const char * filename = it->c_str(); const char * studyUID = gScanner.GetValue(filename, gTagSUID); if (studyUID != 0) { studyMap[studyUID].push_back( filename ); } else { OSLM_ERROR ( "No study UID found in : " << filename ); } } //***** Read and add each study (and so series, ...) *****// DicomStudyReader studyReader; std::map< std::string, std::vector< std::string > >::iterator itMap = studyMap.begin(); std::map< std::string, std::vector< std::string > >::iterator itMapEnd = studyMap.end(); while (itMap != itMapEnd) { OSLM_TRACE ( "Study map key : " << itMap->first ); if ( itMap->second.size() > 0 ) { OSLM_TRACE ( "First study map value : " << *(itMap->second.begin()) ); studyReader.setFileNames(itMap->second); ::fwData::Study::NewSptr study; studyReader.setObject(study); try { // Read one study studyReader.read(); // Add a complete study patient->addStudy(study); } catch (::fwTools::Failed & e) { OSLM_ERROR ("Read error with study : " << itMap->first); // Study skipped } } itMap++; } if(patient->getNumberOfStudies() == 0) throw ::fwTools::Failed("Patient has no study"); //***** Read patient *****// this->setReader( studyReader.getReader() ); // Get reader instantiated by DicomImageReader this->readPatient(); } } // namespace reader } // namespace gdcmIO
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2002 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef XSLT_SUPPORT #include "modules/xslt/src/xslt_namespacealias.h" #include "modules/xslt/src/xslt_parser.h" #include "modules/util/str.h" #include "modules/xmlutils/xmlutils.h" XSLT_NamespaceAlias::XSLT_NamespaceAlias (XMLVersion xmlversion) : stylesheet_prefix (0), result_prefix (0), xmlversion (xmlversion) { } XSLT_NamespaceAlias::~XSLT_NamespaceAlias () { OP_DELETEA (stylesheet_prefix); OP_DELETEA (result_prefix); } /* virtual */ XSLT_Element * XSLT_NamespaceAlias::StartElementL (XSLT_StylesheetParserImpl *parser, XSLT_ElementType type, const XMLCompleteNameN &name, BOOL &ignore_element) { parser->SignalErrorL ("unexpected element in xsl:namespace-alias"); ignore_element = TRUE; return this; } /* virtual */ BOOL XSLT_NamespaceAlias::EndElementL (XSLT_StylesheetParserImpl *parser) { return TRUE; // delete me } static void XSLT_SetPrefix (uni_char *&prefix, XSLT_StylesheetParserImpl *parser, XMLVersion xmlversion, const uni_char *value, unsigned value_length) { if (!XSLT_CompareStrings (value, value_length, "#default") && !XMLUtils::IsValidNCName (xmlversion, value, value_length)) parser->SignalErrorL ("invalid prefix in xsl:namespace-alias"); else LEAVE_IF_ERROR (UniSetStrN (prefix, value, value_length)); } /* virtual */ void XSLT_NamespaceAlias::AddAttributeL (XSLT_StylesheetParserImpl *parser, XSLT_AttributeType type, const XMLCompleteNameN &name, const uni_char *value, unsigned value_length) { switch (type) { case XSLTA_STYLESHEET_PREFIX: XSLT_SetPrefix (stylesheet_prefix, parser, xmlversion, value, value_length); break; case XSLTA_RESULT_PREFIX: XSLT_SetPrefix (result_prefix, parser, xmlversion, value, value_length); break; case XSLTA_NO_MORE_ATTRIBUTES: if (!stylesheet_prefix) parser->SignalErrorL ("xsl:namespace-alias missing required stylesheet-prefix attribute"); else if (!result_prefix) parser->SignalErrorL ("xsl:namespace-alias missing required result-prefix attribute"); else parser->AddNamespaceAliasL (stylesheet_prefix, result_prefix); break; case XSLTA_OTHER: break; default: XSLT_Element::AddAttributeL (parser, type, name, value, value_length); } } #endif // XSLT_SUPPORT
#include "mainview.h" #include "ui_mainview.h" MainView::MainView(QWidget *parent) : QDialog(parent), _ui(new Ui::MainView) { _ui->setupUi(this); // Setup Hand Recongition Class _detector = new HandDetector(); // Setup Mouse Controller Class _mouse = new MouseController(); // Setup child dialogs/windows _setting_dialog = new SettingDialog(this); _monitor_dialog = new MonitorDialog(this); _error_message_box = new QMessageBox(this); // Build connections between detector and dialogs connect(_setting_dialog, SIGNAL(resetSetting()), this, SLOT(makeDefaultSetting())); connect(_setting_dialog, SIGNAL(changeColorUpperBound(int,int, int)), _detector, SLOT(setSkinColorUpperBound(int,int,int))); connect(_setting_dialog, SIGNAL(changeColorLowerBound(int,int, int)), _detector, SLOT(setSkinColorLowerBound(int,int,int))); connect(_setting_dialog, SIGNAL(changeROI(int,int, int, int)), this, SLOT(setROI(int,int,int,int))); connect(_setting_dialog, SIGNAL(changeDetectionArea(int)), _detector, SLOT(setDetectionArea(int))); connect(_setting_dialog, SIGNAL(changeActionInterval(int)), _mouse, SLOT(setActionInterval(int))); connect(_setting_dialog, SIGNAL(changeSamplingFPS(int)), this, SLOT(setCameraFPS(int))); connect(_setting_dialog, SIGNAL(changeSensitivity(int)), this, SLOT(setActionSensitivity(int))); connect(_mouse, SIGNAL(mouseReleased()), this, SLOT(infoMouseReleased())); // Load default setting makeDefaultSetting(); // Setup Camera _camera_capture_timer = new QTimer(); #ifndef USE_QCAMERA _camera = new VideoCapture(); connect(_camera_capture_timer, SIGNAL(timeout()), this, SLOT(imageCapture())); #else _camera = new QCamera; _camera_capture = new QCameraImageCapture(_camera); _camera_viewfinder = new QCameraViewfinder(this); _camera->setViewfinder(_camera_viewfinder); _camera_viewfinder->setAspectRatioMode(Qt::KeepAspectRatio); QImageEncoderSettings image_settings; image_settings.setResolution(_ui->lblVideo->width(), _ui->lblVideo->height()); _camera_capture->setEncodingSettings(image_settings); _camera_capture->setBufferFormat(QVideoFrame::Format_ARGB32); // Setup Signal Triggers for Camera connect(_camera_capture_timer, SIGNAL(timeout()), this, SLOT(imageCapture())); connect(_camera_capture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(processFrame(int, QImage))); connect(_camera_capture, SIGNAL(error(int,QCameraImageCapture::Error,QString)), this, SLOT(processCameraCaptureError(int,QCameraImageCapture::Error,QString))); connect(_camera, SIGNAL(error(QCamera::Error)), this, SLOT(processCameraError(QCamera::Error))); #endif } MainView::~MainView() { delete _detector; delete _mouse; #ifndef USE_QCAMERA delete _camera; #else delete _camera; delete _camera_capture; delete _camera_viewfinder; #endif delete _camera_capture_timer; delete _error_message_box; delete _setting_dialog; delete _monitor_dialog; delete _ui; } void MainView::makeDefaultSetting() { _setting_dialog->setMinH(DEFAULT_SKIN_COLOR_MIN_H); _setting_dialog->setMinS(DEFAULT_SKIN_COLOR_MIN_S); _setting_dialog->setMinV(DEFAULT_SKIN_COLOR_MIN_V); _setting_dialog->setMaxH(DEFAULT_SKIN_COLOR_MAX_H); _setting_dialog->setMaxS(DEFAULT_SKIN_COLOR_MAX_S); _setting_dialog->setMaxV(DEFAULT_SKIN_COLOR_MAX_V); _setting_dialog->setDetectionArea(DEFAULT_DETECTION_AREA); _setting_dialog->setSensitivity(DEFAULT_MOUSE_SENSITIVITY*1000/DEFAULT_CAMERA_FPS); _setting_dialog->setSamplingFPS(DEFAULT_CAMERA_FPS); _setting_dialog->setActionInterval(DEFAULT_MOUSE_ACTION_INTERVAL); _setting_dialog->setMinROIHorizon(48); _setting_dialog->setMaxROIHorizon(98); _setting_dialog->setMinROIVertical(2); _setting_dialog->setMaxROIVertical(96); } void MainView::setCameraFPS(const int & fps) { _camera_FPS = fps; setActionSensitivity(_setting_dialog->getSensitivity()); if (_camera_capture_timer != nullptr && _camera_capture_timer->isActive()) _camera_capture_timer->start(_camera_FPS); } void MainView::setActionSensitivity(const int & sensitivity_in_ms) { _mouse->setActionSensitivity(sensitivity_in_ms*_camera_FPS/1000); } void MainView::setROI(const int & start_x_percent, const int & start_y_percent, const int & end_x_percent, const int & end_y_percent) { // ROI should at least be 9x9 in order to avoid errors caused by morphologyEx _ROI = Rect(_ui->lblVideo->width() * start_x_percent/100, _ui->lblVideo->height() * start_y_percent/100, _ui->lblVideo->width() * (end_x_percent-start_x_percent)/100, _ui->lblVideo->height() * (end_y_percent-start_y_percent)/100); if (_ROI.width < 9) { _ROI.width = 9; if (_ROI.x + _ROI.width > _ui->lblVideo->width()) _ROI.x = _ui->lblVideo->width() - _ROI.width; } if (_ROI.height < 9) { _ROI.height = 9; if (_ROI.y + _ROI.height > _ui->lblVideo->height()) _ROI.y = _ui->lblVideo->height() - _ROI.height; } _detector->setROI(_ROI); } void MainView::processFrame(const Mat& captured_frame) { if (_detector->detect(captured_frame)) { auto cursor_pos = _mouse->estimateCursorPos(_detector->getTrackedPoint()); circle(_detector->getOriginalFrame()(_ROI), _detector->getTrackedPoint(), 6, _detector->ColorRed, -1); circle(_detector->getOriginalFrame()(_ROI), cursor_pos, 6, _detector->ColorBlue, 2); if (_is_tracking == true) { cursor_pos.x = static_cast<float>(cursor_pos.x-50)/(_ROI.width-100)*_qt_widget.geometry().width(); cursor_pos.y = static_cast<float>(cursor_pos.y-100)/(_ROI.height-200)*_qt_widget.geometry().height(); bool has_released = _mouse->hasReleased(); auto result = _mouse->makeAction(cursor_pos.x, cursor_pos.y, _detector->getFingerPoints()); if (result == MOUSE_ACTION_SINGLE_CLICK) _ui->txtPanel->append("Single Click"); else if (result == MOUSE_ACTION_DOUBLE_CLICK) _ui->txtPanel->append("Double Click"); else if (result == MOUSE_ACTION_RIGHT_CLICK) _ui->txtPanel->append("Right Click"); else if (result == MOUSE_ACTION_DRAG && has_released == true) _ui->txtPanel->append("Drag Begining"); } } updateTrackingDialog(); _ui->lblVideo->setPixmap( QtCVImageConverter::CvMat2QPixmap( _detector->getOriginalFrame() ).scaled( QSize(_ui->lblVideo->width(), _ui->lblVideo->height()), Qt::KeepAspectRatio) ); } void MainView::infoMouseReleased() { _ui->txtPanel->append("Drag Released"); } void MainView::processFrame(const int &, const QImage & captured_image) { processFrame(QtCVImageConverter::QImage2CvMat(captured_image)); } void MainView::updateTrackingDialog() { if (_monitor_dialog->isVisible()) _monitor_dialog->updateWindow(QtCVImageConverter::CvMat2QPixmap( _detector->getInterestedFrame() ), QtCVImageConverter::CvMat2QPixmap( _detector->getFilteredFrame() ), QtCVImageConverter::CvMat2QPixmap( _detector->getContourFrame() ), QtCVImageConverter::CvMat2QPixmap( _detector->getConvexityFrame() ) ); } void MainView::on_btnSetting_clicked() { _setting_dialog->show(); _setting_dialog->raise(); _setting_dialog->activateWindow(); } void MainView::on_btnMonitor_clicked() { _monitor_dialog->show(); _monitor_dialog->raise(); _setting_dialog->activateWindow(); } void MainView::on_btnStart_clicked() { if (_camera_capture_timer->isActive() == false) { #ifndef USE_QCAMERA _camera->open(0); if (!_camera->isOpened()) { _ui->txtPanel->append(QString("Error: Camera cannot be accessed.")); showCameraErrorMessage(); return; } #else try { _camera->start(); } catch (...) { _ui->txtPanel->append(QString("Error: Camera cannot be accessed.")); showCameraErrorMessage(); return; } #endif _camera_capture_timer->start(1000/_camera_FPS); _ui->btnStart->setText("Track"); _is_tracking = false; } else if (_is_tracking == true) { _is_tracking = false; _ui->btnStart->setText("Track"); } else { _is_tracking = true; _ui->btnStart->setText("Pause"); } } void MainView::imageCapture() { #ifndef USE_QCAMERA if (_camera->isOpened()) { Mat captured_frame; _camera->read(captured_frame); cv::resize(captured_frame, captured_frame, Size(captured_frame.cols*_ui->lblVideo->height()/captured_frame.rows, _ui->lblVideo->height()) ); processFrame(captured_frame(Rect((captured_frame.cols - _ui->lblVideo->width())/2, 0, _ui->lblVideo->width(), _ui->lblVideo->height()))); } #else if (_camera_capture->isReadyForCapture()) { _camera_capture->capture(); } #endif else { _ui->txtPanel->append("Failed to Capture Image."); qWarning() << "Failed to Capture Image."; showCameraErrorMessage(); } } #ifdef USE_QCAMERA void MainView::processCameraCaptureError(const int &, const QCameraImageCapture::Error &, const QString & error_string) { _ui->txtPanel->append("Failed to Capture Image."); qWarning() << "Failed to Capture Image."; _ui->txtPanel->append(error_string); showCameraErrorMessage(); } void MainView::processCameraError(const QCamera::Error & ) { _ui->txtPanel->append("Failed to Capture Image."); qWarning() << "Failed to Capture Image."; _ui->txtPanel->append(_camera->errorString()); showCameraErrorMessage(); } #endif void MainView::showCameraErrorMessage() { _camera_capture_timer->stop(); _ui->btnStart->setText("Start"); _error_message_box->warning(this, QString("Error"), QString("Failed to load camera.")); qWarning() << "Failed to load camera."; _error_message_box->show(); _error_message_box->raise(); } void MainView::on_btnSetBackground_clicked() { auto input_frame = _detector->getOriginalFrame(); if (!input_frame.empty()) { _detector->setBackgroundImage(input_frame(_ROI)); _ui->lblBackground->setPixmap( QtCVImageConverter::CvMat2QPixmap( input_frame(_ROI) ).scaled( QSize(_ui->lblBackground->width(), _ui->lblBackground->height()), Qt::KeepAspectRatio) ); } }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); int D,I; while( kase-- ){ scanf("%d %d",&D,&I); int ans = 1<<(D-1); I -= 1; int k = D-2; while( I ){ ans |= (I&1)<<(k--); I >>= 1; } printf("%d\n",ans); } return 0; }
 #pragma once #include <string> #include <vector> class RedisAccess; class MySqlAgent; namespace MySqlLogic { struct CardRoomPlayerInfo { int uid; // 玩家id int index; //uid索引 std::string name; // 玩家昵称 int score; // 玩家输赢金币数量,>0表示赢,<0表示输 }; /// </summary> /// 添加房间历史记录,创建房间时调用! RedisLogic::addPassportRoomInfo调用后应该即刻调用 /// roomowner 房间创建者id /// tid 桌子id /// gameid 游戏id /// totalround 最大局数 /// createtime 创建时间戳 /// playercount 每局玩家数量,如郑州麻将人数为4,斗地主为3,等等 /// </summary> bool addCardRoomHistory(MySqlAgent *mysql, int roomowner, int tid, int gameid, int totalround, int createtime, int cost, int playercount); /// </summary> /// 更新房卡历史数据,房间解散前调用,需保证在RedisLogic::clearPassportRoomInfo前调用,否则会查询不到创建时间 /// roomowner 房间创建者id /// tid 桌子id /// gameid 游戏id /// history 历史记录 /// </summary> bool updateCardRoomHistory(MySqlAgent *mysql, int roomowner, int tid, int gameid, int createtime, int finishround, int status, const std::vector<CardRoomPlayerInfo> &history); /// </summary> /// 添加房间每局历史记录 /// roomowner 房间创建者id /// tid 桌子id /// gameid 游戏id /// totalround 最大局数 /// starttime 开始时间戳 /// endtime 结束时间戳 /// playercount 每局玩家数量,如郑州麻将人数为4,斗地主为3,等等 /// </summary> bool addCardRoomRecord(MySqlAgent *mysql, int roomowner, int tid, int gameid, int currentround, int totalround, int createtime, int starttime, int endtime, int status, int playercount, const std::vector<CardRoomPlayerInfo> &history, const std::string& playinfo); /** * 添加消费房卡记录 * @param mysql * @param roomowner * @param tid * @param gameid * @return */ bool addRoomCardChargeLog(MySqlAgent *mysql, int roomowner, int tid, int gameid, int pid, int64_t winMoney, int64_t currentMoney); }
#include <algorithm> #include <cctype> #include <iostream> #include <pqxx/pqxx> #include <string> #include "util.h" using namespace pqxx; int main(int argc, char* argv[]) { if(argc != 2) { std::cerr << "Usage: " << argv[0] << " SEARCH_TERM" << std::endl; } const std::string searchTerm {argv[1]}; std::string lowerSearchTerm; lowerSearchTerm.resize(searchTerm.length()); std::transform(searchTerm.begin(), searchTerm.end(), lowerSearchTerm.begin(), ::tolower); connection conn; // defaults to dbname=<username> read_transaction txn(conn, "Select transaction"); result r = txn.exec("SELECT * FROM users WHERE " "lower(first) LIKE '%" + lowerSearchTerm + "%' OR " "lower(last) LIKE '%" + lowerSearchTerm + "%'" ); for(auto row : r) { std::cout << row["first"] << "\t" << row["last"] << std::endl; } return 0; }
//Normalize main function int normalize_main(int argc, char *argv[]) { //Display help bool show_help = false; //Has parameters bool cover_input_has = false, cover_output_has = false, algorithm_has = false; //String parameters string cover_input_file, cover_output_file, algorithm; //Cover num int cover_num = 0; //Check the number of arguments if(argc == 1){ show_help = true; } //Check for show the help if(show_help == true){ return normalize_help(); } //Read all the arguments for(int i = 1; i < argc; i++) { //Get the argument value string arg_value = argv[i]; //Get the argument length int arg_length = (int) strlen(argv[i]); //Check the algorithm option if(check_opt("--a", 3, arg_value, arg_length) == true) { //Check the count if(argc <= i + 1){ continue; } //Set the algorithm algorithm_has = true; //Save the algorithm name algorithm = argv[i + 1]; //Increment the i counter i = i + 1; } //Check the cover input option else if(check_opt("--cover", 7, arg_value, arg_length) == true) { //Check the count if(argc <= i + 1){ continue; } //Set input cover cover_input_has = true; //Save the input cover file cover_input_file = argv[i + 1]; //Increment the i counter i = i + 1; } //Check the cover output option else if(check_opt("--out", 5, arg_value, arg_length) == true) { //Check the count if(argc <= i + 1){ continue; } //Set output cover cover_output_has = true; //Save the output cover file cover_output_file = argv[i + 1]; //Increment the i counter i = i + 1; } //Unknown option else { //Display unknow parameter cerr << "ERROR: unknown parameter " << arg_value << endl; show_help = true; } } //Check for no input cover file if(cover_input_has == false){ cerr << "ERROR: no input cover file provided" << endl; show_help = true; } //Check for no output cover file if(cover_output_has == false){ cerr << "ERROR: no output cover file provided" << endl; show_help = true; } //Check for no algorithm if(algorithm_has == false){ algorithm = "mean"; } //Check for display the help if(show_help == true){ return normalize_help(); } //Initialize the new coverage list CoverList l = NULL; //Count the number of coverages columns cover_num = cover_count(cover_input_file); //Initialize the list cover_read(cover_input_file, l, cover_num); //Check the normalize algorithm if(algorithm == "mean") { //Apply the mean algorithm normalize_mean(l, cover_num); } //Save the cover file cover_save(cover_output_file, l, cover_num); //Delete the cover list cover_delete(l); //Exit return 0; }
#ifndef INC_3PC_RANDOM_H #define INC_3PC_RANDOM_H #include <random> class Random { private: std::mt19937 eng; public: Random(); explicit Random(unsigned seed); template<typename T> T randomBetween(T begin, T end) { static_assert(std::is_arithmetic<T>::value, "Arguments must me integer or floating-point types"); if (std::is_integral<T>::value) { std::uniform_int_distribution<T> range(begin, end); return range(eng); } else { std::uniform_int_distribution<T> range(begin, end); return range(eng); } } }; #endif //INC_3PC_RANDOM_H
/* #include <gecode/driver.hh> #include <gecode/int.hh> #include <gecode/search.hh> #include <gecode/gist.hh> */ #include "gecode/gecode/driver.hh" #include "gecode/gecode/int.hh" #include "gecode/gecode/search.hh" #include "gecode/gecode/gist.hh" using namespace Gecode; // steps to compile // add to path: export LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib // compile: g++ -std=gnu++11 -I/usr/local/include -c money.cpp // link: g++ -o money -L/usr/local/lib money.o -lgecodesearch -lgecodeint -lgecodekernel -lgecodesupport -lgecodegist class SPLegalizer : public Space { protected: IntVarArray l; int definedVariables; IntVar defVar; public: //default constructor SPLegalizer(int countTickets, int countBills, int ticketsValues[] , int billsValues[] ) : l(*this, countTickets + countBills, 0, 1), defVar(*this, countTickets + countBills, countTickets + countBills) { this->definedVariables = defVar.val(); IntVar variables [this->definedVariables] = {}; for (int i = 0; i < this->definedVariables; i++) { IntVar var(l[i]); variables[i] = var; } IntArgs c(this->definedVariables); IntArgs v(this->definedVariables); IntVarArgs x(this->definedVariables); //setup tickets expressions for (int i = 0; i < countTickets; i++) { c[i] = ticketsValues[i]; x[i] = variables[i]; v[i] = 1; } //setup bills expressions for (int i = 0; i < countBills; i++) { c[countTickets + i] = -1 * billsValues[i]; x[countTickets + i] = variables[countTickets + i]; v[countTickets + i] = 1; } //the sum of tickets & bills must be greater or equal than zero linear(*this, c, x, IRT_GQ, 0); //must be legalized at least one bill & one ticket linear(*this, v, x, IRT_GQ, 2); branch(*this, l, INT_VAR_SIZE_MIN(), INT_VAL_MIN()); } // Copy Constructor SPLegalizer(SPLegalizer& s) : Space(s) { l.update(*this, s.l); defVar.update(*this, s.defVar); } virtual Space* copy(void) { return new SPLegalizer(*this); } void print(void) const { std::cout << l << std::endl; } void print(std::ostream& os) const { os << l << std::endl; } // constrain function virtual void constrain(const Space& _spaceBranch) { const SPLegalizer& branch = static_cast<const SPLegalizer&>(_spaceBranch); int countVariables = branch.defVar.val(); IntVar variables [countVariables] = {}; IntVar branchVariables [countVariables] = {}; //setup variables & branch variables for (int i = 0; i < countVariables; i++) { IntVar var(l[i]); IntVar branch_var(branch.l[i]); variables[i] = var; branchVariables[i] = branch_var; } int legalizedDocuments = 0; for (int i = 0; i < countVariables; i++) { legalizedDocuments = legalizedDocuments + branchVariables[i].val(); } IntArgs c(countVariables); IntVarArgs x(countVariables); for (int i = 0; i < countVariables; i++) { c[i] = 1; x[i] = variables[i]; } linear(*this, c, x, IRT_GR, legalizedDocuments); } }; // main function int main(int argc, char* argv[]) { if (argc < 11) { std::cerr << "Syntax : ./money --mode < 0 => console, 1 => GIST> --tickets <countOfTickets> --ticketList <list_of_tickets> --bills <countOfTickets> --billList <list_of_bills>" << std::endl; return 0; } int countTickets = atoi(argv[4]); int countBills = atoi(argv[8]); int ticketsValues [countTickets] = {}; //{ 3, 6, 2 }; int billsValues [countBills] = {};//{5, 1, 7, 3}; char* pch; //parsing tickets pch = strtok (argv[6]," ,.-"); int i = 0; while (pch != NULL) { ticketsValues[i] = atoi(pch); i++; pch = strtok (NULL, " ,.-"); } //parsing bills pch = strtok (argv[10]," ,.-"); i = 0; while (pch != NULL) { billsValues[i] = atoi(pch); i++; pch = strtok (NULL, " ,.-"); } SPLegalizer* m = new SPLegalizer(countTickets, countBills, ticketsValues, billsValues); switch(atoi(argv[2])) { case 1: {// GIST Gist::Print<SPLegalizer> p("Print solution"); Gist::Options o; o.inspect.click(&p); Gist::bab(m,o); delete m; } break; case 0: { // CONSOLE BAB<SPLegalizer> e(m); delete m; while (SPLegalizer* s = e.next()) { s->print(); delete s; } } break; default: { BAB<SPLegalizer> e(m); delete m; while (SPLegalizer* s = e.next()) { s->print(); delete s; } } } return 0; }
//Created by: Mark Marsala, Marshall Farris, and Johnathon Franco Sosa //Date: 5/4/2021 //Reading and writing for an 8 bit stereo wav file //Even numbers are left buffer, odd numbers are right buffer #include <string> #include <fstream> #include <iostream> #include "stereo8.h" using namespace std; Stereo8::Stereo8(string newFile) { fileName = newFile; } void Stereo8::readFile() { std::ifstream file(fileName,std::ios::binary | std::ios::in); if(file.is_open()) { file.read((char*)&waveHeader, sizeof(wav_header)); buffer = new unsigned char[waveHeader.data_bytes]; file.read((char*)buffer, waveHeader.data_bytes); file.close(); cout << "Reading 8 bit stereo file" << endl; } } unsigned char* Stereo8::getBuffer() { return buffer; } void Stereo8::writeFile(const std::string &outFileName) { std::ofstream outFile(outFileName, std::ios::out | std::ios::binary); outFile.write((char*)&waveHeader,sizeof(wav_header)); outFile.write((char*)buffer, waveHeader.data_bytes); outFile.close(); cout << "Writing 8 bit stereo file" << endl; } Stereo8::~Stereo8() { if(buffer != NULL) { delete[] buffer; } } int Stereo8::getBufferSize() const { return waveHeader.data_bytes; } void Stereo8::allocateBuffer() { int size = (getBufferSize() / 2); leftBuffer = new unsigned char[size]; rightBuffer = new unsigned char[size]; for(int i = 0; i < size; i++) { leftBuffer[i] = buffer[2*i]; rightBuffer[i] = buffer[(2*i)+1]; } } void Stereo8::reallocateBuffer() { int size = (getBufferSize() / 2); for(int i = 0; i < size; i++) { buffer[2*i] = leftBuffer[i]; buffer[(2*i)+1] = rightBuffer[i]; } } unsigned char* Stereo8::getLeftBuffer() { return leftBuffer; } unsigned char* Stereo8::getRightBuffer() { return rightBuffer; }
#include <iostream> #include <gromacs/trajectoryanalysis.h> #include "assembly.h" int main(int argc, char *argv[]) { return gmx::TrajectoryAnalysisCommandLineRunner::runAsMain<assembly>(argc,argv); }
#include "mo_led.h" #include <stdio.h> using namespace std; #define MODE_HEARTBEAT 1 //!< heartbeat operation #define MODE_GPIO 2 //!< gpio operation #define MODE_TIMER 3 //!< timer operation #define MODE_NONE 4 //!< none operation #define BLINKY_TIME 500 /*500ms*/ #define RUNNING_LED_NAME "led-run" #define WARNING_LED_NAME "led-warning" #define REMOTE_LED_NAME "led-remote" #define GPIO_4G_STA 89 /*PC25*/ #define GPIO_MODE_OUTPUT 1 #define LED_RUN_NORMAL 0 #define LED_RUN_BLUETH 1 #ifdef __cplusplus extern "C" { // libled.aº¯Êý int gpio_set_mode(char* dev_name, int mode); int gpio_set_timer_delay(char* dev_name, int delay_on, int delay_off); int gpio_set_onoff(char* dev_name, int on_off); int gpio_register(size_t gpio, int mode); int gpio_unregister(size_t gpio); int gpio_set_value(size_t gpio, int value); int gpio_get_value(size_t gpio); } #endif Mo_Led::Mo_Led() { gpio_register(GPIO_4G_STA, GPIO_MODE_OUTPUT); // SetRunningLed(true); // SetAlarmLed(true); // SetCommLed(true); m_runState = LED_RUN_NORMAL; } Mo_Led::~Mo_Led() { gpio_unregister(GPIO_4G_STA); } void Mo_Led::setEndLight() { SetRunningLed(true); SetAlarmLed(false); SetCommLed(false); } void Mo_Led::setOpenAll() { SetRunningLed(true); SetAlarmLed(true); SetCommLed(true); } void Mo_Led::setCorrectLed() { SetRunningLed(true); SetAlarmLed(false); SetCommLed(true); } void Mo_Led::setErrorLed() { SetRunningLed(false); SetAlarmLed(true); SetCommLed(false); } void Mo_Led::setAllBlack() { SetRunningLed(false); SetAlarmLed(false); SetCommLed(false); } void Mo_Led::SetRunningLed(bool on) { char ledName[50] = { 0 }; sprintf(ledName, "%s", RUNNING_LED_NAME); gpio_set_mode(ledName, MODE_GPIO); gpio_set_onoff(ledName, on ? 1 : 0); } void Mo_Led::SetAlarmLed(bool on) { char ledName[50] = { 0 }; sprintf(ledName, "%s", WARNING_LED_NAME); gpio_set_mode(ledName, MODE_GPIO); gpio_set_onoff(ledName, on ? 1 : 0); } void Mo_Led::SetCommLed(bool on) { gpio_set_value(GPIO_4G_STA, on ? 0 : 1); }
#pragma once #include <vector> class NameGenerator { public: NameGenerator(void); ~NameGenerator(void); std::vector<std::string> places; std::vector<std::string> descriptors; std::string name; int numPlaces; int numDescriptors; std::string GenerateNewName(); void ReadPlaces(char* placeFile); void ReadDescriptions(char* descFile); };
// Created on: 1992-10-21 // Created by: Christian CAILLET // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESData_SingleParentEntity_HeaderFile #define _IGESData_SingleParentEntity_HeaderFile #include <Standard.hxx> #include <IGESData_IGESEntity.hxx> #include <Standard_Integer.hxx> class IGESData_SingleParentEntity; DEFINE_STANDARD_HANDLE(IGESData_SingleParentEntity, IGESData_IGESEntity) //! a SingleParentEntity is a kind of IGESEntity which can refer //! to a (Single) Parent, from Associativities list of an Entity //! a effective SingleParent definition entity must inherit it class IGESData_SingleParentEntity : public IGESData_IGESEntity { public: //! Returns the parent designated by the Entity, if only one ! Standard_EXPORT virtual Handle(IGESData_IGESEntity) SingleParent() const = 0; //! Returns the count of Entities designated as children Standard_EXPORT virtual Standard_Integer NbChildren() const = 0; //! Returns a Child given its rank Standard_EXPORT virtual Handle(IGESData_IGESEntity) Child (const Standard_Integer num) const = 0; DEFINE_STANDARD_RTTIEXT(IGESData_SingleParentEntity,IGESData_IGESEntity) protected: private: }; #endif // _IGESData_SingleParentEntity_HeaderFile
#include <iostream> #include <math.h> int main() { int maxValueOfChar = pow(2, sizeof(char) * 8.0) - 1; int minValueOfChar = (-1) * maxValueOfChar - 1; std::cout << "Max value of char: " << maxValueOfChar << std::endl << "Min value of char: " << minValueOfChar << std::endl; int maxValueOfInt = pow(2, sizeof(int) * 8.0 - 1) - 1; int minValueOfInt = (-1) * maxValueOfInt - 1; std::cout << "Max value of int: " << maxValueOfInt << std::endl << "Min value of int: " << minValueOfInt << std::endl; float maxValueOfFloat = pow(2, sizeof(float) * 8.0 - 1) - 1; float minValueOfFloat = (-1) * maxValueOfFloat - 1; std::cout << "Max value of float: " << maxValueOfFloat << std::endl << "Min value of float: " << minValueOfFloat << std::endl; double maxValueOfDouble = pow(2, sizeof(double) * 8.0 - 1) - 1; double minValueOfDouble = (-1) * maxValueOfDouble - 1; std::cout << "Max value of double: " << maxValueOfDouble << std::endl << "Min value of double: " << minValueOfDouble << std::endl; return 0; }
#pragma once #include <string> #include <utility> #include <vector> // Result = (word, distance) using result_t = std::pair<std::string, int>; class IDictionaryBase { public: // Reset the dictionary with this set of words virtual void init(const std::vector<std::string>& word_list) = 0; }; class IDictionary : public IDictionaryBase { public: IDictionary() = default; virtual result_t search(const std::string& w) const = 0; virtual void insert(const std::string& w) = 0; virtual void erase(const std::string& w) = 0; };
// vec_eigen_pair.cpp // Mike Lujan // July 2010 #include "vec_eigen_pair.h" #include "comm/comm_low.h" #include "io_kentucky.h" #include "io_eigensystem.h" #include <string> #include <stdio.h> #define print0 if( get_node_rank() == 0) printf namespace qcd { template<typename genvector> void read_single_vector(FILE* f, genvector& vec); template<typename genvector, typename genvector2> void read_vec_eigen_pair(const char *feigenvecs, const char *feigenvals, vec_eigen_pair<genvector>& eigen_pair, vec_eigen_pair<genvector2>& eigen_pair2) { int tot = eigen_pair.size + eigen_pair2.size; if(tot !=0) { FILE *fevecs = NULL; //read eigenvalues double_complex egv[tot]; reload_eigenvalues(egv, tot, 2, feigenvals); std::copy(egv , egv+eigen_pair.size, eigen_pair.eval); std::copy(egv+eigen_pair.size, egv+tot , eigen_pair2.eval); //read cpu vectors if(get_node_rank() == 0) fevecs = fopen(feigenvecs,"rb"); for(int i=0; i<eigen_pair.size; i++) read_single_vector(fevecs,*eigen_pair.evec[i]); for(int i=0; i<eigen_pair2.size; i++) read_single_vector(fevecs,*eigen_pair2.evec[i]); if(get_node_rank() == 0) fclose(fevecs); } else print0("\n\n THERE WERE NO EIGENVECTORS OR EIGNEVALUES READ\n\n"); } template<typename genvector> void read_vec_eigen_pair(const char *feigenvecs, const char *feigenvals, vec_eigen_pair<genvector>& eigen_pair) { if(eigen_pair.size !=0) { vec_eigen_pair<genvector> stub(0, *(eigen_pair.evec[0]->desc)); read_vec_eigen_pair(feigenvecs, feigenvals, eigen_pair, stub); } else print0("\n\n THERE WERE NO EIGENVECTORS OR EIGNEVALUES READ\n\n"); } template<typename genvector> vec_eigen_pair<genvector>::vec_eigen_pair(int size, lattice_desc& desc): size(size), eval(new double_complex[size]), evec(new genvector*[size]) { for(int i=0; i<size; ++i) evec[i] = new genvector(&desc); } template<typename genvector> vec_eigen_pair<genvector>::~vec_eigen_pair() { for(int i=0; i<size; ++i) delete evec[i]; delete [] evec; delete [] eval; } }
#pragma once template <typename T> class SingletonBase { protected: static T* instance; SingletonBase() {}; ~SingletonBase() {}; public: static T* GetSingleton(); void ReleaseSingleton(); }; template<typename T> T* SingletonBase<T>::instance = NULL; template<typename T> T* SingletonBase<T>::GetSingleton() { if (!instance) instance = new T; return instance; } template<typename T> void SingletonBase<T>::ReleaseSingleton() { if (instance) { delete instance; instance = 0; } }
# include <iostream> using namespace std; int main () { float a, b, c; cout << "Please enter 3 number: "; cin >> a; cin >> b; cin >> c; if(a < b && a < c) { cout << a << endl; } else if (a < b && c < a) { if (b < c) { cout << b << endl; } else { cout << c << endl; } } else if (b < a && a < c) { if (a < b) { cout << a << endl; } else { cout << b << endl; } } else if (c < a && c < b) { cout << c << endl; } cout << endl; system("pause"); return 0; } //======================================================== # include <iostream> # include <string> using namespace std; void payRollSystem(); int main() { cout << "This program compute The Payroll Interactively." << endl; payRollSystem(); system("pause"); return 0; } void payRollSystem(void) { int n; cout << "To begin, Enter The Number of Employees: "; cin >> n; for (int i = 0; i < n; i++) { string name; float hour, rate; double payRoll; cout << "Enter The Name, Hours and Rate for Employee" << i + 1 << ": "; cin >> name; cin >> hour; cin >> rate; payRoll = hour * rate; cout << name << " " << payRoll << endl; } }
#include<bits/stdc++.h> using namespace std; main() { long int i, sum=0, len, p, power, num1; char number[100]; while(gets(number)) { if(strcmp(number, "0")==0)break; len = strlen(number); p = len; //cout<<len; for(i=0; i<len; i++) { power = pow(2,p) - 1; num1 = (number[i]-'0'); sum += (power*num1); p = p-1; } cout<<sum<<endl; sum = 0; } return 0; }
#include<iostream> #include "../Shoikoth/Person.hpp" #include "../Shoikoth/Date.hpp" #include "Property.hpp" using namespace std; class SellingReport { protected: Date sellingDate; Property soldProperty; Vendor boughtFrom; Customer soldTo; double profit; public: };
#include "Consumables.h" Consumables::Consumables() { } Consumables::~Consumables() { } void Consumables::Init() { } void Consumables::Update(double dt) { } int Consumables::UseHealthPot(int HP) { HP += 50; return HP; } int Consumables::UseManaPot(int Mana) { Mana += 10; return Mana; } float Consumables::UseAtkBuffPot(int Attack) { Attack = (int)(Attack * 1.25f); return (float)Attack; } float Consumables::UseDefBuffPot(int Defence) { Defence = (int)(Defence * 1.25f); return (float)Defence; }
#include "OI.h" #include <frc/WPILib.h> #include <commands/BallCommandIn.h> #include <commands/BallCommandOut.h> OI::OI() { frc::Joystick yoke{0}; frc::Joystick xbox{1}; xboxRB.ToggleWhenPressed(new BallCommandIn); xboxLB.ToggleWhenPressed(new BallCommandOut); } double OI::XboxVertL() { return (xbox.GetRawAxis(1) * -1); } double OI::XboxHorzL() { return xbox.GetRawAxis(0); } double OI::XboxVertR() { return (xbox.GetRawAxis(5) * -1); } double OI::XboxHorzR() { return xbox.GetRawAxis(4); } double OI::YokeVert() { return (yoke.GetRawAxis(1) * -1); } double OI::YokeHorz() { return yoke.GetRawAxis(0); } double OI::YokeWheel() { return (yoke.GetRawAxis(2) * -1); } double OI::XboxLT() { return xbox.GetRawAxis(3); } double OI::XboxRT() { return xbox.GetRawAxis(2); }
#include "block_statement.h" #include "visitor.h" BlockStatement::BlockStatement(Block *_block) : block(_block) {} void BlockStatement::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } BlockStatement::~BlockStatement() { delete block; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: string multiply(string num1, string num2) { //简化版 int l1 = num1.size(); int l2 = num2.size(); string res(l1 + l2, '0'); for(int i=l1-1; i>=0; i--) { for(int j=l2-1; j>=0; j--) { int tmp = (res[i+j+1] - '0') + (num1[i] - '0')*(num2[j] - '0'); res[i+j+1] = tmp%10 + '0'; res[i+j] += tmp/10; } } for(int i = 0; i < l1+l2; i++){ if(res[i]!='0') return res.substr(i); } return "0"; } }; class Solution { public: string multiply(string num1, string num2) { //基本思想:暴力模拟竖式乘法计算过程,两重循环第一重循环读取num2中某个数与第二重循环读取num1所有数相乘这就是一层结果layer,然后将每一层结果加到res最后返回res的逆序 //layer为num2中某个数与num1所有数相乘结果也就是一层结果,将每一层结果加到res就是最后返回结果 string res, layer; //cur是num1中某个数字和num2某个数字相乘得到结果的个位数 char cur; //temp临时num1和num2某两个数字对应相乘结果,carry是结果的十位数也就是进位数 int i, j, carry, temp, k; //如果num1和num2中有一个是0,结果返回0 if (num1 == "0" || num2 == "0") return "0"; //第一重循环读取num2中某个数 for (i = num2.size() - 1; i >= 0; i--) { //每一层layer初始化为空 layer = ""; //根据num2中读取数所在的位数,layer添加相应个数的0 for (k = 0; k < num2.size() - 1 - i; k++) layer.push_back('0'); //进位数carry初始化为0 carry = 0; //第二重循环读取num1所有数与num2读取的数num2[i]相乘得到这一层结果layer for (j = num1.size() - 1; j >= 0; j--) { temp = (num2[i] - '0') * (num1[j] - '0') + carry; cur = temp % 10 + '0'; carry = temp / 10; layer.push_back(cur); } //如果num2[i]与num1所有数相乘后还有进位,加到layer后面 if (carry > 0) layer.push_back(carry + '0'); carry = 0; //然后将每一层结果layer加到res上 for (k = 0; k < res.size() && k < layer.size(); k++) { temp = (res[k] - '0') + (layer[k] - '0') + carry; res[k] = temp % 10 + '0'; carry = temp / 10; } //可能layer的长度大于res的长度,layer大于res长度的部分加到res后面 while (k < layer.size()) { temp = layer[k] - '0' + carry; res.push_back(temp % 10 + '0'); carry = temp / 10; k++; } //考虑可能最后还有进位 if (carry == 1) res.push_back('1'); } //最后返回res的逆序 reverse(res.begin(), res.end()); return res; } }; int main() { Solution solute; string nums1 = "23"; string nums2 = "112"; cout << solute.multiply(nums1, nums2) << endl; return 0; }
#pragma once #include "Ghost.h" class Blinky : public Ghost { public: bool directions[4]; Blinky(); void Update(); int RandomDirection(); void Move(int _velocity); void Animate(); void AnimatePowerUp(); void SetInitialPosition(int _x, int _y); void SetNewAnimation(int _animation); void SetNewAnimationPowerUp(int _animation); void Respawn(); void Draw(); ~Blinky(); };
#pragma once #include <vector> #include <gl/glew.h> struct VertexBufferElement { unsigned int type; unsigned int count; unsigned char normalized; static unsigned int GetSizeOfType(unsigned int type) { switch(type) { case GL_FLOAT: return 4; case GL_UNSIGNED_INT: return 4; case GL_UNSIGNED_BYTE: return 1; } return 0; } }; class VertexBufferLayout { public: VertexBufferLayout() : stride(0) {} ~VertexBufferLayout(); template<typename T> void Push(unsigned int count) { static_assert(false); } template<> void Push<float>(unsigned int count) { elements.push_back({GL_FLOAT,count,GL_FALSE}); stride += VertexBufferElement::GetSizeOfType(GL_FLOAT) * count; } template<> void Push<unsigned int>(unsigned int count) { elements.push_back({GL_UNSIGNED_INT,count , GL_FALSE }); stride += VertexBufferElement::GetSizeOfType(GL_UNSIGNED_INT) * count; } template<> void Push<unsigned char>(unsigned int count) { elements.push_back({GL_UNSIGNED_BYTE,count , GL_TRUE}); stride += VertexBufferElement::GetSizeOfType(GL_UNSIGNED_BYTE) * count; } inline unsigned int GetStride() const { return stride; } inline const std::vector<VertexBufferElement> GetElements() const { return elements; } private: std::vector<VertexBufferElement> elements; unsigned int stride; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-1999 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_LSEXCEPTION #define DOM_LSEXCEPTION #ifdef DOM3_LOAD class DOM_Object; class DOM_LSException { public: enum Code { PARSE_ERR = 81, SERIALIZE_ERR }; static void ConstructLSExceptionObjectL(ES_Object *object, DOM_Runtime *runtime); static int CallException(DOM_Object *object, Code code, ES_Value *value); }; #endif // DOM3_LOAD #endif // DOM_LSEXCEPTION
#ifndef ALGO2_LABO_CLASE5_ALGORITMOS_H #define ALGO2_LABO_CLASE5_ALGORITMOS_H #include <utility> #include <iterator> #include <vector> template<class Contenedor> typename Contenedor::value_type minimo(const Contenedor& c){ auto it2 = c.begin(); for(auto it = c.begin(); it != c.end(); it++){ if (*it < *it2) { it2 = it; } } return *it2; } template<class Contenedor> typename Contenedor::value_type promedio(const Contenedor& c) { typename Contenedor::value_type prom = 0; for(auto& y : c) { prom += y; } prom /= c.size(); return prom; } template<class Iterator> typename Iterator::value_type minimoIter(const Iterator& desde, const Iterator& hasta) { auto it2 = desde; for(auto it = desde; it != hasta; it++) { if (*it < *it2) { it2 = it; } } return *it2; } template<class Iterator> typename Iterator::value_type promedioIter(const Iterator& desde, const Iterator& hasta) { typename Iterator::value_type prom = 0; int size = 0; for(auto it = desde; it != hasta; it++) { prom += *it; size++; } prom /= size; return prom; } template<class Contenedor> void filtrar(Contenedor &c, const typename Contenedor::value_type& elem) { auto it = c.begin(); while(it !=c.end()) { if (*it == elem) { it = c.erase(it); } else { it++; } } } template<class Contenedor> bool ordenado(Contenedor &c) { auto it2 = c.begin(); auto it = it2; it2++; while (it2 != c.end()) { if (*it2 < *it) { return false; } it2++; it++; } return true; } template<class Contenedor> std::pair<Contenedor, Contenedor> split(const Contenedor & c, const typename Contenedor::value_type& elem) { std::pair<Contenedor, Contenedor> par; typename Contenedor::iterator its; for (auto it = c.begin(); it != c.end(); it++) { if (*it < elem) { its = par.first.end(); par.first.insert(its, *it); } else { its = par.second.end(); par.second.insert(its, *it); } } return par; } template <class Contenedor> void merge(const Contenedor& c1, const Contenedor & c2, Contenedor & res) { typename Contenedor::const_iterator it1(c1.begin()); typename Contenedor::const_iterator it2(c2.begin()); typename Contenedor::iterator itres; while(it1 != c1.end() && it2 != c2.end()) { itres = res.end(); if(*it1 < *it2) { res.insert(itres, *it1); it1++; } else { res.insert(itres, *it2); it2++; } } while(it1 != c1.end()) { itres = res.end(); res.insert(itres, *it1); it1++; } while (it2 != c2.end()) { itres = res.end(); res.insert(itres, *it2); it2++; } } #endif //ALGO2_LABO_CLASE5_ALGORITMOS_H
#include<iostream> #include<bits/stdc++.h> #include<algorithm> #include<cmath> #include<string> #include<cstring> #include<vector> #include<map> #include<set> #include<list> #include<unordered_map> #include<unordered_set> #define ll long long #define MAX 10000000 using namespace std; int main() { double min,max,step; cin>>min>>max>>step; for(double i=min;i<=max;i=i+step) { int C=((double)5/9)*(i-32); cout<<i<<" "<<C<<endl; } return 0; }
#include<iostream> #include<vector> #include<algorithm> #include<set> #include<map> using namespace std; class Solution { public: char findTheDifference(string s, string t) { //基本思想:哈希表HashMap char res; vector<int> Maps(26,0),Mapt(26,0); for(auto c:s) Maps[c-'a']++; for(auto c:t) Mapt[c-'a']++; for(int i=0;i<26;i++) { if(Mapt[i]!=Maps[i]) { res=static_cast<char>(i+'a'); break; } } return res; } }; class Solution1 { public: char findTheDifference(string s, string t) { //基本思想:位运算,数字与自身异或结果为0 int res=0; for(auto c:s) res^=c; for(auto c:t) res^=c; return res; } }; class Solution2 { public: char findTheDifference(string s, string t) { //基本思想:数学 int res=0; for(auto c:t) res+=c; for(auto c:s) res-=c; return res; } }; int main() { Solution1 solute; string s = "abcd", t = "abcde"; cout<<solute.findTheDifference(s,t)<<endl; return 0; }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */ #ifndef ES_GLOBAL_BUILTINS_H #define ES_GLOBAL_BUILTINS_H class ES_GlobalBuiltins { public: static BOOL ES_CALLING_CONVENTION parseInt(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION parseFloat(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION isNaN(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION isFinite(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION decodeURI(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION decodeURIComponent(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION encodeURI(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION encodeURIComponent(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION eval(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION escape(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL ES_CALLING_CONVENTION unescape(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static BOOL Eval(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value, ES_Code *code, ES_CodeWord *instruction); static BOOL ES_CALLING_CONVENTION ThrowTypeError(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value); static void PopulateGlobalObject(ES_Context *context, ES_Global_Object *global_object); private: static JString *Decode(ES_Context *context, const uni_char *string, int length, const uni_char *reservedSet); static JString *Encode(ES_Context *context, const uni_char *string, int length, const uni_char *unescapedSet); static JString *Escape(ES_Context *context, const uni_char *string, int length, const uni_char *unescapedSet); static JString *Unescape(ES_Context *context, const uni_char *string, int length); }; #endif // ES_GLOBAL_BUILTINS_H
#pragma once #include <map> class Environment { public: virtual ~Environment() = default; /// trace levels enum class TraceLevel { Error = 0, Warning = 1, Info = 2, Debug = 3 }; std::map<TraceLevel, std::string> traceLevels = { {TraceLevel::Error, "Error: "}, {TraceLevel::Warning, "Warning: "}, {TraceLevel::Info, "Info: "}, {TraceLevel::Debug, "Debug: "} }; /// ability to trace virtual void Trace( TraceLevel severity, std::ostream& stream ) = 0; };
#include "dds_uuid.h" #include "drilling_calibration_state_publisher.h" CDrillingCalibrationStatePublisher::CDrillingCalibrationStatePublisher() { } CDrillingCalibrationStatePublisher::~CDrillingCalibrationStatePublisher() { DDS_String_free(m_pDataInstance->id); } bool CDrillingCalibrationStatePublisher::Initialize() { CDdsUuid uuid; uuid.GenerateUuid(); m_pDataInstance->id = DDS_String_dup(uuid.c_str()); return true; } void CDrillingCalibrationStatePublisher::SetTimestamp(const DataTypes::Time timestamp) { if (m_pDataInstance != nullptr) { m_pDataInstance->timestamp.sec = timestamp.sec; m_pDataInstance->timestamp.nanosec = timestamp.nanosec; } else { LOG_ERROR("Failed to set timestamp because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetWobProportional(const double wobProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->wobProportional = wobProportional; } else { LOG_ERROR("Failed to set wob proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetWobIntegral(const double wobIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->wobIntegral = wobIntegral; } else { LOG_ERROR("Failed to set wob integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetDifferentialPressureProportional(const double differentialPressureProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->differentialPressureProportional = differentialPressureProportional; } else { LOG_ERROR("Failed to set differential pressure proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetDifferentialPressureIntegral(const double differentialPressureIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->differentialPressureIntegral = differentialPressureIntegral; } else { LOG_ERROR("Failed to set differential pressure integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetTorqueProportional(const double torqueProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->torqueProportional = torqueProportional; } else { LOG_ERROR("Failed to set torque proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetTorqueIntegral(const double torqueIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->torqueIntegral = torqueIntegral; } else { LOG_ERROR("Failed to set torque integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMinWobProportional(const double minWobProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->minWobProportional = minWobProportional; } else { LOG_ERROR("Failed to set wob proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMaxWobProportional(const double maxWobProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->maxWobProportional = maxWobProportional; } else { LOG_ERROR("Failed to set wob proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMinWobIntegral(const double minWobIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->minWobIntegral = minWobIntegral; } else { LOG_ERROR("Failed to set wob integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMaxWobIntegral(const double maxWobIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->maxWobIntegral = maxWobIntegral; } else { LOG_ERROR("Failed to set wob integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMinDifferentialPressureProportional(const double minDifferentialPressureProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->minDifferentialPressureProportional = minDifferentialPressureProportional; } else { LOG_ERROR("Failed to set differential pressure proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMaxDifferentialPressureProportional(const double maxDifferentialPressureProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->maxDifferentialPressureProportional = maxDifferentialPressureProportional; } else { LOG_ERROR("Failed to set differential pressure proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMinDifferentialPressureIntegral(const double minDifferentialPressureIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->minDifferentialPressureIntegral = minDifferentialPressureIntegral; } else { LOG_ERROR("Failed to set differential pressure integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMaxDifferentialPressureIntegral(const double maxDifferentialPressureIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->maxDifferentialPressureIntegral = maxDifferentialPressureIntegral; } else { LOG_ERROR("Failed to set differential pressure integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMinTorqueProportional(const double minTorqueProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->minTorqueProportional = minTorqueProportional; } else { LOG_ERROR("Failed to set torque proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMaxTorqueProportional(const double maxTorqueProportional) { if (m_pDataInstance != nullptr) { m_pDataInstance->maxTorqueProportional = maxTorqueProportional; } else { LOG_ERROR("Failed to set torque proportional because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMinTorqueIntegral(const double minTorqueIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->minTorqueIntegral = minTorqueIntegral; } else { LOG_ERROR("Failed to set torque integral because of uninitialized sample"); } } void CDrillingCalibrationStatePublisher::SetMaxTorqueIntegral(const double maxTorqueIntegral) { if (m_pDataInstance != nullptr) { m_pDataInstance->maxTorqueIntegral = maxTorqueIntegral; } else { LOG_ERROR("Failed to set torque integral because of uninitialized sample"); } } bool CDrillingCalibrationStatePublisher::PublishSample() { bool bRetVal = false; DDS_Time_t currentTime; GetParticipant()->get_current_time(currentTime); m_pDataInstance->timestamp.sec = currentTime.sec; m_pDataInstance->timestamp.nanosec = currentTime.nanosec; bRetVal = Publish(); return bRetVal; } bool CDrillingCalibrationStatePublisher::Create(int32_t domain) { return TPublisher::Create(domain, nec::control::DRILLING_CALIBRATION_STATE, "EdgeBaseLibrary", "EdgeBaseProfile"); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2003 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef _BMP_SUPPORT_ #include "modules/img/decoderfactorybmp.h" #if defined(INTERNAL_BMP_SUPPORT) || defined(ASYNC_IMAGE_DECODERS_EMULATION) #include "modules/img/src/imagedecoderbmp.h" ImageDecoder* DecoderFactoryBmp::CreateImageDecoder(ImageDecoderListener* listener) { ImageDecoder* image_decoder = OP_NEW(ImageDecoderBmp, ()); if (image_decoder != NULL) { image_decoder->SetImageDecoderListener(listener); } return image_decoder; } #endif // INTERNAL_BMP_SUPPORT BOOL3 DecoderFactoryBmp::CheckSize(const UCHAR* data, INT32 len, INT32& width, INT32& height) { if (len < 26) { return MAYBE; } UINT32 sizebuf = MakeUINT32(data[17], data[16], data[15], data[14]); if (sizebuf < 40) { width = MakeUINT32(0, 0, data[19], data[18]); height = MakeUINT32(0, 0, data[21], data[20]); } else { width = MakeUINT32(data[21], data[20], data[19], data[18]); height = MakeUINT32(data[25], data[24], data[23], data[22]); if (height < 0) height = -height; } if (width <= 0 || height <= 0) { return NO; } return YES; } BOOL3 DecoderFactoryBmp::CheckType(const UCHAR* data, INT32 len) { if (len < 2) { return MAYBE; } if (data[0] == 'B' && data[1] == 'M') { return YES; } return NO; } #endif // _BMP_SUPPORT_
#ifndef __WPP__QT__IOS_H__ #define __WPP__QT__IOS_H__ #include <QString> namespace wpp { namespace qt { class IOS { public: static void excludeICloudBackup(const QString& path); static void documentsDirectoryExcludeICloudBackup(); }; }//namespace qt }//namespace wpp #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/QuickScrollContainer.h" #include "adjunct/desktop_util/rtl/uidirection.h" #include "adjunct/quick_toolkit/widgets/OpMouseEventProxy.h" #include "modules/display/vis_dev.h" #include "modules/widgets/OpScrollbar.h" #include "modules/hardcore/opera/opera.h" #include "modules/widgets/widgets_module.h" class QuickScrollContainer::ScrollView : public OpMouseEventProxy { public: ScrollView(OpScrollbar* scrollbar) : m_scrollbar(scrollbar) {} virtual Type GetType() { return WIDGET_TYPE_SCROLLABLE; } virtual const char* GetInputContextName() { return "Quick Scroll Container View"; } virtual BOOL OnMouseWheel(INT32 delta,BOOL vertical) { ShiftKeyState keystate = m_scrollbar->GetVisualDevice()->GetView()->GetShiftKeys(); if (keystate & DISPLAY_SCALE_MODIFIER) // Scale { // scaling key is pressed so do not scroll return FALSE; } // Value copied from display module to match web pages return m_scrollbar->OnScroll(delta * DISPLAY_SCROLLWHEEL_STEPSIZE, vertical); } virtual BOOL OnScrollAction(INT32 delta, BOOL vertical, BOOL smooth) { // Don't send vertical scroll events to a horizontal scroll bar if (vertical != m_scrollbar->IsHorizontal()) return m_scrollbar->OnScroll(delta, vertical, smooth); else return FALSE; } virtual BOOL IsScrollable(BOOL vertical) { return TRUE; } virtual void OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks) { SetFocus(FOCUS_REASON_MOUSE); OpMouseEventProxy::OnMouseDown(point, button, nclicks); } virtual BOOL OnInputAction(OpInputAction* action); private: OpScrollbar* m_scrollbar; }; BOOL QuickScrollContainer::ScrollView::OnInputAction(OpInputAction* action) { switch (action->GetAction()) { case OpInputAction::ACTION_PAGE_UP: case OpInputAction::ACTION_PAGE_DOWN: { // Find offset INT32 offset = m_scrollbar->GetValue(); if (action->GetAction() == OpInputAction::ACTION_PAGE_UP) { offset -= m_scrollbar->big_step; } else { offset += m_scrollbar->big_step; } m_scrollbar->SetValue(offset); break; } } return OpWidget::OnInputAction(action); } QuickScrollContainer::QuickScrollContainer(Orientation orientation, Scrollbar scrollbar_behavior) : m_orientation(orientation) , m_scrollbar_behavior(scrollbar_behavior) , m_scrollbar(0) , m_canvas(0) , m_scrollview(0) , m_respect_scrollbar_margin(true) , m_listener(NULL) { } QuickScrollContainer::~QuickScrollContainer() { g_opera->widgets_module.RemoveExternalListener(this); if (m_scrollview && !m_scrollview->IsDeleted()) m_scrollview->Delete(); } OP_STATUS QuickScrollContainer::Init() { g_opera->widgets_module.AddExternalListener(this); RETURN_IF_ERROR(OpScrollbar::Construct(&m_scrollbar, m_orientation == HORIZONTAL)); m_scrollbar->UpdateSkinMargin(); m_scrollbar->SetListener(this); m_scrollview = OP_NEW(ScrollView, (m_scrollbar)); if (!m_scrollview) return OpStatus::ERR_NO_MEMORY; m_canvas = OP_NEW(OpMouseEventProxy, ()); if (!m_canvas) return OpStatus::ERR_NO_MEMORY; m_scrollview->AddChild(m_canvas); m_scrollview->AddChild(m_scrollbar); return OpStatus::OK; } BOOL QuickScrollContainer::SetScroll(int offset, BOOL smooth_scroll) { return m_scrollbar->OnScroll(offset, FALSE, smooth_scroll); } void QuickScrollContainer::ScrollToEnd() { INT32 min, max; m_scrollbar->GetLimits(min, max); m_scrollbar->SetValue(max); // SetValueSmoothScroll() does not work expected. } void QuickScrollContainer::SetContent(QuickWidget* contents) { m_content = contents; m_content->SetContainer(this); m_content->SetParentOpWidget(m_canvas); } bool QuickScrollContainer::IsScrollbarVisible() const { return m_scrollbar->IsVisible() != FALSE; } unsigned QuickScrollContainer::GetScrollbarSize() const { return m_orientation == HORIZONTAL ? m_scrollbar->GetInfo()->GetHorizontalScrollbarHeight() : m_scrollbar->GetInfo()->GetVerticalScrollbarWidth(); } OP_STATUS QuickScrollContainer::Layout(const OpRect& rect) { m_scrollview->SetRect(rect, TRUE, FALSE); OpRect view_rect = rect; view_rect.x = view_rect.y = 0; view_rect = LayoutScrollbar(view_rect); // The canvas should be big enough for the nominal size of the content if (m_orientation == HORIZONTAL) view_rect.width = max(m_content->GetNominalWidth(), (unsigned)view_rect.width); else view_rect.height = max(m_content->GetNominalHeight(view_rect.width), (unsigned)view_rect.height); RETURN_IF_ERROR(m_content->Layout(view_rect)); // Set the canvas to the scrolled position if (m_orientation == HORIZONTAL) view_rect.x = -m_scrollbar->GetValue(); else view_rect.y = -m_scrollbar->GetValue(); m_scrollview->SetChildRect(m_canvas, view_rect, TRUE, FALSE); return OpStatus::OK; } OpRect QuickScrollContainer::LayoutScrollbar(const OpRect& rect) { // Determine scrollbar limits int content_width = rect.width; if (m_orientation == VERTICAL) { content_width -= m_scrollbar->GetInfo()->GetVerticalScrollbarWidth(); content_width = max(content_width, 0); } int content_size = m_orientation == HORIZONTAL ? m_content->GetNominalWidth() : m_content->GetNominalHeight(content_width); int scrollview_size = m_orientation == HORIZONTAL ? rect.width : rect.height; m_scrollbar->SetLimit(0, content_size - scrollview_size, scrollview_size); // Copied from display module to match web pages m_scrollbar->SetSteps(DISPLAY_SCROLL_STEPSIZE, scrollview_size - 20); // Return original rect if we don't need a scrollbar bool needs_scrollbar = m_scrollbar_behavior != SCROLLBAR_NONE; if (m_scrollbar_behavior == SCROLLBAR_AUTO) { if (m_orientation == HORIZONTAL && (int)m_content->GetNominalWidth() <= rect.width) needs_scrollbar = false; else if ((int)m_content->GetNominalHeight(content_width) <= rect.height) needs_scrollbar = false; } if (!needs_scrollbar) { m_scrollbar->SetVisibility(FALSE); return rect; } m_scrollbar->SetVisibility(TRUE); // Calculate scrollbar rect short margin_left = 0, margin_top = 0, margin_right = 0, margin_bottom = 0; if (m_respect_scrollbar_margin) m_scrollbar->GetMargins(margin_left, margin_top, margin_right, margin_bottom); OpRect scrollbar_rect = rect; OpRect scrollview_rect = rect; if (m_orientation == HORIZONTAL) { scrollbar_rect.height = m_scrollbar->GetInfo()->GetHorizontalScrollbarHeight(); scrollbar_rect.y = rect.height - scrollbar_rect.height; scrollview_rect.height -= scrollbar_rect.height + margin_top; scrollview_rect.height = max(scrollview_rect.height, 0); } else { scrollbar_rect.width = m_scrollbar->GetInfo()->GetVerticalScrollbarWidth(); scrollbar_rect.x = rect.width - scrollbar_rect.width; scrollview_rect.width -= scrollbar_rect.width + margin_left; scrollview_rect.width = max(scrollview_rect.width, 0); } m_scrollview->SetChildRect(m_scrollbar, scrollbar_rect); return scrollview_rect; } void QuickScrollContainer::SetParentOpWidget(OpWidget* parent) { if (parent) parent->AddChild(m_scrollview); else m_scrollview->Remove(); } void QuickScrollContainer::Show() { m_scrollview->SetVisibility(TRUE); } void QuickScrollContainer::Hide() { m_scrollview->SetVisibility(FALSE); } BOOL QuickScrollContainer::IsVisible() { return m_scrollview->IsVisible(); } void QuickScrollContainer::SetEnabled(BOOL enabled) { m_scrollview->SetEnabled(enabled); } void QuickScrollContainer::OnScroll(OpWidget *widget, INT32 old_val, INT32 new_val, BOOL caused_by_input) { OpRect canvas_rect = m_canvas->GetRect(); if (m_orientation == HORIZONTAL) canvas_rect.x = -new_val; else canvas_rect.y = -new_val; // Optimization: we do not invalidate the rect but use VisualDevice::ScrollRect() m_canvas->SetRect(canvas_rect, FALSE, FALSE); VisualDevice* vd = m_scrollview->GetVisualDevice(); if (!vd) return; int delta = old_val - new_val; OpRect scroll_rect = m_scrollview->GetRect(TRUE); if (m_orientation == HORIZONTAL) { scroll_rect.height -= m_scrollbar->GetRect().height; vd->ScrollRect(scroll_rect, delta, 0); } else { int scrollbar_width = m_scrollbar->GetRect().width; scroll_rect.width -= scrollbar_width; if (UiDirection::Get() == UiDirection::RTL) scroll_rect.x += scrollbar_width; vd->ScrollRect(scroll_rect, 0, delta); } if (m_listener) { m_listener->OnContentScrolled(new_val, m_scrollbar->limit_min, m_scrollbar->limit_max); } } void QuickScrollContainer::OnFocus(OpWidget *widget, BOOL focus, FOCUS_REASON reason) { if (!focus || reason == FOCUS_REASON_ACTIVATE) return; bool widget_in_canvas = false; for (OpWidget* parent = widget; parent; parent = parent->GetParent()) if (parent == m_canvas) { widget_in_canvas = true; break; } if (widget_in_canvas && widget->ScrollOnFocus()) { OpRect page_rect = m_scrollbar->GetScreenRect(); OpRect widget_rect = widget->GetScreenRect(); if (widget_rect.Bottom() > page_rect.Bottom()) SetScroll(widget->GetRect().Bottom() - page_rect.height, FALSE); else if (widget_rect.Top() < page_rect.Top()) SetScroll(widget->GetRect().Top(), FALSE); } } OpRect QuickScrollContainer::GetScreenRect() { return m_scrollview->GetScreenRect(); } unsigned QuickScrollContainer::GetDefaultMinimumWidth() { // If we're horizontal, should be big enough to fit at least the scrollbar if (m_orientation == HORIZONTAL) return m_scrollbar->GetKnobMinLength(); // Otherwise depends on content and scrollbar width return AddScrollbarWidthTo(m_content->GetMinimumWidth()); } unsigned QuickScrollContainer::GetDefaultMinimumHeight(unsigned width) { // If we're vertical, should be big enough to fit at least the scrollbar if (m_orientation == VERTICAL) return m_scrollbar->GetKnobMinLength(); // Otherwise depends on content and scrollbar height return AddScrollbarHeightTo(m_content->GetMinimumHeight(width)); } unsigned QuickScrollContainer::GetDefaultNominalHeight(unsigned width) { // If we're vertical, try to fit content if (m_orientation == VERTICAL) return m_content->GetNominalHeight(width); // Try to see if content will fit even with scrollbar unsigned min_height = AddScrollbarHeightTo(m_content->GetMinimumHeight(width)); unsigned nom_height = m_content->GetNominalHeight(width); if (min_height <= nom_height) return nom_height; // Otherwise make sure that scrollbar will fit in return AddScrollbarHeightTo(m_content->GetNominalHeight(width)); } unsigned QuickScrollContainer::GetDefaultNominalWidth() { // If we're horizontal, try to fit content if (m_orientation == HORIZONTAL) return m_content->GetNominalWidth(); // Try to see if content will fit even with scrollbar unsigned min_width = AddScrollbarWidthTo(m_content->GetMinimumWidth()); unsigned nom_width = m_content->GetNominalWidth(); if (min_width <= nom_width) return nom_width; // Otherwise make sure that scrollbar will fit in return AddScrollbarWidthTo(m_content->GetNominalWidth()); } unsigned QuickScrollContainer::GetDefaultPreferredWidth() { // Depends on content and scrollbar width return AddScrollbarWidthTo(m_content->GetPreferredWidth()); } unsigned QuickScrollContainer::GetDefaultPreferredHeight(unsigned width) { // Depends on content and scrollbar height return AddScrollbarHeightTo(m_content->GetPreferredHeight(width)); } unsigned QuickScrollContainer::AddScrollbarWidthTo(unsigned width) { if (width == WidgetSizes::Infinity || m_orientation == HORIZONTAL || m_scrollbar_behavior == SCROLLBAR_NONE) return width; if (m_respect_scrollbar_margin) { short margin_left, margin_top, margin_right, margin_bottom; m_scrollbar->GetMargins(margin_left, margin_top, margin_right, margin_bottom); width += margin_left; } return width + m_scrollbar->GetInfo()->GetVerticalScrollbarWidth(); } unsigned QuickScrollContainer::AddScrollbarHeightTo(unsigned height) { if (height == WidgetSizes::Infinity || m_orientation == VERTICAL || m_scrollbar_behavior == SCROLLBAR_NONE) return height; if (m_respect_scrollbar_margin) { short margin_left, margin_top, margin_right, margin_bottom; m_scrollbar->GetMargins(margin_left, margin_top, margin_right, margin_bottom); height += margin_top; } return height + m_scrollbar->GetInfo()->GetHorizontalScrollbarHeight(); }
/* BEGIN LICENSE */ /***************************************************************************** * SKCore : the SK core library * Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr> * $Id: output.h,v 1.6.2.2 2005/02/17 15:29:21 krys Exp $ * * Authors: Mathieu Poumeyrol <poumeyrol @at@ idm .dot. fr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Alternatively you can contact IDM <skcontact @at@ idm> for other license * contracts concerning parts of the code owned by IDM. * *****************************************************************************/ /* END LICENSE */ #ifndef __SKC_OUTPUT_H_ #define __SKC_OUTPUT_H_ class SKAPI SKFileOutput : public SKRefCount { public: SK_REFCOUNT_INTF_DEFAULT(SKFileOutput) SKFileOutput (); ~SKFileOutput (); // filename const char* GetSharedFileName() { return m_pszFileName; } virtual SKERR Create(const char* pcFileName); virtual SKERR Append(const char* pcFileName); virtual SKERR Write(const char* pcBuffer, PRUint32 iSize); virtual SKERR Printf(const char* pcFormat, ...); virtual SKERR vPrintf(const char* pcFormat, va_list va); virtual SKERR Flush(); virtual SKERR Close(); PRUint32 GetWritten() { return m_iWritten; } protected: virtual SKERR Open(const char* pcFileName, PRUint32 lFlags); char *m_pszFileName; PRFileDesc* m_pFD; char* m_pcBuffer; PRUint32 m_iBufferSize; PRUint32 m_iDeadLength; PRUint32 m_iWritten; }; #define err_cnf_invalid 100 #else /* __SKC_OUTPUT_H_ */ #error "Multiple inclusions of output.h" #endif /* __SKC_OUTPUT_H_ */
#include "hmi_message_publisher/can_node.h" #include <glog/logging.h> using namespace HMI::SL4::hmi_message_publisher; int main(int argc, char** argv) { ros::init(argc, argv, "hmi_message_publisher_can_node"); ros::NodeHandle nh("~"); auto use_threat_obstacle_topic = nh.getParam("use_threat_obstacle_topic", CanNode::UseThreatObstacleTopic()); auto perception_obstacle_topic = nh.getParam("perception_obstacle_topic", CanNode::PerceptionObstacleTopic()); auto threat_obstacle_topic = nh.getParam("threat_obstacle_topic", CanNode::ThreatObstacleTopic()); auto lane_path_topic = nh.getParam("lane_path_topic", CanNode::LanePathTopic()); auto odom_topic = nh.getParam("odom_topic", CanNode::OdomTopic()); auto steering_report_topic = nh.getParam("steering_report_topic", CanNode::SteeringReportTopic()); auto dbw_enable_topic = nh.getParam("dbw_enable_topic", CanNode::DbwEnableTopic()); auto planning_trajectory_topic = nh.getParam("planning_trajectory_topic", CanNode::PlanningTrajectoryTopic()); auto turn_signal_cmd_topic = nh.getParam("turn_signal_cmd_topic", CanNode::TurnSignalCmdTopic()); auto longitudinal_report_topic = nh.getParam("longitudinal_report_topic", CanNode::LongitudinalReportTopic()); CanNode can_node(0); can_node.Run(); }
#include "stdafx.h" #include "ParticlepropertyView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CParticleProperty IMPLEMENT_DYNCREATE(CParticlePropertyView, CView) CParticlePropertyView::CParticlePropertyView() { } CParticlePropertyView::~CParticlePropertyView() { } BEGIN_MESSAGE_MAP(CParticlePropertyView, CView) //{{AFX_MSG_MAP(CParticlePropertyView) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CParticleProperty drawing void CParticlePropertyView::OnDraw(CDC* pDC) { CView::OnDraw(pDC); } ///////////////////////////////////////////////////////////////////////////// // CParticleProperty diagnostics #ifdef _DEBUG void CParticlePropertyView::AssertValid() const { CView::AssertValid(); } void CParticlePropertyView::Dump(CDumpContext& dc) const { CView::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CParticlePropertyView message handlers void CParticlePropertyView::OnViewTwo() { // alert user. AfxMessageBox(_T("Properties Pane - No. 2")); // set input focus SetFocus(); } void CParticlePropertyView::OnUpdateViewTwo(CCmdUI* /*pCmdUI*/) { // TODO: Add your command update UI handler code here }
template <typename... TArgs> struct System : BaseSystem { public: using TYPE = ComponentList<TArgs...>; void set(ComponentManager& components) { BaseSystem::components = &components; (BaseSystem::components->enable<TArgs>(),...); } protected: /*auto get() -> std::generator<decltype(components->values<TArgs...>({})) > { for (auto const& ref : entities) { co_yield components->values<TArgs...>(ref); } }*/ template <typename F> void foreach(const F& f) { join::run(entities, f, store<TArgs>()...); } private: template <typename T> store_of<T>& store() { return components->store<T>(); } };
#include <iostream> #include <string> #include <vector> using namespace std; class Person { public: int a; // 静态成员变量不能在类内初始化,类内只能声明,定义全局 // 声明的作用只是限制静态成员变量的作用域 static int b; // 静态成员变量,在编译阶段就分配内存,存在静态全局区 void show() { cout << a << " " << b << endl; } static void static_show() // 静态成员函数可以访问静态成员变量,不能访问普通成员的变量 { cout << " " << b << endl; } }; int Person::b = 100; void test01() { Person::static_show();//通过类的作用域访问静态成员函数 Person p1; p1.static_show();//通过对象访问静态成员函数 } int main(int argc, char **argv) { return 0; }
#include "lib_security_door.h" using namespace std; door_ctx::door_ctx() { state_run = false; state_quit = false; p_open = NULL; p_close = NULL; p_middle = NULL; cmd = 0; last_cmd = 0; for (int i = 0; i < 5; i++) { pin[i] = NULL; } p_open = new door_open; p_close = new door_close; p_middle = new door_middle; p_state = NULL; } door_ctx::~door_ctx() { if (state_run) { state_quit = true; pthread_join(thrd_state, NULL); } if (p_open) delete p_open; if (p_close) delete p_close; if (p_middle) delete p_middle; } void door_ctx::init(gpio * door_pin[5]) { for (int i = 0; i < 5; i++) { pin[i] = door_pin[i]; } p_state = get_door_state(); pthread_create(&thrd_state, NULL, state_proc, this); state_run = true; } void * door_ctx::state_proc(void * arg) { int res; door_ctx * ctx = (door_ctx *)arg; while (!ctx->state_quit) { ctx->handler(); usleep(50000); } return NULL; } void door_ctx::handler() { p_state->handler(this); } void door_ctx::set_state(state * st) { p_state = st; } state * door_ctx::get_curr_state() { return p_state; } void door_ctx::set_cmd(int command) { mtx.lock(); cmd = command; mtx.unlock(); } state * door_ctx::get_open() { return p_open; } state * door_ctx::get_close() { return p_close; } state * door_ctx::get_middle() { return p_middle; } state * door_ctx::get_door_state() { int up_state = 0; int dn_state = 0; int door_state = 0; state * st; up_state = pin[INDEX_UP_LIMIT]->get_value(); dn_state = pin[INDEX_DOWN_LIMIT]->get_value(); door_state = (up_state << 1) + dn_state; if (door_state == 1) { st = get_open(); } else if (door_state == 2) { st = get_close(); } else if (door_state == 3) { st = get_middle(); } else { st = NULL; } return st; } void state::handler(door_ctx * ctx) { } void door_open::handler(door_ctx * ctx) { if (ctx->cmd == CMD_STOP) { ctx->pin[INDEX_CLOSE]->set_value(0); ctx->pin[INDEX_OPEN]->set_value(0); ctx->pin[INDEX_STOP]->set_value(1); } else if (ctx->cmd == CMD_CLOSE) { ctx->pin[INDEX_CLOSE]->set_value(1); ctx->pin[INDEX_OPEN]->set_value(0); ctx->pin[INDEX_STOP]->set_value(0); } state * curr_state = ctx->get_door_state(); if (curr_state != NULL) ctx->set_state(curr_state); } void door_close::handler(door_ctx * ctx) { if (ctx->cmd == CMD_STOP) { ctx->pin[INDEX_CLOSE]->set_value(0); ctx->pin[INDEX_OPEN]->set_value(0); ctx->pin[INDEX_STOP]->set_value(1); } else if (ctx->cmd == CMD_OPEN) { ctx->pin[INDEX_OPEN]->set_value(1); ctx->pin[INDEX_CLOSE]->set_value(0); ctx->pin[INDEX_STOP]->set_value(0); } state * curr_state = ctx->get_door_state(); if (curr_state != NULL) ctx->set_state(curr_state); } void door_middle::handler(door_ctx * ctx) { if (ctx->cmd == CMD_STOP) { ctx->pin[INDEX_CLOSE]->set_value(0); ctx->pin[INDEX_OPEN]->set_value(0); ctx->pin[INDEX_STOP]->set_value(1); } else if (ctx->cmd == CMD_OPEN) { ctx->pin[INDEX_OPEN]->set_value(1); ctx->pin[INDEX_CLOSE]->set_value(0); ctx->pin[INDEX_STOP]->set_value(0); } else if (ctx->cmd == CMD_CLOSE) { ctx->pin[INDEX_CLOSE]->set_value(1); ctx->pin[INDEX_OPEN]->set_value(0); ctx->pin[INDEX_STOP]->set_value(0); } state * curr_state = ctx->get_door_state(); if (curr_state != NULL) ctx->set_state(curr_state); }
operator double() const; Vector::operator double() const { return mag; } // 内联形式 operator double() { return mag; }
// https://oj.leetcode.com/problems/valid-number/ class Solution { public: bool isNumber(const char *s) { if (*s == 0) { return false; } bool last_digit = false; bool has_exp = false; bool has_dot = false; while (*s != 0 && *s == ' ') { // heading whitespace s++; } if (*s == '+' || *s == '-') { // heading sign s++; } if (*s == '.') { s++; has_dot = true; } int len = strlen(s); int newlen = 0; for (int i = len - 1; i >= 0; i--) { // tailing whitespace if (s[i] != ' ') { newlen = i + 1; break; } } if (newlen == 0) { return false; } for (int i = 0; i < newlen; i++) { char c = s[i]; if (isdigit(c)) { last_digit = true; } else if (c == '.') { if (has_dot || has_exp || !last_digit) { return false; } has_dot = true; } else if (c == '+' || c == '-') { if (i == 0 || (s[i-1] != 'E' && s[i-1] != 'e') || i == newlen - 1) { return false; } last_digit = false; } else if (c == 'E' || c == 'e') { if (has_exp || !last_digit || i == newlen - 1) { return false; } has_exp = true; last_digit = false; } else { return false; } } return true; } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef MEDIA_HTML_SUPPORT #include "modules/media/src/mediathread.h" MediaThread::MediaThread(MediaThreadListener* listener, ES_Thread* thread) : m_proxy_listener(this) , m_listener(listener) , m_thread(thread) { thread->AddListener(&m_proxy_listener); } BOOL MediaThread::IsTimeUpdateThread() const { DOM_EventType actual = m_thread->GetInfo().data.event.type; return (m_thread->Type() == ES_THREAD_EVENT && actual == MEDIATIMEUPDATE); } OP_STATUS MediaThread::Cancel() { return m_thread->GetScheduler()->CancelThread(m_thread); } void MediaThread::OnThreadSignal() { m_listener->OnThreadFinished(this); } MediaThread::Listener::Listener(MediaThread* owner) : m_owner(owner) { OP_ASSERT(owner); } /* virtual */ OP_STATUS MediaThread::Listener::Signal(ES_Thread* /*thread*/, ES_ThreadSignal /*signal*/) { m_owner->OnThreadSignal(); return OpStatus::OK; } MediaThreadQueue::MediaThreadQueue(MediaThreadQueueListener* listener) : m_listener(listener) , m_timeupdate_queued(0) { OP_ASSERT(listener); } OP_STATUS MediaThreadQueue::QueueEvent(DOM_Environment* environment, const DOM_Environment::EventData &data) { OP_ASSERT(environment); ES_Thread* event_thread; OP_BOOLEAN status = environment->HandleEvent(data, NULL, &event_thread); RETURN_IF_MEMORY_ERROR(status); if (status == OpBoolean::IS_TRUE && event_thread) { MediaThread* media_thread = OP_NEW(MediaThread, (this, event_thread)); RETURN_OOM_IF_NULL(media_thread); media_thread->Into(&m_threads); if (media_thread->IsTimeUpdateThread()) m_timeupdate_queued++; } return OpStatus::OK; } void MediaThreadQueue::CancelAll() { MediaThread* thread = m_threads.First(); while (thread) { MediaThread* next = thread->Suc(); Cancel(thread); thread = next; } } void MediaThreadQueue::Cancel(MediaThread* thread) { if (!thread->IsStarted() && OpStatus::IsError(thread->Cancel())) Remove(thread); } void MediaThreadQueue::Remove(MediaThread* thread) { if (thread->IsTimeUpdateThread()) { OP_ASSERT(m_timeupdate_queued > 0); m_timeupdate_queued--; } thread->Out(); OP_DELETE(thread); } /* virtual */ void MediaThreadQueue::OnThreadFinished(MediaThread* thread) { Remove(thread); if (!IsTimeUpdateQueued()) m_listener->OnTimeUpdateThreadsFinished(); } #endif //MEDIA_HTML_SUPPORT
#include<iostream> using namespace std; int main() { int n; cin>>n; int A[n],B[n]; for(int i=0;i<n;i++) cin>>A[i]; int j=0; for(int i=0;i<n-1;i++) { if(A[i+1]!=A[i]) B[j+1]=A[i]; } B[j+1]=A[n-1]; for(int i=0;i<j;i++) { A[i]=B[i]; cout<<A[i]; } return 0; }
//===- OR1KDisassembler.cpp - Disassembler for OR1K -------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is part of the OR1K Disassembler. // //===----------------------------------------------------------------------===// #include "OR1K.h" #include "OR1KDisassembler.h" #include "OR1KSubtarget.h" #include "OR1KRegisterInfo.h" #include "llvm/MC/MCDisassembler.h" #include "llvm/MC/MCFixedLenDisassembler.h" #include "llvm/Support/MemoryObject.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCInst.h" #include "llvm/Support/MathExtras.h" using namespace llvm; typedef MCDisassembler::DecodeStatus DecodeStatus; namespace llvm { extern Target TheOR1KTarget; } static MCDisassembler *createOR1KDisassembler(const Target &T, const MCSubtargetInfo &STI) { return new OR1KDisassembler(STI, T.createMCRegInfo("")); } extern "C" void LLVMInitializeOR1KDisassembler() { // Register the disassembler TargetRegistry::RegisterMCDisassembler(TheOR1KTarget, createOR1KDisassembler); } // Forward declare because the autogenerated code will reference this. // Definition is further down. DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder); static DecodeStatus DecodeMemoryValue(MCInst &Inst, unsigned Insn, uint64_t Address, const void *Decoder); #include "OR1KGenDisassemblerTables.inc" static DecodeStatus readInstruction32(const MemoryObject &region, uint64_t address, uint64_t &size, uint32_t &insn) { uint8_t Bytes[4]; // We want to read exactly 4 bytes of data. if (region.readBytes(address, 4, (uint8_t*)Bytes) == -1) { size = 0; return MCDisassembler::Fail; } // Encoded as big-endian 32-bit word in the stream. insn = (Bytes[0] << 24) | (Bytes[1] << 16) | (Bytes[2] << 8) | (Bytes[3] << 0); return MCDisassembler::Success; } DecodeStatus OR1KDisassembler::getInstruction(MCInst &instr, uint64_t &Size, const MemoryObject &Region, uint64_t Address, raw_ostream &vStream, raw_ostream &cStream) const { uint32_t Insn; DecodeStatus Result = readInstruction32(Region, Address, Size, Insn); if (Result == MCDisassembler::Fail) return MCDisassembler::Fail; // Call auto-generated decoder function Result = decodeInstruction(DecoderTableOR1K32, instr, Insn, Address, this, STI); if (Result != MCDisassembler::Fail) { Size = 4; return Result; } return MCDisassembler::Fail; } DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, unsigned RegNo, uint64_t Address, const void *Decoder) { if (RegNo > 31) return MCDisassembler::Fail; // The internal representation of the registers counts r0: 2, r1: 3, etc. // FIXME: Use a more stable method of identifying registers Inst.addOperand(MCOperand::CreateReg(RegNo+2)); return MCDisassembler::Success; } static DecodeStatus DecodeMemoryValue(MCInst &Inst, unsigned Insn, uint64_t Address, const void *Decoder) { unsigned Register = (Insn >> 16) & 0x1f; Inst.addOperand(MCOperand::CreateReg(Register+2)); unsigned Offset = (Insn & 0xffff); Inst.addOperand(MCOperand::CreateImm(SignExtend32<16>(Offset))); return MCDisassembler::Success; }
#ifndef ACCOUNTREGISTERWIDGET_HPP #define ACCOUNTREGISTERWIDGET_HPP #include <QWidget> #include <QPushButton> #include <QLabel> #include <QLineEdit> #include <QHBoxLayout> #include <QGridLayout> #include <QFormLayout> #include <QVBoxLayout> #include <QStackedLayout> class AccountRegisterWidget : public QWidget { Q_OBJECT public: explicit AccountRegisterWidget(QWidget *parent = nullptr); signals: public slots: void registerValidateClicked(); void registerClicked(); private: void initLayout(); void initConnection(); private: QLabel *mLabelTelephone; QLabel *mLabelValidate; QLabel *mLabelPasswd; QLabel *mLabelPasswdConfirm; QLabel *mLabelName; QLineEdit *mLineTelephone; QLineEdit *mlineValidate; QLineEdit *mLinePasswd; QLineEdit *mLinePasswdConfirm; QLineEdit *mLineName; QLabel *mLabelPrompt; QPushButton *mButtonValidate; QPushButton *mButtonRegister; }; #endif // ACCOUNTREGISTERWIDGET_HPP
#include "GameOver.h" #include "Title.h" #include "SeaquenceController.h" GameOver::GameOver() { std::cout << "GameOver" << std::endl; mCount = 0; } GameOver::~GameOver() { } Boot* GameOver::Update(SeaquenceController*){ Boot* next = this; if (mCount == 60){ next = new Title; } ++mCount; return next; }
#pragma once #include "plbase/PluginBase.h" #include "eWeaponType.h" #pragma pack(push, 4) class PLUGIN_API CWeapon { public: eWeaponType m_Type; unsigned __int32 m_dwState; unsigned __int32 m_dwAmmoInClip; unsigned __int32 m_dwTotalAmmo; unsigned __int32 m_dwTimeForNextShot; unsigned __int8 field_14; unsigned __int8 field_15; unsigned __int8 field_16; unsigned __int8 field_17; void *m_pParticle; // CParticle * bool HasWeaponAmmoToBeUsed(); }; #pragma pack(pop) VALIDATE_SIZE(CWeapon, 0x1C);
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #include "Core/Variant.hpp" namespace Push { Variant::Variant() : m_pointer(nullptr) , m_copy(Copy<void>) , m_delete(Delete<void>) { } Variant::Variant(const Variant& rhs) : m_pointer(nullptr) , m_copy(Copy<void>) , m_delete(Delete<void>) { Assign(rhs); } Variant::~Variant() { m_delete(&m_pointer); } Variant& Variant::operator=(const Variant& rhs) { m_delete(&m_pointer); Assign(rhs); return *this; } template<> void Variant::Delete<void>(void** ptr) { } template<> void Variant::Copy<void>(void** dst, void* const* src) { *dst = nullptr; } template<> void Variant::Assign<Variant>(Variant&& rhs) { Assign<const Variant&>(rhs); } template<> void Variant::Assign<Variant&>(Variant& rhs) { Assign<const Variant&>(rhs); } template<> void Variant::Assign<const Variant&>(const Variant& rhs) { if(this != &rhs) { m_delete(&m_pointer); rhs.m_copy(&m_pointer, &rhs.m_pointer); m_copy = rhs.m_copy; m_delete = rhs.m_delete; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2003 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SECURITY_PROTOCOLS_DIALOG_H #define SECURITY_PROTOCOLS_DIALOG_H #include "adjunct/quick_toolkit/widgets/Dialog.h" #include "adjunct/desktop_util/treemodel/simpletreemodel.h" class SSL_Options; class SecurityProtocolsDialog : public Dialog { public: SecurityProtocolsDialog(); ~SecurityProtocolsDialog(); Type GetType() {return DIALOG_TYPE_SECURITY_PROTOCOLS;} const char* GetWindowName() {return "Security Protocols Dialog";} const char* GetHelpAnchor() {return "protocols.html";} void Init(DesktopWindow* parent_window); void OnInit(); UINT32 OnOk(); private: SSL_Options* m_options_manager; SimpleTreeModel m_ciphers_model; #ifdef SSL_2_0_SUPPORT int m_ssl2_count; #endif // SSL_2_0_SUPPORT }; #endif //this file
/* Initial author: Convery (tcn@ayria.se) Started: 2019-09-13 License: MIT */ #include <Stdinclude.hpp> #include "../Common/Common.hpp" namespace Tencent { // These should probably be fetched in the background. std::unordered_map<uint32_t, std::wstring> Widestrings { { 14, L"Appname" }, // Probably the main process. { 15, L"Windowname" }, // Used for Sendmessage as well. { 16, L"PASS:-q" }, // Arguments passed to command-line, "-q %u -k %s -s %s -j %s -t %d" }; std::unordered_map<uint32_t, std::string> Bytestrings { { 3, "7" }, // Game-signature length. { 4, "Gamesig" }, // Also used for QQ stuff. { 5, "Loginkey" }, // Seems to be more of a SessionID. { 7, "Appticket" }, // For authentication. { 8, "auth3.qq.com:3074;lsg.qq.com:3074;1004" }, // Authentication-info, last ID being appID. { 22, "PlatformID" }, // { 24, "Tencentticket" },// { 25, "OpenIDKey" }, // OpenID's standardized implementation. { 26, "7" }, // Jump-signature length. { 27, "Jumpsig" }, // Seems to be anti-cheat related. }; std::unordered_map<uint32_t, int32_t> Integers{}; std::unordered_map<uint32_t, uint32_t> DWORDs { { 1, 42 }, // Unknown, seems unused. { 5, 0x7F000001 }, // IP-address. { 7, 38 }, // Authentication-info size. { 18, 1337 }, // UserID. }; void Sendmessage(WPARAM wParam, LPARAM lParam) { auto Result = FindWindowW(L"static", NULL); while(Result) { PostMessageW(Result, 0xBD2u, wParam, lParam); Result = FindWindowExW(NULL, Result, L"static", NULL); } } struct Interface { // TODO(tcn): Implement these when needed. virtual BOOL getLogininfo(void *Loginstruct) { Traceprint(); // Notify listeners. Sendmessage(1 | 0x650000, 0); return true; } virtual BOOL Initialize() { Traceprint(); // Notify listeners. Sendmessage(1 | 0x640000, 0); return true; } virtual BOOL Restart() { Traceprint(); return true; } virtual BOOL Uninitialize() { Traceprint(); return true; } virtual BOOL setEventhandler(void *Eventhandler) { Traceprint(); return true; } virtual void ReleaseTENIO() { Traceprint(); } virtual BOOL Notifyshutdown() { Traceprint(); return true; } virtual void *Closehandle() { Traceprint(); return this; } // Global info. virtual BOOL getInteger(uint32_t Tag, int32_t *Buffer) { Debugprint(va("%s(%u)", __FUNCTION__, Tag)); auto Result = Integers.find(Tag); if(Buffer && Result != Integers.end()) *Buffer = Result->second; // Notify listeners. Sendmessage(1 | (Tag << 0x10), 0); return Result != Integers.end(); } virtual BOOL getDWORD(uint32_t Tag, uint32_t *Buffer) { return getDWORD_(Tag, Buffer, 0); } virtual BOOL getBytestring(uint32_t Tag, uint8_t *Buffer, uint32_t *Size) { return getBytestring_(Tag, Buffer, Size, 0); } virtual BOOL getWidestring(uint32_t Tag, wchar_t *Buffer, uint32_t *Size) { return getWidestring_(Tag, Buffer, Size, 0); } // User info. NOTE(tcn): '_' because it needs to have a different name or CL changes the layout. virtual BOOL getBytestring_(uint32_t Tag, uint8_t *Buffer, uint32_t *Size, uint32_t UserID) { auto Result = Bytestrings.find(Tag); Debugprint(va("%s(%u)", __FUNCTION__, Tag)); if(Result == Bytestrings.end()) return FALSE; // If a buffer is provided, fill it. if(Buffer) std::memcpy(Buffer, Result->second.c_str(), std::min(size_t(*Size), Result->second.size())); // Always set the total size. *Size = Result->second.size(); // Notify listeners. Sendmessage(1 | (Tag << 0x10), UserID != 0); return TRUE; } virtual BOOL getWidestring_(uint32_t Tag, wchar_t *Buffer, uint32_t *Size, uint32_t UserID) { auto Result = Widestrings.find(Tag); Debugprint(va("%s(%u)", __FUNCTION__, Tag)); if(Result == Widestrings.end()) return FALSE; // If a buffer is provided, fill it. if(Buffer) std::wmemcpy(Buffer, Result->second.c_str(), std::min(size_t(*Size >> 1), Result->second.size())); // Always set the total size. *Size = Result->second.size() * sizeof(wchar_t); // Notify listeners. Sendmessage(1 | (Tag << 0x10), UserID != 0); return TRUE; } virtual BOOL getDWORD_(uint32_t Tag, uint32_t *Buffer, uint32_t UserID) { Debugprint(va("%s(%u)", __FUNCTION__, Tag)); auto Result = DWORDs.find(Tag); if(Buffer && Result != DWORDs.end()) *Buffer = Result->second; // Notify listeners. Sendmessage(1 | (Tag << 0x10), UserID != 0); return Result != DWORDs.end(); } }; // Temporary implementation of the Tensafe interface, TODO(tcn): Give it; it's own module? struct Cryptoblock { uint32_t Command; uint8_t *Inputbuffer; uint32_t Inputlength; uint8_t *Outputbuffer; uint32_t Outputlength; }; struct Packetheader { uint32_t Unknown; uint32_t SequenceID; uint32_t CRC32Hash; uint32_t Payloadlength; uint32_t Packettype; }; struct Anticheat { uint32_t UserID; uint32_t Uin; uint32_t Gameversion; uint64_t pSink; time_t Startuptime; uint32_t Configneedsreload; char Outgoingpacket[512]; char Incomingpacket[512]; uint32_t Packetssent; uint32_t Unk5; uint32_t Unk6; uint32_t Unk7; uint32_t SequenceID; uint32_t Unk8; char Config[1030]; virtual size_t setInit(void *Info) { Traceprint(); Uin = ((uint32_t *)Info)[0]; Gameversion = ((uint32_t *)Info)[1]; pSink = *(size_t *)Info + sizeof(uint64_t); return 1; } virtual size_t onLogin() { time(&Startuptime); srand(Startuptime & 0xFFFFFFFF); UserID = rand(); // TODO: Send to server. return 1; } virtual size_t Encrypt(Cryptoblock *Block) { Traceprint(); /* Too tired to implement. */ return 1; } virtual size_t isCheatpacket(uint32_t Command) { Traceprint(); /* Incomingpacket = { uint16_t Header; uint16_t Commandcount; uint32_t Commands[]; ... }; for c in Commands => return c == Command; */ return 1; } virtual size_t Decrypt(Cryptoblock *Block) { Traceprint(); /* Too tired to implement. */ return 1; } virtual size_t Release() { Traceprint(); /* Call Dtor internally. */ return 1; } }; } extern "C" { // Tencent anti-cheat initialization override. EXPORT_ATTR void *CreateObj(int Type) { return new Tencent::Anticheat(); } // Tencent OpenID resolving override. EXPORT_ATTR int InitCrossContextByOpenID(void *) { Traceprint(); return 0; } // Create the interface with the required version. EXPORT_ATTR void Invoke(uint32_t GameID, void **Interface) { Debugprint(va("Initializing Tencent for game %u", GameID)); *Interface = new Tencent::Interface(); } } // Initialize Tencent as a plugin. void Tencent_init() { void *Address{}; // Override the original interface generation. Address = GetProcAddress(LoadLibraryA("TenProxy.dll"), "Invoke"); if(Address) if(!Mhook_SetHook((void **)&Address, Invoke)) Simplehook::Stomphook().Installhook(Address, Invoke); // Override the anti-cheat initialization. Address = GetProcAddress(LoadLibraryA("TerSafe.dll"), "CreateObj"); if(Address) if(!Mhook_SetHook((void **)&Address, CreateObj)) Simplehook::Stomphook().Installhook(Address, CreateObj); // Override the OpenID resolving. Address = GetProcAddress(LoadLibraryA("./Cross/CrossShell.dll"), "InitCrossContextByOpenID"); if(Address) if(!Mhook_SetHook((void **)&Address, InitCrossContextByOpenID)) Simplehook::Stomphook().Installhook(Address, InitCrossContextByOpenID); }
/* -*- coding: utf-8 -*- !@time: 2019-12-23 07:25 !@author: superMC @email: 18758266469@163.com !@fileName: 0023_Post.cpp */ #include <selfFun.h> class Solution { private: static bool judge(vector<int> sequence, int start, int root) { if (root <= start) { return true; } int start_copy = start; while (sequence[start] < sequence[root]) start++; int sep_num = start; while (sequence[start] > sequence[root]) start++; if (start < root) return false; if (!judge(sequence, start_copy, sep_num - 1)) return false; return judge(sequence, sep_num, root - 1); } public: bool verifySquenceOfBST(const vector<int> &a) { if (!a.size()) return false; return judge(a, 0, a.size() - 1); } }; int fun() { string str = "[1,3,2,5,8,6,7]"; Solution solution; vector<int> input = stringToIntegerVector(str); bool ret = solution.verifySquenceOfBST(input); printf("%s", ret ? "true" : "false"); return 0; }
#include <math.h> #include <stdlib.h> #include <array> #include <ctime> #include <random> #include "Irid.h" using namespace std; // Constructors Irid::Irid() : GrowArray() {} // Defaults to zero Irid::Irid(int i) : GrowArray(i) {} Irid::Irid(int i, int j) : GrowArray(i, j) {} // Destructor Irid::~Irid() {} // Iridophore Array Generators void Irid::Blank() { for (int i=0; i < rows; ++i){ for (int j=0; j < cols; ++j) { array[i][j] = 0; } } } void Irid::Band(int bandwidth) { for (int i=0; i < rows; ++i){ for (int j=0; j < cols; ++j) { array[i][j] = 0; } } if (bandwidth > 0) { for (int i = ((rows - bandwidth) / 2); i < ((rows + bandwidth) / 2); ++i) { for (int j=0; j < cols; ++j) { array[i][j] = 1; } } } } void Irid::Random(float probability) { mt19937 generator ((int) time(0)); uniform_real_distribution<float> dis(0.0, 1.0); for (int i=0; i < rows; ++i){ for (int j=0; j < cols; ++j) { float randNum = dis(generator); if (randNum < probability) { array[i][j] = 1; } else { array[i][j] = 0; } } } } // Check to see if there are any iridophores in sim bool Irid::checkExist() { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (array[i][j] != 0) { return true; } } } return false; }
#include <opencv2/opencv.hpp> #include <iostream> #include <stdlib.h> #include <fstream> #include <iterator> #include <string> #include <vector> using namespace std; using namespace cv; #ifndef BHUMAN_ISH_H #define BHUMAN_ISH_H class bhuman_ish { public: bhuman_ish(); vector<KeyPoint> run(Mat frame); vector<KeyPoint> blob(Mat frame); }; #endif // BHUMAN_ISH_H
#define NOMINMAX #include <Windows.h> #include "vulkan.h" #include "./models/Boy01_Head_GeoMesh.vulkan.h" #include "./shaders/vert.h" struct LoopThreadParams { HINSTANCE hInstance; HWND hWnd; }; DWORD WINAPI LoopThread(LPVOID lpParam) { auto& params = *(LoopThreadParams*)lpParam; auto& hWnd = params.hWnd; auto& hInstance = params.hInstance; auto extensions = get_extensions(); auto vk = std::move( createVkInstance("vulkan", VK_KHR_SURFACE_EXTENSION_NAME "," VK_KHR_WIN32_SURFACE_EXTENSION_NAME, "VK_LAYER_KHRONOS_validation") .value()); auto surface = std::move( createVkSurface(hInstance, hWnd, &*vk) .value()); auto gpus = enumeratePhysicalDevices(&*vk); auto gpu0 = gpus[0]; auto [family_index, queueFamily] = getQueue(gpu0, [&](auto i, auto&& f) { return queueFamilySupports(f, VK_QUEUE_GRAPHICS_BIT) && queueFamilyPresentsAt(gpu0, i, &*surface); }).value(); auto device = std::move( createDevice(gpu0, family_index, VK_KHR_SWAPCHAIN_EXTENSION_NAME) .value()); auto queue = getQueue(&*device, family_index, 0).value(); auto [swapChain, format, extent] = std::move(createSwapChain(gpu0, &*device, &*surface).value()); std::vector<VkImage> swapChainImages; uint32_t imageCount; vkGetSwapchainImagesKHR(&*device, &*swapChain, &imageCount, nullptr); swapChainImages.resize(imageCount); vkGetSwapchainImagesKHR(&*device, &*swapChain, &imageCount, swapChainImages.data()); std::vector<VkImageView> swapChainImageViews(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); i++) { VkImageViewCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; createInfo.image = swapChainImages[i]; createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; createInfo.format = format.format; createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; createInfo.subresourceRange.baseMipLevel = 0; createInfo.subresourceRange.levelCount = 1; createInfo.subresourceRange.baseArrayLayer = 0; createInfo.subresourceRange.layerCount = 1; vkCreateImageView(&*device, &createInfo, nullptr, &swapChainImageViews[i]); } auto vert_shader = std::move( createShaderModule(&*device, "shaders/vert.spv").value() ); auto vertex_stage = createPipelineStage(&*vert_shader, VK_SHADER_STAGE_VERTEX_BIT, "main"); auto frag_shader = std::move( createShaderModule(&*device, "shaders/frag.spv").value() ); auto fragment_stage = createPipelineStage(&*frag_shader, VK_SHADER_STAGE_FRAGMENT_BIT, "main"); auto vert_input_stage = createVertexInput(); auto input_assembly_stage = createVertexAssembly(); auto viewport_stage = createViewportState(gpu0, &*surface); auto rasterizer_stage = createRasterizer(); auto multisampling_stage = createMultisampling(); auto color_blend_stage = createColorBlend(); vert v; VkMemoryAllocateInfo alloc_info; v.config(alloc_info); auto uniform_mem = valloc(gpu0, &*device, alloc_info); auto pipeline_info = make_pipeline_info(); v.config(&*device, pipeline_info, uniform_mem); auto pipeline_layout = std::move( createPipelineLayout(&*device) .value() ); auto render_passess = std::move( createRenderPass(gpu0, &*surface, &*device) .value() ); Boy01_Head_GeoMesh h{ vert_input_stage }; h.load(gpu0, &*device, "models/Boy01_Head_GeoMesh"); auto pipeline = std::move( createPipeline( &*device, vertex_stage, fragment_stage, vert_input_stage, input_assembly_stage, viewport_stage, rasterizer_stage, multisampling_stage, color_blend_stage, &*pipeline_layout, &*render_passess).value() ); std::vector<VkFramebuffer> swapChainFramebuffers(swapChainImageViews.size()); for (size_t i = 0; i < swapChainImageViews.size(); i++) { VkImageView attachments[] = { swapChainImageViews[i] }; VkFramebufferCreateInfo framebufferInfo = {}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = &*render_passess;; framebufferInfo.attachmentCount = 1; framebufferInfo.pAttachments = attachments; framebufferInfo.width = extent.currentExtent.width; framebufferInfo.height = extent.currentExtent.height; framebufferInfo.layers = 1; vkCreateFramebuffer(&*device, &framebufferInfo, nullptr, &swapChainFramebuffers[i]); } VkCommandPool commandPool; VkCommandPoolCreateInfo poolInfo = {}; poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; poolInfo.queueFamilyIndex = family_index; poolInfo.flags = 0; // Optional vkCreateCommandPool(&*device, &poolInfo, nullptr, &commandPool); std::vector<VkCommandBuffer> commandBuffers(32); VkCommandBufferAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.commandPool = commandPool; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandBufferCount = (uint32_t)commandBuffers.size(); vkAllocateCommandBuffers(&*device, &allocInfo, commandBuffers.data()); for (size_t i = 0; i < swapChainImageViews.size(); i++) { VkCommandBufferBeginInfo beginInfo = {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = 0; // Optional beginInfo.pInheritanceInfo = nullptr; // Optional vkBeginCommandBuffer(commandBuffers[i], &beginInfo); VkRenderPassBeginInfo renderPassInfo = {}; renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO; renderPassInfo.renderPass = &*render_passess; renderPassInfo.framebuffer = swapChainFramebuffers[i]; renderPassInfo.renderArea.offset = { 0, 0 }; renderPassInfo.renderArea.extent = extent.currentExtent; VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f }; renderPassInfo.clearValueCount = 1; renderPassInfo.pClearValues = &clearColor; vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, &*pipeline); h.draw(commandBuffers[i]); vkCmdEndRenderPass(commandBuffers[i]); vkEndCommandBuffer(commandBuffers[i]); } const int MAX_FRAMES_IN_FLIGHT = 2; std::vector<VkSemaphore> imageAvailableSemaphores(MAX_FRAMES_IN_FLIGHT); std::vector<VkSemaphore> renderFinishedSemaphores(MAX_FRAMES_IN_FLIGHT); std::vector<VkFence> inFlightFences(MAX_FRAMES_IN_FLIGHT); std::vector<VkFence> imagesInFlight(swapChainImages.size(), VK_NULL_HANDLE); VkFenceCreateInfo fenceInfo = {}; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; VkSemaphoreCreateInfo semaphoreInfo = {}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; for (int i = 0; i < inFlightFences.size(); ++i) { vkCreateSemaphore(&*device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]); vkCreateSemaphore(&*device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]); vkCreateFence(&*device, &fenceInfo, nullptr, &inFlightFences[i]); } size_t currentFrame = 0; while (true) { vkWaitForFences(&*device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX); auto imgIndex = waitAcquireNextImage(&*device, &*swapChain, imageAvailableSemaphores[currentFrame]); if (imagesInFlight[imgIndex] != VK_NULL_HANDLE) { vkWaitForFences(&*device, 1, &imagesInFlight[imgIndex], VK_TRUE, UINT64_MAX); } imagesInFlight[imgIndex] = inFlightFences[currentFrame]; VkSubmitInfo submitInfo = {}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; VkSemaphore waitSemaphores[] = { imageAvailableSemaphores[currentFrame] }; VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT }; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = waitSemaphores; submitInfo.pWaitDstStageMask = waitStages; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffers[imgIndex]; VkSemaphore signalSemaphores[] = { renderFinishedSemaphores[currentFrame] }; submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = signalSemaphores; vkResetFences(&*device, 1, &inFlightFences[currentFrame]); vkQueueSubmit(queue, 1, &submitInfo, inFlightFences[currentFrame]); queue << present(&*swapChain, imgIndex, renderFinishedSemaphores[currentFrame]); currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT; } return 0; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProcW(hwnd, msg, wParam, lParam); } return 0; } int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { const wchar_t className[] = L"windowClass"; WNDCLASSEXW wc; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wc.lpszMenuName = NULL; wc.lpszClassName = className; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); RegisterClassExW(&wc); HWND hWnd = CreateWindowExW( WS_EX_CLIENTEDGE, className, L"Game", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); LoopThreadParams p{ hInstance, hWnd }; DWORD dwThreadIdArray; HANDLE hThreadArray = CreateThread( NULL, 0, LoopThread, &p, 0, &dwThreadIdArray); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } DestroyWindow(hWnd); return 0; }
/** \file RendererOps.cpp * \author Eduardo Pinho ( enet4mikeenet AT gmail.com ) * \date 2013 */ #include "RendererOps.h" #include "MathUtils.h" #include <math.h> using namespace derplot; using namespace math; using namespace op; RendererOperation::~RendererOperation() { } int ViewPort::onDispatch( RendererProgram& prg) { prg.viewport = this->viewport; return 0; } int Ortho::onDispatch( RendererProgram& prg) { if ( this->near >= this->far || this->top == this->bottom || this->right == this->left) return 1; prg.proj = Mat4x4f::IDENTITY; math::scale( prg.proj, 2 / (right - left), 2 / (top - bottom), -2 / (far - near)); math::translate(prg.proj, -(right + left) / (right - left), -(top + bottom) / (top - bottom), (near + far) / (far - near)); return 0; } int Perspective::onDispatch( RendererProgram& prg) { if ( near >= far || fovy == 0.f || ratio <= 0.f) return false; const float ang = math::degrees2radians(this->fovy * 0.5f); const float f_len = this->far - this->near; const float y = 1.0f / tan(ang); const float x = y / this->ratio; const float l = -(this->far + this->near) / f_len; const float z = -2.0f * this->near * this->far / f_len; prg.proj = { x, 0, 0, 0, 0, y, 0, 0, 0, 0, l,-1, 0, 0, z, 0 }; return 0; } int MatrixSet::onDispatch( RendererProgram& prg) { if (this->type == 1) prg.proj = this->mat; else prg.modelview = this->mat; return 0; } int MatrixTranslate::onDispatch( RendererProgram& prg) { math::Mat4x4f& mat = (this->matrix == 1) ? prg.proj : prg.modelview; math::translate(mat, this->v); return 0; } int MatrixScale::onDispatch( RendererProgram& prg) { math::Mat4x4f& mat = (this->matrix == 1) ? prg.proj : prg.modelview; math::scale(mat, this->v); return 0; } int MatrixRotate::onDispatch( RendererProgram& prg) { math::Mat4x4f& mat = (this->matrix == 1) ? prg.proj : prg.modelview; switch (this->axis) { case 0: math::rotateAroundX(mat, this->ang); break; case 1: math::rotateAroundY(mat, this->ang); break; case 2: math::rotateAroundZ(mat, this->ang); break; default: ; } return 0; } int Clear::onDispatch( RendererProgram& prg) { return prg.raw_clear(); } int RawPoint::onDispatch( RendererProgram& prg) { if (type == 1) return prg.raw_drawBigPoint(this->point); return prg.raw_drawPoint(this->point); } int RawLine::onDispatch( RendererProgram& prg) { return prg.raw_drawLine(this->point1, this->point2); } int Line::onDispatch( RendererProgram& prg) { return prg.drawLine(this->point1, this->point2); } int Point::onDispatch( RendererProgram& prg) { if (type == 1) return prg.drawBigPoint(this->point); return prg.drawPoint(this->point); } int ClearColor::onDispatch( RendererProgram& prg) { prg.clear_color = this->color; return 0; } int FrontColor::onDispatch( RendererProgram& prg) { prg.front_color = this->color; return 0; }
// // Ship.cpp // GetFish // // Created by zs on 14-12-9. // // #include "Ship.h" #include "Fish.h" #include "Common.h" #include "Tools.h" #include "GameScene.h" //#include "AudioController.h" #define Z_HOOK 999 #define Z_TURN 1000 Ship* Ship::create(int type,int ID ,const char* name) { Ship* ship = new Ship(); if(ship && ship->init(type,ID,name)) { ship->autorelease(); return ship; } CC_SAFE_DELETE(ship); return NULL; } Ship::Ship():_type(TYPE_PLAYER),_timeC(0),_hit(0),_HOOK_MOVE_DISTANCE(0),_testTime(0),_noHurtTime(0),_hookCurAngle(0),_stopTime(0),_speed(10),_volume(0),_volumeMax(1000),_hoolSpeed(12),_hookSpeed(10),_score(0),_moveCD(120),_moveCD_MAX(120),_w_Fish(NULL),_getC(0),_getTime(0),_getTimeMax(0) { } Ship::~Ship() { if (_anims) { _anims->release(); _anims=NULL; } if (_fishSetHooked) { _fishSetHooked->release(); _fishSetHooked=NULL; } CC_SAFE_DELETE(_items); if (_TurnFish) { _TurnFish->release(); _TurnFish = NULL; } } bool Ship::init(int type,int ID ,const char* name) { if(Actor::init(name)) { _state = ACT_STAND; ANGLE_TAN.push_back(0); ANGLE_TAN.push_back(17); ANGLE_TAN.push_back(35); ANGLE_TAN.push_back(52); ANGLE_TAN.push_back(70); ANGLE_TAN.push_back(87); ANGLE_TAN.push_back(176); _anims = CCArray::create(); _anims -> retain(); _fishSetHooked = CCArray::create(); _fishSetHooked->retain(); _items = CCArray::create(); _items -> retain(); _TurnFish = CCArray::create(); _TurnFish -> retain(); _screenSize = CCDirector::sharedDirector()->getWinSize(); _HOOK_MOVE_DISTANCE = _screenSize.height-HOOK_DES; _type = type; setID(ID); if(type == TYPE_AI){ this->setScaleX(-1); } this->initData(); _ct = CCSprite::createWithSpriteFrameName("citieshi_23.png"); _ct->setPosition(ccp(0, getBodyRect().size.height*0.5)); _ct->setOpacity(0); addChild(_ct,999); // this->schedule(schedule_selector(Ship::cycle)); // this->setZOrder(-10); return true; } return false; } void Ship::addCTEffe() { _ct->setOpacity(255); _ct->setScale(0.2); CCFadeOut* out = CCFadeOut::create(0.5); CCScaleTo* st = CCScaleTo::create(0.5, 2); _ct->runAction(CCSequence::create(st,out,NULL)); } void Ship::initData() { setHook(_id); if (_type == TYPE_PLAYER) { _x =_screenSize.width/3; }else{ _x =_screenSize.width*2/3; } _y = _screenSize.height-SHIP_INIT_Y; this->setPosition(ccp(_x, _y)); runUpDown(); } void Ship::setGetTime(int time,int c){ _getC = c; _getTime = _getTimeMax = time; } void Ship::cycle(float delta) { if (_noHurtTime >0) { _noHurtTime--; // if((int)(_noHurtTime*0.3)%2 == 0){ // setVisible(false); // }else{ // setVisible(true); // } }else{ // if (!isVisible()) { // setVisible(true); // } } if (_type == TYPE_AI) { _moveCD--; if (_moveCD<=0) { _moveCD = _moveCD_MAX; setShipTo(Tools::randomIntInRange(_screenSize.width*0.2, _screenSize.width*0.8)); } if (_getC>0) { _getTime--; if (_getTime<=0) { _getC--; _getTime = _getTimeMax; GameScene::instance()->allFishToDead(1); } } } if (_state == ACT_WALK) { if (_x == _desX) { _state = ACT_STAND; } if (_x > _desX) { _dir = DIR_LEFT; if ((_x - _speed) < _desX) { _x = _desX; } else { _x -= _speed; if (_type == TYPE_PLAYER) { if (_x <= LEFT_BORDER) { _x = LEFT_BORDER; } } } } else if (_x < _desX) { _dir = DIR_RIGHT; if ((_x + _speed) > _desX) { _x = _desX; } else { _x += _speed; if (_type == TYPE_PLAYER) { if (_x >=_screenSize.width- RIGHT_BORDER) { _x =_screenSize.width- RIGHT_BORDER; } } } } }else if (_state == ACT_TURN_FISH){ _timeC++; if (_timeC%9==0) { bool ishasfish = false; for (int i = 0; i < _TurnFish->count(); ++i) { Fish* fish =(Fish*) _TurnFish->objectAtIndex(i); if (!fish->isState(Fish::ACT_STATE_TURN)) { fish->setVisible(true); fish->setState(Fish::ACT_STATE_TURN); fish->setXY(_x,_y+10); fish->setSpeedY(25); fish->playWithIndex(Fish::ANIM_TURN); CCRotateBy* action = CCRotateBy::create(1, -360); CCRepeatForever* repeat = CCRepeatForever::create(action); fish->runAction(repeat); _volume -= fish->getVolume(); ishasfish = true; _TurnFish->removeObject(fish); break; } } if (!ishasfish) { _volume = 0; _TurnFish->removeAllObjects(); } if (_volume <= 0) { _volume = 0; _state = ACT_STAND; _TurnFish->removeAllObjects(); } } }else if(_state == ACT_FLY){ if (_w_Fish) { if (_w_Fish->isState(Fish::ACT_STATE_ZHUANG_ATK)) { // CCDirector::sharedDirector()->getActionManager()->pauseTarget(this); this->stopAllActions(); _y =_w_Fish->getPositionY()+_w_Fish->getBone("whale")->getWorldInfo()->y; this->setPositionY(_y); }else{ // CCDirector::sharedDirector()->getActionManager()->resumeTarget(this); _w_Fish = NULL; runFall(); setState(ACT_FALL); } }else{ _w_Fish = NULL; runFall(); setState(ACT_FALL); } }else if(_state == ACT_FALL){ if (this->numberOfRunningActions()==0) { _y = _screenSize.height-SHIP_INIT_Y; this->setPositionY(_y); // CCDirector::sharedDirector()->getActionManager()->resumeTarget(this); setState(ACT_STAND); changeToNohurt(); runUpDown(); } }else if(_state == ACT_EATED){ _stopTime--; if (_stopTime<=0) { setState(ACT_STAND); changeToNohurt(); } }else if(_state == ACT_CUT_LINE){ _cut_Pos.y -= 2.5; _cut_hook.y -=2.5; _hook_anim->setPosition(_cut_hook); _stopTime--; if (_stopTime<=0) { initHook(); setState(ACT_STAND); changeToNohurt(); } }else if(_state == ACT_PULL){ if (_w_Fish!=NULL) { if (_w_Fish->getDir() == DIR_LEFT) { _hook_anim->setRotation(-60*this->getScaleX()); _hook_anim->setPosition(ccpAdd(ccp(_pull_pos.x*this->getScaleX(),_pull_pos.y), ccp(30*this->getScaleX(), -40))); }else{ _hook_anim->setRotation(60*this->getScaleX()); _hook_anim->setPosition(ccpAdd(ccp(_pull_pos.x*this->getScaleX(),_pull_pos.y), ccp(-30*this->getScaleX(), -40))); } }else{ _hook_anim->setPosition(ccp(_pull_pos.x*this->getScaleX(),_pull_pos.y)); } }else if(_state == ACT_ELE){ _stopTime -- ; if (_stopTime<=0) { playWithIndex(0); setState(ACT_STAND); changeToNohurt(); } } if (_state != ACT_SHOCKED &&_state != ACT_ELE && _state != ACT_PULL&& _state != ACT_CUT_LINE) { cycleHook(); } // if (_x >= 180 && _x < 190+_speed) { // if (_type == TYPE_PLAYER && _volume > 0) { // // setState(ACT_TURN_FISH); // } // } this->setPositionX(_x); } void Ship::addVolume(int v) { _volume += v; } bool Ship::isShipFull() { return this->_volume >= this->_volumeMax; } bool Ship::isCanMove() { return _state == ACT_WALK || _state == ACT_STAND; } bool Ship::isShipNormal() { return isCanMove() && _noHurtTime <= 0; } bool Ship::isPlayer() { return _type == TYPE_PLAYER; } void Ship::setState(int state) { _state = state; } void Ship::setDesX(float x) { _desX = x; } void Ship::setHook(int type) { if (_type == TYPE_AI) { _hook_anim =CCSprite::create(("ship/hook100.png")); }else{ _hook_anim =CCSprite::create(("ship/hook"+Tools::intToString(type-1)+".png").c_str()); } _hookDx = _hookInitDx = getBone("hook")->getWorldInfo()->x; _hookDy = _hookInitDy = getBone("hook")->getWorldInfo()->y; _hookDir = HOOK_DIR_UP; _bHasFishHooked = false; if (type == 1) { _hook_anim->setAnchorPoint(ccp(0.6, 1)); }else{ _hook_anim->setAnchorPoint(ccp(0.5, 1)); } _hook_anim->setPosition(ccp(_hookDx,_hookDy)); this->addChild(_hook_anim,Z_HOOK); // _hook_anim->getAnimation()->playByIndex(type); } void Ship::initHook() { _hookDx = _hookInitDx; _hookDy = _hookInitDy; _hookDir = HOOK_DIR_UP; _bHasFishHooked = false; _hook_anim->setPosition(ccp(_hookDx,_hookDy)); } void Ship::hookFish() { _bHasFishHooked = true; _hookDir = HOOK_DIR_UP; } void Ship::setNormal() { if (_state == ACT_SHOCKED || _state == ACT_FLY || _state == ACT_FALL || _state == ACT_FALL_END || _state == ACT_EATED || _state == ACT_CUT_LINE || _state == ACT_PULL) { _state = ACT_STAND; changeToNohurt(); } } void Ship::changeToNohurt() { CCFadeOut* out = CCFadeOut::create(0.1); CCFadeIn* in = CCFadeIn::create(0.1); CCSequence* sq = CCSequence::create(out,in,NULL); CCRepeat* re = CCRepeat::create(sq, 4); this->runAction(re); _hook_anim->setRotation(0); playWithIndex(ANIM_FISHMAN_NORMAL); _noHurtTime = NO_HURT_TIME_MAX; } void Ship::switchHookDir() { if (!_bHasFishHooked) { if (_hookDir == HOOK_DIR_UP) { _hookDir = HOOK_DIR_DOWN; // AUDIO->playSfx("music/fishingLineDown"); } else { _hookDir = HOOK_DIR_UP; } } } void Ship::clearHook() { _hookDir = HOOK_DIR_UP; _hookDy = _hookInitDy; } void Ship::setHookUp() { _hookDir = HOOK_DIR_UP; } bool Ship::isHookOver() { return _hookDir == HOOK_DIR_UP && _hookDy == _hookInitDy; } void Ship::cycleHook() { if (_bHasFishHooked) { if (_hookDir == HOOK_DIR_DOWN) { _hookDir = HOOK_DIR_UP; } _hookDy += _hookSpeed + _hookSpeed*0.5; if (_hookDy > _hookInitDy) { _hookDy = _hookInitDy; _hit = 0; reapFishSetHooked(); _bHasFishHooked = false; } } else { if (_hookDir == HOOK_DIR_UP) { _hookDy += _hookSpeed; if (_hookDy > _hookInitDy) { _hookDy = _hookInitDy; } } else if (_hookDir == HOOK_DIR_DOWN) { _hookDy -= _hookSpeed; if (_hookDy < _hookInitDy - _HOOK_MOVE_DISTANCE) { _hookDy = _hookInitDy - _HOOK_MOVE_DISTANCE; _hookDir = HOOK_DIR_UP; } } } if (_hookDy > _hookInitDy - _HOOK_MOVE_DISTANCE / 4) { _hookWaveType = HOOK_WAVE_NULL; _hookAngleType = ANGLE_NULL; } if (_state == ACT_WALK) { _hookWaveCount = 0; if (_dir == DIR_LEFT) { if (_hookAngleType == ANGLE_NULL) { _hookAngleType = ANGLE_PLUS; _hookWaveType = HOOK_WAVE_UP; } else if (_hookAngleType == ANGLE_PLUS) { _hookWaveType = HOOK_WAVE_UP; } } else if (_dir == DIR_RIGHT) { if (_hookAngleType == ANGLE_NULL) { _hookAngleType = ANGLE_MINUS; _hookWaveType = HOOK_WAVE_UP; } else if (_hookAngleType == ANGLE_MINUS) { _hookWaveType = HOOK_WAVE_UP; } } } if (_hookWaveCount < 5) { if (_hookWaveType == HOOK_WAVE_UP) { _hookCurAngle++; if (_hookCurAngle > ANGLE_5) { _hookCurAngle = ANGLE_5; _hookWaveType = HOOK_WAVE_DOWN; } } else if (_hookWaveType == HOOK_WAVE_DOWN) { _hookCurAngle--; if (_hookCurAngle <= ANGLE_0) { _hookCurAngle = ANGLE_0; _hookWaveCount++; if (_state == ACT_WALK) { if (_dir == DIR_LEFT) { _hookAngleType = ANGLE_PLUS; } else if (_dir == DIR_RIGHT) { _hookAngleType = ANGLE_MINUS; } } else { if (_hookAngleType == ANGLE_PLUS) { _hookAngleType = ANGLE_MINUS; } else if (_hookAngleType == ANGLE_MINUS) { _hookAngleType = ANGLE_PLUS; } } _hookWaveType = HOOK_WAVE_UP; } } else { _hookCurAngle = ANGLE_0; } } if (_hookCurAngle > ANGLE_0 && _hookCurAngle<ANGLE_TAN.size()) { float dx = (_hookInitDy-_hookDy) * ANGLE_TAN[_hookCurAngle] / 3000; if (_hookAngleType == ANGLE_MINUS) { _hookDx = _hookInitDx - dx; } else if (_hookAngleType == ANGLE_PLUS) { _hookDx = _hookInitDx + dx; } } else { _hookDx = _hookInitDx; } _hook_anim->setPosition(ccp(_hookDx, _hookDy)); } void Ship::draw() { Actor::draw(); if(_type == TYPE_AI){ ccDrawColor4B(0xff, 0xff, 0, 0xff); }else{ ccDrawColor4B(0xff, 0xff, 0xff, 0xff); } glLineWidth(2.0f); if(_state == ACT_CUT_LINE){ ccDrawLine(ccp(_hookInitDx, _hookInitDy), ccp(_hookDx, _cut_hook_y)); ccDrawLine(_cut_Pos, _cut_hook); }else if (_state == ACT_PULL){ ccDrawLine(ccp(_hookInitDx, _hookInitDy), ccp(_pull_pos.x*this->getScaleX(),_pull_pos.y)); ccDrawLine(ccp(_pull_pos.x*this->getScaleX(),_pull_pos.y),ccp(_hook_anim->getPositionX(),_hook_anim->getPositionY())); }else{ ccDrawLine(ccp(_hookInitDx, _hookInitDy), ccp(_hookDx, _hookDy)); } // // CCRect*rect =_hook_anim->bodyRectInWorld(); // // ccDrawRect(ccp(rect->origin.x, rect->origin.y), ccp(rect->origin.x+rect->size.width, rect->origin.y+rect->size.height)); } void Ship::hookFish(Fish* fish) { hookFish(); _fishSetHooked->addObject(fish); } void Ship::addItem(Item *it) { hookFish(); _items->addObject(it); } int Ship::getHookDx() { return _hookDx; } int Ship::getHookDy() { return _hookDy; } CCSprite* Ship::getHookAnim() { return _hook_anim; } bool Ship::isState(int state) { return _state == state; } void Ship::reapFishSetHooked(){ for (int i = 0; i < _fishSetHooked->count(); i++) { Fish* fish = (Fish*) _fishSetHooked->objectAtIndex(i); fish->setDead(true); fish->setDeadType(Fish::HOOK_DEAD); fish->setShipID(this->getType()); addVolume(fish->getVolume()); // trunFish(fish); _hit++; } _fishSetHooked->removeAllObjects(); for (int i = 0; i < _items->count(); ++i) { Item* item = (Item*) _items->objectAtIndex(i); item->setDead(); _hit++; } GameScene::instance()->addHitFish(_hit); _items->removeAllObjects(); } void Ship::trunFish(Fish* fish) { fish->setVisible(false); _TurnFish -> addObject(fish); } float Ship::getX() { return _x; } float Ship::getY() { return _y; } void Ship::setw_Fish(Fish *fish) { _w_Fish = fish; } Fish* Ship::getw_Fish() { return _w_Fish; } void Ship::runUpDown() { // CCMoveTo *move = CCMoveTo::create(0.6, CCPoint(_x, _y-2)); // CCMoveTo *move2 = CCMoveTo::create(0.3, CCPoint(_x, _y)); // CCMoveTo *move3 = CCMoveTo::create(0.3, CCPoint(_x, _y+2)); // CCMoveTo *move4 = CCMoveTo::create(0.3, CCPoint(_x, _y+4)); // CCMoveTo *move5 = CCMoveTo::create(0.3, CCPoint(_x, _y+2)); // CCMoveTo *move6 = CCMoveTo::create(0.3, CCPoint(_x, _y)); CCMoveBy* move = CCMoveBy::create(0.6, ccp(0, -2)); CCMoveBy* move2 = CCMoveBy::create(0.9, ccp(0, 6)); CCMoveBy* move3 = CCMoveBy::create(0.6, ccp(0, -4)); // CCMoveBy* move4 = CCMoveBy::create(0.3, ccp(0, 2)); CCSequence* sequence = CCSequence::create(move,move2,move3,NULL); CCRepeatForever* repeat = CCRepeatForever::create(sequence); this->runAction(repeat); } void Ship::runFall() { this->stopAllActions(); CCMoveTo* move = CCMoveTo::create(0.5, ccp(_x, _screenSize.height-SHIP_INIT_Y-20)); CCEaseIn* ease = CCEaseIn::create(move, 1); CCMoveTo *move2 = CCMoveTo::create(0.3, ccp(_x, _screenSize.height-SHIP_INIT_Y)); CCSequence* sequence = CCSequence::create(ease,move2,NULL); this->runAction(sequence); } void Ship::setShipTo(float px) { if (!isCanMove() ) { return; } if (isHookOver() && !isShipFull()) { switchHookDir(); } setState(Ship::ACT_WALK); setDesX(px); } void Ship::hook() { if (isHookOver() && !isShipFull()) { switchHookDir(); } } void Ship::setShipToNoHook(float px) { if (!isCanMove() ) { return; } setState(Ship::ACT_WALK); setDesX(px); } void Ship::setStop(float time) { _stopTime = time; } void Ship::shipOnAtk() { _bHasFishHooked = false; for (int i = 0; i < _fishSetHooked->count(); ++i) { Fish* fish = (Fish*) _fishSetHooked->objectAtIndex(i); fish->setState(Fish::ACT_STATE_NORMAL); fish->setGo(); } _fishSetHooked->removeAllObjects(); for (int i = 0; i < _items->count(); ++i) { Item* item = (Item*) _items->objectAtIndex(i); item->setDead(); } _items->removeAllObjects(); } CCPoint Ship::getEatPos() { return CCPointMake(getPositionX()+ getBone("eat")->getWorldInfo()->x*this->getScaleX(),getPositionY()+ getBone("eat")->getWorldInfo()->y*this->getScaleY()); } void Ship::setCutHookPos() { _cut_hook = CCPointMake(_hookDx, _hookDy); } void Ship::setCutHookY(float y) { _cut_hook_y = y-_y; _cut_Pos = CCPointMake(_hookDx, _cut_hook_y); } CCRect Ship::getHookLine() { // CCLOG("fl : %i",abs( _hookDx-_hookInitDx)); return CCRectMake(((_hookInitDx<_hookDx?_hookInitDx:_hookDx)*this->getScaleX()+_x), _hookDy+_y,Tools::int_abs( _hookDx-_hookInitDx), _hookInitDy-_hookDy); } CCRect Ship::getHookBody() { return CCRectMake(getPositionX()+(getHookAnim()->boundingBox().origin.x*getScaleX()), getPositionY()+getHookAnim()->boundingBox().origin.y, getHookAnim()->boundingBox().size.width, getHookAnim()->boundingBox().size.height); } void Ship::setPullPos(cocos2d::CCPoint pos) { _pull_pos = pos; } void Ship::setX(float x) { _x = x; setPositionX(_x); } void Ship::setY(float y) { _y = y; setPositionY(_y); } void Ship::setXY(float x, float y) { _x = x; _y = y; setPosition(_x, _y); } void Ship::addScore(int sc) { _score+=sc; } int Ship::getType() const { return _type; } int Ship::getHookDir() const { return _hookDir; } void Ship::setMoveCD(int cd) { _moveCD = _moveCD_MAX = cd; }
int btn = 2; int led = 11; int teller; long currentTid; long tidsLimit; int ledStatus = LOW; void setup() { Serial.begin(9600); pinMode(btn, INPUT); pinMode(led, OUTPUT); } void loop() { int knappVerdi = digitalRead(btn); if (knappVerdi == 1){ delay(200); Serial.println("Trykket"); if (teller == 0) { currentTid = millis(); tidsLimit = currentTid + 600; teller = 1; } else if (teller == 1 && millis() < tidsLimit){ Serial.println("To ganger"); styrLys(); currentTid = 0; tidsLimit = 0; teller = 0; } } if (teller == 1 && tidsLimit != 0 && millis() > tidsLimit){ Serial.println("En gang"); currentTid = 0; tidsLimit = 0; teller = 0; } } void styrLys() { if(ledStatus == LOW) { digitalWrite(led, HIGH); ledStatus = HIGH; } else if(ledStatus == HIGH){ digitalWrite(led, LOW); ledStatus = LOW; } }
// Автор: Николай Левшин #include "RegisterMap.h" namespace RegisterAllocation { CRegisterMapBuilder::CRegisterMapBuilder( int k, const CInterferenceGraphBuilder::CInterferenceGraph& interferenceGraph ) : k( k ), sourceInterferenceGraph( interferenceGraph ) {} void CRegisterMapBuilder::Build() { // Упрощаем граф, скидывая вершины на стек while( temporaryInterferenceGraph.GetSize() != 0 ) { if( !Simplify() ) { isColored = false; return; } } // Красим вершины, снимая их со стека while( !vertStack.empty() ) { // Добавляем вершину в уже покрашеный граф temporaryInterferenceGraph.AddVertice( vertStack.top() ); // Восстанавливаем ребра с уже покрашенными вершинами for( const auto& vert : sourceInterferenceGraph.GetNeigbours( vertStack.top() ) ) { if( temporaryInterferenceGraph.HasVetrice( vert ) ){ temporaryInterferenceGraph.AddEdge( vertStack.top(), vert ); } } // Выбираем цвет, которого нет у соседей ChooseColor( vertStack.top() ); vertStack.pop(); } isColored = true; } bool CRegisterMapBuilder::Simplify() { bool isSimpleable = false; Temp::CTemp removeVert; for( const auto& vert : temporaryInterferenceGraph.GetVertices() ) { if( temporaryInterferenceGraph.GetDegree( vert ) < k ) { removeVert = vert; isSimpleable = true; break; } } if( isSimpleable ) { temporaryInterferenceGraph.RemoveVertice( removeVert ); vertStack.push( removeVert ); return true; } return false; } void CRegisterMapBuilder::ChooseColor( Temp::CTemp& vert ) { std::vector<bool> avaliableColors (k, true); // Смотрим, какие цвета заняты for( auto &vert : temporaryInterferenceGraph.GetNeigbours( vert ) ) { avaliableColors[colorMap[vert]] = false; } // Выбираем доступный цвет int color = 0; while( !avaliableColors[color] ) { ++color; } colorMap.insert( std::make_pair(vert, color) ); } std::unordered_map<Temp::CTemp, int>& CRegisterMapBuilder::GetMap() { assert( isColored ); return colorMap; } }
#ifndef ODBCSTATEMENT_HH #define ODBCSTATEMENT_HH #include <memory> #include <cstring> #include <nan.h> #include "ODBCConnection.hh" #include "ConnectionAwareStatement.hh" #include "SafeUnwrap.hh" namespace NC { using NC::ConnectionAwareStatement; using NC::SafeUnwrap; class ODBCStatement final : public Nan::ObjectWrap { public: using value_type = ConnectionAwareStatement; static NAN_MODULE_INIT(Init); static std::shared_ptr<value_type> Unwrap(v8::Local<v8::Object> self) { return SafeUnwrap<ODBCStatement>::Unwrap(self)->statement; } explicit ODBCStatement( std::shared_ptr<UVMonitor<nanodbc::connection>> connection); ODBCStatement(const ODBCStatement&) = delete; ODBCStatement(ODBCStatement&&) = delete; virtual ~ODBCStatement() = default; private: friend struct SafeUnwrap<ODBCStatement>; static const char* js_class_name; static Nan::Persistent<v8::FunctionTemplate> js_constructor; static NAN_METHOD(JsNew); static NAN_METHOD(JsQuery); static NAN_METHOD(JsExecute); static NAN_METHOD(JsPrepare); static NAN_METHOD(JsClose); static NAN_METHOD(JsOpen); std::shared_ptr<ConnectionAwareStatement> statement; }; } // namespace NC #endif /* ODBCSTATEMENT_HH */
#include <iostream> #include "calendar.h" int main() { int roky[5] = {1000, 2000, 2002, 2004, 2014}; for (int i = 0; i < 5; i++) { printf("Rok %d %s prestupny \n", roky[i], jePrestupny(roky[i]) == 1 ? "je" : "neni"); } for (int i = 1; i <= 12; i++) { printf("Mesic %d je %s sudy\n", i, jeSudyMesic(i) ? "je" : "neni"); } }
#include<stdio.h> int main() { int e[10][10], k, i, j, n, m, t1, t2, t3; int inf = 99999999; //用inf存储一个我们认为的无穷值 //读入n和m,n表示顶点个数,m表示边的条数 scanf("%d %d", &n, &m); //初始化 for(i = 0; i <= n; i++) for(j = 0; j <= n; j++) if(i == j) e[i][j] = 0; else e[i][j] = inf; //读入边 for(i = 1; i <= m; i++) { scanf("%d %d %d", &t1, &t2, &t3); e[t1][t2] = t3; } //Floyd-Warshall算法核心语句 for(k = 1; k <= n; k++) for(i = 1; i <= n; i++) for(j = 1; j <= n; j++) if(e[i][j] > e[i][k] + e[k][j]) e[i][j] = e[i][k] + e[k][j]; //输出最终结果 for(i = 1; i <= n; i++) { for(j = 1; j <= n; j++) { printf("%10d", e[i][j]); } printf("\n"); } return 0; }