blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
325e5585443ebe29b2015ac35751a0ec8779503c
b707ed5c3e00ff8132aee5b8f4601a4a560a3f9f
/C/Progs Antigos/Programas/GRAFICO.CPP
8f8c7f4398e7e97d16f0ad21fe0243563f75dc8c
[]
no_license
WiLLStenico/TestesEOutrasBrincadeiras
84b657ebb553ed05b5784f0cc04c645be9d339a1
03c4f5a7380fdc15fa1e579d7d830ee2553e0825
refs/heads/master
2020-04-06T06:54:02.851075
2012-07-20T03:08:15
2012-07-20T03:08:15
null
0
0
null
null
null
null
ISO-8859-5
C++
false
false
1,494
cpp
#include <stdio.h> #include <conio.h> #include <math.h> #include <GRAPHICS.H> #include <stdlib.h> #include <dos.h> #include <time.h> void opengraph() { int driver, mode; detectgraph(&driver,&mode); initgraph(&driver, &mode, "c:\\borlandc\\bgi"); } void hora() { time_t now; struct tm ts;//strutura escrever hora char buf[80]; time(&now); ts=*localtime(&now); strftime(buf,sizeof(buf),"%H:%M:%S",&ts); setcolor(BLACK); settextstyle(0,HORIZ_DIR,1); outtextxy(570,470,"лллллллл"); setcolor(LIGHTGRAY); outtextxy(570,470,buf); } void matriz() { setcolor(WHITE); line(0,240,640,240); line(320,0,320,480); } void desenha(int op,float xi,float xf) { float y,d,yp,dp,inverte; setcolor(CYAN); if(xi>xf)//para numeros invertidos { inverte=xf; xf=xi; xi=inverte; } if(op==1) { outtextxy((xi*10)+317,235-(xf*10),".");//ponto } if(op==2) { for(d=xi;d<=xf;d=d+0.2)//x ao quadrado { y=d*d; dp=d+1; yp=(dp)*(dp); outtextxy((d*5)+317,235-y,"."); //line(d+320,y-240,d+320,y-240);*/ } } } void main(void) { int tecla; float xi,y,xf,d,op; int nova; opengraph(); cleardevice(); nova=0; xi=320; do{ if(nova==0) { scanf("%f",&xi); scanf("%f",&xf); nova=1; cleardevice(); } do{ matriz(); desenha(2,xi,xf); hora(); }while(!kbhit); tecla=getch(); }while(tecla!=27); cleardevice(); }
[ "willstenico@gmail.com" ]
willstenico@gmail.com
e6bcf4ce1f1976134c771a1362a3bd51df9d74a0
37c33fe7fe6876c4cff3f7fda0719295277f250f
/src/main4.cpp
1f281571d0f7e894b2628192cb94ef3840f544e8
[]
no_license
Alsadi1982/C-lab-2
1814b5fc950fce4239b662487aabb8d38ff5fdd4
19ffec30ecb7ce918960671034f62c0327cfd41a
refs/heads/master
2020-04-09T07:43:05.617214
2018-12-15T17:54:01
2018-12-15T17:54:01
160,167,717
0
0
null
null
null
null
UTF-8
C++
false
false
167
cpp
#include <stdio.h> #include "task4.h" int main() { char line[100] ; puts("Enter a string please:"); fgets(line, 100, stdin); printf(process(line)); return 0; }
[ "sav1982@inbox.ru" ]
sav1982@inbox.ru
38a6bd976eb9f1418b2cd8079713fbc9d3c37ba5
4b539c6c996323a8f7d6644c566c535906b2babe
/src/I2Cutils.cpp
e8aacc63dd62cd281e1ea7f062e1be293741d771
[]
no_license
BigBobsky/mpala
849e6c154a3ce7f79d822588e306c6b91ada6bc6
1e37ada6094fc133f6bc6b0f8fa6650efb6109db
refs/heads/master
2023-07-23T02:37:51.913988
2021-09-05T12:44:06
2021-09-05T12:44:06
283,446,457
0
0
null
null
null
null
UTF-8
C++
false
false
1,743
cpp
/* This file is part of MPALA. MPALA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MPALA is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MPALA. If not, see <http://www.gnu.org/licenses/>. */ /* Author : Jean-Luc TRESSET Contact : bigbobsky@gmail.com Creation date : 09/09/14 */ #include <iostream> #include "I2Cutils.hpp" namespace mpala { i2c_uword_16 I2Cutils::twos_complement(i2c_byte high, i2c_byte low) { i2c_uword_16 ret = high; ret = (ret << 8) + low; if (ret >= 0x8000) { ret = -((0xffff - ret) + 1); } return ret; } i2c_word_16 I2Cutils::signed_complement(i2c_byte high, i2c_byte low) { i2c_word_16 ret; uint16_t s = unsigned_word(high, low); if (s >= 0x8000) { // std::cout << "signed : " << s << std::endl; // std::cout << "signed min : " << 0xffff << std::endl; ret = -((0xffff - s) + 1); // std::cout << "signed ret : " << ret << std::endl; } else { // std::cout << "usigned : " << s << std::endl; ret = s; } return ret; } i2c_uword_16 I2Cutils::unsigned_word(i2c_byte high, i2c_byte low) { i2c_uword_16 ret = high << 8; ret = ret + low; return ret; } }
[ "jean-luc.tresset@luceor.com" ]
jean-luc.tresset@luceor.com
47d245329e81e83ccb74d856ce2b4b415403a37d
32e31aae6e1b06119636546287b76ad82f3a12e3
/MegaManX3/IntroScene.cpp
37c55d0849dacc060ba6a93fe9989eb59621b64f
[]
no_license
anhkhoa1704/MegaManX3
b298d5fc4a266ac018737aaaca8f1d15914a7980
1152ed27a985fd28272fc60f6adb831b0093ceec
refs/heads/master
2020-04-02T13:10:54.917119
2018-10-28T14:08:24
2018-10-28T14:08:24
154,470,817
1
0
null
null
null
null
UTF-8
C++
false
false
543
cpp
#include "IntroScene.h" #include "Global.h" #define SCALE 0.25 void IntroScene::Init() { tiledmap.Init("Assets/IntroStage-tile-map.json"); player.Init(); } void IntroScene::Release() { } void IntroScene::Update(float dt) { tiledmap.Update(dt); player.Update(dt); view_port->CalculateViewPortPos(player.GetPositionX(), player.GetPositionY()); } void IntroScene::Draw() { tiledmap.DrawMap(); tiledmap.DrawAnimationObject(); player.Draw(); tiledmap.DrawOverlayObject(); } IntroScene::IntroScene() { } IntroScene::~IntroScene() { }
[ "14520421@gm.uit.edu.vn" ]
14520421@gm.uit.edu.vn
260ed226a151dc8260c8e2427f656886d8a745dc
4abd8793f2f2cb52fe02837c67e39dfef74b5715
/vedant3620/day3/550a.cpp
6813e61d7971e28451379369256066e8f2b15d5b
[]
no_license
Devang-25/100DaysOfCode
bdab847655490b4421454b4693cfcd6ddc3d4ff5
4e3d632be1ecd3b235c03ac593a4ea8ec9562e56
refs/heads/master
2021-05-25T12:50:19.956945
2020-04-06T17:49:02
2020-04-06T17:49:02
253,761,487
1
1
null
2020-12-18T18:33:29
2020-04-07T10:31:32
null
UTF-8
C++
false
false
807
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main(){ string s; cin>>s; ll t=0; for(ll i=0;i<s.length()-1;i++){ if(s[i]=='A' && s[i+1]=='B'){ for(i=i+2;i<s.length()-1;i++){ if(s[i]=='B' && s[i+1]=='A'){ t=1; i=s.length(); } } } } if(t==1){ cout<<"YES"; return 0; } for(ll i=0;i<s.length()-1;i++){ if(s[i]=='B' && s[i+1]=='A'){ for(i=i+2;i<s.length()-1;i++){ if(s[i]=='A' && s[i+1]=='B'){ t=1; i=s.length(); } } } } if(t==1){ cout<<"YES"; return 0; } cout<<"NO"; return 0; }
[ "23037053+rishabhKalakoti@users.noreply.github.com" ]
23037053+rishabhKalakoti@users.noreply.github.com
28383a534c6cce2918c433b45905d0c5326781c6
d0dcd8492a5afd746bad488ee90c2c282998728f
/src/Communication/NetworkTransceiverNodeProcess.h
da6724b4370a1958aaffa3f4351f46f695279e1f
[]
no_license
dgitz/icarus_rover_v2
4c99bcf31b83701cfb130348acb3113721aa4c9e
1d25266f4bf9872bb5b98912d9c938e0d280756c
refs/heads/master
2021-03-09T05:55:47.352511
2020-04-05T20:07:07
2020-04-05T20:07:07
47,700,940
1
0
null
2020-04-05T20:07:08
2015-12-09T15:44:10
C++
UTF-8
C++
false
false
5,945
h
#include "../../include/Base/BaseNodeProcess.cpp" //C System Files //C++ System Files //ROS Base Functionality //ROS Messages #include <eros/systemsnapshot_state.h> //Project #include <tinyxml.h> /*! \class NetworkTransceiverNodeProcess NetworkTransceiverNodeProcess.h "NetworkTransceiverNodeProcess.h" * \brief This is a NetworkTransceiverNodeProcess class. Used for the networktransceiver_node node. * */ class NetworkTransceiverNodeProcess: public BaseNodeProcess { public: //Constants //Enumstouch enum PriorityLevel { UNDEFINED = 0, HIGH = 1, MEDIUM =2, LOW = 3 }; //Structs struct Message { uint16_t id; std::string name; uint32_t sent_counter; uint32_t recv_counter; double sent_rate; double recv_rate; double target_sendrate; uint8_t priority_level; }; struct QueueElement { uint16_t id; std::string item; }; struct RemoteDevice { std::string Name; double current_beatepoch_sec; double expected_beatepoch_sec; double offset_sec; }; ///Initialization Functions /*! \brief NodeProcess specific Initialization * */ eros::diagnostic load(std::string miscconfigfilepath); eros::diagnostic finish_initialization(); void reset() { } //Update Functions /*! \brief Implementation of the update function * */ eros::diagnostic check_remoteHeartbeats(); eros::diagnostic update(double t_dt,double t_ros_time); //Attribute Functions void set_networkconfiguration(std::string t_multicast_group,int t_send_multicast_port,int t_recv_unicast_port); std::string get_multicast_group() { return multicast_group; } int get_send_multicast_port() { return send_multicast_port; } int get_recv_unicast_port() { return recv_unicast_port; } void set_UIMode(std::string t_UIMode) { UIMode = t_UIMode; } std::string get_UIMode() { return UIMode; } std::vector<Message> get_messages() { return messages; }; bool get_remoteheartbeatresult() { return remote_heartbeat_pass; } //Update Functions /*! \brief Push to the Topic List. * Returns -1 if the topic type was not found. Returns 0 if the topic was already in the list, and 1 if the topic was added. */ int push_topiclist(std::string type,std::string name) { if(type == "eros/resource") { for(std::size_t i = 0; i < resource_topics.size();i++) { if(resource_topics.at(i) == name) { return 0; } } resource_topics.push_back(name); return 1; } else if(type == "eros/diagnostic") { for(std::size_t i = 0; i < diagnostic_topics.size();i++) { if(diagnostic_topics.at(i) == name) { return 0; } } diagnostic_topics.push_back(name); return 1; } else if(type == "eros/device") { for(std::size_t i = 0; i < device_topics.size();i++) { if(device_topics.at(i) == name) { return 0; } } device_topics.push_back(name); return 1; } else if(type == "eros/firmware") { for(std::size_t i = 0; i < firmware_topics.size();i++) { if(firmware_topics.at(i) == name) { return 0; } } firmware_topics.push_back(name); return 1; } return -1; } std::vector<std::string> get_topiclist(std::string type) { if(type == "eros/resource") { return resource_topics; } else if(type == "eros/diagnostic") { return diagnostic_topics; } else if(type == "eros/device") { return device_topics; } else if(type == "eros/firmware") { return firmware_topics; } std::vector<std::string> empty_list; return empty_list; } //Message Functions /*! \brief Process Command Message. All implementation should use at least the code in this Sample Function. * */ std::vector<eros::diagnostic> new_commandmsg(const eros::command::ConstPtr& t_msg); eros::diagnostic new_devicemsg(const eros::device::ConstPtr& device); eros::diagnostic new_remoteheartbeatmsg(double timestamp,std::string name,double current_beat,double expected_beat); eros::diagnostic new_message_sent(uint16_t id); eros::diagnostic new_message_recv(uint16_t id); //Support Functions bool push_sendqueue(uint16_t id,std::string msg); std::vector<QueueElement> get_sendqueue(uint8_t level); //Printing Functions std::string get_messageinfo(bool v); protected: private: /*! \brief Process Specific Implementation * */ int parse_miscconfigfile(TiXmlDocument doc); std::vector<eros::diagnostic> check_programvariables(); void init_messages(); Message get_messagebyid(uint16_t id) { for(std::size_t i = 0; i < messages.size(); i++) { if(messages.at(i).id == id) { return messages.at(i); } } Message empty; return empty; } bool push_sendhighqueue(uint16_t id,std::string msg) { QueueElement elem; elem.id = id; elem.item = msg; Message m = get_messagebyid(id); if(m.sent_rate <= (1.5*m.target_sendrate)) { sendqueue_highpriority.push_back(elem); } return true; } bool push_sendmediumqueue(uint16_t id,std::string msg) { QueueElement elem; elem.id = id; elem.item = msg; Message m = get_messagebyid(id); if(m.sent_rate <= (1.5*m.target_sendrate)) { sendqueue_mediumpriority.push_back(elem); } return true; } bool push_sendlowqueue(uint16_t id,std::string msg) { QueueElement elem; elem.id = id; elem.item = msg; Message m = get_messagebyid(id); if(m.sent_rate <= (1.5*m.target_sendrate)) { sendqueue_lowpriority.push_back(elem); } return true; } std::vector<Message> messages; std::vector<QueueElement> sendqueue_highpriority; std::vector<QueueElement> sendqueue_mediumpriority; std::vector<QueueElement> sendqueue_lowpriority; std::vector<RemoteDevice> remote_devices; bool remote_heartbeat_pass; std::string multicast_group; int send_multicast_port; int recv_unicast_port; std::string UIMode; std::vector<std::string> resource_topics; std::vector<std::string> diagnostic_topics; std::vector<std::string> device_topics; std::vector<std::string> firmware_topics; };
[ "davidgitz@gmail.com" ]
davidgitz@gmail.com
37dcd52bc0520d8d32ee626741b294663b7d8b92
cd3fe6562c20ab7095d323984df4305769b67a6f
/TMMiniOS/UserLoopFun.cpp
2e23ad1254d3810ae10826c4a2ebd46fdf219502
[]
no_license
JegernOUTT/TMMiniOS
cc9727b1bb561a4d431a60d57dab89de35bd44f1
67d5f4c4e60a8cc941f4fdc71ac53dfd2d752c97
refs/heads/master
2020-12-24T14:36:36.471435
2015-09-25T12:16:42
2015-09-25T12:16:42
42,584,242
0
0
null
null
null
null
UTF-8
C++
false
false
1,231
cpp
#include "Model.h" /* //======= Begin of Modbus Kernel ======= if(mtModbusPort[iScanCOMPort].EnableMode==_ModbusRTU_Slave) CheckModbusRTURequest(iScanCOMPort); // Is any request from Modbus/RTU Master ? if(mtModbusPort[iScanCOMPort].EnableMode==_ModbusASCII_Slave) CheckModbusASCIIRequest(iScanCOMPort); // Is any request from Modbus/ASCII Master ? if(mtModbusPort[iScanCOMPort].EnableMode==_ModbusRTU_Gateway) { SendModbusRequest(iScanCOMPort); // Passes request to modbus slave device. CheckResponseTimeout(iScanCOMPort); // If response timeout, sets iModbusAction // to IDLE status. CheckModbusResponse(iScanCOMPort); // Is any response from modbus slave device? SendModbusResponse(iScanCOMPort); // Passes response to Modbus/RTU Master. } iScanCOMPort++; if(iScanCOMPort>iTotalCOMPort) iScanCOMPort=1; //======= End of Modbus Kernel ======= */ void UserLoopFun(void) { CycleController & cycleController = CycleController::getInstance(); cycleController.read(); #ifdef VC_1992_16BIT Time::timeUpdate(); #endif }
[ "Hellboysis666@gmail.com" ]
Hellboysis666@gmail.com
73d26ac7ed9014e3563ad6ad3f5c0ce3dbb6b1ff
3a3c0c6cf372bc08e1e084fdc557fceefc879606
/Source/Sessions/Session2/SessionTwoDSP.cpp
f4b7719209be5f7200869696135476342895fedf
[]
no_license
shossa3/DSPExamples
1893456f1d54adda8115ff4299db5fba7745ccc6
3afdcc1312be3ec5c943523f3861b5a19a443c88
refs/heads/master
2020-04-08T04:40:09.213044
2018-11-25T11:59:11
2018-11-25T11:59:11
158,836,762
0
0
null
null
null
null
UTF-8
C++
false
false
5,970
cpp
/* ============================================================================== Shaikat Hossain DSPExamples ============================================================================== */ #include "SessionTwoDSP.h" //============================================================================== const void SessionTwoDSP::calculusAnalogCoefficients (float frequency, float Q, float gain, int type, float &b0, float &b1, float &b2, float &a1, float &a2) { auto w0 = (float)(2.0 * double_Pi * frequency); auto A = (float)(Decibels::decibelsToGain (gain / 2.0)); if (type == Type_LowPass1) { auto a0 = 1.0f; b0 = 1.0f / a0; b1 = 0.0f; b2 = 0.0f; a1 = (1.0f / w0) / a0; a2 = 0.0f; } else if (type == Type_HighPass1) { auto a0 = 1.0f; b0 = 0.f; b1 = (1.0f / w0) / a0; b2 = 0.0f; a1 = (1.0f / w0) / a0; a2 = 0.0f; } else if (type == Type_LowPass2) { auto a0 = 1.f; b0 = 1.f / a0; b1 = 0.f; b2 = 0.f; a1 = (1.0f / (Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else if (type == Type_BandPass2) { auto a0 = 1.f; b0 = 0.f; b1 = (1.0f / (Q * w0)) / a0; b2 = 0.f; a1 = (1.0f / (Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else if (type == Type_HighPass2) { auto a0 = 1.f; b0 = 0.f; b1 = 0.f; b2 = (1.0f / (w0 * w0)) / a0; a1 = (1.0f / (Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else if (type == Type_Peak) { auto a0 = 1.f; b0 = 1.0f / a0; b1 = (A / (Q * w0)) / a0; b2 = (1.0f / w0 / w0) / a0; a1 = (1.0f / (A * Q * w0)) / a0; a2 = (1.0f / (w0 * w0)) / a0; } else { b0 = 1.0f; b1 = 0.0f; b2 = 0.0f; a1 = 0.0f; a2 = 0.0f; } } const void SessionTwoDSP::calculusPreWarpedCoefficients (float frequency, float Q, float gain, int type, double _sampleRate, float &b0, float &b1, float &b2, float &a1, float &a2) { auto Ts = (float)(1.0 / _sampleRate); auto w0 = (float)(2.0 * double_Pi * frequency); auto A = (float)(Decibels::decibelsToGain (gain / 2.0)); Ts = (float) (std::tan (w0 * Ts / 2.0) * 2.0 / w0); auto Ts2 = Ts * Ts; auto w02 = w0 * w0; auto A2 = A * A; if (type == Type_LowPass1) { auto a0 = Ts * w0 + 2.0f; b0 = (Ts * w0) / a0; b1 = (Ts * w0) / a0; b2 = 0.0f; a1 = (Ts * w0 - 2.0f) / a0; a2 = 0.0f; } else if (type == Type_HighPass1) { auto a0 = Ts * w0 + 2.0f; b0 = 2.0f / a0; b1 = -2.0f / a0; b2 = 0.0f; a1 = (Ts * w0 - 2.0f) / a0; a2 = 0.0f; } else if (type == Type_LowPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (Q * Ts2 * w02) / a0; b1 = (2 * Q * Ts2 * w02) / a0; b2 = (Q * Ts2 * w02) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_BandPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (2 * Ts * w0) / a0; b1 = 0.0; b2 = (-2 * Ts * w0) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_HighPass2) { auto a0 = Q * Ts2 * w02 + 2 * Ts * w0 + 4 * Q; b0 = (4 * Q) / a0; b1 = (-8 * Q) / a0; b2 = (4 * Q) / a0; a1 = (2 * Q * Ts2 * w02 - 8 * Q) / a0; a2 = (Q * Ts2 * w02 - 2 * Ts * w0 + 4 * Q) / a0; } else if (type == Type_Peak) { auto a0 = A * Q * Ts2 * w02 + 2 * Ts * w0 + 4 * A * Q; b0 = (2 * A2 * Ts * w0 + Q * A * Ts2 * w02 + Q * A * 4) / a0; b1 = (2 * A * Q * Ts2 * w02 - 8 * A * Q) / a0; b2 = (-2 * A2 * Ts * w0 + Q * A * Ts2 * w02 + Q * A * 4) / a0; a1 = (2 * A * Q * Ts2 * w02 - 8 * A * Q) / a0; a2 = (A * Q * Ts2 * w02 - 2 * Ts * w0 + 4 * A * Q) / a0; } else { b0 = 1.0f; b1 = 0.0f; b2 = 0.0f; a1 = 0.0f; a2 = 0.0f; } } const double SessionTwoDSP::getAnalogMagnitudeForFrequency (double frequency, const float b0, const float b1, const float b2, const float a1, const float a2) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> jw = MathConstants<double>::twoPi * frequency * j; numerator += ((double)b0) * factor; factor *= jw; numerator += ((double)b1) * factor; factor *= jw; numerator += ((double)b2) * factor; denominator = 1.0; factor = jw; denominator += ((double)a1) * factor; factor *= jw; denominator += ((double)a2) * factor; return std::abs (numerator / denominator); } const double SessionTwoDSP::getAnalogPhaseForFrequency (double frequency, const float b0, const float b1, const float b2, const float a1, const float a2) { constexpr std::complex<double> j (0, 1); jassert (frequency >= 0); std::complex<double> numerator = 0.0, denominator = 0.0, factor = 1.0; std::complex<double> jw = MathConstants<double>::twoPi * frequency * j; numerator += ((double)b0) * factor; factor *= jw; numerator += ((double)b1) * factor; factor *= jw; numerator += ((double)b2) * factor; denominator = 1.0; factor = jw; denominator += ((double)a1) * factor; factor *= jw; denominator += ((double)a2) * factor; return std::arg (numerator / denominator); }
[ "shossa3@gmail.com" ]
shossa3@gmail.com
f6033bc51b2b73fb7db8851032a3c9c10d3645fc
04ddbee5901062b97c67a661a5e471fdc74768d0
/fits_data_model/tests/unit_test/src/TestCreateFitsFile.cxx
085630790bd8ba7142eed076c439f86fcf369e17
[]
no_license
davefutyan/common_sw
d0f643ca55488e7af810d8dd84f268f20330f958
1e45b3be84edd18a60e9a0ea8ef65444dfa2a254
refs/heads/master
2023-07-02T06:27:43.253219
2021-08-14T10:32:38
2021-08-14T10:32:38
395,084,522
0
0
null
null
null
null
UTF-8
C++
false
false
1,950
cxx
#define BOOST_TEST_MAIN #include "boost/test/unit_test.hpp" #include <string> #include <stdexcept> #include "ProgramParams.hxx" #include "CreateFitsFile.hxx" #include "SCI_PRW_SubArray.hxx" #include "SCI_COR_Lightcurve.hxx" using namespace boost; using namespace boost::unit_test; /** **************************************************************************** * @brief Required struct by the boost unit test system */ struct Fixture{ Fixture() {} ~Fixture() {} }; BOOST_FIXTURE_TEST_SUITE( TestCreateFitsFile, Fixture ) BOOST_AUTO_TEST_CASE( UTC_Image ) { unlink("result/CH_TU2015-04-09T13-51-30_SCI_PRW_SubArray_V0000.fits"); CheopsInit(framework::master_test_suite().argc, framework::master_test_suite().argv ); UTC utc(2015, 4, 9, 13, 51, 30, 0.45); SciPrwSubarray * sciPrwSubarray = createFitsFile<SciPrwSubarray>( "result", utc, VisitId(), {200, 200, 3}); SciPrwImagemetadata * sciPrwImagemetadata = Append_SciPrwImagemetadata(sciPrwSubarray); sciPrwImagemetadata->setCellCeCounter(4); sciPrwImagemetadata->WriteRow(); // the data classes have to be deleted to write the data into the FITS file. delete sciPrwSubarray; delete sciPrwImagemetadata; } BOOST_AUTO_TEST_CASE( All_Table ) { unlink("result/CH_PR990707_TG070755_PS15012009_TU2015-04-09T13-51-30_SCI_COR_Lightcurve-dataName_V0000.fits"); CheopsInit(framework::master_test_suite().argc, framework::master_test_suite().argv ); PassId passId(15, 1, 20, 9); VisitId visitId(99, 707, 707, 55); UTC utc(2015, 4, 9, 13, 51, 30, 0.45); SciCorLightcurve * sciCorLightcurve = createFitsFile<SciCorLightcurve>( "result", utc, visitId, passId, "dataName"); // the data classes have to be deleted to write the data into the FITS file. delete sciCorLightcurve; } BOOST_AUTO_TEST_SUITE_END()
[ "bekkelie@c1f87a2b-ace2-4d72-87d5-b738fb7f7369" ]
bekkelie@c1f87a2b-ace2-4d72-87d5-b738fb7f7369
4c3e9274e37cf844c907a9e0d2f47ae95aa2ff3a
78ddffce9b6ee052288c763f57c04a5352f9b8eb
/src/events/GetRecipeResultEvent.hpp
7a21af5ddfd2fd835dd0d270d62f46be6eb542c9
[]
no_license
vallism2000/Test
655ba75a5059310c7990e93e3140a3b91e09a7de
34f43114df8ccf4a36ee7740b8a0ccf90d5fec8d
refs/heads/master
2021-01-10T02:03:57.015446
2013-04-03T11:55:33
2013-04-03T11:55:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
369
hpp
/* * GetRecipeResultEvent.hpp * */ #ifndef GETRECIPERESULTEVENT_HPP_ #define GETRECIPERESULTEVENT_HPP_ #include "IEvent.hpp" #include "drinkObjects/DrinkRecipe.hpp" class GetRecipeResultEvent: public IEvent { public: GetRecipeResultEvent(DrinkRecipe * recipe); virtual ~GetRecipeResultEvent(); DrinkRecipe * Recipe; }; #endif /* GETRECIPERESULTEVENT_HPP_ */
[ "nlutz91@gmail.com" ]
nlutz91@gmail.com
b54fed716eff5f6a1f7118ee3757dd5d4b08a2c7
babef98a051ad56f1c0d4c18a2a09ae83b2def31
/simplePython/simplePython/stdafx.cpp
98d44f1872c2c6ff952b15318d6b35ee58e6de95
[]
no_license
xjyDaddy/cplusplus_learn
1af4ec314f0ccc887c17e0ef233e8366ce9e1688
84b1ac2527139c695cfd3a954d351e06090daaa0
refs/heads/master
2020-03-15T13:48:12.096220
2018-06-01T09:46:15
2018-06-01T09:46:15
132,175,548
0
0
null
null
null
null
GB18030
C++
false
false
265
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // simplePython.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ "xijiyuan@foxmail.com" ]
xijiyuan@foxmail.com
dc4006f81d4821fbc676b578d955ff9aa55c0f4c
d084c38697d64f432288282c397d80630a0795c9
/src/ESBServer/src/Renderer/MFC/Browsers/HierarchyBrowserRenderer.cpp
fc0ec9a9e553b03ab2e61a36964374e3ec4af78d
[ "MIT" ]
permissive
124327288/BeSweet
6e0d9dd863b8e5a0927eb693c4d1ec80c7e3f880
fc58c24a32a96cc4026fdf2ff97c1a99b89ba86f
refs/heads/master
2021-06-13T02:49:41.213640
2017-04-20T20:03:29
2017-04-20T20:03:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,099
cpp
/** /* Copyright (c) 2003by Marco Welti /* /* This document is bound by the QT Public License /* (http://www.trolltech.com/licenses/qpl.html). /* See License.txt for more information. /* /* /* /* ALL RIGHTS RESERVED. /* /* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS /* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE /* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY /* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL /* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE /* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, /* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING /* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* /***********************************************************************/ #include "stdafx.h" #include "resource.h" #include "HierarchyBrowserRenderer.h" #include <Model/MetaModel/MetaModel.h> #include <Controller/Browsers/HierarchyBrowser.h> #include <Renderer/MFC/ESBImageList.h> #include <Renderer/MFC/TreeCtrlHelper.h> #include <Renderer/LabelBroker.h> #include <list> using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // HierarchyBrowserRenderer dialog const size_t FIRST_HISTORY_ENTRY = 10000; const size_t MAX_HISTORY_SIZE = 10; BEGIN_MESSAGE_MAP(HierarchyBrowserRenderer, RaisableDialog) //{{AFX_MSG_MAP(HierarchyBrowserRenderer) ON_NOTIFY(TVN_ITEMEXPANDING, IDC_HIERARCHY, onExpandHierarchy) ON_COMMAND(ID_HIERARCHY_FOCUSON, onFocusOn) ON_COMMAND(ID_HIERARCHY_FOCUSONX, onFocusOnX) ON_NOTIFY(NM_CLICK, IDC_HIERARCHY, onMouseClickedHierarchy) ON_NOTIFY(NM_DBLCLK, IDC_HIERARCHY, onMouseClickedHierarchy) ON_NOTIFY(NM_RCLICK, IDC_HIERARCHY, onMouseClickedHierarchy) ON_NOTIFY(TVN_GETINFOTIP, IDC_HIERARCHY, onGetToolInfo) //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_TYPE_HIERARCHY, onShowTypeHierarchy) ON_BN_CLICKED(IDC_SUBTYPE_HIERARCHY, onShowSubtypeHierarchy) ON_BN_CLICKED(IDC_SUPERTYPE_HIERARCHY, onShowSupertypeHierarchy) ON_BN_CLICKED(IDC_LOCK_HIERARCHY, onLockHierarchy) ON_BN_CLICKED(IDC_INHERITED_MEMBERS, onShowInheritedMembers) ON_COMMAND_RANGE(FIRST_HISTORY_ENTRY, FIRST_HISTORY_ENTRY+MAX_HISTORY_SIZE, onHistory) END_MESSAGE_MAP() HierarchyBrowserRenderer::HierarchyBrowserRenderer(HierarchyBrowser *controller, CWnd* pParent /*=NULL*/) : RaisableDialog(HierarchyBrowserRenderer::IDD, pParent), mController(controller) { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::HierarchyBrowserRenderer()"); //{{AFX_DATA_INIT(HierarchyBrowserRenderer) //}}AFX_DATA_INIT setIcon(IDI_HIERARCHY); setPositionKey(Browsers::Hierarchy::POSITION); setRaiseCornerKey(Browsers::Hierarchy::RAISECORNER); mProgress.Create(Progressbar::IDD); } void HierarchyBrowserRenderer::DoDataExchange(CDataExchange* pDX) { RaisableDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(HierarchyBrowserRenderer) DDX_Control(pDX, IDC_OUTLINE_ICON, mOutlineIcon); DDX_Control(pDX, IDC_HIERARCHY, mHierarchyRenderer); //}}AFX_DATA_MAP } size_t HierarchyBrowserRenderer::getStyle() { return WS_CHILD | WS_VISIBLE | WS_GROUP | WS_TABSTOP | BS_BITMAP | BS_AUTOCHECKBOX; } BCMenu* HierarchyBrowserRenderer::getSubMenu(size_t pos) { return dynamic_cast<BCMenu*>(mPreviousHierarchies.GetMenu().GetSubMenu(pos)); } void HierarchyBrowserRenderer::setupHierarchyView() { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::setupHierarchyView()"); CSize size(22,23); CRect rect; GetWindowRect(rect); ScreenToClient(rect); rect.SetRect(CPoint(rect.right-size.cx, 0), CPoint(rect.right, size.cy)); rect.OffsetRect(-5, 0); mShowSupertypeHierarchy.Create(_T(""), getStyle(), rect, this, IDC_SUPERTYPE_HIERARCHY); mShowSupertypeHierarchy.SetBitmaps(IDB_SUPERTYPE_HIERARCHY_A, RGB(0,0,0), IDB_SUPERTYPE_HIERARCHY_F); mShowSupertypeHierarchy.SetTooltipText("Show the Supertype Hierarchy"); AddControl(IDC_SUPERTYPE_HIERARCHY,sizeRepos,sizeNone); rect.OffsetRect(-size.cx, 0); mShowSubtypeHierarchy.Create(_T(""),getStyle(), rect, this, IDC_SUBTYPE_HIERARCHY); mShowSubtypeHierarchy.SetBitmaps(IDB_SUBTYPE_HIERARCHY_A, RGB(0,0,0), IDB_SUBTYPE_HIERARCHY_F); mShowSubtypeHierarchy.SetTooltipText("Show the Subtype Hierarchy"); AddControl(IDC_SUBTYPE_HIERARCHY,sizeRepos,sizeNone); rect.OffsetRect(-size.cx, 0); mShowTypeHierarchy.Create(_T(""),getStyle(), rect, this, IDC_TYPE_HIERARCHY); mShowTypeHierarchy.SetBitmaps(IDB_TYPE_HIERARCHY_A, RGB(0,0,0), IDB_TYPE_HIERARCHY_F); mShowTypeHierarchy.SetTooltipText("Show the Type Hierarchy"); AddControl(IDC_TYPE_HIERARCHY,sizeRepos,sizeNone); size = CSize(40, size.cy); rect.OffsetRect(-size.cx, 0); rect.SetRect(rect.TopLeft(), CPoint(rect.TopLeft().x + size.cx , size.cy)); mPreviousHierarchies.Create(_T(""),WS_CHILD | WS_VISIBLE | WS_GROUP | WS_TABSTOP | BS_BITMAP, rect, this, IDC_PREVIOUS_HIERARCHIES); mPreviousHierarchies.SetBitmaps(IDB_PREVIOUS_HIERARCHIES_A, RGB(0,0,0), IDB_PREVIOUS_HIERARCHIES_F); mPreviousHierarchies.SetTooltipText("Previous Type Hierarchies"); AddControl(IDC_PREVIOUS_HIERARCHIES,sizeRepos,sizeNone); mPreviousHierarchies.SetMenu(IDR_PREVIOUS_HIERARCHIES_POPUPMENU, *this, true); mPreviousHierarchies.GetMenu().RemoveMenu(0, MF_BYPOSITION); BCMenu *popup = mPreviousHierarchies.GetMenu().AppendODPopupMenuA("Previous Type Hierarchies"); AddControl(IDC_HIERARCHY,sizeResize,sizeResize); mShowTypeHierarchy.SetCheck(true); getHierarchyPanel().SetImageList(&ESBImageList::instance(), TVSIL_NORMAL); getHierarchyPanel().ModifyStyle(0, TVS_SHOWSELALWAYS, 0); } void HierarchyBrowserRenderer::setupMemberView() { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::setupMemberView()"); int border = 2; CSize size(22,23); CRect hierarchyRect; getHierarchyPanel().GetWindowRect(&hierarchyRect); ScreenToClient(hierarchyRect); CRect rect(CPoint(hierarchyRect.right-size.cx, 0), CPoint(hierarchyRect.right, size.cy)); rect.OffsetRect(-border - (4/*buttons*/*size.cx + 29/*custom-filter*/), hierarchyRect.bottom+border); mShowInheritedMembers.Create(_T(""), getStyle(), rect, this, IDC_INHERITED_MEMBERS); mShowInheritedMembers.SetBitmaps(IDB_INHERITED_MEMBERS_A, RGB(0,0,0), IDB_INHERITED_MEMBERS_F); mShowInheritedMembers.SetTooltipText("Show All Inherited Members"); AddControl(IDC_INHERITED_MEMBERS,sizeRepos,sizeRepos); rect.OffsetRect(-size.cx, 0); mLockHierarchy.Create(_T(""), getStyle(), rect, this, IDC_LOCK_HIERARCHY); mLockHierarchy.SetBitmaps(IDB_LOCK_HIERARCHY_A, RGB(0,0,0), IDB_LOCK_HIERARCHY_F); mLockHierarchy.SetTooltipText("Lock View and Show Members in Hierarchy"); AddControl(IDC_LOCK_HIERARCHY,sizeRepos,sizeRepos); mLockHierarchy.SetWindowPos(&mShowInheritedMembers, 0,0,0,0, SWP_NOSIZE | SWP_NOMOVE); ///////member outline descriptor (icon & label) rect.OffsetRect(-size.cx, 0); GetDlgItem(IDC_OUTLINE_LABEL)->SetWindowPos(&mShowInheritedMembers, 25, rect.top, rect.right-25, rect.Height(), 0); AddControl(IDC_OUTLINE_LABEL, sizeResize, sizeRepos); int iconSize = 16; GetDlgItem(IDC_OUTLINE_ICON)->SetWindowPos(&mShowInheritedMembers, border, rect.top+((rect.Height()-iconSize)/2), border+iconSize, iconSize, 0); AddControl(IDC_OUTLINE_ICON, sizeNone, sizeRepos); ///////member outline view CWnd *outline = const_cast<CWnd*>(dynamic_cast<CWnd const*>(&getController().getOutlineRenderer())); outline->SetParent(this); CRect thisWnd; GetClientRect(&thisWnd); outline->SetWindowPos(&mLockHierarchy, 0, hierarchyRect.bottom+2, thisWnd.Width(), thisWnd.Height()-hierarchyRect.bottom-2, 0); AddControl(outline->GetDlgCtrlID(),sizeResize,sizeRepos); outline->ShowWindow(SW_SHOW); } void HierarchyBrowserRenderer::setOutlineDescriptor(const Inheritable &i) { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::setOutlineDescriptor()"); LabelBroker broker; GetDlgItem(IDC_OUTLINE_LABEL)->SetWindowText(FullQualifiedName(broker.getLabel(i)).name().c_str()); int icon = ESBImageList::instance().getIcon(i); mOutlineIcon.SetIcon(ESBImageList::instance().ExtractIcon(icon)); } BOOL HierarchyBrowserRenderer::OnInitDialog() { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::OnInitDialog()"); RaisableDialog::OnInitDialog(); AllowSizing(sizeResize,sizeResize); HideSizeIcon(); setupHierarchyView(); setupMemberView(); setFocusableWindow(&getHierarchyPanel()); return TRUE; } void HierarchyBrowserRenderer::render() { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::render()"); getHierarchyPanel().SetRedraw(false); getHierarchyPanel().DeleteAllItems(); mProgress.ShowWindow(SW_SHOW); render(getController().getHierarchyOf(NULL), TVI_ROOT); mProgress.ShowWindow(SW_HIDE); getHierarchyPanel().SetFocus(); getHierarchyPanel().SetRedraw(true); } void HierarchyBrowserRenderer::render(const std::list<smart_ptr<MetaObject> > &elements, HTREEITEM parent) { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::render(MetaObject, HTREEITEM)"); mProgress.mProgressbar.StepIt(); int pos = mProgress.mProgressbar.GetPos(); int lower, upper; mProgress.mProgressbar.GetRange(lower, upper); mProgress.mProgressbar.SetRange(lower, upper+elements.size()); mProgress.mProgressbar.SetStep(1); LabelBroker broker; typedef std::list<smart_ptr<MetaObject> > TagList; for(TagList::const_iterator element = elements.begin(); element != elements.end(); element++) { mProgress.SetWindowText(("Loading " + (*element)->getFQN().toString() + " Hierarchy").c_str()); HTREEITEM x = getHierarchyPanel().InsertItem(broker.getLabel(*(*element)).c_str(), parent); int icon = ESBImageList::instance().getIcon(**element); getHierarchyPanel().SetItemImage(x, icon, icon); getHierarchyPanel().SetItemData(x, (long)element->get()); int select = getController().getSelectionState(**element); if(select & 0x02) { icon = getSelectedIcon(**element); getHierarchyPanel().SetItemImage(x, icon, icon); } if(select & 0x01) { //setCaption(("Hierachy " + broker.getLabel(*(*element))).c_str()); getHierarchyPanel().SelectItem(x); } render(getController().getHierarchyOf(element->get()), x); getHierarchyPanel().Expand(x, TVE_EXPAND); mProgress.mProgressbar.StepIt(); } } void HierarchyBrowserRenderer::onShowTypeHierarchy() { const static string function("HierarchyBrowserRenderer::onShowTypeHierarchy()"); Tracer trc(NO_LABEL, RENDERER, function); try { if(emulateRadioButton(mShowTypeHierarchy, mShowSubtypeHierarchy, mShowSupertypeHierarchy)) { getController().hierarchyFilterChanged(eFullHierarchy); } } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::onShowSubtypeHierarchy() { const static string function("HierarchyBrowserRenderer::onShowSubtypeHierarchy()"); Tracer trc(NO_LABEL, RENDERER, function); try { if(emulateRadioButton(mShowSubtypeHierarchy, mShowTypeHierarchy, mShowSupertypeHierarchy)) { getController().hierarchyFilterChanged(eSubtypesOnly); } } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::onShowSupertypeHierarchy() { const static string function("HierarchyBrowserRenderer::onShowSupertypeHierarchy()"); Tracer trc(NO_LABEL, RENDERER, function); try { if(emulateRadioButton(mShowSupertypeHierarchy, mShowTypeHierarchy, mShowSubtypeHierarchy)) { getController().hierarchyFilterChanged(eSupertypesOnly); } } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::onFocusOn() { const static string function("HierarchyBrowserRenderer::onFocusOn()"); Tracer trc(NO_LABEL, RENDERER, function); try { getController().focusOn(getController().getSelection()); } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::onFocusOnX() { const static string function("HierarchyBrowserRenderer::onFocusOnX()"); Tracer trc(NO_LABEL, RENDERER, function); try { getController().focusOn(NULL); } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } int HierarchyBrowserRenderer::getSelectedIcon(const MetaObject &tag) { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::getSelectedIcon()"); IconDescriptor descriptor; const_cast<MetaObject&>(tag).acceptVisitor(&descriptor); descriptor.decorators.isSelected = true; return ESBImageList::instance().getIcon(descriptor); } void HierarchyBrowserRenderer::onLockHierarchy() { const static string function("HierarchyBrowserRenderer::onLockHierarchy()"); Tracer trc(NO_LABEL, RENDERER, function); try { bool isLocked = mLockHierarchy.GetCheck() == 1; HTREEITEM item = getHierarchyPanel().GetSelectedItem(); if(isLocked && item) { MetaObject *tag = TagRetriever(&getHierarchyPanel()).getTag(item); int icon = getSelectedIcon(*tag); getHierarchyPanel().SetItemImage(item, icon, icon); } getController().hierarchyLockChanged(isLocked); } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::onShowInheritedMembers() { const static string function("HierarchyBrowserRenderer::onShowInheritedMembers()"); Tracer trc(NO_LABEL, RENDERER, function); try { getController().memberFilterChanged(mShowInheritedMembers.GetCheck() == 1); } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } bool HierarchyBrowserRenderer::emulateRadioButton(CButtonST& check, CButtonST &uncheck1, CButtonST &uncheck2) { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::emulateRadioButton()"); uncheck1.SetCheck(false); uncheck2.SetCheck(false); if(check.GetCheck()) { return true; } else { check.SetCheck(true); return false; } } HierarchyViewType HierarchyBrowserRenderer::getSelectedHierachyType() { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::getSelectedHierachyType()"); if(mShowTypeHierarchy.GetCheck()) { return eFullHierarchy; }else if(mShowSupertypeHierarchy.GetCheck()) { return eSupertypesOnly; }else if(mShowSubtypeHierarchy.GetCheck()) { return eSubtypesOnly; } //this should never happen ! throw runtime_error("no hierarchy type selected ?!?!"); } void HierarchyBrowserRenderer::show() { ShowWindow(SW_SHOW); //getController().hierarchyFilterChanged(getSelectedHierachyType()); } MouseEvent HierarchyBrowserRenderer::makeMouseEvent(CWnd *wnd, NMHDR* pNMHDR) { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::makeMouseEvent()"); MSG msg; if(!PeekMessage(&msg, *this, WM_MOUSEFIRST , WM_MOUSELAST , PM_NOREMOVE)){ msg.wParam = 0; } MouseEvent::MouseButton button = MouseEvent::eLeftButton; size_t clickCount = 0; switch(pNMHDR->code) { case NM_CLICK: button = MouseEvent::eLeftButton; clickCount = 1; break; case NM_DBLCLK: button = MouseEvent::eLeftButton; clickCount = 2; break; case NM_RCLICK: button = MouseEvent::eRightButton; clickCount = 1; break; case NM_RDBLCLK: button = MouseEvent::eRightButton; clickCount = 2; break; } return MouseEvent(MouseEvent::eClicked, button | msg.wParam, wnd, GetMessagePos(), clickCount); } void HierarchyBrowserRenderer::onMouseClickedHierarchy(NMHDR* pNMHDR, LRESULT* pResult) { const static string function("HierarchyBrowserRenderer::onMouseClickedHierarchy()"); Tracer trc(NO_LABEL, RENDERER, function); try { *pResult = 0; mouseClicked(makeMouseEvent(&getHierarchyPanel(), pNMHDR)); } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::mouseClicked(const MouseEvent &e) { Tracer trc(NO_LABEL, RENDERER, "HierarchyBrowserRenderer::mouseClicked(MouseEvent)"); TagRetriever retriever(&getHierarchyPanel()); MetaObject *tag = retriever.getTagAt(e.getPoint(), true); getController().hierarchySelectionChanged(tag, e); if(e.getButton() == MouseEvent::eMiddleButton) { CMenu menu; menu.LoadMenu(IDR_HIERARCHY_BROWSER_POPUPMENU); CMenu* pPopup = menu.GetSubMenu(0); if(tag == NULL) { HTREEITEM ti = getHierarchyPanel().GetSelectedItem(); tag = reinterpret_cast<MetaObject*>(getHierarchyPanel().GetItemData(ti)); } LabelBroker broker; string label = "Focus on '" + broker.getLabel(*tag) + "'"; pPopup->ModifyMenu(ID_HIERARCHY_FOCUSON, 0, ID_HIERARCHY_FOCUSON, label.c_str()); pPopup->EnableMenuItem(ID_HIERARCHY_FOCUSONX, MF_GRAYED); pPopup->TrackPopupMenu(TPM_LEFTALIGN, e.getPoint().first, e.getPoint().second, this); } } void HierarchyBrowserRenderer::onExpandHierarchy(NMHDR* pNMHDR, LRESULT* pResult) { const static string function("HierarchyBrowserRenderer::onExpandHierarchy()"); Tracer trc(NO_LABEL, RENDERER, function); try { NM_TREEVIEW* tree = (NM_TREEVIEW*)pNMHDR; CPoint pos = /*tree->ptDrag;//*/GetMessagePos(); getHierarchyPanel().ScreenToClient(&pos); UINT flags; HTREEITEM htItem = getHierarchyPanel().HitTest(pos, &flags); //*pResult = flags & TVHT_ONITEMBUTTON ? 0 : 1/*no expand*/; *pResult = flags & TVHT_ONITEMICON || flags & TVHT_ONITEMLABEL ? 1 : 0; } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::onHistory(UINT id) { const static string function("HierarchyBrowserRenderer::onHistory()"); Tracer trc(NO_LABEL, RENDERER, function); try { getController().historyEntrySelectionChanged(id-FIRST_HISTORY_ENTRY); } catch(std::exception &e) { log(NO_LABEL, RENDERER, eError) << function << endl << e << endlog; } catch(...) { log(NO_LABEL, RENDERER, eError) << function << ": unknown exception occurred" << endlog; } } void HierarchyBrowserRenderer::setHistory(const std::list<smart_ptr<Inheritable> > &history) { const static string function("HierarchyBrowserRenderer::setHistory()"); Tracer trc(NO_LABEL, RENDERER, function); BCMenu *popup = dynamic_cast<BCMenu*>(mPreviousHierarchies.GetMenu().GetSubMenu(0)); for(size_t cnt = popup->GetMenuItemCount(); cnt > 0; --cnt) { popup->RemoveMenu(0, MF_BYPOSITION); } LabelBroker broker; typedef std::list<smart_ptr<Inheritable> > History; int i = 0; for(History::const_iterator x = history.begin(); x != history.end(); ++x, ++i) { int selected = getController().getSelectionState(**x); int icon = selected ? getSelectedIcon(**x) : ESBImageList::instance().getIcon(**x); popup->AppendMenu(MF_OWNERDRAW, FIRST_HISTORY_ENTRY+i, broker.getLabel(**x).c_str(), &ESBImageList::instance(), icon); } } void HierarchyBrowserRenderer::onGetToolInfo(NMHDR* pNMHDR, LRESULT* pResult) { const static string function("HierarchyBrowserRenderer::onGetToolInfo()"); Tracer trc(NO_LABEL, RENDERER, function); NMTVGETINFOTIP *pInfoTip = (NMTVGETINFOTIP*)pNMHDR; *pResult = 1; MetaObject *object = TagRetriever(&getHierarchyPanel()).getTag(pInfoTip->hItem); if(object && PropertiesManager::instance().getProperty(Browsers::SHOW_TOOLTIPS, "1") == "1") { static string hack; hack = object->getFQN().toString(); pInfoTip->pszText = (char*)hack.c_str(); *pResult = 0; } }
[ "david.koch@9online.fr" ]
david.koch@9online.fr
6f075ec27ba519c06b1b3f140cf891a5092d4683
fe6baf4e442ce54dd25772570c64badc44a4e7a7
/recount/recount/stdafx.cpp
a6dd74c5495294e74893bad5615f40e0c6567e0d
[]
no_license
abarankab/competitive-programming
aef5e1adf97824db88ed12056be3d6194db91a79
c1e23841aae4f18859dd23c4a34a5ed3c9662d4f
refs/heads/master
2020-07-31T15:58:18.385851
2019-09-25T17:07:01
2019-09-25T17:07:01
210,660,950
2
0
null
null
null
null
UTF-8
C++
false
false
286
cpp
// stdafx.cpp : source file that includes just the standard includes // recount.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "abarankab@gmail.com" ]
abarankab@gmail.com
81994571c4e6d3f5cdf1f2316735856e1aef36e5
178e012558af3d51145e633dacb8de169477c247
/Assignment2/framework/rasterizer.cpp
e7175a42c35a2d4f9401862542fc2c54764de4b0
[]
no_license
TaKeTube/GAMES-101
776058a8ee92f720f65291ec32e8dc5c7ded3fbe
3f3197abe5378c3c2b1ad6d756dbe4f2bbafde11
refs/heads/master
2023-03-24T06:29:30.474889
2021-03-26T18:52:34
2021-03-26T18:52:34
278,149,829
4
0
null
null
null
null
UTF-8
C++
false
false
11,815
cpp
// clang-format off // // Created by goksu on 4/6/19. // #include <algorithm> #include <vector> #include "rasterizer.hpp" #include <opencv2/opencv.hpp> #include <math.h> rst::pos_buf_id rst::rasterizer::load_positions(const std::vector<Eigen::Vector3f> &positions) { auto id = get_next_id(); pos_buf.emplace(id, positions); return {id}; } rst::ind_buf_id rst::rasterizer::load_indices(const std::vector<Eigen::Vector3i> &indices) { auto id = get_next_id(); ind_buf.emplace(id, indices); return {id}; } rst::col_buf_id rst::rasterizer::load_colors(const std::vector<Eigen::Vector3f> &cols) { auto id = get_next_id(); col_buf.emplace(id, cols); return {id}; } auto to_vec4(const Eigen::Vector3f& v3, float w = 1.0f) { return Vector4f(v3.x(), v3.y(), v3.z(), w); } /* static bool insideTriangle(int x, int y, const Vector3f* _v) { // TODO : Implement this function to check if the point (x, y) is inside the triangle represented by _v[0], _v[1], _v[2] float ab[2] = {_v[0].x()-_v[1].x(), _v[0].y()-_v[1].y()}; float bc[2] = {_v[1].x()-_v[2].x(), _v[1].y()-_v[2].y()}; float ca[2] = {_v[2].x()-_v[0].x(), _v[2].y()-_v[0].y()}; float ap[2] = {x-_v[1].x(), y-_v[1].y()}; float bp[2] = {x-_v[2].x(), y-_v[2].y()}; float cp[2] = {x-_v[0].x(), y-_v[0].y()}; float abxap = ab[0]*ap[1] - ab[1]*ap[0]; float bcxbp = bc[0]*bp[1] - bc[1]*bp[0]; float caxcp = ca[0]*cp[1] - ca[1]*cp[0]; if(((abxap<=0)&&(bcxbp<=0)&&(caxcp<=0))||((abxap>0)&&(bcxbp>0)&&(caxcp>0))){ // debug code //std::cout << _v[0].x() << ' ' << _v[0].y() << std::endl; //std::cout << _v[1].x() << ' ' << _v[1].y() << std::endl; //std::cout << _v[2].x() << ' ' << _v[2].y() << std::endl; //std::cout << x << ' ' << y << std::endl; return 1; }else{ return 0; } } */ static bool insideTriangle(float x, float y, const Vector3f* _v) { float ab[2] = {_v[0].x()-_v[1].x(), _v[0].y()-_v[1].y()}; float bc[2] = {_v[1].x()-_v[2].x(), _v[1].y()-_v[2].y()}; float ca[2] = {_v[2].x()-_v[0].x(), _v[2].y()-_v[0].y()}; float ap[2] = {x-_v[1].x(), y-_v[1].y()}; float bp[2] = {x-_v[2].x(), y-_v[2].y()}; float cp[2] = {x-_v[0].x(), y-_v[0].y()}; float abxap = ab[0]*ap[1] - ab[1]*ap[0]; float bcxbp = bc[0]*bp[1] - bc[1]*bp[0]; float caxcp = ca[0]*cp[1] - ca[1]*cp[0]; if(((abxap<=0)&&(bcxbp<=0)&&(caxcp<=0))||((abxap>0)&&(bcxbp>0)&&(caxcp>0))){ return 1; }else{ return 0; } } static std::tuple<float, float, float> computeBarycentric2D(float x, float y, const Vector3f* v) { float c1 = (x*(v[1].y() - v[2].y()) + (v[2].x() - v[1].x())*y + v[1].x()*v[2].y() - v[2].x()*v[1].y()) / (v[0].x()*(v[1].y() - v[2].y()) + (v[2].x() - v[1].x())*v[0].y() + v[1].x()*v[2].y() - v[2].x()*v[1].y()); float c2 = (x*(v[2].y() - v[0].y()) + (v[0].x() - v[2].x())*y + v[2].x()*v[0].y() - v[0].x()*v[2].y()) / (v[1].x()*(v[2].y() - v[0].y()) + (v[0].x() - v[2].x())*v[1].y() + v[2].x()*v[0].y() - v[0].x()*v[2].y()); float c3 = (x*(v[0].y() - v[1].y()) + (v[1].x() - v[0].x())*y + v[0].x()*v[1].y() - v[1].x()*v[0].y()) / (v[2].x()*(v[0].y() - v[1].y()) + (v[1].x() - v[0].x())*v[2].y() + v[0].x()*v[1].y() - v[1].x()*v[0].y()); return {c1,c2,c3}; } void rst::rasterizer::draw(pos_buf_id pos_buffer, ind_buf_id ind_buffer, col_buf_id col_buffer, Primitive type) { auto& buf = pos_buf[pos_buffer.pos_id]; auto& ind = ind_buf[ind_buffer.ind_id]; auto& col = col_buf[col_buffer.col_id]; float f1 = (50 - 0.1) / 2.0; float f2 = (50 + 0.1) / 2.0; Eigen::Matrix4f mvp = projection * view * model; for (auto& i : ind) { Triangle t; Eigen::Vector4f v[] = { mvp * to_vec4(buf[i[0]], 1.0f), mvp * to_vec4(buf[i[1]], 1.0f), mvp * to_vec4(buf[i[2]], 1.0f) }; //Homogeneous division for (auto& vec : v) { vec /= vec.w(); } //Viewport transformation for (auto & vert : v) { vert.x() = 0.5*width*(vert.x()+1.0); vert.y() = 0.5*height*(vert.y()+1.0); vert.z() = vert.z() * f1 + f2; } for (int i = 0; i < 3; ++i) { t.setVertex(i, v[i].head<3>()); t.setVertex(i, v[i].head<3>()); t.setVertex(i, v[i].head<3>()); } auto col_x = col[i[0]]; auto col_y = col[i[1]]; auto col_z = col[i[2]]; t.setColor(0, col_x[0], col_x[1], col_x[2]); t.setColor(1, col_y[0], col_y[1], col_y[2]); t.setColor(2, col_z[0], col_z[1], col_z[2]); rasterize_triangle(t); } } //Screen space rasterization void rst::rasterizer::rasterize_triangle(const Triangle& t) { auto v = t.toVector4(); // TODO : Find out the bounding box of current triangle. // iterate through the pixel and find if the current pixel is inside the triangle int y_max = std::min((int)ceil(std::max(std::max(v[0].y(),v[1].y()),v[2].y())), height); int y_min = std::max((int)floor(std::min(std::min(v[0].y(),v[1].y()),v[2].y())), 0); int x_max = std::min((int)ceil(std::max(std::max(v[0].x(),v[1].x()),v[2].x())), width); int x_min = std::max((int)floor(std::min(std::min(v[0].x(),v[1].x()),v[2].x())), 0); /* test for the insideTriangle() function Eigen::Vector3f t1 = {0, 0, 0}; Eigen::Vector3f t2 = {2, 0, 0}; Eigen::Vector3f t3 = {0, 2, 0}; Eigen::Vector3f test[3] = {t1, t2, t3}; std::cout<< insideTriangle(0.5, 1, test) <<std::endl; std::cout<< insideTriangle(2, 1, test) <<std::endl; std::cout<< insideTriangle(-2, 1, test) <<std::endl; std::cout<< insideTriangle(1, -1, test) <<std::endl; */ if(SSAA){ // super sample anti-aliasing int flag; for(int x = x_min; x <= x_max; x++){ for(int y = y_min; y <= y_max; y++){ flag = 0; int ind_a = (height*2-1-y*2)*width*2 + x*2; int ind_b = (height*2-1-y*2)*width*2 + x*2 + 1; int ind_c = (height*2-2-y*2)*width*2 + x*2; int ind_d = (height*2-2-y*2)*width*2 + x*2 + 1; if(insideTriangle((float)x, (float)y, t.v)){ auto[alpha, beta, gamma] = computeBarycentric2D(x, y, t.v); float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w()); float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w(); z_interpolated *= w_reciprocal; if(sample_depth_buf[ind_a] > z_interpolated){ flag = 1; sample_frame_buf[ind_a] = t.getColor(); sample_depth_buf[ind_a] = z_interpolated; } } if(insideTriangle((float)x+0.5, (float)y, t.v)){ auto[alpha, beta, gamma] = computeBarycentric2D(x+0.5, y, t.v); float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w()); float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w(); z_interpolated *= w_reciprocal; if(sample_depth_buf[ind_b] > z_interpolated){ flag = 1; sample_frame_buf[ind_b] = t.getColor(); sample_depth_buf[ind_b] = z_interpolated; } } if(insideTriangle((float)x, (float)y+0.5, t.v)){ auto[alpha, beta, gamma] = computeBarycentric2D(x, y+0.5, t.v); float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w()); float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w(); z_interpolated *= w_reciprocal; if(sample_depth_buf[ind_c] > z_interpolated){ flag = 1; sample_frame_buf[ind_c] = t.getColor(); sample_depth_buf[ind_c] = z_interpolated; } } if(insideTriangle((float)x+0.5, (float)y+0.5, t.v)){ auto[alpha, beta, gamma] = computeBarycentric2D(x+0.5, y+0.5, t.v); float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w()); float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w(); z_interpolated *= w_reciprocal; if(sample_depth_buf[ind_d] > z_interpolated){ flag = 1; sample_frame_buf[ind_d] = t.getColor(); sample_depth_buf[ind_d] = z_interpolated; } } if(flag){ int ind = get_index(x,y); frame_buf[ind] = (sample_frame_buf[ind_a]+sample_frame_buf[ind_b]+sample_frame_buf[ind_c]+sample_frame_buf[ind_d])*0.25; } } } }else{ for(int x = x_min; x <= x_max; x++){ for(int y = y_min; y <= y_max; y++){ if(insideTriangle(x, y, t.v)){ // If so, use the following code to get the interpolated z value. //std::cout << x << y << std::endl; auto[alpha, beta, gamma] = computeBarycentric2D(x, y, t.v); float w_reciprocal = 1.0/(alpha / v[0].w() + beta / v[1].w() + gamma / v[2].w()); float z_interpolated = alpha * v[0].z() / v[0].w() + beta * v[1].z() / v[1].w() + gamma * v[2].z() / v[2].w(); z_interpolated *= w_reciprocal; // TODO : set the current pixel (use the set_pixel function) to the color of the triangle (use getColor function) if it should be painted. int ind = get_index(x,y); if(depth_buf[ind] > z_interpolated){ frame_buf[ind] = t.getColor(); depth_buf[ind] = z_interpolated; } } } } } } void rst::rasterizer::set_model(const Eigen::Matrix4f& m) { model = m; } void rst::rasterizer::set_view(const Eigen::Matrix4f& v) { view = v; } void rst::rasterizer::set_projection(const Eigen::Matrix4f& p) { projection = p; } void rst::rasterizer::set_SSAA(int condition){ SSAA = condition; } void rst::rasterizer::clear(rst::Buffers buff) { if ((buff & rst::Buffers::Color) == rst::Buffers::Color) { std::fill(frame_buf.begin(), frame_buf.end(), Eigen::Vector3f{0, 0, 0}); } if ((buff & rst::Buffers::Depth) == rst::Buffers::Depth) { if(SSAA){ std::fill(sample_depth_buf.begin(), sample_depth_buf.end(), std::numeric_limits<float>::infinity()); }else{ std::fill(depth_buf.begin(), depth_buf.end(), std::numeric_limits<float>::infinity()); } } } rst::rasterizer::rasterizer(int w, int h) : width(w), height(h) { frame_buf.resize(w * h); depth_buf.resize(w * h); sample_frame_buf.resize(4 * w * h); sample_depth_buf.resize(4 * w * h); } int rst::rasterizer::get_index(int x, int y) { return (height-1-y)*width + x; } void rst::rasterizer::set_pixel(const Eigen::Vector3f& point, const Eigen::Vector3f& color) { //old index: auto ind = point.y() + point.x() * width; auto ind = (height-1-point.y())*width + point.x(); frame_buf[ind] = color; } // clang-format on
[ "jamie.zimu.guan@gmail.com" ]
jamie.zimu.guan@gmail.com
2f1b7ba30c036ec29efd8041d472b1e4f5e19b83
7e62f0928681aaaecae7daf360bdd9166299b000
/external/DirectXShaderCompiler/external/SPIRV-Tools/test/test_fixture.h
d26ac053cd27ea8acfc16ede7518769ca70ec691
[ "NCSA", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
yuri410/rpg
949b001bd0aec47e2a046421da0ff2a1db62ce34
266282ed8cfc7cd82e8c853f6f01706903c24628
refs/heads/master
2020-08-03T09:39:42.253100
2020-06-16T15:38:03
2020-06-16T15:38:03
211,698,323
0
0
null
null
null
null
UTF-8
C++
false
false
6,896
h
// Copyright (c) 2015-2016 The Khronos Group Inc. // // 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. #ifndef TEST_TEST_FIXTURE_H_ #define TEST_TEST_FIXTURE_H_ #include <string> #include <vector> #include "test/unit_spirv.h" namespace spvtest { // RAII for spv_context. struct ScopedContext { ScopedContext(spv_target_env env = SPV_ENV_UNIVERSAL_1_0) : context(spvContextCreate(env)) {} ~ScopedContext() { spvContextDestroy(context); } spv_context context; }; // Common setup for TextToBinary tests. SetText() should be called to populate // the actual test text. template <typename T> class TextToBinaryTestBase : public T { public: // Shorthand for SPIR-V compilation result. using SpirvVector = std::vector<uint32_t>; // Offset into a SpirvVector at which the first instruction starts. static const SpirvVector::size_type kFirstInstruction = 5; TextToBinaryTestBase() : diagnostic(nullptr), text(), binary(nullptr) { char textStr[] = "substitute the text member variable with your test"; text = {textStr, strlen(textStr)}; } virtual ~TextToBinaryTestBase() { DestroyBinary(); if (diagnostic) spvDiagnosticDestroy(diagnostic); } // Returns subvector v[from:end). SpirvVector Subvector(const SpirvVector& v, SpirvVector::size_type from) { assert(from <= v.size()); return SpirvVector(v.begin() + from, v.end()); } // Compiles SPIR-V text in the given assembly syntax format, asserting // compilation success. Returns the compiled code. SpirvVector CompileSuccessfully(const std::string& txt, spv_target_env env = SPV_ENV_UNIVERSAL_1_0) { DestroyBinary(); DestroyDiagnostic(); spv_result_t status = spvTextToBinary(ScopedContext(env).context, txt.c_str(), txt.size(), &binary, &diagnostic); EXPECT_EQ(SPV_SUCCESS, status) << txt; SpirvVector code_copy; if (status == SPV_SUCCESS) { code_copy = SpirvVector(binary->code, binary->code + binary->wordCount); DestroyBinary(); } else { spvDiagnosticPrint(diagnostic); } return code_copy; } // Compiles SPIR-V text with the given format, asserting compilation failure. // Returns the error message(s). std::string CompileFailure(const std::string& txt, spv_target_env env = SPV_ENV_UNIVERSAL_1_0) { DestroyBinary(); DestroyDiagnostic(); EXPECT_NE(SPV_SUCCESS, spvTextToBinary(ScopedContext(env).context, txt.c_str(), txt.size(), &binary, &diagnostic)) << txt; DestroyBinary(); return diagnostic->error; } // Encodes SPIR-V text into binary and then decodes the binary using // given options. Returns the decoded text. std::string EncodeAndDecodeSuccessfully( const std::string& txt, uint32_t disassemble_options = SPV_BINARY_TO_TEXT_OPTION_NONE, spv_target_env env = SPV_ENV_UNIVERSAL_1_0) { DestroyBinary(); DestroyDiagnostic(); ScopedContext context(env); disassemble_options |= SPV_BINARY_TO_TEXT_OPTION_NO_HEADER; spv_result_t error = spvTextToBinary(context.context, txt.c_str(), txt.size(), &binary, &diagnostic); if (error) { spvDiagnosticPrint(diagnostic); spvDiagnosticDestroy(diagnostic); } EXPECT_EQ(SPV_SUCCESS, error); if (!binary) return ""; spv_text decoded_text; error = spvBinaryToText(context.context, binary->code, binary->wordCount, disassemble_options, &decoded_text, &diagnostic); if (error) { spvDiagnosticPrint(diagnostic); spvDiagnosticDestroy(diagnostic); } EXPECT_EQ(SPV_SUCCESS, error) << txt; const std::string decoded_string = decoded_text->str; spvTextDestroy(decoded_text); return decoded_string; } // Encodes SPIR-V text into binary. This is expected to succeed. // The given words are then appended to the binary, and the result // is then decoded. This is expected to fail. // Returns the error message. std::string EncodeSuccessfullyDecodeFailed( const std::string& txt, const SpirvVector& words_to_append) { DestroyBinary(); DestroyDiagnostic(); SpirvVector code = spvtest::Concatenate({CompileSuccessfully(txt), words_to_append}); spv_text decoded_text; EXPECT_NE(SPV_SUCCESS, spvBinaryToText(ScopedContext().context, code.data(), code.size(), SPV_BINARY_TO_TEXT_OPTION_NONE, &decoded_text, &diagnostic)); if (diagnostic) { std::string error_message = diagnostic->error; spvDiagnosticDestroy(diagnostic); diagnostic = nullptr; return error_message; } return ""; } // Compiles SPIR-V text, asserts success, and returns the words representing // the instructions. In particular, skip the words in the SPIR-V header. SpirvVector CompiledInstructions(const std::string& txt, spv_target_env env = SPV_ENV_UNIVERSAL_1_0) { const SpirvVector code = CompileSuccessfully(txt, env); SpirvVector result; // Extract just the instructions. // If the code fails to compile, then return the empty vector. // In any case, don't crash or invoke undefined behaviour. if (code.size() >= kFirstInstruction) result = Subvector(code, kFirstInstruction); return result; } void SetText(const std::string& code) { textString = code; text.str = textString.c_str(); text.length = textString.size(); } // Destroys the binary, if it exists. void DestroyBinary() { spvBinaryDestroy(binary); binary = nullptr; } // Destroys the diagnostic, if it exists. void DestroyDiagnostic() { spvDiagnosticDestroy(diagnostic); diagnostic = nullptr; } spv_diagnostic diagnostic; std::string textString; spv_text_t text; spv_binary binary; }; using TextToBinaryTest = TextToBinaryTestBase<::testing::Test>; } // namespace spvtest using RoundTripTest = spvtest::TextToBinaryTestBase<::testing::TestWithParam<std::string>>; #endif // TEST_TEST_FIXTURE_H_
[ "yuri410@users.noreply.github.com" ]
yuri410@users.noreply.github.com
7516128ba3af07caf113e7dda5a012acae8e07c0
a80baeb35fe6af3955d7f919670e525159c53682
/src/game/Tactical/UI_Cursors.cc
dac5e9d29eb88793472b353ffec5cf4bc0c94501
[]
no_license
hb029/JA-2-Stracciatella
6a1fcbfa27c20483f1e589569620c3cf863ddebd
6032a92164807419e2d8f49032bda8f1f67f8799
refs/heads/master
2022-12-10T10:01:14.869697
2022-12-04T03:36:47
2022-12-04T03:36:47
4,460,383
2
0
null
2022-06-17T01:32:30
2012-05-27T06:58:10
C++
UTF-8
C++
false
false
35,014
cc
#include "Handle_Items.h" #include "Items.h" #include "Soldier_Find.h" #include "Structure.h" #include "TileDef.h" #include "Timer_Control.h" #include "Weapons.h" #include "Soldier_Control.h" #include "Overhead.h" #include "Handle_UI.h" #include "Animation_Control.h" #include "Points.h" #include "Sound_Control.h" #include "Isometric_Utils.h" #include "Animation_Data.h" #include "UI_Cursors.h" #include "LOS.h" #include "Interface.h" #include "Cursors.h" #include "Cursor_Control.h" #include "Structure_Wrap.h" #include "Physics.h" #include "Soldier_Macros.h" #include "Text.h" #include "Interactive_Tiles.h" #include "PathAI.h" #include "Debug.h" #include "ContentManager.h" #include "GameInstance.h" #include <string_theory/string> // FUNCTIONS FOR ITEM CURSOR HANDLING static UICursorID HandleActivatedTargetCursor( SOLDIERTYPE*, GridNo map_pos, BOOLEAN recalc); static UICursorID HandleNonActivatedTargetCursor(SOLDIERTYPE*, GridNo map_pos, BOOLEAN show_APs, BOOLEAN fRecalc, MouseMoveState); static UICursorID HandleKnifeCursor( SOLDIERTYPE*, GridNo map_pos, BOOLEAN activated, MouseMoveState); static UICursorID HandlePunchCursor( SOLDIERTYPE*, GridNo map_pos, BOOLEAN activated, MouseMoveState); static UICursorID HandleAidCursor( SOLDIERTYPE*, GridNo map_pos, BOOLEAN activated, MouseMoveState); static UICursorID HandleActivatedTossCursor(); static UICursorID HandleNonActivatedTossCursor( SOLDIERTYPE*, GridNo map_pos, BOOLEAN recalc, MouseMoveState, ItemCursor); static UICursorID HandleWirecutterCursor( SOLDIERTYPE*, GridNo map_pos, MouseMoveState); static UICursorID HandleRepairCursor( SOLDIERTYPE*, GridNo map_pos, MouseMoveState); static UICursorID HandleRefuelCursor( SOLDIERTYPE*, GridNo map_pos, MouseMoveState); static UICursorID HandleRemoteCursor( SOLDIERTYPE*, BOOLEAN activated, MouseMoveState); static UICursorID HandleBombCursor( SOLDIERTYPE*, GridNo map_pos, BOOLEAN activated, MouseMoveState); static UICursorID HandleJarCursor( SOLDIERTYPE*, GridNo map_pos, MouseMoveState); static UICursorID HandleTinCanCursor( SOLDIERTYPE*, GridNo map_pos, MouseMoveState); static BOOLEAN gfCannotGetThrough = FALSE; static BOOLEAN gfDisplayFullCountRing = FALSE; BOOLEAN GetMouseRecalcAndShowAPFlags(MouseMoveState* const puiCursorFlags, BOOLEAN* const pfShowAPs) { static bool do_new_tile = false; // Set flags for certain mouse movements MouseMoveState const cursor_flags = GetCursorMovementFlags(); bool recalc = false; // Force if we are currently cycling guys if (gfUIForceReExamineCursorData) { do_new_tile = true; recalc = true; gfUIForceReExamineCursorData = FALSE; } bool show_APs = false; if (cursor_flags != MOUSE_STATIONARY) { // If cursor was previously stationary, make the additional check of grid // pos change RESETCOUNTER(PATHFINDCOUNTER); do_new_tile = true; } else if (COUNTERDONE(PATHFINDCOUNTER)) // Only dipslay aps after a delay { // Don't reset counter: One when we move again do we do this! show_APs = true; if (do_new_tile) { do_new_tile = false; recalc = true; } } if (puiCursorFlags) *puiCursorFlags = cursor_flags; if (pfShowAPs) *pfShowAPs = show_APs; return recalc; } // Functions for cursor determination UICursorID GetProperItemCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const activated) { MouseMoveState cursor_flags; BOOLEAN show_APs; BOOLEAN const recalc = GetMouseRecalcAndShowAPFlags(&cursor_flags, &show_APs); // ATE: Update attacking weapon! // CC has added this attackingWeapon stuff and I need to update it constantly // for CTGH algorithms if (gTacticalStatus.ubAttackBusyCount == 0) { UINT16 const in_hand = s->inv[HANDPOS].usItem; if (GCM->getItem(in_hand)->isWeapon()) s->usAttackingWeapon = in_hand; } UICursorID cursor = NO_UICURSOR; SOLDIERTYPE const* const tgt = gUIFullTarget; GridNo const tgt_grid_no = tgt ? tgt->sGridNo : map_pos; ItemCursor const item_cursor = GetActionModeCursor(s); switch (item_cursor) { case TARGETCURS: cursor = activated ? HandleActivatedTargetCursor(s, tgt_grid_no, recalc) : HandleNonActivatedTargetCursor(s, tgt_grid_no, show_APs, recalc, cursor_flags); if (gCurrentUIMode == ACTION_MODE && gTacticalStatus.uiFlags & INCOMBAT && recalc && tgt && IsValidTargetMerc(tgt) && EnoughAmmo(s, FALSE, HANDPOS) && // ATE: Check for ammo guiUIFullTargetFlags & ENEMY_MERC && // IF it's an ememy, goto confirm action mode guiUIFullTargetFlags & VISIBLE_MERC && !(guiUIFullTargetFlags & DEAD_MERC) && !gfCannotGetThrough) { guiPendingOverrideEvent = A_CHANGE_TO_CONFIM_ACTION; } break; case TOSSCURS: case TRAJECTORYCURS: cursor = activated && gfUIHandlePhysicsTrajectory ? HandleActivatedTossCursor() : HandleNonActivatedTossCursor(s, tgt_grid_no, recalc, cursor_flags, item_cursor); break; case PUNCHCURS: cursor = HandlePunchCursor( s, tgt_grid_no, activated, cursor_flags); break; case KNIFECURS: cursor = HandleKnifeCursor( s, tgt_grid_no, activated, cursor_flags); break; case AIDCURS: cursor = HandleAidCursor( s, map_pos, activated, cursor_flags); break; case BOMBCURS: cursor = HandleBombCursor( s, tgt_grid_no, activated, cursor_flags); break; case REMOTECURS: cursor = HandleRemoteCursor( s, activated, cursor_flags); break; case WIRECUTCURS: cursor = HandleWirecutterCursor(s, tgt_grid_no, cursor_flags); break; case REPAIRCURS: cursor = HandleRepairCursor( s, tgt_grid_no, cursor_flags); break; case JARCURS: cursor = HandleJarCursor( s, tgt_grid_no, cursor_flags); break; case TINCANCURS: cursor = HandleTinCanCursor( s, tgt_grid_no, cursor_flags); break; case REFUELCURS: cursor = HandleRefuelCursor( s, tgt_grid_no, cursor_flags); break; case INVALIDCURS: cursor = INVALID_ACTION_UICURSOR; break; default: break; } return cursor; } static void DetermineCursorBodyLocation(SOLDIERTYPE*, BOOLEAN fDisplay, BOOLEAN fRecalc); static UICursorID HandleActivatedTargetCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const recalc) { bool const is_throwing_knife = GCM->getItem(s->inv[HANDPOS].usItem)->getItemClass() == IC_THROWING_KNIFE; if (is_throwing_knife) { // If we are in realtime, follow! if (!(gTacticalStatus.uiFlags & INCOMBAT) && gAnimControl[s->usAnimState].uiFlags & ANIM_STATIONARY && gUITargetShotWaiting) { guiPendingOverrideEvent = CA_MERC_SHOOT; } } // Determine where we are shooting/aiming DetermineCursorBodyLocation(s, TRUE, TRUE); bool enough_points = true; bool max_point_limit_hit = false; if (gTacticalStatus.uiFlags & INCOMBAT) { gsCurrentActionPoints = CalcTotalAPsToAttack(s, map_pos, TRUE, s->bShownAimTime / 2); gfUIDisplayActionPoints = TRUE; gfUIDisplayActionPointsCenter = TRUE; // If we don't have any points and we are at the first refine, do nothing but warn! if (!EnoughPoints(s, gsCurrentActionPoints, 0 , FALSE)) { gfUIDisplayActionPointsInvalid = TRUE; max_point_limit_hit = true; } else { UINT8 const future_aim = s->bShownAimTime + 2; if (future_aim <= REFINE_AIM_5) { INT16 const AP_costs = MinAPsToAttack(s, map_pos, TRUE) + future_aim / 2; if (!EnoughPoints(s, AP_costs, 0, FALSE)) { enough_points = false; } } } } if (!(gTacticalStatus.uiFlags & INCOMBAT) && COUNTERDONE(TARGETREFINE)) { RESETCOUNTER(TARGETREFINE); if (s->bDoBurst) { s->bShownAimTime = REFINE_AIM_BURST; } else { ++s->bShownAimTime; if (s->bShownAimTime > REFINE_AIM_5) { s->bShownAimTime = REFINE_AIM_5; } else if (s->bShownAimTime % 2 != 0) { PlayJA2Sample(TARG_REFINE_BEEP, MIDVOLUME, 1, MIDDLEPAN); } } } if (recalc) { SOLDIERTYPE const* const tgt = gUIFullTarget; UINT8 const chance = tgt ? SoldierToSoldierBodyPartChanceToGetThrough(s, tgt, s->bAimShotLocation) : SoldierToLocationChanceToGetThrough(s, map_pos, gsInterfaceLevel, s->bTargetCubeLevel, 0); gfCannotGetThrough = chance < OK_CHANCE_TO_GET_THROUGH; } UICursorID cursor = NO_UICURSOR; if (max_point_limit_hit) { // Check if we're in burst mode! cursor = s->bDoBurst ? ACTION_TARGETREDBURST_UICURSOR : is_throwing_knife ? RED_THROW_UICURSOR : ACTION_TARGETRED_UICURSOR; } else if (s->bDoBurst) { cursor = s->fDoSpread ? ACTION_TARGETREDBURST_UICURSOR : ACTION_TARGETCONFIRMBURST_UICURSOR; } else { switch (s->bShownAimTime) { case REFINE_AIM_1: if (is_throwing_knife) { cursor = gfDisplayFullCountRing ? ACTION_THROWAIMYELLOW1_UICURSOR : enough_points ? ACTION_THROWAIM1_UICURSOR : ACTION_THROWAIMCANT1_UICURSOR; } else { cursor = gfDisplayFullCountRing ? ACTION_TARGETAIMYELLOW1_UICURSOR : enough_points ? ACTION_TARGETAIM1_UICURSOR : ACTION_TARGETAIMCANT1_UICURSOR; } break; case REFINE_AIM_2: if (is_throwing_knife) { cursor = gfDisplayFullCountRing ? ACTION_THROWAIMYELLOW2_UICURSOR : enough_points ? ACTION_THROWAIM3_UICURSOR : ACTION_THROWAIMCANT2_UICURSOR; } else { cursor = gfDisplayFullCountRing ? ACTION_TARGETAIMYELLOW2_UICURSOR : enough_points ? ACTION_TARGETAIM3_UICURSOR : ACTION_TARGETAIMCANT2_UICURSOR; } break; case REFINE_AIM_3: if (is_throwing_knife) { cursor = gfDisplayFullCountRing ? ACTION_THROWAIMYELLOW3_UICURSOR : enough_points ? ACTION_THROWAIM5_UICURSOR : ACTION_THROWAIMCANT3_UICURSOR; } else { cursor = gfDisplayFullCountRing ? ACTION_TARGETAIMYELLOW3_UICURSOR : enough_points ? ACTION_TARGETAIM5_UICURSOR : ACTION_TARGETAIMCANT3_UICURSOR; } break; case REFINE_AIM_4: if (is_throwing_knife) { cursor = gfDisplayFullCountRing ? ACTION_THROWAIMYELLOW4_UICURSOR : enough_points ? ACTION_THROWAIM7_UICURSOR : ACTION_THROWAIMCANT4_UICURSOR; } else { cursor = gfDisplayFullCountRing ? ACTION_TARGETAIMYELLOW4_UICURSOR : enough_points ? ACTION_TARGETAIM7_UICURSOR : ACTION_TARGETAIMCANT4_UICURSOR; } break; case REFINE_AIM_5: if (is_throwing_knife) { cursor = gfDisplayFullCountRing ? ACTION_THROWAIMFULL_UICURSOR : enough_points ? ACTION_THROWAIM9_UICURSOR : ACTION_THROWAIMCANT5_UICURSOR; } else { cursor = gfDisplayFullCountRing ? ACTION_TARGETAIMFULL_UICURSOR : enough_points ? ACTION_TARGETAIM9_UICURSOR : ACTION_TARGETAIMCANT5_UICURSOR; } break; case REFINE_AIM_MID1: cursor = ACTION_TARGETAIM2_UICURSOR; break; case REFINE_AIM_MID2: cursor = ACTION_TARGETAIM4_UICURSOR; break; case REFINE_AIM_MID3: cursor = ACTION_TARGETAIM6_UICURSOR; break; case REFINE_AIM_MID4: cursor = ACTION_TARGETAIM8_UICURSOR; break; } } if (!max_point_limit_hit) { UINT16 const free_cursor_name = gUICursors[cursor].usFreeCursorName; RemoveCursorFlags(free_cursor_name, CURSOR_TO_FLASH | CURSOR_TO_PLAY_SOUND); if (gfCannotGetThrough) { SetCursorSpecialFrame(free_cursor_name, 1); } else if (!InRange(s, map_pos)) { // OK, make buddy flash! SetCursorFlags(free_cursor_name, CURSOR_TO_FLASH | CURSOR_TO_PLAY_SOUND); } else { SetCursorSpecialFrame(free_cursor_name, 0); } } return cursor; } static UICursorID HandleNonActivatedTargetCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const show_APs, BOOLEAN const fRecalc, MouseMoveState const uiCursorFlags) { bool const is_throwing_knife = GCM->getItem(s->inv[HANDPOS].usItem)->getItemClass() == IC_THROWING_KNIFE; if (!is_throwing_knife) { if (!(gTacticalStatus.uiFlags & INCOMBAT)) { DetermineCursorBodyLocation(GetSelectedMan(), show_APs, fRecalc); } if (!EnoughAmmo(s, FALSE, HANDPOS)) { // Check if ANY ammo exists if (FindAmmoToReload(s, HANDPOS, NO_SLOT) == NO_SLOT) return BAD_RELOAD_UICURSOR; gsCurrentActionPoints = GetAPsToAutoReload(s); gfUIDisplayActionPoints = TRUE; return GOOD_RELOAD_UICURSOR; } } if (gTacticalStatus.uiFlags & INCOMBAT) { DetermineCursorBodyLocation(GetSelectedMan(), show_APs, fRecalc); gsCurrentActionPoints = CalcTotalAPsToAttack(s, map_pos, TRUE, s->bShownAimTime / 2); gfUIDisplayActionPoints = TRUE; gfUIDisplayActionPointsCenter = TRUE; if (!show_APs) { gfUIDisplayActionPoints = FALSE; } else if (!EnoughPoints(s, gsCurrentActionPoints, 0 , FALSE)) { gfUIDisplayActionPointsInvalid = TRUE; } } if (fRecalc) { gfCannotGetThrough = SoldierToLocationChanceToGetThrough(s, map_pos, gsInterfaceLevel, s->bTargetCubeLevel, 0) < OK_CHANCE_TO_GET_THROUGH; } // If we begin to move, reset the cursor if (uiCursorFlags != MOUSE_STATIONARY) gfCannotGetThrough = FALSE; if (gfCannotGetThrough) { return s->bDoBurst ? ACTION_NOCHANCE_BURST_UICURSOR : is_throwing_knife ? BAD_THROW_UICURSOR : ACTION_NOCHANCE_SHOOT_UICURSOR; } else if (!InRange(s, map_pos)) { // Flash cursor! return s->bDoBurst ? ACTION_FLASH_BURST_UICURSOR : is_throwing_knife ? FLASH_THROW_UICURSOR : ACTION_FLASH_SHOOT_UICURSOR; } else { return s->bDoBurst ? ACTION_TARGETBURST_UICURSOR : is_throwing_knife ? GOOD_THROW_UICURSOR : ACTION_SHOOT_UICURSOR; } } static void DetermineCursorBodyLocation(SOLDIERTYPE* const s, BOOLEAN const display, BOOLEAN const recalc) { if (gTacticalStatus.ubAttackBusyCount > 0) { // ATE: Return if attacker busy count > 0, this helps in RT with re-setting // the flag to random return; } if (recalc) { // Always set aim location to nothing s->bAimShotLocation = AIM_SHOT_RANDOM; GridNo const map_pos = GetMouseMapPos(); if (map_pos == NOWHERE) return; SOLDIERTYPE* tgt = 0; UINT16 flags; // Determine which body part it's on for (LEVELNODE* n = gpWorldLevelData[map_pos].pMercHead; n; n = n->pNext) { if (!(n->uiFlags & LEVELNODE_MERCPLACEHOLDER)) continue; SOLDIERTYPE* const potential_tgt = n->pSoldier; if (!potential_tgt) continue; // ATE: Check their stance - if prone - return! if (gAnimControl[potential_tgt->usAnimState].ubHeight == ANIM_PRONE) { return; } // Check if we have a half tile profile flags = n->uiAnimHitLocationFlags; if (flags & (TILE_FLAG_NORTH_HALF | TILE_FLAG_SOUTH_HALF | TILE_FLAG_WEST_HALF | TILE_FLAG_EAST_HALF | TILE_FLAG_TOP_HALF | TILE_FLAG_BOTTOM_HALF)) { INT16 sCellX; INT16 sCellY; GetMouseWorldCoords(&sCellX, &sCellY); // We are only interested in the sub-tile coordinates sCellX %= CELL_X_SIZE; sCellY %= CELL_Y_SIZE; if (flags & TILE_FLAG_NORTH_HALF && sCellY > CELL_Y_SIZE / 2) continue; if (flags & TILE_FLAG_SOUTH_HALF && sCellY <= CELL_Y_SIZE / 2) continue; if (flags & TILE_FLAG_WEST_HALF && sCellX > CELL_X_SIZE / 2) continue; if (flags & TILE_FLAG_EAST_HALF && sCellX <= CELL_X_SIZE / 2) continue; if (flags & TILE_FLAG_TOP_HALF) { INT16 sScreenX; INT16 sScreenY; FromCellToScreenCoordinates(sCellX, sCellY, &sScreenX, &sScreenY); // Check for Below if (sScreenX > WORLD_TILE_Y / 2) continue; } if (flags & TILE_FLAG_BOTTOM_HALF) { INT16 sScreenX; INT16 sScreenY; FromCellToScreenCoordinates(sCellX, sCellY, &sScreenX, &sScreenY); // Check for Below if (sScreenX <= WORLD_TILE_Y / 2) continue; } } // Check if mouse is in bounding box of soldier if (!IsPointInSoldierBoundingBox(potential_tgt, gusMouseXPos, gusMouseYPos)) { continue; } tgt = potential_tgt; break; } if (!tgt) { // Check if we can find a soldier here SOLDIERTYPE* const potential_tgt = gUIFullTarget; if (potential_tgt) { flags = FindRelativeSoldierPosition(potential_tgt, gusMouseXPos, gusMouseYPos); if (flags != 0) tgt = potential_tgt; } } if (tgt && IsValidTargetMerc(tgt)) { if (flags & TILE_FLAG_FEET) s->bAimShotLocation = AIM_SHOT_LEGS; if (flags & TILE_FLAG_MID) s->bAimShotLocation = AIM_SHOT_TORSO; if (flags & TILE_FLAG_HEAD) s->bAimShotLocation = AIM_SHOT_HEAD; } } if (!display) return; if (s->bDoBurst) return; SOLDIERTYPE* const tgt = gUIFullTarget; if (!tgt) return; ST::string hit_location; if (tgt->ubBodyType == CROW) { s->bAimShotLocation = AIM_SHOT_LEGS; hit_location = TacticalStr[CROW_HIT_LOCATION_STR]; } else { if (!IS_MERC_BODY_TYPE(tgt)) return; switch (s->bAimShotLocation) { case AIM_SHOT_HEAD: hit_location = // If we have a knife in hand, change string GCM->getItem(s->inv[HANDPOS].usItem)->getItemClass() == IC_BLADE ? TacticalStr[NECK_HIT_LOCATION_STR] : TacticalStr[HEAD_HIT_LOCATION_STR]; break; case AIM_SHOT_TORSO: hit_location = TacticalStr[TORSO_HIT_LOCATION_STR]; break; case AIM_SHOT_LEGS: hit_location = TacticalStr[LEGS_HIT_LOCATION_STR]; break; default: return; } } SetHitLocationText(hit_location); } static UICursorID HandleKnifeCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const activated, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_MERCS); if (activated) { DetermineCursorBodyLocation(s, TRUE, TRUE); if (gfUIHandleShowMoveGrid) gfUIHandleShowMoveGrid = 2; // Calculate action points bool enough_points = true; if (gTacticalStatus.uiFlags & INCOMBAT) { gsCurrentActionPoints = CalcTotalAPsToAttack(s, map_pos, TRUE, s->bShownAimTime / 2); gfUIDisplayActionPoints = TRUE; gfUIDisplayActionPointsCenter = TRUE; // If we don't have any points and we are at the first refine, do nothing but warn! if (!EnoughPoints(s, gsCurrentActionPoints, 0, FALSE)) { gfUIDisplayActionPointsInvalid = TRUE; if (s->bShownAimTime == REFINE_KNIFE_1) return KNIFE_HIT_UICURSOR; } INT8 const future_aim = REFINE_KNIFE_2; INT16 const ap_costs = CalcTotalAPsToAttack(s, map_pos, TRUE, future_aim / 2); if (!EnoughPoints(s, ap_costs, 0, FALSE)) enough_points = false; } if (!(gTacticalStatus.uiFlags & INCOMBAT) && COUNTERDONE(NONGUNTARGETREFINE)) { RESETCOUNTER(NONGUNTARGETREFINE); if (s->bShownAimTime == REFINE_KNIFE_1) { PlayJA2Sample(TARG_REFINE_BEEP, MIDVOLUME, 1, MIDDLEPAN); } s->bShownAimTime = REFINE_KNIFE_2; } switch (s->bShownAimTime) { case REFINE_KNIFE_1: return gfDisplayFullCountRing ? KNIFE_YELLOW_AIM1_UICURSOR : enough_points ? KNIFE_HIT_AIM1_UICURSOR : KNIFE_NOGO_AIM1_UICURSOR; case REFINE_KNIFE_2: return gfDisplayFullCountRing ? KNIFE_YELLOW_AIM2_UICURSOR : enough_points ? KNIFE_HIT_AIM2_UICURSOR : KNIFE_NOGO_AIM2_UICURSOR; default: Assert(FALSE); // no return value! return NO_UICURSOR; } } else { gfUIDisplayActionPointsCenter = TRUE; // Check if we are on a guy (who's not selected)! if (gUIFullTarget && !(guiUIFullTargetFlags & SELECTED_MERC)) { DetermineCursorBodyLocation(s, TRUE, TRUE); return KNIFE_HIT_UICURSOR; } else { return KNIFE_REG_UICURSOR; } } } static UICursorID HandlePunchCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const activated, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_MERCS); if (activated) { DetermineCursorBodyLocation(s, TRUE, TRUE); if (gfUIHandleShowMoveGrid) gfUIHandleShowMoveGrid = 2; // Calculate action points bool enough_points = true; gsCurrentActionPoints = CalcTotalAPsToAttack(s, map_pos, TRUE, s->bShownAimTime / 2); gfUIDisplayActionPoints = TRUE; gfUIDisplayActionPointsCenter = TRUE; // If we don't have any points and we are at the first refine, do nothing but warn! if (!EnoughPoints(s, gsCurrentActionPoints, 0, FALSE)) { gfUIDisplayActionPointsInvalid = TRUE; if (s->bShownAimTime == REFINE_PUNCH_1) return ACTION_PUNCH_RED; } INT8 const future_aim = REFINE_PUNCH_2; INT16 const ap_costs = CalcTotalAPsToAttack(s, map_pos, TRUE, future_aim / 2); if (!EnoughPoints(s, ap_costs, 0, FALSE)) enough_points = false; if (!(gTacticalStatus.uiFlags & INCOMBAT) && COUNTERDONE(NONGUNTARGETREFINE)) { RESETCOUNTER(NONGUNTARGETREFINE); if (s->bShownAimTime == REFINE_PUNCH_1) { PlayJA2Sample(TARG_REFINE_BEEP, MIDVOLUME, 1, MIDDLEPAN); } s->bShownAimTime = REFINE_PUNCH_2; } switch (s->bShownAimTime) { case REFINE_PUNCH_1: return gfDisplayFullCountRing ? ACTION_PUNCH_YELLOW_AIM1_UICURSOR : enough_points ? ACTION_PUNCH_RED_AIM1_UICURSOR : ACTION_PUNCH_NOGO_AIM1_UICURSOR; case REFINE_PUNCH_2: return gfDisplayFullCountRing ? ACTION_PUNCH_YELLOW_AIM2_UICURSOR : enough_points ? ACTION_PUNCH_RED_AIM2_UICURSOR : ACTION_PUNCH_NOGO_AIM2_UICURSOR; default: Assert(FALSE); // no return value! return NO_UICURSOR; } } else { gfUIDisplayActionPointsCenter = TRUE; // Check if we are on a guy (who's not selected)! if (gUIFullTarget && !(guiUIFullTargetFlags & SELECTED_MERC)) { DetermineCursorBodyLocation(s, TRUE, TRUE); return ACTION_PUNCH_RED; } else { return ACTION_PUNCH_GRAY; } } } static UICursorID HandleAidCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const activated, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_MERCSFORAID); return activated || gUIFullTarget ? ACTION_FIRSTAID_RED : ACTION_FIRSTAID_GRAY; } static UICursorID HandleActivatedTossCursor() { return ACTION_TOSS_UICURSOR; } static UICursorID HandleNonActivatedTossCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const recalc, MouseMoveState const uiCursorFlags, ItemCursor const ubItemCursor) { static bool bad_ctgh = false; // Check for enough ammo BOOLEAN armed = FALSE; if (ubItemCursor == TRAJECTORYCURS) { if (!EnoughAmmo(s, FALSE, HANDPOS)) { // Check if ANY ammo exists if (FindAmmoToReload(s, HANDPOS, NO_SLOT) == NO_SLOT) return BAD_RELOAD_UICURSOR; gsCurrentActionPoints = GetAPsToAutoReload(s); gfUIDisplayActionPoints = TRUE; return GOOD_RELOAD_UICURSOR; } armed = TRUE; } // Add APs if (gTacticalStatus.uiFlags & INCOMBAT) { gsCurrentActionPoints = ubItemCursor == TRAJECTORYCURS ? CalcTotalAPsToAttack(s, map_pos, TRUE, s->bShownAimTime / 2) : MinAPsToThrow(*s, map_pos, TRUE); gfUIDisplayActionPoints = TRUE; gfUIDisplayActionPointsCenter = TRUE; // If we don't have any points and we are at the first refine, do nothing // but warn! if (!EnoughPoints(s, gsCurrentActionPoints, 0, FALSE)) { gfUIDisplayActionPointsInvalid = TRUE; } } // If we begin to move, reset the cursor if (uiCursorFlags != MOUSE_STATIONARY) EndPhysicsTrajectoryUI(); gfUIHandlePhysicsTrajectory = TRUE; if (recalc) { // Calculate chance to throw here if (map_pos == s->sGridNo) { bad_ctgh = false; } else { OBJECTTYPE const& o = s->inv[HANDPOS]; // ATE: Find the object to use OBJECTTYPE TempObject = o; // Do we have a launchable? for (INT8 i = 0; i != MAX_ATTACHMENTS; ++i) { UINT16 const attach_item = o.usAttachItem[i]; if (attach_item == NOTHING) continue; if (!(GCM->getItem(attach_item)->isExplosive())) continue; CreateItem(attach_item, o.bAttachStatus[i], &TempObject); break; } if (s->bWeaponMode == WM_ATTACHED) { INT8 const slot = FindAttachment(&o, UNDER_GLAUNCHER); if (slot != NO_SLOT) { CreateItem(UNDER_GLAUNCHER, o.bAttachStatus[slot], &TempObject); } } INT16 final_grid_no; INT8 level; bad_ctgh = !CalculateLaunchItemChanceToGetThrough(s, &TempObject, map_pos, gsInterfaceLevel, gsInterfaceLevel * 256, &final_grid_no, armed, &level, TRUE); BeginPhysicsTrajectoryUI(final_grid_no, level, bad_ctgh); } } return bad_ctgh ? BAD_THROW_UICURSOR : GOOD_THROW_UICURSOR; } static UICursorID HandleWirecutterCursor(SOLDIERTYPE* const s, GridNo const map_pos, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_WIREFENCE); return s->bLevel == 0 && IsCuttableWireFenceAtGridNo(map_pos) ? GOOD_WIRECUTTER_UICURSOR : BAD_WIRECUTTER_UICURSOR; } static UICursorID HandleRepairCursor(SOLDIERTYPE* const s, GridNo const map_pos, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_REPAIR); return s->bLevel == 0 && IsRepairableStructAtGridNo(map_pos, 0) ? GOOD_REPAIR_UICURSOR : BAD_REPAIR_UICURSOR; } static UICursorID HandleRefuelCursor(SOLDIERTYPE* const s, GridNo const map_pos, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_REFUEL); return s->bLevel == 0 && GetRefuelableStructAtGridNo(map_pos) ? REFUEL_RED_UICURSOR : REFUEL_GREY_UICURSOR; } static UICursorID HandleJarCursor(SOLDIERTYPE* const s, GridNo const map_pos, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_JAR); return IsCorpseAtGridNo(map_pos, s->bLevel) ? GOOD_JAR_UICURSOR : BAD_JAR_UICURSOR; } static UICursorID HandleTinCanCursor(SOLDIERTYPE* const s, GridNo const map_pos, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_CAN); // Check if a door exists here STRUCTURE* structure; INT16 int_tile_grid_no; LEVELNODE* const int_tile = GetCurInteractiveTileGridNoAndStructure(&int_tile_grid_no, &structure); return int_tile && structure->fFlags & STRUCTURE_ANYDOOR ? PLACE_TINCAN_GREY_UICURSOR : PLACE_TINCAN_RED_UICURSOR; } static UICursorID HandleRemoteCursor(SOLDIERTYPE* const s, BOOLEAN const activated, MouseMoveState const uiCursorFlags) { if (gTacticalStatus.uiFlags & INCOMBAT) { gsCurrentActionPoints = GetAPsToUseRemote(s); gfUIDisplayActionPoints = TRUE; gfUIDisplayActionPointsCenter = TRUE; // If we don't have any points and we are at the first refine, do nothing but warn! if (!EnoughPoints(s, gsCurrentActionPoints, 0, FALSE)) { gfUIDisplayActionPointsInvalid = TRUE; } } return activated ? PLACE_REMOTE_RED_UICURSOR : PLACE_REMOTE_GREY_UICURSOR; } static UICursorID HandleBombCursor(SOLDIERTYPE* const s, GridNo const map_pos, BOOLEAN const activated, MouseMoveState const uiCursorFlags) { HandleUIMovementCursor(s, uiCursorFlags, map_pos, MOVEUI_TARGET_BOMB); if (gTacticalStatus.uiFlags & INCOMBAT) { gsCurrentActionPoints = GetTotalAPsToDropBomb(s, map_pos); gfUIDisplayActionPoints = TRUE; gfUIDisplayActionPointsCenter = TRUE; // If we don't have any points and we are at the first refine, do nothing but warn! if (!EnoughPoints(s, gsCurrentActionPoints, 0, FALSE)) { gfUIDisplayActionPointsInvalid = TRUE; } } return activated ? PLACE_BOMB_RED_UICURSOR : PLACE_BOMB_GREY_UICURSOR; } void HandleLeftClickCursor( SOLDIERTYPE *pSoldier ) { ItemCursor const ubItemCursor = GetActionModeCursor(pSoldier); // OK, if we are i realtime.. goto directly to shoot if (!(gTacticalStatus.uiFlags & INCOMBAT) && ubItemCursor != TOSSCURS && ubItemCursor != TRAJECTORYCURS) { // GOTO DIRECTLY TO USING ITEM // ( only if not burst mode.. ) if ( !pSoldier->bDoBurst ) { guiPendingOverrideEvent = CA_MERC_SHOOT; } return; } const GridNo sGridNo = GetMouseMapPos(); if (sGridNo == NOWHERE) return; gfUIForceReExamineCursorData = TRUE; gfDisplayFullCountRing = FALSE; switch( ubItemCursor ) { case TARGETCURS: pSoldier->bShownAimTime = REFINE_AIM_1; // Reset counter RESETCOUNTER( TARGETREFINE ); break; case PUNCHCURS: pSoldier->bShownAimTime = REFINE_PUNCH_1; // Reset counter RESETCOUNTER( NONGUNTARGETREFINE ); break; case KNIFECURS: pSoldier->bShownAimTime = REFINE_KNIFE_1; // Reset counter RESETCOUNTER( NONGUNTARGETREFINE ); break; default: // GOTO DIRECTLY TO USING ITEM guiPendingOverrideEvent = CA_MERC_SHOOT; } } void HandleRightClickAdjustCursor( SOLDIERTYPE *pSoldier, INT16 usMapPos ) { INT16 sAPCosts; INT8 bFutureAim; INT16 sGridNo; INT8 bTargetLevel; ItemCursor const ubCursor = GetActionModeCursor(pSoldier); // 'snap' cursor to target tile.... if (gUIFullTarget != NULL) usMapPos = gUIFullTarget->sGridNo; switch( ubCursor ) { case TARGETCURS: // CHECK IF GUY HAS IN HAND A WEAPON if ( pSoldier->bDoBurst ) { // Do nothing! // pSoldier->bShownAimTime = REFINE_AIM_BURST; } else { sGridNo = usMapPos; bTargetLevel = (INT8)gsInterfaceLevel; // Look for a target here... const SOLDIERTYPE* const tgt = gUIFullTarget; if (tgt != NULL) { // Get target soldier, if one exists sGridNo = tgt->sGridNo; bTargetLevel = pSoldier->bLevel; if (!HandleCheckForBadChangeToGetThrough(pSoldier, tgt, sGridNo, bTargetLevel)) { return; } } bFutureAim = (INT8)( pSoldier->bShownAimTime + 2 ); if ( bFutureAim <= REFINE_AIM_5 ) { sAPCosts = CalcTotalAPsToAttack( pSoldier, usMapPos, TRUE, (INT8)(bFutureAim / 2) ); // Determine if we can afford! if ( EnoughPoints( pSoldier, sAPCosts, 0, FALSE ) ) { pSoldier->bShownAimTime+= 2; if ( pSoldier->bShownAimTime > REFINE_AIM_5 ) { pSoldier->bShownAimTime = REFINE_AIM_5; } } // Else - goto first level! else { if ( !gfDisplayFullCountRing ) { gfDisplayFullCountRing = TRUE; } else { pSoldier->bShownAimTime = REFINE_AIM_1; gfDisplayFullCountRing = FALSE; } } } else { if ( !gfDisplayFullCountRing ) { gfDisplayFullCountRing = TRUE; } else { pSoldier->bShownAimTime = REFINE_AIM_1; gfDisplayFullCountRing = FALSE; } } } break; case PUNCHCURS: bFutureAim = (INT8)( pSoldier->bShownAimTime + REFINE_PUNCH_2 ); if ( bFutureAim <= REFINE_PUNCH_2 ) { sAPCosts = CalcTotalAPsToAttack( pSoldier, usMapPos, TRUE, (INT8)(bFutureAim / 2) ); // Determine if we can afford! if ( EnoughPoints( pSoldier, sAPCosts, 0, FALSE ) ) { pSoldier->bShownAimTime+= REFINE_PUNCH_2; if ( pSoldier->bShownAimTime > REFINE_PUNCH_2 ) { pSoldier->bShownAimTime = REFINE_PUNCH_2; } } // Else - goto first level! else { if ( !gfDisplayFullCountRing ) { gfDisplayFullCountRing = TRUE; } else { pSoldier->bShownAimTime = REFINE_PUNCH_1; gfDisplayFullCountRing = FALSE; } } } else { if ( !gfDisplayFullCountRing ) { gfDisplayFullCountRing = TRUE; } else { pSoldier->bShownAimTime = REFINE_PUNCH_1; gfDisplayFullCountRing = FALSE; } } break; case KNIFECURS: bFutureAim = (INT8)( pSoldier->bShownAimTime + REFINE_KNIFE_2 ); if ( bFutureAim <= REFINE_KNIFE_2 ) { sAPCosts = CalcTotalAPsToAttack( pSoldier, usMapPos, TRUE, (INT8)(bFutureAim / 2) ); // Determine if we can afford! if ( EnoughPoints( pSoldier, sAPCosts, 0, FALSE ) ) { pSoldier->bShownAimTime+= REFINE_KNIFE_2; if ( pSoldier->bShownAimTime > REFINE_KNIFE_2 ) { pSoldier->bShownAimTime = REFINE_KNIFE_2; } } // Else - goto first level! else { if ( !gfDisplayFullCountRing ) { gfDisplayFullCountRing = TRUE; } else { pSoldier->bShownAimTime = REFINE_KNIFE_1; gfDisplayFullCountRing = FALSE; } } } else { if ( !gfDisplayFullCountRing ) { gfDisplayFullCountRing = TRUE; } else { pSoldier->bShownAimTime = REFINE_KNIFE_1; gfDisplayFullCountRing = FALSE; } } break; case TOSSCURS: break; default: ErasePath(); } } ItemCursor GetActionModeCursor(SOLDIERTYPE const* const pSoldier) { UINT16 usInHand; // If we are an EPC, do nothing.... //if ( ( pSoldier->uiStatusFlags & SOLDIER_VEHICLE ) ) //{ // return( INVALIDCURS ); //} // AN EPC is always not - attackable unless they are a robot! if ( AM_AN_EPC( pSoldier ) && !( pSoldier->uiStatusFlags & SOLDIER_ROBOT ) ) { return( INVALIDCURS ); } // ATE: if a vehicle.... same thing if ( pSoldier->uiStatusFlags & SOLDIER_VEHICLE ) { return( INVALIDCURS ); } // If we can't be controlled, returninvalid... if ( pSoldier->uiStatusFlags & SOLDIER_ROBOT ) { if ( !CanRobotBeControlled( pSoldier ) ) { // Display message that robot cannot be controlled.... return( INVALIDCURS ); } } // If we are in attach shoot mode, use toss cursor... if (pSoldier->bWeaponMode == WM_ATTACHED ) { return( TRAJECTORYCURS ); } usInHand = pSoldier->inv[HANDPOS].usItem; // Start off with what is in our hand ItemCursor ubCursor = GCM->getItem(usInHand)->getCursor(); // OK, check if what is in our hands has a detonator attachment... // Detonators can only be on invalidcurs things... if ( ubCursor == INVALIDCURS ) { if ( FindAttachment( &(pSoldier->inv[HANDPOS]), DETONATOR) != ITEM_NOT_FOUND ) { ubCursor = BOMBCURS; } else if ( FindAttachment( &(pSoldier->inv[HANDPOS]), REMDETONATOR) != ITEM_NOT_FOUND ) { ubCursor = BOMBCURS; } } // Now check our terrain to see if we cannot do the action now... if ( pSoldier->bOverTerrainType == DEEP_WATER ) { ubCursor = INVALIDCURS; } // If we are out of breath, no cursor... if ( pSoldier->bBreath < OKBREATH && pSoldier->bCollapsed ) { ubCursor = INVALIDCURS; } return( ubCursor ); } // Switch on item, display appropriate feedback cursor for a click.... void HandleUICursorRTFeedback( SOLDIERTYPE *pSoldier ) { ItemCursor const ubItemCursor = GetActionModeCursor(pSoldier); switch( ubItemCursor ) { case TARGETCURS: if ( pSoldier->bDoBurst ) { //BeginDisplayTimedCursor( ACTION_TARGETREDBURST_UICURSOR, 500 ); } else { if ( GCM->getItem(pSoldier->inv[ HANDPOS ].usItem)->getItemClass() == IC_THROWING_KNIFE ) { BeginDisplayTimedCursor( RED_THROW_UICURSOR, 500 ); } else { BeginDisplayTimedCursor( ACTION_TARGETRED_UICURSOR, 500 ); } } break; default: break; } }
[ "public1983@web.de" ]
public1983@web.de
1a51c8dbe56f83e4c173f823dd0b6e07b708546b
cafb8c7c0891ac464255d20f148ec4e53ffb6611
/projeto/pessoal/pista.h
a3e46d5eb29b763274e6fd155b5e9a1b641f7764
[]
no_license
davidamurim7/projetoComputacaoGrafica
2e22675cbf6b24b440aa6c21a9c0ee6599a31410
4ad9aee11329ee5e276fb7005f67eeacce29d319
refs/heads/main
2023-08-11T04:55:44.643998
2021-09-20T14:54:00
2021-09-20T14:54:00
408,483,468
3
0
null
null
null
null
UTF-8
C++
false
false
239
h
#ifndef PISTA_H #define PISTA_H #include <objeto.h> class Pista : public Objeto { public: Model3DS* model; public: Pista(); ~Pista(); Pista( Vetor3D t, Vetor3D a, Vetor3D s ); void desenha(); }; #endif // PISTA_H
[ "davidamurim7@gmail.com" ]
davidamurim7@gmail.com
d85e25c04e6308bec728c1d7861f72d553ad1281
07f3074fa979fc99577aeaa93ce22e9853bea3ca
/src/view/gtk/include/gtk_view.h
d3ed5c9514eaa5f4fbf6df53fe49c372f9885622
[ "Apache-2.0" ]
permissive
GuardianRG/erebus
af34713d9650c7b4ab6d4e2e28fae7d187be9b09
37da546f9142b44829572621d328332394dd50ef
refs/heads/master
2020-04-15T20:11:01.573571
2015-08-17T00:55:45
2015-08-17T00:55:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,157
h
#pragma once #include <gtkmm/builder.h> #include <glibmm/refptr.h> #include <gtkmm/viewport.h> #include <gtkmm/menu.h> #include <string> #include <i_view.h> namespace erebus { class IGUIManager; } namespace erebus { /** * This is the base class for every widget that can be added to the gui. * Every widget that derives from this class should at least have a constructor * that allows it to be created by a builder. */ class GTK_View:public Gtk::Viewport,virtual public IView { std::string title_; protected: IGUIManager* guiManager_; public: /** * Constructor. * * This contructor is needed to create this widget from a builder. * * When derived this constructor should be called and not the constructor * of viewport. * * @param cobject used for creating this widget from a builder * @param refBuilder used for created this widget from a builder */ GTK_View(BaseObjectType* cobject); /** * Copy constructor. * * Cant be copied since Gtk::Viewport cant be copied. */ GTK_View(const GTK_View &obj)=delete; /** * Move Constructor. * * Cant be copied since Gtk::Viewport cant be copied. */ GTK_View( GTK_View&& )=delete; /** * Copy assignment operator. * * Cant be copied since Gtk::Viewport cant be copied. */ GTK_View& operator=(const GTK_View&)=delete; /** * Move assignment operator. * * Cant be copied since Gtk::Viewport cant be copied. */ GTK_View& operator=(GTK_View&&)=delete; /** * Destructor. */ virtual ~GTK_View(); /** * Creates a context menu and returns it. * * The created context menu gets shown by the container that this view is contained in. * This method should be overwritten. * * @return the context menu */ virtual std::unique_ptr<Gtk::Menu> createContextMenu(); /** * See IView::setGUIManager. */ void setGUIManager(IGUIManager& manager)override; /** * See IView::getGUIManager. */ IGUIManager& getGUIManager()override; /** * See IView::setTitle */ void setTitle(const std::string& title) override; /** * See IView::getTitle */ std::string getTitle() const override; }; }//namespace erebus
[ "johs.werner@googlemail.com" ]
johs.werner@googlemail.com
8063e028fbfb61b84420d10e2f6546c9a210de0a
6aa437b0c57f644029563206d04bd431edf3d0ac
/labs/lab1/part2/3_flash_string_in_morse/main.cpp
abc74ac0e21e2d76384d973e570b8d5ab779c45d
[]
no_license
canbax/bilkent-cs431
4726daecd21eb693a5518dabee30242bf5fc5a41
6681df30887de02f27eb3b07870b2419e3ccf3dd
refs/heads/master
2020-06-13T09:33:43.970411
2019-08-19T14:59:44
2019-08-19T14:59:44
194,614,193
2
0
null
2020-04-30T11:07:25
2019-07-01T06:37:56
C
UTF-8
C++
false
false
2,303
cpp
#include "mbed.h" #include<string> #include <ctype.h> Serial pc(USBTX, USBRX); // tx, rx DigitalOut myled(LED1); bool hasInp = false; char currChar; char buffer[1024]; int charIdx = -1; int bufferSize = 0; string alphabet = "abcdefghijklmnopqrstuvwqyz1234567890"; string morseAlphabet[] = {".-","-...","-.-.","-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----" }; void flashLed(float time) { myled = 1; wait(time); myled = 0; wait(time); } string char2morse(char c) { c = tolower(c); int index = alphabet.find(c); if(index != -1) { return morseAlphabet[index]; } else { return " "; } } void flashMorse(string morseChar) { if (morseChar == " ") { return; } int len = morseChar.size(); for (int i = 0; i < len; i++) { char ch = morseChar[i]; if (ch == '-') { flashLed(1.5); } else if (ch == '.') { flashLed(0.5); } else { pc.printf("line 46 not dot or dash in morse string"); } } } void flashCharInMorse(char c) { string morseChar = char2morse(c); flashMorse(morseChar); } void flashCharBuffer() { for (int i = 0; i <= bufferSize; i++) { flashCharInMorse(buffer[i]); } } void inpHandler() { hasInp = true; currChar = pc.getc(); } int main() { pc.printf("Hello World!\n\r"); pc.attach(&inpHandler, Serial::RxIrq); while(1) { if (hasInp) { if (currChar == '\n' || currChar == '\r') { pc.printf(buffer); pc.printf("\n"); bufferSize = charIdx + 1; charIdx = -1; flashCharBuffer(); memset(buffer, 0, sizeof buffer); } else { charIdx++; buffer[charIdx] = currChar; } hasInp = false; } } }
[ "yusufsaidcanbaz@gmail.comcd" ]
yusufsaidcanbaz@gmail.comcd
5165c06475388aee9364283ab7965af296ed27e1
d9c062e84856bc5f75beb29c2321d0b18dcb87c6
/components/segmentation_platform/internal/execution/feature_aggregator_impl.cc
aae9176f1ec04c381fc215cb65f7cedec6c6188e
[ "BSD-3-Clause" ]
permissive
Proby143/chromium
785716f3e502e5d921e3ba4a32c66700d20e0e4f
dff2d8e4cbedc970e26fea96d440a7fcbe59e598
refs/heads/master
2023-05-11T17:56:52.720820
2021-06-21T08:31:58
2021-06-21T08:31:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,162
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/segmentation_platform/internal/execution/feature_aggregator_impl.h" #include <algorithm> #include <cstdint> #include <vector> #include "base/notreached.h" #include "base/time/time.h" #include "components/segmentation_platform/internal/database/signal_database.h" #include "components/segmentation_platform/internal/execution/feature_aggregator.h" #include "components/segmentation_platform/internal/proto/aggregation.pb.h" #include "components/segmentation_platform/internal/proto/types.pb.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace segmentation_platform { using Sample = SignalDatabase::Sample; namespace { std::vector<float> SumCountAggregation(const std::vector<Sample>& samples) { return std::vector<float>{samples.size()}; } std::vector<float> SumValuesAggregation(proto::SignalType signal_type, const std::vector<Sample>& samples) { if (signal_type == proto::SignalType::USER_ACTION) return SumCountAggregation(samples); float sum = 0; for (auto& sample : samples) sum += sample.second.value(); return std::vector<float>{sum}; } } // namespace FeatureAggregatorImpl::FeatureAggregatorImpl() = default; FeatureAggregatorImpl::~FeatureAggregatorImpl() = default; std::vector<float> FeatureAggregatorImpl::Process( proto::SignalType signal_type, proto::Aggregation aggregation, uint64_t length, const base::Time& end_time, const base::TimeDelta& bucket_duration, const std::vector<SignalDatabase::Sample>& samples) const { switch (aggregation) { case proto::Aggregation::SUM_COUNT: return SumCountAggregation(samples); case proto::Aggregation::SUM_VALUES: return SumValuesAggregation(signal_type, samples); case proto::Aggregation::BUCKETED_COUNT: case proto::Aggregation::BUCKETED_COUNT_BOOLEAN: case proto::Aggregation::BUCKETED_COUNT_BOOLEAN_TRUE_COUNT: case proto::Aggregation::BUCKETED_CUMULATIVE_COUNT: case proto::Aggregation::SUM_VALUES_BOOLEAN: case proto::Aggregation::BUCKETED_CUMULATIVE_SUM_VALUES: case proto::Aggregation::BUCKETED_SUM_VALUES: case proto::Aggregation::UNKNOWN: // TODO(nyquist): Implement the rest of the aggregations. NOTREACHED(); return std::vector<float>(); } } void FeatureAggregatorImpl::FilterEnumSamples( const std::vector<uint32_t>& accepted_enum_values, std::vector<SignalDatabase::Sample>& samples) const { if (accepted_enum_values.size() == 0) return; auto new_end = std::remove_if( samples.begin(), samples.end(), [&accepted_enum_values](SignalDatabase::Sample sample) { DCHECK(sample.second.has_value()); auto found = std::find(accepted_enum_values.begin(), accepted_enum_values.end(), sample.second.value()) != accepted_enum_values.end(); return !found; }); samples.erase(new_end, samples.end()); } } // namespace segmentation_platform
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
7edd82f0902cb1b4aeda1ee15b5ba43148c533da
b8e93dd209a1288274d12dfb463766120353d650
/BuyerServer/info/buyerinfo.h
b167595422942fa05ab4c67311ffabfbe404077e
[]
no_license
Llq-210120/buyer
4108768beb94ad4ca27780492644d69a19e00a8b
a4a5d0d3b68c52385c786d51624507a9ad93f2ba
refs/heads/master
2023-05-21T02:02:43.763010
2021-06-09T15:09:46
2021-06-09T15:09:46
375,379,487
0
0
null
null
null
null
UTF-8
C++
false
false
561
h
#ifndef BUYERINFO_H #define BUYERINFO_H #include <QString> class BuyerInfo { public: BuyerInfo(); BuyerInfo(const QString &id, const QString &name,const QString &sex); void display(void) const; void setID(const QString &id); void setName(const QString &name); void setSex(const QString &sex); const QString &getID() const; const QString &getName() const; const QString &getSex() const; private: QString m_id; QString m_name; QString m_sex; }; typedef QList<BuyerInfo> buyerInfoList; #endif // BUYERINFO_H
[ "1037918484@qq.com" ]
1037918484@qq.com
3ecce54a98db16ce2b16f2e13661774eeaa5701c
52507f7928ba44b7266eddf0f1a9bf6fae7322a4
/SDK/BP_KickWeapon_classes.h
e7fb66d30f6a2bab9ef10b28346e67a7d767bddb
[]
no_license
LuaFan2/mordhau-sdk
7268c9c65745b7af511429cfd3bf16aa109bc20c
ab10ad70bc80512e51a0319c2f9b5effddd47249
refs/heads/master
2022-11-30T08:14:30.825803
2020-08-13T16:31:27
2020-08-13T16:31:27
287,329,560
1
0
null
null
null
null
UTF-8
C++
false
false
619
h
#pragma once // Name: Mordhau, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_KickWeapon.BP_KickWeapon_C // 0x0000 (0x1C50 - 0x1C50) class ABP_KickWeapon_C : public AKickWeapon { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_KickWeapon.BP_KickWeapon_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "51294434+LuaFan2@users.noreply.github.com" ]
51294434+LuaFan2@users.noreply.github.com
1c6202e84cd485e43b539005f1eec65357d0d314
c7117da45477e486ebefc20bae60b77f555fdf58
/main/touch/ButtonDriver.cpp
1f3b0c393a186745eff6bf795387d5f5520c48a7
[ "MIT" ]
permissive
sascha78/Homepoint
251a6e8d378916627cba77c785a5746759447f89
a6483b7bf825dff0a4be276833353705c340dc31
refs/heads/master
2020-09-04T00:00:28.794025
2019-11-14T20:16:06
2019-11-14T20:16:06
219,610,368
0
0
MIT
2019-11-04T22:41:03
2019-11-04T22:41:03
null
UTF-8
C++
false
false
3,095
cpp
#include <touch/ButtonDriver.h> #include <config/Config.h> // Specifically for M5Stack which uses Pull-Ups on buttons namespace gfx { ButtonDriver::ButtonDriver(TFT_eSPI* tftDriver) { if (ButtonsArePullUp) { pinMode(BUTTON_A_PIN, INPUT_PULLUP); pinMode(BUTTON_B_PIN, INPUT_PULLUP); pinMode(BUTTON_C_PIN, INPUT_PULLUP); } mCurrentPressState.state = PressState::None; } tl::optional<ButtonEvent> ButtonDriver::buttonEvent() { auto now = std::chrono::system_clock::now(); auto button = buttonState(); if (!button) { return tl::nullopt; } auto btn = *button; if (btn.state == PressState::Start) { mLastPressTime = std::chrono::system_clock::now(); } const auto pressDelta = std::chrono::duration_cast<std::chrono::milliseconds>(now - mLastPressTime).count(); const auto isValid = pressDelta < MSBeforeInvalid; if (!isValid) { return tl::nullopt; } const auto isLongPress = pressDelta > MSBeforeLongPress; const auto isShortPress = pressDelta < MSBeforeTap; if (btn.state == PressState::Ended) { ButtonEvent btnEvent; btnEvent.button = btn.btn; if (isShortPress) { btnEvent.state = ButtonPress::Tap; return tl::make_optional(btnEvent); } if (isLongPress) { btnEvent.state = ButtonPress::LongPress; return tl::make_optional(btnEvent); } } return tl::nullopt; } tl::optional<ButtonPressState> ButtonDriver::buttonState() { Button btn = digitalRead(BUTTON_A_PIN) == 0 ? Button::A : Button::NONE; btn = digitalRead(BUTTON_B_PIN) == 0 ? Button::B : btn; btn = digitalRead(BUTTON_C_PIN) == 0 ? Button::C : btn; ButtonPressState newState; if (btn != Button::NONE) { switch (mCurrentPressState.state) { case PressState::None: newState.state = PressState::Start; break; case PressState::Start: newState.state = PressState::Running; case PressState::Running: break; case PressState::Ended: newState.state = PressState::Start; break; } mCurrentPressState = newState; mCurrentPressState.btn = btn; return tl::make_optional(mCurrentPressState); } else { switch (mCurrentPressState.state) { case PressState::None: break; case PressState::Start: case PressState::Running: newState.state = PressState::Ended; break; case PressState::Ended: newState.state = PressState::None; break; default: newState.state = PressState::None; break; } if (newState.state == PressState::Ended) { ButtonPressState evt; evt.btn = mCurrentPressState.btn; evt.state = newState.state; mCurrentPressState.state = newState.state; return tl::make_optional(evt); } mCurrentPressState = newState; return tl::nullopt; } } } // namespace gfx
[ "matthias@s-r-n.de" ]
matthias@s-r-n.de
cb5b1461e89430488fe50ff315e920f76974db1b
45364deefe009a0df9e745a4dd4b680dcedea42b
/SDK/FSD_BP_BarGlass_PotsOGold_classes.hpp
4208ddcb4f043f893f94dab9dc6dda5cc87deaf4
[]
no_license
RussellJerome/DeepRockGalacticSDK
5ae9b59c7324f2a97035f28545f92773526ed99e
f13d9d8879a645c3de89ad7dc6756f4a7a94607e
refs/heads/master
2022-11-26T17:55:08.185666
2020-07-26T21:39:30
2020-07-26T21:39:30
277,796,048
0
0
null
null
null
null
UTF-8
C++
false
false
711
hpp
#pragma once // DeepRockGalactic SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "FSD_BP_BarGlass_PotsOGold_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_BarGlass_PotsOGold.BP_BarGlass_PotsOGold_C // 0x0000 (0x0388 - 0x0388) class ABP_BarGlass_PotsOGold_C : public ABP_BarGlass_Standard_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_BarGlass_PotsOGold.BP_BarGlass_PotsOGold_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "darkmanvoo@gmail.com" ]
darkmanvoo@gmail.com
0250e1a0f52a1d5bc0a241f4c9b843c981dbbe2e
2c5a193cb79c6eb86850a11892719a8989ac8591
/searching/floor.cpp
93a184850a4cd5e2c5b45714b8f132178195caa3
[]
no_license
Anubhav2907/DSA
0b9418f048e16e8bedbda709f5bdedcafeece44b
a2fa56a8e32002a1a77a498cd956d7256b327bf0
refs/heads/master
2023-08-15T19:31:18.723237
2021-09-25T17:58:00
2021-09-25T17:58:00
370,788,119
2
0
null
null
null
null
UTF-8
C++
false
false
466
cpp
#include <bits/stdc++.h> using namespace std; int floor(int arr[], int n, int k){ int low = 0; int high = n-1; int ans = -1; while(low <= high){ int mid = (low + high)/2; if(arr[mid]== k){ return mid; }else if(arr[mid]>k){ high=mid-1; }else{ ans= mid; low=mid+1; } }return ans; } int main(){ int arr[] = {1,2,8,10,11,12,19}; cout << floor(arr,7,5); }
[ "u19ec135@eced.svnit.ac.in" ]
u19ec135@eced.svnit.ac.in
bb0f9bd3d38ac7cbe34840e38812144a9b5dff8b
a3d39c53b1abf4d35c9a9a1d8c8f226572f29bcd
/src/test/util_threadnames_tests.cpp
9193516244481c25d2f5bf31bfd74f5b48b6dd65
[ "MIT" ]
permissive
BakedInside/Beans-Core
afc3a55efa3e14e62a19f4bc4d5ae5a357f5f1de
daa9b2ddbfd3305881749bda7f32146738154260
refs/heads/master
2022-07-30T05:42:26.680123
2021-05-22T15:35:40
2021-05-22T15:35:40
369,584,373
1
0
null
null
null
null
UTF-8
C++
false
false
1,915
cpp
// Copyright (c) 2018-2020 The Beans Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <test/util/setup_common.h> #include <util/string.h> #include <util/threadnames.h> #include <mutex> #include <set> #include <thread> #include <vector> #if defined(HAVE_CONFIG_H) #include <config/beans-config.h> #endif #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(util_threadnames_tests, BasicTestingSetup) const std::string TEST_THREAD_NAME_BASE = "test_thread."; /** * Run a bunch of threads to all call util::ThreadRename. * * @return the set of name each thread has after attempted renaming. */ std::set<std::string> RenameEnMasse(int num_threads) { std::vector<std::thread> threads; std::set<std::string> names; std::mutex lock; auto RenameThisThread = [&](int i) { util::ThreadRename(TEST_THREAD_NAME_BASE + ToString(i)); std::lock_guard<std::mutex> guard(lock); names.insert(util::ThreadGetInternalName()); }; for (int i = 0; i < num_threads; ++i) { threads.push_back(std::thread(RenameThisThread, i)); } for (std::thread& thread : threads) thread.join(); return names; } /** * Rename a bunch of threads with the same basename (expect_multiple=true), ensuring suffixes are * applied properly. */ BOOST_AUTO_TEST_CASE(util_threadnames_test_rename_threaded) { #if !defined(HAVE_THREAD_LOCAL) // This test doesn't apply to platforms where we don't have thread_local. return; #endif std::set<std::string> names = RenameEnMasse(100); BOOST_CHECK_EQUAL(names.size(), 100U); // Names "test_thread.[n]" should exist for n = [0, 99] for (int i = 0; i < 100; ++i) { BOOST_CHECK(names.find(TEST_THREAD_NAME_BASE + ToString(i)) != names.end()); } } BOOST_AUTO_TEST_SUITE_END()
[ "lanorlasystem@gmail.com" ]
lanorlasystem@gmail.com
55825f9eccace895ebef97d0a9faf500a769a800
5456502f97627278cbd6e16d002d50f1de3da7bb
/ash/common/system/date/tray_system_info.h
0e65f2e658315302f69d4af78aa993a8f00821a5
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,181
h
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_COMMON_SYSTEM_DATE_TRAY_SYSTEM_INFO_H_ #define ASH_COMMON_SYSTEM_DATE_TRAY_SYSTEM_INFO_H_ #if defined(OS_CHROMEOS) #include <memory> #endif // defined(OS_CHROMEOS) #include "ash/ash_export.h" #include "ash/common/login_status.h" #include "ash/common/system/date/clock_observer.h" #include "ash/common/system/tray/system_tray_item.h" #include "base/macros.h" namespace views { class Label; } namespace ash { class SystemInfoDefaultView; #if defined(OS_CHROMEOS) class SystemClockObserver; #endif namespace tray { class TimeView; } // The bottom row of the system menu. The default view shows the current date // and power status. The tray view shows the current time. class ASH_EXPORT TraySystemInfo : public SystemTrayItem, public ClockObserver { public: explicit TraySystemInfo(SystemTray* system_tray); ~TraySystemInfo() override; const tray::TimeView* GetTimeTrayForTesting() const; const SystemInfoDefaultView* GetDefaultViewForTesting() const; views::View* CreateDefaultViewForTesting(LoginStatus status); private: // SystemTrayItem: views::View* CreateTrayView(LoginStatus status) override; views::View* CreateDefaultView(LoginStatus status) override; void DestroyTrayView() override; void DestroyDefaultView() override; void UpdateAfterShelfAlignmentChange(ShelfAlignment alignment) override; // ClockObserver: void OnDateFormatChanged() override; void OnSystemClockTimeUpdated() override; void OnSystemClockCanSetTimeChanged(bool can_set_time) override; void Refresh() override; void SetupLabelForTimeTray(views::Label* label); void UpdateTimeFormat(); tray::TimeView* tray_view_; SystemInfoDefaultView* default_view_; LoginStatus login_status_; #if defined(OS_CHROMEOS) std::unique_ptr<SystemClockObserver> system_clock_observer_; #endif DISALLOW_COPY_AND_ASSIGN(TraySystemInfo); }; } // namespace ash #endif // ASH_COMMON_SYSTEM_DATE_TRAY_SYSTEM_INFO_H_
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
13f5a3a12db7dc307b656444ceb71143c599e648
224aa916e8a79497ba7290e4dd3a4712a9eb8217
/airdcpp-webapi/api/TransferApi.cpp
f6c62a1dbe3cd01131c3d267293c64ead80256d2
[]
no_license
roboirc/airdcpp-webclient
54b202086aa21828cd6541c0975f0b9ab4a6bde4
ae563ce2a763af982c9cd155e53a3eae90b13ca2
refs/heads/master
2021-03-17T16:15:30.279461
2019-11-16T17:04:14
2019-11-16T17:04:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,115
cpp
/* * Copyright (C) 2011-2019 AirDC++ Project * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "stdinc.h" #include <web-server/Timer.h> #include <api/TransferApi.h> #include <airdcpp/Download.h> #include <airdcpp/Upload.h> #include <airdcpp/DownloadManager.h> #include <airdcpp/ConnectionManager.h> #include <airdcpp/QueueManager.h> #include <airdcpp/ThrottleManager.h> #include <airdcpp/UploadManager.h> namespace webserver { TransferApi::TransferApi(Session* aSession) : SubscribableApiModule( aSession, Access::TRANSFERS, { "transfer_statistics", "transfer_added", "transfer_updated", "transfer_removed", // These are included in transfer_updated events as well "transfer_starting", "transfer_completed", "transfer_failed", } ), timer(getTimer([this] { onTimer(); }, 1000)), view("transfer_view", this, TransferUtils::propertyHandler, std::bind(&TransferApi::getTransfers, this)) { METHOD_HANDLER(Access::TRANSFERS, METHOD_GET, (), TransferApi::handleGetTransfers); METHOD_HANDLER(Access::TRANSFERS, METHOD_GET, (TOKEN_PARAM), TransferApi::handleGetTransfer); METHOD_HANDLER(Access::TRANSFERS, METHOD_POST, (TOKEN_PARAM, EXACT_PARAM("force")), TransferApi::handleForce); METHOD_HANDLER(Access::TRANSFERS, METHOD_POST, (TOKEN_PARAM, EXACT_PARAM("disconnect")), TransferApi::handleDisconnect); METHOD_HANDLER(Access::TRANSFERS, METHOD_GET, (EXACT_PARAM("tranferred_bytes")), TransferApi::handleGetTransferredBytes); METHOD_HANDLER(Access::TRANSFERS, METHOD_GET, (EXACT_PARAM("stats")), TransferApi::handleGetTransferStats); timer->start(false); loadTransfers(); DownloadManager::getInstance()->addListener(this); UploadManager::getInstance()->addListener(this); ConnectionManager::getInstance()->addListener(this); } TransferApi::~TransferApi() { timer->stop(true); DownloadManager::getInstance()->removeListener(this); UploadManager::getInstance()->removeListener(this); ConnectionManager::getInstance()->removeListener(this); } void TransferApi::loadTransfers() noexcept { // add the existing connections { auto cm = ConnectionManager::getInstance(); RLock l(cm->getCS()); for (const auto& d : cm->getTransferConnections(true)) { auto info = addTransfer(d, "Inactive, waiting for status updates"); updateQueueInfo(info); } for (const auto& u : cm->getTransferConnections(false)) { addTransfer(u, "Inactive, waiting for status updates"); } } { auto um = UploadManager::getInstance(); RLock l(um->getCS()); for (const auto& u : um->getUploads()) { if (u->getUserConnection().getState() == UserConnection::STATE_RUNNING) { on(UploadManagerListener::Starting(), u); } } } { auto dm = DownloadManager::getInstance(); RLock l(dm->getCS()); for (const auto& d : dm->getDownloads()) { if (d->getUserConnection().getState() == UserConnection::STATE_RUNNING) { starting(d, STRING(DOWNLOADING), true); } } } } void TransferApi::unloadTransfers() noexcept { WLock l(cs); transfers.clear(); } TransferInfo::List TransferApi::getTransfers() const noexcept { TransferInfo::List ret; { RLock l(cs); boost::range::copy(transfers | map_values, back_inserter(ret)); } return ret; } api_return TransferApi::handleGetTransfers(ApiRequest& aRequest) { auto j = Serializer::serializeItemList(TransferUtils::propertyHandler, getTransfers()); aRequest.setResponseBody(j); return websocketpp::http::status_code::ok; } api_return TransferApi::handleGetTransfer(ApiRequest& aRequest) { auto item = getTransfer(aRequest); aRequest.setResponseBody(Serializer::serializeItem(item, TransferUtils::propertyHandler)); return websocketpp::http::status_code::ok; } api_return TransferApi::handleGetTransferredBytes(ApiRequest& aRequest) { aRequest.setResponseBody({ { "session_downloaded", Socket::getTotalDown() }, { "session_uploaded", Socket::getTotalUp() }, { "start_total_downloaded", SETTING(TOTAL_DOWNLOAD) - Socket::getTotalDown() }, { "start_total_uploaded", SETTING(TOTAL_UPLOAD) - Socket::getTotalUp() }, }); return websocketpp::http::status_code::ok; } api_return TransferApi::handleForce(ApiRequest& aRequest) { auto item = getTransfer(aRequest); if (item->isDownload()) { ConnectionManager::getInstance()->force(item->getStringToken()); } return websocketpp::http::status_code::no_content; } api_return TransferApi::handleDisconnect(ApiRequest& aRequest) { auto item = getTransfer(aRequest); ConnectionManager::getInstance()->disconnect(item->getStringToken()); return websocketpp::http::status_code::no_content; } TransferInfoPtr TransferApi::getTransfer(ApiRequest& aRequest) const { auto wantedId = aRequest.getTokenParam(); RLock l(cs); auto ret = boost::find_if(transfers | map_values, [&](const TransferInfoPtr& aInfo) { return aInfo->getToken() == wantedId; }); if (ret.base() == transfers.end()) { throw RequestException(websocketpp::http::status_code::not_found, "Transfer not found"); } return *ret; } api_return TransferApi::handleGetTransferStats(ApiRequest& aRequest) { aRequest.setResponseBody(serializeTransferStats()); return websocketpp::http::status_code::ok; } json TransferApi::serializeTransferStats() const noexcept { auto resetSpeed = [](int transfers, int64_t speed) { return (transfers == 0 && speed < 10 * 1024) || speed < 1024; }; auto uploads = UploadManager::getInstance()->getUploadCount(); auto downloads = DownloadManager::getInstance()->getTotalDownloadConnectionCount(); auto downSpeed = DownloadManager::getInstance()->getLastDownSpeed(); if (resetSpeed(downloads, downSpeed)) { downSpeed = 0; } auto upSpeed = DownloadManager::getInstance()->getLastUpSpeed(); if (resetSpeed(uploads, upSpeed)) { upSpeed = 0; } return { { "speed_down", downSpeed }, { "speed_up", upSpeed }, { "limit_down", ThrottleManager::getDownLimit() }, { "limit_up", ThrottleManager::getUpLimit() }, { "upload_bundles", lastUploadBundles }, { "download_bundles", lastDownloadBundles }, { "uploads", uploads }, { "downloads", downloads }, { "queued_bytes", QueueManager::getInstance()->getTotalQueueSize() }, { "session_downloaded", Socket::getTotalDown() }, { "session_uploaded", Socket::getTotalUp() }, }; } void TransferApi::onTimer() { if (!subscriptionActive("transfer_statistics")) return; auto newStats = serializeTransferStats(); if (previousStats == newStats) return; lastUploadBundles = 0; lastDownloadBundles = 0; send("transfer_statistics", JsonUtil::filterExactValues(newStats, previousStats)); previousStats.swap(newStats); } void TransferApi::onTick(const Transfer* aTransfer, bool aIsDownload) noexcept { auto t = findTransfer(aTransfer->getToken()); if (!t) { return; } t->setSpeed(aTransfer->getAverageSpeed()); t->setBytesTransferred(aTransfer->getPos()); t->setTimeLeft(aTransfer->getSecondsLeft()); uint64_t timeSinceStarted = GET_TICK() - t->getStarted(); if (timeSinceStarted < 1000) { t->setStatusString(aIsDownload ? STRING(DOWNLOAD_STARTING) : STRING(UPLOAD_STARTING)); } else { t->setStatusString(STRING_F(RUNNING_PCT, t->getPercentage())); } onTransferUpdated(t, { TransferUtils::PROP_STATUS, TransferUtils::PROP_BYTES_TRANSFERRED, TransferUtils::PROP_SPEED, TransferUtils::PROP_SECONDS_LEFT }, Util::emptyString); } void TransferApi::on(UploadManagerListener::Tick, const UploadList& aUploads) noexcept { for (const auto& ul : aUploads) { if (ul->getPos() == 0) continue; onTick(ul, false); } } void TransferApi::on(DownloadManagerListener::Tick, const DownloadList& aDownloads) noexcept { for (const auto& dl : aDownloads) { onTick(dl, true); } } void TransferApi::on(DownloadManagerListener::BundleTick, const BundleList& bundles, uint64_t /*aTick*/) noexcept { lastDownloadBundles = bundles.size(); } void TransferApi::on(UploadManagerListener::BundleTick, const UploadBundleList& bundles) noexcept { lastUploadBundles = bundles.size(); } TransferInfoPtr TransferApi::addTransfer(const ConnectionQueueItem* aCqi, const string& aStatus) noexcept { auto t = std::make_shared<TransferInfo>(aCqi->getUser(), aCqi->getConnType() == ConnectionType::CONNECTION_TYPE_DOWNLOAD, aCqi->getToken()); { WLock l(cs); transfers[aCqi->getToken()] = t; } t->setStatusString(aStatus); return t; } void TransferApi::on(ConnectionManagerListener::Added, const ConnectionQueueItem* aCqi) noexcept { if (aCqi->getConnType() == CONNECTION_TYPE_PM) return; auto t = addTransfer(aCqi, STRING(CONNECTING)); view.onItemAdded(t); if (subscriptionActive("transfer_added")) { send("transfer_added", Serializer::serializeItem(t, TransferUtils::propertyHandler)); } } void TransferApi::on(ConnectionManagerListener::Removed, const ConnectionQueueItem* aCqi) noexcept { TransferInfoPtr t; { WLock l(cs); auto i = transfers.find(aCqi->getToken()); if (i == transfers.end()) { return; } t = i->second; transfers.erase(i); } view.onItemRemoved(t); if (subscriptionActive("transfer_removed")) { send("transfer_removed", Serializer::serializeItem(t, TransferUtils::propertyHandler)); } } void TransferApi::onFailed(TransferInfoPtr& aInfo, const string& aReason) noexcept { if (aInfo->getState() == TransferInfo::STATE_FAILED) { // The connection is disconnected right after download fails, which causes double events // Don't override the previous message return; } aInfo->setStatusString(aReason); aInfo->setSpeed(-1); aInfo->setBytesTransferred(-1); aInfo->setTimeLeft(-1); aInfo->setState(TransferInfo::STATE_FAILED); onTransferUpdated(aInfo, { TransferUtils::PROP_STATUS, TransferUtils::PROP_SPEED, TransferUtils::PROP_BYTES_TRANSFERRED, TransferUtils::PROP_SECONDS_LEFT }, "transfer_failed"); } void TransferApi::on(ConnectionManagerListener::Failed, const ConnectionQueueItem* aCqi, const string& aReason) noexcept { auto t = findTransfer(aCqi->getToken()); if (!t) { return; } onFailed(t, aCqi->getUser().user->isSet(User::OLD_CLIENT) ? STRING(SOURCE_TOO_OLD) : aReason); } void TransferApi::onTransferUpdated(const TransferInfoPtr& aTransfer, const PropertyIdSet& aUpdatedProperties, const string& aSubscriptionName) noexcept { view.onItemUpdated(aTransfer, aUpdatedProperties); if (subscriptionActive("transfer_updated")) { send("transfer_updated", Serializer::serializePartialItem(aTransfer, TransferUtils::propertyHandler, aUpdatedProperties)); } if (!aSubscriptionName.empty() && subscriptionActive(aSubscriptionName)) { // Serialize all properties send(aSubscriptionName, Serializer::serializeItem(aTransfer, TransferUtils::propertyHandler)); } } void TransferApi::updateQueueInfo(TransferInfoPtr& aInfo) noexcept { { auto qi = QueueManager::getInstance()->getQueueInfo(aInfo->getHintedUser()); if (!qi) { return; } auto type = Transfer::TYPE_FILE; if (qi->getFlags() & QueueItem::FLAG_PARTIAL_LIST) type = Transfer::TYPE_PARTIAL_LIST; else if (qi->getFlags() & QueueItem::FLAG_USER_LIST) type = Transfer::TYPE_FULL_LIST; aInfo->setType(type); aInfo->setTarget(qi->getTarget()); aInfo->setSize(qi->getSize()); aInfo->setQueueToken(qi->getToken()); } aInfo->setState(TransferInfo::STATE_WAITING); aInfo->setStatusString(STRING(CONNECTING)); onTransferUpdated(aInfo, { TransferUtils::PROP_STATUS, TransferUtils::PROP_TARGET, TransferUtils::PROP_TYPE, TransferUtils::PROP_NAME, TransferUtils::PROP_SIZE, TransferUtils::PROP_QUEUE_ID }, Util::emptyString); } void TransferApi::on(ConnectionManagerListener::Connecting, const ConnectionQueueItem* aCqi) noexcept { auto t = findTransfer(aCqi->getToken()); if (!t) { return; } updateQueueInfo(t); } void TransferApi::on(ConnectionManagerListener::Forced, const ConnectionQueueItem* aCqi) noexcept { auto t = findTransfer(aCqi->getToken()); if (!t) { return; } t->setState(TransferInfo::STATE_WAITING); t->setStatusString(STRING(CONNECTING_FORCED)); onTransferUpdated(t, { TransferUtils::PROP_STATUS }, Util::emptyString); } void TransferApi::on(ConnectionManagerListener::UserUpdated, const ConnectionQueueItem* aCqi) noexcept { auto t = findTransfer(aCqi->getToken()); if (!t) { return; } onTransferUpdated(t, { TransferUtils::PROP_USER }, Util::emptyString); } void TransferApi::on(DownloadManagerListener::Failed, const Download* aDownload, const string& aReason) noexcept { auto t = findTransfer(aDownload->getToken()); if (!t) { return; } auto status = aReason; if (aDownload->isSet(Download::FLAG_SLOWUSER)) { status += ": " + STRING(SLOW_USER); } else if (aDownload->getOverlapped() && !aDownload->isSet(Download::FLAG_OVERLAP)) { status += ": " + STRING(OVERLAPPED_SLOW_SEGMENT); } onFailed(t, status); } void TransferApi::starting(TransferInfoPtr& aInfo, const Transfer* aTransfer) noexcept { aInfo->setBytesTransferred(aTransfer->getPos()); aInfo->setTarget(aTransfer->getPath()); aInfo->setStarted(GET_TICK()); aInfo->setType(aTransfer->getType()); aInfo->setSize(aTransfer->getSegmentSize()); aInfo->setState(TransferInfo::STATE_RUNNING); aInfo->setIp(aTransfer->getUserConnection().getRemoteIp()); aInfo->setEncryption(aTransfer->getUserConnection().getEncryptionInfo()); OrderedStringSet flags; aTransfer->appendFlags(flags); aInfo->setFlags(flags); onTransferUpdated(aInfo, { TransferUtils::PROP_STATUS, TransferUtils::PROP_SPEED, TransferUtils::PROP_BYTES_TRANSFERRED, TransferUtils::PROP_TIME_STARTED, TransferUtils::PROP_SIZE, TransferUtils::PROP_TARGET, TransferUtils::PROP_QUEUE_ID, TransferUtils::PROP_NAME, TransferUtils::PROP_TYPE, TransferUtils::PROP_IP, TransferUtils::PROP_ENCRYPTION, TransferUtils::PROP_FLAGS }, "transfer_starting"); } void TransferApi::on(DownloadManagerListener::Requesting, const Download* aDownload, bool /*hubChanged*/) noexcept { starting(aDownload, STRING(REQUESTING), true); } void TransferApi::starting(const Download* aDownload, const string& aStatus, bool aFullUpdate) noexcept { auto t = findTransfer(aDownload->getToken()); if (!t) { return; } t->setStatusString(aStatus); if (aFullUpdate) { starting(t, aDownload); } else { // All flags weren't known when requesting OrderedStringSet flags; aDownload->appendFlags(flags); t->setFlags(flags); // Size was unknown for filelists when requesting t->setSize(aDownload->getSegmentSize()); onTransferUpdated(t, { TransferUtils::PROP_STATUS, TransferUtils::PROP_FLAGS, TransferUtils::PROP_SIZE }, "transfer_starting"); } } void TransferApi::on(DownloadManagerListener::Starting, const Download* aDownload) noexcept { // No need for full update as it's done in the requesting phase starting(aDownload, STRING(DOWNLOAD_STARTING), false); } void TransferApi::on(UploadManagerListener::Starting, const Upload* aUpload) noexcept { auto t = findTransfer(aUpload->getToken()); if (!t) { return; } starting(t, aUpload); } TransferInfoPtr TransferApi::findTransfer(const string& aToken) const noexcept { RLock l(cs); auto i = transfers.find(aToken); return i != transfers.end() ? i->second : nullptr; } void TransferApi::on(DownloadManagerListener::Complete, const Download* aDownload, bool) noexcept { onTransferCompleted(aDownload, true); } void TransferApi::on(UploadManagerListener::Complete, const Upload* aUpload) noexcept { onTransferCompleted(aUpload, false); } void TransferApi::onTransferCompleted(const Transfer* aTransfer, bool aIsDownload) noexcept { auto t = findTransfer(aTransfer->getToken()); if (!t) { return; } t->setStatusString(aIsDownload ? STRING(DOWNLOAD_FINISHED_IDLE) : STRING(UPLOAD_FINISHED_IDLE)); t->setSpeed(-1); t->setTimeLeft(-1); t->setBytesTransferred(aTransfer->getSegmentSize()); t->setState(TransferInfo::STATE_FINISHED); onTransferUpdated(t, { TransferUtils::PROP_STATUS, TransferUtils::PROP_SPEED, TransferUtils::PROP_SECONDS_LEFT, TransferUtils::PROP_TIME_STARTED, TransferUtils::PROP_BYTES_TRANSFERRED }, "transfer_completed"); } }
[ "maksis@adrenaline-network.com" ]
maksis@adrenaline-network.com
f0d60a1d7a0e36e04b874e8d95bef6000c4e5ba3
012b5915900e39c3182cbfa25ff9f61b6d0f0cbd
/Komputer.cpp
5ecde49a3bd0fa7dbf47a6f52d28a16c74fbbd24
[]
no_license
robwin311/Kolko-i-krzyzyk
1d7f622257a8a8f49cce7c71fcba665df36e3011
675d2969484e1821b5b568d0202b5d832f9f64e0
refs/heads/master
2021-01-25T10:56:08.521266
2017-06-10T15:17:59
2017-06-10T15:17:59
93,893,163
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
4,160
cpp
#include "Gracz.hh" #include "Komputer.hh" #include "stdlib.h" #include "time.h" #include <iostream> #include <algorithm> using namespace std; /* --------------------------------------------------------------------------------- */ /* --------------------------- Konstruktory/Destruktory ---------------------------- */ /* --------------------------------------------------------------------------------- */ Komputer::Komputer(char Symbol) : Gracz::Gracz(Symbol){ // Opis: Konstruktor klasy Komputer // IN: Symbol - wartość inicjalizująca pole _Symbol // OUT: Tworzy obiekt klasy Komputer } Komputer::~Komputer(){ // Opis: Destruktor klasy Komputer // IN: Brak. // OUT: Usuwa obiekt klasy Komputer } /* --------------------------------------------------------------------------------- */ /* -------------------------------- Getery/Setery ---------------------------------- */ /* --------------------------------------------------------------------------------- */ void Komputer::WykonajRuch(Plansza* Gameboard){ // Opis: Metoda obsługująca ruch komputera // IN: Brak. // OUT: Wykonuje ruch komputera int MoveVal = -1000; int BestMoveVal = -1000; int alpha = 1000; int beta = -1000; int w = INT_MAX; int k = INT_MAX; for(int i = 0; i < Gameboard->GetSize(); ++i){ for(int j = 0; j < Gameboard->GetSize(); ++j){ if(Gameboard->GetGame()[i][j] == ' '){ Gameboard->SetSymbolOnBoard(i, j, GetSymbol()); MoveVal = MinIMax(Gameboard, 0, false, alpha, beta); Gameboard->SetSymbolOnBoard(i, j, ' ', true); if(MoveVal > BestMoveVal){ w = i; k = j; BestMoveVal = MoveVal; // n } } } } Gameboard->SetSymbolOnBoard(w, k, GetSymbol()); } void Komputer::PierwszyRuch(Plansza* Game)const{ // Opis: Metoda wykonująca ruch jeżeli Komputer gra jako pierwszy // IN: Game - wskaźnik na planszę, na której komputer wykonuje ruch // OUT: Ruch wykonany na planszy. int w = (rand() % (Game->GetSize() - 5)) + 3; int k = (rand() % (Game->GetSize() - 5)) + 3; Game->SetSymbolOnBoard(w-1, k-1, Gracz::GetSymbol()); } int Komputer::Ocen(Plansza* Gameboard, int Depth){ // Opis: Metoda oceniająca sytuację na planszy wywoływana przez algorytm minimax // IN: Gameboard - Plansza z aktualną sytuacją // RETURN: -1/0/1 w zależności od tego że porażka/remis/zwycięstwo Gracz* Winner = Gameboard->CheckForVictory(); if(Winner == NULL) return 0; else if(Winner == this) return 100 - Depth; else return -100 - Depth; } int Komputer::MinIMax(Plansza* Gameboard, int Depth, bool IsMax, int& alpha, int& beta){ // Opis: Implementacja algorytmu MiniMax, sztucznej inteligencji odpowiedzialnej za rozgrywkę w trybie jednoosobowym // IN: Gameboard - referencja do analizowanego stanu planszy w grze // IN: Depth - głędokość wywołań rekurencyjnych // IsMax // RETURN: if(Depth == 11 - 6) return 0; int Score = Ocen(Gameboard, Depth); if(Score != 0) return Score; else if(Gameboard->IsFull()) return Score;//y; if(IsMax == true){ int Maximum = -100; for(int i = 0; i < Gameboard->GetSize(); ++i){ for(int j = 0; j < Gameboard->GetSize(); ++j){ if(!(beta >= Score)){ if(Gameboard->GetGame()[i][j] == ' '){ Gameboard->SetSymbolOnBoard(i, j, GetSymbol()); Maximum = max(Maximum, MinIMax(Gameboard, Depth + 1, false, alpha, beta)); beta = Maximum; //Maximum += MinIMax(Gameboard, Depth + 1, false); Gameboard->SetSymbolOnBoard(i, j, ' ', true); } } } } return Maximum; } else{ int Minimum = 100; char Symbol; Symbol = (Gameboard->GetOpponent(this)->GetSymbol()); for(int i = 0; i < Gameboard->GetSize(); ++i){ for(int j = 0; j < Gameboard->GetSize(); ++j){ if(alpha > Score){ if(Gameboard->GetGame()[i][j] == ' '){ Gameboard->SetSymbolOnBoard(i, j, Symbol); Minimum = min(Minimum, MinIMax(Gameboard, Depth + 1, true, alpha, beta)); //Minimum += MinIMax(Gameboard, Depth + 1, true); Gameboard->SetSymbolOnBoard(i, j, ' ', true); } } } } return Minimum; } }
[ "robertwinkler147@gmail.com" ]
robertwinkler147@gmail.com
6e86729ebe7dd085dc6040a778cc418c854bfc14
e716e98f78fe824f6f1a2bb06d3f8c4cc07d09b7
/noi/动态规划/2985.cpp
0fa344ed120fd8dbfda65f2603bdde48bb7ca4e7
[]
no_license
mingsjtu/OJ_exercise
f4bac0c8964e0061e4108f76b1cdff76286a6d1e
7837332b6c4c2d8eac327c6c7359cbb28b931d11
refs/heads/master
2020-08-18T18:32:11.264653
2019-10-19T06:08:22
2019-10-19T06:08:22
215,821,254
1
0
null
null
null
null
UTF-8
C++
false
false
409
cpp
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int dp[1005]; int a[22]; int num; int all; int main() { int i,j,k; cin>>num>>all; for(i=0;i<num;i++) cin>>a[i]; memset(dp,0,sizeof(dp)); dp[0]=1; dp[a[0]]=1; for(i=1;i<num;i++) { for(j=all;j>=a[i];j--) { dp[j]+=dp[j-a[i]]; } } cout<<dp[all]<<endl; }
[ "mingsjtu@163.com" ]
mingsjtu@163.com
5daa8f66806960b734716a93b56f0cdfd08efbb3
ab039ca37f9540f37674aa1f6e75031ec9dcbbf3
/giroscopio.cpp
3e4f56ad28caefdcfbf8e542c3881b235d08994b
[]
no_license
lennedy/lib_giroscopio
06a1284eb61e3b46dc79709ddf34e3144db40ffc
314fff22f3ada669a77afd9ea477c6dd8ee08e20
refs/heads/master
2020-04-06T06:25:02.147069
2017-03-04T04:11:02
2017-03-04T04:11:02
82,891,456
0
0
null
null
null
null
UTF-8
C++
false
false
4,146
cpp
#include "giroscopio.h" giroscopio * giroscopio::instance; giroscopio::giroscopio(){ instance = this; } int giroscopio::init(){ Wire.begin(); //TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz) // initialize device mpu.initialize(); if(!mpu.testConnection()) return ERR_MPU6050_CONNECTION_FAILED; // Serial.println( ? F("MPU6050 connection successful") : F("MPU6050 connection failed")); // wait for ready // Serial.println(F("\nSend any character to begin DMP programming and demo: ")); // while (Serial.available() && Serial.read()); // empty buffer // while (!Serial.available()); // wait for data // while (Serial.available() && Serial.read()); // empty buffer again // load and configure the DMP // Serial.println(F("Initializing DMP...")); devStatus = mpu.dmpInitialize(); // supply your own gyro offsets here, scaled for min sensitivity mpu.setXGyroOffset(220); mpu.setYGyroOffset(76); mpu.setZGyroOffset(-85); mpu.setZAccelOffset(1788); // 1688 factory default for my test chip // make sure it worked (returns 0 if so) if (devStatus == ERR_NO) { // turn on the DMP, now that it's ready //Serial.println(F("Enabling DMP...")); mpu.setDMPEnabled(true); // enable Arduino interrupt detection //Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)...")); // attachInterrupt(0, dmpDataReady, RISING); mpuIntStatus = mpu.getIntStatus(); // set our DMP Ready flag so the main loop() function knows it's okay to use it //Serial.println(F("DMP ready! Waiting for first interrupt...")); dmpReady = true; // get expected DMP packet size for later comparison packetSize = mpu.dmpGetFIFOPacketSize(); } else { // ERROR! // 1 = initial memory load failed // 2 = DMP configuration updates failed // (if it's going to break, usually the code will be 1) //Serial.print(F("DMP Initialization failed (code ")); //Serial.print(devStatus); //Serial.println(F(")")); return devStatus; } attachInterrupt(0, isr, RISING); return ERR_NO; } void giroscopio::isr(){ instance->interrupcao(); } void giroscopio::interrupcao(){ // reset interrupt flag and get INT_STATUS byte mpuInterrupt = true; } void giroscopio::ler(YPR &leitura){ // if programming failed, don't try to do anything if (!dmpReady) return; mpuIntStatus = mpu.getIntStatus(); // get current FIFO count fifoCount = mpu.getFIFOCount(); // check for overflow (this should never happen unless our code is too inefficient) if ((mpuIntStatus & 0x10) || fifoCount == 1024) { // reset so we can continue cleanly mpu.resetFIFO(); Serial.println(F("FIFO overflow!")); // otherwise, check for DMP data ready interrupt (this should happen frequently) } else if (mpuIntStatus & 0x02) { // wait for correct available data length, should be a VERY short wait while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount(); // read a packet from FIFO mpu.getFIFOBytes(fifoBuffer, packetSize); // track FIFO count here in case there is > 1 packet available // (this lets us immediately read more without waiting for an interrupt) fifoCount -= packetSize; // display Euler angles in degrees mpu.dmpGetQuaternion(&q, fifoBuffer); mpu.dmpGetGravity(&gravity, &q); mpu.dmpGetYawPitchRoll(ypr, &q, &gravity); leitura.yaw = ypr[0]; leitura.pitch= ypr[1]; leitura.roll = ypr[2]; /* Serial.print("ypr\t"); Serial.print(leitura.yaw * 180/M_PI); Serial.print("\t"); Serial.print(leitura.pitch * 180/M_PI); Serial.print("\t"); Serial.println(leitura.roll * 180/M_PI); Serial.print("\t"); */ // Serial.println(fifoCount); // mpu.resetFIFO(); } } void giroscopio::ler(float &x, float &y, float &z){ YPR a; ler(a); x=a.roll; y=a.pitch; z=a.yaw; }
[ "lennedy@gmail.com" ]
lennedy@gmail.com
441f420efe2702f8ef39d05d54ec28254a0b472c
6e73f2b775790c0027763eb208deb3d72191b90f
/archived/vs_solution/fluid_substrate/NWSimulation.h
8525e325694bdf11ac79374bc10c17cfdf02704c
[]
no_license
mvarga6/Nematic-Worms
e850bf3c5354574ee9749f499683d47a0c7dbfc8
ffbfbd3392b3147e4f941b3fcd27957ffada05f7
refs/heads/master
2023-07-20T08:25:53.012271
2021-10-11T00:09:12
2021-10-11T00:09:12
45,878,432
0
1
null
2023-07-06T22:22:45
2015-11-10T01:14:57
C++
UTF-8
C++
false
false
6,792
h
#ifndef __SIMULATION_H__ #define __SIMULATION_H__ // 2D // ----------------------------------------- //////// NEMATIC WORMS PROJECT //////// // ----------------------------------------- #include "NWmain.h" #include "NWWorms.h" #include "NWRandomNumberGenerator.h" #include "NWWormsParameters.h" #include "NWSimulationParameters.h" #include "NWKernels.h" #include "NWXYZIO.h" // -------------------------------------------- //////// CLASS DEFINING A SIMULATION /////// // -------------------------------------------- class NWSimulation { //.. simulation components Worms * worms; WormsParameters * params; GRNG * rng; SimulationParameters * simparams; //.. file stream std::ofstream fxyz; //.. outputfile std::string outputfile; //.. time float time; //.. clocking clock_t timer; public: NWSimulation(int argc, char *argv[]); ~NWSimulation(); void Run(); private: void XYZPrint(int itime); void DisplayErrors(); }; //------------------------------------------------------------------------------------------- // IMPLEMENTATION HERE //------------------------------------------------------------------------------------------- NWSimulation::NWSimulation(int argc, char *argv[]){ //.. setup parameters (should be done with cmdline input) this->params = new WormsParameters(); Init(this->params, argc, argv); //.. setup simulation parameters this->simparams = new SimulationParameters(); Init(this->simparams, argc, argv, this->outputfile); //.. show parameters on device CheckParametersOnDevice <<< 1, 1 >>>(); ErrorHandler(cudaDeviceSynchronize()); //.. setup random number generator this->rng = new GRNG(_D_ * params->_NPARTICLES, 0.0f, 1.0f); //.. define the worms this->worms = new Worms(); //.. initial worms object this->time = 0.0f; this->worms->Init(this->rng, this->params, this->simparams, !this->simparams->_LMEM, 512); //.. outputfile this->fxyz.open(this->outputfile.c_str()); if (!this->fxyz.is_open()) printf("\n***\nError opening output file: %s!\n***", this->outputfile.c_str()); else printf("\nWriting data to outfile: %s\n", this->outputfile.c_str()); } //------------------------------------------------------------------------------------------- NWSimulation::~NWSimulation(){ delete this->worms; delete this->rng; delete this->params; delete this->simparams; } //------------------------------------------------------------------------------------------- void NWSimulation::Run(){ //this->XYZPrint(0); //return; //.. grab needed parameters const int nsteps = this->simparams->_NSTEPS; const int nsteps_inner = this->simparams->_NSTEPS_INNER; const float dt = this->simparams->_DT; const float xtarget = this->params->_XLINKERDENSITY; const int xstart = this->params->_XSTART; int xhold = this->params->_XHOLD; //.. setup cross-linker ramping float xdensity, xramp; if (this->params->_XRAMP) xdensity = 0.0f; // if ramping, init to zero else xdensity = xtarget; // if not, init to target if (xhold < 0) xhold = nsteps; // default to end of simulation, // else already set properly //.. calculate ramping rate (defaults to 0.0f for no xlink options) xramp = (xtarget - xdensity) / float(xhold - xstart); //.. check for errors before starting this->DisplayErrors(); //.. start timer clock this->timer = clock(); //.. MAIN SIMULATION LOOP for (int itime = 0; itime < nsteps; itime++){ //.. setup neighbors for iteration this->worms->ResetNeighborsList(itime); //.. inner loop for high frequency potentials for (int jtime = 0; jtime < nsteps_inner; jtime++){ this->worms->ZeroForce(); this->worms->InternalForces(); this->worms->BendingForces(); //this->worms->XLinkerForces(itime, xdensity); this->worms->LJForces(); this->worms->QuickUpdate(); } //.. finish time set with slow potential forces this->worms->ZeroForce(); this->worms->AutoDriveForces(itime); //this->worms->LandscapeForces(); this->worms->SlowUpdate(); this->XYZPrint(itime); this->worms->DisplayClocks(itime); this->DisplayErrors(); //.. adjust tickers if (itime > xstart && itime < xhold) // in ramping range xdensity += xramp; // no effect if not ramping this->time += dt; } this->fxyz.close(); } //------------------------------------------------------------------------------------------- void NWSimulation::XYZPrint(int itime){ //.. only print when it itime == 0 if (itime % simparams->_FRAMERATE != 0) return; //.. count and grab errors static int frame = 1; this->DisplayErrors(); //.. pull data from GPU this->worms->DataDeviceToHost(); //this->worms->ColorXLinked(); //.. print to ntypes const int maxTypes = 5; const float ka_ratio = this->params->_Ka_RATIO; //const int ntypes = (ka_ratio < 1.0f ? 2 : maxTypes); const char ptypes[maxTypes] = { 'A', 'B', 'C', 'D', 'E' }; const int N = params->_NPARTICLES; const int nworms = params->_NWORMS; int nBlownUp = 0; this->fxyz << N + 4 << std::endl; this->fxyz << nw::util::xyz::makeParameterLine(this->params, this->simparams, __NW_VERSION__); for (int i = 0; i < params->_NPARTICLES; i++){ const int w = i / params->_NP; // choose 0 or 1,2,3,4 type const int t = (w > nworms*ka_ratio ? 0 : w % (maxTypes - 1) + 1); float _r[3] = { 0, 0, 0 }; // always 3d for_D_ _r[d] = worms->r[i + d*N]; //float x = worms->r[i], y = worms->r[i + N], z = 0.0f; //char c = worms->c[i]; const char c = ptypes[t]; //if (abs(z) > 100.0f) nBlownUp++; this->fxyz << c << " " << _r[0] << " " << _r[1] << " " << _r[2] << std::endl; } this->fxyz << "F " << 0 << " " << 0 << " 0 " << std::endl; this->fxyz << "F " << simparams->_XBOX << " " << 0 << " 0 " << std::endl; this->fxyz << "F " << 0 << " " << simparams->_YBOX << " 0 " << std::endl; this->fxyz << "F " << simparams->_XBOX << " " << simparams->_YBOX << " 0 " << std::endl; //.. report blown up particles if (nBlownUp > 0) printf("\n%i particles blown up", nBlownUp); if (nBlownUp >= _LOSS_TOLERANCE) abort(); //.. clocking clock_t now = clock(); double frame_t = (now - this->timer) / (double)(CLOCKS_PER_SEC * 60.0); double frames_left = double(this->simparams->_NSTEPS / this->simparams->_FRAMERATE) - (double)(frame - 1); double mins_left = frame_t * frames_left; double hours_left = mins_left / 60.0; int hours = int(hours_left); int mins = int((hours_left - (double)hours) * 60); printf("\rframe %i: %i hrs %i mins remaining", frame++, hours, mins); this->timer = clock(); } //------------------------------------------------------------------------------------------- void NWSimulation::DisplayErrors(){ this->rng->DisplayErrors(); this->worms->DisplayErrors(); } //------------------------------------------------------------------------------------------- #endif
[ "mvarga6@kent.edu" ]
mvarga6@kent.edu
91ad3ba7930061ed90423e07ab102d35bc9dc133
b30ddfaa661e6e65f7abc0d807f440ec8e71102d
/Sample1-Trace_the_memory/include/type_traits.h
c760512108570675ffeb8e002649eb9cd19ee7cb
[]
no_license
jiahao42/LambSTL
cd1c105e2b5b4a981ca72a0f03743829132a803d
69d7680a00a83adca59920744f6656833750d99c
refs/heads/master
2021-06-12T13:01:01.726308
2017-04-19T05:27:21
2017-04-19T05:27:21
75,935,219
5
1
null
null
null
null
GB18030
C++
false
false
1,035
h
#ifndef __LAMB_STL_INTERNAL_TYPE_TRAITS_H_ #define __LAMB_STL_INTERNAL_TYPE_TRAITS_H_ struct __true_type{}; struct __false_type{}; /* 下列是最基础的traits,接受任何型别的参数,并将各属性都设置成__false_type __true_type将在相应的特化版本中给出 */ template <class type> struct __type_traits{ typedef __true_type this_dummy_member_must_be_first; typedef __false_type has_trivial_default_constructor; typedef __false_type has_trivial_copy_constructor; typedef __false_type has_trivial_assignment_operator; typedef __false_type has_trivial_destructor; typedef __false_type is_POD_type; }; /* 特化版本之一 针对int */ //__STL_TEMPLATE_NULL template<> struct __type_traits<int>{ typedef __true_type this_dummy_member_must_be_first; typedef __true_type has_trivial_default_constructor; typedef __true_type has_trivial_copy_constructor; typedef __true_type has_trivial_assignment_operator; typedef __true_type has_trivial_destructor; typedef __true_type is_POD_type; }; #endif
[ "caterpillarous@yahoo.com" ]
caterpillarous@yahoo.com
60b13fc9dfe10c5ab10aa996d4300c2dd3d1aebd
c4cd24e7da52a6b60b5c63ea76de1a1a97a0c31d
/chuck_allocator/Allocator.cpp
40e3f8d571c57a4591c000a32423dc195308a836
[]
no_license
shubinsa/made-cpp-2020-hw
24c4e345803ab9cdb74ff6beaf7468d245cc453e
6e9f7e0460901ea2a714e75ccb03ab31a24e3720
refs/heads/master
2023-01-21T18:48:25.769391
2020-12-04T10:06:52
2020-12-04T10:06:52
297,466,485
1
0
null
2020-12-04T10:06:53
2020-09-21T21:35:10
C++
UTF-8
C++
false
false
5,254
cpp
#include <iostream> using namespace std; template<typename T> class Allocator { public: using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using propagate_on_container_move_assignment = std::true_type; //ругается на шаблон - не могу понять //using rebind = template< class U > struct rebind { typedef allocator<U> other; }; using rebind = struct rebind { typedef Allocator<T> other; }; using is_always_equal = std::true_type; private: class chunk { private: class memory { public: memory(char* ptr, size_t count, memory* next = NULL) :ptr(ptr), count(count), next(next) {} char* ptr; size_t count; memory* next; }; memory* busy; public: char* data; chunk* next; chunk(chunk* next = NULL) : next(next) { data = new char[N * sizeof(T)]; } ~chunk() { memory* temp = busy; while (temp != NULL) { memory* del = temp; temp = temp->next; delete del; } busy = NULL; next = NULL; delete[] data; data = NULL; } char* get(size_t size) { if (busy != NULL) { //если что-то уже занято if (busy->ptr - data >= size) { //есть ли до первого занятого есть место busy->next = new memory(data, size); //если да, то добавляем return busy->next->ptr; } if (busy->next == NULL) //если элемент только один if (data + N - (busy->ptr + busy->count) >= size) { //проверяем останется ли место после него busy->next = new memory(busy->ptr + busy->count, size); //если да, то добавляем return busy->next->ptr; } else return NULL; //места нет нигде (до или после) - при условии одного элемента memory* p1 = busy; memory* p2 = busy->next; while (p2 != NULL) { //пока не переберём все пары p1-p2 if (p2->ptr - (p1->ptr + p1->count) >= size) { //если есть место-то между занятыми p1->next = new memory(p1->ptr + p1->count, size, p2); //то добавляем return p1->next->ptr; } p1 = p2; p2 = p2->next; } if (data + N - (p1->ptr + p1->count) >= size) { //проверяем останется ли место после последнего (p1) p1->next = new memory(p1->ptr + p1->count, size); //если да, то добавляем return p1->next->ptr; } return NULL; //если ничего не нашли } else { busy = new memory(data, size, NULL); return busy->ptr; } } bool del(T* ptr) { if (busy != NULL) { if (busy->ptr == (char*) ptr) { memory* del = busy; busy = busy->next; delete del; return true; } memory* temp = busy; while (temp->next != NULL) if (temp->next->ptr == (char*)ptr) { memory* del = temp->next; temp->next = del->next; delete del; return true; } } return false; } static const size_t N = 100; }; public: Allocator() { tail = NULL; count = new size_t; *count = 0; } Allocator(const Allocator& B) { tail = B.tail; count = B.count; (*count)++; } ~Allocator() { if (*count > 1) (*count)--; else { chunk* temp = tail; while (temp != NULL) { chunk* del = temp; temp = temp->next; delete del; } tail = NULL; delete[] count; count = NULL; } } T* allocate(size_t size) { if (size <= chunk::N) { T* ptr = NULL; tail = tail != NULL ? tail : (new chunk); //выделение памяти под первый chunk* temp = tail; do { ptr = (T*)temp->get(size); temp = temp->next; } while (ptr == NULL && temp != NULL); //пока в имеющихся чанках не будет найдено простанство или они не кончатся if (temp == NULL && ptr == NULL) { //если чанки кончились и место не найдено, то добавляем новый чанк tail = new chunk(tail); ptr = (T*)tail->get(size); } return ptr; } return NULL; } //надо ли использовать размер? void deallocate(T* ptr, size_t size) { if (tail != NULL) { chunk* temp = tail; while (temp != NULL && !temp->del(ptr)) temp = temp->next; } } static size_t max_size() { return chunk::N; } Allocator& operator =(const Allocator& B) { this->~Allocator(); tail = B.tail; (*B.count)++; count = B.count; return *this; } //ругается на шаблон - не могу понять /*<template typename ...Args> void construct(T* ptr, const Args&&... args) { return new(ptr) T(args...); };*/ void construct(T* ptr) { return new(ptr) T(); }; void destroy(T* ptr) { ptr->~T(); }; private: size_t* count; chunk* tail; }; int main() { Allocator<int> alloc; Allocator<int> pa; int* p = alloc.allocate(5); alloc.deallocate(p, 5); pa = alloc; Allocator<int> alloc2(pa); alloc.max_size(); return 0; }
[ "shubinsa1@gmail.com" ]
shubinsa1@gmail.com
fafae3c8608223890bd6a61b99c49c21f3e69251
b49a0837efa4977e1ae4657dd816f279af003c28
/Calculator/CalculatorPro.cpp
ff8dbb33530a5ed93baffc11b1ded33c4be3a839
[]
no_license
leungyukshing/DataStructure
3cbc695534f52a62061fb62f798a785106583c60
5119c1b3cf421849d20902d3af5d67a5ce08dda2
refs/heads/master
2021-09-06T21:19:41.919296
2018-02-11T15:43:06
2018-02-11T15:43:06
117,672,052
0
0
null
null
null
null
UTF-8
C++
false
false
3,865
cpp
#include <iostream> #include <cstring> #include <stack> #include <string> #include <vector> using namespace std; class CalculatorPro { public: CalculatorPro(); private: void read(); bool isoperator(char op); int priority(char op); void postfix(); double read_number(char str[], int *i); double compute(); vector<char> pre; char post[100]; int size; }; CalculatorPro::CalculatorPro() { size = 0; read(); postfix(); //cout << post << endl; cout << compute() << endl; } void CalculatorPro::read() { string temp; cout << "Please input the expression(end with '='): "; cin >> temp; for (int i = 0; i < temp.size(); i++) { char ch = temp[i]; pre.push_back(ch); } if (pre[0] == '-') { pre.insert(pre.begin(), '0'); } for (int i = 0; i < pre.size(); i++) { if (pre[i] == '(' && pre[i+1] == '-') { pre.insert(pre.begin()+i+1, '0'); } } } bool CalculatorPro::isoperator(char op) { switch(op) { case '+': case '-': case '*': case '/': return 1; default: return 0; } } int CalculatorPro::priority(char op) { switch(op) { case '=': return -1; case '(': return 0; case '+': case '-': return 1; case '*': case '/': return 2; default: return -1; } } void CalculatorPro::postfix() { int i = 0, j = 0; stack<char> st; // used to store operators st.push('='); while(pre[i] != '=') { // judge whether it is a number(both int and double) if ((pre[i] >= '0' && pre[i] <= '9') || pre[i] == '.') { post[j++] = pre[i]; size++; } else if (pre[i] == '(') { st.push(pre[i]); } else if (pre[i] == ')') { while (st.top() != '(') { post[j++] = st.top(); st.pop(); size++; } st.pop(); // pop the'(' } else if (isoperator(pre[i])) { post[j++] = ' '; size++; while (priority(pre[i]) <= priority(st.top())) { post[j++] = st.top(); st.pop(); size++; } st.push(pre[i]); } i++; } while (!st.empty()) { post[j++] = st.top(); st.pop(); size++; } } double CalculatorPro::read_number(char str[], int *i) { double x = 0; int k = 0; while (str[*i] >= '0' && str[*i] <= '9') { x = x*10 + (str[*i] - '0'); (*i)++; } // decimal part if (str[*i] == '.') { (*i)++; while (str[*i] >= '0' && str[*i] <= '9') { x = x * 10 + (str[*i] - '0'); (*i)++; k++; } } while(k != 0) { x /= 10.0; // move decimal point k--; } return x; } double CalculatorPro::compute() { stack<double> st_num; int i = 0; double op1, op2; while (post[i] != '=') { if (post[i] >= '0' && post[i] <= '9') { st_num.push(read_number(post,&i)); } else if (post[i] == ' ') { i++; } else if (post[i] == '+') { op2 = st_num.top(); st_num.pop(); op1 = st_num.top(); st_num.pop(); st_num.push(op1 + op2); i++; } else if (post[i] == '-') { op2 = st_num.top(); st_num.pop(); op1 = st_num.top(); st_num.pop(); st_num.push(op1 - op2); i++; } else if (post[i] == '*') { op2 = st_num.top(); st_num.pop(); op1 = st_num.top(); st_num.pop(); st_num.push(op1 * op2); i++; } else if (post[i] == '/') { op2 = st_num.top(); st_num.pop(); op1 = st_num.top(); st_num.pop(); st_num.push(op1 / op2); i++; } else { exit(0); } } return st_num.top(); } int main() { CalculatorPro ca; return 0; }
[ "jacky14.liang@gmail.com" ]
jacky14.liang@gmail.com
7ecbaeb88d960bc4a0eb2a8c537cea75653b91ee
916109bf168239202442498e568b2bfc9a8bc8a9
/src/asiTestEngine/reportgen/asiTestEngine_DescriptionProc.cpp
2878805f2f8705ae68990ff12b27ae41ee697eae
[ "BSD-3-Clause", "MIT" ]
permissive
yeeeeeeti/3D_feature_extract
35da69cd64cd6ed6c92fd4541da5de7bb96dc2b6
6297daa8afaac09aef9b44858e74fb2a95e1e7c5
refs/heads/master
2020-09-05T02:27:30.997017
2019-11-07T01:24:26
2019-11-07T01:24:26
219,956,109
1
0
null
null
null
null
UTF-8
C++
false
false
13,242
cpp
//----------------------------------------------------------------------------- // Created on: November 2013 //----------------------------------------------------------------------------- // Copyright (c) 2013-pesent, Sergey Slyadnev // 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 the copyright holder(s) nor the // names of all 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 AUTHORS 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. //----------------------------------------------------------------------------- // Own include #include <asiTestEngine_DescriptionProc.h> // STD includes #include <fstream> //----------------------------------------------------------------------------- bool asiTestEngine_DescriptionProc::Process(const std::string& dir, const std::string& filename, const StrStrMap& vars, const int caseID, const int numFunctions, std::string& title, SeqStr& overviewBlocks, SeqStr& detailsBlocks) { /* ================== * Prepare filename * ================== */ std::string fullFilename, dirCopy(dir); char dir_last = dir.at(dir.size() - 1); if ( dir_last != asiTestEngine_Macro_SLASH && dir_last != asiTestEngine_Macro_RSLASH ) { dirCopy += asiTestEngine_Macro_RSLASH; } fullFilename = dirCopy + filename; /* ======================================= * Read file contents to a single string * ======================================= */ std::ifstream FILE( fullFilename.c_str() ); if ( !FILE.is_open() ) return false; std::string text; while ( !FILE.eof() ) { char str[256]; FILE.getline(str, 256); text += str; text += asiTestEngine_Macro_NL_STR; } FILE.close(); /* ================== * Extract sections * ================== */ std::string title_tmp; SeqStr overviewBlocks_tmp, detailsBlocks_tmp; // Extract sections from monolith text block extractBlocks(numFunctions, text, title_tmp, overviewBlocks_tmp, detailsBlocks_tmp); /* ================== * Expand variables * ================== */ // Expand title title = expandVariables(title_tmp, vars, ""); // Null string means "no scope" // Expand overview blocks for ( int block = 0; block < (int) overviewBlocks_tmp.size(); ++block ) overviewBlocks.push_back( expandVariables( overviewBlocks_tmp[block], vars, varScope(caseID, block + 1) ) ); // Expand details blocks for ( int block = 0; block < (int) detailsBlocks_tmp.size(); ++block ) detailsBlocks.push_back( expandVariables( detailsBlocks_tmp[block], vars, varScope(caseID, block + 1) ) ); return true; } //----------------------------------------------------------------------------- void asiTestEngine_DescriptionProc::extractBlocks(const int numFunctions, const std::string& text, std::string& title, SeqStr& overviewBlocks, SeqStr& detailsBlocks) { enum ReadMode { Read_Undefined, // We do not know what is being read currently Read_Title, // Well, the currently read line is related to [TITLE] Read_Overview, // Now we read [OVERVIEW] section Read_Details // And [DETAILS] section goes now } readMode = Read_Undefined; // Split text by newline characters std::vector<std::string> textLines; asiAlgo_Utils::Str::Split(text, std::string(1, asiTestEngine_Macro_NL), textLines); // Iterate over the lines int idx_F = 0, idx_L = 0; bool isUnbounded = false; // for ( int l = 0; l < (int) textLines.size(); ++l ) { const std::string& lineToken = textLines[l]; // Skip empty lines if ( isLineOfNulls(lineToken) ) continue; // Choose reading mode if ( lineToken.find(asiTestEngine_Macro_SEC_TITLE) != std::string::npos ) { readMode = Read_Title; continue; } else if ( lineToken.find(asiTestEngine_Macro_SEC_OVERVIEW) != std::string::npos ) { readMode = Read_Overview; extractIndicesFromTag(lineToken, idx_F, idx_L, isUnbounded); continue; } else if ( lineToken.find(asiTestEngine_Macro_SEC_DETAILS) != std::string::npos ) { readMode = Read_Details; extractIndicesFromTag(lineToken, idx_F, idx_L, isUnbounded); continue; } if ( readMode == Read_Undefined ) continue; // We are completely lost in what we are reading... // Accumulate title if ( readMode == Read_Title ) title += (lineToken + asiTestEngine_Macro_NL); // Accumulate overview if ( readMode == Read_Overview ) { int tillIdx = (isUnbounded ? numFunctions : idx_L); // Add empty blocks while ( (int) overviewBlocks.size() < tillIdx ) overviewBlocks.push_back( std::string() ); // Fill blocks for ( int idx = idx_F; idx <= tillIdx; ++idx ) overviewBlocks[idx-1] += (lineToken + asiTestEngine_Macro_NL); } if ( readMode == Read_Details ) { int tillIdx = (isUnbounded ? numFunctions : idx_L); // Enrich collection with empty items while ( (int) detailsBlocks.size() < tillIdx ) detailsBlocks.push_back( std::string() ); // Fill items for ( int idx = idx_F; idx <= tillIdx; ++idx ) detailsBlocks[idx-1] += (lineToken + asiTestEngine_Macro_NL); } } } //----------------------------------------------------------------------------- void asiTestEngine_DescriptionProc::extractIndicesFromTag(const std::string& tag, int& startIdx, int& endIdx, bool& isUnbounded) { // Remove brackets std::string tagBase = asiAlgo_Utils::Str::SubStr(tag, 1, (int) tag.length() - 2); // Extract tokens delimited with ":" std::vector<std::string> tagTokens; asiAlgo_Utils::Str::Split(tagBase, std::string(1, asiTestEngine_Macro_COLON), tagTokens); std::string leftToken = tagTokens[0]; // Left part in "XX:TAG" is interesting // Just simple integer value if ( leftToken.find(asiTestEngine_Macro_MINUS) == std::string::npos ) { startIdx = endIdx = atoi( leftToken.c_str() ); return; } // Looks like a range of indices, so we split it by minus character std::vector<std::string> idxTokens; asiAlgo_Utils::Str::Split(leftToken, std::string(1, asiTestEngine_Macro_MINUS), idxTokens); std::string numStrFirst = idxTokens[0]; std::string numStrLast = idxTokens[1]; if ( numStrLast == asiTestEngine_Macro_ASTERISK_STR ) isUnbounded = true; else isUnbounded = false; // Store range in output startIdx = atoi( numStrFirst.c_str() ); endIdx = (isUnbounded ? 1 : atoi( numStrLast.c_str() ) ); } //----------------------------------------------------------------------------- std::string asiTestEngine_DescriptionProc::expandVariables(const std::string& text, const StrStrMap& vars, const std::string& varsScope) { std::string textExpanded; // Split text by newline characters std::vector<std::string> textLines; asiAlgo_Utils::Str::Split(text, std::string(1, asiTestEngine_Macro_NL), textLines); // Iterate over lines bool isPreOngoing = false; for ( int l = 0; l < (int) textLines.size(); ++l ) { const std::string& lineToken = textLines[l]; if ( !isPreOngoing && isPre(lineToken, true) ) isPreOngoing = true; if ( isPreOngoing && isPre(lineToken, false) ) isPreOngoing = false; std::string lineAdjusted; if ( !isPreOngoing ) { // Split line by words std::vector<std::string> lineWords; asiAlgo_Utils::Str::Split(lineToken, std::string(1, asiTestEngine_Macro_WHITESPACE), lineWords); // Iterate over thewords for ( int w = 0; w < (int) lineWords.size(); ++w ) { std::string wordToken = lineWords[w]; // Check if word token is a variable placeholder int varStart, varEnd; if ( isVar(wordToken, varStart, varEnd) ) { std::string left, right; // Extract leading and trailing characters if ( varStart > 0 ) left = asiAlgo_Utils::Str::SubStr(wordToken, 0, varStart); if ( varEnd + 2 < (int) wordToken.size() ) right = asiAlgo_Utils::Str::SubStr(wordToken, varEnd + 2, (int) wordToken.size() - varEnd); // Extract variable name wordToken = asiAlgo_Utils::Str::SubStr(wordToken, varStart + 2, (int) varEnd - varStart - 2); // Add namespace (scope) for variable name if ( varsScope.length() ) wordToken = varsScope + asiTestEngine_Macro_NAMESPACE + wordToken; // Replace variable with its value if ( vars.find(wordToken) != vars.end() ) { wordToken = vars.find(wordToken)->second; wordToken = left + wordToken + right; } } lineAdjusted += (wordToken + asiTestEngine_Macro_WHITESPACE); } } else // Contents of <pre> tag are used as-is lineAdjusted = lineToken; textExpanded += (lineAdjusted + asiTestEngine_Macro_NL); } return textExpanded; } //----------------------------------------------------------------------------- bool asiTestEngine_DescriptionProc::isLineOfNulls(const std::string& line) { for ( int s = 0; s < (int) line.length(); ++s ) { char c = line.at(s); if ( c != asiTestEngine_Macro_WHITESPACE && c != asiTestEngine_Macro_NL ) return false; } return true; } //----------------------------------------------------------------------------- bool asiTestEngine_DescriptionProc::isVar(const std::string& token, int& varStart, int& varEnd) { if ( token.length() <= 4 ) return false; varStart = (int) token.find(asiTestEngine_Macro_VAR_MARKER); varEnd = (int) token.rfind(asiTestEngine_Macro_VAR_MARKER); if ( varStart == (int) std::string::npos || varEnd == (int) std::string::npos || varStart >= varEnd ) return false; return true; } //----------------------------------------------------------------------------- bool asiTestEngine_DescriptionProc::isPre(const std::string& token, const bool isOpen) { if ( token.length() <= 6 ) return false; if ( isOpen && token.find(asiTestEngine_Macro_SUBSEC_PRE_O) != std::string::npos ) return true; if ( !isOpen && token.find(asiTestEngine_Macro_SUBSEC_PRE_C) != std::string::npos ) return true; return false; } //----------------------------------------------------------------------------- std::string asiTestEngine_DescriptionProc::varScope(const int caseID, const int funcID) { std::string vScope = asiAlgo_Utils::Str::ToString(caseID) + asiTestEngine_Macro_NAMESPACE + asiAlgo_Utils::Str::ToString(funcID); return vScope; }
[ "469345750@qq.com" ]
469345750@qq.com
8dc538fb29ed7d941c5c67c9aab8267f6c76b63c
fa274ec4f0c66c61d6acd476e024d8e7bdfdcf54
/Tutoria OBI 2020/Aula-38/montagem-bad.cpp
252c49bbee72e3bca91e74c15b92d207174e8b9b
[]
no_license
luanaamorim04/Competitive-Programming
1c204b9c21e9c22b4d63ad425a98f4453987b879
265ad98ffecb304524ac805612dfb698d0a419d8
refs/heads/master
2023-07-13T03:04:51.447580
2021-08-11T00:28:57
2021-08-11T00:28:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
#include<bits/stdc++.h> #define _ ios_base::sync_with_stdio(0); #define MAXN 15 #define INF 0x3f3f3f3f #define vi vector<int> #define eb emplace_back using namespace std; //obs: usar 0-indexado int n, m; int c[MAXN][MAXN]; int u, v, w; vi vis; int memo[MAXN][1<<MAXN]; //f(i, usd) = melhor resposta para preencher a partir posição i, considerando // usado os jogadores na mask USD; int f(int i, int usd){ if (usd == ((1<<n)-1)){ return 0; } if (~memo[i][usd]) return memo[i][usd]; int ans = INF; for (int j=0; j<n; ++j){ if (!(usd & (1<<j))){ ans = min(ans, f(i+1, usd | (1<<j)) + c[i][j]); } } return memo[i][usd] = ans; } int main(){_ while ((cin >> n) && n){ for (int i=0; i<n; ++i){ for (int j=0; j<n; ++j){ cin >> c[i][j]; } } memset(memo, -1, sizeof(memo)); cout << f(0, 0) << endl; } }
[ "francisco.fepaf@gmail.com" ]
francisco.fepaf@gmail.com
a173289f613a86dc3d6d6074132835870088b862
ec3a644fdf1a50fa8efade552bfac649ae9a9386
/src/planner/binder/statement/bind_create_view.cpp
aea620a2dc23c51bcca99f2c20e9d824c750992b
[ "MIT" ]
permissive
Longi94/duckdb
71c012fb00ee190f712c02da4a9a3d172d712705
2debf14528e408841a4bc6f43eb114275a096d4e
refs/heads/master
2020-09-08T20:47:10.391723
2020-01-14T13:32:52
2020-01-14T13:32:52
221,237,347
0
0
MIT
2019-11-12T14:28:50
2019-11-12T14:28:49
null
UTF-8
C++
false
false
761
cpp
#include "duckdb/planner/binder.hpp" #include "duckdb/parser/statement/create_view_statement.hpp" #include "duckdb/planner/statement/bound_simple_statement.hpp" #include "duckdb/planner/bound_query_node.hpp" using namespace duckdb; using namespace std; unique_ptr<BoundSQLStatement> Binder::Bind(CreateViewStatement &stmt) { // bind the view as if it were a query so we can catch errors // note that we bind a copy and don't actually use the bind result auto copy = stmt.info->query->Copy(); auto query_node = Bind(*copy); // verify that the if (stmt.info->aliases.size() > query_node->names.size()) { throw BinderException("More VIEW aliases than columns in query result"); } return make_unique<BoundSimpleStatement>(stmt.type, move(stmt.info)); }
[ "mark.raasveldt@gmail.com" ]
mark.raasveldt@gmail.com
39555c91de446a2902e3caf2fa6babef9efddb4d
429df0e93e69d72c06c8e1e62e9feaa2c3494a35
/DemoEngine/src/Collision/CollisionInfo.h
1ae991e9f575a8b3abec11250752301cef50ecb8
[]
no_license
sdsmorris/DemoEngine
7892068c4312eaa978235cd7b6f6f48e1a94e3a7
c2ac76d8002279def01a592b3975cc666551bfe7
refs/heads/master
2022-12-22T23:21:04.702870
2020-09-26T01:33:25
2020-09-26T01:33:25
293,420,531
0
0
null
null
null
null
UTF-8
C++
false
false
108
h
#pragma once class CollisionInfo { public: bool collide; CollisionInfo(bool collide); void seperate(); };
[ "57079358+sdsmorris@users.noreply.github.com" ]
57079358+sdsmorris@users.noreply.github.com
e9bb3a68a62bc3ac3012ccc4e0f7a6b574b1224a
dca7c72b1e992a7ac8a9f2123185c3da1147a270
/atcoder.jp/abc005/abc005_1/Main.cpp
d4fd04b1d7cca002b0d1ce099a90cbfbde0d9deb
[]
no_license
eTakazawa/procon-archive
4182d3d65016414c124bd03d352c1363b3fe7e70
15ef2e892ed3bdbd86641ad88a9ccf64156b9cdb
refs/heads/master
2021-04-21T04:36:13.418633
2020-08-31T14:18:28
2020-08-31T14:18:28
249,749,882
0
0
null
null
null
null
UTF-8
C++
false
false
108
cpp
#include<iostream> using namespace std; int main(){ int x,y; cin >> x >> y; cout << y/x << endl; return 0; }
[ "takazawa621@gmail.com" ]
takazawa621@gmail.com
56f72550b09aba3567f785bd48c69dee49c33301
00add89b1c9712db1a29a73f34864854a7738686
/packages/monte_carlo/active_region/response/src/MonteCarlo_FullPhaseSpaceParticleResponseFunction.cpp
9da314d7c75d35155c949c8909203831b414a0b3
[ "BSD-3-Clause" ]
permissive
FRENSIE/FRENSIE
a4f533faa02e456ec641815886bc530a53f525f9
1735b1c8841f23d415a4998743515c56f980f654
refs/heads/master
2021-11-19T02:37:26.311426
2021-09-08T11:51:24
2021-09-08T11:51:24
7,826,404
11
6
NOASSERTION
2021-09-08T11:51:25
2013-01-25T19:03:09
C++
UTF-8
C++
false
false
1,871
cpp
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_FullPhaseSpaceParticleResponseFunction.cpp //! \author Alex Robinson //! \brief Full phase-space particle response function class definition //! //---------------------------------------------------------------------------// // FRENSIE Includes #include "FRENSIE_Archives.hpp" #include "MonteCarlo_FullPhaseSpaceParticleResponseFunction.hpp" #include "Utility_DesignByContract.hpp" namespace MonteCarlo{ // Constructor FullPhaseSpaceParticleResponseFunction::FullPhaseSpaceParticleResponseFunction( const std::shared_ptr<const ParticleDistribution>& particle_dist ) : d_particle_dist( particle_dist ) { // Make sure that the particle distribution pointer is valid testPrecondition( particle_dist.get() ); } // Evaluate the response function at the desired phase space point double FullPhaseSpaceParticleResponseFunction::evaluate( const ParticleState& particle ) const { return d_particle_dist->evaluate( particle ); } // Check if the response function is spatially uniform bool FullPhaseSpaceParticleResponseFunction::isSpatiallyUniform() const { return d_particle_dist->isSpatiallyUniform(); } // Get a description of the response function std::string FullPhaseSpaceParticleResponseFunction::description() const { return std::string("f_\"") + d_particle_dist->getName() + "\"(particle)"; } EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo::FullPhaseSpaceParticleResponseFunction ); } // end MonteCarlo namespace BOOST_SERIALIZATION_CLASS_EXPORT_IMPLEMENT( FullPhaseSpaceParticleResponseFunction, MonteCarlo ); //---------------------------------------------------------------------------// // end MonteCarlo_FullPhaseSpaceParticleResponseFunction.cpp //---------------------------------------------------------------------------//
[ "aprobinson@wisc.edu" ]
aprobinson@wisc.edu
34c49c35d2f8e4ba37d036254f9edd2bf347bf82
f8c59c335b0c1dc2e8ab2824de234850e0a4c045
/modules/datastream_html_adapter/src/TextPair.cpp
3fbf260d3ced093e68b1b702a195da82bad6601f
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
DeepBlue14/rqt_ide
469d7ffb9a2fa244c68ceafe526baa24e89b1a7b
853964dc429d61c9afb6f1fe827f2e3e83f92713
refs/heads/master
2020-12-31T06:57:33.789919
2016-09-07T05:04:54
2016-09-07T05:04:54
34,908,755
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
#include "TextPair.h" TextPair::TextPair() { unixElem = new QString(); htmlElem = new QString(); } void TextPair::setUnixElem(QString& unixElem) { this->unixElem = &unixElem; } QString* TextPair::getUnixElem() { return unixElem; } void TextPair::setHtmlElem(QString& htmlElem) { this->htmlElem = &htmlElem; } QString* TextPair::getHtmlElem() { return htmlElem; } QString* TextPair::toString() { QString* tmp; tmp->append("UNIX: " + *unixElem); tmp->append("\nHTML: " + *htmlElem); return tmp; } TextPair::~TextPair() { ; }
[ "james.perl12@gmail.com" ]
james.perl12@gmail.com
f94d99144f1c05f463209079292d669bb8ee5366
3b698b8a7d2730605adc16cda2632d736db896e0
/lib/RelayHandler/RelayHandler.hpp
019eea7b4159490799709c772b5663af6e6ebcfa
[ "Apache-2.0" ]
permissive
thorsten-l/ESP8266-WiFi-Socket-II
a2f2447d42deb91ad1e186662398cd179290fb10
163840f52273ae85c9ea92e12db049c757763050
refs/heads/master
2020-04-13T16:07:30.828419
2020-03-20T16:24:08
2020-03-20T16:24:08
163,313,219
5
2
Apache-2.0
2019-05-29T06:53:04
2018-12-27T16:04:24
C++
UTF-8
C++
false
false
408
hpp
#ifndef __RELAY_HANDLER_HPP__ #define __RELAY_HANDLER_HPP__ class RelayHandler { private: volatile bool powerOn; volatile bool delayState; volatile bool delayAction; void on(); void off(); public: RelayHandler(); const bool isPowerOn(); const bool isDelayedPowerOn(); void toggle(); void delayedOn(); void delayedOff(); void handle(); }; extern RelayHandler relayHandler; #endif
[ "th@l9g.de" ]
th@l9g.de
caca106de40564f0a48cb26bafb602ffab48993a
3b8058f4962c945cee85d81401ae4f499aaede97
/inc/arpterm/util/util.hpp
5170f8caaa5fb79e4c7a4f07d0d37c37d074bf00
[]
no_license
Arp-/arpterm
1f2fcbcb5befce82906ed54a41ff37e95c2c2eba
7a6d4ba971dce6ca6aa608b28b7323c4272d6e74
refs/heads/master
2021-01-24T18:47:31.545711
2017-06-17T19:08:07
2017-06-17T19:08:07
84,477,152
0
0
null
null
null
null
UTF-8
C++
false
false
735
hpp
#ifndef ARPTERM_UTIL_HPP #define ARPTERM_UTIL_HPP namespace arpterm { namespace util { template <typename T, typename ...Args> inline std::unique_ptr<T> make_unique(Args&& ...args) { return std::unique_ptr<T>(new T(args...)); } inline void print_hex(const char* buf, size_t len) { printf("0x"); for (size_t i = 0; i < len; i++) { printf("%02X", buf[i] & 0xff); } printf("\n"); } inline bool is_visual_line_term(char c) { return c == '\r'; } inline bool is_logical_line_term(char c) { return c == '\n'; } inline bool is_line_term(char c) { return is_logical_line_term(c) || is_visual_line_term(c); } } // namespace util } // namesapc arpterm #endif // ARPTERM_UTIL_HPP
[ "irphathil@gmail.com" ]
irphathil@gmail.com
952b4db28ffce276f6e38ef707612b8601e0fe3b
bbc8a61169c0ff9a4d7fc2f4704d5ac280434a2c
/jiang_jason.assignment-1.08/character.h
ea68aa17d45909a0bc18dd58c8d89d776c41ebaa
[]
no_license
JJiang76/COMS327
c0df3bf8af8d74f1abd5e04eb85731ae964e661e
57682d68349c969eeae22b3a42664477769eaaa9
refs/heads/master
2023-05-27T23:42:12.276822
2021-06-02T19:03:06
2021-06-02T19:03:06
343,905,224
0
0
null
null
null
null
UTF-8
C++
false
false
2,111
h
#ifndef CHARACTER_H # define CHARACTER_H # include <stdint.h> # include <vector> # include <string> # include "dims.h" # include "dice.h" typedef enum kill_type { kill_direct, kill_avenged, num_kill_types } kill_type_t; class character { public: char symbol; pair_t position; int32_t speed; int hitpoints; dice damage; std::vector<uint32_t> color; std::string name; uint32_t alive; /* Characters use to have a next_turn for the move queue. Now that it is * * an event queue, there's no need for that here. Instead it's in the * * event. Similarly, sequence_number was introduced in order to ensure * * that the queue remains stable. Also no longer necessary here, but in * * this case, we'll keep it, because it provides a bit of interesting * * metadata: locally, how old is this character; and globally, how many * * characters have been created by the game. */ uint32_t sequence_number; uint32_t kills[num_kill_types]; virtual ~character() = default; }; class dungeon; int32_t compare_characters_by_next_turn(const void *character1, const void *character2); uint32_t can_see(dungeon *d, pair_t voyeur, pair_t exhibitionist, int is_pc, int learn); void character_delete(character *c); int16_t *character_get_pos(character *c); int16_t character_get_y(const character *c); int16_t character_set_y(character *c, int16_t y); int16_t character_get_x(const character *c); int16_t character_set_x(character *c, int16_t x); uint32_t character_get_next_turn(const character *c); void character_die(character *c); int character_is_alive(const character *c); void character_next_turn(character *c); void character_reset_turn(character *c); char character_get_symbol(const character *c); uint32_t character_get_speed(const character *c); uint32_t character_get_dkills(const character *c); uint32_t character_get_ikills(const character *c); uint32_t character_increment_dkills(character *c); uint32_t character_increment_ikills(character *c, uint32_t k); #endif
[ "jasonjiang27@gmail.com" ]
jasonjiang27@gmail.com
6706cb9c4267ec0bdd26b467a70cfe897acac538
1f9b5c9a950b6df166085edf262ad063746c6d8b
/MAPEDITOR/main.cpp
5714408a20e90f68a6785bdfc5935b3f638d9e0f
[ "MIT" ]
permissive
Parseus/pixfight
fb5b936939752333f67a54454f91f8e4904b07c9
b1f134b5e969e2da9ae66653f9e29da77bb6f28f
refs/heads/master
2021-06-03T23:45:53.310829
2018-07-23T09:52:22
2018-07-23T09:52:22
172,204,446
1
0
MIT
2019-02-23T11:05:58
2019-02-23T11:05:57
null
UTF-8
C++
false
false
6,998
cpp
// // main.m // PixEditor // // Created by Marcin Małysz on 23/04/2018. // Copyright © 2018 Marcin Małysz. All rights reserved. // #include <GL/glew.h> #include <GLFW/glfw3.h> #include "Core-pch.hpp" #include "PFMapEditor.hpp" #include <limits.h> #include <unistd.h> #include <chrono> #include <thread> #define WINDOW_WIDTH 1280 #define WINDOW_HEIGHT 800 #define MAX_VERTEX_BUFFER 512 * 1024 #define MAX_ELEMENT_BUFFER 128 * 1024 #define NK_INCLUDE_FIXED_TYPES #define NK_INCLUDE_STANDARD_IO #define NK_INCLUDE_STANDARD_VARARGS #define NK_INCLUDE_DEFAULT_ALLOCATOR #define NK_INCLUDE_VERTEX_BUFFER_OUTPUT #define NK_INCLUDE_FONT_BAKING #define NK_IMPLEMENTATION #include <stdarg.h> #include "nuklear.h" #include "nuklear_glfw_gl3.h" //UI struct nk_context *ctx; struct nk_vec2 scroll; double last_button_click; int is_double_click_down; struct nk_vec2 double_click_pos; #ifndef NK_GLFW_DOUBLE_CLICK_LO #define NK_GLFW_DOUBLE_CLICK_LO 0.02 #endif #ifndef NK_GLFW_DOUBLE_CLICK_HI #define NK_GLFW_DOUBLE_CLICK_HI 0.2 #endif struct nk_font *latosmall = nullptr; PFMapEditor *mapeditor = nullptr; std::string getexepath() { #ifdef _WIN32 return "data/"; #elif defined(__APPLE__) return "data/"; #else char result[ PATH_MAX ]; ssize_t count = readlink( "/proc/self/exe", result, PATH_MAX ); std::string path = std::string( result, (count > 0) ? count : 0 ); return path.substr(0, path.find_last_of("\\/")) + "/data/"; #endif } static void error_callback(int e, const char *d) { std::cout << "Error " << e <<": " << d << std::endl; } void scroll_callback(GLFWwindow *win, double xoff, double yoff) { scroll.x += (float)xoff; scroll.y += (float)yoff; mapeditor->handleScroll(xoff, yoff); } void mouse_callback(GLFWwindow *win, int button, int action, int mods) { double x, y; glfwGetCursorPos(win, &x, &y); mapeditor->handleMouse(x, y, button, action); if (button != GLFW_MOUSE_BUTTON_LEFT) { return; } if (action == GLFW_PRESS) { double dt = glfwGetTime() - last_button_click; if (dt > NK_GLFW_DOUBLE_CLICK_LO && dt < NK_GLFW_DOUBLE_CLICK_HI) { is_double_click_down = nk_true; double_click_pos = nk_vec2((float)x, (float)y); } last_button_click = glfwGetTime(); } else { is_double_click_down = nk_false; } } void text_callback(GLFWwindow *win, unsigned int codepoint) { nk_input_unicode(ctx, codepoint); } int main(int argc, const char * argv[]) { std::string rootPath = getexepath(); last_button_click = 0; is_double_click_down = nk_false; double_click_pos = nk_vec2(0, 0); static GLFWwindow *win; int width = 0, height = 0; glfwSetErrorCallback(error_callback); if (!glfwInit()) { std::cout << "[GFLW] failed to init!" << std::endl; exit(1); } #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); win = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "PixEditor", NULL, NULL); glfwMakeContextCurrent(win); glfwGetWindowSize(win, &width, &height); glViewport(0, 0, width, height); glfwSetScrollCallback(win, scroll_callback); glfwSetMouseButtonCallback(win, mouse_callback); glfwSetCharCallback(win, text_callback); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cout <<"Failed to setup GLEW" << std::endl; exit(1); } ctx = nk_glfw3_init(win); mapeditor = new PFMapEditor(win, rootPath, ctx); mapeditor->loadBlank(); std::string latopath = rootPath + "Lato-Black.ttf"; struct nk_font_atlas *atlas; nk_glfw3_font_stash_begin(&atlas); latosmall = nk_font_atlas_add_from_file(atlas, latopath.c_str(), 16, 0); nk_glfw3_font_stash_end(); nk_style_set_font(ctx, &latosmall->handle); while (!glfwWindowShouldClose(win)) { double x, y; nk_input_begin(ctx); glfwPollEvents(); nk_input_key(ctx, NK_KEY_DEL, glfwGetKey(win, GLFW_KEY_DELETE) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_ENTER, glfwGetKey(win, GLFW_KEY_ENTER) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_TAB, glfwGetKey(win, GLFW_KEY_TAB) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_BACKSPACE, glfwGetKey(win, GLFW_KEY_BACKSPACE) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_LEFT, glfwGetKey(win, GLFW_KEY_LEFT) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_RIGHT, glfwGetKey(win, GLFW_KEY_RIGHT) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_UP, glfwGetKey(win, GLFW_KEY_UP) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_DOWN, glfwGetKey(win, GLFW_KEY_DOWN) == GLFW_PRESS); #ifdef __APPLE__ if(glfwGetKey(win, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS) { #else if (glfwGetKey(win, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(win, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS) { #endif nk_input_key(ctx, NK_KEY_COPY, glfwGetKey(win, GLFW_KEY_C) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_PASTE, glfwGetKey(win, GLFW_KEY_V) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_CUT, glfwGetKey(win, GLFW_KEY_X) == GLFW_PRESS); nk_input_key(ctx, NK_KEY_SHIFT, 1); } else { nk_input_key(ctx, NK_KEY_COPY, 0); nk_input_key(ctx, NK_KEY_PASTE, 0); nk_input_key(ctx, NK_KEY_CUT, 0); nk_input_key(ctx, NK_KEY_SHIFT, 0); } glfwGetCursorPos(win, &x, &y); nk_input_motion(ctx, (int)x, (int)y); nk_input_button(ctx, NK_BUTTON_LEFT, (int)x, (int)y, glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS); nk_input_button(ctx, NK_BUTTON_MIDDLE, (int)x, (int)y, glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS); nk_input_button(ctx, NK_BUTTON_RIGHT, (int)x, (int)y, glfwGetMouseButton(win, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS); nk_input_button(ctx, NK_BUTTON_DOUBLE, (int)double_click_pos.x, (int)double_click_pos.y, is_double_click_down); nk_input_scroll(ctx, scroll); nk_input_end(ctx); scroll = nk_vec2(0,0); mapeditor->handleMouse(x, y, glfwGetMouseButton(win, 1), -1); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.4, 0.4, 0.4, 1); mapeditor->Render(); nk_glfw3_render(NK_ANTI_ALIASING_ON, MAX_VERTEX_BUFFER, MAX_ELEMENT_BUFFER); glfwSwapBuffers(win); #ifndef _WIN32 //slow down std::this_thread::sleep_for(std::chrono::milliseconds(10)); #endif } delete mapeditor; nk_glfw3_shutdown(); glfwDestroyWindow(win); glfwTerminate(); return 0; }
[ "marcin.malysz@explaineverything.com" ]
marcin.malysz@explaineverything.com
d939fc8585527e931c243f4c3fcc982f7a66cb2f
5c0ce7522d6cd8b9dfe7e6d577e4c61f50a13df7
/include/cublas_result.h
9cb6f8e69d1a1dea2a4eec00d78e97dc85917681
[]
no_license
anax32/nvwrap
cd56988be81d9558c53b4f2144b80c5c23a508ec
60b6730955892377c5c2773af9ec9e4fc0b31e20
refs/heads/master
2021-07-16T18:36:35.353780
2017-10-05T12:14:55
2017-10-05T12:14:55
105,268,038
0
0
null
null
null
null
UTF-8
C++
false
false
234
h
#ifndef CUBLAS_RESULT_H #define CUBLAS_RESULT_H class cublas_result { protected: cublasStatus_t result_; public: cublas_result() : result_(CUBLAS_STATUS_SUCCESS) {} cublasStatus_t result() const { return result_; } }; #endif
[ "anax@hotmail.co.uk" ]
anax@hotmail.co.uk
f8ba8caa58ac3595b429993dd3ebf8fdbd6f924d
7c999c6a4b0bcc9fc114cdf253eeb32ba088eda1
/Assn1/10_opengl3_3/10.) Skybox/source/10.) Skybox/shaders.h
29de552cb26bf5e61e92fbbfd2f4a427af994e4b
[]
no_license
ycjungSubhuman/CrossTheRoad
d7923effc991894f96722a66ee37c219384516a6
81cfb64193b6a5acc3f6d07de4df293c64719b56
refs/heads/master
2021-01-21T12:59:11.800892
2016-05-17T05:31:35
2016-05-17T05:31:35
53,595,390
0
0
null
null
null
null
UTF-8
C++
false
false
1,912
h
#pragma once /******************************** Class: CShader Purpose: Wraps OpenGL shader loading and compiling. ********************************/ class CShader { public: bool loadShader(string sFile, int a_iType); void deleteShader(); bool isLoaded(); UINT getShaderID(); CShader(); private: UINT uiShader; // ID of shader int iType; // GL_VERTEX_SHADER, GL_FRAGMENT_SHADER... bool bLoaded; // Whether shader was loaded and compiled }; /******************************** Class: CShaderProgram Purpose: Wraps OpenGL shader program and make its usage easy. ********************************/ class CShaderProgram { public: void createProgram(); void deleteProgram(); bool addShaderToProgram(CShader* shShader); bool linkProgram(); void useProgram(); UINT getProgramID(); // Setting vectors void setUniform(string sName, glm::vec2* vVectors, int iCount = 1); void setUniform(string sName, const glm::vec2 vVector); void setUniform(string sName, glm::vec3* vVectors, int iCount = 1); void setUniform(string sName, const glm::vec3 vVector); void setUniform(string sName, glm::vec4* vVectors, int iCount = 1); void setUniform(string sName, const glm::vec4 vVector); // Setting floats void setUniform(string sName, float* fValues, int iCount = 1); void setUniform(string sName, const float fValue); // Setting 3x3 matrices void setUniform(string sName, glm::mat3* mMatrices, int iCount = 1); void setUniform(string sName, const glm::mat3 mMatrix); // Setting 4x4 matrices void setUniform(string sName, glm::mat4* mMatrices, int iCount = 1); void setUniform(string sName, const glm::mat4 mMatrix); // Setting integers void setUniform(string sName, int* iValues, int iCount = 1); void setUniform(string sName, const int iValue); CShaderProgram(); private: UINT uiProgram; // ID of program bool bLinked; // Whether program was linked and is ready to use };
[ "jung3519@gmail.com" ]
jung3519@gmail.com
66fc62db1a054cd43a9d4a4fb4cde38210f07ea6
a23409a54d6ef8955e8aa890c583355cdb2b2d8f
/libstreetmap/GUI_Autocomplete.cpp
498de16bd2e597a231c6a59316bde23f05a0a93c
[]
no_license
LiuKuen/CityMaps
a6f76e6d67732b436b50f13bdbdd16ca3b0fe7fa
088cdb9a5e58d8e3927c47fac253fe2378db226d
refs/heads/master
2021-06-01T05:45:25.236568
2016-09-07T03:01:53
2016-09-07T03:01:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,404
cpp
#include "GUI_Autocomplete.h" void AutoCompleteHandler::updateQueries(Trie& database, int keysym, string prefix){ if(keysym != XK_Tab){ autocompleteQueries.clear(); int startingRow = 0; // prefix remains the same as the user types TrieNode* prefixNode = database.findPrefixLocation(prefix); database.getWordsFromPrefix(prefixNode, prefix, startingRow, autocompleteQueries); // Change the first letter to uppercase/lowercase if(!prefix.empty()){ if(islower(prefix.at(0))){ prefix[0]+='A'-'a'; } else prefix[0]+='a'-'A'; std::vector<string> otherQuery; //cout << prefix << endl; prefixNode = database.findPrefixLocation(prefix); //cout << prefixNode->getContent() << endl; database.getWordsFromPrefix(prefixNode, prefix, startingRow, otherQuery); autocompleteQueries.insert(autocompleteQueries.end(),otherQuery.begin(),otherQuery.end()); } } return; } void AutoCompleteHandler::autoCompleteString(int keysym, string& input, int currentHighlighting){ if(currentHighlighting>0) currentHighlighting--; if (keysym == XK_Tab){ if(autocompleteQueries.size() > 0){ input = autocompleteQueries[currentHighlighting]; } } }
[ "kuenjeffrey@hotmail.com" ]
kuenjeffrey@hotmail.com
458b859244d5865bfeb9a212e34838daff871919
0003a8a7d0522f18a1f109c76399fa414d5429f5
/src/Magnum/Implementation/maxTextureSize.cpp
72ef0b76394a45f05b565343452d7921d7d1f260
[ "MIT" ]
permissive
aroig/magnum
62b29b6f9e3fe1ef0eb09e152ae20cfd36c0dc0a
9ab2a1553c5de07e7a6083dc6369feaef897742a
refs/heads/master
2021-01-11T18:10:30.240858
2017-01-17T14:47:59
2017-01-17T14:49:50
79,509,604
1
0
null
2017-01-20T00:33:44
2017-01-20T00:33:44
null
UTF-8
C++
false
false
2,416
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016 Vladimír Vondruš <mosra@centrum.cz> 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 "maxTextureSize.h" #include "Magnum/Context.h" #include "State.h" #include "TextureState.h" namespace Magnum { namespace Implementation { GLint maxTextureSideSize() { GLint& value = Context::current().state().texture->maxSize; if(value == 0) glGetIntegerv(GL_MAX_TEXTURE_SIZE, &value); return value; } #if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2)) GLint max3DTextureDepth() { GLint& value = Context::current().state().texture->max3DSize; if(value == 0) #ifndef MAGNUM_TARGET_GLES2 glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE, &value); #else glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE_OES, &value); #endif return value; } #endif #ifndef MAGNUM_TARGET_GLES2 GLint maxTextureArrayLayers() { GLint& value = Context::current().state().texture->maxArrayLayers; if(value == 0) glGetIntegerv(GL_MAX_ARRAY_TEXTURE_LAYERS, &value); return value; } #endif GLint maxCubeMapTextureSideSize() { GLint& value = Context::current().state().texture->maxCubeMapSize; if(value == 0) glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &value); return value; } }}
[ "mosra@centrum.cz" ]
mosra@centrum.cz
8d34ee418ec69c6c685921954ea89f7941f6e4fe
489616aed3f8453b807668c1777e4397c69c5a00
/Problems/1176c.cpp
c50d4e4f86b8a8945d428e80d90032d2d4b8f6ae
[]
no_license
kunalvaswani123/Codeforces
a4f3a52f7883b87ba16402b8373430080a42ca6a
71ce7910abec704282ea37f3117b46ad26104bef
refs/heads/master
2020-06-03T10:54:56.288155
2019-08-16T12:34:59
2019-08-16T12:34:59
191,541,492
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; const ll mod = 1e9 + 7; #define pival 3.14159265359 #define pii pair<int,int> #define pll pair<ll,ll> #define pb push_back #define mp make_pair #define fi first #define se second #define pqq priority_queue #define all(a) a.begin(),a.end() #define sz(a) (ll)(a.size()) ll power(ll x,ll y,ll p) { ll res=1; x=x%p; while (y > 0) { if(y&1) res=(res*x)%p; y=y>>1; x=(x*x)%p; } return res; } const ll L = 5e5 + 5; ll arr[L]; ll ans[100]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); ll i,n,x; cin >> n; for(i=0;i<n;i++) cin >> arr[i]; for(i=n-1;i>=0;i--) { if(arr[i] == 42) ans[42]++; else if(arr[i] == 23) { if(ans[42] > 0) ans[42]--, ans[23]++; } else if(arr[i] == 16) { if(ans[23] > 0) ans[23]--, ans[16]++; } else if(arr[i] == 16) { if(ans[23] > 0) ans[23]--, ans[16]++; } else if(arr[i] == 15) { if(ans[16] > 0) ans[16]--, ans[15]++; } else if(arr[i] == 8) { if(ans[15] > 0) ans[15]--, ans[8]++; } else { if(ans[8] > 0) ans[8]--, ans[4]++; } } ans[4] *= 6; cout << n - ans[4] << endl; return 0; }
[ "kvaswani2012@gmail.com" ]
kvaswani2012@gmail.com
32dbd26cd99056a6a3d4909259b656564513c455
76e652e2ef2c5d57f8115eb4939e1fb460255549
/Plugins/NetworkAbilityKit/Intermediate/Build/Win64/UE4Editor/Inc/NetworkAbilityKit/AbilityFrameworkStruct.gen.cpp
128b24012ea483c79117853cec1976f9436794aa
[]
no_license
alcachofalaruz/NetworkAbilityKit
00fc5a565cb9a73ec0b7a6e2a84ee11ce4663ada
7a90a74a1dc27f617bc50bb27e9c085b5df5f7c4
refs/heads/master
2023-06-08T09:22:44.172313
2021-06-30T18:06:07
2021-06-30T18:06:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,346
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "NetworkAbilityKit/Public/AbilityFrameworkStruct.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeAbilityFrameworkStruct() {} // Cross Module References NETWORKABILITYKIT_API UScriptStruct* Z_Construct_UScriptStruct_FAbilityListStruct(); UPackage* Z_Construct_UPackage__Script_NetworkAbilityKit(); ENGINE_API UScriptStruct* Z_Construct_UScriptStruct_FTableRowBase(); NETWORKABILITYKIT_API UClass* Z_Construct_UClass_AAbilityBase_NoRegister(); NETWORKABILITYKIT_API UScriptStruct* Z_Construct_UScriptStruct_FCostStruct(); NETWORKABILITYKIT_API UEnum* Z_Construct_UEnum_NetworkAbilityKit_EAttrModifyMethod(); // End Cross Module References static_assert(std::is_polymorphic<FAbilityListStruct>() == std::is_polymorphic<FTableRowBase>(), "USTRUCT FAbilityListStruct cannot be polymorphic unless super FTableRowBase is polymorphic"); class UScriptStruct* FAbilityListStruct::StaticStruct() { static class UScriptStruct* Singleton = NULL; if (!Singleton) { extern NETWORKABILITYKIT_API uint32 Get_Z_Construct_UScriptStruct_FAbilityListStruct_Hash(); Singleton = GetStaticStruct(Z_Construct_UScriptStruct_FAbilityListStruct, Z_Construct_UPackage__Script_NetworkAbilityKit(), TEXT("AbilityListStruct"), sizeof(FAbilityListStruct), Get_Z_Construct_UScriptStruct_FAbilityListStruct_Hash()); } return Singleton; } template<> NETWORKABILITYKIT_API UScriptStruct* StaticStruct<FAbilityListStruct>() { return FAbilityListStruct::StaticStruct(); } static FCompiledInDeferStruct Z_CompiledInDeferStruct_UScriptStruct_FAbilityListStruct(FAbilityListStruct::StaticStruct, TEXT("/Script/NetworkAbilityKit"), TEXT("AbilityListStruct"), false, nullptr, nullptr); static struct FScriptStruct_NetworkAbilityKit_StaticRegisterNativesFAbilityListStruct { FScriptStruct_NetworkAbilityKit_StaticRegisterNativesFAbilityListStruct() { UScriptStruct::DeferCppStructOps(FName(TEXT("AbilityListStruct")),new UScriptStruct::TCppStructOps<FAbilityListStruct>); } } ScriptStruct_NetworkAbilityKit_StaticRegisterNativesFAbilityListStruct; struct Z_Construct_UScriptStruct_FAbilityListStruct_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Struct_MetaDataParams[]; #endif static void* NewStructOps(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Dev_AbilityName_MetaData[]; #endif static const UE4CodeGen_Private::FNamePropertyParams NewProp_Dev_AbilityName; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Ability_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Ability; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const UE4CodeGen_Private::FStructParams ReturnStructParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FAbilityListStruct_Statics::Struct_MetaDataParams[] = { { "BlueprintType", "true" }, { "ModuleRelativePath", "Public/AbilityFrameworkStruct.h" }, }; #endif void* Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewStructOps() { return (UScriptStruct::ICppStructOps*)new UScriptStruct::TCppStructOps<FAbilityListStruct>(); } #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Dev_AbilityName_MetaData[] = { { "Category", "AbilityListStruct" }, { "ModuleRelativePath", "Public/AbilityFrameworkStruct.h" }, }; #endif const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Dev_AbilityName = { "Dev_AbilityName", nullptr, (EPropertyFlags)0x0010000000000005, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FAbilityListStruct, Dev_AbilityName), METADATA_PARAMS(Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Dev_AbilityName_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Dev_AbilityName_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Ability_MetaData[] = { { "Category", "AbilityListStruct" }, { "ModuleRelativePath", "Public/AbilityFrameworkStruct.h" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Ability = { "Ability", nullptr, (EPropertyFlags)0x0010000000000005, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FAbilityListStruct, Ability), Z_Construct_UClass_AAbilityBase_NoRegister, METADATA_PARAMS(Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Ability_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Ability_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UScriptStruct_FAbilityListStruct_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Dev_AbilityName, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FAbilityListStruct_Statics::NewProp_Ability, }; const UE4CodeGen_Private::FStructParams Z_Construct_UScriptStruct_FAbilityListStruct_Statics::ReturnStructParams = { (UObject* (*)())Z_Construct_UPackage__Script_NetworkAbilityKit, Z_Construct_UScriptStruct_FTableRowBase, &NewStructOps, "AbilityListStruct", sizeof(FAbilityListStruct), alignof(FAbilityListStruct), Z_Construct_UScriptStruct_FAbilityListStruct_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FAbilityListStruct_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, EStructFlags(0x00000001), METADATA_PARAMS(Z_Construct_UScriptStruct_FAbilityListStruct_Statics::Struct_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FAbilityListStruct_Statics::Struct_MetaDataParams)) }; UScriptStruct* Z_Construct_UScriptStruct_FAbilityListStruct() { #if WITH_HOT_RELOAD extern uint32 Get_Z_Construct_UScriptStruct_FAbilityListStruct_Hash(); UPackage* Outer = Z_Construct_UPackage__Script_NetworkAbilityKit(); static UScriptStruct* ReturnStruct = FindExistingStructIfHotReloadOrDynamic(Outer, TEXT("AbilityListStruct"), sizeof(FAbilityListStruct), Get_Z_Construct_UScriptStruct_FAbilityListStruct_Hash(), false); #else static UScriptStruct* ReturnStruct = nullptr; #endif if (!ReturnStruct) { UE4CodeGen_Private::ConstructUScriptStruct(ReturnStruct, Z_Construct_UScriptStruct_FAbilityListStruct_Statics::ReturnStructParams); } return ReturnStruct; } uint32 Get_Z_Construct_UScriptStruct_FAbilityListStruct_Hash() { return 2458914430U; } class UScriptStruct* FCostStruct::StaticStruct() { static class UScriptStruct* Singleton = NULL; if (!Singleton) { extern NETWORKABILITYKIT_API uint32 Get_Z_Construct_UScriptStruct_FCostStruct_Hash(); Singleton = GetStaticStruct(Z_Construct_UScriptStruct_FCostStruct, Z_Construct_UPackage__Script_NetworkAbilityKit(), TEXT("CostStruct"), sizeof(FCostStruct), Get_Z_Construct_UScriptStruct_FCostStruct_Hash()); } return Singleton; } template<> NETWORKABILITYKIT_API UScriptStruct* StaticStruct<FCostStruct>() { return FCostStruct::StaticStruct(); } static FCompiledInDeferStruct Z_CompiledInDeferStruct_UScriptStruct_FCostStruct(FCostStruct::StaticStruct, TEXT("/Script/NetworkAbilityKit"), TEXT("CostStruct"), false, nullptr, nullptr); static struct FScriptStruct_NetworkAbilityKit_StaticRegisterNativesFCostStruct { FScriptStruct_NetworkAbilityKit_StaticRegisterNativesFCostStruct() { UScriptStruct::DeferCppStructOps(FName(TEXT("CostStruct")),new UScriptStruct::TCppStructOps<FCostStruct>); } } ScriptStruct_NetworkAbilityKit_StaticRegisterNativesFCostStruct; struct Z_Construct_UScriptStruct_FCostStruct_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Struct_MetaDataParams[]; #endif static void* NewStructOps(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_AttributeName_MetaData[]; #endif static const UE4CodeGen_Private::FNamePropertyParams NewProp_AttributeName; static const UE4CodeGen_Private::FBytePropertyParams NewProp_ModifyMethod_Underlying; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ModifyMethod_MetaData[]; #endif static const UE4CodeGen_Private::FEnumPropertyParams NewProp_ModifyMethod; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Value_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_Value; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const UE4CodeGen_Private::FStructParams ReturnStructParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FCostStruct_Statics::Struct_MetaDataParams[] = { { "BlueprintType", "true" }, { "ModuleRelativePath", "Public/AbilityFrameworkStruct.h" }, }; #endif void* Z_Construct_UScriptStruct_FCostStruct_Statics::NewStructOps() { return (UScriptStruct::ICppStructOps*)new UScriptStruct::TCppStructOps<FCostStruct>(); } #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_AttributeName_MetaData[] = { { "Category", "CostStruct" }, { "ModuleRelativePath", "Public/AbilityFrameworkStruct.h" }, }; #endif const UE4CodeGen_Private::FNamePropertyParams Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_AttributeName = { "AttributeName", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Name, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FCostStruct, AttributeName), METADATA_PARAMS(Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_AttributeName_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_AttributeName_MetaData)) }; const UE4CodeGen_Private::FBytePropertyParams Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_ModifyMethod_Underlying = { "UnderlyingType", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Byte, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, nullptr, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_ModifyMethod_MetaData[] = { { "Category", "CostStruct" }, { "ModuleRelativePath", "Public/AbilityFrameworkStruct.h" }, }; #endif const UE4CodeGen_Private::FEnumPropertyParams Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_ModifyMethod = { "ModifyMethod", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Enum, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FCostStruct, ModifyMethod), Z_Construct_UEnum_NetworkAbilityKit_EAttrModifyMethod, METADATA_PARAMS(Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_ModifyMethod_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_ModifyMethod_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_Value_MetaData[] = { { "Category", "CostStruct" }, { "ModuleRelativePath", "Public/AbilityFrameworkStruct.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FCostStruct, Value), METADATA_PARAMS(Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_Value_MetaData, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_Value_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UScriptStruct_FCostStruct_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_AttributeName, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_ModifyMethod_Underlying, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_ModifyMethod, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UScriptStruct_FCostStruct_Statics::NewProp_Value, }; const UE4CodeGen_Private::FStructParams Z_Construct_UScriptStruct_FCostStruct_Statics::ReturnStructParams = { (UObject* (*)())Z_Construct_UPackage__Script_NetworkAbilityKit, nullptr, &NewStructOps, "CostStruct", sizeof(FCostStruct), alignof(FCostStruct), Z_Construct_UScriptStruct_FCostStruct_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FCostStruct_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, EStructFlags(0x00000001), METADATA_PARAMS(Z_Construct_UScriptStruct_FCostStruct_Statics::Struct_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UScriptStruct_FCostStruct_Statics::Struct_MetaDataParams)) }; UScriptStruct* Z_Construct_UScriptStruct_FCostStruct() { #if WITH_HOT_RELOAD extern uint32 Get_Z_Construct_UScriptStruct_FCostStruct_Hash(); UPackage* Outer = Z_Construct_UPackage__Script_NetworkAbilityKit(); static UScriptStruct* ReturnStruct = FindExistingStructIfHotReloadOrDynamic(Outer, TEXT("CostStruct"), sizeof(FCostStruct), Get_Z_Construct_UScriptStruct_FCostStruct_Hash(), false); #else static UScriptStruct* ReturnStruct = nullptr; #endif if (!ReturnStruct) { UE4CodeGen_Private::ConstructUScriptStruct(ReturnStruct, Z_Construct_UScriptStruct_FCostStruct_Statics::ReturnStructParams); } return ReturnStruct; } uint32 Get_Z_Construct_UScriptStruct_FCostStruct_Hash() { return 841839194U; } PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "929509323@qq.com" ]
929509323@qq.com
5bc90c98b79f750a7a63c6250feeae4b7d620b35
04b1803adb6653ecb7cb827c4f4aa616afacf629
/media/formats/mp4/mp4_stream_parser.h
86ef7467c528dd3d3800187a325ed2deb08bd135
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
5,388
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_FORMATS_MP4_MP4_STREAM_PARSER_H_ #define MEDIA_FORMATS_MP4_MP4_STREAM_PARSER_H_ #include <stdint.h> #include <memory> #include <set> #include <vector> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "media/base/media_export.h" #include "media/base/stream_parser.h" #include "media/formats/common/offset_byte_queue.h" #include "media/formats/mp4/parse_result.h" #include "media/formats/mp4/track_run_iterator.h" #if BUILDFLAG(USE_PROPRIETARY_CODECS) #include "media/formats/mp4/aac.h" #endif namespace media { namespace mp4 { struct Movie; struct MovieHeader; struct TrackHeader; class BoxReader; class MEDIA_EXPORT MP4StreamParser : public StreamParser { public: MP4StreamParser(const std::set<int>& audio_object_types, bool has_sbr, bool has_flac); ~MP4StreamParser() override; void Init(InitCB init_cb, const NewConfigCB& config_cb, const NewBuffersCB& new_buffers_cb, bool ignore_text_tracks, const EncryptedMediaInitDataCB& encrypted_media_init_data_cb, const NewMediaSegmentCB& new_segment_cb, const EndMediaSegmentCB& end_of_segment_cb, MediaLog* media_log) override; void Flush() override; bool GetGenerateTimestampsFlag() const override; bool Parse(const uint8_t* buf, int size) override; // Calculates the rotation value from the track header display matricies. VideoTransformation CalculateRotation(const TrackHeader& track, const MovieHeader& movie); private: enum State { kWaitingForInit, kParsingBoxes, kWaitingForSampleData, kEmittingSamples, kError }; ParseResult ParseBox(); bool ParseMoov(mp4::BoxReader* reader); bool ParseMoof(mp4::BoxReader* reader); void OnEncryptedMediaInitData( const std::vector<ProtectionSystemSpecificHeader>& headers); // To retain proper framing, each 'mdat' atom must be read; to limit memory // usage, the atom's data needs to be discarded incrementally as frames are // extracted from the stream. This function discards data from the stream up // to |max_clear_offset|, updating the |mdat_tail_| value so that framing can // be retained after all 'mdat' information has been read. |max_clear_offset| // is the upper bound on what can be removed from |queue_|. Anything below // this offset is no longer needed by the parser. // Returns 'true' on success, 'false' if there was an error. bool ReadAndDiscardMDATsUntil(int64_t max_clear_offset); void ChangeState(State new_state); bool EmitConfigs(); #if BUILDFLAG(USE_PROPRIETARY_CODECS) bool PrepareAACBuffer(const AAC& aac_config, std::vector<uint8_t>* frame_buf, std::vector<SubsampleEntry>* subsamples) const; #endif ParseResult EnqueueSample(BufferQueueMap* buffers); bool SendAndFlushSamples(BufferQueueMap* buffers); void Reset(); // Checks to see if we have enough data in |queue_| to transition to // kEmittingSamples and start enqueuing samples. bool HaveEnoughDataToEnqueueSamples(); // Sets |highest_end_offset_| based on the data in |moov_| // and |moof|. Returns true if |highest_end_offset_| was successfully // computed. bool ComputeHighestEndOffset(const MovieFragment& moof); State state_; InitCB init_cb_; NewConfigCB config_cb_; NewBuffersCB new_buffers_cb_; EncryptedMediaInitDataCB encrypted_media_init_data_cb_; NewMediaSegmentCB new_segment_cb_; EndMediaSegmentCB end_of_segment_cb_; MediaLog* media_log_; OffsetByteQueue queue_; // These two parameters are only valid in the |kEmittingSegments| state. // // |moof_head_| is the offset of the start of the most recently parsed moof // block. All byte offsets in sample information are relative to this offset, // as mandated by the Media Source spec. int64_t moof_head_; // |mdat_tail_| is the stream offset of the end of the current 'mdat' box. // Valid iff it is greater than the head of the queue. int64_t mdat_tail_; // The highest end offset in the current moof. This offset is // relative to |moof_head_|. This value is used to make sure we have collected // enough bytes to parse all samples and aux_info in the current moof. int64_t highest_end_offset_; std::unique_ptr<mp4::Movie> moov_; std::unique_ptr<mp4::TrackRunIterator> runs_; bool has_audio_; bool has_video_; std::set<uint32_t> audio_track_ids_; std::set<uint32_t> video_track_ids_; // The object types allowed for audio tracks. For FLAC indication, use // |has_flac_|; const std::set<int> audio_object_types_; const bool has_sbr_; const bool has_flac_; // Tracks the number of MEDIA_LOGS for skipping empty trun samples. int num_empty_samples_skipped_; // Tracks the number of MEDIA_LOGS for invalid bitstream conversion. int num_invalid_conversions_; // Tracks the number of MEDIA_LOGS for video keyframe MP4<->frame mismatch. int num_video_keyframe_mismatches_; DISALLOW_COPY_AND_ASSIGN(MP4StreamParser); }; } // namespace mp4 } // namespace media #endif // MEDIA_FORMATS_MP4_MP4_STREAM_PARSER_H_
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
5d791efc44f234cf1ad070af855c4a8708676035
33a6c411c7a3a87f6ef03fb702801e65196e0ee9
/a.cpp
5ec6907444a9b64ac1e98eb2ff84ba5c9c422ea7
[]
no_license
pwl-curry/maillist
f85195662f8753f0c3c03fc26355669b592c0276
42a799e4feed29b858db07c1f045a7d009d29811
refs/heads/master
2023-04-10T02:50:52.531082
2021-04-26T11:55:34
2021-04-26T11:55:34
361,715,509
0
0
null
null
null
null
GB18030
C++
false
false
10,182
cpp
#include<stdio.h> #include<stdlib.h> #include<string.h> #define len sizeof(struct curry) #include<iostream> using namespace std; typedef struct curry { int xuhao; char name[50]; char xb[50]; char phone[50]; char year[5]; char jiguan[100]; char dz[100]; char jtdz[100]; char txdz[100]; char youbian[100]; struct curry* next; }; curry;//申明结构体链表,用于储存联系人信息 curry* head = (curry*)malloc(len), * p, * pre = head, * p3;//定义链表指针,作为全局变量 void print(struct curry* p) { printf("序号:%d 姓名:%s\n", p->xuhao, p->name), printf(" 年龄:%s\n", p->year); printf(" 性别:%s\n", p->xb); printf(" 电话号码:%s\n", p->phone); printf(" 工作地址:%s\n", p->dz); printf(" 籍贯:%s\n", p->jiguan); printf(" 家庭地址:%s\n", p->jtdz); printf(" 通信地址:%s\n", p->txdz); printf(" 邮编:%s\n", p->youbian); }//输出某位联系人的所有信息 void xianshi() { struct curry* p; for (p = head->next; p != NULL; p = p->next) { printf("序号:%d 姓名:%s\n", p->xuhao, p->name), printf(" 年龄:%s\n", p->year); printf(" 性别:%s\n", p->xb); printf(" 电话号码:%s\n", p->phone); printf(" 工作地址:%s\n", p->dz); printf(" 籍贯:%s\n", p->jiguan); printf(" 家庭地址:%s\n", p->jtdz); printf(" 通信地址:%s\n", p->txdz); printf(" 邮编:%s\n", p->youbian); } }//在屏幕上显示所有联系人的所有信息 void xiugai() { char x[20]; int t = 0; char b[20]; printf("已有联系人信息:\n"); xianshi(); printf("\n输入要修改的联系人的姓名:"); scanf("%s", x); for (p3 = head, p = head->next, t = 0; p != NULL; p3 = p, p = p->next) if (strcmp(p->name, x) == 0) { printf("原信息姓名:\n"); print(p); t++; printf("修改项原信息:\n"); scanf("%s", b); if (strcmp(p->name, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->name); } if (strcmp(p->year, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->year); } if (strcmp(p->xb, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->xb); } if (strcmp(p->phone, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->phone); } if (strcmp(p->dz, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->dz); } if (strcmp(p->jiguan, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->jiguan); } if (strcmp(p->jtdz, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->jtdz); } if (strcmp(p->txdz, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->txdz); } if (strcmp(p->youbian, b) == 0) { printf("修改项修改后信息:"); scanf("%s", p->youbian); } printf("修改成功\n"); break; } if (t == 0) printf("无此联系人\n"); int n; printf("请选择是否继续执行此功能:1-继续 0-否"); scanf("%d", &n); if (n == 1) xiugai(); else return; }//修改某位联系人的信息 void tianjia() { char b[20]; int t, j; printf("已有联系人信息:\n"); xianshi(); printf("输入要添加联系人的序号:"); scanf("%d", &j); printf("输入添加信息:姓名:\n"); scanf("%s", b); p = (curry*)malloc(len); strcpy(p->name, b); p->xuhao = j; printf("\n年龄:"); scanf("%s", p->year); printf("\n性别:"); scanf("%s", p->xb); printf("\n电话号码:"); scanf("%s", p->phone); printf("\n工作地址:"); scanf("%s", p->dz); printf("\n籍贯:"); scanf("%s", p->jiguan); printf("\n家庭地址:"); scanf("%s", p->jtdz); printf("\n通讯地址:"); scanf("%s", p->txdz); printf("\n邮编:"); scanf("%s", p->youbian); printf("添加成功\n"); pre->next = p; pre = p; pre->next = 0; int n; printf("请选择是否继续执行此功能:1-继续 0-否"); scanf("%d", &n); if (n == 1) tianjia(); else return; } void chazhao1(int n) { char b[20]; int t; if (n == 1) { t = 0; printf("请输入要查找的姓名"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->name, b) == 0) { print(p); t++; } if (t == 0) printf("无此联系人\n"); } if (n == 2) { t = 0; printf("请输入要查找的年龄"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->year, b) == 0) { print(p); t++; } if (t == 0) printf("无此年龄的联系人\n"); } if (n == 3) { t = 0; printf("请输入要查找的性别"); scanf("%s", b); printf("查找信息如下:\n");; for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->xb, b) == 0) { print(p); t++; } if (t == 0) printf("无此性别的联系人\n"); } if (n == 4) { t = 0; printf("请输入要查找的电话号码"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->phone, b) == 0) { print(p); t++; } if (t == 0) printf("无此电话号码联系人\n"); } if (n == 5) { t = 0; printf("请输入要查找的工作地址"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->dz, b) == 0) { print(p); t++; } if (t == 0) printf("无此工作地址的联系人\n"); } if (n == 6) { t = 0; printf("请输入要查找的籍贯"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->jiguan, b) == 0) { print(p); t++; } if (t == 0) printf("无此籍贯的联系人\n"); } if (n == 7) { t = 0; printf("请输入要查找的家庭地址"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->jtdz, b) == 0) { print(p); t++; } if (t == 0) printf("无此家庭地址的联系人\n"); } if (n == 8) { t = 0; printf("请输入要查找的通信地址"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->txdz, b) == 0) { print(p); t++; } if (t == 0) printf("无此通信地址的联系人\n"); } if (n == 9) { t = 0; printf("请输入要查找的邮编"); scanf("%s", b); printf("查找信息如下:\n"); for (p = head->next, t = 0; p != NULL; p = p->next) if (strcmp(p->youbian, b) == 0) { print(p); t++; } if (t == 0) printf("无此邮编的联系人\n"); } }//寻找含有某信息的联系人 void chazhao() { int n; printf("请输入要查找信息的类型:1-姓名 2-年龄 3-性别 4-电话号码 5-工作地址\n 6-籍贯 7-家庭地址 8-通讯地址 9-邮编\n"); scanf("%d", &n); if (n <= 0 || n >= 10) { printf("输入有误,请重新输入:\n"); chazhao(); } printf("已有联系人信息:\n"); xianshi(); chazhao1(n); int k; printf("请选择是否继续执行此功能:1-继续 0-否"); scanf("%d", &k); if (n == 1) chazhao(); else return; }//显示要查找的某类信息 void shanchu() { int t; char b[20]; printf("已有联系人信息:\n"); xianshi(); printf("需删除联系人的姓名:"); scanf("%s", b); for (pre = head, p = pre->next, t = 0; p != NULL; pre = p, p = pre->next) if (strcmp(p->name, b) == 0) { pre->next = p->next; printf("删除成功\n"); free(p); t++; break; } if (t == 0) printf("无此联系人\n"); int n; printf("请选择是否继续执行此功能:1-继续 0-否"); scanf("%d", &n); if (n == 1) shanchu(); else return; }//删除某位联系人的所有信息 void shuju() { int t = 0; FILE* p1, * fp; fp = fopen("shuju.dat", "r"); p1 = fopen("shu.dat", "w"); while (!feof(fp)) { p = (curry*)malloc(len); fscanf(fp, "%d %s %s %s %s %s %s %s %s %s", &p->xuhao, p->name, p->year, p->xb, p->phone, p->dz, p->jiguan, p->jtdz, p->txdz, p->youbian); t++; pre->next = p; pre = p; } pre->next = NULL; printf("已输入\n"); int n; printf("请选择是否继续执行此功能:1-继续 0-否"); scanf("%d", &n); if (n == 1) shuju(); else return; }//将文件中的联系人的信息导入到链表中 void baocun() { int t = 0; FILE* p1, * fp; fp = fopen("shuju.dat", "r"); p1 = fopen("shu.dat", "w"); for (p = head->next, t = 0; p != NULL; p = p->next) { fprintf(p1, "%d %s %s %s %s %s %s %s %s %s", p->xuhao, p->name, p->year, p->xb, p->phone, p->dz, p->jiguan, p->jtdz, p->txdz, p->youbian); t++; } if (t == 0) printf("此通信录无联系人\n"); else { printf("以保存到文件”shu.dat“中\n"); fclose(p1); int n; printf("请选择是否继续执行此功能:1-继续 0-否"); scanf("%d", &n); if (n == 1) baocun(); else return; } }//将整理后的联系人信息到如到文件中 void mean() { printf("*******************通信录功能***********************\n"); printf("*********1-导入初始数据 2-添加联系人************\n"); printf("*********3-查找联系人 4-修改联系人信息********\n"); printf("*********5-删除联系人 6-保存联系人信息********\n"); printf("*********7-显示联系人信息 0-结束运行**************\n"); printf("****************************************************\n"); } int main() { int n; head->next = 0; while (1) { mean(); printf("请输入您要执行的功能:"); scanf("%d", &n); if (n == 0) break; if (n < 0 || n >= 8) { printf("输入有误,请重新输入:\n"); main(); } switch (n) { case 1:shuju(); break; case 2:tianjia(); break; case 3:chazhao(); break; case 4:xiugai(); break; case 5:shanchu(); break; case 7:xianshi(); break; case 6:baocun(); break; } } system("cls"); system("pause"); return 0; }
[ "2154653723@qq.com" ]
2154653723@qq.com
c71627c26dfba47073fc1503c4ec8fd87ac7e7f9
b71136d14603e25a0637de413d2316f96272e148
/nsaChallenge/R0.cpp
7c74a7ffcbe1a537fd9904232cc6dcbe7d48c608
[]
no_license
JSwidinsky/CompetitiveProgramming
34df380b26fad53191a07c692298d68394b4fd48
3742a1c5f9b422f2957ad7d67fed4fbfb6981455
refs/heads/master
2020-09-24T07:48:34.797284
2020-05-21T17:45:29
2020-05-21T17:45:29
225,705,620
0
0
null
null
null
null
UTF-8
C++
false
false
71
cpp
#include <bits/stdc++.h> using namespace std; class int main() { }
[ "swidinjo@gmail.com" ]
swidinjo@gmail.com
f8b7c75d5146ab60dbfa5d995cdf5dfbdff2cd24
37d7eb7ac7c5238bfd43900ac1a10ca601f2dcd2
/Senior/CS475/GL-Examples/dijkstra.cpp
ffaac81ec8cd57aeca1b409d993a7b1474378f43
[ "MIT" ]
permissive
kalaarentz/CollegeCode
9cb493b1a8238ca9fb87a900d33a5cfc76232f40
b906a85880d846c69d925c14859b873010e204cd
refs/heads/master
2020-03-19T04:40:04.891795
2018-06-02T21:54:00
2018-06-02T21:54:00
135,852,084
0
0
null
null
null
null
UTF-8
C++
false
false
4,683
cpp
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <string.h> #include <stdbool.h> #include "platformGL.h" #include "modelVAO.h" #include "minHeap.h" #include "meshTables.h" #include "dijkstra.h" #define SQR(x) ((x) * (x)) // vertex attributes consist of Vector3 for coordinates, Vector3 for normals and Vector2 for UVs #define ATTR_SIZE (8) #define ATTR_BYTES (ATTR_SIZE * sizeof(GLfloat)) int srcVertex, sinkVertex; enum dijkstraModes dijkstraMode = IDLE; int singleStep; bool animating = true; bool haveWall = false; struct faceModelVAO * theModel; void dijkstra_Init(struct faceModelVAO * model) { theModel = model; } void initUVs() { // set UVs of all vertices to 0.0 and FLT_MAX // associate model attrs with buffer data for (int i = 0; i < theModel->vCnt; i++) { GLfloat * uvs = uvsFor(theModel,i); uvs[0] = 0.0; uvs[1] = FLT_MAX; } glBindBuffer(GL_ARRAY_BUFFER,theModel->VBO[0]); glBufferData(GL_ARRAY_BUFFER,theModel->vCnt * ATTR_BYTES,theModel->attr.data(),GL_DYNAMIC_DRAW); } void dijkstra_PickEndPoints() { // init model uvs, init heap, randomly pick src and sink vertices, insert src into heap initUVs(); heap_Init(); srcVertex = (rand() % theModel->vCnt); sinkVertex =(rand() % theModel->vCnt); fprintf(stderr,"pick %d %d\n",srcVertex,sinkVertex); heap_Insert(srcVertex,0.0); dijkstraMode = EXPANDING; //HaveWall = false; } void dijkstra_ReverseEndPoints() { // reverse src and sink and restart initUVs(); heap_Init(); int v = srcVertex; srcVertex = sinkVertex; sinkVertex = v; heap_Insert(srcVertex,0.0); dijkstraMode = EXPANDING; //HaveWall = false; } void disjkatra_UpdateModelAttrs(int vertex) { // update model attr data for vertex glBindBuffer(GL_ARRAY_BUFFER,theModel->VBO[0]); glBufferSubData(GL_ARRAY_BUFFER,vertex * ATTR_BYTES,ATTR_BYTES,&(theModel->attr[vertex*ATTR_SIZE])); } float distance(int a, int b) { GLfloat * aPos = positionFor(theModel,a); GLfloat * bPos = positionFor(theModel,b); return sqrt(SQR(aPos[0] - bPos[0]) + SQR(aPos[1] - bPos[1]) + SQR(aPos[2] - bPos[2])); } void dijkstra_ExpandOneVertex() { // run Dijkstra for one vertex -- remove vertex from heap, if sink return, if marked as already enumerated return, if not mark as enumerated update model data for vertex, get list of neighbors and loop, calc new distance and compare to old, if new smaller update vertex data, if neighbor has been enumerated then return otherwise insert into heap, vertices may be inserted multiple times before being enumerated // if (!SingleStep) return; // SingleStep = 0; int vertex; float value; if (!heap_Remove(&vertex,&value)) { dijkstraMode = IDLE; printf("Dijkstra ended with empy heap before finding sink\n"); return; } if (vertex == sinkVertex) { dijkstraMode = IDLE; // dijkstraMode = (HaveWall) ? (IDLE) : (PATHING); return; } if (uvsFor(theModel,vertex)[0] == 1.0) return; uvsFor(theModel,vertex)[0] = 1.0; disjkatra_UpdateModelAttrs(vertex); std::vector<int> neighs = mesh_V2V(vertex); for (int i = 0; i < neighs.size(); i++) { int neigh = neighs[i]; float newdistance = value + distance(vertex,neigh); float olddistance = uvsFor(theModel,neigh)[1]; if (newdistance < olddistance) { uvsFor(theModel,neigh)[1] = newdistance; disjkatra_UpdateModelAttrs(neigh); } if (uvsFor(theModel,neigh)[0] == 0.0) heap_Insert(neigh,uvsFor(theModel,neigh)[1]); } } void dijkstra_ExpandBoundary() { // expand boundary one vertex at a time for the current size of the heap for (int cnt = heap_Size() ; cnt > 0; cnt--) { dijkstra_ExpandOneVertex(); } } void appendToPath(struct faceModel & path, int vertex) { float *vc = positionFor(theModel,vertex); Vector3 p1 = Vector3(vc[0],vc[1],vc[2]); float *vn = normalFor(theModel,vertex); Vector3 n1 = Vector3(vn[0],vn[1],vn[2]); n1 = 0.05 * n1; Vector3 p2 = p1 + n1; Vector3 lastvert = path.vrts[path.vrts.size()-1]; } struct faceModel dijkstra_MakePath() { struct faceModel path; appendToPath(path,sinkVertex); int vertex = sinkVertex; while (vertex != srcVertex) { std::vector<int> neighs = mesh_V2V(vertex); int minvertex = vertex; float mindist = uvsFor(theModel,vertex)[1]; for (int i = 0; i < neighs.size(); i++) { int neigh = neighs[i]; if (uvsFor(theModel,neigh)[1] < mindist) { minvertex = neigh; mindist = uvsFor(theModel,neigh)[1]; } } if (vertex == minvertex) break; vertex = minvertex; appendToPath(path,vertex); } haveWall = true; dijkstraMode = IDLE; return path; }
[ "arentz.kala@uwlax.edu" ]
arentz.kala@uwlax.edu
10ea4338dcabb61ee99e20e992d435bbb50d0c21
5f5bb4fe58ca6c9758e5ecd4f1acd7f3af7a41a4
/codeforces/contests/educational/80-div2/c.cpp
80538b3eb346cfa5e277777b3980d9e59a2f2eec
[ "MIT" ]
permissive
tysm/cpsols
61a93de55dbeb2d92d92c80681d6615521d3d0ba
262212646203e516d1706edf962290de93762611
refs/heads/master
2023-03-10T01:04:39.409948
2021-02-23T21:49:55
2021-02-23T21:49:55
202,269,911
4
0
null
null
null
null
UTF-8
C++
false
false
217
cpp
#include <cpplib/stdinc.hpp> #include <cpplib/math/modc.hpp> int32_t main(){ desync(); int n, m; cin >> n >> m; ModC<> mc; cout << mc.C(2*m + n-1, 2*m) << endl; // stars and bars. return 0; }
[ "ysm.thalles@gmail.com" ]
ysm.thalles@gmail.com
2c071b048b8374ba18e3bf112acdfce9e29424de
b11ee5504fe02b1b2e06c66565cebf9930935e36
/pyotr-the-pig-journey/pyotr-the-pig-journey/ScoreInfo.h
724b8cacec098c9849687c82bd4db9eec8473cde
[]
no_license
ivan-uskov/project-work-basics-labs
58ab5e7dffc8e20c217cf50714c072c190b20542
9f57bdd43b9053f9056f7b44b4307fe38feb3391
refs/heads/master
2021-01-19T06:56:20.712337
2017-01-29T17:07:36
2017-01-29T17:07:36
68,512,614
0
0
null
null
null
null
UTF-8
C++
false
false
553
h
#pragma once #include "ResourceIdentifiers.h" #include "Component.h" #include <SFML/Graphics/Sprite.hpp> namespace GUI { class ScoreInfo : public Component { public: ScoreInfo(const sf::Texture& texture, sf::IntRect const& textureRect); void operator ++ (); void setScore(unsigned score); unsigned getScore() const; protected: void drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const override; private: unsigned mScore = 0; sf::Sprite mSprite; }; }
[ "ivan.uskov@cpslabs.net" ]
ivan.uskov@cpslabs.net
85af6c5ff4bbb7b6a1d3b07800bd0fbd128c1a4e
d93daecc66d746411223e2bb4d4cfeac10ddc34f
/_Stack.h
e3480477a8da1d78fd7022cd286a7792f1b98fc3
[]
no_license
ElliotVilhelm/Tokenizer
809022c06ab308c6cbcecdf81d8a91324da7d1a5
1687a3a57be80f9b2efd7ee9600d8649095dc3fe
refs/heads/master
2021-01-23T04:29:20.672573
2017-03-26T23:56:15
2017-03-26T23:56:15
86,201,809
0
0
null
null
null
null
UTF-8
C++
false
false
1,484
h
#ifndef _STACK_H #define _STACK_H #include "doublylinkedlist.h" template<class T> class _Stack { public: _Stack(); _Stack(T item); // BIG THREE _Stack(_Stack<T>& CopyThis); ~_Stack(); _Stack<T> &operator =(const _Stack<T>& CopyMe); ostream& operator<< (T item); void Push(T item); T Pop(); bool IsEmpty(); T Top(); void PrintStack(); private: Node<T>* _head; }; template<class T> _Stack<T>::_Stack() { _head = NULL; } template<class T> _Stack<T>::_Stack(T item) { _head = NULL; insertHead(item, _head); } template<class T> _Stack<T>::_Stack(_Stack<T> &CopyThis) { _head = CopyList(CopyThis._head); } template<class T> _Stack<T>::~_Stack() { RemoveAll(_head); cout<<endl<<"~_Stack() fired\n\n"; } template<class T> _Stack<T> &_Stack<T>::operator =(const _Stack<T> &CopyMe) { if(&CopyMe == this) return *this; RemoveAll(_head); _head = CopyList(CopyMe._head); } template<class T> ostream &_Stack<T>::operator<<(T item) { insertTail(item); } template<class T> void _Stack<T>::Push(T item) { insertHead(item, _head); } template<class T> T _Stack<T>::Pop() { return RemoveHead(_head); } template<class T> bool _Stack<T>::IsEmpty() { if(_head == NULL) return true; return false; } template<class T> T _Stack<T>::Top() { return _head->Item; } template<class T> void _Stack<T>::PrintStack() { ::Print(_head); } #endif // _STACK_H
[ "elliot@pourmand.com" ]
elliot@pourmand.com
4f36045cfc0b5a990b973ff09fc8dd38416441aa
091b4208ec2d988da9d1939809999974d2232c3b
/node_modules/node-red-node-serialport/node_modules/serialport/src/win/stdstring.h
2dd0bd8b2f450b4e92ded76f893b7f49d4c613a6
[ "Apache-2.0", "MIT" ]
permissive
albertisfu/smart
386cceb787eb63a6176766bd87a061c79fb9dca9
0da65d79df15af85dec1df4411e78cd90d3b664c
refs/heads/master
2020-12-25T19:15:34.751346
2019-12-10T15:41:02
2019-12-10T15:41:02
40,388,181
0
0
Apache-2.0
2019-12-10T15:45:17
2015-08-08T02:04:47
JavaScript
ISO-8859-1
C++
false
false
136,424
h
// ============================================================================= // FILE: StdString.h // AUTHOR: Joe O'Leary (with outside help noted in comments) // // If you find any bugs in this code, please let me know: // // jmoleary@earthlink.net // http://www.joeo.net/stdstring.htm (a bit outdated) // // The latest version of this code should always be available at the // following link: // // http://www.joeo.net/code/StdString.zip (Dec 6, 2003) // // // REMARKS: // This header file declares the CStdStr template. This template derives // the Standard C++ Library basic_string<> template and add to it the // the following conveniences: // - The full MFC CString set of functions (including implicit cast) // - writing to/reading from COM IStream interfaces // - Functional objects for use in STL algorithms // // From this template, we intstantiate two classes: CStdStringA and // CStdStringW. The name "CStdString" is just a #define of one of these, // based upone the UNICODE macro setting // // This header also declares our own version of the MFC/ATL UNICODE-MBCS // conversion macros. Our version looks exactly like the Microsoft's to // facilitate portability. // // NOTE: // If you you use this in an MFC or ATL build, you should include either // afx.h or atlbase.h first, as appropriate. // // PEOPLE WHO HAVE CONTRIBUTED TO THIS CLASS: // // Several people have helped me iron out problems and othewise improve // this class. OK, this is a long list but in my own defense, this code // has undergone two major rewrites. Many of the improvements became // necessary after I rewrote the code as a template. Others helped me // improve the CString facade. // // Anyway, these people are (in chronological order): // // - Pete the Plumber (???) // - Julian Selman // - Chris (of Melbsys) // - Dave Plummer // - John C Sipos // - Chris Sells // - Nigel Nunn // - Fan Xia // - Matthew Williams // - Carl Engman // - Mark Zeren // - Craig Watson // - Rich Zuris // - Karim Ratib // - Chris Conti // - Baptiste Lepilleur // - Greg Pickles // - Jim Cline // - Jeff Kohn // - Todd Heckel // - Ullrich Pollähne // - Joe Vitaterna // - Joe Woodbury // - Aaron (no last name) // - Joldakowski (???) // - Scott Hathaway // - Eric Nitzche // - Pablo Presedo // - Farrokh Nejadlotfi // - Jason Mills // - Igor Kholodov // - Mike Crusader // - John James // - Wang Haifeng // - Tim Dowty // - Arnt Witteveen // - Glen Maynard // - Paul DeMarco // - Bagira (full name?) // - Ronny Schulz // - Jakko Van Hunen // - Charles Godwin // - Henk Demper // - Greg Marr // - Bill Carducci // - Brian Groose // - MKingman // - Don Beusee // // REVISION HISTORY // // 2005-JAN-10 - Thanks to Don Beusee for pointing out the danger in mapping // length-checked formatting functions to non-length-checked // CRT equivalents. Also thanks to him for motivating me to // optimize my implementation of Replace() // // 2004-APR-22 - A big, big thank you to "MKingman" (whoever you are) for // finally spotting a silly little error in StdCodeCvt that // has been causing me (and users of CStdString) problems for // years in some relatively rare conversions. I had reversed // two length arguments. // // 2003-NOV-24 - Thanks to a bunch of people for helping me clean up many // compiler warnings (and yes, even a couple of actual compiler // errors). These include Henk Demper for figuring out how // to make the Intellisense work on with CStdString on VC6, // something I was never able to do. Greg Marr pointed out // a compiler warning about an unreferenced symbol and a // problem with my version of Load in MFC builds. Bill // Carducci took a lot of time with me to help me figure out // why some implementations of the Standard C++ Library were // returning error codes for apparently successful conversions // between ASCII and UNICODE. Finally thanks to Brian Groose // for helping me fix compiler signed unsigned warnings in // several functions. // // 2003-JUL-10 - Thanks to Charles Godwin for making me realize my 'FmtArg' // fixes had inadvertently broken the DLL-export code (which is // normally commented out. I had to move it up higher. Also // this helped me catch a bug in ssicoll that would prevent // compilation, otherwise. // // 2003-MAR-14 - Thanks to Jakko Van Hunen for pointing out a copy-and-paste // bug in one of the overloads of FmtArg. // // 2003-MAR-10 - Thanks to Ronny Schulz for (twice!) sending me some changes // to help CStdString build on SGI and for pointing out an // error in placement of my preprocessor macros for ssfmtmsg. // // 2002-NOV-26 - Thanks to Bagira for pointing out that my implementation of // SpanExcluding was not properly handling the case in which // the string did NOT contain any of the given characters // // 2002-OCT-21 - Many thanks to Paul DeMarco who was invaluable in helping me // get this code working with Borland's free compiler as well // as the Dev-C++ compiler (available free at SourceForge). // // 2002-SEP-13 - Thanks to Glen Maynard who helped me get rid of some loud // but harmless warnings that were showing up on g++. Glen // also pointed out that some pre-declarations of FmtArg<> // specializations were unnecessary (and no good on G++) // // 2002-JUN-26 - Thanks to Arnt Witteveen for pointing out that I was using // static_cast<> in a place in which I should have been using // reinterpret_cast<> (the ctor for unsigned char strings). // That's what happens when I don't unit-test properly! // Arnt also noticed that CString was silently correcting the // 'nCount' argument to Left() and Right() where CStdString was // not (and crashing if it was bad). That is also now fixed! // // 2002-FEB-25 - Thanks to Tim Dowty for pointing out (and giving me the fix // for) a conversion problem with non-ASCII MBCS characters. // CStdString is now used in my favorite commercial MP3 player! // // 2001-DEC-06 - Thanks to Wang Haifeng for spotting a problem in one of the // assignment operators (for _bstr_t) that would cause compiler // errors when refcounting protection was turned off. // // 2001-NOV-27 - Remove calls to operator!= which involve reverse_iterators // due to a conflict with the rel_ops operator!=. Thanks to // John James for pointing this out. // // 2001-OCT-29 - Added a minor range checking fix for the Mid function to // make it as forgiving as CString's version is. Thanks to // Igor Kholodov for noticing this. // - Added a specialization of std::swap for CStdString. Thanks // to Mike Crusader for suggesting this! It's commented out // because you're not supposed to inject your own code into the // 'std' namespace. But if you don't care about that, it's // there if you want it // - Thanks to Jason Mills for catching a case where CString was // more forgiving in the Delete() function than I was. // // 2001-JUN-06 - I was violating the Standard name lookup rules stated // in [14.6.2(3)]. None of the compilers I've tried so // far apparently caught this but HP-UX aCC 3.30 did. The // fix was to add 'this->' prefixes in many places. // Thanks to Farrokh Nejadlotfi for this! // // 2001-APR-27 - StreamLoad was calculating the number of BYTES in one // case, not characters. Thanks to Pablo Presedo for this. // // 2001-FEB-23 - Replace() had a bug which caused infinite loops if the // source string was empty. Fixed thanks to Eric Nitzsche. // // 2001-FEB-23 - Scott Hathaway was a huge help in providing me with the // ability to build CStdString on Sun Unix systems. He // sent me detailed build reports about what works and what // does not. If CStdString compiles on your Unix box, you // can thank Scott for it. // // 2000-DEC-29 - Joldakowski noticed one overload of Insert failed to do a // range check as CString's does. Now fixed -- thanks! // // 2000-NOV-07 - Aaron pointed out that I was calling static member // functions of char_traits via a temporary. This was not // technically wrong, but it was unnecessary and caused // problems for poor old buggy VC5. Thanks Aaron! // // 2000-JUL-11 - Joe Woodbury noted that the CString::Find docs don't match // what the CString::Find code really ends up doing. I was // trying to match the docs. Now I match the CString code // - Joe also caught me truncating strings for GetBuffer() calls // when the supplied length was less than the current length. // // 2000-MAY-25 - Better support for STLPORT's Standard library distribution // - Got rid of the NSP macro - it interfered with Koenig lookup // - Thanks to Joe Woodbury for catching a TrimLeft() bug that // I introduced in January. Empty strings were not getting // trimmed // // 2000-APR-17 - Thanks to Joe Vitaterna for pointing out that ReverseFind // is supposed to be a const function. // // 2000-MAR-07 - Thanks to Ullrich Pollähne for catching a range bug in one // of the overloads of assign. // // 2000-FEB-01 - You can now use CStdString on the Mac with CodeWarrior! // Thanks to Todd Heckel for helping out with this. // // 2000-JAN-23 - Thanks to Jim Cline for pointing out how I could make the // Trim() function more efficient. // - Thanks to Jeff Kohn for prompting me to find and fix a typo // in one of the addition operators that takes _bstr_t. // - Got rid of the .CPP file - you only need StdString.h now! // // 1999-DEC-22 - Thanks to Greg Pickles for helping me identify a problem // with my implementation of CStdString::FormatV in which // resulting string might not be properly NULL terminated. // // 1999-DEC-06 - Chris Conti pointed yet another basic_string<> assignment // bug that MS has not fixed. CStdString did nothing to fix // it either but it does now! The bug was: create a string // longer than 31 characters, get a pointer to it (via c_str()) // and then assign that pointer to the original string object. // The resulting string would be empty. Not with CStdString! // // 1999-OCT-06 - BufferSet was erasing the string even when it was merely // supposed to shrink it. Fixed. Thanks to Chris Conti. // - Some of the Q172398 fixes were not checking for assignment- // to-self. Fixed. Thanks to Baptiste Lepilleur. // // 1999-AUG-20 - Improved Load() function to be more efficient by using // SizeOfResource(). Thanks to Rich Zuris for this. // - Corrected resource ID constructor, again thanks to Rich. // - Fixed a bug that occurred with UNICODE characters above // the first 255 ANSI ones. Thanks to Craig Watson. // - Added missing overloads of TrimLeft() and TrimRight(). // Thanks to Karim Ratib for pointing them out // // 1999-JUL-21 - Made all calls to GetBuf() with no args check length first. // // 1999-JUL-10 - Improved MFC/ATL independence of conversion macros // - Added SS_NO_REFCOUNT macro to allow you to disable any // reference-counting your basic_string<> impl. may do. // - Improved ReleaseBuffer() to be as forgiving as CString. // Thanks for Fan Xia for helping me find this and to // Matthew Williams for pointing it out directly. // // 1999-JUL-06 - Thanks to Nigel Nunn for catching a very sneaky bug in // ToLower/ToUpper. They should call GetBuf() instead of // data() in order to ensure the changed string buffer is not // reference-counted (in those implementations that refcount). // // 1999-JUL-01 - Added a true CString facade. Now you can use CStdString as // a drop-in replacement for CString. If you find this useful, // you can thank Chris Sells for finally convincing me to give // in and implement it. // - Changed operators << and >> (for MFC CArchive) to serialize // EXACTLY as CString's do. So now you can send a CString out // to a CArchive and later read it in as a CStdString. I have // no idea why you would want to do this but you can. // // 1999-JUN-21 - Changed the CStdString class into the CStdStr template. // - Fixed FormatV() to correctly decrement the loop counter. // This was harmless bug but a bug nevertheless. Thanks to // Chris (of Melbsys) for pointing it out // - Changed Format() to try a normal stack-based array before // using to _alloca(). // - Updated the text conversion macros to properly use code // pages and to fit in better in MFC/ATL builds. In other // words, I copied Microsoft's conversion stuff again. // - Added equivalents of CString::GetBuffer, GetBufferSetLength // - new sscpy() replacement of CStdString::CopyString() // - a Trim() function that combines TrimRight() and TrimLeft(). // // 1999-MAR-13 - Corrected the "NotSpace" functional object to use _istpace() // instead of _isspace() Thanks to Dave Plummer for this. // // 1999-FEB-26 - Removed errant line (left over from testing) that #defined // _MFC_VER. Thanks to John C Sipos for noticing this. // // 1999-FEB-03 - Fixed a bug in a rarely-used overload of operator+() that // caused infinite recursion and stack overflow // - Added member functions to simplify the process of // persisting CStdStrings to/from DCOM IStream interfaces // - Added functional objects (e.g. StdStringLessNoCase) that // allow CStdStrings to be used as keys STL map objects with // case-insensitive comparison // - Added array indexing operators (i.e. operator[]). I // originally assumed that these were unnecessary and would be // inherited from basic_string. However, without them, Visual // C++ complains about ambiguous overloads when you try to use // them. Thanks to Julian Selman to pointing this out. // // 1998-FEB-?? - Added overloads of assign() function to completely account // for Q172398 bug. Thanks to "Pete the Plumber" for this // // 1998-FEB-?? - Initial submission // // COPYRIGHT: // 2002 Joseph M. O'Leary. This code is 100% free. Use it anywhere you // want. Rewrite it, restructure it, whatever. If you can write software // that makes money off of it, good for you. I kinda like capitalism. // Please don't blame me if it causes your $30 billion dollar satellite // explode in orbit. If you redistribute it in any form, I'd appreciate it // if you would leave this notice here. // ============================================================================= // Avoid multiple inclusion #ifndef STDSTRING_H #define STDSTRING_H // When using VC, turn off browser references // Turn off unavoidable compiler warnings #if defined(_MSC_VER) && (_MSC_VER > 1100) #pragma component(browser, off, references, "CStdString") #pragma warning (disable : 4290) // C++ Exception Specification ignored #pragma warning (disable : 4127) // Conditional expression is constant #pragma warning (disable : 4097) // typedef name used as synonym for class name #endif // Borland warnings to turn off #ifdef __BORLANDC__ #pragma option push -w-inl // #pragma warn -inl // Turn off inline function warnings #endif // SS_IS_INTRESOURCE // ----------------- // A copy of IS_INTRESOURCE from VC7. Because old VC6 version of winuser.h // doesn't have this. #define SS_IS_INTRESOURCE(_r) (false) #if !defined (SS_ANSI) && defined(_MSC_VER) #undef SS_IS_INTRESOURCE #if defined(_WIN64) #define SS_IS_INTRESOURCE(_r) (((unsigned __int64)(_r) >> 16) == 0) #else #define SS_IS_INTRESOURCE(_r) (((unsigned long)(_r) >> 16) == 0) #endif #endif // MACRO: SS_UNSIGNED // ------------------ // This macro causes the addition of a constructor and assignment operator // which take unsigned characters. CString has such functions and in order // to provide maximum CString-compatability, this code needs them as well. // In practice you will likely never need these functions... //#define SS_UNSIGNED #ifdef SS_ALLOW_UNSIGNED_CHARS #define SS_UNSIGNED #endif // MACRO: SS_SAFE_FORMAT // --------------------- // This macro provides limited compatability with a questionable CString // "feature". You can define it in order to avoid a common problem that // people encounter when switching from CString to CStdString. // // To illustrate the problem -- With CString, you can do this: // // CString sName("Joe"); // CString sTmp; // sTmp.Format("My name is %s", sName); // WORKS! // // However if you were to try this with CStdString, your program would // crash. // // CStdString sName("Joe"); // CStdString sTmp; // sTmp.Format("My name is %s", sName); // CRASHES! // // You must explicitly call c_str() or cast the object to the proper type // // sTmp.Format("My name is %s", sName.c_str()); // WORKS! // sTmp.Format("My name is %s", static_cast<PCSTR>(sName));// WORKS! // sTmp.Format("My name is %s", (PCSTR)sName); // WORKS! // // This is because it is illegal to pass anything but a POD type as a // variadic argument to a variadic function (i.e. as one of the "..." // arguments). The type const char* is a POD type. The type CStdString // is not. Of course, neither is the type CString, but CString lets you do // it anyway due to the way they laid out the class in binary. I have no // control over this in CStdString since I derive from whatever // implementation of basic_string is available. // // However if you have legacy code (which does this) that you want to take // out of the MFC world and you don't want to rewrite all your calls to // Format(), then you can define this flag and it will no longer crash. // // Note however that this ONLY works for Format(), not sprintf, fprintf, // etc. If you pass a CStdString object to one of those functions, your // program will crash. Not much I can do to get around this, short of // writing substitutes for those functions as well. #define SS_SAFE_FORMAT // use new template style Format() function // MACRO: SS_NO_IMPLICIT_CAST // -------------------------- // Some people don't like the implicit cast to const char* (or rather to // const CT*) that CStdString (and MFC's CString) provide. That was the // whole reason I created this class in the first place, but hey, whatever // bakes your cake. Just #define this macro to get rid of the the implicit // cast. //#define SS_NO_IMPLICIT_CAST // gets rid of operator const CT*() // MACRO: SS_NO_REFCOUNT // --------------------- // turns off reference counting at the assignment level. Only needed // for the version of basic_string<> that comes with Visual C++ versions // 6.0 or earlier, and only then in some heavily multithreaded scenarios. // Uncomment it if you feel you need it. //#define SS_NO_REFCOUNT // MACRO: SS_WIN32 // --------------- // When this flag is set, we are building code for the Win32 platform and // may use Win32 specific functions (such as LoadString). This gives us // a couple of nice extras for the code. // // Obviously, Microsoft's is not the only compiler available for Win32 out // there. So I can't just check to see if _MSC_VER is defined to detect // if I'm building on Win32. So for now, if you use MS Visual C++ or // Borland's compiler, I turn this on. Otherwise you may turn it on // yourself, if you prefer #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WIN32) #define SS_WIN32 #endif // MACRO: SS_ANSI // -------------- // When this macro is defined, the code attempts only to use ANSI/ISO // standard library functions to do it's work. It will NOT attempt to use // any Win32 of Visual C++ specific functions -- even if they are // available. You may define this flag yourself to prevent any Win32 // of VC++ specific functions from being called. // If we're not on Win32, we MUST use an ANSI build #ifndef SS_WIN32 #if !defined(SS_NO_ANSI) #define SS_ANSI #endif #endif // MACRO: SS_ALLOCA // ---------------- // Some implementations of the Standard C Library have a non-standard // function known as alloca(). This functions allows one to allocate a // variable amount of memory on the stack. It is needed to implement // the ASCII/MBCS conversion macros. // // I wanted to find some way to determine automatically if alloca() is // available on this platform via compiler flags but that is asking for // trouble. The crude test presented here will likely need fixing on // other platforms. Therefore I'll leave it up to you to fiddle with // this test to determine if it exists. Just make sure SS_ALLOCA is or // is not defined as appropriate and you control this feature. #if defined(_MSC_VER) && !defined(SS_ANSI) #define SS_ALLOCA #endif // MACRO: SS_MBCS // -------------- // Setting this macro means you are using MBCS characters. In MSVC builds, // this macro gets set automatically by detection of the preprocessor flag // _MBCS. For other platforms you may set it manually if you wish. The // only effect it currently has is to cause the allocation of more space // for wchar_t --> char conversions. // Note that MBCS does not mean UNICODE. // // #define SS_MBCS // #ifdef _MBCS #define SS_MBCS #endif // MACRO SS_NO_LOCALE // ------------------ // If your implementation of the Standard C++ Library lacks the <locale> header, // you can #define this macro to make your code build properly. Note that this // is some of my newest code and frankly I'm not very sure of it, though it does // pass my unit tests. // #define SS_NO_LOCALE // Compiler Error regarding _UNICODE and UNICODE // ----------------------------------------------- // Microsoft header files are screwy. Sometimes they depend on a preprocessor // flag named "_UNICODE". Other times they check "UNICODE" (note the lack of // leading underscore in the second version". In several places, they silently // "synchronize" these two flags this by defining one of the other was defined. // In older version of this header, I used to try to do the same thing. // // However experience has taught me that this is a bad idea. You get weird // compiler errors that seem to indicate things like LPWSTR and LPTSTR not being // equivalent in UNICODE builds, stuff like that (when they MUST be in a proper // UNICODE build). You end up scratching your head and saying, "But that HAS // to compile!". // // So what should you do if you get this error? // // Make sure that both macros (_UNICODE and UNICODE) are defined before this // file is included. You can do that by either // // a) defining both yourself before any files get included // b) including the proper MS headers in the proper order // c) including this file before any other file, uncommenting // the #defines below, and commenting out the #errors // // Personally I recommend solution a) but it's your call. #ifdef _MSC_VER #if defined (_UNICODE) && !defined (UNICODE) #error UNICODE defined but not UNICODE // #define UNICODE // no longer silently fix this #endif #if defined (UNICODE) && !defined (_UNICODE) #error Warning, UNICODE defined but not _UNICODE // #define _UNICODE // no longer silently fix this #endif #endif // ----------------------------------------------------------------------------- // MIN and MAX. The Standard C++ template versions go by so many names (at // at least in the MS implementation) that you never know what's available // ----------------------------------------------------------------------------- template<class Type> inline const Type& SSMIN(const Type& arg1, const Type& arg2) { return arg2 < arg1 ? arg2 : arg1; } template<class Type> inline const Type& SSMAX(const Type& arg1, const Type& arg2) { return arg2 > arg1 ? arg2 : arg1; } // If they have not #included W32Base.h (part of my W32 utility library) then // we need to define some stuff. Otherwise, this is all defined there. #if !defined(W32BASE_H) // If they want us to use only standard C++ stuff (no Win32 stuff) #ifdef SS_ANSI // On Win32 we have TCHAR.H so just include it. This is NOT violating // the spirit of SS_ANSI as we are not calling any Win32 functions here. #ifdef SS_WIN32 #include <TCHAR.H> #include <WTYPES.H> #ifndef STRICT #define STRICT #endif // ... but on non-Win32 platforms, we must #define the types we need. #else typedef const char* PCSTR; typedef char* PSTR; typedef const wchar_t* PCWSTR; typedef wchar_t* PWSTR; #ifdef UNICODE typedef wchar_t TCHAR; #else typedef char TCHAR; #endif typedef wchar_t OLECHAR; #endif // #ifndef _WIN32 // Make sure ASSERT and verify are defined using only ANSI stuff #ifndef ASSERT #include <assert.h> #define ASSERT(f) assert((f)) #endif #ifndef VERIFY #ifdef _DEBUG #define VERIFY(x) ASSERT((x)) #else #define VERIFY(x) x #endif #endif #else // ...else SS_ANSI is NOT defined #include <TCHAR.H> #include <WTYPES.H> #ifndef STRICT #define STRICT #endif // Make sure ASSERT and verify are defined #ifndef ASSERT #include <crtdbg.h> #define ASSERT(f) _ASSERTE((f)) #endif #ifndef VERIFY #ifdef _DEBUG #define VERIFY(x) ASSERT((x)) #else #define VERIFY(x) x #endif #endif #endif // #ifdef SS_ANSI #ifndef UNUSED #define UNUSED(x) x #endif #endif // #ifndef W32BASE_H // Standard headers needed #include <string> // basic_string #include <algorithm> // for_each, etc. #include <functional> // for StdStringLessNoCase, et al #ifndef SS_NO_LOCALE #include <locale> // for various facets #endif // If this is a recent enough version of VC include comdef.h, so we can write // member functions to deal with COM types & compiler support classes e.g. // _bstr_t #if defined (_MSC_VER) && (_MSC_VER >= 1100) #include <comdef.h> #define SS_INC_COMDEF // signal that we #included MS comdef.h file #define STDSTRING_INC_COMDEF #define SS_NOTHROW __declspec(nothrow) #else #define SS_NOTHROW #endif #ifndef TRACE #define TRACE_DEFINED_HERE #define TRACE #endif // Microsoft defines PCSTR, PCWSTR, etc, but no PCTSTR. I hate to use the // versions with the "L" in front of them because that's a leftover from Win 16 // days, even though it evaluates to the same thing. Therefore, Define a PCSTR // as an LPCTSTR. #if !defined(PCTSTR) && !defined(PCTSTR_DEFINED) typedef const TCHAR* PCTSTR; #define PCTSTR_DEFINED #endif #if !defined(PCOLESTR) && !defined(PCOLESTR_DEFINED) typedef const OLECHAR* PCOLESTR; #define PCOLESTR_DEFINED #endif #if !defined(POLESTR) && !defined(POLESTR_DEFINED) typedef OLECHAR* POLESTR; #define POLESTR_DEFINED #endif #if !defined(PCUSTR) && !defined(PCUSTR_DEFINED) typedef const unsigned char* PCUSTR; typedef unsigned char* PUSTR; #define PCUSTR_DEFINED #endif // SGI compiler 7.3 doesnt know these types - oh and btw, remember to use // -LANG:std in the CXX Flags #if defined(__sgi) typedef unsigned long DWORD; typedef void * LPCVOID; #endif // SS_USE_FACET macro and why we need it: // // Since I'm a good little Standard C++ programmer, I use locales. Thus, I // need to make use of the use_facet<> template function here. Unfortunately, // this need is complicated by the fact the MS' implementation of the Standard // C++ Library has a non-standard version of use_facet that takes more // arguments than the standard dictates. Since I'm trying to write CStdString // to work with any version of the Standard library, this presents a problem. // // The upshot of this is that I can't do 'use_facet' directly. The MS' docs // tell me that I have to use a macro, _USE() instead. Since _USE obviously // won't be available in other implementations, this means that I have to write // my OWN macro -- SS_USE_FACET -- that evaluates either to _USE or to the // standard, use_facet. // // If you are having trouble with the SS_USE_FACET macro, in your implementation // of the Standard C++ Library, you can define your own version of SS_USE_FACET. #ifndef schMSG #define schSTR(x) #x #define schSTR2(x) schSTR(x) #define schMSG(desc) message(__FILE__ "(" schSTR2(__LINE__) "):" #desc) #endif #ifndef SS_USE_FACET // STLPort #defines a macro (__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) for // all MSVC builds, erroneously in my opinion. It causes problems for // my SS_ANSI builds. In my code, I always comment out that line. You'll // find it in \stlport\config\stl_msvc.h #if defined(__SGI_STL_PORT) && (__SGI_STL_PORT >= 0x400 ) #if defined(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) && defined(_MSC_VER) #ifdef SS_ANSI #pragma schMSG(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS defined!!) #endif #endif #define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc) #elif defined(_MSC_VER ) #define SS_USE_FACET(loc, fac) std::_USE(loc, fac) // ...and #elif defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE) #define SS_USE_FACET(loc, fac) std::use_facet(loc, (fac*)0) #else #define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc) #endif #endif // ============================================================================= // UNICODE/MBCS conversion macros. Made to work just like the MFC/ATL ones. // ============================================================================= #include <wchar.h> // Added to Std Library with Amendment #1. // First define the conversion helper functions. We define these regardless of // any preprocessor macro settings since their names won't collide. // Not sure if we need all these headers. I believe ANSI says we do. #include <stdio.h> #include <stdarg.h> #include <wctype.h> #include <ctype.h> #include <stdlib.h> #ifndef va_start #include <varargs.h> #endif #ifdef SS_NO_LOCALE #if defined(_WIN32) || defined (_WIN32_WCE) inline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc, UINT acp=CP_ACP) { ASSERT(0 != pSrcA); ASSERT(0 != pDstW); pDstW[0] = '\0'; MultiByteToWideChar(acp, 0, pSrcA, nSrc, pDstW, nDst); return pDstW; } inline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCUSTR pSrcA, int nSrc, UINT acp=CP_ACP) { return StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, acp); } inline PSTR StdCodeCvt(PSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP) { ASSERT(0 != pDstA); ASSERT(0 != pSrcW); pDstA[0] = '\0'; WideCharToMultiByte(acp, 0, pSrcW, nSrc, pDstA, nDst, 0, 0); return pDstA; } inline PUSTR StdCodeCvt(PUSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP) { return (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, acp); } #else #endif #else // StdCodeCvt - made to look like Win32 functions WideCharToMultiByte // and MultiByteToWideChar but uses locales in SS_ANSI // builds. There are a number of overloads. // First argument is the destination buffer. // Second argument is the source buffer //#if defined (SS_ANSI) || !defined (SS_WIN32) // 'SSCodeCvt' - shorthand name for the codecvt facet we use typedef std::codecvt<wchar_t, char, mbstate_t> SSCodeCvt; inline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc, const std::locale& loc=std::locale()) { ASSERT(0 != pSrcA); ASSERT(0 != pDstW); pDstW[0] = '\0'; if ( nSrc > 0 ) { PCSTR pNextSrcA = pSrcA; PWSTR pNextDstW = pDstW; const SSCodeCvt& conv = SS_USE_FACET(loc, SSCodeCvt); SSCodeCvt::state_type st= { 0 }; SSCodeCvt::result res = conv.in(st, pSrcA, pSrcA + nSrc, pNextSrcA, pDstW, pDstW + nDst, pNextDstW); ASSERT(SSCodeCvt::ok == res); ASSERT(SSCodeCvt::error != res); ASSERT(pNextDstW >= pDstW); ASSERT(pNextSrcA >= pSrcA); // Null terminate the converted string if ( pNextDstW - pDstW > nDst ) *(pDstW + nDst) = '\0'; else *pNextDstW = '\0'; } return pDstW; } inline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCUSTR pSrcA, int nSrc, const std::locale& loc=std::locale()) { return StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, loc); } inline PSTR StdCodeCvt(PSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc, const std::locale& loc=std::locale()) { ASSERT(0 != pDstA); ASSERT(0 != pSrcW); pDstA[0] = '\0'; if ( nSrc > 0 ) { PSTR pNextDstA = pDstA; PCWSTR pNextSrcW = pSrcW; const SSCodeCvt& conv = SS_USE_FACET(loc, SSCodeCvt); SSCodeCvt::state_type st= { 0 }; SSCodeCvt::result res = conv.out(st, pSrcW, pSrcW + nSrc, pNextSrcW, pDstA, pDstA + nDst, pNextDstA); ASSERT(SSCodeCvt::error != res); ASSERT(SSCodeCvt::ok == res); // strict, comment out for sanity ASSERT(pNextDstA >= pDstA); ASSERT(pNextSrcW >= pSrcW); // Null terminate the converted string if ( pNextDstA - pDstA > nDst ) *(pDstA + nDst) = '\0'; else *pNextDstA = '\0'; } return pDstA; } inline PUSTR StdCodeCvt(PUSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc, const std::locale& loc=std::locale()) { return (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, loc); } #endif // Unicode/MBCS conversion macros are only available on implementations of // the "C" library that have the non-standard _alloca function. As far as I // know that's only Microsoft's though I've heard that the function exists // elsewhere. #if defined(SS_ALLOCA) && !defined SS_NO_CONVERSION #include <malloc.h> // needed for _alloca // Define our conversion macros to look exactly like Microsoft's to // facilitate using this stuff both with and without MFC/ATL #ifdef _CONVERSION_USES_THREAD_LOCALE #ifndef _DEBUG #define SSCVT int _cvt; _cvt; UINT _acp=GetACP(); \ _acp; PCWSTR _pw; _pw; PCSTR _pa; _pa #else #define SSCVT int _cvt = 0; _cvt; UINT _acp=GetACP();\ _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa #endif #define SSA2W(pa) (\ ((_pa = pa) == 0) ? 0 : (\ _cvt = (sslen(_pa)),\ StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \ _pa, _cvt, _acp))) #define SSW2A(pw) (\ ((_pw = pw) == 0) ? 0 : (\ _cvt = sslen(_pw), \ StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \ _pw, _cvt, _acp))) #else #ifndef _DEBUG #define SSCVT int _cvt; _cvt; UINT _acp=CP_ACP; _acp;\ PCWSTR _pw; _pw; PCSTR _pa; _pa #else #define SSCVT int _cvt = 0; _cvt; UINT _acp=CP_ACP; \ _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa #endif #define SSA2W(pa) (\ ((_pa = pa) == 0) ? 0 : (\ _cvt = (sslen(_pa)),\ StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \ _pa, _cvt))) #define SSW2A(pw) (\ ((_pw = pw) == 0) ? 0 : (\ _cvt = (sslen(_pw)),\ StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \ _pw, _cvt))) #endif #define SSA2CW(pa) ((PCWSTR)SSA2W((pa))) #define SSW2CA(pw) ((PCSTR)SSW2A((pw))) #ifdef UNICODE #define SST2A SSW2A #define SSA2T SSA2W #define SST2CA SSW2CA #define SSA2CT SSA2CW // (Did you get a compiler error here about not being able to convert // PTSTR into PWSTR? Then your _UNICODE and UNICODE flags are messed // up. Best bet: #define BOTH macros before including any MS headers.) inline PWSTR SST2W(PTSTR p) { return p; } inline PTSTR SSW2T(PWSTR p) { return p; } inline PCWSTR SST2CW(PCTSTR p) { return p; } inline PCTSTR SSW2CT(PCWSTR p) { return p; } #else #define SST2W SSA2W #define SSW2T SSW2A #define SST2CW SSA2CW #define SSW2CT SSW2CA inline PSTR SST2A(PTSTR p) { return p; } inline PTSTR SSA2T(PSTR p) { return p; } inline PCSTR SST2CA(PCTSTR p) { return p; } inline PCTSTR SSA2CT(PCSTR p) { return p; } #endif // #ifdef UNICODE #if defined(UNICODE) // in these cases the default (TCHAR) is the same as OLECHAR inline PCOLESTR SST2COLE(PCTSTR p) { return p; } inline PCTSTR SSOLE2CT(PCOLESTR p) { return p; } inline POLESTR SST2OLE(PTSTR p) { return p; } inline PTSTR SSOLE2T(POLESTR p) { return p; } #elif defined(OLE2ANSI) // in these cases the default (TCHAR) is the same as OLECHAR inline PCOLESTR SST2COLE(PCTSTR p) { return p; } inline PCTSTR SSOLE2CT(PCOLESTR p) { return p; } inline POLESTR SST2OLE(PTSTR p) { return p; } inline PTSTR SSOLE2T(POLESTR p) { return p; } #else //CharNextW doesn't work on Win95 so we use this #define SST2COLE(pa) SSA2CW((pa)) #define SST2OLE(pa) SSA2W((pa)) #define SSOLE2CT(po) SSW2CA((po)) #define SSOLE2T(po) SSW2A((po)) #endif #ifdef OLE2ANSI #define SSW2OLE SSW2A #define SSOLE2W SSA2W #define SSW2COLE SSW2CA #define SSOLE2CW SSA2CW inline POLESTR SSA2OLE(PSTR p) { return p; } inline PSTR SSOLE2A(POLESTR p) { return p; } inline PCOLESTR SSA2COLE(PCSTR p) { return p; } inline PCSTR SSOLE2CA(PCOLESTR p){ return p; } #else #define SSA2OLE SSA2W #define SSOLE2A SSW2A #define SSA2COLE SSA2CW #define SSOLE2CA SSW2CA inline POLESTR SSW2OLE(PWSTR p) { return p; } inline PWSTR SSOLE2W(POLESTR p) { return p; } inline PCOLESTR SSW2COLE(PCWSTR p) { return p; } inline PCWSTR SSOLE2CW(PCOLESTR p){ return p; } #endif // Above we've defined macros that look like MS' but all have // an 'SS' prefix. Now we need the real macros. We'll either // get them from the macros above or from MFC/ATL. #if defined (USES_CONVERSION) #define _NO_STDCONVERSION // just to be consistent #else #ifdef _MFC_VER #include <afxconv.h> #define _NO_STDCONVERSION // just to be consistent #else #define USES_CONVERSION SSCVT #define A2CW SSA2CW #define W2CA SSW2CA #define T2A SST2A #define A2T SSA2T #define T2W SST2W #define W2T SSW2T #define T2CA SST2CA #define A2CT SSA2CT #define T2CW SST2CW #define W2CT SSW2CT #define ocslen sslen #define ocscpy sscpy #define T2COLE SST2COLE #define OLE2CT SSOLE2CT #define T2OLE SST2COLE #define OLE2T SSOLE2CT #define A2OLE SSA2OLE #define OLE2A SSOLE2A #define W2OLE SSW2OLE #define OLE2W SSOLE2W #define A2COLE SSA2COLE #define OLE2CA SSOLE2CA #define W2COLE SSW2COLE #define OLE2CW SSOLE2CW #endif // #ifdef _MFC_VER #endif // #ifndef USES_CONVERSION #endif // #ifndef SS_NO_CONVERSION // Define ostring - generic name for std::basic_string<OLECHAR> #if !defined(ostring) && !defined(OSTRING_DEFINED) typedef std::basic_string<OLECHAR> ostring; #define OSTRING_DEFINED #endif // StdCodeCvt when there's no conversion to be done inline PSTR StdCodeCvt(PSTR pDst, int nDst, PCSTR pSrc, int nSrc) { int nChars = SSMIN(nSrc, nDst); if ( nChars > 0 ) { pDst[0] = '\0'; std::basic_string<char>::traits_type::copy(pDst, pSrc, nChars); // std::char_traits<char>::copy(pDst, pSrc, nChars); pDst[nChars] = '\0'; } return pDst; } inline PSTR StdCodeCvt(PSTR pDst, int nDst, PCUSTR pSrc, int nSrc) { return StdCodeCvt(pDst, nDst, (PCSTR)pSrc, nSrc); } inline PUSTR StdCodeCvt(PUSTR pDst, int nDst, PCSTR pSrc, int nSrc) { return (PUSTR)StdCodeCvt((PSTR)pDst, nDst, pSrc, nSrc); } inline PWSTR StdCodeCvt(PWSTR pDst, int nDst, PCWSTR pSrc, int nSrc) { int nChars = SSMIN(nSrc, nDst); if ( nChars > 0 ) { pDst[0] = '\0'; std::basic_string<wchar_t>::traits_type::copy(pDst, pSrc, nChars); // std::char_traits<wchar_t>::copy(pDst, pSrc, nChars); pDst[nChars] = '\0'; } return pDst; } // Define tstring -- generic name for std::basic_string<TCHAR> #if !defined(tstring) && !defined(TSTRING_DEFINED) typedef std::basic_string<TCHAR> tstring; #define TSTRING_DEFINED #endif // a very shorthand way of applying the fix for KB problem Q172398 // (basic_string assignment bug) #if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) #define Q172398(x) (x).erase() #else #define Q172398(x) #endif // ============================================================================= // INLINE FUNCTIONS ON WHICH CSTDSTRING RELIES // // Usually for generic text mapping, we rely on preprocessor macro definitions // to map to string functions. However the CStdStr<> template cannot use // macro-based generic text mappings because its character types do not get // resolved until template processing which comes AFTER macro processing. In // other words, the preprocessor macro UNICODE is of little help to us in the // CStdStr template // // Therefore, to keep the CStdStr declaration simple, we have these inline // functions. The template calls them often. Since they are inline (and NOT // exported when this is built as a DLL), they will probably be resolved away // to nothing. // // Without these functions, the CStdStr<> template would probably have to broken // out into two, almost identical classes. Either that or it would be a huge, // convoluted mess, with tons of "if" statements all over the place checking the // size of template parameter CT. // ============================================================================= #ifdef SS_NO_LOCALE // -------------------------------------------------------------------------- // Win32 GetStringTypeEx wrappers // -------------------------------------------------------------------------- inline bool wsGetStringType(LCID lc, DWORD dwT, PCSTR pS, int nSize, WORD* pWd) { return FALSE != GetStringTypeExA(lc, dwT, pS, nSize, pWd); } inline bool wsGetStringType(LCID lc, DWORD dwT, PCWSTR pS, int nSize, WORD* pWd) { return FALSE != GetStringTypeExW(lc, dwT, pS, nSize, pWd); } template<typename CT> inline bool ssisspace (CT t) { WORD toYourMother; return wsGetStringType(GetThreadLocale(), CT_CTYPE1, &t, 1, &toYourMother) && 0 != (C1_BLANK & toYourMother); } #endif // If they defined SS_NO_REFCOUNT, then we must convert all assignments #if defined (_MSC_VER) && (_MSC_VER < 1300) #ifdef SS_NO_REFCOUNT #define SSREF(x) (x).c_str() #else #define SSREF(x) (x) #endif #else #define SSREF(x) (x) #endif // ----------------------------------------------------------------------------- // sslen: strlen/wcslen wrappers // ----------------------------------------------------------------------------- template<typename CT> inline int sslen(const CT* pT) { return 0 == pT ? 0 : (int)std::basic_string<CT>::traits_type::length(pT); // return 0 == pT ? 0 : std::char_traits<CT>::length(pT); } inline SS_NOTHROW int sslen(const std::string& s) { return static_cast<int>(s.length()); } inline SS_NOTHROW int sslen(const std::wstring& s) { return static_cast<int>(s.length()); } // ----------------------------------------------------------------------------- // sstolower/sstoupper -- convert characters to upper/lower case // ----------------------------------------------------------------------------- #ifdef SS_NO_LOCALE inline char sstoupper(char ch) { return (char)::toupper(ch); } inline wchar_t sstoupper(wchar_t ch){ return (wchar_t)::towupper(ch); } inline char sstolower(char ch) { return (char)::tolower(ch); } inline wchar_t sstolower(wchar_t ch){ return (wchar_t)::tolower(ch); } #else template<typename CT> inline CT sstolower(const CT& t, const std::locale& loc = std::locale()) { return std::tolower<CT>(t, loc); } template<typename CT> inline CT sstoupper(const CT& t, const std::locale& loc = std::locale()) { return std::toupper<CT>(t, loc); } #endif // ----------------------------------------------------------------------------- // ssasn: assignment functions -- assign "sSrc" to "sDst" // ----------------------------------------------------------------------------- typedef std::string::size_type SS_SIZETYPE; // just for shorthand, really typedef std::string::pointer SS_PTRTYPE; typedef std::wstring::size_type SW_SIZETYPE; typedef std::wstring::pointer SW_PTRTYPE; inline void ssasn(std::string& sDst, const std::string& sSrc) { if ( sDst.c_str() != sSrc.c_str() ) { sDst.erase(); sDst.assign(SSREF(sSrc)); } } inline void ssasn(std::string& sDst, PCSTR pA) { // Watch out for NULLs, as always. if ( 0 == pA ) { sDst.erase(); } // If pA actually points to part of sDst, we must NOT erase(), but // rather take a substring else if ( pA >= sDst.c_str() && pA <= sDst.c_str() + sDst.size() ) { sDst =sDst.substr(static_cast<SS_SIZETYPE>(pA-sDst.c_str())); } // Otherwise (most cases) apply the assignment bug fix, if applicable // and do the assignment else { Q172398(sDst); sDst.assign(pA); } } inline void ssasn(std::string& sDst, const std::wstring& sSrc) { if ( sSrc.empty() ) { sDst.erase(); } else { int nDst = static_cast<int>(sSrc.size()); // In MBCS builds, pad the buffer to account for the possibility of // some 3 byte characters. Not perfect but should get most cases. #ifdef SS_MBCS nDst = static_cast<int>(static_cast<double>(nDst) * 1.3); #endif sDst.resize(nDst+1); PCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst, sSrc.c_str(), static_cast<int>(sSrc.size())); // In MBCS builds, we don't know how long the destination string will be. #ifdef SS_MBCS sDst.resize(sslen(szCvt)); #else szCvt; sDst.resize(sSrc.size()); #endif } } inline void ssasn(std::string& sDst, PCWSTR pW) { int nSrc = sslen(pW); if ( nSrc > 0 ) { int nSrc = sslen(pW); int nDst = nSrc; // In MBCS builds, pad the buffer to account for the possibility of // some 3 byte characters. Not perfect but should get most cases. #ifdef SS_MBCS nDst = static_cast<int>(static_cast<double>(nDst) * 1.3); #endif sDst.resize(nDst + 1); PCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst, pW, nSrc); // In MBCS builds, we don't know how long the destination string will be. #ifdef SS_MBCS sDst.resize(sslen(szCvt)); #else sDst.resize(nDst); szCvt; #endif } else { sDst.erase(); } } inline void ssasn(std::string& sDst, const int nNull) { UNUSED(nNull); ASSERT(nNull==0); sDst.assign(""); } inline void ssasn(std::wstring& sDst, const std::wstring& sSrc) { if ( sDst.c_str() != sSrc.c_str() ) { sDst.erase(); sDst.assign(SSREF(sSrc)); } } inline void ssasn(std::wstring& sDst, PCWSTR pW) { // Watch out for NULLs, as always. if ( 0 == pW ) { sDst.erase(); } // If pW actually points to part of sDst, we must NOT erase(), but // rather take a substring else if ( pW >= sDst.c_str() && pW <= sDst.c_str() + sDst.size() ) { sDst = sDst.substr(static_cast<SW_SIZETYPE>(pW-sDst.c_str())); } // Otherwise (most cases) apply the assignment bug fix, if applicable // and do the assignment else { Q172398(sDst); sDst.assign(pW); } } #undef StrSizeType inline void ssasn(std::wstring& sDst, const std::string& sSrc) { if ( sSrc.empty() ) { sDst.erase(); } else { int nSrc = static_cast<int>(sSrc.size()); int nDst = nSrc; sDst.resize(nSrc+1); PCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst, sSrc.c_str(), nSrc); sDst.resize(sslen(szCvt)); } } inline void ssasn(std::wstring& sDst, PCSTR pA) { int nSrc = sslen(pA); if ( 0 == nSrc ) { sDst.erase(); } else { int nDst = nSrc; sDst.resize(nDst+1); PCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst, pA, nSrc); sDst.resize(sslen(szCvt)); } } inline void ssasn(std::wstring& sDst, const int nNull) { UNUSED(nNull); ASSERT(nNull==0); sDst.assign(L""); } // ----------------------------------------------------------------------------- // ssadd: string object concatenation -- add second argument to first // ----------------------------------------------------------------------------- inline void ssadd(std::string& sDst, const std::wstring& sSrc) { int nSrc = static_cast<int>(sSrc.size()); if ( nSrc > 0 ) { int nDst = static_cast<int>(sDst.size()); int nAdd = nSrc; // In MBCS builds, pad the buffer to account for the possibility of // some 3 byte characters. Not perfect but should get most cases. #ifdef SS_MBCS nAdd = static_cast<int>(static_cast<double>(nAdd) * 1.3); #endif sDst.resize(nDst+nAdd+1); PCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst), nAdd, sSrc.c_str(), nSrc); #ifdef SS_MBCS sDst.resize(nDst + sslen(szCvt)); #else sDst.resize(nDst + nAdd); szCvt; #endif } } inline void ssadd(std::string& sDst, const std::string& sSrc) { sDst += sSrc; } inline void ssadd(std::string& sDst, PCWSTR pW) { int nSrc = sslen(pW); if ( nSrc > 0 ) { int nDst = static_cast<int>(sDst.size()); int nAdd = nSrc; #ifdef SS_MBCS nAdd = static_cast<int>(static_cast<double>(nAdd) * 1.3); #endif sDst.resize(nDst + nAdd + 1); PCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst), nAdd, pW, nSrc); #ifdef SS_MBCS sDst.resize(nDst + sslen(szCvt)); #else sDst.resize(nDst + nSrc); szCvt; #endif } } inline void ssadd(std::string& sDst, PCSTR pA) { if ( pA ) { // If the string being added is our internal string or a part of our // internal string, then we must NOT do any reallocation without // first copying that string to another object (since we're using a // direct pointer) if ( pA >= sDst.c_str() && pA <= sDst.c_str()+sDst.length()) { if ( sDst.capacity() <= sDst.size()+sslen(pA) ) sDst.append(std::string(pA)); else sDst.append(pA); } else { sDst.append(pA); } } } inline void ssadd(std::wstring& sDst, const std::wstring& sSrc) { sDst += sSrc; } inline void ssadd(std::wstring& sDst, const std::string& sSrc) { if ( !sSrc.empty() ) { int nSrc = static_cast<int>(sSrc.size()); int nDst = static_cast<int>(sDst.size()); sDst.resize(nDst + nSrc + 1); PCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst), nSrc, sSrc.c_str(), nSrc+1); #ifdef SS_MBCS sDst.resize(nDst + sslen(szCvt)); #else sDst.resize(nDst + nSrc); szCvt; #endif } } inline void ssadd(std::wstring& sDst, PCSTR pA) { int nSrc = sslen(pA); if ( nSrc > 0 ) { int nDst = static_cast<int>(sDst.size()); sDst.resize(nDst + nSrc + 1); PCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst), nSrc, pA, nSrc+1); #ifdef SS_MBCS sDst.resize(nDst + sslen(szCvt)); #else sDst.resize(nDst + nSrc); szCvt; #endif } } inline void ssadd(std::wstring& sDst, PCWSTR pW) { if ( pW ) { // If the string being added is our internal string or a part of our // internal string, then we must NOT do any reallocation without // first copying that string to another object (since we're using a // direct pointer) if ( pW >= sDst.c_str() && pW <= sDst.c_str()+sDst.length()) { if ( sDst.capacity() <= sDst.size()+sslen(pW) ) sDst.append(std::wstring(pW)); else sDst.append(pW); } else { sDst.append(pW); } } } // ----------------------------------------------------------------------------- // sscmp: comparison (case sensitive, not affected by locale) // ----------------------------------------------------------------------------- template<typename CT> inline int sscmp(const CT* pA1, const CT* pA2) { CT f; CT l; do { f = *(pA1++); l = *(pA2++); } while ( (f) && (f == l) ); return (int)(f - l); } // ----------------------------------------------------------------------------- // ssicmp: comparison (case INsensitive, not affected by locale) // ----------------------------------------------------------------------------- template<typename CT> inline int ssicmp(const CT* pA1, const CT* pA2) { // Using the "C" locale = "not affected by locale" std::locale loc = std::locale::classic(); const std::ctype<CT>& ct = SS_USE_FACET(loc, std::ctype<CT>); CT f; CT l; do { f = ct.tolower(*(pA1++)); l = ct.tolower(*(pA2++)); } while ( (f) && (f == l) ); return (int)(f - l); } // ----------------------------------------------------------------------------- // ssupr/sslwr: Uppercase/Lowercase conversion functions // ----------------------------------------------------------------------------- template<typename CT> inline void sslwr(CT* pT, size_t nLen, const std::locale& loc=std::locale()) { SS_USE_FACET(loc, std::ctype<CT>).tolower(pT, pT+nLen); } template<typename CT> inline void ssupr(CT* pT, size_t nLen, const std::locale& loc=std::locale()) { SS_USE_FACET(loc, std::ctype<CT>).toupper(pT, pT+nLen); } // ----------------------------------------------------------------------------- // vsprintf/vswprintf or _vsnprintf/_vsnwprintf equivalents. In standard // builds we can't use _vsnprintf/_vsnwsprintf because they're MS extensions. // // ----------------------------------------------------------------------------- // Borland's headers put some ANSI "C" functions in the 'std' namespace. // Promote them to the global namespace so we can use them here. #if defined(__BORLANDC__) using std::vsprintf; using std::vswprintf; #endif // GNU is supposed to have vsnprintf and vsnwprintf. But only the newer // distributions do. #if defined(__GNUC__) inline int ssvsprintf(PSTR pA, size_t nCount, PCSTR pFmtA, va_list vl) { return vsnprintf(pA, nCount, pFmtA, vl); } inline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl) { return vswprintf(pW, nCount, pFmtW, vl); } // Else if this is VC++ in a regular (non-ANSI) build #elif defined(_MSC_VER) && !defined(SS_ANSI) inline int ssvsprintf(PSTR pA, size_t nCount, PCSTR pFmtA, va_list vl) { return _vsnprintf(pA, nCount, pFmtA, vl); } inline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl) { return _vsnwprintf(pW, nCount, pFmtW, vl); } // Else (an ANSI build) if they want to allow "dangerous" (i.e. non-length- // checked) formatting #elif defined (SS_DANGEROUS_FORMAT) // ignore buffer size parameter if needed? inline int ssvsprintf(PSTR pA, size_t /*nCount*/, PCSTR pFmtA, va_list vl) { return vsprintf(pA, pFmtA, vl); } inline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl) { // JMO: Some distributions of the "C" have a version of vswprintf that // takes 3 arguments (e.g. Microsoft, Borland, GNU). Others have a // version which takes 4 arguments (an extra "count" argument in the // second position. The best stab I can take at this so far is that if // you are NOT running with MS, Borland, or GNU, then I'll assume you // have the version that takes 4 arguments. // // I'm sure that these checks don't catch every platform correctly so if // you get compiler errors on one of the lines immediately below, it's // probably because your implemntation takes a different number of // arguments. You can comment out the offending line (and use the // alternate version) or you can figure out what compiler flag to check // and add that preprocessor check in. Regardless, if you get an error // on these lines, I'd sure like to hear from you about it. // // Thanks to Ronny Schulz for the SGI-specific checks here. // #if !defined(__MWERKS__) && !defined(__SUNPRO_CC_COMPAT) && !defined(__SUNPRO_CC) #if !defined(_MSC_VER) \ && !defined (__BORLANDC__) \ && !defined(__GNUC__) \ && !defined(__sgi) return vswprintf(pW, nCount, pFmtW, vl); // suddenly with the current SGI 7.3 compiler there is no such function as // vswprintf and the substitute needs explicit casts to compile #elif defined(__sgi) nCount; return vsprintf( (char *)pW, (char *)pFmtW, vl); #else nCount; return vswprintf(pW, pFmtW, vl); #endif } // OK, it's some kind of ANSI build but no "dangerous" formatting allowed #else // GOT COMPILER PROBLEMS HERE? // --------------------------- // Does your compiler choke on one or more of the following 2 functions? It // probably means that you don't have have either vsnprintf or vsnwprintf in // your version of the CRT. This is understandable since neither is an ANSI // "C" function. However it still leaves you in a dilemma. In order to make // this code build, you're going to have to to use some non-length-checked // formatting functions that every CRT has: vsprintf and vswprintf. // // This is very dangerous. With the proper erroneous (or malicious) code, it // can lead to buffer overlows and crashing your PC. Use at your own risk // In order to use them, just #define SS_DANGEROUS_FORMAT at the top of // this file. // // Even THEN you might not be all the way home due to some non-conforming // distributions. More on this in the comments below. inline int ssvsprintf(PSTR pA, size_t nCount, PCSTR pFmtA, va_list vl) { #ifdef _MSC_VER return _vsnprintf(pA, nCount, pFmtA, vl); #else return vsnprintf(pA, nCount, pFmtA, vl); #endif } inline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl) { #ifdef _MSC_VER return _vsnwprintf(pW, nCount, pFmtW, vl); #else return vsnwprintf(pW, nCount, pFmtW, vl); #endif } #endif // ----------------------------------------------------------------------------- // ssload: Type safe, overloaded ::LoadString wrappers // There is no equivalent of these in non-Win32-specific builds. However, I'm // thinking that with the message facet, there might eventually be one // ----------------------------------------------------------------------------- #if defined (SS_WIN32) && !defined(SS_ANSI) inline int ssload(HMODULE hInst, UINT uId, PSTR pBuf, int nMax) { return ::LoadStringA(hInst, uId, pBuf, nMax); } inline int ssload(HMODULE hInst, UINT uId, PWSTR pBuf, int nMax) { return ::LoadStringW(hInst, uId, pBuf, nMax); } #endif // ----------------------------------------------------------------------------- // sscoll/ssicoll: Collation wrappers // Note -- with MSVC I have reversed the arguments order here because the // functions appear to return the opposite of what they should // ----------------------------------------------------------------------------- #ifndef SS_NO_LOCALE template <typename CT> inline int sscoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2) { const std::collate<CT>& coll = SS_USE_FACET(std::locale(), std::collate<CT>); return coll.compare(sz2, sz2+nLen2, sz1, sz1+nLen1); } template <typename CT> inline int ssicoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2) { const std::locale loc; const std::collate<CT>& coll = SS_USE_FACET(loc, std::collate<CT>); // Some implementations seem to have trouble using the collate<> // facet typedefs so we'll just default to basic_string and hope // that's what the collate facet uses (which it generally should) // std::collate<CT>::string_type s1(sz1); // std::collate<CT>::string_type s2(sz2); const std::basic_string<CT> sEmpty; std::basic_string<CT> s1(sz1 ? sz1 : sEmpty.c_str()); std::basic_string<CT> s2(sz2 ? sz2 : sEmpty.c_str()); sslwr(const_cast<CT*>(s1.c_str()), nLen1, loc); sslwr(const_cast<CT*>(s2.c_str()), nLen2, loc); return coll.compare(s2.c_str(), s2.c_str()+nLen2, s1.c_str(), s1.c_str()+nLen1); } #endif // ----------------------------------------------------------------------------- // ssfmtmsg: FormatMessage equivalents. Needed because I added a CString facade // Again -- no equivalent of these on non-Win32 builds but their might one day // be one if the message facet gets implemented // ----------------------------------------------------------------------------- #if defined (SS_WIN32) && !defined(SS_ANSI) inline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId, DWORD dwLangId, PSTR pBuf, DWORD nSize, va_list* vlArgs) { return FormatMessageA(dwFlags, pSrc, dwMsgId, dwLangId, pBuf, nSize,vlArgs); } inline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId, DWORD dwLangId, PWSTR pBuf, DWORD nSize, va_list* vlArgs) { return FormatMessageW(dwFlags, pSrc, dwMsgId, dwLangId, pBuf, nSize,vlArgs); } #else #endif // FUNCTION: sscpy. Copies up to 'nMax' characters from pSrc to pDst. // ----------------------------------------------------------------------------- // FUNCTION: sscpy // inline int sscpy(PSTR pDst, PCSTR pSrc, int nMax=-1); // inline int sscpy(PUSTR pDst, PCSTR pSrc, int nMax=-1) // inline int sscpy(PSTR pDst, PCWSTR pSrc, int nMax=-1); // inline int sscpy(PWSTR pDst, PCWSTR pSrc, int nMax=-1); // inline int sscpy(PWSTR pDst, PCSTR pSrc, int nMax=-1); // // DESCRIPTION: // This function is very much (but not exactly) like strcpy. These // overloads simplify copying one C-style string into another by allowing // the caller to specify two different types of strings if necessary. // // The strings must NOT overlap // // "Character" is expressed in terms of the destination string, not // the source. If no 'nMax' argument is supplied, then the number of // characters copied will be sslen(pSrc). A NULL terminator will // also be added so pDst must actually be big enough to hold nMax+1 // characters. The return value is the number of characters copied, // not including the NULL terminator. // // PARAMETERS: // pSrc - the string to be copied FROM. May be a char based string, an // MBCS string (in Win32 builds) or a wide string (wchar_t). // pSrc - the string to be copied TO. Also may be either MBCS or wide // nMax - the maximum number of characters to be copied into szDest. Note // that this is expressed in whatever a "character" means to pDst. // If pDst is a wchar_t type string than this will be the maximum // number of wchar_ts that my be copied. The pDst string must be // large enough to hold least nMaxChars+1 characters. // If the caller supplies no argument for nMax this is a signal to // the routine to copy all the characters in pSrc, regardless of // how long it is. // // RETURN VALUE: none // ----------------------------------------------------------------------------- template<typename CT1, typename CT2> inline int sscpycvt(CT1* pDst, const CT2* pSrc, int nMax) { // Note -- we assume pDst is big enough to hold pSrc. If not, we're in // big trouble. No bounds checking. Caveat emptor. int nSrc = sslen(pSrc); const CT1* szCvt = StdCodeCvt(pDst, nMax, pSrc, nSrc); // If we're copying the same size characters, then all the "code convert" // just did was basically memcpy so the #of characters copied is the same // as the number requested. I should probably specialize this function // template to achieve this purpose as it is silly to do a runtime check // of a fact known at compile time. I'll get around to it. return sslen(szCvt); } inline int sscpycvt(PSTR pDst, PCSTR pSrc, int nMax) { int nCount = nMax; for (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount) std::basic_string<char>::traits_type::assign(*pDst, *pSrc); *pDst = '\0'; return nMax - nCount; } inline int sscpycvt(PWSTR pDst, PCWSTR pSrc, int nMax) { int nCount = nMax; for (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount) std::basic_string<wchar_t>::traits_type::assign(*pDst, *pSrc); *pDst = L'\0'; return nMax - nCount; } inline int sscpycvt(PWSTR pDst, PCSTR pSrc, int nMax) { // Note -- we assume pDst is big enough to hold pSrc. If not, we're in // big trouble. No bounds checking. Caveat emptor. const PWSTR szCvt = StdCodeCvt(pDst, nMax, pSrc, nMax); return sslen(szCvt); } template<typename CT1, typename CT2> inline int sscpy(CT1* pDst, const CT2* pSrc, int nMax, int nLen) { return sscpycvt(pDst, pSrc, SSMIN(nMax, nLen)); } template<typename CT1, typename CT2> inline int sscpy(CT1* pDst, const CT2* pSrc, int nMax) { return sscpycvt(pDst, pSrc, SSMIN(nMax, sslen(pSrc))); } template<typename CT1, typename CT2> inline int sscpy(CT1* pDst, const CT2* pSrc) { return sscpycvt(pDst, pSrc, sslen(pSrc)); } template<typename CT1, typename CT2> inline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc, int nMax) { return sscpycvt(pDst, sSrc.c_str(), SSMIN(nMax, (int)sSrc.length())); } template<typename CT1, typename CT2> inline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc) { return sscpycvt(pDst, sSrc.c_str(), (int)sSrc.length()); } #ifdef SS_INC_COMDEF template<typename CT1> inline int sscpy(CT1* pDst, const _bstr_t& bs, int nMax) { return sscpycvt(pDst, static_cast<PCOLESTR>(bs), SSMIN(nMax, static_cast<int>(bs.length()))); } template<typename CT1> inline int sscpy(CT1* pDst, const _bstr_t& bs) { return sscpy(pDst, bs, static_cast<int>(bs.length())); } #endif // ----------------------------------------------------------------------------- // Functional objects for changing case. They also let you pass locales // ----------------------------------------------------------------------------- #ifdef SS_NO_LOCALE template<typename CT> struct SSToUpper : public std::unary_function<CT, CT> { inline CT operator()(const CT& t) const { return sstoupper(t); } }; template<typename CT> struct SSToLower : public std::unary_function<CT, CT> { inline CT operator()(const CT& t) const { return sstolower(t); } }; #else template<typename CT> struct SSToUpper : public std::binary_function<CT, std::locale, CT> { inline CT operator()(const CT& t, const std::locale& loc) const { return sstoupper<CT>(t, loc); } }; template<typename CT> struct SSToLower : public std::binary_function<CT, std::locale, CT> { inline CT operator()(const CT& t, const std::locale& loc) const { return sstolower<CT>(t, loc); } }; #endif // This struct is used for TrimRight() and TrimLeft() function implementations. //template<typename CT> //struct NotSpace : public std::unary_function<CT, bool> //{ // const std::locale& loc; // inline NotSpace(const std::locale& locArg) : loc(locArg) {} // inline bool operator() (CT t) { return !std::isspace(t, loc); } //}; template<typename CT> struct NotSpace : public std::unary_function<CT, bool> { // DINKUMWARE BUG: // Note -- using std::isspace in a COM DLL gives us access violations // because it causes the dynamic addition of a function to be called // when the library shuts down. Unfortunately the list is maintained // in DLL memory but the function is in static memory. So the COM DLL // goes away along with the function that was supposed to be called, // and then later when the DLL CRT shuts down it unloads the list and // tries to call the long-gone function. // This is DinkumWare's implementation problem. If you encounter this // problem, you may replace the calls here with good old isspace() and // iswspace() from the CRT unless they specify SS_ANSI #ifdef SS_NO_LOCALE bool operator() (CT t) const { return !ssisspace(t); } #else const std::locale loc; NotSpace(const std::locale& locArg=std::locale()) : loc(locArg) {} bool operator() (CT t) const { return !std::isspace(t, loc); } #endif }; // Now we can define the template (finally!) // ============================================================================= // TEMPLATE: CStdStr // template<typename CT> class CStdStr : public std::basic_string<CT> // // REMARKS: // This template derives from basic_string<CT> and adds some MFC CString- // like functionality // // Basically, this is my attempt to make Standard C++ library strings as // easy to use as the MFC CString class. // // Note that although this is a template, it makes the assumption that the // template argument (CT, the character type) is either char or wchar_t. // ============================================================================= //#define CStdStr _SS // avoid compiler warning 4786 // template<typename ARG> ARG& FmtArg(ARG& arg) { return arg; } // PCSTR FmtArg(const std::string& arg) { return arg.c_str(); } // PCWSTR FmtArg(const std::wstring& arg) { return arg.c_str(); } template<typename ARG> struct FmtArg { explicit FmtArg(const ARG& arg) : a_(arg) {} const ARG& operator()() const { return a_; } const ARG& a_; private: FmtArg& operator=(const FmtArg&) { return *this; } }; template<typename CT> class CStdStr : public std::basic_string<CT> { // Typedefs for shorter names. Using these names also appears to help // us avoid some ambiguities that otherwise arise on some platforms #define MYBASE std::basic_string<CT> // my base class //typedef typename std::basic_string<CT> MYBASE; // my base class typedef CStdStr<CT> MYTYPE; // myself typedef typename MYBASE::const_pointer PCMYSTR; // PCSTR or PCWSTR typedef typename MYBASE::pointer PMYSTR; // PSTR or PWSTR typedef typename MYBASE::iterator MYITER; // my iterator type typedef typename MYBASE::const_iterator MYCITER; // you get the idea... typedef typename MYBASE::reverse_iterator MYRITER; typedef typename MYBASE::size_type MYSIZE; typedef typename MYBASE::value_type MYVAL; typedef typename MYBASE::allocator_type MYALLOC; public: // shorthand conversion from PCTSTR to string resource ID #define SSRES(pctstr) LOWORD(reinterpret_cast<unsigned long>(pctstr)) bool TryLoad(const void* pT) { bool bLoaded = false; #if defined(SS_WIN32) && !defined(SS_ANSI) if ( ( pT != NULL ) && SS_IS_INTRESOURCE(pT) ) { UINT nId = LOWORD(reinterpret_cast<unsigned long>(pT)); if ( !LoadString(nId) ) { TRACE(_T("Can't load string %u\n"), SSRES(pT)); } bLoaded = true; } #endif return bLoaded; } // CStdStr inline constructors CStdStr() { } CStdStr(const MYTYPE& str) : MYBASE(SSREF(str)) { } CStdStr(const std::string& str) { ssasn(*this, SSREF(str)); } CStdStr(const std::wstring& str) { ssasn(*this, SSREF(str)); } CStdStr(PCMYSTR pT, MYSIZE n) : MYBASE(NULL == pT ? MYTYPE().c_str() : pT, n) { } #ifdef SS_UNSIGNED CStdStr(PCUSTR pU) { *this = reinterpret_cast<PCSTR>(pU); } #endif CStdStr(PCSTR pA) { #ifdef SS_ANSI *this = pA; #else if ( !TryLoad(pA) ) *this = pA; #endif } CStdStr(PCWSTR pW) { #ifdef SS_ANSI *this = pW; #else if ( !TryLoad(pW) ) *this = pW; #endif } CStdStr(MYCITER first, MYCITER last) : MYBASE(first, last) { } CStdStr(MYSIZE nSize, MYVAL ch, const MYALLOC& al=MYALLOC()) : MYBASE(nSize, ch, al) { } #ifdef SS_INC_COMDEF CStdStr(const _bstr_t& bstr) { if ( bstr.length() > 0 ) this->append(static_cast<PCMYSTR>(bstr), bstr.length()); } #endif // CStdStr inline assignment operators -- the ssasn function now takes care // of fixing the MSVC assignment bug (see knowledge base article Q172398). MYTYPE& operator=(const MYTYPE& str) { ssasn(*this, str); return *this; } MYTYPE& operator=(const std::string& str) { ssasn(*this, str); return *this; } MYTYPE& operator=(const std::wstring& str) { ssasn(*this, str); return *this; } MYTYPE& operator=(PCSTR pA) { ssasn(*this, pA); return *this; } MYTYPE& operator=(PCWSTR pW) { ssasn(*this, pW); return *this; } #ifdef SS_UNSIGNED MYTYPE& operator=(PCUSTR pU) { ssasn(*this, reinterpret_cast<PCSTR>(pU)); return *this; } #endif MYTYPE& operator=(CT t) { Q172398(*this); this->assign(1, t); return *this; } #ifdef SS_INC_COMDEF MYTYPE& operator=(const _bstr_t& bstr) { if ( bstr.length() > 0 ) { this->assign(static_cast<PCMYSTR>(bstr), bstr.length()); return *this; } else { this->erase(); return *this; } } #endif // Overloads also needed to fix the MSVC assignment bug (KB: Q172398) // *** Thanks to Pete The Plumber for catching this one *** // They also are compiled if you have explicitly turned off refcounting #if ( defined(_MSC_VER) && ( _MSC_VER < 1200 ) ) || defined(SS_NO_REFCOUNT) MYTYPE& assign(const MYTYPE& str) { Q172398(*this); sscpy(GetBuffer(str.size()+1), SSREF(str)); this->ReleaseBuffer(str.size()); return *this; } MYTYPE& assign(const MYTYPE& str, MYSIZE nStart, MYSIZE nChars) { // This overload of basic_string::assign is supposed to assign up to // <nChars> or the NULL terminator, whichever comes first. Since we // are about to call a less forgiving overload (in which <nChars> // must be a valid length), we must adjust the length here to a safe // value. Thanks to Ullrich Pollähne for catching this bug nChars = SSMIN(nChars, str.length() - nStart); MYTYPE strTemp(str.c_str()+nStart, nChars); Q172398(*this); this->assign(strTemp); return *this; } MYTYPE& assign(const MYBASE& str) { ssasn(*this, str); return *this; } MYTYPE& assign(const MYBASE& str, MYSIZE nStart, MYSIZE nChars) { // This overload of basic_string::assign is supposed to assign up to // <nChars> or the NULL terminator, whichever comes first. Since we // are about to call a less forgiving overload (in which <nChars> // must be a valid length), we must adjust the length here to a safe // value. Thanks to Ullrich Pollähne for catching this bug nChars = SSMIN(nChars, str.length() - nStart); // Watch out for assignment to self if ( this == &str ) { MYTYPE strTemp(str.c_str() + nStart, nChars); static_cast<MYBASE*>(this)->assign(strTemp); } else { Q172398(*this); static_cast<MYBASE*>(this)->assign(str.c_str()+nStart, nChars); } return *this; } MYTYPE& assign(const CT* pC, MYSIZE nChars) { // Q172398 only fix -- erase before assigning, but not if we're // assigning from our own buffer #if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) if ( !this->empty() && ( pC < this->data() || pC > this->data() + this->capacity() ) ) { this->erase(); } #endif Q172398(*this); static_cast<MYBASE*>(this)->assign(pC, nChars); return *this; } MYTYPE& assign(MYSIZE nChars, MYVAL val) { Q172398(*this); static_cast<MYBASE*>(this)->assign(nChars, val); return *this; } MYTYPE& assign(const CT* pT) { return this->assign(pT, MYBASE::traits_type::length(pT)); } MYTYPE& assign(MYCITER iterFirst, MYCITER iterLast) { #if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) // Q172398 fix. don't call erase() if we're assigning from ourself if ( iterFirst < this->begin() || iterFirst > this->begin() + this->size() ) { this->erase() } #endif this->replace(this->begin(), this->end(), iterFirst, iterLast); return *this; } #endif // ------------------------------------------------------------------------- // CStdStr inline concatenation. // ------------------------------------------------------------------------- MYTYPE& operator+=(const MYTYPE& str) { ssadd(*this, str); return *this; } MYTYPE& operator+=(const std::string& str) { ssadd(*this, str); return *this; } MYTYPE& operator+=(const std::wstring& str) { ssadd(*this, str); return *this; } MYTYPE& operator+=(PCSTR pA) { ssadd(*this, pA); return *this; } MYTYPE& operator+=(PCWSTR pW) { ssadd(*this, pW); return *this; } MYTYPE& operator+=(CT t) { this->append(1, t); return *this; } #ifdef SS_INC_COMDEF // if we have _bstr_t, define a += for it too. MYTYPE& operator+=(const _bstr_t& bstr) { return this->operator+=(static_cast<PCMYSTR>(bstr)); } #endif // ------------------------------------------------------------------------- // Case changing functions // ------------------------------------------------------------------------- MYTYPE& ToUpper(const std::locale& loc=std::locale()) { // Note -- if there are any MBCS character sets in which the lowercase // form a character takes up a different number of bytes than the // uppercase form, this would probably not work... std::transform(this->begin(), this->end(), this->begin(), #ifdef SS_NO_LOCALE SSToUpper<CT>()); #else std::bind2nd(SSToUpper<CT>(), loc)); #endif // ...but if it were, this would probably work better. Also, this way // seems to be a bit faster when anything other then the "C" locale is // used... // if ( !empty() ) // { // ssupr(this->GetBuf(), this->size(), loc); // this->RelBuf(); // } return *this; } MYTYPE& ToLower(const std::locale& loc=std::locale()) { // Note -- if there are any MBCS character sets in which the lowercase // form a character takes up a different number of bytes than the // uppercase form, this would probably not work... std::transform(this->begin(), this->end(), this->begin(), #ifdef SS_NO_LOCALE SSToLower<CT>()); #else std::bind2nd(SSToLower<CT>(), loc)); #endif // ...but if it were, this would probably work better. Also, this way // seems to be a bit faster when anything other then the "C" locale is // used... // if ( !empty() ) // { // sslwr(this->GetBuf(), this->size(), loc); // this->RelBuf(); // } return *this; } MYTYPE& Normalize() { return Trim().ToLower(); } // ------------------------------------------------------------------------- // CStdStr -- Direct access to character buffer. In the MS' implementation, // the at() function that we use here also calls _Freeze() providing us some // protection from multithreading problems associated with ref-counting. // In VC 7 and later, of course, the ref-counting stuff is gone. // ------------------------------------------------------------------------- CT* GetBuf(int nMinLen=-1) { if ( static_cast<int>(this->size()) < nMinLen ) this->resize(static_cast<MYSIZE>(nMinLen)); return this->empty() ? const_cast<CT*>(this->data()) : &(this->at(0)); } CT* SetBuf(int nLen) { nLen = ( nLen > 0 ? nLen : 0 ); if ( this->capacity() < 1 && nLen == 0 ) this->resize(1); this->resize(static_cast<MYSIZE>(nLen)); return const_cast<CT*>(this->data()); } void RelBuf(int nNewLen=-1) { this->resize(static_cast<MYSIZE>(nNewLen > -1 ? nNewLen : sslen(this->c_str()))); } void BufferRel() { RelBuf(); } // backwards compatability CT* Buffer() { return GetBuf(); } // backwards compatability CT* BufferSet(int nLen) { return SetBuf(nLen);}// backwards compatability bool Equals(const CT* pT, bool bUseCase=false) const { return 0 == (bUseCase ? this->compare(pT) : ssicmp(this->c_str(), pT)); } // ------------------------------------------------------------------------- // FUNCTION: CStdStr::Load // REMARKS: // Loads string from resource specified by nID // // PARAMETERS: // nID - resource Identifier. Purely a Win32 thing in this case // // RETURN VALUE: // true if successful, false otherwise // ------------------------------------------------------------------------- #ifndef SS_ANSI bool Load(UINT nId, HMODULE hModule=NULL) { bool bLoaded = false; // set to true of we succeed. #ifdef _MFC_VER // When in Rome (or MFC land)... // If they gave a resource handle, use it. Note - this is archaic // and not really what I would recommend. But then again, in MFC // land, you ought to be using CString for resources anyway since // it walks the resource chain for you. HMODULE hModuleOld = NULL; if ( NULL != hModule ) { hModuleOld = AfxGetResourceHandle(); AfxSetResourceHandle(hModule); } // ...load the string CString strRes; bLoaded = FALSE != strRes.LoadString(nId); // ...and if we set the resource handle, restore it. if ( NULL != hModuleOld ) AfxSetResourceHandle(hModule); if ( bLoaded ) *this = strRes; #else // otherwise make our own hackneyed version of CString's Load // Get the resource name and module handle if ( NULL == hModule ) hModule = GetResourceHandle(); PCTSTR szName = MAKEINTRESOURCE((nId>>4)+1); // lifted DWORD dwSize = 0; // No sense continuing if we can't find the resource HRSRC hrsrc = ::FindResource(hModule, szName, RT_STRING); if ( NULL == hrsrc ) { TRACE(_T("Cannot find resource %d: 0x%X"), nId, ::GetLastError()); } else if ( 0 == (dwSize = ::SizeofResource(hModule, hrsrc) / sizeof(CT))) { TRACE(_T("Cant get size of resource %d 0x%X\n"),nId,GetLastError()); } else { bLoaded = 0 != ssload(hModule, nId, GetBuf(dwSize), dwSize); ReleaseBuffer(); } #endif // #ifdef _MFC_VER if ( !bLoaded ) TRACE(_T("String not loaded 0x%X\n"), ::GetLastError()); return bLoaded; } #endif // #ifdef SS_ANSI // ------------------------------------------------------------------------- // FUNCTION: CStdStr::Format // void _cdecl Formst(CStdStringA& PCSTR szFormat, ...) // void _cdecl Format(PCSTR szFormat); // // DESCRIPTION: // This function does sprintf/wsprintf style formatting on CStdStringA // objects. It looks a lot like MFC's CString::Format. Some people // might even call this identical. Fortunately, these people are now // dead... heh heh. // // PARAMETERS: // nId - ID of string resource holding the format string // szFormat - a PCSTR holding the format specifiers // argList - a va_list holding the arguments for the format specifiers. // // RETURN VALUE: None. // ------------------------------------------------------------------------- // formatting (using wsprintf style formatting) // If they want a Format() function that safely handles string objects // without casting #ifdef SS_SAFE_FORMAT // Question: Joe, you wacky coder you, why do you have so many overloads // of the Format() function // Answer: One reason only - CString compatability. In short, by making // the Format() function a template this way, I can do strong typing // and allow people to pass CStdString arguments as fillers for // "%s" format specifiers without crashing their program! The downside // is that I need to overload on the number of arguments. If you are // passing more arguments than I have listed below in any of my // overloads, just add another one. // // Yes, yes, this is really ugly. In essence what I am doing here is // protecting people from a bad (and incorrect) programming practice // that they should not be doing anyway. I am protecting them from // themselves. Why am I doing this? Well, if you had any idea the // number of times I've been emailed by people about this // "incompatability" in my code, you wouldn't ask. void Fmt(const CT* szFmt, ...) { va_list argList; va_start(argList, szFmt); FormatV(szFmt, argList); va_end(argList); } #ifndef SS_ANSI void Format(UINT nId) { MYTYPE strFmt; if ( strFmt.Load(nId) ) this->swap(strFmt); } template<class A1> void Format(UINT nId, const A1& v) { MYTYPE strFmt; if ( strFmt.Load(nId) ) Fmt(strFmt, FmtArg<A1>(v)()); } template<class A1, class A2> void Format(UINT nId, const A1& v1, const A2& v2) { MYTYPE strFmt; if ( strFmt.Load(nId) ) Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)()); } template<class A1, class A2, class A3> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)()); } } template<class A1, class A2, class A3, class A4> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)()); } } template<class A1, class A2, class A3, class A4, class A5> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(), FmtArg<A6>(v6)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(), FmtArg<A13>(v13)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14, class A15> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14, const A15& v15) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(), FmtArg<A15>(v15)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14, class A15, class A16> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14, const A15& v15, const A16& v16) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(), FmtArg<A15>(v15)(), FmtArg<A16>(v16)()); } } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14, class A15, class A16, class A17> void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14, const A15& v15, const A16& v16, const A17& v17) { MYTYPE strFmt; if ( strFmt.Load(nId) ) { Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(), FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)()); } } #endif // #ifndef SS_ANSI // ...now the other overload of Format: the one that takes a string literal void Format(const CT* szFmt) { *this = szFmt; } template<class A1> void Format(const CT* szFmt, const A1& v) { Fmt(szFmt, FmtArg<A1>(v)()); } template<class A1, class A2> void Format(const CT* szFmt, const A1& v1, const A2& v2) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)()); } template<class A1, class A2, class A3> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)()); } template<class A1, class A2, class A3, class A4> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)()); } template<class A1, class A2, class A3, class A4, class A5> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)()); } template<class A1, class A2, class A3, class A4, class A5, class A6> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(), FmtArg<A13>(v13)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14, class A15> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14, const A15& v15) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(), FmtArg<A15>(v15)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14, class A15, class A16> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14, const A15& v15, const A16& v16) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(), FmtArg<A15>(v15)(), FmtArg<A16>(v16)()); } template<class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9, class A10, class A11, class A12, class A13, class A14, class A15, class A16, class A17> void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3, const A4& v4, const A5& v5, const A6& v6, const A7& v7, const A8& v8, const A9& v9, const A10& v10, const A11& v11, const A12& v12, const A13& v13, const A14& v14, const A15& v15, const A16& v16, const A17& v17) { Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(), FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(), FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(), FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(), FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(), FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)()); } #else // #ifdef SS_SAFE_FORMAT #ifndef SS_ANSI void Format(UINT nId, ...) { va_list argList; va_start(argList, nId); MYTYPE strFmt; if ( strFmt.Load(nId) ) FormatV(strFmt, argList); va_end(argList); } #endif // #ifdef SS_ANSI void Format(const CT* szFmt, ...) { va_list argList; va_start(argList, szFmt); FormatV(szFmt, argList); va_end(argList); } #endif // #ifdef SS_SAFE_FORMAT void AppendFormat(const CT* szFmt, ...) { va_list argList; va_start(argList, szFmt); AppendFormatV(szFmt, argList); va_end(argList); } #define MAX_FMT_TRIES 5 // #of times we try #define FMT_BLOCK_SIZE 2048 // # of bytes to increment per try #define BUFSIZE_1ST 256 #define BUFSIZE_2ND 512 #define STD_BUF_SIZE 1024 // an efficient way to add formatted characters to the string. You may only // add up to STD_BUF_SIZE characters at a time, though void AppendFormatV(const CT* szFmt, va_list argList) { CT szBuf[STD_BUF_SIZE]; int nLen = ssvsprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList); if ( 0 < nLen ) this->append(szBuf, nLen); } // ------------------------------------------------------------------------- // FUNCTION: FormatV // void FormatV(PCSTR szFormat, va_list, argList); // // DESCRIPTION: // This function formats the string with sprintf style format-specs. // It makes a general guess at required buffer size and then tries // successively larger buffers until it finds one big enough or a // threshold (MAX_FMT_TRIES) is exceeded. // // PARAMETERS: // szFormat - a PCSTR holding the format of the output // argList - a Microsoft specific va_list for variable argument lists // // RETURN VALUE: // ------------------------------------------------------------------------- void FormatV(const CT* szFormat, va_list argList) { #ifdef SS_ANSI MYTYPE str; int nLen = sslen(szFormat) + STD_BUF_SIZE; ssvsprintf(str.GetBuffer(nLen), nLen-1, szFormat, argList); str.ReleaseBuffer(); *this = str; #else CT* pBuf = NULL; int nChars = 1; int nUsed = 0; size_type nActual = 0; int nTry = 0; do { // Grow more than linearly (e.g. 512, 1536, 3072, etc) nChars += ((nTry+1) * FMT_BLOCK_SIZE); pBuf = reinterpret_cast<CT*>(_alloca(sizeof(CT)*nChars)); nUsed = ssvsprintf(pBuf, nChars-1, szFormat, argList); // Ensure proper NULL termination. nActual = nUsed == -1 ? nChars-1 : SSMIN(nUsed, nChars-1); pBuf[nActual]= '\0'; } while ( nUsed < 0 && nTry++ < MAX_FMT_TRIES ); // assign whatever we managed to format this->assign(pBuf, nActual); #endif } // ------------------------------------------------------------------------- // CString Facade Functions: // // The following methods are intended to allow you to use this class as a // near drop-in replacement for CString. // ------------------------------------------------------------------------- #ifdef SS_WIN32 BSTR AllocSysString() const { ostring os; ssasn(os, *this); return ::SysAllocString(os.c_str()); } #endif #ifndef SS_NO_LOCALE int Collate(PCMYSTR szThat) const { return sscoll(this->c_str(), this->length(), szThat, sslen(szThat)); } int CollateNoCase(PCMYSTR szThat) const { return ssicoll(this->c_str(), this->length(), szThat, sslen(szThat)); } #endif int Compare(PCMYSTR szThat) const { return this->compare(szThat); } int CompareNoCase(PCMYSTR szThat) const { return ssicmp(this->c_str(), szThat); } int Delete(int nIdx, int nCount=1) { if ( nIdx < 0 ) nIdx = 0; if ( nIdx < this->GetLength() ) this->erase(static_cast<MYSIZE>(nIdx), static_cast<MYSIZE>(nCount)); return GetLength(); } void Empty() { this->erase(); } int Find(CT ch) const { MYSIZE nIdx = this->find_first_of(ch); return static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx); } int Find(PCMYSTR szSub) const { MYSIZE nIdx = this->find(szSub); return static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx); } int Find(CT ch, int nStart) const { // CString::Find docs say add 1 to nStart when it's not zero // CString::Find code doesn't do that however. We'll stick // with what the code does MYSIZE nIdx = this->find_first_of(ch, static_cast<MYSIZE>(nStart)); return static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx); } int Find(PCMYSTR szSub, int nStart) const { // CString::Find docs say add 1 to nStart when it's not zero // CString::Find code doesn't do that however. We'll stick // with what the code does MYSIZE nIdx = this->find(szSub, static_cast<MYSIZE>(nStart)); return static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx); } int FindOneOf(PCMYSTR szCharSet) const { MYSIZE nIdx = this->find_first_of(szCharSet); return static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx); } #ifndef SS_ANSI void FormatMessage(PCMYSTR szFormat, ...) throw(std::exception) { va_list argList; va_start(argList, szFormat); PMYSTR szTemp; if ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER, szFormat, 0, 0, reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 || szTemp == 0 ) { throw std::runtime_error("out of memory"); } *this = szTemp; LocalFree(szTemp); va_end(argList); } void FormatMessage(UINT nFormatId, ...) throw(std::exception) { MYTYPE sFormat; VERIFY(sFormat.LoadString(nFormatId)); va_list argList; va_start(argList, nFormatId); PMYSTR szTemp; if ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER, sFormat, 0, 0, reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 || szTemp == 0) { throw std::runtime_error("out of memory"); } *this = szTemp; LocalFree(szTemp); va_end(argList); } #endif // GetAllocLength -- an MSVC7 function but it costs us nothing to add it. int GetAllocLength() { return static_cast<int>(this->capacity()); } // ------------------------------------------------------------------------- // GetXXXX -- Direct access to character buffer // ------------------------------------------------------------------------- CT GetAt(int nIdx) const { return this->at(static_cast<MYSIZE>(nIdx)); } CT* GetBuffer(int nMinLen=-1) { return GetBuf(nMinLen); } CT* GetBufferSetLength(int nLen) { return BufferSet(nLen); } // GetLength() -- MFC docs say this is the # of BYTES but // in truth it is the number of CHARACTERs (chars or wchar_ts) int GetLength() const { return static_cast<int>(this->length()); } // GetString function added in Visual Studio 2008, if I recall correctly. PCMYSTR GetString() const { return this->c_str(); } int Insert(int nIdx, CT ch) { if ( static_cast<MYSIZE>(nIdx) > this->size()-1 ) this->append(1, ch); else this->insert(static_cast<MYSIZE>(nIdx), 1, ch); return GetLength(); } int Insert(int nIdx, PCMYSTR sz) { if ( static_cast<MYSIZE>(nIdx) >= this->size() ) this->append(sz, static_cast<MYSIZE>(sslen(sz))); else this->insert(static_cast<MYSIZE>(nIdx), sz); return GetLength(); } bool IsEmpty() const { return this->empty(); } MYTYPE Left(int nCount) const { // Range check the count. nCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size()))); return this->substr(0, static_cast<MYSIZE>(nCount)); } #ifndef SS_ANSI bool LoadString(UINT nId) { return this->Load(nId); } #endif void MakeLower() { ToLower(); } void MakeReverse() { std::reverse(this->begin(), this->end()); } void MakeUpper() { ToUpper(); } MYTYPE Mid(int nFirst) const { return Mid(nFirst, this->GetLength()-nFirst); } MYTYPE Mid(int nFirst, int nCount) const { // CString does range checking here. Since we're trying to emulate it, // we must check too. if ( nFirst < 0 ) nFirst = 0; if ( nCount < 0 ) nCount = 0; int nSize = static_cast<int>(this->size()); if ( nFirst + nCount > nSize ) nCount = nSize - nFirst; if ( nFirst > nSize ) return MYTYPE(); ASSERT(nFirst >= 0); ASSERT(nFirst + nCount <= nSize); return this->substr(static_cast<MYSIZE>(nFirst), static_cast<MYSIZE>(nCount)); } void ReleaseBuffer(int nNewLen=-1) { RelBuf(nNewLen); } int Remove(CT ch) { MYSIZE nIdx = 0; int nRemoved = 0; while ( (nIdx=this->find_first_of(ch)) != MYBASE::npos ) { this->erase(nIdx, 1); nRemoved++; } return nRemoved; } int Replace(CT chOld, CT chNew) { int nReplaced = 0; for ( MYITER iter=this->begin(); iter != this->end(); ++iter ) { if ( *iter == chOld ) { *iter = chNew; nReplaced++; } } return nReplaced; } int Replace(PCMYSTR szOld, PCMYSTR szNew) { int nReplaced = 0; MYSIZE nIdx = 0; MYSIZE nOldLen = sslen(szOld); if ( 0 != nOldLen ) { // If the replacement string is longer than the one it replaces, this // string is going to have to grow in size, Figure out how much // and grow it all the way now, rather than incrementally MYSIZE nNewLen = sslen(szNew); if ( nNewLen > nOldLen ) { int nFound = 0; while ( nIdx < this->length() && (nIdx=this->find(szOld, nIdx)) != MYBASE::npos ) { nFound++; nIdx += nOldLen; } this->reserve(this->size() + nFound * (nNewLen - nOldLen)); } static const CT ch = CT(0); PCMYSTR szRealNew = szNew == 0 ? &ch : szNew; nIdx = 0; while ( nIdx < this->length() && (nIdx=this->find(szOld, nIdx)) != MYBASE::npos ) { this->replace(this->begin()+nIdx, this->begin()+nIdx+nOldLen, szRealNew); nReplaced++; nIdx += nNewLen; } } return nReplaced; } int ReverseFind(CT ch) const { MYSIZE nIdx = this->find_last_of(ch); return static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx); } // ReverseFind overload that's not in CString but might be useful int ReverseFind(PCMYSTR szFind, MYSIZE pos=MYBASE::npos) const { MYSIZE nIdx = this->rfind(0 == szFind ? MYTYPE() : szFind, pos); return static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx); } MYTYPE Right(int nCount) const { // Range check the count. nCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size()))); return this->substr(this->size()-static_cast<MYSIZE>(nCount)); } void SetAt(int nIndex, CT ch) { ASSERT(this->size() > static_cast<MYSIZE>(nIndex)); this->at(static_cast<MYSIZE>(nIndex)) = ch; } #ifndef SS_ANSI BSTR SetSysString(BSTR* pbstr) const { ostring os; ssasn(os, *this); if ( !::SysReAllocStringLen(pbstr, os.c_str(), os.length()) ) throw std::runtime_error("out of memory"); ASSERT(*pbstr != 0); return *pbstr; } #endif MYTYPE SpanExcluding(PCMYSTR szCharSet) const { MYSIZE pos = this->find_first_of(szCharSet); return pos == MYBASE::npos ? *this : Left(pos); } MYTYPE SpanIncluding(PCMYSTR szCharSet) const { MYSIZE pos = this->find_first_not_of(szCharSet); return pos == MYBASE::npos ? *this : Left(pos); } #if defined SS_WIN32 && !defined(UNICODE) && !defined(SS_ANSI) // CString's OemToAnsi and AnsiToOem functions are available only in // Unicode builds. However since we're a template we also need a // runtime check of CT and a reinterpret_cast to account for the fact // that CStdStringW gets instantiated even in non-Unicode builds. void AnsiToOem() { if ( sizeof(CT) == sizeof(char) && !empty() ) { ::CharToOem(reinterpret_cast<PCSTR>(this->c_str()), reinterpret_cast<PSTR>(GetBuf())); } else { ASSERT(false); } } void OemToAnsi() { if ( sizeof(CT) == sizeof(char) && !empty() ) { ::OemToChar(reinterpret_cast<PCSTR>(this->c_str()), reinterpret_cast<PSTR>(GetBuf())); } else { ASSERT(false); } } #endif // ------------------------------------------------------------------------- // Trim and its variants // ------------------------------------------------------------------------- MYTYPE& Trim() { return TrimLeft().TrimRight(); } MYTYPE& TrimLeft() { this->erase(this->begin(), std::find_if(this->begin(), this->end(), NotSpace<CT>())); return *this; } MYTYPE& TrimLeft(CT tTrim) { this->erase(0, this->find_first_not_of(tTrim)); return *this; } MYTYPE& TrimLeft(PCMYSTR szTrimChars) { this->erase(0, this->find_first_not_of(szTrimChars)); return *this; } MYTYPE& TrimRight() { // NOTE: When comparing reverse_iterators here (MYRITER), I avoid using // operator!=. This is because namespace rel_ops also has a template // operator!= which conflicts with the global operator!= already defined // for reverse_iterator in the header <utility>. // Thanks to John James for alerting me to this. MYRITER it = std::find_if(this->rbegin(), this->rend(), NotSpace<CT>()); if ( !(this->rend() == it) ) this->erase(this->rend() - it); this->erase(!(it == this->rend()) ? this->find_last_of(*it) + 1 : 0); return *this; } MYTYPE& TrimRight(CT tTrim) { MYSIZE nIdx = this->find_last_not_of(tTrim); this->erase(MYBASE::npos == nIdx ? 0 : ++nIdx); return *this; } MYTYPE& TrimRight(PCMYSTR szTrimChars) { MYSIZE nIdx = this->find_last_not_of(szTrimChars); this->erase(MYBASE::npos == nIdx ? 0 : ++nIdx); return *this; } void FreeExtra() { MYTYPE mt; this->swap(mt); if ( !mt.empty() ) this->assign(mt.c_str(), mt.size()); } // I have intentionally not implemented the following CString // functions. You cannot make them work without taking advantage // of implementation specific behavior. However if you absolutely // MUST have them, uncomment out these lines for "sort-of-like" // their behavior. You're on your own. // CT* LockBuffer() { return GetBuf(); }// won't really lock // void UnlockBuffer(); { } // why have UnlockBuffer w/o LockBuffer? // Array-indexing operators. Required because we defined an implicit cast // to operator const CT* (Thanks to Julian Selman for pointing this out) CT& operator[](int nIdx) { return static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx)); } const CT& operator[](int nIdx) const { return static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx)); } CT& operator[](unsigned int nIdx) { return static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx)); } const CT& operator[](unsigned int nIdx) const { return static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx)); } #ifndef SS_NO_IMPLICIT_CAST operator const CT*() const { return this->c_str(); } #endif // IStream related functions. Useful in IPersistStream implementations #ifdef SS_INC_COMDEF // struct SSSHDR - useful for non Std C++ persistence schemes. typedef struct SSSHDR { BYTE byCtrl; ULONG nChars; } SSSHDR; // as in "Standard String Stream Header" #define SSSO_UNICODE 0x01 // the string is a wide string #define SSSO_COMPRESS 0x02 // the string is compressed // ------------------------------------------------------------------------- // FUNCTION: StreamSize // REMARKS: // Returns how many bytes it will take to StreamSave() this CStdString // object to an IStream. // ------------------------------------------------------------------------- ULONG StreamSize() const { // Control header plus string ASSERT(this->size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR)); return (this->size() * sizeof(CT)) + sizeof(SSSHDR); } // ------------------------------------------------------------------------- // FUNCTION: StreamSave // REMARKS: // Saves this CStdString object to a COM IStream. // ------------------------------------------------------------------------- HRESULT StreamSave(IStream* pStream) const { ASSERT(this->size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR)); HRESULT hr = E_FAIL; ASSERT(pStream != 0); SSSHDR hdr; hdr.byCtrl = sizeof(CT) == 2 ? SSSO_UNICODE : 0; hdr.nChars = this->size(); if ( FAILED(hr=pStream->Write(&hdr, sizeof(SSSHDR), 0)) ) { TRACE(_T("StreamSave: Cannot write control header, ERR=0x%X\n"),hr); } else if ( empty() ) { ; // nothing to write } else if ( FAILED(hr=pStream->Write(this->c_str(), this->size()*sizeof(CT), 0)) ) { TRACE(_T("StreamSave: Cannot write string to stream 0x%X\n"), hr); } return hr; } // ------------------------------------------------------------------------- // FUNCTION: StreamLoad // REMARKS: // This method loads the object from an IStream. // ------------------------------------------------------------------------- HRESULT StreamLoad(IStream* pStream) { ASSERT(pStream != 0); SSSHDR hdr; HRESULT hr = E_FAIL; if ( FAILED(hr=pStream->Read(&hdr, sizeof(SSSHDR), 0)) ) { TRACE(_T("StreamLoad: Cant read control header, ERR=0x%X\n"), hr); } else if ( hdr.nChars > 0 ) { ULONG nRead = 0; PMYSTR pMyBuf = BufferSet(hdr.nChars); // If our character size matches the character size of the string // we're trying to read, then we can read it directly into our // buffer. Otherwise, we have to read into an intermediate buffer // and convert. if ( (hdr.byCtrl & SSSO_UNICODE) != 0 ) { ULONG nBytes = hdr.nChars * sizeof(wchar_t); if ( sizeof(CT) == sizeof(wchar_t) ) { if ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) ) TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); } else { PWSTR pBufW = reinterpret_cast<PWSTR>(_alloca((nBytes)+1)); if ( FAILED(hr=pStream->Read(pBufW, nBytes, &nRead)) ) TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); else sscpy(pMyBuf, pBufW, hdr.nChars); } } else { ULONG nBytes = hdr.nChars * sizeof(char); if ( sizeof(CT) == sizeof(char) ) { if ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) ) TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); } else { PSTR pBufA = reinterpret_cast<PSTR>(_alloca(nBytes)); if ( FAILED(hr=pStream->Read(pBufA, hdr.nChars, &nRead)) ) TRACE(_T("StreamLoad: Cannot read string: 0x%X\n"), hr); else sscpy(pMyBuf, pBufA, hdr.nChars); } } } else { this->erase(); } return hr; } #endif // #ifdef SS_INC_COMDEF #ifndef SS_ANSI // SetResourceHandle/GetResourceHandle. In MFC builds, these map directly // to AfxSetResourceHandle and AfxGetResourceHandle. In non-MFC builds they // point to a single static HINST so that those who call the member // functions that take resource IDs can provide an alternate HINST of a DLL // to search. This is not exactly the list of HMODULES that MFC provides // but it's better than nothing. #ifdef _MFC_VER static void SetResourceHandle(HMODULE hNew) { AfxSetResourceHandle(hNew); } static HMODULE GetResourceHandle() { return AfxGetResourceHandle(); } #else static void SetResourceHandle(HMODULE hNew) { SSResourceHandle() = hNew; } static HMODULE GetResourceHandle() { return SSResourceHandle(); } #endif #endif }; // ----------------------------------------------------------------------------- // MSVC USERS: HOW TO EXPORT CSTDSTRING FROM A DLL // // If you are using MS Visual C++ and you want to export CStdStringA and // CStdStringW from a DLL, then all you need to // // 1. make sure that all components link to the same DLL version // of the CRT (not the static one). // 2. Uncomment the 3 lines of code below // 3. #define 2 macros per the instructions in MS KnowledgeBase // article Q168958. The macros are: // // MACRO DEFINTION WHEN EXPORTING DEFINITION WHEN IMPORTING // ----- ------------------------ ------------------------- // SSDLLEXP (nothing, just #define it) extern // SSDLLSPEC __declspec(dllexport) __declspec(dllimport) // // Note that these macros must be available to ALL clients who want to // link to the DLL and use the class. If they // // A word of advice: Don't bother. // // Really, it is not necessary to export CStdString functions from a DLL. I // never do. In my projects, I do generally link to the DLL version of the // Standard C++ Library, but I do NOT attempt to export CStdString functions. // I simply include the header where it is needed and allow for the code // redundancy. // // That redundancy is a lot less than you think. This class does most of its // work via the Standard C++ Library, particularly the base_class basic_string<> // member functions. Most of the functions here are small enough to be inlined // anyway. Besides, you'll find that in actual practice you use less than 1/2 // of the code here, even in big projects and different modules will use as // little as 10% of it. That means a lot less functions actually get linked // your binaries. If you export this code from a DLL, it ALL gets linked in. // // I've compared the size of the binaries from exporting vs NOT exporting. Take // my word for it -- exporting this code is not worth the hassle. // // ----------------------------------------------------------------------------- //#pragma warning(disable:4231) // non-standard extension ("extern template") // SSDLLEXP template class SSDLLSPEC CStdStr<char>; // SSDLLEXP template class SSDLLSPEC CStdStr<wchar_t>; // ============================================================================= // END OF CStdStr INLINE FUNCTION DEFINITIONS // ============================================================================= // Now typedef our class names based upon this humongous template typedef CStdStr<char> CStdStringA; // a better std::string typedef CStdStr<wchar_t> CStdStringW; // a better std::wstring typedef CStdStr<OLECHAR> CStdStringO; // almost always CStdStringW // ----------------------------------------------------------------------------- // CStdStr addition functions defined as inline // ----------------------------------------------------------------------------- inline CStdStringA operator+(const CStdStringA& s1, const CStdStringA& s2) { CStdStringA sRet(SSREF(s1)); sRet.append(s2); return sRet; } inline CStdStringA operator+(const CStdStringA& s1, CStdStringA::value_type t) { CStdStringA sRet(SSREF(s1)); sRet.append(1, t); return sRet; } inline CStdStringA operator+(const CStdStringA& s1, PCSTR pA) { CStdStringA sRet(SSREF(s1)); sRet.append(pA); return sRet; } inline CStdStringA operator+(PCSTR pA, const CStdStringA& sA) { CStdStringA sRet; CStdStringA::size_type nObjSize = sA.size(); CStdStringA::size_type nLitSize = static_cast<CStdStringA::size_type>(sslen(pA)); sRet.reserve(nLitSize + nObjSize); sRet.assign(pA); sRet.append(sA); return sRet; } inline CStdStringA operator+(const CStdStringA& s1, const CStdStringW& s2) { return s1 + CStdStringA(s2); } inline CStdStringW operator+(const CStdStringW& s1, const CStdStringW& s2) { CStdStringW sRet(SSREF(s1)); sRet.append(s2); return sRet; } inline CStdStringA operator+(const CStdStringA& s1, PCWSTR pW) { return s1 + CStdStringA(pW); } #ifdef UNICODE inline CStdStringW operator+(PCWSTR pW, const CStdStringA& sA) { return CStdStringW(pW) + CStdStringW(SSREF(sA)); } inline CStdStringW operator+(PCSTR pA, const CStdStringW& sW) { return CStdStringW(pA) + sW; } #else inline CStdStringA operator+(PCWSTR pW, const CStdStringA& sA) { return CStdStringA(pW) + sA; } inline CStdStringA operator+(PCSTR pA, const CStdStringW& sW) { return pA + CStdStringA(sW); } #endif // ...Now the wide string versions. inline CStdStringW operator+(const CStdStringW& s1, CStdStringW::value_type t) { CStdStringW sRet(SSREF(s1)); sRet.append(1, t); return sRet; } inline CStdStringW operator+(const CStdStringW& s1, PCWSTR pW) { CStdStringW sRet(SSREF(s1)); sRet.append(pW); return sRet; } inline CStdStringW operator+(PCWSTR pW, const CStdStringW& sW) { CStdStringW sRet; CStdStringW::size_type nObjSize = sW.size(); CStdStringA::size_type nLitSize = static_cast<CStdStringW::size_type>(sslen(pW)); sRet.reserve(nLitSize + nObjSize); sRet.assign(pW); sRet.append(sW); return sRet; } inline CStdStringW operator+(const CStdStringW& s1, const CStdStringA& s2) { return s1 + CStdStringW(s2); } inline CStdStringW operator+(const CStdStringW& s1, PCSTR pA) { return s1 + CStdStringW(pA); } // New-style format function is a template #ifdef SS_SAFE_FORMAT template<> struct FmtArg<CStdStringA> { explicit FmtArg(const CStdStringA& arg) : a_(arg) {} PCSTR operator()() const { return a_.c_str(); } const CStdStringA& a_; private: FmtArg<CStdStringA>& operator=(const FmtArg<CStdStringA>&) { return *this; } }; template<> struct FmtArg<CStdStringW> { explicit FmtArg(const CStdStringW& arg) : a_(arg) {} PCWSTR operator()() const { return a_.c_str(); } const CStdStringW& a_; private: FmtArg<CStdStringW>& operator=(const FmtArg<CStdStringW>&) { return *this; } }; template<> struct FmtArg<std::string> { explicit FmtArg(const std::string& arg) : a_(arg) {} PCSTR operator()() const { return a_.c_str(); } const std::string& a_; private: FmtArg<std::string>& operator=(const FmtArg<std::string>&) { return *this; } }; template<> struct FmtArg<std::wstring> { explicit FmtArg(const std::wstring& arg) : a_(arg) {} PCWSTR operator()() const { return a_.c_str(); } const std::wstring& a_; private: FmtArg<std::wstring>& operator=(const FmtArg<std::wstring>&) {return *this;} }; #endif // #ifdef SS_SAFEFORMAT #ifndef SS_ANSI // SSResourceHandle: our MFC-like resource handle inline HMODULE& SSResourceHandle() { static HMODULE hModuleSS = GetModuleHandle(0); return hModuleSS; } #endif // In MFC builds, define some global serialization operators // Special operators that allow us to serialize CStdStrings to CArchives. // Note that we use an intermediate CString object in order to ensure that // we use the exact same format. #ifdef _MFC_VER inline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringA& strA) { CString strTemp(strA); return ar << strTemp; } inline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringW& strW) { CString strTemp(strW); return ar << strTemp; } inline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringA& strA) { CString strTemp; ar >> strTemp; strA = strTemp; return ar; } inline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringW& strW) { CString strTemp; ar >> strTemp; strW = strTemp; return ar; } #endif // #ifdef _MFC_VER -- (i.e. is this MFC?) // ----------------------------------------------------------------------------- // GLOBAL FUNCTION: WUFormat // CStdStringA WUFormat(UINT nId, ...); // CStdStringA WUFormat(PCSTR szFormat, ...); // // REMARKS: // This function allows the caller for format and return a CStdStringA // object with a single line of code. // ----------------------------------------------------------------------------- inline CStdStringA WUFormatA(PCSTR szFormat, ...) { va_list argList; va_start(argList, szFormat); CStdStringA strOut; strOut.FormatV(szFormat, argList); va_end(argList); return strOut; } inline CStdStringW WUFormatW(PCWSTR szwFormat, ...) { va_list argList; va_start(argList, szwFormat); CStdStringW strOut; strOut.FormatV(szwFormat, argList); va_end(argList); return strOut; } #ifdef SS_ANSI #else inline CStdStringA WUFormatA(UINT nId, ...) { va_list argList; va_start(argList, nId); CStdStringA strFmt; CStdStringA strOut; if ( strFmt.Load(nId) ) strOut.FormatV(strFmt, argList); va_end(argList); return strOut; } inline CStdStringW WUFormatW(UINT nId, ...) { va_list argList; va_start(argList, nId); CStdStringW strFmt; CStdStringW strOut; if ( strFmt.Load(nId) ) strOut.FormatV(strFmt, argList); va_end(argList); return strOut; } #endif // #ifdef SS_ANSI #if defined(SS_WIN32) && !defined (SS_ANSI) // ------------------------------------------------------------------------- // FUNCTION: WUSysMessage // CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID); // CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID); // // DESCRIPTION: // This function simplifies the process of obtaining a string equivalent // of a system error code returned from GetLastError(). You simply // supply the value returned by GetLastError() to this function and the // corresponding system string is returned in the form of a CStdStringA. // // PARAMETERS: // dwError - a DWORD value representing the error code to be translated // dwLangId - the language id to use. defaults to english. // // RETURN VALUE: // a CStdStringA equivalent of the error code. Currently, this function // only returns either English of the system default language strings. // ------------------------------------------------------------------------- #define SS_DEFLANGID MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT) inline CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID) { CHAR szBuf[512]; if ( 0 != ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, dwLangId, szBuf, 511, NULL) ) return WUFormatA("%s (0x%X)", szBuf, dwError); else return WUFormatA("Unknown error (0x%X)", dwError); } inline CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID) { WCHAR szBuf[512]; if ( 0 != ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError, dwLangId, szBuf, 511, NULL) ) return WUFormatW(L"%s (0x%X)", szBuf, dwError); else return WUFormatW(L"Unknown error (0x%X)", dwError); } #endif // Define TCHAR based friendly names for some of these functions #ifdef UNICODE //#define CStdString CStdStringW typedef CStdStringW CStdString; #define WUSysMessage WUSysMessageW #define WUFormat WUFormatW #else //#define CStdString CStdStringA typedef CStdStringA CStdString; #define WUSysMessage WUSysMessageA #define WUFormat WUFormatA #endif // ...and some shorter names for the space-efficient #define WUSysMsg WUSysMessage #define WUSysMsgA WUSysMessageA #define WUSysMsgW WUSysMessageW #define WUFmtA WUFormatA #define WUFmtW WUFormatW #define WUFmt WUFormat #define WULastErrMsg() WUSysMessage(::GetLastError()) #define WULastErrMsgA() WUSysMessageA(::GetLastError()) #define WULastErrMsgW() WUSysMessageW(::GetLastError()) // ----------------------------------------------------------------------------- // FUNCTIONAL COMPARATORS: // REMARKS: // These structs are derived from the std::binary_function template. They // give us functional classes (which may be used in Standard C++ Library // collections and algorithms) that perform case-insensitive comparisons of // CStdString objects. This is useful for maps in which the key may be the // proper string but in the wrong case. // ----------------------------------------------------------------------------- #define StdStringLessNoCaseW SSLNCW // avoid VC compiler warning 4786 #define StdStringEqualsNoCaseW SSENCW #define StdStringLessNoCaseA SSLNCA #define StdStringEqualsNoCaseA SSENCA #ifdef UNICODE #define StdStringLessNoCase SSLNCW #define StdStringEqualsNoCase SSENCW #else #define StdStringLessNoCase SSLNCA #define StdStringEqualsNoCase SSENCA #endif struct StdStringLessNoCaseW : std::binary_function<CStdStringW, CStdStringW, bool> { inline bool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const { return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; } }; struct StdStringEqualsNoCaseW : std::binary_function<CStdStringW, CStdStringW, bool> { inline bool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const { return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; } }; struct StdStringLessNoCaseA : std::binary_function<CStdStringA, CStdStringA, bool> { inline bool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const { return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; } }; struct StdStringEqualsNoCaseA : std::binary_function<CStdStringA, CStdStringA, bool> { inline bool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const { return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; } }; // If we had to define our own version of TRACE above, get rid of it now #ifdef TRACE_DEFINED_HERE #undef TRACE #undef TRACE_DEFINED_HERE #endif // These std::swap specializations come courtesy of Mike Crusader. //namespace std //{ // inline void swap(CStdStringA& s1, CStdStringA& s2) throw() // { // s1.swap(s2); // } // template<> // inline void swap(CStdStringW& s1, CStdStringW& s2) throw() // { // s1.swap(s2); // } //} // Turn back on any Borland warnings we turned off. #ifdef __BORLANDC__ #pragma option pop // Turn back on inline function warnings // #pragma warn +inl // Turn back on inline function warnings #endif #endif // #ifndef STDSTRING_H
[ "albertisfu@gmail.com" ]
albertisfu@gmail.com
739f175bcb2e0d0cf6746e851f5ef389512300ea
ce6fc44470dcb5fca78cdd3349a7be70d75f2e3a
/ORAC questions/Art Class/prog_orac.cpp
46ea5a7e9adb41b7a09ac2798053eec217a40639
[]
no_license
cormackikkert/competitive-programming
f3fa287fcb74248ba218ecd763f8f6df31d57424
3a1200b8ff9b6941c422371961a127d7be8f2e00
refs/heads/master
2022-12-17T02:02:40.892608
2020-09-20T11:47:15
2020-09-20T11:47:15
266,775,265
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
cpp
#include <bits/stdc++.h> using namespace std; int H, W, c; vector<vector<bool>> grid (1000, vector<bool> (1000)); vector<vector<bool>> visited (1000, vector<bool> (1000)); vector<int> minRow (1000); vector<int> maxRow (1000); void search(int x, int y) { visited[y][x] = true; ++c; minRow[y] = min(minRow[y], x); maxRow[y] = max(maxRow[y], x); for (auto pv : vector<pair<int, int>> {{-1, 0}, {1, 0}, {0, 1}, {0, -1}}) { int nx = x + pv.first; int ny = y + pv.second; if (0 <= nx && nx < W && 0 <= ny && ny < H && grid[ny][nx] && !visited[ny][nx]) { search(nx, ny); } } } int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); freopen("artin.txt", "r", stdin); freopen("artout.txt", "w", stdout); cin >> H >> W; for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { char c; cin >> c; grid[i][j] = (c == 'X'); visited[i][j] = false; } } int best = 0; for (int i = 0; i < H; ++i) { for (int j = 0; j < W; ++j) { if (visited[i][j] || !grid[i][j]) continue; c = 0; fill(minRow.begin(), minRow.end(), W); fill(maxRow.begin(), maxRow.end(), -1); search(j, i); if (c - 1 <= best) continue; for (int c1 = 0; c1 < H; ++c1) { if (minRow[c1] == W) continue; for (int c2 = 0; c2 < H; ++c2) { if (maxRow[c2] == -1) continue; best = max(best, abs(maxRow[c2] - minRow[c1]) + abs(c2 - c1)); } } } } cout << best; }
[ "u6427001@anu.edu.au" ]
u6427001@anu.edu.au
95bf9eb196cb51b84dfc588d7a38337a75024dfd
ba4594763eb9cb707289144e89962b18519aa555
/Data Structures/test.cpp
3dd85ccb93fcc678b7dd18284e39195e98088b81
[]
no_license
AnthonyG1371/College-Assignments
b03ab39dcccf9a1d67854c3904d40af7a84d46b6
e129b38cf41acee7d9ad46b6db96c4ad6d5a33cd
refs/heads/master
2020-03-12T12:55:25.335190
2018-05-28T16:57:34
2018-05-28T16:57:34
130,629,978
1
0
null
null
null
null
UTF-8
C++
false
false
459
cpp
// overload_date.cpp // compile with: /EHsc #include <iostream> using namespace std; class Date { int mo, da, yr; public: Date(int m, int d, int y) { mo = m; da = d; yr = y; } friend ostream& operator<<(ostream& os, const Date& dt); }; ostream& operator<<(ostream& os, const Date& dt) { os << dt.mo << '/' << dt.da << '/' << dt.yr; return os; } int main() { Date dt(5, 6, 92); cout << dt; system("pause"); }
[ "Anthony.G1371@gmail.com" ]
Anthony.G1371@gmail.com
363243544b4fa66d359fe2a964487f642493226a
cdf7aae463df69fe52d4e9dbdc63bde7f1df9801
/performer-1.0/src/config/winpriority.cpp
650a6eaa0a3abbb5fb8cfc812e0e67d70072dd76
[]
no_license
iq-dot/performer
b2767c18988ecf5f1039ee64275b25bf8a7a1dac
255fe4b881441dae359faecb2a216a7be3aedf6a
refs/heads/master
2020-04-07T02:27:45.845208
2014-03-31T11:14:30
2014-03-31T11:14:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,005
cpp
#include <windows.h> #include "performer/data_collection/configfile.h" bool changePriority(ConfigFile::ProcPriority priority) { BOOL chk; if(priority == ConfigFile::NORMAL){ chk = SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS); } else if(priority == ConfigFile::HIGH){ chk = SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); } else if(priority == ConfigFile::HIGHER){ chk = SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); } else if(priority == ConfigFile::HIGHEST){ chk = SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); } if(chk == 0){ return false; } else{ return true; } } //add factory function in perfromerfactory with extern c //extern "c" treats functions as c functions instead of c++ functions //it uses c linkage isntead of c++ lingage //it prevents name mangling as done by c++ compilers, which ties it to that compiler and version
[ "iq.quit@gmail.com" ]
iq.quit@gmail.com
e5d7464271c77d30b78bd6c20c71e575f1fbd5ab
7096e9c7f583ed5dda3fa3bf4236344c5f739476
/Software/INOs (Not most up to date)/Ex-Use/Old OG/Layers Example/Code-master-a0defba0c61197c4ce4dd460c3810c5a6583d279/Examples/arduino_cmps11_i2c/arduino_cmps11_i2c.ino
6d4b104637b53bf3512b7afe1c74455e8ff51d2b
[ "WTFPL" ]
permissive
TomFraser/FG-B-2016
5fd66fda75ac3ff43132579e5c8b10e2cd4136d6
e86ddbc886c32f80d94d5899c208abe8a7a0bfe5
refs/heads/master
2021-03-27T10:20:59.547840
2018-04-15T10:53:11
2018-04-15T10:53:11
82,669,457
0
0
null
null
null
null
UTF-8
C++
false
false
1,797
ino
/***************************************** * CMPS11 I2C example for Arduino * * By James Henderson, 2014 * *****************************************/ #include <Wire.h> #define CMPS11_ADDRESS 0x60 // Address of CMPS11 shifted right one bit for arduino wire library #define ANGLE_8 1 // Register to read 8bit angle from unsigned char high_byte, low_byte, angle8; char pitch, roll; unsigned int angle16; void setup() { Serial.begin(9600); // Start serial port Wire.begin(); } void loop() { Wire.beginTransmission(CMPS11_ADDRESS); //starts communication with CMPS11 Wire.write(ANGLE_8); //Sends the register we wish to start reading from Wire.endTransmission(); // Request 5 bytes from the CMPS11 // this will give us the 8 bit bearing, // both bytes of the 16 bit bearing, pitch and roll Wire.requestFrom(CMPS11_ADDRESS, 5); while(Wire.available() < 5); // Wait for all bytes to come back angle8 = Wire.read(); // Read back the 5 bytes high_byte = Wire.read(); low_byte = Wire.read(); pitch = Wire.read(); roll = Wire.read(); angle16 = high_byte; // Calculate 16 bit angle angle16 <<= 8; angle16 += low_byte; Serial.print("roll: "); // Display roll data Serial.print(roll, DEC); Serial.print(" pitch: "); // Display pitch data Serial.print(pitch, DEC); Serial.print(" angle full: "); // Display 16 bit angle with decimal place Serial.print(angle16 / 10, DEC); Serial.print("."); Serial.print(angle16 % 10, DEC); Serial.print(" angle 8: "); // Display 8bit angle Serial.println(angle8, DEC); delay(100); // Short delay before next loop }
[ "18135@student.bbc.qld.edu.au" ]
18135@student.bbc.qld.edu.au
a6d25a62e1a946ac498c7fcb5ee629b69b0c3b16
25c0aa423479567d219c51cad3522324e8c90a24
/Subsystems/CompressorSys.cpp
0878783ba703353b1c6dd9db15da73c8a38e49df
[]
no_license
jmglidden/Fluffy
79b38ab9d7b093d31cc3bef1539c9f7cba066469
9c13fce30dad33a80b2ee96b35919e84d4699e78
HEAD
2016-09-05T22:02:51.641915
2014-07-19T16:33:46
2014-07-19T16:33:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
// RobotBuilder Version: 0.0.2 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. #include "CompressorSys.h" #include "../Robotmap.h" #include "../Commands/StartCompressor.h" CompressorSys::CompressorSys() : Subsystem("CompressorSys") { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS comp = RobotMap::compressorSysComp; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS } void CompressorSys::InitDefaultCommand() { // Set the default command for a subsystem here. //SetDefaultCommand(new MySpecialCommand()); // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND SetDefaultCommand(new StartCompressor()); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND } // Put methods for controlling this subsystem // here. Call these from Commands. void CompressorSys::StartComp(){ comp->Start(); } void CompressorSys::StopComp(){ comp->Stop(); }
[ "jmglidden@gmail.com" ]
jmglidden@gmail.com
3ef289630e0ca418b1b39e9cac87198c91318f7a
b69ce26a991a8fbfcd6ac1abe983648d71346d27
/bridge/main.cc
efeaf5aa2c2a37c39d35e6a7794b8f6caae183a3
[]
no_license
oooxxx996/patterncpp
c914a9a1653bdd64d0356150c254fd8f963db73d
c0e036ad0d064f3ee381e0783924ad0449faf2af
refs/heads/master
2022-12-04T18:00:03.165901
2019-09-08T14:26:26
2019-09-08T14:26:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,471
cc
#include<iostream> #include<memory> using namespace std; //implementor class IOS{ public: virtual void run()=0; ~IOS(){ cout<<"IOS destructor"<<endl; } }; //concret implementor class Ubuntu:public IOS{ public: virtual void run() override{ cout<<"Ubuntu is running..."<<endl; } }; class Win10:public IOS{ public: virtual void run() override{ cout<<"Win10 is running..."<<endl; } }; //Bridge abstraction class Computer{ public: Computer(const shared_ptr<IOS> &os) :os_(os) { } virtual void start()=0; void reinstallOS(const shared_ptr<IOS> &os){ os_=os; } ~Computer(){ cout<<"Computer destructor"<<endl; } protected: shared_ptr<IOS> os_; }; //Concret bridge class Laptop: public Computer{ public: Laptop(const shared_ptr<IOS> &os) :Computer(os) { } virtual void start() override{ cout<<"Laptop is starting..."<<endl; os_->run(); } }; class Desktop: public Computer{ public: Desktop(const shared_ptr<IOS> &os) :Computer(os) { } virtual void start() override{ cout<<"Desktop is starting"<<endl; os_->run(); }; }; int main(){ //构造一个装Ubuntu的Laptop shared_ptr<Computer> pc=make_shared<Laptop>(make_shared<Ubuntu>()); pc->start(); //安装win10系统 pc->reinstallOS(make_shared<Win10>()); pc->start(); //构造一个装Ubuntu的Desktop pc=make_shared<Desktop>(make_shared<Ubuntu>()); pc->start(); //安装win10系统 pc->reinstallOS(make_shared<Win10>()); pc->start(); return 0; }
[ "1902547475@qq.com" ]
1902547475@qq.com
5a9915b70d435488fe91695c7b8c906f114527a9
af9dfcad721a1ecc185f791fa2da922b744a9d28
/longest bitonic sequence.cpp
179536d72dd7774824cc5bd26867739a175e4ee2
[]
no_license
nishitm/c0de
eb58b1fab0d12d03e49906031086a7bb2636d08c
8a12c85f914fa10fa87ed36a9915ee6ac04c6540
refs/heads/master
2021-01-12T13:09:27.628627
2016-11-23T08:13:59
2016-11-23T08:13:59
68,672,133
0
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
#include<bits/stdc++.h> using namespace std; int bitonic( vector<int>v) { int n=v.size(); vector<int>lis(n); for (int i = 0; i < n; i++) lis[i] = 1; vector<int> lis2(n); for (int i = 0; i < n; i++) lis2[i] = 1; for (int i = 1; i < n; i++) for (int j = 0; j < i; j++) if (v[i] > v[j] && lis[i] < lis[j] + 1) lis[i] = lis[j] + 1; for (int i = n-2; i >= 0; i--) for (int j = n-1; j > i; j--) if (v[i] > v[j] && lis2[i] < lis2[j] + 1) lis2[i] = lis2[j] + 1; int max = lis[0] + lis2[0] - 1; for (int i = 1; i < n; i++) if (lis[i] + lis2[i] - 1 > max) max = lis[i] + lis2[i] - 1; return max; } int main() { vector<int> v={2,3,6,9,1,21,245,4,9687,62,13,21,684,3,6,655,41,2,3,56,5}; int size=bitonic(v); cout<<"Size of longest bitonic sequence is:"<<size<<endl; return 0; }
[ "nishitm@cse.iitk.ac.in" ]
nishitm@cse.iitk.ac.in
1f657c03edd25bfa9f2bca1e13bd4a90f761b1e3
ec7cc586344bb518a201f0eab7990ff91b54f054
/lib/qa_baudot_decode_bb.cc
5f76c2c9ed0a96497aa88665badf00a555aa0341
[]
no_license
dl1ksv/gr-radioteletype
e9a426f1eeeeaaa64427d8aa524519c92b60a02a
807960b3572680625c3e056bd6eeb965d15d9a7e
refs/heads/master
2020-07-20T00:00:28.616051
2019-10-13T09:51:49
2019-10-13T09:51:49
206,535,597
2
0
null
2019-09-17T09:54:31
2019-09-05T10:20:51
C++
UTF-8
C++
false
false
1,083
cc
/* -*- c++ -*- */ /* * Copyright 2019 dl1ksv. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include <gnuradio/attributes.h> #include <cppunit/TestAssert.h> #include "qa_baudot_decode_bb.h" #include <radioteletype/baudot_decode_bb.h> namespace gr { namespace radioteletype { void qa_baudot_decode_bb::t1() { // Put test here } } /* namespace radioteletype */ } /* namespace gr */
[ "3470424+dl1ksv@users.noreply.github.com" ]
3470424+dl1ksv@users.noreply.github.com
64bf0727d0c3dbf26ecfd071a47d4654b4bf5c56
425df0659dce92ec507b4ec31b4e1fed30826882
/Recursion I/checkSorted.cpp
304256c26bbc2534f041b6f4d5db506006ed9f95
[]
no_license
mohammadabdullahjawwad/DSAcpp
646bf9a9a8176c05feb320e4926c881c6a29ea92
b637778beb17fb2f632c75cbfc51f133d7e4d66a
refs/heads/master
2023-07-23T17:54:30.967587
2021-09-05T18:39:01
2021-09-05T18:39:01
389,128,151
0
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
#include <iostream> using namespace std; #define FIO \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); #define OJ \ freopen("input.txt", "r", stdin); \ freopen("output.txt", "w", stdout); bool isSorted(int* a, int n) { if(n == 0 || n == 1) { return true; } if(a[0] < a[1] && isSorted(a + 1, n - 1)) { return true; } return false; } void solve() { int n; cin >> n; int* a = new int[n]; for(int i = 0; i < n; i++) { cin >> a[i]; } cout << isSorted(a, n) << endl; } int main() { OJ; FIO; solve(); return 0; }
[ "mohammadabdullahjawwad.official@gmail.com" ]
mohammadabdullahjawwad.official@gmail.com
d4064dd55075f0bd7f59c50120797ad267d5dc93
50f8c138da0165fa140c3241291aa2b0a8a14f99
/prefix flip.cpp
8e1a463e54e44add24a07d9076030316b8ae3055
[]
no_license
Priybhanu99/My-Codes
c5da0821348939d75498e2751bc6c63d5e572294
4dc2e93fb941c4166b3b687a76358a1f309cc976
refs/heads/master
2021-05-19T12:22:09.830851
2021-01-17T15:22:23
2021-01-17T15:22:23
251,694,773
2
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
#include <bits/stdc++.h> using namespace std; #define int long long int #define P pair<int,int> #define pb push_back #define F first #define S second void func(string &a,string &b,int index,int n){ string temp; for (int i = 0; i <= index; ++i) { if(a[i]=='0'){ temp+='1'; }else{ temp+='0'; } } // cout<<"index :"<<index<<" "<<temp<<"\n"; reverse(temp.begin(), temp.end()); for (int i = 0; i <= index; ++i) { a[i] = temp[i]; } } int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int t; cin>>t; while(t--){ int n; cin>>n; string a,b; cin>>a>>b; vector<int> ans; int i = n-1; while(i>=0){ if(a[i]==b[i]){ i--; }else{ if((a[0]==b[0])){ ans.push_back(i+1); func(a,b,i+1,n); // i--; }else{ ans.push_back(1); func(a,b,0,n); // ans.push_back(i+1); // func(a,b,i,n); // i--; } // i--; } // cout<<a<<" "<<b<<"\n"; } cout<<ans.size()<<" "; for(auto ele:ans){ cout<<ele<<" "; } // cout<<"\n"; cout<<"\n"; } }
[ "bhanuyadav1999.by@gmail.com" ]
bhanuyadav1999.by@gmail.com
3d92f0008ee71f9a09abd1910a92119ef80d59cf
f3111dadf4db367239b80c2077d2bdfced1f29c4
/torch/csrc/jit/passes/tensorexpr_fuser.cpp
030d4b2aa14e7e2a19e399ca09c763ebff3080b2
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
Enolerobotti/pytorch
de746ea0b8a052bfdbf563a7ccc3c765d46b99d4
98ad5ff41f82086ce77d5519945aff288b030c6e
refs/heads/master
2022-12-15T20:05:02.998839
2020-09-04T06:35:52
2020-09-04T06:37:45
292,785,956
0
0
NOASSERTION
2020-09-04T07:54:36
2020-09-04T07:54:36
null
UTF-8
C++
false
false
28,420
cpp
#include <torch/csrc/jit/passes/tensorexpr_fuser.h> #include <ATen/record_function.h> #include <torch/csrc/jit/codegen/fuser/interface.h> #include <torch/csrc/jit/ir/alias_analysis.h> #include <torch/csrc/jit/jit_log.h> #include <torch/csrc/jit/passes/common_subexpression_elimination.h> #include <torch/csrc/jit/passes/dead_code_elimination.h> #include <torch/csrc/jit/passes/pass_manager.h> #include <torch/csrc/jit/passes/remove_redundant_profiles.h> #include <torch/csrc/jit/passes/utils/subgraph_utils.h> #include <torch/csrc/jit/runtime/custom_operator.h> #include <torch/csrc/jit/runtime/graph_executor.h> #include <torch/csrc/jit/runtime/operator_options.h> #include <torch/csrc/jit/tensorexpr/kernel.h> #include <torch/csrc/utils/memory.h> namespace torch { namespace jit { static bool texpr_reductions_enabled = false; bool isSupportedForBlock(Node* node) { switch (node->kind()) { case aten::add: case aten::mul: return true; default: return false; } } namespace tensorexpr { bool isSupported(Node* node) { // For Block codegen we allow limited ops. if (tensorexpr::getTEGenerateBlockCode()) { return isSupportedForBlock(node); } // clang-format off // breaks up the schema strings so they are no longer discoverable with ctrl-F static const OperatorSet supported_operator_set{ "aten::add.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor", "aten::add.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor", "aten::_cast_Float(Tensor self, bool non_blocking) -> Tensor", "aten::type_as(Tensor self, Tensor other) -> Tensor", "aten::sub.Tensor(Tensor self, Tensor other, *, Scalar alpha=1) -> Tensor", "aten::sub.Scalar(Tensor self, Scalar other, Scalar alpha=1) -> Tensor", "aten::mul.Tensor(Tensor self, Tensor other) -> Tensor", "aten::mul.Scalar(Tensor self, Scalar other) -> Tensor", "aten::div.Tensor(Tensor self, Tensor other) -> Tensor", "aten::div.Scalar(Tensor self, Scalar other) -> Tensor", "aten::eq.Tensor(Tensor self, Tensor other) -> Tensor", "aten::eq.Scalar(Tensor self, Scalar other) -> Tensor", "aten::ne.Tensor(Tensor self, Tensor other) -> Tensor", "aten::ne.Scalar(Tensor self, Scalar other) -> Tensor", "aten::ge.Tensor(Tensor self, Tensor other) -> Tensor", "aten::ge.Scalar(Tensor self, Scalar other) -> Tensor", "aten::gt.Tensor(Tensor self, Tensor other) -> Tensor", "aten::gt.Scalar(Tensor self, Scalar other) -> Tensor", "aten::le.Tensor(Tensor self, Tensor other) -> Tensor", "aten::le.Scalar(Tensor self, Scalar other) -> Tensor", "aten::lt.Tensor(Tensor self, Tensor other) -> Tensor", "aten::lt.Scalar(Tensor self, Scalar other) -> Tensor", "aten::pow.Tensor_Scalar(Tensor self, Scalar exponent) -> Tensor", "aten::pow.Tensor_Tensor(Tensor self, Tensor exponent) -> Tensor", // TODO : do we support pow.Scalar ? "aten::pow.Scalar(Scalar self, Tensor exponent) -> Tensor", // TODO: support clamp_min, clamp_max "aten::clamp(Tensor self, Scalar? min=None, Scalar? max=None) -> Tensor", "aten::lerp.Scalar(Tensor self, Tensor end, Scalar weight) -> Tensor", "aten::lerp.Tensor(Tensor self, Tensor end, Tensor weight) -> Tensor", "aten::log10(Tensor self) -> Tensor", "aten::log(Tensor self) -> Tensor", "aten::log2(Tensor self) -> Tensor", // TODO: log1p "aten::exp(Tensor self) -> Tensor", "aten::erf(Tensor self) -> Tensor", "aten::erfc(Tensor self) -> Tensor", "aten::fmod.Scalar(Tensor self, Scalar other) -> Tensor", "aten::fmod.Tensor(Tensor self, Tensor other) -> Tensor", "aten::cos(Tensor self) -> Tensor", "aten::sin(Tensor self) -> Tensor", "aten::tan(Tensor self) -> Tensor", "aten::acos(Tensor self) -> Tensor", "aten::asin(Tensor self) -> Tensor", "aten::atan(Tensor self) -> Tensor", "aten::atan2(Tensor self, Tensor other) -> Tensor", "aten::cosh(Tensor self) -> Tensor", "aten::sinh(Tensor self) -> Tensor", "aten::tanh(Tensor self) -> Tensor", "aten::sqrt(Tensor self) -> Tensor", "aten::rsqrt(Tensor self) -> Tensor", "aten::abs(Tensor self) -> Tensor", "aten::floor(Tensor self) -> Tensor", "aten::ceil(Tensor self) -> Tensor", "aten::round(Tensor self) -> Tensor", "aten::trunc(Tensor self) -> Tensor", "aten::threshold(Tensor self, Scalar threshold, Scalar value) -> Tensor", "aten::remainder.Scalar(Tensor self, Scalar other) -> Tensor", "aten::remainder.Tensor(Tensor self, Tensor other) -> Tensor", "aten::cat(Tensor[] tensors, int dim=0) -> Tensor", "aten::sigmoid(Tensor self) -> Tensor", "aten::relu(Tensor self) -> Tensor", "aten::addcmul(Tensor self, Tensor tensor1, Tensor tensor2, *, Scalar value=1) -> Tensor", "aten::neg(Tensor self) -> Tensor", "aten::reciprocal(Tensor self) -> Tensor", "aten::expm1(Tensor self) -> Tensor", "aten::unsqueeze(Tensor(a) self, int dim) -> Tensor(a)", "aten::frac(Tensor self) -> Tensor", // TODO: uncomment once we can handle rand+broadcasts // "aten::rand_like(Tensor self, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor", "aten::__and__.Scalar(Tensor self, Scalar other) -> Tensor", "aten::__and__.Tensor(Tensor self, Tensor other) -> Tensor", "aten::__or__.Scalar(Tensor self, Scalar other) -> Tensor", "aten::__or__.Tensor(Tensor self, Tensor other) -> Tensor", "aten::__xor__.Scalar(Tensor self, Scalar other) -> Tensor", "aten::__xor__.Tensor(Tensor self, Tensor other) -> Tensor", "aten::__lshift__.Scalar(Tensor self, Scalar other) -> Tensor", "aten::__lshift__.Tensor(Tensor self, Tensor other) -> Tensor", "aten::__rshift__.Scalar(Tensor self, Scalar other) -> Tensor", "aten::__rshift__.Tensor(Tensor self, Tensor other) -> Tensor", "aten::where.self(Tensor condition, Tensor self, Tensor other) -> Tensor", "aten::where.ScalarSelf(Tensor condition, Scalar self, Tensor other) -> Tensor", "aten::where.ScalarOther(Tensor condition, Tensor self, Scalar other) -> Tensor", "aten::where.Scalar(Tensor condition, Scalar self, Scalar other) -> Tensor", "aten::where(Tensor condition) -> Tensor[]", // TODO: enable other min/max variants, operators that can be both // elementwise or reductions: "aten::min.other(Tensor self, Tensor other) -> Tensor", "aten::max.other(Tensor self, Tensor other) -> Tensor", // TODO: enable slice, shape inference is not implemented for this op yet }; static const OperatorSet supported_reduction_set{ "aten::sum(Tensor self, *, ScalarType? dtype=None) -> Tensor", "aten::sum.dim_IntList(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor", }; // clang-format on if (node->isMemberOf(supported_operator_set)) { return true; } if (texpr_reductions_enabled && node->isMemberOf(supported_reduction_set)) { return true; } // unschematized ops switch (node->kind()) { case prim::ConstantChunk: case prim::ListConstruct: return true; } return false; } } // namespace tensorexpr static bool texpr_fuser_enabled_ = false; void setTensorExprFuserEnabled(bool val) { texpr_fuser_enabled_ = val; } bool tensorExprFuserEnabled() { static const char* enable_c_str = std::getenv("PYTORCH_TENSOREXPR"); if (!enable_c_str) { return texpr_fuser_enabled_; } if (std::string(enable_c_str) == "0") { return false; } return true; } bool setTexprReductionsEnabled(bool value) { bool old_value = texpr_reductions_enabled; texpr_reductions_enabled = value; return old_value; } bool texprReductionsEnabled() { return texpr_reductions_enabled; } struct nodesComparator { bool operator()(Node* a, Node* b) const { return a->isAfter(b); } }; // TODO: if a value has differently typed uses, temporarrily insert a node // specializing the type for each use and later remove, instead of bailing bool profiledWithDifferentTypes(Value* v) { std::vector<TypePtr> types; for (const auto& use : v->uses()) { if (use.user->kind() == prim::profile) { types.push_back(use.user->ty(attr::profiled_type)); } } for (size_t i = 1; i < types.size(); ++i) { if (types.at(i - 1) != types.at(i)) { return true; } } return false; } void removeProfileNodesAndSpecializeTypes(Block* b) { for (auto it = b->nodes().begin(); it != b->nodes().end(); it++) { if (it->kind() == prim::profile) { GRAPH_DEBUG("Removing prim::profile: %", it->output()->debugName()); it->output()->replaceAllUsesWith(it->input()); if (!profiledWithDifferentTypes(it->input())) { it->input()->setType(it->ty(attr::profiled_type)); } else { GRAPH_DEBUG( "Ignoring value with differently typed profiles :%", it->output()->debugName()); } it.destroyCurrent(); } else { for (Block* ib : it->blocks()) { removeProfileNodesAndSpecializeTypes(ib); } } } } void RemoveProfileNodesAndSpecializeTypes(std::shared_ptr<Graph>& graph) { removeProfileNodesAndSpecializeTypes(graph->block()); } void removeTensorTypeSpecialization(Value* v) { if (!v->type()->cast<TensorType>()) { return; } // Constants & TensorExprGroup will always produce specialized tensor type, // TypeCheck are inserted by this pass and only used by fusion groups that // insert proper guards if (v->node()->kind() == prim::Constant || v->node()->kind() == prim::TypeCheck || v->node()->kind() == prim::TensorExprGroup) { return; } v->setType(TensorType::get()); } void removeTensorTypeSpecializations(Block* block) { for (Value* v : block->inputs()) { removeTensorTypeSpecialization(v); } for (Node* n : block->nodes()) { for (Block* b : n->blocks()) { removeTensorTypeSpecializations(b); } for (Value* v : n->outputs()) { removeTensorTypeSpecialization(v); } } } void RemoveTensorTypeSpecializations(std::shared_ptr<Graph>& graph) { removeTensorTypeSpecializations(graph->block()); } class TensorExprFuser { public: TensorExprFuser(std::shared_ptr<Graph> graph, size_t min_group_size) : graph_(std::move(graph)), min_group_size_(min_group_size) {} void run() { aliasDb_ = torch::make_unique<AliasDb>(graph_); RemoveRedundantProfiles(graph_); GRAPH_DUMP("After removing redundant profile nodes: ", graph_); createFusionGroups(graph_->block()); GRAPH_DUMP("After creating fusion groups: ", graph_); guardFusionGroups(graph_->block()); GRAPH_DUMP("After guarding fusion groups: ", graph_); removeTensorTypeSpecializations(graph_->block()); GRAPH_DUMP("After removing tensor type specializations: ", graph_); } private: // Merges `to_merge` into a subgraph by executing merge_fn. // merge_fn takes in map that will be filled with the mapping b/w // to_merge's outputs and the corresponding values in the subgraph. // merge_fn returns the merged-into subgraph Node* aliasingSafeSubgraphMerge( Node* to_merge, const std::function<Node*(std::unordered_map<Value*, Value*>&)>& merge_fn) { // When we merge a node into a subgraph, the new subgraph outputs // have the same aliasing properties as the original node's outputs. // Here we create a placeholder node, transfer the aliasing properties // to the placeholder, execute the merge, and transfer the aliasing // properties to the appropriate fusion group outputs Node* placeholder_node = graph_->insertNode(graph_->create(prim::Uninitialized, 0)); std::vector<Value*> existing_values; for (size_t i = 0; i < to_merge->outputs().size(); ++i) { Value* existing = to_merge->outputs().at(i); Value* new_value = placeholder_node->insertOutput(i)->copyMetadata( to_merge->outputs().at(i)); aliasDb_->replaceWithNewValue(existing, new_value); existing_values.push_back(existing); } std::unordered_map<Value*, Value*> vmap; Node* fusion_group = merge_fn(vmap); for (size_t i = 0; i < existing_values.size(); ++i) { TORCH_INTERNAL_ASSERT(vmap.count(existing_values.at(i))); Value* subgraph_value = vmap[existing_values.at(i)]; auto subgraph = SubgraphUtils::getSubgraph(fusion_group); size_t subgraph_output_index = 0; for (; subgraph_output_index < subgraph->outputs().size(); ++subgraph_output_index) { if (subgraph->outputs().at(subgraph_output_index) == subgraph_value) { break; } } if (subgraph_output_index != subgraph->outputs().size()) { aliasDb_->replaceWithNewValue( placeholder_node->outputs().at(i), fusion_group->outputs().at(subgraph_output_index)); } } placeholder_node->destroy(); return fusion_group; } Node* getOrCreateTensorExprSubgraph(Node* n) { if (n->hasAttribute(attr::Subgraph) && n->kind() == prim::TensorExprGroup) { return n; } GRAPH_UPDATE("Creating a tensorexpr::Group node from: ", *n); return aliasingSafeSubgraphMerge( n, [&](std::unordered_map<Value*, Value*>& vmap) { return SubgraphUtils::createSingletonSubgraph( n, prim::TensorExprGroup, vmap); }); } void mergeNodeIntoSubgraphAndUpdateAliasing(Node* n, Node* subgraph) { aliasingSafeSubgraphMerge(n, [&](std::unordered_map<Value*, Value*>& vmap) { SubgraphUtils::mergeNodeIntoSubgraph(n, subgraph, vmap); return subgraph; }); } // Add unvisited input nodes to the queue for further merging into the fusion // group. void updateQueue( Node* fusion_group, std::set<Node*, nodesComparator>& queue, const std::unordered_set<Node*>& visited) { for (auto input : fusion_group->inputs()) { if (!visited.count(input->node())) { queue.insert(input->node()); } } } // Create a fusion group starting from the node N. // We then try to pull inputs into the fusion group and repeat that process // until there is nothing we can pull in. Node* createFusionGroup(Node* n) { // Queue of the nodes we should consider for merging into the fusion groups // (those nodes are usually inputs of the fusion group). // We use an ordered set here to visit them in the right order: the fusion // group is closer to the end of the block and we are trying to pull later // nodes first. // NB: the order in the list in theory could stale if we move nodes around. // However, this should only happen to the nodes we could not fuse, and // hence it should not be a problem. std::set<Node*, nodesComparator> queue; std::unordered_set<Node*> visited_nodes; Node* fusion_group = n; if (min_group_size_ == 1) { fusion_group = getOrCreateTensorExprSubgraph(n); } updateQueue(fusion_group, queue, visited_nodes); GRAPH_DEBUG("Iteratively pull input nodes into the fusion group...\n"); while (!queue.empty()) { debugDumpFusionGroup("Current fusion group: ", fusion_group); GRAPH_DEBUG(queue.size(), " nodes are in the queue.\n"); Node* input_node = *queue.begin(); queue.erase(queue.begin()); GRAPH_DEBUG("Trying to merge: ", *input_node); fusion_group = tryMerge(fusion_group, input_node); visited_nodes.insert(input_node); updateQueue(fusion_group, queue, visited_nodes); } return fusion_group; } static void debugDumpFusionGroup(const std::string& msg, Node* n) { GRAPH_DEBUG(msg, *n); if (n->kind() == prim::TensorExprGroup) { GRAPH_DEBUG(*n->g(attr::Subgraph)); } } // Merge fusible nodes into subgraphs in prim::TensorExprGroup nodes. void createFusionGroups(Block* block) { std::vector<Node*> fusion_groups; auto reverse_iter = block->nodes().reverse(); for (auto it = reverse_iter.begin(); it != reverse_iter.end();) { Node* n = *it; GRAPH_DEBUG("Considering node:", *n) for (Block* b : n->blocks()) { createFusionGroups(b); } if (!canHandle(n)) { it++; continue; } // There are some nodes that we can support, but we don't want to start a // fusion group from - skip them. if (n->kind() == prim::ListConstruct || n->kind() == aten::slice || n->kind() == aten::unsqueeze || n->kind() == prim::ConstantChunk || n->kind() == prim::Constant) { it++; continue; } Node* fusion_group = createFusionGroup(n); fusion_groups.push_back(fusion_group); it = fusion_group->reverseIterator(); it++; } for (Node* n : fusion_groups) { inlineIfTooSmall(n); } } size_t blockSize(Block* block) { size_t num = 0; for (Node* n : block->nodes()) { // Don't count prim::Constants and prim::ListConstructs as these are nodes // we only pull in along with another, "main", node. E.g. the // ListConstruct nodes would also be pulled into a fusion group if they // are inputs of an aten::cat node. if (n->kind() == prim::Constant || n->kind() == prim::ListConstruct) { continue; } for (Block* b : n->blocks()) { num += blockSize(b); } num++; } return num; } bool inlineIfTooSmall(Node* n) { if (n->kind() != prim::TensorExprGroup) { return false; } auto subgraph = SubgraphUtils::getSubgraph(n); size_t num_modes = blockSize(subgraph->block()); if (num_modes < min_group_size_) { GRAPH_UPDATE("Fusion group is too small, unmerging: ", *n); SubgraphUtils::unmergeSubgraph(n); return true; } return false; } Node* tryMerge(Node* fusion_group, Node* to_merge) { if (!canMerge(fusion_group, to_merge)) { return fusion_group; } std::vector<Node*> nodes_to_merge = {to_merge}; if (to_merge->kind() == aten::cat) { Node* listconstruct = to_merge->input(0)->node(); nodes_to_merge.push_back(listconstruct); } // First, try to move all the nodes we want to fuse next to the fusion // group. Node* move_point = fusion_group; for (auto n : nodes_to_merge) { GRAPH_UPDATE("Trying to move node next to fusion group: ", getHeader(n)); if (!aliasDb_->moveBeforeTopologicallyValid(n, move_point)) { GRAPH_UPDATE("Failed to move because of AliasDB checks!"); return fusion_group; } move_point = n; } // Now all the nodes that we're going to fuse are moved next to the fusion // group, so we can safely merge them into the fusion group subgraph. fusion_group = getOrCreateTensorExprSubgraph(fusion_group); for (auto n : nodes_to_merge) { GRAPH_UPDATE("Merging ", getHeader(n)); mergeNodeIntoSubgraphAndUpdateAliasing(n, fusion_group); } return fusion_group; } bool allShapesAreKnown(Node* node) { // TODO: Relax the checks to support dynamic shapes for (Value* input : node->inputs()) { if (input->type()->cast<TensorType>()) { if (!input->isCompleteTensor()) { return false; } if (*input->type()->cast<TensorType>()->dim() == 0) { return false; } } } return true; } bool canFuseOnDevice(Value* v) { auto type = v->type()->cast<TensorType>(); if (!type) { return true; } auto device = type->device(); if (!device) { return false; } if (device->is_cpu()) { return canFuseOnCPU(); } else if (device->is_cuda()) { return canFuseOnGPU(); } throw std::runtime_error("Unknown device"); } bool isFusableOnDevice(Node* node) { for (const auto& input : node->inputs()) { if (!canFuseOnDevice(input)) { return false; } } return true; } bool canHandle(Node* node) { if (node->kind() == prim::Constant) { // TODO: add support for tensor constants. return false; } if (!allShapesAreKnown(node)) { return false; } if (!isFusableOnDevice(node)) { return false; } // Don't include nodes whose inputs are tensor constants - we cannot handle // them at the moment. // TODO: actually support tensor constants and remove this. for (Value* input : node->inputs()) { if (input->node()->kind() == prim::Constant && input->type()->cast<TensorType>()) { return false; } } return tensorexpr::isSupported(node); } #define REQ(cond) \ if (!(cond)) { \ GRAPH_DEBUG("Failed cond " #cond "\n"); \ return false; \ } bool canMerge(Node* consumer, Node* producer) { // Only fuse within a block REQ(consumer->owningBlock() == producer->owningBlock()); // Symbolic checks REQ(canHandle(producer)); TORCH_INTERNAL_ASSERT( consumer->kind() == prim::TensorExprGroup || canHandle(consumer)); // Alias checks REQ(aliasDb_->couldMoveBeforeTopologically(producer, consumer)); // Ops that return aliases can only be folded if this is the only use. if (producer->kind() == aten::slice || producer->kind() == aten::unsqueeze || producer->kind() == prim::ConstantChunk) { for (auto& use : producer->output(0)->uses()) { REQ(use.user == consumer); } } if (!consumer->hasAttribute(attr::Subgraph) && consumer->kind() != prim::TensorExprGroup) { // Don't initiate a fusion group from prim::ListConstruct REQ(consumer->kind() != prim::ListConstruct); REQ(consumer->kind() != aten::slice); REQ(consumer->kind() != aten::unsqueeze); REQ(consumer->kind() != prim::ConstantChunk); // Don't initiate a fusion group just for a constant operand REQ(producer->kind() != prim::Constant); } if (producer->kind() == aten::cat) { REQ(producer->input(0)->node()->kind() == prim::ListConstruct); REQ(producer->input(0)->uses().size() == 1); REQ(producer->input(1)->node()->kind() == prim::Constant); auto const& listConstruct = producer->input(0)->node(); for (auto const& input : listConstruct->inputs()) { REQ(isFusableOnDevice(input->node())); } } else if (consumer->kind() == aten::cat) { REQ(consumer->input(0)->node()->kind() == prim::ListConstruct); REQ(consumer->input(0)->uses().size() == 1); REQ(consumer->input(1)->node()->kind() == prim::Constant); auto const& listConstruct = consumer->input(0)->node(); for (auto const& input : listConstruct->inputs()) { REQ(isFusableOnDevice(input->node())); } } else { REQ(isFusableOnDevice(producer)); } return true; } #undef REQ void guardFusionGroup(Node* fusion_group) { GRAPH_DEBUG("Inserting a typecheck guard for a node", *fusion_group); auto subgraph = SubgraphUtils::getSubgraph(fusion_group); // Fixup types of the subgraph inputs std::vector<Value*> inputs_to_check; for (Value* input : fusion_group->inputs()) { // We only check inputs of the fusion group and expect NNC to infer // intermediates and outputs shapes if (!input->type()->cast<TensorType>()) { continue; } // fusion outputs are already guarded if (input->node()->kind() == prim::Constant || input->node()->kind() == prim::FusionGroup) { continue; } inputs_to_check.push_back(input); } if (!inputs_to_check.size()) { return; } // Add prim::TypeCheck node // // TypeCheck nodes look like the following: // %out1 : Float(2, 3), %out2 : Int(10, 30), %types_match : bool = // prim::TypeCheck(%inp1 : Tensor, %inp2 : Tensor) // // They have N inputs whose types we are going to check and N+1 outputs. The // first N outputs specify expected types and N+1-th output holds the result // of the check (bool). Node* typecheck_node = fusion_group->owningGraph() ->create( prim::TypeCheck, inputs_to_check, inputs_to_check.size() + 1) ->insertBefore(fusion_group); Value* typecheck_result = typecheck_node->output(inputs_to_check.size()); std::unordered_map<Value*, Value*> typechecked_inputs; for (size_t i = 0; i < typecheck_node->inputs().size(); ++i) { typechecked_inputs[typecheck_node->input(i)] = typecheck_node->output(i); } // Fixup types of the typecheck node outputs, which are used by the op in // execution typecheck_node->output(inputs_to_check.size())->setType(BoolType::get()); for (size_t i = 0; i < typecheck_node->inputs().size(); ++i) { typecheck_node->output(i)->setType(typecheck_node->input(i)->type()); } // Insert if auto versioning_if = fusion_group->owningGraph() ->create( prim::If, {typecheck_result}, fusion_group->outputs().size()) ->insertAfter(typecheck_node); for (size_t idx = 0; idx < fusion_group->outputs().size(); ++idx) { versioning_if->output(idx)->setType(fusion_group->output(idx)->type()); fusion_group->output(idx)->replaceAllUsesWith(versioning_if->output(idx)); } auto true_block = versioning_if->addBlock(); auto false_block = versioning_if->addBlock(); // Fill in the false block. It should contain the unoptimized // copy of the fused subgraph. WithInsertPoint guard(false_block->return_node()); const auto subgraph_outputs = insertGraph( *fusion_group->owningGraph(), *subgraph, fusion_group->inputs()); for (Value* output : subgraph_outputs) { false_block->registerOutput(output); } replaceBlockWithFallbackGraph(false_block, fusion_group->inputs()); // Fill in the true block. It has all inputs type-checked and its // body should be the fusion group node. fusion_group->moveBefore(true_block->return_node()); for (size_t idx = 0; idx < fusion_group->inputs().size(); ++idx) { if (typechecked_inputs.count(fusion_group->input(idx))) { fusion_group->replaceInput( idx, typechecked_inputs.at(fusion_group->input(idx))); } } for (Value* output : fusion_group->outputs()) { true_block->registerOutput(output); } } void guardFusionGroups(Block* block) { std::vector<Node*> fusion_groups; for (Node* n : block->nodes()) { for (Block* b : n->blocks()) { guardFusionGroups(b); } if (n->kind() == prim::TensorExprGroup) { fusion_groups.push_back(n); } } for (Node* fusion_group : fusion_groups) { guardFusionGroup(fusion_group); } } std::shared_ptr<Graph> graph_; std::unique_ptr<AliasDb> aliasDb_ = nullptr; // Minimal size of a fusion group size_t min_group_size_; }; void FuseTensorExprs(std::shared_ptr<Graph>& graph, size_t min_group_size) { GRAPH_DUMP("Before TExprFuser: ", graph); // Temporary change for Block code generation. if (tensorexpr::getTEGenerateBlockCode()) { min_group_size = 1; } // Get rid of dead code so that we don't waste effort fusing it. EliminateDeadCode(graph); TensorExprFuser fuser(graph, min_group_size); fuser.run(); EliminateCommonSubexpression(graph); EliminateDeadCode(graph); GRAPH_DUMP("After TExprFuser: ", graph); } Operation createTensorExprOp(const Node* node) { auto kernel = std::make_shared<tensorexpr::TensorExprKernel>(node->g(attr::Subgraph)); return [kernel](Stack* stack) { RECORD_FUNCTION("TensorExpr", std::vector<c10::IValue>()); if (!tensorexpr::fallbackAllowed()) { kernel->run(*stack); return 0; } try { kernel->run(*stack); } catch (const std::runtime_error& e) { kernel->fallback(*stack); } return 0; }; } RegisterOperators TensorExprOps({ torch::jit::Operator( prim::TensorExprGroup, createTensorExprOp, AliasAnalysisKind::INTERNAL_SPECIAL_CASE), }); } // namespace jit } // namespace torch
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
c1df7e882849bb311aff38f5e33d7ed4c699e06e
0858a74e7699c814845d3757a66a908ce5902289
/examples/10_IoT/BulutLedKontrol/src/BulutLedKontrol.cpp
b35a995256bced821a4fb71d5762ea5b2c663e15
[ "Apache-2.0" ]
permissive
MelihOzbk/deneyapkart-platformio-core
e1e980b8c43dacccf05eaaea2745e6191fbb029a
c0fbc8ffa181ee22e597569b24bde5a011ccaaa4
refs/heads/master
2023-09-02T16:44:47.698167
2021-10-10T09:02:25
2021-10-10T09:02:25
415,533,253
0
0
null
null
null
null
UTF-8
C++
false
false
3,200
cpp
// Adafruit IO kullanarak IoT tabanli uzaktan led kontrol uygulamasi #include <Arduino.h> #include "deneyap.h" #include "WiFiESP32.h" #include <Adafruit_MQTT.h> #include <Adafruit_MQTT_Client.h> #define WLAN_SSID "***********" // Baglanti kurulacak Wi-Fi agi adi #define WLAN_PASS "***********" // Baglanti kurulacak Wi-Fi agi sifresi #define AIO_SERVER "io.adafruit.com" #define AIO_SERVERPORT 1883 #define AIO_USERNAME "***********" // Adafruit IO kullanici ismi #define AIO_KEY "***********" // Adafruit IO kullanici anahtari WiFiClient client; Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); Adafruit_MQTT_Subscribe kirmizi_led = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/kirmizi-led"); Adafruit_MQTT_Subscribe yesil_led = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/yesil-led"); Adafruit_MQTT_Subscribe mavi_led = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/mavi-led"); void MQTT_connect() { int8_t ret; if (mqtt.connected()) { return; } Serial.print("Bulut sistemine baglaniliyor... "); uint8_t count = 3; while ((ret = mqtt.connect()) != 0) { Serial.println(mqtt.connectErrorString(ret)); Serial.println("3 saniye icinde tekrar baglanti denemesi gerceklesecek..."); mqtt.disconnect(); delay(5000); count = count - 1 ; if (count == 0) { esp_restart(); } } Serial.println("Bulut sistemine baglanildi!"); } void setup() { pinMode(LEDR, OUTPUT); pinMode(LEDG, OUTPUT); pinMode(LEDB, OUTPUT); Serial.begin(115200); delay(10); Serial.println(); Serial.println(); Serial.print(WLAN_SSID); Serial.print(" kablosuz agina baglaniliyor"); WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("Kablosuz aga baglanildi!"); Serial.print("IP adresi: "); Serial.println(WiFi.localIP()); mqtt.subscribe(&kirmizi_led); mqtt.subscribe(&yesil_led); mqtt.subscribe(&mavi_led); } void loop() { MQTT_connect(); Adafruit_MQTT_Subscribe *subscription; while ((subscription = mqtt.readSubscription(5000))) { if(subscription == &kirmizi_led) { Serial.print(F("Gelen mesaj: ")); Serial.println((char *)kirmizi_led.lastread); if (!strcmp((char*) kirmizi_led.lastread, "AÇIK")) { writeRedLed(HIGH); } else { writeRedLed(LOW); } } else if(subscription == &yesil_led) { Serial.print(F("Gelen mesaj: ")); Serial.println((char *)yesil_led.lastread); if (!strcmp((char*) yesil_led.lastread, "AÇIK")) { writeGreenLed(HIGH); } else { writeGreenLed(LOW); } } else if(subscription == &mavi_led) { Serial.print(F("Gelen mesaj: ")); Serial.println((char *)mavi_led.lastread); if (!strcmp((char*) mavi_led.lastread, "AÇIK")) { writeBlueLed(HIGH); } else { writeBlueLed(LOW); } } } }
[ "ozgur.bostan@rftek.com.tr" ]
ozgur.bostan@rftek.com.tr
3e644680727affdd983e8d7c1d0b23b88c8c0e53
84d6d5a193eca3a7a9b9d6159c30c560ca0344b1
/test/linker.cc
cdfedd77425ce6b003d9a45aaae08a2700524381
[ "MIT" ]
permissive
tttcn/Kluster
2f81c775440d99bce9fb9088d4c8ce8744ee2124
a12b450ebdd07b201481aea49375b5673ba278d4
refs/heads/master
2020-09-10T23:24:02.968900
2020-01-05T15:19:42
2020-01-05T15:19:42
221,864,084
1
0
null
null
null
null
UTF-8
C++
false
false
4,080
cc
/* * 用于处理二进制的csv文件 * 数据格式:v1,...,vn 这样的连续向量 */ #include "src/api.cuh" #include "fstream" #include "iostream" #include <string> #include <omp.h> #include <sys/mman.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/stat.h> #include <algorithm> void init_node(Node *node, int node_num) { for (int id = 0; id < node_num; ++id) { node[id].data = id; node[id].rank = 1; node[id].parent = id; } } int get_parent(Node *node, int index) { int parent_index = index; while (parent_index != node[parent_index].parent) { parent_index = node[parent_index].parent; } while (parent_index != node[index].parent) { int tmp = node[index].parent; node[index].parent = parent_index; index = tmp; } return (parent_index); } void Union(Node *node, int a, int b) { a = get_parent(node, a); b = get_parent(node, b); if (node[a].rank > node[b].rank) node[b].parent = a; else { node[a].parent = b; if (node[a].rank == node[b].rank) node[b].rank++; } } bool compareNode(const Node &node1, const Node &node2) { if (node1.parent < node2.parent) return true; if (node1.parent > node2.parent) return false; if (node1.parent == node2.parent) return node1.data < node2.data; } void fprintSet(Node *node, int node_num, FILE *set_file) { // 排序 fprintf(set_file, "set_id:node_ids"); std::sort(node, node + node_num, compareNode); int root = -1; for (int id = 0; id < node_num; ++id) { if (root < node[id].parent) { root = node[id].parent; fprintf(set_file, "\n%d:", node[id].data); } fprintf(set_file, "%d,", node[id].data); } fprintf(set_file, "\n"); } int main(int argc, char *argv[]) { if (argc != 6) { printf("usage: program node_file_name edge_file_name data_num data_dim threshold\n"); return 1; } char *node_file_name = argv[1]; char *edge_file_name = argv[2]; char *data_num_string = argv[3]; char *data_dim_string = argv[4]; char *threshold_string = argv[5]; int data_num = atoi(data_num_string); int data_dim = atoi(data_dim_string); float threshold = atof(threshold_string); int edge_num = MAX_EDGE_NUM; coo *edge_data = new coo[edge_num]; // 并查集初始化 Node *node = new Node[data_num]; init_node(node, data_num); // 打开并读取文件 int fd_node = open(node_file_name, O_RDONLY); unsigned int node_file_size = data_num * data_dim * sizeof(float); float *node_data = (float *)mmap(NULL, node_file_size, PROT_READ, MAP_SHARED, fd_node, 0); // mmap映射数据至内存中 int batch_len = BATCH_LEN; // 经验参数,16K对应最大4G的coo edge_num = DistanceLinker(node_data, edge_data, data_num, data_dim, threshold, batch_len); printf("edge linked\n"); // 写回结果 if (edge_num == -1) // 阈值太高导致取得边数超过了容纳上限 { printf("edge num overflow, lower your threshold!\n"); } else { printf("edge num is %d\n", edge_num); FILE *edge_file = fopen(edge_file_name, "w"); fprintf(edge_file, "node1_position,node2_position,distance\n"); for (int edge_id = 0; edge_id < edge_num; ++edge_id) { fprintf(edge_file, "%d,%d,%f\n", edge_data[edge_id].base_id, edge_data[edge_id].query_id, edge_data[edge_id].distance); } fclose(edge_file); for (int edge_id = 0; edge_id < edge_num; ++edge_id) { Union(node, edge_data[edge_id].base_id, edge_data[edge_id].query_id); } FILE *set_file = fopen("../data/set.txt", "w"); fprintSet(node, data_num, set_file); } delete[] edge_data; delete[] node; munmap(node_data, node_file_size); // 解除映射关系 close(fd_node); return 0; }
[ "tttang.cn@gmail.com" ]
tttang.cn@gmail.com
e1da8aa1680584e241031c509124f28a3e334ab2
a0f040e88a59df2312f05744e1d9ce9650aed54b
/original/Database.cpp
9100de229f96f3711e8ecb7698a583e2c0325ff5
[]
no_license
JaredEzz/RelationalDatabase
989eb1d51d510340736211b8640951230f895677
bda3995b1bcd5d06cc222e04282934f44d6c6816
refs/heads/master
2020-12-03T08:19:37.814756
2020-01-01T18:21:34
2020-01-01T18:21:34
231,249,305
0
0
null
null
null
null
UTF-8
C++
false
false
3,027
cpp
#include "Database.h" using namespace std; string printd(vector<string> vec) { stringstream out; for (unsigned int i = 0; i < vec.size(); i++) { out << "(" << vec.at(i) << ")" << " "; } return out.str(); } Database::Database(char* arg1, char* arg2) : p(arg1, arg2) { schemes = p.getDatalog().getSchemes(); facts = p.getDatalog().getFacts(); queries = p.getDatalog().getQueries(); out.open(arg2); buildRelations(); //toString(); evalQueries(); out.close(); } void Database::buildRelations() { parseSchemes(); parseFacts(); } void Database::parseSchemes() { Relation r; for (unsigned int i = 0; i < schemes.size(); i++) { r.setName(schemes.at(i).getIdentity()); setRelationScheme(r, i); rels.insert(pair<string, Relation>(r.getName(), r)); r.clear(); } } void Database::setRelationScheme(Relation& r, unsigned int i) { for (unsigned int j = 0; j < schemes.at(i).getParameterList().size(); j++) { r.addSchemeAttribute(p.getDatalog().getSchemes().at(i).getParameterList().at(j).getValue()); } } void Database::parseFacts() { Tuple t; for (unsigned int i = 0; i < facts.size(); i++) { if (rels.count(facts.at(i).getIdentity())) { setTupleAttributeValues(t, i); rels.at(facts.at(i).getIdentity()).addTuple(t); t.clear(); } } } void Database::setTupleAttributeValues(Tuple& t, unsigned int i) { for(unsigned int j = 0; j < facts.at(i).getParameterList().size(); j++) { t.addAttributeValue(facts.at(i).getParameterList().at(j).getValue()); } } bool compare (const Relation& r1, const Relation& r2) { return r1.getName() < r2.getName(); } void Database::evalQueries() { Relation r; map<string, unsigned int> variables; map<unsigned int, string> variablePos; for (unsigned int i = 0; i < queries.size(); i++) { if (rels.count(queries.at(i).getIdentity())) { r = rels.at(queries.at(i).getIdentity()); for (unsigned int j = 0; j < queries.at(i).getParameterList().size(); j++) { string value = queries.at(i).getParameterList().at(j).getValue(); if (value.at(0) == '\'') { r.select(j, value); } else { if (variables.count(value) > 0) { r.select(j, variables.at(value)); } variables.insert(pair<string, unsigned int>(value, j)); if (variables.size() > variablePos.size()) { variablePos.insert(pair<unsigned int, string>(j, value)); } } r.setName("select"); } } queryToString(i ,r.getTuples().size()); if (r.getTuples().size() > 0) { //r.toString(out); r.project(variablePos); //r.toString(out); r.rename(variablePos); r.toString(out); cout << endl; } variables.clear(); variablePos.clear(); } } void Database::toString() { for (auto& rel : rels) { rel.second.toString(out); cout << endl; } } void Database::queryToString(unsigned int i, unsigned int numMatches) { cout << queries.at(i).toString() << "? "; if (numMatches > 0) { cout << "Yes(" << numMatches << ")"; } else { cout << "No" << endl; } }
[ "jhasson@simplifile.com" ]
jhasson@simplifile.com
30d9450ff28689f0391eca399d22c2ff0cdf994d
6e0609ae1c009e92501a9cc99d9b368065260b03
/lab2/laba2_cpp/Text.h
45649f42ae905b698c4cd545e83d0dadc89a8252
[]
no_license
lososs244/OOP_labs_2sem
c0e46860ce0810f28189581ac760b09ff058f027
fa70ed8b3d8b89874ec7a99dca73ee1c5d122d6d
refs/heads/master
2022-10-08T22:48:31.609272
2020-06-08T11:46:32
2020-06-08T11:46:32
269,462,808
0
0
null
null
null
null
UTF-8
C++
false
false
386
h
#ifndef TEXT #define TEXT #include "String.h" #include <vector> using namespace std; class Text { private: int size = 0; vector<String> text; public: int get_length(); void output_text(); void add_line(char*); double middle_length(); double vitsotok_holosnyh(); //void find_and_delete(string); void delete_line(int); void clearing(); }; #endif
[ "asdfqwerzxcv549@gmail.com" ]
asdfqwerzxcv549@gmail.com
91e984c9399da005efec152090f2d6cabb3a252b
b7cf5a0ec91b407cead7b77991e1d8e8f98a9eee
/2016/day8.h
9109ccf05bc3b94760e63d3a0ee7968d0747a959
[]
no_license
Kobzol/advent-of-code
07d3737b3b415b41bf1cc1e870fd9717edbff5f8
6b3af9a37b21de738062fb41df3b3479f14d67bc
refs/heads/master
2023-01-11T09:15:05.040074
2022-12-25T09:31:09
2022-12-25T09:31:09
159,705,336
6
0
null
null
null
null
UTF-8
C++
false
false
1,777
h
#pragma once #include <fstream> #include <string> #include <iostream> #include <sstream> void day8() { std::fstream fs("input.txt", std::ios::in); std::string display[6]; for (int i = 0; i < 6; i++) { display[i] = std::string(50, '.'); } std::string row; while (std::getline(fs, row)) { std::stringstream ss(row); std::string tmp; if (row.find("rect") != std::string::npos) { ss >> tmp; ss.get(); int a, b; ss >> a; ss.get(); ss >> b; for (int i = 0; i < b; i++) { for (int j = 0; j < a; j++) { display[i][j] = '#'; } } } else if (row.find("rotate row") != std::string::npos) { row = row.substr(13); int rowIndex, offset; ss = std::stringstream(row); ss >> rowIndex; ss.get(); ss.get(); ss.get(); ss.get(); ss >> offset; offset = offset % 50; std::vector<char> tmp(50, '.'); for (int i = 0; i < 50; i++) { tmp[(i + offset) % 50] = display[rowIndex][i]; } for (int i = 0; i < 50; i++) { display[rowIndex][i] = tmp[i]; } } else if (row.find("rotate column") != std::string::npos) { row = row.substr(16); int columnIndex, offset; ss = std::stringstream(row); ss >> columnIndex; ss.get(); ss.get(); ss.get(); ss.get(); ss >> offset; offset = offset % 6; std::vector<char> tmp(6, '.'); for (int i = 0; i < 6; i++) { tmp[(i + offset) % 6] = display[i][columnIndex]; } for (int i = 0; i < 6; i++) { display[i][columnIndex] = tmp[i]; } } } int lit = 0; for (int i = 0; i < 6; i++) { for (int j = 0; j < 50; j++) { std::cout << display[i][j]; if (display[i][j] == '#') { lit++; } } std::cout << std::endl; } std::cout << lit << std::endl; }
[ "berykubik@gmail.com" ]
berykubik@gmail.com
db8f026b2c5fe443c9aae3da5c58c076993164b7
6852c86d29ea45143de348a38944539e155e23fc
/020-sound-sensor-module/020-sound-sensor-module.ino
6b84a28352ab1b7c627df294d3d63b5be629285c
[]
no_license
fallwall/workshop-intro-to-prototyping-with-arduino
cdd488de07a99e47a8fdd7d244b313ad850b8cb3
7fb811604f511fac370dc376193761bce20e8b89
refs/heads/master
2023-04-08T09:24:52.314018
2021-04-15T18:46:45
2021-04-15T18:46:45
333,990,704
0
0
null
null
null
null
UTF-8
C++
false
false
2,536
ino
/* LED1 should be lit, showing power. LED2 indicates sound input, and the sensitivity is adjusted by potentiometer. There is a tiny screw on the blue potentiometer block that you can use for adjustment. Turning that clockwise lowers the potentiometer value, while counter-clockwise raises the potentiometer value. Use the potentiometer to adjust the Sound Sensor sensitivity. Turn the potentiometer several rotations until you see the LED2 extinguish (or just faintly blink). This might be slightly greater than 500, if you are also watching Serial Monitor (inital adjustment), or, Serial Plotter (the latter is prefererd for observation). Special thanks to user CRomer, for his input and hard work! */ int sensorAnalogPin = A0; // Select the Arduino input pin to accept the Sound Sensor's analog output int sensorDigitalPin = 7; // Select the Arduino input pin to accept the Sound Sensor's digital output int analogValue = 0; // Define variable to store the analog value coming from the Sound Sensor int digitalValue; // Define variable to store the digital value coming from the Sound Sensor int Led13 = 13; // Define LED port; this is the LED built in to the Arduino (labled L) // When D0 from the Sound Sensor (connnected to pin 7 on the // Arduino) sends High (voltage present), L will light. In practice, you // should see LED13 on the Arduino blink when LED2 on the Sensor is 100% lit. void setup() { Serial.begin(9600); // The IDE settings for Serial Monitor/Plotter (preferred) must match this speed pinMode(sensorDigitalPin,INPUT); // Define pin 7 as an input port, to accept digital input pinMode(Led13,OUTPUT); // Define LED13 as an output port, to indicate digital trigger reached } void loop(){ analogValue = analogRead(sensorAnalogPin); // Read the value of the analog interface A0 assigned to digitalValue digitalValue=digitalRead(sensorDigitalPin); // Read the value of the digital interface 7 assigned to digitalValue Serial.println(analogValue); // Send the analog value to the serial transmit interface if(digitalValue==HIGH) // When the Sound Sensor sends signla, via voltage present, light LED13 (L) { digitalWrite(Led13,HIGH); } else { digitalWrite(Led13,LOW); } delay(50); // Slight pause so that we don't overwhelm the serial interface }
[ "fallwall19@gmail.com" ]
fallwall19@gmail.com
9b783c225da1863ed1242a877fdbdd2498132f47
60bb67415a192d0c421719de7822c1819d5ba7ac
/blazetest/src/mathtest/dmatsmatmult/SLDaLCa.cpp
61a98057092315dc8fad91764ef24e55b62dfac5
[ "BSD-3-Clause" ]
permissive
rtohid/blaze
48decd51395d912730add9bc0d19e617ecae8624
7852d9e22aeb89b907cb878c28d6ca75e5528431
refs/heads/master
2020-04-16T16:48:03.915504
2018-12-19T20:29:42
2018-12-19T20:29:42
165,750,036
0
0
null
null
null
null
UTF-8
C++
false
false
4,475
cpp
//================================================================================================= /*! // \file src/mathtest/dmatsmatmult/SLDaLCa.cpp // \brief Source file for the SLDaLCa dense matrix/sparse matrix multiplication math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/LowerMatrix.h> #include <blaze/math/StrictlyLowerMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatsmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'SLDaLCa'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions using SLDa = blaze::StrictlyLowerMatrix< blaze::DynamicMatrix<TypeA> >; using LCa = blaze::LowerMatrix< blaze::CompressedMatrix<TypeA> >; // Creator type definitions using CSLDa = blazetest::Creator<SLDa>; using CLCa = blazetest::Creator<LCa>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=LCa::maxNonZeros( i ); ++j ) { RUN_DMATSMATMULT_OPERATION_TEST( CSLDa( i ), CLCa( i, j ) ); } } // Running tests with large matrices RUN_DMATSMATMULT_OPERATION_TEST( CSLDa( 31UL ), CLCa( 31UL, 7UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CSLDa( 67UL ), CLCa( 67UL, 7UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CSLDa( 127UL ), CLCa( 127UL, 13UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CSLDa( 32UL ), CLCa( 32UL, 8UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CSLDa( 64UL ), CLCa( 64UL, 8UL ) ); RUN_DMATSMATMULT_OPERATION_TEST( CSLDa( 128UL ), CLCa( 128UL, 16UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
5ea44aab59075cfd254dd7f3ef8d9c087199f761
cc3b200a956e69279783d8f31e3a78fbf08ca13c
/src/rx/render/model.cpp
c2a34c9c7948c61792df67eb83a1aac9b68a6047
[ "MIT" ]
permissive
Moneyl/rex
14c94645085c77674b582644df92d5b34661bf61
0f7b3894862f66c71b2af2175b275a1d421b13a0
refs/heads/main
2023-02-02T17:20:58.283072
2020-12-25T20:53:05
2020-12-25T20:53:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,598
cpp
#include <stddef.h> // offsetof #include <string.h> // memcpy #include "rx/render/model.h" #include "rx/render/image_based_lighting.h" #include "rx/render/immediate3D.h" #include "rx/render/frontend/context.h" #include "rx/render/frontend/technique.h" #include "rx/render/frontend/target.h" #include "rx/render/frontend/buffer.h" #include "rx/render/frontend/arena.h" #include "rx/math/frustum.h" #include "rx/core/profiler.h" namespace Rx::Render { Model::Model(Frontend::Context* _frontend) : m_frontend{_frontend} , m_technique{m_frontend->find_technique_by_name("geometry")} , m_arena{nullptr} , m_materials{m_frontend->allocator()} , m_opaque_meshes{m_frontend->allocator()} , m_transparent_meshes{m_frontend->allocator()} , m_model{m_frontend->allocator().create<Rx::Model::Loader>(m_frontend->allocator())} { } Model::Model(Model&& model_) : m_frontend{Utility::exchange(model_.m_frontend, nullptr)} , m_technique{Utility::exchange(model_.m_technique, nullptr)} , m_arena{Utility::exchange(model_.m_arena, nullptr)} , m_block{Utility::move(model_.m_block)} , m_materials{Utility::move(model_.m_materials)} , m_opaque_meshes{Utility::move(model_.m_opaque_meshes)} , m_transparent_meshes{Utility::move(model_.m_transparent_meshes)} , m_model{Utility::exchange(model_.m_model, nullptr)} , m_animation{Utility::move(model_.m_animation)} , m_aabb{Utility::move(model_.m_aabb)} { } Model::~Model() { if (m_model) { m_frontend->allocator().destroy<Rx::Model::Loader>(m_model); } } bool Model::upload() { // Clear incase being called multiple times for model changes. m_materials.clear(); m_opaque_meshes.clear(); m_transparent_meshes.clear(); if (m_model->is_animated()) { using Vertex = Rx::Model::Loader::AnimatedVertex; Frontend::Buffer::Format format; format.record_type(Frontend::Buffer::Type::k_static); format.record_element_type(Frontend::Buffer::ElementType::k_u32); format.record_vertex_stride(sizeof(Vertex)); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec3f, offsetof(Vertex, position)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec3f, offsetof(Vertex, normal)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec4f, offsetof(Vertex, tangent)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec2f, offsetof(Vertex, coordinate)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec4b, offsetof(Vertex, blend_weights)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec4b, offsetof(Vertex, blend_indices)}); format.finalize(); m_arena = m_frontend->arena(format); m_block = m_arena; const auto &vertices = m_model->animated_vertices(); const auto size = vertices.size() * sizeof(Vertex); m_block.write_vertices(vertices.data(), size); m_block.record_vertices_edit(0, size); } else { using Vertex = Rx::Model::Loader::Vertex; Frontend::Buffer::Format format; format.record_type(Frontend::Buffer::Type::k_static); format.record_element_type(Frontend::Buffer::ElementType::k_u32); format.record_vertex_stride(sizeof(Vertex)); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec3f, offsetof(Vertex, position)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec3f, offsetof(Vertex, normal)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec4f, offsetof(Vertex, tangent)}); format.record_vertex_attribute({Frontend::Buffer::Attribute::Type::k_vec2f, offsetof(Vertex, coordinate)}); format.finalize(); m_arena = m_frontend->arena(format); m_block = m_arena; const auto &vertices = m_model->vertices(); const auto size = vertices.size() * sizeof(Vertex); m_block.write_vertices(vertices.data(), size); m_block.record_vertices_edit(0, size); } const auto &elements = m_model->elements(); const auto size = elements.size() * sizeof(Uint32); m_block.write_elements(elements.data(), size); m_block.record_elements_edit(0, size); m_frontend->update_buffer(RX_RENDER_TAG("Model"), m_arena->buffer()); m_materials.clear(); // Map all the loaded material::loader's to render::frontend::material's while // using indices to refer to them rather than strings. Map<String, Size> material_indices{m_frontend->allocator()}; const bool material_load_result = m_model->materials().each_pair([this, &material_indices](const String& _name, Material::Loader& material_) { Frontend::Material material{m_frontend}; if (material.load(Utility::move(material_))) { const Size material_index{m_materials.size()}; material_indices.insert(_name, material_index); m_materials.push_back(Utility::move(material)); return true; } return false; }); if (!material_load_result) { return false; } // Resolve all the meshes of the loaded model. m_model->meshes().each_fwd([this, &material_indices](const Rx::Model::Mesh& _mesh) { if (auto* find = material_indices.find(_mesh.material)) { if (m_materials[*find].has_alpha()) { m_transparent_meshes.push_back({_mesh.offset, _mesh.count, *find, _mesh.bounds}); } else { m_opaque_meshes.push_back({_mesh.offset, _mesh.count, *find, _mesh.bounds}); } } m_aabb.expand(_mesh.bounds); }); return true; } void Model::animate(Size _index, [[maybe_unused]] bool _loop) { if (_index != -1_z && m_model->is_animated()) { m_animation = {m_model, _index}; } else { m_animation = nullopt; } } void Model::update(Float32 _delta_time) { if (m_animation) { m_animation->update(_delta_time, true); } } void Model::render(Frontend::Target* _target, const Math::Mat4x4f& _model, const Math::Mat4x4f& _view, const Math::Mat4x4f& _projection) { Math::Frustum frustum{_view * _projection}; RX_PROFILE_CPU("model::render"); RX_PROFILE_GPU("model::render"); Frontend::State state; // Enable(DEPTH_TEST) state.depth.record_test(true); // Enable(CULL_FACE) state.cull.record_enable(true); // Disable(BLEND) state.blend.record_enable(false); // FrontFace(CW) state.cull.record_front_face(Frontend::CullState::FrontFaceType::k_clock_wise); // CullFace(BACK) state.cull.record_cull_face(Frontend::CullState::CullFaceType::k_back); // DepthMask(TRUE) state.depth.record_write(true); // Viewport(0, 0, w, h) state.viewport.record_dimensions(_target->dimensions()); auto draw = [&](const Mesh& _mesh, bool _allow_cull) { if (!frustum.is_aabb_inside(_mesh.bounds.transform(_model))) { return true; } RX_PROFILE_CPU("batch"); RX_PROFILE_GPU("batch"); const auto& material{m_materials[_mesh.material]}; Uint64 flags{0}; if (m_animation) flags |= 1 << 0; if (material.albedo()) flags |= 1 << 1; if (material.normal()) flags |= 1 << 2; if (material.metalness()) flags |= 1 << 3; if (material.roughness()) flags |= 1 << 4; if (material.alpha_test()) flags |= 1 << 5; if (material.ambient()) flags |= 1 << 6; if (material.emissive()) flags |= 1 << 7; Frontend::Program* program{m_technique->permute(flags)}; auto& uniforms{program->uniforms()}; uniforms[0].record_mat4x4f(_model); uniforms[1].record_mat4x4f(_view); uniforms[2].record_mat4x4f(_projection); if (const auto transform{material.transform()}) { uniforms[3].record_mat3x3f(transform->as_mat3()); } if (m_animation) { uniforms[4].record_bones(m_animation->frames(), m_animation->joints()); } uniforms[5].record_float(material.roughness_value()); uniforms[6].record_float(material.metalness_value()); uniforms[7].record_float(material.occlusion_value()); uniforms[8].record_vec3f(material.albedo_color()); uniforms[9].record_vec3f(material.emission_color()); // Record all the textures. Frontend::Textures draw_textures; if (material.albedo()) uniforms[10].record_sampler(draw_textures.add(material.albedo())); if (material.normal()) uniforms[11].record_sampler(draw_textures.add(material.normal())); if (material.metalness()) uniforms[12].record_sampler(draw_textures.add(material.metalness())); if (material.roughness()) uniforms[13].record_sampler(draw_textures.add(material.roughness())); if (material.ambient()) uniforms[14].record_sampler(draw_textures.add(material.ambient())); if (material.emissive()) uniforms[15].record_sampler(draw_textures.add(material.emissive())); // Record all the draw buffers. Frontend::Buffers draw_buffers; draw_buffers.add(0); // gbuffer albedo (albedo.r, albedo.g, albedo.b, ambient) draw_buffers.add(1); // gbuffer normal (normal.r, normal.g, roughness, metalness) draw_buffers.add(2); // gbuffer emission (emission.r, emission.g, emission.b, 0.0) // Disable backface culling for alpha-tested geometry. if (_allow_cull) { state.cull.record_enable(!material.alpha_test()); } else { state.cull.record_enable(false); } m_frontend->draw( RX_RENDER_TAG("model mesh"), state, _target, draw_buffers, m_arena->buffer(), program, _mesh.count, m_block.base_element() + _mesh.offset, 0, m_block.base_vertex(), m_block.base_instance(), Render::Frontend::PrimitiveType::TRIANGLES, draw_textures); return true; }; m_opaque_meshes.each_fwd([&](const Mesh& _mesh) { draw(_mesh, true); }); /* state.blend.record_enable(true); state.blend.record_blend_factors( Render::Frontend::BlendState::FactorType::k_src_alpha, Render::Frontend::BlendState::FactorType::k_one_minus_src_alpha);*/ m_transparent_meshes.each_fwd([&](const Mesh& _mesh) { draw(_mesh, true); }); } void Model::render_normals(const Math::Mat4x4f& _world, Render::Immediate3D* _immediate) { const auto scale = m_aabb.transform(_world).scale() * 0.25f; if (m_model->is_animated()) { m_model->animated_vertices().each_fwd([&](const Rx::Model::Loader::AnimatedVertex& _vertex) { const Math::Vec3f point_a{_vertex.position}; const Math::Vec3f point_b{_vertex.position + _vertex.normal * scale}; const Math::Vec3f color{_vertex.normal * 0.5f + 0.5f}; if (m_animation) { // CPU skeletal animation of the lines. const auto& frames{m_animation->frames()}; Math::Mat3x4f transform; transform = frames[_vertex.blend_indices.x] * (_vertex.blend_weights.x / 255.0f); transform += frames[_vertex.blend_indices.y] * (_vertex.blend_weights.y / 255.0f); transform += frames[_vertex.blend_indices.z] * (_vertex.blend_weights.z / 255.0f); transform += frames[_vertex.blend_indices.w] * (_vertex.blend_weights.w / 255.0f); const Math::Vec3f& x{transform.x.x, transform.y.x, transform.z.x}; const Math::Vec3f& y{transform.x.y, transform.y.y, transform.z.y}; const Math::Vec3f& z{transform.x.z, transform.y.z, transform.z.z}; const Math::Vec3f& w{transform.x.w, transform.y.w, transform.z.w}; const Math::Mat4x4f& mat{{x.x, x.y, x.z, 0.0f}, {y.x, y.y, y.z, 0.0f}, {z.x, z.y, z.z, 0.0f}, {w.x, w.y, w.z, 1.0f}}; _immediate->frame_queue().record_line( Math::Mat4x4f::transform_point(point_a, mat * _world), Math::Mat4x4f::transform_point(point_b, mat * _world), {color.r, color.g, color.b, 1.0f}, Immediate3D::k_depth_test | Immediate3D::k_depth_write); } else { _immediate->frame_queue().record_line( Math::Mat4x4f::transform_point(point_a, _world), Math::Mat4x4f::transform_point(point_b, _world), {color.r, color.g, color.b, 1.0f}, Immediate3D::k_depth_test | Immediate3D::k_depth_write); } }); } else { m_model->vertices().each_fwd([&](const Rx::Model::Loader::Vertex& _vertex) { const Math::Vec3f point_a{_vertex.position}; const Math::Vec3f point_b{_vertex.position + _vertex.normal * scale}; const Math::Vec3f color{_vertex.normal * 0.5f + 0.5f}; _immediate->frame_queue().record_line( Math::Mat4x4f::transform_point(point_a, _world), Math::Mat4x4f::transform_point(point_b, _world), {color.r, color.g, color.b, 1.0f}, Immediate3D::k_depth_test | Immediate3D::k_depth_write); }); } } void Model::render_skeleton(const Math::Mat4x4f& _world, Render::Immediate3D* _immediate) { if (!m_animation) { return; } const auto& joints = m_model->joints(); #if 0 // Render all the joints. for (Size i{0}; i < joints.size(); i++) { const Math::Mat3x4f& frame = m_animation->frames()[i] * joints[i].frame; const Math::Vec3f& x = Math::normalize({frame.x.x, frame.y.x, frame.z.x}); const Math::Vec3f& y = Math::normalize({frame.x.y, frame.y.y, frame.z.y}); const Math::Vec3f& z = Math::normalize({frame.x.z, frame.y.z, frame.z.z}); const Math::Vec3f& w{frame.x.w, frame.y.w, frame.z.w}; const Math::Mat4x4f& joint{{x.x, x.y, x.z, 0.0f}, {y.x, y.y, y.z, 0.0f}, {z.x, z.y, z.z, 0.0f}, {w.x, w.y, w.z, 1.0f}}; const auto scale = m_aabb.scale().max_element() * 0.01f; _immediate->frame_queue().record_solid_sphere( {16.0f, 16.0f}, {0.5f, 0.5f, 1.0f, 1.0f}, Math::Mat4x4f::scale({scale, scale, scale}) * joint * _world, 0); } #endif // Render the skeleton. for (Size i{0}; i < joints.size(); i++) { const Math::Mat3x4f& frame{m_animation->frames()[i] * joints[i].frame}; const Math::Vec3f& w{frame.x.w, frame.y.w, frame.z.w}; const Sint32 parent{joints[i].parent}; if (parent >= 0) { const Math::Mat3x4f& parent_joint{joints[parent].frame}; const Math::Mat3x4f& parent_frame{m_animation->frames()[parent] * parent_joint}; const Math::Vec3f& parent_position{parent_frame.x.w, parent_frame.y.w, parent_frame.z.w}; _immediate->frame_queue().record_line( Math::Mat4x4f::transform_point(w, _world), Math::Mat4x4f::transform_point(parent_position, _world), {0.5f, 0.5f, 1.0f, 1.0f}, 0); } } } } // namespace rx::render
[ "weilercdale@gmail.com" ]
weilercdale@gmail.com
d6490f8a095c3f88aad3c0a3b45f4b81b92e5f74
7ff2354c647253c9d63831d6c7b46100c05a7bb3
/win32/tinnysprite/ggtest/simplewin/WinTest.cpp
03d2c12ac7fde4715d4deae3af0e53a33fba072b
[]
no_license
Omgan/code4me
d28143c1aac5ff097cc50fab820c1a2706bc1eb7
19b2bd1a06780f29e93745a1dee89932a65b9c76
refs/heads/master
2020-12-28T21:06:36.220571
2013-06-19T02:20:14
2013-06-19T02:20:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,774
cpp
// WinTest.cpp : Defines the entry point for the application. // #include "stdafx.h" #include "WinTest.h" #include "..\simpledll\interface.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WINTEST, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WINTEST)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage are only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WINTEST)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WINTEST); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); SimpleDll* pSimpleDll = NULL; ::CreateInstance(pSimpleDll); if (pSimpleDll){ pSimpleDll->SimpleMethod(); } ::DestoryInstance(pSimpleDll); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "hikerlive@gmail.com" ]
hikerlive@gmail.com
818b85768726a30cbbf0545e7658cc7d996ac8c4
8726841917e4999289451334c356e97f966ee776
/C++/61 Rotate List.cpp
3c0f727ffc6ee061e34105047727ae208c2ca3b2
[]
no_license
weiho1122/LeetCode
cf890eaf3b8299897431564d811c52d1a95f6d94
ac986cb0ccba053afbb21b7fe6ec8fa5f767da5e
refs/heads/master
2021-01-11T02:04:40.560365
2016-09-13T00:09:04
2016-09-13T00:09:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
970
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) {//time O(N), space O(1), 12ms AC. if(head == NULL) return NULL; ListNode *ptr1 = head, *ptr2 = head, *result; k %= findLength(head); int count = 0; while(ptr2->next!=NULL){ ptr2 = ptr2->next; if(count == k){ ptr1 = ptr1->next; continue; } count ++; } ptr2->next = head; result = ptr1->next; ptr1->next = NULL; return result; } int findLength(ListNode* head){ int len = 1; ListNode* tmp = head; while(tmp->next != NULL) { tmp = tmp->next; len++; } return len; } };
[ "zhangweiqi357@gmail.com" ]
zhangweiqi357@gmail.com
67569b683e80ec2e5902c27c3b2c3e39d67eecd5
e0e7c6ec2a65ddcae2f40f33aaecdf2aca372577
/hackerrank/c++/classes/virtual-functions.cpp
73ae9da004f1ea9e25b19017b45fd772fccc912e
[ "MIT" ]
permissive
ParinVachhani/coding-practice
c77349f603634031d68e1a3df60bef6a7ae801fb
2268215b1e1f26bfe09d0dfb4f94366594a6ef37
refs/heads/master
2020-03-15T20:47:52.334115
2018-07-12T22:17:15
2018-07-12T22:17:15
132,341,183
2
0
null
null
null
null
UTF-8
C++
false
false
1,917
cpp
//Problem link - https://www.hackerrank.com/challenges/virtual-functions //Code author - Parin Vachhani - https://github.com/parinvachhani #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; class Person { public: int age; string name; virtual void getdata(){ cin >> name >> age; } virtual void putdata(){ cout << name << " " << age << endl; } }; class Professor : public Person { public: Professor(){ cur_id = ++id; } int publications; static int id; int cur_id; void getdata(){ cin >> name >> age >> publications; } void putdata(){ cout << name << " " << age << " " << publications << " " << cur_id << endl; } }; int Professor::id = 0; class Student : public Person { #define NUM_OF_SUBJECTS 6 public: Student() { cur_id = ++id; } int marks[NUM_OF_SUBJECTS]; static int id; int cur_id; void getdata(){ cin >> name >> age; for(int i=0; i<NUM_OF_SUBJECTS; i++){ cin >> marks[i]; } } void putdata(){ int totalMarks = 0; for(int i=0; i<NUM_OF_SUBJECTS; i++){ totalMarks += marks[i]; } cout << name << " " << age << " " << totalMarks << " " << cur_id << endl; } }; int Student::id = 0; int main(){ int n, val; cin>>n; //The number of objects that is going to be created. Person *per[n]; for(int i = 0;i < n;i++){ cin>>val; if(val == 1){ // If val is 1 current object is of type Professor per[i] = new Professor; } else per[i] = new Student; // Else the current object is of type Student per[i]->getdata(); // Get the data from the user. } for(int i=0;i<n;i++) per[i]->putdata(); // Print the required output for each object. return 0; }
[ "vachhaniparin@gmail.com" ]
vachhaniparin@gmail.com
97f114c6642592ae200984fb6038d74beb0c47da
1cc17e9f4c3b6fba21aef3af5e900c80cfa98051
/chrome/common/extensions/api/extension_api.cc
6d41b3f94adee7e612f9a3ff00e57ba5ca5590a3
[ "BSD-3-Clause" ]
permissive
sharpglasses/BitPop
2643a39b76ab71d1a2ed5b9840217b0e9817be06
1fae4ecfb965e163f6ce154b3988b3181678742a
refs/heads/master
2021-01-21T16:04:02.854428
2013-03-22T02:12:27
2013-03-22T02:12:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,891
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/api/extension_api.h" #include <algorithm> #include <string> #include <vector> #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/common/extensions/api/generated_schemas.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/features/simple_feature_provider.h" #include "chrome/common/extensions/permissions/permission_set.h" #include "googleurl/src/gurl.h" #include "grit/common_resources.h" #include "grit/extensions_api_resources.h" #include "ui/base/layout.h" #include "ui/base/resource/resource_bundle.h" using base::DictionaryValue; using base::ListValue; using base::Value; namespace extensions { using api::GeneratedSchemas; namespace { const char* kChildKinds[] = { "functions", "events" }; // Returns true if |dict| has an unprivileged "true" property. bool IsUnprivileged(const DictionaryValue* dict) { bool unprivileged = false; return dict->GetBoolean("unprivileged", &unprivileged) && unprivileged; } // Returns whether the list at |name_space_node|.|child_kind| contains any // children with an { "unprivileged": true } property. bool HasUnprivilegedChild(const DictionaryValue* name_space_node, const std::string& child_kind) { const ListValue* child_list = NULL; const DictionaryValue* child_dict = NULL; if (name_space_node->GetList(child_kind, &child_list)) { for (size_t i = 0; i < child_list->GetSize(); ++i) { const DictionaryValue* item = NULL; CHECK(child_list->GetDictionary(i, &item)); if (IsUnprivileged(item)) return true; } } else if (name_space_node->GetDictionary(child_kind, &child_dict)) { for (DictionaryValue::Iterator it(*child_dict); it.HasNext(); it.Advance()) { const DictionaryValue* item = NULL; CHECK(it.value().GetAsDictionary(&item)); if (IsUnprivileged(item)) return true; } } return false; } base::StringPiece ReadFromResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetRawDataResource( resource_id, ui::SCALE_FACTOR_NONE); } scoped_ptr<ListValue> LoadSchemaList(const std::string& name, const base::StringPiece& schema) { std::string error_message; scoped_ptr<Value> result( base::JSONReader::ReadAndReturnError( schema, base::JSON_PARSE_RFC | base::JSON_DETACHABLE_CHILDREN, // options NULL, // error code &error_message)); // Tracking down http://crbug.com/121424 char buf[128]; base::snprintf(buf, arraysize(buf), "%s: (%d) '%s'", name.c_str(), result.get() ? result->GetType() : -1, error_message.c_str()); CHECK(result.get()) << error_message << " for schema " << schema; CHECK(result->IsType(Value::TYPE_LIST)) << " for schema " << schema; return scoped_ptr<ListValue>(static_cast<ListValue*>(result.release())); } const DictionaryValue* FindListItem(const ListValue* list, const std::string& property_name, const std::string& property_value) { for (size_t i = 0; i < list->GetSize(); ++i) { const DictionaryValue* item = NULL; CHECK(list->GetDictionary(i, &item)) << property_value << "/" << property_name; std::string value; if (item->GetString(property_name, &value) && value == property_value) return item; } return NULL; } const DictionaryValue* GetSchemaChild(const DictionaryValue* schema_node, const std::string& child_name) { const DictionaryValue* child_node = NULL; for (size_t i = 0; i < arraysize(kChildKinds); ++i) { const ListValue* list_node = NULL; if (!schema_node->GetList(kChildKinds[i], &list_node)) continue; child_node = FindListItem(list_node, "name", child_name); if (child_node) return child_node; } return NULL; } struct Static { Static() : api(ExtensionAPI::CreateWithDefaultConfiguration()) { } scoped_ptr<ExtensionAPI> api; }; base::LazyInstance<Static> g_lazy_instance = LAZY_INSTANCE_INITIALIZER; // If it exists and does not already specify a namespace, then the value stored // with key |key| in |schema| will be updated to |schema_namespace| + "." + // |schema[key]|. void MaybePrefixFieldWithNamespace(const std::string& schema_namespace, DictionaryValue* schema, const std::string& key) { if (!schema->HasKey(key)) return; std::string old_id; CHECK(schema->GetString(key, &old_id)); if (old_id.find(".") == std::string::npos) schema->SetString(key, schema_namespace + "." + old_id); } // Modify all "$ref" keys anywhere in |schema| to be prefxied by // |schema_namespace| if they do not already specify a namespace. void PrefixRefsWithNamespace(const std::string& schema_namespace, Value* value) { if (value->IsType(Value::TYPE_LIST)) { ListValue* list; CHECK(value->GetAsList(&list)); for (ListValue::iterator i = list->begin(); i != list->end(); ++i) { PrefixRefsWithNamespace(schema_namespace, *i); } } else if (value->IsType(Value::TYPE_DICTIONARY)) { DictionaryValue* dict; CHECK(value->GetAsDictionary(&dict)); MaybePrefixFieldWithNamespace(schema_namespace, dict, "$ref"); for (DictionaryValue::key_iterator i = dict->begin_keys(); i != dict->end_keys(); ++i) { Value* next_value; CHECK(dict->GetWithoutPathExpansion(*i, &next_value)); PrefixRefsWithNamespace(schema_namespace, next_value); } } } // Modify all objects in the "types" section of the schema to be prefixed by // |schema_namespace| if they do not already specify a namespace. void PrefixTypesWithNamespace(const std::string& schema_namespace, DictionaryValue* schema) { if (!schema->HasKey("types")) return; // Add the namespace to all of the types defined in this schema ListValue *types; CHECK(schema->GetList("types", &types)); for (size_t i = 0; i < types->GetSize(); ++i) { DictionaryValue *type; CHECK(types->GetDictionary(i, &type)); MaybePrefixFieldWithNamespace(schema_namespace, type, "id"); MaybePrefixFieldWithNamespace(schema_namespace, type, "customBindings"); } } // Modify the schema so that all types are fully qualified. void PrefixWithNamespace(const std::string& schema_namespace, DictionaryValue* schema) { PrefixTypesWithNamespace(schema_namespace, schema); PrefixRefsWithNamespace(schema_namespace, schema); } } // namespace // static ExtensionAPI* ExtensionAPI::GetSharedInstance() { return g_lazy_instance.Get().api.get(); } // static ExtensionAPI* ExtensionAPI::CreateWithDefaultConfiguration() { ExtensionAPI* api = new ExtensionAPI(); api->InitDefaultConfiguration(); return api; } // static void ExtensionAPI::SplitDependencyName(const std::string& full_name, std::string* feature_type, std::string* feature_name) { size_t colon_index = full_name.find(':'); if (colon_index == std::string::npos) { // TODO(aa): Remove this code when all API descriptions have been updated. *feature_type = "api"; *feature_name = full_name; return; } *feature_type = full_name.substr(0, colon_index); *feature_name = full_name.substr(colon_index + 1); } void ExtensionAPI::LoadSchema(const std::string& name, const base::StringPiece& schema) { scoped_ptr<ListValue> schema_list(LoadSchemaList(name, schema)); std::string schema_namespace; while (!schema_list->empty()) { DictionaryValue* schema = NULL; { Value* value = NULL; schema_list->Remove(schema_list->GetSize() - 1, &value); CHECK(value->IsType(Value::TYPE_DICTIONARY)); schema = static_cast<DictionaryValue*>(value); } CHECK(schema->GetString("namespace", &schema_namespace)); PrefixWithNamespace(schema_namespace, schema); schemas_[schema_namespace] = make_linked_ptr(schema); CHECK_EQ(1u, unloaded_schemas_.erase(schema_namespace)); // Populate |{completely,partially}_unprivileged_apis_|. // // For "partially", only need to look at functions/events; even though // there are unprivileged properties (e.g. in extensions), access to those // never reaches C++ land. bool unprivileged = false; if (schema->GetBoolean("unprivileged", &unprivileged) && unprivileged) { completely_unprivileged_apis_.insert(schema_namespace); } else if (HasUnprivilegedChild(schema, "functions") || HasUnprivilegedChild(schema, "events") || HasUnprivilegedChild(schema, "properties")) { partially_unprivileged_apis_.insert(schema_namespace); } // Populate |url_matching_apis_|. ListValue* matches = NULL; if (schema->GetList("matches", &matches)) { URLPatternSet pattern_set; for (size_t i = 0; i < matches->GetSize(); ++i) { std::string pattern; CHECK(matches->GetString(i, &pattern)); pattern_set.AddPattern( URLPattern(UserScript::kValidUserScriptSchemes, pattern)); } url_matching_apis_[schema_namespace] = pattern_set; } // Populate feature maps. // TODO(aa): Consider not storing features that can never run on the current // machine (e.g., because of platform restrictions). bool uses_feature_system = false; schema->GetBoolean("uses_feature_system", &uses_feature_system); if (!uses_feature_system) continue; Feature* feature = new Feature(); feature->set_name(schema_namespace); feature->Parse(schema); FeatureMap* schema_features = new FeatureMap(); CHECK(features_.insert( std::make_pair(schema_namespace, make_linked_ptr(schema_features))).second); CHECK(schema_features->insert( std::make_pair("", make_linked_ptr(feature))).second); for (size_t i = 0; i < arraysize(kChildKinds); ++i) { ListValue* child_list = NULL; schema->GetList(kChildKinds[i], &child_list); if (!child_list) continue; for (size_t j = 0; j < child_list->GetSize(); ++j) { DictionaryValue* child = NULL; CHECK(child_list->GetDictionary(j, &child)); scoped_ptr<Feature> child_feature(new Feature(*feature)); child_feature->Parse(child); if (child_feature->Equals(*feature)) continue; // no need to store no-op features std::string child_name; CHECK(child->GetString("name", &child_name)); child_feature->set_name(schema_namespace + "." + child_name); CHECK(schema_features->insert( std::make_pair(child_name, make_linked_ptr(child_feature.release()))).second); } } } } ExtensionAPI::ExtensionAPI() { RegisterDependencyProvider("api", this); // TODO(aa): Can remove this when all JSON files are converted. RegisterDependencyProvider("", this); } ExtensionAPI::~ExtensionAPI() { } void ExtensionAPI::InitDefaultConfiguration() { RegisterDependencyProvider( "manifest", SimpleFeatureProvider::GetManifestFeatures()); RegisterDependencyProvider( "permission", SimpleFeatureProvider::GetPermissionFeatures()); // Schemas to be loaded from resources. CHECK(unloaded_schemas_.empty()); RegisterSchema("app", ReadFromResource( IDR_EXTENSION_API_JSON_APP)); RegisterSchema("bitpop", ReadFromResource( IDR_EXTENSION_API_JSON_BITPOP)); RegisterSchema("bitpop.facebookChat", ReadFromResource( IDR_EXTENSION_API_JSON_BITPOP_FACEBOOK_CHAT)); RegisterSchema("bookmarks", ReadFromResource( IDR_EXTENSION_API_JSON_BOOKMARKS)); RegisterSchema("browserAction", ReadFromResource( IDR_EXTENSION_API_JSON_BROWSERACTION)); RegisterSchema("browsingData", ReadFromResource( IDR_EXTENSION_API_JSON_BROWSINGDATA)); RegisterSchema("chromeosInfoPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_CHROMEOSINFOPRIVATE)); RegisterSchema("cloudPrintPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_CLOUDPRINTPRIVATE)); RegisterSchema("contentSettings", ReadFromResource( IDR_EXTENSION_API_JSON_CONTENTSETTINGS)); RegisterSchema("contextMenus", ReadFromResource( IDR_EXTENSION_API_JSON_CONTEXTMENUS)); RegisterSchema("cookies", ReadFromResource( IDR_EXTENSION_API_JSON_COOKIES)); RegisterSchema("debugger", ReadFromResource( IDR_EXTENSION_API_JSON_DEBUGGER)); RegisterSchema("declarativeWebRequest", ReadFromResource( IDR_EXTENSION_API_JSON_DECLARATIVE_WEBREQUEST)); RegisterSchema("devtools", ReadFromResource( IDR_EXTENSION_API_JSON_DEVTOOLS)); RegisterSchema("events", ReadFromResource( IDR_EXTENSION_API_JSON_EVENTS)); RegisterSchema("experimental.accessibility", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_ACCESSIBILITY)); RegisterSchema("experimental.app", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_APP)); RegisterSchema("experimental.bookmarkManager", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_BOOKMARKMANAGER)); RegisterSchema("experimental.commands", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_COMMANDS)); RegisterSchema("experimental.infobars", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_INFOBARS)); RegisterSchema("experimental.input.virtualKeyboard", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_INPUT_VIRTUALKEYBOARD)); RegisterSchema("experimental.offscreenTabs", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_OFFSCREENTABS)); RegisterSchema("experimental.processes", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_PROCESSES)); RegisterSchema("experimental.record", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_RECORD)); RegisterSchema("experimental.rlz", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_RLZ)); RegisterSchema("runtime", ReadFromResource( IDR_EXTENSION_API_JSON_RUNTIME)); RegisterSchema("experimental.speechInput", ReadFromResource( IDR_EXTENSION_API_JSON_EXPERIMENTAL_SPEECHINPUT)); RegisterSchema("extension", ReadFromResource( IDR_EXTENSION_API_JSON_EXTENSION)); RegisterSchema("fileBrowserHandler", ReadFromResource( IDR_EXTENSION_API_JSON_FILEBROWSERHANDLER)); RegisterSchema("fileBrowserHandlerInternal", ReadFromResource( IDR_EXTENSION_API_JSON_FILEBROWSERHANDLERINTERNAL)); RegisterSchema("fileBrowserPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_FILEBROWSERPRIVATE)); RegisterSchema("fontSettings", ReadFromResource( IDR_EXTENSION_API_JSON_FONTSSETTINGS)); RegisterSchema("history", ReadFromResource( IDR_EXTENSION_API_JSON_HISTORY)); RegisterSchema("i18n", ReadFromResource( IDR_EXTENSION_API_JSON_I18N)); RegisterSchema("idle", ReadFromResource( IDR_EXTENSION_API_JSON_IDLE)); RegisterSchema("input.ime", ReadFromResource( IDR_EXTENSION_API_JSON_INPUT_IME)); RegisterSchema("inputMethodPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_INPUTMETHODPRIVATE)); RegisterSchema("managedModePrivate", ReadFromResource( IDR_EXTENSION_API_JSON_MANAGEDMODEPRIVATE)); RegisterSchema("management", ReadFromResource( IDR_EXTENSION_API_JSON_MANAGEMENT)); RegisterSchema("mediaPlayerPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_MEDIAPLAYERPRIVATE)); RegisterSchema("metricsPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_METRICSPRIVATE)); RegisterSchema("echoPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_ECHOPRIVATE)); RegisterSchema("omnibox", ReadFromResource( IDR_EXTENSION_API_JSON_OMNIBOX)); RegisterSchema("pageAction", ReadFromResource( IDR_EXTENSION_API_JSON_PAGEACTION)); RegisterSchema("pageActions", ReadFromResource( IDR_EXTENSION_API_JSON_PAGEACTIONS)); RegisterSchema("pageCapture", ReadFromResource( IDR_EXTENSION_API_JSON_PAGECAPTURE)); RegisterSchema("permissions", ReadFromResource( IDR_EXTENSION_API_JSON_PERMISSIONS)); RegisterSchema("privacy", ReadFromResource( IDR_EXTENSION_API_JSON_PRIVACY)); RegisterSchema("proxy", ReadFromResource( IDR_EXTENSION_API_JSON_PROXY)); RegisterSchema("scriptBadge", ReadFromResource( IDR_EXTENSION_API_JSON_SCRIPTBADGE)); RegisterSchema("storage", ReadFromResource( IDR_EXTENSION_API_JSON_STORAGE)); RegisterSchema("systemPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_SYSTEMPRIVATE)); RegisterSchema("tabs", ReadFromResource( IDR_EXTENSION_API_JSON_TABS)); RegisterSchema("terminalPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_TERMINALPRIVATE)); RegisterSchema("test", ReadFromResource( IDR_EXTENSION_API_JSON_TEST)); RegisterSchema("topSites", ReadFromResource( IDR_EXTENSION_API_JSON_TOPSITES)); RegisterSchema("ttsEngine", ReadFromResource( IDR_EXTENSION_API_JSON_TTSENGINE)); RegisterSchema("tts", ReadFromResource( IDR_EXTENSION_API_JSON_TTS)); RegisterSchema("types", ReadFromResource( IDR_EXTENSION_API_JSON_TYPES)); RegisterSchema("wallpaperPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_WALLPAPERPRIVATE)); RegisterSchema("webNavigation", ReadFromResource( IDR_EXTENSION_API_JSON_WEBNAVIGATION)); RegisterSchema("webRequest", ReadFromResource( IDR_EXTENSION_API_JSON_WEBREQUEST)); RegisterSchema("webRequestInternal", ReadFromResource( IDR_EXTENSION_API_JSON_WEBREQUESTINTERNAL)); RegisterSchema("webSocketProxyPrivate", ReadFromResource( IDR_EXTENSION_API_JSON_WEBSOCKETPROXYPRIVATE)); RegisterSchema("webstore", ReadFromResource( IDR_EXTENSION_API_JSON_WEBSTORE)); RegisterSchema("webstorePrivate", ReadFromResource( IDR_EXTENSION_API_JSON_WEBSTOREPRIVATE)); RegisterSchema("windows", ReadFromResource( IDR_EXTENSION_API_JSON_WINDOWS)); // Schemas to be loaded via JSON generated from IDL files. GeneratedSchemas::Get(&unloaded_schemas_); } void ExtensionAPI::RegisterSchema(const std::string& name, const base::StringPiece& source) { unloaded_schemas_[name] = source; } void ExtensionAPI::RegisterDependencyProvider(const std::string& name, FeatureProvider* provider) { dependency_providers_[name] = provider; } bool ExtensionAPI::IsAvailable(const std::string& full_name, const Extension* extension, Feature::Context context) { std::set<std::string> dependency_names; dependency_names.insert(full_name); ResolveDependencies(&dependency_names); for (std::set<std::string>::iterator iter = dependency_names.begin(); iter != dependency_names.end(); ++iter) { Feature* feature = GetFeatureDependency(full_name); CHECK(feature) << *iter; Feature::Availability availability = feature->IsAvailableToContext(extension, context); if (availability != Feature::IS_AVAILABLE) return false; } return true; } bool ExtensionAPI::IsPrivileged(const std::string& full_name) { std::string child_name; std::string api_name = GetAPINameFromFullName(full_name, &child_name); // First try to use the feature system. Feature* feature(GetFeature(full_name)); if (feature) { // An API is 'privileged' if it or any of its dependencies can only be run // in a blessed context. std::set<std::string> resolved_dependencies; resolved_dependencies.insert(full_name); ResolveDependencies(&resolved_dependencies); for (std::set<std::string>::iterator iter = resolved_dependencies.begin(); iter != resolved_dependencies.end(); ++iter) { Feature* dependency = GetFeatureDependency(*iter); for (std::set<Feature::Context>::iterator context = dependency->contexts()->begin(); context != dependency->contexts()->end(); ++context) { if (*context != Feature::BLESSED_EXTENSION_CONTEXT) return false; } } return true; } // If this API hasn't been converted yet, fall back to the old system. if (completely_unprivileged_apis_.count(api_name)) return false; const DictionaryValue* schema = GetSchema(api_name); if (partially_unprivileged_apis_.count(api_name)) return IsChildNamePrivileged(schema, child_name); return true; } bool ExtensionAPI::IsChildNamePrivileged(const DictionaryValue* name_space_node, const std::string& child_name) { bool unprivileged = false; const DictionaryValue* child = GetSchemaChild(name_space_node, child_name); if (!child || !child->GetBoolean("unprivileged", &unprivileged)) return true; return !unprivileged; } const DictionaryValue* ExtensionAPI::GetSchema(const std::string& full_name) { std::string child_name; std::string api_name = GetAPINameFromFullName(full_name, &child_name); const DictionaryValue* result = NULL; SchemaMap::iterator maybe_schema = schemas_.find(api_name); if (maybe_schema != schemas_.end()) { result = maybe_schema->second.get(); } else { // Might not have loaded yet; or might just not exist. std::map<std::string, base::StringPiece>::iterator maybe_schema_resource = unloaded_schemas_.find(api_name); if (maybe_schema_resource == unloaded_schemas_.end()) return NULL; LoadSchema(maybe_schema_resource->first, maybe_schema_resource->second); maybe_schema = schemas_.find(api_name); CHECK(schemas_.end() != maybe_schema); result = maybe_schema->second.get(); } if (!child_name.empty()) result = GetSchemaChild(result, child_name); return result; } namespace { bool IsFeatureAllowedForExtension(const std::string& feature, const extensions::Extension& extension) { if (extension.is_platform_app() && (feature == "app" || feature == "extension")) return false; return true; } // Removes APIs from |apis| that should not be allowed for |extension|. // TODO(kalman/asargent) - Make it possible to specify these rules // declaratively. void RemoveDisallowedAPIs(const Extension& extension, std::set<std::string>* apis) { CHECK(apis); std::set<std::string>::iterator i = apis->begin(); while (i != apis->end()) { if (!IsFeatureAllowedForExtension(*i, extension)) { apis->erase(i++); } else { ++i; } } } } // namespace scoped_ptr<std::set<std::string> > ExtensionAPI::GetAPIsForContext( Feature::Context context, const Extension* extension, const GURL& url) { // We're forced to load all schemas now because we need to know the metadata // about every API -- and the metadata is stored in the schemas themselves. // This is a shame. // TODO(aa/kalman): store metadata in a separate file and don't load all // schemas. LoadAllSchemas(); std::set<std::string> temp_result; // First handle all the APIs that have been converted to the feature system. if (extension) { for (APIFeatureMap::iterator iter = features_.begin(); iter != features_.end(); ++iter) { if (IsAvailable(iter->first, extension, context)) temp_result.insert(iter->first); } } // Second, fall back to the old way. // TODO(aa): Remove this when all APIs have been converted. switch (context) { case Feature::UNSPECIFIED_CONTEXT: break; case Feature::BLESSED_EXTENSION_CONTEXT: if (extension) { // Availability is determined by the permissions of the extension. GetAllowedAPIs(extension, &temp_result); ResolveDependencies(&temp_result); RemoveDisallowedAPIs(*extension, &temp_result); } break; case Feature::UNBLESSED_EXTENSION_CONTEXT: case Feature::CONTENT_SCRIPT_CONTEXT: if (extension) { // Same as BLESSED_EXTENSION_CONTEXT, but only those APIs that are // unprivileged. GetAllowedAPIs(extension, &temp_result); // Resolving dependencies before removing unprivileged APIs means that // some unprivileged APIs may have unrealised dependencies. Too bad! ResolveDependencies(&temp_result); RemovePrivilegedAPIs(&temp_result); } break; case Feature::WEB_PAGE_CONTEXT: if (url.is_valid()) { // Availablility is determined by the url. GetAPIsMatchingURL(url, &temp_result); } break; } // Filter out all non-API features and remove the feature type part of the // name. scoped_ptr<std::set<std::string> > result(new std::set<std::string>()); for (std::set<std::string>::iterator iter = temp_result.begin(); iter != temp_result.end(); ++iter) { std::string feature_type; std::string feature_name; SplitDependencyName(*iter, &feature_type, &feature_name); if (feature_type == "api") result->insert(feature_name); } return result.Pass(); } Feature* ExtensionAPI::GetFeature(const std::string& full_name) { // Ensure it's loaded. GetSchema(full_name); std::string child_name; std::string api_namespace = GetAPINameFromFullName(full_name, &child_name); APIFeatureMap::iterator feature_map = features_.find(api_namespace); if (feature_map == features_.end()) return NULL; Feature* result = NULL; FeatureMap::iterator child_feature = feature_map->second->find(child_name); if (child_feature != feature_map->second->end()) { result = child_feature->second.get(); } else { FeatureMap::iterator parent_feature = feature_map->second->find(""); CHECK(parent_feature != feature_map->second->end()); result = parent_feature->second.get(); } if (result->contexts()->empty()) { LOG(ERROR) << "API feature '" << full_name << "' must specify at least one context."; return NULL; } return result; } Feature* ExtensionAPI::GetFeatureDependency(const std::string& full_name) { std::string feature_type; std::string feature_name; SplitDependencyName(full_name, &feature_type, &feature_name); FeatureProviderMap::iterator provider = dependency_providers_.find(feature_type); CHECK(provider != dependency_providers_.end()) << full_name; Feature* feature = provider->second->GetFeature(feature_name); CHECK(feature) << full_name; return feature; } std::string ExtensionAPI::GetAPINameFromFullName(const std::string& full_name, std::string* child_name) { std::string api_name_candidate = full_name; while (true) { if (features_.find(api_name_candidate) != features_.end() || schemas_.find(api_name_candidate) != schemas_.end() || unloaded_schemas_.find(api_name_candidate) != unloaded_schemas_.end()) { std::string result = api_name_candidate; if (child_name) { if (result.length() < full_name.length()) *child_name = full_name.substr(result.length() + 1); else *child_name = ""; } return result; } size_t last_dot_index = api_name_candidate.rfind('.'); if (last_dot_index == std::string::npos) break; api_name_candidate = api_name_candidate.substr(0, last_dot_index); } *child_name = ""; return ""; } void ExtensionAPI::GetAllowedAPIs( const Extension* extension, std::set<std::string>* out) { for (SchemaMap::const_iterator i = schemas_.begin(); i != schemas_.end(); ++i) { if (features_.find(i->first) != features_.end()) { // This API is controlled by the feature system. Nothing to do here. continue; } if (extension->required_permission_set()->HasAnyAccessToAPI(i->first) || extension->optional_permission_set()->HasAnyAccessToAPI(i->first)) { out->insert(i->first); } } } void ExtensionAPI::ResolveDependencies(std::set<std::string>* out) { std::set<std::string> missing_dependencies; for (std::set<std::string>::iterator i = out->begin(); i != out->end(); ++i) GetMissingDependencies(*i, *out, &missing_dependencies); while (missing_dependencies.size()) { std::string next = *missing_dependencies.begin(); missing_dependencies.erase(next); out->insert(next); GetMissingDependencies(next, *out, &missing_dependencies); } } void ExtensionAPI::GetMissingDependencies( const std::string& api_name, const std::set<std::string>& excluding, std::set<std::string>* out) { std::string feature_type; std::string feature_name; SplitDependencyName(api_name, &feature_type, &feature_name); // Only API features can have dependencies for now. if (feature_type != "api") return; const DictionaryValue* schema = GetSchema(feature_name); CHECK(schema) << "Schema for " << feature_name << " not found"; const ListValue* dependencies = NULL; if (!schema->GetList("dependencies", &dependencies)) return; for (size_t i = 0; i < dependencies->GetSize(); ++i) { std::string dependency_name; if (dependencies->GetString(i, &dependency_name) && !excluding.count(dependency_name)) { out->insert(dependency_name); } } } void ExtensionAPI::RemovePrivilegedAPIs(std::set<std::string>* apis) { std::set<std::string> privileged_apis; for (std::set<std::string>::iterator i = apis->begin(); i != apis->end(); ++i) { if (!completely_unprivileged_apis_.count(*i) && !partially_unprivileged_apis_.count(*i)) { privileged_apis.insert(*i); } } for (std::set<std::string>::iterator i = privileged_apis.begin(); i != privileged_apis.end(); ++i) { apis->erase(*i); } } void ExtensionAPI::GetAPIsMatchingURL(const GURL& url, std::set<std::string>* out) { for (std::map<std::string, URLPatternSet>::const_iterator i = url_matching_apis_.begin(); i != url_matching_apis_.end(); ++i) { if (features_.find(i->first) != features_.end()) { // This API is controlled by the feature system. Nothing to do. continue; } if (i->second.MatchesURL(url)) out->insert(i->first); } } void ExtensionAPI::LoadAllSchemas() { while (unloaded_schemas_.size()) { std::map<std::string, base::StringPiece>::iterator it = unloaded_schemas_.begin(); LoadSchema(it->first, it->second); } } } // namespace extensions
[ "vgachkaylo@crystalnix.com" ]
vgachkaylo@crystalnix.com
264e2d09aa9c5bd71a61eca33e3394cc3b21e1a8
4f9ba865d38cd4079f8d50ab1d0646ff651c060d
/ddnsloop.h
b0f446cd450c4824191ec9368e9ac2f72c518b7b
[]
no_license
ink19/ddns_qt
e05963fca75e7ecccfe60bc75007e023b72bf09b
b63812bb99abbd011621ff15d77ac160aba5a3fe
refs/heads/master
2020-08-05T13:51:51.655619
2019-11-04T08:35:52
2019-11-04T08:35:52
212,567,782
0
0
null
null
null
null
UTF-8
C++
false
false
562
h
#ifndef DDNSLOOP_H #define DDNSLOOP_H #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QThread> #include "ddnssetting.h" #include <QObject> #include <QNetworkInterface> #include <QDebug> class DDnsLoop: public QThread { Q_OBJECT public: DDnsLoop(DDnsSetting *setting); DDnsSetting *setting; int stop_run = 1; QString IPAdress = "127.0.0.1"; QString getHostIP(); signals: void postdata(); protected: void run() override; QNetworkAccessManager* naManager; }; #endif // DDNSLOOP_H
[ "ink19@qq.com" ]
ink19@qq.com
7ed54e1a26588fe8fe9b1bafe4bb190b02670669
8bcbb1cb5ed7af3c1d4da4588da8814fab358ff1
/Colors/ColorRGB.hpp
517633806fb919ecfe2110b89c92f720102ac38f
[]
no_license
viltit/VulkanRenderer
9c5eef02706fccbf4aadf8f90d071aa454684500
e4befcab81ee33a859102bd55809695ebf20c0e0
refs/heads/master
2020-11-30T22:08:09.629687
2020-09-07T17:28:21
2020-09-07T17:28:21
230,491,078
0
0
null
null
null
null
UTF-8
C++
false
false
338
hpp
#pragma once namespace moe { struct ColorRGB { ColorRGB(float r, float g, float b) : r{r}, g{g}, b{b} {} ColorRGB() : r{0}, g{0}, b{0} {} float r; float g; float b; static ColorRGB black() { return ColorRGB{ 0, 0, 0 }; } static ColorRGB white() { return ColorRGB{ 1, 1, 1 };} }; }
[ "villiger.titus@bluewin.ch" ]
villiger.titus@bluewin.ch
28caf13e0f4bd43c19ec76e69c9fb1a1c7aea473
ab0b60a1426754e8e22ee5541b54e20675816541
/BatteryCollector/Intermediate/Build/Win64/UE4Editor/Inc/BatteryCollector/SpawnVolume.gen.cpp
a41febba127eb27f12350b56e5405bceda53af0a
[]
no_license
RikuH/GameProgrammingNow
33a6809057fe51c859130041720cc858a4b86e88
5125a322f0cedf8b090eb355ee824928a857aa82
refs/heads/master
2022-03-24T00:01:19.176664
2019-11-28T08:24:25
2019-11-28T08:24:25
223,348,681
0
0
null
null
null
null
UTF-8
C++
false
false
15,700
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "BatteryCollector/SpawnVolume.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeSpawnVolume() {} // Cross Module References BATTERYCOLLECTOR_API UClass* Z_Construct_UClass_ASpawnVolume_NoRegister(); BATTERYCOLLECTOR_API UClass* Z_Construct_UClass_ASpawnVolume(); ENGINE_API UClass* Z_Construct_UClass_AActor(); UPackage* Z_Construct_UPackage__Script_BatteryCollector(); BATTERYCOLLECTOR_API UFunction* Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume(); COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FVector(); BATTERYCOLLECTOR_API UFunction* Z_Construct_UFunction_ASpawnVolume_SetSpawningActive(); ENGINE_API UClass* Z_Construct_UClass_UBoxComponent_NoRegister(); COREUOBJECT_API UClass* Z_Construct_UClass_UClass(); BATTERYCOLLECTOR_API UClass* Z_Construct_UClass_APickup_NoRegister(); // End Cross Module References void ASpawnVolume::StaticRegisterNativesASpawnVolume() { UClass* Class = ASpawnVolume::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "GetRandomPointInVolume", &ASpawnVolume::execGetRandomPointInVolume }, { "SetSpawningActive", &ASpawnVolume::execSetSpawningActive }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics { struct SpawnVolume_eventGetRandomPointInVolume_Parms { FVector ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(SpawnVolume_eventGetRandomPointInVolume_Parms, ReturnValue), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::Function_MetaDataParams[] = { { "Category", "Spawning" }, { "ModuleRelativePath", "SpawnVolume.h" }, { "ToolTip", "Find a random point within the BoxComponent" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ASpawnVolume, nullptr, "GetRandomPointInVolume", sizeof(SpawnVolume_eventGetRandomPointInVolume_Parms), Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x14820401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics { struct SpawnVolume_eventSetSpawningActive_Parms { bool bShouldSpawn; }; static void NewProp_bShouldSpawn_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bShouldSpawn; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::NewProp_bShouldSpawn_SetBit(void* Obj) { ((SpawnVolume_eventSetSpawningActive_Parms*)Obj)->bShouldSpawn = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::NewProp_bShouldSpawn = { "bShouldSpawn", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(SpawnVolume_eventSetSpawningActive_Parms), &Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::NewProp_bShouldSpawn_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::NewProp_bShouldSpawn, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::Function_MetaDataParams[] = { { "Category", "Spawning" }, { "ModuleRelativePath", "SpawnVolume.h" }, { "ToolTip", "This function toggles wheter or not the spawn volume spawn pickups" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ASpawnVolume, nullptr, "SetSpawningActive", sizeof(SpawnVolume_eventSetSpawningActive_Parms), Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ASpawnVolume_SetSpawningActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ASpawnVolume_SetSpawningActive_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_ASpawnVolume_NoRegister() { return ASpawnVolume::StaticClass(); } struct Z_Construct_UClass_ASpawnVolume_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_WhereToSpawn_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_WhereToSpawn; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SpawnDelayRangeHigh_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_SpawnDelayRangeHigh; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_SpawnDelayRangeLow_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_SpawnDelayRangeLow; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_EvilBatteryToSpawn_MetaData[]; #endif static const UE4CodeGen_Private::FClassPropertyParams NewProp_EvilBatteryToSpawn; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BatteryToSpawn_MetaData[]; #endif static const UE4CodeGen_Private::FClassPropertyParams NewProp_BatteryToSpawn; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_ASpawnVolume_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AActor, (UObject* (*)())Z_Construct_UPackage__Script_BatteryCollector, }; const FClassFunctionLinkInfo Z_Construct_UClass_ASpawnVolume_Statics::FuncInfo[] = { { &Z_Construct_UFunction_ASpawnVolume_GetRandomPointInVolume, "GetRandomPointInVolume" }, // 203629175 { &Z_Construct_UFunction_ASpawnVolume_SetSpawningActive, "SetSpawningActive" }, // 4016594340 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASpawnVolume_Statics::Class_MetaDataParams[] = { { "IncludePath", "SpawnVolume.h" }, { "ModuleRelativePath", "SpawnVolume.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASpawnVolume_Statics::NewProp_WhereToSpawn_MetaData[] = { { "AllowPrivateAccess", "true" }, { "Category", "Spawning" }, { "EditInline", "true" }, { "ModuleRelativePath", "SpawnVolume.h" }, { "ToolTip", "Box compnent to specify where pickups should be spawn" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_ASpawnVolume_Statics::NewProp_WhereToSpawn = { "WhereToSpawn", nullptr, (EPropertyFlags)0x00400000000a001d, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ASpawnVolume, WhereToSpawn), Z_Construct_UClass_UBoxComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_WhereToSpawn_MetaData, ARRAY_COUNT(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_WhereToSpawn_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeHigh_MetaData[] = { { "Category", "Spawning" }, { "ModuleRelativePath", "SpawnVolume.h" }, { "ToolTip", "Maximum spawn delay" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeHigh = { "SpawnDelayRangeHigh", nullptr, (EPropertyFlags)0x0020080000000015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ASpawnVolume, SpawnDelayRangeHigh), METADATA_PARAMS(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeHigh_MetaData, ARRAY_COUNT(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeHigh_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeLow_MetaData[] = { { "Category", "Spawning" }, { "ModuleRelativePath", "SpawnVolume.h" }, { "ToolTip", "Minimum spawn delay" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeLow = { "SpawnDelayRangeLow", nullptr, (EPropertyFlags)0x0020080000000015, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ASpawnVolume, SpawnDelayRangeLow), METADATA_PARAMS(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeLow_MetaData, ARRAY_COUNT(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeLow_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASpawnVolume_Statics::NewProp_EvilBatteryToSpawn_MetaData[] = { { "Category", "Spawning" }, { "ModuleRelativePath", "SpawnVolume.h" }, }; #endif const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_ASpawnVolume_Statics::NewProp_EvilBatteryToSpawn = { "EvilBatteryToSpawn", nullptr, (EPropertyFlags)0x0024080000000001, UE4CodeGen_Private::EPropertyGenFlags::Class, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ASpawnVolume, EvilBatteryToSpawn), Z_Construct_UClass_APickup_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_EvilBatteryToSpawn_MetaData, ARRAY_COUNT(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_EvilBatteryToSpawn_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ASpawnVolume_Statics::NewProp_BatteryToSpawn_MetaData[] = { { "Category", "Spawning" }, { "ModuleRelativePath", "SpawnVolume.h" }, { "ToolTip", "The Pickup to dvsdv" }, }; #endif const UE4CodeGen_Private::FClassPropertyParams Z_Construct_UClass_ASpawnVolume_Statics::NewProp_BatteryToSpawn = { "BatteryToSpawn", nullptr, (EPropertyFlags)0x0024080000000001, UE4CodeGen_Private::EPropertyGenFlags::Class, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(ASpawnVolume, BatteryToSpawn), Z_Construct_UClass_APickup_NoRegister, Z_Construct_UClass_UClass, METADATA_PARAMS(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_BatteryToSpawn_MetaData, ARRAY_COUNT(Z_Construct_UClass_ASpawnVolume_Statics::NewProp_BatteryToSpawn_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_ASpawnVolume_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ASpawnVolume_Statics::NewProp_WhereToSpawn, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeHigh, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ASpawnVolume_Statics::NewProp_SpawnDelayRangeLow, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ASpawnVolume_Statics::NewProp_EvilBatteryToSpawn, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ASpawnVolume_Statics::NewProp_BatteryToSpawn, }; const FCppClassTypeInfoStatic Z_Construct_UClass_ASpawnVolume_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<ASpawnVolume>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_ASpawnVolume_Statics::ClassParams = { &ASpawnVolume::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, Z_Construct_UClass_ASpawnVolume_Statics::PropPointers, nullptr, ARRAY_COUNT(DependentSingletons), ARRAY_COUNT(FuncInfo), ARRAY_COUNT(Z_Construct_UClass_ASpawnVolume_Statics::PropPointers), 0, 0x009000A0u, METADATA_PARAMS(Z_Construct_UClass_ASpawnVolume_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_ASpawnVolume_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_ASpawnVolume() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_ASpawnVolume_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(ASpawnVolume, 665649597); template<> BATTERYCOLLECTOR_API UClass* StaticClass<ASpawnVolume>() { return ASpawnVolume::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_ASpawnVolume(Z_Construct_UClass_ASpawnVolume, &ASpawnVolume::StaticClass, TEXT("/Script/BatteryCollector"), TEXT("ASpawnVolume"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(ASpawnVolume); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
[ "riku_hei@hotmail.com" ]
riku_hei@hotmail.com
5240156bf7a2fbf5dd6ee139b496c630a8079e0d
41575c498b7197e97b12a8ce2a880047df363cc3
/src/local/phys/Node.hpp
f5d875b3df4c920e2a4674a7219d54febe423741
[]
no_license
gongfuPanada/page
f00a6f9015b4aad79398f0df041613ab28be405b
fa2ccdef4b33480c2ac5f872d717323f45618a34
refs/heads/master
2021-01-15T22:09:34.836791
2013-03-23T18:54:13
2013-03-23T18:54:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,692
hpp
/** * @section license * * Copyright (c) 2006-2013 David Osborn * * Permission is granted to use and redistribute this software in source and * binary form, with or without modification, subject to the following * conditions: * * 1. Redistributions in source form must retain the above copyright notice, * this list of conditions, and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions, and the following disclaimer in the documentation * and/or other materials provided with the distribution, and in the same * place and form as other copyright, license, and disclaimer information. * * As a special exception, distributions of derivative works in binary form may * include an acknowledgement in place of the above copyright notice, this list * of conditions, and the following disclaimer in the documentation and/or other * materials provided with the distribution, and in the same place and form as * other acknowledgements, similar in substance to the following: * * Portions of this software are based on the work of David Osborn. * * This software is provided "as is", without any express or implied warranty. * In no event will the authors be liable for any damages arising out of the use * of this software. */ #ifndef page_local_phys_Node_hpp # define page_local_phys_Node_hpp # include "../math/Aabb.hpp" namespace page { namespace phys { struct Node { explicit Node(const math::Aabb<> & = math::Aabb<>()); const math::Aabb<> &GetAabb() const; void SetAabb(const math::Aabb<> &); private: math::Aabb<> aabb; }; } } #endif
[ "davidcosborn@gmail.com" ]
davidcosborn@gmail.com
9152b653ef64c50aeca122bfb90d211ebb70fa0a
6adfc6ccff3781ba852d5bee8e16be67fe272e41
/Source/CryptolensUE/Private/CryptolensUE.cpp
8d06227ac1acf3992b7724bf7ed266c6a1e70aae
[ "MIT" ]
permissive
trdwll/CryptolensUE
9f7a0484c3ea857d279ec303c644995eddaf830b
c4bdb001e74a54bf57c98ed18fc78eb17b26e538
refs/heads/main
2023-05-27T23:02:13.589920
2021-06-08T19:18:09
2021-06-08T19:18:09
366,830,254
0
0
null
null
null
null
UTF-8
C++
false
false
4,941
cpp
// Russ 'trdwll' Treadwell <trdwll.com> - 2021 #include "CryptolensUE.h" #include "Core.h" #include "Engine/Engine.h" #include "Interfaces/IPluginManager.h" #include "Modules/ModuleManager.h" #define LOCTEXT_NAMESPACE "FCryptolensUEModule" void FCryptolensUEModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module // Get the base directory of this plugin FString BaseDir = IPluginManager::Get().FindPlugin("CryptolensUE")->GetBaseDir(); } void FCryptolensUEModule::ShutdownModule() { } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FCryptolensUEModule, CryptolensUE) #pragma comment(lib, "winhttp.lib") #define GETSTR(text, ...) *FString::Printf(TEXT(text), ##__VA_ARGS__) #define PRINT(text, ...) \ if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Purple, GETSTR(text, ##__VA_ARGS__)) UCryptolensLicenseKey* UCryptolens::GetLicenseKey(const FString& LicenseKey) { if (UCryptolensLicenseKey* KeyObj = NewObject<UCryptolensLicenseKey>()) { cryptolens::Error e; Cryptolens cryptolens_handle(e); // Setting up the signature verifier with credentials from "Security Settings" on serialkeymanager.com cryptolens_handle.signature_verifier.set_modulus_base64(e, "0qoNb36dLXFirsOz32a41AtZIvk4hfzeBvg5LRXngVwTxrlddeaoyWuPunBwqhAbasOfTGJ0E+naqr6wvPqt0ZnN/aalV/xUSG9/HW6KMSaoiwnuEjTrs0FWWKSwAfCEKuS7y2iwU4l5SOHa3MBv2c8Myav3n3lpueqMVVGlSNJSeyilhRFVBumts+hSjh5cI4EJ56RI57VtXgANtPAmI32CRxaj78sg8N8Do2bRnOed4MM7SbnWeqFd/IYbQwZuzlPBzlTbtu/DyGFjsZu2gxwSm5yjMGlgCE664xeloKGaP3W1/9g8RgfS9LsRyAMejWt2SGSX4KqF0LVCq6VTiw=="); cryptolens_handle.signature_verifier.set_exponent_base64(e, "AQAB"); cryptolens_handle.machine_code_computer.set_machine_code(e, "289jf2afs3"); KeyObj->Init(LicenseKey, cryptolens_handle, e); if (e) { if (e.get_subsystem() == Subsystem::Main) { // Handle errors from the SKM API PRINT("SKM error %d", e.get_reason()); } else if (e.get_subsystem() == Subsystem::RequestHandler) { size_t code = e.get_extra(); PRINT("Error connecting to the server: error code: %d", code); } else { PRINT("Unhandled error: %d, %d, %d", e.get_subsystem(), e.get_reason(), e.get_extra()); } } return KeyObj; } return nullptr; } bool UCryptolensLicenseKey::IsKeyExpired() const { if (!m_LicenseKey) { return true; } // annoying cast, apparently the explicit bool operator isn't working... return (bool)m_LicenseKey->checkKey().has_expired(FDateTime::Now().ToUnixTimestamp()); } bool UCryptolensLicenseKey::DoesKeyHaveFeature(const ELicenseFeature Feature) { switch (Feature) { case ELicenseFeature::F1: return m_LicenseKey->get_f1() == 1; case ELicenseFeature::F2: return m_LicenseKey->get_f2() == 1; case ELicenseFeature::F3: return m_LicenseKey->get_f3() == 1; case ELicenseFeature::F4: return m_LicenseKey->get_f4() == 1; case ELicenseFeature::F5: return m_LicenseKey->get_f5() == 1; case ELicenseFeature::F6: return m_LicenseKey->get_f6() == 1; case ELicenseFeature::F7: return m_LicenseKey->get_f7() == 1; case ELicenseFeature::F8: return m_LicenseKey->get_f8() == 1; } return false; } int32 UCryptolensLicenseKey::get_product_id() const { return m_LicenseKey->get_product_id(); } int32 UCryptolensLicenseKey::get_period() const { return m_LicenseKey->get_period(); } int64 UCryptolensLicenseKey::get_created() const { return m_LicenseKey->get_created(); } int64 UCryptolensLicenseKey::get_expires() const { return m_LicenseKey->get_expires(); } int64 UCryptolensLicenseKey::get_sign_date() const { return m_LicenseKey->get_sign_date(); } bool UCryptolensLicenseKey::get_block() const { return m_LicenseKey->get_block(); } bool UCryptolensLicenseKey::get_trial_activation() const { return m_LicenseKey->get_trial_activation(); } bool UCryptolensLicenseKey::get_f1() const { return m_LicenseKey->get_f1(); } bool UCryptolensLicenseKey::get_f2() const { return m_LicenseKey->get_f2(); } bool UCryptolensLicenseKey::get_f3() const { return m_LicenseKey->get_f3(); } bool UCryptolensLicenseKey::get_f4() const { return m_LicenseKey->get_f4(); } bool UCryptolensLicenseKey::get_f5() const { return m_LicenseKey->get_f5(); } bool UCryptolensLicenseKey::get_f6() const { return m_LicenseKey->get_f6(); } bool UCryptolensLicenseKey::get_f7() const { return m_LicenseKey->get_f7(); } bool UCryptolensLicenseKey::get_f8() const { return m_LicenseKey->get_f8(); } FString UCryptolensLicenseKey::ToString() const { return UTF8_TO_TCHAR(m_LicenseKey->to_string().c_str()); } void UCryptolensLicenseKey::Init(const FString& LicenseKey, Cryptolens& handle, cryptolens::Error& e) { m_LicenseKey = handle.activate( e, // SKM Access Token "WyIxMzQ2MTk4IiwicTNCWFAvUmFmMjBwRnlLUXFQNmtsQ1IrT1pFRUpSeFdHVDBKbHQxNiJd", // Product id 10833, // License Key TCHAR_TO_UTF8(*LicenseKey)); }
[ "git@trdwll.com" ]
git@trdwll.com
80d339d3eb112ef634dbdf3f76b05b0dd67f2545
3b74241704f1317aef4e54ce66494a4787b0b8c0
/AtCoder/ABC312/A.cpp
af5bbf61911bbffd182bc070afa79a6e6a7feff6
[ "CC0-1.0" ]
permissive
arlechann/atcoder
990a5c3367de23dd79359906fd5119496aad6eee
a62fa2324005201d518b800a5372e855903952de
refs/heads/master
2023-09-01T12:49:34.034329
2023-08-26T17:20:36
2023-08-26T17:20:36
211,708,577
0
0
CC0-1.0
2022-06-06T21:49:11
2019-09-29T18:37:00
Rust
UTF-8
C++
false
false
4,648
cpp
#include <algorithm> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstring> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #define REP(i, n) for(int i = 0, i##_MACRO = (n); i < i##_MACRO; i++) #define RREP(i, n) for(int i = (n)-1; i >= 0; i--) #define RANGE(i, a, b) for(int i = (a), i##_MACRO = (b); i < i##_MACRO; i++) #define RRANGE(i, a, b) for(int i = (b)-1, i##_MACRO = (a); i >= i##_MACRO; i--) #define EACH(e, a) for(auto&& e : a) #define ALL(a) std::begin(a), std::end(a) #define RALL(a) std::rbegin(a), std::rend(a) #define FILL(a, n) memset((a), n, sizeof(a)) #define FILLZ(a) FILL(a, 0) #define CAST(x, t) (static_cast<t>(x)) #define PRECISION(x) std::fixed << std::setprecision(x) using namespace std; using ll = long long; using VI = vector<int>; using VI2D = vector<vector<int>>; using VLL = vector<long long>; using VLL2D = vector<vector<long long>>; constexpr int INF = 2e9; constexpr long long INFLL = 2e18; constexpr double EPS = 1e-10; constexpr double PI = acos(-1.0); template <typename T, std::size_t N> struct make_vector_type { using type = typename std::vector<typename make_vector_type<T, (N - 1)>::type>; }; template <typename T> struct make_vector_type<T, 0> { using type = typename std::vector<T>; }; template <typename T, size_t N> auto make_vector_impl(const std::vector<std::size_t>& ls, T init_value) { if constexpr(N == 0) { return std::vector<T>(ls[N], init_value); } else { return typename make_vector_type<T, N>::type( ls[N], make_vector_impl<T, (N - 1)>(ls, init_value)); } } template <typename T, std::size_t N> auto make_vector(const std::size_t (&ls)[N], T init_value) { std::vector<std::size_t> dimensions(N); for(int i = 0; i < N; i++) { dimensions[N - i - 1] = ls[i]; } return make_vector_impl<T, N - 1>(dimensions, init_value); } template <typename T> std::vector<T> make_vector(std::size_t size, T init_value) { return std::vector<T>(size, init_value); } template <typename T> constexpr int sign(T x) { return x < 0 ? -1 : x > 0 ? 1 : 0; } template <> constexpr int sign(double x) { return x < -EPS ? -1 : x > EPS ? 1 : 0; } template <typename T> constexpr bool chmax(T& m, T x) { if(m >= x) { return false; } m = x; return true; } template <typename T> constexpr bool chmin(T& m, T x) { if(m <= x) { return false; } m = x; return true; } template <typename T> constexpr T square(T x) { return x * x; } template <typename T> constexpr T pow(T a, int n) { T ret = 1; while(n != 0) { if(n % 2) { ret *= a; } a *= a; n /= 2; } return ret; } template <typename T> constexpr T div_ceil(T a, T b) { assert(b != 0); if(a < 0 && b < 0) { a = -a; b = -b; } if(a >= 0 && b > 0) { return (a + b - 1) / b; } return a / b; } template <typename T> constexpr T div_floor(T a, T b) { assert(b != 0); if(a < 0 && b < 0) { a = -a; b = -b; } if(a >= 0 && b > 0) { return a / b; } assert(false); } template <typename T> constexpr bool is_power_of_two(T n) { if constexpr(n == std::numeric_limits<T>::min()) { return true; } return (n & (n - 1)) == 0; } constexpr std::size_t next_power_of_two(std::size_t n) { if((n & (n - 1)) == 0) { return n; } std::size_t ret = 1; while(n != 0) { ret <<= 1; n >>= 1; } return ret; } template <typename T> constexpr T next_multiple_of(T a, T b) { return div_ceil(a, b) * b; } template <typename T> constexpr bool is_mul_overflow(T a, T b) { if(a >= 0 && b >= 0) { return a > std::numeric_limits<T>::max() / b; } if(a <= 0 && b < 0) { return a < div_ceil(std::numeric_limits<T>::max(), b); } if(a < 0) { return a > std::numeric_limits<T>::min() / b; } if(b < 0) { return a < div_ceil(std::numeric_limits<T>::max(), b); } } template <typename T> constexpr T diff(T a, T b) { return max(a, b) - min(a, b); } /** * _ _ _ ____ * (_)_ __ | |_ _ __ ___ __ _(_)_ __ / /\ \ _ * | | '_ \| __| | '_ ` _ \ / _` | | '_ \| | | (_) * | | | | | |_ | | | | | | (_| | | | | | | | |_ * |_|_| |_|\__| |_| |_| |_|\__,_|_|_| |_| | | ( ) * \_\/_/|/ */ int main() { string s; cin >> s; if(s == "ACE" || s == "BDF" || s == "CEG" || s == "DFA" || s == "EGB" || s == "FAC" || s == "GBD") { cout << "Yes" << endl; return 0; } cout << "No" << endl; return 0; }
[ "dragnov3728@gmail.com" ]
dragnov3728@gmail.com
7628f3dc24b46a73cfd2d02f3b03e30e48130c7c
a533d4198ee1237df55c94ee8ae3df4aefdc55bd
/dp/HeadFirstDesignPatterns/c_plusplus/Silver/Interpreter/MiniDuckSimulator/DisplayCommand.hpp
217f420595d37f44003bfa69246ae4db630ac904
[]
no_license
jufenghua596/book
c15aeb9b96e5fbb2e998286ef50bc5f569fa31a5
8b7d2db6b91268b3dcca39da4b067630768afdb6
refs/heads/master
2021-05-06T16:44:30.339828
2017-12-10T06:57:50
2017-12-10T06:57:50
113,723,089
1
0
null
null
null
null
UTF-8
C++
false
false
572
hpp
#ifndef _HFDP_CPP_INTERPRETER_MINI_DUCK_SIMULATOR_DISPLAY_COMMAND_HPP_ #define _HFDP_CPP_INTERPRETER_MINI_DUCK_SIMULATOR_DISPLAY_COMMAND_HPP_ #include "MiniDuckSimulator.hpp" namespace HeadFirstDesignPatterns { namespace Interpreter { namespace MiniDuckSimulator { class DisplayCommand : public Expression { private: ~DisplayCommand() { // disable inheritance } public: void accept( Visitor* visitor ) { assert( visitor ); visitor->interpret( this ); } }; } // namespace MiniDuckSimulator } // namespace Interpreter } // namespace HeadFirstDesignPatterns #endif
[ "jufenghua596@163.com" ]
jufenghua596@163.com
731ab02e082580d07231cae83644b3edd217db1e
04251e142abab46720229970dab4f7060456d361
/lib/rosetta/source/src/protocols/carbohydrates/GlycanSampler.hh
449e2562b47b08fc01797d97c842a36376c47b6d
[]
no_license
sailfish009/binding_affinity_calculator
216257449a627d196709f9743ca58d8764043f12
7af9ce221519e373aa823dadc2005de7a377670d
refs/heads/master
2022-12-29T11:15:45.164881
2020-10-22T09:35:32
2020-10-22T09:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,624
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file protocols/carbohydrates/GlycanSampler.hh /// @brief Main mover for Glycan Relax, which optimizes glycans in a pose. /// @author Jared Adolf-Bryfogle (jadolfbr@gmail.com) and Jason W. Labonte (JWLabonte@jhu.edu) #ifndef INCLUDED_protocols_carbohydrates_GlycanSampler_hh #define INCLUDED_protocols_carbohydrates_GlycanSampler_hh // Unit headers #include <protocols/carbohydrates/GlycanSampler.fwd.hh> #include <protocols/carbohydrates/LinkageConformerMover.hh> #include <protocols/moves/Mover.hh> #include <core/pose/Pose.fwd.hh> #include <core/kinematics/MoveMap.fwd.hh> #include <core/scoring/ScoreFunction.fwd.hh> #include <core/pack/task/TaskFactory.fwd.hh> #include <core/select/residue_selector/ResidueSelector.fwd.hh> #include <protocols/filters/Filter.fwd.hh> #include <protocols/moves/MonteCarlo.fwd.hh> #include <protocols/moves/MoverContainer.fwd.hh> #include <protocols/moves/MonteCarlo.fwd.hh> #include <protocols/simple_moves/BackboneMover.fwd.hh> #include <protocols/minimization_packing/MinMover.fwd.hh> #include <protocols/minimization_packing/PackRotamersMover.fwd.hh> #include <basic/datacache/DataMap.fwd.hh> namespace protocols { namespace carbohydrates { ///@brief Main mover for Glycan Relax, which optimizes glycans in a pose. /// Each round optimizes either one residue for BB sampling, linkage, or multiple for minimization. /// Currently uses a random sampler with a set of weights to each mover for sampling. /// /// Weights are currently as follows: /// .40 Phi/Psi Sugar BB Sampling /// .20 Linkage Conformer Sampling /// .30 Small BB Sampling - equal weight to phi, psi, or omega /// -> .17 +/- 15 degrees /// -> .086 +/- 45 degrees /// -> .044 +/- 90 degrees /// .05 GlycanTreeMinMover /// .05 PackRotamersMover /// /// Supports Symmetry /// class GlycanSampler : public protocols::moves::Mover { public: GlycanSampler(); //@brief constructor with arguments GlycanSampler( core::select::residue_selector::ResidueSelectorCOP selector, core::scoring::ScoreFunctionCOP scorefxn, core::Size rounds = 75); // copy constructor GlycanSampler( GlycanSampler const & src ); // destructor (important for properly forward-declaring smart-pointer members) ~GlycanSampler() override; void apply( core::pose::Pose & pose ) override; public: // Citation Management /////////////////////////////////////////////// /// @brief Does this mover provide information about how to cite it? bool mover_provides_citation_info() const override; /// @brief Provide a list of authors and their e-mail addresses, as strings. utility::vector1< basic::citation_manager::UnpublishedModuleInfoCOP > provide_authorship_info_for_unpublished() const override; public: ///@brief Set the Movemap void set_residue_selector(core::select::residue_selector::ResidueSelectorCOP selector ); ///@brief Set a ResidueSelector for glycan residue selection, instead of the typical movemap. void set_selector(core::select::residue_selector::ResidueSelectorCOP selector); ///@brief Set the TaskFactory to control side-chain packing of surrounding amino acids and the OH groups of the glycans. void set_taskfactory(core::pack::task::TaskFactoryCOP tf); ///@brief Set the ScoreFunction void set_scorefunction( core::scoring::ScoreFunctionCOP scorefxn); ///@brief Each round applys a random mover to pose. /// This setting is multiplied by the number of glycan residues in the movemap for the total number of rounds void set_rounds( core::Size rounds); ///@brief Set how our Conformer mover samples. Default is to do uniform sampling on the conformers instead of using the population as probabilities. void set_population_based_conformer_sampling(bool pop_based_sampling); ///@brief Set whether if we are sampling torsions uniformly within an SD for the LinkageConformerMover (false) /// or sampling the gaussian (true). /// Default false void set_use_gaussian_sampling(bool use_gaussian_sampling); void set_kt( core::Real kt); void set_defaults(); ///@brief Use Cartesian minimization instead of Dihedral minimization. /// Default (for now) is dihedral. void use_cartmin( bool use_cartmin ); ///@brief Set refinement mode instead of denovo modeling mode. void set_refine( bool refine ); ///@brief set to minimize ring torsions during minimzation. Default false. void set_min_rings( bool min_rings); ///@brief Set the protocol to use the refactored Shear Mover for glycan torsions at 10 % probability. /// Default false. void set_use_shear( bool use_shear); ///@brief Set the protocol to randomize torsions before beginning. /// This actually helps get to lower energy models. /// Default True. If doing refinement, this is automatically turned off. void set_randomize_first( bool randomize_first ); ///@brief Set the number of inner cycles for BB sampling through small/sugarBB. /// This is multiplied by the number of glycan residues /// Default 1 void set_inner_bb_cycles( core::Size inner_bb_cycles ); ///@brief Set Conformer Sampling through probabilities at the linkage to the protein only void set_protein_linkage_prob_sampling( bool root_probs); public: void show( std::ostream & output=std::cout ) const override; /// @brief parse XML tag (to use this Mover in Rosetta Scripts) void parse_my_tag( utility::tag::TagCOP tag, basic::datacache::DataMap & data ) override; //GlycanSampler & operator=( GlycanSampler const & src ); /// @brief required in the context of the parser/scripting scheme moves::MoverOP fresh_instance() const override; /// @brief required in the context of the parser/scripting scheme protocols::moves::MoverOP clone() const override; bool reinitialize_for_each_job() const override { return true; } std::string get_name() const override; static std::string mover_name(); static void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ); ///@brief Randomize all torsions of the subset. Used to start the protocol. void randomize_glycan_torsions( core::pose::Pose & pose, utility::vector1< bool > const & subset ) const; ///@brief Attempt to idealize all residues in of a set of trees. Experimental! void idealize_glycan_residues( core::pose::Pose & pose, utility::vector1< core::Size > const & tree_subset ) const; public: ///@brief Get the number of glycan sampler rounds this class is set to run. core::Size get_glycan_sampler_rounds(); ///@brief This allows us to force a number of rounds instead of doing rounds*glycan residues void force_total_rounds( core::Size total_rounds ); private: void init_objects( core::pose::Pose & pose ); void set_cmd_line_defaults(); void apply_to_res( core::pose::Pose & pose, core::Size resnum, core::kinematics::MoveMapOP mm, core::scoring::ScoreFunctionOP score, core::Size round); void setup_default_task_factory(utility::vector1< bool > const & glycan_residues, core::pose::Pose const & pose ); void setup_score_function(); void setup_cartmin(core::scoring::ScoreFunctionOP scorefxn) const; //Setup the final WeightedMover from our subsets and movemap. void setup_movers( core::pose::Pose & pose, utility::vector1< bool > const & dihedral_subset, utility::vector1< bool > const & sugar_bb_subset, utility::vector1< bool > const & subset); void setup_packer( core::pose::Pose & pose, utility::vector1< bool > const & full_subset ); private: core::pack::task::TaskFactoryCOP tf_ = nullptr; moves::MonteCarloOP mc_ = nullptr; core::scoring::ScoreFunctionCOP scorefxn_ = nullptr; LinkageConformerMoverOP linkage_mover_ = nullptr; moves::RandomMoverOP weighted_random_mover_ = nullptr; minimization_packing::MinMoverOP min_mover_ = nullptr; minimization_packing::PackRotamersMoverOP packer_ = nullptr; simple_moves::ShearMoverOP shear_ = nullptr; core::Size rounds_ = 100; // cmdline core::Real kt_ = 2.0; // cmdline utility::vector1<std::string> accept_log_; bool test_ = false; // cmdline bool final_min_ = true; // cmdline bool refine_ = false; // cmdline core::Size total_glycan_residues_ = 0; bool pymol_movie_ = false; // cmdline utility::vector1< std::string > parsed_positions_; core::Real pack_distance_ = 6.0; bool cartmin_ = false; // cmdline bool tree_based_min_pack_ = true; // cmdline core::select::residue_selector::ResidueSelectorCOP selector_; bool population_based_conformer_sampling_ = false; bool use_gaussian_sampling_ = true; bool min_rings_ = false; core::Size forced_total_rounds_ = 0; bool use_shear_ = true; bool randomize_first_ = true; core::Size inner_ncycles_ = 0; //For individual bb movements, multiply this by n glycans. bool match_sampling_of_modeler_ = false; //For benchmarking utility::vector1< bool > final_residue_subset_; bool root_prob_sampling_ = false; }; std::ostream &operator<< (std::ostream &os, GlycanSampler const &mover); } //protocols } //carbohydrates #endif //protocols/carbohydrates_GlycanSampler_hh
[ "lzhangbk@connect.ust.hk" ]
lzhangbk@connect.ust.hk
f3b74c5ea454ee4af779e2c4cd0490a805518dbd
e174dd6067f48e5884cae9fe136f6ff60ba19522
/amazon_robot/amazon_robot_gazebo/src/amazon_robot_drive.cpp
53e49fdbc4955210eb14fa01d53f47e2fcbc2cf5
[]
no_license
SakshayMahna/CustomRobots
383b22f9efea61beb4824eb2068cb0180bbec2ec
bcd2aad6fb2a9a6f358269f22c45354e6b1f64d1
refs/heads/master
2022-11-25T13:33:36.817344
2020-07-29T10:55:56
2020-07-29T10:55:56
283,469,288
0
1
null
2020-07-29T10:31:04
2020-07-29T10:31:03
null
UTF-8
C++
false
false
4,996
cpp
/******************************************************************************* * Copyright 2016 ROBOTIS CO., LTD. * * 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. *******************************************************************************/ /* Authors: Taehun Lim (Darby) */ #include <amazon_robot_gazebo/amazon_robot_drive.h> AmazonRobotDrive::AmazonRobotDrive() : nh_priv_("~") { //Init gazebo ros turtlebot3 node ROS_INFO("Amazon Robot Drive Node Init"); ROS_ASSERT(init()); } AmazonRobotDrive::~AmazonRobotDrive() { updatecommandVelocity(0.0, 0.0); ros::shutdown(); } /******************************************************************************* * Init function *******************************************************************************/ bool AmazonRobotDrive::init() { // initialize ROS parameter std::string cmd_vel_topic_name = nh_.param<std::string>("cmd_vel_topic_name", ""); // initialize variables escape_range_ = 30.0 * DEG2RAD; check_forward_dist_ = 0.7; check_side_dist_ = 0.6; tb3_pose_ = 0.0; prev_tb3_pose_ = 0.0; // initialize publishers cmd_vel_pub_ = nh_.advertise<geometry_msgs::Twist>(cmd_vel_topic_name, 10); // initialize subscribers laser_scan_sub_ = nh_.subscribe("scan", 10, &AmazonRobotDrive::laserScanMsgCallBack, this); odom_sub_ = nh_.subscribe("odom", 10, &AmazonRobotDrive::odomMsgCallBack, this); return true; } void AmazonRobotDrive::odomMsgCallBack(const nav_msgs::Odometry::ConstPtr &msg) { double siny = 2.0 * (msg->pose.pose.orientation.w * msg->pose.pose.orientation.z + msg->pose.pose.orientation.x * msg->pose.pose.orientation.y); double cosy = 1.0 - 2.0 * (msg->pose.pose.orientation.y * msg->pose.pose.orientation.y + msg->pose.pose.orientation.z * msg->pose.pose.orientation.z); tb3_pose_ = atan2(siny, cosy); } void AmazonRobotDrive::laserScanMsgCallBack(const sensor_msgs::LaserScan::ConstPtr &msg) { uint16_t scan_angle[3] = {0, 30, 330}; for (int num = 0; num < 3; num++) { if (std::isinf(msg->ranges.at(scan_angle[num]))) { scan_data_[num] = msg->range_max; } else { scan_data_[num] = msg->ranges.at(scan_angle[num]); } } } void AmazonRobotDrive::updatecommandVelocity(double linear, double angular) { geometry_msgs::Twist cmd_vel; cmd_vel.linear.x = linear; cmd_vel.angular.z = angular; cmd_vel_pub_.publish(cmd_vel); } /******************************************************************************* * Control Loop function *******************************************************************************/ bool AmazonRobotDrive::controlLoop() { static uint8_t amazon_robot_state = 0; switch(amazon_robot_state) { case GET_TB3_DIRECTION: if (scan_data_[CENTER] > check_forward_dist_) { if (scan_data_[LEFT] < check_side_dist_) { prev_tb3_pose_ = tb3_pose_; amazon_robot_state = TB3_RIGHT_TURN; } else if (scan_data_[RIGHT] < check_side_dist_) { prev_tb3_pose_ = tb3_pose_; amazon_robot_state = TB3_LEFT_TURN; } else { amazon_robot_state = TB3_DRIVE_FORWARD; } } if (scan_data_[CENTER] < check_forward_dist_) { prev_tb3_pose_ = tb3_pose_; amazon_robot_state = TB3_RIGHT_TURN; } break; case TB3_DRIVE_FORWARD: updatecommandVelocity(LINEAR_VELOCITY, 0.0); amazon_robot_state = GET_TB3_DIRECTION; break; case TB3_RIGHT_TURN: if (fabs(prev_tb3_pose_ - tb3_pose_) >= escape_range_) amazon_robot_state = GET_TB3_DIRECTION; else updatecommandVelocity(0.0, -1 * ANGULAR_VELOCITY); break; case TB3_LEFT_TURN: if (fabs(prev_tb3_pose_ - tb3_pose_) >= escape_range_) amazon_robot_state = GET_TB3_DIRECTION; else updatecommandVelocity(0.0, ANGULAR_VELOCITY); break; default: amazon_robot_state = GET_TB3_DIRECTION; break; } return true; } /******************************************************************************* * Main function *******************************************************************************/ int main(int argc, char* argv[]) { ros::init(argc, argv, "amazonRobotDrive"); AmazonRobotDrive amazonRobotDrive; ros::Rate loop_rate(125); while (ros::ok()) { amazonRobotDrive.controlLoop(); ros::spinOnce(); loop_rate.sleep(); } return 0; }
[ "shreyas6gokhale@gmail.com" ]
shreyas6gokhale@gmail.com
90f9f29cfd944e19e416a2db67da64601168866b
07b30b07f3ef2fc2734c6a7226aee9b5cba04851
/engine/common/SimpleNavMesh.cpp
b6437075d284afb2613d19fdcc367b6dcf119e70
[ "Apache-2.0" ]
permissive
Endofunctor/noobwerkz-engine
3ba001e97bdf56e52f3baaa263ed9cea0e79cec2
2f35b4cd8724e59e2a442f0697db5cb5897d0b7c
refs/heads/master
2020-12-25T11:16:07.669537
2016-01-13T03:09:50
2016-01-13T03:09:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,591
cpp
/*#define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <string.h> #include "SDL.h" #include "SDL_opengl.h" #include "imgui.h" #include "InputGeom.h" #include "Sample.h" */ #include <vector> #include "Logger.hpp" #include "SimpleNavMesh.hpp" #include "Recast.h" //#include "Sample.h" #include "RecastDebugDraw.h" #include "RecastDump.h" #include "InputGeom.h" #include "DetourNode.h" #include "DetourNavMesh.h" #include "DetourNavMeshBuilder.h" #include "DetourNavMeshQuery.h" #include "DetourStatus.h" #include "DetourDebugDraw.h" #include "NavMeshTesterTool.h" #include "NavMeshPruneTool.h" #include "OffMeshConnectionTool.h" #include "ConvexVolumeTool.h" #include "CrowdTool.h" #include "MathFuncs.hpp" #include <btBulletDynamicsCommon.h> noob::simple_navmesh::simple_navmesh() : m_keepInterResults(true), m_totalBuildTimeMs(0), m_triareas(0), m_solid(0), m_chf(0), m_cset(0), m_pmesh(0), m_dmesh(0), m_DrawMode(DRAWMODE_NAVMESH) { // setTool(new NavMeshTesterTool); } noob::simple_navmesh::~simple_navmesh() { cleanup(); } void noob::simple_navmesh::cleanup() { delete [] m_triareas; m_triareas = 0; rcFreeHeightField(m_solid); m_solid = 0; rcFreeCompactHeightfield(m_chf); m_chf = 0; rcFreeContourSet(m_cset); m_cset = 0; rcFreePolyMesh(m_pmesh); m_pmesh = 0; rcFreePolyMeshDetail(m_dmesh); m_dmesh = 0; dtFreeNavMesh(m_navMesh); m_navMesh = 0; } void noob::simple_navmesh::handleSettings() { /* Sample::handleCommonSettings(); if (imguiCheck("Keep Itermediate Results", m_keepInterResults)) m_keepInterResults = !m_keepInterResults; imguiSeparator(); char msg[64]; snprintf(msg, 64, "Build Time: %.1fms", m_totalBuildTimeMs); imguiLabel(msg); imguiSeparator(); */ } void noob::simple_navmesh::handleTools() { /* int type = !m_tool ? TOOL_NONE : m_tool->type(); if (imguiCheck("Test Navmesh", type == TOOL_NAVMESH_TESTER)) { setTool(new NavMeshTesterTool); } if (imguiCheck("Prune Navmesh", type == TOOL_NAVMESH_PRUNE)) { setTool(new NavMeshPruneTool); } if (imguiCheck("Create Off-Mesh Connections", type == TOOL_OFFMESH_CONNECTION)) { setTool(new OffMeshConnectionTool); } if (imguiCheck("Create Convex Volumes", type == TOOL_CONVEX_VOLUME)) { setTool(new ConvexVolumeTool); } if (imguiCheck("Create Crowds", type == TOOL_CROWD)) { setTool(new CrowdTool); } imguiSeparatorLine(); imguiIndent(); if (m_tool) m_tool->handleMenu(); imguiUnindent(); */ } void noob::simple_navmesh::handle_debug_mode() { // Check which modes are valid. /* bool valid[MAX_DRAWMODE]; for (int i = 0; i < MAX_DRAWMODE; ++i) valid[i] = false; if (m_geom) { valid[DRAWMODE_NAVMESH] = m_navMesh != 0; valid[DRAWMODE_NAVMESH_TRANS] = m_navMesh != 0; valid[DRAWMODE_NAVMESH_BVTREE] = m_navMesh != 0; valid[DRAWMODE_NAVMESH_NODES] = m_navQuery != 0; valid[DRAWMODE_NAVMESH_INVIS] = m_navMesh != 0; valid[DRAWMODE_MESH] = true; valid[DRAWMODE_VOXELS] = m_solid != 0; valid[DRAWMODE_VOXELS_WALKABLE] = m_solid != 0; valid[DRAWMODE_COMPACT] = m_chf != 0; valid[DRAWMODE_COMPACT_DISTANCE] = m_chf != 0; valid[DRAWMODE_COMPACT_REGIONS] = m_chf != 0; valid[DRAWMODE_REGION_CONNECTIONS] = m_cset != 0; valid[DRAWMODE_RAW_CONTOURS] = m_cset != 0; valid[DRAWMODE_BOTH_CONTOURS] = m_cset != 0; valid[DRAWMODE_CONTOURS] = m_cset != 0; valid[DRAWMODE_POLYMESH] = m_pmesh != 0; valid[DRAWMODE_POLYMESH_DETAIL] = m_dmesh != 0; } int unavail = 0; for (int i = 0; i < MAX_DRAWMODE; ++i) if (!valid[i]) unavail++; if (unavail == MAX_DRAWMODE) return; imguiLabel("Draw"); if (imguiCheck("Input Mesh", draw_mode == DRAWMODE_MESH, valid[DRAWMODE_MESH])) draw_mode = DRAWMODE_MESH; if (imguiCheck("Navmesh", draw_mode == DRAWMODE_NAVMESH, valid[DRAWMODE_NAVMESH])) draw_mode = DRAWMODE_NAVMESH; if (imguiCheck("Navmesh Invis", draw_mode == DRAWMODE_NAVMESH_INVIS, valid[DRAWMODE_NAVMESH_INVIS])) draw_mode = DRAWMODE_NAVMESH_INVIS; if (imguiCheck("Navmesh Trans", draw_mode == DRAWMODE_NAVMESH_TRANS, valid[DRAWMODE_NAVMESH_TRANS])) draw_mode = DRAWMODE_NAVMESH_TRANS; if (imguiCheck("Navmesh BVTree", draw_mode == DRAWMODE_NAVMESH_BVTREE, valid[DRAWMODE_NAVMESH_BVTREE])) draw_mode = DRAWMODE_NAVMESH_BVTREE; if (imguiCheck("Navmesh Nodes", draw_mode == DRAWMODE_NAVMESH_NODES, valid[DRAWMODE_NAVMESH_NODES])) draw_mode = DRAWMODE_NAVMESH_NODES; if (imguiCheck("Voxels", draw_mode == DRAWMODE_VOXELS, valid[DRAWMODE_VOXELS])) draw_mode = DRAWMODE_VOXELS; if (imguiCheck("Walkable Voxels", draw_mode == DRAWMODE_VOXELS_WALKABLE, valid[DRAWMODE_VOXELS_WALKABLE])) draw_mode = DRAWMODE_VOXELS_WALKABLE; if (imguiCheck("Compact", draw_mode == DRAWMODE_COMPACT, valid[DRAWMODE_COMPACT])) draw_mode = DRAWMODE_COMPACT; if (imguiCheck("Compact Distance", draw_mode == DRAWMODE_COMPACT_DISTANCE, valid[DRAWMODE_COMPACT_DISTANCE])) draw_mode = DRAWMODE_COMPACT_DISTANCE; if (imguiCheck("Compact Regions", draw_mode == DRAWMODE_COMPACT_REGIONS, valid[DRAWMODE_COMPACT_REGIONS])) draw_mode = DRAWMODE_COMPACT_REGIONS; if (imguiCheck("Region Connections", draw_mode == DRAWMODE_REGION_CONNECTIONS, valid[DRAWMODE_REGION_CONNECTIONS])) draw_mode = DRAWMODE_REGION_CONNECTIONS; if (imguiCheck("Raw Contours", draw_mode == DRAWMODE_RAW_CONTOURS, valid[DRAWMODE_RAW_CONTOURS])) draw_mode = DRAWMODE_RAW_CONTOURS; if (imguiCheck("Both Contours", draw_mode == DRAWMODE_BOTH_CONTOURS, valid[DRAWMODE_BOTH_CONTOURS])) draw_mode = DRAWMODE_BOTH_CONTOURS; if (imguiCheck("Contours", draw_mode == DRAWMODE_CONTOURS, valid[DRAWMODE_CONTOURS])) draw_mode = DRAWMODE_CONTOURS; if (imguiCheck("Poly Mesh", draw_mode == DRAWMODE_POLYMESH, valid[DRAWMODE_POLYMESH])) draw_mode = DRAWMODE_POLYMESH; if (imguiCheck("Poly Mesh Detail", draw_mode == DRAWMODE_POLYMESH_DETAIL, valid[DRAWMODE_POLYMESH_DETAIL])) draw_mode = DRAWMODE_POLYMESH_DETAIL; if (unavail) { imguiValue("Tick 'Keep Itermediate Results'"); imguiValue("to see more debug mode options."); } */ } void noob::simple_navmesh::handleRender() { /* if (!m_geom || !m_geom->getMesh()) return; // DebugDrawGL dd; // glEnable(GL_FOG); // glDepthMask(GL_TRUE); const float texScale = 1.0f / (m_cellSize * 10.0f); // if (draw_mode != DRAWMODE_NAVMESH_TRANS) { // Draw mesh // duDebugDrawTriMeshSlope(&dd, m_geom->getMesh()->getVerts(), m_geom->getMesh()->getVertCount(), m_geom->getMesh()->getTris(), m_geom->getMesh()->getNormals(), m_geom->getMesh()->getTriCount(), m_agentMaxSlope, texScale); // m_geom->drawOffMeshConnections(&dd); } // glDisable(GL_FOG); // glDepthMask(GL_FALSE); // Draw bounds const float* bmin = m_geom->getMeshBoundsMin(); const float* bmax = m_geom->getMeshBoundsMax(); // duDebugDrawBoxWire(&dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duRGBA(255,255,255,128), 1.0f); // dd.begin(DU_DRAW_POINTS, 5.0f); // dd.vertex(bmin[0],bmin[1],bmin[2],duRGBA(255,255,255,128)); // dd.end(); // if (m_navMesh && m_navQuery && (draw_mode == DRAWMODE_NAVMESH || draw_mode == DRAWMODE_NAVMESH_TRANS || draw_mode == DRAWMODE_NAVMESH_BVTREE || draw_mode == DRAWMODE_NAVMESH_NODES || draw_mode == DRAWMODE_NAVMESH_INVIS)) { // if (draw_mode != DRAWMODE_NAVMESH_INVIS) // duDebugDrawNavMeshWithClosedList(&dd, *m_navMesh, *m_navQuery, m_navMeshDrawFlags); // if (draw_mode == DRAWMODE_NAVMESH_BVTREE) // duDebugDrawNavMeshBVTree(&dd, *m_navMesh); // if (draw_mode == DRAWMODE_NAVMESH_NODES) // duDebugDrawNavMeshNodes(&dd, *m_navQuery); // duDebugDrawNavMeshPolysWithFlags(&dd, *m_navMesh, SAMPLE_POLYFLAGS_DISABLED, duRGBA(0,0,0,128)); } // glDepthMask(GL_TRUE); if (m_chf && draw_mode == DRAWMODE_COMPACT) // duDebugDrawCompactHeightfieldSolid(&dd, *m_chf); if (m_chf && draw_mode == DRAWMODE_COMPACT_DISTANCE) // duDebugDrawCompactHeightfieldDistance(&dd, *m_chf); if (m_chf && draw_mode == DRAWMODE_COMPACT_REGIONS) // duDebugDrawCompactHeightfieldRegions(&dd, *m_chf); if (m_solid && draw_mode == DRAWMODE_VOXELS) { // glEnable(GL_FOG); // duDebugDrawHeightfieldSolid(&dd, *m_solid); // glDisable(GL_FOG); } if (m_solid && draw_mode == DRAWMODE_VOXELS_WALKABLE) { // glEnable(GL_FOG); // duDebugDrawHeightfieldWalkable(&dd, *m_solid); // glDisable(GL_FOG); } if (m_cset && draw_mode == DRAWMODE_RAW_CONTOURS) { // glDepthMask(GL_FALSE); // duDebugDrawRawContours(&dd, *m_cset); // glDepthMask(GL_TRUE); } if (m_cset && draw_mode == DRAWMODE_BOTH_CONTOURS) { // glDepthMask(GL_FALSE); // duDebugDrawRawContours(&dd, *m_cset, 0.5f); // duDebugDrawContours(&dd, *m_cset); // glDepthMask(GL_TRUE); } if (m_cset && draw_mode == DRAWMODE_CONTOURS) { // glDepthMask(GL_FALSE); // duDebugDrawContours(&dd, *m_cset); // glDepthMask(GL_TRUE); } if (m_chf && m_cset && draw_mode == DRAWMODE_REGION_CONNECTIONS) { // duDebugDrawCompactHeightfieldRegions(&dd, *m_chf); // glDepthMask(GL_FALSE); // duDebugDrawRegionConnections(&dd, *m_cset); // glDepthMask(GL_TRUE); } if (m_pmesh && draw_mode == DRAWMODE_POLYMESH) { // glDepthMask(GL_FALSE); // duDebugDrawPolyMesh(&dd, *m_pmesh); // glDepthMask(GL_TRUE); } if (m_dmesh && draw_mode == DRAWMODE_POLYMESH_DETAIL) { // glDepthMask(GL_FALSE); // duDebugDrawPolyMeshDetail(&dd, *m_dmesh); // glDepthMask(GL_TRUE); } // m_geom->drawConvexVolumes(&dd); // if (m_tool) // m_tool->handleRender(); // renderToolStates(); // glDepthMask(GL_TRUE); } void noob::simple_navmesh::handleRenderOverlay(double* proj, double* model, int* view) { // if (m_tool) // m_tool->handleRenderOverlay(proj, model, view); // renderOverlayToolStates(proj, model, view); } void noob::simple_navmesh::handleMeshChanged(class InputGeom* geom) { // Sample::handleMeshChanged(geom); dtFreeNavMesh(m_navMesh); m_navMesh = 0; if (m_tool) { m_tool->reset(); m_tool->init(this); } resetToolStates(); initToolStates(this); */ } bool noob::simple_navmesh::handleBuild() { if (!m_geom || !m_geom->getMesh()) { logger::log("buildNavigation: Input mesh is not specified."); return false; } cleanup(); const float* bmin = m_geom->getMeshBoundsMin(); const float* bmax = m_geom->getMeshBoundsMax(); const float* verts = m_geom->getMesh()->getVerts(); nverts = m_geom->getMesh()->getVertCount(); const int* tris = m_geom->getMesh()->getTris(); const int ntris = m_geom->getMesh()->getTriCount(); // // Step 1. Initialize build config. // // Init build configuration from GUI memset(&config, 0, sizeof(config)); //noob::simple_navmesh::config config; config.cs = m_cellSize; config.ch = m_cellHeight; config.walkableSlopeAngle = m_agentMaxSlope; config.walkableHeight = (int)ceilf(m_agentHeight / config.ch); config.walkableClimb = (int)floorf(m_agentMaxClimb / config.ch); config.walkableRadius = (int)ceilf(m_agentRadius / config.cs); config.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize); config.maxSimplificationError = m_edgeMaxError; config.minRegionArea = (int)rcSqr(m_regionMinSize); // Note: area = size*size config.mergeRegionArea = (int)rcSqr(m_regionMergeSize); // Note: area = size*size config.maxVertsPerPoly = (int)m_vertsPerPoly; config.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist; config.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError; // Set the area where the navigation will be build. // Here the bounds of the input mesh are used, but the // area could be specified by an user defined box, etc. rcVcopy(config.bmin, bmin); rcVcopy(config.bmax, bmax); rcCalcGridSize(config.bmin, config.bmax, config.cs, &config.width, &config.height); // Reset build times gathering. m_ctx->resetTimers(); // Start the build process. m_ctx->startTimer(RC_TIMER_TOTAL); logger::log(fmt::format("Building navigation: - {0} x {1} cells - {2}K verts, {3}K tris", config.width, config.height, nverts/1000.0f, ntris/1000.0f)); // // Step 2. Rasterize input polygon soup. // // Allocate voxel heightfield where we rasterize our input data to. m_solid = rcAllocHeightfield(); if (!m_solid) { logger::log("buildNavigation: Out of memory 'solid'."); return false; } if (!rcCreateHeightfield(m_ctx, *m_solid, config.width, config.height, config.bmin, config.bmax, config.cs, config.ch)) { logger::log("buildNavigation: Could not create solid heightfield."); return false; } // Allocate array that can hold triangle area types. // If you have multiple meshes you need to process, allocate // and array which can hold the max number of triangles you need to process. m_triareas = new unsigned char[ntris]; if (!m_triareas) { logger::log(fmt::format("buildNavigation: Out of memory 'm_triareas' ({0}).", ntris)); return false; } // Find triangles which are walkable based on their slope and rasterize them. // If your input data is multiple meshes, you can transform them here, calculate // the are type for each of the meshes and rasterize them. memset(m_triareas, 0, ntris*sizeof(unsigned char)); rcMarkWalkableTriangles(m_ctx, config.walkableSlopeAngle, verts, nverts, tris, ntris, m_triareas); rcRasterizeTriangles(m_ctx, verts, nverts, tris, m_triareas, ntris, *m_solid, config.walkableClimb); if (!m_keepInterResults) { delete [] m_triareas; m_triareas = 0; } // // Step 3. Filter walkables surfaces. // // Once all geoemtry is rasterized, we do initial pass of filtering to // remove unwanted overhangs caused by the conservative rasterization // as well as filter spans where the character cannot possibly stand. rcFilterLowHangingWalkableObstacles(m_ctx, config.walkableClimb, *m_solid); rcFilterLedgeSpans(m_ctx, config.walkableHeight, config.walkableClimb, *m_solid); rcFilterWalkableLowHeightSpans(m_ctx, config.walkableHeight, *m_solid); // // Step 4. Partition walkable surface to simple regions. // // Compact the heightfield so that it is faster to handle from now on. // This will result more cache coherent data as well as the neighbours // between walkable cells will be calculated. m_chf = rcAllocCompactHeightfield(); if (!m_chf) { logger::log("buildNavigation: Out of memory 'chf'."); return false; } if (!rcBuildCompactHeightfield(m_ctx, config.walkableHeight, config.walkableClimb, *m_solid, *m_chf)) { logger::log("buildNavigation: Could not build compact data."); return false; } if (!m_keepInterResults) { rcFreeHeightField(m_solid); m_solid = 0; } // Erode the walkable area by agent radius. if (!rcErodeWalkableArea(m_ctx, config.walkableRadius, *m_chf)) { logger::log("buildNavigation: Could not erode."); return false; } // (Optional) Mark areas. const ConvexVolume* vols = m_geom->getConvexVolumes(); for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i) rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf); // Partition the heightfield so that we can use simple algorithm later to triangulate the walkable areas. // There are 3 martitioning methods, each with some pros and cons: // 1) Watershed partitioning // - the classic Recast partitioning // - creates the nicest tessellation // - usually slowest // - partitions the heightfield into nice regions without holes or overlaps // - the are some corner cases where this method creates produces holes and overlaps // - holes may appear when a small obstacles is close to large open area (triangulation can handle this) // - overlaps may occur if you have narrow spiral corridors (i.e stairs), this make triangulation to fail // * generally the best choice if you precompute the nacmesh, use this if you have large open areas // 2) Monotone partioning // - fastest // - partitions the heightfield into regions without holes and overlaps (guaranteed) // - creates long thin polygons, which sometimes causes paths with detours // * use this if you want fast simple_navmesh generation // 3) Layer partitoining // - quite fast // - partitions the heighfield into non-overlapping regions // - relies on the triangulation code to cope with holes (thus slower than monotone partitioning) // - produces better triangles than monotone partitioning // - does not have the corner cases of watershed partitioning // - can be slow and create a bit ugly tessellation (still better than monotone) // if you have large open areas with small obstacles (not a problem if you use tiles) // * good choice to use for tiled simple_navmesh with medium and small sized tiles if (m_partitionType == SAMPLE_PARTITION_WATERSHED) { // Prepare for region partitioning, by calculating distance field along the walkable surface. if (!rcBuildDistanceField(m_ctx, *m_chf)) { logger::log("buildNavigation: Could not build distance field."); return false; } // Partition the walkable surface into simple regions without holes. if (!rcBuildRegions(m_ctx, *m_chf, 0, config.minRegionArea, config.mergeRegionArea)) { logger::log("buildNavigation: Could not build watershed regions."); return false; } } else if (m_partitionType == SAMPLE_PARTITION_MONOTONE) { // Partition the walkable surface into simple regions without holes. // Monotone partitioning does not need distancefield. if (!rcBuildRegionsMonotone(m_ctx, *m_chf, 0, config.minRegionArea, config.mergeRegionArea)) { logger::log("buildNavigation: Could not build monotone regions."); return false; } } else // SAMPLE_PARTITION_LAYERS { // Partition the walkable surface into simple regions without holes. if (!rcBuildLayerRegions(m_ctx, *m_chf, 0, config.minRegionArea)) { logger::log("buildNavigation: Could not build layer regions."); return false; } } // // Step 5. Trace and simplify region contours. // // Create contours. m_cset = rcAllocContourSet(); if (!m_cset) { logger::log("buildNavigation: Out of memory 'cset'."); return false; } if (!rcBuildContours(m_ctx, *m_chf, config.maxSimplificationError, config.maxEdgeLen, *m_cset)) { logger::log("buildNavigation: Could not create contours."); return false; } // // Step 6. Build polygons mesh from contours. // // Build polygon simple_navmesh from the contours. m_pmesh = rcAllocPolyMesh(); if (!m_pmesh) { logger::log("buildNavigation: Out of memory 'pmesh'."); return false; } if (!rcBuildPolyMesh(m_ctx, *m_cset, config.maxVertsPerPoly, *m_pmesh)) { logger::log("buildNavigation: Could not triangulate contours."); return false; } // // Step 7. Create detail mesh which allows to access approximate height on each polygon. // m_dmesh = rcAllocPolyMeshDetail(); if (!m_dmesh) { logger::log("buildNavigation: Out of memory 'pmdtl'."); return false; } if (!rcBuildPolyMeshDetail(m_ctx, *m_pmesh, *m_chf, config.detailSampleDist, config.detailSampleMaxError, *m_dmesh)) { logger::log("buildNavigation: Could not build detail mesh."); return false; } if (!m_keepInterResults) { rcFreeCompactHeightfield(m_chf); m_chf = 0; rcFreeContourSet(m_cset); m_cset = 0; } // At this point the navigation mesh data is ready, you can access it from m_pmesh. // See duDebugDrawPolyMesh or dtCreateNavMeshData as examples how to access the data. // // (Optional) Step 8. Create Detour data from Recast poly mesh. // // The GUI may allow more max points per polygon than Detour can handle. // Only build the detour simple_navmesh if we do not exceed the limit. /* if (config.maxVertsPerPoly <= DT_VERTS_PER_POLYGON) { */ unsigned char* navData = 0; int navDataSize = 0; // Update poly flags from areas. for (int i = 0; i < m_pmesh->npolys; ++i) { if (m_pmesh->areas[i] == RC_WALKABLE_AREA) m_pmesh->areas[i] = SAMPLE_POLYAREA_GROUND; if (m_pmesh->areas[i] == SAMPLE_POLYAREA_GROUND || m_pmesh->areas[i] == SAMPLE_POLYAREA_GRASS || m_pmesh->areas[i] == SAMPLE_POLYAREA_ROAD) { m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK; } else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_WATER) { m_pmesh->flags[i] = SAMPLE_POLYFLAGS_SWIM; } else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_DOOR) { m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR; } } // // dtNavMeshCreateParams params; memset(&params, 0, sizeof(params)); params.verts = m_pmesh->verts; params.vertCount = m_pmesh->nverts; params.polys = m_pmesh->polys; params.polyAreas = m_pmesh->areas; params.polyFlags = m_pmesh->flags; params.polyCount = m_pmesh->npolys; params.nvp = m_pmesh->nvp; params.detailMeshes = m_dmesh->meshes; params.detailVerts = m_dmesh->verts; params.detailVertsCount = m_dmesh->nverts; params.detailTris = m_dmesh->tris; params.detailTriCount = m_dmesh->ntris; params.offMeshConVerts = m_geom->getOffMeshConnectionVerts(); params.offMeshConRad = m_geom->getOffMeshConnectionRads(); params.offMeshConDir = m_geom->getOffMeshConnectionDirs(); params.offMeshConAreas = m_geom->getOffMeshConnectionAreas(); params.offMeshConFlags = m_geom->getOffMeshConnectionFlags(); params.offMeshConUserID = m_geom->getOffMeshConnectionId(); params.offMeshConCount = m_geom->getOffMeshConnectionCount(); params.walkableHeight = m_agentHeight; params.walkableRadius = m_agentRadius; params.walkableClimb = m_agentMaxClimb; rcVcopy(params.bmin, m_pmesh->bmin); rcVcopy(params.bmax, m_pmesh->bmax); params.cs = config.cs; params.ch = config.ch; params.buildBvTree = true; if (!dtCreateNavMeshData(&params, &navData, &navDataSize)) { logger::log("Could not build Detour simple_navmesh."); return false; } m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { dtFree(navData); logger::log("Could not create Detour simple_navmesh"); return false; } dtStatus status; status = m_navMesh->init(navData, navDataSize, DT_TILE_FREE_DATA); if (dtStatusFailed(status)) { dtFree(navData); logger::log("Could not init Detour simple_navmesh"); return false; } status = m_navQuery->init(m_navMesh, 2048); if (dtStatusFailed(status)) { logger::log("Could not init Detour simple_navmesh query"); return false; } m_ctx->stopTimer(RC_TIMER_TOTAL); // Show performance stats. //duLogBuildTimes(*m_ctx, m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)); logger::log(fmt::format("Polymesh: {0} vertices {1} polygons", m_pmesh->nverts, m_pmesh->npolys)); // m_totalBuildTimeMs = m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f; //if (m_tool) // m_tool->init(this); //initToolStates(this); // return true; }
[ "colingilbert86@gmail.com" ]
colingilbert86@gmail.com
6d488eb8ea0e16ed0ed73b3243eb37f876061625
f769e4df3e80746adadf5ef3c843dda5212809cf
/chuck-norris-joke-part2/HoundCpp/HoundJSON/AreaCodeInfoNuggetJSON.h
ecc9737331ba6479331ef4edfc3d7e009528e871
[]
no_license
jiintonic/weekend-task
0758296644780e172a07b2308ed91d7e5a51b77d
07ec0ba5a0f809d424d134d33e0635376d290c69
refs/heads/master
2020-03-30T09:07:29.518881
2018-10-03T15:13:58
2018-10-03T15:13:58
151,061,148
1
0
null
null
null
null
UTF-8
C++
false
false
10,776
h
/* file "AreaCodeInfoNuggetJSON.h" */ /* Generated automatically by Classy JSON. */ #ifndef AREACODEINFONUGGETJSON_H #define AREACODEINFONUGGETJSON_H #pragma interface #include "InformationNuggetJSON.h" #include "JSONRep.h" #include "JSONHoldingGenerator.h" #include "JSONObjectGenerator.h" #include "JSONStringGenerator.h" #include "JSONHandler.h" #include "JSONCheckingHandler.h" #include "ReferenceCounted.h" #include "RCHandle.h" #include "JSONParse.h" #include <stdlib.h> #include <stdio.h> #include <assert.h> class AreaCodeInfoNuggetJSON : public InformationNuggetJSON { private: AreaCodeInfoNuggetJSON(const AreaCodeInfoNuggetJSON &); AreaCodeInfoNuggetJSON & operator=(const AreaCodeInfoNuggetJSON &other); public: AreaCodeInfoNuggetJSON(void); virtual ~AreaCodeInfoNuggetJSON(void); const char * getNuggetKind(void) const; virtual const char *getAreaCodeInfoNuggetKind(void) const = 0; virtual size_t extraAreaCodeInfoNuggetComponentCount(void) const = 0; virtual const char *extraAreaCodeInfoNuggetComponentKey(size_t component_num) const = 0; virtual JSONValue *extraAreaCodeInfoNuggetComponentValue(size_t component_num) = 0; virtual const JSONValue *extraAreaCodeInfoNuggetComponentValue(size_t component_num) const = 0; virtual JSONValue *extraAreaCodeInfoNuggetLookup(const char *field_name) = 0; virtual const JSONValue *extraAreaCodeInfoNuggetLookup(const char *field_name) const = 0; size_t extraInformationNuggetComponentCount(void) const { size_t result = 1; result += extraAreaCodeInfoNuggetComponentCount(); return result; } const char *extraInformationNuggetComponentKey(size_t component_num) const { if (component_num == 0) return "AreaCodeInfoNuggetKind"; return extraAreaCodeInfoNuggetComponentKey((component_num - 1)); } JSONValue *extraInformationNuggetComponentValue(size_t component_num) { if (component_num == 0) return new JSONStringValue(getAreaCodeInfoNuggetKind()); return extraAreaCodeInfoNuggetComponentValue((component_num - 1)); } const JSONValue *extraInformationNuggetComponentValue(size_t component_num) const { if (component_num == 0) return new JSONStringValue(getAreaCodeInfoNuggetKind()); return extraAreaCodeInfoNuggetComponentValue((component_num - 1)); } JSONValue *extraInformationNuggetLookup(const char *field_name) { if (strcmp(field_name, "AreaCodeInfoNuggetKind") == 0) return new JSONStringValue(getAreaCodeInfoNuggetKind()); return extraAreaCodeInfoNuggetLookup(field_name); } const JSONValue *extraInformationNuggetLookup(const char *field_name) const { if (strcmp(field_name, "AreaCodeInfoNuggetKind") == 0) return new JSONStringValue(getAreaCodeInfoNuggetKind()); return extraAreaCodeInfoNuggetLookup(field_name); } virtual void extraAreaCodeInfoNuggetAppendPair(const char *key, JSONValue *new_component) = 0; virtual void extraAreaCodeInfoNuggetSetField(const char *key, JSONValue *new_component) = 0; void extraInformationNuggetAppendPair(const char *key, JSONValue *new_component) { if (strcmp(key, "AreaCodeInfoNuggetKind") == 0) return; extraAreaCodeInfoNuggetAppendPair(key, new_component); } void extraInformationNuggetSetField(const char *key, JSONValue *new_component) { if (strcmp(key, "AreaCodeInfoNuggetKind") == 0) return; extraAreaCodeInfoNuggetSetField(key, new_component); } virtual void write_as_json(JSONHandler *handler) const { handler->start_object(); write_fields_as_json(handler); handler->finish_object(); } virtual void write_fields_as_json(JSONHandler *handler) const { InformationNuggetJSON::write_fields_as_json(handler); handler->pair("AreaCodeInfoNuggetKind", getAreaCodeInfoNuggetKind()); } virtual const char *missing_field_error(void) const { return NULL; } static AreaCodeInfoNuggetJSON *from_json(JSONValue *json_value, bool ignore_extras = false); static AreaCodeInfoNuggetJSON *from_text(const char *text, bool ignore_extras = false) { AreaCodeInfoNuggetJSON *result; { JSONHoldingGenerator<Generator, RCHandle<AreaCodeInfoNuggetJSON>, AreaCodeInfoNuggetJSON *, bool> generator("Type AreaCodeInfoNugget", ignore_extras); parse_json_value(text, "Text for AreaCodeInfoNuggetJSON", &generator); assert(generator.have_value); result = generator.value.referenced(); result->add_reference(); }; result->remove_reference_no_delete(); return result; } static AreaCodeInfoNuggetJSON *from_file(FILE *fp, const char *file_name, bool ignore_extras = false) { AreaCodeInfoNuggetJSON *result; { JSONHoldingGenerator<Generator, RCHandle<AreaCodeInfoNuggetJSON>, AreaCodeInfoNuggetJSON *, bool> generator("Type AreaCodeInfoNugget", ignore_extras); parse_json_value(fp, file_name, &generator); assert(generator.have_value); result = generator.value.referenced(); result->add_reference(); }; result->remove_reference_no_delete(); return result; } class Generator : public InformationNuggetJSON::Generator { private: class UnknownFieldGenerator : public JSONValueHandler { public: bool ignore; std::vector<std::string> field_names; std::vector<RCHandle<JSONValue> > field_values; string_index *index; UnknownFieldGenerator(bool init_ignore) : ignore(init_ignore) { index = create_string_index(); } ~UnknownFieldGenerator(void) { destroy_string_index(index); } protected: void new_value(JSONValue *item) { if (ignore) return; assert(field_names.size() == (field_values.size() + 1)); enter_into_string_index(index, field_names[field_values.size()].c_str(), item); field_values.push_back(item); } public: void reset() { field_names.clear(); field_values.clear(); destroy_string_index(index); index = create_string_index(); } }; UnknownFieldGenerator unknownFieldGenerator; JSONHoldingGenerator<JSONStringGenerator, std::string, const char *> keyGenerator; protected: void start(void) { } JSONHandler *start_field(const char *field_name) { JSONHandler *result = start_known_field(field_name); if (result != NULL) return result; assert(unknownFieldGenerator.field_names.size() == unknownFieldGenerator.field_values.size()); if (unknownFieldGenerator.ignore) { assert(unknownFieldGenerator.field_names.size() == 0); } else { unknownFieldGenerator.field_names.push_back(field_name); } return &unknownFieldGenerator; } void finish_field(const char *field_name, JSONHandler *field_handler) { } void finish(void) { if (!(keyGenerator.have_value)) throw("The `AreaCodeInfoNuggetKind' field is missing."); if (!(strcmp(getInformationNuggetJSONKey().c_str(), "AreaCodeInfoNugget") == 0)) throw("The key field has a value other than `AreaCodeInfoNugget'."); AreaCodeInfoNuggetJSON *result = createForKey(keyGenerator.value.c_str(), unknownFieldGenerator.index); assert(result != NULL); RCHandle<AreaCodeInfoNuggetJSON> result_holder = result; finish(result); size_t extra_count = unknownFieldGenerator.field_names.size(); assert(extra_count == unknownFieldGenerator.field_values.size()); for (size_t extra_num = 0; extra_num < extra_count; ++extra_num) { result->extraAreaCodeInfoNuggetAppendPair(unknownFieldGenerator.field_names[extra_num].c_str(), unknownFieldGenerator.field_values[extra_num].referenced()); } unknownFieldGenerator.field_names.clear(); unknownFieldGenerator.field_values.clear(); destroy_string_index(unknownFieldGenerator.index); unknownFieldGenerator.index = create_string_index(); const char *missing_field_error = result->missing_field_error(); if (missing_field_error != NULL) error(missing_field_error); handle_result(result); } std::string getAreaCodeInfoNuggetJSONKey(void) { if (!(keyGenerator.have_value)) throw("The `AreaCodeInfoNuggetKind' field is missing."); return keyGenerator.value; } void handle_result(InformationNuggetJSON *new_result) { handle_result((AreaCodeInfoNuggetJSON *)new_result); } void finish(AreaCodeInfoNuggetJSON *result) { InformationNuggetJSON::Generator::finish(result); } virtual void handle_result(AreaCodeInfoNuggetJSON *new_result) = 0; virtual JSONHandler *start_known_field(const char *field_name) { if (strcmp(field_name, "AreaCodeInfoNuggetKind") == 0) { keyGenerator.reset(); return &keyGenerator; } return InformationNuggetJSON::Generator::start_known_field(field_name); } public: Generator(bool ignore_extras = false) : InformationNuggetJSON::Generator(ignore_extras), unknownFieldGenerator(ignore_extras), keyGenerator("key field \"AreaCodeInfoNuggetKind\" of the AreaCodeInfoNugget class") { set_what("the AreaCodeInfoNugget class"); } ~Generator(void) { } void reset(void) { InformationNuggetJSON::Generator::reset(); unknownFieldGenerator.reset(); } }; static AreaCodeInfoNuggetJSON *createForKey(const char *key, string_index *other_field_index); }; #endif /* AREACODEINFONUGGETJSON_H */
[ "ching-chuan.yang@daimler.com" ]
ching-chuan.yang@daimler.com
582de7fc41e34d0fdec8d8ea56abf0ac561f0749
9488dc8080b4c2534aa421744c66bb8f755ff41d
/C++/Projects/Game/Game/DialogState.cpp
e45c1185c780a64509f1ebbfcad188d3166fca38
[]
no_license
Kn1MS/SoftForAll
2e201f18e7de5a34d6fbf2ba163703831e367ff8
221dc13e66690db6a92eab721c5db9a1c7c91743
refs/heads/master
2021-01-20T10:04:37.943122
2017-05-04T16:06:29
2017-05-04T16:06:29
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
9,347
cpp
#include "../Include/DialogState.hpp" #include "../Include/Button.hpp" #include "../Include/Utility.hpp" #include "../Include/ResourceHolder.hpp" #include <SFML/Graphics/RectangleShape.hpp> #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Graphics/View.hpp> DialogState::DialogState(StateStack& stack, Context context) : State(stack, context) , textNumber(0) , mTexture(context.textures->get(Textures::DialogBox)) , mSprite() , mText() , mTalking() , mGUIContainer() , mDialogText() , mDialogTalking() { sf::Vector2f windowSize(context.window->getView().getSize()); sf::Vector2f windowCenter(context.window->getView().getCenter()); mTalking.setFont(context.fonts->get(Fonts::Main)); mTalking.setCharacterSize(24); mText.setFont(context.fonts->get(Fonts::Main)); mText.setCharacterSize(18); mText.setFillColor(sf::Color::Black); mSprite.setTexture(mTexture); mSprite.setScale(windowSize.x / mSprite.getLocalBounds().width, 1.5f); switch(context.playerInfo->mDialogNumber) { case 0: addText(L"Зная, что силы Зла начнут наступление с Теневых Земель, находящихся за Чёрным Хребтом на дальнем востоке королевства, герой Стратклайда отправляется на Восточную долину, принявшую на себя основной удар во время Великой Войны десять лет назад.", L"Повествование"); addText(L"За десять лет, конечно, местные леса восстановиться не успели, но вместо гиблого пустыря, напоминающего скорее мёртвую пустыню, сейчас это место представляло собой покрытые зеленью холмы и луга. И именно сюда сейчас прибыли первые порождения Тьмы.", L"Повествование"); break; case 1: addText("Hello, World! My name is Strange, I'm Archer from Strathclyde.", "Arantir"); addText(L"Это русский язык. Странно, что он нормально отображается...", L"Арантир"); addText("It's English. It's normal that there are not any errors.", "Arantir"); break; case 2: addText(L"Проклятье...", L"Сэр Освальд"); addText(L"В чём проблема?", L"Арантир"); addText(L"Святой Дух, мои глаза не обманывают меня?!", L"Сэр Освальд"); addText(L"Нет, сэр рыцарь. Так что такое?", L"Арантир"); addText(L"Герой Стратклайда! Я уж начал думать, что всё пропало...", L"Сэр Освальд"); addText(L"...", L"Арантир"); addText(L"Прошу прощения, меня зовут сэр Освальд, я рыцарь ордена Священного Света. Вместе с моим давним товарищем - сэром Генрихом, мы отозвались на призыв короля действовать против сил Зла на востоке и вдвоём двинулись в эти места. Когда мы наткнулись на эту пещеру, Генрих решил заглянуть внутрь,мне сказал ждать снаружи.", L"Сэр Освальд"); addText(L"Не успело пройти и нескольких секунд, как я услышал его удаляющийся крик и в этот момент прямо передо мной опустилась эта дверь... Я опасаюсь худшего. Я не хочу грузить вас чужими заботами, господин, да к тому же это моя вина, что я отпустил Генриха туда одного... но всё же я был бы вамблагодарен, если бы вы смогли как-нибудь помочь....", L"Сэр Освальд"); addText(L"М-м... Возможно я смог бы что-нибудь сделать... А может и нет.", L"Арантир"); break; case 3: addText(L"На механизме вы видите причудиво закручивающееся углубление. Сюда бы подошло что - нибудь в форме шестиугольной звезды", L"Повествование"); break; case 4: addText(L"На теле командира дворфов вы нашли странной формы камень в виде шестиугольной звезды", L"Повествование"); break; case 5: addText(L"Вы вкладываете камень в разъём и он, крутясь и опускаясь, достигает дна механизма. Со стороны раздаётся звук отходящей каменной двери", L"Повествование"); break; case 6: addText(L"Прочь, тёмные твари! Я буду биться до конца!", L"Сэр Генрих"); addText(L"Сэр Генрих?", L"Арантир"); addText(L"Откуда вы знаете моё имя, отродья Преисподней!?", L"Сэр Генрих"); addText(L"Сэр Освальд мне его сказал.", L"Арантир"); addText(L"Освальд?", L"Сэр Генрих"); // В: Тут он типа пару шагов делает, так? // О: Ничего не знаю про шаги... addText(L"Святые лики, да вы же Герой Стратклайда!", L"Сэр Генрих"); addText(L"Да-да, это я...", L"Арантир"); addText(L"Слава Святым, я спасён. Немного прошёл во тьму, оступился и упал на самое дно пещеры. Там стал отступать от приближающихся дворфов и гоблинов, а потом... А потом одного прирезал и вдруг тьма. Думал, что всё, дни мои сочтены.", L"Сэр Генрих"); addText(L"Сэр Освальд ждёт вас наверху.", L"Арантир"); addText(L"Благодарю вас, господин. Сейчас передохну немного и пойду наверх.", L"Сэр Генрих"); addText(L"Ага...", L"Арантир"); break; case 255: addText(L"Это русский язык. Странно, что он нормально отображается...", L"Арантир"); break; default: addText("Invalid dialog type.", "Error"); break; } setText(textNumber); auto nextButton = std::make_shared<GUI::Button>(*context.fonts, *context.textures); nextButton->setPosition(windowCenter.x + windowSize.x / 2.f - 220.f, windowCenter.y + windowSize.y / 2.f - 107.f); nextButton->setText(L"Дальше"); nextButton->setCallback([this] () { if (textNumber == mDialogText.size() - 1) { requestStackPop(); } else { textNumber++; setText(textNumber); } }); mGUIContainer.pack(nextButton); auto skipButton = std::make_shared<GUI::Button>(*context.fonts, *context.textures); skipButton->setPosition(windowCenter.x + windowSize.x / 2.f - 220.f, windowCenter.y + windowSize.y / 2.f - 57.f); skipButton->setText(L"Пропустить"); skipButton->setCallback([this]() { requestStackPop(); }); mGUIContainer.pack(skipButton); } void DialogState::addText(sf::String text, sf::String talking) { mDialogText.push_back(text); mDialogTalking.push_back(talking); } void DialogState::setText(size_t number) { sf::String& text = mDialogText[number]; for (size_t i = 0; i < text.getSize(); i++) { if (i % static_cast<int>(mSprite.getGlobalBounds().width / (mText.getCharacterSize() - 5.f)) == 0 && i > 0) text.insert(i, "\n"); } mText.setString(text); mTalking.setString(mDialogTalking[number]); } void DialogState::draw() { sf::RenderWindow& window = *getContext().window; window.setView(window.getDefaultView()); sf::Vector2f center = window.getView().getCenter(); sf::Vector2f size = window.getView().getSize(); mSprite.setScale(size.x / mSprite.getLocalBounds().width, 1.5f); mText.setPosition(center.x - size.x / 2.f + 20.f, center.y + size.y / 2.f - mSprite.getGlobalBounds().height + 10.f); mTalking.setPosition(center.x - size.x / 2.f + 20.f, center.y + size.y / 2.f - mSprite.getGlobalBounds().height - 30.f); mSprite.setPosition(center.x - size.x / 2.f, center.y + size.y / 2.f - mSprite.getGlobalBounds().height); sf::RectangleShape backgroundShape; backgroundShape.setFillColor(sf::Color(0, 0, 0, 150)); backgroundShape.setSize(window.getView().getSize()); window.draw(backgroundShape); window.draw(mSprite); window.draw(mText); window.draw(mTalking); window.draw(mGUIContainer); } bool DialogState::update(sf::Time) { return false; } bool DialogState::handleEvent(const sf::Event& event) { /* if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) requestStackPush(States::Pause); return true; */ mGUIContainer.handleEvent(event); return false; }
[ "vasar007@yandex.ru" ]
vasar007@yandex.ru
337a0cc1d8fe51573ac4451afe88fd40bcc478cf
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/ash/touch/touch_hud_debug.h
40558f22b3c078139198c4262293a91258ae7e0e
[ "BSD-3-Clause" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
2,314
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_TOUCH_TOUCH_HUD_DEBUG_H_ #define ASH_TOUCH_TOUCH_HUD_DEBUG_H_ #include <stdint.h> #include <map> #include <memory> #include "ash/ash_export.h" #include "ash/touch/touch_observer_hud.h" #include "base/macros.h" #include "base/values.h" namespace views { class Label; class View; } namespace ash { class TouchHudCanvas; class TouchLog; // A heads-up display to show touch traces on the screen and log touch events. // As a derivative of TouchObserverHUD, objects of this class manage their own // lifetime. class ASH_EXPORT TouchHudDebug : public TouchObserverHUD { public: enum Mode { FULLSCREEN, REDUCED_SCALE, INVISIBLE, }; explicit TouchHudDebug(aura::Window* initial_root); // Returns the log of touch events for all displays as a dictionary mapping id // of each display to its touch log. static std::unique_ptr<base::DictionaryValue> GetAllAsDictionary(); // Changes the display mode (e.g. scale, visibility). Calling this repeatedly // cycles between a fixed number of display modes. void ChangeToNextMode(); // Returns log of touch events as a list value. Each item in the list is a // trace of one touch point. std::unique_ptr<base::ListValue> GetLogAsList() const; Mode mode() const { return mode_; } // Overriden from TouchObserverHUD. void Clear() override; private: ~TouchHudDebug() override; void SetMode(Mode mode); void UpdateTouchPointLabel(int index); // Overriden from TouchObserverHUD. void OnTouchEvent(ui::TouchEvent* event) override; void OnDisplayMetricsChanged(const display::Display& display, uint32_t metrics) override; void SetHudForRootWindowController(RootWindowController* controller) override; void UnsetHudForRootWindowController( RootWindowController* controller) override; static const int kMaxTouchPoints = 32; Mode mode_; std::unique_ptr<TouchLog> touch_log_; TouchHudCanvas* canvas_; views::View* label_container_; views::Label* touch_labels_[kMaxTouchPoints]; DISALLOW_COPY_AND_ASSIGN(TouchHudDebug); }; } // namespace ash #endif // ASH_TOUCH_TOUCH_HUD_DEBUG_H_
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
d3b76f62ea2253d6384ddea9d15e3d389e86428e
d72ba429177702891d94d121964cccb1ebfaa4f0
/src/highScore.h
5a1bd7765b24c941582a2e040aac5bc3982e4b24
[ "MIT" ]
permissive
tatokis/minesweeper
a32cfb026bd5dc567f1b70fa1a2965f279a39062
65cd025364ea72fe7e333a7524d803e6139cfed2
refs/heads/master
2020-09-11T02:16:14.111093
2019-10-25T23:11:29
2019-10-25T23:11:29
221,907,802
1
0
MIT
2019-11-15T11:11:36
2019-11-15T11:11:36
null
UTF-8
C++
false
false
3,178
h
//-------------------------------------------------------------------------------------------------- // // The MIT License (MIT) // // 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. // //-------------------------------------------------------------------------------------------------- // // Copyright (c) 2017 Nic Holthaus // //-------------------------------------------------------------------------------------------------- // // ATTRIBUTION: // // //-------------------------------------------------------------------------------------------------- // /// @file highScore.h /// @brief Class to contain a minesweeper high score // //-------------------------------------------------------------------------------------------------- #pragma once //------------------------- // INCLUDES //------------------------- #include <QString> #include <QDataStream> #include <QDateTime> //------------------------- // FORWARD DECLARATIONS //------------------------- class HighScoreModel; //-------------------------------------------------------------------------------------------------- // CLASS HIGHSCORE //-------------------------------------------------------------------------------------------------- class HighScore : public QObject { Q_OBJECT public: enum Difficulty { beginner, intermediate, expert, custom, }; Q_ENUM(Difficulty); public: HighScore() = default; HighScore(QString name, Difficulty difficulty, quint32 score, QDateTime date); HighScore(const HighScore& other); HighScore& operator=(const HighScore& other); QString name() const; Difficulty difficulty() const; quint32 score() const; QDateTime date() const; void setName(QString name); void setDifficultty(Difficulty difficulty); void setScore(quint32 score); void setDate(QDateTime date); bool operator<(const HighScore& rhs) const; bool operator==(const HighScore& rhs) const; friend HighScoreModel; private: QString m_name; Difficulty m_difficulty; quint32 m_score; QDateTime m_date; }; Q_DECLARE_METATYPE(HighScore); QDataStream &operator<<(QDataStream &out, const HighScore&); QDataStream &operator>>(QDataStream &in, HighScore&);
[ "nholthaus@gmail.com" ]
nholthaus@gmail.com
21f32ea16ceded35ebfe03d5f73b00b342bb1801
a9116a2fa6e525f2f6b3a3c79377dcc656593bd0
/Client Source/src/AppPrintConfig/msgs.h
b113dcabe4f1a99c0f3020f658cc26e313843d06
[]
no_license
ldsamburn/nt-tony
f916267e4fdfadd40d71dd6f16b63a25f437cee6
89ff243401957678f71a90e33ee8f0596d3ec7e8
refs/heads/master
2021-01-12T03:01:19.444901
2017-01-05T21:16:32
2017-01-05T21:16:32
78,148,560
0
0
null
null
null
null
UTF-8
C++
false
false
1,733
h
/* Copyright(c)2002 Northrop Grumman Corporation All Rights Reserved This material may be reproduced by or for the U.S. Government pursuant to the copyright license under the clause at Defense Federal Acquisition Regulation Supplement (DFARS) 252.227-7013 (NOV 1995). */ // Make sure have stdafx.h #ifndef __AFXWIN_H__ #error include "stdafx.h" before including this file #endif #ifndef _INCLUDE_MSGS_H_ #define _INCLUDE_MSGS_H_ #include "privapis.h" #include "ntcssmsg.h" #include "msgdefs.h" #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 ///////////////////////////////////////////////////////////////////////////// // CmsgGETOTYPEINI // ______________ class CmsgGETOTYPEINI : public CNtcssMEM_MSG_ALLOC_Msg { public: CmsgGETOTYPEINI(); ~CmsgGETOTYPEINI(); BOOL DoItNow() { return(CNtcssMEM_MSG_ALLOC_Msg::DoItNow()); }; BOOL Load(CString strHostname); BOOL UnLoad(char *ini_file_name_path); protected: Sgetotypeini_svrmsgrec *svr_msg_ptr; #ifdef _NTCSS_MSG_DEBUG_ virtual void ShowMsg(CString *show_buf);#include "stdafx.h" #endif }; ///////////////////////////////////////////////////////////////////////////// // CmsgPUTOTYPEINI // ______________ class CmsgPUTOTYPEINI : public CNtcssMEM_MSG_ALLOC_Msg { public: CmsgPUTOTYPEINI(); ~CmsgPUTOTYPEINI(); BOOL DoItNow() { return(CNtcssMEM_MSG_ALLOC_Msg::DoItNow()); }; BOOL Load(const char *file_name,CString strHostname); BOOL UnLoad(char *log_file_name_path); protected: Sputotypeini_svrmsgrec *svr_msg_ptr; #ifdef _NTCSS_MSG_DEBUG_ virtual void ShowMsg(CString *show_buf); #endif }; #endif
[ "ldsamburn@hotmail.com" ]
ldsamburn@hotmail.com
c862ff646547f0fddb8b8a3aba7dd70fa1f740e5
aedec0779dca9bf78daeeb7b30b0fe02dee139dc
/Modules/Registration/include/mirtk/PointSetDistance.h
eb1dbb9e18258b3878e5b84d21bd12bf642f21e7
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BioMedIA/MIRTK
ca92f52b60f7db98c16940cd427a898a461f856c
973ce2fe3f9508dec68892dbf97cca39067aa3d6
refs/heads/master
2022-08-08T01:05:11.841458
2022-07-28T00:03:25
2022-07-28T10:18:00
48,962,880
171
78
Apache-2.0
2022-07-28T10:18:01
2016-01-03T22:25:55
C++
UTF-8
C++
false
false
7,744
h
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2015 Imperial College London * Copyright 2013-2015 Andreas Schuh * * 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. */ #ifndef MIRTK_PointSetDistance_H #define MIRTK_PointSetDistance_H #include "mirtk/DataFidelity.h" #include "mirtk/Array.h" #include "mirtk/Vector3D.h" #include "mirtk/PointSetDistanceMeasure.h" #include "mirtk/RegisteredPointSet.h" namespace mirtk { /** * Base class for point set distance measures */ class PointSetDistance : public DataFidelity { mirtkAbstractMacro(PointSetDistance); // --------------------------------------------------------------------------- // Types public: /// Type of gradient w.r.t a single transformed data point typedef Vector3D<double> GradientType; // --------------------------------------------------------------------------- // Attributes protected: /// First point set mirtkPublicAggregateMacro(RegisteredPointSet, Target); /// Second point set mirtkPublicAggregateMacro(RegisteredPointSet, Source); /// Memory for (non-parametric) gradient w.r.t points of target mirtkComponentMacro(GradientType, GradientWrtTarget); /// Memory for (non-parametric) gradient w.r.t points of source mirtkComponentMacro(GradientType, GradientWrtSource); /// Whether Update has not been called since initialization mirtkAttributeMacro(bool, InitialUpdate); /// Allocate memory for (non-parametric) gradient w.r.t points of target void AllocateGradientWrtTarget(int); /// Allocate memory for (non-parametric) gradient w.r.t points of source void AllocateGradientWrtSource(int); // --------------------------------------------------------------------------- // Construction/Destruction protected: /// Constructor PointSetDistance(const char * = "", double = 1.0); /// Copy constructor PointSetDistance(const PointSetDistance &, int = -1, int = -1); /// Assignment operator PointSetDistance &operator =(const PointSetDistance &); /// Copy attributes from other point set distance measure void CopyAttributes(const PointSetDistance &, int = -1, int = -1); public: /// Instantiate specified similarity measure static PointSetDistance *New(PointSetDistanceMeasure, const char * = "", double = 1.0); /// Destructor virtual ~PointSetDistance(); // --------------------------------------------------------------------------- // Initialization protected: /// Initialize distance measure once input and parameters have been set void Initialize(int, int); /// Reinitialize distance measure after change of input topology /// /// This function is called in particular when an input surface has been /// reparameterized, e.g., by a local remeshing filter. void Reinitialize(int, int); public: /// Initialize distance measure once input and parameters have been set virtual void Initialize(); /// Reinitialize distance measure after change of input topology /// /// This function is called in particular when an input surface has been /// reparameterized, e.g., by a local remeshing filter. virtual void Reinitialize(); // --------------------------------------------------------------------------- // Evaluation /// Update moving input points and internal state of distance measure virtual void Update(bool = true); protected: /// Compute non-parametric gradient w.r.t points of given data set /// /// \param[in] target Transformed point set. /// \param[out] gradient Non-parametric gradient of point set distance measure. virtual void NonParametricGradient(const RegisteredPointSet *target, GradientType *gradient) = 0; /// Convert non-parametric gradient of point set distance measure into /// gradient w.r.t transformation parameters /// /// This function calls Transformation::ParametricGradient of the /// transformation to apply the chain rule in order to obtain the gradient /// of the distance measure w.r.t the transformation parameters. /// It adds the weighted gradient to the final registration energy gradient. /// /// \param[in] target Transformed point set. /// \param[in] np_gradient Point-wise non-parametric gradient. /// \param[in,out] gradient Gradient to which the computed parametric gradient /// is added, after multiplication by the given \p weight. /// \param[in] weight Weight of point set distance measure. virtual void ParametricGradient(const RegisteredPointSet *target, const GradientType *np_gradient, double *gradient, double weight); /// Evaluate gradient of point set distance measure /// /// This function calls the virtual NonParametricGradient function to be /// implemented by subclasses for each transformed input point set to obtain /// the gradient of the point set distance measure. It then converts this gradient /// into a gradient w.r.t the transformation parameters using the ParametricGradient. /// /// If both target and source point sets are transformed by different transformations, /// the resulting gradient vector contains first the derivative values w.r.t /// the parameters of the target transformation followed by those computed /// w.r.t the parameters of the source transformation. If both point sets are /// transformed by the same transformation, the sum of the derivative values /// is added to the resulting gradient vector. This is in particular the case /// for a velocity based transformation model which is applied to deform both /// point sets "mid-way". Otherwise, only one input point set is transformed /// (usually the target) and the derivative values of only the respective /// transformation parameters added to the gradient vector. /// /// \sa NonParametricGradient, ParametricGradient /// /// \param[in,out] gradient Gradient to which the computed gradient of the /// point set distance measure is added after /// multiplying by the given similarity \p weight. /// \param[in] step Step length for finite differences (unused). /// \param[in] weight Weight of point set distance measure. virtual void EvaluateGradient(double *gradient, double step, double weight); // --------------------------------------------------------------------------- // Debugging public: /// Write input of data fidelity term virtual void WriteDataSets(const char *, const char *, bool = true) const; /// Write gradient of data fidelity term w.r.t each transformed input virtual void WriteGradient(const char *, const char *) const; protected: /// Write gradient of data fidelity term w.r.t each transformed input virtual void WriteGradient(const char *, const RegisteredPointSet *, const GradientType *, const Array<int> * = NULL) const; }; } // namespace mirtk #endif // MIRTK_PointSetDistance_H
[ "andreas.schuh.84@gmail.com" ]
andreas.schuh.84@gmail.com
01e29b3599885beb2aa3eff998426e160fdef6cc
576a0f1512bd83a93da56b141ab0bc4093428ce1
/PruebasInerencia/PruebasInerencia/main.cpp
23c909bde1fcc3cadf2d7101709252cbcba15563
[]
no_license
henrykalex/analisisModSistSoft
4379b56de3fc2d0d8324c76c0463b975de38d05f
27c09b4c2e506d4dc78a68ecad348652cedce64a
refs/heads/master
2021-01-13T04:49:13.537352
2017-05-03T14:26:25
2017-05-03T14:26:25
78,641,666
0
0
null
2017-01-18T15:45:28
2017-01-11T13:29:18
null
UTF-8
C++
false
false
633
cpp
// // main.cpp // PruebasInerencia // // Created by Henry on 13/02/17. // Copyright © 2017 Henryk. All rights reserved. // #include <iostream> #include <vector> #include "Papa.h" #include "Hijo.h" int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; Papa nP1(5); std::cout <<nP1.muestraNum()<<"\n"; Hijo nH1(6.6f); std::cout <<nH1.muestraNum()<<"\n"; std::cout <<nH1.muestraTam()<<"\n"; std::vector<Papa*> vec; Papa::facM(); vec.push_back(&nH1); std::cout << vec[0]->muestraNum()<<"\n"; return 0; }
[ "Enrique@MacBook-Pro-de-Enrique-3.local" ]
Enrique@MacBook-Pro-de-Enrique-3.local