text
stringlengths
8
6.88M
#include <iostream> #include <vector> #include <unordered_map> /**https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem */ using namespace std; struct record { int counter = 0; int currentScore = 0; } high, low; vector<int> breakingRecord(vector<int> scores) { // Assign first scores high.currentScore = scores.front(); low.currentScore = scores.front(); // Atart at i = 1, since we want to count high and low after first attempt. for(int i=1 ;i < scores.size(); i++) { if(scores.at(i) > high.currentScore) { high.currentScore = scores.at(i); high.counter += 1; } if(scores.at(i) < low.currentScore) { low.currentScore = scores.at(i); low.counter += 1; } } return {high.counter, low.counter}; } int main() { vector<int> input1 = {3, 4, 21, 36, 10, 28, 35, 5, 24, 42}; // vector<int> input2 ={ 10, 5, 20, 20, 4, 5, 2, 25, 1}; for(auto &x : breakingRecord(input1)) { cout << x << endl; } return 0; }
#include "VirtualScreen.h" VirtualScreen::VirtualScreen(unsigned int width, unsigned int height) { create(width, height); initialize(); } /// Draws the sprite at a given location in the game world. This location is /// dependent on the implementation within a VirtualScreen subclass. void VirtualScreen::worldDraw(sf::Sprite& sprite, const sf::Vector2f& position) { // The sprite's old positon doesn't matter, but it will be restored after // drawing const sf::Vector2f& oldPosition = sprite.getPosition(); // Perform a class-specific conversion from world coordinates to pixel // coordinates sprite.setPosition(getPixelPosition(position)); draw(sprite); // Restore the old position sprite.setPosition(oldPosition); } /// Draws the sprite at an exact pixel location on the VirtualScreen void VirtualScreen::pixelDraw(sf::Sprite& sprite, const sf::Vector2f& position) { // The sprite's old positon doesn't matter, but it will be restored after // drawing const sf::Vector2f& oldPosition = sprite.getPosition(); sprite.setPosition(position); draw(sprite); // Restore the old position sprite.setPosition(oldPosition); } /// Converts a game world positon into an absolute pixel position. This /// position is dependent on class'/subclass' implementation. sf::Vector2f VirtualScreen::getPixelPosition(const sf::Vector2f& worldPosition) { return worldPosition; }
#ifndef KMINT_UFO_ANDRE_HPP #define KMINT_UFO_ANDRE_HPP #include "kmint/map/map.hpp" #include "kmint/play.hpp" #include "kmint/primitives.hpp" namespace kmint::ufo { class andre : public play::map_bound_actor { public: andre(map::map_graph& g, map::map_node& initial_node); // wordt elke game tick aangeroepen void act(delta_time dt) override; ui::drawable const& drawable() const override { return drawable_; } // als incorporeal false is, doet de actor mee aan collision detection bool incorporeal() const override { return false; } // geeft de lengte van een zijde van de collision box van deze actor terug. // Belangrijk voor collision detection scalar collision_range() const override { return 16.0; } // geeft aan dat andré andere actors kan zien bool perceptive() const override { return true; } private: // hoeveel tijd is verstreken sinds de laatste beweging delta_time t_since_move_{}; // weet hoe de koe getekend moet worden play::image_drawable drawable_; }; } // namespace kmint::ufo #endif /* KMINT_UFO_ANDRE_HPP */
#ifdef __STRICT_ANSI__ #undef __STRICT_ANSI__ #endif #include <iostream> #include <gtest/gtest.h> #include <libprecision/libprecision.hpp> #include <bitset> #include <string> std::string operator*(const std::string &left, const int &right) { std::string ret; for(int i = 0; i < right; ++i) ret += left; return ret; } using namespace prec; const std::size_t test_precision = 128; const std::string test_bs_string = std::string("10")*(test_precision/2); std::bitset<test_precision> test_bs{test_bs_string}; #include "UnsignedInteger.hpp" int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <stack> using namespace std; int maxSubArray(int A[], int n){ if(n == 0) return 0; int local =A[0]; int global =A[0]; for(int i=1;i<n;i++){ local = max(A[i],local+A[i]); global = max(local,global); } return global; } int main(){ int b; vector<int> res; while(cin >> b){ res.push_back(b); } int a[res.size()]; for(int i=0;i<res.size();i++){ a[i] = res[i]; } int resnum = maxSubArray(a,res.size()); for(int i=0;i<res.size();i++) cout << a[i] <<" "; cout << "Res: " <<resnum<<endl; }
/* * angleblocker.cpp * deflektor-ds * * Created by Hugh Cole-Baker on 1/18/09. * */ #include <nds.h> #include "angleblocker.h" AngleBlocker::AngleBlocker(int bg, int x, int y, unsigned int palIdx, unsigned int tile, BeamDirection setAngle) : SpinBlocker(bg, x, y, palIdx, tile, setAngle), destroyed(false) { angle = (setAngle & 7); drawUpdate(); } void AngleBlocker::drawUpdate() { volatile u16* mapPtr = (volatile u16*)bgGetMapPtr(bgHandle); if(destroyed) { mapPtr[pos2idx(xPos*2, yPos*2)] = 0; mapPtr[pos2idx(xPos*2+1, yPos*2)] = 0; mapPtr[pos2idx(xPos*2, yPos*2+1)] = 0; mapPtr[pos2idx(xPos*2+1, yPos*2+1)] = 0; } else { mapPtr[pos2idx(xPos*2, yPos*2)] = ((paletteIndex << 12) | (tileBase+angle*4)); mapPtr[pos2idx(xPos*2+1, yPos*2)] = ((paletteIndex << 12) | (tileBase+1+angle*4)); mapPtr[pos2idx(xPos*2, yPos*2+1)] = ((paletteIndex << 12) | (tileBase+2+angle*4)); mapPtr[pos2idx(xPos*2+1, yPos*2+1)] = ((paletteIndex << 12) | (tileBase+3+angle*4)); } } BeamResult AngleBlocker::beamEnters(unsigned int x, unsigned int y, BeamDirection atAngle) { BeamResult res; if(destroyed) { res.action = Pass; } else { res = SpinBlocker::beamEnters(x, y, atAngle); } return res; } void AngleBlocker::destroy() { destroyed = true; drawUpdate(); }
#include <PubSubClient.h> #include <WiFi.h> #include "esp_wifi.h" #include <ESPmDNS.h> #include <WiFiUdp.h> #include <ArduinoOTA.h> #include <Preferences.h> #include <ArduinoJson.h> // Placeholder for ssid and password read from ram const char* key_ssid = "ssid"; const char* key_pwd = "pass"; WiFiClient espClient; PubSubClient client(espClient); Preferences preferences; // Add your MQTT Broker IP address, example: const char* mqtt_server = "10.0.0.2"; // Status messages char* puzzleSolved_message = "{\"method\": \"status\", \"state\": \"solved\"}"; char* puzzleActive_message = "{\"method\": \"status\", \"state\": \"active\"}"; char* puzzleInactive_message = "{\"method\": \"status\", \"state\": \"inactive\"}"; StaticJsonDocument<300> mqtt_decoder; #define S1 17 #define S2 16 #define S3 5 #define S4 18 #define S5 27 #define S6 14 #define S7 13 #define S8 12 #define LED_S_SOLVED 32 #define LED_V_SOLVED 23 #define MEASUREMENT_PIN A0 #define LOWER_THRESHOLD 500 #define HIGHER_THRESHOLD 700 #define AMOUNT_CORRECT_MEAS 5 #define WIFI_TIMEOUT_MS 3000 typedef enum { STATE_INACTIVE = 0, STATE_ACTIVE = 1, STATE_SOLVED = 2, } puzzle_states; typedef enum { VOLT_SOLVED = 1, VOLT_NOT_SOLVED = 0, } voltage_states; typedef enum { SWITCH_SOLVED = 1, SWITCH_NOT_SOLVED = 0, } switch_states; unsigned char switch_status; unsigned char voltage_status; unsigned char puzzle_status; unsigned int adc_val; unsigned int s1_val; unsigned int s2_val; unsigned int s3_val; unsigned int s4_val; unsigned int s5_val; unsigned int s6_val; unsigned int s7_val; unsigned int s8_val; unsigned int adc_correct_value; void setup() { switch_status = SWITCH_NOT_SOLVED; voltage_status = VOLT_NOT_SOLVED; puzzle_status = STATE_ACTIVE; adc_val = 0; s1_val = 0; s2_val = 0; s3_val = 0; s4_val = 0; s5_val = 0; s6_val = 0; s7_val = 0; s8_val = 0; adc_correct_value = 0; // Init ADC GPIO pinMode(A0,INPUT); // Init GPIO for checking the switches pinMode(S1,INPUT_PULLUP); pinMode(S2,INPUT_PULLUP); pinMode(S3,INPUT_PULLUP); pinMode(S4,INPUT_PULLUP); pinMode(S5,INPUT_PULLUP); pinMode(S6,INPUT_PULLUP); pinMode(S7,INPUT_PULLUP); pinMode(S8,INPUT_PULLUP); pinMode(LED_S_SOLVED,OUTPUT); digitalWrite(LED_S_SOLVED,HIGH); pinMode(LED_V_SOLVED,OUTPUT); digitalWrite(LED_V_SOLVED, HIGH); Serial.begin(9600); setup_wifi(); initOTA(); client.setServer(mqtt_server, 1883); client.setCallback(callback); } void loop() { // Debug output current state //Serial.print("Current State:"); Serial.println(puzzle_status); // Always connect to the mqqt server connect_mqqt(); if(puzzle_status == STATE_ACTIVE){ // Check wether puzzle are solved voltage_status = check_voltage(); switch_status = check_switches(); // Publish solved Message once if both parts are solved if(!(puzzle_status == STATE_SOLVED)){ if(voltage_status && switch_status){ Serial.println("Both puzzles solved"); client.publish("5/safe/activate", puzzleSolved_message, true); puzzle_status = STATE_SOLVED; } } } ArduinoOTA.handle(); } // Function returning 1 when switches are in the correct position unsigned int check_switches(){ s1_val = digitalRead(S1); s2_val = digitalRead(S2); s3_val = digitalRead(S3); s4_val = digitalRead(S4); s5_val = digitalRead(S5); s6_val = digitalRead(S6); s7_val = digitalRead(S7); s8_val = digitalRead(S8); /* // Debug output Serial.print("S1: "); Serial.println(s1_val); Serial.print("S2: "); Serial.println(s2_val); Serial.print("S3: "); Serial.println(s3_val); Serial.print("S4: "); Serial.println(s4_val); Serial.print("S5: "); Serial.println(s5_val); Serial.print("S6: "); Serial.println(s6_val); Serial.print("S7: "); Serial.println(s7_val); Serial.print("S8: "); Serial.println(s8_val); */ // If switches are in the correct position set status LED to High if(!s2_val && !s3_val && !s6_val && !s8_val && s1_val && s4_val && s5_val && s7_val){ Serial.println("Puzzle Switches Solved"); delay(200); digitalWrite(LED_S_SOLVED,HIGH); return SWITCH_SOLVED; } else{ delay(200); digitalWrite(LED_S_SOLVED,LOW); return SWITCH_NOT_SOLVED; } } // returns 1 when sensing the correct voltage unsigned int check_voltage(){ adc_val = analogRead(A0); // Debug output //Serial.print("ADC VAL: "); Serial.println(adc_val); // Turn on led and return 1 if measured voltage is between Thresholds if((adc_val < HIGHER_THRESHOLD) && (adc_val > LOWER_THRESHOLD)){ adc_correct_value = adc_correct_value + 1; // Only return solved when there are a least 5 consecutive measurements in the right voltage range if(adc_correct_value > AMOUNT_CORRECT_MEAS){ digitalWrite(LED_V_SOLVED,HIGH); Serial.println("Puzzle Voltage Solved"); adc_correct_value = 0; return VOLT_SOLVED; } else{ return VOLT_NOT_SOLVED; } } else{ digitalWrite(LED_V_SOLVED,LOW); adc_correct_value = 0; return VOLT_NOT_SOLVED; } return VOLT_NOT_SOLVED; } void setup_wifi() { delay(10); // Connect to selected WiFi Network Serial.println(); Serial.print("Connecting"); int timeout_start = millis(); char ssid[30]; char wlan_password[30]; preferences.begin("wifi", false); // Get password and ssid from ram preferences.getString(key_pwd, wlan_password, 30); preferences.getString(key_ssid, ssid, 30); preferences.end(); WiFi.begin(ssid, wlan_password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); // Restart ESP when no connection to the Network is established if (timeout_start + WIFI_TIMEOUT_MS < millis()) { ESP.restart(); } } // Turn LED off to signalise that the device is connected to the Network digitalWrite(LED_S_SOLVED,LOW); digitalWrite(LED_V_SOLVED, LOW); Serial.println(""); Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void initOTA() { ArduinoOTA.setHostname("5/safe_activation"); ArduinoOTA .onStart([]() { String type; if (ArduinoOTA.getCommand() == U_FLASH) type = "sketch"; else // U_SPIFFS type = "filesystem"; // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() Serial.println("Start updating " + type); }) .onEnd([]() { Serial.println("\nEnd"); }) .onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }) .onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); } // Mqqt callback function void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Received message ["); Serial.print(topic); Serial.print("] "); char msg[length+1]; for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); msg[i] = (char)payload[i]; } Serial.println(); msg[length] = '\0'; Serial.println(msg); // Deserialzie messafe deserializeJson(mqtt_decoder, msg); const char* method_msg = mqtt_decoder["method"]; const char* state_msg = mqtt_decoder["state"]; const char* data_msg = mqtt_decoder["data"]; Serial.println(method_msg); Serial.println(state_msg); Serial.println(strcmp(method_msg, "trigger") == 0); Serial.println(strcmp(state_msg, "on") == 0); // If trigger on message was sended if(strcmp(topic, "5/safe/activate") == 0 && strcmp(method_msg, "trigger") == 0 && strcmp(state_msg, "on") == 0){ puzzle_status = STATE_ACTIVE; client.publish("5/safe/activate", puzzleActive_message, true); } // If trigger off message was sended if(strcmp(topic, "5/safe/activate") == 0 && strcmp(method_msg, "trigger") == 0 && strcmp(state_msg, "off") == 0){ puzzle_status = STATE_INACTIVE; client.publish("5/safe/activate", puzzleInactive_message, true); } } // Function connecting to the mqqt server and suscribing the topic void connect_mqqt(){ client.loop(); while (!client.connected()){ Serial.println("no connection"); client.connect("SafeActivation"); client.subscribe("5/safe/activate"); } }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} int dp[55][10050][55]={0}; int main() { int w, n, k; cin >> w >> n >> k; vector<P> a(n+1); rep(i, n){ cin >> a[i].first >> a[i].second;} //dp[i][j][k] : j番目までのソフト幅にi番目までのスクショをはる時の価値最大 //dp[i][j] = max(dp[i-1][j-a[i]]+b[i], dp[i-1][j]) //dp[0][j] = 0; //dp[i][0] = 0; rep(i,n){ rep(j,w+1){ rep(r, k){ if (j < a[i].first){ dp[i+1][j][r] = dp[i][j][r]; } else { dp[i+1][j][r+1] = max(dp[i][j-a[i].first][r]+a[i].second, dp[i][j][r+1]); } } } } // rep(i,n+1){ // rep(j,w+1){ // cout << dp[i][j][k] << " "; // } // cout << endl; // } int ans = 0; rep1(r, k) ans = max(ans, dp[n][w][r]); cout << ans << endl; }
#include <Servo.h> /* pins */ const uint8_t vref_pin = A1; const uint8_t az_pin = 2; const uint8_t z45out_pin = A3; const uint8_t servo_pin = 9; const uint8_t led_pin = 13; Servo servo; uint8_t angle = 90; const uint8_t min_angle = 25; const uint8_t max_angle = 155; /* values in mv */ double vref_mv; double z_mv; double z_val = 0; double z_cal = 0; uint8_t az_cnt = 0; bool led_on = false; uint8_t led_cnt = 0; void TC7_Handler (void) { uint32_t status; status = TC2->TC_CHANNEL[1].TC_SR; if (led_cnt == 0) return; led_on = !led_on; digitalWrite(led_pin, led_on); if (!led_on) --led_cnt; } void TC8_Handler (void) { uint32_t status; status = TC2->TC_CHANNEL[2].TC_SR; vref_mv = analogRead(vref_pin) * 5000.0/1024.0; z_mv = analogRead(z45out_pin) * 5000.0/1024.0; z_val = ((z_mv - vref_mv) / 9.1 - z_cal) / 40; /* Faktor ? */ angle = angle + z_val; if (angle < 25) { led_cnt = 3; angle = 25; } else if (angle > 155) { led_cnt = 3; angle = 155; } servo.write(angle); } void setup() { uint32_t cmr7_val = 0; uint32_t cmr8_val = 0; pmc_set_writeprotect(false); pmc_enable_periph_clk(ID_TC7); pmc_enable_periph_clk(ID_TC8); /* configure TC7 */ cmr7_val |= TC_CMR_WAVE; /* waveform mode */ cmr7_val |= TC_CMR_WAVSEL_UP_RC; /* counting up until eq RC */ cmr7_val |= TC_CMR_TCCLKS_TIMER_CLOCK3; /* MCK/32 */ TC2->TC_CHANNEL[1].TC_RC = 262500; /* set RC val */ TC_Configure(TC2, 1, cmr7_val); TC2->TC_CHANNEL[1].TC_IER = TC_IER_CPCS; /* enable rc cmp interrupt */ TC2->TC_CHANNEL[1].TC_IDR = ~TC_IER_CPCS; /* not disable rc cmp interrupt */ /* configure TC8 */ cmr8_val |= TC_CMR_WAVE; /* waveform mode */ cmr8_val |= TC_CMR_WAVSEL_UP_RC; /* counting up until eq RC */ cmr8_val |= TC_CMR_TCCLKS_TIMER_CLOCK3; /* MCK/32 */ TC2->TC_CHANNEL[2].TC_RC = 131250; /* set RC val */ TC_Configure(TC2, 2, cmr8_val); TC2->TC_CHANNEL[2].TC_IER = TC_IER_CPCS; /* enable rc cmp interrupt */ TC2->TC_CHANNEL[2].TC_IDR = ~TC_IER_CPCS; /* not disable rc cmp interrupt */ /* enable interrupts */ NVIC_ClearPendingIRQ(TC7_IRQn); NVIC_EnableIRQ(TC7_IRQn); NVIC_ClearPendingIRQ(TC8_IRQn); NVIC_EnableIRQ(TC8_IRQn); /* start timer */ TC_Start(TC2, 1); TC_Start(TC2, 2); /* configure i/o pins */ pinMode(vref_pin, INPUT); pinMode(az_pin, OUTPUT); pinMode(z45out_pin, OUTPUT); pinMode(led_pin, OUTPUT); digitalWrite(az_pin, LOW); digitalWrite(led_pin, LOW); delay(6); vref_mv = analogRead(vref_pin) * 5000.0/1024.0; z_mv = analogRead(z45out_pin) * 5000.0/1024.0; z_cal = (z_mv - vref_mv) / 9.1; /* configure servo */ pinMode(servo_pin, OUTPUT); servo.attach(servo_pin); servo.write(90); Serial.begin(9600); Serial.println("setup done"); } void loop() { delay(200); Serial.print("vref: "); Serial.print(vref_mv); Serial.print(" z: "); Serial.print(z_val); Serial.print(" angle: "); Serial.print(angle); Serial.print('\n'); }
// ----------------------------------------------------------------------------- // G4Basic | RunAction.h // // // * Author: Everybody is an author! // * Creation date: 15 Aug 2019 // ----------------------------------------------------------------------------- #include "RunAction.h" // Q-Pix includes #include "AnalysisManager.h" #include "MCTruthManager.h" // GEANT4 includes #include "G4Box.hh" #include "G4LogicalVolumeStore.hh" #include "G4Run.hh" RunAction::RunAction(): G4UserRunAction()//, Detector_Geometry_("APA") { messenger_ = new G4GenericMessenger(this, "/Inputs/"); messenger_->DeclareProperty("root_output", root_output_path_, "path to output ROOT file"); } RunAction::~RunAction() { delete messenger_; } void RunAction::BeginOfRunAction(const G4Run* run) { G4cout << "RunAction::BeginOfRunAction: Run #" << run->GetRunID() << " start." << G4endl; // get run number AnalysisManager * analysis_manager = AnalysisManager::Instance(); analysis_manager->Book(root_output_path_); analysis_manager->SetRun(run->GetRunID()); // reset event variables analysis_manager->EventReset(); // get MC truth manager MCTruthManager * mc_truth_manager = MCTruthManager::Instance(); // reset event in MC truth manager mc_truth_manager->EventReset(); } void RunAction::EndOfRunAction(const G4Run*) { // get analysis manager AnalysisManager * analysis_manager = AnalysisManager::Instance(); // get detector dimensions G4LogicalVolume* detector_logic_vol = G4LogicalVolumeStore::GetInstance()->GetVolume("detector.logical"); if (detector_logic_vol) { analysis_manager->FillMetadata(777., 777., 777.); // if (Detector_Geometry_ == "APA") // {G4Box * detector_solid_vol // = dynamic_cast<G4Box*>(detector_logic_vol->GetSolid()); // double const detector_length_x = detector_solid_vol->GetXHalfLength() * 2. / CLHEP::cm; // double const detector_length_y = detector_solid_vol->GetYHalfLength() * 2. / CLHEP::cm; // double const detector_length_z = detector_solid_vol->GetZHalfLength() * 2. / CLHEP::cm; // // save detector dimensions as metadata // analysis_manager->FillMetadata(detector_length_x, // detector_length_y, // detector_length_z); // } // else // { // analysis_manager->FillMetadata(777., // 777., // 777.); // } } // save run to ROOT file analysis_manager->Save(); }
#include <Arduino.h> #include <TimerOne.h> #include "a_car.h" double x=0; void Motor_Init() { pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT); pinMode(PWMA, OUTPUT); pinMode(BIN1, OUTPUT); pinMode(BIN2, OUTPUT); pinMode(PWMB, OUTPUT); } void motor(double left , double right) { x=left; left=right; right=x; ////////////////////////左轮方向控制//////////////////////////// if (left > 0) { digitalWrite(AIN1, HIGH); digitalWrite(AIN2, LOW); } else if (left < 0) { digitalWrite(AIN1, LOW); digitalWrite(AIN2, HIGH); left = -left; } else { digitalWrite(AIN1, LOW); digitalWrite(AIN2, LOW); } ////////////////////////右轮方向控制//////////////////////////// if (right > 0) { digitalWrite(BIN1, HIGH); digitalWrite(BIN2, LOW); } else if (right < 0) { digitalWrite(BIN1, LOW); digitalWrite(BIN2, HIGH); right = -right; } else { digitalWrite(BIN1, LOW); digitalWrite(BIN2, LOW); } ////////////////////////速度控制//////////////////////////// analogWrite(PWMA, left*2.55); analogWrite(PWMB, right*2.55); }
#include "game_object_visitor.hpp" #include "asteroid.hpp" #include "bullet.hpp" #include "game.hpp" #include "player.hpp" #include "scrolling_bg.hpp" #include "spawn_point.hpp" // --------------------------------------------------------------------------------- // updating game_object::status game_object_updater::update(game_proxy proxy, std::chrono::milliseconds delta, game_object& obj) { auto updater = game_object_updater{proxy, delta}; obj.accept(updater); return updater.status_; } void game_object_updater::visit(asteroid& obj) { obj.pos() += obj.vel(); const auto center_offset = sgfx::vec{obj.img().width(), obj.img().height()} / 2; const auto area = proxy_.area(); if ((obj.pos().x - center_offset.x > area.top_left.x + area.size.w && obj.vel().x > 0) || (obj.pos().x + center_offset.x < area.top_left.x && obj.vel().x < 0) || (obj.pos().y - center_offset.y > area.top_left.y + area.size.h && obj.vel().y > 0) || (obj.pos().y + center_offset.y < area.top_left.y && obj.vel().y < 0)) status_ = game_object::status::dead; else status_ = obj.current_status(); } void game_object_updater::visit(bullet& obj) { if (delta_ >= obj.remaining_lifetime()) status_ = game_object::status::dead; else { obj.pos() += obj.vel(); obj.remaining_lifetime() -= delta_; status_ = game_object::status::alive; } } void game_object_updater::visit(player& obj) { obj.current_status() = player::state::normal; if (proxy_.is_pressed(obj.keys().left)) { --obj.pos().x; obj.current_status() = player::state::flying_left; } if (proxy_.is_pressed(obj.keys().right)) { ++obj.pos().x; obj.current_status() = player::state::flying_right; } if (proxy_.is_pressed(obj.keys().up)) --obj.pos().y; if (proxy_.is_pressed(obj.keys().down)) ++obj.pos().y; if (proxy_.is_pressed(obj.keys().shoot) && obj.space_released()) { obj.space_released() = false; proxy_.spawn<bullet>(obj.get_resource_manager().rle("img/missile.rle"), obj.pos() - sgfx::vec{0, 50}); } else if (!proxy_.is_pressed(obj.keys().shoot)) { obj.space_released() = true; } const auto& current_img = obj.img(obj.current_status()); const auto center_offset = sgfx::vec{current_img.width(), current_img.height()} / 2; const auto area = proxy_.area(); obj.pos().x = std::clamp(obj.pos().x, area.top_left.x + center_offset.x, area.top_left.x + area.size.w - center_offset.x); obj.pos().y = std::clamp(obj.pos().y, area.top_left.y + center_offset.y, area.top_left.y + area.size.h - center_offset.y); status_ = obj.lifes() > 0 ? game_object::status::alive : game_object::status::dead; } void game_object_updater::visit(scrolling_bg& obj) { obj.pos().y = (obj.pos().y + obj.scroll_speed()) % obj.img().height(); status_ = game_object::status::alive; } void game_object_updater::visit(spawn_point& obj) { auto delta = delta_; while (obj.time_remaining() <= delta) { auto const pos = sgfx::point{obj.area().top_left.x + random_uniform_int(obj.area().size.w), obj.area().top_left.y + random_uniform_int(obj.area().size.h)}; obj(proxy_, pos); delta -= obj.time_remaining(); obj.time_remaining() = obj.delay(); } obj.time_remaining() -= delta; status_ = game_object::status::alive; } // --------------------------------------------------------------------------------- // drawing void game_object_drawer::draw(sgfx::canvas_view view, game_object& obj) { auto drawer = game_object_drawer{view}; obj.accept(drawer); } void game_object_drawer::visit(asteroid& obj) { auto const center_offset = sgfx::vec{obj.img().width(), obj.img().height()} / 2; sgfx::draw(target_, obj.img(), obj.pos() - center_offset, asteroid::key_color); } void game_object_drawer::visit(bullet& obj) { auto const center_offset = sgfx::vec{obj.img().width(), obj.img().height()} / 2; sgfx::draw(target_, obj.img(), obj.pos() - center_offset, bullet::key_color); } void game_object_drawer::visit(player& obj) { auto const& current_img = obj.img(obj.current_status()); auto const center_offset = sgfx::vec{current_img.width(), current_img.height()} / 2; sgfx::draw(target_, current_img, obj.pos() - center_offset, player::key_color); auto life_rect = sgfx::rectangle{{10, 10}, {10, 50}}; for (int i = 0; i < obj.lifes(); ++i, life_rect.top_left.x += 15) sgfx::fill(target_, life_rect, sgfx::color::red); } void game_object_drawer::visit(scrolling_bg& obj) { sgfx::draw(target_, obj.img(), obj.pos()); sgfx::draw(target_, obj.img(), obj.pos() - sgfx::vec{0, obj.img().height()}); } void game_object_drawer::visit(spawn_point& /*obj*/) { // no-op }
#include<bits/stdc++.h> using namespace std; class SortedStack{ public: stack<int> s; void sort(); }; stack<int> push_bottom(stack <int> stk, int a){ if(stk.size() == 0 || stk.top() <= a){ stk.push(a); return stk; } if(stk.top() > a){ int t = stk.top(); stk.pop(); stk = push_bottom(stk,a); stk.push(t); return stk; } } void SortedStack :: sort() { //Your code here if(s.size() != 0){ int a = s.top(); s.pop(); sort(); this->s = push_bottom(this->s,a); } } void printStack(stack<int> s) { while (!s.empty()) { printf("%d ", s.top()); s.pop(); } printf("\n"); } int main() { int t; cin>>t; while(t--) { SortedStack *ss = new SortedStack(); int n; cin>>n; for(int i=0;i<n;i++) { int k; cin>>k; ss->s.push(k); } printStack(ss->s); cout<< "hiii"<<endl; ss->sort(); printStack(ss->s); } }
#ifndef MIN_MAX_HIERARCHY_H #define MIN_MAX_HIERARCHY_H #include "cpvs.h" #include "Image.h" #include "Texture.h" /** * A min-max hierarchy can be created from an Image (with 1 channel, e.g. depth values) * and will contain in every level (except level 0, the original image) a min-max value. */ class MinMaxHierarchy { private: enum Channel { MIN_CH = 0, MAX_CH = 1 }; public: /** * Creates a min-max hierarchy for the given Image. * @param orig Image where width equals height and are both a power of two. */ MinMaxHierarchy(const ImageF& orig); ~MinMaxHierarchy() = default; /** * Returns the minimum at (x, y) of the given level. * @note For level 0 min == max */ inline float getMin(size_t level, size_t x, size_t y) const { if (level == 0) { //assert(checkBounds(m_root, x, y)); return m_root.get(x, y, 0); } // The assertion costs a lot of performance, so disable it since everything seems to work //assert(checkBounds(m_levels[level - 1], x, y)); return m_levels[level - 1].get(x, y, MIN_CH); } /** * Returns the maximum at (x, y) of the given level. * @note For level 0 min == max */ inline float getMax(size_t level, size_t x, size_t y) const { if (level == 0) { //assert(checkBounds(m_root, x, y)); return m_root.get(x, y, 0); } // see above //assert(checkBounds(m_levels[level - 1], x, y)); return m_levels[level - 1].get(x, y, MAX_CH); } /** * Returns the number of levels the hierarchy has (including the original image) */ int getNumLevels() const { return m_levels.size() + 1; } /** * Returns a level of the hierarchy. */ inline const ImageF* getLevel(size_t level) const { if (level == 0) return &m_root; else return &m_levels[level-1]; } private: /** * Constructs a new level for the given one (which can't be level 0!) */ ImageF constructLevel(const ImageF& in) const; /** * The first level 0 only contains 1 channel, therefore it needs to be processed differently. */ ImageF constructLevelFromRoot(const ImageF& in) const; inline bool checkBounds(const ImageF& img, size_t x, size_t y) const { return x < img.getWidth() && y < img.getHeight(); } private: const ImageF m_root; vector<ImageF> m_levels; }; #endif
/* * LuaInterface.h * * Created on: Jun 11, 2017 * Author: root */ #ifndef LUA_LUAINTERFACE_H_ #define LUA_LUAINTERFACE_H_ #include "../define.h" #include "lua.hpp" #include "../Memory/MemAllocator.h" namespace CommBaseOut { enum E_LuaRet { eLuaSuccess, }; /** * 类的功能:提供与Lua交互接口 * 说明:打开关闭lua环境,所有与lua交互均通过这个类 */ class CLuaInterface #ifdef USE_MEMORY_POOL : public MemoryBase #endif { public: CLuaInterface(); ~CLuaInterface(); /** * 开启lua环境,打开lua_State * return : * param : */ void OpenLua(); /** * 关闭lua环境,关闭lua_State * return : * param : */ void CloseLua(); /** * 从内存buf中加载lua程序 *return : E_LuaRet *param : strLua 需要加载的lua程序buf strName buf命名(调试时使用) */ int LoadBuffer(const char *strLua, const char *strName); /** * 从文件中加载lua程序 * return : E_LuaRet * param : strFileName 需要加载的程序文件名 */ int LoadFile(const std::string &strFileName); /** * 执行已经加载lua程序或者lua函数 * return : E_LuaRet * param : nArgs lua函数参数个数 nRets lua函数返回结果 * note : 执行一段lua的chunk时,nArgs与nRets均为0 */ int Call(int nArgs = 0, int nRets = 0); /** * 设置一个全局变量的值为字符串值 * return : E_LuaRet * param : strGlobalName 全局变量名 strGlobalValue 全局变量值 */ int SetGlobalString(const char *strGlobalName, const char *strGlobalValue); /** * 设置一个全局变量的值为lightuserdata * return : E_LuaRet *param : strGlobalName 全局变量名 pValue lightuserdata值 */ int SetGlobalLightUserData(const char *strGlobalName, void *pValue); /** * 设置一个全局变量的值为int * return : E_LuaRet * param : strGlobalName 全局变量名 nValue 要设置的值 */ int SetGlobalInt(const char *strGlobalName, int nValue); /** * 在lua中新建一个表 */ void CreateNewTable(); /** * 在lua表中设置字段和值 * return : E_LuaRet *param : strFieldName 表字段名 nValue 字段的值 */ int SetFieldInt(const char *strFieldName, int nValue); /** * 在lua表中设置字段和值 * return : E_LuaRet * param : nIndex 字段索引 nValue 字段的值 */ int SetFieldInt(int nIndex, int nValue); /** * 在lua表中增加一个二级表 * return : E_LuaRet * param : nIndex 表字段索引 */ int SetFieldTable(int nIndex); /** * 在lua表中增加一个二级表 * return : E_LuaRet * param : strTableName 表字段索引 */ int SetFieldTable(const char *strTableName); /** * 结束table创建 * return : E_LuaRet * param : strTableName 创建table名称 */ int FinishTable(const char *strTableName); /** * 在lua中注册一个C函数 * return : E_LuaRet * param : strFunName 要注册函数名称 lua_CFunction fun 要注册函数 */ int RegisterFun(const char *strFunName, lua_CFunction fun); /** * 要调用lua函数名入栈 * return : E_LuaRet * param strFunName 要调用lua函数名 */ int SetLuaFunction(const char *strFunName); /** * 将整数入栈 * return: E_LuaRet * param : nValue 要入栈的值 * note 调用完成占用一个栈空间 */ int SetInt(int nValue); /** * 将一个浮点数入栈 * return : E_LuaRet * param : fValue 要入栈的值 * note 调用完成占用一个栈空间 */ int SetFloat(float fValue); /** * 将字符串入栈 * return : E_LuaRet * param : strValue 要入栈的值 * note 调用完成占用一个栈空间 */ int SetString(const char *strValue); /** * 入栈一个lightuserdata,一般用于指针入栈 * return : E_LuaRet * param : pValue 要入栈的值 * note 调用完成占用一个栈空间 */ int SetLightUserData(void *pValue); /** * 获取一个整数值 * return : 返回变量值 * param : strParamName 要获取的变量名 nIndex 获取变量所在栈位置,默认从栈顶取 */ int GetInt(const char *strParamName = NULL, int nIndex = -1); /** * 获取一个浮点数 * param : strParamName 要获取的变量名 nIndex 获取变量所在栈位置,默认从栈顶取 * return : 返回变量值 */ float GetFloat(const char *strParam = NULL, int nIndex = -1); /** * 获取字符串的值 * return : E_LuaRet * param : buf 获取到的值存放缓冲区 nLen 缓冲区长度 strParamName 要获取变量名,为NULL时返回栈顶值 nIndex 获取变量所在栈位置,默认从栈顶取 */ int GetString(char *buf, int nLen, const char* strParamName = NULL, int nIndex = -1); /** * 将一个table入栈 * return : E_LuaRet * param : strTableName 要入栈table名 * note 调用完成后占用栈空间加1,使用完后需要调用CloseTable */ int GetTable(const char *strTableName); /** * 最近调用的table出栈 */ void CloseTable(void); /** * 获取表的元素个数 * return : 成功返回table的字段数,失败返回小于0 * param : */ int GetTableFieldCount(void); /** * 获取二维表中的数值, 如取表info={{1, 9, 3}, {29, 89, 55}}中的值9 * return : * param : nKey1 表中第一维的索引, 如: nKey1=1,则取第一维的表元素为: {1, 9, 3} nKey2 为表中第二维的索引,如: nKey1=1,nKey2=2,则取第一维表元素: {1, 9, 3}中的元素: 9。 */ int GetFieldIntInTableList(int nKey1, int nKey2); /** * 获取二维表中的字符串, 如取表info={{1, "abc", 3}, {29, 89, 55}}中的字符串"abc" * return : * param : nKey1 表中第一维的索引, 如: nKey1=1,则取第一维的表元素为: {1, "abc", 3} nKey2 为表中第二维的索引,如: nKey1=1,nKey2=2,则取第一维表元素: {1, "abc", 3}中的元素: "abc"。 */ int GetFieldStringInTableList(char *buf, int nLen, int nKey1, int nKey2); /** * 获取table的一个field的整数值 * return : 返回key对应的值大小 * param : strKey 要获取的key名称 * note 当table的key为字符串时调用此函数 */ int GetFieldInt(const char *strKey); /** * 获取table的一个field的整数值 * return : 返回key对应的值大小 * param : nKey 要获取的key索引 * note 当table的key为整数时调用此函数 */ int GetFieldInt(int nKey); /** * 获取table的一个field的浮点数值 * return : 返回key对应的值 * param : nKey 要获取的key索引 * note 当table的key为整数时调用此函数 */ float GetFieldFloat(int nKey); /** * table的一个field为table时,调用此方法获取table的一个field * return : E_LuaRet * param : nKey 要获取的key索引 * note 当table的key为整数时调用此函数,调用完成占用栈空间加1 */ int GetFieldTable(int nKey); /** * table的一个field为table时,调用此方法获取table的一个field * param : nKey 要获取的key索引 * return : E_LuaRet * note 当table的key为整数时调用此函数,调用完成占用栈空间加1 */ int GetFieldTable(const char *sKey); /** * 获取table的一个field的字符串值 * return : E_LuaRet * param : buf 获取字符串缓冲区 nLen 缓冲区大小 strKey 要获取的key名称 * note 当table的key为字符串时调用此函数 */ int GetFieldString(char *buf, int nLen, const char *strKey); /** * 获取table的一个field的字符串值 * return : E_LuaRet * param : buf 获取字符串缓冲区 nLen 缓冲区大小 nKey 要获取的key索引 * note 当table的key为整数时调用此函数 */ int GetFieldString(char *buf, int nLen, int nKey); /** * 出栈 * return : * param : n 要出栈数目 */ void Pop(int n); /** * 获取stack top * return : stack top * param : */ int GetStackTop(); void SavedStackSize(); int GetError() { return lua_error(m_luaState); } protected: lua_State *m_luaState; private: int m_nStackSize;//获取当前栈的的大小:索引 }; } #endif /* LUA_LUAINTERFACE_H_ */
////////////////////////////////////////////////////////////////////// // // File: glrender.cc // // Animation Lab, Computer Science Department // Carnegie Mellon University // // Created: Fri Mar 15 02:55:52 1996 by Zoran Popovic // // various GL dependent rendering methods // // includes routines to draw cubes, spheres, grids, // and also drawing code for both View and GerbilPole classes // ////////////////////////////////////////////////////////////////////// // #include <X11/cursorfont.h> // #include <X11/Xlib.h> #include "StdAfx.h" #include <GL/gl.h> #include <GL/glu.h> // #include <forms.h> // #include "ui.h" #include "pole.hh" #include "glrender.hh" // extern FD_main_form* fdf; inline void glVertex(Vec3 &v) { glVertex3dv(v.Ref()); } // Draw various GL primitives void draw_cube(void) { static GLuint display_tag = 0; if(display_tag == 0) { display_tag = glGenLists(1); glNewList(display_tag, GL_COMPILE_AND_EXECUTE); static GLdouble n[6][3] = { {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; static GLint faces[6][4] = { { 0, 1, 2, 3 }, { 3, 2, 6, 7 }, { 7, 6, 5, 4 }, { 4, 5, 1, 0 }, { 5, 6, 2, 1 }, { 7, 4, 0, 3 } }; GLdouble v[8][3]; GLint i; v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1; v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1; v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1; v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1; v[0][2] = v[3][2] = v[4][2] = v[7][2] = -1; v[1][2] = v[2][2] = v[5][2] = v[6][2] = 1; static GLenum type = GL_QUADS; /* GL_LINE_LOOP */ for (i = 0; i < 6; i++) { glBegin(type); glNormal3dv(&n[i][0]); glVertex3dv(&v[faces[i][0]][0]); glNormal3dv(&n[i][0]); glVertex3dv(&v[faces[i][1]][0]); glNormal3dv(&n[i][0]); glVertex3dv(&v[faces[i][2]][0]); glNormal3dv(&n[i][0]); glVertex3dv(&v[faces[i][3]][0]); glEnd(); } glEndList(); } else { glCallList(display_tag); } } void draw_sphere(void) { static GLuint display_tag = 0; if(display_tag == 0) { display_tag = glGenLists(1); GLUquadricObj *o = gluNewQuadric(); // casting to GLenum for quiet SUN compile gluQuadricOrientation(o, (GLenum) GLU_OUTSIDE); glNewList(display_tag, GL_COMPILE_AND_EXECUTE); gluSphere(o, 1, 20, 10); glEndList(); gluDeleteQuadric(o); } else { glCallList(display_tag); } } static void draw_circle(double x, double y, double radius) { glPushMatrix(); glTranslated(x, y, 0); glScaled(radius, radius, 1.); static GLuint display_tag = 0; if(display_tag == 0) { display_tag = glGenLists(1); glNewList(display_tag, GL_COMPILE_AND_EXECUTE); glBegin(GL_LINE_LOOP); const double segs = 60; for (int i = 0; i < segs; i++) { glVertex2d((cos(i * 2 * M_PI / segs)), (sin(i * 2 * M_PI / segs))); } glEnd(); glEndList(); } else { glCallList(display_tag); } glPopMatrix(); } static void draw_grid(int xblocks, int zblocks, double xdim, double zdim) { Vec3 v[2]; int i; glPushAttrib(GL_LINE_BIT); glLineWidth(2); glBegin(GL_LINES); v[0] = Vec3(-xdim*0.5, 0, 0); v[1] = Vec3( xdim*0.5, 0, 0); for (i=0; i<=zblocks; i++){ v[0][2] = v[1][2] = -zdim*0.5 + i*(zdim/zblocks); glVertex(v[0]); glVertex(v[1]); } v[0] = Vec3(0, 0, zdim*0.5); v[1] = Vec3(0, 0, -zdim*0.5); for (i=0; i<=xblocks; i++){ v[0][0] = v[1][0] = -xdim*0.5 + i*(xdim/xblocks); glVertex(v[0]); glVertex(v[1]); } glEnd(); glPopAttrib(); } static void draw_translucent_rect(double x0, double y0, double x1, double y1) { /* This stipple is a simple checkerboard of bits, which should * make the floor translucent */ static GLubyte halftone[] = { 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55}; glEnable (GL_POLYGON_STIPPLE); //?? glDisable (GL_CULL_FACE); glPolygonStipple (halftone); glBegin(GL_POLYGON); glVertex3d(x0, 0, y0); glVertex3d(x1, 0, y0); glVertex3d(x1, 0, y1); glVertex3d(x0, 0, y1); glEnd(); glDisable (GL_POLYGON_STIPPLE); //?? glEnable (GL_CULL_FACE); } #if 0 void pointer_visibility(int arg) { Window win = fl_get_canvas_id(fdf->gl_canvas); static int no_cursor = 0; char data = 0; if(! no_cursor) { no_cursor = fl_create_bitmap_cursor(&data, &data, 1, 1, 0, 0); } fl_set_cursor(win, (arg) ? XC_top_left_arrow : no_cursor); } #endif // ============================ View ============================ void View::perspective(int w, int h, double fov, double asp, double n, double f) { width = w; height = h; radius = ((height < width) ? height : width) * .5 * .9; fovy = fov; aspect = asp; nnear = n; ffar = f; glViewport(0,0, (GLint)width, (GLint)height); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective(fovy, ((double) width) / height, nnear, ffar); glGetDoublev(GL_PROJECTION_MATRIX, (double *)projection_mat.Ref()); glGetIntegerv(GL_VIEWPORT, viewport); } void View::resize( int w, int h ) { width = w; height = h; radius = ((height < width) ? height : width) * .5 * .9; aspect = double(width) / height; glViewport(0,0, (GLint)width, (GLint)height); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective(fovy, ((double) width) / height, nnear, ffar); glGetDoublev(GL_PROJECTION_MATRIX, (double *)projection_mat.Ref()); glGetIntegerv(GL_VIEWPORT, viewport); } void View::glSetup() { glMatrixMode( GL_PROJECTION ); glLoadMatrixd((const GLdouble *) projection_mat.Ref()); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // light is up, behind us, a little to left // (x points right, y points up, z points toward viewer) GLfloat light0_position[] = { -1, 2, 5, 0 }; glLightfv(GL_LIGHT0, GL_POSITION, light0_position); //GLfloat mat_specular[] = {1., 1., 1., 1.}; GLfloat mat_specular[] = {.5, .5, .5, 1.}; GLfloat mat_shininess[] = {50.}; glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess); glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE); glLoadMatrixd((const GLdouble *) modelview_mat.Ref()); } void View::glPushWorldSpace() { glPushMatrix(); glLoadMatrixd((const GLdouble *) modelview_mat.Ref()); } void View::glRender() { static GLuint floor_tag = 0; static GLuint crosshairs_tag = 0; // draw the floor if (!floor_tag) { floor_tag = glGenLists(1); glNewList(floor_tag, GL_COMPILE_AND_EXECUTE); glDisable (GL_LIGHTING); // glDisable (GL_DITHER); glColor3f(.25,.25,.25); draw_translucent_rect(-5, -5, 5, 5); glColor3f(.5,.5,.5); draw_grid(6, 6, 10, 10); // glEnable (GL_DITHER); glEnable (GL_LIGHTING); glEndList(); } else { glCallList(floor_tag); } // we don't draw unles in the interaction mode or explicitly // ordered to do so. if (! active() && !must_render) { return; } // crosshairs glPushAttrib(GL_LINE_BIT | GL_LIGHTING_BIT); glDisable(GL_LIGHTING); glPushMatrix(); glTranslated(center[0], center[1], center[2]); double size = .2; // proportion of the screen glScaled(zoom * .5 * size, zoom * .5 * size, zoom * .5 * size); #if 0 if (!crosshairs_tag) { crosshairs_tag = glGenLists(1); glNewList(crosshairs_tag, GL_COMPILE_AND_EXECUTE); glLineWidth(2); glBegin(GL_LINES); glColor3f(1,0,0); glVertex3f(-1,0,0); glColor3f(1,.2f,.2f); glVertex3f(1,0,0); glColor3f(0,.4f,0); glVertex3f(0,-1,0); glColor3f(0,1,0); glVertex3f(0,1,0); glColor3f(0,0,1); glVertex3f(0,0,-1); glColor3f(.2f,.2f,1); glVertex3f(0,0,1); glEnd(); glEndList(); } else { glCallList(crosshairs_tag); } #endif glPopMatrix(); // trackball circle in 2D glColor3f(1,1,0); glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); glOrtho(-width*.5, width*.5, -height*.5, height*.5, -1, 1); glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); glLineWidth(3); draw_circle(0,0, radius); glMatrixMode( GL_PROJECTION ); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); glPopMatrix(); glPopAttrib(); } int View::glGetMouseWorldPos(double x, double y, Vec3 &pos) { gluUnProject(x, y, 0, (double*)modelview_mat.Ref(), (double*)projection_mat.Ref(), viewport, &pos[0], &pos[1], &pos[2]); return 1; } int View::glGetPointScreenPos(const Vec3 &pos, double* x, double* y) { double dummy; gluProject(pos[0], pos[1], pos[2], (double*)modelview_mat.Ref(), (double*)projection_mat.Ref(), viewport, x, y, &dummy); return 1; } int View::glGetRay(double x, double y, Vec3 &pt, Vec3 &dir) { // pt is the eye point Mat4 inv_modelview(adj(modelview_mat)); // find origin in homogenous coords pt = proj(inv_modelview * Vec4(0,0,0,1)); // homogeneous division glGetMouseWorldPos(x, y, dir); dir = norm(dir-pt); return 1; } // ============================ Pole ============================ void GerbilPole::glSetMouse(int x, int y, int visible) { // TODO. Learn enough Windows programming to duplicate this stuff?? // Window win = fl_get_canvas_id(fdf->gl_canvas); // int origx, origy, w, h; // fl_get_wingeometry(win, &origx, &origy, &w, &h); // fl_set_mouse(origx + x, origy + (h - y)); // XWarpPointer(fl_display, None, win, 0, 0, 0, 0, x, h - y); // if (visible >= 0) { // pointer_visibility(visible); // } } /* ----------------------------------------------------------------- * 'DrawPole' uses current gl drawing color and transform stack. if * 'shadow_dir' is non-NULL, use it as shine-direction of an * infinite light source that will cause the mousepole to cast a * black shadow onto the xz plane. * -----------------------------------------------------------------*/ void GerbilPole::glRender(Vec3 *shadow_dir) { if (! active()) return; glPushAttrib(GL_LINE_BIT | GL_LIGHTING_BIT); glLineWidth(4); glDisable(GL_LIGHTING); glColor3d(1, 1, 0); Vec3 drop; if (drop_plane_mask & XZ_PLANE) { glBegin(GL_LINES); glVertex(pos); drop = Vec3(pos[0], drop_planes[1], pos[2]); glVertex(drop); glEnd(); } if (drop_plane_mask & XY_PLANE) { glBegin(GL_LINES); glVertex(pos); drop = Vec3(pos[0], pos[1], drop_planes[2]); glVertex(drop); glEnd(); } if (drop_plane_mask & ZY_PLANE) { glBegin(GL_LINES); glVertex(pos); drop = Vec3(drop_planes[0], pos[1], pos[2]); glVertex(drop); glEnd(); } if (shadow_dir){ Vec3 dir = norm(*shadow_dir); double t = -(pos[1]-drop_planes[1])/(double)dir[1]; glColor3d(.0625, .0625, .0625); glBegin(GL_LINES); drop = Vec3(pos[0], drop_planes[1] + .05, pos[2]); glVertex(drop); drop[0] += t * dir[0]; drop[2] += t * dir[2]; glVertex(drop); glEnd(); } glPopAttrib(); }
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; const int maxn = 505; ll big[maxn][maxn], small[maxn][maxn]; int vis_big[maxn], vis_small[maxn]; ll sr[maxn], br[maxn]; ll path[maxn];//记录顶点v之前正在连续的小路 ll n, m; ll Dijkstra(ll v0) { for(ll i = 0; i < n; i++) { sr[i] = small[v0][i]; br[i] = big[v0][i]; if(sr[i] < INF) { path[i] = sr[i]; sr[i] *= sr[i]; } else path[i] = INF; } vis_small[v0] = vis_big[v0] = 1; while(1){ ll minn = INF, flag = 0, v = -1; for(ll j = 0; j < n; j++) { if(!vis_big[j] && br[j] < minn) { flag = 0; v = j; minn = br[j]; } if(!vis_small[j] && sr[j] < minn) { flag = 1; v = j; minn = sr[j]; } } if(v == -1) break; if(flag) vis_small[v] = 1; else vis_big[v] = 1; for(ll j = 0; j < n; j++) { if(!vis_small[j] && small[v][j] < INF) { if(flag) {//prev到v之间是small road ll temp = sr[v] - path[v]*path[v] + (path[v]+small[v][j])*(path[v]+small[v][j]); if(sr[j] > temp || sr[j] == temp && path[j] > path[v]+small[v][j]) { sr[j] = temp; path[j] = path[v]+small[v][j]; } } else{//prev到v之间是big road ll temp = br[v]+small[v][j]*small[v][j]; if(sr[j] > temp || sr[j] == temp && path[j] > small[v][j]) { sr[j] = temp; path[j] = small[v][j]; } } } if(!vis_big[j] && big[v][j] < INF) { if(flag) { ll temp = sr[v] + big[v][j]; br[j] = min(temp, br[j]); } else { ll temp = br[v] + big[v][j]; br[j] = min(temp, br[j]); } } } } return min(br[n-1], sr[n-1]); } int main() { ll t, a, b, c; while(cin >> n >> m) { for (ll i = 0; i < n; i++) { for (ll j = 0; j <= i; j++) { big[i][j] = big[j][i] = INF; small[i][j] = small[j][i] = INF; } } memset(vis_big, 0, sizeof(vis_big)); memset(vis_small, 0, sizeof(vis_small)); for (int i = 0; i < m; i++) { cin >> t >> a >> b >> c; a--; b--; if (t == 1) small[a][b] = small[b][a] = min(c, small[a][b]); else big[a][b] = big[b][a] = min(c, big[a][b]); } cout << Dijkstra(0) << endl; } return 0; }
#pragma once #define FMT_HEADER_ONLY #include "fmt/format.h"
/** Purpose: run server program to testing socket How to run: g++ -std=c++11 -pthread Server.cpp -o server.o */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <iostream> #include <string> #include <thread> #include <sstream> #include <vector> #define MAX_SIZE_BUFFER 256 #define PORT 45001 using namespace std; vector<int> conn_list; char buffer[MAX_SIZE_BUFFER]; /** * Purpose: * process write-read server from client. * * Params: * - ip_con (int): ip of connection. */ void processThread(int ip_conn){ int n; bool flag = true; string msg; while(flag){ /// read process bzero(buffer, MAX_SIZE_BUFFER); n = read(ip_conn, buffer,MAX_SIZE_BUFFER); if (n < 0) perror("ERROR reading from socket"); printf("Here is the message: [%s]\n", buffer); /// write process cout << ">>"; getline(cin, msg); n = write(ip_conn, msg.c_str(), MAX_SIZE_BUFFER); if (n < 0) perror("ERROR writing to socket"); flag = true; } shutdown(ip_conn, SHUT_RDWR); close(ip_conn); return ; } int main(void) { struct sockaddr_in stSockAddr; int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); int n; /// is socket exist? if(-1 == SocketFD) { perror("can not create socket"); exit(EXIT_FAILURE); } memset(&stSockAddr, 0, sizeof(struct sockaddr_in)); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(PORT); stSockAddr.sin_addr.s_addr = INADDR_ANY; /// is socket binding? if(-1 == bind(SocketFD,(const struct sockaddr *)&stSockAddr, sizeof(struct sockaddr_in))) { perror("error bind failed"); close(SocketFD); exit(EXIT_FAILURE); } /// is socket listenning? if(-1 == listen(SocketFD, 10)) { perror("error listen failed"); close(SocketFD); exit(EXIT_FAILURE); } /// manage connection into server for(;;) { int ConnectFD = accept(SocketFD, NULL, NULL); /// is connection accepted? if(0 > ConnectFD) { perror("error accept failed"); close(SocketFD); exit(EXIT_FAILURE); } /// store connect in general list conn_list.push_back(ConnectFD); /// create a listener to message from client thread clientListener(processThread, ConnectFD); clientListener.join(); } close(SocketFD); return 0; }
using namespace std; int getrand(int a, int b) { random_device rd; mt19937 gen(rd()); uniform_int_distribution<int> distrib(a,b); return distrib(gen); }
#include <iostream> #include <string> #include <assert.h> #include <cstdlib> #include <string.h> #include <typeinfo> #include <cerror> #include <cmath> #include "cppJSON.h" using namespace std; #define EXPECT(c, ch) do { assert(*(c->json) == (ch)); c->json++;} while(0) #define ISDIGIT1TO9(ch) do { ((ch) >= '1' && (ch) <= '9') } while(0) #define ISDIGIT(ch) do { ((ch) >= '0' && (ch) <= '9') } while(0) //跳过空白 static void json_parse_whitespace(CppJsonContext * c) { const char* p = c->json; while(*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; c->json = p; } //解析null static JSON_PARSE_RET json_parse_null(CppJsonContext * c, CppJson * v) { EXPECT(c, 'n'); if(c->json[0] != 'u' || c->json[1] != 'l' || c->json[2] != 'l') return JSON_PARSE_INVALID_VALUE; c->json += 3; v->type = JSON_NULL; return JSON_PARSE_OK; } //解析false static JSON_PARSE_RET json_parse_false(CppJsonContext * c, CppJson * v) { EXPECT(c, 'f'); if(c->json[0] != 'a' || c->json[1] != 'l' || c->json[2] != 's' || c->json[3] != 'e') return JSON_PARSE_INVALID_VALUE; c->json += 4; v->type = JSON_FALSE; return JSON_PARSE_OK; } //解析true static JSON_PARSE_RET json_parse_true(CppJsonContext * c, CppJson * v) { EXPECT(c, 't'); if(c->json[0] != 'r' || c->json[1] != 'u' || c->json[2] != 'e') return JSON_PARSE_INVALID_VALUE; c->json += 3; v->type = JSON_TRUE; return JSON_PARSE_OK; } //parse_null\parse_false\parse_true合成一个函数parse_literal static JSON_PARSE_RET json_parse_literal(CppJsonContext * c, CppJson * v, const char * str, int len, json_type type) { EXPECT(c, *str); str++; for(int i = 0; i < len-1; i++) { if(c->json[i] != *str++) return JSON_PARSE_INVALID_VALUE; } c->json += len-1; v->type = type; return JSON_PARSE_OK; } /* number = [ "-" ] int [ frac ] [ exp ] int = "0" / digit1-9 *digit frac = "." 1*digit exp = ("e" / "E") ["-" / "+"] 1*digit */ #if 0 static JSON_PARSE_RET json_parse_number(CppJsonContext * c, CppJson * v) { char *end; //借用strtod函数 v.n = strtod(c->json, &end); //没有数字 if(c->json == end) { return JSON_PARSE_INVALID_VALUE; } c->json = end; v.type = JSON_NUMBER; return JSON_PARSE_OK; } #endif static JSON_PARSE_RET json_parse_number(CppJsonContext * c, CppJson * v) { const char* p = c->json; if(*p == '-') p++; if(*p == '0') p++; else { if(!ISDIGIT1TO9(*p)) return JSON_PARSE_INVALID_VALUE; for(p++; ISDIGIT(*p); p++); } if(*p == '.') { p++; if(!ISDIGIT(*p)) return JSON_PARSE_INVALID_VALUE; for(p++; ISDIGIT(*p); p++); } if(*p == 'e' || *p == 'E') { p++; if(*p != '+' && *p != '-') return JSON_PARSE_INVALID_VALUE; if(!ISDIGIT(*p)) return JSON_PARSE_INVALID_VALUE; for(p++; ISDIGIT(*p); p++); } //数值过大处理 errno = 0; v.n = strtod(c->json, NULL); if (errno == ERANGE && v->n == HUGE_VAL) return JSON_PARSE_NUMBER_TOO_BIG; // v.type = JSON_NUMBER; c->json = p; return JSON_PARSE_OK; } static JSON_PARSE_RET json_parse_value(CppJsonContext * c, CppJson * v) { // cout<<*(c->json)<<" "<<*c->json<<endl; // cout<<typeid(*(c->json)).name()<<endl; // bool b = *(c->json) == 'n'; // cout<<b<<endl; switch(*(c->json)) { case 'n': return json_parse_literal(c, v, "null", 4, JSON_NULL); case 'f': return json_parse_literal(c, v, "false", 5, JSON_FALSE); case 't': return json_parse_literal(c, v, "true", 4, JSON_TRUE); default: return json_parse_number(c, v); case '\0': return JSON_PARSE_EXPECT_VALUE; } } json_type CppJson::json_get_type() { return this->type; } double CppJson::json_get_number() { assert(this->type==JSON_NUMBER); return this->n; } //跳过前后空格 //json-text = ws value ws JSON_PARSE_RET CppJsonParser::json_parse(CppJson * v, const char * json) { CppJsonContext c; JSON_PARSE_RET ret; assert(v != NULL); c.json = json; v->type = JSON_NULL; //前面的空白 json_parse_whitespace(&c); //解析 ret=json_parse_value(&c, v); if(ret==JSON_PARSE_OK) { //后面的空白 json_parse_whitespace(&c); if(*(c.json) != '\0') { ret = JSON_PARSE_ROOT_NOT_SINGULAR; } } return ret; }
#include "precompiled.h" #include "component/jsrendercomponent.h" #include "component/jscomponent.h" #include "entity/jsentity.h" using namespace jscomponent; using namespace component; using namespace script; namespace jscomponent { static bool parseDesc(JSContext* cx, JSObject* obj, JSRenderComponent::desc_type& desc); // method declarations // static JSBool classMethod(JSContext *cx, uintN argc, jsval *vp); // property declarations // static JSBool propGetter(JSContext *cx, JSObject *obj, jsval id, jsval *vp); static JSClass class_ops = { "JSRenderComponent", JSCLASS_HAS_RESERVED_SLOTS(1), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub }; static JSPropertySpec class_properties[] = { // {"name", id, flags, getter, setter}, WRAPPED_LINK(transform, JSRenderComponent, PosComponent), JS_PS_END }; static JSFunctionSpec class_methods[] = { // JS_FN("name", function, nargs, flags, minargs), JS_FS_END }; } ScriptedObject::ScriptClass JSRenderComponent::m_scriptClass = { &class_ops, class_properties, class_methods, NULL }; REGISTER_SCRIPT_INIT(JSRenderComponent, initClass, 20); static void initClass(ScriptEngine* engine) { RegisterScriptClass<JSRenderComponent, Component>(engine); jsentity::RegisterCreateFunction(engine, "createJSRenderComponent", createComponent<JSRenderComponent>); } bool jscomponent::parseDesc(JSContext* cx, JSObject* obj, JSRenderComponent::desc_type& desc) { GetProperty(cx, obj, "transform", desc.transformComponent); return true; }
class 7Rnd_9x17_PPK : CA_Magazine { scope = 2; type = 16; displayName = $STR_DZ_MAG_7RND_9x17_PPK_NAME; descriptionShort = $STR_DZ_MAG_7RND_PPK_9x17_DESC; picture = "\RH_de\inv\m_ppk.paa"; model = "\RH_de\mags\mag_ppk.p3d"; ammo = "B_9x17_Ball"; count = 7; initSpeed = 320; class ItemActions { COMBINE_MAG }; };
#ifndef NMOS_FORMAT_H #define NMOS_FORMAT_H #include "nmos/string_enum.h" namespace nmos { // Formats (used in sources, flows and receivers) // See https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/docs/2.1.%20APIs%20-%20Common%20Keys.md#format // and https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/APIs/schemas/source_generic.json // and https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/APIs/schemas/source_audio.json // and https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/APIs/schemas/flow_video.json // etc. DEFINE_STRING_ENUM(format) namespace formats { const format video{ U("urn:x-nmos:format:video") }; const format audio{ U("urn:x-nmos:format:audio") }; const format data{ U("urn:x-nmos:format:data") }; const format mux{ U("urn:x-nmos:format:mux") }; } } #endif
#pragma once #include "Application.h" #include "Renderer2D.h" #include <vector> #include <vector.h> #include "Behaviour.h" class Agent { public: Agent() {} Agent(vector2 winDim) : windowDimensions(winDim) {}; virtual ~Agent(); // Update the agent and its behaviours virtual void Update(float deltaTime); // Draw the agent virtual void Draw(aie::Renderer2D* renderer); // Add a behaviour to the agent void AddBehaviour(Behaviour* behaviour); // Movement functions void SetPosition(vector2 position) { m_Position = position; } vector2 GetPosition() const { return m_Position; } void SetVelocity(vector2 velocity) { m_Velocity = velocity; } vector2 GetVelocity() { return m_Velocity; } void ClampVelocity(vector2& force); bool WithinBounds(vector2 pos); //within screen returns true protected: std::vector<Behaviour*> m_BehaviourList; vector2 m_Position; vector2 m_Velocity; vector2* m_MaxVelocity = new vector2(50, 50); vector2 windowDimensions; };
#include "BaseEntity.h" #include "Weapon.h" #include "GamePlay.h" #include "Params.h" //---------- weapon general method----------------- // //------------------------------------------------ // shoot at the given position void Weapon::ShootAt(Vec2 pos) { m_iUpdate = (int)Clock->getCurrentTime(); if (isReadyForNextShot()) { // deplay the projectile if (m_bSplash) { } // does not sphas else { } // add a projectile to the world // now only one method for addong peojectile // is defined if (!m_pOwner) return; // getting the position of owner auto posOwner = m_pOwner->getPosition(); //float x=posOwner.x*512/240; //float y =posOwner.y *512/240; auto world = m_pOwner->getWorld(); if (world) { // first method of shooting //world->addProjectile(m_iType,posOwner,Vec2(300,300),m_iCurrentDamage); // second metho // world->addProjectile(m_pOwner,/*Vec2(0,0)*/pos); // third method world->addProjectile(m_pOwner,/*Vec2(0,0)*/pos, m_iType); // update the next timer UpdateTimeWeaponIsNextAvailable(); } } } // increase the damage void Weapon::increaseDamage(unsigned int val) { m_iCurrentDamage += val; } // increase the damage bonus void Weapon::increaseDamageBonusLight(unsigned int val) { m_iBonusLight += val; } // increase the damage bonus void Weapon::increaseDamageBonusArmored(unsigned int val) { m_iBonusArmored += val; } // weapon 1 starting Weapon1::Weapon1(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon1::Start() { m_iType = weapon1; m_bBonusArmored = false; m_bBonusLight = false; m_iCurrentDamage = Weapon1_Damage; m_iBonusArmored = Weapon1_BonusVs_Armored; m_iBonusLight = Weapon1_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon1_Range; m_dRateOfFire = Weapon1_Rate; m_dMaxProjectileSpeed = 600; m_sName = "torpedo1"; } // weapon 2 starting Weapon2::Weapon2(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon2::Start() { m_iType = weapon2; m_bBonusArmored = false; m_bBonusLight = false; m_iCurrentDamage = Weapon2_Damage; m_iBonusArmored = Weapon2_BonusVs_Armored; m_iBonusLight = Weapon2_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon2_Range; m_dRateOfFire = Weapon2_Rate; m_dMaxProjectileSpeed = 600; m_sName = "torpedo2"; } // weapon 3 starting Weapon3::Weapon3(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon3::Start() { m_iType = weapon3; m_bBonusArmored = true; m_bBonusLight = false; m_iCurrentDamage = Weapon3_Damage; m_iBonusArmored = Weapon3_BonusVs_Armored; m_iBonusLight = Weapon3_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon3_Range; m_dRateOfFire = Weapon3_Rate; m_dMaxProjectileSpeed = 600; m_sName = "weaponalien1"; } // weapon 4 starting Weapon4::Weapon4(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon4::Start() { m_iType = weapon4; m_bBonusArmored = false; m_bBonusLight = false; m_iCurrentDamage = Weapon4_Damage; m_iBonusArmored = Weapon4_BonusVs_Armored; m_iBonusLight = Weapon4_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon4_Range; m_dRateOfFire = Weapon4_Rate; m_dMaxProjectileSpeed = 600; m_sName = "weaponalien2"; } // weapon 5 starting Weapon5::Weapon5(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon5::Start() { m_iType = weapon5; m_bBonusArmored = false; m_bBonusLight = false; m_iCurrentDamage = Weapon5_Damage; m_iBonusArmored = Weapon5_BonusVs_Armored; m_iBonusLight = Weapon5_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon5_Range; m_dRateOfFire = Weapon5_Rate; m_dMaxProjectileSpeed = 600; m_sName = "weaponalien3"; } // weapon 6 starting Weapon6::Weapon6(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon6::Start() { m_iType = weapon6; m_bBonusArmored = false; m_bBonusLight = true; m_iCurrentDamage = Weapon6_Damage; m_iBonusArmored = Weapon6_BonusVs_Armored; m_iBonusLight = Weapon6_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon6_Range; m_dRateOfFire = Weapon6_Rate; m_dMaxProjectileSpeed = 600; m_sName = "weaponalien4"; } // weapon 7 starting Weapon7::Weapon7(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon7::Start() { m_iType = weapon7; m_bBonusArmored = false; m_bBonusLight = false; m_iCurrentDamage = Weapon7_Damage; m_iBonusArmored = Weapon7_BonusVs_Armored; m_iBonusLight = Weapon7_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon7_Range; m_dRateOfFire = Weapon7_Rate; m_dMaxProjectileSpeed = 600; m_sName = "weaponalien5"; } // weapon 8 starting Weapon8::Weapon8(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon8::Start() { m_iType = weapon8; m_bBonusArmored = false; m_bBonusLight = true; m_iCurrentDamage = Weapon8_Damage; m_iBonusArmored = Weapon8_BonusVs_Armored; m_iBonusLight = Weapon8_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon8_Range; m_dRateOfFire = Weapon8_Rate; m_dMaxProjectileSpeed = 600; m_sName = "weaponFireBat"; } // weapon 7 starting Weapon9::Weapon9(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon9::Start() { m_iType = weapon9; m_bBonusArmored = true; m_bBonusLight = false; m_iCurrentDamage = /*Weapon7_Damage*/10; m_iBonusArmored = /*Weapon7_BonusVs_Armored*/20; m_iBonusLight = /*Weapon7_BonusVs_Light*/0; m_bSplash = false; m_dIdealRange =/*Weapon7_Range*/125; m_dRateOfFire =/*Weapon7_Rate*/1.1; m_dMaxProjectileSpeed = 600; m_sName = "weaponMarauder"; } // weapon 10 starting Weapon10::Weapon10(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon10::Start() { m_iType = weapon10; m_bBonusArmored = true; m_bBonusLight = false; m_iCurrentDamage =/*Weapon7_Damage*/35; m_iBonusArmored = /*Weapon7_BonusVs_Armored*/35; m_iBonusLight = 0; m_bSplash = true; m_dIdealRange =/*Weapon7_Range*/300; m_dRateOfFire =/*Weapon7_Rate*/0.8f; m_dMaxProjectileSpeed = 600; m_sName = "weaponalien5"; m_dMinRange = 50; } // weapon 11 starting Weapon11::Weapon11(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon11::Start() { m_iType = weapon11; m_bBonusArmored = false; m_bBonusLight = false; m_iCurrentDamage = Weapon7_Damage; m_iBonusArmored = Weapon7_BonusVs_Armored; m_iBonusLight = Weapon7_BonusVs_Light; m_bSplash = false; m_dIdealRange = Weapon7_Range; m_dRateOfFire = Weapon7_Rate; m_dMaxProjectileSpeed = 600; m_sName = "weaponalien5"; } // weapon 12 starting Weapon12::Weapon12(BaseEntity* OwnerOfGun) :Weapon(OwnerOfGun) { // use the start methof for initialise m_iUpdate = 0; Start(); } // init all members's variables void Weapon12::Start() { m_iType = weapon12; m_bBonusArmored = false; m_bBonusLight = false; m_iCurrentDamage =/*Weapon7_Damage*/35; m_iBonusArmored =/* Weapon7_BonusVs_Armored*/0; m_iBonusLight = /*Weapon7_BonusVs_Light*/0; m_bSplash = false; m_dIdealRange = 20; m_dRateOfFire = 2.9f; m_dMaxProjectileSpeed = 600; m_sName = "weaponAlien6"; }
#pragma once enum BonusType {STAR, LIFE, FASTER, SLOWER, BIGGER, SMALLER}; class Bonus { private: int width; int height; int posX, posY; BonusType bonusType; public: Bonus(); void Fall(); int bX(); int bY(); int bWidht(); int bHeight(); BonusType bType(); };
#include <iostream> using namespace std; class Line{ private: int size; int *score; public: Line(){ size = 0; score = NULL; } void setSize(int _size){ size = _size; score = new int[size]; } ~Line(){ delete[] score; } void setScore(int index, int num){ score[index] = num; } int getScore(int index){ return score[index]; } double getAverage(){ int sum = 0; for(int i = 0; i < size; i++){ sum += score[i]; } return (double)sum / size; } double getPercentage(){ double average = getAverage(); int number = 0; for(int i = 0; i < size; i++){ if(score[i] > average){ number++; } } return ((double)number / size)*100.0; } }; int main(){ int lineSize; cin >> lineSize; Line line[lineSize]; for(int i = 0; i < lineSize; i++){ int size; cin >> size; line[i].setSize(size); for(int j = 0; j < size; j++){ int num; cin >> num; line[i].setScore(j, num); } } for(int i = 0; i < lineSize; i++){ cout.setf(ios::fixed); cout.precision(3); cout << line[i].getPercentage() << "%" << endl; } return 0; }
#include "stdio.h" int main(){ int N; while(~scanf("%d",&N)){ if(N==2) printf("Y\n"); else if(N==3) printf("Y\n"); else if(N==4) printf("Y\n"); else if(N==5) printf("Y\n"); else if(N==6) printf("Y\n"); else if(N==7) printf("Y\n"); else if(N==8) printf("Y\n"); else if(N==9) printf("Y\n"); else if(N==10) printf("Y\n"); else if(N==11) printf("Y\n"); else if(N==12) printf("Y\n"); else if(N==13) printf("Y\n"); else if(N==14) printf("Y\n"); else if(N==15) printf("Y\n"); else if(N==16) printf("Y\n"); else if(N==17) printf("Y\n"); else if(N==18) printf("Y\n"); else if(N==19) printf("Y\n"); else if(N==20) printf("Y\n"); else if(N==21) printf("Y\n"); else if(N==22) printf("Y\n"); else if(N==23) printf("Y\n"); else if(N==24) printf("Y\n"); else if(N==25) printf("Y\n"); else if(N==26) printf("Y\n"); else if(N==27) printf("Y\n"); else if(N==28) printf("Y\n"); else if(N==29) printf("Y\n"); else if(N==30) printf("Y\n"); else if(N==31) printf("Y\n"); else if(N==32) printf("Y\n"); else if(N==33) printf("Y\n"); else if(N==34) printf("Y\n"); else if(N==35) printf("Y\n"); else if(N==36) printf("Y\n"); else if(N==37) printf("Y\n"); else if(N==38) printf("Y\n"); else if(N==40) printf("Y\n"); else if(N==0) break; else printf("N\n"); } return 0; }
#include <iostream> #include <string> #include <cstring> #include <sstream> #include <vector> #include <algorithm> #include <iterator> #include <fstream> //files #include <errno.h> //errors #include <stdio.h> //printf #include <unistd.h> // sys calls #include <sys/types.h> // O_ constants #include <sys/ipc.h> // IPC_ constnts #include <sys/stat.h> // mode constants #include <fcntl.h> // O_ constants #include <pthread.h> //threads //#define PTHREAD_COND_INITIALIZER {_PTHREAD_COND_SIG_init, {0}} // initializer to init macros #define MB 1024 char in[MB]; using namespace std; // type-definition: 'pt2Function' now can be used as type typedef void * (*pt2Function)(void *); #define NUM_THREADS 2 void *fun0(void *threadid) { long tid; pthread_mutex_t* mut = (pthread_mutex_t*)threadid; pthread_cond_t cond;// = PHTREAD_COND_INITIALIZER; pthread_cond_init(&cond,NULL); tid = (long)threadid; cout << "Condition variable wait, " << tid << endl; pthread_cond_wait(&cond,mut); cout << "Condition variable end wait, " << tid << endl; pthread_cond_destroy(&cond); pthread_exit(NULL); } void *fun1(void *threadid) { long tid; pthread_barrier_t* bp = (pthread_barrier_t*)threadid; tid = (long)threadid; cout << "Barrier wait, " << tid << endl; pthread_barrier_wait(bp); cout << "Barrier end wait, " << tid << endl; pthread_barrier_destroy(bp); pthread_exit(NULL); } int main (int argc, char** argv) { pthread_t threads[NUM_THREADS]; pt2Function functions[NUM_THREADS]; void ** args = new void*[NUM_THREADS]; functions[0] = &fun0; functions[1] = &fun1; int rc; int i; int fd = open("main.pid", O_WRONLY | O_CREAT, 0666); sprintf(in,"%d", getpid()); int writed = write(fd, in, sizeof(rc)); close(fd); pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_barrier_t bp; pthread_barrier_init(&bp,NULL,2); i=0;args[i] = (void *)&mut; i=1;args[i] = (void *)&bp; for( i=0; i < NUM_THREADS; i++ ){ // cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, functions[i], args[i]); if (rc){ cout << "Error:unable to create thread," << rc << endl; exit(-1); } } //pause(); pthread_exit(NULL); }
// MIT License // Copyright (c) 2020 Marnix van den Berg <m.a.vdberg88@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "Body.h" #include "Contact.h" #include "Shape.h" #include "ErrorLogger.h" Body::Body() : m_invMass(0.0), m_invInertia(0.0), m_held(false) {} Body::Body(Transform trans, std::unique_ptr<Shape> shape, double density): m_transform(trans), m_shape(std::move(shape)), m_invMass(0.0), m_invInertia(0.0), m_held(false) { //It is found that overlap resolving works best with mass and inertia properties proportional to the earial properties. //Resolving overlaps would also work for other mass and interia properties, but generally the convergence is slower. //TODO: Check if these can fail or will always work. double mass = m_shape->calcArea()*density; if (mass > DBL_EPSILON) m_invMass = 1.0 / mass; double inertia = m_shape->calcInertia()*density; if (mass > DBL_EPSILON) m_invInertia = 1.0 / inertia; } Body::~Body() = default; Body::Body(Body&& other) = default; bool Body::isStatic() const { if (m_invMass < DBL_EPSILON) return true; else if (m_held) return true; else return false; } AABB Body::globalAABBWithMargin() const { return m_shape->calcTransformedAABBWithMargin(m_transform); } std::vector<Vector2> Body::globalPoints() const { return m_shape->transformedPoints(m_transform); } const std::vector<Vector2>& Body::localPoints() const { return m_shape->localPoints(); } bool Body::overlaps(Vector2 point) const { Vector2 locPoint = transformVecInv(m_transform, point); return m_shape->overlaps(locPoint); } void Body::updatePosition(Vector2 displacement, double rotation) { if (!isStatic()) //mass = 0 indicates a static body { m_transform.multiply(displacement, rotation); } } void Body::setPosition(Vector2 position) { m_transform.setPosition(position); } void Body::setMargin(double margin) { m_shape->setCollisionMargin(margin); } std::vector<Contact> Body::contactProperties(const Body& otherBody) const { //Contact properties are calculated in the coordinates of this body, //such that only the shape of the other body needs to be transformed. const Transform& otherTrans = otherBody.m_transform; const Shape& otherShape = *otherBody.m_shape; //the combined transform transforms the shape of the other body from the other body's coordinate system //to this bodies coordinate system. Transform combinedTransform = inverseTimes(m_transform, otherTrans); //Overlap properties determination can fail in specific cases, //but these isolated will be corrected in subsequent steps. No need for warnings/errors. std::vector<Contact> contacts; m_shape->overlap(otherShape, combinedTransform, &contacts); //Transform the contact to world coorinates. for (int i = 0; i < contacts.size(); i++) { contacts[i].transform(m_transform); } return contacts; }
/* src/var.cpp -- Variable/computation graph-related functions. Copyright (c) 2020 Wenzel Jakob <wenzel.jakob@epfl.ch> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "var.h" #include "internal.h" #include "log.h" #include "eval.h" #include "util.h" /// Descriptive names for the various variable types const char *var_type_name[(int) VarType::Count]{ "invalid", "global", "mask", "int8", "uint8", "int16", "uint16", "int32", "uint32", "int64", "uint64", "float16", "float32", "float64", "pointer" }; /// Descriptive names for the various variable types (extra-short version) const char *var_type_name_short[(int) VarType::Count]{ "inv", "glo", "msk", "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f16", "f32", "f64", "ptr" }; /// CUDA PTX type names const char *var_type_name_ptx[(int) VarType::Count]{ "???", "???", "pred", "s8", "u8", "s16", "u16", "s32", "u32", "s64", "u64", "f16", "f32", "f64", "u64" }; /// CUDA PTX type names (binary view) const char *var_type_name_ptx_bin[(int) VarType::Count]{ "???", "???", "pred", "b8", "b8", "b16", "b16", "b32", "b32", "b64", "b64", "b16", "b32", "b64", "b64" }; /// LLVM IR type names (does not distinguish signed vs unsigned) const char *var_type_name_llvm[(int) VarType::Count]{ "???", "???", "i1", "i8", "i8", "i16", "i16", "i32", "i32", "i64", "i64", "half", "float", "double", "i8*" }; /// Double size integer arrays for mulhi() const char *var_type_name_llvm_big[(int) VarType::Count]{ "???", "???", "???", "i16", "i16", "i32", "i32", "i64", "i64", "i128", "i128", "???", "???", "???", "???" }; /// Abbreviated LLVM IR type names const char *var_type_name_llvm_abbrev[(int) VarType::Count]{ "???", "???", "i1", "i8", "i8", "i16", "i16", "i32", "i32", "i64", "i64", "f16", "f32", "f64", "i8*" }; /// LLVM IR type names (binary view) const char *var_type_name_llvm_bin[(int) VarType::Count]{ "???", "???", "i1", "i8", "i8", "i16", "i16", "i32", "i32", "i64", "i64", "i16", "i32", "i64", "i64" }; /// LLVM/CUDA register name prefixes const char *var_type_prefix[(int) VarType::Count] { "%u", "gl", "%p", "%b", "%b", "%w", "%w", "%r", "%r", "%rd", "%rd", "%h", "%f", "%d", "%rd" }; /// Maps types to byte sizes const uint32_t var_type_size[(int) VarType::Count] { 0, 0, 1, 1, 1, 2, 2, 4, 4, 8, 8, 2, 4, 8, 8 }; /// String version of the above const char *var_type_size_str[(int) VarType::Count] { "0", "0", "1", "1", "1", "2", "2", "4", "4", "8", "8", "2", "4", "8", "8" }; /// Label prefix, doesn't depend on variable type const char *var_type_label[(int) VarType::Count] { "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L", "L" }; /// Access a variable by ID, terminate with an error if it doesn't exist Variable *jit_var(uint32_t index) { auto it = state.variables.find(index); if (unlikely(it == state.variables.end())) jit_fail("jit_var(%u): unknown variable!", index); return &it.value(); } /// Remove a variable from the cache used for common subexpression elimination void jit_cse_drop(uint32_t index, const Variable *v) { if (state.cse_cache.empty()) return; VariableKey key(*v); auto it = state.cse_cache.find(key); if (it != state.cse_cache.end() && it.value() == index) state.cse_cache.erase(it); } /// Cleanup handler, called when the internal/external reference count reaches zero void jit_var_free(uint32_t index, Variable *v) { bool trace = std::max(state.log_level_stderr, state.log_level_callback) >= LogLevel::Trace; if (unlikely(trace)) jit_trace("jit_var_free(%u)", index); if (v->stmt) jit_cse_drop(index, v); uint32_t dep[4]; memcpy(dep, v->dep, sizeof(uint32_t) * 4); void *data = v->data; bool direct_pointer = v->direct_pointer, has_extra = v->has_extra; // Release GPU memory if (likely(v->data && !v->retain_data)) jit_free(v->data); // Free strings if (unlikely(v->free_stmt)) free(v->stmt); // Remove from hash table. 'v' should not be accessed from here on. state.variables.erase(index); if (likely(!direct_pointer)) { // Decrease reference count of dependencies for (int i = 0; i < 4; ++i) { uint32_t index2 = dep[i]; if (index2 == 0) break; // Inlined implementation of jit_var_dec_ref_int auto it = state.variables.find(index2); Variable *v2 = &it.value(); v2->ref_count_int--; if (unlikely(trace)) jit_trace("jit_var_dec_ref_int(%u): %u", index2, v2->ref_count_int); if (v2->ref_count_ext == 0 && v2->ref_count_int == 0) jit_var_free(index2, v2); } } else { // Free reverse pointer table entry, if needed auto it = state.variable_from_ptr.find(data); if (unlikely(it == state.variable_from_ptr.end())) jit_fail("jit_var_free(): direct pointer not found!"); state.variable_from_ptr.erase(it); // Decrease reference count of dependencies jit_var_dec_ref_ext(dep[0]); } if (unlikely(has_extra)) { auto it = state.extra.find(index); if (it == state.extra.end()) jit_fail("jit_var_free(): entry in 'extra' hash table not found!"); Extra extra = it.value(); state.extra.erase(it); // Free descriptive label free(extra.label); if (extra.free_callback) { unlock_guard guard(state.mutex); extra.free_callback(extra.callback_payload); } if (extra.vcall_bucket_count) { for (uint32_t i = 0; i < extra.vcall_bucket_count; ++i) jit_var_dec_ref_ext(extra.vcall_buckets[i].index); jit_free(extra.vcall_buckets); } } } /// Increase the external reference count of a given variable void jit_var_inc_ref_ext(uint32_t index, Variable *v) noexcept(true) { v->ref_count_ext++; jit_trace("jit_var_inc_ref_ext(%u): %u", index, v->ref_count_ext); } /// Increase the external reference count of a given variable void jit_var_inc_ref_ext(uint32_t index) noexcept(true) { if (index != 0) jit_var_inc_ref_ext(index, jit_var(index)); } /// Increase the internal reference count of a given variable void jit_var_inc_ref_int(uint32_t index, Variable *v) noexcept(true) { v->ref_count_int++; jit_trace("jit_var_inc_ref_int(%u): %u", index, v->ref_count_int); } /// Increase the internal reference count of a given variable void jit_var_inc_ref_int(uint32_t index) noexcept(true) { if (index != 0) jit_var_inc_ref_int(index, jit_var(index)); } /// Decrease the external reference count of a given variable void jit_var_dec_ref_ext(uint32_t index, Variable *v) noexcept(true) { if (unlikely(v->ref_count_ext == 0)) jit_fail("jit_var_dec_ref_ext(): variable %u has no external references!", index); jit_trace("jit_var_dec_ref_ext(%u): %u", index, v->ref_count_ext - 1); v->ref_count_ext--; if (v->ref_count_ext == 0 && v->ref_count_int == 0) jit_var_free(index, v); } /// Decrease the external reference count of a given variable void jit_var_dec_ref_ext(uint32_t index) noexcept(true) { if (index != 0) jit_var_dec_ref_ext(index, jit_var(index)); } /// Decrease the internal reference count of a given variable void jit_var_dec_ref_int(uint32_t index, Variable *v) noexcept(true) { if (unlikely(v->ref_count_int == 0)) jit_fail("jit_var_dec_ref_int(): variable %u has no internal references!", index); jit_trace("jit_var_dec_ref_int(%u): %u", index, v->ref_count_int - 1); v->ref_count_int--; if (v->ref_count_ext == 0 && v->ref_count_int == 0) jit_var_free(index, v); } /// Decrease the internal reference count of a given variable void jit_var_dec_ref_int(uint32_t index) noexcept(true) { if (index != 0) jit_var_dec_ref_int(index, jit_var(index)); } /// Append the given variable to the instruction trace and return its ID std::pair<uint32_t, Variable *> jit_var_new(Variable &v, bool disable_cse_) { Stream *stream = active_stream; if (unlikely(!stream)) { jit_raise("jit_var_new(): you must invoke jitc_set_device() to " "choose a target device before performing computation using " "the JIT compiler."); } else if (unlikely(v.cuda != stream->cuda)) { jit_raise("jit_var_new(): attempted to issue %s computation " "to the %s backend! You must invoke jit_set_device() to set " "the right backend!", v.cuda ? "CUDA" : "LLVM", stream->cuda ? "CUDA" : "LLVM"); } CSECache::iterator key_it; bool is_special = (VarType) v.type == VarType::Invalid, disable_cse = v.stmt == nullptr || v.direct_pointer || !stream->enable_cse || disable_cse_ || is_special, cse_key_inserted = false; // Check if this exact statement already exists .. if (!disable_cse) std::tie(key_it, cse_key_inserted) = state.cse_cache.try_emplace(VariableKey(v), 0); uint32_t index; Variable *v_out; if (likely(disable_cse || cse_key_inserted)) { // .. nope, it is new. VariableMap::iterator var_it; bool var_inserted; do { index = state.variable_index++; if (unlikely(index == 0)) // overflow index = state.variable_index++; std::tie(var_it, var_inserted) = state.variables.try_emplace(index, v); } while (!var_inserted); if (cse_key_inserted) key_it.value() = index; v_out = &var_it.value(); } else { // .. found a match! Deallocate 'v'. if (v.free_stmt) free(v.stmt); for (int i = 0; i < 4; ++i) jit_var_dec_ref_int(v.dep[i]); index = key_it.value(); v_out = jit_var(index); } return std::make_pair(index, v_out); } /// Query the pointer variable associated with a given variable void *jit_var_ptr(uint32_t index) { return index == 0u ? nullptr : jit_var(index)->data; } /// Query the size of a given variable uint32_t jit_var_size(uint32_t index) { return jit_var(index)->size; } /// Query the type of a given variable VarType jit_var_type(uint32_t index) { return (VarType) jit_var(index)->type; } // Resize a scalar variable uint32_t jit_var_set_size(uint32_t index, uint32_t size) { Variable *v = jit_var(index); jit_log(Debug, "jit_var_set_size(%u): %u", index, size); if (v->size == size) { jit_var_inc_ref_ext(index, v); return index; // Nothing to do } else if (v->size != 1) { jit_raise("jit_var_set_size(): variable %u must be a scalar variable!", index); } else if (v->stmt && v->ref_count_int == 0 && v->ref_count_ext == 1) { jit_var_inc_ref_ext(index, v); jit_cse_drop(index, v); v->size = size; return index; } else if (v->is_literal_zero) { return jit_var_new_literal((VarType) v->type, v->cuda, 0, size, 0); } else { Stream *stream = active_stream; uint32_t index_new; if (stream->cuda) { index_new = jit_var_new_1((VarType) v->type, "mov.$t0 $r0, $r1", 1, 1, index); } else { const char *op = jitc_is_floating_point((VarType) v->type) ? "$r0 = fadd <$w x $t0> $r1, $z" : "$r0 = add <$w x $t0> $r1, $z"; index_new = jit_var_new_1((VarType) v->type, op, 1, 0, index); } Variable *v2 = jit_var(index_new); jit_cse_drop(index_new, v2); v2->size = size; return index_new; } } /// Query the descriptive label associated with a given variable const char *jit_var_label(uint32_t index) { ExtraMap::iterator it = state.extra.find(index); return it != state.extra.end() ? it.value().label : nullptr; } /// Assign a descriptive label to a given variable void jit_var_set_label(uint32_t index, const char *label) { Variable *v = jit_var(index); jit_log(Debug, "jit_var_set_label(%u): \"%s\"", index, label ? label : "(null)"); v->has_extra = true; Extra &extra = state.extra[index]; free(extra.label); extra.label = label ? strdup(label) : nullptr; } void jit_var_set_free_callback(uint32_t index, void (*callback)(void *), void *payload) { Variable *v = jit_var(index); jit_log(Debug, "jit_var_set_callback(%u): " ENOKI_PTR " (" ENOKI_PTR ")", index, (uintptr_t) callback, (uintptr_t) payload); v->has_extra = true; Extra &extra = state.extra[index]; if (unlikely(extra.free_callback)) jit_fail("jit_var_set_free_callback(): a callback was already set!"); extra.free_callback = callback; extra.callback_payload = payload; } uint32_t jit_var_new_literal(VarType type, int cuda, uint64_t value, uint32_t size, int eval) { if (unlikely(size == 0)) return 0; if (unlikely(eval)) { void *ptr = jit_malloc(cuda ? AllocType::Device : AllocType::HostAsync, size * var_type_size[(int) type]); if (size == 1) jit_poke(ptr, &value, var_type_size[(int) type]); else jit_memset_async(ptr, size, var_type_size[(int) type], &value); return jit_var_map_mem(type, cuda, ptr, size, true); } bool is_literal_one, is_literal_zero = value == 0; bool is_float = true, is_uint8 = false; switch (type) { case VarType::Float16: is_literal_one = value == 0x3c00ull; break; case VarType::Float32: is_literal_one = value == 0x3f800000ull; // LLVM: double hex floats, even in single precision if (!cuda) { float f = 0.f; memcpy(&f, &value, sizeof(float)); double d = (double) f; memcpy(&value, &d, sizeof(double)); } break; case VarType::Float64: is_literal_one = value == 0x3ff0000000000000ull; break; default: is_literal_one = value == 1; is_float = false; is_uint8 = type == VarType::Int8 || type == VarType::UInt8; break; } const char *digits = "0123456789abcdef"; char digits_buf[20]; int n_digits = 0; /* This is function is performance-critical. The following hand-written code replaces a previous 'snprintf' implementation that was too slow. */ if (cuda || is_float) { // Hex digits for CUDA, and floats in LLVM mode do { digits_buf[sizeof(digits_buf) - 1 - n_digits++] = digits[value & 0xF]; value >>= 4; } while (value); } else { // Base-10 digits for LLVM integers do { digits_buf[sizeof(digits_buf) - 1 - n_digits++] = digits[value % 10]; value /= 10; } while (value); } int bytes_required; if (cuda) bytes_required = is_uint8 ? 37 : 16; else bytes_required = 124; bytes_required += n_digits; char *stmt = (char *) malloc_check(bytes_required), *ptr = stmt; if (cuda) { if (unlikely(is_uint8)) { memcpy(ptr, "mov.b16 %w1, 0x", 15); ptr += 15; memcpy(ptr, digits_buf + sizeof(digits_buf) - n_digits, n_digits); ptr += n_digits; memcpy(ptr, "$ncvt.u8.u16 $r0, %w1", 21); ptr += 21; } else { memcpy(ptr, "mov.$b0 $r0, 0x", 15); ptr += 15; memcpy(ptr, digits_buf + sizeof(digits_buf) - n_digits, n_digits); ptr += n_digits; } } else { memcpy(ptr, "$r0_0 = insertelement <$w x $t0> undef, $t0 ", 44); ptr += 44; if (type == VarType::Float32 || type == VarType::Float64) { memcpy(ptr, "0x", 2); ptr += 2; } memcpy(ptr, digits_buf + sizeof(digits_buf) - n_digits, n_digits); ptr += n_digits; memcpy(ptr, ", i32 0$n$r0 = shufflevector <$w x $t0> $r0_0, " "<$w x $t0> undef, <$w x i32> $z", 78); ptr += 78; } *ptr = '\0'; Variable v; v.type = (uint32_t) type; v.size = size; v.stmt = stmt; v.tsize = 1; v.free_stmt = 1; v.cuda = cuda; v.is_literal_zero = is_literal_zero; v.is_literal_one = is_literal_one; uint32_t index; Variable *vo; std::tie(index, vo) = jit_var_new(v, size != 1); jit_log(Debug, "jit_var_new_literal(%u): %s%s", index, vo->stmt, vo->ref_count_int + vo->ref_count_ext == 0 ? "" : " (reused)"); jit_var_inc_ref_ext(index, vo); return index; } /// Append a variable to the instruction trace (no operands) uint32_t jit_var_new_0(VarType type, const char *stmt, int stmt_static, int cuda, uint32_t size) { if (unlikely(size == 0)) return 0; Variable v; v.type = (uint32_t) type; v.size = size; v.stmt = stmt_static ? (char *) stmt : strdup(stmt); v.tsize = 1; v.free_stmt = stmt_static == 0; v.cuda = cuda; uint32_t index; Variable *vo; std::tie(index, vo) = jit_var_new(v); jit_log(Debug, "jit_var_new(%u): %s%s", index, vo->stmt, vo->ref_count_int + vo->ref_count_ext == 0 ? "" : " (reused)"); jit_var_inc_ref_ext(index, vo); return index; } /// Append a variable to the instruction trace (1 operand) uint32_t jit_var_new_1(VarType type, const char *stmt, int stmt_static, int cuda, uint32_t op1) { if (unlikely(op1 == 0)) return 0; Variable *v1 = jit_var(op1); Variable v; v.type = (uint32_t) type; v.size = v1->size; v.stmt = stmt_static ? (char *) stmt : strdup(stmt); v.dep[0] = op1; v.tsize = 1 + v1->tsize; v.free_stmt = stmt_static == 0; v.cuda = cuda; if (unlikely(v1->pending_scatter)) { jit_eval(); v1 = jit_var(op1); v.tsize = 2; } jit_var_inc_ref_int(op1, v1); uint32_t index; Variable *vo; std::tie(index, vo) = jit_var_new(v); jit_log(Debug, "jit_var_new(%u <- %u): %s%s", index, op1, vo->stmt, vo->ref_count_int + vo->ref_count_ext == 0 ? "" : " (reused)"); jit_var_inc_ref_ext(index, vo); return index; } /// Append a variable to the instruction trace (2 operands) uint32_t jit_var_new_2(VarType type, const char *stmt, int stmt_static, int cuda, uint32_t op1, uint32_t op2) { if (unlikely(op1 == 0 && op2 == 0)) return 0; if (unlikely(op1 == 0 || op2 == 0)) jit_raise("jit_var_new(): arithmetic involving " "uninitialized variable!"); Variable *v1 = jit_var(op1), *v2 = jit_var(op2); Variable v; v.type = (uint32_t) type; v.size = std::max(v1->size, v2->size); v.stmt = stmt_static ? (char *) stmt : strdup(stmt); v.dep[0] = op1; v.dep[1] = op2; v.tsize = 1 + v1->tsize + v2->tsize; v.free_stmt = stmt_static == 0; v.cuda = cuda; if (unlikely((v1->size != 1 && v1->size != v.size) || (v2->size != 1 && v2->size != v.size))) { jit_raise( "jit_var_new(): arithmetic involving arrays of incompatible " "size (%u and %u). The instruction was \"%s\".", v1->size, v2->size, stmt); } else if (unlikely(v1->pending_scatter || v2->pending_scatter)) { jit_eval(); v1 = jit_var(op1); v2 = jit_var(op2); v.tsize = 3; } jit_var_inc_ref_int(op1, v1); jit_var_inc_ref_int(op2, v2); uint32_t index; Variable *vo; std::tie(index, vo) = jit_var_new(v); jit_log(Debug, "jit_var_new(%u <- %u, %u): %s%s", index, op1, op2, vo->stmt, vo->ref_count_int + vo->ref_count_ext == 0 ? "" : " (reused)"); jit_var_inc_ref_ext(index, vo); return index; } /// Append a variable to the instruction trace (3 operands) uint32_t jit_var_new_3(VarType type, const char *stmt, int stmt_static, int cuda, uint32_t op1, uint32_t op2, uint32_t op3) { if (unlikely(op1 == 0 && op2 == 0 && op3 == 0)) return 0; else if (unlikely(op1 == 0 || op2 == 0 || op3 == 0)) jit_raise("jit_var_new(): arithmetic involving " "uninitialized variable!"); Variable *v1 = jit_var(op1), *v2 = jit_var(op2), *v3 = jit_var(op3); Variable v; v.type = (uint32_t) type; v.size = std::max({ v1->size, v2->size, v3->size }); v.stmt = stmt_static ? (char *) stmt : strdup(stmt); v.dep[0] = op1; v.dep[1] = op2; v.dep[2] = op3; v.tsize = 1 + v1->tsize + v2->tsize + v3->tsize; v.free_stmt = stmt_static == 0; v.cuda = cuda; if (unlikely((v1->size != 1 && v1->size != v.size) || (v2->size != 1 && v2->size != v.size) || (v3->size != 1 && v3->size != v.size))) { jit_raise("jit_var_new(): arithmetic involving arrays of incompatible " "size (%u, %u, and %u). The instruction was \"%s\".", v1->size, v2->size, v3->size, stmt); } else if (unlikely(v1->pending_scatter || v2->pending_scatter || v3->pending_scatter)) { jit_eval(); v1 = jit_var(op1); v2 = jit_var(op2); v3 = jit_var(op3); v.tsize = 4; } jit_var_inc_ref_int(op1, v1); jit_var_inc_ref_int(op2, v2); jit_var_inc_ref_int(op3, v3); uint32_t index; Variable *vo; std::tie(index, vo) = jit_var_new(v); jit_log(Debug, "jit_var_new(%u <- %u, %u, %u): %s%s", index, op1, op2, op3, vo->stmt, vo->ref_count_int + vo->ref_count_ext == 0 ? "" : " (reused)"); jit_var_inc_ref_ext(index, vo); return index; } /// Append a variable to the instruction trace (4 operands) uint32_t jit_var_new_4(VarType type, const char *stmt, int stmt_static, int cuda, uint32_t op1, uint32_t op2, uint32_t op3, uint32_t op4) { if (unlikely(op1 == 0 && op2 == 0 && op3 == 0 && op4 == 0)) return 0; else if (unlikely(op1 == 0 || op2 == 0 || op3 == 0 || op4 == 0)) jit_raise("jit_var_new(): arithmetic involving " "uninitialized variable!"); Variable *v1 = jit_var(op1), *v2 = jit_var(op2), *v3 = jit_var(op3), *v4 = jit_var(op4); Variable v; v.type = (uint32_t) type; v.size = std::max({ v1->size, v2->size, v3->size, v4->size }); v.stmt = stmt_static ? (char *) stmt : strdup(stmt); v.dep[0] = op1; v.dep[1] = op2; v.dep[2] = op3; v.dep[3] = op4; v.tsize = 1 + v1->tsize + v2->tsize + v3->tsize + v4->tsize; v.free_stmt = stmt_static == 0; v.cuda = cuda; if (unlikely((v1->size != 1 && v1->size != v.size) || (v2->size != 1 && v2->size != v.size) || (v3->size != 1 && v3->size != v.size) || (v4->size != 1 && v4->size != v.size))) { jit_raise( "jit_var_new(): arithmetic involving arrays of incompatible " "size (%u, %u, %u, and %u). The instruction was \"%s\".", v1->size, v2->size, v3->size, v4->size, stmt); } else if (unlikely(v1->pending_scatter || v2->pending_scatter || v3->pending_scatter || v4->pending_scatter)) { jit_eval(); v1 = jit_var(op1); v2 = jit_var(op2); v3 = jit_var(op3); v4 = jit_var(op4); v.tsize = 5; } jit_var_inc_ref_int(op1, v1); jit_var_inc_ref_int(op2, v2); jit_var_inc_ref_int(op3, v3); jit_var_inc_ref_int(op4, v4); uint32_t index; Variable *vo; std::tie(index, vo) = jit_var_new(v); jit_log(Debug, "jit_var_new(%u <- %u, %u, %u, %u): %s%s", index, op1, op2, op3, op4, vo->stmt, vo->ref_count_int + vo->ref_count_ext == 0 ? "" : " (reused)"); jit_var_inc_ref_ext(index, vo); return index; } /// Register an existing variable with the JIT compiler uint32_t jit_var_map_mem(VarType type, int cuda, void *ptr, uint32_t size, int free) { if (unlikely(size == 0)) return 0; Variable v; v.type = (uint32_t) type; v.data = ptr; v.size = size; v.retain_data = free == 0; v.tsize = 1; v.cuda = cuda; if (cuda == 0) { uintptr_t align = std::min(64u, jit_llvm_vector_width * var_type_size[(int) type]); v.unaligned = uintptr_t(ptr) % align != 0; } uint32_t index; Variable *vo; std::tie(index, vo) = jit_var_new(v); jit_log(Debug, "jit_var_map_mem(%u): " ENOKI_PTR ", size=%u, free=%i", index, (uintptr_t) ptr, size, (int) free); jit_var_inc_ref_ext(index, vo); return index; } /// Copy a memory region onto the device and return its variable index uint32_t jit_var_copy_mem(AllocType atype, VarType vtype, int cuda, const void *ptr, uint32_t size) { Stream *stream = active_stream; if (unlikely(!stream)) { jit_raise("jit_var_copy_mem(): you must invoke jitc_set_device() to " "choose a target device before using this function."); } else if (unlikely((bool) cuda != stream->cuda)) { jit_raise( "jit_var_copy_mem(): attempted to copy to a %s array while the %s " "backend was active! You must invoke jit_set_device() to set " "the right backend!", cuda ? "CUDA" : "LLVM", stream->cuda ? "CUDA" : "LLVM"); } size_t total_size = (size_t) size * (size_t) var_type_size[(int) vtype]; void *target_ptr; if (stream->cuda) { target_ptr = jit_malloc(AllocType::Device, total_size); if (atype == AllocType::Auto) { unsigned int result = 0; CUresult rv = cuPointerGetAttribute( &result, CU_POINTER_ATTRIBUTE_MEMORY_TYPE, (CUdeviceptr) ptr); if (rv == CUDA_ERROR_INVALID_VALUE || result == CU_MEMORYTYPE_HOST) atype = AllocType::Host; else atype = AllocType::Device; } scoped_set_context guard(stream->context); if (atype == AllocType::HostAsync) { jit_fail("jit_var_copy_mem(): copy from HostAsync to GPU memory not supported!"); } else if (atype == AllocType::Host) { void *host_ptr = jit_malloc(AllocType::HostPinned, total_size); memcpy(host_ptr, ptr, total_size); cuda_check(cuMemcpyAsync((CUdeviceptr) target_ptr, (CUdeviceptr) host_ptr, total_size, stream->handle)); jit_free(host_ptr); } else { cuda_check(cuMemcpyAsync((CUdeviceptr) target_ptr, (CUdeviceptr) ptr, total_size, stream->handle)); } } else { if (atype == AllocType::HostAsync) { target_ptr = jit_malloc(AllocType::HostAsync, total_size); jit_memcpy_async(target_ptr, ptr, total_size); } else if (atype == AllocType::Host) { target_ptr = jit_malloc(AllocType::Host, total_size); memcpy(target_ptr, ptr, total_size); target_ptr = jit_malloc_migrate(target_ptr, AllocType::HostAsync, 1); } else { jit_fail("jit_var_copy_mem(): copy from GPU to HostAsync memory not supported!"); } } uint32_t index = jit_var_map_mem(vtype, cuda, target_ptr, size, true); jit_log(Debug, "jit_var_copy_mem(%u, size=%u)", index, size); return index; } /// Register pointer literal as a special variable within the JIT compiler uint32_t jit_var_copy_ptr(const void *ptr, uint32_t index) { auto it = state.variable_from_ptr.find(ptr); if (it != state.variable_from_ptr.end()) { uint32_t index = it.value(); jit_var_inc_ref_ext(index); return index; } Variable v; v.type = (uint32_t) VarType::Pointer; v.data = (void *) ptr; v.size = 1; v.tsize = 0; v.retain_data = true; v.dep[0] = index; v.direct_pointer = true; v.cuda = active_stream->cuda; jit_var_inc_ref_ext(index); uint32_t index_o; Variable *vo; std::tie(index_o, vo) = jit_var_new(v); jit_log(Debug, "jit_var_copy_ptr(%u <- %u): " ENOKI_PTR, index_o, index, (uintptr_t) ptr); jit_var_inc_ref_ext(index_o, vo); state.variable_from_ptr[ptr] = index_o; return index_o; } uint32_t jit_var_copy_var(uint32_t index) { if (index == 0) return 0; Variable *v = jit_var(index); if (v->pending_scatter) { jit_var_eval(index); v = jit_var(index); } uint32_t index_old = index; if (v->data) { index = jit_var_copy_mem(v->cuda ? AllocType::Device : AllocType::HostAsync, (VarType) v->type, v->cuda, v->data, v->size); } else { Variable v2 = *v; v2.ref_count_int = 0; v2.ref_count_ext = 0; v2.has_extra = 0; if (v2.free_stmt) v2.stmt = strdup(v2.stmt); std::tie(index, v) = jit_var_new(v2, true); jit_var_inc_ref_ext(index, v); } jit_log(Debug, "jit_var_copy_var(%u <- %u)", index, index_old); return index; } /// Migrate a variable to a different flavor of memory uint32_t jit_var_migrate(uint32_t src_index, AllocType dst_type) { if (src_index == 0) return 0; jit_var_eval(src_index); Variable *v = jit_var(src_index); auto it = state.alloc_used.find(v->data); if (unlikely(it == state.alloc_used.end())) jit_raise("jit_var_migrate(): Cannot resolve pointer to actual allocation!"); AllocInfo ai = it.value(); uint32_t dst_index = src_index; void *src_ptr = v->data, *dst_ptr = jit_malloc_migrate(src_ptr, dst_type, 0); if (src_ptr != dst_ptr) { Variable v2 = *v; v2.data = dst_ptr; v2.retain_data = false; v2.ref_count_int = 0; v2.ref_count_ext = 0; std::tie(dst_index, v) = jit_var_new(v2); } jit_var_inc_ref_ext(dst_index, v); jit_log(Debug, "jit_var_migrate(%u -> %u, " ENOKI_PTR " -> " ENOKI_PTR ", %s -> %s)", src_index, dst_index, (uintptr_t) src_ptr, (uintptr_t) dst_ptr, alloc_type_name[ai.type], alloc_type_name[(int) dst_type]); return dst_index; } /// Query the current (or future, if not yet evaluated) allocation flavor of a variable AllocType jit_var_alloc_type(uint32_t index) { const Variable *v = jit_var(index); if (v->data) return jit_malloc_type(v->data); return v->cuda ? AllocType::Device : AllocType::HostAsync; } /// Query the device (or future, if not yet evaluated) associated with a variable int jit_var_device(uint32_t index) { const Variable *v = jit_var(index); if (v->data) return jit_malloc_device(v->data); Stream *stream = active_stream; if (unlikely(!stream)) jit_raise("jit_var_device(): you must invoke jitc_set_device() to " "choose a target device before using this function."); return stream->device; } /// Mark a variable as a scatter operation that writes to 'target' void jit_var_mark_scatter(uint32_t index, uint32_t target) { Stream *stream = active_stream; if (unlikely(!stream)) jit_raise("jit_var_mark_scatter(): you must invoke jitc_set_device() to " "choose a target device before using this function."); jit_log(Debug, "jit_var_mark_scatter(%u, %u)", index, target); // Update scatter operation Variable *v = jit_var(index); v->scatter = true; stream->todo.push_back(index); stream->side_effect_counter++; // Update target variable if (target) { v = jit_var(target); v->pending_scatter = true; } } /// Is the given variable a literal that equals zero? int jit_var_is_literal_zero(uint32_t index) { if (index == 0) return 0; return jit_var(index)->is_literal_zero; } /// Is the given variable a literal that equals one? int jit_var_is_literal_one(uint32_t index) { if (index == 0) return 0; return jit_var(index)->is_literal_one; } /// Return a human-readable summary of registered variables const char *jit_var_whos() { buffer.clear(); buffer.put("\n ID Type Status E/I Refs Entries Storage Label"); buffer.put("\n ========================================================================\n"); std::vector<uint32_t> indices; indices.reserve(state.variables.size()); for (const auto& it : state.variables) indices.push_back(it.first); std::sort(indices.begin(), indices.end()); size_t mem_size_evaluated = 0, mem_size_saved = 0, mem_size_unevaluated = 0; for (uint32_t index: indices) { const Variable *v = jit_var(index); size_t mem_size = (size_t) v->size * (size_t) var_type_size[v->type]; buffer.fmt(" %-9u %s %3s ", index, v->cuda ? "cuda" : "llvm", var_type_name_short[v->type]); if (v->direct_pointer) { buffer.put("direct ptr."); } else if (v->data) { auto it = state.alloc_used.find(v->data); if (unlikely(it == state.alloc_used.end())) { if (!v->retain_data) jit_raise("jit_var_whos(): Cannot resolve pointer to actual allocation!"); else buffer.put("mapped mem."); } else { AllocInfo ai = it.value(); if ((AllocType) ai.type == AllocType::Device) buffer.fmt("device %-4i", (int) ai.device); else buffer.put(alloc_type_name_short[ai.type]); } } else { buffer.put("[not ready]"); } size_t sz = buffer.fmt(" %u / %u", v->ref_count_ext, v->ref_count_int); const char *label = jit_var_label(index); buffer.fmt("%*s%-12u%-8s %s\n", 12 - (int) sz, "", v->size, jit_mem_string(mem_size), label ? label : ""); if (v->direct_pointer) continue; else if (v->data) mem_size_evaluated += mem_size; else if (v->ref_count_ext == 0) mem_size_saved += mem_size; else mem_size_unevaluated += mem_size; } if (indices.empty()) buffer.put(" -- No variables registered --\n"); buffer.put(" ========================================================================\n\n"); buffer.put(" JIT compiler\n"); buffer.put(" ============\n"); buffer.fmt(" - Memory usage (evaluated) : %s.\n", jit_mem_string(mem_size_evaluated)); buffer.fmt(" - Memory usage (unevaluated) : %s.\n", jit_mem_string(mem_size_unevaluated)); buffer.fmt(" - Memory usage (saved) : %s.\n", jit_mem_string(mem_size_saved)); buffer.fmt(" - Kernel launches : %zu (%zu cache hits, " "%zu soft, %zu hard misses).\n\n", state.kernel_launches, state.kernel_hits, state.kernel_soft_misses, state.kernel_hard_misses); buffer.put(" Memory allocator\n"); buffer.put(" ================\n"); for (int i = 0; i < (int) AllocType::Count; ++i) buffer.fmt(" - %-20s: %s/%s used (peak: %s).\n", alloc_type_name[i], std::string(jit_mem_string(state.alloc_usage[i])).c_str(), std::string(jit_mem_string(state.alloc_allocated[i])).c_str(), std::string(jit_mem_string(state.alloc_watermark[i])).c_str()); return buffer.get(); } /// Return a GraphViz representation of registered variables const char *jit_var_graphviz() { std::vector<uint32_t> indices; indices.reserve(state.variables.size()); for (const auto& it : state.variables) indices.push_back(it.first); std::sort(indices.begin(), indices.end()); buffer.clear(); buffer.put("digraph {\n"); buffer.put(" graph [dpi=50];\n"); buffer.put(" node [shape=record fontname=Consolas];\n"); buffer.put(" edge [fontname=Consolas];\n"); for (uint32_t index: indices) { const Variable *v = jit_var(index); const char *color = ""; const char *stmt = v->stmt; if (v->direct_pointer) { color = " fillcolor=wheat style=filled"; stmt = "[direct pointer]"; } else if (v->data) { color = " fillcolor=salmon style=filled"; stmt = "[evaluated array]"; } else if (v->scatter) { color = " fillcolor=cornflowerblue style=filled"; } char *out = (char *) malloc(strlen(stmt) * 2 + 1), *ptr = out; for (int j = 0; ; ++j) { if (stmt[j] == '$' && stmt[j + 1] == 'n') { *ptr++='\\'; continue; } else if (stmt[j] == '<' || stmt[j] == '>') { *ptr++='\\'; } *ptr++ = stmt[j]; if (stmt[j] == '\0') break; } const char *label = jit_var_label(index); buffer.fmt(" %u [label=\"{%s%s%s%s%s|{Type: %s %s|Size: %u}|{ID " "#%u|E:%u|I:%u}}\"%s];\n", index, out, label ? "|Label: \\\"" : "", label ? label : "", label ? "\\\"" : "", v->pending_scatter ? "| ** DIRTY **" : "", v->cuda ? "cuda" : "llvm", v->type == (int) VarType::Invalid ? "none" : var_type_name_short[v->type], v->size, index, v->ref_count_ext, v->ref_count_int, color); free(out); for (uint32_t i = 0; i< 4; ++i) { if (v->dep[i]) buffer.fmt(" %u -> %u [label=\" %u\"];\n", v->dep[i], index, i + 1); } } buffer.put("}\n"); return buffer.get(); } /// Return a human-readable summary of the contents of a variable const char *jit_var_str(uint32_t index) { jit_var_eval(index); const Variable *v = jit_var(index); Stream *stream = active_stream; if (unlikely(v->cuda != stream->cuda)) jit_raise("jit_var_str(): attempted to stringify a %s variable " "while the %s backend was activated! You must invoke " "jit_set_device() to set the right backend!", v->cuda ? "CUDA" : "LLVM", stream->cuda ? "CUDA" : "LLVM"); else if (unlikely(v->pending_scatter)) jit_raise("jit_var_str(): element remains dirty after evaluation!"); else if (unlikely(!v->data)) jit_raise("jit_var_str(): invalid/uninitialized variable!"); size_t size = v->size, isize = var_type_size[v->type], limit_remainder = std::min(5u, (state.print_limit + 3) / 4) * 2; uint8_t dst[8]; const uint8_t *src = (const uint8_t *) v->data; buffer.clear(); buffer.putc('['); for (uint32_t i = 0; i < size; ++i) { if (size > state.print_limit && i == limit_remainder / 2) { buffer.fmt(".. %zu skipped .., ", size - limit_remainder); i = (uint32_t) (size - limit_remainder / 2 - 1); continue; } const uint8_t *src_offset = src + i * isize; jit_memcpy(dst, src_offset, isize); const char *comma = i + 1 < (uint32_t) size ? ", " : ""; switch ((VarType) v->type) { case VarType::Bool: buffer.fmt("%" PRIu8 "%s", *(( uint8_t *) dst), comma); break; case VarType::Int8: buffer.fmt("%" PRId8 "%s", *(( int8_t *) dst), comma); break; case VarType::UInt8: buffer.fmt("%" PRIu8 "%s", *(( uint8_t *) dst), comma); break; case VarType::Int16: buffer.fmt("%" PRId16 "%s", *(( int16_t *) dst), comma); break; case VarType::UInt16: buffer.fmt("%" PRIu16 "%s", *((uint16_t *) dst), comma); break; case VarType::Int32: buffer.fmt("%" PRId32 "%s", *(( int32_t *) dst), comma); break; case VarType::UInt32: buffer.fmt("%" PRIu32 "%s", *((uint32_t *) dst), comma); break; case VarType::Int64: buffer.fmt("%" PRId64 "%s", *(( int64_t *) dst), comma); break; case VarType::UInt64: buffer.fmt("%" PRIu64 "%s", *((uint64_t *) dst), comma); break; case VarType::Pointer: buffer.fmt("0x%" PRIx64 "%s", *((uint64_t *) dst), comma); break; case VarType::Float32: buffer.fmt("%g%s", *((float *) dst), comma); break; case VarType::Float64: buffer.fmt("%g%s", *((double *) dst), comma); break; default: jit_fail("jit_var_str(): invalid type!"); } } buffer.putc(']'); return buffer.get(); } /// Schedule a variable \c index for future evaluation via \ref jitc_eval() int jit_var_schedule(uint32_t index) { Stream *stream = active_stream; if (unlikely(!stream)) jit_raise("jit_var_schedule(): you must invoke jitc_set_device() to " "choose a target device before using this function."); auto it = state.variables.find(index); if (unlikely(it == state.variables.end())) jit_raise("jit_var_schedule(%u): unknown variable!", index); Variable *v = &it.value(); if (v->data == nullptr && !v->direct_pointer) { if (unlikely(v->cuda != stream->cuda)) jit_raise("jit_var_schedule(): attempted to schedule a %s variable " "while the %s backend was activated! You must invoke " "jit_set_device() to set the right backend!", v->cuda ? "CUDA" : "LLVM", stream->cuda ? "CUDA" : "LLVM"); stream->todo.push_back(index); jit_log(Debug, "jit_var_schedule(%u)", index); return 1; } else if (v->pending_scatter) { return 1; } return 0; } /// Evaluate the variable \c index right away, if it is unevaluated/dirty. int jit_var_eval(uint32_t index) { Stream *stream = active_stream; auto it = state.variables.find(index); if (unlikely(it == state.variables.end())) jit_raise("jit_var_eval(%u): unknown variable!", index); Variable *v = &it.value(); bool unevaluated = v->data == nullptr && !v->direct_pointer; if (unevaluated || v->pending_scatter) { if (unlikely(!stream)) jit_raise("jit_var_eval(): you must invoke jitc_set_device() to " "choose a target device before using this function."); else if (unlikely(v->cuda != stream->cuda)) jit_raise("jit_var_eval(): attempted to evaluate a %s variable " "while the %s backend was activated! You must invoke " "jit_set_device() to set the right backend!", v->cuda ? "CUDA" : "LLVM", stream->cuda ? "CUDA" : "LLVM"); if (unevaluated) { if (v->is_literal_zero) { /* Optimization: don't bother building a kernel just to zero-initialize a single variable and use an jit_memset_async() call instead. This fits the common use case of creating an arrays of zero and then scattering into it (which will call jit_var_eval() on the target array)*/ jit_cse_drop(index, v); if (v->free_stmt) { free(v->stmt); v->free_stmt = 0; } v->stmt = nullptr; v->is_literal_zero = false; uint32_t isize = var_type_size[v->type]; v->data = jit_malloc(stream->cuda ? AllocType::Device : AllocType::HostAsync, (size_t) v->size * (size_t) isize); uint64_t zero = 0; jit_memset_async(v->data, v->size, isize, &zero); return 1; } else { stream->todo.push_back(index); } } jit_eval(); v = jit_var(index); if (unlikely(v->pending_scatter)) jit_raise("jit_var_eval(): element remains dirty after evaluation!"); else if (unlikely(!v->data)) jit_raise("jit_var_eval(): invalid/uninitialized variable!"); return 1; } return 0; } /// Read a single element of a variable and write it to 'dst' void jit_var_read(uint32_t index, uint32_t offset, void *dst) { jit_var_eval(index); Variable *v = jit_var(index); if (v->size == 1) offset = 0; else if (unlikely(offset >= v->size)) jit_raise("jit_var_read(): attempted to access entry %u in an array of " "size %u!", offset, v->size); size_t isize = var_type_size[v->type]; const uint8_t *src = (const uint8_t *) v->data + (size_t) offset * isize; jit_memcpy(dst, src, isize); } /// Reverse of jit_var_read(). Copy 'dst' to a single element of a variable void jit_var_write(uint32_t index, uint32_t offset, const void *src) { jit_var_eval(index); Variable *v = jit_var(index); if (unlikely(offset >= v->size)) jit_raise("jit_var_write(): attempted to access entry %u in an array of " "size %u!", offset, v->size); uint32_t isize = var_type_size[v->type]; uint8_t *dst = (uint8_t *) v->data + (size_t) offset * isize; jit_poke(dst, src, isize); }
#include <iostream> #include <vector> #include <algorithm> #include <cstring> using namespace std; int v, e; class Edge{ public: int i = 0; int j = 0; int weight = 0; bool operator<(const Edge &v) const{ return weight < v.weight; } Edge(int i = 0, int j = 0, int weight = 0) :i(i), j(j), weight(weight) {} }; int vRoot[10001] = {0, }; vector<Edge> edges; int cost = 0; int findRoot(int v){ if(vRoot[v] == v){ return v; } return vRoot[v] = findRoot(vRoot[v]); } void kruskal(){ //sort부터 한다 weight 오름차순으로 //각 노드의 루트를 정의해준다 sort(edges.begin(), edges.end()); for(Edge it : edges){ //현재 간선을 놓을때 cycle이 발생하나 여부 확인 //-> 노드 i 와 노드 j 의 각 뿌리가 같으면 cycle 발생(이미 연결되어있다) //-> 각 뿌리가 다르면 연결해도 됨. int rootI = findRoot(it.i); int rootJ = findRoot(it.j); if(rootI != rootJ){ //union find 연결. //서로의 뿌리끼리 연결해준다. vRoot[rootJ] = rootI; cost += it.weight; } } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> v >> e; for(int i = 1; i <= v; i++){ vRoot[i] = i; } while(e--){ int i, j, w; cin >> i >> j >> w; edges.push_back(Edge(i, j, w)); } kruskal(); cout << cost << endl; return 0; }
#include <ros/ros.h> #include "FakeMarkerPublisher.h" int main(int argc, char *argv[]) { ros::init(argc, argv, "fake_marker_pub"); FakeMarkerPublisher fmp; if (!fmp.initialize()) { ROS_ERROR("Failed to initialize Fake Marker Publisher"); return 1; } return fmp.run(); }
// BEGIN CUT HERE // PROBLEM STATEMENT // // Dr. Agnew and Dr. Austin have acquired a bag of stones, // each containing some amount of silver and gold. // Dr. Agnew is only interested in the silver contained in // the stones, while // Dr. Austin is only interested in the gold. // Using their sophisticated instruments, they have measured // the value of the silver and gold in each stone. // They want to divide the stones between them, cutting some // if necessary, // in such a way that they each get the same value of the // element they are interested in, // and that that value is as high as possible. // // // // Given the value of silver and gold in each stone, // determine the highest value that both Dr. Agnew and Dr. // Austin can receive of the element they want. // Assume that each element is distributed uniformly within // each stone, // so that if they cut a stone in two parts, each part will // have the same ratio of elements as did the whole stone. // Between them they must take all of the stones, without // throwing any out. // // // // The value of the precious elements in each stone will be // given as two vector <int>s, silver and gold, // where silver[i] and gold[i] give the value of the silver // and gold, respectively, in stone i. // // // DEFINITION // Class:PreciousStones // Method:value // Parameters:vector <int>, vector <int> // Returns:double // Method signature:double value(vector <int> silver, vector // <int> gold) // // // NOTES // -The returned value must be accurate to within a relative // or absolute value of 1e-9. // // // CONSTRAINTS // -silver and gold will each contain between 1 and 50 // elements, inclusive. // -silver and gold will contain the same number of elements. // -Each element of silver and gold will be between 0 and // 100, inclusive. // // // EXAMPLES // // 0) // { 10, 6 } // { 3, 10 } // // Returns: 10.0 // // If Dr. Agnew takes the first stone and Dr. Austin takes // the second, they can each get a value of 10. // // 1) // { 30 } // { 15 } // // Returns: 10.0 // // They cut the stone into pieces of size 1/3 and 2/3. Dr. // Agnew takes the smaller piece (value = 30*1/3 = 10) and // Dr. Austin takes the larger piece (value = 15*2/3 = 10). // // 2) // { 0, 0 } // { 10, 11 } // // Returns: 0.0 // // There is no silver. The only way for each person to get // an equal value is for Dr. Agnew to take both stones. // // 3) // { 3, 5, 4 } // { 3, 5, 4 } // // Returns: 6.0 // // There are multiple ways for each doctor to get a value of // 6. One way is for both of them to take half of each stone. // // 4) // { 1, 2, 3 } // { 2, 2, 2 } // // Returns: 3.5 // // // // 5) // { 11, 9, 13, 10 } // // { 8, 14, 17, 21 } // // Returns: 28.304347826086957 // // // // END CUT HERE #line 117 "PreciousStones.cc" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; class PreciousStones { public: double value(vector <int> silver, vector <int> gold) { } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = { 10, 6 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 3, 10 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 10.0; verify_case(0, Arg2, value(Arg0, Arg1)); } void test_case_1() { int Arr0[] = { 30 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 15 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 10.0; verify_case(1, Arg2, value(Arg0, Arg1)); } void test_case_2() { int Arr0[] = { 0, 0 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 10, 11 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 0.0; verify_case(2, Arg2, value(Arg0, Arg1)); } void test_case_3() { int Arr0[] = { 3, 5, 4 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 3, 5, 4 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 6.0; verify_case(3, Arg2, value(Arg0, Arg1)); } void test_case_4() { int Arr0[] = { 1, 2, 3 }; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 2, 2, 2 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 3.5; verify_case(4, Arg2, value(Arg0, Arg1)); } void test_case_5() { int Arr0[] = { 11, 9, 13, 10 } ; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = { 8, 14, 17, 21 }; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); double Arg2 = 28.304347826086957; verify_case(5, Arg2, value(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PreciousStones ___test; ___test.run_test(-1); } // END CUT HERE
#ifndef IDA_STAR_ALG #define IDA_STAR_ALG #include "a_star_alg.h" #include <deque> bool find_in_path(Node* n, std::deque<Node*> path) { node_ptr_compare cmp; for (auto el : path) if (cmp.operator()(el, n)) return true; return false; } // recursive search int ida_search(std::deque<Node*> path, int bound, Node** res) // returns bound { Node* n = path.back(); int f = n->f(); if (f > bound) return f; if (is_solved(n->field)) { *res = n; return -1; } int min = INT_MAX; for (auto new_node : next_nodes(n)) { if (!find_in_path(new_node, path))//если нет эл-та в очереди { path.push_back(new_node); int t = ida_search(path, bound, res); if (t == -1) return -1; if (t < min) min = t; path.pop_back(); new_node->parent = nullptr; delete new_node; } } return min; } void ida_star(const vector<int>& f_start) { if (!solvable(f_start)) cout << "It is unsolvable.\n"; else { std::deque<Node*> path; Node* start = new Node(nullptr, f_start); path.push_back(start); int bound = h(f_start); while (true) { Node* res = nullptr; int t = ida_search(path, bound, &res); if (t == -1) // FOUND solution { if (res != nullptr) print_answer(start, res); return; } bound = t; } } } #endif // !IDA_STAR_ALG
#include "msg_0x08_healthupdate_stc.h" namespace MC { namespace Protocol { namespace Msg { HealthUpdate::HealthUpdate() { _pf_packetId = static_cast<int8_t>(0x08); _pf_initialized = false; } HealthUpdate::HealthUpdate(int16_t _health, int16_t _food, float _saturation) : _pf_health(_health) , _pf_food(_food) , _pf_saturation(_saturation) { _pf_packetId = static_cast<int8_t>(0x08); _pf_initialized = true; } size_t HealthUpdate::serialize(Buffer& _dst, size_t _offset) { _pm_checkInit(); if(_offset == 0) _dst.clear(); _offset = WriteInt8(_dst, _offset, _pf_packetId); _offset = WriteInt16(_dst, _offset, _pf_health); _offset = WriteInt16(_dst, _offset, _pf_food); _offset = WriteFloat(_dst, _offset, _pf_saturation); return _offset; } size_t HealthUpdate::deserialize(const Buffer& _src, size_t _offset) { _offset = _pm_checkPacketId(_src, _offset); _offset = ReadInt16(_src, _offset, _pf_health); _offset = ReadInt16(_src, _offset, _pf_food); _offset = ReadFloat(_src, _offset, _pf_saturation); _pf_initialized = true; return _offset; } int16_t HealthUpdate::getHealth() const { return _pf_health; } int16_t HealthUpdate::getFood() const { return _pf_food; } float HealthUpdate::getSaturation() const { return _pf_saturation; } void HealthUpdate::setHealth(int16_t _val) { _pf_health = _val; } void HealthUpdate::setFood(int16_t _val) { _pf_food = _val; } void HealthUpdate::setSaturation(float _val) { _pf_saturation = _val; } } // namespace Msg } // namespace Protocol } // namespace MC
//--------------------------------------------------------------------------- #ifndef QCVH #define QCVH //--------------------------------------------------------------------------- //typedef void __fastcall (*TOnRespEvent)( TObject *Sender ); typedef void __fastcall(__closure *TOnReqEvent)( TObject *Sender ); typedef void __fastcall(__closure *TOnRespEvent)( TObject *Sender ); class TQCV : public TThread { private: String uri; int response_code; String response_str; String response_content_type; void __fastcall Execute( void ); void __fastcall setURI( String param ){ uri = param; }; String __fastcall getURI( void ){ return uri; }; void __fastcall sync_event( void ); protected: TOnRespEvent FOnResponse; TOnReqEvent FOnRequest; public: bool run; TStringList *resp_list; __fastcall TQCV(); __fastcall ~TQCV(); __property TOnReqEvent OnRequest = { read=FOnRequest, write=FOnRequest }; __property TOnRespEvent OnResponse = { read=FOnResponse, write=FOnResponse }; //__property int ResponseCode = { read=response_code }; //__property String ResponseContentType = { read=response_content_type }; __property String ResponseString = { read=response_str }; __property String URI = { write=setURI, read=getURI }; }; #endif
#include "fresnel.h" Color3f FresnelDielectric::Evaluate(float cosThetaI) const { //TODO cosThetaI=glm::clamp(cosThetaI,-1.0f,1.0f); float f=0.0f; //potentially swap indices bool entering=cosThetaI>0.0f; float ei=etaI; float et=etaT; if(!entering) { std::swap(ei,et); cosThetaI=std::fabs(cosThetaI); } //compute costhetaT using Snell's law float sinThetaI=std::sqrt(std::max((float)0,1-cosThetaI*cosThetaI)); float sinThetaT=ei/et*sinThetaI; if(sinThetaT>=1.0f) //internal reflection f=1.0f; float cosThetaT=std::sqrt(std::max((float)0,1-sinThetaT*sinThetaT)); float Rparl=((et*cosThetaI)-(ei*cosThetaT))/((et*cosThetaI)+(ei*cosThetaT)); float Rperp=((ei*cosThetaI)-(et*cosThetaT))/((ei*cosThetaI)+(et*cosThetaT)); f = (Rparl*Rparl + Rperp*Rperp) / 2.0f; return f*Color3f(1.0f); } Color3f FresnelConductor::Evaluate(float cosThetaI) const { return Color3f(0.0f); }
// ********************************************************************** // This file was generated by a TAF parser! // TAF version 2.1.5.0 by WSRD Tencent. // Generated from `GMOnline.jce' // ********************************************************************** #ifndef __GMONLINE_H_ #define __GMONLINE_H_ #include <map> #include <string> #include <vector> #include "jce/Jce.h" using namespace std; #include "servant/ServantProxy.h" #include "servant/Servant.h" namespace ServerEngine { /* callback of async proxy for client */ class GMOnlinePrxCallback: public taf::ServantProxyCallback { public: virtual ~GMOnlinePrxCallback(){} public: int onDispatch(taf::ReqMessagePtr msg); }; typedef taf::TC_AutoPtr<GMOnlinePrxCallback> GMOnlinePrxCallbackPtr; /* proxy for client */ class GMOnlineProxy : public taf::ServantProxy { public: typedef map<string, string> TAF_CONTEXT; GMOnlineProxy* taf_hash(int64_t key); }; typedef taf::TC_AutoPtr<GMOnlineProxy> GMOnlinePrx; /* servant for server */ class GMOnline : public taf::Servant { public: virtual ~GMOnline(){} public: int onDispatch(taf::JceCurrentPtr _current, vector<char> &_sResponseBuffer); }; } #endif
#include "readerwriterqueue/readerwriterqueue.h" #include "fmt/format.h" #include <thread> #include <atomic> auto main() -> int { moodycamel::ReaderWriterQueue<int> q(1); std::atomic_bool running { true }; std::thread t1([&] { auto count = 0; while (running) { q.try_enqueue(count); count++; std::this_thread::sleep_for(std::chrono::milliseconds(5)); } }); std::thread t2([&] { while (running) { int result{}; if (q.try_dequeue(result)) { fmt::print("{}\n", result); } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } }); std::getchar(); running.store(false); t1.join(); t2.join(); return 0; }
// Created on: 2014-08-15 // Created by: Varvara POSKONINA // Copyright (c) 2005-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 _SelectMgr_SensitiveEntitySet_HeaderFile #define _SelectMgr_SensitiveEntitySet_HeaderFile #include <BVH_PrimitiveSet3d.hxx> #include <Select3D_BVHBuilder3d.hxx> #include <SelectMgr_EntityOwner.hxx> #include <SelectMgr_SensitiveEntity.hxx> #include <SelectMgr_Selection.hxx> typedef NCollection_IndexedMap<Handle(SelectMgr_SensitiveEntity)> SelectMgr_IndexedMapOfHSensitive; typedef NCollection_DataMap<Handle(SelectMgr_EntityOwner), Standard_Integer> SelectMgr_MapOfOwners; //! This class is used to store all calculated sensitive entities of one selectable object. //! It provides an interface for building BVH tree which is used to speed-up //! the performance of searching for overlap among sensitives of one selectable object class SelectMgr_SensitiveEntitySet : public BVH_PrimitiveSet3d { DEFINE_STANDARD_RTTIEXT(SelectMgr_SensitiveEntitySet, BVH_PrimitiveSet3d) public: //! Empty constructor. Standard_EXPORT SelectMgr_SensitiveEntitySet (const Handle(Select3D_BVHBuilder3d)& theBuilder); virtual ~SelectMgr_SensitiveEntitySet() {} //! Adds new entity to the set and marks BVH tree for rebuild Standard_EXPORT void Append (const Handle(SelectMgr_SensitiveEntity)& theEntity); //! Adds every entity of selection theSelection to the set and marks //! BVH tree for rebuild Standard_EXPORT void Append (const Handle(SelectMgr_Selection)& theSelection); //! Removes every entity of selection theSelection from the set //! and marks BVH tree for rebuild Standard_EXPORT void Remove (const Handle(SelectMgr_Selection)& theSelection); //! Returns bounding box of entity with index theIdx Standard_EXPORT virtual Select3D_BndBox3d Box (const Standard_Integer theIndex) const Standard_OVERRIDE; //! Make inherited method Box() visible to avoid CLang warning using BVH_PrimitiveSet3d::Box; //! Returns geometry center of sensitive entity index theIdx //! along the given axis theAxis Standard_EXPORT virtual Standard_Real Center (const Standard_Integer theIndex, const Standard_Integer theAxis) const Standard_OVERRIDE; //! Swaps items with indexes theIdx1 and theIdx2 Standard_EXPORT virtual void Swap (const Standard_Integer theIndex1, const Standard_Integer theIndex2) Standard_OVERRIDE; //! Returns the amount of entities Standard_EXPORT virtual Standard_Integer Size() const Standard_OVERRIDE; //! Returns the entity with index theIndex in the set Standard_EXPORT const Handle(SelectMgr_SensitiveEntity)& GetSensitiveById (const Standard_Integer theIndex) const; //! Returns map of entities. const SelectMgr_IndexedMapOfHSensitive& Sensitives() const { return mySensitives; } //! Returns map of owners. const SelectMgr_MapOfOwners& Owners() const { return myOwnersMap; } //! Returns map of entities. Standard_Boolean HasEntityWithPersistence() const { return myHasEntityWithPersistence; } protected: //! Adds entity owner to the map of owners (or increases its counter if it is already there). Standard_EXPORT void addOwner (const Handle(SelectMgr_EntityOwner)& theOwner); //! Decreases counter of owner in the map of owners (or removes it from the map if counter == 0). Standard_EXPORT void removeOwner (const Handle(SelectMgr_EntityOwner)& theOwner); private: SelectMgr_IndexedMapOfHSensitive mySensitives; //!< Map of entities and its corresponding index in BVH SelectMgr_MapOfOwners myOwnersMap; //!< Map of entity owners and its corresponding number of sensitives Standard_Boolean myHasEntityWithPersistence; //!< flag if some of sensitive entity has own transform persistence }; #endif // _SelectMgr_SensitiveEntitySet_HeaderFile
// $Id$ // // Copyright (C) 2004-2008 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <RDGeneral/RDLog.h> #include <GraphMol/RDKitBase.h> #include <string> #include <iostream> #include <DistGeom/BoundsMatrix.h> #include <DistGeom/DistGeomUtils.h> #include <DistGeom/TriangleSmooth.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/FileParsers/FileParsers.h> #include <iostream> #include "BoundsMatrixBuilder.h" #include "Embedder.h" #include <stdlib.h> #include <GraphMol/FileParsers/MolWriters.h> #include <GraphMol/FileParsers/MolSupplier.h> #include <GraphMol/ROMol.h> #include <ForceField/ForceField.h> #include <GraphMol/ForceFieldHelpers/UFF/Builder.h> #include <RDGeneral/FileParseException.h> #include <ForceField/ForceField.h> #include <GraphMol/MolAlign/AlignMolecules.h> #include <math.h> #include <RDBoost/Exceptions.h> #include <boost/tokenizer.hpp> typedef boost::tokenizer<boost::char_separator<char> > tokenizer; using namespace RDKit; void test1() { std::string smiString = "CC1=C(C(C)=CC=C2)C2=CC=C1 c1ccccc1C C/C=C/CC \ C/12=C(\\CSC2)Nc3cc(n[n]3C1=O)c4ccccc4 C1CCCCS1(=O)(=O) c1ccccc1 \ C1CCCC1 C1CCCCC1 \ C1CC1(C)C C12(C)CC1CC2"; std::string rdbase = getenv("RDBASE"); std::string fname = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/initCoords.sdf"; SDMolSupplier sdsup(fname); //SDWriter writer("foo.sdf"); boost::char_separator<char> spaceSep(" "); tokenizer tokens(smiString,spaceSep); for(tokenizer::iterator token=tokens.begin(); token!=tokens.end();++token){ std::string smi= *token; RWMol *m = SmilesToMol(smi, 0, 1); int cid = DGeomHelpers::EmbedMolecule(*m, 10, 1,true,false,2,true,1,0,1e-2); CHECK_INVARIANT(cid >= 0, ""); ROMol *m2 = sdsup.next(); //BOOST_LOG(rdInfoLog) << ">>> " << smi << std::endl; //writer.write(*m); //writer.flush(); //ROMol *m2 = NULL; if(m2){ unsigned int nat = m->getNumAtoms(); const Conformer &conf1 = m->getConformer(0); const Conformer &conf2 = m2->getConformer(0); #if 0 BOOST_LOG(rdInfoLog) << "-----------------------" << std::endl; BOOST_LOG(rdInfoLog) << MolToMolBlock(*m2) << std::endl; BOOST_LOG(rdInfoLog) << "---" << std::endl; BOOST_LOG(rdInfoLog) << MolToMolBlock(*m) << std::endl; BOOST_LOG(rdInfoLog) << "-----------------------" << std::endl; #endif for (unsigned int i = 0; i < nat; i++) { RDGeom::Point3D pt1i = conf1.getAtomPos(i); RDGeom::Point3D pt2i = conf2.getAtomPos(i); for(unsigned int j=i+1;j<nat;j++){ RDGeom::Point3D pt1j = conf1.getAtomPos(j); RDGeom::Point3D pt2j = conf2.getAtomPos(j); double d1=(pt1j-pt1i).length(); double d2=(pt2j-pt2i).length(); if(m->getBondBetweenAtoms(i,j)){ //BOOST_LOG(rdInfoLog) << ">1> " <<i<<","<<j<<":"<< d1 << " " << d2 << std::endl; TEST_ASSERT(fabs(d1-d2)/d1<0.06); }else{ //BOOST_LOG(rdInfoLog) << ">2> " <<i<<","<<j<<":"<< d1 << " " << d2 << " "<<fabs(d1-d2)/d1<<std::endl; TEST_ASSERT(fabs(d1-d2)/d1<0.12); } } } } delete m; delete m2; } } void computeDistMat(const RDGeom::PointPtrVect &origCoords, RDNumeric::DoubleSymmMatrix &distMat) { unsigned int N = origCoords.size(); CHECK_INVARIANT(N == distMat.numRows(), ""); unsigned int i, j; RDGeom::Point3D pti, ptj; double d; for (i = 1; i < N; i++) { pti = *(RDGeom::Point3D*)origCoords[i]; for (j = 0; j < i; j++) { ptj = *(RDGeom::Point3D*)origCoords[j]; ptj -= pti; d = ptj.length(); distMat.setVal(i,j, d); } } } void computeMolDmat(ROMol &mol, RDNumeric::DoubleSymmMatrix &distMat) { RDGeom::PointPtrVect origCoords; unsigned int i, nat = mol.getNumAtoms(); Conformer &conf = mol.getConformer(0); for (i = 0; i < nat; i++) { origCoords.push_back(&conf.getAtomPos(i)); } computeDistMat(origCoords, distMat); } void test2() { // check for in ring distances, and distances containing two bonds in a ring std::string smi = "Cc1c(C=CC(C)N2)c2[nH]n1"; ROMol *mol = SmilesToMol(smi, 0, 1); DistGeom::BoundsMatPtr bm; RDNumeric::DoubleSymmMatrix *dmat; int cid; unsigned int nat = mol->getNumAtoms(); #if 1 bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); std::cerr<<"go"<<std::endl; cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,9) - bm->getLowerBound(0,9)) < 0.13); TEST_ASSERT( (bm->getUpperBound(0,9) - dmat->getVal(0,9) > -0.1 ) && (bm->getLowerBound(0,9) - dmat->getVal(0,9) < 0.10)); TEST_ASSERT( (bm->getUpperBound(10,7) - bm->getLowerBound(10,7)) < 0.13); TEST_ASSERT( (bm->getUpperBound(10,7) - dmat->getVal(10,7) > -0.1 ) && (bm->getLowerBound(10,7) - dmat->getVal(10,7) < 0.10 )); TEST_ASSERT( (bm->getUpperBound(2,5) - bm->getLowerBound(2,5)) < 0.20); TEST_ASSERT( (bm->getUpperBound(2,5) - dmat->getVal(2,5) > -0.1 ) && (bm->getLowerBound(2,5) - dmat->getVal(2,5) < 0.10 )); TEST_ASSERT( (bm->getUpperBound(8,4) - bm->getLowerBound(8,4)) > 1.); TEST_ASSERT( (bm->getUpperBound(8,4) - bm->getLowerBound(8,4)) < 1.2); TEST_ASSERT( (bm->getUpperBound(8,4) - dmat->getVal(8,4) > -0.1 ) && (bm->getLowerBound(8,4) - dmat->getVal(8,4) < 0.10)); TEST_ASSERT( (bm->getUpperBound(8,6) - bm->getLowerBound(8,6)) > 1.0); TEST_ASSERT( (bm->getUpperBound(8,6) - bm->getLowerBound(8,6)) < 1.2); TEST_ASSERT( (bm->getUpperBound(8,6) - dmat->getVal(8,6) > -0.1) && (bm->getLowerBound(8,6) - dmat->getVal(8,6) < 0.10 )); delete mol; delete dmat; // chain of singles smi = "CCCC"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) > 1.0); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < 1.3); TEST_ASSERT( (bm->getUpperBound(0,3) - dmat->getVal(0,3) > -0.1) && (bm->getLowerBound(0,3) - dmat->getVal(0,3) < 0.10 )); delete mol; delete dmat; smi = "C=C=C=C"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < .13); TEST_ASSERT( bm->getUpperBound(0,3) > dmat->getVal(0,3)); // this is kinda goofy but this linear molecule doesn't satisfy the bounds completely TEST_ASSERT(fabs(bm->getLowerBound(0,3) - dmat->getVal(0,3)) < 0.2); delete mol; delete dmat; #endif std::cerr << "-------------------------------------\n\n"; smi = "C/C=C/C"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); //std::cerr << "\n-----\n" << MolToMolBlock(mol,false,cid) << std::endl;; computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < .13); //std::cerr << bm->getUpperBound(0,3) << " " << dmat->getVal(0,3) << " " << bm->getLowerBound(0,3) << std::endl; TEST_ASSERT( (bm->getUpperBound(0,3) - dmat->getVal(0,3) > -0.1) && (bm->getLowerBound(0,3) - dmat->getVal(0,3) < 0.1)); delete mol; delete dmat; smi = "C/C=C\\C"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < .13); TEST_ASSERT( (bm->getUpperBound(0,3) - dmat->getVal(0,3) > -0.1) && (bm->getLowerBound(0,3) - dmat->getVal(0,3) < 0.10)); delete mol; delete dmat; smi = "CC=CC"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < 1.13); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) > 1.); TEST_ASSERT( (bm->getUpperBound(0,3) - dmat->getVal(0,3) > -0.1) && (bm->getLowerBound(0,3) - dmat->getVal(0,3) < 0.10)); delete mol; delete dmat; smi = "O=S-S=O"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < .13); TEST_ASSERT( (bm->getUpperBound(0,3) - dmat->getVal(0,3) > -0.1) && (bm->getLowerBound(0,3) - dmat->getVal(0,3) < 0.10 )); delete mol; delete dmat; #if 0 // this next block of tests all handle the special case that led to Issue284 smi = "COC=O"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); //TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < .13); double x,y,z; x = bm->getUpperBound(0,3); y = bm->getLowerBound(0,3); z = dmat->getVal(0,3); //TEST_ASSERT( (bm->getUpperBound(0,3) - dmat->getVal(0,3) > -0.1) // && (bm->getLowerBound(0,3) - dmat->getVal(0,3) < 0.10 )); delete mol; delete dmat; smi = "C[NH]C=O"; mol = SmilesToMol(smi, 0, 1); nat = mol->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm, 0.0, 1000.0); DGeomHelpers::setTopolBounds(*mol, bm); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); TEST_ASSERT(cid>-1); dmat = new RDNumeric::DoubleSymmMatrix(nat, 0.0); computeMolDmat(*mol, *dmat); TEST_ASSERT( (bm->getUpperBound(0,3) - bm->getLowerBound(0,3)) < .13); //TEST_ASSERT( (bm->getUpperBound(0,3) - dmat->getVal(0,3) > -0.1) // && (bm->getLowerBound(0,3) - dmat->getVal(0,3) < 0.10)); delete mol; delete dmat; #endif } void test3() { // check embedding based based on distances calculated from previous created // (good) coordinates std::string rdbase = getenv("RDBASE"); std::string fname = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/combi_coords.sdf"; SDMolSupplier sdsup(fname); unsigned int i, j, nat; bool gotCoords; while (!sdsup.atEnd()) { ROMol *mol = sdsup.next(); std::string mname; mol->getProp("_Name", mname); RDGeom::PointPtrVect origCoords, newCoords; nat = mol->getNumAtoms(); Conformer &conf = mol->getConformer(0); for (i = 0; i < nat; i++) { origCoords.push_back(&conf.getAtomPos(i)); } RDNumeric::DoubleSymmMatrix distMat(nat, 0.0); computeDistMat(origCoords, distMat); gotCoords = DistGeom::computeInitialCoords(distMat, origCoords); CHECK_INVARIANT(gotCoords, ""); RDNumeric::DoubleSymmMatrix distMatNew(nat, 0.0); computeDistMat(origCoords, distMatNew); for (i = 1; i < nat; i++) { for (j = 0; j < i; j++) { CHECK_INVARIANT(RDKit::feq(distMat.getVal(i,j), distMatNew.getVal(i,j), 0.01), ""); } } } } void test4() { std::string smi = "c1cc(C(F)(F)F)ccc1/C=N/NC(=O)c(n2)c[n]3cc(C(F)(F)F)cc(c23)Cl"; ROMol *m = SmilesToMol(smi, 0, 1); DGeomHelpers::EmbedMolecule(*m, 10, 1);//etCoords(*m, iter); std::string fname = "test.mol"; MolToMolFile(*m, fname); delete m; } void test5() { // some real CDK2 molecules lets see how many fail std::string rdbase = getenv("RDBASE"); std::string smifile = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/cis_trans_cases.csv"; SmilesMolSupplier smiSup(smifile, ",", 0, 1); ROMol *mol; int i = 0; int cid; while (1) { try { i++; mol = smiSup.next(); cid = DGeomHelpers::EmbedMolecule(*mol, 10, 1); //getCoords(*mol, iter); TEST_ASSERT(cid>-1); delete mol; } catch (FileParseException &) { break; } } } void test6() { std::string smi; ROMol *m; DistGeom::BoundsMatPtr bm; m = SmilesToMol("CC"); TEST_ASSERT(m); bm.reset(new DistGeom::BoundsMatrix(m->getNumAtoms())); TEST_ASSERT(bm); DGeomHelpers::initBoundsMat(bm,0.0,1000.0); TEST_ASSERT(feq(bm->getLowerBound(0,1),0.0)); TEST_ASSERT(feq(bm->getLowerBound(1,0),0.0)); TEST_ASSERT(feq(bm->getUpperBound(0,1),1000.0)); TEST_ASSERT(feq(bm->getUpperBound(1,0),1000.0)); DGeomHelpers::setTopolBounds(*m,bm); TEST_ASSERT(bm->getLowerBound(0,1)>0.0); TEST_ASSERT(bm->getUpperBound(0,1)<1000.0); TEST_ASSERT(bm->getLowerBound(0,1)<bm->getUpperBound(0,1)); delete m; } void testIssue215() { std::string smi; ROMol *m; DistGeom::BoundsMatPtr bm; bool ok; m = SmilesToMol("C=C1C2CC1C2"); TEST_ASSERT(m); bm.reset(new DistGeom::BoundsMatrix(m->getNumAtoms())); TEST_ASSERT(bm); DGeomHelpers::initBoundsMat(bm,0.0,1000.0); DGeomHelpers::setTopolBounds(*m,bm); // this was the specific problem: TEST_ASSERT(bm->getUpperBound(0,4)<100.0); ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } void _computeStats(const std::vector<double> &vals, double &mean, double &stdDev) { unsigned int N = vals.size(); mean = 0.0; double sqSum=0.0; stdDev = 0.0; std::vector<double>::const_iterator vci; for (vci = vals.begin(); vci != vals.end(); vci++) { mean += (*vci); sqSum += (*vci)*(*vci); } mean /= N; sqSum /= N; stdDev = sqrt(sqSum - (mean*mean)); } void testTemp() { //ROMol *m = SmilesToMol("CN(C)c(cc1)ccc1\\C=C(/C#N)c(n2)c(C#N)c([n]3cccc3)[n]2c(c4)cccc4"); //ROMol *m = SmilesToMol("C12C(=O)N(Cc3ccccc3)C(=O)C1C(C(=O)OC)(NC2c4ccc(Cl)c(c4)[N+]([O-])=O)Cc5c6ccccc6[nH]c5"); //c1(n2cccc2)n(c3ccccc3)ncc1 //ROMol *m = SmilesToMol("N#CCc1c(C#N)cn(C)n1"); //ROMol *m = SmilesToMol("Cc1c(C#N)cn(C)n1"); std::string rdbase = getenv("RDBASE"); std::string smifile = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/cis_trans_cases.csv"; SmilesMolSupplier smiSup(smifile, ",", 0, 1); ROMol *m; unsigned int cnt = 0; while (!smiSup.atEnd()) { m = smiSup.next(); unsigned int i; std::vector<double> energies; double energy; for (i = 0; i < 20; i++) { int cid = DGeomHelpers::EmbedMolecule(*m, 10, 1, false); if (cid >=0) { ForceFields::ForceField *ff=UFF::constructForceField(*m, 10, cid); ff->initialize(); energy = ff->calcEnergy(); energies.push_back(energy); delete ff; } } double mean, stdDev; _computeStats(energies, mean, stdDev); std::string mname; cnt++; m->getProp("_Name", mname); BOOST_LOG(rdDebugLog) << cnt << "," << mname << "," << mean << "," << stdDev << "\n"; delete m; } } void test15Dists() { ROMol *m = SmilesToMol("c1ccccc1C"); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DGeomHelpers::initBoundsMat(mat); DistGeom::BoundsMatPtr mmat(mat); DGeomHelpers::setTopolBounds(*m, mmat); CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(2,6), 4.32, 0.01), ""); CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(2,6), 4.16, 0.01), ""); delete m; m = SmilesToMol("CC1=C(C(C)=CC=C2)C2=CC=C1"); nat = m->getNumAtoms(); mmat.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(mmat); DGeomHelpers::setTopolBounds(*m, mmat); CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(0,4), 2.31, 0.01), ""); CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(0,4), 2.47, 0.01), ""); CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(4,11), 4.11, 0.01), ""); CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(4,11), 4.27, 0.01) , ""); delete m; m = SmilesToMol("C/C=C/C=C/C", 0, 1); nat = m->getNumAtoms(); mmat.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(mmat); DGeomHelpers::setTopolBounds(*m, mmat); CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(0,4), 4.1874), ""); CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(0,4), 4.924), ""); CHECK_INVARIANT(RDKit::feq(mmat->getLowerBound(1,5), 4.1874), ""); CHECK_INVARIANT(RDKit::feq(mmat->getUpperBound(1,5), 4.924) , ""); delete m; m = SmilesToMol("NCc(c1)cccc1"); delete m; } void testMultipleConfs() { std::string smi = "CC(C)(C)c(cc1)ccc1c(cc23)n[n]3C(=O)/C(=C\\N2)C(=O)OCC"; ROMol *m = SmilesToMol(smi, 0, 1); INT_VECT cids = DGeomHelpers::EmbedMultipleConfs(*m, 10, 30, 100, true, false,-1); INT_VECT_CI ci; SDWriter writer("junk.sdf"); double energy; for (ci = cids.begin(); ci != cids.end(); ci++) { writer.write(*m, *ci); ForceFields::ForceField *ff=UFF::constructForceField(*m, 10, *ci); ff->initialize(); energy = ff->calcEnergy(); //BOOST_LOG(rdInfoLog) << energy << std::endl; TEST_ASSERT(energy>100.0); TEST_ASSERT(energy<300.0); delete ff; } } void testOrdering() { std::string smi = "CC(C)(C)C(=O)NC(C1)CC(N2C)CCC12"; ROMol *m = SmilesToMol(smi, 0, 1); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DGeomHelpers::initBoundsMat(mat); DistGeom::BoundsMatPtr mmat(mat); DGeomHelpers::setTopolBounds(*m, mmat); delete m; std::string smi2 = "CN1C2CCC1CC(NC(=O)C(C)(C)C)C2"; ROMol *m2 = SmilesToMol(smi2, 0, 1); DistGeom::BoundsMatrix *mat2 = new DistGeom::BoundsMatrix(nat); DGeomHelpers::initBoundsMat(mat2); DistGeom::BoundsMatPtr mmat2(mat2); DGeomHelpers::setTopolBounds(*m2, mmat2); delete m2; } #if 1 void testIssue227() { std::string smi = "CCOP1(OCC)=CC(c2ccccc2)=C(c2ccc([N+]([O-])=O)cc2)N=C1c1ccccc1"; ROMol *m = SmilesToMol(smi, 0, 1); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); bool ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; smi = "OC(=O)c1cc2cc(c1)-c1c(O)c(ccc1)-c1cc(C(O)=O)cc(c1)OCCOCCO2"; m = SmilesToMol(smi, 0, 1); nat = m->getNumAtoms(); DistGeom::BoundsMatrix *nmat = new DistGeom::BoundsMatrix(nat); bm.reset(nmat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } #endif void testIssue236() { std::string smi = "Cn1c2n(-c3ccccc3)c(=O)c3c(nc4ccc([N+]([O-])=O)cc4c3)c2c(=O)n(C)c1=O"; ROMol *m = SmilesToMol(smi, 0, 1); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); bool ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); smi = "Cc1cccc2c1c(C3=CCC3)c(C)cc2"; m = SmilesToMol(smi, 0, 1); nat = m->getNumAtoms(); DistGeom::BoundsMatrix *nmat = new DistGeom::BoundsMatrix(nat); bm.reset(nmat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } void testIssue244() { // the bug here was a crash during the setting of the topological // bounds, so just completing the calls to setTopolBounds() indicates // success std::string smi = "NC1C(=O)N2C1SCC(Cl)=C2C(O)=O"; ROMol *m = SmilesToMol(smi, 0, 1); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); delete m; smi = "NC1C(=O)N2C1SCC(Cl)=C2C(O)=O"; m = SmilesToMol(smi, 0, 1); nat = m->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); delete m; smi = "CC1(C)SC2N(C1C(O)=O)C(=O)C2N"; m = SmilesToMol(smi, 0, 1); nat = m->getNumAtoms(); bm.reset(new DistGeom::BoundsMatrix(nat)); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); delete m; } void testIssue251() { std::string smi = "COC=O"; ROMol *m = SmilesToMol(smi, 0, 1); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); TEST_ASSERT(RDKit::feq(bm->getLowerBound(0,3), 2.67, 0.01)); TEST_ASSERT(RDKit::feq(bm->getUpperBound(0,3), 2.79, 0.01)); delete m; } void testIssue276() { bool ok; std::string smi = "CP1(C)=CC=CN=C1C"; ROMol *m = SmilesToMol(smi, 0, 1); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); #if 0 for(unsigned int i=0;i<nat;i++){ for(unsigned int j=0;j<nat;j++){ if(i<j) std::cout << bm->getUpperBound(i,j) << " "; else if(i>j) std::cout << bm->getLowerBound(i,j) << " "; else std::cout << "0.00000" << " "; } std::cout << std::endl; } std::cout << std::endl; #endif ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } void testIssue284() { bool ok; std::string smi = "CNC(=O)C"; ROMol *m = SmilesToMol(smi, 0, 1); TEST_ASSERT(m); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); // amide bonds are cis-oid: TEST_ASSERT(bm->getLowerBound(0,3)<3.0); TEST_ASSERT(bm->getUpperBound(0,3)<3.0); delete m; smi = "CN(C)C(=O)C"; m = SmilesToMol(smi, 0, 1); TEST_ASSERT(m); nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat2 = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm2(mat2); DGeomHelpers::initBoundsMat(bm2); DGeomHelpers::setTopolBounds(*m, bm2); ok = DistGeom::triangleSmoothBounds(bm2); TEST_ASSERT(ok); // we've got no information to tell us cis-oid vs trans-oid here, so // the windows are huge: TEST_ASSERT(bm2->getLowerBound(0,4)<3.0); TEST_ASSERT(bm2->getUpperBound(0,4)>3.5); TEST_ASSERT(bm2->getLowerBound(2,4)<3.0); TEST_ASSERT(bm2->getUpperBound(2,4)>3.5); TEST_ASSERT(bm->getLowerBound(0,3)<bm2->getLowerBound(0,4)); TEST_ASSERT(bm->getUpperBound(0,3)<bm2->getUpperBound(0,4)); TEST_ASSERT(bm->getLowerBound(0,3)<bm2->getLowerBound(2,4)); TEST_ASSERT(bm->getUpperBound(0,3)<bm2->getUpperBound(2,4)); delete m; } void testIssue285() { bool ok; std::string smi = "CNC(=O)C"; ROMol *m = SmilesToMol(smi, 0, 1); TEST_ASSERT(m); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); unsigned int tgtNumber=10; INT_VECT cids = DGeomHelpers::EmbedMultipleConfs(*m, tgtNumber); TEST_ASSERT(cids.size()==tgtNumber); std::vector<std::string> molBlocks; for(INT_VECT_CI cid=cids.begin();cid!=cids.end();++cid){ molBlocks.push_back(MolToMolBlock(*m,true,*cid)); } for(std::vector<std::string>::const_iterator mbI=molBlocks.begin(); mbI!=molBlocks.end();++mbI){ for(std::vector<std::string>::const_iterator mbJ=mbI+1; mbJ!=molBlocks.end();++mbJ){ TEST_ASSERT((*mbI)!=(*mbJ)); } //std::cerr << (*mbI) << "\n$$$$\n"; } delete m; } void testIssue355() { bool ok; std::string smi = "CNC(=O)C"; ROMol *m = SmilesToMol(smi, 0, 1); TEST_ASSERT(m); unsigned int nat = m->getNumAtoms(); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(nat); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); TEST_ASSERT(bm->getLowerBound(0,3)<3.0); TEST_ASSERT(bm->getUpperBound(0,3)<3.0); TEST_ASSERT(bm->getUpperBound(0,4)>3.2); TEST_ASSERT(bm->getLowerBound(0,4)>3.2); ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; smi="CNC(=O)NC"; m = SmilesToMol(smi, 0, 1); TEST_ASSERT(m); bm.reset(new DistGeom::BoundsMatrix(m->getNumAtoms())); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); TEST_ASSERT(bm->getLowerBound(0,3)<3.0); TEST_ASSERT(bm->getUpperBound(0,3)<3.0); TEST_ASSERT(bm->getUpperBound(0,4)>3.2); TEST_ASSERT(bm->getLowerBound(0,4)>3.2); TEST_ASSERT(bm->getLowerBound(5,3)<3.0); TEST_ASSERT(bm->getUpperBound(5,3)<3.0); TEST_ASSERT(bm->getUpperBound(5,1)>3.2); TEST_ASSERT(bm->getLowerBound(5,1)>3.2); delete m; smi="CNC(=O)Nc1ccccc1"; m = SmilesToMol(smi, 0, 1); TEST_ASSERT(m); bm.reset(new DistGeom::BoundsMatrix(m->getNumAtoms())); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); TEST_ASSERT(bm->getLowerBound(0,3)<3.0); TEST_ASSERT(bm->getUpperBound(0,3)<3.0); TEST_ASSERT(bm->getUpperBound(0,4)>3.2); TEST_ASSERT(bm->getLowerBound(0,4)>3.2); TEST_ASSERT(bm->getLowerBound(5,3)<3.0); TEST_ASSERT(bm->getUpperBound(5,3)<3.0); TEST_ASSERT(bm->getUpperBound(5,1)>3.2); TEST_ASSERT(bm->getLowerBound(5,1)>3.2); delete m; } void testRandomCoords() { std::string smiString = "CC1=C(C(C)=CC=C2)C2=CC=C1 c1ccccc1C C/C=C/CC \ C/12=C(\\CSC2)Nc3cc(n[n]3C1=O)c4ccccc4 C1CCCCS1(=O)(=O) c1ccccc1 \ C1CCCC1 C1CCCCC1 \ C1CC1(C)C C12(C)CC1CC2"; std::string rdbase = getenv("RDBASE"); std::string fname = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/initCoords.random.sdf"; SDMolSupplier sdsup(fname,true,false); //SDWriter writer("foo.sdf"); //SDWriter writer(fname); boost::char_separator<char> spaceSep(" "); tokenizer tokens(smiString,spaceSep); for(tokenizer::iterator token=tokens.begin(); token!=tokens.end();++token){ std::string smi= *token; ROMol *m = SmilesToMol(smi, 0, 1); RWMol *m2 = (RWMol *)MolOps::addHs(*m); delete m; m=m2; int cid = DGeomHelpers::EmbedMolecule(*m, 10, 1, true, true, 2,true,1,0,1e-2); CHECK_INVARIANT(cid >= 0, ""); //writer.write(*m); //writer.flush(); #if 1 m2 = static_cast<RWMol *>(sdsup.next()); //ROMol *m2 = NULL; if(m2){ TEST_ASSERT(m->getNumAtoms()==m2->getNumAtoms()); unsigned int nat = m->getNumAtoms(); const Conformer &conf1 = m->getConformer(0); const Conformer &conf2 = m2->getConformer(0); #if 0 BOOST_LOG(rdInfoLog) << "-----------------------" << std::endl; BOOST_LOG(rdInfoLog) << MolToMolBlock(*m2) << std::endl; BOOST_LOG(rdInfoLog) << "---" << std::endl; BOOST_LOG(rdInfoLog) << MolToMolBlock(*m) << std::endl; BOOST_LOG(rdInfoLog) << "-----------------------" << std::endl; #endif for (unsigned int i = 0; i < nat; i++) { RDGeom::Point3D pt1i = conf1.getAtomPos(i); RDGeom::Point3D pt2i = conf2.getAtomPos(i); for(unsigned int j=i+1;j<nat;j++){ RDGeom::Point3D pt1j = conf1.getAtomPos(j); RDGeom::Point3D pt2j = conf2.getAtomPos(j); double d1=(pt1j-pt1i).length(); double d2=(pt2j-pt2i).length(); if(m->getBondBetweenAtoms(i,j)){ TEST_ASSERT(fabs(d1-d2)/d1<0.05); }else{ TEST_ASSERT(fabs(d1-d2)/d1<0.1); } } } } delete m2; #endif delete m; } } void testIssue1989539() { { std::string smi="c1ccccc1.Cl"; ROMol *m = SmilesToMol(smi, 0, 1); RWMol *m2 = (RWMol *)MolOps::addHs(*m); delete m; m=m2; int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } { std::string smi="[Cl-].c1ccccc1C[NH3+]"; RWMol *m = SmilesToMol(smi, 0, 1); int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } } void testConstrainedEmbedding() { std::string rdbase = getenv("RDBASE"); std::string fname = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/constrain1.sdf"; SDMolSupplier sdsup(fname); ROMol *ref=sdsup.next(); { ROMol *test = new ROMol(*ref); std::map<int,RDGeom::Point3D> coords; coords[0]=ref->getConformer().getAtomPos(0); coords[1]=ref->getConformer().getAtomPos(1); coords[2]=ref->getConformer().getAtomPos(2); coords[3]=ref->getConformer().getAtomPos(3); coords[4]=ref->getConformer().getAtomPos(4); #if 1 int cid = DGeomHelpers::EmbedMolecule(*test,30,22,true,false,2.,true,1,&coords); TEST_ASSERT(cid>-1); MatchVectType alignMap; alignMap.push_back(std::make_pair(0,0)); alignMap.push_back(std::make_pair(1,1)); alignMap.push_back(std::make_pair(2,2)); alignMap.push_back(std::make_pair(3,3)); alignMap.push_back(std::make_pair(4,4)); double ssd=MolAlign::alignMol(*test,*ref,-1,-1,&alignMap); BOOST_LOG(rdInfoLog)<<"ssd: "<<ssd<<std::endl; TEST_ASSERT(ssd<0.1); #endif delete test; } { ROMol *test = sdsup.next(); std::map<int,RDGeom::Point3D> coords; coords[4]=ref->getConformer().getAtomPos(0); coords[5]=ref->getConformer().getAtomPos(1); coords[6]=ref->getConformer().getAtomPos(2); coords[7]=ref->getConformer().getAtomPos(3); coords[8]=ref->getConformer().getAtomPos(4); int cid = DGeomHelpers::EmbedMolecule(*test,30,22,true,false,2.,true,1,&coords); TEST_ASSERT(cid>-1); MatchVectType alignMap; alignMap.push_back(std::make_pair(4,0)); alignMap.push_back(std::make_pair(5,1)); alignMap.push_back(std::make_pair(6,2)); alignMap.push_back(std::make_pair(7,3)); alignMap.push_back(std::make_pair(8,4)); double ssd=MolAlign::alignMol(*test,*ref,-1,-1,&alignMap); BOOST_LOG(rdInfoLog)<<"ssd: "<<ssd<<std::endl; TEST_ASSERT(ssd<0.1); delete test; } } void testIssue2091864() { { std::string smi="C1C2CC12"; RWMol *m = SmilesToMol(smi); int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); delete m; } { std::string smi="C1CC2C3C1C23"; RWMol *m = SmilesToMol(smi); int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } { std::string smi="c1ccc2c(c1)C1C3C2C13"; RWMol *m = SmilesToMol(smi); int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } } void testIssue2091974() { { std::string smi="CCOC(OCC)(OCC)OCC"; ROMol *m = SmilesToMol(smi); ROMol *m2 =MolOps::addHs(*m); delete m; int cid = DGeomHelpers::EmbedMolecule(*m2); TEST_ASSERT(cid >= 0); delete m2; } { std::string smi="O=N(=O)OCC(CON(=O)=O)(CON(=O)=O)CON(=O)=O"; ROMol *m = SmilesToMol(smi); ROMol *m2 =MolOps::addHs(*m); delete m; int cid = DGeomHelpers::EmbedMolecule(*m2); TEST_ASSERT(cid >= 0); delete m2; } } void testIssue2835784() { #if 1 { std::string smi="C1C=C1"; RWMol *m = SmilesToMol(smi); int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } { std::string smi="C1C=C1"; ROMol *m = SmilesToMol(smi); ROMol *m2 =MolOps::addHs(*m); delete m; int cid = DGeomHelpers::EmbedMolecule(*m2); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m2,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m2; } { std::string smi="C12=CCC1C2"; RWMol *m = SmilesToMol(smi); int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } #endif { std::string smi="C12=CCC1C2"; ROMol *m = SmilesToMol(smi); ROMol *m2 =MolOps::addHs(*m); delete m; int cid = DGeomHelpers::EmbedMolecule(*m2); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m2,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m2; } } void testIssue3019283() { { std::string smi="C1=C2C1C1CC21"; RWMol *m = SmilesToMol(smi); int cid = DGeomHelpers::EmbedMolecule(*m); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } } void testIssue3238580() { { std::string smi="C1CCC2=CC12"; RWMol *m = SmilesToMol(smi); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(m->getNumAtoms()); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); // if we get here it indicates everything was fine. // do bounds smoothing just to be sure: bool ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } { std::string rdbase = getenv("RDBASE"); std::string molfile = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/Issue3238580.1.mol"; RWMol *m = MolFileToMol(molfile); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(m->getNumAtoms()); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); // if we get here it indicates everything was fine. // do bounds smoothing just to be sure: bool ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } { std::string rdbase = getenv("RDBASE"); std::string molfile = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/Issue3238580.2.mol"; RWMol *m = MolFileToMol(molfile); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(m->getNumAtoms()); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); // if we get here it indicates everything was fine. // do bounds smoothing just to be sure: bool ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } { std::string rdbase = getenv("RDBASE"); std::string molfile = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/Issue3238580.3.mol"; RWMol *m = MolFileToMol(molfile); DistGeom::BoundsMatrix *mat = new DistGeom::BoundsMatrix(m->getNumAtoms()); DistGeom::BoundsMatPtr bm(mat); DGeomHelpers::initBoundsMat(bm); DGeomHelpers::setTopolBounds(*m, bm); // if we get here it indicates everything was fine. // do bounds smoothing just to be sure: bool ok = DistGeom::triangleSmoothBounds(bm); TEST_ASSERT(ok); delete m; } } void testIssue3483968() { { std::string rdbase = getenv("RDBASE"); std::string molfile = rdbase + "/Code/GraphMol/DistGeomHelpers/test_data/Issue3483968.mol"; RWMol *m = MolFileToMol(molfile); TEST_ASSERT(m); int cid = DGeomHelpers::EmbedMolecule(*m,0,-1,true,false,2.0,true,1,0,1e-3,true); TEST_ASSERT(cid >= 0); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(*m,10,30, 1,true,false,2.0,true,1,-1.0,0, 1e-3,true); TEST_ASSERT(cids.size() == 10); TEST_ASSERT(std::find(cids.begin(),cids.end(),-1)==cids.end()); delete m; } } #ifdef RDK_TEST_MULTITHREADED namespace { void runblock(const std::vector<ROMol *> &mols,const std::vector<double> &energies, unsigned int count,unsigned int idx){ for(unsigned int j=0;j<100;j++){ for(unsigned int i=0;i<mols.size();++i){ if(i%count != idx) continue; ROMol mol(*mols[i]); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(mol,10,30,0xFEED); TEST_ASSERT(cids.size() == 10); ForceFields::ForceField *field = 0; try { field = UFF::constructForceField(mol,100.0,cids[0]); } catch (...) { field = 0; } TEST_ASSERT(field); field->initialize(); double eng=field->calcEnergy(); if(!feq(eng,energies[i])){ std::cerr<<i<<" iter "<<j<<" "<<energies[i]<<" != "<<eng<<std::endl; } TEST_ASSERT(feq(eng,energies[i])); delete field; } } }; } #include <boost/thread.hpp> void testMultiThread(){ std::cerr<<"building molecules"<<std::endl; //std::string smi="C/12=C(\\CSC2)Nc3cc(n[n]3C1=O)c4ccccc4"; std::string smi="c1ccc2c(c1)C1C3C2C13"; std::vector<ROMol *> mols; for(unsigned int i=0;i<100;++i){ RWMol *m = SmilesToMol(smi); mols.push_back(m); } std::cerr<<"generating reference data"<<std::endl; std::vector<double> energies(mols.size(),0.0); for(unsigned int i=0;i<mols.size();++i){ ROMol mol(*mols[i]); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(mol,10,30,0xFEED); TEST_ASSERT(cids.size() == 10); ForceFields::ForceField *field = 0; try { field = UFF::constructForceField(mol,100.0,cids[0]); } catch (...) { field = 0; } TEST_ASSERT(field); field->initialize(); double eng=field->calcEnergy(); TEST_ASSERT(eng!=0.0); energies[i]=eng; delete field; } std::cerr<<"validating reference data"<<std::endl; for(unsigned int i=0;i<mols.size();++i){ ROMol mol(*mols[i]); std::vector<int> cids=DGeomHelpers::EmbedMultipleConfs(mol,10,30,0xFEED); TEST_ASSERT(cids.size() == 10); ForceFields::ForceField *field = 0; try { field = UFF::constructForceField(mol,100.0,cids[0]); } catch (...) { field = 0; } TEST_ASSERT(field); field->initialize(); double eng=field->calcEnergy(); TEST_ASSERT(feq(eng,energies[i])); delete field; } boost::thread_group tg; std::cerr<<"processing"<<std::endl; unsigned int count=4; for(unsigned int i=0;i<count;++i){ std::cerr<<" launch :"<<i<<std::endl;std::cerr.flush(); tg.add_thread(new boost::thread(runblock,mols,energies,count,i)); } tg.join_all(); for(unsigned int i=0;i<mols.size();++i) delete mols[i]; BOOST_LOG(rdErrorLog) << " done" << std::endl; } #else void testMultiThread(){ } #endif void testGithub55() { { std::string smiles = "c1cnco1"; RWMol *core = SmilesToMol(smiles); TEST_ASSERT(core); int cid = DGeomHelpers::EmbedMolecule(*core); TEST_ASSERT(cid >= 0); smiles = "o1cncc1C"; RWMol *mol = SmilesToMol(smiles); TEST_ASSERT(mol); std::map<int,RDGeom::Point3D> coords; coords[0]=core->getConformer().getAtomPos(4); coords[1]=core->getConformer().getAtomPos(3); coords[2]=core->getConformer().getAtomPos(2); coords[3]=core->getConformer().getAtomPos(1); coords[4]=core->getConformer().getAtomPos(0); cid = DGeomHelpers::EmbedMolecule(*mol,50,22,true,false,2.,true,1,&coords); TEST_ASSERT(cid>-1); delete core; delete mol; } { std::string smiles = "c1cncs1"; RWMol *core = SmilesToMol(smiles); TEST_ASSERT(core); int cid = DGeomHelpers::EmbedMolecule(*core); TEST_ASSERT(cid >= 0); smiles = "s1cncc1C"; RWMol *mol = SmilesToMol(smiles); TEST_ASSERT(mol); std::map<int,RDGeom::Point3D> coords; coords[0]=core->getConformer().getAtomPos(4); coords[1]=core->getConformer().getAtomPos(3); coords[2]=core->getConformer().getAtomPos(2); coords[3]=core->getConformer().getAtomPos(1); coords[4]=core->getConformer().getAtomPos(0); cid = DGeomHelpers::EmbedMolecule(*mol,50,22,true,false,2.,true,1,&coords); TEST_ASSERT(cid>-1); delete core; delete mol; } } void testGithub256() { { RWMol *mol = new RWMol(); TEST_ASSERT(mol); bool ok=false; try{ DGeomHelpers::EmbedMolecule(*mol); ok=false; } catch (const ValueErrorException &e) { ok=true; } TEST_ASSERT(ok); delete mol; } } int main() { RDLog::InitLogs(); BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "Testing DistGeomHelpers\n"; #if 1 BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test2 \n\n"; test2(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test3 \n\n"; test3(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test4 \n\n"; test4(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test5 \n\n"; test5(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test6 \n\n"; test6(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test15Dists \n\n"; test15Dists(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test Issue 215 \n\n"; testIssue215(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testMultipleConfs \n\n"; testMultipleConfs(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue227 \n\n"; testIssue227(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue236 \n\n"; testIssue236(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testOrdering \n\n"; testOrdering(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue244 \n\n"; testIssue244(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue251 \n\n"; testIssue251(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue276 \n"; testIssue276(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue284 \n\n"; testIssue284(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue285 \n\n"; testIssue285(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testIssue355 \n\n"; testIssue355(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t testRandomCoords \n\n"; testRandomCoords(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test sf.net issue 1989539 \n\n"; testIssue1989539(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test sf.net issue 2091864 \n\n"; testIssue2091864(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test constrained embedding \n\n"; testConstrainedEmbedding(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test sf.net issue 2091974 \n\n"; testIssue2091974(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test sf.net issue 2835784 \n\n"; testIssue2835784(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test sf.net issue 3019283 \n\n"; testIssue3019283(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test sf.net issue 3238580 \n\n"; testIssue3238580(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test sf.net issue 3483968 \n\n"; testIssue3483968(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test github issue 55 \n\n"; testGithub55(); #endif BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test1 \n\n"; test1(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test multi-threading \n\n"; testMultiThread(); BOOST_LOG(rdInfoLog) << "\t---------------------------------\n"; BOOST_LOG(rdInfoLog) << "\t test github issue 256: handling of zero-atom molecules\n\n"; testGithub256(); BOOST_LOG(rdInfoLog) << "*******************************************************\n"; return(0); }
// Created on: 1997-07-28 // Created by: Pierre CHALAMET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Graphic3d_Texture2D_HeaderFile #define _Graphic3d_Texture2D_HeaderFile #include <Graphic3d_NameOfTexture2D.hxx> #include <Graphic3d_TextureMap.hxx> //! This abstract class for managing 2D textures class Graphic3d_Texture2D : public Graphic3d_TextureMap { DEFINE_STANDARD_RTTIEXT(Graphic3d_Texture2D, Graphic3d_TextureMap) public: //! Returns the number of predefined textures. Standard_EXPORT static Standard_Integer NumberOfTextures(); //! Returns the name of the predefined texture of rank <aRank> Standard_EXPORT static TCollection_AsciiString TextureName (const Standard_Integer theRank); public: //! Creates a texture from a file. //! MipMaps levels will be automatically generated if needed. Standard_EXPORT Graphic3d_Texture2D (const TCollection_AsciiString& theFileName); //! Creates a texture from a predefined texture name set. //! MipMaps levels will be automatically generated if needed. Standard_EXPORT Graphic3d_Texture2D (const Graphic3d_NameOfTexture2D theNOT); //! Creates a texture from the pixmap. //! MipMaps levels will be automatically generated if needed. Standard_EXPORT Graphic3d_Texture2D (const Handle(Image_PixMap)& thePixMap); //! Returns the name of the predefined textures or NOT_2D_UNKNOWN //! when the name is given as a filename. Standard_EXPORT Graphic3d_NameOfTexture2D Name() const; //! Assign new image to the texture. //! Note that this method does not invalidate already uploaded resources - consider calling ::UpdateRevision() if needed. Standard_EXPORT void SetImage (const Handle(Image_PixMap)& thePixMap); protected: Standard_EXPORT Graphic3d_Texture2D(const TCollection_AsciiString& theFileName, const Graphic3d_TypeOfTexture theType); Standard_EXPORT Graphic3d_Texture2D(const Graphic3d_NameOfTexture2D theName, const Graphic3d_TypeOfTexture theType); Standard_EXPORT Graphic3d_Texture2D(const Handle(Image_PixMap)& thePixMap, const Graphic3d_TypeOfTexture theType); protected: Graphic3d_NameOfTexture2D myName; }; DEFINE_STANDARD_HANDLE(Graphic3d_Texture2D, Graphic3d_TextureMap) #endif // _Graphic3d_Texture2D_HeaderFile
//Note for Press #include<bits/stdc++.h> #include<conio.h> #include<windows.h> #include<time.h> using namespace std; void setcursor(bool visible) { HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_CURSOR_INFO lpCursor; lpCursor.bVisible = visible; lpCursor.dwSize = 20; SetConsoleCursorInfo(console,&lpCursor); } void setcolor(int fg,int bg) { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, bg*16+fg); } void xy(int x, int y) { COORD c = { x, y }; SetConsoleCursorPosition( GetStdHandle(STD_OUTPUT_HANDLE) , c); } void draw(int x,int y) { xy(x,y); setcolor (2,4); cout<<"<-0->"; } void draw_b(int x,int y) { xy(x,y); setcolor (0,15); cout<<"^"; } void erase_ship(int x,int y) { xy(x,y); setcolor (0,0); cout<<" "; } void erase_b(int x,int y) { xy(x,y); setcolor (0,0); cout<<" "; } char cursor(int x, int y) { HANDLE hStd = GetStdHandle(STD_OUTPUT_HANDLE); char buf[2]; COORD c = {x,y}; DWORD num_read; if(!ReadConsoleOutputCharacter(hStd,(LPTSTR)buf,1,c,(LPDWORD)&num_read) ) return '\0'; else return buf[0]; } int main() { int x=38,y=20; vector<int> bx,by; setcursor(0); char ch='s'; int LR = 3; int score = 0; printf("score :%d",score); srand(time(NULL)); xy(rand()%74+2,rand()%10+1); cout<<"*"; char se; se='A'; draw(x,y); do { if (_kbhit()) { ch=_getch(); if(ch=='a' && x-1>=0) {erase_ship(x,y); draw(--x,y);} if(ch=='d' && x+1<79) {erase_ship(x,y); draw(++x,y);} if(ch=='e') { if(bx.size()>4) { for(int j=0;j<bx.size();j++) erase_b(bx[j],by[j]); bx.clear(); by.clear(); } by.push_back(y-1); bx.push_back(x+2); } /*if(ch=='a') LR=0; if(ch=='d') LR=1; if(ch=='s') LR=3;*/ fflush(stdin); } if(LR!=3) { if(LR==0&&x-1>0) { erase_ship(x,y);draw(--x,y); } if(LR==1&&x+1<79) { erase_ship(x,y);draw(++x,y); } } if(bx.size()!=0) { for(int j=0;j<bx.size();j++) { if(by[j]==0) { erase_b(bx[j],by[j]); bx.erase(bx.begin()); by.erase(by.begin()); j--; } else { if(cursor(bx[j],by[j]-1)=='*') { erase_b(bx[j],by[j]-1); erase_b(bx[j],by[j]); bx.erase(bx.begin()+j); by.erase(by.begin()+j); Beep(100,200); score++; j--; setcolor (7,0); xy(rand()%74+2,rand()%10+1); cout<<"*"; xy(0,0); printf("score :%d",score); } else { erase_b(bx[j],by[j]);draw_b(bx[j],--by[j]); } } } } Sleep(100); }while (ch!='x'); return 0; }
class Kriss_DZ: MP5_DZ { displayName = $STR_DZ_WPN_KRISS_NAME; descriptionShort = $STR_DZ_WPN_KRISS_DESC; model = "\RH_smg\RH_kriss.p3d"; picture = "\RH_smg\inv\kriss.paa"; magazines[] = {"33Rnd_45ACP_KRISS"}; handAnim[] = {"OFP2_ManSkeleton","\RH_smg\Anim\NORRN_RH_Kris1.rtm"}; reloadMagazineSound[] = {"\RH_smg\Sound\kriss_reload.wss",0.056234,1,25}; modes[] = {"Single","FullAuto"}; class Single: Mode_SemiAuto { begin1[] = {"\RH_smg\sound\kriss.wss",1.778279,1,900}; soundBegin[] = {"begin1",1}; reloadTime = 0.07; recoil = "recoil_single_primary_2outof10"; recoilProne = "recoil_single_primary_prone_1outof10"; dispersion = 0.003; minRange = 2; minRangeProbab = 0.25; midRange = 40; midRangeProbab = 0.7; maxRange = 150; maxRangeProbab = 0.05; }; delete Burst; class FullAuto: Mode_FullAuto { begin1[] = {"\RH_smg\sound\kriss.wss",1.778279,1,900}; soundBegin[] = {"begin1",1}; soundContinuous = 0; reloadTime = 0.1; ffCount = 1; recoil = "recoil_auto_primary_2outof10"; recoilProne = "recoil_auto_primary_prone_1outof10"; dispersion = 0.003; minRange = 0; minRangeProbab = 0.2; midRange = 20; midRangeProbab = 0.7; maxRange = 40; maxRangeProbab = 0.05; }; class FlashLight { color[] = {0.9,0.9,0.7,0.9}; ambient[] = {0.1,0.1,0.1,1.0}; position = "flash dir"; direction = "flash"; angle = 30; scale[] = {1,1,0.5}; brightness = 0.1; }; class Attachments { Attachment_CCO = "Kriss_CCO_DZ"; Attachment_Holo = "Kriss_Holo_DZ"; Attachment_Sup45 = "Kriss_SD_DZ"; }; }; class Kriss_CCO_DZ: Kriss_DZ { displayname = $STR_DZ_WPN_KRISS_CCO_NAME; model = "\RH_smg\RH_krissaim.p3d"; picture = "\RH_smg\inv\krissaim.paa"; opticsDisablePeripherialVision = 1; distanceZoomMin = 100; distanceZoomMax = 100; class Attachments { Attachment_Sup45 = "Kriss_CCO_SD_DZ"; }; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'Kriss_DZ'] call player_removeAttachment"; }; }; }; class Kriss_Holo_DZ: Kriss_DZ { displayname = $STR_DZ_WPN_KRISS_HOLO_NAME; model = "\RH_smg\RH_krisseot.p3d"; picture = "\RH_smg\inv\krisseot.paa"; opticsDisablePeripherialVision = 1; distanceZoomMin = 100; distanceZoomMax = 100; class Attachments { Attachment_Sup45 = "Kriss_Holo_SD_DZ"; }; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'Kriss_DZ'] call player_removeAttachment"; }; }; }; class Kriss_SD_DZ: MP5_SD_DZ { displayName = $STR_DZ_WPN_KRISS_SD_NAME; descriptionShort = $STR_DZ_WPN_KRISS_SD_DESC; model = "\RH_smg\RH_krisssd.p3d"; picture = "\RH_smg\inv\krisssd.paa"; handAnim[] = {"OFP2_ManSkeleton","\RH_smg\Anim\NORRN_RH_Kris1.rtm"}; reloadMagazineSound[] = {"\RH_smg\Sound\kriss_reload.wss",0.056234,1,25}; magazines[] = {"33Rnd_45ACP_KRISSSD"}; fireLightDuration = 0.0; fireLightIntensity = 0.0; modes[] = {"Single","FullAuto"}; class Single: Mode_SemiAuto { begin1[] = {"\RH_smg\sound\umpsd.wss",1.778279,1,50}; soundBegin[] = {"begin1",1}; reloadTime = 0.07; recoil = "recoil_single_primary_2outof10"; recoilProne = "recoil_single_primary_prone_1outof10"; dispersion = 0.003; minRange = 2; minRangeProbab = 0.25; midRange = 40; midRangeProbab = 0.7; maxRange = 150; maxRangeProbab = 0.05; }; delete Burst; class FullAuto: Mode_FullAuto { begin1[] = {"\RH_smg\sound\umpsd.wss",1.778279,1,50}; soundBegin[] = {"begin1",1}; soundContinuous = 0; reloadTime = 0.1; ffCount = 1; recoil = "recoil_auto_primary_2outof10"; recoilProne = "recoil_auto_primary_prone_1outof10"; dispersion = 0.003; minRange = 0; minRangeProbab = 0.2; midRange = 20; midRangeProbab = 0.7; maxRange = 40; maxRangeProbab = 0.05; }; class FlashLight { color[] = {0.9,0.9,0.7,0.9}; ambient[] = {0.1,0.1,0.1,1.0}; position = "flash dir"; direction = "flash"; angle = 30; scale[] = {1,1,0.5}; brightness = 0.1; }; class Attachments { Attachment_CCO = "Kriss_CCO_SD_DZ"; Attachment_Holo = "Kriss_Holo_SD_DZ"; }; class ItemActions { class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup45',_id,'Kriss_DZ'] call player_removeAttachment"; }; }; }; class Kriss_CCO_SD_DZ: Kriss_SD_DZ { displayname = $STR_DZ_WPN_KRISS_CCO_SD_NAME; model = "\RH_smg\RH_krisssdaim.p3d"; picture = "\RH_smg\inv\krisssdaim.paa"; opticsDisablePeripherialVision = 1; distanceZoomMin = 100; distanceZoomMax = 100; class Attachments {}; class ItemActions { class RemoveCCO { text = $STR_DZ_ATT_CCO_RMVE; script = "; ['Attachment_CCO',_id,'Kriss_SD_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup45',_id,'Kriss_CCO_DZ'] call player_removeAttachment"; }; }; }; class Kriss_Holo_SD_DZ: Kriss_SD_DZ { displayname = $STR_DZ_WPN_KRISS_HOLO_SD_NAME; model = "\RH_smg\RH_krisssdeot.p3d"; picture = "\RH_smg\inv\krisssdeot.paa"; opticsDisablePeripherialVision = 1; distanceZoomMin = 100; distanceZoomMax = 100; class Attachments {}; class ItemActions { class RemoveHolo { text = $STR_DZ_ATT_HOLO_RMVE; script = "; ['Attachment_Holo',_id,'Kriss_SD_DZ'] call player_removeAttachment"; }; class RemoveSuppressor { text = $STR_ATTACHMENT_RMVE_Silencer; script = "; ['Attachment_Sup45',_id,'Kriss_Holo_DZ'] call player_removeAttachment"; }; }; };
#ifndef __ANOMALY_INTERFACE__ #define __ANOMALY_INTERFACE__ #include "IpAddr.hpp" class AnomalyInterface{ public: /* * check whether the packet is considered an anomaly * @return: will return true if packet is considered anomaly and false otherwise */ virtual bool anomalityCheck(IpAddr& ip) = 0; }; #endif
#include "stdafx.h" #include "CorrectDialog.h" CorrectDialog::CorrectDialog(int row, User* user, QWidget* parent) : QDialog(parent) { ui.setupUi(this); m_row = row; m_user = user; ui.lab_money->setText(QString::number(m_user->money) + tr(" RMB")); ui.edit_correct->setText(QString::number(m_user->money)); connect(ui.edit_correct, &QLineEdit::returnPressed, this, &CorrectDialog::onBtnCorrectClicked); connect(ui.btn_correct, &QPushButton::clicked, this, &CorrectDialog::onBtnCorrectClicked); connect(ui.btn_back, &QPushButton::clicked, this, &CorrectDialog::onBtnBackClicked); } CorrectDialog::~CorrectDialog() { } void CorrectDialog::onBtnCorrectClicked() { QString money = ui.edit_correct->text(); QString mpwd = ui.edit_mpwd->text(); if (!isDigitString(money)) { //错误!不规则输入。重输 QMessageBox* msgBox = new QMessageBox(QMessageBox::Critical, tr("Error !"), tr("Irregular Input."), QMessageBox::Ok, this); msgBox->button(QMessageBox::Ok)->setText(tr("Re-input")); msgBox->exec(); } else { if (mpwd != "0601") { //错误!管理密码校验不通过。重输 QMessageBox* msgBox = new QMessageBox(QMessageBox::Critical, tr("Error !"), tr("The MnagPwd check failed."), QMessageBox::Ok, this); msgBox->button(QMessageBox::Ok)->setText(tr("Re-input")); msgBox->exec(); } else { m_user->money = money.toDouble(); this->close(); emit correctBalance(m_row, m_user); } } } void CorrectDialog::onBtnBackClicked() { this->close(); } //检测字符串是否为符合规则的数字 bool CorrectDialog::isDigitString(const QString& src) { int length = src.length(); if (length <= 0) { return false; } int i = 0; for (; i < length; i++) { if (src.at(i) < '0' || src.at(i) > '9') { if (src.at(i) != '.') break; } } return i >= length; }
#include<bits/stdc++.h> using namespace std; int main(){ string s; bool prefix[256]; memset(prefix, false, sizeof(prefix)); getline(cin, s); transform(s.begin(), s.end(), s.begin(), ::tolower); int n = 0; for(int i = 0; i < s.size(); i++){ if (((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= '0' && s[i] <= '9')) && prefix[int(s[i])] == false){ n++; prefix[int(s[i])] = true; } } cout << n; return 0; }
#include <iostream> #include <fstream> #include <cmath> struct point { int x, y; }; double area(point &a, point &b, point &c) { return (0.5 * abs ((a.x - c.x)*(b.y - c.y) - (a.y - c.y)*(b.x - c.x))); } bool validate(point &a, point &b, point &c, point &o) { return ((area(o, b, c) + area(o, a, c) + area(o, a, b)) <= area(a, b, c)); } int main(int argc, char **argv) { point a, b, c, origin = {0, 0}; char ch; int cnt = 0; std::ifstream tri("C:/Users/s521059/CLionProjects/Euler Project/EulerP102/p102_triangles.txt"); while(tri) { tri >> a.x >> ch >> a.y >> ch >> b.x >> ch >> b.y >> ch >> c.x >> ch >> c.y; if(validate(a, b, c, origin)) cnt++; } std::cout << cnt << std::endl; return 0; }
#include <core/maths.h> #include <core/pfm.h> #include <core/mesh.h> #include <core/shader.h> #define STRINGIFY(A) #A #include "sh.h" #include <iostream> #include <cmath> #include <functional> #include <algorithm> #include <stdint.h> // Work Items // ---------- // Implement the spherical harmonic functions in C++ // Write basic unit tests for functions to check orthonormal properties, sanity check against mathematica // Bring in light probe loading code from probe viewer app // Write code to project probe into SH basis and convolve with Lambert function // Write code to view projected map SH basis, check against references // Write code to load and render teapot with projected probe using namespace std; const int kWidth = 800; const int kHeight = 600; uint32_t g_buffer[kWidth*kHeight]; Mesh* g_mesh; Vec3 g_camPos(0.0f, 0.0f, 7.0f); Vec3 g_camVel(0.0f); Vec3 g_camAngle(0.0f, -kPi/12.0f, 0.0f); Vec3 g_shDiffuse[9]; Vec3 g_shPhong[9]; float g_exposure = 0.175f; GLuint g_shader; // vertex shader const char* vertexShader = STRINGIFY ( void main() { gl_Position = gl_ModelViewProjectionMatrix*vec4(gl_Vertex.xyz, 1.0); gl_TexCoord[0] = vec4(normalize(gl_Normal), 0.0); gl_TexCoord[1] = vec4(gl_Vertex.xyz, 1.0); } ); // pixel shader const char* fragmentShader = STRINGIFY ( uniform vec3 shDiffuse[9]; uniform vec3 shPhong[9]; uniform float exposure; vec3 shEval(vec3 dir, vec3 sh[9]) { // evaluate irradiance vec3 e = sh[0]; e += -dir.y*sh[1]; e += dir.z*sh[2]; e += -dir.x*sh[3]; e += dir.x*dir.y*sh[4]; e += -dir.y*dir.z*sh[5]; e += -dir.x*dir.z*sh[7]; e += (3.0*dir.z*dir.z-1.0)*sh[6]; e += (dir.x*dir.x - dir.y*dir.y)*sh[8]; return max(e, vec3(0.0)); } vec3 fresnel(vec3 rf, float cosTheta) { return rf + pow(1.0-cosTheta, 5.0)*(vec3(1.0)-rf); } vec3 lerp(vec3 a, vec3 b, vec3 t) { return a + (b-a)*t; } void main() { vec3 rf = vec3(1.0, 0.71, 0.29); vec3 rd = rf*0.1;//vec3(0.2); vec3 n = gl_TexCoord[0].xyz; vec3 shadePos = gl_TexCoord[1].xyz; vec3 eyePos = gl_ModelViewMatrixInverse[3].xyz; vec3 eyeDir = normalize(eyePos-shadePos); // calculate reflected view direction vec3 r = normalize(2.0*dot(eyeDir, n)*n-eyeDir); // evaluate reflected radiance in reflected view dir vec3 s = shEval(r, shPhong); // calculate diffuse radiance in normal dir vec3 d = shEval(n, shDiffuse); // vec3 f = fresnel(rf, clamp(dot(r, n), 0.0, 1.0)); // lerp between two based on Fresnel function vec3 l = rd*d + f*s; gl_FragColor = vec4(pow(max(l*exposure, 0.0), vec3(1.0/2.0)), 1.0); } ); double lambert(double theta, double phi) { return max(cos(theta), 0.0); } double phong(double theta, double phi) { double kExponent = 40.0f; return 0.5*(2.0 + kExponent)*pow(lambert(theta, phi), kExponent); } Colour light(double theta, double phi) { Vec3 dir(float(sin(theta)*cos(phi)), float(sin(theta)*sin(phi)), float(cos(theta))); float f = Dot(dir, Normalize(Vec3(1.0f, 6.0f, 4.0f))) > cos(kPi/25.0); return Colour(f, f, f, 1.0f); } struct ProbeSampler { ProbeSampler(const char* path) { if (!PfmLoad(path, mProbe)) { cout << "Could not load probe " << path << endl; } else { cout << "Loaded probe: " << path << " (" << mProbe.m_width << ", " << mProbe.m_height << ")" << endl; } } Colour operator()(double theta, double phi) const { Vec3 dir(float(sin(theta)*cos(phi)), float(sin(theta)*sin(phi)), float(cos(theta))); // convert world space dir to probe space float c = (1.0f / kPi) * acosf(dir.z)/sqrt(dir.x*dir.x + dir.y*dir.y); uint32_t px = uint32_t((0.5f + 0.5f*(dir.x*c))*(mProbe.m_width-1)); uint32_t py = uint32_t((0.5f + 0.5f*(dir.y*c))*(mProbe.m_height-1)); float r = mProbe.m_data[py*mProbe.m_width*3 + (px*3)+0]; float g = mProbe.m_data[py*mProbe.m_width*3 + (px*3)+1]; float b = mProbe.m_data[py*mProbe.m_width*3 + (px*3)+2]; return Colour(r, g, b, 1.0f); } PfmImage mProbe; }; ostream& operator<<(ostream& s, const Colour& c) { s << c.r << ", " << c.g << ", " << c.b << ", " << c.a; return s; } void shScale(const Colour in[9], Vec3 out[9]) { const float k0 = 0.5f * 1.0f/sqrtf(kPi); const float k1 = 0.5f * sqrtf(3.0f / kPi); const float k2 = 0.5f * sqrtf(15.0f / kPi); const float k3 = 0.25f * sqrtf(5.0f / kPi); const float k4 = 0.25f * sqrtf(15.0f / kPi); // copy to global probe coefficients, pre-scaled to avoid work in shader out[0] = k0*Vec3(in[0]); out[1] = k1*Vec3(in[1]); out[2] = k1*Vec3(in[2]); out[3] = k1*Vec3(in[3]); out[4] = k2*Vec3(in[4]); out[5] = k2*Vec3(in[5]); out[6] = k3*Vec3(in[6]); out[7] = k2*Vec3(in[7]); out[8] = k4*Vec3(in[8]); // dump to C-array format cout << "Vec3 out[] = {" << endl; for (int i=0; i < 9; ++i) { cout << "Vec3(" << out[i].x << ", " << out[i].y << ", " << out[i].z << ")," << endl; } cout << "}" << endl; } void shTests() { const int lmax = 3; double lambertCoefficients[lmax*lmax] = { 0.0 }; double phongCoefficients[lmax*lmax] = { 0.0 }; shProject(lambert, lmax, lambertCoefficients); shProject(phong, lmax, phongCoefficients); ProbeSampler sampler("../../data/beach.pfm"); Colour probeCoefficients[lmax*lmax]; shProject(sampler, lmax, probeCoefficients); Colour diffuseCoefficients[lmax*lmax]; shConvolve(diffuseCoefficients, probeCoefficients, lambertCoefficients, lmax); shScale(diffuseCoefficients, g_shDiffuse); Colour specularCoefficients[lmax*lmax]; shConvolve(specularCoefficients, probeCoefficients, phongCoefficients, lmax); shScale(specularCoefficients, g_shPhong); // shReduceRinging(g_shPhong, lmax, 0.01); /* for (int i=0; i < (lmax*lmax); ++i) cout << probeCoefficients[i] << endl; // expand for (int y=0; y < kHeight; ++y) { for (int x=0; x < kWidth; ++x) { // calculate direction double u = 2.0*(double(x)/kWidth)-1.0; double v = 2.0*(double(y)/kHeight)-1.0; double theta = atan2(v, u); double phi = kPi*sqrt(u*u+v*v); // do not write pixels outside the sphere if (phi <= kPi) { Vec3 direction = SphericalToXYZ(theta, phi)*0.5 + Vec3(0.5); Colour c(direction.x, direction.y, direction.z); g_buffer[y*kWidth + x] = ColourToRGBA8(0.175*(shExpand(probeCoefficients, lmax, phi, theta)));//sampler(theta, phi)); } } } */ } void Update(void) { const float dt = 1.0f/60.0f; // update camera const Vec3 forward(-sinf(g_camAngle.x)*cosf(g_camAngle.y), sinf(g_camAngle.y), -cosf(g_camAngle.x)*cosf(g_camAngle.y)); const Vec3 right(Normalize(Cross(forward, Vec3(0.0f, 1.0f, 0.0f)))); g_camPos += (forward*g_camVel.z + right*g_camVel.x)*dt; glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); /* glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0f, 1.0f, -2.0f, 2.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDrawPixels(kWidth, kHeight, GL_RGBA, GL_UNSIGNED_BYTE, g_buffer); */ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, float(kWidth)/kHeight, 1.0f, 10000.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotatef(RadToDeg(-g_camAngle.x), 0.0f, 1.0f, 0.0f); glRotatef(RadToDeg(-g_camAngle.y), cosf(-g_camAngle.x), 0.0f, sinf(-g_camAngle.x)); glTranslatef(-g_camPos.x, -g_camPos.y, -g_camPos.z); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, &g_mesh->m_positions.front()); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, &g_mesh->m_normals.front()); glUseProgram(g_shader); GLint uDiffuse = glGetUniformLocation(g_shader, "shDiffuse"); glUniform3fv(uDiffuse, 9, reinterpret_cast<float*>(&g_shDiffuse[0].x)); GLint uPhong = glGetUniformLocation(g_shader, "shPhong"); glUniform3fv(uPhong, 9, reinterpret_cast<float*>(&g_shPhong[0].x)); GLint uExposure = glGetUniformLocation(g_shader, "exposure"); glUniform1f(uExposure, g_exposure); glDrawElements(GL_TRIANGLES, g_mesh->GetNumFaces()*3, GL_UNSIGNED_INT, &g_mesh->m_indices.front()); glUseProgram(0); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glutSwapBuffers(); g_mesh->Transform(RotationMatrix(kPi/180, Vec3(0.0f, 1.0f, 0.0f))); } int lastx = 0; int lasty = 0; void GLUTMouseFunc(int b, int state, int x, int y) { switch (state) { case GLUT_UP: { lastx = x; lasty = y; break; } case GLUT_DOWN: { lastx = x; lasty = y; } }; } void GLUTKeyboardDown(unsigned char key, int x, int y) { const float kSpeed = 50.0f; switch (key) { case 'w': { g_camVel.z = kSpeed; break; } case 's': { g_camVel.z = -kSpeed; break; } case 'a': { g_camVel.x = -kSpeed; break; } case 'd': { g_camVel.x = kSpeed; break; } case 'u': { g_exposure += 0.05f; break; } case 'j': { g_exposure -= 0.05f; break; } case 27: case 'q': { exit(0); break; } }; } void GLUTKeyboardUp(unsigned char key, int x, int y) { switch (key) { case 'w': { g_camVel.z = 0.0f; break; } case 's': { g_camVel.z = 0.0f; break; } case 'a': { g_camVel.x = 0.0f; break; } case 'd': { g_camVel.x = 0.0f; break; } }; } void GLUTMotionFunc(int x, int y) { int dx = x-lastx; int dy = y-lasty; lastx = x; lasty = y; const float kSensitivity = DegToRad(0.2f); g_camAngle.x -= dx*kSensitivity; g_camAngle.y += dy*kSensitivity; } int main(int argc, char* argv[]) { // init gl glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE); glutInitWindowSize(kWidth, kHeight); glutCreateWindow("SHTest"); glutPositionWindow(200, 100); #if _WIN32 glewInit(); #endif g_shader = CompileProgram(vertexShader, fragmentShader); if (g_shader == 0) return 0; g_mesh = ImportMeshFromObj("../../data/happy.obj"); Vec3 minExtents, maxExtents; g_mesh->GetBounds(minExtents, maxExtents); Vec3 center = 0.5f*(maxExtents+minExtents); float scale = 10.0f / (maxExtents.y-minExtents.y); g_mesh->Transform(ScaleMatrix(Vector3(scale, scale, scale))*TranslationMatrix(Point3(-center))); // center camera g_camPos = Vec3(0.0f, 5.0f, 20.0f); shTests(); glutIdleFunc(Update); glutDisplayFunc(Update); glutMouseFunc(GLUTMouseFunc); glutMotionFunc(GLUTMotionFunc); glutKeyboardFunc(GLUTKeyboardDown); glutKeyboardUpFunc(GLUTKeyboardUp); /* glutReshapeFunc(GLUTReshape); glutDisplayFunc(GLUTUpdate); glutSpecialFunc(GLUTArrowKeys); glutSpecialUpFunc(GLUTArrowKeysUp); */ #if __APPLE__ int swap_interval = 1; CGLContextObj cgl_context = CGLGetCurrentContext(); CGLSetParameter(cgl_context, kCGLCPSwapInterval, &swap_interval); #endif glutMainLoop(); return 0; }
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> 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; int main() { freopen("square-free.in", "r", stdin); freopen("square-free.out", "w", stdout); int n; cin >> n; LL a; while (n--) { cin >> a; bool cool = true; for (LL i = 2; i <= 12000; ++i) { if (i * i > a) break; if (a % (i * i) == 0) { cool = false; break; } } if (!cool) { printf("%I64d is not square-free\n", a); continue; } for (LL i = 2; i <= 12000; ++i) { if (a % i == 0) { LL b = a / i; LL s = sqrt(double(b) + 1e-5); while (s * s < b) ++s; if (s * s == b && s > 1) { cool = false; break; } } } if (!cool) { printf("%I64d is not square-free\n", a); } else { printf("%I64d is square-free\n", a); } } return 0; }
#include "stdio.h" #include "conio.h" void main(){ clrscr(); int fact; printf("\n\t\tFactorials................\n"); for(int i=1; i<=7; i++){ fact=i; for(int j=i-1; j>0; j--) fact*=j; printf("%d! = %d\n",i,fact); } getch(); }
#include <iostream> using namespace std; int main(){ int i, num, sum=0, mul=0; cout<<"Introduzca el numero que desea verificar si es perfecto: "; cin>>num; for(i=1; i<num; i++) { mul=num%i; if(mul==0) { sum+=i; } } if(sum==num){ cout<<"El numero es perfecto.\n", num; } else{ cout<<"El numero NO es perfecto.\n", num; } return 0; }
#include <iostream> #include <cmath> #define REP(i, a, n) for(int i = (a); i < (n); i++) using namespace std; struct point { double x, y; }; struct line { point p, q; }; double distance(line l, point p) { double x0 = p.x, y0 = p.y; double x1 = l.p.x, y1 = l.p.y; double x2 = l.q.x, y2 = l.q.y; double a = x2 - x1; double b = y2 - y1; double a2 = a * a; double b2 = b * b; double r2 = a2 + b2; double tt = -(a*(x1 - x0) + b*(y1 - y0)); if(tt < 0) return sqrt((x1 - x0)*(x1-x0) + (y1 - y0)*(y1-y0)); if(tt > r2) return sqrt((x2 - x0)*(x2 - x0) + (y2 - y0)*(y2 - y0)); double f1 = a*(y1 - y0) - b*(x1 - x0); return sqrt((f1*f1)/r2); } int main(void) { point p = (point) { 1, 6 }; line l = (line) { (point) { 2, 5 }, (point) { -1, 1 } }; cout << distance(l, p) << endl; return 0; }
#include<bits/stdc++.h> using namespace std; int main(){ int a[3][2]={10, 20, 30, 40, 50, 60}; for (int i=0;i<3;++i) { for (int j=0;j<2;++j) { printf("a[%d][%d]=%d\n",i,j,a[i][j]); } } printf("\n"); for (int i=0;i<3;++i) { for (int j=0;j<2;++j) { printf("&a[%d][%d]=%p (a[%d]+%d)=%p\n",i,j,&a[i][j], i,j,(a[i]+j)); } } printf("\n"); for (int i=0;i<3;++i) { for (int j=0;j<2;++j) { printf("*(*(a+%d)+%d)=%d\n",i,j, *(*(a+i)+j)); } } }
// Inspired by https://github.com/Radiateurs/Socket-implementation-UE4 // and https://forums.unrealengine.com/t/tcp-socket-listener-receiving-binary-data-into-ue4-from-a-python-script/7549 #pragma once #include "UObject/Object.h" #include "Networking.h" #include "Sockets.h" #include "SocketSubsystem.h" #include "TCPSocket.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnMessageReceived, FString, Message); UCLASS(BlueprintType) class AGENTSOCKET_API UTCPSocket : public UObject { GENERATED_BODY() public: UTCPSocket(); static uint8 ID; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "TCP Socket") FString IP = "0.0.0.0"; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "TCP Socket") int Port = 11111; UPROPERTY(BlueprintAssignable) FOnMessageReceived OnMessageReceived; protected: void BeginDestroy(); public: UPROPERTY(EditAnywhere, BlueprintReadWrite) UWorld* World; FSocket* ListenerSocket; FSocket* ConnectionSocket; FIPv4Endpoint RemoteAddressForConnection; FTimerHandle TCPSocketListenerTimerHandle; FTimerHandle TCPConnectionListenerTimerHandle; bool StartTCPReceiver(const FString& SocketName); FSocket* CreateTCPConnectionListener( const FString& SocketName, const int32 ReceiveBufferSize = 2 * 1024 * 1024 ); // Timer functions, could be threads void TCPConnectionListener(); void TCPSocketListener(); FString StringFromBinaryArray(TArray<uint8> BinaryArray); //Format String IP4 to number array bool FormatIP4ToNumber(const FString& IP, uint8(&Out)[4]); UFUNCTION(BlueprintCallable, Category = "TCP Socket") bool LaunchTCP(); UFUNCTION(BlueprintCallable, Category = "TCP Socket") bool SendMessage(FString Message); // Send raw bytes to connected client UFUNCTION(BlueprintCallable, Category = "TCP Socket") bool SendBinary(TArray<uint8> &BinaryArray); UFUNCTION(/*BlueprintImplementableEvent, */Category = "TCP Socket") void MessageReceived(const FString& Message); };
// // Created by tompi on 6/3/18. // /*#include "../header/Aggregation.h" void Aggregation::Aggregate(cl_device_id _DEVICE, int _sorted_elements[], uint _element_size, uint _no_distinct_val) { // Make array of double the size of distinct value uint * _m_res_arr = new uint[_no_distinct_val * 2]; // Add data to the respective devices add_data("sorted_elements", _sorted_elements, _DEVICE, _element_size); add_data("res_arr", _m_res_arr, _DEVICE, (_no_distinct_val * 2)); lookup_data_buffer(); print_data("sorted_elements", _DEVICE, _element_size); }/**/
#ifndef RTPCLIENT_H #define RTPCLIENT_H #include <QThread> #include <QUdpSocket> #include <errno.h> #include <QSemaphore> #include "rtpclass.h" #include <QTimer> #include "decodeandsendthread.h" const int maxThreadNum=1; class rtpClient : public rtpClass { Q_OBJECT public: rtpClient(QObject *parent = 0); ~rtpClient(); void rtpInit(QString ip,int port); void decodeData(int index,unsigned char *buf,unsigned char *yuv); private: // RTPSession *sess; pic_data picData; QList<QByteArray*> cacheLink; unsigned char buffer[14745600]; unsigned char cam_yuv[14745600]; QFile f; CvCapture * capture; IplImage *frame; QTimer *timer; int width,height; QSemaphore sem; void run(); QMutex lock; int index; int currentIndex; decodeAndSendThread *decodeThread[16]; int decodeResult[maxThreadNum]; signals: void display(IplImage *,int index); void heartpack(); public slots: void getFrame(); void sendH264Data(unsigned char *buffer,int length); void sendData(); void finishDecode(unsigned char *buffer,int length); }; #endif // RTPCLIENT_H
#include <stdlib.h> #include <string.h> #include <map> #include <algorithm> #include "GameCmd.h" #include "PlayerManager.h" #include "Logger.h" #include "HallHandler.h" #include "Util.h" #include "Configure.h" #include "json/json.h" #include "NamePool.h" #include "Protocol.h" #include "RobotUtil.h" #include "Packet.h" using namespace std; static PlayerManager* instance = NULL; PlayerManager* PlayerManager::getInstance() { if(instance==NULL) { instance = new PlayerManager(); } return instance; } PlayerManager::PlayerManager() { m_nStartID = RobotUtil::getRobotStartUid(PacketBase::game_id, Configure::getInstance().level, Configure::getInstance().robot_server_index); LOGGER(E_LOG_INFO) << "Robot Start uid=" << m_nStartID; m_allocInfos.resize(IDNUM); for (int i = 0; i < IDNUM; ++i) { m_frees.push_back(i); m_allocInfos[i] = false; } } int PlayerManager::addPlayer(int uid, Player* player) { playerMap[uid] = player; return 0; } int PlayerManager::getPlayerSize() { return playerMap.size(); } void PlayerManager::delPlayer(int uid, bool isclose) { Player* player = getPlayer(uid); if(player) { ULOGGER(E_LOG_INFO, player->m_Uid) << "exit uid"; delRobotUid(player->m_Uid); if(!isclose) { if(player->handler) delete player->handler; } NamePool::getInstance()->FreeName(player->name.c_str()); delete player; playerMap.erase(uid); } } Player* PlayerManager::getPlayer(int uid) { map<int , Player*>::iterator it = playerMap.find(uid); if(it == playerMap.end()) return NULL; else return it->second; } int PlayerManager::getRobotUID() { std::list<int>::iterator it; int id = -1; it = m_frees.begin(); if (it != m_frees.end()) { id = *it; m_allocInfos[id] = true; id += m_nStartID; m_frees.pop_front(); } return id; } int PlayerManager::delRobotUid(int robotuid) { int id = robotuid - m_nStartID; ASSERT(id >= 0); if (m_allocInfos[id]) { m_frees.push_front(id); m_allocInfos[id] = false; } return 0; } int PlayerManager::productRobot(int tid, short status, short level, short countUser) { if (level > E_MASTER_LEVEL || level < E_PRIMARY_LEVEL) { LOGGER(E_LOG_ERROR) << "level is not invalid:" << level; return -1; } Player* player = new Player(); if (player) { player->init(); player->clevel = level; player->playNum = Configure::getInstance().play_count + rand() % 3; int robotuid = PlayerManager::getInstance()->getRobotUID(); if (robotuid < 0) { delete player; ULOGGER(E_LOG_ERROR, robotuid) << "robotuid is negative level = " << level; return -1; } player->m_Uid = robotuid; player->m_TableId = tid; int totalnum = 0; int winnum = 0; int roll = 0; int mostwin = 0; player->money = Configure::getInstance().base_money[level - 1]; if (level == E_PRIMARY_LEVEL) { player->money += rand() % 500; totalnum += 5 + rand() % 6; winnum += 1 + rand() % 3; //roll += 1; mostwin = 10 * (1 + rand() % 300); } else if (level == E_MIDDLE_LEVEL) { player->money += rand() % 1500; totalnum = 50 + rand() % 800; winnum = 10 + rand() % 300; if (totalnum < winnum) winnum = totalnum * 3 / 10; roll += 150 + rand() % 100; mostwin = 100 * (1 + rand() % 300); } else if (level == E_ADVANCED_LEVEL) { player->money += rand() % 163000; totalnum = 50 + rand() % 1000; winnum = 15 + rand() % 400; if (totalnum < winnum) winnum = totalnum * 3 / 10; roll += 250 + rand() % 200; mostwin = 300 * (1 + rand() % 300); } else if (level == E_MASTER_LEVEL) { player->money += rand() % 200000; totalnum = 50 + rand() % 10000; winnum = 15 + rand() % 800; if (totalnum < winnum) winnum = totalnum * 3 / 10; roll += 250 + rand() % 200; mostwin = 500 * (1 + rand() % 300); } std::string nickname; std::string headurl; int uid = 0; int sex = 0; RobotUtil::makeRobotInfo(Configure::getInstance().head_url, sex, headurl, uid); player->name = nickname = NamePool::getInstance()->AllocName(); roll = rand() % 1000; Json::Value data; data["picUrl"] = string(headurl); data["sum"] = totalnum; data["win"] = winnum; data["sex"] = sex; data["source"] = 30; data["lepaper"] = roll; int robotid = player->m_Uid; data["uid"] = robotid; data["mostwin"] = double(mostwin); short vip = 0; int randnum = rand() % 100; if (randnum < Configure::getInstance().rand_vip[0]) { randnum = rand() % 100; if (randnum < Configure::getInstance().rand_vip[1]) vip = 1; else if (randnum >= Configure::getInstance().rand_vip[1] && randnum < Configure::getInstance().rand_vip[2]) vip = 2; else if (randnum >= Configure::getInstance().rand_vip[2] && randnum < Configure::getInstance().rand_vip[3]) vip = 10; else if (randnum >= Configure::getInstance().rand_vip[3]) vip = 100; } data["vip"] = vip; data["level"] = 1 + rand() % 10; player->json = data.toStyledString(); HallHandler * handler = new HallHandler(); if (CDLReactor::Instance()->Connect(handler, Configure::getInstance().hall_ip.c_str(), Configure::getInstance().hall_port) < 0) { delete handler; delete player; LOGGER(E_LOG_ERROR) << "Connect BackServer error[" << Configure::getInstance().hall_ip << ":" << Configure::getInstance().hall_port << "]"; return -1; } handler->uid = player->m_Uid; player->handler = handler; PlayerManager::getInstance()->addPlayer(player->m_Uid, player); ULOGGER(E_LOG_INFO, player->m_Uid) << "start robot, tid = " << (tid&0x0F) << " name = " << player->name; player->login(); } return 0; }
#include "Enemy.h" void Enemy::Setup( int enemyIndex ) { frameMax = 4; exists = true; atk = 1; atkCounter = -1; frame = IDLE; direction = RIGHT; action = WALKING; deadTimer = 0; collisionRegion.X( position.x + 5 ); collisionRegion.Y( position.y + 5 ); collisionRegion.W( 24 ); collisionRegion.H( 24 ); if ( enemyIndex % 4 == 0 ) { type = EWOK; speed = 1.2f; position.w = 32; position.h = 48; hp = 20; expAmt = 6; } else if ( enemyIndex % 4 == 1 ) { type = ROBOT; speed = 2.0f; position.w = position.h = 32; hp = 50; expAmt = 10; } else if ( enemyIndex % 4 == 2 ) { type = KITTY; speed = 1.5f; position.w = position.h = 32; hp = 60; expAmt = 12; } else if ( enemyIndex % 4 == 3 ) { type = SNAKE; speed = 1.0f; position.w = 48; position.h = 32; hp = 100; expAmt = 8; } int tile = 32; switch ( enemyIndex ) { case 0: position.x = 29*tile; position.y = 6*tile; break; case 1: position.x = 36*tile; position.y = 21*tile; break; case 2: position.x = 60*tile; position.y = 34*tile; break; case 3: position.x = 72*tile; position.y = 42*tile; break; case 4: position.x = 15*tile; position.y = 17*tile; break; case 5: position.x = 7*tile; position.y = 19*tile; break; case 6: position.x = 18*tile; position.y = 29*tile; break; case 7: position.x = 3*tile; position.y = 56*tile; break; case 8: position.x = 28*tile; position.y = 54*tile; break; case 9: position.x = 77*tile; position.y = 3*tile; break; case 10: position.x = 62*tile; position.y = 5*tile; break; case 11: position.x = 73*tile; position.y = 13*tile; break; case 12: position.x = 78*tile; position.y = 26*tile; break; case 13: position.x = 73*tile; position.y = 54*tile; break; case 14: position.x = 33*tile; position.y = 49*tile; break; case 15: position.x = 22*tile; position.y = 41*tile; break; case 16: position.x = 24*tile; position.y = 28*tile; break; case 17: position.x = 47*tile; position.y = 29*tile; break; case 18: position.x = 42*tile; position.y = 26*tile; break; case 19: position.x = 57*tile; position.y = 41*tile; break; } originalHP = hp; originalPosition = position; } void Enemy::ChangeHP( float amount ) { hp += amount; } void Enemy::Update( Character players[2], int soundTimer, int soundTimer2, float gameTimer, SAMPLE* sndAttack, SAMPLE* sndDamage, int MaxText, TextEffect txteffect[] ) { if ( deadTimer > 0 ) { deadTimer -= 0.1; if ( deadTimer <= 0 ) { Reset(); } } if ( exists ) { collisionRegion.X( position.x + 5 ); collisionRegion.Y( position.y + 5 ); collisionRegion.W( 24 ); collisionRegion.H( 24 ); if ( atkCounter > 0 ) { atkCounter -= 0.5; } else { atkCounter = -1; action = WALKING; } for ( int p = 0; p < 2; p++ ) { if ( Exists() == true && players[p].Exists() && IsCollision( &players[p] ) ) { if ( players[p].Is() == ATTACKING ) { if ( soundTimer <= 0 ) { play_sample( sndAttack, 255, 128, 1000, false ); soundTimer = 5.0; ChangeHP( players[p].StrengthFloat() ); if ( hp <= 0 ) { players[p].Exp( Exp() ); } bool foundText = false; //Setup fancy text crap for ( int j=0; j<MaxText; j++ ) { if ( foundText == false ) { if ( txteffect[j].inUse == false ) { txteffect[j].Setup( players[p].StrengthString().c_str(), X()+3, Y(), 255, 100, 75 ); foundText = true; } } } } }//attacking //enemy attack if ( soundTimer2 <= 0 && gameTimer > 20 ) { play_sample( sndDamage, 255, 128, 1000, false ); soundTimer2 = 10.0; players[p].AddHP( -0.1 ); bool foundText = false; //Setup fancy text crap for ( int j=0; j<MaxText; j++ ) { if ( foundText == false ) { if ( txteffect[j].inUse == false ) { txteffect[j].Setup( "-2", players[p].X()+3, players[p].Y(), 255, 0, 0 ); foundText = true; } } } }//not attacking }//if ( enemy[i].Exists() == true && IsCollision( &player, &enemy[i] ) ) } if ( hp <= 0 ) { exists = false; SetDeadTimer(); } } } bool Enemy::IsCollision( Character *player ) { Rect pl, en; pl.x = player->RX(); pl.y = player->RY(); pl.w = player->RW(); pl.h = player->RH(); en.x = RX(); en.y = RY(); en.w = RW(); en.h= RH(); return ( pl.x < en.x+en.w && pl.x+pl.w > en.x && pl.y < en.y+en.h && pl.y+pl.h > en.y ); } void Enemy::Move( Direction dir ) { if ( exists ) { if ( action != ATTACKING ) { if ( dir == LEFT ) { direction = dir; position.x = (int)(position.x - speed); } else if ( dir == RIGHT ) { direction = dir; position.x = (int)(position.x + speed); } else if ( dir == UP ) { position.y = (int)(position.y - speed); } else if ( dir == DOWN ) { position.y = (int)(position.y + speed); } action = WALKING; } IncrementFrame(); } } void Enemy::Reset() { hp = originalHP; position = originalPosition; exists = true; } void Enemy::SetDeadTimer() { deadTimer = 100; } void Enemy::Draw( BITMAP *destination, BITMAP *source, int offsetX, int offsetY ) { if ( exists ) { if ( action != ATTACKING ) masked_blit( source, destination, (int)frame * position.w, (int)direction * position.h, position.x - offsetX, position.y - offsetY, position.w, position.h ); else { int atk; if ( atkCounter > 5 ) { atk = 0; } else { atk = 1; } if ( direction == LEFT ) masked_blit( source, destination, atk*position.w+(position.w*2), 2*position.h, position.x - offsetX, position.y - offsetY, position.w, position.h ); else if ( direction == RIGHT ) masked_blit( source, destination, atk*position.w, 2*position.h, position.x - offsetX, position.y - offsetY, position.w, position.h ); } } } void Enemy::IncrementFrame() { frame += 0.15f; if ( frame >= frameMax ) frame = 0.0f; }
// SimpleGraphic Engine // (c) David Gowor, 2014 // // Module: System Video // Platform: Windows // #include "sys_local.h" // ==================== // sys_IVideo Interface // ==================== class sys_video_c: public sys_IVideo { public: // Interface int Apply(sys_vidSet_s* set); void SetActive(bool active); bool IsActive(); void SizeChanged(int width, int height, bool max); void PosChanged(int x, int y); void GetMinSize(int &width, int &height); void SetVisible(bool vis); void SetTitle(const char* title); void* GetWindowHandle(); void GetRelativeCursor(int &x, int &y); void SetRelativeCursor(int x, int y); // Encapsulated sys_video_c(sys_IMain* sysHnd); ~sys_video_c(); sys_main_c* sys; bool initialised; HWND hwnd; // Window handle static BOOL __stdcall MonitorEnumProc(HMONITOR hMonitor, HDC hdc, LPRECT rect, LPARAM data); bool AddMonitor(HMONITOR hMonitor); void RefreshMonitorInfo(); int numMon; // Number of monitors int priMon; // Index of primary monitor struct { HMONITOR hnd; int left; int top; int width; int height; char devName[CCHDEVICENAME]; } mon[16]; // Array of monitor specs int defRes[2]; // Default resolution sys_vidSet_s cur; // Current settings int scrSize[2]; // Screen size int minSize[2]; // Minimum window size }; sys_IVideo* sys_IVideo::GetHandle(sys_IMain* sysHnd) { return new sys_video_c(sysHnd); } void sys_IVideo::FreeHandle(sys_IVideo* hnd) { delete (sys_video_c*)hnd; } sys_video_c::sys_video_c(sys_IMain* sysHnd) : sys((sys_main_c*)sysHnd) { initialised = false; minSize[0] = minSize[1] = 0; // Register the window class WNDCLASS wndClass; ZeroMemory(&wndClass, sizeof(WNDCLASS)); wndClass.lpszClassName = CFG_TITLE " Class"; wndClass.hInstance = sys->hinst; wndClass.lpfnWndProc = sys_main_c::WndProc; wndClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wndClass.hIcon = sys->icon; wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.style = CS_DBLCLKS; if (RegisterClass(&wndClass) == 0) { sys->Error("Unable to register main window class"); } // Create the window hwnd = CreateWindowEx( 0, CFG_TITLE " Class", CFG_TITLE, WS_POPUP | WS_VISIBLE,/* | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_SIZEBOX | WS_MAXIMIZEBOX, */ 0, 0, 500, 500, NULL, NULL, sys->hinst, NULL ); if (hwnd == NULL) { sys->Error("Unable to create window"); } SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)sys); ShowWindow(hwnd, SW_HIDE); // Process any messages generated during creation sys->RunMessages(NULL, true); } sys_video_c::~sys_video_c() { // Destroy the window DestroyWindow(hwnd); // Unregister the window class UnregisterClass(CFG_TITLE " Class", sys->hinst); if (initialised && (cur.flags & VID_FULLSCREEN)) { // Reset resolution ChangeDisplaySettingsEx(mon[cur.display].devName, NULL, NULL, 0, NULL); } } // ================== // System Video Class // ================== int sys_video_c::Apply(sys_vidSet_s* set) { cur = *set; // Enumerate monitors priMon = -1; numMon = 0; EnumDisplayMonitors(NULL, NULL, &sys_video_c::MonitorEnumProc, (LPARAM)this); // Determine which monitor to create window on if (cur.display >= numMon) { sys->con->Warning("display #%d doesn't exist (max display number is %d)", cur.display, numMon - 1); cur.display = 0; } else if (cur.display < 0) { // Use monitor containing the mouse cursor POINT curPos; GetCursorPos(&curPos); HMONITOR curMon = MonitorFromPoint(curPos, MONITOR_DEFAULTTOPRIMARY); cur.display = 0; for (int m = 0; m < numMon; m++) { if (mon[m].hnd == curMon) { cur.display = m; break; } } } defRes[0] = mon[cur.display].width; defRes[1] = mon[cur.display].height; minSize[0] = minSize[1] = 0; if (sys->debuggerRunning) { // Force topmost off if debugger is attached cur.flags&= ~VID_TOPMOST; } if (cur.mode[0] == 0) { // Use default resolution if one isn't specified Vector2Copy(defRes, cur.mode); } Vector2Copy(cur.mode, vid.size); if (cur.flags & VID_FULLSCREEN) { Vector2Copy(cur.mode, scrSize); if (cur.shown) { // Change screen resolution SetActive(true); } } else { Vector2Copy(defRes, scrSize); } // Select window styles int style = WS_POPUP; if ( !(cur.flags & VID_FULLSCREEN) && (cur.flags & VID_USESAVED || cur.flags & VID_RESIZABLE || cur.mode[0] < defRes[0] || cur.mode[1] < defRes[1]) ) { style|= WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; if (cur.flags & VID_RESIZABLE) { style|= WS_SIZEBOX | WS_MAXIMIZEBOX; } } int exStyle = (cur.flags & VID_TOPMOST)? WS_EX_TOPMOST : 0; SetWindowLong(hwnd, GWL_STYLE, style); SetWindowLong(hwnd, GWL_EXSTYLE, exStyle); // Get window rectangle RECT wrec; if (cur.flags & VID_USESAVED) { POINT savePos = { cur.save.pos[0], cur.save.pos[1] }; HMONITOR winMon = MonitorFromPoint(savePos, MONITOR_DEFAULTTONULL); if (winMon == NULL) { // Window is offscreen, move it to the nearest monitor winMon = MonitorFromPoint(savePos, MONITOR_DEFAULTTONEAREST); for (int m = 0; m < numMon; m++) { if (mon[m].hnd == winMon) { wrec.left = 0; wrec.top = 0; wrec.right = 1000; wrec.bottom = 1000; AdjustWindowRectEx(&wrec, style, FALSE, exStyle); cur.save.pos[0] = mon[m].left - wrec.left; cur.save.pos[1] = mon[m].top - wrec.top; break; } } } wrec.left = cur.save.pos[0]; wrec.top = cur.save.pos[1]; if (cur.save.maximised) { cur.flags|= VID_MAXIMIZE; } else { cur.mode[0] = cur.save.size[0]; cur.mode[1] = cur.save.size[1]; } } else { wrec.left = (scrSize[0] - cur.mode[0])/2 + mon[cur.display].left; wrec.top = (scrSize[1] - cur.mode[1])/2 + mon[cur.display].top; } vid.pos[0] = wrec.left; vid.pos[1] = wrec.top; wrec.right = wrec.left + cur.mode[0]; wrec.bottom = wrec.top + cur.mode[1]; AdjustWindowRectEx(&wrec, style, FALSE, exStyle); SetWindowPos(hwnd, NULL, wrec.left, wrec.top, wrec.right - wrec.left, wrec.bottom - wrec.top, SWP_FRAMECHANGED); if (cur.shown) { ShowWindow(hwnd, SW_SHOW); SetFocus(hwnd); HWND fgHwnd = GetForegroundWindow(); if (fgHwnd) { DWORD processId = 0; GetWindowThreadProcessId(fgHwnd, &processId); if (processId == GetCurrentProcessId()) { SetForegroundWindow(hwnd); } else { FlashWindow(hwnd, FALSE); } } else { SetForegroundWindow(hwnd); } } // Calculate minimum size if (cur.flags & VID_RESIZABLE && cur.minSize[0]) { RECT rec; rec.left = 0; rec.top = 0; rec.right = cur.minSize[0]; rec.bottom = cur.minSize[1]; AdjustWindowRectEx(&rec, style, FALSE, exStyle); minSize[0] = rec.right - rec.left; minSize[1] = rec.bottom - rec.top; } if (cur.flags & VID_MAXIMIZE) { ShowWindow(hwnd, SW_MAXIMIZE); GetClientRect(hwnd, &wrec); vid.size[0] = wrec.right; vid.size[1] = wrec.bottom; } // Process any messages generated during application sys->RunMessages(NULL, true); initialised = true; return 0; } void sys_video_c::SetActive(bool active) { if ((cur.flags & VID_FULLSCREEN) && (cur.mode[0] != defRes[0] || cur.mode[1] != defRes[1] || cur.depth)) { // Fullscreen and mode specified if (active) { // Change resolution DEVMODE dm; ZeroMemory(&dm, sizeof(dm)); dm.dmSize = sizeof(dm); dm.dmPelsWidth = cur.mode[0]; dm.dmPelsHeight = cur.mode[1]; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; if (cur.depth) { dm.dmFields|= DM_BITSPERPEL; dm.dmBitsPerPel = cur.depth; } if (ChangeDisplaySettingsEx(mon[cur.display].devName, &dm, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL) { sys->con->Warning("failed to change screen resolution"); } // Make sure window is positioned correctly RefreshMonitorInfo(); SetWindowPos(hwnd, NULL, mon[cur.display].left, mon[cur.display].top, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } else { // Change back to default ChangeDisplaySettingsEx(mon[cur.display].devName, NULL, NULL, CDS_FULLSCREEN, NULL); } } if (initialised && (cur.flags & VID_TOPMOST) && IsWindowVisible(hwnd)) { if (active) { // Make it topmost SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); } else { if (cur.flags & VID_FULLSCREEN) { // Just minimize it ShowWindow(hwnd, SW_MINIMIZE); } else { HWND fghwnd = GetForegroundWindow(); if (GetWindowLong(fghwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) { // Switching to a topmost window, put our window at the top of all non-topmost windows SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } else { // Switching to a non-topmost window, put our window behind it SetWindowPos(hwnd, fghwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } } } } } bool sys_video_c::IsActive() { return GetForegroundWindow() == hwnd; } void sys_video_c::SizeChanged(int width, int height, bool max) { vid.size[0] = width; vid.size[1] = height; vid.maximised = max; } void sys_video_c::PosChanged(int x, int y) { vid.pos[0] = x; vid.pos[1] = y; } void sys_video_c::GetMinSize(int &width, int &height) { width = minSize[0]; height = minSize[1]; } void sys_video_c::SetVisible(bool vis) { if ( !initialised ) return; ShowWindow(hwnd, vis? SW_SHOW : SW_HIDE); } void sys_video_c::SetTitle(const char* title) { SetWindowText(hwnd, (title && *title)? title : CFG_TITLE); } void* sys_video_c::GetWindowHandle() { return hwnd; } void sys_video_c::GetRelativeCursor(int &x, int &y) { if ( !initialised ) return; POINT cp; GetCursorPos(&cp); ScreenToClient(hwnd, &cp); x = cp.x; y = cp.y; } void sys_video_c::SetRelativeCursor(int x, int y) { if ( !initialised ) return; POINT cp = {x, y}; ClientToScreen(hwnd, &cp); SetCursorPos(cp.x, cp.y); } BOOL __stdcall sys_video_c::MonitorEnumProc(HMONITOR hMonitor, HDC hdc, LPRECT rect, LPARAM data) { sys_video_c* vid = (sys_video_c*)data; return vid->AddMonitor(hMonitor); } bool sys_video_c::AddMonitor(HMONITOR hMonitor) { MONITORINFOEX info; info.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(hMonitor, &info); mon[numMon].hnd = hMonitor; mon[numMon].left = info.rcMonitor.left; mon[numMon].top = info.rcMonitor.top; mon[numMon].width = info.rcMonitor.right - info.rcMonitor.left; mon[numMon].height = info.rcMonitor.bottom - info.rcMonitor.top; if (info.dwFlags & MONITORINFOF_PRIMARY) { priMon = numMon; } strcpy(mon[numMon].devName, info.szDevice); return ++numMon < 16; } void sys_video_c::RefreshMonitorInfo() { for (int m = 0; m < numMon; m++) { MONITORINFO info; info.cbSize = sizeof(MONITORINFO); if (GetMonitorInfo(mon[m].hnd, &info)) { mon[m].left = info.rcMonitor.left; mon[m].top = info.rcMonitor.top; mon[m].width = info.rcMonitor.right - info.rcMonitor.left; mon[m].height = info.rcMonitor.bottom - info.rcMonitor.top; } else { if (m == priMon) sys->Error("Primary monitor no longer exists!"); mon[m].left = mon[priMon].left; mon[m].top = mon[priMon].top; mon[m].width = mon[priMon].width; mon[m].height = mon[priMon].height; } } }
#include "C:\Users\Andrey\Desktop\Linearization\Linerization\Working Test\version 1.1\include\Rectangle.h" Rectangle::Rectangle() { for (int i = 0; i < diskret; i++) val[i] = 0x0; } Rectangle::~Rectangle(void) { } //------------------------------------------------------------------------------------------------ // инициализирует массив значений сигнала меандр void Rectangle::setVal(float _diap) { int x = symmetry*diskret/100; uint16_t value; for (int i = 0; i < x ; i++) { value = (2*amplitude + offsetY) * 0xFFFF / _diap; if (value>0xFFFF) value = 0xFFFF; if (value<0x0) value = 0x0; val[i] = value & 0xFFFF; } for (int i = x; i < diskret; i++) { value = offsetY * 0xFFFF / _diap; if (value>0xFFFF) value = 0xFFFF; if (value<0x0) value = 0x0; val[i] = value & 0xFFFF; } }
#include<iostream> #include<Windows.h> #include<process.h> #include<time.h> #include <Mmsystem.h> #pragma comment(lib, "Winmm.lib") using namespace std; #define MAX 3000000 int getPrime(int* result, int min, int max); unsigned int WINAPI ThreadFunc1(void* arg); unsigned int WINAPI ThreadFunc2(void* arg); unsigned int WINAPI ThreadFunc3(void* arg); int result1 = 0; int result2 = 0; int result3 = 0; int main(){ unsigned int threadId; DWORD t1, t2; t1 = timeGetTime(); HANDLE handle[3]; handle[0]=(HANDLE)_beginthreadex(NULL, 0, ThreadFunc1, NULL, 0, &threadId); handle[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc2, NULL, 0, &threadId); handle[2] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc3, NULL, 0, &threadId); WaitForMultipleObjects(3, handle, true, INFINITE); t2 = timeGetTime(); int result = result1 + result2 + result3; printf("Result= %d \n", result); printf("Use Time:%f\n", (t2 - t1)*1.0 / 1000); } int getPrime(int *result, int min, int max){ int i = 0; int index = min<2 ? 2 : min; for (; index<max; index++){ int mid = sqrt(index) + 1; int flag = 0; int tmp = 2; for (; tmp<mid; tmp++){ if (index%tmp == 0){ flag = 1; } } if (!flag || index == 2){ result[i] = index; i++; } } return i; } unsigned int WINAPI ThreadFunc1(void* arg){ printf("In thread1\n"); int result1_arr[100000]; int max = MAX / 3; result1 = getPrime(result1_arr, 1, max); printf("Out thread1\n"); _endthreadex(2); return 1; } unsigned int WINAPI ThreadFunc2(void* arg){ printf("In thread2\n"); int result2_arr[100000]; int max = 2*MAX / 3; int min = MAX / 3; result2 = getPrime(result2_arr, min, max); printf("Out thread2\n"); _endthreadex(2); return 1; } unsigned int WINAPI ThreadFunc3(void* arg){ printf("In thread3\n"); int result3_arr[100000]; int max = MAX ; int min = 2*MAX / 3; result3 = getPrime(result3_arr, min, max); printf("Out thread3\n"); _endthreadex(2); return 1; }
#ifndef THREADCONTROLLER_H #define THREADCONTROLLER_H #include <QObject> #include <QList> #include <QVector> #include <QThread> #include "httpworker.h" class QThreadController : public QObject { Q_OBJECT public: explicit QThreadController(QObject *parent = 0); ~QThreadController(); int getFreeWorker(); signals: void textFound(QString header, QString page, QVector<QPoint> positions); void stopAll(); void pauseAll(); void resumeAll(); void progressChanged(int value); void searchFinished(); public slots: void startSearch(QUrl url, QString text, int url_count, int thread_count = 1, bool search_all = true, bool case_sens = true); void addTask(QUrl task); void stopAllThreads(); void pauseAllThreads(); void resumeAllThreads(); private slots: void workRequested(int worker_id); void pageLoaded(QString header, QString page, QVector<QPoint> positions); private: void sendTask(int worker_id); QVector<QThread *> _threads; QVector<QHttpWorker *> _workers; QVector<bool> _isWorking; QList<QUrl> _tasks; int _max_task_count; int _current_task; int _finished_task; int _free_workers_count; QMutex _access_mutex; QSemaphore _task_sem; QString _text; bool _search_all; bool _case_sens; }; #endif // THREADCONTROLLER_H
#include <iostream> using namespace std; int binarysearch(int array[],int size,int x) { // code for the binary search int firstindex = 0; int lastindex = size-1; while(firstindex<=lastindex) { int middle = (firstindex +lastindex)/2; if(array[middle] == x){ return middle; } else if(array[middle] > x) { lastindex = middle-1; } else if(array[middle] < x) { firstindex = middle + 1; } } return -1; }; int main() { int array[100],size,i,x; cout<<"Enter the size of the array : "; cin>>size; cout <<"Enter the array : "; for(i=0;i<size;i++) { cin>>array[i]; } cout<<"Enter the number you want to search"<<endl; cin>>x; int result =binarysearch(array,size,x); if(result == -1){ cout<<"element is not found"; }else{ cout<<"element found at index "<<result; } return 0; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Allowed #if-ery: SYSTEM_* defines, *_BOOL, __cplusplus. */ #ifndef POSIX_SYS_DECLARE_BOOL_H #define POSIX_SYS_DECLARE_BOOL_H __FILE__ /** @file declare_bool.h Chose a type to use as BOOL. * * We should aim to move to using bool wherever possible. However, assorted * Opera code abuses BOOL in a delightful diversity of ways (treating it as a * synonym for OP_STATUS, whose semantics are opposite, and even using it to * hold a many-bit unsigned int), so such builds are still prone to bugs, some * of which are hard to track down. We should fix that. * * Generally, test-compiling with perverse alternatives for BOOL is quite a good * way of catching code that mis-uses BOOL and perverse suggestions for * alternatives are encouraged. * * Pointer is not an option since x != y doesn't behave nicely as a pointer. * * Using an enum also doesn't work: we get "cannot convert 'bool' to 'BOOL' in * return" messages all over the place; we'd need to change lots of BOOL * expressions to say ? TRUE : FALSE to convert themselves to BOOL. We'd need * the same change in order to use a char-sized integral type: we have plenty of * code which uses, as a BOOL, expression & MASK of some int-sized type; if MASK * & 0xff is zero, this will always evaluate to false. However, test-compiling * with such types can reveal (among the perfectly legitimate warnings due to * these types' unsuitability as BOOL) real problems that are worth fixing. * * See make variable BOOL_TYPE in the unix-build module. */ #ifdef __cplusplus #ifdef NATIVE_BOOL /* we'd like this to be the default */ typedef bool BOOL; #define TRUE true #define FALSE false #elif defined(CLASS_BOOL) /* BOOL debugging class */ class BOOL { public: BOOL() {} BOOL(bool b) : value(b) {} operator bool() const { return value; } /* The bitwise assignment operators are almost, but not quite * exactly, equivalent to their expanded forms: * * var &= expr; <~> var = expr && var; * var |= expr; <~> var = expr || var; * * The exceptions are e.g. (1 & 2 == 0) and (1 | 2 == 3), but any * such BOOL/int abuse will fail to compile since this class can * only be constructed from bool. */ BOOL& operator &= (const BOOL& other) { value &= other.value; return *this; } BOOL& operator |= (const BOOL& other) { value |= other.value; return *this; } private: /* Require explicit conversion for integer and pointer types. */ BOOL(int); BOOL(void*); /* The following unary operators are disallowed. */ BOOL operator + () const; BOOL operator - () const; BOOL& operator ++ (); BOOL& operator ++ (int); BOOL& operator -- (); BOOL& operator -- (int); BOOL operator ~ () const; bool value; }; /* Ensuring that TRUE/FALSE are of type BOOL helps to avoid ambiguity * in some overloaded functions. Unfortunately it also inhibits GCC's * ability to see that these are constant expressions, which in some * cases results in warnings due to not being able to statically see * which code path(s) will be taken. */ #define TRUE (BOOL(true)) #define FALSE (BOOL(false)) /* The bitwise & and | operators have no advantage over && and ||. * They do guarantee that both operands are evaluated, but this is * obscure and not very useful. */ int operator & (const BOOL&, const BOOL&); int operator & (const BOOL&, int); int operator & (int, const BOOL&); int operator | (const BOOL&, const BOOL&); int operator | (const BOOL&, int); int operator | (int, const BOOL&); #if 0 /* The bitwise ^ operator is equivalent with !=, but which is clearer * depends on the context and personal preference. */ int operator ^ (const BOOL&, const BOOL&); int operator ^ (const BOOL&, int); int operator ^ (int, const BOOL&); #endif /* The arithmetic operators seldom make sense. Using BOOL as int in * arithmetic should be done with explicit type conversion. */ int operator + (const BOOL&, const BOOL&); int operator + (const BOOL&, int); int operator + (int, const BOOL&); int operator - (const BOOL&, const BOOL&); int operator - (const BOOL&, int); int operator - (int, const BOOL&); int operator * (const BOOL&, const BOOL&); int operator * (const BOOL&, int); int operator * (int, const BOOL&); int operator / (const BOOL&, const BOOL&); int operator / (const BOOL&, int); int operator / (int, const BOOL&); int operator % (const BOOL&, const BOOL&); int operator % (const BOOL&, int); int operator % (int, const BOOL&); /* The comparison operators (other than == and !=) don't make sense. * This may also reveal operator precedence errors. */ bool operator < (const BOOL&, const BOOL&); bool operator < (const BOOL&, int); bool operator < (int, const BOOL&); bool operator <= (const BOOL&, const BOOL&); bool operator <= (const BOOL&, int); bool operator <= (int, const BOOL&); bool operator >= (const BOOL&, const BOOL&); bool operator >= (const BOOL&, int); bool operator >= (int, const BOOL&); bool operator > (const BOOL&, const BOOL&); bool operator > (const BOOL&, int); bool operator > (int, const BOOL&); #elif defined(CHAR_BOOL) /* untried */ typedef char BOOL; #define TRUE '\1' #define FALSE '\0' #elif defined(UCHAR_BOOL) /* Catch use of TRUE and FALSE as #if conditionals ... */ typedef unsigned char BOOL; #define TRUE ((BOOL)(1>0)) #define FALSE ((BOOL)(1<0)) #elif defined(ENUM_BOOL) /* Experimental: elegant simplicity, but unusable. */ typedef enum { FALSE, TRUE } BOOL; #elif defined(UNSIGNED_BOOL) /* this is surprisingly good at revealing glitches in code */ typedef unsigned int BOOL; #define TRUE 1U #define FALSE 0U #else /* this is what we have traditionally used ... */ typedef int BOOL; #define TRUE 1 #define FALSE 0 #endif #else /* C compilation units must not use BOOL */ typedef struct { unsigned int i : 1; } unusable_bool; #define BOOL unusable_bool #endif /* __cplusplus */ #endif /* POSIX_SYS_DECLARE_BOOL_H */
/* * QkThings LICENSE * The open source framework and modular platform for smart devices. * Copyright (C) 2014 <http://qkthings.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "qkutils.h" #include <QDebug> #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QJsonParseError> using namespace QkUtils; QkUtils::JsonParser::JsonParser(QObject *parent) : QObject(parent) { _jsonStr = ""; _depthLevel = 0; _inString = false; _escChar = false; } void QkUtils::JsonParser::parseData(QByteArray data) { bool done = false; char *p_data = data.data(); for(int i = 0; i < data.count(); i++) { if(*p_data == '\"') { if(!_inString) _inString = true; else { if(!_escChar) _inString = false; else _escChar = false; } } if(_inString) { if(*p_data == '\\') _escChar = true; } else { if(*p_data == '{') { if(_depthLevel == 0) _jsonStr = ""; _depthLevel++; } else if(*p_data == '}') { _depthLevel--; if(_depthLevel == 0) done = true; } } _jsonStr += *p_data++; if(done) { QJsonParseError jsonError; QJsonDocument jsonDoc = QJsonDocument::fromJson(_jsonStr, &jsonError); if(jsonError.error != QJsonParseError::NoError) { qDebug() << jsonError.errorString(); } else { emit parsed(jsonDoc); done = false; } } } } QMap<QString, Target> QkUtils::supportedTargets(const QString &embPath) { QMap<QString, Target> targets; QString filePath = embPath + "/target/targets.json"; QJsonDocument doc = jsonFromFile(filePath); QVariantMap jsonTargets = doc.object().toVariantMap(); foreach(QString targetName, jsonTargets.keys()) { Target target; if(targetName == "version") continue; target.name = targetName; QVariantMap jsonTargetInfo = jsonTargets[targetName].toMap(); target.toolchainUrl = jsonTargetInfo["toolchainUrl"].toString(); QVariantList jsonTargetVariants = jsonTargetInfo["variants"].toList(); TargetVariantList targetVariants; foreach(QVariant jsonVariant, jsonTargetVariants) { QMap<QString, QVariant> variant = jsonVariant.toMap(); Target::Board targetVariant; targetVariant.name = variant["name"].toString(); targetVariants.append(targetVariant); } target.boards.append(targetVariants); targets.insert(targetName, target); } return targets; } QJsonDocument QkUtils::jsonFromFile(const QString &filePath) { QString jsonFilePath = filePath; QJsonDocument doc; QFile file(jsonFilePath); if(!file.open(QFile::ReadOnly | QFile::Text)) { qDebug() << "failed to open file" << jsonFilePath; } else { QString jsonStr = QString(file.readAll()); jsonStr.remove('\t'); jsonStr.remove(' '); QJsonParseError parseError; doc = QJsonDocument::fromJson(jsonStr.toUtf8(), &parseError); if(parseError.error != QJsonParseError::NoError) qDebug() << "json parse error:" << parseError.errorString(); } return doc; } void QkUtils::fillValue(int value, int count, int *idx, QByteArray &data) { int i, j = *idx; for(i = 0; i < count; i++, j++) { data.insert(j, (value >> 8*i) & 0xFF); } *idx = j; } void QkUtils::fillString(const QString &str, int count, int *idx, QByteArray &data) { QString justifiedStr = str.leftJustified(count, '\0', true); fillString(justifiedStr, idx, data); } void QkUtils::fillString(const QString &str, int *idx, QByteArray &data) { int j = *idx; data.insert(j, str); j += str.length()+1; } int QkUtils::getValue(int count, int *idx, const QByteArray &data, bool sigExt) { int j, value = 0; int i = *idx; for(j = 0; j < count; j++, i++) { if(i < data.count()) value += (data.at(i) & 0xFF) << (8*j); // little endian } switch(count) // truncate and extend sign bit { case 1: value &= 0xFF; if(sigExt & ((value & 0x80) > 0)) value |= 0xFFFFFF00; break; case 2: value &= 0xFFFF; if(sigExt & ((value & 0x8000) > 0)) value |= 0xFFFF0000; break; case 4: value &= 0xFFFFFFFF; break; } *idx = i; return value; } QString QkUtils::getString(int *idx, const QByteArray &data) { int j; char c, buf[1024]; int i = *idx; memset(buf, '\0', sizeof(buf)); for(j=0; j < 1024; j++) { if(j+1 < data.length()) { c = (char)((quint8)data[i++]); if(c == '\0') break; if((c < 32 || c > 126)) c = ' '; buf[j] = c; } else break; } *idx = i; return QString(buf); } QString QkUtils::getString(int count, int *idx, const QByteArray &data) { int j; char c, buf[count+1]; int i = *idx; memset(buf, '\0', sizeof(buf)); for(j=0; j < count; j++) { if(j+1 < data.length()) { c = (char)((quint8)data[i++]); if((c < 32 || c > 126) && c != '\0') c = ' '; buf[j] = c; } else break; } buf[count] = '\0'; *idx = i; return QString(buf); } float QkUtils::floatFromBytes(int value) { IntFloatConverter converter; converter.i_value = value; return converter.f_value; } int QkUtils::bytesFromFloat(float value) { IntFloatConverter converter; converter.f_value = value; return converter.i_value; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #include "core/pch.h" #include "platforms/unix/base/x11/x11_inputmethod.h" #include "platforms/unix/base/x11/x11_inputcontext.h" #include <locale.h> #include <stdlib.h> X11InputMethod::X11InputMethod(X11Types::Display* display) : m_display(display) , m_xim(0) , m_xim_style(0) , m_ic_list(0) { AttachToXIM(display); }; void X11InputMethod::AttachToXIM(X11Types::Display* display) { if (m_xim != 0) return; if (!SetLocaleModifier(0, 0, FALSE) ) { // Recovery to avoid bug DSK-297409 which really is about a broken distribution OpString8 lc_ctype; lc_ctype.Set(setlocale(LC_CTYPE, 0)); BOOL ok = FALSE; OpAutoVector<OpString8> list; OP_STATUS rc = GetAlternativeLocaleFormat(lc_ctype, list); if (OpStatus::IsError(rc) || list.GetCount()==0) { ok = SetLocaleModifier(0, "C", FALSE); } else { for (UINT32 i=0; !ok && i<list.GetCount(); i++) ok = SetLocaleModifier(0, list.Get(i)->CStr(), FALSE); } if(!ok) { fprintf(stderr, "opera: You appear to have an invalid locale set. This may prevent you from being able to type\n"); return; } } m_xim = XOpenIM(display, NULL, NULL, NULL); if (m_xim == NULL) { // Recovery to avoid bug DSK-304220 (broken XMODIFIERS) SetLocaleModifier("@im=", m_lc_modifier.value.CStr(), TRUE); m_xim = XOpenIM(display, NULL, NULL, NULL); if (m_xim == NULL) { fprintf(stderr, "opera: XOpenIM failed. This may prevent you from being able to type\n"); return; } } { // local scope XIMCallback cb; cb.client_data = (XPointer)this; cb.callback = XIMDestroyCallback; const char * setvalueerr = XSetIMValues(m_xim, XNDestroyCallback, &cb, NULL); if (setvalueerr != 0) fprintf(stderr, "opera: Failed to set XIM destroy callback\n"); } XIMStyles* xim_styles = 0; char* im_values = XGetIMValues(m_xim, XNQueryInputStyle, &xim_styles, NULL); if(im_values != NULL || xim_styles == NULL) { fprintf(stderr, "opera: input method does not support any styles\n"); } if(xim_styles) { unsigned long callbacks = 0; for (int i = 0; i < xim_styles->count_styles; i++) { // We try to find the style with the most support for preedit and status callbacks if ((xim_styles->supported_styles[i] & XIMPreeditCallbacks) && (xim_styles->supported_styles[i] & callbacks) == callbacks) { m_xim_style = xim_styles->supported_styles[i]; callbacks |= XIMPreeditCallbacks; } if ((xim_styles->supported_styles[i] & XIMStatusCallbacks) && (xim_styles->supported_styles[i] & callbacks) == callbacks) { m_xim_style = xim_styles->supported_styles[i]; callbacks |= XIMStatusCallbacks; } if ((xim_styles->supported_styles[i] == (XIMPreeditNothing | XIMStatusNothing)) && !callbacks) { m_xim_style = xim_styles->supported_styles[i]; } } if (m_xim_style == 0) { fprintf(stderr, "opera: input method does not support the style we support\n"); } XFree(xim_styles); } } X11InputMethod::~X11InputMethod() { /* I hope it is safe to call this even if we haven't registered * any callbacks. (If it is also sufficient to call this once to * undo all matching XRegisterIMInstantiateCallback()s, we could * remove the other call to this function.) */ XUnregisterIMInstantiateCallback(m_display, NULL, NULL, NULL, XIMInstantiateCallback, (XPointer)this); while (m_ic_list != 0) { ICList * ic = m_ic_list; ic->ic->InputMethodIsDeleted(); m_ic_list = ic->next; OP_DELETE(ic); }; if(m_xim) XCloseIM(m_xim); } X11InputContext* X11InputMethod::CreateIC(X11Widget * window) { if( !m_xim || !m_xim_style ) return 0; X11InputContext* input_context = OP_NEW(X11InputContext, ()); ICList * listentry = OP_NEW(ICList, ()); if (!input_context || !listentry || OpStatus::IsError(input_context->Init(this, window))) { OP_DELETE(input_context); return 0; } listentry->next = m_ic_list; listentry->ic = input_context; m_ic_list = listentry; return input_context; } void X11InputMethod::InputContextIsDeleted(X11InputContext * ic) { ICList ** p = &m_ic_list; while (*p != 0 && (*p)->ic != ic) p = &(*p)->next; if (*p == 0) return; ICList * q = *p; *p = (*p)->next; OP_DELETE(q); return; }; // Bug DSK-297409 // We convert the locale of the form *.utf8 to {*.UTF-8, *, POSIX, C} OP_STATUS X11InputMethod::GetAlternativeLocaleFormat(const OpStringC8& locale, OpVector<OpString8>& list) { int pos = locale.Find(".utf8"); if (pos != KNotFound) { OpString8* s = OP_NEW(OpString8,()); if(!s) return OpStatus::ERR_NO_MEMORY; s->Set(locale, pos); s->Append(".UTF-8"); list.Add(s); s = OP_NEW(OpString8,()); if(!s) return OpStatus::ERR_NO_MEMORY; s->Set(locale, pos); list.Add(s); } OpString8* s = OP_NEW(OpString8,()); if(!s) return OpStatus::ERR_NO_MEMORY; s->Set("POSIX"); list.Add(s); s = OP_NEW(OpString8,()); if(!s) return OpStatus::ERR_NO_MEMORY; s->Set("C"); list.Add(s); return OpStatus::OK; } BOOL X11InputMethod::SetLocaleModifier(const char* modifier, const char* lc_ctype, BOOL silent) { if (lc_ctype && *lc_ctype) { setlocale(LC_CTYPE, lc_ctype); if (!silent) fprintf(stderr, "opera: LC_CTYPE changed to '%s'\n", lc_ctype); } BOOL ok = XSetLocaleModifiers(modifier ? modifier : "") != 0; if (!ok && !silent) fprintf(stderr, "opera: XSetLocaleModifiers failed with LC_CTYPE '%s'\n", lc_ctype ? lc_ctype : setlocale(LC_CTYPE, 0)); if (ok && !m_lc_modifier.valid) { m_lc_modifier.valid = TRUE; if (lc_ctype) m_lc_modifier.value.Set(lc_ctype); } return ok; } void X11InputMethod::XIMDestroyCallback(XIM xim, XPointer client_data, XPointer call_data) { X11InputMethod * self = (X11InputMethod *)client_data; self->m_xim = 0; for (ICList * p = self->m_ic_list; p != 0; p = p->next) p->ic->XIMHasBeenDestroyed(); /* I don't know if it is necessary to call unregister as many * times as register has been called. But I'll do it to be on the * safe side. Conversely, I don't know whether it is really safe * to call unregister without having called register first. But I * expect it is. */ XUnregisterIMInstantiateCallback(self->m_display, NULL, NULL, NULL, XIMInstantiateCallback, (XPointer)self); if (XRegisterIMInstantiateCallback(self->m_display, NULL, NULL, NULL, XIMInstantiateCallback, (XPointer)self) != True) fprintf(stderr, "opera: Failed to register callback to be notified of input methods becoming available.\n"); }; void X11InputMethod::XIMInstantiateCallback(X11Types::Display * dpy, XPointer client_data, XPointer call_data) { X11InputMethod * self = (X11InputMethod *)client_data; if (self->m_xim != 0) return; self->AttachToXIM(dpy); if (self->m_xim == 0) return; for (ICList * p = self->m_ic_list; p != 0; p = p->next) p->ic->Init(self); };
#pragma once #include "libOTe/config.h" #if defined(ENABLE_MRR_TWIST) && defined(ENABLE_SSE) #include <cryptoTools/Common/Defines.h> #include <cryptoTools/Crypto/PRNG.h> #include <cryptoTools/Crypto/Rijndael256.h> #include <cryptoTools/Crypto/RandomOracle.h> namespace osuCrypto { class EKEPopf { public: typedef Block256 PopfFunc; typedef bool PopfIn; // TODO: Make this more general. typedef Block256 PopfOut; EKEPopf(const RandomOracle& ro_) : ro(ro_) {} EKEPopf(RandomOracle&& ro_) : ro(ro_) {} PopfOut eval(PopfFunc f, PopfIn x) const { Rijndael256Dec ic(getKey(x)); return ic.decBlock(f); } PopfFunc program(PopfIn x, PopfOut y, PRNG& prng) const { return program(x, y); } PopfFunc program(PopfIn x, PopfOut y) const { Rijndael256Enc ic(getKey(x)); return ic.encBlock(y); } private: Block256 getKey(PopfIn x) const { Block256 key; RandomOracle roKey = ro; roKey.Update(x); roKey.Final(key); return key; } RandomOracle ro; }; class DomainSepEKEPopf: public RandomOracle { using RandomOracle::Final; using RandomOracle::outputLength; public: typedef EKEPopf ConstructedPopf; const static size_t hashLength = sizeof(Block256); DomainSepEKEPopf() : RandomOracle(hashLength) {} ConstructedPopf construct() { return EKEPopf(*this); } }; } #endif
#include <iostream> #include <iomanip> using namespace std; int sum_f(int** arr, int n){ int s=0; for (int i = 0; i < n;i++){ for (int j = 0;j<n;j++) if (j<=(n-1)-i) s += arr[i][j]; } return s; } void print (int** arr, int n, int sum){ cout << "\t" << " ---- Массив ---- "; for (int i = 0; i < n;i++) { cout << "\n"; for (int j = 0; j < n; j++) cout << setw(5) << arr[i][j]; } cout << "\n" << "\n" << "Результат вычисления: " << sum << "\n"; } void del (int** arr, int n){ for (int i = 0; i < n;i++) { for (int j = 0; j < n; j++) delete arr[i]; } delete [] arr; } int main() { setlocale(LC_ALL, "Russian"); int n, sum, **arr, count = 1; cout << "Введите размерность массива: "; cin >> n; arr = new int *[n]; //Создание массива и заполнение 1 и 0 for (int i = 0; i < n;i++){ arr[i] = new int [n]; for (int j = 0;j<n;j++) if (j<=(n-1)-i) arr[i][j]= 1; else arr[i][j]= 0; } sum = sum_f(arr, n); //Вывод массива и результата print(arr, n, sum); //Создание массива и заполнение цифрами for (int i = 0; i < n;i++){ for (int j = 0;j<n;j++) { arr[i][j] = count; count++; } } sum = sum_f(arr, n); //Вывод массива и результата print(arr, n, sum); //Удаление мссива del (arr, n); }
vector<int> Solution::dNums(vector<int> &A, int B) { unordered_map<int,int> mp; vector<int> ans; if(B>A.size()) return ans; int start=0; for(int i=0;i<B;i++) mp[A[i]]++; ans.push_back(mp.size()); for(int i=B;i<A.size();i++) { mp[A[i]]++; if(mp[A[start]]==1) mp.erase(A[start]); else mp[A[start]]--; start++; ans.push_back(mp.size()); } return ans; }
//==================================================================================== // @Title: WINDOW //------------------------------------------------------------------------------------ // @Location: /prolix/interface/include/cmpWindow.cpp // @Author: Kevin Chen // @Rights: Copyright(c) 2011 Visionary Games //==================================================================================== #include "../include/cmpWindow.h" //==================================================================================== // cmpWindow //==================================================================================== cmpWindow::cmpWindow(Point rPos, Dimensions rDim, cTextureId rSkinId) { pos = rPos; dim = rDim; alive = true; // check dimensions if (dim.w != 0 && (float)(dim.w/16) != 0) { LogMgr->Write(WARNING, "cmpWindow::cmpWindow >>>> Width of window is not a multiple of 32 > 0 as required"); } if (dim.h != 0 && (float)(dim.h/16) != 0) { LogMgr->Write(WARNING, "cmpWindow::cmpWindow >>>> Height of window is not a multiple of 32 > 0 as required"); } skin = AssetMgr->Load<Texture>(rSkinId); frames = new cSprite(rSkinId, 8, 8); frames->spriteset[F_L1N1].pos.x += 8; frames->spriteset[F_L1N2].pos.x -= 22; frames->spriteset[F_L1N2].pos.y += 8; frames->spriteset[F_L2N1].pos.x += 16; frames->spriteset[F_L2N1].pos.y -= 8; frames->spriteset[F_L2N2].pos.x -= 8; frames->spriteset[F_L2N2].pos.y += 0; LogMgr->Write(VERBOSE, "cmpWindow::cmpWindow >>>> Created an interface window"); } void cmpWindow::Draw() { int numX = dim.w/16 - 2; int numY = dim.h/16 - 2; // top texture bar frames->DrawFrame(B_TOPLEFT, Point(pos.x + 8, pos.y + 8)); frames->DrawFrame(T_TOPLEFT, Point(pos.x + 8, pos.y + 8)); for (int i=0;i<numX-1;i++) { if (i%2 == 0) { frames->DrawFrame(B_TOPH1, Point(pos.x + (i+1)*16 + 8, pos.y + 8)); frames->DrawFrame(T_TOPH1, Point(pos.x + (i+1)*16 + 8, pos.y + 8)); } if (i%2 == 1) { frames->DrawFrame(B_TOPH2, Point(pos.x + (i+1)*16 + 8, pos.y + 8)); frames->DrawFrame(T_TOPH2, Point(pos.x + (i+1)*16 + 8, pos.y + 8)); } } frames->DrawFrame(B_TOPRIGHT, Point(pos.x + numX*16 + 8,pos.y + 8)); frames->DrawFrame(T_TOPRIGHT, Point(pos.x + numX*16 + 8,pos.y + 8)); for (int i=0;i<numY;i++) { for (int j=0;j<numX+1;j++) { Point coord = Point(pos.x + j*16 + 8, pos.y + (i+1)*16 + 8); if (i%2 == 0) { if (j%2 == 0) { frames->DrawFrame(B_L1N1, coord); frames->DrawFrame(T_L1N1, coord); } else { frames->DrawFrame(B_L1N2, coord); frames->DrawFrame(T_L1N2, coord); } } else { if (j%2 == 0) { frames->DrawFrame(B_L2N1, coord); frames->DrawFrame(T_L2N1, coord); } else { frames->DrawFrame(B_L2N2, coord); frames->DrawFrame(T_L2N2, coord); } } } } // bottom texture bar frames->DrawFrame(B_BOTLEFT, Point(pos.x + 8, pos.y + numY*16 + 8)); frames->DrawFrame(T_BOTLEFT, Point(pos.x + 8, pos.y + numY*16 + 8)); for (int i=0;i<numX-1;i++) { if (i%2 == 0) { frames->DrawFrame(B_BOTH1, Point(pos.x + (i+1)*16 + 8, pos.y + numY*16 + 8)); frames->DrawFrame(T_BOTH1, Point(pos.x + (i+1)*16 + 8, pos.y + numY*16 + 8)); } if (i%2 == 1) { frames->DrawFrame(B_BOTH2, Point(pos.x + (i+1)*16 + 8, pos.y + numY*16 + 8)); frames->DrawFrame(T_BOTH2, Point(pos.x + (i+1)*16 + 8, pos.y + numY*16 + 8)); } } frames->DrawFrame(B_BOTRIGHT, Point(pos.x + numX*16 + 8,pos.y + numY*16 + 8)); frames->DrawFrame(T_BOTRIGHT, Point(pos.x + numX*16 + 8,pos.y + numY*16 + 8)); //////////////////////////////////////////////////////////////////////////////// // draw top bar frames->DrawFrame(F_TOPLEFT, Point(pos.x,pos.y)); for (int i=0;i<numX;i++) { if (i%2 == 0) frames->DrawFrame(F_TOPH1, Point(pos.x + (i+1)*16, pos.y)); if (i%2 == 1) frames->DrawFrame(F_TOPH2, Point(pos.x + (i+1)*16, pos.y)); } frames->DrawFrame(F_TOPRIGHT, Point(pos.x + (numX+1)*16,pos.y)); // draw vertical frame for (int i=0;i<numY;i++) { if (i%2 == 0) { frames->DrawFrame(F_VLEFT1, Point(pos.x, pos.y + (i+1)*16)); frames->DrawFrame(F_VRIGHT1, Point(pos.x + (numX+1)*16, pos.y + (i+1)*16)); } if (i%2 == 1) { frames->DrawFrame(F_VLEFT2, Point(pos.x, pos.y + (i+1)*16)); frames->DrawFrame(F_VRIGHT2, Point(pos.x + (numX+1)*16, pos.y + (i+1)*16)); } } // draw bottom bar frames->DrawFrame(F_BOTLEFT, Point(pos.x,pos.y + (numY + 1)*16)); for (int i=0;i<numX;i++) { if (i%2 == 0) frames->DrawFrame(F_BOTH1, Point(pos.x + (i+1)*16, pos.y + (numY + 1)*16)); if (i%2 == 1) frames->DrawFrame(F_BOTH2, Point(pos.x + (i+1)*16, pos.y + (numY + 1)*16)); } frames->DrawFrame(F_BOTRIGHT, Point(pos.x + (numX+1)*16,pos.y + (numY + 1)*16)); return; } cmpWindow::~cmpWindow() { LogMgr->Write(VERBOSE, "cmpWindow::~cmpWindow >>>> Deleted an interface window"); } //==================================================================================== // Extern //==================================================================================== std::vector<std::string> LineWrap (cFont font, std::string text, int width) { std::vector<std::string> lines; std::string paragraph; std::vector<std::string> temp; while (text.find ("@") != std::string::npos) { temp.clear(); paragraph = text.substr(0, text.find ("@") + 1); temp = LineWrapParagraph(font, paragraph, width); for (unsigned int i=0;i<temp.size();i++) { if (temp[i] != "") { lines.push_back(temp[i]); } } text = text.substr(text.find ("@") + 1, text.length()); } return lines; } std::vector<std::string> LineWrapParagraph (cFont font, std::string paragraph, int width) { std::vector<std::string> words; // stores the words std::vector<std::string> lines; // stores the Formatted lines // constructing words vector int search; // search index for delimiters while (paragraph.find (" ") != std::string::npos || paragraph.find ("@") != std::string::npos) { // if found period but not space if (paragraph.find ("@") != std::string::npos && paragraph.find (" ") == std::string::npos) { // add word to words vector search = paragraph.find ("@"); words.push_back(paragraph.substr(0,search)); break; } // else a space is found // add words to word vector search = paragraph.find (" "); words.push_back(paragraph.substr(0, search)); paragraph = paragraph.substr(search + 1, paragraph.length()); }; // Formatting lines cTexture *line; // the current calculated line // progressive Formatted lines as strings std::string curr = "", prevCurr = ""; // iterate through registered words for (unsigned int i=0; i<words.size(); i++) { curr = curr + words[i] + " "; line = Engine->Text->Prerender(font, curr); // maximum width not reached if (line->dim.w < width) { // continue to next word prevCurr = curr; AssetMgr->RemoveLast<Texture>(); continue; } // maximum width reached. Commit to lines vector curr = words[i] + " "; lines.push_back(prevCurr); AssetMgr->RemoveLast<Texture>(); } lines.push_back(curr); // finished return lines; }
#pragma once #include <QWidget> namespace Ui { class StartOptionsPassword; } /** Dialog to ask for passphrases. Used for encryption only */ class StartOptionsPassword : public QWidget { Q_OBJECT public: explicit StartOptionsPassword(QWidget *parent = nullptr); ~StartOptionsPassword(); QString getPass(); QString getPassConf(); private: Ui::StartOptionsPassword *ui; };
// // FboPingPong.cpp // emptyExample // // Created by Andreas Müller on 12/08/2013. // // #include "FboPingPong.h" // ------------------------------------------------------------------------------------ // void FboPingPong::allocate( int _w, int _h, int _internalformat, ofColor _clearColor ) { ofFbo::Settings settings = ofFbo::Settings(); settings.width = _w; settings.height = _h; settings.useDepth = true; settings.internalformat = _internalformat; allocate( settings, _clearColor ); } // ------------------------------------------------------------------------------------ // void FboPingPong::allocate( ofFbo::Settings _settings, ofColor _clearColor ) { clearColor = _clearColor; fbo1.allocate( _settings); fbo2.allocate( _settings ); sourceBuffer = &fbo1; destBuffer = &fbo2; clearSource(); clearDest(); } // ------------------------------------------------------------------------------------ // void FboPingPong::draw( ofPoint _pos, float _width, bool _drawBack ) { float desWidth = _width; float desHeight = (source()->getWidth() / source()->getHeight()) * desWidth; source()->draw( _pos, desWidth, desHeight ); if( _drawBack ) { dest()->draw( _pos + ofVec2f(desWidth,0), desWidth, desHeight ); } } // ------------------------------------------------------------------------------------ // void FboPingPong::clearBoth() { clearSource(); clearDest(); } // ------------------------------------------------------------------------------------ // void FboPingPong::clearBoth( ofColor _clearColor ) { clearSource( _clearColor ); clearDest( _clearColor ); } // ------------------------------------------------------------------------------------ // void FboPingPong::clearSource() { clearSource( clearColor ); } // ------------------------------------------------------------------------------------ // void FboPingPong::clearDest() { clearDest( clearColor ); } // ------------------------------------------------------------------------------------ // void FboPingPong::clearSource( ofColor _clearColor ) { source()->begin(); ofClear( _clearColor ); source()->end(); } // ------------------------------------------------------------------------------------ // void FboPingPong::clearDest( ofColor _clearColor ) { dest()->begin(); ofClear( _clearColor ); dest()->end(); } // ------------------------------------------------------------------------------------ // void FboPingPong::setClearColor( ofColor _color ) { clearColor = _color; } // ------------------------------------------------------------------------------------ // void FboPingPong::swap() { std::swap(sourceBuffer, destBuffer); }
#include "LineOrientedVT100Client.h" #include <QFrame> #include <QPainter> class Pty; class QtTerminalWindow : public QFrame, public LineOrientedVT100Client { Q_OBJECT public: QtTerminalWindow(); void setPty(Pty* pty); protected: void paintEvent(QPaintEvent*); void setFont(QFont*); // LineOrientedVT100Client implementation virtual void keyPressEvent(QKeyEvent* event); virtual void resizeEvent(QResizeEvent* resizeEvent); virtual void characterAppended(); virtual void somethingLargeChanged(); virtual void bell(); virtual int charactersWide(); virtual int charactersTall(); virtual void renderTextAt(const char* text, size_t numberOfCharacters, bool isCursor, int x, int y); private: Pty* m_pty; char m_previousCharacter; QFontMetrics* m_fontMetrics; QFont* m_font; QSize m_size; QPainter* m_currentPainter; signals: void updateNeeded(); public slots: void handleUpdateNeeded(); };
#include "androidutils.h" #include <QtGlobal> #include <QQmlEngine> #include <QCoreApplication> #include <systemdispatcher.h> #ifdef Q_OS_ANDROID #include <QtAndroidExtras> #else #include <QDebug> #endif #include "filechooser.h" static void setupUtils(); static QObject *createQmlSingleton(QQmlEngine *qmlEngine, QJSEngine *jsEngine); Q_COREAPP_STARTUP_FUNCTION(setupUtils) AndroidUtils *AndroidUtils::_instance = nullptr; void AndroidUtils::javaThrow() { #ifdef Q_OS_ANDROID QAndroidJniEnvironment env; if (env->ExceptionCheck()) { auto exception = QAndroidJniObject::fromLocalRef(env->ExceptionOccurred()); JavaException exc; exc._what = exception.callObjectMethod("getLocalizedMessage", "()Ljava/lang/String;").toString().toUtf8(); QAndroidJniObject stringWriter("java/io/StringWriter"); QAndroidJniObject printWriter("java/io/PrintWriter", "(Ljava/lang/Writer;)V", stringWriter.object()); exception.callMethod<void>("printStackTrace", "(Ljava/lang/PrintWriter;)V", printWriter.object()); exc._stackTrace = stringWriter.callObjectMethod("toString", "()Ljava/lang/String;").toString().toUtf8(); env->ExceptionClear(); throw exc; } #endif } AndroidUtils::AndroidUtils(QObject *parent) : QObject(parent) {} AndroidUtils *AndroidUtils::instance() { if(!_instance) _instance = new AndroidUtils(qApp); return _instance; } void AndroidUtils::setStatusBarColor(const QColor &color) { #ifdef Q_OS_ANDROID AndroidNative::SystemDispatcher::instance()->dispatch("AndroidUtils.setStatusBarColor", { {"color", color.name()} }); #else Q_UNUSED(color); #endif } void AndroidUtils::showToast(const QString &message, bool showLong) { #ifdef Q_OS_ANDROID AndroidNative::SystemDispatcher::instance()->dispatch("androidnative.Toast.showToast", { {"text", message}, {"longLength", showLong} }); #else Q_UNUSED(showLong) qInfo() << message; #endif } void AndroidUtils::hapticFeedback(HapticFeedbackConstant constant) { #ifdef Q_OS_ANDROID AndroidNative::SystemDispatcher::instance()->dispatch("AndroidUtils.hapticFeedback", { {"feedbackConstant", (int)constant} }); #else Q_UNUSED(constant); #endif } static void setupUtils() { AndroidNative::SystemDispatcher::instance()->loadClass("androidnative.Toast"); AndroidNative::SystemDispatcher::instance()->loadClass("de.skycoder42.androidutils.AndroidUtils"); qmlRegisterSingletonType<AndroidUtils>("de.skycoder42.androidutils", 1, 1, "AndroidUtils", createQmlSingleton); qmlRegisterType<FileChooser>("de.skycoder42.androidutils", 1, 1, "FileChooser"); //qmlProtectModule("de.skycoder42.quickextras", 1); } static QObject *createQmlSingleton(QQmlEngine *qmlEngine, QJSEngine *jsEngine) { Q_UNUSED(qmlEngine) Q_UNUSED(jsEngine) return new AndroidUtils(qmlEngine); } JavaException::JavaException() : _what(), _stackTrace() {} const char *JavaException::what() const noexcept { return _what.constData(); } const QByteArray JavaException::printStackTrace() const noexcept { return _stackTrace; } void JavaException::raise() const { throw *this; } QException *JavaException::clone() const { auto e = new JavaException(); e->_what = _what; e->_stackTrace = _stackTrace; return e; }
/** \file ballDetector2.cpp \author UnBeatables \date LARC2018 \name ballDetector */ #include "ballDetector2.hpp" #include <string> #define RESIZE_FACTOR 0.5 void BallDetector2::run(cv::Mat imgTop, cv::Mat imgBot, PerceptionData* data) { //Time analyze int time_init, time_final, time_total_nsec, time_total_sec; struct timespec tp, tp1; clockid_t clk_id; clk_id = CLOCK_PROCESS_CPUTIME_ID; time_init = clock_gettime(clk_id, &tp); //******* Top Camera *******// if(data->isTopCamera == true){ cv::Mat top_HLS_green; //Color transformation cv::cvtColor(imgTop, top_HLS_green, cv::COLOR_BGR2HLS); //Color segmentation cv::inRange(top_HLS_green, cv::Scalar(iLowH, iLowL, iLowS), cv::Scalar(iHighH, iHighL, iHighS), top_HLS_green); //Noise reduction cv::Mat erodeTop_green, dilateTop_green; cv::Mat element, element2; element2 = cv::getStructuringElement( cv::MORPH_RECT, cv::Size(5,5), cv::Point(-1,-1)); if(kernel>0){ element = cv::getStructuringElement( cv::MORPH_RECT, cv::Size(kernel,kernel), cv::Point(-1,-1)); } cv::erode(top_HLS_green, erodeTop_green, element2, cv::Point(-1,-1),1, cv::BORDER_CONSTANT); cv::dilate(erodeTop_green, dilateTop_green, element, cv::Point(-1,-1),1, cv::BORDER_CONSTANT); //Blob detector cv::Mat topBallMask = dilateTop_green; cv::SimpleBlobDetector::Params params; params.minThreshold = topMinThreshold; params.maxThreshold = topMaxThreshold; params.filterByArea = topFilterByArea; params.minArea = topMinArea; params.filterByCircularity = topFilterByCircularity; params.minCircularity = topMinCircularity; params.filterByConvexity = topFilterByConvexity; params.minConvexity = topMinConvexity; params.filterByInertia = topFilterByInertia; params.minInertiaRatio = topMinInertiaRatio; cv::SimpleBlobDetector topDetector(params); std::vector<cv::KeyPoint> keypoints; topDetector.detect(topBallMask, keypoints); #ifdef DEBUG_PERCEPTION //cv::Mat im_with_keypoints; //cv::drawKeypoints(topBallMask, keypoints, im_with_keypoints, cv::Scalar(0,0,255), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); #endif //Gets field horizon int whiteCount = cv::countNonZero(dilateTop_green); float fieldpercentage = (float)whiteCount/(imgTop.rows*imgTop.cols); int y = fieldpercentage*imgTop.rows*factor; horizont = imgTop.rows-y; //If a blob is found, updates ball coordenate with blob center, else ball center = (-1,-1) cv::Point2f coordenate; float radius; if(keypoints.size()>0){ for(int i = 0; i<keypoints.size(); ++i){ //The ball center must be bellow horizon if(keypoints[i].pt.y > horizont){ coordenate.x = keypoints[i].pt.x; coordenate.y = keypoints[i].pt.y; this->bestCandidate.center = coordenate; break; } else{ this->bestCandidate.center.x = -1; this->bestCandidate.center.y = -1; } } } else{ this->bestCandidate.center.x = -1; this->bestCandidate.center.y = -1; } updateData(data); } //******** Bot Cameta *********// else{ cv::Mat bot_HLS_green, bot_HLS_black; //Color transformations cv::cvtColor(imgBot, bot_HLS_green, cv::COLOR_BGR2HLS); bot_HLS_black = bot_HLS_green.clone(); //Green and black mask cv::inRange(bot_HLS_green, cv::Scalar(iLowH3, iLowL3, iLowS3), cv::Scalar(iHighH3, iHighL3, iHighS3), bot_HLS_green); cv::inRange(bot_HLS_black, cv::Scalar(iLowH4, iLowL4, iLowS4), cv::Scalar(iHighH4, iHighL4, iHighS4), bot_HLS_black); //Noise reduction cv::Mat erodeBot_green, dilateBot_green, dilateBot_black; cv::Mat element, element2; element2 = cv::getStructuringElement( cv::MORPH_RECT, cv::Size(5,5), cv::Point(-1,-1)); if(kernel>0){ element = cv::getStructuringElement( cv::MORPH_RECT, cv::Size(kernel,kernel), cv::Point(-1,-1)); } cv::erode(bot_HLS_green, erodeBot_green, element2, cv::Point(-1,-1),1, cv::BORDER_CONSTANT); cv::dilate(erodeBot_green, dilateBot_green, element, cv::Point(-1,-1),1, cv::BORDER_CONSTANT); cv::dilate(bot_HLS_black, dilateBot_black, element, cv::Point(-1,-1),1, cv::BORDER_CONSTANT); //Bitwise AND between NOTgreen and black cv::Mat botBallMask; cv::bitwise_not(dilateBot_green, botBallMask); cv::bitwise_and(botBallMask, dilateBot_black, botBallMask); cv::bitwise_not(botBallMask,botBallMask); //Blob detector cv::SimpleBlobDetector::Params params; params.minThreshold = botMinThreshold; params.maxThreshold = botMaxThreshold; params.filterByArea = botFilterByArea; params.minArea = botMinArea; params.filterByCircularity = botFilterByCircularity; params.minCircularity = botMinCircularity; params.filterByConvexity = botFilterByConvexity; params.minConvexity = botMinConvexity; params.filterByInertia = botFilterByInertia; params.minInertiaRatio = botMinInertiaRatio; cv::SimpleBlobDetector botDetector(params); std::vector<cv::KeyPoint> bot_keypoints; botDetector.detect(botBallMask, bot_keypoints); //The center os the blob is the averege between all blobs centers found cv::Point2f coordenate2; float radius2; coordenate2.x = 0; coordenate2.y = 0; for(int i = 0; i<bot_keypoints.size(); ++i){ std::cout<<bot_keypoints.size()<<std::endl; coordenate2.x = coordenate2.x + bot_keypoints[i].pt.x; coordenate2.y = coordenate2.y + bot_keypoints[i].pt.y; } //Updates ball center if(bot_keypoints.size()!=0){ coordenate2.x = coordenate2.x/bot_keypoints.size(); coordenate2.y = coordenate2.y/bot_keypoints.size(); this->bestCandidate.center = coordenate2; } else{ this->bestCandidate.center.x = -1; this->bestCandidate.center.y = -1; } updateData(data); } //Time analyze time_final = clock_gettime(clk_id, &tp1); time_total_sec = tp1.tv_sec - tp.tv_sec; time_total_nsec = abs(tp1.tv_nsec - tp.tv_nsec); } void BallDetector2::updateData(PerceptionData *data) { data->ballX = this->bestCandidate.center.x; data->ballY = this->bestCandidate.center.y; }
/* -*- 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 Cihat Imamoglu (cihati) */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/QuickSelectable.h" #include "modules/skin/OpSkinManager.h" QuickSelectable::~QuickSelectable() { RemoveOpWidgetListener(*this); } OP_STATUS QuickSelectable::Init() { RETURN_IF_ERROR(Base::Init()); RETURN_IF_ERROR(ConstructSelectableQuickWidget()); RETURN_IF_ERROR(AddOpWidgetListener(*this)); return OpStatus::OK; } void QuickSelectable::SetParentOpWidget(OpWidget* widget) { Base::SetParentOpWidget(widget); m_child->SetParentOpWidget(widget); } void QuickSelectable::SetChild(QuickWidget* new_child) { new_child->SetParentOpWidget(GetOpWidget()->GetParent()); m_child = new_child; m_child->SetEnabled(GetOpWidget()->GetValue()); BroadcastContentsChanged(); } void QuickSelectable::OnChange(OpWidget *widget, BOOL changed_by_mouse) { m_child->SetEnabled(widget->GetValue()); } OP_STATUS QuickSelectable::FindImageSizes(const char* widget_type) { INT32 dummy_height; RETURN_IF_ERROR(GetOpWidget()->GetSkinManager()->GetSize(widget_type, &m_image_width, &dummy_height)); INT32 top, left, bottom, right; if (OpStatus::IsSuccess(GetOpWidget()->GetSkinManager()->GetMargin(widget_type, &left, &top, &right, &bottom))) GetOpWidget()->SetMargins(left, top, right, bottom); return OpStatus::OK; } OP_STATUS QuickSelectable::Layout(const OpRect& rect) { // selectable_rect defines the area of QuickSelectable that can toggle/change // the state of it via mouse clicks. OpRect selectable_rect = rect; selectable_rect.height = Base::GetDefaultMinimumHeight(rect.width); GetOpWidget()->SetRect(selectable_rect, TRUE, FALSE); OpRect child_rect = rect; const int dx = GetHorizontalSpacing(); const int dy = selectable_rect.height + GetVerticalSpacing(); child_rect.x += dx; child_rect.width -= dx; child_rect.y += dy; child_rect.height -= dy; child_rect.width = min(unsigned(child_rect.width), m_child->GetPreferredWidth()), child_rect.height = min(unsigned(child_rect.height), m_child->GetPreferredHeight()); return m_child->Layout(child_rect, rect); } unsigned QuickSelectable::GetDefaultMinimumWidth() { return max(Base::GetDefaultMinimumWidth(), GetHorizontalSpacing() + m_child->GetMinimumWidth()); } unsigned QuickSelectable::GetDefaultMinimumHeight(unsigned width) { return Base::GetDefaultMinimumHeight(width) + GetVerticalSpacing() + m_child->GetMinimumHeight(width); } unsigned QuickSelectable::GetDefaultNominalWidth() { return max(Base::GetDefaultNominalWidth(), GetHorizontalSpacing() + m_child->GetNominalWidth()); } unsigned QuickSelectable::GetDefaultNominalHeight(unsigned width) { return Base::GetDefaultNominalHeight(width) + GetVerticalSpacing() + m_child->GetNominalHeight(width); } unsigned QuickSelectable::GetDefaultPreferredWidth() { // This check is to avoid overflow caused by WidgetSizes::Infinity and WidgetSizes::Fill if (m_child->GetPreferredWidth() > WidgetSizes::UseDefault) return m_child->GetPreferredWidth(); #ifdef QUICK_TOOLKIT_SELECTABLE_FILLS_BY_DEFAULT return WidgetSizes::Fill; #else return max(Base::GetDefaultPreferredWidth(), GetHorizontalSpacing() + m_child->GetPreferredWidth()); #endif } unsigned QuickSelectable::GetDefaultPreferredHeight(unsigned width) { // This check is to avoid overflow caused by WidgetSizes::Infinity and WidgetSizes::Fill if (m_child->GetPreferredHeight(width) > WidgetSizes::UseDefault) return m_child->GetPreferredHeight(width); return Base::GetDefaultPreferredHeight(width) + GetVerticalSpacing() + m_child->GetPreferredHeight(width); } void QuickSelectable::GetDefaultMargins(WidgetSizes::Margins& margins) { Base::GetDefaultMargins(margins); const WidgetSizes::Margins& child_margins = m_child->GetMargins(); margins.right = max(margins.right, child_margins.right); margins.bottom = max(margins.bottom, child_margins.bottom); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** ** Copyright (C) 1995-2012 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" #include "platforms/windows/WindowsComplexScript.h" #include "platforms/windows/WindowsVegaPrinterListener.h" #include "platforms/windows/user_fun.h" #include "platforms/windows/pi/GdiOpFont.h" #include "platforms/windows/pi/GdiOpFontManager.h" #include "modules/libvega/src/oppainter/vegaoppainter.h" #include "modules/svg/SVGManager.h" #include "modules/svg/svg_path.h" extern HTHEME g_window_theme_handle; // Default overhang for synthesized fonts which report 0 overhang. #define DEFAULT_OVERHANG 1.3 #define DTT_GLOWSIZE (1UL << 11) #define DTT_COMPOSITED (1UL << 13) // // class GdiOpFont // /*static*/ GdiOpFont *GdiOpFont::s_font_on_dc = 0; /*static*/ HDC GdiOpFont::s_fonthdc = 0; /*static*/ HBITMAP GdiOpFont::s_text_bitmap = NULL; /*static*/ HBITMAP GdiOpFont::s_old_text_bitmap = NULL; /*static*/ HDC GdiOpFont::s_text_bitmap_dc = NULL; /*static*/ UINT8* GdiOpFont::s_text_bitmap_data; /*static*/ LONG GdiOpFont::s_text_bitmap_width = 0; /*static*/ LONG GdiOpFont::s_text_bitmap_height = 0; GdiOpFont::GdiOpFont(GdiOpFontManager* font_manager, const uni_char *face, UINT32 size, UINT8 weight, BOOL italic, INT32 blur_radius) : vega_script_cache(NULL) ,m_font_manager(font_manager) ,m_blur_radius(blur_radius) { //Fix for bug DSK-235152. Force some chinese fonts to use a larger size (otherwise, they're unreadable) if (uni_strnicmp(face, UNI_L("SimSun"), 6) == 0 || uni_strnicmp(face, UNI_L("NSimSun"), 7) == 0 || uni_strnicmp(face, UNI_L("\x5B8B\x4F53"), 4) == 0 || uni_strnicmp(face, UNI_L("\x65B0\x5B8B\x4F53"), 6) == 0) if(size >= 9) // if size is less than 9 core is probably trying to paint a thumbnail! hack for DSK-250578 size = MAX(size, 12); m_status = OpStatus::OK; INT32 nHeight = size; INT nWeight=INT(weight*(1000.0/10.0)); #ifdef FONTCACHETEST FontCacheTest* current = OP_NEW(FontCacheTest, (face, size, weight, italic)); BOOL found = FALSE; FontCacheTest* font = (FontCacheTest*)fontcache.First(); while (font) { if (current->Equals(*font)) { found = TRUE; break; } font = (FontCacheTest*)font->Suc(); } if (found) { font->IncUseCount(); OP_DELETE(current); } else { current->Into(&fontcache); } #endif // FONTCACHETEST BOOL acid3_workaround = FALSE; if(!nHeight) { // workaround for CORE-16527 nHeight = -1; acid3_workaround = TRUE; } //Get some information.. (Ascent,descent,height...) TEXTMETRIC met; ZeroMemory(&met, sizeof(met)); for(int i=0; i<2; i++) { m_fnt = CreateFont( (int)-nHeight, // logical height of font 0, // logical average character width 0, // angle of escapement 0, // base-line orientation angle nWeight,italic,FALSE,FALSE, DEFAULT_CHARSET, // character set identifier OUT_DEFAULT_PRECIS , // output precision CLIP_DEFAULT_PRECIS , // clipping precision DEFAULT_QUALITY , // output quality FF_DONTCARE , // pitch and family face // address of typeface name string ); if(m_fnt == NULL) { m_status = OpStatus::ERR; return; } m_oldGdiObj = SelectObject(s_fonthdc, m_fnt); GetTextMetrics(s_fonthdc,&met); // hack for DSK-250578 // switch to a scalable font in case small size of bitmap font is required(which can't be fulfilled) if ( !(met.tmPitchAndFamily&TMPF_VECTOR) && met.tmHeight-met.tmInternalLeading > nHeight + 2 ) { SelectObject(s_fonthdc, (HFONT)GetStockObject(SYSTEM_FONT)); DeleteObject(m_fnt); m_fnt = NULL; face = GdiOpFontManager::GetLatinGenericFont(GENERIC_FONT_SERIF); } else break; } OP_NEW_DBG("CreateFont", "fonts"); OP_DBG((UNI_L("face: %s"), face)); s_font_on_dc = this; m_ascent = met.tmAscent; m_descent = met.tmDescent; if(acid3_workaround) { // workaround for CORE-16527 m_ascent = m_descent = 1; } m_overhang=met.tmOverhang; m_internal_leading=met.tmInternalLeading; m_italic=italic; m_smallcaps=FALSE; //fix m_weight=weight; m_ave_charwidth=met.tmAveCharWidth; m_vectorfont=(met.tmPitchAndFamily & TMPF_VECTOR) ? TRUE : FALSE; m_height = met.tmHeight; #ifdef VEGA_GDIFONT_SUPPORT m_max_advance = met.tmMaxCharWidth + m_overhang + 2; // 2 extra pixels for cleartype fringes // Metrics for some fonts like Lucida Grande does not reflect the extra char width // when it is synthesized, so multiply it by a factor, to make sure we draw it all. if (m_italic && m_overhang == 0) m_max_advance *= DEFAULT_OVERHANG; #endif // VEGA_GDIFONT_SUPPORT //Init the widthcache... /*if(s1.cx==s2.cx) InitCache(s1.cx); //Monospace, the width is s1.cx else InitCache(0); //Not monospace, run GetWidths*/ #ifdef VEGA_GDIFONT_SUPPORT BITMAPINFO bi; bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biWidth = m_max_advance; bi.bmiHeader.biHeight = -(int)m_height; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biSizeImage = 0; bi.bmiHeader.biXPelsPerMeter = 0; bi.bmiHeader.biYPelsPerMeter = 0; bi.bmiHeader.biClrUsed = 0; bi.bmiHeader.biClrImportant = 0; m_bmp = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**)&m_bmp_data, NULL, 0); if (!m_bmp) { m_status = OpStatus::ERR_NO_MEMORY; return; } HBITMAP hOldBitmap = (HBITMAP)SelectObject(s_fonthdc, m_bmp); SetBkMode(s_fonthdc, TRANSPARENT); SelectObject(s_fonthdc, hOldBitmap); m_status = VEGAFont::Construct(); #endif // VEGA_GDIFONT_SUPPORT } GdiOpFont::~GdiOpFont() { // SelectObject(s_fonthdc, m_oldGdiObj); //restore to old if (s_font_on_dc == this) { // Select a systemfont to the font_hdc, otherwise, the font won't be deleted SelectObject(s_fonthdc, (HFONT)GetStockObject(SYSTEM_FONT)); s_font_on_dc = NULL; } if(m_fnt) DeleteObject(m_fnt); #ifdef VEGA_GDIFONT_SUPPORT if (m_bmp) DeleteObject(m_bmp); #endif // VEGA_GDIFONT_SUPPORT ScriptFreeCache(&vega_script_cache); } UINT32 GdiOpFont::StringWidth(const uni_char *str, UINT32 len, OpPainter* painter, INT32 extra_char_spacing) { #ifdef VEGA_PRINTER_LISTENER_SUPPORT BOOL printer = painter?(((VEGAOpPainter*)painter)->getPrinterListener()!=NULL):FALSE; HFONT oldfnt = NULL; HDC bkup_fonthdc = NULL; GdiOpFont* bkup_font_on_dc = NULL; if (printer) { bkup_font_on_dc = s_font_on_dc; bkup_fonthdc = s_fonthdc; s_font_on_dc = this; s_fonthdc = ((WindowsVegaPrinterListener*)((VEGAOpPainter*)painter)->getPrinterListener())->getHDC(); oldfnt = (HFONT)SelectObject(s_fonthdc, m_fnt); } #endif // !VEGA_PRINTER_LISTENER_SUPPORT if (s_font_on_dc != this) { m_oldGdiObj = SelectObject(s_fonthdc, m_fnt); s_font_on_dc = this; } if (extra_char_spacing != 0) SetTextCharacterExtra(s_fonthdc, extra_char_spacing); SIZE s = {0, 0}; #ifdef SUPPORT_TEXT_DIRECTION WIN32ComplexScriptSupport::GetTextExtent(s_fonthdc, str, len, &s, extra_char_spacing); #else GetTextExtentPoint32(s_fonthdc, str, len, &s); #endif if (extra_char_spacing != 0) SetTextCharacterExtra(s_fonthdc, 0); #ifdef VEGA_PRINTER_LISTENER_SUPPORT if (printer) { SelectObject(s_fonthdc, oldfnt); s_fonthdc = bkup_fonthdc; s_font_on_dc = bkup_font_on_dc; } #endif // !VEGA_PRINTER_LISTENER_SUPPORT return s.cx; } # ifdef VEGA_GDIFONT_SUPPORT #pragma comment (lib, "usp10.lib") #ifdef MDF_CAP_PROCESSEDSTRING #include "modules/mdefont/processedstring.h" SCRIPT_ANALYSIS vega_script_analysis; OP_STATUS GdiOpFont::ProcessString(struct ProcessedString* processed_string, const uni_char* str, const size_t len, INT32 extra_char_spacing, short, bool use_glyph_indices) { SCRIPT_ITEM items[1024]; SCRIPT_CONTROL control; SCRIPT_STATE state; op_memset(&control, 0, sizeof(control)); op_memset(&state, 0, sizeof(state)); int num_items; HRESULT error = ScriptItemize(str, len, 1024, &control, &state, items, &num_items); if (FAILED(error)) return (error == E_OUTOFMEMORY) ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR; WORD glyphs[10*1024]; WORD logclust[10*1024]; SCRIPT_VISATTR visattr[10*1024]; int num_glyphs = 0; int total_glyphs = 0; GOFFSET goffsets[10*1024]; int advance[10*1024]; // Don't select font into dc unless necessary BOOL use_dc = FALSE; for (int i = 0; i < num_items; ++i) { int item_len = items[i+1].iCharPos - items[i].iCharPos; const uni_char* str_pos = str + items[i].iCharPos; error = ScriptShape(use_dc ? s_fonthdc : NULL, &vega_script_cache, str_pos, item_len, 10*1024, &items[i].a, &glyphs[total_glyphs], &logclust[total_glyphs], &visattr[total_glyphs], &num_glyphs); if (error == E_PENDING) { if (s_font_on_dc != this) { SelectObject(s_fonthdc, m_fnt); s_font_on_dc = this; } use_dc = TRUE; error = ScriptShape(s_fonthdc, &vega_script_cache, str_pos, item_len, 10*1024, &items[i].a, &glyphs[total_glyphs], &logclust[total_glyphs], &visattr[total_glyphs], &num_glyphs); } if (FAILED(error)) return (error == E_OUTOFMEMORY) ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR; error = ScriptPlace(use_dc ? s_fonthdc : NULL, &vega_script_cache, &glyphs[total_glyphs], num_glyphs, &visattr[total_glyphs], &items[i].a, &advance[total_glyphs], &goffsets[total_glyphs], NULL); if (error == E_PENDING) { if (s_font_on_dc != this) { SelectObject(s_fonthdc, m_fnt); s_font_on_dc = this; } use_dc = TRUE; error = ScriptPlace(s_fonthdc, &vega_script_cache, &glyphs[total_glyphs], num_glyphs, &visattr[total_glyphs], &items[i].a, &advance[total_glyphs], &goffsets[total_glyphs], NULL); } if (FAILED(error)) return (error == E_OUTOFMEMORY) ? OpStatus::ERR_NO_MEMORY : OpStatus::ERR; total_glyphs += num_glyphs; } ProcessedGlyph* glyph_buffer = m_font_manager->GetGlyphBuffer(total_glyphs); if (!glyph_buffer) return OpStatus::ERR; processed_string->m_length = total_glyphs; processed_string->m_is_glyph_indices = TRUE; processed_string->m_top_left_positioned = FALSE; processed_string->m_advance = 0; processed_string->m_processed_glyphs = glyph_buffer; for (int i = 0; i < total_glyphs; ++i) { processed_string->m_processed_glyphs[i].m_pos = OpPoint(processed_string->m_advance+goffsets[i].du, goffsets[i].dv); processed_string->m_advance += advance[i] + extra_char_spacing; processed_string->m_processed_glyphs[i].m_id = glyphs[i]; } return OpStatus::OK; } #endif // MDF_CAP_PROCESSEDSTRING BOOL GdiOpFont::StringWidth(const uni_char* str, UINT32 len, INT32 extra_char_space, UINT32* strlen) { // Only used for native rendering OP_ASSERT(FALSE); *strlen = 0; if (s_font_on_dc != this) { SelectObject(s_fonthdc, m_fnt); s_font_on_dc = this; } SIZE s = {0, 0}; GetTextExtentPoint32(s_fonthdc, str, len, &s); *strlen = s.cx; return TRUE; } OP_STATUS GdiOpFont::loadGlyph(VEGAGlyph& glyph, UINT8* _data, unsigned int stride, BOOL isIndex, BOOL blackOnWhite) { UINT8* data; glyph.left = -1; // 1 pixel reserved for cleartype fringe glyph.top = m_ascent; glyph.width = m_max_advance; glyph.height = m_height; if (_data) // rasterize glyph into buffer provided in data { data = _data; glyph.m_handle = NULL; } else { #ifdef VEGA_SUBPIXEL_FONT_BLENDING data = OP_NEWA(UINT8, glyph.width*glyph.height*4); #else data = OP_NEWA(UINT8, glyph.width*glyph.height); #endif if (!data) return OpStatus::ERR_NO_MEMORY; glyph.m_handle = data; stride = glyph.width; } if (s_font_on_dc != this) { SelectObject(s_fonthdc, m_fnt); s_font_on_dc = this; } #ifndef MDF_CAP_PROCESSEDSTRING SIZE s = {0, 0}; uni_char glyphcode = glyph.glyph; GetTextExtentPoint32(s_fonthdc, &glyphcode, 1, &s); glyph.advance = s.cx; #endif // !MDF_CAP_PROCESSEDSTRING HBITMAP hOldBitmap = (HBITMAP)SelectObject(s_fonthdc, m_bmp); RECT r = {0,0,glyph.width, glyph.height}; if (blackOnWhite) { FillRect(s_fonthdc, &r, (HBRUSH)GetStockObject(WHITE_BRUSH)); SetTextColor(s_fonthdc, RGB(0,0,0)); } else { FillRect(s_fonthdc, &r, (HBRUSH)GetStockObject(BLACK_BRUSH)); SetTextColor(s_fonthdc, RGB(255,255,255)); } #ifdef MDF_CAP_PROCESSEDSTRING int adv = 0; GOFFSET gof; gof.du = 0; gof.dv = 0; WORD codepoint = glyph.glyph; ScriptTextOut(s_fonthdc, &vega_script_cache, -glyph.left, 0, 0, NULL, &vega_script_analysis, NULL, 0, &codepoint, 1, &adv, NULL, &gof); glyph.top = 0; #else // !MDF_CAP_PROCESSEDSTRING TextOut(s_fonthdc, -glyph.left, 0, &glyphcode, 1); #endif // !MDF_CAP_PROCESSEDSTRING for (int yp = 0; yp < glyph.height; ++yp) { for (int xp = 0; xp < glyph.width; ++xp) { UINT8 r,g,b; if (blackOnWhite) { r = 255-((m_bmp_data[yp*m_max_advance+xp]&0xff0000)>>16); g = 255-((m_bmp_data[yp*m_max_advance+xp]&0xff00)>>8); b = 255-((m_bmp_data[yp*m_max_advance+xp]&0xff)); } else { r = ((m_bmp_data[yp*m_max_advance+xp]&0xff0000)>>16); g = ((m_bmp_data[yp*m_max_advance+xp]&0xff00)>>8); b = ((m_bmp_data[yp*m_max_advance+xp]&0xff)); } #ifdef VEGA_SUBPIXEL_FONT_BLENDING data[yp*stride+xp*4] = b; data[yp*stride+xp*4+1] = g; data[yp*stride+xp*4+2] = r; data[yp*stride+xp*4+3] = (b+g+r)/3; #else data[yp*stride+xp] = (b+g+r)/3; #endif } } SelectObject(s_fonthdc, hOldBitmap); return OpStatus::OK; } void GdiOpFont::unloadGlyph(VEGAGlyph& glyph) { OP_DELETEA(((UINT8*)glyph.m_handle)); } void GdiOpFont::getGlyphBuffer(VEGAGlyph& glyph, const UINT8*& buffer, unsigned int& stride) { buffer = (UINT8*)glyph.m_handle; stride = glyph.width; } # endif #include "platforms/windows/pi/WindowsOpWindow.h" BOOL GdiOpFont::nativeRendering() { return g_vegaGlobals.rasterBackend != LibvegaModule::BACKEND_HW3D; } BOOL GdiOpFont::DrawString(const OpPoint &pos, const uni_char* str, UINT32 len, INT32 extra_char_spacing, short adjust, const OpRect& clip, UINT32 color, VEGAWindow* dest) { WindowsVegaWindow* dest_window = static_cast<WindowsVegaWindow*>(dest); if ((color>>24) != 255 || !dest_window->GetBitmapDC()) return FALSE; OpRect dest_rect(0,0,dest_window->getWidth(), dest_window->getHeight()); int trans_top, trans_bottom, trans_left, trans_right; dest_window->getTransparentMargins(trans_top, trans_bottom, trans_left, trans_right); trans_right = dest_rect.width - trans_right; trans_bottom = dest_rect.height - trans_bottom; BOOL restore_alpha = FALSE; unsigned int strw = 0; BOOL in_glass = pos.x < trans_left || pos.x > trans_right || pos.y < trans_top || pos.y > trans_bottom; if (in_glass || dest_window->GetIsLayered()) { restore_alpha = TRUE; strw = StringWidth(str, len, NULL, extra_char_spacing); OpRect rect(pos.x, pos.y, strw, m_height); // Clip rect.IntersectWith(clip); rect.IntersectWith(dest_rect); if (rect.width == 0 || rect.height == 0) return TRUE; UINT32 sample1, sample2, sample3; VEGAPixelStore* ps = dest_window->getPixelStore(); sample1 = ((UINT32*)ps->buffer)[(ps->stride/4)*rect.y+rect.x]; sample2 = ((UINT32*)ps->buffer)[(ps->stride/4)*(rect.y+rect.height/2)+rect.x+rect.width/2]; sample3 = ((UINT32*)ps->buffer)[(ps->stride/4)*(rect.y+rect.height-1)+rect.x+rect.width-1]; if ((sample2>>24) == 0 && in_glass) { dest_window->ChangeDCFont(m_fnt, color); HDC hdc = dest_window->GetBitmapDC(); if (extra_char_spacing != 0) SetTextCharacterExtra(hdc, extra_char_spacing); IntersectClipRect(hdc, clip.x, clip.y, clip.x + clip.width, clip.y + clip.height); DTTOPTS dto = { sizeof(DTTOPTS) }; const UINT uFormat = DT_SINGLELINE|DT_CENTER|DT_VCENTER|DT_NOPREFIX; RECT r; r.top = pos.y; r.left = pos.x; r.bottom = pos.y+m_height; r.right = pos.x+strw; dto.dwFlags = DTT_COMPOSITED|DTT_GLOWSIZE; dto.iGlowSize = 10; HRESULT hr = S_OK; if (!g_window_theme_handle) g_window_theme_handle = OpenThemeData(g_main_hwnd, UNI_L("window")); if (g_window_theme_handle) hr = OPDrawThemeTextEx(g_window_theme_handle, hdc, 0, 0, str, len, uFormat, &r, &dto); SelectClipRgn(hdc, NULL); if (extra_char_spacing != 0) SetTextCharacterExtra(hdc, 0); if (g_window_theme_handle && SUCCEEDED(hr)) return TRUE; else return FALSE; } else if ((sample1>>24) != 255 || (sample2>>24) != 255 || (sample3>>24) != 255) return FALSE; } dest_window->ChangeDCFont(m_fnt, color); HDC hdc = dest_window->GetBitmapDC(); if (extra_char_spacing != 0) SetTextCharacterExtra(hdc, extra_char_spacing); IntersectClipRect(hdc, clip.x, clip.y, clip.x + clip.width, clip.y + clip.height); #ifdef SUPPORT_TEXT_DIRECTION WIN32ComplexScriptSupport::TextOut(hdc, pos.x, pos.y, str, len); #else TextOut(hdc, pos.x, pos.y, str, len); #endif if (restore_alpha) { if (!strw) strw = StringWidth(str, len, NULL, extra_char_spacing); OpRect rect(pos.x, pos.y, strw, m_height); // Cleartype can touch 2 pixels to the left of the starting position, so we have to include those. rect.x -= 2; rect.width += 3; // Also need 1 extra pixel to the right // Clip rect.IntersectWith(clip); rect.IntersectWith(dest_rect); VEGAPixelStore* ps = dest->getPixelStore(); for (int yp = rect.y; yp < rect.Bottom(); ++yp) { UINT32* data = ((UINT32*)ps->buffer)+yp*ps->width; for (int xp = rect.x; xp < rect.Right(); ++xp) { data[xp] |= (255<<24); } } } SelectClipRgn(hdc, NULL); if (extra_char_spacing != 0) SetTextCharacterExtra(hdc, 0); return TRUE; } BOOL GdiOpFont::DrawString(const OpPoint &pos, const uni_char* str, UINT32 len, INT32 extra_char_spacing, short adjust, const OpRect& clip, UINT32 color, VEGASWBuffer* dest) { return FALSE; } BOOL GdiOpFont::DrawString(const OpPoint &pos, const uni_char* str, UINT32 len, INT32 extra_char_spacing, short adjust, const OpRect& clip, UINT32 color, VEGA3dRenderTarget* dest, bool isWindow) { OP_ASSERT(FALSE); return FALSE; } BOOL GdiOpFont::GetAlphaMask(const uni_char* str, UINT32 len, INT32 extra_char_spacing, short adjust, const OpRect& clip, const UINT8** mask, OpPoint* size, unsigned int* rowStride, unsigned int* pixelStride) { if (s_font_on_dc != this) { m_oldGdiObj = SelectObject(s_fonthdc, m_fnt); s_font_on_dc = this; } if (extra_char_spacing != 0) SetTextCharacterExtra(s_fonthdc, extra_char_spacing); SIZE s = {0, 0}; #ifdef SUPPORT_TEXT_DIRECTION WIN32ComplexScriptSupport::GetTextExtent(s_fonthdc, str, len, &s, extra_char_spacing); #else GetTextExtentPoint32(s_fonthdc, str, len, &s); #endif if (extra_char_spacing != 0) SetTextCharacterExtra(s_fonthdc, 0); OpRect dst(0,0,s.cx, s.cy); dst.IntersectWith(clip); if (dst.IsEmpty()) { size->x = 0; size->y = 0; return TRUE; } if (!s_text_bitmap || s_text_bitmap_width < s.cx || s_text_bitmap_height < s.cy) { if (s_text_bitmap_dc) { SelectObject(s_text_bitmap_dc, s_old_text_bitmap); DeleteDC(s_text_bitmap_dc); } s_text_bitmap_dc = NULL; if (s_text_bitmap) DeleteObject(s_text_bitmap); s_text_bitmap = NULL; BITMAPINFO bi; bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biWidth = s.cx; bi.bmiHeader.biHeight = -(int)s.cy; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biSizeImage = 0; bi.bmiHeader.biXPelsPerMeter = 0; bi.bmiHeader.biYPelsPerMeter = 0; bi.bmiHeader.biClrUsed = 0; bi.bmiHeader.biClrImportant = 0; s_text_bitmap = CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (void**)&s_text_bitmap_data, NULL, 0); if (!s_text_bitmap) return FALSE; s_text_bitmap_dc = CreateCompatibleDC(s_fonthdc); if (!s_text_bitmap_dc) return FALSE; s_old_text_bitmap = (HBITMAP)SelectObject(s_text_bitmap_dc, s_text_bitmap); s_text_bitmap_width = s.cx; s_text_bitmap_height = s.cy; SetBkMode(s_text_bitmap_dc, TRANSPARENT); //SetTextColor(s_text_bitmap_dc, RGB(255,255,255)); SetTextColor(s_text_bitmap_dc, 0); } IntersectClipRect(s_text_bitmap_dc, clip.x, clip.y, clip.x + clip.width, clip.y + clip.height); RECT tmprect = { 0, 0, s.cx, s.cy }; //::FillRect(s_text_bitmap_dc, &tmprect, (HBRUSH) GetStockObject(BLACK_BRUSH)); ::FillRect(s_text_bitmap_dc, &tmprect, (HBRUSH) GetStockObject(WHITE_BRUSH)); HFONT old_font = (HFONT) SelectObject(s_text_bitmap_dc, m_fnt); SetTextCharacterExtra(s_text_bitmap_dc, extra_char_spacing); WIN32ComplexScriptSupport::TextOut(s_text_bitmap_dc, 0, 0, str, len); SelectClipRgn(s_text_bitmap_dc, NULL); SelectObject(s_text_bitmap_dc, old_font); *mask = s_text_bitmap_data+1; size->x = s.cx; size->y = s.cy; *rowStride = s_text_bitmap_width*4; *pixelStride = 4; // DSK-281697: Text now rendered black on white, so invert the mask UINT8* line = (UINT8*)*mask; for (int y = 0; y < size->y; ++y) { UINT8* pix = line; for (int x = 0; x < size->x*4; x+=4) { *pix = 255 - *pix; pix+=4; } line += *rowStride; } return TRUE; } #ifndef VEGA_GDIFONT_SUPPORT void GdiOpFont::GetWidths(UINT32 from, UINT32 to, INT *cached_widths) { GetCharWidth(s_fonthdc, from, to, cached_widths); } #endif // VEGA_GDIFONT_SUPPORT #ifdef SVG_SUPPORT double fixed_to_double(FIXED in) { return (double)in.value + (double)in.fract/USHRT_MAX; } OP_STATUS GdiOpFont::GetOutline(const uni_char* in_str, UINT32 in_len, UINT32& io_str_pos, UINT32 in_last_str_pos, BOOL in_writing_direction_horizontal, SVGNumber& out_advance, SVGPath** out_glyph) { // If NULL this is a test to see if GetOutline is supported if (!out_glyph) return OpStatus::OK; if (io_str_pos >= in_len) return OpStatus::ERR_OUT_OF_RANGE; if (s_font_on_dc != this) { SelectObject(s_fonthdc, m_fnt); s_font_on_dc = this; } GLYPHMETRICS metrics; MAT2 matrix; memset(&matrix, 0, sizeof(matrix)); // glyphs are upside down, which is what svg expects, so set the matrix to identity matrix.eM11.value = 1; matrix.eM22.value = 1; uni_char outl_char = in_str[io_str_pos]; DWORD buffer_size = ::GetGlyphOutline(s_fonthdc, outl_char, GGO_NATIVE, &metrics, 0, 0, &matrix); if (buffer_size == GDI_ERROR) return OpStatus::ERR; BYTE *buffer = OP_NEWA(BYTE, buffer_size); if (!buffer) return OpStatus::ERR_NO_MEMORY; OpAutoArray<BYTE> buffer_ap(buffer); DWORD err = ::GetGlyphOutline(s_fonthdc, outl_char, GGO_NATIVE, &metrics, buffer_size, buffer, &matrix); if (err == GDI_ERROR) return OpStatus::ERR; SVGPath* pathTmp; RETURN_IF_ERROR(g_svg_manager->CreatePath(&pathTmp)); OpAutoPtr<SVGPath> path(pathTmp); BYTE *buf_end = buffer + buffer_size; while (buffer < buf_end) { TTPOLYGONHEADER* ph = (TTPOLYGONHEADER*)buffer; RETURN_IF_ERROR(path->MoveTo(fixed_to_double(ph->pfxStart.x), fixed_to_double(ph->pfxStart.y), FALSE)); BYTE *curves_pos = buffer + sizeof(TTPOLYGONHEADER); BYTE *curves_end = buffer + ph->cb; while(curves_pos < curves_end) { TTPOLYCURVE* pc = (TTPOLYCURVE*)curves_pos; if (pc->wType == TT_PRIM_LINE) { // straight line for(int i = 0; i < pc->cpfx; i++) { RETURN_IF_ERROR(path->LineTo(fixed_to_double(pc->apfx[i].x), fixed_to_double(pc->apfx[i].y), FALSE)); } } else if (pc->wType == TT_PRIM_QSPLINE) { // quadratic spline for(int i = 0; i < pc->cpfx-1; i++) { POINTFX* b = &pc->apfx[i]; POINTFX* c = &pc->apfx[i+1]; SVGNumber epx; SVGNumber epy; if (i < pc->cpfx - 2) { epx = (fixed_to_double(b->x) + fixed_to_double(c->x)) / 2; epy = (fixed_to_double(b->y) + fixed_to_double(c->y)) / 2; } else { epx = fixed_to_double(c->x); epy = fixed_to_double(c->y); } RETURN_IF_ERROR(path->QuadraticCurveTo(fixed_to_double(b->x), fixed_to_double(b->y), epx, epy, FALSE, FALSE)); } } else if (pc->wType == TT_PRIM_CSPLINE) { // cubic spline for(int i = 0; i < pc->cpfx-2; i++) { POINTFX* cp1 = &pc->apfx[i]; POINTFX* cp2 = &pc->apfx[i+1]; POINTFX* endp = &pc->apfx[i+2]; RETURN_IF_ERROR(path->CubicCurveTo(fixed_to_double(cp1->x), fixed_to_double(cp1->y), fixed_to_double(cp2->x), fixed_to_double(cp2->y), fixed_to_double(endp->x), fixed_to_double(endp->y), FALSE, FALSE)); } } curves_pos += 2 * sizeof(WORD) + sizeof(POINTFX) * pc->cpfx; } RETURN_IF_ERROR(path->Close()); buffer = curves_end; } *out_glyph = path.release(); if (in_writing_direction_horizontal) { out_advance = metrics.gmCellIncX; } else { // Use Ascent()+Descent() as fallback since most fonts // have no y advance. Actually, the advance.y value might // be completely wrong anyway since it's probably based on // writing horizontally. if (metrics.gmCellIncY != 0) { out_advance = metrics.gmCellIncY; } else if (metrics.gmCellIncX > 0) { out_advance = Ascent() + Descent(); } } io_str_pos++; return OpStatus::OK; } #endif // SVG_SUPPORT
#include<stdio.h> int a=1; main() { while(a!=4) { printf("IOI\n\n"); a++; } }
#include <iostream> #include <mpi.h> #include <vector> using namespace std; void sum_cascade(int rank, int processes, const vector<int>& v) { auto leftChild = 2*rank + 1; auto rightChild = 2*rank + 2; if (rank == 0) { auto vecPointer = v.data(); auto leftSize = v.size() / 2; auto rightSize = v.size() - leftSize; auto start_time = MPI_Wtime(); MPI_Send(vecPointer, leftSize, MPI_INT, leftChild, 0, MPI_COMM_WORLD); MPI_Send(vecPointer + leftSize, rightSize, MPI_INT, rightChild, 0, MPI_COMM_WORLD); int sumL, sumR; MPI_Recv(&sumL, 1, MPI_INT, leftChild, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&sumR, 1, MPI_INT, rightChild, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); int res = sumL + sumR; cout << "CASCADE - time: " << MPI_Wtime() - start_time << "| size: " << v.size() << "| result: " << res << endl; } else { MPI_Status status; MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int count; MPI_Get_count(&status, MPI_INT, &count); auto arr = new int[count]; MPI_Recv(arr, count, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); auto leftSize = count / 2; auto rightSize = count - leftSize; auto hasLeftChild = leftChild < processes; auto hasRightChild = rightChild < processes; int sumL = 0, sumR = 0; if (hasLeftChild) { MPI_Send(arr, leftSize, MPI_INT, leftChild, 0, MPI_COMM_WORLD); MPI_Recv(&sumL, 1, MPI_INT, leftChild, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } else { for (int i = 0; i < leftSize; i++) { sumL += arr[i]; } } if (hasRightChild) { MPI_Send(arr+ leftSize, rightSize, MPI_INT, rightChild, 0, MPI_COMM_WORLD); MPI_Recv(&sumR, 1, MPI_INT, rightChild, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } else { for (int i = leftSize; i < count; i++) { sumR += arr[i]; } } auto sum = sumL + sumR; MPI_Send(&sum, 1, MPI_INT, status.MPI_SOURCE, 0, MPI_COMM_WORLD); delete[] arr; } } void sum_reduce(int rank, int processes, const vector<int>& v) { int size, res, sum = 0; if (rank == processes - 1) { size = v.size() - (processes - 1) * (v.size() / processes); } else { size = v.size() / processes; } for (int i = 0; i < size; i++) { sum += v[rank * (v.size() / processes) + i]; } double start_time = MPI_Wtime(); MPI_Reduce(&sum, &res, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) cout << "REDUCE - time: " << MPI_Wtime() - start_time << "| size: " << v.size() << "| result: " << res << endl; } int main(int argc, char **argv) { MPI_Init(&argc, &argv); int rank, processes; MPI_Comm_size(MPI_COMM_WORLD, &processes); MPI_Comm_rank(MPI_COMM_WORLD, &rank); int vector_size = 100000000; vector<int> v_casc(vector_size/processes, 1); vector<int> v(vector_size, 1); sum_reduce(rank, processes, v); sum_cascade(rank, processes, v_casc); MPI_Finalize(); }
#include <iostream> #include <armadillo> #include "Body.h" #include "Universe.h" using namespace arma; using namespace std; int main() { Universe mysystem; // Body body1(1, 0,0,0, 0,-0.1,0 ); // Body body2(1, 5,0,0, 0, 0.1,0 ); Body Sun(1,0,0,0,0,0,0); Body Mercury(1.2e-7, 0.39, 0, 0,0,9.96,0); Body Venus(2.4e-6, 0.72, 0, 0,0,7.36,0); Body Earth(1.5e-6,1,0,0, 0, 6.26, 0); Body Mars(3.3e-7, 1.52, 0, 0,0,5.06,0); Body Jupiter(9.5e-4, 5.20, 0,0,0,2.75,0); Body Saturn(2.75e-4, 9.54, 0, 0,0,2.04,0); Body Uranus(4.4e-5, 19.19, 0, 0,0,1.43,0); Body Neptune(5.1e-5, 30.06, 0, 0,0,1.14,0); Body Pluto(5.6e-9, 39.53, 0, 0,0,0.99,0); // mysystem.add_body(body1); // mysystem.add_body(body2); mysystem.add_body(Sun); mysystem.add_body(Mercury); mysystem.add_body(Venus); mysystem.add_body(Earth); mysystem.add_body(Mars); mysystem.add_body(Jupiter); mysystem.add_body(Saturn); mysystem.add_body(Uranus); mysystem.add_body(Neptune); mysystem.add_body(Pluto); int elements = mysystem.n_bodies; cout << "number of elements = " << elements<< endl; mysystem.solve_Verlet(0.001, 248); }
#pragma once #include "mapper.hpp" class Mapper1 : public Mapper { int writeN; uint8_t tmpReg; uint8_t regs[4]; void apply(); public: Mapper1(uint8_t* rom) : Mapper(rom) { regs[0] = 0x0C; writeN = tmpReg = regs[1] = regs[2] = regs[3] = 0; apply(); } uint8_t write(uint16_t addr, uint8_t v); uint8_t chr_write(uint16_t addr, uint8_t v); };
#include "Queue.h" int queue::pop() { list.del_front(); count--; return front(); } void queue::push(int value) { list.add_back(value); count++; } int queue::front() { return list.front(); } void queue::print() { list.DEBUG_TEMP_PRINT(); } bool queue::empty() { if (count == 0) { return true; } else { return false; } } void queue::clear() { list.clear(); count = 0; }
/*You have to complete this function*/ void recursion(char str[], string result, int i, int sz) { if (i == sz-1) { // base case at sz-1 because we don't want space after the last char of str result += str[i]; // append last char and then print cout << result << "$"; return; } result += str[i]; // the resulting string must always begin with the first char and not space recursion(str, result, i+1, sz); result += " "; recursion(str, result, i+1, sz); } void printSpace(char str[]) { // only gravity will pull me down // Print all possible strings int sz = 0; while(str[sz] != '\0') // donot use sizeof() to find the size of the array of char sz++; string res = ""; // prefer string over char[] recursion(str, res, 0, sz); }
#include "core/pch.h" #include <windows.h> #include <windowsx.h> #include <zmouse.h> #include "mde.h" #define MDE_SCREEN_W 800 #define MDE_SCREEN_H 600 void InitTest(MDE_Screen *screen); void ShutdownTest(); void PulseTest(MDE_Screen *screen); class TestWindow : public MDE_Screen { public: TestWindow(); ~TestWindow(); // == Inherit MDE_View ======================================== virtual void OnPaint(const MDE_RECT &rect, MDE_BUFFER *screen); // == Inherit MDE_Screen ====================================== virtual void OutOfMemory(); virtual MDE_FORMAT GetFormat(); virtual MDE_BUFFER *LockBuffer(); virtual void UnlockBuffer(MDE_Region *update_region); public: bool quit; unsigned int *data; MDE_BUFFER screen; HWND hwnd; WNDCLASS wc; BITMAPINFO bi; HDC bitmaphdc; HBITMAP hBitmap; }; VOID CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime) { TestWindow *win = (TestWindow *) GetWindowLong(hwnd, GWL_USERDATA); win->Validate(true); PulseTest(win); } static ShiftKeyState WParamToKeyMod(WPARAM wParam) { int keymod = SHIFTKEY_NONE; if ((GET_KEYSTATE_WPARAM(wParam) & MK_CONTROL) != 0) keymod |= SHIFTKEY_CTRL; if ((GET_KEYSTATE_WPARAM(wParam) & MK_SHIFT) != 0) keymod |= SHIFTKEY_SHIFT; return static_cast<ShiftKeyState>(keymod); } long FAR PASCAL WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { RECT r; TestWindow *win = (TestWindow *) GetWindowLong(hwnd, GWL_USERDATA); switch(message) { case WM_ERASEBKGND: break; case WM_KEYDOWN: if ((int) wParam != VK_ESCAPE) break; case WM_CLOSE: win->quit = true; break; case WM_PAINT: if (GetUpdateRect(hwnd, &r, false)) { win->Invalidate(MDE_MakeRect(r.left, r.top, r.right - r.left, r.bottom - r.top), true); ValidateRect(hwnd, &r); } break; case WM_LBUTTONDOWN: win->TrigMouseDown((short)LOWORD(lParam), (short)HIWORD(lParam), 1, 1, WParamToKeyMod(wparam)); SetCapture(hwnd); break; case WM_RBUTTONDOWN: win->TrigMouseDown((short)LOWORD(lParam), (short)HIWORD(lParam), 2, 1, WParamToKeyMod(wparam)); SetCapture(hwnd); break; case WM_MBUTTONDOWN: win->TrigMouseDown((short)LOWORD(lParam), (short)HIWORD(lParam), 3, 1, WParamToKeyMod(wparam)); SetCapture(hwnd); break; case WM_LBUTTONDBLCLK: win->TrigMouseDown((short)LOWORD(lParam), (short)HIWORD(lParam), 1, 2, WParamToKeyMod(wparam)); break; case WM_RBUTTONDBLCLK: win->TrigMouseDown((short)LOWORD(lParam), (short)HIWORD(lParam), 2, 2, WParamToKeyMod(wparam)); break; case WM_MBUTTONDBLCLK: win->TrigMouseDown((short)LOWORD(lParam), (short)HIWORD(lParam), 3, 2, WParamToKeyMod(wparam)); break; case WM_LBUTTONUP: win->TrigMouseUp((short)LOWORD(lParam), (short)HIWORD(lParam), 1, WParamToKeyMod(wparam)); ReleaseCapture(); break; case WM_RBUTTONUP: win->TrigMouseUp((short)LOWORD(lParam), (short)HIWORD(lParam), 2, WParamToKeyMod(wparam)); ReleaseCapture(); break; case WM_MBUTTONUP: win->TrigMouseUp((short)LOWORD(lParam), (short)HIWORD(lParam), 3, WParamToKeyMod(wparam)); ReleaseCapture(); break; case WM_MOUSEMOVE: win->TrigMouseMove((short)LOWORD(lParam), (short)HIWORD(lParam), WParamToKeyMod(wparam)); break; case WM_MOUSEWHEEL: win->TrigMouseWheel(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), ((short)HIWORD(wParam)), true, WParamToKeyMod(wparam)); break; default: return DefWindowProc(hwnd, message, wParam, lParam); } return FALSE; } TestWindow::TestWindow() { quit = false; Init(MDE_SCREEN_W, MDE_SCREEN_H); // ~~~~ Create bitmap ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ bitmaphdc = CreateCompatibleDC(NULL); bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biWidth = MDE_SCREEN_W; bi.bmiHeader.biHeight = -MDE_SCREEN_H; bi.bmiHeader.biPlanes = 1; bi.bmiHeader.biBitCount = 32; bi.bmiHeader.biCompression = BI_RGB; bi.bmiHeader.biSizeImage = MDE_SCREEN_W * MDE_SCREEN_H * 4; bi.bmiHeader.biXPelsPerMeter = 0; bi.bmiHeader.biYPelsPerMeter = 0; bi.bmiHeader.biClrUsed = 0; bi.bmiHeader.biClrImportant = 0; hBitmap = CreateDIBSection( bitmaphdc, &bi, DIB_RGB_COLORS, (void **)&data, NULL, 0 ); SelectObject(bitmaphdc, hBitmap); // ~~~~ Create window ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int x = 150, y = 100; RECT r = { x, y, x + MDE_SCREEN_W, y + MDE_SCREEN_H }; AdjustWindowRect(&r, WS_OVERLAPPEDWINDOW, false); wc.style = CS_OWNDC | CS_DBLCLKS; wc.lpfnWndProc = WindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = NULL; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszMenuName = "MDE Test"; wc.lpszClassName = "MDE Test"; RegisterClass(&wc); hwnd = CreateWindowEx(0, wc.lpszClassName, "MDE Test", WS_OVERLAPPEDWINDOW, r.left, r.top, r.right - r.left, r.bottom - r.top, NULL, NULL, NULL, NULL); SetWindowLong(hwnd, GWL_USERDATA, (long)this); ShowWindow(hwnd, SW_SHOWNORMAL); } TestWindow::~TestWindow() { DestroyWindow(hwnd); // Leak some stuff. (Let windows do its best to free it) } void TestWindow::OnPaint(const MDE_RECT &rect, MDE_BUFFER *screen) { MDE_SetColor(MDE_RGB(69, 81, 120), screen); MDE_DrawRectFill(rect, screen); } MDE_FORMAT TestWindow::GetFormat() { return MDE_FORMAT_BGRA32; } void TestWindow::OutOfMemory() { } MDE_BUFFER *TestWindow::LockBuffer() { MDE_InitializeBuffer(MDE_SCREEN_W, MDE_SCREEN_H, MDE_SCREEN_W * 4, MDE_FORMAT_BGRA32, data, NULL, &screen); return &screen; } void TestWindow::UnlockBuffer(MDE_Region *update_region) { HDC hdc = GetDC(hwnd); for(int i = 0; i < update_region->num_rects; i++) { MDE_ASSERT( update_region->rects[i].x >= 0 && update_region->rects[i].y >= 0 && update_region->rects[i].x + update_region->rects[i].w <= m_rect.w && update_region->rects[i].y + update_region->rects[i].h <= m_rect.h); BitBlt(hdc, update_region->rects[i].x, update_region->rects[i].y, update_region->rects[i].w, update_region->rects[i].h, bitmaphdc, update_region->rects[i].x, update_region->rects[i].y, SRCCOPY); } ReleaseDC(hwnd, hdc); } int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { TestWindow *window = new TestWindow(); InitTest(window); SetTimer(window->hwnd, (long)0, 10, TimerProc); MSG msg; while(GetMessage(&msg, 0, 0, 0) && !window->quit) { TranslateMessage(&msg); DispatchMessage(&msg); } ShutdownTest(); delete window; return 0; }
/* Given an undirected graph G(V, E) and two vertices v1 and v2 (as integers), check if there exists any path between them or not. Print true if the path exists and false otherwise. Note: 1. V is the number of vertices present in graph G and vertices are numbered from 0 to V-1. 2. E is the number of edges present in graph G. Input Format : The first line of input contains two integers, that denote the value of V and E. Each of the following E lines contains two integers, that denote that there exists an edge between vertex 'a' and 'b'. The following line contain two integers, that denote the value of v1 and v2. Output Format : The first and only line of output contains true, if there is a path between v1 and v2 and false otherwise. Constraints : 0 <= V <= 1000 0 <= E <= 1000 0 <= a <= V - 1 0 <= b <= V - 1 0 <= v1 <= V - 1 0 <= v2 <= V - 1 Time Limit: 1 second Sample Input 1 : 4 4 0 1 0 3 1 2 2 3 1 3 Sample Output 1 : true Sample Input 2 : 6 3 5 3 0 1 3 4 0 3 Sample Output 2 : false */ #include<bits/stdc++.h> using namespace std; bool hasPath(int **edges,int n,int s,int d,bool *visited){ queue<int> q; q.push(s); visited[s] = true; while(!q.empty()){ int currVertex = q.front(); q.pop(); for(int i=0;i<n;i++){ if(edges[currVertex][i] == 1 && !visited[i]){ q.push(i); visited[i] = true; } } } if(visited[d]){ return true; }else{ return false; } } int main(){ int n,e; cin >> n >> e; int **edges = new int*[n]; for(int i=0;i<n;i++){ edges[i] = new int[n]; } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ edges[i][j] = 0; } } for(int i=0;i<e;i++){ int f,s; cin >> f >> s; edges[f][s] = 1; edges[s][f] = 1; } int s,d; cin >> s >> d; bool *visited = new bool[n]; for(int i=0;i<n;i++){ visited[i] = false; } if(hasPath(edges,n,s,d,visited)){ cout << "true" << endl; }else{ cout << "false" << endl; } return 0; }
#include <iostream> #include <windows.h> #include <cstdlib> #include <time.h> using namespace std; //length of the array const int arrayLength = 45; int getRandomNumber(int min, int max) { static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0); return static_cast<int>(rand() * fraction * (max - min + 1) + min); } //gets a unique random number for every index in the array void getArray(int array[arrayLength]) { for(int count = 0; count <= arrayLength-1;) { int placeholder = getRandomNumber(1, arrayLength); bool passFail = true; int check = 0; //checks for duplicates for(; check <= arrayLength-1; ++check) { if(placeholder == array[check]) { passFail = false; break; } } if(passFail) { array[count] = placeholder; ++count; } } } int main() { srand(time(0)); int array[arrayLength] {0}; getArray(array); for(int iteration = 0; iteration < arrayLength-1; ++iteration) { //tracks whether a swap was performed bool swapCheck = false; for(int pos = 0; pos < (arrayLength-1)-iteration; ++pos) { if(array[pos] > array[pos+1]) { swapCheck = true; swap(array[pos], array[pos+1]); } for(int pos = 0; pos <= arrayLength-1; ++pos) { if(array[pos] < 10) cout << array[pos] << " "; else cout << array[pos] << " "; for(int count = array[pos]; count >= 1; --count) { cout << "|"; } cout << '\n'; } //Sleep(150); //uncomment for slower execution system("cls"); } //outputs the last iteration permanently if(swapCheck == false) { system("cls"); for(int pos = 0; pos <= arrayLength-1; ++pos) { if(array[pos] < 10) cout << array[pos] << " "; else cout << array[pos] << " "; for(int count = array[pos]; count >= 1; --count) { cout << "|"; } cout << '\n'; } cout << "early termination on iteration " << iteration << '\n'; iteration = arrayLength; } } }
/* Name: ���뷽���� Copyright: Author: Hill bamboo Date: 2019/8/15 16:58:59 Description: �����������ÿ����� */ #include <bits/stdc++.h> using namespace std; int dfs(string num, int s) { if (s >= num.size()) return 1; if (s == num.size() - 1) return ('1' <= num[s] && num[s] <= '9') ? 1 : 0; int ret = 0; if ('1' <= num[s] && num[s] <= '9') ret += dfs(num, s + 1); if (num[s] == '1' || (num[s] == '2' && num[s + 1] <= '6')) ret += dfs(num, s + 2); return ret; } int main() { string str; cin >> str; cout << dfs(str, 0) << endl; return 0; }
#include "Card.h" #include "Dealer.h" #include <vector> #include <stdlib.h> #include <iostream> #include <time.h> #define true 1 #define false 0 using namespace std; //***************************** Dealer Implimentation ********************************************************** Dealer::Dealer(double newBalance):User(newBalance){} // explicit constructor void Dealer::dealCard(vector <Card>& Deck,vector<Card>& Hand){ Card temp; cout<<"Dealt card. Deck Size in now "<<Deck.size()<<endl; int i = Deck.size(); temp.setName(Deck[i-1].getName()); temp.setValue(Deck[i-1].getValue()); Hand.push_back(temp); Deck.pop_back(); } Dealer::~Dealer(){ cout<<" "<<endl; } void Dealer::shuffle(vector<Card>& Deck){ Card temp; srand (time(NULL));// for random number seeding temp.setValue(0); temp.setName("Empty"); int indexOne = 0; int indexTwo = 0; for(int i=0; i<1000;i++){ indexOne = (rand() % 52)+1;// random number 1-52 indexTwo = (rand() % 52)+1;// random number 1-52 temp = Deck[indexOne]; Deck[indexOne]=Deck[indexTwo]; Deck[indexTwo] = temp; } } void Dealer::clearHands(vector<User>& players, vector<User>::iterator it ){ int i=0; it = players.begin(); while(it!=players.end()){ players[i].getHand().clear(); i++; it++; } (this->Hand).clear(); cout<<"Hands have been cleared"<<endl; } void Dealer::reFreshDeck(vector <Card>& Deck){ cout<<"Dealer has collected all cards deck is being reshuffled"<<endl; Deck.clear(); this->makeDeck(Deck); this->shuffle(Deck); } void Dealer::displayDealer(){ cout << "Current Hand: 1)"<<this->Hand[0].getName()<<" 2)Face Down Card"<<endl; cout << "\n\n"; cout << "Hand Value with 1 card: " << this->Hand[0].getValue() << " " << "\n" <<"------------------------------------------------------"<<endl; // set the hand value after every call to print this->setHandValue(this->getHandValue()); } void Dealer::makeDeck(vector <Card>& Deck){ // initilizes the deck to start the game Card temp; // All 4 of the Kings ****************************************************** temp.setName("King of Diamonds"); // Dimonds temp.setValue(10); Deck.push_back(temp);//1 temp.setName("King of Hearts"); // Hearts temp.setValue(10); Deck.push_back(temp);//2 temp.setName("King of Spades"); // Spades temp.setValue(10); Deck.push_back(temp);//3 temp.setName("King of Clubs"); // Clubs temp.setValue(10); Deck.push_back(temp);//4 // All 4 Queens********************************************************** temp.setName("Queen of Diamonds"); // Dimonds temp.setValue(10); Deck.push_back(temp);//1 temp.setName("Queen of Hearts"); // Hearts temp.setValue(10); Deck.push_back(temp);//2 temp.setName("Queen of Spades"); // Spades temp.setValue(10); Deck.push_back(temp);//3 temp.setName("Queen of Clubs"); // Clubs temp.setValue(10); Deck.push_back(temp);//4 // All 4 Jacks*********************************************************** temp.setName("Jack of Diamonds"); // Dimonds temp.setValue(10); Deck.push_back(temp);//1 temp.setName("Jack of Hearts"); // Hearts temp.setValue(10); Deck.push_back(temp);//2 temp.setName("Jack of Spades"); // Spades temp.setValue(10); Deck.push_back(temp);//3 temp.setName("Jack of Clubs"); // Clubs temp.setValue(10); Deck.push_back(temp);//4 // All 4 Tens***************************************************************** temp.setName("Ten of Diamonds"); // Dimonds temp.setValue(10); Deck.push_back(temp);//1 temp.setName("Ten of Hearts"); // Hearts temp.setValue(10); Deck.push_back(temp);//2 temp.setName("Ten of Spades"); // Spades temp.setValue(10); Deck.push_back(temp);//3 temp.setName("Ten of Clubs"); // Clubs temp.setValue(10); Deck.push_back(temp);//4 // All 4 nines *************************************************************** temp.setName("Nine of Diamonds"); // Dimonds temp.setValue(9); Deck.push_back(temp);//1 temp.setName("Nine of Hearts"); // Hearts temp.setValue(9); Deck.push_back(temp);//2 temp.setName("Nine of Spades"); // Spades temp.setValue(9); Deck.push_back(temp);//3 temp.setName("Nine of Clubs"); // Clubs temp.setValue(9); Deck.push_back(temp);//4 // All 4 Eights************************************************************** temp.setName("Eight of Diamonds"); // Dimonds temp.setValue(8); Deck.push_back(temp);//1 temp.setName("Eight of Hearts"); // Hearts temp.setValue(8); Deck.push_back(temp);//2 temp.setName("Eight of Spades"); // Spades temp.setValue(8); Deck.push_back(temp);//3 temp.setName("Eight of Clubs"); // Clubs temp.setValue(8); Deck.push_back(temp);//4 // All 4 Sevens*************************************************************** temp.setName("Seven of Diamonds"); // Dimonds temp.setValue(7); Deck.push_back(temp);//1 temp.setName("Seven of Hearts"); // Hearts temp.setValue(7); Deck.push_back(temp);//2 temp.setName("Seven of Spades"); // Spades temp.setValue(7); Deck.push_back(temp);//3 temp.setName("Seven of Clubs"); // Clubs temp.setValue(7); Deck.push_back(temp);//4 // All 4 six****************************************************************** temp.setName("Six of Diamonds"); // Dimonds temp.setValue(6); Deck.push_back(temp);//1 temp.setName("Six of Hearts"); // Hearts temp.setValue(6); Deck.push_back(temp);//2 temp.setName("Six of Spades"); // Spades temp.setValue(6); Deck.push_back(temp);//3 temp.setName("Six of Clubs"); // Clubs temp.setValue(6); Deck.push_back(temp);//4 // All 4 Fives**************************************************************** temp.setName("Five of Diamonds"); // Dimonds temp.setValue(5); Deck.push_back(temp);//1 temp.setName("Five of Hearts"); // Hearts temp.setValue(5); Deck.push_back(temp);//2 temp.setName("Five of Spades"); // Spades temp.setValue(5); Deck.push_back(temp);//3 temp.setName("Five of Clubs"); // Clubs temp.setValue(5); Deck.push_back(temp);//4 // All 4 Fours***************************************************************** temp.setName("Four of Diamonds"); // Dimonds temp.setValue(4); Deck.push_back(temp);//1 temp.setName("Four of Hearts"); // Hearts temp.setValue(4); Deck.push_back(temp);//2 temp.setName("Four of Spades"); // Spades temp.setValue(4); Deck.push_back(temp);//3 temp.setName("Four of Clubs"); // Clubs temp.setValue(4); Deck.push_back(temp);//4 // All 4 Three************************************************************ temp.setName("Three of Diamonds"); // Dimonds temp.setValue(3); Deck.push_back(temp);//1 temp.setName("Three of Hearts"); // Hearts temp.setValue(3); Deck.push_back(temp);//2 temp.setName("Three of Spades"); // Spades temp.setValue(3); Deck.push_back(temp);//3 temp.setName("Three of Clubs"); // Clubs temp.setValue(3); Deck.push_back(temp);//4 // All 4 Twos************************************************************* temp.setName("Two of Diamonds"); // Dimonds temp.setValue(2); Deck.push_back(temp);//1 temp.setName("Two of Hearts"); // Hearts temp.setValue(2); Deck.push_back(temp);//2 temp.setName("Two of Spades"); // Spades temp.setValue(2); Deck.push_back(temp);//3 temp.setName("Two of Clubs"); // Clubs temp.setValue(2); Deck.push_back(temp);//4 // All 4 Aces************************************************************* temp.setName("Ace of Diamonds"); // Dimonds temp.setValue(1); Deck.push_back(temp);//1 temp.setName("Ace of Hearts"); // Hearts temp.setValue(1); Deck.push_back(temp);//2 temp.setName("Ace of Spades"); // Spades temp.setValue(1); Deck.push_back(temp);//3 temp.setName("Ace of Clubs"); // Clubs temp.setValue(1); Deck.push_back(temp);//4 }
// 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 MeshVS_TwoNodes_HeaderFile #define MeshVS_TwoNodes_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif //! Structure containing two IDs (of nodes) for using as a key in a map //! (as representation of a mesh link) //! struct MeshVS_TwoNodes { Standard_Integer First, Second; MeshVS_TwoNodes (Standard_Integer aFirst=0, Standard_Integer aSecond=0) : First(aFirst), Second(aSecond) {} }; //! Computes a hash code for two nodes, in the range [1, theUpperBound] //! @param theTwoNodes the object of structure containing two IDs which hash code is to be computed //! @param theUpperBound the upper bound of the range a computing hash code must be within //! @return a computed hash code, in the range [1, theUpperBound] inline Standard_Integer HashCode (const MeshVS_TwoNodes& theTwoNodes, const Standard_Integer theUpperBound) { // symmetrical with respect to theTwoNodes.First and theTwoNodes.Second const Standard_Integer aKey = theTwoNodes.First + theTwoNodes.Second; return HashCode (aKey, theUpperBound); } //================================================================ // Function : operator == // Purpose : //================================================================ inline Standard_Boolean operator==( const MeshVS_TwoNodes& obj1, const MeshVS_TwoNodes& obj2 ) { return ( ( obj1.First == obj2.First ) && ( obj1.Second == obj2.Second ) ) || ( ( obj1.First == obj2.Second ) && ( obj1.Second == obj2.First ) ); } #endif
#include <SparkFunAutoDriver.h> #include <SPI.h> #include <Servo.h> Servo servoMag; AutoDriver stepperY(10, 6); // y, board #1 AutoDriver stepperX1(A0, 6); // x1, board #2 AutoDriver stepperX2(A1, 6); // x2, board #3 boolean startup = true; //servo up / down angles int down = 45; int up = 3; int serialDataIn = 0; int serialVars[3]; long stepConstant = 641; //steps long maxX = 830;//830; //mm long maxY = 330;//330; //mm // struct struct posArray { int x1; int x2; int y; }; #define INPUT_SIZE 30 void setup() { Serial.begin(115200); Serial.println("Serial begin <3"); servoMag.attach(3); // server setup servoMag.write(down); StepperSetup(); // stepper setup } void loop() { } void serialEvent(){ while (Serial.available()){ while (startup) { stepperY.resetDev(); stepperX1.resetDev(); stepperX2.resetDev(); startup = false; } // read c string char input[INPUT_SIZE + 1]; //make a buffer of length 31 byte size = Serial.readBytesUntil('Z',input, INPUT_SIZE); // read incoming bytes, put them in the buffer named input input[size] = 0; // add null to c string Serial.print("command received: "); // JAH Serial.println(input); // JAH // read each command pair char* command = strtok(input, ","); // splits a C string into substrings, based on a separator character while (command != 0) { serialVars[serialDataIn % 3] = atoi(command); //turns C substring into integer, stores in array serialDataIn++; command = strtok(0, ","); //goes to next substring } // DO THE WISH actuateWish(serialVars); } } // create a button which resets pos // use resetPos() void actuateWish(int wish[3]) { //naming for an easy time long x = wish[0]; long y = wish[1]; int servo = wish[2]; if (x < 0) { x = 0; Serial.println("x cannot be negative"); }; if (y < 0) { y = 0; Serial.println("y cannot be negative"); } if (x > maxX){ x = maxX - 5; Serial.println("x max"); } if (y > maxY){ y = maxY - 5; Serial.println("y max"); } // Serial.println(x*stepConstant); // get the diff between current location (in steps) and wished location long deltaX1 = (x * stepConstant) - stepperX1.getPos(); long deltaX2 = (x * stepConstant) - stepperX2.getPos(); long deltaY = (y * stepConstant) - stepperY.getPos(); // move to wished location: // Serial.print("x: "); // Serial.print(x); // Serial.print(", y: "); // Serial.print(y); // Serial.print(", servo: "); // Serial.println(servo); // // Serial.print("deltax1: "); // Serial.print(deltaX1); // Serial.print(", deltax2: "); // Serial.print(deltaX2); // Serial.print(", deltay: "); // Serial.print(deltaY); // Serial.print(", servo: "); // Serial.println(servo); // // Serial.print("motorDir x1: "); // Serial.print(getMotorDirection(deltaX1)); // Serial.print(", motorDir x2: "); // Serial.print(getMotorDirection(deltaX2)); // Serial.print(", motorDir y: "); // Serial.println(getMotorDirection(deltaY)); stepperX1.move(getMotorDirection(deltaX1), abs(deltaX1)); stepperX2.move(getMotorDirection(deltaX2), abs(deltaX2)); stepperY.move(getMotorDirection(deltaY), abs(deltaY)); // magnet wishes actuated here: if (servo == 1){ servoMag.write(up); } else { servoMag.write(down); } // debugging while(stepperX1.busyCheck()) { } while(stepperY.busyCheck()){ } struct posArray metricPos = getPosMetric(); // Serial.print("steps x1: "); // Serial.print(stepperX1.getPos()); // Serial.print(", steps x2: "); // Serial.print(stepperX2.getPos()); // Serial.print(", steps y: "); // Serial.print(stepperY.getPos()); // Serial.print(", servo: "); // Serial.println(servo); // Serial.print("x1: "); Serial.print(metricPos.x1); Serial.print(",x2: "); Serial.print(metricPos.x2); Serial.print(",y: "); Serial.print(metricPos.y); Serial.print(", servo: "); Serial.println(servo); } struct posArray getPosMetric() { //return x1, x2, y int y = stepperY.getPos() / stepConstant; int x1 = stepperX1.getPos() / stepConstant; int x2 = stepperX2.getPos() / stepConstant; return {x1: x1, x2 : x2, y : y}; } int getMotorDirection(long delta){ if (delta > 0) { return FWD; } else { return REV; } }
#include "config.h" #include "base.h" #include "boolean.h" #include "arithmetics.h" #include "mul.h" #include "div.h" #include "barrett.h" void barrettMu(t_bint* b, t_bint* n, t_size sizeB, t_size sizeN) { div(b, n, sizeB, sizeN); } void barrettMod(t_bint* a, t_bint* n, t_bint* mu, t_size sizeA, t_size sizeN, t_size sizeMu) { t_size sizeQ = sizeA + 1; t_size k = msw(n,sizeN) + 1; if (k - 1 > msw(a,sizeA)) { return; } t_bint* q = new t_bint[sizeQ]; setNull(q,sizeQ); mov(q, a, sizeA); swr(q,k,sizeQ); mul(q,mu,sizeQ,sizeMu); swr(q,k,sizeQ); mul(q,n,sizeQ,sizeN); setNull(&a[k],sizeA - k); setNull(&q[k],sizeQ - k); switch (cmp(a,q,sizeA,sizeQ)) { case CMP_EQUAL: setNull(a,sizeA); break; case CMP_LOWER: a[k] = 1; case CMP_GREATER: sub(a,q,sizeA,sizeQ); break; } mod(a,n,sizeA,sizeN); delete[] q; }
//include"stdafx.h" #include"updateString.h" string updateString() { string str; cin.ignore();//clear the keyboard buffer getline(cin, str); return str; }
#include <iostream> #include <fstream> #include <vector> #include <map> #include <algorithm> #include "common.h" using namespace std; /** * Day 16 * */ vector<vector<int>> patterns; /** * For each element, a repeating pattern is created. * Start pattern is 0,1,0,-1 * - Pattern for 1st nr is: 0,1,0,-1 * - patttern for 2nd nr is: 0,0,1,1,0,0,-1,-1 * - patttern for 3nd nr is: 0,0,0,1,1,1,0,0,0,-1,-1,-1 */ void buildPatterns(unsigned int nrOfElements) { vector<int> basePattern{0,1,0,-1}; for (unsigned int i = 0; i < nrOfElements; i++) { vector<int>pattern; for (unsigned int pIndex = 0; pIndex < basePattern.size(); pIndex++) { int actNr = basePattern[pIndex]; for (unsigned int repeat = 0; repeat <= i; repeat++) { pattern.push_back(actNr); } } patterns.push_back(pattern); } } void calcPhase(vector<int> &elements) { // Loop over all input numbers for (unsigned int nrIndex = 0; nrIndex < elements.size(); nrIndex++ ) { int sum = 0; for (unsigned int i = 0; i < elements.size(); i++) { // for each number, calc nr * pattern-nr, while pattern-nr is offset by 1. // skip first nr in offset pattern. vector<int> pattern = patterns[nrIndex]; sum += elements[i] * pattern[(i+1) % pattern.size()]; } elements[nrIndex] = abs(sum%10); } } void calcPhases(unsigned int nr, vector<int> &elements) { while (nr > 0) { calcPhase(elements); nr--; } } void outputElements(vector<int>&elements, unsigned long amount) { amount = min(elements.size(), amount); for (unsigned int i = 0; i < amount; i++) { cout << elements[i]; } cout << endl; } void outputElements(vector<int>&elements) { outputElements(elements, elements.size()); } int main(int argc, char *args[]) { bool display = argc >= 3 && string("--display").compare(args[2]) == 0 ? true : false; if (argc < 2) { cerr << "Error: give input file on command line" << endl; exit(1); } // Read input file: vector<string> fileData; readLines(args[1], fileData); string input = fileData[0]; vector<int>elements; for (auto i : input) { elements.push_back(i - '0'); } cout << "Elements: " << elements.size() << endl; buildPatterns(elements.size()); // for (auto p : patterns) { // for (auto e : p) { // cout << e << ","; // } // cout << endl; // } calcPhases(100, elements); // outputElements(elements); cout << "Solution 1: First 8 digits after 100 rounds: "; outputElements(elements, 8); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <algorithm> #include <folly/lang/Assume.h> #include <quic/QuicConstants.h> namespace quic { std::string_view congestionControlTypeToString(CongestionControlType type) { switch (type) { case CongestionControlType::Cubic: return kCongestionControlCubicStr; case CongestionControlType::BBR: return kCongestionControlBbrStr; case CongestionControlType::BBR2: return kCongestionControlBbr2Str; case CongestionControlType::BBRTesting: return kCongestionControlBbrTestingStr; case CongestionControlType::Copa: return kCongestionControlCopaStr; case CongestionControlType::Copa2: return kCongestionControlCopa2Str; case CongestionControlType::NewReno: return kCongestionControlNewRenoStr; case CongestionControlType::StaticCwnd: return kCongestionControlStaticCwndStr; case CongestionControlType::None: return kCongestionControlNoneStr; case CongestionControlType::MAX: return "MAX"; default: return "unknown"; } } std::optional<CongestionControlType> congestionControlStrToType( std::string_view str) { if (str == kCongestionControlCubicStr) { return quic::CongestionControlType::Cubic; } else if (str == kCongestionControlBbr2Str) { return quic::CongestionControlType::BBR2; } else if (str == kCongestionControlBbrStr) { return quic::CongestionControlType::BBR; } else if (str == kCongestionControlBbrTestingStr) { return quic::CongestionControlType::BBRTesting; } else if (str == kCongestionControlCopaStr) { return quic::CongestionControlType::Copa; } else if (str == kCongestionControlCopa2Str) { return quic::CongestionControlType::Copa2; } else if (str == kCongestionControlNewRenoStr) { return quic::CongestionControlType::NewReno; } else if (str == kCongestionControlStaticCwndStr) { return quic::CongestionControlType::StaticCwnd; } else if (str == kCongestionControlNoneStr) { return quic::CongestionControlType::None; } return std::nullopt; } QuicBatchingMode getQuicBatchingMode(uint32_t val) { switch (val) { case static_cast<uint32_t>(QuicBatchingMode::BATCHING_MODE_NONE): return QuicBatchingMode::BATCHING_MODE_NONE; case static_cast<uint32_t>(QuicBatchingMode::BATCHING_MODE_GSO): return QuicBatchingMode::BATCHING_MODE_GSO; case static_cast<uint32_t>(QuicBatchingMode::BATCHING_MODE_SENDMMSG): return QuicBatchingMode::BATCHING_MODE_SENDMMSG; case static_cast<uint32_t>(QuicBatchingMode::BATCHING_MODE_SENDMMSG_GSO): return QuicBatchingMode::BATCHING_MODE_SENDMMSG_GSO; // no default } return QuicBatchingMode::BATCHING_MODE_NONE; } std::vector<QuicVersion> filterSupportedVersions( const std::vector<QuicVersion>& versions) { std::vector<QuicVersion> filteredVersions; std::copy_if( versions.begin(), versions.end(), std::back_inserter(filteredVersions), [](auto version) { return version == QuicVersion::MVFST || version == QuicVersion::QUIC_V1 || version == QuicVersion::QUIC_V1_ALIAS || version == QuicVersion::QUIC_DRAFT || version == QuicVersion::MVFST_INVALID || version == QuicVersion::MVFST_EXPERIMENTAL || version == QuicVersion::MVFST_ALIAS; }); return filteredVersions; } std::string_view writeDataReasonString(WriteDataReason reason) { switch (reason) { case WriteDataReason::PROBES: return "Probes"; case WriteDataReason::ACK: return "Ack"; case WriteDataReason::CRYPTO_STREAM: return "Crypto"; case WriteDataReason::STREAM: return "Stream"; case WriteDataReason::BLOCKED: return "Blocked"; case WriteDataReason::STREAM_WINDOW_UPDATE: return "StreamWindowUpdate"; case WriteDataReason::CONN_WINDOW_UPDATE: return "ConnWindowUpdate"; case WriteDataReason::SIMPLE: return "Simple"; case WriteDataReason::RESET: return "Reset"; case WriteDataReason::PATHCHALLENGE: return "PathChallenge"; case WriteDataReason::PING: return "Ping"; case WriteDataReason::DATAGRAM: return "Datagram"; case WriteDataReason::NO_WRITE: return "NoWrite"; } folly::assume_unreachable(); } std::string_view writeNoWriteReasonString(NoWriteReason reason) { switch (reason) { case NoWriteReason::WRITE_OK: return "WriteOk"; case NoWriteReason::EMPTY_SCHEDULER: return "EmptyScheduler"; case NoWriteReason::NO_FRAME: return "NoFrame"; case NoWriteReason::NO_BODY: return "NoBody"; case NoWriteReason::SOCKET_FAILURE: return "SocketFailure"; } folly::assume_unreachable(); } std::string_view readNoReadReasonString(NoReadReason reason) { switch (reason) { case NoReadReason::READ_OK: return "ReadOK"; case NoReadReason::TRUNCATED: return "Truncated"; case NoReadReason::EMPTY_DATA: return "Empty data"; case NoReadReason::RETRIABLE_ERROR: return "Retriable error"; case NoReadReason::NONRETRIABLE_ERROR: return "Nonretriable error"; case NoReadReason::STALE_DATA: return "Stale data"; } folly::assume_unreachable(); } } // namespace quic
#pragma once #include "merger_base.hpp" #include "proto/data_arena.pb.h" #include "utils/service_thread.hpp" #include <memory> using namespace std; namespace pd = proto::data; namespace nora { class arena_merger : public merger_base { public: static arena_merger& instance() { static arena_merger inst; return inst; } void start(); private: void load_rank(); void merge_rank(); void load_next_page(); void load_to_db_next_page(); void on_db_get_gladiators_done(const shared_ptr<db::message>& msg); void on_db_get_to_db_gladiators_done(const shared_ptr<db::message>& msg); int cur_page_ = 0; int page_size_ = 50; int adding_count_ = 0; unique_ptr<pd::arena_rank> from_arena_; unique_ptr<pd::arena_rank> to_arena_; }; }
#if !defined(__GESTURE_H__) #define __GESTURE_H__ #include "tinyxml.h" #include <vector> #include "Ogre.h" #include "OgreVector3.h" //#include "Preprocessor.h" using namespace std; class Gesture { std::string mName; float mSamplingFrequency; std::vector<Ogre::Vector3> mLocalAccelerationArray; std::vector<Ogre::Vector3> mWorldAccelerationArray; std::vector<Ogre::Vector3> mVelocityArray; std::vector<Ogre::Vector3> mPositionArray; std::vector<int> mSymbolArray; //Quantizer* mQuantizer; char *getTimeLabel(void) { time_t timer; struct tm *t; timer = time(NULL); t = localtime(&timer); static char s[255]; sprintf(s, "%04d_%02d_%02d_%02d_%02d_%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); return s; } public: Gesture(void) { mName = Ogre::String("Gesture_") + Ogre::String(getTimeLabel()); mSamplingFrequency = 30.0f; } Gesture(std::string name) { mName = name; mSamplingFrequency = 30.0f; } //~Gesture(void); std::vector<Ogre::Vector3>& getLocalAccelerationArray(void) { return mLocalAccelerationArray; } std::vector<int>& getSymbolArray(void) { return mSymbolArray; } void setSymbolArray(std::vector<int>& newSymbolArray) { mSymbolArray = newSymbolArray; } void setLocalAccelerationArray(std::vector<Ogre::Vector3>& newSymbolArray) { mLocalAccelerationArray = newSymbolArray; } float getMaxAcceleration(void); float getMinAcceleration(void); void addLocalAcceleration(Ogre::Vector3 &localAcceleration) { mLocalAccelerationArray.push_back(localAcceleration); } bool fillByXml(TiXmlElement *gestureElement) { mName = std::string(gestureElement->Attribute("Name")); TiXmlHandle hRoot = TiXmlHandle(gestureElement); { // parse <LocalAccelerationArray> TiXmlElement *currElement = hRoot.FirstChild("LocalAccelerationArray").FirstChild("LocalAcceleration").Element(); // TODO: need to check empty <LocalAcceleration> for (currElement; currElement; currElement = currElement->NextSiblingElement()) { // TODO: need to check this element is <LocalAcceleration> int index; double x, y, z; if (TIXML_SUCCESS == currElement->QueryIntAttribute("No", &index) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("x", &x) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("y", &y) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("z", &z)) { mLocalAccelerationArray.push_back(Ogre::Vector3(x, y, z)); } else { cout << "Parsing Error " << endl; return false; } } } { // parse <WorldAccelerationArray> TiXmlElement *currElement = hRoot.FirstChild("WorldAccelerationArray").FirstChild("WorldAcceleration").Element(); // TODO: need to check empty <WorldAcceleration> for (currElement; currElement; currElement = currElement->NextSiblingElement()) { // TODO: need to check this element is <WorldAcceleration> int index; double x, y, z; if (TIXML_SUCCESS == currElement->QueryIntAttribute("No", &index) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("x", &x) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("y", &y) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("z", &z)) { mWorldAccelerationArray.push_back(Ogre::Vector3(x, y, z)); } else { cout << "Parsing Error " << endl; return false; } } } { // parse <VelocityArray> TiXmlElement *currElement = hRoot.FirstChild("VelocityArray").FirstChild("Velocity").Element(); // TODO: need to check empty <Velocity> for (currElement; currElement; currElement = currElement->NextSiblingElement()) { // TODO: need to check this element is <Velocity> int index; double x, y, z; if (TIXML_SUCCESS == currElement->QueryIntAttribute("No", &index) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("x", &x) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("y", &y) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("z", &z)) { mVelocityArray.push_back(Ogre::Vector3(x, y, z)); } else { cout << "Parsing Error " << endl; return false; } } } { // parse <PositionArray> TiXmlElement *currElement = hRoot.FirstChild("PositionArray").FirstChild("Position").Element(); // TODO: need to check empty <Position> for (currElement; currElement; currElement = currElement->NextSiblingElement()) { // TODO: need to check this element is <Position> int index; double x, y, z; if (TIXML_SUCCESS == currElement->QueryIntAttribute("No", &index) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("x", &x) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("y", &y) && TIXML_SUCCESS == currElement->QueryDoubleAttribute("z", &z)) { mPositionArray.push_back(Ogre::Vector3(x, y, z)); } else { cout << "Parsing Error " << endl; return false; } } } { // parse <SymbolArray> TiXmlElement *currElement = hRoot.FirstChild("SymbolArray").FirstChild("Symbol").Element(); // TODO: need to check empty <Symbol> for (currElement; currElement; currElement = currElement->NextSiblingElement()) { // TODO: need to check this element is <Symbol> int index, value; if (TIXML_SUCCESS == currElement->QueryIntAttribute("No", &index) && TIXML_SUCCESS == currElement->QueryIntAttribute("Value", &value)) { mSymbolArray.push_back(value); } else { cout << "Parsing Error " << endl; return false; } } } return true; } TiXmlElement *createXmlElement(void) { // <Gesture Name="...." /> TiXmlElement *gestureElement = new TiXmlElement( "Gesture" ); gestureElement->SetAttribute("Name", mName.c_str()); // <Property Name="SamplingFrequency" Value="30" /> TiXmlElement *propertyElement = new TiXmlElement( "Property"); propertyElement->SetAttribute("Name", "SamplingFrequency"); propertyElement->SetDoubleAttribute("Value", mSamplingFrequency); gestureElement->LinkEndChild(propertyElement); // <LocalAccelerationArray> </LocalAccelerationArray> TiXmlElement *localAccelerationArrayElement = new TiXmlElement( "LocalAccelerationArray"); for (int i = 0; i < mLocalAccelerationArray.size(); i++) { TiXmlElement *localAccelerationElement = new TiXmlElement( "LocalAcceleration"); localAccelerationElement->SetAttribute("No", i); localAccelerationElement->SetDoubleAttribute("x", mLocalAccelerationArray[i].x); localAccelerationElement->SetDoubleAttribute("y", mLocalAccelerationArray[i].y); localAccelerationElement->SetDoubleAttribute("z", mLocalAccelerationArray[i].z); localAccelerationArrayElement->LinkEndChild(localAccelerationElement); } gestureElement->LinkEndChild(localAccelerationArrayElement); #if defined(QUANTIZATION_NEEDED) TiXmlElement *symbolArrayElement = new TiXmlElement( "SymbolArray"); for (int i = 0; i < mSymbolArray.size(); i++) { TiXmlElement *symbolElement = new TiXmlElement( "Symbol"); symbolElement->SetAttribute("No", i); symbolElement->SetAttribute("Value", mSymbolArray[i]); Ogre::Vector3 symbolAcceleration = Quantizer::Instance().getSymbolAcceleration(mSymbolArray[i]); symbolElement->SetDoubleAttribute("x", symbolAcceleration.x); symbolElement->SetDoubleAttribute("y", symbolAcceleration.y); symbolElement->SetDoubleAttribute("z", symbolAcceleration.z); symbolArrayElement->LinkEndChild(symbolElement); } gestureElement->LinkEndChild(symbolArrayElement); #endif return gestureElement; } }; #endif // __GESTURE_H__
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { int n, d; cin >> n >> d; cout << ((n - 1) / ((d * 2)+ 1)) + 1<< endl; }