text
stringlengths
8
6.88M
/* * Copyright 2019 LogMeIn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include <mutex> #include <unordered_map> #include <boost/callable_traits/return_type.hpp> #include <function2/function2.hpp> #include "asyncly/observable/Subscription.h" #include "asyncly/observable/detail/ObservableImpl.h" namespace asyncly { template <typename T> class Observable; /// make_lazy_observable creates an observable with customized behavior of what happens /// whenever a new subscriber is added to it. Whenever somebody subscribes to the observable, /// the `onSubscribe` function passed as a parameter is called and is passed a `Subscriber<T>` /// object that can be used to push values, errors, etc to the subscriber. /// The current executor is captured and calls to onSubscribe go through it, similar to /// Future::then(). This means that calls to this function can only be made from inside of an /// executor task. If calls to this function are made from outside of an executor task (think /// main()), an exception is thrown. template <typename T, typename F> Observable<T> make_lazy_observable(F onSubscribe) { auto observable = std::make_shared<detail::ObservableImpl<T>>( onSubscribe, asyncly::this_thread::get_current_executor()); return Observable<T>{ std::move(observable) }; } /// Observable<T> represents a collection of values of type T distributed in time. /// /// | one value | collection of values ///------------------------------------------------- /// space | T | vector<T> /// time | Future<T> | Observable<T> /// ------------------------------------------------ /// template <typename T> class Observable { public: using value_type = T; public: /// This should never be called from users of this library, /// use factory functions (make_lazy_observable) instead. Observable(std::shared_ptr<detail::ObservableImpl<T>> aimpl); public: /// subscribe registers callbacks to the Observable, that will be called /// when the publisher corresponding to the observable pushes values or error/completion events. /// Three callbacks can be supplied /// * valueFunction receives published values and can potentially be called multiple times /// * errorFunction receives an error in form of std::exception_ptr and will be called only once /// * completionFunction is called at most once to signal graceful termination /// /// After receiving a call to errorFunction or completionFunction, no other functions will be /// called. nullptr can be supplied for each of the three functions to signal noop functions. /// /// ## Threading implications /// The handler functions passed to subscribe are executed in the task-local executor context. /// this means that they can only be called inside of an executor task (similar to /// Future::then). It allows business logic code to not deal with threading at all, but it needs /// the executor runtime, which is a tradeoff. If calls to this function are made from outside /// of an executor task (think main()), an exception is thrown. Subscription subscribe(fu2::unique_function<void(T)> valueFunction); Subscription subscribe( fu2::unique_function<void(T)> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction); Subscription subscribe( fu2::unique_function<void(T)> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction, fu2::unique_function<void()> completionFunction); /// map takes a transformation function `f :: U -> T`, similar to std::function<U(T)> that /// transforms a value of type T into a value of type U. It returns a new Observable<U>. For /// each value of type T that is observed, a new value of type U is obtained by calling `f` and /// then emmitted to the Observable<U> returned by this function. Errors and completions are /// forwarded as-is. T and U can be the same. See /// http://reactivex.io/documentation/operators/map.html. template <typename F> // F models std::function<U(T)> auto map(F) -> Observable<boost::callable_traits::return_type_t<F>>; /// filter takes a filter function F and returns an Observable that emits only those values for /// which the application of the filter function to the value returns true (similar to /// std::copy_if). See http://reactivex.io/documentation/operators/filter.html. template <typename F> // F models std::function<bool(T)> Observable<T> filter(F); /// scan asynchronously iterates over values in Observable<T> while maintaining state between /// applications of the function F over each value. It emits an observable of the current state /// after each invocation of F. Think about it like std::accumulate with emiting intermediate /// results as an Observable. See http://reactivex.io/documentation/operators/scan.html for a /// really good description of the concept. Note that it does not emit the initial state as the /// first element, but emits the initial state fed to F together with the first element of the /// underlying Observable. The void overload has a slightly different signature for F, because /// there is no value to be fed into it, but state only. template <typename F> // f models std::function<U(U, T)> with U being any type representing the // state between applications of F to different values of type T auto scan(F function, boost::callable_traits::return_type_t<F> initialState) -> Observable<boost::callable_traits::return_type_t<F>>; private: std::shared_ptr<detail::ObservableImpl<T>> impl; }; template <> class Observable<void> { public: using value_type = void; public: Observable(std::shared_ptr<detail::ObservableImpl<void>> aimpl); public: Subscription subscribe(fu2::unique_function<void()> valueFunction); Subscription subscribe( fu2::unique_function<void()> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction); Subscription subscribe( fu2::unique_function<void()> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction, fu2::unique_function<void()> completionFunction); template <typename F> // F models std::function<U()> auto map(F) -> Observable<boost::callable_traits::return_type_t<F>>; template <typename F> // F models std::function<U(U)> Observable<boost::callable_traits::return_type_t<F>> scan(F, boost::callable_traits::return_type_t<F>); private: std::shared_ptr<detail::ObservableImpl<void>> impl; }; template <typename T> Observable<T>::Observable(std::shared_ptr<detail::ObservableImpl<T>> aimpl) : impl{ std::move(aimpl) } { } template <typename T> Subscription Observable<T>::subscribe(fu2::unique_function<void(T)> valueFunction) { return subscribe(std::move(valueFunction), nullptr); } template <typename T> Subscription Observable<T>::subscribe( fu2::unique_function<void(T)> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction) { return subscribe(std::move(valueFunction), std::move(errorFunction), nullptr); } template <typename T> Subscription Observable<T>::subscribe( fu2::unique_function<void(T)> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction, fu2::unique_function<void()> completionFunction) { return impl->subscribe( std::move(valueFunction), std::move(errorFunction), std::move(completionFunction)); } template <typename T> template <typename F> auto Observable<T>::map(F function) -> Observable<boost::callable_traits::return_type_t<F>> { using ReturnType = boost::callable_traits::return_type_t<F>; return make_lazy_observable<ReturnType>( [cimpl = this->impl, f = std::move(function)](auto subscriber) { cimpl->subscribe( [cf = std::move(f), subscriber](auto value) mutable { subscriber.pushValue(cf(value)); }, [subscriber](auto error) mutable { subscriber.pushError(error); }, [subscriber]() mutable { subscriber.complete(); }); }); } template <typename T> template <typename F> Observable<T> Observable<T>::filter(F function) { return make_lazy_observable<T>( [cimpl = this->impl, cfunction = std::move(function)](auto subscriber) mutable { cimpl->subscribe( [ccfunction = std::move(cfunction), subscriber](auto value) mutable { if (ccfunction(value)) { subscriber.pushValue(std::move(value)); } }, [subscriber](auto error) mutable { subscriber.pushError(error); }, [subscriber]() mutable { subscriber.complete(); }); }); } template <typename T> template <typename F> auto Observable<T>::scan(F function, boost::callable_traits::return_type_t<F> initialState) -> Observable<boost::callable_traits::return_type_t<F>> { return make_lazy_observable<boost::callable_traits::return_type_t<F>>( [cimpl = this->impl, cfunction = std::move(function), cinitialState = std::move(initialState)](auto subscriber) mutable { cimpl->subscribe( [ccfunction = std::move(cfunction), subscriber, state = std::move(cinitialState)]( auto value) mutable { state = ccfunction(state, std::move(value)); subscriber.pushValue(state); }, [subscriber](auto error) mutable { subscriber.pushError(error); }, [subscriber]() mutable { subscriber.complete(); }); }); } inline Observable<void>::Observable(std::shared_ptr<detail::ObservableImpl<void>> aimpl) : impl{ std::move(aimpl) } { } inline Subscription Observable<void>::subscribe(fu2::unique_function<void()> valueFunction) { return subscribe(std::move(valueFunction), nullptr); } inline Subscription Observable<void>::subscribe( fu2::unique_function<void()> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction) { return subscribe(std::move(valueFunction), std::move(errorFunction), nullptr); } inline Subscription Observable<void>::subscribe( fu2::unique_function<void()> valueFunction, fu2::unique_function<void(std::exception_ptr e)> errorFunction, fu2::unique_function<void()> completionFunction) { return impl->subscribe( std::move(valueFunction), std::move(errorFunction), std::move(completionFunction)); } template <typename F> auto Observable<void>::map(F function) -> Observable<boost::callable_traits::return_type_t<F>> { using ReturnType = boost::callable_traits::return_type_t<F>; return make_lazy_observable<ReturnType>( [cimpl = this->impl, f = std::move(function)](auto subscriber) { cimpl->subscribe( [cf = std::move(f), subscriber]() mutable { subscriber.pushValue(cf()); }, [subscriber](auto error) mutable { subscriber.pushError(error); }, [subscriber]() mutable { subscriber.complete(); }); }); } template <typename F> auto Observable<void>::scan(F function, boost::callable_traits::return_type_t<F> initialState) -> Observable<boost::callable_traits::return_type_t<F>> { return make_lazy_observable<boost::callable_traits::return_type_t<F>>( [cimpl = this->impl, cfunction = std::move(function), cinitialState = std::move(initialState)](auto subscriber) mutable { cimpl->subscribe( [ccfunction = std::move(cfunction), subscriber, state = std::move(cinitialState)]() mutable { state = ccfunction(state); subscriber.pushValue(state); }, [subscriber](auto error) mutable { subscriber.pushError(error); }, [subscriber]() mutable { subscriber.complete(); }); }); } }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define show(x) for(auto i: x){cout << i << " ";} #define showm(m) for(auto i: m){cout << m.x << " ";} typedef long long ll; typedef pair<int, int> P; int main() { string s; cin >> s; bool ans = true; rep(i, 3){ if (s[i] == s[i+1]){ ans = false; } } if (ans){ cout << "Good" << endl; } else { cout << "Bad" << endl; } }
#include "spawnEvent.h" spawnEvent::spawnEvent(GameObject a, GameObject b) { this->a = a; this->b = b; } GameObject spawnEvent::getObjA() { return a; } GameObject spawnEvent::getObjB() { return b; } eventType spawnEvent::getType() { return spawnEvent_type; } char spawnEvent::getKeyPress() { return NULL; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #ifndef ASYNC_QUEUE_H #define ASYNC_QUEUE_H class AsyncCommand; /** @brief Queue for AsyncCommands * Use this class to easily set yourself up for executing asynchronous commands. * Example: * AsyncQueue queue(100); * class HelloWorldCommand : public AsyncCommand { * virtual void Execute() { printf("hello world!"); } * }; * * queue.AddCommand(OP_NEW(HelloWorldCommand, ())); */ class AsyncQueue : protected MessageObject, private AutoDeleteHead { public: /** Constructor * @param delay (time in ms) Commands added to this queue will be executed after at least this much time */ AsyncQueue(unsigned long delay = 0); virtual ~AsyncQueue() {} /** Add a command to the queue, will be executed asynchronously * @param command Command to add, ownership is transferred to this queue */ virtual OP_STATUS AddCommand(AsyncCommand* command); /** @return Whether the queue is currently empty (no unfinished commands) */ BOOL Empty() { return AutoDeleteHead::Empty(); } protected: inline MessageHandler& GetMessageHandler() { return m_message_handler; } virtual BOOL PostMessage(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay) { return m_message_handler.PostMessage(msg, par1, par2, delay); } // From MessageObject virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); private: friend class AsyncCommand; OP_STATUS SetupCallBack(); MessageHandler m_message_handler; unsigned long m_delay; BOOL m_callback_initialized; }; #endif // ASYNC_QUEUE_H
#ifndef AOC_5_H #define AOC_5_H #include <vector> #include "Classes/IntCodeCPU/IntCodeCPU.h" namespace AoC_5 { long long AB(std::vector<long long> program, long long systemID) { IntCodeCPU computer(program); computer.Input(systemID); computer.RunToEnd(); return computer.Output(); } } #endif
#include <string> #include <vector> #include <array> #include <cstring> #include <sstream> #include "searchpool.hpp" using namespace std; namespace search { SearchPool::SearchPool() { this->charMap = vector<string>(); } SearchPool::SearchPool(int rows, const char* blob ) { int cols = strlen(blob) / rows; charMap.resize(rows); for(int x = 0; x < rows; ++x) { for(int y = 0; y < cols; ++y) { charMap[x].insert(charMap[x].end(), blob[x*cols + y]); } } } SearchPool::SearchPool(const vector<string> map) { this->charMap = map; } vector<array<point_s, 2>> SearchPool::find(const string term) { vector<array<point_s, 2>> ret; for(int x = 0; x < charMap.size(); ++x) { for(int y = 0; y < charMap[0].size(); ++y) { for(int mx = 0; mx < 3; ++mx) { for(int my = 0; my < 3; ++my) { if(mx + my == 0) break; array<point_s, 2> p { (point_s) { x, y }, (point_s) { (mx - 1), (my - 1) } }; if(streaks(p, term)) ret.push_back(p); } } } } return ret; } bool SearchPool::streaks(const array<point_s, 2> vec, string term) { for(int i = 0; i < term.length(); ++i) { int x = vec[0].x + vec[1].x * i; int y = vec[0].y + vec[1].y * i; if(y >= charMap.size() || y < 0) return false; if(x >= charMap[i].size() || x < 0) return false; if(charMap[y][x] != term[i]) return false; } return true; } }
#include "Deck57.hpp" Deck57::Deck57() :Deck56(){ //Jeu de 56 + Joker const Card Joker = Card (); (*this)+=Joker; }
#ifndef FATE_H #define FATE_H #include <string> #include <vector> #include "BigInt.h" class CSkill; class CMonster; class CFate { friend class CConfig; public: ~CFate(); void init(); CSkill* getSkill(int nIndex) { return m_oSkills[nIndex]; } int getSkillCount() { return (int)m_oSkills.size(); } CBigInt& getMonsterSet() { return m_nMonsterSet; } CMonster* getMonster(int nIndex) { return m_oMonsters[nIndex]; } int getMonsterCount() { return (int)m_oMonsters.size(); } private: std::wstring m_sName; std::vector<CSkill*> m_oSkills; std::vector<CMonster*> m_oMonsters; CBigInt m_nMonsterSet; }; #endif // !MONSTERID_H
#ifndef CAMERA_H #define CAMERA_H #include "core/object.h" // Base class: Object namespace pb { class Camera : public Object { private: Camera(const Camera& rhs); Camera& operator=(const Camera& rhs); public: Camera(); virtual ~Camera(); inline const Mat4& VP(); private: PBError init(); void computeVP(); private: Mat4* mpProjection; Mat4* mpVP; }; const Mat4& Camera::VP() { computeVP(); return *mpVP; } } #endif // CAMERA_H
#include "Bragg.h" #include "ParamConfig.h" #include "Utility.h" #include <iostream> #include <fstream> #include <sstream> using namespace std; #include <TFile.h> #include <TNtuple.h> #include <TDirectory.h> #include <TH1.h> #include <TH2.h> #include <TH3.h> #include <TCut.h> #include <TF1.h> #include <TParameter.h> #include <TGraph.h> Bragg::Bragg(ParamConfig *param, TString adj_fname, TString run_fname) : Nt(param) { fAdjFname = adj_fname; fRunFname = run_fname; fUseProtonAdjust = fRunFname.Length() > 0? kTRUE: kFALSE; fHistBrag = NULL; fFileAdj = NULL; fHistTof = NULL; fHistXy = NULL; //fHistLambda = NULL; fHistXyt = NULL; kTofNbin = fParam->BraggTofNbin(); kTofMin = fParam->BraggTofXmin(); kTofMax = fParam->BraggTofXmax(); kLambdaNbin = fParam->BraggLambdaNbin(); kLambdaMin = fParam->BraggLambdaXmin(); kLambdaMax = fParam->BraggLambdaXmax(); kFitTofMin = fParam->BraggFitTofMin(); kFitTofMax = fParam->BraggFitTofMax(); kFitLambdaMin = fParam->BraggFitLambdaMin(); kFitLambdaMax = fParam->BraggFitLambdaMax(); } Bragg::~Bragg() { CloseFile(); } void Bragg::CloseFile() { if(!fFileAdj){ fFileAdj->Close(); delete fFileAdj; } fFileAdj = NULL; fHistXy = NULL; fHistTof = NULL; //fHistLambda = NULL; } int Bragg::LoadAdjustHist(TString adj_file) { cout << "vanadium data ... " << adj_file << endl; fFileAdj = new TFile(adj_file); if(!fFileAdj->IsOpen()){ cerr << "WARN: failed to open " << adj_file << endl; return -1; } fHistXy = static_cast<TH2D*>(fFileAdj->Get("hvxy")); if(!fHistXy){ cerr << "WARN: histogram 'hvxy' is not found" << endl; return -1; } fHistTof = static_cast<TH1D*>(fFileAdj->Get("hvtof")); if(!fHistTof){ cerr << "WARN: histogram 'hvtof' is not found" << endl; return -1; } /* fHistLambda = static_cast<TH3D*>(fFileAdj->Get("hvxyl")); if(!fHistLambda){ cerr << "WARN: histogram 'hvxyl' is not found" << endl; return -1; } */ fHistXyt = static_cast<TH3D*>(fFileAdj->Get("hvxyt")); if(!fHistXyt){ cerr << "WARN: histogram 'hvxyt' is not found" << endl; return -1; } return 0; } /*! * Load run list. * This list has to have run number and proton count. * * ex) run.dat * # run at 2011.08.09 * 8339 39831444.00 * 8340 39908572.00 * 8341 40084508.00 * 8342 39851812.00 * 8343 40075732.00 * 8344 40126108.00 * * '#' means comment is started */ int Bragg::LoadRunList(TString run_file) { if(fUseProtonAdjust != kTRUE) return 0; cout << "load run list ... " << run_file << endl; fstream fin(run_file.Data(), ios::in); if(!fin) { cerr << "ERROR: " << run_file << " is not found" << endl; return -2; } // load run info string line; map<Int_t, Int_t> run_list; Long64_t sum_count = 0; while(getline(fin, line)) { const unsigned int p = line.find('#', 0); if(p != string::npos) line = line.substr(0, p); // remove comments which is started at '#' stringstream s(line); Int_t run = -1; Int_t count = -1; s >> run >> count; if(run > 0 && count > 0) { if(!is_exist<Int_t, Int_t>(run_list, run)) { run_list[run] = count; sum_count += count; } else { cerr << "WARN: run is duplicated - run=" << run << " count=" << count << endl; continue; } } //cout << run << " " << count << " " << sum_count << " " << run_list.size() << endl; } fin.close(); // create normalizing parameters map<Int_t, Int_t>::iterator it = run_list.begin(); map<Int_t, Int_t>::iterator ie = run_list.end(); const Int_t run_count = run_list.size(); const Double_t ave_count = (Double_t)sum_count / run_count; Double_t runs[run_count]; Double_t protons[run_count]; Double_t proton_norms[run_count]; Int_t c = 0; for(; it != ie; it++) { //cout << (*it).first << " " << (*it).second << endl; const Int_t run = it->first; const Int_t count = it->second; const Double_t norm = count / ave_count; fRunNorm[run] = norm; runs[c] = run; protons[c] = count; proton_norms[c] = norm; ++c; } // save run info TDirectory *tmp = gDirectory; ChdirTop(); TGraph *g_proton_run = new TGraph(run_count, runs, protons); g_proton_run->SetName("gproton"); g_proton_run->SetTitle("Proton Count"); g_proton_run->Write(); delete g_proton_run; g_proton_run = NULL; TGraph *g_protonnorm_run = new TGraph(run_count, runs, proton_norms); g_protonnorm_run->SetName("gproton_norm"); g_protonnorm_run->SetTitle("Proton Normalization Value"); g_protonnorm_run->Write(); delete g_protonnorm_run; g_protonnorm_run = NULL; tmp->cd(); return 0; } //========================================== // methods called by base class //========================================== int Bragg::Init(TNtuple* /*nt*/) { fHistBrag = new TH3D("hbrag", "Bragg 3D Histogram (x-y-tof)", kNxPixels, 0, kNxPixels, kNyPixels, 0, kNyPixels, kTofNbin, kTofMin, kTofMax); /* cout << "kNxPixels=" << kNxPixels << " " << "kNyPixels=" << kNyPixels << " " << "kLmabdaNbin=" << kLambdaNbin << " " << "kLambdaMin=" << kLambdaMin << " " << "kLambdaMax=" << kLambdaMax << endl; */ LoadAdjustHist(fAdjFname); if(LoadRunList(fRunFname) < 0) return -1; return 0; } void Bragg::Reset() { fHistBrag->Reset(); } void Bragg::Fill() { //const Double_t lambda = TofToLambda(f_Xposition, f_Yposition, f_Tof); fHistBrag->Fill(f_Xposition, f_Yposition, f_Tof); //cout << "tof=" << f_Tof << " " << "lambda=" << lambda << endl; } TH2D *Bragg::Projection2D(TH3D *h3, TString name, TString title, TString direction) { TAxis *xaxis = h3->GetXaxis(); const Int_t nbinx = xaxis->GetNbins(); const Double_t xmin = xaxis->GetXmin(); const Double_t xmax = xaxis->GetXmax(); TAxis *yaxis = h3->GetYaxis(); const Int_t nbiny = yaxis->GetNbins(); const Int_t ymin = yaxis->GetXmin(); const Int_t ymax = yaxis->GetXmax(); TAxis *zaxis = h3->GetZaxis(); const Int_t nbinz = zaxis->GetNbins(); const Int_t zmin = zaxis->GetXmin(); const Int_t zmax = zaxis->GetXmax(); TH2D *h2 = NULL; if(direction == "xy") { h2 = new TH2D(name, title, nbinx, xmin, xmax, nbiny, ymin, ymax); const Int_t max = nbinx * nbiny; Int_t num = 0; #ifdef _OPENMP #pragma omp parallel for #endif for(Int_t xbin = 1; xbin <= nbinx; xbin++) { for(Int_t ybin = 1; ybin <= nbiny; ybin++) { cout << TString::Format("%5.1f%%", (++num)/(Double_t)max*100.) << "\r" << flush; const Double_t v = h3->Integral(xbin, xbin, ybin, ybin, 1, nbinz); h2->SetBinContent(xbin, ybin, v); } } } else if(direction == "yz") { //h2 = new TH2D(name, title, nbiny, ymin, ymax, nbinz, zmin, zmax); h2 = new TH2D(name, title, nbinz, zmin, zmax, nbiny, ymin, ymax); const Int_t max = nbiny * nbinz; Int_t num = 0; #ifdef _OPENMP #pragma omp parallel for #endif for(Int_t ybin = 1; ybin <= nbiny; ybin++) { for(Int_t zbin = 1; zbin <= nbinz; zbin++) { cout << TString::Format("%5.1f%%", (++num)/(Double_t)max*100.) << "\r" << flush; const Double_t v = h3->Integral(1, nbinx, ybin, ybin, zbin, zbin); //h2->SetBinContent(ybin, zbin, v); h2->SetBinContent(zbin, ybin, v); } } } else if(direction == "xz") { //h2 = new TH2D(name, title, nbinx, xmin, xmax, nbinz, zmin, zmax); h2 = new TH2D(name, title, nbinz, zmin, zmax, nbinx, xmin, xmax); const Int_t max = nbinx * nbinz; Int_t num = 0; #ifdef _OPENMP #pragma omp parallel for #endif for(Int_t xbin = 1; xbin <= nbinx; xbin++) { for(Int_t zbin = 1; zbin <= nbinz; zbin++) { cout << TString::Format("%5.1f%%", (++num)/(Double_t)max*100.) << "\r" << flush; const Double_t v = h3->Integral(xbin, xbin, 1, nbiny, zbin, zbin); //h2->SetBinContent(xbin, zbin, v); h2->SetBinContent(zbin, xbin, v); } } } return h2; } //============================================= // analyzing methods //============================================== /*! * HISTOGRAM AND PARAMETER LIST AND FLOW * * 3D X-Y-Tof [ hxyt] ------+ * 2D X-Y [ hxy] ------|--+ * 2D X-Tof [ hxt] ------|--|--+ * 2D Y-Tof [ hyt] ------|--|--|--+ * 1D TOF [ htof] ------|--|--|--|--+ * 1D Lambda [hlambda] ------|--|--|--|--|--+ * | | | | | | * | A B C D E F * -----+------------------ * Raw Bragg [ ] - I | 1 . . . . . * Adjust Only X-Y [_axy ] - II | 2 . . . . . * Adjust Only Lambda [_at ] - III | . . . . . . * adjust X-Y and Lambda [_axyt] - IV | 3 4 . . 5 6 * * 1 - A-I - hxyt * 2 - A-II - hxyt_axy * 3 - A-III - hxyt_axyt * 4 - B-IV - hxy_axyt * 5 - E-IV - htof_axyt * 6 - F-IV - hlambda_axyt * */ int Bragg::Analyze(const Long_t runid, const TDirectory *currdir) { cout << "RunId=" << runid << " [/" << currdir->GetName() << "]" << endl; // set name and title of bragg hist and save cout << " creating bragg histogram" << endl; fHistBrag->SetName("hxyt"); fHistBrag->SetTitle("Bragg 3D Histogram"); /*TH3D *hxyt_norm = NULL; if(fUseProtonAdjust == kTRUE) { if(is_exist<Int_t, Double_t>(fRunNorm, runid)) { hxyt_norm = AdjustProton(fHistBrag, fRunNorm[runid]); hxyt_norm->SetName("hxyt_norm"); hxyt_norm->SetTitle("Bragg 3D Normalized Histogram"); } else { cerr << "WARN: no run normalization data - run=" << runid << endl; hxyt_norm = fHistBrag; } } else hxyt_norm = fHistBrag; */ TH3D *hxyt_axy = NULL; TH3D *hxyt_at = NULL; // adjust x-y cout << " adjusting x-y" << endl; if(fUseProtonAdjust == kTRUE) { if(is_exist<Int_t, Double_t>(fRunNorm, runid)) { hxyt_axy = AdjustXy(fHistBrag, fHistXy); hxyt_axy = AdjustProton(hxyt_axy, fRunNorm[runid]); hxyt_axy->SetName("hxyt_axy"); hxyt_axy->SetTitle("X-Y-TOF histogram"); } else { cerr << "WARN: no run normalization data - run=" << runid << endl; hxyt_axy = AdjustXy(fHistBrag, fHistXy); hxyt_axy->SetName("hxyt_axy"); hxyt_axy->SetTitle("X-Y-TOF histogram"); } } else hxyt_axy = AdjustXy(fHistBrag, fHistXy); // adjust TOF cout << " adjusting only TOF" << endl; if(fUseProtonAdjust == kTRUE) { if(is_exist<Int_t, Double_t>(fRunNorm, runid)) { hxyt_at = AdjustTof(fHistBrag, fHistXyt); hxyt_at = AdjustProton(hxyt_at, fRunNorm[runid]); } else { cerr << "WARN: no run normalization data - run=" << runid << endl; hxyt_at = AdjustTof(fHistBrag, fHistXyt); } } else hxyt_at = AdjustTof(fHistBrag, fHistXyt); hxyt_at->SetName("hxyt_at"); hxyt_at->SetTitle("X-Y-TOF histogram"); // adjust TOF cout << " adjusting TOF" << endl; TH3D *hxyt_axyt = AdjustTof(hxyt_axy, fHistXyt); hxyt_axyt->SetName("hxyt_axyt"); hxyt_axyt->SetTitle("X-Y-TOF histogram"); TString hxyt_axyt_title = TString::Format("X-Y histogram (RunId=%d)", runid); TH2D *hxy_axyt = ProjectionXY(hxyt_axyt, "hxy_axyt0", hxyt_axyt_title); AREARANGES ar = Analyze(hxyt_axyt, hxy_axyt, runid, "_axyt", NULL, NULL, NULL, true); Analyze(hxyt_axy, NULL, runid, "_axy", ar.area, ar.range, ar.lrange, false); Analyze(hxyt_at, NULL, runid, "_at", ar.area, ar.range, ar.lrange, false); Analyze((TH3D*)fHistBrag->Clone(), NULL, runid, "", ar.area, ar.range, ar.lrange, false); return 0; } /*! * Analyze * * When following argments is NULL, calculate ones. * area * range * lrange * */ AREARANGES Bragg::Analyze(TH3D *hist, TH2D *h2, const Long_t runid, TString suffix, BOXAREA *area, RANGE *range, RANGE *lrange, Bool_t is_savepeak) { // select box area from 2D histogram if(!area) { cout << " select area" << endl; BOXAREA a = SelectArea(h2, runid); area = &a; } cout << " Projections " << hist->GetName() << endl; HISTS *hs = Projections(hist, *area, NULL, suffix); SaveWithRunId(hs , runid); cout << " htof integration" << endl; // select range for tof if(!range) { cout << " select range" << endl; RANGE r = SelectRange(hs->htof, kFitTofMin, kFitTofMax, "_t"); range = &r; } // peak area if(is_savepeak) SavePeakArea(hist, *area, *range); // integrate for lambda cout << " integral" << endl; const Double_t intg = Integral(hs->htof, *range); TParameter<Double_t> p_intg(TString("p_intg_t") + suffix, intg); p_intg.Write(); cout << " hlambda integration" << endl; // select range for lambda if(!lrange) { cout << " select range" << endl; RANGE r = SelectRange(hs->hlambda, kFitLambdaMin, kFitLambdaMax, "_l"); lrange = &r; } // integrate for lambda cout << " integral" << endl; const Double_t lintg = Integral(hs->hlambda, *lrange); TParameter<Double_t> p_intg_l(TString("p_intg_l") + suffix, lintg); p_intg_l.Write(); delete hs; hs = NULL; /* cout << "area: " << area->x1 << " " << area->y1 << " " << area->x2 << " " << area->y2 << endl; cout << "range: " << range->min << " " << range->max << endl; cout << "lrange: " << lrange->min << " " << lrange->max << endl; */ AREARANGES area_range(area, range, lrange); return area_range; } /*! * hxyt (3D) [A] * -> hxy (2D) [B] * -> hxz (2D) [C] * -> hyz (2D) [D] * -> htof (1D) [E] */ HISTS *Bragg::Projections(TH3D *hxyt, BOXAREA area, const char *prefix, const char *suffix) { HISTS *hists = new HISTS(); hists->hxyt = hxyt; cout << " A. original histogram - " << hxyt->GetName() << endl; // project hxyt to 2D histogram (x-y) TString hxy_name = "hxy"; if(prefix != NULL) hxy_name = prefix + hxy_name; if(suffix != NULL) hxy_name = hxy_name + suffix; cout << " B. projection x-y - " << hxy_name << endl; hists->hxy = ProjectionXY(hxyt, hxy_name, "2D X-Y Histogram"); // project hxyt to 2D histogram (x-t) TString hxt_name = "hxt"; if(prefix != NULL) hxt_name = prefix + hxt_name; if(suffix != NULL) hxt_name = hxt_name + suffix; cout << " C. projection x-tof - " << hxt_name << endl; hists->hxt = ProjectionXZ(hxyt, hxt_name, "2D X-TOF Histogram"); // project hxyt to 2D histogram (y-t) TString hyt_name = "hyt"; if(prefix != NULL) hyt_name = prefix + hyt_name; if(suffix != NULL) hyt_name = hyt_name + suffix; cout << " D. projection y-tof - " << hyt_name << endl; hists->hyt = ProjectionYZ(hxyt, hyt_name, "2D Y-TOF Histogram"); // create 1D TOF histogram from bragg adjusted completely at the box area TString htof_name = "htof"; if(prefix != NULL) htof_name = prefix + htof_name; if(suffix != NULL) htof_name = htof_name + suffix; cout << " E. create 1D TOF histogram - " << htof_name << endl; hists->htof = CreateTofHist(hxyt, area, htof_name, "1D TOF Histogram"); // create 1D Lambda histogram from bragg adjusted completely at the box area TString hlambda_name = "hlambda"; if(prefix != NULL) hlambda_name = prefix + hlambda_name; if(suffix != NULL) hlambda_name = hlambda_name + suffix; cout << " F. create 1D Lambda histogram - " << hlambda_name << endl; hists->hlambda = CreateLambdaHist(hxyt, area, hlambda_name, "1D Lambda Histogram"); return hists; } TH2D *Bragg::ProjectionXY(TH3D *h3, TString name, TString title) { return Projection2D(h3, name, title, "xy"); } TH2D *Bragg::ProjectionXZ(TH3D *h3, TString name, TString title) { return Projection2D(h3, name, title, "xz"); } TH2D *Bragg::ProjectionYZ(TH3D *h3, TString name, TString title) { return Projection2D(h3, name, title, "yz"); } void Bragg::SaveWithRunId(HISTS *hs, Int_t runid) { hs->hxyt->SetTitle(TString::Format("%s (RunId=%d)", hs->hxyt->GetTitle(), runid)); hs->hxy->SetTitle(TString::Format("%s (RunId=%d)", hs->hxy->GetTitle(), runid)); hs->hyt->SetTitle(TString::Format("%s (RunId=%d)", hs->hyt->GetTitle(), runid)); hs->hxt->SetTitle(TString::Format("%s (RunId=%d)", hs->hxt->GetTitle(), runid)); hs->htof->SetTitle(TString::Format("%s (RunId=%d)", hs->htof->GetTitle(), runid)); hs->hlambda->SetTitle(TString::Format("%s (RunId=%d)", hs->hlambda->GetTitle(), runid)); hs->hxyt->Write(); hs->hxy->Write(); hs->hyt->Write(); hs->hxt->Write(); hs->htof->Write(); hs->hlambda->Write(); } TH3D *Bragg::AdjustProton(TH3D *hraw, Double_t norm) { //TH3D *h3 = clone? (TH3D*)hraw->Clone(): hraw; hraw->Scale(1./norm); return hraw; } TH3D *Bragg::AdjustXy(TH3D *hraw, const TH2D *hxy, bool clone) { TH3D *h3 = clone? (TH3D*)hraw->Clone(): hraw; const Int_t max = kNxPixels * kNyPixels; Int_t num = 0; #ifdef _OPENMP #pragma omp parallel for #endif for(Int_t xbin = 1; xbin <= kNxPixels; xbin++) { for(Int_t ybin = 1; ybin <= kNyPixels; ybin++) { const Double_t norm = hxy->GetBinContent(xbin, ybin); cout << TString::Format("%5.1f%%", (++num)/(Double_t)max*100.) << "\r" << flush; if(norm <= 0) continue; for(Int_t tbin = 1; tbin <= kTofNbin; tbin++) { const Double_t value = h3->GetBinContent(xbin, ybin, tbin); h3->SetBinContent(xbin, ybin, tbin, value/norm); /* cout << "xbin=" << xbin << " " << "ybin=" << ybin << " " << "lbin=" << lbin << " " << "norm=" << norm << " " << "value=" << value << " " << "v/n=" << value/norm << endl; */ } } } return h3; } TH3D *Bragg::AdjustTof(TH3D *hraw, const TH3D *hxyt, bool clone) { TH3D *h3 = clone? (TH3D*)hraw->Clone(): hraw; #ifdef _OPENMP const Int_t max = kNxPixels * kNyPixels; Int_t num = 0; Int_t ig = 0; #pragma omp parallel for for(Int_t xbin = 1; xbin <= kNxPixels; xbin++) { for(Int_t ybin = 1; ybin <= kNyPixels; ybin++) { cout << TString::Format("%5.1f%%", (++num)/(Double_t)max*100.) << "\r" << flush; for(Int_t tbin = 1; tbin <= kTofNbin; tbin++) { const Double_t norm = hxyt->GetBinContent(xbin, ybin, tbin); if(norm <= 0) { ig++; continue; } const Double_t value = h3->GetBinContent(xbin, ybin, tbin); //cout << "norm=" << norm << " value=" << value << endl; h3->SetBinContent(xbin, ybin, tbin, value/norm); } } } if(ig > 0) cout << "WARN: canceled normalizing " << ig << " bins because value of hxyt is 0" << endl; #else h3->Divide(hxyt); #endif return h3; } BOXAREA Bragg::SelectArea(TH2D *hbrag, Int_t run) { // TODO: devermine box area on bragg data for bragg peak Double_t x1 = fParam->BraggAreaX1(run); Double_t x2 = fParam->BraggAreaX2(run); Double_t y1 = fParam->BraggAreaY1(run); Double_t y2 = fParam->BraggAreaY2(run); if(x1 < 0) { cout << "INFO: box area x1 of run " << run << " is not set" << endl; x1 = 0; } if(x2 < 0) { cout << "INFO: box area x2 of run " << run << " is not set" << endl; x2 = 256; } if(y1 < 0) { cout << "INFO: box area y1 of run " << run << " is not set" << endl; y1 = 0; } if(y2 < 0) { cout << "INFO: box area y2 of run " << run << " is not set" << endl; y2 = 256; } TParameter<Int_t> p_x1("p_x1", x1); p_x1.Write(); TParameter<Int_t> p_x2("p_x2", x2); p_x2.Write(); TParameter<Int_t> p_y1("p_y1", y1); p_y1.Write(); TParameter<Int_t> p_y2("p_y2", y2); p_y2.Write(); cout << " box area ... " << "x1=" << x1 << " " << "x2=" << x2 << " " << "y1=" << y1 << " " << "y2=" << y2 << endl; return BOXAREA(x1, y1, x2, y2); } TH1D *Bragg::CreateTofHist(TH3D *hxyt, BOXAREA area, const char *name, const char *title) { TAxis *xaxis = hxyt->GetXaxis(); TAxis *yaxis = hxyt->GetYaxis(); TAxis *zaxis = hxyt->GetZaxis(); const Int_t xbinmin = xaxis->FindBin(area.x1); const Int_t xbinmax = xaxis->FindBin(area.x2); const Int_t ybinmin = yaxis->FindBin(area.y1); const Int_t ybinmax = yaxis->FindBin(area.y2); /* cout << " xbin = " << xbinmin << " - " << xbinmax << " " << "ybin = " << ybinmin << " - " << ybinmax << endl; */ TH1D *h = new TH1D(name, title, kTofNbin, kTofMin, kTofMax); #ifdef _OPENMP #pragma omp parallel for #endif for(Int_t xbin = xbinmin; xbin <= xbinmax; xbin++) { //const Int_t x = (Int_t)xaxis->GetBinLowEdge(xbin); //const Double_t x = xaxis->GetBinCenter(xbin); for(Int_t ybin = ybinmin; ybin <= ybinmax; ybin++) { //const Int_t y = (Int_t)yaxis->GetBinLowEdge(ybin); //const Double_t y = yaxis->GetBinCenter(ybin); //for(Int_t lbin = 1; lbin <= kLambdaNbin; lbin++) for(Int_t tbin = 1; tbin <= kTofNbin; tbin++) { //const Double_t l = zaxis->GetBinLowEdge(lbin); //const Double_t l = zaxis->GetBinCenter(lbin); const Double_t v = hxyt->GetBinContent(xbin, ybin, tbin); //const Double_t tof = LambdaToTof(x, y, l); const Double_t tof = zaxis->GetBinCenter(tbin); h->Fill(tof, v); } } } return h; } TH1D *Bragg::CreateLambdaHist(TH3D *hxyt, BOXAREA area, const char *name, const char *title) { TAxis *xaxis = hxyt->GetXaxis(); TAxis *yaxis = hxyt->GetYaxis(); TAxis *zaxis = hxyt->GetZaxis(); const Int_t xbinmin = xaxis->FindBin(area.x1); const Int_t xbinmax = xaxis->FindBin(area.x2); const Int_t ybinmin = yaxis->FindBin(area.y1); const Int_t ybinmax = yaxis->FindBin(area.y2); /* cout << " xbin = " << xbinmin << "-" << xbinmax << " " << "ybin = " << ybinmin << "-" << ybinmax << endl; */ TH1D *h = new TH1D(name, title, kLambdaNbin, kLambdaMin, kLambdaMax); #ifdef _OPENMP #pragma omp parallel for #endif for(Int_t xbin = xbinmin; xbin <= xbinmax; xbin++) { //const Int_t x = (Int_t)xaxis->GetBinLowEdge(xbin); const Double_t x = xaxis->GetBinCenter(xbin); for(Int_t ybin = ybinmin; ybin <= ybinmax; ybin++) { //const Int_t y = (Int_t)yaxis->GetBinLowEdge(ybin); const Double_t y = yaxis->GetBinCenter(ybin); //for(Int_t lbin = 1; lbin <= kLambdaNbin; lbin++) for(Int_t tbin = 1; tbin <= kTofNbin; tbin++) { //const Double_t l = zaxis->GetBinLowEdge(lbin); const Double_t t = zaxis->GetBinCenter(tbin); const Double_t v = hxyt->GetBinContent(xbin, ybin, tbin); const Double_t lambda = TofToLambda(x, y, t); h->Fill(lambda, v); } } } return h; } RANGE Bragg::SelectRange(TH1D *hist, const Double_t xmin, const Double_t xmax, const char *suffix) { TString name = TString::Format("g%s", suffix); //const Double_t xmin = 25000; //const Double_t xmax = 35000; TF1 *g = new TF1(name, "landau", xmin, xmax); // output fit results to stdout is disabled hist->Fit(g, "RNQ", "", xmin, xmax); g->Write(); const Double_t c = g->GetParameter(0); const Double_t dc = g->GetParError(0); const Double_t mpv = g->GetParameter(1); const Double_t dmpv = g->GetParError(1); const Double_t sigma = g->GetParameter(2); const Double_t dsigma = g->GetParError(2); const Double_t xlo = mpv - fParam->BraggFitSigmaLow() * sigma; const Double_t xhi = mpv + fParam->BraggFitSigmaHigh() * sigma; TString cname = TString::Format("p_c%s", suffix); TString dcname = TString::Format("p_dc%s", suffix); TString mpvname = TString::Format("p_mpv%s", suffix); TString dmpvname = TString::Format("p_dmpv%s", suffix); TString sigmaname = TString::Format("p_sigma%s", suffix); TString dsigmaname = TString::Format("p_dsigma%s", suffix); TParameter<Double_t> p_c(cname, c); p_c.Write(); TParameter<Double_t> p_dc(dcname, dc); p_dc.Write(); TParameter<Double_t> p_mpv(mpvname, mpv); p_mpv.Write(); TParameter<Double_t> p_dmpv(dmpvname, dmpv); p_dmpv.Write(); TParameter<Double_t> p_sigma(sigmaname, sigma); p_sigma.Write(); TParameter<Double_t> p_dsigma(dsigmaname, dsigma); p_dsigma.Write(); TString xloname = TString::Format("p_xlo%s", suffix); TString xhiname = TString::Format("p_xhi%s", suffix); TParameter<Double_t> p_xlo(xloname, xlo); p_xlo.Write(); TParameter<Double_t> p_xhi(xhiname, xhi); p_xhi.Write(); cout << " landau fit ... " << "mu=" << mpv << " " << "sigma=" << sigma << " " << "xlo=" << xlo << " " << "xhi=" << xhi << endl; delete g; g = NULL; return RANGE(xlo, xhi); } Double_t Bragg::Integral(TH1D *hist, RANGE range) { const Int_t bmin = hist->FindBin(range.min); const Int_t bmax = hist->FindBin(range.max); Double_t intg = hist->Integral(bmin, bmax); cout << " " << "xmin=" << range.min << " " << "xmax=" << range.max << " " << "binmin=" << bmin << " " << "binmax=" << bmax << " " << "integral=" << intg << endl; return intg; } void Bragg::SavePeakArea(TH3D *hist, BOXAREA area, RANGE range) { TAxis *xaxis = hist->GetXaxis(); TAxis *yaxis = hist->GetYaxis(); TAxis *zaxis = hist->GetZaxis(); const Int_t xbinmin = xaxis->FindBin(area.x1); const Int_t xbinmax = xaxis->FindBin(area.x2); const Int_t nxbin = xbinmax - xbinmin; const Int_t ybinmin = yaxis->FindBin(area.y1); const Int_t ybinmax = yaxis->FindBin(area.y2); const Int_t nybin = ybinmax - ybinmin; const Int_t zbinmin = zaxis->FindBin(range.min); const Int_t zbinmax = zaxis->FindBin(range.max); const Int_t nzbin = zbinmax - zbinmin; TString name = hist->GetName(); name += "_peak"; TString title = hist->GetTitle(); title += " (Peak Area)"; TH3D *hpeak = new TH3D(name, title, nxbin, area.x1, area.x2, nybin, area.y1, area.y2, nzbin, range.min, range.max); #ifdef _OPENMP #pragma omp parallel for #endif for(Int_t xbin = xbinmin; xbin < xbinmax; xbin++) { for(Int_t ybin = ybinmin; ybin < ybinmax; ybin++) { for(Int_t zbin = zbinmin; zbin < zbinmax; zbin++) { hpeak->SetBinContent(xbin, ybin, zbin, hist->GetBinContent(xbin, ybin, zbin)); } } } cout << " save peak area - " << name << endl; hpeak->Write(); delete hpeak; hpeak = NULL; }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/object/es_special_property.h" #include "modules/ecmascript/carakan/src/object/es_object.h" #include "modules/ecmascript/carakan/src/object/es_arguments.h" #include "modules/ecmascript/carakan/src/object/es_regexp_object.h" #include "modules/ecmascript/carakan/src/vm/es_execution_context.h" PutResult ES_Special_Property::SpecialPutL(ES_Context *context, ES_Object *this_object, const ES_Value_Internal &value, const ES_Value_Internal &this_value) { switch (GCTag()) { case GCTAG_ES_Special_Global_Variable: { OP_ASSERT(this_object->IsGlobalObject()); ES_Global_Object *global_object = static_cast<ES_Global_Object *>(this_object); unsigned index = static_cast<ES_Special_Global_Variable *>(this)->index; #ifdef ES_NATIVE_SUPPORT global_object->InvalidateInlineFunction(context, index); #endif // ES_NATIVE_SUPPORT global_object->GetVariableValue(index) = value; return PROP_PUT_OK; } case GCTAG_ES_Special_Aliased: *static_cast<ES_Special_Aliased *>(this)->property = value; return PROP_PUT_OK; case GCTAG_ES_Special_Mutable_Access: { if (!context) return PROP_PUT_FAILED; ES_Execution_Context *exec_context = context->GetExecutionContext(); if (!exec_context) return PROP_PUT_FAILED; ES_Object *setter = static_cast<ES_Special_Mutable_Access *>(this)->setter; if (setter == NULL) return PROP_PUT_READ_ONLY; /* Save scratch registers since we will now execute more code. */ ES_Value_Internal *register_storage = exec_context->SaveScratchRegisters(); ES_Value_Internal *registers = exec_context->SetupFunctionCall(setter, /* argc = */ 1); registers[0] = this_value; registers[1].SetObject(setter); registers[2] = value; if (!exec_context->CallFunction(registers, /* argc = */ 1)) { exec_context->RestoreScratchRegisters(register_storage); return PROP_PUT_FAILED; } exec_context->RestoreScratchRegisters(register_storage); return PROP_PUT_OK; } case GCTAG_ES_Special_Function_Caller: return PROP_PUT_READ_ONLY; case GCTAG_ES_Special_Function_Length: return PROP_PUT_READ_ONLY; case GCTAG_ES_Special_Function_Prototype: { OP_ASSERT(this_object->IsFunctionObject()); ES_Function *function = static_cast<ES_Function *>(this_object); ES_Box *properties = function->GetProperties(); ES_Property_Info info(DE|DD); ES_Layout_Info old_layout = function->Class()->GetLayoutInfoAtInfoIndex(ES_PropertyIndex(ES_Function::PROTOTYPE)); ES_Class *old_klass = ES_Class::ActualClass(function->Class()); BOOL needs_conversion = FALSE; ES_Class *new_klass = ES_Class::ChangeAttribute(context, function->Class(), context->rt_data->idents[ESID_prototype], info, function->Count(), needs_conversion); ES_CollectorLock gclock(context); if (function->GetGlobalObject()->IsDefaultFunctionProperties(properties)) { properties = ES_Box::Make(context, new_klass->SizeOf(function->Count())); op_memcpy(properties->Unbox(), function->GetProperties()->Unbox(), function->GetProperties()->Size()); this_object->SetProperties(properties); } if (needs_conversion) function->ConvertObject(context, old_klass, new_klass); else { ES_Property_Info prototype_info = old_klass->GetPropertyInfoAtIndex(ES_PropertyIndex(ES_Function::PROTOTYPE)); int diff = new_klass->GetLayoutInfoAtIndex(prototype_info.Index()).Diff(old_layout); function->ConvertObjectSimple(context, new_klass, ES_LayoutIndex(prototype_info.Index() + 1), diff, old_klass->SizeOf(function->Count()), function->Count()); } this_object->PutCachedAtIndex(ES_PropertyIndex(ES_Function::PROTOTYPE), value); OP_ASSERT_PROPERTY_COUNT(this_object); return PROP_PUT_OK; } case GCTAG_ES_Special_Error_StackTrace: { OP_ASSERT(this_object->IsErrorObject()); ES_Error::StackTraceFormat format = static_cast<ES_Special_Error_StackTrace *>(this)->format; ES_Error::ErrorSpecialProperties property; JString *name = NULL; switch (format) { default: OP_ASSERT(!"I don't know nothing about that format."); /* fall through */ case ES_Error::FORMAT_READABLE: property = ES_Error::PROP_stacktrace; name = context->rt_data->idents[ESID_stacktrace]; break; case ES_Error::FORMAT_MOZILLA: property = ES_Error::PROP_stack; name = context->rt_data->idents[ESID_stack]; break; } BOOL needs_conversion = FALSE; ES_Class *old_klass = ES_Class::ActualClass(this_object->Class()); ES_Class *new_klass = ES_Class::ChangeAttribute(context, this_object->Class(), context->rt_data->idents[ESID_stacktrace], ES_Property_Info(DE, ES_LayoutIndex(format)), this_object->Count(), needs_conversion); ES_CollectorLock gclock(context); new_klass = ES_Class::ChangeAttribute(context, this_object->Class(), name, ES_Property_Info(DE, ES_LayoutIndex(format)), this_object->Count(), needs_conversion); this_object->ConvertObject(context, old_klass, new_klass); return this_object->PutCachedAtIndex(ES_PropertyIndex(property), value); } default: return PROP_PUT_OK; case GCTAG_ES_Special_RegExp_Capture: ES_RegExp_Constructor *ctor = static_cast<ES_RegExp_Constructor *>(this_object); unsigned index = static_cast<ES_Special_RegExp_Capture *>(this)->index; if (index == ES_RegExp_Constructor::INDEX_INPUT) ctor->PutCachedAtIndex(ES_PropertyIndex(ES_RegExp_Constructor::INPUT), value); else if (index == ES_RegExp_Constructor::INDEX_MULTILINE) ctor->SetMultiline(value.AsBoolean().GetBoolean()); return PROP_PUT_OK; } } GetResult ES_Special_Property::SpecialGetL(ES_Context *context, ES_Object *this_object, ES_Value_Internal &value, const ES_Value_Internal &this_value) { switch (GCTag()) { case GCTAG_ES_Special_Global_Variable: { OP_ASSERT(this_object->IsGlobalObject()); ES_Global_Object *global_object = static_cast<ES_Global_Object *>(this_object); unsigned index = static_cast<ES_Special_Global_Variable *>(this)->index; value = global_object->GetVariableValue(index); return PROP_GET_OK; } case GCTAG_ES_Special_Aliased: value = *static_cast<ES_Special_Aliased *>(this)->property; return PROP_GET_OK; case GCTAG_ES_Special_Mutable_Access: { if (!context) return PROP_GET_FAILED; ES_Execution_Context *exec_context = context->GetExecutionContext(); if (!exec_context || !exec_context->IsActive()) return PROP_GET_FAILED; ES_Object *getter = static_cast<ES_Special_Mutable_Access *>(this)->getter; if (getter == NULL) { value.SetUndefined(); return PROP_GET_OK; } ES_Value_Internal result; ES_Value_Internal *registers = exec_context->SetupFunctionCall(getter, /* argc = */ 0); registers[0] = this_value; registers[1].SetObject(getter); if (!exec_context->CallFunction(registers, /* argc = */ 0, &result)) return PROP_GET_FAILED; value = result; return PROP_GET_OK; } case GCTAG_ES_Special_Function_Name: { OP_ASSERT(this_object->IsFunctionObject()); JString *name = static_cast<ES_Function *>(this_object)->GetName(context); value.SetString(name); return PROP_GET_OK; } case GCTAG_ES_Special_Function_Length: { OP_ASSERT(this_object->IsFunctionObject()); ES_Function *function = static_cast<ES_Function *>(this_object); value.SetUInt32(function->GetLength()); return PROP_GET_OK; } case GCTAG_ES_Special_Function_Prototype: { OP_ASSERT(this_object->IsFunctionObject()); ES_Function *function = static_cast<ES_Function *>(this_object); ES_FunctionCode *fncode = function->GetFunctionCode(); if (fncode) { ES_Object *prototype = ES_Object::Make(context, fncode->global_object->GetFunctionPrototypeClass()); ES_CollectorLock gclock(context); prototype->PutCachedAtIndex(ES_PropertyIndex(0), this_object); SpecialPutL(context, this_object, prototype, this_value); value.SetObject(prototype); } else value.SetUndefined(); return PROP_GET_OK; } case GCTAG_ES_Special_Function_Arguments: { OP_ASSERT(this_object->IsFunctionObject()); ES_Execution_Context *exec_context = context->GetExecutionContext(); if (exec_context) { ES_Function *function = static_cast<ES_Function *>(this_object); ES_FunctionCode *fncode = function->GetFunctionCode(); if (fncode) { ES_FrameStackIterator frames(exec_context); while (frames.Next()) if (frames.GetCode() == fncode) { #ifdef ES_NATIVE_SUPPORT if (frames.IsFollowedByNative()) { frames.Next(); OP_ASSERT(frames.GetCode() == fncode); } #endif // ES_NATIVE_SUPPORT ES_Value_Internal *registers = frames.GetRegisterFrame(); ES_Arguments_Object *arguments = frames.GetArgumentsObject(); if (arguments ? arguments->GetFunction() == function : registers[1].GetObject() == function) { ES_FunctionCodeStatic *data = fncode->GetData(); if (data->arguments_index != ES_FunctionCodeStatic::ARGUMENTS_NOT_USED) { value = registers[data->arguments_index]; return PROP_GET_OK; } if (!arguments) { #ifdef ES_NATIVE_SUPPORT function->SetHasCreatedArgumentsArray(context); #endif // ES_NATIVE_SUPPORT arguments = ES_Arguments_Object::Make(context, function, registers, frames.GetArgumentsCount()); frames.SetArgumentsObject(arguments); } arguments->SetUsed(); value.SetObject(arguments); return PROP_GET_OK; } } } } value.SetNull(); return PROP_GET_OK; } case GCTAG_ES_Special_Function_Caller: { OP_ASSERT(this_object->IsFunctionObject()); ES_Execution_Context *exec_context = context->GetExecutionContext(); if (exec_context) { ES_Function *function = static_cast<ES_Function *>(this_object); if (ES_FunctionCode *fncode = function->GetFunctionCode()) { ES_FrameStackIterator frames(exec_context); while (frames.Next()) if (frames.GetCode() == fncode) { #ifdef ES_NATIVE_SUPPORT if (frames.IsFollowedByNative()) { frames.Next(); OP_ASSERT(frames.GetCode() == fncode); } #endif // ES_NATIVE_SUPPORT ES_Arguments_Object *arguments = frames.GetArgumentsObject(); if (arguments ? arguments->GetFunction() == function : frames.GetRegisterFrame()[1].GetObject() == function) { while (frames.Next()) if (ES_Code *code = frames.GetCode()) if (code->type == ES_Code::TYPE_FUNCTION && !code->is_strict_eval) { if (code->data->is_strict_mode) { exec_context->ThrowTypeError("Illegal property access"); return PROP_GET_FAILED; } value.SetObject(frames.GetRegisterFrame()[1].GetObject()); return PROP_GET_OK; } break; } } } } value.SetNull(); return PROP_GET_OK; } case GCTAG_ES_Special_RegExp_Capture: { ES_RegExp_Constructor *ctor = static_cast<ES_RegExp_Constructor *>(this_object); unsigned index = static_cast<ES_Special_RegExp_Capture *>(this)->index; switch (index) { case ES_RegExp_Constructor::INDEX_INPUT: ctor->GetCachedAtIndex(ES_PropertyIndex(ES_RegExp_Constructor::INPUT), value); break; case ES_RegExp_Constructor::INDEX_LASTMATCH: ctor->GetLastMatch(context, value); break; case ES_RegExp_Constructor::INDEX_LASTPAREN: ctor->GetLastParen(context, value); break; case ES_RegExp_Constructor::INDEX_LEFTCONTEXT: ctor->GetLeftContext(context, value); break; case ES_RegExp_Constructor::INDEX_RIGHTCONTEXT: ctor->GetRightContext(context, value); break; case ES_RegExp_Constructor::INDEX_MULTILINE: value.SetBoolean(ctor->GetMultiline()); break; default: ctor->GetCapture(context, value, index); } return PROP_GET_OK; } case GCTAG_ES_Special_Error_StackTrace: { ES_Error *error = static_cast<ES_Error *>(this_object); if (ES_Execution_Context *exec_context = context->GetExecutionContext()) value.SetString(error->GetStackTraceString(exec_context, NULL, static_cast<ES_Special_Error_StackTrace *>(this)->format, 0)); else value.SetNull(); return PROP_GET_OK; } default: OP_ASSERT(FALSE); value.SetUndefined(); return PROP_GET_OK; } } BOOL ES_Special_Property::WillCreatePropertyOnGet(ES_Object *this_object) const { return GCTag() == GCTAG_ES_Special_Function_Prototype && static_cast<ES_Function *>(this_object)->GetFunctionCode() != NULL; } /* static */ ES_Special_Mutable_Access *ES_Special_Mutable_Access::Make(ES_Context *context, ES_Function *ma_getter, ES_Function *ma_setter) { ES_Special_Mutable_Access *self; GC_ALLOCATE(context, self, ES_Special_Mutable_Access, (self, ma_getter, ma_setter)); return self; } /* static */ void ES_Special_Mutable_Access::Initialize(ES_Special_Mutable_Access *self, ES_Function *ma_getter, ES_Function *ma_setter) { self->InitGCTag(GCTAG_ES_Special_Mutable_Access); self->getter = ma_getter; self->setter = ma_setter; } /* static */ ES_Special_Aliased *ES_Special_Aliased::Make(ES_Context *context, ES_Value_Internal *alias) { ES_Special_Aliased *self; GC_ALLOCATE(context, self, ES_Special_Aliased, (self, alias)); return self; } /* static */ void ES_Special_Aliased::Initialize(ES_Special_Aliased *self, ES_Value_Internal *alias) { self->InitGCTag(GCTAG_ES_Special_Aliased); self->property = alias; } /* static */ ES_Special_Global_Variable *ES_Special_Global_Variable::Make(ES_Context *context, unsigned index) { ES_Special_Global_Variable *self; GC_ALLOCATE(context, self, ES_Special_Global_Variable, (self, index)); return self; } /* static */ void ES_Special_Global_Variable::Initialize(ES_Special_Global_Variable *self, unsigned index) { self->InitGCTag(GCTAG_ES_Special_Global_Variable); self->index = index; } /* static */ ES_Special_Function_Name *ES_Special_Function_Name::Make(ES_Context *context) { ES_Special_Function_Name *self; GC_ALLOCATE(context, self, ES_Special_Function_Name, (self)); return self; } /* static */ void ES_Special_Function_Name::Initialize(ES_Special_Function_Name *self) { self->InitGCTag(GCTAG_ES_Special_Function_Name); } /* static */ ES_Special_Function_Length *ES_Special_Function_Length::Make(ES_Context *context) { ES_Special_Function_Length *self; GC_ALLOCATE(context, self, ES_Special_Function_Length, (self)); return self; } /* static */ void ES_Special_Function_Length::Initialize(ES_Special_Function_Length *self) { self->InitGCTag(GCTAG_ES_Special_Function_Length); } /* static */ ES_Special_Function_Prototype *ES_Special_Function_Prototype::Make(ES_Context *context) { ES_Special_Function_Prototype *self; GC_ALLOCATE(context, self, ES_Special_Function_Prototype, (self)); return self; } /* static */ void ES_Special_Function_Prototype::Initialize(ES_Special_Function_Prototype *self) { self->InitGCTag(GCTAG_ES_Special_Function_Prototype); } /* static */ ES_Special_Function_Arguments *ES_Special_Function_Arguments::Make(ES_Context *context) { ES_Special_Function_Arguments *self; GC_ALLOCATE(context, self, ES_Special_Function_Arguments, (self)); return self; } /* static */ void ES_Special_Function_Arguments::Initialize(ES_Special_Function_Arguments *self) { self->InitGCTag(GCTAG_ES_Special_Function_Arguments); } /* static */ ES_Special_Function_Caller *ES_Special_Function_Caller::Make(ES_Context *context) { ES_Special_Function_Caller *self; GC_ALLOCATE(context, self, ES_Special_Function_Caller, (self)); return self; } /* static */ void ES_Special_Function_Caller::Initialize(ES_Special_Function_Caller *self) { self->InitGCTag(GCTAG_ES_Special_Function_Caller); } /* static */ ES_Special_RegExp_Capture *ES_Special_RegExp_Capture::Make(ES_Context *context, unsigned index) { ES_Special_RegExp_Capture *self; GC_ALLOCATE(context, self, ES_Special_RegExp_Capture, (self, index)); return self; } /* static */ void ES_Special_RegExp_Capture::Initialize(ES_Special_RegExp_Capture *self, unsigned index) { self->InitGCTag(GCTAG_ES_Special_RegExp_Capture); self->index = index; } /* static */ ES_Special_Error_StackTrace * ES_Special_Error_StackTrace::Make(ES_Context *context, ES_Error::StackTraceFormat format) { ES_Special_Error_StackTrace *self; GC_ALLOCATE(context, self, ES_Special_Error_StackTrace, (self, format)); return self; } /* static */ void ES_Special_Error_StackTrace::Initialize(ES_Special_Error_StackTrace *self, ES_Error::StackTraceFormat format) { self->InitGCTag(GCTAG_ES_Special_Error_StackTrace); self->format = format; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2006-2007 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * * Peter Krefting */ #include "core/pch.h" #include "modules/prefs/init/delayed_init.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" #include "modules/hardcore/mh/mh.h" #ifdef PREFS_DELAYED_INIT_NEEDED PrefsDelayedInit::PrefsDelayedInit() { } PrefsDelayedInit::~PrefsDelayedInit() { g_main_message_handler->UnsetCallBacks(this); } void PrefsDelayedInit::StartL() { LEAVE_IF_ERROR(g_main_message_handler->SetCallBack(this, MSG_PREFS_RECONFIGURE, 0)); g_main_message_handler->PostMessage(MSG_PREFS_RECONFIGURE, 0, 0); } void PrefsDelayedInit::HandleCallback(OpMessage msg, MH_PARAM_1, MH_PARAM_2) { // Opera is now initialized, and we can do whatever delayed configuration // we needed to make. if (msg == MSG_PREFS_RECONFIGURE) { #ifdef PREFS_VALIDATE TRAPD(rc2, g_pccore->DelayedInitL()); RAISE_IF_ERROR(rc2); #endif // PREFS_VALIDATE // This object is not needed any longer. OP_DELETE(this); g_opera->prefs_module.m_delayed_init = NULL; } } #endif // PREFS_DELAYED_INIT_NEEDED
/***************************************************************************//** * \brief * \copyright Michael Coutlakis 2021 * \license MIT License, see the LICENSE file. *******************************************************************************/ #pragma once #include <flatbuffers/flatbuffers.h> #include <boost/asio.hpp> //template<typename FlatBufferT> //boost::asio::const_buffer ToBuffer(const FlatBufferT& FlatBuf) //{ // // Serialize to buffer: // flatbuffers::FlatBufferBuilder builder; // builder.FinishSizePrefixed(std::remove_reference<decltype(FlatBuf)) // size_t uSize = 10; // void* pData = nullptr; // return boost::asio::const_buffer(pData, uSize); //} namespace dvis { inline flatbuffers::FlatBufferBuilder ToBuffer(const pkt::NetPacketT& packet) { // Serialize to buffer: flatbuffers::FlatBufferBuilder builder; builder.FinishSizePrefixed(pkt::NetPacket::Pack(builder, &packet)); return builder; } }
#ifndef ARRAY_H #define ARRAY_H #include "Punto.h" using namespace std; class PointArray{ private: Punto *points; int _size; void resize(const int x); public: PointArray(); PointArray(const Punto points[], const int _size); PointArray(const PointArray &p); ~PointArray(); void print(); void pushback(const Punto &p); void insert(const int pos, const Punto &p); void remove(const int pos); int getsize(); void clear(); const Punto get(const int) const; Punto get(const int); }; #endif // ARRAY_H
#pragma once class CSamplerState : Noncopyable { public: CSamplerState(); ~CSamplerState(); bool Create(const D3D11_SAMPLER_DESC& desc); /*! * @brief 明示的な開放処理。 */ void Release() { if (m_samplerState != nullptr) { m_samplerState->Release(); m_samplerState = nullptr; } } /*! * @brief サンプラステートを取得。 */ ID3D11SamplerState*& GetBody() { return m_samplerState; } private: ID3D11SamplerState * m_samplerState = nullptr; };
// Author : chenwj // Time : 2017/1/16 // Copyright :All rights reserved by chenwj @copyright 2017 ~ 2018. // // Use of this source code is governed by a BSD-style license // that can be found in the License file. //////////////////////////////////////////////////////////////////////// #ifndef _CODE_H_ #define _CODE_H_ #include <stdint.h> #include <memory.h> #include <string> using namespace std; // data encode and decode // format // | len | -- sizeof (int32_t) // | name len | -- sizeof (int32_t) // | msg name | -- name len (name len) // | body(protobuf data) | -- len - sizeof(int32_t) - sizeof(int32_t) - (name len) - sizeof(int32_t) // | check sum | -- sizeof (int32_t) namespace net{ class Coder { public: Coder(); ~Coder(); // set Msg name void setMsgName(const string& name); // set msg data (protobuf data) void setBody(const string& body); // encoding the data to buff void encoding(); // get the encoding buffer const string & getData(); // get Msg name string getMsgName(); // get msg data (protobuf data) string getBody(); // decoding the data from buff void decoding(const char * buff, int size); private: int buf_size_; int buf_index_; char * buf_; int32_t len_; int32_t name_len_; string msg_name_; string body_; int32_t check_sum_; string data_; }; // !class Coder } // !namespace net #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ #include "core/pch.h" #ifdef _PNG_SUPPORT_ #include "modules/zlib/zlib.h" #include "modules/minpng/minpng.h" #include "modules/minpng/png_int.h" #ifndef MINPNG_NO_GAMMA_SUPPORT static void _set_gamma(float gamma, minpng_state* s) { int i; if (gamma == 0.0) { return; } s->gamma = ((float)1.0) / gamma; if ((float)op_fabs(s->gamma - (float)1.0) < (float)0.01) { s->gamma = 0.0; return; } s->gamma_table[0] = 0; s->gamma_table[255] = 255; for (i = 1; i < 255; i++) s->gamma_table[i] = (int)(op_pow((float)(i * (1 / 255.0)), (float)s->gamma) * 255); } #endif #define NEW_IMAGE( X, Y, indexed ) _alloc_image(X,Y,indexed) void *_alloc_image(int w, int h, BOOL indexed) { // when indexed, add 8 bytes to handle "optimization" in _decode if(indexed) return OP_NEWA(UINT8, w * h + 8); return OP_NEWA(RGBAGroup, w * h); } static inline long _int_from_16bit(const unsigned char* data) { return (data[0] << 8) | (data[1]); } /* Faster as inline, but somewhat larger. Not called in time-critical code anyway. */ static unsigned long _int_from_32bit(const unsigned char* data) { return (data[0] << 24) | (data[1] << 16) | (data[2] << 8) | (data[3]); } // FIXME: If this was moved to a callback we could save quite a lot of // memory by not having a deinterlace buffer. static inline void _draw_rectangle_rgba(RGBAGroup *dest, int span, int width, int height, RGBAGroup col) { for (int y = 0; y < height; y++, dest += span) for (int x = 0; x < width; x++) dest[x]=col; } // FIXME: If this was moved to a callback we could save quite a lot of // memory by not having a deinterlace buffer. static inline void _draw_rectangle_indexed(UINT8 *dest, int span, int width, int height, UINT8 index) { for (int y = 0; y < height; y++, dest += span) for (int x = 0; x < width; x++) dest[x]=index; } // width and height checked not to overflow when multipled by values // smaller than 16 _or_ with eachother. static int convert_to_rgba(RGBAGroup* w1, int type, int bpp, unsigned char* s, long width, long height, minpng_palette* ct, minpng_trns* trns) { /* returns 1 if alpha channel, 0 if not */ RGBAGroup* d1 = w1; int i; int yp, x; if (ct && trns) for (i = 0; i < 256; i++) ct->palette[i].a = trns->str[i]; switch( type ) { case 0: /* 1,2,4,8 or 16 bit greyscale */ { int tcol = -1; if (trns && trns->len >= 2) tcol = _int_from_16bit(trns->str); #ifndef LIMITED_FOOTPRINT_DEVICE if (bpp == 8) { for (yp=0; yp < height; yp++) { s++; /* filter method. */ for (x = 0; x < width; x++, s++) { d1[x].a = *s != tcol ? 255 : 0; d1[x].r = d1[x].g = d1[x].b = *s; } d1 += width; } } else #endif if (bpp < 16) { /* Rather slow, but somewhat compact, routine for all bpp < 16 * It's not all _that_ slow either. */ unsigned int msk = (1 << bpp) - 1; /* unsigned int sft = bpp==4 ? 2 : bpp-1; */ for (yp = 0; yp < height; yp++) { s++; for (x = width; x > 0; s++) { for (i = 8-bpp; i >= 0 && x--; i -= bpp) { int c = ((*s) >> i) & msk; d1->r = d1->g = d1->b = (c * 255 / msk); d1->a = c == tcol ? 0 : 255; d1++; } } } } else { for (yp = 0; yp < height; yp++) { s++; for (x = 0; x < width; x++, s += 2) { int c = _int_from_16bit(s); d1[x].a = c != tcol ? 255 : 0; d1[x].r = d1[x].g = d1[x].b = c >> 8; } d1 += width; } } return tcol >= 0 ? 1 : 0; } case 2: /* 8 or 16 bit r,g,b */ { int tr = -1, tg = -1, tb = -1; if (trns && trns->len >= 6) { tr = _int_from_16bit(trns->str); tg = _int_from_16bit(trns->str + 2); tb = _int_from_16bit(trns->str + 4); } if (bpp == 8) { for (yp = 0; yp < height; yp++) { s++; for (x = 0; x < width; x++, d1++) { int r = *(s++); int g = *(s++); int b = *(s++); d1->r = r; d1->g = g; d1->b = b; d1->a = ((r == tr) && (g == tg) && (b == tb)) ? 0 : 255; } } } else { for (yp = 0; yp < height; yp++) { s++; for (x = 0; x < width; x++, d1++) { int r = _int_from_16bit(s), g = _int_from_16bit(s + 2), b = _int_from_16bit(s + 4); s += 6; d1->r = r >> 8; d1->g = g >> 8; d1->b = b >> 8; d1->a = ((r == tr) && (g == tg) && (b == tb)) ? 0 : 255; } } } return tr < 0 ? 0 : 1; } case 3: /* 1,2,4,8 bit palette index. Alpha might be in palette */ { unsigned int msk = (1 << bpp) - 1; for (yp = 0; yp < height; yp++) { s++; for (x = width; x > 0; s++) { for (i = 8 - bpp; i >= 0 && x--; i -= bpp) { unsigned char col_idx = ((*s) >> i) & msk; if (col_idx < ct->size) *(d1++) = ct->palette[col_idx]; else { RGBAGroup black = { 0,0,0,255 }; *(d1++) = black; } } } } return !!trns; /* Alpha channel if trns chunk. */ } case 4: /* 8 or 16 bit grey,a */ if (bpp == 8) { for (yp = 0; yp < height; yp++) { s++; for (x = 0; x < width; x++) { d1->r = d1->g = d1->b = s[0]; (d1++)->a = s[1]; s += 2; } } } else { for (yp = 0; yp < height; yp++) { s++; for (x = 0; x < width; x++) { d1->r = d1->g = d1->b = s[0]; (d1++)->a = s[2]; s += 4; } } } return 1; case 6: /* 8 or 16 bit r,g,b,a */ if (bpp == 8) { for (yp = 0; yp < height; yp++) { s++; for (x = 0; x < width; x++) { d1->r = s[0]; d1->g = s[1]; d1->b = s[2]; (d1++)->a = s[3]; s += 4; } } return 1; } else { for (yp = 0; yp < height; yp++) { s++; for (x = 0; x < width; x++) { d1->r = s[0]; d1->g = s[2]; d1->b = s[4]; (d1++)->a = s[6]; s += 8; } } } return 1; /* always alpha channel */ } return -1; } static void _defilter(minpng_buffer* ps, unsigned int linew, unsigned int height, char type, char bpp, unsigned int* last_line, unsigned int* left, unsigned char** line_start) { unsigned char* row; unsigned int len = ps->size(); unsigned int yp, xp; unsigned int bps; char upp = 1; /* -1 in an unsigned. This is ok here, and is used to indicate * that not a single line was decoded. last_line=0 means that one * line was decoded, namely line number 0. */ *last_line = (unsigned int)-1; *left = len; if (!(type & 1)) /* This generated 16 bytes smaller code than a switch. :-) */ { if (type & 4) upp += 1; if(type & 2) upp+=2; } bpp *= upp; /* multipy for units/pixel (rgba=4, grey=1, etc) */ linew = (linew*bpp+7) >> 3; /* linew in bytes (round up to even bytes) */ bps = (bpp + 7) >> 3; /* bytes per sample up */ if (len < (linew + 1) * MIN(height, 2)) return; row = ps->ptr(); if (len >= (linew + 1) * height) /* Whole image is in there. */ { *last_line = height - 1; *line_start = row + (height) * (linew + 1); *left -= (linew + 1) * (height); } else { height = len / (linew + 1); *last_line = len / (linew + 1) - 2; *line_start = row + (height - 1) * (linew + 1); *left -= (linew + 1) * (height - 1); } for (yp = 0; yp < height; yp++, row += linew + 1) { unsigned char *d = row + 1; switch (*row) // Defilter a single row of data. { case 0: /* No filter */ break; case 1: /* Subtract left. */ d += bps; for ( xp = bps; xp < linew; xp++, d++) *d = d[0] + d[-(int)bps]; break; case 2: /* Subtract up. */ if (!yp) break; // Ignore if it's the first line... for (xp = 0; xp < linew; xp++) d[xp] += d[(int)xp - (int)linew - 1]; break; case 3: /* Average left/up. */ if (yp > 0) for (xp = 0; xp < linew; xp++, d++) *d += (d[-((int)linew + 1)] + (xp < bps ? 0 : d[-(int)bps])) >> 1; else for (xp = bps; xp < linew; xp++) d[xp] += d[(int)xp - (int)bps] >> 1; break; case 4: /* paeth (left up) */ for (xp = 0 ; xp < linew; xp++, d++) { int a, q, c, pa, pb, pc; if (xp >= (unsigned)bps) a = d[-(int)bps]; else a = 0; if (yp > 0) { q = d[-(int)(linew + 1)]; if (xp >= (unsigned)bps) c = d[-(int)linew - 1 - (int)bps]; else c = 0; pa= (q - c); if (pa < 0) pa = -pa; } else pa = c = q = 0; pb = (a - c); if (pb < 0) pb = -pb; pc = (a + q - (c << 1)); if (pc < 0) pc = -pc; if (pa <= pb && pa <= pc) *d += a; else if (pb <= pc) *d += q; else *d += c; } break; } // Set filter to 0 for this row for the next pass, if any. // Sometimes rows are looked at twice with the current algorithm. *row = 0; } return; } static unsigned int _decode(minpng_state* s, PngRes* res, int width, int height) { int last_line, left; unsigned char* line_start = 0; _defilter(&s->uncompressed_data, width, height, s->ihdr.type, s->ihdr.bpp, (unsigned int*)&last_line, (unsigned int*)&left, &line_start); last_line++; res->image_data.data = 0; res->lines = last_line; if (last_line) /* At least one line decoded. */ { res->image_data.data = NEW_IMAGE(width, last_line, s->output_indexed); res->nofree_image = 0; if (!res->image_data.data) return (unsigned int)-1; res->first_line = s->first_line; s->first_line += last_line; if(s->output_indexed) { int bpp = s->ihdr.bpp; res->has_alpha = FALSE; if(bpp == 8) // just copy indexed data for(int y=0;y<last_line;y++) op_memcpy(res->image_data.indexed + y*width, s->uncompressed_data.ptr() + y*(width+1) + 1, width); else // unpack packed bytes { int per_byte = 8 / bpp; int packed_line_bytes = (width / per_byte) + ((width%per_byte) ? 1 : 0); for(int y=0;y<last_line;y++) { UINT8 *src = (UINT8*)(s->uncompressed_data.ptr() + y*(packed_line_bytes+1) + 1); UINT8 *dst = res->image_data.indexed + y*width; for(int x=0;x<packed_line_bytes;x++) { UINT8 pattern = ~((UINT8)(-1) >> bpp); int to_shift = 8 - bpp; /* Yes... we added some extra bytes while allocating res->image in order to * allow some "overflow" here (<= 7 bytes) */ for(int i=0;i<per_byte;i++) { *(dst++) = ((*src) & pattern) >> to_shift; pattern >>= bpp; to_shift -= bpp; } src++; } } } } else { res->has_alpha = convert_to_rgba(res->image_data.rgba, s->ihdr.type, s->ihdr.bpp, s->uncompressed_data.ptr(), width, last_line, s->ct, s->trns); #ifndef MINPNG_NO_GAMMA_SUPPORT // if s->ihdr.type == 3, then has gamma already been adjusted if (!s->ignore_gamma && s->gamma != 0.0 && s->ihdr.type != 3) { int i; for (i = 0; i < width * last_line; i++) { res->image_data.rgba[i].r = s->gamma_table[res->image_data.rgba[i].r]; res->image_data.rgba[i].g = s->gamma_table[res->image_data.rgba[i].g]; res->image_data.rgba[i].b = s->gamma_table[res->image_data.rgba[i].b]; } } #endif } s->uncompressed_data.consume(line_start-s->uncompressed_data.ptr()); } return last_line; } /* Only used once, thus inline and here. */ static inline minpng_palette* _palette_new(int size, unsigned char* data) { minpng_palette* t = OP_NEW(minpng_palette, ()); if (!t) return 0; int i; t->size = size; for (i = 0; i < size; i++) { t->palette[i].a = 255; t->palette[i].r = *(data++); t->palette[i].g = *(data++); t->palette[i].b = *(data++); } return t; } static inline PngRes::Result on_first_idat_found(minpng_state *s) { #ifndef MINPNG_NO_GAMMA_SUPPORT if(s->image_frame_data_pal && s->gamma != 0.0) { for(int i=s->pal_size-1;i>=0;i--) { s->image_frame_data_pal[i*3+0] = s->gamma_table[s->image_frame_data_pal[i*3+0]]; s->image_frame_data_pal[i*3+1] = s->gamma_table[s->image_frame_data_pal[i*3+1]]; s->image_frame_data_pal[i*3+2] = s->gamma_table[s->image_frame_data_pal[i*3+2]]; } } #endif if(s->ihdr.type == 3 && !s->image_frame_data_pal) { return PngRes::ILLEGAL_DATA; } OP_ASSERT(!s->output_indexed || (!s->trns && (s->ihdr.type == 3 || (s->ihdr.type == 0 && s->ihdr.bpp <= 8)))); if(s->output_indexed && s->ihdr.type == 0) { int indexes = 1 << s->ihdr.bpp; s->pal_size = indexes; s->image_frame_data_pal = OP_NEWA(UINT8, indexes*3); if (!s->image_frame_data_pal) { return PngRes::OOM_ERROR; } #ifndef MINPNG_NO_GAMMA_SUPPORT if(s->gamma != 0.0) { for(int i=0;i<indexes;i++) { UINT8 val = (UINT8)(s->gamma_table[(255*i) / (indexes-1)]); s->image_frame_data_pal[i*3+0] = val; s->image_frame_data_pal[i*3+1] = val; s->image_frame_data_pal[i*3+2] = val; } } else #endif { for(int i=0;i<indexes;i++) { UINT8 val = (UINT8)((i*255) / (indexes-1)); s->image_frame_data_pal[i*3+0] = val; s->image_frame_data_pal[i*3+1] = val; s->image_frame_data_pal[i*3+2] = val; } } } else if(!s->output_indexed && s->ihdr.type == 3) { s->ct = _palette_new(s->pal_size,s->image_frame_data_pal); if(!s->ct) { return PngRes::OOM_ERROR; } OP_DELETEA(s->image_frame_data_pal); s->image_frame_data_pal = NULL; } #ifdef APNG_SUPPORT if(!s->is_apng) #endif { s->frame_index = 0; } s->first_idat_found = TRUE; return PngRes::OK; } #ifdef EMBEDDED_ICC_SUPPORT static inline PngRes::Result on_icc_profile_found(minpng_state* s, PngRes* res, unsigned char* icc_data, int icc_data_len) { minpng_zbuffer zbuf; PngRes::Result png_res = zbuf.init(); if (png_res != PngRes::OK) return png_res; if (zbuf.append(icc_data_len, icc_data) != 0) return PngRes::OOM_ERROR; if (!s->buf) { s->buf = OP_NEWA(unsigned char, MINPNG_BUFSIZE); if (!s->buf) { return PngRes::OOM_ERROR; } } minpng_buffer decomp_icc_data; do { int res = zbuf.read(s->buf, MINPNG_BUFSIZE); if (res <= 0) return res == minpng_zbuffer::Oom ? PngRes::OOM_ERROR : PngRes::ILLEGAL_DATA; if (decomp_icc_data.append(res, s->buf) != 0) return PngRes::OOM_ERROR; } while (zbuf.size()); // Put data in result res->icc_data = decomp_icc_data.ptr(); res->icc_data_len = decomp_icc_data.size(); // The result now owns the data decomp_icc_data.release(); #ifndef MINPNG_NO_GAMMA_SUPPORT // If gamma has been set, disable it s->gamma = 0.0; #endif return PngRes::OK; } #endif #define CONSUME(X) do { s->consumed += (X); data += (X); len -= (X); } while(0) static const interlace_state adam7[8] = { {0,8,8, 0,8,8}, {0,8,8, 4,8,4}, {4,8,4, 0,4,4}, {0,4,4, 2,4,2}, {2,4,2, 0,2,2}, {0,2,2, 1,2,1}, {1,2,1, 0,1,1} }; PngRes::Result minpng_decode(PngFeeder* feed_me, PngRes* res) { minpng_state* s; unsigned char* data; unsigned int len; if (!feed_me->state) { feed_me->state = s = minpng_state::construct(); if (!s) return PngRes::OOM_ERROR; #ifndef MINPNG_NO_GAMMA_SUPPORT _set_gamma(((float)feed_me->screen_gamma) * (float)(1.0 / 2.2), s ); #endif } else s = (minpng_state*)feed_me->state; s->ignore_gamma = feed_me->ignore_gamma; res->lines = 0; res->draw_image = TRUE; if (s->consumed) { s->current_chunk.consume(s->consumed); s->consumed = 0; } // Skip extra malloc/switch/copy/free step. if (feed_me->len) { if (s->state == STATE_IDAT) { int cons = MIN(s->more_needed, feed_me->len); if (cons) { if (s->compressed_data.append(cons, feed_me->data)) { return PngRes::OOM_ERROR; } feed_me->len -= cons; s->more_needed -= cons; feed_me->data += cons; if(!s->more_needed) s->state = STATE_CRC; } } /* Check again, data consumed above.*/ if (feed_me->len) { if (s->current_chunk.append(feed_me->len, feed_me->data)) { return PngRes::OOM_ERROR; } feed_me->len = 0; } } data = s->current_chunk.ptr(); len = s->current_chunk.size(); while (len) { switch (s->state) { case STATE_INITIAL: /* No header read yet. */ if (len < 8 + 8 + 13 + 4 + 8) { /* Header and IHDR size, and size of next chunk header. */ return PngRes::NEED_MORE; /* return directly, no received data. */ } if (data[0] != 137 || data[1] != 'P' || data[2] != 'N' || data[3] != 'G' || data[4] != 13 || data[5] != 10 || data[6] != 26 || data[7]!=10) { return PngRes::ILLEGAL_DATA; } else { int id = _int_from_32bit(data + 12); unsigned char bpp, type; s->more_needed = _int_from_32bit(data + 8); if (id != 0x49484452 || s->more_needed != 13) {/* IHDR */ return PngRes::ILLEGAL_DATA; } s->mainframe_x = _int_from_32bit(data + 16); s->mainframe_y = _int_from_32bit(data + 20); bpp = s->ihdr.bpp = data[24]; type = s->ihdr.type = data[25]; // Verify that there will be no overflows. // FIXME: This is not really true. (returning OOM // for images larger than ~2G). We limit to 2Gb to // avoid signed integer overflow in any routines. s->pixel_count = (float)s->mainframe_x * (float)s->mainframe_y * (float)4.0; if (s->pixel_count > 2.0e9 || (s->mainframe_x > (1 << 25)) || (s->mainframe_y > (1 << 25))) { return PngRes::OOM_ERROR; } s->rect.Set(0, 0, s->mainframe_x, s->mainframe_y); // Check bpp and type. // From the spec: // Color Allowed Interpretation // Type Bit Depths // // 0 1,2,4,8,16 Each pixel is a grayscale sample. // // 2 8,16 Each pixel is an R,G,B triple. // // 3 1,2,4,8 Each pixel is a palette index; // a PLTE chunk must appear. // // 4 8,16 Each pixel is a grayscale sample, // followed by an alpha sample. // // 6 8,16 Each pixel is an R,G,B triple, // followed by an alpha sample. switch (type) { case 2: case 4: case 6: if (bpp != 8 && bpp != 16) { return PngRes::ILLEGAL_DATA; } break; case 0: case 3: if (bpp != 8 && bpp != 4 && bpp != 2 && bpp != 1 && (type || bpp != 16 )) { return PngRes::ILLEGAL_DATA; } #if defined(SUPPORT_INDEXED_OPBITMAP) if(bpp <= 8) { s->output_indexed = TRUE; } #endif break; default: return PngRes::ILLEGAL_DATA; } // Check compression. Must be 0 if (data[26] != 0) { return PngRes::ILLEGAL_DATA; } // Check filter. Must be 0. if (data[27] != 0) { return PngRes::ILLEGAL_DATA; } s->ihdr.interlace = data[28]; CONSUME(13 + 4 + 8 + 8); } /* Fallthrough.. */ case STATE_CHUNKHEADER: /* Reading generic chunk header. */ if (len < 8) goto decode_received_data; { ChunkID id = (ChunkID)_int_from_32bit(data + 4); s->more_needed = _int_from_32bit(data); CONSUME(8); switch (id) { case CHUNK_PLTE: s->state = STATE_PLTE; if (s->ct || s->image_frame_data_pal || s->ihdr.type != 3) s->state = STATE_IGNORE; // Already have one, or no needed. break; case CHUNK_IDAT: if(!s->first_idat_found) { PngRes::Result result = on_first_idat_found(s); // sets s->first_idat_found=TRUE if(result != PngRes::OK) return result; } #ifdef APNG_SUPPORT if(s->is_apng && s->apng_seq == 0) { // This is the default-frame which should be ignored (no fcTL found before this IDAT) s->state = STATE_IGNORE; } else #endif { s->state = STATE_IDAT; } break; case CHUNK_tRNS: s->state = s->first_idat_found ? STATE_IGNORE : STATE_tRNS; break; #ifndef MINPNG_NO_GAMMA_SUPPORT case CHUNK_gAMA: s->state = STATE_gAMA; // Long enough? if (s->more_needed < 4) s->state = STATE_IGNORE; #ifdef EMBEDDED_ICC_SUPPORT // If an ICC profile is present we use that instead if (s->first_iccp_found) s->state = STATE_IGNORE; #endif // EMBEDDED_ICC_SUPPORT break; #endif #ifdef EMBEDDED_ICC_SUPPORT case CHUNK_iCCP: s->state = s->first_iccp_found ? STATE_IGNORE : STATE_iCCP; break; #endif #ifdef APNG_SUPPORT case CHUNK_fdAT: s->state = STATE_fdAT; break; case CHUNK_fcTL: s->state = STATE_fcTL; break; case CHUNK_acTL: s->state = s->is_apng ? STATE_IGNORE : STATE_acTL; break; /* Fallthrough */ #endif default: s->state = STATE_IGNORE; break; } break; } #ifndef MINPNG_NO_GAMMA_SUPPORT case STATE_gAMA: /* gAMA */ if (len < s->more_needed) goto decode_received_data; _set_gamma((float)(_int_from_32bit(data) / 100000.0) * (float)(feed_me->screen_gamma), s); CONSUME(s->more_needed); s->state = STATE_CRC; break; #endif #ifdef EMBEDDED_ICC_SUPPORT case STATE_iCCP: /* iCCP chunk */ { if (len < s->more_needed) goto decode_received_data; unsigned char* icc_data = data; int icc_data_len = s->more_needed; while (*icc_data && icc_data_len != 0) icc_data++, icc_data_len--; if (icc_data_len > 2 && *(icc_data+1) == 0) { if (on_icc_profile_found(s, res, icc_data+2, icc_data_len-2) == PngRes::OOM_ERROR) return PngRes::OOM_ERROR; s->first_iccp_found = TRUE; } CONSUME(s->more_needed); s->state = STATE_CRC; break; } #endif case STATE_PLTE: /* PLTE chunk */ if (len < s->more_needed) goto decode_received_data; // We only support at most 256 entries in the // palette (as per the specification, incidentally). s->pal_size = MIN(s->more_needed/3,256); s->image_frame_data_pal = OP_NEWA(UINT8, s->pal_size*3); if (!s->image_frame_data_pal) { return PngRes::OOM_ERROR; } op_memcpy(s->image_frame_data_pal,data,s->pal_size*3); CONSUME(s->more_needed); s->state = STATE_CRC; break; #ifdef APNG_SUPPORT case STATE_acTL: if (len < s->more_needed) goto decode_received_data; s->is_apng = TRUE; s->num_frames = _int_from_32bit(data); if(!s->num_frames) return PngRes::ILLEGAL_DATA; s->num_iterations = _int_from_32bit(data+4); CONSUME(s->more_needed); s->state = STATE_CRC; break; case STATE_fcTL: { if (len < s->more_needed) goto decode_received_data; if(s->more_needed < 26) return PngRes::ILLEGAL_DATA; if(s->compressed_data.size()) // We're not finished with the previous frame, continue to decode that one instead goto decode_received_data; if(s->frame_index != s->last_finished_index) // frame_index is the index for the previous frame return PngRes::ILLEGAL_DATA; // The previous frame didn't contain all the data it was supposed to if(_int_from_32bit(data) != s->apng_seq++) return PngRes::ILLEGAL_DATA; unsigned int apng_rect_x = _int_from_32bit(data+12); unsigned int apng_rect_y = _int_from_32bit(data+16); unsigned int apng_rect_w = _int_from_32bit(data+4); unsigned int apng_rect_h = _int_from_32bit(data+8); s->pixel_count += (float)apng_rect_w * (float)apng_rect_h * (float)4.0; if (s->pixel_count > 2.0e9 || (apng_rect_w > (1 << 25)) || (apng_rect_h > (1 << 25))) { return PngRes::OOM_ERROR; } // Make sure the frame rect is inside the image (first check x/y agains max width/height to avoid overflows) if ((apng_rect_x > (1 << 25)) || (apng_rect_y > (1 << 25)) || ((apng_rect_x + apng_rect_w) > s->mainframe_x) || ((apng_rect_y+apng_rect_h) > s->mainframe_y)) return PngRes::ILLEGAL_DATA; s->frame_index++; s->rect.Set(apng_rect_x, apng_rect_y, apng_rect_w, apng_rect_h); s->adam_7_state = 0; if(s->compressed_data.re_init()) return PngRes::OOM_ERROR; int numerator = _int_from_16bit(data+20); int denom = _int_from_16bit(data+22); if(!denom) { // Spec says: If the denominator is 0, it is to be treated as if it were 100 denom = 100; } if (!numerator) { // Spec says: If the value of the numerator is 0 the decoder should render the next frame as quickly as possible, though viewers may impose a reasonable lower bound. // Firefox 3.0b3 seems to implement a lower bound when numerator < 10 (demon 1000) but allow faster speed than the lower bound if numerator > 10. I'm not clear exactly // how and if we should do the same. s->duration = 10; } else s->duration = (100*numerator)/denom; if(data[24] == 1) s->disposal_method = DISPOSAL_METHOD_RESTORE_BACKGROUND; else if(data[24] == 2) s->disposal_method = DISPOSAL_METHOD_RESTORE_PREVIOUS; else s->disposal_method = DISPOSAL_METHOD_DO_NOT_DISPOSE; s->blend = data[25] != 0; CONSUME(s->more_needed); s->state = STATE_CRC; break; } case STATE_fdAT: // Sequence-nr + IDAT content // Though perhaps a bit vague, // https://wiki.mozilla.org/APNG_Specification seems to // strongly imply that an fdAT chunk must never appear before // the first IDAT chunk. // // We also perform some initialization upon seeing the first // IDAT (in on_first_idat_found()), which if not done triggers // CORE-34284 upon processing the first fdAT. if(!s->first_idat_found) return PngRes::ILLEGAL_DATA; if(s->more_needed < 4) return PngRes::ILLEGAL_DATA; if(s->frame_index == s->last_finished_index) return PngRes::ILLEGAL_DATA; // We havn't got any fcTL preceding this fdAT if (len < 4) goto decode_received_data; if(_int_from_32bit(data) != s->apng_seq++) return PngRes::ILLEGAL_DATA; s->more_needed -= 4; CONSUME(4); s->state = s->more_needed ? STATE_IDAT : STATE_CRC; break; #endif // APNG_SUPPORT case STATE_IDAT: { int cons = MIN(s->more_needed,len); if (s->compressed_data.append(cons, data)) { return PngRes::OOM_ERROR; } s->more_needed -= cons; CONSUME(cons); if (!s->more_needed) { s->state = STATE_CRC; break; } else goto decode_received_data; } case STATE_tRNS: if (len < s->more_needed) goto decode_received_data; #if defined(SUPPORT_INDEXED_OPBITMAP) if(s->ihdr.type == 3 && s->more_needed == 1 && data[0] == 0) { s->has_transparent_col = TRUE; s->transparent_index = 0; CONSUME(1); s->state = STATE_CRC; break; } if(s->ihdr.type == 0 && s->image_frame_data_pal && s->more_needed == 2) { s->has_transparent_col = TRUE; s->transparent_index = data[1]; CONSUME(1); s->state = STATE_CRC; break; } s->output_indexed = FALSE; #endif s->trns = OP_NEW(minpng_trns, ()); /* simplifies code elsewhere. */ if (!s->trns) { return PngRes::OOM_ERROR; } s->trns->len = len; // We only support at most 256 entries in the // transparent table (as per the // specification, incidentally). { int trnslen = MIN(256, s->more_needed); op_memcpy(s->trns->str, data, trnslen); op_memset(s->trns->str + trnslen, 255, 256 - trnslen); CONSUME(s->more_needed); s->state = STATE_CRC; } break; case STATE_IGNORE: /* Ignore chunk. */ { int cons = MIN(s->more_needed, len); CONSUME(cons); s->more_needed -= cons; if (s->more_needed) goto decode_received_data; s->state = STATE_CRC; } // break; case STATE_CRC: /* CRC */ if (len < 4) goto decode_received_data; CONSUME(4); s->state = STATE_CHUNKHEADER; break; } } decode_received_data: { unsigned int last_line; if (s->ihdr.type == 3 && !s->ct && !s->image_frame_data_pal) return PngRes::NEED_MORE; if (!s->compressed_data.size()) return PngRes::NEED_MORE; OP_ASSERT(s->first_idat_found); if (!s->buf) { s->buf = OP_NEWA(unsigned char, MINPNG_BUFSIZE); if (!s->buf) { return PngRes::OOM_ERROR; } } int bytes = s->compressed_data.read(s->buf, MINPNG_BUFSIZE); if (bytes <= 0) { if (bytes == minpng_zbuffer::Oom) { return PngRes::OOM_ERROR; } else if (bytes == minpng_zbuffer::IllegalData) { return PngRes::ILLEGAL_DATA; } else if (bytes == minpng_zbuffer::Eof) // There was "junk" after end of zlib-stream in IDAT { return PngRes::ILLEGAL_DATA; } else { OP_ASSERT(bytes == 0); if(s->first_line == unsigned(s->rect.height)) { // only ending zlib-data left (termination-symbol, adler-checksum...) #if !defined(APNG_SUPPORT) OP_ASSERT(FALSE); #endif s->compressed_data.re_init(); return PngRes::AGAIN; } // we're before the actual data in the zlib-stream - or can't process even a single symbol, // might be if input-data is max 2 bytes. return PngRes::NEED_MORE; } } else if (s->uncompressed_data.append(bytes, s->buf)) { return PngRes::OOM_ERROR; } PngRes::Result more_res = s->compressed_data.size() > 0 ? PngRes::AGAIN : PngRes::NEED_MORE; #ifdef APNG_SUPPORT if(s->state == STATE_fcTL) more_res = PngRes::AGAIN; #endif /* --- fill in info in the result struct. --- */ res->depth = s->ihdr.bpp; int upp = 1; if (!(s->ihdr.type & 1)) /* This generated 16 bytes smaller code than a switch. :-) */ { if (s->ihdr.type & 4) upp += 1; if (s->ihdr.type & 2) upp += 2; } res->depth *= upp; res->mainframe_x = s->mainframe_x; res->mainframe_y = s->mainframe_y; res->rect = s->rect; #ifdef APNG_SUPPORT res->num_iterations = s->num_iterations; res->duration = s->duration; res->disposal_method = s->disposal_method; res->blend = s->blend; #endif res->num_frames = s->num_frames; res->frame_index = s->frame_index; res->image_frame_data_pal = s->image_frame_data_pal; res->has_transparent_col = s->has_transparent_col; res->transparent_index = s->transparent_index; res->pal_colors = s->pal_size; res->interlaced = !!s->ihdr.interlace; if (!s->ihdr.interlace) { /* FIXME: Here it's possible to do row-by-row * writing. There is really no need for the image buffer. */ last_line = _decode(s, res, s->rect.width, s->rect.height - s->first_line); if (res->has_alpha == -1) { return PngRes::ILLEGAL_DATA; } if ((int)last_line == -1) { return PngRes::OOM_ERROR; } if (s->rect.height-s->first_line) return more_res; #ifdef APNG_SUPPORT s->last_finished_index = s->frame_index; if(s->compressed_data.size()) // It seems like we where given to much data s->compressed_data.re_init(); if(s->num_frames > s->frame_index+1) { s->first_line = 0; return more_res; } #endif return PngRes::OK; } else { if (s->rect.width * s->rect.height > (int)(s->deinterlace_image_pixels)) { if(s->deinterlace_image.data) { if(s->output_indexed) OP_DELETEA(s->deinterlace_image.indexed); else OP_DELETEA(s->deinterlace_image.rgba); } s->deinterlace_image.data = NEW_IMAGE(s->rect.width, s->rect.height, s->output_indexed); // FIXME: _could_ be>>1 on height. if (!s->deinterlace_image.data) { return PngRes::OOM_ERROR; } s->deinterlace_image_pixels = s->rect.width * s->rect.height; } res->first_line = 0; for (; s->adam_7_state < 7; s->adam_7_state++) { int st = s->adam_7_state; unsigned int y0 = adam7[st].y0; unsigned int x0 = adam7[st].x0; unsigned int xw = adam7[st].xd; unsigned int yw = adam7[st].yd; unsigned int ys = adam7[st].ys; unsigned int xs = adam7[st].xs; unsigned int iwidth =(s->rect.width - x0 + xw - 1) / xw; unsigned int iheight=(s->rect.height - y0 + yw - 1) / yw; int old_first = res->first_line; int old_lines = res->lines; if (!iwidth || !iheight) continue; last_line = _decode(s, res, iwidth, iheight - s->first_line); if ((int)last_line == -1) { return PngRes::OOM_ERROR; } res->first_line = old_first; res->lines = old_lines; if (res->has_alpha == -1) { return PngRes::ILLEGAL_DATA; } if (last_line) // We have res->image_data... else NULL { unsigned int sy = 0; unsigned int row = y0 + (s->first_line - last_line) * yw; if(s->output_indexed) { UINT8 *src = res->image_data.indexed; UINT8 *dest; while (row < unsigned(s->rect.height) && sy < last_line) { unsigned int sx = 0; unsigned int yh = MIN(ys, s->rect.height - row); UINT8* dend; dest = s->deinterlace_image.indexed + row * s->rect.width + x0; dend = dest + s->rect.width - x0; #ifdef APNG_SUPPORT if(s->is_apng) { while(dest < dend) { *dest = src[sx++]; dest += xw; } } else #endif { while (dest < dend) { /* FIXME: This method (or a similar one) could be ** implemented in the 'res' struct, thus skipping the ** need for the deinterlaced image buffer completely. */ _draw_rectangle_indexed(dest, s->rect.width, MIN((int)xs, dend-dest), yh, src[sx++]); dest += xw; } } sy++; row += yw; src += iwidth; } OP_DELETEA(res->image_data.indexed); } else { RGBAGroup *src = res->image_data.rgba; RGBAGroup *dest; while (row < unsigned(s->rect.height) && sy < last_line) { unsigned int sx = 0; unsigned int yh = MIN(ys, s->rect.height - row); RGBAGroup* dend; dest = s->deinterlace_image.rgba + row * s->rect.width + x0; dend = dest + s->rect.width - x0; #ifdef APNG_SUPPORT if(s->is_apng) { while(dest < dend) { *dest = src[sx++]; dest += xw; } } else #endif { while (dest < dend) { /* FIXME: This method (or a similar one) could be ** implemented in the 'res' struct, thus skipping the ** need for the deinterlaced image buffer completely. */ _draw_rectangle_rgba(dest, s->rect.width, MIN((int)xs, dend-dest), yh, src[sx++]); dest += xw; } } sy++; row += yw; src += iwidth; } OP_DELETEA(res->image_data.rgba); } if (res->lines) { unsigned int num_lines = MAX(y0 + s->first_line * yw, res->first_line + res->lines); if (num_lines > unsigned(s->rect.height)) num_lines = s->rect.height; res->first_line = MIN(res->first_line, y0 + (s->first_line - last_line) * yw); res->lines = num_lines-res->first_line; } else { res->first_line = y0 + (s->first_line - last_line) * yw; res->lines = MIN((y0 + s->first_line * yw), unsigned(res->rect.height)) - res->first_line; } } res->nofree_image = 1; if(s->output_indexed) { OP_ASSERT(res->image_frame_data_pal); res->image_data.indexed = s->deinterlace_image.indexed + res->first_line * res->rect.width; } else { OP_ASSERT(!res->image_frame_data_pal); res->image_data.rgba = s->deinterlace_image.rgba + res->first_line * res->rect.width; } if (s->first_line < iheight) { #ifdef APNG_SUPPORT if(s->is_apng) { res->draw_image = FALSE; minpng_clear_result(res); } #endif return more_res; } else { s->first_line = 0; } } #ifdef APNG_SUPPORT if(s->is_apng) { s->last_finished_index = s->frame_index; if(s->compressed_data.size()) // It seems like we where given to much data s->compressed_data.re_init(); OP_ASSERT(res->nofree_image && res->draw_image); res->image_data.data = s->deinterlace_image.data; res->first_line = 0; res->lines = res->rect.height; if(res->frame_index < s->num_frames - 1) return more_res; } #endif return PngRes::OK; } } } void minpng_clear_result(PngRes* res) { if (!res->nofree_image) { if(res->image_frame_data_pal) OP_DELETEA(res->image_data.indexed); else OP_DELETEA(res->image_data.rgba); } #ifdef EMBEDDED_ICC_SUPPORT OP_DELETEA(res->icc_data); #endif // EMBEDDED_ICC_SUPPORT minpng_init_result(res); } void minpng_clear_feeder(PngFeeder* res) { OP_DELETE((minpng_state*)res->state); res->state = NULL; } void minpng_init_result(PngRes* res) { op_memset(res, 0, sizeof(PngRes)); } void minpng_init_feeder(PngFeeder* res) { op_memset(res, 0, sizeof(PngFeeder)); res->screen_gamma = 2.2; } minpng_state::~minpng_state() { OP_DELETE(ct); OP_DELETE(trns); if(output_indexed) OP_DELETEA(deinterlace_image.indexed); else OP_DELETEA(deinterlace_image.rgba); OP_DELETEA(buf); OP_DELETEA(image_frame_data_pal); } minpng_state* minpng_state::construct() { minpng_state* state = OP_NEW(minpng_state, ()); if (state == NULL) return NULL; PngRes::Result res = state->init(); if (res == PngRes::OK) // Take care of different errors later. return state; OP_DELETE(state); return NULL; } PngRes::Result minpng_state::init() { return compressed_data.init(); } minpng_state::minpng_state() { more_needed = consumed = first_line = 0; state = adam_7_state = 0; pal_size = 0; output_indexed = has_transparent_col = FALSE; transparent_index = 0; first_idat_found = FALSE; image_frame_data_pal = NULL; ct = NULL; trns = NULL; buf = NULL; deinterlace_image_pixels = 0; #ifdef APNG_SUPPORT is_apng = FALSE; apng_seq = 0; last_finished_index = -1; #endif #ifdef EMBEDDED_ICC_SUPPORT first_iccp_found = FALSE; #endif frame_index = -1; num_frames = 1; pixel_count = 0; mainframe_x = 0; mainframe_y = 0; #if !defined(MINPNG_NO_GAMMA_SUPPORT) gamma = 0.0; #endif deinterlace_image.data = NULL; op_memset(&ihdr, 0, sizeof(ihdr)); } #endif // _PNG_SUPPORT_
/// Include the header file created for this assignment #include "TicTacToe.h" /** * @brief This is the main function to run the game * */ int main(){ // Utilize srand and time to seed the random number generator srand(time(0)); // Create a humanPlayer instance humanPlayer Tony("Tony"); // Create a C3P0Player instance computerPlayer C3P0 ("C3P0"); // Create an instance of the board Board game; // Create strings to hold the names string humanName, C3P0Name; // Get the names from the Player objects humanName = Tony.getName(); C3P0Name = C3P0.getName(); /** * @brief Declare all ints needed * C3P0R0W, C3P0Column: The row and column C3P0 needs to make a move * humanRow, humanColumn: The row and column the human needs to make a move * canMove: an int to determine if the current move is valid or not */ int C3P0Row, C3P0Column, humanRow, humanColumn, canMove; // Alert to the beginning of a game cout << "BEGINNING TIC TAC TOE GAME " << "\n" << endl; /** While true technically executes forever, so continue this loop until the program exits. These comments have been left as Doxygen comments for documentation purposes. **/ while (true){ /// Print out the human's name, and initiate their turn cout << humanName << "'s move." << endl; /// Utilize a do while loop to ensure the move is valid do{ /// Collect the row and column to play the human move humanRow = Tony.collectRowMovement(); humanColumn = Tony.collectColMovement(); /// Determine if the move is valid canMove = game.checkMove(humanRow, humanColumn, 'O'); } while (canMove != 1); /// Keep going until the move is valid /// Once it is, play the move game.placeMove(humanRow, humanColumn, 'X'); /// Print out the board game.printBoard(); /// Check to see if anybody has won, or if it is a tie game.checkStatus(humanName); /// Now repeat the process for the computer /// Print out the computer's name, and initiate their turn cout << C3P0Name << "'s move." << endl; /// Utilize a do while loop to ensure the move is valid do{ /// Collect the row and column to play the computer move C3P0Row = C3P0.generateRowMovement(); C3P0Column = C3P0.generateColMovement(); /// Determine if the move is valid canMove = game.checkMove(C3P0Row, C3P0Column, 'O'); } while (canMove != 1); /// Keep going until the move is valid /// Once it is, play the move game.placeMove(C3P0Row, C3P0Column, 'O'); /// Print out the board game.printBoard(); /// Check to see if anybody has won game.checkStatus(C3P0Name); /** Assuming the program has not exited, continue on in the while(true) loop **/ } // end while } // end main
/* * cDiInfo - An application to get information via the Windows SetupDi... APIs * Charles Machalow - MIT License - (C) 2016 * Registry.cpp - Windows Registry interfacing implementation file */ // Local includes #include "Registry.h" namespace cdi { namespace registry { bool getStringFromRegistry(HKEY hKey, std::string subKey, std::string value, std::string & output) { DWORD size; DWORD type; LONG retVal = RegGetValue(hKey, subKey.c_str(), value.c_str(), RRF_RT_ANY, NULL, NULL, &size); // For some reason this doesn't always work unless I add a bit (maybe for a null terminator?) size = size + 1; if (retVal == ERROR_SUCCESS) { char * allocatedString = new char[size]; retVal = RegGetValue(hKey, subKey.c_str(), value.c_str(), RRF_RT_ANY, &type, allocatedString, &size); output = cdi::strings::rTrim(std::string(allocatedString, size - 1)); delete[] allocatedString; if (retVal == ERROR_SUCCESS) { return true; } } return false; } bool getUIntFromRegistry(HKEY hkey, std::string subKey, std::string value, UINT64 &output) { std::string outString = ""; if (getStringFromRegistry(hkey, subKey, value, outString)) { // Now we have a string, cast it back to UINT64 memcpy(&output, outString.data(), outString.size()); return true; } return false; } } }
#include "CSoftInstallResultSendTh.h" #include "Markup.h" #include "CClientLog.h" #include "NetClass.h" #include "CMessageEventMediator.h" #include "NetClt.h" #include "CMessageDataMediator.h" #include "CMisc.h" #include <QtCore/QCoreApplication> CSoftInstallResultSendThread::CSoftInstallResultSendThread(QObject *parent) : QThread(qApp) { m_nHasWaitSendTime = 0; m_nSendWaitTime = 60000; m_bIsStart = false; m_bThreadExit = true; m_bIsTreatSendReceive = false; } CSoftInstallResultSendThread* CSoftInstallResultSendThread::m_Instance = NULL; CSoftInstallResultSendThread* CSoftInstallResultSendThread::Instance() { if (NULL == m_Instance) { m_Instance = new CSoftInstallResultSendThread(); Q_ASSERT(m_Instance); } return m_Instance; } CSoftInstallResultSendThread::~CSoftInstallResultSendThread() { Clear(); } //启动 bool CSoftInstallResultSendThread::Start(const QString& strPath) { if(strPath.isNull() || strPath.isEmpty()) { return false; } if(m_bIsStart) return true; //从文件中还原上传队列到list m_strPath = strPath; ReloadFromFile(); m_bIsStart = true; start(); m_bThreadExit = false; return true; } //添加 void CSoftInstallResultSendThread::AddSoftData(const SoftData& softData) { if(!m_bIsStart) return; QMutexLocker locker(&m_TempSoftDataListMutex); for (int i = 0; i < m_TempSoftDataList.count(); i++) { SoftData& refSoftData = m_TempSoftDataList[i]; if(refSoftData.name == softData.name) {//同一软件多个版本只会有一个软件序列上传 if(CMisc::IsNeedUpdate(refSoftData.version, softData.version)) //比较版本号 yhb { refSoftData.version = softData.version; ChangeInfoInFile(softData); } return; } } if(!WriteToFile(softData)) ClientLogger->AddLog("安装结果写入文件失败!"); m_TempSoftDataList.append(softData); } void CSoftInstallResultSendThread::serverHasGetSoftInstall(const QString& name, const QString& version) { QMutexLocker locker(&m_TempSoftDataListMutex); for (int i = 0; i < m_TempSoftDataList.count(); i++) { SoftData& refSoftData = m_TempSoftDataList[i]; if(refSoftData.name == name) {//同一软件多个版本只会有一个软件序列上传 if(refSoftData.version <= version) //比较版本号 yhb { DeleteInfoInFile(refSoftData); m_TempSoftDataList.removeAt(i); } return; } } if(m_nCurSendSoftData.name == name && m_nCurSendSoftData.version == version) { m_bIsTreatSendReceive = false; m_nHasWaitSendTime = 0; } } //释放资源 void CSoftInstallResultSendThread::Clear() { if(!m_bIsStart) return; m_bThreadExit = true; msleep(1000); terminate(); QMutexLocker locker(&m_TempSoftDataListMutex); m_TempSoftDataList.clear(); } //检查列表 bool CSoftInstallResultSendThread::CheckSoftDataList() { if(m_TempSoftDataList.count() <= 0) return false; //如果正在处理一个请求并且还没到超时时间则继续等待 if(m_bIsTreatSendReceive && (m_nHasWaitSendTime < m_nSendWaitTime)) return false; QMutexLocker locker(&m_TempSoftDataListMutex); if(m_TempSoftDataList.count() <= 0) return false; m_nCurSendSoftData = m_TempSoftDataList[0]; MessageDataMediator->m_strSoftname = m_nCurSendSoftData.name; MessageDataMediator->m_strVersion = m_nCurSendSoftData.version; return true; } //上传 void CSoftInstallResultSendThread::Update() { if(NetClass->m_pNetClt->SendMsg(EMSG_SOFTINSTALL, false)) { m_nHasWaitSendTime = 0; m_bIsTreatSendReceive = true; } } //记录到文件 bool CSoftInstallResultSendThread::WriteToFile(const SoftData& softData) { CMarkup xml; if(!xml.Load(m_strPath.toLocal8Bit().constData())) { xml.SetDoc("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"); xml.AddElem("Root"); xml.AddChildElem("SoftwareList"); } else { ::SetFileAttributes(m_strPath.toLocal8Bit().constData(), FILE_ATTRIBUTE_NORMAL); } xml.ResetMainPos(); if(!xml.FindChildElem("SoftwareList")) { ClientLogger->AddLog(QString::fromLocal8Bit("发现 WriteToFile xml!xml.FindChildElem(\"SoftwareList\") ")); xml.SetDoc("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"); xml.AddElem("Root"); xml.AddChildElem("SoftwareList"); } xml.IntoElem(); xml.AddChildElem("Software"); xml.IntoElem(); xml.AddAttrib("name", softData.name.toStdString()); xml.AddAttrib("version", softData.version.toStdString()); xml.OutOfElem(); xml.OutOfElem(); bool bRet = xml.Save(m_strPath.toLocal8Bit().constData()); ::SetFileAttributes(m_strPath.toLocal8Bit().constData(), FILE_ATTRIBUTE_HIDDEN); return bRet; } //从文件中还原上传队列到list bool CSoftInstallResultSendThread::ReloadFromFile() { QMutexLocker locker(&m_TempSoftDataListMutex); CMarkup xml; if(!xml.Load(m_strPath.toLocal8Bit().constData())) { return false; } if(!xml.FindChildElem("SoftwareList")) return false; xml.IntoElem(); while(xml.FindChildElem("Software")) { SoftData softData; xml.IntoElem(); softData.name = QString::fromStdString(xml.GetAttrib("name")); softData.version = QString::fromStdString(xml.GetAttrib("version")); xml.OutOfElem(); m_TempSoftDataList.push_back(softData); } xml.OutOfElem(); return true; } //改变信息 bool CSoftInstallResultSendThread::ChangeInfoInFile(const SoftData& softData) { CMarkup xml; if(!xml.Load(m_strPath.toLocal8Bit().constData())) { xml.SetDoc("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"); xml.AddElem("Root"); xml.AddChildElem("SoftwareList"); xml.IntoElem(); xml.AddChildElem("Software"); xml.IntoElem(); xml.AddAttrib("name", softData.name.toStdString()); xml.AddAttrib("version", softData.version.toStdString()); xml.OutOfElem(); xml.OutOfElem(); bool bRet = xml.Save(m_strPath.toLocal8Bit().constData()); ::SetFileAttributes(m_strPath.toLocal8Bit().constData(), FILE_ATTRIBUTE_HIDDEN); return bRet; } if(xml.FindChildElem("SoftwareList")) return false; xml.IntoElem(); bool bFind = false; while(!bFind && xml.FindChildElem("Software")) { xml.IntoElem(); QString strName = QString::fromStdString(xml.GetAttrib("name")); if(strName == softData.name) { xml.SetAttrib("version", softData.version.toStdString()); bFind = true; } xml.OutOfElem(); } xml.OutOfElem(); if(!bFind) { xml.ResetMainPos(); if(!xml.FindChildElem("SoftwareList")) { ClientLogger->AddLog(QString::fromLocal8Bit("!xml.FindChildElem(\"SoftwareList\") 致命错误!")); return false; } xml.IntoElem(); xml.AddChildElem("Software"); xml.IntoElem(); xml.AddAttrib("name", softData.name.toStdString()); xml.AddAttrib("version", softData.version.toStdString()); xml.OutOfElem(); xml.OutOfElem(); } ::SetFileAttributes(m_strPath.toLocal8Bit().constData(), FILE_ATTRIBUTE_NORMAL); bool bRet = xml.Save(m_strPath.toLocal8Bit().constData()); ::SetFileAttributes(m_strPath.toLocal8Bit().constData(), FILE_ATTRIBUTE_HIDDEN); return bRet; } //删除一条信息 bool CSoftInstallResultSendThread::DeleteInfoInFile(const SoftData& softData) { CMarkup xml; if(!xml.Load(m_strPath.toLocal8Bit().constData())) { return true; } if(!xml.FindChildElem("SoftwareList")) return false; xml.IntoElem(); bool bFind = false; while(!bFind && xml.FindChildElem("Software")) { xml.IntoElem(); QString strName = QString::fromStdString(xml.GetAttrib("name")); if(strName == softData.name) { xml.RemoveElem(); bFind = true; break; } xml.OutOfElem(); } xml.OutOfElem(); bool bRet = true; if(bFind) { ::SetFileAttributes(m_strPath.toLocal8Bit().constData(), FILE_ATTRIBUTE_NORMAL); bRet = xml.Save(m_strPath.toLocal8Bit().constData()); ::SetFileAttributes(m_strPath.toLocal8Bit().constData(), FILE_ATTRIBUTE_HIDDEN); } return true; } void CSoftInstallResultSendThread::run() { while(!m_bThreadExit) { if(CheckSoftDataList()) { Update(); } msleep(10); if(m_bIsTreatSendReceive) m_nHasWaitSendTime += 10; } m_bThreadExit = true; }
#ifndef __DLGSELECTCLS_CTRLPNL_H #define __DLGSELECTCLS_CTRLPNL_H #include "VObjCatalogCtrl.h" namespace wh{ class CatDlg: public wxDialog ,public ctrlWithResMgr { public: typedef std::function<bool(const wh::rec::Cls*,const wh::rec::Obj*)> TargetValidator; CatDlg(wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title=wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 500,400 ),//wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER, const wxString& name = wxDialogNameStr); template <class T> void SetModel(std::shared_ptr<T> model) { SetModel(std::dynamic_pointer_cast<IModel>(model)); } void SetModel(std::shared_ptr<IModel> model); void SetTargetValidator(const TargetValidator& tv) { mTargetValidator = tv; } bool GetSelectedCls(wh::rec::Cls& cls); bool GetSelectedObj(wh::rec::ObjInfo& obj); protected: wxButton* m_btnOK; wxButton* m_btnCancel; wxStdDialogButtonSizer* m_sdbSizer; view::VObjCatalogCtrl* mMainPanel; std::shared_ptr<object_catalog::MObjCatalog> mCatalog; TargetValidator mTargetValidator; void OnActivated(wxDataViewEvent& evt); void OnSelect(wxDataViewEvent& evt); }; }//namespace wh #endif //__*_H
#include <Arduino.h> #include "xfm2.h" #include "XFM2_vars.h" int program=0; void change_unit() { // Default to unit 1 if (active_unit == 1) { active_unit = 2; //swap unit params //or do 2 memcpy's for(int i=0;i<n_params;i++) { unit1_params[i]=params[i]; params[i]=unit2_params[i]; } } else { active_unit = 1; //swap unit params //or do 2 memcpy's for(int i=0;i<n_params;i++) { unit2_params[i]=params[i]; params[i]=unit1_params[i]; } } Serial1.write(active_unit); // Serial.print("Active Unit Changed:"); // Serial.println(active_unit); delay(30); } // Code for setting the parameter on the XFM2 void set_parameter( int param, int value ) { Serial1.write( 's' ); // 's' = Set Parameter if( param > 255 ) { // Parameters above 255 have a two-byte format: b1 = 255, b2 = x-256 Serial1.write( 255 ); Serial1.write( param - 256 ); Serial1.write( value ); } else { Serial1.write( param ); Serial1.write( value ); } } // Code for getting a selected parameter on the XFM2 int get_parameter( int param) { Serial1.write( 'g' ); // 'g' = Get Parameter if( param > 255 ) { // Parameters above 255 have a two-byte format: b1 = 255, b2 = x-256 Serial1.write( 255 ); Serial1.write( param - 256 ); } else Serial1.write( param ); while(!Serial1.available());//wait for it return Serial1.read(); } // Code for getting all parameters on the XFM2 void get_all_parameter() { Serial1.write( '2' ); for (int i = 0; i < n_params; i++) params[i]=get_parameter(i); }
#include <stdio.h> int main() { float tank = 20; float avgMPGrd = 21.5; float avgMPGhwy = 26.8; float distRd = tank*avgMPGrd; float distHwy = tank*avgMPGhwy; printf("Distance on road: %f\nDistance on High-way: %f\n", distRd,distHwy); return 0; }
#include <conio.h> #include <iostream.h> #include <stdio.h> #include <salman.h> #include <main.h> void main () { int op,op1,op2,op3,op4; // Start of Main while clrscr(); cout <<"\n\t\tOPTIONAL SOFTWARE\n"; Main1(); cout <<"\n\n\tEnter your choice: "; cin >>op; while (op!=4) { switch (op) { case 1: clrscr(); cout <<"\n\n\tWELCOME TO SIMPLE PROGRAMS"; Main2(); cout <<"\n\n\tEnter your choice: "; cin >>op1; while (op1!=6) { switch (op1) { // Start of inner Switch clrscr(); case 1: Amount(); break; case 2: Salary(); break; case 3: Area(); break; case 4: Marksheet(); break; case 5: Equation(); break; default: cout <<"\n\n\tInvalid choice !"; break; } // End of Inner Switch getche(); clrscr(); cout <<"\n\n\tWELCOME TO SIMPLE PROGRAMS"; Main2(); cout <<"\n\n\tEnter your choice: "; cin >>op1; } // End of While break; case 2: clrscr(); cout <<"\n\n\tWELCOME TO IF ELSE PROGRAMS"; Main3(); cout <<"\n\n\tEnter your choice: "; cin >>op2; while (op2!=5) { switch (op2) { case 1: clrscr(); EBC(); break; case 2: OddEven(); break; case 3: PosNeg(); break; case 4: Pass(); break; default: cout <<"\n\n\tINVALID CHOICE !"; break; } // End of Switch getche(); clrscr(); cout <<"\n\n\tWELCOME TO IF ELSE PROGRAMS"; Main3(); cout <<"\n\n\tEnter your choice: "; cin >>op2; } // End of While break; case 3: clrscr(); cout <<"\n\n\tFOR LOOP PROGRAM"; Main4(); cout <<"\n\n\tEnter your choice: "; cin >>op3; while (op3!=6) { switch(op3) { case 1: For(); break; case 2: Table(); break; case 3: Range(); break; case 4: TabRange(); break; case 5: Time(); break; default: cout <<"\n\n\tINVALID CHOICE !"; break; } // End of Switch getche(); clrscr(); cout <<"\n\n\tFOR LOOP PROGRAMS"; Main4(); cout <<"\n\n\tEnter your choice: "; cin >>op3; } // End of While break; default: cout<<"\n\n\tINVALID CHOICE !"; break; } // End of Main Switch clrscr(); cout <<"\n\t\tOPTIONAL SOFTWARE\n"; Main1(); cout <<"\n\n\tEnter your choice: "; cin >>op; } // End of While }
#include <Drawables/Mesh.h> CMesh::CMesh(const std::vector<SVertex> &vertices, const std::vector<unsigned> &indices) : CIndexedDrawable(GL_TRIANGLES, static_cast<GLsizei>(indices.size()), GL_UNSIGNED_INT) { updateVertices(vertices.size() * sizeof(SVertex), vertices.data(), GL_STATIC_DRAW); for (unsigned j = 0, offset = 0; j < SVertex::offsets.size(); ++j) { updateAttrib(j, SVertex::offsets[j], SVertex::size, offset); offset += SVertex::offsets[j] * sizeof(GLfloat); } updateIndices(indices.size() * sizeof(unsigned), indices.data(), GL_STATIC_DRAW); } void CMesh::render() const { if (_material) _material->bind(); CIndexedDrawable::render(); } constexpr std::array<unsigned, CMesh::SVertex::n> CMesh::SVertex::offsets;
//: C11:PmemFunDefinition.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt class Simple2 { public: int f(float) const { return 1; } }; int (Simple2::*fp)(float) const; int (Simple2::*fp2)(float) const = &Simple2::f; int main() { fp = &Simple2::f; } ///:~
// // Created by 史浩 on 2020-01-12. // #include "BaseEGLSurface.h" BaseEGLSurface::BaseEGLSurface(EGLCore *eglCore) { this->mEGLCore=eglCore; this->mEGLSurface=EGL_NO_SURFACE; mWidth=-1; mHeight=-1; } BaseEGLSurface::~BaseEGLSurface() {} void BaseEGLSurface::createWindowSurface(ANativeWindow *window) { if (mEGLSurface!=EGL_NO_SURFACE){ //已经创建了 return; } mEGLSurface=mEGLCore->createWindowSurface(window); } void BaseEGLSurface::createOffscreenSurface(int width, int height) { if (mEGLSurface!=EGL_NO_SURFACE){ //已经创建了 return; } mEGLSurface=mEGLCore->createOffscreenSurface(width,height); mWidth=width; mHeight=height; } void BaseEGLSurface::releaseEglSurface() { mEGLCore->releaseSurface(mEGLSurface); mEGLSurface=EGL_NO_SURFACE; mWidth=mHeight=-1; } void BaseEGLSurface::makeCurrent() { mEGLCore->makeCurrent(mEGLSurface); } bool BaseEGLSurface::swapBuffers() { bool result=mEGLCore->swapBuffers(mEGLSurface); if (!result){ //swapBuffers failed } return result; } void BaseEGLSurface::setPresentationTime(long nsecs) { mEGLCore->setPresentationTime(mEGLSurface,nsecs); } char* BaseEGLSurface::getCurrentFrame() { char* pixels; glReadPixels(0,0,getWidth(),getHeight(),GL_RGBA,GL_UNSIGNED_BYTE,pixels); return pixels; } int BaseEGLSurface::getWidth() { return mWidth; } int BaseEGLSurface::getHeight() { return mHeight; }
#pragma once #include "mt4part\MT4ServerEmulator.h" #include "BaseExecutionSignal.h" class OpenOrderSignal : public BaseExecutionSignal { public: OpenOrderSignal(); OpenOrderSignal(int login, std::string symbol, double volume, int cmd, std::string comment, MT4Server* server, double commission); ~OpenOrderSignal(void); virtual bool Execute(double bid, double ask); private: double GetTradingCommission(int volume, double provider_commission); double equity, margin, free_margin, profit, prevmargin, open_price, provider_commission; void CalculateVolume(); std::string comment; int cmd; int volume; virtual bool CheckParametres(); virtual RequestInfo GenerateRequest(); };
#pragma once #include "DynamicObjectController.h" #include "DynamicObjectModel.h" #include "DynamicObjectLogicCalculator.h" #include "DynamicObjectView.h" #include "Vector4.h" #include "LevelModel.h" #include "LevelView.h" class DynamicObjectFactory { public: static DynamicObjectController* create(LevelModel* levelModel,LevelView* levelView,int id); };
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_SHELL_GAMELOOP_H_ #define BAJKA_SHELL_GAMELOOP_H_ #include <stdint.h> struct android_app; struct AInputEvent; class ShellFactory; namespace Util { class ShellContext; class LifecycleHandler; } /** * */ class GameLoop { public: ~GameLoop (); void init (); void loop (); private: friend class ShellFactory; GameLoop (Util::ShellContext *c, Util::LifecycleHandler *h); private: Util::ShellContext *context; Util::LifecycleHandler *lifecycleHandler; bool autoPause; bool suspended; bool firstGainedFocus; bool savedStatePending; bool rendering; // rendering i suspended są osobno, bo w czasie inicjowania mają odwrotne wartości. }; #endif /* GAMELOOP_H_ */
/* Citation and Sources... Final Project Milestone 1 Module: Menu Filename: Menu.h Version 1.0 Author John Doe Revision History ----------------------------------------------------------- Date Reason 2020/11/13 Preliminary release 2020/11/13 Debugged DMA ----------------------------------------------------------- I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments.*/ #define _CRT_SECURE_NO_WARNINGS #include <cstring> #include "utils.h" #include "Menu.h" using namespace std; namespace sdds { Menu::Menu(const char* text, int NoOfSelections) { m_text = new char[strlen(text) + 1]; strcpy(m_text, text); m_noOfSel = NoOfSelections; } Menu::~Menu() { delete[] m_text; m_text = nullptr; } ostream& Menu::display(ostream& ostr) const { ostr << m_text << endl; ostr << "0- Exit" << endl; ostr << "> "; return ostr; } int& Menu::operator>>(int& Selection) { display(); int select; bool invalid; do { invalid = false; cin >> select; cin.ignore(256, '\n'); if (cin.fail()) { cout << "Bad integer value, try again: "; cin.clear(); cin.ignore(3000, '\n'); invalid = true; } else if (select < 0 || select > m_noOfSel) { cout << "Invalid value enterd, retry[0 <= value <= " << m_noOfSel << "]: "; cin.ignore(3000, '\n'); invalid = true; } } while (invalid); Selection = select; return Selection; } }
#pragma once #include "Module.h" #include "p2List.h" #include "p2Point.h" #include "Globals.h" #include "ModuleTextures.h" class PhysBody; struct Sprite; class ModuleSceneIntro : public Module { public: ModuleSceneIntro(Application* app, bool start_enabled = true); ~ModuleSceneIntro(); bool Start(); update_status Update(); bool CleanUp(); void OnCollision(PhysBody* bodyA, PhysBody* bodyB); public: Sprite Background; Sprite Play; uint bonus_fx; PhysBody* last_collided; };
class WoodenGate_ghost_DZ: NonStrategic { scope = 2; displayName = $STR_BLD_name_WoodenGate_1_ghost; model = "z\addons\dayz_buildings\models\gates\gate_wood_ghost.p3d"; armor = 1000; }; class WoodenGate_foundation_DZ: DZE_Housebase { scope = 2; displayName = $STR_BLD_name_WoodenGate_Foundation; model = "z\addons\dayz_buildings\models\gates\gate0_dzam.p3d"; armor = 1000; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 8; GhostPreview = "WoodenGate_ghost_DZ"; offset[] = {0,4,2}; upgradeBuilding[] = {"WoodenGate_1_DZ",{"ItemToolbox","Handsaw_DZE","Hammer_DZE"},{{"ItemPlank",8},{"equip_nails",1},{"ItemComboLock",1}}}; }; class WoodenGate_1_DZ: DZE_Housebase { scope = 2; displayName = $STR_BLD_name_WoodenGate_1; model = "z\addons\dayz_buildings\models\gates\gate1_dzam.p3d"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 8; offset[] = {0,4,0}; armor = 2000; upgradeBuilding[] = {"WoodenGate_2_DZ",{"ItemToolbox","Handsaw_DZE","Hammer_DZE"},{{"ItemPlank",10},{"equip_nails",1}}}; class AnimationSources { class DoorR { source = "User"; animPeriod = 3; initPhase = 0; }; class DoorL { source = "User"; animPeriod = 3; initPhase = 0; }; }; class UserActions { class Lock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_LOCKGATE; condition = "this animationPhase 'DoorR' >= 0.7"; statement = "[this,'combo_locked',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,4];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 0];this animate ['DoorL', 0]"; }; class Unlock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "(!keypadCancel && DZE_Lock_Door == (this getvariable['CharacterID','0'])) && (this animationPhase 'DoorR' < 0.3)"; statement = "[this,'combo_unlock',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,5,GateMethod];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 1];this animate ['DoorL', 1];"; }; class Unlock_Door_Dialog { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "!keypadCancel && (DZE_Lock_Door != (this getvariable['CharacterID','0'])) && (this animationPhase ""DoorR"" == 0)"; statement = "dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;if(DZE_doorManagement) then {createdialog ""DoorAccess"";} else {createdialog ""ComboLockUI"";};"; }; }; lockable = 3; }; class WoodenGate_2_DZ: DZE_Housebase { scope = 2; displayName = $STR_BLD_name_WoodenGate_2; model = "z\addons\dayz_buildings\models\gates\gate2_dzam.p3d"; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 8; offset[] = {0,4,0}; armor = 2500; upgradeBuilding[] = {"WoodenGate_3_DZ",{"ItemToolbox","Handsaw_DZE","Hammer_DZE"},{{"ItemPlank",10},{"equip_nails",1}}}; class AnimationSources { class DoorR { source = "User"; animPeriod = 3; initPhase = 0; }; class DoorL { source = "User"; animPeriod = 3; initPhase = 0; }; }; class UserActions { class Lock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_LOCKGATE; condition = "this animationPhase 'DoorR' >= 0.7"; statement = "[this,'combo_locked',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,4];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 0];this animate ['DoorL', 0]"; }; class Unlock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "(!keypadCancel && DZE_Lock_Door == (this getvariable['CharacterID','0'])) && (this animationPhase 'DoorR' < 0.3)"; statement = "[this,'combo_unlock',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,5,GateMethod];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 1];this animate ['DoorL', 1];"; }; class Unlock_Door_Dialog { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "!keypadCancel && (DZE_Lock_Door != (this getvariable['CharacterID','0'])) && (this animationPhase ""DoorR"" == 0)"; statement = "dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;if(DZE_doorManagement) then {createdialog ""DoorAccess"";} else {createdialog ""ComboLockUI"";};"; }; }; lockable = 3; }; class WoodenGate_3_DZ: DZE_Housebase { scope = 2; displayName = $STR_BLD_name_WoodenGate_3; model = "z\addons\dayz_buildings\models\gates\gate3_dzam.p3d"; armor = 3000; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 8; offset[] = {0,4,0}; upgradeBuilding[] = {"WoodenGate_4_DZ",{"ItemToolbox","Handsaw_DZE","Hammer_DZE"},{{"ItemPlank",10},{"equip_nails",1}}}; class AnimationSources { class DoorR { source = "User"; animPeriod = 3; initPhase = 0; }; class DoorL { source = "User"; animPeriod = 3; initPhase = 0; }; }; class UserActions { class Lock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_LOCKGATE; condition = "this animationPhase 'DoorR' >= 0.7"; statement = "[this,'combo_locked',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,4];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 0];this animate ['DoorL', 0]"; }; class Unlock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "(!keypadCancel && DZE_Lock_Door == (this getvariable['CharacterID','0'])) && (this animationPhase 'DoorR' < 0.3)"; statement = "[this,'combo_unlock',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,5,GateMethod];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 1];this animate ['DoorL', 1];"; }; class Unlock_Door_Dialog { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "!keypadCancel && (DZE_Lock_Door != (this getvariable['CharacterID','0'])) && (this animationPhase ""DoorR"" == 0)"; statement = "dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;if(DZE_doorManagement) then {createdialog ""DoorAccess"";} else {createdialog ""ComboLockUI"";};"; }; }; lockable = 3; }; class WoodenGate_4_DZ: DZE_Housebase { armor = 3500; scope = 2; displayName = $STR_BLD_name_WoodenGate_4; icon = "\ca\data\data\Unknown_object.paa"; mapSize = 8; offset[] = {0,4,0}; model = "z\addons\dayz_buildings\models\gates\gate4_dzam.p3d"; class AnimationSources { class DoorR { source = "User"; animPeriod = 3; initPhase = 0; }; class DoorL { source = "User"; animPeriod = 3; initPhase = 0; }; }; class UserActions { class Lock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_LOCKGATE; condition = "this animationPhase 'DoorR' >= 0.7"; statement = "[this,'combo_locked',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,4];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 0];this animate ['DoorL', 0]"; }; class Unlock_Door { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "(!keypadCancel && DZE_Lock_Door == (this getvariable['CharacterID','0'])) && (this animationPhase 'DoorR' < 0.3)"; statement = "[this,'combo_unlock',0,false] spawn dayz_zombieSpeak;PVDZE_handleSafeGear = [player,this,5,GateMethod];publicVariableServer ""PVDZE_handleSafeGear"";this animate ['DoorR', 1];this animate ['DoorL', 1];"; }; class Unlock_Door_Dialog { radius = 4; position = "Door"; onlyForPlayer = 1; priority = 6; displayName = $STR_BLD_ACTIONS_UNLOCKGATE; condition = "!keypadCancel && (DZE_Lock_Door != (this getvariable['CharacterID','0'])) && (this animationPhase ""DoorR"" == 0)"; statement = "dayz_selectedDoor = this;DZE_topCombo = 0;DZE_midCombo = 0;DZE_botCombo = 0;if(DZE_doorManagement) then {createdialog ""DoorAccess"";} else {createdialog ""ComboLockUI"";};"; }; }; lockable = 3; };
/****************************************************************************** Fichier: fichiers.cpp Auteur: William Fecteau et Jordan Gagnon Utilité: Implémentation des fonctions permettant de gérer les fichiers "./mtg.txt" et "./nom_carte.index" ******************************************************************************/ #include "fichiers.h" #include "carte.h" #include <fstream> #include <string> #include "index_nom_carte.h" #include <algorithm> /****************************************************************************** Permet d'obtenir le nombre de lignes dans le fichier de données. Retourne -1 si l'ouverture du fichier échoue. ******************************************************************************/ int ObtenirNbLignes(const char* szFichierDonnnees) { if (szFichierDonnnees != NULL) { //Stream du fichier de données fstream ficDonnees; ficDonnees.open(szFichierDonnnees, ios::in | ios::binary); if (!ficDonnees.fail()) { ficDonnees.clear(); //Nombre de lignes du fichiers (Nbr de \n) int intNbLignes = 0; //Parcours du fichier while (!ficDonnees.eof()) { string strTampon; getline(ficDonnees, strTampon); intNbLignes++; } ficDonnees.close(); //-2 on retire la première et la dernière ligne return intNbLignes - 2; } } //Une erreur est survenue return -1; } /****************************************************************************** Permet de créer le fichier d'index en fonction du fichier de données. Retourne le nombre d'index créée ou bien -1 si la création du fichier échoue. ******************************************************************************/ int CreerIndexNomCarte(const char* szFichierDonnnees, const char* szFichierIndex) { if (szFichierDonnnees != NULL && szFichierIndex != NULL) { //Stream du fichier de données fstream ficDonnees; //Stream du fichier index fstream ficIndex; //Nombre de lignes dans le fichier de données int intNbLignes = ObtenirNbLignes(szFichierDonnnees); if (intNbLignes > -1) { //Ouverture du fichier de données en lecture ficDonnees.open(szFichierDonnnees, ios::in | ios::binary); if (!ficDonnees.fail()) { ficDonnees.clear(); //Vecteur de pointeurs vers les objets index des cartes CIndexNomCarte* pLesIndexCartes = new CIndexNomCarte[intNbLignes]; //La première vrai ligne commence à la position 84 ficDonnees.seekg(83, ios::beg); //Création de chaque objet index for (int intI = 0; intI < intNbLignes; intI++) { //Données pour la carte courante string strDonneeCarte; //Position du début des données de la carte courante int intPosition = ficDonnees.tellg(); getline(ficDonnees, strDonneeCarte); //Pointeur sur la carte temporaire CCarte* pCarteTemp = CreerCarte(strDonneeCarte); pLesIndexCartes[intI].SetNomCarte(pCarteTemp->GetNom()); pLesIndexCartes[intI].SetPosition(intPosition); delete pCarteTemp; } ficDonnees.close(); //Tri sort(pLesIndexCartes, pLesIndexCartes + intNbLignes); //Ouverture du fichier index en écriture (et remplace celui existant s'il y a lieu) ficIndex.open(szFichierIndex, ios::out | ios::trunc | ios::binary); if (ficIndex.fail()) throw "Une erreur incontrolable s'est produite."; //Écriture de tous les index dans le fichier index for (int intI = 0; intI < intNbLignes; intI++) { //Nom de la carte (avec des espaces ajoutés pour faire 30 caractères) string strNomCarte = pLesIndexCartes[intI].GetNomCarte(); int intNbTour = 30 - strNomCarte.length(); for (int intJ = 0; intJ < intNbTour; intJ++) { strNomCarte += '\0'; } ficIndex.write(strNomCarte.c_str(), 30); //Position de la carte (avec des 0 ajoutés pour faire 10 caractères) string strPosCarte = to_string(pLesIndexCartes[intI].GetPosition()); while (strPosCarte.length() < 10) { strPosCarte.insert(0, "0"); } ficIndex.write(strPosCarte.c_str(), 10); } ficIndex.close(); delete[] pLesIndexCartes; return intNbLignes; } } } //Une erreur s'est produite return -1; } /****************************************************************************** Permet de rechercher et retourner les cartes correspondant au nom (strNomRech) ainsi que le nombre de ces cartes par référence (nbCartesTrouvees). ******************************************************************************/ CCarte** RechercherDichoCartes(const string& strNomRech, int& nbCartesTrouvees, const char* szFichierDonnnees, const char* szFichierIndex) { nbCartesTrouvees = 0; //To lower PENISSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS string strSearchTerm; for (int i = 0; i < 30; i++) { if (i < strNomRech.length()) strSearchTerm += tolower(strNomRech[i]); else strSearchTerm += '\0'; } //Lecture fichier index fstream fIndex; fIndex.open(szFichierIndex, ios::in | ios::binary); if (!fIndex.fail()) { fIndex.clear(); //=================Recherche dichotomique================= //Debut de la plage de recherche int debut = 0; fIndex.seekg(0, fIndex.end); //Pointeur à la fin //Position du dernier caractère du fichier int longueurFichier = fIndex.tellg(); //Fin de la plage de recherche int fin = longueurFichier; fIndex.seekg(0, fIndex.beg); //Pointeur au début //Nombre de cartes dans le fichier d'indexe unsigned int uintNbCartes = longueurFichier / TAILLE_ENREG_INDEX; //Booléen si la variable a été trouvé bool trouve = false; while (!trouve && debut < fin) { //Position de la carte au millieu int millieu = floor((debut/TAILLE_ENREG_INDEX + fin/TAILLE_ENREG_INDEX) / 2)*TAILLE_ENREG_INDEX; fIndex.seekg(millieu); //Curseur est à la carte du millieu //Nom de la carte sélectionnée char szCarteSelect[30]; fIndex.read(szCarteSelect, 30); if (szCarteSelect == strSearchTerm) { trouve = true; //debut stocke la position de la carte debut = millieu; } else if (strSearchTerm > szCarteSelect) debut = millieu + TAILLE_ENREG_INDEX; else fin = millieu - TAILLE_ENREG_INDEX; } //Recherche des autres cartes du même nom if (trouve) { //Indique si la carte dans debut est la première de son type bool premier = false; //Recherche de la première carte du nom (vers gauche) do { if (debut > 0) { fIndex.seekg(debut - TAILLE_ENREG_INDEX); //Pointeur sur la carte d'avant char szCarteSel[30]; fIndex.read(szCarteSel, 30); if (szCarteSel == strSearchTerm) debut -= TAILLE_ENREG_INDEX; else premier = true; } else premier = true; } while (!premier); bool dernier = false; nbCartesTrouvees = 1; fin = debut + TAILLE_ENREG_INDEX; do { fIndex.seekg(fin); char cCarteSel[30]; for (int i = 0; i < 30; i++) { cCarteSel[i] = std::tolower(fIndex.get()); } string strCarteSel = cCarteSel; if (strCarteSel == strSearchTerm) { nbCartesTrouvees++; fin += TAILLE_ENREG_INDEX; } else dernier = true; } while (!dernier); CCarte** ppCartesCherchers = new CCarte* [nbCartesTrouvees]; fstream fData; fData.open(szFichierDonnnees, ios::in|ios::binary); if (!fData.fail()) { for (int i = 0; i < nbCartesTrouvees; i++) { //Placement du curseur à la position de la ligne fIndex.seekg(debut + (i * TAILLE_ENREG_INDEX) + 30); char* ligneData = new char[10]; fIndex.read(ligneData, 10); int intLigne = stoi(ligneData); //Ligne a laquelle se trouve la carte fData.seekg(intLigne); string strInfoCarte; getline(fData, strInfoCarte); ppCartesCherchers[i] = CreerCarte(strInfoCarte); } fData.close(); fIndex.close(); return ppCartesCherchers; } } } return NULL; } /****************************************************************************** Permet de créer et retourner une carte à partir d'une chaîne correspondant à l'enregistrement dans le fichier de données. ******************************************************************************/ CCarte* CreerCarte(string strEnregDonnees) { /* Données stockées 00: ID 01: NAME 02: COST 03: TYPE 04: POWER 05: TOUGHNESS 06: ORACLE 07: SET 08: RARITY 09: ARTIST 10: COLLNUM 11: TEXT 12: PROPERTIES */ string strDonnes[12]; //Position dans le string des données int intPos = 0; //Séparation des données dans les différents index for (int intI = 0; intI < 12; intI++) { while (strEnregDonnees[intPos] != '|') { strDonnes[intI] += strEnregDonnees[intPos]; intPos++; } intPos++; } //Met le nom de la carte en minuscule for (int intI = 0; intI < strDonnes[1].length(); intI++) { strDonnes[1][intI] = tolower(strDonnes[1][intI]); } return new CCarte(stoi(strDonnes[0]), strDonnes[1], strDonnes[2], strDonnes[3], strDonnes[4], strDonnes[5], strDonnes[7], strDonnes[8], strDonnes[6]); }
#ifndef __CTRL_UNDO_H #define __CTRL_UNDO_H #include "CtrlWindowBase.h" #include "IViewUndo.h" #include "ModelUndo.h" namespace wh{ //----------------------------------------------------------------------------- class CtrlUndoWindow final : public CtrlWindowBase<IViewUndoWindow, ModelUndoWindow> { sig::scoped_connection connViewCmd_ExecuteUndo; sig::scoped_connection connViewCmd_Load; sig::scoped_connection connModel_HistoryRecordLoaded; public: CtrlUndoWindow(const std::shared_ptr<IViewUndoWindow>& view , const std::shared_ptr<ModelUndoWindow>& model); void ExecuteUndo(); void Load(); }; //----------------------------------------------------------------------------- } // namespace wh{ #endif // __*_H
#include "global.h" float ***v,***at; bool SHOW_INFO = false; bool SAVE_AT_INTERFACE = false; bool INIT_AT_INTERFACE = false; void process_args(int argc,char* argv[]) { if (argc < 5) { cout<<"a TEST or WRONG input params:"<<endl; cout<<argc<<endl; for (int i=0;i<argc;i++) cout<<argv[i]<<endl; argv[1] = "test"; argv[2] = "0"; argv[3] = "1"; //show info argv[4] = "0"; //save at interface } if (strcmp(argv[3],"1")==0) SHOW_INFO = true; if (strcmp(argv[4],"save")==0) SAVE_AT_INTERFACE = true; if (strcmp(argv[4],"init")==0) INIT_AT_INTERFACE = true; } int main(int argc, char* argv[]) { process_args(argc,argv); INFO("reading model"); Data d = Data(argv[1],argv[2]); v = d.read_model(); INFO("reading model finished"); at = allocate3D<float>(nx,ny,nz); if (INIT_AT_INTERFACE) { init_interface(at,d.computation_ID); } else { FORALL at[i][j][k]=-2; Source s = d.read_source(); s.excite(1); } int p = 0; clock_t c_start = time_start(); Bod b = Bod(0,0,0,0); INFO("MAIN LOOP"); while ( !pq.empty() ) { b = pq.top(); pq.pop(); b.sir(); p++; if (SHOW_INFO) { if (p%10000000 == 0) { char c[64]; sprintf(c,"%.6f out of %.6f completed",p/1000000.f,nx*ny*nz/1000000.f); INFO(c,false); } } } time(c_start); //cout<<"writing output"<<endl; Output out; out.save_at(&d); if (!d.isAdjoint) { vector<Receiver> recs = d.read_receivers(); out.save_arrivals(recs,d); } time(c_start); /* out.save_spherical_cuts(s); out.save_err_vs_dist(s); out.save_err_surface(s); */ //cout<<"OK. Finished, press anything to exit."<<endl; //cin.get(); if (SAVE_AT_INTERFACE) save_interface(at,d.computation_ID); }
// Copyright 2017 Google Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "FirebaseInvitesScene.h" #include <stdarg.h> #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) #include <android/log.h> #include <jni.h> #include "platform/android/jni/JniHelper.h" #endif #include "FirebaseCocos.h" #include "firebase/future.h" #include "firebase/invites.h" USING_NS_CC; /// Padding for the UI elements. static const float kUIElementPadding = 10.0; /// The title text for the Firebase buttons. static const char* kInviteButtonText = "Invite"; /// Creates the Firebase scene. Scene* CreateFirebaseScene() { return FirebaseInvitesScene::createScene(); } /// Creates the FirebaseInvitesScene. Scene* FirebaseInvitesScene::createScene() { // Create the scene. auto scene = Scene::create(); // Create the layer. auto layer = FirebaseInvitesScene::create(); // Add the layer to the scene. scene->addChild(layer); return scene; } /// Initializes the FirebaseScene. bool FirebaseInvitesScene::init() { if (!Layer::init()) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); cocos2d::Vec2 origin = Director::getInstance()->getVisibleOrigin(); // Intitialize Firebase Invites. CCLOG("Initializing the Invites with Firebase API."); firebase::invites::Initialize(*firebase::App::GetInstance()); // Create the Firebase label. auto firebaseLabel = Label::createWithTTF("Firebase Invites", "fonts/Marker Felt.ttf", 20); nextYPosition = origin.y + visibleSize.height - firebaseLabel->getContentSize().height; firebaseLabel->setPosition( cocos2d::Vec2(origin.x + visibleSize.width / 2, nextYPosition)); this->addChild(firebaseLabel, 1); const float scrollViewYPosition = nextYPosition - firebaseLabel->getContentSize().height - kUIElementPadding * 2; // Create the ScrollView on the Cocos2d thread. cocos2d::Director::getInstance() ->getScheduler() ->performFunctionInCocosThread( [=]() { this->createScrollView(scrollViewYPosition); }); // Set up the invite button. invite_button_ = createButton(true, kInviteButtonText); invite_button_->addTouchEventListener( [this](Ref* /*sender*/, cocos2d::ui::Widget::TouchEventType type) { switch (type) { case cocos2d::ui::Widget::TouchEventType::ENDED: { firebase::invites::Invite invite; invite.title_text = "Invite Friends"; invite.message_text = "Try out this super cool sample app!"; invite.call_to_action_text = "Download now!"; firebase::invites::SendInvite(invite); invite_sent_ = true; break; } default: { break; } } }); this->addChild(invite_button_); // Create the close app menu item. auto closeAppItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(FirebaseScene::menuCloseAppCallback, this)); closeAppItem->setContentSize(cocos2d::Size(25, 25)); // Position the close app menu item on the top-right corner of the screen. closeAppItem->setPosition(cocos2d::Vec2( origin.x + visibleSize.width - closeAppItem->getContentSize().width / 2, origin.y + visibleSize.height - closeAppItem->getContentSize().height / 2)); // Create the Menu for touch handling. auto menu = Menu::create(closeAppItem, NULL); menu->setPosition(cocos2d::Vec2::ZERO); this->addChild(menu, 1); // Schedule the update method for this scene. this->scheduleUpdate(); return true; } // Called automatically every frame. The update is scheduled in `init()`. void FirebaseInvitesScene::update(float /*delta*/) { if (invite_sent_) { firebase::Future<firebase::invites::SendInviteResult> future = firebase::invites::SendInviteLastResult(); if (future.Status() == firebase::kFutureStatusComplete) { if (future.Error() == 0) { const firebase::invites::SendInviteResult& result = *future.Result(); if (result.invitation_ids.size() > 0) { // One or more invitations were sent. You can log the invitation IDs // here for analytics purposes, as they will be the same on the // receiving side. logMessage("Invite sent successfully!"); } else { // Zero invitations were sent. This tells us that the user canceled // sending invitations. logMessage("Invite canceled."); } } else { // error() is nonzero, which means an error occurred. You can check // future_result.error_message() for more information. logMessage("Error sending the invite. (Error %i: \"%s\")", future.Error(), future.ErrorMessage()); } invite_sent_ = false; } else { // The SendInvite() operation has not completed yet, which means the // Invites client UI is still on screen. Check the status() again soon. } } } /// Handles the user tapping on the close app menu item. void FirebaseInvitesScene::menuCloseAppCallback(Ref* pSender) { CCLOG("Cleaning up Invites C++ resources."); // Close the cocos2d-x game scene and quit the application. Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
#include "mutantstack.hpp" # include <iostream> # include <list> int main() { MutantStack<int> mstack; std::cout << "-Push: 5\n"; mstack.push(5); std::cout << "-Push: 17\n"; mstack.push(17); std::cout << "at TOP: " << mstack.top() << std::endl; std::cout << "-Pop\n"; mstack.pop(); std::cout << "Stack size: "<< mstack.size() << std::endl; std::cout << "-Push: 3\n"; std::cout << "-Push: 5\n"; mstack.push(3); mstack.push(5); std::cout << "-Push: 737\n"; mstack.push(737); //[...] std::cout << "-Push: 0\n"; mstack.push(0); MutantStack<int>::iterator it = mstack.begin(); MutantStack<int>::iterator ite = mstack.end(); ++it; --it; std::cout << "While iter_begin != iter_end ->> cout:\n"; while (it != ite) { std::cout << *it << std::endl; ++it; } std::stack<int> s(mstack); std::cout << "\033[32mMy tests (REVERSE ITERATOR): \033[0m \n"; MutantStack<int> mstack1; mstack1.push(1); mstack1.push(17); mstack1.push(71); mstack1.push(15); mstack1.push(51); mstack1.push(19); MutantStack<int>::reverse_iterator rb = mstack1.rbegin(); MutantStack<int>::reverse_iterator re = mstack1.rend(); while (rb != re) { std::cout << *rb << std::endl; rb++; } std::cout << "\033[32mMy tests (CONST DIRECT ITERATOR): \033[0m \n"; MutantStack<int>::const_iterator cb = mstack1.cbegin(); MutantStack<int>::const_iterator ce = mstack1.cend(); while (cb != ce) { std::cout << *cb << std::endl; cb++; } std::cout << "\033[32mMy tests (CONST REVERSE ITERATOR): \033[0m \n"; MutantStack<int>::const_reverse_iterator crb = mstack1.crbegin(); MutantStack<int>::const_reverse_iterator cre = mstack1.crend(); while (crb != cre) { std::cout << *crb << std::endl; crb++; } return 0; }
#pragma once #include "Scene.h" #include "TextField.h" #include "Button.h" class LevelEditorSkyboxLoader { public: enum SKYBOX_LOCATION {TOP = 0, BOTTOM = 1, LEFT = 2, RIGHT = 3, FRONT = 4, BACK = 5}; LevelEditorSkyboxLoader(Scene &scene, Font &font); virtual ~LevelEditorSkyboxLoader(); void setVisible(bool visisble); void update(); TextField* top = nullptr; TextField* bottom = nullptr; TextField* left = nullptr; TextField* right = nullptr; TextField* front = nullptr; TextField* back = nullptr; private: Scene* scene = nullptr; bool visible; Button* apply = nullptr; };
// // Camera.h // Odin.MacOSX // // Created by Daniel on 04/06/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef __Odin_MacOSX__Camera__ #define __Odin_MacOSX__Camera__ #include "Math.h" namespace odin { namespace render { class Camera { public: Camera(const math::vec3& position = math::vec3(0,0,0), const math::vec2& angles = math::vec2(math::radians(180),0)); ~Camera(); math::vec3& position(); void setPosition(const math::vec3& position); void move(const math::vec3& position); void rotate(const math::vec2& angles, bool constrain = true); math::vec3 forward(); math::vec3 right(); math::vec3 up(); void lookAt(); void lookAt(const math::vec3& position, const math::vec3& forward, const math::vec3& up); const math::mat4& view(); private: math::vec3 m_position; math::vec2 m_angles; math::mat4 m_view; bool m_viewUpdated; bool m_firstMouseUpdate; }; math::mat4 ortho(F32 left, F32 right, F32 bottom, F32 top, F32 near = -1.0f, F32 far = 1.0f); math::mat4 frustum(F32 left, F32 right, F32 bottom, F32 top, F32 near, F32 far); math::mat4 perspective(F32 fov, F32 aspectRatio, F32 near, F32 far); } } #endif /* defined(__Odin_MacOSX__Camera__) */
#include<cstdio> #include<ctype.h> #define R register //================================================== struct node { int x,y; }a[15]; int n,ans; bool vis[15]; //================================================== inline int read() { int fl=1,w=0;char ch=getchar(); while(!isdigit(ch)) if(ch=='-') {fl=-1,ch=getchar();break;} while(isdigit(ch)){w=w*10+ch-'0',ch=getchar();} return fl*w; } inline bool check(int s,int v,int dir) { switch(dir) { case 1: {return (a[v].x>a[s].x && a[v].y==a[s].y); } case 2: {return (a[v].x<a[s].x && a[v].y==a[s].y); } case 3: {return (a[v].x==a[s].x && a[v].y<a[s].y); } case 4: {return (a[v].x==a[s].x && a[v].y>a[s].y); } default:{return 0;} } } inline int getdir(int s,int v) { if(a[v].y==a[s].y) return (a[s].x<a[v].x?1:2); return (a[v].y>a[s].y?4:3); } void dfs(int s,int dir,int num) { if(num>n) { if((a[s].x==0 || a[s].y==0 ) && (!check(s,0,dir))) ans++; return ; } for(R int i=1;i<=n;i++) if(a[i].x==a[s].x || a[i].y==a[s].y) if(!vis[i] && !check(s,i,dir)) { vis[i]=1; dfs(i,getdir(s,i),num+1); vis[i]=0; } return ; } //================================================== signed main() { n=read(); for(R int i=1;i<=n;i++) a[i].x=read(),a[i].y=read(); dfs(0,0,1); printf("%d",ans); }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int maxn = 1e5; int f[maxn + 100]; bool vis[maxn + 100]; stack<int> S; int find(int k) { while (f[k] != k) { S.push(k); k = f[k]; } while (!S.empty()) { int p = S.top();S.pop(); f[p] = k; } return k; } int main() { int a,b; for ( ; ; ) { for (int i = 1;i < maxn; i++) f[i] = i; memset(vis,false,sizeof(vis)); int ok = 1,coun = 0,coum = 0; scanf("%d%d",&a,&b); if ((a == -1) && (b == -1)) break; do { if (a == 0 && b == 0) break; if (!vis[a]) {vis[a] = true;coun++;} if (!vis[b]) {vis[b] = true;coun++;} coum++; a = find(a),b = find(b); if (a != b) f[a] = b; else ok = 0; scanf("%d%d",&a,&b); } while (a && b); if (coum && coun != coum + 1) ok = 0; if (ok) printf("Yes\n"); else printf("No\n"); } return 0; }
#include <iostream> #include <string> #include "SeatUpholstery.hpp" #pragma warning (disable:4996) SeatUpholstery::SeatUpholstery(): color(colors::black) { this->product_name = product::seatUpholstery; } SeatUpholstery::SeatUpholstery(const std::string& mark, const double& price, const unsigned int& count, const colors& color): Product(mark, price, count) { this->color = color; this->product_name = product::seatUpholstery; } void SeatUpholstery::set_color(const colors& color) { this->color = color; } SeatUpholstery::colors SeatUpholstery::get_color()const { return this->color; } product SeatUpholstery::get_product_name()const { return product::seatUpholstery; } void SeatUpholstery::print()const { Product::print(); std::cout << "Material: "; switch (SeatUpholstery::get_color()) { case 0: std::cout << "black" << '\n'; break; case 1: std::cout << "red_and_black" << '\n'; break; case 2: std::cout << "blue_and_black" << '\n'; break; default: break; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" #include "modules/pi/OpSystemInfo.h" #include "modules/url/url_man.h" #ifdef _MIME_SUPPORT_ #include "modules/mime/mimedec2.h" #include "modules/hardcore/mem/mem_man.h" #include "modules/viewers/viewers.h" #include "modules/idna/idna.h" #include "modules/encodings/charconverter.h" #include "modules/encodings/decoders/inputconverter.h" #include "modules/encodings/detector/charsetdetector.h" #include "modules/prefs/prefsmanager/collections/pc_display.h" #include "modules/olddebug/tstdump.h" #include "modules/formats/base64_decode.h" #include "modules/formats/uri_escape.h" void GeneralValidateSuggestedFileNameFromMIMEL(OpString & suggested, const OpStringC &mime_type); OP_STATUS ConvertAndAppend(OpString &target, CharConverter *converter, const char *a_source, int a_len, BOOL a_contain_email_address = FALSE) { const char * OP_MEMORY_VAR source = a_source; OP_MEMORY_VAR int len = a_len; OP_MEMORY_VAR BOOL contain_email_address = a_contain_email_address; uni_char *tempunidata; int templen, tempunidatalen, tempunilen; if(source == NULL || len <= 0) return OpStatus::OK; tempunidata = (uni_char *) g_memory_manager->GetTempBufUni(); tempunidatalen = g_memory_manager->GetTempBufUniLenUniChar(); while(len > 0) { if(contain_email_address) { OP_MEMORY_VAR char temp = source[len]; ((char *)source)[len] = '\0'; // Ugly, but needed BOOL is_emailaddress = TRUE; TRAPD(op_err, IDNA::ConvertFromIDNA_L(source, tempunidata, tempunidatalen, is_emailaddress)); ((char *)source)[len] = temp; // Ugly, but needed if(OpStatus::IsError(op_err)) { contain_email_address = FALSE; continue; } tempunilen = (int)uni_strlen(tempunidata); templen = len; } else if(converter) { templen = 0; tempunilen = UNICODE_DOWNSIZE(converter->Convert((char *) source, len, (char *) tempunidata, UNICODE_SIZE(tempunidatalen), &templen)); } else { templen = len; if(templen+1 > tempunidatalen) templen = tempunidatalen-1; tempunilen = templen; make_doublebyte_in_buffer(source, templen, tempunidata, tempunidatalen); } OP_ASSERT(templen>0); if (templen==0) //Avoid infinite loop for wrongly encoded multi-byte encodings (Fixes bug #176576) break; source += templen; len -= templen; RETURN_IF_ERROR(UriEscape::AppendEscaped(target, tempunidata, tempunilen, UriEscape::PrefixBackslash | UriEscape::NonSpaceCtrl)); } return OpStatus::OK; } void RemoveHeaderEscapes(OpString &target, const char *&source, int maxlen, BOOL toplevel, BOOL structured, const char *def_charset, CharConverter *converter2, BOOL contain_email_address) { int charsetlen, encodinglen,datalen; const char *src, *charset,*encoding, *data; const char *start; char *tempdata, *temppos; int tempdatalen, templen, unprocessed=0; CharConverter *converter= NULL; CharConverter *converter3= NULL; const char *unconverted = NULL; int unconv_len = 0; if(source == NULL) return; if(target.Capacity() < target.Length() + maxlen +1) { if(target.Reserve(target.Length() + maxlen +1) == NULL) return; } if(toplevel) { int i; for(i=0;i<maxlen && ((unsigned char) source[i])!=0x1b && ((unsigned char) source[i]) <0x80 ;i++) { #ifdef _DEBUG // int j=0; #endif } if(i < maxlen) { OpString8 cset; CharsetDetector test(NULL,NULL); test.PeekAtBuffer(source, maxlen); cset.Set(test.GetDetectedCharset()); if(cset.IsEmpty()) { // charset decoder haven't got a clue and def. charset is not set, use system charset cset.Set(def_charset ? def_charset : g_op_system_info->GetSystemEncodingL()); } InputConverter *new_converter=NULL; OP_STATUS rc = InputConverter::CreateCharConverter(cset.CStr(), &new_converter, TRUE); converter3 = converter2 = new_converter; if (OpStatus::IsSuccess(rc)) def_charset = converter3->GetCharacterSet(); } } tempdata = (char *) g_memory_manager->GetTempBuf2(); tempdatalen = g_memory_manager->GetTempBuf2Len(); while(maxlen>0) { unprocessed = 0; if(toplevel && structured && *source == '<') { if(unconverted) { ConvertAndAppend(target, converter2, unconverted, unconv_len); unconverted = NULL; unconv_len = 0; } // This is supposed to be normal 7-bit email addresses start = source; while(maxlen > 0 && *source != '>') { maxlen --; source ++; //*(target++) = *(source++); } maxlen --; source ++; if(contain_email_address) { target.Append(UNI_L("<")); ConvertAndAppend(target, converter2, start+1, (int)(source - start-2), contain_email_address); target.Append(UNI_L(">")); } else target.Append(start, (int)(source - start)); } else if(toplevel && /*structured &&*/ *source == '"') { if(unconverted) { ConvertAndAppend(target, converter2, unconverted, unconv_len); unconverted = NULL; unconv_len = 0; } temppos = tempdata; templen = 0; maxlen --; templen ++; *(temppos++) = *(source++); while(maxlen > 0 && *source != '"') { if(templen < tempdatalen-4) { *temppos='\0'; target.Append(tempdata, templen); temppos = tempdata; templen = 0; } char temp0 = *source; if(temp0 == '\\') { source ++; maxlen --; if(*source != '\0') { *(temppos++) = *(source); templen++; if(*source == '\r' && *(source+1) == '\n') { *(temppos++) = '\n'; templen++; source ++; source ++; maxlen -=2; if(*source == ' ') { source++; maxlen --; } } else { source++; maxlen --; } } continue; } maxlen --; templen++; *(temppos++) = *(source++); } if(maxlen && *source) { maxlen --; templen++; *(temppos++) = *(source++); } if(templen) { *temppos='\0'; ConvertAndAppend(target, converter2, tempdata, templen); } } else if(structured && *source == '(') { if(unconverted) { ConvertAndAppend(target, converter2, unconverted, unconv_len); unconverted = NULL; unconv_len = 0; } int level = 1; const char *src1 = source+1; int len1 = 1; while(len1< maxlen && level > 0) { if(*src1 == '(') level++; else if(*src1 == ')') level --; src1++; len1++; } if(level > 0) { ConvertAndAppend(target, converter2, source,maxlen); source+=maxlen; maxlen = 0; } else { target.Append((source++),1); RemoveHeaderEscapes(target,source,len1-2,FALSE, FALSE, def_charset, converter2); target.Append((source++),1); maxlen-=len1; } } else if(maxlen >2 && *source == '=' && source[1] == '?') { if(unconverted) { ConvertAndAppend(target, converter2, unconverted, unconv_len); unconverted = NULL; unconv_len = 0; } unprocessed = maxlen -2; src = source +2; charset = src; while(unprocessed > 0 && *src && *src != '?') { src++; unprocessed--; } charsetlen = maxlen-unprocessed-2; { // Look for RFC 2231 language segment int j = charsetlen; while(j>0) { j--; if(charset[j] == '*') { charsetlen = j; break; } } } if(unprocessed <= 0 || !*src) goto fail_escape; encoding = ++src; unprocessed--; if(unprocessed <= 0 || *src == '=') goto fail_escape; while(unprocessed > 0 && *src && *src != '?') { src++; unprocessed--; } if(unprocessed <= 0) goto fail_escape; encodinglen = maxlen-unprocessed-3-charsetlen; if(unprocessed <= 0 || !*src) goto fail_escape; data = ++src; if(unprocessed > 0) unprocessed--; if(unprocessed <= 0) goto fail_escape; while(unprocessed > 0 && *src && (*src != '?' || (unprocessed > 1 && src[1] != '='))) { src++; unprocessed--; } datalen = maxlen-unprocessed-4 - charsetlen - encodinglen; if(*src) src++; if(unprocessed > 0) unprocessed--; char encodingtype = op_toupper(*encoding); OpString8 charset_str; if(OpStatus::IsError(charset_str.Set(charset, charsetlen))) goto fail_escape; InputConverter *new_converter=NULL; if (OpStatus::IsError(InputConverter::CreateCharConverter(charset_str.CStr(), &new_converter, TRUE))) if (OpStatus::IsError(InputConverter::CreateCharConverter(g_pcdisplay->GetDefaultEncoding(), &new_converter, TRUE))) goto fail_escape; converter = new_converter; if(*src != '=' || charsetlen == 0 || encodinglen != 1 || datalen == 0 || (encodingtype != 'Q' && encodingtype != 'B')) goto fail_escape; temppos = tempdata; templen = 0; if(encodingtype == 'Q') { while(datalen >0) { if(templen > tempdatalen -4) { if(OpStatus::IsError(ConvertAndAppend(target,converter, tempdata, templen))) goto fail_escape; templen = 0; temppos = tempdata; } if(*data=='_') *(temppos++) = '\x20'; else if(*data == '=') { if(datalen == 1) *(temppos++) = *data; else if(datalen == 2) { *(temppos++) = *(data++); *(temppos++) = *data; datalen --; } else { //if(!op_isxdigit(data[1]) || !op_isxdigit(data[2])) if(!op_isxdigit((unsigned char) data[1]) || !op_isxdigit((unsigned char) data[2])) // 01/04/98 YNP { *(temppos++) = *(data++); *(temppos++) = *(data++); *(temppos++) = *data; datalen -= 2; } else { *(temppos++) = UriUnescape::Decode(data[1], data[2]); data+=2; datalen -= 2; } } } else *(temppos++) = *data; data++; datalen --; templen = (int)(temppos - tempdata); } } else // if(encodingtype == 'B') { for(;datalen >0;) { BOOL warning = FALSE; unsigned long pos = 0; templen = datalen; templen = (datalen <= tempdatalen ? datalen : tempdatalen); unsigned long target_pos = GeneralDecodeBase64((const unsigned char*) data, templen, pos, (unsigned char *) tempdata, warning); if(OpStatus::IsError(ConvertAndAppend(target,converter, tempdata, target_pos))) goto fail_escape; templen = 0; datalen -= pos; data += pos; if(pos == 0) break; } } if(templen && OpStatus::IsError(ConvertAndAppend(target,converter, tempdata, templen))) goto fail_escape; OP_DELETE(converter); converter = NULL; source = ++src; maxlen = --unprocessed; while(unprocessed > 0 && op_isspace((unsigned char) *src)) // 01/04/98 YNP { src++; unprocessed --; } if(unprocessed >2 && *src == '=' && src[1] == '?') { source = src; maxlen = unprocessed; } } else { if(*source != '\0') { if(!unconverted) { unconverted= source; unconv_len = 0; } source ++; unconv_len ++; } //ConvertAndAppend(target, converter2, source++,1); maxlen--; } continue; fail_escape: if(converter) { OP_DELETE(converter); converter = NULL; } if(unconverted) { ConvertAndAppend(target, converter2, unconverted, unconv_len); unconverted = NULL; unconv_len = 0; } ConvertAndAppend(target, converter2, source, maxlen - unprocessed); maxlen = unprocessed; source = src; continue; } if(unconverted) { ConvertAndAppend(target, converter2, unconverted, unconv_len); unconverted = NULL; unconv_len = 0; } OP_DELETE(converter3); } URL ConstructFullAttachmentURL_L(URLType base_url_type, BOOL no_store, HeaderEntry *content_id, const OpStringC &ext0, HeaderEntry *content_type, const OpStringC &suggested_filename, URL *content_id_url #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , URL_CONTEXT_ID context_id #endif ) { if(content_id_url && content_id) { *content_id_url = ConstructContentIDURL_L(content_id->Value() #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , context_id #endif ); if(content_id_url->IsEmpty()) { content_id = NULL; content_id_url = NULL; } } else { content_id_url = NULL; content_id = NULL; } const uni_char *urlpref; switch(base_url_type) { case URL_NEWSATTACHMENT: urlpref = UNI_L("newsatt"); break; case URL_SNEWSATTACHMENT: urlpref = UNI_L("snewsatt"); break; default: urlpref = UNI_L("attachment"); break; } ANCHORD(OpString, content_type_tmp_str); if(content_type && content_type->Value()) { ParameterList *parameters = content_type->GetParametersL(PARAM_SEP_SEMICOLON| PARAM_ONLY_SEP | PARAM_STRIP_ARG_QUOTES | PARAM_HAS_RFC2231_VALUES, KeywordIndex_HTTP_General_Parameters); if(parameters && parameters->First()) content_type_tmp_str.Set(parameters->First()->Name()); } const uni_char *ext = ext0.CStr(); if(suggested_filename.IsEmpty() && ext0.IsEmpty()) { if(content_type_tmp_str.HasContent() && content_type_tmp_str.CompareI(UNI_L("application/octet-stream")) != 0) { if (Viewer *v = g_viewers->FindViewerByMimeType(content_type_tmp_str)) { const OpStringC extension = v->GetExtension(0); ext = extension.HasContent() ? extension.CStr() : NULL; } else ext = NULL; } } g_mime_attachment_counter++; uni_char *attachnum= (uni_char *) g_memory_manager->GetTempBuf2(); const uni_char *tmp_str = (!ext ? UNI_L("tmp") : ext); uni_snprintf(attachnum, UNICODE_DOWNSIZE(g_memory_manager->GetTempBuf2Len()), UNI_L("attachment%ld.%s"),g_mime_attachment_counter, tmp_str); ANCHORD(OpString, candidate_filename); if(suggested_filename.HasContent()) { candidate_filename.SetL(suggested_filename.CStr(), MIN(suggested_filename.Length(), 256)); // limit namelength to 256 GeneralValidateSuggestedFileNameFromMIMEL(candidate_filename, content_type_tmp_str); uni_char *temp_buf = (uni_char*)g_memory_manager->GetTempBuf2(); EscapeFileURL(temp_buf, candidate_filename.CStr(), TRUE); candidate_filename.Set(temp_buf); } uni_char *tempurl = (uni_char *) g_memory_manager->GetTempBufUni(); uni_snprintf(tempurl, g_memory_manager->GetTempBufUniLenUniChar()-1, UNI_L("%s:/%u/%s"),urlpref, g_mime_attachment_counter, (candidate_filename.HasContent() ? candidate_filename.CStr() : attachnum)); ANCHORD(URL, ret); ret = urlManager->GetURL(tempurl #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , context_id #endif ); if(content_id_url) content_id_url->SetAttributeL(URL::KAliasURL, ret); if(no_store) ret.SetAttributeL(URL::KCachePolicy_NoStore, TRUE); if (content_id) g_mime_module.SetContentID_L(ret, content_id->Value()); return ret; } #endif // MIME_SUPPORT BOOL GetTextLine(const unsigned char *data, unsigned long startpos, unsigned long data_len, unsigned long &nextline_pos, unsigned long &length, BOOL no_more) { BOOL found_end_of_line = FALSE; unsigned long pos = startpos, line_len = 0; const unsigned char *current = data + startpos; while(pos < data_len) { unsigned char temp_code = *current++; pos++; // look for CRLF, LF and CR (LFCR is assumed to be end of line for different lines) if(temp_code == 13 /* CR */) { if (pos < data_len) { if(*current++ == 10 /* LF */) pos++; found_end_of_line = TRUE; } // Otherwise, we will have to wait until the next time to see if the CR was followed by LF break; } else if(temp_code == 10 /* LF */) { found_end_of_line = TRUE; break; } line_len++; } if (pos == data_len && no_more) //Are we at the end of the text? found_end_of_line = TRUE; nextline_pos = pos; length = line_len; return found_end_of_line; } URL ConstructContentIDURL_L(const OpStringC8 &content_id #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , URL_CONTEXT_ID context_id #endif ) { char *tempurl = (char *) g_memory_manager->GetTempBuf2k(); if(content_id.HasContent()) { char *tempurl1 = (char *) tempurl; op_strcpy(tempurl1,"cid:"); if(op_sscanf(content_id.CStr(), " <%1000[^> \r\n]",tempurl1+4) == 1 || op_sscanf(content_id.CStr(), " %1000[^> \r\n]",tempurl1+4) == 1 ) return urlManager->GetURL(tempurl #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , context_id #endif ); } return URL(); } void InheritExpirationDataL(URL_InUse &child, URL_Rep *parent) { // Inherit Expires and Last-Modified from parent url time_t expires; parent->GetAttribute(URL::KVHTTP_ExpirationDate, &expires); child->SetAttributeL(URL::KVHTTP_ExpirationDate, &expires); OpStringC8 lastmod(parent->GetAttribute(URL::KHTTP_LastModified)); // If both Expires and Last-Modified are unset, set a dummy Last-Modified. // Prevents "Expired" from returning TRUE in certain situations as in CORE-25572 // (If we set expiration date instead, we might use an an inappropriate expiry // pref depending on the content type. This way we keep that logic in "Expired") if (expires==0 && lastmod.IsEmpty()) child->SetAttributeL(URL::KHTTP_LastModified, "Thu, 01 Jan 2009 00:00:00 GMT"); else child->SetAttributeL(URL::KHTTP_LastModified, lastmod); }
#include "sphere.h" sphere::sphere() { } sphere::~sphere() { } //-------------------------------------------------------------- void sphere::setup(int posX, int posY, int posZ, int size) { sphereRadius = size; sphereRes = 3; spherePulse = 0; ofSetSphereResolution(sphereRes); sphereShell.set(sphereRadius, sphereRes); rotation = 0; counter = 0; alpha = 0; point.set(posX, posY, posZ); } //-------------------------------------------------------------- void sphere::update(){ counter += 1; if (counter >= 20 && counter <= 200) { alpha += 2; } rotation += 0.33f; timeOfDay = ofGetHours(); //cout << timeOfDay << endl; // Change color of Orbs depending on time of day user views the application if (timeOfDay == ofWrap(timeOfDay, 1, 12)) { colorChange = colorChange.salmon; } if (timeOfDay == ofWrap(timeOfDay, 12, 18)) { colorChange = colorChange.lightYellow; } if (timeOfDay == ofWrap(timeOfDay, 18, 24)) { colorChange = colorChange.crimson; } } //-------------------------------------------------------------- void sphere::draw(){ ofPushMatrix(); ofTranslate(point.x, point.y, point.z); ofScale(1.0, 1.0); ofRotateX(rotation); ofRotateY(rotation); ofSetColor(ofColor::black, alpha); sphereShell.drawWireframe(); ofSetColor(colorChange, 100); sphereShell.drawFaces(); ofPopMatrix(); }
#pragma once #include "EdushiPipeline.h" #include "AppFrameWork2.h" #include "CarSimulation.h" #include "InteractionControler.h" #include "GUIWrapper.h" #include "socketSceneLoader\SceneLoader.h" using namespace Block; struct EdushiConfig { Vector3 cameraPos; Vector3 cameraUp; Vector3 LookCenter; bool cameraReset = false; float LookDownAngle = 2.7; float UpYAngle = 0; float cameraCenterDist = 10; float cameraRoundAngle = 30; //int w = 1024; //int h = 768; float fov = 25; int mapw = 32; int maph = 16; string ip; string port; META(N(cameraPos),N(cameraUp), N(LookCenter), N(cameraReset),N(LookDownAngle),N(UpYAngle), N(cameraCenterDist),N(ip),N(port),N(cameraRoundAngle), N(fov),N(mapw),N(maph)); }; class App_edushi :public App { public: CarSimulation CarSim; bool IsLogCamera = false; float scenescale = 0.16; Vector3 sceneTranlate = Vector3(-2.5, 0, -1.6); Vector3 modelTranslate = Vector3(0.0); float modelscale = 1.0; float modelrotate = 0; SceneLoader* sl=NULL; EdushiConfig c, originConfig; float rotatespeed = 0; bool rotateCamera=false; bool updateCamera = false; void SetCamera1() { c.LookDownAngle = 0; c.cameraCenterDist = 7; c.cameraRoundAngle = 270; c.LookCenter[1] = 0.72; } void SetCamera2() { c.LookDownAngle = 2.7; c.cameraCenterDist = 10; c.cameraRoundAngle = 180; c.LookCenter[1] = 1.80; } void SetCamera4() { c.LookDownAngle = 2.7; c.cameraCenterDist = 10; c.cameraRoundAngle = 0; c.LookCenter[1] = 1.82; } //void SetCamera3_2() { // c.LookDownAngle = 1.7; // c.cameraCenterDist = 7; // c.cameraRoundAngle = 90; // c.LookCenter[1] = 0.81; //} void SetCamera3() { c.LookDownAngle = 0; c.cameraCenterDist = 7; c.cameraRoundAngle = 90; c.LookCenter[1] = 1.5; } void Init() { w = 1280; h = 1024; render = new EGLRenderSystem; render->SetWandH(w, h); render->Initialize(); InitDevice(); InitPipeline(); CreateScene(); LoadConfig(); //sceneLoader sl = new SceneLoader(scene, meshMgr, 16, 8, LEFT, RIGHT, TOP, BOTTOM); sl->loadMesh(); sl->InitClient(c.ip, c.port); sl->InitEbus(AbsolutTime); /*sl->LoadJson(); sl->show_json = true; sl->UpdateScene(AbsolutTime);*/ vector<Vector3> pos; vector<Quaternion> orients; UpdateCamera(c); } Vector3 getSceneCenter(int w,int h) { Vector3 cen = 0.5*Vector3(w, 0, h)*scenescale + sceneTranlate; return cen; } void UpdateCamera(EdushiConfig& c) { auto cen = getSceneCenter(c.mapw, c.maph); cen.y = c.LookCenter[1]; float radRound = c.cameraRoundAngle / 180 * PI; float radUp = c.LookDownAngle / 180 * PI; float h = c.cameraCenterDist*sin(radUp); Vector3 offset = Vector3(c.cameraCenterDist*sin(radRound), h, c.cameraCenterDist*cos(radRound)); float rady = c.UpYAngle / 180 * PI; Quaternion q(rady, -offset); Vector3 up2 = q*Vector3(0, 1, 0); camera->lookAt(cen + offset, cen, up2); c.cameraPos = cen + offset; c.LookCenter = cen; c.cameraUp = up2; } //void SetCamera(float angleUp, float angleRound) { // auto cen = getSceneCenter(32,16); // cen.y += c.LookCenter[1]; // float radRound = angleRound/180* PI; // float radUp = angleUp / 180 * PI; // float h = c.cameraCenterDist*sin(radUp); // Vector3 offset = Vector3(c.cameraCenterDist*sin(radRound), h, c.cameraCenterDist*cos(radRound)); // camera->lookAt(cen + offset, cen, Vector3(0, 1, 0)); // //camera->setPerspective(fovy, float(w) / float(h), 0.01, 200); //} bool firstRotate = true; void RotateCamera() { static float lasttime; if (firstRotate) { lasttime = AbsolutTime; firstRotate = !firstRotate; } float dura = AbsolutTime - lasttime; lasttime = AbsolutTime; c.cameraRoundAngle += 20*dura; if (c.cameraRoundAngle > 360.0f) c.cameraRoundAngle -= 360.0f; UpdateCamera(c); } void InitPipeline() { pipeline = new EdushiPipeline; pipeline->Init(); } void Render() { UpdateGUI(); /*if (rotateCamera) RotateCamera();*/ //sl->rotateFlag = true; printf("render in\n"); if (sl->rotateFlag) RotateCamera(); else { c.cameraRoundAngle = originConfig.cameraRoundAngle; //printf("cameraReset %d\n", c.cameraReset); //if(c.cameraReset) UpdateCamera(c); UpdateCamera(c); firstRotate = true; } sl->UpdateScene(AbsolutTime); printf("pipeline->Render()\n"); pipeline->Render(); //CarSim.Update(); } void LoadModel(string path, string name = "") { SceneManager* scene = SceneContainer::getInstance().get("scene1"); SceneNode* root = scene->GetSceneRoot(); SceneNode* s; if (name == "") name = path; s = LoadMeshtoSceneNode(path, name); if (s == NULL) { cout << "cant find model:" << path << endl; return; } s->setScale(Vector3(modelscale)); s->setTranslation(modelTranslate); Quaternion q; float rad = modelrotate*PI / 180; q.fromAngleAxis(rad, Vector3(0, 1, 0)); s->setOrientation(q); if (s != NULL) root->attachNode(s); } void RemoveAllNodes() { SceneManager* scene = SceneContainer::getInstance().get("scene1"); SceneNode* root = scene->GetSceneRoot(); root->detachAllNodes(); auto nodes=root->getAllChildNodes(); } void LoadConfig() { serializeLoad("EdushiConfig.txt", c); originConfig = c; } void SaveConfig() { serializeSave("EdushiConfig.txt", c); } void UpdateGUI() { ImGui_ImplGlfwGL3_NewFrame(); { ImGui::Begin("Params"); ImGui::Text("%.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); auto p =(EdushiPipeline*) pipeline; ImGui::TextWrapped(p->profile.ToString().c_str()); static bool show_load_model = false; if (ImGui::Button("Show Model Window")) show_load_model = !show_load_model; if (show_load_model) { ImGui::Begin("model"); ImGui::Text("Model Path"); static char file[100] = "model/uniform/building01.obj"; //static char file[100] = "../../../daochu/b1.obj"; static char name[100] = "node_b0_0"; ImGui::InputText("Model Path", file, 100); ImGui::InputText("SceneNode Name", name, 100); ImGui::DragFloat3("model translate", &modelTranslate[0], 0.01); ImGui::DragFloat("model scale", &modelscale, 0.01); ImGui::DragFloat("model rotate degree", &modelrotate, 0.01); string tmp(file); string tmp2(name); if (ImGui::Button("Load model")) LoadModel(tmp, name); if (ImGui::Button("RemoveAll")) RemoveAllNodes(); ImGui::SameLine(); if (ImGui::Button("AttachFloor")) sl->AttachFloar(); if (ImGui::Button("Switch Show Json")) sl->show_json = !sl->show_json; ImGui::End(); } static bool show_config = true; if (ImGui::Button("Show Camera Config")) show_config = !show_config; if (show_config) { ImGui::Begin("config"); ImGui::DragFloat("scene scale", &scenescale, 0.001); ImGui::DragFloat3("scene translate", &sceneTranlate[0], 0.01); static bool scene2x=false; ImGui::Checkbox("2x Scene", &scene2x); { SceneNode* root = scene->GetSceneRoot(); int x = 1; if (scene2x) x = 2; root->setScale(Vector3(scenescale)*x); root->setTranslation(sceneTranlate); } ImGui::Text("Camera"); c.cameraPos = camera->getPosition(); c.cameraUp = camera->getUp(); ImGui::DragFloat3("CameraPos", &c.cameraPos[0],0.01); ImGui::DragFloat3("CameraCenter", &c.LookCenter[0], 0.01); ImGui::DragFloat3("CameraUp", &c.cameraUp[0], 0.01); ImGui::DragFloat("LookCenterY", &c.LookCenter[1], 0.01); ImGui::DragFloat("LookDownAngle", &c.LookDownAngle, 0.1, 0, 89); ImGui::DragFloat("UpYAngle", &c.UpYAngle, 0.1, -89, 89); ImGui::DragFloat("RoundAngle", &c.cameraRoundAngle, 0.2, 0, 360); ImGui::DragFloat("cameraCenterDist", &c.cameraCenterDist, 0.1); ImGui::DragFloat("cameraRotateSpeed", &rotatespeed); ImGui::DragFloat("cameraFov", &c.fov, 0.1); static bool updatecamera=false; ImGui::Checkbox("Use param Camera", &updatecamera); if (updatecamera) UpdateCamera(c); ImGui::SameLine(); if (ImGui::Button("Next Camera")) { static int i = 0; i = (i + 1) % 4; if (i == 0) SetCamera4(); if (i == 1) SetCamera3(); if (i == 2) SetCamera2(); if (i == 3) SetCamera1(); //cameraRoundAngle = (floor((cameraRoundAngle) / 90) + 1) * 90; //if (cameraRoundAngle >= 360) cameraRoundAngle -= 360; UpdateCamera(c); } ImGui::SameLine(); ImGui::Checkbox("Start Rotate Camera", &rotateCamera); if (ImGui::Button("Save Config")) SaveConfig(); ImGui::End(); } static bool show_block_window = false; if (ImGui::Button("Show Block Window")) show_block_window = !show_block_window; if (show_block_window) { ImGui::Begin(""); static char blockpath[100] = "model/uniform/data/block0.txt"; ImGui::InputText("Block Path", blockpath, 100); static char blockname[100] = "1"; ImGui::InputText("Block Name", blockname, 100); static char blocksize[100] = "1x1"; ImGui::InputText("Block Size", blocksize, 100); static char blocktype[100] = "block"; ImGui::InputText("Block type", blocktype, 100); static int blockorien = 1; ImGui::InputInt("Block Orientation", &blockorien); if (ImGui::Button("Load Block Preset")) { string bname = sl->bh.LoadBlockPreset(blockpath); auto& b = sl->bh.blockPresets[bname]; b.name.copy(blockname, b.name.size() + 1); b.size.copy(blocksize, b.size.size() + 1); b.type.copy(blocktype, b.type.size() + 1); blockorien = b.orientation; } ImGui::SameLine(); if (ImGui::Button("Save Block Preset")) sl->bh.SaveBlock(blockpath, blockname, blocksize, blocktype, blockorien); static char nodename[100] = "node_b0_"; static Vector3 blockPos(0.0); ImGui::DragFloat3("Block Translate", &blockPos[0], 0.01); ImGui::InputText("Block Node Name", nodename, 100); if (ImGui::Button("Attach Block")) { sl->bh.AttachBlock(blockname, string(nodename), blockPos); }ImGui::SameLine(); if (ImGui::Button("Attach All Block")) { sl->bh.attachAllBlock(); }ImGui::SameLine(); if (ImGui::Button("Attach All Mesh")) { sl->bh.attachAllMesh(); } ImGui::End(); } static bool show_shading = false; if (ImGui::Button("Show Shading")) show_shading = !show_shading; if (show_shading) { ImGui::Begin("shading"); ImGui::Text("Shading"); ImGui::ColorEdit3("LightColor0", &p->LightColor[0][0]); ImGui::ColorEdit3("LightColor1", &p->LightColor[1][0]); ImGui::DragFloat3("LightPos0", &p->LightPos[0][0]); ImGui::DragFloat3("LightPos1", &p->LightPos[1][0]); ImGui::DragFloat("Metalness", &p->metalness, 0.002, 0.0001, 1.0); ImGui::DragFloat("Roughness", &p->roughness, 0.002, 0.0001, 1.0); const char* ModeDesc[] = { "direct light+Env", "direct light+Env+ao", "ao", "Env", "Direct light", "Normal", "ShadowMap", "Shadow Factor", "Shaodw+Direct" }; int modeNum = 9; ImGui::Combo("Shading Mode", &p->mode, ModeDesc, modeNum); ImGui::Combo("EnvMap", &p->envMapId, "pisa\0uffizi\0sky\0"); ImGui::DragFloat("SSAO Radius", &p->ssao.radius, 0.002, 0.0001, 1.0); ImGui::DragFloat("ToneMap exposure", &p->tonemap.exposure, 0.01, 0.1, 10.0); static bool f = true; ImGui::Checkbox("Tonemap ON", &f); p->tonemap.ToneMapOn = f ? 1 : 0; ImGui::Text("ShadowMap"); static bool f2 = false; //ImGui::Checkbox("LinearDepth", &f2); p->shadowmap.LinearDepth = f2 ? 1 : 0; ImGui::DragFloat("ReduceBleeding", &p->shadowmap.ReduceBleeding, 0.002, 0.0001, 1.0); ImGui::DragFloat("BlurRadius", &p->shadowmap.blureffect.radius, 0.002, 0.0001, 5.0); ImGui::DragFloat("bias", &p->LightCamera.bias, 0.001, -0.1, 0.1); ImGui::DragFloat("near", &p->LightCamera.Near, 0.002, 0.0001); ImGui::DragFloat("far", &p->LightCamera.Far, 0.002, 0.0001); ImGui::DragFloat("width", &p->LightCamera.width, 0.002, 0.0001); ImGui::DragFloat("height", &p->LightCamera.height, 0.002, 0.0001); p->shadowmap.SetLightCamera(0, p->LightCamera); ImGui::End(); } ImGui::End(); } } void CreateScene() { scene = new OctreeSceneManager("scene1", render); SceneContainer::getInstance().add(scene); SceneNode* pRoot = scene->GetSceneRoot(); camera = scene->CreateCamera("main"); camera->lookAt(Vector3(-1.8, 0.6, 0.4), Vector3(-2, 0, -2), Vector3(0, 1, 0)); camera->setPerspective(c.fov, float(w) / float(h), 0.01, 200); loadModels(); //sl->bh.PutblockTest(); //CarSim.Init(this); } void loadModels() { SceneManager* scene = SceneContainer::getInstance().get("scene1"); SceneNode* root = scene->GetSceneRoot(); SceneNode* s; //s = LoadMeshtoSceneNode("model/edushi/exportcity/city.obj", "city"); //s->scale(0.01, 0.01, 0.01); //root->attachNode(s); //s = LoadMeshtoSceneNode("model/edushi/city2.obj", "city"); //s->scale(0.01, 0.01, 0.01); //root->attachNode(s); } };
#ifndef __BOX_HPP__ #define __BOX_HPP__ class Box { private: int id; public: Box(); Box(int); Box(const Box&); Box& operator=(const Box&); ~Box(); void peek(); }; #endif
#include<bits/stdc++.h> using namespace std; main() { char s1[300], s2[300], s3[300]; while(cin>>s1>>s2) { int j=0; int len = strlen(s2); for(int i=len-1; i>=0; i--) { s3[j] = s2[i]; j++; } s3[j] = '\0'; if(strcmp(s1, s3)==0) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
#include <iostream> #include <vector> #include <string> using namespace std; class TheSimilarNumbers { public: int find(int lower,int upper) { int count = 0; int countFromUpper = 0; int countFromLower = 0; int work = upper; while (work > lower) { ++countFromUpper; work /= 10; } work = lower; while (work <= upper) { ++countFromLower; work *= 10; ++work; } if (countFromLower > countFromUpper) { count = countFromLower; } else { count = countFromUpper; } return count; } };
#include<bits/stdc++.h> using namespace std; typedef unsigned long long ull; const ull base=131; const ull mod=212370440130137957ll; ull a[10005]; char s[10005]; ull Hash(char s[]){ int i; ull ans=0; for(i=0;s[i];i++) ans=(ans*base+(ull)s[i])%mod; return ans; }
#include <iostream> #include <cmath> #include <vector> #include <string> #include <sstream> #include <iterator> #include <regex> using namespace std; struct Bus { int id; int idx; Bus(int id, int idx) : id(id), idx(idx){} }; using ull = unsigned long long; using ll = long long; ull extendedEuclidean(ull a, ull b, ll & a_mul, ll & b_mul){ if(a == 0){ a_mul = 0; b_mul = 1; return b; } else { ull q = b/a; // b = q*a + r // q = b div a ull r = b - q*a; // r = b mod a ll x, y; ull gcd = extendedEuclidean(r, a, x, y); a_mul = y - (ll)q * x; b_mul = x; return gcd; } } int main(){ vector<Bus> input; string line; int timestamp; cin >> timestamp >> line; regex re("(\\d|x)+"); auto busIds = sregex_iterator(line.begin(), line.end(), re); auto b_end = sregex_iterator(); auto b_beg = busIds; int idx = 0; ll prod = 1; for(sregex_iterator bi = b_beg; bi != b_end; bi++, idx++){ smatch m = *bi; string ms = m.str(); if(ms[0] != 'x'){ stringstream ss(ms); int id; ss >> id; prod *= id; input.push_back(Bus(id, idx)); } } cout << "prod = " << prod << endl; ll res = 0; for(Bus b : input){ // https://en.wikipedia.org/wiki/Chinese_remainder_theorem#Existence_(direct_construction) ll prod_sub = prod/((ll)b.id); ll mul, tmp; extendedEuclidean(prod_sub, b.id, mul, tmp); cout << mul << endl; ll newPart = (b.id-(b.idx%b.id))*mul*prod_sub; res += newPart; cout << "res: " << res << endl; } if(res < 0LL){ res = res % prod; res += prod; } res = res % prod; cout << "res = " << res << endl; cout << "Check:" << endl; for(auto i : input){ cout << i.idx << ": " << i.id << " " << (res+i.idx)%((ull)i.id) << endl; } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef DROPZONE_ATTRIBUTE_H #define DROPZONE_ATTRIBUTE_H #ifdef DRAG_SUPPORT #include "modules/logdoc/complex_attr.h" /** * This class is used to represent dropzone attribute. * * It stores attribute value in two data representations: string and structure containing operation type enum * and accepted data types. **/ class DropzoneAttribute : public ComplexAttr { public: enum OperationType { OPERATION_COPY, OPERATION_MOVE, OPERATION_LINK }; /** The structure describing data acceptable by a dropzone. */ struct AcceptedData { public: /** Enumerates all kinds of data which might be accepted by the dropzone. * The d'n'd specification currently defines only 'string' and 'file' data kind as valid. */ enum { /** The data kind is unknown i.e. it's neither 'string' nor 'file'. */ DATA_KIND_UNKNOWN, /** The data kind is 'string'. */ DATA_KIND_FILE, /** The data kind is 'file'. */ DATA_KIND_STRING } m_data_kind; /** A mime type of the data. */ OpString m_data_type; }; virtual ~DropzoneAttribute() {} static DropzoneAttribute* Create(const uni_char* attr_str, size_t str_len); // Implements ComplexAttr. virtual OP_STATUS CreateCopy(ComplexAttr **copy_to); virtual OP_STATUS ToString(TempBuffer *buffer) { return buffer->Append(m_string.CStr()); } virtual BOOL Equals(ComplexAttr* other) { OP_ASSERT(other); return uni_strcmp(GetAttributeString(), static_cast<DropzoneAttribute*>(other)->GetAttributeString()) == 0; } /** * Fully set value of attribute. * * @param attr_str Non-null string which has to be set on attribute. Will * be split on whitespaces. * * @return OpStatus::OK or OOM. */ OP_STATUS Set(const uni_char* attr_str, size_t str_len); /** Get attribute literal string value. */ const uni_char* GetAttributeString() const { return m_string.CStr(); } /** Get attribute literal string value. */ OperationType GetOperation() const { return m_operation; } /** Gets accepted data types */ const OpVector<AcceptedData>& GetAcceptedData() const { return m_list; } private: DropzoneAttribute() : m_operation(OPERATION_COPY) {} OpAutoVector<AcceptedData> m_list; //< A vector of accepted data containing data type and mime. OperationType m_operation; //< Allowed operation. OpString m_string; //< Attribute string, includes whitespaces. }; #endif // DRAG_SUPPORT #endif // DROPZONE_ATTRIBUTE_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2005-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Peter Krefting */ #if !defined OPCONSOLEENGINE_H && defined OPERA_CONSOLE #define OPCONSOLEENGINE_H #include "modules/hardcore/mh/messobj.h" #include "modules/util/simset.h" class OpConsoleListener; class OpConsoleFilter; class Window; class OpWindowCommander; /** Global console engine object. */ #define g_console (g_opera->console_module.OpConsoleEngine()) /** * The Opera Console. This class is the engine of the Opera message console. * It will store a list of messages up to a configured maximum size. When * that number is exceeded, the oldest message will be deleted. */ class OpConsoleEngine : private MessageObject { public: /** * First-phase constructor. */ OpConsoleEngine(); /** * Second-phase constructor. * * @param size Number of messages to keep in the console. */ void ConstructL(size_t size); /** * Destructor. */ virtual ~OpConsoleEngine(); /** * Source description for messages to the console. This list should * be kept in synch with m_keywords in opconsoleengine.cpp to * ensure that serialization from/to preferences works properly. */ enum Source { EcmaScript, ///< EcmaScript message #ifdef _APPLET_2_EMBED_ Java, ///< Java message #endif #ifdef M2_SUPPORT M2, ///< M2 message #endif Network, ///< Networking code XML, ///< XML parser and related code HTML, ///< HTML parser and related code CSS, ///< CSS parser and related code #ifdef XSLT_SUPPORT XSLT, ///< XSLT parser and related code #endif #ifdef SVG_SUPPORT SVG, ///< SVG parser and related code #endif #ifdef _BITTORRENT_SUPPORT_ BitTorrent, ///< BitTorrent message #endif #ifdef GADGET_SUPPORT Gadget, ///< Gadget message #endif #if defined(SUPPORT_DATA_SYNC) || defined(WEBSERVER_SUPPORT) OperaAccount, ///< Opera Account message for Opera Link and Opera Unite #endif #ifdef SUPPORT_DATA_SYNC OperaLink, ///< Opera Link messages #endif // SUPPORT_DATA_SYNC #ifdef WEBSERVER_SUPPORT OperaUnite, ///< Opera Unite messages #endif // WEBSERVER_SUPPORT #ifdef AUTO_UPDATE_SUPPORT AutoUpdate, ///< Autoupdate messages #endif Internal, ///< Internal debugging messages #ifdef DATABASE_MODULE_MANAGER_SUPPORT PersistentStorage, ///< HTML5 Persistant Storage / Web Storage #endif //DATABASE_MODULE_MANAGER_SUPPORT #ifdef WEBSOCKETS_SUPPORT WebSockets, ///< WebSocket message #endif //WEBSOCKETS_SUPPORT #ifdef GEOLOCATION_SUPPORT Geolocation, ///< Geolocation message #endif // GEOLOCATION_SUPPORT #ifdef MEDIA_SUPPORT Media, ///< Media (<video>, <track> et al.) #endif // MEDIA_SUPPORT #ifdef _PLUGIN_SUPPORT_ Plugins, ///< Plug-in messages #endif // _PLUGIN_SUPPORT_ // Insert new components above #ifdef SELFTEST SelfTest, ///< Used by internal selftest code #endif SourceTypeLast ///< Sentinel value, not allowed in messages }; /** * Severity indication for messages to the console. */ enum Severity { #ifdef _DEBUG Debugging = 0, ///< Internal debugging information (debug builds only) #endif Verbose = 1, ///< Verbose log information, not normally shown in the UI console Information, ///< Standard log information, normally shown in the UI console Error, ///< Error information, which would pop up the UI console if enabled Critical, ///< Critical error information, which would always pop up the UI console DoNotShow ///< Special severity used for filters to not show messages. }; /** * Structure used for posting messages to the console. */ struct Message { unsigned int id; ///< ID of the message (Can be used in GetMessage call) enum Source source; ///< Sender of message enum Severity severity; ///< Severity of message unsigned long window; ///< Window associated with message (0 if none) time_t time; ///< Time (set automatically if 0) OpString url; ///< URL associated with message (empty if none) OpString context; ///< Context associated with message OpString message; ///< Message text INT32 error_code; ///< Error code associated with the message Message(Source src, Severity sev, unsigned long window_id = 0, time_t posted_time = 0) : source(src), severity(sev), window(window_id), time(posted_time) {}; Message(Source src, Severity sev, OpWindowCommander *wic, time_t posted_time = 0); Message(Source src, Severity sev, Window *win, time_t posted_time = 0); Message() : window(0), time(0) {}; /** Deep copy data from another OpConsoleEngine::Message struct. */ void CopyL(const Message *); /** Deallocate all data used by this message. */ void Clear(); private: Message operator = (const Message &); ///< Prohibit use of unsafe copying. Message(const Message &); ///< Prohibit use of unsafe copying. }; /** * Post a message to the Opera console. The data in the posted object * is copied and must be deleted by the caller. If the console has been * configured to display whenever an error message appears, calling * this with a severity of Error or higher will cause it to be displayed. * * Messages posted for a window running in privacy mode will be dropped. * If the console stores no backlog (CON_NO_BACKLOG), and there are no * listeners, the message will also be blocked. In both these cases, * the special value MESSAGE_BLOCKED will be returned. * * @param msg Message to post. * @return Number assigned to the posted message, or MESSAGE_BLOCKED. */ unsigned int PostMessageL(const OpConsoleEngine::Message *msg); /** Non-leaving version of PostMessageL. */ OP_STATUS PostMessage(const OpConsoleEngine::Message *msg, unsigned int& message_number) { TRAPD(rc, message_number = PostMessageL(msg)); return rc; } /** Non-leaving version of PostMessageL, which ignores message_number.*/ inline OP_STATUS PostMessage(const OpConsoleEngine::Message *msg) { unsigned int unused; return PostMessage(msg, unused); } enum { MESSAGE_BLOCKED = static_cast<unsigned int>(-1) }; /** * Retrieve a message from the Opera console. The returned pointer is * owned by the console and is not guaranteed to live beyond the next * call to GetMessage() or PostMessageL(). * * @param id Number of the message to retrieve. * @return Pointer to the message structure. NULL if message does not * exist. */ const OpConsoleEngine::Message *GetMessage(unsigned int id); /** * Retrieve the number of the oldest stored message. If this number * is higher than the return value from GetHighestId(), there are * no messages in the console. * * @return id Number of the oldest meessage. */ inline unsigned int GetLowestId() { return m_lowest_id; } /** * Retrieve the number of the most recently stored message. If this * number if lower than the return value from GetHighestId(), there * are no messages in the console. * * @return id Number of the most recently meessage. */ inline unsigned int GetHighestId() { return m_highest_id; } /** * Remove all messages stored in the console. */ void Clear(); /** * Register a console listener. The listener will be notified each time * a new message is posted to the console. */ inline void RegisterConsoleListener(OpConsoleListener *listener); /** * Unregister a console listener. The listener will no longer be notified * of changes. */ inline void UnregisterConsoleListener(OpConsoleListener *listener); /** * Is the console engine actually logging messages? This can be called to * see if there is any point in generating the message at all. */ inline BOOL IsLogging(); #ifdef CON_GET_SOURCE_KEYWORD /** * Retrieve the internal string representation of a console source. */ inline const char *GetSourceKeyword(Source source); #endif private: Head m_listeners; ///< List of console listeners. Message *m_messages; ///< Circular buffer of messages in the console. unsigned int m_lowest_id; ///< Lowest message id. unsigned int m_highest_id; ///< Highest message id. size_t m_size; ///< Size of message buffer. BOOL m_pending_broadcast; ///< Broadcast of messages is pending. #ifdef CON_GET_SOURCE_KEYWORD /** String representations of message sources */ # ifdef HAS_COMPLEX_GLOBALS static const char * const m_keywords[static_cast<int>(OpConsoleEngine::SourceTypeLast)]; # else const char *m_keywords[static_cast<int>(OpConsoleEngine::SourceTypeLast)]; void InitSourceKeywordsL(); # endif #endif // Inherited interfaces from MessageObject: virtual void HandleCallback(OpMessage, MH_PARAM_1, MH_PARAM_2); }; /** * Interface for listening to messages from the OpConsoleEngine. * Implementations of this class that are registered with the g_engine object * will receive a signal for each new message that is posted to the Opera * console. It can then chose to either process that message or ignore it as * it sees fit. */ class OpConsoleListener : private Link { public: /** * A new message has been posted to the console. * * @param id Number of the posted message. * @param message The posted message. */ virtual OP_STATUS NewConsoleMessage(unsigned int id, const OpConsoleEngine::Message *message) = 0; private: friend class OpConsoleEngine; }; inline void OpConsoleEngine::RegisterConsoleListener(OpConsoleListener *listener) { listener->Into(&m_listeners); } inline void OpConsoleEngine::UnregisterConsoleListener(OpConsoleListener *listener) { listener->Out(); } inline BOOL OpConsoleEngine::IsLogging() { #ifdef CON_NO_BACKLOG return m_listeners.Cardinal() > 0; #else return TRUE; #endif } #ifdef CON_GET_SOURCE_KEYWORD inline const char *OpConsoleEngine::GetSourceKeyword(Source source) { # ifdef HAS_COMPLEX_GLOBALS return OpConsoleEngine::m_keywords[source]; # else return m_keywords[source]; # endif } #endif #endif // OPCONSOLEENGINE_H
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <string> #include <cstdio> #include <cstring> #include <climits> #include <set> using namespace std; int main() { int n; cin >> n; vector<int> v(n+1, 0); int sum = 0; int d; for (int i = 1; i <= n; i++) { cin >> d; sum += d; v[i] = sum; } cin >> n; int a, b; while (n--) { cin >> a >> b; if (a > b) swap(a, b); cout << min(v[b - 1] - v[a - 1], sum - (v[b - 1] - v[a - 1])) << endl; } return 0; }
//知识点:模拟 /* By:Luckyblock 题目要求: 进行区间矩阵修改,所有修改完成后,查询单点权值 发现询问是离线的,并且只有一次 所以可以将修改操作也进行离线处理 , 对于区间矩阵修改, 只需要判断它对查询单点有无影响即可 如果矩阵覆盖了 单点, 那么将单点的权值,更改为修改后的权值 */ #include<cstdio> #include<ctype.h> const int MARX = 1e5+10; //============================================================= int x,y,n,p=-1, a[MARX],b[MARX],g[MARX],k[MARX]; //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } //============================================================= signed main() { n=read(); for(int i=1;i<=n;i++) a[i]=read(),b[i]=read(),g[i]=read(),k[i]=read(); x=read(),y=read(); for(int i=1;i<=n;i++)//枚举每一个修改操作 { int l1=a[i] , l2=b[i] , r1=a[i]+g[i] , r2=b[i]+k[i];//修改区间 if(x<=r1 && x>=l1)//判断是否影响到单点 if(y<=r2 && y>=l2) p=i;//更新单点权值 } printf("%d",p); }
/* * 题目:203. 移除链表元素 * 链接:https://leetcode-cn.com/problems/remove-linked-list-elements/ * 知识点:链表的遍历与节点删除 */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode *tHead = new ListNode(); tHead->next = head; ListNode *p = tHead; while (p != nullptr && p->next != nullptr) { ListNode *nextNode = p->next; if (nextNode->val == val) { p->next = nextNode->next; } else { p = p->next; } } return tHead->next; } };
#pragma once class CUserManager : public CMultiThreadSync<CUserManager> { public: CUserManager(); ~CUserManager(); private: std::vector<CUserSession*> m_UserSessionVector; SOCKET m_ListenSocket; public: BOOL Begin(DWORD maxUserCount, SOCKET listenSocket); BOOL End(VOID); BOOL AcceptAll(VOID); BOOL WriteAll(DWORD protocol, BYTE *data, DWORD dataLength); CUserSession* GetSession(CPacketSession* pPacketSession); };
#pragma once //====================================================================== #include <upl/common.hpp> #include <upl/definitions.hpp> #include <set> #include <unordered_map> #include <utility> //====================================================================== #ifdef __GNUG__ /* * GCC seems to not have hash<basic_string<uint8_t> >. We provide a simple * implementation as a workaround. */ namespace std { template <> struct hash<basic_string<uint8_t> > { inline size_t operator()(const basic_string<uint8_t> & us) const { hash<char *> cstring_hash; return cstring_hash((char *) us.c_str()); } }; } #endif /* __GNUG__ */ //====================================================================== namespace UPL { namespace Type { //====================================================================== // This file implements the ST-Code codec and a container for them. // (ST-Code: Sertialized Type Code. A compact serialized form for the // types defined in the language.) //====================================================================== typedef uint32_t ID; typedef uint32_t Size; ID const InvalidID = 0; //---------------------------------------------------------------------- #define TAG_ENUM(v,e,s,b0,b1,b2,b3,b4) e = v, enum class Tag : uint8_t { UPL_PRIVATE__TYPE_TAGS(TAG_ENUM) }; #undef TAG_ENUM #define TAG_COUNT(v,e,s,b0,b1,b2,b3,b4) +1 int const TagCount = UPL_PRIVATE__TYPE_TAGS(TAG_COUNT); #undef TAG_COUNT static_assert (TagCount < 32, "Can't accomodate more than 5 bits worth of tags."); //---------------------------------------------------------------------- struct TagInfo_t { Tag tag; char const * name; bool is_basic; // Is this type stand-alone (doesn't depend on any other type, e.g. "int" vs. "array" which requires specifying "array of what.") bool is_scalar; // Does this hold only one value? And yes, strings are scalar. bool is_composite; // Is this a "product" type (e.g. structs in C.) bool is_collection; // Is this a collection of same-type values (e.g. array and strings. Yes, strings.) bool is_callable; // Can you call an instance of this type, as in a function? }; //---------------------------------------------------------------------- TagInfo_t TagInfo (Tag tag); inline uint8_t TagToInt (Tag tag) {return int(tag);} inline Tag IntToTag (uint8_t i) {return Tag(i);} //====================================================================== typedef std::basic_string<uint8_t> STIR; // ST Intermediate Representation! typedef std::basic_string<uint8_t> PackedST; //---------------------------------------------------------------------- struct Unpacked { Tag tag = Tag::INVALID; ID type1 = InvalidID; ID type2 = InvalidID; Size size = 0; std::vector<ID> type_list; bool is_const = false; Unpacked () {} explicit Unpacked (Tag tag_, bool is_const_) : tag (tag_), is_const (is_const_) {} Unpacked (Tag tag_, bool is_const_, ID type1_) : tag (tag_), type1 (type1_), is_const (is_const_) {} Unpacked (Tag tag_, bool is_const_, ID type1_, ID type2_, Size size_) : tag (tag_), type1 (type1_), type2 (type2_), size (size_), is_const (is_const_) {} Unpacked (Tag tag_, bool is_const_, std::vector<ID> type_list_) : tag (tag_), type_list (std::move(type_list_)), is_const (is_const_) {} Unpacked (Tag tag_, bool is_const_, ID type1_, std::vector<ID> type_list_) : tag (tag_), type1 (type1_), type_list (std::move(type_list_)), is_const (is_const_) {} PackedST pack () const; }; //====================================================================== class STCode { public: static uint8_t const msc_StashedEntryBit = (1 << 7); static uint8_t const msc_ConstnessBit = (1 << 6); static uint8_t const msc_OddLengthBit = (1 << 5); public: // Being "odd length" means that the least signigicant 4 bits of the last // byte the *packed* form is not part of the ST-code. static inline uint8_t SerializeTag (Tag tag, bool is_const, bool is_odd_length); static inline Tag GetTag (uint8_t serialized_tag); static inline bool IsValid (uint8_t serialized_tag); static inline bool IsConst (uint8_t serialized_tag); static inline bool IsOddLength (uint8_t serialized_tag); static inline void RetagLengthOddness (STIR & st_ir); static inline STIR SerializeInt (uint32_t v); static inline uint32_t DeserializeInt (uint8_t const * const mem, unsigned & start_qrtt); // Returns the deserialized number and the number of quartets it required template <typename F> static inline std::pair<uint32_t, int> DeserializeInt (int base_quartet, F const & quartet_fetcher); template <typename F> static inline uint32_t DeserializeInt (F const & quartet_fetcher, int & start_quartet); static inline STIR MakeInvalid (); static inline STIR MakeBasic (bool is_const, Tag tag); static inline STIR MakeVariant (bool is_const, std::set<ID> const & allowed_types); static inline STIR MakeArray (bool is_const, Size size, ID type); static inline STIR MakeVector (bool is_const, ID type); static inline STIR MakeMap (bool is_const, ID key_type, ID value_type); static inline STIR MakeTuple (bool is_const, std::vector<ID> const & field_types); static inline STIR MakePackage (bool is_const, std::vector<ID> const & field_types); static inline STIR MakeFuction (bool is_const, ID return_type, std::vector<ID> const & param_types); static inline STIR MakeNil () {return MakeBasic(false, Tag::Nil);} static inline STIR MakeBool (bool is_const) {return MakeBasic(is_const, Tag::Bool);} static inline STIR MakeByte (bool is_const) {return MakeBasic(is_const, Tag::Byte);} static inline STIR MakeChar (bool is_const) {return MakeBasic(is_const, Tag::Char);} static inline STIR MakeInt (bool is_const) {return MakeBasic(is_const, Tag::Int);} static inline STIR MakeReal (bool is_const) {return MakeBasic(is_const, Tag::Real);} static inline STIR MakeString (bool is_const) {return MakeBasic(is_const, Tag::String);} static inline STIR MakeAny (bool is_const) {return MakeBasic(is_const, Tag::Any);} static inline int PackedSize (STIR const & st_ir); // in bytes, rounded up static inline int UnpackedSize (PackedST const & packed_st); static inline PackedST Pack (STIR const & st_ir); static inline STIR Unpack (PackedST const & packed_st); static inline bool IsValid (PackedST const & packed_st); private: static inline uint8_t Qrtt (uint32_t v, unsigned quartet); // Zero is the low-order 4 bits static inline uint8_t Qrtt (uint8_t const * packed_mem, unsigned quartet); // Zero is the high-order 4 bits }; //---------------------------------------------------------------------- //====================================================================== class STContainer { private: struct Entry { uint8_t bytes [4]; }; typedef std::unordered_map<PackedST, ID> TypeLookup; public: STContainer (); ~STContainer (); size_t size () const {return m_types.size();} ID createType (PackedST const & packed_st); ID createType (Unpacked const & unpacked); ID lookupType (PackedST const & packed_st) const; ID byTag (Tag tag) const; inline bool isValid (ID id) const; inline Tag tag (ID id) const; inline bool isConst (ID id) const; inline std::vector<ID> getVariantTypes (ID id) const; inline std::vector<ID> getTupleTypes (ID id) const; inline std::vector<ID> getPackageTypes (ID id) const; inline std::vector<ID> getFunctionParamTypes (ID id) const; inline ID getArrayType (ID id) const; inline ID getVectorType (ID id) const; inline ID getMapKeyType (ID id) const; inline ID getMapValueType (ID id) const; inline ID getFunctionReturnType (ID id) const; inline Size getArraySize (ID id) const; Unpacked unpack (ID id) const; private: uint32_t stashCurPos() const { return uint32_t(m_stash.size()); } inline bool isInline (ID id) const; inline uint32_t stashedIndex (ID id) const; inline void setInlineEntry (ID id, bool is_inline); inline void setStashIndex (ID id, uint32_t stash_index); inline uint8_t getByte (ID id, int b) const; inline uint8_t getQuartet (ID id, int q) const; // Starting from _after_ the first byte (the tag byte.) std::vector<ID> getTypeList (ID id) const; // For Variant, Tuple, Package std::vector<ID> getParamTypeList (ID id) const; // For Function ID getFirstType (ID id) const; // For Array, Vector, Map (key), Function (return type) ID getSecondType (ID id) const; // For Map (value) Size getSize (ID id) const; // For Array private: std::vector<Entry> m_types; std::basic_string<uint8_t> m_stash; TypeLookup m_lookup; private: static_assert (sizeof(Entry) == 4, "Entry was expected to be 4 bytes long."); }; //====================================================================== } // namespace Types } // namespace UPL //====================================================================== //====================================================================== namespace UPL { namespace Type { //====================================================================== inline uint8_t STCode::SerializeTag (Tag tag, bool is_const, bool is_odd_length) { uint8_t ret = TagToInt (tag); if (is_const) ret |= msc_ConstnessBit; if (is_odd_length) ret |= msc_OddLengthBit; return ret; } //---------------------------------------------------------------------- inline Tag STCode::GetTag (uint8_t serialized_tag) { static_assert (msc_OddLengthBit < msc_ConstnessBit, ""); return IntToTag (serialized_tag & (msc_OddLengthBit - 1)); } //---------------------------------------------------------------------- inline bool STCode::IsValid (uint8_t serialized_tag) { return GetTag(serialized_tag) != Tag::INVALID; } //---------------------------------------------------------------------- inline bool STCode::IsConst (uint8_t serialized_tag) { return 0 != (serialized_tag & msc_ConstnessBit); } //---------------------------------------------------------------------- inline bool STCode::IsOddLength (uint8_t serialized_tag) { return 0 != (serialized_tag & msc_OddLengthBit); } //---------------------------------------------------------------------- inline void STCode::RetagLengthOddness (STIR & st_ir) { // Yeah! The length-oddness bit is set when the length is even! :D // But keep in mind that the first byte of STIR actually holds two quartets. if (st_ir.size() > 0 && (st_ir.size() % 2) == 0) st_ir[0] |= msc_OddLengthBit; } //---------------------------------------------------------------------- inline STIR STCode::SerializeInt (uint32_t v) { if (v < 8) return STIR({uint8_t(v)}); else if (v < 0x10) return STIR({uint8_t(7+1), Qrtt(v,0)}); else if (v < 0x100) return STIR({uint8_t(7+2), Qrtt(v,1), Qrtt(v,0)}); else if (v < 0x1000) return STIR({uint8_t(7+3), Qrtt(v,2), Qrtt(v,1), Qrtt(v,0)}); else if (v < 0x10000) return STIR({uint8_t(7+4), Qrtt(v,3), Qrtt(v,2), Qrtt(v,1), Qrtt(v,0)}); else if (v < 0x100000) return STIR({uint8_t(7+5), Qrtt(v,4), Qrtt(v,3), Qrtt(v,2), Qrtt(v,1), Qrtt(v,0)}); else if (v < 0x1000000) return STIR({uint8_t(7+6), Qrtt(v,5), Qrtt(v,4), Qrtt(v,3), Qrtt(v,2), Qrtt(v,1), Qrtt(v,0)}); else if (v < 0x10000000) return STIR({uint8_t(7+7), Qrtt(v,6), Qrtt(v,5), Qrtt(v,4), Qrtt(v,3), Qrtt(v,2), Qrtt(v,1), Qrtt(v,0)}); else return STIR({uint8_t(7+8), Qrtt(v,7), Qrtt(v,6), Qrtt(v,5), Qrtt(v,4), Qrtt(v,3), Qrtt(v,2), Qrtt(v,1), Qrtt(v,0)}); } //---------------------------------------------------------------------- inline uint32_t STCode::DeserializeInt (uint8_t const * const packed_mem, unsigned & q) { auto len = Qrtt(packed_mem, q++); if (len < 8) return len; uint32_t ret = 0; for (int i = len - 7; i > 0; --i) ret = (ret << 4) | Qrtt(packed_mem, q++); return ret; } //---------------------------------------------------------------------- template <typename F> inline std::pair<uint32_t, int> STCode::DeserializeInt (int base_quartet, F const & quartet_fetcher) { uint8_t len = quartet_fetcher(base_quartet + 0); if (len < 8) return {len, 1}; len -= 6; uint32_t ret = 0; for (int i = 1; i < len; ++i) ret = (ret << 4) | quartet_fetcher(base_quartet + i); return {ret, len}; } //---------------------------------------------------------------------- template <typename F> inline uint32_t STCode::DeserializeInt (F const & quartet_fetcher, int & start_quartet) { auto len = quartet_fetcher (start_quartet++); if (len < 8) return len; uint32_t ret = 0; for (int i = len - 7; i > 0; --i) ret = (ret << 4) | quartet_fetcher(start_quartet++); return ret; } //---------------------------------------------------------------------- inline STIR STCode::MakeInvalid () { return STIR({SerializeTag (Tag::INVALID, false, false)}); } //---------------------------------------------------------------------- inline STIR STCode::MakeBasic (bool is_const, Tag tag) { assert (TagInfo(tag).is_basic); return STIR({SerializeTag (tag, is_const, false)}); } //---------------------------------------------------------------------- inline STIR STCode::MakeVariant (bool is_const, std::set<ID> const & allowed_types) { STIR ret; ret += SerializeTag (Tag::Variant, is_const, false); ret += SerializeInt (uint32_t(allowed_types.size())); for (auto id : allowed_types) ret += SerializeInt (id); RetagLengthOddness (ret); return ret; } //---------------------------------------------------------------------- inline STIR STCode::MakeArray (bool is_const, Size size, ID type) { STIR ret; ret += SerializeTag (Tag::Array, is_const, false); ret += SerializeInt (size); ret += SerializeInt (type); RetagLengthOddness (ret); return ret; } //---------------------------------------------------------------------- inline STIR STCode::MakeVector (bool is_const, ID type) { STIR ret; ret += SerializeTag (Tag::Vector, is_const, false); ret += SerializeInt (type); RetagLengthOddness (ret); return ret; } //---------------------------------------------------------------------- inline STIR STCode::MakeMap (bool is_const, ID key_type, ID value_type) { STIR ret; ret += SerializeTag (Tag::Map, is_const, false); ret += SerializeInt (key_type); ret += SerializeInt (value_type); RetagLengthOddness (ret); return ret; } //---------------------------------------------------------------------- inline STIR STCode::MakeTuple (bool is_const, std::vector<ID> const & field_types) { STIR ret; ret += SerializeTag (Tag::Tuple, is_const, false); ret += SerializeInt (uint32_t(field_types.size())); for (auto id : field_types) ret += SerializeInt (id); RetagLengthOddness (ret); return ret; } //---------------------------------------------------------------------- inline STIR STCode::MakePackage (bool is_const, std::vector<ID> const & field_types) { STIR ret; ret += SerializeTag (Tag::Package, is_const, false); ret += SerializeInt (uint32_t(field_types.size())); for (auto id : field_types) ret += SerializeInt (id); RetagLengthOddness (ret); return ret; } //---------------------------------------------------------------------- inline STIR STCode::MakeFuction (bool is_const, ID return_type, std::vector<ID> const & param_types) { STIR ret; ret += SerializeTag (Tag::Function, is_const, false); ret += SerializeInt (return_type); ret += SerializeInt (uint32_t(param_types.size())); for (auto id : param_types) ret += SerializeInt (id); RetagLengthOddness (ret); return ret; } //---------------------------------------------------------------------- inline int STCode::PackedSize (STIR const & st_ir) { assert (st_ir.size() > 0); // One byte for the first byte of STIR (which has 7 significant bits.) // Plus one byte per two bytes of STIR (each with 4 significant bits.) // The bottom bits of the last byte of output are filled with 0 if needed. return 1 + int(st_ir.size()) / 2; } //---------------------------------------------------------------------- inline int STCode::UnpackedSize (PackedST const & packed_st) { assert (packed_st.size() > 0); return + 1 + 2 * (int(packed_st.size()) - 1) - (IsOddLength(packed_st[0]) ? 1 : 0); } //---------------------------------------------------------------------- inline PackedST STCode::Pack (STIR const & st_ir) { auto s = PackedSize(st_ir); assert (st_ir[st_ir.size()] == 0); // Assume there's a NUL at the end of st_ir; this is BAD. PackedST ret (s, 0); ret[0] = st_ir[0]; for (int i = 1, j = 1, n = int(st_ir.size()); j < n; ++i, j += 2) ret[i] = ((st_ir[j] & 0xF) << 4) | (st_ir[j + 1] & 0xF); return ret; } //---------------------------------------------------------------------- inline STIR STCode::Unpack (PackedST const & packed_st) { auto s = UnpackedSize(packed_st); STIR ret (s, 0xFF); assert (ret[ret.size()] == 0); // Assume there's a NUL at the end of ret; this is BAD. ret[0] = packed_st[0]; for (int i = 1, j = 1, n = int(packed_st.size()); j < n; i += 2, ++j) { ret[i] = (packed_st[j] >> 4) & 0xF; ret[i + 1] = packed_st[j] & 0xF; } ret[ret.size()] = 0; return ret; } //---------------------------------------------------------------------- inline bool STCode::IsValid (PackedST const & packed_st) { return packed_st.size() > 0 && IsValid(packed_st[0]); } //---------------------------------------------------------------------- //---------------------------------------------------------------------- inline uint8_t STCode::Qrtt (uint32_t v, unsigned quartet) { return (v >> (4 * quartet)) & 0x0F; } //---------------------------------------------------------------------- inline uint8_t STCode::Qrtt (uint8_t const * packed_mem, unsigned quartet) { unsigned const shift = 4 * (1 - (quartet & 1)); return (packed_mem[quartet >> 1] >> shift) & 0x0F; } //====================================================================== inline bool STContainer::isValid (ID id) const { return id < m_types.size(); } //---------------------------------------------------------------------- inline Tag STContainer::tag (ID id) const { if (id >= m_types.size()) return Tag::INVALID; else return STCode::GetTag(getByte(id, 0)); } //---------------------------------------------------------------------- inline bool STContainer::isConst (ID id) const { if (id >= m_types.size()) return false; else return STCode::IsConst(getByte(id, 0)); } //---------------------------------------------------------------------- inline std::vector<ID> STContainer::getVariantTypes (ID id) const { return getTypeList(id); } //---------------------------------------------------------------------- inline std::vector<ID> STContainer::getTupleTypes (ID id) const { return getTypeList(id); } //---------------------------------------------------------------------- inline std::vector<ID> STContainer::getPackageTypes (ID id) const { return getTypeList(id); } //---------------------------------------------------------------------- inline std::vector<ID> STContainer::getFunctionParamTypes (ID id) const { return getParamTypeList(id); } //---------------------------------------------------------------------- inline ID STContainer::getArrayType (ID id) const { return getSecondType(id); } //---------------------------------------------------------------------- inline ID STContainer::getVectorType (ID id) const { return getFirstType(id); } //---------------------------------------------------------------------- inline ID STContainer::getMapKeyType (ID id) const { return getFirstType(id); } //---------------------------------------------------------------------- inline ID STContainer::getMapValueType (ID id) const { return getSecondType(id); } //---------------------------------------------------------------------- inline ID STContainer::getFunctionReturnType (ID id) const { return getFirstType(id); } //---------------------------------------------------------------------- inline Size STContainer::getArraySize (ID id) const { return getSize(id); } //---------------------------------------------------------------------- inline bool STContainer::isInline (ID id) const { return 0 == (m_types[id].bytes[0] & STCode::msc_StashedEntryBit); } //---------------------------------------------------------------------- inline uint32_t STContainer::stashedIndex (ID id) const { assert(!isInline(id)); auto b = m_types[id]; return ((b.bytes[0] & 0x7F) << 24) | (b.bytes[1] << 16) | (b.bytes[2] << 8) | b.bytes[3]; } //---------------------------------------------------------------------- inline void STContainer::setInlineEntry (ID id, bool is_inline) { if (!is_inline) m_types[id].bytes[0] |= STCode::msc_StashedEntryBit; else { assert (0 == (m_types[id].bytes[0] & STCode::msc_StashedEntryBit)); } } //---------------------------------------------------------------------- inline void STContainer::setStashIndex (ID id, uint32_t stash_index) { assert (stash_index < 0x80000000U); // Must keep the msb free. m_types[id].bytes[0] = (stash_index >> 24) & 0x7F; m_types[id].bytes[1] = (stash_index >> 16) & 0xFF; m_types[id].bytes[2] = (stash_index >> 8) & 0xFF; m_types[id].bytes[3] = stash_index & 0xFF; setInlineEntry (id, false); assert (!isInline(id)); assert (stashedIndex(id) == stash_index); } //---------------------------------------------------------------------- inline uint8_t STContainer::getByte (ID id, int b) const { return isInline(id) ? m_types[id].bytes[b] : m_stash[stashedIndex(id) + b]; } //---------------------------------------------------------------------- inline uint8_t STContainer::getQuartet (ID id, int q) const { auto b = getByte(id, 1 + q / 2); return 0xF & ((q & 1) ? b : (b >> 4)); } //---------------------------------------------------------------------- //====================================================================== } // namespace Types } // namespace UPL //======================================================================
// Author: Kirill Gavrilov // Copyright (c) 2016-2019 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _RWGltf_GltfAccessorCompType_HeaderFile #define _RWGltf_GltfAccessorCompType_HeaderFile //! Low-level glTF enumeration defining Accessor component type. enum RWGltf_GltfAccessorCompType { RWGltf_GltfAccessorCompType_UNKNOWN, //!< unknown or invalid type RWGltf_GltfAccessorCompType_Int8 = 5120, //!< GL_BYTE RWGltf_GltfAccessorCompType_UInt8 = 5121, //!< GL_UNSIGNED_BYTE RWGltf_GltfAccessorCompType_Int16 = 5122, //!< GL_SHORT RWGltf_GltfAccessorCompType_UInt16 = 5123, //!< GL_UNSIGNED_SHORT RWGltf_GltfAccessorCompType_UInt32 = 5125, //!< GL_UNSIGNED_INT RWGltf_GltfAccessorCompType_Float32 = 5126, //!< GL_FLOAT }; #endif // _RWGltf_GltfAccessorCompType_HeaderFile
#include <iostream> #include "cqueue.h" #include <string.h> using namespace std; CQueue::CQueue() //constructor { front=MAX-1; rear=MAX-1; } bool CQueue::IsEmpty() { bool emp; if(front == rear) emp= 1; else emp=0; return emp; } bool CQueue::IsFull() { bool ful; if((rear+1)%MAX == front) ful=1; else ful=0; return ful; } void CQueue::Enqueue(Passenger added) { if(IsFull()) { cout<<"Queue is full\n"; //error check } else { rear=(rear+1)% MAX; strcpy(passengers[rear].name, added.name); } } Passenger CQueue::Front() { return passengers[(front+1)%MAX]; } void CQueue::Dequeue() { if(IsEmpty()) { cout<<"Queue is empty\n"; //error check } else { front=(front+1)%MAX; } }
#include "stdafx.h" #include "ModifyDialog.h" ModifyDialog::ModifyDialog(int row, QString num, QWidget* parent) : QDialog(parent) { ui.setupUi(this); m_sqlOprtor = new SQLiteOperator(this); m_row = row; m_oUser = m_sqlOprtor->queryTable(num); m_nUser = m_sqlOprtor->queryTable(num); ui.edit_name->setText(m_nUser->id); ui.edit_num->setText(m_nUser->num); ui.lab_money->setText(QString::number(m_nUser->money) + tr(" RMB")); connect(ui.edit_num, &QLineEdit::returnPressed, this, &ModifyDialog::onBtnModifyClicked); connect(ui.btn_modify, &QPushButton::clicked, this, &ModifyDialog::onBtnModifyClicked); connect(ui.btn_back, &QPushButton::clicked, this, &ModifyDialog::onBtnBackClicked); } void ModifyDialog::onBtnModifyClicked() { QString name = ui.edit_name->text(); QString num = ui.edit_num->text(); if (name.length() <= 0) { //错误!姓名不能为空。重输 QMessageBox* msgBox = new QMessageBox(QMessageBox::Critical, tr("Error !"), tr("Names cannot be empty."), QMessageBox::Ok, this); msgBox->button(QMessageBox::Ok)->setText(tr("Re-input")); msgBox->exec(); } else { if (!isDigitString(num) || num.length() != 10) { //错误!账号应该为10位纯数字。重输 QMessageBox* msgBox = new QMessageBox(QMessageBox::Critical, tr("Error !"), tr("The account number should be 10 digits."), QMessageBox::Ok, this); msgBox->button(QMessageBox::Ok)->setText(tr("Re-input")); msgBox->exec(); } else { if (checkNumRepeat(num)) { //错误!账号已存在,请重新输入。好的 QMessageBox* msgBox = new QMessageBox(QMessageBox::Critical, tr("Error !"), tr("The account already exists. Please re-input."), QMessageBox::Ok, this); msgBox->button(QMessageBox::Ok)->setText(tr("Ok")); msgBox->exec(); } else { m_nUser->id = name; m_nUser->num = num; this->close(); emit modifyInfo(m_row, m_oUser, m_nUser); } } } } //检测字符串是否为纯数字 bool ModifyDialog::isDigitString(const QString& src) { int length = src.length(); if (length <= 0) { return false; } int i = 0; for (; i < length; i++) { if (src.at(i) < '0' || src.at(i) > '9') { break; } } return i >= length; } //检测账号是否重复 bool ModifyDialog::checkNumRepeat(QString& num) { if (num == m_nUser->num)//排除自己的帐号 { return false; } return m_sqlOprtor->queryTable(num); } void ModifyDialog::onBtnBackClicked() { this->close(); } ModifyDialog::~ModifyDialog() { }
// // Created by Cristian Marastoni on 23/04/15. // #include "Debug.h" #include <stdarg.h> #include <stdio.h> void Debug::Log(const char *ctx, const char *fmt, ...) { va_list va; va_start(va, fmt); vprintf(fmt, va); va_end(va); } void Debug::Error(const char *ctx, const char *fmt, ...) { va_list va; va_start(va, fmt); vprintf(fmt, va); va_end(va); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/server/async_tran/QuicServerAsyncTransport.h> #include <folly/Conv.h> namespace quic { void QuicServerAsyncTransport::setServerSocket( std::shared_ptr<quic::QuicSocket> sock) { setSocket(std::move(sock)); } void QuicServerAsyncTransport::onNewBidirectionalStream(StreamId id) noexcept { CHECK_EQ(id, 0) << "only single stream w/ id=0 is supported"; setStreamId(id); } void QuicServerAsyncTransport::onNewUnidirectionalStream( StreamId /*id*/) noexcept { LOG(FATAL) << "Unidirectional stream not supported"; } void QuicServerAsyncTransport::onStopSending( StreamId /*id*/, ApplicationErrorCode /*error*/) noexcept {} void QuicServerAsyncTransport::onConnectionEnd() noexcept { folly::AsyncSocketException ex( folly::AsyncSocketException::UNKNOWN, "Quic connection ended"); closeNowImpl(std::move(ex)); } void QuicServerAsyncTransport::onConnectionError(QuicError code) noexcept { folly::AsyncSocketException ex( folly::AsyncSocketException::UNKNOWN, folly::to<std::string>("Quic connection error", code.message)); closeNowImpl(std::move(ex)); } void QuicServerAsyncTransport::onTransportReady() noexcept {} } // namespace quic
#include <bits/stdc++.h> using namespace std; #define MAX 1000 Class Stack{ int top; public: int a[MAX]; Stack(){ top = -1; } bool push(int x); int pop(); bool isEmpty(); } bool Stack::push(int x){ if(top }
#include <stdio.h> int main() { int remain=0; int reverse=0.0; int num; printf("enter numbers\n"); scanf("%d",&num); while(num !=0) { remain = num % 10; reverse = reverse * 10 + remain; num /=10; } printf("here is the reverse: %d\n",reverse); return 0; }
#include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<string> using namespace std; string IsTriangle(int a, int b, int c) { return "Error"; }
#ifndef COMMANDE_H #define COMMANDE_H #include <QWidget> #include <clienttcp.h> namespace Ui { class commande; } class commande : public QWidget { Q_OBJECT public: explicit commande(QWidget *parent = 0); ~commande(); int number; void connexion(); private slots: void on_pushButton_camera1_clicked(); void on_pushButton_camera2_clicked(); void on_pushButton_camera3_clicked(); void on_pushButton_camera4_clicked(); private: Ui::commande *ui; ClientTcp ClientCamera; }; #endif // COMMANDE_H
/** * created: 2013-4-7 0:15 * filename: FKClass * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #include <string.h> #include <stdlib.h> #include "../Include/FKLogger.h" #include "../Include/RTTI/FKReflect.h" //------------------------------------------------------------------------ RTTIFieldDescriptor* RTTIClassDescriptor::findFieldByAliasName(char const* name,int nbegin,int flag,bool bocasestr){ for (int i=nbegin;i<nFields;i++){ if ( (fields[i]->flags & flag)==flag && (strcmp(fields[i]->aliasname, name) == 0 || (bocasestr && stricmp(fields[i]->aliasname, name) == 0) ) ){ return fields[i]; } } return NULL; } //------------------------------------------------------------------------ RTTIFieldDescriptor* RTTIClassDescriptor::findField(char const* name,int nbegin,int flag) { for (int i=nbegin;i<nFields;i++){ if ( (fields[i]->flags & flag)==flag && strcmp(fields[i]->name, name) == 0 ){ return fields[i]; } } return NULL; } //------------------------------------------------------------------------ static int cmpFields(const void* p, const void* q) { return ((int)(*(RTTIFieldDescriptor**)p)->getOffset())- ((int)(*(RTTIFieldDescriptor**)q)->getOffset()); } //------------------------------------------------------------------------ static int cmpMethods(const void* p, const void* q) { return strcmp((*(RTTIMethodDescriptor**)p)->getName(), (*(RTTIMethodDescriptor**)q)->getName()); } //------------------------------------------------------------------------ RTTIClassDescriptor::RTTIClassDescriptor(char const* name, int size, RTTIDescribeFieldsFunc describeFieldsFunc, RTTIDescribeMethodsFunc describeMethodsFunc, int flags,int sortfieldtype,char const* aliasname, unsigned short int userdefine) : RTTIType(RTTI_STRUCT,userdefine) { this->name = name; this->aliasname=aliasname; if (!this->aliasname){ this->aliasname=name; } this->size = size; this->flags = flags; this->fieldList = NULL; this->methodList = NULL; this->nFields=0; this->fields=NULL; this->nMethods=0; this->methods=NULL; this->nBaseClasses=0; this->baseClassesFields=NULL; this->baseClasses=NULL; fieldList=NULL; if (describeFieldsFunc){ fieldList = (*describeFieldsFunc)(); } methodList=NULL; if (describeMethodsFunc){ methodList = (*describeMethodsFunc)(); } buildClassDescriptor(sortfieldtype); RTTIRepository* repo = RTTIRepository::getInstance(); repo->addClass(this); } //------------------------------------------------------------------------ RTTIClassDescriptor::RTTIClassDescriptor(char const* name, int size, int flags,int sortfieldtype,char const* aliasname,unsigned short int userdefine) : RTTIType(RTTI_STRUCT,userdefine) { this->name = name; this->aliasname=aliasname; if (!this->aliasname){ this->aliasname=name; } this->size = size; this->flags = flags; this->fieldList = NULL; this->methodList = NULL; this->nFields=0; this->fields=NULL; this->nMethods=0; this->methods=NULL; this->nBaseClasses=0; this->baseClassesFields=NULL; this->baseClasses=NULL; initialized = false; } //------------------------------------------------------------------------ void* RTTIClassDescriptor::ConvertClassPtr(void* psrc,RTTIClassDescriptor* src_cls,RTTIClassDescriptor* dst_cls){ int noffset=0; if (src_cls && src_cls->isClass() && src_cls->IsKindOf(dst_cls,&noffset)){ return ((void*)((char*)psrc+noffset)); }else if (dst_cls && dst_cls->isClass() && dst_cls->IsKindOf(src_cls,&noffset)){ return ((void*)((char*)psrc-noffset)); }else { char szbuf[512];char szbuf1[512]; g_logger.warn("源类型 %s* : 目标类型 %s* 没有合适的上下转型路径!",((RTTIType*)src_cls)->getTypeName(szbuf),((RTTIType*)dst_cls)->getTypeName(szbuf1) ); } return NULL; } //------------------------------------------------------------------------ void* RTTIClassDescriptor::ConvertClassPtr(void* p,int ibase){ return ((void*)(((char*)p) + baseClassesFields[ibase]->getOffset())); } //------------------------------------------------------------------------ bool RTTIClassDescriptor::IsKindOf(RTTIClassDescriptor* kindclass,int* offset){ if (kindclass!=this){ for (int i=0;i<nBaseClasses;i++){ if(baseClasses[i]->IsKindOf(kindclass,offset)){ if(offset){ (*offset)=(*offset)+baseClassesFields[i]->getOffset(); } return true; }; } return false; }else if(offset){ (*offset)=(*offset)+0; } return true; } //------------------------------------------------------------------------ void RTTIClassDescriptor::buildClassDescriptor(int sortfieldtype) { int i, n, nb; RTTIFieldDescriptor *fd; RTTIMethodDescriptor* md; for (fd = fieldList, n = 0, nb = 0; fd != NULL; fd = fd->next) { fd->declaringClass = this; if (fd->type != NULL && fd->type->tag == RTTI_DERIVED) { nb++; }else{ n++; } } nBaseClasses = nb; nFields = n; fields=NULL; baseClasses=NULL; if (n>0 || nb>0){ if (n>0){ fields = new RTTIFieldDescriptor*[n]; } if (nb>0){ char* tmp = new char[(sizeof(RTTIClassDescriptor*)+sizeof(int))*(nb+2)]; baseClasses=(RTTIClassDescriptor**)tmp; baseClassesFields=(RTTIFieldDescriptor**)&tmp[sizeof(RTTIClassDescriptor*)*(nb+1)]; } int nf=0;int nfb=0; for (fd = fieldList; fd != NULL; fd = fd->next){ if (fd->type != NULL && fd->type->tag == RTTI_DERIVED && baseClasses){ if (nfb<nb){ baseClasses[nfb] = ((RTTIDerivedType*)fd->type)->getBaseClass(); baseClassesFields[nfb]=fd; nfb++; } }else{ if (nf<n){ fields[nf] = fd;nf++;} } } switch (sortfieldtype) { case eSortByOffSet: { qsort(fields, n, sizeof(RTTIFieldDescriptor*), cmpFields); } break; case eSortByName: default: { } break; } for (i = 0; i < nb; i++) { baseClassesFields[i]->index = i; } for (i = 0; i < n; i++) { fields[i]->index = i; } } for (n = 0, md = methodList; md != NULL; md = md->next) { n += 1; } nMethods = n; methods=NULL; if (n>0){ methods = new RTTIMethodDescriptor*[n]; for (n = 0, md = methodList; md != NULL; md = md->next) { methods[n++] = md; } qsort(methods, n, sizeof(RTTIMethodDescriptor*), cmpMethods); for (i = 0; i < n; i++) { methods[i]->index = i; } } initialized = true; } //------------------------------------------------------------------------ char* RTTIClassDescriptor::getTypeName(char* buf) { strcpy(buf, name); return buf; } //------------------------------------------------------------------------ RTTIMethodDescriptor* RTTIClassDescriptor::findMethodByAliasName(char const* name,int nbegin,int flag,bool bocasestr){ for (int i=nbegin;i<nMethods;i++){ if ( (methods[i]->flags & flag)==flag && (strcmp(methods[i]->aliasname, name) == 0 || (bocasestr && stricmp(methods[i]->aliasname, name) == 0) ) ){ return methods[i]; } } return NULL; } //------------------------------------------------------------------------ RTTIMethodDescriptor* RTTIClassDescriptor::findMethod(char const* name,int nbegin,int flag) { for (int i=nbegin;i<nMethods;i++){ if ( (methods[i]->flags & flag)==flag && strcmp(methods[i]->name, name) == 0 ){ return methods[i]; } } return NULL; } //------------------------------------------------------------------------ RTTIClassDescriptor::~RTTIClassDescriptor() { if (baseClassesFields){ for (int i=0;i<nBaseClasses;i++){ delete baseClassesFields[i]; } delete[] baseClasses; } if (nMethods){ for (int i=0;i<nMethods;i++){ delete methods[i]; } delete[] methods; } if (fields){ for (int i=0;i<nFields;i++){ delete fields[i]; } delete[] fields; } } //------------------------------------------------------------------------
#pragma once #include <string> namespace Codingfield { namespace Brew { namespace Actuators { namespace Relays { enum class States { Unknown, Open, Closed }; class Relay { public: Relay(States initialState); virtual ~Relay() = default; virtual States State() const = 0; virtual void State(States s) = 0; protected: States state; }; const std::string ToString(const States s); } } } }
#include<iostream> using namespace std; int main() { const int a = 0; int b = 3, c = 7; int result = a + b + c; cout << result << endl; a = result; // Считается ошибкой, т.к. константы не перезаписываются cout << a << endl; return 0; }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "base/net/stratum/BaseClient.h" #include "3rdparty/rapidjson/document.h" #include "base/io/Env.h" #include "base/io/log/Log.h" #include "base/io/log/Tags.h" #include "base/kernel/interfaces/IClientListener.h" #include "base/net/stratum/SubmitResult.h" namespace xmrig { int64_t BaseClient::m_sequence = 1; } /* namespace xmrig */ xmrig::BaseClient::BaseClient(int id, IClientListener *listener) : m_listener(listener), m_id(id) { } void xmrig::BaseClient::setPool(const Pool &pool) { if (!pool.isValid()) { return; } m_pool = pool; m_user = Env::expand(pool.user()); m_password = Env::expand(pool.password()); m_rigId = Env::expand(pool.rigId()); m_tag = std::string(Tags::network()) + " " CYAN_BOLD_S + m_pool.url().data() + CLEAR; } bool xmrig::BaseClient::handleResponse(int64_t id, const rapidjson::Value &result, const rapidjson::Value &error) { if (id == 1) { return false; } auto it = m_callbacks.find(id); if (it != m_callbacks.end()) { const uint64_t elapsed = Chrono::steadyMSecs() - it->second.ts; if (error.IsObject()) { it->second.callback(error, false, elapsed); } else { it->second.callback(result, true, elapsed); } m_callbacks.erase(it); return true; } return false; } bool xmrig::BaseClient::handleSubmitResponse(int64_t id, const char *error) { auto it = m_results.find(id); if (it != m_results.end()) { it->second.done(); m_listener->onResultAccepted(this, it->second, error); m_results.erase(it); return true; } return false; }
// // Created by fab on 27/02/2020. // #ifndef DUMBERENGINE_WORLD_HPP #define DUMBERENGINE_WORLD_HPP #include "Chunk.hpp" #include "../IComponent.hpp" #include "../../rendering/helper/Shader.hpp" #include "../../rendering/renderer/opengl/Texture2D.hpp" #include "../../debug/CubeDebug.hpp" class World : public IComponent { public: static const int CHUNK_SIZE = 1; typedef uint8_t MAxis; static const int AXIS_X = 0b00000001; static const int AXIS_Y = 0b00000010; static const int AXIS_Z = 0b00000100; private: Chunk *chunks[CHUNK_SIZE][CHUNK_SIZE][CHUNK_SIZE]; Shader shaderWorld; Texture2D texture; glm::vec3 skyColor; glm::vec3 sunColor; CubeDebug* debug; void setNeighborhood(); public: static glm::vec3 sunDirection; ~World(); World(); void start() override; void update() override; void draw() override; void drawShadow(Shader *pShader) override; bool castShadow() { return true; } void drawInspector() override; void deleteCube(int x, int y, int z); Cube *getCube(int x, int y, int z); void updateCube(int x, int y, int z); Chunk *getChunkAt(int x, int y, int z); MAxis getMinCol(glm::vec3 pos, glm::vec3 dir, float width, float height, float & valueColMin, bool oneShot); }; #endif //DUMBERENGINE_WORLD_HPP
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef DOM_DOMCALLLSTATE_H #define DOM_DOMCALLLSTATE_H #include "modules/ecmascript/ecmascript.h" #include "modules/ecmascript_utils/esthread.h" #include "modules/dom/src/domobj.h" class DOM_CallState : public DOM_Object { public: enum CallPhase { PHASE_NONE = 0, PHASE_SECURITY_CHECK = 1, PHASE_EXECUTION_0 = 2 }; static OP_STATUS Make(DOM_CallState*& new_obj, DOM_Runtime* origining_runtime, ES_Value* argv, int argc); DOM_CallState(); virtual ~DOM_CallState(); virtual void GCTrace(); virtual BOOL IsA(int type) { return type == DOM_TYPE_CALLSTATE || DOM_Object::IsA(type); } static DOM_CallState* FromReturnValue(ES_Value* return_value); static DOM_CallState* FromES_Object(ES_Object* es_object); static OP_STATUS RestoreArgumentsFromRestartValue(ES_Value* restart_value, ES_Value*& argv, int& argc); static CallPhase GetPhaseFromESValue(ES_Value* restart_value); /** Prepares call state for actual suspending * Performs actions necessary for suspending like making copies of strings in argv, which we don't * want to perform if we don't really have to(when we are using it and call doesnt need to suspend). */ OP_STATUS PrepareForSuspend(); void RestoreArguments(ES_Value*& argv, int& argc) const { argv = m_argv; argc = m_argc; } void SetPhase(CallPhase phase) { m_phase = phase; } CallPhase GetPhase() const { return m_phase; } void SetUserData(void* user_data) { m_user_data = user_data; } void* GetUserData() const { return m_user_data; } private: OP_STATUS SetArguments(ES_Value* argv, int argc); ES_Value* m_argv; int m_argc; void* m_user_data; CallPhase m_phase; BOOL m_ready_for_suspend; }; #ifdef _DEBUG # define DOM_CHECK_OR_RESTORE_PERFORMED int ___missing_DOM_CHECK_OR_RESTORE_ARGUMENTS # define DOM_CHECK_OR_RESTORE_GUARD ___missing_DOM_CHECK_OR_RESTORE_ARGUMENTS = 0, (void)___missing_DOM_CHECK_OR_RESTORE_ARGUMENTS #else # define DOM_CHECK_OR_RESTORE_PERFORMED # define DOM_CHECK_OR_RESTORE_GUARD #endif // _DEBUG /** Check arguments and restore them from callstate if it's a restarted call. * * When the function is entered the first time, it behaves as DOM_CHECK_ARGUMENTS. * If the function is suspended and entered for the second (or more) time the * macro restores original arguments from the callstate. * * It also sets a DOM_CHECK_OR_RESTORE_PERFORMED "marker" in its scope so that * other macros that need rely on the arguments being restored may make sure * that the arguments have been restored by embedding DOM_CHECK_OR_RESTORE_GUARD. */ #define DOM_CHECK_OR_RESTORE_ARGUMENTS(expected_arguments) \ DOM_CHECK_OR_RESTORE_PERFORMED; \ DOM_CHECK_OR_RESTORE_GUARD; \ { \ if (argc < 0) \ CALL_FAILED_IF_ERROR(DOM_CallState::RestoreArgumentsFromRestartValue(return_value, argv, argc));\ DOM_CHECK_ARGUMENTS(expected_arguments); \ } #ifdef DOM_JIL_API_SUPPORT /** JIL version of DOM_CHECK_OR_RESTORE_ARGUMENTS. * * Throws JIL exception if the arguments are incorrect. Otherwise it behaves * exactly the same as DOM_CHECK_OR_RESTORE_ARGUMENTS. */ #define DOM_CHECK_OR_RESTORE_ARGUMENTS_JIL(expected_arguments) \ DOM_CHECK_OR_RESTORE_PERFORMED; \ DOM_CHECK_OR_RESTORE_GUARD; \ { \ if (argc < 0) \ CALL_FAILED_IF_ERROR(DOM_CallState::RestoreArgumentsFromRestartValue(return_value, argv, argc));\ DOM_CHECK_ARGUMENTS_JIL(expected_arguments); \ } #endif #endif // DOM_DOMCALLLSTATE_H
// Copyright 2015 Intelligent Robotics Group, NASA ARC #include <handrail_detect/handrail_detect_general.h> namespace handrail_detect_node { HandrailDetect::HandrailDetect(ros::NodeHandle* nh, ros::NodeHandle* private_nh) { srand (time(NULL)); std::cout<<std::fixed; std::cout.precision(3); const float pi = 3.14159; const float pi_half = pi / 2.0; std::string depth_msg_topic; double tmp_rail_dist, tmp_rail_width, tmp_RANSAC_plane_threshold, tmp_arm_length, tmp_side_scale, tmp_handrail_point_gap_thres, tmp_plane_rate_from_points, tmp_line_rate_from_plane, tmp_RANSAC_line_threshold, tmp_depth_sensor_x_pos, tmp_depth_sensor_y_pos, tmp_depth_sensor_z_pos, tmp_depth_sensor_x_rot, tmp_depth_sensor_y_rot, tmp_depth_sensor_z_rot, tmp_rail_center_x_offset, tmp_rail_center_y_offset, tmp_rail_center_z_offset; //private_nh->param<std::string>("file_name", file_name_, "data"); // Handrail description private_nh->param("rail_dist", tmp_rail_dist, 0.09); // Distance between the ISS surface of the wall and the handrail private_nh->param("rail_width", tmp_rail_width, 0.04); // Width of the handrail private_nh->param("rail_center_x_offset", tmp_rail_center_x_offset, 0.0); private_nh->param("rail_center_y_offset", tmp_rail_center_y_offset, 0.0); private_nh->param("rail_center_z_offset", tmp_rail_center_z_offset, 0.0); // Handrail detection parameters private_nh->param("side_scale", tmp_side_scale, 1.2); private_nh->param("handrail_point_gap_thres", tmp_handrail_point_gap_thres, 0.05);// Gap distance between groups in line inliers private_nh->param("plane_rate_from_points", tmp_plane_rate_from_points, 0.3); // Rate of plane points from downsampled points private_nh->param("line_rate_from_plane", tmp_line_rate_from_plane, 0.05); // Rate of line points from plane points private_nh->param("min_rail_size", min_rail_size_, 5); // Minimum number of points in a line // Depth sensor parameters private_nh->param<std::string>("depth_msg_topic", depth_msg_topic, "/kinect/depth/points"); private_nh->param("depth_sensor_width", depth_width_, 224); // Width and height of sensor data private_nh->param("depth_sensor_height", depth_height_, 172); // Total #of pixels in a received data = width * height // Depth sensor located side of the robot arm private_nh->param("depth_sensor_x_pos", tmp_depth_sensor_x_pos, -0.125); private_nh->param("depth_sensor_y_pos", tmp_depth_sensor_y_pos, 0.06); private_nh->param("depth_sensor_z_pos", tmp_depth_sensor_z_pos, 0.0); private_nh->param("depth_sensor_x_rot", tmp_depth_sensor_x_rot, static_cast<double>(pi_half)); private_nh->param("depth_sensor_y_rot", tmp_depth_sensor_y_rot, 0.0); private_nh->param("depth_sensor_z_rot", tmp_depth_sensor_z_rot, static_cast<double>(pi)); private_nh->param("arm_length", tmp_arm_length, 0.18); // Robot Arm description // RANSAC parameters private_nh->param("RANSAC_line_iteration", RANSAC_line_iteration_, 10); private_nh->param("RANSAC_line_threshold", tmp_RANSAC_line_threshold, 0.02); private_nh->param("RANSAC_plane_iteration", RANSAC_plane_iteration_, 10); private_nh->param("RANSAC_plane_threshold", tmp_RANSAC_plane_threshold, 0.01); // Downsampling parameters private_nh->param("min_step", min_step_, 3); // Minimum step for downsampling private_nh->param("max_step", max_step_, 15); // Maximum step for downsampling private_nh->param("max_depth_msg_cnt", max_depth_msg_cnt_, 5); // Use every "max_depth_msg_cnt" th received data // Convert from double to float (since param does not receive float types) rail_dist_ = static_cast<float>(tmp_rail_dist); rail_width_ = static_cast<float>(tmp_rail_width); min_measure_dist_ = rail_width_ * 0.5; // Minimum measurement distance. x_step and y_step is calculated from it plane_rate_from_points_ = static_cast<float>(tmp_plane_rate_from_points); line_rate_from_plane_ = static_cast<float>(tmp_line_rate_from_plane); RANSAC_plane_threshold_ = static_cast<float>(tmp_RANSAC_plane_threshold); RANSAC_line_threshold_ = static_cast<float>(tmp_RANSAC_line_threshold); side_scale_ = static_cast<float>(tmp_side_scale); // It scales x_side_step handrail_point_gap_thres_ = static_cast<float>(tmp_handrail_point_gap_thres); rail_center_offset_ << static_cast<float>(tmp_rail_center_x_offset), static_cast<float>(tmp_rail_center_y_offset), static_cast<float>(tmp_rail_center_z_offset); arm_length_ = static_cast<float>(tmp_arm_length); // Rotation matrix of the depth sensor frame with respect to robot frame // Depth sensor frame x: right, y: down, z: front // Robot frame x: front, y: leftside, z: up Eigen::Matrix3f rot_sen, rot_frame; rot_sen = Eigen::AngleAxisf(-pi_half, Eigen::Vector3f::UnitZ()) * Eigen::AngleAxisf(0, Eigen::Vector3f::UnitY()) * Eigen::AngleAxisf(-pi_half, Eigen::Vector3f::UnitX()); rot_frame = Eigen::AngleAxisf(static_cast<float>(tmp_depth_sensor_z_rot), Eigen::Vector3f::UnitZ()) * Eigen::AngleAxisf(static_cast<float>(tmp_depth_sensor_y_rot), Eigen::Vector3f::UnitY()) * Eigen::AngleAxisf(static_cast<float>(tmp_depth_sensor_x_rot), Eigen::Vector3f::UnitX()); rot_tot_ = rot_frame * rot_sen; // depth sensor location from base_link Eigen::Vector3f depth_sensor_origin; depth_sensor_origin(0) = static_cast<float>(tmp_depth_sensor_x_pos); depth_sensor_origin(1) = static_cast<float>(tmp_depth_sensor_y_pos); depth_sensor_origin(2) = static_cast<float>(tmp_depth_sensor_z_pos); // H transformation from depth_sensor to base_link H_ << rot_tot_.row(0), depth_sensor_origin(0), rot_tot_.row(1), depth_sensor_origin(1), rot_tot_.row(2), depth_sensor_origin(2), 0, 0, 0, 1; // The handrail that has more than "target_angle_threshold_" with respect to // its horizontal line is considered to detect vertical handrails only target_angle_threshold_ = pi_half / 4.0; float depth_sensor_x_rot = fabs(static_cast<float>(tmp_depth_sensor_x_rot)); target_angle_ = depth_sensor_x_rot; if (depth_sensor_x_rot == 0) { vertical_sensor_check_ = false; ROS_WARN("Depth sensor is parallel to the floor"); } else if (fabs(depth_sensor_x_rot - pi_half) < target_angle_threshold_){ vertical_sensor_check_ = true; ROS_WARN("Depth sensor is vertical to the floor"); } else { ROS_ERROR("depth_sensor_x_rot is not properly set. It should be either 0 or pi/2"); target_angle_ = -1; } // Subscribe depth sensor data depth_sub_ = nh->subscribe<sensor_msgs::PointCloud2>(depth_msg_topic, 1, &HandrailDetect::DepthCallback, this); // Publish markers for rviz visualization marker_pub_ = nh->advertise<visualization_msgs::Marker>("handrail_marker", 10); // Plblish planes for rviz visualization cloud_pub_ = nh->advertise<sensor_msgs::PointCloud>("pcd_publish", 1); target_handrail_dist_ = fabs(depth_sensor_origin(0)) + arm_length_; std::cout << "target_handrail_dist_: " << target_handrail_dist_ <<std::endl; close_dist_ = target_handrail_dist_ * 2.0; // If the distance between the base_link and the handrail is less than close_dist_, close_dist_check_ = false; // left and right sample_cut_idx are returned to their initial value handrail_found_ = false; depth_msg_cnt_ = 0; handrail_prev_idx_ = 0; handrail_idx_ = 0; InitMarker(); // Marker initialization for rviz visualization } void HandrailDetect::FilterLinePoints(const std::vector<unsigned int>& line_inliers, std::vector<unsigned int>* filtered_line_inliers) { // 1. Sort the line inliers by their x or y values std::vector<float> axis_vals; for (size_t i = 0; i < line_inliers.size(); ++i) { size_t idx = line_inliers[i]; if (vertical_sensor_check_) axis_vals.push_back(cloud_.points[idx].x); else axis_vals.push_back(cloud_.points[idx].y); } std::sort(axis_vals.begin(), axis_vals.end()); // 2. Find groups that are apart from each other with handrail_point_gap_thres_ distance // Store min and max values as well as number of members of each group std::vector<float> min_val; std::vector<float> max_val; std::vector<size_t> group_cnt; size_t group_id = 0; size_t max_element = 1, max_group_id = 0; min_val.push_back(axis_vals[0]); group_cnt.push_back(1); for (size_t i = 1; i < axis_vals.size(); ++i) { if (fabs(axis_vals[i - 1] - axis_vals[i]) < handrail_point_gap_thres_) { ++group_cnt[group_id]; } else { if (group_cnt[group_id] > max_element) { max_element = group_cnt[group_id]; max_group_id = group_id; } ++group_id; max_val.push_back(axis_vals[i - 1]); min_val.push_back(axis_vals[i]); group_cnt.push_back(1); } } max_val.push_back(axis_vals[axis_vals.size() - 1]); if (group_cnt[group_cnt.size() - 1] > max_element) { // Check the last group whether it has the maximum number of members max_group_id = group_cnt.size() - 1; } // 3. If there are more than one group, find the one with the largest number of members (*filtered_line_inliers) = line_inliers; if (group_cnt.size() > 1) { filtered_line_inliers->clear(); for (size_t i = 0; i < line_inliers.size(); ++i) { size_t idx = line_inliers[i]; float check_point_val; check_point_val = cloud_.points[idx].y; if (vertical_sensor_check_) { check_point_val = cloud_.points[idx].x; } if (check_point_val >= min_val[max_group_id] && check_point_val <= max_val[max_group_id]) { filtered_line_inliers->push_back(idx); } } } } void HandrailDetect::GetTargetPose(const Eigen::Vector4f& plane_parameter, const Eigen::Vector3f& line_vector, const Eigen::Vector3f& line_center, tf2::Quaternion* pose_rot, Eigen::Vector3f* rob_frame_line_center, float* axis_angles, Eigen::Vector3f* pos_err) { // Get line center in base_link Eigen::Vector4f tmp_vector4f; tmp_vector4f << line_center, 1; tmp_vector4f = H_ * tmp_vector4f; (*rob_frame_line_center) << tmp_vector4f(0), tmp_vector4f(1), tmp_vector4f(2); (*rob_frame_line_center) += rail_center_offset_; // Set close_dist_check close_dist_check_ = false; if (fabs((*rob_frame_line_center)(0)) < close_dist_) { close_dist_check_ = true; } // Convert plane vector from the sensor frame to the robot frame Eigen::Vector3f rob_frame_plane_vector, plane_vector; plane_vector << plane_parameter(0), plane_parameter(1), plane_parameter(2); plane_vector /= plane_vector.norm(); rob_frame_plane_vector = rot_tot_* plane_vector; // Heading direction of the line vector is set to +x axis of base_link frame if (rob_frame_plane_vector(0) < 0 ) rob_frame_plane_vector *= -1.0; // Convert line vector and line center position from the sensor frame to the robot frame Eigen::Vector3f rob_frame_line_vector; rob_frame_line_vector = rot_tot_ * line_vector; // Heading direction of the plane vector is set to +z axis of base_link frame if (rob_frame_line_vector(2) < 0) rob_frame_line_vector *= -1.0; // Make a rotation matrix: [line_vector, plane_vector, cross_vector] Eigen::Vector3f cross_vector = rob_frame_line_vector.cross(rob_frame_plane_vector); cross_vector /= cross_vector.norm(); Eigen::Matrix3f r_err; r_err.col(0) = rob_frame_plane_vector; r_err.col(1) = cross_vector; r_err.col(2) = rob_frame_line_vector; tf2::Matrix3x3 rot_m; for (size_t i = 0; i < 3; ++i) for (size_t j = 0; j < 3; ++j) rot_m[i][j] = r_err(i, j); // Get roll, pitch and yaw from the rotation matrix double roll, pitch, yaw; rot_m.getRPY(roll, pitch, yaw); rot_m.getRotation(*pose_rot); axis_angles[0] = static_cast<float>(roll); axis_angles[1] = static_cast<float>(pitch); axis_angles[2] = static_cast<float>(yaw); (*pos_err) = (*rob_frame_line_center) + target_handrail_dist_ * rob_frame_plane_vector; /* // Get quaternions of plane vector and line vector //tf2::Quaternion plane_q, line_q; Eigen::Vector3f plane_ref_vect, line_ref_vect; plane_ref_vect << -1, 0, 0; line_ref_vect << 0, 0, 1; GetQuaternionFromVector(plane_ref_vect, rob_frame_plane_vector, plane_q); GetQuaternionFromVector(line_ref_vect, rob_frame_line_vector, line_q); */ } void HandrailDetect::FindHandrail() { // For computation time measurement clock_t t_strt, t, t_plane, t_line, t_total; t_strt = clock(); t = clock(); if (target_angle_ < 0 ) { ROS_ERROR("[Stop] depth_sensor_x_rot is not properly set. It should be either 0 or pi/2"); } else { std::vector<unsigned int> downsample_points, plane_inliers, plane_outliers, line_inliers; Eigen::Vector4f plane_parameter; std::cout << "===============================" << std::endl; GetXYScale(); // Get x,y scale of current measurement DownsamplePoints(&downsample_points); // Get downsampled points if (!FindPlane(downsample_points, &plane_inliers, &plane_outliers, &plane_parameter)) { ROS_WARN("No plane found yet"); handrail_found_ = false; } else { //std::cout << "Num plane points: " << plane_inliers.size() << std::endl; Eigen::Vector3f line_vector = Eigen::Vector3f::Zero(); Eigen::Vector3f line_center = Eigen::Vector3f::Zero(); if (!FindLine(plane_outliers, plane_parameter, &line_vector, &line_center, &line_inliers)) { ROS_WARN("No rail found yet"); t_total = clock() - t_strt; std::cout << "tot time(ms): " << ((double)t_total / CLOCKS_PER_SEC) * 1000.0 << std::endl; } else { //std::cout << "Num line points: " << line_inliers.size() << std::endl; tf2::Quaternion pose_rot; float axis_angles[3]; Eigen::Vector3f rob_frame_line_center, pos_err; GetTargetPose(plane_parameter, line_vector, line_center, &pose_rot, &rob_frame_line_center, axis_angles, &pos_err); t_total = clock() - t_strt; std::cout << "tot time(ms): " << ((double)t_total / CLOCKS_PER_SEC) * 1000.0 << std::endl; std::cout << "Pos err = " << pos_err(0) <<"/"<< pos_err(1) <<"/"<< pos_err(2) << std::endl; std::cout << "Rot err = " << axis_angles[0] <<"/"<< axis_angles[1] <<"/"<< axis_angles[2] << std::endl; PublishMarker(plane_inliers, line_inliers, rob_frame_line_center, pos_err, pose_rot); } } } } bool HandrailDetect::FindLine(const std::vector<unsigned int>& plane_outliers, const Eigen::Vector4f& plane_parameter, Eigen::Vector3f* line_vector, Eigen::Vector3f* line_center, std::vector<unsigned int>* line_inliers) { // Find potential line inliers by checking the distance between the plane and the points in the plane outliers std::vector<unsigned int> potential_line_inliers; Eigen::Vector4f tmp_point; Eigen::Vector3f plane_vector; plane_vector << plane_parameter(0), plane_parameter(1), plane_parameter(2); // For each outlier, check whether its x-axis neighbors in both -x_step and x_step have higher z values than itself. // This is to avoid detecting object attached on the wall with "rail_dist" distance as a handrail. // x_step is decided by the scale of x-axis. Scale changed by the distance of an object. // It assumes that the robot only detects vertical handrail with +- pi/8 size_t total_side_step = side_step_; if (vertical_sensor_check_) { total_side_step = side_step_ * depth_width_; } for (size_t i = 0; i < plane_outliers.size(); ++i) { size_t potential_inlier_ID = plane_outliers[i]; size_t chk_idx = potential_inlier_ID % depth_width_; size_t max_depth_size = depth_width_; if (vertical_sensor_check_) { chk_idx = potential_inlier_ID / depth_width_; max_depth_size = depth_height_; } float z_dist = cloud_.points[potential_inlier_ID].z + 0.5 * rail_dist_; bool left_check = true, right_check = true; if (chk_idx > side_step_ ) { if (!std::isnan(cloud_.points[potential_inlier_ID - total_side_step].z) && (cloud_.points[potential_inlier_ID - total_side_step].z < z_dist && cloud_.points[potential_inlier_ID - total_side_step].z > arm_length_)) { left_check = false; } } if (chk_idx < max_depth_size - side_step_ ) { if (!std::isnan(cloud_.points[potential_inlier_ID + total_side_step].z) && (cloud_.points[potential_inlier_ID + total_side_step].z < z_dist && cloud_.points[potential_inlier_ID + total_side_step].z > arm_length_)) { right_check = false; } } if (left_check && right_check) { tmp_point << cloud_.points[potential_inlier_ID].x, cloud_.points[potential_inlier_ID].y, cloud_.points[potential_inlier_ID].z, 1; float dist_from_plane = (tmp_point.transpose() * plane_parameter).norm() / plane_vector.norm(); if (fabs(dist_from_plane - rail_dist_) < RANSAC_line_threshold_) {// Measure distance of the point from the plane potential_line_inliers.push_back(potential_inlier_ID); // Collect the point within a threshold //std::cout << "dist_from_plane = " << dist_from_plane << std::endl; } } } //std::cout << "Plane outliers / Pot inliers: " << plane_outliers.size() << "/" << potential_line_inliers.size() << std::endl; // Find a line model from potential_line_inliers using RANSAC size_t num_potential_data = potential_line_inliers.size(); if (num_potential_data < line_size_threshold_) { handrail_found_ = false; std::cout << "[2] Small line points: " << static_cast<int>(num_potential_data) << " thres = " << line_size_threshold_ << std::endl; return false; } else { std::vector<unsigned int> best_line_inliers; Eigen::Vector3f fst_line_point, scd_line_point, tmp_line_vector, point_diff, potential_point; unsigned int r1, r2, seed; // Select two random points to model a line vector size_t total_iteration = 0, max_iteration = RANSAC_line_iteration_ * 2; for (size_t i = 0; i < RANSAC_line_iteration_; ++i) { do { r1 = rand_r(&seed) % num_potential_data; r2 = rand_r(&seed) % num_potential_data; } while (r1 == r2); fst_line_point << cloud_.points[potential_line_inliers[r1]].x, cloud_.points[potential_line_inliers[r1]].y, cloud_.points[potential_line_inliers[r1]].z; scd_line_point << cloud_.points[potential_line_inliers[r2]].x, cloud_.points[potential_line_inliers[r2]].y, cloud_.points[potential_line_inliers[r2]].z; tmp_line_vector = fst_line_point - scd_line_point; // Consider only the handrail that has higher angle than vertical_ang_threshold // This condition is used to filter out horizontal handrails // Currently, only horizontal handrail can be detected since only x_step in FindLine function is defined. float nang = fabs(atan2(fabs(tmp_line_vector(0)), fabs(tmp_line_vector(1))) - target_angle_); if (nang > target_angle_threshold_) { // If the angle is smaller than vertical_ang_threshold, do the iteration again // To avoid infinite for loop, at most max_iteration is allowed if (i > 0 && total_iteration < max_iteration) --i; } else { // Calculate residual of potential points with respect to the sampled line vector tmp_line_vector /= tmp_line_vector.norm(); std::vector<unsigned int> tmp_line_inliers; for (size_t j = 0; j < num_potential_data; ++j) { size_t potential_inlier_ID = potential_line_inliers[j]; potential_point << cloud_.points[potential_inlier_ID].x, cloud_.points[potential_inlier_ID].y, cloud_.points[potential_inlier_ID].z; point_diff = fst_line_point - potential_point; if ((point_diff.cross(tmp_line_vector)).norm() < rail_width_) tmp_line_inliers.push_back(potential_inlier_ID); } // Track the best line with the higher number of inliers if (tmp_line_inliers.size() > best_line_inliers.size()) best_line_inliers = tmp_line_inliers; } ++total_iteration; } // Get filtered line points std::vector<unsigned int> filtered_line_inliers; FilterLinePoints(best_line_inliers, &filtered_line_inliers); float idx_sum = 0; // Refine a line vector from filtered_line_inliers size_t num_final_data = filtered_line_inliers.size(); if (num_final_data < line_size_threshold_) { ROS_WARN("[3] Small line points: %d", static_cast<int>(num_final_data)); handrail_found_ = false; return false; } else { // Find a center of inliers to consider it as the point that the line passes through Eigen::Vector3f line_point, best_line_center = Eigen::Vector3f::Zero(); for (size_t i = 0; i < num_final_data; ++i) { size_t inlier_point_ID = filtered_line_inliers[i]; line_point << cloud_.points[inlier_point_ID].x, cloud_.points[inlier_point_ID].y, cloud_.points[inlier_point_ID].z; best_line_center += line_point; if (vertical_sensor_check_) idx_sum += (inlier_point_ID / depth_width_); else idx_sum += (inlier_point_ID % depth_width_); } best_line_center /= num_final_data; int tmp_handrail_idx = static_cast<int>(idx_sum / num_final_data); if (fabs(static_cast<int>(handrail_prev_idx_) - tmp_handrail_idx) > side_step_) { handrail_prev_idx_ = handrail_idx_; handrail_idx_ = static_cast<size_t>(tmp_handrail_idx); } // Measure the distance between the line vector from each point (v_s) and the estimated line vector (v_t) by cross product // v_s cross v_t should be zero if v_s = v_t // So, convert "v_s cross" to a matrix form and set v_t as x (unknow) // Then Ax = 0, where A is 3n by 3 matrix and x is 3 by 1 matrix Eigen::MatrixX3f A(3 * num_final_data, 3); for (size_t i = 0; i < num_final_data; ++i) { line_point << cloud_.points[filtered_line_inliers[i]].x, cloud_.points[filtered_line_inliers[i]].y, cloud_.points[filtered_line_inliers[i]].z; point_diff = best_line_center - line_point; // Convert "v_s cross" to a matrix form A.row(i * 3) << 0, -point_diff(2), point_diff(1); A.row(i * 3 + 1) << point_diff(2), 0, -point_diff(0); A.row(i * 3 + 2) << -point_diff(1), point_diff(0), 0; } Eigen::Matrix3f ATA = A.transpose() * A; Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> eigensolver(ATA); *line_vector = eigensolver.eigenvectors().col(0); *line_inliers = filtered_line_inliers; *line_center = best_line_center; handrail_found_ = true; return true; } } } void HandrailDetect::GetXYScale() { size_t ID1, ID2; // The leftmost colum of the data has the minimum x, and // the rightmost column of the data has the maximum x // So, find the minimum and the maximum x values and get the scale // Since there are nan data, we need to do for loop until there is no nan in both side size_t num_sample = 10; size_t x_scale_check_step = depth_width_ / num_sample; std::vector<float> val_diff; for (size_t i = 1; i < num_sample - 1; ++i) { ID1 = x_scale_check_step * i; ID2 = ID1 + 1; if (!(std::isnan(cloud_.points[ID1].x) || std::isnan(cloud_.points[ID2].x))) { val_diff.push_back(fabs(cloud_.points[ID1].x - cloud_.points[ID2].x)); } } std::sort(val_diff.begin(), val_diff.end()); size_t mid_idx = val_diff.size() / 2; x_scale_ = val_diff[mid_idx]; //std::cout <<"[x scale] "<< x_scale_ <<std::endl; // Find the y_scale size_t y_scale_check_step = depth_height_ / num_sample; for (size_t i = 0; i < num_sample; ++i) { ID1 = depth_width_ * y_scale_check_step * i; ID2 = ID1 + depth_width_; if (!(std::isnan(cloud_.points[ID1].y) || std::isnan(cloud_.points[ID2].y))) { val_diff.push_back(fabs(cloud_.points[ID1].y - cloud_.points[ID2].y)); } } std::sort(val_diff.begin(), val_diff.end()); mid_idx = val_diff.size() / 2; y_scale_ = val_diff[mid_idx]; //std::cout <<"[y scale] "<< y_scale_ <<std::endl; // Get x_step and y_step x_step_ = min_measure_dist_ / x_scale_; if (x_step_ < min_step_) x_step_ = min_step_; else if (x_step_ > max_step_) x_step_ = max_step_; y_step_ = min_measure_dist_ / y_scale_; if (y_step_ < min_step_) y_step_ = min_step_; else if (y_step_ > max_step_) y_step_ = max_step_; // Set the minimum point numbers for the plane and the line plane_size_threshold_ = (depth_width_ / x_step_) * (depth_height_ / y_step_) * plane_rate_from_points_; line_size_threshold_ = plane_size_threshold_ * line_rate_from_plane_; if (line_size_threshold_ < min_rail_size_) line_size_threshold_ = min_rail_size_; // Set sampling area float handrail_search_size = depth_width_ / 4; left_sample_cut_idx_ = 0; right_sample_cut_idx_ = depth_width_; if (vertical_sensor_check_) { right_sample_cut_idx_ = depth_height_; handrail_search_size = depth_height_ / 4; } if (handrail_found_ && !close_dist_check_) { // If the handrail is found, the size of the points are reduced by half // so that the thresholds of plane and line should also be reduced by half plane_size_threshold_ /= 2; line_size_threshold_ /= 2; // If the handrail is found, reduce sampling area in x-axis, centered at the handrail center // Very important!! if size_t type value is compared with negative integer value, the inequality result is wrong! // ex) size_t a = 0; b = -1; // if (a > b) std::cout<<"Right"; // else std::cout<<"Wrong"; // The result was "Wrong"!! if (handrail_idx_ > handrail_search_size) left_sample_cut_idx_ = handrail_idx_ - handrail_search_size; right_sample_cut_idx_ = handrail_idx_ + handrail_search_size; } // For each potential inlier of the line, check the z distance of both sides of the points at +- side_step side_step_ = ceil(side_scale_ * rail_width_ / x_scale_); if (vertical_sensor_check_) side_step_ = ceil(side_scale_ * rail_width_ / y_scale_); //std::cout << "rail_width " << rail_width_ << std::endl; //std::cout << "x_scale " << x_scale_ << std::endl; //std::cout << "y_scale " << y_scale_ << std::endl; //std::cout << "x_step " << x_step_ << std::endl; //std::cout << "y_step " << y_step_ << std::endl; //std::cout << "y_side_step " << side_step_ << std::endl; } void HandrailDetect::GetPlaneInNOut(const std::vector<unsigned int>& downsample_points, const Eigen::Vector4f& tmp_plane_parameter, std::vector<unsigned int>* tmp_inliers, std::vector<unsigned int>* tmp_outliers) { // downsampling points for a plane from pointcloud data in x-axis Eigen::RowVector4f res_row; for (size_t i = 0; i < downsample_points.size(); ++i) { res_row << cloud_.points[downsample_points[i]].x, cloud_.points[downsample_points[i]].y, cloud_.points[downsample_points[i]].z, 1; if ((res_row * tmp_plane_parameter).norm() < RANSAC_plane_threshold_) (*tmp_inliers).push_back(downsample_points[i]); // Plane inliers else (*tmp_outliers).push_back(downsample_points[i]); // Plane outliers which contain potential line points (line inliers) } } void HandrailDetect::DownsamplePoints(std::vector<unsigned int>* downsample_points) { size_t point_cnt = 0; size_t x_step_half = x_step_ / 2; size_t y_step_half = y_step_ / 2; for (size_t i = 1; i < cloud_.points.size(); i += x_step_) { size_t i_x = i % depth_width_; size_t i_y = i / depth_width_; size_t i_xy = i_x; if (vertical_sensor_check_) i_xy = i_y; if (i_xy > left_sample_cut_idx_ && i_xy < right_sample_cut_idx_ && i_y % y_step_ == 0) { ++point_cnt; if (point_cnt % 2 == 0) i += y_step_half * depth_width_; if (point_cnt == 1) i += x_step_half; // Check whether the point is nan if (!(std::isnan(cloud_.points[i].x) || std::isnan(cloud_.points[i].y) || std::isnan(cloud_.points[i].z))) { (*downsample_points).push_back(i); // Plane inliers } if (point_cnt % 2 == 0) i -= y_step_half * depth_width_; } else { point_cnt = 0; } } /* plane_mk_.points.clear(); geometry_msgs::Point line_point; Eigen::Vector4f tf_point, conv_point; for (size_t i = 0; i < (*downsample_points).size(); ++i) { size_t inlier_ID = (*downsample_points)[i]; tf_point << cloud_.points[inlier_ID].x, cloud_.points[inlier_ID].y, cloud_.points[inlier_ID].z, 1; conv_point = H_ * tf_point; line_point.x = conv_point(0); line_point.y = conv_point(1); line_point.z = conv_point(2); plane_mk_.points.push_back(line_point); } marker_pub_.publish(plane_mk_); */ /* sensor_msgs::PointCloud disp_cloud; disp_cloud.header = cloud_.header; for (size_t i = 0; i < (*downsample_points).size(); ++i) { size_t inlier_ID = (*downsample_points)[i]; disp_cloud.points.push_back(cloud_.points[inlier_ID]); } cloud_pub_.publish(disp_cloud); */ } bool HandrailDetect::FindPlane(const std::vector<unsigned int>& downsample_points, std::vector<unsigned int>* plane_inliers, std::vector<unsigned int>* plane_outliers, Eigen::Vector4f* plane_parameter) { // Find plane using RANSAC size_t num_data = cloud_.points.size(); unsigned int r1, r2, r3, seed; Eigen::MatrixX4f A(3, 4), ATA(4, 4); size_t total_iteration = 0, max_iteration = RANSAC_plane_iteration_ * 2; for (size_t i = 0; i < RANSAC_plane_iteration_; ++i) { // Sample three points to model a normal vector of a plane do { r1 = rand_r(&seed) % num_data; r2 = rand_r(&seed) % num_data; r3 = rand_r(&seed) % num_data; } while (r1 == r2 || r1 == r3 || r2 == r3); if (std::isnan(cloud_.points[r1].x) || std::isnan(cloud_.points[r2].x) || std::isnan(cloud_.points[r3].x)) { if (i > 0) --i; } else { A << cloud_.points[r1].x, cloud_.points[r1].y, cloud_.points[r1].z, 1, cloud_.points[r2].x, cloud_.points[r2].y, cloud_.points[r2].z, 1, cloud_.points[r3].x, cloud_.points[r3].y, cloud_.points[r3].z, 1; ATA = A.transpose() * A; Eigen::SelfAdjointEigenSolver<Eigen::Matrix4f> eigensolver(ATA); Eigen::Vector4f tmp_plane_parameter = eigensolver.eigenvectors().col(0); // Since the plane is assumed to be vertical, the normal vector should have a large z axis element, // and small x and y axes elements in depth sensor frame // This can make the algorithm to avoid detecting ceiling or the robot arm as a plane if (fabs(tmp_plane_parameter(2)) < fabs(tmp_plane_parameter(0)) || fabs(tmp_plane_parameter(2)) < fabs(tmp_plane_parameter(1))) { // To avoid infinite for loop, at most max_iteration is allowed if (i > 0 && total_iteration < max_iteration) --i; } else { std::vector<unsigned int> tmp_inliers, tmp_outliers; GetPlaneInNOut(downsample_points, tmp_plane_parameter, &tmp_inliers, &tmp_outliers); if (tmp_inliers.size() > (*plane_inliers).size()) { *plane_inliers = tmp_inliers; *plane_outliers = tmp_outliers; *plane_parameter = tmp_plane_parameter; } } ++total_iteration; } } /* sensor_msgs::PointCloud disp_cloud; disp_cloud.header = cloud_.header; for (size_t i = 0; i < (*plane_inliers).size(); ++i) { size_t inlier_ID = (*plane_inliers)[i]; disp_cloud.points.push_back(cloud_.points[inlier_ID]); } cloud_pub_.publish(disp_cloud); */ if ((*plane_inliers).size() > plane_size_threshold_) { // Set the sign of the normal vector of the plane to direct the sensor (-z axis) in the depth sensor frame if ((*plane_parameter)(2) > 0) (*plane_parameter) *= -1.0; return true; } else { std::cout << "[1] Small plane points: " << static_cast<int>((*plane_inliers).size()) << " threshold = " << plane_size_threshold_ << std::endl; return false; } } void HandrailDetect::DepthCallback(const sensor_msgs::PointCloud2ConstPtr& depth_msg) { //static int record_cnt = 1; if (depth_msg_cnt_ > max_depth_msg_cnt_) { // Convert from pointcloud2 to pointcloud for easy 3d measurement data access sensor_msgs::convertPointCloud2ToPointCloud(*depth_msg, cloud_); depth_msg_cnt_ = 0; FindHandrail(); //RecordDataToText(record_cnt); // Record data for algorithm test //++record_cnt; } ++depth_msg_cnt_; } void HandrailDetect::GetQuaternionFromVector(const Eigen::Vector3f& target_vector, const Eigen::Vector3f& curr_vector, tf2::Quaternion* quat) { // Find a quaternion of curr_vect with respect to target_vect Eigen::Vector3f axis_vector; // rotation axis vector axis_vector = curr_vector.cross(target_vector); axis_vector /= axis_vector.norm(); float theta = curr_vector.dot(target_vector); float angle_rotation = -1.0 * acos(theta); // rotation angle between curr_vect and target_vect with respect to axis_vect // Convert axis vect from Eigen to ROS TF2 tf2::Vector3 tf_axis_vector(axis_vector(0), axis_vector(1), axis_vector(2)); // Create quaternion from axis rotation representation tf2::Quaternion q(tf_axis_vector, angle_rotation); *quat = q; } void HandrailDetect::RecordDataToText(int record_cnt) { std::string int_to_str = std::to_string(record_cnt); std::ofstream x_file, y_file, z_file; std::string f_path("/home/dh/catkin_ws/src/handrail_detect/launch/data/"); std::string x_path = f_path + file_name_ + "_x_" + int_to_str; std::string y_path = f_path + file_name_ + "_y_" + int_to_str; std::string z_path = f_path + file_name_ + "_z_" + int_to_str; x_file.open(x_path); y_file.open(y_path); z_file.open(z_path); for (size_t i = 0; i < cloud_.points.size(); ++i) { x_file << cloud_.points[i].x << std::endl; y_file << cloud_.points[i].y << std::endl; z_file << cloud_.points[i].z << std::endl; } x_file.close(); y_file.close(); z_file.close(); ROS_WARN("Record %d-th data!!!", record_cnt); } void HandrailDetect::InitMarker(){ handrail_mk_.header.frame_id = "base_link"; handrail_mk_.header.stamp = ros::Time::now(); handrail_mk_.ns = "handrail"; handrail_mk_.action = visualization_msgs::Marker::MODIFY; handrail_mk_.type = visualization_msgs::Marker::CYLINDER; handrail_mk_.id = 0; handrail_mk_.scale.x = rail_width_; handrail_mk_.scale.y = handrail_mk_.scale.x; handrail_mk_.scale.z = 0.5; handrail_mk_.color.g = 1.0; // color handrail_mk_.color.a = 0.3; // 0 is completely transparent (invisible), and 1 is completely opaque handrail_mk_.pose.position.x = 0; handrail_mk_.pose.position.y = 0; handrail_mk_.pose.position.z = 0; handrail_mk_.pose.orientation.x = 0.0; handrail_mk_.pose.orientation.y = 0.0; handrail_mk_.pose.orientation.z = 0.0; handrail_mk_.pose.orientation.w = 1.0; handrail_center_mk_.header.frame_id = "base_link"; handrail_center_mk_.header.stamp = ros::Time::now(); handrail_center_mk_.ns = "handrail_center"; handrail_center_mk_.action = visualization_msgs::Marker::MODIFY; handrail_center_mk_.type = visualization_msgs::Marker::CYLINDER; handrail_center_mk_.id = 1; handrail_center_mk_.scale.x = handrail_mk_.scale.x * 1.5; handrail_center_mk_.scale.y = handrail_mk_.scale.x * 1.5; handrail_center_mk_.scale.z = 0.1; handrail_center_mk_.color.r = 1.0; handrail_center_mk_.color.g = 1.0; handrail_center_mk_.color.a = 0.5; handrail_center_mk_.pose.position.x = 0; handrail_center_mk_.pose.position.y = 0; handrail_center_mk_.pose.position.z = 0; handrail_center_mk_.pose.orientation.x = 0.0; handrail_center_mk_.pose.orientation.y = 0.0; handrail_center_mk_.pose.orientation.z = 0.0; handrail_center_mk_.pose.orientation.w = 1.0; target_pose_mk_.header.frame_id = "base_link"; target_pose_mk_.header.stamp = ros::Time::now(); target_pose_mk_.ns = "target_pose"; target_pose_mk_.action = visualization_msgs::Marker::MODIFY; target_pose_mk_.type = visualization_msgs::Marker::CUBE; target_pose_mk_.id = 2; target_pose_mk_.scale.x = 0.35; target_pose_mk_.scale.y = 0.35; target_pose_mk_.scale.z = 0.35; target_pose_mk_.color.r = 1.0; target_pose_mk_.color.b = 1.0; target_pose_mk_.color.a = 0.5; target_pose_mk_.pose.position.x = 0; target_pose_mk_.pose.position.y = 0; target_pose_mk_.pose.position.z = 0; target_pose_mk_.pose.orientation.x = 0.0; target_pose_mk_.pose.orientation.y = 0.0; target_pose_mk_.pose.orientation.z = 0.0; target_pose_mk_.pose.orientation.w = 1.0; handrail_points_mk_.header.frame_id = "base_link"; handrail_points_mk_.header.stamp = ros::Time::now(); handrail_points_mk_.ns = "handrail_points"; handrail_points_mk_.action = visualization_msgs::Marker::MODIFY; handrail_points_mk_.type = visualization_msgs::Marker::SPHERE_LIST; handrail_points_mk_.id = 3; handrail_points_mk_.scale.x = 0.02; handrail_points_mk_.scale.y = 0.02; handrail_points_mk_.scale.z = 0.02; handrail_points_mk_.color.r = 1.0; handrail_points_mk_.color.a = 1.0; handrail_side_points_mk_.header.frame_id = "base_link"; handrail_side_points_mk_.header.stamp = ros::Time::now(); handrail_side_points_mk_.ns = "handrail_side_points"; handrail_side_points_mk_.action = visualization_msgs::Marker::MODIFY; handrail_side_points_mk_.type = visualization_msgs::Marker::SPHERE_LIST; handrail_side_points_mk_.id = 4; handrail_side_points_mk_.scale.x = 0.02; handrail_side_points_mk_.scale.y = 0.02; handrail_side_points_mk_.scale.z = 0.02; handrail_side_points_mk_.color.b = 1.0; handrail_side_points_mk_.color.a = 1.0; plane_mk_.header.frame_id = "base_link"; plane_mk_.header.stamp = ros::Time::now(); plane_mk_.ns = "handrail_side_points"; plane_mk_.action = visualization_msgs::Marker::MODIFY; plane_mk_.type = visualization_msgs::Marker::POINTS; plane_mk_.id = 5; plane_mk_.scale.x = 0.01; plane_mk_.scale.y = 0.01; plane_mk_.scale.z = 0.01; plane_mk_.color.g = 1.0; plane_mk_.color.a = 1.0; } void HandrailDetect::PublishMarker(const std::vector<unsigned int>& plane_inliers, const std::vector<unsigned int>& line_inliers, const Eigen::Vector3f& rob_frame_line_center, const Eigen::Vector3f& pos_err, const tf2::Quaternion& pose_rot) { // Plane display sensor_msgs::PointCloud disp_cloud; disp_cloud.header = cloud_.header; for (size_t i = 0; i < plane_inliers.size(); ++i) { size_t inlier_ID = plane_inliers[i]; disp_cloud.points.push_back(cloud_.points[inlier_ID]); } cloud_pub_.publish(disp_cloud); handrail_points_mk_.points.clear(); handrail_side_points_mk_.points.clear(); Eigen::Vector4f tf_point, conv_point; geometry_msgs::Point line_point; //std::cout << "side_step: " << side_step_ << std::endl; for (size_t i = 0; i < line_inliers.size(); ++i) { size_t inlier_ID = line_inliers[i]; tf_point << cloud_.points[inlier_ID].x, cloud_.points[inlier_ID].y, cloud_.points[inlier_ID].z, 1; conv_point = H_ * tf_point; line_point.x = conv_point(0); line_point.y = conv_point(1); line_point.z = conv_point(2); handrail_points_mk_.points.push_back(line_point); //std::cout << "Cntr: " << tf_point(0) << "/" << tf_point(1) << "/" << tf_point(2) << std::endl; size_t total_side_step = side_step_; size_t chk_idx = inlier_ID % depth_width_; size_t max_depth_size = depth_width_; if (vertical_sensor_check_) { total_side_step = side_step_ * depth_width_; chk_idx = inlier_ID / depth_width_; max_depth_size = depth_height_; } if (chk_idx > side_step_) { if (!std::isnan(cloud_.points[inlier_ID - total_side_step].z)) { tf_point << cloud_.points[inlier_ID - total_side_step].x, cloud_.points[inlier_ID - total_side_step].y, cloud_.points[inlier_ID - total_side_step].z; conv_point = H_ * tf_point; line_point.x = conv_point(0); line_point.y = conv_point(1); line_point.z = conv_point(2); handrail_side_points_mk_.points.push_back(line_point); //std::cout << "Left: " << tf_point(0) << "/" << tf_point(1) << "/" << tf_point(2) << std::endl; } } if (chk_idx < max_depth_size - side_step_) { if (!std::isnan(cloud_.points[inlier_ID + total_side_step].z)) { tf_point << cloud_.points[inlier_ID + total_side_step].x, cloud_.points[inlier_ID + total_side_step].y, cloud_.points[inlier_ID + total_side_step].z; conv_point = H_ * tf_point; line_point.x = conv_point(0); line_point.y = conv_point(1); line_point.z = conv_point(2); handrail_side_points_mk_.points.push_back(line_point); //std::cout << "Rght: " << tf_point(0) << "/" << tf_point(1) << "/" << tf_point(2) << std::endl; } } } marker_pub_.publish(handrail_points_mk_); marker_pub_.publish(handrail_side_points_mk_); // Handrail cylinder dislpay handrail_mk_.pose.position.x = rob_frame_line_center(0); handrail_mk_.pose.position.y = rob_frame_line_center(1); handrail_mk_.pose.position.z = rob_frame_line_center(2); handrail_mk_.pose.orientation.x = pose_rot.getX(); handrail_mk_.pose.orientation.y = pose_rot.getY(); handrail_mk_.pose.orientation.z = pose_rot.getZ(); handrail_mk_.pose.orientation.w = pose_rot.getW(); marker_pub_.publish(handrail_mk_); // Handrail center display handrail_center_mk_.pose.position = handrail_mk_.pose.position; marker_pub_.publish(handrail_center_mk_); // Target robot pose display target_pose_mk_.pose.position.x = pos_err(0); target_pose_mk_.pose.position.y = pos_err(1); target_pose_mk_.pose.position.z = pos_err(2); target_pose_mk_.pose.orientation.x = pose_rot.getX(); target_pose_mk_.pose.orientation.y = pose_rot.getY(); target_pose_mk_.pose.orientation.z = pose_rot.getZ(); target_pose_mk_.pose.orientation.w = pose_rot.getW(); marker_pub_.publish(target_pose_mk_); } } // end namespace handrail_detect_node int main(int argc, char **argv) { ros::init(argc, argv, "handrail_detect_node"); ros::NodeHandle nh, priv_nh("~"); handrail_detect_node::HandrailDetect hd(&nh, &priv_nh); ros::spin(); return 0; }
/******************************************************************************* * filename: CMatrix.hpp * description: Adapter class for a unified matrix interface * author: Moritz Beber * created: 2010-04-12 * copyright: Jacobs University Bremen. All rights reserved. ******************************************************************************* * Currently will work with a typedef, an adapter class is too much work at the * moment and of questionable performance due to 'virtual' mechanism. * Nevertheless, a skeletton is provided here. ******************************************************************************/ #ifndef _CMATRIX_HPP #define _CMATRIX_HPP /******************************************************************************* * Includes ******************************************************************************/ // project #include "../headers/common_definitions.hpp" /******************************************************************************* * Declarations ******************************************************************************/ namespace meb { template<class D> class Matrix { public: // get method virtual D& operator()(unsigned i, unsigned j) = 0; // set method virtual void operator()(unsigned i, unsigned j) = 0; // maybe matrix views }; // class Matrix } // namespace meb #endif // _CMATRIX_HPP
#include <bits/stdc++.h> using namespace std; int main(){ string s; cin >> s; string ans = ""; for(int i=0; i<s.size(); i++){ string tmp = ""; for(int j=i; j<s.size(); j++){ string t = (string() + s[j]); if(t == "A" || t == "C" || t == "G" || t == "T") tmp += t; else break; } if(ans.size() < tmp.size()) ans = tmp; } cout << ans.size() << endl; return 0; }
#include <iostream> #include <math.h> using namespace std; int main() { int n,ctr=-1; cout<<"Enter the number N\n"; cin>>n; int l=sqrt(n); int r; r=l%10; for(int i=0;i<r;i++) ctr++; cout<<"Integers less than N in the sample space is "<<ctr; return 0; }
#include <bits/stdc++.h> typedef long long ll; typedef unsigned long long ull; #define tests int t; cin >> t; while(t--) #define vll vector<ll> #define vi vector<int> #define pb push_back using namespace std; void solve() { int n, m, k; cin >> n >> m >> k; string s[n]; for(int i = 0; i < n; i++) { cin >> s[i]; } bool vis[n][m]; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { vis[i][j] = false; } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(s[i][j] == '*') { int ii = i+1, jj = j+1; while(ii < n && jj < m) { if(s[ii][jj] == '.') { break; } if(jj-j >= k) { int iii = ii, jjj = jj; while(iii-i >= 0 && jjj < m) { if(s[iii][jjj] == '.') { break; } iii--; jjj++; } if(jjj-jj >= k+1) { int iiii = ii, jjjj = jj; while(iiii-i >= 0 && jjjj < m) { if(s[iiii][jjjj] == '.') { break; } vis[iiii][jjjj] = true; vis[iiii][2*jj-jjjj] = true; iiii--; jjjj++; } } else { ii++; jj++; continue; } if(jjj-jj < jj-j+1) { for(int iiii = ii, jjjj = jj; iiii >= i;) { if(!vis[iiii][2*jj-jjjj]) { break; } jjjj++; iiii--; } } } ii++; jj++; } if(jj-j <= k && !vis[i][j]) { cout << "NO\n"; return; } } } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(s[i][j] == '*' && !vis[i][j]) { cout << "NO\n"; return; } } } cout << "YES\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; for(int test = 1; test <= t; test++) { solve(); } return 0; }
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; using Graph = vector<vector<int>>; const double PI = 3.14159265358979323846; const ll MOD = 1000000007; int main(){ char X; cin >> X; string S; cin >> S; for(int i = 0; i < (int)S.size(); i++){ if(S.at(i) == X)continue; cout << S.at(i); } cout << endl; return 0; }
#define MAX_INT 10000001 #define MAX_NUM 500000 #include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int sort(int *points,int n); int dichotomyleft(int *points,int e,int righ); int dichotomyright(int *points,int e,int righ); static int points[MAX_NUM]; static int borders_a[MAX_NUM]; static int borders_b[MAX_NUM]; int m; int n; int i; int a; int b; int leftposition; int rightposition; //输入 scanf("%d %d",&n,&m); for (i=0;i<n;i++){ scanf("%d",&(points[i])); } for (i=0;i<m;i++) { scanf("%d %d",&a,&b); borders_a[i]=a; borders_b[i]=b; } //排序 sort(points,n); //二分查找 for(i=0;i<m;i++){ leftposition=dichotomyleft(points,borders_a[i],n-1); rightposition=dichotomyright(points,borders_b[i],n-1); printf("%d\n",rightposition-leftposition); } return 0; } int dichotomyleft(int *points,int e,int n){ int lef=0; int righ=n; int count; if (e<points[lef]) return count=-1; if (points[righ]<e){ count=righ; return count; } while(lef<righ){ int middle=(lef+righ)>>1; if (points[middle]<e&&e<points[middle+1]){ int count=middle; return count; } if (points[middle]<e&&e==points[middle+1]){ int count=middle; return count; } if(points[middle]<e){ lef=middle; } if(e<points[middle]){ righ=middle; } if(e==points[middle]){ while(e==points[middle]){ middle=middle-1; } count=middle; return count; } } count=lef+1; return count; } int dichotomyright(int *points,int e,int n){ int lef=0; int righ=n; int count; if (e<points[lef]){ count=-1; return count; } if (points[righ]<e){ count=righ; return count;} //1 while(lef<righ){ int middle=(lef+righ)>>1; if (points[middle]<e&&e<points[middle+1]){ int count=middle; return count; } if (points[middle]<e&&e==points[middle+1]){ int count=middle+1; return count; } if(points[middle]<e){ lef=middle; } if(e<points[middle]){ righ=middle; } if(e==points[middle]){ while(e==points[middle]){ middle=middle+1; } count=middle-1; return count; } } count=lef+1; if (count<righ&&points[count+1]==e){ count=count+1; } return count; } int sort(int *points,int n){ int temp; bool sorted=false; while(!sorted){ sorted=true; for(int j=1;j<n;j++) if(points[j-1]>points[j]){ temp=points[j]; points[j]=points[j-1]; points[j-1]=temp; sorted=false; } } return sorted; }
int data; int en=12; int in1=11; int in2=10; void setup() { Serial.begin(9600); pinMode(en,OUTPUT); digitalWrite(en,HIGH); pinMode(in1,OUTPUT); pinMode(in2,OUTPUT); digitalWrite(in1,LOW); digitalWrite(in2,LOW); } void loop() { while(Serial.available()) { data=Serial.read(); Serial.write(data); } if (data=='1') {digitalWrite(in1,HIGH); digitalWrite(in2,LOW); delay(1000); } if (data=='2') {digitalWrite(in1,LOW); digitalWrite(in2,HIGH); delay(1000); } if(data=='0') {digitalWrite(in1,LOW); digitalWrite(in2,LOW); } if(data=='3') digitalWrite(en,LOW); digitalWrite(in1,LOW); digitalWrite(in2,LOW); }
// Copyright (c) 2019 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _XmlMXCAFDoc_VisMaterialDriver_HeaderFile #define _XmlMXCAFDoc_VisMaterialDriver_HeaderFile #include <Standard.hxx> #include <XmlMDF_ADriver.hxx> #include <XmlObjMgt_RRelocationTable.hxx> #include <XmlObjMgt_SRelocationTable.hxx> DEFINE_STANDARD_HANDLE(XmlMXCAFDoc_VisMaterialDriver, XmlMDF_ADriver) //! Attribute Driver. class XmlMXCAFDoc_VisMaterialDriver : public XmlMDF_ADriver { DEFINE_STANDARD_RTTIEXT(XmlMXCAFDoc_VisMaterialDriver, XmlMDF_ADriver) public: //! Main constructor. Standard_EXPORT XmlMXCAFDoc_VisMaterialDriver (const Handle(Message_Messenger)& theMessageDriver); //! Create new instance of XCAFDoc_VisMaterial. Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE; //! Paste attribute from persistence into document. Standard_EXPORT Standard_Boolean Paste (const XmlObjMgt_Persistent& theSource, const Handle(TDF_Attribute)& theTarget, XmlObjMgt_RRelocationTable& theRelocTable) const Standard_OVERRIDE; //! Paste attribute from document into persistence. Standard_EXPORT void Paste (const Handle(TDF_Attribute)& theSource, XmlObjMgt_Persistent& theTarget, XmlObjMgt_SRelocationTable& theRelocTable) const Standard_OVERRIDE; }; #endif // _XmlMXCAFDoc_VisMaterialDriver_HeaderFile
#include "SM_Math.h" #include <string.h> namespace { float i2f(unsigned int i) { float ret; memcpy(&ret, &i, sizeof(float)); return ret; } } namespace sm { // from glm float f16_to_f32(unsigned short value) { int s = (value >> 15) & 0x00000001; int e = (value >> 10) & 0x0000001f; int m = value & 0x000003ff; if(e == 0) { if(m == 0) { // // Plus or minus zero // return i2f(static_cast<unsigned int>(s << 31)); } else { // // Denormalized number -- renormalize it // while(!(m & 0x00000400)) { m <<= 1; e -= 1; } e += 1; m &= ~0x00000400; } } else if(e == 31) { if(m == 0) { // // Positive or negative infinity // return i2f(static_cast<unsigned int>((s << 31) | 0x7f800000)); } else { // // Nan -- preserve sign and significand bits // return i2f(static_cast<unsigned int>((s << 31) | 0x7f800000 | (m << 13))); } } // // Normalized number // e = e + (127 - 15); m = m << 13; // // Assemble s, e and m. // return i2f(static_cast<unsigned int>((s << 31) | (e << 23) | m)); } }
#include "Cylinder.h" Cylinder::Cylinder(Point3 c, Point3 t, Point3 s, float th) :center(c), tilt(t), shape(s), theta(th) { colour = color + BLACK; } Cylinder::Cylinder() { colour = color + BLACK; theta = 0; } Cylinder::~Cylinder() { } void Cylinder::Draw() { glPushMatrix(); //set the color glColor3fv(colour); glColorMaterial(GL_FRONT, GL_AMBIENT); glEnable(GL_COLOR_MATERIAL); //draw the body of cylinder glTranslatef(center.axis[0], center.axis[1], center.axis[2]); glRotatef(theta, tilt.axis[0], tilt.axis[1], tilt.axis[2]); GLUquadric* q = gluNewQuadric(); gluCylinder(q, shape.axis[2], shape.axis[1], shape.axis[0], DRAWPARA, DRAWPARA); //draw the top and the base of the cylinder GLUquadric* q1 = gluNewQuadric(); GLUquadric* q2 = gluNewQuadric(); gluDisk(q1, 0, shape.axis[2], DRAWPARA, DRAWPARA); glTranslatef(0, 0, shape.axis[0]); gluDisk(q2, 0, shape.axis[1], DRAWPARA, DRAWPARA); glDisable(GL_COLOR_MATERIAL); glPopMatrix(); }
isalnum() 如果参数是字母或者数字 isalpha() 如果参数是字母 iscntrl() 如果参数是控制字符 isdigit() 如果参数是数字(0~9) isgraph() 如果参数是除空格之外的打印字符 islower() 如果参数是小写字母 isprint() 如果参数是打印字符(包括打印字符) ispunct() 如果参数是标点符号 isspace() 如果参数是标准空白字符,like空格、进纸、换行符、回车、水平制表符、垂直制表符 isupper() 如果参数是大写字母 isxdigit() 如果参数是十六进制数字 tolower() 如果参数是大写字符,返回其小写,否则返回该参数 toupper() 如果参数是小写字符,返回其大写,否则返回该参数 #include <iostream> #include <cctype> int main() { using namespace std; cout << "Please enter text for analysis, and quit with EOF!" << endl; char ch; int whitespace = 0; int digits = 0; int chars = 0; int punct = 0; int others = 0; cin.get(ch); while (cin.get(ch)) { if (isalpha(ch)) chars++; else if (isspace(ch)) { whitespace++; } else if (isdigit(ch)) digits++; else if (ispunct(ch)) { punct++; } else { others++; } } cout << chars << "letters, " << whitespace << " whitespace, " << digits << " digits, " << punct << " punctuations, " << others << " others." << endl; while (cin.get() != 'q') ; return 0; }
#include "literal.h" #include "visitor.h" Literal::Literal() {} Literal::~Literal() {} CharacterLiteral::CharacterLiteral(char _val) : val(_val) {} void CharacterLiteral::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } CharacterLiteral::~CharacterLiteral() {} IntegerLiteral::IntegerLiteral(int _val) : val(_val) {} void IntegerLiteral::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } IntegerLiteral::~IntegerLiteral() {} UnsignedLiteral::UnsignedLiteral(unsigned _val) : val(_val) {} void UnsignedLiteral::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } UnsignedLiteral::~UnsignedLiteral() {} BooleanLiteral::BooleanLiteral(bool _val) : val(_val) {} void BooleanLiteral::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } BooleanLiteral::~BooleanLiteral() {} StringLiteral::StringLiteral(std::string _val) { val = ""; for(int i=0; i<(int)_val.length(); ++i) { if(_val[i] != '\\') val += _val[i]; else if(_val[i+1] == 'n') { val += '\n'; ++i; } else if(_val[i+1] == 't') { val += '\t'; ++i; } else if(_val[i+1] == '\'') { val += '\''; ++i; } else if(_val[i+1] == '\\') { val += '\\'; ++i; } else if(_val[i+1] == '\"') { val += '\"'; ++i; } else if(_val[i+1] == 'r') { val += '\r'; ++i; } else { assert(0); } } } void StringLiteral::Accept(AbstractDispatcher& dispatcher) { dispatcher.Dispatch(*this); } StringLiteral::~StringLiteral() {}
// -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- // should this whole module be #ifdef QUICK ? /* Strings referenced in adjunct/desktop_util/. * * Comment lines of both forms valid in C++ are ignored. Preprocessor * directives are allowed: the #if-ery around each string tag should reflect the * #if-ery around its use in the indicated file(s). Strings tags may be * repeated to simplify matching the #if-ery (e.g. when used in two places with * different #if-ery). * * Please indicate which file a string is used in, to help others track it * down. An end-of-line comment indicates the file(s) the string is in. A * file-name comment on a line of its own applies to all subsequent lines up to * the next blank line; an end-of-line comment starting with + indicates more * files containing the string; other end-of-line filename comments transiently * over-ride the block rule. Include commented-out string tags for string tags * that appear only in comments. */ // file_choosers/save_document.cpp D_SAVE_DOCUMENT_TYPES D_SAVE_DOCUMENT_MHTML_TYPES #ifdef WIC_CAP_DOCUMENTTYPE_WEBFEED D_SAVE_DOCUMENT_WEBFEED_TYPES #endif D_SAVE_DOCUMENT_XML_TYPES // handlers/DownloadManager.cpp // should these be #ifdef QUICK ? SI_IDSTR_DOWNLOAD_DLG_UNKNOWN_SERVER SI_SAVE_FILE_TYPES S_SAVE_AS_CAPTION // sessions/opsessionmanager.cpp #ifdef SESSION_SUPPORT # ifdef UPGRADE_SUPPORT # ifdef AUTOSAVE_WINDOWS S_IMPORTED_OLD_AUTO_SESSION # endif S_IMPORTED_OLD_SESSION # endif #endif // search/searchmanager.cpp: SI_IDSTR_SEARCH_HEADER_ENGINE SI_IDSTR_SEARCH_HEADER_KEYWORD SI_IDSTR_SEARCH_FORMAT_WITH // + search/search_net.cpp // selftest/ S_SELFTEST_TITLE // string/stringutils.cpp #ifdef QUICK SI_IDSTR_1BYTE SI_IDSTR_BYTE SI_IDSTR_BYTES SI_IDSTR_GIGABYTE SI_IDSTR_KILOBYTE SI_IDSTR_MEGABYTE #endif // QUICK // src/desktop_util_module.cpp #ifdef M2_SUPPORT D_MAIL_PROBLEM_INITIALIZING_TEXT D_MAIL_PROBLEM_INITIALIZING_TITLE // sound/SoundUtils.cpp SI_NO_SOUND_STRING // adjunct/m2_ui/widgets/MessageHeaderGroup.cpp S_FILE_SAVE_PROMPT_OVERWRITE #endif // M2_SUPPORT
#include "stdio.h" #include "winsock2.h" #pragma comment(lib,"ws2_32.lib") #define SERVERIP "192.168.0.102" #define SERVERPORT 6666 int main(){ int ret; char sendBuf[512],recvBuf[512],file_name[512]; //存放windows socket初始化信息 WSADATA data; SOCKET sockListen,sockTongXun; printf("输入存储文件的文件名:\n"); scanf("%s",file_name); //1.create file FILE *fp=fopen(file_name,"wb"); if (fp==NULL){ printf("creat file %s failed\n",file_name); return -1; } //2.初始化winsock ret=WSAStartup(MAKEWORD(2,2),&data); if (SOCKET_ERROR==ret){ printf("client WSAStartup failed: %d\n",ret); return -1; } //3.创建套接字(套接字类型,流式套接字,TCP协议) sockListen=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (SOCKET_ERROR==sockListen){ printf("socket 错误"); return -2; } //4.设置服务器地址 struct sockaddr_in addrServer; int len; addrServer.sin_addr.S_un.S_addr=inet_addr(SERVERIP); addrServer.sin_family=AF_INET; addrServer.sin_port=htons(SERVERPORT); len=sizeof(sockaddr); //5.绑定套接字 ret=bind(sockListen,(sockaddr*)&addrServer,len); if (SOCKET_ERROR==ret){ printf("bind 错误"); return -3; } //6.开始监听 ret=listen(sockListen,1); if (SOCKET_ERROR==ret){ printf("listen 错误"); return -4; } printf("服务器启动成功,正在监听...\n\n"); //7.如果没有client要连接,server在调用时就阻塞,有client要连接,就从这个要连接的队列里取出然后accept //监听知道有client要连接 struct sockaddr_in addrClient; len=sizeof(sockaddr); sockTongXun=accept(sockListen,(sockaddr*)&addrClient,&len); if (INVALID_SOCKET==ret){ printf("accept 错误"); return -5; } printf("接收到一个客户端连接,下面开始通信...\n\n"); //8.向client发送消息 memset(sendBuf,0,sizeof(sendBuf)); strcpy(sendBuf,"Welcome to tcpServer,你已经连接到了TCP服务器!"); ret=send(sockTongXun,sendBuf,sizeof(sendBuf)+1,0); if (SOCKET_ERROR==ret){ printf("send 错误"); return -6; } printf("向客户端成功发送以下信息:\n%s\n\n",sendBuf); memset(recvBuf,0,sizeof(recvBuf)); //9.接受从客户端发来的消息 int num = 0; while (1){ num = recv(sockTongXun, recvBuf, 512, 0); if (SOCKET_ERROR==num){ printf("recv 错误"); return -7; } if(num == 0) break; fwrite(recvBuf, 1, num, fp); } printf("transmission done\n"); //10.关闭文件 fclose(fp); //11.shutdown 两个sock /*ret=shutdown(sockListen,SD_SEND); if(ret == SOCKET_ERROR){ printf("server shutdown failed %ld\n", WSAGetLastError()); closesocket(sockListen); WSACleanup(); return 1; } ret=shutdown(sockTongXun,SD_SEND); if(ret == SOCKET_ERROR){ printf("server shutdown failed %ld\n", WSAGetLastError()); closesocket(sockTongXun); WSACleanup(); return 1; } */ //12.关闭套接字 closesocket(sockListen); closesocket(sockTongXun); //13.卸载winsock WSACleanup(); system("pause"); return 0; }
#include "../SDK.h" void ConVar::SetValue( const char* value ) { typedef void( __thiscall* OriginalFn )( void*, const char* ); return U::GetVFunc<OriginalFn>( this, 14 )( this, value ); } void ConVar::SetValue( float value ) { typedef void( __thiscall* OriginalFn )( void*, float ); return U::GetVFunc<OriginalFn>( this, 15 )( this, value ); } void ConVar::SetValue( int value ) { typedef void( __thiscall* OriginalFn )( void*, int ); return U::GetVFunc<OriginalFn>( this, 16 )( this, value ); } float ConVar::GetFloat() { typedef float(*oGetFloat)(void*); return U::GetVFunc<oGetFloat>(this, 15)(this); } int ConVar::GetInt() { typedef int(*oGetInt)(void*); return U::GetVFunc<oGetInt>(this, 16)(this); } void ConVar::SetValue( Color value ) { typedef void( __thiscall* OriginalFn )( void*, Color ); return U::GetVFunc<OriginalFn>( this, 17 )( this, value ); } char* ConVar::GetName( ) { typedef char*( __thiscall* OriginalFn )( void* ); return U::GetVFunc<OriginalFn>( this, 5 )( this ); } char* ConVar::GetDefault( ) { return pszDefaultValue; } SpoofedConvar::SpoofedConvar(){} SpoofedConvar::SpoofedConvar( const char* szCVar ) { m_pOriginalCVar = I::Cvar->FindVar( szCVar ); Spoof(); } SpoofedConvar::SpoofedConvar( ConVar* pCVar ) { m_pOriginalCVar = pCVar; Spoof(); } SpoofedConvar::~SpoofedConvar() { if( IsSpoofed() ) { DWORD dwOld; SetFlags( m_iOriginalFlags ); SetString( m_szOriginalValue ); VirtualProtect( ( LPVOID )m_pOriginalCVar->pszName, 128, PAGE_READWRITE, &dwOld ); strcpy( ( char* )m_pOriginalCVar->pszName, m_szOriginalName ); VirtualProtect( ( LPVOID )m_pOriginalCVar->pszName, 128, dwOld, &dwOld ); //Unregister dummy cvar I::Cvar->UnregisterConCommand( m_pDummyCVar ); free( m_pDummyCVar ); m_pDummyCVar = nullptr; } } bool SpoofedConvar::IsSpoofed() { return m_pDummyCVar != nullptr; } void SpoofedConvar::Spoof() { if( !IsSpoofed() && m_pOriginalCVar ) { //Save old name value and flags so we can restore the cvar lates if needed m_iOriginalFlags = m_pOriginalCVar->nFlags; strcpy( m_szOriginalName, m_pOriginalCVar->pszName ); strcpy( m_szOriginalValue, m_pOriginalCVar->pszDefaultValue ); sprintf_s( m_szDummyName, 128, "d_%s", m_szOriginalName ); //Create the dummy cvar m_pDummyCVar = ( ConVar* )malloc( sizeof( ConVar ) ); if( !m_pDummyCVar ) return; memcpy( m_pDummyCVar, m_pOriginalCVar, sizeof( ConVar ) ); m_pDummyCVar->pNext = nullptr; //Register it I::Cvar->RegisterConCommand( m_pDummyCVar ); //Fix "write access violation" bullshit DWORD dwOld; VirtualProtect( ( LPVOID )m_pOriginalCVar->pszName, 128, PAGE_READWRITE, &dwOld ); //Rename the cvar strcpy( ( char* )m_pOriginalCVar->pszName, m_szDummyName ); VirtualProtect( ( LPVOID )m_pOriginalCVar->pszName, 128, dwOld, &dwOld ); SetFlags( FCVAR_NONE ); } } void SpoofedConvar::SetFlags( int flags ) { if( IsSpoofed() ) { m_pOriginalCVar->nFlags = flags; } } int SpoofedConvar::GetFlags() { return m_pOriginalCVar->nFlags; } void SpoofedConvar::SetInt( int iValue ) { if( IsSpoofed() ) { m_pOriginalCVar->SetValue( iValue ); } } void SpoofedConvar::SetBool( bool bValue ) { if( IsSpoofed() ) { m_pOriginalCVar->SetValue( bValue ); } } void SpoofedConvar::SetFloat( float flValue ) { if( IsSpoofed() ) { m_pOriginalCVar->SetValue( flValue ); } } void SpoofedConvar::SetString( const char* szValue ) { if( IsSpoofed() ) { m_pOriginalCVar->SetValue( szValue ); } }
#ifndef INC_SHADY_ENGINE_APPLICATION_H #define INC_SHADY_ENGINE_APPLICATION_H //C++ headers #include<string> //third party headers #include<GL/glew.h> #include<GLFW/glfw3.h> namespace shady_engine { class application { protected: GLFWwindow *mWindow; float mWindowWidth; float mWindowHeight; public: application( const std::string& pName, int pWindowWidth, int pWindowHeight, bool pFullScreen ); virtual ~application(); void start(); //Callbacks virtual void key_callback( GLFWwindow* pWindow, int pKey, int pScancode, int pAction, int pMods ); virtual void error_callback( int pError, const char* pDesc ); virtual void window_resize_callback( GLFWwindow* pWindow, int pWidth, int pHeight ); virtual void mouse_button_callback( GLFWwindow* pWindow, int pKey, int pAction, int pMods ); virtual void cursor_pos_callback( GLFWwindow* pWindow, double pX, double pY ); virtual void loop() = 0; void glfw_loop(); inline GLFWwindow* get_window() const { return mWindow; } }; } #endif
#pragma once #include <iostream> #include "VariableNode.hpp" template<class Type> struct VariableSingleValueNode : VariableNode<Type> { VariableSingleValueNode(Type & value, Type & delta) : m_value(value) , m_delta(delta) {} ArrayView<Type const> getOutputValues() const override { return ArrayView<Type const>(m_value); } std::size_t getNumOutputs() const override { return 1; } void backPropagate(ArrayView<Type const> errors) override { m_delta += errors[0]; } private: Type & m_value; Type & m_delta; };
#include "../SDL_main.cc" #include <SDL2/SDL_image.h> #include "cp_lib/basic.cc" #include "cp_lib/array.cc" #include "cp_lib/vector.cc" #include "cp_lib/matrix.cc" #include "cp_lib/memory.cc" #include <stdlib.h> #include <unistd.h> #include "../draw.cc" #include "wireframe_test.cc" using namespace cp; sbuff<Tuple<vec3f, vec2f, vec4f>, 4> cube_vertices = {{ { { -1, -1, -1 }, { {0, 0}, {{1, 1, 0, 0}} } }, { { 1, -1, -1 }, { {1, 0}, {{1, 0, 1, 0}} } }, { { 1, 1, -1 }, { {1, 1}, {{1, 0, 0, 1}} } }, { { -1, 1, -1 }, { {0, 1}, {{1, 1, 0, 0}} } } }}; sbuff<u32[3], 10> cube_triangles = {{ {0, 2, 1}, //face front {0, 3, 2}, }}; // sbuff<u32[2], 12> cube_edges = {{ // {0, 1}, {0, 3}, {1, 2}, {2, 3}, // {4, 5}, {4, 7}, {6, 5}, {6, 7}, // {0, 7}, {1, 6}, {2, 5}, {3, 4}, // }}; Mesh cube_mesh = {{(u8*)cube_vertices.buffer, cap(&cube_vertices) * (u32)sizeof(Tuple<vec3f, vec2f, vec4f>)}, {cube_triangles.buffer, cap(&cube_triangles)}}; vec3f cube_position = { 0, 0, 3}; quat cube_rotation = {1, 0, 0, 0}; bool is_ortho = true; dbuff<vec3f> proj_buffer; dbuff<u8> proc_buffer; float line_color[2][4] = {{1, 0.9, 0, 0.9}, {1, 0, 0.9, 0.9}}; dbuff2f line_color_buffer = {(f32*)line_color, 2, 4}; // float triangle_color[3][4] = {{1, 0.9, 0, 0.9}, {1, 0, 0.9, 0.9}, {1, 0.9, 0.9, 0}}; float triangle_color[3][4] = {{1, 1, 0, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}}; dbuff2f triangle_color_buffer = {(f32*)triangle_color, 3, 4}; dbuff2f z_buffer; static quat rot_x; static quat rot_y; static quat rot_z; dbuff2u test_texture; void test_color_itpl_vsh(void* handle_p) { auto handle = (Vertex_Shader_Handle*)handle_p; auto vertex = (Tuple<vec3f, vec2f, vec4f>*)handle->vertex; auto t_args = (Tuple<mat4f*, vec2f(*)(vec3f)>*)handle->args; mat4f* affine_m = t_args->get<0>(); vec2f(*project_lmd)(vec3f) = t_args->get<1>(); vec4f vertex_pos = { vertex->get<0>().x, vertex->get<0>().y, vertex->get<0>().z, 1 }; vec4f p = *affine_m * vertex_pos; vec2f pr = project_lmd({p.x, p.y, p.z}); handle->out_vertex_itpl_vector[0] = p.z; *(vec2f*)&handle->out_vertex_itpl_vector[1] = vertex->get<1>(); *(vec4f*)&handle->out_vertex_itpl_vector[3] = vertex->get<2>(); *handle->out_vertex_position = space_to_screen_coord(pr, window_size, {100, 100}); } void test_color_itpl_fsh(void* args) { auto handle = (Fragment_Shader_Handle*)args; float z = handle->itpl_vector[0]; dbuff2f *z_buffer = (dbuff2f*)handle->args; f32* prev_z; if (!z_buffer->sget(&prev_z, handle->point.y, handle->point.x) || z > *prev_z) return; vec4f *fcolor = (vec4f*)&handle->itpl_vector[1]; Color color; if (abs(z) != 0) { color = to_color( *fcolor / z); } else color = {0xffffffff}; handle->set_pixel_color_lmd(handle->out_frame_buffer, handle->point, color); *prev_z = z; } void test_texture_fsh(void* args) { auto handle = (Fragment_Shader_Handle*)args; float z = handle->itpl_vector[0]; auto args_tuple = (Tuple<dbuff2f*, dbuff2u*>*)handle->args; dbuff2f *z_buffer = args_tuple->get<0>(); f32* prev_z; if (!z_buffer->sget(&prev_z, handle->point.y, handle->point.x) || z > *prev_z) return; dbuff2u *texture = args_tuple->get<1>(); vec2f *itpl_uv = (vec2f*)&handle->itpl_vector[1]; vec2i uv = { (i32)(texture->x_cap * itpl_uv->u), (i32)(texture->y_cap * itpl_uv->v) }; Color color = { texture->get(uv.y, uv.x) }; if (color.a < 1) return; // if (abs(z) != 0) { // color = to_color( *fcolor / z); // } else // color = {0xffffffff}; handle->set_pixel_color_lmd(handle->out_frame_buffer, handle->point, color); *prev_z = z; } void game_init() { input_init(); window_max_size = {1920, 1080}; window_size = {1280, 720}; proj_buffer.init(8); proc_buffer.init(80000); // create buffer frame_buffer.init(window_size.y/4, window_size.x/4); z_buffer.init(window_size.y/4, window_size.x/4); frame_buffer.init(window_size.y, window_size.x); z_buffer.init(window_size.y, window_size.x); rot_x.init(normalized(vec3f{1, 0, 0}), M_PI/10); rot_y.init(normalized(vec3f{0, 1, 0}), M_PI/10); rot_z.init(normalized(vec3f{0, 0, 1}), M_PI/10); SDL_Init(SDL_INIT_VIDEO); int flags = IMG_INIT_PNG; if ( !( IMG_Init( flags ) & flags ) ) { printf("Can't init image: %i\n", IMG_GetError()); assert(false); } TTF_Init(); SDL_Surface *test_texture_sur = IMG_Load("Test/Assets/TestTexture.png"); test_texture = { (u32*)test_texture_sur->pixels, test_texture_sur->h, test_texture_sur->w }; } void game_shut() { input_shut(); proj_buffer.shut(); proc_buffer.shut(); frame_buffer.shut(); z_buffer.shut(); } void game_update() { if (get_bit(Input::keys_down, 'q')) { is_running = false; } if (get_bit(Input::keys_down, 'o')) { is_ortho = !is_ortho; } if (get_bit(Input::keys_hold, 'w')) { cube_position += vec3f(0, 0, 0.1); } if (get_bit(Input::keys_hold, 's')) { cube_position += vec3f(0, 0, -0.1); } if (get_bit(Input::keys_hold, 'a')) { cube_position += vec3f(-0.1, 0, 0); } if (get_bit(Input::keys_hold, 'd')) { cube_position += vec3f(0.1, 0, 0); } if (get_bit(Input::keys_hold, 't')) { cube_rotation = rot_x * cube_rotation; } if (get_bit(Input::keys_hold, 'g')) { cube_rotation = inverse(rot_x) * cube_rotation; } if (get_bit(Input::keys_hold, 'f')) { cube_rotation = rot_y * cube_rotation; } if (get_bit(Input::keys_hold, 'h')) { cube_rotation = inverse(rot_y) * cube_rotation; } if (get_bit(Input::keys_hold, 'r')) { cube_rotation = rot_z * cube_rotation; } if (get_bit(Input::keys_hold, 'y')) { cube_rotation = inverse(rot_z) * cube_rotation; } // write to buffer for (auto p = begin(&frame_buffer); p < end(&frame_buffer); p++) { *p = 0xff223344; } for (auto p = begin(&z_buffer); p < end(&z_buffer); p++) { *p = INT_MAX; } // Color c = {0xff5533ff}; // if (pointer_local_pos.x < window_size.x && pointer_local_pos.y < window_size.y) // rasterize_line(frame_buffer, {500, 500}, pointer_local_pos - vec2i(100, 100), // line_color_buffer, color_itpl_frag_shader, null, set_pixel_color); // if (pointer_local_pos.x < window_size.x && pointer_local_pos.y < window_size.y) // rasterize_triangle_scanline(frame_buffer, {500, 500}, {300, 200}, pointer_local_pos, {0xff00ff00}, proc_buffer, set_pixel_color); // if (pointer_local_pos.x < window_size.x && pointer_local_pos.y < window_size.y) // rasterize_triangle_scanline(frame_buffer, {500, 500}, {300, 200}, pointer_local_pos, // triangle_color_buffer, color_itpl_frag_shader, null, proc_buffer, set_pixel_color); // rasterize_triangle_scanline(frame_buffer, {500, 500}, {300, 200}, {700, 600}, // triangle_color_buffer, color_itpl_frag_shader, null, proc_buffer, set_pixel_color); // for (i32 i = 1; i < 200; i++) { // rasterize_line(frame_buffer, {1800, 100 + i}, {300, 900 + i}, {0xffff55ff + i}, set_pixel_color); // } // if (is_ortho) { // render_wireframe({&cube_mesh, &cube_position, &cube_rotation}, project_xy_orthogonal, _proj_buffer, // frame_buffer, {0xffffffff}, window_size, {100, 100}); // } else { // render_wireframe({&cube_mesh, &cube_position, &cube_rotation}, project_xy_perspective, _proj_buffer, // frame_buffer, {0xffffffff}, window_size, {100, 100}); // } // if (is_ortho) { // render_wireframe({&cube_mesh, &cube_position, &cube_rotation}, project_xy_orthogonal, _proj_buffer, // frame_buffer, z_buffer, window_size, {100, 100}); // } else { // render_wireframe({&cube_mesh, &cube_position, &cube_rotation}, project_xy_perspective, _proj_buffer, // frame_buffer, z_buffer, window_size, {100, 100}); // } // if (is_ortho) { // render_mesh({&cube_mesh, &cube_position, &cube_rotation}, project_xy_orthogonal, proc_buffer, // &frame_buffer, z_buffer, window_size/4, {25, 25}); // } else { // render_mesh({&cube_mesh, &cube_position, &cube_rotation}, project_xy_perspective, proc_buffer, // &frame_buffer, z_buffer, window_size/4, {100, 100}); // } Render_Object robj = {&cube_mesh, &cube_position, &cube_rotation}; desbuff vb = {{(u8*)robj.mesh->vertex_buffer.buffer, robj.mesh->vertex_buffer.cap}, sizeof(Tuple<vec3f, vec2f, vec4f>)}; Tuple<mat4f*, vec2f(*)(vec3f)> vsh_args; mat4f scale_m = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, }; mat4f rotation_m = vec_rot_mat4(cube_rotation); mat4f translation_m = { 1, 0, 0, cube_position.x, 0, 1, 0, cube_position.y, 0, 0, 1, cube_position.z, 0, 0, 0, 1 }; mat4f affine_m = translation_m * rotation_m * scale_m; vsh_args.get<0>() = &affine_m; if (is_ortho) { vsh_args.get<1>() = project_xy_orthogonal; } else vsh_args.get<1>() = project_xy_perspective; Tuple<dbuff2f*, dbuff2u*> fsh_arg_tupple = { &z_buffer, {&test_texture} }; Shader_Pack shaders = {test_color_itpl_vsh, &vsh_args, test_texture_fsh, &fsh_arg_tupple, 7}; draw_triangles(&frame_buffer, &vb, &robj.mesh->index_buffer, &shaders, &proc_buffer); // dbuff<u32[2]> edges_ib = {cube_edges.buffer, cap(&cube_edges)}; // draw_lines(&frame_buffer, &vb, &edges_ib, &shaders, &proc_buffer); vec2i pointer_local_pos = Input::mouse_pos/4; if (0 < pointer_local_pos.x - 5 && pointer_local_pos.x - 5 < window_size.x/4 && 0 < pointer_local_pos.y - 5 && pointer_local_pos.y - 5 < window_size.y/4) { frame_buffer.get(pointer_local_pos.y-5, pointer_local_pos.x-5) = 0xffff0000; // printf("%i %i\n", pointer_localq_pos.x-5, pointer_local_pos.y-5); } }
#include "classes.h" Global::Global() { xres = 1920; yres = 1080; mousecode = 0; //memset(keys, 0, 65536); } Base::Base() { VecZero(dir); VecZero(vec); VecZero(projection); angle[0] = 90; // xy plane (360) x is right left, y is forward backwards angle[1] = 90; // z angle (180) 0 = up, 180 = down pos[0] = 0; pos[1] = 0; pos[2] = 0; xyz[0] = 0.0; xyz[1] = 0.0; xyz[2] = 0.0; xyz2[0] = 0.0; xyz2[1] = 0.0; xyz2[2] = 0.0; polar[0] = 0.0; polar[1] = 0.0; polar[2] = 0.0; xScale = 0.0; yScale = 0.0; bulletAngle[0] = 90.0; bulletAngle[1] = 90.0; radius = 100; currentHealth = 3; maxHealth = 3; boost = 100.0; clock_gettime(CLOCK_REALTIME, &bulletTimer); clock_gettime(CLOCK_REALTIME, &thrustTimer); clock_gettime(CLOCK_REALTIME, &shieldTimer); } void Base::updatePolar(Vec ship) { xyz[0] = pos[0] - ship[0]; xyz2[0] = xyz[0]*xyz[0]; xyz[1] = pos[1] - ship[1]; xyz2[1] = xyz[1] * xyz[1]; xyz[2] = pos[2] - ship[2]; xyz2[2] = xyz[2]*xyz[2]; // r, distance polar[0] = sqrt(xyz2[0] + xyz2[1] + xyz2[2]); // theta, z angle polar[2] = acos(xyz[2]/polar[0]); polar[2] *= 180/PI; // xy angle if (xyz[0]) { polar[1] = atan2(xyz[1],xyz[0]); polar[1] *= 180/PI; } else polar[1] = 90.0; if (polar[1] > 180) { polar[1] -= 180; polar[1] = 180 - polar[2]; } } void Base::drawBase(Game * g, Global gl) { float e[3]; e[0] = 0; e[1] = polar[1]; e[2] = polar[2]; if (e[1] < 0) { e[1] = 360 + e[1]; } float s[2]; s[0] = (*g).ship.angle[0]; s[1] = (*g).ship.angle[1]; float low, high; low = s[0] - 60; high = s[0] + 60; high -= low; e[1] -= low; if (e[1] > 360) { e[1] -= 360; } if (e[1] < 0) { e[1] += 360; } projection[0] = ((high - e[1])/120)*gl.xres; projection[1] = ((s[1] + 45 - e[2])/90)*gl.yres; float x = projection[0]; float y = projection[1]; float tempValue = 0; //Scale max at the right edge of the setup_screen xScale = ((high - e[1])/60); yScale = ((s[1] + 45 - e[2])/45); if (xScale > 1.0) { tempValue = xScale - 1.0; xScale = 1.0; xScale = xScale - tempValue; } if (yScale > 1.0) { tempValue = yScale - 1.0; yScale = 1.0; yScale = yScale - tempValue; } /* float distanceScale; if (polar[0]) float distanceScale = 12/polar[0]; else distanceScale = 12; */ //float distanceScale = 12/polar[0]; float Yellow[3] = {1,1,0}; glColor3fv(Yellow); glPushMatrix(); glBegin(GL_TRIANGLE_STRIP); //Override to different Vertices for different classes? /* glVertex2i(x-(radius*xScale*distanceScale),y-(radius*yScale*distanceScale)); glVertex2i(x-(radius*xScale*distanceScale),y+(radius*yScale*distanceScale)); glVertex2i(x,y); glVertex2i(x+(radius*xScale*distanceScale),y-(radius*yScale*distanceScale)); glVertex2i(x+(radius*xScale*distanceScale),y+(radius*yScale*distanceScale)); */ glVertex2i(x,y); glEnd(); glPopMatrix(); //float cx = gl.xres/2; //float cy = gl.yres/2; Rect r; // r.bot = y + 10; r.left = x; r.center = 0; //ggprint8b(&r, 16, 0x00ff0000, "3350 - Asteroids"); ggprint8b(&r, 16, 0x00ffff00, "",currentHealth); } void Base::drawBullet(Game * g, Global gl) { if (type == 1 || type == 2) { float e[3]; e[0] = 0; e[1] = polar[1]; e[2] = polar[2]; if (e[1] > 360) { e[1] -= 360; } if (e[1] < 0) { e[1] += 360; } float s[2]; s[0] = (*g).ship.angle[0]; s[1] = (*g).ship.angle[1]; float low, high; low = s[0] - 60; high = s[0] + 60; high -= low; e[1] -= low; if (e[1] > 360) { e[1] = e[1] - 360; } float x, y; x = ((high - e[1])/120)*gl.xres; y = ((s[1] + 45 - e[2])/90)*gl.yres; float distanceScale; if (polar[0]) distanceScale = 48/polar[0]; else distanceScale = 48; if (type == 1) { color[0] = 0; color[1] = 1; color[2] = 0; } if (type == 2) { color[0] = 1; color[1] = 0; color[2] = 0; } glColor3fv(color); glPushMatrix(); glBegin(GL_POLYGON); glVertex2i(x-radius*distanceScale,y); glVertex2i(x,y+radius*distanceScale); glVertex2i(x+radius*distanceScale,y); glVertex2i(x,y-radius*distanceScale); glEnd(); glPopMatrix(); } if (type == 3) { float e[3]; e[0] = 0; e[1] = polar[1]; e[2] = polar[2]; if (e[1] > 360) { e[1] -= 360; } if (e[1] < 0) { e[1] += 360; } float s[2]; s[0] = (*g).ship.angle[0]; s[1] = (*g).ship.angle[1]; float low, high; low = s[0] - 60; high = s[0] + 60; high -= low; e[1] -= low; if (e[1] > 360) { e[1] = e[1] - 360; } float x, y; x = ((high - e[1])/120)*gl.xres; y = ((s[1] + 45 - e[2])/90)*gl.yres; float distanceScale = 48/polar[0]; //glColor3fv(color); //float Green[3] = {0,1,0}; float capsule[3] = {0,1,0}; glColor3fv(capsule); glPushMatrix(); glBegin(GL_LINE_LOOP); for (int i = 0; i < 6; i++) { glVertex2i(x + cos((i*2*PI)/6)*radius*2*distanceScale,y + sin((i*2*PI)/6)*radius*2*distanceScale); } glEnd(); glPopMatrix(); glPushMatrix(); glBegin(GL_LINE_LOOP); glVertex2i(x + cos((1*2*PI)/6)*radius*2*distanceScale,y + sin((1*2*PI)/6)*radius*2*distanceScale); glVertex2i(x + cos((2*2*PI)/6)*radius*2*distanceScale,y + sin((2*2*PI)/6)*radius*2*distanceScale); glVertex2i(x, y + radius*3*distanceScale); glEnd(); glPopMatrix(); glPushMatrix(); glBegin(GL_LINE_LOOP); glVertex2i(x + cos((3*2*PI)/6)*radius*2*distanceScale,y + sin((3*2*PI)/6)*radius*2*distanceScale); glVertex2i(x + cos((4*2*PI)/6)*radius*2*distanceScale,y + sin((4*2*PI)/6)*radius*2*distanceScale); glVertex2i(x + cos((7*PI)/6)*radius*3*distanceScale,y + sin((7*PI)/6)*radius*3*distanceScale); glEnd(); glPopMatrix(); glPushMatrix(); glBegin(GL_LINE_LOOP); glVertex2i(x + cos((5*2*PI)/6)*radius*2*distanceScale,y + sin((5*2*PI)/6)*radius*2*distanceScale); glVertex2i(x + cos((6*2*PI)/6)*radius*2*distanceScale,y + sin((6*2*PI)/6)*radius*2*distanceScale); glVertex2i(x + cos((11*PI)/6)*radius*3*distanceScale,y + sin((11*PI)/6)*radius*3*distanceScale); glEnd(); glPopMatrix(); float flame[3] = {1,.6,0}; glColor3fv(flame); glPushMatrix(); glBegin(GL_POLYGON); for (int i = 0; i < 16; i++) { glVertex2i(x + cos(i*PI/8)*radius*distanceScale,y + sin(i*PI/8)*radius*distanceScale); } glEnd(); glPopMatrix(); } if (type == 4) { float e[3]; e[0] = 0; e[1] = polar[1]; e[2] = polar[2]; if (e[1] > 360) { e[1] -= 360; } if (e[1] < 0) { e[1] += 360; } float s[2]; s[0] = (*g).ship.angle[0]; s[1] = (*g).ship.angle[1]; float low, high; low = s[0] - 60; high = s[0] + 60; high -= low; e[1] -= low; if (e[1] > 360) { e[1] = e[1] - 360; } float x, y; x = ((high - e[1])/120)*gl.xres; y = ((s[1] + 45 - e[2])/90)*gl.yres; float distanceScale = 48/polar[0]; //glColor3fv(color); //float Green[3] = {0,1,0}; float explode[4] = {1,0,0,.4}; glEnable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glColor4fv(explode); glPushMatrix(); int PTS = 48; glBegin(GL_POLYGON); for (int i = 0; i < PTS; i++) { glVertex2i(x + cos((i*2*PI)/PTS)*radius*distanceScale, y + sin((i*2*PI)/PTS)*radius*distanceScale); } glEnd(); glPopMatrix(); } } void Enemy::targeting(Game * g) { if (bulletAngle[0] < 0.0f) { bulletAngle[0] += 360.0f; } if (bulletAngle[0] > 360.0f) { bulletAngle[0] -= 360.0f; } if (bulletAngle[1] < 0.1f) { bulletAngle[1] = 0.1f; } if (bulletAngle[1] > 179.9f) { bulletAngle[1] = 179.9f; } // change it based on the ships position not its angle bulletAngle[0] = polar[1] + 180; bulletAngle[1] = 180 - polar[2]; struct timespec bt; clock_gettime(CLOCK_REALTIME, &bt); double ts = timeDiff(&bulletTimer, &bt); if (ts > 3.0) { timeCopy(&bulletTimer, &bt); if ((*g).nbullets < MAX_ARRAY) { //shoot a bullet... //Bullet *b = new Bullet; Bullet *b = &(*g).barr[(*g).nbullets]; timeCopy(&b->time, &bt); b->pos[0] = pos[0]; b->pos[1] = pos[1]; b->pos[2] = pos[2]; //b->vel = (*g).ship.vel + 25; b->vel = (*g).ship.vel + 25; //convert ship angle to radians int randNum = rand() % 4; if(randNum == 0){ b->angle[0] = bulletAngle[0]; b->angle[1] = bulletAngle[1]; } else { b->angle[0] = bulletAngle[0] + (rand() % 50 - 25); b->angle[1] = bulletAngle[1] + (rand() % 50 - 25); } b->color[0] = 0.0f; b->color[1] = 1.0f; b->color[2] = 0.0f; b->enemyBullet = true; b->type = 2; (*g).nbullets++; } } } Image::Image(const char *fname) { if (fname[0] == '\0') return; //printf("fname **%s**\n", fname); int ppmFlag = 0; char name[40]; strcpy(name, fname); int slen = strlen(name); char ppmname[80]; if (strncmp(name+(slen-4), ".ppm", 4) == 0) ppmFlag = 1; if (ppmFlag) { strcpy(ppmname, name); } else { name[slen-4] = '\0'; //printf("name **%s**\n", name); sprintf(ppmname,"%s.ppm", name); //printf("ppmname **%s**\n", ppmname); char ts[100]; //system("convert eball.jpg eball.ppm"); sprintf(ts, "convert %s %s", fname, ppmname); system(ts); } //sprintf(ts, "%s", name); FILE *fpi = fopen(ppmname, "r"); if (fpi) { char line[200]; fgets(line, 200, fpi); fgets(line, 200, fpi); //skip comments and blank lines while (line[0] == '#' || strlen(line) < 2) fgets(line, 200, fpi); sscanf(line, "%i %i", &width, &height); fgets(line, 200, fpi); //get pixel data int n = width * height * 3; data = new unsigned char[n]; for (int i=0; i<n; i++) data[i] = fgetc(fpi); fclose(fpi); } else { printf("ERROR opening image: %s\n",ppmname); exit(0); } if (!ppmFlag) unlink(ppmname); } Ship::Ship(int x, int y, int z) { pos[0] = x; pos[1] = y; pos[2] = z; vel = 0; color[0] = color[1] = color[2] = 1.0; color[3] = .1; lockedOn = false; numLockedOn = 0; for (int i = 0; i < 16; i++) { for (int j = 0; j < 4; j++) { missileXY[i][j] = 0; } } color[0] = color[1] = color[2] = 1.0; maxHealth = maxShield = maxBoost = 100; currentHealth = maxHealth; currentShield = maxShield; boost = maxBoost; powerLevel = 1; maxBullets = MAX; weaponType = 1; boost = 100; clock_gettime(CLOCK_REALTIME, &bulletTimer); } Object::Object(int x, int y, int z) { pos[0] = x; pos[1] = y; pos[2] = z; } Bullet::Bullet() { type = 1; radius = 15; enemyBullet = false; } Game::Game(const Ship& ship, const Object& object) : ship(ship), object(object) { gameState = GameState::GS_Menu; playmusic = false; playmusic2 = false; menuitem = 0; playw=0; controlsw=0; creditsw=0; exitw=0; show_credits = false; barr = new Bullet[MAX_ARRAY]; earr = new Enemy[MAX_ARRAY]; sarr = new Squadron[MAX_ARRAY]; nenemies = 0; nbullets = 0; nsquadrons = 0; mouseThrustOn = false; mtext = 0; difficulty = 1.0; level = 1; score = 0; num_stars = 32000; clock_gettime(CLOCK_REALTIME, &difficultyTimer); }
/** \file WalkInit.hpp \author UnBeatables \date LARC2018 \name WalkInit */ #pragma once /* * WalkInit inherited from BehaviorBase. */ #include <BehaviorBase.hpp> /** \brief This class is responsable for robot's walk when game starts. */ class WalkInit : public BehaviorBase { private: static WalkInit *instance; int ballX, ballY, lostCount; bool isLost, camera; bool motionFinished; public: /** \brief Class constructor. \details Inicialize class parameters. */ WalkInit(); /** \brief Sets WalkInit as current instance. \return Current instance. */ static BehaviorBase* Behavior(); /** \brief This function determines WalkInit transition. \details Transitions to LookForBall when robot finishes walking. \param _ub void pointer for UnBoard. \return Transition state. */ BehaviorBase* transition(void*); /** \brief In this action robot will walk a few steps after kickoff. \param _ub void pointer for UnBoard. */ void action(void*); };
#include <conio.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include <locale.h> #include <ctype.h> int num[20]; int comp,a,b,mult; int main() { printf("insira 20 numeros:\n"); for(a=0; a<20; a++) { scanf("%d", &num[a]); } printf("insira uma constante multiplicativa:\n"); scanf("%d", &mult); comp=0; for(b=0; b< 20; b++) { num[b] = num[b]*mult; } printf ("Os numeros inseridos e multiplciados pela constante foram:\n"); for(comp=0; comp< 20; comp++) { printf("%d \n",num[comp]); } }
#include <CapacitiveSensor.h> CapacitiveSensor cs_4_2 = CapacitiveSensor(4,2); // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil const int numReadings = 10; const int OUTPUT_PIN = 6; int readings[numReadings]; // the readings from the analog input int readIndex = 0; // the index of the current reading int total = 0; // the running total int average = 0; void setup(){ cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF); // turn off autocalibrate on channel 1 - just as an example Serial.begin(9600); Serial.begin(9600); } void loop(){ long start = millis(); // long total1 = cs_4_2.capacitiveSensor(30); total = total - readings[readIndex]; // read from the sensor: readings[readIndex] = cs_4_2.capacitiveSensor(30); // add the reading to the total: total = total + readings[readIndex]; // advance to the next position in the array: readIndex = readIndex + 1; // if we're at the end of the array... if (readIndex >= numReadings) { // ...wrap around to the beginning: readIndex = 0; } // calculate the average: average = total / numReadings; Serial.print(millis() - start); // check on performance in milliseconds Serial.print("\t"); // tab character for debug window spacing Serial.println(average); // print sensor output 1 average = average < 10 ? 0 : average - 10; int ledPower = average > 255 ? 255 : average; analogWrite(OUTPUT_PIN, ledPower); delay(10); // arbitrary delay to limit data to serial port }
#include "constants.hpp" const QString ConstantStrings::averageRatio = "averageRatio"; const QString ConstantStrings::brainCount = "brainCount"; const QString ConstantStrings::neuronPerBrain = "neuronPerBrain"; const QString ConstantStrings::loopPerCompute = "loopPerCompute"; const QString ConstantStrings::mutationFrequency = "mutationFrequency"; const QString ConstantStrings::mutationIntensity = "mutationIntensity"; const QString ConstantStrings::imageId = "imageId"; const QString ConstantStrings::steps = "steps"; const QString ConstantStrings::brains = "brains"; const QString ConstantStrings::brain = "brain"; const QString ConstantStrings::age = "age"; const QString ConstantStrings::winCount = "winCount"; const QString ConstantStrings::loseCount = "loseCount"; const QString ConstantStrings::dna = "dna"; const QString ConstantStrings::dnaSize = "dnaSize";
#pragma once #include"Padre.h" #include"PoderPersonajeA.h" using namespace std; using namespace System::Drawing; class PersonajeA:public Padre { public: int Energia; int puntoH; int puntoV; int AnchoI; int AltoI; bool transparente; public: PersonajeA(int x, int y, Bitmap^bmp); PersonajeA(); ~PersonajeA(); void Dibujar(Graphics^gr, Bitmap^bmp); void Mover(Graphics^gr, Bitmap^bmp, Direccion D); void DibujarVida(Graphics^gr); void DibujarEnergia(Graphics^gr); list<PoderPersonajeA*> list_PoderPersonajeA; void AgregarPoder(int x, int y, Bitmap^bmp); void MostrarPoder(Graphics^gr, Bitmap^bmp); }; PersonajeA::PersonajeA(int x, int y, Bitmap^bmp){ AnchoI = bmp->Width / 4; AltoI = bmp->Height / 4; SET_X(x); SET_Y(y); transparente=true; puntoH = 0; puntoV = 0; SET_Dx(0); SET_Dy(0); SET_Alto(70); SET_Ancho(70); SET_movimiento(Direccion::Ninguno); SET_Vida(100); Energia = 100; } PersonajeA::PersonajeA() { } PersonajeA::~PersonajeA() { } void PersonajeA::Dibujar(Graphics^gr, Bitmap^bmp){ Rectangle Origen = Rectangle(AnchoI*puntoH, AltoI*puntoV, AnchoI, AltoI); Rectangle Fin = Rectangle(GET_X(), GET_Y(), GET_Ancho(), GET_Alto()); gr->DrawImage(bmp, Fin, Origen, GraphicsUnit::Pixel); if (puntoH == 3){ puntoH = 0; } puntoH++; } void PersonajeA::Mover(Graphics^gr, Bitmap^bmp, Direccion D){ switch (D) { case Arriba: SET_Dy(-5); SET_Dx(0); puntoV = 3; break; case Abajo: SET_Dy(5); SET_Dx(0); puntoV=0; break; case Derecha: SET_Dy(0); SET_Dx(5); puntoV=2; break; case Izquiera: SET_Dy(0); SET_Dx(-5); puntoV=1; break; case Ninguno: SET_Dx(0); SET_Dy(0); puntoH = 0; break; } SET_X(GET_X() + GET_Dx()); SET_Y(GET_Y() + GET_Dy()); Dibujar(gr, bmp); DibujarEnergia(gr); DibujarVida(gr); } void PersonajeA::DibujarVida(Graphics^gr){ gr->DrawRectangle(gcnew Pen(Color::Black), GET_X() - 1, GET_Y() - 12, 101, 4); gr->FillRectangle(gcnew SolidBrush(Color::Red), GET_X(), GET_Y() - 12, GET_Vida(), 3); } void PersonajeA::DibujarEnergia(Graphics^gr){ gr->DrawRectangle(gcnew Pen(Color::Black), GET_X() - 1, GET_Y() - 6, 101, 4); gr->FillRectangle(gcnew SolidBrush(Color::Yellow), GET_X(), GET_Y() - 6, Energia, 3); } void PersonajeA::AgregarPoder(int x, int y, Bitmap^bmp){ list_PoderPersonajeA.push_back(new PoderPersonajeA(x, y, bmp)); } void PersonajeA::MostrarPoder(Graphics^gr, Bitmap^bmp){ for (list<PoderPersonajeA*>::iterator it = list_PoderPersonajeA.begin(); it != list_PoderPersonajeA.end(); ++it){ (*it)->DibujarPoder1(gr, bmp); } }
#include<iostream> #include<algorithm> #include<cmath> #include<utility> using namespace std; struct Interval{ int st; int et; }; bool compare(Interval i1,Interval i2){ return i1.st < i2.st; } int main(){ int arr[] = {1,3,2,5,7,6}; sort(arr,arr+6); for(int i=0;i<6;i++){ cout<<arr[i] << " "; } //to sort in decreasing order // sort(arr,arr+6,greater<int>()); // for(int i=0;i<6;i++){ // cout<<arr[i]<<" "; // } //if this ,it will sort from index 2 to end // sort(arr+2,arr+6); // for(int i=0;i<6;i++){ // cout<<arr[i] << " "; // } //to sort intervals on the basis of starting index define struct Interval and function compare Interval arr1[] = {{6,4} , {3,4}, {4,6} , {8,13}}; sort(arr1,arr1+4,compare); for(int i=0;i<4;i++){ cout<<arr1[i].st<<":"<<arr1[i].et<<endl; } cout<<endl; //search 2, using binary_search cout << "index of 2 is"<<binary_search(arr,arr+6,2); cout<<endl; //search 8, using binary_search cout << "index of 8 is"<<binary_search(arr,arr+6,8); cout<<endl; //lower bound returns pointer to that position like arr+2 that's why we substract by arr cout<<lower_bound(arr,arr+6,3) - arr; cout<<endl; //if element does't exist then it will return position where element should be cout<<lower_bound(arr,arr+6,4) - arr; cout<<endl; //if there is repetition then it will return position of first occuring no //upper_bound will return just next higher no.and if there is repetition it will consider last //occurence and then add 1 cout<<upper_bound(arr,arr+6,3) - arr; cout<<endl; cout<<endl; cout<<__gcd(10,6)<<endl; //pow is in cmath cout<<pow(2.2,5)<<endl; int x= 10; int y=12; //swap is in utility swap(x,y); cout<<x<<endl; cout<<y<<endl; cout<<min(14,18)<<endl; // for(int i=0;i<4;i++){ // cout << arr[i].st << " : " << arr[i].et << endl; // } return 0; }
// PingerDlg.cpp : implementation file // #include "stdafx.h" #include "Pinger.h" #include "PingerDlg.h" #include "sockeng.h" #include "cbtext.h" #include "HelpDialog.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define DELAY 100 int gRunning=0; int gResolving=0; int totalThreads=0; int sem=0; struct ThreadArgs { HWND win; long NumPasses; long Start,End,Timeout; long Delay; }; struct ResolvArgs { HWND win; long address; int index; }; /* Our pinging thread entry point */ UINT Scan(LPVOID pParam) { struct ThreadArgs *ta; ta=(struct ThreadArgs *)pParam; gRunning=1; ::PostMessage(ta->win,WM_THREADSTARTING,0,0); sockeng *s=new sockeng(ta->Timeout,ta->Start,ta->End, ta->NumPasses,ta->Delay); s->ping(ta->win); ::PostMessage(ta->win,WM_THREADDONE,0,0); delete s; return 0; } /* Our host resolving thread entry point */ UINT ResolveHost(LPVOID pParam) { struct ResolvArgs *ta; struct hostent *hp; struct in_addr ip; ta=(struct ResolvArgs *)pParam; ip.S_un.S_addr=ta->address; totalThreads++; /* makeshift semaphore :< */ /* god i wish i knew what i was doing */ /* wierd stuff can happen beacuse it's not atomic, but it * doesn't really matter */ while ((sem>30) && (gRunning==1)) { Sleep(1000); } sem++; if (!gRunning) { free(ta); totalThreads--; sem--; return 0; } hp=gethostbyaddr((char *)&(ta->address),4,AF_INET); if (!hp) { ::PostMessage(ta->win,WM_THREADRESOLVED, (long)strdup(inet_ntoa(ip)),NULL); free(ta); totalThreads--; sem--; return 0; } if (hp->h_name) { ::PostMessage(ta->win,WM_THREADRESOLVED, (long)strdup(inet_ntoa(ip)), (long)strdup(hp->h_name)); } else { ::PostMessage(ta->win,WM_THREADRESOLVED, (long)strdup(inet_ntoa(ip)),NULL); } free(ta); totalThreads--; sem--; return 0; } void AddStringSorted(CListBox *cl,char *s) { CString walker; unsigned long ip,wip; unsigned char o1,o2,o3,o4; sscanf(s,"%d.%d.%d.%d",&o1,&o2,&o3,&o4); ip=(o1<<24)+(o2<<16)+(o3<<8)+o4; for (int i=0;i<cl->GetCount();i++) { cl->GetText(i,walker); /* This is so horifically stupid... * however, I'm tired so fuck it */ sscanf(walker,"%d.%d.%d.%d",&o1,&o2,&o3,&o4); wip=(o1<<24)+(o2<<16)+(o3<<8)+o4; if (wip>ip) break; } cl->InsertString(i,s); } LRESULT CPingerDlg::OnStartup(WPARAM wParam, LPARAM lParam) { CStatic *statusBar=(CStatic *)GetDlgItem(IDC_STATUS); CListBox *list=(CListBox *)GetDlgItem(IDC_LIST); statusBar->SetWindowText("Initializing Socket Engine..."); return 0L; } LRESULT CPingerDlg::OnDone(WPARAM wParam, LPARAM lParam) { CStatic *statusBar=(CStatic *)GetDlgItem(IDC_STATUS); MSG msg; if (gResolving==1 && gRunning==1) { statusBar->SetWindowText("Resolving hostnames..."); while ((totalThreads>0) && (gRunning==1)) { // Goddamn this is sloppy GetMessage(&msg,NULL,0,0); { TranslateMessage(&msg); // Translate virt. key codes DispatchMessage(&msg); // Dispatch msg. to window } } } statusBar->SetWindowText(""); CButton *cb=(CButton *)GetDlgItem(IDC_SCAN); cb->SetWindowText("Ping"); gRunning=0; return 0L; } LRESULT CPingerDlg::OnPing(WPARAM wParam, LPARAM lParam) { CStatic *statusBar=(CStatic *)GetDlgItem(IDC_STATUS); static char bob[8192]; sprintf(bob,"Pinging %d.%d.%d.%d",(lParam&255),(lParam>>8)&255, (lParam>>16)&255,(lParam>>24)&255); statusBar->SetWindowText(bob); return 0L; } LRESULT CPingerDlg::OnHostAlive(WPARAM wParam, LPARAM lParam) { CStatic *statusBar=(CStatic *)GetDlgItem(IDC_STATUS); CListBox *list=(CListBox *)GetDlgItem(IDC_LIST); if (!gResolving) { static char bob[256]; sprintf(bob,"%d.%d.%d.%d",(lParam&255),(lParam>>8)&255, (lParam>>16)&255,(lParam>>24)&255); AddStringSorted(list,bob); } else { struct ResolvArgs *ta; ta=(struct ResolvArgs *)malloc(sizeof (struct ResolvArgs)); ta->win=GetSafeHwnd(); ta->address=lParam; CWinThread *pThread = AfxBeginThread(ResolveHost, ta, THREAD_PRIORITY_NORMAL); } return 0L; } LRESULT CPingerDlg::OnResolved(WPARAM wParam, LPARAM lParam) { CListBox *list=(CListBox *)GetDlgItem(IDC_LIST); static char bob[512]; if (lParam) sprintf(bob,"%s \t%s",(char*)wParam,(char *)lParam); else sprintf(bob,"%s",(char*)wParam); if (gRunning) AddStringSorted(list,bob); return 0L; } LRESULT CPingerDlg::OnListen(WPARAM wParam, LPARAM lParam) { CStatic *statusBar=(CStatic *)GetDlgItem(IDC_STATUS); statusBar->SetWindowText("Listening for pings..."); return 0L; } LRESULT CPingerDlg::OnError(WPARAM wParam, LPARAM lParam) { CStatic *statusBar=(CStatic *)GetDlgItem(IDC_STATUS); statusBar->SetWindowText(""); CButton *cb=(CButton *)GetDlgItem(IDC_SCAN); cb->SetWindowText("Ping"); gRunning=0; if (lParam) { CString msg((char *)lParam); MessageBox(msg,"Ping Error", MB_ICONEXCLAMATION); } return 0L; } ///////////////////////////////////////////////////////////////////////////// // CPingerDlg dialog CPingerDlg::CPingerDlg(CWnd* pParent /*=NULL*/) : CDialog(CPingerDlg::IDD, pParent) { //{{AFX_DATA_INIT(CPingerDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CPingerDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPingerDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPingerDlg, CDialog) //{{AFX_MSG_MAP(CPingerDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_CLEAR, OnClear) ON_EN_CHANGE(IDC_O1, OnChangeO1) ON_EN_CHANGE(IDC_O2, OnChangeO2) ON_EN_CHANGE(IDC_O3, OnChangeO3) ON_BN_CLICKED(IDC_RESOLVE, OnResolve) ON_BN_CLICKED(IDC_SCAN, OnScan) ON_BN_CLICKED(IDC_SAVE, OnSave) ON_BN_CLICKED(IDC_COPY, OnCopy) ON_WM_COMPAREITEM() ON_BN_CLICKED(IDC_ABOUT, OnAbout) //}}AFX_MSG_MAP ON_MESSAGE(WM_THREADSTARTING, OnStartup) ON_MESSAGE(WM_THREADDONE, OnDone) ON_MESSAGE(WM_THREADERROR, OnError) ON_MESSAGE(WM_THREADPING, OnPing) ON_MESSAGE(WM_THREADHOSTALIVE, OnHostAlive) ON_MESSAGE(WM_THREADLISTEN, OnListen) ON_MESSAGE(WM_THREADRESOLVED, OnResolved) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CPingerDlg message handlers BOOL CPingerDlg::OnInitDialog() { CDialog::OnInitDialog(); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here CEdit *ce; ce=(CEdit *)GetDlgItem(IDC_TIMEOUT); ce->SetWindowText("3000"); ce=(CEdit *)GetDlgItem(IDC_PASSES); ce->SetWindowText("2"); ce=(CEdit *)GetDlgItem(IDC_O4); ce->SetWindowText("1"); ce=(CEdit *)GetDlgItem(IDC_O8); ce->SetWindowText("254"); gRunning=0; gResolving=1; CButton *cb=(CButton *)GetDlgItem(IDC_RESOLVE); cb->SetCheck(1); srand(GetTickCount()); return TRUE; // return TRUE unless you set the focus to a control } void CPingerDlg::OnOK() { } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CPingerDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CPingerDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CPingerDlg::OnClear() { CListBox *list=(CListBox *)GetDlgItem(IDC_LIST); list->ResetContent(); } void CPingerDlg::OnChangeO1() { CString cstr; CEdit *pOct1=(CEdit *)GetDlgItem(IDC_O1); CEdit *pOct5=(CEdit *)GetDlgItem(IDC_O5); if (pOct1 && pOct5) { pOct1->GetWindowText(cstr); if (cstr) pOct5->SetWindowText(cstr); } } void CPingerDlg::OnChangeO2() { CString cstr; CEdit *pOct2=(CEdit *)GetDlgItem(IDC_O2); CEdit *pOct6=(CEdit *)GetDlgItem(IDC_O6); if (pOct2 && pOct6) { pOct2->GetWindowText(cstr); if (cstr) pOct6->SetWindowText(cstr); } } void CPingerDlg::OnChangeO3() { CString cstr; CEdit *pOct3=(CEdit *)GetDlgItem(IDC_O3); CEdit *pOct7=(CEdit *)GetDlgItem(IDC_O7); if (pOct3 && pOct7) { pOct3->GetWindowText(cstr); if (cstr) pOct7->SetWindowText(cstr); } } void CPingerDlg::OnResolve() { CButton *cb=(CButton *)GetDlgItem(IDC_RESOLVE); gResolving=cb->GetCheck(); } void CPingerDlg::OnScan() { struct ThreadArgs ta; CString o1,o2,o3,o4,o5,o6,o7,o8,passes,to,np,dl; if (gRunning==1) { gRunning=0; return; } CEdit *pFOct1=(CEdit *)GetDlgItem(IDC_O1); CEdit *pFOct2=(CEdit *)GetDlgItem(IDC_O2); CEdit *pFOct3=(CEdit *)GetDlgItem(IDC_O3); CEdit *pFOct4=(CEdit *)GetDlgItem(IDC_O4); CEdit *pTOct1=(CEdit *)GetDlgItem(IDC_O5); CEdit *pTOct2=(CEdit *)GetDlgItem(IDC_O6); CEdit *pTOct3=(CEdit *)GetDlgItem(IDC_O7); CEdit *pTOct4=(CEdit *)GetDlgItem(IDC_O8); pFOct1->GetWindowText(o1); pFOct2->GetWindowText(o2); pFOct3->GetWindowText(o3); pFOct4->GetWindowText(o4); pTOct1->GetWindowText(o5); pTOct2->GetWindowText(o6); pTOct3->GetWindowText(o7); pTOct4->GetWindowText(o8); CEdit *pTimeout=(CEdit *)GetDlgItem(IDC_TIMEOUT); CEdit *pPasses=(CEdit *)GetDlgItem(IDC_PASSES); pPasses->GetWindowText(passes); pTimeout->GetWindowText(to); ta.NumPasses=atoi(passes); ta.Timeout=atoi(to); ta.Delay=DELAY; char startIP[80],endIP[80]; sprintf(startIP,"%s.%s.%s.%s",o1.GetBuffer(3),o2.GetBuffer(3) ,o3.GetBuffer(3),o4.GetBuffer(3)); sprintf(endIP,"%s.%s.%s.%s",o5.GetBuffer(3),o6.GetBuffer(3) ,o7.GetBuffer(3),o8.GetBuffer(3)); ta.Start=sockeng::getaddr(startIP); if (ta.Start==-1) { CString msg("There is a problem with your starting IP."); MessageBox(msg,"Data Validation Error", MB_ICONEXCLAMATION); return; } ta.End=sockeng::getaddr(endIP); if (ta.End==-1) { CString msg("There is a problem with your ending IP."); MessageBox(msg,"Data Validation Error", MB_ICONEXCLAMATION); return; } if ((ntohl(ta.End))<(ntohl(ta.Start))) { CString msg("Your ending IP is lower than your starting IP."); MessageBox(msg,"Data Validation Error", MB_ICONEXCLAMATION); return; } CButton *cb=(CButton *)GetDlgItem(IDC_SCAN); cb->SetWindowText("Stop"); ta.win=GetSafeHwnd(); totalThreads=0; sem=0; CWinThread *pThread = AfxBeginThread(Scan, &ta, THREAD_PRIORITY_NORMAL); } void CPingerDlg::OnSave() { CFileDialog fileDialog(FALSE, "txt", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Text Files (*.txt)|*.txt|All Files (*.*)|*.*||"); if (fileDialog.DoModal() == IDOK) { CString filePathName=fileDialog.GetPathName(); CFile file; if (!file.Open(filePathName,CFile::modeCreate| CFile::modeWrite)) { CString msg("Can't Open "+ filePathName+ "\nCheck the filename."); MessageBox(msg,"File Save Error", MB_ICONEXCLAMATION); } else { char item[8192]; CString clip; CListBox *list=(CListBox *)GetDlgItem(IDC_LIST); for (int i=0;i<list->GetCount();i++) { list->GetText(i,item); clip=clip+item+"\n"; } file.Write(clip,strlen(clip)); file.Close(); } } } void CPingerDlg::OnCopy() { CBText t; char item[8192]; CString clip; CListBox *list=(CListBox *)GetDlgItem(IDC_LIST); for (int i=0;i<list->GetCount();i++) { list->GetText(i,item); clip=clip+item+"\n"; } t.SetText(clip); } void CPingerDlg::OnAbout() { HelpDialog ch; ch.DoModal(); }