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
7395c930bef12ba020a5aba9133c2b29da2d6bde
dff2935d74bc50140eb757079732ed5237146d6b
/Juce Projects/AudioManagementTemplate/Source/BasicAudioProcessor.cpp
0431a62e80b28ecb31e9ee005dca91154bd80a53
[]
no_license
brenthompson2/JUCE-Summer-Project
242639e0baefd6b636b10ee5a1392c198f5b3780
c0b60d71cc238a112b35c2e91324a9f4f2d086ca
refs/heads/master
2021-07-14T06:51:31.576271
2017-10-19T21:09:53
2017-10-19T21:09:53
94,351,946
2
0
null
null
null
null
UTF-8
C++
false
false
1,742
cpp
/* ============================================================================== BasicAudioProcessor.cpp Updated: 08/06/17 Author: Brendan Thompson A Basic Audio Processor that inherits from the AudioProcessor class ============================================================================== */ #include "BasicAudioProcessor.h" #include "BasicAudioProcessorEditor.h" //============================================================================== // Constructor & Destructor BasicAudioProcessor::BasicAudioProcessor(){ //BasicAudioProcessorEditor* theEditor = createEditor(); } BasicAudioProcessor::~BasicAudioProcessor(){ } // Create The Editor AudioProcessorEditor* BasicAudioProcessor::createEditor(){ return new BasicAudioProcessorEditor (*this); } // This creates new instances of the processor? I don't think it's used AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new BasicAudioProcessor; } //============================================================================== // Public Audio Functions void BasicAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlockExpected){ } void BasicAudioProcessor::processBlock (AudioBuffer<double>& buffer, MidiBuffer& midiMessages){ process (buffer, midiMessages, delayBufferDouble); } void BasicAudioProcessor::releaseResources(){ } //============================================================================== // Private Methods: template <typename FloatType> void BasicAudioProcessor::process (AudioBuffer<FloatType>& buffer, MidiBuffer& midiMessages, AudioBuffer<FloatType>& delayBuffer){ }
[ "brenthompson2@gmail.com" ]
brenthompson2@gmail.com
dbacec5d5d3801ab15b513051aadd8a637fa69e6
eeea48b3a280f835cc2b485bb3dca0ca45d2abe6
/Cylinder.h
e23ea16c9f65645cb13b5e7451117bc00b2c6eca
[]
no_license
astpeepman/Graphics-pipeline-shading-OpenGL-
ad62e9fc3fc28dda4f73388f1df2a45e9cd1d231
bb9fe9c82b130226c5b7d0f7ed225ce4e574d5f3
refs/heads/master
2022-12-28T13:56:22.475776
2020-10-06T09:56:17
2020-10-06T09:56:17
301,448,801
0
0
null
null
null
null
UTF-8
C++
false
false
699
h
#include <GL/glew.h> #include <GLFW/glfw3.h> #include "3dMath.h" #include "Shader.h" class Cylinder { private: vec3 position; GLfloat radius; GLfloat height; Shader shader; mat4 model; GLuint vertexVBO, normalsVBO, texcoordVBO, indicesVBO; GLuint VAO, VBO; GLsizei indicSize; mat4 beginModel; public: Cylinder() {}; Cylinder(vec3 p, GLfloat r, Shader s, GLfloat h, int numberSlices); void draw(); void setLightParam(vec3 ambient, vec3 diff, vec3 spec); void setLightPos(vec3 p); void setViewPos(vec3 p); void setproj(mat4 prj); void setview(mat4 view); void setmaterial(vec3 am, vec3 diff, vec3 spec, GLfloat sh); void Rotate(GLfloat angle, vec3 axis); void Trans(vec3 pos); };
[ "62560939+astpeepman@users.noreply.github.com" ]
62560939+astpeepman@users.noreply.github.com
18297347bb8a782bbdecbcac62f1e1085158c8d5
dc303cfe42dbb6a0e867877837e2eacc1a899e92
/QMediaCore/EffectEditor/sources/SoftwareSource.cpp
3392b10ee2f0c847043f38bf246cab2230ffde53
[]
no_license
Romantic-LiXuefeng/QMedia
4c28a093fdea7dcfe692ad9bc67260ccf02ed950
9c12b351feeedaaa89ecf70cb347e4c10d9350fc
refs/heads/master
2023-08-26T21:06:13.147571
2021-10-20T03:21:07
2021-10-20T03:23:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,299
cpp
// // SoftwareSource.cpp // QMediaCore // // Created by spring on 20/05/2019. // Copyright © 2017 QMedia. All rights reserved. // #include "Utils/Logger.h" #include "SoftwareSource.h" #include "MediaCore/demuxer/GeneralDemuxer.h" #include "SoftwareFrameDrawer.h" #include "MediaCore/core/SteadyClock.h" #include "Utils/Logger.h" void SoftwareSource::run() { if (_demuxerIndex < 0 && _demuxerIndex < _demuxerList.size()) { LOGE("SoftwareSource::run _selectIndex < 0 or _selectIndex overflow"); return; } while (_isStarted) { bool bPacketOverCache = true; for(auto& stream : _mediaStreams) { bPacketOverCache &= (stream->getEncodedPacketQueue().size() >= _packetCacheConut); } if (bPacketOverCache) { std::this_thread::sleep_for(std::chrono::milliseconds(20)); continue; } //demuxer is read end, wait for seek or stop std::unique_lock<std::mutex> lock(_mutex); while (_isStarted && _demuxerIndex >= _demuxerList.size()) { //send empty packet to finish decode for (auto& stream : _mediaStreams) { EncodedPacket empty_packet(nullptr,std::numeric_limits<int64_t >::max()); stream->getEncodedPacketQueue().addPacket(empty_packet); } LOGI("source read end and wait"); _condition.wait(lock); } if (!_isStarted) break; EncodedPacket packet(nullptr,0); Demuxer* demuxer = _demuxerList[_demuxerIndex].get(); int readRet = demuxer->ReadPacket(packet); if (readRet >= 0) { int media_stream_idx = _stream_map[packet.getEncodedBuffer()->stream_id()]; if (media_stream_idx >= 0) { MediaStream *stream = _mediaStreams[media_stream_idx].get(); if (stream) { packet.set_ntp_time_ms(packet.ntp_time_ms() + _duration_offset); stream->getEncodedPacketQueue().addPacket(packet); } } } else if(demuxer->IsEOF()) { //TODO: Demuxer read end _demuxerIndex ++; _duration_offset += demuxer->getDuration(); if (_demuxerIndex < _demuxerList.size()) _demuxerList[_demuxerIndex]->Seek(0, _videoStreamIndex != -1 ? 0 : 1); } } } SoftwareSource::SoftwareSource(std::vector<std::string>& fileList, bool enableVideo, bool enableAudio): _fileList(fileList), _isLoaded(false), _enableVideo(enableVideo), _enableAudio(enableAudio), _videoStreamIndex(-1), _audioStreamIndex(-1), _demuxerIndex(-1){ std::memset(_stream_map, -1, sizeof(_stream_map)); _packetCacheConut = 25; } SoftwareSource::~SoftwareSource() { } bool SoftwareSource::load() { if (_isLoaded) return true; for(auto& file : _fileList) { DemuxerRef demuxer = DemuxerRef(new GeneralDemuxer()); if( demuxer->Open(file.c_str(), 0) >= 0) { if (!_isLoaded) { for (int i = 0; i < demuxer->getMediaStreamDescribes().size() && i < MAX_STREAMS; ++i) { auto stream_describes = demuxer->getMediaStreamDescribes()[i]; if (stream_describes.describe.mediatype_ == MediaType::Video && _videoStreamIndex == -1 && _enableVideo) { _stream_map[i] = static_cast<int>(_mediaStreams.size()); _mediaStreams.push_back(MediaStreamRef(new MediaStream(stream_describes))); _mediaDescs.push_back(stream_describes.describe); _videoStreamIndex = i; } else if (stream_describes.describe.mediatype_ == MediaType::Audio && _audioStreamIndex == -1 && _enableAudio) { _stream_map[i] = static_cast<int>(_mediaStreams.size()); _mediaStreams.push_back(MediaStreamRef(new MediaStream(stream_describes))); _mediaDescs.push_back(stream_describes.describe); _audioStreamIndex = i; } } } _demuxerList.push_back(demuxer); _media_duration += demuxer->getDuration(); _isLoaded = true; } } return _isLoaded; } void SoftwareSource::unload() { _media_duration = 0; std::memset(_stream_map, -1, sizeof(_stream_map)); _mediaStreams.clear(); _mediaDescs.clear(); _videoStreamIndex = -1; _audioStreamIndex = -1; _isLoaded = false; } bool SoftwareSource::isInit() { return _isLoaded; } bool SoftwareSource::start(int64_t startMSec, int64_t endMSec) { if (_isLoaded) { if (_isStarted) return true; MediaSource::start(startMSec, endMSec); _demuxerIndex = getDemuxerIndex(startMSec, _duration_offset); _demuxerList[_demuxerIndex]->Seek(startMSec - _duration_offset, _videoStreamIndex != -1 ? 0 : 1); for (auto& stream : _mediaStreams) { stream->setMaxOutputFrameNum(2); stream->start(); } _isStarted = true; _processThread = std::thread(&SoftwareSource::run, this); } return _isStarted; } void SoftwareSource::stop() { if (_isStarted) { { std::unique_lock<std::mutex> lock(_mutex); _isStarted = false; _condition.notify_one(); } if (_processThread.joinable()) _processThread.join(); for (auto& stream : _mediaStreams) { stream->stop(); } for (auto& demuxer : _demuxerList) { demuxer->Close(); } } } bool SoftwareSource::seekTo(int64_t mSec) { if (! _isStarted) return false; if (mSec > _media_time_range._end) { return false; } int64_t duration_offset; int demuxerIndex = getDemuxerIndex(mSec, duration_offset); if (demuxerIndex < 0) return false; _media_time_range._start = mSec; _duration_offset = duration_offset; _demuxerIndex = demuxerIndex; return decodeTo(mSec); } bool SoftwareSource::decodeTo(int64_t mSec, bool precise) { //check if deocde finish auto check_frame_output = [this]()->bool{ bool bRet = false; if (_videoStreamIndex >= 0) { //wait for first video decodeframe bRet = _mediaStreams[_stream_map[_videoStreamIndex]]->getDecodedFrameQueue().length() > 0; } else { //wait for first decodeframe for (auto& stream : _mediaStreams) { bRet |= stream->getDecodedFrameQueue().length() > 0; } } return bRet; }; std::unique_lock<std::mutex> lock(_mutex); _condition.notify_one(); //clear all stream cache for (auto& stream : _mediaStreams){ stream->getDecodedFrameQueue().setAbort(false); stream->flush(); } bool bRet = false; auto& demuxer_seek = _demuxerList[_demuxerIndex]; demuxer_seek->Seek(mSec - _duration_offset, _videoStreamIndex != -1 ? 0 : 1); demuxer_seek->setIgnoreBFrame(true); for (auto& stream : _mediaStreams) { stream->waitForFlush(); stream->setStartTimeLimit(precise? mSec : -1); } int flush_packet_count = 1; //decode and wait for frame output while (flush_packet_count > 0) { if (_demuxerIndex >= _demuxerList.size()) { //file lists end flush_packet_count --; //wait for decode finished if (_videoStreamIndex >= 0) _mediaStreams[_stream_map[_videoStreamIndex]]->getDecodedFrameQueue().peekFrame(); else if (_audioStreamIndex >= 0) _mediaStreams[_stream_map[_audioStreamIndex]]->getDecodedFrameQueue().peekFrame(); break; } //check break condition bRet = check_frame_output(); if (bRet) break; //check Packet OverCache condition bool bPacketOverCache = true; for(auto& stream : _mediaStreams) { bPacketOverCache &= (stream->getEncodedPacketQueue().size() >= _packetCacheConut); } if (bPacketOverCache) { std::this_thread::sleep_for(std::chrono::milliseconds(5)); continue; } //read new packet EncodedPacket packet(nullptr,0); auto& demuxer = _demuxerList[_demuxerIndex]; if (demuxer->ReadPacket(packet) >= 0) { int media_stream_idx = _stream_map[packet.getEncodedBuffer()->stream_id()]; if (media_stream_idx >= 0) { MediaStream *stream = _mediaStreams[media_stream_idx].get(); if (stream) { //packet pts add duration_offset int64_t new_pts = packet.ntp_time_ms() + _duration_offset; packet.set_ntp_time_ms(new_pts); stream->getEncodedPacketQueue().addPacket(packet); //check if ignore b frame if (new_pts >= mSec - 10) demuxer_seek->setIgnoreBFrame(false); } } } else if(demuxer->IsEOF()) { //TODO: Demuxer read end _demuxerIndex ++; _duration_offset += demuxer->getDuration(); if (_demuxerIndex < _demuxerList.size()) _demuxerList[_demuxerIndex]->Seek(0, _videoStreamIndex != -1 ? 0 : 1); else { //send empty packet to finish decode for (auto& stream : _mediaStreams) { EncodedPacket empty_packet(nullptr,std::numeric_limits<int64_t >::max()); stream->getEncodedPacketQueue().addPacket(empty_packet); } } } } demuxer_seek->setIgnoreBFrame(false); return bRet; } bool SoftwareSource::isEOF() { return _demuxerIndex >= _demuxerList.size(); } int SoftwareSource::getDemuxerIndex(int64_t time_ms, int64_t& time_offset) { int index = -1; int64_t duration = 0; for (int i = 0; i < _demuxerList.size(); ++i) { if (duration + _demuxerList[i]->getDuration() >= time_ms) { time_offset = duration; index = i; break; } duration += _demuxerList[i]->getDuration(); } return index; } VideoFrame SoftwareSource::readNextVideoFrame(int& error) { error = -1; VideoFrame videoFrame(nullptr, 0); MediaStream* stream = _mediaStreams[_stream_map[_videoStreamIndex]].get(); if (stream->getDecodedFrameQueue().length() <=0 && stream->isEnd()) { error = 1; return videoFrame; } DecodedFrame decodedFrame = stream->getDecodedFrameQueue().popFrame(); if (decodedFrame.frame_buffer_) { videoFrame = VideoFrame(std::dynamic_pointer_cast<VideoFrameBuffer>(decodedFrame.frame_buffer_),decodedFrame.render_time_ms()); error = 0; } return videoFrame; } AudioFrame SoftwareSource::readNextAudioFrame(int& error) { error = -1; AudioFrame audioFrame(nullptr, 0, 0); MediaStream* stream = _mediaStreams[_stream_map[_audioStreamIndex]].get(); if (stream->getDecodedFrameQueue().length() <=0 && stream->isEnd()) { error = 1; return audioFrame; } DecodedFrame decodedFrame = stream->getDecodedFrameQueue().popFrame(); if (decodedFrame.frame_buffer_) { audioFrame = AudioFrame(std::dynamic_pointer_cast<AudioFrameBuffer>(decodedFrame.frame_buffer_),decodedFrame.timestamp_ ,decodedFrame.render_time_ms()); error = 0; } return audioFrame; } VideoFrameDrawer* SoftwareSource::createVideoFrameDrawer() { VideoFrameDrawer* videoFrameDrawer = nullptr; RawVideoFormat videoFormat = RawVideoFormat::kUnknown; if (_videoStreamIndex >= 0) videoFormat = _mediaStreams[_stream_map[_videoStreamIndex]]->getMediaDescribe().describe._videodesc.format; switch (videoFormat) { case RawVideoFormat::kI420: case RawVideoFormat::kYV12: videoFrameDrawer = new YUVFrameDrawer(_videoTarget); break; case RawVideoFormat::kARGB: case RawVideoFormat::kBGRA: videoFrameDrawer = new RGBAFrameDrawer(_videoTarget); break; default: break; } return videoFrameDrawer; }
[ "spring_zhsp@163.com" ]
spring_zhsp@163.com
4d0cc846279d41ef7e7e7a5133f58f2be823792a
42b478ff4d1a2a440ee5a4834a19aa4d04ad3f0d
/WindowsTextSearch/test/cpps/Entry.cpp
0e87f7c665836b07db730f7392ca98ed48797150
[]
no_license
ammarsalman94/Projects
f86eff7e250f98086fab6835f34e4eb45558c4d9
aa7ed49c7ae23c288288bcf4ec119c0b57489be1
refs/heads/master
2020-12-27T07:53:48.213766
2020-02-02T19:45:44
2020-02-02T19:45:44
237,822,598
0
0
null
null
null
null
UTF-8
C++
false
false
3,004
cpp
///////////////////////////////////////////////////////////////////// // Entry.cpp - Test stub for NoSqlDb package // // Ver 1.0 // // Application: Project #1 - No-SQL Database - CSE-687 // // Platform: Dell Inspiron 5520, Win 10, Visual Studio 2015 // // Author: Ammar Salman, EECS, Syracuse University // // (313) 788-4694 hoplite.90@hotmail.com // ///////////////////////////////////////////////////////////////////// #include <iostream> #include <string> #include <vector> #include "..\RegularExpression\RegularExpression.h" #include "Element.h" #include "NoSqlDb.h" using namespace std; // test stub for Element<T> and NoSQLDB<KeyType, Type> #ifdef TEST_NOSQLDB Element<string> TestElement() { Element<string> e1; e1.SetKey("key1"); e1.SetName("element1"); e1.SetCategory("C++"); e1.SetDescription("example element"); e1.SetData("i love c++"); e1.AddChild("key2"); e1.AddChild("key3"); cout << "\n Testing Element<string> "; cout << "\n ========================= "; cout << "\n Printing element:"; cout << "\n" << e1.ToString(); cout << "\n\n Printing element to XML:"; cout << "\n" << e1.ToXMLString(); return e1; } int main() { // testing element Element<string> e1 = TestElement(); Element<string> e2; e2.SetKey("key2"); e2.SetName("element2"); e2.SetCategory("C#"); e2.SetDescription("example element two"); e2.SetData("i love c#"); e2.AddChild("key3"); e2.AddChild("key4"); cout << "\n\n\n Testing NoSQLDB<string> "; cout << "\n ================================= "; cout << "\n\n Creating database"; NoSQLDB<string> db; cout << "\n\n Adding elements to database:"; if (db.AddEntry(e1.GetKey(), e1) && db.AddEntry(e2.GetKey(), e2)) cout << "\n Entries added:\n" << e1.ToString() << "\n" << e2.ToString(); cout << "\n\n Importing Database from 'database.xml'"; db.ImportXML("database.xml"); cout << "\n" << db.ToString(); cout << "\n\n Executing query: { get data='dummy' and (name='ammar' or category='python') }"; vector<string> output = db.ExecuteQuery("get data='dummy' and (name='ammar' or category='python')"); cout << "\n obtained keys and their information:"; int size = output.size(); for (int i = 0; i < size; i++) cout << "\n Key: " << output[i] << "; Data: " << db.GetElement(output[i]).GetData() << "; Name: " << db.GetElement(output[i]).GetName() << "; Category: " << db.GetElement(output[i]).GetCategory(); cout << "\n\n Adding element using regular expression: "; cout << "\n { add key='key10' name='ammar' category='mongodb' description='testquery'"; cout << "\n data = 'something' children = 'key1,key2,key3' }"; db.ExecuteQuery("add key='key10' name='ammar' category='mongodb' description='testquery' data='something' children='key1,key2,key3'"); cout << "\n Printing out the new element:\n" << db.GetElement("key10").ToString() << "\n"; db.StoreXML("database2.xml"); return 0; } #endif
[ "hoplite.90@hotmail.com" ]
hoplite.90@hotmail.com
4c8a716bfba9cc8e25b3041c6201fa18e90e6596
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/exporter/3dsplugin/src/n3dsmaterial/nabstractpropbuilder.cc
2bee889a35355417bed7fdde40b22ce9b3110114
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,605
cc
#include "precompiled/pchn3dsmaxexport.h" #pragma warning( push, 3 ) #include "Max.h" #pragma warning( pop ) #include "n3dsmaterial/nabstractpropbuilder.h" #include "kernel/nkernelserver.h" #include "nscene/nscenenode.h" #include "nmaterial/nmaterialnode.h" nClass* nAbstractPropBuilder::nmaterialnode = 0; nClass* nAbstractPropBuilder::nsurfacenode = 0; nAbstractPropBuilder::nAbstractPropBuilder() : thisType(nAbstractPropBuilder::NONE), stringValid(false), matTypeIsValid(false) { n_assert(nKernelServer::ks); nmaterialnode = nKernelServer::ks->FindClass("nmaterialnode"); n_assert(nmaterialnode); nsurfacenode = nKernelServer::ks->FindClass("nsurfacenode"); n_assert(nsurfacenode); } int __cdecl nAbstractPropBuilder::TextureSorter(const varTexture* elm0, const varTexture* elm1) { return strcmp(elm0->varName.Get(), elm1->varName.Get() ); } int __cdecl nAbstractPropBuilder::AnimSorter( const nString* elm0, const nString* elm1) { n_assert(elm0); n_assert(elm1); return strcmp( elm0->Get(), elm1->Get() ); } int __cdecl nAbstractPropBuilder::FloatSorter(const varFloat* elm0, const varFloat* elm1) { return strcmp(elm0->varName.Get(), elm1->varName.Get() ); } int __cdecl nAbstractPropBuilder::IntSorter(const varInt* elm0, const varInt* elm1) { return strcmp(elm0->varName.Get(), elm1->varName.Get() ); } int __cdecl nAbstractPropBuilder::VectorSorter(const varVector* elm0, const varVector* elm1) { return strcmp(elm0->varName.Get(), elm1->varName.Get() ); } int __cdecl nAbstractPropBuilder::ShaderSorter(const varShader* elm0, const varShader* elm1) { return strcmp(elm0->varName.Get(), elm1->varName.Get() ); } void nAbstractPropBuilder::SetTexture ( const varTexture& var) { this->stringValid = false; varTexture var2(var); var2.texName.ToLower(); this->textures.Append ( var ); } const nAbstractPropBuilder::nSortedTextures& nAbstractPropBuilder::GetTextureArray() const { return this->textures; } nAbstractPropBuilder::nSortedTextures& nAbstractPropBuilder::GetTextureArray() { return this->textures; } void nAbstractPropBuilder::SetInt ( const varInt& var) { this->stringValid = false; this->integers.Append( var ); } void nAbstractPropBuilder::SetFloat ( const varFloat& var) { this->stringValid = false; this->floats.Append( var ); } void nAbstractPropBuilder::SetVector ( const varVector& var) { this->stringValid = false; this->vectors.Append( var ); } void nAbstractPropBuilder::SetAnim ( const nString& pathAnim) { this->stringValid = false; this->anims.Append(pathAnim); } void nAbstractPropBuilder::SetShader ( const varShader& var) { n_assert( this->thisType == NONE || this->thisType == NSURFACE); this->stringValid = false; this->thisType = NSURFACE; this->shaders.Append( var ); } void nAbstractPropBuilder::SetMaterial( const nMatTypePropBuilder& val) { n_assert( this->thisType == NONE || this->thisType == NMATERIAL ); this->stringValid = false; this->thisType = NMATERIAL; this->matType = val; this->matTypeIsValid = true; } //------------------------------------------------------------------------------ /** Set type Libaray. @parama val. The original material type for future conversion */ void nAbstractPropBuilder::SetMatType( const nMatTypePropBuilder& val) { n_assert( this->thisType == NONE || this->thisType == NMATERIAL || this->thisType == SHADERTYPELIBRARY ); this->stringValid = false; this->matType = val; this->matTypeIsValid = true; } //------------------------------------------------------------------------------ /** Set type Libaray. @param name The name's material in Library @parama val. The original material type for future conversion */ void nAbstractPropBuilder::SetMaterialTypeFromLibrary( const char* name , const nMatTypePropBuilder& val) { n_assert( this->thisType == NONE || this->thisType == SHADERTYPELIBRARY ); this->stringValid = false; this->thisType = SHADERTYPELIBRARY; this->matType = val; this->matTypeIsValid = true; this->materialTypeNameInLibrary = name; } //------------------------------------------------------------------------------ /** Set type Libaray. @param name The name's material in Library @parama val. The original material type for future conversion */ void nAbstractPropBuilder::SetMaterialTypeFromLibrary( const char* name) { n_assert( this->thisType == NONE || this->thisType == SHADERTYPELIBRARY ); this->stringValid = false; this->thisType = SHADERTYPELIBRARY; this->materialTypeNameInLibrary = name; } //------------------------------------------------------------------------------ /** */ const char* nAbstractPropBuilder::GetMaterialTypeName() const { return this->materialTypeNameInLibrary.Get(); } //------------------------------------------------------------------------------ /** */ bool nAbstractPropBuilder::IsInvalidShader() const { n_assert ( this->thisType == SHADERTYPELIBRARY ); return (this->materialTypeNameInLibrary.IsEmpty()) || (this->materialTypeNameInLibrary == "invalid" ); } //------------------------------------------------------------------------------ /** */ bool nAbstractPropBuilder::IsCustomShader() const { return (this->materialTypeNameInLibrary == "custom" ); } const char* nAbstractPropBuilder::GetUniqueString() { int idx; if (! this->stringValid ) { char buf[255]; stringKey=""; switch (thisType) { case NONE: stringKey+="NONE#"; break; case NMATERIAL: stringKey+="NMATERIAL#";//+material+"/"; if (this->matTypeIsValid) { stringKey += this->matType.GetUniqueString(); stringKey +="/"; } break; case NSURFACE: stringKey+="NSURFACE#"; for (idx = 0; idx < shaders.Size() ; idx ++) { varShader& shader = shaders[idx]; stringKey+= shader.varName + "." + shader.val+"/"; } break; case SHADERTYPELIBRARY: stringKey+="SHADERLIBRARY#"; stringKey+=this->materialTypeNameInLibrary; // If the material is custom get the matType properties if (this->matTypeIsValid && (this->IsInvalidShader() || this->IsCustomShader() ) ) { stringKey += this->matType.GetUniqueString(); stringKey +="/"; } } stringKey+="TEX#"; for (idx=0; idx < textures.Size() ; idx++) { varTexture& texture = textures[idx]; stringKey += texture.varName +"." + texture.texName + "/"; } stringKey+="INT#"; for ( idx=0; idx < integers.Size(); idx++) { varInt& integer = integers[idx]; sprintf(buf,".%i#", integer.val); stringKey += integer.varName + buf; } stringKey+="FLOAT#"; for (idx=0; idx < floats.Size(); idx ++) { varFloat& var = floats[idx]; sprintf(buf,".%f#", var.val ); stringKey += var.varName + buf; } stringKey+="VECTOR#"; for (idx = 0; idx< vectors.Size(); idx ++) { varVector& var = vectors[idx]; sprintf(buf,".%f_%f_%f_%f#", var.val.x, var.val.y, var.val.z, var.val.w); stringKey += var.varName + buf; } stringKey+="ANIMS$"; for (idx = 0 ; idx < anims.Size() ; idx ++) { stringKey += anims[idx] + "$"; } this->stringValid = true; } return this->stringKey.Get(); } void nAbstractPropBuilder::SetTo( nAbstractShaderNode* node) { n_assert(nKernelServer::ks); int idx; switch (thisType) { case NONE: break; case NMATERIAL: if ( node->IsA(nmaterialnode)) { //nMaterialNode* MaterialNode = (nMaterialNode*) node; //MaterialNode->SetMaterial( this->material.Get() ); } break; case NSURFACE: if ( node->IsA(nsurfacenode) ) { nSurfaceNode* SurfaceNode = (nSurfaceNode*) node; for (idx = 0; idx < shaders.Size() ; idx ++) { varShader& var = shaders[idx]; SurfaceNode->SetShader( nVariableServer::StringToFourCC(var.varName.Get()) , var.val.Get() ); } } break; case SHADERTYPELIBRARY: break; } for (idx = 0; idx < textures.Size() ; idx ++) { varTexture& var = textures[idx]; node->SetTexture( nShaderState::StringToParam( var.varName.Get()), var.texName.Get() ); } for (idx = 0; idx < floats.Size(); idx ++) { varFloat& var = floats[idx]; node->SetFloat( nShaderState::StringToParam( var.varName.Get()), var.val); } for (idx = 0; idx < integers.Size(); idx++) { varInt& var = integers[idx]; node->SetInt( nShaderState::StringToParam( var.varName.Get()) , var.val); } for (idx = 0; idx < vectors.Size(); idx++) { varVector& var = vectors[idx]; node->SetVector( nShaderState::StringToParam( var.varName.Get() ), var.val); } for (idx = 0 ; idx < anims.Size() ; idx ++) { node->AddAnimator( anims[idx].Get() ); } } void nAbstractPropBuilder::operator +=(const nAbstractPropBuilder& rhs) { switch (rhs.thisType) { case NONE: break; case NMATERIAL: if (this->thisType == NONE || this->thisType == NMATERIAL) { this->thisType = NMATERIAL; if (rhs.matTypeIsValid) { this->matTypeIsValid = true; this->matType += rhs.matType; } } break; case NSURFACE: if (this->thisType == NONE || this->thisType == NSURFACE) { this->thisType = NSURFACE; this->shaders += rhs.shaders; } break; case SHADERTYPELIBRARY: if (this->thisType == NONE || this->thisType == SHADERTYPELIBRARY) { this->thisType = SHADERTYPELIBRARY; this->matTypeIsValid = true; this->matType += rhs.matType; if ( this->thisType == NONE ) { this->materialTypeNameInLibrary = rhs.materialTypeNameInLibrary; } } } this->textures+= rhs.textures; this->integers+= rhs.integers; this->floats+= rhs.floats; this->vectors+= rhs.vectors; this->stringValid = false; } const char* nAbstractPropBuilder::GetNameClass() { switch (thisType ) { case nAbstractPropBuilder::NONE: return "nabstractshadernode"; break; case nAbstractPropBuilder::NMATERIAL : return "nmaterialnode"; break; case nAbstractPropBuilder::NSURFACE : return "nsurfacenode"; break; case nAbstractPropBuilder::SHADERTYPELIBRARY : return "nmaterialnode"; break; } return ""; } void nAbstractPropBuilder::Reduce() { //@ todo remove unnecesary variables, textures , etc.... by material properties }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91
e5e48a82a475ad2ae3d337063469492e629854be
a9e308c81c27a80c53c899ce806d6d7b4a9bbbf3
/SDK/include/WildMagic4/SDK/Include/Wm4RandomHypersphere.h
afa93fd1ac7c896e60460fbd8ea26246689be25b
[ "BSL-1.0" ]
permissive
NikitaNikson/xray-2_0
00d8e78112d7b3d5ec1cb790c90f614dc732f633
82b049d2d177aac15e1317cbe281e8c167b8f8d1
refs/heads/master
2023-06-25T16:51:26.243019
2020-09-29T15:49:23
2020-09-29T15:49:23
390,966,305
1
0
null
null
null
null
UTF-8
C++
false
false
2,550
h
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 4.10.0 (2009/11/18) #ifndef WM4RANDOMHYPERSPHERE_H #define WM4RANDOMHYPERSPHERE_H #include "Wm4FoundationLIB.h" #include "Wm4System.h" namespace Wm4 { // Generate N random points on the hypersphere in D-space, // // x_1^2 + ... + x_D^2 = 1 // // The function selects a random angle in [0,2*pi) and partitions // the equation into // // x_1^2 + ... + x_{D/2}^2 = (cos(A))^2 // // and // // x_{D/2+1}^2 + ... + x_D^2 = (sin(A))^2 // // The function initializes all components of P to 1. The partitioned // components are updated as x_i *= cos(A) for 0 <= i < D/2 and // x_i *= sin(A) for D/2 <= i < D. The function is recursively called // on the partitioned components. WM4_FOUNDATION_ITEM void RandomPointOnHypersphere (int iDimension, double* adPoint); // An attempt to determine the uniformity of N randomly generated // points P[0] through P[N-1] on the hypersphere. Select a positive // angle. For each point P[i] count the number H[i] of random points // P[j] which lie in the cone with axis P[i] and specified angle. For // N suitably large, H[i] should be constant for all i. To be really // sure of the uniformity, you should look at other cones whose axes // are not the sample points. However, this requires generating random // points to get the axes and, well, you can see the problem... WM4_FOUNDATION_ITEM void Histogram (int iDimension, double dAngle, int iQuantity, double** aadPoint, int* aiHistogram); //An example of how to use these functions. // //void TestRandomHyperspherePoints () //{ // const int iQuantity = 4096; // const int iDimension = 3; // int i; // // double** aadPoint = WM4_NEW double*[iQuantity]; // aadPoint[0] = WM4_NEW double[iQuantity*iDimension]; // for (i = 1; i < iQuantity; i++) // aadPoint[i] = &aadPoint[0][iDimension*i]; // // for (i = 0; i < iQuantity; i++) // RandomPointOnHypersphere(iDimension,aadPoint[i]); // // int* aiHistogram = WM4_NEW int[iQuantity]; // double dAngle = 0.5; // Histogram(iDimension,dAngle,iQuantity,aadPoint,aiHistogram); // // ofstream ostr("histo.txt"); // for (i = 0; i < iQuantity; i++) // ostr << i << ' ' << aiHistogram[i] << endl; // // WM4_DELETE[] aiHistogram; // WM4_DELETE[] aadPoint[0]; // WM4_DELETE[] aadPoint; //} } #endif
[ "loxotron@bk.ru" ]
loxotron@bk.ru
a1df2f00efba8b1a277da7deb9fca819dda14c56
a1fbf16243026331187b6df903ed4f69e5e8c110
/cs/sdk/3d_sdk/maya/ver-8.5/devkit/ExternalWebBrowser/Windows/src/PlugIn/gecko-sdk/include/nsIDOMDocumentType.h
f7b4adbbe3889283e6b9416285df5e6318dc785b
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
OpenXRay/xray-15
ca0031cf1893616e0c9795c670d5d9f57ca9beff
1390dfb08ed20997d7e8c95147ea8e8cb71f5e86
refs/heads/xd_dev
2023-07-17T23:42:14.693841
2021-09-01T23:25:34
2021-09-01T23:25:34
23,224,089
64
23
NOASSERTION
2019-04-03T17:50:18
2014-08-22T12:09:41
C++
UTF-8
C++
false
false
5,534
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM d:/BUILDS/tinderbox/Mozilla1.7/WINNT_5.0_Clobber/mozilla/dom/public/idl/core/nsIDOMDocumentType.idl */ #ifndef __gen_nsIDOMDocumentType_h__ #define __gen_nsIDOMDocumentType_h__ #ifndef __gen_nsIDOMNode_h__ #include "nsIDOMNode.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMDocumentType */ #define NS_IDOMDOCUMENTTYPE_IID_STR "a6cf9077-15b3-11d2-932e-00805f8add32" #define NS_IDOMDOCUMENTTYPE_IID \ {0xa6cf9077, 0x15b3, 0x11d2, \ { 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }} class NS_NO_VTABLE nsIDOMDocumentType : public nsIDOMNode { public: NS_DEFINE_STATIC_IID_ACCESSOR(NS_IDOMDOCUMENTTYPE_IID) /** * Each Document has a doctype attribute whose value is either null * or a DocumentType object. * The nsIDOMDocumentType interface in the DOM Core provides an * interface to the list of entities that are defined for the document. * * For more information on this interface please see * http://www.w3.org/TR/DOM-Level-2-Core/ * * @status FROZEN */ /* readonly attribute DOMString name; */ NS_IMETHOD GetName(nsAString & aName) = 0; /* readonly attribute nsIDOMNamedNodeMap entities; */ NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities) = 0; /* readonly attribute nsIDOMNamedNodeMap notations; */ NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations) = 0; /* readonly attribute DOMString publicId; */ NS_IMETHOD GetPublicId(nsAString & aPublicId) = 0; /* readonly attribute DOMString systemId; */ NS_IMETHOD GetSystemId(nsAString & aSystemId) = 0; /* readonly attribute DOMString internalSubset; */ NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset) = 0; }; /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMDOCUMENTTYPE \ NS_IMETHOD GetName(nsAString & aName); \ NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities); \ NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations); \ NS_IMETHOD GetPublicId(nsAString & aPublicId); \ NS_IMETHOD GetSystemId(nsAString & aSystemId); \ NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMDOCUMENTTYPE(_to) \ NS_IMETHOD GetName(nsAString & aName) { return _to GetName(aName); } \ NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities) { return _to GetEntities(aEntities); } \ NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations) { return _to GetNotations(aNotations); } \ NS_IMETHOD GetPublicId(nsAString & aPublicId) { return _to GetPublicId(aPublicId); } \ NS_IMETHOD GetSystemId(nsAString & aSystemId) { return _to GetSystemId(aSystemId); } \ NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset) { return _to GetInternalSubset(aInternalSubset); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMDOCUMENTTYPE(_to) \ NS_IMETHOD GetName(nsAString & aName) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetName(aName); } \ NS_IMETHOD GetEntities(nsIDOMNamedNodeMap * *aEntities) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetEntities(aEntities); } \ NS_IMETHOD GetNotations(nsIDOMNamedNodeMap * *aNotations) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNotations(aNotations); } \ NS_IMETHOD GetPublicId(nsAString & aPublicId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPublicId(aPublicId); } \ NS_IMETHOD GetSystemId(nsAString & aSystemId) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSystemId(aSystemId); } \ NS_IMETHOD GetInternalSubset(nsAString & aInternalSubset) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInternalSubset(aInternalSubset); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMDocumentType : public nsIDOMDocumentType { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMDOCUMENTTYPE nsDOMDocumentType(); private: ~nsDOMDocumentType(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMDocumentType, nsIDOMDocumentType) nsDOMDocumentType::nsDOMDocumentType() { /* member initializers and constructor code */ } nsDOMDocumentType::~nsDOMDocumentType() { /* destructor code */ } /* readonly attribute DOMString name; */ NS_IMETHODIMP nsDOMDocumentType::GetName(nsAString & aName) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMNamedNodeMap entities; */ NS_IMETHODIMP nsDOMDocumentType::GetEntities(nsIDOMNamedNodeMap * *aEntities) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMNamedNodeMap notations; */ NS_IMETHODIMP nsDOMDocumentType::GetNotations(nsIDOMNamedNodeMap * *aNotations) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute DOMString publicId; */ NS_IMETHODIMP nsDOMDocumentType::GetPublicId(nsAString & aPublicId) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute DOMString systemId; */ NS_IMETHODIMP nsDOMDocumentType::GetSystemId(nsAString & aSystemId) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute DOMString internalSubset; */ NS_IMETHODIMP nsDOMDocumentType::GetInternalSubset(nsAString & aInternalSubset) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMDocumentType_h__ */
[ "paul-kv@yandex.ru" ]
paul-kv@yandex.ru
e52c2a00b4800ca7df0be3322cbbf0cfa06aa0a7
68c8eead2f74f6acfe1dfd25aca5d4c09d2c9c92
/src/opencv-code/precomp.hpp
8787f1b3c0f162e8aaea84cc23c264eb06d3b342
[]
no_license
rmeesters/GnomeVision-2020
22379dea5968954c88d261a76f5d1e8d6a494856
0ddce4ddcbe55ae5bbad9bf3496e7a5d2135e86e
refs/heads/master
2020-12-18T13:26:23.932184
2020-02-09T17:36:43
2020-02-09T17:36:43
235,399,387
0
0
null
null
null
null
UTF-8
C++
false
false
9,453
hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of Intel Corporation may not 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 Intel Corporation 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. // //M*/ #ifndef __HIGHGUI_H_ #define __HIGHGUI_H_ #include "cvconfig.h" #include "opencv2/highgui/highgui.hpp" #include "opencv2/highgui/highgui_c.h" #include "opencv2/imgproc/imgproc_c.h" // #include "opencv3/core/core.hpp" #include "opencv2/videoio/videoio_c.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> #include <ctype.h> #include <assert.h> #if defined WIN32 || defined WINCE #if !defined _WIN32_WINNT #ifdef HAVE_MSMF #define _WIN32_WINNT 0x0600 // Windows Vista #else #define _WIN32_WINNT 0x0500 // Windows 2000 #endif #endif #include <windows.h> #undef small #undef min #undef max #undef abs #endif #ifdef HAVE_TEGRA_OPTIMIZATION #include "opencv2/highgui/highgui_tegra.hpp" #endif /* Errors */ #define HG_OK 0 /* Don't bet on it! */ #define HG_BADNAME -1 /* Bad window or file name */ #define HG_INITFAILED -2 /* Can't initialize HigHGUI */ #define HG_WCFAILED -3 /* Can't create a window */ #define HG_NULLPTR -4 /* The null pointer where it should not appear */ #define HG_BADPARAM -5 #define __BEGIN__ __CV_BEGIN__ #define __END__ __CV_END__ #define EXIT __CV_EXIT__ #define CV_WINDOW_MAGIC_VAL 0x00420042 #define CV_TRACKBAR_MAGIC_VAL 0x00420043 /***************************** CvCapture structure ******************************/ struct CvCapture { virtual ~CvCapture() {} virtual double getProperty(int) { return 0; } virtual bool setProperty(int, double) { return 0; } virtual bool grabFrame() { return true; } virtual IplImage* retrieveFrame(int) { return 0; } virtual int getCaptureDomain() { return CV_CAP_ANY; } // Return the type of the capture object: CV_CAP_VFW, etc... }; /*************************** CvVideoWriter structure ****************************/ struct CvVideoWriter { virtual ~CvVideoWriter() {} virtual bool writeFrame(const IplImage*) { return false; } }; CvCapture * cvCreateCameraCapture_V4L( int index ); CvCapture * cvCreateCameraCapture_DC1394( int index ); CvCapture * cvCreateCameraCapture_DC1394_2( int index ); CvCapture* cvCreateCameraCapture_MIL( int index ); CvCapture* cvCreateCameraCapture_Giganetix( int index ); CvCapture * cvCreateCameraCapture_CMU( int index ); CV_IMPL CvCapture * cvCreateCameraCapture_TYZX( int index ); CvCapture* cvCreateFileCapture_Win32( const char* filename ); CvCapture* cvCreateCameraCapture_VFW( int index ); CvCapture* cvCreateFileCapture_VFW( const char* filename ); CvVideoWriter* cvCreateVideoWriter_Win32( const char* filename, int fourcc, double fps, CvSize frameSize, int is_color ); CvVideoWriter* cvCreateVideoWriter_VFW( const char* filename, int fourcc, double fps, CvSize frameSize, int is_color ); CvCapture* cvCreateCameraCapture_DShow( int index ); CvCapture* cvCreateCameraCapture_MSMF( int index ); CvCapture* cvCreateFileCapture_MSMF (const char* filename); CvVideoWriter* cvCreateVideoWriter_MSMF( const char* filename, int fourcc, double fps, CvSize frameSize, int is_color ); CvCapture* cvCreateCameraCapture_OpenNI( int index ); CvCapture* cvCreateFileCapture_OpenNI( const char* filename ); CvCapture* cvCreateCameraCapture_Android( int index ); CvCapture* cvCreateCameraCapture_XIMEA( int index ); CvCapture* cvCreateCameraCapture_AVFoundation(int index); CvCapture* cvCreateCameraCapture_IntelPerC(int index); CVAPI(int) cvHaveImageReader(const char* filename); CVAPI(int) cvHaveImageWriter(const char* filename); CvCapture* cvCreateFileCapture_Images(const char* filename); CvVideoWriter* cvCreateVideoWriter_Images(const char* filename); CvCapture* cvCreateFileCapture_XINE (const char* filename); #define CV_CAP_GSTREAMER_1394 0 #define CV_CAP_GSTREAMER_V4L 1 #define CV_CAP_GSTREAMER_V4L2 2 #define CV_CAP_GSTREAMER_FILE 3 CvCapture* cvCreateCapture_GStreamer(int type, const char *filename); CvCapture* cvCreateFileCapture_FFMPEG_proxy(const char* filename); CvVideoWriter* cvCreateVideoWriter_FFMPEG_proxy( const char* filename, int fourcc, double fps, CvSize frameSize, int is_color ); CvCapture * cvCreateFileCapture_QT (const char * filename); CvCapture * cvCreateCameraCapture_QT (const int index); CvVideoWriter* cvCreateVideoWriter_QT ( const char* filename, int fourcc, double fps, CvSize frameSize, int is_color ); CvCapture* cvCreateFileCapture_AVFoundation (const char * filename); CvVideoWriter* cvCreateVideoWriter_AVFoundation( const char* filename, int fourcc, double fps, CvSize frameSize, int is_color ); CvCapture * cvCreateCameraCapture_Unicap (const int index); CvCapture * cvCreateCameraCapture_PvAPI (const int index); CvVideoWriter* cvCreateVideoWriter_GStreamer( const char* filename, int fourcc, double fps, CvSize frameSize, int is_color ); //Yannick Verdie 2010 void cvSetModeWindow_W32(const char* name, double prop_value); void cvSetModeWindow_GTK(const char* name, double prop_value); void cvSetModeWindow_CARBON(const char* name, double prop_value); void cvSetModeWindow_COCOA(const char* name, double prop_value); double cvGetModeWindow_W32(const char* name); double cvGetModeWindow_GTK(const char* name); double cvGetModeWindow_CARBON(const char* name); double cvGetModeWindow_COCOA(const char* name); double cvGetPropWindowAutoSize_W32(const char* name); double cvGetPropWindowAutoSize_GTK(const char* name); double cvGetRatioWindow_W32(const char* name); double cvGetRatioWindow_GTK(const char* name); double cvGetOpenGlProp_W32(const char* name); double cvGetOpenGlProp_GTK(const char* name); //for QT #if defined (HAVE_QT) double cvGetModeWindow_QT(const char* name); void cvSetModeWindow_QT(const char* name, double prop_value); double cvGetPropWindow_QT(const char* name); void cvSetPropWindow_QT(const char* name,double prop_value); double cvGetRatioWindow_QT(const char* name); void cvSetRatioWindow_QT(const char* name,double prop_value); double cvGetOpenGlProp_QT(const char* name); #endif /*namespace cv { class CV_EXPORTS BaseWindow { public: BaseWindow(const String& name, int flags=0); virtual ~BaseWindow(); virtual void close(); virtual void show(const Mat& mat); virtual void resize(Size size); virtual void move(Point topleft); virtual Size size() const; virtual Point topLeft() const; virtual void setGeometry(Point topLeft, Size size); virtual void getGeometry(Point& topLeft, Size& size) const; virtual String getTitle() const; virtual void setTitle(const String& str); virtual String getName() const; virtual void setScaleMode(int mode); virtual int getScaleMode(); virtual void setScrollPos(double pos); virtual double getScrollPos() const; virtual void setScale(double scale); virtual double getScale() const; virtual Point getImageCoords(Point pos) const; virtual Scalar getPixelValue(Point pos, const String& colorspace=String()) const; virtual void addTrackbar( const String& trackbar, int low, int high, int step ); }; typedef Ptr<BaseWindow> Window; }*/ #endif /* __HIGHGUI_H_ */
[ "meesters.rich@gmail.com" ]
meesters.rich@gmail.com
2d2417d04062b5250820515da4c114d3c9013c2d
0f6b28bf6dfdc14808b5849455abc41ad7a79466
/AI/8-puzzle/firstchioce/firstChioce.cpp
5e5132739ab3c2a1ac1204c2ad72be7d717e1a76
[]
no_license
warsonchou/AI
c18e73bff3de953e56b6eded022ae9f096d4047d
42fca33773e527911e4db3109722676bb809d8c1
refs/heads/master
2021-05-31T04:14:43.491229
2016-02-25T03:31:12
2016-02-25T03:31:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,339
cpp
// 使用曼哈顿距离来到度量好坏 // first choice version #include "iostream" #include "algorithm" #include "stdlib.h" #include "stdio.h" #include "time.h" using namespace std; const int range = 100; void getRandomStart(int a[3][3]) { int i, j, num; bool isPut[9]; memset(isPut, false, sizeof(isPut)); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { while(1) { srand((unsigned) time(NULL)); num = rand() % 9; if (isPut[num]) { continue; } else { isPut[num] = true; a[i][j] = num + 1; break; } } } } } bool isReached(int a[3][3]) { int i, j; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (a[i][j] != i * 3 + j + 1) break; } } return (i == 3 && j == 3); } int getDistance(int target, int x, int y) { int shouldX = target / 3 + 1, shouldY = target % 3; if (shouldY == 0) { shouldX--; shouldY = 3; } return (abs(shouldX - x) + abs(shouldY - y)); } int getH(int a[3][3]) { int i, j, sum = 0; for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (a[i][j] == 9) continue; sum += getDistance(a[i][j], i + 1, j + 1); } } return sum; } bool hillClimb(int a[3][3]) { int i, j, h, loops, posxofspace, posyofspace, x[4] = {0, 0, 1, -1}, y[4] ={1, -1, 0, 0}, currentH, bestx, bestH, besty, temp; bool direction[4]; // get the position of 9 for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (a[i][j] == 9) break; } if (a[i][j] == 9) break; } posxofspace = i; posyofspace = j; currentH = getH(a); bestH = currentH; bestx = posxofspace; besty = posyofspace; for (loops = 0; loops < 10000; loops++) { memset(direction, false, sizeof(direction)); int count = 0; while(1) { count++; srand((unsigned) time(NULL)); i = rand() % 4; if (posxofspace + x[i] >=0 && posxofspace + x[i] < 3 && posyofspace + y[i] < 3 && posyofspace + y[i] >= 0) { temp = a[posxofspace][posyofspace]; a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]]; a[posxofspace + x[i]][posyofspace + y[i]] = temp; h = getH(a); // 还原回来原来的状态 temp = a[posxofspace][posyofspace]; a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]]; a[posxofspace + x[i]][posyofspace + y[i]] = temp; if (h < bestH) { bestx = posxofspace + x[i]; besty = posyofspace + y[i]; bestH = h; break; } } if (count == 4) break; } if (isReached(a)) break; if (bestH == currentH) { for (int g = 0; g < range; g++) { i = rand() % 4; if (posxofspace + x[i] >=0 && posxofspace + x[i] < 3 && posyofspace + y[i] < 3 && posyofspace + y[i] >= 0) { temp = a[posxofspace][posyofspace]; a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]]; a[posxofspace + x[i]][posyofspace + y[i]] = temp; h = getH(a); if (h > currentH) { // 还原回来原来的状态 temp = a[posxofspace][posyofspace]; a[posxofspace][posyofspace] = a[posxofspace + x[i]][posyofspace + y[i]]; a[posxofspace + x[i]][posyofspace + y[i]] = temp; } else { posxofspace += x[i]; posyofspace += y[i]; } } } if (bestH == currentH) return false; } else { currentH = bestH; temp = a[posxofspace][posyofspace]; a[posxofspace][posyofspace] = a[bestx][besty]; a[bestx][besty] = temp; posxofspace = bestx; posyofspace = besty; } } // cout << currentH << endl; return isReached(a); } int main(int argc, char const *argv[]) { int i, j, k, count = 0, a[3][3], test[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, test1[3][3] = {{7, 2, 4}, {5, 9, 6}, {8 ,3 ,1}}; while(cin >> a[0][0]) { // getRandomStart(a); for (j = 0; j < 3; j++) { for (k = 0; k < 3; k++) { if (k == 0 && j == 0) continue; cin >> a[j][k]; } } // for (j = 0; j < 3; j++) { // for (k = 0; k < 3; k++) { // cout << a[j][k] << " "; // } // } // cout << endl; if (hillClimb(a)) { count++; } // for (j = 0; j < 3; j++) { // for (k = 0; k < 3; k++) { // cout << a[j][k] << " "; // } // } // cout << endl << endl; } cout << "FirstChioce HillClimb algorithm in solving the 8-puzzle problem:\nSolved percentage: "; cout << ((double)count / (double)10000 * (double)100) << "%" << endl; return 0; }
[ "1129134022@qq.com" ]
1129134022@qq.com
0e24840b48a7f7dce6a8fc38fd8d760fb5c3efc9
2c362195203bb7ee9d8595b028ac8087ca3f0be3
/Smart_Strings/Owned_Pointers.cpp
b6fe8c16a47f7b2d645819d8d842dc7b86878d45
[]
no_license
syed789/Assignment_02_-_Smart_Strings
15bbf9807712077b86760d079d34b0301f353bb0
943a0e4e92aa4ffc3b0740177896d56064efc387
refs/heads/master
2020-06-10T20:12:44.826951
2016-12-08T00:30:51
2016-12-08T00:30:51
75,887,484
0
0
null
null
null
null
UTF-8
C++
false
false
3,423
cpp
#include <iostream> using namespace std; // String Buffer class class String_Buffer { private: // string buffer char* string_buffer; // string size int size; public: // default constructor String_Buffer() { string_buffer = NULL; size = 0; } // destructor ~String_Buffer() { delete[size] string_buffer; size = 0; } // parametrized / overload constructor void load_string(char* string, int length) { allocate(length); for (int i = 0; i < length; ++i) { string_buffer[i] = string[i]; } } // returns character at specified index char char_at(int index) const { if (index < size) { return string_buffer[index]; } else { cout << "Error! Index out of bound!"; return ' '; } } // returns size of string buffer int length() const { return size; } // allocate memory void allocate(int length) { delete[] string_buffer; string_buffer = new char[length]; size = length; } // appends character at the end void append(char character) { char* new_string = new char[size + 1]; for (int i = 0; i < size; i++) { new_string[i] = string_buffer[i]; } new_string[size] = character; delete[size] string_buffer; string_buffer = new_string; ++size; } void print() { for (int i = 0; i < size; i++) { cout << string_buffer[i]; } } }; // String class class String { private: String_Buffer* string_buffer; bool owner; public: // default constructor String() { string_buffer = NULL; owner = 0; } // parametrized / overload constructor String(char* input_string, int length) { string_buffer = new String_Buffer; string_buffer->load_string(input_string, length); } // parametrized / overload constructor String(String& source) { this->owner = true; source.owner = false; this->string_buffer = source.string_buffer; } // destructor ~String() { if (owner) { delete string_buffer; } else { string_buffer = NULL; } } // returns character at specified index char char_at(int index) const { if (string_buffer != NULL) { return string_buffer->char_at(index); } return ' '; } // returns size of string buffer int length() const { if (string_buffer != NULL) { return string_buffer->length(); } return 0; } // appends character at the end of string void append(char character) { if (string_buffer == NULL) { string_buffer = new String_Buffer; } string_buffer->append(character); } void print() { if (string_buffer != NULL) { string_buffer->print(); } } }; int main(void) { cout << "OUTER SCOPE" << endl << endl; String string_1("HELLO", 5); cout << "String 1: "; string_1.print(); cout << endl << endl; { cout << "INNER SCOPE" << endl << endl; String string_2(string_1); cout << "String 2: "; string_2.print(); cout << endl << endl; cout << "String 1: "; string_1.print(); cout << endl << endl; string_1.append(' '); string_1.append('F'); string_1.append('A'); string_1.append('H'); string_1.append('A'); string_1.append('D'); string_1.append('!'); cout << "After append \" FAHAD!\" in String 1" << endl << endl; cout << "String 1: "; string_1.print(); cout << endl << endl; cout << "String 2: "; string_2.print(); cout << endl << endl; } cout << "OUTER SCOPE" << endl << endl; cout << "String 1: "; string_1.print(); cout << endl << endl; return 0; }
[ "14bscsstayyab@seecs.edu.pk" ]
14bscsstayyab@seecs.edu.pk
1ee76788bf6a3a28eceb229f676eded53643e4ca
95c367e58a79fd5a933dc0a2043adadccec5630c
/External/boost_1_63_0/boost/spirit/home/lex/lexer/lexertl/functor.hpp
260e4dcc507a66548d94c2f6acc1dc7dbad237cb
[ "BSL-1.0" ]
permissive
fl4re/COLLADAMobu
cf06fa2462d6655407ebc0502a6f25c7274dee84
4a81bec2b1d98b23311f13255fd9182c570a9b3d
refs/heads/master
2020-05-24T02:34:55.534671
2017-04-12T16:06:28
2017-04-12T16:06:28
84,808,624
0
0
null
2017-04-12T22:13:17
2017-03-13T09:35:38
C++
UTF-8
C++
false
false
11,900
hpp
// Copyright (c) 2001-2011 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(BOOST_SPIRIT_LEX_LEXER_FUNCTOR_NOV_18_2007_1112PM) #define BOOST_SPIRIT_LEX_LEXER_FUNCTOR_NOV_18_2007_1112PM #if defined(_MSC_VER) #pragma once #endif #include <boost/mpl/bool.hpp> #include <boost/detail/iterator.hpp> #include <boost/detail/workaround.hpp> #include <boost/spirit/home/lex/lexer/pass_flags.hpp> #include <boost/assert.hpp> #if 0 != __COMO_VERSION__ || !BOOST_WORKAROUND(BOOST_MSVC, <= 1310) #define BOOST_SPIRIT_STATIC_EOF 1 #define BOOST_SPIRIT_EOF_PREFIX static #else #define BOOST_SPIRIT_EOF_PREFIX #endif namespace boost { namespace spirit { namespace lex { namespace lexertl { /////////////////////////////////////////////////////////////////////////// // // functor is a template usable as the functor object for the // multi_pass iterator allowing to wrap a lexertl based dfa into a // iterator based interface. // // Token: the type of the tokens produced by this functor // this needs to expose a constructor with the following // prototype: // // Token(std::size_t id, std::size_t state, // Iterator start, Iterator end) // // where 'id' is the token id, state is the lexer state, // this token has been matched in, and 'first' and 'end' // mark the start and the end of the token with respect // to the underlying character stream. // FunctorData: // this is expected to encapsulate the shared part of the // functor (see lex/lexer/lexertl/functor_data.hpp for an // example and documentation). // Iterator: the type of the underlying iterator // SupportsActors: // this is expected to be a mpl::bool_, if mpl::true_ the // functor invokes functors which (optionally) have // been attached to the token definitions. // SupportState: // this is expected to be a mpl::bool_, if mpl::true_ the // functor supports different lexer states, // otherwise no lexer state is supported. // /////////////////////////////////////////////////////////////////////////// template <typename Token , template <typename, typename, typename, typename> class FunctorData , typename Iterator = typename Token::iterator_type , typename SupportsActors = mpl::false_ , typename SupportsState = typename Token::has_state> class functor { public: typedef typename boost::detail::iterator_traits<Iterator>::value_type char_type; private: // Needed by compilers not implementing the resolution to DR45. For // reference, see // http://www.open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#45. typedef typename Token::token_value_type token_value_type; friend class FunctorData<Iterator, SupportsActors, SupportsState , token_value_type>; // Helper template allowing to assign a value on exit template <typename T> struct assign_on_exit { assign_on_exit(T& dst, T const& src) : dst_(dst), src_(src) {} ~assign_on_exit() { dst_ = src_; } T& dst_; T const& src_; private: // silence MSVC warning C4512: assignment operator could not be generated assign_on_exit& operator= (assign_on_exit const&); }; public: functor() #if defined(__PGI) : eof() #endif {} #if BOOST_WORKAROUND(BOOST_MSVC, <= 1310) // somehow VC7.1 needs this (meaningless) assignment operator functor& operator=(functor const& rhs) { return *this; } #endif /////////////////////////////////////////////////////////////////////// // interface to the iterator_policies::split_functor_input policy typedef Token result_type; typedef functor unique; typedef FunctorData<Iterator, SupportsActors, SupportsState , token_value_type> shared; BOOST_SPIRIT_EOF_PREFIX result_type const eof; /////////////////////////////////////////////////////////////////////// typedef Iterator iterator_type; typedef typename shared::semantic_actions_type semantic_actions_type; typedef typename shared::next_token_functor next_token_functor; typedef typename shared::get_state_name_type get_state_name_type; // this is needed to wrap the semantic actions in a proper way typedef typename shared::wrap_action_type wrap_action_type; /////////////////////////////////////////////////////////////////////// template <typename MultiPass> static result_type& get_next(MultiPass& mp, result_type& result) { typedef typename result_type::id_type id_type; shared& data = mp.shared()->ftor; for(;;) { if (data.get_first() == data.get_last()) #if defined(BOOST_SPIRIT_STATIC_EOF) return result = eof; #else return result = mp.ftor.eof; #endif data.reset_value(); Iterator end = data.get_first(); std::size_t unique_id = boost::lexer::npos; bool prev_bol = false; // lexer matching might change state std::size_t state = data.get_state(); std::size_t id = data.next(end, unique_id, prev_bol); if (boost::lexer::npos == id) { // no match #if defined(BOOST_SPIRIT_LEXERTL_DEBUG) std::string next; Iterator it = data.get_first(); for (std::size_t i = 0; i < 10 && it != data.get_last(); ++it, ++i) next += *it; std::cerr << "Not matched, in state: " << state << ", lookahead: >" << next << "<" << std::endl; #endif return result = result_type(0); } else if (0 == id) { // EOF reached #if defined(BOOST_SPIRIT_STATIC_EOF) return result = eof; #else return result = mp.ftor.eof; #endif } #if defined(BOOST_SPIRIT_LEXERTL_DEBUG) { std::string next; Iterator it = end; for (std::size_t i = 0; i < 10 && it != data.get_last(); ++it, ++i) next += *it; std::cerr << "Matched: " << id << ", in state: " << state << ", string: >" << std::basic_string<char_type>(data.get_first(), end) << "<" << ", lookahead: >" << next << "<" << std::endl; if (data.get_state() != state) { std::cerr << "Switched to state: " << data.get_state() << std::endl; } } #endif // account for a possibly pending lex::more(), i.e. moving // data.first_ back to the start of the previously matched token. bool adjusted = data.adjust_start(); // set the end of the matched input sequence in the token data data.set_end(end); // invoke attached semantic actions, if defined, might change // state, id, data.first_, and/or end BOOST_SCOPED_ENUM(pass_flags) pass = data.invoke_actions(state, id, unique_id, end); if (data.has_value()) { // return matched token using the token value as set before // using data.set_value(), advancing 'data.first_' past the // matched sequence assign_on_exit<Iterator> on_exit(data.get_first(), end); return result = result_type(id_type(id), state, data.get_value()); } else if (pass_flags::pass_normal == pass) { // return matched token, advancing 'data.first_' past the // matched sequence assign_on_exit<Iterator> on_exit(data.get_first(), end); return result = result_type(id_type(id), state, data.get_first(), end); } else if (pass_flags::pass_fail == pass) { #if defined(BOOST_SPIRIT_LEXERTL_DEBUG) std::cerr << "Matching forced to fail" << std::endl; #endif // if the data.first_ got adjusted above, revert this adjustment if (adjusted) data.revert_adjust_start(); // one of the semantic actions signaled no-match data.reset_bol(prev_bol); if (state != data.get_state()) continue; // retry matching if state has changed // if the state is unchanged repeating the match wouldn't // move the input forward, causing an infinite loop return result = result_type(0); } #if defined(BOOST_SPIRIT_LEXERTL_DEBUG) std::cerr << "Token ignored, continuing matching" << std::endl; #endif // if this token needs to be ignored, just repeat the matching, // while starting right after the current match data.get_first() = end; } } // set_state are propagated up to the iterator interface, allowing to // manipulate the current lexer state through any of the exposed // iterators. template <typename MultiPass> static std::size_t set_state(MultiPass& mp, std::size_t state) { std::size_t oldstate = mp.shared()->ftor.get_state(); mp.shared()->ftor.set_state(state); #if defined(BOOST_SPIRIT_LEXERTL_DEBUG) std::cerr << "Switching state from: " << oldstate << " to: " << state << std::endl; #endif return oldstate; } template <typename MultiPass> static std::size_t get_state(MultiPass& mp) { return mp.shared()->ftor.get_state(); } template <typename MultiPass> static std::size_t map_state(MultiPass const& mp, char_type const* statename) { return mp.shared()->ftor.get_state_id(statename); } // we don't need this, but it must be there template <typename MultiPass> static void destroy(MultiPass const&) {} }; #if defined(BOOST_SPIRIT_STATIC_EOF) /////////////////////////////////////////////////////////////////////////// // eof token /////////////////////////////////////////////////////////////////////////// template <typename Token , template <typename, typename, typename, typename> class FunctorData , typename Iterator, typename SupportsActors, typename SupportsState> typename functor<Token, FunctorData, Iterator, SupportsActors, SupportsState>::result_type const functor<Token, FunctorData, Iterator, SupportsActors, SupportsState>::eof = typename functor<Token, FunctorData, Iterator, SupportsActors , SupportsState>::result_type(); #endif }}}} #undef BOOST_SPIRIT_EOF_PREFIX #undef BOOST_SPIRIT_STATIC_EOF #endif
[ "franck.ohayon@starbreeze.com" ]
franck.ohayon@starbreeze.com
bc6a6e3b4ef1cf1ebc7ac3fdcb061bb7fdc7d274
b6adedeede3e21df8038de6d27103da22e1e2a8f
/protections1300VValueChangesTracked.cpp
7d6f3131f73e924db2cfa6a5d93a16c2a62a42b2
[]
no_license
claymore2000/AmptGUI_X_5_15
fdd1054e2642654b2dbb2803afec19428096f4d7
88591032631865d5137163ebff2f9e978a604a97
refs/heads/master
2023-03-23T18:37:30.358533
2021-03-18T20:08:18
2021-03-18T20:08:18
349,204,092
0
0
null
null
null
null
UTF-8
C++
false
false
21,153
cpp
#include "protections1300VValueChangesTracked.h" #include "amptRegisterConstants.h" #include "amptparameterblockconstants.h" protectionsValueChangesTracked::protectionsValueChangesTracked( void ) { resetAllTrackedValues(true); } protectionsValueChangesTracked::~protectionsValueChangesTracked( void ) { } void protectionsValueChangesTracked::sendAllChangedValues( void ) { } void protectionsValueChangesTracked::resetAllTrackedValues ( bool s ) { qDebug() << Q_FUNC_INFO << " entering ..."; if (s) qDebug() << Q_FUNC_INFO << " INFO: called with argument of " << s; fetCountChanged = false; fetCount = 0; fetThresholdChanged = false; fetThreshold = 0; fetDeltaCurrentChanged = false; fetDeltaCurrent = 0; protection1Changed = false; protection1 = 0; protection2Changed = false; protection2 = 0; protection3Changed = false; protection3 = 0; protection4Changed = false; protection4 = 0; amfTimer1Changed = false; amfTimer1 = 0; amfTimer2Changed = false; amfTimer2 = 0; amfV_OVChanged = false; amfV_OV = 0; amfI_OCChanged = false; amfI_OC = 0; amfDebugChanged = false; amfDebug = 0; amfMPPOffCyclesChanged = false; amfMPPOffCycles = 0; amfMPPTimesOffChanged = false; amfMPPTimesOff = 0; efInputCurrentThresholdChanged = false; efInputCurrentThreshold = 0; efOccurrenceThresholdChanged = false; efOccurrenceThreshold = 0; efCountDownTimerChanged = false; efCountDownTimer = 0; efAlphaNumeratorChanged = false; efAlphaNumerator = 0; iinLimitChanged = false; iinLimit = 0; iinLimitOCStepsChanged = false; iinLimitOCSteps = 0; iinLimitOCDelayChanged = false; iinLimitOCDelay = 0; iinLimitTempAmbientAdjustChanged = false; iinLimitTempAmbientAdjust = 0; } bool protectionsValueChangesTracked::getFETCountChanged( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(fetCountChanged); return fetCountChanged; } void protectionsValueChangesTracked::changeFETCount(const int & s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; fetCount = s; fetCountChanged = true; } bool protectionsValueChangesTracked::getIinLimitChanged( void ) { return iinLimitChanged; } void protectionsValueChangesTracked::changeIinLimit( const unsigned int & s) { iinLimit = s; iinLimitChanged = true; } bool protectionsValueChangesTracked::getIinLimitOCStepsChanged( void ) { return iinLimitOCStepsChanged; } void protectionsValueChangesTracked::changeIinLimitOCSteps(const unsigned int & s) { iinLimitOCSteps = s; iinLimitOCStepsChanged = true; } bool protectionsValueChangesTracked::getIinLimitOCDelayChanged( void ) { return iinLimitOCDelayChanged; } void protectionsValueChangesTracked::changeIinLimitOCDelay(const unsigned int & s) { iinLimitOCDelay = s; iinLimitOCDelayChanged = true; } bool protectionsValueChangesTracked::getIinLimitTempAmbientAdjustChanged( void ) { return iinLimitTempAmbientAdjustChanged; } void protectionsValueChangesTracked::changeIinLimitTempAmbientAdjust(const signed int &s) { iinLimitTempAmbientAdjust = s; iinLimitTempAmbientAdjustChanged = true; } bool protectionsValueChangesTracked::getEFInputCurrentThresholdChanged( void ) { return efInputCurrentThresholdChanged; } void protectionsValueChangesTracked::changeEFInputCurrentThreshold( const unsigned int & s) { qDebug() << Q_FUNC_INFO << " new value:" << s; efInputCurrentThreshold = s; efInputCurrentThresholdChanged = true; } bool protectionsValueChangesTracked::getEFOccurrenceThresholdChanged( void ) { return efOccurrenceThresholdChanged; } void protectionsValueChangesTracked::changeEFOccurrenceThreshold( const unsigned int & s) { qDebug() << Q_FUNC_INFO << " new value:" << s; efOccurrenceThreshold = s; efOccurrenceThresholdChanged = true; } bool protectionsValueChangesTracked::getEFCountDownTimerChanged( void ) { return efCountDownTimerChanged; } void protectionsValueChangesTracked::changeEFCountDownTimer( const unsigned int & s) { qDebug() << Q_FUNC_INFO << " new value:" << s; efCountDownTimer = s; efCountDownTimerChanged = true; } bool protectionsValueChangesTracked::getEFAlphaNumeratorChanged( void ) { return efAlphaNumeratorChanged; } void protectionsValueChangesTracked::changeEFAlphaNumerator( const unsigned int & s ) { qDebug() << Q_FUNC_INFO << " new value:" << s; efAlphaNumerator = s; efAlphaNumeratorChanged = true; } bool protectionsValueChangesTracked::getFETThresholdChanged( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(fetThresholdChanged); return fetThresholdChanged; } void protectionsValueChangesTracked::changeFETThreshold(const int &s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; fetThreshold = s; fetThresholdChanged = true; } bool protectionsValueChangesTracked::getFETDeltaCurrentChanged( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(fetDeltaCurrentChanged); return fetDeltaCurrentChanged; } void protectionsValueChangesTracked::changeFETDeltaCurrent(const int &s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; fetDeltaCurrent = s; fetDeltaCurrentChanged = true; } bool protectionsValueChangesTracked::getProtection1Changed( void ) { qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection1Changed); return protection1Changed; } void protectionsValueChangesTracked::changeProtection1( const unsigned int & s) { qDebug() << Q_FUNC_INFO << " new value:" << s; protection1 = s; protection1Changed = true; } bool protectionsValueChangesTracked::getProtection2Changed( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection2Changed); return protection2Changed; } void protectionsValueChangesTracked::changeProtection2( const unsigned int & s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; protection2 = s; protection2Changed = true; } bool protectionsValueChangesTracked::getProtection3Changed( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection3Changed); return protection3Changed; } void protectionsValueChangesTracked::changeProtection3( const unsigned int & s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; protection3 = s; protection3Changed = true; } bool protectionsValueChangesTracked::getProtection4Changed( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(protection4Changed); return protection4Changed; } void protectionsValueChangesTracked::changeProtection4( const unsigned int & s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; protection4 = s; protection4Changed = true; } bool protectionsValueChangesTracked::getAMFTimer1Changed( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfTimer1Changed); return amfTimer1Changed; } void protectionsValueChangesTracked::changeAMFTimer1( const unsigned int & s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; amfTimer1 = s; amfTimer1Changed = true; } bool protectionsValueChangesTracked::getAMFTimer2Changed( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfTimer2Changed); return amfTimer2Changed; } void protectionsValueChangesTracked::changeAMFTimer2( const unsigned int & s) { //qDebug() << Q_FUNC_INFO << " new value:" << s; amfTimer2 = s; amfTimer2Changed = true; } bool protectionsValueChangesTracked::getAMFV_OVChanged( void ) { //qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfV_OVChanged); return amfV_OVChanged; } void protectionsValueChangesTracked::changeAMFV_OV( const unsigned int & s) { //qDebug() << Q_FUNC_INFO << " new value:" << s; amfV_OV = s; amfV_OVChanged = true; } bool protectionsValueChangesTracked::getAMFI_OCChanged( void ) { //qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfI_OCChanged); return amfI_OCChanged; } void protectionsValueChangesTracked::changeAMFI_OC( const unsigned int & s) { // qDebug() << Q_FUNC_INFO << " new value:" << s; amfI_OC = s; amfI_OCChanged = true; } bool protectionsValueChangesTracked::getAMFMPPOffCyclesChanged( void ) { // qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfMPPOffCycles); return amfMPPOffCyclesChanged; } void protectionsValueChangesTracked::changeAMFMPPOffCycles(const unsigned int &s) { //qDebug() << Q_FUNC_INFO << " new value:" << s; amfMPPOffCycles = s; amfMPPOffCyclesChanged = true; } bool protectionsValueChangesTracked::getAMFMPPTimesOffChanged( void ) { //qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfMPPTimesOff); return amfMPPTimesOffChanged; } void protectionsValueChangesTracked::changeAMFMPPTimesOff(const unsigned int &s) { //qDebug() << Q_FUNC_INFO << " new value:" << s; amfMPPTimesOff = s; amfMPPTimesOffChanged = true; } bool protectionsValueChangesTracked::getAMFDebugChanged( void ) { //qDebug() << Q_FUNC_INFO << " returning " << QString::number(amfDebug); return amfDebugChanged; } void protectionsValueChangesTracked::changeAMFDebug(const unsigned int &s) { //qDebug() << Q_FUNC_INFO << " new value:" << s; amfDebug = s; amfDebugChanged = true; } void protectionsValueChangesTracked::sendAllChangedValuesToMemory( const QString intendedFor, const QString theFamily ) { qDebug() << Q_FUNC_INFO << " send changed values to optimizer " << intendedFor << " ..."; QString aCommand; // Need MAC address or * QString commandPrefix("s m"); if (intendedFor == "*") { commandPrefix = "s "; } if (efInputCurrentThresholdChanged == true) { qDebug() << Q_FUNC_INFO << " send change of efInputCurrentThreshold:" << efInputCurrentThreshold << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetEFInputCurrentThreshold + ShortIntegerRegisterCommand + QString::number(efInputCurrentThreshold); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (efOccurrenceThresholdChanged == true) { qDebug() << Q_FUNC_INFO << " send change of efOccurrenceThreshold:" << efOccurrenceThreshold << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_SetEFOccurrentThreshold + ByteRegisterCommand + QString::number(efOccurrenceThreshold); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (efCountDownTimerChanged == true) { qDebug() << Q_FUNC_INFO << " send change of efCountDownTimer:" << efCountDownTimer << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_SetEFCountDownTimer + ByteRegisterCommand + QString::number(efCountDownTimer); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (efAlphaNumeratorChanged == true) { qDebug() << Q_FUNC_INFO << " send change of efAlphaNumerator:" << efAlphaNumerator << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_SetEFAlphaNumerator + ByteRegisterCommand + QString::number(efAlphaNumerator); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (fetCountChanged == true) { // qDebug() << Q_FUNC_INFO << " send change of fetCount:" << fetCount << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_FETFailureCount + ShortIntegerRegisterCommand + QString::number(fetCount); // qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (fetThresholdChanged == true) { //qDebug() << Q_FUNC_INFO << " send change of fetThreshold:" << fetThreshold << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_FETCurrentThreshold + ShortIntegerRegisterCommand + QString::number(fetThreshold); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (fetDeltaCurrentChanged == true) { //qDebug() << Q_FUNC_INFO << " send change of fetThreshold:" << fetDeltaCurrent << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_FETDeltaI + ShortIntegerRegisterCommand + QString::number(fetDeltaCurrent); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (protection1Changed == true) { if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd)) { //qDebug() << Q_FUNC_INFO << " send change of VhvVoutLimit:" << protection1 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_VhvLimitVout + ShortIntegerRegisterCommand + QString::number(protection1); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd)) { qDebug() << Q_FUNC_INFO << " send change of VoutLimitCount:" << protection1 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetVoutLimitCount + ShortIntegerRegisterCommand + QString::number(protection1); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } } if (protection2Changed == true) { if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd)) { //qDebug() << Q_FUNC_INFO << " send change of IhvVoutLimit:" << protection2 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_IhvLimitVout + ShortIntegerRegisterCommand + QString::number(protection2); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd)) { qDebug() << Q_FUNC_INFO << " send change of VoutLimit:" << protection2 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetVoutLimit + ShortIntegerRegisterCommand + QString::number(protection2); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } } if (protection3Changed == true) { if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd)) { //qDebug() << Q_FUNC_INFO << " send change of VhvVinsLimit:" << protection3 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_VhvLimitVins + ShortIntegerRegisterCommand + QString::number(protection3); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd)) { qDebug() << Q_FUNC_INFO << " send change of IoutLimitCount:" << protection3 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetIoutLimitCount + ShortIntegerRegisterCommand + QString::number(protection3); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } } if (protection4Changed == true) { if ((theFamily == Family1300V) || (theFamily == Family1300V_2nd)) { //qDebug() << Q_FUNC_INFO << " send change of IhvVinsLimit:" << protection4 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_IhvLimitVins + ShortIntegerRegisterCommand + QString::number(protection4); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } else if ((theFamily == Family1500V) || (theFamily == Family1500V_30) || (theFamily == Family1500V_2nd)) { qDebug() << Q_FUNC_INFO << " send change of IoutLimit:" << protection4 << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_SetIoutLimit + ShortIntegerRegisterCommand + QString::number(protection4); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } } if (amfTimer1Changed == true) { //qDebug() << Q_FUNC_INFO << " send change of amfTimer1:" << amfTimer1 << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_AMFTimer1 + ByteRegisterCommand + QString::number(amfTimer1); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (amfTimer2Changed == true) { //qDebug() << Q_FUNC_INFO << " send change of amfTimer2:" << amfTimer2 << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_AMFTimer2 + ByteRegisterCommand + QString::number(amfTimer2); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (amfV_OVChanged == true) { //qDebug() << Q_FUNC_INFO << " send change of amfV_OV:" << amfV_OV << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_AMFV_OV + ShortIntegerRegisterCommand + QString::number(amfV_OV); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (amfI_OCChanged == true) { //qDebug() << Q_FUNC_INFO << " send change of amfI_OC:" << amfI_OC << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_AMFI_OC + ShortIntegerRegisterCommand + QString::number(amfI_OC); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if ((amfMPPOffCyclesChanged == true) || (amfMPPTimesOffChanged == true)) { // qDebug() << Q_FUNC_INFO << " send change of amfMPPOffCycles:" << amfMPPOffCycles << " and/or change of amfMPPTimesOff:" << amfMPPTimesOff << " to gateway."; // qDebug() << Q_FUNC_INFO << " (0xF0 & (amfMPPOffCycles < 4)) => " << (0x00F0 & (amfMPPOffCycles << 4)) << " from " << (amfMPPOffCycles << 4); unsigned char value = ((0x00F0 & (amfMPPOffCycles << 4)) | (0x000F & amfMPPTimesOff)); aCommand = commandPrefix + intendedFor + ByteRegister_AMF_Timer2MPPOffCyclesAndTimesToCycle + ByteRegisterCommandInHex + QString::number(value,16); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (amfDebugChanged == true) { // qDebug() << Q_FUNC_INFO << " send change of amfDebug:" << amfDebug << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_AMF_Debug + ByteRegisterCommand + QString::number(amfDebug); //qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (iinLimitChanged == true) { qDebug() << Q_FUNC_INFO << " send change of iinLimit:" << iinLimit << " to gateway."; aCommand = commandPrefix + intendedFor + ShortIntegerRegister_IinLimit + ShortIntegerRegisterCommand + QString::number(iinLimit); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (iinLimitOCStepsChanged == true) { qDebug() << Q_FUNC_INFO << " send change of iinLimitOCSteps:" << iinLimitOCSteps << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_SetIinLimitOCSteps + ByteRegisterCommand + QString::number(iinLimitOCSteps); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (iinLimitOCDelayChanged == true) { qDebug() << Q_FUNC_INFO << " send change of iinLimitOCDelay:" << iinLimitOCDelay << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_SetIinLimitOCDelay + ByteRegisterCommand + QString::number(iinLimitOCDelay); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } if (iinLimitTempAmbientAdjustChanged == true) { qDebug() << Q_FUNC_INFO << " send change of iinLimitTempAmbientAdjust:" << iinLimitTempAmbientAdjust << " to gateway."; aCommand = commandPrefix + intendedFor + ByteRegister_SetIinLimitTempAmbientAdjust + ByteRegisterCommand + QString::number(iinLimitTempAmbientAdjust); qDebug() << Q_FUNC_INFO << " emit command:" << aCommand; emit publishCommand(aCommand); } }
[ "lcoburn@ampt.com" ]
lcoburn@ampt.com
6a8a4f962e338fc9e65d8984f44ce536a62d84a8
1ee6daace32d2b103cc29f36e836d23426dd76de
/553e4a8d6d656372d3000000/code/RobotAI.cpp
c7707cc7215eefb2ec56e3eab739a7a88b55a798
[ "Apache-2.0" ]
permissive
MechEmpire/Mechempire-meches
874ae3360c74e25573cb5bc2c3872f2696258744
aa95b15f061f4179c9061595e73c7127587cc4df
refs/heads/master
2021-01-14T12:27:01.390406
2015-06-06T07:42:03
2015-06-06T07:42:03
35,320,888
1
0
null
null
null
null
UTF-8
C++
false
false
23,793
cpp
#include "RobotAI.h" #include<iostream> RobotAI::RobotAI() { } RobotAI::~RobotAI() { } //----------------------------------------------------- //1.必须完成的战斗核心 //----------------------------------------------------- static int frame = 0; void RobotAI::Update(RobotAI_Order& order,const RobotAI_BattlefieldInformation& info,int myID) { //帧操纵函数 //功能:在每一帧被调用,完成你的机甲在这一帧的动作决策 //参数:order ... 机甲操纵指令,你在函数体中给它赋值以操纵机甲在这一帧的行为 // info ... 战场信息 // myID ... 自己机甲在info中robot数组对应的下标 // (这几个参数的详细说明在开发手册可以找到,你也可以在RobotAIstruct.h中直接找到它们的代码) auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1 - myID]; /*静态成员列表*/ static int hp_tag = tag.hp; /*静态成员列表*/ //开火操作 if (frame != 0) { onFire1(order, info, myID); } onTag1(order, info, myID); //躲避操纵 //isDodeg——判断是否执行躲避函数,如果执行则为true,将跳过后面的移动函数优先躲避 //bullet ——最近的子弹 bool isDodge = false; //int b_index_nearest = GetNearetBul(order, info, myID); //if (b_index_nearest != -1)//如果有敌方子弹则进行躲避判断 //{ // auto bullet = info.bulletInformation[b_index_nearest]; // isDodge = onDodge(order, info, myID, bullet); //} //获取地方子弹数组,并按距离升序排列 int b_tag = 0; for (int b_index = 0; b_index <= info.num_bullet; b_index++) { auto bullet = info.bulletInformation[b_index]; if (bullet.launcherID == myID)continue; b_tag++; } if (frame < 500) { /* cout << "zhen下面" << frame << endl << "无序数组" << endl;*/ for (int b_index = 0; b_index <= info.num_bullet; b_index++) { auto bullet = info.bulletInformation[b_index]; if (bullet.launcherID == myID)continue; //cout << dis(info.bulletInformation[b_index].circle, me.circle) << " & "; } //cout << endl; } int *bulArray = new int[b_tag]; int bulArray_index = 0; for (int b_index = 0; b_index <= info.num_bullet; b_index++) { auto bullet = info.bulletInformation[b_index]; if (bullet.launcherID == myID)continue; bulArray[bulArray_index] = b_index; bulArray_index++; } /*if (frame < 500) { cout << "未排数组" << GetNearetBul(order, info, myID) << "^" << bulArray[0] << endl; for (int i = 0; i < bulArray_index; i++) cout << dis(info.bulletInformation[bulArray[i]].circle, me.circle) << " & "; cout << endl; }*/ for (int i = bulArray_index; i > 0; i--) { for (int j = 0; j < bulArray_index-1; j++) { if (dis(info.bulletInformation[bulArray[j]].circle, me.circle) <= dis(info.bulletInformation[bulArray[j + 1]].circle, me.circle) ) continue; else { int temp = bulArray[j + 1]; bulArray[j + 1] = bulArray[j]; bulArray[j] = temp; } } } if (bulArray_index!=0)//如果有敌方子弹则进行躲避判断 { int b_index_nearest = bulArray[0]; //if (frame < 500) //{ // cout << "有序数组" << GetNearetBul(order, info, myID) << "^" << bulArray[0] << endl; // for (int i = 0; i < bulArray_index; i++) // cout << dis(info.bulletInformation[bulArray[i]].circle, me.circle) << " & "; // cout << endl; //} auto bullet = info.bulletInformation[b_index_nearest]; //isDodge = onDodge(order, info, myID, bullet); } isDodge = onDodge2(order, info, myID); //正常移动操作 //isDodge = false; if (!isDodge) { onMove1(order, info, myID, tag.circle); } //静态变量更新 hp_tag = tag.hp; frame++; delete bulArray; } void RobotAI::ChooseArmor(weapontypename& weapon,enginetypename& engine,bool a) { //挑选装备函数 //功能:在战斗开始时为你的机甲选择合适的武器炮塔和引擎载具 //参数:weapon ... 代表你选择的武器,在函数体中给它赋值 // engine ... 代表你选择的引擎,在函数体中给它赋值 //tip: 括号里的参数是枚举类型 weapontypename 或 enginetypename // 开发文档中有详细说明,你也可以在RobotAIstruct.h中直接找到它们的代码 //tip: 最后一个bool是没用的。。那是一个退化的器官 srand(time(0)); MyCar = rand() % 2+ 1; MyCar = AFV_Esaw; if (MyCar == AFV_Esaw)//幽灵电锯 { weapon = WT_ElectricSaw; engine = ET_AFV; } if (MyCar == AFV_Prism)//幽灵光棱 { weapon = WT_Prism; engine = ET_AFV; } if (MyCar == AFV_WT_Machinegun) { weapon = WT_Machinegun; engine = ET_AFV; } } //----------------------------------------------------- //2.个性信息 //----------------------------------------------------- string RobotAI::GetName() { //返回你的机甲的名字 return "艾欧尼亚闪电"; } string RobotAI::GetAuthor() { //返回机甲制作人或团队的名字 return "爆炸何"; } //返回一个(-255,255)之间的机甲武器炮塔的颜色偏移值(红、绿、蓝) //你可以在flash客户端的参数预览中预览颜色搭配的效果 int RobotAI::GetWeaponRed() { //返回一个-255-255之间的整数,代表武器红色的偏移值 return color; } int RobotAI::GetWeaponGreen() { //返回一个-255-255之间的整数,代表武器绿色的偏移值 return color; } int RobotAI::GetWeaponBlue() { //返回一个-255-255之间的整数,代表武器蓝色的偏移值 return color; } //返回一个(-255,255)之间的机甲引擎载具的颜色偏移值(红、绿、蓝) //你可以在flash客户端的参数预览中预览颜色搭配的效果 int RobotAI::GetEngineRed() { //返回一个-255-255之间的数,代表载具红色的偏移值 return color; } int RobotAI::GetEngineGreen() { //返回一个-255-255之间的整数,代表载具绿色的偏移值 return color; } int RobotAI::GetEngineBlue() { //返回一个-255-255之间的整数,代表载具蓝色的偏移值 return color; } //----------------------------------------------------- //3.用不用随你的触发函数 //----------------------------------------------------- void RobotAI::onBattleStart(const RobotAI_BattlefieldInformation& info,int myID) { //一场战斗开始时被调用,可能可以用来初始化 //参数:info ... 战场信息 // myID ... 自己机甲在info中robot数组对应的下标 } void RobotAI::onBattleEnd(const RobotAI_BattlefieldInformation& info,int myID) { //一场战斗结束时被调用,可能可以用来析构你动态分配的内存空间(如果你用了的话) //参数:info ... 战场信息 // myID ... 自己机甲在info中robot数组对应的下标 system("Pause"); } void RobotAI::onSomeoneFire(int fireID) { //有机甲开火时被调用 //参数:fireID ... 开火的机甲下标 } void RobotAI::onHit(int launcherID,bullettypename btn) { //被子弹击中时被调用 //参数:btn ... 击中你的子弹种类(枚举类型) } //TODO:这里可以实现你自己的函数 //判断和敌方之间是否有障碍物,ArID为障碍物ID bool RobotAI::HaveBarrier(const RobotAI_BattlefieldInformation& info,const int myID,const int ArID) { auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1 - myID]; Circle obs_circle = info.obstacle[ArID]; double pdis = pointdis(me.circle, tag.circle, obs_circle); if (pdis > info.obstacle[ArID].r) return false; else { if (((me.circle.y - obs_circle.y)*(tag.circle.y - obs_circle.y)) && ((me.circle.x - obs_circle.x)*(tag.circle.x - obs_circle.x))) return false; else return true; } } bool RobotAI::HaveBarrier(const RobotAI_BattlefieldInformation& info, const int myID, Circle obs_circle) { auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1 - myID]; double c = dis(tag.circle, obs_circle); double b = obs_circle.r; double a = sqrt(c*c - b*b); double rotaob = abvalue( atan2(b ,a) * 180 / PI); double rota1 = atan2(obs_circle.y-tag.circle.y, obs_circle.x-tag.circle.x) * 180 / PI;//障碍物和tag夹角 double c2 = dis(tag.circle, me.circle); double b2 = me.circle.r; double a2 = sqrt(c2*c2 - b2*b2); double rotame = abvalue(atan2(b2, a2) * 180 / PI); double rota2 = atan2(me.circle.y - tag.circle.y, me.circle.x - tag.circle.x) * 180 / PI;//我方和tag夹角 double r1 = rota2 + rotame; double r2 = rota2 - rotame; double t1 = rota1 + rotaob; double t2 = rota1 - rotaob; AngleAdjust(r1); AngleAdjust(r2); AngleAdjust(t1); AngleAdjust(t2); if (r1 <= t1&&r2 >= t2) return true; else return false; } int RobotAI::GetNearetBul(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID) { auto me = info.robotInformation[myID]; //cout << "地图上子弹数量" << info.num_bullet + 1 << endl; int b_index_near = -1; int b_tag = 0;//敌方子弹数 for (int b_index = 0; b_index <= info.num_bullet; b_index++) { //cout << "判断第" << b_index << "子弹" << endl; auto bullet = info.bulletInformation[b_index]; if (bullet.launcherID == myID) { continue; } b_tag++; if (b_tag == 1)b_index_near = b_index; //cout << "第" << b_index << "子弹是敌方子弹" << endl; if (dis(bullet.circle, me.circle) <= dis(info.bulletInformation[b_index_near].circle, me.circle)) b_index_near = b_index; } //cout << "最近!" << b_index_near << endl; return b_index_near;//如果没有找到最近的敌方子弹就返回-1 } void RobotAI::onTag1(RobotAI_Order& order,const RobotAI_BattlefieldInformation& info, const int myID)//瞄准函数(不带预判) { auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1 - myID]; double dx = tag.circle.x - me.circle.x; double dy = tag.circle.y - me.circle.y; double Rota = atan2(dy, dx) * 180 / PI; double wpRota = info.robotInformation[myID].weaponRotation; double offset = wpRota - Rota; if (abvalue(offset) >= 180) { if (offset > 0) order.wturn = 1; else order.wturn = -1; } else{ if (offset > 0) order.wturn = -1; else order.wturn = 1; } } double RobotAI::onTagRota(const RobotAI_BattlefieldInformation& info, const int myID) { auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1 - myID]; double dx = tag.circle.x - me.circle.x; double dy = tag.circle.y - me.circle.y; double Rota = atan2(dy, dx) * 180 / PI; double wpRota = info.robotInformation[myID].weaponRotation; double offset = wpRota - Rota; return offset; } void RobotAI::onMove1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const Circle circle_tag) { onMove1(order, info, myID, circle_tag.x, circle_tag.y); } void RobotAI::onMove1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID,const double x_tag,const double y_tag) { auto me = info.robotInformation[myID]; double dx = x_tag - me.circle.x; double dy = y_tag - me.circle.y; double Rota = atan2(dy, dx) * 180 / PI; onMove1(order, info, myID, Rota); } void RobotAI::onMoveCircle(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const double x_tag, const double y_tag) { auto me = info.robotInformation[myID]; double dx = x_tag - me.circle.x; double dy = y_tag - me.circle.y; double Rota = atan2(dy, dx) * 180 / PI; Circle tag_circle; tag_circle.x = x_tag; tag_circle.y = y_tag; if (dis(me.circle, tag_circle) <= me.circle.r) order.run = 0; else onMove1(order, info, myID, Rota); } void RobotAI::onMove1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const double rota_tag) { auto me = info.robotInformation[myID]; double Rota = rota_tag; double Rota_eng = me.engineRotation; double offset = Rota_eng - Rota; switch (MyCar) { case AFV_Esaw: case AFV_WT_Machinegun: case AFV_Prism: if (abvalue(offset) >= 180) { if (offset > 0) order.eturn = 1; else order.eturn = -1; } else{ if (offset > 0) order.eturn = -1; else order.eturn = 1; } order.run = 1; break; default: break; } } void RobotAI::onFire1(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID) { auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1 - myID]; switch (MyCar) { case AFV_Esaw: if (tag.weaponTypeName == WT_ElectricSaw) { if ( !HaveBarrier(info, myID, 0) && !HaveBarrier(info, myID, 1) && (onTagRota(info, myID)<3) && (onTagRota(info, myID)>-3) && dis(me.circle, tag.circle)<120 + tag.circle.r ) order.fire = 1; break; } if ( !HaveBarrier(info, myID, 0) && !HaveBarrier(info, myID, 1) && dis(me.circle, tag.circle)<95 + tag.circle.r ) order.fire = 1; break; case AFV_Prism: case AFV_WT_Machinegun: if ( !HaveBarrier(info, myID, 0) && !HaveBarrier(info, myID, 1) && (onTagRota(info, myID)<3)&& (onTagRota(info, myID)>-3) ) order.fire = 1; break; default: break; } } bool RobotAI::onDodge(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID,const RobotAI_BulletInformation& bullet) //躲闪函数,如果发出了躲避命令,则返回true; { auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1-myID]; bool inHitRange = dis(bullet.circle, me.circle) <= 0.6 * me.circle.r *getBulletSpeed(bullet.type);//判断在监控范围内再躲 double Rota_bulv = atan2(bullet.vy, bullet.vx) * 180 / PI;//子弹速度方向 double Rota_bulv_ag = Rota_bulv - 180;//子弹速度反方向 double tag_vrota = atan2(tag.vy, tag.vx) * 180 / PI;//对方机甲移动方向 AngleAdjust(Rota_bulv_ag); auto Type_Bul = bullet.type; switch (MyCar) { case AFV_Esaw: case AFV_Prism: case AFV_WT_Machinegun: if (order.fire == 1) return false; switch (tag.weaponTypeName) { case WT_Shotgun: case WT_Machinegun: if ((tag.remainingAmmo + 2)*getBulletDamage(bullet.type) < me.hp || (dis(me.circle, tag.circle) <= me.circle.r * 3) ) { onMove1(order, info, myID, tag.circle); return true; } else{ int arsen; if (dis(info.arsenal[0].circle, me.circle) >= dis(info.arsenal[1].circle, me.circle)) arsen = 1; else arsen = 0; if (info.arsenal[arsen].respawning_time == 0) { onMove1(order, info, myID, info.arsenal[arsen].circle); return true; } if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1])) return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]); else return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]); } case WT_Cannon: case WT_Apollo: case WT_PlasmaTorch: if ( (tag.remainingAmmo+2)*getBulletDamage(bullet.type) < me.hp|| (dis(me.circle, tag.circle) <= me.circle.r * 3) ) { onMove1(order, info, myID, tag.circle ); return true; } else{ if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1])) return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]); else return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]); } //接近型躲避方案1 //AngleAdjust(tag_vrota); //if (tag_vrota>me.engineRotation) //{ // order.eturn = 1; // order.run = 1; //} //else //{ // order.eturn = -1; // order.run = 1; //} //直接绕圈躲避方案2 return false; break; default: //躲低速子弹,躲避方案3 if (!inHitRange) { return false; } if (me.engineRotation >= Rota_bulv_ag) order.eturn = -1; else order.eturn = 1; order.run = 1; return true; break; } break; /*…………………………………………………………*/ return false; } } bool RobotAI::onDodge2(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID) //躲闪函数,如果发出了躲避命令,则返回true; { auto me = info.robotInformation[myID]; auto tag = info.robotInformation[1 - myID]; double dy = me.circle.y-tag.circle.y; double dx = me.circle.x - tag.circle.x; double Rota_bulv = tag.engineRotation-atan2(dy, dx) * 180 / PI;//子弹速度方向 AngleAdjust(Rota_bulv); bool isNear; switch (MyCar) { case AFV_Esaw: case AFV_Prism: case AFV_WT_Machinegun: if (order.fire == 1) return false; switch (tag.weaponTypeName) { case WT_Shotgun: if ((tag.remainingAmmo + 1) * 50 < me.hp || (dis(me.circle, tag.circle) <= me.circle.r *2)) { onMove1(order, info, myID, tag.circle); return true; } else{ int arsen; if (dis(info.arsenal[0].circle, me.circle) >= dis(info.arsenal[1].circle, me.circle)) arsen = 1; else arsen = 0; if (info.arsenal[arsen].respawning_time == 0&& dis(info.arsenal[arsen].circle,tag.circle)>=700) { onMove1(order, info, myID, info.arsenal[arsen].circle); return true; } if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1])) return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]); else return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]); } break; case WT_Machinegun: if ((tag.remainingAmmo + 5)*7 < me.hp|| (dis(me.circle, tag.circle) <= me.circle.r * 2) ) { onMove1(order, info, myID, tag.circle); return true; } else{ int arsen; if (dis(info.arsenal[0].circle, me.circle) >= dis(info.arsenal[1].circle, me.circle)) arsen = 1; else arsen = 0; if (info.arsenal[arsen].respawning_time == 0) { onMove1(order, info, myID, info.arsenal[arsen].circle); return true; } if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1])) return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]); else return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]); } break; case WT_Cannon: case WT_Apollo: case WT_PlasmaTorch: if ((tag.remainingAmmo + 2)*25 < me.hp || (dis(me.circle, tag.circle) <= me.circle.r * 3) ) { onMove1(order, info, myID, tag.circle); return true; } int arsen; if (dis(me.circle, info.obstacle[0]) >= dis(me.circle, info.obstacle[1])) return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[1]); else return onDodgeCircle(order, info, myID, tag.circle, info.obstacle[0]); //接近型躲避方案1 //AngleAdjust(tag_vrota); //if (tag_vrota>me.engineRotation) //{ // order.eturn = 1; // order.run = 1; //} //else //{ // order.eturn = -1; // order.run = 1; //} //直接绕圈躲避方案2 return false; break; default: //躲低速子弹,躲避方案3 return false; } break; /*…………………………………………………………*/ return false; } } bool RobotAI::onDodgeCircle(RobotAI_Order& order, const RobotAI_BattlefieldInformation& info, const int myID, const Circle tag, const Circle ob){ if (HaveBarrier(info, myID, ob)) { order.run = 0; return true; } //if (dis(ob, info.robotInformation[myID].circle) <= ob.r * 2) //{ // cout << "在圈后" << endl; // order.run = 0; // return true; //} double a = tag.x - ob.x; double b = tag.y - ob.y; double c = sqrt(a*a + b*b); double tagx = ob.x - dis(info.robotInformation[myID].circle,ob)*a / c; double tagy = ob.y - dis(info.robotInformation[myID].circle,ob)*b / c; onMoveCircle(order, info, myID, tagx, tagy); return true; } bool RobotAI::WillNotHit(const RobotAI_BulletInformation& bullet, const RobotAI_RobotInformation& rotinfo) //判断在之后短时间内绝对不可能达到的子弹 { double Rota_bul = atan2(bullet.vy, bullet.vx) * 180 / PI;//子弹射击方向角 AngleAdjust(Rota_bul); Beam bulbeam; bulbeam.x = bullet.circle.x; bulbeam.y = bullet.circle.y; bulbeam.rotation = Rota_bul; bool HitTest=HitTestBeamCircle(bulbeam, rotinfo.circle);//碰撞测试 double Rota_engine = rotinfo.engineRotation; double Rota_engine_downb = AnglePlus(Rota_engine, -90); double Rota_engine_upb = AnglePlus(Rota_engine, 90); bool vRotaTest = (Rota_bul<Rota_engine_upb && Rota_bul>Rota_engine_downb);//子弹角度测试 double dy = bullet.circle.y - rotinfo.circle.y; double dx = bullet.circle.x - rotinfo.circle.x; double Rota_place = atan2(dy, dx) * 180 / PI; AngleAdjust(Rota_place); bool pRotaTest = (Rota_place<Rota_engine_upb && Rota_place>Rota_engine_downb); if (!HitTest&&vRotaTest&&pRotaTest) return true;//如果不会打到了就返回true else return false; } bool RobotAI::WillHit(const RobotAI_BulletInformation& bullet, const RobotAI_RobotInformation& rotinfo) //判断子弹能否击中rotinfo { //double pointdis_me_bul = pointdis( // bullet.circle.x, // bullet.circle.y, // bullet.circle.x + bullet.vx, // bullet.circle.y + bullet.vy, // rotinfo.circle.x, // rotinfo.circle.y // ); //double Rota = atan2(rotinfo.circle.y - bullet.circle.y, // rotinfo.circle.x- bullet.circle.x) * 180 / PI;//子弹为原点,子弹和机甲中心所构成的角 //double Rota_bul = atan2(bullet.vy-rotinfo.vx, bullet.vx-rotinfo.vy) * 180 / PI;//子弹相对机甲射击方向角 //double dis_me_bul = sqrt(dis(bullet.circle, rotinfo.circle)); //double Rota_hit = atan2( // rotinfo.circle.r, // sqrt(dis_me_bul*dis_me_bul - rotinfo.circle.r*rotinfo.circle.r) // );//能击中的角度范围 //if ( // pointdis_me_bul <= rotinfo.circle.r && // (Rota_bul<Rota + abvalue(Rota_hit) || Rota_bul>Rota - abvalue(Rota_hit)) // ) // return true; //else // return false; double Rota_bul = atan2(bullet.vy, bullet.vx ) * 180 / PI;//子弹射击方向角 AngleAdjust(Rota_bul); Beam bulbeam; bulbeam.x = bullet.circle.x; bulbeam.y = bullet.circle.y; bulbeam.rotation = Rota_bul; return HitTestBeamCircle(bulbeam, rotinfo.circle); } double RobotAI::abvalue(double x) { if (x >= 0) return x; else return -x; } double RobotAI::pointdis(double x1, double y1, double x2, double y2, double x3, double y3) //返回(x3,y3)到(x1,y1),(x2,y2)连线的距离 { double A = (y2 - y1) / (x2 - x1); double B = -1.0; double C = y1 - (y2 - y1)*x1 / (x2 - x1); double son = A*x3 + B*y3 + C; double Abvalue = son / sqrt(A*A + B*B); if (Abvalue > 0) return Abvalue; else return -Abvalue; } double pointdis(double k, double x1, double y1, double x3, double y3) { double A = k; double B = -1.0; double C = y1 - k*x1; double son = A*x3 + B*y3 + C; double Abvalue = son / sqrt(A*A + B*B); if (Abvalue > 0) return Abvalue; else return -Abvalue; } double RobotAI::pointdis(const Circle a1, const Circle a2, const Circle a3) { return pointdis(a1.x, a1.y, a2.x, a2.y, a3.x, a3.y); } double RobotAI::dis(double x1, double y1, double x2, double y2) { return sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)); } double RobotAI::dis(const Circle& a, const Circle& b){ return dis(a.x, a.y, b.x, b.y); }
[ "tairyguo@gmail.com" ]
tairyguo@gmail.com
6951c61901ad8d1d8c9d51f2dd83e6535b2e9fe2
745d39cad6b9e11506d424f008370b5dcb454c45
/BOJ/16000/16212.cpp
942f93a1f95a9765c35fa1e1c85b294da89305eb
[]
no_license
nsj6646/PS
0191a36afa0c04451d704d8120dc25f336988a17
d53c111a053b159a0fb584ff5aafc18556c54a1c
refs/heads/master
2020-04-28T09:18:43.333045
2019-06-19T07:19:03
2019-06-19T07:19:03
175,162,727
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int n; cin>>n; vector<int> v(n); for(int i=0;i<n;++i){ cin>>v[i]; } sort(v.begin(),v.end()); for(int x:v){ cout<<x<<' '; } return 0; }
[ "nsj6646@gmail.com" ]
nsj6646@gmail.com
a0487e8dda71db2471557894d60f9ddec4268113
9870e11c26c15aec3cc13bc910e711367749a7ff
/SPOJ/sp_375.cpp
fa0e7ff593c43623389d20a3db0e8e05a5df5fb8
[]
no_license
liuq901/code
56eddb81972d00f2b733121505555b7c7cbc2544
fcbfba70338d3d10bad2a4c08f59d501761c205a
refs/heads/master
2021-01-15T23:50:10.570996
2016-01-16T16:14:18
2016-01-16T16:14:18
12,918,517
1
1
null
null
null
null
UTF-8
C++
false
false
6,575
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> struct data { int x,l,r,left,right; }; struct data tree[20000]; int sum,c[10001],d[10001],b[10001],r[10001],s[10001],g[10001],father[10001],heavy[10001]; int w[10001],len[10001],l[20000],e[20000],a[20000][4],h[10001][7],f[16][20000][2]; int main() { void work(); int i,t; scanf("%d",&t); for (i=1;i<=t;i++) work(); system("pause"); return(0); } void work() { void init(int),build(),floodfill(int),change(int,int); int lca(int,int),find(int,int); int n,m,x,y,z,i,j,t,ans; char order[10]; scanf("%d",&n); init(n); build(); e[0]=e[1]=1; memset(g,0,sizeof(g)); g[1]=1; l[1]=0; floodfill(1); memset(g,0,sizeof(g)); for (i=1;i<=e[0];i++) l[i]=d[e[i]]; for (i=1;i<=e[0];i++) { if (g[e[i]]) continue; g[e[i]]=1; r[e[i]]=i; } m=(int)(log(e[0])/log(2)+0.00001); memset(f,26,sizeof(f)); for (i=1;i<=e[0];i++) { f[0][i][0]=l[i]; f[0][i][1]=e[i]; } t=1; for (i=1;i<=m;i++) { for (j=1;j<=e[0];j++) { if (j+t>e[0]) break; if (f[i-1][j][0]<f[i][j][0]) { f[i][j][0]=f[i-1][j][0]; f[i][j][1]=f[i-1][j][1]; } if (f[i-1][j+t][0]<f[i][j][0]) { f[i][j][0]=f[i-1][j+t][0]; f[i][j][1]=f[i-1][j+t][1]; } } t*=2; } while (1) { scanf("%s",order); if (order[0]=='D') break; scanf("%d%d%*c",&x,&y); if (order[0]=='C') change(x,y); else { ans=-2147483647; if (x!=y) { z=lca(x,y); t=find(x,z); if (t>ans) ans=t; t=find(y,z); if (t>ans) ans=t; } printf("%d\n",ans); } } } void init(int n) { void dfs(int,int); int i,t,x,y,z; int p[10000][3]; memset(b,0,sizeof(b)); for (i=1;i<=n-1;i++) { scanf("%d%d%d",&x,&y,&z); a[2*i-1][0]=y; a[2*i-1][1]=b[x]; b[x]=2*i-1; a[2*i][0]=x; a[2*i][1]=b[y]; b[y]=2*i; p[i][0]=x; p[i][1]=y; p[i][2]=z; } c[0]=0; dfs(1,0); memset(b,0,sizeof(b)); for (i=1;i<=n-1;i++) { if (c[p[i][0]]>c[p[i][1]]) t=p[i][0],p[i][0]=p[i][1],p[i][1]=t; x=p[i][0]; y=p[i][1]; z=p[i][2]; father[y]=x; w[y]=z; a[i][0]=y; a[i][1]=z; a[i][2]=b[x]; a[i][3]=0; b[x]=i; } } void dfs(int x,int father) { int i; i=b[x]; c[x]=c[father]+1; while (i!=0) { if (a[i][0]!=father) dfs(a[i][0],x); i=a[i][1]; } } void build() { int count(int); void calc(int),search(int,int,int),make(int); int i; count(1); calc(1); sum=1; h[1][2]=1; search(1,1,1); len[0]=0; for (i=1;i<=sum;i++) make(i); } int count(int x) { int i,t; s[x]=1; i=b[x]; while (i!=0) { t=count(a[i][0]); s[x]+=t; i=a[i][2]; } return(s[x]); } void calc(int x) { int i,max,k; k=-1; max=0; i=b[x]; while (i!=0) { heavy[a[i][0]]=0; if (s[a[i][0]]>max) { max=s[a[i][0]]; k=i; } calc(a[i][0]); i=a[i][2]; } if (k!=-1) { a[k][3]=1; heavy[a[k][0]]=1; } } void search(int x,int t,int p) { int i; i=b[x]; h[x][0]=t; h[x][1]=p; h[t][3]=x; h[x][4]=h[x][5]=0; while (i!=0) { if (a[i][3]) { h[x][4]=a[i][0]; h[x][5]=i; if (s[a[i][0]]!=1) search(a[i][0],t,p+1); } else if (s[a[i][0]]!=1) { sum++; h[sum][2]=a[i][0]; search(a[i][0],sum,1); } i=a[i][2]; } } void make(int t) { void buildtree(int,int,int); int i,s; i=h[t][2]; s=0; while (i!=h[t][3]) { s++; len[s]=a[h[i][5]][1]; i=a[h[i][5]][0]; } s++; len[s]=a[h[i][5]][1]; len[0]++; h[t][6]=len[0]; buildtree(len[0],1,s); } void buildtree(int x,int l,int r) { int mid; mid=(l+r)/2; tree[x].l=l; tree[x].r=r; if (l==r) { tree[x].x=len[l]; return; } len[0]++; tree[x].left=len[0]; buildtree(len[0],l,mid); len[0]++; tree[x].right=len[0]; buildtree(len[0],mid+1,r); if (tree[tree[x].left].x>tree[tree[x].right].x) tree[x].x=tree[tree[x].left].x; else tree[x].x=tree[tree[x].right].x; } void floodfill(int x) { int i; i=b[x]; while (i!=0) { g[a[i][0]]=1; d[a[i][0]]=d[x]+1; e[0]++; e[e[0]]=a[i][0]; floodfill(a[i][0]); e[0]++; e[e[0]]=x; i=a[i][2]; } } void change(int x,int y) { void insert(int,int,int); int t,p; if (!a[x][3]) { a[x][1]=y; w[a[x][0]]=y; return; } t=h[h[father[a[x][0]]][0]][6]; p=h[father[a[x][0]]][1]; insert(t,p,y); } void insert(int x,int p,int t) { int mid; if (tree[x].l==tree[x].r) { tree[x].x=t; return; } mid=(tree[x].l+tree[x].r)/2; if (p<=mid) insert(tree[x].left,p,t); else insert(tree[x].right,p,t); if (tree[tree[x].left].x>tree[tree[x].right].x) tree[x].x=tree[tree[x].left].x; else tree[x].x=tree[tree[x].right].x; } int lca(int x,int y) { int t,i; if (r[x]>r[y]) t=x,x=y,y=t; t=(int)(log(r[y]-r[x])/log(2)+0.0001); if (f[t][r[x]][0]<f[t][r[y]-(1<<t)+1][0]) return(f[t][r[x]][1]); else return(f[t][r[y]-(1<<t)+1][1]); } int find(int x,int root) { int get(int,int,int); int t,p,q,ans; ans=-2147483647; while (x!=root) { if (!heavy[x]) { if (w[x]>ans) ans=w[x]; x=father[x]; continue; } p=h[father[x]][0]; q=h[root][0]; if (p==q) { t=get(h[p][6],h[root][1],h[father[x]][1]); if (t>ans) ans=t; break; } t=get(h[p][6],1,h[father[x]][1]); if (t>ans) ans=t; x=h[p][2]; } return(ans); } int get(int x,int l,int r) { int max(int,int); int mid; if (l==tree[x].l && r==tree[x].r) return(tree[x].x); mid=(tree[x].l+tree[x].r)/2; if (r<=mid) return(get(tree[x].left,l,r)); if (l>mid) return(get(tree[x].right,l,r)); return(max(get(tree[x].left,l,mid),get(tree[x].right,mid+1,r))); } int max(int x,int y) { if (x>y) return(x); else return(y); }
[ "liuq901@163.com" ]
liuq901@163.com
01e8ec44b80deffdd92d33706685a9deabbffac3
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nscene/src/nscene/nsurfacenode_main.cc
74d5e83ef12b4c20b501095b24518e59c6cfe3b1
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,575
cc
#include "precompiled/pchnscene.h" //------------------------------------------------------------------------------ // nsurfacenode_main.cc // (C) 2002 RadonLabs GmbH //------------------------------------------------------------------------------ #include "nscene/nsurfacenode.h" #include "nscene/nsceneshader.h" #include "nscene/nscenegraph.h" #include "nscene/nshadertree.h" #include "gfx2/ngfxserver2.h" #include "gfx2/nshader2.h" #include "gfx2/ntexture2.h" #include "kernel/ntimeserver.h" #include "nscene/ncscene.h" #include "entity/nentity.h" #include "kernel/ndebug.h" #include "nscene/nanimator.h" nNebulaScriptClass(nSurfaceNode, "nabstractshadernode"); //------------------------------------------------------------------------------ /** */ nSurfaceNode::nSurfaceNode() : shaderArray(4, 4) { // empty } //------------------------------------------------------------------------------ /** */ nSurfaceNode::~nSurfaceNode() { this->UnloadResources(); } //------------------------------------------------------------------------------ /** Unload all shaders. */ void nSurfaceNode::UnloadShaders() { int i; for (i = 0; i < this->shaderArray.Size(); i++) { if (this->shaderArray[i].IsShaderValid()) { this->shaderArray[i].GetShader()->Release(); this->shaderArray[i].Invalidate(); } } for (i = 0; i < this->shaderTreeArray.Size(); ++i) { if (this->shaderTreeArray[i].isvalid()) { this->shaderTreeArray[i]->Release(); this->shaderTreeArray[i].invalidate(); } } } //------------------------------------------------------------------------------ /** Load shader resources. */ bool nSurfaceNode::LoadShaders() { // load shaders int i; for (i = 0; i < this->shaderArray.Size(); i++) { ShaderEntry& shaderEntry = this->shaderArray[i]; if (!shaderEntry.IsShaderValid() && shaderEntry.GetName()) { #if 0 // keep this commented while the shader database is not used // try to get shader by name from shader repository int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName()); if (shaderIndex != -1) { nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex); if (!sceneShader.IsValid()) { sceneShader.Validate(); n_assert(sceneShader.IsValid()); } sceneShader.GetShaderObject()->AddRef(); shaderEntry.SetShaderIndex(shaderIndex); shaderEntry.SetShader(sceneShader.GetShaderObject()); } else #endif { // create a new empty shader object nShader2* shd = nGfxServer2::Instance()->NewShader(shaderEntry.GetName()); n_assert(shd); if (!shd->IsLoaded()) { // load shader resource file shd->SetFilename(shaderEntry.GetName()); } if (shd) { // register shader object in scene shader database nSceneShader sceneShader; sceneShader.SetShader(shaderEntry.GetName());// filename sceneShader.SetShaderName(shaderEntry.GetName());// shader name int shaderIndex = nSceneServer::Instance()->FindShader(shaderEntry.GetName()); if (shaderIndex == -1) { shaderIndex = nSceneServer::Instance()->AddShader(sceneShader); n_assert(shaderIndex != -1); } // set shader object and index for local entry shaderEntry.SetShader(shd); shaderEntry.shaderIndex = shaderIndex; // create a degenerate decision tree for use in the render path nShaderTree* shaderTree = static_cast<nShaderTree*>( kernelServer->New("nshadertree") ); n_assert( shaderTree ); shaderTree->BeginNode( nVariable::InvalidHandle, 0 ); shaderTree->SetShaderObject( shd ); shaderTree->SetShaderIndexAt( 0, shaderIndex ); shaderTree->EndNode(); this->shaderTreeArray.Set( shaderEntry.GetPassIndex(), shaderTree ); } } } } return true; } //------------------------------------------------------------------------------ /** Load the resources needed by this object. */ bool nSurfaceNode::LoadResources() { if (this->LoadShaders()) { if (nAbstractShaderNode::LoadResources()) { return true; } } return false; } //------------------------------------------------------------------------------ /** Unload the resources if refcount has reached zero. */ void nSurfaceNode::UnloadResources() { nAbstractShaderNode::UnloadResources(); this->UnloadShaders(); } //------------------------------------------------------------------------------ /** Find shader object associated with fourcc code. */ nSurfaceNode::ShaderEntry* nSurfaceNode::FindShaderEntry(nFourCC fourcc) const { int i; int numShaders = this->shaderArray.Size(); for (i = 0; i < numShaders; i++) { ShaderEntry& shaderEntry = this->shaderArray[i]; if (shaderEntry.GetFourCC() == fourcc) { return &shaderEntry; } } // fallthrough: no loaded shader matches this fourcc code return 0; } //------------------------------------------------------------------------------ /** Return number of levels. */ int nSurfaceNode::GetNumLevels() { return (this->shaderArray.Size() > 0) ? 1 : 0; } //------------------------------------------------------------------------------ /** Return number of passes for a level */ int nSurfaceNode::GetNumLevelPasses(int /*level*/) { return this->shaderArray.Size(); } //------------------------------------------------------------------------------ /** Return number of passes for a level */ int nSurfaceNode::GetLevelPassIndex(int level, int pass) { n_assert_return((level == 0) && (pass < this->shaderArray.Size()), -1); return this->shaderArray[pass].GetPassIndex(); } //------------------------------------------------------------------------------ /** */ nShaderTree* nSurfaceNode::GetShaderTree(int /*level*/, int passIndex) { n_assert(passIndex < this->shaderTreeArray.Size()); return this->shaderTreeArray[passIndex]; } //------------------------------------------------------------------------------ /** */ void nSurfaceNode::SetShader(nFourCC fourcc, const char* name) { n_assert(name); ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc); if (shaderEntry) { shaderEntry->Invalidate(); shaderEntry->SetName(name); } else { ShaderEntry newShaderEntry(fourcc, name); this->shaderArray.Append(newShaderEntry); } } //------------------------------------------------------------------------------ /** */ const char* nSurfaceNode::GetShader(nFourCC fourcc) const { ShaderEntry* shaderEntry = this->FindShaderEntry(fourcc); if (shaderEntry) { return shaderEntry->GetName(); } else { return 0; } } //------------------------------------------------------------------------------ /** */ bool nSurfaceNode::IsTextureUsed(nShaderState::Param /*param*/) { #if 0 // check in all shaders if anywhere the texture specified by param is used int i; int numShaders = this->shaderArray.Size(); for (i = 0; i < numShaders; i++) { const ShaderEntry& shaderEntry = this->shaderArray[i]; // first be sure that the shader entry could be loaded if (shaderEntry.IsShaderValid()) { nShader2* shader = shaderEntry.GetShader(); if (shader->IsParameterUsed(param)) { return true; } } } // fallthrough: texture not used by any shader return false; #else return true; #endif } //------------------------------------------------------------------------------ /** Setup shader attributes before rendering instances of this scene node. FIXME */ bool nSurfaceNode::Apply(nSceneGraph* sceneGraph) { n_assert(sceneGraph); int shaderIndex = sceneGraph->GetShaderIndex(); if (shaderIndex != -1) { nSceneShader& sceneShader = nSceneServer::Instance()->GetShaderAt(shaderIndex); nGfxServer2::Instance()->SetShader(sceneShader.GetShaderObject()); nAbstractShaderNode::Apply(sceneGraph); return true; } return false; } //------------------------------------------------------------------------------ /** Update shader and set as current shader in the gfx server. - 15-Jan-04 floh AreResourcesValid()/LoadResources() moved to scene server */ bool nSurfaceNode::Render(nSceneGraph* sceneGraph, nEntityObject* entityObject) { n_assert(sceneGraph); n_assert(entityObject); //nShader2* shader = nSceneServer::Instance()->GetShaderAt(sceneGraph->GetShaderIndex()).GetShaderObject(); // invoke shader manipulators this->InvokeAnimators(entityObject); /* //nGfxServer2* gfxServer = nGfxServer2::Instance(); // set texture transforms (that can be animated) //n_assert(nGfxServer2::MaxTextureStages >= 4); static matrix44 m; this->textureTransform[0].getmatrix44(m); gfxServer->SetTransform(nGfxServer2::Texture0, m); this->textureTransform[1].getmatrix44(m); gfxServer->SetTransform(nGfxServer2::Texture1, m); */ // transfer the rest of per-instance (animated, overriden) parameters // per instance-set parameters are handled at Apply() // also, shader overrides are handled at nGeometryNode::Render() nAbstractShaderNode::Render(sceneGraph, entityObject); return true; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91
2f7c53e6eca61a4d65b5a9090d33a226af61dcdd
f18fc611d43a332493e082cfd1ebed01a50d29f2
/flakor/base/entity/Scene.cpp
5f79fa8b26db8d973d705db58191744703f06ca6
[]
no_license
7heaven/Flakor
011995263f92d47179e79bd93527e32b660dfe5a
357d93db8592df9476b26cb43593eab7e6b652db
refs/heads/master
2020-12-27T15:14:11.269061
2014-12-03T09:59:30
2014-12-03T09:59:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
#include "targetMacros.h" #include "base/entity/Scene.h" FLAKOR_NS_BEGIN Scene::Scene() { relativeAnchorPoint = false; setAnchorPoint(MakePoint(0.5,0.5)); } Scene::~Scene() { } Scene* Scene::create() { Scene *pRet = new Scene(); if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { FK_SAFE_DELETE(pRet); return NULL; } } FLAKOR_NS_END
[ "saint@aliyun.com" ]
saint@aliyun.com
122c26ad61b675ac7a70687447a2c90b0a067f85
19eb97436a3be9642517ea9c4095fe337fd58a00
/private/shell/ext/mydocs/src/viewcb.h
9b16d1c997fd3360d81d407b2cded1de7e65ffb7
[]
no_license
oturan-boga/Windows2000
7d258fd0f42a225c2be72f2b762d799bd488de58
8b449d6659840b6ba19465100d21ca07a0e07236
refs/heads/main
2023-04-09T23:13:21.992398
2021-04-22T11:46:21
2021-04-22T11:46:21
360,495,781
2
0
null
null
null
null
UTF-8
C++
false
false
898
h
#ifndef __viewcb_h #define __viewcb_h /*----------------------------------------------------------------------------- / CMyDocsViewCB /----------------------------------------------------------------------------*/ class CMyDocsViewCB : public IShellFolderViewCB, CUnknown { private: IShellFolderView * m_psfv; IShellFolderViewCB * m_psfvcb; LPITEMIDLIST m_pidlReal; public: CMyDocsViewCB(IShellFolderView * psfv, LPITEMIDLIST pidl); ~CMyDocsViewCB(); STDMETHOD(SetRealCB)(IShellFolderViewCB * psfvcb); // IUnknown STDMETHOD(QueryInterface)(REFIID riid, LPVOID* ppvObject); STDMETHOD_(ULONG, AddRef)(); STDMETHOD_(ULONG, Release)(); // IShellFolderViewCB STDMETHOD(MessageSFVCB)(UINT uMsg, WPARAM wParam, LPARAM lParam); }; #endif
[ "mehmetyilmaz3371@gmail.com" ]
mehmetyilmaz3371@gmail.com
f69b885084c9cf74fe193810bbb1a9c435dd559e
6712863f4ba992d6b02e603b8c18c5a098c681eb
/lab/lab 28-05-2018/lab.cpp
5865b35cb80f95487034b1d3ba7a6e52ec205587
[]
no_license
Hasanul-Bari/oop
b141c95492d73c84baa0a3217d11beca5353f3c4
aa4efdebf83e5e9f1907effc081191aa6fee25e8
refs/heads/master
2021-05-17T02:51:48.875156
2020-12-31T14:00:44
2020-12-31T14:00:44
250,583,528
0
0
null
null
null
null
UTF-8
C++
false
false
518
cpp
#include<iostream> using namespace std; class student { int sid; char name; int level; float marks; float gp; public: void get(void) { cin>>sid>>marks; } void put(void) { cout<<sid<<"\t"<<marks<<endl; } }; int main() { student s[5]; cout<<"Enter 5 objects"<<endl; for( int i=0; i<5; i++) { s[i].get(); } cout<<"Entered objects are"<<endl; for( int i=0; i<5; i++) { s[i].put(); } return 0; }
[ "hasanul.bari.hasan96@gmail.com" ]
hasanul.bari.hasan96@gmail.com
d23236156489e847368bd1cd87e77cd030ede2e9
d79408a9616a8ff8ac9375b9fffaa45ae6698fd5
/src/rpc/rawtransaction.cpp
a4745ac25c4341ca87809c750df9d380ab44bad3
[ "MIT" ]
permissive
Schepses/nero
6c77f5df6afd36a6ebcb14af1d8257d918d7bda7
7ec5e3a6c7f1c75f5ec15b1f4d0bcb9cdc0ec9b0
refs/heads/master
2020-03-07T13:43:18.425050
2018-03-28T12:27:27
2018-03-28T12:27:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,564
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Nero Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "chain.h" #include "coins.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" #include "keystore.h" #include "validation.h" #include "merkleblock.h" #include "net.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpc/server.h" #include "script/script.h" #include "script/script_error.h" #include "script/sign.h" #include "script/standard.h" #include "txmempool.h" #include "uint256.h" #include "utilstrencodings.h" #include "instantx.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <stdint.h> #include <boost/assign/list_of.hpp> #include <univalue.h> using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey))); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); UniValue a(UniValue::VARR); BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) { uint256 txid = tx.GetHash(); entry.push_back(Pair("txid", txid.GetHex())); entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION))); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); UniValue vin(UniValue::VARR); BOOST_FOREACH(const CTxIn& txin, tx.vin) { UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); UniValue o(UniValue::VOBJ); o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true))); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); // Add address and value info if spentindex enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n); if (GetSpentIndex(spentKey, spentInfo)) { in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis))); in.push_back(Pair("valueSat", spentInfo.satoshis)); if (spentInfo.addressType == 1) { in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString())); } else if (spentInfo.addressType == 2) { in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString())); } } } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("valueSat", txout.nValue)); out.push_back(Pair("n", (int64_t)i)); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(txout.scriptPubKey, o, true); out.push_back(Pair("scriptPubKey", o)); // Add spent information if spentindex is enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txid, i); if (GetSpentIndex(spentKey, spentInfo)) { out.push_back(Pair("spentTxId", spentInfo.txid.GetHex())); out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex)); out.push_back(Pair("spentHeight", spentInfo.blockHeight)); } vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (!hashBlock.IsNull()) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { entry.push_back(Pair("height", pindex->nHeight)); entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight)); entry.push_back(Pair("time", pindex->GetBlockTime())); entry.push_back(Pair("blocktime", pindex->GetBlockTime())); } else { entry.push_back(Pair("height", -1)); entry.push_back(Pair("confirmations", 0)); } } } } UniValue getrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction \"txid\" ( verbose )\n" "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n" "or there is an unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option.\n" "\nReturn the raw transaction data.\n" "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n" "If verbose is non-zero, returns an Object with information about 'txid'.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n" "\nResult (if verbose is not set or set to 0):\n" "\"data\" (string) The serialized, hex-encoded data for 'txid'\n" "\nResult (if verbose > 0):\n" "{\n" " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n" " \"txid\" : \"id\", (string) The transaction id (same as provided)\n" " \"size\" : n, (numeric) The transaction size\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) \n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"neroaddress\" (string) nero address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n" " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1") ); LOCK(cs_main); uint256 hash = ParseHashV(params[0], "parameter 1"); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock; if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); string strHex = EncodeHexTx(tx); if (!fVerbose) return strHex; UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } UniValue gettxoutproof(const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 1 && params.size() != 2)) throw runtime_error( "gettxoutproof [\"txid\",...] ( blockhash )\n" "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n" "\nNOTE: By default this function only works sometimes. This is when there is an\n" "unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option or\n" "specify the block in which the transaction is included in manually (by blockhash).\n" "\nReturn the raw transaction data.\n" "\nArguments:\n" "1. \"txids\" (string) A json array of txids to filter\n" " [\n" " \"txid\" (string) A transaction hash\n" " ,...\n" " ]\n" "2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n" "\nResult:\n" "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n" "\nExamples:\n" + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'") + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"") + HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"") ); set<uint256> setTxids; uint256 oneTxid; UniValue txids = params[0].get_array(); for (unsigned int idx = 0; idx < txids.size(); idx++) { const UniValue& txid = txids[idx]; if (txid.get_str().length() != 64 || !IsHex(txid.get_str())) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str()); uint256 hash(uint256S(txid.get_str())); if (setTxids.count(hash)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str()); setTxids.insert(hash); oneTxid = hash; } LOCK(cs_main); CBlockIndex* pblockindex = NULL; uint256 hashBlock; if (params.size() > 1) { hashBlock = uint256S(params[1].get_str()); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hashBlock]; } else { CCoins coins; if (pcoinsTip->GetCoins(oneTxid, coins) && coins.nHeight > 0 && coins.nHeight <= chainActive.Height()) pblockindex = chainActive[coins.nHeight]; } if (pblockindex == NULL) { CTransaction tx; if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); pblockindex = mapBlockIndex[hashBlock]; } CBlock block; if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); unsigned int ntxFound = 0; BOOST_FOREACH(const CTransaction&tx, block.vtx) if (setTxids.count(tx.GetHash())) ntxFound++; if (ntxFound != setTxids.size()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block"); CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock mb(block, setTxids); ssMB << mb; std::string strHex = HexStr(ssMB.begin(), ssMB.end()); return strHex; } UniValue verifytxoutproof(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "verifytxoutproof \"proof\"\n" "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n" "and throwing an RPC error if the block is not in our best chain\n" "\nArguments:\n" "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n" "\nResult:\n" "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n" "\nExamples:\n" + HelpExampleCli("verifytxoutproof", "\"proof\"") + HelpExampleRpc("gettxoutproof", "\"proof\"") ); CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock merkleBlock; ssMB >> merkleBlock; UniValue res(UniValue::VARR); vector<uint256> vMatch; if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot) return res; LOCK(cs_main); if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()])) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); BOOST_FOREACH(const uint256& hash, vMatch) res.push_back(hash.GetHex()); return res; } UniValue createrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n" "\nCreate a transaction spending the given inputs and creating new outputs.\n" "Outputs can be addresses or data.\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network.\n" "\nArguments:\n" "1. \"transactions\" (string, required) A json array of json objects\n" " [\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n (numeric, required) The output number\n" " }\n" " ,...\n" " ]\n" "2. \"outputs\" (string, required) a json object with outputs\n" " {\n" " \"address\": x.xxx (numeric or string, required) The key is the nero address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n" " \"data\": \"hex\", (string, required) The key is \"data\", the value is hex encoded data\n" " ...\n" " }\n" "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" "\nResult:\n" "\"transaction\" (string) hex string of the transaction\n" "\nExamples\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"") ); LOCK(cs_main); RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true); if (params[0].isNull() || params[1].isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null"); UniValue inputs = params[0].get_array(); UniValue sendTo = params[1].get_obj(); CMutableTransaction rawTx; if (params.size() > 2 && !params[2].isNull()) { int64_t nLockTime = params[2].get_int64(); if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range"); rawTx.nLockTime = nLockTime; } for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; const UniValue& o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); const UniValue& vout_v = find_value(o, "vout"); if (!vout_v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max()); CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; vector<string> addrList = sendTo.getKeys(); BOOST_FOREACH(const string& name_, addrList) { if (name_ == "data") { std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data"); CTxOut out(0, CScript() << OP_RETURN << data); rawTx.vout.push_back(out); } else { CBitcoinAddress address(name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Nero address: ")+name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } } return EncodeHexTx(rawTx); } UniValue decoderawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction \"hexstring\"\n" "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n" "\nArguments:\n" "1. \"hex\" (string, required) The transaction hex string\n" "\nResult:\n" "{\n" " \"txid\" : \"id\", (string) The transaction id\n" " \"size\" : n, (numeric) The transaction size\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) The output number\n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" (string) Nero address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" "}\n" "\nExamples:\n" + HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\"") ); LOCK(cs_main); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)); CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); UniValue result(UniValue::VOBJ); TxToJSON(tx, uint256(), result); return result; } UniValue decodescript(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript \"hex\"\n" "\nDecode a hex-encoded script.\n" "\nArguments:\n" "1. \"hex\" (string) the hex encoded script\n" "\nResult:\n" "{\n" " \"asm\":\"asm\", (string) Script public key\n" " \"hex\":\"hex\", (string) hex encoded public key\n" " \"type\":\"type\", (string) The output type\n" " \"reqSigs\": n, (numeric) The required signatures\n" " \"addresses\": [ (json array of string)\n" " \"address\" (string) nero address\n" " ,...\n" " ],\n" " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n" "}\n" "\nExamples:\n" + HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)); UniValue r(UniValue::VOBJ); CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); UniValue type; type = find_value(r, "type"); if (type.isStr() && type.get_str() != "scripthash") { // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH, // don't return the address for a P2SH of the P2SH. r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString())); } return r; } /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage) { UniValue entry(UniValue::VOBJ); entry.push_back(Pair("txid", txin.prevout.hash.ToString())); entry.push_back(Pair("vout", (uint64_t)txin.prevout.n)); entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); entry.push_back(Pair("sequence", (uint64_t)txin.nSequence)); entry.push_back(Pair("error", strMessage)); vErrorsRet.push_back(entry); } UniValue signrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n" "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain.\n" "The third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" #ifdef ENABLE_WALLET + HelpRequiringPassphrase() + "\n" #endif "\nArguments:\n" "1. \"hexstring\" (string, required) The transaction hex string\n" "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n" " [ (json array of json objects, or 'null' if none provided)\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n, (numeric, required) The output number\n" " \"scriptPubKey\": \"hex\", (string, required) script key\n" " \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n" " }\n" " ,...\n" " ]\n" "3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n" " [ (json array of strings, or 'null' if none provided)\n" " \"privatekey\" (string) private key in base58-encoding\n" " ,...\n" " ]\n" "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\"\n" "\nResult:\n" "{\n" " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n" " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n" " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n" " {\n" " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n" " \"vout\" : n, (numeric) The index of the output to spent and used as input\n" " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n" " \"sequence\" : n, (numeric) Script sequence number\n" " \"error\" : \"text\" (string) Verification or signing error related to the input\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\"") ); #ifdef ENABLE_WALLET LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL); #else LOCK(cs_main); #endif RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true); vector<unsigned char> txData(ParseHexV(params[0], "argument 1")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CMutableTransaction> txVariants; while (!ssData.empty()) { try { CMutableTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (const std::exception&) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CMutableTransaction mergedTx(txVariants[0]); // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache &viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) { const uint256& prevHash = txin.prevout.hash; CCoins coins; view.AccessCoins(prevHash); // this is certainly allowed to fail } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && !params[2].isNull()) { fGivenKeys = true; UniValue keys = params[2].get_array(); for (unsigned int idx = 0; idx < keys.size(); idx++) { UniValue k = keys[idx]; CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); tempKeystore.AddKey(key); } } #ifdef ENABLE_WALLET else if (pwalletMain) EnsureWalletIsUnlocked(); #endif // Add previous txouts given in the RPC call: if (params.size() > 1 && !params[1].isNull()) { UniValue prevTxs = params[1].get_array(); for (unsigned int idx = 0; idx < prevTxs.size(); idx++) { const UniValue& p = prevTxs[idx]; if (!p.isObject()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); UniValue prevOut = p.get_obj(); RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { CCoinsModifier coins = view.ModifyCoins(txid); if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coins->vout[nOut].scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } if ((unsigned int)nOut >= coins->vout.size()) coins->vout.resize(nOut+1); coins->vout[nOut].scriptPubKey = scriptPubKey; coins->vout[nOut].nValue = 0; // we don't know the actual output value } // if redeemScript given and not using the local wallet (private keys // given), add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) { RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR)); UniValue v = find_value(prevOut, "redeemScript"); if (!v.isNull()) { vector<unsigned char> rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } } #ifdef ENABLE_WALLET const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain); #else const CKeyStore& keystore = tempKeystore; #endif int nHashType = SIGHASH_ALL; if (params.size() > 3 && !params[3].isNull()) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Script verification errors UniValue vErrors(UniValue::VARR); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const CCoins* coins = view.AccessCoins(txin.prevout.hash); if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) { TxInErrorToJSON(txin, vErrors, "Input not found or already spent"); continue; } const CScript& prevPubKey = coins->vout[txin.prevout.n].scriptPubKey; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CMutableTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } ScriptError serror = SCRIPT_ERR_OK; if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) { TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror)); } } bool fComplete = vErrors.empty(); UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", EncodeHexTx(mergedTx))); result.push_back(Pair("complete", fComplete)); if (!vErrors.empty()) { result.push_back(Pair("errors", vErrors)); } return result; } UniValue sendrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "sendrawtransaction \"hexstring\" ( allowhighfees instantsend )\n" "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n" "\nAlso see createrawtransaction and signrawtransaction calls.\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n" "2. allowhighfees (boolean, optional, default=false) Allow high fees\n" "3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n" "\nResult:\n" "\"hex\" (string) The transaction hash in hex\n" "\nExamples:\n" "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") + "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + "\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\"") ); LOCK(cs_main); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL)); // parse hex string from parameter CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); uint256 hashTx = tx.GetHash(); bool fOverrideFees = false; if (params.size() > 1) fOverrideFees = params[1].get_bool(); bool fInstantSend = false; if (params.size() > 2) fInstantSend = params[2].get_bool(); CCoinsViewCache &view = *pcoinsTip; const CCoins* existingCoins = view.AccessCoins(hashTx); bool fHaveMempool = mempool.exists(hashTx); bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000; if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets if (fInstantSend && !instantsend.ProcessTxLockRequest(tx, *g_connman)) { throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info"); } CValidationState state; bool fMissingInputs; if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, !fOverrideFees)) { if (state.IsInvalid()) { throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason())); } else { if (fMissingInputs) { throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs"); } throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason()); } } } else if (fHaveChain) { throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain"); } if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); g_connman->RelayTransaction(tx); return hashTx.GetHex(); }
[ "root@DS792121.clientshostname.com" ]
root@DS792121.clientshostname.com
64a04d0fa7d7aa7e632d9071251e6a13e6b4fd5e
dc603c3d2bf052384f1157a6c9c83ff08a60bd86
/src/draw/css/parser/CSSTokenizerInputStream.h
e6e0e1b99252b3ea11746b07fdabb764cff7d964
[ "MIT" ]
permissive
cyllene-project/Rubric
b9d9d6246904acbf1a8e84a6ec353f3db766c5ef
dae36e7a0801b35056dfb676c2f9c60faaaa09f8
refs/heads/master
2020-06-04T17:46:58.512132
2019-07-19T15:23:59
2019-07-19T15:23:59
192,129,479
0
0
null
null
null
null
UTF-8
C++
false
false
4,204
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Copyright (C) 2016 Apple Inc. 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 Google Inc. 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 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #pragma once namespace WebCore { constexpr LChar kEndOfFileMarker = 0; class CSSTokenizerInputStream { CSSTokenizerInputStream(const CSSTokenizerInputStream&) = delete; CSSTokenizerInputStream& operator=(const CSSTokenizerInputStream&) = delete; public: explicit CSSTokenizerInputStream(const std::string& input); // Gets the char in the stream replacing NUL characters with a unicode // replacement character. Will return (NUL) kEndOfFileMarker when at the // end of the stream. UChar nextInputChar() const { if (m_offset >= m_stringLength) return '\0'; UChar result = (*m_string)[m_offset]; return result ? result : 0xFFFD; } // Gets the char at lookaheadOffset from the current stream position. Will // return NUL (kEndOfFileMarker) if the stream position is at the end. // NOTE: This may *also* return NUL if there's one in the input! Never // compare the return value to '\0'. UChar peekWithoutReplacement(unsigned lookaheadOffset) const { if ((m_offset + lookaheadOffset) >= m_stringLength) return '\0'; return (*m_string)[m_offset + lookaheadOffset]; } void advance(unsigned offset = 1) { m_offset += offset; } void pushBack(UChar cc) { --m_offset; ASSERT_UNUSED(cc, nextInputChar() == cc); } double getDouble(unsigned start, unsigned end) const; template<bool characterPredicate(UChar)> unsigned skipWhilePredicate(unsigned offset) { if (m_string->is8Bit()) { const LChar* characters8 = m_string->characters8(); while ((m_offset + offset) < m_stringLength && characterPredicate(characters8[m_offset + offset])) ++offset; } else { const UChar* characters16 = m_string->characters16(); while ((m_offset + offset) < m_stringLength && characterPredicate(characters16[m_offset + offset])) ++offset; } return offset; } void advanceUntilNonWhitespace(); unsigned length() const { return m_stringLength; } unsigned offset() const { return std::min(m_offset, m_stringLength); } std::string_view rangeAt(unsigned start, unsigned length) const { assert(start + length <= m_stringLength); return StringView(m_string.get()).substring(start, length); // FIXME: Should make a constructor on StringView for this. } private: size_t m_offset; const size_t m_stringLength; std::shared_ptr<StringImpl> m_string; }; } // namespace WebCore
[ "chebizarro@gmail.com" ]
chebizarro@gmail.com
e50dfbf3493132b4631611703d23ff5f7b5b1fe7
889070c36584bf72670ead396b2c0932b9cb2f2d
/vish.cpp
49bb0161ac86526d97fb362265da05afdff43058
[]
no_license
viralipurbey/CompetitiveProgramminCodingNinjas
2586cb1f688265c29e66a50da906424986f98fa8
7fa063930a92f02efbdcf9afe55252df9e0299a6
refs/heads/master
2022-11-27T06:44:22.829945
2020-08-02T07:20:19
2020-08-02T07:20:19
257,389,120
0
0
null
null
null
null
UTF-8
C++
false
false
1,373
cpp
#include <stdio.h> #include<bits/stdc++.h> #define ll long long using namespace std; ll count(ll a[],ll k,ll sti,ll endi) { ll sum = 0; if(sti < endi) { ll midi = (sti+endi)/2; sum += count(a,k,sti,midi); sum += count(a,k,midi+1,endi); ll li = sti; ll ri=midi+1; vector<ll> temp; while(li <= midi && ri <= endi) { if(a[li] > a[ri]) { temp.push_back(a[ri]); if(a[li] - a[ri] >= k) { sum += (midi+1-li); } ri++; } else { temp.push_back(a[li]); if(a[ri] - a[li] >= k) { sum += (endi + 1-ri); } li++; } } while(li <= midi) { temp.push_back(a[li++]); } while( ri <= midi) { temp.push_back(a[ri++]); } for(ll i = sti, k = 0; i <= endi; i++, k++){ a[i] = temp[k]; } } return sum; } int main(void) { // your code goes here ll n; cin>>n; ll k; cin>>k; ll arr[n]; for(ll i=0;i<n;i++) { ll ele; cin>>ele; arr[i] = ele; } cout<<count(arr,k,0,n-1)<<endl; //delete []arr; return 0; }
[ "viralipurbey4567@gmail.com" ]
viralipurbey4567@gmail.com
36218916249b629db40665712be2b46f6df1b321
6d8d760e9b1b2bebdbf1177bc52b7b0bf5319fed
/data/tplcache/6295c1fea5c50f198b71ab2ede809999.inc
943a7911fcd0fc97549c0db1b240491eb163e7df
[]
no_license
xiaolaifeng/cms
eda2eda59d3a4b9159b6888d3b5b56994d626c26
17308ad59ba0c85b1757d633c48d36059ab7a615
refs/heads/master
2016-09-11T02:07:01.120174
2015-01-02T04:46:17
2015-01-02T04:46:17
25,720,169
1
1
null
null
null
null
UTF-8
C++
false
false
693
inc
{dede:pagestyle maxwidth='800' pagepicnum='12' ddmaxwidth='200' row='3' col='4' value='3'/} {dede:img ddimg='/uploads/allimg/141007/1-14100G54010-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54010.png {/dede:img} {dede:img ddimg='/uploads/allimg/141007/1-14100G54014-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54014.png {/dede:img} {dede:img ddimg='/uploads/allimg/141007/1-14100G54016-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54016.png {/dede:img} {dede:img ddimg='/uploads/allimg/141007/1-14100G54020-lp.png' text='' width='320' height='568'} /uploads/allimg/141007/1-14100G54020.png {/dede:img}
[ "xiaofeng_hero@163.com" ]
xiaofeng_hero@163.com
1f80fab377c76adb00557d6376cda5f006c46e52
bfe6df5301221a56f2328923506cc4a1839e8077
/Version 1.x/Source/dpagesourcewindow.cc
8b0795b7dfb6ce82afe0e8568ae018c48fe220b3
[]
no_license
elementakion/dooble
64f7ca6f8468f3e15d65841b647b99f93f0efdeb
5406278697eb462c0a3a5d388067738bbf60aa79
refs/heads/master
2021-01-14T09:55:13.356385
2015-04-03T16:51:24
2015-04-03T16:51:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,343
cc
/* ** Copyright (c) 2008 - present, Alexis Megas. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from Dooble without specific prior written permission. ** ** DOOBLE 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 ** DOOBLE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QUrl> #include <QFile> #include <QPrinter> #include <QSettings> #include <QCloseEvent> #include <QFileDialog> #include <QTextStream> #include <QPrintDialog> #include <QDesktopServices> #include <QPrintPreviewDialog> #include "dooble.h" #include "dpagesourcewindow.h" dpagesourcewindow::dpagesourcewindow(QWidget *parent, const QUrl &url, const QString &html):QMainWindow() { ui.setupUi(this); #ifdef Q_OS_MAC setAttribute(Qt::WA_MacMetalStyle, false); #if QT_VERSION >= 0x050000 setWindowFlags(windowFlags() & ~Qt::WindowFullscreenButtonHint); #endif statusBar()->setSizeGripEnabled(false); #endif m_findLineEditPalette = ui.findLineEdit->palette(); ui.textBrowser->setPlainText(html); connect(ui.actionPrint, SIGNAL(triggered(void)), this, SLOT(slotPrint(void))); connect(ui.actionPrint_Preview, SIGNAL(triggered(void)), this, SLOT(slotPrintPreview(void))); connect(ui.actionClose, SIGNAL(triggered(void)), this, SLOT(slotClose(void))); connect(ui.actionFind, SIGNAL(triggered(void)), this, SLOT(slotShowFind(void))); connect(ui.actionSave_As, SIGNAL(triggered(void)), this, SLOT(slotSavePageAs(void))); connect(ui.hideFindToolButton, SIGNAL(clicked(void)), this, SLOT(slotHideFind(void))); connect(ui.findLineEdit, SIGNAL(returnPressed(void)), this, SLOT(slotNextFind(void))); connect(ui.findLineEdit, SIGNAL(textEdited(const QString &)), this, SLOT(slotNextFind(const QString &))); connect(ui.actionWrap_Lines, SIGNAL(toggled(bool)), this, SLOT(slotWrapLines(bool))); connect(ui.nextToolButton, SIGNAL(clicked(void)), this, SLOT(slotNextFind(void))); connect(ui.previousToolButton, SIGNAL(clicked(void)), this, SLOT(slotPreviousFind(void))); if(!url.isEmpty()) setWindowTitle(tr("Dooble Web Browser - Page Source (") + url.toString(QUrl::StripTrailingSlash) + tr(")")); else setWindowTitle(tr("Dooble Web Browser - Page Source")); if(url.path().isEmpty() || url.path() == "/") fileName = "source"; else if(url.path().contains("/")) { fileName = url.path(); fileName = fileName.mid(fileName.lastIndexOf("/") + 1); } else fileName = url.path(); ui.actionWrap_Lines->setChecked (dooble::s_settings.value("pageSource/wrapLines", false).toBool()); slotWrapLines(ui.actionWrap_Lines->isChecked()); slotSetIcons(); slotHideFind(); if(parent) { if(parent->height() == height() && parent->width() == width()) setGeometry(parent->geometry()); else { QPoint p(parent->pos()); int X = 0; int Y = 0; if(parent->width() >= width()) X = p.x() + (parent->width() - width()) / 2; else X = p.x() - (width() - parent->width()) / 2; if(parent && parent->height() >= height()) Y = p.y() + (parent->height() - height()) / 2; else Y = p.y() - (height() - parent->height()) / 2; move(X, Y); } } else move(100, 100); show(); } dpagesourcewindow::~dpagesourcewindow() { } void dpagesourcewindow::slotClose(void) { close(); } void dpagesourcewindow::closeEvent(QCloseEvent *event) { QMainWindow::closeEvent(event); deleteLater(); } void dpagesourcewindow::slotPrint(void) { QPrinter printer; QPrintDialog printDialog(&printer, this); #ifdef Q_OS_MAC printDialog.setAttribute(Qt::WA_MacMetalStyle, false); #endif if(printDialog.exec() == QDialog::Accepted) ui.textBrowser->print(&printer); } void dpagesourcewindow::slotPrintPreview(void) { QPrinter printer; QPrintPreviewDialog printDialog(&printer, this); #ifdef Q_OS_MAC printDialog.setAttribute(Qt::WA_MacMetalStyle, false); #endif printDialog.setWindowModality(Qt::WindowModal); connect(&printDialog, SIGNAL(paintRequested(QPrinter *)), this, SLOT(slotTextEditPrintPreview(QPrinter *))); if(printDialog.exec() == QDialog::Accepted) ui.textBrowser->print(&printer); } void dpagesourcewindow::slotTextEditPrintPreview(QPrinter *printer) { if(printer) ui.textBrowser->print(printer); } void dpagesourcewindow::slotHideFind(void) { ui.findFrame->setVisible(false); } void dpagesourcewindow::slotShowFind(void) { ui.findFrame->setVisible(true); ui.findLineEdit->setFocus(); ui.findLineEdit->selectAll(); #ifdef Q_OS_MAC static int fixed = 0; if(!fixed) { QColor color(255, 255, 255); QPalette palette(ui.findLineEdit->palette()); palette.setColor(ui.findLineEdit->backgroundRole(), color); ui.findLineEdit->setPalette(palette); fixed = 1; } #endif } void dpagesourcewindow::keyPressEvent(QKeyEvent *event) { if(event && event->key() == Qt::Key_Escape) ui.findFrame->setVisible(false); QMainWindow::keyPressEvent(event); } void dpagesourcewindow::slotNextFind(void) { slotNextFind(ui.findLineEdit->text()); } void dpagesourcewindow::slotNextFind(const QString &text) { QTextDocument::FindFlags findFlags = 0; if(ui.matchCaseCheckBox->isChecked()) findFlags |= QTextDocument::FindCaseSensitively; if(ui.textBrowser->find(text, findFlags) || text.isEmpty()) { ui.findLineEdit->setPalette(m_findLineEditPalette); if(text.isEmpty()) ui.textBrowser->moveCursor(QTextCursor::PreviousCharacter); } else { if(ui.textBrowser->textCursor().anchor() == ui.textBrowser->textCursor().position()) { if(!ui.textBrowser->textCursor().atEnd()) { QColor color(240, 128, 128); // Light Coral QPalette palette(ui.findLineEdit->palette()); palette.setColor(ui.findLineEdit->backgroundRole(), color); ui.findLineEdit->setPalette(palette); } else ui.textBrowser->moveCursor(QTextCursor::Start); } else { ui.textBrowser->moveCursor(QTextCursor::Start); slotNextFind(text); } } } void dpagesourcewindow::slotPreviousFind(void) { slotPreviousFind(ui.findLineEdit->text()); } void dpagesourcewindow::slotPreviousFind(const QString &text) { QTextDocument::FindFlags findFlags = QTextDocument::FindBackward; if(ui.matchCaseCheckBox->isChecked()) findFlags |= QTextDocument::FindCaseSensitively; if(ui.textBrowser->find(text, findFlags) || text.isEmpty()) ui.findLineEdit->setPalette(m_findLineEditPalette); else { if(ui.textBrowser->textCursor().anchor() == ui.textBrowser->textCursor().position()) { QColor color(240, 128, 128); // Light Coral QPalette palette(ui.findLineEdit->palette()); palette.setColor(ui.findLineEdit->backgroundRole(), color); ui.findLineEdit->setPalette(palette); } else { ui.textBrowser->moveCursor(QTextCursor::End); slotPreviousFind(text); } } } void dpagesourcewindow::slotSavePageAs(void) { QString path(dooble::s_settings.value("settingsWindow/myRetrievedFiles", "").toString()); QFileInfo fileInfo(path); QFileDialog fileDialog(this); if(!fileInfo.isReadable() || !fileInfo.isWritable()) #if QT_VERSION >= 0x050000 path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); #else path = QDesktopServices::storageLocation (QDesktopServices::DesktopLocation); #endif #ifdef Q_OS_MAC fileDialog.setAttribute(Qt::WA_MacMetalStyle, false); #endif fileDialog.setOption (QFileDialog::DontUseNativeDialog, !dooble::s_settings.value("settingsWindow/useNativeFileDialogs", false).toBool()); fileDialog.setWindowTitle(tr("Dooble Web Browser: Save Page Source As")); fileDialog.setFileMode(QFileDialog::AnyFile); fileDialog.setDirectory(path); fileDialog.setLabelText(QFileDialog::Accept, tr("Save")); fileDialog.setAcceptMode(QFileDialog::AcceptSave); fileDialog.selectFile(fileName); if(fileDialog.exec() == QDialog::Accepted) { QStringList list(fileDialog.selectedFiles()); if(!list.isEmpty()) { QFile file(list.at(0)); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream out(&file); out << ui.textBrowser->toPlainText(); file.close(); } } } } void dpagesourcewindow::slotWrapLines(bool checked) { QSettings settings; settings.setValue("pageSource/wrapLines", checked); dooble::s_settings["pageSource/wrapLines"] = checked; if(checked) ui.textBrowser->setLineWrapMode(QTextEdit::WidgetWidth); else ui.textBrowser->setLineWrapMode(QTextEdit::NoWrap); } void dpagesourcewindow::slotSetIcons(void) { QSettings settings (dooble::s_settings.value("iconSet").toString(), QSettings::IniFormat); settings.beginGroup("pageSourceWindow"); ui.actionPrint->setIcon(QIcon(settings.value("actionPrint").toString())); ui.actionPrint_Preview->setIcon (QIcon(settings.value("actionPrint_Preview").toString())); ui.actionClose->setIcon(QIcon(settings.value("actionClose").toString())); ui.actionFind->setIcon(QIcon(settings.value("actionFind").toString())); ui.actionSave_As->setIcon (QIcon(settings.value("actionSave_As").toString())); ui.hideFindToolButton->setIcon (QIcon(settings.value("hideFindToolButton").toString())); ui.nextToolButton->setIcon (QIcon(settings.value("nextToolButton").toString())); ui.previousToolButton->setIcon (QIcon(settings.value("previousToolButton").toString())); setWindowIcon(QIcon(settings.value("windowIcon").toString())); } #ifdef Q_OS_MAC #if QT_VERSION >= 0x050000 && QT_VERSION < 0x050300 bool dpagesourcewindow::event(QEvent *event) { if(event) if(event->type() == QEvent::WindowStateChange) if(windowState() == Qt::WindowNoState) { /* ** Minimizing the window on OS 10.6.8 and Qt 5.x will cause ** the window to become stale once it has resurfaced. */ hide(); show(); update(); } return QMainWindow::event(event); } #else bool dpagesourcewindow::event(QEvent *event) { return QMainWindow::event(event); } #endif #else bool dpagesourcewindow::event(QEvent *event) { return QMainWindow::event(event); } #endif
[ "textbrowser@gmail.com" ]
textbrowser@gmail.com
7069e7eb869ab45174e16cf9c0fdc79c5c50204b
47f53bed9d6a4e8f2f84c1931ebe773cf58256b9
/lib/CATGUI/CAT3DView.cpp
a3c09b951b17fd161c0ff6fad34572b0fa2cb43b
[ "Libpng", "LicenseRef-scancode-unknown-license-reference", "MIT", "Zlib", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
michaelellison/Mike-s-Demo-App
a105ac46bbd29df0403423190579d24e0c4a4746
c0ba505e935bb1d98925c3b6bf04d3d5e2afa19a
refs/heads/master
2021-01-17T06:28:45.247677
2011-06-09T00:25:00
2011-06-09T00:25:00
1,840,197
0
0
null
null
null
null
UTF-8
C++
false
false
18,890
cpp
// ------------------------------------------------------------------ // CAT3DView.cpp // Copyright (c) 2002-2011 Mike Ellison. // Quick hack to wedge it from old GUI to new.... needs work. // ------------------------------------------------------------------ #include "CAT3DView.h" #include "CATWindow.h" #include "CATCursor.h" #include "CATUtil.h" #include "CATEventDefs.h" // Include opengl libs for 3D #include "gl\gl.h" #include "gl\glu.h" CATFloat32 kMinRotate = 0.0001f; int kRotateTimer = 100; CAT3DView::CAT3DView( const CATString& element, const CATString& rootDir) : CATControlWnd(element, rootDir) { // Defaults // Register a window class for the 3D view fWindowAtom = 0; fDisplayList = -1; fAxisList = -1; fRotateSpeed = 0.0f; f3DXYTranslating = false; // Are we moving the view? f3DXYRotating = false; // Rotating it? f3DZTranslating = false; // Translating on Z? f3DZRotating = false; // Rotating on Z? fStereoView = false; // Stereo mode? fFullScreen = false; // Full screen mode? fTracking = false; fLastMouseX = 0; // Last known position of the mouse with a button down fLastMouseY = 0; memset(&fOrgRect,0,sizeof(RECT)); // Start out at origin for view fViewX = fViewY = fViewZ = 0.0; fViewRotX = fViewRotY = fViewRotZ = 0.0; fCursor.SetType(CATCURSOR_HAND); } // Destructor CAT3DView::~CAT3DView() { // Kill the display list if we got one if (fDisplayList != -1) { glDeleteLists(fDisplayList,1); } if (fAxisList != -1) { glDeleteLists(fAxisList,1); } } // We draw the 3D stuff after the main CodeRock GUI draws, so that // it won't be scaled with the other stuff. // void CAT3DView::PostDraw( CATDRAWCONTEXT hdc, const CATRect& updateRect) { HDC odc; PAINTSTRUCT ps; // Begin a paint operation odc = BeginPaint(fHwnd, &ps); // Make the OpenGL RC current for drawing ::wglMakeCurrent(odc,fHRC); // Clear the window - we should double buffer here.... ::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Store the current matrix - we should be in modelview mode right now ::glPushMatrix(); // Translate first, then rotate Z/Y/X to our current camera view ::glTranslatef(fViewX, fViewY, fViewZ); ::glRotatef(fViewRotZ,0,0,1); ::glRotatef(fViewRotY,0,1,0); ::glRotatef(fViewRotX,1,0,0); GLfloat ambient[] = {1.6f, 1.6f, 1.6f, 1.0f}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient); GLfloat lightColor1[] = {1.0f, 1.0f, 1.0f, 1.0f}; GLfloat lightPos1[] = {fViewX, fViewY, fMaxZ, 0.0f}; glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor1); glLightfv(GL_LIGHT0, GL_POSITION, lightPos1); // Draw anything in our display list if (fDisplayList != -1) { ::glCallList(fDisplayList); } if (fAxisList != -1) { ::glCallList(fAxisList); } // Restore the default view matrix ::glPopMatrix(); // Flush out all drawing commands ::glFlush(); ::SwapBuffers(odc); // End the session with the OpenGL RC ::wglMakeCurrent(NULL,NULL); // End Paint session EndPaint(fHwnd,&ps); } // This is more or less our OnSize() event, 'cept it's different // for Post-drawn controls as they don't have the scaling and such // applied to them like all the other controls do... CATResult CAT3DView::RectFromAttribs() { CATResult res = CATControlWnd::RectFromAttribs(); CATRect rect = this->GetRectAbs(); // Move the 3D window to our new location - don't redraw it yet MoveWindow( fHwnd, rect.left, rect.top, rect.Width(), rect.Height(), FALSE); // Make the OpenGL RC current for our window HDC hdc = GetDC(fHwnd); ::wglMakeCurrent(hdc,fHRC); GLsizei glw, glh; glw = rect.Width(); glh = rect.Height(); // Reset the viewport, persepective, and matrix ::glViewport(0,0,glw,glh); ::glMatrixMode(GL_PROJECTION); ::glLoadIdentity(); ::gluPerspective(45.0, (CATFloat64)glw/(CATFloat64)glh, fabs(fMaxZ-fMinZ)/10, // 1 to 100 for viewing. Hey, sounds good to me ;) fabs(fMaxZ-fMinZ)*10); // might actually calc this or something later, but for objects // with a 12" z-depth, should work pretty well... // Switch to model view for our next draw, and reset the matrix // We perform the view translations/rotations during the draw. ::glMatrixMode(GL_MODELVIEW); ::glLoadIdentity(); // Release the RC and DC ::wglMakeCurrent(NULL,NULL); ReleaseDC(fHwnd, hdc); return res; } bool CAT3DView::OnControlEvent(const CATEvent& eventMsg, CATInt32& returnVal) { switch (eventMsg.fEventCode) { case CATEVENT_WINDOWS_EVENT: { returnVal = (CATInt32)CAT3DViewProc( (HWND)eventMsg.fIntParam1, (UINT)eventMsg.fIntParam2, (WPARAM)eventMsg.fIntParam3, (LPARAM)eventMsg.fIntParam4); } break; default: break; } return false; } // This is the raw Win32 window proc for the 3D view window. // Handle mousing and stuff here... LRESULT CALLBACK CAT3DView::CAT3DViewProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // Get our "this" pointer from the window. WARNING: will not be true on WM_CREATE // (it is set on WM_CREATE though from the datastructure in lParam for window creation) CAT3DView* wnd3d = (CAT3DView*)GetWindowLongPtr(hwnd,GWLP_USERDATA); switch (uMsg) { // Mouse has left the building. // Bail out of any mouse-down stuff we were doing. case WM_KILLFOCUS: wnd3d->f3DXYTranslating = false; wnd3d->f3DXYRotating = false; wnd3d->f3DZTranslating = false; wnd3d->f3DZRotating = false; break; // This gets called anytime the mouse moves within our window // check button-down motions case WM_MOUSEMOVE: { // Find the XY offsets from the last location of the mouse CATFloat32 xOff = (CATFloat32)(((CATInt16)LOWORD(lParam) - wnd3d->fLastMouseX)); CATFloat32 yOff = (CATFloat32)(((CATInt16)HIWORD(lParam) - wnd3d->fLastMouseY)); // Figure out what to do wnd3d->On3DMouseMove( xOff, yOff, (wParam & MK_LBUTTON) > 0, (wParam & MK_MBUTTON) > 0, (wParam & MK_RBUTTON) > 0); // Save the last mouse position wnd3d->fLastMouseX = (CATInt16)LOWORD(lParam); wnd3d->fLastMouseY = (CATInt16)HIWORD(lParam); return TRUE; } break; case WM_TIMER: if ((wParam == kRotateTimer) && (wnd3d->fRotateSpeed > kMinRotate)) { // This time, the ratios are based from a full circle / window size CATFloat32 ratio = (360.0f) / (CATFloat32)(wnd3d->fRect.right - wnd3d->fRect.left); wnd3d->fViewRotY += wnd3d->fRotateSpeed * ratio; while (wnd3d->fViewRotY > 360) wnd3d->fViewRotY -= 360; wnd3d->MarkDirty(); } break; case WM_CREATE: // Store our "this" pointer with the window { LPCREATESTRUCT lpc = (LPCREATESTRUCT)lParam; SetWindowLongPtr(hwnd,GWLP_USERDATA,(LONG)lpc->lpCreateParams); // SetWindowLong's don't take effect until the next SetWindowPos, so flush it now // before we get a message that might want to use the this pointer... SetWindowPos(hwnd,0,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOZORDER|SWP_NOSIZE); ::SetTimer(hwnd,kRotateTimer,40,0); } return 0; break; // Yukky blinkies go away. case WM_ERASEBKGND: return TRUE; break; case WM_DESTROY: // When the window is destroyed, we should destroy our // OpenGL context as well. ::KillTimer(hwnd,kRotateTimer); ::wglMakeCurrent(0,0); ::wglDeleteContext(wnd3d->fHRC); wnd3d->fHRC = 0; return 0; break; } return DefWindowProc(hwnd,uMsg,wParam,lParam); } void CAT3DView::SetRotateSpeed(CATFloat32 speed) { fRotateSpeed = speed; } // Handle mouse movements / buttons in 3D window void CAT3DView::On3DMouseMove(CATFloat32 xOff, CATFloat32 yOff, bool leftBtn, bool midBtn, bool rightBtn) { CATFloat32 xRatio; // x-motion ratio, generally a ratio of "What we're adjusting" / "Width of Window Mouse is in" CATFloat32 yRatio; // y-motion ratio, generally a ratio of "What we're adjusting" / "Height of Window Mouse is in" CATFloat32 ratio; // If x and y adjust similar stuff, we might want to pick a speed that is somewhere between // the two but equal so things work as expected for the operator... bool wasTracking = fTracking; // Calc width/height of the view rectangle CATInt32 wndWidth = this->fRect.right - this->fRect.left; CATInt32 wndHeight = this->fRect.bottom - this->fRect.top; // right mouse button controls normal translation on XY axis if (rightBtn) { // If we just put the button down, then don't translate anything yet, // just set the location for the last mouse position and start the // translation process... if (!f3DXYTranslating) { f3DXYTranslating = true; } else { // xRatio is the (width of the object) / (width of view window) // yRatio is the (height of object) / (height of view window) // // With these ratios, we can move the mouse exactly one screen to move the object across the screen. // However, if we got a long skinny object, this "feels" weird, so we take the average of the two. xRatio = (fMaxX - fMinX) / (CATFloat32)(wndWidth); yRatio = (fMaxY - fMinY) / (CATFloat32)(wndHeight); // Average ratio ratio = (xRatio + yRatio)/2; // Translate XY by our mouse offsets * ratio. // Note that for Y, the view's (0,0) point is in top-left, so we invert motion. fViewX += xOff*ratio; fViewY -= yOff*ratio; } } else { // No more mouse button = no more translating. f3DXYTranslating = false; } // Middle button - Z translation // Z translation is performed similarly to XY translation, // only it's just on the Z axis. // // Note that if both the middle AND the left button are down, we're going to do // Z-rotation instead (further down in dah code...) if (midBtn && !(leftBtn)) { if (!f3DZTranslating) { f3DZTranslating = true; f3DZRotating = false; } else { // We allow motion on either X or Y by the mouse to change Z xRatio = (fMaxZ - fMinZ) / (CATFloat32)(wndWidth); yRatio = (fMaxZ - fMinZ) / (CATFloat32)(wndHeight); // Translation on Z = xMovement*xRatio + yMovement*yRatio fViewZ += ((xOff * xRatio) + (yOff*yRatio)); } } else { f3DZTranslating = false; } // Now for rotational fun - // Left button (alone) performs rotation on the X and Y Axis // Note: if both left and middle are down, we do Z-Rotation (see farther below...) if (leftBtn && !(midBtn)) { if (!f3DXYRotating) { f3DXYRotating = true; f3DZRotating = false; } else { // This time, the ratios are based from a full circle / window size xRatio = (360.0f) / (CATFloat32)(wndWidth); yRatio = (360.0f) / (CATFloat32)(wndHeight); ratio = (xRatio + yRatio)/2; // Add rotations to our view fViewRotX += yOff * ratio; fViewRotY += xOff * ratio; // Keep the rotations legal in degrees // We use while in case for some reason the mouse movement // was really really big - probably not necessary, but not // particularly costly either. while (fViewRotX > 360) fViewRotX -= 360; while (fViewRotX < 0) fViewRotX += 360; while (fViewRotY > 360) fViewRotY -= 360; while (fViewRotY < 0) fViewRotY += 360; } } else { // End rotating stuff. f3DXYRotating = false; } // Z-Rotation // Left button with Middle button performs rotation on the Z Axis if (leftBtn && midBtn) { if (!f3DZRotating) { f3DZTranslating = false; f3DXYRotating = false; f3DZRotating = true; } else { // This time, the ratios are based from a full circle / window size xRatio = (360.0f) / (CATFloat32)(wndWidth); yRatio = (360.0f) / (CATFloat32)(wndHeight); // Z rotation is a combination of y movement and x movement fViewRotZ += (yOff * yRatio) + (xOff * xRatio); // Keep the rotations legal in degrees while (fViewRotZ > 360) fViewRotZ -= 360; while (fViewRotZ < 0) fViewRotZ += 360; } } else { // End rotating stuff. f3DZRotating = false; } // If we're doing something, force a redraw. if (f3DXYRotating || f3DXYTranslating || f3DZTranslating || f3DZRotating) { MarkDirty(); } if (!wasTracking) { if (leftBtn || rightBtn || midBtn) { fTracking = true; ::SetCapture(fControlWnd); } } else { if (fTracking) { if (!(leftBtn || rightBtn || midBtn)) { ::ReleaseCapture(); fTracking = false; } } } } // Center the viewport to our object void CAT3DView::CenterViewport() { // Zero rotations this->fViewRotX = 0.0; this->fViewRotY = 0.0; this->fViewRotZ = 0.0; // Look at center, a little back on Z this->fViewX = (fMaxX + fMinX)/2; this->fViewY = (fMaxY + fMinY)/2; this->fViewZ = (CATFloat32)((fMinZ - fabs((fMaxZ - fMinZ))*2 )); } void CAT3DView::SetAxisDisplay(bool on, bool corner) { // Connect to the OpenGL RC HDC hdc = GetDC(this->fHwnd); ::wglMakeCurrent(hdc,fHRC); // Delete old axis display if (fAxisList != -1) { ::glDeleteLists(fAxisList,1); fAxisList = -1; } // If we are just turning it off, bail now. if (on == false) { return; } // Create a new list fAxisList = ::glGenLists(1); // Start list compiling ::glNewList(fAxisList,GL_COMPILE); { ::glBegin(GL_LINES); // Draw vertex lines // X-axis glColor3f(1,0,0); glVertex3f(0,0,0); glVertex3f(12,0,0); // Y - axis glColor3f(0,1,0); glVertex3f(0,0,0); glVertex3f(0,12,0); // Z - axis glColor3f(0,0,1); glVertex3f(0,0,0); glVertex3f(0,0,12); ::glEnd(); // End the list operations } ::glEndList(); // Release OpenGL and DC ::wglMakeCurrent(NULL,NULL); ReleaseDC(this->fHwnd, hdc); } // Auto-facet for scanned information void CAT3DView::Set3dFacets( CATC3DPoint* pointArray, CATInt32 numScans, CATInt32 height, bool triangles) { // Connect to the OpenGL RC HDC hdc = GetDC(this->fHwnd); ::wglMakeCurrent(hdc,fHRC); // Nuke the old display list if there is one if (fDisplayList != -1) { ::glDeleteLists(fDisplayList,1); fDisplayList = -1; } if ((pointArray == 0) || (numScans == 0) || (height == 0)) { return; } // Create a new list fDisplayList = ::glGenLists(1); CATC3DPoint* curPoint = pointArray; // We want to track our min/max positions of the object - // start 'em out here or bail if we can't get the point. fMinX = fMaxX = (CATFloat32)curPoint->x; fMinY = fMaxY = -(CATFloat32)curPoint->y; fMinZ = fMaxZ = (CATFloat32)curPoint->z; // Start list compiling ::glNewList(fDisplayList,GL_COMPILE); { ::glBegin(GL_QUADS); { // Loop through all the points in the list and // store 'em into the display list. Also // compile our min/max locations for the object. for (CATInt32 x = 0; x < numScans - 1; x++) { for (CATInt32 y = 0; y < height - 1; y++) { CATC3DPoint *tlPoint, *trPoint, *blPoint, *brPoint; tlPoint = &pointArray[x*height + y]; trPoint = &pointArray[(x + 1)*height + y]; blPoint = &pointArray[x*height + y + 1]; brPoint = &pointArray[(x + 1)*height + y + 1]; if ((tlPoint->x == 0) && (tlPoint->y == 0) && (tlPoint->z == 0)) continue; if ((trPoint->x == 0) && (trPoint->y == 0) && (trPoint->z == 0)) continue; if ((blPoint->x == 0) && (blPoint->y == 0) && (blPoint->z == 0)) continue; if ((brPoint->x == 0) && (brPoint->y == 0) && (brPoint->z == 0)) continue; ::glColor3f( ((GLfloat)(tlPoint->color.r)/255.0f), ((GLfloat)(tlPoint->color.g)/255.0f), ((GLfloat)(tlPoint->color.b)/255.0f)); // Set location ::glVertex3f( (CATFloat32)tlPoint->x, -(CATFloat32)tlPoint->y, (CATFloat32)tlPoint->z ); ::glColor3f( ((GLfloat)(trPoint->color.r)/255.0f), ((GLfloat)(trPoint->color.g)/255.0f), ((GLfloat)(trPoint->color.b)/255.0f)); // Set location ::glVertex3f( (CATFloat32)trPoint->x, -(CATFloat32)trPoint->y, (CATFloat32)trPoint->z ); ::glColor3f( ((GLfloat)(brPoint->color.r)/255.0f), ((GLfloat)(brPoint->color.g)/255.0f), ((GLfloat)(brPoint->color.b)/255.0f)); // Set location ::glVertex3f( (CATFloat32)brPoint->x, -(CATFloat32)brPoint->y, (CATFloat32)brPoint->z ); ::glColor3f( ((GLfloat)(blPoint->color.r)/255.0f), ((GLfloat)(blPoint->color.g)/255.0f), ((GLfloat)(blPoint->color.b)/255.0f)); // Set location ::glVertex3f( (CATFloat32)blPoint->x, -(CATFloat32)blPoint->y, (CATFloat32)blPoint->z ); // Track min/max fMinX = min(fMinX,(CATFloat32)tlPoint->x); fMaxX = max(fMaxX,(CATFloat32)tlPoint->x); fMinY = min(fMinY,-(CATFloat32)tlPoint->y); fMaxY = max(fMaxY,-(CATFloat32)tlPoint->y); fMinZ = min(fMinZ,(CATFloat32)tlPoint->z); fMaxZ = max(fMaxZ,(CATFloat32)tlPoint->z); } } } // End the points operations ::glEnd(); // End the list operations } ::glEndList(); // Center the viewport to look at the object RectFromAttribs(); CenterViewport(); // Release OpenGL and DC ::wglMakeCurrent(NULL,NULL); ReleaseDC(this->fHwnd, hdc); } void CAT3DView::OnParentCreate() { fWindowType = "CAT3DView"; // Register a window class for us.. // Set up the Win32 structure for creating a window for our 3D OpenGL view WNDCLASS wc; wc.style = CS_HREDRAW|CS_VREDRAW; wc.lpfnWndProc = CAT3DViewProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = gApp->GetInstance(); wc.hIcon = NULL; wc.hCursor = 0; wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = 0; wc.lpszClassName = fWindowType; fWindowAtom = RegisterClass(&wc); CATControlWnd::OnParentCreate(); fHwnd = CATControlWnd::GetControlWndHndl(); // Now create the OpenGL objects needed for this window.... // Why telling it I want a damned color pixel takes so many zeros, // I may never understand... PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 24, 0,0,0, 0,0,0, 0,0, 0,0,0,0,0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0}; // Set pixel format and get an openGL RC HDC hdc = GetDC(fHwnd); // Pick our pixel format for the DC and set it fPixelFormat = ::ChoosePixelFormat(hdc,&pfd); SetPixelFormat(hdc,fPixelFormat,&pfd); // Create the openGL context and store fHRC = ::wglCreateContext(hdc); // Make it current ::wglMakeCurrent(hdc,fHRC); // Set our clear color to 0 ::glClearColor(0.0f,0.0f,0.0f,0.0f); ::glClearDepth(1.0f); // Enable depth checking and smooth points at size 2 ::glEnable(GL_DEPTH_TEST); ::glEnable(GL_POINT_SMOOTH); glEnable(GL_COLOR_MATERIAL); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glShadeModel(GL_SMOOTH); ::glPointSize(2); // Unset the context ::wglMakeCurrent(0,0); ReleaseDC(fHwnd, hdc); }
[ "me@michaelellison.me" ]
me@michaelellison.me
cf0079b50392ef28a65d7161fffcfeff53a44a11
da9985577c307a6f2b00f2d6afd6654d06a9230a
/src/commonlib/kslib/anet/src/anet/ipackethandler.h
67106ae44aa87599e7de99427aca9a8f0c8c6c6a
[]
no_license
charpty/kingso
e720bd247efd7b1b7674c089947d9adb9963f4a1
c65cd16a7aa38f9dfa37f66320bc8e42b30c8662
refs/heads/master
2023-08-09T09:47:51.121529
2019-03-03T15:28:14
2019-03-03T15:28:14
173,532,203
4
12
null
2020-10-13T12:12:18
2019-03-03T04:51:21
C++
UTF-8
C++
false
false
1,088
h
#ifndef ANET_IPACKETHANDLER_H_ #define ANET_IPACKETHANDLER_H_ namespace anet { class Packet; class IPacketHandler { public: enum HPRetCode { KEEP_CHANNEL = 0, CLOSE_CHANNEL = 1, FREE_CHANNEL = 2 }; /** * This function is used in Client. When ANET receive response, * it will call handlePacket() to deal with response packet. * User use ANET send requests and use handlePacket() deal * with response. This function is Called in * Connection::handlePacket(). * In some exceptions, ControlPacket(such as TimeoutPacket, * BadPacket) will be received. Obviously, you should consider * all these exceptions in you implementation. * * @param packet response packet or ControlPacket * @param args it's used to indicate which request packet this * respose packet corresponding. It's the same as args you used * in Connection::posePacket(). * @return not used temporary. */ virtual HPRetCode handlePacket(Packet *packet, void *args) = 0; }; } #endif /*IPACHETHANDLER_H_*/
[ "charpty@gmail.com" ]
charpty@gmail.com
c65385ba0b57b9c24e5148df1b2ea84f08dee214
de3b55be8224007e01e79000d8d9800ff9da1ac3
/hash/hash/Hashing.cpp
81d96805c3977095d23806b627f7ac9b2dbf8c0e
[]
no_license
katherin2096/ADA
7f22cb566239fec5dba36200f6d12fa403008d26
ac1c0c73c2d0808cd2024f3ce185099e1460f18e
refs/heads/master
2022-06-03T03:10:38.815242
2020-05-01T00:20:26
2020-05-01T00:20:26
260,348,475
0
0
null
null
null
null
UTF-8
C++
false
false
3,003
cpp
#include "Hashing.h" #include <cstdio> #include <string> #include <fstream> #include "Hashing.h" #include <iostream> //#include <bits/types/FILE.h> #include <cstring> #include <tuple> #include <functional> using namespace std; Hashing::Hashing(int size, string filepath) { this->size = size; this->filepath = filepath; setup(); } // Main Functions Node Hashing::search(int key) { return get<1>(search_data(key, &Hashing::is_same_key)); } double Hashing::time_spent() { int amount = 0; Node node = Node::empty_node(); int items_count = 0; for (int i = 0; i < size; i++) { node = get_item(i); if (!node.is_empty) { items_count++; amount += time_spent(node.key); } } return amount / (double)items_count; } // Search type functions bool Hashing::is_same_key(Node node, int key) { return !node.is_empty && node.key == key; } bool Hashing::empty_node(Node node, int key) { return node.is_empty; } bool Hashing::previous_node(Node node, int key) { return get_item(node.next).key == key; } // Advanced void Hashing::delete_item(int position) { set_item(Node::empty_node(), position); } int Hashing::item_position(int key) { return get<0>(search_data(key, &Hashing::is_same_key)); } int Hashing::time_spent(int key) { return get<2>(search_data(key, &Hashing::is_same_key)); } // Receives key to be used to find positions, and criteria // that will identify proper position, if exists // Returns position, node at position and amount of iterations to find tuple<int, Node, int> Hashing::search_data( int key, bool(Hashing::* criteria)(Node, int), int(Hashing::* position_calculator)(int, int, Node)) { int position = (this->*position_calculator)(-1, key, Node::empty_node()); Node node = get_item(position); int counter = 1; while (!(this->*criteria)(node, key)) { position = (this->*position_calculator)(position, key, node); // Has searched entire file if (counter > this->size || position == -1) { return make_tuple(-1, Node::empty_node(), counter); } node = get_item(position); counter++; } return make_tuple(position, node, counter); } // Config void Hashing::setup() { // Check if file exists if (!ifstream(filepath)) { fstream file(filepath, ios::binary | ios::app); if (file.is_open()) { // Fills file with empty nodes for (int i = 0; i < this->size; i++) { Node node = Node::empty_node(); file.write((char*)&node, sizeof(Node)); } file.close(); } } } // File manipulation Node Hashing::get_item(int position) { ifstream file(filepath, ios::binary); Node* searched = (Node*)malloc(sizeof(Node)); if (file.is_open()) { file.seekg(sizeof(Node) * position, ios_base::beg); file.read((char*)searched, sizeof(Node)); file.close(); } return *searched; } void Hashing::set_item(Node node, int position) { fstream file(filepath, ios::binary | ios::in | ios::out); if (file.is_open()) { file.seekp(sizeof(Node) * position, ios_base::beg); file.write((char*)&node, sizeof(Node)); file.close(); } }
[ "38145569+katherin2096@users.noreply.github.com" ]
38145569+katherin2096@users.noreply.github.com
e3f25b525e9909e48bd122e105bdb81ea1531f02
ce4a3f0f6fad075b6bd2fe7d84fd9b76b9622394
/CTRTextureGouraudAdd.cpp
34303a450deccf92ff7a79ce99d1de6eaa1168cb
[]
no_license
codetiger/IrrNacl
c630187dfca857c15ebfa3b73fd271ef6bad310f
dd0bda2fb1c2ff46813fac5e11190dc87f83add7
refs/heads/master
2021-01-13T02:10:24.919588
2012-07-22T06:27:29
2012-07-22T06:27:29
4,461,459
5
2
null
null
null
null
UTF-8
C++
false
false
12,730
cpp
// Copyright (C) 2002-2011 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h #include "IrrCompileConfig.h" #include "CTRTextureGouraud.h" #ifdef _IRR_COMPILE_WITH_SOFTWARE_ namespace irr { namespace video { class CTRTextureGouraudAdd : public CTRTextureGouraud { public: //! constructor CTRTextureGouraudAdd(IZBuffer* zbuffer); //! draws an indexed triangle list virtual void drawIndexedTriangleList(S2DVertex* vertices, s32 vertexCount, const u16* indexList, s32 triangleCount); protected: }; //! constructor CTRTextureGouraudAdd::CTRTextureGouraudAdd(IZBuffer* zbuffer) : CTRTextureGouraud(zbuffer) { #ifdef _DEBUG setDebugName("CTRTextureGouraudAdd"); #endif } //! draws an indexed triangle list void CTRTextureGouraudAdd::drawIndexedTriangleList(S2DVertex* vertices, s32 vertexCount, const u16* indexList, s32 triangleCount) { const S2DVertex *v1, *v2, *v3; u16 color; f32 tmpDiv; // temporary division factor f32 longest; // saves the longest span s32 height; // saves height of triangle u16* targetSurface; // target pointer where to plot pixels s32 spanEnd; // saves end of spans f32 leftdeltaxf; // amount of pixels to increase on left side of triangle f32 rightdeltaxf; // amount of pixels to increase on right side of triangle s32 leftx, rightx; // position where we are f32 leftxf, rightxf; // same as above, but as f32 values s32 span; // current span u16 *hSpanBegin, *hSpanEnd; // pointer used when plotting pixels s32 leftR, leftG, leftB, rightR, rightG, rightB; // color values s32 leftStepR, leftStepG, leftStepB, rightStepR, rightStepG, rightStepB; // color steps s32 spanR, spanG, spanB, spanStepR, spanStepG, spanStepB; // color interpolating values while drawing a span. s32 leftTx, rightTx, leftTy, rightTy; // texture interpolating values s32 leftTxStep, rightTxStep, leftTyStep, rightTyStep; // texture interpolating values s32 spanTx, spanTy, spanTxStep, spanTyStep; // values of Texturecoords when drawing a span core::rect<s32> TriangleRect; s32 leftZValue, rightZValue; s32 leftZStep, rightZStep; s32 spanZValue, spanZStep; // ZValues when drawing a span TZBufferType* zTarget, *spanZTarget; // target of ZBuffer; lockedSurface = (u16*)RenderTarget->lock(); lockedZBuffer = ZBuffer->lock(); lockedTexture = (u16*)Texture->lock(); for (s32 i=0; i<triangleCount; ++i) { v1 = &vertices[*indexList]; ++indexList; v2 = &vertices[*indexList]; ++indexList; v3 = &vertices[*indexList]; ++indexList; // back face culling if (BackFaceCullingEnabled) { s32 z = ((v3->Pos.X - v1->Pos.X) * (v3->Pos.Y - v2->Pos.Y)) - ((v3->Pos.Y - v1->Pos.Y) * (v3->Pos.X - v2->Pos.X)); if (z < 0) continue; } //near plane clipping if (v1->ZValue<0 && v2->ZValue<0 && v3->ZValue<0) continue; // sort for width for inscreen clipping if (v1->Pos.X > v2->Pos.X) swapVertices(&v1, &v2); if (v1->Pos.X > v3->Pos.X) swapVertices(&v1, &v3); if (v2->Pos.X > v3->Pos.X) swapVertices(&v2, &v3); if ((v1->Pos.X - v3->Pos.X) == 0) continue; TriangleRect.UpperLeftCorner.X = v1->Pos.X; TriangleRect.LowerRightCorner.X = v3->Pos.X; // sort for height for faster drawing. if (v1->Pos.Y > v2->Pos.Y) swapVertices(&v1, &v2); if (v1->Pos.Y > v3->Pos.Y) swapVertices(&v1, &v3); if (v2->Pos.Y > v3->Pos.Y) swapVertices(&v2, &v3); TriangleRect.UpperLeftCorner.Y = v1->Pos.Y; TriangleRect.LowerRightCorner.Y = v3->Pos.Y; if (!TriangleRect.isRectCollided(ViewPortRect)) continue; // calculate height of triangle height = v3->Pos.Y - v1->Pos.Y; if (!height) continue; // calculate longest span longest = (v2->Pos.Y - v1->Pos.Y) / (f32)height * (v3->Pos.X - v1->Pos.X) + (v1->Pos.X - v2->Pos.X); spanEnd = v2->Pos.Y; span = v1->Pos.Y; leftxf = (f32)v1->Pos.X; rightxf = (f32)v1->Pos.X; leftZValue = v1->ZValue; rightZValue = v1->ZValue; leftR = rightR = video::getRed(v1->Color)<<8; leftG = rightG = video::getGreen(v1->Color)<<8; leftB = rightB = video::getBlue(v1->Color)<<8; leftTx = rightTx = v1->TCoords.X; leftTy = rightTy = v1->TCoords.Y; targetSurface = lockedSurface + span * SurfaceWidth; zTarget = lockedZBuffer + span * SurfaceWidth; if (longest < 0.0f) { tmpDiv = 1.0f / (f32)(v2->Pos.Y - v1->Pos.Y); rightdeltaxf = (v2->Pos.X - v1->Pos.X) * tmpDiv; rightZStep = (s32)((v2->ZValue - v1->ZValue) * tmpDiv); rightStepR = (s32)(((s32)(video::getRed(v2->Color)<<8) - rightR) * tmpDiv); rightStepG = (s32)(((s32)(video::getGreen(v2->Color)<<8) - rightG) * tmpDiv); rightStepB = (s32)(((s32)(video::getBlue(v2->Color)<<8) - rightB) * tmpDiv); rightTxStep = (s32)((v2->TCoords.X - rightTx) * tmpDiv); rightTyStep = (s32)((v2->TCoords.Y - rightTy) * tmpDiv); tmpDiv = 1.0f / (f32)height; leftdeltaxf = (v3->Pos.X - v1->Pos.X) * tmpDiv; leftZStep = (s32)((v3->ZValue - v1->ZValue) * tmpDiv); leftStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - leftR) * tmpDiv); leftStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - leftG) * tmpDiv); leftStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - leftB) * tmpDiv); leftTxStep = (s32)((v3->TCoords.X - leftTx) * tmpDiv); leftTyStep = (s32)((v3->TCoords.Y - leftTy) * tmpDiv); } else { tmpDiv = 1.0f / (f32)height; rightdeltaxf = (v3->Pos.X - v1->Pos.X) * tmpDiv; rightZStep = (s32)((v3->ZValue - v1->ZValue) * tmpDiv); rightStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - rightR) * tmpDiv); rightStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - rightG) * tmpDiv); rightStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - rightB) * tmpDiv); rightTxStep = (s32)((v3->TCoords.X - rightTx) * tmpDiv); rightTyStep = (s32)((v3->TCoords.Y - rightTy) * tmpDiv); tmpDiv = 1.0f / (f32)(v2->Pos.Y - v1->Pos.Y); leftdeltaxf = (v2->Pos.X - v1->Pos.X) * tmpDiv; leftZStep = (s32)((v2->ZValue - v1->ZValue) * tmpDiv); leftStepR = (s32)(((s32)(video::getRed(v2->Color)<<8) - leftR) * tmpDiv); leftStepG = (s32)(((s32)(video::getGreen(v2->Color)<<8) - leftG) * tmpDiv); leftStepB = (s32)(((s32)(video::getBlue(v2->Color)<<8) - leftB) * tmpDiv); leftTxStep = (s32)((v2->TCoords.X - leftTx) * tmpDiv); leftTyStep = (s32)((v2->TCoords.Y - leftTy) * tmpDiv); } // do it twice, once for the first half of the triangle, // end then for the second half. for (s32 triangleHalf=0; triangleHalf<2; ++triangleHalf) { if (spanEnd > ViewPortRect.LowerRightCorner.Y) spanEnd = ViewPortRect.LowerRightCorner.Y; // if the span <0, than we can skip these spans, // and proceed to the next spans which are really on the screen. if (span < ViewPortRect.UpperLeftCorner.Y) { // we'll use leftx as temp variable if (spanEnd < ViewPortRect.UpperLeftCorner.Y) { leftx = spanEnd - span; span = spanEnd; } else { leftx = ViewPortRect.UpperLeftCorner.Y - span; span = ViewPortRect.UpperLeftCorner.Y; } leftxf += leftdeltaxf*leftx; rightxf += rightdeltaxf*leftx; targetSurface += SurfaceWidth*leftx; zTarget += SurfaceWidth*leftx; leftZValue += leftZStep*leftx; rightZValue += rightZStep*leftx; leftR += leftStepR*leftx; leftG += leftStepG*leftx; leftB += leftStepB*leftx; rightR += rightStepR*leftx; rightG += rightStepG*leftx; rightB += rightStepB*leftx; leftTx += leftTxStep*leftx; leftTy += leftTyStep*leftx; rightTx += rightTxStep*leftx; rightTy += rightTyStep*leftx; } // the main loop. Go through every span and draw it. while (span < spanEnd) { leftx = (s32)(leftxf); rightx = (s32)(rightxf + 0.5f); // perform some clipping // thanks to a correction by hybrid // calculations delayed to correctly propagate to textures etc. s32 tDiffLeft=0, tDiffRight=0; if (leftx<ViewPortRect.UpperLeftCorner.X) tDiffLeft=ViewPortRect.UpperLeftCorner.X-leftx; else if (leftx>ViewPortRect.LowerRightCorner.X) tDiffLeft=ViewPortRect.LowerRightCorner.X-leftx; if (rightx<ViewPortRect.UpperLeftCorner.X) tDiffRight=ViewPortRect.UpperLeftCorner.X-rightx; else if (rightx>ViewPortRect.LowerRightCorner.X) tDiffRight=ViewPortRect.LowerRightCorner.X-rightx; // draw the span if (rightx + tDiffRight - leftx - tDiffLeft) { tmpDiv = 1.0f / (f32)(rightx - leftx); spanZStep = (s32)((rightZValue - leftZValue) * tmpDiv); spanZValue = leftZValue+tDiffLeft*spanZStep; spanStepR = (s32)((rightR - leftR) * tmpDiv); spanR = leftR+tDiffLeft*spanStepR; spanStepG = (s32)((rightG - leftG) * tmpDiv); spanG = leftG+tDiffLeft*spanStepG; spanStepB = (s32)((rightB - leftB) * tmpDiv); spanB = leftB+tDiffLeft*spanStepB; spanTxStep = (s32)((rightTx - leftTx) * tmpDiv); spanTx = leftTx + tDiffLeft*spanTxStep; spanTyStep = (s32)((rightTy - leftTy) * tmpDiv); spanTy = leftTy+tDiffLeft*spanTyStep; hSpanBegin = targetSurface + leftx+tDiffLeft; spanZTarget = zTarget + leftx+tDiffLeft; hSpanEnd = targetSurface + rightx+tDiffRight; while (hSpanBegin < hSpanEnd) { if (spanZValue > *spanZTarget) { //*spanZTarget = spanZValue; color = lockedTexture[((spanTy>>8)&textureYMask) * lockedTextureWidth + ((spanTx>>8)&textureXMask)]; s32 basis = *hSpanBegin; s32 r = (video::getRed(basis)<<3) + (video::getRed(color)<<3); if (r > 255) r = 255; s32 g = (video::getGreen(basis)<<3) + (video::getGreen(color)<<3); if (g > 255) g = 255; s32 b = (video::getBlue(basis)<<3) + (video::getBlue(color)<<3); if (b > 255) b = 255; *hSpanBegin = video::RGB16(r, g, b); } spanR += spanStepR; spanG += spanStepG; spanB += spanStepB; spanTx += spanTxStep; spanTy += spanTyStep; spanZValue += spanZStep; ++hSpanBegin; ++spanZTarget; } } leftxf += leftdeltaxf; rightxf += rightdeltaxf; ++span; targetSurface += SurfaceWidth; zTarget += SurfaceWidth; leftZValue += leftZStep; rightZValue += rightZStep; leftR += leftStepR; leftG += leftStepG; leftB += leftStepB; rightR += rightStepR; rightG += rightStepG; rightB += rightStepB; leftTx += leftTxStep; leftTy += leftTyStep; rightTx += rightTxStep; rightTy += rightTyStep; } if (triangleHalf>0) // break, we've gout only two halves break; // setup variables for second half of the triangle. if (longest < 0.0f) { tmpDiv = 1.0f / (v3->Pos.Y - v2->Pos.Y); rightdeltaxf = (v3->Pos.X - v2->Pos.X) * tmpDiv; rightxf = (f32)v2->Pos.X; rightZValue = v2->ZValue; rightZStep = (s32)((v3->ZValue - v2->ZValue) * tmpDiv); rightR = video::getRed(v2->Color)<<8; rightG = video::getGreen(v2->Color)<<8; rightB = video::getBlue(v2->Color)<<8; rightStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - rightR) * tmpDiv); rightStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - rightG) * tmpDiv); rightStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - rightB) * tmpDiv); rightTx = v2->TCoords.X; rightTy = v2->TCoords.Y; rightTxStep = (s32)((v3->TCoords.X - rightTx) * tmpDiv); rightTyStep = (s32)((v3->TCoords.Y - rightTy) * tmpDiv); } else { tmpDiv = 1.0f / (v3->Pos.Y - v2->Pos.Y); leftdeltaxf = (v3->Pos.X - v2->Pos.X) * tmpDiv; leftxf = (f32)v2->Pos.X; leftZValue = v2->ZValue; leftZStep = (s32)((v3->ZValue - v2->ZValue) * tmpDiv); leftR = video::getRed(v2->Color)<<8; leftG = video::getGreen(v2->Color)<<8; leftB = video::getBlue(v2->Color)<<8; leftStepR = (s32)(((s32)(video::getRed(v3->Color)<<8) - leftR) * tmpDiv); leftStepG = (s32)(((s32)(video::getGreen(v3->Color)<<8) - leftG) * tmpDiv); leftStepB = (s32)(((s32)(video::getBlue(v3->Color)<<8) - leftB) * tmpDiv); leftTx = v2->TCoords.X; leftTy = v2->TCoords.Y; leftTxStep = (s32)((v3->TCoords.X - leftTx) * tmpDiv); leftTyStep = (s32)((v3->TCoords.Y - leftTy) * tmpDiv); } spanEnd = v3->Pos.Y; } } RenderTarget->unlock(); ZBuffer->unlock(); Texture->unlock(); } } // end namespace video } // end namespace irr #endif // _IRR_COMPILE_WITH_SOFTWARE_ namespace irr { namespace video { ITriangleRenderer* createTriangleRendererTextureGouraudAdd(IZBuffer* zbuffer) { #ifdef _IRR_COMPILE_WITH_SOFTWARE_ return new CTRTextureGouraudAdd(zbuffer); #else return 0; #endif // _IRR_COMPILE_WITH_SOFTWARE_ } } // end namespace video } // end namespace irr
[ "smackallgames@smackall-2bbd93.(none)" ]
smackallgames@smackall-2bbd93.(none)
e11167364bc8d27de7b4e5dc9c98a3abb11c4596
74474c3e970b3c640e74bb9ac41c961593b88c31
/src/webserver/Cookie.cpp
ccdcb72f4dbdbf90fa43edf210a597c23bbae586
[]
no_license
tglane/webServPP
c95d755659d53d13b1effcd686eac3d1eb7462a0
53758fa3b23e0e898c1fd909707935a37607ff70
refs/heads/master
2021-06-22T15:24:20.606906
2021-02-08T21:31:21
2021-02-08T21:31:21
191,049,911
1
0
null
null
null
null
UTF-8
C++
false
false
1,374
cpp
// // Created by timog on 24.02.19. // #include "Cookie.hpp" namespace webserv { Cookie::Cookie(string name, string value, bool httpOnly, bool secure, string comment, string domain, string max_age, string path, int expires) { m_name = std::move(name); m_value = std::move(value); m_http_only = httpOnly; m_secure = secure; m_comment = std::move(comment); m_domain = std::move(domain); m_max_age = std::move(max_age); m_path = std::move(path); if(expires > 0) { set_expiry_date(expires); } } string Cookie::build_header() { string header = "Set-Cookie: " + m_name + "=" + m_value; if(!m_comment.empty()) { header.append("; Comment=" + m_comment); } if(!m_domain.empty()) { header.append("; Domain=" + m_domain); } if(!m_max_age.empty()) { header.append("; Max-Age=" + m_max_age); } if(!m_path.empty()) { header.append("; Path=" + m_path); } if(m_http_only) { header.append("; HttpOnly"); } if(m_secure) { header.append("; secure"); } if(!m_expires.empty()) { header.append("; Expires=" + m_expires); } return header; } void Cookie::set_expiry_date(int days) { std::chrono::time_point<std::chrono::system_clock> e(std::chrono::system_clock::now() + std::chrono::hours(days * 24)); std::time_t t(std::chrono::system_clock::to_time_t(e)); m_expires = std::ctime(&t); } }
[ "timo.glane@gmail.com" ]
timo.glane@gmail.com
484d26c21d64174b4c0d92a9f6665e706368a585
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/asio/read.hpp
bc114db39e51934b3bce64ec56e7a47bf73b68e7
[]
no_license
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,006
hpp
// // read.hpp // ~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_READ_HPP #define BOOST_ASIO_READ_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/asio/async_result.hpp> #include <boost/asio/basic_streambuf_fwd.hpp> #include <boost/asio/error.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /** * @defgroup read boost::asio::read * * @brief Attempt to read a certain amount of data from a stream before * returning. */ /*@{*/ /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::read(s, boost::asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, buffers, * boost::asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::read(s, boost::asio::buffer(data, size), ec); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, buffers, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, boost::system::error_code& ec); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const boost::system::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::read(s, boost::asio::buffer(data, size), * boost::asio::transfer_at_least(32)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const boost::system::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, boost::system::error_code& ec); #if !defined(BOOST_ASIO_NO_IOSTREAM) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, b, * boost::asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code boost::asio::read( * s, b, * boost::asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, boost::system::error_code& ec); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const boost::system::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws boost::system::system_error Thrown on failure. */ template <typename SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const boost::system::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, boost::system::error_code& ec); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) /*@}*/ /** * @defgroup async_read boost::asio::async_read * * @brief Start an asynchronous operation to read a certain amount of data from * a stream. */ /*@{*/ /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * boost::asio::io_service::post(). * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * boost::asio::async_read(s, boost::asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code boost::asio::async_read( * s, buffers, * boost::asio::transfer_all(), * handler); @endcode */ template <typename AsyncReadStream, typename MutableBufferSequence, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (boost::system::error_code, std::size_t)) async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, BOOST_ASIO_MOVE_ARG(ReadHandler) handler); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const boost::system::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * boost::asio::io_service::post(). * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code boost::asio::async_read(s, * boost::asio::buffer(data, size), * boost::asio::transfer_at_least(32), * handler); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename AsyncReadStream, typename MutableBufferSequence, typename CompletionCondition, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (boost::system::error_code, std::size_t)) async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, BOOST_ASIO_MOVE_ARG(ReadHandler) handler); #if !defined(BOOST_ASIO_NO_IOSTREAM) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * boost::asio::io_service::post(). * * @note This overload is equivalent to calling: * @code boost::asio::async_read( * s, b, * boost::asio::transfer_all(), * handler); @endcode */ template <typename AsyncReadStream, typename Allocator, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (boost::system::error_code, std::size_t)) async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, BOOST_ASIO_MOVE_ARG(ReadHandler) handler); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const boost::system::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const boost::system::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * boost::asio::io_service::post(). */ template <typename AsyncReadStream, typename Allocator, typename CompletionCondition, typename ReadHandler> BOOST_ASIO_INITFN_RESULT_TYPE(ReadHandler, void (boost::system::error_code, std::size_t)) async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, BOOST_ASIO_MOVE_ARG(ReadHandler) handler); #endif // !defined(BOOST_ASIO_NO_IOSTREAM) /*@}*/ } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #include <boost/asio/impl/read.hpp> #endif // BOOST_ASIO_READ_HPP ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "adm.fael.hs@gmail.com" ]
adm.fael.hs@gmail.com
3d2c7332c6e711bb9c4d909bb660f6aab7622f7f
6e20207f8aff0f0ad94f05bd025810c6b10a1d5f
/SDK/GlimpseShopkeeperNPC_classes.h
ee02910d9ba7389cbd1d0680fba4b6eb20c054b2
[]
no_license
zH4x-SDK/zWeHappyFew-SDK
2a4e246d8ee4b58e45feaa4335f1feb8ea618a4a
5906adc3edfe1b5de86b7ef0a0eff38073e12214
refs/heads/main
2023-08-17T06:05:18.561339
2021-08-27T13:36:09
2021-08-27T13:36:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
840
h
#pragma once // Name: WeHappyFew, Version: 1.8.8 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass GlimpseShopkeeperNPC.GlimpseShopkeeperNPC_C // 0x0048 (0x1FD8 - 0x1F90) class AGlimpseShopkeeperNPC_C : public AGlimpseAICharacter { public: unsigned char UnknownData00[0x48]; // 0x1F90(0x0048) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass GlimpseShopkeeperNPC.GlimpseShopkeeperNPC_C"); return ptr; } void UserConstructionScript(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
f31b657238964f0d43a1a68e3fc918d1ff027da2
7d66dfb8210fb31ecce8a7d758f8ffa0d6b06b8a
/chrome/browser/chromeos/login/login_ui_keyboard_browsertest.cc
3e5b8d1b6df38f41b8e5e142e6c46c6ef3c673ac
[ "BSD-3-Clause" ]
permissive
souldanger/iridium-browser
e5cb80d7e9bc8b54b1cd8b187913584d4f60ef06
260fd220fbd10a976ebd32d2266f05070b0e421e
refs/heads/master
2023-02-24T09:03:11.671406
2015-05-04T12:30:46
2017-04-24T13:59:34
90,760,286
1
0
null
2017-05-09T15:11:56
2017-05-09T15:11:56
null
UTF-8
C++
false
false
9,415
cc
// 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. #include "base/command_line.h" #include "base/location.h" #include "base/message_loop/message_loop.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/input_method/input_method_persistence.h" #include "chrome/browser/chromeos/language_preferences.h" #include "chrome/browser/chromeos/login/login_manager_test.h" #include "chrome/browser/chromeos/login/startup_utils.h" #include "chrome/browser/chromeos/login/test/oobe_screen_waiter.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/ui/webui/chromeos/login/signin_screen_handler.h" #include "chrome/common/pref_names.h" #include "chromeos/chromeos_switches.h" #include "components/prefs/pref_service.h" #include "content/public/test/test_utils.h" namespace chromeos { namespace { const char kTestUser1[] = "test-user1@gmail.com"; const char kTestUser2[] = "test-user2@gmail.com"; const char kTestUser3[] = "test-user3@gmail.com"; void Append_en_US_InputMethods(std::vector<std::string>* out) { out->push_back("xkb:us::eng"); out->push_back("xkb:us:intl:eng"); out->push_back("xkb:us:altgr-intl:eng"); out->push_back("xkb:us:dvorak:eng"); out->push_back("xkb:us:dvp:eng"); out->push_back("xkb:us:colemak:eng"); out->push_back("xkb:us:workman:eng"); out->push_back("xkb:us:workman-intl:eng"); chromeos::input_method::InputMethodManager::Get()->MigrateInputMethods(out); } class FocusPODWaiter { public: FocusPODWaiter() : focused_(false), runner_(new content::MessageLoopRunner) { GetOobeUI()->signin_screen_handler()->SetFocusPODCallbackForTesting( base::Bind(&FocusPODWaiter::OnFocusPOD, base::Unretained(this))); } ~FocusPODWaiter() { GetOobeUI()->signin_screen_handler()->SetFocusPODCallbackForTesting( base::Closure()); } void OnFocusPOD() { ASSERT_TRUE(base::MessageLoopForUI::IsCurrent()); focused_ = true; if (runner_.get()) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FocusPODWaiter::ExitMessageLoop, base::Unretained(this))); } } void ExitMessageLoop() { runner_->Quit(); } void Wait() { if (focused_) return; runner_->Run(); GetOobeUI()->signin_screen_handler()->SetFocusPODCallbackForTesting( base::Closure()); runner_ = NULL; } private: OobeUI* GetOobeUI() { OobeUI* oobe_ui = LoginDisplayHost::default_host()->GetOobeUI(); CHECK(oobe_ui); return oobe_ui; } bool focused_; scoped_refptr<content::MessageLoopRunner> runner_; }; } // anonymous namespace class LoginUIKeyboardTest : public chromeos::LoginManagerTest { public: LoginUIKeyboardTest() : LoginManagerTest(false) {} ~LoginUIKeyboardTest() override {} void SetUpOnMainThread() override { user_input_methods.push_back("xkb:fr::fra"); user_input_methods.push_back("xkb:de::ger"); chromeos::input_method::InputMethodManager::Get()->MigrateInputMethods( &user_input_methods); LoginManagerTest::SetUpOnMainThread(); } // Should be called from PRE_ test so that local_state is saved to disk, and // reloaded in the main test. void InitUserLRUInputMethod() { PrefService* local_state = g_browser_process->local_state(); input_method::SetUserLRUInputMethodPreferenceForTesting( kTestUser1, user_input_methods[0], local_state); input_method::SetUserLRUInputMethodPreferenceForTesting( kTestUser2, user_input_methods[1], local_state); } protected: std::vector<std::string> user_input_methods; }; IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, PRE_CheckPODScreenDefault) { RegisterUser(kTestUser1); RegisterUser(kTestUser2); StartupUtils::MarkOobeCompleted(); } // Check default IME initialization, when there is no IME configuration in // local_state. IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, CheckPODScreenDefault) { js_checker().ExpectEQ("$('pod-row').pods.length", 2); std::vector<std::string> expected_input_methods; Append_en_US_InputMethods(&expected_input_methods); EXPECT_EQ(expected_input_methods, input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetActiveInputMethodIds()); } IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, PRE_CheckPODScreenWithUsers) { RegisterUser(kTestUser1); RegisterUser(kTestUser2); InitUserLRUInputMethod(); StartupUtils::MarkOobeCompleted(); } // TODO(crbug.com/602951): Test is flaky. IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTest, DISABLED_CheckPODScreenWithUsers) { js_checker().ExpectEQ("$('pod-row').pods.length", 2); EXPECT_EQ(user_input_methods[0], input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetCurrentInputMethod() .id()); std::vector<std::string> expected_input_methods; Append_en_US_InputMethods(&expected_input_methods); // Active IM for the first user (active user POD). expected_input_methods.push_back(user_input_methods[0]); EXPECT_EQ(expected_input_methods, input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetActiveInputMethodIds()); FocusPODWaiter waiter; js_checker().Evaluate("$('pod-row').focusPod($('pod-row').pods[1])"); waiter.Wait(); EXPECT_EQ(user_input_methods[1], input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetCurrentInputMethod() .id()); } class LoginUIKeyboardTestWithUsersAndOwner : public chromeos::LoginManagerTest { public: LoginUIKeyboardTestWithUsersAndOwner() : LoginManagerTest(false) {} ~LoginUIKeyboardTestWithUsersAndOwner() override {} void SetUpCommandLine(base::CommandLine* command_line) override { LoginManagerTest::SetUpCommandLine(command_line); command_line->AppendSwitch(switches::kStubCrosSettings); LoginManagerTest::SetUpCommandLine(command_line); } void SetUpOnMainThread() override { user_input_methods.push_back("xkb:fr::fra"); user_input_methods.push_back("xkb:de::ger"); user_input_methods.push_back("xkb:pl::pol"); chromeos::input_method::InputMethodManager::Get()->MigrateInputMethods( &user_input_methods); CrosSettings::Get()->SetString(kDeviceOwner, kTestUser3); LoginManagerTest::SetUpOnMainThread(); } // Should be called from PRE_ test so that local_state is saved to disk, and // reloaded in the main test. void InitUserLRUInputMethod() { PrefService* local_state = g_browser_process->local_state(); input_method::SetUserLRUInputMethodPreferenceForTesting( kTestUser1, user_input_methods[0], local_state); input_method::SetUserLRUInputMethodPreferenceForTesting( kTestUser2, user_input_methods[1], local_state); input_method::SetUserLRUInputMethodPreferenceForTesting( kTestUser3, user_input_methods[2], local_state); local_state->SetString(language_prefs::kPreferredKeyboardLayout, user_input_methods[2]); } void CheckGaiaKeyboard(); protected: std::vector<std::string> user_input_methods; }; void LoginUIKeyboardTestWithUsersAndOwner::CheckGaiaKeyboard() { std::vector<std::string> expected_input_methods; // kPreferredKeyboardLayout is now set to last focused POD. expected_input_methods.push_back(user_input_methods[0]); // Locale default input methods (the first one also is hardware IM). Append_en_US_InputMethods(&expected_input_methods); EXPECT_EQ(expected_input_methods, input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetActiveInputMethodIds()); } IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTestWithUsersAndOwner, PRE_CheckPODScreenKeyboard) { RegisterUser(kTestUser1); RegisterUser(kTestUser2); RegisterUser(kTestUser3); InitUserLRUInputMethod(); StartupUtils::MarkOobeCompleted(); } IN_PROC_BROWSER_TEST_F(LoginUIKeyboardTestWithUsersAndOwner, CheckPODScreenKeyboard) { js_checker().ExpectEQ("$('pod-row').pods.length", 3); std::vector<std::string> expected_input_methods; // Owner input method. expected_input_methods.push_back(user_input_methods[2]); // Locale default input methods (the first one also is hardware IM). Append_en_US_InputMethods(&expected_input_methods); // Active IM for the first user (active user POD). expected_input_methods.push_back(user_input_methods[0]); EXPECT_EQ(expected_input_methods, input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetActiveInputMethodIds()); // Switch to Gaia. js_checker().Evaluate("$('add-user-button').click()"); OobeScreenWaiter(OobeScreen::SCREEN_GAIA_SIGNIN).Wait(); CheckGaiaKeyboard(); // Switch back. js_checker().Evaluate("$('gaia-signin').cancel()"); OobeScreenWaiter(OobeScreen::SCREEN_ACCOUNT_PICKER).Wait(); EXPECT_EQ(expected_input_methods, input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetActiveInputMethodIds()); } } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
38ee073dc35957ed694a581005ef2bdfc2a8411e
c5ad94c5f44ea26bfcd67f0b88862b895fe965d2
/MIPSCompiler/Compiler.cpp
31acbf5d2752d2b8f57fa1fb6ef78fd77e450e8b
[]
no_license
Gongzq5/SYSU-Computer-Organization-And-Design
2540ecfe7f24983d04b643b0ae676c2f9b04da37
04f4eb160d0469382cb941b79af82ee466c49ab0
refs/heads/master
2020-03-19T12:18:09.227802
2018-07-09T01:20:50
2018-07-09T01:20:50
136,509,221
1
0
null
null
null
null
UTF-8
C++
false
false
5,988
cpp
/* * @Time 2018/06/05 16:33 * @Author Zequn Gong * * Compile MIPS code to binary code */ #include <stdio.h> #include <memory.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <map> using namespace std; std::string instruction; /* // // If you want single one, just change to use this map. // std::map<string, string> op2code = { // {"add", "000000"}, // {"sub", "000010"}, // {"addi", "000001"}, // {"or", "010010"}, // {"and", "010001"}, // {"ori", "010000"}, // {"sll", "011000"}, // {"slt", "100110"}, // {"slti", "011011"}, // {"beq", "110000"}, // {"bne", "110001"}, // {"sltiu", "100111"}, // {"sw", "100110"}, // {"lw", "100111"}, // {"bltz", "110110"}, // {"j", "111000"}, // {"jr", "111001"}, // {"jal", "111010"}, // {"halt", "111111"} // }; */ std::map<string, string> op2code = { {"add", "000000"}, {"sub", "000001"}, {"addi", "000010"}, {"or", "010000"}, {"and", "010001"}, {"ori", "010010"}, {"sll", "011000"}, {"slt", "100110"}, {"slti", "011011"}, {"bne", "110001"}, {"sltiu", "100111"}, {"sw", "110000"}, {"lw", "110001"}, {"beq", "110100"}, {"bltz", "110110"}, {"j", "111000"}, {"jr", "111001"}, {"jal", "111010"}, {"halt", "111111"} }; /* * Type introducation * 1: op rd rs rt * 2: op rt rs immediate * 3: op rd rt sa * 4: op rt immediate(rs) * 5: op rs rt immediate * 6: op rs immediate * 7: op addr * 8: op rs * 9: op null */ std::map<string, int> op2type = { {"add", 1}, {"sub", 1}, {"addi", 2}, {"or", 1}, {"and", 1}, {"ori", 2}, {"sll", 3}, {"slt", 1}, {"slti", 2}, {"sltiu", 2}, {"sw", 4}, {"lw", 4}, {"beq", 5}, {"bne", 5}, {"bltz", 6}, {"j", 7}, {"jr", 8}, {"jal", 7}, {"halt", 9} }; void trim_last_16_from_32 (char* dest, char* source) { int begin = 16; for (int i=begin; i<begin+16; i++) { dest[i-begin] = source[i]; } dest[16] = 0; return; } std::string convert() { std::string opCommand; std::cin >> opCommand; instruction = op2code[opCommand]; if (opCommand == "") { return "wrong"; } std::cerr << "[" << opCommand << "] over" << endl; int rs, rt, rd, sa, immediate; long long int addr; char tmps[6], tmpt[6], tmpd[6], tmpsa[6], tmpaddr[27], tmpimm_32[33]; char rss[6], rts[6], rds[6], sas[6], immediates[17], addrs[27], immediates_32[33]; int type = op2type[opCommand]; switch (type) { // 1: op rd rs rt case 1: scanf(" $%d , $%d , $%d", &rd, &rs, &rt); ltoa(rd, tmpd, 2); ltoa(rt, tmpt, 2); ltoa(rs, tmps, 2); sprintf(rss, "%05s", tmps); sprintf(rds, "%05s", tmpd); sprintf(rts, "%05s", tmpt); instruction = instruction + rss + rts + rds + "00000" + "000000"; break; // 2: op rt rs immediate case 2: scanf(" $%d , $%d , %d", &rt, &rs, &immediate); ltoa(rt, tmpt, 2); ltoa(rs, tmps, 2); ltoa(immediate, tmpimm_32, 2); sprintf(rts, "%05s", tmpt); sprintf(rss, "%05s", tmps); sprintf(immediates_32, "%032s", tmpimm_32); trim_last_16_from_32(immediates, immediates_32); instruction = instruction + rss + rts + immediates; break; // 3: op rd rt sa case 3: scanf(" $%d , $%d , %d", &rd, &rt, &sa); ltoa(rd, tmpd, 2); ltoa(rt, tmpt, 2); ltoa(sa, tmpsa, 2); sprintf(rds, "%05s", tmpd); sprintf(rts, "%05s", tmpt); sprintf(sas, "%05s", tmpsa); instruction = instruction + "00000" + rts + rds + sas + "000000"; break; // 4: op rt immediate(rs) case 4: scanf(" $%d , %d ( $%d )", &rt, &immediate, &rs); ltoa(rt, tmpt, 2); ltoa(immediate, tmpimm_32, 2); ltoa(rs, tmps, 2); sprintf(rts, "%05s", tmpt); sprintf(immediates_32, "%032s", tmpimm_32); trim_last_16_from_32(immediates, immediates_32); sprintf(rss, "%05s", tmps); instruction = instruction + rss + rts + immediates; break; // 5: op rs rt immediate case 5: scanf(" $%d , $%d , %d", &rs, &rt, &immediate); ltoa(rs, tmps, 2); ltoa(rt, tmpt, 2); ltoa(immediate, tmpimm_32, 2); sprintf(rss, "%05s", tmps); sprintf(rts, "%05s", tmpt); sprintf(immediates_32, "%032s", tmpimm_32); trim_last_16_from_32(immediates, immediates_32); instruction = instruction + rss + rts + immediates; break; // 6: op rs immediate case 6: scanf(" $%d , %d", &rs, &immediate); ltoa(rs, tmps, 2); ltoa(immediate, tmpimm_32, 2); sprintf(rss, "%05s", tmps); sprintf(immediates_32, "%016s", tmpimm_32); trim_last_16_from_32(immediates, immediates_32); instruction = instruction + rss + "00000" + immediates; break; // 7: op addr case 7: scanf("%x", &addr); addr /= 4; ltoa(addr, tmpaddr, 2); sprintf(addrs, "%026s", tmpaddr); instruction = instruction + addrs; break; // 8: op rs case 8: scanf(" $%d", &rs); ltoa(rs, tmps, 2); sprintf(rss, "%05s", tmps); instruction = instruction + rss + "00000" + "00000" + "00000" + "000000"; break; // 9: op null case 9: instruction = instruction + "00000000000000000000000000"; break; default: break; }; return instruction; } int main(void) { freopen("out.txt", "w", stdout); while (true) { if ("wrong" == convert()) { return 0; } cout << instruction << endl; } return 0; }
[ "765194873@qq.com" ]
765194873@qq.com
2e8005a997839cfa728fc00f6bc089f56ad2384e
16ce45e5ad8aead05730b118cef3be4523636ca3
/src/49. Group Anagrams/main.cpp
3b97b1fb125ca31d021ac1b83161dfd4c88c70b4
[ "MIT" ]
permissive
sheepduke/leetcode
9a23d3392310e0ba91cae8e9cb557d85cddc6ccc
7808b3370e4c3e19b2b0bc2bcee62f659906c3eb
refs/heads/master
2020-05-02T21:56:22.689703
2019-10-30T03:35:02
2019-10-30T03:35:02
178,235,715
0
0
null
null
null
null
UTF-8
C++
false
false
1,065
cpp
/* Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note: All inputs will be in lowercase. The order of your output does not matter. */ #include "../util/common.hpp" class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { auto hash_to_vector = map<string, vector<string>>(); for (auto str: strs) { auto hash = str; sort(begin(hash), end(hash)); if (hash_to_vector.find(hash) == end(hash_to_vector)) { hash_to_vector[hash] = vector<string>{str}; } else { hash_to_vector[hash].push_back(str); } } auto result = vector<vector<string>>(); for (auto pair: hash_to_vector) { result.push_back(pair.second); } return result; } }; int main() { Solution solution; auto input = vector<string>{ "eat", "tea", "tan", "ate", "nat", "bat" }; cout << solution.groupAnagrams(input) << endl; return 0; }
[ "sheepduke@gmail.com" ]
sheepduke@gmail.com
01610748b5c716a5ed3ca870dbe434abc0c2f4f0
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2755486_0/C++/Takuma/C.cpp
71fdb2b5eb59626e1d78df7c916092d99e2d3490
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
GB18030
C++
false
false
1,634
cpp
// C.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #define maxn ( 105 ) #define BASE ( 500 ) using namespace std; struct Tnode{ int day, west, east, s; }attack[ maxn ]; int wall[ 2005 ], M, N, day, Ni, Wi, Ei, Si, delta_d, delta_p, delta_s, now, testcase; bool cmp( Tnode a, Tnode b ){ return a.day<b.day; } int _tmain( int argc, _TCHAR* argv[ ] ){ freopen( "C-small-attempt0.in", "r", stdin ); freopen( "out.txt", "w", stdout ); scanf( "%d", &testcase ); for ( now=1;testcase--;now++ ){ scanf( "%d", &N ); printf( "Case #%d: ", now ); M=0; for ( int i=0;i<N;i++ ){ scanf( "%d%d%d%d%d%d%d%d", &day, &Ni, &Wi, &Ei, &Si, &delta_d, &delta_p, &delta_s ); for ( int j=0;j<Ni;j++ ){ attack[ M ].day=day; attack[ M ].west=Wi; attack[ M ].east=Ei; attack[ M ].s=Si; day+=delta_d; Wi+=delta_p; Ei+=delta_p; Si+=delta_s; M++; } } sort( attack, attack+M, cmp ); memset( wall, 0, sizeof( wall ) ); int res=0; for ( int i=0, prei=-1;i<M;i++ ){ bool ok=false; for ( int j=attack[ i ].west;j<attack[ i ].east && !ok;j++ ) if ( wall[ j+BASE ]<attack[ i ].s ) ok=true; if ( ok ) res++; if ( i==M-1 || attack[ i ].day!=attack[ i+1 ].day ){ for ( int j=prei+1;j<=i;j++ ){ for ( int k=attack[ j ].west;k<attack[ j ].east;k++ ) if ( wall[ k+BASE ]<attack[ j ].s ) wall[ k+BASE ]=attack[ j ].s; } prei=i; } } printf( "%d\n", res ); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
373dcdcddb1d1fa32b2095e20088a06a5b729804
b668dd9561e7cc31fd31471277cccb266bf8474a
/source/tetrixboard.cpp
67101ee7158e7405c0eb2987e05ad336851c363d
[]
no_license
wu-hua-guo/Myteris
968316860c5e4d7c089fbbdb0619862506376974
544e990cf3afcbd51c128ad7c38c498b597d1345
refs/heads/master
2020-03-22T13:44:42.055910
2018-07-09T14:49:44
2018-07-09T14:49:44
140,128,866
0
0
null
null
null
null
UTF-8
C++
false
false
8,644
cpp
#include <QtWidgets> #include "tetrixboard.h" class QDebug; //! [0] TetrixBoard::TetrixBoard(QWidget *parent) : QFrame(parent) { setFrameStyle(QFrame::Panel | QFrame::Sunken); setFocusPolicy(Qt::StrongFocus); isStarted = false; isPaused = false; clearBoard(); nextPiece.setRandomShape(); } //! [0] //! [1] void TetrixBoard::setNextPieceLabel(QLabel *label) { nextPieceLabel = label; } //! [1] //! [2] QSize TetrixBoard::sizeHint() const { QSize size=QSize(BoardWidth * 15 + frameWidth() * 2, BoardHeight * 15 + frameWidth() * 2); //qDebug()<<"sizeHint:"<<size; return size; } QSize TetrixBoard::minimumSizeHint() const //! [2] //! [3] { return QSize(BoardWidth * 5 + frameWidth() * 2, BoardHeight * 5 + frameWidth() * 2); } //! [3] //! [4] void TetrixBoard::start() { if (isPaused) return; isStarted = true; isWaitingAfterLine = false; numLinesRemoved = 0; numPiecesDropped = 0; score = 0; level = 1; clearBoard(); emit linesRemovedChanged(numLinesRemoved); emit scoreChanged(score); emit levelChanged(level); newPiece(); timer.start(timeoutTime(), this); } //! [4] //! [5] void TetrixBoard::pause() { if (!isStarted) return; isPaused = !isPaused; if (isPaused) { timer.stop(); } else { timer.start(timeoutTime(), this); } update(); //! [5] //! [6] } //! [6] //! [7] void TetrixBoard::paintEvent(QPaintEvent *event) { // static int i=0; //qDebug()<<tr("paintEvent %1").arg(i++); QFrame::paintEvent(event); QPainter painter(this); QRect rect = contentsRect(); //! [7] // if (isPaused) { // painter.drawText(rect, Qt::AlignCenter, tr("Pause")); // return; // } //! [8] int boardTop = rect.bottom() - BoardHeight*squareHeight(); for (int y = 0; y < BoardHeight; ++y) { for (int x = 0; x < BoardWidth; ++x) { TetrixShape shape = shapeAt(x, y); if (shape != NoShape) drawSquare(painter, rect.left() + x * squareWidth(), boardTop + y * squareHeight(), shape); } //! [8] //! [9] } //! [9] //! [10] if (curPiece.shape() != NoShape) { for (int i = 0; i < 4; ++i) { int x = curX + curPiece.x(i); int y = curY + curPiece.y(i); drawSquare(painter, rect.left() + x * squareWidth(), boardTop + y * squareHeight(), curPiece.shape()); } //! [10] //! [11] } //! [11] //! [12] } //! [12] //! [13] void TetrixBoard::keyPressEvent(QKeyEvent *event) { if (!isStarted || isPaused || curPiece.shape() == NoShape) { QFrame::keyPressEvent(event); return; } //! [13] //! [14] switch (event->key()) { case Qt::Key_Left: tryMove(curPiece, curX - 1, curY); break; case Qt::Key_A: tryMove(curPiece, curX - 1, curY); break; case Qt::Key_Right: tryMove(curPiece, curX + 1, curY); break; case Qt::Key_D: tryMove(curPiece, curX + 1, curY); break; case Qt::Key_Down: tryMove(curPiece.rotatedRight(), curX, curY); break; case Qt::Key_S: oneLineDown(); break; case Qt::Key_Up: tryMove(curPiece.rotatedLeft(), curX, curY); break; case Qt::Key_W: tryMove(curPiece.rotatedLeft(), curX, curY); break; case Qt::Key_Space: dropDown(); break; default: QFrame::keyPressEvent(event); } //! [14] } //! [15] void TetrixBoard::timerEvent(QTimerEvent *event) { if (event->timerId() == timer.timerId()) { if (isWaitingAfterLine) { isWaitingAfterLine = false; newPiece(); timer.start(timeoutTime(), this); } else { oneLineDown(); } } else { QFrame::timerEvent(event); //! [15] //! [16] } //! [16] //! [17] } //! [17] //! [18] void TetrixBoard::clearBoard() { for (int i = 0; i < BoardHeight * BoardWidth; ++i) board[i] = NoShape; } //! [18] //! [19] void TetrixBoard::dropDown() { int dropHeight = 0; int newY = curY; while (newY < BoardHeight) { if (!tryMove(curPiece, curX, newY + 1)) break; ++newY; ++dropHeight; } pieceDropped(dropHeight); //! [19] //! [20] } //! [20] //! [21] void TetrixBoard::oneLineDown() { if (!tryMove(curPiece, curX, curY + 1)) pieceDropped(0); } //! [21] //! [22] void TetrixBoard::pieceDropped(int dropHeight) { for (int i = 0; i < 4; ++i) { int x = curX + curPiece.x(i); int y = curY + curPiece.y(i); shapeAt(x, y) = curPiece.shape(); } ++numPiecesDropped; if (numPiecesDropped % 25 == 0) { ++level; timer.start(timeoutTime(), this); emit levelChanged(level); } score += dropHeight + 7; emit scoreChanged(score); removeFullLines(); if (!isWaitingAfterLine) newPiece(); //! [22] //! [23] } //! [23] //! [24] void TetrixBoard::removeFullLines() { int numFullLines = 0; for (int y = 0; y < BoardHeight; ++y) { bool lineIsFull = true; for (int x = 0; x < BoardWidth; ++x) { if (shapeAt(x, y) == NoShape) { lineIsFull = false; break; } } if (lineIsFull) { //! [24] //! [25] ++numFullLines; for (int k = y; k > 0; --k) { for (int x = 0; x < BoardWidth; ++x) shapeAt(x, k) = shapeAt(x, k - 1); } //! [25] //! [26] for (int x = 0; x < BoardWidth; ++x) shapeAt(x, 0) = NoShape; } //! [26] //! [27] } //! [27] //! [28] if (numFullLines > 0) { numLinesRemoved += numFullLines; score += 10 * numFullLines; emit linesRemovedChanged(numLinesRemoved); emit scoreChanged(score); timer.start(500, this); isWaitingAfterLine = true; curPiece.setShape(NoShape); update(); } //! [28] //! [29] } //! [29] //! [30] void TetrixBoard::newPiece() { curPiece = nextPiece; curX = BoardWidth / 2 -2; curY = -curPiece.minY(); qDebug()<<curY; if (!tryMove(curPiece, curX, curY)) { curPiece.setShape(NoShape); timer.stop(); isStarted = false; return; } nextPiece.setRandomShape(); showNextPiece(); //! [30] //! [31] } //! [31] //! [32] void TetrixBoard::showNextPiece() { if (!nextPieceLabel) return; int dx = nextPiece.maxX() - nextPiece.minX() + 1; int dy = nextPiece.maxY() - nextPiece.minY() + 1; QPixmap pixmap(dx * squareWidth(), dy * squareHeight()); QPainter painter(&pixmap); painter.fillRect(pixmap.rect(), nextPieceLabel->palette().background()); for (int i = 0; i < 4; ++i) { int x = nextPiece.x(i) - nextPiece.minX(); int y = nextPiece.y(i) - nextPiece.minY(); drawSquare(painter, x * squareWidth(), y * squareHeight(), nextPiece.shape()); } nextPieceLabel->setPixmap(pixmap); //! [32] //! [33] } //! [33] //! [34] bool TetrixBoard::tryMove(const TetrixPiece &newPiece, int newX, int newY) { for (int i = 0; i < 4; ++i) { int x = newX + newPiece.x(i); int y = newY + newPiece.y(i); //qDebug()<<x<<y; if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight) return false; if (shapeAt(x, y) != NoShape) return false; } //! [34] //! [35] curPiece = newPiece; curX = newX; curY = newY; update(); return true; } //! [35] //! [36] void TetrixBoard::drawSquare(QPainter &painter, int x, int y, TetrixShape shape) { static const QRgb colorTable[8] = { 0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00 }; QColor color = colorTable[int(shape)]; // !1 绘制一个边框宽度为1的矩形 painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2, color); painter.setPen(color.light()); painter.drawLine(x, y + squareHeight() - 1, x, y); painter.drawLine(x, y, x + squareWidth() - 1, y); painter.setPen(color.dark()); painter.drawLine(x + 1, y + squareHeight() - 1, x + squareWidth() - 1, y + squareHeight() - 1); painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1, x + squareWidth() - 1, y + 1); // !1 } //! [36]
[ "2206757071@qq.com" ]
2206757071@qq.com
f3ada1fdf961eefeddf365fd1fadc4c20c458450
b3cbf86f1704e0d62ca2fbb952a692a2de580c88
/2-2/cardMatch/cardmatch.cpp
e108efb08dbcefc7335faca8138b3973c7b8587a
[]
no_license
WoosungMichael/CSE
e343846c44db52089430a5b6e8d09fa59ba0ada9
937f0d366cd69bedc3aaf2b1cccefa08515ec124
refs/heads/master
2023-05-09T12:35:39.879861
2021-06-02T05:00:17
2021-06-02T05:00:17
327,325,348
1
0
null
null
null
null
UHC
C++
false
false
7,578
cpp
//2017112148 김우성 #include "Common.h" #include "P2017112148.h" P2017112148::P2017112148() //생성자 { for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { //가능한 모든 인덱스의 조합을 2차원 벡터를 이용하여 넣어준다. vector<int> v2; v2.push_back(i); v2.push_back(j); //size가 2인 v2벡터를 만들고 v.push_back(v2); //v에 v 벡터를 push_back해준다. } } } Point P2017112148::inputFirst() //첫번째 카드를 뽑을 때 어떤 카드를 뽑을지를 정하는 함수 { for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서 Point p(v[s][0], v[s][1]); //v[s][0],v[s][1]의 위치를 가지는 p객체 선언 if (isOpenSet()) {//아직 짝지어지지 않은 이미 오픈된 카드쌍이 있는 경우 if (myboard[v[s][0]][v[s][1]] == index + 1) {//아직 짝지어지지 않은 오픈된 값(index+1)을 가진 카드의 인덱스 [v[s][0]][v[s][1]]을 찾은 경우 Point p2(v[s][0], v[s][1]); //그 위치를 가지는 Point객체 p2를 선언 p_first = p2; //첫번째 선택에서 뽑은 카드의 위치로 p2를 저장 was_zero = false; //첫번째 카드를 뽑을 때 원래 오픈되어있던 카드를 뽑았음을 표시 return p2; //p2객체 반환 } } else { //아직 짝지어지지 않은 오픈된 카드쌍이 없는 경우 if (myboard[v[s][0]][v[s][1]] != 0) { //이미 오픈된 카드인 경우 continue; //반복문의 다음 인덱스로 돌아가도록 한다. } else { //아직 오픈되지 않은 카드인 경우 p_first = p; //첫번째 선택에서 뽑은 카드의 위치로 p를 저장 was_zero = true; //첫번째 카드를 뽑을 때 원래 오픈되어있지않던 카드를 뽑았음을 표시 return p; //p객체 반환 } }//아직 짝지어지지 않은 오픈된 카드쌍이 없는 경우, 이미 오픈된 카드를 먼저 뽑는 것 보다 아직 오픈 되지않은 카드를 먼저 오픈하는것이 효과적이다. 이는 첫번째 때, 아직 오픈 되지않은 카드를 뽑음으로서 두번째 카드를 뽑을 때 1장이라도 더 많은 오픈된 카드와 첫번째 카드를 비교해보고 뽑을 수 있기 때문이다. } } Point P2017112148::inputSecond() //두번째 카드를 뽑을 때 어떤 카드를 뽑을지를 정하는 함수 { if (was_zero == true) { //첫번째 카드를 뽑을 당시 뽑은 카드에 적힌 수를 몰랐던 경우 //isOpenSet이 falsed였던 경우 Point p(v[0][0], v[0][1]); //아래의 조건문을 모두 만족하지 않을 경우 반환할 v[0][0],v[0][1]의 위치를 가지는 p객체 선언 for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서 if (myboard[v[s][0]][v[s][1]] == myboard[p_first.getX()][p_first.getY()] && ((v[s][0] != p_first.getX()) || (v[s][1] != p_first.getY()))) { //첫번째 뽑은 카드와 같은 값을 가졌고 첫번째 뽑은 카드도 아닌 카드의 인덱스 [v[s][0]][v[s][1]]을 찾은 경우 Point p2(v[s][0],v[s][1]); //두번째 선택에서 뽑을 카드의 위치로 p를 저장 return p2; //p2객체 반환 } } for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서 if (myboard[v[s][0]][v[s][1]] == 0) { //아직 오픈되지 않은 카드인 경우 Point p2(v[s][0], v[s][1]); //이 위치를 두번째 선택에서 뽑을 카드의 위치로 p에 저장 return p2; //p2객체 반환 } else { //이미 오픈된 카드인 경우 continue; //반복문의 다음 인덱스로 돌아가도록 한다. } } return p; //p객체 반환 } else { //첫번째 카드를 뽑을 당시 뽑은 카드에 적힌 수를 알았던 경우 //isOpenSet이 true였던 경우 for (int s = 0; s < v.size(); s++) { //현재 아직 짝을 이루지 못한 가능한 모든 인덱스의 조합을 돌면서 if (myboard[v[s][0]][v[s][1]] == myboard[p_first.getX()][p_first.getY()] && ((v[s][0] != p_first.getX()) || (v[s][1] != p_first.getY()))) { //첫번째 뽑은 카드와 같은 값을 가졌고 이미 짝을 맞춘 카드도 아니고 첫번째 뽑은 카드도 아닌 카드의 인덱스 [v[s][0]][v[s][1]]을 찾은 경우 Point p2(v[s][0],v[s][1]); //이 위치를 두번째 선택에서 뽑을 카드의 위치로 p2에 저장 return p2; //p2객체 반환 } } } } void P2017112148::checkCardInfo(Point point, int card) //플레이어가 카드를 오픈했을 때, 이를 확인하고 수행할 작업을 행하는 함수 //카드의 값을 알게 되는 경우, 이를 카드 뒤집기에 활용할 수 있으므로 이를 저장해둔다. { if (myboard[point.getX()][point.getY()] == 0) { //선택되어 오픈된 카드가 이전까지 아직 오픈되지 않은 카드였던 경우 myboard[point.getX()][point.getY()] = card; //myboard의 해당 위치에 오픈된 카드의 값을 저장해준다. count[card - 1]++; //오픈된 카드의 값을 가지는 오픈되었지만 매치되지않은 카드 수를 1 증가시킨다. } } void P2017112148::matchedCard(Point p1, Point p2, int card) //플레이어가 한 턴에 오픈한 두 카드가 새롭게 짝을 이루게 되었을 때의 작업을 행하는 함수 //이미 짝을 찾은 카드는 다시 뽑지 않아야 더 이길 확률을 높일 수 있으므로 짝을 찾은 여부를 저장한다. { mymatched[p1.getX()][p1.getY()] = true; //myboard의 p1의 위치에 값을 이미 짝을 맞췄음을 나타내는 true를 저장한다. mymatched[p2.getX()][p2.getY()] = true; //myboard의 p2의 위치에 값을 이미 짝을 맞췄음을 나타내는 true를 저장한다. count[card - 1] -= 2; //오픈된 카드의 값을 가지는 오픈되었지만 매치되지않은 카드 수를 2 감소시킨다. (주어진 2장이 매치되었기때문에) for (int i = 0; i < v.size(); i++) { //현재 아직 짝을 이루진 못한 가능한 모든 인덱스의 조합을 가지는 벡터를 돌면서 if ((v[i][0] == p1.getX() && v[i][1] == p1.getY()) || (v[i][0] == p2.getX() && v[i][1] == p2.getY())) { //p1또는 p2의 인덱스 조합과 같은 값을 가지는 조합을 찾으면 v.erase(v.begin()+i); //더 이상 그 인덱스 조합은 짝을 이루지 못한 인덱스의 조합이 아니므로 해당하는 벡터를 지워준다. i--; //주어진 for문은 계속 돌아가야하는데 위에서 erase를 하면 erase된 뒤부분의 인덱스가 땡겨져 다시 지워진 바로 직후의 인덱스에 대해서는 검사가 이루어지지 않으므로 이를 검사해주기 위해 i--를 해준다. } } } bool P2017112148::isOpenSet() //이미 오픈된 카드들 중 아직 매치가 안된 카드쌍이 존재하는지를 반환하는 함수 //이 경우에는 가장 우선적으로 이러한 카드쌍을 뽑아야하므로 이 경우에 대해 확인해주는 함수를 작성하였다. { bool isOpenSet = false; //isOpenSet을 false로 초기화 for (int i = 0; i < LAST_CARD_NUMBER; i++) { //모든 count배열의 인덱스에 대해 if (count[i] >= 2) { //이미 오픈된 카드들 중 같은 값을 가지는 카드가 2장 이상인 경우 isOpenSet = true; //isOpenSet을 true로 변경 index = i; //count[i]가 2 이상이 되도록 하는 i의 값을 index에 저장 return isOpenSet; //isOpenSet의 true값 반환 } } return isOpenSet; //isOpenSet의 false값 반환 }
[ "woosung0420k@naver.com" ]
woosung0420k@naver.com
9c7f46fbe2f48dfd946d5f9ded8a91c8b1003304
79cb191be612b15d12c791381d290f256e3d5406
/Framework Praktikum 2/Matrix4.cpp
8680b6a6eb9096e623a68df2819acbc5167ddd03
[]
no_license
cr4ckl1n/GEMCAD-1
ccea1fe523549f94cde6d0d9d35bfe170dd3489d
935770d5e1dc3edc8819662ad506e1cdd5dffcec
refs/heads/master
2021-01-10T13:18:44.096448
2016-01-27T08:30:30
2016-01-27T08:30:30
47,255,637
0
3
null
2016-01-27T08:30:32
2015-12-02T11:04:20
C++
MacCentralEurope
C++
false
false
5,607
cpp
// ========================================================================= // // Authors: Matthias Bein // // mailto:matthias.bein@igd.fraunhofer.de // // // // GRIS - Graphisch Interaktive Systeme // // Technische Universitšt Darmstadt // // Fraunhoferstrasse 5 // // D-64283 Darmstadt, Germany // // // // Creation Date: 29.10.2013 // // ========================================================================= // #include "Matrix4.h" #include <stdio.h> // cout #include <iostream> // cout Matrix4f::Matrix4f() { for(unsigned int row = 0; row < 4; ++row) { for(unsigned int column = 0; column < 4; ++column) { if(row == column) values[row][column] = 1.0f; else values[row][column] = 0.0f; } } } Matrix4f::Matrix4f(float val) { for(unsigned int row = 0; row < 4; ++row) { for(unsigned int column = 0; column < 4; ++column) { values[row][column] = val; } } } Matrix4f Matrix4f::operator* (const Matrix4f& rightMatrix) const { // start with 0-matrix Matrix4f result(0.0f); for(int row =0 ; row < 4; row ++) { for( int col = 0 ; col < 4 ; col ++) { result.values[row][col] = this->values[row][0] * rightMatrix.values[0][col] +this->values[row][1] * rightMatrix.values[1][col] + this->values[row][2] * rightMatrix.values[2][col] + this->values[row][3] * rightMatrix.values[3][col]; Matrix4f test= Matrix4f::values[row][col]; // printf("%d", test); } } return result; } Vec4f Matrix4f::operator* (const Vec4f& vec) const { // start with 0-vector Vec4f result; for(int row =0 ; row < 4; row ++) { for( int col = 0 ; col < 4 ; col ++) { result[row] = this->values[row][0] * vec[0] +this->values[row][1] * vec[1] + this->values[row][2] * vec[2] + this->values[row][3] * vec[3]; } } return result; } Vec3f Matrix4f::operator*(const Vec3f& vec) const { Vec4f v4(vec.x, vec.y, vec.z, 1.0f); Vec4f result = *this * v4; result.homogenize(); return Vec3f(result.x, result.y, result.z); } std::ostream& operator<< (std::ostream& os, const Matrix4f& matrix) { os << matrix.values[0][0] << ", " << matrix.values[0][1] << ", " << matrix.values[0][2] << ", " << matrix.values[0][3] << std::endl << matrix.values[1][0] << ", " << matrix.values[1][1] << ", " << matrix.values[1][2] << ", " << matrix.values[1][3] << std::endl << matrix.values[2][0] << ", " << matrix.values[2][1] << ", " << matrix.values[2][2] << ", " << matrix.values[2][3] << std::endl << matrix.values[3][0] << ", " << matrix.values[3][1] << ", " << matrix.values[3][2] << ", " << matrix.values[3][3]; return os; } // ================================================== Matrix4f Matrix4f::rotationXMatrix(float angle) { Matrix4f result; result.values[1][1] = std::cosf(angle); result.values[1][2] = - std::sinf(angle); result.values[2][1] = std::sinf(angle); result.values[2][2] = std::cosf(angle); return result; } Matrix4f Matrix4f::rotationYMatrix(float angle) { Matrix4f result; result.values[0][0] = std::cosf(angle); result.values[0][2] = std::sinf(angle); result.values[2][0] = -std::sinf(angle); result.values[2][2] = std::cosf(angle); return result; } Matrix4f Matrix4f::rotationZMatrix(float angle) { Matrix4f result; result.values[0][0] = std::cosf(angle); result.values[0][1] = - std::sinf(angle); result.values[1][0] = std::sinf(angle); result.values[1][1] = std::cosf(angle); return result; } Matrix4f Matrix4f::scaleMatrix(float sx, float sy, float sz){ Matrix4f result; result.values[0][0] = sx; result.values[1][1] = sy; result.values[2][2] = sz; return result; } Matrix4f Matrix4f::translateMatrix(int dx, int dy, int dz){ Matrix4f result; result.values[0][3] = dx; result.values[1][3] = dy; result.values[2][3] = dz; return result; } Matrix4f Matrix4f::quaternion(double a, double b, double c, double d){ Matrix4f result; result.values[0][0] = (a*a) + (b*b) - (c*c) -(d*d); result.values[1][0] = 2.0f*((b*c) -(a*d)); result.values[2][0] = 2.0f*(b*d+a*c); result.values[0][1] = 2.0f*(b*c+a*d); result.values[1][1] = (a*a) - (b*b) + (c*c) - (d*d); result.values[2][1] = 2.0f*(c*d-a*b); result.values[0][2] = 2.0f*(b*d-a*c); result.values[1][2] = 2.0f*(c*d+a*b); result.values[2][2] = (a*a)-(b*b)-(c*c)+(d*d); return result; } Matrix4f Matrix4f::test_Multiplikation(){ Matrix4f a(1.0f); Matrix4f b(1.0f); float c=2.0f; for (int row=0 ; row < 4 ; row++){ for(int col=0; col < 4; col++){ a.values[row][col] = a.values[row][col] +c; b.values[row][col] = a.values[row][col] +(2.0f*c); } } std::cout << a << std::endl; std::cout << b << std::endl; Matrix4f result = a.operator*(b); std::cout << result << std::endl; return result; } Vec4f Matrix4f::test_vecMult(){ Matrix4f a(2.0f); Vec4f b; b[3] = 1.0f; b.x = 2.0f; b.y = 3.0f; b.z = 4.0f; std::cout << b << std::endl; std::cout << "\n" << std::endl; std::cout << a << std::endl; std::cout << "\n" << std::endl; Vec4f result = a.operator*(b); std::cout << result << std::endl; return result; } // ==================================================
[ "cr4kl1n@gmail.com" ]
cr4kl1n@gmail.com
d590a825873fd24da451812f74e35fee50807b98
f2609d00ba6e66f4bbd909c796d68361867a497e
/Player.cpp
ec03be1c8ff4bd692647cc67b372aa58759a0195
[]
no_license
filosmusic/BaseCode
e655c68520c8b66b436822ab79aefecfe88d5681
bbaa22823a1eaae5cfcce80a8afb7067986209f5
refs/heads/master
2021-01-14T08:50:09.930051
2015-11-28T20:54:10
2015-11-28T20:54:10
43,768,213
0
0
null
2015-10-06T17:56:43
2015-10-06T17:56:42
null
UTF-8
C++
false
false
3,538
cpp
#include "Player.h" #include "TextureManager.h" #include "game.h" #include "inputManager.h" #include <iostream> using namespace std; #define UP SDL_SCANCODE_W #define DOWN SDL_SCANCODE_S #define RIGHT SDL_SCANCODE_D #define LEFT SDL_SCANCODE_A Player::Player() { this->spriteCol = 0; this->spriteRow = 0; this->xDirection = 0; this->yDirection = 0; this->speed = 0; this->maxSpeed = 5; this->accel = 0.01; this->friction = 0.005; this->startMove = 0; } Player::~Player() { } GameObject * Player::create() { return new Player(); } void Player::load(LoaderParams* params) { this->setId(params->getId()); this->position.setX((float)params->getX()); this->position.setY((float)params->getY()); this->width = params->getWidth(); this->height = params->getHeight(); } void Player::draw() { TextureManager::getInstance()->drawFrame( this->textureID, this->position.getX(), this->position.getY(), this->width, this->height, this->spriteRow, this->spriteCol, Game::getInstance()->getRenderer() ); } void Player::update() { //SET SPEED if (xDirection != 0 || yDirection != 0) { //ACCELERATION if (startMove == 0) startMove = SDL_GetTicks(); speed += (accel - friction) * (SDL_GetTicks() - startMove); startMove = SDL_GetTicks(); if (speed > maxSpeed) speed = maxSpeed; } else { //DECELERATION if (startMove == 0) startMove = SDL_GetTicks(); speed -= friction * (SDL_GetTicks() - startMove); startMove = SDL_GetTicks(); if (speed < 0.0f) speed = 0.0f; else if (speed == 0.0f) startMove = 0.0f; } if (speed != 0) { //MOVEMENT X spriteCol = (int)((SDL_GetTicks() / 120) % nCols); if (xDirection > 0) { position += Vector2(speed, 0); spriteRow = 2; } else if (xDirection < 0) { position -= Vector2(speed, 0); spriteRow = 1; } //MOVEMENT Y if (yDirection > 0) { position += Vector2(0, speed); spriteRow = 0; } else if (yDirection < 0) { position -= Vector2(0, speed); spriteRow = 3; } //FIX POSITION if (position.getX() + (width / 2) >(SDL_GetWindowSurface(Game::getInstance()->getWindow())->w)) position.setX(SDL_GetWindowSurface(Game::getInstance()->getWindow())->w - (width / 2)); if (position.getX() < (width / 2)) position.setX((width / 2)); if (position.getY() + (height / 2) > (SDL_GetWindowSurface(Game::getInstance()->getWindow())->h)) position.setY(SDL_GetWindowSurface(Game::getInstance()->getWindow())->h - (height / 2)); if (position.getY() < (height / 2)) position.setY((height / 2)); } else spriteCol = 0; } void Player::handleEvents(SDL_Event e) { InputManager* input = InputManager::getInstance(); //X AXIS if (input->isKeyPressed(LEFT) || input->isKeyPressed(RIGHT)) { if (input->isKeyPressed(LEFT)) xDirection = -1; if (input->isKeyPressed(RIGHT)) xDirection = 1; } else xDirection = 0; //Y AXIS if (input->isKeyPressed(DOWN) || input->isKeyPressed(UP)) { if (input->isKeyPressed(DOWN)) yDirection = 1; if (input->isKeyPressed(UP)) yDirection = -1; } else yDirection = 0; } void Player::clean() { } void Player::setTexture(std::string textureID, std::string texturePath, int nCols, int nRows) { this->textureID = textureID; this->texturePath = texturePath; this->nCols = nCols; this->nRows = nRows; } void Player::setTexture(std::string textureID, int nCols, int nRows) { this->textureID = textureID; this->nCols = nCols; this->nRows = nRows; } std::string Player::getTextureId() { return textureID; } std::string Player::getTexturePath() { return texturePath; }
[ "filosmusic@hotmail.com" ]
filosmusic@hotmail.com
6fa81dd5da8e06749cf2e2768cc28834c18bdbb8
d6437d847b7e1298d4d3fe61a5c3b84cd3dd504b
/dstreader/src/THB1D.cxx
0aa8e28665eee6ddd8aaa04ddfc845744e42160e
[]
no_license
adamjaro/star-upc
607c92edd3200687c31689552a238e16d742407e
b858f2ca09f90710ce18145debba638672f4a8c4
refs/heads/master
2023-03-15T18:00:29.818523
2023-03-10T23:16:36
2023-03-10T23:16:36
140,722,696
0
0
null
null
null
null
UTF-8
C++
false
false
4,652
cxx
//c++ headers #include <iostream> #include <sstream> #include <iomanip> #include <vector> #include <string> //ROOT headers #include "TMath.h" //local headers #include "THB1D.h" using namespace std; //_____________________________________________________________________________ THB1D::THB1D() { //cout << "THB1D" << endl; fHeight = 30; SetHeight(fHeight); fLeftMarg = 9; fTotHeight=0; fDigLines.reserve(10); }//THB1D //_____________________________________________________________________________ THB1D::THB1D(const char *name, const char *title, Int_t nbins, Double_t xmin, Double_t xmax): TH1D(name, title, nbins, xmin, xmax) { fHeight = 30; SetHeight(fHeight); fLeftMarg = 9; fTotHeight=0; fDigLines.reserve(10); fLogy = kFALSE; }//THB1D //_____________________________________________________________________________ THB1D::~THB1D() { //cout << "~THB1D" << endl; }//~THB1D //_____________________________________________________________________________ void THB1D::SetHeight(Int_t h) { fHeight = h; fYLabels.clear(); fYLabels.reserve(fHeight); fHistLines.clear(); fHistLines.reserve(fHeight); }//SetHeight //_____________________________________________________________________________ ostream& operator<<(std::ostream& os, THB1D& hx) { //Y axis labels Int_t lyval=0; Int_t yunit = 1; Int_t ytick = (Int_t) ceil( hx.GetMaximum()/hx.fHeight/yunit ); ytick *= yunit; for(Int_t i=0; i<hx.fHeight; i++) { hx.fYLabels.push_back(string("")); } for(vector<string>::iterator it = hx.fYLabels.begin(); it != hx.fYLabels.end(); it++) { lyval += ytick; stringstream st; st << lyval; *it = st.str(); } //fill histogram representation strings Int_t yprev=0; Int_t nbins = hx.GetNbinsX(); for(Int_t i=0; i<hx.fHeight; i++) { hx.fHistLines.push_back(string(nbins, ' ')); } for(Int_t ibin=1; ibin <= nbins; ibin++) { if( ((Int_t) hx.GetBinContent(ibin)) == 0 ) continue; Int_t ypos = (Int_t) hx.GetBinContent(ibin)/ytick; if( ypos >= hx.fHeight ) { ypos = hx.fHeight-1; } hx.fHistLines[ypos].replace(ibin-1, 1, "-"); if( ibin == 1 ) { yprev = ypos; continue; } if( ypos > yprev ) { for(Int_t yc = yprev; yc < ypos; yc++) { hx.fHistLines[yc].replace(ibin-1, 1, "I"); } } if( yprev > ypos ) { for(Int_t yc = ypos; yc < yprev; yc++) { hx.fHistLines[yc].replace(ibin-2, 1, "I"); } } yprev = ypos; } //bin content Int_t maxdig = (Int_t)( log10(hx.GetMaximum()) + 1 ); for(Int_t i=0; i<maxdig; i++) { hx.fDigLines.push_back(string(nbins, ' ')); } for(Int_t ibin=1; ibin <= nbins; ibin++) { Int_t cnt = (Int_t) hx.GetBinContent(ibin); stringstream st; st.width(maxdig); st.fill('_'); st << right << cnt; string scnt( st.str() ); string sdig; for(Int_t idig=0; idig<maxdig; idig++) { sdig = scnt[idig]; if( sdig == "_" ) continue; hx.fDigLines[idig].replace(ibin-1, 1, sdig); } } //print the histogram Int_t toth = hx.fTotHeight; Int_t digmarg = maxdig + 1; Int_t ilin = hx.fHeight-1; os << endl; toth--; for(vector<string>::reverse_iterator it = hx.fYLabels.rbegin(); it != hx.fYLabels.rend(); it++) { os.width(hx.fLeftMarg); os << right << *it; os.width(digmarg); os << " "; os.width(nbins+2); os << hx.fHistLines[ilin--] << endl; toth--; } os << endl; toth--; for(Int_t idig=0; idig<maxdig; idig++) { os.width(hx.fLeftMarg); if( idig==0 ) { os << "CONTENTS"; } else { os << " "; } os.width(digmarg); //os << " "; os << pow(10,maxdig-idig-1); os.width(nbins+2); os << hx.fDigLines[idig] << endl; toth--; } os << endl; toth--; //entries, overflow and underflow os.width(hx.fLeftMarg); os << "ENTRIES" << " = "; os.width(9); os << left << hx.GetEntries(); os << "UNDERFLOW = "; os.width(4); os << hx.GetBinContent(0); os << " OVERFLOW = "; os << hx.GetBinContent(nbins+1); os << endl; toth--; os << endl; toth--; while( toth-- > 0 ) { os << endl;// toth--; } //os << "size: " << hx.fHistLines.size() << endl; //os << "capacity: " << hx.fHistLines.capacity() << endl; //clean-up hx.fYLabels.clear(); hx.fHistLines.clear(); hx.fDigLines.clear(); //os << "size: " << hx.fHistLines.size() << endl; //os << "capacity: " << hx.fHistLines.capacity() << endl; //os << "ftoth: " << hx.fTotHeight << endl; //os << "toth: " << toth; //os << "ytick: " << ytick; return os; }
[ "jaroslav.adam@cern.ch" ]
jaroslav.adam@cern.ch
10a05799dac0686ccc5d60d0f57064e9cec97120
00c018a0d1a98c617d23ad84ea3097796d6eb772
/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h
c75aae900c003c952697f6fb41a67107af00c34b
[ "BSD-3-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0" ]
permissive
Ambyjkl/chromium
14ea14729df5e6ecdfbe5c996855c73740b5304f
23b2a91ba2010775480846cf8df64aeb7dba3db3
refs/heads/master
2023-03-10T21:18:50.899286
2019-11-22T02:46:17
2019-11-22T02:46:17
223,312,529
0
0
BSD-3-Clause
2019-11-22T03:04:16
2019-11-22T03:04:14
null
UTF-8
C++
false
false
11,376
h
// Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENTATION_UTILS_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENTATION_UTILS_H_ #include "third_party/blink/renderer/core/layout/ng/geometry/ng_box_strut.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_break_token.h" #include "third_party/blink/renderer/core/layout/ng/ng_block_node.h" #include "third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h" #include "third_party/blink/renderer/core/layout/ng/ng_constraint_space.h" #include "third_party/blink/renderer/core/layout/ng/ng_physical_container_fragment.h" #include "third_party/blink/renderer/core/style/computed_style_constants.h" #include "third_party/blink/renderer/platform/geometry/layout_unit.h" namespace blink { class NGLayoutResult; // Join two adjacent break values specified on break-before and/or break- // after. avoid* values win over auto values, and forced break values win over // avoid* values. |first_value| is specified on an element earlier in the flow // than |second_value|. This method is used at class A break points [1], to join // the values of the previous break-after and the next break-before, to figure // out whether we may, must, or should not break at that point. It is also used // when propagating break-before values from first children and break-after // values on last children to their container. // // [1] https://drafts.csswg.org/css-break/#possible-breaks EBreakBetween JoinFragmentainerBreakValues(EBreakBetween first_value, EBreakBetween second_value); // Return true if the specified break value has a forced break effect in the // current fragmentation context. bool IsForcedBreakValue(const NGConstraintSpace&, EBreakBetween); // Return true if the specified break value means that we should avoid breaking, // given the current fragmentation context. template <typename Property> bool IsAvoidBreakValue(const NGConstraintSpace&, Property); // Return true if we're resuming layout after a previous break. inline bool IsResumingLayout(const NGBlockBreakToken* token) { return token && !token->IsBreakBefore(); } // Calculate the final "break-between" value at a class A or C breakpoint. This // is the combination of all break-before and break-after values that met at the // breakpoint. EBreakBetween CalculateBreakBetweenValue(NGLayoutInputNode child, const NGLayoutResult&, const NGBoxFragmentBuilder&); // Calculate the appeal of breaking before this child. NGBreakAppeal CalculateBreakAppealBefore(const NGConstraintSpace&, NGLayoutInputNode child, const NGLayoutResult&, const NGBoxFragmentBuilder&, bool has_container_separation); // Calculate the appeal of breaking inside this child. NGBreakAppeal CalculateBreakAppealInside(const NGConstraintSpace& space, NGBlockNode child, const NGLayoutResult&); // Return the block space that was available in the current fragmentainer at the // start of the current block formatting context. Note that if the start of the // current block formatting context is in a previous fragmentainer, the size of // the current fragmentainer is returned instead. inline LayoutUnit FragmentainerSpaceAtBfcStart(const NGConstraintSpace& space) { DCHECK(space.HasKnownFragmentainerBlockSize()); return space.FragmentainerBlockSize() - space.FragmentainerOffsetAtBfc(); } // Adjust a box strut (margins, borders, scrollbars, and/or padding) to take // fragmentation into account. Leading block margin, border, scrollbar or // padding should only take up space in the first fragment generated from a // node. inline void AdjustForFragmentation(const NGBlockBreakToken* break_token, NGBoxStrut* box_strut) { if (LIKELY(!break_token)) return; if (break_token->IsBreakBefore()) return; box_strut->block_start = LayoutUnit(); } // Set up a child's constraint space builder for block fragmentation. The child // participates in the same fragmentation context as parent_space. If the child // establishes a new formatting context, |fragmentainer_offset_delta| must be // set to the offset from the parent block formatting context, or, if the parent // formatting context starts in a previous fragmentainer; the offset from the // current fragmentainer block-start. void SetupFragmentation(const NGConstraintSpace& parent_space, LayoutUnit fragmentainer_offset_delta, NGConstraintSpaceBuilder*, bool is_new_fc); // Write fragmentation information to the fragment builder after layout. void FinishFragmentation(const NGConstraintSpace&, LayoutUnit block_size, LayoutUnit intrinsic_block_size, LayoutUnit previously_consumed_block_size, LayoutUnit space_left, NGBoxFragmentBuilder*); // Outcome of considering (and possibly attempting) breaking before a child. enum class NGBreakStatus { // Continue layout. No break was inserted before the child (but there may be // a break inside). kContinue, // A break was inserted before the child. Discard the child fragment and // finish layout of the container. If there was a break inside the child, it // will be discarded along with the child fragment. kBrokeBefore, // The child couldn't fit here, but no break was inserted before the child, // as it was an unappealing place to break, and we have a better earlier // breakpoint. We now need to abort the current layout, and go back and // re-layout to said earlier breakpoint. kNeedsEarlierBreak }; // Insert a fragmentainer break before the child if necessary. In that case, the // previous in-flow position will be updated, we'll return |kBrokeBefore|. If we // don't break inside, we'll consider the appeal of doing so anyway (and store // it as the most appealing break point so far if that's the case), since we // might have to go back and break here. Return |kContinue| if we're to continue // laying out. If |kNeedsEarlierBreak| is returned, it means that we ran out of // space, but shouldn't break before the child, but rather abort layout, and // re-layout to a previously found good breakpoint. If // |has_container_separation| is true, it means that we're at a valid // breakpoint. We obviously prefer valid breakpoints, but sometimes we need to // break at undesirable locations. Class A breakpoints occur between block // siblings. Class B breakpoints between line boxes. Both these breakpoint // classes imply that we're already past the first in-flow child in the // container, but there's also another way of achieving container separation: // class C breakpoints. Those occur if there's a positive gap between the // block-start content edge of the container and the block-start margin edge of // the first in-flow child. https://www.w3.org/TR/css-break-3/#possible-breaks NGBreakStatus BreakBeforeChildIfNeeded(const NGConstraintSpace&, NGLayoutInputNode child, const NGLayoutResult&, LayoutUnit fragmentainer_block_offset, bool has_container_separation, NGBoxFragmentBuilder*); // Insert a break before the child, and propagate space shortage if needed. void BreakBeforeChild(const NGConstraintSpace&, NGLayoutInputNode child, const NGLayoutResult&, LayoutUnit fragmentainer_block_offset, NGBreakAppeal, bool is_forced_break, NGBoxFragmentBuilder*); // Propagate the block-size of unbreakable content. This is used to inflate the // initial minimal column block-size when balancing columns, before we calculate // a tentative (or final) column block-size. Unbreakable content will actually // fragment if the columns aren't large enough, and we want to prevent that, if // possible. inline void PropagateUnbreakableBlockSize(LayoutUnit block_size, LayoutUnit fragmentainer_block_offset, NGBoxFragmentBuilder* builder) { // Whatever is before the block-start of the fragmentainer isn't considered to // intersect with the fragmentainer, so subtract it (by adding the negative // offset). if (fragmentainer_block_offset < LayoutUnit()) block_size += fragmentainer_block_offset; builder->PropagateTallestUnbreakableBlockSize(block_size); } // Propagate space shortage to the builder and beyond, if appropriate. This is // something we do during column balancing, when we already have a tentative // column block-size, as a means to calculate by how much we need to stretch the // columns to make everything fit. void PropagateSpaceShortage(const NGConstraintSpace&, const NGLayoutResult&, LayoutUnit fragmentainer_block_offset, NGBoxFragmentBuilder*); // Move past the breakpoint before the child, if possible, and return true. Also // update the appeal of breaking before or inside the child (if we're not going // to break before it). If false is returned, it means that we need to break // before the child (or even earlier). bool MovePastBreakpoint(const NGConstraintSpace& space, NGLayoutInputNode child, const NGLayoutResult& layout_result, LayoutUnit fragmentainer_block_offset, NGBreakAppeal appeal_before, NGBoxFragmentBuilder* builder); // If the appeal of breaking before or inside the child is the same or higher // than any previous breakpoint we've found, set a new breakpoint in the // builder, and update appeal accordingly. void UpdateEarlyBreakAtBlockChild(const NGConstraintSpace&, NGBlockNode child, const NGLayoutResult&, NGBreakAppeal appeal_before, NGBoxFragmentBuilder*); // Attempt to insert a soft break before the child, and return true if we did. // If false is returned, it means that the desired breakpoint is earlier in the // container, and that we need to abort and re-layout to that breakpoint. bool AttemptSoftBreak(const NGConstraintSpace&, NGLayoutInputNode child, const NGLayoutResult&, LayoutUnit fragmentainer_block_offset, NGBreakAppeal appeal_before, NGBoxFragmentBuilder*); } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_FRAGMENTATION_UTILS_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a8024bdf919b025fc735a6547e1bbdb688593e0e
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/A/B/D/B/C/AABDBC.h
229083dea784fb12643b1db83dcdddff8b752393
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
67
h
#ifndef AABDBC_H namespace AABDBC { std::string run(); } #endif
[ "nakhyun@devsisters.com" ]
nakhyun@devsisters.com
5260027aa62ddbdf628d6155fbd42137e23b243c
401cc62accb8f5630fe6531cf8faf911e4ff6dae
/Utilities.cpp
2f70af973840bc2c9cc5a02d19c3bba149eb2692
[ "MIT" ]
permissive
soulhez/VkColors
c2f7926548b2b99f22a6d040690a31bdff30ed12
98acef13fb990311e7185af1195e58984e86238f
refs/heads/master
2020-12-11T04:55:28.756081
2019-05-22T21:35:57
2019-05-22T21:35:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
936
cpp
#include "Utilities.h" #include <fstream> #include <stdexcept> std::vector<char> loadFile(const std::string& path) { std::ifstream file = std::ifstream(path, std::ios::binary | std::ios::ate); if (!file) throw std::runtime_error("Could not open file"); std::vector<char> result; result.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(result.data(), result.size()); return result; } vk::ShaderModule loadShader(vk::Device& device, const std::string& path) { std::vector<char> data = loadFile(path); vk::ShaderModuleCreateInfo info = {}; info.code = std::move(data); return vk::ShaderModule(device, info); } size_t align(size_t ptr, size_t align) { size_t unalign = ptr % align; if (unalign != 0) { return ptr + (align - unalign); } else { return ptr; } } int32_t length2(glm::ivec3 v) { return v.x * v.x + v.y * v.y + v.z * v.z; }
[ "vazgriz@gmail.com" ]
vazgriz@gmail.com
a14029da149a281b32e591384ddf3f34ff744177
168c0dca487228f7682febfef1aaafe87e0006aa
/03/ex02/FragTrap.cpp
155df2b4fd78fdc6212b057b6411c5ba232b17c2
[]
no_license
yaksaer/42-CPP-Module
d22f50e35c8cac8d41ccee0691e3670719086ce8
e1faddb142ef00eb0aa54f1cff4d40b63f9f521e
refs/heads/master
2022-03-29T17:22:27.363929
2020-01-10T17:45:47
2020-01-10T17:45:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,614
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* FragTrap.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ncolomer <ncolomer@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/18 17:00:28 by ncolomer #+# #+# */ /* Updated: 2019/12/27 14:23:22 by ncolomer ### ########.fr */ /* */ /* ************************************************************************** */ #include "FragTrap.hpp" std::string FragTrap::quotes[FragTrap::nbrQuotes] = { "Take that!", "Get off my lawn!", "Coffee? Black... like my soul.", "I am Fire, I am Death!", "Lightening! Kukachow!" }; FragTrap::FragTrap(std::string const &name): ClapTrap(name) { std::cout << this->name << ": Recompiling my combat code !" << std::endl; this->meleeAttackDamage = 30; this->rangedAttackDamage = 20; this->armorDamageReduction = 5; } FragTrap::FragTrap(FragTrap const &other): ClapTrap(other.name) { std::cout << this->name << ": Recompiling my combat code !" << std::endl; ClapTrap::copy(other); } FragTrap::~FragTrap() { std::cout << this->name << ": Argh arghargh death gurgle gurglegurgle urgh... death." << std::endl; } FragTrap &FragTrap::operator=(FragTrap const &other) { ClapTrap::copy(other); return (*this); } void FragTrap::meleeAttack(std::string const &target) { std::cout << this->name << " attacks " << target << " at melee, causing " << this->meleeAttackDamage << " points of damage!" << std::endl; } void FragTrap::rangedAttack(std::string const &target) { std::cout << this->name << " attacks " << target << " at range, causing " << this->rangedAttackDamage << " points of damage!" << std::endl; } void FragTrap::vaulthunter_dot_exe(std::string const &target) { if (this->energyPoints >= 25) { this->energyPoints -= 25; std::cout << this->name << ": " << FragTrap::quotes[rand() % FragTrap::nbrQuotes] << std::endl << this->name << " attacks " << target << " for " << ((rand() % this->meleeAttackDamage) + 1) << " points of damage!" << std::endl; } else { std::cout << "FR4G-TP " << this->name << " is out of energy!" << std::endl; } }
[ "ncolomer@e2r2p4.42.fr" ]
ncolomer@e2r2p4.42.fr
7488e4cb87fefd3c5b39f32a47a38b45f2fd63b3
5849b70aac97193a486155c59e58b34a3fdab20f
/Terrain.h
2517bed0464e789d952eed8fb4cd174e80a9cda6
[]
no_license
widavies/5607-Final
5feb27da89a5ce207081a14113e49bf417b7e25e
1d939cac0eb4a35c25e59e46b0256b410e3bfaaa
refs/heads/master
2023-04-19T14:39:03.154505
2021-05-08T05:51:28
2021-05-08T05:51:28
361,471,638
1
0
null
null
null
null
UTF-8
C++
false
false
647
h
#pragma once #include "RawModel.h" #include "ModelTexture.h" #include "ModelLoader.h" #define SIZE 800 #define VERTEX_COUNT 128 class Terrain { public: Terrain(int gridX, int gridZ, ModelLoader& loader, ModelTexture* texture) : _texture(texture) { _x = gridX * SIZE; _z = gridZ * SIZE; _model = generateTerrain(loader); } RawModel& getModel() { return _model; } ModelTexture* getTexture() { return _texture; } float getX() { return _x; } float getZ() { return _z; } private: float _x, _z; RawModel _model; ModelTexture* _texture; RawModel generateTerrain(ModelLoader& loader); };
[ "wdavies973@gmail.com" ]
wdavies973@gmail.com
20f100bd9a27835ed617f1331c7468df503cf4e9
d377590bb4e636ab642e748ca221bb9bd9b83a81
/sessio6/ex3/MyGLWidget.h
b0ea54b6ff26a0ddc2b9590d6dff5caf0ea2ed86
[]
no_license
ArnauRamon/FIB-IDI-Labs
f39e0b0f57fcb34492827a7c2e7b5da56c50c7d0
b2946ca9092d6e03398970a80f1f722d2ab153a6
refs/heads/master
2022-03-11T09:40:00.074707
2019-11-16T16:25:06
2019-11-16T16:25:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,690
h
#define GLM_FORCE_RADIANS #include <QOpenGLFunctions_3_3_Core> #include <QOpenGLWidget> #include <QOpenGLShader> #include <QOpenGLShaderProgram> #include <QKeyEvent> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "model.h" class MyGLWidget : public QOpenGLWidget, protected QOpenGLFunctions_3_3_Core { Q_OBJECT public: MyGLWidget (QWidget *parent=0); ~MyGLWidget (); protected: // initializeGL - Aqui incluim les inicialitzacions del contexte grafic. virtual void initializeGL ( ); // paintGL - Mètode cridat cada cop que cal refrescar la finestra. // Tot el que es dibuixa es dibuixa aqui. virtual void paintGL ( ); // resizeGL - És cridat quan canvia la mida del widget virtual void resizeGL (int width, int height); // keyPressEvent - Es cridat quan es prem una tecla virtual void keyPressEvent (QKeyEvent *event); private: void createBuffers (); void carregaShaders (); void modelTransform (); // -------------------------------- // ----- LES MEVES FUNCIONS ------- // -------------------------------- void projectTransform(); void viewTransform(); void iniCamera(); void carregarModel(); void pintaHomer(); void pintaTerra(); void carregaTerra(); void modelTransformTerra(); // Sessio 5 void calculaCapsaContenidoraHomer(); void calculaCentreRadi(); void calculaCapsaContenidoraPatricio(); void carregarPatricio(); void pintaPatricio(); void mousePressEvent (QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *e); typedef enum {NONE, ROTATE} InteractiveAction; InteractiveAction DoingInteractive; // Sessio 6 void modelTransformPatricio2(); void pintaPatricio2(); void calculaCapsaEscena(); void calculaCentreRadiEscena(); GLuint projLoc, viewLoc; glm::vec3 VRP, OBS, UP; float ra, zNear, zFar, FOV; float radi, radiEscena; glm::vec3 modelMinim, modelMaxim, centre, escenaMaxim, escenaMinim, centreEscena; Model homer; Model patricio; GLuint VAOhomer, VBOhomerVertex, VBOhomerMaterial; GLuint VAOpatricio, VBOpatricioVertex, VBOpatricioMaterial; float antigaX, antigaY, rotaX, rotaY; float rotacio; GLuint VAOterra, VBOterraVertex, VBOterraColor; // -------------------------------- // attribute locations GLuint vertexLoc, colorLoc; // uniform locations GLuint transLoc; // VAO i VBO names //GLuint VAO_Casa, VBO_CasaPos, VBO_CasaCol; // Program QOpenGLShaderProgram *program; // Internal vars float scale; glm::vec3 pos; };
[ "ana.gabriela.mestre@est.fib.upc.edu" ]
ana.gabriela.mestre@est.fib.upc.edu
e927b31f3f5f82fa4202f157ee94bef9a06d025c
46bc6200b2e8e060f5e319ac8e2d6701fdf38793
/Koramu/ScriptManager.h
6432716915fe6f1beffda3a354e84cb47b9d0ccd
[]
no_license
ariogato/Koramu
31937a01e53bab8f6cae5c4b14e32d5c135f7326
55502dd61cdb434c7364f1a03105ccaa62247123
refs/heads/master
2021-11-10T20:23:13.789728
2021-11-08T15:37:31
2021-11-08T15:37:31
74,519,918
4
0
null
null
null
null
ISO-8859-1
C++
false
false
1,844
h
#pragma once #include <string> #include <map> #include "Script.h" namespace LuaRegistrations { class BaseLuaRegistration; } /* Dies ist eine Singleton Klasse, die nach dem Vorbild des TextureManagers alle Lua Skripte * mit den dazugehörigen Methoden, Tabellen, etc. organisiert. * über den ScriptManager können andere Klassen auf Lua Methoden zugreifen */ class ScriptManager { private: ScriptManager(); // Konstruktor ~ScriptManager(); // Destruktor bool m_isInit; // Zeigt an, ob init() bereits aufgerufen wurde lua_State* m_pLuaState; // In diesem Member ist praktisch alles gespeichert, das mit der Kommunikation mit Lua zu tun hat std::map<std::string, Script*>* m_pScriptMap; // Dictionary, in dem jeder ID ein Script zugeordnet wird std::vector<LuaRegistrations::BaseLuaRegistration*> m_registrations; // Alle Funktionen, Variablen, etc., die an Lua weiterzugeben sind // Wichtig für Singleton static ScriptManager* s_pInstance; public: bool init(); // Initialisiert all das, was für Lua gebraucht wird (i.e. luaL_newstate(), etc.) Script& getScriptById(std::string id) const; // Gibt das der übergebenen id zugehörigen Script zurück void removeScriptFromMap(std::string id); // Entfernt ein Skript (die Lua Referenz & das Objekt) void callFunction(const char* table, const char* func); // Ruft eine Funktion 'func' aus der globalen Tabelle 'table' auf void addRegistration(LuaRegistrations::BaseLuaRegistration* reg); // Fügt dem Vektor aus Registrierungen ein weiteres Element hinzu // getter-Funktionen lua_State* getLuaState() { return m_pLuaState; } // Wichtig für Singleton static ScriptManager* Instance(); static void destroy(); }; typedef ScriptManager TheScriptManager;
[ "ario2000.ad@gmail.com" ]
ario2000.ad@gmail.com
5a496d0bd1d3b569c0acac032cc04486137d4598
ac8e6ecd711e2c4d8ec12435a32d53d57f14f875
/C4BoardPartWidget.hpp
c61b9c1c78a475a3feb0d11cc3a06d12c7e28b02
[]
no_license
starring94/connect4
1de5bb725b535d8286ac4f9941dc8545d1673012
7e0b42187a2650efb2c85e7cb8b3a0f3df4772a3
refs/heads/master
2023-04-29T12:29:28.940934
2021-05-17T21:52:21
2021-05-17T21:52:21
363,424,119
0
0
null
null
null
null
UTF-8
C++
false
false
648
hpp
#ifndef C4BOARDPARTWIDGET_HPP_INCLUDED #define C4BOARDPARTWIDGET_HPP_INCLUDED #include "BasicWidget.hpp" #include "C4PieceWidget.hpp" class C4PieceWidget; class C4BoardPartWidget : public BasicWidget { protected: int m_radius; int m_relativePositionX; int m_relativePositionY; public: C4BoardPartWidget(window* parent, int x, int y, int partSize); virtual void handleWidgetEvent(genv::event event); //virtual bool isMouseInside(Mouse &mouse); virtual void drawWidget(); virtual std::string getValues(); void updateRelativePositionFromPiece(C4PieceWidget* widget); }; #endif // C4BOARDPARTWIDGET_HPP_INCLUDED
[ "kovinor123@gmail.com" ]
kovinor123@gmail.com
7589d43a7b791287c6505d22fb04531097645f27
83ed1e2f176133c03a5f6dfa504b8df15ae71efb
/c/DMD/DMD10/Variable_r_ext/txt2txt.cpp
97dc75deb9d9109340dc85d80c2aada4a6021394
[]
no_license
jmborr/code
319db14f28e1dea27f9fc703be629f171e6bd95f
32720b57699bf01803367566cdc5fff2b6bce810
refs/heads/master
2022-03-09T16:11:07.455402
2019-10-28T15:03:01
2019-10-28T15:03:01
23,627,627
0
0
null
null
null
null
UTF-8
C++
false
false
59,752
cpp
#include "pseudoAA.h" #include "pseudoPep.h" #include "PDBLib.h" #include "random.h" #include "pseudoTXT.h" #include <cstring> using namespace std; int isKeywords(string line){ //cout << sizeof(txtKeyWords)/sizeof(string) << endl; for(int i=0; i<sizeof(txtKeyWords)/sizeof(string); i++){ if(txtKeyWords[i]==line) return i+1; } return 0; } inline void str2ch(const string line, char* buf){ line.copy(buf, line.length()); buf[line.length()]='\0'; } void process_txt(const char* txt, double& size, vector<double>& xyz){ ifstream in(txt); string line; int theKey=0; int tmpKey=0; char buf[1024]; int iatom, itype; double x,y,z; double vx, vy, vz; while(getline(in, line)){ tmpKey=isKeywords(line); if(theKey){ if(!tmpKey){ //not a key if(!isComments(line)){ //not a comment --> data entry line switch(theKey){ case 1://SYSTEM SIZE str2ch(line, buf); sscanf(buf, "%lf", &size);//read size break; case 8://list of atoms str2ch(line, buf); sscanf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf", &iatom, &itype, &x, &y, &z, &vx, &vy, &vz); xyz.push_back(x); xyz.push_back(y); xyz.push_back(z); break; default: break; } } } else if(theKey!=tmpKey){ theKey=tmpKey; } } else if(tmpKey){ theKey=tmpKey; } } in.close(); } void single_bond_sprint(char* buf, double ave, double dev){ sprintf(buf, "%lf %lf", ave*(1.0-dev), ave*(1.0+dev)); } void single_bond_sprint_len(char* buf, double ave, double len_dev){ sprintf(buf, "%lf %lf", ave-len_dev, ave+len_dev); } void double_bond_sprint(char* buf, double l_ave, double l_dev, double r_ave, double r_dev){ if(l_ave*(1.0+l_dev) > r_ave*(1.0-r_dev)){ cerr << "Error: overlaping bonds" << endl; exit(1); } sprintf(buf, "%lf %lf %lf %lf %lf %lf", l_ave*(1.0-l_dev), l_ave*(1.0+l_dev), -max_height, r_ave*(1.0-r_dev), max_height, r_ave*(1.0+r_dev)); } void type_sprint(char* buf, dmd_atom_t type, double mass, double hdr, double ir){ if(ir==0) ir = hdr + eps; sprintf(buf, "%ld %lf %lf %lf", type, mass, hdr, ir); } double getTriDev_angle(double a, double b, double dev, double theta, double& c){ c = sqrt(a*a+b*b-2.0*a*b*cos(theta)); double dummy = (a-b*cos(theta))/c*a; double dummy1= (b-a*cos(theta))/c*b; dummy = sqrt(dummy*dummy + dummy1*dummy1)*dev; dummy1 = dummy/c; return dummy1; } double getTriDev_length(double a, double b, double dev, double c){ double theta = acos((a*a+b*b-c*c)/(2.0*a*b)); double dummy = (a-b*cos(theta))/c*a; double dummy1= (b-a*cos(theta))/c*b; dummy = sqrt(dummy*dummy + dummy1*dummy1)*dev; dummy1 = dummy/c; return dummy1; } void list_atom_sprint(char* buf, int index, dmd_atom_t type, vec& r, vec& v){ sprintf(buf,"%-4ld %-4ld %18.13lf %18.13lf %18.13lf %18.13lf %18.13lf %18.13lf", index, type, r.getX(), r.getY(), r.getZ(), v.getX(), v.getY(), v.getZ()); } void el_col_sprint(char* buf, dmd_atom_t a, dmd_atom_t b, double min_d){ sprintf(buf, "%ld %ld %lf", a, b, min_d); } void sel_col_sprint(char* buf, dmd_atom_t a, dmd_atom_t b, double hdr, double min_d, int nstep=1, double e=Dihedral_E){ double delta = min_d - hdr; double step = delta/nstep; int pt = sprintf(buf, "%ld %ld %lf", a, b, hdr); double dist = hdr; for(int i=0; i<nstep; i++){ dist += step; pt += sprintf(&buf[pt], " %lf %lf", dist, e); } } void hp_sprint(char* buf, dmd_atom_t a, dmd_atom_t b, double hd, double id, double e){ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", a, b, hd, id, -fabs(e), id+ir_ext, -fabs(e)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", a, b, hd, id, -fabs(e));} } void sb_sprint(char* buf, dmd_atom_t a, dmd_atom_t b, double hd, double id, double e){ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf", a, b, hd, id-ir_ext, -fabs(e), id, -fabs(e)/4.0, id+ir_ext, -fabs(e)/4.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", a, b, hd, id, -fabs(e)); } } void rsb_sprint(char* buf, dmd_atom_t a, dmd_atom_t b, double hd, double id, double e){ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf", a, b, hd, id-ir_ext, fabs(e), id, fabs(e)/4.0, id+ir_ext, fabs(e)/4.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", a, b, hd, id, fabs(e)); } } void printSYS_SIZE(ostream& out, double size, int dimension=3){ out << txtKeyWords[SYS_SIZE] << endl; for(int i=0; i<dimension; i++){ out << size << " "; } out << endl; } void printNUM_ATOMS(ostream& out, pseudoPep& p, int np=1, int ng=0){ out << txtKeyWords[NUM_ATOMS] << endl; int nTotal = ng; pseudoAA* lastAA = p.getResidue(p.getLength()-1); atom* lastAtom = NULL; if(lastAtom=lastAA->getG2()); else if(lastAtom=lastAA->getD()); else if(lastAtom=lastAA->getG()); else if(lastAtom=lastAA->getCB()); else if(lastAtom=lastAA->getCA()); else{ cerr << "last amino acids is not a protein!!" << endl; exit(1); } nTotal += np*lastAtom->getIndex(); out << nTotal << endl; } void printATOM_TYPE(ostream& out){ out << txtKeyWords[TYPE_ATOMS] << endl; char buf[1024]; /*generic atoms*/ /*N*/ type_sprint(buf, _N_, N_M, N_HDR, 0.0); out << buf << endl; /*C*/ type_sprint(buf, _C_, C_M, C_HDR, 0.0); out << buf << endl; /*O*/ type_sprint(buf, _O_, O_M, O_HDR, 0.0); out << buf << endl; /*CA*/ type_sprint(buf, _CA_, CA_M, CA_HDR, 0.0); out << buf << endl; /*CB*/ type_sprint(buf, _CB_, CB_M, CB_HDR, 0.0); out << buf << endl; /*PRO_N*/ type_sprint(buf, _PRO_N_, N_M, N_HDR, 0.0); out << buf << endl; /*NP*/ type_sprint(buf, _N_HB_, N_M, N_HDR, 0.0); out << buf << endl; /*OP*/ type_sprint(buf, _O_HB_, O_M, O_HDR, 0.0); out << buf << endl; /*CB atoms*/ int type_shift = _CYS_CB_; for(int i=0; i<20; i++){ dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i); if(i!=GLY){ type_sprint(buf, cb_t, CB_M, CB_HDR, 0.0); } else{/*gly CB is a never-used type*/ type_sprint(buf, cb_t, 1.0, eps, eps); } out << buf << endl; } /*CG atoms*/ type_shift = _CYS_CG_; for(int i=0; i<20; i++){ dmd_atom_t cg_t = static_cast<dmd_atom_t>(type_shift + i); if(i!=ALA && i!=GLY){ const double* cg_para = G1_CONST[i]; type_sprint(buf, cg_t, cg_para[G1_M], cg_para[G1_HDR], cg_para[G1_IR]); } else{/*ala, gly CG is a never-used type*/ type_sprint(buf, cg_t, 1.0, eps, eps); } out << buf << endl; } /*CG2 atoms*/ /*ILE*/ type_sprint(buf, _ILE_CG2_, ILE_G2[G2_M], ILE_G2[G2_HDR], ILE_G2[G2_IR]); out << buf << endl; /*THR*/ type_sprint(buf, _THR_CG2_, THR_G2[G2_M], THR_G2[G2_HDR], THR_G2[G2_IR]); out << buf << endl; /*VAL*/ type_sprint(buf, _VAL_CG2_, VAL_G2[G2_M], VAL_G2[G2_HDR], VAL_G2[G2_IR]); out << buf << endl; /*CD atoms*/ /*ARG*/ type_sprint(buf, _ARG_CD_, ARG_D[D_M], ARG_D[D_HDR], ARG_D[D_IR]); out << buf << endl; /*LYS*/ type_sprint(buf, _LYS_CD_, LYS_D[D_M], LYS_D[D_HDR], LYS_D[D_IR]); out << buf << endl; /*TRP*/ type_sprint(buf, _TRP_CD_, TRP_D[D_M], TRP_D[D_HDR], TRP_D[D_IR]); out << buf << endl; /*DERIVED HBA types*/ type_sprint(buf, _ASP_HBA_, G1_CONST[ASP][G1_M], G1_CONST[ASP][G1_HDR], G1_CONST[ASP][G1_IR]); out << buf << endl; type_sprint(buf, _ASN_HBA_, G1_CONST[ASN][G1_M], G1_CONST[ASN][G1_HDR], G1_CONST[ASN][G1_IR]); out << buf << endl; type_sprint(buf, _GLN_HBA_, G1_CONST[GLN][G1_M], G1_CONST[GLN][G1_HDR], G1_CONST[GLN][G1_IR]); out << buf << endl; type_sprint(buf, _GLU_HBA_, G1_CONST[GLU][G1_M], G1_CONST[GLU][G1_HDR], G1_CONST[GLU][G1_IR]); out << buf << endl; type_sprint(buf, _SER_HBA_, G1_CONST[SER][G1_M], G1_CONST[SER][G1_HDR], G1_CONST[SER][G1_IR]); out << buf << endl; type_sprint(buf, _THR_HBA_, THR_G2[G2_M], THR_G2[G2_HDR], THR_G2[G2_IR]); out << buf << endl; /*derived HBD types*/ type_sprint(buf, _ASN_HBD_, G1_CONST[ASN][G1_M], G1_CONST[ASN][G1_HDR], G1_CONST[ASN][G1_IR]); out << buf << endl; type_sprint(buf, _GLN_HBD_, G1_CONST[GLN][G1_M], G1_CONST[GLN][G1_HDR], G1_CONST[GLN][G1_IR]); out << buf << endl; type_sprint(buf, _SER_HBD_, G1_CONST[SER][G1_M], G1_CONST[SER][G1_HDR], G1_CONST[SER][G1_IR]); out << buf << endl; type_sprint(buf, _THR_HBD_, THR_G2[G2_M], THR_G2[G2_HDR], THR_G2[G2_IR]); out << buf << endl; } void printNONEL_COL(ostream& out){ out << txtKeyWords[NONEL_COL] << endl; char buf[1024]; /*mainchain hydogen related*/ /*O-N*/ sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _O_, min_NO, HB_N_O[2]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _O_HB_, min_NO, HB_N_O[2]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _O_HB_, min_NO, HB_N_O[2]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _O_, min_NO, HB_N_O[2]); out << buf << endl; /*N-C*/ sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _C_, min_NC, HB_N_C[4]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _C_, min_NC, HB_N_C[4]); out << buf << endl; /*O-C*/ sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _C_, min_CO, HB_O_C[3]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _C_, min_CO, HB_O_C[3]); out << buf << endl; /*O-Ca*/ sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _CA_, min_OCa, HB_O_CA[3]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _CA_, min_OCa, HB_O_CA[3]); out << buf << endl; /*N-N*/ sel_col_sprint(buf, _N_, _N_, hdr_NN, min_NN, 2, Dihedral_E/2); out << buf << endl; sel_col_sprint(buf, _N_, _N_HB_, hdr_NN, min_NN, 2, Dihedral_E/2); out << buf << endl; sel_col_sprint(buf, _N_HB_, _N_HB_, hdr_NN, min_NN, 2, Dihedral_E/2); out << buf << endl; sel_col_sprint(buf, _N_, _PRO_N_, hdr_NN, min_PRO_NN, 1, Dihedral_E/2.0); out << buf << endl; sel_col_sprint(buf, _N_HB_, _PRO_N_, hdr_NN, min_PRO_NN, 1, Dihedral_E/2.0); out << buf << endl; sel_col_sprint(buf, _PRO_N_, _PRO_N_, hdr_NN, min_PRO_NN, 1, Dihedral_E/2.0); out << buf << endl; int type_shift = _CYS_CB_; /*O-Cb, OP-Cb*/ sel_col_sprint(buf, _O_, _CB_, hdr_OCb, min_OCb, 2, Dihedral_E/2); out << buf << endl; sel_col_sprint(buf, _O_HB_, _CB_, hdr_OCb, min_OCb, 2, Dihedral_E/2); out << buf << endl; for(int i=0; i<20; i++){ dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i); if(cb_t!=_PRO_CB_){ sel_col_sprint(buf, _O_, cb_t, hdr_OCb, min_OCb, 2, Dihedral_E/2); out << buf << endl; sel_col_sprint(buf, _O_HB_, cb_t, hdr_OCb, min_OCb, 2, Dihedral_E/2); out << buf << endl; } else{ sel_col_sprint(buf, _O_, cb_t, hdr_PRO_OCb, min_PRO_OCb, 2, Dihedral_E/2.0); out << buf << endl; sel_col_sprint(buf, _O_HB_, cb_t, hdr_PRO_OCb, min_PRO_OCb, 2, Dihedral_E/2.0); out << buf << endl; } } /*PRO_CB-N*/ sel_col_sprint(buf, _N_, _PRO_CB_, hdr_NCb, min_PRO_NCb, 5, Dihedral_E); out << buf << endl; sel_col_sprint(buf, _N_HB_, _PRO_CB_, hdr_NCb, min_PRO_NCb, 5, Dihedral_E); out << buf << endl; sel_col_sprint(buf, _PRO_N_, _PRO_CB_, hdr_NCb, min_PRO_NCb, 5, Dihedral_E); out << buf << endl; /*sidechain main related*/ /*HBA*/ sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _ASP_CG_, N_HDR+G1_CONST[ASP][G1_HDR], HB_ASP_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _ASN_CG_, N_HDR+G1_CONST[ASN][G1_HDR], HB_ASN_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _GLN_CG_, N_HDR+G1_CONST[GLN][G1_HDR], HB_GLN_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _GLU_CG_, N_HDR+G1_CONST[GLU][G1_HDR], HB_GLU_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _SER_CG_, min_NO, HB_SER_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_, _THR_CG2_, min_NO, HB_THR_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _ASP_CG_, N_HDR+G1_CONST[ASP][G1_HDR], HB_ASP_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _ASN_CG_, N_HDR+G1_CONST[ASN][G1_HDR], HB_ASN_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _GLN_CG_, N_HDR+G1_CONST[GLN][G1_HDR], HB_GLN_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _GLU_CG_, N_HDR+G1_CONST[GLU][G1_HDR], HB_GLU_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _SER_CG_, min_NO, HB_SER_N[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _N_HB_, _THR_CG2_, min_NO, HB_THR_N[1]); out << buf << endl; /*HBD*/ sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _ASN_CG_, O_HDR+G1_CONST[ASN][G1_HDR], HBD_ASN_O[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _GLN_CG_, O_HDR+G1_CONST[GLN][G1_HDR], HBD_GLN_O[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _SER_CG_, HBD_SER_O[0], HBD_SER_O[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_, _THR_CG2_, HBD_THR_O[0], HBD_THR_O[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _ASN_CG_, O_HDR+G1_CONST[ASN][G1_HDR], HBD_ASN_O[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _GLN_CG_, O_HDR+G1_CONST[GLN][G1_HDR], HBD_GLN_O[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _SER_CG_, HBD_SER_O[0], HBD_SER_O[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf 0.0000", _O_HB_, _THR_CG2_, HBD_THR_O[0], HBD_THR_O[1]); out << buf << endl; /*define hydrophobic interaction*/ dmd_atom_t type_i, type_j; double hdr_i, hdr_j; double ir_i, ir_j; for(int i=0; i<sizeof(dmd_atom_hp)/sizeof(hp_t); i++){ if(dmd_atom_hp[i]!=IRRELEVANT){ /*type determination of ith atom*/ type_i = static_cast<dmd_atom_t>(_CYS_CB_+i); if(type_i>=_CYS_CB_ && type_i<=_PRO_CB_){ hdr_i = CB_HDR; ir_i = CB_IR; } else if(type_i>=_CYS_CG_ && type_i<=_PRO_CG_){ hdr_i = G1_CONST[type_i-_CYS_CG_][G1_HDR]; ir_i = G1_CONST[type_i-_CYS_CG_][G1_IR]; } else if(type_i==_ILE_CG2_){ hdr_i = ILE_G2[G2_HDR]; ir_i = ILE_G2[G2_IR]; } else if(type_i==_THR_CG2_){ hdr_i = THR_G2[G2_HDR]; ir_i = THR_G2[G2_IR]; } else if(type_i==_VAL_CG2_) { hdr_i = VAL_G2[G2_HDR]; ir_i = VAL_G2[G2_IR]; } else if(type_i==_ARG_CD_){ hdr_i = ARG_D[D_HDR]; ir_i = ARG_D[D_IR]; } else if(type_i==_LYS_CD_){ hdr_i = LYS_D[D_HDR]; ir_i = LYS_D[D_IR]; } else if(type_i==_TRP_CD_){ hdr_i = TRP_D[D_HDR]; ir_i = TRP_D[D_IR]; } for(int j=i; j<sizeof(dmd_atom_hp)/sizeof(hp_t); j++){ /*type determination of ith atom*/ if(dmd_atom_hp[j]!=IRRELEVANT){ type_j = static_cast<dmd_atom_t>(_CYS_CB_+j); if(type_j>=_CYS_CB_ && type_j<=_PRO_CB_){ hdr_j = CB_HDR; ir_j = CB_IR; } else if(type_j>=_CYS_CG_ && type_j<=_PRO_CG_){ hdr_j = G1_CONST[type_j-_CYS_CG_][G1_HDR]; ir_j = G1_CONST[type_j-_CYS_CG_][G1_IR]; } else if(type_j==_ILE_CG2_){ hdr_j = ILE_G2[G2_HDR]; ir_j = ILE_G2[G2_IR]; } else if(type_j==_THR_CG2_){ hdr_j = THR_G2[G2_HDR]; ir_j = THR_G2[G2_IR]; } else if(type_j==_VAL_CG2_){ hdr_j = VAL_G2[G2_HDR]; ir_j = VAL_G2[G2_IR]; } else if(type_j==_ARG_CD_){ hdr_j = ARG_D[D_HDR]; ir_j = ARG_D[D_IR]; } else if(type_j==_LYS_CD_){ hdr_j = LYS_D[D_HDR]; ir_j = LYS_D[D_IR]; } else if(type_j==_TRP_CD_){ hdr_j = TRP_D[D_HDR]; ir_j = TRP_D[D_IR]; } /*determine the interaction potential*/ if(dmd_atom_hp[i]==APOLOR && dmd_atom_hp[j]==APOLOR){/*APOLOR-APOLOR*/ if((type_i==_PHE_CG_ || type_i==_TRP_CD_ || type_i==_TYR_CG_ || type_i==_PRO_CG_) && (type_j==_PHE_CG_ || type_j==_TRP_CD_ || type_j==_TYR_CG_ || type_j==_PRO_CG_)){ /*AROMATIC interaction is more than HYDROPHOBIC; The interaction potential will be assigned later {PHE,TYR,TRP,PRO}--{PHE,TYR,TRP,PRO}*/ } else{ hp_sprint(buf, type_i, type_j, hdr_i+hdr_j, ir_i+ir_j, HP_E); out << buf << endl; } } else if((dmd_atom_hp[i]==APOLOR && dmd_atom_hp[j]==AMPHI) || (dmd_atom_hp[i]==AMPHI && dmd_atom_hp[j]==APOLOR)){ if((type_i==_PHE_CG_ || type_i==_TRP_CD_ || type_i==_TYR_CG_ || type_i==_PRO_CG_) && (type_j==_PHE_CG_ || type_j==_TRP_CD_ || type_j==_TYR_CG_ || type_j==_PRO_CG_)){ /*PRO as an amphipatic amino acid with aromatic ring, it has a strong AROMATIC interaction with hydrophobic aromatic residues; The interaction is assgined later {PHE,TYR,TRP,PRO}--{PHE,TYR,TRP,PRO}*/ } else{ hp_sprint(buf, type_i, type_j, hdr_i+hdr_j, ir_i+ir_j, HA_E); out << buf << endl; } } } } } } /*end the definition of HYDROPHOBIC interactions*/ /*SB related: We treat the Electrostatic interaction as short-range attraction*/ double hcd = 0; double itd = 0; /*ARG(D)-ASP(G)*/ hcd = ARG_D[D_HDR]+G1_CONST[ASP][G1_HDR]; itd = ARG_D[D_IR] +G1_CONST[ASP][G1_IR]; sb_sprint(buf, _ARG_CD_, _ASP_CG_, hcd, itd, SB_E); out << buf << endl; sb_sprint(buf, _ARG_CD_, _ASP_HBA_, hcd, itd, SB_E); out << buf << endl; /*ARG(D)-GLU(G)*/ hcd = ARG_D[D_HDR]+G1_CONST[GLU][G1_HDR]; itd = ARG_D[D_IR] +G1_CONST[GLU][G1_IR]; sb_sprint(buf, _ARG_CD_, _GLU_CG_, hcd, itd, SB_E); out << buf << endl; sb_sprint(buf, _ARG_CD_, _GLU_HBA_, hcd, itd, SB_E); out << buf << endl; /*ARG(D)-LYS(D)*/ hcd = ARG_D[D_HDR]+LYS_D[D_HDR]; itd = ARG_D[D_IR] +LYS_D[D_IR]; rsb_sprint(buf, _ARG_CD_, _LYS_CD_, hcd, itd, SB_E); out << buf << endl; /*ARG-ARG*/ hcd = ARG_D[D_HDR]+ARG_D[D_HDR]; itd = ARG_D[D_IR] +ARG_D[D_IR]; rsb_sprint(buf, _ARG_CD_, _ARG_CD_, hcd, itd, SB_E); out << buf << endl; /*LYS-ASP*/ hcd = LYS_D[D_HDR]+G1_CONST[ASP][G1_HDR]; itd = LYS_D[D_IR] +G1_CONST[ASP][G1_IR]; sb_sprint(buf, _LYS_CD_, _ASP_CG_, hcd, itd, SB_E); out << buf << endl; sb_sprint(buf, _LYS_CD_, _ASP_HBA_, hcd, itd, SB_E); out << buf << endl; /*LYS-GLU*/ hcd = LYS_D[D_HDR]+G1_CONST[GLU][G1_HDR]; itd = LYS_D[D_IR] +G1_CONST[GLU][G1_IR]; sb_sprint(buf, _LYS_CD_, _GLU_CG_, hcd, itd, SB_E); out << buf << endl; sb_sprint(buf, _LYS_CD_, _GLU_HBA_, hcd, itd, SB_E); out << buf << endl; /*LYS-LYS*/ hcd = LYS_D[D_HDR]+LYS_D[D_HDR]; itd = LYS_D[D_IR] +LYS_D[D_IR]; rsb_sprint(buf, _LYS_CD_, _LYS_CD_, hcd, itd, SB_E); out << buf << endl; /*GLU-ASP*/ hcd = G1_CONST[GLU][G1_HDR]+G1_CONST[ASP][G1_HDR]; itd = G1_CONST[GLU][G1_IR] +G1_CONST[ASP][G1_IR]; rsb_sprint(buf, _GLU_CG_, _ASP_CG_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _GLU_HBA_, _ASP_CG_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _GLU_CG_, _ASP_HBA_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _GLU_HBA_, _ASP_HBA_, hcd, itd, SB_E); out << buf << endl; /*GLU-GLU*/ hcd = G1_CONST[GLU][G1_HDR]+G1_CONST[GLU][G1_HDR]; itd = G1_CONST[GLU][G1_IR] +G1_CONST[GLU][G1_IR]; rsb_sprint(buf, _GLU_CG_, _GLU_CG_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _GLU_HBA_, _GLU_CG_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _GLU_CG_, _GLU_HBA_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _GLU_HBA_, _GLU_HBA_, hcd, itd, SB_E); out << buf << endl; /*ASP-ASP*/ hcd = G1_CONST[ASP][G1_HDR]+G1_CONST[ASP][G1_HDR]; itd = G1_CONST[ASP][G1_IR] +G1_CONST[ASP][G1_IR]; rsb_sprint(buf, _ASP_CG_, _ASP_CG_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _ASP_HBA_, _ASP_CG_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _ASP_CG_, _ASP_HBA_, hcd, itd, SB_E); out << buf << endl; rsb_sprint(buf, _ASP_HBA_, _ASP_HBA_, hcd, itd, SB_E); out << buf << endl; /*end SB*/ /*define the AROMATIC interactions*/ /*ARO --- ARO; the hardcore diameter is increased due to ringpacking*/ /*PHE-PHE*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _PHE_CG_, ARO_R_PHE+ARO_R_PHE, G1_CONST[PHE][G1_IR] + G1_CONST[PHE][G1_IR], -fabs(AROMATIC_E), G1_CONST[PHE][G1_IR] + G1_CONST[PHE][G1_IR]+ir_ext, -fabs(AROMATIC_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _PHE_CG_, ARO_R_PHE+ARO_R_PHE, G1_CONST[PHE][G1_IR] + G1_CONST[PHE][G1_IR], -fabs(AROMATIC_E) ) ; } out << buf << endl; /*PHE-TRP*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _TRP_CD_, ARO_R_PHE+ARO_R_TRP, G1_CONST[PHE][G1_IR] + TRP_D[D_IR], -fabs(AROMATIC_E), G1_CONST[PHE][G1_IR] + TRP_D[D_IR]+ir_ext, -fabs(AROMATIC_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _TRP_CD_, ARO_R_PHE+ARO_R_TRP, G1_CONST[PHE][G1_IR] + TRP_D[D_IR], -fabs(AROMATIC_E) ); } out << buf << endl; /*TRP-TRP*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TRP_CD_, _TRP_CD_, ARO_R_TRP+ARO_R_TRP, TRP_D[D_IR] +TRP_D[D_IR], -fabs(AROMATIC_E), TRP_D[D_IR] +TRP_D[D_IR]+ir_ext, -fabs(AROMATIC_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _TRP_CD_, _TRP_CD_, ARO_R_TRP+ARO_R_TRP, TRP_D[D_IR] +TRP_D[D_IR], -fabs(AROMATIC_E) ); } out << buf << endl; /*TRP-TYR*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TRP_CD_, _TYR_CG_, ARO_R_TRP + ARO_R_TYR, TRP_D[D_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E), TRP_D[D_IR] +G1_CONST[TYR][G1_IR]+ir_ext, -fabs(AROMATIC_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _TRP_CD_, _TYR_CG_, ARO_R_TRP + ARO_R_TYR, TRP_D[D_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E) ); } out << buf << endl; /*PHE-TYR*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _TYR_CG_, ARO_R_PHE + ARO_R_TYR, G1_CONST[PHE][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E), G1_CONST[PHE][G1_IR] +G1_CONST[TYR][G1_IR]+ir_ext, -fabs(AROMATIC_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _TYR_CG_, ARO_R_PHE + ARO_R_TYR, G1_CONST[PHE][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E) ); } out << buf << endl; /*TYR-TYR*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TYR_CG_, _TYR_CG_, ARO_R_TYR + ARO_R_TYR, G1_CONST[TYR][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E), G1_CONST[TYR][G1_IR] +G1_CONST[TYR][G1_IR]+ir_ext, -fabs(AROMATIC_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _TYR_CG_, _TYR_CG_, ARO_R_TYR + ARO_R_TYR, G1_CONST[TYR][G1_IR] +G1_CONST[TYR][G1_IR], -fabs(AROMATIC_E) ); } out << buf << endl; /*ARO---PRO*/ /*TRP-PRO*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TRP_CD_, _PRO_CG_, TRP_D[D_HDR]+G1_CONST[PRO][G1_HDR], TRP_D[D_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E), TRP_D[D_IR] +G1_CONST[PRO][G1_IR]+ir_ext, -fabs(ARO_PRO_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _TRP_CD_, _PRO_CG_, TRP_D[D_HDR]+G1_CONST[PRO][G1_HDR], TRP_D[D_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E) ); } out << buf << endl; /*TYR-PRO*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _TYR_CG_, _PRO_CG_, G1_CONST[TYR][G1_HDR]+G1_CONST[PRO][G1_HDR], G1_CONST[TYR][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E), G1_CONST[TYR][G1_IR] +G1_CONST[PRO][G1_IR]+ir_ext, -fabs(ARO_PRO_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _TYR_CG_, _PRO_CG_, G1_CONST[TYR][G1_HDR]+G1_CONST[PRO][G1_HDR], G1_CONST[TYR][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E) ); } out << buf << endl; /*PHE-PRO*/ if( ir_ext>0 ){ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf", _PHE_CG_, _PRO_CG_, G1_CONST[PHE][G1_HDR]+G1_CONST[PRO][G1_HDR], G1_CONST[PHE][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E), G1_CONST[PHE][G1_IR] +G1_CONST[PRO][G1_IR]+ir_ext, -fabs(ARO_PRO_E)/2.0); } else{ sprintf(buf, "%ld %ld %lf %lf %lf", _PHE_CG_, _PRO_CG_, G1_CONST[PHE][G1_HDR]+G1_CONST[PRO][G1_HDR], G1_CONST[PHE][G1_IR] +G1_CONST[PRO][G1_IR], -fabs(ARO_PRO_E) ); } out << buf << endl; /*HIS?*/ /*end the definition of AROMATIC interactions*/ } void printEL_COL(ostream& out){ out << txtKeyWords[EL_COL] << endl; char buf[1024]; /*N-C*/ /* el_col_sprint(buf, _N_, _C_, min_NC); out << buf << endl; el_col_sprint(buf, _N_HB_, _C_, min_NC); out << buf << endl; */ el_col_sprint(buf, _PRO_N_, _C_, min_NC); out << buf << endl; /*N-Cb*/ el_col_sprint(buf, _N_, _CB_, min_NCb); out << buf << endl; el_col_sprint(buf, _N_HB_, _CB_, min_NCb); out << buf << endl; el_col_sprint(buf, _PRO_N_, _CB_, min_NCb); out << buf << endl; int type_shift = _CYS_CB_; for(int i=0; i<20; i++){ dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i); if(cb_t!=_PRO_CB_){ el_col_sprint(buf, _N_, cb_t, min_NCb); out << buf << endl; el_col_sprint(buf, _N_HB_, cb_t, min_NCb); out << buf << endl; el_col_sprint(buf, _PRO_N_, cb_t, min_NCb); out << buf << endl; } } /*C-CB*/ el_col_sprint(buf, _C_, _CB_, min_CCb); out << buf << endl; for(int i=0; i<20; i++){ dmd_atom_t cb_t = static_cast<dmd_atom_t>(type_shift + i); el_col_sprint(buf, _C_, cb_t, min_CCb); out << buf << endl; } /*O-Ca, OP-Ca*/ /* el_col_sprint(buf, _O_, _CA_, min_OCa); out << buf << endl; el_col_sprint(buf, _O_HB_, _CA_, min_OCa); out << buf << endl; */ /*main chain hydrogen bonding related*/ /*NP-OP*/ /* el_col_sprint(buf, _N_HB_, _O_HB_, min_NO); out << buf << endl; el_col_sprint(buf, _N_HB_, _O_, min_NO); out << buf << endl; el_col_sprint(buf, _N_, _O_HB_, min_NO); out << buf << endl; */ /*side-main hydrogen bonding related*/ el_col_sprint(buf, _N_, _ASP_HBA_, N_HDR+G1_CONST[ASP][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_, _ASN_HBA_, N_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_, _GLN_HBA_, N_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_, _GLU_HBA_, N_HDR+G1_CONST[GLU][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_, _SER_HBA_, min_NO); out << buf << endl; el_col_sprint(buf, _N_, _THR_HBA_, min_NO); out << buf << endl; el_col_sprint(buf, _N_HB_, _ASP_HBA_, N_HDR+G1_CONST[ASP][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_HB_, _ASN_HBA_, N_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_HB_, _GLN_HBA_, N_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_HB_, _GLU_HBA_, N_HDR+G1_CONST[GLU][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_HB_, _SER_HBA_, min_NO); out << buf << endl; el_col_sprint(buf, _N_HB_, _THR_HBA_, min_NO); out << buf << endl; el_col_sprint(buf, _O_, _ASN_HBD_, O_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_, _GLN_HBD_, O_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_, _SER_HBD_, HBD_SER_O[0]); out << buf << endl; el_col_sprint(buf, _O_, _THR_HBD_, HBD_THR_O[0]); out << buf << endl; el_col_sprint(buf, _O_HB_, _ASN_HBD_, O_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_HB_, _GLN_HBD_, O_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_HB_, _SER_HBD_, HBD_SER_O[0]); out << buf << endl; el_col_sprint(buf, _O_HB_, _THR_HBD_, HBD_THR_O[0]); out << buf << endl; el_col_sprint(buf, _O_, _ASN_HBA_, O_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_HB_, _ASN_HBA_, O_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_, _ASN_HBD_, N_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_HB_, _ASN_HBD_, N_HDR+G1_CONST[ASN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_, _GLN_HBA_, O_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_HB_, _GLN_HBA_, O_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_, _GLN_HBD_, N_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _N_HB_, _GLN_HBD_, N_HDR+G1_CONST[GLN][G1_HDR]); out << buf << endl; el_col_sprint(buf, _O_, _SER_HBA_, HBD_SER_O[0]); out << buf << endl; el_col_sprint(buf, _O_HB_, _SER_HBA_, HBD_SER_O[0]); out << buf << endl; el_col_sprint(buf, _N_, _SER_HBD_, min_NO); out << buf << endl; el_col_sprint(buf, _N_HB_, _SER_HBD_, min_NO); out << buf << endl; el_col_sprint(buf, _O_, _THR_HBA_, HBD_THR_O[0]); out << buf << endl; el_col_sprint(buf, _O_HB_, _THR_HBA_, HBD_THR_O[0]); out << buf << endl; el_col_sprint(buf, _N_, _THR_HBD_, min_NO); out << buf << endl; el_col_sprint(buf, _N_HB_, _THR_HBD_, min_NO); out << buf << endl; } void printBOND_TYPE(ostream& out){ out << txtKeyWords[LINK_PAIRS] << endl; char buf[1024]; /*N-Ca, Ca_N1*/ double n_len; double n_dev = getTriDev_angle(CA_C, C_N, BOND_DEV, CA_C_N*rpi, n_len); double_bond_sprint(buf, N_CA, BOND_DEV, n_len, n_dev); out << _N_ << " " << _CA_ << " " << buf << endl; /*Ca-C, C-Ca1*/ n_dev = getTriDev_angle(C_N, N_CA, BOND_DEV, C_N_CA*rpi, n_len); double_bond_sprint(buf, CA_C, BOND_DEV, n_len, n_dev); out << _C_ << " " << _CA_ << " " << buf << endl; /*C-N1, N-C*/ n_dev = getTriDev_angle(N_CA, CA_C, BOND_DEV, N_CA_C*rpi, n_len); double_bond_sprint(buf, C_N, BOND_DEV, n_len, n_dev); out << _N_ << " " << _C_ << " " << buf << endl; /*CA-CB*/ single_bond_sprint(buf, CA_CB, BOND_DEV); out << _CA_ << " " << _CB_ << " " << buf << endl; /*CA-PRO_CB*/ out << _CA_ << " " << _PRO_CB_ << " " << buf << endl; /*N-CB*/ n_dev = getTriDev_angle(N_CA, CA_CB, BOND_DEV, N_CA_CB*rpi, n_len); single_bond_sprint(buf, n_len, n_dev); out << _N_ << " " << _CB_ << " " << buf << endl; /*N-PRO_CB*/ n_dev = getTriDev_angle(N_CA, CA_CB, BOND_DEV, PRO_N_CA_CB*rpi, n_len); single_bond_sprint(buf, n_len, n_dev); out << _N_ << " " << _PRO_CB_ << " " << buf << endl; /*C-CB*/ n_dev = getTriDev_angle(CA_C, CA_CB, BOND_DEV, C_CA_CB*rpi, n_len); single_bond_sprint(buf, n_len, n_dev); out << _C_ << " " << _CB_ << " " << buf << endl; /*C-PRO_CB, C-PRO_CB1, used to fix the phi angle of PRO*/ n_dev = getTriDev_angle(CA_C, CA_CB, BOND_DEV, PRO_C_CA_CB*rpi, n_len); double_bond_sprint(buf, n_len, n_dev, PRO_C_CB, PRO_C_CB_D/PRO_C_CB); out << _C_ << " " << _PRO_CB_ << " " << buf << endl; /*C-C, used to alow certain phi region for PRO*/ sprintf(buf, "%ld %ld %lf %lf", _C_, _C_, PRO_C_C1_MIN, PRO_C_C1_MAX); out << buf << endl; /*C-O*/ single_bond_sprint(buf, C_O, BOND_DEV_O); out << _C_ << " " << _O_ << " " << buf << endl; /*CA-O*/ n_dev = getTriDev_angle(CA_C, C_O, BOND_DEV_O, CA_C_O*rpi, n_len); single_bond_sprint(buf, n_len, n_dev); out << _O_ << " " << _CA_ << " " << buf << endl; /*O-N1*/ n_dev = getTriDev_angle(C_O, C_N, BOND_DEV_O, (360.0-CA_C_N-CA_C_O)*rpi, n_len); single_bond_sprint(buf, n_len, n_dev); out << _O_ << " " << _N_ << " " << buf << endl; /*CA-CA*/ double c_ca = sqrt(C_N*C_N + N_CA*N_CA - 2.0*C_N*N_CA*cos(C_N_CA*rpi)); n_dev = getTriDev_angle(CA_C, c_ca, BOND_DEV, CA_C_CA*rpi, n_len); single_bond_sprint(buf, n_len, n_dev); out << _CA_ << " " << _CA_ << " " << buf << endl; /*CG-CB, CG-CA and C-CG, N-CG*/ int type_shift = _CYS_CG_; for(int i=0; i<20; i++){ dmd_atom_t cg_t = static_cast<dmd_atom_t>(type_shift + i); if(i!=ALA && i!=GLY){ const double* cg_para = G1_CONST[i]; if(cg_para[G1_CB_D]==0){ single_bond_sprint(buf, cg_para[G1_CB], BOND_DEV_G); } else{ single_bond_sprint_len(buf, cg_para[G1_CB], cg_para[G1_CB_D]); } if(i!=PRO) out << _CB_ << " " << cg_t << " " << buf << endl; else out << _PRO_CB_ << " " << cg_t << " " << buf << endl; if(cg_para[G1_CA_D]==0){ n_dev = getTriDev_length(cg_para[G1_CB], CA_CB, BOND_DEV_G, cg_para[G1_CA]); single_bond_sprint(buf, cg_para[G1_CA], n_dev); } else{ single_bond_sprint_len(buf, cg_para[G1_CA], cg_para[G1_CA_D]); } out << _CA_ << " " << cg_t << " " << buf << endl; /*N-CG, C-CG*/ const double* dihedral = Dihedral_C_CG[i]; if(dihedral[0]!=INF){ //c-cg sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf %lf", _C_, cg_t, Dihedral_MIN, dihedral[0], Dihedral_E, dihedral[1], -Dihedral_E, dihedral[2], Dihedral_E, Dihedral_MAX); out << buf << endl; //n-cg sprintf(buf, "%ld %ld %lf %lf", _N_, cg_t, Dihedral_MIN, Dihedral_MAX); out << buf << endl; } if(i==PRO){//different constraint for PROLINE single_bond_sprint_len(buf, PRO_N_CG, PRO_N_CG_D); out << _N_ << " " << cg_t << " " << buf << endl; /*this constraint is actually used to avoid the small distance of c-PRO_CB*/ single_bond_sprint_len(buf, PRO_C_CG, PRO_C_CG_D); out << _C_ << " " << cg_t << " " << buf << endl; } } } /*ILE, G2*/ //CG2-CB single_bond_sprint(buf, ILE_G2[G2_CB], BOND_DEV_G); out << _CB_ << " " << _ILE_CG2_ << " " << buf << endl; //CG2-CA n_dev = getTriDev_length(CA_CB, ILE_G2[G2_CB], BOND_DEV_G, ILE_G2[G2_CA]); single_bond_sprint(buf, ILE_G2[G2_CA], n_dev); out << _CA_ << " " << _ILE_CG2_ << " " << buf << endl; //CG2-CG1 //n_dev = getTriDev_length(ILE_G2[G2_CB], G1_CONST[ILE][G1_CB], //BOND_DEV_G, ILE_G2[G1_G2]); n_dev = ILE_G2[CG_G2_D]/ILE_G2[G1_G2]; single_bond_sprint(buf, ILE_G2[G1_G2], n_dev); out << _ILE_CG_ << " " << _ILE_CG2_ << " " << buf << endl; //N-CG2 sprintf(buf, "%ld %ld %lf %lf", _N_, _ILE_CG2_, Dihedral_MIN, Dihedral_MAX); out << buf << endl; //C-CG2 const double* dihedral = Dihedral_C_CG[ILE]; sprintf(buf, "%ld %ld %lf %lf", _C_, _ILE_CG2_, Dihedral_MIN, Dihedral_MAX); out << buf << endl; /*THR, G2*/ //CG2-CB single_bond_sprint(buf, THR_G2[G2_CB], BOND_DEV_G); out << _CB_ << " " << _THR_CG2_ << " " << buf << endl; //CG2-CA n_dev = getTriDev_length(CA_CB, THR_G2[G2_CB], BOND_DEV_G, THR_G2[G2_CA]); single_bond_sprint(buf, THR_G2[G2_CA], n_dev); out << _CA_ << " " << _THR_CG2_ << " " << buf << endl; //CG2-CG1 n_dev = getTriDev_length(THR_G2[G2_CB], G1_CONST[THR][G1_CB], BOND_DEV_G, THR_G2[G1_G2]); single_bond_sprint(buf, THR_G2[G1_G2], n_dev); out << _THR_CG_ << " " << _THR_CG2_ << " " << buf << endl; //N-CG2 sprintf(buf, "%ld %ld %lf %lf", _N_, _THR_CG2_, Dihedral_MIN, Dihedral_MAX); out << buf << endl; //C-CG2 sprintf(buf, "%ld %ld %lf %lf", _C_, _THR_CG2_, Dihedral_MIN, Dihedral_MAX); out << buf << endl; /*VAL, G2*/ //CG2-CB single_bond_sprint(buf, VAL_G2[G2_CB], BOND_DEV_G); out << _CB_ << " " << _VAL_CG2_ << " " << buf << endl; //CG2-CA n_dev = getTriDev_length(CA_CB, VAL_G2[G2_CB], BOND_DEV_G, VAL_G2[G2_CA]); single_bond_sprint(buf, VAL_G2[G2_CA], n_dev); out << _CA_ << " " << _VAL_CG2_ << " " << buf << endl; //CG2-CG1 n_dev = getTriDev_length(VAL_G2[G2_CB], G1_CONST[VAL][G1_CB], BOND_DEV_G, VAL_G2[G1_G2]); single_bond_sprint(buf, VAL_G2[G1_G2], n_dev); out << _VAL_CG_ << " " << _VAL_CG2_ << " " << buf << endl; //N-CG2 sprintf(buf, "%ld %ld %lf %lf", _N_, _VAL_CG2_, Dihedral_MIN, Dihedral_MAX); out << buf << endl; //C-CG2 sprintf(buf, "%ld %ld %lf %lf", _C_, _VAL_CG2_, Dihedral_MIN, Dihedral_MAX); out << buf << endl; /*TRP, CD*/ /*CD-CG*/ single_bond_sprint(buf, TRP_D[D_CG], BOND_DEV_G); out << _TRP_CG_ << " " << _TRP_CD_ << " " << buf << endl; /*CD-CB*/ n_dev = getTriDev_length(G1_CONST[TRP][G1_CB], TRP_D[D_CG], BOND_DEV_G, TRP_D[D_CB]); single_bond_sprint(buf, TRP_D[D_CB], n_dev); out << _TRP_CD_ << " " << _CB_ << " " << buf << endl; /*CD-CA; Dihedral*/ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf %lf", _CA_, _TRP_CD_, Dihedral_MIN, Dihedral_TRP_D[0], Dihedral_E, Dihedral_TRP_D[1], -Dihedral_E, Dihedral_TRP_D[2], Dihedral_E, Dihedral_MAX); out << buf << endl; /*ARG, CD*/ /*CD-CG*/ single_bond_sprint(buf, ARG_D[D_CG], BOND_DEV_G); out << _ARG_CG_ << " " << _ARG_CD_ << " " << buf << endl; /*CD-CB*/ n_dev = ARG_D[D_CB_D]/ARG_D[D_CB]; single_bond_sprint(buf, ARG_D[D_CB], n_dev); out << _ARG_CD_ << " " << _CB_ << " " << buf << endl; /*LYS, CD*/ /*CD-CG*/ single_bond_sprint(buf, LYS_D[D_CG], BOND_DEV_G); out << _LYS_CG_ << " " << _LYS_CD_ << " " << buf << endl; /*CD-CB*/ n_dev = LYS_D[D_CB_D]/LYS_D[D_CB]; single_bond_sprint(buf, LYS_D[D_CB], n_dev); out << _LYS_CD_ << " " << _CB_ << " " << buf << endl; /*mainchain hydrogen bond related*/ /*NP-OP*/ sprintf(buf,"%ld %ld %lf %lf %lf %lf 0.00000", _N_HB_, _O_HB_, HB_N_O[0], HB_N_O[1], -fabs(EHB_M_M)/4.0, HB_N_O[2]+eps); out << buf << endl; /*NP-C*/ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf %lf %lf 0.00000", _N_HB_, _C_, HB_N_C[0], HB_N_C[1], fabs(EHB_M_M)/4.0, HB_N_C[2], fabs(EHB_M_M)/4.0, HB_N_C[3], -fabs(EHB_M_M)/4.0, HB_N_C[4]+eps); out << buf << endl; //sprintf(buf, "%ld %ld %lf %lf", //_N_HB_, _C_, //HB_N_C[1], //HB_N_C[2]), //out << buf << endl; /*OP-C*/ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf 0.00000", _O_HB_, _C_, HB_O_C[0], HB_O_C[1], fabs(EHB_M_M)/2.0, HB_O_C[2], -fabs(EHB_M_M)/4.0, HB_O_C[3]+eps); out << buf << endl; //sprintf(buf, "%ld %ld %lf %lf", // _O_HB_, _C_, // HB_O_C[1], // HB_O_C[2]); //out << buf << endl; /*OP-CA*/ sprintf(buf, "%ld %ld %lf %lf %lf %lf %lf %lf 0.0000", _O_HB_, _CA_, HB_O_CA[0], HB_O_CA[1], fabs(EHB_M_M)/2.0, HB_O_CA[2], -fabs(EHB_M_M)/4.0, HB_O_CA[3]+eps); out << buf << endl; //sprintf(buf, "%ld %ld %lf %lf", // _O_HB_, _CA_, // HB_O_CA[1], // HB_O_CA[2]); //out << buf << endl; /*side-main hydrogen bond related*/ //HBA /*ASP*/ sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _ASP_HBA_, HB_ASP_N[0], HB_ASP_N[1]+eps, -fabs(EHB_S_M)); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _ASP_HBA_, _C_, HB_ASP_C[0], HB_ASP_C[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _ASP_HBA_, _CA_, HB_ASP_CA[0], HB_ASP_CA[1]); out << buf << endl; /*ASN*/ sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _ASN_HBA_, HB_ASN_N[0], HB_ASN_N[1]+eps, -fabs(EHB_S_M)); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _ASN_HBA_, _C_, HB_ASN_C[0], HB_ASN_C[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _ASN_HBA_, _CA_, HB_ASN_CA[0], HB_ASN_CA[1]); out << buf << endl; // /*GLU*/ // sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _GLU_HBA_, // HB_GLU_N[0], HB_GLU_N[1]+eps, -fabs(EHB_S_M)); // out << buf << endl; // sprintf(buf, "%ld %ld %lf %lf", _GLU_HBA_, _C_, // HB_GLU_C[0], HB_GLU_C[1]); // out << buf << endl; // sprintf(buf, "%ld %ld %lf %lf", _GLU_HBA_, _CA_, // HB_GLU_CA[0], HB_GLU_CA[1]); // out << buf << endl; // /*GLN*/ // sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _GLN_HBA_, // HB_GLN_N[0], HB_GLN_N[1]+eps, -fabs(EHB_S_M)); // out << buf << endl; // sprintf(buf, "%ld %ld %lf %lf", _GLN_HBA_, _C_, // HB_GLN_C[0], HB_GLN_C[1]); // out << buf << endl; // sprintf(buf, "%ld %ld %lf %lf", _GLN_HBA_, _CA_, // HB_GLN_CA[0], HB_GLN_CA[1]); // out << buf << endl; /*SER*/ sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _SER_HBA_, HB_SER_N[0], HB_SER_N[1]+eps, -fabs(EHB_S_M)); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _SER_HBA_, _C_, HB_SER_C[0], HB_SER_C[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _SER_HBA_, _CA_, HB_SER_CA[0], HB_SER_CA[1]); out << buf << endl; /*THR*/ sprintf(buf, "%ld %ld %lf %lf %lf", _N_HB_, _THR_HBA_, HB_THR_N[0], HB_THR_N[1]+eps, -fabs(EHB_S_M)); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _THR_HBA_, _C_, HB_THR_C[0], HB_THR_C[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _THR_HBA_, _CA_, HB_THR_CA[0], HB_THR_CA[1]); out << buf << endl; //HBD // sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _ASN_HBD_, // HBD_ASN_O[0], HBD_ASN_O[1]+eps, -fabs(EHB_S_M)); // out << buf << endl; // sprintf(buf, "%ld %ld %lf %lf", _C_, _ASN_HBD_, // HBD_ASN_C[0], HBD_ASN_C[1]); // out << buf << endl; // sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _GLN_HBD_, // HBD_GLN_O[0], HBD_GLN_O[1]+eps, -fabs(EHB_S_M)); // out << buf << endl; // sprintf(buf, "%ld %ld %lf %lf", _C_, _GLN_HBD_, // HBD_GLN_C[0], HBD_GLN_C[1]); // out << buf << endl; sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _SER_HBD_, HBD_SER_O[0], HBD_SER_O[1]+eps, -fabs(EHB_S_M)); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _C_, _SER_HBD_, HBD_SER_C[0], HBD_SER_C[1]); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf %lf", _O_HB_, _THR_HBD_, HBD_THR_O[0], HBD_THR_O[1]+eps, -fabs(EHB_S_M)); out << buf << endl; sprintf(buf, "%ld %ld %lf %lf", _C_, _THR_HBD_, HBD_THR_C[0], HBD_THR_C[1]); out << buf << endl; } void printREACT(ostream& out){ out << txtKeyWords[REACT] << endl; char buf[1024]; /*mainchain hydrogen bonding*/ sprintf(buf, "%ld %ld %ld %ld 1", _N_, _O_, _N_HB_, _O_HB_); out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _N_, _C_, _N_HB_, _C_); out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _O_, _C_, _O_HB_, _C_); out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _O_, _CA_, _O_HB_, _CA_); out << buf << endl; /*side-main hydrogen bonding*/ sprintf(buf, "%ld %ld %ld %ld 1", _N_, _ASP_CG_, _N_HB_, _ASP_HBA_); out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _N_, _ASN_CG_, _N_HB_, _ASN_HBA_); out << buf << endl; // sprintf(buf, "%ld %ld %ld %ld 1", // _N_, _GLU_CG_, _N_HB_, _GLU_HBA_); // out << buf << endl; // sprintf(buf, "%ld %ld %ld %ld 1", // _N_, _GLN_CG_, _N_HB_, _GLN_HBA_); // out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _N_, _SER_CG_, _N_HB_, _SER_HBA_); out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _N_, _THR_CG2_, _N_HB_, _THR_HBA_); out << buf << endl; // sprintf(buf, "%ld %ld %ld %ld 1", // _C_, _ASN_CG_, _O_HB_, _ASN_HBD_); // out << buf << endl; // sprintf(buf, "%ld %ld %ld %ld 1", // _C_, _GLN_CG_, _O_HB_, _GLN_HBD_); // out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _O_, _SER_CG_, _O_HB_, _SER_HBD_); out << buf << endl; sprintf(buf, "%ld %ld %ld %ld 1", _O_, _THR_CG_, _O_HB_, _THR_HBD_); out << buf << endl; } void printATOM_LIST(ostream& out, pseudoPep& p, vector<double>xyz, randomGenerator& r){ out << txtKeyWords[LIST_ATOMS] << endl; char buf[1024]; vec v; vec pos; int index=1; atom* CB; atom* CG; atom* CG2; atom* CD; dmd_atom_t type; for(int i=0; i<p.getLength(); i++){ pseudoAA* theAA = p.getResidue(i); /*N*/ v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss()); pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); if(theAA->getID()==PRO){ list_atom_sprint(buf, index++, _PRO_N_, pos, v); } else{ if(i==0)/*first N atom will be hydrogen-active!*/ list_atom_sprint(buf, index++, _N_HB_, pos, v); else list_atom_sprint(buf, index++, _N_, pos, v); } out << buf << endl; /*C*/ v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss()); pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); list_atom_sprint(buf, index++, _C_, pos, v); out << buf << endl; /*O*/ v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss()); pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); if(i<p.getLength()-1){ list_atom_sprint(buf, index++, _O_, pos, v); } else{ list_atom_sprint(buf, index++, _O_HB_, pos, v); } out << buf << endl; /*CA*/ pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss()); list_atom_sprint(buf, index++, _CA_, pos, v); out << buf << endl; /*CB*/ if(CB = theAA->getCB()){ type = static_cast<dmd_atom_t>(theAA->getID()+_CYS_CB_); v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss()); pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); list_atom_sprint(buf, index++, type, pos, v); out << buf << endl; /*CG*/ if(CG = theAA->getG()){ type = static_cast<dmd_atom_t>(theAA->getID()+_CYS_CG_); double mass = G1_CONST[theAA->getID()][G1_M]; v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss())/sqrt(mass); pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); list_atom_sprint(buf, index++, type, pos, v); out << buf << endl; /*CG2*/ if(CG2 = theAA->getG2()){ if(theAA->getID()==ILE) type = _ILE_CG2_; else if(theAA->getID()==THR) type = _THR_CG2_; else if(theAA->getID()==VAL) type = _VAL_CG2_; else{ cerr << "error in type" << endl; exit(1); } v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss()); pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); list_atom_sprint(buf, index++, type, pos, v); out << buf << endl; } /*CD*/ if(CD = theAA->getD()){ if(theAA->getID()==TRP) type = _TRP_CD_; else if(theAA->getID()==ARG) type = _ARG_CD_; else if(theAA->getID()==LYS) type = _LYS_CD_; else{ cerr << "error in type" << endl; exit(1); } v = vec(r.nextGauss(), r.nextGauss(), r.nextGauss()); pos = vec(xyz[3*index-3],xyz[3*index-2],xyz[3*index-1]); list_atom_sprint(buf, index++, type, pos, v); out << buf << endl; } } } } } void printBOND_LIST(ostream& out, pseudoPep& p){ out << txtKeyWords[LIST_BONDS] << endl; char buf[1024]; for(int i=0; i<p.getLength(); i++){ /*intra amino acids*/ pseudoAA* theAA = p.getResidue(i); /*N-CA*/ out << theAA->getN()->getIndex() << " " << theAA->getCA()->getIndex() << endl; /*CA-C*/ out << theAA->getCA()->getIndex() << " " << theAA->getC()->getIndex() << endl; /*N-C*/ out << theAA->getN()->getIndex() << " " << theAA->getC()->getIndex() << endl; /*C-O*/ out << theAA->getC()->getIndex() << " " << theAA->getO()->getIndex() << endl; /*CA-O*/ out << theAA->getCA()->getIndex() << " " << theAA->getO()->getIndex() << endl; if(theAA->getCB()){/*not GLY*/ /*CA-CB*/ out << theAA->getCA()->getIndex() << " " << theAA->getCB()->getIndex() << endl; /*N-CB*/ out << theAA->getN()->getIndex() << " " << theAA->getCB()->getIndex() << endl; /*C-CB*/ out << theAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << endl; if(theAA->getG()){/*not ALA*/ /*CB-CG*/ out << theAA->getCB()->getIndex() << " " << theAA->getG()->getIndex() << endl; /*CA-CG*/ out << theAA->getCA()->getIndex() << " " << theAA->getG()->getIndex() << endl; /*N-CG, C-CG*/ int id = theAA->getID(); if(Dihedral_C_CG[id][0]!=INF){ out << theAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << endl; out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << endl; } if(theAA->getG2()){/*beta-branched*/ /*CG2-CB*/ out << theAA->getCB()->getIndex() << " " << theAA->getG2()->getIndex() << endl; /*CG2-CA*/ out << theAA->getCA()->getIndex() << " " << theAA->getG2()->getIndex() << endl; /*CG2-CG*/ out << theAA->getG()->getIndex() << " " << theAA->getG2()->getIndex() << endl; /*C-CG2*/ out << theAA->getC()->getIndex() << " " << theAA->getG2()->getIndex() << endl; /*N-CG2*/ out << theAA->getN()->getIndex() << " " << theAA->getG2()->getIndex() << endl; } if(theAA->getD()){ dmd_atom_t dt; if(theAA->getID()==ARG) dt = _ARG_CD_; else if(theAA->getID()==LYS) dt = _LYS_CD_; else if(theAA->getID()==TRP) dt = _TRP_CD_; /*CG-CD*/ out << theAA->getG()->getIndex() << " " << theAA->getD()->getIndex() << endl; /*CB-CD*/ out << theAA->getCB()->getIndex() << " " << theAA->getD()->getIndex() << endl; /*CA-CD---Dihedral of TRP*/ if(theAA->getID()==TRP){ out << theAA->getCA()->getIndex() << " " << theAA->getD()->getIndex() << endl; } } } } /*extra constraints for PRO*/ if(theAA->getID()==PRO){ out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << endl; } /*inter amino acids*/ if(i>0){ pseudoAA* preAA = p.getResidue(i-1); /*Ca0 -- N1*/ out << preAA->getCA()->getIndex() << " " << theAA->getN()->getIndex() << endl; /*C0 -- Ca1*/ out << preAA->getC()->getIndex() << " " << theAA->getCA()->getIndex() << endl; /*C0 -- N1*/ out << preAA->getC()->getIndex() << " " << theAA->getN()->getIndex() << endl; /*O0--N1*/ out << preAA->getO()->getIndex() << " " << theAA->getN()->getIndex() << endl; /*Ca0 -- Ca1*/ out << preAA->getCA()->getIndex() << " " << theAA->getCA()->getIndex() << endl; if(theAA->getID()==PRO){ out << preAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << endl; out << preAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << endl; out << preAA->getC()->getIndex() << " " << theAA->getC()->getIndex() << endl; } } } } void printPERM_BOND_LIST(ostream& out, pseudoPep& p){ out << txtKeyWords[LIST_PERM_BONDS] << endl; char buf[1024]; for(int i=0; i<p.getLength(); i++){ /*intra amino acids*/ pseudoAA* theAA = p.getResidue(i); /*N-CA*/ out << theAA->getN()->getIndex() << " " << theAA->getCA()->getIndex() << " " << _N_ << " " << _CA_ << endl; /*CA-C*/ out << theAA->getCA()->getIndex() << " " << theAA->getC()->getIndex() << " " << _CA_ << " " << _C_ << endl; /*N-C*/ out << theAA->getN()->getIndex() << " " << theAA->getC()->getIndex() << " " << _N_ << " " << _C_ << endl; /*C-O*/ out << theAA->getC()->getIndex() << " " << theAA->getO()->getIndex() << " " << _C_ << " " << _O_ << endl; /*CA-O*/ out << theAA->getCA()->getIndex() << " " << theAA->getO()->getIndex() << " " << _CA_ << " " << _O_ << endl; if(theAA->getCB()){/*not GLY*/ dmd_atom_t cbt = _CB_; if(theAA->getID()==PRO) cbt = _PRO_CB_; /*CA-CB*/ out << theAA->getCA()->getIndex() << " " << theAA->getCB()->getIndex() << " " << _CA_ << " " << cbt << endl; /*N-CB*/ out << theAA->getN()->getIndex() << " " << theAA->getCB()->getIndex() << " " << _N_ << " " << cbt << endl; /*C-CB*/ out << theAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << " " << _C_ << " " << cbt << endl; if(theAA->getG()){/*not ALA*/ dmd_atom_t gt = static_cast<dmd_atom_t>(_CYS_CG_ + theAA->getID()); /*CB-CG*/ out << theAA->getCB()->getIndex() << " " << theAA->getG()->getIndex() << " " << cbt << " " << gt << endl; /*CA-CG*/ out << theAA->getCA()->getIndex() << " " << theAA->getG()->getIndex() << " " << _CA_ << " " << gt << endl; if(Dihedral_C_CG[theAA->getID()][0]!=INF){ /*N-CG*/ out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << " " << _N_ << " " << gt << endl; /*C-CG*/ out << theAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << " " << _C_ << " " << gt << endl; } if(theAA->getG2()){/*beta-branched*/ dmd_atom_t g2t; if(theAA->getID() == ILE) g2t = _ILE_CG2_; else if(theAA->getID() == THR) g2t = _THR_CG2_; else if(theAA->getID() == VAL) g2t = _VAL_CG2_; /*CB-CG2*/ out << theAA->getCB()->getIndex() << " " << theAA->getG2()->getIndex() << " " << cbt << " " << g2t << endl; /*CA-CG2*/ out << theAA->getCA()->getIndex() << " " << theAA->getG2()->getIndex() << " " << _CA_ << " " << g2t << endl; /*CG-CG2*/ out << theAA->getG()->getIndex() << " " << theAA->getG2()->getIndex() << " " << gt << " " << g2t << endl; /*N-CG2*/ out << theAA->getN()->getIndex() << " " << theAA->getG2()->getIndex() << " " << _N_ << " " << g2t << endl; /*C-CG2*/ out << theAA->getC()->getIndex() << " " << theAA->getG2()->getIndex() << " " << _C_ << " " << g2t << endl; } if(theAA->getD()){/*bulky residues with Cd*/ dmd_atom_t dt; if(theAA->getID()==ARG) dt = _ARG_CD_; else if(theAA->getID()==LYS) dt = _LYS_CD_; else if(theAA->getID()==TRP) dt = _TRP_CD_; /*CG-CD*/ out << theAA->getG()->getIndex() << " " << theAA->getD()->getIndex() << " " << gt << " " << dt << endl; /*CB-CD*/ out << theAA->getCB()->getIndex() << " " << theAA->getD()->getIndex() << " " << cbt << " " << dt << endl; /*CA-CD, TRP--Dihedral*/ if(theAA->getID()==TRP){ out << theAA->getCA()->getIndex() << " " << theAA->getD()->getIndex() << " " << _CA_ << " " << _TRP_CD_ << endl; } } /*extra constraints for PRO: N-CG*/ if(theAA->getID()==PRO){ out << theAA->getN()->getIndex() << " " << theAA->getG()->getIndex() << " " << _N_ << " " << gt << endl; } } } /*inter amino acids*/ if(i>0){ pseudoAA* preAA = p.getResidue(i-1); /*Ca0 -- N1*/ out << preAA->getCA()->getIndex() << " " << theAA->getN()->getIndex() << " " << _CA_ << " " << _N_ << endl; /*C0 -- Ca1*/ out << preAA->getC()->getIndex() << " " << theAA->getCA()->getIndex() << " " << _C_ << " " << _CA_ << endl; /*C0 -- N1*/ out << preAA->getC()->getIndex() << " " << theAA->getN()->getIndex() << " " << _C_ << " " << _N_ << endl; /*O0--N1*/ out << preAA->getO()->getIndex() << " " << theAA->getN()->getIndex() << " " << _O_ << " " << _N_ << endl; /*Ca0 -- Ca1*/ out << preAA->getCA()->getIndex() << " " << theAA->getCA()->getIndex() << " " << _CA_ << " " << _CA_ << endl; if(theAA->getID()==PRO){ out << preAA->getC()->getIndex() << " " << theAA->getCB()->getIndex() << " " << _C_ << " " << _PRO_CB_ << endl; out << preAA->getC()->getIndex() << " " << theAA->getG()->getIndex() << " " << _C_ << " " << _PRO_CG_ << endl; out << preAA->getC()->getIndex() << " " << theAA->getC()->getIndex() << " " << _C_ << " " << _C_ << endl; } } } } void printHBA_LIST(ostream& out, pseudoPep& p){ out << txtKeyWords[HB_LIST] << endl; char buf[1024]; for(int i=0; i<p.getLength(); i++){ /*N*/ if(i>0){ sprintf(buf, "%ld %ld %ld %ld", p.getResidue(i)->getN()->getIndex(), i, p.getResidue(i-1)->getC()->getIndex(), p.getResidue(i)->getCA()->getIndex()); out << buf << endl; } /*O*/ if(i<p.getLength()-1){ sprintf(buf, "%ld %ld %ld", p.getResidue(i)->getO()->getIndex(), i, p.getResidue(i)->getC()->getIndex()); out << buf << endl; } /*HBA*/ aa_t type = static_cast<aa_t>(p.getResidue(i)->getID()); /*do not consider GLN/GLU*/ if(type==ASP || type==ASN || type==SER){ sprintf(buf, "%ld %ld", p.getResidue(i)->getG()->getIndex(), i); out << buf << endl; } else if(type==THR){ sprintf(buf, "%ld %ld", p.getResidue(i)->getG2()->getIndex(), i); out << buf << endl; } } } void print_GID(ostream& out, pseudoPep& p){ out << txtKeyWords[GID_LIST] << endl; char buf[1024]; for(int i=0; i<p.getLength(); i++){ aa_t type = static_cast<aa_t>(p.getResidue(i)->getID()); if(type!=GLY){ /*CB*/ sprintf(buf, "%ld %ld", p.getResidue(i)->getCB()->getIndex(), i); out << buf<< endl; /*CG*/ if(type!=ALA){ sprintf(buf, "%ld %ld", p.getResidue(i)->getG()->getIndex(), i); out << buf << endl; /*CG2*/ if(type==ILE || type==VAL || type==THR){ sprintf(buf, "%ld %ld", p.getResidue(i)->getG2()->getIndex(), i); out << buf << endl; } /*CD*/ if(type==ARG || type==LYS || type==TRP){ sprintf(buf, "%ld %ld", p.getResidue(i)->getD()->getIndex(), i); out << buf << endl; } } } } } vec getCM(pseudoPep& p){ vec tmp(0,0,0); int natom=0; for(int i=0; i<p.getLength(); i++){ pseudoAA* theAA = p.getResidue(i); tmp += *theAA->getN()->getR(); natom++; tmp += *theAA->getC()->getR(); natom++; tmp += *theAA->getO()->getR(); natom++; tmp += *theAA->getCA()->getR(); natom++; if(theAA->getCB()) { tmp += *theAA->getCB()->getR(); natom++; if(theAA->getG()){ tmp += *theAA->getG()->getR(); natom++; if(theAA->getG2()){ tmp += *theAA->getG2()->getR(); natom++; } if(theAA->getD()){ tmp += *theAA->getD()->getR(); natom++; } } } } tmp /= static_cast<double>(natom); return tmp; } typedef enum { NON_ENER_KEY=-1,E_HB_MM=0, E_HB_SM, E_HH, E_HA, E_SB, E_AROMATIC, E_ARO_PRO, E_ROTAMER } ener_t; const static char* ener_key[] = { "E_HB_MM", "E_HB_SM", "E_HH", "E_HA", "E_SB", "E_AROMATIC", "E_ARO_PRO", "E_ROTAMER" }; void process_para(const char* para_f){ FILE* in = fopen(para_f,"r"); char keyword[100]; char val[100]; ener_t key; if(!in) cerr << "Can not open the parameter file!\n" << endl; while(!feof(in)){ fscanf(in, "%s%s", keyword, val); key = NON_ENER_KEY; for(int i=0; i<sizeof(ener_key)/sizeof(char*); i++){ if(strcmp(ener_key[i], keyword)==0){ key = static_cast<ener_t>(i); break; } } switch(key){ case E_HB_MM: setMMHB_E(atof(val)); break; case E_HB_SM: setSMHB_E(atof(val)); break; case E_HH: setHP_E(atof(val)); break; case E_HA: setHA_E(atof(val)); break; case E_SB: setSB_E(atof(val)); break; case E_AROMATIC: setAROMATIC_E(atof(val)); break; case E_ARO_PRO: setARO_PRO_E(atof(val)); break; case E_ROTAMER: setDI_E(atof(val)); break; default: break; } } fclose(in); } int main(int argc, char* argv[]){ if(argc<5){ cout << "usage: command seq relaxedTXT E_Para_F ir_ext [is_ExN]" << endl; cout << "ir_ext: external radius. If set to zero, then we do not add external radius"; cout << " is_ExN -- OPT parameter to exclude neightbouring interaction: 0/1" << endl; exit(1); } process_para(argv[3]); ir_ext = atof( argv[4] ); int is_en=0; if(argc==6){ is_en = atoi(argv[5]); } pseudoPep p(argv[1], (input_t)0); pseudoAA* lastAA=p.getResidue(p.getLength()-1); lastAA->getO()->getR()->Rotate(*lastAA->getCA()->getR(),*lastAA->getC()->getR(), -PI/3.0); p.makeIndex(); randomGenerator ran(_RAN2_, -100); double size; vec cm = getCM(p); vec shift = vec(size/2.0, size/2.0, size/2.0) - cm; p.shift(shift); vector<double>xyz; process_txt(argv[2], size, xyz); /*create the TXT*/ printSYS_SIZE(cout, size); printNUM_ATOMS(cout, p); printATOM_TYPE(cout); printNONEL_COL(cout); printEL_COL(cout); printBOND_TYPE(cout); printREACT(cout); printATOM_LIST(cout, p, xyz, ran); printBOND_LIST(cout, p); printPERM_BOND_LIST(cout, p); printHBA_LIST(cout, p); if(is_en) print_GID(cout, p); /*END of the txt output*/ }
[ "borreguero@gmail.com" ]
borreguero@gmail.com
9d120febe3a9229a8070e72022b4c415b9a1933a
87b0a0cc6d5c1477b3b4942f544b84c9bcaa281b
/aitu_sorosorosibaku/src/Gimmick/EnergyBullet.cpp
ee1770aea969b976c631b47063a1e639c2ed48be
[]
no_license
yuki-nakano/TeamProduction_2_firstSemester
bb3830e302573976ef89ba608744fbbc5779888e
b3e6bda9a7cac14400661156ff04dea2ac80bd26
refs/heads/master
2023-06-05T04:06:52.444348
2021-06-27T16:43:10
2021-06-27T16:43:10
373,681,446
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
#include "EnergyBullet.h" EnergyBullet::~EnergyBullet() { } bool EnergyBullet::Exec(float player_posx_, float player_posy_) { if (!isAlive) { return false; } AddCount(); Move(); IsCollidePlayer(player_posx_, player_posy_); if (IsFinished()) { isAlive = false; } return true; } void EnergyBullet::Draw() { if (!isAlive) { return; } DrawGraph(pos.X - gimmickWidht / 2, pos.Y - gimmickWidht / 2, textureManager->GetTextureDate(TextureDate::kEnergyBullet_left), TRUE); // DrawBox(pos.X, pos.Y, pos.X + gimmickWidht, pos.Y + gimmickHeight, GetColor(0, 0, 0), FALSE); } void EnergyBullet::Spown(float player_posx_, float player_posy_) { if (isAlive) { return; } isAlive = true; pos.Y = player_posy_; pos.X = Widht + gimmickWidht; } void EnergyBullet::IsCollidePlayer(float player_posx_, float player_posy_) { if (powf(player_posx_ - pos.X, 2.0f) <= powf((PlayerWidht + gimmickWidht) / 2, 2.0f) && powf(player_posy_ - PlayerHeight / 2 - pos.Y, 2.0f) <= powf((PlayerHeight + gimmickHeight) / 2, 2.0f)) { gameManager->SetIsCollide(true); isAlive = false; } } void EnergyBullet::Move() { pos.X -= speed; } void EnergyBullet::AddCount() { count++; if (count % 20 == 19) { animationCount += 1; } } bool EnergyBullet::IsFinished() { return pos.X + gimmickWidht < 0; }
[ "nyuki0614@gmail.com" ]
nyuki0614@gmail.com
d7830067513037fe3a125cdb9762766258141ce6
c75e00a4569cf9eb5392f48f81623f6d7991ce3e
/Jungding/Snowboard/ResourceManager/Type/GdsVertexBuffer.cpp
23d9fdd561199c35e69f081ef7ac13d1b2d1d2a6
[]
no_license
rodrigobmg/choding
b90dd63ff3916d969ca625134553e1ff034e1de8
7b559066e0c0989720a507c011bbfd0168c7de8f
refs/heads/master
2021-01-01T03:41:36.274647
2012-04-02T07:03:21
2012-04-02T07:03:21
57,394,584
0
0
null
null
null
null
UTF-8
C++
false
false
1,954
cpp
#include "stdafx.h" GdsVertexBuffer::GdsVertexBuffer() :m_Vertex_Maxcount(0) , m_FVF( GDSVERTEX::FVF ) , m_iStartVertexIndex(0) , m_VertexSize(0) , m_iEndVertexIndex(0) { } GdsVertexBuffer::~GdsVertexBuffer() { vRelease(); } void GdsVertexBuffer::vClear() { m_pBuffer.clear(); m_Vertex_Maxcount = 0; } HRESULT GdsVertexBuffer::vRelease() { Free(); vClear(); return S_OK; } HRESULT GdsVertexBuffer::vLoadResource( LPDIRECT3DDEVICE9 device ) { return S_OK; } void GdsVertexBuffer::Alloc() { if ( m_pVB != NULL && m_Vertex_Maxcount > 0 ) { RESMGR.AllocVertexBuffer( m_pVB , m_Vertex_Maxcount* sizeof(GDSVERTEX) ); if ( m_pVB == NULL ) return; VOID* pI; if( FAILED( m_pVB->Lock( 0 , m_Vertex_Maxcount*sizeof(GDSVERTEX), (void**)&pI, 0 ) ) ) return; GDSVERTEX* p = (GDSVERTEX*)pI; for ( size_t i=0 ; i < m_Vertex_Maxcount ; i++ ) { *p++ = m_pBuffer.at(i); } m_pVB->Unlock(); m_VertexSize = sizeof(GDSVERTEX); m_iEndVertexIndex = m_Vertex_Maxcount; } } void GdsVertexBuffer::Update() { VOID* pI; if( FAILED( m_pVB->Lock( 0 , m_Vertex_Maxcount*sizeof(GDSVERTEX), (void**)&pI, 0 ) ) ) return; GDSVERTEX* p = (GDSVERTEX*)pI; for ( size_t i=0 ; i < m_Vertex_Maxcount ; i++ ) { *p++ = m_pBuffer.at(i); } m_pVB->Unlock(); } void GdsVertexBuffer::Free() { if ( m_pVB ) { RESMGR.FreeVertexBuffer( m_pVB ); m_pBuffer.clear(); } } void GdsVertexBuffer::AddVertex( GDSVERTEX& vertex ) { m_Vertex_Maxcount++; m_pBuffer.push_back( vertex ); } void GdsVertexBuffer::GetVertexFromIndex(int index , GDSVERTEX& vertex ) { if( index < m_pBuffer.size() && index >= 0 ) { vertex = m_pBuffer.at(index); } } void GdsVertexBuffer::SetVertexToIndex( int index , GDSVERTEX& vertex ) { if( index >= 0 && index < m_pBuffer.size() ) { GDSVERTEX& p = m_pBuffer.at(index); p = vertex; } }
[ "LeeOneHyo@gmail.com" ]
LeeOneHyo@gmail.com
28ef5e09a4bd59857ca44aa31ccc2314a16cd3e7
e20151c58b3b035f8cc08e72d292add2581f46f3
/CG_skel_2017/CG_skel_w_MFC/InitShader.cpp
fb10b5ac8bb318b13b720548371bcaeb12474080
[]
no_license
dolbb/ComputerGraphics
f2a1133bb7377fe1d0c9e0df11a510da9a18f1cd
84227b475c85c868742643cb68dd0db8823ee4da
refs/heads/master
2021-09-05T14:36:13.654943
2018-01-28T22:31:27
2018-01-28T22:31:27
108,871,834
1
0
null
null
null
null
UTF-8
C++
false
false
2,354
cpp
#include "stdafx.h" #include "GL/glew.h" #include "GL/freeglut.h" #include "GL/freeglut_ext.h" #include "InitShader.h" #include <iostream> // Create a NULL-terminated string by reading the provided file static char* readShaderSource(const char* shaderFile) { FILE* fp = fopen(shaderFile, "r"); if ( fp == NULL ) { return NULL; } fseek(fp, 0L, SEEK_END); long size = ftell(fp); fseek(fp, 0L, SEEK_SET); char* buf = new char[size + 1]; fread(buf, 1, size, fp); buf[size] = '\0'; fclose(fp); return buf; } // Create a GLSL program object from vertex and fragment shader files GLuint InitShader(const char* vShaderFile, const char* fShaderFile) { struct Shader { const char* filename; GLenum type; GLchar* source; } shaders[2] = { { vShaderFile, GL_VERTEX_SHADER, NULL }, { fShaderFile, GL_FRAGMENT_SHADER, NULL } }; GLuint program = glCreateProgram(); for ( int i = 0; i < 2; ++i ) { Shader& s = shaders[i]; s.source = readShaderSource( s.filename ); if ( shaders[i].source == NULL ) { std::cerr << "Failed to read " << s.filename << std::endl; exit( EXIT_FAILURE ); } GLuint shader = glCreateShader( s.type ); glShaderSource( shader, 1, (const GLchar**) &s.source, NULL ); glCompileShader( shader ); GLint compiled; glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled ); if ( !compiled ) { std::cerr << s.filename << " failed to compile:" << std::endl; GLint logSize; glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize ); char* logMsg = new char[logSize]; glGetShaderInfoLog( shader, logSize, NULL, logMsg ); std::cerr << logMsg << std::endl; delete [] logMsg; exit( EXIT_FAILURE ); } delete [] s.source; glAttachShader( program, shader ); } /* link and error check */ glLinkProgram(program); GLint linked; glGetProgramiv( program, GL_LINK_STATUS, &linked ); if ( !linked ) { std::cerr << "Shader program failed to link" << std::endl; GLint logSize; glGetProgramiv( program, GL_INFO_LOG_LENGTH, &logSize); char* logMsg = new char[logSize]; glGetProgramInfoLog( program, logSize, NULL, logMsg ); std::cerr << logMsg << std::endl; delete [] logMsg; exit( EXIT_FAILURE ); } /* use program object */ glUseProgram(program); return program; }
[ "dolbb@campus.technion.ac.il" ]
dolbb@campus.technion.ac.il
5dbfa5f3fba6ad7d954c1e5a3344935ddf1a15cc
dbec01ac3551d4dd2e1efbed81f6b1701a416fe3
/Models/AgileTrafficLight2/TrafficLightMVP2/MVP2Config/TrafficLightSystem.cpp
196ee0ae9a36924ce2024785785588f855866a46
[ "MIT" ]
permissive
ceobkdn/Agile-Model-Based-Systems-Engineering-Cookbook
8bebdb3892b12c6efc13a0bb8c71f34f0c81c119
459c90a7b5af0aa9c16f517fd6caafc39d83f545
refs/heads/main
2023-03-23T05:58:06.611129
2021-03-16T08:29:14
2021-03-16T08:29:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,144
cpp
/******************************************************************** Rhapsody : 9.0 Login : Bruce Component : TrafficLightMVP2 Configuration : MVP2Config Model Element : TrafficLightSystem //! Generated Date : Tue, 8, Dec 2020 File Path : TrafficLightMVP2/MVP2Config/TrafficLightSystem.cpp *********************************************************************/ //#[ ignore #define NAMESPACE_PREFIX #define _OMSTATECHART_ANIMATED //#] //## auto_generated #include "TrafficLightSystem.h" //#[ ignore #define Default_TrafficLightSystem_TrafficLightSystem_SERIALIZE OM_NO_OP //#] //## package Default //## class TrafficLightSystem TrafficLightSystem::TrafficLightSystem(IOxfActive* theActiveContext) { NOTIFY_REACTIVE_CONSTRUCTOR(TrafficLightSystem, TrafficLightSystem(), 0, Default_TrafficLightSystem_TrafficLightSystem_SERIALIZE); setActiveContext(theActiveContext, false); { { primaryThru.setShouldDelete(false); } { secondaryThru.setShouldDelete(false); } { primaryTurn.setShouldDelete(false); } { secondaryTurn.setShouldDelete(false); } } initRelations(); initStatechart(); } TrafficLightSystem::~TrafficLightSystem() { NOTIFY_DESTRUCTOR(~TrafficLightSystem, true); } ThruLane* TrafficLightSystem::getPrimaryThru() const { return (ThruLane*) &primaryThru; } TurnLane* TrafficLightSystem::getPrimaryTurn() const { return (TurnLane*) &primaryTurn; } ThruLane* TrafficLightSystem::getSecondaryThru() const { return (ThruLane*) &secondaryThru; } TurnLane* TrafficLightSystem::getSecondaryTurn() const { return (TurnLane*) &secondaryTurn; } bool TrafficLightSystem::startBehavior() { bool done = true; done &= primaryThru.startBehavior(); done &= primaryTurn.startBehavior(); done &= secondaryThru.startBehavior(); done &= secondaryTurn.startBehavior(); done &= OMReactive::startBehavior(); return done; } void TrafficLightSystem::initRelations() { { primaryThru.get_pOutThru()->setItsEvLaneDone_ProxyReceptionInterface(secondaryThru.get_pInThru()->getItsEvLaneDone_ProxyReceptionInterface()); } { secondaryThru.get_pOutThru()->setItsEvLaneDone_ProxyReceptionInterface(primaryThru.get_pInThru()->getItsEvLaneDone_ProxyReceptionInterface()); } { primaryThru.get_pTurn()->setItsEvGoTurn_ProxyReceptionInterface(primaryTurn.get_pThru()->getItsEvGoTurn_ProxyReceptionInterface()); }{ primaryTurn.get_pThru()->setItsEvTurnDone_ProxyReceptionInterface(primaryThru.get_pTurn()->getItsEvTurnDone_ProxyReceptionInterface()); primaryTurn.get_pThru()->setItsEvCarArrive_ProxyReceptionInterface(primaryThru.get_pTurn()->getItsEvCarArrive_ProxyReceptionInterface()); } { secondaryThru.get_pTurn()->setItsEvGoTurn_ProxyReceptionInterface(secondaryTurn.get_pThru()->getItsEvGoTurn_ProxyReceptionInterface()); }{ secondaryTurn.get_pThru()->setItsEvTurnDone_ProxyReceptionInterface(secondaryThru.get_pTurn()->getItsEvTurnDone_ProxyReceptionInterface()); secondaryTurn.get_pThru()->setItsEvCarArrive_ProxyReceptionInterface(secondaryThru.get_pTurn()->getItsEvCarArrive_ProxyReceptionInterface()); } } void TrafficLightSystem::initStatechart() { rootState_subState = OMNonState; rootState_active = OMNonState; } void TrafficLightSystem::setActiveContext(IOxfActive* theActiveContext, bool activeInstance) { OMReactive::setActiveContext(theActiveContext, activeInstance); { primaryThru.setActiveContext(theActiveContext, false); secondaryThru.setActiveContext(theActiveContext, false); primaryTurn.setActiveContext(theActiveContext, false); secondaryTurn.setActiveContext(theActiveContext, false); } } void TrafficLightSystem::destroy() { primaryThru.destroy(); primaryTurn.destroy(); secondaryThru.destroy(); secondaryTurn.destroy(); OMReactive::destroy(); } void TrafficLightSystem::rootState_entDef() { { NOTIFY_STATE_ENTERED("ROOT"); NOTIFY_TRANSITION_STARTED("0"); NOTIFY_STATE_ENTERED("ROOT.Ready"); rootState_subState = Ready; rootState_active = Ready; NOTIFY_TRANSITION_TERMINATED("0"); } } IOxfReactive::TakeEventStatus TrafficLightSystem::rootState_processEvent() { IOxfReactive::TakeEventStatus res = eventNotConsumed; switch (rootState_active) { // State Ready case Ready: { if(IS_EVENT_TYPE_OF(exStart_Default_id)) { NOTIFY_TRANSITION_STARTED("1"); NOTIFY_STATE_EXITED("ROOT.Ready"); NOTIFY_STATE_ENTERED("ROOT.sendaction_2"); pushNullTransition(); rootState_subState = sendaction_2; rootState_active = sendaction_2; //#[ state sendaction_2.(Entry) primaryThru.GEN(evGo(TRUE,"Primary Thru")); //#] NOTIFY_TRANSITION_TERMINATED("1"); res = eventConsumed; } } break; // State sendaction_2 case sendaction_2: { if(IS_EVENT_TYPE_OF(OMNullEventId)) { NOTIFY_TRANSITION_STARTED("2"); popNullTransition(); NOTIFY_STATE_EXITED("ROOT.sendaction_2"); NOTIFY_STATE_ENTERED("ROOT.sendaction_3"); pushNullTransition(); rootState_subState = sendaction_3; rootState_active = sendaction_3; //#[ state sendaction_3.(Entry) secondaryThru.GEN(evGo(FALSE,"Secondary")); //#] NOTIFY_TRANSITION_TERMINATED("2"); res = eventConsumed; } } break; // State sendaction_3 case sendaction_3: { if(IS_EVENT_TYPE_OF(OMNullEventId)) { NOTIFY_TRANSITION_STARTED("3"); popNullTransition(); NOTIFY_STATE_EXITED("ROOT.sendaction_3"); NOTIFY_STATE_ENTERED("ROOT.sendaction_4"); pushNullTransition(); rootState_subState = sendaction_4; rootState_active = sendaction_4; //#[ state sendaction_4.(Entry) primaryTurn.GEN(evGo(FALSE,"Primary Turn")); //#] NOTIFY_TRANSITION_TERMINATED("3"); res = eventConsumed; } } break; // State sendaction_4 case sendaction_4: { if(IS_EVENT_TYPE_OF(OMNullEventId)) { NOTIFY_TRANSITION_STARTED("4"); popNullTransition(); NOTIFY_STATE_EXITED("ROOT.sendaction_4"); NOTIFY_STATE_ENTERED("ROOT.sendaction_5"); pushNullTransition(); rootState_subState = sendaction_5; rootState_active = sendaction_5; //#[ state sendaction_5.(Entry) secondaryTurn.GEN(evGo(FALSE,"Secondary Turn")); //#] NOTIFY_TRANSITION_TERMINATED("4"); res = eventConsumed; } } break; // State sendaction_5 case sendaction_5: { if(IS_EVENT_TYPE_OF(OMNullEventId)) { NOTIFY_TRANSITION_STARTED("5"); popNullTransition(); NOTIFY_STATE_EXITED("ROOT.sendaction_5"); NOTIFY_STATE_ENTERED("ROOT.Running"); rootState_subState = Running; rootState_active = Running; NOTIFY_TRANSITION_TERMINATED("5"); res = eventConsumed; } } break; default: break; } return res; } #ifdef _OMINSTRUMENT //#[ ignore void OMAnimatedTrafficLightSystem::serializeRelations(AOMSRelations* aomsRelations) const { aomsRelations->addRelation("primaryThru", true, true); aomsRelations->ADD_ITEM(&myReal->primaryThru); aomsRelations->addRelation("secondaryThru", true, true); aomsRelations->ADD_ITEM(&myReal->secondaryThru); aomsRelations->addRelation("primaryTurn", true, true); aomsRelations->ADD_ITEM(&myReal->primaryTurn); aomsRelations->addRelation("secondaryTurn", true, true); aomsRelations->ADD_ITEM(&myReal->secondaryTurn); } void OMAnimatedTrafficLightSystem::rootState_serializeStates(AOMSState* aomsState) const { aomsState->addState("ROOT"); switch (myReal->rootState_subState) { case TrafficLightSystem::Ready: { Ready_serializeStates(aomsState); } break; case TrafficLightSystem::Running: { Running_serializeStates(aomsState); } break; case TrafficLightSystem::sendaction_2: { sendaction_2_serializeStates(aomsState); } break; case TrafficLightSystem::sendaction_3: { sendaction_3_serializeStates(aomsState); } break; case TrafficLightSystem::sendaction_4: { sendaction_4_serializeStates(aomsState); } break; case TrafficLightSystem::sendaction_5: { sendaction_5_serializeStates(aomsState); } break; default: break; } } void OMAnimatedTrafficLightSystem::sendaction_5_serializeStates(AOMSState* aomsState) const { aomsState->addState("ROOT.sendaction_5"); } void OMAnimatedTrafficLightSystem::sendaction_4_serializeStates(AOMSState* aomsState) const { aomsState->addState("ROOT.sendaction_4"); } void OMAnimatedTrafficLightSystem::sendaction_3_serializeStates(AOMSState* aomsState) const { aomsState->addState("ROOT.sendaction_3"); } void OMAnimatedTrafficLightSystem::sendaction_2_serializeStates(AOMSState* aomsState) const { aomsState->addState("ROOT.sendaction_2"); } void OMAnimatedTrafficLightSystem::Running_serializeStates(AOMSState* aomsState) const { aomsState->addState("ROOT.Running"); } void OMAnimatedTrafficLightSystem::Ready_serializeStates(AOMSState* aomsState) const { aomsState->addState("ROOT.Ready"); } //#] IMPLEMENT_REACTIVE_META_P(TrafficLightSystem, Default, Default, false, OMAnimatedTrafficLightSystem) #endif // _OMINSTRUMENT /********************************************************************* File Path : TrafficLightMVP2/MVP2Config/TrafficLightSystem.cpp *********************************************************************/
[ "45961039+packt-pradeeps@users.noreply.github.com" ]
45961039+packt-pradeeps@users.noreply.github.com
4a986e5576d8281150c170e02dfae074c294f573
bac2e3150dad528691b93c7b7d0ca4959cece801
/others/xPlusYCardProblem.cpp
66acd9b3104f8b7095c34fd1f43418446abd6f4e
[]
no_license
bbvch13531/algorithm
78c566bcac9dd642dd81ad4d6aca10fa50746cfb
cf2737d2ffe7f1ef53841c273ff460e38e397ebf
refs/heads/master
2023-01-06T05:24:55.207768
2022-12-21T11:17:49
2022-12-21T11:17:49
164,439,044
1
0
null
null
null
null
UTF-8
C++
false
false
1,120
cpp
// // xPlusYCardProblem.cpp // Algorithm // // Created by KyungYoung Heo on 2018. 7. 28.. // Copyright © 2018년 KyungYoung Heo. All rights reserved. // #include <iostream> using namespace std; string process(string str); bool isFinished(string str); void flipCard(string& str, int index); int main(void){ string input,res; cin>>input; res = process(input); cout<<res<<endl; return 0; } string process(string str){ int len = str.length(); for(int i = 0; i<len; i++){ for(int j=i; j<len-1; j++){ if(str[j]=='0') continue; else{ flipCard(str,j); flipCard(str,j+1); } cout<<str<<endl; } } if(str[len-1] == '1'){ str[len-1] = '0'; cout<<str<<endl; } return str; } bool isFinished(string str){ for(int i=0; i<str.length() - 1; i++){ if(str[i]=='1') return false; } return true; } void flipCard(string& strp, int index){ if(strp[index] == '1') strp[index]='0'; else strp[index]='1'; return; }
[ "bbvch13531@gmail.com" ]
bbvch13531@gmail.com
91dbe0453bb6260b70f55a27665dad5b9df8f90f
b93f4b53bd4e87b13478eb310a503031e58c47cd
/work-directory/PowerOfThree/main.cpp
8a751ef85849d738910e21bf83a7c3a9fcee428f
[]
no_license
eugenemavrin/leetcode
65437c5d1f92a369ad2ab70ee80c88bbc5d05a01
35516fedbd766ffa4ed686866bffe5fa2d03d305
refs/heads/master
2023-03-23T16:50:59.806695
2021-03-14T21:06:52
2021-03-14T21:06:52
337,873,647
0
0
null
null
null
null
UTF-8
C++
false
false
541
cpp
#include <iostream> using namespace std; class Solution { public: bool isPowerOfThree(int n) { // Runtime: 8 ms, 89% // Memory Usage: 5.9 MB, 81% if (n == 1) return true; const int three = 3; if (n % three != 0 && n > 1) return false; n = n / three; int res = 1; while (res < n) { res *= three; } return res == n; } }; int main() { Solution s; cout << s.isPowerOfThree(1) << endl; return 0; }
[ "e.mavrin@skoltech.ru" ]
e.mavrin@skoltech.ru
23b300e2fca7645fd2965fabd053bd2c19e59e93
9d2c614b95606cf6cc4524544634b14a54cc3cbb
/ExtraStuff/Solarthing/tst/Source/CommonUtilities/CU/Utility/WindowsFunctions.h
aae7a328d69479795678b161d7d160437df3228a
[]
no_license
ellet/Labbar
ed91378b8499b7ece5544e8cc565a02089cc3c46
a9771aded1583dd5b16b2b39d5e5312debb5e512
refs/heads/master
2021-06-19T09:13:18.971703
2016-11-30T21:16:17
2016-11-30T21:16:17
57,976,756
0
0
null
null
null
null
UTF-8
C++
false
false
519
h
#pragma once #include <windows.h> #include "CU/Vectors/Vector4.h" #include <iostream> #ifdef UNICODE typedef std::wstring windowsString; #else typedef std::string windowsString; #endif namespace CommonUtilities { namespace WindowsFunctions { bool CheckIfWindowFullscreen(HWND aWindowID); Vector4f GetWindowSize(HWND aWindowID); windowsString CreateFolder(const windowsString & aFilePathAndFolderName); windowsString CreateFolder(const windowsString & aFilePath, const windowsString & aFolderName); } }
[ "Simon.Skogsrydh.sp15@thegameassembly.com" ]
Simon.Skogsrydh.sp15@thegameassembly.com
a18900ff60b49e9dc118fceaec8b133b3593b69b
d5b7ae5e5f6d7e379040514c10f1f2aa715348bd
/ProcessLib/ThermoMechanics/ThermoMechanicsProcess-impl.h
25fc9223234b694adda3952887e932355f1f6486
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
mahg/ogs
fa27c04633d095fa551654779bfced6df925257a
6409f0f4682c037ba8313cfc9af5925d4bc849e8
refs/heads/master
2021-08-15T15:29:43.977208
2017-11-17T21:47:43
2017-11-17T21:47:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,554
h
/** * \file * * \copyright * Copyright (c) 2012-2017, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #pragma once #include <cassert> #include "BaseLib/Functional.h" #include "ProcessLib/SmallDeformation/CreateLocalAssemblers.h" #include "ThermoMechanicsFEM.h" namespace ProcessLib { namespace ThermoMechanics { template <int DisplacementDim> ThermoMechanicsProcess<DisplacementDim>::ThermoMechanicsProcess( MeshLib::Mesh& mesh, std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler, std::vector<std::unique_ptr<ParameterBase>> const& parameters, unsigned const integration_order, std::vector<std::reference_wrapper<ProcessVariable>>&& process_variables, ThermoMechanicsProcessData<DisplacementDim>&& process_data, SecondaryVariableCollection&& secondary_variables, NumLib::NamedFunctionCaller&& named_function_caller) : Process(mesh, std::move(jacobian_assembler), parameters, integration_order, std::move(process_variables), std::move(secondary_variables), std::move(named_function_caller)), _process_data(std::move(process_data)) { } template <int DisplacementDim> bool ThermoMechanicsProcess<DisplacementDim>::isLinear() const { return false; } template <int DisplacementDim> void ThermoMechanicsProcess<DisplacementDim>::initializeConcreteProcess( NumLib::LocalToGlobalIndexMap const& dof_table, MeshLib::Mesh const& mesh, unsigned const integration_order) { ProcessLib::SmallDeformation::createLocalAssemblers< DisplacementDim, ThermoMechanicsLocalAssembler>( mesh.getElements(), dof_table, _local_assemblers, mesh.isAxiallySymmetric(), integration_order, _process_data); // TODO move the two data members somewhere else. // for extrapolation of secondary variables std::vector<MeshLib::MeshSubsets> all_mesh_subsets_single_component; all_mesh_subsets_single_component.emplace_back( _mesh_subset_all_nodes.get()); _local_to_global_index_map_single_component.reset( new NumLib::LocalToGlobalIndexMap( std::move(all_mesh_subsets_single_component), // by location order is needed for output NumLib::ComponentOrder::BY_LOCATION)); Base::_secondary_variables.addSecondaryVariable( "sigma_xx", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaXX)); Base::_secondary_variables.addSecondaryVariable( "sigma_yy", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaYY)); Base::_secondary_variables.addSecondaryVariable( "sigma_zz", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaZZ)); Base::_secondary_variables.addSecondaryVariable( "sigma_xy", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaXY)); if (DisplacementDim == 3) { Base::_secondary_variables.addSecondaryVariable( "sigma_xz", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaXZ)); Base::_secondary_variables.addSecondaryVariable( "sigma_yz", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtSigmaYZ)); } Base::_secondary_variables.addSecondaryVariable( "epsilon_xx", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonXX)); Base::_secondary_variables.addSecondaryVariable( "epsilon_yy", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonYY)); Base::_secondary_variables.addSecondaryVariable( "epsilon_zz", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonZZ)); Base::_secondary_variables.addSecondaryVariable( "epsilon_xy", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonXY)); if (DisplacementDim == 3) { Base::_secondary_variables.addSecondaryVariable( "epsilon_yz", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonYZ)); Base::_secondary_variables.addSecondaryVariable( "epsilon_xz", makeExtrapolator( 1, getExtrapolator(), _local_assemblers, &ThermoMechanicsLocalAssemblerInterface::getIntPtEpsilonXZ)); } } template <int DisplacementDim> void ThermoMechanicsProcess<DisplacementDim>::assembleConcreteProcess( const double t, GlobalVector const& x, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b) { DBUG("Assemble ThermoMechanicsProcess."); // Call global assembler for each local assembly item. GlobalExecutor::executeMemberDereferenced( _global_assembler, &VectorMatrixAssembler::assemble, _local_assemblers, *_local_to_global_index_map, t, x, M, K, b, _coupling_term); } template <int DisplacementDim> void ThermoMechanicsProcess<DisplacementDim>:: assembleWithJacobianConcreteProcess(const double t, GlobalVector const& x, GlobalVector const& xdot, const double dxdot_dx, const double dx_dx, GlobalMatrix& M, GlobalMatrix& K, GlobalVector& b, GlobalMatrix& Jac) { DBUG("AssembleJacobian ThermoMechanicsProcess."); // Call global assembler for each local assembly item. GlobalExecutor::executeMemberDereferenced( _global_assembler, &VectorMatrixAssembler::assembleWithJacobian, _local_assemblers, *_local_to_global_index_map, t, x, xdot, dxdot_dx, dx_dx, M, K, b, Jac, _coupling_term); } template <int DisplacementDim> void ThermoMechanicsProcess<DisplacementDim>::preTimestepConcreteProcess( GlobalVector const& x, double const t, double const dt) { DBUG("PreTimestep ThermoMechanicsProcess."); _process_data.dt = dt; _process_data.t = t; GlobalExecutor::executeMemberOnDereferenced( &ThermoMechanicsLocalAssemblerInterface::preTimestep, _local_assemblers, *_local_to_global_index_map, x, t, dt); } template <int DisplacementDim> void ThermoMechanicsProcess<DisplacementDim>::postTimestepConcreteProcess( GlobalVector const& x) { DBUG("PostTimestep ThermoMechanicsProcess."); GlobalExecutor::executeMemberOnDereferenced( &ThermoMechanicsLocalAssemblerInterface::postTimestep, _local_assemblers, *_local_to_global_index_map, x); } } // namespace ThermoMechanics } // namespace ProcessLib
[ "dmitri.naumov@ufz.de" ]
dmitri.naumov@ufz.de
5beb47d9607f60a40ee6533b9d77aabcb30be7d9
f8925857535c223bdff7e087767a51f1f9f16657
/Assignment 3/Assignment 3/StringSplitter.h
65c6aa71adb281f91eaae6baf8abde114a9b958d
[ "MIT" ]
permissive
justin-harper/cs122
388c6ac4162b2bf503d1ca68d3c0ca29f0d7fb48
83949bc097cf052ffe6b8bd82002377af4d9cede
refs/heads/master
2021-01-13T05:00:02.683181
2017-02-07T04:21:38
2017-02-07T04:21:38
81,165,793
0
0
null
null
null
null
UTF-8
C++
false
false
1,320
h
/* Assignment: 3 Description: Paycheck Calculator Author: Justin Harper WSU ID: 10696738 Completion Time: 8hrs In completing this program, I received help from the following people: myself version 1.0 I am happy with this version! */ #ifndef STRINGSPLITTER_H #define STRINGSPLITTER_H #include <string> #include <vector> using namespace std; class StringSplitter { public: //Breaks apart the supplied text based on the given delimiter static vector<string> split(string text, string delimiter) { //vectors are dynamically expanding arrays vector<string> pieces; //find the first delimiter int location = text.find(delimiter); //we are starting at the beginning of our string int start = 0; //go until we have no more delimiters while(location != string::npos) { //add the current piece to our list of pieces string piece = text.substr(start, location - start); pieces.push_back(piece); //update our index markers for the next round start = location + 1; location = text.find(delimiter, start); } //at the end of our loop, we're going to have one trailing piece to take care of. //handle that now. string piece = text.substr(start, location - start); pieces.push_back(piece); //now, return the completed vector return pieces; } }; #endif
[ "justin.harper@outlook.com" ]
justin.harper@outlook.com
178c93cd235149f23668e02cfba704a73e3cad94
71c8e39d9d849a2e4ec94ff8c3f0120d9da47686
/arduino/blink_isr/sketch_jan23d/sketch_jan23d.ino
e36018e7fcb5ef398fd1ed975439798136d492e9
[ "MIT" ]
permissive
joshcol9232/AL-FanControl
d588ba3e619037d02a53b5d82a0b8cd2dec51a5b
ea01a3318bf07deeb78df5eab99e7cef3bf8fcc2
refs/heads/master
2023-05-31T22:04:14.712753
2021-06-09T18:09:16
2021-06-09T18:09:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
816
ino
/* Arduino 101: timer and interrupts 1: Timer1 compare match interrupt example more infos: http://www.letmakerobots.com/node/28278 created by RobotFreak */ #define ledPin 17 void setup() { pinMode(ledPin, OUTPUT); // initialize timer1 noInterrupts(); // disable all interrupts TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; OCR1A = 31250; // compare match register 16MHz/256/2Hz TCCR1B |= (1 << WGM12); // CTC mode TCCR1B |= (1 << CS12); // 256 prescaler TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt interrupts(); // enable all interrupts } ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine { digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle LED pin } void loop() { // your program here... }
[ "bengt.lueers@gmail.com" ]
bengt.lueers@gmail.com
7387368f142152a7eb86cf2e026adda251929d8e
11372f47584ed7154697ac3b139bf298cdc10675
/CF练习/CF1238/A.cpp
c373d311b2a7cfb84572878c468adeb80b6cf25e
[]
no_license
strategist614/ACM-Code
b5d893103e4d2ea0134fbaeb0cbd18c0fec06d12
d1e0f36dab47f649e2fade5e7ff23cfd0e8c8e56
refs/heads/master
2020-12-20T04:21:50.750182
2020-01-24T07:43:50
2020-01-24T07:45:08
235,958,679
0
0
null
null
null
null
UTF-8
C++
false
false
260
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { long long x, y; cin >> x >> y; if (x - y > 1) puts("YES"); else puts("NO"); } return 0; }
[ "syf981002@gmail.com" ]
syf981002@gmail.com
3b57e499468d066328ed6bdee28d49e6f46a233f
47a0a6676349129af4873dc1951531bd76b28228
/base/memory/read_only_shared_memory_region.cc
8c0d27609c3fe60031329c32ad77fdf6d48af3f8
[ "BSD-3-Clause" ]
permissive
Kaleb8812/chromium
f61c4a42e211ba4df707a45388a62e70dcae9cd7
4c098731f333f0d38b403af55133182d626be182
refs/heads/master
2022-12-23T01:13:33.470865
2018-04-06T11:44:50
2018-04-06T11:44:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,847
cc
// Copyright 2018 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 "base/memory/read_only_shared_memory_region.h" #include <utility> #include "base/memory/shared_memory.h" #include "build/build_config.h" namespace base { // static MappedReadOnlyRegion ReadOnlySharedMemoryRegion::Create(size_t size) { subtle::PlatformSharedMemoryRegion handle = subtle::PlatformSharedMemoryRegion::CreateWritable(size); if (!handle.IsValid()) return {}; void* memory_ptr = nullptr; size_t mapped_size = 0; if (!handle.MapAt(0, handle.GetSize(), &memory_ptr, &mapped_size)) return {}; WritableSharedMemoryMapping mapping(memory_ptr, mapped_size, handle.GetGUID()); #if defined(OS_MACOSX) && !defined(OS_IOS) handle.ConvertToReadOnly(memory_ptr); #else handle.ConvertToReadOnly(); #endif // defined(OS_MACOSX) && !defined(OS_IOS) ReadOnlySharedMemoryRegion region(std::move(handle)); if (!region.IsValid()) return {}; return {std::move(region), std::move(mapping)}; } // static ReadOnlySharedMemoryRegion ReadOnlySharedMemoryRegion::Deserialize( subtle::PlatformSharedMemoryRegion handle) { return ReadOnlySharedMemoryRegion(std::move(handle)); } // static subtle::PlatformSharedMemoryRegion ReadOnlySharedMemoryRegion::TakeHandleForSerialization( ReadOnlySharedMemoryRegion region) { return std::move(region.handle_); } ReadOnlySharedMemoryRegion::ReadOnlySharedMemoryRegion() = default; ReadOnlySharedMemoryRegion::ReadOnlySharedMemoryRegion( ReadOnlySharedMemoryRegion&& region) = default; ReadOnlySharedMemoryRegion& ReadOnlySharedMemoryRegion::operator=( ReadOnlySharedMemoryRegion&& region) = default; ReadOnlySharedMemoryRegion::~ReadOnlySharedMemoryRegion() = default; ReadOnlySharedMemoryRegion ReadOnlySharedMemoryRegion::Duplicate() { return ReadOnlySharedMemoryRegion(handle_.Duplicate()); } ReadOnlySharedMemoryMapping ReadOnlySharedMemoryRegion::Map() { return MapAt(0, handle_.GetSize()); } ReadOnlySharedMemoryMapping ReadOnlySharedMemoryRegion::MapAt(off_t offset, size_t size) { if (!IsValid()) return {}; void* memory = nullptr; size_t mapped_size = 0; if (!handle_.MapAt(offset, size, &memory, &mapped_size)) return {}; return ReadOnlySharedMemoryMapping(memory, mapped_size, handle_.GetGUID()); } bool ReadOnlySharedMemoryRegion::IsValid() const { return handle_.IsValid(); } ReadOnlySharedMemoryRegion::ReadOnlySharedMemoryRegion( subtle::PlatformSharedMemoryRegion handle) : handle_(std::move(handle)) { CHECK_EQ(handle_.GetMode(), subtle::PlatformSharedMemoryRegion::Mode::kReadOnly); } } // namespace base
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a2b27b38a4466567c1eeb26fe500d0b5aac70993
afdd66a3c6c71be75b1e6bf12904c9216646be66
/CApp.h
cb6b467ed8949a0d07d7057eba4c96962cf13719
[]
no_license
thebum06/Tic-Tac-Toe-for-GCGPG
e2cedd337133bf8227dc3c63e3df723d696d7b9c
980f29830ed258790905fe7410aec47bc3b7a685
refs/heads/master
2021-01-01T18:34:20.661959
2012-04-13T23:54:36
2012-04-13T23:54:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,231
h
#ifndef _CAPP_H_ #define _CAPP_H_ #include <SDL/SDL.h> #include <ctime> #include <cstdlib> #include "CEvent.h" #include "CSurface.h" class CApp : public CEvent { private: bool Running; bool Winner; bool Draw; bool AI, AISelect; SDL_Surface* Surf_Display; private: SDL_Surface* Surf_Grid; SDL_Surface* Surf_X; SDL_Surface* Surf_O; SDL_Surface* Surf_XWin; SDL_Surface* Surf_OWin; SDL_Surface* Surf_Draw; SDL_Surface* Surf_Again; SDL_Surface* Surf_AI; private: int Grid[9]; int CurrentPlayer, StartPlayer; enum { GRID_TYPE_NONE = 0, GRID_TYPE_X, GRID_TYPE_O }; public: CApp(); int OnExecute(); public: bool OnInit(); void OnEvent(SDL_Event* Event); void OnExit(); void OnLButtonDown(int mX, int mY); void OnLoop(); void Victory(); void Computer(); void OnRender(); void OnCleanup(); public: void Reset(); void SetCell(int ID, int Type); }; #endif
[ "thebum06@hotmail.com" ]
thebum06@hotmail.com
eba666c5e540ea9a66766b5743cbf574b5bd8cb1
8b7ccd22aa258b016e4317d222dce9eac0709f36
/example-advanced-servo/src/Servo.h
d4f2d0a0c0d40b5f3d497ab449f1867f9026b5b4
[ "BSD-2-Clause" ]
permissive
WatershedArts/ofxAdafruitPWMBonnet
c0145a77959f90d1ef9c7950c28734eb4e618341
5e6b827e34d207273b108c3e428e5e76b80fde27
refs/heads/master
2020-03-29T19:26:53.235730
2018-09-27T16:27:45
2018-09-27T16:27:45
150,263,686
1
0
null
null
null
null
UTF-8
C++
false
false
3,744
h
// // Servo.h // // Created by David Haylock on 26/09/2018. // #include "ofMain.h" #ifndef Servo_h #define Servo_h class Servo { public: /** Default Constructor */ //-------------------------------------------------------------- Servo() { } /** Deconstructor */ //-------------------------------------------------------------- ~Servo() {} /** Init Constructor */ //-------------------------------------------------------------- Servo(u_int16_t ctrlAddress, u_int16_t pinNo, glm::vec2 pos, glm::vec2 size, float initAngle) { init(ctrlAddress, pinNo, pos, size, initAngle); } /** Initialize */ //-------------------------------------------------------------- void init(u_int16_t ctrlAddress, u_int16_t pinNo, glm::vec2 pos, glm::vec2 size, float initAngle) { this->ctrlAddress = ctrlAddress; this->pinNo = pinNo; this->pos = pos; this->size = size; this->currentAngle = initAngle; } /** Returns the Current Angle of the Servo @return Servo Angle */ //-------------------------------------------------------------- int getCurrentAngle() { return currentAngle; } /** Get the Connected Pin Number @return pin no */ //-------------------------------------------------------------- u_int16_t getCtrlAddress() { return ctrlAddress; } /** Get the Connected Pin Number @return pin no */ //-------------------------------------------------------------- u_int16_t getPin() { return pinNo; } /** Returns the Size of the Servo @return size */ //-------------------------------------------------------------- glm::vec2 getSize() { return size; } /** Returns the Position of the Servo @return pos */ //-------------------------------------------------------------- glm::vec2 getPosition() { return pos; } /** Set the New Angle @param angle angle */ //-------------------------------------------------------------- void setAngle(float angle) { this->currentAngle = angle; } /** Draw Servo */ //-------------------------------------------------------------- void drawServo() { ofPushMatrix(); { ofTranslate(pos.x,pos.y); ofPushStyle(); ofNoFill(); ofSetColor(255); ofDrawRectangle(-(size.x/2),-(size.y/2),size.x,size.y); ofPushMatrix(); ofTranslate(0,-(size.y/3)); { ofPushMatrix(); { ofTranslate(0,0); ofRotateZDeg(currentAngle); ofPushMatrix(); { ofDrawCircle(0,0,(size.y/3)); ofDrawCircle(0,0,5); ofDrawLine(0,0,0,-(size.y/3)); } ofPopMatrix(); } ofPopMatrix(); } ofPopMatrix(); ofPopStyle(); } ofPopMatrix(); ofSetColor(255,255,0); stringstream ss; ss << "Servo " << pinNo << endl; ss << "CTRL " << ctrlAddress << endl; ofDrawBitmapString(ss.str(),pos.x-(size.x/2)-7,pos.y+size.y/2+15); } private: u_int16_t ctrlAddress; u_int16_t pinNo; glm::vec2 pos; glm::vec2 size; float currentAngle; }; #endif /* Servo_h */
[ "david.haylock@watershed.co.uk" ]
david.haylock@watershed.co.uk
87e7b59a8bf9eb09acdfb7788046e97b9c084a9e
cc9ae71207dc667c2e0be27671ced5c86f2f71a3
/test/oldstudy/class_fun.cpp
c450701affda8c3b7a4499a732b4d0fa809bd115
[]
no_license
xm0629/c-study
aed8480aa30b35637bfca307e009eb8b827b328d
26183be9c91b2b53bd71b6693fe6d39823bc5d63
refs/heads/master
2020-04-09T11:35:48.047562
2019-03-30T15:27:01
2019-03-30T15:27:01
160,316,327
1
0
null
null
null
null
UTF-8
C++
false
false
645
cpp
// 带参数的构造函数 # include <iostream> using namespace std; class Box { public: Box(int, int, int); // 带参数的构造函数 int volume(); private: int height; int width; int length; }; //在类外定义带参数的构造函数 Box::Box(int h, int w, int len) { height = h; width = w; length = len; } int Box::volume() { return height*width*length; } int main() { Box box1(12, 25, 30); cout << "The volume of box1 is " << box1.volume() << endl; Box box2(15, 30, 21); cout << "The volume of box2 is " << box2.volume() << endl; return 0; }
[ "920972751@qq.com" ]
920972751@qq.com
dcec21da638b1dd7b38921c5d38e9b3f5daf6d1b
f5d3a2db357c4ce5f34bfdb0866c058182e30b72
/src/imagemanip.cpp
270aa3555d7990b3b2ab3c45ab02764bc6eacae4
[]
no_license
JoaquimGuerra/fingerPrint
40f56fd0d033aa745a33d21ad6fe1c7e02a2167c
73264a2c2c3506dd13afdfd39e31b5f25013b9fa
refs/heads/master
2021-01-18T16:21:45.383654
2016-02-08T22:37:14
2016-02-08T22:37:14
51,331,792
0
0
null
2016-02-08T22:25:55
2016-02-08T22:25:55
null
GB18030
C++
false
false
41,045
cpp
/*############################################################################# * 文件名:imagemanip.cpp * 功能: 实现了主要的图像处理操作 #############################################################################*/ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "imagemanip.h" #ifndef min #define min(a,b) (((a)<(b))?(a):(b)) #endif /* 宏定义 */ #define PIJKL p[i+k + (j+l)*nSizeX] /****************************************************************************** * 功能:图像缩放操作 * 参数:image 指纹图像 * size 缩放的图像块大小 * tolerance 消去直方图的边界 * 返回:错误编号 ******************************************************************************/ FvsError_t ImageLocalStretch(FvsImage_t image, const FvsInt_t size, const FvsInt_t tolerance) { /* 定义一些变量 */ int nSizeX = ImageGetWidth(image) - size + 1; int nSizeY = ImageGetHeight(image) - size + 1; FvsInt_t i, j, t, l; FvsInt_t sum, denom; FvsByte_t a = 0; FvsInt_t k = 0; FvsByte_t b = 255; int hist[256]; FvsByte_t* p = ImageGetBuffer(image); if (p == NULL) return FvsMemory; for (j = 0; j < nSizeY; j += size) { for (i = 0; i < nSizeX; i += size) { /* 计算直方图 */ memset(hist, 0, 256 * sizeof(int)); for (l = 0; l < size; l++) for (k = 0; k < size; k++) hist[PIJKL]++; /* 伸缩 */ for (k = 0, sum = 0; k < 256; k++) { sum += hist[k]; a = (FvsByte_t)k; if (sum > tolerance) break; } for (k = 255, sum = 0; k >= 0; k--) { sum += hist[k]; b = (FvsByte_t)k; if (sum > tolerance) break; } denom = (FvsInt_t)(b - a); if (denom != 0) { for (l = 0; l < size; l++) { for (k = 0; k < size; k++) { if (PIJKL < a) PIJKL = a; if (PIJKL > b) PIJKL = b; t = (FvsInt_t)((((PIJKL) - a) * 255) / denom); PIJKL = (FvsByte_t)(t); } } } } } return FvsOK; } #define P(x,y) ((int32_t)p[(x)+(y)*pitch]) /****************************************************************************** ** 估算脊线的方向 ** 给定一个归一化的指纹图像,算法的主要步骤如下: ** ** 1 - 将G分成大小为 w x w - (15 x 15) 的块; ** ** 2 - 计算每个象素 (i,j)的梯度 dx(i,j) 和 dy(i,j) , ** 根据计算的需求,梯度算子可以从简单的Sobel算子到复杂的Marr-Hildreth 算子。 ** ** 3 - 估算优势方向(i,j), 使用如下的操作: ** ** i+w/2 j+w/2 ** --- --- ** \ \ ** Nx(i,j) = -- -- 2 dx(u,v) dy(u,v) ** / / ** --- --- ** u=i-w/2 v=j-w/2 ** ** i+w/2 j+w/2 ** --- --- ** \ \ ** Ny(i,j) = -- -- dx(u,v) - dy(u,v) ** / / ** --- --- ** u=i-w/2 v=j-w/2 ** ** 1 -1 / Nx(i,j) \ ** Theta(i,j) = - tan | ------- | ** 2 \ Ny(i,j) / ** ** 这里,Theta(i,j)是局部脊线方向的最小方差估计,以像素 (i,j) 为中心。 ** 从数学的角度看,它代表傅立叶频谱中直角占有时的方向。 ** ** 4 - 由于有噪声,脊线的中断,细节点等等的存在,在输入图像中,对局部脊线 ** 方向的估计并不总是正确的。由于局部脊线方向变化缓慢,所以可以用低通 ** 滤波器来修正不正确的脊线方向。为了运用低通滤波器,方向图必须转换成 ** 连续的矢量域,定义如下: ** Phi_x(i,j) = cos( 2 x theta(i,j) ) ** Phi_y(i,j) = sin( 2 x theta(i,j) ) ** 在矢量域,可以用如下的卷积低通滤波: ** Phi2_x(i,j) = (W @ Phi_x) (i,j) ** Phi2_y(i,j) = (W @ Phi_y) (i,j) ** W是一个二维的低通滤波器。 ** ** 5 - 用如下公式计算 (i,j) 处的方向: ** ** 1 -1 / Phi2_y(i,j) \ ** O(i,j) = - tan | ----------- | ** 2 \ Phi2_x(i,j) / ** ** 用这个算法可以得到相当平滑的方向图 ** */ static FvsError_t FingerprintDirectionLowPass(FvsFloat_t* theta, FvsFloat_t* out, FvsInt_t nFilterSize, FvsInt_t w, FvsInt_t h) { FvsError_t nRet = FvsOK; FvsFloat_t* filter = NULL; FvsFloat_t* phix = NULL; FvsFloat_t* phiy = NULL; FvsFloat_t* phi2x = NULL; FvsFloat_t* phi2y = NULL; FvsInt_t fsize = nFilterSize * 2 + 1; size_t nbytes = (size_t)(w * h * sizeof(FvsFloat_t)); FvsFloat_t nx, ny; FvsInt_t val; FvsInt_t i, j, x, y; filter = (FvsFloat_t*)malloc((size_t)fsize * fsize * sizeof(FvsFloat_t)); phix = (FvsFloat_t*)malloc(nbytes); phiy = (FvsFloat_t*)malloc(nbytes); phi2x = (FvsFloat_t*)malloc(nbytes); phi2y = (FvsFloat_t*)malloc(nbytes); if (filter == NULL || phi2x == NULL || phi2y == NULL || phix == NULL || phiy == NULL) nRet = FvsMemory; else { /* 置 0 */ memset(filter, 0, (size_t)fsize * fsize * sizeof(FvsFloat_t)); memset(phix, 0, nbytes); memset(phiy, 0, nbytes); memset(phi2x, 0, nbytes); memset(phi2y, 0, nbytes); /* 步骤4 */ for (y = 0; y < h; y++) for (x = 0; x < w; x++) { val = x + y * w; phix[val] = cos(theta[val]); phiy[val] = sin(theta[val]); } /* 构造低通滤波器 */ nx = 0.0; for (j = 0; j < fsize; j++) for (i = 0; i < fsize; i++) { filter[j * fsize + i] = 1.0; nx += filter[j * fsize + i]; /* 系数和 */ } if (nx > 1.0) { for (j = 0; j < fsize; j++) for (i = 0; i < fsize; i++) /* 归一化结果 */ filter[j * fsize + i] /= nx; } /* 低通滤波 */ for (y = 0; y < h - fsize; y++) for (x = 0; x < w - fsize; x++) { nx = 0.0; ny = 0.0; for (j = 0; j < fsize; j++) for (i = 0; i < fsize; i++) { val = (x + i) + (j + y) * w; nx += filter[j * fsize + i] * phix[val]; ny += filter[j * fsize + i] * phiy[val]; } val = x + y * w; phi2x[val] = nx; phi2y[val] = ny; } /* 销毁 phix, phiy */ if (phix != NULL) { free(phix); phix = NULL; } if (phiy != NULL) { free(phiy); phiy = NULL; } /* 步骤5 */ for (y = 0; y < h - fsize; y++) for (x = 0; x < w - fsize; x++) { val = x + y * w; out[val] = atan2(phi2y[val], phi2x[val]) * 0.5; } } if (phix != NULL) free(phix); if (phiy != NULL) free(phiy); if (phi2x != NULL) free(phi2x); if (phi2y != NULL) free(phi2y); if (filter != NULL)free(filter); return nRet; } /****************************************************************************** * 功能:计算指纹图像脊线的方向。 该算法在许多论文中都有描述,如果图像做了归一化,并且对比度较高, 则最后的处理效果也较好。 方向的值在-PI/2和PI/2之间,弧度和脊并不相同。 选取的块越大,分析的效果也越好,但所需的处理计算时间也越长。 由于指纹图像中脊线方向的变化比较缓慢,所以低通滤波器可以较好的 过虑掉方向中的噪声和错误。 * 参数:image 指向图像对象的指针 * field 指向浮点域对象的指针,保存结果 * nBlockSize 块大小 * nFilterSize 滤波器大小 * 返回:错误编号 ******************************************************************************/ FvsError_t FingerprintGetDirection(const FvsImage_t image, FvsFloatField_t field, const FvsInt_t nBlockSize, const FvsInt_t nFilterSize) { /* 输入图像的宽度和高度 */ FvsInt_t w = ImageGetWidth (image); FvsInt_t h = ImageGetHeight(image); FvsInt_t pitch = ImageGetPitch (image); FvsByte_t* p = ImageGetBuffer(image); FvsInt_t i, j, u, v, x, y; FvsFloat_t dx[16][16]; FvsFloat_t dy[16][16]; // FvsFloat_t dx[(nBlockSize*2+1)][(nBlockSize*2+1)]; // FvsFloat_t dy[(nBlockSize*2+1)][(nBlockSize*2+1)]; FvsFloat_t nx, ny; FvsFloat_t* out; FvsFloat_t* theta = NULL; FvsError_t nRet = FvsOK; /* 输出图像 */ nRet = FloatFieldSetSize(field, w, h); if (nRet != FvsOK) return nRet; nRet = FloatFieldClear(field); if (nRet != FvsOK) return nRet; out = FloatFieldGetBuffer(field); /* 为方向数组申请内存 */ if (nFilterSize > 0) { theta = (FvsFloat_t*)malloc(w * h * sizeof(FvsFloat_t)); if (theta != NULL) memset(theta, 0, (w * h * sizeof(FvsFloat_t))); } /* 内存错误,返回 */ if (out == NULL || (nFilterSize > 0 && theta == NULL)) nRet = FvsMemory; else { /* 1 - 图像分块 */ for (y = nBlockSize + 1; y < h - nBlockSize - 1; y++) for (x = nBlockSize + 1; x < w - nBlockSize - 1; x++) { /* 2 - 计算梯度 */ for (j = 0; j < (nBlockSize * 2 + 1); j++) for (i = 0; i < (nBlockSize * 2 + 1); i++) { dx[i][j] = (FvsFloat_t) (P(x + i - nBlockSize, y + j - nBlockSize) - P(x + i - nBlockSize - 1, y + j - nBlockSize)); dy[i][j] = (FvsFloat_t) (P(x + i - nBlockSize, y + j - nBlockSize) - P(x + i - nBlockSize, y + j - nBlockSize - 1)); } /* 3 - 计算方向 */ nx = 0.0; ny = 0.0; for (v = 0; v < (nBlockSize * 2 + 1); v++) for (u = 0; u < (nBlockSize * 2 + 1); u++) { nx += 2 * dx[u][v] * dy[u][v]; ny += dx[u][v] * dx[u][v] - dy[u][v] * dy[u][v]; } /* 计算角度 (-pi/2 .. pi/2) */ if (nFilterSize > 0) theta[x + y * w] = atan2(nx, ny); else out[x + y * w] = atan2(nx, ny) * 0.5; } if (nFilterSize > 0) nRet = FingerprintDirectionLowPass(theta, out, nFilterSize, w, h); } if (theta != NULL) free(theta); return nRet; } /* 指纹频率域 */ /****************************************************************************** ** 这个步骤里,我们估计指纹脊线的频率。在局部邻域里,没有凸现的细节点或者孤点, ** 沿着脊线和谷底,可以用一个正弦曲线波形作为模型,因此,局部脊线频率是指纹图 ** 像的另一个本质的特征。对指纹图像G进行归一化,O是其方向图,估算局部脊线频率 ** 的步骤如下: ** ** 1 - 图像分块 w x w - (16 x 16) ** ** 2 - 对每块,计算大小为l x w (32 x 16)的方向图窗口 ** ** 3 - 对中心在 (i,j) 的每块, 计算脊线和谷底的 x-signature ** X[0], X[1], ... X[l-1] 采用如下公式: ** ** --- w-1 ** 1 \ ** X[k] = - -- G (u, v), k = 0, 1, ..., l-1 ** w / ** --- d=0 ** ** u = i + (d - w/2).cos O(i,j) + (k - l/2).sin O(i,j) ** ** v = j + (d - w/2).sin O(i,j) - (k - l/2).cos O(i,j) ** ** 如果方向图窗口中没有细节点和孤立的点,则x-signature形成了一个离散 ** 的正弦曲线波,与方向图中脊线和谷底的频率一样。因此,脊线和谷底的 ** 频率可以由x-signature来估计。设T(i,j)是两个峰顶的平均距离,则频率 ** OHM(i,j)可以这样计算:OHM(i,j) = 1 / T(i,j)。 ** ** 如果没有两个连续的峰顶,则频率置为-1,说明其无效。 ** ** 4 - 对于一个指纹图像而言,脊线频率的值在一个范围之内变动,比如说对于500 ** dpi的图像,变动范围为[1/3, 1/25],因此,如果估计出的频率不在这个范 ** 围内,说明频率估计无效,同意置为-1。 ** ** 5 - 如果某块有断点或者细节点,则不会有正弦曲线,其频率可以由邻块的频率 ** 插值估计(比如说高斯函数,均值为0,方差为9,宽度为7)。 ** ** 6 - 脊线内部距离变化缓慢,可以用低通滤波器 ** */ /* 宽度 */ #define BLOCK_W 16 #define BLOCK_W2 8 /* 长度 */ #define BLOCK_L 32 #define BLOCK_L2 16 #define EPSILON 0.0001 #define LPSIZE 3 #define LPFACTOR (1.0/((LPSIZE*2+1)*(LPSIZE*2+1))) FvsError_t FingerprintGetFrequency(const FvsImage_t image, const FvsFloatField_t direction, FvsFloatField_t frequency) { /* 输入图像的宽度和高度 */ FvsError_t nRet = FvsOK; FvsInt_t w = ImageGetWidth (image); FvsInt_t h = ImageGetHeight(image); FvsInt_t pitchi = ImageGetPitch (image); FvsByte_t* p = ImageGetBuffer(image); FvsFloat_t* out; FvsFloat_t* freq; FvsFloat_t* orientation = FloatFieldGetBuffer(direction); FvsInt_t x, y, u, v, d, k; size_t size; if (p == NULL) return FvsMemory; /* 输出图像的内存申请 */ nRet = FloatFieldSetSize(frequency, w, h); if (nRet != FvsOK) return nRet; (void)FloatFieldClear(frequency); freq = FloatFieldGetBuffer(frequency); if (freq == NULL) return FvsMemory; /* 输出的内存申请 */ size = w * h * sizeof(FvsFloat_t); out = (FvsFloat_t*)malloc(size); if (out != NULL) { FvsFloat_t dir = 0.0; FvsFloat_t cosdir = 0.0; FvsFloat_t sindir = 0.0; FvsInt_t peak_pos[BLOCK_L]; /* 顶点 */ FvsInt_t peak_cnt; /* 顶点数目 */ FvsFloat_t peak_freq; /* 顶点频率 */ FvsFloat_t Xsig[BLOCK_L]; /* x signature */ FvsFloat_t pmin, pmax; memset(out, 0, size); memset(freq, 0, size); /* 1 - 图像分块 BLOCK_W x BLOCK_W - (16 x 16) */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { /* 2 - 脊线方向的窗口 l x w (32 x 16) */ // dir = orientation[(x+BLOCK_W2) + (y+BLOCK_W2)*w]; dir = orientation[(x) + (y) * w]; cosdir = cos(dir); sindir = sin(dir); /* 3 - 计算 x-signature X[0], X[1], ... X[l-1] */ for (k = 0; k < BLOCK_L; k++) { Xsig[k] = 0.0; for (d = 0; d < BLOCK_W; d++) { u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir - (d - BLOCK_W2) * sindir); v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir + (d - BLOCK_W2) * cosdir); /* clipping */ if (u < 0) u = 0; else if (u > w - 1) u = w - 1; if (v < 0) v = 0; else if (v > h - 1) v = h - 1; Xsig[k] += p[u + (v * pitchi)]; } Xsig[k] /= BLOCK_W; } /* 计算 T(i,j) */ /* 寻找 x signature 中的顶点 */ peak_cnt = 0; pmax = pmin = Xsig[0]; for (k = 1; k < BLOCK_L; k++) { if (pmin > Xsig[k]) pmin = Xsig[k]; if (pmax < Xsig[k]) pmax = Xsig[k]; } if ((pmax - pmin) > 64.0) { for (k = 1; k < BLOCK_L - 1; k++) if ((Xsig[k - 1] < Xsig[k]) && (Xsig[k] >= Xsig[k + 1])) { peak_pos[peak_cnt++] = k; } } /* 计算均值 */ peak_freq = 0.0; if (peak_cnt >= 2) { for (k = 0; k < peak_cnt - 1; k++) peak_freq += peak_pos[k + 1] - peak_pos[k]; peak_freq /= peak_cnt - 1; } /* 4 - 验证频率范围 [1/25-1/3] */ /* 可以扩大到 [1/30-1/2] */ if (peak_freq > 30.0) out[x + y * w] = 0.0; else if (peak_freq < 2.0) out[x + y * w] = 0.0; else out[x + y * w] = 1.0 / peak_freq; } /* 5 - 未知点 */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { if (out[x + y * w] < EPSILON) { if (out[x + (y - 1)*w] > EPSILON) { out[x + (y * w)] = out[x + (y - 1) * w]; } else { if (out[x - 1 + (y * w)] > EPSILON) out[x + (y * w)] = out[x - 1 + (y * w)]; } } } /* 6 - 频率插值 */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { k = x + y * w; peak_freq = 0.0; for ( v = -LPSIZE; v <= LPSIZE; v++) for ( u = -LPSIZE; u <= LPSIZE; u++) peak_freq += out[(x + u) + (y + v) * w]; freq[k] = peak_freq * LPFACTOR; } free(out); } return nRet; } /****************************************************************************** * 功能:获取指纹图像的有效区域,以进行进一步的处理。 * 如果某个区域不可用用,则掩码置为0,包括如下区域: * 边界,背景点,图像质量很差的区域。 * 有效区域的掩码置为255。 * 参数:image 指纹图像 * direction 脊线方向 * frequency 脊线频率 * mask 输出的掩码 * 返回:错误编号 ******************************************************************************/ FvsError_t FingerprintGetMask(const FvsImage_t image, const FvsFloatField_t direction, const FvsFloatField_t frequency, FvsImage_t mask) { FvsError_t nRet = FvsOK; FvsFloat_t freqmin = 1.0 / 25; FvsFloat_t freqmax = 1.0 / 3; /* 输入图像的宽度高度 */ FvsInt_t w = ImageGetWidth (image); FvsInt_t h = ImageGetHeight(image); FvsByte_t* out; FvsInt_t pitchout; FvsInt_t pos, posout, x, y; FvsFloat_t* freq = FloatFieldGetBuffer(frequency); if (freq == NULL) return FvsMemory; /* 需要做改进:检查 */ nRet = ImageSetSize(mask, w, h); if (nRet == FvsOK) nRet = ImageClear(mask); out = ImageGetBuffer(mask); if (out == NULL) return FvsMemory; if (nRet == FvsOK) { pitchout = ImageGetPitch(mask); for (y = 0; y < h; y++) for (x = 0; x < w; x++) { pos = x + y * w; posout = x + y * pitchout; out[posout] = 0; if (freq[pos] >= freqmin && freq[pos] <= freqmax) { out[posout] = 255; } } /* 补洞 */ for (y = 0; y < 4; y++) (void)ImageDilate(mask); /* 去除边界 */ for (y = 0; y < 12; y++) (void)ImageErode(mask); } return nRet; } /* 细化算法 */ #undef P #define P(x,y) ((x)+(y)*pitch) #define REMOVE_P { p[P(x,y)]=0x80; changed = FvsTrue; } /****************************************************************************** ** 邻域点定义如下: ** 9 2 3 ** 8 1 4 ** 7 6 5 ******************************************************************************/ /* 宏定义 */ #define P1 p[P(x ,y )] #define P2 p[P(x ,y-1)] #define P3 p[P(x+1,y-1)] #define P4 p[P(x+1,y )] #define P5 p[P(x+1,y+1)] #define P6 p[P(x ,y+1)] #define P7 p[P(x-1,y+1)] #define P8 p[P(x-1,y )] #define P9 p[P(x-1,y-1)] FvsError_t ImageRemoveSpurs(FvsImage_t image) { FvsInt_t w = ImageGetWidth(image); FvsInt_t h = ImageGetHeight(image); FvsInt_t pitch = ImageGetPitch(image); FvsByte_t* p = ImageGetBuffer(image); FvsInt_t x, y, n, t, c; c = 0; do { n = 0; for (y = 1; y < h - 1; y++) for (x = 1; x < w - 1; x++) { if( p[P(x, y)] == 0xFF) { t = 0; if (P3 == 0 && P2 != 0 && P4 == 0) t++; if (P5 == 0 && P4 != 0 && P6 == 0) t++; if (P7 == 0 && P6 != 0 && P8 == 0) t++; if (P9 == 0 && P8 != 0 && P2 == 0) t++; if (P3 != 0 && P4 == 0) t++; if (P5 != 0 && P6 == 0) t++; if (P7 != 0 && P8 == 0) t++; if (P9 != 0 && P2 == 0) t++; if (t == 1) { p[P(x, y)] = 0x80; n++; } } } for (y = 1; y < h - 1; y++) for (x = 1; x < w - 1; x++) { if( p[P(x, y)] == 0x80) p[P(x, y)] = 0; } } while (n > 0 && ++c < 5); return FvsOK; } /* a) 验证其有2-6个邻点 */ #define STEP_A n = 0; /* 邻点个数 */ \ if (P2!=0) n++; if (P3!=0) n++; if (P4!=0) n++; if (P5!=0) n++; \ if (P6!=0) n++; if (P7!=0) n++; if (P8!=0) n++; if (P9!=0) n++; \ if (n>=2 && n<=6) /* b) 统计由0变1的个数 */ #define STEP_B t = 0; /* 变化的数目 */ \ if (P9==0 && P2!=0) t++; if (P2==0 && P3!=0) t++; \ if (P3==0 && P4!=0) t++; if (P4==0 && P5!=0) t++; \ if (P5==0 && P6!=0) t++; if (P6==0 && P7!=0) t++; \ if (P7==0 && P8!=0) t++; if (P8==0 && P9!=0) t++; \ if (t==1) /****************************************************************************** * 功能:细化指纹图像 * 图像必须是二值化过的(只包含0x00或oxFF) * 该算法基于领域的判断,决定某个象素该移去还是保留 * 参数:image 指纹图像 * 返回:错误编号 ******************************************************************************/ FvsError_t ImageThinConnectivity(FvsImage_t image) { FvsInt_t w = ImageGetWidth(image); FvsInt_t h = ImageGetHeight(image); FvsInt_t pitch = ImageGetPitch(image); FvsByte_t* p = ImageGetBuffer(image); FvsInt_t x, y, n, t; FvsBool_t changed = FvsTrue; if (p == NULL) return FvsMemory; if (ImageGetFlag(image) != FvsImageBinarized) return FvsBadParameter; while (changed == FvsTrue) { changed = FvsFalse; for (y = 1; y < h - 1; y++) for (x = 1; x < w - 1; x++) { if (p[P(x, y)] == 0xFF) { STEP_A { STEP_B { /* c) 2*4*6=0 (2,4 ,or 6 为0) d) 4*6*8=0 */ if (P2*P4 * P6 == 0 && P4*P6 * P8 == 0) REMOVE_P; } } } } for (y = 1; y < h - 1; y++) for (x = 1; x < w - 1; x++) if (p[P(x, y)] == 0x80) p[P(x, y)] = 0; for (y = 1; y < h - 1; y++) for (x = 1; x < w - 1; x++) { if (p[P(x, y)] == 0xFF) { STEP_A { STEP_B { /* c) 2*6*8=0 d) 2*4*8=0 */ if (P2*P6 * P8 == 0 && P2*P4 * P8 == 0) REMOVE_P; } } } } for (y = 1; y < h - 1; y++) for (x = 1; x < w - 1; x++) if (p[P(x, y)] == 0x80) p[P(x, y)] = 0; } ImageRemoveSpurs(image); return ImageSetFlag(image, FvsImageThinned); } /* 重新定义 REMOVE_P */ #undef REMOVE_P #define REMOVE_P { p[P(x,y)]=0x00; changed = FvsTrue; } /****************************************************************************** * 功能:细化指纹图像,使用“Hit and Miss”结构元素。 * 图像必须是二值化过的(只包含0x00或oxFF) * 该算法的缺点是产生很多伪造的线条(伪特征), * 必须由另外的算法来消除,后处理非常必要。 * 参数:image 指纹图像 * 返回:错误编号 ******************************************************************************/ FvsError_t ImageThinHitMiss(FvsImage_t image) { FvsInt_t w = ImageGetWidth(image); FvsInt_t h = ImageGetHeight(image); FvsInt_t pitch = ImageGetPitch(image); FvsByte_t* p = ImageGetBuffer(image); /* // // 0 0 0 0 0 // 1 1 1 0 // 1 1 1 1 // */ FvsInt_t x, y; FvsBool_t changed = FvsTrue; if (p == NULL) return FvsMemory; if (ImageGetFlag(image) != FvsImageBinarized) return FvsBadParameter; while (changed == FvsTrue) { changed = FvsFalse; for (y = 1; y < h - 1; y++) for (x = 1; x < w - 1; x++) { if (p[P(x, y)] == 0xFF) { /* // 0 0 0 0 1 1 1 1 1 0 // 1 0 1 1 1 1 1 0 // 1 1 1 0 1 0 0 0 1 0 */ if (p[P(x - 1, y - 1)] == 0 && p[P(x, y - 1)] == 0 && p[P(x + 1, y - 1)] == 0 && p[P(x - 1, y + 1)] != 0 && p[P(x, y + 1)] != 0 && p[P(x + 1, y + 1)] != 0) REMOVE_P; if (p[P(x - 1, y - 1)] != 0 && p[P(x, y - 1)] != 0 && p[P(x + 1, y - 1)] != 0 && p[P(x - 1, y + 1)] == 0 && p[P(x, y + 1)] == 0 && p[P(x + 1, y + 1)] == 0) REMOVE_P; if (p[P(x - 1, y - 1)] == 0 && p[P(x - 1, y)] == 0 && p[P(x - 1, y + 1)] == 0 && p[P(x + 1, y - 1)] != 0 && p[P(x + 1, y)] != 0 && p[P(x + 1, y + 1)] != 0) REMOVE_P; if (p[P(x - 1, y - 1)] != 0 && p[P(x - 1, y)] != 0 && p[P(x - 1, y + 1)] != 0 && p[P(x + 1, y - 1)] == 0 && p[P(x + 1, y)] == 0 && p[P(x + 1, y + 1)] == 0) REMOVE_P; /* // 0 0 0 0 1 1 // 1 1 0 0 1 1 0 1 1 1 1 0 // 1 1 0 0 0 0 */ if (p[P(x, y - 1)] == 0 && p[P(x + 1, y - 1)] == 0 && p[P(x + 1, y)] == 0 && p[P(x - 1, y)] != 0 && p[P(x, y + 1)] != 0) REMOVE_P; if (p[P(x - 1, y - 1)] == 0 && p[P(x, y - 1)] == 0 && p[P(x - 1, y)] == 0 && p[P(x + 1, y)] != 0 && p[P(x, y + 1)] != 0) REMOVE_P; if (p[P(x - 1, y + 1)] == 0 && p[P(x - 1, y)] == 0 && p[P(x, y + 1)] == 0 && p[P(x + 1, y)] != 0 && p[P(x, y - 1)] != 0) REMOVE_P; if (p[P(x + 1, y + 1)] == 0 && p[P(x + 1, y)] == 0 && p[P(x, y + 1)] == 0 && p[P(x - 1, y)] != 0 && p[P(x, y - 1)] != 0) REMOVE_P; } } } ImageRemoveSpurs(image); return ImageSetFlag(image, FvsImageThinned); } /* modified */ FvsError_t FingerprintGetFrequency1(const FvsImage_t image, const FvsFloatField_t direction, FvsFloatField_t frequency) { /* 输入图像的宽度和高度 */ FvsError_t nRet = FvsOK; FvsInt_t w = ImageGetWidth (image); FvsInt_t h = ImageGetHeight(image); FvsInt_t pitchi = ImageGetPitch (image); FvsByte_t* p = ImageGetBuffer(image); FvsFloat_t* out; FvsFloat_t* freq; FvsFloat_t* orientation = FloatFieldGetBuffer(direction); FvsFloat_t dir, dir1, dir2; FvsFloat_t cosdir, sindir, cosdir1, sindir1, cosdir2, sindir2; FvsInt_t x, y, u, v, d, k; size_t size; if (p == NULL) return FvsMemory; /* 输出图像的内存申请 */ nRet = FloatFieldSetSize(frequency, w, h); if (nRet != FvsOK) return nRet; (void)FloatFieldClear(frequency); freq = FloatFieldGetBuffer(frequency); if (freq == NULL) return FvsMemory; /* 输出的内存申请 */ size = w * h * sizeof(FvsFloat_t); out = (FvsFloat_t*)malloc(size); if (out != NULL) { FvsInt_t peak_pos[BLOCK_L]; /* 顶点 */ FvsInt_t peak_cnt; /* 顶点数目 */ FvsFloat_t peak_freq, save[50]; /* 顶点频率 */ FvsFloat_t Xsig[BLOCK_L]; /* x signature */ FvsFloat_t pmin, pmax; memset(out, 0, size); memset(freq, 0, size); /* 1 - 图像分块 BLOCK_W x BLOCK_W - (16 x 16) */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { /* 2 - 脊线方向的窗口 l x w (32 x 16) */ dir = orientation[x + y * w]; cosdir = cos(dir); sindir = sin(dir); u = (FvsInt_t)(-sindir * BLOCK_L2 / 2) + x; v = (FvsInt_t)(cosdir * BLOCK_L2 / 2) + y; dir1 = orientation[u + v * w]; cosdir1 = cos(dir1); sindir1 = sin(dir1); u = (FvsInt_t)(sindir * BLOCK_L2 / 2) + x; v = (FvsInt_t)(-cosdir * BLOCK_L2 / 2) + y; dir2 = orientation[u + v * w]; cosdir2 = cos(dir2); sindir2 = sin(dir2); /* 3 - 计算 x-signature X[0], X[1], ... X[l-1] */ for (k = 0; k < BLOCK_L; k++) { Xsig[k] = 0.0; for (d = 0; d < BLOCK_W; d++) { if(d - BLOCK_W2 > 0) { u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir1 - (d - BLOCK_W2) * sindir1); v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir1 + (d - BLOCK_W2) * cosdir1); } else { u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir2 - (d - BLOCK_W2) * sindir2); v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir2 + (d - BLOCK_W2) * cosdir2); } /* clipping */ if (u < 0) u = 0; else if (u > w - 1) u = w - 1; if (v < 0) v = 0; else if (v > h - 1) v = h - 1; Xsig[k] += p[u + (v * pitchi)]; } Xsig[k] /= BLOCK_W; } /* 计算 T(i,j) */ /* 寻找 x signature 中的顶点 */ peak_cnt = 0; pmax = pmin = Xsig[0]; for (k = 1; k < BLOCK_L; k++) { if (pmin > Xsig[k]) pmin = Xsig[k]; if (pmax < Xsig[k]) pmax = Xsig[k]; } if ((pmax - pmin) > 64.0) { for (k = 1; k < BLOCK_L - 1; k++) if ((Xsig[k - 1] < Xsig[k]) && (Xsig[k] >= Xsig[k + 1])) { peak_pos[peak_cnt++] = k; } } /* 计算均值 */ peak_freq = 0.0; if (peak_cnt > 2) { for (k = 0; k < peak_cnt - 1; k++) peak_freq += peak_pos[k + 1] - peak_pos[k]; peak_freq /= peak_cnt - 1; } /* 4 - 验证频率范围 [1/25-1/3] */ /* 可以扩大到 [1/30-1/2] */ if (peak_freq > 25.0 && peak_freq < 3.0) peak_freq = 0.0; if (peak_freq == 0.0) out[x + y * w] = 0.0; else out[x + y * w] = 1.0 / peak_freq; if(x < 230 && x > 220 && y == 46) x = x; } /* 5 - 未知点 */ /* for (y = BLOCK_L2; y < h-BLOCK_L2; y++) for (x = BLOCK_L2; x < w-BLOCK_L2; x++) { if (out[x+y*w]<EPSILON) { if (out[x+(y-1)*w]>EPSILON) { out[x+(y*w)] = out[x+(y-1)*w]; } else { if (out[x-1+(y*w)]>EPSILON) out[x+(y*w)] = out[x-1+(y*w)]; } } } /* 6 - 频率插值 */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { k = x + y * w; peak_freq = 0.0; for ( v = -LPSIZE; v <= LPSIZE; v++) for ( u = -LPSIZE; u <= LPSIZE; u++) { save[(v + LPSIZE) * (LPSIZE * 2 + 1) + u + LPSIZE] = out[(x + u) + (y + v) * w]; peak_freq += out[(x + u) + (y + v) * w]; } freq[k] = peak_freq * LPFACTOR; if(x < 230 && x > 220 && y == 46) x = x; } free(out); } return nRet; } /* modified */ struct mycomplex { FvsFloat_t real; FvsFloat_t imag; }; static void fft(FvsFloat_t data[32]) { FvsInt_t i, j, k, bfsize, p, count, r = 5; FvsFloat_t angle; struct mycomplex *w, *x1, *x2, *x; count = 1 << r; w = (struct mycomplex*)malloc(sizeof(struct mycomplex) * count / 2); x1 = (struct mycomplex*)malloc(sizeof(struct mycomplex) * count); x2 = (struct mycomplex*)malloc(sizeof(struct mycomplex) * count); for(i = 0; i < count / 2; i++) { angle = -i * M_PI * 2 / count; w[i].real = cos(angle); w[i].imag = sin(angle); } for(j = 0; j < count; j++) { p = 0; for(i = 0; i < r; i++) { if(j & (1 << i)) { p += 1 << (r - i - 1); } } x1[p].real = data[j]; x1[p].imag = 0; } for(k = 0; k < r; k++) { bfsize = 1 << (k + 1); for(j = 0; j < 1 << (r - k - 1); j++) { for(i = 0; i < bfsize / 2; i++) { p = j * bfsize; x2[i + p].real = x1[i + p].real + x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].real \ -x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].imag; x2[i + p].imag = x1[i + p].imag + x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].real \ +x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].imag; x2[i + p + bfsize / 2].real = x1[i + p].real - x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].real \ +x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].imag; x2[i + p + bfsize / 2].imag = x1[i + p].imag - x1[i + p + bfsize / 2].imag * w[i * 1 << (r - k - 1)].real \ -x1[i + p + bfsize / 2].real * w[i * 1 << (r - k - 1)].imag; } } x = x1; x1 = x2; x2 = x; } for(j = 0; j < count; j++) { data[j] = sqrt(x1[j].real * x1[j].real + x1[j].imag * x1[j].imag) / 10; } free(w); free(x1); free(x2); } FvsError_t FingerprintGetFrequency2(const FvsImage_t image, const FvsFloatField_t direction, FvsFloatField_t frequency) { /* 输入图像的宽度和高度 */ FvsError_t nRet = FvsOK; FvsInt_t w = ImageGetWidth (image); FvsInt_t h = ImageGetHeight(image); FvsInt_t pitchi = ImageGetPitch (image); FvsByte_t* p = ImageGetBuffer(image); FvsFloat_t* out; FvsFloat_t* freq; FvsFloat_t* orientation = FloatFieldGetBuffer(direction); FvsInt_t x, y, u, v, d, k; size_t size; if (p == NULL) return FvsMemory; /* 输出图像的内存申请 */ nRet = FloatFieldSetSize(frequency, w, h); if (nRet != FvsOK) return nRet; (void)FloatFieldClear(frequency); freq = FloatFieldGetBuffer(frequency); if (freq == NULL) return FvsMemory; /* 输出的内存申请 */ size = w * h * sizeof(FvsFloat_t); out = (FvsFloat_t*)malloc(size); if (out != NULL) { FvsFloat_t dir = 0.0; FvsFloat_t cosdir = 0.0; FvsFloat_t sindir = 0.0; FvsInt_t peak_pos[BLOCK_L]; /* 顶点 */ FvsInt_t peak_cnt; /* 顶点数目 */ FvsFloat_t peak_freq; /* 顶点频率 */ FvsFloat_t Xsig[BLOCK_L]; /* x signature */ FvsFloat_t pmin, pmax; memset(out, 0, size); memset(freq, 0, size); /* 1 - 图像分块 BLOCK_W x BLOCK_W - (16 x 16) */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { /* 2 - 脊线方向的窗口 l x w (32 x 16) */ // dir = orientation[(x+BLOCK_W2) + (y+BLOCK_W2)*w]; dir = orientation[(x) + (y) * w]; cosdir = cos(dir); sindir = sin(dir); /* 3 - 计算 x-signature X[0], X[1], ... X[l-1] */ for (k = 0; k < BLOCK_L; k++) { Xsig[k] = 0.0; for (d = 0; d < BLOCK_W; d++) { u = (FvsInt_t)(x + (k - BLOCK_L2) * cosdir - (d - BLOCK_W2) * sindir); v = (FvsInt_t)(y + (k - BLOCK_L2) * sindir + (d - BLOCK_W2) * cosdir); /* clipping */ if (u < 0) u = 0; else if (u > w - 1) u = w - 1; if (v < 0) v = 0; else if (v > h - 1) v = h - 1; Xsig[k] += p[u + (v * pitchi)]; } Xsig[k] /= BLOCK_W; } if(x == 130 && y == 100) x = x; // for(k=0;k<32;k++) // Xsig[k]=cos(2*M_PI*7*k/32)+cos(2*M_PI*3*k/32); fft(Xsig); if (peak_freq > 30.0) out[x + y * w] = 0.0; else if (peak_freq < 2.0) out[x + y * w] = 0.0; else out[x + y * w] = 1.0 / peak_freq; } /* 5 - 未知点 */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { if (out[x + y * w] < EPSILON) { if (out[x + (y - 1)*w] > EPSILON) { out[x + (y * w)] = out[x + (y - 1) * w]; } else { if (out[x - 1 + (y * w)] > EPSILON) out[x + (y * w)] = out[x - 1 + (y * w)]; } } } /* 6 - 频率插值 */ for (y = BLOCK_L2; y < h - BLOCK_L2; y++) for (x = BLOCK_L2; x < w - BLOCK_L2; x++) { k = x + y * w; peak_freq = 0.0; for ( v = -LPSIZE; v <= LPSIZE; v++) for ( u = -LPSIZE; u <= LPSIZE; u++) peak_freq += out[(x + u) + (y + v) * w]; freq[k] = peak_freq * LPFACTOR; } free(out); } return nRet; }
[ "chenke625@gmail.com" ]
chenke625@gmail.com
719fda0ac135e469c5efe5740864ce50cca58547
bae8d959d84d75c262b686390d12895f933423f6
/timelapseV2/timelapseV2.ino
f2ef47220c6a65d92b373d071d9c0973ecc1e843
[]
no_license
tkarsist/ArduinoCode
25d0e306ea9d30ff7d187fb845a793f4650f9f13
02e0fd487b0e8ee124202a9b98ab8c3163ed06aa
refs/heads/master
2016-09-02T06:05:16.888164
2013-11-24T18:47:39
2013-11-24T18:47:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,282
ino
#include <Servo.h> #define Length 10 typedef struct{ unsigned long int atTime; int servoID; int servoSpeed; int servoDir; }commandAction; commandAction actionlist[Length]; //struct commandAction actionlist[1000]; Servo servo1; Servo servo2; String sanoma=""; boolean sanomaReady=false; boolean sanomaOngoing=false; int actionlistIndex=0; int actionlistNext=0; //commandAction actionlist[]; void setup() { pinMode(1,OUTPUT); servo1.attach(9); //analog pin 0 //servo1.setMaximumPulse(2000); //servo1.setMinimumPulse(700); servo2.attach(3); //analog pin 1 Serial.begin(19200); Serial.println("Ready"); } void loop() { //servo write 89 -0 toinen suunta, 90-179 toinen suunta static int v = 0; static int v2 = 0; static int servoID=9; static int servoID2=3; static int sign=1; //static int rotatetime=0; static unsigned long time; time= millis(); int i=0; /* if(actionlistIndex>0){ Serial.println(actionlist[actionlistNext].atTime); Serial.println(time); } */ if (actionlistIndex>0 && actionlist[actionlistNext].atTime!=0 && time>actionlist[actionlistNext].atTime){ Serial.println(actionlist[actionlistNext].atTime); int tmpIndex=0; if (actionlist[actionlistNext].servoSpeed>0){ //Serial.println("tuli tanne"); if (actionlist[actionlistNext].servoID==1){ v=actionlist[actionlistNext].servoSpeed*10-2; sign=actionlist[actionlistNext].servoDir; if(sign==1){ sign=-0; v=187 - v; } servo1.attach(servoID); servo1.write(v); Serial.println("servo start"); v=0; tmpIndex=1; } } if(actionlist[actionlistNext].servoSpeed==0){ if(actionlist[actionlistNext].servoID==1){ Serial.println("servo detach"); servo1.detach(); tmpIndex=1; } } if(tmpIndex!=0){ actionlistNext=actionlistNext+1; Serial.println(actionlistNext); } } if ( Serial.available()) { char ch = Serial.read(); //viestin alku if(ch == '<'){ sanomaOngoing=true; } //viestin loppu if (ch == '>'){ sanomaOngoing=false; sanomaReady=true; } //lisataan merkit sanomaan if(sanomaOngoing && ch!='<'){ sanoma=sanoma + ch; } //sanoma valmis if(sanomaReady){ Serial.print("sanoma: "); Serial.println(sanoma); //Serial.println(sanoma.substring(0,10)); //At time extract char charAtTime[11]; String stringAtTime=sanoma.substring(0,10); stringAtTime.toCharArray(charAtTime, sizeof(charAtTime)); unsigned long int tmpAtTime=atol(charAtTime); Serial.print("attime: "); Serial.println(tmpAtTime); //servoid extract String stringServoId=sanoma.substring(10,11); int tmpServoId=stringServoId[0]-48; Serial.print("servoid: "); Serial.println(tmpServoId); //servospeed extract String stringServoSpeed=sanoma.substring(11,12); int tmpServoSpeed=stringServoSpeed[0]-48; Serial.print("servospeed: "); Serial.println(tmpServoSpeed); //servodirection extract String stringServoDir=sanoma.substring(12,13); int tmpServoDir=stringServoDir[0]-48; Serial.print("servodirection: "); Serial.println(tmpServoDir); actionlist[actionlistIndex].atTime=tmpAtTime; actionlist[actionlistIndex].servoID=tmpServoId; actionlist[actionlistIndex].servoSpeed=tmpServoSpeed; actionlist[actionlistIndex].servoDir=tmpServoDir; //Serial.println(actionlist[actionlistIndex].atTime); /* commandAction tmpCommandAction; //tmpCommandAction.atTime=19191991; tmpCommandAction.atTime=tmpAtTime; tmpCommandAction.servoID=tmpServoId; tmpCommandAction.servoSpeed=tmpServoSpeed; tmpCommandAction.servoDir=tmpServoDir; //actionlist[0]=tmpCommandAction; */ actionlistIndex=actionlistIndex+1; Serial.println(actionlistIndex); sanoma=""; sanomaReady=false; } //static unsigned long detachS1; //detachS1=0; /* if(detachS1!=0 && time>detachS1){ Serial.println("Detaching Servo1"); servo1.detach(); detachS1=0; } */ /* if(ch == '<') { i=0; Serial.println(Serial.available()); if(Serial.available()){ ch=Serial.read(); Serial.println("hottii shittii"); } //while (!sanomaValmis) while (Serial.available() && !sanomaValmis && i<10){ ch = Serial.read(); //Serial.println("osuma1.5"); //oliko loppumerkki if (ch =='>') { Serial.println("osuma2"); sanomaValmis=true; Serial.println(sanoma); } else { Serial.println(ch); sanoma+=ch; // strArray[i]=val; //laitetaan merkki bufferiin } i++; } } sanomaValmis=false; sanoma=""; */ } //switch logic: direction (-, optional), time (optional: s,m,l), speed: 0..9 (optional), servo: a-x) /* switch(ch) { //direction to rotate case '-': sign=-1*sign; Serial.println(sign, DEC); break; //small time to rotate case 's': //115 //Serial.println(ch, DEC); rotatetime=500; detachS1=time+500; break; //medium time to rotate case 'm': //109 //Serial.println(ch, DEC); rotatetime=5000; detachS1=time+5000; break; //large time to rotate case 'l': //108 //Serial.println(ch, DEC); detachS1=time+20000; rotatetime=20000; break; //servo speed for continuous. 0 is fastest and 9 slowest case '0'...'9': //char merkit on koodilta 48-57 //v = v * 100 + ch - '0'; //v=ch-40; if(ch==48){ v=1; } else{ v=ch-48; } v=v*10-2; v2=ch-48; v2=v2*40-1; v2=v2*sign; if(sign==-1){ sign=-1*sign; v=187 - v; } Serial.println(""); Serial.println (" ---------- "); Serial.print("'0-9' :"); Serial.print(" CH:"); Serial.print(ch, DEC); Serial.print(" V:"); Serial.print(v, DEC); Serial.print( " V2:"); Serial.print(v2, DEC); Serial.println(" . Case 0-9 --END"); //v=v+ch -'0'; break; // servo a (there are servos a,b,c,d,e,f,g) case 'a': Serial.print("'A' :"); Serial.print(" V:"); Serial.println(v, DEC); servo1.attach(servoID); servo1.write(v); if(v==0){ servo1.detach(); } v = 0; break; //detach all servos case 'd': servo1.detach(); break; //attach all servos case 'x': Serial.print("'x' :"); Serial.println(v2, DEC); servo2.write(v2); delay(500); v = 0; v2 =0; break; } */ }
[ "timo.karsisto@gmail.com" ]
timo.karsisto@gmail.com
4a0c6a3732cf0316f43b1a0b09332273bb89b381
b9a83ad74c8864660cb2c13fd712f709f522848d
/include/Old_Junk/Matrix.h
7461a817631510106338f29fde360efa06e339ec
[]
no_license
95ellismle/Spin_Accumulation
3e50c6522c7da9a445575aca2e43e6cbf384aaf1
4e259c694a515fa105d794703d7335682e9d17d5
refs/heads/master
2021-01-20T13:11:58.527151
2017-08-30T14:06:29
2017-08-30T14:06:29
101,739,809
0
0
null
null
null
null
UTF-8
C++
false
false
10,148
h
#ifndef MATRIX_H #define MATRIX_H #include <iostream> #include <fstream> #include <vector> #include <cmath> #include "correctors.h" ////////////////////////////////////////////////// SYSTEM SETUP PARAMETERS ///////////////////////////////////////////////////////////////////////// // Parameters affecting accuracy and the dimensions of the system // // extern const double dx; // The space step (m) // extern const double dt; // The time step (s) // extern const double T; // The total time (s) // extern const double L; // The total length (m) // extern const double F1_Boundaries[2]; // Position of the first ferromagnetic layer // extern const double F2_Boundaries[2]; // Position of the first ferromagnetic layer // // // // Material Properties. First in the array is the Magnet, the Second is in a non-magnet. // // extern const double DL; // extern const double j_e; // extern const double beta[2]; // The charge current polarisation // extern const double beta_prime[2]; // The spin current polarisation // extern const double lambda_sf[2]; // The spin flip length // extern const double lambda_J[2]; // A damping coefficient (spin accumulation precession around Magnetisation) // extern const double lambda_phi[2]; // Another damping coefficient (a dephasing lengthscale) // extern const double D[2]; // Diffusivity 1st item is for the magnet and 2nd is for the non-magnet // extern const double minf_magnitude; // The magnitude of the equilibrium spin accumlation vector // // // // The magnetisations of the layers // // // extern const double M1[3]; // F1 Magnetisation, this code will only work with an x and y magnetisation // extern const double M2[3]; // F2 Magnetisation, this code will only work with an x and y magnetisation // // // // The Number of Time Steps to Save // // // extern unsigned int Saves; // F1 Magnetisation, this code will only work with an x and y magnetisation // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The lengths of the data storage containers and the number of iterations. extern const unsigned int x_coords_len; extern const unsigned int Iterations; // The Positions of the Magnetic Layers in the Storage Containers. extern const unsigned int F1_Boundaries_Indices[2]; extern const unsigned int F2_Boundaries_Indices[2]; // Constants to use later extern const double fact1; extern const double fact2; extern const double fact3[2]; // Vectors extern double Byy; extern double Bzz; extern double B1yz; extern double B2yz; extern std::vector<double> vec_beta; extern std::vector<double> diff_beta; extern std::vector<double> Sx; extern std::vector<double> v; extern std::vector<double> S2x; extern std::vector<double> Cy; extern std::vector<double> Cz; extern std::vector<unsigned int> steps_to_save; // Data Storage Containers // // The Save Vectors Save the number of time steps requested evenly spaced. extern std::vector < std::vector < double > > Save_Ux; extern std::vector < std::vector < double > > Save_Uy; extern std::vector < std::vector < double > > Save_Uz; // // These Vectors are used in the calculations extern std::vector<double> Uz; extern std::vector<double> Uz_half; extern std::vector<double> Uy; extern std::vector<double> Uy_half; extern std::vector<double> Ux; // The A Matrix extern std::vector<double> A; // A function to recreate the A Matrix void A_Refresher(std::vector<double> a, std::vector<double> b, std::vector<double> c, std::vector<double> L) { for (unsigned int i=3; i<(x_coords_len-1)*3;i+=3) { unsigned int x = (int) i/3; A[i] = -a[x]; A[i+1] = 1+(2*b[x])+L[x]; A[i+2] = -c[x]+L[x]; } A[0] = 0; A[1] = 1; A[2] = 0; A[3*x_coords_len-1] = 0; A[3*x_coords_len-2] = 1; A[3*x_coords_len-3] = 0; } // A function to solve the Matrix equation std::vector<double> Solver(std::vector<double> & input_array, int xyz) { std::vector <double> tmp_array (input_array); if (xyz == 0) { for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Z_NM_corrector(i); } for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Z1_corrector(i); } for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Z_NM_corrector(i); } for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Z2_corrector(i); } for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++) { tmp_array[i] = tmp_array[i] + Z_NM_corrector(i); } } else if (xyz == 1) { for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Z_NM_corrector(i); } for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Z1_half_corrector(i); } for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Z_NM_corrector(i); } for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Z2_half_corrector(i); } for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++) { tmp_array[i] = tmp_array[i] + Z_NM_corrector(i); } } else if (xyz == 2) { for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Y_NM_corrector(i); } for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Y1_corrector(i); } for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Y_NM_corrector(i); } for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Y2_corrector(i); } for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++) { tmp_array[i] = tmp_array[i] + Y_NM_corrector(i); } } else if (xyz == 3) { for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Y_NM_corrector(i); } for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Y1_half_corrector(i); } for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + Y_NM_corrector(i); } for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + Y2_half_corrector(i); } for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++) { tmp_array[i] = tmp_array[i] + Y_NM_corrector(i); } } else if (xyz == 4) { for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + X_NM_corrector(i); } for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + X1_corrector(i); } for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + X_NM_corrector(i); } for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + X2_corrector(i); } for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++) { tmp_array[i] = tmp_array[i] + X_NM_corrector(i); } } else if (xyz == 5) { for(unsigned int i=1; i<F1_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + X_NM_corrector(i); } for (unsigned int i=F1_Boundaries_Indices[0];i<F1_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + X1_half_corrector(i); } for(unsigned int i=F1_Boundaries_Indices[1]; i<F2_Boundaries_Indices[0]; i++) { tmp_array[i] = tmp_array[i] + X_NM_corrector(i); } for (unsigned int i=F2_Boundaries_Indices[0];i<F2_Boundaries_Indices[1]; i++) { tmp_array[i] = tmp_array[i] + X2_half_corrector(i); } for(unsigned int i=F2_Boundaries_Indices[1]; i<x_coords_len-1; i++) { tmp_array[i] = tmp_array[i] + X_NM_corrector(i); } } int counter = 1; for(unsigned int i=3; i<3*(x_coords_len-1);i+=3) { double mul = A[i]/A[i-2]; double new_value = (double) tmp_array[counter] - tmp_array[counter-1]*mul; tmp_array[counter] = new_value; A[i+1] = A[i+1] - A[i-1]*mul; A[i] = A[i] - A[i-2]*mul; counter++; } counter = x_coords_len-1; for(int i=3*(x_coords_len-1); i>3; i-=3) { double mul = A[i-1]/A[i+1]; double new_value = (double) tmp_array[counter-1] - tmp_array[counter]*mul; tmp_array[counter-1] = new_value; A[i-1] = A[i-1] - A[i+1]*mul; counter--; } for(unsigned int i=1; i<x_coords_len-1; i++) { double new_value = (double) tmp_array[i]/A[3*i+1]; tmp_array[i] = new_value; } //Neumann (floating) boundary conditions tmp_array[0] = tmp_array[1] - (tmp_array[2]-tmp_array[1])/2.718; tmp_array[x_coords_len-1] = tmp_array[x_coords_len-2]-(tmp_array[x_coords_len-3]-tmp_array[x_coords_len-2])/2.718; return tmp_array; } #endif
[ "95ellismle@gmail.com" ]
95ellismle@gmail.com
de86afaeacd89c61157f3ba79837b0b30a3d2d6f
88ae8695987ada722184307301e221e1ba3cc2fa
/components/security_interstitials/core/https_only_mode_metrics.h
50efe38ed5554839101f8444a10227ff7e4ade8d
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
7,404
h
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SECURITY_INTERSTITIALS_CORE_HTTPS_ONLY_MODE_METRICS_H_ #define COMPONENTS_SECURITY_INTERSTITIALS_CORE_HTTPS_ONLY_MODE_METRICS_H_ #include <cstddef> #include "base/time/time.h" namespace security_interstitials::https_only_mode { // The main histogram that records events about HTTPS-First Mode and HTTPS // Upgrades. extern const char kEventHistogram[]; // Same as kEventHistogram, but only recorded if the event happened on a // navigation where HFM was enabled due to the site engagement heuristic. extern const char kEventHistogramWithEngagementHeuristic[]; extern const char kNavigationRequestSecurityLevelHistogram[]; // Histogram that records enabled/disabled states for sites. If HFM gets enabled // or disabled due to Site Engagement on a site, records an entry. extern const char kSiteEngagementHeuristicStateHistogram[]; // Histogram that records the current number of host that have HFM enabled due // to the site engagement heuristic. Includes hosts that have HTTP allowed. extern const char kSiteEngagementHeuristicHostCountHistogram[]; // Histogram that records the accumulated number of host that have HFM enabled // at some point due to the site engagement heuristic. Includes hosts that have // HTTP allowed. extern const char kSiteEngagementHeuristicAccumulatedHostCountHistogram[]; // Histogram that records the duration a host has HFM enabled due to the site // engagement heuristic. Only recorded for hosts removed from the HFM list. // Recorded at the time of navigation when HFM upgrades trigger. extern const char kSiteEngagementHeuristicEnforcementDurationHistogram[]; // Recorded by HTTPS-First Mode and HTTPS-Upgrade logic when a navigation is // upgraded, or is eligible to be upgraded but wasn't. // // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. enum class Event { // Navigation was upgraded from HTTP to HTTPS at some point (either the // initial request or after a redirect). kUpgradeAttempted = 0, // Navigation succeeded after being upgraded to HTTPS. kUpgradeSucceeded = 1, // Navigation failed after being upgraded to HTTPS. kUpgradeFailed = 2, // kUpgradeCertError, kUpgradeNetError, kUpgradeTimedOut, and // kUpgradeRedirectLoop are subsets of kUpgradeFailed. kUpgradeFailed should // also be recorded whenever these events are recorded. // Navigation failed due to a cert error. kUpgradeCertError = 3, // Navigation failed due to a net error. kUpgradeNetError = 4, // Navigation failed due to timing out. kUpgradeTimedOut = 5, // A prerendered HTTP navigation was cancelled. kPrerenderCancelled = 6, // An upgrade would have been attempted but wasn't because neither HTTPS-First // Mode nor HTTPS Upgrading were enabled. kUpgradeNotAttempted = 7, // Upgrade failed due to encountering a redirect loop and failing early. kUpgradeRedirectLoop = 8, kMaxValue = kUpgradeRedirectLoop, }; // Recorded by HTTPS-Upgrade logic when each step in a navigation request is // observed, recording information about the protocol used. For a request with // two redirects, this will be recorded three times (once for each redirect, // then for the final URL). // // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. Values may be added to offer greater // specificity in the future. Keep in sync with NavigationRequestSecurityLevel // in enums.xml. enum class NavigationRequestSecurityLevel { // Request was ignored because not all prerequisites were met. kUnknown = 0, // Request was for a secure (HTTPS) resource. kSecure = 1, // Request was for an insecure (HTTP) resource. kInsecure = 2, // Request was for an insecure (HTTP) resource, but was internally redirected // due to HSTS. kHstsUpgraded = 3, // Request was for localhost, and thus no network // due to HSTS. kLocalhost = 4, // Request was for an insecure (HTTP) resource, but was internally redirected // by the HTTPS-First Mode/HTTP Upgrading logic. kUpgraded = 5, // Request was for a URL with a scheme other than HTTP or HTTPS. kOtherScheme = 6, // Request was explicitly allowlisted by content or enterprise settings // (NOT by clicking through the HFM interstitial / an upgrade failing). kAllowlisted = 7, // Request was insecure (HTTP), but was to a hostname that isn't globally // unique (e.g. a bare RFC1918 IP address, single-label or .local hostname). // This bucket is recorded IN ADDITION to kInsecure/kAllowlisted. kNonUniqueHostname = 8, // Request was insecure (HTTP), but was to a URL that was fully typed (as // opposed to autocompleted) that included an explicit http scheme. kExplicitHttpScheme = 9, kMaxValue = kExplicitHttpScheme, }; // Recorded by the Site Engagement Heuristic logic, recording whether HFM should // be enabled on a site due to its HTTP and HTTPS site engagement scores. Only // recorded if the enabled/disabled state changes. // // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. Values may be added to offer greater // specificity in the future. Keep in sync with SiteEngagementHeuristicState // in enums.xml. enum class SiteEngagementHeuristicState { // HFM was not enabled and is now enabled on this site because its HTTPS score // is high and HTTP score is low. kEnabled = 0, // HFM was enabled and is now disabled on this site because its HTTPS score is // low or HTTP score is high. kDisabled = 1, kMaxValue = kDisabled, }; // Stores the parameters to decide whether to show an interstitial for the // current site. struct HttpInterstitialState { // Whether HTTPS-First Mode is enabled using the global UI toggle. bool enabled_by_pref = false; // Whether HTTPS-First Mode is enabled for the current site due to the // site engagement heuristic. bool enabled_by_engagement_heuristic = false; // Whether HTTPS-First Mode is enabled because the user is in the Advanced // Protection program. bool enabled_by_advanced_protection = false; }; // Helper to record an HTTPS-First Mode navigation event. void RecordHttpsFirstModeNavigation( Event event, const HttpInterstitialState& interstitial_state); // Helper to record a navigation request security level. void RecordNavigationRequestSecurityLevel(NavigationRequestSecurityLevel level); // Helper to record Site Engagement Heuristic enabled state. void RecordSiteEngagementHeuristicState(SiteEngagementHeuristicState state); // Helper to record metrics about the number of hosts affected by the Site // Engagement Heuristic. // `current_count` is the number of hosts that currently have HFM enabled. // `accumulated_count` is the number of accumulated hosts that had HFM enabled // at some point. void RecordSiteEngagementHeuristicCurrentHostCounts(size_t current_count, size_t accumulated_count); void RecordSiteEngagementHeuristicEnforcementDuration( base::TimeDelta enforcement_duration); } // namespace security_interstitials::https_only_mode #endif // COMPONENTS_SECURITY_INTERSTITIALS_CORE_HTTPS_ONLY_MODE_METRICS_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
c76c87e765af4f7867f37d73f1853e2b3c94a2e5
4d209d683e5fcd03f7ffeff999ee47adb3b8fcc3
/WarpTPS/Dib.cpp
7b5d5a3ece3fd339d9b3e2026d7c2c4c11f98f13
[]
no_license
yuzhuqingyun/pheonixrt
6aebed75b78f4ac5db162429955901d963b5de49
6d5f2229362cedef111eea5ffea85c5022565f9b
refs/heads/master
2016-09-05T10:05:06.204029
2014-10-24T04:21:55
2014-10-24T04:21:55
32,519,414
1
0
null
null
null
null
UTF-8
C++
false
false
9,413
cpp
//////////////////////////////////////////////////////////////// // PixieLib(TM) Copyright 1997-1999 Paul DiLascia // If this code works, it was written by Paul DiLascia. // If not, I don't know who wrote it. // // CDib - Device Independent Bitmap.CDib is derived from CBitmap, so // you can use it with other MFC functions that use bitmaps. // #include "StdAfx.h" #include "Dib.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif const int MAXPALCOLORS = 256; IMPLEMENT_DYNAMIC(CDib, CObject) CDib::CDib() { memset(&m_bm, 0, sizeof(m_bm)); m_hdd = NULL; } CDib::~CDib() { DeleteObject(); } // helper to make a copy void CDib::CopyPixels(CDib* pFrom) { // get the number of bytes-per-pixel for each BITMAP srcBitmap; pFrom->GetBitmap(&srcBitmap); int nSrcBytesPerPixel = (srcBitmap.bmBitsPixel+7)/8; // ensure the scan line width is on a LONG boundary int nSrcWidthBytes = 4 * ((srcBitmap.bmWidth * nSrcBytesPerPixel + 3) / 4); BITMAP dstBitmap; GetBitmap(&dstBitmap); int nDstBytesPerPixel = (dstBitmap.bmBitsPixel+7)/8; // ensure the scan line width is on a LONG boundary int nDstWidthBytes = 4 * ((dstBitmap.bmWidth * nDstBytesPerPixel + 3) / 4); // should have same pixel format ASSERT(nDstBytesPerPixel == nSrcBytesPerPixel); ASSERT(nDstWidthBytes == nSrcWidthBytes); ASSERT(srcBitmap.bmHeight == dstBitmap.bmHeight); // retrieve the source and destination pixels UCHAR *pSrcPixels = (UCHAR *) pFrom->GetDIBits(); UCHAR *pDstPixels = (UCHAR *) GetDIBits(); for (int nRow = 0; nRow < dstBitmap.bmHeight; nRow++) { memcpy(&pDstPixels[nRow*nDstWidthBytes], &pSrcPixels[nRow*nSrcWidthBytes], nDstWidthBytes); } } // helper to blend with another void CDib::BlendPixels(CDib* pFrom, float percent) { // get the number of bytes-per-pixel for each BITMAP srcBitmap; pFrom->GetBitmap(&srcBitmap); int nSrcBytesPerPixel = (srcBitmap.bmBitsPixel+7)/8; // ensure the scan line width is on a LONG boundary int nSrcWidthBytes = 4 * ((srcBitmap.bmWidth * nSrcBytesPerPixel + 3) / 4); BITMAP dstBitmap; GetBitmap(&dstBitmap); int nDstBytesPerPixel = (dstBitmap.bmBitsPixel+7)/8; // ensure the scan line width is on a LONG boundary int nDstWidthBytes = 4 * ((dstBitmap.bmWidth * nDstBytesPerPixel + 3) / 4); // should have same pixel format ASSERT(nDstBytesPerPixel == nSrcBytesPerPixel); ASSERT(nDstWidthBytes == nSrcWidthBytes); ASSERT(srcBitmap.bmHeight == dstBitmap.bmHeight); // get the size of the source image CSize dstSize = GetSize(); // retrieve the source and destination pixels UCHAR *pSrcPixels = (UCHAR *) pFrom->GetDIBits(); UCHAR *pBlendPixels = (UCHAR *) GetDIBits(); for (int nAt = 0; nAt < (dstSize.cx * dstSize.cy * nSrcBytesPerPixel); nAt++)//nSrcBytesPixel { pBlendPixels[nAt] = (UCHAR)((float) pSrcPixels[nAt] * percent + (float) pBlendPixels[nAt] * (1.0 - percent)); } } ////////////////// // Delete Object. Delete DIB and palette. // BOOL CDib::DeleteObject() { m_pal.DeleteObject(); if (m_hdd) { DrawDibClose(m_hdd); m_hdd = NULL; } memset(&m_bm, 0, sizeof(m_bm)); return CBitmap::DeleteObject(); } ////////////////// // Read DIB from file. // BOOL CDib::Load(LPCTSTR lpszPathName) { return Attach(::LoadImage(NULL, lpszPathName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE)); } ////////////////// // Load bitmap resource. Never tested. // BOOL CDib::Load(HINSTANCE hInst, LPCTSTR lpResourceName) { return Attach(::LoadImage(hInst, lpResourceName, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_DEFAULTSIZE)); } ////////////////// // Attach is just like the CGdiObject version, // except it also creates the palette // BOOL CDib::Attach(HGDIOBJ hbm) { if (CBitmap::Attach(hbm)) { if (!GetBitmap(&m_bm)) // load BITMAP for speed return FALSE; m_pal.DeleteObject(); // in case one is already there return CreatePalette(m_pal); // create palette } return FALSE; } //////////////////////////////////////////////////////////////// // Draw DIB on caller's DC. Does stretching from source to destination // rectangles. Generally, you can let the following default to zero/NULL: // // bUseDrawDib = whether to use use DrawDib, default TRUE // pPal = palette, default=NULL, (use DIB's palette) // bForeground = realize in foreground (default FALSE) // // If you are handling palette messages, you should use bForeground=FALSE, // since you will realize the foreground palette in WM_QUERYNEWPALETTE. // BOOL CDib::Draw(CDC& dc, const CRect* rcDst, const CRect* rcSrc, BOOL bUseDrawDib, CPalette* pPal, BOOL bForeground) { if (!m_hObject) return FALSE; // Select, realize palette if (pPal==NULL) // no palette specified: pPal = GetPalette(); // use default CPalette* pOldPal = dc.SelectPalette(pPal, !bForeground); dc.RealizePalette(); BOOL bRet = FALSE; if (bUseDrawDib) { // Compute rectangles where NULL specified // CRect rc(0,0,-1,-1); // default for DrawDibDraw if (!rcSrc) rcSrc = &rc; if (!rcDst) rcDst=rcSrc; if (!m_hdd) VERIFY(m_hdd = DrawDibOpen()); // Get BITMAPINFOHEADER/color table. I copy into stack object each time. // This doesn't seem to slow things down visibly. // DIBSECTION ds; VERIFY(GetObject(sizeof(ds), &ds)==sizeof(ds)); char buf[sizeof(BITMAPINFOHEADER) + MAXPALCOLORS*sizeof(RGBQUAD)]; BITMAPINFOHEADER& bmih = *(BITMAPINFOHEADER*)buf; RGBQUAD* colors = (RGBQUAD*)(&bmih+1); memcpy(&bmih, &ds.dsBmih, sizeof(bmih)); GetColorTable(colors, MAXPALCOLORS); // Let DrawDib do the work! bRet = DrawDibDraw(m_hdd, dc, rcDst->left, rcDst->top, rcDst->Width(), rcDst->Height(), &bmih, // ptr to BITMAPINFOHEADER + colors m_bm.bmBits, // bits in memory rcSrc->left, rcSrc->top, rcSrc->Width(), rcSrc->Height(), bForeground ? 0 : DDF_BACKGROUNDPAL); } else { // use normal draw function bRet = PLDrawBitmap(dc, this, rcDst, rcSrc); } if (pOldPal) dc.SelectPalette(pOldPal, TRUE); return bRet; } #define PALVERSION 0x300 // magic number for LOGPALETTE ////////////////// // Create the palette. Use halftone palette for hi-color bitmaps. // BOOL CDib::CreatePalette(CPalette& pal) { // should not already have palette ASSERT(pal.m_hObject==NULL); BOOL bRet = FALSE; RGBQUAD* colors = new RGBQUAD[MAXPALCOLORS]; UINT nColors = GetColorTable(colors, MAXPALCOLORS); if (nColors > 0) { // Allocate memory for logical palette int len = sizeof(LOGPALETTE) + sizeof(PALETTEENTRY) * nColors; LOGPALETTE* pLogPal = (LOGPALETTE*)new char[len]; if (!pLogPal) return NULL; // set version and number of palette entries pLogPal->palVersion = PALVERSION; pLogPal->palNumEntries = nColors; // copy color entries for (UINT i = 0; i < nColors; i++) { pLogPal->palPalEntry[i].peRed = colors[i].rgbRed; pLogPal->palPalEntry[i].peGreen = colors[i].rgbGreen; pLogPal->palPalEntry[i].peBlue = colors[i].rgbBlue; pLogPal->palPalEntry[i].peFlags = 0; } // create the palette and destroy LOGPAL bRet = pal.CreatePalette(pLogPal); delete [] (char*)pLogPal; } else { CWindowDC dcScreen(NULL); bRet = pal.CreateHalftonePalette(&dcScreen); } delete colors; return bRet; } ////////////////// // Helper to get color table. Does all the mem DC voodoo. // UINT CDib::GetColorTable(RGBQUAD* colorTab, UINT nColors) { CWindowDC dcScreen(NULL); CDC memdc; memdc.CreateCompatibleDC(&dcScreen); CBitmap* pOldBm = memdc.SelectObject(this); nColors = GetDIBColorTable(memdc, 0, nColors, colorTab); memdc.SelectObject(pOldBm); return nColors; } ////////////////// // Get size (width, height) of bitmap. // extern fn works for ordinary CBitmap objects. // CSize PLGetBitmapSize(CBitmap* pBitmap) { BITMAP bm; return pBitmap->GetBitmap(&bm) ? CSize(bm.bmWidth, bm.bmHeight) : CSize(0,0); } ////////////////// // You can use this static function to draw ordinary // CBitmaps as well as CDibs // BOOL PLDrawBitmap(CDC& dc, CBitmap* pBitmap, const CRect* rcDst, const CRect* rcSrc, DWORD dwRop) { // Compute rectangles where NULL specified CRect rc; if (!rcSrc) { // if no source rect, use whole bitmap rc = CRect(CPoint(0,0), PLGetBitmapSize(pBitmap)); rcSrc = &rc; } if (!rcDst) { // if no destination rect, use source rcDst=rcSrc; } // Create memory DC CDC memdc; memdc.CreateCompatibleDC(&dc); CBitmap* pOldBm = memdc.SelectObject(pBitmap); // Blast bits from memory DC to target DC. // Use StretchBlt if size is different. // BOOL bRet = FALSE; if (rcDst->Size()==rcSrc->Size()) { bRet = dc.BitBlt(rcDst->left, rcDst->top, rcDst->Width(), rcDst->Height(), &memdc, rcSrc->left, rcSrc->top, dwRop); } else { // dc.SetStretchBltMode(COLORONCOLOR); dc.SetStretchBltMode(HALFTONE); bRet = dc.StretchBlt(rcDst->left, rcDst->top, rcDst->Width(), rcDst->Height(), &memdc, rcSrc->left, rcSrc->top, rcSrc->Width(), rcSrc->Height(), dwRop); } memdc.SelectObject(pOldBm); return bRet; } void *CDib::GetDIBits() { ASSERT(m_bm.bmBits != NULL); return m_bm.bmBits; }
[ "dglane001@gmail.com@5160d9da-b3a6-11de-af8f-1f60b1e8fe01" ]
dglane001@gmail.com@5160d9da-b3a6-11de-af8f-1f60b1e8fe01
e4b98049621db95dde767a8ad87a44c4aa4effde
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/MuonSpectrometer/MuonCnv/MuonByteStreamCnvTest/MuonByteStreamCnvTest/MuonRdoToMuonDigit.h
2695a1de11a7e17f20a29b9f816b3b34146ea86d
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
600
h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef MUONBYTESTREAMCNVTEST_MUONRDOTOMUONDIGIT_H #define MUONBYTESTREAMCNVTEST_MUONRDOTOMUONDIGIT_H #include "GaudiKernel/ToolHandle.h" #include "AthenaBaseComps/AthAlgorithm.h" class IMuonDigitizationTool; class MuonRdoToMuonDigit : public AthAlgorithm { public: MuonRdoToMuonDigit(const std::string& name, ISvcLocator* pSvcLocator); ~MuonRdoToMuonDigit(); StatusCode initialize(); StatusCode execute(); StatusCode finalize(); private: ToolHandle<IMuonDigitizationTool> m_digTool; }; #endif
[ "rushioda@lxplus754.cern.ch" ]
rushioda@lxplus754.cern.ch
8df331dce45e7438630fdc1b125b0af0f608adf7
1edf35c781432e70c9083f306c08d7a55bdf5297
/CIT125_Ch.13_Fig_13-13/CIT125_Ch.13_Fig_13-13.cpp
1e6accaf88daf50bfe0814ce3ade026c9040eb94
[]
no_license
LuigiRobles/CIT125_Ch.13_Fig_13-13
eea0aa31d4e2f5c0e49e7248c558f003cf4d218e
dfa244e9c077e097e734e18eaeba53ee3cfc701f
refs/heads/master
2022-11-30T15:38:07.593246
2020-08-02T22:55:49
2020-08-02T22:55:49
284,556,301
0
0
null
null
null
null
UTF-8
C++
false
false
1,678
cpp
// CIT125 Intro To C++ Luigi Robles // 08-01-2020 Summer Term // Ch.13 pg.475 Fig.13-13 Zip Code Program // Checks whether a ZIP code contains valid number of characters // and whether each character is a number #include <iostream> #include <string> using namespace std; //function prototype char verifyNumeric(string zip); int main() { //declare and initialize variables string zipCode = ""; char isAllNumbers = ' '; cout << "Five-character ZIP code (-1 to end): "; cin >> zipCode; //input for ZIP code while (zipCode != "-1") { if (zipCode.length() == 5) //checking ZIP code for 5 characters { cout << "-->Correct number of characters"; isAllNumbers = verifyNumeric(zipCode); if (isAllNumbers == 'Y') cout << endl << "-->All numbers"; else cout << endl << "-->Not all numbers"; //end if } else cout << "-->Incorrect number of characters"; //False path for anything below 5 characters //end if cout << endl << endl; cout << "Five-characters ZIP code (-1 to end): "; cin >> zipCode; //continue with loop if -1 is not entered } //end while return 0; } //end of main function //******Function Definitions***** char verifyNumeric(string zip) { //determine whether each character is a number string currentChar = ""; int sub = 0; //character subscript char isANumber = 'Y'; //assume all numbers while (sub < 5 && isANumber == 'Y') { currentChar = zip.substr(sub, 1); if (currentChar >= "0" && currentChar <= "9") //character is numeric, so check next character sub += 1; else //character is not a number isANumber = 'N'; //end if } //end while return isANumber; } //end of verifyNumeric function
[ "Luigi.robles0846@my.riohondo.edu" ]
Luigi.robles0846@my.riohondo.edu
523a09011711fadf0454ecd2afb51ae72505c8b8
0f7f3bdd19f9c460bbf5f66ba79cb0c3cd80fa63
/Results/Force0000005x52/main.cpp
d2f5b84d2b35ddf1638e2ff61caecdf9d2644cd5
[]
no_license
shurikkuzmin/BinaryMicrochannel3D
9c95d8c75cbbb3e83bc0dd81cec0385dbe199b7d
152de567b25aa1b881dcb793db9fef57ec84392c
refs/heads/master
2021-09-02T03:46:39.502135
2011-09-25T14:13:11
2011-09-25T14:13:11
115,768,117
2
1
null
null
null
null
UTF-8
C++
false
false
3,934
cpp
#include <mpi.h> #include <iostream> #include <math.h> #include <fstream> #include <string> #include <sstream> #include "mpi_singleton.h" //Inclusion of lattice implementation #include "lattice.hpp" #include "solver.hpp" #include "params_list.h" #include "descriptor.h" //Lattice Boltzmann initialization and parameters const int NX=52; const int NY=52; const int NZ=1500; const int NPOP=19; const int NUM=NX*NY*NZ; const int NUMTOTAL=NUM*NPOP; const int NUMTIME=250001; const int NUMOUTPUT=10000; const int NUMSIGNAL=50; //Binary-liquid initialization const int width=10; const int radius=6; const double rhol=1.0; const double rhog=1.0; int main(int argc,char* argv[]) { //Parallel Debugging #ifdef DEBUG int DebugWait=1; while (DebugWait); #endif /* DEBUG */ //Specify main communicator MPISingleton mpi_singleton; ParamsList params; if (argc>1) params.add("force_z",atof(argv[1])*0.000005); else params.add("force_z",0.00003); std::cout<<params("force_z").value<double>()<<"\n"; //Specify parameters params.add("omega",1.0); params.add("aconst", 0.04); params.add("kconst", 0.04); params.add("gammaconst",1.0); params.add("phase_gradient",0.0); params.add("phase_wall",0.0); params.add("rho_wall",0.5); params.add("tau_phi",2.0); params.add("tau_liq",2.5); params.add("tau_gas",0.7); params.add("force_x",0.0); params.add("force_y",0.0); //params.add("force_z",0.00003); params.add("NX",NX); params.add("NY",NY); params.add("NZ",NZ); Solver<Descriptor> solver(params); //Solver initialization from the file //solver.load_file("equili"); //Initialization //Density and phase field initialization double rho_temp; double phase_temp; double u_temp[3]; for (int counter=0; counter<NUM; counter++) { int iZ=counter/(NX*NY); int iY=(counter%(NX*NY))/NX; int iX=(counter%(NX*NY))%NX; //Initialization of the part of the channel //if ((iZ>=(NZ-1)/3)&&(iZ<=2*(NZ-1)/3)&&(iX*iX+iY*iY<=20*20)) if ((iZ>=(NZ-1)/3)&&(iZ<=2*(NZ-1)/3)&&(iX<=NX-width-1)&&(iY<=NY-width-1)) { rho_temp=rhog; phase_temp=-1.0; u_temp[0]=0.0; u_temp[1]=0.0; u_temp[2]=0.0; } else { rho_temp=rhol; phase_temp=1.0; u_temp[0]=0.0; u_temp[1]=0.0; u_temp[2]=0.0; } // if ((iX==1)&&(iY!=NY-1)) // { // rho_temp=rhog; // phase_temp=-1.0; // u_temp[0]=0.1; // u_temp[1]=0.0; // u_temp[2]=0.1; // } // if ((iY==1)&&(iX!=NX-1)) // { // u_temp[0]=0.0; // u_temp[1]=0.1; // u_temp[2]=0.1; // rho_temp=rhog; // phase_temp=-1.0; // // // } solver.putDensity(iX,iY,iZ,iX,iY,iZ,rho_temp); solver.putPhase(iX,iY,iZ,iX,iY,iZ,phase_temp); solver.putVelocity(iX,iY,iZ,iX,iY,iZ,u_temp); } //Initialization of the populations solver.init(); //Main iteration for (int time_counter=0; time_counter<NUMTIME; time_counter++) { //Collision procedure with the reconstruction of the equilibrium populations solver.collide_stream(); if (time_counter%NUMSIGNAL==0) { cout<<"Time is "<<time_counter<<"\n"; if (solver.checkNAN()) { cout<<"Phase fields contain NaN values\n"; MPI_Abort(MPI_COMM_WORLD,-1); } } //Output files if (time_counter%NUMOUTPUT==0) { std::stringstream file_name; std::stringstream time_string; time_string<<time_counter; file_name<<"phase"<<std::string(6-time_string.str().size(),'0')<<time_counter; //solver.writeTextWholeVelocity(file_name.str()); solver.writeWholeDensityPhaseVelocity(file_name.str()); cout<<"Output is done on the step "<<time_counter<<"\n"; } } return 0; }
[ "shurik@alex-desktop.(none)" ]
shurik@alex-desktop.(none)
70d39bc8388a2e6fd5be569514b07f748b59f080
961dd3e240d615415f2a2fb0108aa23959475755
/Blinker/examples/Blinker_ESPTOUCH/ESPTOUCH_MQTT/ESPTOUCH_MQTT.ino
1f74eff8f4c37ba895e5145ac4f008938620edb7
[ "MIT" ]
permissive
ilkerya/ArduinoLibraries
d2a2d8d7b88f3563d1b326369f6a3e4169c46fde
e7338a82d7aa987dff0a0fdb9ac0cea547104fe4
refs/heads/master
2020-04-08T16:23:20.419305
2018-11-28T14:37:11
2018-11-28T14:37:11
159,516,277
0
2
null
null
null
null
UTF-8
C++
false
false
1,724
ino
/* ***************************************************************** * * Download latest Blinker library here: * https://github.com/blinker-iot/blinker-library/archive/master.zip * * * Blinker is a platform with iOS and Android apps to * control embedded hardware like Arduino, Raspberrt Pi. * You can easily build graphic interfaces for all your * projects by simply dragging and dropping widgets. * * Docs: https://doc.blinker.app/ * https://github.com/blinker-iot/blinker-doc/wiki * * ***************************************************************** * * Blinker 库下载地址: * https://github.com/blinker-iot/blinker-library/archive/master.zip * * Blinker 是一个运行在 IOS 和 Android 上用于控制嵌入式硬件的应用程序。 * 你可以通过拖放控制组件,轻松地为你的项目建立图形化控制界面。 * * 文档: https://doc.blinker.app/ * https://github.com/blinker-iot/blinker-doc/wiki * * *****************************************************************/ #define BLINKER_PRINT Serial #define BLINKER_MQTT #define BLINKER_ESP_SMARTCONFIG #include <Blinker.h> char auth[] = "Your MQTT Secret Key"; void setup() { Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); digitalWrite(LED_BUILTIN, LOW); Blinker.begin(auth); } void loop() { Blinker.run(); if (Blinker.available()) { BLINKER_LOG2("Blinker.readString(): ", Blinker.readString()); uint32_t BlinkerTime = millis(); Blinker.beginFormat(); Blinker.vibrate(); Blinker.print("millis", BlinkerTime); Blinker.endFormat(); digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } }
[ "ilkerya@gmail.com" ]
ilkerya@gmail.com
6030686aff6853b93d476ac2cfbfc848293353f1
13d96ca0d2d2dcb4434e2c676b12866d402685ae
/polymorphism/Shapes/main.cpp
e031015c4ed8a00291ec70b99ca7241e79b2f126
[]
no_license
merilinpisina/fmi-oop-2019-2020
e7fb4576ce45ab387a721692c7d53c782500c22d
ba3af46b7759b44b9cbd3a1cfb60facefad784b7
refs/heads/master
2021-07-11T19:04:40.191672
2021-03-26T08:18:08
2021-03-26T08:18:08
241,052,236
0
1
null
null
null
null
UTF-8
C++
false
false
1,529
cpp
#include <fstream> #include <iostream> #include "FigureContainer.h" void createVectorFromFile(FigureContainer& vec) { std::ifstream ifs("Input.txt"); if (!ifs.is_open()) return; while (!ifs.eof()) { //last reading will return nullptr...ok Figure* curFig = Figure::createFigure(ifs); if (curFig != nullptr && ifs) { vec.push_back(curFig); vec.back()->readFromFile(ifs); } } ifs.close(); // not needed } void solveAtIndex(const FigureContainer& vec){ int index; std::cout << "you are searching for Figure at index = "; std::cin >> index; int searched = 0; for (size_t i = 0; i < vec.getSize(); i++){ size_t j = 0; while (vec.getAt(i)->getFigureAt(j) != NULL) { searched++; if (searched - 1 == index) { vec.getAt(i)->getFigureAt(j)->print(); return; } j++; } std::cout << '\n'; } std::cout << "none"; } void solveIsThere(const FigureContainer& vec){ double x, y; std::cout << "enter coordinates for point A\n"; std::cin >> x >> y; std::cout << "the following figures contain the point A (" << x << " ," << y << ")\n"; bool seen = false; for (size_t i = 0; i < vec.getSize(); i++){ if (vec.getAt(i)->isInside(x, y)) { seen = true; std::cout << '\n'; } } if (!seen) std::cout << "none\n"; } int main() { FigureContainer vec; createVectorFromFile(vec); std::cout << "all figures : \n"; for (size_t i = 0; i < vec.getSize(); i++) vec.getAt(i)->print(); solveIsThere(vec); solveAtIndex(vec); return 0; }
[ "merilinpisina@gmail.com" ]
merilinpisina@gmail.com
97e41b3ed9bbfd98f709713fe94efb131bc54639
1be5334d362a3bb1fdf3ec4d87b316f65c866558
/src/BLE_Connect_mac.cpp
71ca3279c88e4059fb52c3c683cccd1f7dadf567
[]
no_license
perrycharlton/BLE_CLIENT_MAC
30ce76e7349f24dbacc54e5517a4f36f7f15b3d1
e732bb892529e11e62fbbe25fc4adb2574304730
refs/heads/master
2020-12-02T18:46:43.985657
2019-12-31T12:39:31
2019-12-31T12:39:31
231,085,858
0
0
null
null
null
null
UTF-8
C++
false
false
4,405
cpp
#include "BLEDevice.h" #include <Arduino.h> // The remote service we wish to connect to. static BLEUUID serviceUUID("226c0000-6476-4566-7562-66734470666d"); // The characteristic of the remote service we are interested in. static BLEUUID charUUID("226caa55-6476-4566-7562-66734470666d"); // static BLEAddress MJAddress("58:2d:34:32:2c:c7"); // static BLEAddress MJAddress("58:2d:34:32:33:6e"); // static BLEAddress MJAddress; static const int addressSize = 5; char const* address[addressSize] = { "58:2d:34:32:33:6e", "58:2d:34:32:2c:c7", "58:2d:34:32:3c:f3", "58:2d:34:32:3c:f3", "58:2d:34:32:2e:d4"}; int i = 0; char const* addrs; // static boolean doConnect = false; static boolean connected = false; static BLERemoteService* pRemoteService; static BLERemoteCharacteristic* pMyRemoteCharacteristic; // static boolean doScan = false; // static BLERemoteCharacteristic* pRemoteCharacteristic; // static BLEAdvertisedDevice* myDevice; static BLEClient* pClient; static void notifyCallback( BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) { // Serial.print("Notify callback for characteristic "); // Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str()); // Serial.print(" of data length "); // Serial.println(length); // Serial.print("data: "); // Serial.println((char*)pData); Serial.printf("Connected to mac: %s\t Data: %s\n", addrs, pData); // pMyRemoteCharacteristic->registerForNotify(NULL, false); // delay(300); // pClient->disconnect(); } // class MyClientCallback : public BLEClientCallbacks { // void onConnect(BLEClient* pclient) { // } // void onDisconnect(BLEClient* pclient) { // connected = false; // // delete pClient; // // delete pclient; // Serial.println("onDisconnect"); // } // }; bool connectToServer(char const* Address) { BLEAddress MJAddress(Address); // pClient = BLEDevice::createClient(); // Serial.println("Forming a connection to "); // Serial.printf("Is client connected %i\n", pClient->isConnected()); // pClient->setClientCallbacks(new MyClientCallback()); connected = pClient->connect(MJAddress); if(!connected){ // delete pClient; // delete myDevice; return false; } // Serial.printf("Connected = %i - Connected to mac: %s\n", pClient->isConnected(), MJAddress.toString().c_str()); // Serial.println(pClient->isConnected()); // Get a reference to a specific remote service on the server // Obtain a reference to the service we are after in the remote BLE server. pRemoteService = pClient->getService(serviceUUID); if (pRemoteService == nullptr) { Serial.print("Failed to find our service UUID: "); Serial.println(serviceUUID.toString().c_str()); pClient->disconnect(); } // Serial.printf(" - Found our service - %s\n" , pRemoteService->toString().c_str()); // Get a reference to a specific remote characteristic owned by the service pMyRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID); if (pMyRemoteCharacteristic == nullptr) { Serial.print("Failed to find our characteristic UUID: "); Serial.println(charUUID.toString().c_str()); pClient->disconnect(); } pMyRemoteCharacteristic->registerForNotify(notifyCallback, true); // Retrieve the current value of the remote characteristic. delay(200); std::string myValue = pMyRemoteCharacteristic->readValue(); // Serial.printf("Thes ae the values returned: %f\n", pMyRemoteCharacteristic->readFloat()); // pMyRemoteCharacteristic->registerForNotify(notifyCallback, false); // Serial.printf("The notifcations value: %s\n\n", myValue.c_str()); connected = true; return true; } void setup() { Serial.begin(115200); Serial.println("Starting Arduino BLE Client application..."); BLEDevice::init(""); // Create the client pClient = BLEDevice::createClient(); } // This is the Arduino main loop function. void loop() { // Serial.printf("Connection: %d\n", pClient->isConnected()); // pClient->isConnected(); if (!pClient->isConnected() ){ delay(1000); Serial.println("Reconnecting"); addrs = address[i]; connectToServer(address[i]); i < (addressSize-1)?i++:i=0; Serial.printf("Reconnecting no = %i. Mac = %s\n", i, address[i]); } delay(1000); } // End of loop
[ "perry@perrycharlton.com" ]
perry@perrycharlton.com
1740096e05c7c09548ab31cc80c9d998b92cd5db
db1700bb59fa3f0e5f1e080c3ed69829850eea1f
/lab4/stackonarray.cpp
02a68645160aa491c35e67cf880455fc7e539092
[]
no_license
iperius93/209180
4d904f3699d06c2749966765f1a87f39a1de5080
c87676bb8085d9724b5cea910ec090317d850728
refs/heads/master
2021-01-20T05:29:23.728190
2015-04-18T14:37:53
2015-04-18T14:37:53
31,706,670
0
1
null
null
null
null
UTF-8
C++
false
false
2,108
cpp
/* * stackonarray.cpp * * Created on: Mar 19, 2015 * Author: serek8 */ #include "stackonarray.h" StackOnArray::StackOnArray() { sizeOfTable =1; index=0; tableOfData = new int[1]; } void StackOnArray::pushByOneAlloc(int arg) { if(index==0){ tableOfData[0] = arg; ++index; // teraz index = 1 return; } if(index==sizeOfTable) { int *tmpTableOfData = new int[index+1]; //index pokazuje zawsze na nastepny element ktory jest jeszcze pusty for(int i =0 ; i<index; i++) { tmpTableOfData[i] = tableOfData[i]; } delete[] tableOfData; tableOfData = tmpTableOfData; } tableOfData[index] = arg; sizeOfTable = ++index ; //Po zakonczeniu tej funkcji index i sizeOfTable musza byc sobie rowne } void StackOnArray::pushByDoubleAlloc(int arg) { if(index==0){ tableOfData[0] = arg; ++index; return; } if(sizeOfTable==index) { int *tmpTableOfData = new int[2*index]; sizeOfTable = 2*index; for(int i =0 ; i<index; i++) { tmpTableOfData[i] = tableOfData[i]; } delete[] tableOfData; tableOfData = tmpTableOfData; } tableOfData[index++] = arg; // powiekszam index po przypisaniu nowej wartosci } int StackOnArray::pop() { return tableOfData[--index]; } StackOnArray:: ~StackOnArray() { delete [] tableOfData; } int StackOnArray::returnIndex() { return index; } void StackOnArray::quicksort(int lewy, int prawy) { int v= this->tableOfData[(lewy+prawy)/2]; int i,j,x; i=lewy; j=prawy; do { while(this->tableOfData[i]<v) i++; while(this->tableOfData[j]>v) j--; if(i<=j) { x=this->tableOfData[i]; this->tableOfData[i]=this->tableOfData[j]; this->tableOfData[j]=x; i++; j--; } } while(i<=j); if(j>lewy) this->quicksort(lewy, j); if(i<prawy) this->quicksort(i, prawy); } void StackOnArray::wyswietl_stos() { for(int i=0;i<index;i++) { cout<<this->tableOfData[i]<<' '; if(i%10 == 0 && i != 0) cout << endl; } }
[ "rafal@Asus.(none)" ]
rafal@Asus.(none)
c69c2043865e13927ba8892068074461863cdc79
0e4d04d7fbedcd245d084d7296ca1b06d06de89e
/project/CardFour.h
23e0a30f33c825482f7b8f968690f625f977e2be
[]
no_license
mennatallah-nawar/Snakes-and-ladders-game
fe314477c9953cb81abbb5530330be84f325bc06
8386b6e0c4564052b11eb0f4ffe1d7cc11cd4362
refs/heads/master
2023-05-15T18:23:15.584650
2021-06-13T23:02:06
2021-06-13T23:02:06
376,606,691
0
0
null
null
null
null
UTF-8
C++
false
false
584
h
#pragma once #include "Card.h" class CardFour :public Card { Cell* pCell; public: CardFour(const CellPosition& pos); // A Constructor takes card position virtual void Apply(Grid* pGrid, Player* pPlayer); // Applies the effect of CardOne on the passed Player // by decrementing the player's wallet by the walletAmount data member //virtual bool Validate(); virtual void CopyCard(Grid* pGrid); virtual void CutCard(Grid* pGrid); virtual void PasteCard(Grid* pGrid); void Save(ofstream& OutFile, TYPE CARD); void Read(ifstream& Infile); ~CardFour(); };
[ "55787939+mennatallah-nawar@users.noreply.github.com" ]
55787939+mennatallah-nawar@users.noreply.github.com
4c892992495110e209dab6f1875dd8caffacf817
920c4ef30727f0c51b5c9f00bdd9b923b541853e
/Code_Cpp/cppserver备份资料/code/library/source/operators/include/cookie/cookie.h
2e32f7948bf9266e4aeb65dd898f7801db5f0c66
[]
no_license
fishney/TDServer
10e50cd156b9109816ddebde241614a28546842a
19305fc7bf649a9add86146bd1bfd253efa6e9cb
refs/heads/master
2023-03-16T22:24:45.802339
2017-10-19T07:02:56
2017-10-19T07:02:56
null
0
0
null
null
null
null
GB18030
C++
false
false
596
h
/*----------------- cookie.h * * Copyright (C): 2011 Mokylin·Mokyqi * Author : 赵文源 * Version : V1.0 * Date : 2012/6/27 19:32:53 *-------------------------------------------------------------- * *------------------------------------------------------------*/ #pragma once #include "basic/stringFunctions.h" #include "encrypt/include/encrypts.h" /*************************************************************/ namespace cookie { //--- 初始化 bool init (uint32 _timeout,pc_str _key); //--- 登录验证 bool login_verify(url_parser&_param,std::string&_uname); };
[ "haibo tang" ]
haibo tang
406582ce5925b9c2bf071800c7a0b268f44f9f55
887f3a72757ff8f691c1481618944b727d4d9ff5
/third_party/gecko_1.9.1/win32/gecko_sdk/include/nsIHttpHeaderVisitor.h
4a3acc9703e1efee2e966dfd9c990662ea71f821
[]
no_license
zied-ellouze/gears
329f754f7f9e9baa3afbbd652e7893a82b5013d1
d3da1ed772ed5ae9b82f46f9ecafeb67070d6899
refs/heads/master
2020-04-05T08:27:05.806590
2015-09-03T13:07:39
2015-09-03T13:07:39
41,813,794
1
0
null
null
null
null
UTF-8
C++
false
false
3,238
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/netwerk/protocol/http/public/nsIHttpHeaderVisitor.idl */ #ifndef __gen_nsIHttpHeaderVisitor_h__ #define __gen_nsIHttpHeaderVisitor_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIHttpHeaderVisitor */ #define NS_IHTTPHEADERVISITOR_IID_STR "0cf40717-d7c1-4a94-8c1e-d6c9734101bb" #define NS_IHTTPHEADERVISITOR_IID \ {0x0cf40717, 0xd7c1, 0x4a94, \ { 0x8c, 0x1e, 0xd6, 0xc9, 0x73, 0x41, 0x01, 0xbb }} /** * Implement this interface to visit http headers. * * @status FROZEN */ class NS_NO_VTABLE NS_SCRIPTABLE nsIHttpHeaderVisitor : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IHTTPHEADERVISITOR_IID) /** * Called by the nsIHttpChannel implementation when visiting request and * response headers. * * @param aHeader * the header being visited. * @param aValue * the header value (possibly a comma delimited list). * * @throw any exception to terminate enumeration */ /* void visitHeader (in ACString aHeader, in ACString aValue); */ NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIHttpHeaderVisitor, NS_IHTTPHEADERVISITOR_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIHTTPHEADERVISITOR \ NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIHTTPHEADERVISITOR(_to) \ NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) { return _to VisitHeader(aHeader, aValue); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIHTTPHEADERVISITOR(_to) \ NS_SCRIPTABLE NS_IMETHOD VisitHeader(const nsACString & aHeader, const nsACString & aValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->VisitHeader(aHeader, aValue); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsHttpHeaderVisitor : public nsIHttpHeaderVisitor { public: NS_DECL_ISUPPORTS NS_DECL_NSIHTTPHEADERVISITOR nsHttpHeaderVisitor(); private: ~nsHttpHeaderVisitor(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsHttpHeaderVisitor, nsIHttpHeaderVisitor) nsHttpHeaderVisitor::nsHttpHeaderVisitor() { /* member initializers and constructor code */ } nsHttpHeaderVisitor::~nsHttpHeaderVisitor() { /* destructor code */ } /* void visitHeader (in ACString aHeader, in ACString aValue); */ NS_IMETHODIMP nsHttpHeaderVisitor::VisitHeader(const nsACString & aHeader, const nsACString & aValue) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIHttpHeaderVisitor_h__ */
[ "gears.daemon@fe895e04-df30-0410-9975-d76d301b4276" ]
gears.daemon@fe895e04-df30-0410-9975-d76d301b4276
b2eb5e3914c4af86dc26dfd5de0cc55e9162472f
fae45a23a885b72cd27c0ad1b918ad754b5de9fd
/benchmarks/shenango/shenango/apps/bench/netbench.cc
cfc41f6514646da5d5f97e02c776a891ebcaf9f0
[ "MIT", "Apache-2.0" ]
permissive
bitslab/CompilerInterrupts
6678700651c7c83fd06451c94188716e37e258f0
053a105eaf176b85b4c0d5e796ac1d6ee02ad41b
refs/heads/main
2023-06-24T18:09:43.148845
2021-07-26T17:32:28
2021-07-26T17:32:28
342,868,949
3
3
MIT
2021-07-19T15:38:30
2021-02-27T13:57:16
C
UTF-8
C++
false
false
9,073
cc
extern "C" { #include <base/log.h> #include <net/ip.h> } #undef min #undef max #include "thread.h" #include "sync.h" #include "timer.h" #include "net.h" #include "fake_worker.h" #include "proto.h" #include <iostream> #include <iomanip> #include <utility> #include <memory> #include <chrono> #include <vector> #include <algorithm> #include <numeric> #include <random> namespace { using sec = std::chrono::duration<double, std::micro>; // The number of samples to discard from the start and end. constexpr uint64_t kDiscardSamples = 1000; // The maximum lateness to tolerate before dropping egress samples. constexpr uint64_t kMaxCatchUpUS = 10; // the number of worker threads to spawn. int threads; // the remote UDP address of the server. netaddr raddr; // the number of samples to gather. uint64_t n; // the mean service time in us. double st; void ServerWorker(std::unique_ptr<rt::TcpConn> c) { payload p; std::unique_ptr<FakeWorker> w(FakeWorkerFactory("stridedmem:3200:64")); if (w == nullptr) panic("couldn't create worker"); while (true) { // Receive a network response. ssize_t ret = c->ReadFull(&p, sizeof(p)); if (ret <= 0 || ret > static_cast<ssize_t>(sizeof(p))) { if (ret == 0 || ret == -ECONNRESET) break; panic("read failed, ret = %ld", ret); } // Perform fake work if requested. if (p.workn != 0) w->Work(p.workn * 82.0); // Send a network request. ssize_t sret = c->WriteFull(&p, ret); if (sret != ret) { if (sret == -EPIPE || sret == -ECONNRESET) break; panic("write failed, ret = %ld", sret); } } } void ServerHandler(void *arg) { std::unique_ptr<rt::TcpQueue> q(rt::TcpQueue::Listen({0, kNetbenchPort}, 4096)); if (q == nullptr) panic("couldn't listen for connections"); while (true) { rt::TcpConn *c = q->Accept(); if (c == nullptr) panic("couldn't accept a connection"); rt::Thread([=]{ServerWorker(std::unique_ptr<rt::TcpConn>(c));}).Detach(); } } std::vector<double> PoissonWorker(rt::TcpConn *c, double req_rate, double service_time, rt::WaitGroup *starter) { constexpr int kBatchSize = 32; // Seed the random generator. std::mt19937 g(microtime()); // Create a packet transmit schedule. std::vector<double> sched; std::exponential_distribution<double> rd(1.0 / (1000000.0 / req_rate)); std::vector<double> tmp(n); std::generate(tmp.begin(), tmp.end(), std::bind(rd, g)); sched.push_back(tmp[0]); for (std::vector<double>::size_type j = 1; j < tmp.size(); ++j) { tmp[j] += tmp[j - 1]; sched.push_back(static_cast<uint64_t>(tmp[j])); } // Create a fake work schedule. std::vector<double> work(n); std::exponential_distribution<double> wd(1.0 / service_time); std::generate(work.begin(), work.end(), std::bind(wd, g)); // Reserve space to record results. auto n = sched.size(); std::vector<double> timings; timings.reserve(n); std::vector<uint64_t> start_us(n); // Start the receiver thread. auto th = rt::Thread([&]{ payload rp; while (true) { ssize_t ret = c->ReadFull(&rp, sizeof(rp)); if (ret != static_cast<ssize_t>(sizeof(rp))) { if (ret == 0 || ret < 0) break; panic("read failed, ret = %ld", ret); } barrier(); uint64_t ts = microtime(); barrier(); timings.push_back(ts - start_us[rp.idx]); } }); // Initialize timing measurement data structures. payload p[kBatchSize]; int j = 0; // Synchronized start of load generation. starter->Done(); starter->Wait(); barrier(); uint64_t expstart = microtime(); barrier(); for (unsigned int i = 0; i < n; ++i) { barrier(); uint64_t now = microtime(); barrier(); if (now - expstart < sched[i]) { ssize_t ret = c->WriteFull(p, sizeof(payload) * j); if (ret != static_cast<ssize_t>(sizeof(payload) * j)) panic("write failed, ret = %ld", ret); j = 0; rt::Sleep(sched[i] - (microtime() - expstart)); now = microtime(); } if (now - expstart - sched[i] > kMaxCatchUpUS) continue; barrier(); start_us[i] = microtime(); barrier(); // Enqueue a network request. p[j].idx = i; p[j].workn = work[i]; p[j].tag = 0; j++; if (j >= kBatchSize || i == n - 1) { ssize_t ret = c->WriteFull(p, sizeof(payload) * j); if (ret != static_cast<ssize_t>(sizeof(payload) * j)) panic("write failed, ret = %ld", ret); j = 0; } } c->Shutdown(SHUT_RD); th.Join(); return timings; } std::vector<double> RunExperiment(double req_rate, double *reqs_per_sec) { // Create one TCP connection per thread. std::vector<std::unique_ptr<rt::TcpConn>> conns; for (int i = 0; i < threads; ++i) { std::unique_ptr<rt::TcpConn> outc(rt::TcpConn::Dial({0, 0}, raddr)); if (unlikely(outc == nullptr)) panic("couldn't connect to raddr."); conns.emplace_back(std::move(outc)); } // Launch a worker thread for each connection. rt::WaitGroup starter(threads + 1); std::vector<rt::Thread> th; std::unique_ptr<std::vector<double>> samples[threads]; for (int i = 0; i < threads; ++i) { th.emplace_back(rt::Thread([&, i]{ auto v = PoissonWorker(conns[i].get(), req_rate / threads, st, &starter); samples[i].reset(new std::vector<double>(std::move(v))); })); } // Give the workers time to initialize, then start recording. starter.Done(); starter.Wait(); // |--- start experiment duration timing ---| barrier(); auto start = std::chrono::steady_clock::now(); barrier(); // Wait for the workers to finish. for (auto& t: th) t.Join(); // |--- end experiment duration timing ---| barrier(); auto finish = std::chrono::steady_clock::now(); barrier(); // Close the connections. for (auto& c: conns) c->Abort(); // Aggregate all the latency timings together. uint64_t total = 0; std::vector<double> timings; for (int i = 0; i < threads; ++i) { auto &v = *samples[i]; total += v.size(); if (v.size() <= kDiscardSamples * 2) panic("not enough samples"); v.erase(v.begin(), v.begin() + kDiscardSamples); v.erase(v.end() - kDiscardSamples, v.end()); timings.insert(timings.end(), v.begin(), v.end()); } // Report results. double elapsed = std::chrono::duration_cast<sec>(finish - start).count(); *reqs_per_sec = static_cast<double>(total) / elapsed * 1000000; return timings; } void DoExperiment(double req_rate) { constexpr int kRounds = 1; std::vector<double> timings; double reqs_per_sec = 0; for (int i = 0; i < kRounds; i++) { double tmp; auto t = RunExperiment(req_rate, &tmp); timings.insert(timings.end(), t.begin(), t.end()); reqs_per_sec += tmp; rt::Sleep(500 * rt::kMilliseconds); } reqs_per_sec /= kRounds; std::sort(timings.begin(), timings.end()); double sum = std::accumulate(timings.begin(), timings.end(), 0.0); double mean = sum / timings.size(); double count = static_cast<double>(timings.size()); double p9 = timings[count * 0.9]; double p99 = timings[count * 0.99]; double p999 = timings[count * 0.999]; double p9999 = timings[count * 0.9999]; double min = timings[0]; double max = timings[timings.size() - 1]; std::cout << std::setprecision(2) << std::fixed << "t: " << threads << " rps: " << reqs_per_sec << " n: " << timings.size() << " min: " << min << " mean: " << mean << " 90%: " << p9 << " 99%: " << p99 << " 99.9%: " << p999 << " 99.99%: " << p9999 << " max: " << max << std::endl; } void ClientHandler(void *arg) { for (double i = 500000; i <= 5000000; i += 500000) DoExperiment(i); } int StringToAddr(const char *str, uint32_t *addr) { uint8_t a, b, c, d; if(sscanf(str, "%hhu.%hhu.%hhu.%hhu", &a, &b, &c, &d) != 4) return -EINVAL; *addr = MAKE_IP_ADDR(a, b, c, d); return 0; } } // anonymous namespace int main(int argc, char *argv[]) { int ret; if (argc < 3) { std::cerr << "usage: [cfg_file] [cmd] ..." << std::endl; return -EINVAL; } std::string cmd = argv[2]; if (cmd.compare("server") == 0) { ret = runtime_init(argv[1], ServerHandler, NULL); if (ret) { printf("failed to start runtime\n"); return ret; } } else if (cmd.compare("client") != 0) { std::cerr << "invalid command: " << cmd << std::endl; return -EINVAL; } if (argc != 7) { std::cerr << "usage: [cfg_file] client [#threads] [remote_ip] [n] [service_us]" << std::endl; return -EINVAL; } threads = std::stoi(argv[3], nullptr, 0); ret = StringToAddr(argv[4], &raddr.ip); if (ret) return -EINVAL; raddr.port = kNetbenchPort; n = std::stoll(argv[5], nullptr, 0); st = std::stod(argv[6], nullptr); ret = runtime_init(argv[1], ClientHandler, NULL); if (ret) { printf("failed to start runtime\n"); return ret; } return 0; }
[ "nilanjana.basu87@gmail.com" ]
nilanjana.basu87@gmail.com
9fb38c2550c943739f31f58fd5da74a0dea8ee07
d988f3302c7c4f49583fec21c07658ddb09b81e0
/src/Cpl/Itc/ServiceMessage.h
f99607b5691113b98db0d4d4374daec3f693d186
[]
no_license
johnttaylor/colony.apps
2b10141d8cb30067a5e387e6c53af9955549b17b
839f3d62b660111ab122a96f550c8ae9de63faa0
refs/heads/develop
2023-05-10T17:24:58.286447
2021-12-05T20:54:43
2021-12-05T20:54:43
41,272,799
0
0
null
2021-12-05T20:54:45
2015-08-24T00:10:30
C
UTF-8
C++
false
false
1,637
h
#ifndef Cpl_Itc_ServiceMessage_h_ #define Cpl_Itc_ServiceMessage_h_ /*----------------------------------------------------------------------------- * This file is part of the Colony.Core Project. The Colony.Core Project is an * open source project with a BSD type of licensing agreement. See the license * agreement (license.txt) in the top/ directory or on the Internet at * http://integerfox.com/colony.core/license.txt * * Copyright (c) 2014-2020 John T. Taylor * * Redistributions of the source code must retain the above copyright notice. *----------------------------------------------------------------------------*/ /** @file */ #include "Cpl/Itc/Message.h" #include "Cpl/Itc/ReturnHandler.h" /// namespace Cpl { /// namespace Itc { /** This class represents a defined message, which is posted to a mailbox-server as a request. It includes members which enable the client to be notified when the server thread has completed the request. */ class ServiceMessage : public Message { private: /** References the handler which is invoked by the server thread when it returns ownership of the message to the client. */ ReturnHandler& m_rh; public: /// Constructor ServiceMessage( ReturnHandler& rh ) noexcept; /** This operation is invoked by the server when it has completed the operation implemented as a part of this message. Use of this operation relinquishes the ownership of the message from the server (which invokes the operation) to the client. */ void returnToSender() noexcept; }; }; // end namespaces }; #endif // end header latch
[ "john.t.taylor@gmail.com" ]
john.t.taylor@gmail.com
77969f4c70ca56aa199d5957ab3d793bdabf46fc
a1cc22bafb4429b53898962b1131333420eddf05
/cmdstan/stan/lib/stan_math/test/unit/math/rev/meta/VectorBuilderHelper_test.cpp
ac845bbfe35ce5555226d59d779a212b8c5f71f3
[ "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only", "Apache-2.0", "BSD-3-Clause", "GPL-3.0-only" ]
permissive
metrumresearchgroup/Torsten
d9510b00242b9f77cdc989657a4956b3018a5f3a
0168482d400e4b819acadbc28cc817dd1a037c1b
refs/heads/master
2023-09-01T17:44:46.020886
2022-05-18T22:46:35
2022-05-18T22:46:35
124,574,336
50
18
BSD-3-Clause
2023-09-09T06:32:36
2018-03-09T17:48:27
C++
UTF-8
C++
false
false
3,134
cpp
#include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/fun/size.hpp> #include <gtest/gtest.h> #include <vector> TEST(MetaTraitsRevScal, VectorBuilderHelper_false_true) { using stan::VectorBuilderHelper; using stan::math::size; using stan::math::var; var a_var(1); VectorBuilderHelper<double, false, true> dvv1(size(a_var)); EXPECT_THROW(dvv1[0], std::logic_error); EXPECT_THROW(dvv1.data(), std::logic_error); } TEST(MetaTraitsRevArr, VectorBuilderHelper_false_true) { using stan::VectorBuilderHelper; using stan::math::size; using stan::math::var; using std::vector; std::vector<var> a_std_vector(3); VectorBuilderHelper<double, false, true> dvv2(size(a_std_vector)); EXPECT_THROW(dvv2[0], std::logic_error); EXPECT_THROW(dvv2.data(), std::logic_error); } TEST(MetaTraitsRevArr, VectorBuilderHelper_true_true) { using stan::VectorBuilderHelper; using stan::math::size; using stan::math::var; using std::vector; var a_var(1); std::vector<var> a_std_vector(3); VectorBuilderHelper<double, true, true> dvv1(size(a_var)); dvv1[0] = 0.0; EXPECT_FLOAT_EQ(0.0, dvv1[0]); std::vector<double> data1; EXPECT_NO_THROW(data1 = dvv1.data()); EXPECT_EQ(size(a_var), data1.size()); VectorBuilderHelper<double, true, true> dvv2(size(a_std_vector)); dvv2[0] = 0.0; dvv2[1] = 1.0; dvv2[2] = 2.0; EXPECT_FLOAT_EQ(0.0, dvv2[0]); EXPECT_FLOAT_EQ(1.0, dvv2[1]); EXPECT_FLOAT_EQ(2.0, dvv2[2]); std::vector<double> data2; EXPECT_NO_THROW(data2 = dvv2.data()); EXPECT_EQ(size(a_std_vector), data2.size()); } TEST(MetaTraitsRevMat, VectorBuilderHelper_false_true) { using Eigen::Dynamic; using Eigen::Matrix; using stan::VectorBuilderHelper; using stan::math::size; using stan::math::var; Matrix<var, Dynamic, 1> a_vector(4); Matrix<var, 1, Dynamic> a_row_vector(5); VectorBuilderHelper<double, false, true> dvv3(size(a_vector)); EXPECT_THROW(dvv3[0], std::logic_error); EXPECT_THROW(dvv3.data(), std::logic_error); VectorBuilderHelper<double, false, true> dvv4(size(a_row_vector)); EXPECT_THROW(dvv4[0], std::logic_error); EXPECT_THROW(dvv3.data(), std::logic_error); } TEST(MetaTraitsRevMat, VectorBuilderHelper_true_true) { using Eigen::Dynamic; using Eigen::Matrix; using stan::VectorBuilderHelper; using stan::math::size; using stan::math::var; Matrix<var, Dynamic, 1> a_vector(4); Matrix<var, 1, Dynamic> a_row_vector(5); VectorBuilderHelper<double, true, true> dvv3(size(a_vector)); dvv3[0] = 0.0; dvv3[1] = 1.0; dvv3[2] = 2.0; EXPECT_FLOAT_EQ(0.0, dvv3[0]); EXPECT_FLOAT_EQ(1.0, dvv3[1]); EXPECT_FLOAT_EQ(2.0, dvv3[2]); std::vector<double> data3; EXPECT_NO_THROW(data3 = dvv3.data()); EXPECT_EQ(size(a_vector), data3.size()); VectorBuilderHelper<double, true, true> dvv4(size(a_row_vector)); dvv4[0] = 0.0; dvv4[1] = 1.0; dvv4[2] = 2.0; EXPECT_FLOAT_EQ(0.0, dvv4[0]); EXPECT_FLOAT_EQ(1.0, dvv4[1]); EXPECT_FLOAT_EQ(2.0, dvv4[2]); std::vector<double> data4; EXPECT_NO_THROW(data4 = dvv4.data()); EXPECT_EQ(size(a_row_vector), data4.size()); }
[ "yzhang@c-path.org" ]
yzhang@c-path.org
d0af6888d29b2e61e16cc19a51e7585b39ea1648
c03b1c7da6b5b44681fda3bc3d06dc194eff0fdd
/example/Classes/HelloWorldScene.cpp
bab99ebfb1e5d603d886b0ad88a27191ac1609c3
[ "MIT" ]
permissive
adjust/cocos2dx_sdk
190b57a04ed46459ca9bac4e2ebcbb5f17656faf
8189ea0515fb33c40eef5f69cf9147f726605d1c
refs/heads/master
2023-08-01T00:13:58.449498
2022-10-20T10:46:49
2022-10-20T10:46:49
37,716,849
11
12
MIT
2022-10-20T10:46:51
2015-06-19T10:48:57
C++
UTF-8
C++
false
false
8,274
cpp
#include <platform/CCApplication.h> #include "HelloWorldScene.h" #include "AppDelegate.h" #include "Adjust/Adjust2dx.h" #include "Adjust/AdjustEvent2dx.h" USING_NS_CC; Scene *HelloWorld::createScene() { return HelloWorld::create(); } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if (!Scene::init()) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // Create a Label to identify the sample auto label = Label::create(); label->setString("Adjust Cocos2dx Examples app"); label->setSystemFontSize(19); label->setTextColor(Color4B::BLUE); // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); ///////////////////////////// // 3. add main menu auto mainmenu = Menu::create(); int index = 2; int offset = 35; int divide = 20; // Track Event auto position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Track Event", position, CC_CALLBACK_1(HelloWorld::onTrackEvent, this)); // Track Revenue Event position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Track Revenue Event", position, CC_CALLBACK_1(HelloWorld::onTrackRevenueEvent, this)); // Track Callback Event position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Track Callback Event", position, CC_CALLBACK_1(HelloWorld::onTrackCallbackEvent, this)); // Track Partner Event position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Track Partner Event", position, CC_CALLBACK_1(HelloWorld::onTrackPartnerEvent, this)); // Enable offline mode position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Enable Offline Mode", position, CC_CALLBACK_1(HelloWorld::onEnableOfflineMode, this)); // Disable offline mode position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Disable Offline Mode", position, CC_CALLBACK_1(HelloWorld::onDisableOfflineMode, this)); // Enable SDK position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Enable SDK", position, CC_CALLBACK_1(HelloWorld::onEnableSdk, this)); // Disable SDK position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Disable SDK", position, CC_CALLBACK_1(HelloWorld::onDisableSdk, this)); // is Sdk Enabled position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Is SDK Enabled?", position, CC_CALLBACK_1(HelloWorld::onIsSdkEnabled, this)); // Send Push Token position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Send Push Token", position, CC_CALLBACK_1(HelloWorld::onSendPushToken, this)); // Get IDs position = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height + offset - divide * (++index)); makeButton(mainmenu, "Get IDs", position, CC_CALLBACK_1(HelloWorld::onGetIds, this)); // Add main menu to screen mainmenu->setPosition(Vec2::ZERO); this->addChild(mainmenu, 1); return true; } void HelloWorld::makeButton(Menu *menu, std::string title, Vec2 position, const ccMenuCallback &callback) { auto itemlabel = Label::create(); itemlabel->setString(title); itemlabel->setSystemFontSize(15); auto menuItem = MenuItemLabel::create(itemlabel); menuItem->setCallback(callback); menuItem->setPosition(position); menu->addChild(menuItem, 2); } void HelloWorld::onTrackEvent(cocos2d::Ref *pSender) { auto adjustEvent = AdjustEvent2dx("g3mfiw"); Adjust2dx::trackEvent(adjustEvent); } void HelloWorld::onTrackRevenueEvent(cocos2d::Ref *pSender) { auto adjustEvent = AdjustEvent2dx("a4fd35"); adjustEvent.setRevenue(10.0, "USD"); adjustEvent.setTransactionId("DUMMY_TRANSACTION_ID"); Adjust2dx::trackEvent(adjustEvent); } void HelloWorld::onTrackCallbackEvent(cocos2d::Ref *pSender) { auto adjustEvent = AdjustEvent2dx("34vgg9"); adjustEvent.addCallbackParameter("DUMMY_KEY_1", "DUMMY_VALUE_1"); adjustEvent.addCallbackParameter("DUMMY_KEY_2", "DUMMY_VALUE_2"); Adjust2dx::trackEvent(adjustEvent); } void HelloWorld::onTrackPartnerEvent(cocos2d::Ref *pSender) { auto adjustEvent = AdjustEvent2dx("w788qs"); adjustEvent.addPartnerParameter("DUMMY_KEY_1", "DUMMY_VALUE_1"); adjustEvent.addPartnerParameter("DUMMY_KEY_2", "DUMMY_VALUE_2"); Adjust2dx::trackEvent(adjustEvent); } void HelloWorld::onEnableOfflineMode(cocos2d::Ref *pSender) { Adjust2dx::setOfflineMode(true); } void HelloWorld::onDisableOfflineMode(cocos2d::Ref *pSender) { Adjust2dx::setOfflineMode(false); } void HelloWorld::onEnableSdk(cocos2d::Ref *pSender) { Adjust2dx::setEnabled(true); } void HelloWorld::onDisableSdk(cocos2d::Ref *pSender) { Adjust2dx::setEnabled(false); } void HelloWorld::onIsSdkEnabled(cocos2d::Ref *pSender) { if (Adjust2dx::isEnabled()) { CCLOG(">>> SDK is enabled"); } else { CCLOG(">>> SDK is disabled"); } } void HelloWorld::onSendPushToken(cocos2d::Ref *pSender) { Adjust2dx::setDeviceToken("bunny_foo_foo"); } void HelloWorld::onGetIds(cocos2d::Ref *pSender) { CCLOG(">>> Adid = %s", Adjust2dx::getAdid().c_str()); Adjust2dx::getGoogleAdId([](std::string adId) { CCLOG(">>> Google Ad Id = %s", adId.c_str()); }); CCLOG(">>> Amazon Ad Id = %s", Adjust2dx::getAmazonAdId().c_str()); CCLOG(">>> Get IDFA = %s", Adjust2dx::getIdfa().c_str()); auto attribution = Adjust2dx::getAttribution(); CCLOG(">>> Attribution:"); CCLOG("Tracker token = %s", attribution.getTrackerToken().c_str()); CCLOG("Tracker name = %s", attribution.getTrackerName().c_str()); CCLOG("Network = %s", attribution.getNetwork().c_str()); CCLOG("Campaign = %s", attribution.getCampaign().c_str()); CCLOG("Adgroup = %s", attribution.getAdgroup().c_str()); CCLOG("Creative = %s", attribution.getCreative().c_str()); CCLOG("Click label = %s", attribution.getClickLabel().c_str()); CCLOG("Adid = %s", attribution.getAdid().c_str()); }
[ "ugi@adjust.com" ]
ugi@adjust.com
018fa554ea0524382e817ff809fd467be1679454
939315e591a462843ea48a1690d76d6bcc95ea72
/src/fine_grained_rw_bst.h
46817adb375f070671cdeed95964c6e821bb7e2a
[]
no_license
VasuAgrawal/418FinalProject
f0014a3509407946c212780a8a57365e1691f127
99673dd1dfdc9410c8d5b7d4ac9c049f6724f2cb
refs/heads/master
2021-01-19T22:21:01.273355
2017-05-13T02:22:20
2017-05-13T02:22:20
88,797,639
1
2
null
null
null
null
UTF-8
C++
false
false
692
h
#ifndef FINE_GRAINED_RW_BST_H_ #define FINE_GRAINED_RW_BST_H_ #include "bst.h" #include <memory> #include "utils.h" class BST : public BinarySearchTree { public: bool insert(int x); bool remove(int x); bool contains(int x); BST(); ~BST(); BST(const BST&) = delete; BST& operator=(const BST&) = delete; private: struct Node { pthread_rwlock_t rwlock; int value; std::unique_ptr<Node> left; std::unique_ptr<Node> right; Node(int value); }; // Dummy node to serve as the root. This should help eliminate special // cases in a bunch of places. //Node root; std::unique_ptr<Node> root; }; #endif
[ "vasu_agrawal@yahoo.com" ]
vasu_agrawal@yahoo.com
b81d40829bfb0323fc11f8b54d86e03521be63f4
d0fb46aecc3b69983e7f6244331a81dff42d9595
/teambition-aliyun/src/model/GetProjectTaskInfoResult.cc
34a468e28411b106654de0b897449462c2b22e00
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
4,114
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/teambition-aliyun/model/GetProjectTaskInfoResult.h> #include <json/json.h> using namespace AlibabaCloud::Teambition_aliyun; using namespace AlibabaCloud::Teambition_aliyun::Model; GetProjectTaskInfoResult::GetProjectTaskInfoResult() : ServiceResult() {} GetProjectTaskInfoResult::GetProjectTaskInfoResult(const std::string &payload) : ServiceResult() { parse(payload); } GetProjectTaskInfoResult::~GetProjectTaskInfoResult() {} void GetProjectTaskInfoResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto objectNode = value["Object"]; if(!objectNode["TasklistId"].isNull()) object_.tasklistId = objectNode["TasklistId"].asString(); if(!objectNode["TaskflowstatusId"].isNull()) object_.taskflowstatusId = objectNode["TaskflowstatusId"].asString(); if(!objectNode["TaskType"].isNull()) object_.taskType = objectNode["TaskType"].asString(); if(!objectNode["IsDeleted"].isNull()) object_.isDeleted = objectNode["IsDeleted"].asString() == "true"; if(!objectNode["CreatorId"].isNull()) object_.creatorId = objectNode["CreatorId"].asString(); if(!objectNode["IsTopInProject"].isNull()) object_.isTopInProject = objectNode["IsTopInProject"].asString() == "true"; if(!objectNode["ExecutorId"].isNull()) object_.executorId = objectNode["ExecutorId"].asString(); if(!objectNode["StoryPoint"].isNull()) object_.storyPoint = objectNode["StoryPoint"].asString(); if(!objectNode["Created"].isNull()) object_.created = objectNode["Created"].asString(); if(!objectNode["OrganizationId"].isNull()) object_.organizationId = objectNode["OrganizationId"].asString(); if(!objectNode["IsDone"].isNull()) object_.isDone = objectNode["IsDone"].asString() == "true"; if(!objectNode["Id"].isNull()) object_.id = objectNode["Id"].asString(); if(!objectNode["Updated"].isNull()) object_.updated = objectNode["Updated"].asString(); if(!objectNode["SprintId"].isNull()) object_.sprintId = objectNode["SprintId"].asString(); if(!objectNode["ProjectId"].isNull()) object_.projectId = objectNode["ProjectId"].asString(); if(!objectNode["Content"].isNull()) object_.content = objectNode["Content"].asString(); if(!objectNode["Note"].isNull()) object_.note = objectNode["Note"].asString(); if(!objectNode["DueDate"].isNull()) object_.dueDate = objectNode["DueDate"].asString(); if(!objectNode["StartDate"].isNull()) object_.startDate = objectNode["StartDate"].asString(); if(!objectNode["Visible"].isNull()) object_.visible = objectNode["Visible"].asString(); if(!objectNode["Priority"].isNull()) object_.priority = objectNode["Priority"].asString(); auto allInvolveMembers = objectNode["InvolveMembers"]["InvolveMember"]; for (auto value : allInvolveMembers) object_.involveMembers.push_back(value.asString()); if(!value["Successful"].isNull()) successful_ = value["Successful"].asString() == "true"; if(!value["ErrorCode"].isNull()) errorCode_ = value["ErrorCode"].asString(); if(!value["ErrorMsg"].isNull()) errorMsg_ = value["ErrorMsg"].asString(); } std::string GetProjectTaskInfoResult::getErrorMsg()const { return errorMsg_; } GetProjectTaskInfoResult::Object GetProjectTaskInfoResult::getObject()const { return object_; } std::string GetProjectTaskInfoResult::getErrorCode()const { return errorCode_; } bool GetProjectTaskInfoResult::getSuccessful()const { return successful_; }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
5a5870d5bb0790aad3211bc30014287392e1f14f
97876f53d0f943095aad81ff1861daf98e2bd46c
/practice/AOJ/ALDS1/ALDS1_5_D.cc
b29758295cc413c81cf87b84cd81d85897e11a56
[]
no_license
aita/cpp-junks
7f7c4dad596605f25a83ee36e1898a8c839ad237
2a3efe9b63d7dcb926aa4f51a09417c2d031f42b
refs/heads/main
2023-03-09T03:33:18.901666
2021-02-21T05:50:00
2021-02-21T05:50:00
328,188,400
0
0
null
null
null
null
UTF-8
C++
false
false
1,163
cc
#include <vector> #include <iostream> using namespace std; using long64 = long long int; using int_vec = vector<long64>; long64 inversion = 0; void merge(int_vec& v, int_vec& left, int_vec& right) { auto it = v.begin(); auto l = left.begin(); auto r = right.begin(); auto n = left.size(); while (l != left.end() && r != right.end()) { if (*l <= *r) { *it++ = *l++; --n; } else { *it++ = *r++; inversion += n; } } if (l != left.end()) { copy(l, left.end(), it); } else { copy(r, right.end(), it); } return; } void merge_sort(int_vec& v) { if (v.size() < 2) { return; } auto mid = v.begin() + distance(v.begin(), v.end()) / 2; auto left = int_vec(v.begin(), mid); auto right = int_vec(mid, v.end()); merge_sort(left); merge_sort(right); merge(v, left, right); return; } int main() { int n; cin >> n; int_vec v; for (int i = 0; i < n; ++i) { int x; cin >> x; v.push_back(x); } merge_sort(v); cout << inversion << endl; return 0; }
[ "792803+aita@users.noreply.github.com" ]
792803+aita@users.noreply.github.com
dd3aec142915f1a66b4c79be0d2df1eff48fcbc9
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/third_party/blink/renderer/bindings/modules/v8/v8_webgl_shader_precision_format.h
4236e9987855a97e4005eafff22afffcbdab703f
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
3,017
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. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/interface.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_WEBGL_SHADER_PRECISION_FORMAT_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_WEBGL_SHADER_PRECISION_FORMAT_H_ #include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webgl/webgl_shader_precision_format.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { MODULES_EXPORT extern const WrapperTypeInfo v8_webgl_shader_precision_format_wrapper_type_info; class V8WebGLShaderPrecisionFormat { STATIC_ONLY(V8WebGLShaderPrecisionFormat); public: MODULES_EXPORT static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*); static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*); MODULES_EXPORT static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&); static WebGLShaderPrecisionFormat* ToImpl(v8::Local<v8::Object> object) { return ToScriptWrappable(object)->ToImpl<WebGLShaderPrecisionFormat>(); } MODULES_EXPORT static WebGLShaderPrecisionFormat* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>); MODULES_EXPORT static constexpr const WrapperTypeInfo* GetWrapperTypeInfo() { return &v8_webgl_shader_precision_format_wrapper_type_info; } static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount; // Callback functions MODULES_EXPORT static void RangeMinAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void RangeMaxAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void PrecisionAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); static void InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interface_template); }; template <> struct V8TypeOf<WebGLShaderPrecisionFormat> { typedef V8WebGLShaderPrecisionFormat Type; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_WEBGL_SHADER_PRECISION_FORMAT_H_
[ "xueqi@zjmedia.net" ]
xueqi@zjmedia.net
30cd76f92ec36bd75dd9255b6e3e0e45dad7d6b7
524dd1a8e629da15699a0b80a2d700579f141713
/20-Constructer_Overloading.cpp
98bc59bb6b64a86fe5104c51d5f5543aa5fb386a
[]
no_license
Shakti-chaudhary/Cpp-Learn-Code-with-harry-
9dc1766c699f196b655516684b7e1f12324a8f61
03d2e3144e72268862f10132807a8114441ad109
refs/heads/master
2023-06-03T09:43:22.628283
2021-06-29T04:16:51
2021-06-29T04:16:51
375,919,058
0
0
null
null
null
null
UTF-8
C++
false
false
629
cpp
#include <iostream> using namespace std; class complex { int a; int b; public: void printdata() { cout << "The no is : " << a << " and +i : " << b << endl; } complex(); /* ***************** Constructer Overloading ********************** */ complex(int x); complex(int x, int y); }; complex::complex(){ int a=0; int b=0; } complex::complex(int x){a=x;b=0;} /* Constructer with default Arguments */ complex::complex(int x,int y){a=x;b=y;} int main() { complex A; complex B(5); complex C(13, 32); A.printdata(); B.printdata(); C.printdata(); return 0; }
[ "shaktichaudhary4321@gmail.com" ]
shaktichaudhary4321@gmail.com
1bdb1c450e69ee01ca9d19295b1a1deb7d8973a4
5c6a0e9ae96f04b0f269d24bfc838d075b1190d1
/TouchDemo/object/buttons/mechButtons/SwitchButtonHandler.h
a2a2691e35665ba70fc5d204f6cd3ae8b5523662
[]
no_license
EvdochukArtem/TouchDemo
192cc0aae85c82a12930811e03bfe89564faba27
5f5fa616cf7b2b994d2e878d580c1eae14113cca
refs/heads/master
2021-05-21T06:41:02.271198
2021-03-31T12:58:47
2021-03-31T12:58:47
252,588,512
0
0
null
null
null
null
UTF-8
C++
false
false
219
h
#pragma once #include "SwitchButton.h" class CSwitchButtonHandler { public: CSwitchButtonHandler() {}; ~CSwitchButtonHandler() {}; static void CALLBACK OnSwitchButtonPress(MOUSE_EVNT bEvent, CSwitchButton* btn); };
[ "evdochukartem@gmail.com" ]
evdochukartem@gmail.com
1055e773373fb34198642a8095e6aa6b01e60eac
fed36be2b78410eb5191417b61ba8142d5576ac2
/mixtureModelCPU/readData.cpp
244cef4ca5e3f1577ca8469a35558361588d32f0
[]
no_license
cyberaide/biostatistics
68bd25a1edaf458b9795f4059c93f7fa56018f11
86b8dd1a469b222eee09a13bbdc3de4a5f795633
refs/heads/master
2016-09-15T22:13:40.528403
2013-02-08T11:27:25
2013-02-08T11:27:25
4,278,883
1
2
null
null
null
null
UTF-8
C++
false
false
3,571
cpp
/* * readData.cpp * * Created on: Nov 4, 2008 * Author: Doug Roberts * Modified by: Andrew Pangborn */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <string> #include <vector> #include <iostream> #include <fstream> using namespace std; extern "C" float* readData(char* f, int* ndims, int* nevents); float* readBIN(char* f, int* ndims, int* nevents); float* readCSV(char* f, int* ndims, int* nevents); float* readData(char* f, int* ndims, int* nevents) { int length = strlen(f); printf("File Extension: %s\n",f+length-3); if(strcmp(f+length-3,"bin") == 0) { return readBIN(f,ndims,nevents); } else { return readCSV(f,ndims,nevents); } } float* readBIN(char* f, int* ndims, int* nevents) { FILE* fin = fopen(f,"rb"); fread(nevents,4,1,fin); fread(ndims,4,1,fin); printf("Number of elements removed for memory alignment: %d\n",*nevents % (16 * 2)); *nevents -= *nevents % (16 * 2) ; // 2 gpus int num_elements = (*ndims)*(*nevents); printf("Number of rows: %d\n",*nevents); printf("Number of cols: %d\n",*ndims); float* data = (float*) malloc(sizeof(float)*num_elements); fread(data,sizeof(float),num_elements,fin); fclose(fin); return data; } float* readCSV(char* f, int* ndims, int* nevents) { string line1; ifstream file(f); vector<string> lines; int num_dims = 0; char* temp; float* data; if (file.is_open()) { while(!file.eof()) { getline(file, line1); if (!line1.empty()) { lines.push_back(line1); } } file.close(); } else { cout << "Unable to read the file " << f << endl; return NULL; } if(lines.size() > 0) { line1 = lines[0]; string line2 (line1.begin(), line1.end()); temp = strtok((char*)line1.c_str(), ","); while(temp != NULL) { num_dims++; temp = strtok(NULL, ","); } lines.erase(lines.begin()); // Remove first line, assumed to be header int num_events = (int)lines.size(); //int pad_size = 64 - (num_events % 64); //if(pad_size == 64) pad_size = 0; //pad_size = 0; //printf("Number of events in input file: %d\n",num_events); //printf("Number of padding events added for alignment: %d\n",pad_size); printf("Number of events removed to ensure memory alignment %d\n",num_events % (16 * 2)); num_events -= num_events % (16 * 2); // Allocate space for all the FCS data data = (float*)malloc(sizeof(float) * num_dims * (num_events)); if(!data){ printf("Cannot allocate enough memory for FCS data.\n"); return NULL; } for (int i = 0; i < num_events; i++) { temp = strtok((char*)lines[i].c_str(), ","); for (int j = 0; j < num_dims; j++) { if(temp == NULL) { free(data); return NULL; } data[i * num_dims + j] = atof(temp); temp = strtok(NULL, ","); } } //for(int i = num_events; i < num_events+pad_size; i++) { // for(int j = 0; j < num_dims; j++) { // data[i * num_dims + j] = 0.0f; // } //} //num_events += pad_size; *ndims = num_dims; *nevents = num_events; return data; } else { return NULL; } }
[ "apangborn@6884be23-2c2a-0410-b59a-f50d4d03ee1a" ]
apangborn@6884be23-2c2a-0410-b59a-f50d4d03ee1a
7e39bd2f099b1e8e160a6fe4e8435ffdd7a155f6
6e27c245fe0b0f2f7d6c9293b3cf182f9b0fe19c
/khf0.cpp
db002227f46349b505be4611638234bef6788749
[]
no_license
csaba215/dekla-homework
868999a4a6f1120992b149fc4ae797146d3dc4b0
e1b600dba021d8ddaae91ecfdef27fdedc390962
refs/heads/master
2023-06-06T19:54:06.659223
2021-06-30T17:39:12
2021-06-30T17:39:12
381,783,232
0
0
null
null
null
null
UTF-8
C++
false
false
1,943
cpp
#include "cekla.h"// így szabályos C++ program is int pow2(const int A, const int N, const int P) { if (N > 0) return pow2(A, N-1, P*A); else return P; } const list reverse2(const list L, const list L0) { if (L == nil) return L0; return reverse2(tl(L), cons(hd(L), L0)); } const list felbont2(const int szam,const int szamrendszer,const list lista){ if(szam == 0) return lista; int darab = szam%szamrendszer; const list l = cons(darab,lista); return felbont2((szam-darab)/szamrendszer,szamrendszer,l); } int pow(const int A, const int N){ return pow2(A, N, 1); } const list reverse(const list L) { return reverse2(L,nil); } const list felbont(const int szam,const int szamrendszer){ return felbont2(szam,szamrendszer,nil); } int vissza2(const list L,const int A, const int sum,const int n){ if(L == nil) return sum; return vissza2(tl(L),A,sum+hd(L)*pow(A,n),n+1); } int vissza(const list L,const int A){ return vissza2(L,A,0,0); } const list bont(const list l1,const list l2,const int n){ if(l1 == nil) return l2; if(n%2==0) return bont(tl(l1),cons(hd(l1),l2),n+1); return bont(tl(l1),l2,n+1); } const list osszefuz(const list paratlan_forditva,const list paros){ if(paratlan_forditva == nil) return paros; return osszefuz(tl(paratlan_forditva),cons(hd(paratlan_forditva),paros)); } int atrendezett(const int S, const int A) { const list lista = felbont(S,A); const list paros_forditva = bont(lista,nil,1); const list paratlan_forditva = bont(lista,nil,0); const list paros = reverse(paros_forditva); const list atrendezett = reverse(osszefuz(paratlan_forditva,paros)); return vissza(atrendezett,A); } int main() {// szabályos függvénydeklaráció writeln(atrendezett(123, 10)); writeln(atrendezett(101, 10)); writeln(atrendezett(5, 2)); writeln(atrendezett(1023, 10)); writeln(atrendezett(11, 3)); writeln(atrendezett(162738495, 10)); writeln(atrendezett(15263748, 10)); }
[ "csaba215@gmail.com" ]
csaba215@gmail.com
36dab40cc09adcd59be7a6774546c545d1cf5094
dd1dda0434b7a487854eddf89914f74d15324a10
/DX11Tutorial-GlassAndIce/modelclass.cpp
ec60d2618c5cd37d077d692c8c70a7de82c44cec
[]
no_license
KsGin-Fork/DX11Tutorial
02e8014d4bd84f559a5584cf98b4642e2743ee93
66bd8d13a161b909702f9ad753f15a5107400cbb
refs/heads/master
2020-03-21T06:57:46.154782
2018-04-27T15:06:47
2018-04-27T15:06:47
138,252,211
0
1
null
2018-06-22T03:52:36
2018-06-22T03:52:36
null
UTF-8
C++
false
false
7,128
cpp
//////////////////////////////////////////////////////////////////////////////// // Filename: modelclass.cpp //////////////////////////////////////////////////////////////////////////////// #include "modelclass.h" ModelClass::ModelClass() { m_vertexBuffer = 0; m_indexBuffer = 0; m_Texture = 0; m_model = 0; m_NormalTexture = 0; } ModelClass::ModelClass(const ModelClass& other) { } ModelClass::~ModelClass() { } bool ModelClass::Initialize(ID3D11Device* device, char* textureFilename, char* modelFilename , char* normalFilename) { bool result; // Load in the model data, result = LoadModel(modelFilename); if(!result) { return false; } // Initialize the vertex and index buffers. result = InitializeBuffers(device); if(!result) { return false; } // Load the texture for this model. result = LoadTexture(device, textureFilename); if(!result) { return false; } if (normalFilename) { result = LoadNormalTexture(device, normalFilename); if(!result) { return false; } } return true; } ID3D11ShaderResourceView* ModelClass::GetNormalTexture() { return m_NormalTexture->GetTexture(); } bool ModelClass::LoadNormalTexture(ID3D11Device* device, char* filename) { bool result; // Create the texture object. m_NormalTexture = new TextureClass; if(!m_NormalTexture) { return false; } // Initialize the texture object. result = m_NormalTexture->Initialize(device, filename); if(!result) { return false; } return true; } void ModelClass::ReleaseNormalTexture() { if (m_NormalTexture) { m_NormalTexture->Shutdown(); delete m_NormalTexture; m_NormalTexture = 0; } } void ModelClass::Shutdown() { // Release the model texture. ReleaseTexture(); // Shutdown the vertex and index buffers. ShutdownBuffers(); // Release the model data. ReleaseModel(); return; } void ModelClass::Render(ID3D11DeviceContext* deviceContext) { // Put the vertex and index buffers on the graphics pipeline to prepare them for drawing. RenderBuffers(deviceContext); return; } int ModelClass::GetIndexCount() { return m_indexCount; } ID3D11ShaderResourceView* ModelClass::GetTexture() { return m_Texture->GetTexture(); } bool ModelClass::InitializeBuffers(ID3D11Device* device) { VertexType* vertices; unsigned long* indices; D3D11_BUFFER_DESC vertexBufferDesc, indexBufferDesc; D3D11_SUBRESOURCE_DATA vertexData, indexData; HRESULT result; int i; // Create the vertex array. vertices = new VertexType[m_vertexCount]; if(!vertices) { return false; } // Create the index array. indices = new unsigned long[m_indexCount]; if(!indices) { return false; } // Load the vertex array and index array with data. for(i=0; i<m_vertexCount; i++) { vertices[i].position = DirectX::XMFLOAT3(m_model[i].x, m_model[i].y, m_model[i].z); vertices[i].texture = DirectX::XMFLOAT2(m_model[i].tu, m_model[i].tv); vertices[i].normal = DirectX::XMFLOAT3(m_model[i].nx, m_model[i].ny, m_model[i].nz); indices[i] = i; } // Set up the description of the static vertex buffer. vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT; vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount; vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexBufferDesc.CPUAccessFlags = 0; vertexBufferDesc.MiscFlags = 0; vertexBufferDesc.StructureByteStride = 0; // Give the subresource structure a pointer to the vertex data. vertexData.pSysMem = vertices; vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; // Now create the vertex buffer. result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer); if(FAILED(result)) { return false; } // Set up the description of the static index buffer. indexBufferDesc.Usage = D3D11_USAGE_DEFAULT; indexBufferDesc.ByteWidth = sizeof(unsigned long) * m_indexCount; indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexBufferDesc.CPUAccessFlags = 0; indexBufferDesc.MiscFlags = 0; indexBufferDesc.StructureByteStride = 0; // Give the subresource structure a pointer to the index data. indexData.pSysMem = indices; indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; // Create the index buffer. result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer); if(FAILED(result)) { return false; } // Release the arrays now that the vertex and index buffers have been created and loaded. delete [] vertices; vertices = 0; delete [] indices; indices = 0; return true; } void ModelClass::ShutdownBuffers() { // Release the index buffer. if(m_indexBuffer) { m_indexBuffer->Release(); m_indexBuffer = 0; } // Release the vertex buffer. if(m_vertexBuffer) { m_vertexBuffer->Release(); m_vertexBuffer = 0; } return; } void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext) { unsigned int stride; unsigned int offset; // Set vertex buffer stride and offset. stride = sizeof(VertexType); offset = 0; // Set the vertex buffer to active in the input assembler so it can be rendered. deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset); // Set the index buffer to active in the input assembler so it can be rendered. deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0); // Set the type of primitive that should be rendered from this vertex buffer, in this case triangles. deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); return; } bool ModelClass::LoadTexture(ID3D11Device* device, CHAR* filename) { bool result; // Create the texture object. m_Texture = new TextureClass; if(!m_Texture) { return false; } // Initialize the texture object. result = m_Texture->Initialize(device, filename); if(!result) { return false; } return true; } void ModelClass::ReleaseTexture() { // Release the texture object. if(m_Texture) { m_Texture->Shutdown(); delete m_Texture; m_Texture = 0; } return; } bool ModelClass::LoadModel(char* filename) { ifstream fin; char input; int i; // Open the model file. If it could not open the file then exit. fin.open(filename); if(fin.fail()) { return false; } // Read up to the value of vertex count. fin.get(input); while(input != ':') { fin.get(input); } // Read in the vertex count. fin >> m_vertexCount; // Set the number of indices to be the same as the vertex count. m_indexCount = m_vertexCount; // Create the model using the vertex count that was read in. m_model = new ModelType[m_vertexCount]; if(!m_model) { return false; } // Read up to the beginning of the data. fin.get(input); while(input != ':') { fin.get(input); } fin.get(input); fin.get(input); // Read in the vertex data. for(i=0; i<m_vertexCount; i++) { fin >> m_model[i].x >> m_model[i].y >> m_model[i].z; fin >> m_model[i].tu >> m_model[i].tv; fin >> m_model[i].nx >> m_model[i].ny >> m_model[i].nz; } // Close the model file. fin.close(); return true; } void ModelClass::ReleaseModel() { if(m_model) { delete [] m_model; m_model = 0; } return; }
[ "imqqyangfan@gmail.com" ]
imqqyangfan@gmail.com
9198b56631737c3fd4a4d16e88178a847dd81d4a
801d0701d19b392a4ff7c268d470959815462398
/include/hl2sdk-css/game/client/c_baseplayer.h
0e03b988805be78e74106ae3850370100e8a19d7
[]
no_license
rdbo/CS-Source-Base
c6e21cc46bca5fb57f3e7f9ee44c3522fd072885
4605df4b11a2c779d56d16dd7e817536cdc541f7
refs/heads/main
2023-03-03T13:19:04.657557
2021-02-06T13:46:53
2021-02-06T13:46:53
335,521,112
6
1
null
null
null
null
WINDOWS-1252
C++
false
false
21,246
h
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Client-side CBasePlayer. // // - Manages the player's flashlight effect. // //=============================================================================// #ifndef C_BASEPLAYER_H #define C_BASEPLAYER_H #ifdef _WIN32 #pragma once #endif #include "c_playerlocaldata.h" #include "c_basecombatcharacter.h" #include "playerstate.h" #include "usercmd.h" #include "shareddefs.h" #include "timedevent.h" #include "smartptr.h" #include "fx_water.h" #include "hintsystem.h" #include "soundemittersystem/isoundemittersystembase.h" #include "c_env_fog_controller.h" class C_BaseCombatWeapon; class C_BaseViewModel; class C_FuncLadder; class CFlashlightEffect; extern int g_nKillCamMode; extern int g_nKillCamTarget1; extern int g_nKillCamTarget2; class C_CommandContext { public: bool needsprocessing; CUserCmd cmd; int command_number; }; class C_PredictionError { public: float time; Vector error; }; #define CHASE_CAM_DISTANCE 96.0f #define WALL_OFFSET 6.0f bool IsInFreezeCam( void ); //----------------------------------------------------------------------------- // Purpose: Base Player class //----------------------------------------------------------------------------- class C_BasePlayer : public C_BaseCombatCharacter { public: DECLARE_CLASS( C_BasePlayer, C_BaseCombatCharacter ); DECLARE_CLIENTCLASS(); DECLARE_PREDICTABLE(); DECLARE_INTERPOLATION(); C_BasePlayer(); virtual ~C_BasePlayer(); virtual void Spawn( void ); virtual void SharedSpawn(); // Shared between client and server. // IClientEntity overrides. virtual void OnPreDataChanged( DataUpdateType_t updateType ); virtual void OnDataChanged( DataUpdateType_t updateType ); virtual void PreDataUpdate( DataUpdateType_t updateType ); virtual void PostDataUpdate( DataUpdateType_t updateType ); virtual void ReceiveMessage( int classID, bf_read &msg ); virtual void OnRestore(); virtual void AddEntity( void ); virtual void MakeTracer( const Vector &vecTracerSrc, const trace_t &tr, int iTracerType ); virtual void GetToolRecordingState( KeyValues *msg ); void SetAnimationExtension( const char *pExtension ); C_BaseViewModel *GetViewModel( int viewmodelindex = 0 ); C_BaseCombatWeapon *GetActiveWeapon( void ) const; const char *GetTracerType( void ); // View model prediction setup virtual void CalcView( Vector &eyeOrigin, QAngle &eyeAngles, float &zNear, float &zFar, float &fov ); virtual void CalcViewModelView( const Vector& eyeOrigin, const QAngle& eyeAngles); // Handle view smoothing when going up stairs void SmoothViewOnStairs( Vector& eyeOrigin ); virtual float CalcRoll (const QAngle& angles, const Vector& velocity, float rollangle, float rollspeed); void CalcViewRoll( QAngle& eyeAngles ); void CreateWaterEffects( void ); virtual void SetPlayerUnderwater( bool state ); void UpdateUnderwaterState( void ); bool IsPlayerUnderwater( void ) { return m_bPlayerUnderwater; } virtual Vector Weapon_ShootPosition(); virtual void Weapon_DropPrimary( void ) {} virtual Vector GetAutoaimVector( float flScale ); void SetSuitUpdate(const char *name, int fgroup, int iNoRepeat); // Input handling virtual bool CreateMove( float flInputSampleTime, CUserCmd *pCmd ); virtual void AvoidPhysicsProps( CUserCmd *pCmd ); virtual void PlayerUse( void ); CBaseEntity *FindUseEntity( void ); virtual bool IsUseableEntity( CBaseEntity *pEntity, unsigned int requiredCaps ); // Data handlers virtual bool IsPlayer( void ) const { return true; } virtual int GetHealth() const { return m_iHealth; } int GetBonusProgress() const { return m_iBonusProgress; } int GetBonusChallenge() const { return m_iBonusChallenge; } // observer mode virtual int GetObserverMode() const; virtual CBaseEntity *GetObserverTarget() const; void SetObserverTarget( EHANDLE hObserverTarget ); bool AudioStateIsUnderwater( Vector vecMainViewOrigin ); bool IsObserver() const; bool IsHLTV() const; void ResetObserverMode(); bool IsBot( void ) const { return false; } // Eye position.. virtual Vector EyePosition(); virtual const QAngle &EyeAngles(); // Direction of eyes void EyePositionAndVectors( Vector *pPosition, Vector *pForward, Vector *pRight, Vector *pUp ); virtual const QAngle &LocalEyeAngles(); // Direction of eyes // This can be overridden to return something other than m_pRagdoll if the mod uses separate // entities for ragdolls. virtual IRagdoll* GetRepresentativeRagdoll() const; // override the initial bone position for ragdolls virtual void GetRagdollInitBoneArrays( matrix3x4_t *pDeltaBones0, matrix3x4_t *pDeltaBones1, matrix3x4_t *pCurrentBones, float boneDt ); // Returns eye vectors void EyeVectors( Vector *pForward, Vector *pRight = NULL, Vector *pUp = NULL ); void CacheVehicleView( void ); // Calculate and cache the position of the player in the vehicle bool IsSuitEquipped( void ) { return m_Local.m_bWearingSuit; }; // Team handlers virtual void TeamChange( int iNewTeam ); // Flashlight void Flashlight( void ); void UpdateFlashlight( void ); // Weapon selection code virtual bool IsAllowedToSwitchWeapons( void ) { return !IsObserver(); } virtual C_BaseCombatWeapon *GetActiveWeaponForSelection( void ); // Returns the view model if this is the local player. If you're in third person or // this is a remote player, it returns the active weapon // (and its appropriate left/right weapon if this is TF2). virtual C_BaseAnimating* GetRenderedWeaponModel(); virtual bool IsOverridingViewmodel( void ) { return false; }; virtual int DrawOverriddenViewmodel( C_BaseViewModel *pViewmodel, int flags ) { return 0; }; virtual float GetDefaultAnimSpeed( void ) { return 1.0; } void SetMaxSpeed( float flMaxSpeed ) { m_flMaxspeed = flMaxSpeed; } float MaxSpeed() const { return m_flMaxspeed; } // Should this object cast shadows? virtual ShadowType_t ShadowCastType() { return SHADOWS_NONE; } virtual bool ShouldReceiveProjectedTextures( int flags ) { return false; } bool IsLocalPlayer( void ) const; // Global/static methods virtual void ThirdPersonSwitch( bool bThirdperson ); static bool ShouldDrawLocalPlayer(); static C_BasePlayer *GetLocalPlayer( void ); int GetUserID( void ); virtual bool CanSetSoundMixer( void ); // Called by the view model if its rendering is being overridden. virtual bool ViewModel_IsTransparent( void ); #if !defined( NO_ENTITY_PREDICTION ) void AddToPlayerSimulationList( C_BaseEntity *other ); void SimulatePlayerSimulatedEntities( void ); void RemoveFromPlayerSimulationList( C_BaseEntity *ent ); void ClearPlayerSimulationList( void ); #endif virtual void PhysicsSimulate( void ); virtual unsigned int PhysicsSolidMaskForEntity( void ) const { return MASK_PLAYERSOLID; } // Prediction stuff virtual bool ShouldPredict( void ); virtual void PreThink( void ); virtual void PostThink( void ); virtual void ItemPreFrame( void ); virtual void ItemPostFrame( void ); virtual void AbortReload( void ); virtual void SelectLastItem(void); virtual void Weapon_SetLast( C_BaseCombatWeapon *pWeapon ); virtual bool Weapon_ShouldSetLast( C_BaseCombatWeapon *pOldWeapon, C_BaseCombatWeapon *pNewWeapon ) { return true; } virtual bool Weapon_ShouldSelectItem( C_BaseCombatWeapon *pWeapon ); virtual bool Weapon_Switch( C_BaseCombatWeapon *pWeapon, int viewmodelindex = 0 ); // Switch to given weapon if has ammo (false if failed) virtual C_BaseCombatWeapon *GetLastWeapon( void ) { return m_hLastWeapon.Get(); } void ResetAutoaim( void ); virtual void SelectItem( const char *pstr, int iSubType = 0 ); virtual void UpdateClientData( void ); virtual float GetFOV( void ); int GetDefaultFOV( void ) const; virtual bool IsZoomed( void ) { return false; } bool SetFOV( CBaseEntity *pRequester, int FOV, float zoomRate, int iZoomStart = 0 ); void ClearZoomOwner( void ); float GetFOVDistanceAdjustFactor(); virtual void ViewPunch( const QAngle &angleOffset ); void ViewPunchReset( float tolerance = 0 ); void UpdateButtonState( int nUserCmdButtonMask ); int GetImpulse( void ) const; virtual void Simulate(); virtual bool ShouldInterpolate(); virtual bool ShouldDraw(); virtual int DrawModel( int flags ); // Called when not in tactical mode. Allows view to be overriden for things like driving a tank. virtual void OverrideView( CViewSetup *pSetup ); // returns the player name const char * GetPlayerName(); virtual const Vector GetPlayerMins( void ) const; // uses local player virtual const Vector GetPlayerMaxs( void ) const; // uses local player // Is the player dead? bool IsPlayerDead(); bool IsPoisoned( void ) { return m_Local.m_bPoisoned; } C_BaseEntity *GetUseEntity(); // Vehicles... IClientVehicle *GetVehicle(); bool IsInAVehicle() const { return ( NULL != m_hVehicle.Get() ) ? true : false; } virtual void SetVehicleRole( int nRole ); void LeaveVehicle( void ); bool UsingStandardWeaponsInVehicle( void ); virtual void SetAnimation( PLAYER_ANIM playerAnim ); float GetTimeBase( void ) const; float GetFinalPredictedTime() const; bool IsInVGuiInputMode() const; bool IsInViewModelVGuiInputMode() const; C_CommandContext *GetCommandContext(); // Get the command number associated with the current usercmd we're running (if in predicted code). int CurrentCommandNumber() const; const CUserCmd *GetCurrentUserCommand() const; const QAngle& GetPunchAngle(); void SetPunchAngle( const QAngle &angle ); float GetWaterJumpTime() const; void SetWaterJumpTime( float flWaterJumpTime ); float GetSwimSoundTime( void ) const; void SetSwimSoundTime( float flSwimSoundTime ); float GetDeathTime( void ) { return m_flDeathTime; } void SetPreviouslyPredictedOrigin( const Vector &vecAbsOrigin ); const Vector &GetPreviouslyPredictedOrigin() const; // CS wants to allow small FOVs for zoomed-in AWPs. virtual float GetMinFOV() const; virtual void DoMuzzleFlash(); virtual void PlayPlayerJingle(); virtual void UpdateStepSound( surfacedata_t *psurface, const Vector &vecOrigin, const Vector &vecVelocity ); virtual void PlayStepSound( Vector &vecOrigin, surfacedata_t *psurface, float fvol, bool force ); virtual surfacedata_t * GetFootstepSurface( const Vector &origin, const char *surfaceName ); virtual void GetStepSoundVelocities( float *velwalk, float *velrun ); virtual void SetStepSoundTime( stepsoundtimes_t iStepSoundTime, bool bWalking ); // Called by prediction when it detects a prediction correction. // vDelta is the line from where the client had predicted the player to at the usercmd in question, // to where the server says the client should be at said usercmd. void NotePredictionError( const Vector &vDelta ); // Called by the renderer to apply the prediction error smoothing. void GetPredictionErrorSmoothingVector( Vector &vOffset ); virtual void ExitLadder() {} surfacedata_t *GetLadderSurface( const Vector &origin ); surfacedata_t *GetSurfaceData( void ) { return m_pSurfaceData; } void SetLadderNormal( Vector vecLadderNormal ) { m_vecLadderNormal = vecLadderNormal; } // Hints virtual CHintSystem *Hints( void ) { return NULL; } bool ShouldShowHints( void ) { return Hints() ? Hints()->ShouldShowHints() : false; } bool HintMessage( int hint, bool bForce = false, bool bOnlyIfClear = false ) { return Hints() ? Hints()->HintMessage( hint, bForce, bOnlyIfClear ) : false; } void HintMessage( const char *pMessage ) { if (Hints()) Hints()->HintMessage( pMessage ); } virtual IMaterial *GetHeadLabelMaterial( void ); // Fog fogparams_t *GetFogParams( void ) { return &m_CurrentFog; } void FogControllerChanged( bool bSnap ); void UpdateFogController( void ); void UpdateFogBlend( void ); void IncrementEFNoInterpParity(); int GetEFNoInterpParity() const; float GetFOVTime( void ){ return m_flFOVTime; } virtual void OnAchievementAchieved( int iAchievement ) {} protected: fogparams_t m_CurrentFog; EHANDLE m_hOldFogController; public: int m_StuckLast; // Data for only the local player CNetworkVarEmbedded( CPlayerLocalData, m_Local ); // Data common to all other players, too CPlayerState pl; // Player FOV values int m_iFOV; // field of view int m_iFOVStart; // starting value of the FOV changing over time (client only) float m_flFOVTime; // starting time of the FOV zoom int m_iDefaultFOV; // default FOV if no other zooms are occurring EHANDLE m_hZoomOwner; // This is a pointer to the entity currently controlling the player's zoom // Only this entity can change the zoom state once it has ownership // For weapon prediction bool m_fOnTarget; //Is the crosshair on a target? char m_szAnimExtension[32]; int m_afButtonLast; int m_afButtonPressed; int m_afButtonReleased; int m_nButtons; CUserCmd *m_pCurrentCommand; // Movement constraints EHANDLE m_hConstraintEntity; Vector m_vecConstraintCenter; float m_flConstraintRadius; float m_flConstraintWidth; float m_flConstraintSpeedFactor; protected: void CalcPlayerView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov ); void CalcVehicleView(IClientVehicle *pVehicle, Vector& eyeOrigin, QAngle& eyeAngles, float& zNear, float& zFar, float& fov ); virtual void CalcObserverView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov ); virtual Vector GetChaseCamViewOffset( CBaseEntity *target ); void CalcChaseCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov ); void CalcInEyeCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov ); virtual void CalcDeathCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov ); void CalcRoamingView(Vector& eyeOrigin, QAngle& eyeAngles, float& fov); virtual void CalcFreezeCamView( Vector& eyeOrigin, QAngle& eyeAngles, float& fov ); // Check to see if we're in vgui input mode... void DetermineVguiInputMode( CUserCmd *pCmd ); // Used by prediction, sets the view angles for the player virtual void SetLocalViewAngles( const QAngle &viewAngles ); virtual void SetViewAngles( const QAngle& ang ); // used by client side player footsteps surfacedata_t* GetGroundSurface(); protected: // Did we just enter a vehicle this frame? bool JustEnteredVehicle(); // DATA int m_iObserverMode; // if in spectator mode != 0 EHANDLE m_hObserverTarget; // current observer target float m_flObserverChaseDistance; // last distance to observer traget Vector m_vecFreezeFrameStart; float m_flFreezeFrameStartTime; // Time at which we entered freeze frame observer mode float m_flFreezeFrameDistance; bool m_bWasFreezeFraming; float m_flDeathTime; // last time player died float m_flStepSoundTime; private: // Make sure no one calls this... C_BasePlayer& operator=( const C_BasePlayer& src ); C_BasePlayer( const C_BasePlayer & ); // not defined, not accessible // Vehicle stuff. EHANDLE m_hVehicle; EHANDLE m_hOldVehicle; EHANDLE m_hUseEntity; float m_flMaxspeed; int m_iBonusProgress; int m_iBonusChallenge; CInterpolatedVar< Vector > m_iv_vecViewOffset; // Not replicated Vector m_vecWaterJumpVel; float m_flWaterJumpTime; // used to be called teleport_time int m_nImpulse; float m_flSwimSoundTime; Vector m_vecLadderNormal; QAngle m_vecOldViewAngles; bool m_bWasFrozen; int m_flPhysics; int m_nTickBase; int m_nFinalPredictedTick; EHANDLE m_pCurrentVguiScreen; // Player flashlight dynamic light pointers CFlashlightEffect *m_pFlashlight; typedef CHandle<C_BaseCombatWeapon> CBaseCombatWeaponHandle; CNetworkVar( CBaseCombatWeaponHandle, m_hLastWeapon ); #if !defined( NO_ENTITY_PREDICTION ) CUtlVector< CHandle< C_BaseEntity > > m_SimulatedByThisPlayer; #endif // players own view models, left & right hand CHandle< C_BaseViewModel > m_hViewModel[ MAX_VIEWMODELS ]; float m_flOldPlayerZ; float m_flOldPlayerViewOffsetZ; Vector m_vecVehicleViewOrigin; // Used to store the calculated view of the player while riding in a vehicle QAngle m_vecVehicleViewAngles; // Vehicle angles float m_flVehicleViewFOV; int m_nVehicleViewSavedFrame; // Used to mark which frame was the last one the view was calculated for // For UI purposes... int m_iOldAmmo[ MAX_AMMO_TYPES ]; C_CommandContext m_CommandContext; // For underwater effects float m_flWaterSurfaceZ; bool m_bResampleWaterSurface; TimedEvent m_tWaterParticleTimer; CSmartPtr<WaterDebrisEffect> m_pWaterEmitter; bool m_bPlayerUnderwater; friend class CPrediction; // HACK FOR TF2 Prediction friend class CTFGameMovementRecon; friend class CGameMovement; friend class CTFGameMovement; friend class CHL1GameMovement; friend class CCSGameMovement; friend class CHL2GameMovement; friend class CDODGameMovement; friend class CPortalGameMovement; // Accessors for gamemovement float GetStepSize( void ) const { return m_Local.m_flStepSize; } float m_flNextAvoidanceTime; float m_flAvoidanceRight; float m_flAvoidanceForward; float m_flAvoidanceDotForward; float m_flAvoidanceDotRight; protected: virtual bool IsDucked( void ) const { return m_Local.m_bDucked; } virtual bool IsDucking( void ) const { return m_Local.m_bDucking; } virtual float GetFallVelocity( void ) { return m_Local.m_flFallVelocity; } void ForceSetupBonesAtTimeFakeInterpolation( matrix3x4_t *pBonesOut, float curtimeOffset ); float m_flLaggedMovementValue; // These are used to smooth out prediction corrections. They're most useful when colliding with // vphysics objects. The server will be sending constant prediction corrections, and these can help // the errors not be so jerky. Vector m_vecPredictionError; float m_flPredictionErrorTime; Vector m_vecPreviouslyPredictedOrigin; // Used to determine if non-gamemovement game code has teleported, or tweaked the player's origin char m_szLastPlaceName[MAX_PLACE_NAME_LENGTH]; // received from the server // Texture names and surface data, used by CGameMovement int m_surfaceProps; surfacedata_t* m_pSurfaceData; float m_surfaceFriction; char m_chTextureType; bool m_bSentFreezeFrame; float m_flFreezeZOffset; byte m_ubEFNoInterpParity; byte m_ubOldEFNoInterpParity; private: struct StepSoundCache_t { StepSoundCache_t() : m_usSoundNameIndex( 0 ) {} CSoundParameters m_SoundParameters; unsigned short m_usSoundNameIndex; }; // One for left and one for right side of step StepSoundCache_t m_StepSoundCache[ 2 ]; public: const char *GetLastKnownPlaceName( void ) const { return m_szLastPlaceName; } // return the last nav place name the player occupied float GetLaggedMovementValue( void ){ return m_flLaggedMovementValue; } bool ShouldGoSouth( Vector vNPCForward, Vector vNPCRight ); //Such a bad name. void SetOldPlayerZ( float flOld ) { m_flOldPlayerZ = flOld; } }; EXTERN_RECV_TABLE(DT_BasePlayer); //----------------------------------------------------------------------------- // Inline methods //----------------------------------------------------------------------------- inline C_BasePlayer *ToBasePlayer( C_BaseEntity *pEntity ) { if ( !pEntity || !pEntity->IsPlayer() ) return NULL; #if _DEBUG Assert( dynamic_cast<C_BasePlayer *>( pEntity ) != NULL ); #endif return static_cast<C_BasePlayer *>( pEntity ); } inline C_BaseEntity *C_BasePlayer::GetUseEntity() { return m_hUseEntity; } inline IClientVehicle *C_BasePlayer::GetVehicle() { C_BaseEntity *pVehicleEnt = m_hVehicle.Get(); return pVehicleEnt ? pVehicleEnt->GetClientVehicle() : NULL; } inline bool C_BasePlayer::IsObserver() const { return (GetObserverMode() != OBS_MODE_NONE); } inline int C_BasePlayer::GetImpulse( void ) const { return m_nImpulse; } inline C_CommandContext* C_BasePlayer::GetCommandContext() { return &m_CommandContext; } inline int CBasePlayer::CurrentCommandNumber() const { Assert( m_pCurrentCommand ); return m_pCurrentCommand->command_number; } inline const CUserCmd *CBasePlayer::GetCurrentUserCommand() const { Assert( m_pCurrentCommand ); return m_pCurrentCommand; } #endif // C_BASEPLAYER_H
[ "rdbodev@gmail.com" ]
rdbodev@gmail.com
a41c7441ce384d9cf940d130dcef460ac7f18ba0
05fcca80c3fa1f4d78bf8f4aed7e8100cacb15a0
/Young Tableau/young.cpp
c0aa885ab66bce509f7a4cc00b2a0bd757f1d2d1
[]
no_license
diogommartins/Young-Tableau
46be239e22f6b0deff70d12f6834d3174dc5c959
6ee2d65e2014792815752636c43f0c281f13b862
refs/heads/master
2016-09-06T07:37:30.364190
2015-06-15T04:59:49
2015-06-15T04:59:49
35,956,049
0
0
null
null
null
null
UTF-8
C++
false
false
4,153
cpp
// // young.cpp // Young Tableau // // Created by Diogo Martins on 5/20/15. // Copyright (c) 2015 Diogo Martins. All rights reserved. // #include "young.h" #define INFINITO INT_MAX /** 1. O construtor cria um quadro vazio. Para tal, aloca espaço para a matriz de inteiros Y, m × n e inicializa os valores com a constante simbólica INT_MAX para representar ∞. */ young::young(int linhas, int colunas){ m = linhas; n = colunas; Y = new int*[m]; for (int i=0; i<m; i++) Y[i] = new int[n]; for (int i=0; i<m; i++) for(int j=0; j<n; j++) Y[i][j] = INFINITO; } /** 2. O destrutor libera a memória alocada para a matriz Y . */ young::~young(){ delete Y; } /** 3. Função bool vazio() retorna true se o quadro está vazio e false, caso contrário. */ bool young::vazio(){ for (int i=0; i<=m; i++) for(int j=0; i<=n; i++) if (Y[i][j] != INFINITO) return false; // Se achou pelo menos uma posição preenchida return true; // Não achou nenhuma posição preenchida } /** 4. Função bool cheio() retorna true se o quadro está cheio e false, caso contrário. */ bool young::cheio(){ for (int i=0; i<=m; i++) for(int j=0; j<=n; j++) if (Y[i][j] == INFINITO) return false; // Se achou pelo menos uma posição vazia return true; // Não achou nenhuma posição vazia } bool tem_esquerda(int &coluna) { return (coluna - 1 >= 0); } bool tem_topo(int &linha) { return (linha - 1 >= 0); } void young::youngify(int i, int j){ if (tem_topo(i) && (Y[i-1][j] > Y[i][j])) { int atual = Y[i][j]; Y[i][j] = Y[i-1][j]; Y[i-1][j] = atual; youngify(i-1, j); } if(tem_esquerda(j) && (Y[i][j-1] > Y[i][j])) { int atual = Y[i][j]; Y[i][j] = Y[i][j-1]; Y[i][j-1] = atual; youngify(i, j-1); } } void troca(int &a, int &b) { int temp = a; a = b; b = temp; } void youngfy_remove(int **Y, int i, int j, int &m, int &n) { int menor_i = i; int menor_j = j; if (i+1 <= m && (Y[i][j] > Y[i+1][j])) { menor_i = i+1; menor_j = j; } if (j+1 <= n && (Y[menor_i][menor_j] > Y[i][j+1])) { menor_i = i; menor_j = j+1; } if ((menor_i != i) || (menor_j != j)) { troca(Y[i][j], Y[menor_i][menor_j]); youngfy_remove(Y, menor_i, menor_j, m, n); } } /** 5. Função bool remove(int & elem) para extrair o menor elemento do quadro. Uma vez que o menor elemento está sempre na posição Y [1, 1] (no caso da linguagem C, Y [0, 0] ) a função pode retornar o elemento armazenado em Y [1, 1] e fazer Y [1, 1] = ∞ para indicar que o elemento não existe mais. Entretanto, tal fato pode deixar o quadro inconsistente. Isso acontece quando Y [1, 1] = ∞ e o quadro não está vazio. */ bool young::remove(int &elem){ if (!vazio()){ elem = Y[0][0]; Y[0][0] = INFINITO; youngfy_remove(Y, 0, 0, m, n); return true; } return false; } /** 6. Função bool insere(int valor), para inserir um elemento no quadro. Se o quadro não estiver cheio, então Y [m, n] = ∞ (no caso da linguagem C, Y [m − 1, n − 1] ) e é possível colocar o novo elemento nesta posição. Entretanto, o quadro pode ficar inconsistente. Pode-se resolver este problema recursivamente retraindo o elemento novo e trocando-o com o elemento da esquerda ou do topo até conseguir um quadro de Young. A função retorna true se o elemento foi inserido com sucesso e false, caso contrário. */ bool young::insere(int valor){ if (!cheio()){ Y[m-1][n-1] = valor; youngify(m-1, n-1); return true; } return false; } string human_representation(int &valor){ if (valor != INFINITO) return to_string(valor); return "∞"; } void young::imprime(){ for (int i=0; i<m; i++){ for(int j=0; j<n; j++) cout << human_representation(Y[i][j]) << "\t"; cout << "\n"; } cout << "\n"; }
[ "diogo.martins@unirio.br" ]
diogo.martins@unirio.br
3bfb432a52e3e206b9366d9aaeea0a05162bd888
4e57cfc1809d50e979a6e46302065b4a99a26747
/RenderEngine/FPCExtension.h
11e170152bbc036eeb846e2368234f65554b40db
[]
no_license
GScience-Studio/MagicCube
ca2966d63d203d62df00ba40ff3e7c147758a98f
9d51f8f87bcc461fa2a57ea5ac4606347d48711f
refs/heads/master
2020-09-24T00:23:30.611638
2017-04-19T09:58:16
2017-04-19T09:58:16
67,795,557
9
4
null
null
null
null
GB18030
C++
false
false
234
h
#pragma once #include "ExtensionManager.h" #include "FPCManager.h" #include "Application.h" //第一人称控制器扩展 class fpc_extension :public extension { public: fpc_extension() :extension(std::string("FPCExtension")) {} };
[ "GM2000@outlook.com" ]
GM2000@outlook.com
cb84acc9090f131e319281811b8001b4d31ae013
1cb1b83de025d1ad1e756e0b8028d5164965925d
/ABC/A-MaximizeTheFormula.cpp
27c995902dc1244e73e7de7e26dff11245ea1256
[]
no_license
FukeKazki/CompetitionProgramming
7c39aceec00a9ce393a7054a921b4f08a35aba0e
4fff369180b35d230f19d8935344468a7da4bff4
refs/heads/master
2022-10-09T15:34:02.391840
2022-10-02T07:52:44
2022-10-02T07:52:44
181,264,546
0
0
null
null
null
null
UTF-8
C++
false
false
221
cpp
#include <iostream> using namespace std; int main() { int A, B, C; cin >> A >> B >> C; if(A < B) swap(A, B); if(B < C) swap(B, C); if(A < B) swap(A, B); cout << A*10+B+C << endl; return 0; }
[ "kazkichi0906@gmail.com" ]
kazkichi0906@gmail.com
eb7b65657cf2c71cfca6d79f1a7ac8fb7ab332e9
8adec48dfaee1cdfd6c7f4d2fb3038aa1c17bda6
/WProf/src/chrome/browser/protector/protector_service.cc
aa16f7f9329aa4111b249638fab579629f07932e
[ "BSD-3-Clause" ]
permissive
kusoof/wprof
ef507cfa92b3fd0f664d0eefef7fc7d6cd69481e
8511e9d4339d3d6fad5e14ad7fff73dfbd96beb8
refs/heads/master
2021-01-11T00:52:51.152225
2016-12-10T23:51:14
2016-12-10T23:51:14
70,486,057
0
1
null
null
null
null
UTF-8
C++
false
false
7,657
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/browser/protector/protector_service.h" #include "base/logging.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/protector/composite_settings_change.h" #include "chrome/browser/protector/keys.h" #include "chrome/browser/protector/protected_prefs_watcher.h" #include "chrome/browser/protector/protector_utils.h" #include "chrome/browser/protector/settings_change_global_error.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/singleton_tabs.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "content/public/browser/notification_source.h" #include "net/base/registry_controlled_domain.h" namespace protector { namespace { // Returns true if changes with URLs |url1| and |url2| can be merged. bool CanMerge(const GURL& url1, const GURL& url2) { VLOG(1) << "Checking if can merge " << url1.spec() << " with " << url2.spec(); // All Google URLs are considered the same one. if (google_util::IsGoogleHostname(url1.host(), google_util::DISALLOW_SUBDOMAIN)) { return google_util::IsGoogleHostname(url2.host(), google_util::DISALLOW_SUBDOMAIN); } // Otherwise URLs must have the same domain. return net::RegistryControlledDomainService::SameDomainOrHost(url1, url2); } } // namespace ProtectorService::ProtectorService(Profile* profile) : profile_(profile), has_active_change_(false) { // Start observing pref changes. prefs_watcher_.reset(new ProtectedPrefsWatcher(profile)); } ProtectorService::~ProtectorService() { DCHECK(!IsShowingChange()); // Should have been dismissed by Shutdown. } void ProtectorService::ShowChange(BaseSettingChange* change) { DCHECK(change); // Change instance will either be owned by |this| or deleted after this call. scoped_ptr<BaseSettingChange> change_ptr(change); DVLOG(1) << "Init change"; if (!protector::IsEnabled()) { change_ptr->InitWhenDisabled(profile_); return; } else if (!change_ptr->Init(profile_)) { LOG(WARNING) << "Error while initializing, dismissing change"; return; } Item* item_to_merge_with = FindItemToMergeWith(change_ptr.get()); if (item_to_merge_with) { // CompositeSettingsChange takes ownership of merged changes. BaseSettingChange* existing_change = item_to_merge_with->change.release(); CompositeSettingsChange* merged_change = existing_change->MergeWith(change_ptr.release()); item_to_merge_with->change.reset(merged_change); item_to_merge_with->was_merged = true; if (item_to_merge_with->error->GetBubbleView()) item_to_merge_with->show_when_merged = true; // Remove old GlobalError instance. Later in OnRemovedFromProfile() a new // GlobalError instance will be created for the composite change. item_to_merge_with->error->RemoveFromProfile(); } else if (change->IsUserVisible()) { Item new_item; SettingsChangeGlobalError* error = new SettingsChangeGlobalError(change_ptr.get(), this); new_item.error.reset(error); new_item.change.reset(change_ptr.release()); items_.push_back(new_item); // Do not show the bubble immediately if another one is active. error->AddToProfile(profile_, !has_active_change_); has_active_change_ = true; } else { VLOG(1) << "Not showing a change because it's not user-visible."; } } bool ProtectorService::IsShowingChange() const { return !items_.empty(); } void ProtectorService::ApplyChange(BaseSettingChange* change, Browser* browser) { change->Apply(browser); DismissChange(change); } void ProtectorService::DiscardChange(BaseSettingChange* change, Browser* browser) { change->Discard(browser); DismissChange(change); } void ProtectorService::DismissChange(BaseSettingChange* change) { Items::iterator item = std::find_if(items_.begin(), items_.end(), MatchItemByChange(change)); DCHECK(item != items_.end()); item->error->RemoveFromProfile(); } void ProtectorService::OpenTab(const GURL& url, Browser* browser) { DCHECK(browser); chrome::ShowSingletonTab(browser, url); } ProtectedPrefsWatcher* ProtectorService::GetPrefsWatcher() { return prefs_watcher_.get(); } void ProtectorService::StopWatchingPrefsForTesting() { prefs_watcher_.reset(); } ProtectorService::Item* ProtectorService::FindItemToMergeWith( const BaseSettingChange* change) { if (!change->CanBeMerged()) return NULL; GURL url = change->GetNewSettingURL(); for (Items::iterator item = items_.begin(); item != items_.end(); item++) { if (item->change->CanBeMerged() && CanMerge(url, item->change->GetNewSettingURL())) return &*item; } return NULL; } void ProtectorService::Shutdown() { while (IsShowingChange()) items_[0].error->RemoveFromProfile(); } void ProtectorService::OnApplyChange(SettingsChangeGlobalError* error, Browser* browser) { DVLOG(1) << "Apply change"; error->change()->Apply(browser); has_active_change_ = false; } void ProtectorService::OnDiscardChange(SettingsChangeGlobalError* error, Browser* browser) { DVLOG(1) << "Discard change"; error->change()->Discard(browser); has_active_change_ = false; } void ProtectorService::OnDecisionTimeout(SettingsChangeGlobalError* error) { DVLOG(1) << "Timeout"; error->change()->Timeout(); } void ProtectorService::OnRemovedFromProfile(SettingsChangeGlobalError* error) { Items::iterator item = std::find_if(items_.begin(), items_.end(), MatchItemByError(error)); DCHECK(item != items_.end()); if (item->was_merged) { bool show_new_error = !has_active_change_ || item->show_when_merged; item->was_merged = false; item->show_when_merged = false; // Item was merged with another change instance and error has been removed, // create a new one for the composite change. item->error.reset(new SettingsChangeGlobalError(item->change.get(), this)); item->error->AddToProfile(profile_, show_new_error); has_active_change_ = true; return; } items_.erase(item); // If no other change is shown and there are changes that haven't been shown // yet, show the first one. if (!has_active_change_) { for (item = items_.begin(); item != items_.end(); ++item) { if (!item->error->HasShownBubbleView()) { item->error->ShowBubble(); has_active_change_ = true; return; } } } } BaseSettingChange* ProtectorService::GetLastChange() { return items_.empty() ? NULL : items_.back().change.get(); } ProtectorService::Item::Item() : was_merged(false), show_when_merged(false) { } ProtectorService::Item::~Item() { } ProtectorService::MatchItemByChange::MatchItemByChange( const BaseSettingChange* other) : other_(other) { } bool ProtectorService::MatchItemByChange::operator()( const ProtectorService::Item& item) { return item.change->Contains(other_); } ProtectorService::MatchItemByError::MatchItemByError( const SettingsChangeGlobalError* other) : other_(other) { } bool ProtectorService::MatchItemByError::operator()( const ProtectorService::Item& item) { return other_ == item.error.get(); } } // namespace protector
[ "kusoof@kookaburra.(none)" ]
kusoof@kookaburra.(none)
2538a3a9b373b02173300a8cfb1b88e1081ffbb9
9b920b5572dd7196de8adea6ed9b4e3859bd90d7
/code/Classes/Bullet.cpp
e2acc6951ce4f16dea4d2f3b88be395454eeb48e
[]
no_license
SYSUcarey/Survivor_Island
712ac4d2758d383d20013dffe60834e06e43d50a
be062a0d445165b3341f2b5f2de4420258ecf7fc
refs/heads/master
2020-03-24T14:11:02.152507
2018-07-29T13:04:35
2018-07-29T13:04:35
142,761,481
0
1
null
null
null
null
GB18030
C++
false
false
5,994
cpp
#include"Bullet.h" #include"GlobalVar.h" USING_NS_CC; bulletFactory* bulletFactory::bulletfactory = NULL; bulletFactory::bulletFactory() { initSpriteFrame(); } bulletFactory* bulletFactory::getInstance() { if (bulletfactory == NULL) { bulletfactory = new bulletFactory(); } return bulletfactory; } // 产生子弹,进入Vector中,返回子弹Sprite* Sprite* bulletFactory::createBullet(int type, bool isPlayer1) { // 根据不同类型的子弹,创建到场景子弹队列中,同时剩余弹药数要减一 // 如果子弹不足,返回NULL if (isPlayer1 && bulletNumForPlayer1[type] <= 0) return NULL; if (!isPlayer1 && bulletNumForPlayer2[type] <= 0) return NULL; // 判断是否执行完射击动作(除了UZI都不能连发) bool isShotDone = (isPlayer1) ? GlobalVar::getInstance()->player1_isShotDone : GlobalVar::getInstance()->player2_isShotDone; if (type != 1 && !isShotDone) return NULL; std::string pic = "bullet" + Value(type+1).asString() + ".png"; Sprite* b = Sprite::create(pic.c_str()); setScale_and_setRotation(b, type, isPlayer1); if (isPlayer1) { bulletForPlayer1[type].pushBack(b); bulletNumForPlayer1[type]--; } else { bulletForPlayer2[type].pushBack(b); bulletNumForPlayer2[type]--; } return b; } //移除子弹 void bulletFactory::removeBullet(Sprite* sp, int type, bool isPlayer1) { /* Animation* anim = Animation::createWithSpriteFrames(monsterDead, 0.2); Animate* ani = Animate::create(anim); Sequence* seq = Sequence::create(ani, CallFunc::create(CC_CALLBACK_0(Sprite::removeFromParent, sp)), NULL); sp->runAction(seq); monster.eraseObject(sp); */ if (isPlayer1) { bulletForPlayer1[type].eraseObject(sp); } else { bulletForPlayer2[type].eraseObject(sp); } sp->removeFromParent(); } void bulletFactory::moveMonster(Vec2 playerPos, float time) { /* for (auto i : monster) { Vec2 Pos = i->getPosition(); Vec2 dir = playerPos - Pos; dir.normalize(); i->runAction(MoveBy::create(time, dir * 30)); } */ } //判断碰撞 Sprite* bulletFactory::collider(Rect rect) { /* for (auto i : monster) { if (rect.containsPoint(i->getPosition())) { return i; } } return NULL; */ return NULL; } void bulletFactory::initSpriteFrame() { /* auto texture = Director::getInstance()->getTextureCache()->addImage("Monster.png"); monsterDead.reserve(4); for (int i = 0; i < 4; i++) { auto frame = SpriteFrame::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(258 - 48 * i, 0, 42, 42))); monsterDead.pushBack(frame); } */ //auto bullet1_texture = Director::getInstance()->getTextureCache()->addImage("bullet1"); } // 获得现有子弹数量 int bulletFactory::getBulletNum(int type, bool isPlayer1) { if (isPlayer1) return bulletNumForPlayer1[type]; return bulletNumForPlayer2[type]; } // 获得场景中子弹的队列 Vector<Sprite*> bulletFactory::getBulletNumInScene(int type, bool isPlayer1) { if (isPlayer1) return bulletForPlayer1[type]; return bulletForPlayer2[type]; } // 根据子弹类型、玩家朝向调节子弹大小和方向和锚点(激光枪) void bulletFactory::setScale_and_setRotation(Sprite* b, int type, bool isPlayer1) { // 获得玩家的朝向toward std::string toward = (isPlayer1) ? GlobalVar::getInstance()->player1_toward : GlobalVar::getInstance()->player2_toward; //根据type调整精灵大小,根据toward设置锚点 switch (type) { case 0 : b->setScale(0.5); break; case 1 : b->setScaleY(0.5); break; case 2 : b->setScale(0.5); break; case 3 : b->setScale(0.2); break; case 4 : b->setScaleY(1.5); break; case 5 : b->setScaleY(0.5); b->ignoreAnchorPointForPosition(false); b->setAnchorPoint(ccp(1, 0)); break; default: break; } //根据朝向toward设置子弹旋转 float angle; for (int i = 0; i < 8; i++) { if (toward == GlobalVar::getInstance()->Direction[i]) { angle = i * 45; break; } } b->setRotation(angle); } // 子弹发射之后的轨迹运行 void bulletFactory::moveBullet(Sprite * b, int type, bool isPlayer1) { // 获得玩家朝向 std::string toward = (isPlayer1) ? GlobalVar::getInstance()->player1_toward : GlobalVar::getInstance()->player2_toward; Vec2 nextNearPos = Vec2(0, 0); Vec2 nextFarPos = Vec2(0, 0); if (toward == GlobalVar::getInstance()->Direction[0]) { nextNearPos = Vec2(-300, 0); nextFarPos = Vec2(-500,0); } else if (toward == GlobalVar::getInstance()->Direction[1]) { nextNearPos = Vec2(-200, 200); nextFarPos = Vec2(-350, 350); } else if (toward == GlobalVar::getInstance()->Direction[2]) { nextNearPos = Vec2(0, 300); nextFarPos = Vec2(0, 500); } else if (toward == GlobalVar::getInstance()->Direction[3]) { nextNearPos = Vec2(200, 200); nextFarPos = Vec2(350, 350); } else if (toward == GlobalVar::getInstance()->Direction[4]) { nextNearPos = Vec2(300, 0); nextFarPos = Vec2(500, 0); } else if (toward == GlobalVar::getInstance()->Direction[5]) { nextNearPos = Vec2(200, -200); nextFarPos = Vec2(350, -350); } else if (toward == GlobalVar::getInstance()->Direction[6]) { nextNearPos = Vec2(0, -300); nextFarPos = Vec2(0, -500); } else if (toward == GlobalVar::getInstance()->Direction[7]) { nextNearPos = Vec2(-200, -200); nextFarPos = Vec2(-350, -350); } auto MoveToNear = MoveBy::create(0.5f, nextNearPos); auto MoveToFar = MoveBy::create(0.5f, nextFarPos); auto disapper = CallFunc::create([&, b, type, isPlayer1]() { removeBullet(b, type, isPlayer1); }); auto sequence1 = Sequence::create(MoveToNear, disapper, NULL); auto sequence2 = Sequence::create(MoveToFar, disapper, NULL); switch (type) { case 0: case 1: case 2: b->runAction(sequence1); break; case 3: case 4: case 5: b->runAction(sequence2); default: break; } } void bulletFactory::clear() { bulletForPlayer1->clear(); bulletForPlayer2->clear(); // 玩家现在拥有的弹药数目 for (int i = 0; i < 6; i++) { bulletNumForPlayer1[i] = 9999; bulletNumForPlayer2[i] = 9999; } }
[ "944131226@qq.com" ]
944131226@qq.com
2d9fbe9e00327093325992303c09dea4b6b38279
1b8e1ddcb86f0a5cd018bc6b3400c8c6fb1c1984
/server/server/activity/.svn/text-base/EntityActivityComponent.h.svn-base
2a478d33d3168192f761c587c50e1a285db4d5df
[]
no_license
yzfrs/ddianle_d1
5e9a3ab0ad646ca707368850c01f8117a09f5bfd
abffb574419cc2a8a361702e012cdd14f1102a6d
refs/heads/master
2021-01-01T03:32:51.973703
2016-05-12T09:27:00
2016-05-12T09:27:00
58,615,329
0
2
null
null
null
null
GB18030
C++
false
false
16,447
#ifndef __ENTITYACTIVITYCOMPONENT_H__ #define __ENTITYACTIVITYCOMPONENT_H__ // 累计在线时长奖励的数据库只存储最新的数据,不会删除或者清零。 // 数据是否有效只在DB存储出来后做由程序做处理。 #include <list> #include "../logic/RoleComponentImpl.h" #include "../logic/EntityComponent.h" #include "ActivityDataStruct.h" #define INVITATION_DB_QUERY_MIN_INTERVAL 5 using namespace std; class CEntityNetComponent; class CEntityTimerComponent; class CEntityAttributeComponent; class CEntityItemComponent; class CEntityMailComponent; class CEntityFriendComponent; class CEntityChatComponent; class CCummulativeRechareActivityInfo; class CCummulativeSpendActivityInfo; class CExchangeItemActivityInfo; class CShowInTimeOnlineActivity; class CPlainTextActivityInfo; class CGiftCodeActivityInfo; class COnlineRewardActivity; class CumulativeSpendGotMedalActivityData; class BuyItemGotMedalActivityData; class CEntityCoupleComponent; class CProprietaryActivityInfo; class CEntityQuestComponent; class CEntityVIPComponent; class CEntityQuestNewComponent; class CEntityMedalComponent; class CEntityDanceGroupComponent; class CEntityActivityComponent : public CEntityComponent, public CommonSubscriber { public: CEntityActivityComponent(); ~CEntityActivityComponent(); public: virtual void OnEvent(CComponentEvent& refEvent); virtual void Start(); virtual void OnLogin(); virtual void OnLogout(); virtual void OnUpdate(const unsigned long &nTimeElapsed); virtual void SerializeComponent(CParamPool &IOBuff); virtual const char* SerializeName(){ return "Activity"; }; virtual bool CreateFromDB(ROLEINFO_DB* pRoleInfoDB); virtual bool PacketToDB(ROLEINFO_DB *pRoleInforDB) const; virtual bool PacketToCache( ROLEINFO_DB* pRoleInforDB ) const; virtual void SendExtraStaticData(){}; virtual void PacketBuff(std::list<BuffData>& listBuff); virtual void OnNotify(IParam &param); void RegComponentNetMsgMap(); void SendAllActivitiesInfo(); public: void OnOnlineRewardActivityStart(); void OnOnlineRewardActivityEnd(); void OnCumulativeRechargeActivityStart(); void OnCumulativeRechargeActivityEnd(); void UpdateOnlineRewardInfoToClient(); void OnPlayerRecharge(int nCharge); void LogMeetAction(int nAction, unsigned int nCoupleRoleID = 0, int nAmuseID = 0); void OnTestActivity(int nPara1, int nPara2, int nPara3); bool IsSharedToSocial(EUISocialShare ui); void SetSharedToSocial(EUISocialShare ui, bool b, bool bToDB = true); time_t GetFirstSharedTime(EUISocialShare ui); bool CanGetPhotoShareVIPReward() const { return m_bNotGetPhotoShareVIPReward; } void SetNotGetPhotoShareVIPReward(bool bNoGetVIPReward) { m_bNotGetPhotoShareVIPReward = bNoGetVIPReward; } void OnActivityChange(unsigned char nActivityID, bool bOpen); EUISocialShare GetEUISocialShareByActivityID(EActivity eActivity); EActivity GetActivityIDByEUISocialShare(EUISocialShare eUI); void AddCumulativeSpendBill(int nValue); void AddCumulativeSpendBindBill(int nValue); private: void _OnGetAllActivitiesInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); void GetCDKeyInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); void GetBindActivationInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); // 获取在线奖励 void _OnGetOnlineReward(GameMsg_Base & msg, CSlotPeer &slotPeer); //获取礼品 void _OnGetGift(GameMsg_Base & msg, CSlotPeer &slotPeer); //累计充值 void _OnGetCumulativeRechargeReward(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnExchangeItem(GameMsg_Base & msg, CSlotPeer &slotPeer); //累计消费 void OnGetCumulativeSpendReward(GameMsg_Base & msg, CSlotPeer &slotPeer); void _LoadCumulativeSpendInfo(); void _LoadCumulativeSpendInfoForMedal(); int GetCumulativeSpendValue(int nCurrencyType); int GetCumulativeSpendValueForMedal(int nCurType); // 累计消费获取勋章 void OnGetCumulativeSpendGotMedalReward(GameMsg_Base &msg, CSlotPeer &slotPeer); void LoadCumulativeSpendGotMedalReward(); bool CanGetCumulativeSpendGotMedalRewards(unsigned char nIndex); //IOS尊享版奖励领取操作 void _OnGetProprietaryReward(GameMsg_Base & msg, CSlotPeer &slotPeer); //活动扩展数据 void _OnGetExtraActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); //圣诞免费礼物 void _SaveXmasFreeRewardInfo(unsigned int nLastGetRewardTime); void _LoadXmasFreeRewardInfo(); void _SendXmasFreeRewardActivityInfo(); void _OnGetXmasActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnGetXmasFreeReward(GameMsg_Base & msg, CSlotPeer &slotPeer); //许愿活动 void _LoadFestivalWishInfo(); void _SaveFestivalWishInfo(); void _SendFestivalWishActivityInfo(); void _OnGetFestivalWishActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnRoleFestivalWish(GameMsg_Base & msg, CSlotPeer &slotPeer); //祝福活动 void _SaveBlessInfo(CFestivalBlessInfoDB *pBlessEntryDB); void _SaveRoleBlessActivityInfo(unsigned int nGetRewardTime); void _LoadRoleBlessActivityInfo(); void _OnGetFestivalBlessActivityInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); void _BlessFriend(GameMsg_Base & msg, CSlotPeer &slotPeer); void _BlessFriend_G(GameMsg_Base & msg, CSlotPeer &slotPeer); void _GetFestivalBlessReward(GameMsg_Base & msg, CSlotPeer &slotPeer); bool _ReachCumulativeRechargeRequire(int nCurRechargeNum, int nLevel); bool _ReachCumulativeSpendRequire(int nCurRechargeNum, int nLevel); void _LoadCumulativeRechargeInfo(); //拼图活动 void _LoadRolePuzzleDB(); void _UpdateRolePuzzleDB(int nOriTime, const CRolePuzzleActivityInfo & rPuzzleInfo); void _InitRolePuzzleInfo(const std::list<CRolePuzzleActivityDB> &rlistPuzzle); void _InitRolePuzzleInfo(CRoleAllPuzzleDB *pPuzzleDB); void _OnFillPuzzle(GameMsg_Base & msg, CSlotPeer &slotPeer); void SyncPuzzleData(); //玩家招募活动 void _SetInvitationActivity(CInvitationActivityInfo& activity); void _OnGetInvitationInviterInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnBindInvitationCode(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnGetInviterCumulativeReward(GameMsg_Base & msg, CSlotPeer &slotPeer); // 新手七天乐活动 void _SetFresherActivity(CFresherActivityInfo &activity); void _OnGetFresherReward(GameMsg_Base & msg, CSlotPeer &slotPeer); bool _HasReceivedAllFresherReward(); bool HaveGetFresherReward(int nDay); bool ReissueVipReward(std::list<CReward> & viprewardlist); //商城社交分享 void _SetMallShareActivity(CMallShareActivityData& activity); // 数据库加载邀请人数和已经获得的奖励信息 void _OnDBCheckInvitationCode(QueryBase& rQuery); void _OnDBGetInvitationInfo(QueryBase& rQuery); // 邂逅活动 void _OnMeetMatch(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnMeetCancelMatch(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnMeetLeaveScene(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnMeetCameraEvent(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnMeetEnd(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnMeetEnterAmuseScene(GameMsg_Base & msg, CSlotPeer &slotPeer); //普通社交分享功能 void _OnSocialShare(GameMsg_Base & msg, CSlotPeer &slotPeer); //社交分享活动 void _OnActivitySocialShare(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnRequestVipExtraReward(GameMsg_Base &msg, CSlotPeer &slotPeer); void SendAllShareActivitiesCanFirst(); void SendCanSocialShareFirst(EUISocialShare ui, bool bCanShare); void SyncGiftData(); // 光效石兑换 void ExchangeEffectStone(); //数据库加载礼品 void _OnLoadGift(QueryBase & rQuery); void _OnLoadCumulativeRechargeInfo(QueryBase & rQuery); void _OnLoadCumulativeSpendInfo(QueryBase & rQuery); void _OnLoadCumulativeSpendInfoForMedal(QueryBase& rQuery); void _OnDBLoadXmasFreeRewardInfo(QueryBase & rQuery); void _OnDBLoadRoleBlessActivityInfo(QueryBase & rQuery); void _OnDBLoadRoleFestivalWishActivityInfo(QueryBase & rQuery); void _OnDBLoadRolePuzzleActivityInfo(QueryBase & rQuery); void OnQueryCumulativeSpendGotMedalReward(QueryBase &rQuery); void OnQueryBuyItemGotMedalRewardedInfo(QueryBase &rQuery); void _SendPlayerMsg(GameMsg_Base *pMsg); void _SetNextKeepOnlineReward(int nIndex, CKeepOnlineReward & onlineInfo, bool bCanReset = true); void _ResetKeepOnlineRewardInfo(); void _UpdateOnlineRewardInfoDB(); void _HandleOnlineInfo(CKeepOnlineReward & onlineRewardInfo, unsigned int nNow); void _OnOnlineRewardActivityReset(); void _SetCumulativeRechargeActivity(CCummulativeRechareActivityInfo & activity); void _SetCumulativeSpendActivity(CCummulativeSpendActivityInfo & activity); bool _HasReceivedCumulativeReward(int nLevel); bool _HasReceivedCumulativeSpendReward(int nLevel); bool IsSpendRewardEmpty(); void SetCumulativeSpendGotMedalActivity(CumulativeSpendGotMedalActivityData &rActivity); bool HasReceivedCumulativeSpendGotMedalReward(int nIndex); void OnRequestBuyItemGotMedalReward(GameMsg_Base &msg, CSlotPeer &slotPeer); void SetBuyItemGotMedalActivity(BuyItemGotMedalActivityData &rActivity) const; bool HasReceivedBuyItemGotMedalReward(unsigned char nIndex) const; bool CanGetBuyItemGotMedalRewards(unsigned char nIndex) const; void GetBuyItemGotMedalRewardedInfo(unsigned char nIndex, bool *rReceived, unsigned short *rCurrentCount) const; void LoadBuyItemGotMedalRewardedInfo(); void UpdateBuyItemGotMedalInfo(unsigned int nItemType, unsigned short nItemCount); void _SetExchangeItemActivity(CExchangeItemActivityInfo & activity); bool _ReachExchangeItemRequire(int nLevel); void _SetInTimeOnlineActivity(CShowInTimeOnlineActivity & activity); void _SetPlainTextActivity(CPlainTextActivityInfo & activity); void _SetGiftCodeActivity(CGiftCodeActivityInfo & activity); void _SetOnlineRewardActivity(COnlineRewardActivity & activit); bool _OnlineRewardActivityActivated(); void _SendPlayerReward(int nIndex); void _SetMallSocialShareActivity(CMallSocialShareActivityData &activity); void _SetPhotoSocialShareActivity(CPhotoSocialShareActivityData &activity); void _SetProprietaryAcitivty(CProprietaryActivityInfo& activity); // 获取长效累冲信息 void OnGetLongactingCumulativeRechargeInfo(GameMsg_Base & msg, CSlotPeer &slotPeer); // 领取长效累冲奖励 void OnGetLongactingCumulativeReward(GameMsg_Base & msg, CSlotPeer &slotPeer); // 获取长效累冲广播 void OnGetLongactingCumulativeBoardCast(GameMsg_Base & msg, CSlotPeer &slotPeer); void _OnGetLongactingCumulativeBoardCast(GameMsg_Base & msg, CSlotPeer &slotPeer); public://...........舞团红包................ // 获取红包列表 void OnGetRedEnvelopeList(GameMsg_Base &msg, CSlotPeer &slotPeer); void _OnGetRedEnvelopeList(GameMsg_Base &msg, CSlotPeer &slotPeer); // 获取红包详细信息 void OnGetRedEnvelopeDetails(GameMsg_Base &msg, CSlotPeer &slotPeer); void _OnGetRedEnvelopeDetails(GameMsg_Base &msg, CSlotPeer &slotPeer); // 新红包广播 void OnNewRedEnvelopeNotice(GameMsg_Base &msg, CSlotPeer &slotPeer); // 设置匿名 void OnSetAnonymity(GameMsg_Base &msg, CSlotPeer &slotPeer); // 开红包 void OnOpenRedEnvelope(GameMsg_Base &msg, CSlotPeer &slotPeer); void _OnOpenRedEnvelope(GameMsg_Base &msg, CSlotPeer &slotPeer); // void OnGetCanOpenRedEnvelopeCount(GameMsg_Base &msg, CSlotPeer &slotPeer); void _OnGetCanOpenRedEnvelopeCount(GameMsg_Base &msg, CSlotPeer &slotPeer); public: // 更新奖励序列 void UpdateLongactingRechargeRewardIndex(unsigned int nRewardIndex); private: CEntityNetComponent * m_pRoleNet; CEntityTimerComponent * m_pRoleTimer; CEntityAttributeComponent * m_pRoleAttr; CEntityItemComponent * m_pRoleItem; CEntityMailComponent * m_pRoleMail; CEntityFriendComponent * m_pRoleFriend; CEntityChatComponent * m_pRoleChat; CEntityCoupleComponent * m_pRoleCouple; CEntityQuestComponent * m_pRoleFresherQuest; CEntityVIPComponent * m_pRoleVip; CEntityQuestNewComponent * m_pRoleQuest; CEntityMedalComponent * m_pRoleMedal; CEntityDanceGroupComponent * m_pRoleDanceGroup; private: int m_nLastStop; unsigned long m_nTimeElapsed; unsigned long m_nUpdateDBTimeElapse; std::map< int, GiftDB > m_GiftMap; //当前玩家的礼品列表 // 累计充值 int m_nCumulativeRechargeNum; //累积充值,表示当前开启的累计充值活动的数值 bool m_bLoadCumulativeRechargeDB;//是否已经加载了玩家累计充值的数据 std::vector<int> m_vecCumulativeRewards; // 累计消费 std::vector<unsigned int> m_CumulativeSpendReward; unsigned int m_nCumulativeBill; unsigned int m_nCumulativeBindBill; bool m_bLoadCumulativeSpendSuc; /// <summary> /// 记录勋章累计消费活动的值 /// <summary unsigned int m_nCumulativeBillForMedal; unsigned int m_nCumulativeBindBillForMedal; std::vector<unsigned int> m_CumulativeSpendRewardForMedal; std::vector<bool> m_vectCumulativeSpendGotMedalReward; // 购买物品获取勋章 BuyItemGotMedalRewardedInfoMap m_mapBuyItemGotMedalRewardedInfo; // 圣诞节免费领取 CRoleXmasFreeRewardInfo m_roleXmasFreeRewardInfo; // 许愿活动 CRoleFestivalWishActivityInfo m_roleFestivalWishActivityInfo; // 祝福活动 CRoleBlessActivityInfo m_roleBlessActivityInfo; // 拼图活动 bool m_bCheckPuzzleOpen; std::map<int, CRolePuzzleActivityInfo> m_rolePuzzleActivityInfo; // 新玩家招募活动 unsigned int m_nInvitationBindCount; CRoleInvitationRewardDBMap m_InvitationRewards; unsigned int m_nInvitationQueryTime; // 新手七天乐活动 std::set<int> m_FresherRewardDays; int m_nFresherDay; int m_nCurrentFresherDay; //最后领取奖励的day bool m_bProprietaryReward; //是否已经领取过尊享版的奖励 // 社交分享 std::map<EUISocialShare, time_t> m_mapSocialShareRecord; std::map<EActivity, EUISocialShare> m_mapSocialShareActivity2UI; //社交分享的活动id与界面id的对应关系 bool m_bNotGetPhotoShareVIPReward; // 拍照分享没有获得VIP奖励 // 在线奖励 CKeepOnlineReward m_keepOnlineRewardInfo; // 长效累冲活动 unsigned int m_nLongactingCumulativeRechargeIndex; //奖励序列 // 光效石兑换活动 bool m_bHaveExchangeItem; std::list<CItem> m_listExchangeItem; }; typedef CRoleComponentImpl<CEntityActivityComponent, CGetRoleProcessorObj, CGetRoleProcessorObj> CRoleActivity; #endif
[ "root@localhost.localdomain" ]
root@localhost.localdomain
ad79e11b5f0cc9ad7258b4deacf8e4eeb1b610c4
f0a26ec6b779e86a62deaf3f405b7a83868bc743
/Engine/Source/Editor/GraphEditor/Private/KismetNodes/SGraphNodeK2Base.cpp
589afd53c93423f2d237060fb92b99ea6c6078d6
[]
no_license
Tigrouzen/UnrealEngine-4
0f15a56176439aef787b29d7c80e13bfe5c89237
f81fe535e53ac69602bb62c5857bcdd6e9a245ed
refs/heads/master
2021-01-15T13:29:57.883294
2014-03-20T15:12:46
2014-03-20T15:12:46
18,375,899
1
0
null
null
null
null
UTF-8
C++
false
false
14,675
cpp
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. #include "GraphEditorCommon.h" #include "SGraphNodeK2Base.h" #include "Editor/UnrealEd/Public/Kismet2/KismetDebugUtilities.h" #include "Editor/UnrealEd/Public/Kismet2/BlueprintEditorUtils.h" #include "KismetNodeInfoContext.h" #include "IDocumentation.h" #define LOCTEXT_NAMESPACE "SGraphNodeK2Base" ////////////////////////////////////////////////////////////////////////// // SGraphNodeK2Base const FLinearColor SGraphNodeK2Base::BreakpointHitColor(0.7f, 0.0f, 0.0f); const FLinearColor SGraphNodeK2Base::LatentBubbleColor(1.f, 0.5f, 0.25f); const FLinearColor SGraphNodeK2Base::TimelineBubbleColor(0.7f, 0.5f, 0.5f); const FLinearColor SGraphNodeK2Base::PinnedWatchColor(0.7f, 0.5f, 0.5f); void SGraphNodeK2Base::UpdateStandardNode() { SGraphNode::UpdateGraphNode(); // clear the default tooltip, to make room for our custom "complex" tooltip SetToolTip(NULL); } void SGraphNodeK2Base::UpdateCompactNode() { InputPins.Empty(); OutputPins.Empty(); // error handling set-up TSharedPtr<SWidget> ErrorText = SetupErrorReporting(); // Reset variables that are going to be exposed, in case we are refreshing an already setup node. RightNodeBox.Reset(); LeftNodeBox.Reset(); TSharedPtr< SToolTip > NodeToolTip = SNew( SToolTip ); if ( !GraphNode->GetTooltip().IsEmpty() ) { NodeToolTip = IDocumentation::Get()->CreateToolTip( TAttribute< FText >( this, &SGraphNode::GetNodeTooltip ), NULL, GraphNode->GetDocumentationLink(), GraphNode->GetDocumentationExcerptName() ); } // // ______________________ // | (>) L | | R (>) | // | (>) E | | I (>) | // | (>) F | + | G (>) | // | (>) T | | H (>) | // | | | T (>) | // |_______|______|_______| // this->ContentScale.Bind( this, &SGraphNode::GetContentScale ); this->ChildSlot .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew(SVerticalBox) +SVerticalBox::Slot() .AutoHeight() .Padding( FMargin(5.0f, 1.0f) ) [ ErrorText->AsShared() ] +SVerticalBox::Slot() [ // NODE CONTENT AREA SNew(SOverlay) .ToolTip( NodeToolTip.ToSharedRef() ) +SOverlay::Slot() [ SNew(SImage) .Image( FEditorStyle::GetBrush("Graph.CompactNode.Body") ) ] +SOverlay::Slot() .HAlign(HAlign_Center) // Pad out so that the node circles do not // overlap the background text. .Padding( FMargin(23,0) ) [ // MIDDLE SNew(STextBlock) .TextStyle( FEditorStyle::Get(), "Graph.CompactNode.Title" ) .Text( this, &SGraphNodeK2Base::GetNodeCompactTitle ) ] +SOverlay::Slot() .Padding( FMargin(0,3) ) [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .Padding( FMargin(0,0,5,0) ) .HAlign(HAlign_Left) .VAlign(VAlign_Center) .FillWidth(1.0f) [ // LEFT SAssignNew(LeftNodeBox, SVerticalBox) ] +SHorizontalBox::Slot() .AutoWidth() .Padding( FMargin(5,0,0,0) ) .HAlign(HAlign_Right) .VAlign(VAlign_Center) [ // RIGHT SAssignNew(RightNodeBox, SVerticalBox) ] ] ] ]; CreatePinWidgets(); // Hide pin labels for (int32 PinIndex=0; PinIndex < this->InputPins.Num(); ++PinIndex) { InputPins[PinIndex]->SetShowLabel(false); } for (int32 PinIndex = 0; PinIndex < this->OutputPins.Num(); ++PinIndex) { OutputPins[PinIndex]->SetShowLabel(false); } } TSharedPtr<SToolTip> SGraphNodeK2Base::GetComplexTooltip() { TSharedPtr<SToolTip> NodeToolTip; TSharedRef<SToolTip> DefaultToolTip = IDocumentation::Get()->CreateToolTip(TAttribute<FText>(this, &SGraphNode::GetNodeTooltip), NULL, GraphNode->GetDocumentationLink(), GraphNode->GetDocumentationExcerptName()); struct LocalUtils { static EVisibility IsToolTipVisible(TSharedRef<SGraphNodeK2Base> const NodeWidget) { return NodeWidget->GetNodeTooltip().IsEmpty() ? EVisibility::Collapsed : EVisibility::Visible; } static EVisibility IsToolTipHeadingVisible(TSharedRef<SGraphNodeK2Base> const NodeWidget) { return NodeWidget->GetToolTipHeading().IsEmpty() ? EVisibility::Collapsed : EVisibility::Visible; } static bool IsInteractive() { const FModifierKeysState ModifierKeys = FSlateApplication::Get().GetModifierKeys(); return ( ModifierKeys.IsAltDown() && ModifierKeys.IsControlDown() ); } }; TSharedRef<SGraphNodeK2Base> ThisRef = SharedThis(this); SAssignNew(NodeToolTip, SToolTip) .Visibility_Static(&LocalUtils::IsToolTipVisible, ThisRef) .IsInteractive_Static(&LocalUtils::IsInteractive) [ SNew(SVerticalBox) // heading container +SVerticalBox::Slot() [ SNew(SVerticalBox) .Visibility_Static(&LocalUtils::IsToolTipHeadingVisible, ThisRef) +SVerticalBox::Slot() .AutoHeight() [ SNew(STextBlock) .Font(FEditorStyle::GetFontStyle(TEXT("Kismet.Tooltip.SubtextFont"))) .ColorAndOpacity(FSlateColor::UseSubduedForeground()) .Text(this, &SGraphNodeK2Base::GetToolTipHeading) ] +SVerticalBox::Slot() .AutoHeight() .Padding(0.f, 2.f, 0.f, 5.f) [ SNew(SBorder) // use the border's padding to actually create the horizontal line .Padding(1.f) .BorderImage(FEditorStyle::GetBrush(TEXT("Menu.Separator"))) ] ] // tooltip body +SVerticalBox::Slot() .AutoHeight() [ DefaultToolTip->GetContent() ] ]; return NodeToolTip; } FText SGraphNodeK2Base::GetToolTipHeading() const { if (UK2Node const* K2Node = CastChecked<UK2Node>(GraphNode)) { return K2Node->GetToolTipHeading(); } return FText::GetEmpty(); } /** * Update this GraphNode to match the data that it is observing */ void SGraphNodeK2Base::UpdateGraphNode() { UK2Node* K2Node = CastChecked<UK2Node>(GraphNode); const bool bCompactMode = K2Node->ShouldDrawCompact(); if (bCompactMode) { UpdateCompactNode(); } else { UpdateStandardNode(); } } bool SGraphNodeK2Base::RequiresSecondPassLayout() const { UK2Node* K2Node = CastChecked<UK2Node>(GraphNode); const bool bBeadMode = K2Node->ShouldDrawAsBead(); return bBeadMode; } FString SGraphNodeK2Base::GetNodeCompactTitle() const { UK2Node* K2Node = CastChecked<UK2Node>(GraphNode); return K2Node->GetCompactNodeTitle(); } /** Populate the brushes array with any overlay brushes to render */ void SGraphNodeK2Base::GetOverlayBrushes(bool bSelected, const FVector2D WidgetSize, TArray<FOverlayBrushInfo>& Brushes) const { UBlueprint* OwnerBlueprint = FBlueprintEditorUtils::FindBlueprintForNodeChecked(GraphNode); // Search for an enabled or disabled breakpoint on this node UBreakpoint* Breakpoint = FKismetDebugUtilities::FindBreakpointForNode(OwnerBlueprint, GraphNode); if (Breakpoint != NULL) { FOverlayBrushInfo BreakpointOverlayInfo; if (Breakpoint->GetLocation()->IsA<UK2Node_Composite>() || Breakpoint->GetLocation()->IsA<UK2Node_MacroInstance>()) { if (Breakpoint->IsEnabledByUser()) { BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(FKismetDebugUtilities::IsBreakpointValid(Breakpoint) ? TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndValidCollapsed") : TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndInvalidCollapsed")); } else { BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(TEXT("Kismet.DebuggerOverlay.Breakpoint.DisabledCollapsed")); } } else { if (Breakpoint->IsEnabledByUser()) { BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(FKismetDebugUtilities::IsBreakpointValid(Breakpoint) ? TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndValid") : TEXT("Kismet.DebuggerOverlay.Breakpoint.EnabledAndInvalid")); } else { BreakpointOverlayInfo.Brush = FEditorStyle::GetBrush(TEXT("Kismet.DebuggerOverlay.Breakpoint.Disabled")); } } if(BreakpointOverlayInfo.Brush != NULL) { BreakpointOverlayInfo.OverlayOffset -= BreakpointOverlayInfo.Brush->ImageSize/2.f; } Brushes.Add(BreakpointOverlayInfo); } // Is this the current instruction? if (FKismetDebugUtilities::GetCurrentInstruction() == GraphNode) { FOverlayBrushInfo IPOverlayInfo; // Pick icon depending on whether we are on a hit breakpoint const bool bIsOnHitBreakpoint = FKismetDebugUtilities::GetMostRecentBreakpointHit() == GraphNode; IPOverlayInfo.Brush = FEditorStyle::GetBrush( bIsOnHitBreakpoint ? TEXT("Kismet.DebuggerOverlay.InstructionPointerBreakpoint") : TEXT("Kismet.DebuggerOverlay.InstructionPointer") ); if (IPOverlayInfo.Brush != NULL) { float Overlap = 10.f; IPOverlayInfo.OverlayOffset.X = (WidgetSize.X/2.f) - (IPOverlayInfo.Brush->ImageSize.X/2.f); IPOverlayInfo.OverlayOffset.Y = (Overlap - IPOverlayInfo.Brush->ImageSize.Y); } IPOverlayInfo.AnimationEnvelope = FVector2D(0.f, 10.f); Brushes.Add(IPOverlayInfo); } // @todo remove if Timeline nodes are rendered in their own slate widget if (const UK2Node_Timeline* Timeline = Cast<const UK2Node_Timeline>(GraphNode)) { float Offset = 0.0f; if (Timeline && Timeline->bAutoPlay) { FOverlayBrushInfo IPOverlayInfo; IPOverlayInfo.Brush = FEditorStyle::GetBrush( TEXT("Graph.Node.Autoplay") ); if (IPOverlayInfo.Brush != NULL) { const float Padding = 2.5f; IPOverlayInfo.OverlayOffset.X = WidgetSize.X - IPOverlayInfo.Brush->ImageSize.X - Padding; IPOverlayInfo.OverlayOffset.Y = Padding; } Brushes.Add(IPOverlayInfo); Offset = IPOverlayInfo.Brush->ImageSize.X; } if (Timeline && Timeline->bLoop) { FOverlayBrushInfo IPOverlayInfo; IPOverlayInfo.Brush = FEditorStyle::GetBrush( TEXT("Graph.Node.Loop") ); if (IPOverlayInfo.Brush != NULL) { const float Padding = 2.5f; IPOverlayInfo.OverlayOffset.X = WidgetSize.X - IPOverlayInfo.Brush->ImageSize.X - Padding - Offset; IPOverlayInfo.OverlayOffset.Y = Padding; } Brushes.Add(IPOverlayInfo); } } // Display an icon depending on the type of node and it's settings if (const UK2Node* K2Node = Cast<const UK2Node>(GraphNode)) { FName ClientIcon = K2Node->GetCornerIcon(); if ( ClientIcon != NAME_None ) { FOverlayBrushInfo IPOverlayInfo; IPOverlayInfo.Brush = FEditorStyle::GetBrush( ClientIcon ); if (IPOverlayInfo.Brush != NULL) { IPOverlayInfo.OverlayOffset.X = (WidgetSize.X - (IPOverlayInfo.Brush->ImageSize.X/2.f))-3.f; IPOverlayInfo.OverlayOffset.Y = (IPOverlayInfo.Brush->ImageSize.Y/-2.f)+2.f; } Brushes.Add(IPOverlayInfo); } } } void SGraphNodeK2Base::GetNodeInfoPopups(FNodeInfoContext* Context, TArray<FGraphInformationPopupInfo>& Popups) const { FKismetNodeInfoContext* K2Context = (FKismetNodeInfoContext*)Context; // Display any pending latent actions if (UObject* ActiveObject = K2Context->ActiveObjectBeingDebugged) { TArray<FKismetNodeInfoContext::FObjectUUIDPair>* Pairs = K2Context->NodesWithActiveLatentActions.Find(GraphNode); if (Pairs != NULL) { for (int32 Index = 0; Index < Pairs->Num(); ++Index) { FKismetNodeInfoContext::FObjectUUIDPair Action = (*Pairs)[Index]; if (Action.Object == ActiveObject) { if (UWorld* World = GEngine->GetWorldFromContextObject(Action.Object)) { FLatentActionManager& LatentActionManager = World->GetLatentActionManager(); const FString LatentDesc = LatentActionManager.GetDescription(Action.Object, Action.UUID); const FString& ActorLabel = Action.GetDisplayName(); new (Popups) FGraphInformationPopupInfo(NULL, LatentBubbleColor, LatentDesc); } } } } // Display pinned watches if (K2Context->WatchedNodeSet.Contains(GraphNode)) { UBlueprint* Blueprint = K2Context->SourceBlueprint; const UEdGraphSchema* Schema = GraphNode->GetSchema(); FString PinnedWatchText; int32 ValidWatchCount = 0; for (int32 PinIndex = 0; PinIndex < GraphNode->Pins.Num(); ++PinIndex) { UEdGraphPin* WatchPin = GraphNode->Pins[PinIndex]; if (K2Context->WatchedPinSet.Contains(WatchPin)) { if (ValidWatchCount > 0) { PinnedWatchText += TEXT("\n"); } FString PinName = UEdGraphSchema_K2::TypeToString(WatchPin->PinType); PinName += TEXT(" "); PinName += Schema->GetPinDisplayName(WatchPin); FString WatchText; const FKismetDebugUtilities::EWatchTextResult WatchStatus = FKismetDebugUtilities::GetWatchText(/*inout*/ WatchText, Blueprint, ActiveObject, WatchPin); switch (WatchStatus) { case FKismetDebugUtilities::EWTR_Valid: PinnedWatchText += FString::Printf(*LOCTEXT("WatchingAndValid", "Watching %s\n\t%s").ToString(), *PinName, *WatchText);//@TODO: Print out object being debugged name? break; case FKismetDebugUtilities::EWTR_NotInScope: PinnedWatchText += FString::Printf(*LOCTEXT("WatchingWhenNotInScope", "Watching %s\n\t(not in scope)").ToString(), *PinName); break; case FKismetDebugUtilities::EWTR_NoProperty: PinnedWatchText += FString::Printf(*LOCTEXT("WatchingUnknownProperty", "Watching %s\n\t(no debug data)").ToString(), *PinName); break; default: case FKismetDebugUtilities::EWTR_NoDebugObject: PinnedWatchText += FString::Printf(*LOCTEXT("WatchingNoDebugObject", "Watching %s").ToString(), *PinName); break; } ValidWatchCount++; } } if (ValidWatchCount) { new (Popups) FGraphInformationPopupInfo(NULL, PinnedWatchColor, PinnedWatchText); } } } } const FSlateBrush* SGraphNodeK2Base::GetShadowBrush(bool bSelected) const { const UK2Node* K2Node = CastChecked<UK2Node>(GraphNode); const bool bCompactMode = K2Node->ShouldDrawCompact(); if (bSelected && bCompactMode) { return FEditorStyle::GetBrush( "Graph.CompactNode.ShadowSelected" ); } else { return SGraphNode::GetShadowBrush(bSelected); } } void SGraphNodeK2Base::PerformSecondPassLayout(const TMap< UObject*, TSharedRef<SNode> >& NodeToWidgetLookup) const { TSet<UEdGraphNode*> PrevNodes; TSet<UEdGraphNode*> NextNodes; // Gather predecessor/successor nodes for (int32 PinIndex = 0; PinIndex < GraphNode->Pins.Num(); ++PinIndex) { UEdGraphPin* Pin = GraphNode->Pins[PinIndex]; if (Pin->LinkedTo.Num() > 0) { if (Pin->Direction == EGPD_Input) { for (int32 LinkIndex = 0; LinkIndex < Pin->LinkedTo.Num(); ++LinkIndex) { PrevNodes.Add(Pin->LinkedTo[LinkIndex]->GetOwningNode()); } } if (Pin->Direction == EGPD_Output) { for (int32 LinkIndex = 0; LinkIndex < Pin->LinkedTo.Num(); ++LinkIndex) { NextNodes.Add(Pin->LinkedTo[LinkIndex]->GetOwningNode()); } } } } // Place this node smack between them const float Height = 0.0f; PositionThisNodeBetweenOtherNodes(NodeToWidgetLookup, PrevNodes, NextNodes, Height); } #undef LOCTEXT_NAMESPACE
[ "michaellam430@gmail.com" ]
michaellam430@gmail.com