text
stringlengths
8
6.88M
#include <iostream> #include <stdio.h> #include <algorithm> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int score[8]; int sort5[8]; int *index = new int[5]; for(int i=0; i<8; i++) { cin >> score[i]; sort5[i] = score[i]; } sort(sort5, sort5+8); int mid = sort5[2]; int cnt=0; int sum=0; for(int i=0; i<8; i++) { if (score[i] > mid) { index[cnt++] = i; sum += score[i]; } } cout <<sum << "\n"; for(int i=0; i<5; i++) { cout << index[i]+1 << " "; } }
/* * SPDX-FileCopyrightText: (C) 2013-2022 Daniel Nicoletti <dantti12@gmail.com> * SPDX-License-Identifier: BSD-3-Clause */ #ifndef CUTELYSTPLUGIN_H #define CUTELYSTPLUGIN_H #include <Cutelyst/cutelyst_global.h> #include <QtCore/qhash.h> #include <QtCore/qobject.h> #include <QtCore/qstring.h> namespace Cutelyst { class Application; class CUTELYST_LIBRARY Plugin : public QObject { Q_OBJECT public: /** * Constructs a new plugin object with the given Application parent. */ Plugin(Application *parent); /** * Reimplement this if you need to connect to * the signals emitted from Cutelyst::Application */ virtual bool setup(Application *app); }; } // namespace Cutelyst #endif // CUTELYSTPLUGIN_H
#include <boost/timer/timer.hpp> #include <seqan/index.h> #include <seqan/seq_io.h> #include <seqan/sequence.h> #include <fstream> #include <iostream> using namespace seqan; typedef StringSet< DnaString > string_set_t; typedef Index< string_set_t > index_t; typedef Iterator< index_t, TopDown<> >::Type top_down_t; typedef Iterator< index_t, TopDown< ParentLinks<> > >::Type top_down_history_t; StringSet< CharString > ids; string_set_t seqs; const unsigned numdescents = 5000; int read_seqs( const char * filename ) { // Open file and create RecordReader. std::fstream in( filename, std::ios::binary | std::ios::in ); RecordReader<std::fstream, SinglePass<> > reader( in ); // Read file in one pass. if( read2( ids, seqs, reader, Fasta() ) != 0 ) { return 1; // Could not read file. } return 0; } template< typename It > unsigned descendcopy( It it ) { unsigned n = 1; if( goDown( it ) ) { while( true ) { n += descendcopy( it ); if( ! goRight( it ) ) { break; } } } return n; } template< typename It > unsigned descendhistory( It & it ) { unsigned n = 1; if( goDown( it ) ) { while( true ) { n += descendhistory( it ); if( ! goRight( it ) ) { break; } } goUp( it ); } return n; } void timedescendcopy( index_t & index ) { unsigned n; std::cout << "Descend copy ... "; boost::timer::auto_cpu_timer t; for( unsigned i = 0; numdescents != i; ++i ) { n = descendcopy( top_down_t( index ) ); } std::cout << n << " "; } void timedescendhistory( index_t & index ) { unsigned n; std::cout << "Descend history... "; boost::timer::auto_cpu_timer t; for( unsigned i = 0; numdescents != i; ++i ) { top_down_history_t it( index ); n = descendhistory( it ); } std::cout << n << " "; } int main( int argc, char * argv[] ) { if (argc != 2) { std::cerr << "Wrong number of arguments.\n"; return 1; // Invalid number of arguments. } if( read_seqs( argv[ 1 ] ) ) { std::cerr << "Cannot read sequences\n"; return 1; } index_t index( seqs ); timedescendcopy( index ); timedescendhistory( index ); timedescendcopy( index ); return 0; }
#ifndef __CRange #define __CRange #include <vector> using namespace std; ///////////////////////////////////////////////////////////////////// // 关于范围的描述。 class CRange { public: float fFrom; // 起始处 float fTo; // 终止处 public: CRange(float _from, float _to) { fFrom = _from; fTo = _to; } CRange() { fFrom = 0; fTo = 0; } CRange& CRangeObject() { return *this; } // 判断此范围是否合法 bool IsValid() { return fFrom >= fTo; } // 判断此范围是否大于另一个 bool operator > (const CRange& another) { return (fFrom > another.fTo); } // 判断此范围是否小于另一个 bool operator < (const CRange& another) { return (fTo < another.fFrom); } // 判断一个数是否在该范围中 bool Contain(float f) const { return (f >= fFrom && f <= fTo); } // 判断此范围是否与另一个范围有重叠区 bool IsOverlap(const CRange& another) { if (*this > another || *this < another) return false; else return true; } // 尝试将两个范围进行合并 bool Merge(const CRange& another) { if (!IsOverlap(another)) return false; if (another.fFrom < fFrom) fFrom = another.fFrom; if (another.fTo > fTo) fTo = another.fTo; return true; } }; ///////////////////////////////////////////////////////////////////// // 定义“范围段的集合”。 class CRangeSet : public vector<CRange> { private: public: CRangeSet() {} // 直接按另一集合构造 CRangeSet(const CRangeSet& another); // 添加一个范围 void operator +=(const CRange& range); // 添加一个范围集合 void operator +=(const CRangeSet& another); // 实现集合与元素的加法 CRangeSet operator + (const CRange& range); // 实现集合与集合的加法 CRangeSet operator + (const CRangeSet& another); // 赋值 void operator = (const vector<CRange>& another); // 判断一个数是否在该范围集合中 bool Contain(float f) const; // 对一个“范围集合”进行标准化 void Normalize(); }; #endif
#include <TimeAlarms.h> #include <TimeLib.h> #include <Time.h> #include <SPI.h> #define MY_RADIO_NRF24 #define MY_NODE_ID 251 #define R1_VALUE_ID 1 #define R2_VALUE_ID 2 #define VOLTAGE_ID 3 #define VOLTAGE_SENSE_PIN A0 #define THRESHOLD_VOLTAGE_PIN A1 #define MOSFET_DRIVER_PIN 3 #include <MyNodes.h> #include <MySensors.h> #include <MyConfig.h> #define APPLICATION_NAME "Voltage Test" #define DEFAULT_R1_VALUE 10.00F #define DEFAULT_R2_VALUE 10.00F #define DEFAULT_VOLTS 0.00F AlarmId heartbeatTimer; AlarmId getVoltageTimer; AlarmId requestTimer; boolean sendR1Request; boolean sendR2Request; boolean resistorR1Received; boolean resistorR2Received; byte resistorR1RequestCount; byte resistorR2RequestCount; float voltsPerBit; float voltage; float resistorR1Value; float resistorR2Value; MyMessage voltageMessage(VOLTAGE_ID, V_VOLTAGE); void before() { pinMode(VOLTAGE_SENSE_PIN, INPUT); pinMode(THRESHOLD_VOLTAGE_PIN, INPUT); pinMode(MOSFET_DRIVER_PIN, OUTPUT); } void setup() { resistorR1Value = DEFAULT_R1_VALUE; resistorR2Value = DEFAULT_R2_VALUE; sendR1Request = true; sendR2Request = false; resistorR1Received = false; resistorR2Received = false; resistorR1RequestCount = 0; resistorR2RequestCount = 0; digitalWrite(MOSFET_DRIVER_PIN, LOW); voltage = 0; heartbeatTimer = Alarm.timerRepeat(HEARTBEAT_INTERVAL, sendHeartbeat); } void presentation() { sendSketchInfo(APPLICATION_NAME, getCodeVersion()); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); present(R1_VALUE_ID, S_CUSTOM, "R1 Value"); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); present(R2_VALUE_ID, S_CUSTOM, "R2 Value"); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); present(VOLTAGE_ID, S_MULTIMETER, "Voltage"); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); } void loop() { if (sendR1Request) { sendR1Request = false; request(R1_VALUE_ID, V_VAR1); requestTimer = Alarm.timerOnce(REQUEST_INTERVAL, checkR1RequestStatus); resistorR1RequestCount++; if (resistorR1RequestCount == 10) { MyMessage resistorR1ValueMessage(R1_VALUE_ID, V_VAR1); send(resistorR1ValueMessage.set(DEFAULT_R1_VALUE, 2)); wait(WAIT_AFTER_SEND_MESSAGE); } } if (sendR2Request) { sendR2Request = false; request(R2_VALUE_ID, V_VAR2); requestTimer = Alarm.timerOnce(REQUEST_INTERVAL, checkR2RequestStatus); resistorR2RequestCount++; if (resistorR2RequestCount == 10) { MyMessage resistorR2ValueMessage(R2_VALUE_ID, V_VAR2); send(resistorR2ValueMessage.set(DEFAULT_R2_VALUE, 2)); wait(WAIT_AFTER_SEND_MESSAGE); } } Alarm.delay(1); } void receive(const MyMessage &message) { switch (message.type) { case V_VAR1: resistorR1Value = message.getFloat(); if (!resistorR1Received) { resistorR1Received = true; Alarm.free(requestTimer); sendR1Request = false; request(R1_VALUE_ID, V_VAR1); sendR2Request = true; } break; case V_VAR2: resistorR2Value = message.getFloat(); if (!resistorR2Received) { resistorR2Received = true; Alarm.free(requestTimer); sendR2Request = false; request(R2_VALUE_ID, V_VAR2); getVoltageTimer = Alarm.timerRepeat(FIVE_MINUTES, getVoltage); } break; } } void getVoltage() { float sensedInputVoltage = 0; float thresholdVoltage = 0; digitalWrite(MOSFET_DRIVER_PIN, HIGH); for (byte readCount = 1; readCount <= 10; readCount++) { thresholdVoltage = thresholdVoltage + analogRead(THRESHOLD_VOLTAGE_PIN); wait(WAIT_50MS); sensedInputVoltage = sensedInputVoltage + analogRead(VOLTAGE_SENSE_PIN); wait(WAIT_50MS); } thresholdVoltage = thresholdVoltage / 10; thresholdVoltage = thresholdVoltage * 5.0 / 1024; voltsPerBit = ((thresholdVoltage * (resistorR1Value + resistorR2Value)) / (resistorR2Value * 1024)); sensedInputVoltage = sensedInputVoltage / 10; voltage = (sensedInputVoltage * voltsPerBit); send(voltageMessage.set(voltage, 5)); wait(WAIT_AFTER_SEND_MESSAGE); digitalWrite(MOSFET_DRIVER_PIN, LOW); } void checkR1RequestStatus() { if (!resistorR1Received) sendR1Request = true; } void checkR2RequestStatus() { if (!resistorR2Received) sendR2Request = true; }
// // Created by sun on 19-8-1. // #ifndef EX_7_15_PERSON_H #define EX_7_15_PERSON_H class person { private: string strname; string straddress; public: person()=default; person(const string &name, const string &add) { strname=name; straddress=add; } person(std::istream &is){is>>*this}; public: string getname() const { return strname}; string getaddd() const { return straddress}; }; #endif //EX_7_15_PERSON_H
#ifndef LINKED_LIST_EXAMPLE #define LINKED_LIST_EXAMPLE #include <iostream> #include <cstring> #include <exception> #include <fstream> #include <cassert> int size(const char *arr) { // if (*arr == '\0') -> return // -> 1 + size(++arr) int s = 0; if (arr == nullptr) return s; for (int i = 0; arr[i] != '\0'; ++i) { ++s; } return s; } class Contact { public: Contact(const char *_name = "", const char *_phone = "", Contact *_next = nullptr) : next(_next) { setName(_name); setPhone(_phone); } ~Contact() { destroy(); } Contact &operator=(const Contact &other) { if (this != &other) { destroy(); copy(other); } return *this; } Contact(const Contact &other) { copy(other); } void setName(const char *_name) { this->name = new (std::nothrow) char[size(_name) + 1]; if (this->name == nullptr) { throw std::bad_alloc(); } std::memcpy(this->name, _name, size(_name) + 1); } void setPhone(const char *_phone) { this->phone = new (std::nothrow) char[size(_phone) + 1]; if (this->phone == nullptr) { throw std::bad_alloc(); } std::memcpy(this->phone, _phone, size(_phone) + 1); } friend std::istream& operator>>(std::istream& in, Contact& element); friend std::ostream& operator<<(std::ostream& out, const Contact& element); public: Contact *next; private: char *name; char *phone; void copy(const Contact &other) { setName(other.name); setPhone(other.phone); } void destroy() { delete[] name; delete[] phone; // next = nullptr; } }; std::istream& operator>>(std::istream& in, Contact& element) { char from_file[128], from_file_2[128]; in >> from_file; std::cout << from_file <<std::endl; element.setName(from_file); in >> from_file_2; std::cout << from_file_2 <<std::endl; element.setPhone(from_file_2); return in; } class PhoneBook { public: PhoneBook(): head(nullptr), end(nullptr), size(0) {} PhoneBook(const PhoneBook &); PhoneBook &operator=(const PhoneBook &); ~PhoneBook() { if (size > 0) { Contact *temp = nullptr; while (size && head) { temp = head->next; delete head; head = temp; --size; } } } void push_front(Contact *new_node) { // Contact* temp = new (std::nothrow) Contact(new_node); // if (temp == nullptr) { // throw std::bad_alloc(); // } // temp->next = head; // head = temp; // ++size; new_node->next = head; head = new_node; ++size; } void push_front(const char *name, const char *phone) { Contact *new_node = new (std::nothrow) Contact(name, phone, head); if (new_node == nullptr) { throw std::bad_alloc(); } head = new_node; ++size; } void push_back(Contact *new_node) { std::cout << "Pushing..\n"; if (size == 0) { head = end = new_node; } else if (size == 1){ head->next = new_node; end = new_node; } else { end->next = new_node; end = new_node; } ++size; std::cout << "Pushed\n"; } void push_back(const char *name, const char *phone) { Contact *new_node = new (std::nothrow) Contact(name, phone); if (new_node == nullptr) { throw std::bad_alloc(); } push_back(new_node); // end->next = new_node; // end = new_node; // ++size; } void pop_front() { if (size > 0) { Contact *temp = head->next; delete head; head = temp; --size; } // Contact *temp = head; // head = head->next; // delete temp; } void pop_back() { if (size > 0) { Contact *temp = head; while (temp->next != end) { temp = temp->next; } delete end; // nullptr end = temp; end->next = nullptr; // optional --size; } } // insert // [] // at void read(const char* file_name) { assert(file_name != nullptr); std::ifstream in(file_name, std::ios::in); if (!in.good()) { throw std::invalid_argument("Could not open file!"); } while(!in.eof()) { Contact *new_node = new (std::nothrow) Contact(); in >> (*new_node); this->push_back(new_node); } } private: Contact *head, *end; size_t size; }; #endif
/* * Lab 3 * By: Daniel Speiser, Maria Shen, Mark Assad */ // library imports #include <Servo.h> // import servo library // global variable declarations and initializations Servo servo; // create servo object to control a servo int pwPin = 3; // declare pw pin 3 for sonar depth tracker int servoPin = 5; // declare pin 5 as servo pin int pos = 0; // keep track of servo position int startPos = 0; // initial start position int endPos = 0; // end position int increment = 0; // angle degree in which to increment servo bool isInput = false; // flag for detecting if input has been given float pulse, mm; // calculate and store pulse and mm of sonar // helper methods /* * The parseInput method reads and parses serial input for * servo rotation in the form of: int start, end, increment */ void parseInput() { isInput = true; // set flag to true startPos = Serial.parseInt(); // parse first int as start pos endPos = Serial.parseInt(); // parse second int as end pos increment = Serial.parseInt(); // parse third int as angle increment } /* * The readSensor method pulses the pw pin to high * in order to allow the sonar depth tracker to * read in and record an object's distance. */ void readSensor() { pulse = pulseIn(pwPin, HIGH); // set pw pin to high, record pulse mm = pulse; // mm is equal to pulse width delay(100); // delay 100ms for servo to reach position } /* * The printReadings method prints the recorded depth * readings to the console. TODO: Implement with GUI */ void printReadings() { Serial.print(mm); Serial.print(","); Serial.println(pos); } /* * the rotate method rotates the servo in the in the given * angle range (0-180 degrees), angle increment, and direction */ void rotate(int startPos, int endPos, int increment, boolean dir) { if (dir) // rotate if direction is forward // rotate servo from start position to end position, moving by given increment for (pos = startPos; pos <= endPos; pos += increment) readSonarAndRotateServo(pos); else // rotate backwards // rotate servo from end position to start position, moving by given increment for (pos = endPos; pos >= startPos; pos -= increment) readSonarAndRotateServo(pos); } /* * reads the sonar and rotates the servo together to accrue * distance readings along with the servo's rotation */ void readSonarAndRotateServo(int pos) { readSensor(); // call read sensor printReadings(); // display sensor readings servo.write(pos); // move servo to position pos delay(100); // delay 100ms for servo to reach position } // initial setup void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps pinMode(pwPin, INPUT); // set pw pin for sonar depth tracker as input servo.attach(servoPin); // attach servo to the servo pin declared above } // main loop void loop() { if (Serial.available()) // if input is available parseInput(); // call parse helper else if (isInput == true) { // if there is input, start rotating servo // rotate servo from start position to end position, moving by given increment rotate(startPos, endPos, increment, true); // call helper to rotate forward rotate(startPos, endPos, increment, false); // call helper to rotate backward } }
//----------------------------------------------------------------------------- // Perimeter Map Compiler // Copyright (c) 2005, Don Reba // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // • Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // • Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // • Neither the name of Don Reba nor the names of his contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- #include "StdAfx.h" #include "about wnd.h" #include "resource.h" #include "resource management.h" #include "task common.h" #include "gaussian blur.ipp" #include <cmath> #include <fstream> //--------------------- // About implementation //--------------------- About::About() :painting_(false) ,current_bk_colour_(0) ,lightmap_lookup_(ComputeLightmapLookup()) { // set initial mouse coordinate records cursor_pos_.x = cursor_pos_.y = 0; // initialise the background colours bk_colours_[0] = 0x00007FFF; bk_colours_[1] = 0x00FFFFFF; bk_colours_[2] = 0x00A56E3A; // initialise the painting brush probabilites for (size_t r(0); r != brush_size_; ++r) for (size_t c(0); c != brush_size_; ++c) { const float x(r - brush_size_ / 2.0f); const float y(c - brush_size_ / 2.0f); float radius = sqrt(x*x + y*y); brush_[r][c] = radius / brush_size_ * 2; } } About::~About() { delete [] lightmap_lookup_; } INT_PTR About::DoModal(HWND parent_wnd) { HINSTANCE hinstance(GetModuleHandle(NULL)); // register window class WNDCLASSEX window_class = { sizeof(window_class) }; { window_class.lpfnWndProc = WndProc<About>; window_class.hInstance = hinstance; window_class.hIcon = LoadIcon(hinstance, (LPCTSTR)IDI_COMPILER); window_class.hCursor = LoadCursor(NULL, IDC_ARROW); window_class.lpszClassName = _T("EnhancedAboutDialog"); window_class.hIconSm = LoadIcon(hinstance, (LPCTSTR)IDI_COMPILER); RegisterClassEx(&window_class); } // create window CreateWindow( window_class.lpszClassName, _T("About Perimeter Map Compiler"), WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, parent_wnd, NULL, hinstance, this); if (NULL == hwnd_) return IDCANCEL; // disable the parent bool parent_was_enabled(EnableWindow(parent_wnd, FALSE) == FALSE); // enter the message loop MSG msg = {}; quitting_ = false; while (!quitting_ && GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } if (parent_was_enabled) { EnableWindow(parent_wnd, TRUE); SetFocus(parent_wnd); } DestroyWindow(hwnd_); if (WM_QUIT == msg.message) PostQuitMessage(static_cast<int>(msg.wParam)); return IDOK; } void About::OnCaptureChanged(Msg<WM_CAPTURECHANGED> &msg) { painting_ = false; msg.result_ = FALSE; msg.handled_ = true; } void About::OnClose(Msg<WM_CLOSE> &msg) { Destroy(); } void About::OnCreate(Msg<WM_CREATE> &msg) { msg.result_ = FALSE; msg.handled_ = true; // load evmp uint width, height; { const size_t evmp_alloc(0x200000); // 2MB should be enough vector<BYTE> evmp(evmp_alloc); if (!RsrcMgmt::UncompressResource(IDR_EVMP, &evmp[0], evmp_alloc)) { MacroDisplayError(_T("EVMP could not be loaded.")); return; } width = *ri_cast<uint*>(&evmp[0]); height = *ri_cast<uint*>(&evmp[4]); bmp_size_.cx = width; bmp_size_.cy = height; map_size_.cx = width + 1; map_size_.cy = height; map_.resize(map_size_.cx * map_size_.cy); CopyMemory(&map_[0], &evmp[8], map_.size() * sizeof(MapPixel)); // initialize the temporary buffer temp_dim_.cx = bmp_size_.cx + 2 * border_; temp_dim_.cy = map_size_.cy + 2 * border_; temp_buffer_.resize(temp_dim_.cx * temp_dim_.cy); } // initialise the background bitmap { RECT client_rect; GetClientRect(hwnd_, &client_rect); HDC client_dc(GetDC(hwnd_)); bk_dc_ = CreateCompatibleDC(client_dc); bk_bmp_ = CreateCompatibleBitmap( client_dc, client_rect.right - client_rect.left, client_rect.bottom - client_rect.top); ReleaseDC(hwnd_, client_dc); SelectObject(bk_dc_, bk_bmp_); RenderLines(0, map_size_.cy); } // resize window (centre on the same monitor as the parent) { RECT rect = { 0, 0, width, height }; AdjustWindowRect(&rect, GetWindowLong(hwnd_, GWL_STYLE), FALSE); HMONITOR monitor(MonitorFromWindow(GetParent(hwnd_), MONITOR_DEFAULTTONEAREST)); MONITORINFO info = { sizeof(info) }; if (!GetMonitorInfo(monitor, &info)) { MacroDisplayError(_T("Monitor information could not be querried.")); return; } SIZE win_size = { rect.right - rect.left, rect.bottom - rect.top }; RECT &mon_rect(info.rcMonitor); SetWindowPos( hwnd_, NULL, mon_rect.left + ((mon_rect.right - mon_rect.left) - win_size.cx) / 2, mon_rect.top + ((mon_rect.bottom - mon_rect.top) - win_size.cy) / 2, win_size.cx, win_size.cy, SWP_SHOWWINDOW | SWP_NOZORDER); } // set timers SetTimer(hwnd_, TMR_CHANGE_BK, 10000, NULL); SetTimer(hwnd_, TMR_DRAW_STROKE, 128, NULL); msg.result_ = TRUE; msg.handled_ = true; } void About::OnDestroy(Msg<WM_DESTROY> &msg) { // destroy the background dc DeleteDC(bk_dc_); DeleteObject(bk_bmp_); } void About::OnEraseBkgnd(Msg<WM_ERASEBKGND> &msg) { // draw background RECT client_rect; GetClientRect(hwnd_, &client_rect); BitBlt( msg.DC(), 0, 0, client_rect.right - client_rect.left, client_rect.bottom - client_rect.top, bk_dc_, 0, 0, SRCCOPY); msg.handled_ = true; } void About::OnKeyDown(Msg<WM_KEYDOWN> &msg) { switch (msg.VKey()) { case VK_RETURN: case VK_ESCAPE: case VK_SPACE: Destroy(); break; } } void About::OnLButtonDown(Msg<WM_LBUTTONDOWN> &msg) { cursor_pos_.x = msg.Position().x; cursor_pos_.y = msg.Position().y; if ( cursor_pos_.x > 0 && cursor_pos_.x < bmp_size_.cx && cursor_pos_.y > 0 && cursor_pos_.y < bmp_size_.cy && !(map_[cursor_pos_.y * map_size_.cx + cursor_pos_.x].flags & MapPixel::F_OK)) Destroy(); SetCapture(hwnd_); painting_ = true; msg.result_ = FALSE; msg.handled_ = true; } void About::OnLButtonUp(Msg<WM_LBUTTONUP> &msg) { painting_ = false; ReleaseCapture(); msg.result_ = FALSE; msg.handled_ = true; } void About::OnMouseMove(Msg<WM_MOUSEMOVE> &msg) { cursor_pos_.x = msg.Position().x; cursor_pos_.y = msg.Position().y; msg.result_ = FALSE; msg.handled_ = true; } void About::OnSetCursor(Msg<WM_SETCURSOR> &msg) { if (msg.Hwnd() != hwnd_) return; // set cursor to hand in client area, but to normal elsewhere RECT client_rect; POINT cursor_pos; GetClientRect(hwnd_, &client_rect); ClientToScreen(hwnd_, &client_rect); GetCursorPos(&cursor_pos); if ( TRUE == PtInRect(&client_rect, cursor_pos) && cursor_pos_.x > 0 && cursor_pos_.x < bmp_size_.cx && cursor_pos_.y > 0 && cursor_pos_.y < bmp_size_.cy && map_[cursor_pos_.y * map_size_.cx + cursor_pos_.x].flags & MapPixel::F_OK) { SetCursor(LoadCursor(NULL, IDC_HAND)); } else SetCursor(LoadCursor(NULL, IDC_ARROW)); msg.result_ = TRUE; msg.handled_ = true; } void About::OnTimer(Msg<WM_TIMER> &msg) { switch (msg.TimerId()) { case TMR_CHANGE_BK: ChangeBackground(); break; case TMR_DRAW_STROKE: DrawStroke(); break; }; } void About::ProcessMessage(WndMsg &msg) { static Handler mmp[] = { &About::OnCaptureChanged, &About::OnClose, &About::OnCreate, &About::OnDestroy, &About::OnEraseBkgnd, &About::OnKeyDown, &About::OnLButtonDown, &About::OnLButtonUp, &About::OnMouseMove, &About::OnSetCursor, &About::OnTimer }; if (!Handler::Call(mmp, this, msg)) __super::ProcessMessage(msg); } void About::ChangeBackground() { current_bk_colour_ = (current_bk_colour_ + 1) % num_bk_colours_; } const BYTE *About::ComputeLightmapLookup() { BYTE *lightmap_lookup(new BYTE[0x1FF]); float normal_dy(1.0f); float light_dx (1.0f / static_cast<float>(sqrt(2.0f))); float light_dy (1.0f / static_cast<float>(sqrt(2.0f))); for (int i(0); i != 0x1FF; ++i) { float normal_dx(-static_cast<float>(i - 0xFF)); // calculate and store the cosine of the angle between the vectors float normal_l(sqrt(normal_dx * normal_dx + normal_dy * normal_dy)); float cos_a((normal_dx * light_dx + normal_dy * light_dy) / normal_l); lightmap_lookup[i] = static_cast<BYTE>(0xFF * abs(cos_a)); } return lightmap_lookup; } void About::DrawStroke() { if (!painting_) return; // return if the brush does not touch the canvas if ( cursor_pos_.x + static_cast<int>(brush_size_/2) < 0 || cursor_pos_.y + static_cast<int>(brush_size_/2) < 0 || cursor_pos_.x - static_cast<int>(brush_size_/2) >= bmp_size_.cx || cursor_pos_.y - static_cast<int>(brush_size_/2) >= bmp_size_.cy) return; // seed random number generator srand(clock()); // calculate the border around the painting region _ASSERTE(0 == brush_size_ % 2); const int radius(brush_size_ / 2); RECT offset; offset.left = cursor_pos_.x - radius; offset.top = cursor_pos_.y - radius; offset.right = map_size_.cx - offset.left - brush_size_; offset.bottom = map_size_.cy - offset.top - brush_size_; // draw a stroke MapType::iterator map_iter(map_.begin() + map_size_.cx * offset.top); for (int r(0); r != brush_size_; ++r) { if (0 <= offset.top + r && offset.top + r < bmp_size_.cy) { map_iter += offset.left; for (int c(0); c != brush_size_; ++c) { if (0 <= offset.left + c && offset.left + c < bmp_size_.cx) { float p(static_cast<float>(rand())); p /= RAND_MAX; if (p > brush_[r][c] && map_iter->flags & MapPixel::F_SOFT) if (current_bk_colour_ < 3) map_iter->top_texture = bk_colours_[current_bk_colour_]; else map_iter->heightmap = static_cast<uint>(__max(0, static_cast<int>(map_iter->heightmap) - 3)); } ++map_iter; } map_iter += offset.right; } else map_iter += map_size_.cx; } { uint overlap(0); if (offset.top < 0) overlap += -offset.top; if (offset.top + static_cast<int>(brush_size_) >= bmp_size_.cy) overlap += offset.top + brush_size_ - bmp_size_.cy + 1; const uint first_line(__max(0, offset.top)); const uint line_count(brush_size_ - overlap); RenderLines(first_line, line_count); } InvalidateRect(hwnd_, NULL, TRUE); } void About::Destroy() { quitting_ = true; } void About::RenderLines(uint first_line, uint line_count) { // calculate adjusted first_line and line_count, for borders const uint first_line_e(__max(0, static_cast<int>(first_line) - border_)); const uint temp_offset (border_ + first_line_e - first_line); const uint line_count_e(__min( line_count + border_ * 2 - temp_offset, line_count - (first_line_e + line_count - bmp_size_.cy))); // calculate the lightmap { TempType::iterator temp_iter(temp_buffer_.begin() + temp_dim_.cx * temp_offset); MapType::const_iterator map_iter (map_.begin() + map_size_.cx * first_line_e); MapType::const_iterator row_iter; MapType::const_iterator peak_x; uint peak_y; for (uint y(0); y != line_count_e; ++y) { row_iter = map_iter + bmp_size_.cx; // end of the row peak_x = row_iter; // location of the nearest peak peak_y = row_iter->heightmap; // height of the nearest peak temp_iter += bmp_size_.cx + border_; // move to the end of the row while (row_iter != map_iter) { --temp_iter; --row_iter; _ASSERTE(temp_iter - temp_buffer_.begin() < static_cast<ptrdiff_t>(temp_buffer_.size())); const uint dx(&*peak_x - &*row_iter); // distance to the peak const uint y (row_iter->heightmap); // current height // if the point is unshadowed, dot surface slope with the sun, othewise set to zero // the sun vector is presumed to be (1,1) if (peak_y < y || peak_y - y < dx * 2) // shadows are shortened twofold { // carry out the projection table lookup const int dy(row_iter[1].heightmap - static_cast<int>(y)); *temp_iter = lightmap_lookup_[dy + 0xFF]; // shift the highest point to this one peak_y = y; peak_x = row_iter; } else *temp_iter = 0x00; // shadow lightness } temp_iter += temp_dim_.cx - border_; map_iter += map_size_.cx; } } // blur the buffer GaussianBlur<BYTE, ushort>(&temp_buffer_[0], temp_dim_); // merge the buffer with the bitmap { TempType::const_iterator temp_iter(temp_buffer_.begin() + temp_dim_.cx * border_); MapType::const_iterator map_iter (map_.begin() + map_size_.cx * first_line); for (uint y(first_line); y != first_line + line_count; ++y) { temp_iter += border_; for (LONG x(0); x != bmp_size_.cx; ++x) { // determine the texture colour const COLORREF colour(map_iter->heightmap ? map_iter->top_texture : map_iter->bottom_texture); // compute the lighting ratio * 0x100 const uint factor(0x101); // precision (odd to avoid bit shifts) const uint i_light(((*temp_iter + 0x80) * factor) / 0xFF); SetPixelV(bk_dc_, x, y, RGB( __min(0xFF, (GetRValue(colour) * i_light) / factor), __min(0xFF, (GetGValue(colour) * i_light) / factor), __min(0xFF, (GetBValue(colour) * i_light) / factor))); ++temp_iter; ++map_iter; } temp_iter += border_; ++map_iter; } } }
//Call centre program (Call class header) - Christopher Haynes - 10748982 #ifndef CALL_H //Used to clarify that this header file should only be used #define CALL_H //once when the linker is compling the program class Call //Defenition of the class Call { private: //Private variables and functions are not accessable from outside the class int active; //Marks whether a call exists, 0 - no call, 1 - active call int callNum; //The global call number for this call int queueID; //The current queue position for this call DWORD startTime; //The tick count from when the call first entered the queue float holdTime; //The total time in seconds the call has been in the queue public: //Public variables and functions are accessable from outside the class void Init(int, int); //Initialises the call with the required values void Clear(); //Marks a call inactive and resets data values int GetActive() { return active; }; //Getter for "active" int GetCallNum() { return callNum; }; //Getter for "callNum" int GetID() { return queueID; }; //Getter for "queueID" float GetHoldTime() { return holdTime; } //Getter for "holdTime" void AdvancePosition(); //Advance the calls queue position by 1 void UpdateCallTime(); //Update call time based on current tick count }; #endif
#include "settingdialog.h" #include "ui_settingdialog.h" SettingDialog::SettingDialog(QWidget *parent, int frameNum, QImage imgLeft, QImage imgRight, QSize size) : QDialog(parent), ui(new Ui::SettingDialog) { ui->setupUi(this); qApp->installEventFilter(this); this->frameNumber = frameNum; this->imgLeft = imgLeft; if(this->frameNumber == 2) this->imgRight = imgRight; this->pointNum = 0; this->imageNum = 0; this->ui->graphicsView->resize(size); this->ui->constLblPoint->setText("Left Upper Corner"); this->width = size.width(); this->height = size.height(); QGraphicsScene *scene = new QGraphicsScene; scene->addPixmap(QPixmap::fromImage(imgLeft)); this->ui->graphicsView->setScene(scene); this->ui->graphicsView->update(); } SettingDialog::~SettingDialog() { delete ui; } int SettingDialog::getWidth() { return this->width; } int SettingDialog::getHeight() { return this->height; } Point2f *SettingDialog::getSrcPtLeft() { return this->srcPtLeft; } Point2f *SettingDialog::getSrcPtRight() { if(this->frameNumber == 1) return NULL; return this->srcPtRight; } bool SettingDialog::eventFilter(QObject *obj, QEvent *event) { if(obj != this) return false; if(obj == this->ui->btnCancel || obj == this->ui->btnOk || obj == this->ui->constLblPoint || obj == this->ui->txtPoint) return false; if(event->type() == QEvent::MouseButtonPress) { QMouseEvent *mEvent = static_cast<QMouseEvent*>(event); if(mEvent->x() < 10 || mEvent->y() < 10) return false; if(mEvent->x() > this->width + 10 || mEvent->y() > this->height + 10) return false; this->ui->txtPoint->setText(QString::number(mEvent->x() - this->ui->graphicsView->x()) + ", " + QString::number(mEvent->y() - this->ui->graphicsView->y())); return true; } return false; } void SettingDialog::setPointImage() { Point2f currPt = Point2f(this->ui->txtPoint->text().split(",")[0].toInt(), this->ui->txtPoint->text().split(",")[1].toInt()); switch (this->pointNum) { case 0: if(this->imageNum == 0) this->srcPtLeft[0] = currPt; else this->srcPtRight[0] = currPt; this->ui->constLblPoint->setText("Left Lower Corner"); break; case 1: if(this->imageNum == 0) this->srcPtLeft[1] = currPt; else this->srcPtRight[1] = currPt; this->ui->constLblPoint->setText("Right Lower Corner"); break; case 2: if(this->imageNum == 0) this->srcPtLeft[2] = currPt; else this->srcPtRight[2] = currPt; this->ui->constLblPoint->setText("Right Upper Corner"); break; case 3: if(this->imageNum == 0) { this->srcPtLeft[3] = currPt; if(this->frameNumber == 1) break; this->imageNum = 1; this->pointNum = -1; QGraphicsScene *scene = new QGraphicsScene; scene->addPixmap(QPixmap::fromImage(this->imgRight)); this->ui->graphicsView->setScene(scene); this->ui->graphicsView->update(); this->ui->constLblPoint->setText("Left Upper Corner"); } else this->srcPtRight[3] = currPt; break; default: break; } } void SettingDialog::on_btnOk_clicked() { // if(true) if(this->frameNumber == 2 && this->imageNum == 1 && this->pointNum == 3 || this->frameNumber == 1 && this->pointNum == 3) { // if(false) if(!(this->validate())) { QMessageBox::warning(this, tr("Warning!"), tr("Please retry to input corner!"), QMessageBox::Ok); return; } this->setPointImage(); this->accept(); return; } if(this->ui->txtPoint->text() == "") return; this->setPointImage(); this->pointNum++; } void SettingDialog::on_btnCancel_clicked() { this->setResult(QDialog::Rejected); this->close(); } bool SettingDialog::validate() { return true; }
#include "Mutex.h" #include <cassert> // ThisThread::tid #include "ThisThread.h" USE_NAMESPACE Mutex::Mutex() : mutex_(), holder_(0) { pthread_mutex_init(&mutex_, nullptr); } Mutex::~Mutex() { // assert(holder_ == 0); pthread_mutex_destroy(&mutex_); } bool Mutex::isLockedByThisThread() const { return holder_ == ThisThread::tid(); } void Mutex::assertLocked() const { assert(isLockedByThisThread()); } void Mutex::lock() { pthread_mutex_lock(&mutex_); // holder_ = ThisThread::tid(); } void Mutex::unlock() { pthread_mutex_unlock(&mutex_); // holder_ = 0; } pthread_mutex_t* Mutex::getPthreadMutex() { return &mutex_; } LockGuard::LockGuard(Mutex& lock) : lock_(lock) { lock.lock(); } LockGuard::~LockGuard() { lock_.unlock(); }
// // LoadingScene.cpp // demo_ddz // // Created by 谢小凡 on 2018/2/8. // #include "LoadingScene.hpp" #include "RoomData.hpp" #include "FirstScene.hpp" using namespace cocos2d; Scene* LoadingScene::createScene() { return LoadingScene::create(); } LoadingScene::~LoadingScene() { RoomDataManager::destroyInstance(); } bool LoadingScene::init() { if (!Scene::init()) return false; // backgroud Sprite* bg = Sprite::create("image/loading_bg.jpg"); this->addChild(bg); bg->setNormalizedPosition(Vec2::ANCHOR_MIDDLE); // loading texture SpriteFrameCache::getInstance()->addSpriteFramesWithFile("res/res_card.plist"); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("res/res_optpanel.plist"); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("res/res_roomentry.plist"); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("res/res_seatandinfobar.plist"); // create data single instance RoomDataManager::getInstance(); return true; } void LoadingScene::onEnter() { Scene::onEnter(); Director::getInstance()->pushScene(FirstScene::createScene()); }
/* tools/mkbootimg/mkbootimg.c ** ** Copyright 2007, The Android Open Source Project ** ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <stdbool.h> #include "mincrypt/sha.h" #include "mkbootimg.h" const char *mtk_names[] = { "", "KERNEL", "ROOTFS" }; static void *load_file(const char *fn, unsigned *_sz, enum mtk_type type) { char *data; int sz; int fd; int datasz; int needs_mtkheader = 0; int offset = 0; data = 0; fd = open(fn, O_RDONLY); if(fd < 0) return 0; sz = datasz = lseek(fd, 0, SEEK_END); if(sz < 0) goto oops; if(lseek(fd, 0, SEEK_SET) != 0) goto oops; // add mtk_type if(type != MTK_NONE) { printf("Type is %d\n", type); unsigned int magic; if(read(fd, &magic, 4) == 4 && magic != MTK_MAGIC) { printf("No MTK Header, making one...\n"); needs_mtkheader = 1; sz += sizeof(mtk_header); offset = sizeof(mtk_header); printf("old sz=%d, new sz=%d, offset=%d\n", datasz, sz, offset); } if(lseek(fd, 0, SEEK_SET) != 0) goto oops; } // add end data = (char*) malloc(sz); if(data == 0) { printf( "1\n" ); goto oops; } if(read(fd, &data[offset], datasz) != datasz) { printf( "[-]read fail %d\n", datasz ); goto oops; } close(fd); // add if(needs_mtkheader) { printf("Generating mtk header\n"); mtk_header* hdr = (mtk_header*)data; memset(hdr->padding, 0xFF, sizeof(mtk_header)); hdr->info.magic = MTK_MAGIC; hdr->info.size = datasz; memset(hdr->info.name, 0, sizeof(hdr->info.name)); strcpy(hdr->info.name, mtk_names[type]); } // add end if(_sz) *_sz = sz; return data; oops: close(fd); if(data != 0) free(data); return 0; } int newrepackbootimg_usage(void) { fprintf(stderr,"usage: mkbootimg\n" " --kernel <filename>\n" " [ --ramdisk <filename> ]\n" " [ --second <2ndbootloader-filename> ]\n" " [ --cmdline <kernel-commandline> ]\n" " [ --board <boardname> ]\n" " [ --base <address> ]\n" " [ --pagesize <pagesize> ]\n" " [ --dt <filename> ]\n" " [ --kernel_offset <base offset> ]\n" " [ --ramdisk_offset <base offset> ]\n" " [ --second_offset <base offset> ]\n" " [ --tags_offset <base offset> ]\n" " [ --id ]\n" " [ --mtk 1 ]\n" " -o|--output <filename>\n" ); return 1; } static unsigned char padding[131072] = { 0, }; static void print_id(const uint8_t *id, size_t id_len) { printf("0x"); unsigned i = 0; for (i = 0; i < id_len; i++) { printf("%02x", id[i]); } printf("\n"); } int write_padding(int fd, unsigned pagesize, unsigned itemsize) { unsigned pagemask = pagesize - 1; ssize_t count; if((itemsize & pagemask) == 0) { return 0; } count = pagesize - (itemsize & pagemask); if(write(fd, padding, count) != count) { return -1; } else { return 0; } } int main(int argc, char **argv) { boot_img_hdr hdr; char *kernel_fn = NULL; void *kernel_data = NULL; char *ramdisk_fn = NULL; void *ramdisk_data = NULL; char *second_fn = NULL; void *second_data = NULL; char *cmdline = ""; char *bootimg = NULL; char *board = ""; char *dt_fn = NULL; void *dt_data = NULL; uint32_t pagesize = 2048; int repack_mtk = 0; enum mtk_type re_mtk_type = MTK_NONE; int fd; SHA_CTX ctx; const uint8_t* sha; uint32_t base = 0x10000000U; uint32_t kernel_offset = 0x00008000U; uint32_t ramdisk_offset = 0x01000000U; uint32_t second_offset = 0x00f00000U; uint32_t tags_offset = 0x00000100U; size_t cmdlen; argc--; argv++; memset(&hdr, 0, sizeof(hdr)); bool get_id = false; while(argc > 0){ char *arg = argv[0]; if (!strcmp(arg, "--id")) { get_id = true; argc -= 1; argv += 1; } else if(argc >= 2) { char *val = argv[1]; argc -= 2; argv += 2; if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) { bootimg = val; } else if(!strcmp(arg, "--kernel")) { kernel_fn = val; } else if(!strcmp(arg, "--ramdisk")) { ramdisk_fn = val; } else if(!strcmp(arg, "--second")) { second_fn = val; } else if(!strcmp(arg, "--cmdline")) { cmdline = val; } else if(!strcmp(arg, "--base")) { base = strtoul(val, 0, 16); } else if(!strcmp(arg, "--kernel_offset")) { kernel_offset = strtoul(val, 0, 16); } else if(!strcmp(arg, "--ramdisk_offset")) { ramdisk_offset = strtoul(val, 0, 16); } else if(!strcmp(arg, "--second_offset")) { second_offset = strtoul(val, 0, 16); } else if(!strcmp(arg, "--tags_offset")) { tags_offset = strtoul(val, 0, 16); } else if(!strcmp(arg, "--board")) { board = val; } else if(!strcmp(arg,"--pagesize")) { pagesize = strtoul(val, 0, 10); if ((pagesize != 2048) && (pagesize != 4096) && (pagesize != 8192) && (pagesize != 16384) && (pagesize != 32768) && (pagesize != 65536) && (pagesize != 131072)) { fprintf(stderr,"error: unsupported page size %d\n", pagesize); return -1; } } else if(!strcmp(arg, "--dt")) { dt_fn = val; } else if ( !strcmp(arg, "--mtk")) { repack_mtk = 1; } else { return newrepackbootimg_usage(); } } else { return newrepackbootimg_usage(); } } hdr.page_size = pagesize; hdr.kernel_addr = base + kernel_offset; hdr.ramdisk_addr = base + ramdisk_offset; hdr.second_addr = base + second_offset; hdr.tags_addr = base + tags_offset; if(bootimg == 0) { fprintf(stderr,"error: no output filename specified\n"); return newrepackbootimg_usage(); } if(kernel_fn == 0) { fprintf(stderr,"error: no kernel image specified\n"); return newrepackbootimg_usage(); } if(strlen(board) >= BOOT_NAME_SIZE) { fprintf(stderr,"error: board name too large\n"); return newrepackbootimg_usage(); } strcpy((char *) hdr.name, board); memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE); cmdlen = strlen(cmdline); if(cmdlen > (BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE - 2)) { fprintf(stderr,"error: kernel commandline too large\n"); return 1; } /* Even if we need to use the supplemental field, ensure we * are still NULL-terminated */ strncpy((char *)hdr.cmdline, cmdline, BOOT_ARGS_SIZE - 1); hdr.cmdline[BOOT_ARGS_SIZE - 1] = '\0'; if (cmdlen >= (BOOT_ARGS_SIZE - 1)) { cmdline += (BOOT_ARGS_SIZE - 1); strncpy((char *)hdr.extra_cmdline, cmdline, BOOT_EXTRA_ARGS_SIZE); } re_mtk_type = repack_mtk ? MTK_KERNEL: MTK_NONE; kernel_data = load_file(kernel_fn, &hdr.kernel_size, re_mtk_type); if(kernel_data == 0) { fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn); return 1; } if(ramdisk_fn == 0) { ramdisk_data = 0; hdr.ramdisk_size = 0; } else { re_mtk_type = repack_mtk ? MTK_ROOTFS : MTK_NONE; ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size,re_mtk_type); if(ramdisk_data == 0) { fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn); return 1; } } if(second_fn) { second_data = load_file(second_fn, &hdr.second_size, MTK_NONE); if(second_data == 0) { fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn); return 1; } } if(dt_fn) { dt_data = load_file(dt_fn, &hdr.dt_size, MTK_NONE); if (dt_data == 0) { fprintf(stderr,"error: could not load device tree image '%s'\n", dt_fn); return 1; } } /* put a hash of the contents in the header so boot images can be * differentiated based on their first 2k. */ SHA_init(&ctx); SHA_update(&ctx, kernel_data, hdr.kernel_size); SHA_update(&ctx, &hdr.kernel_size, sizeof(hdr.kernel_size)); SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size); SHA_update(&ctx, &hdr.ramdisk_size, sizeof(hdr.ramdisk_size)); SHA_update(&ctx, second_data, hdr.second_size); SHA_update(&ctx, &hdr.second_size, sizeof(hdr.second_size)); if(dt_data) { SHA_update(&ctx, dt_data, hdr.dt_size); SHA_update(&ctx, &hdr.dt_size, sizeof(hdr.dt_size)); } sha = SHA_final(&ctx); memcpy(hdr.id, sha, SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE); fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644); if(fd < 0) { fprintf(stderr,"error: could not create '%s'\n", bootimg); return 1; } if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail; if(write_padding(fd, pagesize, sizeof(hdr))) goto fail; if(write(fd, kernel_data, hdr.kernel_size) != (ssize_t) hdr.kernel_size) goto fail; if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail; if(write(fd, ramdisk_data, hdr.ramdisk_size) != (ssize_t) hdr.ramdisk_size) goto fail; if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail; if(second_data) { if(write(fd, second_data, hdr.second_size) != (ssize_t) hdr.second_size) goto fail; if(write_padding(fd, pagesize, hdr.second_size)) goto fail; } if(dt_data) { if(write(fd, dt_data, hdr.dt_size) != (ssize_t) hdr.dt_size) goto fail; if(write_padding(fd, pagesize, hdr.dt_size)) goto fail; } if (get_id) { print_id((uint8_t *) hdr.id, sizeof(hdr.id)); } return 0; fail: unlink(bootimg); close(fd); fprintf(stderr,"error: failed writing '%s': %s\n", bootimg, strerror(errno)); return 1; }
#ifndef BSCHEDULER_API_HH #define BSCHEDULER_API_HH #include <bscheduler/config.hh> #include <bscheduler/ppl/basic_factory.hh> namespace bsc { typedef BSCHEDULER_KERNEL_TYPE kernel; enum Target { Local, Remote, Child }; template <Target t=Target::Local> inline void send(kernel* k) { factory.send(k); } template <> inline void send<Local>(kernel* k) { factory.send(k); } template <> inline void send<Remote>(kernel* k) { factory.send_remote(k); } template<Target target=Target::Local> void upstream(kernel* lhs, kernel* rhs) { rhs->parent(lhs); send<target>(rhs); } template<Target target=Target::Local> void commit(kernel* rhs, exit_code ret) { if (!rhs->parent()) { delete rhs; bsc::graceful_shutdown(static_cast<int>(ret)); } else { rhs->return_to_parent(ret); send<target>(rhs); } } template<Target target=Target::Local> void commit(kernel* rhs) { exit_code ret = rhs->return_code(); commit<target>( rhs, ret == exit_code::undefined ? exit_code::success : ret ); } template<Target target=Target::Local> void send(kernel* lhs, kernel* rhs) { lhs->principal(rhs); send<target>(lhs); } struct factory_guard { inline factory_guard() { ::bsc::factory.start(); } inline ~factory_guard() { ::bsc::factory.stop(); ::bsc::factory.wait(); } }; template<class Pipeline> void upstream(Pipeline& ppl, kernel* lhs, kernel* rhs) { rhs->parent(lhs); ppl.send(rhs); } } #endif // vim:filetype=cpp
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #include <flux/Singleton> #include <flux/File> #include <flux/stdio> namespace flux { template<int fd> class StdIo: public Object, public Singleton< StdIo<fd> > { public: StdIo(): stream_(SystemStream::create(fd)) {} Ref<SystemStream> stream_; }; SystemStream *stdIn() { return StdIo<File::StandardInput>::instance()->stream_; } SystemStream *stdOut() { return StdIo<File::StandardOutput>::instance()->stream_; } SystemStream *stdErr() { return StdIo<File::StandardError>::instance()->stream_; } } // namespace flux
#include <cstdio> #include <cstring> // 大数,10进制到2进制,这里还不知道大数除法所以是硬模拟写出来的,但思路是一样的 int main() { char t[32]; while (scanf("%s", t) != EOF) { int o[128] = {}; int i = 0; int cnt = 0; do { o[i++] = (t[strlen(t) - 1] - '0') % 2; for (int j = 0; j < strlen(t); j++) { if (t[j] % 2 && j != strlen(t) - 1) t[j + 1] += 10; t[j] = (t[j] - '0') / 2 + '0'; } cnt = 0; for (int j = 0; j < strlen(t); j++) { if (t[j] == '0') cnt++; } } while (cnt != strlen(t)); for (int j = i - 1; j >= 0; j--) printf("%d", o[j]); printf("\n"); } }
#include <algorithm> #include <array> #include <cstdio> #include <iostream> #include <iterator> #include <map> #include <math.h> #include <queue> #include <set> #include <stack> #include <vector> #define ll long long using namespace std; typedef tuple<ll, ll, ll> tp; typedef pair<ll, ll> pr; const ll MOD = 1000000007; const ll INF = 1e18; template <typename T> void print(const T &t) { std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " ")); cout << endl; } template <typename T> void print2d(const T &t) { std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>); } void setIO(string s) { // the argument is the filename without the extension freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } vector<vector<ll>> lava; int main() { string line; ll count = 0; ll n; while (getline(cin, line)) { n = line.size(); vector<ll> temp(n + 2, 11); if (count == 0) { lava.push_back(temp); } for (ll i = 1; i <= n; i++) { temp[i] = line[i - 1] - '0'; } lava.push_back(temp); count++; } vector<ll> temp(n + 2, 11); lava.push_back(temp); ll res = 0; for (ll i = 1; i < lava.size(); i++) { for (ll j = 1; j <= n; j++) { if (lava[i][j] < lava[i - 1][j] && lava[i][j] < lava[i + 1][j] && lava[i][j] < lava[i][j - 1] && lava[i][j] < lava[i][j + 1]) { res += lava[i][j] + 1; } } } vector<ll> R{-1, 0, 1, 0}; vector<ll> C{0, 1, 0, -1}; vector<ll> ans; set<pr> seen; ll size; for (ll i = 1; i < lava.size(); i++) { for (ll j = 1; j <= n; j++) { if (!seen.count({i, j}) && lava[i][j] != 9) { size = 0; queue<pr> q; q.push({i, j}); while (!q.empty()) { pr pi = q.front(); q.pop(); if (seen.count({pi.first, pi.second})) continue; seen.insert({pi.first, pi.second}); size += 1; for (ll z = 0; z < 4; z++) { ll x = pi.first; ll y = pi.second; x += R[z]; y += C[z]; if (1 <= x && x < lava.size() && 1 <= y && y <= n && lava[x][y] != 9 && lava[x][y] != 11) { q.push({x, y}); } } } ans.push_back(size); } } } sort(ans.rbegin(), ans.rend()); cout << ans[0] * ans[1] * ans[2] << endl; }
/** * Image Resource */ #ifndef FISHY_IMAGE_H #define FISHY_IMAGE_H #include <CORE/BASE/status.h> #include <CORE/MEMORY/blob.h> #include <CORE/types.h> #include <algorithm> #include <vector> namespace fsengine { namespace resources { /** * Image holder class */ class Image { public: /** * Input file format type */ enum FmtType { FORMAT_TGA, FORMAT_COUNT }; /** * Load from a file buffer in memory. Makes a copy of the image data. */ bool loadFromMemory(const FmtType fmt, const core::memory::ConstBlob &data); /** * Save to a buffer in memory that can be written as a correctly formatted * file. */ bool saveToMemory(const FmtType fmt, core::memory::Blob &data) const; /** * @return the max size of the save buffer needed for {@link #saveToMemory} */ size_t getSaveSize(const FmtType fmt) const; /** * @return the X dimention of the image */ size_t sizeX() const { return m_szx; } /** * @return the Y dimention of the image */ size_t sizeY() const { return m_szy; } /** * @return pointer to the 32bit image data in RGBA format */ std::vector< u8 > &getMutableDataRgba8(size_t sx, size_t sy) { m_szx = std::max(sx, m_szx); m_szy = std::max(sy, m_szy); m_RGBA8_data.resize(4 * m_szx * m_szy); return m_RGBA8_data; } /** * @return pointer to the 32bit image data in RGBA format */ const std::vector< u8 > &getDataRgba8() const { return m_RGBA8_data; } /** * @return true if the image contains data */ bool isValid() const { return (m_RGBA8_data.size() != 0); } private: Status serializeFromTga(const core::memory::ConstBlob &); Status serializeToTga(core::memory::Blob &) const; size_t getSizeTga() const; std::vector< u8 > m_RGBA8_data; size_t m_szx, m_szy; }; } // namespace resources } // namespace fsengine #endif
//using library #include<iostream> using namespace std; //using main functiobn int main(){ //declaring variables int i = 97; while (i <= 122){ char a = char (i); cout << a << endl; i++; } }
// // Created by NPCXU on 2020/11/8. // #include <stdio.h> #include <malloc.h> typedef int ElemType; typedef struct { ElemType data[50]; int length; } SqList; //建立顺序表 void CreateList(SqList *&list, ElemType elem[], int n) { list = (SqList *) malloc(sizeof(SqList)); for (int i = 0; i < n; i++) list->data[i] = elem[i]; list->length = n; } //按照元素删除 void DeleteList(SqList *&list, ElemType elem) { int pos; for (int i = 0; i < list->length; i++) { if (list->data[i] == elem) { pos = i; } } for (int i = pos; i < list->length - 1; i++) { list->data[i] = list->data[i + 1]; } list->length--; } //打印 void DisplayList(SqList *list) { for (int i = 0; i < list->length; i++) printf("%d ", list->data[i]); printf("\n"); } //查找最小值 int FindMin(SqList *list) { int tmp = list->data[0]; for (int i = 0; i < list->length; i++) { if (tmp > list->data[i]) { tmp = list->data[i]; } } return tmp; } //查找最大值和最小值 3n/2比较次数 void MaxAndMin(SqList *list) { int max = list->data[0], min = list->data[0]; for (int i = 0; i < list->length; i++) if (max < list->data[i]) max = list->data[i]; else if (min > list->data[i]) min = list->data[i]; printf("\nmax= %d,min= %d", max, min); } //递归查找值 返回位置 int SeqSearch(SqList *list, ElemType item, int pos) { if (pos > list->length) return -1; else if (list->data[pos] == item) return pos; return SeqSearch(list, item, pos + 1); } //逆转 void reverse(SqList *list) { ElemType temp; for (int i = 0; i < list->length / 2; i++) { temp = list->data[i]; list->data[i] = list->data[list->length - i - 1]; list->data[list->length - i - 1] = temp; } } //删除奇数 void DeleteOdd(SqList *list) { for (int i = 0; i < list->length; i++) { if (list->data[i] % 2 != 0) { DeleteList(list, list->data[i]); } } } //删除序号为奇数 void DeleteNumOdd(SqList *list) { int j = -1; for (int i = 0; i < list->length; i += 2) { list->data[++j] = list->data[i]; } int odd; for (int i = 0; i < list->length; i++) { if (i % 2 != 0) { odd++; } } list->length = list->length - odd; } //删除范围内的数据 (有序条件) void DeleteRange(SqList *list, ElemType low, ElemType high) { int l = 0, h = list->length - 1; while (list->data[l] < low) { l++; } while (list->data[h] > high) { h--; } int pos = l; for (int k = h + 1; k < list->length; k++) { list->data[l++] = list->data[k]; } list->length = list->length - h + pos - 1; } //建立一个长度为n且不包含重复元素的线性表a void BuildList(SqList *&list, int length) { int flag, i; list->length = length; scanf("%d", &list->data[0]); while (i < length - 1) { scanf("%d", &list->data[i]); for (int j = 0; j < i; j++) { if (list->data[j] == list->data[i]) { flag = 1; break; } } if (flag == 0) i++; else flag = 0; } } //向A中的第i个元素插入B 不考虑溢出 int InsertAB(ElemType A[], int n, ElemType B[], int m, int i) { int j; for (int j = n - 1; j > i - 2; j--) { A[j + m] = A[j]; } for (j = 0; j < m; j++) { A[i + j - 1] = B[j]; } return n + m; } //int main() { // SqList *list; // int n = 5; // ElemType elem[] = {10, 8, 2, 6, 15}; // CreateList(list, elem, n); // DisplayList(list); // //// 1. //// printf("最小值为:\n"); //// int min = FindMin(list); //// printf("%d",min); // //// 2. //// MaxAndMin(list); // //// 3. //// int pos = SeqSearch(list, elem[3], 0); //// printf("最小值位置为:%d\n", pos); // //// 4. //// reverse(list); //// DisplayList(list); // //// 5. //// DeleteOdd(list); //// DisplayList(list); // //// 6. //// DeleteNumOdd(list); //// DisplayList(list); // //// 7. //// SqList *listOrder; //// ElemType elemOrder[] = {2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 21, 56, 78}; //// CreateList(listOrder, elemOrder, 14); //// DisplayList(listOrder); //// DeleteRange(listOrder,7,14); //// DisplayList(listOrder); // //// 8. //// SqList *list_new; //// BuildList(list_new,10); // //// 9. // //}
#include "CShaderManager.h" #include "StringHelper.h" CShaderManager::CShaderManager(string config_path) { //parse well and map<string, string> VerShaderPaths; map<string, string> FragShaderPaths; map<string, string> PolygonData; map<string, string> ProgramData; string Line = ""; ifstream is(config_path.c_str(), std::ios::in); if (is.is_open()) { while (getline(is, Line)) { if(Line == "%vs_start") { getline(is, Line); while (Line != "%vs_end") { M_ParseData(Line, VerShaderPaths, 0); getline(is, Line); } } if (Line == "%fs_start") { getline(is, Line); while (Line != "%fs_end") { M_ParseData(Line, FragShaderPaths, 0); getline(is, Line); } } if (Line == "%polygon_start") { getline(is, Line); while (Line != "%polygon_end") { M_ParseData(Line, PolygonData, 1); getline(is, Line); } } if (Line == "%program_start") { getline(is, Line); while (Line != "%program_end") { M_ParseData(Line, ProgramData, 1); getline(is, Line); } } } is.close(); } else CError("Config file " + config_path + " not found.", true); for (auto p : VerShaderPaths) { M_LoadShader(p.second, p.first, GL_VERTEX_SHADER); } for (auto p : FragShaderPaths) { M_LoadShader(p.second, p.first, GL_FRAGMENT_SHADER); } for(auto p : PolygonData) { M_LoadPolygon(p.second, p.first); } for (auto p : ProgramData) { vector<string> v = StringHelper::M_split(p.second, ','); M_LoadProgram(p.first, StringHelper::M_trim(v[0]), StringHelper::M_trim(v[1])); } } CShaderManager::~CShaderManager() { for (auto x : V_Polygons) { GLuint u = x.second.aindex; glDeleteVertexArrays(1, &u); } for (auto x : V_Buffers) { GLuint u = x.second; glDeleteBuffers(1, &u); } for (auto x : V_Programs) glDeleteProgram(x.second); for (auto x : V_VerShaders) glDeleteShader(x.second); for (auto x : V_FragShaders) glDeleteShader(x.second); freeInstance(); } void CShaderManager::M_LoadShader(string path, string name, int type) { GLuint id = glCreateShader(type); string code; ifstream is(path.c_str(), std::ios::in); if (is.is_open()) { std::string Line = ""; while (getline(is, Line)) code += "\n" + Line; is.close(); } else CError("Shader code " + path + " not found.", true); GLint Result = GL_FALSE; int InfoLogLength; char const * sp = code.c_str(); glShaderSource(id, 1, &sp, NULL); glCompileShader(id); glGetShaderiv(id, GL_COMPILE_STATUS, &Result); glGetShaderiv(id, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { vector<char> error_msg(InfoLogLength + 1); glGetShaderInfoLog(id, InfoLogLength, NULL, &error_msg[0]); printf("%s\n", &error_msg[0]); CError("Shader code " + path + " can't be compoiled", true); } if (type == GL_VERTEX_SHADER) V_VerShaders[name] = id; else V_FragShaders[name] = id; } void CShaderManager::M_LoadPolygon(string data, string name) { //parse data string to float array size_t start = data.find("{"); size_t end = data.find("}", start + 1); data = data.substr(start + 1, end - start - 1); vector<size_t> positions; size_t pos = data.find(","); while (pos != string::npos) { positions.push_back(pos); pos = data.find(",", pos + 1); } int n = positions.size()+1; float * arr = (float *)malloc(n*sizeof(float)); int i = 0; size_t prev = 0; for (auto p : positions) { arr[i] = atof(data.substr(prev,p-prev).c_str()); i++; prev = p+1; } arr[i] = atof(data.substr(prev, string::npos).c_str()); GLuint vbid; GLuint vaid; glGenVertexArrays(1, &vaid); glBindVertexArray(vaid); glGenBuffers(1, &vbid); glBindBuffer(GL_ARRAY_BUFFER, vbid); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * n, arr, GL_STATIC_DRAW); SVerArray va; va.num = n/4; va.aindex = vaid; V_Polygons[name] = va; V_Buffers[name] = vbid; } void CShaderManager::M_LoadProgram(string name, string ver, string frag) { GLuint id = glCreateProgram(); glAttachShader(id, V_VerShaders[ver]); glAttachShader(id, V_FragShaders[frag]); glBindFragDataLocation(id, 0, "color"); glLinkProgram(id); GLint Result = GL_FALSE; int InfoLogLength; glGetProgramiv(id, GL_LINK_STATUS, &Result); glGetProgramiv(id, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { vector<char> error_msg(InfoLogLength + 1); glGetProgramInfoLog(id, InfoLogLength, NULL, &error_msg[0]); printf("%s\n", &error_msg[0]); CError("Program " + name + " can't be linked", true); } V_Programs[name] = id; auto vl = glGetAttribLocation(id, "position"); for (auto p : V_Polygons) { auto a = p.second; auto b = V_Buffers[p.first]; glBindVertexArray(a.aindex); glBindBuffer(GL_ARRAY_BUFFER, b); glEnableVertexAttribArray(vl); glVertexAttribPointer(vl, 4, GL_FLOAT, GL_FALSE, 0, (void*)0); } } void CShaderManager::M_ParseData(string line, map<string,string>& t, int mode) { if (mode == 0) //direct { vector<string> l = StringHelper::M_split(line, ':'); if (l.size() != 2) return; string name = StringHelper::M_trim(l[0]); string path = StringHelper::M_trim(l[1]); t[name] = path; } if (mode == 1) //indirect { ifstream is(line.c_str(), std::ios::in); if (is.is_open()) { string subLine = ""; while (getline(is, subLine)) { vector<string> l = StringHelper::M_split(subLine, ':'); if (l.size() != 2) { is.close(); return; } string name = StringHelper::M_trim(l[0]); string data = StringHelper::M_trim(l[1]); //invalid string error catch t[name] = data; } is.close(); } else CError("file " + line + " not found.", true); } }
/** * Created by Ken van der Eerden * Created on 22/7/2017 17:19 * Developed by * - Ken van der Eerden * - ... * * @Author Ken van der Eerden * @Version 1.0 */ #ifndef BAWS_TYPE_H #define BAWS_TYPE_H class Token { char const* _content; char const* _type; public: Token(char const* content, char const* type); char const* content() const; char const* type() const; }; #endif //BAWS_TYPE_H
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QVector> #include <QDebug> #include <QFile> #include <QFileDialog> #include <QProcess> #include "region.h" #include "paintdisplay.h" namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = nullptr); ~Widget(); private slots: void on_button_Clear_clicked(); void on_button_AddRegion_clicked(); void on_button_AddPoint_clicked(); void on_button_EditPoint_clicked(); void on_button_MovePoint_clicked(); void on_button_DelePoint_clicked(); void on_button_SetValues_clicked(); void on_button_TriangleAll_clicked(); void on_button_Save_clicked(); void on_button_Import_clicked(); void shouMouse(QPointF mouse); void flat(int x); void getRegions(QVector <Region > allregions, double a, double b, double c, double d); signals: void setMode(int x); void clear(); void get(); void importRegion(QVector <Region > importregions, double a, double b, double c, double d); void triangleRegions(QVector <Region > triangleregions, double a, double b, double c, double d); private: bool writepoly(); bool triangle(); bool readnodeele(); bool inRegion(Node a, Region b); private: Ui::Widget *ui; PaintDisplay *paintdisplay; QVector < Region > allRegionsbefore; QVector < Region > allRegions; double top, bottom, left, right; }; #endif // WIDGET_H
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/Rand.h" #include "sp/Grid.h" #include "sp/KdTree.h" using namespace ci; using namespace ci::app; using namespace std; // Minimal verlet particle class struct Particle { void operator+=( const vec2 &position ){ mPosition += position; } vec2 mPosition, mLastPosition; float mSize; }; class Particles2dApp : public App { public: Particles2dApp(); void update() override; void draw() override; void simulate( double timestep ); void mouseDrag( MouseEvent event ) override; //using SpatialStruct = sp::KdTree2<Particle*>; using SpatialStruct = sp::Grid2<Particle*>; SpatialStruct mParticleSpatialStruct; gl::BatchRef mParticlesBatch; gl::VboMeshRef mParticlesVbo; vector<Particle> mParticles; }; Particles2dApp::Particles2dApp() { // init the particle positions vector<vec2> vertices; vector<float> custom0; for( size_t i = 0; i < 20000; ++i ) { auto pos = vec2( randFloat(), randFloat() ) * vec2( getWindowSize() ); auto size = randFloat( 0.4f, 2.0f ); if( randFloat() < 0.015 ) size = randFloat( 2.0f, 6.0f ); mParticles.push_back( { pos, pos + randVec2(), size } ); vertices.push_back( pos ); custom0.push_back( size ); } // create a vbo and a batch to render the particles mParticlesVbo = gl::VboMesh::create( vertices.size(), GL_POINTS, { { geom::BufferLayout( { geom::AttribInfo( geom::POSITION, 2, 0, 0, 0 ) } ), gl::Vbo::create( GL_ARRAY_BUFFER, vertices, GL_DYNAMIC_DRAW ) }, { geom::BufferLayout( { geom::AttribInfo( geom::CUSTOM_0, 1, 0, 0, 0 ) } ), gl::Vbo::create( GL_ARRAY_BUFFER, custom0, GL_STATIC_DRAW ) } } ); mParticlesBatch = gl::Batch::create( mParticlesVbo, gl::GlslProg::create( gl::GlslProg::Format() .vertex( loadAsset( "shader.vert" ) ) .fragment( loadAsset( "shader.frag" ) ) .attrib( geom::POSITION, "ciPosition" ) .attrib( geom::CUSTOM_0, "ciCustom0" ) ) ); // and the grid that will be user to do a really basic n-body simulation mParticleSpatialStruct = SpatialStruct(); } void Particles2dApp::update() { // update the grid mParticleSpatialStruct.clear(); for( auto& particle : mParticles ) { mParticleSpatialStruct.insert( particle.mPosition, &particle ); } // update particle-particle forces for( auto& particle : mParticles ) { // find nearest neighbors and apply repulsion forces mParticleSpatialStruct.rangeSearch( particle.mPosition, particle.mSize * 3.0f, [&particle]( SpatialStruct::Node* neighbor, float distSq ) { // check the distance square to see if it's the same particle or a neighbor if( distSq > 0 ) { auto neighborParticle = neighbor->getData(); auto diff = ( particle.mPosition - neighborParticle->mPosition ); particle += diff * 0.0075f; *neighborParticle += -diff * 0.0075f; } } ); } // physic integration steps static const double timestep = 1.0 / 60.0; static double time = getElapsedSeconds(); static double accumulator = 0.0; double elapsed = getElapsedSeconds() - time; time += elapsed; accumulator += glm::min( elapsed, 0.1 ); while( accumulator >= timestep ) { simulate( timestep ); accumulator -= timestep; } // update particle vbo gl::VboMesh::MappedAttrib<vec2> mappedPos = mParticlesVbo->mapAttrib2f( geom::POSITION ); for( size_t i = 0; i < mParticlesVbo->getNumVertices(); i++ ) { *mappedPos = mParticles[i].mPosition; mappedPos++; } mappedPos.unmap(); getWindow()->setTitle( to_string( (int) getAverageFps() ) ); } void Particles2dApp::simulate( double timestep ) { // update particles positions for( auto& particle : mParticles ) { // constraint to windows bounds particle.mPosition = glm::max( glm::min( particle.mPosition, vec2( getWindowSize() ) ), vec2( 0 ) ); // apply weak force that attracts all particle to the center particle += ( vec2( getWindowCenter() ) - particle.mPosition ) * 0.000001f; // basic verlet integration const float friction = 0.985f; auto temp = particle.mPosition; particle += ( particle.mPosition - particle.mLastPosition ) * friction; particle.mLastPosition = temp; } } void Particles2dApp::mouseDrag( MouseEvent event ) { // get the particles around the mouse vec2 mouse = event.getPos(); mParticleSpatialStruct.rangeSearch( mouse, event.isLeft() ? 100.0f : 25.0f, [mouse,event]( SpatialStruct::Node* node, float distSq ) { // and move them away auto particle = static_cast<Particle*>( node->getData() ); *particle += ( particle->mPosition - mouse ) * ( event.isLeft() ? 0.005f : 0.5f ); } ); } void Particles2dApp::draw() { gl::clear( Color( 0, 0, 0 ) ); gl::ScopedBlendAlpha alphaBlending; gl::ScopedState glslPointSize( GL_PROGRAM_POINT_SIZE, true ); mParticlesBatch->draw(); } CINDER_APP( Particles2dApp, RendererGl, []( App::Settings* settings ) { settings->setWindowSize( 1280, 720 ); })
/** Assignment 2 1. enter a no. and find location done 2. insert element at given index done 3. delete element from an array done 4. perform binary search done 5. append one array element of integers to other 6. reverse all array element without using temprary variable done Bubble sort as prerequist done **/ #include<iostream> using namespace std; int len(int a[]); void find(int a[],int n); void insert(int a[],int i,int item); int del(int a[],int e); int bubble(int a[]); int binary(int a[],int l,int h,int e); void reverse(int a[]); int main() { int a[50]={30,60,50,10,30,20,40,30,5},i=0; find(a,30); insert(a,2,100); cout<<endl; del(a,30); del(a,30); del(a,30); //bubble(a); reverse(a); while(a[i]!='\0') { cout<<a[i++]<<","; } // cout<<endl<<"20 at "<<binary(a,0,7,20)<<"in sorted"; return 0; } void find(int a[],int n) { int i=0; while(a[i]!='\0') { if(a[i++]==n) cout<<"Number Found at index :"<<i-1<<endl; } } int len(int a[]) { int i=0; while(a[i++]!='\0'); return --i; } void insert(int a[],int i,int item) { int x=len(a),j; for( j=x;j>=i;j--) { a[j+1]=a[j]; } a[j+1]=item; } int del(int a[],int e) { int i=0,x; while(a[i]!='\0') { if(a[i]==e) { //cout<<"found"; break; } i++; } // cout<<"i = "<<i<<"and len is "<<len(a)<<endl; if(i>=len(a)) { cout<<"Element Not Found"<<endl; return -1; } else { x=a[i]; for(int j=i;j<len(a);j++) { a[j]=a[j+1]; } a[len(a)]='\0'; } return x; } int bubble(int a[]) { for(int i=0;i<len(a)-1;i++) { for(int j=len(a)-1;j>i;j--) { if(a[j-1]>a[j]) { int t=a[j]; a[j]=a[j-1]; a[j-1]=t; } } } } int binary(int a[],int l,int h,int e) { int mid; bubble(a); mid=(l+h)/2; if(a[mid]==e) return mid; else { if(e<a[mid]) binary(a,l,mid,e); else binary(a,mid,h,e); } } void reverse(int a[]) { int x=len(a); for(int i=2;i<=x;i++) insert(a,x-1,del(a,a[x-i])); }
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pthread.h> #include<string.h> #include<fcntl.h> #include<netinet/in.h> #include<arpa/inet.h> #include<netinet/tcp.h> #include<errno.h> #include"params.h" #include"miscutils.h" #include"clusterip.h" #include"clusterinfo.h" #include"pinger.h" extern CClusterInfo clusterInfo; extern char TIMEOUT_EVENT_SCRIPT[256]; //! \brief Pinger thread. This thread is responsible for checking the connection to the cloud. //! void *pinger(void *args) { CParams *cp = (CParams *)args; CMiscUtils cmu; char ping_cmd[128]; int exit_code; time_t pingok, now; bool alerted = false; memset( TIMEOUT_EVENT_SCRIPT, 0, sizeof(TIMEOUT_EVENT_SCRIPT)); // TODO: use ping6 if NexHopIP() is ipv6. if ( IsIPV6(cp->NextHopIP()) ) snprintf(ping_cmd, 128,"ping6 -c1 -w3 %s > /dev/null 2>&1", cp->NextHopIP()); else snprintf(ping_cmd, 128,"ping -c1 -w3 %s > /dev/null 2>&1", cp->NextHopIP()); cmu.LogMsg(DEBUG, "pinger(): %s", ping_cmd); time( &pingok ); while(1){ clusterInfo.SetPingerHB(); // update the hearbeat time if ( clusterInfo.State() == MAINTENANCE_STATE || clusterInfo.MyStatus() == MAINTENANCE_STATUS ) { //printf("********pinger do nothing...\n"); sleep(1); continue; } //printf("%s\n", ping_cmd); exit_code = system( ping_cmd ); //cmu.LogMsg(DEBUG, "pinger(): exit_code:%d [%s]", exit_code, ping_cmd); //printf("exit_code: %d\n", exit_code); if ( exit_code == 0 ){ if ( clusterInfo.MyStatus() != ONLINE_STATUS ){ clusterInfo.ResetLastACK(); clusterInfo.MyStatus( ONLINE_STATUS ); } time( &pingok ); clusterInfo.PingOK(); alerted = false; } else{ // next hop is unreachable... cmu.LogMsg(WARNING, "pinger(): next hop [%s] is unreachable", cp->NextHopIP()); time( &now ); if ( (now - pingok) >= cp->Timeout() ){ if ( ! alerted ) { alerted = true; // reach the maximum timeout allowed. Set the node status to OFFLINE and node ROLE to UNKNOWN clusterInfo.MyStatus( OFFLINE_STATUS ); clusterInfo.MyRole( UNKNOWN ); clusterInfo.State( UNKNOWN_STATE ); cmu.LogMsg(WARNING, "pinger(): maximum timeout has been reached! Demoting..."); Demote( false ); // parameter should be true if user wants to put the node to standby... } } sleep( cp->PingInterval() ); continue; } sleep( cp->PingInterval() ); } }
#include<bits/stdc++.h> using namespace std; int main() { map<char,int> mp; pair<char,int> p; p = make_pair('a',200); mp.insert(p); p = make_pair('b',500); mp.insert(p); for(auto x: mp) { cout<<x.first<<"->"<<x.second<<"\n"; } }
#ifndef DE_MATERIAL_H #define DE_MATERIAL_H #include "core/Program.h" #include "core/AssetDatabase.h" #include "data/Texture.h" #include <list> #include <cstdint> namespace de { namespace argv { class AShaderArg; } class DE_EXPORT Material : public ILoadableAsset { protected: static std::list<int16_t> sFreeIDs; static int16_t sIDCounter; static std::map<int16_t, Material*> sMaterials; std::list<int> mFreeUnit; // count free texture unit Program* mProgram; int16_t mID; std::map<std::string, argv::AShaderArg*> mArguments; // list of all user defined argument to pass to shader std::list<data::Texture*> mTexture; public: Material(); ~Material(); void setProgram(Program* pProgram); /** * \brief Add or set a texture to this mat. if pInstantUpload == true, it upload to the program the texture immediatly */ void addTexture(const std::string& pName, data::Texture* pTexture, bool pInstantUpload = false); Program* program() const; /** * \brief this setup the material (bind program, push texture to it etc...) If pForCurrentCam == true (default), it will bind current cam matrix to it too. */ void setup(bool pForCurrentCam = true); void fromFile(const std::string& pFile); int16_t getID(); static Material* getMaterialFromID(uint16_t pID); }; namespace argv { //--------Shader argument class (allow unified binding) class AShaderArg { protected: std::string mName; public: AShaderArg(const std::string& pName); virtual void upload(Program* pProgram) = 0; }; //****** class Vec4Arg : public AShaderArg { protected: glm::vec4 mData; public: Vec4Arg(const std::string& pName, glm::vec4 pData); void upload(Program* pProgram); }; //****** class MatrixArg : public AShaderArg { protected: glm::mat4 mData; public: MatrixArg(const std::string& pName, const glm::mat4& pData); void upload(Program* pProgram); }; //********* class TextureArg : public AShaderArg { protected: data::Texture* mTexture; int mData; public: TextureArg(const std::string& pName, int pTextureUnit, data::Texture* pTexture); void upload(Program* pProgram); void changeTexture(de::data::Texture* pTex); }; //---------------------------------------------- } } #endif
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include "multimedia/mm_ashmem.h" #include "multimedia/mm_debug.h" #if defined(OS_YUNOS) #include <thread/LooperThread.h> #include <string/String.h> #include <dbus/DServiceManager.h> #include <pointer/SharedPtr.h> #include <dbus/DMessage.h> #include <dbus/DService.h> #include <dbus/DProxy.h> #include <dbus/DAdaptor.h> #endif MM_LOG_DEFINE_MODULE_NAME("MMASHMEM") using namespace yunos; using namespace YUNOS_MM; class MMAshMemTest : public testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } }; #if (defined OS_YUNOS ) static const char* gAshMemName = "com.yunos.mm.ashmem"; static const char* gAshMemObjectPath = "/com/yunos/mm/ashmem"; static const char* gAshMemInterface = "com.yunos.mm.ashmem.interface"; class ProxyTest : public DProxy { public: ProxyTest(const SharedPtr<DService>& service, const String& path, const String& iface) : DProxy(service, path, iface) { } virtual ~ProxyTest() {} bool create_ashmem() { SharedPtr<DMessage> msg = obtainMethodCallMessage(String("create_ashmem")); size_t size = 32; mAshMem = MMAshMem::create("ProxyTest", size); msg->writeInt32(size); msg->writeFd(mAshMem->getKey()); SharedPtr<DMessage> reply = sendMessageWithReplyBlocking(msg); int32_t ret = -1; if (reply) { ret = reply->readInt32(); INFO("ret %d\n", ret); return true; } else { ASSERT(0); ERROR("invalid reply"); } return false; } bool test_ashmem() { for (int i = 0; i < 16; i++) { SharedPtr<DMessage> msg = obtainMethodCallMessage(String("test_ashmem")); uint8_t *data = (uint8_t*)mAshMem->getBase(); size_t size = mAshMem->getSize(); memset(data, i, size); msg->writeInt32(i); SharedPtr<DMessage> reply = sendMessageWithReplyBlocking(msg); int32_t ret = -1; if (reply) { ret = reply->readInt32(); //dump buffer, changed by adaptor hexDump(data, size, 32); INFO("ret %d\n", ret); } else { ASSERT(0); ERROR("invalid reply"); return false; } } return true; } private: MMAshMemSP mAshMem; }; class AshMemTestIpc { public: AshMemTestIpc() : mCondition(mLock) { SharedPtr<LooperThread> mLooper = new LooperThread(); mLooper->start("MetaTest"); if (mLooper->isRunning() != true) { INFO("LooperThread is not running\n"); return; } mLooper->sendTask(Task(AshMemTestIpc::createProxy, this)); mCondition.wait(); } static void createProxy(AshMemTestIpc *instance) { INFO("create proxy: service(%s) path(%s) interface(%s)\n", gAshMemName, gAshMemObjectPath, gAshMemInterface); instance->mManager = DServiceManager::getInstance(); instance->mService = instance->mManager->getService(String(gAshMemName)); if (!instance->mService) { INFO("getService %s failed\n", gAshMemName); instance->mCondition.signal(); return; } instance->mProxyTest = new ProxyTest(instance->mService, String(gAshMemObjectPath), String(gAshMemInterface)); instance->mCondition.signal(); } bool create_ashmem() { if (!mProxyTest) { WARNING("proxy is invalid"); return false; } return mProxyTest->create_ashmem(); } bool test_ashmem() { if (!mProxyTest) { WARNING("proxy is invalid"); return false; } return mProxyTest->test_ashmem(); } private: Lock mLock; YUNOS_MM::Condition mCondition; SharedPtr<DServiceManager> mManager; SharedPtr<DService> mService; SharedPtr<ProxyTest> mProxyTest; }; #endif TEST_F(MMAshMemTest, mmashmemtest) { #if defined(OS_YUNOS) AshMemTestIpc *testObjectIpc = new AshMemTestIpc(); EXPECT_TRUE(testObjectIpc->create_ashmem()); EXPECT_TRUE(testObjectIpc->test_ashmem()); delete testObjectIpc; testObjectIpc = NULL; #endif INFO("done\n"); } int main(int argc, char* const argv[]) { int ret; MMLOGD("testing begin\n"); try { ::testing::InitGoogleTest(&argc, (char **)argv); ret = RUN_ALL_TESTS(); } catch (testing::internal::GoogleTestFailureException) { MMLOGE("InitGoogleTest failed!"); return -1; } catch (...) { MMLOGE("unknown exception!"); return -1; } usleep(3000000); MMLOGD("exit\n"); return ret; }
#ifndef MASK_HPP #define MASK_HPP class MaskFigure{ public: virtual ~MaskFigure()=0; protected: MaskFigure(); }; class MaskRound:public MaskFigure { public: MaskRound(); ~MaskRound(); }; class MaskRec:public MaskFigure { public: MaskRec(); ~MaskRec(); }; class MaskTri:public MaskFigure { public: MaskTri(); ~MaskTri(); }; #endif
// Physics List #include "WCSimPhysicsList.hh" #include "WCSimPhysicsMessenger.hh" #include "G4ParticleDefinition.hh" #include "G4ParticleWithCuts.hh" #include "G4LeptonConstructor.hh" #include "G4MesonConstructor.hh" #include "G4BaryonConstructor.hh" #include "G4BosonConstructor.hh" #include "G4IonConstructor.hh" #include "G4ShortLivedConstructor.hh" #include "G4ProcessManager.hh" #include "G4ProcessVector.hh" #include "G4ParticleTypes.hh" #include "G4ParticleTable.hh" #include "G4Material.hh" #include "G4ios.hh" #include "G4UImanager.hh" #include "globals.hh" #include <iomanip> #include "G4HadronCaptureProcess.hh" //amb79 //WCSimPhysicsList::WCSimPhysicsList(): G4VUserPhysicsList(), PhysicsMessenger(0) WCSimPhysicsList::WCSimPhysicsList(): G4VPhysicsConstructor(), PhysicsMessenger(0) { //defaultCutValue = 1.0*mm; //moved to WCSimPhysicsListFactory.cc SetVerboseLevel(1); PhysicsMessenger = new WCSimPhysicsMessenger(this); } WCSimPhysicsList::~WCSimPhysicsList() { delete PhysicsMessenger; PhysicsMessenger = 0; } //----particle construction---- void WCSimPhysicsList::ConstructParticle() { G4LeptonConstructor leptonConstructor; G4MesonConstructor mesonConstructor; G4BaryonConstructor baryonConstructor; G4BosonConstructor bosonConstructor; G4IonConstructor ionConstructor; G4ShortLivedConstructor ShortLivedConstructor; leptonConstructor.ConstructParticle(); mesonConstructor.ConstructParticle(); baryonConstructor.ConstructParticle(); bosonConstructor.ConstructParticle(); ionConstructor.ConstructParticle(); ShortLivedConstructor.ConstructParticle(); G4OpticalPhoton::OpticalPhotonDefinition(); } //----construction of processes---- void WCSimPhysicsList::ConstructProcess() { //AddTransportation(); ConstructEM(); ConstructlArStepLimiter(); ConstructGeneral(); ConstructOp(); ConstructHad(); } #include "G4ComptonScattering.hh" #include "G4GammaConversion.hh" #include "G4PhotoElectricEffect.hh" //#include "G4MultipleScattering.hh"//K.Z.: obsolete class, has to be removed. #include "G4eIonisation.hh" #include "G4eBremsstrahlung.hh" #include "G4eplusAnnihilation.hh" #include "G4MuIonisation.hh" #include "G4MuBremsstrahlung.hh" #include "G4MuPairProduction.hh" #include "G4hIonisation.hh" #include "G4MuonMinusCaptureAtRest.hh" //K.Z.: New MultipleScattering classes #include "G4eMultipleScattering.hh" #include "G4MuMultipleScattering.hh" #include "G4hMultipleScattering.hh" //---E&M construction void WCSimPhysicsList::ConstructEM() { //G4MultipleScattering class becomes obsolete and has to be removed and //replaced by new G4MultipleScattering classes for e+-, mu+-, hadron and ions. //K. Zbiri, 12/30/2009 theParticleIterator->reset(); while( (*theParticleIterator)() ){ G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); if (particleName == "gamma") { // gamma pmanager->AddDiscreteProcess(new G4GammaConversion()); pmanager->AddDiscreteProcess(new G4ComptonScattering()); pmanager->AddDiscreteProcess(new G4PhotoElectricEffect()); } else if (particleName == "e-") { //electron // G4VProcess* theeminusMultipleScattering = new G4MultipleScattering(); G4VProcess* theeminusMultipleScattering = new G4eMultipleScattering(); G4VProcess* theeminusIonisation = new G4eIonisation(); G4VProcess* theeminusBremsstrahlung = new G4eBremsstrahlung(); // // add processes pmanager->AddProcess(theeminusMultipleScattering); pmanager->AddProcess(theeminusIonisation); pmanager->AddProcess(theeminusBremsstrahlung); // // set ordering for AlongStepDoIt pmanager->SetProcessOrdering(theeminusMultipleScattering,idxAlongStep,1); pmanager->SetProcessOrdering(theeminusIonisation, idxAlongStep,2); // // set ordering for PostStepDoIt pmanager->SetProcessOrdering(theeminusMultipleScattering, idxPostStep,1); pmanager->SetProcessOrdering(theeminusIonisation, idxPostStep,2); pmanager->SetProcessOrdering(theeminusBremsstrahlung, idxPostStep,3); } else if (particleName == "e+") { //positron // G4VProcess* theeplusMultipleScattering = new G4MultipleScattering(); G4VProcess* theeplusMultipleScattering = new G4eMultipleScattering(); G4VProcess* theeplusIonisation = new G4eIonisation(); G4VProcess* theeplusBremsstrahlung = new G4eBremsstrahlung(); G4VProcess* theeplusAnnihilation = new G4eplusAnnihilation(); // // add processes pmanager->AddProcess(theeplusMultipleScattering); pmanager->AddProcess(theeplusIonisation); pmanager->AddProcess(theeplusBremsstrahlung); pmanager->AddProcess(theeplusAnnihilation); // // set ordering for AtRestDoIt pmanager->SetProcessOrderingToFirst(theeplusAnnihilation, idxAtRest); // // set ordering for AlongStepDoIt pmanager->SetProcessOrdering(theeplusMultipleScattering, idxAlongStep,1); pmanager->SetProcessOrdering(theeplusIonisation, idxAlongStep,2); // // set ordering for PostStepDoIt pmanager->SetProcessOrdering(theeplusMultipleScattering, idxPostStep,1); pmanager->SetProcessOrdering(theeplusIonisation, idxPostStep,2); pmanager->SetProcessOrdering(theeplusBremsstrahlung, idxPostStep,3); pmanager->SetProcessOrdering(theeplusAnnihilation, idxPostStep,4); } else if( particleName == "mu+" || particleName == "mu-" ) { //muon //G4VProcess* aMultipleScattering = new G4MultipleScattering(); G4VProcess* aMultipleScattering = new G4MuMultipleScattering(); G4VProcess* aBremsstrahlung = new G4MuBremsstrahlung(); G4VProcess* aPairProduction = new G4MuPairProduction(); G4VProcess* anIonisation = new G4MuIonisation(); // // add processes pmanager->AddProcess(anIonisation); pmanager->AddProcess(aMultipleScattering); pmanager->AddProcess(aBremsstrahlung); pmanager->AddProcess(aPairProduction); // // set ordering for AlongStepDoIt pmanager->SetProcessOrdering(aMultipleScattering, idxAlongStep,1); pmanager->SetProcessOrdering(anIonisation, idxAlongStep,2); // // set ordering for PostStepDoIt pmanager->SetProcessOrdering(aMultipleScattering, idxPostStep,1); pmanager->SetProcessOrdering(anIonisation, idxPostStep,2); pmanager->SetProcessOrdering(aBremsstrahlung, idxPostStep,3); pmanager->SetProcessOrdering(aPairProduction, idxPostStep,4); // MF , stolen from CWW, april 2005 if (particleName == "mu-") { G4VProcess* aG4MuonMinusCaptureAtRest = new G4MuonMinusCaptureAtRest(); pmanager->AddProcess(aG4MuonMinusCaptureAtRest); pmanager->SetProcessOrdering(aG4MuonMinusCaptureAtRest,idxAtRest); } } else if ((!particle->IsShortLived()) && (particle->GetPDGCharge() != 0.0)&& (particle->GetParticleName() != "chargedgeantino")) { // G4VProcess* aMultipleScattering = new G4MultipleScattering(); G4VProcess* aMultipleScattering = new G4hMultipleScattering(); G4VProcess* anIonisation = new G4hIonisation(); // // add processes pmanager->AddProcess(anIonisation); pmanager->AddProcess(aMultipleScattering); // // set ordering for AlongStepDoIt pmanager->SetProcessOrdering(aMultipleScattering, idxAlongStep,1); pmanager->SetProcessOrdering(anIonisation, idxAlongStep,2); // // set ordering for PostStepDoIt pmanager->SetProcessOrdering(aMultipleScattering, idxPostStep,1); pmanager->SetProcessOrdering(anIonisation, idxPostStep,2); } } } #ifdef GEANT4_7_0 #include "G4StepLimiter.hh" #endif void WCSimPhysicsList::ConstructlArStepLimiter(){ #ifdef GEANT4_7_0 theParticleIterator->reset(); while( (*theParticleIterator)() ){ G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); if ((!particle->IsShortLived()) && (particle->GetPDGCharge() != 0.0)&& (particle->GetParticleName() != "chargedgeantino")) { G4VProcess* stepLimiter = new G4StepLimiter(); pmanager->AddProcess(stepLimiter); pmanager->SetProcessOrdering(stepLimiter, idxPostStep, pmanager->GetProcessListLength()); } } #endif } #include "G4Cerenkov.hh" #include "G4Scintillation.hh" #include "G4EmSaturation.hh" #include "G4OpAbsorption.hh" #include "G4OpRayleigh.hh" #include "G4OpWLS.hh" #include "G4OpMieHG.hh" #include "G4OpBoundaryProcess.hh" void WCSimPhysicsList::ConstructOp(){ G4Cerenkov* theCherenkovProcess = new G4Cerenkov("Cerenkov"); G4OpAbsorption* theAbsorptionProcess = new G4OpAbsorption(); G4OpRayleigh* theRayleighScatteringProcess = new G4OpRayleigh(); G4OpWLS* theWLSProcess = new G4OpWLS(); G4OpMieHG* theMieHGScatteringProcess = new G4OpMieHG(); G4OpBoundaryProcess* theBoundaryProcess = new G4OpBoundaryProcess(); // theCherenkovProcess->DumpPhysicsTable(); // theAbsorptionProcess->DumpPhysicsTable(); // theRayleighScatteringProcess->DumpPhysicsTable(); theCherenkovProcess->SetVerboseLevel(0); // add scintillation process and saturation (controlled by birk's constant) G4Scintillation* theScintProcess = new G4Scintillation("Scintillation"); G4EmSaturation* theEmSatProcess = new G4EmSaturation(); theScintProcess->SetTrackSecondariesFirst(true); theScintProcess->SetScintillationYieldFactor(1.0); theScintProcess->AddSaturation(theEmSatProcess); theAbsorptionProcess->SetVerboseLevel(0); theRayleighScatteringProcess->SetVerboseLevel(0); theMieHGScatteringProcess->SetVerboseLevel(0); theBoundaryProcess->SetVerboseLevel(0); theWLSProcess->SetVerboseLevel(0); theWLSProcess->UseTimeProfile("exponential"); G4int MaxNumPhotons = 300; theCherenkovProcess->SetTrackSecondariesFirst(false); theCherenkovProcess->SetMaxNumPhotonsPerStep(MaxNumPhotons); // FROM N06 example: // theCherenkovProcess->SetMaxNumPhotonsPerStep(20); // theCherenkovProcess->SetMaxBetaChangePerStep(10.0); // theCherenkovProcess->SetTrackSecondariesFirst(true); G4OpticalSurfaceModel themodel = unified; theBoundaryProcess->SetModel(themodel); theParticleIterator->reset(); while( (*theParticleIterator)() ) { G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); /* if (theCherenkovProcess->IsApplicable(*particle)) pmanager->AddContinuousProcess(theCherenkovProcess);*/ if (theCherenkovProcess->IsApplicable(*particle)) { pmanager->AddProcess(theCherenkovProcess); pmanager->SetProcessOrdering(theCherenkovProcess,idxPostStep); } if (theScintProcess->IsApplicable(*particle)){ pmanager->AddProcess(theScintProcess); pmanager->SetProcessOrderingToLast(theScintProcess,idxAtRest); pmanager->SetProcessOrderingToLast(theScintProcess,idxPostStep); } if (particleName == "opticalphoton") { pmanager->AddDiscreteProcess(theAbsorptionProcess); // G4cout << "warning direct light only\n"; pmanager->AddDiscreteProcess(theRayleighScatteringProcess); pmanager->AddDiscreteProcess(theWLSProcess); pmanager->AddDiscreteProcess(theMieHGScatteringProcess); pmanager->AddDiscreteProcess(theBoundaryProcess); } } } //---General construction #include "G4Decay.hh" void WCSimPhysicsList::ConstructGeneral() { // Add Decay Process G4Decay* theDecayProcess = new G4Decay(); theParticleIterator->reset(); while( (*theParticleIterator)() ){ G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); if (theDecayProcess->IsApplicable(*particle)) { pmanager ->AddProcess(theDecayProcess); // set ordering for PostStepDoIt and AtRestDoIt pmanager ->SetProcessOrdering(theDecayProcess, idxPostStep); pmanager ->SetProcessOrdering(theDecayProcess, idxAtRest); } } } // Elastic processes: #include "G4HadronElasticProcess.hh" // Inelastic processes: #include "G4PionPlusInelasticProcess.hh" #include "G4PionMinusInelasticProcess.hh" #include "G4KaonPlusInelasticProcess.hh" #include "G4KaonZeroSInelasticProcess.hh" #include "G4KaonZeroLInelasticProcess.hh" #include "G4KaonMinusInelasticProcess.hh" #include "G4ProtonInelasticProcess.hh" #include "G4AntiProtonInelasticProcess.hh" #include "G4NeutronInelasticProcess.hh" #include "G4AntiNeutronInelasticProcess.hh" #include "G4DeuteronInelasticProcess.hh" #include "G4TritonInelasticProcess.hh" #include "G4AlphaInelasticProcess.hh" // Low-energy Models: < 20GeV #include "G4LElastic.hh" #include "G4LEPionPlusInelastic.hh" #include "G4LEPionMinusInelastic.hh" #include "G4LEKaonPlusInelastic.hh" #include "G4LEKaonZeroSInelastic.hh" #include "G4LEKaonZeroLInelastic.hh" #include "G4LEKaonMinusInelastic.hh" #include "G4LEProtonInelastic.hh" #include "G4LEAntiProtonInelastic.hh" #include "G4LENeutronInelastic.hh" #include "G4LEAntiNeutronInelastic.hh" #include "G4LEDeuteronInelastic.hh" #include "G4LETritonInelastic.hh" #include "G4LEAlphaInelastic.hh" // High-energy Models: >20 GeV #include "G4HEPionPlusInelastic.hh" #include "G4HEPionMinusInelastic.hh" #include "G4HEKaonPlusInelastic.hh" #include "G4HEKaonZeroInelastic.hh" #include "G4HEKaonZeroInelastic.hh" #include "G4HEKaonMinusInelastic.hh" #include "G4HEProtonInelastic.hh" #include "G4HEAntiProtonInelastic.hh" #include "G4HENeutronInelastic.hh" #include "G4HEAntiNeutronInelastic.hh" // Neutron high-precision models: <20 MeV #include "G4NeutronHPElastic.hh" #include "G4NeutronHPElasticData.hh" #include "G4NeutronHPCapture.hh" #include "G4NeutronHPCaptureData.hh" #include "G4NeutronHPInelastic.hh" #include "G4NeutronHPInelasticData.hh" #include "G4LCapture.hh" //================================= // Added by JLR 2005-07-05 //================================= // Secondary hadronic interaction models #include "G4CascadeInterface.hh" #include "G4BinaryCascade.hh" // Stopping processes #include "G4PiMinusAbsorptionAtRest.hh" #include "G4KaonMinusAbsorptionAtRest.hh" #include "G4AntiProtonAnnihilationAtRest.hh" #include "G4AntiNeutronAnnihilationAtRest.hh" void WCSimPhysicsList::ConstructHad() { // Makes discrete physics processes for the hadrons, at present limited // to those particles with GHEISHA interactions (INTRC > 0). // The processes are: Elastic scattering and Inelastic scattering. // F.W.Jones 09-JUL-1998 // // This code stolen from: // examples/advanced/underground_physics/src/DMXPhysicsList.cc // CWW 2/23/05 // G4HadronElasticProcess* theElasticProcess = new G4HadronElasticProcess; G4LElastic* theElasticModel = new G4LElastic; theElasticProcess->RegisterMe(theElasticModel); theParticleIterator->reset(); while ((*theParticleIterator)()) { G4ParticleDefinition* particle = theParticleIterator->value(); G4ProcessManager* pmanager = particle->GetProcessManager(); G4String particleName = particle->GetParticleName(); if (particleName == "pi+") { pmanager->AddDiscreteProcess(theElasticProcess); G4PionPlusInelasticProcess* theInelasticProcess = new G4PionPlusInelasticProcess(); G4LEPionPlusInelastic* theLEInelasticModel = new G4LEPionPlusInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEPionPlusInelastic* theHEInelasticModel = new G4HEPionPlusInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "pi-") { pmanager->AddDiscreteProcess(theElasticProcess); G4PionMinusInelasticProcess* theInelasticProcess = new G4PionMinusInelasticProcess(); G4LEPionMinusInelastic* theLEInelasticModel = new G4LEPionMinusInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEPionMinusInelastic* theHEInelasticModel = new G4HEPionMinusInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); G4String prcNam; pmanager->AddRestProcess(new G4PiMinusAbsorptionAtRest, ordDefault); } else if (particleName == "kaon+") { pmanager->AddDiscreteProcess(theElasticProcess); G4KaonPlusInelasticProcess* theInelasticProcess = new G4KaonPlusInelasticProcess(); G4LEKaonPlusInelastic* theLEInelasticModel = new G4LEKaonPlusInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEKaonPlusInelastic* theHEInelasticModel = new G4HEKaonPlusInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "kaon0S") { pmanager->AddDiscreteProcess(theElasticProcess); G4KaonZeroSInelasticProcess* theInelasticProcess = new G4KaonZeroSInelasticProcess(); G4LEKaonZeroSInelastic* theLEInelasticModel = new G4LEKaonZeroSInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEKaonZeroInelastic* theHEInelasticModel = new G4HEKaonZeroInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "kaon0L") { pmanager->AddDiscreteProcess(theElasticProcess); G4KaonZeroLInelasticProcess* theInelasticProcess = new G4KaonZeroLInelasticProcess(); G4LEKaonZeroLInelastic* theLEInelasticModel = new G4LEKaonZeroLInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEKaonZeroInelastic* theHEInelasticModel = new G4HEKaonZeroInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "kaon-") { pmanager->AddDiscreteProcess(theElasticProcess); G4KaonMinusInelasticProcess* theInelasticProcess = new G4KaonMinusInelasticProcess(); G4LEKaonMinusInelastic* theLEInelasticModel = new G4LEKaonMinusInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEKaonMinusInelastic* theHEInelasticModel = new G4HEKaonMinusInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); pmanager->AddRestProcess(new G4KaonMinusAbsorptionAtRest, ordDefault); } else if (particleName == "proton") { pmanager->AddDiscreteProcess(theElasticProcess); G4ProtonInelasticProcess* theInelasticProcess = new G4ProtonInelasticProcess(); //================================= // Added by JLR 2005-07-05 //================================= // Options for secondary interaction models // Choice defined in jobOptions.mac, which is // read in before initialization of the run manager. // In the absence of this file, BINARY will be used. // Gheisha = Original Geant4 default // Bertini = Bertini intra-nuclear cascade model // Binary = Binary intra-nuclear cascade model if (gheishahad) { G4LEProtonInelastic* theLEInelasticModel = new G4LEProtonInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); } else if (bertinihad) { G4CascadeInterface* theBertiniModel = new G4CascadeInterface; theInelasticProcess->RegisterMe(theBertiniModel); } else if (binaryhad) { G4BinaryCascade* theBinaryModel = new G4BinaryCascade(); theInelasticProcess->RegisterMe(theBinaryModel); G4LEProtonInelastic* theLEInelasticModel = new G4LEProtonInelastic; theLEInelasticModel->SetMinEnergy(10.1*GeV); theLEInelasticModel->SetMaxEnergy( 45.*GeV ); theInelasticProcess->RegisterMe(theLEInelasticModel); } else { G4cout << "No secondary interaction model chosen! Using G4 BINARY." << G4endl; G4BinaryCascade* theBinaryModel = new G4BinaryCascade(); theInelasticProcess->RegisterMe(theBinaryModel); } G4HEProtonInelastic* theHEInelasticModel = new G4HEProtonInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "anti_proton") { pmanager->AddDiscreteProcess(theElasticProcess); G4AntiProtonInelasticProcess* theInelasticProcess = new G4AntiProtonInelasticProcess(); G4LEAntiProtonInelastic* theLEInelasticModel = new G4LEAntiProtonInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEAntiProtonInelastic* theHEInelasticModel = new G4HEAntiProtonInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "neutron") { // elastic scattering G4HadronElasticProcess* theNeutronElasticProcess = new G4HadronElasticProcess; G4LElastic* theElasticModel1 = new G4LElastic; G4NeutronHPElastic * theElasticNeutron = new G4NeutronHPElastic; theNeutronElasticProcess->RegisterMe(theElasticModel1); theElasticModel1->SetMinEnergy(19*MeV); theNeutronElasticProcess->RegisterMe(theElasticNeutron); G4NeutronHPElasticData * theNeutronData = new G4NeutronHPElasticData; theNeutronElasticProcess->AddDataSet(theNeutronData); pmanager->AddDiscreteProcess(theNeutronElasticProcess); // inelastic scattering G4NeutronInelasticProcess* theInelasticProcess = new G4NeutronInelasticProcess(); //================================= // Added by JLR 2005-07-05 //================================= // Options for secondary interaction models // Choice defined in jobOptions.mac, which is // read in before initialization of the run manager. // In the absence of this file, BINARY will be used. // GHEISHA = Original Geant4 default model // BERTINI = Bertini intra-nuclear cascade model // BINARY = Binary intra-nuclear cascade model if (gheishahad) { G4LENeutronInelastic* theInelasticModel = new G4LENeutronInelastic; theInelasticModel->SetMinEnergy(19*MeV); theInelasticProcess->RegisterMe(theInelasticModel); } else if (bertinihad) { G4CascadeInterface* theBertiniModel = new G4CascadeInterface; theBertiniModel->SetMinEnergy(19*MeV); theInelasticProcess->RegisterMe(theBertiniModel); } else if (binaryhad) { G4BinaryCascade* theBinaryModel = new G4BinaryCascade(); theBinaryModel->SetMinEnergy(19*MeV); theInelasticProcess->RegisterMe(theBinaryModel); G4LENeutronInelastic* theInelasticModel = new G4LENeutronInelastic; theInelasticModel->SetMinEnergy(10.1*GeV); theInelasticModel->SetMaxEnergy( 45.*GeV ); theInelasticProcess->RegisterMe(theInelasticModel); } else { G4cout << "No secondary interaction model chosen! Using G4 BINARY." << G4endl; G4BinaryCascade* theBinaryModel = new G4BinaryCascade(); theBinaryModel->SetMinEnergy(19*MeV); theInelasticProcess->RegisterMe(theBinaryModel); } G4HENeutronInelastic* theHEInelasticModel = new G4HENeutronInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); G4NeutronHPInelastic * theLENeutronInelasticModel = new G4NeutronHPInelastic; theInelasticProcess->RegisterMe(theLENeutronInelasticModel); G4NeutronHPInelasticData * theNeutronData1 = new G4NeutronHPInelasticData; theInelasticProcess->AddDataSet(theNeutronData1); pmanager->AddDiscreteProcess(theInelasticProcess); // capture G4HadronCaptureProcess* theCaptureProcess = new G4HadronCaptureProcess; G4LCapture* theCaptureModel = new G4LCapture; theCaptureModel->SetMinEnergy(19*MeV); theCaptureProcess->RegisterMe(theCaptureModel); G4NeutronHPCapture * theLENeutronCaptureModel = new G4NeutronHPCapture; theCaptureProcess->RegisterMe(theLENeutronCaptureModel); G4NeutronHPCaptureData * theNeutronData3 = new G4NeutronHPCaptureData; theCaptureProcess->AddDataSet(theNeutronData3); pmanager->AddDiscreteProcess(theCaptureProcess); // G4ProcessManager* pmanager = G4Neutron::Neutron->GetProcessManager(); // pmanager->AddProcess(new G4UserSpecialCuts(),-1,-1,1); } else if (particleName == "anti_neutron") { pmanager->AddDiscreteProcess(theElasticProcess); G4AntiNeutronInelasticProcess* theInelasticProcess = new G4AntiNeutronInelasticProcess(); G4LEAntiNeutronInelastic* theLEInelasticModel = new G4LEAntiNeutronInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); G4HEAntiNeutronInelastic* theHEInelasticModel = new G4HEAntiNeutronInelastic; theInelasticProcess->RegisterMe(theHEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "deuteron") { pmanager->AddDiscreteProcess(theElasticProcess); G4DeuteronInelasticProcess* theInelasticProcess = new G4DeuteronInelasticProcess(); G4LEDeuteronInelastic* theLEInelasticModel = new G4LEDeuteronInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "triton") { pmanager->AddDiscreteProcess(theElasticProcess); G4TritonInelasticProcess* theInelasticProcess = new G4TritonInelasticProcess(); G4LETritonInelastic* theLEInelasticModel = new G4LETritonInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } else if (particleName == "alpha") { pmanager->AddDiscreteProcess(theElasticProcess); G4AlphaInelasticProcess* theInelasticProcess = new G4AlphaInelasticProcess(); G4LEAlphaInelastic* theLEInelasticModel = new G4LEAlphaInelastic; theInelasticProcess->RegisterMe(theLEInelasticModel); pmanager->AddDiscreteProcess(theInelasticProcess); } } } //================================= // Added by JLR 2005-07-05 //================================= // Sets secondary hadronic interaction model // Note: this is currently only implemented for // protons and neutrons -- not pions. // Gheisha = Original Geant4 default // Bertini = Bertini intra-nuclear cascade model // Binary = Binary intra-nuclear cascade model void WCSimPhysicsList::SetSecondaryHad(G4String hadval) { SecondaryHadModel = hadval; if (SecondaryHadModel == "GHEISHA") { G4cout << "Secondary interaction model set to GHEISHA" << G4endl; gheishahad = true; bertinihad = false; binaryhad = false; } else if (SecondaryHadModel == "BERTINI") { G4cout << "Secondary interaction model set to BERTINI" << G4endl; gheishahad = false; bertinihad = true; binaryhad = false; } else if (SecondaryHadModel == "BINARY") { G4cout << "Secondary interaction model set to BINARY" << G4endl; gheishahad = false; bertinihad = false; binaryhad = true; } else { G4cout << "Secondary interaction model " << SecondaryHadModel << " is not a valid choice. BINARY model will be used." << G4endl; gheishahad = false; bertinihad = false; binaryhad = true; } } //----set cut values---- /* Setting cuts occurs in WCSimPhysicsListFactory.cc void WCSimPhysicsList::SetCuts() { if (verboseLevel >0){ G4cout << "WCSimPhysicsList::SetCuts:"; G4cout << "CutLength : " << G4BestUnit(defaultCutValue,"Length") << G4endl; } // set cut values for gamma at first and for e- second and next for e+, // because some processes for e+/e- need cut values for gamma // SetCutValue(defaultCutValue, "gamma"); SetCutValue(defaultCutValue, "e-"); SetCutValue(defaultCutValue, "e+"); if (verboseLevel>0) DumpCutValuesTable(); } */
#include<algorithm> #include<iostream> #include<stdio.h> using namespace std; #define N 100100 int num[N]; int main() { long long m,n,t,i,sum; while(~scanf("%lld %lld",&n,&m)) { sum=0; for(i=0; i<n; i++) scanf("%d",&num[i]); for(i=0; i<n-2; i++) { t=upper_bound(num,num+n,num[i]+m)-num; sum+=(t-i-1)*(t-i-2)/2; } cout << sum <<endl; } return 0; }
#include <sstream> #include "JsonServer.h" #include <stdexcept> using std::string; using std::ostringstream; JsonServer::JsonServer() : running(true) { } string JsonServer::process(const char *str) { return process(string(str)); } string JsonServer::process(const string &str) { Json::Reader reader; Json::Value request; if (reader.parse(str, request)) { Json::Value response = process(request); Json::FastWriter writer; return writer.write(response); } return "[0,\"Unable to parse the request\"]"; } Json::Value JsonServer::processSub(const string &sub, const Json::Value &request) { iterator it = find(sub); if (it != end()) { return it->second->process(request); } else { ostringstream oss; oss << "Unknown sub: " << sub; throw oss.str(); } } Json::Value JsonServer::process(const Json::Value &request) { Json::Value response; response[0] = 0; if (request.isArray() && request.size() >= 1 && request[0].isString()) { string command = request[0].asString(); Json::Value parameters; if (request.size() >= 2) { parameters = request[1]; } try { if (command == "sub") { if (parameters.isArray() && parameters.size() == 2) { return processSub(parameters[0].asString(), parameters[1]); } else { throw string("Malformed sub request"); } } else if (command == "ping") { response[0] = 1; response[1] = "pong"; } else { response[1] = handle(command, parameters); response[0] = 1; } } catch (string error) { response[1] = error; } catch (std::runtime_error e) { response[1] = e.what(); } catch (...) { response[1] = "Error while processing command"; } } else { response[1] = "Bad request"; } return response; } bool JsonServer::isRunning() { return running; } void JsonServer::stop() { running = false; }
#include "video.h" Video::Video() : Binary() { } Video::Video(const QString& id, const QString& titre, const QString &path, const QString &desc) : Binary(id,titre,path,desc) { } Note::NoteType Video::getType()const { return VIDEO; }
#ifndef COMPONENT_H_ #define COMPONENT_H_ #include "../ModelingTime.cpp" class Component{ private: static int countComponents; protected: double matrix[2][3]; int idComponent; public: Component(){ idComponent = countComponents; countComponents++; } virtual double* include(double value) = 0; int getId(){ return idComponent; } static bool comparate(Component* comp1 , Component* comp2){ return comp1 -> getId() < comp2 -> getId(); } }; int Component :: countComponents = 0; #endif
#include <iostream> #include "Animal.h" using std::cout; using std::endl; Animal::Animal( const int h, const int w ) { height = h; weight = w; } void Animal::print() const { cout << "This animal's height and weight are as follows\n" << "Height:" << height << "\tWeight: " << weight << endl << endl; } int Animal::getHeight() const { return height; } int Animal::getWeight() const { return weight; } void Animal::setHeight( const int h ) { height = h; } void Animal::setWeight( const int w ) { weight = w; }
#pragma once #include "../pch.h" struct GameReport { std::vector<int> cards; std::vector<int> victoryPoints; std::vector<int> coins; };
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll n; cin>>n; vector<int>v(n); set<int>st; for(int i=0;i<n;i++){ cin>>v[i]; st.insert(v[i]); } sort(v.begin(),v.end()); if(st.size()==1) { cout<<0<<" "; cout<<(n*(n-1))/(ll)2; } else { ll cnt1=1,cnt2=1,i=1,j=n-2; while(v[i]==v[0]&& i<n) { cnt1++; i++; } while(v[j]==v[n-1]&& j>=0) { cnt2++; j--; } cout<<v[n-1]-v[0]<<" "; cout<<cnt1*cnt2<<"\n"; } }
#include <Windows.h> #include "CubeApp.h" #include "Window.h" #include "Device.h" int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { CubeApp cube; App::Desc desc; desc.winDesc.title = "Cube App"; desc.winDesc.width = 800; desc.winDesc.height = 600; cube.run(desc); return 0; }
#pragma once #include "Types/vector3.h" class Object { public: Object(); virtual unsigned int getID() const = 0; protected: unsigned int ID; };
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QtGui> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { this->initialized = false; ui->setupUi(this); qApp->installEventFilter(this); this->ui->btnStop->setEnabled(false); ui->graphicsView->setMouseTracking(true); this->imgInfo = new ImageInfo(); this->imgInfo->setSourceNumber(ImageInfo::SourceNumber::One); this->tracker = new Tracker(this->imgInfo); // this->imgInfo = new ImageInfo(fileNames); // this->tracker = new Tracker(this->imgInfo, 10); // this->ui->horizontalSlider->setMaximum(this->imgInfo->getCapture()[0].get(CAP_PROP_FRAME_COUNT)); // this->ui->horizontalSlider->setMinimum(0); } void MainWindow::on_horizontalSlider_valueChanged(int value) { this->setCapturePosition(value); this->tracker->setFrameCount( (int)this->imgInfo->getCapture()[0].get(CAP_PROP_POS_FRAMES) ); this->tracker->incrementTime(); this->setImg(GuiUtils::Mat2QImg(this->imgInfo->getDispImg())); } void MainWindow::setCapturePosition(int pos) { //this->sendData(); this->imgInfo->setCaptureNumber((double) pos - 1.0); this->tracker->next(); } MainWindow::~MainWindow() { delete ui; } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if(event->type() == QEvent::MouseButtonPress) { if(obj != this) return false; if(obj == this->ui->frameCountLabel || obj == this->ui->constFrameLabel || obj == this->ui->btnInit || obj == this->ui->btnChooseExFile || obj == this->ui->btnStart || obj == this->ui->btnStop || obj == this->ui->btnTrain) return false; QMouseEvent *mEvent = static_cast<QMouseEvent*>(event); if(mEvent->x() < this->ui->graphicsView->x() || mEvent->y() < this->ui->graphicsView->y()) return false; if(mEvent->x() > this->ui->graphicsView->width() + this->ui->graphicsView->x() || mEvent->y() > this->ui->graphicsView->height() + this->ui->graphicsView->y()) return false; this->ui->coordinates->setText(QString::number(mEvent->x() - this->ui->graphicsView->x()) + ", " + QString::number(mEvent->y() - this->ui->graphicsView->y())); if(!(this->stopFlag)) { this->tracking(Point2f(mEvent->x() - this->ui->graphicsView->x(), mEvent->y() - this->ui->graphicsView->y())); // this->tracker->track(Point2f(mEvent->x() - this->ui->graphicsView->x(), mEvent->y() - this->ui->graphicsView->y())); } return true; } return false; } void MainWindow::init() { this->fileNames[0] = this->leftFileName; if(this->imgInfo->getSourceNumber() == ImageInfo::SourceNumber::Two) this->fileNames[1] = this->rightFileName; this->imgInfo->setCapture(this->fileNames); this->imgInfo->setup(true); this->ui->horizontalSlider->setMaximum(this->imgInfo->getCapture()[0].get(CAP_PROP_FRAME_COUNT)); this->ui->horizontalSlider->setMinimum(0); } void MainWindow::on_btnChooseSrcLeftFile_clicked() { this->leftFileName = GuiUtils::getFilePath(this); if(this->imgInfo->getSourceNumber() == ImageInfo::SourceNumber::One && this->leftFileName != "") { this->init(); return; } if(this->leftFileName != "" && this->rightFileName != "") this->init(); } void MainWindow::on_btnChooseSrcRightFile_clicked() { if(this->imgInfo->getSourceNumber() == ImageInfo::SourceNumber::One) { QMessageBox::warning(this, tr("Warning!"), tr("Please set Source Number '2'."), QMessageBox::Ok); return; } this->rightFileName = GuiUtils::getFilePath(this); if(this->leftFileName != "" && this->rightFileName != "") this->init(); } void MainWindow::on_btnChooseExFile_clicked() { this->tracker->setExFileName(GuiUtils::getFilePath(this)); } //void MainWindow::setCoordinates(QPointF pt) //{ // QString x = QString::number(pt.x()); // QString y = QString::number(pt.y()); // cout << "Coordinates are: " << x.toStdString() + " " << y.toStdString() << endl; //} void MainWindow::on_btnStart_clicked() { /*Validation area*/ if(this->tracker->getObjectNumber() == 0) { QMessageBox::warning(this, tr("Warning!"), tr("Please set object number!"), QMessageBox::Ok); return; } if(!this->initialized) { QMessageBox::warning(this, tr("Warning!"), tr("Please define corners of src image!"), QMessageBox::Ok); return; } if(!(this->tracker->validate())) { QMessageBox::warning(this, tr("Warning!"), tr("Please initialize Tracker!"), QMessageBox::Ok); return; } if(this->tracker->getExFileName() == "") { QMessageBox::warning(this, tr("Warning!"), tr("Please set export file name!"), QMessageBox::Ok); return; } this->stopFlag = false; this->ui->btnStart->setEnabled(false); this->ui->btnStop->setEnabled(true); /*Tracking start*/ char buff[20]; if(this->tracker->getAutomatic()) { while(!this->stopFlag) { if(this->currentId == this->tracker->getObjectNumber()) this->prepareTracker(); this->tracker->match(); QImage image = GuiUtils::Mat2QImg(this->imgInfo->getDispImg()); this->setImg(image); sprintf(buff, "%d", (int)this->tracker->getFrameCount()); ui->frameCountLabel->setText(QString(buff)); qApp->processEvents(); this->tracker->nextPlayer(); this->currentId = this->tracker->getCurrentId(); } } else { if(this->tracker->getExData() == NULL) { vector<struct exData*> *tmp = new vector<struct exData*>(); this->tracker->setExData(tmp); } /*TODO: Implement process of manual traking *like show message that tell user to start tracking *with click to pick position of current player. */ } } void MainWindow::tracking(Point2f pt) { if(this->tracker->getCurrentId() == this->tracker->getObjectNumber()) this->prepareTracker(); this->currPoint.x = stod(this->ui->coordinates->text().split(",")[0].toStdString()); this->currPoint.y = stod(this->ui->coordinates->text().split(",")[1].toStdString()); this->tracker->track(pt); this->currentId = this->tracker->getCurrentId(); this->setImg(GuiUtils::Mat2QImg(this->imgInfo->getDispImg())); } void MainWindow::setImg(QImage img) { // this->ui->graphicsView->resize(img.width, img.height); this->ui->isAutomatic->setEnabled(false); this->item = QPixmap::fromImage(img); this->scene = new QGraphicsScene(this); this->scene->addPixmap(item); this->ui->graphicsView->setScene(scene); this->ui->graphicsView->update(); this->ui->graphicsView->repaint(); this->ui->graphicsView->show(); } void MainWindow::on_btnStop_clicked() { this->stopFlag = true; this->ui->btnStart->setEnabled(true); this->ui->btnStop->setEnabled(false); this->ui->isAutomatic->setEnabled(true); this->sendData(); } void MainWindow::on_btnTrain_clicked() { // this->model->applyEM(this->matcher->getTmpMat(), 3); // this->matcher->setTrained(true); } void MainWindow::prepareTracker() { this->tracker->setCurrentId(0); this->currentId = this->tracker->getCurrentId(); this->tracker->next(); this->tracker->incrementTime(); this->setImg(GuiUtils::Mat2QImg(this->imgInfo->getDispImg())); } void MainWindow::on_btnInit_clicked() { if(this->leftFileName == "" && this->rightFileName == "" || this->imgInfo->getSourceNumber() == ImageInfo::SourceNumber::Two && this->rightFileName == "") { QMessageBox::warning(this, tr("Warning!"), tr("Please choose source file!"), QMessageBox::Ok); return; } if(this->imgInfo == NULL) { QMessageBox::warning(this, tr("Warning!"), tr("Please choose source file."), QMessageBox::Ok); } if(!(this->imgInfo->validate())) { QMessageBox::warning(this, tr("Warning!"), tr("Please initialize ImageInfo!"), QMessageBox::Ok); } SettingDialog *dialog = new SettingDialog(this, this->imgInfo->getSourceNumber() == ImageInfo::SourceNumber::One ? 1 : 2, GuiUtils::Mat2QImg(this->imgInfo->getTmpLeftImg()), GuiUtils::Mat2QImg(this->imgInfo->getTmpRightImg()), QSize(this->imgInfo->getCapture()[0].get(CAP_PROP_FRAME_WIDTH), this->imgInfo->getCapture()[0].get(CAP_PROP_FRAME_HEIGHT))); dialog->exec(); if(dialog->result() == QDialog::Accepted) { this->imgInfo->setSrcPtLeft(dialog->getSrcPtLeft()); if(this->imgInfo->getSourceNumber() == ImageInfo::SourceNumber::Two) this->imgInfo->setSrcPtRight(dialog->getSrcPtRight()); this->imgInfo->setDstSize(Size(537, 269)); this->imgInfo->setWarpPerspective(); this->imgInfo->setInitialized(true); this->initialized = true; this->imgInfo->setup(); this->imgInfo->setDispImg(this->imgInfo->getTmpImg()); this->setImg(GuiUtils::Mat2QImg(this->imgInfo->getDispImg())); } } void MainWindow::on_isAutomatic_stateChanged(int arg1) { if(arg1 == Qt::Checked) { this->tracker->setAutomatic(true); if(!(this->ui->btnStart->isEnabled())) this->ui->btnStart->setEnabled(true); if(this->tracker->getCurrentId() - this->currentId > 0) { cout << "Please track other "; cout << this->tracker->getObjectNumber() - this->currentId; cout << " number objects. Then can track automatic." << endl; } } else { this->tracker->setAutomatic(false); if(!(this->ui->btnStart->isEnabled())) this->ui->btnStart->setEnabled(true); } } void MainWindow::on_btnCommit_clicked() { this->sendData(); } void MainWindow::sendData() { if(this->tracker->getExData() == NULL || this->tracker->getExData()->size() == 0) return; vector<struct exData*>::iterator begin, end; begin = this->tracker->getExData()->begin(); end = this->tracker->getExData()->end(); for(; begin != end; begin++) { this->tracker->exportData(*begin); vector<struct exData*> *newVec = new vector<struct exData*>(); this->tracker->setExData(newVec); } } void MainWindow::on_btnPreview_clicked() { vector<struct exData*> *tmp = this->tracker->getExData(); tmp->pop_back(); if(this->tracker->getCurrentId() == 0) { this->tracker->setFrameCount(this->tracker->getFrameCount() - 1); this->tracker->setTimeStamp(this->tracker->getTimeStamp() - 0.03); this->tracker->setCurrentId(this->tracker->getObjectNumber()); this->imgInfo->setCaptureNumber(this->imgInfo->getCaptureNumber() - 1); } else this->tracker->setCurrentId(this->tracker->getCurrentId() - 1); } void MainWindow::on_btnOk_clicked() { int objNum = this->ui->txtObjectNumber->text().toInt(); this->tracker->setObjectNumber(objNum); } void MainWindow::on_btnSouceNumberOk_clicked() { this->imgInfo->setSourceNumber(this->ui->txtSourceNumber->text().toInt() == 1 ? ImageInfo::SourceNumber::One : ImageInfo::SourceNumber::Two); }
#include "bnb_MPI.cpp" class TSP_Problem; class TSP_Solution: public Solution{ public: int cost; vector<int> taken; // list of vertices traversed int pos; // length of the current path int get_cost(); bool is_feasible(); void print_sol(); int get_bound(); int to_str(char *buf); }; class TSP_Problem: public Problem<TSP_Solution>{ public: vector<vector<int> > graph; int n; // num of vertices in the graph int min_edge; bool get_goal(); TSP_Solution empty_sol(); TSP_Solution worst_sol(); vector<TSP_Solution> expand(TSP_Solution s); int to_str(char *buf); static TSP_Problem decode_prob(char *buf, int &pos); static TSP_Solution decode_sol(char *buf, int &pos); }; /* ----------------- method defs: ------------------------------ */ int TSP_Solution::to_str(char *buf){ int p = 0; p += sprintf(buf+p," %d %d ",pos,cost); for(int i=0;i<pos;i++) p += sprintf(buf+p," %d ",taken[i]); return p; } TSP_Solution TSP_Problem::decode_sol(char *buf, int &pos){ TSP_Solution s; int b; sscanf(buf+pos,"%d%d%n",&(s.pos),&(s.cost),&b); pos += b; for(int i=0;i<s.pos;i++){ int temp; sscanf(buf+pos,"%d%n",&temp,&b); pos += b; s.taken.push_back(temp); } return s; } int TSP_Problem::to_str(char *buf){ int p = 0; p += sprintf(buf+p," %d %d ",n,min_edge); for(int i=0;i<n;i++) for(int j=0;j<n;j++) p += sprintf(buf+p," %d ",graph[i][j]); return p; } TSP_Problem TSP_Problem::decode_prob(char *buf, int &pos){ TSP_Problem prob; int b; sscanf(buf+pos,"%d%d%n",&(prob.n),&(prob.min_edge),&b); pos += b; for(int i=0;i<prob.n;i++){ vector<int> v; for(int j=0;j<prob.n;j++){ int temp; sscanf(buf+pos,"%d%n",&temp,&b); pos += b; v.push_back(temp); } prob.graph.push_back(v); } return prob; } int TSP_Solution::get_cost(){ return cost; } int TSP_Solution::get_bound(){ // need to give a lower bound! int left = (((TSP_Problem *)prob_ptr)->n) - taken.size(); return cost+(left*(((TSP_Problem *)prob_ptr)->min_edge)); /*t bound = cost; for(int i=pos;i<((TSP_Problem *)prob_ptr)->n;i++){ bound += ((TSP_Problem *)prob_ptr) -> costs[i]; } // loose upper bound assuming all remaining items are taken return bound;*/ } bool TSP_Solution::is_feasible(){ //cout<<"checking feasibility"<<endl; return (pos == (((TSP_Problem *) prob_ptr) -> n)); /* if(pos == (((TSP_Problem *)prob_ptr)->n)) { bool flag[((TSP_Problem *)prob_ptr)->n]; for(int i=0;i<((TSP_Problem *)prob_ptr)->n;i++) flag[i] = false; for(int i=0;i<taken.size();i++) { if(!flag[taken[i]]) flag[taken[i]] = true; else return false; } return true; } return false;*/ } void TSP_Solution::print_sol(){ cout<<"Minimum cost of "<<cost<<" achieved for the path with vertices "; for(int i=0;i<taken.size();i++) cout<<taken[i]<<", "; cout<<endl; } bool TSP_Problem::get_goal(){ return false; // it is a minimization problem } TSP_Solution TSP_Problem::empty_sol(){ TSP_Solution s1; // include the starting vertex s1.pos = 0; s1.prob_ptr = this; s1.cost = 0; return s1; } TSP_Solution TSP_Problem::worst_sol(){ TSP_Solution s1; s1.prob_ptr = this; s1.cost = 100000000; s1.pos = 0; return s1; } vector<TSP_Solution> TSP_Problem::expand(TSP_Solution s){ bool flag[((TSP_Problem*)s.prob_ptr)->n]; vector<TSP_Solution> ret; memset(flag,false,sizeof(flag)); for(int i=0;i<s.taken.size();i++) { flag[s.taken[i]] = true; } if(s.taken.size()==0) { for(int i=0;i<((TSP_Problem *)s.prob_ptr)->n;i++) { TSP_Solution first = s; first.pos = 1; first.taken.push_back(i); ret.push_back(first); } return ret; } for(int i=0;i<((TSP_Problem *)s.prob_ptr)->n;i++) { if(!flag[i]) { TSP_Solution s1 = s; s1.pos++; s1.taken.push_back(i); int prev; prev = s1.taken[s1.taken.size()-2]; //cout<<"Position of the new q element"<<s1.pos<<endl; s1.cost += graph[prev][i]; ret.push_back(s1); //return; } } return ret; } int main(){ TSP_Problem p; BnB_solver<TSP_Problem, TSP_Solution> bnbs; cin>>p.n; p.min_edge = 1000000; for(int i=0;i<p.n;i++){ vector<int> temp; for(int j=0;j<p.n;j++) { int val; cin>>val; p.min_edge = min(p.min_edge,val); temp.push_back(val); } p.graph.push_back(temp); } bnbs.solve(p); return 0; }
#include <memory> #include "simphys/force_generator.h" #include "simphys/vec3.h" #include "simphys/particle.h" #include "simphys/force_wind.h" namespace simphys { using std::shared_ptr; class vec3; class Particle; // Assign gravity value to force (arbitrary direction) ForceWind::ForceWind ( const vec3 _wind ) : wind{ _wind } {} // Updated particle with gravity void ForceWind::update ( shared_ptr<Particle> p, fsecond dt ) { if ( p->getMass() <= 0 ) return; p->applyForce( wind ); } }
// https://www.hackerearth.com/practice/algorithms/graphs/articulation-points-and-bridges/tutorial/ #include <cstdio> #include <vector> #include <list> #include <set> using namespace std; int n; vector<bool> vis; vector<int> tin, low; vector<list<int>> adj; set<int> articulation_points; set<pair<int, int>> bridges; int timer; void tarjan(int u = 0, int p = -1) { vis[u] = true; tin[u] = low[u] = timer++; int children = 0; for (int child: adj[u]) { if (child == p) { continue; } if (vis[child]) { low[u] = min(low[u], tin[child]); } else { tarjan(child, u); low[u] = min(low[u], low[child]); if (low[child] > tin[u]) { bridges.insert({min(u, child), max(u, child)}); } if (low[child] >= tin[u] && p != -1) { articulation_points.insert(u); } ++children; } } if (p == -1 && children > 1) { articulation_points.insert(u); } } void init() { int m; scanf("%d %d", &n, &m); adj.resize(n); vis.resize(n); tin.resize(n); low.resize(n); int u, v; while (m--) { scanf("%d %d", &u, &v); adj[u].push_back(v); adj[v].push_back(u); } } int main() { init(); tarjan(); printf("%lu\n", articulation_points.size()); for (const auto &art_pt: articulation_points) { printf("%d ", art_pt); } printf("\n%lu\n", bridges.size()); for (const pair<int, int> &bridge: bridges) { printf("%d %d\n", bridge.first, bridge.second); } return 0; }
#include <iostream> #include "requests.h" #include "import.h" using std::cout; using std::cin; using std::endl; int main(int argc, char *argv[]) { if (argc != 2) return 1; Requests requests; cin >> requests; Import import(requests); auto ret = import.import(argv[1]); if (ret) return ret; cout << requests << endl; return 0; }
#include <Segments/Visitor.hpp> #include <iscore/actions/Menu.hpp> #include <QInputDialog> #include "iscore_addon_segments.hpp" #include <iscore/actions/ActionManager.hpp> #include <iscore/actions/MenuManager.hpp> namespace Segments { struct ApplicationPlugin : public QObject, public iscore::GUIApplicationPlugin { public: using iscore::GUIApplicationPlugin::GUIApplicationPlugin; GUIElements makeGUIElements() override { // This will add a button in File > Export. auto& m = context.menus.get().at(iscore::Menus::Export()); QMenu* menu = m.menu(); auto act = new QAction{QObject::tr("Segments example"), this}; menu->addAction(act); connect(act, &QAction::triggered, this, [=] { if(auto doc = this->currentDocument()) { QInputDialog::getMultiLineText( nullptr, "Segments", "Segments", PrintScenario(doc->context())); } }); return {}; } }; } iscore_addon_segments::iscore_addon_segments() = default; iscore::GUIApplicationPlugin* iscore_addon_segments::make_guiApplicationPlugin( const iscore::GUIApplicationContext& app) { return new Segments::ApplicationPlugin{app}; } iscore::Version iscore_addon_segments::version() const { return iscore::Version{1}; } UuidKey<iscore::Plugin> iscore_addon_segments::key() const { return_uuid("e64a847a-fdf6-453d-9902-608885d3707f"); }
#include <iostream> #include <string> #include <fstream> #include <iomanip> using namespace std; //function prototypes void readLines(fstream *file, int&, string, string *); void searchArray(string, string *, int); void requestUserInput(string&); //main Function int main() { //declaring all variables fstream file; file.open("phonenumbers.txt"); int numOfPpl = 0; const int size = 20; string line; string *phoneArray = new string[size]; string userInput; //Calling functions readLines(&file, numOfPpl, line, phoneArray); requestUserInput(userInput); searchArray(userInput, phoneArray, size); cout << "The number of people in this list is: " << numOfPpl << endl; cout << endl; system("pause"); } //Function that will read the entire file and display the numbers to the console //as well as place the lines into the phoneArray void readLines(fstream *file, int& numOfPpl, string line, string *phoneArray) { while (getline(*file, line)) { //getline(*file, line); phoneArray[numOfPpl] = line; numOfPpl++; } cout << "Here is the list of everyone in the PhoneBook File!" << endl; cout << endl; for (int i = 0; i < 20; i++) { cout << phoneArray[i] << endl; } cout << endl; cout << endl; } //Function that will ask for the user input void requestUserInput(string& userInput) { cout << "Please enter the name or partial number you wish to search! "; cin >> userInput; cout << endl; } //Function that will check the user input to the array and tell us if there //are any matches and display them to the console void searchArray(string userInput, string *phoneArray, int size) { bool match = false; cout << "Here are the results that were found!" << endl; for (int i = 0; i < size; i++) { if (phoneArray[i].find(userInput) != -1) { cout << phoneArray[i] << endl; match = true; } } cout << endl; if (!match) { cout << "No matches were found with the term: " << userInput << endl; } }
#include "grayimage.h" #include"note.h" GrayImage::GrayImage(string fileName) { this->bmpfileheader=new BITMAPFILEHEADER; this->bmpinfoheader=new BITMAPINFOHEADER; this->rgbquad=new RGBQUAD[256]; this->fileName=fileName; dialog=new QProgressDialog; //设置进度对话框采用模态方式进行,即显示进度的同时,其他窗口将不响应输入信号 dialog->setWindowModality(Qt::WindowModal); //设置进度对话框出现需等待的时间,默认为4s dialog->setMinimumDuration(5); //设置进度对话框的窗体标题 dialog->setWindowTitle(QObject::tr("Please Wait")); dialog->setRange(0,300); //设置进度对话框的步进范围 //设置进度对话框的“取消”按钮的显示文字 dialog->setCancelButtonText(QObject::tr("Cancel")); } bool GrayImage::ReadBitmap() { wchar_t strUnicode[260]; UTF8ToUnicode(this->fileName.c_str(), strUnicode); FILE* fp=_wfopen(strUnicode,L"rb"); if(fp==NULL){ QMessageBox::critical(NULL,"error","打开文件失败.","ok"); return false; } fread(bmpfileheader,sizeof(BITMAPFILEHEADER),1,fp); fread(bmpinfoheader,sizeof(BITMAPINFOHEADER),1,fp); // showBmpHead(*bmpfileheader); // showBmpInforHead(*bmpinfoheader); this->rgb_count=(bmpfileheader->bfOffBits-54)/4; fread(rgbquad,sizeof(RGBQUAD),this->rgb_count,fp); // bmpWidth=(bmpinfoheader->biWidth+3)/4*4; bmpWidth=bmpinfoheader->biWidth; bmpHeight=bmpinfoheader->biHeight; //qDebug()<<bmpfileheader->bfOffBits; img=new BYTE*[bmpHeight]; for(int i=0;i<bmpHeight;++i){ img[i]=new BYTE[bmpWidth]; fread(img[i],1,bmpWidth,fp); } fclose(fp); return true; } bool GrayImage::Compress() { this->Linearization(); int count=this->bmpHeight*this->bmpWidth; dialog->setLabelText(QObject::tr("Compressing..."));//设置进度对话框的显示文字信息 unsigned int *s=new unsigned int[count+1];//纪录分段位置 unsigned int *l=new unsigned int[count+1];//纪录每段长度 unsigned int *b=new unsigned int[count+1];//纪录每段位数 this->dp(count,this->imgline,s,l,b); int m=this->Output(s,l,b,count); string nfileName=this->fileName.substr(0,fileName.length()-4); nfileName+=".img"; wchar_t strUnicode[260]; UTF8ToUnicode(nfileName.c_str(), strUnicode); FILE *nfp=_wfopen(strUnicode,L"wb"); if(nfp==NULL){ QMessageBox::critical(NULL,"error","打开文件失败.","ok"); return false; } //写入头文件信息 fwrite(this->bmpfileheader,sizeof(BITMAPFILEHEADER),1,nfp); fwrite(this->bmpinfoheader,sizeof(BITMAPINFOHEADER),1,nfp); fwrite(this->rgbquad,sizeof(RGBQUAD),this->rgb_count,nfp); fseek(nfp,this->bmpfileheader->bfOffBits,SEEK_SET); fwrite(&m,sizeof(m),1,nfp); /******************************************************/ // int index=1;//要读取的位置 unsigned char value=0;//每次写入八位 size_t pos=0; unsigned int t; for(int i=1;i<=m;i++){ dialog->setValue(200+i/m*100); if(dialog->wasCanceled()){ fclose(nfp); remove(nfileName.c_str()); return false; } size_t a=8; t=l[i]-1; while (a>0) { value=(value<<1)|((t>>(a-1))&1); if (++pos == 8) { fputc(value, nfp); value = 0; pos = 0; } --a; } a=3; t=b[i]-1; // qDebug()<<b[i]; while (a>0) { value=(value<<1)|((t>>(a-1))&1); if (++pos == 8) { fputc(value, nfp); value = 0; pos = 0; } --a; } for(size_t j=1;j<=l[i];j++){ size_t tmp=b[i]; while (tmp>0) {//? value=(value<<1)|((imgline[s[i-1]+j]>>(tmp-1))&1); if (++pos == 8) { fputc(value, nfp); value = 0; pos = 0; } --tmp; } } } if (pos) { value=value << (8 - pos); fputc(value, nfp); } fclose(nfp); return true; } bool GrayImage::Linearization() { this->ReadBitmap(); this->imgline=new unsigned char[this->bmpWidth*this->bmpHeight+1]; imgline[0]=0; int k=1; for(int i=0;i<bmpHeight;i++){ if(i%2==0){ for(int j=0;j<bmpWidth;j++){ imgline[k++]=img[i][j]; } }else { for(int j=bmpWidth-1;j>=0;j--){ imgline[k++]=img[i][j]; } } } return true; } bool GrayImage::UnCompress() { dialog->setLabelText(QObject::tr("Compressing..."));//设置进度对话框的显示文字信息 wchar_t strUnicode[260]; UTF8ToUnicode(this->fileName.c_str(), strUnicode); FILE *fp=_wfopen(strUnicode,L"rb"); if(fp==NULL){ QMessageBox::critical(NULL,"error","打开文件失败.","ok"); return false; } fread(bmpfileheader,sizeof(BITMAPFILEHEADER),1,fp); fread(bmpinfoheader,sizeof(BITMAPINFOHEADER),1,fp); this->rgb_count=(bmpfileheader->bfOffBits-54)/4; fread(rgbquad,sizeof(RGBQUAD),this->rgb_count,fp); // fseek(fp,bmpfileheader->bfOffBits,SEEK_SET); // bmpWidth=(bmpinfoheader->biWidth+3)/4*4; bmpWidth=bmpinfoheader->biWidth; bmpHeight=bmpinfoheader->biHeight; this->imgline=new unsigned char[this->bmpWidth*this->bmpHeight+1]; int m;//多少段 fread(&m,sizeof(m),1,fp); unsigned char value=0; unsigned int l=0,b=0; int pos=0;size_t tmp; int index=0; // qDebug()<<this->bmpWidth*this->bmpHeight; for(int i=0;i<m;i++){ this->dialog->setValue((i*200)/m); if(dialog->wasCanceled()){ fclose(fp); return false; } l=0;b=0; tmp=0; while (tmp<8) { if(pos==0){ value=fgetc(fp); pos=8; } --pos; l=(l<<1)|((value>>pos)&1); ++tmp; } tmp=0; while (tmp<3) { if(pos==0){ value=fgetc(fp); pos=8; } --pos; b=(b<<1)|((value>>pos)&1); ++tmp; } for(size_t j=0;j<=l;j++){ tmp=0; imgline[index]=0; while (tmp<=b) { if(pos==0){ value=fgetc(fp); pos=8; } --pos; this->imgline[index]=(imgline[index]<<1)|((value>>(pos))&1); ++tmp; } ++index; } } fclose(fp); return UnLinearization(); } bool GrayImage::UnLinearization() { string nfileName=this->fileName.substr(0,fileName.length()-4); nfileName+="_decompress.bmp"; wchar_t strUnicode[260]; UTF8ToUnicode(nfileName.c_str(), strUnicode); FILE *nfp=_wfopen(strUnicode,L"wb"); if(nfp==NULL){ QMessageBox::critical(NULL,"error","创建文件失败.","ok"); return false; } fwrite(this->bmpfileheader,sizeof(BITMAPFILEHEADER),1,nfp); fwrite(this->bmpinfoheader,sizeof(BITMAPINFOHEADER),1,nfp); fwrite(this->rgbquad,sizeof(RGBQUAD),this->rgb_count,nfp); int index=0; for(int i=0;i<bmpHeight;i++){ this->dialog->setValue(200+((i+1)*100)/bmpHeight); if(dialog->wasCanceled()){ fclose(nfp); remove(nfileName.c_str()); return false; } if(i%2==0){ for(int j=0;j<bmpWidth;j++){ fputc(imgline[index++],nfp); } }else { for(int j=bmpWidth;j>0;j--){ fputc(imgline[index+j-1],nfp); } index+=bmpWidth; } } fclose(nfp); return true; } void GrayImage::dp(int n, unsigned char p[], unsigned int s[], unsigned int l[], unsigned int b[]) { int Lmax = 256,header = 11; s[0] = 0; for(int i=1; i<=n; i++) { if(i%100==0){ dialog->setValue((i*200)/n); } b[i] = length(p[i]);//计算像素点p需要的存储位数 int bmax = b[i]; s[i] = s[i-1] + bmax; l[i] = 1; for(int j=2; j<=i && j<=Lmax;j++)//i=1时,不进入此循环 { if(bmax<b[i-j+1]) { bmax = b[i-j+1]; } if(s[i]>s[i-j]+j*bmax) { s[i] = s[i-j] + j*bmax; l[i] = j; } } s[i] += header; } } void GrayImage::Traceback(int n, int &i, unsigned int s[], unsigned int l[]) { if(n==0) return; Traceback(n-l[n],i,s,l);//p1,p2,p3,...,p(n-l[n])像素序列,最后一段有l[n]个像素 s[i++]=n-l[n];//重新为s[]数组赋值,用来存储分段位置,最终i为共分了多少段 // if (n == 0) // return; // Traceback(n - l[n], m, s, l);//s[i]纪录第i段到的位置 // s[m++] = n - l[n]; //重新为s[]数组赋值,用来存储分段位置 } int GrayImage::Output(unsigned int s[], unsigned int l[], unsigned int b[], int n) { int m = 0; Traceback(n,m,s,l);//s[0]:第一段从哪分,s[1]:第二段从哪分...,s[m-1]第m段从哪分 s[m] = n;//此时m为总段数,设s[m]=n,分割位置为第n个像素 // qDebug()<<"将原灰度序列分成"<<m<<"段序列段"<<endl; for(int j=1; j<=m; j++) { l[j] = l[s[j]]; // b[j] = b[s[j]]; } for (int j = 1; j <= m; j++) { b[j] = b[s[j - 1] + 1]; for (int i = s[j-1] + 1; i <= s[j-1] + l[j];i++) { b[j] = max(b[j], b[i]); } } // for (int j = 1; j <= m; j++) // { // qDebug() << "l" << l[j] << ",b:" << b[j] <<"s"<<s[j-1]; // } return m;//段数 } int GrayImage::length(unsigned char n) { if(!n)return 1; int c = 0; // counter for(; n; n >>= 1) ++c ; return c ; } bool GrayImage::UTF8ToUnicode(const char *UTF8, wchar_t *strUnicode) { DWORD dwUnicodeLen; //转换后Unicode的长度 TCHAR *pwText; //保存Unicode的指针 // wchar_t* strUnicode; //返回值 //获得转换后的长度,并分配内存 dwUnicodeLen = MultiByteToWideChar(CP_UTF8,0,UTF8,-1,NULL,0); pwText = new TCHAR[dwUnicodeLen]; if(!pwText) { return false; } //转为Unicode MultiByteToWideChar(CP_UTF8,0,UTF8,-1,pwText,dwUnicodeLen); //转为CString wcscpy(strUnicode, pwText); //清除内存 delete[] pwText; return true; }
// // Created by Liang on 2019-07-14. // #include <string> #include <iostream> #include <cstring> using namespace std; class Solution { public: string longestPalindrome(string s) { // 计算字符串的最长子字符串 if(s.length() == 0) return ""; string new_s = ""; for(auto c: s){ new_s += '#'; new_s += c; } new_s += '#'; int size = new_s.length(); int mp[size]; // 代表每个点所对应的回文字符串的长度 int idx = 0; int mx = 1; mp[0] = 1; cout<<new_s<<endl; for(int i=1;i<size;i++){ mp[i] = i < mx ? min(mp[2 * idx - i], mx - i) : 1; while((i-mp[i]) >= 0 && (i + mp[i]) < size && new_s[i-mp[i]] == new_s[i + mp[i]]) mp[i] += 1; if(mx < mp[i]){ mx = i + mp[i]; idx = i; } } string res = ""; for(int i=2*idx-mx;i<=mx;i++){ if(new_s[i] == '#') continue; res += new_s[i]; } return res; } static void solution(){ Solution solution1; string input_str = "cbbd"; cout<<solution1.longestPalindrome(input_str)<<endl; } };
#ifndef FORMATINPUT_H #define FORMATINPUT_H #include <QObject> #include <QQmlComponent> /* This function formats the data input while the user is typing example ---> ( AB CD 45 73 ) */ class FormatInput : public QObject { Q_OBJECT public: explicit FormatInput(QObject *parent = 0); Q_INVOKABLE QString formatData(QString arg_text); //data input field formatting Q_INVOKABLE QString formatId(QString arg_text); //id input field formatting Q_INVOKABLE QString deleteLastChar(QString arg_text); //delete button function signals: public slots: }; #endif // FORMATINPUT_H
// // Created by 梁栋 on 2019-01-10. // #include <iostream> #include <vector> using namespace std; class Solution { public: string longestCommonPrefix(vector<string>& strs) { int pos = 0; string res = ""; if(strs.size() == 0){ return res; } if(strs.size() == 1){ return strs[0]; } while(true){ bool equal_flag = true; for(int i=0;i<strs.size()-1;i++){ if(pos<strs[i].length() && pos < strs[i+1].length() && strs[i][pos] == strs[i+1][pos]){ continue; }else{ equal_flag = false; break; } } if(not equal_flag){ break; } res += strs[0][pos]; pos += 1; } return res; } }; class LongestCommonPrefix { public: static void test(){ Solution solution = Solution(); vector<string> strs = vector<string>(); strs.push_back("flower"); strs.push_back("flows"); strs.push_back("flight"); cout<<solution.longestCommonPrefix(strs)<<endl; } };
//************************************************************************************************* //************************************************************************************************* //* The MIT License (MIT) * //* Copyright (C) 2019 Ivan Matic, Rados Radoicic, and Dan Stefanica * //* * //* 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"GCOpenCL.h" void deleteStrin_gListInGC(Strin_gList* first){ if(first->next!=0){ deleteStrin_gListInGC(first->next); } delete first; } GraphicCard::GraphicCard(std::string programName,mysint forceCPU){ contextGC=nullptr; commandQueueGC=nullptr; programGC=nullptr; deviceGC=0; kernflsGC=nullptr; numMemObjectsGC=0; memObjectsGC=nullptr; numberOfKernelsGC=0; preferred_workgroup_sizeGC=new size_t; *preferred_workgroup_sizeGC=128; variablesCorrectlySetInKernelGC=nullptr; kernelPreLoadedGC="gc_parallel_rnum.cl"; axisSizeGC=new myint; *axisSizeGC=0; xAxisGC=nullptr; yAxisGC=nullptr; randNumbersGC=nullptr; lengthInBinaryGC=new myint; *lengthInBinaryGC=0; shufflingPrimeGC=new myint; *shufflingPrimeGC=3; numBalancedNumbersGC=new myint; *numBalancedNumbersGC=0; xPermutationsGC=nullptr; yPermutationsGC=nullptr; indFirstRNInitGC=0; inspectorExecutedGC=0; sampleGenKernExecutedGC=0; uniformLimitGC=10000; currentSeedGC=std::chrono::high_resolution_clock::now().time_since_epoch().count(); overrideAntiteticGC=0; powersOfTwoGC=nullptr; balancedNumbersGC=nullptr; contextGC=CreateContext(forceCPU); kernelFileGC=programName; pascalTriangleGC=nullptr; sizePascalTrGC=new myint; *sizePascalTrGC=0; highestPrecisionGC=new myint; *highestPrecisionGC=100000; precisionRequestGC=new myint; *precisionRequestGC=0; exponentKGC=new myint; *exponentKGC=3; sizeForRejectionSamplingGC=new myint; *sizeForRejectionSamplingGC=5; sampleLengthGC=new myint; *sampleLengthGC=0; antitheticGC=1; parameter1GC=new cl_double; *parameter1GC=0; parameter2GC=new cl_double; *parameter2GC=1; randomSampleGC=nullptr; inspectorRejSampGC=nullptr; kernelResponsibilitiesGC=nullptr; randSampGC="randSampGCCL"; normalBSMNameGC="normalBSMGC"; exponentialDistNameGC="exponentialDistGC"; createFenwickGC="createFenwickGC"; justSummationFenwickGC="justSummationFenwickGC"; partialSumsFTreeGC="partialSumsFTreeGC"; partialSumsPSSGC="partialSumsPSSGC"; shiftCalculationMergSortIncGC="shiftCalculationMergSortIncGC"; shiftCalculationMergSortDecGC="shiftCalculationMergSortDecGC"; copyResultToStartGC="copyResultToStartGC"; shiftCalculationMergSortFollIncGC="shiftCalculationMergSortFollIncGC"; shiftCalculationMergSortFollDecGC="shiftCalculationMergSortFollDecGC"; copyResultToStartFollGC="copyResultToStartFollGC"; normalBSMAntNameGC="normalBSMAntitheticGC"; origNamePSSGC="origNamePSSGC"; namePSSGC="namePSSGC"; lengthNamePSSGC="lengthNamePSSGC"; nameBlockSizePSSGC="nameBlockSizePSSGC"; kernelNameStage1PSSGC="stage1PSSGC"; kernelNameStage2PSSGC="stage2PSSGC"; posVariableNamePSSGC="positionNamePSSGC"; blockSizePSSGC=*preferred_workgroup_sizeGC; lengthValuePSSGC=-1; lastRandAlgUsedGC=-1; mysint shouldQuit=0; if (contextGC == nullptr) { std::cerr << "Failed to create OpenCL context." << std::endl; shouldQuit=1; } if(shouldQuit==0){ commandQueueGC = CreateCommandQueue(contextGC, &deviceGC); } if((shouldQuit==0)&& (commandQueueGC == nullptr)) { Cleanup(); shouldQuit= 1; } if(shouldQuit==0){ const char * cChar = kernelFileGC.c_str(); programGC = CreateProgram(contextGC, deviceGC, cChar); } if((shouldQuit==0)&&(programGC == nullptr)) { Cleanup(); shouldQuit=1; } } mysint GraphicCard::overrideAntitetic(myint ov){ overrideAntiteticGC=ov; return 1; } mysint GraphicCard::findAddKernel(std::string nameToAdd, mysint preventAddition){ mysint i=0; mysint foundName=-1; std::map<std::string, myint>::iterator it; it=kernelNamesGC.find(nameToAdd); if(it!=kernelNamesGC.end()){ foundName=it->second; } if((foundName==-1)&&(preventAddition==0)){ cl_kernel *newKernfls; mysint *newVarCS; newKernfls=new cl_kernel[numberOfKernelsGC+1]; newVarCS=new mysint[numberOfKernelsGC+1]; for(i=0;i<numberOfKernelsGC;++i){ newKernfls[i]=kernflsGC[i]; newVarCS[i]=variablesCorrectlySetInKernelGC[i]; } if(numberOfKernelsGC>0){ delete[] kernflsGC; delete[] variablesCorrectlySetInKernelGC; } kernflsGC=newKernfls; variablesCorrectlySetInKernelGC=newVarCS; kernelNamesGC.insert(std::make_pair(nameToAdd,numberOfKernelsGC));; const char * cChar = nameToAdd.c_str(); cl_int error_ret; kernflsGC[numberOfKernelsGC]=clCreateKernel(programGC,cChar,&error_ret); myint jErr=0; while((jErr<1000)&&(error_ret!=0)){ kernflsGC[numberOfKernelsGC]=clCreateKernel(programGC,cChar,&error_ret); ++jErr; } if(numberOfKernelsGC<3){ clGetKernelWorkGroupInfo (kernflsGC[numberOfKernelsGC], deviceGC, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(size_t), preferred_workgroup_sizeGC, nullptr); } variablesCorrectlySetInKernelGC[numberOfKernelsGC]=0; numberOfKernelsGC++; } return foundName; } cl_context GraphicCard::CreateContext(mysint forceCPU) { cl_int errNum; cl_uint numPlatforms; cl_platform_id firstPlatformId; cl_context context = nullptr; errNum = clGetPlatformIDs(1, &firstPlatformId, &numPlatforms); if (errNum != CL_SUCCESS || numPlatforms <= 0) { std::cerr << "No OpenCL platforms." << std::endl; return nullptr; } cl_context_properties contextProperties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)firstPlatformId, 0 }; //Select GPU: if(forceCPU==0){ context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU,nullptr, nullptr, &errNum); if (errNum != CL_SUCCESS) { std::cout << "No GPU context. Trying CPU." << std::endl; context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU, nullptr, nullptr, &errNum); if (errNum != CL_SUCCESS) { std::cerr << "Failed to create an OpenCL GPU or CPU context." << std::endl; return nullptr; } } } //Comparison: Select CPU: if(forceCPU==1){ context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_CPU, nullptr, nullptr, &errNum); if (errNum != CL_SUCCESS) { std::cerr << "Failed to create an OpenCL CPU context." << std::endl; return nullptr; } } return context; } cl_command_queue GraphicCard::CreateCommandQueue(cl_context context, cl_device_id *device) { cl_int errNum; cl_device_id *devices; cl_command_queue commandQueue = nullptr; size_t deviceBufferSize = -1; // First get the size of the devices buffer errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, nullptr, &deviceBufferSize); if (errNum != CL_SUCCESS) { std::cerr << "Failed call to clGetContextInfo(...,GL_CONTEXT_DEVICES,...)"; return nullptr; } if (deviceBufferSize <= 0) { std::cerr << "No devices available."; return nullptr; } // Allocate memory for the devices buffer myint numDevices=(myint)(deviceBufferSize / sizeof(cl_device_id)); devices = new cl_device_id[deviceBufferSize / sizeof(cl_device_id)]; errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, deviceBufferSize, devices, nullptr); if (errNum != CL_SUCCESS) { delete [] devices; std::cerr << "Failed to get device IDs"; return nullptr; } myint deviceToChoose=numDevices-1; commandQueue = clCreateCommandQueue(context, devices[deviceToChoose], 0, nullptr); if (commandQueue == nullptr) { delete [] devices; std::cerr << "Failed to create commandQueue for device 0"; return nullptr; } *device = devices[deviceToChoose]; delete [] devices; return commandQueue; } cl_program GraphicCard::CreateProgram(cl_context context, cl_device_id device, const char* fileName) { cl_int errNum; cl_program program; const char * fileName0 = kernelPreLoadedGC.c_str(); std::ifstream kernelFile0(fileName0, std::ios::in); if (!kernelFile0.is_open()) { std::cerr << "Failed to open file for reading: " << fileName0 << std::endl; return nullptr; } std::ostringstream oss0; oss0 << kernelFile0.rdbuf(); std::string srcStdStr0 = oss0.str(); std::ifstream kernelFile(fileName, std::ios::in); if (!kernelFile.is_open()) { std::cerr << "Failed to open file for reading: " << fileName << std::endl; return nullptr; } std::ostringstream oss; oss << kernelFile.rdbuf(); std::string srcStdStr = srcStdStr0; srcStdStr+=oss.str(); const char *srcStr = srcStdStr.c_str(); program = clCreateProgramWithSource(context, 1, (const char**)&srcStr, nullptr, nullptr); if (program == nullptr) { std::cerr << "Failed to create CL program from source." << std::endl; return nullptr; } errNum = clBuildProgram(program, 0, nullptr, nullptr, nullptr, nullptr); if (errNum != CL_SUCCESS) { char buildLog[16384]; clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, sizeof(buildLog), buildLog, nullptr); std::cerr << "Error in kernel: " << std::endl; std::cerr << buildLog; clReleaseProgram(program); return nullptr; } return program; } void GraphicCard::Cleanup() { for (myint i = 0; i < numMemObjectsGC; ++i) { if (memObjectsGC[i] != nullptr) clReleaseMemObject(memObjectsGC[i]); } if (commandQueueGC != nullptr) clReleaseCommandQueue(commandQueueGC); for(myint k=0;k<numberOfKernelsGC;++k){ if(kernflsGC[k]!=nullptr){ clReleaseKernel(kernflsGC[k]); } } if (programGC != nullptr) clReleaseProgram(programGC); if (contextGC != nullptr) clReleaseContext(contextGC); delete[] kernflsGC; delete[] memObjectsGC; delete[] kernelResponsibilitiesGC; delete preferred_workgroup_sizeGC; delete axisSizeGC; delete lengthInBinaryGC; delete shufflingPrimeGC; delete[] variablesCorrectlySetInKernelGC; delete[] powersOfTwoGC; delete[] xAxisGC; delete[] yAxisGC; delete[] xPermutationsGC; delete[] yPermutationsGC; delete[] balancedNumbersGC; delete numBalancedNumbersGC; delete[] pascalTriangleGC; delete sizePascalTrGC; delete highestPrecisionGC; delete precisionRequestGC; delete exponentKGC; delete sizeForRejectionSamplingGC; delete sampleLengthGC; delete parameter1GC; delete parameter2GC; delete[] randomSampleGC; delete[] inspectorRejSampGC; delete randNumbersGC; } template <typename int_doub> mysint GraphicCard::deviceMemoryAccess(std::string memBlockName,int_doub *memorySequence, myint sLength, mysint action, myint writingShift){ mysint i=0; mysint foundName=-1; cl_int errNum; cl_event eventE; myint *pSLength; pSLength=new myint; *pSLength=sLength; std::map<std::string, myint>::iterator it; it=memObjNamesGC.find(memBlockName); if(it!=memObjNamesGC.end()){ foundName=it->second; } if((foundName==-1)&&(action==0)){ cl_mem *newMemObjects; std::set<myint>*newKernelResp; newKernelResp=new std::set<myint>[numMemObjectsGC+1]; newMemObjects=new cl_mem[2*(numMemObjectsGC+1)]; for(i=0;i<numMemObjectsGC;++i){ newKernelResp[i]=kernelResponsibilitiesGC[i]; newMemObjects[2*i]=memObjectsGC[2*i]; newMemObjects[2*i+1]=memObjectsGC[2*i+1]; } if(numMemObjectsGC>0){ delete[] memObjectsGC; delete[] kernelResponsibilitiesGC; } memObjectsGC=newMemObjects; kernelResponsibilitiesGC=newKernelResp; memObjNamesGC.insert(std::make_pair(memBlockName,numMemObjectsGC)); //kernelResponsibilitiesGC[numMemObjectsGC] is empty set without us having to do anything memObjectsGC[2*numMemObjectsGC] = clCreateBuffer(contextGC, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(myint) , pSLength, nullptr); memObjectsGC[2*numMemObjectsGC+1] = clCreateBuffer(contextGC, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, sizeof(int_doub) * sLength , memorySequence, nullptr); ++numMemObjectsGC; } if((foundName!=-1)&&(action==1)){ errNum = clEnqueueReadBuffer(commandQueueGC, memObjectsGC[2*foundName+1], CL_TRUE, sizeof(int_doub) * writingShift, sizeof(int_doub)* sLength, memorySequence, 0, nullptr, &eventE); clWaitForEvents(1, &eventE); } if((foundName!=-1)&&(action==0)){ clEnqueueWriteBuffer(commandQueueGC, memObjectsGC[2*foundName+1], CL_TRUE, sizeof(int_doub) * writingShift, sizeof(int_doub)* sLength,memorySequence,0,nullptr, &eventE); clWaitForEvents(1, &eventE); } if((foundName!=-1)&&(action==2)){ clEnqueueWriteBuffer(commandQueueGC, memObjectsGC[2*foundName], CL_TRUE, 0, sizeof(myint),pSLength,0,nullptr, &eventE); clWaitForEvents(1, &eventE); } if((foundName!=-1)&&(action==4)){ if (memObjectsGC[2*foundName] != nullptr){ clReleaseMemObject(memObjectsGC[2*foundName]); } if (memObjectsGC[2*foundName+1] != nullptr){ clReleaseMemObject(memObjectsGC[2*foundName+1]); } --numMemObjectsGC; memObjNamesGC.erase(memBlockName); std::map<std::string, myint>::iterator it1; for(it1=memObjNamesGC.begin();it1!=memObjNamesGC.end();++it1){ if((*it1).second>foundName){ --((*it1).second); } } for(myint i=foundName;i<numMemObjectsGC;++i){ memObjectsGC[2*i]=memObjectsGC[2*(i+1)]; memObjectsGC[2*i+1]=memObjectsGC[2*(i+1)+1]; kernelResponsibilitiesGC[i]=kernelResponsibilitiesGC[i+1]; } } delete pSLength; return foundName; } mysint GraphicCard::setKernelArguments(std::string kernelName,std::string* parNames,mysint numberOfParameters){ mysint kernelNumber=findAddKernel(kernelName); mysint forReturn=0; myint *memSequence=nullptr; mysint helpNum; cl_int errNum; if(kernelNumber==-1){ kernelNumber=findAddKernel(kernelName); } mysint *parNumbers; parNumbers=new mysint[numberOfParameters]; for(mysint i=0;i<numberOfParameters;++i){ parNumbers[i]=deviceMemoryAccess(parNames[i],memSequence , 0, 3, 0); if(parNumbers[i]==-1){ forReturn=-1; } } if(forReturn!=-1){ for(mysint i=0;i<numberOfParameters;++i){ kernelResponsibilitiesGC[parNumbers[i]].insert(kernelNumber); helpNum=2*parNumbers[i]; ++helpNum; errNum=clSetKernelArg(kernflsGC[kernelNumber], i, sizeof(cl_mem), &memObjectsGC[helpNum]); if (errNum != CL_SUCCESS) { std::cerr << "Error setting kernel argument " << i<<" "<<errNum<<std::endl; std::cerr << "Kernel number: " << kernelNumber<<", kernel code:"<<kernflsGC[kernelNumber]<<std::endl; if(errNum==CL_INVALID_KERNEL){ std::cout<<"CL_INVALID_KERNEL"<<std::endl; } if(errNum==CL_INVALID_ARG_INDEX){ std::cout<<"CL_INVALID_ARG_INDEX"<<std::endl; } if(errNum==CL_INVALID_ARG_VALUE){ std::cout<<"CL_INVALID_ARG_VALUE"<<std::endl; } if(errNum==CL_INVALID_MEM_OBJECT){ std::cout<<"CL_INVALID_MEM_OBJECT"<<std::endl; } if(errNum==CL_INVALID_SAMPLER){ std::cout<<"CL_INVALID_SAMPLER"<<std::endl; } if(errNum==CL_INVALID_ARG_SIZE){ std::cout<<"CL_INVALID_ARG_SIZE"<<std::endl; } if(errNum==CL_OUT_OF_RESOURCES){ std::cout<<"CL_OUT_OF_RESOURCES"<<std::endl; } if(errNum==CL_OUT_OF_HOST_MEMORY){ std::cout<<"CL_OUT_OF_HOST_MEMORY"<<std::endl; } forReturn=-2; } if(forReturn!=-2){ variablesCorrectlySetInKernelGC[kernelNumber]=1; } } } delete[] parNumbers; return forReturn; } mysint GraphicCard::executeKernel(std::string kernelName, myint numberOfProcessingElements){ mysint kernelNumber=findAddKernel(kernelName, 1); cl_int errNum; cl_event eventE; size_t *globalWorkSizeP; size_t *localWorkSizeP; globalWorkSizeP=new size_t; localWorkSizeP=new size_t; size_t pws; if(kernelNumber==-1){ kernelNumber=findAddKernel(kernelName); if(kernelNumber==-1){ kernelNumber=findAddKernel(kernelName,1); } } if(kernelNumber!=-1){ if(variablesCorrectlySetInKernelGC[kernelNumber]==0){ // The variables were not set correctly // We need to set them up. std::ifstream t(kernelFileGC); std::string str; t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); replace (str.begin(), str.end(), '*' , ' '); replace (str.begin(), str.end(), ',' , ' '); replace (str.begin(), str.end(), ';' , ' '); replace (str.begin(), str.end(), ')' , ' '); replace (str.begin(), str.end(), '&' , ' '); replace (str.begin(), str.end(), '(' , ' '); size_t index; while ((index = str.find("const")) != std::string::npos) str.replace(index, 5, " "); while ((index = str.find("void")) != std::string::npos) str.replace(index, 4, " "); while ((index = str.find("__local")) != std::string::npos) str.replace(index, 7, " __global "); std::regex word_regex("(\\S+)"); std::sregex_iterator words_begin = std::sregex_iterator(str.begin(), str.end(), word_regex); std::sregex_iterator words_end = std::sregex_iterator(); std::sregex_iterator cWord; std::string wordNext; mysint ik=0; mysint jk=0; cWord=words_begin; Strin_gList* firstListEl, *currentListEl; firstListEl=new Strin_gList; currentListEl=firstListEl; (*firstListEl).next=0; while(cWord!=words_end){ wordNext=(*cWord).str(); if(wordNext=="__kernel"){ ++cWord; if(cWord!=words_end){ wordNext=(*cWord).str(); if(wordNext==kernelName){ ++cWord; while(cWord!=words_end){ wordNext=(*cWord).str(); if(wordNext=="__global"){ ++cWord; if(cWord!=words_end){ ++cWord; if(cWord!=words_end){ ++ik; (*currentListEl).content=(*cWord).str(); (*currentListEl).next=new Strin_gList; currentListEl=(*currentListEl).next; (*currentListEl).next=0; } } } if(cWord!=words_end){++cWord;} if(cWord!=words_end){ if(((*cWord).str())=="__kernel"){ cWord=words_end; } } } } } } if(cWord!=words_end){++cWord;} } std::string* myStList; myStList=new std::string[ik]; currentListEl=firstListEl; for(myint i=0;i<ik;++i){ myStList[i]=currentListEl->content; currentListEl=currentListEl->next; } deleteStrin_gListInGC(firstListEl); setKernelArguments(kernelName,myStList,ik); delete[] myStList; } pws= (size_t) numberOfProcessingElements; pws= ( (pws/ (*preferred_workgroup_sizeGC))+1) * (*preferred_workgroup_sizeGC); *globalWorkSizeP=pws; *localWorkSizeP=*preferred_workgroup_sizeGC; errNum=clEnqueueNDRangeKernel(commandQueueGC, kernflsGC[kernelNumber], 1, nullptr, globalWorkSizeP, localWorkSizeP, 0, nullptr, &eventE); if (errNum != CL_SUCCESS){ std::cout<<"Error in kernel "<<kernelNumber<<std::endl; std::map<std::string, myint>::iterator it; for(it=kernelNamesGC.begin();it!=kernelNamesGC.end();++it){ if(it->second==kernelNumber){ std::cout<<it->first<<std::endl; } } treatError(errNum,contextGC, commandQueueGC, programGC, kernflsGC, numberOfKernelsGC, memObjectsGC, numMemObjectsGC); return 1; } clWaitForEvents(1, &eventE); } delete globalWorkSizeP; delete localWorkSizeP; return kernelNumber; } myint GraphicCard::treatError(cl_int errNum, cl_context context, cl_command_queue commandQueue, cl_program program, cl_kernel *kernfls, myint numKernels,cl_mem *memObjects, myint numMemObjects){ std::cerr << "Error queuing kernel for execution! " << " "<<errNum<< std::endl; if(errNum==CL_INVALID_PROGRAM_EXECUTABLE){std::cout<<"CL_INVALID_PROGRAM_EXECUTABLE"<<std::endl;} if(errNum==CL_INVALID_COMMAND_QUEUE){std::cout<<"CL_INVALID_COMMAND_QUEUE"<<std::endl;} if(errNum==CL_INVALID_KERNEL){std::cout<<"CL_INVALID_KERNEL"<<std::endl;} if(errNum==CL_INVALID_CONTEXT){std::cout<<"CL_INVALID_CONTEXT"<<std::endl;} if(errNum==CL_INVALID_KERNEL_ARGS){std::cout<<"CL_INVALID_KERNEL_ARGS"<<std::endl;} if(errNum==CL_INVALID_WORK_DIMENSION){std::cout<<"CL_INVALID_WORK_DIMENSION"<<std::endl;} if(errNum==CL_INVALID_GLOBAL_WORK_SIZE){std::cout<<"CL_INVALID_GLOBAL_WORK_SIZE"<<std::endl;} if(errNum==CL_INVALID_GLOBAL_OFFSET){std::cout<<"CL_INVALID_GLOBAL_OFFSET"<<std::endl;} if(errNum==CL_INVALID_WORK_GROUP_SIZE){std::cout<<"CL_INVALID_WORK_GROUP_SIZE"<<std::endl;} if(errNum==CL_INVALID_WORK_ITEM_SIZE){std::cout<<"CL_INVALID_WORK_ITEM_SIZE"<<std::endl;} if(errNum==CL_MISALIGNED_SUB_BUFFER_OFFSET){std::cout<<"CL_MISALIGNED_SUB_BUFFER_OFFSET"<<std::endl;} if(errNum==CL_OUT_OF_RESOURCES){std::cout<<"CL_OUT_OF_RESOURCES"<<std::endl;} if(errNum==CL_MEM_OBJECT_ALLOCATION_FAILURE){std::cout<<"CL_MEM_OBJECT_ALLOCATION_FAILURE"<<std::endl;} if(errNum==CL_INVALID_EVENT_WAIT_LIST){std::cout<<"CL_INVALID_EVENT_WAIT_LIST"<<std::endl;} if(errNum==CL_OUT_OF_HOST_MEMORY){std::cout<<"CL_OUT_OF_HOST_MEMORY"<<std::endl;} Cleanup(); return 1; } template <typename int_doub> mysint GraphicCard::writeDeviceMemory(std::string memBlockName,int_doub *memorySequence, myint sLength){ mysint memId=deviceMemoryAccess(memBlockName,memorySequence,sLength,3); if(memId!=-1){ // We will check whether the new length is bigger than the allocated length. // If that is the case, we need to reallocate more space. myint currentLength; myint *clp; clp=&currentLength; cl_int errNum; cl_event eventE; errNum = clEnqueueReadBuffer(commandQueueGC, memObjectsGC[2*memId], CL_TRUE, 0, sizeof(myint) , clp, 0, nullptr, &eventE); clWaitForEvents(1, &eventE); if(errNum!=CL_SUCCESS){ std::cout<<"Error in reading "<<memBlockName<<" "<<errNum<< std::endl; if(errNum==CL_INVALID_COMMAND_QUEUE){ std::cout<<"CL_INVALID_COMMAND_QUEUE"<<std::endl; } if(errNum==CL_INVALID_CONTEXT){ std::cout<<"CL_INVALID_CONTEXT"<<std::endl; } if(errNum==CL_INVALID_MEM_OBJECT){ std::cout<<"CL_INVALID_MEM_OBJECT"<<std::endl; } if(errNum==CL_INVALID_VALUE){ std::cout<<"CL_INVALID_VALUE"<<std::endl; } if(errNum== CL_INVALID_EVENT_WAIT_LIST ){ std::cout<<"CL_INVALID_EVENT_WAIT_LIST"<<std::endl; } if(errNum== CL_MEM_OBJECT_ALLOCATION_FAILURE){ std::cout<<"CL_MEM_OBJECT_ALLOCATION_FAILURE"<<std::endl; } if(errNum==CL_OUT_OF_HOST_MEMORY){ std::cout<<"CL_OUT_OF_HOST_MEMORY"<<std::endl; } if(errNum==CL_OUT_OF_RESOURCES){ std::cout<<"CL_OUT_OF_RESOURCES"<<std::endl; } } if(currentLength<sLength){ std::set<myint>::iterator it; for(it=(kernelResponsibilitiesGC[memId]).begin();it!=(kernelResponsibilitiesGC[memId]).end();++it){ variablesCorrectlySetInKernelGC[*it]=0; } deviceMemoryAccess(memBlockName,memorySequence,sLength,4); } } return deviceMemoryAccess(memBlockName,memorySequence,sLength); } template <typename int_doub> mysint GraphicCard::readDeviceMemory(std::string memBlockName,int_doub *memorySequence, myint sLength){ return deviceMemoryAccess(memBlockName,memorySequence,sLength,1); } cl_double * GraphicCard::convertVectToSeq(const std::vector<mydouble> & _v){ myint len=_v.size(); cl_double * fR; fR=new cl_double[len]; myint nthreads; #pragma omp parallel { if(omp_get_thread_num()==0){ nthreads=omp_get_num_threads(); } } #pragma omp barrier #pragma omp parallel num_threads(nthreads) { myint myId=omp_get_thread_num(); myint numberOfMyJobs=(len/nthreads); if(len % nthreads!=0){ ++numberOfMyJobs; } myint i; for(myint mI=0;mI<numberOfMyJobs;++mI){ i=mI*nthreads+ myId; if(i<len){ fR[i] = (cl_double)(_v[i]); } } } #pragma omp barrier return fR; } myint * GraphicCard::convertVectToSeq(const std::vector<myint> & _v){ myint len=_v.size(); myint * fR; fR=new myint[len]; myint nthreads; #pragma omp parallel { if(omp_get_thread_num()==0){ nthreads=omp_get_num_threads(); } } #pragma omp barrier #pragma omp parallel num_threads(nthreads) { myint myId=omp_get_thread_num(); myint numberOfMyJobs=(len/nthreads); if(len % nthreads!=0){ ++numberOfMyJobs; } myint i; for(myint mI=0;mI<numberOfMyJobs;++mI){ i=mI*nthreads+ myId; if(i<len){fR[i] = _v[i];} } } #pragma omp barrier return fR; } std::vector<mydouble> GraphicCard::convertSeqToVect(cl_double * _s, const myint &len){ std::vector<mydouble> fR; fR.resize(len); for(myint i=0;i<len;++i){ fR[i]=(mydouble)(_s[i]); } return fR; } std::vector<myint> GraphicCard::convertSeqToVect(myint * _s, const myint &len){ std::vector<myint> fR; fR.resize(len); for(myint i=0;i<len;++i){ fR[i]= _s[i] ; } return fR; } mysint GraphicCard::writeDeviceMemory(std::string memBlockName, const std::vector<mydouble> & _v, myint sLength){ cl_double * _ts; _ts=convertVectToSeq(_v); mysint fR=writeDeviceMemory(memBlockName,_ts,sLength); delete[] _ts; return fR; } mysint GraphicCard::writeDeviceMemory(std::string memBlockName, const std::vector<myint> & _v, myint sLength){ myint * _ts; _ts=convertVectToSeq(_v); mysint fR=writeDeviceMemory(memBlockName,_ts,sLength); delete[] _ts; return fR; } mysint GraphicCard::readDeviceMemory(std::string memBlockName, std::vector<mydouble> & _v, myint sLength){ cl_double * recV; recV=new cl_double[sLength]; mysint fR=readDeviceMemory(memBlockName,recV,sLength); _v=convertSeqToVect(recV,sLength); delete[] recV; return fR; } mysint GraphicCard::readDeviceMemory(std::string memBlockName, std::vector<myint> & _v, myint sLength){ myint * recV; recV=new myint[sLength]; mysint fR=readDeviceMemory(memBlockName,recV,sLength); _v=convertSeqToVect(recV,sLength); delete[] recV; return fR; } mysint GraphicCard::freeDeviceMemory(std::string memBlockName){ myint*memorySequence, sLength; return deviceMemoryAccess(memBlockName,memorySequence,sLength,4); } GraphicCard::~GraphicCard(){ Cleanup(); } class TripleGC{ public: myint a; myint b; myint c ; myint sorting; TripleGC(); TripleGC(myint, myint, myint); TripleGC(myint, myint, myint,myint); mysint operator<(const TripleGC&); mysint operator>(const TripleGC&); mysint operator=(const TripleGC&); }; TripleGC::TripleGC(){ a=0; b=0; c =0; sorting=-1; } TripleGC::TripleGC(myint p, myint q, myint r){ a=p; b=q; c=r; } TripleGC::TripleGC(myint p, myint q, myint r,myint s ){ a=p; b=q; c=r; sorting=s; } mysint TripleGC::operator=(const TripleGC& t){ a=t.a; b=t.b; c=t.c; sorting=t.sorting; return 1; } mysint TripleGC::operator<(const TripleGC& t){ if(a<t.a){ return 1; } if(a>t.a){ return 0; } if(b<t.b){ return 1; } if(b>t.b){ return 0; } if(c<t.c){ return 1; } if(c>t.c){ return 0; } return 0; } mysint TripleGC::operator>(const TripleGC& t){ if(a>t.a){ return 1; } if(a<t.a){ return 0; } if(b>t.b){ return 1; } if(b<t.b){ return 0; } if(c>t.c){ return 1; } if(c<t.c){ return 0; } return 0; } myint mergeSortTGC(TripleGC *seq, myint lS, TripleGC *sSeq=nullptr, myint lSS=0){ //First job is to sort the first sequence seq // and the second job is to add the sorted sequence sSeq into seq // If the length of the first sequence is 1 or 0, there is no need for sorting. if(lS>1){ //The sorting will be done by dividing the sequence in two parts. myint middle=(lS+1)/2; mergeSortTGC(seq+middle,lS-middle); mergeSortTGC(seq,middle,seq+middle,lS-middle); } if(lSS>0){ myint length=lS+lSS; TripleGC* help; help=new TripleGC[length]; myint r=0, rL=0,rR=0; while(r<length){ if(rL>=lS){ help[r]=sSeq[rR]; ++rR; } else{ if(rR>=lSS){ help[r]=seq[rL]; ++rL; } else{ if(seq[rL]<sSeq[rR]){ help[r]=seq[rL]; ++rL; } else{ help[r]=sSeq[rR]; ++rR; } } } ++r; } for(r=0;r<length;++r){ seq[r]=help[r]; } delete[] help; } return 0; } myint powerGC(myint base, myint exponent, myint modulo=0){ if(exponent==1){ if(modulo!=0){ return base%modulo; } else{ return base; } } if(exponent==0){ return 1; } myint forReturn=1; myint forReturnH,exp1; if(exponent%2==1){ forReturn=base; } exp1=exponent/2; forReturnH= powerGC(base, exp1, modulo); forReturn*=forReturnH; forReturn*=forReturnH; if(modulo!=0){ forReturn%=modulo; } return forReturn; } mysint GraphicCard::generatePermutationsGC(myint *seqToFill, myint N, myint r){ if(uniformLimitGC<r){ uniformLimitGC=r; } std::uniform_int_distribution<myint> uInt(0,uniformLimitGC); myint i,j; TripleGC *permuts; permuts=new TripleGC[r]; myint seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); seed+=currentSeedGC; std::mt19937 mt_randIF(seed); for(i=0;i<r;++i){ permuts[i].a=0; permuts[i].b=0; permuts[i].c=0; } for(i=0;i<N;++i){ for(j=0;j<r;++j){ permuts[j].a=uInt(mt_randIF); permuts[j].sorting=j; } mergeSortTGC(permuts,r); for(j=0;j<r;++j){ seqToFill[i*r+j]=permuts[j].sorting; } } currentSeedGC+=uInt(mt_randIF); delete[] permuts; return 1; } myint GraphicCard::createPascalTriangleGC(myint sizeM ){ if(pascalTriangleGC!=nullptr){ delete[] pascalTriangleGC; } myint size=sizeM; if(size<5){size=5;} *sizePascalTrGC=( (size +1)*(size +2) )/2; pascalTriangleGC=new myint[*sizePascalTrGC]; myint index1,index2,index3; pascalTriangleGC[*sizePascalTrGC-1]=1; pascalTriangleGC[0]=1; pascalTriangleGC[1]=1; for(myint n=2;n <=size;++n){ index1=( n*(n+1) )/2; pascalTriangleGC[index1]=1; pascalTriangleGC[index1-1]=1; index2=index1-n; for(myint k =1;k <n; ++k){ //calculating n choose k //Its index in the sequence is k+ n(n+1)/2 // We will use that \binom nk=\binom{n-1}{k}+\binom{n-1}{k-1} pascalTriangleGC[index1+k]=pascalTriangleGC[index2+k]+pascalTriangleGC[index2+k-1]; } } return 1; } myint GraphicCard::createBalancedNumbersGC(myint *seqBalNum, myint *cNumber, myint* remZero, myint *remOne, myint *cCounter){ if((*remZero==0) && (*remOne==0)){ seqBalNum[*cCounter]=*cNumber; *cCounter+=1; return 1; } if(*remZero>0){ *cNumber= (*cNumber) * 2; *remZero-=1; createBalancedNumbersGC(seqBalNum,cNumber,remZero,remOne,cCounter); *remZero+=1; *cNumber=(*cNumber)/2; } if(*remOne>0){ *cNumber= (*cNumber) * 2 +1 ; *remOne-=1; createBalancedNumbersGC(seqBalNum,cNumber,remZero,remOne,cCounter); *remOne+=1; *cNumber=(*cNumber)/2; } return 1; } mysint GraphicCard::generateRandomNumbers(myint N,myint r,mysint inputIndPGen){ myint indPGen=inputIndPGen; myint padding; padding=*preferred_workgroup_sizeGC; std::string *lArgRNK; myint numArg=12; lArgRNK=new std::string[numArg]; lArgRNK[0]="rNumGCCL"; lArgRNK[1]="xAxGCCL"; lArgRNK[2]="yAxGCCL"; lArgRNK[3]="permutationsXGCCL"; lArgRNK[4]="permutationsYGCCL"; lArgRNK[5]="powersOfTwoGCCL"; lArgRNK[6]="balancedNumbersGCCL"; lArgRNK[7]="pascalTGCCL"; lArgRNK[8]="axisSizeGCCL"; lArgRNK[9]="binaryLengthGCCL"; lArgRNK[10]="numBalancedNumbersGCCL"; lArgRNK[11]="shufflingPrimeGCCL"; if((indPGen==1)||(N!=*axisSizeGC)||(r!=*lengthInBinaryGC)){ indPGen=1; indFirstRNInitGC=0; if(r!=*lengthInBinaryGC){ delete[]balancedNumbersGC; balancedNumbersGC=nullptr; *numBalancedNumbersGC=0; delete[]pascalTriangleGC; pascalTriangleGC=nullptr; *sizePascalTrGC=0; } for(myint i=0;i<numArg;++i){ freeDeviceMemory(lArgRNK[i]); } *lengthInBinaryGC=r; *axisSizeGC=N; if(xAxisGC!=nullptr){ delete[] xAxisGC; } xAxisGC=new myint[*axisSizeGC+padding]; if(yAxisGC!=nullptr){ delete[] yAxisGC; } yAxisGC=new myint[*axisSizeGC+padding]; uniformLimitGC=*numBalancedNumbersGC-1; if(randNumbersGC==nullptr){ delete[] randNumbersGC; } randNumbersGC=new myint[ (*axisSizeGC+padding)*(*axisSizeGC+padding)]; for(myint i=0;i<(*axisSizeGC+padding)*(*axisSizeGC+padding);++i){ randNumbersGC[i]=17; } if(xPermutationsGC!=nullptr){ delete[] xPermutationsGC; } xPermutationsGC=new myint[(*axisSizeGC+padding)* (*lengthInBinaryGC)]; if(yPermutationsGC!=nullptr){ delete[] yPermutationsGC; } yPermutationsGC=new myint[(*axisSizeGC+padding)* (*lengthInBinaryGC)]; if(powersOfTwoGC!=nullptr){ delete[] powersOfTwoGC; } powersOfTwoGC=new myint[*lengthInBinaryGC]; powersOfTwoGC[0]=1; for(myint k=1;k<*lengthInBinaryGC;++k){ powersOfTwoGC[k]=2 * powersOfTwoGC[k-1]; } generatePermutationsGC(xPermutationsGC,*axisSizeGC+padding,*lengthInBinaryGC); generatePermutationsGC(yPermutationsGC,*axisSizeGC+padding,*lengthInBinaryGC); } if(balancedNumbersGC==nullptr){ myint **binMatrix; myint bigInt=*lengthInBinaryGC+2; binMatrix=new myint*[bigInt]; for(myint i=0;i<bigInt;++i){ binMatrix[i]=new myint[bigInt]; for(myint j=0;j<bigInt;++j){ binMatrix[i][j]=-1; } } createPascalTriangleGC(*lengthInBinaryGC+3); *numBalancedNumbersGC=pascalTriangleGC[ ((*lengthInBinaryGC)*(*lengthInBinaryGC+1))/2+ (*lengthInBinaryGC)/2]; uniformLimitGC=*numBalancedNumbersGC-1; for(myint i=0;i<bigInt;++i){ delete[] binMatrix[i]; } delete[] binMatrix; balancedNumbersGC=new myint[*numBalancedNumbersGC]; myint cNumber=0; myint remZero=(*lengthInBinaryGC)/2; myint remOne=remZero; myint cCounter=0; createBalancedNumbersGC(balancedNumbersGC, &cNumber, &remZero, &remOne, &cCounter); } std::uniform_int_distribution<myint> uInt(0,uniformLimitGC); myint seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); seed+=currentSeedGC; std::mt19937 mt_randIF(seed); for(myint i=0;i<*axisSizeGC+padding;++i){ xAxisGC[i]= uInt(mt_randIF); yAxisGC[i]= uInt(mt_randIF); } currentSeedGC+=uInt(mt_randIF); writeDeviceMemory("xAxGCCL",xAxisGC,*axisSizeGC+padding); writeDeviceMemory("yAxGCCL",yAxisGC,*axisSizeGC+padding); if(indPGen==1){ writeDeviceMemory("permutationsXGCCL",xPermutationsGC,(*axisSizeGC+padding)*(*lengthInBinaryGC)); writeDeviceMemory("permutationsYGCCL",yPermutationsGC,(*axisSizeGC+padding)*(*lengthInBinaryGC)); writeDeviceMemory("powersOfTwoGCCL",powersOfTwoGC,*lengthInBinaryGC); writeDeviceMemory("balancedNumbersGCCL",balancedNumbersGC,*numBalancedNumbersGC); writeDeviceMemory("binaryLengthGCCL",lengthInBinaryGC,1); writeDeviceMemory("shufflingPrimeGCCL",shufflingPrimeGC,1); writeDeviceMemory("numBalancedNumbersGCCL",numBalancedNumbersGC,1); writeDeviceMemory("pascalTGCCL",pascalTriangleGC,*sizePascalTrGC); writeDeviceMemory("axisSizeGCCL",axisSizeGC,1); } if(indFirstRNInitGC==0){ indPGen=1; indFirstRNInitGC=1; writeDeviceMemory("rNumGCCL",randNumbersGC,(*axisSizeGC+padding)*(*axisSizeGC+padding)); findAddKernel("genMainRandomMatrixGC"); setKernelArguments("genMainRandomMatrixGC",lArgRNK,numArg); } delete[] lArgRNK; executeKernel("genMainRandomMatrixGC", (*axisSizeGC)*(*axisSizeGC)); return 1; } mysint GraphicCard::setLocationNameForRandomNumbers(std::string newName){ randSampGC=newName; sampleGenKernExecutedGC=0; lastRandAlgUsedGC=-1; return 1; } mysint GraphicCard::generateNormalBeasleySpringerMoro(myint N,myint r, myint prec1ReqInput, myint *sampleLength, cl_double par1, cl_double par2, mysint inputIndPGen){ if((antitheticGC==1)||(overrideAntiteticGC==0)){ generateRandomNumbers(N,r,inputIndPGen); mysint inspResFun=0; myint precReq= prec1ReqInput; myint type=7; *highestPrecisionGC=powerGC(*numBalancedNumbersGC, prec1ReqInput)-1; *precisionRequestGC=precReq; *sizeForRejectionSamplingGC=precReq; *sampleLength= (N * N) / (*sizeForRejectionSamplingGC); if((*sampleLength!=*sampleLengthGC)||(lastRandAlgUsedGC!=type)){ lastRandAlgUsedGC=type; delete[] randomSampleGC; inspectorExecutedGC=0; sampleGenKernExecutedGC=0; *sampleLengthGC=*sampleLength; randomSampleGC=new cl_double[*sampleLengthGC]; writeDeviceMemory(randSampGC,randomSampleGC,*sampleLengthGC); writeDeviceMemory("sampleLengthGCCL",sampleLengthGC,1); writeDeviceMemory("sizeRejectionSamplingGCCL",sizeForRejectionSamplingGC,1); writeDeviceMemory("precReqGCCL",precisionRequestGC,1); writeDeviceMemory("par1GCCL",&par1,1); writeDeviceMemory("par2GCCL",&par2,1); writeDeviceMemory("numBalancedNumbersGCCL",numBalancedNumbersGC,1); writeDeviceMemory("biggestNumGCCL",highestPrecisionGC,1); cl_double *a,*b,*c; myint numAB=4, numC=9; a=new cl_double[numAB]; b=new cl_double[numAB]; c=new cl_double[numC]; a[0]=2.50662823884; a[1]=-18.61500062529; a[2]=41.39119773534; a[3]=-25.44106049637; b[0]=-8.47351093090; b[1]=23.08336743743; b[2]=-21.06224101826; b[3]=3.13082909833; c[0]=0.3374754822726147; c[1]=0.9761690190917186; c[2]=0.1607979714918209; c[3]=0.0276438810333863; c[4]=0.0038405729373609; c[5]=0.0003951896511919; c[6]=0.0000321767881768; c[7]=0.0000002888167364; c[8]=0.0000003960315187; writeDeviceMemory("seqAGCCL",a,numAB); writeDeviceMemory("seqBGCCL",b,numAB); writeDeviceMemory("seqCGCCL",c,numC); writeDeviceMemory("numABGCCL",&numAB,1); writeDeviceMemory("numCGCCL",&numC,1); delete[]a; delete[]b; delete[]c; } std::string *lArgRNK; myint numArg=14; lArgRNK=new std::string[numArg]; lArgRNK[0]=randSampGC; lArgRNK[1]="rNumGCCL"; lArgRNK[2]="sampleLengthGCCL"; lArgRNK[3]="sizeRejectionSamplingGCCL"; lArgRNK[4]="precReqGCCL"; lArgRNK[5]="par1GCCL"; lArgRNK[6]="par2GCCL"; lArgRNK[7]="numBalancedNumbersGCCL"; lArgRNK[8]="biggestNumGCCL"; lArgRNK[9]="seqAGCCL"; lArgRNK[10]="seqBGCCL"; lArgRNK[11]="seqCGCCL"; lArgRNK[12]="numABGCCL"; lArgRNK[13]="numCGCCL"; if(sampleGenKernExecutedGC==0){ sampleGenKernExecutedGC=1; findAddKernel(normalBSMNameGC); setKernelArguments(normalBSMNameGC,lArgRNK,numArg); } executeKernel(normalBSMNameGC,*sampleLengthGC); delete[] lArgRNK; antitheticGC=-1; } else{ std::string *lArgRNK; myint numArg=14; lArgRNK=new std::string[numArg]; lArgRNK[0]=randSampGC; lArgRNK[1]="rNumGCCL"; lArgRNK[2]="sampleLengthGCCL"; lArgRNK[3]="sizeRejectionSamplingGCCL"; lArgRNK[4]="precReqGCCL"; lArgRNK[5]="par1GCCL"; lArgRNK[6]="par2GCCL"; lArgRNK[7]="numBalancedNumbersGCCL"; lArgRNK[8]="biggestNumGCCL"; lArgRNK[9]="seqAGCCL"; lArgRNK[10]="seqBGCCL"; lArgRNK[11]="seqCGCCL"; lArgRNK[12]="numABGCCL"; lArgRNK[13]="numCGCCL"; findAddKernel(normalBSMAntNameGC); setKernelArguments(normalBSMAntNameGC,lArgRNK,numArg); executeKernel(normalBSMAntNameGC,*sampleLengthGC); delete[] lArgRNK; antitheticGC=1; } return 1; } mysint GraphicCard::generateExponential(myint N,myint r, myint prec1ReqInput, myint *sampleLength, cl_double lambda, mysint inputIndPGen){ generateRandomNumbers(N,r,inputIndPGen); mysint inspResFun=0; myint precReq= prec1ReqInput; myint type=8; *highestPrecisionGC=powerGC(*numBalancedNumbersGC, prec1ReqInput)-1; *precisionRequestGC=precReq; *sizeForRejectionSamplingGC=precReq; *sampleLength= (N * N) / (*sizeForRejectionSamplingGC); if((*sampleLength!=*sampleLengthGC)||(lastRandAlgUsedGC!=type)){ lastRandAlgUsedGC=type; delete[] randomSampleGC; sampleGenKernExecutedGC=0; *sampleLengthGC=*sampleLength; randomSampleGC=new cl_double[*sampleLengthGC]; writeDeviceMemory(randSampGC,randomSampleGC,*sampleLengthGC); writeDeviceMemory("sampleLengthGCCL",sampleLengthGC,1); writeDeviceMemory("sizeRejectionSamplingGCCL",sizeForRejectionSamplingGC,1); writeDeviceMemory("precReqGCCL",precisionRequestGC,1); writeDeviceMemory("par2GCCL",&lambda,1); writeDeviceMemory("numBalancedNumbersGCCL",numBalancedNumbersGC,1); writeDeviceMemory("biggestNumGCCL",highestPrecisionGC,1); } std::string *lArgRNK; myint numArg=8; lArgRNK=new std::string[numArg]; lArgRNK[0]=randSampGC; lArgRNK[1]="rNumGCCL"; lArgRNK[2]="sampleLengthGCCL"; lArgRNK[3]="sizeRejectionSamplingGCCL"; lArgRNK[4]="precReqGCCL"; lArgRNK[5]="par2GCCL"; lArgRNK[6]="numBalancedNumbersGCCL"; lArgRNK[7]="biggestNumGCCL"; if(sampleGenKernExecutedGC==0){ sampleGenKernExecutedGC=1; findAddKernel(exponentialDistNameGC); setKernelArguments(exponentialDistNameGC,lArgRNK,numArg); } executeKernel(exponentialDistNameGC,*sampleLengthGC); delete[] lArgRNK; return 1; } template <typename int_doub> myint GraphicCard::createFenwickTree(std::string treeName, std::string lengthKeeper, int_doub *inputSeq, myint length){ myint i; myint powerOfTwoGreaterThanLength=1; while(powerOfTwoGreaterThanLength<length){ powerOfTwoGreaterThanLength*=2; } int_doub *seqToCopy; if(powerOfTwoGreaterThanLength>length){ seqToCopy=new int_doub[powerOfTwoGreaterThanLength]; for(i=0;i<length;++i){ seqToCopy[i]=inputSeq[i]; } while(i<powerOfTwoGreaterThanLength){ seqToCopy[i]=int_doub(0); ++i; } } else{ seqToCopy=inputSeq; } std::string *lArgRNK; myint numArg=3; lArgRNK=new std::string[numArg]; lArgRNK[0]=treeName; lArgRNK[1]=lengthKeeper; lArgRNK[2]="layerSkipGCCL"; myint layer=0, layerSkip=1, layerSkip2; writeDeviceMemory(treeName,seqToCopy,powerOfTwoGreaterThanLength); writeDeviceMemory(lengthKeeper,&powerOfTwoGreaterThanLength,1); writeDeviceMemory("layerSkipGCCL",&layerSkip,1); findAddKernel(createFenwickGC); setKernelArguments(createFenwickGC,lArgRNK,numArg); layerSkip2=2*layerSkip; while(layerSkip2<=powerOfTwoGreaterThanLength){ writeDeviceMemory("layerSkipGCCL",&layerSkip,1); executeKernel(createFenwickGC,powerOfTwoGreaterThanLength/layerSkip2); layerSkip=layerSkip2; layerSkip2*=2; } if(powerOfTwoGreaterThanLength>length){ delete[] seqToCopy; } delete[] lArgRNK; return powerOfTwoGreaterThanLength; } cl_double GraphicCard::justSummation(std::string seqName, std::string lengthKeeper, myint length, myint avInd){ myint i; myint powerOfTwoGreaterThanLength=1; while(powerOfTwoGreaterThanLength<length){ powerOfTwoGreaterThanLength*=2; } std::string *lArgRNK; myint numArg=4; lArgRNK=new std::string[numArg]; lArgRNK[0]=seqName; lArgRNK[1]=lengthKeeper; lArgRNK[2]="layerSkipGCCL"; lArgRNK[3]="multiplierFnwGCCL"; myint layer=0, layerSkip=1, layerSkip2; cl_double mult=1.0; if(avInd==1){ mult*=cl_double(powerOfTwoGreaterThanLength)/cl_double(2*length); } writeDeviceMemory(lengthKeeper,&length,1); writeDeviceMemory("layerSkipGCCL",&layerSkip,1); writeDeviceMemory("multiplierFnwGCCL",&mult,1); findAddKernel(justSummationFenwickGC); setKernelArguments(justSummationFenwickGC,lArgRNK,numArg); layerSkip2=2*layerSkip; while(layerSkip2<=powerOfTwoGreaterThanLength){ writeDeviceMemory("layerSkipGCCL",&layerSkip,1); executeKernel(justSummationFenwickGC,powerOfTwoGreaterThanLength/layerSkip2); layerSkip=layerSkip2; if((avInd==1)&&(layerSkip2==2)){ mult=0.5; writeDeviceMemory("multiplierFnwGCCL",&mult,1); } layerSkip2*=2; } cl_double fR; readDeviceMemory(seqName,&fR,1); delete[] lArgRNK; return fR; } myint GraphicCard::partialSumsFTree(std::string treeName, std::string lengthKeeper, std::string fromSeqN, std::string toSeqN, std::string resultN, myint length){ findAddKernel(partialSumsFTreeGC); myint numArg=5; std::string *lArgRNK; lArgRNK=new std::string[numArg]; lArgRNK[0]=treeName; lArgRNK[1]=lengthKeeper; lArgRNK[2]=fromSeqN; lArgRNK[3]=toSeqN; lArgRNK[4]=resultN; writeDeviceMemory(lengthKeeper,&length,1); setKernelArguments(partialSumsFTreeGC,lArgRNK,numArg); executeKernel(partialSumsFTreeGC,length); delete[] lArgRNK; return 1; } myint GraphicCard::mergeSort(std::string stSeqName, myint nRAM, myint direction, std::string resSeqName){ myint potentialMemoryLeak=0; if(resSeqName=="not provided"){ resSeqName="resSeqMergSortGCCL"; if(resSeqName==stSeqName){ resSeqName="resSeqMergSortGCCLRB"; } cl_double *auxSeq; auxSeq=new cl_double[nRAM]; writeDeviceMemory(resSeqName,auxSeq,nRAM); delete[] auxSeq; potentialMemoryLeak=1; } std::string lengthName="lenMergSortGCCL"; std::string sortedSizeN="sortedSizeMergSortGCCL"; std::string correctKernel=shiftCalculationMergSortIncGC; if(direction==1){ correctKernel=shiftCalculationMergSortDecGC; } std::string switcher; myint numArg=4; std::string *lArgRNK; lArgRNK=new std::string[numArg]; lArgRNK[0]=stSeqName; lArgRNK[1]=lengthName; lArgRNK[2]=resSeqName; lArgRNK[3]=sortedSizeN; findAddKernel(correctKernel); findAddKernel(copyResultToStartGC); writeDeviceMemory(lengthName,&nRAM,1); myint sortSize=1; while(sortSize<nRAM){ writeDeviceMemory(sortedSizeN,&sortSize,1); setKernelArguments(correctKernel,lArgRNK,numArg); executeKernel(correctKernel,nRAM); switcher=lArgRNK[0]; lArgRNK[0]=lArgRNK[2]; lArgRNK[2]=switcher; sortSize*=2; } if(lArgRNK[2]==stSeqName){ myint numArg2=3; std::string *lArgRNK2; lArgRNK2=new std::string[numArg2]; lArgRNK2[0]=stSeqName; lArgRNK2[1]=lengthName; lArgRNK2[2]=resSeqName; setKernelArguments(copyResultToStartGC,lArgRNK2,numArg2); executeKernel(copyResultToStartGC,nRAM); delete[] lArgRNK2; } delete[] lArgRNK; if(potentialMemoryLeak==1){ freeDeviceMemory(resSeqName); } return 1; } myint GraphicCard::mergeSortWithFollower(std::string stSeqName,std::string followerName, myint nRAM, myint direction, std::string resSeqName, std::string resFollName){ myint potentialMemoryLeak=0; if(resSeqName=="not provided"){ resSeqName="resSeqMergSortGCCL"; resFollName="resSeqFollGCCL"; if(resSeqName==stSeqName){ resSeqName="resSeqMergSortGCCLRB"; } if(resFollName==followerName){ resFollName="resSeqFollGCCLRB"; } cl_double *auxSeq; myint *auxSeqFoll; auxSeq=new cl_double[nRAM]; auxSeqFoll=new myint[nRAM]; writeDeviceMemory(resSeqName,auxSeq,nRAM); writeDeviceMemory(resFollName,auxSeqFoll,nRAM); delete[] auxSeq; delete[] auxSeqFoll; potentialMemoryLeak=1; } std::string lengthName="lenMergSortGCCL"; std::string sortedSizeN="sortedSizeMergSortGCCL"; std::string correctKernel=shiftCalculationMergSortFollIncGC; if(direction==1){ correctKernel=shiftCalculationMergSortFollDecGC; } std::string switcher; myint numArg=6; std::string *lArgRNK; lArgRNK=new std::string[numArg]; lArgRNK[0]=stSeqName; lArgRNK[1]=lengthName; lArgRNK[2]=resSeqName; lArgRNK[3]=sortedSizeN; lArgRNK[4]=followerName; lArgRNK[5]=resFollName; findAddKernel(correctKernel); findAddKernel(copyResultToStartGC); writeDeviceMemory(lengthName,&nRAM,1); myint sortSize=1; while(sortSize<nRAM){ writeDeviceMemory(sortedSizeN,&sortSize,1); setKernelArguments(correctKernel,lArgRNK,numArg); executeKernel(correctKernel,nRAM); switcher=lArgRNK[0]; lArgRNK[0]=lArgRNK[2]; lArgRNK[2]=switcher; switcher=lArgRNK[4]; lArgRNK[4]=lArgRNK[5]; lArgRNK[5]=switcher; sortSize*=2; } if(lArgRNK[2]==stSeqName){ myint numArg2=5; std::string *lArgRNK2; lArgRNK2=new std::string[numArg2]; lArgRNK2[0]=stSeqName; lArgRNK2[1]=lengthName; lArgRNK2[2]=resSeqName; lArgRNK2[3]=followerName; lArgRNK2[4]=resFollName; setKernelArguments(copyResultToStartFollGC,lArgRNK2,numArg2); executeKernel(copyResultToStartFollGC,nRAM); delete[] lArgRNK2; } delete[] lArgRNK; if(potentialMemoryLeak==1){ freeDeviceMemory(resSeqName); freeDeviceMemory(resFollName); } return 1; } myint GraphicCard::setParametersPSS(std::string origSeqN, std::string pSSN, std::string lengthN, std::string blSizN, myint length,myint blSize){ origNamePSSGC=origSeqN; namePSSGC=pSSN; lengthNamePSSGC=lengthN; nameBlockSizePSSGC=blSizN; blockSizePSSGC=blSize; lengthValuePSSGC=length; writeDeviceMemory(lengthNamePSSGC,&lengthNamePSSGC,1); writeDeviceMemory(nameBlockSizePSSGC,&blockSizePSSGC,1); return 1; } myint GraphicCard::createPSS(){ if(lengthValuePSSGC>0){ //STAGE 1 findAddKernel(kernelNameStage1PSSGC); myint counter=0; writeDeviceMemory(posVariableNamePSSGC,&counter,1); myint numArg=5; std::string *lArgRNK; lArgRNK=new std::string[numArg]; lArgRNK[0]=origNamePSSGC; lArgRNK[1]=namePSSGC; lArgRNK[2]=lengthNamePSSGC; lArgRNK[3]=nameBlockSizePSSGC; lArgRNK[4]=posVariableNamePSSGC; setKernelArguments(kernelNameStage1PSSGC,lArgRNK,numArg); myint kernelsNeededStage1= lengthValuePSSGC/blockSizePSSGC; if(lengthValuePSSGC%blockSizePSSGC>0){ kernelsNeededStage1+=1; } for(counter=0;counter<blockSizePSSGC;++counter){ writeDeviceMemory(posVariableNamePSSGC,&counter,1); executeKernel(kernelNameStage1PSSGC,kernelsNeededStage1); } //STAGE 2 findAddKernel(kernelNameStage2PSSGC); setKernelArguments(kernelNameStage2PSSGC,lArgRNK,numArg); for(counter=0;counter<kernelsNeededStage1;++counter){ writeDeviceMemory(posVariableNamePSSGC,&counter,1); executeKernel(kernelNameStage2PSSGC,blockSizePSSGC); } delete[] lArgRNK; } else{ std::cout<<"Set-up not performed correctly. Could not create PSS"<<std::endl; return 0; } return 1; } myint GraphicCard::createPSS(std::string origSeqN, std::string pSSN, std::string lengthN, std::string blSizN, myint length, myint blSize){ setParametersPSS(origSeqN, pSSN, lengthN,blSizN, length,blSize); return createPSS(); } myint GraphicCard::partialSumsPSS(std::string pssName, std::string lengthKeeper, std::string fromSeqN, std::string toSeqN, std::string resultN, myint length){ findAddKernel(partialSumsPSSGC); myint numArg=5; std::string *lArgRNK; lArgRNK=new std::string[numArg]; lArgRNK[0]=pssName; lArgRNK[1]=lengthKeeper; lArgRNK[2]=fromSeqN; lArgRNK[3]=toSeqN; lArgRNK[4]=resultN; writeDeviceMemory(lengthKeeper,&length,1); setKernelArguments(partialSumsPSSGC,lArgRNK,numArg); executeKernel(partialSumsPSSGC,length); delete[] lArgRNK; return 1; } myint GraphicCard::getPrefferedWorkGroupSize() const{ return static_cast<myint>( *preferred_workgroup_sizeGC); }
#include <iostream> #include <string> #include <cmath> #include <vector> using namespace std; int find_sum(int); int is_palindrome(int, int); int recursive_check(int, int); int find_lower_bound(int num, int length); int main() { string s; cin >> s; int length = s.length(); int num = 0; for (int i = 0; i < length; i++) { num += int(s[(length - 1) - i] - '0') * pow(10, i); } int lower_bound = find_lower_bound(num, length); cout << lower_bound << endl; for (int i = 0; i <= lower_bound; i++) { int limit = pow(10, length); for (int j = 0; j < pow(10, length); j++) { if (find_sum(j) != i) continue; int candidate = (num + j) % limit; if (is_palindrome(candidate, length)) { cout << i << endl; return 0; } } } cout << "Wtf no palindrome"; return 0; } int find_sum(int a) { int sum = 0; while (a != 0) { sum += a % 10; a = a / 10; } return sum; } int is_palindrome(int candidate, int length) { vector<int> v1 (length, 0); for (int i = length - 1; i >= 0; i--) { v1[i] = candidate % 10; candidate = candidate / 10; } for (int i = 1; i <= (length + 1) / 2; i++) { if (v1[i - 1] != v1[(length - 1) - (i - 1)]) return 0; } return 1; } int find_lower_bound(int num, int length) { int lower_bound = 0; int base_1 = 1, base_2 = pow(10, length-1); while (base_2 > base_1) { int a = (num / base_1) % 10, b = (num / base_2) % 10; lower_bound += abs(a-b); base_1 *= 10; base_2 /= 10; } return lower_bound; }
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #include <flux/tar/ArchiveReader> namespace flux { namespace tar { void ArchiveReader::skipData(ArchiveEntry *entry) { readData(entry); } }} // namespace flux::tar
// // Created by anggo on 5/17/2020. // #include "Centipede.h" Centipede::Centipede() :mushroom("Sprites/mushroom.png"),p("Sprites/blaster.png") { image_path = "Sprites/Centipede.png"; title = "Centipede"; info_path = "Information/info.txt"; load_game(); } void Centipede::start(sf::RenderWindow& window) { initializeGame(window); } void Centipede::addEvents(sf::RenderWindow& window) { sf::Vector2f centipedeVelocity(5.0f, 0.2f); frameTime = clock.getElapsedTime(); for(int i=0;i<centipedes.size();i++) { for(int j=0;j<centipedes[i].size();j++) { // Centipede going down to y = 30 if (centipedes[i][j].getPosition().y <= 70.0f) { centipedeVelocity = sf::Vector2f(0.0f, 10.0f); centipedes[i][j].move(centipedeVelocity); } // After passing the y = 30 mark else { // Centipede needs to go to left if (LMovement[i][j]) { centipedeVelocity = sf::Vector2f(-10.0f, 0.0f); centipedes[i][j].move(centipedeVelocity); } // Centipede needs to go to the right else if (RMovement[i][j]) { centipedeVelocity = sf::Vector2f(10.0f, 0.0f); centipedes[i][j].move(centipedeVelocity); } // Check centipede collides with the left window barrier if (centipedes[i][j].getPosition().x <= 420) { centipedeVelocity = sf::Vector2f(0.0f, 10.0f); centipedes[i][j].move(centipedeVelocity); LMovement[i][j] = false; RMovement[i][j] = true; } if (centipedes[i][j].getPosition().x >= 1500) { centipedeVelocity = sf::Vector2f(0.0f, 10.0f); centipedes[i][j].move(centipedeVelocity); RMovement[i][j] = false; LMovement[i][j] = true; } for (int k = 0; k < level1.size(); k++) { if (Collision::PixelPerfectTest(centipedes[i][j].getHead(), level1[k].getSprite())) { if (LMovement[i][j]) { centipedeVelocity = sf::Vector2f(0.0f, 10.0f); centipedes[i][j].move(centipedeVelocity); LMovement[i][j] = false; RMovement[i][j] = true; } else { centipedeVelocity = sf::Vector2f(0.0f, 10.0f); centipedes[i][j].move(centipedeVelocity); RMovement[i][j] = false; LMovement[i][j] = true; } } } } } } // Movement of the blaster if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { p.move(sf::Vector2f(5.0f, 0.0f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { p.move(sf::Vector2f(-5.0f, 0.0f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { p.move(sf::Vector2f(0.0f, -5.0f)); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { p.move(sf::Vector2f(0.0f, 5.0f)); } // Blaster not getting out of window if (p.getPosition().x >= window.getSize().x - 50) { p.move(sf::Vector2f(-1.5f, 0.0f)); } if (p.getPosition().x <= 0) { p.move(sf::Vector2f(1.5f, 0.0f)); } if (p.getPosition().y >= window.getSize().y - 50) { p.move(sf::Vector2f(0.0f, -1.5f)); } // Shooting bullets if (shootTimer < 25) { shootTimer++; } if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && shootTimer >= 25) { Bullet newBullet(bulletTexture); newBullet.setPosition(sf::Vector2f(p.getPosition().x, p.getPosition().y)); newBullet.setSize(sf::Vector2f(2.5f, 2.5f)); bullets.push_back(newBullet); shootTimer = 0; } for (int i = 0; i < bullets.size(); i++) { bullets[ i ].fire(-10); if (bullets[ i ].getSprite().getPosition().y < 0) { bullets.erase(bullets.begin() + i); } } // Collision bullets with mushrooms for (int i = 0; i < bullets.size(); i++) { for (int j = 0; j < level1.size(); j++) { if (Collision::PixelPerfectTest(bullets[ i ].getSprite(), level1[ j ].getSprite())) { bullets.erase(bullets.begin() + i); level1[ j ].Update(); if (level1[ j ].getAnimation1().getiFrame() == 4) { level1.erase(level1.begin() + j); score+=100; scoreCount.setString(std::to_string(score)); } } } } /******* FLEA ********/ //The speed of the fleas~ sf::Vector2f fleasSpeed(0,1.0f); if ((static_cast<int>(frameTime.asSeconds())%5) == 0) { if(!repeat) { Flea *newFlea = new Flea("Sprites/flea.png"); newFlea->setPosition(sf::Vector2f(rand()% 1080 + 420,-50)); newFlea->setSize(sf::Vector2f(2.0f,2.0f)); FleasV.push_back(*newFlea); repeat = true; } } //To make sure that the vector don't increase as for milliseconds if(static_cast<int>(frameTime.asSeconds())%5 != 0) { repeat = false; } //Summon the Feas to the attack the player FleasV[0].attack(fleasSpeed); //Delete the Feas when it collides with the player if ((Collision::PixelPerfectTest(FleasV[0].getSprite(), p.getSprite()))) { FleasV.erase(FleasV.begin()); healthVector.erase(healthVector.begin()); } if(FleasV[0].getPosition().y>1080) { FleasV.erase(FleasV.begin()); } for(int i=0;i<bullets.size();i++) { if ((Collision::PixelPerfectTest(FleasV[0].getSprite(), bullets[i].getSprite()))) { FleasV.erase(FleasV.begin()); bullets.erase(bullets.begin()+i); score+= 50; } } /******* SPIDER *********/ //Increase vector every 7 seconds to summon the spider if ((static_cast<int>(frameTime.asSeconds())%7) == 0) { if(!repeat2) { Spider *newSpider = new Spider("Sprites/spider.png"); newSpider->setPosition(sf::Vector2f(rand()%2000,rand()%2000)); newSpider->setSize(sf::Vector2f(4.0f,4.0f)); SpiderV.push_back(*newSpider); repeat2 = true; } } //To make sure that the vector don't increase as for milliseconds if(static_cast<int>(frameTime.asSeconds())%7 != 0) { repeat2 = false; } //Direction of the spider moving if (SpiderV[0].getPosition().y >= 1080) touchGround = true; if (SpiderV[0].getPosition().y <= 0) touchGround = false; if (SpiderV[0].getPosition().x >= 1500) touchWall = true; if (SpiderV[0].getPosition().x <= 420) touchWall = false; //Spider will move and attack if (SpiderV.size() > 0) { if (touchGround) { SpiderV[0].attack(sf::Vector2f(0, -1.0f)); } else { SpiderV[0].attack(sf::Vector2f(0, 1.0f)); } if (touchWall) { SpiderV[0].attack(sf::Vector2f(-1.0f, 0)); } else { SpiderV[0].attack(sf::Vector2f(1.0f, 0)); } } if (frameTime.asSeconds()>7) { SpiderV.erase(SpiderV.begin()); frameTime = clock.restart(); } //Delete the Spider when it collides with the player if ((Collision::PixelPerfectTest(SpiderV[0].getSprite(), p.getSprite())) && SpiderV.size()>0) { SpiderV.erase(SpiderV.begin() ); healthVector.erase(healthVector.begin()); } //Delete the Spider when it collides with the centipede for(int i=0;i<bullets.size();i++) { if ((Collision::PixelPerfectTest(SpiderV[0].getSprite(), bullets[i].getSprite()))) { SpiderV.erase(SpiderV.begin() ); bullets.erase(bullets.begin()+i); score+=50; } } //Collision bullet with body for(int i=0;i<centipedes.size();i++) { for (int j = 0; j < centipedes[i].size(); j++) { if(Collision::PixelPerfectTest(centipedes[i][j].getHead(),p.getSprite()) && healthVector.size()>0) { healthVector.erase(healthVector.begin()); } for (int k = 0; k < bullets.size(); k++) { if (Collision::PixelPerfectTest(centipedes[i][j].getHead(), bullets[k].getSprite())) { // Erase bullet sprite bullets.erase(bullets.begin()+k); if(centipedes[i].size() == 1) { mushroom.setSize(sf::Vector2f(2.0f, 2.0f)); mushroom.setPosition(sf::Vector2f(centipedes[i][j].getPosition().x - 10.0f,centipedes[i][j].getPosition().y)); level1.push_back(mushroom); centipedes[i].erase(centipedes[i].begin()); RMovement[i].erase(RMovement[i].begin()); LMovement[i].erase(LMovement[i].begin()); score+=500; } else { if(j==0) { Head *newCentipede = new Head("Sprites/centipede_head.png","Sprites/centipede_head.png"); newCentipede->setPosition(sf::Vector2f(centipedes[i][j+1].getPosition())); newCentipede->setSize(sf::Vector2f(4.0f,4.0f)); centipedes[i][j+1] = *newCentipede; mushroom.setSize(sf::Vector2f(2.0f, 2.0f)); mushroom.setPosition(sf::Vector2f(centipedes[i][j].getPosition().x - 10.0f,centipedes[i][j].getPosition().y)); level1.push_back(mushroom); centipedes[i].erase(centipedes[i].begin()); RMovement[i].erase(RMovement[i].begin()); LMovement[i].erase(LMovement[i].begin()); score+=500; } else if(j == centipedes[i].size()-1) { mushroom.setSize(sf::Vector2f(2.0f, 2.0f)); mushroom.setPosition(sf::Vector2f(centipedes[i][j].getPosition().x - 10.0f,centipedes[i][j].getPosition().y)); level1.push_back(mushroom); centipedes[i].erase(centipedes[i].end()); RMovement[i].erase(RMovement[i].end()); LMovement[i].erase(LMovement[i].end()); score+=100; } else { // Calculate the body destroyed int bodyDestroyed = j+1; std::vector<Head> newCent; std::vector<bool> newLeftMovement; std::vector<bool> newRightMovement; Head *newCentipede = new Head("Sprites/centipede_head.png","Sprites/centipede_head.png"); newCentipede->setPosition(sf::Vector2f(centipedes[i][j+1].getPosition())); newCentipede->setSize(sf::Vector2f(4.0f,4.0f)); newCent.push_back(*newCentipede); newLeftMovement.push_back(true); newRightMovement.push_back(false); for(int x= bodyDestroyed + 1;x<centipedes[i].size();x++) { Head *newCentipede = new Head("Sprites/centipede_body.png","Sprites/centipede_body.png"); newCentipede->setSize(sf::Vector2f(4.0f,4.0f)); newCentipede->setPosition(sf::Vector2f(centipedes[i][x].getPosition())); newCent.push_back(*newCentipede); newLeftMovement.push_back(true); newRightMovement.push_back(false); } LMovement.push_back(newLeftMovement); RMovement.push_back(newRightMovement); centipedes.push_back(newCent); mushroom.setSize(sf::Vector2f(2.0f, 2.0f)); mushroom.setPosition(sf::Vector2f(centipedes[i][j].getPosition().x - 10.0f,centipedes[i][j].getPosition().y)); level1.push_back(mushroom); int sizeToBeDestroyed = centipedes[i].size(); for(int x=j;x<sizeToBeDestroyed;x++) { centipedes[i].erase(centipedes[i].end()); RMovement[i].erase(RMovement[i].end()); LMovement[i].erase(LMovement[i].end()); } score+=100; } } scoreCount.setString(std::to_string(score)); } } if(centipedes[i].size() == 0) { centipedes.erase(centipedes.begin() + i); LMovement.erase(LMovement.begin()+i); RMovement.erase(RMovement.begin()+i); } } } if(centipedes.size() == 0) { retry = true; sf::Font gameOverFont; if(!gameOverFont.loadFromFile("Font/cosmic.ttf")) { std:: cout << "File failed to load! \n"; } sf::Text gameOverText; gameOverText.setFont(myFont); gameOverText.setCharacterSize(100); gameOverText.setPosition(sf::Vector2f(window.getSize().x/8, window.getSize().y/4)); gameOverText.setFillColor(sf::Color::White); std::string gameOverMessage="You won! \nFinal score:"; gameOverMessage=gameOverMessage.append(std::to_string(score)); gameOverText.setString(gameOverMessage); window.draw(gameOverText); } if(healthVector.size()<=0) { retry = true; if(sf::Keyboard::isKeyPressed(sf::Keyboard::Enter)) { int mushroomSize = level1.size(); for(int i=0;i<mushroomSize;i++) { level1.erase(level1.begin() + i); } int centipedeSize = centipedes.size(); for(int i=0;i<centipedeSize;i++) { centipedes.erase(centipedes.begin()); LMovement.erase(LMovement.begin()); RMovement.erase(RMovement.begin()); } int healthSize = healthVector.size(); for(int i=0;i<healthSize;i++) { healthVector.erase(healthVector.begin()); } score = 0; initializeGame(window); } else { sf::Font gameOverFont; if(!gameOverFont.loadFromFile("Font/cosmic.ttf")) { std:: cout << "File failed to load! \n"; } sf::Text gameOverText; gameOverText.setFont(myFont); gameOverText.setCharacterSize(100); gameOverText.setPosition(sf::Vector2f(window.getSize().x/8, window.getSize().y/4)); gameOverText.setFillColor(sf::Color::White); std::string gameOverMessage="Press enter to retry! \nFinal score:"; gameOverMessage=gameOverMessage.append(std::to_string(score)); gameOverText.setString(gameOverMessage); window.draw(gameOverText); } } } void Centipede::addEvents(const sf::RenderWindow &window, sf::Event& event) { } void Centipede::draw(sf::RenderTarget& window, sf::RenderStates states) const { // window.draw(thumbnailSprite); // window.draw(blaster); if(!retry) { window.draw(p); for (int i = 0; i < level1.size(); i++) { window.draw(level1[i]); } for (int i = 0; i < bullets.size(); i++) { window.draw(bullets[i]); } // for(int i =0; i<centipede.size();i++) // { // window.draw(centipede[i]); // } for(int i=0; i<centipedes.size(); i++) for(int j =0; j<centipedes[i].size();j++) { window.draw(centipedes[i][j]); } for (int i=0; i<FleasV.size(); i++) { window.draw(FleasV[i]); } for (int i=0; i<SpiderV.size(); i++) { window.draw(SpiderV[i]); } for(int i=0;i<healthVector.size();i++) { window.draw(healthVector[i]); } window.draw(scoreCount); } } void Centipede::exit() { }; void Centipede::initializeGame(sf::RenderWindow& window) { int healthXCoordinate=20; for(int i=0 ; i<3; i++) { Health* health = new Health("Sprites/PlayerHealth.png"); health->setSize(sf::Vector2f(0.8f,0.8f)); health->setPosition(sf::Vector2f(healthXCoordinate,200)); healthVector.push_back(*health); healthXCoordinate+=50; } // Initialize scores if(!myFont.loadFromFile("Font/DS-DIGII.TTF")) { std:: cout << "Font file error \n"; } scoreCount.setFont(myFont); scoreCount.setString(std::to_string(score)); scoreCount.setCharacterSize(100); scoreCount.setFillColor(sf::Color::White); bulletTexture.loadFromFile("Sprites/bullet.png"); srand(time(NULL)); // Initialize mushrooms for (int i = 0; i < 40; i++) { mushroom.setSize(sf::Vector2f(2.0f, 2.0f)); mushroom.setPosition(sf::Vector2f(rand() % 1080 + 420 , rand() % 1080 + 30)); level1.push_back(mushroom); } // Initialize player p.setSize(sf::Vector2f(2.50f, 2.50f)); p.setPos(sf::Vector2f(window.getSize().x / 2, window.getSize().y -75)); // Head of the centipede Head *centipedeHead = new Head("Sprites/centipede_head.png","Sprites/centipede_head.png"); centipedeHead->setPosition(sf::Vector2f(window.getSize().x/2, 0)); centipedeHead->setSize(sf::Vector2f(4.0f,4.0f)); centipede.push_back(*centipedeHead); leftMovement.push_back(true); rightMovement.push_back(false); // Body of the centipede for(int i=1;i<11;i++) { Head *centipedeBody = new Head("Sprites/centipede_body.png","Sprites/centipede_body.png"); centipedeBody->setSize(sf::Vector2f(4.0f,4.0f)); centipedeBody->setPosition(sf::Vector2f(window.getSize().x/2,((-30*(i+1)+30)))); centipede.push_back(*centipedeBody); leftMovement.push_back(true); rightMovement.push_back(false); } LMovement.push_back(leftMovement); RMovement.push_back(rightMovement); centipedes.push_back(centipede); for(int i=0;i<3;i++) { Flea *newFlea = new Flea("Sprites/flea.png"); newFlea->setPosition(sf::Vector2f(rand()% 1080 + 420,-50)); newFlea->setSize(sf::Vector2f(2.0f,2.0f)); FleasV.push_back(*newFlea); } retry = false; }
#pragma once #include "revoke.h" #include "sol2/sol.hpp" #include <map> #include <string> struct CSLua { struct CSStaticCall { sol::variadic_results operator()(const sol::variadic_args va) { printf("Called with %lu args\n", va.size()); sol::variadic_results r; return r; } }; struct CSConstruct { cs::csptr classObj; struct Member { Member(std::string const& name, cs::csptr mi, int typ) : name(name), memberInfo(mi), type(typ) {} std::string name; cs::csptr memberInfo; int type; }; std::map<std::string, Member> memberMap; CSConstruct(ObjectRef* classPtr) : classObj(classPtr) { #if 0 void** target = new void*[100]; int count = Revoke::instance().GetMembers(classPtr, target); printf("Found %d members\n", count); for (int i = 0; i < count; i++) { auto* name = (const char*)target[i * 3]; auto mt = (MemberType)(uint64_t)target[i * 3 + 1]; auto* p = target[i * 3 + 2]; printf("%s %u\n", name, mt); Member member(name, cs::make_csptr(p), mt); memberMap.try_emplace(name, member); } #endif } cs::Obj operator()() { printf("Constructor on %p\n", classObj.get()); auto* obj = Revoke::instance().NamedCall("new", classObj.get(), 0, nullptr); return cs::Obj(cs::make_csptr(obj), classObj); } }; struct CSCall { cs::csptr method; CSCall(void* ptr) : method(cs::make_csptr(ptr)) {} sol::variadic_results operator()(cs::Obj& thiz, const sol::variadic_args va) { printf("MEMBER Called with %lu args\n", va.size()); int rc; int i = 0; void** pargs = new void*[va.size()]; // = {convert(args)...}; for (const auto& v : va) { auto t = v.get_type(); pargs[i] = nullptr; printf("TYPE %d\n", (int)t); switch (t) { case sol::type::number: printf("NUMBER\n"); rc = (int)v; pargs[i] = Revoke::instance().CreateFrom(ObjType::INT, &rc); break; case sol::type::string: pargs[i] = Revoke::instance().CreateFrom( ObjType::STRING, (void*)v.get<std::string>().c_str()); break; case sol::type::userdata: printf("TABLE\n"); if (v.is<cs::Obj>()) { printf("OBJ\n"); cs::Obj obj = v.get<cs::Obj>(); pargs[i] = obj.ptr.get(); } break; default: break; } i++; } Revoke::instance().MethodCall(method.get(), thiz.ptr.get(), va.size(), pargs); sol::variadic_results r; return r; } }; static sol::state& lua() { static sol::state lua; return lua; } enum MemberType { Constructor = 1, Property = 2, Field = 4, Method = 8 }; static void my_setter(const cs::Obj& obj, const char*, sol::object, sol::this_state s) { printf("In setter\n"); } static sol::object my_getter(const cs::Obj& obj, std::string const& name, sol::this_state s) { printf("In getter\n"); Revoke::instance().GetMember(); if (name == "TestFn") { return sol::make_object( s, [](cs::Obj& z, int x, cs::Obj& y) -> int { return 3; }); } return sol::make_object(s, 3); } static void init() { lua().open_libraries(sol::lib::base, sol::lib::package); std::string className = "GameObject"; void* t = Revoke::instance().GetType(className.c_str()); lua().new_usertype<cs::Obj>( className, "new", sol::factories(CSConstruct(t)), sol::meta_function::index, &my_getter, sol::meta_function::new_index, &my_setter //,sol::meta_function::new_index, &cs::Obj::set_field ); lua()["println"] = &puts; printf("Running script\n"); lua().script(R"( go = GameObject.new() go:TestFn(4, go) println("Test called") y = go.transform print(y) println("here") )"); // lua()["GameObject"]["static_call"] = CSStaticCall(); // lua()["GameObject"]["member_call"] = CSCall(); // lua().script("GameObject.static_call(1,2,3)\ngo = " // "GameObject.new()\ngo:member_call(3)\n"); } };
#pragma once #include <vector> #include <string> #include "misc.h" #include "png.h" struct GameDesc { uint32_t id; std::string name; std::string desc; std::vector<std::string> assets; }; struct Asset { Image image; std::string name; }; enum EGameErrorCode { kGameErrorOk = 0, kGameErrorNotFound, kGameErrorInternal, }; bool GamesStart(); void GetGamesList(std::vector<GameDesc*>& list); EGameErrorCode GetGameIcon(uint32_t gameId, Image& icon); EGameErrorCode GetGameAsset(uint32_t gameId, uint32_t assetIndex, Asset& asset); EGameErrorCode GetGameCode(uint32_t gameId, void** code, uint32_t& codeSize); bool AddGame(void* zipFile, uint32_t zipFileSize, const char* zipName);
#include<iostream> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/opencv.hpp> using namespace cv; int main() { VideoCapture capture(0); while (1) { Mat frame; Mat edge,grayimage; capture >> frame; if (frame.empty()) break; cvtColor(frame, grayimage, CV_BGR2GRAY); blur(grayimage,edge, Size(6, 6)); Canny(edge,edge,3,9,3); imshow("ÊÓÆµÖ¡", edge); waitKey(30); } return 0; }
#include <iostream> #include <string> #include <vector> using namespace std; #ifndef _command_H #define _command_H class command{ public: virtual bool run(bool prev) = 0; command(const vector<string>& arr); protected: bool internalRun(); private: vector<string> args; }; #endif
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; int main() { //载入原始图 Mat srcImage = imread("D:\\18.jpg"); Mat midImage, dstImage; //canny检测边缘转化为灰度图 Canny(srcImage, midImage, 50, 200, 3); cvtColor(midImage, dstImage, CV_GRAY2BGR); //进行霍夫变换 std::vector<cv::Vec2f> lines; HoughLines(midImage, lines, 4, CV_PI / 180,150, 0, 0); //一次在图中绘制出每条线段 for (size_t i = 0; i < lines.size(); i++) { float rho = lines[i][0]; float theta = lines[i][1]; Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(srcImage, pt1, pt2, Scalar(55, 100, 195), 1, LINE_AA); } //边缘检测之后的图 imshow("【边缘检测后的图】", midImage); //显示效果图 imshow("【效果图】", srcImage); waitKey(0); return 0; }
#include "player.h" #include <iostream> #include <string> #include <array> #include <cstdio> #include <ctime> using namespace std; Player::Player(string piece){ team = 1; this->piece = "X"; if(piece == "O"){ team = -1; this->piece = "O"; } } //Converts the teams id to game piece string Player::convertToPiece(){ switch(team){ case(1): return "X"; break; case(-1): return "O"; break; } return ""; } array<int,2> AI::getAIMove(int team, Board &current_game, bool trace){ bool max = true; if(team == -1) //if AI is "O" then AI is min max = false; double duration; clock_t start = clock(); //logs how long it took AI to consider moves array<long,4>move = minimax(current_game, max, this->difficulty, trace); duration = (clock() - start) / (double)CLOCKS_PER_SEC; cout << endl << endl << "Possible states considered: " << move[3]; cout << endl << "Time: " << duration << "s"; return array<int,2>{{(int)move[1],(int)move[2]}}; } array<long,4> AI::minimax(Board &current_game, bool max, int depth, bool trace, long alpha, long beta, long count){ vector<array<int,2>> move = current_game.getMoves(); //gets all possible moves for current game state long score = 0; long bestCol = -1; long bestRow = -1; int current_team = (max) ? 1 : -1; if(move.size() == 0 || depth == 0 || current_game.win() != 2){ score = current_game.evaluate(); //evaluate the current boards state if(trace){ //shows states related to state current_game.print(); cout << "Reason stopped: "; if(move.size() == 0){ cout << "No more moves."; }else if(depth == 0){ cout << "Depth bound reached."; }else{ cout << "End game state detected."; } cout << endl << "Depth: " << this->difficulty - depth << ", Score: " << score << endl; } return array<long,4>{{score, bestCol, bestRow, count}}; }else{ for (unsigned int i = 0; i < move.size(); ++i){ //for all possible moves at a state current_game.cells[move[i][0]][move[i][1]] = current_team; //make a move into the game if(trace){ //shows states related to state current_game.print(); cout << "Depth: " << this->difficulty - depth << endl; } ++count; //counts how many moves made if(max){ array<long,4>temp = minimax(current_game, false, depth-1, trace, alpha, beta, count); //call minimax on the new game state for min score = temp[0]; count = temp[3]; if(score > alpha){ //if the new state scores higher than previous best alpha = score; //new best for max bestCol = move[i][0]; bestRow = move[i][1]; } }else{ array<long,4>temp = minimax(current_game, true, depth-1, trace, alpha, beta, count);//call minimax on the new game state for max score = temp[0]; count = temp[3]; if(score < beta){ //if new score scores lower than previous best beta = score; //new best for min bestCol = move[i][0]; bestRow = move[i][1]; } } current_game.cells[move[i][0]][move[i][1]] = 0; //undo test move if(alpha >= beta) break; //prune do to unlikely game state } return array<long,4>{{(max) ? alpha : beta, bestCol, bestRow, count}}; } return array<long,4>{{0,0,0,0}}; }
// ChildView.h : interface of the CChildView class // #pragma once #include <freewill.h> // obligatory #include <fwrender.h> // to start the renderer #include <fwaction.h> // actions class CCamera; // CChildView window class CChildView : public CWnd { // FreeWill Objects IFWDevice *m_pFWDevice; // FreeWill Device IRenderer *m_pRenderer; // The Renderer IScene *m_pScene; // The Scene ISceneLightDir *m_pLight1; // light 1 ISceneLightDir *m_pLight2; // light 2 IAction *m_pActionTick; // The Clock Tick Action... CCamera *m_pCamera; // camera bool m_bFWDone; // true if FreeWill fully initialised... CPoint m_ptDrag; // mouse initial position while dragging // Characters int m_nCurBody; // index to the current character IBody *m_pBody[2]; // character bodies IAction *m_pWalkAction[2]; // character walking actions int m_nWalkState[2]; // current walking action - simply the key code W, A, S, D or X; 0 if none // Construction public: CChildView(); // Attributes public: // Operations public: // Overrides protected: virtual BOOL PreCreateWindow(CREATESTRUCT& cs); // Implementation public: virtual ~CChildView(); // Generated message map functions protected: afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() public: afx_msg void OnActionsAction1(); afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnActionsAction2(); afx_msg void OnActionsAction3(); afx_msg void OnActionsAction4(); afx_msg void OnActionsAction5(); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnActionsAction6(); afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnUpdateIndicatorScrl(CCmdUI *pCmdUI); };
#include <vector> #include <utility> // std::pair, std::make_pair #define cube_size (int)16 #define backgroundColor (uint16_t)0b0011000110000110 #define appleColor (uint16_t)0b1111100000000000 class Game { public: std::pair <int, int> UP; std::pair <int, int> DOWN; std::pair <int, int> LEFT; std::pair <int, int> RIGHT; std::vector <std::pair<int, int>> snake; std::pair <int, int> apple; std::pair <int, int> dir; std::pair <int, int> last; public: Game(); void init(); void draw(); void move(); void loss_check(); void new_apple(); void loss_message(); void goUp(); void goDown(); void goLeft(); void goRight(); };
/*원본소스 //tstbtree.cc #include "btnode.h" #include "btnode.tc" #include "btree.h" #include "btree.tc" #include <iostream.h> const char * keys="CSDTAMPIBWNGURKEHOLJYQZFXV"; const int BTreeSize = 4; main (int argc, char * argv) { int result, i; BTree <char> bt (BTreeSize); result = bt.Create ("testbt.dat",ios::in|ios::out); if (!result){cout<<"Please delete testbt.dat"<<endl;return 0;} for (i = 0; i<26; i++) { cout<<"Inserting "<<keys[i]<<endl; result = bt.Insert(keys[i],i); bt.Print(cout); } bt.Search(1,1); return 1; } */ //tstbtree.cc #include "btnode.h" #include "btnode.cpp" #include "btree.h" #include "btree.cpp" #include "person.h" #include "recfile.h" #include "delim.h" #include "simpind.h" #include "strclass.h" #include <iostream> const int BTreeSize = 5; using namespace std; int main (int argc, char * argv) { int result = 0, recaddr = 0; char tkey[10]; DelimFieldBuffer Buffer; RecordFile<Person> Recfile (Buffer); Recfile . Create ("record.dat",ios::in|ios::out|ios::trunc); BTree <char*> bt (BTreeSize); result = bt.Create ("testbt.dat",ios::in|ios::out); if (!result){cout<<"Please delete testbt.dat"<<endl;return 0;} Person* P[35]; for(int i = 0; i < 35; i++) P[i] = new Person(); cout << "Person의 입력" << endl; for (int i = 0; i < 35; i++) { cout << i+1 << "번째 Person" << endl; cin >> *P[i]; fflush(stdin); } for(int i=0;i<35;++i) { recaddr = Recfile.Write(*P[i]); result = bt.Insert(P[i]->Key(),i); bt.TPrint(cout); } for (int i = 0; i < 25; i++){ cout << "삭제할 Key값을 입력하시오." << endl; cin >> tkey; fflush(stdin); String key(tkey); result = bt.Remove(key); bt.TPrint(cout); } Recfile.Close(); bt.Close(); return 1; }
//Problem Link: https://www.codechef.com/problems/HIGHWAYC #include <bits/stdc++.h> using namespace std; main() { long int t; cin >> t; cout << fixed << showpoint; cout << setprecision(6); while (t--) { int n; double s, y; cin >> n >> s >> y; double p[n], v[n], d[n], l[n]; for (int i = 0; i < n; i++) cin >> v[i]; for (int i = 0; i < n; i++) cin >> d[i]; for (int i = 0; i < n; i++) cin >> p[i]; for (int i = 0; i < n; i++) cin >> l[i]; double r[n], c[n]; for (int i = 0; i < n; i++) { if ((d[i] == 1 && p[i] > 0) || (d[i] == 0 && p[i] < 0)) { r[i] = -1; c[i] = -1; } else if (p[i] == 0) { r[i] = 0; c[i] = (l[i] + pow(10, -6)) / v[i]; } else { r[i] = (abs(p[i]) - pow(10, -6)) / v[i]; c[i] = (abs(p[i]) + l[i] + pow(10, -6)) / v[i]; } } double time = 0; double ntime; double lct = y / s; for (int i = 0; i < n; i++) { if (r[i] == -1) time = time + lct; else { if (((time + lct) < r[i]) || (time > c[i])) time = time + lct; else time = c[i] + lct; } } cout << time << "\n"; } }
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; if(matrix.empty()) return res; int m = matrix.size(); int n = matrix[0].size(); int cur = 0; while(2 * cur < m && 2 * cur < n) { for(int j = cur; j < n - cur; j++) res.push_back(matrix[cur][j]); for(int i = cur + 1; i < m - cur; i++) res.push_back(matrix[i][n - cur - 1]); for(int j = n - cur - 2; m - cur - 1 != cur && j >= cur; j--) res.push_back(matrix[m - cur - 1][j]); for(int i = m - cur - 2; cur != n - cur - 1 && i >= cur + 1; i--) res.push_back(matrix[i][cur]); cur++; } return res; } };
// AUTHOR: Sumit Prajapati #include <bits/stdc++.h> using namespace std; #define ull unsigned long long #define ll long long #define int long long #define pii pair<int, int> #define pll pair<ll, ll> #define pb push_back #define mk make_pair #define ff first #define ss second #define all(a) a.begin(),a.end() #define trav(x,v) for(auto &x:v) #define debug(x) cerr<<#x<<" = "<<x<<'\n' #define llrand() distribution(generator) #define rep(i,n) for(int i=0;i<n;i++) #define repe(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=a;i<=b;i++) #define printar(a,s,e) FOR(i,s,e)cout<<a[i]<<" ";cout<<'\n' #define endl '\n' #define curtime chrono::high_resolution_clock::now() #define timedif(start,end) chrono::duration_cast<chrono::nanoseconds>(end - start).count() #define INF 1'000'000'000 #define MD 1'000'000'007 #define MDL 998244353 #define MX 100'005 auto time0 = curtime; random_device rd; default_random_engine generator(rd()); uniform_int_distribution<ull> distribution(0,0xFFFFFFFFFFFFFFFF); //Is testcase present? struct{ int a; int b; int h; }D[MX]; int n; int dp[MX],segm[4*MX]; int query(int cur,int start,int end,int qs,int qe){ if(start>=qs && end<=qe) return segm[cur]; if(start>qe || end<qs) return -1; //INVALID RETURN int mid=(start+end)>>1; int A=query(2*cur,start,mid,qs,qe); int B=query(2*cur+1,mid+1,end,qs,qe); //MERGING STEP int res=max(A,B); return res; } void update(int cur,int start,int end,int ind,int val){ if(start==ind && start==end){ //DO UPDATE segm[cur]=val; return; } if(start>ind|| end<ind) return; //OUT OF RANGE int mid=(start+end)>>1; update(cur<<1,start,mid,ind,val); update((cur<<1)^1,mid+1,end,ind,val); segm[cur]=max(segm[2*cur],segm[2*cur+1]); //MERGING STEP } void solve(){ // OP BIRRROO cin>>n; int a[5]; repe(i,n) cin>>D[i].a>>D[i].b>>D[i].h; sort(D+1,D+n+1,[&](const auto& P,const auto& Q){ if(P.b==Q.b) return P.a<Q.a; return P.b<Q.b; }); int ans=0; for(int i=1;i<=n;i++){ int s_r=D[i].a,ind=i; int l=1,r=i; while(l<=r){ int mid=(l+r)>>1; if(D[mid].b>s_r) ind=mid,r=mid-1; else l=mid+1; } // cout<<i<<" "<<ind<<'\n'; int best_here=0; if(ind!=i) best_here=query(1,1,n,ind,i-1); dp[i]=D[i].h+best_here; update(1,1,n,i,dp[i]); ans=max(ans,dp[i]); } cout<<ans<<'\n'; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); time0 = curtime; int t=1; // cin>>t; repe(tt,t){ //cout<<"Case #"<<tt<<": "; solve(); } //cerr<<"Execution Time: "<<timedif(time0,curtime)*1e-9<<" sec\n"; return 0; }
#include "vtkMetaImageReader.h" #include "vtkSmartPointer.h" #include "vtkContourFilter.h" #include "vtkSmoothPolyDataFilter.h" #include "vtkDecimatePro.h" #include "vtkPLYWriter.h" #include "vtkPolyDataWriter.h" #include "tinyxml.h" #include <sstream> #include <iostream> #include <string> #include <vector> #include "vtkMarchingCubes.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageToVTKImageFilter.h" int main(int argc, char *argv[]) { // preliminaries if( argc < 2 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " paramfile " << std::endl; //std::cerr << argv[0] << " inDT outMesh lsval" << std::endl; return EXIT_FAILURE; } // variables std::vector< std::string > inFilenames; inFilenames.clear(); std::vector< std::string > outFilenames; outFilenames.clear(); float levelsetValue = 0.0; float targetReduction = 0.01; // percentage to decimate float featureAngle = 30; // in degrees int lsSmootherIterations = 1; // number of iterations to smooth the levelset int meshSmootherIterations = 1; // number of iterations to smooth the initial mesh bool preserveTopology = true; // read parameters TiXmlDocument doc(argv[1]); bool loadOkay = doc.LoadFile(); if (loadOkay) { TiXmlHandle docHandle( &doc ); TiXmlElement *elem; std::istringstream inputsBuffer; std::string filename("/dev/null\0"); // Compile the list of input files. elem = docHandle.FirstChild( "inputs" ).Element(); if (elem) { inputsBuffer.str(elem->GetText()); while (inputsBuffer >> filename) { inFilenames.push_back(filename); } inputsBuffer.clear(); inputsBuffer.str(""); } else { std::cerr << "No inputs to process!" << std::endl; return EXIT_FAILURE; } // Compile the list of output files. elem = docHandle.FirstChild( "outputs" ).Element(); if (elem) { inputsBuffer.str(elem->GetText()); while (inputsBuffer >> filename) { outFilenames.push_back(filename); } inputsBuffer.clear(); inputsBuffer.str(""); } // read levelset value if given elem = docHandle.FirstChild( "levelsetValue" ).Element(); if (elem) { levelsetValue = atof( elem->GetText() ); } // read target reduction value if given elem = docHandle.FirstChild( "targetReduction" ).Element(); if (elem) { targetReduction = atof( elem->GetText() ); } // read feature angle value if given elem = docHandle.FirstChild( "featureAngle" ).Element(); if (elem) { featureAngle = atof( elem->GetText() ); } // read number of iterations for levelset smoother if given elem = docHandle.FirstChild( "lsSmootherIterations" ).Element(); if (elem) { lsSmootherIterations = atoi( elem->GetText() ); } // read number of iterations for mesh smoother if given elem = docHandle.FirstChild( "meshSmootherIterations" ).Element(); if (elem) { meshSmootherIterations = atoi( elem->GetText() ); } // check if topology changes are allowed elem = docHandle.FirstChild( "preserveTopology" ).Element(); if (elem) { atoi(elem->GetText()) > 0 ? preserveTopology = true : preserveTopology = false; } // Make sure lists are the same size. if (inFilenames.size() > outFilenames.size()) { std::cerr << "Input list size does not match output list size!" << std::endl; return EXIT_FAILURE; } } // create meshes from all input distance transforms at particular levelsetValue for (unsigned int shapeNo = 0; shapeNo < inFilenames.size(); shapeNo++) { typedef itk::Image< double, 3 > ImageType; typedef itk::ImageFileReader<ImageType> ReaderType; typedef itk::ImageToVTKImageFilter<ImageType> ConnectorType; ReaderType::Pointer reader = ReaderType::New(); ConnectorType::Pointer connector = ConnectorType::New(); reader->SetFileName(inFilenames[shapeNo].c_str()); connector->SetInput(reader->GetOutput()); //vtkSmartPointer<vtkMetaImageReader> reader = vtkSmartPointer<vtkMetaImageReader>::New(); //reader->SetFileName( inFilenames[shapeNo].c_str() ); //reader->Update(); std::cout << "processing DT: " << inFilenames[shapeNo].c_str() << ".."; vtkSmartPointer<vtkContourFilter> ls = vtkSmartPointer<vtkContourFilter>::New(); //vtkSmartPointer<vtkMarchingCubes> ls = vtkSmartPointer<vtkMarchingCubes>::New(); //ls->SetInputConnection( reader->GetOutputPort() ); ls->SetInput( connector->GetOutput() ); ls->SetValue(0, levelsetValue); ls->Update(); std::cout << ".."; vtkSmartPointer<vtkSmoothPolyDataFilter> lsSmoother = vtkSmartPointer<vtkSmoothPolyDataFilter>::New(); lsSmoother->SetInputConnection( ls->GetOutputPort() ); lsSmoother->SetNumberOfIterations(lsSmootherIterations); lsSmoother->Update(); std::cout << ".."; vtkSmartPointer<vtkDecimatePro> decimator = vtkSmartPointer<vtkDecimatePro>::New(); decimator->SetInputConnection( lsSmoother->GetOutputPort() ); decimator->SetTargetReduction(targetReduction); decimator->SetFeatureAngle(featureAngle); preserveTopology == true ? decimator->PreserveTopologyOn() : decimator->PreserveTopologyOff(); decimator->BoundaryVertexDeletionOn(); decimator->Update(); std::cout << ".."; vtkSmartPointer<vtkSmoothPolyDataFilter> smoother = vtkSmartPointer<vtkSmoothPolyDataFilter>::New(); smoother->SetInputConnection(decimator->GetOutputPort()); smoother->SetNumberOfIterations(meshSmootherIterations); smoother->Update(); std::cout << ".."; vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New(); writer->SetInputConnection(smoother->GetOutputPort()); writer->SetFileTypeToASCII(); writer->SetFileName( outFilenames[shapeNo].c_str() ); writer->Update(); std::cout << " Done !" << std::endl; //vtkSmartPointer<vtkPLYWriter> writer = vtkSmartPointer<vtkPLYWriter>::New(); //writer->SetInputConnection(smoother->GetOutputPort()); //writer->SetFileName( outFilenames[shapeNo].c_str() ); //writer->Update(); //std::cout << " Done !" << std::endl; } return EXIT_SUCCESS; }
#include <Keypad.h> #include <SPI.h> #include <TimeAlarms.h> #include <TimeLib.h> #include <Time.h> #define SUMP_RELATED_NODE #define NODE_HAS_RELAY #define NODE_WITH_HIGH_LOW_FEATURE #define WATER_TANK_NODE #define KEYPAD_1R_2C #define MY_RADIO_NRF24 #define MY_NODE_ID SUMP_MOTOR_NODE_ID #define MY_PARENT_NODE_ID REPEATER_02_NODE_ID #define MY_PARENT_NODE_IS_STATIC #include <MyNodes.h> #include <MySensors.h> #include <MyConfig.h> #define APPLICATION_NAME "Sump Motor" AlarmId heartbeatTimer; AlarmId updateTimer; volatile boolean tank02LowLevel; volatile boolean tank02HighLevel; volatile boolean tank03LowLevel; volatile boolean tank03HighLevel; boolean sumpMotorOn; MyMessage thingspeakMessage(WIFI_NODEMCU_ID, V_CUSTOM); MyMessage sumpMotorRelayMessage(SUMP_MOTOR_RELAY_ID, V_STATUS); MyMessage tank02Message(SUMP_MOTOR_RELAY_ID, V_STATUS); MyMessage tank02LowLevelMessage(TANK02_LOW_LEVEL_ID, V_TRIPPED); MyMessage tank02HighLevelMessage(TANK02_HIGH_LEVEL_ID, V_TRIPPED); MyMessage tank03LowLevelMessage(TANK03_LOW_LEVEL_ID, V_TRIPPED); MyMessage tank03HighLevelMessage(TANK03_HIGH_LEVEL_ID, V_TRIPPED); Keypad keypad = Keypad(makeKeymap(keys), rowsPins, colsPins, ROWS, COLS); void before() { pinMode(RELAY_PIN, OUTPUT); pinMode(MOTOR_STATUS_PIN, OUTPUT); } void setup() { keypad.addEventListener(keypadEvent); keypad.setDebounceTime(WAIT_50MS); sumpMotorOn = false; tank02LowLevel = false; tank02HighLevel = false; tank03LowLevel = false; tank03HighLevel = false; digitalWrite(RELAY_PIN, LOW); digitalWrite(MOTOR_STATUS_PIN, LOW); thingspeakMessage.setDestination(THINGSPEAK_NODE_ID); thingspeakMessage.setType(V_CUSTOM); thingspeakMessage.setSensor(WIFI_NODEMCU_ID); tank02LowLevelMessage.setDestination(TANK_02_NODE_ID); tank02HighLevelMessage.setDestination(TANK_02_NODE_ID); tank03LowLevelMessage.setDestination(TANK_03_NODE_ID); tank03HighLevelMessage.setDestination(TANK_03_NODE_ID); heartbeatTimer = Alarm.timerRepeat(HEARTBEAT_INTERVAL, sendHeartbeat); updateTimer = Alarm.timerRepeat(QUATER_HOUR, sendUpdate); } void presentation() { sendSketchInfo(APPLICATION_NAME, getCodeVersion()); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); present(SUMP_MOTOR_RELAY_ID, S_BINARY, "Sump Motor Relay"); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); send(sumpMotorRelayMessage.set(RELAY_OFF)); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); send(thingspeakMessage.set(RELAY_OFF)); Alarm.delay(WAIT_AFTER_SEND_MESSAGE); } void loop() { char key = keypad.getKey(); Alarm.delay(1); } void receive(const MyMessage &message) { byte incomingValue; switch (message.type) { case V_STATUS: switch (message.sender) { case THINGSPEAK_NODE_ID: incomingValue = message.getBool(); break; default: incomingValue = message.getInt(); break; } switch (incomingValue) { case RELAY_ON: if (!tank02HighLevel && !tank03LowLevel && !sumpMotorOn) turnOnSumpMotor(); break; case RELAY_OFF: if (sumpMotorOn) turnOffSumpMotor(); break; } break; case V_TRIPPED: switch (message.sensor) { case TANK02_LOW_LEVEL_ID: if (message.getInt()) tank02LowLevel = LOW_LEVEL; else tank02LowLevel = NOT_LOW_LEVEL; tank02LowLevelMessage.set(tank02LowLevel); send(tank02LowLevelMessage); wait(WAIT_AFTER_SEND_MESSAGE); break; case TANK02_HIGH_LEVEL_ID: if (message.getInt()) tank02HighLevel = HIGH_LEVEL; else tank02HighLevel = NOT_HIGH_LEVEL; tank02HighLevelMessage.set(tank02HighLevel); send(tank02HighLevelMessage); wait(WAIT_AFTER_SEND_MESSAGE); break; case TANK03_LOW_LEVEL_ID: if (message.getInt()) tank03LowLevel = LOW_LEVEL; else tank03LowLevel = NOT_LOW_LEVEL; tank03LowLevelMessage.set(tank03LowLevel); send(tank03LowLevelMessage); wait(WAIT_AFTER_SEND_MESSAGE); break; case TANK03_HIGH_LEVEL_ID: if (message.getInt()) tank03HighLevel = HIGH_LEVEL; else tank03HighLevel = NOT_HIGH_LEVEL; tank03HighLevelMessage.set(tank03HighLevel); send(tank03HighLevelMessage); wait(WAIT_AFTER_SEND_MESSAGE); break; } if (tank02LowLevel && !tank03LowLevel && !sumpMotorOn) turnOnSumpMotor(); if (sumpMotorOn) { send(tank02Message.set(RELAY_ON)); wait(WAIT_AFTER_SEND_MESSAGE); } if ((tank02HighLevel || tank03LowLevel) && sumpMotorOn) turnOffSumpMotor(); if (!sumpMotorOn) { send(tank02Message.set(RELAY_OFF)); wait(WAIT_AFTER_SEND_MESSAGE); } break; } } void turnOnSumpMotor() { digitalWrite(RELAY_PIN, RELAY_ON); send(sumpMotorRelayMessage.set(RELAY_ON)); wait(WAIT_AFTER_SEND_MESSAGE); send(thingspeakMessage.set(RELAY_ON)); wait(WAIT_AFTER_SEND_MESSAGE); digitalWrite(MOTOR_STATUS_PIN, RELAY_ON); sumpMotorOn = true; } void turnOffSumpMotor() { digitalWrite(RELAY_PIN, RELAY_OFF); send(sumpMotorRelayMessage.set(RELAY_OFF)); wait(WAIT_AFTER_SEND_MESSAGE); send(thingspeakMessage.set(RELAY_OFF)); wait(WAIT_AFTER_SEND_MESSAGE); digitalWrite(MOTOR_STATUS_PIN, RELAY_OFF); sumpMotorOn = false; } void sendUpdate() { if(digitalRead(RELAY_PIN)) send(sumpMotorRelayMessage.set(RELAY_ON)); else send(sumpMotorRelayMessage.set(RELAY_OFF)); wait(WAIT_AFTER_SEND_MESSAGE); } void keypadEvent(KeypadEvent key) { switch (keypad.getState()) { case PRESSED: switch (key) { case '1': if (!tank02HighLevel && !tank03LowLevel && !sumpMotorOn) turnOnSumpMotor(); break; case '2': if (sumpMotorOn) turnOffSumpMotor(); break; } break; case HOLD: switch (key) { case '1': if (!tank02HighLevel && !tank03LowLevel && !sumpMotorOn) turnOnSumpMotor(); break; case '2': if (sumpMotorOn) turnOffSumpMotor(); break; } break; } }
/*************************************************************************** Copyright (c) 2020 Philip Fortier This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ***************************************************************************/ #include "stdafx.h" #include "LevelMeter.h" #include "AudioRecording.h" #include "format.h" IMPLEMENT_DYNAMIC(LevelMeter, CStatic) #define LEVEL_TIMER 8361 #define LOW_FREQ_TIMER 9526 // LevelMeter control const int MaxSegments = 15; LevelMeter::~LevelMeter() {} LevelMeter::LevelMeter() : CStatic(), _level(0), _monitor(false), _maxRecentLevel(0) { } void LevelMeter::PreSubclassWindow() { SetTimer(LOW_FREQ_TIMER, 100, nullptr); __super::PreSubclassWindow(); } void LevelMeter::Monitor(bool monitor) { if (monitor) { SetTimer(LEVEL_TIMER, 30, nullptr); } else { _level = 0; _maxRecentLevel = 0; KillTimer(LEVEL_TIMER); } if (_monitor != monitor) { _monitor = monitor; if (!_monitor) { g_audioRecording.StopMonitor(); } Invalidate(FALSE); } if (_checkbox) { _checkbox->SetCheck(_monitor ? BST_CHECKED : BST_UNCHECKED); } } void LevelMeter::OnTimer(UINT_PTR nIDEvent) { if (nIDEvent == LEVEL_TIMER) { _level = g_audioRecording.GetLevel(); _maxRecentLevel = max(_maxRecentLevel, _level); RedrawWindow(nullptr); } else if (nIDEvent == LOW_FREQ_TIMER) { // If we're not monitoring, but we've started recording, turn ourselves on. if (!_monitor && g_audioRecording.IsRecording()) { Monitor(true); } // Also, use this to decrease the level we show _maxRecentLevel -= 100 / MaxSegments; _maxRecentLevel = max(_maxRecentLevel, _level); } } void LevelMeter::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { LPRECT prc = &lpDrawItemStruct->rcItem; CDC dc; dc.Attach(lpDrawItemStruct->hDC); InflateRect(prc, -1, -1); int activeSegmentCount = _maxRecentLevel * MaxSegments / 100; int gap = 1; int segmentWidth = RECTWIDTH(*prc) / MaxSegments; int lightWidth = max(1, segmentWidth - gap); int remainder = 0; for (int i = 0; i < activeSegmentCount; i++) { COLORREF color = RGB(0, 255, 0); if (i >= 14) { color = RGB(255, 0, 0); } else if (i > 10) { color = RGB(255, 255, 0); } CRect rcLight = { i * segmentWidth, prc->top, i * segmentWidth + lightWidth, prc->bottom }; dc.FillSolidRect(&rcLight, color); CRect rcGap = { rcLight.right, prc->top, rcLight.right + gap, prc->bottom }; dc.FillSolidRect(&rcGap, RGB(0, 0, 0)); remainder = rcGap.right; } CRect rcEnd = { remainder, prc->top, prc->right, prc->bottom }; dc.FillSolidRect(&rcEnd, _monitor ? RGB(0, 0, 0) : RGB(96, 96, 96)); // Draw a bevel around the edge InflateRect(prc, 1, 1); CPen pen(PS_SOLID, 1, RGB(0, 0, 0)); HGDIOBJ hOldPen = dc.SelectObject(pen); dc.MoveTo(prc->left, prc->top); dc.LineTo(prc->right, prc->top); dc.LineTo(prc->right, prc->bottom); CPen lightPen(PS_SOLID, 1, RGB(128, 128, 128)); dc.SelectObject(lightPen); dc.LineTo(prc->left, prc->bottom); dc.LineTo(prc->left, prc->top); dc.SelectObject(hOldPen); dc.Detach(); } BEGIN_MESSAGE_MAP(LevelMeter, CStatic) ON_WM_TIMER() ON_WM_DRAWITEM_REFLECT() END_MESSAGE_MAP()
/* ------------------------------------------------------------------------- // 文件名 : tinyhttp.cpp // 创建者 : magictong // 创建时间 : 2016/11/16 17:13:55 // 功能描述 : support windows of tinyhttpd, use mutilthread... // // $Id: $ // -----------------------------------------------------------------------*/ /* J. David's webserver */ /* This is a simple webserver. * Created November 1999 by J. David Blackstone. * CSE 4344 (Network concepts), Prof. Zeigler * University of Texas at Arlington */ /* This program compiles for Sparc Solaris 2.6. * To compile for Linux: * 1) Comment out the #include <pthread.h> line. * 2) Comment out the line that defines the variable newthread. * 3) Comment out the two lines that run pthread_create(). * 4) Uncomment the line that runs accept_request(). * 5) Remove -lsocket from the Makefile. */ #include "stdafx.h" #include "windowcgi.h" #include "ThreadProc.h" #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <WinSock2.h> #pragma comment(lib, "wsock32.lib") #pragma warning(disable : 4267) #define ISspace(x) isspace((int)(x)) #define SERVER_STRING "Server: tinyhttp /0.1.0\r\n" // ------------------------------------------------------------------------- // ------------------------------------------------------------------------- // 类名 : CTinyHttp // 功能 : // 附注 : // ------------------------------------------------------------------------- class CTinyHttp { public: typedef struct tagSocketContext { SOCKET socket_Client; tagSocketContext() : socket_Client(-1) {} } SOCKET_CONTEXT, *PSOCKET_CONTEXT; /**********************************************************************/ /* A request has caused a call to accept() on the server port to * return. Process the request appropriately. * Parameters: the socket connected to the client */ /**********************************************************************/ void accept_request(nilstruct&, SOCKET_CONTEXT& socket_context) { printf("Tid[%u] accept_request\n", (unsigned int)::GetCurrentThreadId()); #ifdef _DEBUG // 测试是否可以并发 ::Sleep(200); #endif char buf[1024] = {0}; int numchars = 0; char method[255] = {0}; char url[255] = {0}; char path[512] = {0}; int i = 0, j = 0; struct stat st; int cgi = 0; /* becomes true if server decides this is a CGI program */ char* query_string = NULL; SOCKET client = socket_context.socket_Client; numchars = get_line(client, buf, sizeof(buf)); // 获取HTTP的请求方法名 while (j < numchars && !ISspace(buf[j]) && (i < sizeof(method) - 1)) { method[i] = buf[j]; i++; j++; } method[i] = '\0'; if (_stricmp(method, "GET") != 0 && _stricmp(method, "POST")) // 只处理GET请求 { if (numchars > 0) { discardheaders(client); } unimplemented(client); closesocket(client); return; } if (_stricmp(method, "POST") == 0) cgi = 1; // POST请求,当成CGI处理 // 获取到URL路径,存放到url字符数组里面 i = 0; while (ISspace(buf[j]) && (j < sizeof(buf))) { j++; } while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf))) { url[i] = buf[j]; i++; j++; } url[i] = '\0'; if (_stricmp(method, "GET") == 0) { query_string = url; while ((*query_string != '?') && (*query_string != '\0')) query_string++; if (*query_string == '?') { // URL带参数,当成CGI处理 cgi = 1; *query_string = '\0'; query_string++; } } sprintf_s(path, 512, "htdocs%s", url); if (path[strlen(path) - 1] == '/') { // 补齐 strcat_s(path, 512, "index.html"); } if (stat(path, &st) == -1) { // 文件不存在 if (numchars > 0) { discardheaders(client); } not_found(client); } else { // 如果是文件夹则补齐 if ((st.st_mode & S_IFMT) == S_IFDIR) strcat_s(path, 512, "/index.html"); if (st.st_mode & S_IEXEC) cgi = 1; // 具有可执行权限 if (!cgi) { serve_file(client, path); } else { execute_cgi(client, path, method, query_string); } } closesocket(client); } /**********************************************************************/ /* Execute a CGI script. Will need to set environment variables as * appropriate. * Parameters: client socket descriptor * path to the CGI script */ /**********************************************************************/ void execute_cgi(SOCKET client, const char *path, const char* method, const char* query_string) { char buf[1024] = {0}; int cgi_output[2] = {0}; int cgi_input[2] = {0}; int i = 0; char c = 0; int numchars = 1; int content_length = -1; buf[0] = 'A'; buf[1] = '\0'; if (_stricmp(method, "GET") == 0) { discardheaders(client); } else /* POST */ { numchars = get_line(client, buf, sizeof(buf)); while ((numchars > 0) && strcmp("\n", buf)) { buf[15] = '\0'; if (_stricmp(buf, "Content-Length:") == 0) { content_length = atoi(&(buf[16])); } numchars = get_line(client, buf, sizeof(buf)); } if (content_length == -1) { bad_request(client); return; } } CWinCGI cgi; if (!cgi.Exec(path, query_string)) { bad_request(client); return; } //SOCKET client, const char *path, const char* method, const char* query_string if (_stricmp(method, "POST") == 0) { for (i = 0; i < content_length; i++) { recv(client, &c, 1, 0); cgi.Write((PBYTE)&c, 1); } c = '\n'; cgi.Write((PBYTE)&c, 1); } cgi.Wait(); char outBuff[2048] = {0}; cgi.Read((PBYTE)outBuff, 2047); send(client, outBuff, strlen(outBuff), 0); } /**********************************************************************/ /* Put the entire contents of a file out on a socket. This function * is named after the UNIX "cat" command, because it might have been * easier just to do something like pipe, fork, and exec("cat"). * Parameters: the client socket descriptor * FILE pointer for the file to cat */ /**********************************************************************/ void cat(SOCKET client, FILE *resource) { char buf[1024] = {0}; do { fgets(buf, sizeof(buf), resource); size_t len = strlen(buf); if (len > 0) { send(client, buf, len, 0); } } while (!feof(resource)); } /**********************************************************************/ /* Print out an error message with perror() (for system errors; based * on value of errno, which indicates system call errors) and exit the * program indicating an error. */ /**********************************************************************/ void error_die(const char *sc) { perror(sc); exit(1); } /**********************************************************************/ /* Get a line from a socket, whether the line ends in a newline, * carriage return, or a CRLF combination. Terminates the string read * with a null character. If no newline indicator is found before the * end of the buffer, the string is terminated with a null. If any of * the above three line terminators is read, the last character of the * string will be a linefeed and the string will be terminated with a * null character. * Parameters: the socket descriptor * the buffer to save the data in * the size of the buffer * Returns: the number of bytes stored (excluding null) */ /**********************************************************************/ int get_line(SOCKET sock, char *buf, int size) { int i = 0; char c = '\0'; int n; while ((i < size - 1) && (c != '\n')) { n = recv(sock, &c, 1, 0); /* DEBUG printf("%02X\n", c); */ if (n > 0) { if (c == '\r') { n = recv(sock, &c, 1, MSG_PEEK); /* DEBUG printf("%02X\n", c); */ if ((n > 0) && (c == '\n')) { recv(sock, &c, 1, 0); } else { c = '\n'; } } buf[i] = c; i++; } else { c = '\n'; } } buf[i] = '\0'; return(i); } /**********************************************************************/ /* Return the informational HTTP headers about a file. */ /* Parameters: the socket to print the headers on * the name of the file */ /**********************************************************************/ void headers(SOCKET client, const char *filename) { (void)filename; char* pHeader = "HTTP/1.0 200 OK\r\n"\ SERVER_STRING \ "Content-Type: text/html\r\n\r\n"; send(client, pHeader, strlen(pHeader), 0); } /**********************************************************************/ /* Give a client a 404 not found status message. */ /**********************************************************************/ void not_found(SOCKET client) { char* pResponse = "HTTP/1.0 404 NOT FOUND\r\n"\ SERVER_STRING \ "Content-Type: text/html\r\n\r\n"\ "<HTML><TITLE>Not Found</TITLE>\r\n"\ "<BODY><P>The server could not fulfill\r\n"\ "your request because the resource specified\r\n"\ "is unavailable or nonexistent.\r\n"\ "</BODY></HTML>\r\n"; send(client, pResponse, strlen(pResponse), 0); } /**********************************************************************/ /* Inform the client that the requested web method has not been * implemented. * Parameter: the client socket */ /**********************************************************************/ void unimplemented(SOCKET client) { char* pResponse = "HTTP/1.0 501 Method Not Implemented\r\n"\ SERVER_STRING \ "Content-Type: text/html\r\n\r\n"\ "<HTML><HEAD><TITLE>Method Not Implemented\r\n"\ "</TITLE></HEAD>\r\n"\ "<BODY><P>HTTP request method not supported.</P>\r\n"\ "</BODY></HTML>\r\n"; send(client, pResponse, strlen(pResponse), 0); } /**********************************************************************/ /* Inform the client that a CGI script could not be executed. * Parameter: the client socket descriptor. */ /**********************************************************************/ void cannot_execute(SOCKET client) { char* pResponse = "HTTP/1.0 500 Internal Server Error\r\n"\ "Content-Type: text/html\r\n\r\n"\ "<P>Error prohibited CGI execution.</P>\r\n"; send(client, pResponse, strlen(pResponse), 0); } /**********************************************************************/ /* Inform the client that a request it has made has a problem. * Parameters: client socket */ /**********************************************************************/ void bad_request(SOCKET client) { char* pResponse = "HTTP/1.0 400 BAD REQUEST\r\n"\ "Content-Type: text/html\r\n\r\n"\ "<P>Your browser sent a bad request, such as a POST without a Content-Length.</P>\r\n"; send(client, pResponse, strlen(pResponse), 0); } /**********************************************************************/ /* Send a regular file to the client. Use headers, and report * errors to client if they occur. * Parameters: a pointer to a file structure produced from the socket * file descriptor * the name of the file to serve */ /**********************************************************************/ void serve_file(SOCKET client, const char *filename) { FILE *resource = NULL; discardheaders(client); fopen_s(&resource, filename, "r"); if (resource == NULL) { not_found(client); } else { headers(client, filename); cat(client, resource); } fclose(resource); } // ------------------------------------------------------------------------- // 函数 : discardheaders // 功能 : 清除http头数据(从网络中全部读出来) // 返回值 : void // 参数 : SOCKET client // 附注 : // ------------------------------------------------------------------------- void discardheaders(SOCKET client) { char buf[1024] = {0}; int numchars = 1; while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */ { numchars = get_line(client, buf, sizeof(buf)); } } /**********************************************************************/ /* This function starts the process of listening for web connections * on a specified port. If the port is 0, then dynamically allocate a * port and modify the original port variable to reflect the actual * port. * Parameters: pointer to variable containing the port to connect on * Returns: the socket */ /**********************************************************************/ SOCKET startup(u_short* port) { SOCKET httpd = 0; struct sockaddr_in name = {0}; httpd = socket(AF_INET, SOCK_STREAM, 0); if (httpd == INVALID_SOCKET) { error_die("startup socket"); } name.sin_family = AF_INET; name.sin_port = htons(*port); name.sin_addr.s_addr = inet_addr("127.0.0.1"); if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0) { error_die("startup bind"); } if (*port == 0) /* if dynamically allocating a port */ { int namelen = sizeof(name); if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1) { error_die("getsockname"); } *port = ntohs(name.sin_port); } if (listen(httpd, 5) < 0) { error_die("listen"); } return httpd; } }; // End Class CTinyHttp int _tmain(int argc, _TCHAR* argv[]) { SOCKET server_sock = INVALID_SOCKET; //u_short port = 0; u_short port = 80; struct sockaddr_in client_name = {0}; int client_name_len = sizeof(client_name); typedef CMultiTaskThreadPoolT<CTinyHttp, CTinyHttp::SOCKET_CONTEXT, nilstruct, 5, CComMultiThreadModel::AutoCriticalSection> CMultiTaskThreadPool; CTinyHttp tinyHttpSvr; // init socket WSADATA wsaData = {0}; WSAStartup(MAKEWORD(2, 2), &wsaData); server_sock = tinyHttpSvr.startup(&port); printf("httpd running on port: %d\n", port); CMultiTaskThreadPool m_threadpool(&tinyHttpSvr, &CTinyHttp::accept_request); while (1) { CTinyHttp::SOCKET_CONTEXT socket_context; socket_context.socket_Client = accept(server_sock, (struct sockaddr *)&client_name, &client_name_len); if (socket_context.socket_Client == INVALID_SOCKET) { tinyHttpSvr.error_die("accept"); } printf("Tid[%u] accetp new connect: %u\n", (unsigned int)::GetCurrentThreadId(), (unsigned int)socket_context.socket_Client); m_threadpool.AddTask(socket_context); } // can not to run this m_threadpool.EndTasks(); closesocket(server_sock); WSACleanup(); return 0; } // ------------------------------------------------------------------------- // $Log: $
// // Created by Fabian Terhorst on 02.12.19. // #ifndef NATIVE_JAVAFUNCTION_H #define NATIVE_JAVAFUNCTION_H #include <jni.h> #include <jni.h> #include "Function.h" /** * A C++ Function suitable for JNI calls. */ class JavaFunction : public Function { private: JNIEnv* env; // JVM environment jobject instance; // the Java function instance jmethodID fct; // the Java method jstring jname; // the Java function name jdoubleArray array; // the Java array as argument public: /** * Constructor to wrap a Java Function implementation. */ JavaFunction(JNIEnv* env, jobject instance); ~JavaFunction() override; // overloaded operator to execute double y = f(x) // for java functions implementations. double operator()(double x) const override { // our C++ functions are one dimensional the java function not... env->SetDoubleArrayRegion(array, 0, 1, &x); return (env->CallDoubleMethod(instance, fct, array)); } }; #endif //NATIVE_JAVAFUNCTION_H
// myinterpreter.cpp : Defines the initialization routines for the DLL. // #include "stdafx.h" #include "myinterpreter.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #include<stdio.h> #include<string.h> #include<stdlib.h> #include "datastructure.h" // // Note! // // If this DLL is dynamically linked against the MFC // DLLs, any functions exported from this DLL which // call into MFC must have the AFX_MANAGE_STATE macro // added at the very beginning of the function. // // For example: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // normal function body here // } // // It is very important that this macro appear in each // function, prior to any calls into MFC. This means that // it must appear as the first statement within the // function, even before any object variable declarations // as their constructors may generate calls into the MFC // DLL. // // Please see MFC Technical Notes 33 and 58 for additional // details. // ///////////////////////////////////////////////////////////////////////////// // CMyinterpreterApp BEGIN_MESSAGE_MAP(CMyinterpreterApp, CWinApp) //{{AFX_MSG_MAP(CMyinterpreterApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CMyinterpreterApp construction CMyinterpreterApp::CMyinterpreterApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CMyinterpreterApp object CMyinterpreterApp theApp; int t,a,b,sx,c1,c2,lc; //各种表格的索引 bool canexe; //是否可以解释执行p代码 int display[lmax]; //分程序索引表 table tab[tmax+1]; //符号表 btable btab[bmax+1]; //分程序表 char stab[smax+1]; //字符串常量数组 double rconst[c2max]; //实常量数组 order code[cmax+1]; //p代码数组 atable atab[amax+1]; //数组信息向量表 bool readbinary(char *file){ char bfile[200]; strcpy(bfile,file); FILE *fp=fopen(bfile,"rb"); if(!fp){ printf("文件名不对!\n"); system("pause"); return false; } fread(&t,sizeof(int),1,fp); // fscanf(fp,"%d",&t); fread(tab,sizeof(table),t+1,fp); fread(&b,sizeof(int),1,fp); // fscanf(fp,"%d",&b); fread(btab,sizeof(btable),b+1,fp); fread(&sx,sizeof(int),1,fp); // fscanf(fp,"%d",&sx); fread(stab,sizeof(char),sx+1,fp); fread(&c2,sizeof(int),1,fp); // fscanf(fp,"%d",&c2); fread(rconst,sizeof(double),c2+1,fp); fread(&lc,sizeof(int),1,fp); // fscanf(fp,"%d",&lc); fread(code,sizeof(order),lc+1,fp); fread(&a,sizeof(int),1,fp); fread(atab,sizeof(atable),a+1,fp); fclose(fp); return true; } extern "C" _declspec(dllexport) void interpreter(char *file){ AFX_MANAGE_STATE(AfxGetStaticModuleState()); if(!readbinary(file)){ printf("加载文件出错!\n"); return; } order ir; int pc; int t; int b; int h1,h2,h3,h4; int lncnt,ocnt; enum p {run,fin,divchk,inxchk,stkchk,linchk,}; int display[lmax]; char temp; struct datastack{ int i; double r; }; datastack s[stacksize+1]; p ps; s[1].i=0; s[2].i=0; s[3].i=-1;s[4].i=btab[1].last; display[1]=0;t=btab[2].vsize-1; b=0; pc=tab[s[4].i].adr; lncnt=0;ocnt=0; ps=run; do{ ir=code[pc]; pc++;ocnt++; switch(ir.f){ case 0: t++; if(t>stacksize) ps=stkchk; else s[t].i=display[ir.x]+ir.y; break; case 1: t++; if(t>stacksize) ps=stkchk; else s[t]=s[display[ir.x]+ir.y]; break; case 2:; t++; if(t>stacksize) ps=stkchk; else s[t]=s[s[display[ir.x]+ir.y].i]; break; case 3: h1=ir.y;h2=ir.x;h3=b; do{ display[h1]=h3;h1--;h3=s[h3+2].i; }while(h1!=h2); break; case 9: s[t].i=s[t].i+ir.y; break; case 10: pc=ir.y; break; case 11: if(!s[t].i) pc=ir.y; t--; break; case 12: if(s[t].i) pc=ir.y; t--; break; case 14: h1=s[t-1].i; if(h1<=s[t].i){ s[s[t-2].i].i=h1; } else { t=t-3; pc=ir.y; } break; case 15: h2=s[t-2].i; h1=s[h2].i+1; if(h1<=s[t].i) { s[h2].i=h1;pc=ir.y; } else { t=t-3; } break; case 16: h1=s[t-1].i; if(h1>=s[t].i) { s[s[t-2].i].i=h1; } else { pc=ir.y;t=t-3; } break; case 17: h2=s[t-2].i; h1=s[h2].i-1; if(h1>=s[t].i) { s[h2].i=h1;pc=ir.y; } else { t=t-3; } break; case 18: h1=btab[tab[ir.y].ref].vsize; if(t+h1>stacksize) ps=stkchk; else { t=t+5; s[t-1].i=h1-1;s[t].i=ir.y; } break; case 19: h1=t-ir.y; h2=s[h1+4].i; h3=tab[h2].lev; display[h3+1]=h1; h4=s[h1+3].i+h1; s[h1+1].i=pc; s[h1+3].i=b; for(h3=t+1;h3<=h4;++h3) s[h3].i=0; b=h1;t=h4; pc=tab[h2].adr; break; case 20: h1=ir.y; h2=atab[h1].low; h3=s[t].i; if(h3<h2) ps=inxchk; else if(h3>atab[h1].high) ps=inxchk; else { --t; s[t].i+=h3-h2; } break; case 21: h1=ir.y; h2=atab[h1].low; h3=s[t].i; if(h3<h2) ps=inxchk; else if(h3>atab[h1].high) ps=inxchk; else { --t; s[t].i+=(h3-h2)*atab[h1].elsize; } break; case 22: h1=s[t].i;t--; h2=ir.y+t; if(h2>stacksize) ps=stkchk; else while(t<h2){ t++; s[t]=s[h1];h1++; } break; case 23: h1=s[t-1].i; h2=s[t].i; h3=h1+ir.y; while(h1<h3){ s[h1]=s[h2]; h1++; h2++; } t=t-2; break; case 24: t++; if(t>stacksize) ps=stkchk; else s[t].i=ir.y; break; case 25: t++; if(t>stacksize) ps=stkchk; else s[t].r=rconst[ir.y]; break; case 26: h1=t-ir.y; s[h1].r=s[h1].i; break; case 27: switch(ir.y){ case 1: scanf("%d",&s[s[t].i].i); break; case 2: scanf("%lf",&s[s[t].i].r); break; case 3: do{ temp=getchar(); }while(temp=='\n'); s[s[t].i].i=(int)temp; break; } --t; break; case 28: h1=s[t].i; h2=ir.y;t--; if(h1!=0) do{ printf("%c",(char)stab[h2]); h1--; h2++; }while(h1!=0); break; case 29: switch(ir.y){ case 1: printf("%d",s[t].i); break; case 2: printf("%lf",s[t].r); break; case 3: printf("%c",(char)s[t].i); break; } t--; break; case 31: ps=fin; break; case 32: t=b-1; pc=s[b+1].i;b=s[b+3].i; break; case 33: t=b; pc=s[b+1].i;b=s[b+3].i; break; case 34: s[t]=s[s[t].i]; break; case 36: s[t].i=-s[t].i; s[t].r=-s[t].r; break; case 38: s[s[t-1].i]=s[t]; t=t-2; break; case 39: t--; if(s[t].r==s[t+1].r) s[t].i=1; else s[t].i=0; break; case 40: t--; if(s[t].r!=s[t+1].r) s[t].i=1; else s[t].i=0; break; case 41: t--; if(s[t].r<s[t+1].r) s[t].i=1; else s[t].i=0; break; case 42: t--; if(s[t].r<=s[t+1].r) s[t].i=1; else s[t].i=0; break; case 43: t--; if(s[t].r>s[t+1].r) s[t].i=1; else s[t].i=0; break; case 44: t--; if(s[t].r>=s[t+1].r) s[t].i=1; else s[t].i=0; break; case 45: t--; if(s[t].i==s[t+1].i) s[t].i=1; else s[t].i=0; break; case 46: t--; if(s[t].i!=s[t+1].i) s[t].i=1; else s[t].i=0; break; case 47: t--; if(s[t].i<s[t+1].i) s[t].i=1; else s[t].i=0; break; case 48: t--; if(s[t].i<=s[t+1].i) s[t].i=1; else s[t].i=0; break; case 49: t--; if(s[t].i>s[t+1].i) s[t].i=1; else s[t].i=0; break; case 50: t--; if(s[t].i>=s[t+1].i) s[t].i=1; else s[t].i=0; break; case 52: t--; s[t].i=s[t].i+s[t+1].i; break; case 53: t--; s[t].i=s[t].i-s[t+1].i; break; case 54: t--; s[t].r=s[t].r+s[t+1].r; break; case 55: t--; s[t].r=s[t].r-s[t+1].r; break; case 57: t--; s[t].i=s[t].i*s[t+1].i; break; case 58: t--; if(s[t+1].i==0) ps=divchk; else s[t].i=s[t].i/s[t+1].i; break; case 60: t--; s[t].r=s[t].r*s[t+1].r; break; case 61: t--; if(s[t+1].r==0) ps=divchk; else s[t].r=s[t].r/s[t+1].r; break; case 63: printf("\n"); break; } }while(ps==run); if(ps!=fin){ printf("halt at %5d because of",pc-1); switch(ps){ case divchk: printf("\ndivision by 0!\n"); break; case inxchk: printf("\ninvalid index!\n"); break; case stkchk: printf("\nstorage overflow!\n"); break; case linchk: printf("\ntoo much output!\n"); break; } } else printf("\nThe program has executed successfully!\n"); system("pause"); }
#include<stdio.h> #include<malloc.h> #include<stdlib.h> struct tnode{ int data; struct tnode *left; struct tnode *right; }; struct snode{ struct tnode *t; struct snode *next; }; struct tnode *newNode(int data){ struct tnode *temp=(struct tnode *)malloc(sizeof(struct tnode)); temp->data=data; temp->left=NULL; temp->right=NULL; return temp; } int Inorder(struct tnode *root){ struct tnode *current=root; struct snode *s=NULL; bool done=0; while(!done) { if(current!=NULL){ push(&s,current); current=current->left; } else{ if(!empty(s)){ } } }
#define ROW_1 2 #define ROW_2 3 #define ROW_3 4 #define ROW_4 5 #define ROW_5 6 #define ROW_6 7 #define ROW_7 8 #define ROW_8 9 #define COL_1 22 #define COL_2 23 #define COL_3 24 #define COL_4 25 #define COL_5 26 #define COL_6 27 #define COL_7 28 #define COL_8 29 int button1=36; int button2=38; int control1; int controlscore,controlheart,controlface=0; const byte rows[] = { ROW_1, ROW_2, ROW_3, ROW_4, ROW_5, ROW_6, ROW_7, ROW_8 }; //(1 = ON, 0 = OFF) byte heart1[] = {B00110110,B01110111,B01111111,B01111111,B00111110,B00011100,B00001000,B00000000}; byte heart2[] = {B00000000,B00110110,B01111111,B01111111,B01111111,B00111110,B00011100,B00001000}; byte heart3[]={B00001000,B00000000,B00110110,B01111111,B01111111,B01111111,B00111110,B00011100}; byte heart4[]={B00011100,B00001000,B00000000,B00110110,B01111111,B01111111,B01111111,B00111110}; byte heart5[]={B00111110,B00011100,B00001000,B00000000,B00110110,B01111111,B01111111,B01111111}; byte heart6[]={B01111111,B00111110,B00011100,B00001000,B00000000,B00110110,B01111111,B01111111}; byte heart7[]={B01111111,B01111111,B00111110,B00011100,B00001000,B00000000,B00110110,B01111111}; byte heart8[]={B01111111,B01111111,B01111111,B00111110,B00011100,B00001000,B00000000,B00110110}; byte smile[]={B00000000,B00110110,B00110110,B00000000,B01111111,B01111111,B00111110,B00011100}; byte sad[]={B00000000,B00110110,B00110110,B00000000,B00111110,B01111111,B01100011,B01000001}; byte angry[]={B01000001,B00100010,B00010100,B00000000,B00111110,B01000001,B01000001,B00111110}; byte happy[]={B00000000,B00100010,B00010100,B00100010,B00000000,B01100011,B00111110,B00011100}; byte Aplus[]={B00100000,B01110000,B00101110,B00010001,B00010001,B00011111,B00010001,B00010001}; byte A[]={B00000000,B00011100,B00100010,B00100010,B00111110,B00100010,B00100010,B00000000}; byte Bplus[]={B00100000,B01110111,B00101001,B00001001,B00000111,B00001001,B00001001,B00000111}; byte B[]={B00011110,B00100010,B00100010,B00011110,B00100010,B00100010,B00100010,B00011110}; byte Cplus[]={B00100000,B01110000,B00101110,B00010001,B00000001,B00000001,B00010001,B00001110}; byte C[]={B00000000,B00011100,B00100010,B00000010,B00000010,B00100010,B00011100,B00000000}; byte F[]={B00111110,B00000010,B00000010,B00011110,B00000010,B00000010,B00000010,B00000010}; float timeCount,timeCount2,timeCount3 = 0; int a,b,c; void setup() { Serial.begin(9600); for (byte i = 2; i <= 9; i++){ pinMode(i, OUTPUT); } for (byte i = 22; i <= 28; i++){ pinMode(i, OUTPUT); } pinMode(36,INPUT); pinMode(38,INPUT); } void loop() { delay(5); int state1=digitalRead(button1); int state2=digitalRead(button2); if( state1 ==0 ){ control1++; if(control1==3){ control1=0; } delay(200); } if(control1==0){ drawheart(); } else if(control1==1){ drawface(); } else if(control1==2){ drawscore(); } //1번 버튼- 그림 종류 선택 //if(state2==0){ // control2++; // if(control2==2){ // control2=0; // } // delay(200); //} if(state2==0){ if(control1==0){ controlheart++; if (controlheart==2){ controlheart=0; } delay(200); } else if(control1==1){ controlface++; if (controlface==2){ controlface=0; } delay(200); } else if(control1==2){ controlscore++; if (controlscore==2){ controlscore=0; } delay(200); } } //1번그림 if(controlheart==0 && control1==0){ if (a==1){ drawScreen(heart1); } else if(a==2){ drawScreen(heart2); } else if(a==3){ drawScreen(heart3); } else if(a==4){ drawScreen(heart4); } else if(a==5){ drawScreen(heart5); } else if(a==6){ drawScreen(heart6); } else if(a==7){ drawScreen(heart7); } else if(a==8){ drawScreen(heart8); } else{ } } else if(controlheart==1 && control1==0){ if (a==1){ timeCount=0; } else if(a==2){ timeCount=40; } else if(a==3){ timeCount=80; } else if(a==4){ timeCount=120; } else if(a==5){ timeCount=160; } else if(a==6){ timeCount=200; } else if(a==7){ timeCount=240; } else if(a==8){ timeCount=280; } else{ } } //2번그림 if(controlface==0 && control1==1){ if (b==1){ drawScreen(smile); } else if(b==2){ drawScreen(sad); } else if(b==3){ drawScreen(angry); } else if(b=4){ drawScreen(happy); } else{ drawScreen(smile); } } else if(controlface==1 && control1==1){ if (b==1){ timeCount2=0; } else if(b==2){ timeCount2=40; } else if(b==3){ timeCount2=80; } else if(b==4){ timeCount2=120; } else{ } } if(controlscore==0 && control1==2){ if (c==1){ drawScreen(Aplus); } else if(c==2){ drawScreen(A); } else if(c==3){ drawScreen(Bplus); } else if(c==4){ drawScreen(B); } else if(c==5){ drawScreen(Cplus); } else if(c==6){ drawScreen(C); } else if(c==7){ drawScreen(F); } else{ } } else if(controlscore==1 && control1==2){ if (c==1){ timeCount3=0; } else if(c==2){ timeCount3=30; } else if(c==3){ timeCount3=60; } else if(c==4){ timeCount3=90; } else if(c==5){ timeCount3=120; } else if(c==6){ timeCount3=150; } else if(c==7){ timeCount3=180; } else{ } } } //2번 버튼 void drawscore(){ timeCount3 += 1; if(timeCount3 < 20) { drawScreen(Aplus); c=1; } else if (timeCount3 < 30) { } else if (timeCount3 < 50) { drawScreen(A); c=2; } else if (timeCount3 < 60) { //N } else if (timeCount3 < 80) { drawScreen(Bplus); c=3; } else if (timeCount3 < 90) { //N } else if (timeCount3 < 110) { drawScreen(B); c=4; } else if (timeCount3 < 120) { //N } else if (timeCount3 < 140) { drawScreen(Cplus); c=5; } else if (timeCount3 < 150) { //N } else if (timeCount3 < 170) { drawScreen(C); c=6; } else if (timeCount3 < 180) { //N } else if (timeCount3 < 200) { drawScreen(F); c=7; } else if (timeCount3 < 210) { //N } else { // back to the start timeCount3 = 0; } } void drawface(){ timeCount2 += 1; if(timeCount2 < 30) { drawScreen(smile); b=1; } else if (timeCount2 < 40) { } else if (timeCount2 < 70) { drawScreen(sad); b=2; } else if (timeCount2 < 80) { //N } else if (timeCount2<110){ drawScreen(angry); b=3; } else if(timeCount2<120){ } else if(timeCount2<150){ drawScreen(happy); b=4; } else if(timeCount2<160){ } else { // back to the start timeCount2 = 0; } } void drawheart(){ timeCount += 1; if(timeCount < 30) { drawScreen(heart1); a=1; } else if (timeCount < 40) { } else if (timeCount < 70) { drawScreen(heart2); a=2; } else if (timeCount < 80) { //N } else if (timeCount<110){ drawScreen(heart3); a=3; } else if(timeCount<120){ } else if (timeCount<150){ drawScreen(heart4); a=4; } else if(timeCount<160){ } else if (timeCount<190){ drawScreen(heart5); a=5; } else if(timeCount<200){ } else if (timeCount<230){ drawScreen(heart6); a=6; } else if(timeCount<240){ } else if (timeCount<270){ drawScreen(heart7); a=7; } else if(timeCount<280){ } else if (timeCount<310){ drawScreen(heart8); a=8; } else if(timeCount<320){ } else { // back to the start timeCount = 0; } } void drawScreen(byte buffer2[]){ // Turn on each row in series for (byte i = 0; i < 8; i++) { setColumns(buffer2[i]); // Set columns for this specific row digitalWrite(rows[i], HIGH); delay(2); // Set this to 50 or 100 if you want to see the multiplexing effect! digitalWrite(rows[i], LOW); } } void setColumns(byte b) { digitalWrite(COL_1, (~b >> 0) & 0x01); // Get the 1st bit: 10000000 digitalWrite(COL_2, (~b >> 1) & 0x01); // Get the 2nd bit: 01000000 digitalWrite(COL_3, (~b >> 2) & 0x01); // Get the 3rd bit: 00100000 digitalWrite(COL_4, (~b >> 3) & 0x01); // Get the 4th bit: 00010000 digitalWrite(COL_5, (~b >> 4) & 0x01); // Get the 5th bit: 00001000 digitalWrite(COL_6, (~b >> 5) & 0x01); // Get the 6th bit: 00000100 digitalWrite(COL_7, (~b >> 6) & 0x01); // Get the 7th bit: 00000010 digitalWrite(COL_8, (~b >> 7) & 0x01); // Get the 8th bit: 00000001 }
/* * parser.cpp * * Created on: 9 Nov 2013 * Author: leal */ #include <iostream> #include <fstream> #include <vector> #include <string> #include <map> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/erase.hpp> class ILLParser { public: ILLParser(const std::string &filename) { fin.open(filename); } virtual ~ILLParser() { //if (fin != NULL) { if (!fin.fail() ){ fin.close(); } } /** * Main function */ void startParsing() { std::string line; while (std::getline(fin, line)) { if (line.find( "RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR") != std::string::npos) { parseFieldR(); } else if (line.find( "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") != std::string::npos) { parseFieldA(); } else if (line.find( "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII") != std::string::npos) { parseFieldNumeric(header, intWith); } else if (line.find( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF") != std::string::npos) { parseFieldNumeric(header, floatWith); } else if (line.find( "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS") != std::string::npos) { startParseSpectra(); } } } /** * Parse fields of type R and keep them in the header */ void parseFieldR() { std::string line; std::getline(fin, line); std::vector<std::string> parsedLineFields = splitLineInFixedWithFields( line, intWith); header["NRUN"] = parsedLineFields[0]; header["NTEXT"] = parsedLineFields[1]; header["NVERS"] = parsedLineFields[2]; } /** * Parse fields of type A */ void parseFieldA() { std::string line; std::getline(fin, line); std::vector<std::string> parsedLineFields = splitLineInFixedWithFields( line, intWith); // I'm not using this for now //int numberOfCharsToRead = evaluate<int>(parsedLineFields[0]); int numberOfLinesToRead = evaluate<int>(parsedLineFields[1]); std::string key; std::string value(""); std::getline(fin, key); for (int i = 0; i < numberOfLinesToRead; i++) { std::getline(fin, line); value += line; } header[key] = value; } /** * Parses a field of numeric type and puts the result in a map */ void parseFieldNumeric(std::map<std::string, std::string> &header, int fieldWith) { std::string line; std::getline(fin, line); int nNumericFields = -1, nTextLines = -1; sscanf(line.c_str(), "%d %d", &nNumericFields, &nTextLines); std::vector<std::string> keys(nNumericFields); std::vector<std::string> values(nNumericFields); size_t index = 0; for (int i = 0; i < nTextLines; i++) { std::getline(fin, line); std::vector<std::string> s = splitLineInFixedWithFields(line, fieldWith); for (auto it = s.begin(); it != s.end(); ++it) { keys[index] = *it; index += 1; } } // parse numeric fields int pos = 0; index = 0; while (pos < nNumericFields) { std::getline(fin, line); std::vector<std::string> s = splitLineInFixedWithFields(line, fieldWith); pos += s.size(); for (auto it = s.begin(); it != s.end(); ++it) { values[index] = *it; index += 1; } } std::vector<std::string>::const_iterator iKey; std::vector<std::string>::const_iterator iValue; for (iKey = keys.begin(), iValue = values.begin(); iKey < keys.end() && iValue < values.end(); ++iKey, ++iValue) { if (*iValue != "" && *iKey != "") { header[*iKey] = *iValue; } } } /** * Parses the spectrum */ std::vector<int> parseFieldISpec(int fieldWith = intWith) { std::string line; std::getline(fin, line); int nSpectra; sscanf(line.c_str(), "%d", &nSpectra); std::vector<int> spectrumValues(nSpectra); int nSpectraRead = 0, index = 0; while (nSpectraRead < nSpectra) { std::getline(fin, line); std::vector<std::string> s = splitLineInFixedWithFields(line, fieldWith); nSpectraRead += s.size(); for (auto it = s.begin(); it != s.end(); ++it) { sscanf(it->c_str(), "%d", &spectrumValues[index]); index += 1; } } return spectrumValues; } /** * Shows contents */ void showHeader() { std::cout << "* Global header" << '\n'; for (auto it = header.begin(); it != header.end(); ++it) std::cout << it->first << " => " << it->second << '\n'; std::cout << "* Spectrum header" << '\n'; int i = 0; std::vector<std::map<std::string, std::string> >::const_iterator s; for (s = spectraHeaders.begin(); s != spectraHeaders.end(); ++s) { std::cout << "** Spectrum i : " << i << '\n'; std::map<std::string, std::string>::const_iterator it; for (it = s->begin(); it != s->end(); ++it) std::cout << it->first << " => " << it->second << ','; std::cout << std::endl; i++; } std::cout << "* Spectrum list" << '\n'; std::vector<std::vector<int> >::const_iterator l; for (l = spectraList.begin(); l != spectraList.end(); ++l) { std::cout << "From " << (*l)[0] << " to " << (*l)[l->size() - 1] << " => " << l->size() << '\n'; } } void startParseSpectra() { std::string line; std::getline(fin, line); while (std::getline(fin, line)) { if (line.find( "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII") != std::string::npos) { spectraList.push_back(parseFieldISpec()); } else if (line.find( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF") != std::string::npos) { spectraHeaders.push_back(std::map<std::string, std::string>()); parseFieldNumeric(spectraHeaders.back(), floatWith); } else if (line.find( "SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS") != std::string::npos) { std::getline(fin, line); } } } /** * Splits a line in fixed length fields. */ std::vector<std::string> splitLineInFixedWithFields(const std::string &s, int fieldWidth, int lineWitdh = 80) { size_t outVecSize = lineWitdh / fieldWidth; std::vector<std::string> outVec(outVecSize); size_t pos = 0, posInVec = 0; while (pos + fieldWidth <= s.length()) { std::string subs = s.substr(pos, fieldWidth); if (subs.find_first_not_of(' ') != std::string::npos) { // not empty substring outVec[posInVec] = subs; posInVec += 1; } else { // delete not necessary entries outVec.erase(outVec.begin() + posInVec); } pos += fieldWidth; } return outVec; } template<typename T> T evaluate(std::string field) { boost::algorithm::erase_all(field, " "); //std::cout << subs << std::endl; T value; try { value = boost::lexical_cast<T>(field); } catch (boost::bad_lexical_cast &e) { throw e; } return value; } private: // each line being padded out to exactly 80 characters of text. //static const int lineWith = 80; static const int intWith = 8; static const int floatWith = 16; std::ifstream fin; std::map<std::string, std::string> header; std::vector<std::map<std::string, std::string> > spectraHeaders; std::vector<std::vector<int> > spectraList; }; int main_parser() { ILLParser p("/net/serdon/illdata/data/d2b/exp_5-21-1076/rawdata/123944"); p.startParsing(); p.showHeader(); std::cout << "Done!" << std::endl; return 0; }
#include<bits/stdc++.h> #define ll long long #define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) using namespace std; #define N 100000 #define limit 10000 int main() { io; ll test_case; //cin>>test_case; test_case=1; while(test_case--) { int n,k; cin>>n; char temp; vector<int> police; vector<int> thieves; for(int i=0;i<n;i++){ cin>>temp; if(temp=='T') thieves.push_back(i); else police.push_back(i); } cin>>k; int l=0,r=0,res=0; while(l<police.size()&&r<thieves.size()) { if(abs(police[l]-thieves[r])<=k) { res++; l++; r++; } else if(thieves[r]>police[l]) l++; else r++; } cout<<res<<"\n"; } }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Hdf5DataReader.hpp" #include "Exception.hpp" #include "OutputFileHandler.hpp" #include "PetscTools.hpp" #include <cassert> #include <algorithm> Hdf5DataReader::Hdf5DataReader(const std::string& rDirectory, const std::string& rBaseName, bool makeAbsolute, std::string datasetName) : AbstractHdf5Access(rDirectory, rBaseName, datasetName, makeAbsolute), mNumberTimesteps(1), mClosed(false) { CommonConstructor(); } Hdf5DataReader::Hdf5DataReader(const FileFinder& rDirectory, const std::string& rBaseName, std::string datasetName) : AbstractHdf5Access(rDirectory, rBaseName, datasetName), mNumberTimesteps(1), mClosed(false) { CommonConstructor(); } void Hdf5DataReader::CommonConstructor() { if (!mDirectory.IsDir() || !mDirectory.Exists()) { EXCEPTION("Directory does not exist: " + mDirectory.GetAbsolutePath()); } std::string file_name = mDirectory.GetAbsolutePath() + mBaseName + ".h5"; FileFinder h5_file(file_name, RelativeTo::Absolute); if (!h5_file.Exists()) { EXCEPTION("Hdf5DataReader could not open " + file_name + " , as it does not exist."); } // Open the file and the main dataset mFileId = H5Fopen(file_name.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); if (mFileId <= 0) { EXCEPTION("Hdf5DataReader could not open " << file_name << " , H5Fopen error code = " << mFileId); } mVariablesDatasetId = H5Dopen(mFileId, mDatasetName.c_str(), H5P_DEFAULT); SetMainDatasetRawChunkCache(); if (mVariablesDatasetId <= 0) { H5Fclose(mFileId); EXCEPTION("Hdf5DataReader opened " << file_name << " but could not find the dataset '" << mDatasetName.c_str() << "', H5Dopen error code = " << mVariablesDatasetId); } hid_t variables_dataspace = H5Dget_space(mVariablesDatasetId); mVariablesDatasetRank = H5Sget_simple_extent_ndims(variables_dataspace); // Get the dataset/dataspace dimensions hsize_t dataset_max_sizes[AbstractHdf5Access::DATASET_DIMS]; H5Sget_simple_extent_dims(variables_dataspace, mDatasetDims, dataset_max_sizes); for (unsigned i=1; i<AbstractHdf5Access::DATASET_DIMS; i++) // Zero is excluded since it may be unlimited { assert(mDatasetDims[i] == dataset_max_sizes[i]); } // Check if an unlimited dimension has been defined if (dataset_max_sizes[0] == H5S_UNLIMITED) { // In terms of an Unlimited dimension dataset: // * Files pre - r16738 (inc. Release 3.1 and earlier) use simply "Time" for "Data"'s unlimited variable. // * Files generated by r16738 - r18257 used "<DatasetName>_Time" for "<DatasetName>"'s unlimited variable, // - These are not to be used and there is no backwards compatibility for them, since they weren't in a release. // * Files post r18257 (inc. Release 3.2 onwards) use "<DatasetName>_Unlimited" for "<DatasetName>"'s // unlimited variable, // - a new attribute "Name" has been added to the Unlimited Dataset to allow it to assign // any name to the unlimited variable. Which can then be easily read by this class. // - if this dataset is missing we look for simply "Time" to remain backwards compatible with Releases <= 3.1 SetUnlimitedDatasetId(); hid_t timestep_dataspace = H5Dget_space(mUnlimitedDatasetId); // Get the dataset/dataspace dimensions H5Sget_simple_extent_dims(timestep_dataspace, &mNumberTimesteps, nullptr); } // Get the attribute where the name of the variables are stored hid_t attribute_id = H5Aopen_name(mVariablesDatasetId, "Variable Details"); // Get attribute datatype, dataspace, rank, and dimensions hid_t attribute_type = H5Aget_type(attribute_id); hid_t attribute_space = H5Aget_space(attribute_id); hsize_t attr_dataspace_dim; H5Sget_simple_extent_dims(attribute_space, &attr_dataspace_dim, nullptr); unsigned num_columns = H5Sget_simple_extent_npoints(attribute_space); char* string_array = (char *)malloc(sizeof(char)*MAX_STRING_SIZE*(int)num_columns); H5Aread(attribute_id, attribute_type, string_array); // Loop over column names and store them. for (unsigned index=0; index < num_columns; index++) { // Read the string from the raw vector std::string column_name_unit(&string_array[MAX_STRING_SIZE*index]); // Find beginning of unit definition. size_t name_length = column_name_unit.find('('); size_t unit_length = column_name_unit.find(')') - name_length - 1; std::string column_name = column_name_unit.substr(0, name_length); std::string column_unit = column_name_unit.substr(name_length+1, unit_length); mVariableNames.push_back(column_name); mVariableToColumnIndex[column_name] = index; mVariableToUnit[column_name] = column_unit; } // Release all the identifiers H5Tclose(attribute_type); H5Sclose(attribute_space); H5Aclose(attribute_id); // Free allocated memory free(string_array); // Find out if it's incomplete data H5E_BEGIN_TRY //Supress HDF5 error if the IsDataComplete name isn't there { attribute_id = H5Aopen_name(mVariablesDatasetId, "IsDataComplete"); } H5E_END_TRY; if (attribute_id < 0) { // This is in the old format (before we added the IsDataComplete attribute). // Just quit (leaving a nasty hdf5 error). return; } attribute_type = H5Aget_type(attribute_id); attribute_space = H5Aget_space(attribute_id); unsigned is_data_complete; H5Aread(attribute_id, H5T_NATIVE_UINT, &is_data_complete); // Release all the identifiers H5Tclose(attribute_type); H5Sclose(attribute_space); H5Aclose(attribute_id); mIsDataComplete = (is_data_complete == 1) ? true : false; if (is_data_complete) { return; } // Incomplete data // Read the vector thing attribute_id = H5Aopen_name(mVariablesDatasetId, "NodeMap"); attribute_type = H5Aget_type(attribute_id); attribute_space = H5Aget_space(attribute_id); // Get the dataset/dataspace dimensions unsigned num_node_indices = H5Sget_simple_extent_npoints(attribute_space); // Read data from hyperslab in the file into the hyperslab in memory mIncompleteNodeIndices.clear(); mIncompleteNodeIndices.resize(num_node_indices); H5Aread(attribute_id, H5T_NATIVE_UINT, &mIncompleteNodeIndices[0]); H5Tclose(attribute_type); H5Sclose(attribute_space); H5Aclose(attribute_id); } std::vector<double> Hdf5DataReader::GetVariableOverTime(const std::string& rVariableName, unsigned nodeIndex) { if (!mIsUnlimitedDimensionSet) { EXCEPTION("The dataset '" << mDatasetName << "' does not contain time dependent data"); } unsigned actual_node_index = nodeIndex; if (!mIsDataComplete) { unsigned node_index = 0; for (node_index=0; node_index<mIncompleteNodeIndices.size(); node_index++) { if (mIncompleteNodeIndices[node_index]==nodeIndex) { actual_node_index = node_index; break; } } if (node_index == mIncompleteNodeIndices.size()) { EXCEPTION("The incomplete dataset '" << mDatasetName << "' does not contain info of node " << nodeIndex); } } if (actual_node_index >= mDatasetDims[1]) { EXCEPTION("The dataset '" << mDatasetName << "' doesn't contain info of node " << actual_node_index); } std::map<std::string, unsigned>::iterator col_iter = mVariableToColumnIndex.find(rVariableName); if (col_iter == mVariableToColumnIndex.end()) { EXCEPTION("The dataset '" << mDatasetName << "' doesn't contain data for variable " << rVariableName); } unsigned column_index = (*col_iter).second; // Define hyperslab in the dataset. hsize_t offset[3] = {0, actual_node_index, column_index}; hsize_t count[3] = {mDatasetDims[0], 1, 1}; hid_t variables_dataspace = H5Dget_space(mVariablesDatasetId); H5Sselect_hyperslab(variables_dataspace, H5S_SELECT_SET, offset, nullptr, count, nullptr); // Define a simple memory dataspace hid_t memspace = H5Screate_simple(1, &mDatasetDims[0] ,nullptr); // Data buffer to return std::vector<double> ret(mDatasetDims[0]); // Read data from hyperslab in the file into the hyperslab in memory H5Dread(mVariablesDatasetId, H5T_NATIVE_DOUBLE, memspace, variables_dataspace, H5P_DEFAULT, &ret[0]); H5Sclose(variables_dataspace); H5Sclose(memspace); return ret; } std::vector<std::vector<double> > Hdf5DataReader::GetVariableOverTimeOverMultipleNodes(const std::string& rVariableName, unsigned lowerIndex, unsigned upperIndex) { if (!mIsUnlimitedDimensionSet) { EXCEPTION("The dataset '" << mDatasetName << "' does not contain time dependent data"); } if (!mIsDataComplete) { EXCEPTION("GetVariableOverTimeOverMultipleNodes() cannot be called using incomplete data sets (those for which data was only written for certain nodes)"); } if (upperIndex > mDatasetDims[1]) { EXCEPTION("The dataset '" << mDatasetName << "' doesn't contain info for node " << upperIndex-1); } std::map<std::string, unsigned>::iterator col_iter = mVariableToColumnIndex.find(rVariableName); if (col_iter == mVariableToColumnIndex.end()) { EXCEPTION("The dataset '" << mDatasetName << "' doesn't contain data for variable " << rVariableName); } unsigned column_index = (*col_iter).second; // Define hyperslab in the dataset. hsize_t offset[3] = {0, lowerIndex, column_index}; hsize_t count[3] = {mDatasetDims[0], upperIndex-lowerIndex, 1}; hid_t variables_dataspace = H5Dget_space(mVariablesDatasetId); H5Sselect_hyperslab(variables_dataspace, H5S_SELECT_SET, offset, nullptr, count, nullptr); // Define a simple memory dataspace hsize_t data_dimensions[2]; data_dimensions[0] = mDatasetDims[0]; data_dimensions[1] = upperIndex-lowerIndex; hid_t memspace = H5Screate_simple(2, data_dimensions, nullptr); double* data_read = new double[mDatasetDims[0]*(upperIndex-lowerIndex)]; // Read data from hyperslab in the file into the hyperslab in memory H5Dread(mVariablesDatasetId, H5T_NATIVE_DOUBLE, memspace, variables_dataspace, H5P_DEFAULT, data_read); H5Sclose(variables_dataspace); H5Sclose(memspace); // Data buffer to return unsigned num_nodes_read = upperIndex-lowerIndex; unsigned num_timesteps = mDatasetDims[0]; std::vector<std::vector<double> > ret(num_nodes_read); for (unsigned node_num=0; node_num<num_nodes_read; node_num++) { ret[node_num].resize(num_timesteps); for (unsigned time_num=0; time_num<num_timesteps; time_num++) { ret[node_num][time_num] = data_read[num_nodes_read*time_num + node_num]; } } delete[] data_read; return ret; } void Hdf5DataReader::GetVariableOverNodes(Vec data, const std::string& rVariableName, unsigned timestep) { if (!mIsDataComplete) { EXCEPTION("You can only get a vector for complete data"); } if (!mIsUnlimitedDimensionSet && timestep!=0) { EXCEPTION("The dataset '" << mDatasetName << "' does not contain time dependent data"); } std::map<std::string, unsigned>::iterator col_iter = mVariableToColumnIndex.find(rVariableName); if (col_iter == mVariableToColumnIndex.end()) { EXCEPTION("The dataset '" << mDatasetName << "' does not contain data for variable " << rVariableName); } unsigned column_index = (*col_iter).second; // Check for valid timestep if (timestep >= mNumberTimesteps) { EXCEPTION("The dataset '" << mDatasetName << "' does not contain data for timestep number " << timestep); } int lo, hi, size; VecGetSize(data, &size); if ((unsigned)size != mDatasetDims[1]) { EXCEPTION("Could not read data because Vec is the wrong size"); } // Get range owned by each processor VecGetOwnershipRange(data, &lo, &hi); if (hi > lo) // i.e. we own some... { // Define a dataset in memory for this process hsize_t v_size[1] = {(unsigned)(hi-lo)}; hid_t memspace = H5Screate_simple(1, v_size, nullptr); // Select hyperslab in the file. hsize_t offset[3] = {timestep, (unsigned)(lo), column_index}; hsize_t count[3] = {1, (unsigned)(hi-lo), 1}; hid_t hyperslab_space = H5Dget_space(mVariablesDatasetId); H5Sselect_hyperslab(hyperslab_space, H5S_SELECT_SET, offset, nullptr, count, nullptr); double* p_petsc_vector; VecGetArray(data, &p_petsc_vector); herr_t err = H5Dread(mVariablesDatasetId, H5T_NATIVE_DOUBLE, memspace, hyperslab_space, H5P_DEFAULT, p_petsc_vector); UNUSED_OPT(err); assert(err==0); VecRestoreArray(data, &p_petsc_vector); H5Sclose(hyperslab_space); H5Sclose(memspace); } } std::vector<double> Hdf5DataReader::GetUnlimitedDimensionValues() { // Data buffer to return std::vector<double> ret(mNumberTimesteps); if (!mIsUnlimitedDimensionSet) { // Fake it assert(mNumberTimesteps==1); ret[0] = 0.0; return ret; } // Read data from hyperslab in the file into memory H5Dread(mUnlimitedDatasetId, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, &ret[0]); return ret; } void Hdf5DataReader::Close() { if (!mClosed) { H5Dclose(mVariablesDatasetId); if (mIsUnlimitedDimensionSet) { H5Dclose(mUnlimitedDatasetId); } H5Fclose(mFileId); mClosed = true; } } Hdf5DataReader::~Hdf5DataReader() { Close(); } unsigned Hdf5DataReader::GetNumberOfRows() { return mDatasetDims[1]; } std::vector<std::string> Hdf5DataReader::GetVariableNames() { return mVariableNames; } std::string Hdf5DataReader::GetUnit(const std::string& rVariableName) { return mVariableToUnit[rVariableName]; }
// C++ for the Windows Runtime vv1.0.170303.6 // Copyright (c) 2017 Microsoft Corporation. All rights reserved. #pragma once #include "base.h" WINRT_WARNING_PUSH #include "internal/Windows.UI.Xaml.3.h" #include "internal/Windows.Foundation.3.h" #include "internal/Windows.UI.Xaml.Controls.Primitives.3.h" #include "internal/Windows.UI.Composition.3.h" #include "internal/Windows.UI.Xaml.Controls.3.h" #include "internal/Windows.UI.Xaml.Hosting.3.h" #include "Windows.UI.Xaml.h" WINRT_EXPORT namespace winrt { namespace impl { template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IElementCompositionPreview> : produce_base<D, Windows::UI::Xaml::Hosting::IElementCompositionPreview> {}; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics> : produce_base<D, Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics> { HRESULT __stdcall abi_GetElementVisual(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> element, impl::abi_arg_out<Windows::UI::Composition::IVisual> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetElementVisual(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&element))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_GetElementChildVisual(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> element, impl::abi_arg_out<Windows::UI::Composition::IVisual> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetElementChildVisual(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&element))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } HRESULT __stdcall abi_SetElementChildVisual(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> element, impl::abi_arg_in<Windows::UI::Composition::IVisual> visual) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetElementChildVisual(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&element), *reinterpret_cast<const Windows::UI::Composition::Visual *>(&visual)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_GetScrollViewerManipulationPropertySet(impl::abi_arg_in<Windows::UI::Xaml::Controls::IScrollViewer> scrollViewer, impl::abi_arg_out<Windows::UI::Composition::ICompositionPropertySet> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetScrollViewerManipulationPropertySet(*reinterpret_cast<const Windows::UI::Xaml::Controls::ScrollViewer *>(&scrollViewer))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics2> : produce_base<D, Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics2> { HRESULT __stdcall abi_SetImplicitShowAnimation(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> element, impl::abi_arg_in<Windows::UI::Composition::ICompositionAnimationBase> animation) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetImplicitShowAnimation(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&element), *reinterpret_cast<const Windows::UI::Composition::ICompositionAnimationBase *>(&animation)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetImplicitHideAnimation(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> element, impl::abi_arg_in<Windows::UI::Composition::ICompositionAnimationBase> animation) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetImplicitHideAnimation(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&element), *reinterpret_cast<const Windows::UI::Composition::ICompositionAnimationBase *>(&animation)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetIsTranslationEnabled(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> element, bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetIsTranslationEnabled(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&element), value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_GetPointerPositionPropertySet(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> targetElement, impl::abi_arg_out<Windows::UI::Composition::ICompositionPropertySet> result) noexcept override { try { typename D::abi_guard guard(this->shim()); *result = detach_abi(this->shim().GetPointerPositionPropertySet(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&targetElement))); return S_OK; } catch (...) { *result = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IXamlUIPresenter> : produce_base<D, Windows::UI::Xaml::Hosting::IXamlUIPresenter> { HRESULT __stdcall get_RootElement(impl::abi_arg_out<Windows::UI::Xaml::IUIElement> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().RootElement()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_RootElement(impl::abi_arg_in<Windows::UI::Xaml::IUIElement> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().RootElement(*reinterpret_cast<const Windows::UI::Xaml::UIElement *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ThemeKey(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ThemeKey()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_ThemeKey(impl::abi_arg_in<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ThemeKey(*reinterpret_cast<const hstring *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall get_ThemeResourcesXaml(impl::abi_arg_out<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().ThemeResourcesXaml()); return S_OK; } catch (...) { *value = nullptr; return impl::to_hresult(); } } HRESULT __stdcall put_ThemeResourcesXaml(impl::abi_arg_in<hstring> value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().ThemeResourcesXaml(*reinterpret_cast<const hstring *>(&value)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetSize(int32_t width, int32_t height) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetSize(width, height); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_Render() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Render(); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_Present() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().Present(); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterHost> : produce_base<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterHost> { HRESULT __stdcall abi_ResolveFileResource(impl::abi_arg_in<hstring> path, impl::abi_arg_out<hstring> returnValue) noexcept override { try { typename D::abi_guard guard(this->shim()); *returnValue = detach_abi(this->shim().ResolveFileResource(*reinterpret_cast<const hstring *>(&path))); return S_OK; } catch (...) { *returnValue = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterHost2> : produce_base<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterHost2> { HRESULT __stdcall abi_GetGenericXamlFilePath(impl::abi_arg_out<hstring> returnValue) noexcept override { try { typename D::abi_guard guard(this->shim()); *returnValue = detach_abi(this->shim().GetGenericXamlFilePath()); return S_OK; } catch (...) { *returnValue = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterHost3> : produce_base<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterHost3> { HRESULT __stdcall abi_ResolveDictionaryResource(impl::abi_arg_in<Windows::UI::Xaml::IResourceDictionary> dictionary, impl::abi_arg_in<Windows::Foundation::IInspectable> dictionaryKey, impl::abi_arg_in<Windows::Foundation::IInspectable> suggestedValue, impl::abi_arg_out<Windows::Foundation::IInspectable> returnValue) noexcept override { try { typename D::abi_guard guard(this->shim()); *returnValue = detach_abi(this->shim().ResolveDictionaryResource(*reinterpret_cast<const Windows::UI::Xaml::ResourceDictionary *>(&dictionary), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&dictionaryKey), *reinterpret_cast<const Windows::Foundation::IInspectable *>(&suggestedValue))); return S_OK; } catch (...) { *returnValue = nullptr; return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics> : produce_base<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics> { HRESULT __stdcall get_CompleteTimelinesAutomatically(bool * value) noexcept override { try { typename D::abi_guard guard(this->shim()); *value = detach_abi(this->shim().CompleteTimelinesAutomatically()); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall put_CompleteTimelinesAutomatically(bool value) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().CompleteTimelinesAutomatically(value); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_SetHost(impl::abi_arg_in<Windows::UI::Xaml::Hosting::IXamlUIPresenterHost> host) noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().SetHost(*reinterpret_cast<const Windows::UI::Xaml::Hosting::IXamlUIPresenterHost *>(&host)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_NotifyWindowSizeChanged() noexcept override { try { typename D::abi_guard guard(this->shim()); this->shim().NotifyWindowSizeChanged(); return S_OK; } catch (...) { return impl::to_hresult(); } } }; template <typename D> struct produce<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics2> : produce_base<D, Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics2> { HRESULT __stdcall abi_GetFlyoutPlacementTargetInfo(impl::abi_arg_in<Windows::UI::Xaml::IFrameworkElement> placementTarget, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode preferredPlacement, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode * targetPreferredPlacement, bool * allowFallbacks, impl::abi_arg_out<Windows::Foundation::Rect> returnValue) noexcept override { try { typename D::abi_guard guard(this->shim()); *returnValue = detach_abi(this->shim().GetFlyoutPlacementTargetInfo(*reinterpret_cast<const Windows::UI::Xaml::FrameworkElement *>(&placementTarget), preferredPlacement, *targetPreferredPlacement, *allowFallbacks)); return S_OK; } catch (...) { return impl::to_hresult(); } } HRESULT __stdcall abi_GetFlyoutPlacement(impl::abi_arg_in<Windows::Foundation::Rect> placementTargetBounds, impl::abi_arg_in<Windows::Foundation::Size> controlSize, impl::abi_arg_in<Windows::Foundation::Size> minControlSize, impl::abi_arg_in<Windows::Foundation::Rect> containerRect, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode targetPreferredPlacement, bool allowFallbacks, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode * chosenPlacement, impl::abi_arg_out<Windows::Foundation::Rect> returnValue) noexcept override { try { typename D::abi_guard guard(this->shim()); *returnValue = detach_abi(this->shim().GetFlyoutPlacement(*reinterpret_cast<const Windows::Foundation::Rect *>(&placementTargetBounds), *reinterpret_cast<const Windows::Foundation::Size *>(&controlSize), *reinterpret_cast<const Windows::Foundation::Size *>(&minControlSize), *reinterpret_cast<const Windows::Foundation::Rect *>(&containerRect), targetPreferredPlacement, allowFallbacks, *chosenPlacement)); return S_OK; } catch (...) { return impl::to_hresult(); } } }; } namespace Windows::UI::Xaml::Hosting { template <typename D> hstring impl_IXamlUIPresenterHost<D>::ResolveFileResource(hstring_view path) const { hstring returnValue; check_hresult(WINRT_SHIM(IXamlUIPresenterHost)->abi_ResolveFileResource(get_abi(path), put_abi(returnValue))); return returnValue; } template <typename D> hstring impl_IXamlUIPresenterHost2<D>::GetGenericXamlFilePath() const { hstring returnValue; check_hresult(WINRT_SHIM(IXamlUIPresenterHost2)->abi_GetGenericXamlFilePath(put_abi(returnValue))); return returnValue; } template <typename D> Windows::Foundation::IInspectable impl_IXamlUIPresenterHost3<D>::ResolveDictionaryResource(const Windows::UI::Xaml::ResourceDictionary & dictionary, const Windows::Foundation::IInspectable & dictionaryKey, const Windows::Foundation::IInspectable & suggestedValue) const { Windows::Foundation::IInspectable returnValue; check_hresult(WINRT_SHIM(IXamlUIPresenterHost3)->abi_ResolveDictionaryResource(get_abi(dictionary), get_abi(dictionaryKey), get_abi(suggestedValue), put_abi(returnValue))); return returnValue; } template <typename D> Windows::UI::Xaml::UIElement impl_IXamlUIPresenter<D>::RootElement() const { Windows::UI::Xaml::UIElement value { nullptr }; check_hresult(WINRT_SHIM(IXamlUIPresenter)->get_RootElement(put_abi(value))); return value; } template <typename D> void impl_IXamlUIPresenter<D>::RootElement(const Windows::UI::Xaml::UIElement & value) const { check_hresult(WINRT_SHIM(IXamlUIPresenter)->put_RootElement(get_abi(value))); } template <typename D> hstring impl_IXamlUIPresenter<D>::ThemeKey() const { hstring value; check_hresult(WINRT_SHIM(IXamlUIPresenter)->get_ThemeKey(put_abi(value))); return value; } template <typename D> void impl_IXamlUIPresenter<D>::ThemeKey(hstring_view value) const { check_hresult(WINRT_SHIM(IXamlUIPresenter)->put_ThemeKey(get_abi(value))); } template <typename D> hstring impl_IXamlUIPresenter<D>::ThemeResourcesXaml() const { hstring value; check_hresult(WINRT_SHIM(IXamlUIPresenter)->get_ThemeResourcesXaml(put_abi(value))); return value; } template <typename D> void impl_IXamlUIPresenter<D>::ThemeResourcesXaml(hstring_view value) const { check_hresult(WINRT_SHIM(IXamlUIPresenter)->put_ThemeResourcesXaml(get_abi(value))); } template <typename D> void impl_IXamlUIPresenter<D>::SetSize(int32_t width, int32_t height) const { check_hresult(WINRT_SHIM(IXamlUIPresenter)->abi_SetSize(width, height)); } template <typename D> void impl_IXamlUIPresenter<D>::Render() const { check_hresult(WINRT_SHIM(IXamlUIPresenter)->abi_Render()); } template <typename D> void impl_IXamlUIPresenter<D>::Present() const { check_hresult(WINRT_SHIM(IXamlUIPresenter)->abi_Present()); } template <typename D> bool impl_IXamlUIPresenterStatics<D>::CompleteTimelinesAutomatically() const { bool value {}; check_hresult(WINRT_SHIM(IXamlUIPresenterStatics)->get_CompleteTimelinesAutomatically(&value)); return value; } template <typename D> void impl_IXamlUIPresenterStatics<D>::CompleteTimelinesAutomatically(bool value) const { check_hresult(WINRT_SHIM(IXamlUIPresenterStatics)->put_CompleteTimelinesAutomatically(value)); } template <typename D> void impl_IXamlUIPresenterStatics<D>::SetHost(const Windows::UI::Xaml::Hosting::IXamlUIPresenterHost & host) const { check_hresult(WINRT_SHIM(IXamlUIPresenterStatics)->abi_SetHost(get_abi(host))); } template <typename D> void impl_IXamlUIPresenterStatics<D>::NotifyWindowSizeChanged() const { check_hresult(WINRT_SHIM(IXamlUIPresenterStatics)->abi_NotifyWindowSizeChanged()); } template <typename D> Windows::Foundation::Rect impl_IXamlUIPresenterStatics2<D>::GetFlyoutPlacementTargetInfo(const Windows::UI::Xaml::FrameworkElement & placementTarget, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode preferredPlacement, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode & targetPreferredPlacement, bool & allowFallbacks) const { Windows::Foundation::Rect returnValue {}; check_hresult(WINRT_SHIM(IXamlUIPresenterStatics2)->abi_GetFlyoutPlacementTargetInfo(get_abi(placementTarget), preferredPlacement, &targetPreferredPlacement, &allowFallbacks, put_abi(returnValue))); return returnValue; } template <typename D> Windows::Foundation::Rect impl_IXamlUIPresenterStatics2<D>::GetFlyoutPlacement(const Windows::Foundation::Rect & placementTargetBounds, const Windows::Foundation::Size & controlSize, const Windows::Foundation::Size & minControlSize, const Windows::Foundation::Rect & containerRect, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode targetPreferredPlacement, bool allowFallbacks, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode & chosenPlacement) const { Windows::Foundation::Rect returnValue {}; check_hresult(WINRT_SHIM(IXamlUIPresenterStatics2)->abi_GetFlyoutPlacement(get_abi(placementTargetBounds), get_abi(controlSize), get_abi(minControlSize), get_abi(containerRect), targetPreferredPlacement, allowFallbacks, &chosenPlacement, put_abi(returnValue))); return returnValue; } template <typename D> Windows::UI::Composition::Visual impl_IElementCompositionPreviewStatics<D>::GetElementVisual(const Windows::UI::Xaml::UIElement & element) const { Windows::UI::Composition::Visual result { nullptr }; check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics)->abi_GetElementVisual(get_abi(element), put_abi(result))); return result; } template <typename D> Windows::UI::Composition::Visual impl_IElementCompositionPreviewStatics<D>::GetElementChildVisual(const Windows::UI::Xaml::UIElement & element) const { Windows::UI::Composition::Visual result { nullptr }; check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics)->abi_GetElementChildVisual(get_abi(element), put_abi(result))); return result; } template <typename D> void impl_IElementCompositionPreviewStatics<D>::SetElementChildVisual(const Windows::UI::Xaml::UIElement & element, const Windows::UI::Composition::Visual & visual) const { check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics)->abi_SetElementChildVisual(get_abi(element), get_abi(visual))); } template <typename D> Windows::UI::Composition::CompositionPropertySet impl_IElementCompositionPreviewStatics<D>::GetScrollViewerManipulationPropertySet(const Windows::UI::Xaml::Controls::ScrollViewer & scrollViewer) const { Windows::UI::Composition::CompositionPropertySet result { nullptr }; check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics)->abi_GetScrollViewerManipulationPropertySet(get_abi(scrollViewer), put_abi(result))); return result; } template <typename D> void impl_IElementCompositionPreviewStatics2<D>::SetImplicitShowAnimation(const Windows::UI::Xaml::UIElement & element, const Windows::UI::Composition::ICompositionAnimationBase & animation) const { check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics2)->abi_SetImplicitShowAnimation(get_abi(element), get_abi(animation))); } template <typename D> void impl_IElementCompositionPreviewStatics2<D>::SetImplicitHideAnimation(const Windows::UI::Xaml::UIElement & element, const Windows::UI::Composition::ICompositionAnimationBase & animation) const { check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics2)->abi_SetImplicitHideAnimation(get_abi(element), get_abi(animation))); } template <typename D> void impl_IElementCompositionPreviewStatics2<D>::SetIsTranslationEnabled(const Windows::UI::Xaml::UIElement & element, bool value) const { check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics2)->abi_SetIsTranslationEnabled(get_abi(element), value)); } template <typename D> Windows::UI::Composition::CompositionPropertySet impl_IElementCompositionPreviewStatics2<D>::GetPointerPositionPropertySet(const Windows::UI::Xaml::UIElement & targetElement) const { Windows::UI::Composition::CompositionPropertySet result { nullptr }; check_hresult(WINRT_SHIM(IElementCompositionPreviewStatics2)->abi_GetPointerPositionPropertySet(get_abi(targetElement), put_abi(result))); return result; } inline Windows::UI::Composition::Visual ElementCompositionPreview::GetElementVisual(const Windows::UI::Xaml::UIElement & element) { return get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics>().GetElementVisual(element); } inline Windows::UI::Composition::Visual ElementCompositionPreview::GetElementChildVisual(const Windows::UI::Xaml::UIElement & element) { return get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics>().GetElementChildVisual(element); } inline void ElementCompositionPreview::SetElementChildVisual(const Windows::UI::Xaml::UIElement & element, const Windows::UI::Composition::Visual & visual) { get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics>().SetElementChildVisual(element, visual); } inline Windows::UI::Composition::CompositionPropertySet ElementCompositionPreview::GetScrollViewerManipulationPropertySet(const Windows::UI::Xaml::Controls::ScrollViewer & scrollViewer) { return get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics>().GetScrollViewerManipulationPropertySet(scrollViewer); } inline void ElementCompositionPreview::SetImplicitShowAnimation(const Windows::UI::Xaml::UIElement & element, const Windows::UI::Composition::ICompositionAnimationBase & animation) { get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics2>().SetImplicitShowAnimation(element, animation); } inline void ElementCompositionPreview::SetImplicitHideAnimation(const Windows::UI::Xaml::UIElement & element, const Windows::UI::Composition::ICompositionAnimationBase & animation) { get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics2>().SetImplicitHideAnimation(element, animation); } inline void ElementCompositionPreview::SetIsTranslationEnabled(const Windows::UI::Xaml::UIElement & element, bool value) { get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics2>().SetIsTranslationEnabled(element, value); } inline Windows::UI::Composition::CompositionPropertySet ElementCompositionPreview::GetPointerPositionPropertySet(const Windows::UI::Xaml::UIElement & targetElement) { return get_activation_factory<ElementCompositionPreview, IElementCompositionPreviewStatics2>().GetPointerPositionPropertySet(targetElement); } inline bool XamlUIPresenter::CompleteTimelinesAutomatically() { return get_activation_factory<XamlUIPresenter, IXamlUIPresenterStatics>().CompleteTimelinesAutomatically(); } inline void XamlUIPresenter::CompleteTimelinesAutomatically(bool value) { get_activation_factory<XamlUIPresenter, IXamlUIPresenterStatics>().CompleteTimelinesAutomatically(value); } inline void XamlUIPresenter::SetHost(const Windows::UI::Xaml::Hosting::IXamlUIPresenterHost & host) { get_activation_factory<XamlUIPresenter, IXamlUIPresenterStatics>().SetHost(host); } inline void XamlUIPresenter::NotifyWindowSizeChanged() { get_activation_factory<XamlUIPresenter, IXamlUIPresenterStatics>().NotifyWindowSizeChanged(); } inline Windows::Foundation::Rect XamlUIPresenter::GetFlyoutPlacementTargetInfo(const Windows::UI::Xaml::FrameworkElement & placementTarget, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode preferredPlacement, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode & targetPreferredPlacement, bool & allowFallbacks) { return get_activation_factory<XamlUIPresenter, IXamlUIPresenterStatics2>().GetFlyoutPlacementTargetInfo(placementTarget, preferredPlacement, targetPreferredPlacement, allowFallbacks); } inline Windows::Foundation::Rect XamlUIPresenter::GetFlyoutPlacement(const Windows::Foundation::Rect & placementTargetBounds, const Windows::Foundation::Size & controlSize, const Windows::Foundation::Size & minControlSize, const Windows::Foundation::Rect & containerRect, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode targetPreferredPlacement, bool allowFallbacks, Windows::UI::Xaml::Controls::Primitives::FlyoutPlacementMode & chosenPlacement) { return get_activation_factory<XamlUIPresenter, IXamlUIPresenterStatics2>().GetFlyoutPlacement(placementTargetBounds, controlSize, minControlSize, containerRect, targetPreferredPlacement, allowFallbacks, chosenPlacement); } } } template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IElementCompositionPreview> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IElementCompositionPreview & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics2> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IElementCompositionPreviewStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenter> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenter & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterHost> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterHost & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterHost2> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterHost2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterHost3> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterHost3 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics2> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::IXamlUIPresenterStatics2 & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::ElementCompositionPreview> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::ElementCompositionPreview & value) const noexcept { return winrt::impl::hash_unknown(value); } }; template<> struct std::hash<winrt::Windows::UI::Xaml::Hosting::XamlUIPresenter> { size_t operator()(const winrt::Windows::UI::Xaml::Hosting::XamlUIPresenter & value) const noexcept { return winrt::impl::hash_unknown(value); } }; WINRT_WARNING_POP
/** <p> This unit test shapes the spirit code for the ntriples ebnf grammer. During operation this also fires small console events to indicate the event state during a commandline pipe operation. currently this is run by executing : <pre> jnorthrup@dove /c/work/sandbox/agent/release $ ./ntriple_grammar.exe < ../agent_api/final.ntriples </pre> for more info on the grammar see: <p> http://www.w3.org/2001/sw/RDFCore/ntriples/ <p> Extended Backus-Naur Form (EBNF) Grammar An N-Triples document is a sequence of US-ASCII characters and is defined by the ntripleDoc grammar term below. Parsing it results in a sequence of RDF statements formed from the subject, predicate and object terms. The meaning of these are defined either in [RDFMS] or is ongoing as part of the RDF Core WG activity. <pre> This EBNF is the notation used in XML 1.0 second edition ntripleDoc ::= line* line ::= ws* (comment | triple) ? eoln comment ::= '#' (character - ( cr | lf ) )* triple ::= subject ws+ predicate ws+ object ws* '.' ws* subject ::= uriref | namedNode predicate ::= uriref object ::= uriref | namedNode | literal uriref ::= '<' absoluteURI '>' namedNode ::= '_:' name literal ::= '"' string '"' ws ::= space | tab eoln ::= cr | lf | cr lf space ::= #x20 /* US-ASCII space - decimal 32 cr ::= #xD /* US-ASCII carriage return - decimal 13 lf ::= #xA /* US-ASCII linefeed - decimal 10 tab ::= #x9 /* US-ASCII horizontal tab - decimal 9 string ::= character* with escapes. Defined in section Strings name ::= [A-Za-z][A-Za-z0-9]* absoluteURI ::= ( character - ( '<' | '>' | space ) )+ character ::= [#x20-#x7E] /* US-ASCII space to decimal 127 </pre> */ #include <boost/spirit/core.hpp> #include <boost/spirit/utility/confix.hpp> #include <boost/spirit/utility/chset.hpp> #include <boost/spirit/utility/escape_char.hpp> #include <iostream> #include <string> //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; namespace{ void do_comment(const char*begin , const char* end){cout << "comment!" << endl;}; void do_triple(const char*begin , const char* end){cout << "triple!\t";}; void do_blank(const char*begin , const char* end){cout << "blank!\t";}; } struct ntriples: public grammar<ntriples> { template <typename ScannerT> struct definition { definition(ntriples const& /*self*/) { ntripleDoc = *(line); line = blank_p >> *(comment [&do_comment] | triple[&do_triple] ) >> !eol_p; comment = ch_p('#') >> * ( character - eol_p ) ; triple = subject >> + blank_p >> predicate>> + blank_p >> object>> *blank_p >> '.' >> *blank_p; //see the cin<< parser statement to fine-tune subject = uriref | namedNode ; predicate = uriref ; object = (uriref | namedNode | literal);a literal = confix_p('"', *c_escape_ch_p, '"'); uriref = confix_p('<',absoluteURI,'>'); namedNode = (chseq_p("_:" ) >> alnum_p)[&do_blank]; absoluteURI = +( character - ( blank_p| '<' | '>' ) ); character = range_p( 0x20 , 0x7E); // /* US-ASCII space to decimal 127 } rule<ScannerT> ntripleDoc , line , comment , triple , subject , predicate , object , literal , uriref , namedNode , absoluteURI , character; rule<ScannerT> const& start() const { return ntripleDoc; } }; }; int main(int argc, char**argv){ ntriples triples; //our parser string str; while (getline(cin, str)) { parse_info<> info = parse(str.c_str(), triples, eol_p); cout << (info.full ?"+":"-"); } cout << "Bye... :-) \n\n"; return 0; };
// 使用for循环,答应10~1 #include <iostream> using namespace std; int main(){ for(int i=10;i>=0;i--) cout << i <<endl; return 0; }
/* * Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ //----------------------------------------------------------------------------- #include "server_memory.h" #include "server_platform.h" #include "message/msg_memory.h" #include "composite/composite_command_queue.h" #include "composite/composite_context.h" #include "composite/composite_memory.h" #include "composite/composite_event.h" using dcl::composite::composite_event; using dcl::composite::composite_context; using dcl::composite::composite_memory; using dcl::composite::composite_command_queue; using dcl::composite::composite_image; using dcl::info::generic_memory_object; using dcl::info::generic_event; //----------------------------------------------------------------------------- namespace dcl { namespace server { //----------------------------------------------------------------------------- void msgCreateBuffer_command::execute() { server_platform& server = session_context_ptr_->get_server_platform(); remote_id_t context_id = message_->get_context_id(); composite_context* context_ptr = server.get_context_manager().get( context_id ); generic_memory_object* ptr = context_ptr->create_buffer( message_->get_buffer_pointer(), message_->get_buffer_size(), message_->get_flags() ); composite_memory* buffer_ptr = reinterpret_cast<composite_memory*>( ptr ); remote_id_t id = server.get_memory_manager().add( buffer_ptr ); //std::cerr << id; message_->set_remote_id( id ); } //----------------------------------------------------------------------------- void msgEnqueueWriteBuffer_command::async_prepare() { message_->copy_buffer(); } //----------------------------------------------------------------------------- void msgEnqueueWriteBuffer_command::execute() { //std::cerr << "executing msgEnqueueWriteBuffer_command..."; server_platform& server = session_context_ptr_->get_server_platform(); remote_id_t id = message_->get_remote_id(); //std::cerr << id; remote_id_t command_queue_id = message_->get_command_queue_id(); composite_memory* buffer_ptr = server.get_memory_manager().get( id ); composite_command_queue* queue_ptr = server.get_command_queue_manager().get( command_queue_id ); server.flush( command_queue_id ); dcl::events_t events; load_message_events( message_->get_events(), events ); // Always no blocking buffer_ptr->write( queue_ptr, message_->get_buffer_pointer(), message_->get_buffer_size(), message_->get_offset(), false, events, get_event_ptr() ); //std::cerr << "... Ok" << std::endl; } //----------------------------------------------------------------------------- bool msgEnqueueWriteBuffer_command::async_run() const { //return !message_->get_blocking(); return true; //return message_->get_return_event(); } //----------------------------------------------------------------------------- void msgEnqueueReadBuffer_command::execute() { server_platform& server = session_context_ptr_->get_server_platform(); remote_id_t id = message_->get_remote_id(); remote_id_t command_queue_id = message_->get_command_queue_id(); composite_memory* buffer_ptr = server.get_memory_manager().get( id ); composite_command_queue* queue_ptr = server.get_command_queue_manager().get( command_queue_id ); message_->allocate_buffer(); server.flush( command_queue_id ); dcl::events_t events; load_message_events( message_->get_events(), events ); //std::cerr << "read memory " << message_->get_buffer_size() << " bytes" << std::endl; // Always blocking buffer_ptr->read( queue_ptr, message_->get_buffer_pointer(), message_->get_buffer_size(), message_->get_offset(), true, events, get_event_ptr() ); // Should be no blocking, but I need to keep the command } //----------------------------------------------------------------------------- bool msgEnqueueReadBuffer_command::async_run() const { return !message_->get_blocking(); //return true; //return message_->get_return_event(); } //----------------------------------------------------------------------------- void msgEnqueueCopyBuffer_command::execute() { server_platform& server = session_context_ptr_->get_server_platform(); remote_id_t src_id = message_->get_src_remote_id(); remote_id_t dst_id = message_->get_dst_remote_id(); remote_id_t command_queue_id = message_->get_command_queue_id(); //std::cerr << std::endl << "copy memory " << message_->get_buffer_size() << " bytes: " //<< src_id << "(+" << message_->get_src_offset() //<< ") -> " << dst_id << "(+" << message_->get_dst_offset() << ")" //<< std::endl; composite_memory* src_buffer_ptr = server.get_memory_manager().get( src_id ); composite_memory* dst_buffer_ptr = server.get_memory_manager().get( dst_id ); composite_command_queue* queue_ptr = server.get_command_queue_manager().get( command_queue_id ); server.flush( command_queue_id ); dcl::events_t events; load_message_events( message_->get_events(), events ); dst_buffer_ptr->copy( queue_ptr, src_buffer_ptr, message_->get_buffer_size(), message_->get_src_offset(), message_->get_dst_offset(), events, get_event_ptr() ); } //----------------------------------------------------------------------------- bool msgEnqueueCopyBuffer_command::async_run() const { return true; //return message_->get_return_event(); } //----------------------------------------------------------------------------- void msgCreateImage2D_command::execute() { server_platform& server = session_context_ptr_->get_server_platform(); remote_id_t context_id = message_->get_context_id(); composite_context* context_ptr = server.get_context_manager().get( context_id ); cl_image_format format; format.image_channel_order = message_->get_channel_order(); format.image_channel_data_type = message_->get_channel_type(); generic_memory_object* ptr = context_ptr->create_image( message_->get_buffer(), message_->get_flags(), &format, message_->get_width(), message_->get_height(), message_->get_row_pitch() ); composite_image* image_ptr = reinterpret_cast<composite_image*>( ptr ); remote_id_t id = server.get_image_manager().add( image_ptr ); //std::cerr << id; message_->set_remote_id( id ); } //----------------------------------------------------------------------------- void msgEnqueueWriteImage_command::execute() { server_platform& server = session_context_ptr_->get_server_platform(); remote_id_t id = message_->get_remote_id(); remote_id_t command_queue_id = message_->get_command_queue_id(); composite_image* image_ptr = server.get_image_manager().get( id ); composite_command_queue* queue_ptr = server.get_command_queue_manager().get( command_queue_id ); server.flush( command_queue_id ); dcl::events_t events; load_message_events( message_->get_events(), events ); // Always no blocking image_ptr->write( queue_ptr, message_->get_buffer(), message_->get_origin(), message_->get_region(), message_->get_row_pitch(), message_->get_slice_pitch(), false, events, get_event_ptr() ); } //----------------------------------------------------------------------------- bool msgEnqueueWriteImage_command::async_run() const { //return !message_->get_blocking(); return true; } //----------------------------------------------------------------------------- }} // namespace dcl::server //-----------------------------------------------------------------------------
/* * Interface Character * @author Patricio Ferreira <3dimentionar@gmail.com> */ #ifndef HEADERS_CHARACTER_H_ #define HEADERS_CHARACTER_H_ #include <string> #include <boost/uuid/uuid.hpp> namespace game_model { typedef enum { HEROE = 1, ENEMY = 2, PASSIVE = 3, } CharacterType; class Character { private: boost::uuids::uuid _id; CharacterType _type; std::string _name; public: Character(); Character(std::string name); Character(std::string name, CharacterType type); Character walk(); std::string id(); CharacterType type(); Character type(CharacterType type); std::string name(); Character name(std::string name); }; } #endif /* HEADERS_CHARACTER_H_ */
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AbstractCellCycleModelOdeSolver.hpp" #include "CvodeAdaptor.hpp" AbstractCellCycleModelOdeSolver::AbstractCellCycleModelOdeSolver() : mSizeOfOdeSystem(UNSIGNED_UNSET) { } AbstractCellCycleModelOdeSolver::~AbstractCellCycleModelOdeSolver() { } void AbstractCellCycleModelOdeSolver::SolveAndUpdateStateVariable(AbstractOdeSystem* pAbstractOdeSystem, double startTime, double endTime, double timeStep) { assert(IsSetUp()); mpOdeSolver->SolveAndUpdateStateVariable(pAbstractOdeSystem, startTime, endTime, timeStep); } bool AbstractCellCycleModelOdeSolver::StoppingEventOccurred() { assert(IsSetUp()); return mpOdeSolver->StoppingEventOccurred(); } double AbstractCellCycleModelOdeSolver::GetStoppingTime() { assert(IsSetUp()); return mpOdeSolver->GetStoppingTime(); } void AbstractCellCycleModelOdeSolver::SetSizeOfOdeSystem(unsigned sizeOfOdeSystem) { mSizeOfOdeSystem = sizeOfOdeSystem; } unsigned AbstractCellCycleModelOdeSolver::GetSizeOfOdeSystem() { return mSizeOfOdeSystem; } void AbstractCellCycleModelOdeSolver::CheckForStoppingEvents() { #ifdef CHASTE_CVODE assert(IsSetUp()); if (boost::dynamic_pointer_cast<CvodeAdaptor>(mpOdeSolver)) { (boost::static_pointer_cast<CvodeAdaptor>(mpOdeSolver))->CheckForStoppingEvents(); } #endif //CHASTE_CVODE } void AbstractCellCycleModelOdeSolver::SetMaxSteps(long numSteps) { #ifdef CHASTE_CVODE assert(IsSetUp()); if (boost::dynamic_pointer_cast<CvodeAdaptor>(mpOdeSolver)) { (boost::static_pointer_cast<CvodeAdaptor>(mpOdeSolver))->SetMaxSteps(numSteps); } #endif //CHASTE_CVODE } void AbstractCellCycleModelOdeSolver::SetTolerances(double relTol, double absTol) { #ifdef CHASTE_CVODE assert(IsSetUp()); if (boost::dynamic_pointer_cast<CvodeAdaptor>(mpOdeSolver)) { (boost::static_pointer_cast<CvodeAdaptor>(mpOdeSolver))->SetTolerances(relTol, absTol); } #endif //CHASTE_CVODE } bool AbstractCellCycleModelOdeSolver::IsAdaptive() { bool adaptive = false; #ifdef CHASTE_CVODE assert(IsSetUp()); if (boost::dynamic_pointer_cast<CvodeAdaptor>(mpOdeSolver)) { adaptive = true; } #endif //CHASTE_CVODE return adaptive; }
#include "Nodo.h" Nodo::Nodo(string ciudad) { this->ciudad = ciudad; //ctor } Nodo::~Nodo() { //dtor }
// // Created by 王润基 on 2017/4/19. // #include <cmath> #include "SpotLight.h" SpotLight::SpotLight(Color const &color, const Ray &ray, float angle, float edgeAngle) : ray(ray), angle(angle), edgeAngle(edgeAngle) { this->color = color; } Light SpotLight::illuminate(Vector3f const &point) const { Color c = Color::zero; float theta = acosf(ray.getUnitDir().cos(point - ray.getStartPoint())); if(theta < angle + edgeAngle) { float t = sqrtf(std::min(1.0f, (angle + edgeAngle - theta) / edgeAngle)); c = color * t; // c = color / (point - ray.getStartPoint()).len2() * t; } return Light(ray.getStartPoint(), point, c); } bool SpotLight::inRange(Vector3f const &point) const { return ray.getUnitDir().cos(point - ray.getStartPoint()) > cosf(angle + edgeAngle) - eps; } Ray SpotLight::sample() const { auto const& pos = ray.getStartPoint(); auto const& main = ray.getUnitDir(); Vector3f dir; do {dir = Vector3f::getRandUnit();} while(main.angle(dir) > angle + edgeAngle); return Ray(pos, dir); }
int Solution::searchMatrix(vector<vector<int> > &arr, int k) { int n=arr.size(),m=arr[0].size(); for(int i=0;i<n;i++){ if(arr[i][0]>k) break; if(arr[i][m-1]<k) continue; if(binary_search(arr[i].begin(),arr[i].end(),k)) return 1; } return 0; }
/********************************************************************* Matt Marchant 2014 - 2016 http://trederia.blogspot.com xygine - Zlib license. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #ifndef XY_SHADER_POSTGAUSSIAN_HPP_ #define XY_SHADER_POSTGAUSSIAN_HPP_ #include <xygine/shaders/Default.hpp> namespace xy { namespace Shader { namespace PostGaussianBlur { static const std::string fragment = "#version 120\n" \ "uniform sampler2D u_sourceTexture;\n" \ "uniform vec2 u_offset;\n" \ "void main()\n" \ "{\n " \ " vec2 texCoords = gl_TexCoord[0].xy;\n" \ " vec4 colour = vec4(0.0);\n" \ " colour += texture2D(u_sourceTexture, texCoords - 4.0 * u_offset) * 0.0162162162;\n" \ " colour += texture2D(u_sourceTexture, texCoords - 3.0 * u_offset) * 0.0540540541;\n" \ " colour += texture2D(u_sourceTexture, texCoords - 2.0 * u_offset) * 0.1216216216;\n" \ " colour += texture2D(u_sourceTexture, texCoords - u_offset) * 0.1945945946;\n" \ " colour += texture2D(u_sourceTexture, texCoords) * 0.2270270270;\n" \ " colour += texture2D(u_sourceTexture, texCoords + u_offset) * 0.1945945946;\n" \ " colour += texture2D(u_sourceTexture, texCoords + 2.0 * u_offset) * 0.1216216216;\n" \ " colour += texture2D(u_sourceTexture, texCoords + 3.0 * u_offset) * 0.0540540541;\n" \ " colour += texture2D(u_sourceTexture, texCoords + 4.0 * u_offset) * 0.0162162162;\n" \ " gl_FragColor = colour;\n" \ "}"; } }//namespace Shader }//namespace xy #endif //XY_SHADER__HPP_
#include "multi_pipeline.hh" #include "config.hh" template <class T> bsc::Multi_pipeline<T>::Multi_pipeline(unsigned npipelines): _pipelines(npipelines) { unsigned num = 0; for (base_pipeline& ppl : this->_pipelines) { ppl.set_number(num); ++num; } } template <class T> void bsc::Multi_pipeline<T>::set_name(const char* rhs) { for (base_pipeline& ppl : this->_pipelines) { ppl.set_name(rhs); } } template <class T> void bsc::Multi_pipeline<T>::start() { this->setstate(pipeline_state::starting); for (base_pipeline& ppl : this->_pipelines) { ppl.start(); } this->setstate(pipeline_state::started); } template <class T> void bsc::Multi_pipeline<T>::stop() { this->setstate(pipeline_state::stopping); for (base_pipeline& ppl : this->_pipelines) { ppl.stop(); } this->setstate(pipeline_state::stopped); } template <class T> void bsc::Multi_pipeline<T>::wait() { for (base_pipeline& ppl : this->_pipelines) { ppl.wait(); } } template class bsc::Multi_pipeline<BSCHEDULER_KERNEL_TYPE>;
class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { // 本题是BFS,也可以认为是拓扑排序。这些基本原理见代码后面的附录。 // 为了描述方便,称0入度的课为初级课,需要入度的是高级课。 vector<vector<int>> edges(numCourses); // edges用来存初级课下面的高级课,就像是一个node连着几门大课,有几门课就有几条edge vector<int> inDegree(numCourses); // 用来存每门课的入度 queue<int> q; // 入度为0的课进入queue int count = 0; // 如果count可以和numCourses相等,说明可以上完课,return true,反之不行,return false。 for (const auto& course : prerequisites){ // 为什么auto后面要加&? 详见Solution的图。 edges[course[1]].push_back(course[0]); // 将初级课程对应的后续高级课程联系起来 inDegree[course[0]]++; // 有初级课程cue到高级课程,那么高级课程入度+1 } for (int i = 0; i < numCourses; i++){ // 放入所有的入度为0的课程 if (inDegree[i] == 0){ q.push(i); } } while (!q.empty()){ // 当有课程时 count++; // 结果+1 int coursePre = q.front(); // 让queue把之前存的初级课程弹出来 q.pop(); for (int edge : edges[coursePre]){ // 根据初级课程,向下挖掘对应高级课程的内容 inDegree[edge]--; // 既然修完初级课程,那么高级课程入度-1 if (inDegree[edge] == 0){ // 入度为0,代表可以修了 q.push(edge); } } } return count == numCourses; // 如果相等,则可以修完;否则不行 } }; // reference1 https://leetcode-cn.com/problems/course-schedule/solution/ke-cheng-biao-by-leetcode-solution/ // reference2 https://leetcode-cn.com/problems/course-schedule/solution/bao-mu-shi-ti-jie-shou-ba-shou-da-tong-tuo-bu-pai-/ /* 附录 reference1是官方题解,这里的C++代码参考于此,但增加了可读性; reference2是相关原理介绍,这里写代码的思路参考于此。 可能有几个问题,是妨碍阅读代码的: 1.什么是拓扑排序? 在图论中,拓扑排序(Topological Sorting)是一个有向无环图(DAG, Directed Acyclic Graph)的所有顶点的线性序列。且该序列必须满足下面两个条件: 每个顶点出现且只出现一次。 若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面。 有向无环图(DAG)才有拓扑排序,非DAG图没有拓扑排序一说。 所以,这里选课程显然是一个拓扑排序的过程。具体见链接:https://www.jianshu.com/p/b59db381561a 2.什么是入度和出度? 如果存在一条有向边 A --> B,则这条边给 A 增加了 1 个出度,给 B 增加了 1 个入度。 */
/* * Copyright 2016-2017 Flatiron Institute, Simons Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mountainprocessrunner.h" #include "mvdiscrimhistview_guide.h" #include <QGridLayout> #include <taskprogress.h> #include "mlcommon.h" #include "histogramview.h" #include <QWheelEvent> #include "mvmainwindow.h" #include "actionfactory.h" struct DiscrimHistogram { int k1, k2; QVector<double> data1, data2; }; class MVDiscrimHistViewGuideComputer { public: //input QString mlproxy_url; DiskReadMda32 timeseries; DiskReadMda firings; int num_histograms; //old version QSet<int> clusters_to_exclude; //old version QList<int> cluster_numbers; QString method; //old version //output QList<DiscrimHistogram> histograms; void compute(); }; class MVDiscrimHistViewGuidePrivate { public: MVDiscrimHistViewGuide* q; int m_num_histograms = 20; MVDiscrimHistViewGuideComputer m_computer; QList<DiscrimHistogram> m_histograms; double m_zoom_factor = 1; void set_views(); QSet<int> get_clusters_to_exclude(); }; MVDiscrimHistViewGuide::MVDiscrimHistViewGuide(MVAbstractContext* context) : MVHistogramGrid(context) { d = new MVDiscrimHistViewGuidePrivate; d->q = this; this->recalculateOn(context, SIGNAL(currentTimeseriesChanged())); this->recalculateOn(context, SIGNAL(firingsChanged()), false); this->recalculateOn(context, SIGNAL(clusterMergeChanged()), true); this->recalculateOn(context, SIGNAL(clusterVisibilityChanged()), true); this->recalculateOn(context, SIGNAL(viewMergedChanged()), true); this->recalculateOnOptionChanged("discrim_hist_method", true); ActionFactory::addToToolbar(ActionFactory::ActionType::ZoomInHorizontal, this, SLOT(slot_zoom_in_horizontal())); ActionFactory::addToToolbar(ActionFactory::ActionType::ZoomOutHorizontal, this, SLOT(slot_zoom_out_horizontal())); ActionFactory::addToToolbar(ActionFactory::ActionType::PanLeft, this, SLOT(slot_pan_left())); ActionFactory::addToToolbar(ActionFactory::ActionType::PanRight, this, SLOT(slot_pan_right())); this->recalculate(); } MVDiscrimHistViewGuide::~MVDiscrimHistViewGuide() { this->stopCalculation(); delete d; } void MVDiscrimHistViewGuide::setNumHistograms(int num) { d->m_num_histograms = num; } void MVDiscrimHistViewGuide::prepareCalculation() { MVContext* c = qobject_cast<MVContext*>(mvContext()); Q_ASSERT(c); d->m_computer.mlproxy_url = c->mlProxyUrl(); d->m_computer.timeseries = c->currentTimeseries(); d->m_computer.firings = c->firings(); d->m_computer.num_histograms = d->m_num_histograms; d->m_computer.clusters_to_exclude = d->get_clusters_to_exclude(); d->m_computer.cluster_numbers = c->selectedClusters(); d->m_computer.method = c->option("discrim_hist_method").toString(); } void MVDiscrimHistViewGuide::runCalculation() { d->m_computer.compute(); } double compute_min3(const QList<DiscrimHistogram>& data0) { double ret = 0; for (int i = 0; i < data0.count(); i++) { QVector<double> tmp = data0[i].data1; tmp.append(data0[i].data2); for (int j = 0; j < tmp.count(); j++) { if (tmp[j] < ret) ret = tmp[j]; } } return ret; } double max3(const QList<DiscrimHistogram>& data0) { double ret = 0; for (int i = 0; i < data0.count(); i++) { QVector<double> tmp = data0[i].data1; tmp.append(data0[i].data2); for (int j = 0; j < tmp.count(); j++) { if (tmp[j] > ret) ret = tmp[j]; } } return ret; } void MVDiscrimHistViewGuide::onCalculationFinished() { d->m_histograms = d->m_computer.histograms; d->set_views(); } void MVDiscrimHistViewGuideComputer::compute() { TaskProgress task(TaskProgress::Calculate, QString("Discrim Histograms")); histograms.clear(); MountainProcessRunner MPR; MPR.setMLProxyUrl(mlproxy_url); /* MPR.setProcessorName("mv_discrimhist_guide"); QMap<QString, QVariant> params; params["timeseries"] = timeseries.makePath(); params["firings"] = firings.makePath(); params["num_histograms"] = num_histograms; params["clusters_to_exclude"] = MLUtil::intListToStringList(clusters_to_exclude.toList()).join(","); params["method"]=method; */ MPR.setProcessorName("mv_discrimhist_guide2"); QMap<QString, QVariant> params; params["timeseries"] = timeseries.makePath(); params["firings"] = firings.makePath(); params["clip_size"] = 50; params["add_noise_level"] = 1; params["cluster_numbers"] = MLUtil::intListToStringList(cluster_numbers).join(","); params["max_comparisons_per_cluster"] = 5; MPR.setInputParameters(params); QString output_path = MPR.makeOutputFilePath("output"); MPR.runProcess(); DiskReadMda output(output_path); //output.setRemoteDataType("float32"); QMap<QString, DiscrimHistogram*> hist_lookup; int LL = output.N2(); for (int i = 0; i < LL; i++) { int k1 = output.value(0, i); int k2 = output.value(1, i); int k0 = output.value(2, i); double val = output.value(3, i); QString code = QString("%1:%2").arg(k1).arg(k2); DiscrimHistogram* HH = hist_lookup.value(code); if (!HH) { DiscrimHistogram H; this->histograms << H; DiscrimHistogram* ptr = &this->histograms[this->histograms.count() - 1]; ptr->k1 = k1; ptr->k2 = k2; hist_lookup[code] = ptr; HH = hist_lookup.value(code); } { if (k0 == k1) HH->data1 << val; else HH->data2 << val; } } } void MVDiscrimHistViewGuide::wheelEvent(QWheelEvent* evt) { Q_UNUSED(evt) /* if (evt->delta() > 0) { slot_zoom_in(); } else if (evt->delta() < 0) { slot_zoom_out(); } */ } void MVDiscrimHistViewGuide::slot_zoom_in_horizontal(double zoom_factor) { QList<HistogramView*> views = this->histogramViews(); //inherited for (int i = 0; i < views.count(); i++) { views[i]->setXRange(views[i]->xRange() * (1.0 / zoom_factor)); } } void MVDiscrimHistViewGuide::slot_zoom_out_horizontal(double factor) { slot_zoom_in_horizontal(1 / factor); } void MVDiscrimHistViewGuide::slot_pan_left(double units) { QList<HistogramView*> views = this->histogramViews(); //inherited for (int i = 0; i < views.count(); i++) { MVRange range = views[i]->xRange(); if (range.range()) { range = range + units * range.range(); } views[i]->setXRange(range); } } void MVDiscrimHistViewGuide::slot_pan_right(double units) { slot_pan_left(-units); } void MVDiscrimHistViewGuidePrivate::set_views() { MVContext* c = qobject_cast<MVContext*>(q->mvContext()); Q_ASSERT(c); double bin_min = compute_min3(m_histograms); double bin_max = max3(m_histograms); double max00 = qMax(qAbs(bin_min), qAbs(bin_max)); int num_bins = 500; //how to choose this? QList<HistogramView*> views; for (int ii = 0; ii < m_histograms.count(); ii++) { int k1 = m_histograms[ii].k1; int k2 = m_histograms[ii].k2; //if (q->c->clusterIsVisible(k1)) { { HistogramView* HV = new HistogramView; QVector<double> tmp = m_histograms[ii].data1; tmp.append(m_histograms[ii].data2); HV->setData(tmp); HV->setSecondData(m_histograms[ii].data2); HV->setColors(c->colors()); //HV->autoSetBins(50); HV->setBinInfo(bin_min, bin_max, num_bins); QString title0 = QString("%1/%2").arg(k1).arg(k2); HV->setTitle(title0); //HV->setDrawVerticalAxisAtZero(true); HV->setDrawVerticalAxisAtZero(false); HV->setXRange(MVRange(-max00, max00)); HV->autoCenterXRange(); HV->setProperty("k1", k1); HV->setProperty("k2", k2); views << HV; } } q->setHistogramViews(views); //base class q->slot_zoom_in_horizontal(2.5); //give it a nice zoom in to start } QSet<int> MVDiscrimHistViewGuidePrivate::get_clusters_to_exclude() { MVContext* c = qobject_cast<MVContext*>(q->mvContext()); Q_ASSERT(c); QSet<int> ret; QList<int> keys = c->clusterAttributesKeys(); foreach (int key, keys) { if (c->clusterTags(key).contains("rejected")) ret.insert(key); } return ret; } MVDiscrimHistGuideFactory::MVDiscrimHistGuideFactory(MVMainWindow* mw, QObject* parent) : MVAbstractViewFactory(mw, parent) { } QString MVDiscrimHistGuideFactory::id() const { return QStringLiteral("open-discrim-histograms-guide"); } QString MVDiscrimHistGuideFactory::name() const { return tr("Discrim Histograms Guide"); } QString MVDiscrimHistGuideFactory::title() const { return tr("Discrim"); } MVAbstractView* MVDiscrimHistGuideFactory::createView(MVAbstractContext* context) { MVDiscrimHistViewGuide* X = new MVDiscrimHistViewGuide(context); X->setPreferredHistogramWidth(200); X->setNumHistograms(80); return X; } bool MVDiscrimHistGuideFactory::isEnabled(MVAbstractContext* context) const { Q_UNUSED(context) return true; }
// This file has been generated by Py++. #ifndef FrameWindow_hpp__pyplusplus_wrapper #define FrameWindow_hpp__pyplusplus_wrapper void register_FrameWindow_class(); #endif//FrameWindow_hpp__pyplusplus_wrapper
#ifndef _DATACONFIGREADER_H_ #define _DATACONFIGREADER_H_ #include <QString> //#include "moduleBase/IOBase.h" #include <QFile> #include "DataProperty/modelTreeItemType.h" class QDomElement; class QDomDocument; namespace ConfigOption { class DataConfig; class PostConfig; class DataConfigReader //: public ModuleBase::IOBase { public: DataConfigReader(const QString fileName, DataConfig* dataconfig, PostConfig* postconfig); ~DataConfigReader(); bool read() /*override*/; private: void readDataBlock(ProjectTreeType t, QDomElement* e); void readPostConfig(ProjectTreeType t, QDomElement* e); private: DataConfig* _dataConfig{}; PostConfig* _postConfig{}; QDomDocument* _doc{}; QFile _file{}; }; } #endif
#pragma once #include "Set.h" #include <set> namespace TestSet { void TestAll(); #if PRINT_INT_TREE void TestPrintSet(); #endif } // SET OUTPUT template<class K> std::ostream &operator<<(std::ostream &os, std::set<K> const &m) { os << "{"; bool first = true; for (auto const &v : m) { if (!first) { os << ", "; } first = false; os << v; } return os << "}"; } template<class K> std::ostream &operator<<(std::ostream &os, ft::Set<K> const &m) { os << "{"; bool first = true; for (auto const &v : m) { if (!first) { os << ", "; } first = false; os << v; } return os << "}"; } // SET vs FT::SET template<class K> bool operator==(ft::Set<K> const &fm, std::set<K> const &m) { if (fm.size() != m.size()) { return false; } auto ft_it = fm.begin(); for (auto it = m.begin(); it != m.end(); ++it) { if (*it != *ft_it) { return false; } ++ft_it; } return true; } template<class K> bool operator!=(ft::Set<K> const &fm, std::set<K> const &m) { return !(fm == m); } template<class K> bool operator==(std::set<K> const &m, ft::Set<K> const &fm) { return fm == m; } template<class K> bool operator!=(std::set<K> const &m, ft::Set<K> const &fm) { return !(fm == m); }
/* * CstyleIndex.h * * Created on: Oct 8, 2013 * Author: vbonnici */ #ifndef CSTYLEINDEX_H_ #define CSTYLEINDEX_H_ #include <stdio.h> #include <string.h> #include <vector> #include <bitset> #include "data_ts.h" #include "sais.h" #include "DNA5Alphabet.h" namespace dolierlib{ /* * print the suffix (of length n) in the suffix array at position pos */ void print_dna5_SA(dna5_t *seq/*the indexed sequence*/, usize_t *SA, usize_t pos, int n){ for(int i=0; i<n; i++){ std::cout<<DNA5Alphabet::symbolFor(seq[SA[pos]+i]); } } //inline //void //fill_code4_from_SA(dna5_t *seq, usize_t *SA, usize_t pos, _ui16 *c4){ //// print_dna5_SA(seq,SA,pos,8);std::cout<<"\n"; // int mask = 0x3; // int shift = 14; // int cc5; // *c4 = 0; // for(int i=0; i< 8; i++ ){ // cc5 = seq[SA[pos]+i]; // if(cc5 > DNA5Alphabet::T) cc5 = DNA5Alphabet::A; //// std::cout<<shift<<"|"<<cc5<<"|"<<((cc5&mask)<<shift)<<"\n"; //// std::cout<<std::bitset<16>((cc5&mask)<<shift)<<"\n"; // *c4 |= (cc5&mask)<<shift; // shift -= 2; // } //// std::cout<<(*c4)<<"\n"; //// std::cout<<std::bitset<16>(*c4)<<"\n"; //} /* * convert a nucleotide sequence in a dna5_t array */ dna5_t* to_dna5(std::string &s){ dna5_t *s5 = new dna5_t[s.length()]; for(usize_t i=0; i<s.length(); i++){ s5[i] = DNA5Alphabet::codeFor(s[i]); } return s5; } /* * convert a dna5_t array of length k in a string */ std::string to_string(dna5_t *t, int k){ std::stringstream ss; std::string s; for(int i=0;i<k;i++){ s = s + DNA5Alphabet::symbolFor(t[i]); } return s; } void print_dna5(dna5_t *s, int n){ for(int i=0;i<n;i++){ std::cout<<DNA5Alphabet::symbolFor(s[i]); } } void print_dna5(const dna5_t *s, int n){ for(int i=0;i<n;i++){ std::cout<<DNA5Alphabet::symbolFor(s[i]); } } void print_dna5(dna5_t *s, int p, int n){ for(int i=p;i<p+n;i++){ std::cout<<DNA5Alphabet::symbolFor(s[i]); } } /* * push the reverse complement of sequence s (of length n) in d */ inline void reverseComplement(dna5_t *s, dna5_t *d, int n){ for(int i=0; i<n; i++){ d[n-i-1] = DNA5Alphabet::complement(s[i]); } } /* * tell if s (of length k) is less/equal to its reverse complement */ inline bool leqRC(dna5_t *s, int k){ for(int i=0; i<k; i++){ if(DNA5Alphabet::complement(s[i]) != s[k-i-1]) return (DNA5Alphabet::complement(s[i]) >= s[k-i-1]); } return true; } /* * tell if s (of length k) is equal to its reverse complement */ inline bool RCeq(dna5_t *s, int k){ //// if(k%2==0){ // //std::cout<<"#"<<k<<"|"<<(k/2)<<"\n"; // //for(int i=0; i<k/2; i++){ // for(int i=0; i<k; i++){ // if(DNA5Alphabet::complement(s[i]) != s[k-i-1]) // return false; // } //// } //// else{ //// for(int i=0; i<k; i++){ //// if(DNA5Alphabet::complement(s[i]) != s[k-i-1]) //// return false; //// } //// } // return true; if(k%2==0){ for(int i=0; i<k/2; i++){ if(DNA5Alphabet::complement(s[i]) != s[k-i-1]) return false; } return true; } return false; } /* * return the reverse complement of the nucleotide sequence s */ inline std::string reverseComplement(std::string &s){ std::string r = ""; //for(int i=0; i<s.length(); i++){ for(size_t i=0; i<s.length(); i++){ // std::cout<<"r:"<<(DNA5Alphabet::symbolFor( DNA5Alphabet::complement( DNA5Alphabet::codeFor(s[i]) ) ))<<"\n"; r = DNA5Alphabet::symbolFor( DNA5Alphabet::complement( DNA5Alphabet::codeFor(s[i]) ) ) + r; } return r; } /* * tell if two nucleotide sequences of length n are equal */ inline bool equal_dna5(dna5_t *s, dna5_t *d, int n){ for(int i=0; i<n; i++) if(s[i]!=d[i]) return false; return true; } /* * return * 0 if a=b * <0 if a<b * >0 if a>b * in the lexicographic order */ inline int compare(dna5_t *a, dna5_t *b, int k){ for(int i=0; i<k; i++){ if(a[i] != b[i]){ //it works because in DNA5Alphabet A=0,C=1,G=2,T=3,N=4,$=5 return a[i] - b[i]; } } return 0; } /* * An object to store the concatenation of a set of sequences plus other data. */ class DNA5MS_t{ public: dna5_t *seq; //the concatenation sequence usize_t seq_length; //the length of the concatenation sequence usize_t nof_seqs; //the number of original sequences usize_t *lengths; //the length of each original sequence, in the same order in which they are concatenated bool areUndefTeminated; //true if the concatenation is made by putting $ between sequences bool freeOnExit; //if true then delete array on deconstruction DNA5MS_t(){ seq = NULL; seq_length = 0; nof_seqs = 0; lengths = NULL; freeOnExit = false; areUndefTeminated = false; } DNA5MS_t(bool _freeOnExit){ seq = NULL; seq_length = 0; nof_seqs = 0; lengths = NULL; areUndefTeminated = false; freeOnExit = _freeOnExit; } // DNA5MS_t(const DNA5MS_t &ms){ // seq = ms.seq; // seq_length = ms.seq_length; // nof_seqs = ms.nof_seqs; // lengths = ms.lengths; // } ~DNA5MS_t(){ if(freeOnExit){ if(seq!=NULL) delete [] seq; if(lengths!= NULL) delete [] lengths; } } }; /* * concatenate a set of sequences, putting $ between them and at the end of the result sequence */ void concat(DNA5MS_t& gmseq, //output concatenation std::vector<dna5_t*>& a_sequences, //input sequences std::vector<usize_t>& a_lengths, //input sequences lengths bool areUndefTerminated //true if input sequences are already $ terminated ){ gmseq.nof_seqs = a_sequences.size(); gmseq.lengths = new usize_t[gmseq.nof_seqs]; if(areUndefTerminated){ gmseq.seq_length = 0; for(usize_t i=0; i<gmseq.nof_seqs; i++){ gmseq.lengths[i] = a_lengths.at(i); gmseq.seq_length += gmseq.lengths[i]; } gmseq.seq = new dna5_t[gmseq.seq_length]; dna5_t *ss; int i=0, ii=0, l=0; for(std::vector<dna5_t*>::iterator IT = a_sequences.begin(); IT!= a_sequences.end();IT++){ ss = (*IT); l = gmseq.lengths[i]; memcpy(&(gmseq.seq[ii]), ss, l*sizeof(dna5_t)); ii += l; i++; } } else{ gmseq.seq_length = 0; for(usize_t i=0; i<gmseq.nof_seqs; i++){ gmseq.lengths[i] = a_lengths.at(i) +1; gmseq.seq_length += gmseq.lengths[i]; } gmseq.seq = new dna5_t[gmseq.seq_length]; dna5_t *ss; int i=0, ii=0, l=0; for(std::vector<dna5_t*>::iterator IT = a_sequences.begin(); IT!= a_sequences.end();IT++){ ss = (*IT); l = gmseq.lengths[i]-1; memcpy(&(gmseq.seq[ii]), ss, l*sizeof(dna5_t)); ii += l; gmseq.seq[ii] = DNA5Alphabet::UNDEF; ii++; i++; } } } /* * An object to store suffix array data */ class CsFullyContainer{ public: usize_t *SA; usize_t *LCP; usize_t *NS; usize_t first_ncode; //first position in SA where we found a N character (as start of that suffix) usize_t first_ecode; //first position in SA where we found a $ character (as start of that suffix) bool freeOnExit;//if true then delete data on decostruction CsFullyContainer( usize_t *_SA, usize_t *_LCP, usize_t *_NS, usize_t _first_ncode, usize_t _first_ecode, bool _freeOnExit ) : SA(_SA), LCP(_LCP), NS(_NS), first_ncode(_first_ncode), first_ecode(_first_ecode), freeOnExit(_freeOnExit){ } CsFullyContainer(bool _freeOnExit){ SA =NULL; LCP = NULL; NS = NULL; first_ncode = 0; first_ecode = 0; freeOnExit = _freeOnExit; } ~CsFullyContainer(){ if(freeOnExit){ if(SA!=NULL) delete [] SA; if(LCP!=NULL) delete [] LCP; if(NS!=NULL) delete [] NS; } } }; /* * template function to build a suffix array of a sequence (of undefined type). See sais.h, too. */ template <typename T> usize_t* build_SA(T *seq, usize_t length){ //usize_t *SA;// = new usize_t[length]; //SA = sais_build_SA(seq, length); return sais_build_SA(seq, length); } /* * print a suffix array and its suffixes (of length n) */ void print_SA(dna5_t *seq/*indexed sequence*/, usize_t length, usize_t* SA, usize_t n){ for(usize_t i=0; i<length; i++){ std::cout<<i<<"\t"; for(usize_t j=0; j<n; j++){ std::cout<<DNA5Alphabet::symbolFor(seq[SA[i] + j]); } std::cout<<"\t"<<SA[i]<<"\n"; } } /* * linear algorithm to biuld the LCP array. * LCP[i] = lcp( suffix(sa[i]), suffix(sa[i-1]) ) */ template <typename T> usize_t* build_LCP(T *seq, usize_t length, usize_t *SA){ usize_t *LCP = new usize_t[length]; _si64* rank = new _si64 [length]; usize_t ilength = (usize_t)length; for (_si64 i = 0; i < ilength; i++) rank[SA[i]] = i; _si64 h = 0, k, j; for (_si64 i = 0; i < ilength; i++){ k = rank[i]; if (k == 0){ //lcp[k] = -1; LCP[k] = 0; } else{ j = SA[k - 1]; while (i + h < ilength && j + h < ilength && seq[i + h] == seq[j + h]){ h++; } LCP[k] = h; } if (h > 0) h--; } delete [] rank; return LCP; } /* * linear algorithm to build the NS array. * NS[i] = is the distance between the position SA[i] in seq and the closest next N. * For example, if seq[sa[i]]=N => NS[i] = 0 * if seq[sa[i]]|=N and seq[sa[i]+1]=N => NS[i] = 1 */ usize_t* build_NS(dna5_t *seq, usize_t length, usize_t *SA){ usize_t *NS = new usize_t[length]; usize_t *_ns = new usize_t[length]; usize_t last_n = length; dna5_t ncode = DNA5Alphabet::N; for(usize_t i=length-1; i>=0; i--){ if(seq[i] >= ncode){ last_n = i; } _ns[i] = last_n - i; if(i==0){ break; } } for(usize_t i=0; i<length; i++){ NS[i] = _ns[SA[i]]; } delete [] _ns; return NS; } /* * print SA,LCP and NS data, plus suffixes of length n */ void print_SA_LCP_N(dna5_t *seq/*indexed sequence*/, usize_t length, usize_t* SA, usize_t *LCP, usize_t *N, usize_t n){ for(usize_t i=0; i<length; i++){ std::cout<<i<<"\t"; for(usize_t j=0; j<n; j++){ std::cout<<DNA5Alphabet::symbolFor(seq[SA[i] + j]); } std::cout<<"\t"<<SA[i]<<"\t"<<LCP[i]<<"\t"<<N[i]<<"\n"; } } /* * tell min_i(SA[i] = N) */ usize_t where_first_ncode(usize_t *SA, usize_t *NS, usize_t length){ usize_t i; for(i=length -1; i>0 && NS[i]==0; i--); return i +1; } /* * tell min_i(SA[i] = N) */ usize_t where_first_ncode(dna5_t *seq, usize_t *SA, usize_t length){ usize_t i; for(i=length -1; i>0 && seq[SA[i]] > DNA5Alphabet::T; i--); return i +1; } /* * tell min_i(SA[i] > N), namely min_i(SA[i] = $) */ usize_t where_first_ecode(dna5_t *seq, usize_t *SA, usize_t length){ usize_t i; for(i=length -1; i>0 && seq[SA[i]] > DNA5Alphabet::N; i--); return i +1; } void write_nelsa( std::string &ofile, usize_t iseq_length, usize_t *SA, usize_t *LCP, usize_t *NS ){ std::ofstream off; off.open(ofile, std::ios::out | std::ios::binary); off.write(reinterpret_cast<const char *>(&iseq_length), sizeof(usize_t) ); for(usize_t i=0; i<iseq_length; i++){ off.write( reinterpret_cast<const char *>(&SA[i]), sizeof(usize_t) ); off.write( reinterpret_cast<const char *>(&LCP[i]), sizeof(usize_t) ); off.write( reinterpret_cast<const char *>(&NS[i]), sizeof(usize_t) ); } off.flush(); off.close(); } void read_nelsa( std::string &ifile, usize_t *length, usize_t *&SA, usize_t *&LCP, usize_t *&NS ){ std::ifstream iff; iff.open(ifile, std::ios::in | std::ios::binary); iff.read(reinterpret_cast<char *>(length), sizeof(usize_t) ); SA = new usize_t[*length]; LCP = new usize_t[*length]; NS = new usize_t[*length]; std::cout<<"allocation done "<< length <<"\n"; for(usize_t i=0; i<*length; i++){ iff.read( reinterpret_cast<char *>(SA+i) ,sizeof(usize_t)); iff.read( reinterpret_cast<char *>(LCP+i) ,sizeof(usize_t)); iff.read( reinterpret_cast<char *>(NS+i) ,sizeof(usize_t)); } iff.close(); } } #endif /* CSTYLEINDEX_H_ */
#ifndef ___DISPLAY__HPP #define ___DISPLAY__HPP #include "Catalog.hpp" #include <string> #include <iostream> #include <cctype> using namespace std; class Display { public: virtual ~Display() = default; virtual void display(vector<Book*> books,ostream& out) = 0; bool iequals(const string& a, const string& b) { unsigned int sz = a.size(); if (b.size() != sz) return false; for (unsigned int i = 0; i < sz; ++i) if (tolower(a[i]) != tolower(b[i])) return false; return true; } }; #endif // !1
// Question Name :- P 302 - A Smaller Team // /*The coach from the previous problem has now changed his mind. He only wants to take n-k people into the team. He asks the first person in the line to go find the shortest person and switch places with him. He then asks the second person in line to go find the second shortest person and switch places with him. So on, until the kth person has switched with the Kth shortest person in front of the line. Formally, swap the first element of the array with the smallest element of the array, then second element of the array with the second smallest element in the array and so on. Repeat this process k times. INPUT The first line of input is n (1≤n≤100), the number of applicants for the basketball team The second line of input is the heights of the n players (distinct positive numbers) each separated by a space. The third line of input is the number k (1≤k≤n) OUTPUT Print the heights of the players in a line after the k switches are complete. Sample Input 0 7 4 9 6 3 1 7 5 4 Sample Output 0 1 3 4 5 6 7 9 */ // Solution // #include <bits/stdc++.h> using namespace std; void s(int arr[], int n, int k) { int i, j, min_idx; for (i = 0; i < n-1; i++) { min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; swap(arr[min_idx], arr[i]); k--; if(!k) break; } } int main() { int n, k; cin >> n; int arr[n]; for(auto &x : arr) cin >> x; cin >> k; s(arr,n,k); for(auto &x : arr) cout << x << " "; return 0; }
/* On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. You can move according to the next rules: In one second always you can either move vertically, horizontally by one unit or diagonally (it means to move one unit vertically and one unit horizontally in one second). You have to visit the points in the same order as they appear in the array. */ #include <iostream> #include <vector> using namespace std; int minTimeToVisitAllPoints(vector<vector<int>> &points) { int ans = 0; for (int i = 0; i < points.size() - 1; i++) { int xi = points[i][0] - points[i + 1][0]; int yi = abs(points[i][1] - points[i + 1][1] - xi); ans += (abs(xi) + yi); } return ans; } int main() { // above function is the solution! // no driver code was writter for this problem! return 0; }
#include <limits.h> #include <iostream> #include <ctime> #include <cfenv> #include <cmath> #include <memory> #include <string> #include "data_region_a.h" #include "data_region_base.h" #include "data_region_bare_base.h" using namespace std; const int kColCount = 16*16; const int kRepetition = 10; const int kReqUnits = 32; void Create(){ unique_ptr<ADataRegion<int>> region_p(new DataRegionBareBase<int>(kColCount)); auto &region = *region_p; } void CM(){ DataRegionBareBase<int> region(kColCount); for(size_t i=0; i<kColCount; ++i) region[i]= i; /* Copy assignment */ DataRegionBareBase<int> replica_0(kColCount*2); for(size_t i=0; i<kColCount*2; ++i) replica_0[i]= i*2; replica_0 = region; for(size_t i=0; i<kColCount; ++i) replica_0[i]= replica_0[i]*2; for(size_t i=0; i<kColCount; ++i) /* Move assignment */ DataRegionBareBase<int> replica_1 = move(replica_0); } void MNextMirroredRegion(){ ADataRegion<int> *region_p = new DataRegionBareBase<int>(kColCount); auto &region = *region_p; for(size_t i=0; i<kColCount; ++i) region[i]= i; vector<MirroredRegionBareBase<int> *> mirrored_regions; auto mr = region.NextMirroredRegion(kReqUnits); int counter = 0; while(mr != nullptr){ for(size_t i=0; i<mr->count(); i++) counter++ ; mirrored_regions.push_back(mr); mr = region.NextMirroredRegion(kReqUnits); } fesetround(FE_UPWARD); int mregion_count = rint(1.*region.num_cols()/kReqUnits); region.ResetMirroredRegionIter(); auto mr2 = region.NextMirroredRegion(kReqUnits); int counter2 = 0; while(mr2 != nullptr){ for(size_t i=0; i<mr2->count(); i++) counter2++; mirrored_regions.push_back(mr2); mr2 = region.NextMirroredRegion(kReqUnits); } delete region_p; /* * Below results in double delete! Because of internal * delete that happen with region_p * for(auto &mr : mirrored_regions) delete mr; */ } typedef struct mm{ int a=0; uint64_t b=1011; } Metadata; void TestMDataRegion(){ Metadata metadata; metadata.a=1024; ADataRegion<int> *region_p = new DataRegionBase<int, Metadata>(kColCount, &metadata); auto &region = *region_p; auto &region_r = *(dynamic_cast<DataRegionBase<int, Metadata>*>(region_p)); for(size_t i=0; i<kColCount; ++i) region[i]= i; vector<MirroredRegionBase<int, Metadata> *> mirrored_regions; auto mr = dynamic_cast<MirroredRegionBase<int, Metadata>*> (region.NextMirroredRegion(kReqUnits)); int counter = 0; while(mr != nullptr){ for(size_t i=0; i<mr->count(); i++) counter++; mirrored_regions.push_back(mr); mr = dynamic_cast<MirroredRegionBase<int, Metadata>*> (region.NextMirroredRegion(kReqUnits)); } fesetround(FE_UPWARD); int mregion_count = rint(1.*region.num_cols()/kReqUnits); region.ResetMirroredRegionIter(); auto mr2 = dynamic_cast<MirroredRegionBase<int, Metadata>*> (region.NextMirroredRegion(kReqUnits)); int counter2 = 0; while(mr2 != nullptr){ for(size_t i=0; i<mr2->count(); i++) counter2++; mirrored_regions.push_back(mr2); mr2 = dynamic_cast<MirroredRegionBase<int, Metadata>*> (region.NextMirroredRegion(kReqUnits)); } delete region_p; /* * Below results in double delete! Because of internal * delete that happen with region_p * for(auto &reg : mirrored_regions) delete reg; */ } void DirectAssign(){ unique_ptr<ADataRegion<int>> region_p(new DataRegionBareBase<int>(kColCount)); auto &region = *region_p; uint64_t total_2x_real = 0; for(size_t i=0; i<kColCount; ++i){ region[i] = i; total_2x_real += 2*i; } uint64_t total_2x_calc = 0; for(size_t i=0; i<kColCount; ++i){ region[i] *= 2; total_2x_calc += region[i]; } } int main(){ Create(); DirectAssign(); TestMDataRegion(); MNextMirroredRegion(); CM(); }