blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
81779703eb29a1b94a0d5eefe5818d02dc7ddc87
27b17470be140efa743c18cbb12df7e339d46b7d
/word_break_II/main.cpp
060c4e08844867ba0933b1f863fb027fbebc6f6e
[]
no_license
slicer2/leetcode
196f0035154b1767308e39209d8574178f9e00c9
c240353d68eef24fa4de7526cbcbac9aee1323d4
refs/heads/master
2021-01-01T19:05:00.812940
2017-07-27T21:05:11
2017-07-27T21:05:11
98,502,329
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
main.cpp
#include <iostream> #include <unordered_set> #include <unordered_map> #include <string> #include <vector> #include <list> #include <stack> #include "dan.h" using namespace std; class Solution { private: unordered_map<int, unordered_set<int>> graph; vector<string> res; string s; public: vector<string> wordBreak(string s, unordered_set<string> &dict) { this->s = s; buildGraph(s.size(), dict); string row; buildBreak(0, row); return res; } void buildGraph(int start, unordered_set<string> &dict) { if (start == 0) return; for (int i=start-1; i>=0; i--) { if (dict.find(s.substr(i, start-i)) != dict.end()) { graph[i].insert(start); if (graph[i].size() == 1) buildGraph(i, dict); } } } void buildBreak(int start, string &row) { if (start == s.size()) { res.push_back(row.substr(0, row.size()-1)); return; } for (auto x: graph[start]) { string row0 = row; row += s.substr(start, x-start)+" "; buildBreak(x, row); row = row0; } } }; int main() { string s, longword; unordered_set<string> dict; cin>>longword; while (cin >> s) dict.insert(s); Solution sol; vector<string> ss = sol.wordBreak(longword, dict); for (auto x: ss) cout << x << endl; return 0; }
4043b5dee45add1077c39cf641410376e90e9e1e
f7c6efd5cb9dca903d95669ba4d7766b61ed45f2
/Animation/Animation/FramePattern.h
58723f892d886a626a9091522a131311dcbda9df
[]
no_license
ElisbanFlores/RealidadAumentada
2eb1d42b8737154abe51af7f81665e3a20d57d4c
0e207d5c6785fcf56849a6f0db3b821f05a5c366
refs/heads/master
2021-01-20T01:33:28.610160
2017-04-25T00:52:22
2017-04-25T00:52:22
89,295,109
1
0
null
null
null
null
UTF-8
C++
false
false
353
h
FramePattern.h
#pragma once #include "Common.h" class FramePattern { public: vector<Point2f> pattern_points; Point2f mean; double min_dist; string path; string imageFileName; string dataFileName; Mat frame; FramePattern (void); friend bool operator < (FramePattern fp1, FramePattern fp2){ return fp1.min_dist < fp2.min_dist; } };
7fba74bae63c69aad9b18dceaf0854abbab810ca
c4e5f59f2b8d5219c0c69fae57b6420749414439
/Source/Framework/Thread.h
8820297a0cc97b25cd97a2120926525b58934a79
[]
no_license
SerafAC/DS203
29b02ed25037d76a810e35b476b296ac3d03c53d
5b1e73c6bec62dfa81901b21c184ecf89d44d903
refs/heads/master
2021-09-10T03:45:56.208007
2018-03-20T22:16:45
2018-03-20T22:16:45
125,899,853
3
0
null
2018-03-19T18:03:38
2018-03-19T18:03:38
null
UTF-8
C++
false
false
596
h
Thread.h
#pragma once #ifndef DSO_FRAMEWORK_THREAD_H #define DSO_FRAMEWORK_THREAD_H #include <Source/HwLayer/Bios.h> #include <Source/Main/Application.h> class CThread { public: virtual void Start() { _ASSERT(0); } virtual void Stop() { _ASSERT(0); } virtual void Run() { _ASSERT(0); } virtual bool IsRunning() { _ASSERT(0); return false; } virtual int GetResult() { _ASSERT(0); return 0; } void Sleep(int nTime) { ui32 nLastTime = BIOS::SYS::GetTick() + nTime; do { Application.operator()(); } while (BIOS::SYS::GetTick() < nLastTime); } }; #endif
17579ab3711f067b1b64556ad3aa269da4728873
1707be6d432614b0677a8faa45d41018dccd16ba
/src/NB/trainLb_NeuroBayes.cpp
3420ec0b69858571af84b1aebb28ade6fb5857da
[]
no_license
lucapescatore88/Lmumu
429063e0af88d425292988baf0ba52d5c41d4d01
7c791b8289718da221df082bd9aff94ec45ab5a5
refs/heads/master
2021-01-22T01:34:05.206937
2015-07-01T21:05:48
2015-07-01T21:05:48
38,391,606
0
0
null
null
null
null
UTF-8
C++
false
false
5,497
cpp
trainLb_NeuroBayes.cpp
#include "TMath.h" #include "TFile.h" #include "TTree.h" #include "TChain.h" #include "TBranch.h" #include "TLeaf.h" #include "TLorentzVector.h" #include "TCanvas.h" #include "TH1F.h" #include "TRandom3.h" #include "NeuroBayesTeacher.hh" #include "NeuroBayesExpert.hh" #include <iostream> #include <string> #include "NBfunctions.hpp" #include "ReadTree_comp.hpp" #include "general_functions.hpp" int main(int argc, char** argv) { string dataType = "12"; //if(argc > 1) if((string)argv[1] == "11") dataType = "11"; NeuroBayesTeacher* nb = NeuroBayesTeacher::Instance(); nb->NB_DEF_TASK("CLASSIFICATION"); //setup network topology int nvar = 20; // Set this to number of inputs to your NN char ** varnames = new char*[nvar]; varnames[0] = "chi2_DTF"; varnames[1] = "Lb_TAU"; varnames[2] = "Lb_DIRA_OWNPV"; varnames[3] = "Lb_IPCHI2_OWNPV"; varnames[4] = "max_mu_IPCHI2_OWNPV"; varnames[5] = "min_mu_TRACKCHI2"; varnames[6] = "min_mu_PID"; varnames[7] = "min_mu_PID"; varnames[8] = "LL_Lambda0_IPCHI2_OWNPV"; varnames[9] = "LL_Lambda0_FDCHI2_OWNPV"; varnames[10] = "LL_Lambda0_PT"; varnames[11] = "DD_Lambda0_IPCHI2_OWNPV"; varnames[12] = "DD_Lambda0_FDCHI2_OWNPV"; varnames[13] = "DD_Lambda0_PT"; varnames[14] = "DD_pplus_IPCHI2_OWNPV"; varnames[15] = "DD_piminus_IPCHI2_OWNPV"; varnames[16] = "DD_piminus_PT"; varnames[17] = "LL_pplus_IPCHI2_OWNPV"; varnames[18] = "LL_piminus_IPCHI2_OWNPV"; varnames[19] = "LL_piminus_PT"; nb->NB_DEF_NODE1(nvar+1); nb->NB_DEF_NODE2(nvar); // nodes in hidden layer nb->NB_DEF_NODE3(1); // nodes in output layer nb->NB_DEF_TASK("CLA"); // binominal classification nb->NB_DEF_PRE(822); // nb->NB_DEF_PRE(812); nb->NB_DEF_REG("REG"); // 'OFF','REG' (def) ,'ARD','ASR','ALL' nb->NB_DEF_LOSS("ENTROPY"); // 'ENTROPY'(def),'QUADRATIC' nb->NB_DEF_METHOD("BFGS"); nb->NB_DEF_SHAPE("DIAG"); nb->NB_DEF_LEARNDIAG(1); nb->NB_DEF_RTRAIN(1.0); // use 70% of events for training // nb->NB_DEF_EPOCH(200); // weight update after n events nb->NB_DEF_SPEED(2.0); // multiplicative factor to enhance global learning speed nb->NB_DEF_MAXLEARN(1.0); // multiplicative factor to limit the global learning speed in any direction, this number should be smaller than NB_DEF_SPEED nb->NB_DEF_ITER(100); // number of training iteration //nb->NB_DEF_ITER(0); // number of training iteration //int i = 4701; //int j = 29; //nb->NB_RANVIN(i,j,2); // random number seed initialisation, i has to be an odd number, the third argument is a debugging flag nb->SetOutputFile(("expert_"+dataType+".nb").c_str()); // expert file SetupNNPrepro(nb); // MC TreeReader* reader = new TreeReader("tree"); reader->AddFile("/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2Lmumu_MC_Pythia8_NBweighted_new.root"); reader->Initialize(); // We take all signal and 20% of background nb->SetTarget(1); int ntot = reader->GetEntries(); int npassedMC = 0; cout << "Read in " << ntot << " events" << endl; int nstepMC = 5; //if(dataType=="11") nstepMC = 5; TFile ofile("/afs/cern.ch/work/p/pluca/Lmumu/weighted/samplesMVA_"+(TString)dataType+".root","recreate"); TTree * sigTrainSample = new TTree("sigTrainSample",""); reader->BranchNewTree(sigTrainSample); TTree * sigTestSample = new TTree("sigTestSample",""); reader->BranchNewTree(sigTestSample); for(int event = 0; event < ntot; event++) { reader->GetEntry(event); if( TrueID(reader) && TriggerPassed(reader)) { if( event%nstepMC==0 && npassedMC <= 4e4 ) { npassedMC++; float InputArray[nvar+1]; fillInputArray(reader,InputArray); if(isnan(InputArray[0])) continue; nb->SetWeight(reader->GetValue("Lb_weight")); nb->SetNextInput(nvar,InputArray); sigTrainSample->Fill(); } else sigTestSample->Fill(); } } // Data TreeReader* reader2 = new TreeReader("tree"); reader2->AddFile("/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2Lmumu_CL_NBweighted.root"); reader2->Initialize(); TTree * bkgTrainSample = new TTree("bkgTrainSample",""); reader2->BranchNewTree(bkgTrainSample); TTree * bkgTestSample = new TTree("bkgTestSample",""); reader2->BranchNewTree(bkgTestSample); nb->SetTarget(0); int ntot2 = reader2->GetEntries(); int npassed = 0; cout << "Read in " << ntot2 << " events" << endl; int nstep = 2; //if(dataType=="11") nstep = 2; for(int event = 0; event < ntot2; event++) { reader2->GetEntry(event); double massLb = reader2->GetValue("Lb_MassConsLambda_M",0); double massJpsi = reader2->GetValue("J_psi_1S_MM"); if(massLb > 6000 && TMath::Abs(massJpsi - 3096) > 100 && TMath::Abs(massJpsi - 3686) > 90 && TriggerPassed(reader2)) { if(event%nstep==0 && npassed <=4e4) { float InputArray[100]; npassed++; fillInputArray(reader2,InputArray); if(isnan(InputArray[0])) continue; nb->SetWeight(1.); nb->SetNextInput(nvar,InputArray); bkgTrainSample->Fill(); } else bkgTestSample->Fill(); } } bkgTrainSample->Write(); bkgTestSample->Write(); sigTestSample->Write(); sigTrainSample->Write(); ofile.Close(); cout << "\nData used = " << npassed << ", MC used = " << npassedMC << endl; cout << "Train the Network\n" << endl; nb->TrainNet(); nb->nb_correl_signi(varnames,"correl_signi.txt","correl_signi.html"); cout << "\nData used = " << npassed << ", MC used = " << npassedMC << endl; return 0; }
d820e583adba6ea19b75c56afdf1750299cf36e2
3dd58ac52a0ffab6657fdf994abdfd1bab45b71c
/PringlesNode.ino
86922caf5d31e22a05eda6f79e23da9963700226
[]
no_license
abhisola/ProductLevelStock
540686969e80ffb620ed40d3b0fda6ca6a7cb3c2
2d694e82d231a2166656e771befd8d87382f6a2b
refs/heads/master
2020-03-21T12:34:29.018978
2018-09-05T13:37:27
2018-09-05T13:37:27
138,560,041
0
0
null
null
null
null
UTF-8
C++
false
false
991
ino
PringlesNode.ino
#include <SoftwareSerial.h> #include <ArduinoJson.h> #include "UbidotsMicroESP8266.h" #define TOKEN "A1E-sa3GBevj4R8uoCLtRIowWj5bgfBNtO" /* Put here your Ubidots TOKEN */ #define WIFISSID "CBCI-9557-2.4" /* Put here your Wi-Fi SSID */ #define PASSWORD "bacon6291camera" /* Put here your Wi-Fi password */ // SSID -> ARRIS-5G // Pass -> BSY89A601622 SoftwareSerial ESPserial(D5, D6); // tx Rx Ubidots client(TOKEN); boolean start = false; void setup() { Serial.begin(19200); ESPserial.begin(19200); delay(10); client.wifiConnection(WIFISSID, PASSWORD); } void loop() { if(ESPserial.available()) { StaticJsonBuffer<2048> jsonBuffer; JsonObject& root = jsonBuffer.parseObject(ESPserial); if (!root.success()) { Serial.println("parseObject() failed"); return; } String ID = root[F("id")].asString(); char idBuff[30]; ID.toCharArray(idBuff, 30); float val = root["value"]; client.add(idBuff, val); client.sendAll(false); } }
418330bf2856a474754c8782fa57c0e65a8b43e1
f0567e1f5147194a19815ac456f5738defaa27e9
/src/LFO2.h
32141e890369bcb8c5c3efd35655881d259232d2
[]
no_license
RonCG/RonSynth
e9aa3c543aaf122e969c224559d4405716cc8ef9
19a17d1725b3efdf063854552cd8f4d5f45ec6b3
refs/heads/main
2023-02-24T04:12:58.128669
2021-01-30T22:46:31
2021-01-30T22:46:31
334,526,051
0
0
null
null
null
null
UTF-8
C++
false
false
1,079
h
LFO2.h
/* ============================================================================== LFO2.h Created: 12 Feb 2019 11:36:13am Author: RonnyCG ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "PluginProcessor.h" //============================================================================== /* */ class LFO2 : public Component { public: LFO2(RonSynthAudioProcessor&); ~LFO2(); void paint (Graphics&) override; void resized() override; private: ComboBox lfo2WaveCB; ComboBox lfo2DestCB; Slider lfo2RateSL; Slider lfo2IntensitySL; ScopedPointer<AudioProcessorValueTreeState::ComboBoxAttachment> lfo2WaveVal; ScopedPointer<AudioProcessorValueTreeState::ComboBoxAttachment> lfo2DestVal; ScopedPointer<AudioProcessorValueTreeState::SliderAttachment> lfo2RateVal; ScopedPointer<AudioProcessorValueTreeState::SliderAttachment> lfo2IntensityVal; RonSynthAudioProcessor& processor; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LFO2) };
06360aabfef51946fec4ce8f6bd6039c07c00a15
50b0d958fa5cff16c3e689f5371f3b080e83f45e
/code/samples/arduino/doorbell-NRF24L01/transmitter/doorbell.ino
e12a6a03cf4504b25ff327a5b5ae3ed8df54b439
[ "MIT" ]
permissive
davidalexisnyt/Making-Things-Arduino-Workshop
96293414297a59f687f0d789895260034223842c
654356fe5cd73b3c2a1c0ecb4db93c2557d36586
refs/heads/master
2020-04-26T22:19:54.939137
2019-04-08T17:39:31
2019-04-08T17:39:31
173,869,686
2
0
null
2019-03-18T00:49:14
2019-03-05T03:55:08
C++
UTF-8
C++
false
false
7,632
ino
doorbell.ino
/* * DOORBELL UNIT - NRF24L01+ * --------------------------------------------------------------------------- * This version of the doorbell uses the NRF24L01+ 2.4GHz radio to receive * ring notifications from the doorbell transmitter unit. * * ATTRIBUTIONS * * Uses the excellent NRFLite library from dparson55. https://github.com/dparson55/NRFLite * --------------------------------------------------------------------------- */ #include <avr/sleep.h> #include <avr/power.h> #include <SPI.h> #include <NRFLite.h> // Define pins used by NRF24L01+ for chip select and chip enable #define CE_PIN 9 #define CSN_PIN 10 // This is the radio ID of the receiver. const static uint8_t DESTINATION_RADIO_ID = 0; // This is our transmitter ID. If we have more than one transmitter, each should have its own ID. const static uint8_t RADIO_ID = 1; const static uint8_t RADIO_CE_PIN = 9; const static uint8_t RADIO_CSN_PIN = 10; const static int BUTTON = 3; const static int LED = 4; const static int DEBOUNCED_ELAY = 500; const static int ACTIVITY_TIMEOUT = 10000; struct RadioPacket // Any packet up to 32 bytes can be sent. { uint8_t FromRadioId; uint32_t OnTimeMillis; uint32_t FailedTxCount; }; NRFLite radio; RadioPacket radioData; volatile bool ringRequested = false; volatile int lastPressed = 0; bool ledOn = false; bool startingUp; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Initialize NRF24L01+ radio to enable communication. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void initializeComm() { if (!radio.init(RADIO_ID, RADIO_CE_PIN, RADIO_CSN_PIN)) { #ifdef DEBUGMODE Serial.println("Cannot communicate with radio"); #endif // Loop forever, rapidly flashing the LED in error mode while (1) { flashLed(1); } } radioData.FromRadioId = RADIO_ID; delay(50); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void sendNotify() { radioData.OnTimeMillis = millis(); #ifdef DEBUGMODE Serial.print("Sending "); Serial.print(radioData.OnTimeMillis); Serial.println(" ms"); #endif if (radio.send(DESTINATION_RADIO_ID, &radioData, sizeof(radioData))) { #ifdef DEBUGMODE Serial.println("Successfully sent data to receiver"); #endif } else { #ifdef DEBUGMODE Serial.println("Failed to send data to receiver!"); #endif radioData.FailedTxCount++; } flashLed(4); } /* ------------------- MAIN HANDLERS & LOOP -------------------------------- */ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void flashLed(int repeat) { for (byte i = 0; i < repeat; i++) { digitalWrite(LED, LOW); delay(100); digitalWrite(LED, HIGH); delay(100); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void buttonPressed() { // Handle button debouncing by not handling a button press within 1 second of the previous press. if ( !startingUp && !ringRequested && (millis() - lastPressed > DEBOUNCED_ELAY) ) { ringRequested = true; ledOn = true; lastPressed = millis(); } startingUp = false; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void wakeUp() { sleep_disable(); // When we wake up, we want to trigger the button press event // Remove the wakeUp interrupt handler detachInterrupt(INT1); #ifdef DEBUGMODE Serial.println("wake!"); #endif // Restore AVR peripherals used elsewhere in the code power_usart0_enable(); // Enable Serial power_timer0_enable(); // Enable millis() etc. power_spi_enable(); // Enable SPI // Turn on the NRF24L01+ radio. // radio.powerUp(); // Set up button to trigger an interrupt. attachInterrupt(INT1, buttonPressed, FALLING); delay(50); // Simulate button press to set the correct flags buttonPressed(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // goToSleep() // Powers down communication module and microcontroller. The normal button // interrupt handler is disconnected, and another handler that handles the // wakup is attached. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void goToSleep(void) { noInterrupts(); detachInterrupt(INT1); delay(50); attachInterrupt(INT1, wakeUp, LOW); interrupts(); delay(50); digitalWrite(LED, LOW); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); radio.powerDown(); power_spi_disable(); // Disable SPI delay(50); // Stall for last serial output power_timer0_disable(); // Disable millis() etc. power_usart0_disable(); // Disable Serial // Go to sleep sleep_mode(); /* The program will continue from here. */ // .... } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Setup // Initializes the communication module, and configures the LED and button. // The button presses are handled with an interrupt handler rather than // polling. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void setup() { startingUp = true; ringRequested = false; #ifdef DEBUGMODE Serial.begin(115200); delay(10); Serial.println(); Serial.println(); Serial.print("Configuring..."); #endif pinMode(BUTTON, INPUT_PULLUP); pinMode(LED, OUTPUT); initializeComm(); flashLed(3); ledOn = true; // Set up button to trigger an interrupt. noInterrupts(); attachInterrupt(INT1, buttonPressed, FALLING); interrupts(); delay(50); startingUp = false; #ifdef DEBUGMODE Serial.println(); Serial.print("Done."); #endif } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Main loop // Sends the wireless notification to the base unit if someone presses the // doorbell. Flashes the LED then leaves it solid on for 20 seconds. If // the bell is not pressed again in that time, the device is put to sleep. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void loop() { if ( ringRequested ) { #ifdef DEBUGMODE Serial.println( "Button pressed" ); Serial.println( "Sending message to base station ..." ); #endif sendNotify(); // Reset the ring request flag so button presses are allowed again. ringRequested = false; } // Let's check if the unit has been awake longer than the activity timeout // since the last time the button was pressed. If so, put the unit to sleep. int timePassed = millis() - lastPressed; if ( timePassed > ACTIVITY_TIMEOUT ) { flashLed(4); digitalWrite(LED, LOW); ledOn = false; goToSleep(); } else { // When the button is pressed, flash the LED every half a second for 2 seconds // to let the user know that something is happening. if ( timePassed < 2000 && (0 < (timePassed % 500) < 10) ) { flashLed(1); } } }
2396dc5beec8a9a7ad9b3db8e690c417f4e71c12
3a931f9427d64143dba81435bcaa7528756e15b4
/sourcefiles/main.cpp
4be945286d06cf13ab5f6b9f3a934239c0425eb1
[]
no_license
gkuracz/Metodos-E4
602c7e789be0803c89cd6130e17c86dd2a1596e6
17b21f7c5d0fbb0d11fa5d355ced88262927ecf6
refs/heads/master
2021-01-10T20:30:03.590283
2015-04-22T00:49:00
2015-04-22T00:49:00
34,014,136
0
0
null
null
null
null
UTF-8
C++
false
false
4,249
cpp
main.cpp
#include<stdio.h> #include <iostream> #include <string> #include"csv.h" #include"mat.h" #include "getFileInfo.h" using namespace std; int main(int argc, char** argv) { if (argc<4) { cout << "############################################################" << endl << endl; cout << "[DEBUG] This program needs 3 arguments to run:" << endl; cout << "[DEBUG] nameA nameB nameX" << endl << endl << endl; cout << "[DEBUG] (nameA,nameB and nameX must be the .csv file name)." << endl << endl; cout << "############################################################" << endl << endl; } else { char* fileNameA = argv[1]; char* fileNameB = argv[2]; char* fileNameX = argv[3]; cout << "[DEBUG] nameA: " << fileNameA << endl; cout << "[DEBUG] nameB: " << fileNameB << endl; cout << "[DEBUG] nameX: " << fileNameX << endl<<endl; /*mat timeRatio = mat(17610, 2); // we create the timeRatio, knowing the amount of lines beforehand fileSampleRead("spdc2693.txt", timeRatio.matrix, -1, -1); // we obtain all the data from the file mat matrixA = mat(timeRatio.M, 3); //Since we think our polinomialis Ao + A1x + A2x^2 = Y we have a vector 1x3 long double ** tMatrix = NULL, ** sMatrix = NULL; tMatrix = timeRatio.get_col(timeRatio.matrix, 0, timeRatio.M, timeRatio.N); // We seperate from the data the time column sMatrix = timeRatio.get_col(timeRatio.matrix, 1, timeRatio.M, timeRatio.N);// We seperate from the data the data values column sMatrix = applyLogarithmToDataValues(sMatrix, timeRatio.M); // Since the original values correspond to S = exp{Ao + A1x + A2x^2 = Y}, we have to apply log to each value. tMatrix = standarizationOfTimeValues(tMatrix, timeRatio.M); // we standarized the time values so we can work with them without any unit matrixA.matrix = createTimeVectorMatrix(matrixA.matrix, tMatrix, timeRatio.M); // we create the time value A matrix ( 1 t t^2 ) delete tMatrix; // Since we used this matrix, we don't need it anymore. //matrixA.print_mat(); matrixA.qr(); //matrixA.QRDecomposition(); // we obtain the QR function to solveLeastSquares long double ** matrixX = new long double *[1]; // we create the solution matrix where all the values will go. matrixX[0] = new long double[matrixA.N]; solveLeastSquares(matrixA.Q, matrixA.R, sMatrix, matrixX, timeRatio.M, matrixA.N); matrixA.print_mat_R(); cout << endl; matrixA.print_thisMatrix(matrixX, 1, 3); //timeRatio.print_thisMatrix(tMatrix, timeRatio.M, 1); //timeRatio.print_thisMatrix(sMatrix, timeRatio.M, 1); delete matrixX; delete sMatrix; //.print_thisMatrix(sMatrix, timeRatio.M, 1); //timeRatio.print_mat(); //timeRatio.qr(); */ //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // This is a working example of solving least squares with the QR decomposition algorithm method. // - There is a set of examples that will work with this algorithm, such as Example01/02/03 on the csv files. // - It will use the QRDecomposition algorithm. mat A= mat(fileNameA); mat b = mat(fileNameB); long double ** matrixX = new long double * [1]; // we create the solution matrix where all the values will go. matrixX[0] = new long double [A.N]; printf("A:\n"); A.print_mat(); printf("b:\n"); b.print_mat(); A.qr(); //A.QRDecomposition(); solveLeastSquares(A.Q, A.R, b.matrix, matrixX, A.M, A.N); printf("X:\n"); A.print_thisMatrix(matrixX,1,A.N); csvWrite(fileNameX, matrixX, 1, A.N); delete matrixX; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%8/ /* cout << endl << endl << "@@@@@@@@@@@@@@@@@@@" << endl << endl; A.LUdecomposition(); cout << "[DEBUG]: MATRIX LOWER" << endl << endl; A.print_mat_L(); cout << "[DEBUG]: MATRIX UPPER" << endl << endl; A.print_mat_U();*/ /*cout << endl << endl << "@@@@@@@@@@@@@@@@@@@" << endl << endl; cout << "[DEBUG]: TRANSPOSE" << endl << endl; A.transpuesta(); A.print_mat(); cout << endl << endl << "@@@@@@@@@@@@@@@@@@@" << endl << endl; cout << "[DEBUG]: IDENTITY" << endl << endl; mat B = mat("identityMatrix",5,5); B.print_mat();*/ /*mat B = mat("mat2.csv"); B.print_mat(); mat C = mat(A.M, B.N); C.product(A, B); C.print_mat();*/ } }
cfca821951b10ce4985c8c8e480ed8c2b0e54b99
ab2be5b473cb8e15be6e3d77bf71d8a804b2d314
/Codigo_Fuente/Proyecto_Final/obstacle.cpp
ddd30289c20eab6ea86b0eec768663122705de2e
[]
no_license
MaverickST/Proyecto_Final
4e4465c94a8eca03b9d40aca462b923aae8b69c0
d2908fbd396e9978051f022052b6f6c58891f0ef
refs/heads/master
2023-08-19T22:06:33.448516
2021-10-29T06:43:14
2021-10-29T06:43:14
350,148,407
0
1
null
2021-10-25T00:56:27
2021-03-21T23:39:27
C++
UTF-8
C++
false
false
828
cpp
obstacle.cpp
#include "obstacle.h" Obstacle::Obstacle() {} Obstacle::Obstacle(double _posx, double _posy, double _width, double _height, double _velObst, std::string &_nameSpObst) { posx = _posx; posy = _posy; width = _width; height = _height; vel = _velObst; nameSpObj = _nameSpObst; pixMapObj.load(nameSpObj.c_str()); pixMapObj = pixMapObj.scaled(width, height); } QRectF Obstacle::boundingRect() const { return QRectF (-width/2, -height/2, width, height); } void Obstacle::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { // painter->drawEllipse(boundingRect()); // painter->drawPixmap(QRectF (0, 0, width, height), pixMapObj, boundingRect()); painter->drawPixmap(-width/2, -height/2, pixMapObj, 0, 0, width, height); setPos(posx, posy); }
166f88a07429674fd17080c3d33b7d46df58a7fb
daf2571fb4a1daca589888fb15e319d3f6199b2e
/AddFile.h
0c1330aa7f8f727a9da5708fd628309c8851e182
[]
no_license
chrip/mtb
46cfaebd271361a57225e436d8e97894be30bbba
f87a6a4c9f0de4535772827e63cf021d05e9c8ea
refs/heads/master
2020-12-02T08:10:48.816633
2017-07-10T13:47:16
2017-07-10T13:47:16
96,781,948
1
0
null
null
null
null
UTF-8
C++
false
false
653
h
AddFile.h
#ifndef ADDFILETREAD_H #define ADDFILETREAD_H #include <QObject> #include <QRunnable> class QImage; class ImageContainer; class AddFile : public QObject, public QRunnable { Q_OBJECT public: AddFile(QString imagePath, int totalNumberOfImages); ~AddFile(); void run(); void displayError(QImage *image); signals: void newInputImageLoaded(ImageContainer *img); void errorByLoadingImage(QString imagePath); void updateImageViewer(); void updateProgressBarValue(double val); private: QString imagePath; int totalNumberOfImages; int cumputeMaxScaleLevel(int width, int height); }; #endif // ADDFILETREAD_H
9ec20017ab71e987b9403db77157b12bc382663b
ba876dd8da92e03b7e78eb91a34a389a4c375b83
/code/trunk/p2p/rcs/src/protocol/bt/bt_session.cpp
10ffb4abe8028c2f53e1e3edf07a7cbc789be237
[]
no_license
ivgotcrazy/ResourceCache
dd54183ebe2b46e601fd3d3101026f5be395bb42
d2f8ca1f3ae0f8b9916e09aa6fd7d74443a60b4e
refs/heads/master
2021-07-06T05:08:21.656640
2020-07-19T02:05:51
2020-07-19T02:05:51
123,457,051
0
0
null
null
null
null
GB18030
C++
false
false
12,268
cpp
bt_session.cpp
/*############################################################################# * 文件名 : bt_session.cpp * 创建人 : teck_zhou * 创建时间 : 2013年9月13日 * 文件描述 : BtSession类实现 * 版权声明 : Copyright (c) 2013 BroadInter. All rights reserved. * ##########################################################################*/ #include <boost/bind.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include "bt_session.hpp" #include "bc_typedef.hpp" #include "bc_util.hpp" #include "rcs_util.hpp" #include "rcs_config_parser.hpp" #include "server_socket.hpp" #include "bt_torrent.hpp" #include "client_socket.hpp" #include "bt_peer_connection.hpp" #include "socket_server.hpp" #include "socket_connection.hpp" #include "ip_filter.hpp" #include "communicator.hpp" #include "message.pb.h" namespace BroadCache { /*----------------------------------------------------------------------------- * 描 述: 构造函数 * 参 数: * 返回值: * 修 改: * 时间 2013年10月14日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ BtSession::BtSession() { // 设置session 类型 SetSessionType("bt"); // 解析保存路径 ParseSavePath(); Communicator::GetInstance().RegisterConnectedHandler( boost::bind(&BtSession::OnUgsConnected, this)); } /*----------------------------------------------------------------------------- * 描 述: 析构函数 * 参 数: * 返回值: * 修 改: * 时间 2013年10月14日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ BtSession::~BtSession() { } /*----------------------------------------------------------------------------- * 描 述: 创建socket服务器 * 参 数: [out] servers socket服务器容器 * 返回值: * 修 改: * 时间 2013年10月14日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ bool BtSession::CreateSocketServer(SocketServerVec& servers) { // 从配置文件读取监听IP:PORT std::string listen_addr_str; GET_RCS_CONFIG_STR("bt.common.listen-addr", listen_addr_str); std::vector<EndPoint> ep_vec = ParseEndPoints(listen_addr_str); if (ep_vec.empty()) { LOG(ERROR) << "Invalid listen_addr_str"; return false; } FOREACH(endpoint, ep_vec) { // 根据监听端口创建socket服务器 SocketServerSP server(new TcpSocketServer(sock_ios(), endpoint, boost::bind(&Session::OnNewConnection, this, _1))); servers.push_back(server); } return true; } /*----------------------------------------------------------------------------- * 描 述: 创建被动连接 * 参 数: conn socket连接 * 返回值: * 修 改: * 时间 2013年10月13日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ PeerConnectionSP BtSession::CreatePeerConnection(const SocketConnectionSP& conn) { // 从配置文件获取连接带宽限制即是否内网peer AccessInfo access_info = IpFilter::GetInstance().Access( ip_address(ipv4_address(conn->connection_id().remote.ip))); if (access_info.flags == BLOCKED) return PeerConnectionSP(); PeerType peer_type = (access_info.flags == INNER) ? PEER_INNER : PEER_OUTER; return PeerConnectionSP(new BtPeerConnection(*this, conn, peer_type, access_info.download_speed_limit * 1024, access_info.upload_speed_limit * 1024)); } /*----------------------------------------------------------------------------- * 描 述: 创建主动连接 * 参 数: remote peer地址 * 返回值: * 修 改: * 时间 2013年10月13日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ PeerConnectionSP BtSession::CreatePeerConnection(const EndPoint& remote, PeerType peer_type) { uint64 download_speed_limit = 0, upload_speed_limit = 0; IpFilter& filter = IpFilter::GetInstance(); if (peer_type == PEER_INNER || peer_type == PEER_OUTER) { AccessInfo access_info = filter.Access(ip_address(ipv4_address(remote.ip))); download_speed_limit = access_info.download_speed_limit * 1024; upload_speed_limit = access_info.upload_speed_limit * 1024; } else // PEER_RCS, PEER_INNER_PROXY, PEER_OUTER_PROXY { //TODO: 这里暂时写死 download_speed_limit = 1024 * 1024; upload_speed_limit = 1024 * 1024; } SocketConnectionSP sock_conn(new TcpSocketConnection(sock_ios(), remote)); return PeerConnectionSP(new BtPeerConnection(*this, sock_conn, peer_type, download_speed_limit, upload_speed_limit)); } /*----------------------------------------------------------------------------- * 描 述: 创建BtTorrent * 参 数: [in] hash torrent的InfoHash * [in] save_path torrent保存路径 * 返回值: BtTorrent指针 * 修 改: * 时间 2013年09月10日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ TorrentSP BtSession::CreateTorrent(const InfoHashSP& hash, const fs::path& save_path) { return TorrentSP(new BtTorrent(*this, hash, save_path)); } /*----------------------------------------------------------------------------- * 描 述: 解析BT协议Session的保存路径 * 参 数: * 返回值: * 修 改: * 时间 2013年10月31日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ void BtSession::ParseSavePath() { // 从配置文件读取BT资源文件的保存路径 std::string save_path; GET_RCS_CONFIG_STR("bt.common.save-path", save_path); if (save_path.empty()) { LOG(ERROR) << "Empty save path string"; return; } // 解析配置路径 std::vector<std::string> str_vec = SplitStr(save_path, ' '); for (std::string& str : str_vec) { error_code ec; fs::path full_path = fs::system_complete(fs::path(str), ec); if (ec) { LOG(ERROR) << "Fail to get complete path | " << str; continue; } // 如果路径不存在则创建路径 if (!fs::exists(full_path, ec)) { if (!fs::create_directory(full_path, ec)) { LOG(ERROR) << "Fail to create BT session save path | " << full_path; continue; } } save_paths_.push_back(full_path); } LOG(INFO) << "Success to parse BT session save path"; } /*----------------------------------------------------------------------------- * 描 述: 获取指定路径下所有Torrent的InfoHash * 参 数: [in] save_path 路径 * 返回值: InfoHash * 修 改: * 时间 2013年10月31日 * 作者 teck_zhou * 描述 创建 ----------------------------------------------------------------------------*/ Session::InfoHashVec BtSession::GetTorrentInfoHash(const fs::path& save_path) { if (!fs::is_directory(save_path)) { LOG(ERROR) << "Path is not a directory | " << save_path; return InfoHashVec(); } InfoHashVec hash_vec; fs::directory_iterator end; for (fs::directory_iterator pos(save_path); pos != end; ++pos) { fs::path path(*pos); if (!fs::is_directory(path)) { LOG(WARNING) << "Unexpected path | " << path; continue; } std::string hash_str = path.filename().string(); if (hash_str.size() != 40) // 路径下应该都是40位infohash目录 { LOG(WARNING) << "Invalid path string length | " << hash_str; continue; } hash_vec.push_back(InfoHashSP(new BtInfoHash(FromHex(hash_str)))); } return hash_vec; } /*----------------------------------------------------------------------------- * 描 ? 判断path传入穆肪妒欠裎猻ave_path的最上级父路径 例如 /disk * 参 数: [in] path 路径 * 返回值: bool * 修 改: * 时间 2013年11月2日 * 作者 tom_liu * 描述 创建 ----------------------------------------------------------------------------*/ SavePathVec BtSession::GetSavePath() { return save_paths_; } std::string BtSession::GetSessionProtocol() { return "BT"; } /*------------------------------------------------------------------------------ * 描 述: 获取peer-id字节数 * 参 数: * 返回值: peer-id字节数 * 修 改: * 时间 2013.11.18 * 作者 rosan * 描述 创建 -----------------------------------------------------------------------------*/ constexpr uint32 BtSession::GetPeerIdLength() { return 20; } /*------------------------------------------------------------------------------ * 描 述: 获取本RCS客户端的peer-id * 参 数: * 返回值: 本RCS客户端的peer-id * 修 改: * 时间 2013.11.18 * 作者 rosan * 描述 创建 -----------------------------------------------------------------------------*/ const char* BtSession::GetLocalPeerId() { static const uint32 kPeerIdLength = GetPeerIdLength(); static char peer_id[kPeerIdLength] = "BI/"; // 本客户端的peer-id static bool peer_id_generated = false; // peer-id是否已经生成 if (!peer_id_generated) { boost::random::mt19937 gen; boost::random::uniform_int_distribution<> dist(0, 9); for (uint32 i=3; i<kPeerIdLength; ++i) { peer_id[i] = static_cast<char>(dist(gen) + '0'); } peer_id_generated = true; } return peer_id; } /*------------------------------------------------------------------------------ * 描 述: 上报本地资源 * 参 数: * 返回值: * 修 改: * 时间 2013.11.28 * 作者 rosan * 描述 创建 -----------------------------------------------------------------------------*/ void BtSession::ReportResource() { // 从配置文件读取监听IP:PORT std::string listen_addr_str; GET_RCS_CONFIG_STR("bt.common.listen-addr", listen_addr_str); LOG(INFO) << "Report service address."; BtReportServiceAddressMsg report_address_msg; std::vector<EndPoint> ep_vec = ParseEndPoints(listen_addr_str); FOREACH(endpoint, ep_vec) { EndPointStruct* ep = report_address_msg.add_rcs(); ep->set_ip(endpoint.ip); ep->set_port(endpoint.port); LOG(INFO) << endpoint; } Communicator::GetInstance().SendMsg(report_address_msg); // 从配置文件读取BT资源文件的保存路径 std::string save_path; GET_RCS_CONFIG_STR("bt.common.save-path", save_path); LOG(INFO) << "Report file resource : "; BtReportResourceMsg msg; // 解析配置路径 std::vector<std::string> str_vec = SplitStr(save_path, ' '); for (std::string& str : str_vec) { error_code ec; fs::path full_path = fs::system_complete(fs::path(str), ec); if (ec || !fs::exists(full_path) || !fs::is_directory(full_path)) { continue; } fs::directory_iterator i(full_path); fs::directory_iterator end; for (; i != end; ++i) { static const boost::regex kRegexInfoHash("[A-Za-z0-9]{40}"); fs::path entry = i->path(); std::string filename = entry.filename().string(); if (fs::is_directory(entry) && boost::regex_match(filename, kRegexInfoHash)) { msg.add_info_hash(FromHex(filename)); LOG(INFO) << filename; } } } Communicator::GetInstance().SendMsg(msg); } /*------------------------------------------------------------------------------ * 描 述: 发送keep-alive消息 * 参 数: * 返回值: * 修 改: * 时间 2013.11.28 * 作者 rosan * 描述 创建 -----------------------------------------------------------------------------*/ void BtSession::SendKeepAlive() { BtKeepAliveMsg keep_alive_msg; Communicator::GetInstance().SendMsg(keep_alive_msg); } /*------------------------------------------------------------------------------ * 描 述: 当UGS连接上后的回调函数 * 参 数: * 返回值: * 修 改: * 时间 2013.12.05 * 作者 rosan * 描述 创建 -----------------------------------------------------------------------------*/ void BtSession::OnUgsConnected() { ReportResource(); } } // namespace BroadCache
33c22cccc0f8c4505fbb75afe806101a7d5b12b5
03b5b626962b6c62fc3215154b44bbc663a44cf6
/src/keywords/for_each_in.cpp
6acd8c929cd9542eb7e9d14ea541624d031be5c4
[]
no_license
haochenprophet/iwant
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
1c9bd95280216ee8cd7892a10a7355f03d77d340
refs/heads/master
2023-06-09T11:10:27.232304
2023-05-31T02:41:18
2023-05-31T02:41:18
67,756,957
17
5
null
2018-08-11T16:37:37
2016-09-09T02:08:46
C++
UTF-8
C++
false
false
187
cpp
for_each_in.cpp
#include "for_each_in.h" int Cfor_each_in::my_init(void *p) { this->name = "Cfor_each_in"; this->alias = "for_each_in"; return 0; } Cfor_each_in::Cfor_each_in() { this->my_init(); }
173f5a37d14b1578f815a8c3721b9a7a1dfab16d
52c69024f89ae9aa37aea77fa6f0a6176c2eeb49
/incremental_calibration_examples/incremental_calibration_examples_time_delay/test/test_main.cpp
1b81eb1f27a7e889d38fd875c0df845ed56cb889
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
debuleilei/aslam_incremental_calibration
bdac51aa86ba6bab296d43606e527594de3b6c38
16a44b86b6e7eb5ae4ee247f10c429494697ae0b
refs/heads/master
2020-10-01T18:52:49.080112
2019-02-14T19:41:16
2019-02-14T19:41:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
551
cpp
test_main.cpp
/****************************************************************************** * Copyright (C) 2014 by Jerome Maye * * jerome.maye@gmail.com * ******************************************************************************/ /** \file test_main.cpp \brief This file runs all the tests that were declared with TEST() */ #include <gtest/gtest.h> int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
e844ecf9139af15787ef0dae1779b5d973f82679
01a42b69633daf62a2eb3bb70c5b1b6e2639aa5f
/SCUM_BP_PlaceableActorFortifications_parameters.hpp
d844deda608dd318f9f90e2720c210665f937773
[]
no_license
Kehczar/scum_sdk
45db80e46dac736cc7370912ed671fa77fcb95cf
8d1770b44321a9d0b277e4029551f39b11f15111
refs/heads/master
2022-07-25T10:06:20.892750
2020-05-21T11:45:36
2020-05-21T11:45:36
265,826,541
1
0
null
null
null
null
UTF-8
C++
false
false
2,166
hpp
SCUM_BP_PlaceableActorFortifications_parameters.hpp
#pragma once // Scum 3.79.22573 (UE 4.24) #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace Classes { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function ConZ.PlaceableActorBase.Server_UpdateState struct ABP_PlaceableActorFortifications_C_Server_UpdateState_Params { struct FPlaceableActorStateReplicationHelper* State; // (ConstParm, Parm, ReferenceParm) }; // Function ConZ.PlaceableActorBase.Server_Place struct ABP_PlaceableActorFortifications_C_Server_Place_Params { struct FVector* Location; // (ConstParm, Parm, ZeroConstructor, ReferenceParm, IsPlainOldData) struct FRotator* Rotation; // (ConstParm, Parm, ZeroConstructor, IsPlainOldData) }; // Function ConZ.PlaceableActorBase.OnRep_ReplicatedRotation struct ABP_PlaceableActorFortifications_C_OnRep_ReplicatedRotation_Params { }; // Function ConZ.PlaceableActorBase.OnRep_ReplicatedPlacedLocation struct ABP_PlaceableActorFortifications_C_OnRep_ReplicatedPlacedLocation_Params { }; // Function ConZ.PlaceableActorBase.OnRep_ReplicatedLocation struct ABP_PlaceableActorFortifications_C_OnRep_ReplicatedLocation_Params { }; // Function ConZ.PlaceableActorBase.OnRep_PlacementState struct ABP_PlaceableActorFortifications_C_OnRep_PlacementState_Params { }; // Function ConZ.PlaceableActorBase.OnRep_Ingredients struct ABP_PlaceableActorFortifications_C_OnRep_Ingredients_Params { }; // Function ConZ.PlaceableActorBase.OnRep_IngredientMultiplier struct ABP_PlaceableActorFortifications_C_OnRep_IngredientMultiplier_Params { }; // Function ConZ.PlaceableActorBase.OnRep_Id struct ABP_PlaceableActorFortifications_C_OnRep_Id_Params { }; // Function ConZ.PlaceableActorBase.OnRep_CraftingIndex struct ABP_PlaceableActorFortifications_C_OnRep_CraftingIndex_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
152c1ea20790618de97aac6340dd7072b81ecd6a
0b16906eada728048f2ff61ee3096256e74a9530
/src/Line.hpp
a67c138466b7affe9d70dbad645c62b47b88c33e
[]
no_license
thenathanmcc/TardigradeRenderEngine
80b6c796f628acd4abf1862cfc3e560a5630dffc
2eabb79b59c454a3ffc3adcdf1b57dc09ac7afce
refs/heads/master
2023-02-22T07:10:46.115795
2021-01-24T21:14:21
2021-01-24T21:14:21
273,626,187
0
0
null
null
null
null
UTF-8
C++
false
false
540
hpp
Line.hpp
/* * Line class definition * @author Nathan McCulloch */ #ifndef Line_HPP #define Line_HPP #include <vector> #include "Shader.hpp" #include "Camera.hpp" class Line { public: Line (); Line (glm::vec3 start, glm::vec3 end, Shader* shader); void render(Camera* camera); void updateMVP(glm::mat4 mvp); void setColour(glm::vec3 colour); private: GLuint m_vertexBuffer; GLfloat m_vertices[6]; glm::vec3 m_startPoint; glm::vec3 m_endPoint; glm::mat4 m_MVP; glm::vec3 m_lineColour; protected: Shader* m_shader; }; #endif
80dfbaf6d43a11f9cb3137292f94822ae806fd91
656d2b0fb42461a7bac10561a0fde3dbbe023556
/GameEngine/GameEngine/src/AudioSystem/SoundSource.h
d7650a7a57759ce9af902fde73e94e0ffcde9dc0
[]
no_license
olbo98/D7049E-Game-Engine
674ee73bd5699b3c553d8e409fb1375931cd8f5f
1bd08a5884fdb0560a0d84d92a0099d4b5606586
refs/heads/main
2023-05-09T19:27:07.981369
2021-05-25T13:47:16
2021-05-25T13:47:16
355,449,754
0
0
null
2021-05-24T13:47:59
2021-04-07T07:20:18
C++
UTF-8
C++
false
false
414
h
SoundSource.h
#pragma once #include <AL\al.h> class SoundSource { public: SoundSource(); ~SoundSource(); //Playing the sound with the right buffer void Play(const ALuint buffer_to_play); private: /* Speaker variables, default settings */ ALuint p_Source; float p_Pitch = 1.f; float p_Gain = 1.f; float p_Position[3] = { 0,0,0 }; float p_Velocity[3] = { 0,0,0 }; bool p_LoopSound = false; ALuint p_Buffer = 0; };
7831e5ac1571887b8192c855cc1129d7188228f6
b9dd98d301aa2055616f21fd1026a5e4ff9e81fb
/Codeforces/143A - Help Vasilisa the Wise 2.cpp
a4d5ce5716d09fbb9a0816da02c73fbe1cbf66a3
[]
no_license
AlaaAbuHantash/Competitive-Programming
f587fcbbe9da33114c6bed3eb76f5cf0429fbf95
179a8473662d04b8c5c129e852f6eab075e80fb2
refs/heads/master
2021-07-25T08:17:49.841307
2018-08-06T10:06:54
2018-08-06T10:06:54
128,920,319
2
1
null
null
null
null
UTF-8
C++
false
false
1,288
cpp
143A - Help Vasilisa the Wise 2.cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <queue> #include <map> #include <set> #include <utility> #include <stack> #include <cstring> #include <math.h> #include<cstdio> #include<deque> #include<sstream> /* * You got a dream, you gotta protect it. */ #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) #define sz(v) ((int)v.size()) #define rep(i,m) for(int i=0;i<(int)(m);i++) #define oo ((int) 1e9) #define mp make_pair #define pi 2 * acos(0); #define eps 1e-6 using namespace std; int dx[] = {0 , 0 , 1 ,-1 , 1 , 1 , -1 , -1 } ; int dy[] = {1 , -1 , 0 , 0 , 1 ,-1 , 1 , -1 } ; string s,res; int a,b,c,d,e,f; bool gg; int main() { // freopen("test.in" , "rt" , stdin); scanf("%d%d%d%d%d%d",&a,&b,&c,&d,&e,&f); gg=false ; for (int i =1 ; i<=9 ; i++) { for(int j=1;j<=9;j++){ for(int k=1;k<=9;k++){ for(int g=1;g<=9;g++) { if (i+j==a && k+g ==b&& i+k == c && j+g == d && i+g ==e && j+k ==f && i!=j && i!=k &&i!=g && j!=k && j!=g && k!=g ) { printf("%d %d\n" ,i,j); printf("%d %d\n" ,k,g); gg=true; } if(gg)break; } if(gg)break; } if(gg)break; } if(gg)break; } if (!gg)printf("-1\n"); return 0 ; }
6ddf145ec9819c5ecbe675fed74db7c940100664
c9e0d986ff97a074732272cec455eae2f2387fda
/Game/Labyrinth_Game/MazeMan.cpp
74f7b100860fd3a7f8284e485ec9f8167acb426c
[]
no_license
rainbowhxch/first-step
2b70b00e6fb32642cb6f76647453d6de5b75d068
672f3438d433ee4cebb12d99910660f0f87a5c9e
refs/heads/master
2022-06-22T13:55:25.781149
2020-05-08T01:33:12
2020-05-08T01:33:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,473
cpp
MazeMan.cpp
#include "MazeMan.h" MazeMan::MazeMan(char man,char manface) { m_cMan = man; m_cManFace = manface; m_iSteps = 0; } void MazeMan::setMap(MazeMap * map) { m_pMap = map; } void MazeMan::setPosition(int x,int y) { unsigned long numWritten; HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); m_COORDManCurrentPosition.X = x; m_COORDManCurrentPosition.Y = y; FillConsoleOutputCharacter(handle,m_cMan,1,m_COORDManCurrentPosition,&numWritten); } void MazeMan::moveForward(direction direct) { unsigned long numWritten; HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE); FillConsoleOutputCharacter(handle,m_pMap->m_cRoad,1,m_COORDManCurrentPosition,&numWritten); switch(direct) { case U: m_COORDManCurrentPosition.Y -= 1; break; case D: m_COORDManCurrentPosition.Y += 1; break; case L: m_COORDManCurrentPosition.X -= 1; break; case R: m_COORDManCurrentPosition.X += 1; break; default: break; } FillConsoleOutputCharacter(handle,m_cMan,1,m_COORDManCurrentPosition,&numWritten); m_cManFace = direct; } bool MazeMan::walkUp() { if (m_pMap->getMap()[m_COORDManCurrentPosition.Y - 1][m_COORDManCurrentPosition.X]) return false; else moveForward(U); return true; } bool MazeMan::walkDown() { if (m_pMap->getMap()[m_COORDManCurrentPosition.Y + 1][m_COORDManCurrentPosition.X]) return false; else moveForward(D); return true; } bool MazeMan::walkLeft() { if (m_pMap->getMap()[m_COORDManCurrentPosition.Y][m_COORDManCurrentPosition.X - 1]) return false; else moveForward(L); return true; } bool MazeMan::walkRight() { if (m_pMap->getMap()[m_COORDManCurrentPosition.Y][m_COORDManCurrentPosition.X + 1]) return false; else moveForward(R); return true; } void MazeMan::start() { while(true) { m_pMap->pintMazeMap(); switch(m_cManFace) { case U: walkRight() || walkUp() || walkLeft() || walkDown(); break; case D: walkLeft() || walkDown() || walkRight() || walkUp(); break; case L: walkUp() || walkLeft() || walkDown() || walkRight(); break; case R: walkDown() || walkRight() || walkUp() || walkLeft(); break; default: break; } m_iSteps++; if(m_COORDManCurrentPosition.X == m_pMap->m_COORDExitPostion.X && m_COORDManCurrentPosition.Y == m_pMap->m_COORDExitPostion.Y) break; std::cout << "You have walk " << m_iSteps - 1 << " step."; Sleep(500); } }
6b31103d524b08b6d023c353238ad26ecbe1a547
8f3c088b5ff6c995f9e0be2ee9375931d96e7a64
/queue/queue/main.cpp
50696dfa882d70793471c3204489844a0a91e279
[]
no_license
dashachernyh/mp2-lab4
6de1e5f659b2b5a5edfcb1659327f7282042cff4
d9f75f3e6a893ccdbec98b5ada1bcf277fe63e6a
refs/heads/master
2020-11-25T09:24:54.104257
2019-12-24T20:54:42
2019-12-24T20:54:42
228,594,948
0
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
main.cpp
#include"queue-list.h" #include<conio.h> #include<iostream> using namespace std; int main() { TQueue<int> q; int el; bool b; cin >> el; b = q.IsEmpty(); cout<< b<<endl; q.Push(el); b = q.IsEmpty(); cout<<b<<endl; q.Pop(); for (int i = 0; i <10; i++) { cin >> el; q.Push(el); } b=q.IsFull(); cout << b<<endl; el = q.Pop(); cout << el<<endl; _getch(); }
afbc5789df6b2a282370b65549bd5ab6b3a7f23b
9da6ffc55ba8a19192bd0efad09657758de4e792
/maxflow/loj 127.cpp
8cc0bc57dba2d2ebd27bd100fb21527edd8f1191
[]
no_license
fsq/codeforces
b771cb33c67fb34168c8ee0533a67f16673f9057
58f3b66439457a7368bb40af38ceaf89b9275b36
refs/heads/master
2021-05-11T03:12:27.130277
2020-10-16T16:55:03
2020-10-16T16:55:03
117,908,849
0
0
null
null
null
null
UTF-8
C++
false
false
3,370
cpp
loj 127.cpp
#include <cstdio> #include <cstring> #include <vector> #include <algorithm> #include <numeric> #include <memory> #include <list> #include <climits> using namespace std; #define PB push_back #define F first #define S second #define REP(i,from,to) for(auto i=(from); i<=(to); ++i) #define PER(i,from,to) for(auto i=(from); i>=(to); --i) #define REP_IF(i,from,to,assert) for(auto i=(from); i<=(to); ++i) if (assert) #define FOR(i,less_than) for (auto i=0; i<(less_than); ++i) #define FORI(i, container) for (auto i=0; i<(container).size(); ++i) #define FORI_IF(i, container, assert) for (auto i=0; i<(container).size(); ++i) if (assert) #define ROFI(i, container) for (auto i=(container).size()-1; i>=0; --i) #define FOREACH(elem, container) for (auto elem : (container)) #define FILL(container, value) memset(container, value, sizeof(container)) #define ALL(container) (container).begin(), (container).end() #define SZ(container) (int)((container).size()) #define BACK(set_map) *prev((set_map).end(), 1) #define FRONT(set_map) *(set_map).begin() inline void _RD(int &x) { scanf("%d", &x); } inline void _RD(long long &x) { scanf("%lld", &x); } inline void _RD(double &x) { scanf("%lf", &x); } inline void _RD(long double &x) { scanf("%Lf", &x); } inline void _RD(char &x) { scanf(" %c", &x); } inline void RD() {} template<class T, class... U> inline void RD(T &head, U &... tail) { _RD(head); RD(tail...); } using PII = pair<int,int>; using LL = long long; using VI = vector<int>; using VLL = vector<LL>; using VVI = vector<VI>; const int MAXN = 1301; class Node { public: int h, p, sz, e; int N[MAXN]; Node() {h=e=p=sz=0;} } V[MAXN]; int n, m, src, snk; int f[MAXN][MAXN], c[MAXN][MAXN]; inline void link(int x, int y, int cap) { c[x][y] = cap; V[x].N[V[x].sz++] = y; V[y].N[V[y].sz++] = x; } void build() { int u,v, cap; REP(i, 1, m) { scanf("%d %d %d", &u, &v, &cap); link(u, v, cap); } } inline int cf(int u, int v) { return c[u][v]-f[u][v]+f[v][u]; } inline void _push(int u, int v, int fl) { f[u][v] += fl, V[u].e -= fl, V[v].e += fl; } inline void relabel(int u) { int h = n<<1; FOR(i, V[u].sz) if (cf(u, V[u].N[i])>0) h = min(h, V[V[u].N[i]].h+1); V[u].h = h; } inline void push(int u, int v) { int fl = min(V[u].e, cf(u, v)); if (f[v][u]>0) _push(v, u, -fl); else _push(u, v, fl); } void discharge(int u) { for (Node& n =V[u]; n.e;) if (n.p==n.sz) { relabel(u); n.p = 0; } else { int v = n.N[n.p]; if (cf(u,v)>0 && n.h==V[v].h+1) push(u, v); else ++n.p; } } inline void init() { V[src].h = n; FOR(i, V[src].sz) _push(src, V[src].N[i], c[src][V[src].N[i]]); } int relabel_to_front() { init(); list<int> ls; REP(i, 1, n) if (i!=src && i!=snk) ls.PB(i); for (auto it=ls.begin(); it!=ls.end(); ++it) { int u = *it, oldh = V[u].h; discharge(u); if (V[u].h>oldh) ls.splice(ls.begin(), ls, it); } return V[snk].e; } int main() { scanf("%d %d %d %d", &n,&m,&src,&snk); build(); printf("%d\n", relabel_to_front()); return 0; }
dad6e63bf6e33f60e9072612bc75865c56c249fa
50df5a8accbcb4fd216d95304f08882ec4d74bde
/toonz/sources/image/pli/pli_io.cpp
d003e5e2770263ece4b1da017388ad3ad22dfeef
[ "BSD-3-Clause" ]
permissive
opentoonz/opentoonz
87dbc490b67a23c9912a0f988fb2b0473c9b50ba
0a2a4a9ec52e0a0a33f73d709e034538800cfb51
refs/heads/master
2023-08-17T06:56:15.619842
2023-08-16T12:08:25
2023-08-16T12:08:25
54,221,232
4,392
710
NOASSERTION
2023-09-11T15:55:51
2016-03-18T17:55:48
C++
UTF-8
C++
false
false
79,076
cpp
pli_io.cpp
#include <memory> #include "tmachine.h" #include "pli_io.h" #include "tcommon.h" #include "timage_io.h" #include "tvectorimage.h" //#include "tstrokeoutline.h" #include "tsimplecolorstyles.h" #include "tcontenthistory.h" #include "tfilepath_io.h" //#include <fstream.h> #include "../compatibility/tfile_io.h" #include "tenv.h" /*=====================================================================*/ #if defined(MACOSX) #include <architecture/i386/io.h> #elif defined(_WIN32) #include <io.h> #endif using namespace std; typedef TVectorImage::IntersectionBranch IntersectionBranch; #if !defined(TNZ_LITTLE_ENDIAN) TNZ_LITTLE_ENDIAN undefined !! #endif static const int c_majorVersionNumber = 150; static const int c_minorVersionNumber = 0; /*=====================================================================*/ /*=====================================================================*/ /*=====================================================================*/ inline void ulongFromDouble1(double x, TUINT32 &hi, TUINT32 &lo) { assert(x < 1.0); // x+=1.0; TUINT32 *l = (TUINT32 *)&x; #if TNZ_LITTLE_ENDIAN hi = l[1], lo = l[0]; #else hi = l[0], lo = l[1]; #endif // return (hi&0XFFFFF)<<12 | ((lo&0xFFE00000)>>20); } /*=====================================================================*/ inline double doubleFromUlong1(TUINT32 hi, TUINT32 lo) { // assert((lo&0X00000001)==0); TUINT32 l[2]; #if TNZ_LITTLE_ENDIAN l[1] = hi; l[0] = lo; #else l[0] = hi; l[1] = lo; #endif return *(double *)l; // - 1; } /*=====================================================================*/ static TThickPoint operator*(const TAffine &aff, const TThickPoint &p) { TPointD p1(p.x, p.y); return TThickPoint(aff * p1, p.thick); } /*=====================================================================*/ class MyOfstream final : public Tofstream { public: MyOfstream(const TFilePath &path) : Tofstream(path) {} MyOfstream &operator<<(TUINT32 n) { TUINT32 app; #if TNZ_LITTLE_ENDIAN app = n; #else UCHAR *uc = (UCHAR *)&n; app = *(uc) | (*(uc + 1)) << 8 | (*(uc + 2)) << 16 | (*(uc + 3)) << 24; #endif write((char *)&app, sizeof(TUINT32)); return *this; } MyOfstream &operator<<(USHORT n) { USHORT app; #if TNZ_LITTLE_ENDIAN app = n; #else UCHAR *uc = (UCHAR *)&n; app = *(uc) | (*(uc + 1)) << 8; #endif write((char *)&app, sizeof(USHORT)); return *this; } MyOfstream &operator<<(UCHAR un) { write((char *)&un, sizeof(UCHAR)); return *this; } MyOfstream &operator<<(char un) { write((char *)&un, sizeof(char)); return *this; } MyOfstream &operator<<(const TRaster32P &r); MyOfstream &operator<<(const std::string &r); MyOfstream &writeBuf(void *un, UINT s) { write((char *)un, s); return *this; } }; /*=====================================================================*/ MyOfstream &MyOfstream::operator<<(const TRaster32P &r) { assert(r->getLx() == r->getWrap()); (*this) << (USHORT)r->getLx(); (*this) << (USHORT)r->getLy(); r->lock(); MyOfstream &ret = writeBuf(r->getRawData(), r->getLx() * r->getLy() * r->getPixelSize()); r->unlock(); return ret; } /*=====================================================================*/ MyOfstream &MyOfstream::operator<<(const std::string &s) { (*this) << (USHORT)s.size(); for (UINT i = 0; i < s.size(); i++) (*this) << (UCHAR)(s[i]); return *this; } /*=====================================================================*/ class MyIfstream // The input is done without stl; it was crashing in release // version loading textures!! { private: bool m_isIrixEndian; FILE *m_fp; public: MyIfstream() : m_isIrixEndian(false) { m_fp = 0; } ~MyIfstream() { if (m_fp) fclose(m_fp); } void setEndianess(bool isIrixEndian) { m_isIrixEndian = isIrixEndian; } MyIfstream &operator>>(TUINT32 &un); MyIfstream &operator>>(string &un); MyIfstream &operator>>(USHORT &un); MyIfstream &operator>>(UCHAR &un); MyIfstream &operator>>(char &un); void open(const TFilePath &filename); void close() { if (m_fp) fclose(m_fp); m_fp = 0; } TUINT32 tellg() { return (TUINT32)ftell(m_fp); } // void seekg(TUINT32 pos, ios_base::seek_dir type); void seekg(TUINT32 pos, int type); void read(char *m_buf, int length) { fread((void *)m_buf, sizeof(char), length, m_fp); } }; /*=====================================================================*/ void MyIfstream::open(const TFilePath &filename) { try { m_fp = fopen(filename, "rb"); } catch (TException &) { throw TImageException(filename, "File not found"); } } /*=====================================================================*/ void MyIfstream::seekg(TUINT32 pos, int type) { if (type == ios_base::beg) fseek(m_fp, pos, SEEK_SET); else if (type == ios_base::cur) fseek(m_fp, pos, SEEK_CUR); else assert(false); } /*=====================================================================*/ inline MyIfstream &MyIfstream::operator>>(UCHAR &un) { int ret = fread((void *)&un, sizeof(UCHAR), 1, m_fp); if (ret < 1) throw TException("corrupted pli file: unexpected end of file"); // read((char *)&un, sizeof(UCHAR)); return *this; } /*=====================================================================*/ inline MyIfstream &MyIfstream::operator>>(char &un) { int ret = fread((void *)&un, sizeof(char), 1, m_fp); if (ret < 1) throw TException("corrupted pli file: unexpected end of file"); // read((char *)&un, sizeof(char)); return *this; } /*=====================================================================*/ inline MyIfstream &MyIfstream::operator>>(USHORT &un) { int ret = fread((void *)&un, sizeof(USHORT), 1, m_fp); if (ret < 1) throw TException("corrupted pli file: unexpected end of file"); // read((char *)&un, sizeof(USHORT)); if (m_isIrixEndian) un = ((un & 0xff00) >> 8) | ((un & 0x00ff) << 8); return *this; } /*=====================================================================*/ inline MyIfstream &MyIfstream::operator>>(TUINT32 &un) { int ret = fread((void *)&un, sizeof(TUINT32), 1, m_fp); if (ret < 1) throw TException("corrupted pli file: unexpected end of file"); // read((char *)&un, sizeof(TUINT32)); if (m_isIrixEndian) un = ((un & 0xff000000) >> 24) | ((un & 0x00ff0000) >> 8) | ((un & 0x0000ff00) << 8) | ((un & 0x000000ff) << 24); return *this; } /*=====================================================================*/ inline MyIfstream &MyIfstream::operator>>(string &un) { string s = ""; USHORT length; (*this) >> length; for (UINT i = 0; i < length; i++) { UCHAR ch; (*this) >> ch; s.append(1, ch); } un = s; return *this; } /*=====================================================================*/ UINT TStyleParam::getSize() { switch (m_type) { case SP_BYTE: return 1; case SP_INT: return 4; case SP_DOUBLE: return 4; case SP_USHORT: return 2; case SP_RASTER: return 2 + 2 + m_r->getLx() * m_r->getLy() * m_r->getPixelSize(); case SP_STRING: return (m_string.size() + sizeof(USHORT)); default: assert(false); return 0; } } /*=====================================================================*/ #define CHECK_FOR_READ_ERROR(filePath) #define CHECK_FOR_WRITE_ERROR(filePath) \ { \ if (m_oChan->fail() /*m_oChan.flags()&(ios::failbit)*/) { \ m_lastError = WRITE_ERROR; \ throw TImageException(filePath, "Error on writing file"); \ } \ } const TUINT32 c_magicNt = 0x4D494C50; const TUINT32 c_magicIrix = 0x504C494D; class TagElem { public: PliTag *m_tag; TUINT32 m_offset; TagElem *m_next; TagElem(PliTag *tag, TUINT32 offset, TagElem *next = NULL) : m_tag(tag), m_offset(offset), m_next(next) {} TagElem(const TagElem &elem) : m_tag(elem.m_tag), m_offset(elem.m_offset), m_next(NULL) {} ~TagElem() { if (m_tag) delete m_tag; } }; /*=====================================================================*/ class TContentHistory; class ParsedPliImp { public: UCHAR m_majorVersionNumber; UCHAR m_minorVersionNumber; bool m_versionLocked = false; USHORT m_framesNumber; double m_thickRatio; double m_maxThickness; double m_autocloseTolerance; bool m_isIrixEndian; TFilePath m_filePath; UCHAR m_currDynamicTypeBytesNum; TUINT32 m_tagLength; TUINT32 m_bufLength; std::unique_ptr<UCHAR[]> m_buf; TAffine m_affine; int m_precisionScale; std::map<TFrameId, int> m_frameOffsInFile; PliTag *readTextTag(); PliTag *readPaletteTag(); PliTag *readPaletteWithAlphaTag(); PliTag *readThickQuadraticChainTag(bool isLoop); PliTag *readColorTag(); PliTag *readStyleTag(); PliTag *readGroupTag(); PliTag *readImageTag(); PliTag *readGeometricTransformationTag(); PliTag *readDoublePairTag(); PliTag *readBitmapTag(); PliTag *readIntersectionDataTag(); PliTag *readOutlineOptionsTag(); PliTag *readPrecisionScaleTag(); PliTag *readAutoCloseToleranceTag(); inline void readDynamicData(TUINT32 &val, TUINT32 &bufOffs); inline bool readDynamicData(TINT32 &val, TUINT32 &bufOffs); inline void readFloatData(double &val, TUINT32 &bufOffs); inline UINT readRasterData(TRaster32P &r, TUINT32 &bufOffs); inline void writeFloatData(double val); inline void readUShortData(USHORT &val, TUINT32 &bufOffs); inline void readTUINT32Data(TUINT32 &val, TUINT32 &bufOffs); TUINT32 writeTagHeader(UCHAR type, UINT tagLength); TUINT32 writeTextTag(TextTag *tag); TUINT32 writePaletteTag(PaletteTag *tag); TUINT32 writePaletteWithAlphaTag(PaletteWithAlphaTag *tag); TUINT32 writeThickQuadraticChainTag(ThickQuadraticChainTag *tag); TUINT32 writeGroupTag(GroupTag *tag); TUINT32 writeImageTag(ImageTag *tag); TUINT32 writeColorTag(ColorTag *tag); TUINT32 writeStyleTag(StyleTag *tag); TUINT32 writeGeometricTransformationTag(GeometricTransformationTag *tag); TUINT32 writeDoublePairTag(DoublePairTag *tag); TUINT32 writeBitmapTag(BitmapTag *tag); TUINT32 writeIntersectionDataTag(IntersectionDataTag *tag); TUINT32 writeOutlineOptionsTag(StrokeOutlineOptionsTag *tag); TUINT32 writePrecisionScaleTag(PrecisionScaleTag *tag); TUINT32 writeAutoCloseToleranceTag(AutoCloseToleranceTag *tag); inline void writeDynamicData(TUINT32 val); inline void writeDynamicData(TINT32 val, bool isNegative); inline void setDynamicTypeBytesNum(int minval, int maxval); PliTag *findTagFromOffset(UINT tagOffs); UINT findOffsetFromTag(PliTag *tag); TagElem *findTag(PliTag *tag); USHORT readTagHeader(); public: enum errorType { NO__ERROR = 0, NO_FILE, BAD_MAGIC, PREMATURE_EOF, WRITE_ERROR, ERRORTYPE_HOW_MANY }; errorType m_lastError; string m_creator; TagElem *m_firstTag; TagElem *m_lastTag; TagElem *m_currTag; MyIfstream m_iChan; MyOfstream *m_oChan; ParsedPliImp(); ParsedPliImp(UCHAR majorVersionNumber, UCHAR minorVersionNumber, USHORT framesNumber, UCHAR precision, UCHAR maxThickness, double autocloseTolerance); ParsedPliImp(const TFilePath &filename, bool readInfo); ~ParsedPliImp(); void setFrameCount(int frameCount); int getFrameCount(); void loadInfo(bool readPalette, TPalette *&palette, TContentHistory *&history); ImageTag *loadFrame(const TFrameId &frameNumber); TagElem *readTag(); void writeTag(TagElem *tag); bool addTag(PliTag *tag, bool addFront = false); bool addTag(const TagElem &tag, bool addFront = false); bool writePli(const TFilePath &filename); inline void WRITE_UCHAR_FROM_DOUBLE(double dval); inline void WRITE_SHORT_FROM_DOUBLE(double dval); }; /*=====================================================================*/ double ParsedPli::getMaxThickness() const { return imp->m_maxThickness; }; void ParsedPli::setMaxThickness(double maxThickness) { imp->m_maxThickness = maxThickness; }; /* indirect inclusion of <math.h> causes 'abs' to return double on Linux */ #if defined(LINUX) || defined(FREEBSD) || (defined(_WIN32) && defined(__GNUC__)) || defined(HAIKU) template <typename T> T abs_workaround(T a) { return (a > 0) ? a : -a; } #define abs abs_workaround #endif /*=====================================================================*/ static inline UCHAR complement1(char val, bool isNegative = false) { if (val == 0) return isNegative ? 0x80 : 0; return (UCHAR)(abs(val) | (val & 0x80)); } /*=====================================================================*/ static inline USHORT complement1(short val, bool isNegative = false) { if (val == 0) return isNegative ? 0x8000 : 0; return (USHORT)(abs(val) | (val & 0x8000)); } /*=====================================================================*/ static inline TUINT32 complement1(TINT32 val, bool isNegative = false) { if (val == 0) return isNegative ? 0x80000000 : 0; return (TUINT32)(abs(val) | (val & 0x80000000)); } /*=====================================================================*/ static inline short complement2(USHORT val) { return (val & 0x8000) ? -(val & 0x7fff) : (val & 0x7fff); } #if defined(LINUX) || defined(FREEBSD) || (defined(_WIN32) && defined(__GNUC__)) #undef abs #endif /*=====================================================================*/ ParsedPliImp::ParsedPliImp() : m_majorVersionNumber(0) , m_minorVersionNumber(0) , m_framesNumber(0) , m_thickRatio(1.0) , m_maxThickness(0.0) , m_firstTag(NULL) , m_lastTag(NULL) , m_currTag(NULL) , m_iChan() , m_oChan(0) , m_bufLength(0) , m_affine() , m_precisionScale(REGION_COMPUTING_PRECISION) , m_creator("") {} /*=====================================================================*/ ParsedPliImp::ParsedPliImp(UCHAR majorVersionNumber, UCHAR minorVersionNumber, USHORT framesNumber, UCHAR precision, UCHAR maxThickness, double autocloseTolerance) : m_majorVersionNumber(majorVersionNumber) , m_minorVersionNumber(minorVersionNumber) , m_framesNumber(framesNumber) , m_maxThickness(maxThickness) , m_autocloseTolerance(autocloseTolerance) , m_thickRatio(maxThickness / 255.0) , m_firstTag(NULL) , m_lastTag(NULL) , m_currTag(NULL) , m_iChan() , m_oChan(0) , m_bufLength(0) , m_affine(TScale(1.0 / pow(10.0, precision))) , m_precisionScale(REGION_COMPUTING_PRECISION) , m_creator("") {} /*=====================================================================*/ ParsedPliImp::ParsedPliImp(const TFilePath &filename, bool readInfo) : m_majorVersionNumber(0) , m_minorVersionNumber(0) , m_framesNumber(0) , m_thickRatio(1.0) , m_maxThickness(0) , m_firstTag(NULL) , m_lastTag(NULL) , m_currTag(NULL) , m_iChan() , m_oChan(0) , m_bufLength(0) , m_precisionScale(REGION_COMPUTING_PRECISION) , m_creator("") { TUINT32 magic; // TUINT32 fileLength; TagElem *tagElem; UCHAR maxThickness; // cerr<<m_filePath<<endl; //#ifdef _WIN32 m_iChan.open(filename); // m_iChan.exceptions( ios::failbit | ios::badbit); //#else // m_iChan.open(filename.c_str(), ios::in); //#endif m_iChan >> magic; CHECK_FOR_READ_ERROR(filename); if (magic == c_magicNt) { #if TNZ_LITTLE_ENDIAN m_isIrixEndian = false; #else m_isIrixEndian = true; #endif m_iChan.setEndianess(false); } else if (magic == c_magicIrix) { #if TNZ_LITTLE_ENDIAN m_isIrixEndian = true; #else m_isIrixEndian = false; #endif m_iChan.setEndianess(true); } else { m_lastError = BAD_MAGIC; throw TImageException(filename, "Error on reading magic number"); } m_iChan >> m_majorVersionNumber; m_iChan >> m_minorVersionNumber; // Loading pli versions AFTER current one is NOT SUPPORTED. This means that an // exception is directly called at this point. if (m_majorVersionNumber > c_majorVersionNumber || (m_majorVersionNumber == c_majorVersionNumber && m_minorVersionNumber > c_minorVersionNumber)) throw TImageVersionException(filename, m_majorVersionNumber, m_minorVersionNumber); if (m_majorVersionNumber > 5 || (m_majorVersionNumber == 5 && m_minorVersionNumber >= 8)) m_iChan >> m_creator; if (m_majorVersionNumber < 5) { TUINT32 fileLength; m_iChan >> fileLength; m_iChan >> m_framesNumber; m_iChan >> maxThickness; m_thickRatio = maxThickness / 255.0; if (readInfo) return; CHECK_FOR_READ_ERROR(filename); m_currDynamicTypeBytesNum = 2; while ((tagElem = readTag())) { if (!m_firstTag) m_firstTag = m_lastTag = tagElem; else { m_lastTag->m_next = tagElem; m_lastTag = m_lastTag->m_next; } } for (tagElem = m_firstTag; tagElem; tagElem = tagElem->m_next) tagElem->m_offset = 0; m_iChan.close(); } } /*=====================================================================*/ extern TPalette *readPalette(GroupTag *paletteTag, int majorVersion, int minorVersion); /*=====================================================================*/ const TFrameId &ParsedPli::getFrameNumber(int index) { assert(imp->m_frameOffsInFile.size() == imp->m_framesNumber); std::map<TFrameId, int>::iterator it = imp->m_frameOffsInFile.begin(); std::advance(it, index); return it->first; } /*=====================================================================*/ void ParsedPliImp::loadInfo(bool readPlt, TPalette *&palette, TContentHistory *&history) { TUINT32 fileLength; m_iChan >> fileLength; m_iChan >> m_framesNumber; if (!((m_majorVersionNumber == 5 && m_minorVersionNumber >= 7) || (m_majorVersionNumber > 5))) { UCHAR maxThickness; m_iChan >> maxThickness; m_thickRatio = maxThickness / 255.0; } else m_thickRatio = 0; UCHAR ii, d, s = 2; if (m_majorVersionNumber > 6 || (m_majorVersionNumber == 6 && m_minorVersionNumber >= 5)) m_iChan >> s; m_iChan >> ii; m_iChan >> d; m_autocloseTolerance = ((double)(s - 1)) * (ii + 0.01 * d); m_currDynamicTypeBytesNum = 2; // m_frameOffsInFile = new int[m_framesNumber]; // for (int i=0; i<m_framesNumber; i++) // m_frameOffsInFile[i] = -1; TUINT32 pos = m_iChan.tellg(); USHORT type; while ((type = readTagHeader()) != PliTag::END_CNTRL) { if (type == PliTag::IMAGE_BEGIN_GOBJ) { USHORT frame; m_iChan >> frame; QByteArray suffix; if (m_majorVersionNumber >= 150) { TUINT32 suffixLength; m_iChan >> suffixLength; if ((int)suffixLength > 0) { suffix.resize(suffixLength); m_iChan.read(suffix.data(), suffixLength); } } else { char letter = 0; if (m_majorVersionNumber > 6 || (m_majorVersionNumber == 6 && m_minorVersionNumber >= 6)) m_iChan >> letter; if (letter > 0) suffix = QByteArray(&letter, 1); } m_frameOffsInFile[TFrameId(frame, QString::fromUtf8(suffix))] = m_iChan.tellg(); // m_iChan.seekg(m_tagLength, ios::cur); if (m_majorVersionNumber < 150) m_iChan.seekg(m_tagLength - 2, ios::cur); } else if (type == PliTag::STYLE_NGOBJ) { m_iChan.seekg(pos, ios::beg); TagElem *tagElem = readTag(); addTag(*tagElem); tagElem->m_tag = 0; delete tagElem; } else if (type == PliTag::TEXT) { m_iChan.seekg(pos, ios::beg); TagElem *tagElem = readTag(); TextTag *textTag = (TextTag *)tagElem->m_tag; history = new TContentHistory(true); history->deserialize(QString::fromStdString(textTag->m_text)); delete tagElem; } else if (type == PliTag::GROUP_GOBJ && readPlt) // la paletta!!! { m_iChan.seekg(pos, ios::beg); TagElem *tagElem = readTag(); GroupTag *grouptag = (GroupTag *)tagElem->m_tag; if (grouptag->m_type == (UCHAR)GroupTag::PALETTE) { readPlt = false; palette = readPalette((GroupTag *)tagElem->m_tag, m_majorVersionNumber, m_minorVersionNumber); } else assert(grouptag->m_type == (UCHAR)GroupTag::STROKE); delete tagElem; } else { m_iChan.seekg(m_tagLength, ios::cur); switch (type) { case PliTag::SET_DATA_8_CNTRL: m_currDynamicTypeBytesNum = 1; break; case PliTag::SET_DATA_16_CNTRL: m_currDynamicTypeBytesNum = 2; break; case PliTag::SET_DATA_32_CNTRL: m_currDynamicTypeBytesNum = 4; break; default: break; } } pos = m_iChan.tellg(); } assert(m_frameOffsInFile.size() == m_framesNumber); // palette = new TPalette(); // for (int i=0; i<256; i++) // palette->getPage(0)->addStyle(TPixel::Black); } /*=====================================================================*/ USHORT ParsedPliImp::readTagHeader() { UCHAR ucharTagType, tagLengthId; USHORT tagType; // unused variable #if 0 TUINT32 tagOffset = m_iChan.tellg(); #endif m_iChan >> ucharTagType; if (ucharTagType == 0xFF) { m_iChan >> tagType; tagLengthId = tagType >> 14; tagType &= 0x3FFF; } else { tagType = ucharTagType; tagLengthId = tagType >> 6; tagType &= 0x3F; } m_tagLength = 0; switch (tagLengthId) { case 0x0: m_tagLength = 0; break; case 0x1: { UCHAR clength; m_iChan >> clength; m_tagLength = clength; break; } case 0x2: { USHORT slength; m_iChan >> slength; m_tagLength = slength; break; } case 0x3: m_iChan >> m_tagLength; break; default: assert(false); break; } return tagType; } /*=====================================================================*/ ImageTag *ParsedPliImp::loadFrame(const TFrameId &frameNumber) { m_currDynamicTypeBytesNum = 2; TagElem *tagElem = m_firstTag; while (tagElem) { TagElem *auxTag = tagElem; tagElem = tagElem->m_next; delete auxTag; } m_firstTag = 0; // PliTag *tag; USHORT type = PliTag::IMAGE_BEGIN_GOBJ; USHORT frame; QByteArray suffix; TFrameId frameId; // cerco il frame std::map<TFrameId, int>::iterator it; it = m_frameOffsInFile.find(frameNumber); if (it != m_frameOffsInFile.end()) { m_iChan.seekg(it->second, ios::beg); frameId = it->first; } else while ((type = readTagHeader()) != PliTag::END_CNTRL) { if (type == PliTag::IMAGE_BEGIN_GOBJ) { m_iChan >> frame; if (m_majorVersionNumber >= 150) { TUINT32 suffixLength; m_iChan >> suffixLength; suffix.resize(suffixLength); m_iChan.read(suffix.data(), suffixLength); } else { char letter = 0; if (m_majorVersionNumber > 6 || (m_majorVersionNumber == 6 && m_minorVersionNumber >= 6)) { m_iChan >> letter; if (letter > 0) suffix = QByteArray(&letter, 1); } } frameId = TFrameId(frame, QString::fromUtf8(suffix)); m_frameOffsInFile[frameId] = m_iChan.tellg(); if (frameId == frameNumber) break; } else m_iChan.seekg(m_tagLength, ios::cur); } if (type == PliTag::END_CNTRL) { throw TImageException(TFilePath(), "Pli: frame not found"); return 0; } // trovato; leggo i suoi tag while ((tagElem = readTag())) { if (!m_firstTag) m_firstTag = m_lastTag = tagElem; else { m_lastTag->m_next = tagElem; m_lastTag = m_lastTag->m_next; } if (tagElem->m_tag->m_type == PliTag::IMAGE_GOBJ) { assert(((ImageTag *)(tagElem->m_tag))->m_numFrame == frameId); return (ImageTag *)tagElem->m_tag; } } return 0; } /*=====================================================================*/ TagElem *ParsedPliImp::readTag() { UCHAR ucharTagType, tagLengthId; USHORT tagType; TUINT32 tagOffset = m_iChan.tellg(); m_iChan >> ucharTagType; if (ucharTagType == 0xFF) { m_iChan >> tagType; tagLengthId = tagType >> 14; tagType &= 0x3FFF; } else { tagType = ucharTagType; tagLengthId = tagType >> 6; tagType &= 0x3F; } m_tagLength = 0; switch (tagLengthId) { case 0x0: m_tagLength = 0; break; case 0x1: { UCHAR clength; m_iChan >> clength; m_tagLength = clength; break; } case 0x2: { USHORT slength; m_iChan >> slength; m_tagLength = slength; break; } case 0x3: m_iChan >> m_tagLength; break; default: assert(false); } if (m_bufLength < m_tagLength) { m_bufLength = m_tagLength; m_buf.reset(new UCHAR[m_bufLength]); } if (m_tagLength) { m_iChan.read((char *)m_buf.get(), (int)m_tagLength); CHECK_FOR_READ_ERROR(m_filePath); } PliTag *newTag = NULL; switch (tagType) { case PliTag::SET_DATA_8_CNTRL: m_currDynamicTypeBytesNum = 1; break; case PliTag::SET_DATA_16_CNTRL: m_currDynamicTypeBytesNum = 2; break; case PliTag::SET_DATA_32_CNTRL: m_currDynamicTypeBytesNum = 4; break; case PliTag::TEXT: newTag = readTextTag(); break; case PliTag::PALETTE: newTag = readPaletteTag(); break; case PliTag::PALETTE_WITH_ALPHA: newTag = readPaletteWithAlphaTag(); break; case PliTag::THICK_QUADRATIC_CHAIN_GOBJ: case PliTag::THICK_QUADRATIC_LOOP_GOBJ: newTag = readThickQuadraticChainTag(tagType == PliTag::THICK_QUADRATIC_LOOP_GOBJ); break; case PliTag::GROUP_GOBJ: newTag = readGroupTag(); break; case PliTag::IMAGE_GOBJ: newTag = readImageTag(); break; case PliTag::COLOR_NGOBJ: newTag = readColorTag(); break; case PliTag::STYLE_NGOBJ: newTag = readStyleTag(); break; case PliTag::GEOMETRIC_TRANSFORMATION_GOBJ: newTag = readGeometricTransformationTag(); break; case PliTag::DOUBLEPAIR_OBJ: newTag = readDoublePairTag(); break; case PliTag::BITMAP_GOBJ: newTag = readBitmapTag(); break; case PliTag::INTERSECTION_DATA_GOBJ: newTag = readIntersectionDataTag(); break; case PliTag::OUTLINE_OPTIONS_GOBJ: newTag = readOutlineOptionsTag(); break; case PliTag::PRECISION_SCALE_GOBJ: newTag = readPrecisionScaleTag(); break; case PliTag::AUTOCLOSE_TOLERANCE_GOBJ: newTag = readAutoCloseToleranceTag(); break; case PliTag::END_CNTRL: return 0; } if (newTag) return new TagElem(newTag, tagOffset); else return readTag(); } /*=====================================================================*/ PliTag *ParsedPliImp::findTagFromOffset(UINT tagOffs) { for (TagElem *elem = m_firstTag; elem; elem = elem->m_next) if (elem->m_offset == tagOffs) return elem->m_tag; return NULL; } /*=====================================================================*/ UINT ParsedPliImp::findOffsetFromTag(PliTag *tag) { for (TagElem *elem = m_firstTag; elem; elem = elem->m_next) if (elem->m_tag == tag) return elem->m_offset; return 0; } /*=====================================================================*/ TagElem *ParsedPliImp::findTag(PliTag *tag) { for (TagElem *elem = m_firstTag; elem; elem = elem->m_next) if (elem->m_tag == tag) return elem; return NULL; } /*=====================================================================*/ inline void ParsedPliImp::readDynamicData(TUINT32 &val, TUINT32 &bufOffs) { switch (m_currDynamicTypeBytesNum) { case 1: val = m_buf[bufOffs++]; break; case 2: if (m_isIrixEndian) val = m_buf[bufOffs + 1] | (m_buf[bufOffs] << 8); else val = m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8); bufOffs += 2; break; case 4: if (m_isIrixEndian) val = m_buf[bufOffs + 3] | (m_buf[bufOffs + 2] << 8) | (m_buf[bufOffs + 1] << 16) | (m_buf[bufOffs] << 24); else val = m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8) | (m_buf[bufOffs + 2] << 16) | (m_buf[bufOffs + 3] << 24); bufOffs += 4; break; default: assert(false); } } /*=====================================================================*/ inline bool ParsedPliImp::readDynamicData(TINT32 &val, TUINT32 &bufOffs) { bool isNegative = false; switch (m_currDynamicTypeBytesNum) { case 1: val = m_buf[bufOffs] & 0x7f; if (m_buf[bufOffs] & 0x80) { val = -val; isNegative = true; } bufOffs++; break; case 2: if (m_isIrixEndian) { val = (m_buf[bufOffs + 1] | (m_buf[bufOffs] << 8)) & 0x7fff; if (m_buf[bufOffs] & 0x80) { val = -val; isNegative = true; } } else { val = (m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8)) & 0x7fff; if (m_buf[bufOffs + 1] & 0x80) { val = -val; isNegative = true; } } bufOffs += 2; break; case 4: if (m_isIrixEndian) { val = (m_buf[bufOffs + 3] | (m_buf[bufOffs + 2] << 8) | (m_buf[bufOffs + 1] << 16) | (m_buf[bufOffs] << 24)) & 0x7fffffff; if (m_buf[bufOffs] & 0x80) { val = -val; isNegative = true; } } else { val = (m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8) | (m_buf[bufOffs + 2] << 16) | (m_buf[bufOffs + 3] << 24)) & 0x7fffffff; if (m_buf[bufOffs + 3] & 0x80) { val = -val; isNegative = true; } } bufOffs += 4; break; default: assert(false); } return isNegative; } /*=====================================================================*/ /*=====================================================================*/ /*=====================================================================*/ /*=====================================================================*/ PliTag *ParsedPliImp::readTextTag() { if (m_tagLength == 0) return new TextTag(""); return new TextTag(string((char *)m_buf.get(), m_tagLength)); } /*=====================================================================*/ PliTag *ParsedPliImp::readPaletteTag() { TPixelRGBM32 *plt; TUINT32 numColors = 0; plt = new TPixelRGBM32[m_tagLength / 3]; for (unsigned int i = 0; i < m_tagLength; i += 3, numColors++) { plt[numColors].r = m_buf[i]; plt[numColors].g = m_buf[i + 1]; plt[numColors].b = m_buf[i + 2]; } PaletteTag *tag = new PaletteTag(numColors, plt); delete[] plt; return tag; } /*=====================================================================*/ PliTag *ParsedPliImp::readPaletteWithAlphaTag() { TPixelRGBM32 *plt; TUINT32 numColors = 0; plt = new TPixelRGBM32[m_tagLength / 4]; for (unsigned int i = 0; i < m_tagLength; i += 4, numColors++) { plt[numColors].r = m_buf[i]; plt[numColors].g = m_buf[i + 1]; plt[numColors].b = m_buf[i + 2]; plt[numColors].m = m_buf[i + 3]; } PaletteWithAlphaTag *tag = new PaletteWithAlphaTag(numColors, plt); delete[] plt; return tag; } /*=====================================================================*/ PliTag *ParsedPliImp::readThickQuadraticChainTag(bool isLoop) { TThickPoint p; TUINT32 bufOffs = 0; double dx1, dy1, dx2, dy2; TINT32 d; TUINT32 numQuadratics = 0; double scale; bool newThicknessWriteMethod = ((m_majorVersionNumber == 5 && m_minorVersionNumber >= 7) || (m_majorVersionNumber > 5)); scale = 1.0 / (double)m_precisionScale; int maxThickness; if (newThicknessWriteMethod) { maxThickness = m_buf[bufOffs++]; m_thickRatio = maxThickness / 255.0; } else { maxThickness = (int)m_maxThickness; assert(m_thickRatio != 0); } TINT32 val; readDynamicData(val, bufOffs); p.x = scale * val; readDynamicData(val, bufOffs); p.y = scale * val; p.thick = m_buf[bufOffs++] * m_thickRatio; if (newThicknessWriteMethod) numQuadratics = (m_tagLength - 2 * m_currDynamicTypeBytesNum - 1 - 1) / (4 * m_currDynamicTypeBytesNum + 2); else numQuadratics = (m_tagLength - 2 * m_currDynamicTypeBytesNum - 1) / (4 * m_currDynamicTypeBytesNum + 3); std::unique_ptr<TThickQuadratic[]> quadratic( new TThickQuadratic[numQuadratics]); for (unsigned int i = 0; i < numQuadratics; i++) { quadratic[i].setThickP0(p); readDynamicData(d, bufOffs); dx1 = scale * d; readDynamicData(d, bufOffs); dy1 = scale * d; if (newThicknessWriteMethod) p.thick = m_buf[bufOffs++] * m_thickRatio; else { if (m_isIrixEndian) p.thick = complement2((USHORT)(m_buf[bufOffs + 1] | (m_buf[bufOffs] << 8))) * m_thickRatio; else p.thick = complement2((USHORT)(m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8))) * m_thickRatio; bufOffs += 2; } readDynamicData(d, bufOffs); dx2 = scale * d; readDynamicData(d, bufOffs); dy2 = scale * d; if (dx1 == 0 && dy1 == 0) // p0==p1, or p1==p2 creates problems (in the // increasecontrolpoints for example) I slightly // move it... { if (dx2 != 0 || dy2 != 0) { dx1 = 0.001 * dx2; dx2 = 0.999 * dx2; dy1 = 0.001 * dy2; dy2 = 0.999 * dy2; assert(dx1 != 0 || dy1 != 0); } } else if (dx2 == 0 && dy2 == 0) { if (dx1 != 0 || dy1 != 0) { dx2 = 0.001 * dx1; dx1 = 0.999 * dx1; dy2 = 0.001 * dy1; dy1 = 0.999 * dy1; assert(dx2 != 0 || dy2 != 0); } } p.x += dx1; p.y += dy1; quadratic[i].setThickP1(p); p.thick = m_buf[bufOffs++] * m_thickRatio; p.x += dx2; p.y += dy2; quadratic[i].setThickP2(p); } ThickQuadraticChainTag *tag = new ThickQuadraticChainTag(); tag->m_numCurves = numQuadratics; tag->m_curve = std::move(quadratic); tag->m_isLoop = isLoop; tag->m_maxThickness = maxThickness; return tag; } /*=====================================================================*/ PliTag *ParsedPliImp::readGroupTag() { TUINT32 bufOffs = 0; UCHAR type = m_buf[bufOffs++]; assert(type < GroupTag::TYPE_HOW_MANY); TUINT32 numObjects = (m_tagLength - 1) / m_currDynamicTypeBytesNum; std::unique_ptr<PliObjectTag *[]> object(new PliObjectTag *[numObjects]); std::unique_ptr<TUINT32[]> tagOffs(new TUINT32[numObjects]); for (TUINT32 i = 0; i < numObjects; i++) { readDynamicData(tagOffs[i], bufOffs); } TagElem *elem; for (TUINT32 i = 0; i < numObjects; i++) while (!(object[i] = (PliObjectTag *)findTagFromOffset(tagOffs[i]))) if ((elem = readTag())) addTag(*elem); else assert(false); std::unique_ptr<GroupTag> tag(new GroupTag()); tag->m_type = type; tag->m_numObjects = numObjects; tag->m_object = std::move(object); return tag.release(); } /*=====================================================================*/ PliTag *ParsedPliImp::readColorTag() { ColorTag::styleType style; ColorTag::attributeType attribute; TUINT32 bufOffs = 0; style = (ColorTag::styleType)m_buf[bufOffs++]; attribute = (ColorTag::attributeType)m_buf[bufOffs++]; assert(style < ColorTag::STYLE_HOW_MANY); assert(attribute < ColorTag::ATTRIBUTE_HOW_MANY); TUINT32 numColors = (m_tagLength - 2) / m_currDynamicTypeBytesNum; std::unique_ptr<TUINT32[]> colorArray(new TUINT32[numColors]); for (unsigned int i = 0; i < numColors; i++) { TUINT32 color; readDynamicData(color, bufOffs); colorArray[i] = color; } std::unique_ptr<ColorTag> tag( new ColorTag(style, attribute, numColors, std::move(colorArray))); return tag.release(); } /*=====================================================================*/ PliTag *ParsedPliImp::readStyleTag() { std::vector<TStyleParam> paramArray; TUINT32 bufOffs = 0; int length = m_tagLength; UINT i; USHORT id = 0; USHORT pageIndex = 0; UCHAR currDynamicTypeBytesNumSaved = m_currDynamicTypeBytesNum; m_currDynamicTypeBytesNum = 2; readUShortData(id, bufOffs); length -= 2; if (m_majorVersionNumber > 5 || (m_majorVersionNumber == 5 && m_minorVersionNumber >= 6)) { readUShortData(pageIndex, bufOffs); length -= 2; } while (length > 0) { TStyleParam param; param.m_type = (enum TStyleParam::Type)m_buf[bufOffs++]; length--; switch (param.m_type) { case TStyleParam::SP_BYTE: param.m_numericVal = m_buf[bufOffs++]; length--; break; case TStyleParam::SP_USHORT: { USHORT val; readUShortData(val, bufOffs); param.m_numericVal = val; length -= 2; break; } case TStyleParam::SP_INT: case TStyleParam::SP_DOUBLE: readFloatData(param.m_numericVal, bufOffs); length -= 4; break; case TStyleParam::SP_RASTER: length -= readRasterData(param.m_r, bufOffs); break; case TStyleParam::SP_STRING: { USHORT strLen; readUShortData(strLen, bufOffs); // bufOffs+=2; param.m_string = ""; for (i = 0; i < strLen; i++) { param.m_string.append(1, m_buf[bufOffs++]); } length -= strLen + sizeof(USHORT); break; } default: assert(false); } paramArray.push_back(param); } int paramArraySize = paramArray.size(); StyleTag *tag = new StyleTag(id, pageIndex, paramArraySize, (paramArraySize > 0) ? paramArray.data() : nullptr); m_currDynamicTypeBytesNum = currDynamicTypeBytesNumSaved; return tag; } /*=====================================================================*/ PliTag *ParsedPliImp::readOutlineOptionsTag() { TUINT32 bufOffs = 0; TINT32 d; const double scale = 0.001; // Read OutlineOptions int capStyle, joinStyle; double miterLower, miterUpper; capStyle = m_buf[bufOffs++]; joinStyle = m_buf[bufOffs++]; readDynamicData(d, bufOffs); miterLower = scale * d; readDynamicData(d, bufOffs); miterUpper = scale * d; return new StrokeOutlineOptionsTag( TStroke::OutlineOptions(capStyle, joinStyle, miterLower, miterUpper)); } /*=====================================================================*/ PliTag *ParsedPliImp::readPrecisionScaleTag() { TUINT32 bufOffs = 0; TINT32 d; readDynamicData(d, bufOffs); m_precisionScale = d; return new PrecisionScaleTag(m_precisionScale); } /*=====================================================================*/ PliTag *ParsedPliImp::readAutoCloseToleranceTag() { TUINT32 bufOffs = 0; TINT32 d; readDynamicData(d, bufOffs); return new AutoCloseToleranceTag(d); } /*=====================================================================*/ void ParsedPliImp::readFloatData(double &val, TUINT32 &bufOffs) { // UCHAR currDynamicTypeBytesNumSaved = m_currDynamicTypeBytesNum; // m_currDynamicTypeBytesNum = 2; TINT32 valInt; TUINT32 valDec; bool isNegative; isNegative = readDynamicData(valInt, bufOffs); readDynamicData(valDec, bufOffs); val = valInt + (double)valDec / 65536.0; // 2^16 if (valInt == 0 && isNegative) val = -val; // m_currDynamicTypeBytesNum = currDynamicTypeBytesNumSaved; } /*=====================================================================*/ UINT ParsedPliImp::readRasterData(TRaster32P &r, TUINT32 &bufOffs) { USHORT lx, ly; readUShortData(lx, bufOffs); readUShortData(ly, bufOffs); // readUShortData((USHORT&)lx, bufOffs); // readUShortData((USHORT&)ly, bufOffs); r.create((int)lx, (int)ly); UINT size = lx * ly * 4; r->lock(); memcpy(r->getRawData(), m_buf.get() + bufOffs, size); r->unlock(); bufOffs += size; return size + 2 + 2; } /*=====================================================================*/ inline void getLongValFromFloat(double val, TINT32 &intVal, TUINT32 &decVal) { intVal = (TINT32)val; if (val < 0) decVal = (TUINT32)((double)((-val) - (-intVal)) * 65536.0); /*if (intVal<(0x1<<7)) intVal|=(0x1<<7); else if (intVal<(0x1<<15)) intVal|=(0x1<<15); else { assert(intVal<(0x1<<31)); intVal|=(0x1<<31); }*/ else decVal = (TUINT32)((double)(val - intVal) * 65536.0); } /*=====================================================================*/ void ParsedPliImp::writeFloatData(double val) { UCHAR currDynamicTypeBytesNumSaved = m_currDynamicTypeBytesNum; m_currDynamicTypeBytesNum = 2; TINT32 valInt; TUINT32 valDec; // bool neg=false; valInt = (int)val; if (val < 0) valDec = (int)((double)(-val + valInt) * 65536.0); else valDec = (int)((double)(val - valInt) * 65536.0); assert(valInt < (0x1 << 15)); assert(valDec < (0x1 << 16)); writeDynamicData(valInt, val < 0); writeDynamicData(valDec); m_currDynamicTypeBytesNum = currDynamicTypeBytesNumSaved; } /*=====================================================================*/ PliTag *ParsedPliImp::readGeometricTransformationTag() { TUINT32 bufOffs = 0; TAffine affine; readFloatData(affine.a11, bufOffs); readFloatData(affine.a12, bufOffs); readFloatData(affine.a13, bufOffs); readFloatData(affine.a21, bufOffs); readFloatData(affine.a22, bufOffs); readFloatData(affine.a23, bufOffs); TUINT32 tagOffs; readDynamicData(tagOffs, bufOffs); TagElem *elem; PliObjectTag *object = NULL; if (tagOffs != 0) while (!(object = (PliObjectTag *)findTagFromOffset(tagOffs))) if ((elem = readTag())) addTag(*elem); else assert(false); else m_affine = affine; /*int realScale = tround(log10(1.0/m_affine.a11)); m_affine = TScale(1.0/pow(10.0, realScale));*/ GeometricTransformationTag *tag = new GeometricTransformationTag(affine, (PliGeometricTag *)object); return tag; } /*=====================================================================*/ PliTag *ParsedPliImp::readDoublePairTag() { TUINT32 bufOffs = 0; double first, second; readFloatData(first, bufOffs); readFloatData(second, bufOffs); DoublePairTag *tag = new DoublePairTag(first, second); return tag; } /*=====================================================================*/ void ParsedPliImp::readUShortData(USHORT &val, TUINT32 &bufOffs) { if (m_isIrixEndian) val = m_buf[bufOffs + 1] | (m_buf[bufOffs] << 8); else val = m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8); bufOffs += 2; } /*=====================================================================*/ void ParsedPliImp::readTUINT32Data(TUINT32 &val, TUINT32 &bufOffs) { if (m_isIrixEndian) val = m_buf[bufOffs + 3] | (m_buf[bufOffs + 2] << 8) | (m_buf[bufOffs + 1] << 16) | (m_buf[bufOffs] << 24); else val = m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8) | (m_buf[bufOffs + 2] << 16) | (m_buf[bufOffs + 3] << 24); bufOffs += 4; } /*=====================================================================*/ PliTag *ParsedPliImp::readBitmapTag() { USHORT lx, ly; TUINT32 bufOffs = 0; readUShortData(lx, bufOffs); readUShortData(ly, bufOffs); TRaster32P r; r.create(lx, ly); r->lock(); memcpy(r->getRawData(), m_buf.get() + bufOffs, lx * ly * 4); r->unlock(); BitmapTag *tag = new BitmapTag(r); return tag; } /*=====================================================================*/ PliTag *ParsedPliImp::readImageTag() { USHORT frame; TUINT32 bufOffs = 0; if (m_isIrixEndian) frame = m_buf[bufOffs + 1] | (m_buf[bufOffs] << 8); else frame = m_buf[bufOffs] | (m_buf[bufOffs + 1] << 8); bufOffs += 2; int headerLength = 2; QByteArray suffix; if (m_majorVersionNumber >= 150) { TUINT32 suffixLength; readTUINT32Data(suffixLength, bufOffs); headerLength += 4; if (suffixLength > 0) { suffix = QByteArray((char *)m_buf.get() + bufOffs, suffixLength); bufOffs += suffixLength; headerLength += suffixLength; } } else { char letter = 0; if (m_majorVersionNumber > 6 || (m_majorVersionNumber == 6 && m_minorVersionNumber >= 6)) { letter = (char)m_buf[bufOffs++]; ++headerLength; if (letter > 0) suffix = QByteArray(&letter, 1); } } TUINT32 numObjects = (m_tagLength - headerLength) / m_currDynamicTypeBytesNum; std::unique_ptr<PliObjectTag *[]> object(new PliObjectTag *[numObjects]); std::unique_ptr<TUINT32[]> tagOffs(new TUINT32[numObjects]); for (TUINT32 i = 0; i < numObjects; i++) { readDynamicData(tagOffs[i], bufOffs); } TagElem *elem; for (TUINT32 i = 0; i < numObjects; i++) while (!(object[i] = (PliObjectTag *)findTagFromOffset(tagOffs[i]))) if ((elem = readTag())) addTag(*elem); else assert(false); std::unique_ptr<ImageTag[]> tag( new ImageTag(TFrameId(frame, QString::fromUtf8(suffix)), numObjects, std::move(object))); return tag.release(); } /*=====================================================================*/ const TSolidColorStyle ConstStyle(TPixel32::Red); /*=====================================================================*/ inline double doubleFromUlong(TUINT32 q) { assert((q & 0X00000001) == 0); TUINT32 l[2]; #if TNZ_LITTLE_ENDIAN l[1] = 0x3FF00000 | (q >> 12); l[0] = (q & 0xFFE) << 20; #else l[0] = 0x3FF00000 | (q >> 12); l[1] = (q & 0xFFE) << 20; #endif return *(double *)l - 1; } /*=====================================================================*/ // vedi commento sulla write per chiarimenti!! inline double truncate(double x) { x += 1.0; TUINT32 *l = (TUINT32 *)&x; #if TNZ_LITTLE_ENDIAN l[0] &= 0xFFE00000; #else l[1] &= 0xFFE00000; #endif return x - 1.0; } /*=====================================================================*/ PliTag *ParsedPliImp::readIntersectionDataTag() { TUINT32 bufOffs = 0; TUINT32 branchCount; readTUINT32Data(branchCount, bufOffs); std::unique_ptr<IntersectionBranch[]> branchArray( new IntersectionBranch[branchCount]); UINT i; for (i = 0; i < branchCount; i++) { TINT32 currInter; readDynamicData((TINT32 &)branchArray[i].m_strokeIndex, bufOffs); readDynamicData(currInter, bufOffs); readDynamicData((TUINT32 &)branchArray[i].m_nextBranch, bufOffs); USHORT style; readUShortData(style, bufOffs); branchArray[i].m_style = style; /* */ if (m_buf[bufOffs] & 0x80) // in un numero double tra 0 e 1, il bit piu' // significativo e' sempre 0 // sfrutto questo bit; se e' 1, vuol dire che il valore e' 0.0 o 1.0 in un // singolo byte { branchArray[i].m_w = (m_buf[bufOffs] & 0x1) ? 1.0 : 0.0; bufOffs++; } else { TUINT32 hi, lo; hi = m_buf[bufOffs + 3] | (m_buf[bufOffs + 2] << 8) | (m_buf[bufOffs + 1] << 16) | (m_buf[bufOffs] << 24); bufOffs += 4; readTUINT32Data(lo, bufOffs); // readTUINT32Data(hi, bufOffs); branchArray[i].m_w = doubleFromUlong1(hi, lo); } if (currInter < 0) { branchArray[i].m_currInter = -currInter - 1; branchArray[i].m_gettingOut = false; } else { branchArray[i].m_currInter = currInter - 1; branchArray[i].m_gettingOut = true; } } IntersectionDataTag *tag = new IntersectionDataTag(); tag->m_branchCount = branchCount; tag->m_branchArray = std::move(branchArray); return tag; } /*=====================================================================*/ bool ParsedPliImp::addTag(PliTag *tagPtr, bool addFront) { TagElem *_tag = new TagElem(tagPtr, 0); assert(tagPtr->m_type); if (!m_firstTag) { m_firstTag = m_lastTag = _tag; } else if (addFront) { _tag->m_next = m_firstTag; m_firstTag = _tag; } else { m_lastTag->m_next = _tag; m_lastTag = m_lastTag->m_next; } return true; } /*=====================================================================*/ bool ParsedPliImp::addTag(const TagElem &elem, bool addFront) { TagElem *_tag = new TagElem(elem); if (!m_firstTag) { m_firstTag = m_lastTag = _tag; } else if (addFront) { _tag->m_next = m_firstTag; m_firstTag = _tag; } else { m_lastTag->m_next = _tag; m_lastTag = m_lastTag->m_next; } return true; } /*=====================================================================*/ void ParsedPliImp::writeTag(TagElem *elem) { if (elem->m_offset != 0) // already written return; switch (elem->m_tag->m_type) { case PliTag::TEXT: elem->m_offset = writeTextTag((TextTag *)elem->m_tag); break; case PliTag::PALETTE: elem->m_offset = writePaletteTag((PaletteTag *)elem->m_tag); break; case PliTag::PALETTE_WITH_ALPHA: elem->m_offset = writePaletteWithAlphaTag((PaletteWithAlphaTag *)elem->m_tag); break; case PliTag::THICK_QUADRATIC_CHAIN_GOBJ: elem->m_offset = writeThickQuadraticChainTag((ThickQuadraticChainTag *)elem->m_tag); break; case PliTag::GROUP_GOBJ: elem->m_offset = writeGroupTag((GroupTag *)elem->m_tag); break; case PliTag::IMAGE_GOBJ: elem->m_offset = writeImageTag((ImageTag *)elem->m_tag); break; case PliTag::COLOR_NGOBJ: elem->m_offset = writeColorTag((ColorTag *)elem->m_tag); break; case PliTag::STYLE_NGOBJ: elem->m_offset = writeStyleTag((StyleTag *)elem->m_tag); break; case PliTag::GEOMETRIC_TRANSFORMATION_GOBJ: elem->m_offset = writeGeometricTransformationTag( (GeometricTransformationTag *)elem->m_tag); break; case PliTag::DOUBLEPAIR_OBJ: elem->m_offset = writeDoublePairTag((DoublePairTag *)elem->m_tag); break; case PliTag::BITMAP_GOBJ: elem->m_offset = writeBitmapTag((BitmapTag *)elem->m_tag); break; case PliTag::INTERSECTION_DATA_GOBJ: elem->m_offset = writeIntersectionDataTag((IntersectionDataTag *)elem->m_tag); break; case PliTag::OUTLINE_OPTIONS_GOBJ: elem->m_offset = writeOutlineOptionsTag((StrokeOutlineOptionsTag *)elem->m_tag); break; case PliTag::PRECISION_SCALE_GOBJ: elem->m_offset = writePrecisionScaleTag((PrecisionScaleTag *)elem->m_tag); break; case PliTag::AUTOCLOSE_TOLERANCE_GOBJ: elem->m_offset = writeAutoCloseToleranceTag((AutoCloseToleranceTag *)elem->m_tag); break; default: assert(false); // m_error = UNKNOWN_TAG; ; } } /*=====================================================================*/ inline void ParsedPliImp::setDynamicTypeBytesNum(int minval, int maxval) { assert(m_oChan); if (maxval > 32767 || minval < -32767) { if (m_currDynamicTypeBytesNum != 4) { m_currDynamicTypeBytesNum = 4; *m_oChan << (UCHAR)PliTag::SET_DATA_32_CNTRL; } } else if (maxval > 127 || minval < -127) { if (m_currDynamicTypeBytesNum != 2) { m_currDynamicTypeBytesNum = 2; *m_oChan << (UCHAR)PliTag::SET_DATA_16_CNTRL; } } else if (m_currDynamicTypeBytesNum != 1) { m_currDynamicTypeBytesNum = 1; *m_oChan << (UCHAR)PliTag::SET_DATA_8_CNTRL; } } /*=====================================================================*/ inline void ParsedPliImp::writeDynamicData(TUINT32 val) { assert(m_oChan); switch (m_currDynamicTypeBytesNum) { case 1: *m_oChan << (UCHAR)val; break; case 2: *m_oChan << (USHORT)val; break; case 4: *m_oChan << (TUINT32)val; break; default: assert(false); } } /*=====================================================================*/ inline void ParsedPliImp::writeDynamicData(TINT32 val, bool isNegative = false) { assert(m_oChan); switch (m_currDynamicTypeBytesNum) { case 1: *m_oChan << complement1((char)val, isNegative); break; case 2: *m_oChan << complement1((short)val, isNegative); break; case 4: *m_oChan << complement1(val, isNegative); break; default: assert(false); } } /*=====================================================================*/ TUINT32 ParsedPliImp::writeTagHeader(UCHAR type, UINT tagLength) { assert(m_oChan); TUINT32 offset = m_oChan->tellp(); assert((type & 0xc0) == 0x0); if (tagLength == 0) *m_oChan << type; else if (tagLength < 256) { *m_oChan << (UCHAR)(type | (0x1 << 6)); *m_oChan << (UCHAR)tagLength; } else if (tagLength < 65535) { *m_oChan << (UCHAR)(type | (0x2 << 6)); *m_oChan << (USHORT)tagLength; } else { *m_oChan << (UCHAR)(type | (0x3 << 6)); *m_oChan << (TUINT32)tagLength; } return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeTextTag(TextTag *tag) { assert(m_oChan); int offset, tagLength = tag->m_text.length(); offset = (int)writeTagHeader((UCHAR)PliTag::TEXT, tagLength); for (int i = 0; i < tagLength; i++) *m_oChan << tag->m_text[i]; return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writePaletteTag(PaletteTag *tag) { assert(m_oChan); int offset, tagLength = (int)(tag->m_numColors * 3); offset = (int)writeTagHeader((UCHAR)PliTag::PALETTE, tagLength); for (unsigned int i = 0; i < tag->m_numColors; i++) { *m_oChan << tag->m_color[i].r; *m_oChan << tag->m_color[i].g; *m_oChan << tag->m_color[i].b; } return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writePaletteWithAlphaTag(PaletteWithAlphaTag *tag) { assert(m_oChan); int offset, tagLength = (int)(tag->m_numColors * 4); offset = (int)writeTagHeader((UCHAR)PliTag::PALETTE_WITH_ALPHA, tagLength); for (unsigned int i = 0; i < tag->m_numColors; i++) { *m_oChan << tag->m_color[i].r; *m_oChan << tag->m_color[i].g; *m_oChan << tag->m_color[i].b; *m_oChan << tag->m_color[i].m; } return offset; } /*=====================================================================*/ #define SET_MINMAX \ if (p.x < minval) minval = (int)p.x; \ if (p.y < minval) minval = (int)p.y; \ if (p.x > maxval) maxval = (int)p.x; \ if (p.y > maxval) maxval = (int)p.y; /*=====================================================================*/ inline void ParsedPliImp::WRITE_UCHAR_FROM_DOUBLE(double dval) { assert(m_oChan); int ival = tround(dval); if (ival > 255) ival = 255; assert(ival >= 0); *m_oChan << (UCHAR)ival; } /*=====================================================================*/ inline void ParsedPliImp::WRITE_SHORT_FROM_DOUBLE(double dval) { assert(m_oChan); int ival = (int)(dval); assert(ival >= -32768 && ival < 32768); *m_oChan << complement1((short)ival); } /*=====================================================================*/ TUINT32 ParsedPliImp::writeThickQuadraticChainTag(ThickQuadraticChainTag *tag) { assert(m_oChan); int maxval = -(std::numeric_limits<int>::max)(), minval = (std::numeric_limits<int>::max)(); TPointD p; double scale; int i; assert(m_majorVersionNumber > 5 || (m_majorVersionNumber == 5 && m_minorVersionNumber >= 5)); scale = m_precisionScale; /*for ( i=0; i<tag->m_numCurves; i++) tag->m_curve[i] = aff*tag->m_curve[i];*/ p = scale * tag->m_curve[0].getP0(); SET_MINMAX for (i = 0; i < (int)tag->m_numCurves; i++) { p = scale * (tag->m_curve[i].getP1() - tag->m_curve[i].getP0()); SET_MINMAX p = scale * (tag->m_curve[i].getP2() - tag->m_curve[i].getP1()); SET_MINMAX } setDynamicTypeBytesNum(minval, maxval); int tagLength = (int)(2 * (2 * tag->m_numCurves + 1) * m_currDynamicTypeBytesNum + 1 + 1 + 2 * tag->m_numCurves); int offset; if (tag->m_isLoop) offset = (int)writeTagHeader((UCHAR)PliTag::THICK_QUADRATIC_LOOP_GOBJ, tagLength); else offset = (int)writeTagHeader((UCHAR)PliTag::THICK_QUADRATIC_CHAIN_GOBJ, tagLength); // assert(scale*tag->m_curve[0].getThickP0().x == // (double)(TINT32)(scale*tag->m_curve[0].getThickP0().x)); // assert(scale*tag->m_curve[0].getThickP0().y == // (double)(TINT32)(scale*tag->m_curve[0].getThickP0().y)); double thickRatio = tag->m_maxThickness / 255.0; assert(tag->m_maxThickness <= 255); assert(tag->m_maxThickness > 0); UCHAR maxThickness = (UCHAR)(tceil(tag->m_maxThickness)); *m_oChan << maxThickness; thickRatio = maxThickness / 255.0; writeDynamicData((TINT32)(scale * tag->m_curve[0].getThickP0().x)); writeDynamicData((TINT32)(scale * tag->m_curve[0].getThickP0().y)); double thick = tag->m_curve[0].getThickP0().thick / thickRatio; WRITE_UCHAR_FROM_DOUBLE(thick < 0 ? 0 : thick); for (i = 0; i < (int)tag->m_numCurves; i++) { TPoint dp = convert(scale * (tag->m_curve[i].getP1() - tag->m_curve[i].getP0())); assert(dp.x == (double)(TINT32)dp.x); assert(dp.y == (double)(TINT32)dp.y); writeDynamicData((TINT32)dp.x); writeDynamicData((TINT32)dp.y); thick = tag->m_curve[i].getThickP1().thick / thickRatio; WRITE_UCHAR_FROM_DOUBLE(thick < 0 ? 0 : thick); dp = convert(scale * (tag->m_curve[i].getP2() - tag->m_curve[i].getP1())); writeDynamicData((TINT32)dp.x); writeDynamicData((TINT32)dp.y); thick = tag->m_curve[i].getThickP2().thick / thickRatio; WRITE_UCHAR_FROM_DOUBLE(thick < 0 ? 0 : thick); } return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeGroupTag(GroupTag *tag) { assert(m_oChan); TUINT32 offset, tagLength; int maxval = 0, minval = 100000; std::vector<TUINT32> objectOffset(tag->m_numObjects); unsigned int i; for (i = 0; i < tag->m_numObjects; i++) { if (!(objectOffset[i] = findOffsetFromTag(tag->m_object[i]))) // the object was not // already written before: // write it now { TagElem elem(tag->m_object[i], 0); writeTag(&elem); objectOffset[i] = elem.m_offset; addTag(elem); elem.m_tag = 0; } if (objectOffset[i] < (unsigned int)minval) minval = (int)objectOffset[i]; if (objectOffset[i] > (unsigned int)maxval) maxval = (int)objectOffset[i]; } setDynamicTypeBytesNum(minval, maxval); tagLength = tag->m_numObjects * m_currDynamicTypeBytesNum + 1; offset = writeTagHeader((UCHAR)PliTag::GROUP_GOBJ, tagLength); *m_oChan << tag->m_type; for (i = 0; i < tag->m_numObjects; i++) writeDynamicData(objectOffset[i]); return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeImageTag(ImageTag *tag) { assert(m_oChan); TUINT32 *objectOffset, offset, tagLength; int maxval = 0, minval = 100000; QByteArray suffix = tag->m_numFrame.getLetter().toUtf8(); TUINT32 suffixLength = suffix.size(); UINT fIdTagLength; if (m_majorVersionNumber >= 150) { // write the suffix length before data fIdTagLength = 2 + 4 + suffixLength; writeTagHeader((UCHAR)PliTag::IMAGE_BEGIN_GOBJ, fIdTagLength); *m_oChan << (USHORT)tag->m_numFrame.getNumber(); *m_oChan << suffixLength; if (suffixLength > 0) m_oChan->writeBuf(suffix.data(), suffixLength); } else { // write only the first byte fIdTagLength = 3; writeTagHeader((UCHAR)PliTag::IMAGE_BEGIN_GOBJ, fIdTagLength); *m_oChan << (USHORT)tag->m_numFrame.getNumber(); if (suffixLength > 0) m_oChan->writeBuf(suffix.data(), 1); else *m_oChan << (UCHAR)0; } m_currDynamicTypeBytesNum = 3; objectOffset = new TUINT32[tag->m_numObjects]; unsigned int i; for (i = 0; i < tag->m_numObjects; i++) { if (!(objectOffset[i] = findOffsetFromTag(tag->m_object[i]))) // the object was not // already written before: // write it now { TagElem elem(tag->m_object[i], 0); writeTag(&elem); objectOffset[i] = elem.m_offset; addTag(elem); elem.m_tag = 0; } if (objectOffset[i] < (unsigned int)minval) minval = (int)objectOffset[i]; if (objectOffset[i] > (unsigned int)maxval) maxval = (int)objectOffset[i]; } setDynamicTypeBytesNum(minval, maxval); tagLength = tag->m_numObjects * m_currDynamicTypeBytesNum + fIdTagLength; // tagLength = tag->m_numObjects * m_currDynamicTypeBytesNum + 3; offset = writeTagHeader((UCHAR)PliTag::IMAGE_GOBJ, tagLength); suffix = tag->m_numFrame.getLetter().toUtf8(); *m_oChan << (USHORT)tag->m_numFrame.getNumber(); if (m_majorVersionNumber >= 150) { // write the suffix length before data *m_oChan << suffixLength; if (suffixLength > 0) m_oChan->writeBuf(suffix.data(), suffixLength); } else { // write only the first byte if (suffixLength > 0) m_oChan->writeBuf(suffix.data(), 1); else *m_oChan << (UCHAR)0; } for (i = 0; i < tag->m_numObjects; i++) writeDynamicData(objectOffset[i]); delete[] objectOffset; return offset; } /*=====================================================================*/ /*struct intersectionBranch { int m_strokeIndex; const TColorStyle* m_style; double m_w; UINT currInter; UINT m_nextBranch; bool m_gettingOut; }; */ // per scrivere il valore m_w, molto spesso vale 0 oppure 1; // se vale 0, scrivo un bye con valore 0x0; // se vale 1, scrivo un bye con valore 0x1; // altrimenti, 4 byte con val&0x3==0x2; // e gli altri (32-2) bit contenenti iol valore di w. inline TUINT32 ulongFromDouble(double x) { assert(x < 1.0); x += 1.0; TUINT32 *l = (TUINT32 *)&x; #if TNZ_LITTLE_ENDIAN TUINT32 hi = l[1], lo = l[0]; #else TUINT32 hi = l[0], lo = l[1]; #endif return (hi & 0XFFFFF) << 12 | ((lo & 0xFFE00000) >> 20); } /*=====================================================================*/ TUINT32 ParsedPliImp::writeIntersectionDataTag(IntersectionDataTag *tag) { TUINT32 offset, tagLength; int maxval = -100000, minval = 100000; // bool isNew = false; int floatWCount = 0; unsigned int i; assert(m_oChan); if (-(int)tag->m_branchCount - 1 < minval) minval = -(int)tag->m_branchCount - 1; if ((int)tag->m_branchCount + 1 > maxval) maxval = (int)tag->m_branchCount + 1; for (i = 0; i < tag->m_branchCount; i++) { if (tag->m_branchArray[i].m_w != 0 && tag->m_branchArray[i].m_w != 1) floatWCount++; if (tag->m_branchArray[i].m_strokeIndex < minval) minval = tag->m_branchArray[i].m_strokeIndex; else if (tag->m_branchArray[i].m_strokeIndex > maxval) maxval = tag->m_branchArray[i].m_strokeIndex; } setDynamicTypeBytesNum(minval, maxval); tagLength = 4 + tag->m_branchCount * (3 * m_currDynamicTypeBytesNum + 2) + floatWCount * 8 + (tag->m_branchCount - floatWCount) * 1; offset = writeTagHeader((UCHAR)PliTag::INTERSECTION_DATA_GOBJ, tagLength); *m_oChan << (TUINT32)tag->m_branchCount; for (i = 0; i < tag->m_branchCount; i++) { writeDynamicData((TINT32)tag->m_branchArray[i].m_strokeIndex); writeDynamicData((tag->m_branchArray[i].m_gettingOut) ? (TINT32)(tag->m_branchArray[i].m_currInter + 1) : -(TINT32)(tag->m_branchArray[i].m_currInter + 1)); writeDynamicData((TUINT32)tag->m_branchArray[i].m_nextBranch); assert(tag->m_branchArray[i].m_style >= 0 && tag->m_branchArray[i].m_style < 65536); *m_oChan << (USHORT)tag->m_branchArray[i].m_style; assert(tag->m_branchArray[i].m_w >= 0 && tag->m_branchArray[i].m_w <= 1); if (tag->m_branchArray[i].m_w == 0) *m_oChan << ((UCHAR)0x80); else if (tag->m_branchArray[i].m_w == 1) *m_oChan << ((UCHAR)0x81); else { TUINT32 hi, lo; ulongFromDouble1(tag->m_branchArray[i].m_w, hi, lo); assert((hi & 0x80000000) == 0); *m_oChan << (UCHAR)((hi >> 24) & 0xff); *m_oChan << (UCHAR)((hi >> 16) & 0xff); *m_oChan << (UCHAR)((hi >> 8) & 0xff); *m_oChan << (UCHAR)((hi)&0xff); // m_oChan<<((TUINT32)hi); *m_oChan << (TUINT32)(lo); // m_oChan<<((TUINT32)hi); } } return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeColorTag(ColorTag *tag) { assert(m_oChan); TUINT32 tagLength, offset; int maxval = 0, minval = 100000; unsigned int i; for (i = 0; i < tag->m_numColors; i++) { if (tag->m_color[i] < (unsigned int)minval) minval = (int)tag->m_color[i]; if (tag->m_color[i] > (unsigned int)maxval) maxval = (int)tag->m_color[i]; } setDynamicTypeBytesNum(minval, maxval); tagLength = tag->m_numColors * m_currDynamicTypeBytesNum + 2; offset = writeTagHeader((UCHAR)PliTag::COLOR_NGOBJ, tagLength); *m_oChan << (UCHAR)tag->m_style; *m_oChan << (UCHAR)tag->m_attribute; for (i = 0; i < tag->m_numColors; i++) writeDynamicData(tag->m_color[i]); return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeStyleTag(StyleTag *tag) { assert(m_oChan); TUINT32 tagLength = 0, offset; // int maxval=0, minval = 100000; int i; tagLength = 2 + 2; for (i = 0; i < tag->m_numParams; i++) tagLength += 1 + tag->m_param[i].getSize(); offset = writeTagHeader((UCHAR)PliTag::STYLE_NGOBJ, tagLength); *m_oChan << tag->m_id; *m_oChan << tag->m_pageIndex; for (i = 0; i < tag->m_numParams; i++) { *m_oChan << (UCHAR)tag->m_param[i].m_type; switch (tag->m_param[i].m_type) { case TStyleParam::SP_BYTE: *m_oChan << (UCHAR)tag->m_param[i].m_numericVal; break; case TStyleParam::SP_USHORT: *m_oChan << (USHORT)tag->m_param[i].m_numericVal; break; case TStyleParam::SP_INT: case TStyleParam::SP_DOUBLE: writeFloatData((double)tag->m_param[i].m_numericVal); break; case TStyleParam::SP_RASTER: *m_oChan << tag->m_param[i].m_r; break; case TStyleParam::SP_STRING: *m_oChan << tag->m_param[i].m_string; break; default: assert(false); break; } } return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeOutlineOptionsTag(StrokeOutlineOptionsTag *tag) { assert(m_oChan); const double scale = 1000.0; TINT32 miterLower = scale * tag->m_options.m_miterLower; TINT32 miterUpper = scale * tag->m_options.m_miterUpper; setDynamicTypeBytesNum(scale * miterLower, scale * miterUpper); int tagLength = 2 + 2 * m_currDynamicTypeBytesNum; int offset = (int)writeTagHeader((UCHAR)PliTag::OUTLINE_OPTIONS_GOBJ, tagLength); *m_oChan << (UCHAR)tag->m_options.m_capStyle; *m_oChan << (UCHAR)tag->m_options.m_joinStyle; writeDynamicData(miterLower); writeDynamicData(miterUpper); return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writePrecisionScaleTag(PrecisionScaleTag *tag) { assert(m_oChan); setDynamicTypeBytesNum(0, tag->m_precisionScale); int tagLength = m_currDynamicTypeBytesNum; int offset = (int)writeTagHeader((UCHAR)PliTag::PRECISION_SCALE_GOBJ, tagLength); writeDynamicData((TINT32)tag->m_precisionScale); return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeAutoCloseToleranceTag(AutoCloseToleranceTag *tag) { assert(m_oChan); setDynamicTypeBytesNum(0, 10000); int tagLength = m_currDynamicTypeBytesNum; int offset = (int)writeTagHeader((UCHAR)PliTag::AUTOCLOSE_TOLERANCE_GOBJ, tagLength); writeDynamicData((TINT32)tag->m_autoCloseTolerance); return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeGeometricTransformationTag( GeometricTransformationTag *tag) { assert(m_oChan); TUINT32 offset, tagLength; int maxval = 0, minval = 100000; TINT32 intVal[6]; TUINT32 decVal[6]; TUINT32 objectOffset = 0; if (tag->m_object) { if (!(objectOffset = findOffsetFromTag(tag->m_object))) // the object was // not already // written before: // write it now { TagElem elem(tag->m_object, 0); writeTag(&elem); objectOffset = elem.m_offset; addTag(elem); elem.m_tag = 0; } } if (objectOffset < (unsigned int)minval) minval = (int)objectOffset; if (objectOffset > (unsigned int)maxval) maxval = (int)objectOffset; getLongValFromFloat(tag->m_affine.a11, intVal[0], decVal[0]); if (intVal[0] < minval) minval = (int)intVal[0]; if (intVal[0] > maxval) maxval = (int)intVal[0]; if (decVal[0] > (unsigned int)maxval) maxval = (int)decVal[0]; getLongValFromFloat(tag->m_affine.a12, intVal[1], decVal[1]); if (decVal[1] > (unsigned int)maxval) maxval = (int)decVal[1]; if (intVal[1] < minval) minval = (int)intVal[1]; if (intVal[1] > maxval) maxval = (int)intVal[1]; getLongValFromFloat(tag->m_affine.a13, intVal[2], decVal[2]); if (decVal[2] > (unsigned int)maxval) maxval = (int)decVal[2]; if (intVal[2] < minval) minval = (int)intVal[2]; if (intVal[2] > maxval) maxval = (int)intVal[2]; getLongValFromFloat(tag->m_affine.a21, intVal[3], decVal[3]); if (decVal[3] > (unsigned int)maxval) maxval = (int)decVal[3]; if (intVal[3] < minval) minval = (int)intVal[3]; if (intVal[3] > maxval) maxval = (int)intVal[3]; getLongValFromFloat(tag->m_affine.a22, intVal[4], decVal[4]); if (decVal[4] > (unsigned int)maxval) maxval = (int)decVal[4]; if (intVal[4] < minval) minval = (int)intVal[4]; if (intVal[4] > maxval) maxval = (int)intVal[4]; getLongValFromFloat(tag->m_affine.a23, intVal[5], decVal[5]); if (decVal[5] > (unsigned int)maxval) maxval = (int)decVal[5]; if (intVal[5] < minval) minval = (int)intVal[5]; if (intVal[5] > maxval) maxval = (int)intVal[5]; setDynamicTypeBytesNum(minval, maxval); tagLength = (1 + 6 * 2) * m_currDynamicTypeBytesNum; offset = writeTagHeader((UCHAR)PliTag::GEOMETRIC_TRANSFORMATION_GOBJ, tagLength); writeDynamicData(intVal[0]); writeDynamicData(decVal[0]); writeDynamicData(intVal[1]); writeDynamicData(decVal[1]); writeDynamicData(intVal[2]); writeDynamicData(decVal[2]); writeDynamicData(intVal[3]); writeDynamicData(decVal[3]); writeDynamicData(intVal[4]); writeDynamicData(decVal[4]); writeDynamicData(intVal[5]); writeDynamicData(decVal[5]); writeDynamicData(objectOffset); return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeDoublePairTag(DoublePairTag *tag) { TUINT32 offset, tagLength; TINT32 minval = 100000, maxval = 0; TINT32 xIntVal, yIntVal; TUINT32 xDecVal, yDecVal; getLongValFromFloat(tag->m_first, xIntVal, xDecVal); getLongValFromFloat(tag->m_second, yIntVal, yDecVal); if (xIntVal < minval) minval = (int)xIntVal; if (xIntVal > maxval) maxval = (int)xIntVal; if ((int)xDecVal > maxval) maxval = (int)xDecVal; if (yIntVal < minval) minval = (int)yIntVal; if (yIntVal > maxval) maxval = (int)yIntVal; if ((int)yDecVal > maxval) maxval = (int)yDecVal; setDynamicTypeBytesNum(minval, maxval); tagLength = 4 * m_currDynamicTypeBytesNum; offset = writeTagHeader((UCHAR)PliTag::DOUBLEPAIR_OBJ, tagLength); writeDynamicData(xIntVal); writeDynamicData(xDecVal); writeDynamicData(yIntVal); writeDynamicData(yDecVal); return offset; } /*=====================================================================*/ TUINT32 ParsedPliImp::writeBitmapTag(BitmapTag *tag) { assert(m_oChan); TUINT32 offset, tagLength; TRaster32P r = tag->m_r; UINT bmpSize = r->getLx() * r->getLy() * r->getPixelSize(); tagLength = 2 + 2 + bmpSize; offset = writeTagHeader((UCHAR)PliTag::BITMAP_GOBJ, tagLength); *m_oChan << (USHORT)r->getLx(); *m_oChan << (USHORT)r->getLy(); r->lock(); m_oChan->writeBuf(r->getRawData(), bmpSize); r->unlock(); return offset; } /*=====================================================================*/ bool ParsedPliImp::writePli(const TFilePath &filename) { MyOfstream os(filename); if (!os || os.fail()) return false; m_oChan = &os; *m_oChan << c_magicNt; // m_oChan << c_magicIrix; *m_oChan << m_majorVersionNumber; *m_oChan << m_minorVersionNumber; *m_oChan << m_creator; *m_oChan << (TUINT32)0; // fileLength; *m_oChan << m_framesNumber; UCHAR s, i, d; double absAutoClose = fabs(m_autocloseTolerance); s = tsign(m_autocloseTolerance) + 1; i = (UCHAR)((int)absAutoClose); d = (UCHAR)((int)round((absAutoClose - i) * 100)); *m_oChan << s; *m_oChan << i; *m_oChan << d; CHECK_FOR_WRITE_ERROR(filename); m_currDynamicTypeBytesNum = 2; for (TagElem *elem = m_firstTag; elem; elem = elem->m_next) { writeTag(elem); CHECK_FOR_WRITE_ERROR(filename); } *m_oChan << (UCHAR)PliTag::END_CNTRL; m_oChan->close(); m_oChan = 0; return true; } /*=====================================================================*/ /*=====================================================================*/ /*=====================================================================*/ ParsedPli::ParsedPli() { imp = new ParsedPliImp(); } /*=====================================================================*/ ParsedPli::ParsedPli(USHORT framesNumber, UCHAR precision, UCHAR maxThickness, double autocloseTolerance) { imp = new ParsedPliImp(c_majorVersionNumber, c_minorVersionNumber, framesNumber, precision, maxThickness, autocloseTolerance); } /*=====================================================================*/ ParsedPli::~ParsedPli() { delete imp; } /*=====================================================================*/ bool ParsedPli::addTag(PliTag *tag, bool addFront) { return imp->addTag(tag, addFront); } PliTag *ParsedPli::getFirstTag() { imp->m_currTag = imp->m_firstTag; return imp->m_currTag->m_tag; } /*=====================================================================*/ PliTag *ParsedPli::getNextTag() { assert(imp->m_currTag); imp->m_currTag = imp->m_currTag->m_next; return (imp->m_currTag) ? imp->m_currTag->m_tag : NULL; } /*=====================================================================*/ void ParsedPli::setCreator(const QString &creator) { imp->m_creator = creator.toStdString(); } /*=====================================================================*/ QString ParsedPli::getCreator() const { return QString::fromStdString(imp->m_creator); } /*=====================================================================*/ ParsedPli::ParsedPli(const TFilePath &filename, bool readInfo) { imp = new ParsedPliImp(filename, readInfo); } /*=====================================================================*/ void ParsedPli::getVersion(UINT &majorVersionNumber, UINT &minorVersionNumber) const { majorVersionNumber = imp->m_majorVersionNumber; minorVersionNumber = imp->m_minorVersionNumber; } /*=====================================================================*/ void ParsedPli::setVersion(UINT majorVersionNumber, UINT minorVersionNumber) { if (imp->m_versionLocked) { // accept only when settings higher versions if ((imp->m_majorVersionNumber > majorVersionNumber) || (imp->m_majorVersionNumber == majorVersionNumber && imp->m_minorVersionNumber >= minorVersionNumber)) return; } if (majorVersionNumber >= 120) imp->m_versionLocked = true; imp->m_majorVersionNumber = majorVersionNumber; imp->m_minorVersionNumber = minorVersionNumber; } /*=====================================================================*/ bool ParsedPli::writePli(const TFilePath &filename) { return imp->writePli(filename); } /*=====================================================================*/ /* Necessario per fissare un problema di lettura con le vecchie versioni di PLI ( < 3 ). */ double ParsedPli::getThickRatio() const { return imp->m_thickRatio; } /*=====================================================================*/ ParsedPliImp::~ParsedPliImp() { TagElem *tag = m_firstTag; while (tag) { TagElem *auxTag = tag; tag = tag->m_next; delete auxTag; } } /*=====================================================================*/ /*=====================================================================*/ /*=====================================================================*/ /*=====================================================================*/ /*=====================================================================*/ void ParsedPli::loadInfo(bool readPalette, TPalette *&palette, TContentHistory *&history) { imp->loadInfo(readPalette, palette, history); } /*=====================================================================*/ ImageTag *ParsedPli::loadFrame(const TFrameId &frameId) { return imp->loadFrame(frameId); } /*=====================================================================*/ void ParsedPli::setFrameCount(int frameCount) { imp->setFrameCount(frameCount); } /*=====================================================================*/ void ParsedPliImp::setFrameCount(int frameCount) { m_framesNumber = frameCount; } /*=====================================================================*/ int ParsedPli::getFrameCount() const { return imp->getFrameCount(); } /*=====================================================================*/ int ParsedPliImp::getFrameCount() { return m_framesNumber; } /*=====================================================================*/ double ParsedPli::getAutocloseTolerance() const { return imp->m_autocloseTolerance; } /*=====================================================================*/ /*=====================================================================*/ void ParsedPli::setAutocloseTolerance(int tolerance) { imp->m_autocloseTolerance = tolerance; } /*=====================================================================*/ int &ParsedPli::precisionScale() { return imp->m_precisionScale; }
25854a965ecc9fcb503aaf9ebd92fd73b4d9f9ac
32a03ea6bfb49ffcce26e2f5a1ee3f0ed0e87318
/src/Actions.cpp
1d3c289c1d1124838f31dc02aec3e3393bd552ae
[ "MIT" ]
permissive
mjiricka/gongfu-tea-timer
2126cfecde16141ad49b9d46868fdc85463d7e4c
f4bec066d7c5955a7338603ecf10079ccf5a661e
refs/heads/master
2020-03-16T02:26:19.385163
2018-07-02T23:09:50
2018-07-02T23:09:50
132,464,976
0
0
null
null
null
null
UTF-8
C++
false
false
3,871
cpp
Actions.cpp
#include "Actions.h" #include <iostream> #include <string> #include <vector> #include "Settings.h" #include "App.h" using std::string; using std::vector; using std::cout; using std::endl; using std::stoi; Action::~Action() { // Nothing to do... } Action* Action::factory(vector<string> &input) { if (Volume::isMine(input)) { if (input.size() == 2) { return new Volume(input[1]); } else { return new Volume(""); } } if (Info::isMine(input)) { return new Info(); } if (Delete::isMine(input)) { if (input.size() == 2) { return new Delete(input[1]); } else { return new Delete(""); } } if (Reset::isMine(input)) { return new Reset(); } if (Title::isMine(input)) { if (input.size() >= 2) { // TODO: here join all params together! return new Title(input[1]); } else { return new Title(""); } } else { return NULL; } } /******************************************************************** * Volume ********************************************************************/ Volume::Volume(string param) { this->param = param; } void Volume::set(Settings &settings, int volume) { settings.soundVolume = volume; } void Volume::print(Settings &settings) { cout << settings.soundVolume << endl; } bool Volume::isMine(vector<string> &input) { return (input.size() > 0) && (input.front() == "volume"); } void Volume::execute(Settings &settings, App &app) { if (param == "") { print(settings); } else { set(settings, stoi(param)); } } /******************************************************************** * Info ********************************************************************/ bool Info::isMine(vector<string> &input) { return (input.size() > 0) && ( input.front() == "i" || input.front() == "info"); } void Info::execute(Settings &settings, App &app) { app.printer.printSession(app.sessionData); cout << endl; } /******************************************************************** * Delete ********************************************************************/ Delete::Delete(string param) { this->param = param; } bool Delete::isMine(vector<string> &input) { return (input.size() > 0) && (input.front() == "delete"); } void Delete::execute(Settings &settings, App &app) { int sessionIdx; if (param == "") { sessionIdx = app.sessionData.getSessionNum() - 1; } else { sessionIdx = stoi(param); if (sessionIdx < 0) { sessionIdx = app.sessionData.getSessionNum() + sessionIdx; } } app.sessionData.deleteSession(sessionIdx); } /******************************************************************** * Reset ********************************************************************/ bool Reset::isMine(vector<string> &input) { return (input.size() > 0) && (input.front() == "reset"); } void Reset::execute(Settings &settings, App &app) { app.sessionData = SessionData(); app.printer.printSession(app.sessionData); } /******************************************************************** * Title ********************************************************************/ Title::Title(string param) { this->param = param; } void Title::set(SessionData &sessionData, string title) { sessionData.setTitle(title); } void Title::print(SessionData &sessionData) { cout << sessionData.getTitle() << endl; } bool Title::isMine(vector<string> &input) { return (input.size() > 0) && (input.front() == "title"); } void Title::execute(Settings &settings, App &app) { if (param == "") { print(app.sessionData); } else { set(app.sessionData, param); } }
e4d2f72e6e475a5e4c116cc13b28921bfd75cc82
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/devel/electron24/files/patch-electron_shell_browser_native__window.cc
b73f2c99667a353b05efd2a142c1126d6da31210
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C++
false
false
464
cc
patch-electron_shell_browser_native__window.cc
--- electron/shell/browser/native_window.cc.orig 2023-07-26 12:12:20 UTC +++ electron/shell/browser/native_window.cc @@ -197,7 +197,7 @@ void NativeWindow::InitFromOptions(const gin_helper::D } else { SetSizeConstraints(size_constraints); } -#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_BSD) bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable);
1d8f3aaf2c71867b22ff140f0fe12529ce6dd017
1240cab345c126566291f8e461d063cb6430396f
/src/openms/include/OpenMS/MATH/MISC/RANSAC.h
a3f60505a628c720a784c46f90489fe591891a4f
[ "BSD-3-Clause", "BSL-1.0" ]
permissive
OpenMS/OpenMS
05cd6c9a2b8f3004ef47755305711a6631c13340
15e8641e9b6fad76e8314448a808d68231a93088
refs/heads/develop
2023-08-18T03:44:50.273261
2023-08-17T19:45:27
2023-08-17T19:45:27
15,763,403
443
312
NOASSERTION
2023-09-14T13:29:36
2014-01-09T10:15:13
C++
UTF-8
C++
false
false
11,574
h
RANSAC.h
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2023. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/MATH/MISC/RANSACModel.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/MATH/MISC/RANSACModelLinear.h> #include <OpenMS/MATH/MISC/MathFunctions.h> #include <limits> // std::numeric_limits #include <vector> // std::vector #include <sstream> // stringstream namespace OpenMS { namespace Math { /** @brief A simple struct to carry all the parameters required for a RANSAC run. */ struct RANSACParam { /// Default constructor RANSACParam() : n(0), k(0), t(0), d(0), relative_d(false) { } /// Full constructor RANSACParam(size_t p_n, size_t p_k, double p_t, size_t p_d, bool p_relative_d = false) : n(p_n), k(p_k), t(p_t), d(p_d), relative_d(p_relative_d) { if (relative_d) { if (d >= 100) throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("RANSAC: Relative 'd' >= 100% given. Use a lower value; the more outliers you expect, the lower it should be.")); } } [[nodiscard]] std::string toString() const { std::stringstream r; r << "RANSAC param:\n n: " << n << "\n k: " << k << " iterations\n t: " << t << " threshold\n d: " << d << " inliers\n\n"; return r.str(); } size_t n; ///< data points: The minimum number of data points required to fit the model size_t k; ///< iterations: The maximum number of iterations allowed in the algorithm double t; ///< Threshold value: for determining when a data point fits a model. Corresponds to the maximal squared deviation in units of the _second_ dimension (dim2). size_t d; ///< The number of close data values (according to 't') required to assert that a model fits well to data bool relative_d; ///< Should 'd' be interpreted as percentages (0-100) of data input size. }; /** @brief This class provides a generic implementation of the RANSAC outlier detection algorithm. Is implemented and tested after the SciPy reference: http://wiki.scipy.org/Cookbook/RANSAC */ template<typename TModelType = RansacModelLinear> class RANSAC { public: explicit RANSAC(uint64_t seed = time(nullptr)): shuffler_(seed) {} ~RANSAC() = default; /// set seed for random shuffle void setSeed(uint64_t seed) { shuffler_.seed(seed); } /// alias for ransac() with full params std::vector<std::pair<double, double> > ransac( const std::vector<std::pair<double, double> >& pairs, const RANSACParam& p) { return ransac(pairs, p.n, p.k, p.t, p.d, p.relative_d); } /** @brief This function provides a generic implementation of the RANSAC outlier detection algorithm. Is implemented and tested after the SciPy reference: http://wiki.scipy.org/Cookbook/RANSAC If possible, restrict 'n' to the minimal number of points which the model requires to make a fit, i.e. n=2 for linear, n=3 for quadratic. Any higher number will result in increasing the chance of including an outlier, hence a lost iteration. While iterating, this RANSAC implementation will consider any model which explains more data points than the currently best model as even better. If the data points are equal, RSS (residual sum of squared error) will be used. Making 'd' a relative measure (1-99%) is useful if you cannot predict how many points RANSAC will actually receive at runtime, but you have a rough idea how many percent will be outliers. E.g. if you expect 20% outliers, then setting d=60, relative_d=true (i.e. 60% inliers with some margin for error) is a good bet for a larger input set. (Consider that 2-3 data points will be used for the initial model already -- they cannot possibly become inliers). @param pairs Input data (paired data of type <dim1, dim2>) @param n The minimum number of data points required to fit the model @param k The maximum number of iterations allowed in the algorithm @param t Threshold value for determining when a data point fits a model. Corresponds to the maximal squared deviation in units of the _second_ dimension (dim2). @param d The number of close data values (according to 't') required to assert that a model fits well to data @param relative_d Should 'd' be interpreted as percentages (0-100) of data input size @param rng Custom RNG function (useful for testing with fixed seeds) @return A vector of pairs fitting the model well; data will be unsorted */ std::vector<std::pair<double, double> > ransac( const std::vector<std::pair<double, double> >& pairs, size_t n, size_t k, double t, size_t d, bool relative_d = false) { // translate relative percentages into actual numbers if (relative_d) { if (d >= 100) throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("RANSAC: Relative 'd' >= 100% given. Use a lower value; the more outliers you expect, the lower it should be.")); d = pairs.size() * d / 100; } // implementation of the RANSAC algorithm according to http://wiki.scipy.org/Cookbook/RANSAC. if (pairs.size() <= n) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("RANSAC: Number of total data points (") + String(pairs.size()) + ") must be larger than number of initial points (n=" + String(n) + ")."); } TModelType model; std::vector< std::pair<double, double> > alsoinliers, betterdata, bestdata; std::vector<std::pair<double, double> > pairs_shuffled = pairs; // mutable data. will be shuffled in every iteration double besterror = std::numeric_limits<double>::max(); typename TModelType::ModelParameters coeff; #ifdef DEBUG_RANSAC std::pair<double, double > bestcoeff; double betterrsq = 0; double bestrsq = 0; #endif for (size_t ransac_int=0; ransac_int<k; ransac_int++) { // check if the model already includes all points if (bestdata.size() == pairs.size()) break; // use portable RNG in test mode shuffler_.portable_random_shuffle(pairs_shuffled.begin(), pairs_shuffled.end()); // test 'maybeinliers' try { // fitting might throw UnableToFit if points are 'unfortunate' coeff = model.rm_fit(pairs_shuffled.begin(), pairs_shuffled.begin()+n); } catch (...) { continue; } // apply model to remaining data; pick inliers alsoinliers = model.rm_inliers(pairs_shuffled.begin()+n, pairs_shuffled.end(), coeff, t); // ... and add data if (alsoinliers.size() > d || alsoinliers.size() >= (pairs_shuffled.size()-n)) // maximum number of inliers we can possibly have (i.e. remaining data) { betterdata.clear(); std::copy( pairs_shuffled.begin(), pairs_shuffled.begin()+n, back_inserter(betterdata) ); betterdata.insert( betterdata.end(), alsoinliers.begin(), alsoinliers.end() ); typename TModelType::ModelParameters bettercoeff = model.rm_fit(betterdata.begin(), betterdata.end()); double bettererror = model.rm_rss(betterdata.begin(), betterdata.end(), bettercoeff); #ifdef DEBUG_RANSAC betterrsq = model.rm_rsq(betterdata); #endif // If the current model explains more points, we assume its better (these points pass the error threshold 't', so they should be ok); // If the number of points is equal, we trust rss. // E.g. imagine gaining a zillion more points (which pass the threshold!) -- then rss will automatically be worse, no matter how good // these points fit, since its a simple absolute SUM() of residual error over all points. if (betterdata.size() > bestdata.size() || (betterdata.size() == bestdata.size() && (bettererror < besterror))) { besterror = bettererror; bestdata = betterdata; #ifdef DEBUG_RANSAC bestcoeff = bettercoeff; bestrsq = betterrsq; std::cout << "RANSAC " << ransac_int << ": Points: " << betterdata.size() << " RSQ: " << bestrsq << " Error: " << besterror << " c0: " << bestcoeff.first << " c1: " << bestcoeff.second << std::endl; #endif } } } #ifdef DEBUG_RANSAC std::cout << "=======STARTPOINTS=======" << std::endl; for (std::vector<std::pair<double, double> >::iterator it = bestdata.begin(); it != bestdata.end(); ++it) { std::cout << it->first << "\t" << it->second << std::endl; } std::cout << "=======ENDPOINTS=======" << std::endl; #endif return(bestdata); } // ransac() private: Math::RandomShuffler shuffler_{}; }; // class } // namespace Math } // namespace OpenMS
274110c39fe79c3908de6b01b675128e6605d8d0
d1c21ab049eafd42dce19e5cecf6703415d459ff
/Hexic v2.0/Hexic v2.0/Hexagon.cpp
55672bc7c14c53e5d293b7478bd8578a51471f42
[]
no_license
alseether/Hexic
73c8fde1d447cb17cb3fad26d30e6f2bd6d3407a
a22dcb81810b98374d426931356ce34f2cfbdb63
refs/heads/master
2021-06-05T08:34:44.800668
2018-05-21T12:52:52
2018-05-21T12:52:52
48,120,322
0
0
null
2018-05-21T12:07:14
2015-12-16T15:59:27
C++
UTF-8
C++
false
false
2,670
cpp
Hexagon.cpp
#include "Hexagon.hpp" #include "ResourceHolder.hpp" Hexagon::Hexagon(sf::Vector2f center, float side, State::Context context, sf::Color color, sf::Color border) : center(center), color(color) { border = border; this->setSide(side); this->setCenter(center); shape.setFillColor(color); text.setFont(context.fonts->get(Fonts::Main)); text.setCharacterSize(10); } Hexagon::Hexagon(const Hexagon* other): center(other->center), color(other->color) { border = other->getBorder(); this->setSide(other->side); this->setCenter(center); shape.setFillColor(other->color); } Hexagon::~Hexagon() { } void Hexagon::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(shape); target.draw(vertices); target.draw(text); } sf::VertexArray Hexagon::getVertices(){ return this->vertices; } sf::Color Hexagon::getColor() const{ return color; } void Hexagon::setColor(sf::Color color){ this->color = color; } sf::Color Hexagon::getBorder() const{ return border; } void Hexagon::setBorder(sf::Color color){ this->border = color; } std::string Hexagon::getText() const{ return text.getString(); } void Hexagon::setText(std::string text){ this->text.setString(text); } void Hexagon::setCenter(sf::Vector2f cent){ this->center = cent; vertices.clear(); vertices.setPrimitiveType(sf::LineStrip); vertices.append(sf::Vertex(sf::Vector2f(center.x - side / 2, center.y - h), border)); // top-left vertex vertices.append(sf::Vertex(sf::Vector2f(center.x + side / 2, center.y - h), border)); // top-right vertex vertices.append(sf::Vertex(sf::Vector2f(center.x + side, center.y), border)); // right vertex vertices.append(sf::Vertex(sf::Vector2f(center.x + side / 2, center.y + h), border)); // bottom-right vertex vertices.append(sf::Vertex(sf::Vector2f(center.x - side / 2, center.y + h), border)); // bottom-left vertex vertices.append(sf::Vertex(sf::Vector2f(center.x - side, center.y), border)); // left vertex vertices.append(sf::Vertex(sf::Vector2f(center.x - side / 2, center.y - h), border)); // top-left vertex (again, to close the shape shape.setPointCount(6); shape.setPoint(0, vertices[0].position); shape.setPoint(1, vertices[1].position); shape.setPoint(2, vertices[2].position); shape.setPoint(3, vertices[3].position); shape.setPoint(4, vertices[4].position); shape.setPoint(5, vertices[5].position); text.setPosition(center); centerOrigin(text); text.setPosition(center); } sf::Vector2f Hexagon::getCenter(){ return this->center; } void Hexagon::setSide(float newSide){ this->side = newSide; h = sqrt((3 * side*side) / 4); this->setCenter(center); } float Hexagon::getSide(){ return this->side; }
8d29ccf7b6ed715376951b934328c0de1f96ff9d
6e4a14e061d1af3f468bec159860b477444a6be1
/duffTest.cpp
fae5c379b2067a23cfe3da3e5f78ed521ba7493f
[ "MIT" ]
permissive
stuthedew/DuffDevice
100a005145fa995222229e8c422241570cd747e1
45844a8274828c0bb2e1237a5691039b22ef1ad3
refs/heads/master
2016-09-03T06:49:56.132568
2014-11-04T16:11:31
2014-11-04T16:11:31
26,175,021
0
0
null
2014-11-04T16:11:31
2014-11-04T15:29:09
C
UTF-8
C++
false
false
1,943
cpp
duffTest.cpp
#include <iostream> #include <stdio.h> #include <assert.h> #include "stu_duffdevice.h" #define ARRAY_SIZE 10 using namespace std; int writeAry[ARRAY_SIZE]; int readAry[ARRAY_SIZE]; void loopUnroll(int rPtr[], int wPtr[]){ // Handle copy as much as we can with unrolling int loopCycles = (ARRAY_SIZE + 4) / 5; for (int i = 0; i < loopCycles; ++i) { *wPtr++ = *rPtr++; *wPtr++ = *rPtr++; *wPtr++ = *rPtr++; *wPtr++ = *rPtr++; *wPtr++ = *rPtr++; } // Take care of the remainder memory to copy for (int j=0; j < ARRAY_SIZE % 5; ++j) { *wPtr++ = *rPtr++; } } clock_t t = 0; clock_t runTime; int main(int argc, char *argv[]) { cout << endl << "Stuart's Duff device implementation test" << endl; for(int i = 0; i < ARRAY_SIZE; i++){ readAry[i] = random() % 1000; } int *rPtr = readAry; int *wPtr = writeAry; runTime = clock(); for(unsigned int i = 0; i < 500000; i++){ rPtr = readAry; wPtr = writeAry; runTime = clock(); loopUnroll(rPtr, wPtr); t += clock() - runTime; } for(int i = 0; i < ARRAY_SIZE; i++){ assert(readAry[i] == writeAry[i]); } unsigned int nTime = t; cout << endl << "Naive: " << nTime << " clock ticks" << endl; t = 0; runTime = clock(); for(unsigned int i = 0; i < 500000; i++){ rPtr = readAry; wPtr = writeAry; duff(rPtr, wPtr); } t += clock() - runTime; for(int i = 0; i < ARRAY_SIZE; i++){ assert(readAry[i] == writeAry[i]); } unsigned int dTime = t; cout << "Duff: " << dTime << " clock ticks" << endl; double improve = (nTime - dTime); improve /= nTime; int iPercent = improve *100; cout << "Improvment of " << iPercent << "%!" << endl <<endl; }
dc1d7259fbb882b2e303697a6754a27c9dfb5651
f9af249af2422d307c9874c1f407f96644d98a51
/balle.cpp
87b57a84d5504e094d3fad8bc4a9e7520320dbe8
[]
no_license
ParvilusLM/Jeu-Pong
e3c90bca2dd5dc3ec9b0969d16c477909e2f5105
c9148929dcf400bc8630a8202c28620735b0f51d
refs/heads/master
2022-12-17T00:36:43.357281
2020-09-11T03:10:40
2020-09-11T03:10:40
254,775,746
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
balle.cpp
#include "balle.h" Balle::Balle(sf::RenderWindow &fenetre):m_fenetre(0),m_angleBalle(0),m_facteurDepl(0) { m_fenetre=&fenetre; m_vitesseBalle=400; m_tballe.loadFromFile("donnees/balle.png"); m_rayBalle=10.f; initBalle(); } void Balle::initBalle() { do { m_angleBalle=(std::rand()%360)*2*pi/360; } while(std::abs(std::cos(m_angleBalle))<0.7f); m_sballe.setOrigin(m_rayBalle,m_rayBalle); m_sballe.setPosition(largeurF/2,hauteurF/2); m_sballe.setTexture(m_tballe); } sf::Vector2f Balle::getBallePos() { return m_sballe.getPosition(); } void Balle::setBallePos(float posx,float posy) { m_sballe.setPosition(posx,posy); } float Balle::getRayBalle() { return m_rayBalle; } void Balle::deplacementBalle() { m_facteurDepl=m_vitesseBalle*deltaTime; m_sballe.move(std::cos(m_angleBalle)*m_facteurDepl,std::sin(m_angleBalle)*m_facteurDepl); } void Balle::afficherBalle() { m_fenetre->draw(m_sballe); } void Balle::setAngleBalle(bool negatif) { if(negatif==true) { m_angleBalle=-m_angleBalle; } } void Balle::setAngleBalle2(float angle) { m_angleBalle=angle; } float Balle::getAngleBalle() { return m_angleBalle; } Balle::~Balle() { }
5e14b470d52a66ea31fceb5d4080c48314784b14
36f6588952b2d2e90526af34dcff5e17189d27ed
/abc056/abc056_b/4178231.cpp
05915bd96f1d6fce098430af7472f06af5c9f8f7
[]
no_license
key-moon/atcoder
83d097a24b570b0faa6bc56b6a87892441e68976
f1536be7b25317c668fe6302dce3d139bc0ec3d1
refs/heads/master
2020-09-22T00:45:34.193794
2020-02-25T20:07:37
2020-02-25T20:07:37
224,687,083
1
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
4178231.cpp
// detail: https://atcoder.jp/contests/abc056/submissions/4178231 //============================================================================ #include<bits/stdc++.h> typedef long long ll; #define rep(i, n) for(ll i = 0; i < (n); i++) using namespace std; int main(){ int w,a,b; cin >> w >> a >> b; cout << max(0,abs(b - a) - w) << endl; }
645545970663a487587b02eab3aefde3b82f5dae
2e9e9aa6e629b2cbbb36d43705df904652ccead2
/EasyConsole.cpp
81e56435b4620d26c5a53ed57ba97b94b1711125
[]
no_license
michal1000w/graZaliczenie
cc02c3579ed497f525b849ae8bd2b4b4fcf7f104
d2639e2a672842531edbe45afb27af1b1e8afaf5
refs/heads/master
2020-04-08T02:24:43.306676
2019-01-18T13:16:28
2019-01-18T13:16:28
158,934,636
0
0
null
null
null
null
UTF-8
C++
false
false
1,722
cpp
EasyConsole.cpp
#include "EasyConsole.h" void EasyConsole::ConsoleInit(){ setlocale(LC_ALL, ""); // ustawienie kodowania na polskie initscr(); //inicjacja ekranu konsoli noecho(); // nie wyświetla znaku po naciśnięciu klawisza (getch()) keypad(stdscr, true); //oczytuje wszystkie znaki HideCursor(true); //ukrywanie kursora srand(time(NULL)); //resetowanie czasu } void EasyConsole::ColorInit() { start_color(); use_default_colors(); } void EasyConsole::Color(int col){ //inicjacja kolorów init_pair(1, COLOR_WHITE, -1); init_pair(2, COLOR_RED, -1); init_pair(3, COLOR_GREEN, -1); init_pair(4, COLOR_BLUE, -1); init_pair(5, COLOR_MAGENTA, -1); init_pair(6, COLOR_YELLOW, -1); init_pair(7, COLOR_CYAN, -1); init_pair(8, COLOR_WHITE, COLOR_WHITE); //ustawianie koloru attron(COLOR_PAIR(col)); } void EasyConsole::ColorEnd(){ attroff(COLOR_PAIRS); } void EasyConsole::BoldText(bool a){ if (a == true) attron(A_BOLD); else attroff(A_BOLD); } void EasyConsole::UnderlineText(bool a){ if (a == true) attron(A_UNDERLINE); else attroff(A_UNDERLINE); } void EasyConsole::HideCursor(bool a){ if (a == true) curs_set(0); else curs_set(1); } void EasyConsole::BlinkText(bool a){ if (a == true) attron(A_BLINK); else attroff(A_BLINK); } void EasyConsole::ClearScr(){ clear(); refresh(); } void EasyConsole::Sleep(float time){ usleep(time * 1000); }
e7e815e39de0293f63361d9f0f35cf384776068f
c6a9053e6cf80128afa93f763ba6638234a40f35
/include/zapi/bridge/Extension.h
d7f283c2e61bf7af299695f4aa34f170a4942c5c
[ "Apache-2.0" ]
permissive
zhsongbj/zendapi
7071473bf4e32bbc09f540bcd0befe0fca903289
36158efc5bd8aa2a2f6d68e426a69c5cfd136a5e
refs/heads/master
2021-01-25T04:58:33.857795
2017-06-06T08:14:24
2017-06-06T08:14:24
93,493,824
1
0
null
2017-06-06T08:19:57
2017-06-06T08:19:57
null
UTF-8
C++
false
false
4,639
h
Extension.h
// Copyright 2017-2018 zzu_softboy <zzu_softboy@163.com> // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Created by softboy on 18/05/2017. // #ifndef ZAPI_BRIDGE_EXTENSION_H #define ZAPI_BRIDGE_EXTENSION_H #include "zapi/Global.h" namespace zapi { namespace bridge { class ExtensionPrivate; class ZAPI_DECL_EXPORT Extension { public: /** * Constructor that defines a number of functions right away * * The first two parameters should be filled by the extension programmer with the * name of the extension, and the version number of the extension (like "1.0"). * The third parameter, apiversion, does not have to be supplied and is best kept * to the default value. This third parameter checks whether the PHP-CPP version * that is currently installed on the server is the same as the PHP-CPP version * that was used to compile the extension with. * * @param name Extension name * @param version Extension version string * @param apiversion ZAPI API version (this should always be ZAPI_API_VERSION, so you better not supply it) */ Extension(const char *name, const char *version = "1.0", int apiVersion = ZAPI_API_VERSION); Extension(const Extension &extension) = delete; Extension(Extension &&extension) = delete; operator void * () { return getModule(); } /** * Register a function to be called when the PHP engine is ready * * The callback will be called after all extensions are loaded, and all * functions and classes are available, but before the first pageview/request * is handled. You can register this callback if you want to be notified * when the engine is ready, for example to initialize certain things. * * @param Callback callback Function to be called * @return Extension Same object to allow chaining */ Extension &setStartupHandler(const Callback &callback); /** * Register a function to be called when the PHP engine is going to stop * * The callback will be called right before the process is going to stop. * You can register a function if you want to clean up certain things. * * @param callback Function to be called * @return Extension Same object to allow chaining */ Extension &setShutdownHandler(const Callback &callback); /** * Register a callback that is called at the beginning of each pageview/request * * You can register a callback if you want to initialize certain things * at the beginning of each request. Remember that the extension can handle * multiple requests after each other, and you may want to set back certain * global variables to their initial variables in front of each request * * @param Callback callback Function to be called * @return Extension Same object to allow chaining */ Extension &setRequestHandler(const Callback &callback); /** * Register a callback that is called to cleanup things after a pageview/request * * The callback will be called after _each_ request, so that you can clean up * certain things and make your extension ready to handle the next request. * This method is called onIdle because the extension is idle in between * requests. * * @param Callback callback Function to be called * @return Extension Same object to allow chaining */ Extension &setIdleHandler(const Callback &callback); /** * Retrieve the module pointer * * This is the memory address that should be exported by the get_module() * function. * * @return void* */ void *getModule(); virtual ~Extension() {} protected: virtual bool locked() const; private: /** * The implementation object * * @var std::unique_ptr<ExtensionPrivate> m_implPtr */ std::unique_ptr<ExtensionPrivate> m_implPtr; }; } // bridge } // zapi #endif //ZAPI_BRIDGE_EXTENSION_H
a1a13969c7bef676c50069848dc1f458ec12adb2
95d426de781b011b0ee8d82d8b976720fc2613f6
/HCT138.cpp
3ca6a796e60e91dd564c14d0afe1cb5a8952e03f
[]
no_license
jkytomaki/vtxLapTimer
d3184dece563d35c312229001a2c11e830458c45
e75977e493a474f1962339842f532f6454903f8b
refs/heads/master
2020-12-25T05:16:36.730242
2016-08-04T17:13:44
2016-08-04T17:13:44
64,881,167
1
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
HCT138.cpp
#include <Arduino.h> void setPinHigh(int pin){ digitalWrite(D8, HIGH); digitalWrite(D0, bitRead(pin, 0)); digitalWrite(D1, bitRead(pin, 1)); digitalWrite(D2, bitRead(pin, 2)); } void setPinLow(int pin){ digitalWrite(D8, LOW); digitalWrite(D0, bitRead(pin, 0)); digitalWrite(D1, bitRead(pin, 1)); digitalWrite(D2, bitRead(pin, 2)); }
ea607b699a5016e538a5161d1eaa628436a77688
0e6e81a3788fd9847084991c3177481470546051
/AnswerByCpp/0047_Permutations II.cpp
5bd89e119e6330c52d62816be5ca69dfcff27486
[]
no_license
Azhao1993/Leetcode
6f84c62620f1bb60f82d4383764b777a4caa2715
1c1f2438e80d7958736dbc28b7ede562ec1356f7
refs/heads/master
2020-03-25T19:34:30.946119
2020-03-05T14:28:17
2020-03-05T14:28:17
144,089,629
4
2
null
2019-11-18T00:30:31
2018-08-09T02:10:26
C++
UTF-8
C++
false
false
2,064
cpp
0047_Permutations II.cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; /* 47. 全排列 II 给定一个可包含重复数字的序列,返回所有不重复的全排列。 示例: 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ] */ class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> res; sort(nums.begin(),nums.end()); // vector<int> tem; // vector<bool> flag(nums.size(),false); // dfs(res,nums,tem,flag); helper(res,nums,0); return res; } void helper(vector<vector<int>>& res,vector<int> nums,int left){ if(left == nums.size()){ res.push_back(nums); return ; } for(int i=left;i<nums.size();++i){ // 与后面的每一个数交换并存储 当前数与需要交换的数相同时跳过 if(i>left && nums[i] == nums[left])continue; swap(nums[i],nums[left]); helper(res,nums,left+1); } } void dfs(vector<vector<int>>& res, vector<int> nums, vector<int> tem, vector<bool> flag){ if(tem.size()==nums.size()){ res.push_back(tem); return ; } for(int i=0;i<nums.size();++i){ // 同样的元素,先排最后一个,再排前面的 去重 // if(i+1<nums.size() && nums[i]==nums[i+1] && !flag[i+1])continue ; // 同样的元素,先第一个,再排后面的 当前面的排过后就不排重复的元素 if(i>0 && nums[i]==nums[i-1] && flag[i-1])continue ; if(flag[i])continue ; flag[i] = true; tem.push_back(nums[i]); dfs(res,nums,tem,flag); tem.pop_back(); flag[i] = false; } } }; int main(){ vector<int> a({1,3,3,3,2}); Solution* so = new Solution(); vector<vector<int>> arr = so->permuteUnique(a); for(auto it:arr){ for(auto n:it) cout<<n<<' '; cout<<endl; } return 0; }
b1eaa4899f1762a6d41994bbe88050411881d90a
0a35a623333fc370df0ff4777ac74db40819faea
/ros_homework/src/t2_turtle_listener.cpp
95ad6acff51ee366ceb470f621631a8c3f5c96b9
[]
no_license
suyunzzz/ROS_homework
973353109c9af707ffb0d348960c84cb39c8c0d4
f6b811ab9b31448a4ca3111435a893c9410bbb7f
refs/heads/master
2020-06-18T17:23:39.093027
2019-07-16T15:26:14
2019-07-16T15:26:14
196,380,603
3
0
null
null
null
null
UTF-8
C++
false
false
866
cpp
t2_turtle_listener.cpp
/***** *此节点是作业2的listener,将订阅/turtle2/pose,消息类型是turtlesim::Pose *此节点可有可无,因为订阅该话题完全可以由turtle2_creater节点实现(与turtlesim双向通信) *作者:苏云征 ***/ #include<ros/ros.h> //#include<geometry_msgs/Twist.h> #include<turtlesim/Pose.h> void turtle2_call_back(const turtlesim::PoseConstPtr msg) //自定义定义回调函数 { ROS_INFO("Turtle2 postion : (%f,%f,%f,%f,%f)",msg->x,msg->y,msg->theta,msg->linear_velocity,msg->angular_velocity); } int main (int argc,char **argv) { ros::init(argc, argv, "turtle2_listener"); //初始化节点名称 ros::NodeHandle node; //创建句柄 ros::Subscriber sub = node.subscribe("turtle2/pose",10,turtle2_call_back); //定义一个订阅者,订阅的话题是turtle2/pose ros::spin(); return 0; }
58493ba507198b47b711e1268a76e994f5d18dd8
8d7c126fbdbf04a7c6be986964f71b8f11b92d99
/errorf.cpp
c48ba034350701590e61f64a76ccea20e931604a
[]
no_license
antonislambrou/GACP
4c4dcc06fa2955359aea74fe71780d66c421e969
26ef820b0342c75e07b929312e40008ef5f84cd5
refs/heads/master
2016-09-13T13:13:21.362843
2016-05-07T11:40:24
2016-05-07T11:40:24
57,453,612
0
0
null
null
null
null
UTF-8
C++
false
false
254
cpp
errorf.cpp
//return 1 for error, 0 otherwise #include "global.h" int errorf(double err,double p[],int actual) { int y=1; for(int i=1; i<=classes;i++) { if(p[i-1] > err && i == actual) { y = 0; break; } } return y; }
05fd493553dfb97a249a60cda21ff06a69d64396
f00687b9f8671496f417672aaf8ddffc2fa8060a
/codeforces/884/E2.cpp
a6fa71e082c8c8b9859042c48f6a4c570869ecd5
[]
no_license
kazi-nayeem/Programming-Problems-Solutions
29c338085f1025b2545ff66bdb0476ec4d7773c2
7ee29a4e06e9841388389be5566db34fbdda8f7c
refs/heads/master
2023-02-05T15:06:50.355903
2020-12-30T10:19:54
2020-12-30T10:19:54
279,388,214
2
2
null
null
null
null
UTF-8
C++
false
false
2,278
cpp
E2.cpp
#include <cstdio> #include <queue> //#include <bits/stdc++.h> using namespace std; typedef pair<short,short> pii; int dx[]= {0,0,1,-1};/*4 side move*/ int dy[]= {-1,1,0,0};/*4 side move*/ #define MX 100005 #define inf 100000000 char mat[(1<<12)][(1<<11)]; char check(char mask, int pos) { return (mask>>(7-pos))&1; } char setBit(char mask, int pos) { return mask^(1<<(7-pos)); } bool isone(int x, int y) { return check(mat[x][y>>3],y&7); } void setVisited(int x, int y) { mat[x][y>>3] = setBit(mat[x][y>>3],y&7); } int cnt; int n, m; queue<pii> qu; void dfs(int x, int y) { //deb(x,y); if(x<0 || y < 0 || x >= n || y >= m) return; //deb("--",x,y); if(isone(x,y) == 0) return; setVisited(x,y); qu.push(make_pair(x,y)); cnt = 0; while(!qu.empty()) { int x = qu.front().first; int y = qu.front().second; qu.pop(); cnt++; for(int i = 0; i < 4; i++) { int tx = x+dx[i]; int ty = y+dy[i]; if(tx<0 || ty < 0 || tx >= n || ty >= m) continue; //deb("--",x,y); if(isone(tx,ty) == 0) continue; setVisited(tx,ty); qu.push(make_pair(tx,ty)); } } } char str[MX]; int main() { // ios_base::sync_with_stdio(0); // freopen("00.txt", "r", stdin); scanf("%d %d", &n, &m); for(int i = 0; i < n; i++) { scanf("%s", str); for(int j = 0; j < (m>>2); j++) { int v; if(str[j]>='0' && str[j] <= '9') v = str[j]-'0'; else v = str[j]-'A'+10; if(j%2 == 0) v = (v<<4); //deb(v); mat[i][j/2] = mat[i][j/2]|v; //deb((int) mat[i][j/2]); } } // for(int i = 0; i < n; i++, puts("")) // for(int j = 0; j < m; j++) { // printf("%d", isone(i,j)); // } int ans = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) { cnt = 0; dfs(i,j); ans += cnt != 0; } printf("%d\n", ans); return 0; }
2656e76264de99c9825f3d6f31c7c9586c3a35df
eae4549cbcab075813b2e7756bdd28b3106a22fe
/list/DL/Node.h
bb7b72420f2fd051bf7f7a20240d0521ded58a50
[ "MIT" ]
permissive
devgr/data-structures
65db7c2722810349bc3468fd68e33e2b3cd9be8f
e6467acc67ee6243b57a92674a9e406ce9b4981c
refs/heads/master
2020-05-01T11:48:53.897009
2013-12-27T04:12:01
2013-12-27T04:12:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
601
h
Node.h
/** Node.h George Darling 9/5/2013 Header file for the Node type. Each node points to a next node and a previous node, forming a doubly linked list. There is a spot to hold data; this can either be modified to fit the needs of the program, or point to some other data containing type. */ #include "Data.h" using namespace std; class Node{ Data * data; Node * next; // these are private, Node and List are friends so Node * prev; // they can access and change. public: Node(Data*, Node*, Node*); // data, prev, next ~Node(); // destruct the node Data * getData(); friend class List; };
a54df2ce647e480166341186488c6ebd04f4309a
a4f927122775e7c27e7d56a97d9c3fe4d0652616
/main.cpp
af0e00d66cd54146ec97c4037daf546bf727fa0f
[]
no_license
hypa6816/Park_CSCI2270_FinalProject
65368a97d8314edc1382cfb4570ba1d7b94dbe76
960a94a42ec1697d19117c2dd5e4c746480af0f8
refs/heads/master
2020-12-24T21:22:39.647011
2016-04-27T19:43:15
2016-04-27T19:43:15
56,077,423
0
1
null
2016-05-04T03:47:02
2016-04-12T15:55:59
C++
UTF-8
C++
false
false
4,207
cpp
main.cpp
#include "Keyboard.h" #include <iostream> #include <vector> #include <sstream> #include <string> #include <stdlib.h> using namespace std; int main() { Keyboard KB; //Start up the menu int option = 0; do { cout << "======Main Menu======" << endl; cout << "1. Create Keyboard" << endl; cout << "2. Print Keyboard" << endl; cout << "3. Directions to Type a Word" << endl; cout << "4. Find and Print the Key Index" << endl; cout << "5. Print all indexes of Keyboard" <<endl; cout << "6. Check if a Letter is in the Keyboard" << endl; cout << "7. Change length of Keyboard" << endl; cout << "8. Change width of Keyboard" << endl; cout << "9. Rotate the Keyboard" <<endl; cout << "10. Delete the Keyboard" <<endl; cout << "11. Quit" << endl; cin >> option ; cin.ignore(); switch(option) { case 1: { //Create The Keyboard string rowString; string columnString; cout<< "Enter the length of the keyboard:" <<endl; getline(cin,rowString); cin.ignore(); cout<< "Enter the width of the keyboard:" <<endl; getline(cin,columnString); cin.ignore(); //converting into integer KB.Row = atoi(rowString.c_str()); KB.Column = atoi(columnString.c_str()); KB.createKeyboard(KB.Row,KB.Column); break; } case 2: { //print KB.printKeyboard(); break; } case 3: { //Word Directions string word; cout<< "Please enter a word (in CAPS): "<<endl; getline(cin, word); cin.ignore(); KB.wordDirections(word); break; } case 4: { //Find the letter's index string letter; cout<< "Please enter a letter (in CAPS): "<<endl; getline(cin, letter); cin.ignore(); int *index; //index is a pointer to an array index = KB.findKeyIndex(letter); int row = *(index+0); //row is the first int column = *(index+1); cout<< "The row of letter, "<<letter<< " is " <<row<<endl; cout<< "The column of letter, "<<letter<< " is " <<column<<endl; break; } case 5: { //print all indexes of the keys KB.printIndexes(); break; } case 6: { //check if letter is in the keyboard string letter; bool found; cout<< "Please enter a letter (in CAPS): "<<endl; getline(cin, letter); cin.ignore(); found = KB.isLetterInKeyboard(letter); if(found==true){ cout<<"The letter is in the keyboard."<<endl; } else{ cout<<"The letter is not in the keyboard."<<endl; } break; } case 7: { //Change length of keyboard string newRowString; cout<< "Please enter the new length of the keyboard: "<<endl; getline(cin, newRowString); int newRow = atoi(newRowString.c_str()); KB.changeLength(newRow); break; } case 8: { //Change width of keyboard string newColumnString; cout<< "Please enter the new width of the keyboard: "<<endl; getline(cin, newColumnString); int newColumn = atoi(newColumnString.c_str()); KB.changeWidth(newColumn); break; } case 9: { //Rotate Keyboard KB.rotateKeyboard(); break; } case 10: { //Delete Keyboard KB.deleteKeyboard(); break; } case 11: { //Quit cout << "Goodbye!" << endl; break; } } } while(option!=11); }
3589409ae58c9ad5e05eaf0d019172bc73df4f5f
fc7359b2aebff4580611767fa0d622c5ba642c9c
/3rdParty/iresearch/tests/utils/compression_tests.cpp
b94b8e0d6d7d84c156708c8654cb33d012e10d38
[ "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "Unicode-DFS-2016", "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "Bison-exception-2.2", "BSD-2-Clause", "GPL-3.0-only", "BSD-4-Clause", "LGPL-2.1-or-later"...
permissive
William533036/arangodb
36106973f1db1ffe2872e36af09cbdc7f0ba444b
08785b946a21c127bcc22f6950d8c3f9bc2c5d76
refs/heads/master
2020-12-06T23:09:43.024228
2019-12-30T08:16:24
2019-12-30T08:16:24
232,570,534
1
0
Apache-2.0
2020-01-08T13:33:37
2020-01-08T13:33:36
null
UTF-8
C++
false
false
1,956
cpp
compression_tests.cpp
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 by EMC Corporation, All Rights Reserved /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is EMC Corporation /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #ifndef IRESEARCH_COMPRESSION_TESTS_H #define IRESEARCH_COMPRESSION_TESTS_H #include "tests_shared.hpp" #include "utils/compression.hpp" namespace tests { namespace detail { using namespace iresearch; void compress_decompress_core( const bytes_ref& src) { compressor cmp( src.size()); cmp.compress( src); decompressor dcmp( src.size()); dcmp.decompress( cmp.data()); tests::assert_equal(src, dcmp.data()); } } // detail } // tests TEST( compression_tests, compress_decompress) { using namespace iresearch; const bytes_ref alphabet( reinterpret_cast< const byte_type* >(alphabet::ENGLISH), strlen(alphabet::ENGLISH) ); tests::detail::compress_decompress_core( generate<bytes>( alphabet, 12314U)); tests::detail::compress_decompress_core( generate<bytes>( alphabet, 1024U)); tests::detail::compress_decompress_core( generate<bytes>( alphabet, 512U)); tests::detail::compress_decompress_core( generate<bytes>( alphabet, 128U)); tests::detail::compress_decompress_core( bytes_ref::NIL); } #endif
050a6096f22fe2a42e86640ddaa4453606bcbe52
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/3rdParty/boost/1.78.0/boost/vmd/detail/sequence_size.hpp
0f308eb82945f9a8ef7942af6eb632bda8c76762
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C++
false
false
723
hpp
sequence_size.hpp
// (C) Copyright Edward Diener 2011-2015 // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #if !defined(BOOST_VMD_DETAIL_SEQUENCE_SIZE_HPP) #define BOOST_VMD_DETAIL_SEQUENCE_SIZE_HPP #include <boost/preprocessor/array/size.hpp> #include <boost/vmd/detail/sequence_to_array.hpp> #define BOOST_VMD_DETAIL_SEQUENCE_SIZE(vseq) \ BOOST_PP_ARRAY_SIZE(BOOST_VMD_DETAIL_SEQUENCE_TO_ARRAY(vseq)) \ /**/ #define BOOST_VMD_DETAIL_SEQUENCE_SIZE_D(d,vseq) \ BOOST_PP_ARRAY_SIZE(BOOST_VMD_DETAIL_SEQUENCE_TO_ARRAY_D(d,vseq)) \ /**/ #endif /* BOOST_VMD_DETAIL_SEQUENCE_SIZE_HPP */
3a9acfe24c668b540263187ffebd2f727d2c2309
e798f8dabca00cd8e8477d04beb77d78aae6c82a
/Imgproc/affinetransformation.cpp
f80ee8bb7358e0cccaa75d9ecef0e0b2e83afada
[ "MIT" ]
permissive
manashmandal/ImageProcessingToolbox
e956d721b68b0b39ba6de286ee82d73bb8948972
df0cd88af41d88190de882ba7ef8693483b67211
refs/heads/master
2021-06-02T05:10:57.183023
2016-06-26T19:38:36
2016-06-26T19:38:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,286
cpp
affinetransformation.cpp
#include "affinetransformation.h" #include "ui_affinetransformation.h" AffineTransformation::AffineTransformation(QWidget *parent) : QWidget(parent), ui(new Ui::AffineTransformation) { ui->setupUi(this); } AffineTransformation::AffineTransformation(Mat img) : originalImage(img), ui(new Ui::AffineTransformation), rotation_mat(2, 3, CV_32FC1), warp_mat(2, 3, CV_32FC1), warpDst(Mat::zeros(img.rows, img.cols, img.type())), angle(0.0), scale(1.0) { ui->setupUi(this); ui->image->setPixmap(ImageHandler::getQPixmap(originalImage)); ui->imageScrollArea->setSizeAdjustPolicy(QScrollArea::AdjustToContents); sourceTriangle[0] = Point2f(0, 0); sourceTriangle[1] = Point2f(img.cols -1, 0); sourceTriangle[2] = Point2f(0, img.rows - 1); destinationTriangle[0] = Point2f(img.cols * 0.0, img.rows * 0.33); destinationTriangle[1] = Point2f(img.cols * 0.85, img.rows * 0.25); destinationTriangle[2] = Point2f(img.cols * 0.15, img.rows * 0.7); warp_mat = getAffineTransform(sourceTriangle, destinationTriangle); warpAffine(originalImage, warpDst, warp_mat, warpDst.size()); center = Point(warpDst.cols / 2, warpDst.rows / 2); } AffineTransformation::~AffineTransformation() { delete ui; } void AffineTransformation::affineTransform(float angle, float scale) { rotation_mat = getRotationMatrix2D(center, angle, scale); warpAffine(warpDst, warp_rotate_dst, rotation_mat, warpDst.size()); ui->image->setPixmap(ImageHandler::getQPixmap(warp_rotate_dst)); } void AffineTransformation::on_pointButton_clicked(bool checked) { if (checked){ QMessageBox::about(this, "This function is not available", "This function will be added later"); } ui->pointButton->setChecked(false); } void AffineTransformation::on_angleSlider_sliderMoved(int position) { angle = float(position); affineTransform(angle, scale); } void AffineTransformation::on_scaleSlider_sliderMoved(int position) { scale = float(position) / 100.0; affineTransform(angle, scale); } void AffineTransformation::on_autoFitCheckBox_clicked(bool checked) { ui->image->setScaledContents(checked); } void AffineTransformation::on_resetButton_clicked() { ui->image->setPixmap(ImageHandler::getQPixmap(originalImage)); }
b56dad4a9b6c37f593359e8558f040d577f55d44
d7d286bf071822dd6fff0e5fa6baa120b352286a
/hanoipanel.h
73b5fa3776528ac80da76d1fab3fbc24b236e747
[]
no_license
husama/HanoiTower
bd47496caae00608ecad8d9cb84b4f2d8ddf982f
c39bd9a92eea0f03045dfa32312a02da88ef67a6
refs/heads/master
2021-01-10T10:12:46.860452
2016-03-29T10:58:04
2016-03-29T10:58:04
54,965,660
2
1
null
null
null
null
UTF-8
C++
false
false
2,332
h
hanoipanel.h
#ifndef HANOIPANEL_H #define HANOIPANEL_H #include <QGraphicsItemAnimation> #include <QWidget> #include <QComboBox> #include <QSlider> #include <QGraphicsView> #include <QLabel> #include <QPushButton> #include <QLayout> #include <QTimer> #include <QPalette> #include <QStack> #include <QTimeLine> #include <QThread> #include <QPropertyAnimation> #include <QDebug> #include <QTimeLine> #include <QEventLoop> #include <QPauseAnimation> #include <QElapsedTimer> #include <QCoreApplication> #include <QTextEdit> #include <QTextBrowser> #include <QFont> #include "disk.h" #include "diskstack.h" #include "showstack.h" struct group { int n; diskstack *x,*y,*z; group(int v=0,diskstack *i=NULL,diskstack *j=NULL, diskstack *k=NULL) { n = v; x = i,y = j,z = k; } }; class hanoiPanel : public QWidget { Q_OBJECT public: explicit hanoiPanel(QWidget *parent = 0); //menu QComboBox *numComboBox; QSlider *speedSlider; QHBoxLayout *menuContainer,*hanoiContainer,*hcontainer1,*hcontainer2; QVBoxLayout *container,*vcontainer; QPushButton *start1,*start2,*stop,*reset; QLabel *numLabel,*speedLabel; QLabel *fromtoLabel,*codeLabel,*paraLabel; QStringList *values; //hanoi tower Graphics view QGraphicsScene *hanoiScene; QGraphicsView *hanoiView; showstack *stackwin; QTextEdit *showfromto,*showpara; QTextBrowser *showcode; //number int num; int speed; bool state; bool resetState; bool pauseState; int curNum,maxNum;//迭代算法的实时入栈数目和最大入栈数目 int moveNum; diskstack StackA,StackB,StackC; QTimer *timer; // QStack<QLabel> labelStackA,labelStackB,labelStackC; void algorithm(int n, diskstack *A, diskstack *B,diskstack *C); void algorithm2(int n, diskstack *A, diskstack *B,diskstack *C); void diskmove(diskstack*, diskstack*); void getdraw(); //void highLightCode(QString *); signals: void sendPush(int, int, int, int); void sendPop(); void sendSpeed(int); void sendMaxNum(int); void sendMoveNum(int); void sendClear(); public slots: void applystart(); void applystart2(); void applystop(); void applyreset(); void applyspeedchange(); void applynewstackwin(); }; #endif // HANOIPANEL_H
59414ec942308864c0e1c0f3f7c2cd11d3bf46b6
2fd059b7c5234015eba056b2f3d9b1197df4a60d
/include/ReductionQualityChecker.h
e9f6b35acb5e592de3ec2496361291370b13be2e
[ "MIT" ]
permissive
FredericJacobs/Lattices-Jacobi_Method
64069d7346e59a4a6d17d306bdd4d96fea09160e
28025931a59c34e00fc413febf6d1bb0625f5487
refs/heads/master
2021-01-02T09:02:13.474738
2015-01-22T21:50:22
2015-01-22T21:50:22
23,916,539
1
0
null
null
null
null
UTF-8
C++
false
false
375
h
ReductionQualityChecker.h
#ifndef REDUCTIONQUALITYCHECKER_H #define REDUCTIONQUALITYCHECKER_H #include <newNTL/mat_ZZ.h> #include <newNTL/matrix.h> #include <newNTL/RR.h> class ReductionQualityChecker { public: static newNTL::RR computeHermiteFactor(newNTL::mat_ZZ &mat); static newNTL::RR computeOrthogonalityDefect(newNTL::mat_ZZ &mat); protected: private: }; #endif // MATRIXFACTORY_H
af26b05daece097bcedbddc1525c703f19c2c1e7
9402379373dceaacddbd68911410df582f763246
/src/tlocCore/utilities/tlocCheckpoints.cpp
d8804dffc7045036b21f939ddab3c3ca0422c626
[]
no_license
samaursa/tlocEngine
45c08cf4c63e618f0df30adc91b39f58c7978608
5fab63a31af9c4e266d7805a24a3d6611af71fa7
refs/heads/master
2022-12-30T20:10:38.841709
2014-09-12T07:36:27
2014-09-12T07:36:27
305,503,446
2
0
null
null
null
null
UTF-8
C++
false
false
2,128
cpp
tlocCheckpoints.cpp
#include "tlocCheckpoints.h" #include <tlocCore/containers/tlocContainers.inl.h> namespace tloc { namespace core { namespace utils { Checkpoints:: Checkpoints(tl_uint a_numberOfCheckpoints, bool a_initial) : m_flags(a_numberOfCheckpoints, a_initial) { } Checkpoints::value_type& Checkpoints:: operator [](tl_int a_index) { return m_flags[a_index]; } Checkpoints::value_type Checkpoints:: operator [](tl_int a_index) const { return m_flags[a_index]; } bool Checkpoints:: IsMarked(tl_int a_index) const { return m_flags[a_index]; } bool Checkpoints:: IsUnMarked(tl_int a_index) const { return m_flags[a_index] == false; } void Checkpoints:: MarkAll() { SetAllTo(true); } void Checkpoints:: UnmarkAll() { SetAllTo(false); } void Checkpoints:: ToggleAll() { for (flags_type::iterator itr = m_flags.begin(), itrEnd = m_flags.end(); itr != itrEnd; ++itr) { *itr = !(*itr); } } void Checkpoints:: SetAllTo(value_type a_flag) { for (flags_type::iterator itr = m_flags.begin(), itrEnd = m_flags.end(); itr != itrEnd; ++itr) { *itr = a_flag; } } void Checkpoints:: Mark(size_type a_index) { m_flags[a_index] = true; } void Checkpoints:: Unmark(size_type a_index) { m_flags[a_index] = false; } void Checkpoints:: Toggle(size_type a_index) { m_flags[a_index] = !m_flags[a_index]; } Checkpoints::value_type Checkpoints:: ReturnAndMark(size_type a_index) { value_type toRet = IsMarked(a_index); Mark(a_index); return toRet; } Checkpoints::value_type Checkpoints:: ReturnAndUnmark(size_type a_index) { value_type toRet = IsMarked(a_index); Unmark(a_index); return toRet; } Checkpoints::value_type Checkpoints:: ReturnAndToggle(size_type a_index) { value_type toRet = IsMarked(a_index); Toggle(a_index); return toRet; } };};};
3440a45011efc6c7d26ed538d02d0ec34e0d7c5c
67e8364603f885231b6057abd6859e60562a4008
/Cpp/300_LongestIncreasingSubsequence/002.cpp
ebe7aa783d89f3b0a11a4586326cabec7ff9507d
[]
no_license
NeighborUncleWang/Leetcode
988417721c4a395ac8800cd04e4d5d973b54e9d4
d5bdbdcd698006c9997ef0e368ffaae6f546ac44
refs/heads/master
2021-01-18T22:03:27.400480
2019-02-22T04:45:52
2019-02-22T04:45:52
36,253,135
0
0
null
null
null
null
UTF-8
C++
false
false
382
cpp
002.cpp
class Solution { public: int lengthOfLIS(vector<int>& nums) { vector<int> result; for (int num : nums) { auto it = lower_bound(result.begin(), result.end(), num); if (it == result.end()) { result.push_back(num); } else { *it = num; } } return result.size(); } };
f0673771cf2ca525c3240696b50bd22b4a2e3c09
132c3adaa9f04851b3d9dc342190a30f1bc3cd45
/Kamikaze/Main_Kamikaze.cpp
b85d3c862a073b18993d7ff708df41aa59c7d87a
[]
no_license
blakesullivan/TRON-Kamikaze
72ae9191b6262be0fb5443d0cc987942de8af3e0
ce38db90449abcceb8a0bf41dbb37f1de07fbd1c
refs/heads/master
2020-09-03T08:33:10.604113
2019-11-04T05:24:45
2019-11-04T05:24:45
219,427,028
0
0
null
null
null
null
UTF-8
C++
false
false
2,235
cpp
Main_Kamikaze.cpp
//Blake Sullivan - Main.cpp #include "GameManage.h" #include <Windows.h> //The attributes of the screen const int SCREEN_WIDTH = 800; const int SCREEN_HEIGHT = 600; const int SCREEN_BPP = 32; //Bits Per Pixel SDL_Surface *screen = NULL; //the pointer to the screen in memory /* Mix_Chunk is like Mix_Music, only it's for ordinary sounds. */ //Mix_Chunk *phaser = NULL; //Mix_Music *game = NULL; /* Every sound that gets played is assigned to a channel. Note that this is different from the number of channels you request when you open the audio device; a channel in SDL_mixer holds information about a sound sample that is playing, while the number of channels you request when opening the device is dependant on what sort of sound you want (1 channel = mono, 2 = stereo, etc) */ //int phaserChannel = -1; int main(int argc, char *argv[]) { FreeConsole(); GameManage GM; SDL_Event event; bool bgameRunning= true; //Audio setup int audio_rate = 22050; Uint16 audio_format = AUDIO_S16; int audio_channels = 2; int audio_buffers = 4096; //Initialize all SDL subsystems if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ) { return 1; } //Set up the screen screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE ); //If there was an error in setting up the screen if( screen == NULL ) { return 1; } //Set up sound if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers)) { printf("Unable to open audio!\n"); exit(1); } //game = Mix_LoadMUS("title.wav"); //Set the window caption SDL_WM_SetCaption("TRON: Kamikaze", NULL ); //Fill the screen white SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0, 0, 0 ) ); //Mix_PlayMusic(game, -1); GM.Init(); GM.ResetMusic("title.wav"); while (bgameRunning) { // check for any events from the user or the system SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0, 0, 0 ) ); GM.Manage(event, bgameRunning); //Update the screen if( SDL_Flip( screen ) == -1 ) { return 1; } //Sends the picture to the monitor } //Mix_HaltMusic(); //Mix_FreeMusic(game); //GM.~GameManage(); Mix_CloseAudio(); SDL_Quit(); return 0; }
f026e45a7a1e5bcb72aac50772f18ab1d9d4a640
67977c4e86a5f3d0648084c900993dac6f956ab5
/week4/Lab4/Lab4/building.hpp
50a87eb03f36ac3cff7b2ba68d84d3b285c21c38
[]
no_license
cmatian/CS-162
86a050dfd3492b4d17b346ee19ca38a93a722b92
88c108b910289b9ebaaf63bbee452a33296046c3
refs/heads/master
2020-04-08T17:35:27.544340
2018-11-28T22:48:10
2018-11-28T22:48:10
159,573,650
0
0
null
null
null
null
UTF-8
C++
false
false
638
hpp
building.hpp
/****************************************************************** ** Name: Christopher Matian ** OID: 933308644 ** ** Header specification and function prototypes for Building class ** and functions. ** ** BUILDING.HPP *****************************************************************/ #ifndef building_hpp #define building_hpp #include "validation.hpp" class Building { private: string name; int size; string address; public: // Constructor Building(string, int, string); // Destructor ~Building(); string bName(); int bSize(); string bAddress(); }; #endif
90dd3a4365c00ce7a3ca11d368488a4add06ef3e
b2cb5f27d41449cf6d082478e0ee016efe2c35cc
/test/test_main.cpp
bf9403b6d3575f59b01189e7fbc2494d712168ab
[]
no_license
AndrewHegman/ProgrammableFridge
02e8d9c8166a465dd7d0e62df4f83ab34ad46741
9cd17f16dbc391064018fe9f878335b8b28516a8
refs/heads/Arduino
2020-04-13T21:27:00.275791
2019-01-22T14:07:21
2019-01-22T14:07:21
163,456,586
0
0
null
2019-01-03T19:31:51
2018-12-28T23:06:07
C++
UTF-8
C++
false
false
298
cpp
test_main.cpp
#include <TemperatureWatcher.h> #include <unity.h> void test_pass(void){ TEST_ASSERT_EQUAL(1, 1); } void test_fail(void){ TEST_ASSERT_EQUAL(0, 1); } int main(int argc, char **argv){ UNITY_BEGIN(); RUN_TEST(test_pass); RUN_TEST(test_fail); UNITY_END(); return 0; }
6cf2b011dd413fb81d5f482ba43ad287d261ae0b
f1eb1dc6983029992e581079e56e58b76a0054f7
/limited/tests/unordered_map_insertion_test.cpp
3edaae55fdacbdf30060ca63178f84183a8494c4
[ "BSL-1.0" ]
permissive
sodmitriev/Extened-Associative-Containers
3f99ddcd57bc25a2428b5c3c168d300cb154e45c
7037c50e36cd2162a98a0dc63107dc5f1793797c
refs/heads/master
2020-09-27T13:38:06.228913
2019-12-11T19:56:33
2019-12-29T19:41:06
226,529,947
0
0
BSL-1.0
2019-12-11T19:57:19
2019-12-07T14:49:57
C++
UTF-8
C++
false
false
73,042
cpp
unordered_map_insertion_test.cpp
// Copyright 2019 Sviatoslav Dmitriev // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt #include "../unordered_map.h" #include <unordered_set> #define CATCH_CONFIG_MAIN #include <catch.hpp> #define GENERATE_ONE(a, b) GENERATE(take(1, random(a, b))) #define GENERATE_ANY(type) GENERATE(take(1, random(std::numeric_limits<type>::min(), std::numeric_limits<type>::max()))) using namespace extended_containers::limited; struct testHasher : public std::hash<int> {}; struct testEqual : public std::equal_to<int> {}; struct testWeight : public cache_manager::weight<int> {}; struct testPolicy : public cache_manager::policy::lru<std::pair<int, int>> {}; typedef std::allocator<cache_manager::stored_node<std::pair<int, int>>> testAlloc; TEMPLATE_TEST_CASE_SIG("limited unordered map insertion test", "[extended containers][limited containers][unordered map]", ((size_t capacity), capacity), 1024) { SECTION("Insert single") { unordered_map<int, int> map{capacity}; SECTION("Map has free space") { SECTION("Copy") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Move") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(decltype(val)(val)); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Convertible pair") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; std::pair<long, const long> val1{val.first, val.second}; auto res = map.insert(val1); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Copy with hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(map.begin(), val); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Move with hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(map.begin(), decltype(val)(val)); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Convertible pair with hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; std::pair<long, const long> val1{val.first, val.second}; auto res = map.insert(map.begin(), val1); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Key already exists") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); SECTION("Copy") { auto res = map.insert(val); REQUIRE(!res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Move") { auto res = map.insert(decltype(val)(val)); REQUIRE(!res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Convertible pair") { std::pair<long, const long> val1{val.first, val.second}; auto res = map.insert(val1); REQUIRE(!res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Copy with hint") { auto res = map.insert(map.begin(), val); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Move with hint") { auto res = map.insert(map.begin(), decltype(val)(val)); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("Convertible pair with hint") { std::pair<long, const long> val1{val.first, val.second}; auto res = map.insert(map.begin(), val1); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Map needs to free") { std::unordered_set<int> used; std::pair<int, int> initVal{GENERATE_ANY(int), GENERATE_ANY(int)}; map.insert(initVal); for (size_t i = 1; i < map.capacity(); ++i) { int val; do { val = GENERATE_ANY(int); } while (val == initVal.first || !used.insert(val).second); } for (auto i : used) { REQUIRE(map.insert({i, GENERATE_ANY(int)}).second); } REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(map.size() == map.capacity()); int key; do { key = GENERATE_ANY(int); } while (key == initVal.first || !used.insert(key).second); std::pair<int, int> val{key, GENERATE_ANY(int)}; SECTION("Copy") { auto res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("Move") { auto res = map.insert(decltype(val)(val)); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("Convertible pair") { std::pair<long, const long> val1{val.first, val.second}; auto res = map.insert(val1); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("Copy with hint") { auto res = map.insert(map.begin(), val); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("Move with hint") { auto res = map.insert(map.begin(), decltype(val)(val)); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("Convertible pair with hint") { std::pair<long, const long> val1{val.first, val.second}; auto res = map.insert(map.begin(), val1); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } } SECTION("Map can't fit") { unordered_map<int, int> map1{0}; SECTION("Copy") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert(val), no_space_error); REQUIRE(map1.empty()); } SECTION("Move") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert(decltype(val)(val)), no_space_error); REQUIRE(map1.empty()); } SECTION("Convertible pair") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; std::pair<long, const long> val1{val.first, val.second}; REQUIRE_THROWS_AS(map1.insert(val1), no_space_error); REQUIRE(map1.empty()); } SECTION("Copy with hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert(map1.begin(), val), no_space_error); REQUIRE(map1.empty()); } SECTION("Move with hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert(map1.begin(), decltype(val)(val)), no_space_error); REQUIRE(map1.empty()); } SECTION("Convertible pair with hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; std::pair<long, const long> val1{val.first, val.second}; REQUIRE_THROWS_AS(map1.insert(map1.begin(), val1), no_space_error); REQUIRE(map1.empty()); } } } SECTION("Emplace") { unordered_map<int, int> map{capacity}; SECTION("Map has free space") { SECTION("No hint") { std::pair<const int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.emplace(val.first, val.second); REQUIRE(res.second); REQUIRE(res.first->first == val.first); REQUIRE(res.first->second == val.second); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(map.begin()->first == val.first); REQUIRE(map.begin()->second == val.second); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(map.replacement_begin()->first == val.first); REQUIRE(map.replacement_begin()->second == val.second); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint") { std::pair<const int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.emplace_hint(map.begin(), val.first, val.second); REQUIRE(res->first == val.first); REQUIRE(res->second == val.second); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(map.begin()->first == val.first); REQUIRE(map.begin()->second == val.second); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(map.replacement_begin()->first == val.first); REQUIRE(map.replacement_begin()->second == val.second); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Key already exists") { std::pair<const int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(val); REQUIRE(res.second); REQUIRE(res.first->first == val.first); REQUIRE(res.first->second == val.second); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(map.begin()->first == val.first); REQUIRE(map.begin()->second == val.second); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(map.replacement_begin()->first == val.first); REQUIRE(map.replacement_begin()->second == val.second); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); SECTION("No hint") { auto res = map.emplace(val.first, val.second); REQUIRE(!res.second); REQUIRE(res.first->first == val.first); REQUIRE(res.first->second == val.second); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(map.begin()->first == val.first); REQUIRE(map.begin()->second == val.second); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(map.replacement_begin()->first == val.first); REQUIRE(map.replacement_begin()->second == val.second); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint") { auto res = map.emplace_hint(map.begin(), val.first, val.second); REQUIRE(res->first == val.first); REQUIRE(res->second == val.second); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(map.begin()->first == val.first); REQUIRE(map.begin()->second == val.second); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(map.replacement_begin()->first == val.first); REQUIRE(map.replacement_begin()->second == val.second); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Map needs to free") { std::unordered_set<int> used; std::pair<int, int> initVal{GENERATE_ANY(int), GENERATE_ANY(int)}; map.insert(initVal); for (size_t i = 1; i < map.capacity(); ++i) { int val; do { val = GENERATE_ANY(int); } while (val == initVal.first || !used.insert(val).second); } for (auto i : used) { REQUIRE(map.insert({i, GENERATE_ANY(int)}).second); } REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(map.size() == map.capacity()); int key; do { key = GENERATE_ANY(int); } while (key == initVal.first || !used.insert(key).second); std::pair<int, int> val{key, GENERATE_ANY(int)}; SECTION("No hint") { auto res = map.emplace(val.first, val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("With hint") { auto res = map.emplace_hint(map.begin(), val.first, val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } } SECTION("Map can't fit") { unordered_map<int, int> map1{0}; SECTION("No hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.emplace(val.first, val.second), no_space_error); REQUIRE(map1.empty()); } SECTION("With hint") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.emplace_hint(map1.begin(), val.first, val.second), no_space_error); REQUIRE(map1.empty()); } } } SECTION("Try emplace") { unordered_map<int, int> map{capacity}; SECTION("Map has free space") { SECTION("No hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.try_emplace(val.first, val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("No hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.try_emplace(int(val.first), val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.try_emplace(map.begin(), val.first, val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.try_emplace(map.begin(), int(val.first), val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Key already exists") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); SECTION("No hint copy key") { auto res = map.try_emplace(val.first, val.second); REQUIRE(!res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("No hint move key") { auto res = map.try_emplace(int(val.first), val.second); REQUIRE(!res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint copy key") { auto res = map.try_emplace(map.begin(), val.first, val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint move key") { auto res = map.try_emplace(map.begin(), int(val.first), val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Map needs to free") { std::unordered_set<int> used; std::pair<int, int> initVal{GENERATE_ANY(int), GENERATE_ANY(int)}; map.insert(initVal); for (size_t i = 1; i < map.capacity(); ++i) { int val; do { val = GENERATE_ANY(int); } while (val == initVal.first || !used.insert(val).second); } for (auto i : used) { REQUIRE(map.insert({i, GENERATE_ANY(int)}).second); } REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(map.size() == map.capacity()); int key; do { key = GENERATE_ANY(int); } while (key == initVal.first || !used.insert(key).second); std::pair<int, int> val{key, GENERATE_ANY(int)}; SECTION("No hint copy key") { auto res = map.try_emplace(val.first, val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("No hint move key") { auto res = map.try_emplace(int(val.first), val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("With hint copy key") { auto res = map.try_emplace(map.begin(), val.first, val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("With hint move key") { auto res = map.try_emplace(map.begin(), int(val.first), val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } } SECTION("Map can't fit") { unordered_map<int, int> map1{0}; SECTION("No hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.try_emplace(val.first, val.second), no_space_error); REQUIRE(map1.empty()); } SECTION("No hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.try_emplace(int(val.first), val.second), no_space_error); REQUIRE(map1.empty()); } SECTION("With hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.try_emplace(map1.begin(), val.first, val.second), no_space_error); REQUIRE(map1.empty()); } SECTION("With hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.try_emplace(map1.begin(), int(val.first), val.second), no_space_error); REQUIRE(map1.empty()); } } } SECTION("Insert node") { unordered_map<int, int> map{capacity}; SECTION("Map has free space") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); auto node = map.extract(res.first); REQUIRE(node.key() == val.first); REQUIRE(node.mapped() == val.second); REQUIRE(map.empty()); REQUIRE(map.weight() == 0); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 0); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 0); REQUIRE(map.size() == 0); REQUIRE(map.quiet_count(val.first) == 0); SECTION("No hint") { auto res = map.insert(std::move(node)); REQUIRE(res.inserted); REQUIRE(*res.position == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint") { auto res = map.insert(map.begin(), std::move(node)); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Key already exists") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); auto node = map.extract(res.first); REQUIRE(node.key() == val.first); REQUIRE(node.mapped() == val.second); REQUIRE(map.empty()); REQUIRE(map.weight() == 0); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 0); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 0); REQUIRE(map.size() == 0); REQUIRE(map.quiet_count(val.first) == 0); res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); SECTION("No hint") { auto res = map.insert(std::move(node)); REQUIRE(!res.inserted); REQUIRE(*res.position == val); REQUIRE(res.node.key() == val.first); REQUIRE(res.node.mapped() == val.second); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint") { auto res = map.insert(map.begin(), std::move(node)); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Map needs to free") { std::unordered_set<int> used; std::pair<int, int> initVal{GENERATE_ANY(int), GENERATE_ANY(int)}; map.insert(initVal); for (size_t i = 1; i < map.capacity(); ++i) { int val; do { val = GENERATE_ANY(int); } while (val == initVal.first || !used.insert(val).second); } for (auto i : used) { REQUIRE(map.insert({i, GENERATE_ANY(int)}).second); } REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(map.size() == map.capacity()); int key; do { key = GENERATE_ANY(int); } while (key == initVal.first || !used.insert(key).second); std::pair<int, int> val{key, GENERATE_ANY(int)}; unordered_map<int, int> map1{1}; auto res = map1.insert(val); REQUIRE(res.second); auto node = map1.extract(res.first); REQUIRE(node.key() == val.first); REQUIRE(node.mapped() == val.second); SECTION("No hint") { auto res = map.insert(std::move(node)); REQUIRE(res.inserted); REQUIRE(*res.position == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("With hint") { auto res = map.insert(map.begin(), std::move(node)); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } } SECTION("Map can't fit") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert(val); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); auto node = map.extract(res.first); REQUIRE(node.key() == val.first); REQUIRE(node.mapped() == val.second); REQUIRE(map.empty()); REQUIRE(map.weight() == 0); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 0); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 0); REQUIRE(map.size() == 0); REQUIRE(map.quiet_count(val.first) == 0); unordered_map<int, int> map1{0}; SECTION("No hint") { REQUIRE_THROWS_AS(map1.insert(std::move(node)), no_space_error); REQUIRE(map1.empty()); } SECTION("With hint") { REQUIRE_THROWS_AS(map1.insert(map1.begin(), std::move(node)), no_space_error); REQUIRE(map1.empty()); } } } SECTION("Insert or assign") { unordered_map<int, int> map{capacity}; SECTION("Map has free space") { SECTION("No hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert_or_assign(val.first, val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("No hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert_or_assign(int(val.first), val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert_or_assign(map.begin(), val.first, val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; auto res = map.insert_or_assign(map.begin(), int(val.first), val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Key already exists") { std::pair<int, int> initVal{GENERATE_ANY(int), GENERATE_ANY(int)}; std::pair<int, int> val{initVal.first, GENERATE_ANY(int)}; auto res = map.insert(initVal); REQUIRE(res.second); REQUIRE(*res.first == initVal); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == initVal); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == initVal); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(initVal.first) == 1); SECTION("No hint copy key") { auto res = map.insert_or_assign(val.first, val.second); REQUIRE(!res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("No hint move key") { auto res = map.insert_or_assign(int(val.first), val.second); REQUIRE(!res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint copy key") { auto res = map.insert_or_assign(map.begin(), val.first, val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } SECTION("With hint move key") { auto res = map.insert_or_assign(map.begin(), int(val.first), val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == 1); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == 1); REQUIRE(*map.begin() == val); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == 1); REQUIRE(*map.replacement_begin() == val); REQUIRE(map.size() == 1); REQUIRE(map.quiet_count(val.first) == 1); } } SECTION("Map needs to free") { std::unordered_set<int> used; std::pair<int, int> initVal{GENERATE_ANY(int), GENERATE_ANY(int)}; map.insert(initVal); for (size_t i = 1; i < map.capacity(); ++i) { int val; do { val = GENERATE_ANY(int); } while (val == initVal.first || !used.insert(val).second); } for (auto i : used) { REQUIRE(map.insert({i, GENERATE_ANY(int)}).second); } REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(map.size() == map.capacity()); int key; do { key = GENERATE_ANY(int); } while (key == initVal.first || !used.insert(key).second); std::pair<int, int> val{key, GENERATE_ANY(int)}; SECTION("No hint copy key") { auto res = map.insert_or_assign(val.first, val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("No hint move key") { auto res = map.insert_or_assign(int(val.first), val.second); REQUIRE(res.second); REQUIRE(*res.first == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("With hint copy key") { auto res = map.insert_or_assign(map.begin(), val.first, val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } SECTION("With hint move key") { auto res = map.insert_or_assign(map.begin(), int(val.first), val.second); REQUIRE(*res == val); REQUIRE(!map.empty()); REQUIRE(map.weight() == map.capacity()); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == map.capacity()); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == map.capacity()); REQUIRE(*--map.replacement_end() == val); REQUIRE(map.size() == map.capacity()); REQUIRE(map.quiet_count(val.first) == 1); REQUIRE(map.quiet_count(initVal.first) == 0); } } SECTION("Map can't fit") { unordered_map<int, int> map1{0}; SECTION("No hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert_or_assign(val.first, val.second), no_space_error); REQUIRE(map1.empty()); } SECTION("No hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert_or_assign(int(val.first), val.second), no_space_error); REQUIRE(map1.empty()); } SECTION("With hint copy key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert_or_assign(map1.begin(), val.first, val.second), no_space_error); REQUIRE(map1.empty()); } SECTION("With hint move key") { std::pair<int, int> val{GENERATE_ANY(int), GENERATE_ANY(int)}; REQUIRE_THROWS_AS(map1.insert_or_assign(map1.begin(), int(val.first), val.second), no_space_error); REQUIRE(map1.empty()); } } } SECTION("Insert range") { unordered_map<int, int> map{capacity}; size_t count = GENERATE_ANY(size_t)%(capacity - 1) + 2; std::unordered_map<int, int> cmpMap{count}; while(cmpMap.size() < count) { cmpMap.insert({GENERATE_ANY(int), GENERATE_ANY(int)}); } SECTION("Map has free space") { map.insert(cmpMap.cbegin(), cmpMap.cend()); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } } SECTION("Some keys already exist") { size_t usedCount = (GENERATE_ANY(size_t)%count) / 2 + 1; auto start = cmpMap.cbegin(); std::advance(start, (GENERATE_ANY(size_t)%count) / 3); auto end = start; std::advance(end, usedCount); map.insert(start, end); map.insert(cmpMap.cbegin(), cmpMap.cend()); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } } SECTION("Map needs to free") { size_t usedCount = GENERATE_ANY(size_t)%count + capacity - count + 1; std::unordered_set<int> usedVals(usedCount); while(usedVals.size() < usedCount) { auto val = GENERATE_ANY(int); if(cmpMap.count(val) == 0) usedVals.insert(val); } for(auto i : usedVals) { map.insert({i, GENERATE_ANY(int)}); } REQUIRE(!map.empty()); REQUIRE(map.weight() == usedCount); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == usedCount); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == usedCount); REQUIRE(map.size() == usedCount); map.insert(cmpMap.cbegin(), cmpMap.cend()); REQUIRE(!map.empty()); REQUIRE(map.weight() == capacity); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == capacity); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == capacity); REQUIRE(map.size() == capacity); for(auto & i : map) { auto it = cmpMap.find(i.first); auto it1 = usedVals.find(i.first); REQUIRE((it != cmpMap.cend() || it1 != usedVals.cend())); if(it != cmpMap.cend()) { REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } else { REQUIRE(*it1 == i.first); } } } SECTION("Map can't fit") { map.insert(cmpMap.cbegin(), cmpMap.cend()); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } auto fullCount = GENERATE_ANY(size_t)%capacity + capacity + 1; while(cmpMap.size() < fullCount + count) { cmpMap.insert({GENERATE_ANY(int), GENERATE_ANY(int)}); } REQUIRE_THROWS_AS(map.insert(cmpMap.cbegin(), cmpMap.cend()), no_space_error); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == capacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } } } SECTION("Insert initializer list") { size_t ilistCapacity = 3; unordered_map<int, int> map{ilistCapacity}; size_t count = 2; std::unordered_map<int, int> cmpMap{count}; while(cmpMap.size() < count) { cmpMap.insert({GENERATE_ANY(int), GENERATE_ANY(int)}); } SECTION("Map has free space") { map.insert({*cmpMap.begin(), *(++cmpMap.begin())}); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == ilistCapacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } } SECTION("Some keys already exist") { map.insert({*cmpMap.begin()}); map.insert({*cmpMap.begin(), *(++cmpMap.begin())}); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == ilistCapacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } } SECTION("Map needs to free") { size_t usedCount = GENERATE_ANY(size_t)%count + ilistCapacity - count + 1; std::unordered_set<int> usedVals(usedCount); while(usedVals.size() < usedCount) { auto val = GENERATE_ANY(int); if(cmpMap.count(val) == 0) usedVals.insert(val); } for(auto i : usedVals) { map.insert({i, GENERATE_ANY(int)}); } REQUIRE(!map.empty()); REQUIRE(map.weight() == usedCount); REQUIRE(map.capacity() == ilistCapacity); REQUIRE(std::distance(map.begin(), map.end()) == usedCount); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == usedCount); REQUIRE(map.size() == usedCount); map.insert({*cmpMap.begin(), *(++cmpMap.begin())}); REQUIRE(!map.empty()); REQUIRE(map.weight() == ilistCapacity); REQUIRE(map.capacity() == ilistCapacity); REQUIRE(std::distance(map.begin(), map.end()) == ilistCapacity); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == ilistCapacity); REQUIRE(map.size() == ilistCapacity); for(auto & i : map) { auto it = cmpMap.find(i.first); auto it1 = usedVals.find(i.first); REQUIRE((it != cmpMap.cend() || it1 != usedVals.cend())); if(it != cmpMap.cend()) { REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } else { REQUIRE(*it1 == i.first); } } } SECTION("Map can't fit") { map.insert({*cmpMap.begin(), *(++cmpMap.begin())}); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == ilistCapacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } auto fullCount = 4; while(cmpMap.size() < fullCount + count) { cmpMap.insert({GENERATE_ANY(int), GENERATE_ANY(int)}); } REQUIRE_THROWS_AS(map.insert( {*cmpMap.begin(), *(++cmpMap.begin()), *(++++cmpMap.begin()), *(++++++cmpMap.begin()), *(++++++++cmpMap.begin()), *(++++++++++cmpMap.begin())} ), no_space_error); REQUIRE(!map.empty()); REQUIRE(map.weight() == count); REQUIRE(map.capacity() == ilistCapacity); REQUIRE(std::distance(map.begin(), map.end()) == count); REQUIRE(std::distance(map.replacement_begin(), map.replacement_end()) == count); REQUIRE(map.size() == count); for(auto & i : map) { auto it = cmpMap.find(i.first); REQUIRE(it != cmpMap.cend()); REQUIRE(it->first == i.first); REQUIRE(it->second == i.second); } } } }
ea66cff77da2da63a24400c5c9c43b2ecd345c7f
aa1c32385121b87af4f1e22a833ef36840565029
/336.cpp
801d12e005c6e3c144e09f9b8c77138e7ea4b5df
[]
no_license
AsifWatson/UVa-Online-Judge
d4ba1d99a10991347b81a21b33e14a18fc36805f
831e8306b61eb550d525333d76e9458fe3c1bd38
refs/heads/master
2020-04-11T09:47:57.705730
2020-02-27T09:46:30
2020-02-27T09:46:30
161,692,126
0
0
null
null
null
null
UTF-8
C++
false
false
3,087
cpp
336.cpp
#include<bits/stdc++.h> #define MAX 350 using namespace std; map<int,int> m; vector<int> adj[MAX]; int visited[MAX]={0}; int level[MAX]; void addEdge(int v,int e) { adj[v].push_back(e); adj[e].push_back(v); } void bfs(int s) { for(int i=0;i<MAX;i++) { visited[i]=0; } visited[s]=1; queue<int> q; q.push(s); level[s]=0; while(!q.empty()) { int u=q.front(); for(int i=0;i<adj[u].size();i++) { if(visited[adj[u][i]]==0) { int v=adj[u][i]; visited[v]=1; level[v]=level[u]+1; q.push(v); } } q.pop(); } } int check(int s,int ttl) { int cou=0; for(int i=0;i<MAX;i++) visited[i]=0; visited[s]=1; queue<int> q; q.push(s); while(!q.empty()) { int u=q.front(); for(int i=0;i<adj[u].size();i++) { if(visited[adj[u][i]]==0) { int v=adj[u][i]; if(level[v]<=ttl) { cou++; } visited[v]=1; q.push(v); } } q.pop(); } return cou; } int main() { int n,z,a,b,tot; static int r=1; while(scanf("%d",&n) && n) { int mapp[MAX]; z=0; for(int i=0;i<n;i++) { int x,y; scanf("%d %d",&x,&y); if(m.empty()) { mapp[z]=x; z++; m[x]=z; if(m.end() == m.find(y)) { mapp[z]=y; z++; m[y]=z; } } if(m.end() == m.find(x)) { //pai nai; mapp[z]=x; z++; m[x]=z; } if(m.end() == m.find(y)) { mapp[z]=y; z++; m[y]=z; } addEdge(m[x],m[y]); } while(scanf("%d %d",&a,&b)) { int flag=0; if(a==0 && b==0) break; for(int i=0;i<MAX;i++) { if(mapp[i]==a) { flag=1; } } if(flag==0) { printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",r,z,a,b); r++; continue; } bfs(m[a]); tot=check(m[a],b); printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",r,z-(tot+1),a,b); r++; } for(int i=0;i<MAX;i++) { adj[i].clear(); } while(!m.empty()) { m.clear(); } } return 0; }
3c8ab20419546572ea0036f5cdb73f69e1f41ce5
7f25ac596812ed201f289248de52d8d616d81b93
/eggeek/codeforces/698B.cpp
a837ca950d6b25c5a52b16ef969097c124abc762
[]
no_license
AplusB/ACEveryDay
dc6ff890f9926d328b95ff536abf6510cef57eb7
e958245213dcdba8c7134259a831bde8b3d511bb
refs/heads/master
2021-01-23T22:15:34.946922
2018-04-07T01:45:20
2018-04-07T01:45:20
58,846,919
25
49
null
2016-07-14T10:38:25
2016-05-15T06:08:55
C++
UTF-8
C++
false
false
1,474
cpp
698B.cpp
#include <bits/stdc++.h> using namespace std; #define ALL(a) (a).begin(), (a).end() #define SZ(a) int((a).size()) #define LOWB(x) (x & (-x)) #define UNIQUE(a) sort(ALL(a)), (a).erase(unique(ALL(a)), (a).end()) #define INF 1e9 #define INF_LL 4e18 #define rep(i,a,b) for(__typeof(b) i=a; i<(b); ++i) typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; /*-----------------------------------*/ #define N 200010 int n, p[N], f[N], root; int find_fa(int x) { if (f[x] == x) return x; else { f[x] = find_fa(f[x]); return f[x]; } } bool verify() { for (int i=1; i<=n; i++) f[i] = i; for (int i=1; i<=n; i++) if (i != root) { int fu = find_fa(i); int fv = find_fa(p[i]); if (fu == fv) return false; else f[fu] = fv; } return true; } int main() { scanf("%d", &n); for (int i=1; i<=n; i++) f[i] = i; for (int i=1; i<=n; i++) { scanf("%d", &p[i]); } root = -1; for (int i=1; i<=n; i++) { if (p[i] == i) { root = i; break; } } int cnt = 0; for (int i=1; i<=n; i++) if (i != root) { int fu = find_fa(i); int fv = find_fa(p[i]); if (fu == fv) { if (root == -1) { p[i] = i; root = i; } else p[i] = root; cnt++; } else f[fu] = fv; } printf("%d\n", cnt); for (int i=1; i<=n; i++) printf("%d%c", p[i], i==n?'\n': ' '); assert(verify()); return 0; }
e983342fa0b25f4b7f26c8c68bb8270090d1e9b4
779a71666ae45220828ca681edb8d10930a0133e
/21-5-27/21-5-27/demo.cpp
2b553d1e862ed638fab2ceff3cdc929ea3c060a9
[]
no_license
zhanghaoyu020418/winter-practice
4374a651066bb80f5ca6d7a15093a89f730831f5
9b47fbb2dc640e38460c88f9e0a103745ab47326
refs/heads/master
2023-06-17T19:42:13.020845
2021-07-13T00:32:25
2021-07-13T00:32:25
331,566,065
1
0
null
null
null
null
GB18030
C++
false
false
623
cpp
demo.cpp
#define _CRT_SECURE_NO_WARNINGS 1 #include <iostream> using namespace std; int main() { int i = 0; //if (i > 0) // cout << 1 << endl, i--; //using zhy = int; //for (zhy i = 0; i < 9; i++) // cout << i << endl; //decltype((i)) a = i; //a += 10; //cout << i << endl; // 可以权限缩小 // 但是不能权限放大 int a = 10; const int b = 20; a = b; b = a; // const int ! int 权限缩小 int a = 1; int b = 1; int* t1 = &a; const int* t2 = &b; t1 = t2; // int* ! const int* 权限放大 t2 = t1; return 0; } //Date tmp(*this); //tmp -= day; //return tmp;
c143666d3b7d5a0e4c1f940c8b0c327b93233405
880ba6f0ad1090d5c1d837d0e76d1d767ebe20d8
/source/database/db246.cpp
f4efaab464a4c1934df49eb40cbc605ac91cc737
[]
no_license
jetma/adso
7657e02978c0afdc35c66a67771841ddbed69f17
56fd41696a542cc9a80da60a6ffe06ebfb2e67f3
refs/heads/master
2020-06-18T12:32:10.407939
2019-03-03T08:49:52
2019-03-03T08:49:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
86
cpp
db246.cpp
#include "db246.h" Db246::Db246() { #include "db246.dat" }; Db246::~Db246() {};
d6eca859a7b7f2e40604037f8eebd7b962c71a49
ef2256000bf1544db1d097fd8a3ca3be8cbf93e2
/main.cpp
14a205e01704b234ecd7df2bfcf7e3ef310af28f
[ "MIT" ]
permissive
paperrune/WinAPI-Wav
82ff38ba8143abf5bffa9ef9cd263fb6901aad68
aefea112e969c83a082378e9472049be4a0bc215
refs/heads/master
2021-09-04T00:27:22.362944
2018-01-13T08:40:45
2018-01-13T08:40:45
109,534,673
0
0
null
null
null
null
UTF-8
C++
false
false
2,012
cpp
main.cpp
#include <thread> #include "Wav.h" int main(){ Wav wav("BalloonPop01.wav"); // wav.Load("BalloonPop01.wav"); printf("Play\n"); wav.WavToBuffer(); wav.Play(); // create wav from data { unsigned char *data; int length_data; int nChannels; int nSamplesPerSec; int wBitsPerSample; Wav wav("BalloonPop01.wav"); wav.Get_Properties(&nChannels, &nSamplesPerSec, &wBitsPerSample); printf("\nnChannels: %d\nnSamplesPerSec: %d\nwBitsPerSample: %d\n", nChannels, nSamplesPerSec, wBitsPerSample); data = new unsigned char[length_data = wav.length_wav]; for (int i = 0; i < wav.length_wav; i++){ data[i] = wav.data[i]; } Wav new_wav(nChannels, nSamplesPerSec, wBitsPerSample); // new_wav.Set_Properties(nChannels, nSamplesPerSec, wBitsPerSample); new_wav.Create(data, length_data); new_wav.Save("BalloonPop02.wav"); delete[] data; } // create wav from buffer { double *buffer; int length_buffer; int nChannels; int nSamplesPerSec; int wBitsPerSample; Wav wav("BalloonPop02.wav"); wav.Get_Properties(&nChannels, &nSamplesPerSec, &wBitsPerSample); printf("\nnChannels: %d\nnSamplesPerSec: %d\nwBitsPerSample: %d\n", nChannels, nSamplesPerSec, wBitsPerSample); wav.WavToBuffer(); buffer = new double[length_buffer = wav.length_buffer]; for (int i = 0; i < wav.length_buffer; i++){ buffer[i] = wav.Get_Buffer(i); } Wav new_wav(nChannels, nSamplesPerSec, wBitsPerSample); // new_wav.Set_Properties(nChannels, nSamplesPerSec, wBitsPerSample); new_wav.Create(length_buffer, buffer); new_wav.BufferToWav(); new_wav.Save("BalloonPop03.wav"); delete[] buffer; } printf("\nRecord\n"); wav.Record(2000); printf("Play\n"); wav.Play(); wav.BufferToWav(); wav.Save("record.wav"); printf("\nRecord\n"); std::thread thread = wav.Record_Thread(2000); thread.detach(); printf("Interrupt\n"); wav.recording = false; return 0; }
b4a1f6e7275f8fe3148d1cf3d745a5fa5677261e
ec9106a5a1c91077f2aef585fb5baa4d29fdc480
/Withdrawal.cpp
c9542d0286f5cdb86563f817b727cc38dc05663e
[]
no_license
mosobhy/ATM-Software-System
9b246a3add3d7d99554cdfa988421f7efcedb0b7
d65baf870c70c9593ef59b2d6431fe7642c07549
refs/heads/main
2023-07-11T17:09:32.063628
2021-08-06T14:32:25
2021-08-06T14:32:25
362,509,407
0
0
null
null
null
null
UTF-8
C++
false
false
3,703
cpp
Withdrawal.cpp
// Withdrawal.cpp #include "Withdrawal.h" #include <iostream> using namespace std; static const int CANCELLED = 7; // constructor Withdrawal::Withdrawal(int accountNubmer, Screen screen, BankDatabase bank , CashDispenser cashDispenser, KeyPad keypad) // invoke the parent constructor to initilaize its members :Transaction(accountNubmer, screen, bank), cashDispenser(cashDispenser), keypad(keypad) { } int Withdrawal::displayManueOfOptions() const { Screen screen = getScreen(); KeyPad keypad; int amounts[] = {0, 20, 40, 60, 80, 100, 200}; int choice = 0; while (choice == 0) { screen.displayMessageLine("Please, Select the amount: "); screen.displayMessage("1 - "); screen.displayMessage("20$"); screen.displayMessage("\t"); screen.displayMessage("2 - "); screen.displayMessage("40$"); cout << endl; screen.displayMessage("3 - "); screen.displayMessage("60$"); screen.displayMessage("\t"); screen.displayMessage("4 - "); screen.displayMessage("80$"); cout << endl; screen.displayMessage("5 - "); screen.displayMessage("100$"); screen.displayMessage("\t"); screen.displayMessage("6 - "); screen.displayMessage("200$"); cout << endl; screen.displayMessage("7 - CANCEL"); cout << endl; screen.displayMessage("Your choice: "); choice = keypad.getInput(); switch(choice) { case 1: case 2: case 3: case 4: case 5: case 6: choice = amounts[choice]; break; case CANCELLED: choice = CANCELLED; break; // otherwise default: screen.displayMessageLine("You Entered an Invalid Input...."); } } return choice; } // override the execute() method void Withdrawal::execute() { // prompt the user with a list of options Screen &screen = getScreen(); bool transactionDone = false; bool cancelled = false; do { int userChoice = displayManueOfOptions(); if (userChoice != CANCELLED) { // interact with database int requestedAmount = userChoice; BankDatabase &bank = getBankDatabase(); // this in the trasaction abstract class int currentAccountNumber = getAccountNumber(); // check if the user's availableBalance suffice double availBalance = bank.getAvailableBalance(currentAccountNumber); if (availBalance >= requestedAmount) { // check if there is avalible cash in the ATM dispenser if (cashDispenser.isSufficientCredit(requestedAmount)) { // withdraw the cash bank.withdraw(currentAccountNumber, requestedAmount); // dispense cash from the ATM cashDispenser.dispenseCash(requestedAmount); // prompt the user to take it screen.displayMessageLine("Please take off your cash!"); transactionDone = true; } else { screen.displayMessageLine("Sorry, We cannot serve your withdraw now!"); } } else { screen.displayMessageLine("Your credit is not sufficient!"); } } else { screen.displayMessageLine("Transaction Declined!"); cancelled = true; } } while (!transactionDone && !cancelled); }
9db019278f0af3521a36e5abd1685e04eeb5c35e
b487cbd289394844c65dc448d2ba075771f5d7eb
/51nod/1082.cpp
c4e3fa146956af9571b5ae6d75f3835acc23e95d
[]
no_license
zyw3000/ACM-CODE
ce7155188a3c98a8942ac98ee5d4000bd0644be1
a34a7463fac7919af9dc7de9fad0d96c7f0920ea
refs/heads/master
2021-01-01T03:32:41.763583
2016-10-31T02:52:52
2016-10-31T02:52:52
59,165,133
0
0
null
null
null
null
UTF-8
C++
false
false
765
cpp
1082.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <iostream> #include <algorithm> #include <vector> #include <string> #include <queue> #include <map> #include <set> #include <stack> #define rep(i,n) for(int i = 1; i <= n; i++) using namespace std; #define LL long long LL res[1000005]; void init() { LL test; int flag,t; res[0] = 0; rep(i,1000002){ flag = 0; t = i; if(t % 7 == 0){ res[i] = res[i-1]; continue; } while(t){ if(t % 10 == 7){ flag = 1; break; } t /= 10; } if(flag){ res[i] = res[i-1]; continue; } test = pow(i,2); res[i] = res[i-1]+test; } } int main() { int idx,n; init(); cin>>idx; while(idx--){ scanf("%d",&n); cout<<res[n]<<endl; } return 0; }
e445c2e4ea60d78a97064d11a88efd43d10f8b39
56c632b232b00d122eb922ef88a3714704ee8980
/Miscellaneous/C++/GraphAlgorithms/Floyd.cpp
7c92ab1f3a0ed70d0ead94eea5199ebe4c9bbe84
[]
no_license
thsmcoding/P_Projects
8b48dc0923c1fba8c7c782b415ff8a64c35e4acf
5e02dd6ad156c221adf3d3a3dac0fd97c47d3ba2
refs/heads/local-experiments
2023-05-12T00:43:45.617007
2021-03-04T22:42:18
2021-03-04T22:42:18
194,916,376
0
0
null
2021-06-04T02:28:18
2019-07-02T18:35:52
JavaScript
UTF-8
C++
false
false
2,586
cpp
Floyd.cpp
#include "pch.h" #include "Floyd.h" bool existsNegativeCycle(vector<vector<double>>distances) { int vertices = distances.size(); int count = 0; for (int i = 1; i < vertices; i++) { vector<double> current_node_distances = distances[i]; if (current_node_distances[i] < 0) count++; } cout << "NUMBER OF NEGATIVE CYCLES FOUND :" << count << endl; return (count != 0); } void printFloydPaths(int vertices, int source, vector<vector<int>>allPaths, vector<vector<double>> distance) { double real_cost = 0.0; for (int u = 1; u < vertices + 1; u++) { double cost = 0.0; stack<int> onePath; if (u == source) { cout << "PATH BETWEEN " << source << " AND " << u << " IS :"; cout << u << " -> " << u << " : "; real_cost = (cost == 0.0) ? -1.0 : cost; cout << fixed << " :" << real_cost; cout << "\n"; } else { int destination = u; onePath.push(destination); int current = allPaths[source][destination]; while (current != -1) { onePath.push(current); cost += distance[current][destination]; destination = current; current = allPaths[source][destination]; } cout << "PATH BETWEEN " << source << " AND " << u << " IS :"; while (!onePath.empty()) { int current = onePath.top(); onePath.pop(); cout << current; real_cost = (cost == 0.0) ? -1.0 : cost; if (!onePath.empty()) cout << " -> "; else cout << fixed << " :" << real_cost; } cout << "\n"; } } } void floydWarshall(Graph graph, int startPoint) { int vertices = graph.getV(); double INF = numeric_limits<double>::max(); vector<double>init_distances(vertices + 1, INF); vector<int>init_paths(vertices + 1, -1); vector<vector<double>>distances(vertices + 1, init_distances); vector<vector<int>>paths(vertices + 1, init_paths); vector<vector<int>> *edges = graph.getEdges(); /* Initialization: */ for (int i = 0; i < edges->size(); i++) { vector<int> ed = (*edges)[i]; int u = ed[0]; int v = ed[1]; double w = (double)ed[2]; distances[u][v] = w; distances[u][u] = 0.0; distances[v][v] = 0.0; paths[u][v] = u; } /* FLOYD-WARSHALL algorithm : */ for (int a = 1; a < vertices + 1; a++) { for (int b = 1; b < vertices + 1; b++) { for (int c = 1; c < vertices + 1; c++) { if (distances[b][c] > distances[b][a] + distances[a][c]) { distances[b][c] = distances[b][a] + distances[a][c]; paths[b][c] = paths[a][c]; } } } } if (existsNegativeCycle(distances)) cout << "NEGATIVE CYCLES FOUND \n"; printFloydPaths(vertices, startPoint, paths, distances); }
439417e2548021b86660c97e7d036f1f51d0e6eb
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/ThirdParty/WebRTC/rev.9862/include/Win64/VS2013/include/talk/media/webrtc/simulcast.h
d96ccd07dd0782d0cc21063c50755356317319d0
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
4,641
h
simulcast.h
/* * libjingle * Copyright 2014 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TALK_MEDIA_WEBRTC_SIMULCAST_H_ #define TALK_MEDIA_WEBRTC_SIMULCAST_H_ #include <vector> #include "webrtc/base/basictypes.h" #include "webrtc/config.h" namespace webrtc { struct VideoCodec; } namespace cricket { struct VideoOptions; struct StreamParams; enum SimulcastBitrateMode { SBM_NORMAL = 0, SBM_HIGH, SBM_VERY_HIGH, SBM_COUNT }; // Config for use with screen cast when temporal layers are enabled. struct ScreenshareLayerConfig { public: ScreenshareLayerConfig(int tl0_bitrate, int tl1_bitrate); // Bitrates, for temporal layers 0 and 1. int tl0_bitrate_kbps; int tl1_bitrate_kbps; static ScreenshareLayerConfig GetDefault(); // Parse bitrate from group name on format "(tl0_bitrate)-(tl1_bitrate)", // eg. "100-1000" for the default rates. static bool FromFieldTrialGroup(const std::string& group, ScreenshareLayerConfig* config); }; // TODO(pthatcher): Write unit tests just for these functions, // independent of WebrtcVideoEngine. // Get the simulcast bitrate mode to use based on // options.video_highest_bitrate. SimulcastBitrateMode GetSimulcastBitrateMode( const VideoOptions& options); // Get the ssrcs of the SIM group from the stream params. void GetSimulcastSsrcs(const StreamParams& sp, std::vector<uint32>* ssrcs); // Get simulcast settings. std::vector<webrtc::VideoStream> GetSimulcastConfig( size_t max_streams, SimulcastBitrateMode bitrate_mode, int width, int height, int max_bitrate_bps, int max_qp, int max_framerate); // Set the codec->simulcastStreams, codec->width, and codec->height // based on the number of ssrcs to use and the bitrate mode to use. bool ConfigureSimulcastCodec(int number_ssrcs, SimulcastBitrateMode bitrate_mode, webrtc::VideoCodec* codec); // Set the codec->simulcastStreams, codec->width, and codec->height // based on the video options (to get the simulcast bitrate mode) and // the stream params (to get the number of ssrcs). This is really a // convenience function. bool ConfigureSimulcastCodec(const StreamParams& sp, const VideoOptions& options, webrtc::VideoCodec* codec); // Set the numberOfTemporalLayers in each codec->simulcastStreams[i]. // Apparently it is useful to do this at a different time than // ConfigureSimulcastCodec. // TODO(pthatcher): Figure out why and put this code into // ConfigureSimulcastCodec. void ConfigureSimulcastTemporalLayers( int num_temporal_layers, webrtc::VideoCodec* codec); // Turn off all simulcasting for the given codec. void DisableSimulcastCodec(webrtc::VideoCodec* codec); // Log useful info about each of the simulcast substreams of the // codec. void LogSimulcastSubstreams(const webrtc::VideoCodec& codec); // Configure the codec's bitrate and temporal layers so that it's good // for a screencast in conference mode. Technically, this shouldn't // go in simulcast.cc. But it's closely related. void ConfigureConferenceModeScreencastCodec(webrtc::VideoCodec* codec); } // namespace cricket #endif // TALK_MEDIA_WEBRTC_SIMULCAST_H_
e24d3083fdea6ef9295e6e8675b50bce38d712d3
b1a49bd5dcac6e6b28a6850c6f07daa04715ee05
/grammer_anaylse/grammer_anaylse.cpp
40797dab249682de8cdde0a5a4699be9859068ac
[]
no_license
XiaoyuanXie/dragon
a0086f727a6319bd1b2503f4d31f2437f5d73380
892d6bfe193577ffb765cc79b9b40551997410ef
refs/heads/master
2021-05-29T11:25:04.306859
2015-05-28T13:42:24
2015-05-28T13:42:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,014
cpp
grammer_anaylse.cpp
/// \file grammer_anaylse.cpp /* ------------------------------------ Create date : 2015-05-26 12:39 Modified date: 2015-05-28 09:40 Author : Sen1993 Email : gsen1993@gmail.com ------------------------------------ */ #include <iostream> #include <unordered_map> #include <string> #include <vector> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sstream> using namespace std; #define UMM(x,y) unordered_multimap<x,y>::value_type enum PRI{LT=-1,EQ,GT}; unordered_multimap<string, string> grammer; unordered_multimap<char, char> firstvt; unordered_multimap<char, char> lastvt; unordered_map<string, PRI> table; bool isTerminator(char c){ if(c >= 'A' && c <= 'Z') return false; return true; } bool multi_find(unordered_multimap<char,char> vt, char key, char value){ auto it = vt.find(key); if(it == vt.end()) return false; while(it != vt.end()){ if(it->second == value) return true; ++it; } return false; } void get_firstvt(){ vector<pair<char,char>> s; string nt, te; for(auto it : grammer){ nt = it.first; te = it.second; for(auto c : te){ if(isTerminator(c)){ s.push_back(make_pair(nt[0], c)); firstvt.insert(UMM(char,char)(nt[0], c)); break; } } } while(!s.empty()){ pair<char,char> top = s.back(); s.pop_back(); for(auto it : grammer){ nt = it.first; te = it.second; if(te[0] == top.first && !multi_find(firstvt, nt[0], top.second)){ s.push_back(make_pair(nt[0], top.second)); firstvt.insert(UMM(char,char)(nt[0], top.second)); } } } char bef = '\0'; cout << "---firstvt---"; for(auto it : firstvt){ if(it.first != bef) cout << endl << it.first << ": "; cout << it.second << " "; bef = it.first; } cout << endl; } void get_lastvt(){ vector<pair<char,char>> s; string nt, te; for(auto it : grammer){ nt = it.first; te = it.second; for(int i = te.length()-1; i >= 0; --i){ if(isTerminator(te[i])){ s.push_back(make_pair(nt[0], te[i])); lastvt.insert(UMM(char,char)(nt[0], te[i])); break; } } } while(!s.empty()){ pair<char,char> top = s.back(); s.pop_back(); for(auto it : grammer){ nt = it.first; te = it.second; if(te[ te.length()-1 ] == top.first && !multi_find(lastvt, nt[0], top.second)){ s.push_back(make_pair(nt[0], top.second)); lastvt.insert(UMM(char,char)(nt[0], top.second)); } } } char bef = '\0'; cout << "---lastvt---"; for(auto it : lastvt){ if(it.first != bef) cout << endl << it.first << ": "; cout << it.second << " "; bef = it.first; } cout << endl; } void str_replace(string &str, string s, string t){ size_t pos = 0; size_t s_len = s.length(); size_t t_len = t.length(); while( (pos=str.find(s,pos)) != string::npos){ str.replace(pos, s_len, t); pos += t_len; } } void process_grammer(){ string nt, te; unordered_multimap<string, string> grammer_tmp; for(auto it : grammer){ nt = it.first; te = it.second; size_t pos = te.find('|'); if(pos == string::npos) grammer_tmp.insert(UMM(string,string)(nt, te)); else{ str_replace(te, "|", " "); stringstream ss(te); string tmp; while(ss >> tmp) grammer_tmp.insert(UMM(string,string)(nt, tmp)); } } grammer = grammer_tmp; for(auto it : grammer) cout << it.first << " " << it.second << endl; } void make_table(){ string nt, te; for(auto it : grammer){ nt = it.first; te = it.second; for(int i = 0; i < te.length()-1; ++i){ if(isTerminator(te[i])){ if(isTerminator(te[i+1])) table[te.substr(i,2)] = EQ; else if(i+2 < te.length() && isTerminator(te[i+2])) table[te.substr(i,1)+te.substr(i+2,1)] = EQ; else{ auto it2 = firstvt.find(te[i+1]); while(it2 != firstvt.end() && it2->first == te[i+1]){ table[te.substr(i,1).append(1,it2->second)] = LT; ++it2; } } }else{ if(isTerminator(te[i+1])){ auto it2 = lastvt.find(te[i]); while(it2 != lastvt.end() && it2->first == te[i]){ string tmp(""); tmp.append(1,it2->second); table[tmp+te.substr(i+1,1)] = GT; ++it2; } } } } } cout << "---table---" << endl; for(auto it : table) cout << it.first[0] << "," << it.first[1] << " " << it.second << endl; } PRI get_pri(char a, char b){ if(a == '#' && b == '#') return EQ; if(a == '#') return LT; if(b == '#') return GT; string tmp(""); tmp.append(1,a); tmp.append(1,b); if(table.find(tmp) != table.end()) return table[tmp]; tmp.clear(); tmp.append(1,b); tmp.append(1,a); if(table.find(tmp) == table.end()){ cout << "error!" << "-" << a << b << endl; exit(0); } switch(table[tmp]){ case GT: return LT; case EQ: return EQ; case LT: return GT; } } char guiyue(string str){ for(auto it : grammer) if(it.second == str) return it.first[0]; } void do_analyse(){ char S[100]; memset(S, 0, 100); int k = 0; S[k] = '#'; cin.clear(); int fd = open("txt", O_RDONLY); dup2(fd, STDIN_FILENO); char a; cout << "---analyse---" << endl; do{ cin >> a; int j = k; if( !isTerminator(S[k]) ) --j; while(get_pri(S[j],a) == GT){ char q; do{ q = S[j]; --j; if( !isTerminator(S[j]) ) --j; }while(get_pri(S[j],q) != LT); string tmp(""); for(int i = j+1; i <= k; ++i) tmp.append(1,S[i]); k = j+1; S[k] = guiyue(tmp); cout << "stack: " << S << endl; cout << "guiyue: " << tmp << " - " << guiyue(tmp) << endl; } if(get_pri(S[j],a) != GT){ ++k; S[k] = a; cout << "stack: " << S << endl; }else{ cout << "error" << endl; } }while(a != '#'); close(fd); } void analyse(){ process_grammer(); get_firstvt(); get_lastvt(); make_table(); do_analyse(); } int main(){ string line; int fd = open("grammer", O_RDONLY); dup2(fd,STDIN_FILENO); while(cin >> line){ int pos = line.find("->"); if(pos == string::npos){ cout << "grammer error!" << endl; return 0; } grammer.insert(UMM(string,string)(line.substr(0,pos),line.substr(pos+2))); } close(fd); analyse(); return 0; }
17955e194699ecd5df2427772f4ad718d9fde8cc
86908a017b44cd07963eedd4325c99d410f02395
/GUICraft/headers/amyCanvas.h
a4defd34b667cc94b5159bfee0d1db66ef099c7f
[]
no_license
laoniu2020/MedicalTile
a8ebf9604f2f76cef7740d07e6d20419127950dd
6d0f172ae863c9d1a3176d2933ff0a5440888f50
refs/heads/master
2021-05-29T06:03:36.556875
2015-10-04T15:10:05
2015-10-04T15:10:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
907
h
amyCanvas.h
#pragma once #include"GuiMacro.h" #include<vector> #include<qwidget.h> using namespace std; class amyLing; class GUI_INTERFACE amyCanvas:public QWidget { public: amyCanvas(QWidget *parent = 0); ~amyCanvas(); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent * event); virtual void mouseLeaveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *); virtual void mouseDoubleClickEvent(QMouseEvent * event); virtual void wheelEvent ( QWheelEvent * event ); virtual void resizeEvent ( QResizeEvent * event ); virtual void dropEvent(QDropEvent *event); virtual void dragEnterEvent(QDragEnterEvent *event); virtual void keyPressEvent ( QKeyEvent * event ); void AddLing(amyLing* am); void paintEvent(QPaintEvent *); void RemoveLing(amyLing* am); void ReplaceLing(amyLing* replaced,amyLing* newling); private: vector<amyLing*> m_LingArr; };
571ea3f31ae277626135244e5e090959d813cf9d
c89d83d50ffbfe2c7dead921dce4351162b1b876
/may_2020/translation.cpp
61bd885b24524fd2c9cc6fe316d2546c8db5ff5f
[]
no_license
shadabeqbal/codeforces
f261e6793760b76ad0cbea17343a248cddb88dac
1d12dbd980ccdb9bdc721e24311c3787c81e9f7c
refs/heads/master
2022-11-06T06:59:47.644997
2020-07-01T16:44:53
2020-07-01T16:44:53
267,477,766
0
0
null
2020-05-29T20:07:42
2020-05-28T02:49:41
C++
UTF-8
C++
false
false
864
cpp
translation.cpp
/* // // // // \\// \>> //\\ // \\ Author: Shadab Eqbal Created on: "30-05-2020" Name: A. Translation Link: https://codeforces.com/problemset/problem/41/A */ #include <iostream> #include <vector> #include <algorithm> #include <map> #include <stack> #include <queue> #include <iterator> #include <climits> #include <string> #include <math.h> #define MAX 1e18 #define MIN -1e18 #define MOD 1000000007 #define PB push_back #define MP make_pair #define vi vector<int> #define vii vector<vector<int>> #define pi pair<int, int> #define vpi vector<pi> #define ll long long int #define vll vector<ll> using namespace std; int main() { string str1, str2; cin >> str1 >> str2; reverse(str1.begin(), str1.end()); if (str1 == str2) cout << "YES\n"; else cout << "NO\n"; return 0; }
e79f2181fff81f929860cf1f212242a46e0cfe36
956bda043789c5587142afcde8ab70b32cf494aa
/Polje_brzina/velocity_functions.h
837c2727ef7a4dbaa21070ac6a47c35c2d4ae27b
[]
no_license
Kuljat991/Velocity-field
44693f261c7e6d9897e1e0cd6346762d7b71df71
a3d087a54dd21816f03192373e7515d443bc1573
refs/heads/master
2020-03-22T03:29:35.987737
2018-07-02T12:58:49
2018-07-02T12:58:49
139,435,418
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
h
velocity_functions.h
#ifndef VELOCITY_FUNCTIONS_H #define VELOCITY_FUNCTIONS_H #include <vector> typedef std::vector< double > state_type; /** * Testna f-ja 1 * dx/dt = 1 * dy/dt = cos(t) * Ocekujemo: * x = t + x0 * y = sin(t) + y0 */ void sinusoida ( const state_type &/*state*/, state_type &dxdt , const double t ); /** * Testna f-ja 1 * Stacionarno vektorsko polje brzina - ne mijenja se u vremenu * \nabla \times \mathbf{v} = 0 * gdje je \mathbf{v} = \left( -\frac{y}{x^2+y^2}, \frac{x}{x^2+y^2} \right) * * Za render copy/paste ovdje: http://arachnoid.com/latex/ * * Rješenje: svugdje vektori jednake duljine (1) i kružno gibanje oko (0,0) */ void const_kruzno_gibanje ( const state_type &state, state_type &dxdt , const double t ); /** * Testna f-ja 1 * Stacionarno vektorsko polje brzina - ne mijenja se u vremenu * \nabla \times \mathbf{v} = 0 * gdje je \mathbf{v} = \left( -\frac{y}{x^2+y^2}, \frac{x}{x^2+y^2} \right) * * Za render copy/paste ovdje: http://arachnoid.com/latex/ * * Rješenje: svugdje vektori jednake duljine (1) i kružno gibanje oko (0,0) */ void kruzno_gibanje ( const state_type &state, state_type &dxdt , const double t ); #endif //VELOCITY_FUNCTIONS_H
ca49d08c597c87061582c0ad764645e1084f5497
cb3239595fcc166cfcbd185c0aecbe1da35daaef
/include/Matriz.h
a6a2caf7dfa1a214f3d625e63248036954415f31
[]
no_license
ianfreitas1/TrabalhoGrafos2
da809d8f4468872f0947ec8dcdc0c8f126ba3658
4ef4afefe8cce3f9571ee816dd7d070aebcc2acd
refs/heads/master
2020-03-28T00:16:55.984128
2018-11-26T01:20:29
2018-11-26T01:20:29
147,390,961
0
0
null
null
null
null
UTF-8
C++
false
false
604
h
Matriz.h
#ifndef MATRIZ_H_ #define MATRIZ_H_ #include "Grafo.h" #include <string> #include <vector> #include <tuple> // struct int1bit{ // int x:1; // }int1bit; // using namespace std; class Matriz : public Grafo{ public: Matriz(std::string path); ~Matriz(); void Grau(); vector<tuple<int, float> > vizinhos(int v); void Grau2(); vector<bool> DFS(int raiz); vector<int> BFS(int raiz); void CC(); protected: //void iniciaMatriz(int m_numVertices); void addAresta(int v0, int vf, float peso); int** m_Matriz; }; #endif
fe0d35d7eec8a2857251386eb9add65f6b412c11
74ad260319522ef4902f79c119cbdcebd86762c0
/solvers/CoinAll-1.6.0-win64-intel11.1/include/coin/CouennePrecisions.hpp
d087b607307c2fe0c5d75d2ee3c0f20994c44150
[]
no_license
johnpaulguzman/MINLP-Solve
84251e5131ff425ef7e3bac76d1fd360b44a02c8
0a475ac59020aacecbda165b3af6055d1c9aa10c
refs/heads/master
2020-12-25T18:51:43.999191
2017-06-29T20:16:06
2017-06-29T20:16:06
93,992,900
0
0
null
null
null
null
UTF-8
C++
false
false
1,091
hpp
CouennePrecisions.hpp
/* $Id: CouennePrecisions.hpp 571 2011-05-09 13:26:44Z pbelotti $ * * Name: CouennePrecisions.hpp * Author: Pietro Belotti * Purpose: constants for evaluation procedures * * (C) Carnegie-Mellon University, 2006-10. * This file is licensed under the Eclipse Public License (EPL) */ #ifndef COUENNE_PRECISIONS_HPP #define COUENNE_PRECISIONS_HPP #include <math.h> namespace Couenne { // must be >= 1e-7 #define COUENNE_EPS 1.e-07 // to be used in bounds tightening to avoid node pruning due to strict COUENNE_EPS tolerance #define COUENNE_BOUND_PREC 1.e-5 // for integrality check #define COUENNE_EPS_INT 1.e-9 // for simplification #define COUENNE_EPS_SIMPL 1.e-20 // for bounds #define COUENNE_INFINITY 1.e+50 // for cuts, ensures stability and scaling in Clp #define COU_MAX_COEFF 1.e+9 // for cuts, ditto #define COU_MIN_COEFF 1.e-9 // rounds to nearest integer #define COUENNE_round(x) ((int) (floor ((x) + 0.5))) #define MAX_BOUND 1.e45 /// used to declare LP unbounded const double Couenne_large_bound = 9.999e12; } #endif
e06d665cdd93a0a3b8bc1c04cd0154ff8035ac3f
a93987f358caecd2f2b1d9f06a5546acb2767ad5
/08_Multiplayer/Networking/src/SFML-Book/server/main.cpp
799844b9ffea85d8234a076b88dde732ea2fca62
[ "BSD-2-Clause" ]
permissive
Clever-Boy/SFML-book
5787d9344a9a21c8340f714db94cc00f89f58f20
526f96a8933de021750843fbb86e37372cb3a8f0
refs/heads/master
2021-01-18T10:04:45.497486
2016-07-15T13:19:44
2016-07-15T13:20:22
65,650,868
2
0
null
2016-08-14T05:07:10
2016-08-14T05:07:08
null
UTF-8
C++
false
false
376
cpp
main.cpp
#include <SFML-Book/server/Server.hpp> #include <iostream> #include <cstdlib> int main(int argc, char* argv[]) { int port = 5678; std::cout<<"Usage is : "<<argv[0]<<" [port]"<<std::endl; if(argc >1 ) port = std::atoi(argv[1]); std::cout<<"Server start on port "<<port<<std::endl; book::Server server(port); server.run(); return 0; }
06eb3e41b63a4723f95bdccfaf28ecc82a6f47f8
6c40b92de13b247e682fe703899293b5e1e2d7a6
/hdu/1024/main.cpp
ca3b5601727985ea6d0a2454cee8d34d0a0c5cab
[]
no_license
ismdeep/ICPC
8154e03c20d55f562acf95ace5a37126752bad2b
2b661fdf5dc5899b2751de7d67fb26ccb6e24fc1
refs/heads/master
2020-04-16T17:44:24.296597
2016-07-08T02:59:01
2016-07-08T02:59:01
9,766,019
1
0
null
null
null
null
WINDOWS-1256
C++
false
false
1,110
cpp
main.cpp
//project name:1024 ( Max Sum Plus Plus ) //Author:¼üإجة±تض //Creat Date & Time:Sun Apr 22 21:27:13 2012 #include <iostream> #include <stdio.h> using namespace std; int f[1000003]; int best[2][1000003]; int N, M; int a[1000003]; int sum[1000003]; int main() { while (scanf("%d%d", &M, &N) != EOF) { int ans = -2000000000; sum[0] = 0; for (int i = 1; i <= N; i++) { scanf("%d", &a[i]); sum[i] = sum[i - 1] + a[i]; } for (int i = 0; i <= N; i++) best[0][i] = 0; int cur = 0; for (int j = 1; j <= M; j++) { for (int i = 0; i <= j - 1; i++) best[1 - cur][i] = -2000000000; for (int i = j; i <= N; i++) { if (j == i) f[i] = sum[i]; else f[i] = max(best[cur][i - 1], f[i - 1]) + a[i]; best[1 - cur][i] = max(best[1 - cur][i - 1], f[i]); if (j == M) ans = max(ans, f[i]); } cur = 1 - cur; } printf("%d\n", ans); } return 0; } //end //ism
6eee41d9a45e64475e0d9b60468dd2a51aa9f53d
7219e61fe07bd6fc581dcd212f4a6c82f2ec2be9
/Game6.0/core/客户端组件/游戏广场/GameFrame.cpp
a6e2676b5a1037079c8b76b740bfe03d0e01e9e8
[]
no_license
860git/whgame
5028006f02fb2e73f574b4482f59409edfce91c1
548170488da5c2d26ac2c8ba9085b0d37899d637
refs/heads/master
2021-08-10T20:54:41.195861
2019-03-21T15:31:17
2019-03-21T15:31:17
102,350,514
0
0
null
2017-09-04T10:42:51
2017-09-04T10:42:51
null
GB18030
C++
false
false
13,818
cpp
GameFrame.cpp
#include "Stdafx.h" #include "GameFrame.h" #include "GlobalUnits.h" ////////////////////////////////////////////////////////////////////////// //宏定义 #define BORDER_WIDTH 7 //边框宽度 #define TITLE_HEIGHT 95 //标题高度 //屏幕位置 #define LESS_SCREEN_X 1024 //最小宽度 #define LESS_SCREEN_Y 720 //最小高度 //按钮标示 #define IDC_BT_MIN 1000 //最小按钮 #define IDC_BT_MAX 1001 //最小按钮 #define IDC_BT_CLOSE 1002 //关闭按钮 #define IDC_BT_BUTTON_1 1003 //功能按钮 #define IDC_BT_BUTTON_2 1004 //功能按钮 #define IDC_BT_BUTTON_3 1005 //功能按钮 #define IDC_BT_BUTTON_4 1006 //功能按钮 #define IDC_BT_BUTTON_5 1007 //功能按钮 //消息定义 #define WM_SETUP_FINISH WM_USER+100 //安装完成 ////////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CGameFrame, CFrameWnd) ON_WM_SIZE() ON_WM_PAINT() ON_WM_CLOSE() ON_WM_CREATE() ON_WM_NCHITTEST() ON_WM_ERASEBKGND() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONDBLCLK() ON_WM_SETTINGCHANGE() ON_WM_GETMINMAXINFO() ON_BN_CLICKED(IDC_BT_MIN, OnBnClickedMin) ON_BN_CLICKED(IDC_BT_MAX, OnBnClickedMax) ON_BN_CLICKED(IDC_BT_CLOSE, OnBnClickedClose) ON_MESSAGE(WM_HOTKEY,OnHotKeyMessage) ON_MESSAGE(WM_SETUP_FINISH,OnMessageSetupFinish) ON_BN_CLICKED(IDC_BT_BUTTON_1, OnBnClickedButton1) ON_BN_CLICKED(IDC_BT_BUTTON_2, OnBnClickedButton2) ON_BN_CLICKED(IDC_BT_BUTTON_3, OnBnClickedButton3) ON_BN_CLICKED(IDC_BT_BUTTON_4, OnBnClickedButton4) ON_BN_CLICKED(IDC_BT_BUTTON_5, OnBnClickedButton5) END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////// //构造函数 CGameFrame::CGameFrame() { //界面状态 m_bMaxShow=false; m_rcNormalSize.SetRect(0,0,0,0); //加载资源 HINSTANCE hInstance=AfxGetInstanceHandle(); m_ImageL.SetLoadInfo(IDB_FRAME_L,hInstance); m_ImageR.SetLoadInfo(IDB_FRAME_R,hInstance); m_ImageTL.SetLoadInfo(IDB_FRAME_TL,hInstance); m_ImageTM.SetLoadInfo(IDB_FRAME_TM,hInstance); m_ImageTR.SetLoadInfo(IDB_FRAME_TR,hInstance); return; } //析构函数 CGameFrame::~CGameFrame() { } //消息解释 BOOL CGameFrame::PreTranslateMessage(MSG * pMsg) { m_ToolTipCtrl.RelayEvent(pMsg); return __super::PreTranslateMessage(pMsg); } //最大窗口 bool CGameFrame::MaxSizeWindow() { //状态判断 if (m_bMaxShow==false) { //默认位置 GetWindowRect(&m_rcNormalSize); //设置按钮 m_btMax.SetButtonImage(IDB_FRAME_RESORE,AfxGetInstanceHandle(),false); //获取位置 CRect rcArce; SystemParametersInfo(SPI_GETWORKAREA,0,&rcArce,SPIF_SENDCHANGE); //移动窗口 m_bMaxShow=true; LockWindowUpdate(); SetWindowPos(NULL,rcArce.left-2,rcArce.top-2,rcArce.Width()+4,rcArce.Height()+4,SWP_NOZORDER); UnlockWindowUpdate(); } return true; } //还原窗口 bool CGameFrame::RestoreWindow() { //状态判断 if (m_bMaxShow==true) { //设置按钮 m_btMax.SetButtonImage(IDB_FRAME_MAX,AfxGetInstanceHandle(),false); //移动窗口 m_bMaxShow=false; LockWindowUpdate(); SetWindowPos(NULL,m_rcNormalSize.left,m_rcNormalSize.top,m_rcNormalSize.Width(),m_rcNormalSize.Height(),SWP_NOZORDER); UnlockWindowUpdate(); } return true; } //建立消息 int CGameFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (__super::OnCreate(lpCreateStruct)==-1) return -1; //设置属性 ModifyStyle(WS_CAPTION|WS_BORDER,0,0); //设置图标 HICON hIcon=LoadIcon(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_MAINFRAME)); SetIcon(hIcon,TRUE); SetIcon(hIcon,FALSE); //设置标题 CString strTitle; strTitle.LoadString(AfxGetInstanceHandle(),IDS_MAIN_TITLE); SetWindowText(strTitle); //广告控件 //m_BrowerAD.Create(NULL,NULL,WS_VISIBLE|WS_CHILD,CRect(0,0,0,0),this,100,NULL); //m_BrowerAD.Navigate(TEXT("http://127.0.0.1/AD/GamePlazaAD.asp"),NULL,NULL,NULL,NULL); //创建按钮 m_btMin.Create(NULL,WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_MIN); m_btMax.Create(NULL,WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_MAX); m_btClose.Create(NULL,WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_CLOSE); m_btButton1.Create(TEXT(""),WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_BUTTON_1); m_btButton2.Create(TEXT(""),WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_BUTTON_2); m_btButton3.Create(TEXT(""),WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_BUTTON_3); m_btButton4.Create(TEXT(""),WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_BUTTON_4); m_btButton5.Create(TEXT(""),WS_CHILD|WS_VISIBLE,CRect(0,0,0,0),this,IDC_BT_BUTTON_5); //设置图片 m_btMin.SetButtonImage(IDB_FRAME_MIN,AfxGetInstanceHandle(),false); m_btMax.SetButtonImage(IDB_FRAME_RESORE,AfxGetInstanceHandle(),false); m_btClose.SetButtonImage(IDB_FRAME_CLOSE,AfxGetInstanceHandle(),false); m_btButton1.SetButtonImage(IDB_FRAME_BT_BUTTON_1,AfxGetInstanceHandle(),false); m_btButton2.SetButtonImage(IDB_FRAME_BT_BUTTON_2,AfxGetInstanceHandle(),false); m_btButton3.SetButtonImage(IDB_FRAME_BT_BUTTON_3,AfxGetInstanceHandle(),false); m_btButton4.SetButtonImage(IDB_FRAME_BT_BUTTON_4,AfxGetInstanceHandle(),false); m_btButton5.SetButtonImage(IDB_FRAME_BT_BUTTON_5,AfxGetInstanceHandle(),false); //建立提示控件 m_ToolTipCtrl.Create(this); m_ToolTipCtrl.Activate(TRUE); m_ToolTipCtrl.AddTool(GetDlgItem(IDC_BT_MIN),TEXT("最小化游戏大厅")); m_ToolTipCtrl.AddTool(GetDlgItem(IDC_BT_CLOSE),TEXT("退出游戏大厅")); //创建控件 m_DlgControlBar.Create(IDD_CONTROL_BAR,this); m_DlgGamePlaza.Create(IDD_GAME_PLAZA,this); m_DlgControlBar.ActivePlazaViewItem(); m_DlgControlBar.ShowWindow(SW_SHOW); //注册热键 g_GlobalUnits.RegisterHotKey(m_hWnd,IDI_HOT_KEY_BOSS,g_GlobalOption.m_wBossHotKey); //窗口位置 CRect rcArce; SystemParametersInfo(SPI_GETWORKAREA,0,&rcArce,SPIF_SENDCHANGE); //显示窗口 MaxSizeWindow(); //ShowWindow(SW_SHOW); //默认位置 m_rcNormalSize.left=(rcArce.Width()-LESS_SCREEN_X)/2; m_rcNormalSize.top=(rcArce.Height()-LESS_SCREEN_Y)/2; m_rcNormalSize.right=(rcArce.Width()+LESS_SCREEN_X)/2; m_rcNormalSize.bottom=(rcArce.Height()+LESS_SCREEN_Y)/2; return 0; } //绘画消息 void CGameFrame::OnPaint() { CPaintDC dc(this); //获取位置 CRect rcClient; GetClientRect(&rcClient); //加载资源 int nXPos=0,nYPos=0; CImageHandle ImageLHandle(&m_ImageL); CImageHandle ImageRHandle(&m_ImageR); CImageHandle ImageTLHandle(&m_ImageTL); CImageHandle ImageTMHandle(&m_ImageTM); CImageHandle ImageTRHandle(&m_ImageTR); //绘画上边 m_ImageTL.BitBlt(dc,0,0); for (nXPos=m_ImageTL.GetWidth();nXPos<rcClient.Width()-m_ImageTR.GetWidth();nXPos+=m_ImageTM.GetWidth()) { m_ImageTM.BitBlt(dc,nXPos,0); } m_ImageTR.BitBlt(dc,rcClient.Width()-m_ImageTR.GetWidth(),0); //绘画左右 nXPos=rcClient.Width()-m_ImageR.GetWidth(); for (int nYPos=m_ImageTL.GetHeight();nYPos<rcClient.Height();nYPos+=m_ImageL.GetHeight()) { m_ImageL.BitBlt(dc,0,nYPos); m_ImageR.BitBlt(dc,nXPos,nYPos); } return; } //绘画背景 BOOL CGameFrame::OnEraseBkgnd(CDC * pDC) { Invalidate(FALSE); UpdateWindow(); return TRUE; } //设置改变 void CGameFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { __super::OnSettingChange(uFlags, lpszSection); //调整框架大小 CRect rcClient; SystemParametersInfo(SPI_GETWORKAREA,0,&rcClient,SPIF_SENDCHANGE); MoveWindow(&rcClient,TRUE); return; } //关闭消息 void CGameFrame::OnClose() { //关闭提示 if (g_GlobalUnits.GetGolbalUserData().dwUserID!=0L) { int nCode=AfxMessageBox(TEXT("您确实要关闭游戏广场吗?"),MB_YESNO|MB_DEFBUTTON2|MB_ICONQUESTION); if (nCode!=IDYES) return; } //隐藏界面 ShowWindow(SW_HIDE); //关闭房间 g_pControlBar->CloseAllRoomViewItem(); //保存配置 g_GlobalOption.SaveOptionParameter(); g_GlobalUnits.m_CompanionManager->SaveCompanion(); __super::OnClose(); } //功能按钮 void CGameFrame::OnBnClickedButton1() { m_DlgControlBar.WebBrowse(TEXT("http://www.dreamlib.com/game/"),true); return; } //功能按钮 void CGameFrame::OnBnClickedButton2() { m_DlgControlBar.WebBrowse(TEXT("http://www.dreamlib.com/home/"),true); return; } //功能按钮 void CGameFrame::OnBnClickedButton3() { m_DlgControlBar.WebBrowse(TEXT("http://www.dreamlib.com/bank/"),true); return; } //功能按钮 void CGameFrame::OnBnClickedButton4() { m_DlgControlBar.WebBrowse(TEXT("http://www.dreamlib.com/user/"),true); return; } //功能按钮 void CGameFrame::OnBnClickedButton5() { m_DlgControlBar.WebBrowse(TEXT("http://www.dreamlib.com/bbs/"),true); return; } //获取最大位置 void CGameFrame::OnGetMinMaxInfo(MINMAXINFO FAR * lpMMI) { //设置变量 lpMMI->ptMinTrackSize.x=LESS_SCREEN_X; lpMMI->ptMinTrackSize.y=LESS_SCREEN_Y; __super::OnGetMinMaxInfo(lpMMI); } //位置消息 void CGameFrame::OnSize(UINT nType, int cx, int cy) { __super::OnSize(nType, cx, cy); //设置控件 m_DlgControlBar.SetViewItemRect(BORDER_WIDTH,TITLE_HEIGHT,cx-2*BORDER_WIDTH,cy-TITLE_HEIGHT-CONTROL_BAR_HEIGHT); //锁定屏幕 LockWindowUpdate(); //移动控件 HDWP hDwp=BeginDeferWindowPos(32); const UINT uFlags=SWP_NOACTIVATE|SWP_NOZORDER|SWP_NOCOPYBITS; //其他控件 DeferWindowPos(hDwp,m_btMin,NULL,cx-102,3,0,0,uFlags|SWP_NOSIZE); DeferWindowPos(hDwp,m_btMax,NULL,cx-72,3,0,0,uFlags|SWP_NOSIZE); DeferWindowPos(hDwp,m_btClose,NULL,cx-42,3,0,0,uFlags|SWP_NOSIZE); DeferWindowPos(hDwp,m_DlgControlBar,NULL,0,cy-CONTROL_BAR_HEIGHT,cx,CONTROL_BAR_HEIGHT,uFlags); //按钮位置 CRect rcButton; m_btButton1.GetWindowRect(&rcButton); //间隔计算 int nEndPos=105; int nBeginPos=560; int nWindth=cx-nBeginPos-rcButton.Width()*5-nEndPos; int nButtonSpace=__min((cx-nBeginPos-rcButton.Width()*5-nEndPos)/4,30); //广告控件 DeferWindowPos(hDwp,m_BrowerAD,NULL,300,8,250,52,uFlags); //导航按钮 DeferWindowPos(hDwp,m_btButton1,NULL,cx-rcButton.Width()*5-nButtonSpace*4-nEndPos,6,0,0,uFlags|SWP_NOSIZE); DeferWindowPos(hDwp,m_btButton2,NULL,cx-rcButton.Width()*4-nButtonSpace*3-nEndPos,6,0,0,uFlags|SWP_NOSIZE); DeferWindowPos(hDwp,m_btButton3,NULL,cx-rcButton.Width()*3-nButtonSpace*2-nEndPos,6,0,0,uFlags|SWP_NOSIZE); DeferWindowPos(hDwp,m_btButton4,NULL,cx-rcButton.Width()*2-nButtonSpace*1-nEndPos,6,0,0,uFlags|SWP_NOSIZE); DeferWindowPos(hDwp,m_btButton5,NULL,cx-rcButton.Width()*1-nButtonSpace*0-nEndPos,6,0,0,uFlags|SWP_NOSIZE); //移动控件 EndDeferWindowPos(hDwp); //解除锁定 UnlockWindowUpdate(); return; } //最小按钮 void CGameFrame::OnBnClickedMin() { ShowWindow(SW_MINIMIZE); return; } //最小按钮 void CGameFrame::OnBnClickedMax() { if (m_bMaxShow==true) RestoreWindow(); else MaxSizeWindow(); return; } //关闭按钮 void CGameFrame::OnBnClickedClose() { g_pControlBar->CloseCurrentViewItem(); return; } //按键测试 LRESULT CGameFrame::OnNcHitTest(CPoint Point) { //按钮测试 if (m_bMaxShow==false) { //获取位置 CRect rcClient; GetClientRect(&rcClient); //转换位置 CPoint ClientPoint=Point; ScreenToClient(&ClientPoint); //左面位置 if (ClientPoint.x<=BORDER_WIDTH) { if (ClientPoint.y<=TITLE_HEIGHT) return HTTOPLEFT; if (ClientPoint.y>=(rcClient.Height()-BORDER_WIDTH)) return HTBOTTOMLEFT; return HTLEFT; } //右面位置 if (ClientPoint.x>=(rcClient.Width()-BORDER_WIDTH)) { if (ClientPoint.y<=TITLE_HEIGHT) return HTTOPRIGHT; if (ClientPoint.y>=(rcClient.Height()-BORDER_WIDTH)) return HTBOTTOMRIGHT; return HTRIGHT; } //上下位置 if (ClientPoint.y<=BORDER_WIDTH) return HTTOP; if (ClientPoint.y>=(rcClient.Height()-BORDER_WIDTH)) return HTBOTTOM; } return __super::OnNcHitTest(Point); } //鼠标消息 void CGameFrame::OnLButtonDown(UINT nFlags, CPoint Point) { __super::OnLButtonDown(nFlags,Point); //模拟按标题 if ((m_bMaxShow==false)&&(Point.y<=TITLE_HEIGHT)) { PostMessage(WM_NCLBUTTONDOWN,HTCAPTION,MAKELPARAM(Point.x,Point.y)); } return; } //鼠标消息 void CGameFrame::OnLButtonDblClk(UINT nFlags, CPoint Point) { __super::OnLButtonDblClk(nFlags,Point); //状态判断 if (Point.y>TITLE_HEIGHT) return; //控制窗口 if (m_bMaxShow==true) RestoreWindow(); else MaxSizeWindow(); return; } //安装完成 LRESULT CGameFrame::OnMessageSetupFinish(WPARAM wParam, LPARAM lParam) { g_GlobalUnits.m_ServerListManager.UpdateGameKind((WORD)wParam); return 0; } //热键消息 LRESULT CGameFrame::OnHotKeyMessage(WPARAM wParam, LPARAM lParam) { switch (wParam) { case IDI_HOT_KEY_BOSS: //老板热键 { //变量定义 bool bBossCome=(IsWindowVisible()==FALSE)?false:true; //隐藏窗口 if (bBossCome==false) { //还原窗口 ShowWindow(SW_RESTORE); ShowWindow(SW_SHOW); //置顶窗口 SetActiveWindow(); BringWindowToTop(); SetForegroundWindow(); } else { //隐藏窗口 ShowWindow(SW_MINIMIZE); ShowWindow(SW_HIDE); } //发送消息 for (INT_PTR i=0;i<MAX_SERVER;i++) { if (m_DlgControlBar.m_pRoomViewItem[i]!=NULL) { m_DlgControlBar.m_pRoomViewItem[i]->NotifyBossCome(bBossCome); } } return 0; } } return 0; } //////////////////////////////////////////////////////////////////////////
2e80d11208eacdacfed2e2cf9aa3ce8e1757689c
aa82c3e3be201e05225d31bda4e01ac577457d6f
/Src/FruitsAnimator/Edit/EditWholeSkeletonOP.h
e9b01c24a1c1feefd7d2f67897d32eff83123e50
[]
no_license
xzrunner/doodle_editor
8524493765676b821398acc090c0e7838e6e9647
78351087470cb38265f7a26317dcd116b8d02b0d
refs/heads/master
2020-03-22T18:55:22.851215
2018-07-10T22:17:30
2018-07-10T22:17:30
140,491,803
0
0
null
null
null
null
UTF-8
C++
false
false
813
h
EditWholeSkeletonOP.h
#ifndef _FRUITS_ANIMATOR_EDIT_WHOLE_SKELETON_OP_H_ #define _FRUITS_ANIMATOR_EDIT_WHOLE_SKELETON_OP_H_ #include "Dataset/WholeSkeleton.h" namespace FRUITS_ANIMATOR { namespace edit_whole_skeleton { class RotateBoneAOP; } class EditWholeSkeletonOP : public wxgui::ZoomViewOP { public: EditWholeSkeletonOP(wxgui::EditPanel* editPanel, WholeSkeleton* skeleton); virtual bool onMouseLeftDown(int x, int y); virtual bool onMouseLeftUp(int x, int y); virtual bool onMouseDrag(int x, int y); //virtual bool onDraw() const; virtual bool clear(); private: WholeSkeleton* m_skeleton; WholeSkeleton::Sprite* m_selected; f2Vec2 m_lastPos; f2Vec2 m_firstPos; friend class edit_whole_skeleton::RotateBoneAOP; }; // EditWholeSkeletonOP } #endif // _FRUITS_ANIMATOR_EDIT_WHOLE_SKELETON_OP_H_
2b52c11d3b15cb81f86678e97155363d883affa7
84fe0a2cfc951d3636272951cd2a4fa582ae557b
/TankWar/Source/TankWar/Private/TankPlayerController.cpp
b272e4c0d7d58a3aee736830e04717bc7d0508a5
[]
no_license
cristian67/TankWar3D-UnrealEngine4
e5a88abe646767e3043c7a6d0ae12ca10d9469a9
29342990334bb316450435206c721408ba01cf79
refs/heads/master
2021-10-16T15:19:07.333996
2018-12-28T13:13:23
2018-12-28T13:13:23
154,738,503
1
0
null
null
null
null
UTF-8
C++
false
false
2,852
cpp
TankPlayerController.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "TankPlayerController.h" #include "TankWar.h" #include "Engine/World.h" #include "TankAimingComponent.h" #include "Tank.h" class Tank; void ATankPlayerController::BeginPlay() { Super::BeginPlay(); if (!GetPawn()) { return; } auto AimingComponent = GetPawn()->FindComponentByClass<UTankAimingComponent>(); if (!ensure(AimingComponent)) { return; } FoundAimingComponent(AimingComponent); } void ATankPlayerController::SetPawn(APawn * InPawn) { Super::SetPawn(InPawn); if (InPawn) { auto PosesionTank = Cast<ATank>(InPawn); if (!ensure(PosesionTank)) { return; } //subscribir el metodo local del tanque (dead event) PosesionTank->OnDeath.AddUniqueDynamic(this, &ATankPlayerController::OnPossedTankDeath); } } void ATankPlayerController::OnPossedTankDeath() { StartSpectatingOnly(); } // Called every frame void ATankPlayerController::Tick(float DeltaTime) { Super::Tick(DeltaTime); AimTowardsCrosshair(); } //Punteria void ATankPlayerController::AimTowardsCrosshair() { auto AimingComponent = GetPawn()->FindComponentByClass<UTankAimingComponent>(); if (!ensure(AimingComponent)) { return; } FVector HitLocation; bool bGotHitLocation = GetSightRayHitLocation(HitLocation); if (bGotHitLocation) { //llamar clase tank metodo AimAT AimingComponent->AimAt(HitLocation); } } //Get world location si la linetrace esta a travez del crosshair bool ATankPlayerController::GetSightRayHitLocation(FVector &HitLocation) const { //Find the crooshair position int32 ViewportSizeX, ViewportSizeY; GetViewportSize(ViewportSizeX, ViewportSizeY); auto ScreenLocation = FVector2D(ViewportSizeX * CrosshairXLocation, ViewportSizeY * CrosshairYLocation); //Actualizar posicion del puntero(crosshair) FVector LookDirection; if (GetLookDirection(ScreenLocation, LookDirection)) { //linea de trazo y rango maximo de golpe GetLookVectorHit(LookDirection, HitLocation); } return true; } bool ATankPlayerController::GetLookVectorHit(FVector LookDirection, FVector &HitLocation) const { FHitResult HitResult; auto StartLocation = PlayerCameraManager->GetCameraLocation(); auto EndLocation = StartLocation + (LookDirection * LineTranceRange); if (GetWorld()->LineTraceSingleByChannel( HitResult, StartLocation, EndLocation, ECollisionChannel::ECC_Camera) ) { HitLocation = HitResult.Location; return true; } HitLocation = FVector(0); return false; } bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector &LookDirection) const { FVector CamaraWorldLocation; //Descartado //DeprojectScreenPostitionToWorld es bool, y da valor a Camara y World return DeprojectScreenPositionToWorld( ScreenLocation.X, ScreenLocation.Y, CamaraWorldLocation, LookDirection ); }
a668f6df2e38f9707324863fc4c5389c14c166d3
2c6494171023427fded3555ca6d13af7ea921843
/InterviewBit/backtracking/SUBSET/main.cpp
b1a731f304276551f9fc3de629e5e0b141003a2a
[]
no_license
monish001/CPP-Programs
7d835cb4ec59c03d7b402d7be91062d68a7001a5
406d1949a52d03bfec15beef4378729a2c284eee
refs/heads/master
2021-01-23T19:12:22.356388
2016-03-12T13:06:18
2016-03-12T13:06:18
1,692,308
1
0
null
null
null
null
UTF-8
C++
false
false
1,613
cpp
main.cpp
#include <string> #include <algorithm> #include <vector> #include <iostream> using namespace std; vector<vector<int> > result; void _subsets(const vector<int>& nums, const int startIndex, vector<int> setSoFar){ int nNums = nums.size(); if(nNums == startIndex){ result.push_back(setSoFar); return; } _subsets(nums, startIndex+1, setSoFar); setSoFar.push_back(nums[startIndex]); _subsets(nums, startIndex+1, setSoFar); setSoFar.pop_back(); } bool compareVecInts(const vector<int>& vec1, const vector<int>& vec2){ int ind1=0, ind2=0, len1=vec1.size(), len2 = vec2.size(); for(; ind1<len1 && ind2<len2; ind1++, ind2++){ if(vec1[ind1] != vec2[ind2]){ return vec1[ind1] < vec2[ind2]; } } if(ind1 == len1){ return true; } return false; } //vector<vector<int> > Solution::subsets(vector<int> &A) { vector<vector<int> > subsets(vector<int> &nums) { sort(nums.begin(), nums.end()); result = vector<vector<int> >(); _subsets(nums, 0, vector<int>()); sort(result.begin(), result.end(), compareVecInts); return result; } void printVec(const vector<vector<int> >& vec){ int len = vec.size(); for(int index=0; index<len; index++){ vector<int> aVec = vec[index]; int innerLen = aVec.size(); for(int innerIndex=0; innerIndex<innerLen; innerIndex++){ cout<<aVec[innerIndex]<<" "; } cout<<endl; } } int main() { vector<int> vec; vec.push_back(3); vec.push_back(2); vec.push_back(1); printVec(subsets(vec)); return 0; }
62a232cc323cd06369c0be8e220b61176fb7123e
721476f984dbbb7efe9e3aec6f0dbb305a4c47d8
/lab 5/lab5_3.cpp
3ea17344839cbe554e385753ffba2753dcbde024
[]
no_license
kogs11/T2004E_LBEP
13ab130910319d2255b86380b5dc2a5870a1d703
38641edff58efedd01f3df15fce80e8e009b5b13
refs/heads/master
2022-09-10T07:15:40.986560
2020-06-02T13:03:39
2020-06-02T13:03:39
262,034,491
0
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
lab5_3.cpp
#include <stdio.h> int main(){ int s=0; for(int i=0,count=0 ;count<100 ; i++){ if(i%2!=0){ s+=i; count++; } } printf("Tong 100 so le >0 dau tien la:%d",s); }
54790c173ad97fdf702efe52eb741e4b60dd3763
333b58a211c39f7142959040c2d60b69e6b20b47
/Include/CmdServer.h
8f950d76b4ed82121c3089bc21f7365e79f738e0
[]
no_license
JoeAltmaier/Odyssey
d6ef505ade8be3adafa3740f81ed8d03fba3dc1a
121ea748881526b7787f9106133589c7bd4a9b6d
refs/heads/master
2020-04-11T08:05:34.474250
2015-09-09T20:03:29
2015-09-09T20:03:29
42,187,845
0
0
null
null
null
null
UTF-8
C++
false
false
9,015
h
CmdServer.h
/************************************************************************* * * This material is a confidential trade secret and proprietary * information of ConvergeNet Technologies, Inc. which may not be * reproduced, used, sold or transferred to any third party without the * prior written consent of ConvergeNet Technologies, Inc. This material * is also copyrighted as an unpublished work under sections 104 and 408 * of Title 17 of the United States Code. Law prohibits unauthorized * use, copying or reproduction. * * Description: * * Update Log: * 06/11/99 Dipam Patel: Create file * *************************************************************************/ #ifndef __QUEUE_OPERATIONS_H__ #define __QUEUE_OPERATIONS_H__ #pragma pack(4) #include "CtTypes.h" #include "assert.h" #include "DdmOsServices.h" #include "PtsCommon.h" #include "ReadTable.h" #include "Listen.h" #include "Rows.h" #include "Table.h" #include "CommandQueue.h" #include "StatusQueue.h" #ifndef WIN32 typedef void* HANDLE; #endif typedef void (DdmServices::*pCmdCallback_t)(HANDLE handle, void *pData); #ifndef INITIALIZECALLBACK typedef void (DdmServices::*pInitializeCallback_t)(STATUS status); #endif #ifdef WIN32 #define CMDCALLBACK(clas,method) (pCmdCallback_t) method #elif defined(__ghs__) // Green Hills #define CMDCALLBACK(clas,method) (pCmdCallback_t) &clas::method #else // MetroWerks #define CMDCALLBACK(clas,method) (pCmdCallback_t)&method #endif #ifndef INITIALIZECALLBACK #ifdef WIN32 #define INITIALIZECALLBACK(clas,method) (pInitializeCallback_t) method #elif defined(__ghs__) // Green Hills #define INITIAlIZECALLBACK(clas,method) (pInitializeCallback_t) &clas::method #else // MetroWerks #define INITIALIZECALLBACK(clas,method) (pInitializeCallback_t)&method #endif #endif class CmdServer : DdmServices { public: //************************************************************************ // CONSTRUCTOR // // queueName - name of the queue to be used (Status Que // name generated internally) // sizeofCmdData - Max size for cmd data // sizeofStatusData- Max size for status(event) data (Can be 0) // pParentDdm - parent Ddm pointer // cmdInsertionCallback - address of the handler routine which // will be called when any cmd is inserted // in the cmd queue. // // Note: The queueName, sizeofCmdData and sizeofStatusData should // match the ones used by the corresponding CmdSender object //************************************************************************ CmdServer( String64 queueName, U32 sizeofCmdData, U32 sizeofStatusData, DdmServices *pParentDdm, pCmdCallback_t cmdInsertionCallback); #ifdef VAR_CMD_QUEUE CmdServer( String64 queueName, DdmServices *pParentDdm, pCmdCallback_t cmdInsertionCallback); #endif //************************************************************************ // DESTRUCTOR // // This object should never be deleted. You should call the csrvTerminate() // method which will internally take care of deletion. //************************************************************************ ~CmdServer(); //************************************************************************ // csrvInitialize // // Will Define the Command Queue and Status Queues // Also a listener will be registered on the CQ for any inserts // into the CQ // // objectInitializedCallback - will be called when the object is // completely initialized. After this any // method on the object can be called safely. //************************************************************************ STATUS csrvInitialize(pInitializeCallback_t objectInitializedCallback); //************************************************************************ // csrvReportCmdStatus: // Functionality: // Allows reporting of Command Status // // cmdHandle - Handle corresponding to cmd for which status is being // reported. // statusCode - opcode for the cmd status // pResultData - any result data associated with the status (can be NULL) // pCmdData - the original cmd data corresponding to status // //************************************************************************ STATUS csrvReportCmdStatus( HANDLE cmdHandle, STATUS statusCode, void *pResultData, void *pCmdData); #ifdef VAR_CMD_QUEUE STATUS csrvReportCmdStatus( HANDLE cmdHandle, STATUS statusCode, void *pResultData, U32 cbResultData, void *pCmdData, U32 cbCmdData); #endif //************************************************************************ // csrvReportEventStatus: // Functionality: // Allows reporting of Events // // eventCode - opcode specifying the event // pResultData - any result data associated with the event // (can be NULL, if sizeofStatusData = 0) // //************************************************************************ STATUS csrvReportEvent( STATUS statusCode, void *pResultData); #ifdef VAR_CMD_QUEUE STATUS csrvReportEvent( STATUS statusCode, void *pResultData, U32 cbResultData); #endif //************************************************************************ // csrvTerminate // Functionality: // This routine is mandatory. It should be used instead of // delete and delete should never be called. // //************************************************************************ void csrvTerminate(); private: U32 m_isInitialized; #ifdef VAR_CMD_QUEUE bool m_varSizeData; #endif String64 m_CQTableName; String64 m_SQTableName; U32 m_sizeofCmdData; U32 m_sizeofStatusData; DdmServices *m_pDdmServices; void *m_pCallersContext; pCmdCallback_t m_CQInsertRowCallback; U32 m_CQListenerType; U32 m_CQListenerId; // to stop listen U32* m_pCQListenTypeRet; U32 m_CQSizeOfModifiedRecord; void *m_pCQModifiedRecord; // for listeners void *m_pCQTableDataRet; // table data U32 m_sizeofCQTableDataRet; // size of table data U32 m_useTerminate; TSListen *m_pCQListenObject; pInitializeCallback_t m_objectInitializedCallback; enum { csrvCQ_TABLE_DEFINED_STATE = 1, csrvSQ_TABLE_DEFINED_STATE, csrvCQ_LISTENER_REGISTERED_STATE, csrvSQ_LISTENER_REGISTERED_STATE, csrvSQ_ROW_INSERTED_STATE, csrvSQ_ROW_DELETED_STATE, csrvCQ_ROW_DELETED_STATE #ifdef VAR_CMD_QUEUE ,csrvCQ_VL_ROW_READ_STATE #endif }; typedef struct{ U32 state; U32 rowsDeleted; void *pData; rowID newRowId; #ifdef VAR_CMD_QUEUE U32 value; U32 value1; #endif } CONTEXT; typedef struct _OUTSTANDING_CMD{ rowID cmdRowId; void *pCmdData; _OUTSTANDING_CMD *pNextCmd; } OUTSTANDING_CMD; OUTSTANDING_CMD *pHead; OUTSTANDING_CMD *pTail; private: //************************************************************************ // csrvReportStatus: // Functionality: // Allows reporting of events and command status // // cmdHandle - Handle corresponding to cmd for which status is being // reported. If reporting event then cmdHandle=NULL // type - SQ_COMMAND_STATUS or SQ_EVENT_STATUS // statusCode - opcode for the status // pResultData - any result data associated with the status (can be NULL) // pCmdData - the original cmd data corresponding to status (NULL for events) // //************************************************************************ STATUS csrvReportStatus( HANDLE cmdHandle, // NULL for events SQ_STATUS_TYPE type, // SQ_COMMAND_STATUS or SQ_EVENT_STATUS STATUS statusCode, void *pResultData, void *pCmdData); #ifdef VAR_CMD_QUEUE STATUS csrvReportStatus( HANDLE cmdHandle, // NULL for events SQ_STATUS_TYPE type, // SQ_COMMAND_STATUS or SQ_EVENT_STATUS STATUS statusCode, void *pResultData, U32 cbResultData, void *pCmdData, U32 cbCmdData); #endif STATUS csrvReplyHandler(void* _pContext, STATUS status ); STATUS csrvCQDefineTable(); STATUS csrvSQDefineTable(); #ifdef VAR_CMD_QUEUE STATUS csrvCQDefineVLTable(); STATUS csrvSQDefineVLTable(); #endif STATUS csrvDeleteRow( String64 tableName, rowID *pRowId, void *pContext); STATUS csrvRegisterListener( String64 tableName, U32 listenerType, U32 *pListenerId, U32** ppListenTypeRet, void** ppModifiedRecord, U32* pSizeofModifiedRecord, void *pContext, pTSCallback_t pCallback); void csrvAddOutstandingCmd(OUTSTANDING_CMD *pOutstandingCmd); void csrvCheckIfCmdOutstanding(StatusQueueRecord *pSQRecord); void csrvGetOutstandingCmd(HANDLE handle, OUTSTANDING_CMD **ppOutstandingCmd); void csrvDeleteOutstandingCmd(OUTSTANDING_CMD *pOutstandingCmd); void csrvDeleteAllOutstandingCmds(); }; #endif
8f3466310363e773bc46744f7f7b5e0cced0a529
6f28c80d2a04e8a178ce537ac79495dbd12aebb2
/cv_machine_learning/knn/knn.cpp
12461d0d24e664399339090e5421c208ed2fc497
[]
no_license
Frandy/machine_learning
383b6b082a175bc0e98935d85292d049b0761c5c
528f36905422f71be9533ebcadf6e9aab18b0cc1
refs/heads/master
2016-09-06T08:37:23.321570
2012-11-03T15:10:43
2012-11-03T15:10:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,218
cpp
knn.cpp
/* * knn.cpp * * Created on: Nov 1, 2012 * Author: chjd */ /* * knn, one of the simplest classification algorithm. * for a new point, it lookup its k nearest neighbors, and set the new point as the majority. */ /* * OpenCV中也实现了KNN算法, * 这里是OpenCV的doxygen文档关于KNN的部分, * http://www710.univ-lyon1.fr/~eguillou/documentation/opencv2/class_cv_k_nearest.html * 下面一篇对OpenCV里面KNN源码分析的博文,还没仔细看 * http://www.aiseminar.cn/bbs/forum.php?mod=viewthread&tid=824 */ /* C interface bool train ( const CvMat * trainData, const CvMat * responses, const CvMat * sampleIdx = 0, bool is_regression = false, int maxK = 32, bool updateBase = false ) float predict( const CvMat* sample [,<params>] ) ==> float knearest(const CvMat * trainData, const CvMat * responses, const CvMat* sample, int maxK = 32 ) // 与 kmeans 类似的时,train的输入和kmeans的输入基本上相同,但是kmeans是要得到分类结果,将结果写在response里面, * 而knn的train输入的response是有label的,作为训练用的,knn需要训练吗? * 与kmeans不同的是,knn应该可以predict,OpenCV里面不是这样给接口的,但这里我就用与其它分类器类似的接口,使用predict * 对给定的sample确定分类 * * 这里简化一下,将train与predict合并, */ /* knn algorithm 1. calculate the first k-points, make a max-heap by distance, 2. for each point in the remain train data, calculate the distance between samples, if it is smaller than the heap-top, pop-heap the max distance out, push_heap the new neighbor 3. find the majority label of the k neighbors in the heap */ #include "knn.h" #include "kmeans.h" // to use the getDis function bool CmpNeighbor(const Neighbor& a, const Neighbor& b) { return (a.dis<b.dis); } void InitKNeighbors(vector<Neighbor>& kneighbors, CvMat* trainData, CvPoint& sample, int maxK) { for(auto i=0;i<maxK;i++) { CvPoint tmp = cvPointFrom32f(((CvPoint2D32f*)trainData->data.fl)[i]); double dis = getDis(tmp,sample); Neighbor nneighbor; nneighbor.index = i; nneighbor.dis = dis; kneighbors.push_back(nneighbor); } make_heap(kneighbors.begin(),kneighbors.end(),CmpNeighbor); } void AddNewNeighbor(vector<Neighbor>& kneighbors, CvMat * trainData, int index, CvPoint& sample) { CvPoint tmp = cvPointFrom32f(((CvPoint2D32f*)trainData->data.fl)[index]); double dis = getDis(tmp,sample); double maxd = kneighbors[0].dis; // the first one, as the heap-top if(dis<maxd) { pop_heap(kneighbors.begin(),kneighbors.end(),CmpNeighbor); kneighbors.pop_back(); Neighbor nneighbor; nneighbor.index = index; nneighbor.dis = dis; kneighbors.push_back(nneighbor); push_heap(kneighbors.begin(),kneighbors.end(),CmpNeighbor); } } int FindMaxIndex(vector<int>& count, int cluster_count) { int maxk = 0; int maxc = count[maxk]; for(auto i = 0;i<cluster_count;i++) { if(count[i]>maxc) maxk = i; } return maxk; } /* * to get the majority label, * use majority algorithm ? if no label count larger than maxK/2 ? * add the param cluster_count, */ int MajorityLabel(vector<Neighbor>& kneighbors,CvMat * responses, int cluster_count) { vector<int> labels_count(cluster_count,0); int maxK = kneighbors.size(); for(auto i=0;i<maxK;i++) { int label = responses->data.i[kneighbors[i].index]; labels_count[label] += 1; } int label_index = FindMaxIndex(labels_count,cluster_count); return label_index; } int knearest(CvMat * trainData, CvMat * responses, int cluster_count, CvMat* samples, CvMat* sample_responses, int maxK) { int sample_count = samples->rows; // assert(sample_count==1); int data_count = trainData->rows; for(auto i=0;i<sample_count;i++) { CvPoint sample = cvPointFrom32f(((CvPoint2D32f*)samples->data.fl)[i]); vector<Neighbor> kneighbors; InitKNeighbors(kneighbors,trainData,sample,maxK); for(auto j=maxK;j<data_count;j++) { AddNewNeighbor(kneighbors,trainData,j,sample); } int label = MajorityLabel(kneighbors,responses,cluster_count); sample_responses->data.i[i] = label; } return 1; }
175f1294d875e4515af3beb8f64cb3b7f0493dd9
6d088ec295b33db11e378212d42d40d5a190c54c
/contrib/mul/clsfy/clsfy_logit_loss_function.h
dae86f590510bebe8d31356c0ac7deb8afe0f496
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
vxl/vxl
29dffd5011f21a67e14c1bcbd5388fdbbc101b29
594ebed3d5fb6d0930d5758630113e044fee00bc
refs/heads/master
2023-08-31T03:56:24.286486
2023-08-29T17:53:12
2023-08-29T17:53:12
9,819,799
224
126
null
2023-09-14T15:52:32
2013-05-02T18:32:27
C++
UTF-8
C++
false
false
2,445
h
clsfy_logit_loss_function.h
// This is mul/clsfy/clsfy_logit_loss_function.h #ifndef clsfy_logit_loss_function_h_ #define clsfy_logit_loss_function_h_ //: // \file // \brief Loss function for logit of linear classifier // \author TFC #include <vnl/vnl_cost_function.h> #include <mbl/mbl_data_wrapper.h> //: Loss function for logit of linear classifier. // For vector v' = (b w') (ie b=y[0], w=(y[1]...y[n])), computes // r(v) - (1/n_eg)sum log[(1-minp)logit(c_i * (b+w.x_i)) + minp] // // This is the sum of log prob of correct classification (+regulariser) // which should be minimised to train the classifier. // // Note: Regularisor only important to deal with case where perfect // classification possible, where scaling v would always increase f(v). // Plausible choice of regularisor is clsfy_quad_regulariser (below) class clsfy_logit_loss_function : public vnl_cost_function { private: mbl_data_wrapper<vnl_vector<double> >& x_; //: c[i] = -1 or +1, indicating class of x[i] const vnl_vector<double> & c_; //: Min probability (avoids log(zero)) double min_p_; //: Optional regularising function vnl_cost_function *reg_fn_; public: clsfy_logit_loss_function(mbl_data_wrapper<vnl_vector<double> >& x, const vnl_vector<double> & c, double min_p, vnl_cost_function* reg_fn=nullptr); //: The main function: Compute f(v) double f(vnl_vector<double> const& v) override; //: Calculate the gradient of f at parameter vector v. void gradf(vnl_vector<double> const& v, vnl_vector<double>& gradient) override; //: Compute f(v) and its gradient (if non-zero pointers supplied) void compute(vnl_vector<double> const& v, double *f, vnl_vector<double>* gradient) override; }; //: Simple quadratic term used to regularise functions // For vector v' = (b w') (ie b=y[0], w=(y[1]...y[n])), computes // f(v) = alpha*|w|^2 (ie ignores first element, which is bias of linear classifier) class clsfy_quad_regulariser : public vnl_cost_function { private: //: Scaling factor double alpha_; public: clsfy_quad_regulariser(double alpha=1e-6); //: The main function: Compute f(v) double f(vnl_vector<double> const& v) override; //: Calculate the gradient of f at parameter vector v. void gradf(vnl_vector<double> const& v, vnl_vector<double>& gradient) override; }; #endif // clsfy_logit_loss_function_h_
195f01129fb0953de69ee8ae4afe8f12de2797fe
c88a790764118bf4679f85c0c4b37d3dd99e3490
/seqlearningdecode/seq_ocr_chn_batch.cpp
c6286a0f2dc4d016691f57b8400cbe760180af8c
[]
no_license
swq-1993/ocr_record
40c120c1b4632731763843bdd6ae0e3c4c743217
4d168dd57d87add25d99170bbfd6cac97dd15398
refs/heads/master
2020-03-22T01:29:50.433144
2018-08-28T05:27:32
2018-08-28T05:27:32
139,309,006
0
0
null
null
null
null
UTF-8
C++
false
false
34,095
cpp
seq_ocr_chn_batch.cpp
/*************************************************************************** * * Copyright (c) 2016 Baidu.com, Inc. All Rights Reserved * **************************************************************************/ /** * @file seq_ocr_chn_batch.cpp * @author xieshufu(com@baidu.com) * @date 2016/12/23 13:28:08 * @brief * **/ #include "seq_ocr_chn_batch.h" #include "common_func.h" #include "SeqLEngLineBMSSWordDecoder.h" #include "seql_asia_line_bmss_word_decoder.h" #include "seql_asia_word_recog.h" #include "seql_asia_word_seg_processor.h" #include "reform_en_rst.h" #include "SeqLEngWordSegProcessor.h" #include <omp.h> extern char g_pimage_title[256]; namespace nsseqocrchn { /*sunwanqi add 0503 remove the chn_model,only through eng model*/ int CSeqModelChBatch::recognize_image_batch_only_eng(const std::vector<st_batch_img> vec_image,\ int model_type, bool fast_flag, std::vector<SSeqLEngLineInfor> &out_line_vec) { int ret =0; if (vec_image.size() <= 0 || (model_type != 0 && model_type != 1 && model_type != 2)) { ret = -1; return ret; } out_line_vec.resize(vec_image.size()); recognize_line_eng_batch_whole(vec_image, _m_recog_model_eng,\ _m_table_flag, out_line_vec); int out_line_vec_size = out_line_vec.size(); for (unsigned int i = 0; i < out_line_vec_size; i++) { std::string str_line_rst = ""; for (unsigned int j = 0; j < out_line_vec[i].wordVec_.size(); j++) { if (out_line_vec[i].wordVec_[j].left_add_space_) { str_line_rst += out_line_vec[i].wordVec_[j].wordStr_ + " "; } else { str_line_rst += out_line_vec[i].wordVec_[j].wordStr_; } } out_line_vec[i].lineStr_ = str_line_rst; } return ret; } int CSeqModelChBatch::recognize_image_batch(const std::vector<st_batch_img> vec_image,\ int model_type, bool fast_flag, std::vector<SSeqLEngLineInfor> &out_line_vec) { int ret = 0; if (vec_image.size() <= 0 || (model_type != 0 && model_type != 1 && model_type != 2)) { ret = -1; return ret; } recognize_line_chn(vec_image, \ _m_recog_model_row_chn, _m_recog_model_col_chn, out_line_vec); for(unsigned int i = 0; i < out_line_vec.size(); ++i){ std::cout<<"after_chnModel_out_line_vec_chn"<<i<<":"<<out_line_vec[i].lineStr_<<std::endl; } // call second english recognition if (model_type == 0 || model_type == 2) { recognize_line_eng_batch(vec_image, _m_recog_model_eng,\ _m_table_flag, out_line_vec); } for(unsigned int i = 0; i < out_line_vec.size(); ++i){ std::cout<<"after_engModel_out_line_vec_chn"<<i<<":"<<out_line_vec[i].lineStr_<<std::endl; } // merge the charcters which are overlapped // the small english model is called here int out_line_vec_size = out_line_vec.size(); for (unsigned int i = 0; i < out_line_vec_size; i++) { std::string str_line_rst = ""; for (unsigned int j = 0; j < out_line_vec[i].wordVec_.size(); j++) { if (out_line_vec[i].wordVec_[j].left_add_space_) { str_line_rst += out_line_vec[i].wordVec_[j].wordStr_ + " "; } else { str_line_rst += out_line_vec[i].wordVec_[j].wordStr_; } } out_line_vec[i].lineStr_ = str_line_rst; } return ret; } // sunwanqi add the recognize the row with whole english OCR engine void CSeqModelChBatch::recognize_line_eng_batch_whole(const std::vector<st_batch_img> &vec_imgs, CSeqLEngWordReg *recog_processor_en,\ int *ptable_flag, std::vector<SSeqLEngLineInfor> &out_line_vec){ SSeqLEngLineInfor out_line; for(unsigned int i = 0; i<vec_imgs.size(); ++i){ recognize_row_whole_eng_batch_v3(vec_imgs[i].img, recog_processor_en, true, out_line); out_line_vec[i] = out_line; /*std::cout<<"checkout_line:"; for(int i=0;i<out_line.wordVec_.size();i++) { std::cout<<out_line.wordVec_[i].wordStr_<<" "; } std::cout<<std::endl;*/ } //std::cout<<"_m_resnet_strategy_flag = 1:"<<_m_resnet_strategy_flag<<std::endl; if (_m_formulate_output_flag) { // formulate the output information for chinese/english output // english: word as the units std::vector<SSeqLEngLineInfor> new_line_vec; if (_m_resnet_strategy_flag) { formulate_output_resnet(out_line_vec, new_line_vec); } else { formulate_output(out_line_vec, new_line_vec); } out_line_vec = new_line_vec; } /*std::cout<<"checkout_line_vec:"; for(int i = 0;i<out_line_vec.size(); i++) { for(int j = 0; j < out_line_vec[i].wordVec_.size(); j++) { std::cout<<out_line_vec[i].wordVec_[j].wordStr_<<" "; } } std::cout<<std::endl;*/ return ; } // recognize the row with English OCR engine void CSeqModelChBatch::recognize_line_eng_batch(const std::vector<st_batch_img> &vec_imgs, CSeqLEngWordReg *recog_processor_en,\ int *ptable_flag, std::vector<SSeqLEngLineInfor> &out_line_vec) { // threshold for the whole row using english ocr const float row_whole_eng_thresh = 0.95; // threhsold for piecewise english ocr const int row_piece_eng_thresh = 5; const double vertical_aspect_ratio = 2.0; int out_line_vec_size = out_line_vec.size(); for (int i = 0; i < out_line_vec_size; i++) { int word_num = out_line_vec[i].wordVec_.size(); int line_w = out_line_vec[i].wid_; int line_h = out_line_vec[i].hei_; double ver_line_thresh = line_w * vertical_aspect_ratio; if (word_num <= 1 || line_h > ver_line_thresh) { continue ; } int eng_char_cnt = 0; double d_num_en_ratio = compute_en_char_ratio(out_line_vec[i], ptable_flag, eng_char_cnt); SSeqLEngLineInfor out_line; if (d_num_en_ratio >= row_whole_eng_thresh) { // call the whole row english model recognition // true: the region will be extend recognize_row_whole_eng_batch(vec_imgs[i].img, recog_processor_en, true, out_line_vec[i], out_line); out_line_vec[i] = out_line; } else if (eng_char_cnt >= row_piece_eng_thresh) { // call the piecewise english model recognition // false: the region will not be extended recognize_row_piece_eng_batch(vec_imgs[i].img, recog_processor_en, false, out_line_vec[i], out_line); out_line_vec[i] = out_line; } } //std::cout<<"_m_formulate_output_flag; "<<_m_formulate_output_flag<<std::endl; #1 //std::cout<<"_m_resnet_strategy_flag: "<<_m_resnet_strategy_flag<<std::endl; #0 if (_m_formulate_output_flag) { // formulate the output information for chinese/english output // english: word as the units std::vector<SSeqLEngLineInfor> new_line_vec; if (_m_resnet_strategy_flag) { formulate_output_resnet(out_line_vec, new_line_vec); } else { formulate_output(out_line_vec, new_line_vec); } out_line_vec = new_line_vec; } return ; } void CSeqModelChBatch::recognize_row_whole_eng_batch_v3(const IplImage *image, CSeqLEngWordReg *recog_processor_en, bool extend_flag, SSeqLEngLineInfor &out_line){ std::vector<SSeqLESegDecodeSScanWindow> in_eng_line_dect_vec; SSeqLESegDecodeSScanWindow temp_wind; temp_wind.left = 0; temp_wind.right = image->width - 1; temp_wind.top = 0; temp_wind.bottom = image->height - 1; temp_wind.isBlackWdFlag = 1; temp_wind.detectConf = 0; in_eng_line_dect_vec.push_back(temp_wind); std::vector<SSeqLEngLineInfor> out_line_vec_en; recognize_eng_row_batch(image, in_eng_line_dect_vec, extend_flag, recog_processor_en, out_line_vec_en); std::vector<SSeqLEngLineInfor> out_line_vec_en_new; reform_line_infor_vec_split_char(out_line_vec_en, image->width,out_line_vec_en_new); /*for(int i = 0; i<out_line_vec_en_new.size();i++) { for(int j = 0; j < out_line_vec_en_new[i].wordVec_.size(); j++) { std::cout<<out_line_vec_en_new[i].wordVec_[j].wordStr_<<" "; } std::cout<<std::endl; }*/ if (_m_formulate_output_flag) { for (unsigned int i = 0; i < out_line_vec_en_new.size(); i++) { for (unsigned int j = 0; j < out_line_vec_en_new[i].wordVec_.size(); j++) { out_line_vec_en_new[i].wordVec_[j].left_add_space_ = true; } } } out_line = out_line_vec_en_new[0]; } void CSeqModelChBatch::recognize_row_whole_eng_batch(const IplImage *image, CSeqLEngWordReg *recog_processor_en, bool extend_flag, const SSeqLEngLineInfor &out_line_chn, SSeqLEngLineInfor &out_line) { std::vector<SSeqLESegDecodeSScanWindow> in_eng_line_dect_vec; SSeqLESegDecodeSScanWindow temp_wind; temp_wind.left = out_line_chn.left_; temp_wind.right = out_line_chn.left_ + out_line_chn.wid_ - 1; temp_wind.top = out_line_chn.top_; temp_wind.bottom = out_line_chn.top_ + out_line_chn.hei_ - 1; temp_wind.isBlackWdFlag = out_line_chn.isBlackWdFlag_; temp_wind.detectConf = 0; in_eng_line_dect_vec.push_back(temp_wind); for (int i = 0; i < in_eng_line_dect_vec.size(); i++) { std::cout << "in_eng_line_dect_vec:" << in_eng_line_dect_vec[i].left << in_eng_line_dect_vec[i].right << std::endl; } std::vector<SSeqLEngLineInfor> out_line_vec_en; recognize_eng_row_batch(image, in_eng_line_dect_vec, extend_flag, recog_processor_en, out_line_vec_en); std::vector<SSeqLEngLineInfor> out_line_vec_en_new; reform_line_infor_vec_split_char(out_line_vec_en, image->width, out_line_vec_en_new); std::cout<<"out_line_vec_en_new.size():"<<out_line_vec_en.size()<<std::endl; //std::cout<<"out_line_vec_en_new.size():"<<out_line_vec_en_new.size()<<std::endl; //std::cout<<"out_line_vec_en_new[i].wordVec_.size()"<<out_line_vec_en_new[0].wordVec_.size()<<std::endl; //std::cout<<"_m_formulate_output_flag:"<<_m_formulate_output_flag<<std::endl; if (_m_formulate_output_flag) { for (unsigned int i = 0; i < out_line_vec_en_new.size(); i++) { for (unsigned int j = 0; j < out_line_vec_en_new[i].wordVec_.size(); j++) { out_line_vec_en_new[i].wordVec_[j].left_add_space_ = true; } } } int line_vec_ch_size = out_line_chn.wordVec_.size(); int line_eng_row_size = out_line_vec_en_new.size(); out_line = out_line_chn; if (line_eng_row_size > 0) { int line_vec_en_size = 0; for (unsigned int j = 0; j < out_line_vec_en_new[0].wordVec_.size(); j++) { line_vec_en_size += out_line_vec_en_new[0].wordVec_[j].charVec_.size(); } if (line_vec_en_size > line_vec_ch_size / 4.0) { out_line = out_line_vec_en_new[0]; } } return ; } void CSeqModelChBatch::recognize_row_piece_eng_batch(const IplImage *image, CSeqLEngWordReg *recog_processor_en, bool extend_flag, const SSeqLEngLineInfor &out_line_chn, SSeqLEngLineInfor &out_line) { int ret_val = 0; std::vector<SSeqLESegDecodeSScanWindow> in_eng_line_dect_vec; std::vector<int> start_vec; std::vector<int> end_vec; out_line = out_line_chn; ret_val = locate_eng_pos(out_line_chn, in_eng_line_dect_vec, start_vec, end_vec); if (ret_val != 0) { return ; } // recognize the row with english ocr std::vector<SSeqLEngLineInfor> out_line_vec_en; ret_val = recognize_eng_row_batch(image, in_eng_line_dect_vec, extend_flag, recog_processor_en, out_line_vec_en); if (ret_val != 0) { return ; } // get the position of each character std::vector<SSeqLEngLineInfor> out_vec_new; reform_line_infor_vec_split_char(out_line_vec_en, image->width, out_vec_new); SSeqLEngLineInfor merge_line; ret_val = merge_two_results(out_line, out_vec_new, start_vec, end_vec, merge_line); if (ret_val == 0) { out_line = merge_line; } return ; } int CSeqModelChBatch::merge_seg_line(std::vector<SSeqLEngLineRect> line_rect_vec, std::vector<SSeqLEngLineInfor> in_line_vec, std::vector<SSeqLEngLineInfor>& out_line_vec) { if (line_rect_vec.size() != in_line_vec.size()) { return -1; } if (in_line_vec.size() <= 0) { return -1; } out_line_vec.clear(); SSeqLEngLineInfor out_line = in_line_vec[0]; out_line.wordVec_.clear(); int last_line_right = 0; for (int i = 0; i < in_line_vec.size(); i++) { SSeqLEngLineInfor line = in_line_vec[i]; int next_line_left = 0; if (i < in_line_vec.size() - 1) { next_line_left = line_rect_vec[i + 1].left_; } else { next_line_left = line_rect_vec[i].left_ + line_rect_vec[i].wid_; } last_line_right = std::max(last_line_right, line_rect_vec[i].left_); //std::cout << next_line_left << " " << last_line_right << std::endl; int word_right = 0; for (int j = 0; j < line.wordVec_.size(); j++) { SSeqLEngWordInfor word = line.wordVec_[j]; if (word.left_ > next_line_left) { continue; } else if (word.left_ < last_line_right) { continue; } else { out_line.wordVec_.push_back(word); word_right = word.left_ + word.wid_; } } last_line_right = word_right; out_line.wid_ = next_line_left; } out_line_vec.push_back(out_line); return 0; } // recognize the english rows int CSeqModelChBatch::recognize_eng_row_batch(const IplImage *image, std::vector<SSeqLESegDecodeSScanWindow> in_eng_line_dect_vec, bool extend_flag, CSeqLEngWordReg *recog_processor_en, std::vector<SSeqLEngLineInfor>& out_line_vec_en) { int ret_val = 0; int max_long_line = 900; int max_seg_long = 900; int max_overlap_seg = 200; CSeqLEngWordSegProcessor seg_processor_en; std::vector<SSeqLEngLineRect> line_rect_vec_en; std::vector<SSeqLEngLineInfor> out_line_vec_tmp; ////////_m_resnet_strategy_flag==1 if (_m_resnet_strategy_flag) { std::vector<SSeqLEngLineRect> line_rect_vec; if (image->width <= max_long_line) { SSeqLEngLineRect line_rect; line_rect.left_ = 0; line_rect.top_ = 0; line_rect.wid_ = image->width; line_rect.hei_ = image->height; line_rect.isBlackWdFlag_ = 1; SSeqLEngRect win_rect; win_rect.left_ = 0; win_rect.top_ = 0; win_rect.wid_ = image->width; win_rect.hei_ = image->height; line_rect.rectVec_.push_back(win_rect); line_rect_vec.push_back(line_rect); } else { int st_pos = 0; while (st_pos + max_overlap_seg < image->width) { int seg_long = std::min(max_seg_long, (int)(image->width - st_pos)); //to overcome the last part too short if (st_pos + seg_long + max_overlap_seg >= image->width) { seg_long = image->width - st_pos; } SSeqLEngLineRect line_rect; line_rect.left_ = st_pos; line_rect.top_ = 0; line_rect.wid_ = seg_long; line_rect.hei_ = image->height; line_rect.isBlackWdFlag_ = 1; SSeqLEngRect win_rect; win_rect.left_ = st_pos; win_rect.top_ = 0; win_rect.wid_ = seg_long; win_rect.hei_ = image->height; line_rect.rectVec_.push_back(win_rect); line_rect_vec.push_back(line_rect); //std::cout << st_pos << " " << image->width << std::endl; st_pos += seg_long - max_overlap_seg; } } int line_rect_vec_size_t = line_rect_vec.size(); for (int j = 0; j < line_rect_vec_size_t; j++) { line_rect_vec_en.push_back(line_rect_vec[j]); } } else { //std::vector<SSeqLEngLineRect> line_rect_vec_en; seg_processor_en.set_exd_parameter(extend_flag); seg_processor_en.process_image_eng_ocr(image, in_eng_line_dect_vec); seg_processor_en.wordSegProcessGroupNearby(4); line_rect_vec_en = seg_processor_en.getSegLineRectVec(); } int line_rect_vec_size = line_rect_vec_en.size(); std::vector<SSeqLEngLineInfor> line_infor_vec_en; CSeqLEngLineDecoder * line_decoder = new CSeqLEngLineBMSSWordDecoder; for (unsigned int i = 0; i < line_rect_vec_size; i++) { // true: do not utilize the 2nd recognition function // false: utilize the 2nd recognition function SSeqLEngLineInfor temp_line; bool fast_recg_flag = true; SSeqLEngSpaceConf space_conf; // = seg_processor_en.getSegSpaceConf(i); ///////////_m_resnet_strategy_flag=0///// if (!_m_resnet_strategy_flag) { space_conf = seg_processor_en.getSegSpaceConf(i); } recog_processor_en->recognize_eng_word_whole_line(image, line_rect_vec_en[i], \ temp_line, space_conf, fast_recg_flag); /*std::cout<<"after_engModel_lineStr_:"; for (unsigned int i = 0; i < temp_line.wordVec_.size(); ++i){ std::cout<<temp_line.wordVec_[i].wordStr_<<" "; } std::cout<<std::endl;*/ line_infor_vec_en.push_back(temp_line); line_decoder->setWordLmModel(_m_eng_search_recog_eng, _m_inter_lm_eng); line_decoder->setSegSpaceConf(space_conf); line_decoder->set_acc_eng_highlowtype_flag(_m_acc_eng_highlowtype_flag); ((CSeqLEngLineBMSSWordDecoder*)line_decoder)->\ set_resnet_strategy_flag(_m_resnet_strategy_flag); SSeqLEngLineInfor out_line = line_decoder->decodeLine(\ recog_processor_en, temp_line); /*std::cout<<"after_decodePart_outline:"; for (unsigned int i = 0; i < out_line.wordVec_.size(); i++){ std::cout<<out_line.wordVec_[i].wordStr_<<" "; } std::cout<<std::endl;*/ /*std::string str_line = ""; for (unsigned int j = 0; j < out_line.wordVec_.size(); j++) { std::cout << out_line.left_ << " " << out_line.wid_ << std::endl; std::cout << out_line.wordVec_[j].wordStr_ << " " << out_line.wordVec_[j].left_ << " " << out_line.wordVec_[j].left_ + out_line.wordVec_[j].wid_ << std::endl; if (out_line.wordVec_[j].left_add_space_) { str_line += out_line.wordVec_[j].wordStr_ + " "; } else { str_line += out_line.wordVec_[j].wordStr_; } } std::cout << str_line << std::endl;*/ out_line_vec_tmp.push_back(out_line); } delete line_decoder; line_decoder = NULL; if (out_line_vec_tmp.size() > 1 && _m_resnet_strategy_flag) { merge_seg_line(line_rect_vec_en, out_line_vec_tmp, out_line_vec_en); } else { out_line_vec_en = out_line_vec_tmp; } return ret_val; } int CSeqModelChBatch::divide_dect_imgs(const std::vector<st_batch_img> &indectVec, std::vector<st_batch_img> &vec_row_imgs, std::vector<st_batch_img> &vec_column_imgs, std::vector<int> &vec_row_idxs, std::vector<int> &vec_column_idxs) { int ret = 0; const double vertical_aspect_ratio = 2.0; int dect_img_num = indectVec.size(); for (unsigned int iline_idx = 0; iline_idx < dect_img_num; iline_idx++) { int line_height = indectVec[iline_idx].img->height; int line_width = indectVec[iline_idx].img->width; double vertical_height_thresh = vertical_aspect_ratio*line_width; // classify whether the input line image belongs to vertical column if (line_height > vertical_height_thresh) { // vertical images vec_column_imgs.push_back(indectVec[iline_idx]); vec_column_idxs.push_back(iline_idx); } else { // horizontal images vec_row_imgs.push_back(indectVec[iline_idx]); vec_row_idxs.push_back(iline_idx); } } return ret; } void CSeqModelChBatch::recognize_line_chn(const std::vector<st_batch_img> vec_imgs,\ CSeqLAsiaWordReg *row_recog_processor, CSeqLAsiaWordReg *col_recog_processor, std::vector<SSeqLEngLineInfor> &out_line_vec) { // Here, the relationship between input and output should be preserved // 1.divide the image into row_image and col_image std::vector<st_batch_img> vec_row_imgs; std::vector<st_batch_img> vec_column_imgs; std::vector<int> vec_row_idxs; std::vector<int> vec_column_idxs; divide_dect_imgs(vec_imgs, vec_row_imgs, vec_column_imgs, \ vec_row_idxs, vec_column_idxs); // 2. recognize the row rectangle set std::vector<SSeqLEngLineInfor> out_row_line_vec; recognize_line_row_chn(vec_row_imgs, row_recog_processor, out_row_line_vec); out_line_vec.resize(vec_imgs.size()); for (int i = 0; i < out_row_line_vec.size(); i++) { int row_idx = vec_row_idxs[i]; out_line_vec[row_idx] = out_row_line_vec[i]; } // 3. recognize the column rectangle set if (col_recog_processor != NULL) { std::vector<SSeqLEngLineInfor> out_col_line_vec; recognize_line_col_chn(vec_column_imgs, col_recog_processor, out_col_line_vec); for (int i = 0; i < out_col_line_vec.size(); i++) { int row_idx = vec_column_idxs[i]; out_line_vec[row_idx] = out_col_line_vec[i]; } } return ; } void CSeqModelChBatch::recognize_line_seg(\ const std::vector<st_batch_img> vec_row_imgs,\ std::vector<SSeqLEngLineRect> line_rect_vec,\ CSeqLAsiaWordReg *recog_processor,\ std::vector<SSeqLEngLineInfor>& out_line_vec) { // 1. recognize using batch std::vector<SSeqLEngLineInfor> line_infor_vec; line_infor_vec.resize(line_rect_vec.size()); std::vector<SSeqLEngLineInfor> out_line_vec_tmp; ((CSeqLAsiaWordReg*)recog_processor)->set_candidate_num(_m_recg_cand_num); ((CSeqLAsiaWordReg*)recog_processor)->set_resnet_strategy_flag(_m_resnet_strategy_flag); ((CSeqLAsiaWordReg*)recog_processor)->recognize_line_batch(vec_row_imgs,\ line_rect_vec, line_infor_vec); // 2. decode row by row out_line_vec_tmp.clear(); for (unsigned int i = 0; i < line_infor_vec.size(); i++) { if (_m_debug_line_index != -1 && _m_debug_line_index != i) { continue ; } CSeqLAsiaLineBMSSWordDecoder * line_decoder = new CSeqLAsiaLineBMSSWordDecoder; //line_decoder->setWordLmModel(_m_eng_search_recog_chn, _m_inter_lm_chn); SSeqLEngLineInfor out_line; line_decoder->set_save_low_prob_flag(_m_save_low_prob_flag); line_decoder->set_resnet_strategy_flag(_m_resnet_strategy_flag); out_line = line_decoder->decode_line(recog_processor, line_infor_vec[i]); delete line_decoder; out_line_vec_tmp.push_back(out_line); /*std::string res = ""; for (int k = 0; k < out_line.wordVec_.size(); k++) { res += out_line.wordVec_[k].wordStr_; } std::cout << res << std::endl;*/ } // 3. merge seg line merge_seg_line(line_rect_vec, out_line_vec_tmp, out_line_vec); } // recognize the row image void CSeqModelChBatch::recognize_line_row_chn(\ const std::vector<st_batch_img> &vec_row_imgs,\ CSeqLAsiaWordReg *recog_processor, std::vector<SSeqLEngLineInfor> &out_line_vec) { int max_long_line = 900; int max_seg_long = 900; int max_overlap_seg = 200; std::vector<SSeqLEngLineInfor> out_line_vec_tmp; std::vector<int> long_line_id_vec; std::vector<SSeqLEngLineInfor> long_line_res_vec; std::vector<SSeqLEngLineInfor> short_line_vec; std::vector<st_batch_img> vec_short_row_imgs; long_line_res_vec.clear(); long_line_id_vec.clear(); short_line_vec.clear(); vec_short_row_imgs.clear(); // 1. row word segmentation std::vector<SSeqLEngLineRect> merge_rect_vec; for (int i = 0; i < vec_row_imgs.size(); i++) { if (vec_row_imgs[i].img->width > max_long_line) { int st_pos = 0; std::vector<SSeqLEngLineRect> line_rect_vec; line_rect_vec.clear(); std::vector<st_batch_img> vec_long_row_img; vec_long_row_img.clear(); std::vector<SSeqLEngLineInfor> out_long_line_vec; out_long_line_vec.clear(); while (st_pos + max_overlap_seg < vec_row_imgs[i].img->width) { int seg_long = std::min(max_seg_long, (int)(vec_row_imgs[i].img->width - st_pos)); //to overcome the last part too short if (st_pos + seg_long + max_overlap_seg >= \ vec_row_imgs[i].img->width) { seg_long = vec_row_imgs[i].img->width - st_pos; } SSeqLEngLineRect line_rect; line_rect.left_ = st_pos; line_rect.top_ = 0; line_rect.wid_ = seg_long; line_rect.hei_ = vec_row_imgs[i].img->height; line_rect.isBlackWdFlag_ = 1; SSeqLEngRect win_rect; win_rect.left_ = st_pos; win_rect.top_ = 0; win_rect.wid_ = seg_long; win_rect.hei_ = vec_row_imgs[i].img->height; line_rect.rectVec_.push_back(win_rect); line_rect_vec.push_back(line_rect); vec_long_row_img.push_back(vec_row_imgs[i]); //std::cout << st_pos << " " << vec_row_imgs[i].img->width << " " << seg_long << std::endl; st_pos += seg_long - max_overlap_seg; } recognize_line_seg(vec_long_row_img, line_rect_vec, recog_processor, out_long_line_vec); if (out_long_line_vec.size() == 1) { /*std::cout << "long id " << i << std::endl; std::string res = ""; for (int k = 0; k < out_long_line_vec[0].wordVec_.size(); k++) { res += out_long_line_vec[0].wordVec_[k].wordStr_; } std::cout << "out res: " << res << std::endl;*/ long_line_id_vec.push_back(i); long_line_res_vec.push_back(out_long_line_vec[0]); } } else { std::vector<SSeqLEngLineRect> line_rect_vec; SSeqLEngLineRect line_rect; line_rect.left_ = 0; line_rect.top_ = 0; line_rect.wid_ = vec_row_imgs[i].img->width; line_rect.hei_ = vec_row_imgs[i].img->height; line_rect.isBlackWdFlag_ = 1; SSeqLEngRect win_rect; win_rect.left_ = 0; win_rect.top_ = 0; win_rect.wid_ = vec_row_imgs[i].img->width; win_rect.hei_ = vec_row_imgs[i].img->height; line_rect.rectVec_.push_back(win_rect); line_rect_vec.push_back(line_rect); vec_short_row_imgs.push_back(vec_row_imgs[i]); int line_rect_vec_size = line_rect_vec.size(); for (int j = 0; j < line_rect_vec_size; j++) { merge_rect_vec.push_back(line_rect_vec[j]); } } } std::vector<SSeqLEngLineInfor> line_infor_vec; line_infor_vec.resize(merge_rect_vec.size()); _m_recg_line_num = 0; for (int i = 0; i < merge_rect_vec.size(); i++) { _m_recg_line_num += merge_rect_vec[i].rectVec_.size(); } // 2. recognize using batch ((CSeqLAsiaWordReg*)recog_processor)->set_candidate_num(_m_recg_cand_num); ((CSeqLAsiaWordReg*)recog_processor)->set_resnet_strategy_flag(_m_resnet_strategy_flag); ((CSeqLAsiaWordReg*)recog_processor)->recognize_line_batch(vec_short_row_imgs,\ merge_rect_vec, line_infor_vec); // 3. decode row by row out_line_vec.clear(); for (unsigned int i = 0; i < line_infor_vec.size(); i++) { if (_m_debug_line_index != -1 && _m_debug_line_index != i) { continue ; } CSeqLAsiaLineBMSSWordDecoder * line_decoder = new CSeqLAsiaLineBMSSWordDecoder; //line_decoder->setWordLmModel(_m_eng_search_recog_chn, _m_inter_lm_chn); SSeqLEngLineInfor out_line; line_decoder->set_save_low_prob_flag(_m_save_low_prob_flag); line_decoder->set_resnet_strategy_flag(_m_resnet_strategy_flag); out_line = line_decoder->decode_line(recog_processor, line_infor_vec[i]); delete line_decoder; if (long_line_id_vec.size() > 0) { short_line_vec.push_back(out_line); } else { out_line_vec.push_back(out_line); } } //merge the long line if (long_line_id_vec.size() > 0) { int long_line_vec_idx = 0; int short_line_vec_idx = 0; while (long_line_vec_idx < long_line_id_vec.size() || short_line_vec_idx < short_line_vec.size()) { if (long_line_vec_idx < long_line_id_vec.size()) { int long_line_id = long_line_id_vec[long_line_vec_idx]; while (out_line_vec.size() < long_line_id && \ short_line_vec_idx < short_line_vec.size()) { out_line_vec.push_back(short_line_vec[short_line_vec_idx++]); } out_line_vec.push_back(long_line_res_vec[long_line_vec_idx++]); } else { while (short_line_vec_idx < short_line_vec.size()) { out_line_vec.push_back(short_line_vec[short_line_vec_idx++]); } } } } // merge the result of the same row int out_line_vec_size = out_line_vec.size(); for (unsigned int i = 0; i < out_line_vec_size; i++) { std::string str_line_rst = ""; for (unsigned int j = 0; j < out_line_vec[i].wordVec_.size(); j++) { str_line_rst += out_line_vec[i].wordVec_[j].wordStr_; } out_line_vec[i].lineStr_ = str_line_rst; //std::cout << "final_res: " << out_line_vec[i].lineStr_ << std::endl; } return ; } void CSeqModelChBatch::recognize_line_col_chn( const std::vector<st_batch_img> &vec_col_imgs,\ CSeqLAsiaWordReg *recog_processor, std::vector<SSeqLEngLineInfor> &out_line_vec) { if (vec_col_imgs.size() <= 0) { return ; } std::vector<st_batch_img> vec_rotate_imgs; std::vector<CvRect> vec_dect_rect; for (unsigned int i = 0; i < vec_col_imgs.size(); i++) { if (_m_debug_line_index != -1 && _m_debug_line_index !=i) { continue ; } // 2.rotate the cropped image patch IplImage* rot_col_img = rotate_image(vec_col_imgs[i].img, 90, false); int flag = g_ini_file->get_int_value( "DRAW_COL_ROTATE_FLAG", IniFile::_s_ini_section_global); if (flag == 1) { char save_path[256]; snprintf(save_path, 256, "./temp/%s-%d.jpg", g_pimage_title, i); cvSaveImage(save_path, rot_col_img); } st_batch_img batch_img; batch_img.img = rot_col_img; batch_img.bg_flag = vec_col_imgs[i].bg_flag; vec_rotate_imgs.push_back(batch_img); CvRect dect_rect; int dect_w = vec_col_imgs[i].img->width; int dect_h = vec_col_imgs[i].img->height; dect_rect = cvRect(0, 0, dect_w, dect_h); vec_dect_rect.push_back(dect_rect); } std::vector<SSeqLEngLineInfor> out_col_line_vec; recognize_line_row_chn(vec_rotate_imgs, recog_processor, out_col_line_vec); // 5.convert the result to get the position in the orginal image std::vector<SSeqLEngLineInfor> rot_out_col_line_vec; rotate_col_recog_rst(out_col_line_vec, vec_dect_rect, rot_out_col_line_vec); for (int j = 0; j < rot_out_col_line_vec.size(); j++) { out_line_vec.push_back(rot_out_col_line_vec[j]); } // free the memory for (int i = 0; i < vec_rotate_imgs.size(); i++) { if (vec_rotate_imgs[i].img) { cvReleaseImage(&vec_rotate_imgs[i].img); vec_rotate_imgs[i].img = NULL; } } return ; } // process the recognition result of the column image void CSeqModelChBatch::rotate_col_recog_rst(std::vector<SSeqLEngLineInfor> in_col_line_vec, std::vector<CvRect> dect_rect_vec, std::vector<SSeqLEngLineInfor> &out_col_line_vec) { out_col_line_vec = in_col_line_vec; for (int line_idx = 0; line_idx < in_col_line_vec.size(); line_idx++) { out_col_line_vec[line_idx].left_ = dect_rect_vec[line_idx].x; out_col_line_vec[line_idx].top_ = dect_rect_vec[line_idx].y; out_col_line_vec[line_idx].wid_ = dect_rect_vec[line_idx].width; out_col_line_vec[line_idx].hei_ = dect_rect_vec[line_idx].height; for (int i = 0; i < in_col_line_vec[line_idx].wordVec_.size(); i++) { SSeqLEngWordInfor in_word = in_col_line_vec[line_idx].wordVec_[i]; SSeqLEngWordInfor& out_word = out_col_line_vec[line_idx].wordVec_[i]; out_word.wid_ = in_word.hei_; out_word.hei_ = in_word.wid_; out_word.left_ = in_word.top_ + dect_rect_vec[line_idx].x; int shift_y = (int)(out_word.hei_ * 0.25); out_word.top_ = std::max(in_word.left_ + dect_rect_vec[line_idx].y - shift_y, 0); } } return ; } }; /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
6e9982d18c721a759f2ccb02e7a7aa6784b27682
4031667e7a2068314d2be3ae4e9d3f897f42b314
/code-make/cmake/use_boost/boost.cpp
34682b48c76cddb48c0911cc164589d27f701bff
[]
no_license
xeonye/kb
c04d4bebf215466a5dc887b18b1b48a6d336ed09
80d3a09ba45f6a0dd04114412ae3e962a5868097
refs/heads/master
2020-12-06T00:42:35.289305
2020-01-06T22:02:21
2020-01-06T22:02:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
775
cpp
boost.cpp
#include <iostream> #include <cstring> #include <vector> #include <fstream> #include <bitset> #include <boost/lexical_cast.hpp> #include <regex> #include <gmock/gmock.h> // g++ -g -std=c++0x t_override.cpp using namespace std; // ={========================================================================= // string-pos TEST(Boost, BooxtLexicalCast) { EXPECT_THAT(boost::lexical_cast<std::string>(11), "11"); EXPECT_THAT(boost::lexical_cast<std::string>(3301), "3301"); EXPECT_THAT(boost::lexical_cast<int>("11"), 11); EXPECT_THAT(boost::lexical_cast<int>("3301"), 3301); } // ={========================================================================= int main(int argc, char **argv) { testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); }
4a34a3d331867946cf740a4015f27365e1974da1
f1122a0708d9250944cfd380c439c7e70fcf605b
/src/product.h
0dc6a9972f7964e2624bb2c29f201fffbc372eb1
[]
no_license
alexoff13/HashTable
c7a89af32eb94a5e4805e9a3b2c32b2f9bdb0847
a322173f9e51a525230d9e23f72de922392b890f
refs/heads/main
2023-03-26T07:58:07.689789
2021-03-22T11:57:01
2021-03-22T11:57:01
347,633,662
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
h
product.h
#ifndef HASH_TABLE_PRODUCT_H #define HASH_TABLE_PRODUCT_H #include <utility> #include "iostream" #include "string" using namespace std; class product { public: string name; unsigned long barcode; string dateOfPurchase; string dateOfExpiration; product(string Name, unsigned long Barcode, string DateOfPurchase, string DateOfExpiration) { this->name = std::move(Name); this->barcode = Barcode; this->dateOfPurchase = std::move(DateOfPurchase); this->dateOfExpiration = std::move(DateOfExpiration); } friend std::ostream &operator<<(std::ostream &out, const product &product) { // out << "Product: " << product.name << "\nКуплен: " << product.dateOfPurchase << "\nГоден до: " // << product.dateOfExpiration << "\nШтрихкод: " << product.barcode << "\n"; out << "Product: " << product.name << " Куплен: " << product.dateOfPurchase << " Годен до: " << product.dateOfExpiration << " Штрихкод: " << product.barcode << "\n"; return out; } friend bool operator==(const product &a, const product &b) { return b.name == a.name && b.barcode == a.barcode && b.dateOfPurchase == a.dateOfPurchase && b.dateOfExpiration == a.dateOfExpiration; } }; #endif //HASH_TABLE_PRODUCT_H
6b8016d6cf6c1a28aa44889f066710873671c4d5
1a90ec74dc103a89c6696e4985cc5821ed9fbbca
/thrift/gen-cpp/adserver_types.h
007e8721c09a8f3bb7aedb2c9f161edb4e6e234d
[]
no_license
baodier/advertise_lab
24801590535be49ad2b92089cbec42bb820f2f50
e4aa5aaefde8a0d7a820af8a0db4999331498908
refs/heads/master
2016-09-06T09:18:45.419273
2015-01-18T16:04:30
2015-01-18T16:04:30
28,140,628
0
1
null
null
null
null
UTF-8
C++
false
true
2,136
h
adserver_types.h
/** * Autogenerated by Thrift Compiler (0.9.2) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #ifndef adserver_TYPES_H #define adserver_TYPES_H #include <iosfwd> #include <thrift/Thrift.h> #include <thrift/TApplicationException.h> #include <thrift/protocol/TProtocol.h> #include <thrift/transport/TTransport.h> #include <thrift/cxxfunctional.h> class ad_info; typedef struct _ad_info__isset { _ad_info__isset() : os(false), browser(false), region(false), hour(false), searchWord(false) {} bool os :1; bool browser :1; bool region :1; bool hour :1; bool searchWord :1; } _ad_info__isset; class ad_info { public: static const char* ascii_fingerprint; // = "C18AD26BF3FFAD5198DC3D25D5D7A521"; static const uint8_t binary_fingerprint[16]; // = {0xC1,0x8A,0xD2,0x6B,0xF3,0xFF,0xAD,0x51,0x98,0xDC,0x3D,0x25,0xD5,0xD7,0xA5,0x21}; ad_info(const ad_info&); ad_info& operator=(const ad_info&); ad_info() : os(), browser(), region(), hour(0), searchWord() { } virtual ~ad_info() throw(); std::string os; std::string browser; std::string region; int32_t hour; std::string searchWord; _ad_info__isset __isset; void __set_os(const std::string& val); void __set_browser(const std::string& val); void __set_region(const std::string& val); void __set_hour(const int32_t val); void __set_searchWord(const std::string& val); bool operator == (const ad_info & rhs) const { if (!(os == rhs.os)) return false; if (!(browser == rhs.browser)) return false; if (!(region == rhs.region)) return false; if (!(hour == rhs.hour)) return false; if (!(searchWord == rhs.searchWord)) return false; return true; } bool operator != (const ad_info &rhs) const { return !(*this == rhs); } bool operator < (const ad_info & ) const; uint32_t read(::apache::thrift::protocol::TProtocol* iprot); uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const; friend std::ostream& operator<<(std::ostream& out, const ad_info& obj); }; void swap(ad_info &a, ad_info &b); #endif
024fbf2b100036441b6b5d4cb64703c10ffd53b9
0d593477c06b373039a39a7a1de1d7a13edab2c1
/OOPS/cpp/negative and positive no.cpp
a2f77509d408ed3f1b2674d2303474cd2fb18635
[]
no_license
sartajroshan/aptitude-problem
47f8346d244bd631b924c036fc0d4c37f16d6ad8
76d04219f62e31ed8c5c1e127c3a0a2904974c87
refs/heads/main
2023-08-22T21:41:58.273081
2021-10-25T09:13:33
2021-10-25T09:13:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,071
cpp
negative and positive no.cpp
/* Write C++ program to store set of negative and positive numbers using linked list. Write functions to a) Insert numbers b) Delete nodes with negative numbers c) Create two more linked lists using this list, one containing all positive numbers and other containing negative numbers d) For two lists that are sorted; Merge these two lists into third resultant list that is sorted */ #include<iostream> using namespace std; struct node { int num; node *next; }; class numbers { public: node *head,*head1,*head2; numbers() { head=NULL; head1=NULL; head2=NULL; } void create(); void display(node *); void insert(); void sort(node *); void display2(); void remove(); void seperate(); void merge(); }; void numbers::create() { node *current,*new_node; char c; cout<<"\n------------CREATION OF NUMBERS LIST-------------\n\n "; do { new_node=new node; cout<<"\n Enter the no: \n "; cin>>new_node->num; new_node->next=NULL; if(head==NULL) { head=new_node; current=new_node; } else { current->next=new_node; current=new_node; } cout<<"\nDo you want to add new member "; cin>>c; }while(c!='n'); } void numbers::seperate() { node *temp,*current1,*current2,*n1,*n2; temp=head; while(temp!=NULL) { if((temp->num)<0) { n1=new node; n1->num=temp->num; n1->next=NULL; if(head1==NULL) { current1=n1; head1=n1; } else { current1->next=n1; current1=n1; } } else if((temp->num)>=0) { n2=new node; n2->num=temp->num; n2->next=NULL; if(head2==NULL) { current2=n2; head2=n2; } else { current2->next=n2; n2->next=NULL; current2=n2; } } temp=temp->next; } } void numbers::display(node *head) { node *p; p=head; if(p==NULL) { cout<<"\nThe list is Empty"; } else { while(p!=NULL) { cout<<p->num<<"\t"; p=p->next; } } } void numbers::sort(node *head_d) { node *temp1,*temp2,*temp3; temp1 = head_d; for( ;temp1->next!=NULL;temp1=temp1->next) { for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next) { if(temp1->num>temp2->num) { int temp= temp1->num; temp1->num = temp2->num; temp2->num = temp; } } } temp3 = head_d; while (temp3!=NULL) { cout<<"\t"<< temp3->num; temp3 =temp3->next; } } void numbers::merge() { node *temp; temp=head1; while(temp->next!=NULL) { temp=temp->next; } temp->next=head2; } void numbers::insert() { node *p,*temp; p=new node; cout<<"\n\n Enter New Number to be insert : "; cin>>p->num; p->next=NULL; temp=head; while(temp->next!=NULL) { temp=temp->next; } temp->next=p; } int main() { numbers n; n.create(); cout<<"\n \nTHE LIST OF +VE AND -VE NUMBERS IS: \n"; n.display(n.head); n.insert(); cout<<"\n \nTHE LIST AFTER INSERTION IS: \n"; n.display(n.head); n.seperate(); cout<<"\n\n THE LIST OF ONLY -VE NUMBERS IS: \n"; n.display(n.head1); cout<<"\n\n THE LIST OF ONLY +VE NUMBERS IS: \n"; n.display(n.head2); cout<<"\n\n THE LIST OF ONLY SORTED -VE NUMBERS IS : \n"; n.sort(n.head1); cout<<"\n\n THE LIST OF ONLY SORTED +VE NUMBERS IS : \n"; n.sort(n.head2); n.merge(); cout<<"\n AFTER MERGE .....THE LIST IS AS FOLLOWS: \n"; n.display(n.head1); cout<<"\n\n THE LIST OF SORTED +VE AND -VE NUMBERS IS : \n\n"; n.display(n.head1); return 0; }
a4476732348d009b454bf5d3b99a0f0b67d53886
a8f78b56beed85650593f7aa82ce6de74b8ff518
/ghost_original.h
49bb8b1982ebaee7ca8bfea39552f28837f209b2
[]
no_license
Chialiang86/Two-Player-Pacman-Game
12a839c3886c4ff9502d24200c1ef594714f1348
7d0d9dddfc891d3741c8705e17d2ba1f4a189cf9
refs/heads/master
2022-04-19T01:02:21.491023
2020-02-14T10:04:16
2020-02-14T10:04:16
240,476,748
1
0
null
null
null
null
UTF-8
C++
false
false
823
h
ghost_original.h
#ifndef GHOST_ORIGINAL_H #define GHOST_ORIGINAL_H //This is a virtual class #include <QWidget> #include <QLabel> #include <QPixmap> #include <QTimer> #include <cstdlib> #include <iostream> #include "map_info.h" using namespace map_info; using namespace std; class ghost_original : public QWidget { Q_OBJECT public: ghost_original(QWidget *,const int [],const int [],ghost_key); QLabel * ghost_label; QTimer * act_timer; QPixmap ghost_img[2]; const ghost_key ghost_color; int map_xpos[map_info::map_width]; int map_ypos[map_info::map_height]; int ghost_row; int ghost_col; int ghost_x; int ghost_y; int ghost_xpos; int ghost_ypos; int ghost_act_index; virtual void move_method() = 0; public slots: void ghost_act(); signals: }; #endif // GHOST_H
e80d5422c166114d3dba5759854d9530e079a90c
ba24159ef4ad85aaf3606e1cdc4f7810f60a6024
/mesh.h
2b4ccc898656286a8642639ec649c5f77dbbe609
[]
no_license
HindrikStegenga/WMCS006-ACG-PN-Quads
1c4f0f1448303c034e6e5978dac2cf95c878f8da
5107859e98cd216e178575b838840ba5ce882257
refs/heads/main
2023-02-13T01:50:53.804304
2021-01-18T14:44:21
2021-01-18T14:44:21
312,584,820
0
0
null
null
null
null
UTF-8
C++
false
false
2,598
h
mesh.h
#ifndef MESH_H #define MESH_H #include <QVector> #include "patch.h" #include "vertex.h" #include "face.h" #include "halfedge.h" #include "objfile.h" //#define MAX_INT ((unsigned int) -1) class Mesh { public: Mesh(); Mesh(OBJFile *loadedOBJFile); ~Mesh(); inline QVector<Vertex>& getVertices() { return vertices; } inline QVector<HalfEdge>& getHalfEdges() { return halfEdges; } inline QVector<Face>& getFaces() { return faces; } inline QVector<QVector3D>& getLimitCoords() { return limitCoords; } inline QVector<QVector3D>& getVertexCoords() { return vertexCoords; } inline QVector<QVector3D>& getVertexNorms() { return vertexNormals; } inline QVector<QVector3D>& getLimitNorms() { return limitNormals; } inline QVector<unsigned int>& getPolyIndices() { return polyIndices; } inline QVector<unsigned int>& getBsplineTessPatchIndices() { return bsplineTessPatchIndices; } inline QVector<unsigned int>& getPnQuadTessPatchIndices() { return pnquadTessPatchIndices; } void setTwins(unsigned int numHalfEdges, unsigned int indexH, QVector<QVector<unsigned int>>& potentialTwins); QVector3D facePoint(Face* firstEdge); QVector3D edgePoint(HalfEdge* firstEdge, QVector<Vertex>& newVertices); QVector3D vertexPoint(HalfEdge* firstEdge, QVector<Vertex>& newVertices); void subdivideLoop(Mesh& mesh); void extractAttributes(); void setFaceNormal(Face* currentFace); QVector3D computeVertexNormal(Vertex* currentVertex); QVector3D computeLimitNormal(Vertex* currentVertex); // For debugging void dispVertInfo(unsigned short vertIndex); void dispHalfEdgeInfo(unsigned short edgeIndex); void dispFaceInfo(unsigned short faceIndex); void static computeLimitMesh(Mesh& mesh); void static computeQuadPatches(Mesh& mesh); inline int bsplinePatchCount() { return bsplineTessPatches.size(); }; inline int pnQuadPatchCount() { return pnQuadTessPatches.size(); }; void subdivideCatmullClark(Mesh& mesh); void splitHalfEdges(QVector<Vertex>& newVertices, QVector<HalfEdge>& newHalfEdges); private: QVector<Vertex> vertices; QVector<Face> faces; QVector<HalfEdge> halfEdges; QVector<QVector3D> vertexCoords; QVector<QVector3D> limitCoords; QVector<QVector3D> limitNormals; QVector<QVector3D> vertexNormals; QVector<unsigned int> polyIndices; QVector<QuadPatchWithNeighbourhood> bsplineTessPatches; QVector<QuadPatch> pnQuadTessPatches; QVector<unsigned int> bsplineTessPatchIndices, pnquadTessPatchIndices; }; #endif // MESH_H
da924ba6aa08574df88b4d8e734e08ad8135402a
6d61c703a8bf21504d81eea52f889aa31fea1a02
/cc_include/constants.hpp
726609e833b103b9d6052c0b16610d22d2129102
[ "MIT" ]
permissive
pit-ray/TxEditorCCTool
28eeb901c46e6bc63ea2a876801d82648786bcf8
903180082db5ddc80009608e46630f6cfc026eaf
refs/heads/master
2021-04-17T08:48:40.177079
2020-08-25T02:39:38
2020-08-25T02:39:38
249,430,605
0
0
null
null
null
null
UTF-8
C++
false
false
2,612
hpp
constants.hpp
#ifndef CONSTANTS_HPP #define CONSTANTS_HPP #include <type_traits> //enum classを範囲forで扱えるようにするマクロ #define GENERATE_ENUM_ITERATOR(ENUM_T)\ inline ENUM_T operator ++( ENUM_T& x ) { return x = static_cast<ENUM_T>( std::underlying_type<ENUM_T>::type( x ) + 1 ) ; }\ inline ENUM_T operator *( ENUM_T x ) { return x ; }\ inline ENUM_T begin( ENUM_T ) { return static_cast<ENUM_T>( 0 ) ; }\ inline ENUM_T end( ENUM_T ) { return static_cast<ENUM_T>( std::underlying_type<ENUM_T>::type( ENUM_T::iterator_end ) + 1 ) ; } enum class CCItems : int { /* * 読み込み時のとき、類似するものには別で入れる。 * 連続するもので、データが一つの場合、色をどんどん薄くする手法をとる。 * */ //文字関係 TEXT, BACK, SEL_TEXT, SEL_BACK, LINE_END, EOF_MK, TAB, HALF_SPACE, FULL_SPACE, LINK, QUOTE, BRACKET, NUMBER, //行や列 CURRENT_BACK, CURRENT_UNDER, CURRENT_COLUMN, EVEN_LINE_BACK, RAP_LINE, DIGIT_LINE, LINE_NUM, LINE_NUM_CHANGED, RULER, CURSOR, CURSOR_IME, NOTE_LINE, //その他 CTRL_CODE, HERE_DOC, DIFF_ADD, DIFF_CHANGE, DIFF_DELETE, BOOK_MARK, MINI_MAP, //多数項目 FIND_STR, FIND_STR1, FIND_STR2, FIND_STR3, FIND_STR4, FIND_STR5, KEYWORD1, KEYWORD2, KEYWORD3, KEYWORD4, KEYWORD5, KEYWORD6, KEYWORD7, KEYWORD8, KEYWORD9, KEYWORD10, REGEX1, REGEX2, REGEX3, REGEX4, REGEX5, REGEX6, REGEX7, REGEX8, REGEX9, REGEX10, //コーディング系 SQ_STR, DQ_STR, ASP_XML, TAG, OPTION, SECTION, KEY, LABEL, COMMENT, //Info size, iterator_end = COMMENT, error = -1, } ; GENERATE_ENUM_ITERATOR( CCItems ) ; enum class CCOpts : int { BOLD, CASE, SHOW, UNDER, size, iterator_end = UNDER, error = -1, } ; GENERATE_ENUM_ITERATOR( CCOpts ) ; enum class CCLangs : int { COMMON, HTML, PERL, PHP, CSS, RUBY, INI, BAT, CPP, JAVA, JS, VB, HSP, DELPHI, size, ALL, //全ての言語に対して行う iterator_end = DELPHI, error = -1, } ; GENERATE_ENUM_ITERATOR( CCLangs ) ; enum class CCTextEditor : int { TeraPad, Sakura, size, error = -1, } ; enum class ColorType : int { NONE, OWN, MAIN, SUB, PALE, size, iterator_end = PALE, error = -1, } ; #endif
4a4ea6e158b03b7f3d630cf6abb5c62c9052a694
e25326f06d3c20a89095dc446f09f99a52632e0a
/Lab3/gui.h
323f62b24c5c19f033ef8bccea83490dc9bb11b3
[]
no_license
Cvelth/university_probability_theory_project
e64c3db8630b66a2327c33d7eaec1db7071356fa
7a06961892bbf11c6b1cfdcfba13e68ddfcfdc3f
refs/heads/master
2021-06-10T15:16:58.790853
2016-12-13T07:59:04
2016-12-13T07:59:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
274
h
gui.h
#ifndef GUI_H #define GUI_H #include "ui_gui.h" #include "Graphs.hpp" class GUI : public QWidget { Q_OBJECT public: GUI(QWidget *parent = 0); ~GUI(); protected slots: void refresh(); void setData(Data d); private: Graphs* c; Ui::GUIClass ui; }; #endif // GUI_H
2e5e24fd133b7659febefe1de0ecb7d569bc1dba
9d2f0d0220ddd28281c14f4bd74d23875c079a91
/include/RadonFramework/Core/Pattern/Event.hpp
975fbf6f47e203ae0ad97a7d8c9b2757713b36fa
[ "Apache-2.0" ]
permissive
tak2004/RadonFramework
4a07b217aa2b5e27a6569f6bb659ac4aec7bdca7
e916627a54a80fac93778d5010c50c09b112259b
refs/heads/master
2021-04-18T23:47:52.810122
2020-06-11T21:01:50
2020-06-11T21:01:50
17,737,460
3
1
null
2015-12-11T16:56:34
2014-03-14T06:29:16
C++
UTF-8
C++
false
false
5,167
hpp
Event.hpp
#ifndef RF_CORE_PATTERN_EVENT_HPP #define RF_CORE_PATTERN_EVENT_HPP #if _MSC_VER > 1000 #pragma once #endif #include <RadonFramework/Collections/List.hpp> #include <RadonFramework/Core/Pattern/Delegate.hpp> namespace RadonFramework::Core::Pattern { class IObserver; template <typename _ARGU = const IObserver*> class Event; template <typename CONAP = const IObserver*> class EventConnection { friend class IObserver; public: using DefaultMethod = typename Delegate1<void(CONAP)>; ~EventConnection(); DefaultMethod Method(); void operator()(CONAP Arg) const; void AddEvent(Event<>* Obj); void RemoveEvent(Event<>* Obj); private: DefaultMethod m_Method; RF_Collect::List<Event<>*> m_Events; EventConnection(DefaultMethod Method); }; class IObserver { protected: RF_Collect::List<EventConnection<>*> m_Connections; public: template <class T, typename AP> EventConnection<AP>* Connector(void (T::*Method)(AP)); virtual ~IObserver(); }; template <typename _ARGU> class Event { protected: RF_Collect::List<EventConnection<_ARGU>*> m_EventHandler; public: ~Event(); void Attach(EventConnection<_ARGU>* ConnectionHandler); void Detach(EventConnection<_ARGU>* ConnectionHandler); void ConnectionRemoved(EventConnection<_ARGU>* ConnectionHandler); void Notify(_ARGU Arg); void operator()(_ARGU Arg); Event& operator+=(EventConnection<_ARGU>* Con); Event& operator-=(EventConnection<_ARGU>* Con); }; template <typename CONAP /*=const IObserver**/> EventConnection<CONAP>::EventConnection(DefaultMethod Method) : m_Method(Method) { } template <typename CONAP /*=const IObserver**/> EventConnection<CONAP>::~EventConnection() { for(typename RF_Collect::List<Event<>*>::Iterator it = m_Events.Begin(); it != m_Events.End(); ++it) { reinterpret_cast<Event<CONAP>*>(*it)->ConnectionRemoved(this); } } template <typename CONAP /*=const IObserver**/> typename EventConnection<CONAP>::DefaultMethod EventConnection<CONAP>::Method() { return m_Method; } template <typename CONAP /*=const IObserver**/> void EventConnection<CONAP>::operator()(CONAP Arg) const { m_Method(Arg); } template <typename CONAP /*=const IObserver**/> void EventConnection<CONAP>::AddEvent(Event<>* Obj) { for(typename RF_Collect::List<Event<>*>::Iterator it = m_Events.Begin(); it != m_Events.End(); ++it) if((void*)*it == (void*)Obj) return; m_Events.AddLast(Obj); } template <typename CONAP /*=const IObserver**/> void EventConnection<CONAP>::RemoveEvent(Event<>* Obj) { for(typename RF_Collect::List<Event<>*>::Iterator it = m_Events.Begin(); it != m_Events.End();) { if(reinterpret_cast<void*>(*it) == reinterpret_cast<void*>(Obj)) { m_Events.Remove(it); return; } } } template <class T, typename AP> EventConnection<AP>* IObserver::Connector(void (T::*Method)(AP)) { Delegate1<void(AP)> delegate(static_cast<T*>(this), Method); EventConnection<AP>* con = new EventConnection<AP>(delegate); m_Connections.AddLast((EventConnection<>*)con); return con; } template <typename _ARGU> Event<_ARGU>::~Event() { for(typename RF_Collect::List<EventConnection<_ARGU>*>::Iterator it = m_EventHandler.Begin(); it != m_EventHandler.End();) { (*it)->RemoveEvent((Event<>*)this); m_EventHandler.Remove(it); } } template <typename _ARGU> void Event<_ARGU>::Attach(EventConnection<_ARGU>* ConnectionHandler) { m_EventHandler.AddLast((EventConnection<_ARGU>*)ConnectionHandler); ConnectionHandler->AddEvent(reinterpret_cast<Event<>*>(this)); } template <typename _ARGU> void Event<_ARGU>::Detach(EventConnection<_ARGU>* ConnectionHandler) { for(typename RF_Collect::List<EventConnection<_ARGU>*>::Iterator it = m_EventHandler.Begin(); it != m_EventHandler.End();) if((void*)*it == (void*)ConnectionHandler) { ConnectionHandler->RemoveEvent((Event<>*)this); m_EventHandler.Remove(it); return; } } template <typename _ARGU> void Event<_ARGU>::ConnectionRemoved(EventConnection<_ARGU>* ConnectionHandler) { for(typename RF_Collect::List<EventConnection<_ARGU>*>::Iterator it = m_EventHandler.Begin(); it != m_EventHandler.End();) { if(reinterpret_cast<void*>(*it) == reinterpret_cast<void*>(ConnectionHandler)) { m_EventHandler.Remove(it); return; } } } template <typename _ARGU> void Event<_ARGU>::Notify(_ARGU Arg) { for(typename RF_Collect::List<EventConnection<_ARGU>*>::Iterator it = m_EventHandler.Begin(); it != m_EventHandler.End(); ++it) { (*(*it))(Arg); } } template <typename _ARGU> void Event<_ARGU>::operator()(_ARGU Arg) { Notify(Arg); } template <typename _ARGU> Event<_ARGU>& Event<_ARGU>::operator+=(EventConnection<_ARGU>* Con) { Attach(Con); return *this; } template <typename _ARGU> Event<_ARGU>& Event<_ARGU>::operator-=(EventConnection<_ARGU>* Con) { Detach(Con); return *this; } } // namespace RadonFramework::Core::Pattern #ifndef RF_SHORTHAND_NAMESPACE_PATTERN #define RF_SHORTHAND_NAMESPACE_PATTERN namespace RF_Pattern = RadonFramework::Core::Pattern; #endif #endif
c550bc78ab635d8403ef14558eb88e98be0920bc
bb46956c0e7d1c7076ccddab9d3fcb1749bc36ed
/Decorator/Decorator.cpp
2deb1f1eb2efb1a131bdf9c886c0287a6fcc38f0
[]
no_license
64Teenage/Design-Pattern-Cpp
32e9b4937c0c714e031b2af47b7bd81a5c59faf0
fcf17c1b4092f6470cc581a92f6acc8e7fe57706
refs/heads/master
2020-04-04T10:26:29.613667
2018-12-11T14:11:28
2018-12-11T14:11:28
155,855,052
0
0
null
null
null
null
UTF-8
C++
false
false
1,599
cpp
Decorator.cpp
#include <iostream> #include <string> using std::string; using std::cout; using std::endl; class Component { public: virtual string getDescription() = 0; }; class ConcreteComponent : public Component { private: string m_strDescription; public: ConcreteComponent(string strDescription) : m_strDescription(strDescription){} string getDescription() { return m_strDescription; } }; class Decorator : public Component { protected: Component * m_pComponent; public: Decorator(Component * component) : m_pComponent(component){} virtual string getDescription() = 0; }; class ConcreteDecoratorOne : public Decorator { public: ConcreteDecoratorOne(Component * component) : Decorator(component){} string getDescription() { return m_pComponent->getDescription() + " ConcreteDecoratorOne "; } }; class ConcreteDecoratorTwo : public Decorator { public: ConcreteDecoratorTwo(Component * component) : Decorator(component){} string getDescription() { return m_pComponent->getDescription() + " ConcreteDecoratorTwo "; } }; int main() { Component * pComponent = new ConcreteComponent("Conponent"); std::cout<<pComponent->getDescription()<<std::endl; Component * pComponentOne = new ConcreteDecoratorOne(pComponent); std::cout<<pComponentOne->getDescription()<<std::endl; Component * pComponentTwo = new ConcreteDecoratorTwo(pComponentOne); std::cout<<pComponentTwo->getDescription()<<std::endl; delete pComponentTwo; delete pComponentOne; delete pComponent; return 0; }
3f37e2341a7525904af51de83c2355cf7d395b09
0c0ef0973bc1a95fdff27509cc89138b78ef6aff
/crypt_crt/SRC/crt_math.cpp
57d595c6a39034fc47c94e694383cf32fd8cec98
[]
no_license
notphage/crypt_mc
b1e6ef0357bd56136968fd4f703615031239f97e
d9a11b0bfdf28ab73b5c6fb3c83010700c7bf70d
refs/heads/master
2023-03-12T20:31:52.289724
2020-05-18T01:19:12
2020-05-18T01:19:12
192,854,438
1
0
null
null
null
null
UTF-8
C++
false
false
1,940
cpp
crt_math.cpp
template <typename T> T abs_template(T t) { return t > (T)0 ? t : -t; } float fabs(float f) { return abs_template<float>(f); } extern "C" float copysignf(float x, float y) { return y == 0.f ? fabs(x) : fabs(x) * y / fabs(y); } extern "C" double log2(double a) { union { double d; long long x; } u = { a }; return (u.x - 4607182418800017409) * 1.539095918623324e-16; /* 1 / 6497320848556798.0; */ } typedef union { float value; unsigned int word; } ieee_float_shape_type; /* Get a 32 bit int from a float. */ # define GET_FLOAT_WORD(i,d) \ do { \ ieee_float_shape_type gf_u; \ gf_u.value = (d); \ (i) = gf_u.word; \ } while (0) /* Set a float from a 32 bit int. */ #define SET_FLOAT_WORD(d, i) \ do { \ ieee_float_shape_type sf_u; \ sf_u.word = (i); \ (d) = sf_u.value; \ } while (0) extern "C" float roundf(float x) { int signbit; unsigned int w; /* Most significant word, least significant word. */ int exponent_less_127; GET_FLOAT_WORD(w, x); /* Extract sign bit. */ signbit = w & 0x80000000; /* Extract exponent field. */ exponent_less_127 = (int)((w & 0x7f800000) >> 23) - 127; if (exponent_less_127 < 23) { if (exponent_less_127 < 0) { w &= 0x80000000; if (exponent_less_127 == -1) /* Result is +1.0 or -1.0. */ w |= ((unsigned int)127 << 23); } else { unsigned int exponent_mask = 0x007fffff >> exponent_less_127; if ((w & exponent_mask) == 0) /* x has an integral value. */ return x; w += 0x00400000 >> exponent_less_127; w &= ~exponent_mask; } } else { if (exponent_less_127 == 128) /* x is NaN or infinite. */ return x + x; else return x; } SET_FLOAT_WORD(x, w); return x; }
b3841b51fe37ac4d9e6fa292032d62555c0c25a1
f9759b3118826bb4787fe8ace58307523763cdfb
/DAY8 B/main.cpp
2b6a07810368653ba6db9d87e2f026ec4edea52d
[]
no_license
Abraham-WH/2017ACMtraining
72eb3ec2d6d6760da22b671c05764db6bb57ed27
048ab6ae3b94b45b771208d2fbcbf16b47ec5c6d
refs/heads/master
2020-04-10T21:11:56.368966
2018-12-11T07:00:28
2018-12-11T07:00:28
161,290,523
0
0
null
null
null
null
UTF-8
C++
false
false
726
cpp
main.cpp
//u = 3 * i can *2,can - 6 * i (3u+i)*2||-6 ==1 #include <iostream> #include <cstring> #include <string> using namespace std; int main() { int testcase; cin>>testcase; while(testcase--) { string p="MI"; int counti=1,countu=0,counti2=0,countu2=0,cm=0,pos=0; string tar; cin>>tar; for(int i=0;i<tar.length();i++) { if(tar[i]=='M') { cm++; } if(tar[i]=='I') { counti2++; } if(tar[i]=='U') { countu2++; } } if( cm==1 && tar[0]=='M'&& (((countu2*3+counti2)%2==0 && (countu2*3+counti2)%3!=0)||(countu2*3+counti2)==1)) { pos=1; } else { pos=0; } if(pos==0) { cout<<"No"<<endl; } else if(pos==1) cout<<"Yes"<<endl; } return 0; }
f2f436091654f802b7b953bfdb8638c49b9074fd
d2241838244257729d5632d1eea423f31279b596
/realtimevaluefortcp.h
e0cee96ea8e7ad37f167965d8508a58f98951f8d
[]
no_license
Myzhencai/HeatControl
38a392e49b47bfba2ad500fae9b3ece0885f56ea
8e1e1d63a0bafb90f872ec7a4e70b67b55a35f3b
refs/heads/master
2023-05-30T01:49:14.362244
2021-06-11T03:55:25
2021-06-11T03:55:25
375,895,746
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
h
realtimevaluefortcp.h
#ifndef REALTIMEVALUEFORTCP_H #define REALTIMEVALUEFORTCP_H #include <QObject> #include <QThread> #include <QByteArray> #include"heatcontrolmenu.h" class RealtimeValueForTCP:public QThread { Q_OBJECT public: RealtimeValueForTCP(); RealtimeValueForTCP(HeatControlMenu* TempMenu,bool Tempvalue):HeatControlMenuPointer(TempMenu),isTruable(Tempvalue){} void run(); ~RealtimeValueForTCP(); public slots: void TCPSetSingleCoceMode();//设置不同的模式 void TCPSetPageCodeMode(); void stop(); void TCPLiveSingleCoceMode();//离开设置模式 void TCPLivePageCodeMode(); void TCPSingleCoceModeisRunningFalse(); void TCPSendAllModeinRunningFalse(); void TCPSendDefualtModeinRunningFalse(); signals: void TCPSingleCoceModeRealTimeValue();//不同运作方式以信号形式传递 void TCPDefaultModeRealTimeValue(); void TCPPageCodeModeRealTimeValue(); private: bool DefaultMode = true; bool SingleCoceMode = false; bool SendAllMode = false; bool isTruable;//用于判定是否创建进程 bool SingleCoceModeinRunning = false; bool SendAllModeinRunning =false; bool DefaultModeinRunning= false; HeatControlMenu* HeatControlMenuPointer; }; #endif // REALTIMEVALUEFORTCP_H
be5679033e37b7d88f202b86b4c5dbca291b9090
bdd4abdeb988eb5f4bdb14af8e720a80df300910
/Shapes.cpp
881762c8724924a89ea6c6a6ebc0cad336b9e0a3
[]
no_license
mdu2017/algorithms-project
d436ee6a0d3885e4d937c9f78fff8dd543541b77
8ba796382ef2aa7a28591b0eeefb46474781074f
refs/heads/master
2020-08-03T03:00:07.361361
2019-10-04T21:21:31
2019-10-04T21:21:31
211,605,815
1
0
null
2019-09-29T05:00:31
2019-09-29T05:00:31
null
UTF-8
C++
false
false
4,668
cpp
Shapes.cpp
/* AUTHORS: Chris Helms * Adam Naumann * Garrett Yero, * Stirling Strafford * Gilbert Tao * ASSIGNMENT TITLE: Pac-Man * ASSIGNMENT DESCIRPTION: Emulates Pac-Man in C++ * DATE CREATED: 11/2/2017 * DUE DATE: 12/4/2017 * DATE LAST MODIFIED: 12/3/2017 */ #include "Shapes.h" Color::Color(int r, int g, int b){ R = r; G = g; B = b; } Point::Point(int m, int n){ x = m; y = n; } double Point::distance(Point p){ return sqrt(pow(x-p.x,2.0)+pow(y-p.y,2.0)); } bool Point::isEqual(Point p){ bool equality = false; if(x == p.x && y == p.y) equality = true; return equality; } Rectangle::Rectangle(Point a, Point b, Color c){ c1 = a; c2 = b; color = c; } void Rectangle::setCorner(Point a, Point b){ c1 = a; c2 = b; return; } void Rectangle::collision(Rectangle hb, bool& up, bool& right, bool& down, bool& left){ if((hb.c1.y > c1.y && hb.c2.y < c2.y) //hit box in middle || (hb.c1.y < c2.y && hb.c2.y > c2.y) //top hit box collide || (hb.c1.y < c1.y && hb.c2.y > c1.y)){ //bottom hit box collide //left side of wall : right side of hit box if(hb.c2.x == c1.x) right = false; //right side of wall : left side of hit box if(hb.c1.x == c2.x) left = false; } if((hb.c1.x > c1.x && hb.c2.x < c2.x) //hit box in middle || (hb.c1.x < c1.x && hb.c2.x > c1.x) //right hit box collide || (hb.c1.x < c2.x && hb.c2.x > c2.x)){ //left hit box collide //top of wall : bottom of hit box if(hb.c2.y == c1.y) down = false; //bottom of wall : top of hit box if(hb.c1.y == c2.y) up = false; } return; } bool Rectangle::collision(Rectangle hb){ bool isCollide = false; if((hb.c1.y > c1.y && hb.c2.y < c2.y) //hit box in middle || (hb.c1.y < c2.y && hb.c2.y > c2.y) //top hit box collide || (hb.c1.y < c1.y && hb.c2.y > c1.y)){ //bottom hit box collide //left & right if((hb.c2.x == c1.x) || (hb.c1.x == c2.x)) {isCollide = true;} } if((hb.c1.x > c1.x && hb.c2.x < c2.x) //hit box in middle || (hb.c1.x < c1.x && hb.c2.x > c1.x) //right hit box collide || (hb.c1.x < c2.x && hb.c2.x > c2.x)){ //left hit box collide //top & bottom if((hb.c2.y == c1.y) || (hb.c1.y == c2.y)) {isCollide = true;} } return isCollide; } void Rectangle::draw(SDL_Plotter& g){ int deltaX = 1, deltaY = 1; int xOffSet = 0; if(c1.x > c2.x) deltaX = xOffSet = -1; if(c1.y > c2.y) deltaY = -1; for(int y = c1.y; y != c2.y; y += deltaY){ for(int x = c1.x; x != c2.x; x += deltaX){ g.plotPixel(x + xOffSet, y, color.R, color.G, color.B); } } return; } Circle::Circle(Point p, double r, Color c){ center = p; radius = r; color = c; } void Circle::draw(SDL_Plotter& g){ for(int x = center.x-radius; x < center.x+radius; x++){ for(int y = center.y-radius; y < center.y+radius; y++){ if(abs(y-center.y) < sqrt(radius*radius-(x-center.x)*(x-center.x))){ g.plotPixel(x, y, color.R, color.G, color.B); } } } return; } Triangle::Triangle(Point p, double sL, Direction d, Color c){ tip = p; sideLength = sL; dir = d; color = c; } void Triangle::draw(SDL_Plotter& g){ double m = tan(PI/6), heigth = sideLength*cos(PI/6); int delta = 1; if(dir == RIGHT || dir == LEFT){ if(dir == LEFT) {delta = -1;} heigth *= delta; for(int dx = 0; abs(dx-heigth) > 1; dx += delta){ for(int dy = -sideLength/2; dy < sideLength/2; dy++){ if(dy < m*dx*delta && dy > -m*dx*delta) {g.plotPixel(tip.x+dx, tip.y+dy, color.R, color.G, color.B);} } } } else if(dir == UP || dir == DOWN){ if(dir == UP) {delta = -1;} m = 1/m; heigth *= delta; for(int dy = 0; abs(dy-heigth) > 1; dy += delta){ for(int dx = -sideLength/2; dx < sideLength/2; dx++){ if(dx < dy/m*delta && dx > -dy/m*delta) {g.plotPixel(tip.x+dx, tip.y+dy, color.R, color.G, color.B);} } } } }
1c919873b5f644e3281184f61922846a39655f76
615e167705a2a7027202aa2f3aac35ecf25df948
/Projects/연습/ConsoleApplication1/ConsoleApplication1/문제3.cpp
0bfc8d9917018b8bd993edd6786997e490f63148
[]
no_license
wkdehdlr/VS-2017
9813efb14274ffd24341cd4de49040ea39020f24
0a6f24971b7c153050b447229800bd61f5d6ad6c
refs/heads/master
2021-08-19T01:51:42.715873
2017-11-24T11:54:04
2017-11-24T11:54:04
110,057,403
0
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
문제3.cpp
#include<iostream> #include<vector> using namespace std; int main() { int x, y; int x1 = 0, y1 = 0, x2 = 0, y2 = 0; int x1n = 0, y1n = 0, x2n = 0, y2n = 0; vector<vector<int> > vec = { {1,4},{3,4},{3,10} }; x1 = vec[0][0]; y1 = vec[0][1]; x1n++; y1n++; for (int i = 1; i < vec.size(); i++) { if (vec[i][0] == x1) { x1n++; } else { x2 = vec[i][0]; x2n++; } if (vec[i][1] == y1) { y1n++; } else { y2 = vec[i][1]; y2n++; } } if (x1n == 1) { x = x1; } else { x = x2; } if (y1n == 1) { y = y1; } else { y = y2; } printf("%d %d\n", x, y); }
879155bee775b9b180ec8f694a5ffa92b09695c1
30871a624da21421ee839ad49a0b6f65f74b80bf
/Lectures Codes/Code (9)/Code/permutations.cpp
6e039f5b98452cbd66d93d751593b4711f220401
[]
no_license
bakurits/Programming-Abstractions
7b15dbe543951e74d543389cb0c37efd4ef07cb2
680a87b3f029fe004355512be70ba822d1cd5ca9
refs/heads/master
2021-01-19T19:14:26.673149
2017-07-19T18:21:16
2017-07-19T18:21:16
88,407,754
0
1
null
null
null
null
UTF-8
C++
false
false
1,677
cpp
permutations.cpp
/* File: permutations.cpp * * A program to list off all permutations of a master set. */ #include <iostream> #include <string> #include "set.h" #include "vector.h" using namespace std; /* This version of the function returns a Vector holding all * permutations of the string. */ Vector<string> permutationsOf(string s); /* This function prints out the permutations of the string one * after another. */ void listPermutationsOf(string s); int main() { listPermutationsOf("UNCOPYRIGHTABLE"); } /* Given a string, returns a Vector holding all permutations * of that string. */ Vector<string> permutationsOf(string s) { Vector<string> result; /* Base case: If there are no characters in the string, the only permutation * of the string is the string itself. */ if (s == "") { result += ""; return result; } /* Recursive step: For each character in the string, try removing that * character, generating all other permutations recursively, then snapping * that string back into place. */ else { for (int i = 0; i < s.length(); i++) { Vector<string> v = permutationsOf(s.substr(0, i) + s.substr(i + 1)); foreach (string permutation in v) { result += s[i] + permutation; } } return result; } } /* Recursive function that lists, but does not process, each string. */ void recListPermutationsOf(string &s, string &soFar) { if (s == "") { cout << soFar << endl; } else { for (int i = 0; i < s.length(); i++) { soFar = soFar + s[i]; s = s.substr(0, i) + s.substr(i + 1); recListPermutationsOf(s, soFar); } } } void listPermutationsOf(string s) { string s1 = ""; recListPermutationsOf(s, s1); }
2ec92863f5829939f3e195b1c944551804a61553
f4173138b361d145422848b937e7c9775ee8aab0
/SP1Framework/PrintCredits.h
2af59974c8f1a5af0641c6ecd04ed29d0ee2bfd2
[]
no_license
theduckhorse/SP1Framework
65d9ea7dc7fd8fecb46e92839b98c5fc724d4cfc
b99fda305c62c7c776c963892d8640982fc42906
refs/heads/master
2022-09-29T08:09:44.308216
2016-09-03T07:13:22
2016-09-03T07:13:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
414
h
PrintCredits.h
#include <iostream> #include "Framework\console.h" #include <time.h> #include "game.h" #include <sstream> #include <vector> //template <size_t size_x, size_t size_y> using namespace std; //Must extern this only extern Console g_Console; //Dont extern here other than g_Console //extern char map[50][150]; void printCredits(int width, int height, int *currentX, int *currentY, double *timer, char map[600][150]);
bbbf59988958e9ec48c4976bb35a5f20990db905
6b53d6ad238c4accd27cf584284b4d6846e56554
/Sources/Pipeline/Assimp/AssimpLoader.h
32d09220cf1b386d077dd78aede6d1c14696a43f
[ "Apache-2.0" ]
permissive
IvanPleshkov/RedLiliumEngine
1dc5f25cabe2c703a648141122cf3482e24b9898
5e7c14d9c750db8054bde53b772e30e3682c2f1d
refs/heads/master
2021-12-31T20:23:17.584013
2019-04-07T14:29:05
2019-04-07T14:29:05
140,816,021
0
0
null
null
null
null
UTF-8
C++
false
false
623
h
AssimpLoader.h
#pragma once #include <Core/Common.h> #include <Render/RenderCommon.h> namespace RED_LILIUM_NAMESPACE { class Entity; class AssimpMaterial; struct AssimpImportOptions { bool optimizeMeshes = false; bool splitMeshes = false; bool generateNormals = true; bool saveCpuMeshes = true; bool generateGpuMeshes = true; bool loadCameras = false; bool loadLights = true; std::function<sptr<Material>(std::string_view)> materialFabric; }; bool LoadSceneByAssimp(ptr<RenderDevice> renderDevice, std::string_view filename, ptr<Entity> rootEntity, const AssimpImportOptions& options); } // namespace RED_LILIUM_NAMESPACE
c5536d38386dfb22fcbfd6e22df0f709597012b0
57410b7bb61e7fb82f0cb949757cb5bba6966e93
/Logic Sim/IC.cpp
86765b191705bf8ecaf9159a1e8e439da6598aca
[ "BSD-3-Clause" ]
permissive
AntonSievering/Logic-Sim
88acb4d9a07f2bb79ec38c7e8416a093a1b8718b
039a4967dccb9d3348eb2480249cdef96d7e4fbc
refs/heads/master
2022-12-09T07:26:54.489945
2020-09-15T13:55:38
2020-09-15T13:55:38
282,175,732
0
0
null
null
null
null
UTF-8
C++
false
false
11,024
cpp
IC.cpp
#include "IC.h" Node::Node() { from = to = nullptr; bCharge = false; posFrom = posTo = 0; olc::Sprite *spr = new olc::Sprite(1, 1); spr->SetPixel(0, 0, olc::BLACK); pBlack = new olc::Decal(spr); spr->SetPixel(0, 0, olc::GREEN); pGreen = new olc::Decal(spr); } Node::Node(IC* from, IC* to, int posFrom, int posTo) { this->from = from; this->to = to; bCharge = false; olc::Sprite *spr = new olc::Sprite(1, 1); spr->SetPixel(0, 0, olc::BLACK); pBlack = new olc::Decal(spr); spr->SetPixel(0, 0, olc::GREEN); pGreen = new olc::Decal(spr); this->posFrom = posFrom; this->posTo = posTo; } Node::~Node() { if (to != nullptr) to->deleteInNode(posTo); if (from != nullptr) from->deleteOutNode(posFrom, this); delete pBlack; delete pGreen; } void Node::Draw(PGEGui* pge) { float fLength = 4.0f * pge->GetZoom(); olc::vf2d posFromNewWorld = from->getOutNodePos(posFrom) + olc::vf2d(4, 4); olc::vf2d posToNewWorld = to->getInNodePos(posTo) + olc::vf2d(3, 4); olc::vf2d posFromNew = pge->WorldToScreen(posFromNewWorld); olc::vf2d posToNew = pge->WorldToScreen(posToNewWorld); posFromNew.x -= 2.0f; posToNew.x += 2.0f; auto _2dCollision = [&](olc::vi2d pos0, olc::vi2d pos1, olc::vi2d pos2, olc::vi2d pos3) { float s1_x, s1_y, s2_x, s2_y; s1_x = pos1.x - pos0.x; s1_y = pos1.y - pos0.y; s2_x = pos3.x - pos2.x; s2_y = pos3.y - pos1.y; float s, t; s = (-s1_y * (pos0.x - pos2.x) + s1_x * (pos0.y - pos2.y)) / (-s2_x * s1_y + s1_x * s2_y); t = (s2_x * (pos0.y - pos2.y) - s2_y * (pos0.x - pos2.x)) / (-s2_x * s1_y + s1_x * s2_y); if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { return 1; } return 0; // No collision }; // Draw if visible if (posFromNew.x < 0 && posToNew.x > 800 && posFromNew.y < 0 && posToNew.y > 800 || posFromNew.x > 0 && posFromNew.x < 800 && posFromNew.y > 0 && posFromNew.y < 800 || posToNew.x > 0 && posToNew.x < 800 && posToNew.y > -fLength && posToNew.y < 800 || !_2dCollision({ 0, 0 }, { 0, 800 }, posFromNew, posToNew) || !_2dCollision({ 0, 800 }, { 800, 800 }, posFromNew, posToNew) || !_2dCollision({ 800, 800 }, { 800, 0 }, posFromNew, posToNew) || !_2dCollision({ 800, 0 }, { 0, 0 }, posFromNew, posToNew)) { // calculate x and y offset from the draw point float fSlope = -(posToNew.x - posFromNew.x) / (posToNew.y - posFromNew.y); float fAngle = atanf(fSlope); float dx = 0.5f * fLength * cosf(fAngle); float dy = 0.5f * fLength * sinf(fAngle); // calculate the four points olc::vf2d pos0 = posFromNew + olc::vf2d(dx, dy); olc::vf2d pos1 = posFromNew - olc::vf2d(dx, dy); olc::vf2d pos2 = posToNew - olc::vf2d(dx, dy); olc::vf2d pos3 = posToNew + olc::vf2d(dx, dy); if (bCharge) pge->DrawWarpedDecal(pGreen, { pos0, pos1, pos2, pos3 }); else pge->DrawWarpedDecal(pBlack, { pos0, pos1, pos2, pos3 }); } } void IC::prepare(olc::vi2d pos) { // Input nodes size_t nStreak = 0; for (int i = 0; i < decIC->sprite->height; i++) { olc::Pixel col = decIC->sprite->GetPixel(0, i); if (col == olc::BLACK) nStreak++; else nStreak = 0; if (nStreak == 4) { nStreak = 0; vInNodesToDraw.push_back(olc::vi2d(pos.x - 4, pos.y - 5 + i)); nInNodes++; vInNames.push_back(""); } } // output nodes nStreak = 0; for (int i = 0; i < decIC->sprite->height; i++) { olc::Pixel col = decIC->sprite->GetPixel(decIC->sprite->width - 1, i); if (col == olc::BLACK) nStreak++; else { if (nStreak == 4) { nStreak = 0; vOutNodesToDraw.push_back(olc::vi2d(pos.x + decIC->sprite->width - 1, pos.y - 6 + i)); nOutNodes++; vOutNames.push_back(""); } nStreak = 0; } } // create the std::vector for the out nodes for (int i = 0; i < nOutNodes; i++) vOutNodes.push_back(std::vector<Node*>()); for (std::vector<Node*>& vNodes : vOutNodes) vNodes.push_back(nullptr); // create the std::vector for the in nodes vInNodes = std::vector<Node*>(); for (int i = 0; i < nInNodes; i++) { vInNodes.push_back(nullptr); } } IC::IC() { decIC = nullptr; nOutNodes = nInNodes = 0; sName = "IC"; sIdentifier = "IC"; } IC::IC(olc::Decal* decIC, olc::vi2d pos, SpriteManager *sm) { this->decIC = decIC; this->pos = pos; nOutNodes = nInNodes = 0; sName = "IC"; sIdentifier = "IC"; load_sprites("", sm); prepare(pos); } IC::IC(std::string sFilename, olc::vi2d pos, SpriteManager *sm) { this->pos = pos; nOutNodes = nInNodes = 0; sName = "IC"; load_sprites("", sm); prepare(pos); } IC::~IC() { } void IC::deleteInNode(int nNodeIdx) { if (nNodeIdx > -1 && nNodeIdx < vInNodes.size()) vInNodes.at(nNodeIdx) = nullptr; } void IC::deleteOutNode(int nNodeIdx, Node* node) { std::vector<Node *> &vNodes = vOutNodes.at(nNodeIdx); for (int i = 0; i < vNodes.size(); i++) { if (vNodes.at(i) == node) { if (vNodes.size() > 1) vNodes.erase(vNodes.begin() + i); else vNodes.at(i) = nullptr; } } } void IC::addOutNode(int nNodeIdx, Node* node) { // if the first one is a nullptr, replace it if (vOutNodes.at(nNodeIdx).at(0) == nullptr) vOutNodes.at(nNodeIdx).at(0) = node; else vOutNodes.at(nNodeIdx).push_back(node); } void IC::addInNode(int nNodeIdx, Node* node) { delete vInNodes.at(nNodeIdx); vInNodes.at(nNodeIdx) = node; } int IC::getSelectedOutNode(PGEGui* pge) { olc::vf2d vMouse = pge->ScreenToWorld(olc::vf2d(pge->GetMouseX(), pge->GetMouseY())); int i = 0; for (olc::vf2d& pos : vOutNodesToDraw) { if (vMouse.x > pos.x && vMouse.y > pos.y && vMouse.x < pos.x + 8 && vMouse.y < pos.y + 8) return i; i++; } return -1; } int IC::getSelectedInNode(PGEGui* pge) { olc::vf2d vMouse = pge->ScreenToWorld(olc::vf2d(pge->GetMouseX(), pge->GetMouseY())); int i = 0; for (olc::vf2d& pos : vInNodesToDraw) { if (vMouse.x > pos.x && vMouse.y > pos.y && vMouse.x < pos.x + 8 && vMouse.y < pos.y + 8) return i; i++; } return -1; } bool IC::getInNodeState(size_t nInNode) { return vInNodes.at(nInNode) != nullptr; } std::vector<Node*>* IC::getInNodes() { return &vInNodes; } std::vector<std::vector<Node*>>* IC::getOutNodes() { return &vOutNodes; } olc::vf2d IC::getOutNodePos(int nNodeIdx) { return vOutNodesToDraw.at(nNodeIdx); } olc::vf2d IC::getInNodePos(int nNodeIdx) { return vInNodesToDraw.at(nNodeIdx); } void IC::DrawNodes(PGEGui* pge, int nSelected) { // draw the lines to other gates for (std::vector<Node*> vNodes : vOutNodes) { for (Node* node : vNodes) { if (node != nullptr) node->Draw(pge); } } // Draw the out nodes int i = 0; for (olc::vf2d& pos : vOutNodesToDraw) { // if the node is visible and not "filled", draw it olc::vf2d screenpos = pge->WorldToScreen(pos); if (screenpos.x > -4.0f * pge->GetZoom() && screenpos.y > -4.0f * pge->GetZoom() && screenpos.x <= 800 + 4.0f * pge->GetZoom() && screenpos.y <= 800 + 4.0f * pge->GetZoom()) { // Highlights the clicked node if (nSelected == i) { pge->DrawDecal(screenpos, decNodeSelected, olc::vf2d(pge->GetZoom(), pge->GetZoom()) / 8.0f); } else if (getSelectedOutNode(pge) == i) { pge->DrawDecal(screenpos, decNodeHovered, olc::vf2d(pge->GetZoom(), pge->GetZoom()) / 8.0f); } // draws the basic node else if (vOutNodes.at(i).at(0) == nullptr) { pge->DrawDecal(screenpos, decNode, olc::vf2d(pge->GetZoom(), pge->GetZoom()) / 8.0f); } else { pge->DrawDecal(screenpos, decNodeFilled, olc::vf2d(pge->GetZoom(), pge->GetZoom()) / 8.0f); } } i++; } // draw the in nodes i = 0; for (olc::vf2d& pos : vInNodesToDraw) { // if the node is visible and not "filled", draw it olc::vf2d screenpos = pge->WorldToScreen(pos); if (screenpos.x > -4.0f * pge->GetZoom() && screenpos.y > -4.0f * pge->GetZoom() && screenpos.x <= 800 + 4.0f * pge->GetZoom() && screenpos.y <= 800 + 4.0f * pge->GetZoom()) { if (getSelectedInNode(pge) == i) { pge->DrawDecal(screenpos, decNodeHovered, olc::vf2d(pge->GetZoom(), pge->GetZoom()) / 8.0f); } else if (vInNodes.at(i) == nullptr) { pge->DrawDecal(screenpos, decNode, olc::vf2d(pge->GetZoom(), pge->GetZoom()) / 8.0f); } else { pge->DrawDecal(screenpos, decNodeFilled, olc::vf2d(pge->GetZoom(), pge->GetZoom()) / 8.0f); } } i++; } } void IC::DrawNames(PGEGui* pge) { if (pge->GetZoom() > 1.0f) { int i = 0; const olc::vf2d vZoom = { 0.5f * pge->GetZoom(), 0.5f * pge->GetZoom() }; // Input Nodes Names for (std::string &str : vInNames) { olc::vf2d pos = pge->WorldToScreen(getInNodePos(i) + olc::vf2d(10.0f, 0.0f)); pge->DrawStringDecal(pos, str, olc::WHITE, vZoom); i++; } i = 0; // Output Nodes Names for (std::string &str : vOutNames) { olc::vf2d pos = pge->WorldToScreen(getOutNodePos(i) - olc::vf2d(10.0f, 0.0f)); pge->DrawStringDecal(pos, str, olc::WHITE, vZoom); i++; } // Draw the name int namelen = 4.0f * sName.size(); olc::vi2d vTextPos = pge->WorldToScreen(olc::vf2d(pos.x + 0.5f * decIC->sprite->width - 0.5f * namelen, pos.y + decIC->sprite->height)); olc::vi2d vSize = olc::vf2d(pge->GetZoom(), pge->GetZoom()) * olc::vf2d(namelen, 8.0f); if (vTextPos.x < 800 && vTextPos.y < 800 && vTextPos.x + vSize.x > 0 && vTextPos.y + vSize.y > 0) pge->DrawStringDecal(vTextPos, sName, olc::WHITE, vZoom); } } void IC::Draw(PGEGui* pge, int nSelected) { // Draw the IC its self olc::vi2d vPos = pge->WorldToScreen(pos); olc::vi2d vSize = olc::vf2d(pge->GetZoom(), pge->GetZoom()) * olc::vi2d(decIC->sprite->width, decIC->sprite->height); if (vPos.x < 800 && vPos.y < 800 && vPos.x + vSize.x > 0 && vPos.y + vSize.y > 0) pge->DrawDecal(vPos, decIC, { pge->GetZoom(), pge->GetZoom() }); DrawNodes(pge, nSelected); DrawNames(pge); } std::vector<bool> IC::getInputs() { std::vector<bool> vInputs = std::vector<bool>(); for (Node* node : vInNodes) { if (node != nullptr) vInputs.push_back(node->bCharge); else vInputs.push_back(false); } return vInputs; } void IC::load_sprites(const std::string& sFilename, SpriteManager* sm) { if (sFilename != "") decIC = sm->query(sFilename); else decIC = nullptr; decNode = sm->query("sprites/node.png"); decNodeSelected = sm->query("sprites/node_selected.png"); decNodeHovered = sm->query("sprites/node_hovered.png"); decNodeFilled = sm->query("sprites/node_filled.png"); } inline void IC::Update() { } bool IC::collides_with(PGEGui* pge, olc::vf2d vMouse) { olc::vf2d vMouseWorld(pge->ScreenToWorld(vMouse)); return (pos.x < vMouseWorld.x && pos.x + decIC->sprite->width > vMouseWorld.x && pos.y < vMouseWorld.y && pos.y + decIC->sprite->height > vMouseWorld.y); } void IC::pressed() { } void IC::UpdatePos(olc::vf2d vNewPos) { olc::vf2d delta = pos - vNewPos; pos = vNewPos; for (olc::vf2d& vNodePos : vOutNodesToDraw) vNodePos -= delta; for (olc::vf2d& vNodePos : vInNodesToDraw) vNodePos -= delta; } olc::vf2d IC::GetPos() { return pos; } bool IC::is_input() { return false; } bool IC::is_output() { return false; }
af954cb2a60021304649f318a608e90229cbf939
09abbfed45aefc46e648a875305f38f07fd6e6d0
/External/FEXCore/Source/Interface/IR/Passes/SyscallOptimization.cpp
eb5401107819b386d645f84ae0fad1d5cf5d1afb
[ "MIT" ]
permissive
FEX-Emu/FEX
804b02ce10f3cb446f6166470497cf79e760e05f
6cb0f52e9487e6ab7eaf57839f681ffa370b5149
refs/heads/main
2023-08-17T10:46:44.800259
2023-08-16T21:24:33
2023-08-16T21:24:33
245,352,386
1,460
99
MIT
2023-09-14T21:54:40
2020-03-06T07:07:03
C++
UTF-8
C++
false
false
2,860
cpp
SyscallOptimization.cpp
/* $info$ tags: ir|opts desc: Removes unused arguments if known syscall number $end_info$ */ #include "Interface/IR/PassManager.h" #include <FEXCore/IR/IR.h> #include <FEXCore/IR/IREmitter.h> #include <FEXCore/IR/IntrusiveIRList.h> #include <FEXCore/HLE/SyscallHandler.h> #include <FEXCore/Utils/Profiler.h> #include <memory> #include <stdint.h> namespace FEXCore::IR { class SyscallOptimization final : public FEXCore::IR::Pass { public: bool Run(IREmitter *IREmit) override; }; bool SyscallOptimization::Run(IREmitter *IREmit) { FEXCORE_PROFILE_SCOPED("PassManager::SyscallOpt"); bool Changed = false; auto CurrentIR = IREmit->ViewIR(); for (auto [CodeNode, IROp] : CurrentIR.GetAllCode()) { if (IROp->Op == FEXCore::IR::OP_SYSCALL) { auto Op = IROp->CW<IR::IROp_Syscall>(); // Is the first argument a constant? uint64_t Constant; if (IREmit->IsValueConstant(Op->SyscallID, &Constant)) { auto SyscallDef = Manager->SyscallHandler->GetSyscallABI(Constant); auto SyscallFlags = Manager->SyscallHandler->GetSyscallFlags(Constant); // Update the syscall flags Op->Flags = SyscallFlags; // XXX: Once we have the ability to do real function calls then we can call directly in to the syscall handler if (SyscallDef.NumArgs < FEXCore::HLE::SyscallArguments::MAX_ARGS) { // If the number of args are less than what the IR op supports then we can remove arg usage // We need +1 since we are still passing in syscall number here for (uint8_t Arg = (SyscallDef.NumArgs + 1); Arg < FEXCore::HLE::SyscallArguments::MAX_ARGS; ++Arg) { IREmit->ReplaceNodeArgument(CodeNode, Arg, IREmit->Invalid()); } #ifdef _M_ARM_64 // Replace syscall with inline passthrough syscall if we can if (SyscallDef.HostSyscallNumber != -1) { IREmit->SetWriteCursor(CodeNode); // Skip Args[0] since that is the syscallid auto InlineSyscall = IREmit->_InlineSyscall( CurrentIR.GetNode(IROp->Args[1]), CurrentIR.GetNode(IROp->Args[2]), CurrentIR.GetNode(IROp->Args[3]), CurrentIR.GetNode(IROp->Args[4]), CurrentIR.GetNode(IROp->Args[5]), CurrentIR.GetNode(IROp->Args[6]), SyscallDef.HostSyscallNumber, Op->Flags); // Replace all syscall uses with this inline one IREmit->ReplaceAllUsesWith(CodeNode, InlineSyscall); // We must remove here since DCE can't remove a IROp with sideeffects IREmit->Remove(CodeNode); } #endif } Changed = true; } } } return Changed; } fextl::unique_ptr<FEXCore::IR::Pass> CreateSyscallOptimization() { return fextl::make_unique<SyscallOptimization>(); } }
88fd1bf6e59761015d22abfd76b89b5b3a980b55
53f90e1e4cfb68291e6bc78a813142fe6b7ba774
/螺旋矩阵 II.cpp
9f7a3f49ab2953d2828bdd11cd4763343369427a
[]
no_license
Bo-rrr/Exercises
6f7dfb3651d9458b8f77c78cdbca401ce5e5737a
2b379124527ae590f57ecfa2850384370dd13b56
refs/heads/main
2023-04-19T21:32:16.405656
2021-05-08T05:26:00
2021-05-08T05:26:00
316,713,003
0
0
null
null
null
null
UTF-8
C++
false
false
1,808
cpp
螺旋矩阵 II.cpp
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n,vector<int>(n,0));//开辟二维数组 int loop = n/2;//每个圈循环几次,例如n为奇数3 那么loop=1,只循环一圈,矩阵中间的值需要特殊处理 int mid = n/2;//矩阵中间的位置,例如:n为3,中间的位置就是(1,1),n为5,中间的位置就是(2,2) int startx = 0;//定义每一圈的起始位置 int starty = 0; int count = 1;//用来矩阵中每一个方格赋值 int offset = 1;//每一圈循环,需要控制每一条边的遍历的长度 int i,j; while(loop--) { i = startx; j = starty; //四个for循环一圈 //左闭右开 for(j = starty; j < starty + n - offset; j++) { res[i][j] = count++ ; } //上闭下开 for(i = startx; i < startx + n - offset; i++) { res[i][j] = count++ ; } //右闭左开 for(; j > starty; j--) { res[i][j] = count++ ; } //下闭上开 for(; i > startx; i--) { res[i][j] = count++; } //第二圈开始的时候,起始位置要各自+1, 例如第一圈起始位置是(0,0),第二圈起始位置是(1,1) startx++; starty++; //offset 控制每一圈里每一条边遍历的长度 offset += 2; } //如果n为奇数的话,需要单独给矩阵最中间的位置赋值 if(n%2) { res[mid][mid] = count; } return res; } };
4153657bf2d616284c8a1248abf2c73608f8c076
073f9a3b6e9defde09bdb453d7c79a2169c4a31b
/2015-09/s1-5-c.cpp
7b8a7df61aa1af96ce70bb8bd0e4a0ba31e5f48f
[]
no_license
kenrick95/code-archive
9dc1c802f6d733ad10324ed217bacd3d4b2c455f
72c420353e3aa7b18af6970b6a81f710c4f5d1b0
refs/heads/master
2021-03-24T12:47:52.016103
2018-07-08T13:22:46
2018-07-08T13:22:46
69,313,404
1
0
null
null
null
null
UTF-8
C++
false
false
1,015
cpp
s1-5-c.cpp
#include <iostream> #include <fstream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> //#include <bits/stdc++.h> #define INF 1000000007 #define INFLL 9223372036854775807LL typedef long long int64; typedef unsigned long long qword; using namespace std; /** * @problem * @url * @status */ // cur = 0: n // cur = 1: m int g(int n, int m, bool cur); int f(int n, int m, bool cur) { if (n <= 0 && m <= 0) return 0; if (cur) return max(g(n - 1, m , cur) + 1, g(n, m, !cur)); else return max(g(n, m - 1, cur) + 1, g(n, m, !cur)); } int g(int n, int m, bool cur) { if (n <= 0 && m <= 0) return 0; if (cur) return max(f(n, m - 1, cur) + 1, f(n, m, !cur)); else return max(f(n - 1, m, cur) + 1, f(n, m, !cur)); } int main(){ // freopen("test.in","r",stdin); // freopen("test.out","w",stdout); int n,m; scanf("%d %d", &n, &m); printf("%d\n", max(f(n, m, 0), f(n, m, 1))); return 0; }
7dedc5c713cba2041493053389d51fc86e3a02a3
16c7354e03e866fec6999dec6a6f87350826f59b
/MyCodes/MyCodes/Linked Lists/MergeTwoSortedLLs.cpp
07746045b1181599082341209e9235fa7f34539a
[]
no_license
kevindra/MyCodes
a57f69f59b5f48b9902f25b68c1eb010f8d025dd
1864a5b926fcf6db9ac266822bea5c66551573ca
refs/heads/master
2016-09-06T11:55:32.953922
2012-10-26T10:53:01
2012-10-26T10:53:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,449
cpp
MergeTwoSortedLLs.cpp
/** * Program to merge two sorted linked lists. */ #include <iostream> using namespace std; struct node { int val; node *next; }; node *createNewNode(int val) { node *np = new node; np->val = val; np->next = NULL; return np; } /** insert a node in the beginning of a linked list **/ void insert(node *&root, int val) { if(root == NULL) { root = createNewNode(val); return; } node *np = createNewNode(val); np->next = root; root = np; } void print(node *root) { if(root == NULL) return; cout<<root->val<<" "; print(root->next); } /** take nodes one by one from both the lists - just like MERGE SORT **/ node *merge(node *root1, node *root2) { if(root1 == NULL) { return root2; } if(root2 == NULL) { return root1; } node *result = NULL; if(root1->val > root2->val) { result = root2; result->next = merge(root1, root2->next); } else { result = root1; result->next = merge(root1->next, root2); } return result; } int main() { int a[] = {30,8,7,5}; int n = 4; node *root1 = NULL; for(int i=0; i<n; i++) insert(root1, a[i]); cout<<"linked list 1: "<<endl; print(root1); cout<<endl; int b[] = {45,40,35,28,20,10}; int n2 = 6; node *root2 = NULL; for(int i=0; i<n2; i++) insert(root2, b[i]); cout<<"linked list 2: "<<endl; print(root2); cout<<endl; node *mergedList = merge(root1, root2); cout<<"Merged list: "<<endl; print(mergedList); cout<<endl; system("pause"); return 0; }
6d787ee55dc84a77d5f804a16785daa2f3a9645a
f0b84e3432c02d67b93efeafbbf1a801fa21ded3
/ziy/Classes/scripts/ScriptPara/Script88_58_SetBattleBarrier.cpp
97ae97d10218b1640a221a9868a0f9c7a7804b0a
[]
no_license
qwe00921/game-1
d49a096f096b7de0a2da7764632b20ad929d4926
2c7bd14a75ee8cd65528309bca33033f170c813a
refs/heads/master
2021-05-14T19:10:16.374869
2017-05-27T09:18:06
2017-05-27T09:18:06
116,101,350
1
0
null
2018-01-03T06:38:41
2018-01-03T06:38:41
null
UTF-8
C++
false
false
2,198
cpp
Script88_58_SetBattleBarrier.cpp
#include "Common.h" #include "Scripts.h" #include "MapElem.h" int ScriptSetBattleBarrier::HandleScript() { if(frame == 0) { need_frame = delay1 + 1; } if(frame == delay1) { // if (set)//移除障碍物 // { // int size = history->elem_list->size(); // for (int index = 0; index < size; index++) // { // if (((MapElemPtr)(history->elem_list->elementAt(index)))->x == x && ((MapElemPtr)(history->elem_list->elementAt(index)))->y == y) // { // history->elem_list->removeElementAt(index); // break; // } // } // } int iIsFind = 1; MapElem* ptrMapElem = new MapElem(x, y, barrier_id, land_id, set, iIsFind); if (!iIsFind) { SAFE_DELETE(ptrMapElem); } else { int size = history->elem_list->size(); for (int index = 0; index < size; index++) { if (((MapElemPtr)(history->elem_list->elementAt(index)))->x == x && ((MapElemPtr)(history->elem_list->elementAt(index)))->y == y) { history->elem_list->removeElementAt(index); break; } } history->elem_list->addElement(ptrMapElem); } need_frame = delay1 + delay2; playSound(SOUND_SET_FIRE); } return need_frame - frame++; } int ScriptSetBattleBarrier::initPara(char* SceneData, int index) { unkown1 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; barrier_id = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; unkown2 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; set = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; unkown3 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; land_id = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; unkown4 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; x = bytesToShort(SceneData, index); index += INT_NUM_LEN; unkown5 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; y = bytesToShort(SceneData, index); index += INT_NUM_LEN; unkown6 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; delay1 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; unkown7 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; delay2 = bytesToShort(SceneData, index); index += SHORT_NUM_LEN; return index; }
a7e40b013477cf90824ebfc69f8771526a884a76
8421f12557650910fb4c290b9b1c5bb9521e34d7
/day06/ex00/toFloat.cpp
c3e6fa074290bc49f5952d3004f07df464baeb99
[]
no_license
tvideira/piscine_cpp
6a00cb320edb8737495e67305d86037e1d061083
9bcc92d8a7b3421552bc4755ee4016757ab22e9e
refs/heads/master
2023-06-01T03:18:48.652943
2021-07-03T04:19:53
2021-07-03T04:19:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,001
cpp
toFloat.cpp
#include "convert.hpp" void toFloat(char * input, int precision) { std::string str = input; // SPECIAL CASES if (str == "nanf") { std::cout << "char: impossible" << std::endl; std::cout << "int: impossible" << std::endl; std::cout << "float: nanf" << std::endl; std::cout << "double: nan" << std::endl; return; } if (str == "-inff") { std::cout << "char: impossible" << std::endl; std::cout << "int: impossible" << std::endl; std::cout << "float: -inff" << std::endl; std::cout << "double: -inf" << std::endl; return; } if (str == "+inff") { std::cout << "char: impossible" << std::endl; std::cout << "int: impossible" << std::endl; std::cout << "float: +inff" << std::endl; std::cout << "double: +inf" << std::endl; return; } //GET FLOAT float f = strtof(input, NULL); //CAST OTHER int i = static_cast<int>(f); char c = static_cast<char>(f); double d = static_cast<double>(f); if (errno == ERANGE) { std::cout << "Cannot convert input! (float overflow)" << std::endl; return; } //PRINT CHAR if (f <= std::numeric_limits<char>::max() && f >= std::numeric_limits<char>::min()) { if (isprint(c)) std::cout << "char: '" << c << "'" << std::endl; else std::cout << "char: Non displayable" << std::endl; } else { std::cout << "char: overflow" << std::endl; } //PRINT INT if (f <= std::numeric_limits<int>::max() && f >= std::numeric_limits<int>::min()) std::cout << "int: " << i << std::endl; else std::cout << "int: overflow" << std::endl; //SET PRECISION std::cout << std::fixed << std::setprecision(precision); //PRINT FLOAT std::cout << "float: " << f << "f" << std::endl; //PRINT DOUBLE std::cout << "double: " << d << std::endl; }
369bd2db3b08f77871e47602020cd8cfd4646baa
7cdf9cde71694d73fc8f45f150a60e4c48551186
/src/bs_rect.cc
9c4fe9b8a22ed1907461bd6fa04a9f2203cd5c8f
[]
no_license
BorjaSerranoGarcia/Funciona
4944f20425e97e45a80c0449cc74471d873c2962
73606e97482c1249985fac16e6396e377d32787d
refs/heads/master
2022-11-05T01:35:47.109890
2020-06-20T20:00:49
2020-06-20T20:00:49
273,354,123
0
0
null
null
null
null
UTF-8
C++
false
false
3,745
cc
bs_rect.cc
/** * Author: Borja Serrano <serranoga@esat-alumni.com> * Filename: bs_backgorund.cc * * Implementation: background class */ #include "bs_entity.cc" #include "bs_rect.h" bsRect::bsRect() { pos_ = {0.0f, 0.0f}; width_ = 1.0f; height_ = 1.0f; rotation_ = 0.0f; scale_ = {1.0f, 1.0f}; border_r_ = 0xFF; border_g_ = 0x80; border_b_ = 0xFF; border_a_ = 0xFF; interior_r_ = 0xFF; interior_g_ = 0x80; interior_b_ = 0xFF; interior_a_ = 0xFF; hollow_ = 0; bsRect::total_rects_; } bsRect::bsRect(esat::Vec2 pos, float width, float height, float rotation, esat::Vec2 scale, uint8_t border_r, uint8_t border_g, uint8_t border_b, uint8_t border_a, uint8_t interior_r, uint8_t interior_g, uint8_t interior_b, uint8_t interior_a, uint8_t hollow) { pos_ = pos; width_ = width; height_ = height; rotation_ = rotation; scale_ = scale; border_r_ = border_r; border_g_ = border_g; border_b_ = border_b; border_a_ = border_a; interior_r_ = interior_r; interior_g_ = interior_g; interior_b_ = interior_b; interior_a_ = interior_a; hollow_ = hollow; } bsRect::bsRect(const bsRect& copy) { pos_ = copy.pos_; width_ = copy.width_; height_ = copy.height_; rotation_ = copy.rotation_; scale_ = copy.scale_; border_r_ = copy.border_r_; border_g_ = copy.border_g_; border_b_ = copy.border_b_; border_a_ = copy.border_a_; interior_r_ = copy.interior_r_; interior_g_ = copy.interior_g_; interior_b_ = copy.interior_b_; interior_a_ = copy.interior_a_; hollow_ = copy.hollow_; } void bsRect::init() { pos_ = {0.0f, 0.0f}; width_ = 1.0f; height_ = 1.0f; rotation_ = 0.0f; scale_ = {1.0f, 1.0f}; border_r_ = 0xFF; border_g_ = 0x80; border_b_ = 0xFF; border_a_ = 0xFF; interior_r_ = 0xFF; interior_g_ = 0x80; interior_b_ = 0xFF; interior_a_ = 0xFF; hollow_ = 0; } void bsRect::init(esat::Vec2 pos, float width, float height, float rotation, esat::Vec2 scale, uint8_t border_r, uint8_t border_g, uint8_t border_b, uint8_t border_a, uint8_t interior_r, uint8_t interior_g, uint8_t interior_b, uint8_t interior_a, uint8_t hollow) { pos_ = pos; width_ = width; height_ = height; rotation_ = rotation; scale_ = scale; border_r_ = border_r; border_g_ = border_g; border_b_ = border_b; border_a_ = border_a; interior_r_ = interior_r; interior_g_ = interior_g; interior_b_ = interior_b; interior_a_ = interior_a; hollow_ = hollow; } void bsRect::draw() { if (enabled_) { esat::DrawSetStrokeColor(border_r_, border_g_, border_b_, border_a_); esat::DrawSetFillColor(interior_r_, interior_g_, interior_b_, interior_a_); float quad[10] = {pos_.x, pos_.y, pos_.x + (width_ * scale_.x), pos_.y, pos_.x + (width_ * scale_.x), pos_.y + (height_ * scale_.y), pos_.x, pos_.y + (height_ * scale_.y), pos_.x, pos_.y}; esat::DrawSolidPath(quad, 5); } } void bsRect::set_position(esat::Vec2 pos) {pos_ = pos;} void bsRect::set_rotation(float rot) {} void bsRect::set_scale(esat::Vec2 scale) {scale_ = scale;} esat::Vec2 bsRect::position() {return pos_;} float bsRect::rotation() {return rotation_;} esat::Vec2 bsRect::scale() {return scale_;} /* bsRect* bsRect::CreateRect() { if (bsRect::total_rects_ < kMaxRects) { bsRect* rect = new bsRect(); rect->init(); return rect; } else { return nullptr; } } */ bsRect::~bsRect() { //--bsRect::total_rects_; }