blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
158
f16c675ea62328d3b6048d8b2f33e1756b0a0072
001c1c1a1e4044a0061ce8736d272842add9caff
/src/visualization/view/GraphItemFactory.cpp
92151cb3be4ae0e86f6c93e2c7c95f5e8050293c
[]
no_license
moodah/PRO
c3a2f5c9f66d3549fb41f4fce330915870e309f3
5da689ab9a7e6167b4b50b0c100d05e03e91f7d9
refs/heads/master
2021-05-01T01:17:07.163039
2016-06-06T13:09:55
2016-06-06T13:09:55
52,285,580
0
1
null
null
null
null
UTF-8
C++
false
false
435
cpp
/*! * \brief Graph factory class * * \file GraphItemFactory.cpp * \author Damien Rochat * \date 23.05.2016 */ #include "../../graph/graphs/IEdge.h" #include "GraphItemFactory.h" #include "EdgeItem.h" EdgeItem *GraphItemFactory::createEdge(const IEdge *edge, VertexItem *source, VertexItem *dest) { return new EdgeItem(edge, source, dest); } GraphItemFactory::~GraphItemFactory() {}
fbced8bb5452a299470872815793ed2413130372
1f8c74d888511275ad769c561cc8d78a6a2a044d
/Audio/Audio.h
d7c0e786990465a904546a45c98ef7153794df09
[]
no_license
dddgg9511/WavEditor
616323bea026b6b663b8f635aa7fe89e7f8e3875
999acc8e601349f8fbbaa04abbe96ccdc120f8ec
refs/heads/main
2023-03-01T00:38:10.354998
2021-02-10T08:12:48
2021-02-10T08:12:48
337,657,019
1
0
null
null
null
null
UHC
C++
false
false
681
h
// Prototype.h : PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다. // #pragma once #ifndef __AFXWIN_H__ #error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다." #endif #include "resource.h" // 주 기호입니다. // CAudioApp: // 이 클래스의 구현에 대해서는 Audio.cpp을 참조하십시오. // class CAudioApp : public CWinApp { public: CAudioApp(); ULONG_PTR m_gditoken; //GDI+ 객체 GdiplusStartupInput gpsi; //GDI+ 객체 // 재정의입니다. public: virtual BOOL InitInstance(); // 구현입니다. DECLARE_MESSAGE_MAP() virtual int ExitInstance(); }; extern CAudioApp theApp;
5232b9a2a12dbfaa52334c8bac040f055a1252fc
dcec9c2353abd339b42ca7b2d2c799dc7135624c
/BinaryGenerator/bgSymbol.h
83cc589d7145dd9f6eeb75e2062a46220a93a5dd
[]
no_license
gitmesam/BinaryGenerator
2fe5f878b93aa9ddf36e382c6326719a22cea29e
cec4a2316e368bf052c267be5be9a998f8b3333e
refs/heads/master
2022-01-20T22:56:44.818991
2019-05-10T02:29:40
2019-05-10T02:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
#pragma once namespace bg { class SymbolTable { public: using Symbols = std::vector<Symbol>; public: SymbolTable(Context *ctx); SymbolTable(Context *ctx, const SymbolTable& base); Symbols& getSymbols(); Symbol& addSymbol(const Symbol& sym); Symbol* getSymbol(size_t i); Symbol* findSymbol(const char *name); uint32 getVirtualAddress(const char *name); private: Context *m_ctx; Symbols m_symbols; }; } // namespace bg
431ff081938c8641e6dae688879a3a241a6cfd83
26df6604faf41197c9ced34c3df13839be6e74d4
/src/org/apache/poi/ss/usermodel/charts/LayoutMode.hpp
f7576880bb2756388e335833b7309e0dcb3648ff
[ "Apache-2.0" ]
permissive
pebble2015/cpoi
58b4b1e38a7769b13ccfb2973270d15d490de07f
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
refs/heads/master
2021-07-09T09:02:41.986901
2017-10-08T12:12:56
2017-10-08T12:12:56
105,988,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,582
hpp
// Generated from /POI/java/org/apache/poi/ss/usermodel/charts/LayoutMode.java #pragma once #include <java/io/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/ss/usermodel/charts/fwd-POI.hpp> #include <java/lang/Enum.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } // io namespace lang { typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::Enum, ObjectArray, ComparableArray, ::java::io::SerializableArray > EnumArray; } // lang } // java namespace poi { namespace ss { namespace usermodel { namespace charts { typedef ::SubArray< ::poi::ss::usermodel::charts::LayoutMode, ::java::lang::EnumArray > LayoutModeArray; } // charts } // usermodel } // ss } // poi struct default_init_tag; class poi::ss::usermodel::charts::LayoutMode final : public ::java::lang::Enum { public: typedef ::java::lang::Enum super; public: /* package */ static LayoutMode *EDGE; static LayoutMode *FACTOR; // Generated public: LayoutMode(::java::lang::String* name, int ordinal); protected: LayoutMode(const ::default_init_tag&); public: static ::java::lang::Class *class_(); static LayoutMode* valueOf(::java::lang::String* a0); static LayoutModeArray* values(); private: virtual ::java::lang::Class* getClass0(); };
0d6c1d26c5d7699510a3e323b31e4ccaf06ecb11
7a85beaae1b1de6594e595ad047a2c68f6c4971b
/qlo/objects/credit/latentmodels.hpp
905957039e208a0c91f219d297288e55a1538962
[]
no_license
benwaldner/QuantLibAddin
ed1acf80de15b000c3729c623dff1e45df21fa9f
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
refs/heads/master
2023-03-17T17:05:37.624063
2018-03-10T18:23:52
2018-03-10T18:23:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,197
hpp
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2014 Jose Aparicio This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #ifndef qla_latentmodels_hpp #define qla_latentmodels_hpp #include <rp/libraryobject.hpp> #include <ql/types.hpp> namespace QuantLib { template<class copulaPolicy> class DefaultLatentModel; struct GaussianCopulaPolicy; class TCopulaPolicy; typedef DefaultLatentModel<GaussianCopulaPolicy> GaussianDefProbLM; typedef DefaultLatentModel<TCopulaPolicy> TDefProbLM; class Basket; } namespace QuantLibAddin { /* \todo: This needs to be turn into a factory with a common ancestor and all the available options (integration policy etc) */ class GaussianDefProbLM : public reposit::LibraryObject<QuantLib::GaussianDefProbLM> { public: GaussianDefProbLM( const boost::shared_ptr<reposit::ValueObject>& properties, const boost::shared_ptr<QuantLib::Basket>& basket, const std::vector<std::vector<QuantLib::Real> >& factorWeights, bool permanent); }; class TDefProbLM : public reposit::LibraryObject<QuantLib::TDefProbLM> { public: TDefProbLM( const boost::shared_ptr<reposit::ValueObject>& properties, const std::vector<QuantLib::Integer>& tOrders, const boost::shared_ptr<QuantLib::Basket>& basket, const std::vector<std::vector<QuantLib::Real> >& factorWeights, bool permanent); }; } #endif
c5236df6c142ef8a86120f1c2008fd6bf0de6eae
fe39e4d1bca62d7bff7b6713b8b596d88f8aa354
/src/plugins/3rdparty/LLVM/tools/clang/include/clang/Basic/ObjCRuntime.h
a805299fd70a35e669b7fb4b17c32060d6acdb90
[]
no_license
panpanSun/opencor
a29a806475f43adb0f64047631d4dc044f05e030
71449e1ecaa988ea8b6cfea7875d9f3593a8dc26
refs/heads/master
2020-12-24T11:53:33.902565
2013-04-20T18:59:29
2013-04-20T18:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,739
h
//===--- ObjCRuntime.h - Objective-C Runtime Configuration ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines types useful for describing an Objective-C runtime. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_OBJCRUNTIME_H #define LLVM_CLANG_OBJCRUNTIME_H #include "clang/Basic/VersionTuple.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/ErrorHandling.h" namespace clang { /// \brief The basic abstraction for the target Objective-C runtime. class ObjCRuntime { public: /// \brief The basic Objective-C runtimes that we know about. enum Kind { /// 'macosx' is the Apple-provided NeXT-derived runtime on Mac OS /// X platforms that use the non-fragile ABI; the version is a /// release of that OS. MacOSX, /// 'macosx-fragile' is the Apple-provided NeXT-derived runtime on /// Mac OS X platforms that use the fragile ABI; the version is a /// release of that OS. FragileMacOSX, /// 'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS /// simulator; it is always non-fragile. The version is a release /// version of iOS. iOS, /// 'gcc' is the Objective-C runtime shipped with GCC, implementing a /// fragile Objective-C ABI GCC, /// 'gnustep' is the modern non-fragile GNUstep runtime. GNUstep, /// 'objfw' is the Objective-C runtime included in ObjFW ObjFW }; private: Kind TheKind; VersionTuple Version; public: /// A bogus initialization of the runtime. ObjCRuntime() : TheKind(MacOSX) {} ObjCRuntime(Kind kind, const VersionTuple &version) : TheKind(kind), Version(version) {} void set(Kind kind, VersionTuple version) { TheKind = kind; Version = version; } Kind getKind() const { return TheKind; } const VersionTuple &getVersion() const { return Version; } /// \brief Does this runtime follow the set of implied behaviors for a /// "non-fragile" ABI? bool isNonFragile() const { switch (getKind()) { case FragileMacOSX: return false; case GCC: return false; case MacOSX: return true; case GNUstep: return true; case ObjFW: return false; case iOS: return true; } llvm_unreachable("bad kind"); } /// The inverse of isNonFragile(): does this runtime follow the set of /// implied behaviors for a "fragile" ABI? bool isFragile() const { return !isNonFragile(); } /// The default dispatch mechanism to use for the specified architecture bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch) { // The GNUstep runtime uses a newer dispatch method by default from // version 1.6 onwards if (getKind() == GNUstep && getVersion() >= VersionTuple(1, 6)) { if (Arch == llvm::Triple::arm || Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) return false; // Mac runtimes use legacy dispatch everywhere except x86-64 } else if (isNeXTFamily() && isNonFragile()) return Arch != llvm::Triple::x86_64; return true; } /// \brief Is this runtime basically of the GNUstep family of runtimes? bool isGNUFamily() const { switch (getKind()) { case FragileMacOSX: case MacOSX: case iOS: return false; case GCC: case GNUstep: case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Is this runtime basically of the NeXT family of runtimes? bool isNeXTFamily() const { // For now, this is just the inverse of isGNUFamily(), but that's // not inherently true. return !isGNUFamily(); } /// \brief Does this runtime allow ARC at all? bool allowsARC() const { switch (getKind()) { case FragileMacOSX: return false; case MacOSX: return true; case iOS: return true; case GCC: return false; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime natively provide the ARC entrypoints? /// /// ARC cannot be directly supported on a platform that does not provide /// these entrypoints, although it may be supportable via a stub /// library. bool hasNativeARC() const { switch (getKind()) { case FragileMacOSX: return false; case MacOSX: return getVersion() >= VersionTuple(10, 7); case iOS: return getVersion() >= VersionTuple(5); case GCC: return false; case GNUstep: return getVersion() >= VersionTuple(1, 6); case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime supports optimized setter entrypoints? bool hasOptimizedSetter() const { switch (getKind()) { case MacOSX: return getVersion() >= VersionTuple(10, 8); case iOS: return (getVersion() >= VersionTuple(6)); default: return false; } } /// Does this runtime allow the use of __weak? bool allowsWeak() const { return hasNativeWeak(); } /// \brief Does this runtime natively provide ARC-compliant 'weak' /// entrypoints? bool hasNativeWeak() const { // Right now, this is always equivalent to whether the runtime // natively supports ARC decision. return hasNativeARC(); } /// \brief Does this runtime directly support the subscripting methods? /// /// This is really a property of the library, not the runtime. bool hasSubscripting() const { switch (getKind()) { case FragileMacOSX: return false; case MacOSX: return getVersion() >= VersionTuple(10, 8); case iOS: return getVersion() >= VersionTuple(6); // This is really a lie, because some implementations and versions // of the runtime do not support ARC. Probably -fgnu-runtime // should imply a "maximal" runtime or something? case GCC: return true; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime allow sizeof or alignof on object types? bool allowsSizeofAlignof() const { return isFragile(); } /// \brief Does this runtime allow pointer arithmetic on objects? /// /// This covers +, -, ++, --, and (if isSubscriptPointerArithmetic() /// yields true) []. bool allowsPointerArithmetic() const { switch (getKind()) { case FragileMacOSX: case GCC: return true; case MacOSX: case iOS: case GNUstep: case ObjFW: return false; } llvm_unreachable("bad kind"); } /// \brief Is subscripting pointer arithmetic? bool isSubscriptPointerArithmetic() const { return allowsPointerArithmetic(); } /// \brief Does this runtime provide an objc_terminate function? /// /// This is used in handlers for exceptions during the unwind process; /// without it, abort() must be used in pure ObjC files. bool hasTerminate() const { switch (getKind()) { case FragileMacOSX: return getVersion() >= VersionTuple(10, 8); case MacOSX: return getVersion() >= VersionTuple(10, 8); case iOS: return getVersion() >= VersionTuple(5); case GCC: return false; case GNUstep: return false; case ObjFW: return false; } llvm_unreachable("bad kind"); } /// \brief Does this runtime support weakly importing classes? bool hasWeakClassImport() const { switch (getKind()) { case MacOSX: return true; case iOS: return true; case FragileMacOSX: return false; case GCC: return true; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime use zero-cost exceptions? bool hasUnwindExceptions() const { switch (getKind()) { case MacOSX: return true; case iOS: return true; case FragileMacOSX: return false; case GCC: return true; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Try to parse an Objective-C runtime specification from the given /// string. /// /// \return true on error. bool tryParse(StringRef input); std::string getAsString() const; friend bool operator==(const ObjCRuntime &left, const ObjCRuntime &right) { return left.getKind() == right.getKind() && left.getVersion() == right.getVersion(); } friend bool operator!=(const ObjCRuntime &left, const ObjCRuntime &right) { return !(left == right); } }; raw_ostream &operator<<(raw_ostream &out, const ObjCRuntime &value); } // end namespace clang #endif
5c4094a13025c1386e27ef8cd55d813003e90afd
a60ff43808d79e528b76f62ad44598827cb95d60
/cameronet.h
6e3b0fc0727e0f8824c42559236e13cce60dc24d
[]
no_license
yyyly/cameronet
93f1f8ce2f1f29677aa449b2c663ba884aa6d14f
c400cd55a0a0caec83b3d6649180367ff1792bac
refs/heads/master
2020-12-02T13:07:05.931854
2020-08-22T02:27:15
2020-08-22T02:27:15
231,015,624
0
0
null
null
null
null
UTF-8
C++
false
false
3,190
h
#ifndef CAMERONET_H #define CAMERONET_H #include<QObject> #include<QWidget> #include<QMultiMap> #include<QThread> #include<QMap> #include "HCNetSDK.h" #include "cameronet_global.h" #include "enums.h" #include "cameradeviceimf.h" #include "screen.h" #include "soundpushbutton.h" #include "dhnetsdk.h" #include "dhwork.h" #include "dummy.h" class CAMERONETSHARED_EXPORT CameroNet : public QObject { Q_OBJECT private: explicit CameroNet(QObject *p =nullptr); public: static CameroNet* getInstance() { static CameroNet * instance; if(instance == nullptr) { instance = new CameroNet(); } return instance; } ~CameroNet(); public slots: /*登陆函数*/ void login(CameraDeviceImf &i); /*播放函数,默认采用主码流,TCP连接方式*/ LLONG realPlay(CameraDeviceImf *info, LONG channel, Screen &screen); /*停止播放,函数的错误信息留给调用模块处理*/ DWORD stopPlay(CameraDeviceImf &info, Screen *screen); DWORD stopPlay(LONG realHandle); /*登出,函数的错误信息留给调用模块处理*/ DWORD loginOut(CameraDeviceImf *info); /*抓图函数*/ DWORD capPic(CameraDeviceImf &info); /*声音控制函数*/ DWORD changeSoundState(CameraDeviceImf& info,SoundCommond c); DWORD opendSound(CameraDeviceImf *info); DWORD closeSound(CameraDeviceImf *info); /*只录像,不播放*/ LONG recordVedio(CameraDeviceImf *info,LONG channel,QString *fileName,Screen *screen = nullptr); /*云台控制*/ bool PtzControl(CameraDeviceImf &info,Camero::PTZcommond c,int start,int step = 4,int channal = 1);//start = 1 开始,start = 0,结束 //DH private slots: void dhLoginResut(const CameraDeviceImf& info,int state,int err); signals: void signalDeviceStatusChanged(CameraDeviceImf* camero,Camero::LineState state); void dhLogin(const CameraDeviceImf* imf); protected: bool event(QEvent *event); private: static QMap<LONG,QString> fileNameMap; //HK static void CALLBACK hkLoginResutCallback(LONG lUserID,DWORD dwResult, LPNET_DVR_DEVICEINFO_V30 lpDeviceInfo,void *pUser); static void CALLBACK g_RealDataCallBack_V30(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer,DWORD dwBufSize,void* dwUser); static void CALLBACK fExceptionCallBack(DWORD dwType,LONG lUserID, LONG lHandle,void *pUser); //DH static void CALLBACK autoConnectFunc(LONG lLoginID,char *pchDVRIP,LONG nDVRPort,DWORD dwUser); static void CALLBACK fDisConnect( LLONG lLoginID,char *pchDVRIP,LONG nDVRPort,LDWORD dwUser);//设备断线回调函数 static QList<CameraDeviceImf *> HKPinfoList;//存储登陆信息,析构函数使用 static QMap<LLONG,CameraDeviceImf *> pImfByUserIdMap; static QMultiMap<LONG,Screen *> pScreenByUserMap; //DH static QMap<LLONG,CameraDeviceImf *> dhImfByUserIdMap; static void CALLBACK fRealDataCallBack( LLONG lRealHandle,DWORD dwDataType, BYTE *pBuffer, DWORD dwBufsize, LDWORD dwUser); }; #endif // CAMERONET_H
ac61d2aca10a0598fe477cdd2e358a0aa079435c
cf167ca0058324dff74cf35ad3143d169859a3b5
/chat1/EasyChatRoom/TcpServer/tcpclientsocket.cpp
c60bda4b5c7e1943a0ad91a8656f030e88aa032e
[]
no_license
Evan05300/test
efe70166b82c4871d27bc2af5224616036e4a6b2
b0db0f0737125fabdfc63c6b1c4e01c3fb03f254
refs/heads/master
2023-05-12T11:35:07.389069
2021-06-07T07:02:20
2021-06-07T07:02:20
374,554,172
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
#include "tcpclientsocket.h" TcpClientSocket::TcpClientSocket(QObject *parent) { connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived()));//接收信号 connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected())); } //接收客户端消息 void TcpClientSocket::dataReceived() { while(bytesAvailable()>0) { int length = bytesAvailable(); char buf[1024]; read(buf,length); QString msg=buf; emit updateClients(msg,length);//发送客户端更新信号 } } void TcpClientSocket::slotDisconnected() { emit disconnected(this->socketDescriptor());//发送断开连接信号 }
ec1d5dd0100a851fbaab0c99e39e0573ae5b9620
d44b3e1503b6cb241e2f738188feec91d74b3432
/src/demux.h
589d1df172b05a3228fe035e1b9275bcff1c1179
[]
no_license
notspiff/pvr.mythtv
4e9399dd8fd660aa8369b84c0b91276aa5787318
cf6899c4b195a1fa24872f13629eb4221db1e224
refs/heads/master
2021-01-01T15:25:14.246232
2014-12-07T15:29:50
2014-12-07T15:29:50
22,757,479
0
1
null
2014-12-07T15:29:50
2014-08-08T12:46:37
C++
UTF-8
C++
false
false
2,986
h
#pragma once /* * Copyright (C) 2005-2013 Team XBMC * http://www.xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * http://www.gnu.org/copyleft/gpl.html * */ #include "demuxer/tsDemuxer.h" #include "client.h" #include <mythstream.h> #include <kodi/threads/threads.h> #include <kodi/threads/mutex.h> #include <kodi/util/buffer.h> #include <kodi/xbmc_stream_utils.hpp> #include <map> #include <set> #define AV_BUFFER_SIZE 131072 class Demux : public TSDemuxer, PLATFORM::CThread { public: Demux(Myth::Stream *file); ~Demux(); const unsigned char* ReadAV(uint64_t pos, size_t n); void* Process(); bool GetStreamProperties(PVR_STREAM_PROPERTIES* props); void Flush(); void Abort(); DemuxPacket* Read(); bool SeekTime(int time, bool backwards, double* startpts); int GetPlayingTime(); private: Myth::Stream *m_file; uint16_t m_channel; PLATFORM::SyncedBuffer<DemuxPacket*> m_demuxPacketBuffer; PLATFORM::CMutex m_mutex; ADDON::XbmcStreamProperties m_streams; bool get_stream_data(ElementaryStream::STREAM_PKT* pkt); void reset_posmap(); // PVR interfaces void populate_pvr_streams(); bool update_pvr_stream(uint16_t pid); void push_stream_change(); DemuxPacket* stream_pvr_data(ElementaryStream::STREAM_PKT* pkt); void push_stream_data(DemuxPacket* dxp); // AV raw buffer size_t m_av_buf_size; ///< size of av buffer uint64_t m_av_pos; ///< absolute position in av unsigned char* m_av_buf; ///< buffer unsigned char* m_av_rbs; ///< raw data start in buffer unsigned char* m_av_rbe; ///< raw data end in buffer // Playback context AVContext* m_AVContext; uint16_t m_mainStreamPID; ///< PID of main stream uint64_t m_DTS; ///< absolute decode time of main stream uint64_t m_PTS; ///< absolute presentation time of main stream int64_t m_pinTime; ///< pinned relative position (90Khz) int64_t m_curTime; ///< current relative position (90Khz) int64_t m_endTime; ///< last relative marked position (90Khz)) typedef struct { uint64_t av_pts; uint64_t av_pos; } AV_POSMAP_ITEM; std::map<int64_t, AV_POSMAP_ITEM> m_posmap; bool m_isChangePlaced; std::set<uint16_t> m_nosetup; };
c6639cb1eee991788c32993886d3aa13bfd03a3e
5a6518cf9301fffaea32bc2d8e1adb84bb958f32
/components/certificate_transparency/ct_policy_manager_unittest.cc
82573f8dd0f0586857e22195160ab054a0b7eb01
[ "BSD-3-Clause" ]
permissive
srashtisj/chromium
0dbfd3f00836723e1f142511279c11dc4f9a2137
e72eabf20722d616feb232776b95cc7f051a2aa3
refs/heads/master
2023-01-06T14:03:40.313390
2018-04-05T12:43:54
2018-04-05T12:43:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,499
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/certificate_transparency/ct_policy_manager.h" #include <iterator> #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/test/test_message_loop.h" #include "base/values.h" #include "components/certificate_transparency/pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" #include "net/base/hash_value.h" #include "net/cert/x509_certificate.h" #include "net/cert/x509_util.h" #include "net/test/cert_test_util.h" #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" namespace certificate_transparency { namespace { std::unique_ptr<base::ListValue> ListValueFromStrings( const std::vector<const char*>& strings) { std::unique_ptr<base::ListValue> result(new base::ListValue); for (auto* const str : strings) { result->AppendString(str); } return result; } class CTPolicyManagerTest : public ::testing::Test { public: CTPolicyManagerTest() : message_loop_(base::MessageLoop::TYPE_IO) {} void SetUp() override { cert_ = net::CreateCertificateChainFromFile( net::GetTestCertsDirectory(), "ok_cert.pem", net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE); ASSERT_TRUE(cert_); hashes_.push_back(net::HashValue( net::X509Certificate::CalculateFingerprint256(cert_->cert_buffer()))); } protected: base::TestMessageLoop message_loop_; TestingPrefServiceSimple pref_service_; scoped_refptr<net::X509Certificate> cert_; net::HashValueVector hashes_; }; // Treat the preferences as a black box as far as naming, but ensure that // preferences get registered. TEST_F(CTPolicyManagerTest, RegistersPrefs) { auto registered_prefs = std::distance(pref_service_.registry()->begin(), pref_service_.registry()->end()); CTPolicyManager::RegisterPrefs(pref_service_.registry()); auto newly_registered_prefs = std::distance(pref_service_.registry()->begin(), pref_service_.registry()->end()); EXPECT_NE(registered_prefs, newly_registered_prefs); } TEST_F(CTPolicyManagerTest, DelegateChecksRequired) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set a preference, pump the message loop, and ensure things are now // reflected. pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{"google.com"})); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); } TEST_F(CTPolicyManagerTest, DelegateChecksExcluded) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set a preference, pump the message loop, and ensure things are now // reflected. pref_service_.SetManagedPref( prefs::kCTExcludedHosts, ListValueFromStrings(std::vector<const char*>{"google.com"})); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); } TEST_F(CTPolicyManagerTest, IgnoresInvalidEntries) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now setup invalid preferences (that is, that fail to be parsable as // URLs). pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{ "file:///etc/fstab", "file://withahost/etc/fstab", "file:///c|/Windows", "*", "https://*", "example.com", "https://example.test:invalid_port", })); base::RunLoop().RunUntilIdle(); // Wildcards are ignored (both * and https://*). EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // File URL hosts are ignored. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("withahost", cert_.get(), hashes_)); // While the partially parsed hosts should take effect. EXPECT_EQ( CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("example.test", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); } // Make sure the various 'undocumented' priorities apply: // - non-wildcards beat wildcards // - more specific hosts beat less specific hosts // - requiring beats excluding TEST_F(CTPolicyManagerTest, AppliesPriority) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("login.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("login.sub.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("test.example.com", cert_.get(), hashes_)); // Set up policies that exclude it for a domain and all of its subdomains, // but then require it for a specific host. pref_service_.SetManagedPref( prefs::kCTExcludedHosts, ListValueFromStrings(std::vector<const char*>{ "example.com", ".sub.example.com", ".sub.accounts.example.com", "test.example.com"})); pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{ "sub.example.com", "accounts.example.com", "test.example.com"})); base::RunLoop().RunUntilIdle(); EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); // Non-wildcarding (.sub.example.com) beats wildcarding (sub.example.com). EXPECT_EQ( CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); // More specific hosts (accounts.example.com) beat less specific hosts // (example.com + wildcard). EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("accounts.example.com", cert_.get(), hashes_)); // More specific hosts (accounts.example.com) beat less specific hosts // (example.com). EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("login.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("sub.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("login.sub.accounts.example.com", cert_.get(), hashes_)); // Requiring beats excluding. EXPECT_EQ( CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("test.example.com", cert_.get(), hashes_)); } // Ensure that the RequireCTDelegate is still valid and usable after Shutdown // has been called. Preferences should no longer sync, but the old results // should still be returned. TEST_F(CTPolicyManagerTest, UsableAfterShutdown) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set a preference, pump the message loop, and ensure things are now // reflected. pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{"google.com"})); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Shut down the preferences, which should unregister any observers. manager.Shutdown(); base::RunLoop().RunUntilIdle(); // Update the preferences again, which should do nothing; the // RequireCTDelegate should continue to be valid and return the old results. EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{"sub.example.com"})); base::RunLoop().RunUntilIdle(); EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); // And it should still be possible to get the delegate, even after calling // Shutdown(). EXPECT_TRUE(manager.GetDelegate()); } TEST_F(CTPolicyManagerTest, SupportsOrgRestrictions) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); base::FilePath test_directory = net::GetTestNetDataDirectory().Append( FILE_PATH_LITERAL("ov_name_constraints")); // As all the leaves and intermediates share SPKIs in their classes, load // known-good answers for the remaining test config. scoped_refptr<net::X509Certificate> tmp = net::ImportCertFromFile(test_directory, "leaf-o1.pem"); ASSERT_TRUE(tmp); net::HashValue leaf_spki; ASSERT_TRUE( net::x509_util::CalculateSha256SpkiHash(tmp->cert_buffer(), &leaf_spki)); tmp = net::ImportCertFromFile(test_directory, "int-o3.pem"); ASSERT_TRUE(tmp); net::HashValue intermediate_spki; ASSERT_TRUE(net::x509_util::CalculateSha256SpkiHash(tmp->cert_buffer(), &intermediate_spki)); struct { const char* const leaf_file; const char* const intermediate_file; const net::HashValue spki; CTRequirementLevel expected; } kTestCases[] = { // Positive cases // // Exact match on the leaf SPKI (leaf has O) {"leaf-o1.pem", nullptr, leaf_spki, CTRequirementLevel::NOT_REQUIRED}, // Exact match on the leaf SPKI (leaf does not have O) {"leaf-no-o.pem", nullptr, leaf_spki, CTRequirementLevel::NOT_REQUIRED}, // Exact match on the leaf SPKI (leaf has O), even when the // intermediate does not {"leaf-o1.pem", "int-cn.pem", leaf_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches (multiple) organization values in two SEQUENCEs+SETs {"leaf-o1-o2.pem", "int-o1-o2.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches (multiple) organization values in a single SEQUENCE+SET {"leaf-o1-o2.pem", "int-o1-plus-o2.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches nameConstrained O {"leaf-o1.pem", "nc-int-permit-o1.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches the second nameConstraint on the O, out of 3 {"leaf-o1.pem", "nc-int-permit-o2-o1-o3.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Leaf is in different string type than issuer (BMPString), but it is // in the issuer O field, not the nameConstraint // TODO(rsleevi): Make this fail, because it's not byte-for-byte // identical {"leaf-o1.pem", "int-bmp-o1.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Negative cases // Leaf is missing O {"leaf-no-o.pem", "int-o1-o2.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Leaf is missing O {"leaf-no-o.pem", "int-cn.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Leaf doesn't match issuer O {"leaf-o1.pem", "int-o3.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Multiple identical organization values, but in different orders. {"leaf-o1-o2.pem", "int-o2-o1.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, with a dirName, but not an O {"leaf-o1.pem", "nc-int-permit-cn.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, but with a dNSName {"leaf-o1.pem", "nc-int-permit-dns.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, but with an excludedSubtrees that // has a dirName that matches the O. {"leaf-o1.pem", "nc-int-exclude-o1.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, but the encoding of the // nameConstraint is different from the encoding of the leaf {"leaf-o1.pem", "nc-int-permit-bmp-o1.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, }; for (const auto& test : kTestCases) { SCOPED_TRACE(::testing::Message() << "leaf=" << test.leaf_file << ",intermediate=" << test.intermediate_file); scoped_refptr<net::X509Certificate> leaf = net::ImportCertFromFile(test_directory, test.leaf_file); ASSERT_TRUE(leaf); net::HashValueVector hashes; net::HashValue leaf_hash; ASSERT_TRUE(net::x509_util::CalculateSha256SpkiHash(leaf->cert_buffer(), &leaf_hash)); hashes.push_back(std::move(leaf_hash)); // Append the intermediate to |leaf|, if any. if (test.intermediate_file) { scoped_refptr<net::X509Certificate> intermediate = net::ImportCertFromFile(test_directory, test.intermediate_file); ASSERT_TRUE(intermediate); net::HashValue intermediate_hash; ASSERT_TRUE(net::x509_util::CalculateSha256SpkiHash( intermediate->cert_buffer(), &intermediate_hash)); hashes.push_back(std::move(intermediate_hash)); std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates; intermediates.push_back( net::x509_util::DupCryptoBuffer(intermediate->cert_buffer())); leaf = net::X509Certificate::CreateFromBuffer( net::x509_util::DupCryptoBuffer(leaf->cert_buffer()), std::move(intermediates)); } std::unique_ptr<base::ListValue> excluded_spkis = std::make_unique<base::ListValue>(); pref_service_.SetManagedPref(prefs::kCTExcludedSPKIs, std::move(excluded_spkis)); base::RunLoop().RunUntilIdle(); // There should be no existing settings. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", leaf.get(), hashes)); // Update the preference excluded_spkis = std::make_unique<base::ListValue>(); excluded_spkis->AppendString(test.spki.ToString()); pref_service_.SetManagedPref(prefs::kCTExcludedSPKIs, std::move(excluded_spkis)); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(test.expected, delegate->IsCTRequiredForHost("google.com", leaf.get(), hashes)); } } TEST_F(CTPolicyManagerTest, SupportsLegacyCaRestrictions) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // The hash of a known legacy CA. See // //net/cert/root_cert_list_generated.h net::SHA256HashValue legacy_spki = {{ 0x00, 0x6C, 0xB2, 0x26, 0xA7, 0x72, 0xC7, 0x18, 0x2D, 0x77, 0x72, 0x38, 0x3E, 0x37, 0x3F, 0x0F, 0x22, 0x9E, 0x7D, 0xFE, 0x34, 0x44, 0x81, 0x0A, 0x8D, 0x6E, 0x50, 0x90, 0x5D, 0x20, 0xD6, 0x61, }}; hashes_.push_back(net::HashValue(legacy_spki)); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Setting a preference to a non-legacy CA should not work. std::string leaf_hash_string = hashes_.front().ToString(); pref_service_.SetManagedPref( prefs::kCTExcludedLegacySPKIs, ListValueFromStrings(std::vector<const char*>{leaf_hash_string.c_str()})); base::RunLoop().RunUntilIdle(); // The new preference should have no effect, because the hash for |cert_| // is not a legacy CA hash. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set the preference to a truly legacy CA, and create a chain that // contains that legacy CA hash. std::string legacy_ca_hash_string = hashes_.back().ToString(); pref_service_.SetManagedPref(prefs::kCTExcludedLegacySPKIs, ListValueFromStrings(std::vector<const char*>{ legacy_ca_hash_string.c_str()})); base::RunLoop().RunUntilIdle(); EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); } } // namespace } // namespace certificate_transparency
67598b9a309d261a8f0b418b6ae4cc923c326649
033c1fe882eb426a21b7b45aefae4f0aa59fe57e
/算法导论/CH02/Problem/pb_2_2__冒泡排序.cpp
7cb2e752b8c20910387bd5106d54c934618e9de8
[]
no_license
CN-DXTZ/CLRS
e30b128a8404c0588baf366a06108491a3ee0e5a
dfde7f25766d1cc81c2bc7f9a1d818fcb17d0766
refs/heads/master
2023-04-16T02:57:10.703923
2023-04-11T01:26:10
2023-04-11T01:26:10
196,676,637
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
// 冒泡排序 #include <iostream> using namespace std; #define GET_LEN(array) (sizeof(array) / sizeof(array[0])) void bubble_sort(int A[], int length) { for (int i = 0; i < length; i++) { for (int j = length-1; j > i; j--) { if (A[j] < A[j - 1]) { int tmp = A[j]; A[j] = A[j - 1]; A[j - 1] = tmp; } } } } int main() { int A[] = {5, 2, 4, 7, 1, 3, 2, 6}; int length = GET_LEN(A); bubble_sort(A, length); for (int i = 0; i < length; i++) cout << A[i] << endl; return 0; }
21816a20e0f94d8b0329ba886aa6d1b2c56effd5
ab570cfbba5d90e73727dca01008e43029a42eae
/bonus6.cpp
78bf05e380abbe8bf02ab8139a613c6c7f6f5ba7
[]
no_license
rileym65/Casino
3adfbdf4501f0c55191c031a0ffe3615b30b8cfc
6b73002fdfebbda9ca490774b941f561cb73a049
refs/heads/master
2020-08-08T22:08:40.508213
2019-10-09T13:49:34
2019-10-09T13:49:34
213,931,230
0
0
null
null
null
null
UTF-8
C++
false
false
29,136
cpp
#include <stdlib.h> #include "header.h" #include "poker.h" #include "bonus6.h" #ifdef GRAPHIC #include "images/bonus6.xpm" #endif Bonus6::Bonus6(int decks,int jokers,float minbet): Poker(decks,jokers,minbet) { betAmount=1; } void Bonus6::clearBets(int p) { #ifdef GRAPHIC rcs_GC gc; gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"black"); rcs_copyArea(display,table,mainScreen,gc,playerBetX(p)-80,playerBetY(p)-90, 140,217,playerBetX(p)-80,playerBetY(p)-90); rcs_closeGC(display,gc); #endif } int Bonus6::playerX(int p) { #ifdef GRAPHIC switch (p) { case 0:return 9; case 1:return 166; case 2:return 334; case 3:return 504; case 4:return 662; case 99:return 360; } #endif #ifdef CONSOLE switch (p) { case 0:return 60; case 1:return 60; case 2:return 30; case 3:return 1; case 4:return 1; case 99:return 30; } #endif return 325; } int Bonus6::playerY(int p) { #ifdef GRAPHIC switch (p) { case 0:return 464; case 1:return 488; case 2:return 509; case 3:return 488; case 4:return 464; case 99:return 21; } #endif #ifdef CONSOLE switch (p) { case 0:return 3; case 1:return 14; case 2:return 17; case 3:return 14; case 4:return 3; case 99:return 5; } #endif return 21; } int Bonus6::playerBetX(int p) { #ifdef GRAPHIC switch (p) { case 0:return 82; case 1:return 239; case 2:return 408; case 3:return 579; case 4:return 736; case 99:return 33; } #endif #ifdef CONSOLE switch (p) { case 0:return 63; case 1:return 63; case 2:return 33; case 3:return 4; case 4:return 4; case 99:return 33; } #endif return 33; } int Bonus6::playerBetY(int p) { #ifdef GRAPHIC switch (p) { case 0:return 213; case 1:return 240; case 2:return 262; case 3:return 240; case 4:return 213; case 99:return 5; case 98:return 8; } #endif #ifdef CONSOLE switch (p) { case 0:return 2; case 1:return 13; case 2:return 16; case 3:return 13; case 4:return 2; case 99:return 5; case 98:return 8; } #endif return 5; } void Bonus6::showBetAmount() { rcs_GC gc; rcs_Font font; char buffer[80]; gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"darkgreen"); rcs_drawFilledBox(display,mainScreen,gc,377,565,99,32); rcs_namedForeground(display,gc,"yellow"); font=rcs_openFont(display,BET_FONT); rcs_setFont(display,gc,font); sprintf(buffer,"$%ld",betAmount); rcs_drawString(display,mainScreen,gc,385,586,buffer); rcs_closeFont(display,font); rcs_closeGC(display,gc); displayScreen(); } void Bonus6::showPlayers() { int i; #ifdef GRAPHIC rcs_GC gc; rcs_Font font; #endif for (i=0;i<PLAYERS_DSTUD;i++) if (players[i]!=NULL) { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); font=rcs_openFont(display,PLAYER_FONT); rcs_setFont(display,gc,font); rcs_namedForeground(display,gc,"darkgreen"); rcs_drawFilledBox(display,mainScreen,gc,playerX(i),playerY(i),125,40); rcs_namedForeground(display,gc,"yellow"); rcs_drawString(display,mainScreen,gc,playerX(i),playerY(i), players[i]->getName()); sprintf(buffer,"Money $%12.2f",players[i]->money()); rcs_drawString(display,mainScreen,gc,playerX(i),playerY(i)+20,buffer); rcs_closeFont(display,font); rcs_closeGC(display,gc); #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)); Output(players[i]->getName()); GotoXY(playerX(i),playerY(i)+1); Output("Money $"); sprintf(buffer,"%12.2f",players[i]->money()); Output(buffer); GotoXY(playerX(i),playerY(i)+2); Output("Comm: $"); sprintf(buffer,"%12.2f",comms[i]); Output(buffer); #endif } #ifdef GRAPHIC displayScreen(); #endif } float Bonus6::placeBet(int player) { float betReturn; char flag; char betFlags; #ifdef GRAPHIC rcs_Event event; rcs_GC gc; rcs_Font font; betFlags=0; gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"gray"); rcs_drawFilledBox(display,mainScreen,gc,10,566,80,29); rcs_namedForeground(display,gc,"black"); rcs_drawBox(display,mainScreen,gc,12,568,76,25); font=rcs_openFont(display,BET_FONT); rcs_setFont(display,gc,font); rcs_drawString(display,mainScreen,gc,32,587,"Exit"); rcs_namedForeground(display,gc,"gray"); rcs_drawFilledBox(display,mainScreen,gc,210,566,80,29); rcs_namedForeground(display,gc,"black"); rcs_drawBox(display,mainScreen,gc,212,568,76,25); rcs_drawString(display,mainScreen,gc,232,587,"Play"); rcs_closeFont(display,font); rcs_closeGC(display,gc); displayScreen(); flag=' '; while (flag==' ') { event=getEvent(display); switch(event.type) { case EVENT_BUTTON_PRESS: if (event.d1 == 1 && event.d3>=566 && event.d3<=598) { if (event.d1 == 1 && event.d2>=210 && event.d2<=290) { flag='P'; } if (event.d1 == 1 && event.d2>=10 && event.d2<=90) { flag='X'; betFlags=0; } if (event.d2>=490 && event.d2<516) { betAmount+=1; showBetAmount(); } if (event.d2>=522 && event.d2<546) { betAmount+=5; showBetAmount(); } if (event.d2>=553 && event.d2<578) { betAmount+=10; showBetAmount(); } if (event.d2>=584 && event.d2<609) { betAmount+=25; showBetAmount(); } if (event.d2>=615 && event.d2<640) { betAmount+=50; showBetAmount(); } if (event.d2>=645 && event.d2<671) { betAmount+=100; showBetAmount(); } if (event.d2>=676 && event.d2<701) { betAmount+=500; showBetAmount(); } if (event.d2>=708 && event.d2<733) { betAmount+=1000; showBetAmount(); } if (event.d2>=739 && event.d2<765) { betAmount+=5000; showBetAmount(); } if (event.d2>=771 && event.d2<796) { betAmount+=10000; showBetAmount(); } } if (event.d1 == 3 && event.d3>=566 && event.d3<=598) { if (event.d2>=490 && event.d2<516) { betAmount-=1; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=522 && event.d2<546) { betAmount-=5; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=553 && event.d2<578) { betAmount-=10; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=584 && event.d2<609) { betAmount-=25; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=615 && event.d2<640) { betAmount-=50; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=645 && event.d2<671) { betAmount-=100; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=676 && event.d2<701) { betAmount-=500; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=708 && event.d2<733) { betAmount-=1000; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=739 && event.d2<765) { betAmount-=5000; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=771 && event.d2<796) { betAmount-=10000; if (betAmount<1) betAmount=1; showBetAmount(); } } if (event.d1 == 1 && (betFlags & 1) != 1 && event.d2>=playerBetX(player)-50 && event.d2<=playerBetX(player)+20 && event.d3>=playerBetY(player)-90 && event.d3<=playerBetY(player)-20 && (betAmount & 1) != 1) { betReturn=players[player]->placeBet(betAmount,0,playerBetX(player)-20,playerBetY(player)-50); betFlags |= 1; showPlayers(); players[i]->paintBets(); displayScreen(); if (betFlags == 3) flag='P'; } if (event.d1 == 1 && betFlags==1 && event.d2>=playerBetX(player)-80 && event.d2<=playerBetX(player)-10 && event.d3>=playerBetY(player)+50 && event.d3<=playerBetY(player)+120) { betReturn=players[player]->placeBet(players[player]->getHandBet(0)/2,3,playerBetX(player)-50,playerBetY(player)+85); betFlags |= 2; progressives[PROG_CARIB]+=.75; showPlayers(); players[i]->paintBets(); displayScreen(); if (betFlags == 3) flag='P'; } break; } } gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"darkgreen"); rcs_drawFilledBox(display,mainScreen,gc,10,566,80,29); rcs_drawFilledBox(display,mainScreen,gc,210,566,80,29); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+7); Output("Enter Bet :"); Input(buffer); sscanf(buffer,"%f",&bet); betReturn=players[i]->placeBet(bet,0,1,1); betReturn=players[i]->placeBet(bet,1,1,1); betReturn=players[i]->placeBet(bet,2,1,1); GotoXY(playerX(i),playerY(i)+7); Output(" "); GotoXY(playerX(i),playerY(i)+1); GotoXY(playerX(i),playerY(i)+7); Output("Tourn. Bet (y/n):"); Input(buffer); if (buffer[0]=='y') { betReturn=players[i]->placeBet(1,3,1,1); GotoXY(playerX(i)+17,playerY(i)+1); Output("*"); } GotoXY(playerX(i),playerY(i)+7); Output(" "); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f",bet,bet,bet); Output(buffer); #endif if (betFlags != 0) flag='P'; if (flag!='P' && flag!='D') return 0; else return betReturn; } void Bonus6::play() { float bet; float betReturn; #ifdef GRAPHIC rcs_GC gc; table=rcs_xpmToPixmap(display,mainWindow,bonus6_xpm); #endif bet=1; while (bet!=0) { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,0,0,800,600,0,0); rcs_closeGC(display,gc); showBetAmount(); displayScreen(); #endif #ifdef CONSOLE ClrScr(); #endif deck->shuffle(); for (i=0;i<5;i++) if (players[i]!=NULL) players[i]->clearAllBets(); showPlayers(); for (i=0;i<5;i++) if (players[i]!=NULL) { if (players[i]->playerType()=='H') { bet=placeBet(i); } else { betReturn=players[i]->placeBet(minBet,0,playerBetX(i)-20,playerBetY(i)-50); if (rcs_random(10)<4) betReturn=players[i]->placeBet(minBet/2,3,playerBetX(i)-50,playerBetY(i)+85); #ifdef CONSOLE GotoXY(playerX(i)+17,playerY(i)+1); Output("*"); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f",minBet,minBet,minBet); Output(buffer); #endif } #ifdef GRAPHIC showPlayers(); players[i]->paintBets(); displayScreen(); #endif #ifdef CONSOLE players[i]->showBets(); #endif } if (betReturn) ; if (bet!=0) { round(); } } #ifdef GRAPHIC rcs_closePixmap(display,table); #endif } void Bonus6::round() { int i,j; Card *c1,*c2,*c3,*c4; Card *communityCard; unsigned long high; // float betReturn; int folded[5]; Hand* pHand; #ifdef GRAPHIC rcs_GC gc; #endif for (i=0;i<PLAYERS_BONUS6;i++) folded[i]=0; for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL) players[i]->newHand(0); for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL) { for (j=0;j<2;j++) { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[j]->setPosition(playerX(i)+j*15,playerY(i)-120); } GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(0); #endif } else { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,3); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(3); #endif } Delay(1); } communityCard=deck->dealCard(); communityCard->setSide('F'); communityCard->setPosition(playerX(99),playerY(99)); gc=rcs_openGC(display,mainScreen); communityCard->paint(display,mainScreen,gc); rcs_closeGC(display,gc); displayScreen(); /* players[i]->newCard(deck->dealCard(),0); GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') players[i]->getHand(0)->display(0); else players[i]->getHand(0)->display(3); Delay(1); } */ #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(99),playerY(99)); #endif Delay(1); for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { if (players[i]->playerType()=='H') { #ifdef GRAPHIC if (actionBox(playerX(i),playerY(i),130,70,"Continue?","Yes","No")==0) { players[i]->placeBet(players[i]->getHandBet(0),1,playerBetX(i)-50,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } /* gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); */ #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+7); Output("Let it ride ? "); Input(buffer); if (buffer[0]=='N' || buffer[0]=='n') { players[i]->winHandBets(2,0); players[i]->loseHandBets(2); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0), players[i]->getHandBet(1),players[i]->getHandBet(2)); Output(buffer); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); } GotoXY(playerX(i),playerY(i)+7); Output(" "); #endif } else { pHand=players[i]->getHand(0); pHand->cards[2]=communityCard; pHand->numCards=3; c1=pHand->cards[0]; c2=pHand->cards[1]; high=pHand->pokerValue(5,0); pHand->numCards=2; pHand->cards[0]=c1; pHand->cards[1]=c2; if (high>PK_PAIR || (c1->getSuit()==c2->getSuit() && c2->getSuit()==communityCard->getSuit()) || (c1->value()>5 && c2->value()>5 && communityCard->value()>5) ) { players[i]->placeBet(players[i]->getHandBet(0),1,playerBetX(i)-50,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } } clearBets(i); #ifdef GRAPHIC showPlayers(); players[i]->paintBets(); displayScreen(); #endif Delay(1); } #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(99),playerY(99)); #endif Delay(1); /* ******************* Deal first card **************** */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[2]->setPosition(playerX(i)+2*15,playerY(i)-120); GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(0); #endif } else { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,4); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(3); #endif } Delay(1); } /* ***************** round 2 ************** */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { if (players[i]->playerType()=='H') { #ifdef GRAPHIC if (actionBox(playerX(i),playerY(i),130,70,"Continue?","Yes","No")==0) { players[i]->placeBet(players[i]->getHandBet(0),2,playerBetX(i)+20,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(1); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } /* gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); */ #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+7); Output("Let it ride ? "); Input(buffer); if (buffer[0]=='N' || buffer[0]=='n') { players[i]->winHandBets(2,0); players[i]->loseHandBets(2); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0), players[i]->getHandBet(1),players[i]->getHandBet(2)); Output(buffer); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); } GotoXY(playerX(i),playerY(i)+7); Output(" "); #endif } else { pHand=players[i]->getHand(0); pHand->cards[3]=communityCard; pHand->numCards=4; c1=pHand->cards[0]; c2=pHand->cards[1]; c3=pHand->cards[2]; high=pHand->pokerValue(5,0); pHand->numCards=3; pHand->cards[0]=c1; pHand->cards[1]=c2; pHand->cards[2]=c3; if (high>PK_PAIR || (c1->getSuit()==c2->getSuit() && c2->getSuit()==c3->getSuit() && c3->getSuit()==communityCard->getSuit()) || (abs((c1->value()>5)+(c2->value()>5)+(c3->value()>5)+ (communityCard->value()>5))>2) ) { players[i]->placeBet(players[i]->getHandBet(0),2,playerBetX(i)+20,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(1); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } } clearBets(i); #ifdef GRAPHIC showPlayers(); players[i]->paintBets(); displayScreen(); #endif Delay(1); } /* ******************* Deal Second card **************** */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[3]->setPosition(playerX(i)+3*15,playerY(i)-120); GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(0); #endif } else { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,5); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(3); #endif } Delay(1); } /* now check for 6th cards */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { pHand=players[i]->getHand(0); c1=pHand->cards[0]; c2=pHand->cards[1]; c3=pHand->cards[2]; c4=pHand->cards[3]; pHand->cards[pHand->numCards++]=communityCard; high=pHand->pokerValue(5,0); pHand->cards[0]=c1; pHand->cards[1]=c2; pHand->cards[2]=c3; pHand->cards[3]=c4; pHand->numCards--; if (high<(PK_PAIR|(6<<24)|(6<<16)) && players[i]->getHandBet(3)>0) { if (players[i]->playerType()=='H') { if (actionBox(playerX(i),playerY(i),130,70,"6th Card?","Yes","No")==0) { players[i]->placeBet(players[i]->getHandBet(0),4,playerBetX(i)+20,playerBetY(i)+85); players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[4]->setPosition(playerX(i)+4*15,playerY(i)-120); gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); players[i]->paintBets(); displayScreen(); Delay(1); } } else { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[4]->setPosition(playerX(i)+4*15,playerY(i)-120); gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); players[i]->paintBets(); displayScreen(); Delay(1); } } } #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(99),playerY(99)); #endif Delay(1); for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { pHand=players[i]->getHand(0); #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); pHand->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+3); pHand->display(0); #endif pHand->cards[pHand->numCards++]=communityCard; high=pHand->pokerValue(5,0); /* GotoXY(playerX(i),playerY(i)+4); printf(">%ld ",(high>>28)&15); printf("%ld ",(high>>24)&15); printf("%ld ",(high>>20)&15); printf("%ld ",(high>>16)&15); printf("%ld ",(high>>12)&15); printf("%ld ",(high>>8)&15); */ #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+2); #endif if (high>(PK_PAIR|(6<<24)) && high<PK_2_PAIR) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Pair"); #endif #ifdef CONSOLE Output("*Pair*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0), players[i]->getHandBet(1),players[i]->getHandBet(2)); Output(buffer); #endif players[i]->winHandBets(0,1); players[i]->winHandBets(1,1); players[i]->winHandBets(2,1); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_2_PAIR) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"2 Pair"); #endif #ifdef CONSOLE Output("*2 Pair*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*2, players[i]->getHandBet(1)*2,players[i]->getHandBet(2)*2); Output(buffer); #endif players[i]->winHandBets(0,2); players[i]->winHandBets(1,2); players[i]->winHandBets(2,2); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_THREE) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"3 of a kind"); #endif #ifdef CONSOLE Output("*3 of a kind*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*3, players[i]->getHandBet(1)*3,players[i]->getHandBet(2)*3); Output(buffer); #endif players[i]->winHandBets(0,3); players[i]->winHandBets(1,3); players[i]->winHandBets(2,3); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_STRAIGHT) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Straight"); #endif #ifdef CONSOLE Output("*Straight*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*5, players[i]->getHandBet(1)*5,players[i]->getHandBet(2)*5); Output(buffer); #endif players[i]->winHandBets(0,4); players[i]->winHandBets(1,4); players[i]->winHandBets(2,4); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_FLUSH) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Flush"); #endif #ifdef CONSOLE Output("*Flush*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*8, players[i]->getHandBet(1)*8,players[i]->getHandBet(2)*8); Output(buffer); #endif players[i]->winHandBets(0,6); players[i]->winHandBets(1,6); players[i]->winHandBets(2,6); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_FULLHOUSE) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Full House"); #endif #ifdef CONSOLE Output("*Full House*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*11, players[i]->getHandBet(1)*11,players[i]->getHandBet(2)*11); Output(buffer); #endif players[i]->winHandBets(0,20); players[i]->winHandBets(1,20); players[i]->winHandBets(2,20); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_FOUR) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"4 of a kind"); #endif #ifdef CONSOLE Output("*4 of a kind*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*50, players[i]->getHandBet(1)*50,players[i]->getHandBet(2)*50); Output(buffer); #endif players[i]->winHandBets(0,50); players[i]->winHandBets(1,50); players[i]->winHandBets(2,50); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_STFLUSH) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Straight Flush"); #endif #ifdef CONSOLE Output("*Straight Flush*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*200, players[i]->getHandBet(1)*200,players[i]->getHandBet(2)*200); Output(buffer); #endif players[i]->winHandBets(0,100); players[i]->winHandBets(1,100); players[i]->winHandBets(2,100); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_ROYAL) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Royal Flush"); #endif #ifdef CONSOLE Output("*Royal Flush*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*1000, players[i]->getHandBet(1)*1000,players[i]->getHandBet(2)*1000); Output(buffer); #endif players[i]->winHandBets(0,1000); players[i]->winHandBets(1,1000); players[i]->winHandBets(2,1000); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else { #ifdef CONSOLE Output("Game Over"); #endif players[i]->loseHandBets(0); players[i]->loseHandBets(1); players[i]->loseHandBets(2); players[i]->loseHandBets(3); players[i]->loseHandBets(4); players[i]->loseHandBets(5); } #ifdef GRAPHIC clearBets(i); players[i]->paintBets(); displayScreen(); showPlayers(); #endif #ifdef CONSOLE players[i]->showBets(); #endif Delay(1); } Delay(5); }
d7127e15eed5731c748aa028140f9f0605a1f879
3751d5701b0ec5fe8e2fe5e955aa278c3e53e87d
/GLProject_ModelNormalMap/GLProject_model/MyModel.cpp
4b3532ab1733a75c61b511aff5658d4572595bcb
[]
no_license
liuxuanhai/Cplus_Cplus_OpenGL_test
72fbe6d3a73fe7d7881490c5d76ae1d052ce0e0e
441f6d8043920dd44dc68704768ef6f62bae3924
refs/heads/master
2020-05-15T18:01:11.891474
2016-12-08T07:32:33
2016-12-08T07:32:33
null
0
0
null
null
null
null
GB18030
C++
false
false
9,117
cpp
#include "Utility.h" #include "MyCamera.h" #include "MyMesh.h" #include "MyModel.h" map<string, GLuint> CMyModel::m_textures; D_LIGHT CMyModel::directLight; CMyModel::CMyModel() { } CMyModel::~CMyModel() { } CMyModel::CMyModel(GLchar * _path) :m_dirty(true), m_matView(nullptr), m_matProjection(nullptr), m_scale(1.0f), m_position(0.0f) { Assimp::Importer importer; const aiScene * scene = importer.ReadFile(_path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { printf_s("Read model failed\n"); return; } m_directory = _path; m_directory = m_directory.substr(0, m_directory.find_last_of('/')); this->ProcessNode(scene, scene->mRootNode); int a = 1; } void CMyModel::SetCamera(CMyCamera * _camera) { m_camera = _camera; m_matView = _camera->GetView(); m_matProjection = _camera->GetProjection(); m_dirty = true; } void CMyModel::Update(GLfloat _dt) { if (m_dirty) { m_matModel = glm::mat4(); m_matModel = glm::translate(m_matModel, m_position); m_matModel = glm::rotate(m_matModel, glm::radians(m_degree), m_rotateAxis); m_matModel = glm::scale(m_matModel, m_scale); m_dirty = false; } } void CMyModel::Draw(GLuint _shaderProgram) { glUseProgram(_shaderProgram); glUniformMatrix4fv(glGetUniformLocation(_shaderProgram, "matModel"), 1, GL_FALSE, glm::value_ptr(m_matModel)); glUniformMatrix4fv(glGetUniformLocation(_shaderProgram, "matView"), 1, GL_FALSE, glm::value_ptr(*m_matView)); glUniformMatrix4fv(glGetUniformLocation(_shaderProgram, "matProjection"), 1, GL_FALSE, glm::value_ptr(*m_matProjection)); glUniform3fv(glGetUniformLocation(_shaderProgram, "viewPos"), 1, glm::value_ptr(*m_camera->GetPosition())); glUniform3fv(glGetUniformLocation(_shaderProgram, "lightDir"), 1, glm::value_ptr(m_lightDir)); //d light //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.lightDir"), 1, glm::value_ptr(directLight.direction)); //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.ambient"), 1, glm::value_ptr(directLight.ambient)); //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.diffuse"), 1, glm::value_ptr(directLight.diffuse)); //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.specular"), 1, glm::value_ptr(directLight.specular)); //glUniform1f(glGetUniformLocation(_shaderProgram, "shiniess"), 128); //pt light //char name[128] = {}; //for (int i = 0; i < m_ptLights.size(); ++i) //{ // //sprintf_s(name, sizeof(name), "ptLights[%d].lightPosition", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].position)); // //sprintf_s(name, sizeof(name), "ptLights[%d].ambient", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].ambient)); // //sprintf_s(name, sizeof(name), "ptLights[%d].diffuse", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].diffuse)); // //sprintf_s(name, sizeof(name), "ptLights[%d].specular", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].specular)); // //sprintf_s(name, sizeof(name), "ptLights[%d].constant", i); // //glUniform1f(glGetUniformLocation(_shaderProgram, name), m_ptLights[i].constant); // //sprintf_s(name, sizeof(name), "ptLights[%d].linear", i); // //glUniform1f(glGetUniformLocation(_shaderProgram, name), m_ptLights[i].linear); // //sprintf_s(name, sizeof(name), "ptLights[%d].quadratic", i); // //glUniform1f(glGetUniformLocation(_shaderProgram, name), m_ptLights[i].quadratic); //} ////Spot light ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.position") ,1, glm::value_ptr(*m_camera->GetPosition())); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.faceTo"), 1, glm::value_ptr(*m_camera->GetFaceTo())); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.ambient"), 1, glm::value_ptr(m_spotLight.ambient)); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.diffuse"), 1, glm::value_ptr(m_spotLight.diffuse)); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.specular"), 1, glm::value_ptr(m_spotLight.specular)); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.constant"), m_spotLight.constant); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.linear"), m_spotLight.linear); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.quadratic"), m_spotLight.quadratic); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.cutoff"), m_spotLight.cutoff); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.outCutoff"), m_spotLight.outCutoff); for (auto mesh : m_meshes) { mesh->Draw(_shaderProgram); } } void CMyModel::ProcessNode(const aiScene * _scene, aiNode * _node) { //处理自己的网格 for (int i = 0; i < _node->mNumMeshes; ++i) { auto mesh = this->ProcessMesh(_scene, _scene->mMeshes[_node->mMeshes[i]]); m_meshes.push_back(mesh); } //遍历子节点 for (int i = 0; i < _node->mNumChildren; ++i) { this->ProcessNode(_scene, _node->mChildren[i]); } } CMyMesh * CMyModel::ProcessMesh(const aiScene * _scene, aiMesh * _mesh) { vector<VERTEX> vertices; vector<GLuint> indices; vector<TEXTURE> textures; for (int i = 0; i < _mesh->mNumVertices; ++i) { VERTEX vertex; vertex.position.x = _mesh->mVertices[i].x; vertex.position.y = _mesh->mVertices[i].y; vertex.position.z = _mesh->mVertices[i].z; vertex.normal2.x = _mesh->mNormals[i].x; vertex.normal2.y = _mesh->mNormals[i].y; vertex.normal2.z = _mesh->mNormals[i].z; //直接读取 vertex.tangent.x = _mesh->mTangents[i].x; vertex.tangent.y = _mesh->mTangents[i].y; vertex.tangent.z = _mesh->mTangents[i].z; vertex.tangent = glm::normalize(vertex.tangent); vertex.bitangent.x = _mesh->mBitangents[i].x; vertex.bitangent.y = _mesh->mBitangents[i].y; vertex.bitangent.z = _mesh->mBitangents[i].z; vertex.bitangent = glm::normalize(vertex.bitangent); vertex.normal = glm::cross(vertex.tangent, vertex.bitangent); if (_mesh->mTextureCoords[0]) { vertex.texcoords.x = _mesh->mTextureCoords[0][i].x; vertex.texcoords.y = _mesh->mTextureCoords[0][i].y; } vertices.push_back(vertex); } for (int i = 0; i < _mesh->mNumFaces; i++) { aiFace face = _mesh->mFaces[i]; for (int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } if (_mesh->mMaterialIndex >= 0) { this->ProcessMaterial(_scene, _mesh->mMaterialIndex, textures); } CMyMesh * mesh = new CMyMesh(vertices, indices, textures); return mesh; } void CMyModel::ProcessMaterial(const aiScene * _scene, GLint _materialIdx, vector<TEXTURE> & _textures) { if (_materialIdx < 0) return; aiMaterial * material = _scene->mMaterials[_materialIdx]; vector<TEXTURE> texDiff = LoadMaterialTextures(material, aiTextureType_DIFFUSE, "tex_diffuse"); _textures.insert(_textures.end(), texDiff.begin(), texDiff.end()); vector<TEXTURE> texSpec = LoadMaterialTextures(material, aiTextureType_SPECULAR, "tex_specular"); _textures.insert(_textures.end(), texSpec.begin(), texSpec.end()); vector<TEXTURE> texNormalMap = LoadMaterialTextures(material, aiTextureType_HEIGHT, "tex_normalMap"); _textures.insert(_textures.end(), texNormalMap.begin(), texNormalMap.end()); vector<TEXTURE> texReflect = LoadMaterialTextures(material, aiTextureType_AMBIENT, "tex_reflect"); _textures.insert(_textures.end(), texReflect.begin(), texReflect.end()); } vector<TEXTURE> CMyModel::LoadMaterialTextures(aiMaterial * _material, aiTextureType _type, string _typeName) { vector<TEXTURE> vec; aiString name; for (int i = 0; i < _material->GetTextureCount(_type); i++) { if (_type == aiTextureType_REFLECTION) { int a = 1; } //获取纹理名称 _material->GetTexture(_type, i, &name); TEXTURE tex; tex.type = _typeName; tex.path = m_directory + '/' + name.C_Str(); tex.id = this->GetLocalTexture(tex.path.c_str()); vec.push_back(tex); } return vec; } GLuint CMyModel::GetLocalTexture(const GLchar * _texName) { //从map中找 if (m_textures.count(_texName)) return m_textures[_texName]; //没有 GLuint texture = 0; GLubyte * source = nullptr; int texWidth, texHeight; glGenTextures(1, &texture); source = SOIL_load_image(_texName, &texWidth, &texHeight, nullptr, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, source); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); SOIL_free_image_data(source); source = nullptr; m_textures.emplace(make_pair(_texName, texture)); return texture; } void CMyModel::AddPointLight(PT_LIGHT _ptLight) { m_ptLights.push_back(_ptLight); }
02f1dcd80682763ef6fa7597b9908346867d99bf
b066028fea8c16eb9134bf94024a3962ca14ca97
/lib/libgsmo/gmb_cols.cc
2e0952b3ad395048b6a60eb4658e36d67f92cb0c
[ "MIT" ]
permissive
elifesciences-publications/bpps-sipris-code
9afa7646079f1da44f82539e8b8f472e46286374
3c5382489c5e6aeca20c93b7ba2907b19fad3cf7
refs/heads/master
2021-05-14T03:59:31.629499
2017-10-04T19:12:20
2017-10-04T19:12:20
116,630,816
0
0
null
null
null
null
UTF-8
C++
false
false
15,460
cc
/****************************************************************************************** Copyright (C) 1997-2014 Andrew F. Neuwald, Cold Spring Harbor Laboratory and the University of Maryland School of Medicine. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For further information contact: Andrew F. Neuwald Institute for Genome Sciences and Department of Biochemistry & Molecular Biology University of Maryland School of Medicine 801 West Baltimore St. BioPark II, Room 617 Baltimore, MD 21201 Tel: 410-706-6724; Fax: 410-706-1482; E-mail: [email protected] ******************************************************************************************/ #include "gmb_typ.h" #define Debug_FB 0 char *gmb_typ::FindBlocks(ssx_typ *ssx, char mode, double cutoff, double bild_cut,Int4 Limit) { // ssx->InitNDL(0.0); // initialize model parameters. cma_typ cma=ssx->RtnCMA(),rcma=0,xcma=cma; assert(nBlksCMSA(cma) == 1); FILE *efp=0; // efp=stderr; Int4 blk=1,i,j,*N_INS,*INS_RES,n_ins,n_del,ins_res; char *Report,c; double *BILD,d,D,*deleted,BS,BSps,TotalWtSq=ssx->TotalWtSeq(); enum location { start, middle, end, stop }; BooLean trigger; //=============== 1. Allocate memory. ================ location *SITE; NEW(SITE,LengthCMSA(blk,cma) +3, location); NEW(Report,LengthCMSA(blk,cma) +3, char); NEW(BILD,LengthCMSA(blk,cma) +3, double); NEW(N_INS,LengthCMSA(blk,cma) +3, Int4); NEW(INS_RES,LengthCMSA(blk,cma) +3, Int4); //=============== 2. Compute data. ================ double **xBS=BILD_ScoresCMSA(ssx),*BldSc=xBS[1]; free(xBS); for(SITE[0]=end, i=1; i <= LengthCMSA(blk,cma); i++){ Report[i]=' '; #if 0 BILD[i]=ssx->BildScore(blk,i); #else BILD[i]=ssx->ContextBildScore(blk,i,BldSc); #endif n_ins=NumInsertsCMSA(blk,i,cma,ins_res); N_INS[i]=n_ins; INS_RES[i]=ins_res; #if Debug_FB if(n_ins > 0){ d=(double)n_ins/(double)NumAlnSeqsCMSA(cma); fprintf(stderr,"%d. n_ins=%d; ins_res=%d (%.2f vs %.2f)\n",i,n_ins,ins_res,d,cutoff); } #endif if(mode == 'A'){ // AddColumns() mode. d=(double)n_ins/(double)NumAlnSeqsCMSA(cma); // d=(double)n_ins/(double)NumSeqsCMSA(cma); if(d >= cutoff) trigger=TRUE; else trigger=FALSE; } else if(mode =='R'){ // RmColumns() mode; treat this as start of a "block". if(ins_res > 10) trigger=TRUE; else trigger=FALSE; } else { // RmShortBlk() mode. if(ins_res > 10) trigger=TRUE; else trigger=FALSE; } if(trigger){ SITE[i]=end; SITE[i+1]=start; } else if(SITE[i-1]==end) SITE[i]=start; else SITE[i]=middle; } i=LengthCMSA(blk,cma); SITE[i]=end; SITE[i+1]=stop; Report[0]=Report[i+1]=' '; free(BldSc); if(mode== 'A'){ // for AddColumns() //=============== 3. Find columns next to insertions. ================ for(i=1; i <= LengthCMSA(blk,cma); i++){ if(SITE[i] == middle) continue; switch (SITE[i]) { case start: Report[i]='B'; break; // insert column before.. case end: Report[i]='A'; break; // insert column after... default: print_error("FindBlocks(): This should not happen"); } } } else if(mode == 'R'){ // for RmColumns() //=============== 3. Label bad columns at start or end of blocks. ================ Int4 *NDEL=0; if(cutoff > 0){ NEW(NDEL, LengthCMSA(blk,cma)+9, Int4); for(i=1; i <= LengthCMSA(blk,cma); i++) NDEL[i]=NumDeletionsCMSA(blk,i,cma); } #if 1 // avoid removing all columns... double Cutoff=cutoff, Bild_cut=bild_cut,mfact=0.0,inc=0.05,dfact=1.0; do { Int4 num_cols=0,ndel=0,nbild=0,nboth=0; for(i=1; i <= LengthCMSA(blk,cma); i++){ d=(double)NDEL[i]/(double)NumAlnSeqsCMSA(cma); if(BILD[i] >= bild_cut && d <= cutoff){ nboth++; num_cols++; } if(BILD[i] >= bild_cut){ nbild++; } if(d <= cutoff){ ndel++; } } if(efp) fprintf(stderr,"%d columns retained; nbild=%d; ndel=%d; NumSeqs=%d (%.3g; %.3g; %d)\n", num_cols,nbild,ndel,NumAlnSeqsCMSA(cma),bild_cut,cutoff,Limit); if(num_cols < Limit){ // Limit == 3 by default... if(nbild < ndel){ // fewer BILD-signifcant columns than filled columns. mfact = mfact + inc; // mfact = 0.05, 0.10, 0.15, 0.25...10.0 d=fabs(bild_cut)*mfact; bild_cut = Bild_cut - d; } else { // fewer filled columns than BILD-signifcant columns. dfact = dfact + inc; // mfact = 0.50, 0.55, 0.60, ... 0.75 cutoff = Cutoff * dfact; // e.g., cutoff = 0.50 ... 0.75 } if(efp){ // WriteCMSA("junk.cma",cma); fprintf(stderr,"%d high deletion columns retained\n",ndel); fprintf(stderr,"%d BILD scored columns retained\n",nbild); fprintf(stderr,"Too many columns removed; adjusting BILD parameter (%.3g)\n",bild_cut); } } else break; } while(mfact < 10.0 && cutoff <= 0.75); #endif for(i=1; i <= LengthCMSA(blk,cma); i++){ if(BILD[i] >= bild_cut) continue; if(SITE[i] == middle) continue; switch (SITE[i]) { case start: do { Report[i]='*'; i++; } while(BILD[i] < bild_cut && SITE[i] != stop); break; case end: j=i; do { Report[j]='*'; j--; } while(j > 0 && BILD[j] < bild_cut && Report[j] == ' '); break; default: print_error("FindBlocks(): This should not happen"); } } #if 1 // if fraction of deletions > cutoff then remove the column. if(cutoff > 0){ for(i=1; i <= LengthCMSA(blk,cma); i++){ d=(double)NDEL[i]/(double)NumAlnSeqsCMSA(cma); if(d > cutoff) Report[i]='*'; } } free(NDEL); #endif } else { // for RmShortBlk() ... //=============== 4. Label short blocks. ================ #if 0 for(j=0,i=1; i <= LengthCMSA(blk,cma); i++){ if(SITE[i] == start) j=0; if(Report[i]==' '){ j++; continue; } if(Report[i]=='*'){ if(j < 3){ while(j > 0){ Report[i-j]='*'; j--; } } j=0; } } #else // New: remove all short blocks... for(j=0, i=1; i <= LengthCMSA(blk,cma); i++){ if(SITE[i] == start) j=1; else if(SITE[i] == end){ if(j < 3){ while(j >= 0){ Report[i-j]='*'; j--; } } j=0; } else { assert(SITE[i] == middle); j++; } } #endif } //=============== 4. Print out results. ================ if(0){ // for testing... this->RtnMap(); for(i=1; i <= LengthCMSA(blk,cma); i++){ BS=BILD[i]; BSps=BS/TotalWtSq; n_del=NumDeletionsCMSA(blk,i,cma); n_ins=N_INS[i]; ins_res=INS_RES[i]; switch (SITE[i]) { case start: c='S'; break; case middle: c=' '; break; case end: c='E'; break; default: print_error("FindBlocks(): This should not happen"); } fprintf(stderr,"%c%c%d: bild=%.1f (%.2f npws); ins=%d (%d) del=%d (%.1f%c).\n", c,Report[i],i,BS,BSps,n_ins,ins_res,n_del,100.0*FractDeletionsCMSA(blk,i,cma),'%'); if(ins_res > 10) ssx->PutPenalties(stderr,blk,i); else if(cutoff <= 0 && c==' ' && ins_res > 0) ssx->PutPenalties(stderr,blk,i); } fprintf(stderr,"\n\n %s\n",Report+1); } free(BILD); free(N_INS); free(INS_RES); free(SITE); return Report; } #define debug_AC 0 cma_typ gmb_typ::AddColumns(double bild_cut, BooLean Widen, set_typ InSet, double MinMatchFrq, BooLean EndsOnly) { Int4 blk=1,i,j,x,startA,endA,startB,endB,numcol,maxcols=4; cma_typ cma=SSX->RtnCMA(),rcma=0,xcma=cma,bcma,acma; double d,BS,bBS,aBS,prior_wt=SSX->GetPriorWt(); BooLean improved,found; str_typ *head = new str_typ('E'),*Str=head,*tail; if(this->AddOp){ x=strlen(this->AddOp); assert(x == (LengthCMSA(blk,cma)+2)); for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append(AddOp[i]); Str=Str->Next(); } } else for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append('m'); Str=Str->Next(); } Str->Append('E'); tail=Str->Next(); // head->Print(stderr); // if(EndsOnly) Widen=TRUE; SSX->InitNDL(0.0); // initialize model parameters. do { improved=FALSE; gmb_typ *xgmb= new gmb_typ(aa_per_io,aa_per_do,exp_ie,exp_de,xcma,dms_mode,prior_wt); char *BeforeOrAfter=this->FindBlocks(xgmb->RtnSSX(),'A',MinMatchFrq,bild_cut); delete xgmb; if(Widen){ endA=LengthCMSA(blk,xcma); startA=1; endB=endA; startB=1; } else { endA=LengthCMSA(blk,xcma)-1; startA=1; endB=endA+1; startB=startA+1; } for(Str=tail->Prev(),i=LengthCMSA(blk,xcma); i >= 0; Str=Str->Prev(),i--) // for(Str=tail->Prev(),i=105; i >= 100; Str=Str->Prev(),i--) { for(found=FALSE,numcol=1; numcol <= maxcols; numcol++){ j=i+1; BS=-999999999; #if debug_AC fprintf(stderr,"%d. Try adding %d cols: BOA[j=%d]=%c; BOA[i=%d]=%c.\n", i,numcol,j,BeforeOrAfter[j],i,BeforeOrAfter[i]); #endif if(BeforeOrAfter[j] == 'B' || BeforeOrAfter[i] == 'A'){ if(i > endA || i < startA){ acma=0; aBS=-99999999; } else { // Add column AFTER position i. if(i == LengthCMSA(blk,xcma)) acma=ExtendBlkCMSA(xcma, blk,0,numcol); else acma=InsertColumnsCMSA(xcma,blk,i,numcol); xgmb=new gmb_typ(aa_per_io,aa_per_do,exp_ie,exp_de,acma,dms_mode,prior_wt); // xgmb->SetPriorWt(prior_wt); aBS=xgmb->ScoreBILD(blk,i+numcol); ssx_typ *xssx=xgmb->RtnSSX(); d=xssx->RtnPercentGaps(blk,i+numcol); #if debug_AC fprintf(stderr,"A %d: BS=%.2f(cut=%.2f)[%d] ", i+numcol,aBS,bild_cut,NumAlnSeqsCMSA(acma)); xssx->PutWtCnts(stderr,blk,i+numcol); #endif delete xgmb; if(d >= 50.0){ if(acma) NilCMSA(acma); acma=0; aBS = -9999999.0; } } if(j > endB || j < startB){ bcma=0; bBS=-9999999; } else { // add column before position j. if(j == 1) bcma=ExtendBlkCMSA(xcma, blk,numcol,0); else bcma=InsertColumnsCMSA(xcma,blk,j,-numcol); xgmb=new gmb_typ(aa_per_io,aa_per_do,exp_ie,exp_de,bcma,dms_mode,prior_wt); bBS=xgmb->ScoreBILD(blk,i+1); ssx_typ *xssx=xgmb->RtnSSX(); d=xssx->RtnPercentGaps(blk,i+1); #if debug_AC fprintf(stderr,"B %d: BS=%.2f(cut=%.2f)[%d] ", i+1,bBS,bild_cut,NumAlnSeqsCMSA(bcma)); xssx=xgmb->RtnSSX(); xssx->PutWtCnts(stderr,blk,i+1); #endif delete xgmb; if(d >= 50.0){ if(bcma) NilCMSA(bcma); bcma=0; bBS = -9999999.0; } } if(aBS > bBS){ if(bcma) NilCMSA(bcma); bcma=0; BS=aBS; rcma=acma; } else { if(acma) NilCMSA(acma); acma=0; BS=bBS; rcma=bcma; } if(rcma==0){ numcol=maxcols; continue; } // Need not lengthen any further. if(BS < bild_cut){ if(rcma) NilCMSA(rcma); rcma=0; continue; } else { // if(bcma) for(x=1; x <= numcol; x++){ Str=Str->Prev(); Str->Append('d'); } else for(x=1; x <= numcol; x++){ Str->Append('d'); } found=TRUE; } } if(found){ #if debug_AC if(bcma) fprintf(stderr,"Added %d columns before position %d\n",numcol,j); if(acma) fprintf(stderr,"Added %d column after position %d\n",numcol,i); #endif if(xcma != cma) NilCMSA(xcma); xcma=rcma; improved=TRUE; Str=Str->Next(); i++; break; // break from numcol loop... } } if(found) break; // break from i loop. } free(BeforeOrAfter); } while(improved); // head->Print(); if(AddOp) free(AddOp); AddOp=head->Return(); AddOp[1]=toupper(AddOp[1]); // fprintf(stderr,"%s\n",AddOp); // exit(1); delete head; if(xcma != cma) return xcma; else return 0; } cma_typ gmb_typ::RmColumns(double bild_cut,BooLean Shrink,double MinDelFrq) { SSX->InitNDL(0.0); // initialize model parameters. cma_typ cma=SSX->RtnCMA(),rcma=0,xcma=cma; Int4 limit=3,i,j,blk=1,start,end,Len=LengthCMSA(blk,xcma); char c,*ToRm=this->FindBlocks(this->RtnSSX(),'R',MinDelFrq,bild_cut,limit); #if 0 str_typ *head = new str_typ('E'),*Str=head,*tail; assert(this->AddOp == 0); // free up before using this!! if(this->AddOp){ x=strlen(this->AddOp); assert(x == (LengthCMSA(blk,cma)+2)); for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append(AddOp[i]); Str=Str->Next(); } } else for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append('m'); Str=Str->Next(); } Str->Append('E'); tail=Str->Next(); // head->Print(stderr); #else assert(this->AddOp == 0); // free up before using this!! #endif if(Shrink){ end=LengthCMSA(blk,xcma); start=0; } else { end=LengthCMSA(blk,xcma)-1; start=1; } for(i=end; i > start; i--){ if(ToRm[i] != '*') continue; for(j=i; ToRm[j-1] == '*'; ) j--; if(i == LengthCMSA(blk,xcma)){ // assert(LengthCMSA(blk,xcma) >= ((i-j+1)+limit)); rcma=TrimBlkCMSA(xcma,blk,0,i-j+1,limit); i=j; // Blk=1; RmLeft=0; RmRight=i-j+1. if(rcma==0) print_error("gmb_typ::RmColumns(): too many aligned columns removed"); } else if(j==1){ // fprintf(stderr,"'%s'\n",ToRm); // assert(LengthCMSA(blk,xcma) >= (i+limit)); rcma=TrimBlkCMSA(xcma,blk,i,0,limit); i=j; // Blk=1; RmLeft=i; RmRight=0. if(rcma==0) print_error("gmb_typ::RmColumns(): too many columns removed from alignment"); } else { rcma=ConvertColsToInsertsCMSA(xcma,1,j,i); i=j; } if(xcma != cma) NilCMSA(xcma); xcma=rcma; } if(!Shrink){ // this->AddOp=rtn... char *rtn; NEW(rtn, Len+5, char); this->AddOp=rtn; rtn[0]='E'; rtn[1]='M'; for(j=2; j <= end && (c=ToRm[j]); j++){ if(c=='*') rtn[j]='d'; else rtn[j]='m'; } rtn[j]='m'; j++; rtn[j]='E'; j++; rtn[j]=0; // assume extra length added by FindBlocks(); } free(ToRm); assert(NumColumnsCMSA(xcma) >= 3); if(xcma != cma) return xcma; else return 0; } cma_typ gmb_typ::RmShortBlks(double bild_cut,BooLean Shrink) { // return 0; SSX->InitNDL(0.0); // initialize model parameters. cma_typ cma=SSX->RtnCMA(),rcma=0,xcma=cma; char *ToRm=this->FindBlocks(this->RtnSSX(),'S',-1.0,bild_cut); Int4 i,j,blk=1,start,end; double BS; if(Shrink){ end=LengthCMSA(blk,xcma); start=0; } else { end=LengthCMSA(blk,xcma)-1; start=1; } for(i=end; i > start; i--){ if(ToRm[i] != '*') continue; for(j=i; ToRm[j-1] == '*'; ) j--; if(i == LengthCMSA(blk,xcma)){ rcma=TrimBlkCMSA(xcma,1,0,i-j+1,1); i=j; // Blk=1; RmLeft=0; RmRight=i-j+1; limit=1. if(rcma==0) print_error("TrimBlkCMSA(): too many columns removed from alignment"); } else if(j==1){ rcma=TrimBlkCMSA(xcma,1,i,0,1); i=j; // Blk=1; RmLeft=i; RmRight=0; limit=1. if(rcma==0) print_error("TrimBlkCMSA(): too many columns removed from alignment"); } else { rcma=ConvertColsToInsertsCMSA(xcma,1,j,i); i=j; } if(xcma != cma) NilCMSA(xcma); xcma=rcma; } free(ToRm); if(xcma != cma) return xcma; else return 0; }
[ "aneuwald@bf312fdc-5263-4627-9904-0a588619bb94" ]
aneuwald@bf312fdc-5263-4627-9904-0a588619bb94
4572afe3191a3f42ee577600df794017dd07d198
cf99281f2660ed447312f5e821abed448e8b4fc3
/connectedComponents.cpp
89607f2adbb30e6544b3618df80929d4cb308ce1
[]
no_license
abhisehekkumr/tree
69c439ef4ffb6f7055ec52fff31606ee19dc5212
67697f5280b728ba16422a385bd84edbfd6971ad
refs/heads/master
2022-01-04T14:40:13.793257
2019-08-17T08:23:06
2019-08-17T08:23:06
156,063,456
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; void getDfs(int **edges, int n, bool *visited, vector<int> &k, int start){ k.push_back(start); visited[start] = true; for(int i = 0; i < n; i++){ if(i == start) continue; if(edges[start][i] && !visited[i]) getDfs(edges,n,visited,k,i); } } void getConnectedComponents(int **edges, int n, vector<vector<int>> &v){ bool *visited = new bool[n]; for(int i = 0; i < n; i++) visited[i] = false; for(int i = 0; i < n; i++){ vector<int> k; if(!visited[i]){ getDfs(edges,n,visited,k,i); v.push_back(k); } } delete [] visited; } int main(){ int n,e; cin >> n >> e; int **edges = new int*[n]; for(int i = 0; i < n; i++){ edges[i] = new int[n]; for(int j = 0; j < n; j++) edges[i][j] = 0; } for(int i = 0; i < e; i++){ int f,s; cin >> f >> s; edges[f][s] = 1; edges[s][f] = 1; } vector<vector<int>> v; getConnectedComponents(edges,n,v); for(int i = 0; i < v.size(); i++){ sort(v[i].begin(),v[i].end()); for(int j = 0; j < v[i].size(); j++) std::cout << v[i][j] << ' '; std::cout << '\n'; } for(int i = 0; i < n; i++) delete [] edges[i]; delete [] edges; }
cfa8e23bd7e65a2a113bf00228380ea04a99a037
3b1c7561c8d3b9452fc0cdefe299b208e0db1853
/src/shaders/SkTransformShader.h
4c6bcd28ab9f81ea7ba32a5ad1c5229767444e21
[ "BSD-3-Clause" ]
permissive
NearTox/Skia
dee04fc980bd40c1861c424b5643e7873f656b01
4d0cd2b6deca44eb2255651c4f04396963688761
refs/heads/master
2022-12-24T02:01:41.138176
2022-08-27T14:32:37
2022-08-27T14:32:37
153,816,056
0
0
BSD-3-Clause
2022-12-13T23:42:44
2018-10-19T17:05:47
C++
UTF-8
C++
false
false
1,809
h
/* * Copyright 2021 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkTextCoordShader_DEFINED #define SkTextCoordShader_DEFINED #include "src/core/SkVM.h" #include "src/shaders/SkShaderBase.h" // SkTransformShader allows the transform used by the shader to change without regenerating the // jitted code. This supports the drawVertices call to change the mapping as the texture // coordinates associated with each vertex change with each new triangle. class SkTransformShader : public SkUpdatableShader { public: explicit SkTransformShader(const SkShaderBase& shader); // Adds instructions to use the mapping stored in the uniforms represented by fMatrix. After // generating a new skvm::Coord, it passes the mapped coordinates to fShader's onProgram // along with the identity matrix. skvm::Color onProgram( skvm::Builder* b, skvm::Coord device, skvm::Coord local, skvm::Color color, const SkMatrixProvider& matrices, const SkMatrix* localM, const SkColorInfo& dst, skvm::Uniforms* uniforms, SkArenaAlloc* alloc) const override; // Add code to calculate a new coordinate given local using the mapping in fMatrix. skvm::Coord applyMatrix( skvm::Builder* b, const SkMatrix& matrix, skvm::Coord local, skvm::Uniforms* uniforms) const; void appendMatrix(const SkMatrix& matrix, SkRasterPipeline* p) const; // Change the values represented by the uniforms in fMatrix. bool update(const SkMatrix& ctm) const override; bool onAppendStages(const SkStageRec& rec) const override; private: const SkShaderBase& fShader; mutable SkScalar fMatrixStorage[9]; mutable skvm::Uniform fMatrix; mutable bool fProcessingAsPerspective{false}; }; #endif // SkTextCoordShader_DEFINED
59f3fb1f681c088aa465cfb3181d42a497331212
1de5dbf9d55db225dcea0703c2686c05b5ad6044
/CLONE_client/CLONE_client/Code/Frustum.cpp
ebfeb1ae8f1c25d5fd5766770ddb6ea6bdbf13cd
[]
no_license
RYUHYEONGSEOK/CLONE
4e48c8307445402a8fb656b599090513e63786ab
3a3d3e18e84fe7fea3667ab9f9d2123b8246a2fe
refs/heads/master
2021-01-15T13:18:40.409938
2017-08-17T01:42:46
2017-08-17T01:42:46
78,752,257
0
0
null
null
null
null
UTF-8
C++
false
false
2,072
cpp
#include "stdafx.h" #include "Frustum.h" //Objact #include "Camera.h" IMPLEMENT_SINGLETON(CFrustum) CFrustum::CFrustum(void) { } CFrustum::~CFrustum(void) { } HRESULT CFrustum::UpdateFrustum(CObj* pCam) { D3DXMATRIX viewProjection; D3DXMatrixMultiply(&viewProjection, &(*((CCamera*)pCam)->GetViewMatrix()), &(*((CCamera*)pCam)->GetProjMatrix())); // Left plane m_Plane[0].a = viewProjection._14 + viewProjection._11; m_Plane[0].b = viewProjection._24 + viewProjection._21; m_Plane[0].c = viewProjection._34 + viewProjection._31; m_Plane[0].d = viewProjection._44 + viewProjection._41; // Right plane m_Plane[1].a = viewProjection._14 - viewProjection._11; m_Plane[1].b = viewProjection._24 - viewProjection._21; m_Plane[1].c = viewProjection._34 - viewProjection._31; m_Plane[1].d = viewProjection._44 - viewProjection._41; // Top plane m_Plane[2].a = viewProjection._14 - viewProjection._12; m_Plane[2].b = viewProjection._24 - viewProjection._22; m_Plane[2].c = viewProjection._34 - viewProjection._32; m_Plane[2].d = viewProjection._44 - viewProjection._42; // Bottom plane m_Plane[3].a = viewProjection._14 + viewProjection._12; m_Plane[3].b = viewProjection._24 + viewProjection._22; m_Plane[3].c = viewProjection._34 + viewProjection._32; m_Plane[3].d = viewProjection._44 + viewProjection._42; // Near plane m_Plane[4].a = viewProjection._13; m_Plane[4].b = viewProjection._23; m_Plane[4].c = viewProjection._33; m_Plane[4].d = viewProjection._43; // Far plane m_Plane[5].a = viewProjection._14 - viewProjection._13; m_Plane[5].b = viewProjection._24 - viewProjection._23; m_Plane[5].c = viewProjection._34 - viewProjection._33; m_Plane[5].d = viewProjection._44 - viewProjection._43; // Normalize planes for (int i = 0; i < 6; i++) { D3DXPlaneNormalize(&m_Plane[i], &m_Plane[i]); } return S_OK; } bool CFrustum::SphereInFrustum(const D3DXVECTOR3* pCenter, const float& fRadius) { for (int i = 0; i < 6; ++i) { if (D3DXPlaneDotCoord(&m_Plane[i], pCenter) + fRadius < 0) return false; } return true; }
561fb5d6db284b75fd87e7d55d3a8e486f77f4ad
5d62cdda6593f2d14957997b4bf2b10e9e9ed717
/Demo/src/SmokeEffect.hpp
9d7f4477aa201376afb42d5ad60cdf08549058c2
[]
no_license
luoxz-ai/KetrazmEngine
d2daf6e66f090133075316c4c43bc14b1fd8d400
bc02d7627c409da7b06aa0a4d743d0b9d32d94e1
refs/heads/master
2021-05-30T21:37:04.887960
2015-09-02T21:08:44
2015-09-02T21:08:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
755
hpp
#ifndef SMOKEEFFECT_HEADER #define SMOKEEFFECT_HEADER #include <Engine/Audio/Sound.hpp> #include <Engine/Graphics/ParticlesHandler.hpp> using namespace Engine; class SmokeEffect { private: std::shared_ptr<Graphics::ShaderProgram> _physicsProgram; std::shared_ptr<Graphics::ShaderProgram> _displayProgram; std::shared_ptr<Graphics::ParticlesHandler> _particlesHandler; std::shared_ptr<Audio::Sound> _sound; public: SmokeEffect(void); ~SmokeEffect(void); void init(const glm::vec3 &position, GLuint numParticles); void setPosition(const glm::vec3 &pos); const std::shared_ptr<Graphics::ParticlesHandler> &getParticlesHandler(void) const; const std::shared_ptr<Audio::Sound> &getSound(void) const; void updateParticles(void) const; }; #endif
515772bce22aad18260016de1ba2694f90d85119
2b54f128becb618435b1c1eaaae84608ecbcc594
/剔除A串中B串的字符.cpp
93d72d2072cb5997b879dd953ff3e51f4c765ad9
[]
no_license
waten1992/Interview_Questions_Collections
b4790c7da05f78016b60ee4ec1e71058e919ab71
ccae4a12ae2745b36a4f0def353d0e12bd75b2f3
refs/heads/master
2020-05-27T17:40:37.568490
2015-03-19T14:25:00
2015-03-19T14:25:00
25,059,705
0
0
null
null
null
null
UTF-8
C++
false
false
2,408
cpp
/* --描述:A 字符串 “hello world” , B 字符串 "er" ,默认都是小写字母 , 要求写一个函数在A中除去B字符,返回A --INPUT: hello world , er --OUTPUT:hllowold --要求空间复杂度为O(1),时间复杂度越低越好; ----方法:1-先对A HASH 到 一个临时int变量check中,相应位置1 ----------2-在对B HASH 的相应的位和check相与 ,把A置1的清零 ----------3-扫描A串 同时HASH 和check相与,判断是否为零,若是直接跳过. 若不是则赋值给一个临时串保存; ----------4-把A串的指针,指向临时串。同时return A串的指针; */ #include <iostream> using namespace std; void Print_Binary_Num(int Num) //输出二进制 , 按照小端序列输出 { int i = 32 ; while(i) { cout<<(Num&0X1); //总是输出第一个数 Num = Num>>1; //不断的右移 i--; if (i%4 == 0) cout<<'\t'; } } char * Handler(char *s1 , char *s2) { int i = 0 , Tmp = 0 , check = 0 , index = 0; char *Tmp_String = new char [10]; //临时数组 while (s1[i]) //HASH --- A 相应的位置1 { Tmp = (s1[i] - 'a') % 32 ; // HASH if (Tmp >= 0 && Tmp <=25) //排出其他字符 check = (1<<Tmp)|check; i++; } i = 0; //再次初始化 while (s2[i]) //HASH ---B ----把A 和 B中都存在的字符 都置0 { Tmp = (s2[i] - 'a') % 32 ; if (Tmp >= 0 && Tmp <=25) //排出其他字符 check = (~(1<<Tmp))&check;//---1 两种方式都可以,都是把相应的为清零 ; 推荐用第一种 //check = (1<<Tmp)^check; //----2 但是第二种有副作用,假若A不存在,而B存在; // 则check的相应位被置1,不过在本例中,没有影响,后面是相与 i++; } i = 0; //第3次初始化 while(s1[i]) //再次 扫描A 和check 位相与 。赋值给临时数组 { Tmp = (s1[i] - 'a') % 32 ; if ((1<<Tmp)&check) { Tmp_String[index] = s1[i]; index++; } i++; } s1 = Tmp_String; return s1; } int main() { char *s1 , *s2 ; s1 = "hello world " ; s2 = "re"; s1 = Handler(s1 , s2); cout<<s1<<endl; return 0; } /* THE Answer as follows----> hllowold Process returned 0 (0x0) execution time : 0.029 s Press any key to continue. */
8e44ecf6b779231c8bdab6a97bff52e9b160b933
be30e126df12d9ac6087ab8f82101c6b932121c8
/sdk/CPed.cpp
19f8ca3cce7ec415bb9aa8654dad04cd6a870235
[]
no_license
ArnCarveris/gta-sa-plugin-sdk
fc53265bbce06de9276ad2a289e50505aaea2d52
f64548b0f588856d2da6100cd1c69a5880f89fd2
refs/heads/master
2020-05-20T15:46:06.287895
2014-02-23T14:07:29
2014-02-23T14:07:29
34,955,493
1
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
#include "CPed.h" NOINLINE CPed::CPed(ePedType type) { PREPARE_FOR_REDIRECTION(); //((void (__thiscall *)(CPed *, ePedType))0x5E8030)(this, type); } NOINLINE CPed::~CPed() { PREPARE_FOR_REDIRECTION(); //((void (__thiscall *)(CPed *))0x5E8620)(this); } void *CPed::operator new(unsigned int size) { return ((void *(__cdecl *)(unsigned int))0x5E4720)(size); } void CPed::operator delete(void *object) { ((void (__cdecl *)(void *))0x5E4760)(object); } void CPed::SetMoveAnim() { ((void (__thiscall *)(CPed *))this->vtable[23])(this); } bool CPed::Save() { return ((bool (__thiscall *)(CPed *))this->vtable[24])(this); } bool CPed::Load() { return ((bool (__thiscall *)(CPed *))this->vtable[25])(this); } void CPed::RemoveWeaponAnims(int weaponSlot, float blenDelta) { ((void (__thiscall *)(CPed *, int, float))0x5F0250)(this, weaponSlot, blenDelta); } unsigned char CPed::GetWeaponSkill(eWeaponType weaponType) { return ((unsigned char (__thiscall *)(CPed *, eWeaponType))0x5E3B60)(this, weaponType); }
[ "[email protected]@a08e2604-8956-8f2e-fb63-2a67f058b60e" ]
[email protected]@a08e2604-8956-8f2e-fb63-2a67f058b60e
b0992e8676f7969b54a97e78e2932b6fda899e65
e1bc05eee7ee3a46af7661cfe16d49710c683984
/lib/resourcemanager/textureload.cpp
8211b480a083f6417c17f45ca8e90aef61675f31
[]
no_license
TheAks999/Visualizer
55c706e327c0685f83f0a96a5ea1578e925c866c
1589aea26eb96ad114fc7287ec67d3d572265e6e
refs/heads/master
2016-09-06T14:14:32.117880
2011-06-16T04:39:33
2011-06-16T04:39:33
1,651,762
0
0
null
null
null
null
UTF-8
C++
false
false
6,670
cpp
/************** *This file may change between projects * ~Shep **************/ #ifndef TEXTURELOAD_CPP #define TEXTURELOAD_CPP #include "texture.h" #include <qgl.h> #include <GL/glu.h> #include <iostream> enum IMAGE_TYPE { IMG_NONE, IMG_TIFF, IMG_PNG, IMG_TGA, IMG_BMP }; IMAGE_TYPE getImageType(const QString & path) { if ( path.endsWith(".tif")) return IMG_TIFF; if ( path.endsWith(".png")) return IMG_PNG; if ( path.endsWith(".tga")) return IMG_TGA; if ( path.endsWith(".bmp")) return IMG_BMP; return IMG_NONE; } bool ResTexture::load( const QImage& img ) { QImage fixed( img.width(), img.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, img ); painter.end(); QImage texture = QGLWidget::convertToGLFormat( fixed ); glEnable( GL_TEXTURE ); glEnable( GL_TEXTURE_2D ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return false; } #include <iostream> using namespace std; bool ResTexture::load( const std::string & path ) { glEnable( GL_TEXTURE ); glEnable( GL_TEXTURE_2D ); switch (getImageType(path.c_str())) { case IMG_TIFF: loadTIFF(path.c_str(),texId,texture); break; case IMG_PNG: loadPNG(path.c_str(),texId,texture); break; case IMG_TGA: loadTGA(path.c_str(),texId,texture); break; case IMG_BMP: loadBMP(path.c_str(),texId,texture); default: return false; } return true; } bool loadTIFF(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: TIFF File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } bool loadPNG(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: PNG File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } bool loadTGA(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: TGA File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } bool loadBMP(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: BMP File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } #endif
20d49af522c7316cf4e2fadd99d6b65794be1392
554e6b73ed500172abe5fdef08fbc7caf4089f78
/Cpp/Practice/insertionSort.cpp
25b69261536a3ddcb24e182e10c1893819d54e8e
[]
no_license
Shandilier/Competitive-Programming-1
e65388adff421398d803b746635597b2fa5a53c2
c9d66f472aee2fd1fbd3e934e3efb2230dbeebd6
refs/heads/main
2023-06-25T09:33:46.317893
2021-07-28T03:06:16
2021-07-28T03:06:16
385,301,682
0
0
null
null
null
null
UTF-8
C++
false
false
454
cpp
#include<bits/stdc++.h> #define ll long long int using namespace std; int main() { ll n; cin>>n; ll arr[n]; for(ll i=0;i<n;i++) cin>>arr[i]; ll key; ll j; for(ll i=0;i<n;i++) { key = arr[i]; j=i-1; while(j>=0 && arr[j]>=key) { arr[j+1] = arr[j]; j--; } arr[j+1]=key; } for(ll i=0;i<n;i++) cout<<arr[i]<<" "; cout<<endl; }
ab5774960c8f3def583b2bf7bc2097ec6772edeb
115cd4d9eb0916772fa5622693a367663d5946f4
/cpp-HSDS/include/hsds/rank-index.hpp
50e807e9c63a55166eec5350cad54bbac63c4ad0
[ "MIT" ]
permissive
jasonjin22/BWA177
287e8704c5bf1f3edceb3ad8c118531917e155ac
a23542cc03802141f33382eafbd222fa0b219c6d
refs/heads/master
2020-05-17T10:30:56.696782
2019-05-16T15:15:24
2019-05-16T15:15:24
183,659,247
0
0
null
null
null
null
UTF-8
C++
false
false
4,192
hpp
/** * @file rank-index.hpp * @brief Implementation of RankIndex class * @author Hideaki Ohno */ #if !defined(HSDS_RANK_INDEX_H_) #define HSDS_RANK_INDEX_H_ #if !defined(_MSC_VER) #include <stdint.h> #endif // !defined(_MSC_VER) /** * @namespace hsds */ namespace hsds { /** * @class RankIndex * * @brief Index structure for rank operation. */ class RankIndex { public: /** * @brief Constructor */ RankIndex() : abs_(0), rel_(0) { } /** * @brief Destructor */ ~RankIndex() { } /** * @brief Setter method for absolute rank value. * * @param[in] value Absolute value of rank. */ void set_abs(uint32_t value) { abs_ = value; } /** * @brief Setter method for relative rank value at 1st block. * * @param[in] value Relative rank value. */ void set_rel1(uint64_t value) { rel_ = ((rel_ & ~0x7FULL) | (value & 0x7FULL)); } /** * @brief Setter method for relative rank value at 2nd block. * * @param[in] value Relative rank value. */ void set_rel2(uint64_t value) { rel_ = ((rel_ & ~(0xFFULL << 7)) | (value & 0xFFULL) << 7); } /** * @brief Setter method for relative rank value at 3rd block. * * @param[in] value Relative rank value. */ void set_rel3(uint64_t value) { rel_ = ((rel_ & ~(0xFFULL << 15)) | (value & 0xFFULL) << 15); } /** * @brief Setter method for relative rank value at 4th block. * * @param[in] value Relative rank value. */ void set_rel4(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 23)) | (value & 0x1FFULL) << 23); } /** * @brief Setter method for relative rank value at 5th block. * * @param[in] value Relative rank value. */ void set_rel5(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 32)) | (value & 0x1FFULL) << 32); } /** * @brief Setter method for relative rank value at 6th block. * * @param[in] value Relative rank value. */ void set_rel6(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 41)) | (value & 0x1FFULL) << 41); } /** * @brief Setter method for relative rank value at 7th block. * * @param[in] value Relative rank value. */ void set_rel7(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 50)) | (value & 0x1FFULL) << 50); } /** * @brief Getter method for absolute rank value. * * @return Absolute rank value. */ uint64_t abs() const { return abs_; } /** * @brief Getter method for relative value at 1st block. * * @return Relative value at 1st block. */ uint64_t rel1() const { return rel_ & 0x7FULL; } /** * @brief Getter method for relative value at 2nd block. * * @return Relative value at 1st block. */ uint64_t rel2() const { return (rel_ >> 7) & 0xFFULL; } /** * @brief Getter method for relative value at 3rd block. * * @return Relative value at 1st block. */ uint64_t rel3() const { return (rel_ >> 15) & 0xFFULL; } /** * @brief Getter method for relative value at 4th block. * * @return Relative value at 1st block. */ uint64_t rel4() const { return (rel_ >> 23) & 0x1FFULL; } /** * @brief Getter method for relative value at 5th block. * * @return Relative value at 1st block. */ uint64_t rel5() const { return (rel_ >> 32) & 0x1FFULL; } /** * @brief Getter method for relative value at 6th block. * * @return Relative value at 1st block. */ uint64_t rel6() const { return (rel_ >> 41) & 0x1FFULL; } /** * @brief Getter method for relative value at 7th block. * * @return Relative value at 1st block. */ uint64_t rel7() const { return (rel_ >> 50) & 0x1FFULL; } private: uint64_t abs_; ///< Absolute rank value uint64_t rel_; ///< Relative rank value container }; } #endif /* !defined(HSDS_RANK_INDEX_H_) */
fca5b2ab7b0b4e0c2793a765b5c84fea13e3c3e7
6e9b20902f4e232d12e865f192ea5128ae253ba7
/Fluid/7.4/uniform/time
815a736038b424044dd1a5297547ac9d34a00257
[]
no_license
abarcaortega/FSI_3
1de5ed06ca7731016e5136820aecdc0a74042723
016638757f56e7b8b33af4a1af8e0635b88ffbbc
refs/heads/master
2020-08-03T22:28:04.707884
2019-09-30T16:33:31
2019-09-30T16:33:31
211,905,379
0
0
null
null
null
null
UTF-8
C++
false
false
823
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: dev \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "7.4/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 7.39999999999988667; name "7.4"; index 740; deltaT 0.01; deltaT0 0.01; // ************************************************************************* //
34120f1b774b1d6a25064dd007ed62501b2a1db7
9da88ab805303c25bd9654ad45287a62a6c4710f
/Cpp/atcoder/abc/292/D.cpp
96addbbdd41b3cfb222cb285565917cda88fc5fd
[]
no_license
ms303956362/myexercise
7bb7be1ac0b8f40aeee8ca2df19255024c6d9bdc
4730c438354f0c7fc3bce54f8c1ade6e627586c9
refs/heads/master
2023-04-13T01:15:01.882780
2023-04-03T15:03:22
2023-04-03T15:03:22
232,984,051
2
0
null
2022-12-02T06:55:19
2020-01-10T06:47:00
C
UTF-8
C++
false
false
1,726
cpp
// IO #include <iostream> #include <iomanip> // std::setprecision #include <sstream> // ordered container #include <vector> #include <deque> #include <list> #include <forward_list> #include <string> #include <stack> #include <queue> // associative-container #include <map> #include <set> #include <unordered_map> #include <unordered_set> // algorithm #include <algorithm> #include <cmath> // utility #include <initializer_list> #include <iterator> #include <memory> #include <utility> // c #include <cstdio> #include <cstdlib> #include <cstring> // functional #include <functional> using namespace std; using ll = long long; int main(int argc, char const *argv[]) { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; vector<int> p(n); for (int i = 0; i < n; ++i) { p[i] = i; } function<int(int)> find = [&](int u) { return p[u] == u ? u : (p[u] = find(p[u])); }; auto merge = [&](int u, int v) { int pu = find(u), pv = find(v); if (pu == pv) { return false; } p[pu]= pv; return true; }; vector<pair<int, int>> edges; for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; --u; --v; merge(u, v); edges.emplace_back(u, v); } map<int, int> cntv, cnte; for (int i = 0; i < n; ++i) { ++cntv[find(i)]; } for (const auto& [u, v] : edges) { ++cnte[find(u)]; } auto check = [&]() { for (const auto& [u, c] : cntv) { if (c != cnte[u]) { return false; } } return true; }; cout << (check() ? "Yes" : "No") << '\n'; return 0; }
4532a0dd142389699a8739a7ab431f4dc63474c2
9557a0940de8ee41cb814a4177e419e202ff9188
/binTree/tree/Tree.cpp
1999c2d83b0b026f4756bdba2ba1b94b548c416c
[]
no_license
ljt141421/DataStructure
416a85d1ae28d394a1e4d6fd44ed72969f8cdded
613de0582bd9a80735f4a7c1a73947e3cf7ac7fb
refs/heads/master
2022-11-18T02:25:02.145547
2022-11-05T15:51:52
2022-11-05T15:51:52
194,282,918
3
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
#include"Tree.h" void initTree(Tree *tree,ElemType ref) { tree->root=NULL; tree->refValue=ref; } void createTree(Tree *tree,char *str) { createTree(tree,tree->root,str); } void createTree(Tree *tree,TreeNode *&t,char *&str) { if(*str == tree->refValue) t=NULL; else { t=(TreeNode*)malloc(sizeof(TreeNode)); assert(t != NULL); t->data=*str; createTree(tree,t->firstChild,++str); createTree(tree,t->nextSibling,++str); } } TreeNode* root(Tree *tree) { return tree->root; } TreeNode* firstChild(Tree *tree) { return firstChild(tree->root); } TreeNode* firstChild(TreeNode *t) { if(t == NULL) return NULL; return t->firstChild; } TreeNode* nextSibling(Tree *tree) { return nextSibling(tree->root); } TreeNode* nextSibling(TreeNode *t) { if(t == NULL) return NULL; return t->nextSibling; } TreeNode* find(Tree *tree,ElemType key) { return find(tree->root,key); } TreeNode* find(TreeNode *t,ElemType key) { if(t == NULL) return NULL; if(t->data == key) return t; TreeNode *p=find(t->firstChild,key); if(p != NULL) return p; return find(t->nextSibling,key); } TreeNode* parent(Tree *tree,TreeNode *p) { return parent(tree->root,p); } TreeNode* parent(TreeNode *t,TreeNode *p) { if(t == NULL || p == NULL) return NULL; TreeNode *q=t->firstChild; TreeNode *par;//parent while(q != NULL && q != p) { par=parent(q,p); if(par != NULL) return par; q=q->nextSibling; } if(q != NULL && q==p) return t; return NULL; }
a9d39ed32107029a51e97c26996c61ab0c3aea6e
c8e6f194669663e0e2748dbc56a7172b9ea008f7
/.localhistory/GUI/1472028309$MainForm.h
e52932e83702bc6d660060f023fd277cdffd518f
[]
no_license
itreppert/GUI
1922e781d804d17cb8008197fdbfa11576077618
9ca4ea0531eb45a4462a4d8278aec67f8c2705ef
refs/heads/master
2020-04-17T20:29:10.965471
2016-09-06T13:18:01
2016-09-06T13:18:01
67,501,677
0
0
null
null
null
null
ISO-8859-1
C++
false
false
105,891
h
#pragma once #include "Test.h" #include "TeilenDurch0Exception.h" #include "BlinkinButton.h" #include "DrawingPanel.h" #include "RegexTextBox.h" namespace GUI { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace NLog; /// <summary> /// Zusammenfassung für MainForm /// </summary> public ref class MainForm : public System::Windows::Forms::Form { public: MainForm(void) { logger->Info("ctor"); InitializeComponent(); initialiseComponents(); tabControl1->SelectTab(tabControl1->TabCount - 1); step = 0; richTextBox1->LoadFile("d:\\Dokument.rtf"); points = gcnew ArrayList; points->Add(lastPoint); } protected: /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> ~MainForm() { if (components) { delete components; } } //Logger !! private: static Logger^ logger = LogManager::GetCurrentClassLogger(); private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::Panel^ panel1; private: System::Windows::Forms::Button^ cmdChangeFormColor; private: System::Windows::Forms::TabControl^ tabControl1; private: System::Windows::Forms::TabPage^ tabPage1; private: System::Windows::Forms::TabPage^ tabPage2; private: System::Windows::Forms::TabPage^ tabPage3; private: System::Windows::Forms::Button^ btnChangeTab; private: System::Windows::Forms::Panel^ panel2; private: System::Windows::Forms::CheckBox^ checkBox1; private: System::Windows::Forms::Button^ btnCheckbox; private: System::Windows::Forms::RadioButton^ radioButton3; private: System::Windows::Forms::RadioButton^ radioButton2; private: System::Windows::Forms::RadioButton^ radioButton1; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::Button^ btnRadioButton; private: System::Windows::Forms::ComboBox^ cmbBlubb; private: System::Windows::Forms::Button^ btnComboboxValue; private: System::Windows::Forms::Button^ btnComboAddItem; private: System::Windows::Forms::Button^ btnComboremoveItem; private: System::Windows::Forms::Button^ btnComboInsert; private: System::Windows::Forms::ListBox^ listBox1; private: System::Windows::Forms::TextBox^ txtAnswers; private: System::Windows::Forms::TextBox^ txtQuestions; Test^ t; int progress; String^ antwort1; String^ antwort2; String^ antwort3; String^ antwort4; private: System::Windows::Forms::Button^ btnNextStep; int step; private: System::Windows::Forms::Button^ btnChangeFromAnotherClass; private: System::Windows::Forms::MaskedTextBox^ maskedTextBox1; private: System::Windows::Forms::NumericUpDown^ numericUpDown1; private: System::Windows::Forms::Panel^ panel3; private: System::Windows::Forms::PictureBox^ pictureBox1; private: System::Windows::Forms::Button^ btnStartProgress; private: System::Windows::Forms::ProgressBar^ progressBar1; private: System::Windows::Forms::RichTextBox^ richTextBox1; private: System::Windows::Forms::Timer^ timer1; private: System::Windows::Forms::TrackBar^ trackBar1; private: System::Windows::Forms::MenuStrip^ menuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem2; private: System::Windows::Forms::ToolStripSeparator^ toolStripSeparator1; private: System::Windows::Forms::ToolStripMenuItem^ mnuSaveFileDialog; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem3; private: System::Windows::Forms::OpenFileDialog^ openFileDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuFarben; private: System::Windows::Forms::ColorDialog^ colorDialog1; private: System::Windows::Forms::SaveFileDialog^ saveFileDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuSchriftart; private: System::Windows::Forms::FontDialog^ fontDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuRichtextBox; private: System::Windows::Forms::ToolStripMenuItem^ mnuFolderBrowser; private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1; private: System::Windows::Forms::ContextMenuStrip^ contextMenuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ mnuClearText; private: System::Windows::Forms::ToolStripMenuItem^ mnuOpen; private: System::Windows::Forms::ToolStripMenuItem^ mnuSave; private: System::Windows::Forms::DateTimePicker^ dateTimePicker1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem4; private: System::Windows::Forms::ToolStripMenuItem^ mnuButtonsHerstellen; private: System::Windows::Forms::ToolStripMenuItem^ mnuListControls; private: System::Windows::Forms::ToolStripMenuItem^ mnuTextBoxenHerstellen; private: System::Windows::Forms::Button^ btnAddDoubles; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::TextBox^ txtZweiteZahl; private: System::Windows::Forms::TextBox^ txtErsteZahl; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel2; private: System::Windows::Forms::Panel^ panel4; private: System::Windows::Forms::Button^ btnArrayList; private: System::Windows::Forms::TextBox^ txtCollections; private: System::Windows::Forms::Button^ btnQueue; private: System::Windows::Forms::Button^ btnStack; private: System::Windows::Forms::Button^ btnSortedList; private: System::Windows::Forms::Button^ btnHashtable; private: System::Windows::Forms::Button^ btnList; private: System::Windows::Forms::Button^ btnArray; private: System::Windows::Forms::Button^ btnBenchmark; private: System::Windows::Forms::TabPage^ tabPage4; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel3; private: System::Windows::Forms::Panel^ pnlDrawing; private: System::Windows::Forms::Panel^ pnlGraphics; private: System::Windows::Forms::Button^ btnDrawLine; private: System::Windows::Forms::Button^ btnTranslatePoints; private: System::Windows::Forms::PictureBox^ pictureBox2; private: System::Windows::Forms::Button^ btnDrawImage; private: System::Windows::Forms::Button^ btnDrawHouse; private: System::Windows::Forms::Button^ btnDivide; private: System::Windows::Forms::TabPage^ tabPage5; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel4; private: System::Windows::Forms::TextBox^ textBox2; private: System::Windows::Forms::Panel^ panel5; private: BlinkinButton^ btnBlinkinButton; private: System::Windows::Forms::Panel^ panel6; private: DrawingPanel^ pnlHouse; private: System::Windows::Forms::TabPage^ tabPage6; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel5; private: System::Windows::Forms::Panel^ panel8; private: System::Windows::Forms::TextBox^ txtTreeView; private: System::Windows::Forms::TreeView^ treeView1; private: System::Windows::Forms::Panel^ panel7; private: System::Windows::Forms::Button^ btnAddTreeNodeToTreeView; private: System::Windows::Forms::Button^ btnRemoveTreeNOde; private: System::Windows::Forms::Button^ btnReadDirectories; private: System::Windows::Forms::Button^ btnRecursion; private: System::Windows::Forms::Button^ btnRegex; private: System::Windows::Forms::TextBox^ txtRegex; private: System::Windows::Forms::TextBox^ txtRegexExpr; private: RegexTextBox^ txtAutoRegexMatcher; private: System::Windows::Forms::Button^ btnChangeRegexInRegexTextBox; private: System::Windows::Forms::Button^ btnWalkTreeViewRecursive; private: System::Windows::Forms::Button^ btnDriveInfo; private: System::Windows::Forms::TabPage^ tabPage7; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel6; private: System::Windows::Forms::TreeView^ trvDirectories; private: System::Windows::Forms::ListView^ lsvFiles; private: System::Windows::Forms::ToolStripMenuItem^ mnuRefreshTreeView; private: System::ComponentModel::IContainer^ components; protected: private: /// <summary> /// Erforderliche Designervariable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MainForm::typeid)); System::Windows::Forms::TreeNode^ treeNode1 = (gcnew System::Windows::Forms::TreeNode(L"Knoten7")); System::Windows::Forms::TreeNode^ treeNode2 = (gcnew System::Windows::Forms::TreeNode(L"Knoten8")); System::Windows::Forms::TreeNode^ treeNode3 = (gcnew System::Windows::Forms::TreeNode(L"Knoten9")); System::Windows::Forms::TreeNode^ treeNode4 = (gcnew System::Windows::Forms::TreeNode(L"Knoten15")); System::Windows::Forms::TreeNode^ treeNode5 = (gcnew System::Windows::Forms::TreeNode(L"Knoten16")); System::Windows::Forms::TreeNode^ treeNode6 = (gcnew System::Windows::Forms::TreeNode(L"Knoten21")); System::Windows::Forms::TreeNode^ treeNode7 = (gcnew System::Windows::Forms::TreeNode(L"Knoten22")); System::Windows::Forms::TreeNode^ treeNode8 = (gcnew System::Windows::Forms::TreeNode(L"Knoten26")); System::Windows::Forms::TreeNode^ treeNode9 = (gcnew System::Windows::Forms::TreeNode(L"Knoten27")); System::Windows::Forms::TreeNode^ treeNode10 = (gcnew System::Windows::Forms::TreeNode(L"Knoten28")); System::Windows::Forms::TreeNode^ treeNode11 = (gcnew System::Windows::Forms::TreeNode(L"Knoten29")); System::Windows::Forms::TreeNode^ treeNode12 = (gcnew System::Windows::Forms::TreeNode(L"Knoten30")); System::Windows::Forms::TreeNode^ treeNode13 = (gcnew System::Windows::Forms::TreeNode(L"Knoten31")); System::Windows::Forms::TreeNode^ treeNode14 = (gcnew System::Windows::Forms::TreeNode(L"Knoten32")); System::Windows::Forms::TreeNode^ treeNode15 = (gcnew System::Windows::Forms::TreeNode(L"Knoten33")); System::Windows::Forms::TreeNode^ treeNode16 = (gcnew System::Windows::Forms::TreeNode(L"Knoten34")); System::Windows::Forms::TreeNode^ treeNode17 = (gcnew System::Windows::Forms::TreeNode(L"Knoten23", gcnew cli::array< System::Windows::Forms::TreeNode^ >(9) { treeNode8, treeNode9, treeNode10, treeNode11, treeNode12, treeNode13, treeNode14, treeNode15, treeNode16 })); System::Windows::Forms::TreeNode^ treeNode18 = (gcnew System::Windows::Forms::TreeNode(L"Knoten24")); System::Windows::Forms::TreeNode^ treeNode19 = (gcnew System::Windows::Forms::TreeNode(L"Knoten25")); System::Windows::Forms::TreeNode^ treeNode20 = (gcnew System::Windows::Forms::TreeNode(L"Knoten17", gcnew cli::array< System::Windows::Forms::TreeNode^ >(5) { treeNode6, treeNode7, treeNode17, treeNode18, treeNode19 })); System::Windows::Forms::TreeNode^ treeNode21 = (gcnew System::Windows::Forms::TreeNode(L"Knoten18")); System::Windows::Forms::TreeNode^ treeNode22 = (gcnew System::Windows::Forms::TreeNode(L"Knoten19")); System::Windows::Forms::TreeNode^ treeNode23 = (gcnew System::Windows::Forms::TreeNode(L"Knoten20")); System::Windows::Forms::TreeNode^ treeNode24 = (gcnew System::Windows::Forms::TreeNode(L"Knoten10", gcnew cli::array< System::Windows::Forms::TreeNode^ >(6) { treeNode4, treeNode5, treeNode20, treeNode21, treeNode22, treeNode23 })); System::Windows::Forms::TreeNode^ treeNode25 = (gcnew System::Windows::Forms::TreeNode(L"Knoten11")); System::Windows::Forms::TreeNode^ treeNode26 = (gcnew System::Windows::Forms::TreeNode(L"Knoten12")); System::Windows::Forms::TreeNode^ treeNode27 = (gcnew System::Windows::Forms::TreeNode(L"Knoten13")); System::Windows::Forms::TreeNode^ treeNode28 = (gcnew System::Windows::Forms::TreeNode(L"Knoten14")); System::Windows::Forms::TreeNode^ treeNode29 = (gcnew System::Windows::Forms::TreeNode(L"Knoten0", gcnew cli::array< System::Windows::Forms::TreeNode^ >(8) { treeNode1, treeNode2, treeNode3, treeNode24, treeNode25, treeNode26, treeNode27, treeNode28 })); this->tableLayoutPanel1 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->contextMenuStrip1 = (gcnew System::Windows::Forms::ContextMenuStrip(this->components)); this->mnuClearText = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuOpen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuSave = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->panel1 = (gcnew System::Windows::Forms::Panel()); this->btnStartProgress = (gcnew System::Windows::Forms::Button()); this->btnChangeFromAnotherClass = (gcnew System::Windows::Forms::Button()); this->btnComboInsert = (gcnew System::Windows::Forms::Button()); this->btnComboremoveItem = (gcnew System::Windows::Forms::Button()); this->btnComboAddItem = (gcnew System::Windows::Forms::Button()); this->btnComboboxValue = (gcnew System::Windows::Forms::Button()); this->btnRadioButton = (gcnew System::Windows::Forms::Button()); this->btnCheckbox = (gcnew System::Windows::Forms::Button()); this->btnChangeTab = (gcnew System::Windows::Forms::Button()); this->cmdChangeFormColor = (gcnew System::Windows::Forms::Button()); this->panel2 = (gcnew System::Windows::Forms::Panel()); this->dateTimePicker1 = (gcnew System::Windows::Forms::DateTimePicker()); this->trackBar1 = (gcnew System::Windows::Forms::TrackBar()); this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown()); this->maskedTextBox1 = (gcnew System::Windows::Forms::MaskedTextBox()); this->listBox1 = (gcnew System::Windows::Forms::ListBox()); this->cmbBlubb = (gcnew System::Windows::Forms::ComboBox()); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->radioButton3 = (gcnew System::Windows::Forms::RadioButton()); this->radioButton2 = (gcnew System::Windows::Forms::RadioButton()); this->radioButton1 = (gcnew System::Windows::Forms::RadioButton()); this->checkBox1 = (gcnew System::Windows::Forms::CheckBox()); this->panel3 = (gcnew System::Windows::Forms::Panel()); this->btnDivide = (gcnew System::Windows::Forms::Button()); this->btnAddDoubles = (gcnew System::Windows::Forms::Button()); this->label1 = (gcnew System::Windows::Forms::Label()); this->txtZweiteZahl = (gcnew System::Windows::Forms::TextBox()); this->txtErsteZahl = (gcnew System::Windows::Forms::TextBox()); this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox()); this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); this->tabControl1 = (gcnew System::Windows::Forms::TabControl()); this->tabPage1 = (gcnew System::Windows::Forms::TabPage()); this->tabPage2 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel2 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->panel4 = (gcnew System::Windows::Forms::Panel()); this->btnBenchmark = (gcnew System::Windows::Forms::Button()); this->btnArray = (gcnew System::Windows::Forms::Button()); this->btnList = (gcnew System::Windows::Forms::Button()); this->btnHashtable = (gcnew System::Windows::Forms::Button()); this->btnSortedList = (gcnew System::Windows::Forms::Button()); this->btnStack = (gcnew System::Windows::Forms::Button()); this->btnQueue = (gcnew System::Windows::Forms::Button()); this->btnArrayList = (gcnew System::Windows::Forms::Button()); this->txtCollections = (gcnew System::Windows::Forms::TextBox()); this->tabPage3 = (gcnew System::Windows::Forms::TabPage()); this->txtAnswers = (gcnew System::Windows::Forms::TextBox()); this->txtQuestions = (gcnew System::Windows::Forms::TextBox()); this->btnNextStep = (gcnew System::Windows::Forms::Button()); this->tabPage4 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel3 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->pnlDrawing = (gcnew System::Windows::Forms::Panel()); this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox()); this->pnlGraphics = (gcnew System::Windows::Forms::Panel()); this->btnDrawHouse = (gcnew System::Windows::Forms::Button()); this->btnDrawImage = (gcnew System::Windows::Forms::Button()); this->btnTranslatePoints = (gcnew System::Windows::Forms::Button()); this->btnDrawLine = (gcnew System::Windows::Forms::Button()); this->tabPage5 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel4 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->textBox2 = (gcnew System::Windows::Forms::TextBox()); this->panel5 = (gcnew System::Windows::Forms::Panel()); this->panel6 = (gcnew System::Windows::Forms::Panel()); this->tabPage6 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel5 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->panel8 = (gcnew System::Windows::Forms::Panel()); this->btnChangeRegexInRegexTextBox = (gcnew System::Windows::Forms::Button()); this->txtRegexExpr = (gcnew System::Windows::Forms::TextBox()); this->txtRegex = (gcnew System::Windows::Forms::TextBox()); this->btnRegex = (gcnew System::Windows::Forms::Button()); this->txtTreeView = (gcnew System::Windows::Forms::TextBox()); this->treeView1 = (gcnew System::Windows::Forms::TreeView()); this->panel7 = (gcnew System::Windows::Forms::Panel()); this->btnDriveInfo = (gcnew System::Windows::Forms::Button()); this->btnWalkTreeViewRecursive = (gcnew System::Windows::Forms::Button()); this->btnRecursion = (gcnew System::Windows::Forms::Button()); this->btnReadDirectories = (gcnew System::Windows::Forms::Button()); this->btnRemoveTreeNOde = (gcnew System::Windows::Forms::Button()); this->btnAddTreeNodeToTreeView = (gcnew System::Windows::Forms::Button()); this->timer1 = (gcnew System::Windows::Forms::Timer(this->components)); this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->toolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem2 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripSeparator1 = (gcnew System::Windows::Forms::ToolStripSeparator()); this->mnuSaveFileDialog = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuRichtextBox = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuFolderBrowser = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem3 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuFarben = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuSchriftart = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem4 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuButtonsHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuListControls = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuTextBoxenHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog()); this->colorDialog1 = (gcnew System::Windows::Forms::ColorDialog()); this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog()); this->fontDialog1 = (gcnew System::Windows::Forms::FontDialog()); this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog()); this->tabPage7 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel6 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->trvDirectories = (gcnew System::Windows::Forms::TreeView()); this->lsvFiles = (gcnew System::Windows::Forms::ListView()); this->mnuRefreshTreeView = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->tableLayoutPanel1->SuspendLayout(); this->contextMenuStrip1->SuspendLayout(); this->panel1->SuspendLayout(); this->panel2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->BeginInit(); this->groupBox1->SuspendLayout(); this->panel3->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit(); this->tabControl1->SuspendLayout(); this->tabPage1->SuspendLayout(); this->tabPage2->SuspendLayout(); this->tableLayoutPanel2->SuspendLayout(); this->panel4->SuspendLayout(); this->tabPage3->SuspendLayout(); this->tabPage4->SuspendLayout(); this->tableLayoutPanel3->SuspendLayout(); this->pnlDrawing->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->BeginInit(); this->pnlGraphics->SuspendLayout(); this->tabPage5->SuspendLayout(); this->tableLayoutPanel4->SuspendLayout(); this->tabPage6->SuspendLayout(); this->tableLayoutPanel5->SuspendLayout(); this->panel8->SuspendLayout(); this->panel7->SuspendLayout(); this->menuStrip1->SuspendLayout(); this->tabPage7->SuspendLayout(); this->tableLayoutPanel6->SuspendLayout(); this->SuspendLayout(); // // tableLayoutPanel1 // this->tableLayoutPanel1->ColumnCount = 2; this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->Controls->Add(this->textBox1, 1, 0); this->tableLayoutPanel1->Controls->Add(this->panel1, 0, 0); this->tableLayoutPanel1->Controls->Add(this->panel2, 0, 1); this->tableLayoutPanel1->Controls->Add(this->panel3, 1, 1); this->tableLayoutPanel1->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel1->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel1->Name = L"tableLayoutPanel1"; this->tableLayoutPanel1->RowCount = 2; this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel1->TabIndex = 3; // // textBox1 // this->textBox1->ContextMenuStrip = this->contextMenuStrip1; this->textBox1->Dock = System::Windows::Forms::DockStyle::Fill; this->textBox1->Location = System::Drawing::Point(431, 3); this->textBox1->Multiline = true; this->textBox1->Name = L"textBox1"; this->textBox1->ScrollBars = System::Windows::Forms::ScrollBars::Both; this->textBox1->Size = System::Drawing::Size(422, 282); this->textBox1->TabIndex = 2; // // contextMenuStrip1 // this->contextMenuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) { this->mnuClearText, this->mnuOpen, this->mnuSave }); this->contextMenuStrip1->Name = L"contextMenuStrip1"; this->contextMenuStrip1->Size = System::Drawing::Size(160, 70); // // mnuClearText // this->mnuClearText->Name = L"mnuClearText"; this->mnuClearText->Size = System::Drawing::Size(159, 22); this->mnuClearText->Text = L"TextBox löschen"; this->mnuClearText->Click += gcnew System::EventHandler(this, &MainForm::mnuClearText_Click); // // mnuOpen // this->mnuOpen->Name = L"mnuOpen"; this->mnuOpen->Size = System::Drawing::Size(159, 22); this->mnuOpen->Text = L"Datei öffnen"; this->mnuOpen->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click); // // mnuSave // this->mnuSave->Name = L"mnuSave"; this->mnuSave->Size = System::Drawing::Size(159, 22); this->mnuSave->Text = L"Speichern als"; this->mnuSave->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click); // // panel1 // this->panel1->Controls->Add(this->btnStartProgress); this->panel1->Controls->Add(this->btnChangeFromAnotherClass); this->panel1->Controls->Add(this->btnComboInsert); this->panel1->Controls->Add(this->btnComboremoveItem); this->panel1->Controls->Add(this->btnComboAddItem); this->panel1->Controls->Add(this->btnComboboxValue); this->panel1->Controls->Add(this->btnRadioButton); this->panel1->Controls->Add(this->btnCheckbox); this->panel1->Controls->Add(this->btnChangeTab); this->panel1->Controls->Add(this->cmdChangeFormColor); this->panel1->Dock = System::Windows::Forms::DockStyle::Fill; this->panel1->Location = System::Drawing::Point(3, 3); this->panel1->Name = L"panel1"; this->panel1->Size = System::Drawing::Size(422, 282); this->panel1->TabIndex = 1; // // btnStartProgress // this->btnStartProgress->Location = System::Drawing::Point(115, 32); this->btnStartProgress->Name = L"btnStartProgress"; this->btnStartProgress->Size = System::Drawing::Size(109, 23); this->btnStartProgress->TabIndex = 9; this->btnStartProgress->Text = L"Start Progress"; this->btnStartProgress->UseVisualStyleBackColor = true; this->btnStartProgress->Click += gcnew System::EventHandler(this, &MainForm::btnStartProgress_Click); // // btnChangeFromAnotherClass // this->btnChangeFromAnotherClass->Location = System::Drawing::Point(115, 3); this->btnChangeFromAnotherClass->Name = L"btnChangeFromAnotherClass"; this->btnChangeFromAnotherClass->Size = System::Drawing::Size(109, 23); this->btnChangeFromAnotherClass->TabIndex = 8; this->btnChangeFromAnotherClass->Text = L"Class Fun"; this->btnChangeFromAnotherClass->UseVisualStyleBackColor = true; this->btnChangeFromAnotherClass->Click += gcnew System::EventHandler(this, &MainForm::btnChangeFromAnotherClass_Click); // // btnComboInsert // this->btnComboInsert->Location = System::Drawing::Point(3, 178); this->btnComboInsert->Name = L"btnComboInsert"; this->btnComboInsert->Size = System::Drawing::Size(109, 23); this->btnComboInsert->TabIndex = 7; this->btnComboInsert->Text = L"Combo insert Item"; this->btnComboInsert->UseVisualStyleBackColor = true; this->btnComboInsert->Click += gcnew System::EventHandler(this, &MainForm::btnComboInsert_Click); // // btnComboremoveItem // this->btnComboremoveItem->Location = System::Drawing::Point(4, 207); this->btnComboremoveItem->Name = L"btnComboremoveItem"; this->btnComboremoveItem->Size = System::Drawing::Size(109, 23); this->btnComboremoveItem->TabIndex = 6; this->btnComboremoveItem->Text = L"Combo remove Item"; this->btnComboremoveItem->UseVisualStyleBackColor = true; this->btnComboremoveItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboremoveItem_Click); // // btnComboAddItem // this->btnComboAddItem->Location = System::Drawing::Point(3, 149); this->btnComboAddItem->Name = L"btnComboAddItem"; this->btnComboAddItem->Size = System::Drawing::Size(96, 23); this->btnComboAddItem->TabIndex = 5; this->btnComboAddItem->Text = L"Combo Add Item"; this->btnComboAddItem->UseVisualStyleBackColor = true; this->btnComboAddItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboAddItem_Click); // // btnComboboxValue // this->btnComboboxValue->Location = System::Drawing::Point(4, 120); this->btnComboboxValue->Name = L"btnComboboxValue"; this->btnComboboxValue->Size = System::Drawing::Size(96, 23); this->btnComboboxValue->TabIndex = 4; this->btnComboboxValue->Text = L"Combo Value"; this->btnComboboxValue->UseVisualStyleBackColor = true; this->btnComboboxValue->Click += gcnew System::EventHandler(this, &MainForm::btnComboboxValue_Click); // // btnRadioButton // this->btnRadioButton->Location = System::Drawing::Point(4, 91); this->btnRadioButton->Name = L"btnRadioButton"; this->btnRadioButton->Size = System::Drawing::Size(96, 23); this->btnRadioButton->TabIndex = 3; this->btnRadioButton->Text = L"Radiobutton"; this->btnRadioButton->UseVisualStyleBackColor = true; this->btnRadioButton->Click += gcnew System::EventHandler(this, &MainForm::btnRadioButton_Click); // // btnCheckbox // this->btnCheckbox->Location = System::Drawing::Point(4, 62); this->btnCheckbox->Name = L"btnCheckbox"; this->btnCheckbox->Size = System::Drawing::Size(96, 23); this->btnCheckbox->TabIndex = 2; this->btnCheckbox->Text = L"Checkbox"; this->btnCheckbox->UseVisualStyleBackColor = true; this->btnCheckbox->Click += gcnew System::EventHandler(this, &MainForm::btnCheckbox_Click); // // btnChangeTab // this->btnChangeTab->Location = System::Drawing::Point(3, 32); this->btnChangeTab->Name = L"btnChangeTab"; this->btnChangeTab->Size = System::Drawing::Size(97, 23); this->btnChangeTab->TabIndex = 1; this->btnChangeTab->Text = L"Change Tab"; this->btnChangeTab->UseVisualStyleBackColor = true; this->btnChangeTab->Click += gcnew System::EventHandler(this, &MainForm::btnChangeTab_Click); // // cmdChangeFormColor // this->cmdChangeFormColor->Location = System::Drawing::Point(3, 3); this->cmdChangeFormColor->Name = L"cmdChangeFormColor"; this->cmdChangeFormColor->Size = System::Drawing::Size(97, 23); this->cmdChangeFormColor->TabIndex = 0; this->cmdChangeFormColor->Text = L"Change Color"; this->cmdChangeFormColor->UseVisualStyleBackColor = true; this->cmdChangeFormColor->Click += gcnew System::EventHandler(this, &MainForm::cmdChangeFormColor_Click); // // panel2 // this->panel2->Controls->Add(this->dateTimePicker1); this->panel2->Controls->Add(this->trackBar1); this->panel2->Controls->Add(this->numericUpDown1); this->panel2->Controls->Add(this->maskedTextBox1); this->panel2->Controls->Add(this->listBox1); this->panel2->Controls->Add(this->cmbBlubb); this->panel2->Controls->Add(this->groupBox1); this->panel2->Controls->Add(this->checkBox1); this->panel2->Dock = System::Windows::Forms::DockStyle::Fill; this->panel2->Location = System::Drawing::Point(3, 291); this->panel2->Name = L"panel2"; this->panel2->Size = System::Drawing::Size(422, 282); this->panel2->TabIndex = 3; // // dateTimePicker1 // this->dateTimePicker1->Location = System::Drawing::Point(24, 205); this->dateTimePicker1->Name = L"dateTimePicker1"; this->dateTimePicker1->Size = System::Drawing::Size(200, 20); this->dateTimePicker1->TabIndex = 10; this->dateTimePicker1->ValueChanged += gcnew System::EventHandler(this, &MainForm::dateTimePicker1_ValueChanged); // // trackBar1 // this->trackBar1->Location = System::Drawing::Point(10, 158); this->trackBar1->Name = L"trackBar1"; this->trackBar1->Size = System::Drawing::Size(104, 45); this->trackBar1->TabIndex = 9; this->trackBar1->Scroll += gcnew System::EventHandler(this, &MainForm::trackBar1_Scroll); // // numericUpDown1 // this->numericUpDown1->Increment = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 }); this->numericUpDown1->Location = System::Drawing::Point(191, 132); this->numericUpDown1->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 }); this->numericUpDown1->Name = L"numericUpDown1"; this->numericUpDown1->Size = System::Drawing::Size(79, 20); this->numericUpDown1->TabIndex = 8; this->numericUpDown1->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 }); // // maskedTextBox1 // this->maskedTextBox1->Location = System::Drawing::Point(4, 131); this->maskedTextBox1->Mask = L"00/00/0000 00:00"; this->maskedTextBox1->Name = L"maskedTextBox1"; this->maskedTextBox1->Size = System::Drawing::Size(172, 20); this->maskedTextBox1->TabIndex = 7; this->maskedTextBox1->ValidatingType = System::DateTime::typeid; // // listBox1 // this->listBox1->FormattingEnabled = true; this->listBox1->Items->AddRange(gcnew cli::array< System::Object^ >(4) { L"Bli", L"Bla", L"Blubb", L"Trallallaaaaaa" }); this->listBox1->Location = System::Drawing::Point(133, 30); this->listBox1->Name = L"listBox1"; this->listBox1->SelectionMode = System::Windows::Forms::SelectionMode::MultiSimple; this->listBox1->Size = System::Drawing::Size(137, 95); this->listBox1->TabIndex = 6; this->listBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::listBox1_SelectedIndexChanged); // // cmbBlubb // this->cmbBlubb->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->cmbBlubb->FormattingEnabled = true; this->cmbBlubb->Items->AddRange(gcnew cli::array< System::Object^ >(5) { L"Bli", L"Bla", L"Blubb", L"Trallalla", L"Whooop" }); this->cmbBlubb->Location = System::Drawing::Point(133, 3); this->cmbBlubb->Name = L"cmbBlubb"; this->cmbBlubb->Size = System::Drawing::Size(137, 21); this->cmbBlubb->TabIndex = 5; this->cmbBlubb->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::cmbBlubb_SelectedIndexChanged); // // groupBox1 // this->groupBox1->Controls->Add(this->radioButton3); this->groupBox1->Controls->Add(this->radioButton2); this->groupBox1->Controls->Add(this->radioButton1); this->groupBox1->Location = System::Drawing::Point(4, 26); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(113, 91); this->groupBox1->TabIndex = 4; this->groupBox1->TabStop = false; this->groupBox1->Text = L"groupBox1"; // // radioButton3 // this->radioButton3->AutoSize = true; this->radioButton3->Location = System::Drawing::Point(6, 65); this->radioButton3->Name = L"radioButton3"; this->radioButton3->Size = System::Drawing::Size(85, 17); this->radioButton3->TabIndex = 3; this->radioButton3->TabStop = true; this->radioButton3->Text = L"radioButton3"; this->radioButton3->UseVisualStyleBackColor = true; // // radioButton2 // this->radioButton2->AutoSize = true; this->radioButton2->Location = System::Drawing::Point(6, 42); this->radioButton2->Name = L"radioButton2"; this->radioButton2->Size = System::Drawing::Size(85, 17); this->radioButton2->TabIndex = 2; this->radioButton2->TabStop = true; this->radioButton2->Text = L"radioButton2"; this->radioButton2->UseVisualStyleBackColor = true; // // radioButton1 // this->radioButton1->AutoSize = true; this->radioButton1->Location = System::Drawing::Point(6, 19); this->radioButton1->Name = L"radioButton1"; this->radioButton1->Size = System::Drawing::Size(85, 17); this->radioButton1->TabIndex = 1; this->radioButton1->TabStop = true; this->radioButton1->Text = L"radioButton1"; this->radioButton1->UseVisualStyleBackColor = true; // // checkBox1 // this->checkBox1->AutoSize = true; this->checkBox1->Location = System::Drawing::Point(3, 3); this->checkBox1->Name = L"checkBox1"; this->checkBox1->Size = System::Drawing::Size(80, 17); this->checkBox1->TabIndex = 0; this->checkBox1->Text = L"checkBox1"; this->checkBox1->UseVisualStyleBackColor = true; this->checkBox1->CheckedChanged += gcnew System::EventHandler(this, &MainForm::checkBox1_CheckedChanged); // // panel3 // this->panel3->Controls->Add(this->btnDivide); this->panel3->Controls->Add(this->btnAddDoubles); this->panel3->Controls->Add(this->label1); this->panel3->Controls->Add(this->txtZweiteZahl); this->panel3->Controls->Add(this->txtErsteZahl); this->panel3->Controls->Add(this->richTextBox1); this->panel3->Controls->Add(this->progressBar1); this->panel3->Controls->Add(this->pictureBox1); this->panel3->Dock = System::Windows::Forms::DockStyle::Fill; this->panel3->Location = System::Drawing::Point(431, 291); this->panel3->Name = L"panel3"; this->panel3->Size = System::Drawing::Size(422, 282); this->panel3->TabIndex = 4; // // btnDivide // this->btnDivide->Location = System::Drawing::Point(107, 196); this->btnDivide->Name = L"btnDivide"; this->btnDivide->Size = System::Drawing::Size(30, 23); this->btnDivide->TabIndex = 11; this->btnDivide->Text = L"/"; this->btnDivide->UseVisualStyleBackColor = true; this->btnDivide->Click += gcnew System::EventHandler(this, &MainForm::btnDivide_Click); // // btnAddDoubles // this->btnAddDoubles->Location = System::Drawing::Point(240, 167); this->btnAddDoubles->Name = L"btnAddDoubles"; this->btnAddDoubles->Size = System::Drawing::Size(30, 23); this->btnAddDoubles->TabIndex = 10; this->btnAddDoubles->Text = L"="; this->btnAddDoubles->UseVisualStyleBackColor = true; this->btnAddDoubles->Click += gcnew System::EventHandler(this, &MainForm::btnAddDoubles_Click); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(124, 173); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(13, 13); this->label1->TabIndex = 5; this->label1->Text = L"+"; // // txtZweiteZahl // this->txtZweiteZahl->Location = System::Drawing::Point(138, 170); this->txtZweiteZahl->Name = L"txtZweiteZahl"; this->txtZweiteZahl->Size = System::Drawing::Size(100, 20); this->txtZweiteZahl->TabIndex = 4; // // txtErsteZahl // this->txtErsteZahl->Location = System::Drawing::Point(18, 170); this->txtErsteZahl->Name = L"txtErsteZahl"; this->txtErsteZahl->Size = System::Drawing::Size(100, 20); this->txtErsteZahl->TabIndex = 3; // // richTextBox1 // this->richTextBox1->Location = System::Drawing::Point(93, 29); this->richTextBox1->Name = L"richTextBox1"; this->richTextBox1->Size = System::Drawing::Size(177, 88); this->richTextBox1->TabIndex = 2; this->richTextBox1->Text = L""; // // progressBar1 // this->progressBar1->Location = System::Drawing::Point(93, 3); this->progressBar1->Name = L"progressBar1"; this->progressBar1->Size = System::Drawing::Size(177, 14); this->progressBar1->Style = System::Windows::Forms::ProgressBarStyle::Continuous; this->progressBar1->TabIndex = 1; this->progressBar1->Value = 40; // // pictureBox1 // this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox1.Image"))); this->pictureBox1->Location = System::Drawing::Point(3, 3); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(84, 82); this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox1->TabIndex = 0; this->pictureBox1->TabStop = false; // // tabControl1 // this->tabControl1->Controls->Add(this->tabPage1); this->tabControl1->Controls->Add(this->tabPage2); this->tabControl1->Controls->Add(this->tabPage3); this->tabControl1->Controls->Add(this->tabPage4); this->tabControl1->Controls->Add(this->tabPage5); this->tabControl1->Controls->Add(this->tabPage6); this->tabControl1->Controls->Add(this->tabPage7); this->tabControl1->Dock = System::Windows::Forms::DockStyle::Fill; this->tabControl1->Location = System::Drawing::Point(0, 24); this->tabControl1->Name = L"tabControl1"; this->tabControl1->SelectedIndex = 0; this->tabControl1->Size = System::Drawing::Size(870, 608); this->tabControl1->TabIndex = 4; // // tabPage1 // this->tabPage1->Controls->Add(this->tableLayoutPanel1); this->tabPage1->Location = System::Drawing::Point(4, 22); this->tabPage1->Name = L"tabPage1"; this->tabPage1->Padding = System::Windows::Forms::Padding(3); this->tabPage1->Size = System::Drawing::Size(862, 582); this->tabPage1->TabIndex = 0; this->tabPage1->Text = L"Basics"; this->tabPage1->UseVisualStyleBackColor = true; // // tabPage2 // this->tabPage2->Controls->Add(this->tableLayoutPanel2); this->tabPage2->Location = System::Drawing::Point(4, 22); this->tabPage2->Name = L"tabPage2"; this->tabPage2->Padding = System::Windows::Forms::Padding(3); this->tabPage2->Size = System::Drawing::Size(862, 582); this->tabPage2->TabIndex = 1; this->tabPage2->Text = L"Other"; this->tabPage2->UseVisualStyleBackColor = true; // // tableLayoutPanel2 // this->tableLayoutPanel2->ColumnCount = 2; this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->Controls->Add(this->panel4, 0, 0); this->tableLayoutPanel2->Controls->Add(this->txtCollections, 1, 0); this->tableLayoutPanel2->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel2->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel2->Name = L"tableLayoutPanel2"; this->tableLayoutPanel2->RowCount = 1; this->tableLayoutPanel2->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel2->TabIndex = 0; // // panel4 // this->panel4->Controls->Add(this->btnBenchmark); this->panel4->Controls->Add(this->btnArray); this->panel4->Controls->Add(this->btnList); this->panel4->Controls->Add(this->btnHashtable); this->panel4->Controls->Add(this->btnSortedList); this->panel4->Controls->Add(this->btnStack); this->panel4->Controls->Add(this->btnQueue); this->panel4->Controls->Add(this->btnArrayList); this->panel4->Dock = System::Windows::Forms::DockStyle::Fill; this->panel4->Location = System::Drawing::Point(3, 3); this->panel4->Name = L"panel4"; this->panel4->Size = System::Drawing::Size(422, 570); this->panel4->TabIndex = 0; // // btnBenchmark // this->btnBenchmark->Location = System::Drawing::Point(4, 207); this->btnBenchmark->Name = L"btnBenchmark"; this->btnBenchmark->Size = System::Drawing::Size(121, 23); this->btnBenchmark->TabIndex = 8; this->btnBenchmark->Text = L"Benchmark"; this->btnBenchmark->UseVisualStyleBackColor = true; this->btnBenchmark->Click += gcnew System::EventHandler(this, &MainForm::btnBenchmark_Click); // // btnArray // this->btnArray->Location = System::Drawing::Point(4, 178); this->btnArray->Name = L"btnArray"; this->btnArray->Size = System::Drawing::Size(121, 23); this->btnArray->TabIndex = 7; this->btnArray->Text = L"array"; this->btnArray->UseVisualStyleBackColor = true; this->btnArray->Click += gcnew System::EventHandler(this, &MainForm::btnArray_Click); // // btnList // this->btnList->Location = System::Drawing::Point(4, 149); this->btnList->Name = L"btnList"; this->btnList->Size = System::Drawing::Size(121, 23); this->btnList->TabIndex = 6; this->btnList->Text = L"List"; this->btnList->UseVisualStyleBackColor = true; this->btnList->Click += gcnew System::EventHandler(this, &MainForm::btnList_Click); // // btnHashtable // this->btnHashtable->Location = System::Drawing::Point(4, 120); this->btnHashtable->Name = L"btnHashtable"; this->btnHashtable->Size = System::Drawing::Size(121, 23); this->btnHashtable->TabIndex = 4; this->btnHashtable->Text = L"HashTable"; this->btnHashtable->UseVisualStyleBackColor = true; this->btnHashtable->Click += gcnew System::EventHandler(this, &MainForm::btnHashtable_Click); // // btnSortedList // this->btnSortedList->Location = System::Drawing::Point(4, 91); this->btnSortedList->Name = L"btnSortedList"; this->btnSortedList->Size = System::Drawing::Size(121, 23); this->btnSortedList->TabIndex = 3; this->btnSortedList->Text = L"SortedList"; this->btnSortedList->UseVisualStyleBackColor = true; this->btnSortedList->Click += gcnew System::EventHandler(this, &MainForm::btnSortedList_Click); // // btnStack // this->btnStack->Location = System::Drawing::Point(4, 62); this->btnStack->Name = L"btnStack"; this->btnStack->Size = System::Drawing::Size(121, 23); this->btnStack->TabIndex = 2; this->btnStack->Text = L"Stack"; this->btnStack->UseVisualStyleBackColor = true; this->btnStack->Click += gcnew System::EventHandler(this, &MainForm::btnStack_Click); // // btnQueue // this->btnQueue->Location = System::Drawing::Point(4, 33); this->btnQueue->Name = L"btnQueue"; this->btnQueue->Size = System::Drawing::Size(121, 23); this->btnQueue->TabIndex = 1; this->btnQueue->Text = L"Queue"; this->btnQueue->UseVisualStyleBackColor = true; this->btnQueue->Click += gcnew System::EventHandler(this, &MainForm::btnQueue_Click); // // btnArrayList // this->btnArrayList->Location = System::Drawing::Point(4, 4); this->btnArrayList->Name = L"btnArrayList"; this->btnArrayList->Size = System::Drawing::Size(121, 23); this->btnArrayList->TabIndex = 0; this->btnArrayList->Text = L"ArrayList"; this->btnArrayList->UseVisualStyleBackColor = true; this->btnArrayList->Click += gcnew System::EventHandler(this, &MainForm::btnArrayList_Click); // // txtCollections // this->txtCollections->Dock = System::Windows::Forms::DockStyle::Fill; this->txtCollections->Location = System::Drawing::Point(431, 3); this->txtCollections->Multiline = true; this->txtCollections->Name = L"txtCollections"; this->txtCollections->Size = System::Drawing::Size(422, 570); this->txtCollections->TabIndex = 1; // // tabPage3 // this->tabPage3->Controls->Add(this->txtAnswers); this->tabPage3->Controls->Add(this->txtQuestions); this->tabPage3->Controls->Add(this->btnNextStep); this->tabPage3->Location = System::Drawing::Point(4, 22); this->tabPage3->Name = L"tabPage3"; this->tabPage3->Padding = System::Windows::Forms::Padding(3); this->tabPage3->Size = System::Drawing::Size(862, 582); this->tabPage3->TabIndex = 2; this->tabPage3->Text = L"Quiz"; this->tabPage3->UseVisualStyleBackColor = true; // // txtAnswers // this->txtAnswers->Location = System::Drawing::Point(288, 231); this->txtAnswers->Multiline = true; this->txtAnswers->Name = L"txtAnswers"; this->txtAnswers->Size = System::Drawing::Size(268, 203); this->txtAnswers->TabIndex = 2; // // txtQuestions // this->txtQuestions->Location = System::Drawing::Point(288, 4); this->txtQuestions->Multiline = true; this->txtQuestions->Name = L"txtQuestions"; this->txtQuestions->Size = System::Drawing::Size(268, 203); this->txtQuestions->TabIndex = 1; // // btnNextStep // this->btnNextStep->Location = System::Drawing::Point(7, 7); this->btnNextStep->Name = L"btnNextStep"; this->btnNextStep->Size = System::Drawing::Size(75, 23); this->btnNextStep->TabIndex = 0; this->btnNextStep->Text = L"Next"; this->btnNextStep->UseVisualStyleBackColor = true; this->btnNextStep->Click += gcnew System::EventHandler(this, &MainForm::btnNextStep_Click); // // tabPage4 // this->tabPage4->Controls->Add(this->tableLayoutPanel3); this->tabPage4->Location = System::Drawing::Point(4, 22); this->tabPage4->Name = L"tabPage4"; this->tabPage4->Padding = System::Windows::Forms::Padding(3); this->tabPage4->Size = System::Drawing::Size(862, 582); this->tabPage4->TabIndex = 3; this->tabPage4->Text = L"Graphics"; this->tabPage4->UseVisualStyleBackColor = true; // // tableLayoutPanel3 // this->tableLayoutPanel3->ColumnCount = 2; this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->Controls->Add(this->pnlDrawing, 1, 0); this->tableLayoutPanel3->Controls->Add(this->pnlGraphics, 0, 0); this->tableLayoutPanel3->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel3->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel3->Name = L"tableLayoutPanel3"; this->tableLayoutPanel3->RowCount = 1; this->tableLayoutPanel3->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel3->TabIndex = 0; // // pnlDrawing // this->pnlDrawing->BackColor = System::Drawing::Color::Gainsboro; this->pnlDrawing->Controls->Add(this->pictureBox2); this->pnlDrawing->Dock = System::Windows::Forms::DockStyle::Fill; this->pnlDrawing->Location = System::Drawing::Point(431, 3); this->pnlDrawing->Name = L"pnlDrawing"; this->pnlDrawing->Size = System::Drawing::Size(422, 570); this->pnlDrawing->TabIndex = 0; this->pnlDrawing->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click); // // pictureBox2 // this->pictureBox2->Dock = System::Windows::Forms::DockStyle::Fill; this->pictureBox2->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox2.Image"))); this->pictureBox2->Location = System::Drawing::Point(0, 0); this->pictureBox2->Name = L"pictureBox2"; this->pictureBox2->Size = System::Drawing::Size(422, 570); this->pictureBox2->TabIndex = 0; this->pictureBox2->TabStop = false; this->pictureBox2->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click); this->pictureBox2->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MainForm::pnlDrawing_Paint); // // pnlGraphics // this->pnlGraphics->Controls->Add(this->btnDrawHouse); this->pnlGraphics->Controls->Add(this->btnDrawImage); this->pnlGraphics->Controls->Add(this->btnTranslatePoints); this->pnlGraphics->Controls->Add(this->btnDrawLine); this->pnlGraphics->Dock = System::Windows::Forms::DockStyle::Fill; this->pnlGraphics->Location = System::Drawing::Point(3, 3); this->pnlGraphics->Name = L"pnlGraphics"; this->pnlGraphics->Size = System::Drawing::Size(422, 570); this->pnlGraphics->TabIndex = 1; // // btnDrawHouse // this->btnDrawHouse->Location = System::Drawing::Point(3, 90); this->btnDrawHouse->Name = L"btnDrawHouse"; this->btnDrawHouse->Size = System::Drawing::Size(75, 23); this->btnDrawHouse->TabIndex = 3; this->btnDrawHouse->Text = L"Draw House"; this->btnDrawHouse->UseVisualStyleBackColor = true; this->btnDrawHouse->Click += gcnew System::EventHandler(this, &MainForm::btnDrawHouse_Click); // // btnDrawImage // this->btnDrawImage->Location = System::Drawing::Point(3, 61); this->btnDrawImage->Name = L"btnDrawImage"; this->btnDrawImage->Size = System::Drawing::Size(75, 23); this->btnDrawImage->TabIndex = 2; this->btnDrawImage->Text = L"Draw Image"; this->btnDrawImage->UseVisualStyleBackColor = true; this->btnDrawImage->Click += gcnew System::EventHandler(this, &MainForm::btnDrawImage_Click); // // btnTranslatePoints // this->btnTranslatePoints->Location = System::Drawing::Point(3, 32); this->btnTranslatePoints->Name = L"btnTranslatePoints"; this->btnTranslatePoints->Size = System::Drawing::Size(75, 23); this->btnTranslatePoints->TabIndex = 1; this->btnTranslatePoints->Text = L"Zoom"; this->btnTranslatePoints->UseVisualStyleBackColor = true; this->btnTranslatePoints->Click += gcnew System::EventHandler(this, &MainForm::btnTranslatePoints_Click); // // btnDrawLine // this->btnDrawLine->Location = System::Drawing::Point(3, 3); this->btnDrawLine->Name = L"btnDrawLine"; this->btnDrawLine->Size = System::Drawing::Size(75, 23); this->btnDrawLine->TabIndex = 0; this->btnDrawLine->Text = L"Draw Line"; this->btnDrawLine->UseVisualStyleBackColor = true; this->btnDrawLine->Click += gcnew System::EventHandler(this, &MainForm::btnDrawLine_Click); // // tabPage5 // this->tabPage5->Controls->Add(this->tableLayoutPanel4); this->tabPage5->Location = System::Drawing::Point(4, 22); this->tabPage5->Name = L"tabPage5"; this->tabPage5->Padding = System::Windows::Forms::Padding(3); this->tabPage5->Size = System::Drawing::Size(862, 582); this->tabPage5->TabIndex = 4; this->tabPage5->Text = L"Own Components"; this->tabPage5->UseVisualStyleBackColor = true; // // tableLayoutPanel4 // this->tableLayoutPanel4->ColumnCount = 2; this->tableLayoutPanel4->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel4->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel4->Controls->Add(this->textBox2, 1, 0); this->tableLayoutPanel4->Controls->Add(this->panel5, 0, 0); this->tableLayoutPanel4->Controls->Add(this->panel6, 0, 1); this->tableLayoutPanel4->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel4->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel4->Name = L"tableLayoutPanel4"; this->tableLayoutPanel4->RowCount = 2; this->tableLayoutPanel4->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 22.91667F))); this->tableLayoutPanel4->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 77.08334F))); this->tableLayoutPanel4->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel4->TabIndex = 0; // // textBox2 // this->textBox2->Dock = System::Windows::Forms::DockStyle::Fill; this->textBox2->Location = System::Drawing::Point(431, 3); this->textBox2->Multiline = true; this->textBox2->Name = L"textBox2"; this->textBox2->Size = System::Drawing::Size(422, 125); this->textBox2->TabIndex = 0; // // panel5 // this->panel5->Dock = System::Windows::Forms::DockStyle::Fill; this->panel5->Location = System::Drawing::Point(3, 3); this->panel5->Name = L"panel5"; this->panel5->Size = System::Drawing::Size(422, 125); this->panel5->TabIndex = 1; // // panel6 // this->panel6->Dock = System::Windows::Forms::DockStyle::Fill; this->panel6->Location = System::Drawing::Point(3, 134); this->panel6->Name = L"panel6"; this->panel6->Size = System::Drawing::Size(422, 439); this->panel6->TabIndex = 2; // // tabPage6 // this->tabPage6->Controls->Add(this->tableLayoutPanel5); this->tabPage6->Location = System::Drawing::Point(4, 22); this->tabPage6->Name = L"tabPage6"; this->tabPage6->Padding = System::Windows::Forms::Padding(3); this->tabPage6->Size = System::Drawing::Size(862, 582); this->tabPage6->TabIndex = 5; this->tabPage6->Text = L"Trees"; this->tabPage6->UseVisualStyleBackColor = true; // // tableLayoutPanel5 // this->tableLayoutPanel5->ColumnCount = 2; this->tableLayoutPanel5->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel5->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel5->Controls->Add(this->panel8, 0, 1); this->tableLayoutPanel5->Controls->Add(this->txtTreeView, 1, 0); this->tableLayoutPanel5->Controls->Add(this->treeView1, 0, 0); this->tableLayoutPanel5->Controls->Add(this->panel7, 1, 1); this->tableLayoutPanel5->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel5->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel5->Name = L"tableLayoutPanel5"; this->tableLayoutPanel5->RowCount = 2; this->tableLayoutPanel5->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 55.20833F))); this->tableLayoutPanel5->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 44.79167F))); this->tableLayoutPanel5->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel5->TabIndex = 1; // // panel8 // this->panel8->Controls->Add(this->btnChangeRegexInRegexTextBox); this->panel8->Controls->Add(this->txtRegexExpr); this->panel8->Controls->Add(this->txtRegex); this->panel8->Controls->Add(this->btnRegex); this->panel8->Dock = System::Windows::Forms::DockStyle::Fill; this->panel8->Location = System::Drawing::Point(3, 320); this->panel8->Name = L"panel8"; this->panel8->Size = System::Drawing::Size(422, 253); this->panel8->TabIndex = 2; // // btnChangeRegexInRegexTextBox // this->btnChangeRegexInRegexTextBox->Location = System::Drawing::Point(3, 72); this->btnChangeRegexInRegexTextBox->Name = L"btnChangeRegexInRegexTextBox"; this->btnChangeRegexInRegexTextBox->Size = System::Drawing::Size(103, 23); this->btnChangeRegexInRegexTextBox->TabIndex = 4; this->btnChangeRegexInRegexTextBox->Text = L"Change Regex"; this->btnChangeRegexInRegexTextBox->UseVisualStyleBackColor = true; this->btnChangeRegexInRegexTextBox->Click += gcnew System::EventHandler(this, &MainForm::btnChangeRegexInRegexTextBox_Click); // // txtRegexExpr // this->txtRegexExpr->Location = System::Drawing::Point(3, 6); this->txtRegexExpr->Name = L"txtRegexExpr"; this->txtRegexExpr->Size = System::Drawing::Size(416, 20); this->txtRegexExpr->TabIndex = 6; this->txtRegexExpr->Text = L"^([\\+][0-9]{1,3}[ \\.\\-])\?([\\(]{1}[0-9]{1,6}[\\)])\?([0-9 \\.\\-\\/]{3,20})((x|ext|exte" L"nsion)[ ]\?[0-9]{1,4})\?$"; // // txtRegex // this->txtRegex->Location = System::Drawing::Point(112, 43); this->txtRegex->Name = L"txtRegex"; this->txtRegex->Size = System::Drawing::Size(307, 20); this->txtRegex->TabIndex = 5; this->txtRegex->Text = L"+49 (0) 123 456789"; // // btnRegex // this->btnRegex->Location = System::Drawing::Point(3, 43); this->btnRegex->Name = L"btnRegex"; this->btnRegex->Size = System::Drawing::Size(103, 23); this->btnRegex->TabIndex = 4; this->btnRegex->Text = L"Regex"; this->btnRegex->UseVisualStyleBackColor = true; this->btnRegex->Click += gcnew System::EventHandler(this, &MainForm::btnRegex_Click); // // txtTreeView // this->txtTreeView->Dock = System::Windows::Forms::DockStyle::Fill; this->txtTreeView->Location = System::Drawing::Point(431, 3); this->txtTreeView->Multiline = true; this->txtTreeView->Name = L"txtTreeView"; this->txtTreeView->Size = System::Drawing::Size(422, 311); this->txtTreeView->TabIndex = 0; // // treeView1 // this->treeView1->Dock = System::Windows::Forms::DockStyle::Fill; this->treeView1->Location = System::Drawing::Point(3, 3); this->treeView1->Name = L"treeView1"; treeNode1->Name = L"Knoten7"; treeNode1->Text = L"Knoten7"; treeNode2->Name = L"Knoten8"; treeNode2->Text = L"Knoten8"; treeNode3->Name = L"Knoten9"; treeNode3->Text = L"Knoten9"; treeNode4->Name = L"Knoten15"; treeNode4->Text = L"Knoten15"; treeNode5->Name = L"Knoten16"; treeNode5->Text = L"Knoten16"; treeNode6->Name = L"Knoten21"; treeNode6->Text = L"Knoten21"; treeNode7->Name = L"Knoten22"; treeNode7->Text = L"Knoten22"; treeNode8->Name = L"Knoten26"; treeNode8->Text = L"Knoten26"; treeNode9->Name = L"Knoten27"; treeNode9->Text = L"Knoten27"; treeNode10->Name = L"Knoten28"; treeNode10->Text = L"Knoten28"; treeNode11->Name = L"Knoten29"; treeNode11->Text = L"Knoten29"; treeNode12->Name = L"Knoten30"; treeNode12->Text = L"Knoten30"; treeNode13->Name = L"Knoten31"; treeNode13->Text = L"Knoten31"; treeNode14->Name = L"Knoten32"; treeNode14->Text = L"Knoten32"; treeNode15->Name = L"Knoten33"; treeNode15->Text = L"Knoten33"; treeNode16->Name = L"Knoten34"; treeNode16->Text = L"Knoten34"; treeNode17->Name = L"Knoten23"; treeNode17->Text = L"Knoten23"; treeNode18->Name = L"Knoten24"; treeNode18->Text = L"Knoten24"; treeNode19->Name = L"Knoten25"; treeNode19->Text = L"Knoten25"; treeNode20->Name = L"Knoten17"; treeNode20->Text = L"Knoten17"; treeNode21->Name = L"Knoten18"; treeNode21->Text = L"Knoten18"; treeNode22->Name = L"Knoten19"; treeNode22->Text = L"Knoten19"; treeNode23->Name = L"Knoten20"; treeNode23->Text = L"Knoten20"; treeNode24->Name = L"Knoten10"; treeNode24->Text = L"Knoten10"; treeNode25->Name = L"Knoten11"; treeNode25->Text = L"Knoten11"; treeNode26->Name = L"Knoten12"; treeNode26->Text = L"Knoten12"; treeNode27->Name = L"Knoten13"; treeNode27->Text = L"Knoten13"; treeNode28->Name = L"Knoten14"; treeNode28->Text = L"Knoten14"; treeNode29->Name = L"Knoten0"; treeNode29->Text = L"Knoten0"; this->treeView1->Nodes->AddRange(gcnew cli::array< System::Windows::Forms::TreeNode^ >(1) { treeNode29 }); this->treeView1->Size = System::Drawing::Size(422, 311); this->treeView1->TabIndex = 3; this->treeView1->AfterSelect += gcnew System::Windows::Forms::TreeViewEventHandler(this, &MainForm::treeView1_AfterSelect); // // panel7 // this->panel7->Controls->Add(this->btnDriveInfo); this->panel7->Controls->Add(this->btnWalkTreeViewRecursive); this->panel7->Controls->Add(this->btnRecursion); this->panel7->Controls->Add(this->btnReadDirectories); this->panel7->Controls->Add(this->btnRemoveTreeNOde); this->panel7->Controls->Add(this->btnAddTreeNodeToTreeView); this->panel7->Dock = System::Windows::Forms::DockStyle::Fill; this->panel7->Location = System::Drawing::Point(431, 320); this->panel7->Name = L"panel7"; this->panel7->Size = System::Drawing::Size(422, 253); this->panel7->TabIndex = 4; // // btnDriveInfo // this->btnDriveInfo->Location = System::Drawing::Point(3, 119); this->btnDriveInfo->Name = L"btnDriveInfo"; this->btnDriveInfo->Size = System::Drawing::Size(103, 23); this->btnDriveInfo->TabIndex = 5; this->btnDriveInfo->Text = L"DriveInfo"; this->btnDriveInfo->UseVisualStyleBackColor = true; this->btnDriveInfo->Click += gcnew System::EventHandler(this, &MainForm::btnDriveInfo_Click); // // btnWalkTreeViewRecursive // this->btnWalkTreeViewRecursive->Location = System::Drawing::Point(3, 72); this->btnWalkTreeViewRecursive->Name = L"btnWalkTreeViewRecursive"; this->btnWalkTreeViewRecursive->Size = System::Drawing::Size(103, 23); this->btnWalkTreeViewRecursive->TabIndex = 4; this->btnWalkTreeViewRecursive->Text = L"Tree Recursive"; this->btnWalkTreeViewRecursive->UseVisualStyleBackColor = true; this->btnWalkTreeViewRecursive->Click += gcnew System::EventHandler(this, &MainForm::btnWalkTreeViewRecursive_Click); // // btnRecursion // this->btnRecursion->Location = System::Drawing::Point(220, 3); this->btnRecursion->Name = L"btnRecursion"; this->btnRecursion->Size = System::Drawing::Size(88, 23); this->btnRecursion->TabIndex = 3; this->btnRecursion->Text = L"recursion"; this->btnRecursion->UseVisualStyleBackColor = true; this->btnRecursion->Click += gcnew System::EventHandler(this, &MainForm::btnRecursion_Click); // // btnReadDirectories // this->btnReadDirectories->Location = System::Drawing::Point(97, 32); this->btnReadDirectories->Name = L"btnReadDirectories"; this->btnReadDirectories->Size = System::Drawing::Size(103, 23); this->btnReadDirectories->TabIndex = 2; this->btnReadDirectories->Text = L"Read Directrories"; this->btnReadDirectories->UseVisualStyleBackColor = true; this->btnReadDirectories->Click += gcnew System::EventHandler(this, &MainForm::btnReadDirectories_Click); // // btnRemoveTreeNOde // this->btnRemoveTreeNOde->Location = System::Drawing::Point(97, 3); this->btnRemoveTreeNOde->Name = L"btnRemoveTreeNOde"; this->btnRemoveTreeNOde->Size = System::Drawing::Size(117, 23); this->btnRemoveTreeNOde->TabIndex = 1; this->btnRemoveTreeNOde->Text = L"Remove TreeNode"; this->btnRemoveTreeNOde->UseVisualStyleBackColor = true; this->btnRemoveTreeNOde->Click += gcnew System::EventHandler(this, &MainForm::btnRemoveTreeNOde_Click); // // btnAddTreeNodeToTreeView // this->btnAddTreeNodeToTreeView->Location = System::Drawing::Point(3, 3); this->btnAddTreeNodeToTreeView->Name = L"btnAddTreeNodeToTreeView"; this->btnAddTreeNodeToTreeView->Size = System::Drawing::Size(88, 23); this->btnAddTreeNodeToTreeView->TabIndex = 0; this->btnAddTreeNodeToTreeView->Text = L"Add TreeNode"; this->btnAddTreeNodeToTreeView->UseVisualStyleBackColor = true; this->btnAddTreeNodeToTreeView->Click += gcnew System::EventHandler(this, &MainForm::btnAddTreeNodeToTreeView_Click); // // timer1 // this->timer1->Interval = 1000; this->timer1->Tick += gcnew System::EventHandler(this, &MainForm::timer1_Tick); // // menuStrip1 // this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) { this->toolStripMenuItem1, this->toolStripMenuItem3, this->toolStripMenuItem4 }); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->Size = System::Drawing::Size(870, 24); this->menuStrip1->TabIndex = 5; this->menuStrip1->Text = L"menuStrip1"; // // toolStripMenuItem1 // this->toolStripMenuItem1->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(5) { this->toolStripMenuItem2, this->toolStripSeparator1, this->mnuSaveFileDialog, this->mnuRichtextBox, this->mnuFolderBrowser }); this->toolStripMenuItem1->Name = L"toolStripMenuItem1"; this->toolStripMenuItem1->Size = System::Drawing::Size(46, 20); this->toolStripMenuItem1->Text = L"Datei"; // // toolStripMenuItem2 // this->toolStripMenuItem2->Name = L"toolStripMenuItem2"; this->toolStripMenuItem2->Size = System::Drawing::Size(190, 22); this->toolStripMenuItem2->Text = L"Öffnen"; this->toolStripMenuItem2->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click); // // toolStripSeparator1 // this->toolStripSeparator1->Name = L"toolStripSeparator1"; this->toolStripSeparator1->Size = System::Drawing::Size(187, 6); // // mnuSaveFileDialog // this->mnuSaveFileDialog->Name = L"mnuSaveFileDialog"; this->mnuSaveFileDialog->Size = System::Drawing::Size(190, 22); this->mnuSaveFileDialog->Text = L"Speichern"; this->mnuSaveFileDialog->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click); // // mnuRichtextBox // this->mnuRichtextBox->Name = L"mnuRichtextBox"; this->mnuRichtextBox->Size = System::Drawing::Size(190, 22); this->mnuRichtextBox->Text = L"Richtextbox Speichern"; this->mnuRichtextBox->Click += gcnew System::EventHandler(this, &MainForm::mnuRichtextBox_Click); // // mnuFolderBrowser // this->mnuFolderBrowser->Name = L"mnuFolderBrowser"; this->mnuFolderBrowser->Size = System::Drawing::Size(190, 22); this->mnuFolderBrowser->Text = L"FolderBrowserDialog"; this->mnuFolderBrowser->Click += gcnew System::EventHandler(this, &MainForm::mnuFolderBrowser_Click); // // toolStripMenuItem3 // this->toolStripMenuItem3->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) { this->mnuFarben, this->mnuSchriftart }); this->toolStripMenuItem3->Name = L"toolStripMenuItem3"; this->toolStripMenuItem3->Size = System::Drawing::Size(90, 20); this->toolStripMenuItem3->Text = L"Einstellungen"; // // mnuFarben // this->mnuFarben->Name = L"mnuFarben"; this->mnuFarben->Size = System::Drawing::Size(122, 22); this->mnuFarben->Text = L"Farben"; this->mnuFarben->Click += gcnew System::EventHandler(this, &MainForm::mnuFarben_Click); // // mnuSchriftart // this->mnuSchriftart->Name = L"mnuSchriftart"; this->mnuSchriftart->Size = System::Drawing::Size(122, 22); this->mnuSchriftart->Text = L"Schriftart"; this->mnuSchriftart->Click += gcnew System::EventHandler(this, &MainForm::mnuSchriftart_Click); // // toolStripMenuItem4 // this->toolStripMenuItem4->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(4) { this->mnuButtonsHerstellen, this->mnuListControls, this->mnuTextBoxenHerstellen, this->mnuRefreshTreeView }); this->toolStripMenuItem4->Name = L"toolStripMenuItem4"; this->toolStripMenuItem4->Size = System::Drawing::Size(54, 20); this->toolStripMenuItem4->Text = L"Debug"; // // mnuButtonsHerstellen // this->mnuButtonsHerstellen->Name = L"mnuButtonsHerstellen"; this->mnuButtonsHerstellen->Size = System::Drawing::Size(198, 22); this->mnuButtonsHerstellen->Text = L"Buttons herstellen"; this->mnuButtonsHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuButtonsHerstellen_Click); // // mnuListControls // this->mnuListControls->Name = L"mnuListControls"; this->mnuListControls->Size = System::Drawing::Size(198, 22); this->mnuListControls->Text = L"Liste Controls tabPage2"; this->mnuListControls->Click += gcnew System::EventHandler(this, &MainForm::mnuListControls_Click); // // mnuTextBoxenHerstellen // this->mnuTextBoxenHerstellen->Name = L"mnuTextBoxenHerstellen"; this->mnuTextBoxenHerstellen->Size = System::Drawing::Size(198, 22); this->mnuTextBoxenHerstellen->Text = L"TextBoxen herstellen"; this->mnuTextBoxenHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuTextBoxenHerstellen_Click); // // openFileDialog1 // this->openFileDialog1->FileName = L"openFileDialog1"; // // fontDialog1 // this->fontDialog1->ShowColor = true; // // tabPage7 // this->tabPage7->Controls->Add(this->tableLayoutPanel6); this->tabPage7->Location = System::Drawing::Point(4, 22); this->tabPage7->Name = L"tabPage7"; this->tabPage7->Padding = System::Windows::Forms::Padding(3); this->tabPage7->Size = System::Drawing::Size(862, 582); this->tabPage7->TabIndex = 6; this->tabPage7->Text = L"Explorer"; this->tabPage7->UseVisualStyleBackColor = true; // // tableLayoutPanel6 // this->tableLayoutPanel6->ColumnCount = 2; this->tableLayoutPanel6->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 49.41589F))); this->tableLayoutPanel6->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50.58411F))); this->tableLayoutPanel6->Controls->Add(this->trvDirectories, 0, 0); this->tableLayoutPanel6->Controls->Add(this->lsvFiles, 1, 0); this->tableLayoutPanel6->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel6->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel6->Name = L"tableLayoutPanel6"; this->tableLayoutPanel6->RowCount = 1; this->tableLayoutPanel6->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel6->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel6->TabIndex = 0; // // trvDirectories // this->trvDirectories->Dock = System::Windows::Forms::DockStyle::Fill; this->trvDirectories->Location = System::Drawing::Point(3, 3); this->trvDirectories->Name = L"trvDirectories"; this->trvDirectories->Size = System::Drawing::Size(417, 570); this->trvDirectories->TabIndex = 0; // // lsvFiles // this->lsvFiles->Dock = System::Windows::Forms::DockStyle::Fill; this->lsvFiles->Location = System::Drawing::Point(426, 3); this->lsvFiles->Name = L"lsvFiles"; this->lsvFiles->Size = System::Drawing::Size(427, 570); this->lsvFiles->TabIndex = 1; this->lsvFiles->UseCompatibleStateImageBehavior = false; // // mnuRefreshTreeView // this->mnuRefreshTreeView->Name = L"mnuRefreshTreeView"; this->mnuRefreshTreeView->Size = System::Drawing::Size(198, 22); this->mnuRefreshTreeView->Text = L"Refresh ExplorerTree"; this->mnuRefreshTreeView->Click += gcnew System::EventHandler(this, &MainForm::mnuRefreshTreeView_Click); // // MainForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(870, 632); this->Controls->Add(this->tabControl1); this->Controls->Add(this->menuStrip1); this->MainMenuStrip = this->menuStrip1; this->Name = L"MainForm"; this->Text = L"MainForm"; this->tableLayoutPanel1->ResumeLayout(false); this->tableLayoutPanel1->PerformLayout(); this->contextMenuStrip1->ResumeLayout(false); this->panel1->ResumeLayout(false); this->panel2->ResumeLayout(false); this->panel2->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->EndInit(); this->groupBox1->ResumeLayout(false); this->groupBox1->PerformLayout(); this->panel3->ResumeLayout(false); this->panel3->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit(); this->tabControl1->ResumeLayout(false); this->tabPage1->ResumeLayout(false); this->tabPage2->ResumeLayout(false); this->tableLayoutPanel2->ResumeLayout(false); this->tableLayoutPanel2->PerformLayout(); this->panel4->ResumeLayout(false); this->tabPage3->ResumeLayout(false); this->tabPage3->PerformLayout(); this->tabPage4->ResumeLayout(false); this->tableLayoutPanel3->ResumeLayout(false); this->pnlDrawing->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->EndInit(); this->pnlGraphics->ResumeLayout(false); this->tabPage5->ResumeLayout(false); this->tableLayoutPanel4->ResumeLayout(false); this->tableLayoutPanel4->PerformLayout(); this->tabPage6->ResumeLayout(false); this->tableLayoutPanel5->ResumeLayout(false); this->tableLayoutPanel5->PerformLayout(); this->panel8->ResumeLayout(false); this->panel8->PerformLayout(); this->panel7->ResumeLayout(false); this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); this->tabPage7->ResumeLayout(false); this->tableLayoutPanel6->ResumeLayout(false); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion void initialiseComponents() { this->btnBlinkinButton = gcnew BlinkinButton(250, System::Drawing::Color::Coral, System::Drawing::Color::CornflowerBlue); // // btnBlinkinButton // this->btnBlinkinButton->Location = System::Drawing::Point(3, 3); this->btnBlinkinButton->Name = L"btnBlinkinButton"; this->btnBlinkinButton->Size = System::Drawing::Size(75, 23); this->btnBlinkinButton->TabIndex = 0; this->btnBlinkinButton->Text = L"button1"; this->btnBlinkinButton->UseVisualStyleBackColor = true; this->btnBlinkinButton->Click += gcnew System::EventHandler(this, &GUI::MainForm::BlinkinButtonOnClick); this->btnBlinkinButton->MouseHover += gcnew System::EventHandler(this, &GUI::MainForm::BlinkinButtonOnMouseHover); this->panel5->Controls->Add(this->btnBlinkinButton); this->pnlHouse = (gcnew DrawingPanel); // // pnlHouse // this->pnlHouse->Location = System::Drawing::Point(25, 25); this->pnlHouse->Name = L"pnlHouse"; this->pnlHouse->Size = System::Drawing::Size(300, 300); this->pnlHouse->TabIndex = 0; this->panel6->Controls->Add(this->pnlHouse); this->txtAutoRegexMatcher = (gcnew RegexTextBox); // // txtAutoRegexMatcher // this->txtAutoRegexMatcher->Location = System::Drawing::Point(3, 117); this->txtAutoRegexMatcher->Name = L"txtAutoRegexMatcher"; this->txtAutoRegexMatcher->Size = System::Drawing::Size(307, 20); this->txtAutoRegexMatcher->TabIndex = 7; this->txtAutoRegexMatcher->Text = L"+49 (0) 123 456789"; this->panel8->Controls->Add(this->txtAutoRegexMatcher); } private: System::Void BlinkinButtonOnMouseHover(System::Object^ sender, System::EventArgs^ e) { logger->Debug("I got hovered from the form !!!"); } private: System::Void BlinkinButtonOnClick(System::Object^ sender, System::EventArgs^ e) { this->btnBlinkinButton->changeConfig(125, Color::Yellow, Color::OrangeRed); } private: System::Void cmdChangeFormColor_Click(System::Object^ sender, System::EventArgs^ e) { cmdChangeFormColor->BackColor = System::Drawing::Color(Color::HotPink); this->BackColor = System::Drawing::Color(Color::GreenYellow); } private: System::Void btnChangeTab_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(tabControl1->SelectedIndex.ToString()); tabControl1->SelectedIndex = 1; tabControl1->SelectTab(1); textBox1->AppendText(textBox1->GetType()->ToString()); } private: System::Void btnCheckbox_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(checkBox1->Checked.ToString()); if (checkBox1->Checked) { System::Windows::Forms::DialogResult dR = MessageBox::Show("Oh nooooo, I'm checked !\r\n", "Please click !", MessageBoxButtons::YesNoCancel, MessageBoxIcon::Warning); if (dR == System::Windows::Forms::DialogResult::Cancel) { System::Diagnostics::Debug::WriteLine("User clicked cancel"); textBox1->AppendText("User cancelled the action !\r\n"); } else if (dR == System::Windows::Forms::DialogResult::Yes) { System::Diagnostics::Debug::WriteLine("User clicked yes"); textBox1->AppendText("You're amazing !!\r\n"); } else if (dR == System::Windows::Forms::DialogResult::No) { System::Diagnostics::Debug::WriteLine("User clicked no"); textBox1->AppendText("Whaaaaat ??!!\r\n"); } } else { MessageBox::Show("Pleaseeeeee check me !\r\n"); } } private: System::Void checkBox1_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("You changed the checkBox1 to " + checkBox1->Checked.ToString() + "\r\n"); } RadioButton^ gimmeActiveRadioButton() { if (radioButton1->Checked) { return radioButton1; } else if (radioButton2->Checked) { return radioButton2; } else if (radioButton3->Checked) { return radioButton3; } } private: System::Void btnRadioButton_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("Radiobutton : " + gimmeActiveRadioButton()->Name); } private: System::Void btnComboboxValue_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void cmbBlubb_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(cmbBlubb->Text); } private: System::Void btnComboAddItem_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->Add("WoW"); } private: System::Void btnComboremoveItem_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->RemoveAt(2); } private: System::Void btnComboInsert_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->Insert(2, "Test"); } private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { int selectedItemsCount = listBox1->SelectedItems->Count; for (int i = 0;i < selectedItemsCount;i++) { textBox1->AppendText(listBox1->SelectedItems[i]->ToString() + "\r\n"); } } private: System::Void btnNextStep_Click(System::Object^ sender, System::EventArgs^ e) { if (step == 0) { txtQuestions->Clear(); txtQuestions->AppendText("Wie heisst Du ?\r\n"); txtAnswers->Clear(); } else if (step == 1) { txtQuestions->AppendText("Du heisst also " + txtAnswers->Text + " !\r\n"); antwort1 = txtAnswers->Text; txtQuestions->AppendText("Wie alt bist Du ?\r\n"); txtAnswers->Clear(); } else if (step == 2) { txtQuestions->AppendText("Du bist also " + txtAnswers->Text + " alt !\r\n"); antwort2 = txtAnswers->Text; txtQuestions->AppendText("Was ist Deine Lieblingsfarbe ?\r\n"); txtAnswers->Clear(); } else if (step == 3) { txtQuestions->AppendText("Deine Lieblingsfarbe ist also " + txtAnswers->Text + " !\r\n"); antwort3 = txtAnswers->Text; txtQuestions->AppendText("Danke für's Gespräch !\r\n"); txtAnswers->Clear(); } step++; } private: System::Void btnChangeFromAnotherClass_Click(System::Object^ sender, System::EventArgs^ e) { t = gcnew Test(); //t->changeTextBoxText(this); } private: System::Void btnStartProgress_Click(System::Object^ sender, System::EventArgs^ e) { //for(int counter = 0;counter <=100 ;counter++){ // System::Threading::Thread::Sleep(500); // progressBar1->Value = counter; //} progress = 0; timer1->Enabled = true; } private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) { if (progress <= 100) { progressBar1->Value = progress; progress += 5; } else { timer1->Enabled = false; } } private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(trackBar1->Value + "\r\n"); } private: System::Void toolStripMenuItem2_Click(System::Object^ sender, System::EventArgs^ e) { openFileDialog1->Filter = "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"; openFileDialog1->FilterIndex = 2; openFileDialog1->InitialDirectory = "d:\\"; System::Windows::Forms::DialogResult dialogResult = openFileDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { if (openFileDialog1->Multiselect == true) { for each(String^ einFileName in openFileDialog1->FileNames) { textBox1->AppendText(einFileName + "\r\n"); } } else { textBox1->AppendText(openFileDialog1->FileName + "\r\n"); String^ inhaltDerDatei = System::IO::File::ReadAllText(openFileDialog1->FileName); textBox1->AppendText(inhaltDerDatei); } } else { textBox1->AppendText("Datei auswählen !\r\n"); } } private: System::Void mnuFarben_Click(System::Object^ sender, System::EventArgs^ e) { System::Windows::Forms::DialogResult dialogResult = colorDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { textBox1->BackColor = colorDialog1->Color; } } private: System::Void mnuSaveFileDialog_Click(System::Object^ sender, System::EventArgs^ e) { saveFileDialog1->Filter = "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"; saveFileDialog1->FilterIndex = 2; saveFileDialog1->InitialDirectory = "d:\\"; System::Windows::Forms::DialogResult dialogResult = saveFileDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { System::IO::File::WriteAllText(saveFileDialog1->FileName, textBox1->Text); } } private: System::Void mnuSchriftart_Click(System::Object^ sender, System::EventArgs^ e) { System::Windows::Forms::DialogResult dialogResult = fontDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { textBox1->Font = fontDialog1->Font; textBox1->ForeColor = fontDialog1->Color; } } private: System::Void mnuRichtextBox_Click(System::Object^ sender, System::EventArgs^ e) { richTextBox1->SaveFile("d:\\richtexttest.rtf"); } private: System::Void mnuFolderBrowser_Click(System::Object^ sender, System::EventArgs^ e) { folderBrowserDialog1->ShowDialog(); } private: System::Void mnuClearText_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->Clear(); } private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e) { DateTime t = dateTimePicker1->Value; DateTime aktuelleZeit = DateTime::Now; textBox1->AppendText(t.ToLongDateString() + "\n"); textBox1->AppendText(aktuelleZeit.ToLongTimeString() + "\n"); TimeSpan dauer(10, 10, 10, 10); DateTime summe = t.Add(dauer); } private: System::Void mnuButtonsHerstellen_Click(System::Object^ sender, System::EventArgs^ e) { for (int counter = 0; counter < 10;counter++) { System::Windows::Forms::Button^ btnDynamicButton = gcnew System::Windows::Forms::Button; btnDynamicButton->Location = System::Drawing::Point(0, 0 + 25 * counter); btnDynamicButton->Name = L"btnDynamicButton" + counter; btnDynamicButton->Size = System::Drawing::Size(109, 23); btnDynamicButton->TabIndex = 8; btnDynamicButton->Text = L"I'm dynamic " + counter; btnDynamicButton->UseVisualStyleBackColor = true; btnDynamicButton->Click += gcnew System::EventHandler(this, &MainForm::dynamicButtonsClick); tabPage2->Controls->Add(btnDynamicButton); } } private: System::Void mnuListControls_Click(System::Object^ sender, System::EventArgs^ e) { for each(Control^ control in tabPage2->Controls) { textBox1->AppendText(control->Name + "\n"); } } private: System::Void dynamicButtonsClick(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("Dynamic Button clicked !\t" + ((Button^)sender)->Name + "\n"); if (((Button^)sender)->Name == "btnDynamicButton3") { MessageBox::Show("Du hast den richtigen Button gedrückt !"); } } private: System::Void mnuTextBoxenHerstellen_Click(System::Object^ sender, System::EventArgs^ e) { createTextBoxes(); } void createTextBoxes() { for (int counter = 0;counter < 10;counter++) { TextBox^ dynamicTextBox = gcnew TextBox; dynamicTextBox->Location = System::Drawing::Point(200, 0 + 25 * counter); dynamicTextBox->Name = L"textBox" + counter; dynamicTextBox->ScrollBars = System::Windows::Forms::ScrollBars::Both; dynamicTextBox->TabIndex = 67; dynamicTextBox->TextChanged += gcnew System::EventHandler(this, &MainForm::dynamicTextBoxesTextChanged); tabPage2->Controls->Add(dynamicTextBox); } } private: System::Void dynamicTextBoxesTextChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(((TextBox^)sender)->Name + " TextChanged : " + ((TextBox^)sender)->Text + "\n"); } private: System::Void btnAddDoubles_Click(System::Object^ sender, System::EventArgs^ e) { double ersteZahl = Double::Parse(txtErsteZahl->Text); double zweiteZahl = Double::Parse(txtZweiteZahl->Text); double ergebnis = ersteZahl + zweiteZahl; textBox1->AppendText(ergebnis.ToString("N2")); } private: System::Void btnArrayList_Click(System::Object^ sender, System::EventArgs^ e) { ArrayList^ listeVonElementen = gcnew ArrayList; listeVonElementen->Add("Bli"); txtCollections->AppendText("\n:::" + listeVonElementen[0]->ToString() + "\n"); listeVonElementen->Add("Bla"); listeVonElementen->Add("Blubb"); listeVonElementen->Add("Yeah"); listeVonElementen->Add(this); listeVonElementen->Add(3); listeVonElementen->Add(gcnew Button); listeVonElementen->Remove("Bli"); txtCollections->AppendText(listeVonElementen->IndexOf("Yeah").ToString()); listeVonElementen->Insert(3, "Blubbbbbb"); listeVonElementen->Reverse(); for each(Object^ o in listeVonElementen) { txtCollections->AppendText(o->GetType() + " | " + o->ToString() + "\r\n"); } } private: System::Void btnQueue_Click(System::Object^ sender, System::EventArgs^ e) { System::Collections::Queue^ queue = gcnew System::Collections::Queue; queue->Enqueue("1"); queue->Enqueue("3"); queue->Enqueue("2"); queue->Enqueue("4"); txtCollections->Text += queue->Count.ToString(); int count = queue->Count; for (int counter = 1;counter <= count;counter++) { txtCollections->AppendText(queue->Dequeue()->ToString()); //NICHT rausnehmen, nur drauf schauen //txtCollections->AppendText(queue->Peek()->ToString()); } } private: System::Void btnStack_Click(System::Object^ sender, System::EventArgs^ e) { Stack^ stack = gcnew Stack; stack->Push("1"); //stack->Push(1); //stack->Push(this); stack->Push("2"); stack->Push("3"); stack->Push("4"); stack->Push("5"); int count = stack->Count; for (int counter = 0;counter < count;counter++) { txtCollections->AppendText((String^)stack->Pop()); } } private: System::Void btnSortedList_Click(System::Object^ sender, System::EventArgs^ e) { SortedList^ sortedList = gcnew SortedList; sortedList->Add(1, "Sieger"); //sortedList->Add(1, "Sieger"); -> Fehler, existiert schon sortedList->Add(3, "Drittplatzierter"); sortedList->Add(2, "Zweiter Sieger"); for each(int key in sortedList->Keys) { txtCollections->AppendText(key + " | " + sortedList[key] + "\r\n"); } SortedList^ sortedList1 = gcnew SortedList; DateTime d = DateTime(1971, 12, 12); sortedList1->Add(d, "Sieger3"); sortedList1->Add(DateTime(1970, 12, 12), "Sieger2"); sortedList1->Add(DateTime(1968, 12, 12), "Sieger1"); for each(DateTime key in sortedList1->Keys) { txtCollections->AppendText(key + " | " + sortedList1[key] + "\r\n"); } } private: System::Void btnHashtable_Click(System::Object^ sender, System::EventArgs^ e) { Hashtable^ openWith = gcnew Hashtable; // Add some elements to the hash table. There are no // duplicate keys, but some of the values are duplicates. openWith->Add("txt", "notepad.exe"); //openWith->Add("txt", "notepad.exe"); -> Fehler openWith->Add("bmp", "paint.exe"); openWith->Add("dib", "paint.exe"); openWith->Add("rtf", "wordpad.exe"); txtCollections->AppendText(openWith["txt"] + "\r\n"); openWith["rtf"] = "winword.exe"; //If the key "ht" doesn't exist, add entry to our Hashtable if (!openWith->ContainsKey("ht")) { openWith->Add("ht", "hypertrm.exe"); } for each(DictionaryEntry de in openWith) { txtCollections->AppendText(de.Key + " | " + de.Value + "\r\n"); } } private: System::Void btnList_Click(System::Object^ sender, System::EventArgs^ e) { //Fully qualified |Diamantoperator System::Collections::Generic::List<String^>^ phrases = gcnew System::Collections::Generic::List<String^>(); phrases->Add("Text"); phrases->Add("Text1"); phrases->Add("Text2"); phrases->Add("Text3"); //phrases->Add(34);-> Fehler for each(String^ oneElement in phrases) { txtCollections->AppendText(oneElement); } } private: System::Void btnArray_Click(System::Object^ sender, System::EventArgs^ e) { array<String^>^ myArr = { L"The", L"quick", L"brown", L"fox", L"jumps", L"over", L"the", L"lazy", L"dog" }; Array::Resize(myArr, myArr->Length + 5); array<Byte>^ buffer = gcnew array<Byte>(1024); ArrayList^ l = gcnew ArrayList(myArr); l->AddRange(myArr); array<String ^, 3> ^ my3DArray = gcnew array<String ^, 3>(3, 5, 6); my3DArray[0, 0, 0] = "Bla"; ArrayList^ zeile = gcnew ArrayList; ArrayList^ spalte = gcnew ArrayList; spalte->Add(zeile); ((ArrayList^)spalte[0])[0] = "j"; } private: System::Void btnBenchmark_Click(System::Object^ sender, System::EventArgs^ e) { int size = 10000000; ArrayList^ numbers = gcnew ArrayList; DateTime startTime = DateTime::Now; for (int counter = 0; counter < size; counter++) { numbers->Add(counter); } DateTime endTime = DateTime::Now; txtCollections->AppendText("\r\nCreation of 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; array<int>^ intArray = gcnew array<int>(size); for (int counter = 0; counter < size; counter++) { intArray[counter] = counter; } endTime = DateTime::Now; txtCollections->AppendText("\r\nCreation of 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; for (int counter = 0;counter < size;counter++) { int temp = (int)numbers[counter]; } endTime = DateTime::Now; txtCollections->AppendText("\r\nAccessing 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; for (int counter = 0;counter < size;counter++) { int temp = intArray[counter]; } endTime = DateTime::Now; txtCollections->AppendText("\r\nAccessing 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds); } private: System::Void btnDrawLine_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics(); System::Drawing::Pen^ penRed = gcnew System::Drawing::Pen(Color::Red); System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue); System::Drawing::Pen^ penGreen = gcnew System::Drawing::Pen(Color::Green); System::Drawing::Brush^ brushYellow = gcnew System::Drawing::SolidBrush(Color::Yellow); graphics->DrawLine(penRed, 0, 0, 100, 300); graphics->DrawLine(penBlue, 100, 200, 0, 0); graphics->DrawEllipse(penGreen, 20, 90, 40, 20); graphics->FillRectangle(brushYellow, 70, 70, 30, 60); } System::Drawing::Point lastPoint = Point(0, 0); ArrayList^ points; private: System::Void pnlDrawing_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics(); System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); // |Umrechnung |aktuelle Mouseposition Bildschirm System::Drawing::Point actualPosition = pnlDrawing->PointToClient(this->Cursor->Position); graphics->DrawLine(penBlack, lastPoint, actualPosition); lastPoint = actualPosition; points->Add(lastPoint); System::Diagnostics::Debug::WriteLine(actualPosition.ToString()); } private: System::Void pnlDrawing_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { drawLinesByPoints(e->Graphics); } void drawLinesByPoints(Graphics^ g) { System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); int pointsCount = points->Count; logger->Info("Amount of points in points :" + pointsCount); for (int counter = 0; counter < pointsCount - 1;counter++) { logger->Debug((Point)points[counter]); g->DrawLine(penBlack, (Point)points[counter], (Point)points[counter + 1]); } } void translatePoints(int factor) { logger->Debug("factor =" + factor); int pointsCount = points->Count; logger->Info("Amount of points in points :" + pointsCount); for (int counter = 0; counter < pointsCount - 1;counter++) { logger->Trace("old point:" + (Point)points[counter]); Point newPoint = Point(((Point)points[counter]).X * factor, ((Point)points[counter]).Y * factor); points[counter] = newPoint; logger->Trace("new point:" + newPoint); } } private: System::Void btnTranslatePoints_Click(System::Object^ sender, System::EventArgs^ e) { translatePoints(2); pnlDrawing->CreateGraphics()->Clear(Color::Gainsboro); pnlDrawing->Refresh(); } private: System::Void btnDrawImage_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); System::Drawing::Image^ image = Image::FromFile("d:\\spaghettimonster.jpg"); Graphics^ imageGraphics = Graphics::FromImage(image); imageGraphics->DrawLine(penBlack, 0, 0, 200, 200); Point ulCorner = Point(100, 0); pnlGraphics->CreateGraphics()->DrawImage(image, ulCorner); image->Save("d:\\spaghettimonster12.jpg"); } private: System::Void btnDrawHouse_Click(System::Object^ sender, System::EventArgs^ e) { for (double counter = 0.1;counter < 1;counter += 0.1) { drawHouse(pnlGraphics->CreateGraphics(), 0 + 20 * counter, 0 + 20 * counter, counter, counter); } } void drawHouse(Graphics^ graphics, int startPositionX, int startPositionY, double scaleFactorX, double scaleFactorY) { System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 300, 0, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 100, 200, 300, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 0, 300, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 100, 20, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 300, 20, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 300, 20, 400, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 100, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 300, 400, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 400, 300, scaleFactorX, scaleFactorY); } void drawSpecialLine(Graphics^ graphics, Pen^ pen, float startPositionX, float startPositionY, float x1, float y1, float x2, float y2, float scaleFactorX, float scaleFactorY) { graphics->DrawLine(pen, startPositionX + x1 * scaleFactorX, startPositionY + y1 * scaleFactorY, startPositionX + x2 * scaleFactorX, startPositionY + y2 * scaleFactorY); } private: System::Void btnDivide_Click(System::Object^ sender, System::EventArgs^ e) { double ersteZahl = double::Parse(txtErsteZahl->Text); double zweiteZahl = double::Parse(txtZweiteZahl->Text); try { divide(ersteZahl, zweiteZahl); } catch (TeilenDurch0Exception^ ex) { logger->Fatal(ex->Message); logger->Fatal("Zähler war : " + ex->zaehler); txtZweiteZahl->BackColor = Color::LightSalmon; } catch (Exception^ ex) { logger->Fatal(ex->Message); } finally{ //Aufräumarbeiten } } private: /// <summary>Divides two numbers (number1, number2) and returns the result as int /// </summary> /// <param name="number1">Is the numerator as <code>int</code></param> /// <param name="number2">Is the denominator as <code>int</code></param> /// <returns>The result of the division</returns> /// <exception cref="Notepad.TeilenDurch0Exception">Thrown when number2 == 0</exception> int divide(int number1, int number2) { if (number2 == 0) { TeilenDurch0Exception^ ex = gcnew TeilenDurch0Exception("Teilen durch 0 is nich !", number1); throw ex; } return number1 / number2; } private: System::Void btnAddTreeNodeToTreeView_Click(System::Object^ sender, System::EventArgs^ e) { treeView1->ExpandAll(); TreeNode^ anotherNode = gcnew TreeNode("I'm amazingly dynamic!"); anotherNode->Name = "I'm amazingly dynamic!"; treeView1->Nodes[0]->Nodes->Add(anotherNode); } private: System::Void treeView1_AfterSelect(System::Object^ sender, System::Windows::Forms::TreeViewEventArgs^ e) { txtTreeView->AppendText(e->Node->Name + "\r\n"); txtTreeView->AppendText("Parent : " + e->Node->Parent + "\r\n"); e->Node->BackColor = Color::LightSalmon; } private: System::Void btnRemoveTreeNOde_Click(System::Object^ sender, System::EventArgs^ e) { if (treeView1->SelectedNode) { treeView1->Nodes->Remove(treeView1->SelectedNode); } } private: System::Void btnReadDirectories_Click(System::Object^ sender, System::EventArgs^ e) { TreeNode^ root = gcnew TreeNode("d:\\"); for each(String^ oneDirectory in System::IO::Directory::GetDirectories("d:\\")) { TreeNode^ directoryNode = gcnew TreeNode(oneDirectory); root->Nodes->Add(directoryNode); } treeView1->Nodes->Add(root); } int fakultaet(int n) { logger->Trace("Einsprung"); logger->Trace("n=" + n); if (n == 1) { logger->Trace("Raussprung"); logger->Trace("n=" + n); return 1; } int result = n*fakultaet(n - 1); logger->Trace("result=" + result); logger->Trace("Raussprung"); return result; } //Fakultät 5! //5! = 5 * 4 * 3 * 2 * 1 private: System::Void btnRecursion_Click(System::Object^ sender, System::EventArgs^ e) { txtTreeView->AppendText(fakultaet(4).ToString()); } private: System::Void btnRegex_Click(System::Object^ sender, System::EventArgs^ e) { System::Text::RegularExpressions::Regex^ regex = gcnew System::Text::RegularExpressions::Regex(txtRegexExpr->Text); if (regex->IsMatch(txtRegex->Text)) { txtRegex->BackColor = Color::White; } else { txtRegex->BackColor = Color::LightSalmon; } } private: System::Void btnChangeRegexInRegexTextBox_Click(System::Object^ sender, System::EventArgs^ e) { this->txtAutoRegexMatcher->reconfigure(txtRegexExpr->Text, Color::LightPink); } private: System::Void btnWalkTreeViewRecursive_Click(System::Object^ sender, System::EventArgs^ e) { showTreeNodes(treeView1->Nodes[0], 0); } //Rekursion void showTreeNodes(TreeNode^ t, int level) { level++; logger->Trace(level + " : " + t->Name); for each(TreeNode^ tn in t->Nodes) { showTreeNodes(tn, level); } } private: System::Void btnDriveInfo_Click(System::Object^ sender, System::EventArgs^ e) { for each(System::IO::DriveInfo^ d in System::IO::DriveInfo::GetDrives()) { txtTreeView->AppendText(d->Name + "\r\n"); } } private: System::Void mnuRefreshTreeView_Click(System::Object^ sender, System::EventArgs^ e) { Type^ treeNodeType = TreeNode::typeid; treeView1->Nodes->AddRange(getDriveInfoTreeNodes()->ToArray(TreeNode)); } ArrayList^ getDriveInfoTreeNodes() { ArrayList^ driveInfoTreeNodes = gcnew ArrayList; for each(System::IO::DriveInfo^ d in System::IO::DriveInfo::GetDrives()) { TreeNode^ driveInfoTreeNode = gcnew TreeNode(d->Name); driveInfoTreeNodes->Add(driveInfoTreeNode); logger->Trace(d->Name); } return driveInfoTreeNodes; } }; }
[ "Alfa-Dozent@SB-U03-001" ]
Alfa-Dozent@SB-U03-001
9c7fd64205e8276c5b9640622b0ad8537664886e
ae474c46e47d8e5084bbc2b8aad44a59c5effad7
/TestCasesInSuits/CaseAndSuitForRayRender.h
1a07918c69bb04e753ef16528707c0de4e1e2546
[]
no_license
181847/LearningFundamentalsOfComputerGraphic
9bb3bd325dffa1131d3a1743f588b2e91a8c4bde
c4215f710853ebbc7c73f233ddc1df7931ed2f62
refs/heads/master
2020-03-23T03:35:33.703762
2019-07-26T15:52:38
2019-07-26T15:52:38
141,038,418
1
0
null
null
null
null
UTF-8
C++
false
false
841
h
#pragma once #include "CommonHeaders.h" #define CASE_NAME_IN_RAY_RENDER(RestClassName) CaseFor##RestClassName #define DECLARE_CASE_IN_RAY_RENDER_FOR(RestClassName, CaseName) \ class CASE_NAME_IN_RAY_RENDER(RestClassName) : public CaseForPipline\ {\ public:\ CASE_NAME_IN_RAY_RENDER(RestClassName)() :CaseForPipline(CaseName) {}\ virtual void Run() override;\ virtual std::wstring GetStoragePath() const override {return Super::GetStoragePath() + SUB_FOLDER;}\ protected:\ const std::wstring SUB_FOLDER = L"RayRender/";\ } DECLARE_CASE_IN_RAY_RENDER_FOR(InsideBoxesAndSphere, "render inside boxes and sphere"); DECLARE_CASE_IN_RAY_RENDER_FOR(TrasparentMat, "transparent material"); using SuitForRayRender = SuitForPipline< //CASE_NAME_IN_RAY_RENDER(InsideBoxesAndSphere), CASE_NAME_IN_RAY_RENDER(TrasparentMat) >;
97777fd74e98e30d2eded7935885abaf559dbfbd
f11ed31357628473e0bfb89902bc9c94157c6c59
/Vending_machine/Vending_machine/Machine.h
7c2e10549535b9f92dae842bf8dc3225fe3aaa4d
[]
no_license
ChouJustice/WinForm-Project
06da737d6e31578b257955c3c8917691c1777e6f
e923d7c1a70e3420664574a9bd3bcee074aa7135
refs/heads/master
2020-03-15T19:56:18.445743
2018-08-20T06:41:49
2018-08-20T06:41:49
132,320,836
0
0
null
null
null
null
UTF-8
C++
false
false
468
h
#pragma once #include "Goods.h" ref class Machine { private: array<Goods^> ^Sale_goods; int money; int balance; public: Machine(void); void setMoney(int); void setBalance(int); void plus_100(); void plus_50(); void plus_10(); void machine_initialization(void); void setName(int,System::String^); void setStock(int,int); void setPrice(int,int); System::String^ getName(int); int getStock(int); int getPrice(int); int getMoney(); int getBalance(); };
47f539eb399e8414e29683a7771c0f51d605b728
d0f37e29d49d76f15773f7d48fe3fa5f426de8f0
/cocos2d-x-3.6/cocos/ui/UILayoutComponent.cpp
f33581f2df4aaee6b8b3c9f58b422a57d2cf4160
[ "LicenseRef-scancode-warranty-disclaimer", "Zlib", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Libpng", "BSD-2-Clause-Views", "FTL", "Apache-2.0", "BSD-2-Clause" ]
permissive
SakuyaPrs/kirikiroid2lite
6898334ccceb5c911662e8062101daab73e15887
ee5890cf5b9714a9348cb6dd8fdbb0a7304c2cbe
refs/heads/master
2022-12-07T08:54:18.618074
2020-09-02T04:17:21
2020-09-02T04:17:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,599
cpp
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "UILayoutComponent.h" #include "2d/CCNode.h" #include "GUIDefine.h" #include "UIHelper.h" NS_CC_BEGIN namespace ui { LayoutComponent::LayoutComponent() :_horizontalEdge(HorizontalEdge::None) , _verticalEdge(VerticalEdge::None_) , _leftMargin(0) , _rightMargin(0) , _bottomMargin(0) , _topMargin(0) , _usingPositionPercentX(false) , _positionPercentX(0) , _usingPositionPercentY(false) , _positionPercentY(0) , _usingStretchWidth(false) , _usingStretchHeight(false) , _percentWidth(0) , _usingPercentWidth(false) , _percentHeight(0) , _usingPercentHeight(false) , _actived(true) , _isPercentOnly(false) { _name = __LAYOUT_COMPONENT_NAME; } LayoutComponent::~LayoutComponent() { } LayoutComponent* LayoutComponent::bindLayoutComponent(Node* node) { LayoutComponent * layout = (LayoutComponent*)node->getComponent(__LAYOUT_COMPONENT_NAME); if (layout != nullptr) return layout; layout = new (std::nothrow) LayoutComponent(); if (layout && layout->init()) { layout->autorelease(); node->addComponent(layout); return layout; } CC_SAFE_DELETE(layout); return nullptr; } bool LayoutComponent::init() { bool ret = true; do { if (!Component::init()) { ret = false; break; } //put layout component initalized code here } while (0); return ret; } Node* LayoutComponent::getOwnerParent() { Node* parent = _owner->getParent(); return parent; } void LayoutComponent::refreshHorizontalMargin() { Node* parent = this->getOwnerParent(); if (parent == nullptr) return; const Point& ownerPoint = _owner->getPosition(); const Point& ownerAnchor = _owner->getAnchorPoint(); const Size& ownerSize = _owner->getContentSize(); const Size& parentSize = parent->getContentSize(); _leftMargin = ownerPoint.x - ownerAnchor.x * ownerSize.width; _rightMargin = parentSize.width - (ownerPoint.x + (1 - ownerAnchor.x) * ownerSize.width); } void LayoutComponent::refreshVerticalMargin() { Node* parent = this->getOwnerParent(); if (parent == nullptr) return; const Point& ownerPoint = _owner->getPosition(); const Point& ownerAnchor = _owner->getAnchorPoint(); const Size& ownerSize = _owner->getContentSize(); const Size& parentSize = parent->getContentSize(); _bottomMargin = ownerPoint.y - ownerAnchor.y * ownerSize.height; _topMargin = parentSize.height - (ownerPoint.y + (1 - ownerAnchor.y) * ownerSize.height); } //OldVersion void LayoutComponent::setUsingPercentContentSize(bool isUsed) { _usingPercentWidth = _usingPercentHeight = isUsed; } bool LayoutComponent::getUsingPercentContentSize()const { return _usingPercentWidth && _usingPercentHeight; } void LayoutComponent::setPercentContentSize(const Vec2 &percent) { this->setPercentWidth(percent.x); this->setPercentHeight(percent.y); } Vec2 LayoutComponent::getPercentContentSize()const { Vec2 vec2=Vec2(_percentWidth,_percentHeight); return vec2; } //Position & Margin const Point& LayoutComponent::getAnchorPosition()const { return _owner->getAnchorPoint(); } void LayoutComponent::setAnchorPosition(const Point& point) { Rect oldRect = _owner->getBoundingBox(); _owner->setAnchorPoint(point); Rect newRect = _owner->getBoundingBox(); float offSetX = oldRect.origin.x - newRect.origin.x; float offSetY = oldRect.origin.y - newRect.origin.y; Point ownerPosition = _owner->getPosition(); ownerPosition.x += offSetX; ownerPosition.y += offSetY; this->setPosition(ownerPosition); } const Point& LayoutComponent::getPosition()const { return _owner->getPosition(); } void LayoutComponent::setPosition(const Point& position) { Node* parent = this->getOwnerParent(); if (parent != nullptr) { Point ownerPoint = position; const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _positionPercentX = ownerPoint.x / parentSize.width; else { _positionPercentX = 0; if (_usingPositionPercentX) ownerPoint.x = 0; } if (parentSize.height != 0) _positionPercentY = ownerPoint.y / parentSize.height; else { _positionPercentY = 0; if (_usingPositionPercentY) ownerPoint.y = 0; } _owner->setPosition(ownerPoint); this->refreshHorizontalMargin(); this->refreshVerticalMargin(); } else _owner->setPosition(position); } bool LayoutComponent::isPositionPercentXEnabled()const { return _usingPositionPercentX; } void LayoutComponent::setPositionPercentXEnabled(bool isUsed) { _usingPositionPercentX = isUsed; if (_usingPositionPercentX) { _horizontalEdge = HorizontalEdge::None; } } float LayoutComponent::getPositionPercentX()const { return _positionPercentX; } void LayoutComponent::setPositionPercentX(float percentMargin) { _positionPercentX = percentMargin; Node* parent = this->getOwnerParent(); if (parent != nullptr) { _owner->setPositionX(parent->getContentSize().width * _positionPercentX); this->refreshHorizontalMargin(); } } bool LayoutComponent::isPositionPercentYEnabled()const { return _usingPositionPercentY; } void LayoutComponent::setPositionPercentYEnabled(bool isUsed) { _usingPositionPercentY = isUsed; if (_usingPositionPercentY) { _verticalEdge = VerticalEdge::None_; } } float LayoutComponent::getPositionPercentY()const { return _positionPercentY; } void LayoutComponent::setPositionPercentY(float percentMargin) { _positionPercentY = percentMargin; Node* parent = this->getOwnerParent(); if (parent != nullptr) { _owner->setPositionY(parent->getContentSize().height * _positionPercentY); this->refreshVerticalMargin(); } } LayoutComponent::HorizontalEdge LayoutComponent::getHorizontalEdge()const { return _horizontalEdge; } void LayoutComponent::setHorizontalEdge(HorizontalEdge hEage) { _horizontalEdge = hEage; if (_horizontalEdge != HorizontalEdge::None) { _usingPositionPercentX = false; } Node* parent = this->getOwnerParent(); if (parent != nullptr) { Point ownerPoint = _owner->getPosition(); const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _positionPercentX = ownerPoint.x / parentSize.width; else { _positionPercentX = 0; ownerPoint.x = 0; if (_usingPositionPercentX) _owner->setPosition(ownerPoint); } this->refreshHorizontalMargin(); } } LayoutComponent::VerticalEdge LayoutComponent::getVerticalEdge()const { return _verticalEdge; } void LayoutComponent::setVerticalEdge(VerticalEdge vEage) { _verticalEdge = vEage; if (_verticalEdge != VerticalEdge::None_) { _usingPositionPercentY = false; } Node* parent = this->getOwnerParent(); if (parent != nullptr) { Point ownerPoint = _owner->getPosition(); const Size& parentSize = parent->getContentSize(); if (parentSize.height != 0) _positionPercentY = ownerPoint.y / parentSize.height; else { _positionPercentY = 0; ownerPoint.y = 0; if (_usingPositionPercentY) _owner->setPosition(ownerPoint); } this->refreshVerticalMargin(); } } float LayoutComponent::getLeftMargin()const { return _leftMargin; } void LayoutComponent::setLeftMargin(float margin) { _leftMargin = margin; } float LayoutComponent::getRightMargin()const { return _rightMargin; } void LayoutComponent::setRightMargin(float margin) { _rightMargin = margin; } float LayoutComponent::getTopMargin()const { return _topMargin; } void LayoutComponent::setTopMargin(float margin) { _topMargin = margin; } float LayoutComponent::getBottomMargin()const { return _bottomMargin; } void LayoutComponent::setBottomMargin(float margin) { _bottomMargin = margin; } //Size & Percent const Size& LayoutComponent::getSize()const { return this->getOwner()->getContentSize(); } void LayoutComponent::setSize(const Size& size) { Node* parent = this->getOwnerParent(); if (parent != nullptr) { Size ownerSize = size; const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _percentWidth = ownerSize.width / parentSize.width; else { _percentWidth = 0; if (_usingPercentWidth) ownerSize.width = 0; } if (parentSize.height != 0) _percentHeight = ownerSize.height / parentSize.height; else { _percentHeight = 0; if (_usingPercentHeight) ownerSize.height = 0; } _owner->setContentSize(ownerSize); this->refreshHorizontalMargin(); this->refreshVerticalMargin(); } else _owner->setContentSize(size); } bool LayoutComponent::isPercentWidthEnabled()const { return _usingPercentWidth; } void LayoutComponent::setPercentWidthEnabled(bool isUsed) { _usingPercentWidth = isUsed; if (_usingPercentWidth) { _usingStretchWidth = false; } } float LayoutComponent::getSizeWidth()const { return _owner->getContentSize().width; } void LayoutComponent::setSizeWidth(float width) { Size ownerSize = _owner->getContentSize(); ownerSize.width = width; Node* parent = this->getOwnerParent(); if (parent != nullptr) { const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _percentWidth = ownerSize.width / parentSize.width; else { _percentWidth = 0; if (_usingPercentWidth) ownerSize.width = 0; } _owner->setContentSize(ownerSize); this->refreshHorizontalMargin(); } else _owner->setContentSize(ownerSize); } float LayoutComponent::getPercentWidth()const { return _percentWidth; } void LayoutComponent::setPercentWidth(float percentWidth) { _percentWidth = percentWidth; Node* parent = this->getOwnerParent(); if (parent != nullptr) { Size ownerSize = _owner->getContentSize(); ownerSize.width = parent->getContentSize().width * _percentWidth; _owner->setContentSize(ownerSize); this->refreshHorizontalMargin(); } } bool LayoutComponent::isPercentHeightEnabled()const { return _usingPercentHeight; } void LayoutComponent::setPercentHeightEnabled(bool isUsed) { _usingPercentHeight = isUsed; if (_usingPercentHeight) { _usingStretchHeight = false; } } float LayoutComponent::getSizeHeight()const { return _owner->getContentSize().height; } void LayoutComponent::setSizeHeight(float height) { Size ownerSize = _owner->getContentSize(); ownerSize.height = height; Node* parent = this->getOwnerParent(); if (parent != nullptr) { const Size& parentSize = parent->getContentSize(); if (parentSize.height != 0) _percentHeight = ownerSize.height / parentSize.height; else { _percentHeight = 0; if (_usingPercentHeight) ownerSize.height = 0; } _owner->setContentSize(ownerSize); this->refreshVerticalMargin(); } else _owner->setContentSize(ownerSize); } float LayoutComponent::getPercentHeight()const { return _percentHeight; } void LayoutComponent::setPercentHeight(float percentHeight) { _percentHeight = percentHeight; Node* parent = this->getOwnerParent(); if (parent != nullptr) { Size ownerSize = _owner->getContentSize(); ownerSize.height = parent->getContentSize().height * _percentHeight; _owner->setContentSize(ownerSize); this->refreshVerticalMargin(); } } bool LayoutComponent::isStretchWidthEnabled()const { return _usingStretchWidth; } void LayoutComponent::setStretchWidthEnabled(bool isUsed) { _usingStretchWidth = isUsed; if (_usingStretchWidth) { _usingPercentWidth = false; } } bool LayoutComponent::isStretchHeightEnabled()const { return _usingStretchHeight; } void LayoutComponent::setStretchHeightEnabled(bool isUsed) { _usingStretchHeight = isUsed; if (_usingStretchHeight) { _usingPercentHeight = false; } } void LayoutComponent::refreshLayout() { if (!_actived) return; Node* parent = this->getOwnerParent(); if (parent == nullptr) return; const Size& parentSize = parent->getContentSize(); const Point& ownerAnchor = _owner->getAnchorPoint(); Size ownerSize = _owner->getContentSize(); Point ownerPosition = _owner->getPosition(); switch (this->_horizontalEdge) { case HorizontalEdge::None: if (_usingStretchWidth && !_isPercentOnly) { ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = _leftMargin + ownerAnchor.x * ownerSize.width; } else { if (_usingPositionPercentX) ownerPosition.x = parentSize.width * _positionPercentX; if (_usingPercentWidth) ownerSize.width = parentSize.width * _percentWidth; } break; case HorizontalEdge::Left: if (_isPercentOnly) break; if (_usingPercentWidth || _usingStretchWidth) ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = _leftMargin + ownerAnchor.x * ownerSize.width; break; case HorizontalEdge::Right: if (_isPercentOnly) break; if (_usingPercentWidth || _usingStretchWidth) ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = parentSize.width - (_rightMargin + (1 - ownerAnchor.x) * ownerSize.width); break; case HorizontalEdge::Center: if (_isPercentOnly) break; if (_usingStretchWidth) { ownerSize.width = parentSize.width - _leftMargin - _rightMargin; if (ownerSize.width < 0) ownerSize.width = 0; ownerPosition.x = _leftMargin + ownerAnchor.x * ownerSize.width; } else { if (_usingPercentWidth) ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = parentSize.width * _positionPercentX; } break; default: break; } switch (this->_verticalEdge) { case VerticalEdge::None_: if (_usingStretchHeight && !_isPercentOnly) { ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = _bottomMargin + ownerAnchor.y * ownerSize.height; } else { if (_usingPositionPercentY) ownerPosition.y = parentSize.height * _positionPercentY; if (_usingPercentHeight) ownerSize.height = parentSize.height * _percentHeight; } break; case VerticalEdge::Bottom: if (_isPercentOnly) break; if (_usingPercentHeight || _usingStretchHeight) ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = _bottomMargin + ownerAnchor.y * ownerSize.height; break; case VerticalEdge::Top: if (_isPercentOnly) break; if (_usingPercentHeight || _usingStretchHeight) ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = parentSize.height - (_topMargin + (1 - ownerAnchor.y) * ownerSize.height); break; case VerticalEdge::Center_: if (_isPercentOnly) break; if (_usingStretchHeight) { ownerSize.height = parentSize.height - _topMargin - _bottomMargin; if (ownerSize.height < 0) ownerSize.height = 0; ownerPosition.y = _bottomMargin + ownerAnchor.y * ownerSize.height; } else { if (_usingPercentHeight) ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = parentSize.height* _positionPercentY; } break; default: break; } _owner->setPosition(ownerPosition); _owner->setContentSize(ownerSize); ui::Helper::doLayout(_owner); } void LayoutComponent::setActiveEnabled(bool enable) { _actived = enable; } void LayoutComponent::setPercentOnlyEnabled(bool enable) { _isPercentOnly = enable; } } NS_CC_END
05587762221d9f405c6f047aff1fba677658ba03
b958286bb016a56f5ddff5514f38fbd29f3e9072
/include/ublox/message/MgaGloEph.h
731a95cbae3ab84986c3e0854bce4db66f60c74f
[]
no_license
yxw027/cc.ublox.generated
abdda838945777a498f433b0d9624a567ab1ea80
a8bf468281d2d06e32d3e029c40bc6d38e4a34de
refs/heads/master
2021-01-14T23:03:20.722801
2020-02-20T06:24:46
2020-02-20T06:24:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,098
h
// Generated by commsdsl2comms v3.3.2 /// @file /// @brief Contains definition of <b>"MGA-GLO-EPH"</b> message and its fields. #pragma once #include <cstdint> #include <tuple> #include "comms/MessageBase.h" #include "comms/field/IntValue.h" #include "comms/options.h" #include "ublox/MsgId.h" #include "ublox/field/FieldBase.h" #include "ublox/field/Res1.h" #include "ublox/field/Res4.h" #include "ublox/message/MgaGloEphCommon.h" #include "ublox/options/DefaultOptions.h" namespace ublox { namespace message { /// @brief Fields of @ref MgaGloEph. /// @tparam TOpt Extra options /// @see @ref MgaGloEph /// @headerfile "ublox/message/MgaGloEph.h" template <typename TOpt = ublox::options::DefaultOptions> struct MgaGloEphFields { /// @brief Definition of <b>"type"</b> field. struct Type : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::FailOnInvalid<>, comms::option::def::DefaultNumValue<1>, comms::option::def::ValidNumValue<1> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::TypeCommon::name(); } }; /// @brief Definition of <b>"version"</b> field. struct Version : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::ValidNumValue<0> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::VersionCommon::name(); } }; /// @brief Definition of <b>"svid"</b> field. struct Svid : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::SvidCommon::name(); } }; /// @brief Definition of <b>"reserved1"</b> field. struct Reserved1 : public ublox::field::Res1< TOpt > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::Reserved1Common::name(); } }; /// @brief Definition of <b>"FT"</b> field. struct FT : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::FTCommon::name(); } }; /// @brief Definition of <b>"B"</b> field. struct B : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::BCommon::name(); } }; /// @brief Definition of <b>"M"</b> field. struct M : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::MCommon::name(); } }; /// @brief Definition of <b>"H"</b> field. struct H : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::HCommon::name(); } }; /// @brief Definition of <b>"x"</b> field. struct X : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 2048>, comms::option::def::UnitsKilometers > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::XCommon::name(); } }; /// @brief Definition of <b>"y"</b> field. struct Y : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 2048>, comms::option::def::UnitsKilometers > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::YCommon::name(); } }; /// @brief Definition of <b>"z"</b> field. struct Z : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 2048>, comms::option::def::UnitsKilometers > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::ZCommon::name(); } }; /// @brief Definition of <b>"dx"</b> field. struct Dx : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1048576L>, comms::option::def::UnitsKilometersPerSecond > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DxCommon::name(); } }; /// @brief Definition of <b>"dy"</b> field. struct Dy : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1048576L>, comms::option::def::UnitsKilometersPerSecond > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DyCommon::name(); } }; /// @brief Definition of <b>"dz"</b> field. struct Dz : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1048576L>, comms::option::def::UnitsKilometersPerSecond > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DzCommon::name(); } }; /// @brief Definition of <b>"ddx"</b> field. struct Ddx : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DdxCommon::name(); } }; /// @brief Definition of <b>"ddy"</b> field. struct Ddy : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DdyCommon::name(); } }; /// @brief Definition of <b>"ddz"</b> field. struct Ddz : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DdzCommon::name(); } }; /// @brief Definition of <b>"tb"</b> field. struct Tb : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::ScalingRatio<15, 1>, comms::option::def::UnitsMinutes > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::TbCommon::name(); } }; /// @brief Definition of <b>"gamma"</b> field. struct Gamma : public comms::field::IntValue< ublox::field::FieldBase<>, std::int16_t, comms::option::def::ScalingRatio<1, 0x10000000000LL> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::GammaCommon::name(); } }; /// @brief Definition of <b>"E"</b> field. struct E : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::UnitsDays > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::ECommon::name(); } }; /// @brief Definition of <b>"deltaTau"</b> field. struct DeltaTau : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L>, comms::option::def::UnitsSeconds > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DeltaTauCommon::name(); } }; /// @brief Definition of <b>"tau"</b> field. struct Tau : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1073741824L>, comms::option::def::UnitsSeconds > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::TauCommon::name(); } }; /// @brief Definition of <b>"reserved2"</b> field. struct Reserved2 : public ublox::field::Res4< TOpt > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::Reserved2Common::name(); } }; /// @brief All the fields bundled in std::tuple. using All = std::tuple< Type, Version, Svid, Reserved1, FT, B, M, H, X, Y, Z, Dx, Dy, Dz, Ddx, Ddy, Ddz, Tb, Gamma, E, DeltaTau, Tau, Reserved2 >; }; /// @brief Definition of <b>"MGA-GLO-EPH"</b> message class. /// @details /// See @ref MgaGloEphFields for definition of the fields this message contains. /// @tparam TMsgBase Base (interface) class. /// @tparam TOpt Extra options /// @headerfile "ublox/message/MgaGloEph.h" template <typename TMsgBase, typename TOpt = ublox::options::DefaultOptions> class MgaGloEph : public comms::MessageBase< TMsgBase, typename TOpt::message::MgaGloEph, comms::option::def::StaticNumIdImpl<ublox::MsgId_MgaGlo>, comms::option::def::FieldsImpl<typename MgaGloEphFields<TOpt>::All>, comms::option::def::MsgType<MgaGloEph<TMsgBase, TOpt> >, comms::option::def::HasName > { // Redefinition of the base class type using Base = comms::MessageBase< TMsgBase, typename TOpt::message::MgaGloEph, comms::option::def::StaticNumIdImpl<ublox::MsgId_MgaGlo>, comms::option::def::FieldsImpl<typename MgaGloEphFields<TOpt>::All>, comms::option::def::MsgType<MgaGloEph<TMsgBase, TOpt> >, comms::option::def::HasName >; public: /// @brief Provide names and allow access to internal fields. /// @details See definition of @b COMMS_MSG_FIELDS_NAMES macro /// related to @b comms::MessageBase class from COMMS library /// for details. /// /// The generated types and functions are: /// @li @b Field_type type and @b field_type() fuction /// for @ref MgaGloEphFields::Type field. /// @li @b Field_version type and @b field_version() fuction /// for @ref MgaGloEphFields::Version field. /// @li @b Field_svid type and @b field_svid() fuction /// for @ref MgaGloEphFields::Svid field. /// @li @b Field_reserved1 type and @b field_reserved1() fuction /// for @ref MgaGloEphFields::Reserved1 field. /// @li @b Field_fT type and @b field_fT() fuction /// for @ref MgaGloEphFields::FT field. /// @li @b Field_b type and @b field_b() fuction /// for @ref MgaGloEphFields::B field. /// @li @b Field_m type and @b field_m() fuction /// for @ref MgaGloEphFields::M field. /// @li @b Field_h type and @b field_h() fuction /// for @ref MgaGloEphFields::H field. /// @li @b Field_x type and @b field_x() fuction /// for @ref MgaGloEphFields::X field. /// @li @b Field_y type and @b field_y() fuction /// for @ref MgaGloEphFields::Y field. /// @li @b Field_z type and @b field_z() fuction /// for @ref MgaGloEphFields::Z field. /// @li @b Field_dx type and @b field_dx() fuction /// for @ref MgaGloEphFields::Dx field. /// @li @b Field_dy type and @b field_dy() fuction /// for @ref MgaGloEphFields::Dy field. /// @li @b Field_dz type and @b field_dz() fuction /// for @ref MgaGloEphFields::Dz field. /// @li @b Field_ddx type and @b field_ddx() fuction /// for @ref MgaGloEphFields::Ddx field. /// @li @b Field_ddy type and @b field_ddy() fuction /// for @ref MgaGloEphFields::Ddy field. /// @li @b Field_ddz type and @b field_ddz() fuction /// for @ref MgaGloEphFields::Ddz field. /// @li @b Field_tb type and @b field_tb() fuction /// for @ref MgaGloEphFields::Tb field. /// @li @b Field_gamma type and @b field_gamma() fuction /// for @ref MgaGloEphFields::Gamma field. /// @li @b Field_e type and @b field_e() fuction /// for @ref MgaGloEphFields::E field. /// @li @b Field_deltaTau type and @b field_deltaTau() fuction /// for @ref MgaGloEphFields::DeltaTau field. /// @li @b Field_tau type and @b field_tau() fuction /// for @ref MgaGloEphFields::Tau field. /// @li @b Field_reserved2 type and @b field_reserved2() fuction /// for @ref MgaGloEphFields::Reserved2 field. COMMS_MSG_FIELDS_NAMES( type, version, svid, reserved1, fT, b, m, h, x, y, z, dx, dy, dz, ddx, ddy, ddz, tb, gamma, e, deltaTau, tau, reserved2 ); // Compile time check for serialisation length. static const std::size_t MsgMinLen = Base::doMinLength(); static const std::size_t MsgMaxLen = Base::doMaxLength(); static_assert(MsgMinLen == 48U, "Unexpected min serialisation length"); static_assert(MsgMaxLen == 48U, "Unexpected max serialisation length"); /// @brief Name of the message. static const char* doName() { return ublox::message::MgaGloEphCommon::name(); } }; } // namespace message } // namespace ublox
c9e26336b698723eb09076a6793616a152dd2565
6f9d495e097bbfe2ebe1dc01dc2149ec4f8372e0
/cpp/cpp04/ex03/Character.hpp
7e8c74f73b9f100d291f083bb74b0bb3a658cfa5
[]
no_license
nirgoth/nirgoth
abc22e2a4810c979be66a590c142dbd76a5d6fa0
4cc2b8e60cfc50d4ca7ee3dff45f1f1603ca7a07
refs/heads/master
2021-06-23T07:42:20.373983
2021-05-03T13:49:55
2021-05-03T13:49:55
223,377,216
0
0
null
null
null
null
UTF-8
C++
false
false
463
hpp
#ifndef CHARACTER_HPP # define CHARACTER_HPP # include "AMateria.hpp" class Character { private: std::string _name; AMateria *_inv[4] = {NULL, NULL, NULL, NULL}; Character(); public: Character(std::string name); ~Character(); Character(Character const &el); Character &operator=(Character const &el); std::string const &getName() const; void equip(AMateria *m); void unequip(int idx); void use(int idx, ICharacter &target); }; #endif
302bc5ab25ac8330a4e74117432545491f959879
a3a8de60a97adc6279adbac65656f9fec5f2e8e6
/2017011507-陈昱宏-源代码/SearchOrder.h
3cb50f4674c961aeed4119f5b545d9e323f8bed2
[]
no_license
THU-Yu/Hotel-Booking-Application
5dec346f905848f19fb17f9ba7233d19304f8865
3abcc2e7c23a16ab0af94720f7f8a85b0e65549e
refs/heads/master
2021-05-18T08:18:00.872611
2020-03-30T03:44:04
2020-03-30T03:44:04
251,193,613
1
0
null
null
null
null
UTF-8
C++
false
false
1,505
h
#ifndef SEARCHORDER_H #define SEARCHORDER_H #include "normaluser.h" #include "hotaluser.h" #include "platformuser.h" #include "hotalorder.h" #include "orderdetail.h" #include "PinJiaMessage.h" #include "hotal.h" #include <QWidget> class QTableWidget; class QTableWidgetItem; class SearchOrder:public QWidget { Q_OBJECT public: SearchOrder(Hotal *hotalhead,Message *Messagehead, PinJiaMessage *pinjiahead,Room *roomhead, HotalOrder *Orderhead,NormalUser *MainAccount1,HotalUser *MainAccount2,PlatformUser *MainAccount3,QWidget *parent=0) :Hotalhead(hotalhead),Messagehead(Messagehead),PinJiahead(pinjiahead),Roomhead(roomhead),Orderhead(Orderhead),MainAccount1(MainAccount1),MainAccount2(MainAccount2),MainAccount3(MainAccount3),QWidget(parent){} void changeSearchOrder(NormalUser *Mainaccount1, HotalUser *Mainaccount2, PlatformUser *Mainccount3); void changeTable(NormalUser *Mainaccount1,HotalUser *Mainaccount2,PlatformUser *Mainaccount3); ~SearchOrder(){} signals: void back(); private slots: void ButtonClicked(QTableWidgetItem *item); void CheckCancelOrder(); void Back(); private: QTableWidget *MainTable; Hotal *Hotalhead; HotalOrder *Orderhead; Message *Messagehead; Room *Roomhead; PinJiaMessage *PinJiahead; NormalUser *MainAccount1; HotalUser *MainAccount2; PlatformUser *MainAccount3; OrderDetail *orderdetail; QPushButton *BackButton; QPushButton *CancelOrderButton; }; #endif // SEARCHORDER_H
0b6551bd116eb78cb7b0c5954d975e8fddad538c
3ffb5a515f1ea50f8c3467af3c9ee63a4b73f706
/src/qt/qrcodedialog.cpp
d6b86d1caf33d74540bf4e6871a5723059fdc962
[ "MIT" ]
permissive
sppl/iti
c75db061242c98983e5204fdaf4b68e61f2230fd
384c67784177ca5eb3d218f4276f00584a8b8743
refs/heads/master
2020-04-02T07:32:54.267090
2017-07-14T18:38:33
2017-07-14T18:38:33
61,468,392
3
2
null
null
null
null
UTF-8
C++
false
false
4,360
cpp
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "dialogwindowflags.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent, DIALOGWINDOWHINTS), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("iticoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
6e2cd9be1190ed93729bffe4719a50fa05661319
c4cf06c5b7e8e27d80fe276016efd7da2115b449
/Light.cpp
534498139fe8a06fa8a6e11d0977cbe9541c869f
[]
no_license
uans3k/u3krender
93f94a5ee3b345e6d5efde6ac554a9f6dd9d267b
2841d81941facd9768174842bb1fb65da921b6a8
refs/heads/master
2021-01-10T02:03:59.761353
2019-05-10T11:23:29
2019-05-10T11:23:29
53,245,333
0
0
null
null
null
null
UTF-8
C++
false
false
1,823
cpp
#include "stdafx.h" #include "Light.h" void Light::init(Point4D *pos, Vector4D *dir, Color ambient, Color diffuse, Color specular, float kc, float kl, float kq, float spotInner, float, float pf, int attr) { this->ambient = ambient; this->diffuse = diffuse; this->specular = specular; this->kc = kc; this->kl = kl; this->kq = kq; this->spotInner = spotInner; this->spotOutter = spotOutter; this->pf = pf; this->attr = attr; if (pos) { Point4D_Init(&oPos,pos); Point4D_Init(&tPos, &oPos); } if (dir) { Vector4D_Init(&oDir, dir); Vector4D_Normalize(&oDir); Vector4D_Init(&tDir,&oDir); } } void Light::initAmbientLight(Color ambient) { this->ambient = ambient; this->attr = LIGHT_ATTR_AMBIENT; open(); } void Light::initInfinityLight(Vector4D *dir,Color diffuse, Color specular) { this->diffuse = diffuse; this->specular = specular; if (dir) { Vector4D_Init(&oDir, dir); Vector4D_Normalize(&oDir); Vector4D_Init(&tDir, &oDir); } this->attr = LIGHT_ATTR_INFINITY; open(); } void Light::initPointLight(Point4D *pos, Color diffuse, Color specular, float kc, float kl, float kq) { this->diffuse = diffuse; this->specular = specular; this->kc = kc; this->kl = kl; this->kq = kq; if (pos) { Point4D_Init(&oPos, pos); Point4D_Init(&tPos, &oPos); } this->attr = LIGHT_ATTR_POINT; open(); } void Light::initSpotLight(Point4D * pos, Vector4D * dir, Color diffuse, Color specular, float kc, float kl, float kq,float pf) { this->diffuse = diffuse; this->specular = specular; this->kc = kc; this->kl = kl; this->kq = kq; this->pf = pf; if (pos) { Point4D_Init(&oPos, pos); Point4D_Init(&tPos, &oPos); } if (dir) { Vector4D_Init(&oDir, dir); Vector4D_Normalize(&oDir); Vector4D_Init(&tDir, &oDir); } this->attr = LIGHT_ATTR_SPOT; open(); }
457af226f09b9954407a70c35b4b6c4b688c3255
575527ccc679f5c2718bb35eb58a5e4f470b11eb
/include/message_wrap.h
c1b0cd4ddbf7f48df5b4b58a2162bde038d5144e
[]
no_license
wukong2016/wukong
dd4fd9d11b93aea0c7223d26bc513e61ef464a56
a053391c57863782579db5f25a6f0aa7e02237a3
refs/heads/master
2020-12-24T20:32:36.107846
2016-05-10T02:07:14
2016-05-10T02:07:14
58,422,145
0
0
null
null
null
null
UTF-8
C++
false
false
740
h
#pragma once #include "query_basic_types.h" #include "network_node.h" #include "rdma_resource.h" #include "thread_cfg.h" #include "global_cfg.h" void SendR(thread_cfg* cfg,int r_mid,int r_tid,request_or_reply& r); request_or_reply RecvR(thread_cfg* cfg); bool TryRecvR(thread_cfg* cfg,request_or_reply& r); template<typename T> void SendObject(thread_cfg* cfg,int r_mid,int r_tid,T& r){ std::stringstream ss; boost::archive::binary_oarchive oa(ss); oa << r; cfg->node->Send(r_mid,r_tid,ss.str()); } template<typename T> T RecvObject(thread_cfg* cfg){ std::string str; str=cfg->node->Recv(); std::stringstream s; s << str; boost::archive::binary_iarchive ia(s); T r; ia >> r; return r; }
8fb5f252d6caa80ac889665bf468119687dc17f9
1cdf0777a01cc71e78f4482c25609de89eee1b67
/client_lib.cpp
ef57d5b8d83671e02ff0c6b6bc106b205fd9916f
[]
no_license
ogolosovskiy/speed_test
9ef3fa5f61e7ec268910c99dce6db0bf40bd6363
891c48feecc6c55aff46eddd5ca9cb88be595685
refs/heads/master
2020-03-30T23:45:27.246754
2018-10-10T10:10:23
2018-10-10T10:10:23
151,712,343
0
0
null
null
null
null
UTF-8
C++
false
false
7,527
cpp
// // Created by Oleg Golosovskiy on 08/10/2018. // #include "client_lib.h" #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> to_print_callback* g_logger = 0; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-security" template<typename ... Args> static void print_log(char const* fmt, Args ... args) { if(!g_logger) return; size_t size = snprintf(nullptr, 0, fmt, args ...) + 1; std::unique_ptr<char[]> buf(new char[size]); snprintf(buf.get(), size, fmt, args ...); std::string formatted(buf.get(), buf.get() + size - 1); (*g_logger)(formatted.c_str()); } #pragma clang diagnostic pop client_lib::client_lib(to_print_callback* log) { g_logger = log; } int client_lib::run_test(char const* server) { struct addrinfo hints, *res0 = nullptr; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE; int error = getaddrinfo(server, std::to_string(SERVER_PORT).c_str(), &hints, &res0); if (error) { print_log("find_interface: syscall getaddrinfo failed: %s(%d) %s\n", strerror(error), error, server); return error; } sockaddr* server_addr = res0->ai_addr; socklen_t server_addr_len = res0->ai_addrlen; print_log("UDP Speed Test 1.1"); int sock; if ((sock = socket(server_addr->sa_family, SOCK_DGRAM, 0)) < 0) { print_log("could not create socket"); return -1; } struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 500000; if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) { print_log("Error setsockopt"); return -1; } int av_desync = 0; int av_rtt = 0; int av_delivery = 0; int av_packet_lost = 0; // measure RTT without load and clock desync { print_log("Measuring RTT ..."); packet out; out._type = ETimeSync; int rtt[RTT_MAX_ATTEMPTS]; int clock_desync[RTT_MAX_ATTEMPTS]; NEGATIVE_RESET(rtt); NEGATIVE_RESET(clock_desync); int position = 0; for (int attempt = 0; attempt < RTT_MAX_ATTEMPTS; ++attempt) { //print_log("."); std::chrono::time_point<std::chrono::system_clock> now; now = std::chrono::system_clock::now(); time_sync_payload* payload = reinterpret_cast<time_sync_payload*>(&out._payload[0]); payload->_client_time_stamp = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); ::sendto(sock, &out, sizeof(packet), 0, server_addr, server_addr_len); char recv_buffer[2048]; sockaddr_storage in_addr; socklen_t in_addr_len = sizeof(sockaddr_in); int len = ::recvfrom(sock, recv_buffer, sizeof(recv_buffer), 0, (sockaddr *) &in_addr, &in_addr_len); if (len == -1) { int err = errno; if (err == ETIMEDOUT || err == EAGAIN) { now = std::chrono::system_clock::now(); long err_time = std::chrono::duration_cast<std::chrono::milliseconds>( now.time_since_epoch()).count(); print_log("\ntime out %s %d", strerror(err), (int) (err_time - payload->_client_time_stamp)); continue; } print_log("\ncould not read from socket %s", strerror(err)); return 1; } else if (len == sizeof(recv_buffer)) { print_log("read buffer overflow"); continue; } // printf("received: %d byte from server %s", len, inet_ntoa(((sockaddr_in *) &in_addr)->sin_addr)); now = std::chrono::system_clock::now(); long milisecs2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); packet *recv_packet = reinterpret_cast<packet *> (&recv_buffer[0]); time_sync_payload *recv_payload = reinterpret_cast<time_sync_payload *> (recv_packet->_payload); long recv_server_milisec = recv_payload->_server_time_stamp; long recv_client_start_milisec = recv_payload->_client_time_stamp; rtt[position] = milisecs2 - recv_client_start_milisec; long approx_server_time = milisecs2 - (rtt[position] / 2); clock_desync[position] = recv_server_milisec - approx_server_time; //print_log("rtt: %d clock desync: %d", rtt[position], clock_desync[position]); ++position; std::this_thread::sleep_for(std::chrono::milliseconds(250)); } av_desync = mediana(clock_desync); av_rtt = mediana(rtt); print_log("Average RTT: %d ms\nAverage clock out of synchronization: %d ms", av_rtt, av_desync ); } // make socket non blocking bool blocking = true; int flags = fcntl(sock, F_GETFL, 0); if (flags == -1) return 0; flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK); if (fcntl(sock, F_SETFL, flags) == -1) return 0; long global_seqence_count = 0; int received_reports = 0; // 1.5 Upload MBits test { print_log("1.5 MBits upload - Measuring packet lost and latency ..."); packet out; int delivery_time[MAX_REPORTS]; NEGATIVE_RESET(delivery_time); int packet_lost[MAX_REPORTS]; NEGATIVE_RESET(packet_lost); for(int attempt = 0; attempt<LOAD_SERIES; ++attempt) { // send Media Packet // how much packets we will send for this set int packets = load_bits / 8 /*bits->bytes*/ / /*bytes->packets*/ sizeof(packet) / /*4 times per second*/ packets_per_seconds; out.clear(); out._type = ELoad; load_payload* payload = reinterpret_cast<load_payload*>(&out._payload[0]); payload->_load_set_count = attempt; payload->_load_set_packets = packets; long time_stamp_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); time_stamp_ms += av_desync; payload->_set_start_time_stamp = time_stamp_ms; //printf("send %d packest by %lu size", packets, sizeof(packet)); //print_log("."); for(int num_packet = 0; num_packet<packets; ++num_packet) { payload->_seqence_number = global_seqence_count++; ::sendto(sock, &out, sizeof(packet), 0, server_addr, server_addr_len); } std::this_thread::sleep_for(std::chrono::milliseconds(1000/packets_per_seconds)); // check stats packet char recv_buffer[load_statistic_buffer]; sockaddr_storage in_addr; socklen_t in_addr_len = sizeof(sockaddr_in); while(true) { int len = ::recvfrom(sock, recv_buffer, sizeof(recv_buffer), 0, (sockaddr *) &in_addr, &in_addr_len); if (len == -1) { int err = errno; if (err != ETIMEDOUT && err != EAGAIN) { print_log("could not read stat packet %s", strerror(err)); return 1; } break; } else if (len == sizeof(recv_buffer)) { print_log("read buffer overflow"); return 1; } else { //printf("received: %d byte from server %s", len, inet_ntoa(((sockaddr_in *) &in_addr)->sin_addr)); packet *recv_packet = reinterpret_cast<packet *> (&recv_buffer[0]); if (recv_packet->_type == ELoadStatistics) { packet *recv_packet = reinterpret_cast<packet *> (&recv_buffer[0]); statistics_payload *recv_stats = reinterpret_cast<statistics_payload *> (recv_packet->_payload); //printf("ELoadStatistics: count: %d delivery time: %d ms", recv_stats->_packets_count, recv_stats->_delivery_time); assert(received_reports<MAX_REPORTS); delivery_time[received_reports] = recv_stats->_delivery_time; packet_lost[received_reports] = recv_stats->_packet_lost; received_reports++; } } } } av_delivery = mediana(delivery_time); av_packet_lost = mediana(packet_lost); } if(received_reports==0) print_log("Stat server not responce"); else print_log("Upload %f MBits/sec average latency: %d ms, packet lost: %.2f%%", (float)load_bits/1000000, av_delivery, av_packet_lost/100.00); return 0; }
818ed4a97462a87feed0dad29f49ead70ce9942f
5b0c1f4bfe523e55e9ad2f7842a08b31be0410d3
/bitsgintp1_hackerrank/RepeatedString.cpp
ae6aaec5aa255728b8d477acc69df53101258c3a
[]
no_license
palash1611/Competitive_Coding
ffc437740a197d8bb9777d00e0c1d0076590edd2
45783550b46e023dc45a276da3a8e085dc790a52
refs/heads/master
2020-03-19T05:13:19.087112
2018-06-09T12:42:25
2018-06-09T12:42:25
135,910,767
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
//https://www.hackerrank.com/contests/bitsgintp1/challenges/repeated-string #include <bits/stdc++.h> using namespace std; #define V vector typedef long long LL; typedef long double LD; typedef pair<int, int> pii; typedef V<int> vi; typedef V<string> vs; typedef V<LL> vll; typedef V<double> vd; typedef V<pii> vpii; #define ll long long #define rep(i,a) for(int i=0; i<(a); ++i) #define fov(i,a) rep(i,(a).size()) #define nl cout<<endl; #define fs first #define sc second #define pb push_back #define mp make_pair // Complete the repeatedString function below. long repeatedString(string s, long n) { long res=0; int size=s.length(); int a=0; int t = n/size; //t=t*size; int rem = n-(t*size); //cout<<n<<" "<<size<<" "<<t<<" "<<rem;nl; for(char& c : s) { if (c=='a') a++; } res=a*t; //cout<<res;nl; for(char& c : s) { if(rem==0) break; if (c=='a') res++; rem--; } //cout<<res;nl; return res; } int main() { //ofstream fout(getenv("OUTPUT_PATH")); string s; getline(cin, s); long n; cin >> n; //cin.ignore(numeric_limits<streamsize>::max(), '\n'); long result = repeatedString(s, n); cout << result << "\n"; // fout.close(); return 0; }
33917c4c5aa6bca1045854a49a356723b24ca811
cc7661edca4d5fb2fc226bd6605a533f50a2fb63
/mscorlib/ImageFileMachine.h
ff2c5c5c2c668938b38d0c533c2e7130ba9c3303
[ "MIT" ]
permissive
g91/Rust-C-SDK
698e5b573285d5793250099b59f5453c3c4599eb
d1cce1133191263cba5583c43a8d42d8d65c21b0
refs/heads/master
2020-03-27T05:49:01.747456
2017-08-23T09:07:35
2017-08-23T09:07:35
146,053,940
1
0
null
2018-08-25T01:13:44
2018-08-25T01:13:44
null
UTF-8
C++
false
false
195
h
#pragma once namespace System { namespace Reflection { class ImageFileMachine : public Enum // 0x0 { public: int value__; // 0x10 (size: 0x4, flags: 0x606, type: 0x8) }; // size = 0x18 }
4ce772be8fa1270aa9a014e408cd64137afb3a88
f92e90323339912314faf6475b988d26f679372b
/test_suite/dr_branch_12_locks_Yes.cpp
8f3cef3e6be168ca86b0686d746acc920fbf685b
[]
no_license
rutgers-apl/PTRacer
eea91b7606730565bf54524ce8bbb52b58529f1b
3624264c38302513f0d28fc22f875d9e3dd8fdcf
refs/heads/master
2020-12-25T13:51:17.473837
2017-06-06T06:11:27
2017-06-06T06:11:27
62,167,491
8
2
null
null
null
null
UTF-8
C++
false
false
18,198
cpp
#include<iostream> #include "t_debug_task.h" #include "tbb/mutex.h" using namespace std; using namespace tbb; #define NUM_TASKS 22 int shd[NUM_TASKS]; bool c; tbb::mutex x_mutex; tbb::mutex::scoped_lock myLock; class Task1: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); int str_1 = 1; RecordTStore (get_cur_tid(), &c, &str_1); c = true; // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task2: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); RecordTLoad (get_cur_tid(), &c); if (c == true) { int str_2 = 1; RecordTBrCheck(get_cur_tid(), &c, &str_2, EQ); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[1]); int tmp = shd[1] + 1; RecordTStore (get_cur_tid(), &shd[1], &tmp); shd[1]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); } else { int str_2 = 1; RecordTBrCheck(get_cur_tid(), &c, &str_2, NEQ); RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[1]); int tmp = shd[1] + 1; RecordTStore (get_cur_tid(), &shd[1], &tmp); shd[1]++; } RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task3: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task4: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task5: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task6: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task7: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task8: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task9: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task10: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task11: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task12: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task13: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task14: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task15: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task16: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task17: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task18: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task19: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task20: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task21: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; int main( int argc, const char *argv[] ) { TD_Activate(); TraceGenActivate(); int str_1 = 0; RecordTStoreMain(&c, &str_1); c = false; t_debug_task& a = *new(task::allocate_root()) Task1(); t_debug_task::spawn(a); int a_cid = a.getTaskId(); RecordTSpawnMain(&a_cid); t_debug_task& b = *new(task::allocate_root()) Task2(); t_debug_task::spawn(b); int b_cid = b.getTaskId(); RecordTSpawnMain(&b_cid); t_debug_task& c = *new(task::allocate_root()) Task3(); t_debug_task::spawn(c); int c_cid = c.getTaskId(); RecordTSpawnMain(&c_cid); t_debug_task& d = *new(task::allocate_root()) Task4(); t_debug_task::spawn(d); int d_cid = d.getTaskId(); RecordTSpawnMain(&d_cid); t_debug_task& e = *new(task::allocate_root()) Task5(); t_debug_task::spawn(e); int e_cid = e.getTaskId(); RecordTSpawnMain(&e_cid); t_debug_task& f = *new(task::allocate_root()) Task6(); t_debug_task::spawn(f); int f_cid = f.getTaskId(); RecordTSpawnMain(&f_cid); t_debug_task& g = *new(task::allocate_root()) Task7(); t_debug_task::spawn(g); int g_cid = g.getTaskId(); RecordTSpawnMain(&g_cid); t_debug_task& h = *new(task::allocate_root()) Task8(); t_debug_task::spawn(h); int h_cid = h.getTaskId(); RecordTSpawnMain(&h_cid); t_debug_task& i = *new(task::allocate_root()) Task9(); t_debug_task::spawn(i); int i_cid = i.getTaskId(); RecordTSpawnMain(&i_cid); t_debug_task& j = *new(task::allocate_root()) Task10(); t_debug_task::spawn(j); int j_cid = j.getTaskId(); RecordTSpawnMain(&j_cid); t_debug_task& k = *new(task::allocate_root()) Task11(); t_debug_task::spawn(k); int k_cid = k.getTaskId(); RecordTSpawnMain(&k_cid); t_debug_task& l = *new(task::allocate_root()) Task12(); t_debug_task::spawn(l); int l_cid = l.getTaskId(); RecordTSpawnMain(&l_cid); t_debug_task& m = *new(task::allocate_root()) Task13(); t_debug_task::spawn(m); int m_cid = m.getTaskId(); RecordTSpawnMain(&m_cid); t_debug_task& n = *new(task::allocate_root()) Task14(); t_debug_task::spawn(n); int n_cid = n.getTaskId(); RecordTSpawnMain(&n_cid); t_debug_task& o = *new(task::allocate_root()) Task15(); t_debug_task::spawn(o); int o_cid = o.getTaskId(); RecordTSpawnMain(&o_cid); t_debug_task& p = *new(task::allocate_root()) Task16(); t_debug_task::spawn(p); int p_cid = p.getTaskId(); RecordTSpawnMain(&p_cid); t_debug_task& q = *new(task::allocate_root()) Task17(); t_debug_task::spawn(q); int q_cid = q.getTaskId(); RecordTSpawnMain(&q_cid); t_debug_task& s = *new(task::allocate_root()) Task18(); t_debug_task::spawn(s); int s_cid = s.getTaskId(); RecordTSpawnMain(&s_cid); t_debug_task& t = *new(task::allocate_root()) Task19(); t_debug_task::spawn(t); int t_cid = t.getTaskId(); RecordTSpawnMain(&t_cid); t_debug_task& u = *new(task::allocate_root()) Task20(); t_debug_task::spawn(u); int u_cid = u.getTaskId(); RecordTSpawnMain(&u_cid); t_debug_task& v = *new(task::allocate_root()) Task21(); t_debug_task::spawn_root_and_wait(v); int v_cid = v.getTaskId(); RecordTSpawnMain(&v_cid); for (size_t i = 0 ; i < 1000000000 ; i++); cout << "Addr of shd[1] " << (size_t)&shd[1] << std::endl; RecordTReturn(0); Fini(); }
34957995c11b2fe45b30ca916ac9c99b8076d1d5
28b7078f834d6a16ff0f0bffc2ddad50bbc43536
/Memory_Management_Header/static_allocator.h
2352ed6d857eba2b3471a13b71a3745aa72c6c35
[]
no_license
ccpang96/SGI_STL
89289b57395d90d9b9a6a63c81243b3feeb7f029
d63d4630b9d096357aae7a617ccf813220784014
refs/heads/master
2020-12-11T23:43:35.979492
2020-01-15T08:52:46
2020-01-15T08:52:46
233,987,129
1
0
null
null
null
null
GB18030
C++
false
false
843
h
#pragma once #include <string> namespace static_allocator { //设计allocator1类去封装malloc和delete class allocator1 { private: struct obj { struct obj*next; //嵌入式指针 embedded pointer }; public: void* allocate(size_t); void deallocate(void*, size_t); private: obj * freeStore = nullptr; const int CHUNK = 5; //小一些以便观察 }; //实现Foo类去测试上面的allocator1类 class Foo { public: long L; std::string str; static allocator1 myAlloc; public: Foo(long l) : L(l) {} //重载Foo类的operator new static void* operator new(size_t size) { return myAlloc.allocate(size); } //重载Foo类的operator delete static void operator delete(void* pdead, size_t size) { return myAlloc.deallocate(pdead, size); } }; void static_allocator_function(); }
ed4e1db9cc3e46558fa65a6a20bdaf3b04bff57e
caf6ae544fce3b332b40a03462c0646a32c913e1
/master/qtcplus/client/SWGStandardInitiateLoginResultData.cpp
03d47c7c24ee00f55370ce08e15926776b9168db
[ "Apache-2.0" ]
permissive
coinsecure/plugins
827eb0ce03a6a23b4819a618ee47600161bec1c7
ad6f08881020c268b530d5242d9deed8d2ec84de
refs/heads/master
2020-05-30T07:17:56.255709
2016-11-27T22:22:23
2016-11-27T22:22:23
63,496,663
3
5
null
null
null
null
UTF-8
C++
false
false
4,677
cpp
/** * Coinsecure Api Documentation * To generate an API key, please visit <a href='https://coinsecure.in/api' target='_new' class='homeapi'>https://coinsecure.in/api</a>.<br>Guidelines for use can be accessed at <a href='https://api.coinsecure.in/v1/guidelines'>https://api.coinsecure.in/v1/guidelines</a>.<br>Programming Language Libraries for use can be accessed at <a href='https://api.coinsecure.in/v1/code-libraries'>https://api.coinsecure.in/v1/code-libraries</a>. * * OpenAPI spec version: beta * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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 "SWGStandardInitiateLoginResultData.h" #include "SWGHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace Swagger { SWGStandardInitiateLoginResultData::SWGStandardInitiateLoginResultData(QString* json) { init(); this->fromJson(*json); } SWGStandardInitiateLoginResultData::SWGStandardInitiateLoginResultData() { init(); } SWGStandardInitiateLoginResultData::~SWGStandardInitiateLoginResultData() { this->cleanup(); } void SWGStandardInitiateLoginResultData::init() { success = false; message = new SWGSuccessInitiateLoginResponse(); method = new QString(""); title = new QString(""); time = NULL; } void SWGStandardInitiateLoginResultData::cleanup() { if(message != nullptr) { delete message; } if(method != nullptr) { delete method; } if(title != nullptr) { delete title; } if(time != nullptr) { delete time; } } SWGStandardInitiateLoginResultData* SWGStandardInitiateLoginResultData::fromJson(QString &json) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); return this; } void SWGStandardInitiateLoginResultData::fromJsonObject(QJsonObject &pJson) { ::Swagger::setValue(&success, pJson["success"], "bool", ""); ::Swagger::setValue(&message, pJson["message"], "SWGSuccessInitiateLoginResponse", "SWGSuccessInitiateLoginResponse"); ::Swagger::setValue(&method, pJson["method"], "QString", "QString"); ::Swagger::setValue(&title, pJson["title"], "QString", "QString"); ::Swagger::setValue(&time, pJson["time"], "QDateTime", "QDateTime"); } QString SWGStandardInitiateLoginResultData::asJson () { QJsonObject* obj = this->asJsonObject(); QJsonDocument doc(*obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject* SWGStandardInitiateLoginResultData::asJsonObject() { QJsonObject* obj = new QJsonObject(); obj->insert("success", QJsonValue(success)); toJsonValue(QString("message"), message, obj, QString("SWGSuccessInitiateLoginResponse")); toJsonValue(QString("method"), method, obj, QString("QString")); toJsonValue(QString("title"), title, obj, QString("QString")); toJsonValue(QString("time"), time, obj, QString("QDateTime")); return obj; } bool SWGStandardInitiateLoginResultData::getSuccess() { return success; } void SWGStandardInitiateLoginResultData::setSuccess(bool success) { this->success = success; } SWGSuccessInitiateLoginResponse* SWGStandardInitiateLoginResultData::getMessage() { return message; } void SWGStandardInitiateLoginResultData::setMessage(SWGSuccessInitiateLoginResponse* message) { this->message = message; } QString* SWGStandardInitiateLoginResultData::getMethod() { return method; } void SWGStandardInitiateLoginResultData::setMethod(QString* method) { this->method = method; } QString* SWGStandardInitiateLoginResultData::getTitle() { return title; } void SWGStandardInitiateLoginResultData::setTitle(QString* title) { this->title = title; } QDateTime* SWGStandardInitiateLoginResultData::getTime() { return time; } void SWGStandardInitiateLoginResultData::setTime(QDateTime* time) { this->time = time; } } /* namespace Swagger */
a9e134c7dfa6d503ca6630a59bac4f97a3bded4d
ddad5e9ee062d18c33b9192e3db95b58a4a67f77
/util/uring/sliding_counter.h
861d4797670e511d9b977b0c35817b122e9a5291
[ "BSD-2-Clause" ]
permissive
romange/gaia
c7115acf55e4b4939f8111f08e5331dff964fd02
8ef14627a4bf42eba83bb6df4d180beca305b307
refs/heads/master
2022-01-11T13:35:22.352252
2021-12-28T16:11:13
2021-12-28T16:11:13
114,404,005
84
17
BSD-2-Clause
2021-12-28T16:11:14
2017-12-15T19:20:34
C++
UTF-8
C++
false
false
3,177
h
// Copyright 2020, Beeri 15. All rights reserved. // Author: Roman Gershman ([email protected]) // #pragma once #include <array> #include <cstdint> #include <memory> #include <numeric> #include "util/uring/proactor_pool.h" namespace util { namespace uring { namespace detail { class SlidingCounterTLBase { protected: // Returns the bin corresponding to the current timestamp. Has second precision. // updates last_ts_ according to the current timestamp and returns the latest bin. // has const semantics even though it updates mutable last_ts_. uint32_t MoveTsIfNeeded(size_t size, int32_t* dest) const; mutable uint32_t last_ts_ = 0; }; class SlidingCounterBase { protected: void InitInternal(ProactorPool* pp); void CheckInit() const; unsigned ProactorThreadIndex() const; ProactorPool* pp_ = nullptr; }; } // namespace detail /** * @brief Sliding window data structure that can aggregate moving statistics. * It's implmented using ring-buffer with size specified at compile time. * * @tparam NUM */ template <unsigned NUM> class SlidingCounterTL : protected detail::SlidingCounterTLBase { static_assert(NUM > 1, "Invalid window size"); using T = int32_t; mutable std::array<T, NUM> count_; public: SlidingCounterTL() { Reset(); } void Inc() { IncBy(1); } void IncBy(int32_t delta) { int32_t bin = MoveTsIfNeeded(NUM, count_.data()); count_[bin] += delta; } // Sums over bins not including the last bin that is currently being filled. T SumTail() const; T Sum() const { MoveTsIfNeeded(NUM, count_.data()); return std::accumulate(count_.begin(), count_.end(), 0); } void Reset() { count_.fill(0); } }; // Requires proactor_pool initialize all the proactors. template <unsigned NUM> class SlidingCounter : protected detail::SlidingCounterBase { using Counter = SlidingCounterTL<NUM>; public: enum {WIN_SIZE = NUM}; SlidingCounter() = default; void Init(ProactorPool* pp) { InitInternal(pp); sc_thread_map_.reset(new Counter[pp_->size()]); } void Inc() { sc_thread_map_[ProactorThreadIndex()].Inc(); } uint32_t Sum() const { CheckInit(); std::atomic_uint32_t res{0}; pp_->AwaitOnAll([&](unsigned i, Proactor*) { res.fetch_add(sc_thread_map_[i].Sum(), std::memory_order_relaxed); }); return res.load(std::memory_order_release); } uint32_t SumTail() const { CheckInit(); std::atomic_uint32_t res{0}; pp_->AwaitOnAll([&](unsigned i, Proactor*) { res.fetch_add(sc_thread_map_[i].SumTail(), std::memory_order_relaxed); }); return res.load(std::memory_order_release); } private: std::unique_ptr<Counter[]> sc_thread_map_; }; /********************************************* Implementation section. **********************************************/ template <unsigned NUM> auto SlidingCounterTL<NUM>::SumTail() const -> T { int32_t start = MoveTsIfNeeded(NUM, count_.data()) + 1; // the tail is one after head. T sum = 0; for (unsigned i = 0; i < NUM - 1; ++i) { sum += count_[(start + i) % NUM]; } return sum; } } // namespace uring } // namespace util
cec6705e458eb24c34267b6b01a44a90e8b29c02
119828e4a5a7bd3cec7360d47765e68a780fe34d
/Framework/Core/D3D11/OMStage/BlendState.cpp
9ba9fdd85887f311af31d83522d5a3aed346be0d
[]
no_license
JoSungHun/TerrianEditor
4b5b11cf0d672b114e0ab7d7940f674e232beae2
fb8c57dfe270df7e52dfd04e9e81c7b00b29f458
refs/heads/master
2020-06-05T03:53:00.212549
2019-06-17T08:33:19
2019-06-17T08:33:19
192,304,158
1
0
null
null
null
null
UTF-8
C++
false
false
3,741
cpp
#include "Framework.h" #include "BlendState.h" std::map<Factor, D3D11_BLEND> BlendState::blend_factors { std::make_pair(Factor::ZERO , D3D11_BLEND_ZERO), std::make_pair(Factor::ONE , D3D11_BLEND_ONE), std::make_pair(Factor::SRC_COLOR , D3D11_BLEND_SRC_COLOR), std::make_pair(Factor::INV_SRC_COLOR , D3D11_BLEND_INV_SRC_COLOR), std::make_pair(Factor::SRC_ALPHA , D3D11_BLEND_SRC_ALPHA), std::make_pair(Factor::INV_SRC_ALPHA , D3D11_BLEND_INV_SRC_ALPHA), std::make_pair(Factor::DEST_ALPHA , D3D11_BLEND_DEST_ALPHA), std::make_pair(Factor::INV_DEST_ALPHA , D3D11_BLEND_INV_DEST_ALPHA), std::make_pair(Factor::DEST_COLOR , D3D11_BLEND_DEST_COLOR), std::make_pair(Factor::INV_DEST_COLOR , D3D11_BLEND_INV_DEST_COLOR), }; std::map<Operation, D3D11_BLEND_OP> BlendState::blend_operations { std::make_pair(Operation::ADD , D3D11_BLEND_OP_ADD), std::make_pair(Operation::SUBTRACT , D3D11_BLEND_OP_SUBTRACT), std::make_pair(Operation::REV_SUBTRACT , D3D11_BLEND_OP_REV_SUBTRACT), std::make_pair(Operation::MIN , D3D11_BLEND_OP_MIN), std::make_pair(Operation::MAX , D3D11_BLEND_OP_MAX), }; std::map<ColorMask, D3D11_COLOR_WRITE_ENABLE> BlendState::blend_color_masks { std::make_pair(ColorMask::RED , D3D11_COLOR_WRITE_ENABLE_RED), std::make_pair(ColorMask::GREEN , D3D11_COLOR_WRITE_ENABLE_GREEN), std::make_pair(ColorMask::BLUE , D3D11_COLOR_WRITE_ENABLE_BLUE), std::make_pair(ColorMask::ALPHA , D3D11_COLOR_WRITE_ENABLE_ALPHA), std::make_pair(ColorMask::ALL , D3D11_COLOR_WRITE_ENABLE_ALL), }; auto BlendState::GetBitMask(const bool & blend_enable, const Factor & src_blend, const Factor & dest_blend, const Operation & blend_op, const Factor & src_blend_alpha, const Factor & dest_blend_alpha, const Operation & blend_op_alpha, const ColorMask & color_mask) -> const uint { return static_cast<uint>(blend_enable) | static_cast<uint>(src_blend) | static_cast<uint>(dest_blend) | static_cast<uint>(blend_op) | static_cast<uint>(src_blend_alpha) | static_cast<uint>(dest_blend_alpha) | static_cast<uint>(blend_op_alpha) | static_cast<uint>(color_mask); } BlendState::BlendState(Context * context) : state(nullptr) { graphics = context->GetSubsystem<Graphics>(); } BlendState::~BlendState() { Clear(); } auto BlendState::Create(const bool & blend_enable, const Factor & src_blend, const Factor & dest_blend, const Operation & blend_op, const Factor & src_blend_alpha, const Factor & dest_blend_alpha, const Operation & blend_op_alpha, const ColorMask & color_mask) -> const uint { D3D11_BLEND_DESC desc; ZeroMemory(&desc, sizeof(D3D11_BLEND_DESC)); desc.AlphaToCoverageEnable = false; desc.IndependentBlendEnable = false; desc.RenderTarget[0].BlendEnable = blend_enable; desc.RenderTarget[0].SrcBlend = blend_factors[src_blend]; desc.RenderTarget[0].DestBlend = blend_factors[dest_blend]; desc.RenderTarget[0].BlendOp = blend_operations[blend_op]; desc.RenderTarget[0].SrcBlendAlpha = blend_factors[src_blend_alpha]; desc.RenderTarget[0].DestBlendAlpha = blend_factors[dest_blend_alpha]; desc.RenderTarget[0].BlendOpAlpha = blend_operations[blend_op_alpha]; desc.RenderTarget[0].RenderTargetWriteMask = blend_color_masks[color_mask]; auto result = SUCCEEDED(graphics->GetDevice()->CreateBlendState(&desc, &state)); if (!result) { LOG_ERROR("Failed to create blend state"); return 0; } return GetBitMask ( blend_enable, src_blend, dest_blend, blend_op, src_blend_alpha, dest_blend_alpha, blend_op_alpha, color_mask ); } void BlendState::Clear() { SAFE_RELEASE(state); } void BlendState::BindPipeline() { float blend_factor[4]{ 0.0f,0.0f,0.0f,0.0f }; graphics->GetDeviceContext()->OMSetBlendState(state, blend_factor, 0xffffffff); }
c71c2e6fb4831bd3611b792147154dbc6ecd989b
20049d88e2e8f0e1904efc561103c1d84d21507a
/bessonov.alexandr/common/circle.cpp
3cc59c615221d4b7f7f2fa7b8df6b9fbfd60b722
[]
no_license
gogun/Labs-for-SPbSPU-C-course-during-2019
5442a69152add3e66f02a7541e8dc8dd817f38a1
16ade47b859517a48d0fdb2e9704464bce4cc355
refs/heads/master
2022-01-09T16:02:54.728830
2019-06-06T11:06:33
2019-06-06T11:06:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
#define _USE_MATH_DEFINES #include "circle.hpp" #include <iostream> #include <stdexcept> #include <cmath> bessonov::Circle::Circle(const bessonov::point_t &newCenter, double radius) : center_(newCenter), radius_(radius) { if (radius <= 0) { throw std::invalid_argument("Problematic radius"); } } void bessonov::Circle::move(double dx, double dy) { center_.x += dx; center_.y += dy; } void bessonov::Circle::move(const point_t &newCenter) { center_ = newCenter; } double bessonov::Circle::getArea() const { return M_PI * radius_ * radius_; } bessonov::rectangle_t bessonov::Circle::getFrameRect() const { return { 2 * radius_, 2 * radius_, center_ }; } void bessonov::Circle::scale(double factor) { if (factor <= 0) { throw std::invalid_argument("Problematic factor"); } radius_ *= factor; }
02d1973b51d370b7d2b701461066ff3d31094db9
834b551c9e17345d761bc54c6a56c2de9002d6ac
/problems/234. Palindrome Linked List/two_pointer.cpp
0c72fcee42c8dfdc6135830fd3bb120d76f67216
[]
no_license
nullscc/leetcode
15507aecbb256acff0506bbc2bdb4dada113553b
95fbe47252b6f5e88378719fcdf3ee6200c68de4
refs/heads/main
2023-03-20T08:36:22.313209
2021-03-02T08:40:20
2021-03-02T08:40:20
330,892,647
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { ListNode *fast=head, *slow=head; vector<int> s; while(fast && fast->next) { s.push_back(slow->val); slow = slow->next; fast = fast->next->next; } if(fast) { slow = slow->next; } int n = s.size()-1; while(n >= 0) { if(s[n--] != slow->val) return false; slow = slow->next; } return true; } };
050df6bcfe398a091ab5348c45947ad92f8822eb
4441cd8e9c5049016c42f03d5c2da893ac294505
/include/demons.h
3ce5e25b0aaeb30b733d51ddbc8576d7e2de2fee
[]
no_license
yourDM-tristan-j/ex08-creatures
17372e78f6dbcdcd8cdfafd2ee91572226ab3586
43abaa3fdc15cd6b825024bcedb18f05775ed0eb
refs/heads/master
2020-04-10T00:56:00.028114
2018-12-06T17:49:12
2018-12-06T17:49:12
160,700,398
0
0
null
2018-12-06T16:16:49
2018-12-06T16:16:48
null
UTF-8
C++
false
false
1,395
h
class Demons : public Creature { private: } static const std::string CYBERDEMON_NAME = "CyberDemon"; static const std::string BALROG_NAME = "BALROG"; class Cyberdemon : public Demons{ private: int type = 1; int strength = DEFAULT_STRENGTH; int strength = DEFAULT_HIT_POINTS; const string &getSpecies() const { return CYBERDEMON_NAME; }; public : Creature( ); // Initialize to human, 10 strength, 10 hit points Creature( int newType, int newStrength, int newHit); // Initialize creature to new type, strength, hit points // Also add appropriate accessor and mutator functions // for type, strength, and hit points int getDamage(); // Returns amount of damage this creature // inflicts in one round of combat }; class Balrog : public Demons { private: int type = 2; int strength = DEFAULT_STRENGTH; int strength = DEFAULT_HIT_POINTS; const string &getSpecies() const { return BALROG_NAME; }; public : Creature( ); // Initialize to human, 10 strength, 10 hit points Creature( int newType, int newStrength, int newHit); // Initialize creature to new type, strength, hit points // Also add appropriate accessor and mutator functions // for type, strength, and hit points int getDamage(); // Returns amount of damage this creature // inflicts in one round of combat };
39f254028246b96f1f7f1493dd100052b2867c5f
8de91a1aebb00600a98a69b7b8c783cb6a020720
/cp/MaxFlow.cpp
05ef8dbcd14733a3b3738e3a9485ab2cd295f79c
[]
no_license
RenatoBrittoAraujo/Competitive-Programming
2148d5fc4b0ac4b8fdbadc8de2916b31a549e183
de641f129a1ce27deffb7bf7c1635d702d05bf3e
refs/heads/master
2020-05-22T21:17:41.420014
2019-05-17T00:39:20
2019-05-17T00:39:20
186,523,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,340
cpp
#include <bits/stdc++.h> using namespace std; #define MAX_V 1500 //more than this and maxflow takes too long #define inf 1000000 using vi = vector<int>; int G[MAX_V][MAX_V]; vi p; int mf,f,s,t; void augment(int v,int me){ if(v==s){ f=me; return; }else if(p[v]!=-1){ augment(p[v],min(me,G[p[v]][v])); G[p[v]][v]-=f; G[v][p[v]]+=f; } } int main(){ //SET 't' (sink), 's' (source), and the 'G' graph to run max flow //print graph for(int i=0;i<n+2;i++){ for(int j=0;j<n+2;j++){ printf(" %5d",G[i][j]); }printf("\n"); } //MAX FLOW BFS LOOP mf=0; while(1){ f=0; vi dist(MAX_V, inf); dist[s]=0; queue<int> q; q.push(s); p.assign(MAX_V,-1); while(!q.empty()){ int u = q.front(); q.pop(); if(t==u)break; for(int v=0;v<MAX_V;v++) if(G[u][v]>0&&dist[v]==inf) dist[v]=dist[u]+1,q.push(v),p[v]=u; } augment(t,inf); if(f==0)break; mf+=f; } //mf is the maxflow value, n-mf=mcbm, in a bipartite graph mcbm = mis (max independent set) } return 0; }
cf3d8362f23fa1b071612e055f47c7515d2de9b0
2348000ede440b3513010c29a154ca70b22eb88e
/src/CPP/src/epi/chapter17/IsPatternContainedInGrid.hpp
e5104c7c368eb4a77f2e4bad62dec24a0a54f491
[]
no_license
ZhenyingZhu/ClassicAlgorithms
76438e02ecc813b75646df87f56d9588ffa256df
86c90c23ea7ed91e8ce5278f334f0ce6e034a38c
refs/heads/master
2023-08-27T20:34:18.427614
2023-08-25T06:08:00
2023-08-25T06:08:00
24,016,875
2
1
null
null
null
null
UTF-8
C++
false
false
1,200
hpp
#ifndef SRC_EPI_CHAPTER17_ISPATTERNCONTAINEDINGRID_HPP_ #define SRC_EPI_CHAPTER17_ISPATTERNCONTAINEDINGRID_HPP_ #include "../../Solution.h" #include <vector> #include <unordered_set> #include <tuple> namespace epi { namespace chapter17 { class IsPatternContainedInGrid : public myutils::Solution { public: IsPatternContainedInGrid(): Solution("EPI Chapter 17.5", "Search for a sequence in a 2D array", "Start from a cell, check if it could be a start of " "a subarray. Use hash table to record previous results.") { } ~IsPatternContainedInGrid() { } bool isPatternContainedInGrid(const std::vector<std::vector<int>> &grid, const std::vector<int> &pattern); bool test(); private: typedef int Offset; struct TupleHash; bool patternChecker(int x, int y, Offset offset, const std::vector<std::vector<int>> &grid, const std::vector<int> &pattern, std::unordered_set<std::tuple<int, int, Offset>, TupleHash> &failedCells); }; } // chapter17 } // epi #endif /* SRC_EPI_CHAPTER17_ISPATTERNCONTAINEDINGRID_HPP_ */
d22d8a8843200b30a97c610fe6081041957d9b54
a72916978618f0978974e58be661bb347a28bb10
/plugins/Project/vlSaveProject.h
d9281e79952cadbc2103fbfdd37a97b0270f159f
[]
no_license
Armida220/drv2.0
a77523c163ee6887cccb648b833de3bbe1c840fe
5b2610fd2159ad1408608c35f5d4bef4e64127ba
refs/heads/master
2020-04-10T10:03:12.552174
2018-07-19T02:40:40
2018-07-19T02:40:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
851
h
#pragma once #include "UIPlugins.h" #include "x3py/module/classmacro.h" //#include "ProjectObserver.h" #include "UIPluginsEvents.h" USING_NAMESPACE_EARTHMATRIX const char* const clsidvlSaveProject = "00000000-6000-0000-0000-000000000002"; class CvlSaveProject : public IUICommon, public IUICommand, public IAnythingEventObserver { X3BEGIN_CLASS_DECLARE(CvlSaveProject, clsidvlSaveProject) X3DEFINE_INTERFACE_ENTRY(IUICommon) X3DEFINE_INTERFACE_ENTRY(IUICommand) X3END_CLASS_DECLARE() public: CvlSaveProject(void); ~CvlSaveProject(void); public: // IUICommon virtual bool Initialize(); virtual bool UnInitialize(); virtual bool SetBuddy(x3::IObject* val); virtual bool OnAnything2(x3::IObject* sender, const std::string& eventKey, const std::string& filename); // IUICommand virtual bool OnClick(); void SaveProject(); };
7b040c87258aa6fe094d601d6f589386390d4bd5
15612c6affbeb98781e19f7de0d3f1db72cf1db9
/include/utility/relation_node.hpp
97e5891a725439904d443bf8903a71bbf70d4c53
[ "Apache-2.0" ]
permissive
federeghe/chronovise
332ad62ab046a2ff8ed1d03cf7e66a366717b630
4b332f10669af73f33e00f8749040eed9601bfb2
refs/heads/master
2023-02-24T05:25:51.369574
2021-12-08T10:31:26
2021-12-08T10:31:26
111,384,255
3
5
null
null
null
null
UTF-8
C++
false
false
2,009
hpp
/* * chronovise - Copyright 2018 Politecnico di Milano * * 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. */ /** * @file utility/relation_node.hpp * @author Check commit authors * @brief File containing the RelationNode and related classes/types */ #ifndef UTILITY_RELATION_NODE_HPP_ #define UTILITY_RELATION_NODE_HPP_ #include <list> #include <memory> #include <numeric> namespace chronovise { typedef enum class relation_node_e { UKNOWN, /** Error value, it should not be used */ TEST, /** Statistical test */ OPERATOR, /** Operator */ } relation_node_t; class RelationNode { public: RelationNode(relation_node_t type) : type(type) { } virtual ~RelationNode() { } relation_node_t get_type() const noexcept { return this->type; } void add_child(std::shared_ptr<RelationNode> rn); std::list<std::shared_ptr<RelationNode>>::const_iterator cbegin() const noexcept { return this->children.cbegin(); } std::list<std::shared_ptr<RelationNode>>::const_iterator cend() const noexcept { return this->children.cend(); } const std::list<std::shared_ptr<RelationNode>> & get_children() const noexcept { return this->children; } size_t get_local_size() const noexcept { return this->children.size(); } size_t get_total_size() const noexcept; private: relation_node_t type; std::list<std::shared_ptr<RelationNode>> children; }; } // namespace chronovise #endif
50e9d5f1b0d52fe9c7b4b4f85244af9b7e7839d4
cc733834bdb5b4d33210c091744100c818beb2cb
/knRapid/src/rapidCommanding/RapidSubsystemRepository.cpp
ef85f41b27edfac089e25209869c166af5e64dc3
[ "Apache-2.0" ]
permissive
hhutz/soraCore
b7d592424afb2ff111c24f542853a993d99326e3
0b140e0bca251498c3b12c102d04bcb68e4c31b1
refs/heads/master
2021-06-26T00:37:20.379488
2015-12-17T17:18:51
2016-02-11T17:29:47
21,436,387
1
5
null
2021-06-18T16:59:09
2014-07-02T18:50:50
C++
UTF-8
C++
false
false
348
cpp
#include "RapidSubsystemRepository.h" // does this evaluate to true on any of our target platforms? #if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION) template kn::Singleton<kn::RapidSubsystemRepository> * kn::Singleton<kn::RapidSubsystemRepository>::s_instance; #endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */
[ "mallan@71bd3d61-4118-0410-985d-8aea7a627388" ]
mallan@71bd3d61-4118-0410-985d-8aea7a627388
b5b70ea6679d5af7de9a77fdcf3cb0fb7a07ef78
058355106fcf57b746afc5e9979281477c8bd34c
/.history/138.copy-list-with-random-pointer_20200907102809.cpp
fbf65e27a52076910a2e4344160d812b3ce7149b
[]
no_license
Subzero-10/leetcode
ff24f133f984b86eac686ed9b9cccbefb15c9dd8
701ec3dd4020970ecb55734de0355c8666849578
refs/heads/master
2022-12-24T19:03:16.482923
2020-10-11T09:25:29
2020-10-11T09:25:29
291,388,415
0
0
null
null
null
null
UTF-8
C++
false
false
978
cpp
/* * @lc app=leetcode id=138 lang=cpp * * [138] Copy List with Random Pointer */ // @lc code=start /* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { Node* root = head; while (head) { Node* newHead = new Node(head->val); newHead->next = head->next; head->next = newHead; head = newHead->next; } Node* head2 = root; root = root->next; while (head2) { Node* newHead = head2->next; newHead->random = head2->random->next; head2->next = newHead->next; newHead->next = newHead->next->next; head2 = head2->next; printf("?"); } return root; } }; // @lc code=end
6fdde89259ba407174c3281cdb9aaca262f2bfc0
4d682826c92a14c3d8bb12a213130b8a6814b738
/Wires/wires.cpp
7e9d429cce7ae2d21c9e37dbda9e3e9d0698fad7
[]
no_license
FilipKernan/adventOfCodeCpp
1cc84bec2da5ef33e633d781f48face146b8347d
e1eea76ef56d1371fbb8876a5f83113c59a981c1
refs/heads/master
2022-11-21T17:13:22.890686
2020-07-21T18:04:54
2020-07-21T18:04:54
277,353,000
0
0
null
null
null
null
UTF-8
C++
false
false
3,648
cpp
// // Created by filip on 7/7/20. // #include "wires.h" std::vector<intersection> findIntersections(std::string string,int &height,int &width){ // creates an array for the wires to exist on long** wireArray = new long *[height]; for (int l = 0; l < height; ++l) { wireArray[l] = new long[width]; } fill(wireArray, height, width); // splits the puzzle input std::size_t found = string.find("\n", 1); std::string stringArray[2] = {string.substr(1, found), string.substr(found + 1)}; // creates a log of intersections std::vector<intersection> intersections; // loops though each wire for (int i = 0; i < 2; ++i) { int x = height/2, y = width/2; int size = 0; // splits wire instructions appart std::vector<std::string> stringVector = split(stringArray[i], size); long pastLength = 0; for (int j = 0; j < size; ++j) { // parsing the wire instructions std::string currentInstruction = stringVector[j]; char direction = currentInstruction[0]; int lenght = std::stoi(currentInstruction.substr(1)); for (int k = 0; k < lenght; ++k) { if (wireArray[y][x] > 0 && i == 1) { // logs any intersections that are detected intersection section; section.x = x; section.y = y; section.xSteps = pastLength + k; section.ySteps = wireArray[y][x]; intersections.push_back(section); } else { if (i <= 0 && wireArray[y][x] == 0) { wireArray[y][x] = pastLength + k; } } switch (direction) { case 'U': y++; break; case 'D': y--; break; case 'R': x++; break; case 'L': x--; break; } } pastLength += lenght ; } } return intersections; } // splits appart a string of instuctions to individual instuctions std::vector<std::string> split(std::string string, int& size){ size = std::count(string.begin(), string.end(), ',') + 1; std::vector<std::string> turnList; int lastTurn = 0; for (int j = 0; j < size; ++j) { turnList.push_back( string.substr(lastTurn, string.find(",", lastTurn + 1) - (lastTurn))); lastTurn = string.find(",", lastTurn + 1) + 1; } return turnList; } intersection findClosestManhatten(std::vector<intersection> intersections){ std::sort(intersections.begin(), intersections.end(), compareManhattenDistance); return intersections[0]; } intersection findClosestWireDistance(std::vector<intersection> intersections){ std::sort(intersections.begin(), intersections.end(), compareWireDistance); return intersections[0]; } // fills an array with 0s void fill(long** wireArray, int height, int width) { for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { wireArray[i][j] = 0; } } } bool compareManhattenDistance( intersection &a, intersection &b){ return (abs(a.x - (ARRAY_SIZE/2)) + abs(a.y - (ARRAY_SIZE/2))) < (abs(b.x - (ARRAY_SIZE/2)) + abs(b.y - (ARRAY_SIZE/2))); } bool compareWireDistance( intersection &a, intersection &b) { return a.xSteps + a.ySteps < b.xSteps + b.ySteps; }
d7a556185663cc98990de49e3175279a6e05f520
37421955fdae8ab64fa65c4fa91a6b2622bc14ef
/common/camera.h
99fbafcb7fdf33da12cbd11b8b3e59f06dd905d0
[]
no_license
SasaWakaba/Stelemate
c8ac4f49e4116911c044a9f559437c9b82d464bd
20c003206ff3ba2b987ef978a98c8fe0514f87ab
refs/heads/master
2020-09-05T18:52:41.011485
2020-03-29T11:53:39
2020-03-29T11:53:39
220,181,236
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
857
h
#pragma once #include "Game_Object.h" class CCamera:public CGameObject { private: XMMATRIX m_ViewMatrix; RECT m_Viewport; static XMFLOAT3 m_Eye; //カメラ座標 static XMFLOAT3 m_at; //見てる場所(注視点) XMFLOAT3 m_CameraFront; //カメラの正面、長さ1 XMFLOAT3 m_CameraRight; //カメラの右側、長さ1 XMFLOAT3 m_CameraUp; //カメラの上、長さ1 float m_Length; //見てる場所までの長さ static bool bMove; static XMFLOAT3 MoveLength; static int cnt; public: void Initialize(); void Finalize(); void Update(); void Draw(); XMMATRIX* GetView(); static void SetAt(XMFLOAT3 pos) { m_at = pos; } static void Move(XMFLOAT3 at) { MoveLength = XMFLOAT3(at.x - m_at.x, at.y - m_at.y, at.z - m_at.z); bMove = true; cnt = 0; } static XMFLOAT3 GetEye() { return m_Eye; } };
41b472878bb0ffe02474a43f939a0f9d14736c31
b62835c35ededb2d1b4cb0a83db1945f06099479
/threads/threads/sample.cpp
ffe4901e335165c8ef0d0cd3c87d6567c05e3c12
[]
no_license
kylerichey/exampleCodeCS360
b03a584492f8a480af612cf23c85991d82ad5836
b88805047bacdffb2e8982db1da919ea68bac5b3
refs/heads/master
2021-01-24T17:50:44.485337
2016-03-28T21:08:15
2016-03-28T21:08:15
53,171,449
1
0
null
null
null
null
UTF-8
C++
false
false
956
cpp
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> void *functionC(void *ptr); int counter = 0; main() { int rc1, rc2; pthread_t thread1, thread2; /* Create independent threads each of which will execute functionC */ if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) ) { printf("Thread creation failed: %d\n", rc1); } if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) ) { printf("Thread creation failed: %d\n", rc2); } /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL); exit(0); } void *functionC(void *ptr) { int tmp = counter; sleep(1); tmp++; counter = tmp; printf("Counter value: %d\n",counter); }
c6ae62bae17c0ec324ca0aa0d67cbb08a72dce4d
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/Display/Font.h
03d4940ce4ff0bfd662810249e01fff5b4dea7da
[]
no_license
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,208
h
#ifndef __FONT_H__ #define __FONT_H__ #include "../Display/Display.h" namespace ElixirEngine { //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFontText : public DisplayObject { public: DisplayFontText(); virtual ~DisplayFontText(); virtual void SetText(const wstring& _wstrText) = 0; virtual void SetColor(const Vector4& _f4Color) = 0; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFont : public CoreObject { public: DisplayFont(DisplayFontManagerRef _rFontManager); virtual ~DisplayFont(); virtual DisplayFontTextPtr CreateText() = 0; virtual void ReleaseText(DisplayFontTextPtr _pText) = 0; virtual DisplayRef GetDisplay() = 0; protected: DisplayFontManagerRef m_rFontManager; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFontLoader : public CoreObject { public: DisplayFontLoader(DisplayFontManagerRef _rFontManager); virtual ~DisplayFontLoader(); virtual DisplayFontPtr Load(const string& _strFileName) = 0; virtual void Unload(DisplayFontPtr _pFont) = 0; protected: DisplayFontManagerRef m_rFontManager; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFontManager : public CoreObject { public: DisplayFontManager(DisplayRef _rDisplay); virtual ~DisplayFontManager(); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); bool Load(const Key& _uNameKey, const string& _strFileName); void Unload(const Key& _uNameKey); DisplayFontPtr Get(const Key& _uNameKey); DisplayRef GetDisplay(); protected: struct Link { Link(); Link(DisplayFontPtr _pFont, DisplayFontLoaderPtr _pLoader); DisplayFontPtr m_pFont; DisplayFontLoaderPtr m_pLoader; }; typedef map<Key, Link> LinkMap; protected: bool RegisterLoader(const Key& _uExtensionKey, DisplayFontLoaderPtr _pLoader); void UnregisterLoader(const Key& _uExtensionKey); DisplayFontLoaderPtr GetLoader(const Key& _uExtensionKey); protected: DisplayRef m_rDisplay; LinkMap m_mFonts; DisplayFontLoaderPtrMap m_mLoaders; }; } #endif
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329
457ac81b2f53dc5f3dd38774e432d5f86fa4ce4d
aa803dab12247d693cddb8e2ba1b61f807547fe9
/build-SMail-Desktop_Qt_5_4_1_MSVC2013_64bit-Debug/ui_mainwindow.h
b57400ec4fc348c1f9684832be58bb9b44ad20ca
[]
no_license
Luqaz/SPOVM
1a767ccc6f8e5c996deb4b4beb99eefa266395a2
5fa5d18a6250c7ee7a0b8b3bed6ecbad32cf469a
refs/heads/master
2020-12-25T19:26:09.156788
2015-05-31T16:39:18
2015-05-31T16:39:18
30,823,319
0
0
null
null
null
null
UTF-8
C++
false
false
3,211
h
/******************************************************************************** ** Form generated from reading UI file 'mainwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.4.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MAINWINDOW_H #define UI_MAINWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QListWidget> #include <QtWidgets/QMainWindow> #include <QtWidgets/QPushButton> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_MainWindow { public: QWidget *centralWidget; QListWidget *AccountList; QListWidget *MessageList; QPushButton *sendButton; QPushButton *addAccountButton; QPushButton *deleteButton; void setupUi(QMainWindow *MainWindow) { if (MainWindow->objectName().isEmpty()) MainWindow->setObjectName(QStringLiteral("MainWindow")); MainWindow->resize(813, 493); MainWindow->setMinimumSize(QSize(813, 493)); MainWindow->setMaximumSize(QSize(813, 493)); centralWidget = new QWidget(MainWindow); centralWidget->setObjectName(QStringLiteral("centralWidget")); centralWidget->setStyleSheet(QStringLiteral("background-color: rgb(255, 255, 255)")); AccountList = new QListWidget(centralWidget); AccountList->setObjectName(QStringLiteral("AccountList")); AccountList->setGeometry(QRect(10, 100, 256, 351)); AccountList->setResizeMode(QListView::Adjust); MessageList = new QListWidget(centralWidget); MessageList->setObjectName(QStringLiteral("MessageList")); MessageList->setGeometry(QRect(270, 100, 521, 351)); MessageList->setResizeMode(QListView::Adjust); sendButton = new QPushButton(centralWidget); sendButton->setObjectName(QStringLiteral("sendButton")); sendButton->setGeometry(QRect(714, 460, 81, 23)); addAccountButton = new QPushButton(centralWidget); addAccountButton->setObjectName(QStringLiteral("addAccountButton")); addAccountButton->setGeometry(QRect(110, 460, 75, 23)); deleteButton = new QPushButton(centralWidget); deleteButton->setObjectName(QStringLiteral("deleteButton")); deleteButton->setGeometry(QRect(190, 460, 75, 23)); MainWindow->setCentralWidget(centralWidget); retranslateUi(MainWindow); QMetaObject::connectSlotsByName(MainWindow); } // setupUi void retranslateUi(QMainWindow *MainWindow) { MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0)); sendButton->setText(QApplication::translate("MainWindow", "Send Message", 0)); addAccountButton->setText(QApplication::translate("MainWindow", "Add Account", 0)); deleteButton->setText(QApplication::translate("MainWindow", "Delete", 0)); } // retranslateUi }; namespace Ui { class MainWindow: public Ui_MainWindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MAINWINDOW_H
9c8e823ec318d1bd184c3f0581615cdd1690f0c2
99a2728f6ac5193c6d2f95f1d8d739463a216d83
/core/game_state.h
e80f53a7bc787fcac94f4c8524a13d9bf6096df1
[]
no_license
LeifAndersen/MarbleMachine
d78d1a14dd3d10bf0bf4c0701d3d2d2db7658a3e
4dd06c0f817a0b177ae1c288b754dabbc9b361d5
refs/heads/master
2021-01-22T06:54:52.572160
2011-08-24T17:28:15
2011-08-24T17:28:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,582
h
#ifndef GAME_STATE_H #define GAME_STATE_H #include <list> #include <pthread.h> #include <string> #include "os_calls.h" #include "physics.h" #include "data_importer.h" #include "sphere.h" #include "point.h" #include "button.h" #define UPDATE_TIME 0.000000005f #define WIDTH 100.0f #define TOUCH_DAMPENER 15.0f #define ROTATION_SPEED 25.0f #define MODE_GALACTIC_MENU_SETUP 0 #define MODE_GALACTIC_MENU 1 #define MODE_GALACTIC_SECTOR_MENU 2 #define MODE_GALACTIC_SECTOR_MENU_SETUP 3 #define MODE_LEVEL_SETUP 4 #define MODE_LEVEL 5 #define MODE_LEVEL_WON 6 #define MODE_LEVEL_LOST 7 #define FONT_CHAR_SIZE 62 #define MINIMUM_WEIGHT 1 #define LIGHT_PLANET_WEIGHT_MAX 10 #define LIGHT_PLANET_WEIGHT_VARIENCE 1 #define MEDIUM_PLANET_WEIGHT_MAX 50 #define MEDIUM_PLANET_WEIGHT_VARIENCE 2 #define HEAVY_PLANET_WEIGHT_MAX 100 #define HEAVY_PLANET_WEIGHT_VARIENCE 3 #define ANTI_PLANET_WEIGHT_MAX -20 #define ANTI_PLANET_WEIGHT_VARIENCE -2 #define BLACK_HOLE_WEIGHT 100 #define MINIMUM_RADIUS 1 #define LIGHT_PLANET_RADIUS_MAX 5 #define LIGHT_PLANET_RADIUS_VARIENCE 1 #define MEDIUM_PLANET_RADIUS_MAX 10 #define MEDIUM_PLANET_RADIUS_VARIENCE 2 #define HEAVY_PLANET_RADIUS_MAX 15 #define HEAVY_PLANET_RADIUS_VARIENCE 3 #define ANTI_PLANET_RADIUS_MAX 12 #define ANTI_PLANET_RADIUS_VARIENCE 2 #define BLACK_HOLE_RADIUS 100 #define RADIUS_OFFSET 10 // Because we need the radius opperators in a mod function. #define BOTTOM_BUTTONS 5.0f #define BUTTON_WIDTH 40.0f #define BUTTON_WIDTH_HALF 20.0f #define BUTTON_HEIGHT 20.0f #define BUTTON_HEIGHT_HALF 10.0f #define PARTICLE_ROTATION 100 #define PARTICLE_ROTATION_VARIENT 200 #define PLANET_ROTATION 10 #define PLANET_ROTATION_VARIENT 20 typedef std::vector<Sphere>::iterator SphereIterator; class GameState { public: GameState(); ~GameState(); GameState(const GameState & other); GameState & operator =(const GameState & other); void mainLoop(); // Level data unsigned int level; unsigned int sector; std::string levelName; std::string sectorName; unsigned int highestLevel; unsigned int highestSector; unsigned int levelsInSector; unsigned int sectorsInGalaxy; // For those pieces of data which need a mutex, but aren't // written to much. pthread_mutex_t miscMutex; // Aspect ratio of the window (for matrix magic) void setAspectRatio(float width, float height); // For turning it into projection coordinates Matrix projectionMatrix; // The ship Sphere ship; std::vector<DrawablePoint> shipVerts; std::vector<GLushort> shipIndices; MMTEX * tex0; // Planets, also used for levels in menu bool activePlanetInUse; bool activePlanetPlaced; bool activePlanetSettingVelocity; unsigned short * activePlanetCount; // Points to the four unsigned short planet counts below Sphere activePlanet; std::vector<DrawablePoint> activePlanetVerts; std::vector<GLushort> activePlanetIndices; std::vector<Sphere> planets; std::vector<Sphere> particles; pthread_mutex_t planetsMutex; // If the game state's thread wants to add data pthread_mutex_t planetsAddMutex; // If any other thread wants to add data std::vector<DrawablePoint> lightPlanetVerts; std::vector<GLushort> lightPlanetIndices; std::vector<DrawablePoint> mediumPlanetVerts; std::vector<GLushort> mediumPlanetIndices; std::vector<DrawablePoint> heavyPlanetVerts; std::vector<GLushort> heavyPlanetIndices; std::vector<DrawablePoint> antiPlanetVerts; std::vector<GLushort> antiPlanetIndices; std::vector<DrawablePoint> blackHoleVerts; std::vector<GLushort> blackHoleIndices; std::vector<Sphere> pendingPlanets; std::vector<DrawablePoint> arrowVerts; std::vector<GLushort> arrowIndices; std::vector<DrawablePoint> particleVerts; std::vector<GLushort> particleIndices; unsigned short lightPlanets; unsigned short mediumPlanets; unsigned short heavyPlanets; unsigned short antiPlanets; // Goal the player is trying to get the ball to. Sphere goal; std::vector<DrawablePoint> goalVerts; std::vector<GLushort> goalIndices; // Should be handeled by controller code (main.cpp). // contineues the main loop when true bool stopLooping; pthread_mutex_t stopLoopingMutex; // For what the main loop will do. unsigned int mode; pthread_mutex_t modeMutex; // For the GLview, to see if there's new data to be loaded onto GPU bool dataNeedsLoading; pthread_mutex_t dataLoadingMutex; // Buttons Button menuButton; Button lightPlanetButton; Button mediumPlanetButton; Button heavyPlanetButton; Button antiPlanetButton; Button wonLevelButton; Button lostLevelButton; // a-z 0-25 // A-Z 26-51 // 0-9 52-61 button_verts_t font_chars[FONT_CHAR_SIZE]; // Menu Buttons Button restartLevelButton; Button quitLevelButton; Button muteMusicButton; Button unMuteMusicButton; Button muteEfxButton; Button unMuteEfxButton; DataImporter importer; bool menuOn; bool musicMuted; bool efxMuted; pthread_mutex_t soundMutex; // Background for the zone button_verts_t background; // Counters to know how many planets you have left Button counter; // Aspect ratio, read only please, set with the setaspectratio function float aspectRatio; // Loaded sounds int explosion; int buttonSound; private: Physics engine; // For time deltas MMTIMER * timer; }; #endif // GAME_STATE_H
0e90d0f6a8ce90f6a76e2bec6ad486a9a4a8046a
fe5e4748939432af1d691f9d5837206fbf6c6c2f
/C++/bfs_4.cpp
ab358cfa89455f1c25507562d4c0817d26161b16
[]
no_license
soadkhan/My-Code
e0ebe0898d68df983e8c41e56633780d6ac22c39
72fc258cdbf08d86f20a565afe371713e8e8bc39
refs/heads/master
2021-01-23T03:27:34.181019
2017-03-24T14:42:15
2017-03-24T14:42:15
86,077,758
0
0
null
null
null
null
UTF-8
C++
false
false
1,863
cpp
#include<bits/stdc++.h> using namespace std; typedef unsigned long long int ulld; typedef long long int lld; typedef long int ld; class node{ public: ld x; ld y; node(int a=0, int b=0){ x = a; y = b; } bool operator == (node a){ if(x==a.x&&y==a.y) return true; else return false; } }; ld mat[1010][1010]; ld dx[] = {1,0,-1,0}; ld dy[] = {0,1,0,-1}; ld bfs(node start,node des,ld r , ld c){ queue<node>list_node; list_node.push(start); while(list_node.empty()!=true){ node hand = list_node.front(); list_node.pop(); for(ld i = 0; i < 4 ; i++){ if(hand.x+dx[i]>=0&&hand.x+dx[i]<r&&hand.y+dy[i]>=0&&hand.y+dy[i]<c) if(mat[hand.x+dx[i]][hand.y+dy[i]]==0) { node next(hand.x+dx[i],hand.y+dy[i]); if(!(next==start))list_node.push(next); if(!(next==start))mat[hand.x+dx[i]][hand.y+dy[i]] = mat[hand.x][hand.y] + 1; if(des == next ) return mat[des.x][des.y]; } } } } int main(void) { //freopen("uva.txt","rt",stdin); //freopen("uva_out.txt","wt",stdout); ld r,c; while(cin>>r>>c){ if(r==0&&c==0) break; for(ld i = 0;i<r;i++) for(ld j=0;j<c;j++) mat[i][j] = 0; ld cases; cin>>cases; while(cases--){ ld row,col,num; cin>>row>>num; while(num--){ cin>>col; mat[row][col] = -1; } } int x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2; node start(x1,y1); node des(x2,y2); cout<<bfs(start,des,r,c)<<endl; } return 0; }
dde61d24a8ec8ab0aa669234ad4b8f9cccd4ccab
efa0c247b3d0636c14e83d548b407024c1aa594d
/core/pygmy_console.cpp
7af2dae02f36841429a8f8c995480e174b061002
[]
no_license
WarrenDGreenway/pygmyos
2729dd6e1fb6e80081a7660de3d00fb148ddacb5
f1738456a974c680539101e223a0e608e8564f52
refs/heads/master
2020-05-30T04:26:22.628394
2014-06-24T04:08:07
2014-06-24T04:08:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,260
cpp
/************************************************************************** PygmyOS ( Pygmy Operating System ) - BootLoader Copyright (C) 2011-2012 Warren D Greenway This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ***************************************************************************/ #include <vector> #include "pygmy_string.h" #include "pygmy_console.h" #include "pygmy_command.h" using namespace std; void Console::init( void ) { Command action( (void*)this, (void *)Console::run, "\r" ); this->RXBuffer->addAction( action ); commands = vector<Command>(); // initialize the command vector //this->commands.insert( new Command( (void *)Console::uname, "uname" ) ); this->commands.push_back( Command( (void *)this, (void *)Console::uname, "uname" ) ); //this->print( "\nsize in constructor: %d", this->commands.size() ); } void Console::init( vector<Command>&commands ) { this->commands = commands; } /* bool Console::run( const char *s ) { PygmyString tmpString( s ); this->run( tmpString ); } bool Console::run( PygmyString& s ) { }*/ bool Console::run( void *c, PygmyString& s ) { Console *console = (Console*)c; bool status; int size = console->commands.size(); //console->print( "\ns: %s", s.c_str() ); for( int i = 0; i < console->commands.size(); i++ ){ if( s.startsWith( console->commands[ i ].getName() ) ){ CommandFunctionPointer handler = (CommandFunctionPointer)console->commands[ i ].getHandler(); // todo: erase the command from string before passing to handler status = handler( console, s ); if( status == false ){ console->print( "\nError\n>" ); } // if return( status ); } // if } // for // no match was found } bool Console::uname( void *c, PygmyString& s ) { Console *console = (Console*)c; console->print( "\nuname not implemented" ); } bool Console::analog( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::pinconfig( void *c, PygmyString& s ) { Console *console = (Console*)c; PYGMYPARAMLIST parameters; if( s.getAllParameters( &parameters ) && parameters.ParamCount == 2 ){ /*if( pinConfig( convertStringToPin( parameters.Params[ 0 ] ), s.convertStringToMode( Parameters.Params[ 1 ] ) ) ){ freeParameterList( &Parameters ); return( TRUE ); } // if */ } // if return( false ); } bool Console::pinget( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::pinpwm( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::pinset( void *c, PygmyString& s ) { Console *console = (Console*)c; } //bool cmd_set( PygmyString& s ); //bool cmd_erase( PygmyString& s ); bool Console::format( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::rx( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::tx( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::read( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::rm( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::cd( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::append( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::open( void *c, PygmyString& s ) { Console *console = (Console*)c; } /*bool Console::new( vid *, PygmyString& s ) { Console *console = (Console*)c; }*/ bool Console::mkdir( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::rmdir( void *c, PygmyString& s ) { Console *console = (Console*)c; } //bool cmd_echo( PygmyString& s ); bool Console::cat( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::strings( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::dump( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::ls( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::touch( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::mv( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::cp( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::reset( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::boot( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::flash( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::fdisk( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::umount( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::mount( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::verify( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::test( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::date( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::time( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::find( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::df( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::du( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::pwd( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::tail( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::cksum( void *c, PygmyString& s ) { Console *console = (Console*)c; } //bool Console::if( PygmyString& s ); bool Console::sleep( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::lsof( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::gawk( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::declare( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::dc( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::kill( void *c, PygmyString& s ) { Console *console = (Console*)c; } bool Console::killall( void *c, PygmyString& s ) { Console *console = (Console*)c; } //bool cmd_null( PygmyString& s ); //bool cmd_cmd( PygmyString& s ); //bool cmd_run( PygmyString& s );*/
80f7c532559ad444bd1aaf29b105c279c18a08db
f0bba79c584a12c8461c4650572953ef719cbbaf
/include/core/gpumemory.h
a92e1456fc464f503e0370e4e4cba98637e90127
[]
no_license
YYXXYYZZ/soft-renderer
88490cf1665dc4ba49c77817a181cb9118dfc800
f4300575b967fc6035b4b41df441182554ce8c45
refs/heads/master
2021-11-25T10:46:08.291477
2014-10-29T07:57:29
2014-10-29T07:57:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,486
h
#ifndef GPUMEMORY_H #define GPUMEMORY_H #include <map> #include <cstring> #include <typeindex> #include <iostream> #include <exception> using std::string; using std::map; using std::type_index; namespace GPUMemory { struct MemoryInfo{ void * address; int size; string type; }; typedef map<string,MemoryInfo> DataMap; extern DataMap Global_Data; template<class T> bool alloc(const string& name, const int & size,T *&pointer){ try{ Global_Data.at(name); std::cerr << "Warning: alloc exist element! " << name << std::endl; return false; } catch(const std::out_of_range & ){ MemoryInfo info; T *data = new T[size](); info.address = static_cast<void *>(data); info.size = size; info.type = typeid(T).name(); Global_Data[name] = info; pointer = data; } return true; } template<class T> bool alloc(const string& name, const int & size){ try{ Global_Data.at(name); std::cerr << "Warning: alloc exist element! " << name << std::endl; return false; } catch(const std::out_of_range & ){ MemoryInfo info; T *data = new T[size](); info.address = static_cast<void *>(data); info.size = size; info.type = typeid(T).name(); Global_Data[name] = info; } return true; } template<class T> void dealloc(const string& name) { try{ MemoryInfo info = Global_Data.at(name); if (info.type != typeid(T).name()) { std::cerr << "Warning: dealloc a different type elemet! " << name << std::endl; return; } T * data = static_cast<T *>(info.address); delete []data; Global_Data.erase(name); } catch(const std::out_of_range & ){ std::cerr << "Warning: dealloc none-exist element! " << name << std::endl; } } template<class T> bool memoryCopy(const string &name, const int &size, T *in_data) { try{ MemoryInfo mem_info = Global_Data.at(name); if (size > mem_info.size) { std::cerr << "Warning: memory copy to a smaller space! " << name << std::endl; return false; } if(mem_info.type != typeid(T).name()){ std::cerr << "Warning: memory copy to a different type! " << name << std::endl; return false; } // This is an insidious bug! can not use memcpy here, for it may copy a pointer // based data type ! T *dest = static_cast<T *>(mem_info.address); for (int i = 0; i < size; ++i) { dest[i] = in_data[i]; } return true; } catch(const std::out_of_range & ){ std::cerr << "Warning: memory copy to none-exist element! " << name << std::endl; } return false; } template<class T> bool retrieve(const std::string &name,int &size,T *&out_data) { try{ MemoryInfo mem_info = Global_Data.at(name); if(mem_info.type != typeid(T).name()){ std::cerr << "Warning: retrieve to a different type! " << name << std::endl; out_data = NULL; return false; } out_data = static_cast<T *>(mem_info.address); size = mem_info.size; return true; } catch(const std::out_of_range & ){ std::cerr << "Warning: retrieve none-exist element! " << name << std::endl; } size = 0; out_data = NULL; return false; } } //namespace #endif // GPUMEMORY_H
bc2bfc8bbf202f7adf914d9b06690c13fe892768
e58a4f1b096b9544ef56f865afe9f079d3fc89db
/Graphs/breadth_first_search_in_graphs.cc
92bda9a92f974211793494933103aa3efe7b51ab
[]
no_license
0APOCALYPSE0/Algorithm-Concepts
c14c27ba967f524202ed9be8a79428bfc01e5dc0
587f620dc5b1481790987a86ef34225899d4f35d
refs/heads/master
2023-06-13T08:05:02.208567
2021-07-04T22:32:25
2021-07-04T22:32:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
cc
#include <bits/stdc++.h> using namespace std; #define ll long long int #define endl "\n" template<typename T> class Graph{ map<T,list<T>> adjList; public: Graph(){} // Function To add the nodes into the graph. void addEdge(T src,T des,bool bidir = true){ adjList[src].push_back(des); if(bidir){ adjList[des].push_back(src); } } // Printing the adjecency List. void printAdjList(){ for(auto src : adjList) { cout << src.first << " -> "; for(auto des : src.second) { cout << des << ", "; } cout << endl; } } // Traversing the graph using B.F.S Technique. void BFS(T src){ queue<T> Q; map<T,bool> visited; Q.push(src); visited[src] = true; while(!Q.empty()) { T cur_node = Q.front(); Q.pop(); cout << cur_node << " "; for(auto node : adjList[cur_node]) { if(!visited[node]) { Q.push(node); visited[node] = true; } } } } }; int main(){ #ifndef ONLINE_JUGDE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); freopen("error.txt","w",stderr); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); Graph<int> ga; ga.addEdge(0,1); ga.addEdge(0,4); ga.addEdge(4,3); ga.addEdge(1,4); ga.addEdge(1,2); ga.addEdge(2,3); ga.addEdge(1,3); ga.BFS(0); return 0; } // Sample Outout : // 0 1 4 2 3
[ "ajaysharma388" ]
ajaysharma388
31e6426075fb037ae514214f4ad1dfd0a400c303
3bd1a6c15e63cbbef0e60a02957fb01722139f47
/RoverMain/RoverFi.cpp
488a20f5efd01026cec120dfdc49967c9ed9d919
[]
no_license
DynamicBrute/SARSRover
447ed77d266686776b4c8f703eb7a384e609dc82
30c9b25914b842937abd1b0b169bf6f7527c12b1
refs/heads/master
2020-05-17T05:15:04.989202
2015-04-21T16:58:34
2015-04-21T16:58:34
33,909,840
0
0
null
null
null
null
UTF-8
C++
false
false
6,626
cpp
#include "RoverFi.h" #include "GPS.h" #include "GPIO.h" #include "HMC5883.h" //#include "RoverMain.h" char ssid[] = "SARSNet"; // your network password char password[] = "sarsrover"; WiFiClient debugClient; //Server object, the argument is the port that it listens too WiFiServer debugServer(3284); WiFiServer mainServer(7277); WiFiServer teleServer(8353); WiFiClient teleClient; boolean alreadyConnected, alreadyConnectedMain, alreadyConnectedTele; //Connect to a WiFi network void startWiFi() { // attempt to connect to Wifi network: Serial.print("Attempting to connect to Network named: "); // print the network name (SSID); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: //Serial.print("IP: "); //Serial.println(WiFi.localIP()); //if(WiFi.localIP() == INADDR_NONE) WiFi.beginNetwork(ssid, password); /* while ( WiFi.status() != WL_CONNECTED) { // print dots while we wait to connect Serial.print("."); delay(300); }*/ Serial.println("\nYou're connected to the network"); Serial.println("Waiting for an ip address"); while (WiFi.localIP() == INADDR_NONE) { // print dots while we wait for an ip addresss Serial.print("."); delay(300); } Serial.println("\nIP Address obtained"); // you're connected now, so print out the status: printWifiStatus(); alreadyConnectedMain = false; } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); debugClient.print("SSID: "); debugClient.println(WiFi.SSID()); // print your WiFi shield's IP address: debugClient.print("IP Address: "); debugClient.println(ip); // print the received signal strength: debugClient.print("signal strength (RSSI):"); debugClient.print(rssi); debugClient.println(" dBm"); } void waitForTarget() { //define a client object to connect to the server WiFiClient mainClient; //wait for a client to connect to the server while(!alreadyConnectedMain) { //attempt to save a client connecting to the server mainClient = mainServer.available(); //if a client is connected, begin communication if (mainClient) { if (!alreadyConnectedMain) { // clead out the input buffer: mainClient.flush(); Serial.println("We have a new client"); debugServer.println("We have a new client"); mainClient.println("Hello, client!"); alreadyConnectedMain = true; } } delay(100); delay(100); } Serial.println("writing"); debugClient.println("writing"); //mainServer.println("ready"); delay(1000); //Strings to read in latitude and longitude from the client char lat[50] = ""; char lon[50] = ""; int ind = 0; //Wait for input to be on the buffer while(!mainClient.available()); char destNum = '0'; while(!(destNum == '1' || destNum == '2' || destNum == '3')) { destNum = mainClient.read(); Serial.println(destNum); } if(destNum == '1') { tarLat = LAT1; tarLon = LON1; } if(destNum == '2') { tarLat = LAT2; tarLon = LON2; } if(destNum == '3') { tarLat = LAT3; tarLon = LON3; } /* //Read in characters from the input buffer until a new line character is reached //this will be the latitude while(mainClient.available()) { char c = mainClient.read(); lat[ind] = c; if(c == '\n') { lat[ind] = NULL; break; } ind++; } ind = 0; //Read in characters from the input buffer until a new line character is reached //this will be the longitude while(mainClient.available()) { char c = mainClient.read(); lon[ind] = c; if(c == '\n') { lon[ind] = NULL; break; } ind++; } mainClient.stop(); //convert from a string to a float tarLat = strtof(lat, NULL); tarLon = strtof(lon, NULL); //digitalWrite(LED1, LOW); //tarLat = atof(lat); //tarLon = atof(lon);*/ Serial.print("Lat: "); Serial.print(lat); Serial.print(" "); Serial.println(tarLat, 6); Serial.print("Lon: "); Serial.print(lon); Serial.print(" "); Serial.println(tarLon, 6); debugClient.print("Lat: "); debugClient.print(lat); debugClient.print(" "); debugClient.println(tarLat, 6); debugClient.print("Lon: "); debugClient.print(lon); debugClient.print(" "); debugClient.println(tarLon, 6); //Erick's //tarLat = 28.504906f; //tarLon = -81.457456f; //apt //tarLat = 28.582183f; //tarLon = -81.202770f; //apt 2 //tarLat = 28.582373f; //tarLon = -81.202996f; //curLat = 28.628811f; //curLon = -81.199479f; //mem mall //tarLat = 28.603710f; //tarLon = -81.199371f; //matt's //tarLat = 28.628391; //tarLon = -81.200013; } void transmitTele() { Serial.println("tele"); while(!alreadyConnectedTele) { //attempt to save a client connecting to the server teleClient = teleServer.available(); //if a client is connected, begin communication if (teleClient) { if (!alreadyConnectedTele) { // clead out the input buffer: teleClient.flush(); Serial.println("We have a new client"); alreadyConnectedTele = true; } } } for(int i = 0; i < 20; i++) { if (teleClient.available() > 0) { // read the bytes incoming from the client: char thisChar = teleClient.read(); // echo the bytes back to the client: if(thisChar == '1') teleServer.println(curSpeedKn * KNOTS_TO_MPS); if(thisChar == '2') teleServer.println(pollPing()); if(thisChar == '3') teleServer.println(distToTar()); if(thisChar == '4') teleServer.println(curLat); if(thisChar == '5') teleServer.println(curLon); if(thisChar == '6') teleServer.println(curHead); // echo the bytes to the server as well: Serial.println(thisChar); } } }
29cb0510e98b37a20bd1f7ea4b7d36b954711aad
efe2b4dedbc6bab31ffe88c271daa5463f8649f6
/branches/fast-extension/src/udp_tracker_connection.cpp
d08abd3595eacec600dec250f555c23f5efea516
[]
no_license
svn2github/libtorrent
867c84f0c271cdc255c3e268c17db75d46010dde
8cfe21e253d8b90086bb0b15c6c881795bf12ea1
refs/heads/master
2020-03-30T03:50:32.931129
2015-01-07T23:21:54
2015-01-07T23:21:54
17,344,601
0
1
null
null
null
null
UTF-8
C++
false
false
14,411
cpp
/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author 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. */ #include "libtorrent/pch.hpp" #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/tracker_manager.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/io.hpp" namespace { enum { udp_connection_retries = 4, udp_announce_retries = 15, udp_connect_timeout = 15, udp_announce_timeout = 10, udp_buffer_size = 2048 }; } using boost::bind; using boost::lexical_cast; namespace libtorrent { udp_tracker_connection::udp_tracker_connection( asio::strand& str , tracker_manager& man , tracker_request const& req , std::string const& hostname , unsigned short port , address bind_infc , boost::weak_ptr<request_callback> c , session_settings const& stn) : tracker_connection(man, req, str, bind_infc, c) , m_man(man) , m_strand(str) , m_name_lookup(m_strand.io_service()) , m_transaction_id(0) , m_connection_id(0) , m_settings(stn) , m_attempts(0) { udp::resolver::query q(hostname, boost::lexical_cast<std::string>(port)); m_name_lookup.async_resolve(q , m_strand.wrap(boost::bind( &udp_tracker_connection::name_lookup, self(), _1, _2))); set_timeout(m_settings.tracker_completion_timeout , m_settings.tracker_receive_timeout); } void udp_tracker_connection::name_lookup(asio::error_code const& error , udp::resolver::iterator i) try { if (error == asio::error::operation_aborted) return; if (!m_socket) return; // the operation was aborted if (error || i == udp::resolver::iterator()) { fail(-1, error.message().c_str()); return; } #if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING) if (has_requester()) requester().debug_log("udp tracker name lookup successful"); #endif restart_read_timeout(); // look for an address that has the same kind as the one // we're listening on. To make sure the tracker get our // correct listening address. udp::resolver::iterator target = i; udp::resolver::iterator end; udp::endpoint target_address = *i; for (; target != end && target->endpoint().address().is_v4() != bind_interface().is_v4(); ++target); if (target == end) { assert(target_address.address().is_v4() != bind_interface().is_v4()); if (has_requester()) { std::string tracker_address_type = target_address.address().is_v4() ? "IPv4" : "IPv6"; std::string bind_address_type = bind_interface().is_v4() ? "IPv4" : "IPv6"; requester().tracker_warning("the tracker only resolves to an " + tracker_address_type + " address, and you're listening on an " + bind_address_type + " socket. This may prevent you from receiving incoming connections."); } } else { target_address = *target; } if (has_requester()) requester().m_tracker_address = tcp::endpoint(target_address.address(), target_address.port()); m_target = target_address; m_socket.reset(new datagram_socket(m_name_lookup.io_service())); m_socket->open(target_address.protocol()); m_socket->bind(udp::endpoint(bind_interface(), 0)); m_socket->connect(target_address); send_udp_connect(); } catch (std::exception& e) { fail(-1, e.what()); }; void udp_tracker_connection::on_timeout() { m_socket.reset(); m_name_lookup.cancel(); fail_timeout(); } void udp_tracker_connection::send_udp_connect() { #if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING) if (has_requester()) { requester().debug_log("==> UDP_TRACKER_CONNECT [" + lexical_cast<std::string>(tracker_req().info_hash) + "]"); } #endif if (!m_socket) return; // the operation was aborted char send_buf[16]; char* ptr = send_buf; if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); // connection_id detail::write_uint32(0x417, ptr); detail::write_uint32(0x27101980, ptr); // action (connect) detail::write_int32(action_connect, ptr); // transaction_id detail::write_int32(m_transaction_id, ptr); m_socket->send(asio::buffer((void*)send_buf, 16), 0); ++m_attempts; m_buffer.resize(udp_buffer_size); m_socket->async_receive_from(asio::buffer(m_buffer), m_sender , boost::bind(&udp_tracker_connection::connect_response, self(), _1, _2)); } void udp_tracker_connection::connect_response(asio::error_code const& error , std::size_t bytes_transferred) try { if (error == asio::error::operation_aborted) return; if (!m_socket) return; // the operation was aborted if (error) { fail(-1, error.message().c_str()); return; } if (m_target != m_sender) { // this packet was not received from the tracker m_socket->async_receive_from(asio::buffer(m_buffer), m_sender , boost::bind(&udp_tracker_connection::connect_response, self(), _1, _2)); return; } if (bytes_transferred >= udp_buffer_size) { fail(-1, "udp response too big"); return; } if (bytes_transferred < 8) { fail(-1, "got a message with size < 8"); return; } restart_read_timeout(); const char* ptr = &m_buffer[0]; int action = detail::read_int32(ptr); int transaction = detail::read_int32(ptr); if (action == action_error) { fail(-1, std::string(ptr, bytes_transferred - 8).c_str()); return; } if (action != action_connect) { fail(-1, "invalid action in connect reply"); return; } if (m_transaction_id != transaction) { fail(-1, "incorrect transaction id"); return; } if (bytes_transferred < 16) { fail(-1, "udp_tracker_connection: " "got a message with size < 16"); return; } // reset transaction m_transaction_id = 0; m_attempts = 0; m_connection_id = detail::read_int64(ptr); #if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING) if (has_requester()) { requester().debug_log("<== UDP_TRACKER_CONNECT_RESPONSE [" + lexical_cast<std::string>(m_connection_id) + "]"); } #endif if (tracker_req().kind == tracker_request::announce_request) send_udp_announce(); else if (tracker_req().kind == tracker_request::scrape_request) send_udp_scrape(); } catch (std::exception& e) { fail(-1, e.what()); } void udp_tracker_connection::send_udp_announce() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); if (!m_socket) return; // the operation was aborted std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); tracker_request const& req = tracker_req(); // connection_id detail::write_int64(m_connection_id, out); // action (announce) detail::write_int32(action_announce, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(req.info_hash.begin(), req.info_hash.end(), out); // peer_id std::copy(req.pid.begin(), req.pid.end(), out); // downloaded detail::write_int64(req.downloaded, out); // left detail::write_int64(req.left, out); // uploaded detail::write_int64(req.uploaded, out); // event detail::write_int32(req.event, out); // ip address if (m_settings.announce_ip != address() && m_settings.announce_ip.is_v4()) detail::write_uint32(m_settings.announce_ip.to_v4().to_ulong(), out); else detail::write_int32(0, out); // key detail::write_int32(req.key, out); // num_want detail::write_int32(req.num_want, out); // port detail::write_uint16(req.listen_port, out); // extensions detail::write_uint16(0, out); #if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING) if (has_requester()) { requester().debug_log("==> UDP_TRACKER_ANNOUNCE [" + lexical_cast<std::string>(req.info_hash) + "]"); } #endif m_socket->send(asio::buffer(buf), 0); ++m_attempts; m_socket->async_receive_from(asio::buffer(m_buffer), m_sender , bind(&udp_tracker_connection::announce_response, self(), _1, _2)); } void udp_tracker_connection::send_udp_scrape() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); if (!m_socket) return; // the operation was aborted std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (scrape) detail::write_int32(action_scrape, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(tracker_req().info_hash.begin(), tracker_req().info_hash.end(), out); m_socket->send(asio::buffer(&buf[0], buf.size()), 0); ++m_attempts; m_socket->async_receive_from(asio::buffer(m_buffer), m_sender , bind(&udp_tracker_connection::scrape_response, self(), _1, _2)); } void udp_tracker_connection::announce_response(asio::error_code const& error , std::size_t bytes_transferred) try { if (error == asio::error::operation_aborted) return; if (!m_socket) return; // the operation was aborted if (error) { fail(-1, error.message().c_str()); return; } if (m_target != m_sender) { // this packet was not received from the tracker m_socket->async_receive_from(asio::buffer(m_buffer), m_sender , bind(&udp_tracker_connection::connect_response, self(), _1, _2)); return; } if (bytes_transferred >= udp_buffer_size) { fail(-1, "udp response too big"); return; } if (bytes_transferred < 8) { fail(-1, "got a message with size < 8"); return; } restart_read_timeout(); char* buf = &m_buffer[0]; int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { fail(-1, "incorrect transaction id"); return; } if (action == action_error) { fail(-1, std::string(buf, bytes_transferred - 8).c_str()); return; } if (action != action_announce) { fail(-1, "invalid action in announce response"); return; } if (bytes_transferred < 20) { fail(-1, "got a message with size < 20"); return; } int interval = detail::read_int32(buf); int incomplete = detail::read_int32(buf); int complete = detail::read_int32(buf); int num_peers = (bytes_transferred - 20) / 6; if ((bytes_transferred - 20) % 6 != 0) { fail(-1, "invalid udp tracker response length"); return; } #if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING) if (has_requester()) { requester().debug_log("<== UDP_TRACKER_ANNOUNCE_RESPONSE"); } #endif if (!has_requester()) { m_man.remove_request(this); return; } std::vector<peer_entry> peer_list; for (int i = 0; i < num_peers; ++i) { peer_entry e; std::stringstream s; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf); e.ip = s.str(); e.port = detail::read_uint16(buf); e.pid.clear(); peer_list.push_back(e); } requester().tracker_response(tracker_req(), peer_list, interval , complete, incomplete); m_man.remove_request(this); return; } catch (std::exception& e) { fail(-1, e.what()); }; // msvc 7.1 seems to require this void udp_tracker_connection::scrape_response(asio::error_code const& error , std::size_t bytes_transferred) try { if (error == asio::error::operation_aborted) return; if (!m_socket) return; // the operation was aborted if (error) { fail(-1, error.message().c_str()); return; } if (m_target != m_sender) { // this packet was not received from the tracker m_socket->async_receive_from(asio::buffer(m_buffer), m_sender , bind(&udp_tracker_connection::connect_response, self(), _1, _2)); return; } if (bytes_transferred >= udp_buffer_size) { fail(-1, "udp response too big"); return; } if (bytes_transferred < 8) { fail(-1, "got a message with size < 8"); return; } restart_read_timeout(); char* buf = &m_buffer[0]; int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { fail(-1, "incorrect transaction id"); return; } if (action == action_error) { fail(-1, std::string(buf, bytes_transferred - 8).c_str()); return; } if (action != action_scrape) { fail(-1, "invalid action in announce response"); return; } if (bytes_transferred < 20) { fail(-1, "got a message with size < 20"); return; } int complete = detail::read_int32(buf); /*int downloaded = */detail::read_int32(buf); int incomplete = detail::read_int32(buf); if (!has_requester()) { m_man.remove_request(this); return; } std::vector<peer_entry> peer_list; requester().tracker_response(tracker_req(), peer_list, 0 , complete, incomplete); m_man.remove_request(this); } catch (std::exception& e) { fail(-1, e.what()); } }
[ "arvidn@f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda" ]
arvidn@f43f7eb3-cfe1-5f9d-1b5f-e45aa6702bda
626698f15d91203e09063693c38b9af803d1bcda
a19c187518fe30e61ed377c4c13376e162b5f0c1
/utrason_alice_yannick.ino
8e8c7273516aec7ea928551bfd01fe3fe216bf80
[]
no_license
ycarissan/utrason_alice_yannick
1113d39faa86ad152160d5b92502cd6e31df687c
e8764bba5edcacfaba66e1770e7e7f753f8c183a
refs/heads/master
2022-08-13T11:48:55.653856
2020-05-24T09:06:57
2020-05-24T09:06:57
266,360,665
0
0
null
null
null
null
UTF-8
C++
false
false
1,326
ino
/* * Ultrasonic Sensor HC-SR04 and Arduino Tutorial * * by Dejan Nedelkovski, * www.HowToMechatronics.com * */ // defines pins numbers const int trigPin = 2; const int echoPin = 3; // defines variables long duration; int distance; void setup() { pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input Serial.begin(9600); // Starts the serial communication } void loop() { // Clears the trigPin digitalWrite(trigPin, LOW); delayMicroseconds(2); // Sets the trigPin on HIGH state for 10 micro seconds digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Reads the echoPin, returns the sound wave travel time in microseconds duration = pulseIn(echoPin, HIGH); // Calculating the distance distance= duration*0.034/2; // Prints the distance on the Serial Monitor Serial.print("Distance: "); Serial.print(distance); if (distance<7) { Serial.println("allumer"); allumer_rouge(); eteindre_vert(); } else { Serial.println("eteindre"); allumer_vert(); eteindre_rouge(); } } void allumer_rouge() { digitalWrite(10, HIGH); } void eteindre_rouge() { digitalWrite(10, LOW); } void allumer_vert() { digitalWrite(11, HIGH); } void eteindre_vert() { digitalWrite(11, LOW); }
4fb1a52d748490242e2d2a86623aa59b6c14d186
c824d97cc1208744e4453bac916dcc24dc77a377
/libcaf_io/caf/io/network/stream_manager.hpp
c9129d4c56adf1dc5baaba06417ca8b692ab6c9c
[ "BSL-1.0" ]
permissive
DePizzottri/actor-framework
1a033440660c4ea507b743b0d46a46de7fd30df6
bdbd19541b1e1e6ec0abe16bcf7db90d73c649d2
refs/heads/master
2021-01-24T00:23:18.672012
2018-04-28T13:04:21
2018-04-28T13:04:21
59,172,681
0
0
null
2017-03-07T04:22:26
2016-05-19T04:04:18
C++
UTF-8
C++
false
false
2,414
hpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_IO_NETWORK_STREAM_MANAGER_HPP #define CAF_IO_NETWORK_STREAM_MANAGER_HPP #include <cstddef> #include "caf/io/network/manager.hpp" namespace caf { namespace io { namespace network { /// A stream manager configures an IO stream and provides callbacks /// for incoming data as well as for error handling. class stream_manager : public manager { public: stream_manager(abstract_broker* ptr); ~stream_manager() override; /// Called by the underlying I/O device whenever it received data. /// @returns `true` if the manager accepts further reads, otherwise `false`. virtual bool consume(execution_unit* ctx, const void* buf, size_t bsize) = 0; /// Called by the underlying I/O device whenever it sent data. virtual void data_transferred(execution_unit* ctx, size_t num_bytes, size_t remaining_bytes) = 0; }; } // namespace network } // namespace io } // namespace caf #endif // CAF_IO_NETWORK_STREAM_MANAGER_HPP
47f03ff81ab71217cc3e8ebabdfcf6502f96132f
78590c60dac38e9b585d0a277ea76944544e9bd8
/src/pool/pstring.cxx
4c17513a96aee622eaf9cc3b0170584ad44c15df
[]
no_license
sandeshdevadiga/beng-proxy
05adedcf28c31ad5fbaa073f85e5d2d420e5b3ca
436e8de75a28aa8c7b09f6ed97c1a1dfcf0fcfc4
refs/heads/master
2023-03-02T09:04:20.466704
2021-02-11T17:05:38
2021-02-11T17:10:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,133
cxx
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * 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. * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "pool.hxx" #include "util/CharUtil.hxx" #include "util/StringView.hxx" #include <algorithm> #include <assert.h> #include <string.h> #include <stdarg.h> #include <stdio.h> static char * Copy(char *dest, const char *src, size_t n) noexcept { return std::copy_n(src, n, dest); } static char * CopyLower(char *dest, const char *src, size_t n) noexcept { return std::transform(src, src + n, dest, ToLowerASCII); } void * p_memdup(struct pool *pool, const void *src, size_t length TRACE_ARGS_DECL) noexcept { void *dest = p_malloc_fwd(pool, length); memcpy(dest, src, length); return dest; } char * p_strdup(struct pool *pool, const char *src TRACE_ARGS_DECL) noexcept { return (char *)p_memdup_fwd(pool, src, strlen(src) + 1); } char * p_strndup(struct pool *pool, const char *src, size_t length TRACE_ARGS_DECL) noexcept { char *dest = (char *)p_malloc_fwd(pool, length + 1); *Copy(dest, src, length) = 0; return dest; } char * p_strdup(struct pool &pool, StringView src TRACE_ARGS_DECL) noexcept { char *dest = (char *)p_malloc_fwd(&pool, src.size + 1); *Copy(dest, src.data, src.size) = 0; return dest; } char * p_strdup_lower(struct pool &pool, StringView src TRACE_ARGS_DECL) noexcept { char *dest = (char *)p_malloc_fwd(&pool, src.size + 1); *CopyLower(dest, src.data, src.size) = 0; return dest; } char * gcc_malloc p_sprintf(struct pool *pool, const char *fmt, ...) noexcept { va_list ap; va_start(ap, fmt); size_t length = (size_t)vsnprintf(nullptr, 0, fmt, ap) + 1; va_end(ap); char *p = (char *)p_malloc(pool, length); va_start(ap, fmt); gcc_unused int length2 = vsnprintf(p, length, fmt, ap); va_end(ap); assert((size_t)length2 + 1 == length); return p; }
9d82c3f45d9417342d4cf95f55276234ac428495
5e191124f3ae3cb374500b392123b75475b55030
/tpl/gtest-mpi-listener/gtest-mpi-listener.hpp
44e9578e1ce67de5d4439d3767c93977c52f8a39
[ "BSD-3-Clause" ]
permissive
LLNL/MPIDiff
501056918b6c49c8970b284251f73bbd7e62b089
f7e24ce6ba4c2139424b26707742a7124ac8a045
refs/heads/develop
2023-06-30T16:45:28.039741
2021-08-04T15:45:09
2021-08-04T15:45:09
321,845,944
4
0
BSD-3-Clause
2021-08-04T15:45:10
2020-12-16T02:31:35
C++
UTF-8
C++
false
false
19,412
hpp
/****************************************************************************** * * Slight modifications made by Alan Dayton (2019) * *******************************************************************************/ // /****************************************************************************** * * Copyright (c) 2016-2018, Lawrence Livermore National Security, LLC * and other gtest-mpi-listener developers. See the COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) * *******************************************************************************/ // /******************************************************************************* * An example from Google Test was copied with minor modifications. The * license of Google Test is below. * * Google Test has the following copyright notice, which must be * duplicated in its entirety per the terms of its license: * * Copyright 2005, Google 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. *******************************************************************************/ #ifndef GTEST_MPI_MINIMAL_LISTENER_H #define GTEST_MPI_MINIMAL_LISTENER_H #include "mpi.h" #include "gtest/gtest.h" #include <cassert> #include <vector> #include <string> #include <sstream> #include "mpidiff/MPIDiff.h" namespace GTestMPIListener { // This class sets up the global test environment, which is needed // to finalize MPI. class MPIEnvironment : public ::testing::Environment { public: MPIEnvironment() : ::testing::Environment() {} virtual ~MPIEnvironment() {} virtual void SetUp() { int is_mpi_initialized; ASSERT_EQ(MPI_Initialized(&is_mpi_initialized), MPI_SUCCESS); if (!is_mpi_initialized) { printf("MPI must be initialized before RUN_ALL_TESTS!\n"); printf("Add '::testing::InitGoogleTest(&argc, argv);\n"); printf(" MPI_Init(&argc, &argv);' to your 'main' function!\n"); FAIL(); } } virtual void TearDown() { int is_mpi_finalized; ASSERT_EQ(MPI_Finalized(&is_mpi_finalized), MPI_SUCCESS); if (!is_mpi_finalized) { int rank; ASSERT_EQ(MPI_Comm_rank(MPI_COMM_WORLD, &rank), MPI_SUCCESS); if (rank == 0) { printf("Finalizing MPI...\n"); } MPIDiff::Finalize(); ASSERT_EQ(MPI_Finalize(), MPI_SUCCESS); } ASSERT_EQ(MPI_Finalized(&is_mpi_finalized), MPI_SUCCESS); ASSERT_TRUE(is_mpi_finalized); } private: // Disallow copying MPIEnvironment(const MPIEnvironment&) {} }; // class MPIEnvironment // This class more or less takes the code in Google Test's // MinimalistPrinter example and wraps certain parts of it in MPI calls, // gathering all results onto rank zero. class MPIMinimalistPrinter : public ::testing::EmptyTestEventListener { public: MPIMinimalistPrinter() : ::testing::EmptyTestEventListener(), result_vector() { int is_mpi_initialized; assert(MPI_Initialized(&is_mpi_initialized) == MPI_SUCCESS); if (!is_mpi_initialized) { printf("MPI must be initialized before RUN_ALL_TESTS!\n"); printf("Add '::testing::InitGoogleTest(&argc, argv);\n"); printf(" MPI_Init(&argc, &argv);' to your 'main' function!\n"); assert(0); } MPI_Comm_dup(MPI_COMM_WORLD, &comm); UpdateCommState(); } MPIMinimalistPrinter(MPI_Comm comm_) : ::testing::EmptyTestEventListener(), result_vector() { int is_mpi_initialized; assert(MPI_Initialized(&is_mpi_initialized) == MPI_SUCCESS); if (!is_mpi_initialized) { printf("MPI must be initialized before RUN_ALL_TESTS!\n"); printf("Add '::testing::InitGoogleTest(&argc, argv);\n"); printf(" MPI_Init(&argc, &argv);' to your 'main' function!\n"); assert(0); } MPI_Comm_dup(comm_, &comm); UpdateCommState(); } MPIMinimalistPrinter (const MPIMinimalistPrinter& printer) { int is_mpi_initialized; assert(MPI_Initialized(&is_mpi_initialized) == MPI_SUCCESS); if (!is_mpi_initialized) { printf("MPI must be initialized before RUN_ALL_TESTS!\n"); printf("Add '::testing::InitGoogleTest(&argc, argv);\n"); printf(" MPI_Init(&argc, &argv);' to your 'main' function!\n"); assert(0); } MPI_Comm_dup(printer.comm, &comm); UpdateCommState(); result_vector = printer.result_vector; } // Called before the Environment is torn down. void OnEnvironmentTearDownStart() { int is_mpi_finalized; assert(MPI_Finalized(&is_mpi_finalized) == MPI_SUCCESS); if (!is_mpi_finalized) { MPI_Comm_free(&comm); } } // Called before a test starts. virtual void OnTestStart(const ::testing::TestInfo& test_info) { // Only need to report test start info on rank 0 if (rank == 0) { printf("*** Test %s.%s starting.\n", test_info.test_case_name(), test_info.name()); } } // Called after an assertion failure or an explicit SUCCESS() macro. // In an MPI program, this means that certain ranks may not call this // function if a test part does not fail on all ranks. Consequently, it // is difficult to have explicit synchronization points here. virtual void OnTestPartResult (const ::testing::TestPartResult& test_part_result) { result_vector.push_back(test_part_result); } // Called after a test ends. virtual void OnTestEnd(const ::testing::TestInfo& test_info) { int localResultCount = result_vector.size(); std::vector<int> resultCountOnRank(size, 0); MPI_Gather(&localResultCount, 1, MPI_INT, &resultCountOnRank[0], 1, MPI_INT, 0, comm); if (rank != 0) { // Nonzero ranks send constituent parts of each result to rank 0 for (int i = 0; i < localResultCount; i++) { const ::testing::TestPartResult test_part_result = result_vector.at(i); int resultStatus(test_part_result.failed()); std::string resultFileName(test_part_result.file_name()); int resultLineNumber(test_part_result.line_number()); std::string resultSummary(test_part_result.summary()); // Must add one for null termination int resultFileNameSize(resultFileName.size()+1); int resultSummarySize(resultSummary.size()+1); MPI_Send(&resultStatus, 1, MPI_INT, 0, rank, comm); MPI_Send(&resultFileNameSize, 1, MPI_INT, 0, rank, comm); MPI_Send(&resultLineNumber, 1, MPI_INT, 0, rank, comm); MPI_Send(&resultSummarySize, 1, MPI_INT, 0, rank, comm); MPI_Send(resultFileName.c_str(), resultFileNameSize, MPI_CHAR, 0, rank, comm); MPI_Send(resultSummary.c_str(), resultSummarySize, MPI_CHAR, 0, rank, comm); } } else { // Rank 0 first prints its local result data for (int i = 0; i < localResultCount; i++) { const ::testing::TestPartResult test_part_result = result_vector.at(i); printf(" %s on rank %d, %s:%d\n%s\n", test_part_result.failed() ? "*** Failure" : "Success", rank, test_part_result.file_name(), test_part_result.line_number(), test_part_result.summary()); } for (int r = 1; r < size; r++) { for (int i = 0; i < resultCountOnRank[r]; i++) { int resultStatus, resultFileNameSize, resultLineNumber; int resultSummarySize; MPI_Recv(&resultStatus, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&resultFileNameSize, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&resultLineNumber, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&resultSummarySize, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); std::string resultFileName; std::string resultSummary; resultFileName.resize(resultFileNameSize); resultSummary.resize(resultSummarySize); MPI_Recv(&resultFileName[0], resultFileNameSize, MPI_CHAR, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&resultSummary[0], resultSummarySize, MPI_CHAR, r, r, comm, MPI_STATUS_IGNORE); printf(" %s on rank %d, %s:%d\n%s\n", resultStatus ? "*** Failure" : "Success", r, resultFileName.c_str(), resultLineNumber, resultSummary.c_str()); } } printf("*** Test %s.%s ending.\n", test_info.test_case_name(), test_info.name()); } result_vector.clear(); } private: MPI_Comm comm; int rank; int size; std::vector< ::testing::TestPartResult > result_vector; int UpdateCommState() { int flag = MPI_Comm_rank(comm, &rank); if (flag != MPI_SUCCESS) { return flag; } flag = MPI_Comm_size(comm, &size); return flag; } }; // class MPIMinimalistPrinter // This class more or less takes the code in Google Test's // MinimalistPrinter example and wraps certain parts of it in MPI calls, // gathering all results onto rank zero. class MPIWrapperPrinter : public ::testing::TestEventListener { public: MPIWrapperPrinter(::testing::TestEventListener *l, MPI_Comm comm_) : ::testing::TestEventListener(), listener(l), result_vector() { int is_mpi_initialized; assert(MPI_Initialized(&is_mpi_initialized) == MPI_SUCCESS); if (!is_mpi_initialized) { printf("MPI must be initialized before RUN_ALL_TESTS!\n"); printf("Add '::testing::InitGoogleTest(&argc, argv);\n"); printf(" MPI_Init(&argc, &argv);' to your 'main' function!\n"); assert(0); } MPI_Comm_dup(comm_, &comm); UpdateCommState(); } MPIWrapperPrinter (const MPIWrapperPrinter& printer) : listener(printer.listener), result_vector(printer.result_vector) { int is_mpi_initialized; assert(MPI_Initialized(&is_mpi_initialized) == MPI_SUCCESS); if (!is_mpi_initialized) { printf("MPI must be initialized before RUN_ALL_TESTS!\n"); printf("Add '::testing::InitGoogleTest(&argc, argv);\n"); printf(" MPI_Init(&argc, &argv);' to your 'main' function!\n"); assert(0); } MPI_Comm_dup(printer.comm, &comm); UpdateCommState(); } // Called before test activity starts virtual void OnTestProgramStart(const ::testing::UnitTest &unit_test) { if (rank == 0) { listener->OnTestProgramStart(unit_test); } } // Called before each test iteration starts, where iteration is // the iterate index. There could be more than one iteration if // GTEST_FLAG(repeat) is used. virtual void OnTestIterationStart(const ::testing::UnitTest &unit_test, int iteration) { if (rank == 0) { listener->OnTestIterationStart(unit_test, iteration); } } // Called before environment setup before start of each test iteration virtual void OnEnvironmentsSetUpStart(const ::testing::UnitTest &unit_test) { if (rank == 0) { listener->OnEnvironmentsSetUpStart(unit_test); } } virtual void OnEnvironmentsSetUpEnd(const ::testing::UnitTest &unit_test) { if (rank == 0) { listener->OnEnvironmentsSetUpEnd(unit_test); } } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ virtual void OnTestCaseStart(const ::testing::TestCase &test_case) { if (rank == 0) { listener->OnTestCaseStart(test_case); } } #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ // Called before a test starts. virtual void OnTestStart(const ::testing::TestInfo& test_info) { // Only need to report test start info on rank 0 if (rank == 0) { listener->OnTestStart(test_info); } } // Called after an assertion failure or an explicit SUCCESS() macro. // In an MPI program, this means that certain ranks may not call this // function if a test part does not fail on all ranks. Consequently, it // is difficult to have explicit synchronization points here. virtual void OnTestPartResult (const ::testing::TestPartResult& test_part_result) { result_vector.push_back(test_part_result); if (rank == 0) { listener->OnTestPartResult(test_part_result); } } // Called after a test ends. virtual void OnTestEnd(const ::testing::TestInfo& test_info) { int localResultCount = result_vector.size(); std::vector<int> resultCountOnRank(size, 0); MPI_Gather(&localResultCount, 1, MPI_INT, &resultCountOnRank[0], 1, MPI_INT, 0, comm); if (rank != 0) { // Nonzero ranks send constituent parts of each result to rank 0 for (int i = 0; i < localResultCount; i++) { const ::testing::TestPartResult test_part_result = result_vector.at(i); int resultStatus(test_part_result.failed()); std::string resultFileName(test_part_result.file_name()); int resultLineNumber(test_part_result.line_number()); std::string resultMessage(test_part_result.message()); int resultFileNameSize(resultFileName.size()); int resultMessageSize(resultMessage.size()); MPI_Send(&resultStatus, 1, MPI_INT, 0, rank, comm); MPI_Send(&resultFileNameSize, 1, MPI_INT, 0, rank, comm); MPI_Send(&resultLineNumber, 1, MPI_INT, 0, rank, comm); MPI_Send(&resultMessageSize, 1, MPI_INT, 0, rank, comm); MPI_Send(resultFileName.c_str(), resultFileNameSize, MPI_CHAR, 0, rank, comm); MPI_Send(resultMessage.c_str(), resultMessageSize, MPI_CHAR, 0, rank, comm); } } else { // Rank 0 first prints its local result data for (int i = 0; i < localResultCount; i++) { const ::testing::TestPartResult test_part_result = result_vector.at(i); if (test_part_result.failed()) { std::string message(test_part_result.message()); std::istringstream input_stream(message); std::stringstream to_stream_into_failure; std::string line_as_string; while (std::getline(input_stream, line_as_string)) { to_stream_into_failure << "[Rank 0/" << size << "] " << line_as_string << std::endl; } ADD_FAILURE_AT(test_part_result.file_name(), test_part_result.line_number()) << to_stream_into_failure.str(); } } for (int r = 1; r < size; r++) { for (int i = 0; i < resultCountOnRank[r]; i++) { int resultStatus, resultFileNameSize, resultLineNumber; int resultMessageSize; MPI_Recv(&resultStatus, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&resultFileNameSize, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&resultLineNumber, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&resultMessageSize, 1, MPI_INT, r, r, comm, MPI_STATUS_IGNORE); std::vector<char> fileNameBuffer(resultFileNameSize); std::vector<char> messageBuffer(resultMessageSize); MPI_Recv(&fileNameBuffer[0], resultFileNameSize, MPI_CHAR, r, r, comm, MPI_STATUS_IGNORE); MPI_Recv(&messageBuffer[0], resultMessageSize, MPI_CHAR, r, r, comm, MPI_STATUS_IGNORE); std::string resultFileName(fileNameBuffer.begin(), fileNameBuffer.end()); std::string resultMessage(messageBuffer.begin(), messageBuffer.end()); bool testPartHasFailed = (resultStatus == 1); if (testPartHasFailed) { std::string message(resultMessage); std::istringstream input_stream(message); std::stringstream to_stream_into_failure; std::string line_as_string; while (std::getline(input_stream, line_as_string)) { to_stream_into_failure << "[Rank " << r << "/" << size << "] " << line_as_string << std::endl; } ADD_FAILURE_AT(resultFileName.c_str(), resultLineNumber) << to_stream_into_failure.str(); } } } } result_vector.clear(); if (rank == 0) { listener->OnTestEnd(test_info); } } #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ virtual void OnTestCaseEnd(const ::testing::TestCase &test_case) { if (rank == 0) { listener->OnTestCaseEnd(test_case); } } #endif // Called before the Environment is torn down. virtual void OnEnvironmentsTearDownStart(const ::testing::UnitTest &unit_test) { int is_mpi_finalized; assert(MPI_Finalized(&is_mpi_finalized) == MPI_SUCCESS); if (!is_mpi_finalized) { MPI_Comm_free(&comm); } if (rank == 0) { listener->OnEnvironmentsTearDownStart(unit_test); } } virtual void OnEnvironmentsTearDownEnd(const ::testing::UnitTest &unit_test) { if (rank == 0) { listener->OnEnvironmentsTearDownEnd(unit_test); } } virtual void OnTestIterationEnd(const ::testing::UnitTest &unit_test, int iteration) { if (rank == 0) { listener->OnTestIterationEnd(unit_test, iteration); } } // Called when test driver program ends virtual void OnTestProgramEnd(const ::testing::UnitTest &unit_test) { if (rank == 0) { listener->OnTestProgramEnd(unit_test); } } private: // Use a pointer here instead of a reference because // ::testing::TestEventListeners::Release returns a pointer // (namely, one of type ::testing::TesteEventListener*). ::testing::TestEventListener *listener; MPI_Comm comm; int rank; int size; std::vector< ::testing::TestPartResult > result_vector; int UpdateCommState() { int flag = MPI_Comm_rank(comm, &rank); if (flag != MPI_SUCCESS) { return flag; } flag = MPI_Comm_size(comm, &size); return flag; } }; } // namespace GTestMPIListener #endif /* GTEST_MPI_MINIMAL_LISTENER_H */
71f6a27c440793cc1ec61f17efa085ba29a7ebf5
91e6abe135f8969bfc7aeba30277271590b76ff6
/cartographer/cartographer/mapping/map_builder.cc
80eb7fe5c218ef92428d8ffa4e005ff0a6525d3b
[ "Apache-2.0" ]
permissive
eglrp/carto_modify
2075d186fbd5f802b627a5f50e6e62cbf2f1ad4b
9d5eb1d1fa511d1ce41222ea7006c416cd513434
refs/heads/master
2020-04-07T03:08:25.908720
2018-11-14T03:03:39
2018-11-14T03:03:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,363
cc
/* * Copyright 2016 The Cartographer Authors * * 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 "cartographer/mapping/map_builder.h" #include "absl/memory/memory.h" #include "cartographer/common/time.h" #include "cartographer/io/internal/mapping_state_serialization.h" #include "cartographer/io/proto_stream.h" #include "cartographer/io/proto_stream_deserializer.h" #include "cartographer/io/serialization_format_migration.h" #include "cartographer/mapping/internal/2d/local_trajectory_builder_2d.h" #include "cartographer/mapping/internal/2d/pose_graph_2d.h" #include "cartographer/mapping/internal/3d/local_trajectory_builder_3d.h" #include "cartographer/mapping/internal/3d/pose_graph_3d.h" #include "cartographer/mapping/internal/collated_trajectory_builder.h" #include "cartographer/mapping/internal/global_trajectory_builder.h" #include "cartographer/mapping/proto/internal/legacy_serialized_data.pb.h" #include "cartographer/sensor/internal/collator.h" #include "cartographer/sensor/internal/trajectory_collator.h" #include "cartographer/sensor/internal/voxel_filter.h" #include "cartographer/transform/rigid_transform.h" #include "cartographer/transform/transform.h" namespace cartographer { namespace mapping { namespace { using mapping::proto::SerializedData; std::vector<std::string> SelectRangeSensorIds( const std::set<MapBuilder::SensorId>& expected_sensor_ids) { std::vector<std::string> range_sensor_ids; for (const MapBuilder::SensorId& sensor_id : expected_sensor_ids) { if (sensor_id.type == MapBuilder::SensorId::SensorType::RANGE) { range_sensor_ids.push_back(sensor_id.id); } } return range_sensor_ids; } void MaybeAddPureLocalizationTrimmer( const int trajectory_id, const proto::TrajectoryBuilderOptions& trajectory_options, PoseGraph* pose_graph) { if (trajectory_options.pure_localization()) { LOG(WARNING) << "'TrajectoryBuilderOptions::pure_localization' field is deprecated. " "Use 'TrajectoryBuilderOptions::pure_localization_trimmer' instead."; pose_graph->AddTrimmer(absl::make_unique<PureLocalizationTrimmer>( trajectory_id, 3 /* max_submaps_to_keep */)); return; } if (trajectory_options.has_pure_localization_trimmer()) { pose_graph->AddTrimmer(absl::make_unique<PureLocalizationTrimmer>( trajectory_id, trajectory_options.pure_localization_trimmer().max_submaps_to_keep())); } } } // namespace proto::MapBuilderOptions CreateMapBuilderOptions( common::LuaParameterDictionary* const parameter_dictionary) { proto::MapBuilderOptions options; options.set_use_trajectory_builder_2d( parameter_dictionary->GetBool("use_trajectory_builder_2d")); options.set_use_trajectory_builder_3d( parameter_dictionary->GetBool("use_trajectory_builder_3d")); options.set_num_background_threads( parameter_dictionary->GetNonNegativeInt("num_background_threads")); *options.mutable_pose_graph_options() = CreatePoseGraphOptions( parameter_dictionary->GetDictionary("pose_graph").get()); CHECK_NE(options.use_trajectory_builder_2d(), options.use_trajectory_builder_3d()); return options; } MapBuilder::MapBuilder(const proto::MapBuilderOptions& options) : options_(options), thread_pool_(options.num_background_threads()) { CHECK(options.use_trajectory_builder_2d() ^ options.use_trajectory_builder_3d()); if (options.use_trajectory_builder_2d()) { pose_graph_ = absl::make_unique<PoseGraph2D>( options_.pose_graph_options(), absl::make_unique<optimization::OptimizationProblem2D>( options_.pose_graph_options().optimization_problem_options()), &thread_pool_); } if (options.use_trajectory_builder_3d()) { pose_graph_ = absl::make_unique<PoseGraph3D>( options_.pose_graph_options(), absl::make_unique<optimization::OptimizationProblem3D>( options_.pose_graph_options().optimization_problem_options()), &thread_pool_); } if (options.collate_by_trajectory()) { sensor_collator_ = absl::make_unique<sensor::TrajectoryCollator>(); } else { sensor_collator_ = absl::make_unique<sensor::Collator>(); } } int MapBuilder::AddTrajectoryBuilder( const std::set<SensorId>& expected_sensor_ids, const proto::TrajectoryBuilderOptions& trajectory_options, LocalSlamResultCallback local_slam_result_callback) { const int trajectory_id = trajectory_builders_.size(); if (options_.use_trajectory_builder_3d()) { std::unique_ptr<LocalTrajectoryBuilder3D> local_trajectory_builder; if (trajectory_options.has_trajectory_builder_3d_options()) { local_trajectory_builder = absl::make_unique<LocalTrajectoryBuilder3D>( trajectory_options.trajectory_builder_3d_options(), SelectRangeSensorIds(expected_sensor_ids)); } DCHECK(dynamic_cast<PoseGraph3D*>(pose_graph_.get())); trajectory_builders_.push_back(absl::make_unique<CollatedTrajectoryBuilder>( trajectory_options, sensor_collator_.get(), trajectory_id, expected_sensor_ids, CreateGlobalTrajectoryBuilder3D( std::move(local_trajectory_builder), trajectory_id, static_cast<PoseGraph3D*>(pose_graph_.get()), local_slam_result_callback))); } else { std::unique_ptr<LocalTrajectoryBuilder2D> local_trajectory_builder; if (trajectory_options.has_trajectory_builder_2d_options()) { local_trajectory_builder = absl::make_unique<LocalTrajectoryBuilder2D>( trajectory_options.trajectory_builder_2d_options(), SelectRangeSensorIds(expected_sensor_ids)); } DCHECK(dynamic_cast<PoseGraph2D*>(pose_graph_.get())); trajectory_builders_.push_back(absl::make_unique<CollatedTrajectoryBuilder>( trajectory_options, sensor_collator_.get(), trajectory_id, expected_sensor_ids, CreateGlobalTrajectoryBuilder2D( std::move(local_trajectory_builder), trajectory_id, static_cast<PoseGraph2D*>(pose_graph_.get()), local_slam_result_callback))); } MaybeAddPureLocalizationTrimmer(trajectory_id, trajectory_options, pose_graph_.get()); if (trajectory_options.has_initial_trajectory_pose()) { const auto& initial_trajectory_pose = trajectory_options.initial_trajectory_pose(); pose_graph_->SetInitialTrajectoryPose( trajectory_id, initial_trajectory_pose.to_trajectory_id(), transform::ToRigid3(initial_trajectory_pose.relative_pose()), common::FromUniversal(initial_trajectory_pose.timestamp())); } proto::TrajectoryBuilderOptionsWithSensorIds options_with_sensor_ids_proto; for (const auto& sensor_id : expected_sensor_ids) { *options_with_sensor_ids_proto.add_sensor_id() = ToProto(sensor_id); } *options_with_sensor_ids_proto.mutable_trajectory_builder_options() = trajectory_options; all_trajectory_builder_options_.push_back(options_with_sensor_ids_proto); CHECK_EQ(trajectory_builders_.size(), all_trajectory_builder_options_.size()); return trajectory_id; } int MapBuilder::AddTrajectoryForDeserialization( const proto::TrajectoryBuilderOptionsWithSensorIds& options_with_sensor_ids_proto) { const int trajectory_id = trajectory_builders_.size(); trajectory_builders_.emplace_back(); all_trajectory_builder_options_.push_back(options_with_sensor_ids_proto); CHECK_EQ(trajectory_builders_.size(), all_trajectory_builder_options_.size()); return trajectory_id; } void MapBuilder::FinishTrajectory(const int trajectory_id) { sensor_collator_->FinishTrajectory(trajectory_id); pose_graph_->FinishTrajectory(trajectory_id); } std::string MapBuilder::SubmapToProto( const SubmapId& submap_id, proto::SubmapQuery::Response* const response) { if (submap_id.trajectory_id < 0 || submap_id.trajectory_id >= num_trajectory_builders()) { return "Requested submap from trajectory " + std::to_string(submap_id.trajectory_id) + " but there are only " + std::to_string(num_trajectory_builders()) + " trajectories."; } const auto submap_data = pose_graph_->GetSubmapData(submap_id); if (submap_data.submap == nullptr) { return "Requested submap " + std::to_string(submap_id.submap_index) + " from trajectory " + std::to_string(submap_id.trajectory_id) + " but it does not exist: maybe it has been trimmed."; } submap_data.submap->ToResponseProto(submap_data.pose, response); return ""; } void MapBuilder::SerializeState(bool include_unfinished_submaps, io::ProtoStreamWriterInterface* const writer) { io::WritePbStream(*pose_graph_, all_trajectory_builder_options_, writer, include_unfinished_submaps); } std::map<int, int> MapBuilder::LoadState( io::ProtoStreamReaderInterface* const reader, bool load_frozen_state) { io::ProtoStreamDeserializer deserializer(reader); // Create a copy of the pose_graph_proto, such that we can re-write the // trajectory ids. proto::PoseGraph pose_graph_proto = deserializer.pose_graph(); const auto& all_builder_options_proto = deserializer.all_trajectory_builder_options(); std::map<int, int> trajectory_remapping; for (int i = 0; i < pose_graph_proto.trajectory_size(); ++i) { auto& trajectory_proto = *pose_graph_proto.mutable_trajectory(i); const auto& options_with_sensor_ids_proto = all_builder_options_proto.options_with_sensor_ids(i); const int new_trajectory_id = AddTrajectoryForDeserialization(options_with_sensor_ids_proto); CHECK(trajectory_remapping .emplace(trajectory_proto.trajectory_id(), new_trajectory_id) .second) << "Duplicate trajectory ID: " << trajectory_proto.trajectory_id(); trajectory_proto.set_trajectory_id(new_trajectory_id); if (load_frozen_state) { pose_graph_->FreezeTrajectory(new_trajectory_id); } } // Apply the calculated remapping to constraints in the pose graph proto. for (auto& constraint_proto : *pose_graph_proto.mutable_constraint()) { constraint_proto.mutable_submap_id()->set_trajectory_id( trajectory_remapping.at(constraint_proto.submap_id().trajectory_id())); constraint_proto.mutable_node_id()->set_trajectory_id( trajectory_remapping.at(constraint_proto.node_id().trajectory_id())); } MapById<SubmapId, transform::Rigid3d> submap_poses; for (const proto::Trajectory& trajectory_proto : pose_graph_proto.trajectory()) { for (const proto::Trajectory::Submap& submap_proto : trajectory_proto.submap()) { submap_poses.Insert(SubmapId{trajectory_proto.trajectory_id(), submap_proto.submap_index()}, transform::ToRigid3(submap_proto.pose())); } } MapById<NodeId, transform::Rigid3d> node_poses; for (const proto::Trajectory& trajectory_proto : pose_graph_proto.trajectory()) { for (const proto::Trajectory::Node& node_proto : trajectory_proto.node()) { node_poses.Insert( NodeId{trajectory_proto.trajectory_id(), node_proto.node_index()}, transform::ToRigid3(node_proto.pose())); } } // Set global poses of landmarks. for (const auto& landmark : pose_graph_proto.landmark_poses()) { pose_graph_->SetLandmarkPose(landmark.landmark_id(), transform::ToRigid3(landmark.global_pose())); } MapById<SubmapId, mapping::proto::Submap> submap_id_to_submap; MapById<NodeId, mapping::proto::Node> node_id_to_node; SerializedData proto; while (deserializer.ReadNextSerializedData(&proto)) { switch (proto.data_case()) { case SerializedData::kPoseGraph: LOG(ERROR) << "Found multiple serialized `PoseGraph`. Serialized " "stream likely corrupt!."; break; case SerializedData::kAllTrajectoryBuilderOptions: LOG(ERROR) << "Found multiple serialized " "`AllTrajectoryBuilderOptions`. Serialized stream likely " "corrupt!."; break; case SerializedData::kSubmap: { proto.mutable_submap()->mutable_submap_id()->set_trajectory_id( trajectory_remapping.at( proto.submap().submap_id().trajectory_id())); submap_id_to_submap.Insert( SubmapId{proto.submap().submap_id().trajectory_id(), proto.submap().submap_id().submap_index()}, proto.submap()); break; } case SerializedData::kNode: { proto.mutable_node()->mutable_node_id()->set_trajectory_id( trajectory_remapping.at(proto.node().node_id().trajectory_id())); const NodeId node_id(proto.node().node_id().trajectory_id(), proto.node().node_id().node_index()); const transform::Rigid3d& node_pose = node_poses.at(node_id); pose_graph_->AddNodeFromProto(node_pose, proto.node()); node_id_to_node.Insert(node_id, proto.node()); break; } case SerializedData::kTrajectoryData: { proto.mutable_trajectory_data()->set_trajectory_id( trajectory_remapping.at(proto.trajectory_data().trajectory_id())); pose_graph_->SetTrajectoryDataFromProto(proto.trajectory_data()); break; } case SerializedData::kImuData: { if (load_frozen_state) break; pose_graph_->AddImuData( trajectory_remapping.at(proto.imu_data().trajectory_id()), sensor::FromProto(proto.imu_data().imu_data())); break; } case SerializedData::kOdometryData: { if (load_frozen_state) break; pose_graph_->AddOdometryData( trajectory_remapping.at(proto.odometry_data().trajectory_id()), sensor::FromProto(proto.odometry_data().odometry_data())); break; } case SerializedData::kFixedFramePoseData: { if (load_frozen_state) break; pose_graph_->AddFixedFramePoseData( trajectory_remapping.at( proto.fixed_frame_pose_data().trajectory_id()), sensor::FromProto( proto.fixed_frame_pose_data().fixed_frame_pose_data())); break; } case SerializedData::kLandmarkData: { if (load_frozen_state) break; pose_graph_->AddLandmarkData( trajectory_remapping.at(proto.landmark_data().trajectory_id()), sensor::FromProto(proto.landmark_data().landmark_data())); break; } default: LOG(WARNING) << "Skipping unknown message type in stream: " << proto.GetTypeName(); } } // TODO(schwoere): Remove backwards compatibility once the pbstream format // version 2 is established. if (deserializer.header().format_version() == io::kFormatVersionWithoutSubmapHistograms) { submap_id_to_submap = cartographer::io::MigrateSubmapFormatVersion1ToVersion2( submap_id_to_submap, node_id_to_node, pose_graph_proto); } for (const auto& submap_id_submap : submap_id_to_submap) { pose_graph_->AddSubmapFromProto(submap_poses.at(submap_id_submap.id), submap_id_submap.data); } if (load_frozen_state) { // Add information about which nodes belong to which submap. // Required for 3D pure localization. for (const proto::PoseGraph::Constraint& constraint_proto : pose_graph_proto.constraint()) { if (constraint_proto.tag() != proto::PoseGraph::Constraint::INTRA_SUBMAP) { continue; } pose_graph_->AddNodeToSubmap( NodeId{constraint_proto.node_id().trajectory_id(), constraint_proto.node_id().node_index()}, SubmapId{constraint_proto.submap_id().trajectory_id(), constraint_proto.submap_id().submap_index()}); } } else { // When loading unfrozen trajectories, 'AddSerializedConstraints' will // take care of adding information about which nodes belong to which // submap. pose_graph_->AddSerializedConstraints( FromProto(pose_graph_proto.constraint())); } CHECK(reader->eof()); return trajectory_remapping; } std::map<int, int> MapBuilder::LoadStateFromFile( const std::string& state_filename) { const std::string suffix = ".pbstream"; if (state_filename.substr( std::max<int>(state_filename.size() - suffix.size(), 0)) != suffix) { LOG(WARNING) << "The file containing the state should be a " ".pbstream file."; } LOG(INFO) << "Loading saved state '" << state_filename << "'..."; io::ProtoStreamReader stream(state_filename); return LoadState(&stream, true); } } // namespace mapping } // namespace cartographer
c3073a438eb84ebb36e12fe23b7bb73d4597609a
eaba85a3864089c45b9820052162529e1a4b7b77
/src/ds-algo/trie.cpp
d4f9e8fd634b71285118e1ebfbd22403c7d23147
[]
no_license
shafwanur010/cp
77efc596af1038ba2c4769988fc948803ea10d78
1d0fc234956e8b469b1ed769c9fa1bae4a72888a
refs/heads/master
2023-09-03T23:04:05.054541
2023-08-19T06:20:50
2023-08-19T06:20:50
288,452,374
0
0
null
null
null
null
UTF-8
C++
false
false
1,505
cpp
#include <bits/stdc++.h> using namespace std; struct node { node *child[26]; bool isEnd; }; node* make() { node *u = new node; for (int i = 0; i < 26; i++) { u->child[i] = nullptr; } u->isEnd = false; return u; } void insert(node *root, string s) { node *u = root; for (char c : s) { int idx = c - 'a'; if (u->child[idx] == nullptr) { u->child[idx] = make(); } u = u->child[idx]; } u->isEnd = true; } bool search(node *root, string s) { node *u = root; for (char c : s) { int idx = c - 'a'; if (u->child[idx] == nullptr) { return false; } u = u->child[idx]; } return (u != nullptr and u->isEnd); } bool isEmpty(node *root) { for (int i = 0; i < 26; i++) { if (root->child[i] != nullptr) { return false; } } return true; } node* remove(node *root, string s, int dep = 0) { if (root == nullptr) { return nullptr; } if (dep == (int) s.size()) { if (root->isEnd) { root->isEnd = false; } if (isEmpty(root)) { delete root; root = nullptr; } return root; } int idx = s[dep] - 'a'; root->child[idx] = remove(root->child[idx], s, dep + 1); if (isEmpty(root) and !root->isEnd) { delete root; root = nullptr; } return root; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); node *root = make(); insert(root, "abcd"); cout << search(root, "abcd") << '\n'; remove(root, "abcd"); cout << search(root, "abcd") << '\n'; }
842dcfb3f6758d88873d60a66f6007e37cdcf6ce
8eac6a6d838ceb06c44daa28bb9ef7aaccddbf9b
/Chapter11/ch11ex2/DLHashTable.h
478bd21802e614e5802ba0f13415dc735bc91a96
[]
no_license
Song621/CPP-Classes-and-Data-Structures
e66def3fca5eb85c2e7503e5d8293879e53250c6
d9c1ede3c92ab123a600a18ae03f124e41ba3c6f
refs/heads/master
2023-08-30T12:56:06.279988
2021-11-10T16:53:46
2021-11-10T16:53:46
303,077,699
0
0
null
null
null
null
UTF-8
C++
false
false
2,484
h
#pragma once #include "Array.h" #include "CollisionList.h" template <class DataType> class DLHashTable { public: DLHashTable(int (*hf)(const DataType&), int s); bool insert(const DataType& newObject); bool retrieve(DataType& retrieved); bool remove(DataType& removed); bool update(DataType& updateObject); void makeEmpty(); Node<DataType>* getcurrent(); int (*gethashfunc() const)(const DataType&); void sethashfunc(int (*hf)(const DataType&)); int getsize() const; void changeSize(int newSize); private: Array<CollisionList<DataType> > table; int (*hashfunc)(const DataType&); int location; }; template <class DataType> DLHashTable<DataType>::DLHashTable(int(*hf)(const DataType&), int s) :table(s) { hashfunc = hf; } template <class DataType> bool DLHashTable<DataType>::insert(const DataType& newObject) { location = hashfunc(newObject); if (location < 0 || location > table.length()) return false; table[location].insert(newObject); return true; } template <class DataType> bool DLHashTable<DataType>::retrieve(DataType& retrieved) { location = hashfunc(retrieved); if (location < 0 || location > table.length()) return false; if (!table[location].retrieve(retrieved)) return false; return true; } template <class DataType> bool DLHashTable<DataType>::remove(DataType& removed) { location = hashfunc(removed); if (location < 0 || location > table.length()) return false; if (!table[location].remove(removed)) return false; return true; } template <class DataType> bool DLHashTable<DataType>::update(DataType& updateObject) { location = hashfunc(updateObject); if (location < 0 || location > table.length()) return false; if (!table[location].find(updateObject)) return false; table[location].replace(updateObject); return true; } template <class DataType> void DLHashTable<DataType>::makeEmpty() { for (int i = 0; i < table.length(); i++) table[i].makeEmpty(); } template <class DataType> Node<DataType>* DLHashTable<DataType>::getcurrent() { return table[location].getcurrent(); } template <class DataType> int (*DLHashTable<DataType>::gethashfunc() const)(const DataType&) { return hashfunc; } template <class DataType> void DLHashTable<DataType>::sethashfunc(int (*hf)(const DataType&)) { hashfunc = hf; } template <class DataType> int DLHashTable<DataType>::getsize() const { return table.length(); } template <class DataType> void DLHashTable<DataType>::changeSize(int newSize) { table.changeSize(newSize); }
8d85a96e2987285412807bf7aa6e7d3c057206e0
fa623d526d6ca624d60a702f5c6671cbcec1c23e
/praduck/levelmap.h
d128d14e50a77a1eba2a03375c8b2745fa81195f
[]
no_license
imclab/plusplus-warrior
a9e3372de7bfbdc68efc2f9936efb6e035b80825
668279f82ca7a641d68c66d87589f2327eb0403c
refs/heads/master
2021-05-01T20:31:36.547667
2014-02-06T03:14:49
2014-02-06T03:14:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
780
h
#ifndef __praduck__LevelMap__ #define __praduck__LevelMap__ #include <iostream> #include <fstream> #include <iomanip> #include "BaseTile.h" #include "CreatureTile.h" class TileController; using namespace std; class LevelMap { protected: BaseTile* map[20][20]; BaseTile* TileFromChar(char c); public: int width, height; CreatureTile** creatures = new CreatureTile*[20]; TileController** controllers = new TileController*[20]; int creatureCount = 0; BaseTile* GetTile (int x, int y); void SetTile(int x, int y, BaseTile* value); int MoveTile(BaseTile* tile, int x, int y); void PrintMap(ostream& output); void LoadMap(string filename); }; ostream& operator<<(ostream& os, LevelMap& lm); #endif /* defined(__praduck__LevelMap__) */
2e7d2144d4a8365ee58e6b203563b4089467d6ae
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14539/function14539_schedule_15/function14539_schedule_15.cpp
34f3a0086c48f3256198d482c3c0cea85fb84035
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,781
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14539_schedule_15"); constant c0("c0", 256), c1("c1", 128), c2("c2", 2048); var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i01("i01"), i02("i02"), i03("i03"), i04("i04"); input input00("input00", {i1}, p_int32); input input01("input01", {i1, i2}, p_int32); input input02("input02", {i0}, p_int32); input input03("input03", {i1, i2}, p_int32); input input04("input04", {i0, i1}, p_int32); input input05("input05", {i1, i2}, p_int32); input input06("input06", {i0}, p_int32); computation comp0("comp0", {i0, i1, i2}, input00(i1) + input01(i1, i2) - input02(i0) - input03(i1, i2) + input04(i0, i1) - input05(i1, i2) + input06(i0)); comp0.tile(i1, i2, 128, 64, i01, i02, i03, i04); comp0.parallelize(i0); buffer buf00("buf00", {128}, p_int32, a_input); buffer buf01("buf01", {128, 2048}, p_int32, a_input); buffer buf02("buf02", {256}, p_int32, a_input); buffer buf03("buf03", {128, 2048}, p_int32, a_input); buffer buf04("buf04", {256, 128}, p_int32, a_input); buffer buf05("buf05", {128, 2048}, p_int32, a_input); buffer buf06("buf06", {256}, p_int32, a_input); buffer buf0("buf0", {256, 128, 2048}, p_int32, a_output); input00.store_in(&buf00); input01.store_in(&buf01); input02.store_in(&buf02); input03.store_in(&buf03); input04.store_in(&buf04); input05.store_in(&buf05); input06.store_in(&buf06); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf06, &buf0}, "../data/programs/function14539/function14539_schedule_15/function14539_schedule_15.o"); return 0; }
75a303642f8bc683a5bbe664f60b731685865ac4
f0779717341f2c471191a94250f5b83ab3dc20cc
/OpenCV3/CPP-TCP-Client/CPP-TCP-Client/main.cpp
52ac2624257c173696723642a11704b9222d22cd
[]
no_license
IceArmour/ZSC-2017-ETHEIH
c6de0e143dcf683d436c0dd653423743769ba9d9
f85f0a64c7b2521bfc8e6a6d58c88980f0027e05
refs/heads/master
2020-03-27T08:34:03.460285
2018-08-12T23:15:10
2018-08-12T23:15:10
131,006,600
0
0
null
2018-04-25T12:57:53
2018-04-25T12:57:53
null
UTF-8
C++
false
false
1,343
cpp
//--------------------------------------【程序说明】------------------------------------------- // 程序说明:第11次汇报 CPP-TCP-Client // 程序描述:建立TCP通信协议,作为客户端与VISOR进行通信 // 开发测试所用操作系统:Windows 10 64bit // 开发测试所用IDE版本:Visual Studio 2017 // 2018年8月9日 Created by @ZHWKnight // 2018年4月13日 Revised by @ZHWKnight //--------------------------------------------------------------------------------------------- #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <WinSock2.h> #include <conio.h> #pragma comment(lib, "ws2_32.lib") int main() { WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockAddr)); sockAddr.sin_family = PF_INET; sockAddr.sin_addr.s_addr = inet_addr("192.168.100.100"); sockAddr.sin_port = htons(2005); connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)); char szBuffer[MAXBYTE] = { 0 }; int flag = 1; char unch; while (flag){ if (_kbhit() && (unch = _getch()) == 0x1b) flag = 0; recv(sock, szBuffer, MAXBYTE, NULL); printf("Coordinate form VISOR: %s\n", szBuffer); } closesocket(sock); WSACleanup(); system("pause"); return 0; }
7de8422be9b8145b2418279d253c84d60eef52c5
8f5f13f74e63cbe9d8a28d60a649b9fece7b2146
/OpenGL/src/5_advanced_lighting/3_15_deferred_lighting_with_SSAO_with_blur.cpp
f676fbbf29156d07db5b7de0b385ce991575d4d0
[]
no_license
GameDevZone/OpenGL
0a2c424405cd8f97efefb29bdc884df8fd31a97f
1670e4d90187536eb0e477416f7d134431d142de
refs/heads/master
2020-04-11T02:52:35.337836
2019-02-21T09:01:09
2019-02-21T09:01:09
161,459,704
0
0
null
null
null
null
UTF-8
C++
false
false
25,404
cpp
#include <glad/glad.h> #include <GLFW/glfw3.h> #include "../std_image.h" #include "glm.hpp" #include "gtc/matrix_transform.hpp" #include "gtc/type_ptr.hpp" #include "../Shader.h" #include "../Camera.h" #include "../Model.h" #include <iostream> #include <random> #define WINDOW_WIDTH 1280 #define WINDOW_HEIGHT 720 const unsigned int SHADOW_WIDTH = 1024 * 2, SHADOW_HEIGHT = 1024 * 2; void framebuffer_size_callback(GLFWwindow *Window, int width, int height); void processInput(GLFWwindow *window); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); unsigned int loadTexture(const char *path, bool gamma); unsigned int loadSkyBox(std::vector<std::string> faces); unsigned int createFrameBuffer(unsigned int textureColorBuffer, unsigned int renderBuffer, GLenum attch); unsigned int createTextureBuffer(GLint internalFormat, GLenum format, GLenum type); unsigned int createRenderBuffer(GLenum internalformat); unsigned int createFloatFrameBuffer(); void renderCube(); void renderQuad(); float lerp(float a, float b, float t) { return a + b * (1 - t); } // camera Camera camera(glm::vec3(0.0f, 0.0f, 5.0f)); bool firstMouse = true; float lastX = WINDOW_WIDTH / 2.0; float lastY = WINDOW_WIDTH / 2.0; // delta time float deltaTime = .0f; float lastTime = .0f; // switch diffuse color buffer int startIndex = 0; // 0,1,2 bool switchKeyPressed = false; #define max_index 3 float checkRaidus = 0.5f; bool checkKeyPressed = false; float power = 2.0f; bool powerKeyPressed = false; int main(void) { GLFWwindow* window; if (!glfwInit()) return -1; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // __APPLE__ /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Learn OpenGL", NULL, NULL); if (!window) { std::cout << "Failed To Create GLFW Window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); glEnable(GL_DEPTH_TEST); Shader deferredGeometryPass( "shader/5_section_shaders/3_13_ssao_deferred_shading_geometry_pass.vs", "shader/5_section_shaders/3_13_ssao_deferred_shading_geometry_pass.fs"); Shader ssaoCalcluate( "shader/5_section_shaders/3_13_ssao_calcluate.vs", "shader/5_section_shaders/3_13_ssao_calcluate.fs"); Shader ssaoShow( "shader/5_section_shaders/3_13_show_ssao.vs", "shader/5_section_shaders/3_13_show_ssao.fs"); Shader ssaoBlur( "shader/5_section_shaders/3_14_ssao_blur.vs", "shader/5_section_shaders/3_14_ssao_blur.fs"); Shader lightGeometryPass( "shader/5_section_shaders/3_14_lighting_geomety_buffer_ssao_blur.vs", "shader/5_section_shaders/3_14_lighting_geomety_buffer_ssao_blur.fs"); Shader lightObject( "shader/5_section_shaders/3_12_deferred_lighting_box.vs", "shader/5_section_shaders/3_12_deferred_lighting_box.fs"); ssaoBlur.Use(); ssaoBlur.SetInt("ssaoInput", 0); lightGeometryPass.Use(); lightGeometryPass.SetInt("position", 0); lightGeometryPass.SetInt("normal", 1); lightGeometryPass.SetInt("albedo", 2); lightGeometryPass.SetInt("ssao", 3); ssaoCalcluate.Use(); ssaoCalcluate.SetInt("gPosition", 0); ssaoCalcluate.SetInt("gNormal", 1); ssaoCalcluate.SetInt("gNoise", 2); ssaoShow.Use(); ssaoShow.SetInt("imageBuffer", 0); Model nanosuit("Resources/objects/nanosuit/nanosuit.obj"); // create geometry buffer unsigned int geometryBuffer; glGenFramebuffers(1, &geometryBuffer); glBindFramebuffer(GL_FRAMEBUFFER, geometryBuffer); // color buffers unsigned int positionBuffer, normalBuffer, albedoSpecBuffer; glGenTextures(1, &positionBuffer); glBindTexture(GL_TEXTURE_2D, positionBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, positionBuffer, 0); glGenTextures(1, &normalBuffer); glBindTexture(GL_TEXTURE_2D, normalBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, normalBuffer, 0); glGenTextures(1, &albedoSpecBuffer); glBindTexture(GL_TEXTURE_2D, albedoSpecBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, albedoSpecBuffer, 0); unsigned int attachments[3] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2 }; glDrawBuffers(3, attachments); // depth buffer unsigned int depthRenderbuffer; glGenRenderbuffers(1, &depthRenderbuffer); glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WINDOW_WIDTH, WINDOW_HEIGHT); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Frame Buffer is not complete!!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); glm::vec3 lightPos = glm::vec3(2.0, 4.0, -2.0); glm::vec3 lightColor = glm::vec3(0.2, 0.2, 0.7); // sample kernel std::uniform_real_distribution<float> randomFloats(0.0, 1.0); std::default_random_engine generator; std::vector<glm::vec3> ssaoKernel; for (unsigned int i = 0; i < 64; i ++) { glm::vec3 sample( randomFloats(generator) * 2.0 - 1.0, // x randomFloats(generator) * 2.0 - 1.0, // y randomFloats(generator) // z keep it in 0.0-1.0 cuz we using hemisphere ); sample = glm::normalize(sample); sample *= randomFloats(generator); float scale = 1.0 / 64.0f; scale = lerp(0.1f, 1.0f, scale * scale); sample *= scale; ssaoKernel.push_back(sample); } // random kernel rotaions std::vector<glm::vec3> ssaoNoise; for (unsigned int i = 0; i < 16; i++) { glm::vec3 rotation( randomFloats(generator) * 2.0 - 1.0, randomFloats(generator) * 2.0 - 1.0, 0.0f // we rotate along z axis ); ssaoNoise.push_back(rotation); } // create noise texture unsigned int noiseTexture; glGenTextures(1, &noiseTexture); glBindTexture(GL_TEXTURE_2D, noiseTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, 4, 4, 0, GL_RGB, GL_FLOAT, &ssaoNoise[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // SSAO framebuffer unsigned int ssaoFrameBuffer; glGenFramebuffers(1, &ssaoFrameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, ssaoFrameBuffer); unsigned int ssaoColorBuffer; glGenTextures(1, &ssaoColorBuffer); glBindTexture(GL_TEXTURE_2D, ssaoColorBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //glDrawBuffer(GL_NONE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoColorBuffer, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << "Create SSAO Frame buffer failed!!" << std::endl; } glBindFramebuffer(GL_FRAMEBUFFER, 0); // SSAO framebuffer unsigned int ssaoblurFrameBuffer; glGenFramebuffers(1, &ssaoblurFrameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, ssaoblurFrameBuffer); unsigned int ssaoblurColorBuffer; glGenTextures(1, &ssaoblurColorBuffer); glBindTexture(GL_TEXTURE_2D, ssaoblurColorBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGB, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //glDrawBuffer(GL_NONE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoblurColorBuffer, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << "Create SSAO Frame buffer failed!!" << std::endl; } while (!glfwWindowShouldClose(window)) { float currentFrame = (float)glfwGetTime(); deltaTime = currentFrame - lastTime; lastTime = currentFrame; /* key input */ processInput(window); glClearColor(0.2f, 0.2f, 0.2f, 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 1. geometry pass glBindFramebuffer(GL_FRAMEBUFFER, geometryBuffer); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float)WINDOW_WIDTH / (float)WINDOW_HEIGHT, 0.1f, 100.0f); glm::mat4 view = camera.GetViewMatrix(); deferredGeometryPass.Use(); deferredGeometryPass.SetMat4("projection", projection); deferredGeometryPass.SetMat4("view", view); // room cube glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(0.0, 7.0f, 0.0f)); model = glm::scale(model, glm::vec3(7.5f, 7.5f, 7.5f)); deferredGeometryPass.SetMat4("model", model); deferredGeometryPass.SetInt("inverse_normal", 1); // invert normals as we're inside the cube renderCube(); model = glm::mat4(1.0f); deferredGeometryPass.SetInt("inverse_normal", 0); // nanosuit model on the floor model = glm::translate(model, glm::vec3(0.0f, 0.0f, 5.0)); model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0, 0.0, 0.0)); model = glm::scale(model, glm::vec3(0.5f)); deferredGeometryPass.SetMat4("model", model); //model = glm::scale(model, glm::vec3(0.2f)); //model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(1.0, 0.0, 0.0)); //model = glm::translate(model, glm::vec3(0.0, -2.0f, 0.0)); //deferredGeometryPass.SetMat4("model", model); nanosuit.Draw(deferredGeometryPass); glBindFramebuffer(GL_FRAMEBUFFER, 0); // ssao factor glBindFramebuffer(GL_FRAMEBUFFER, ssaoFrameBuffer); glClear(GL_COLOR_BUFFER_BIT); ssaoCalcluate.Use(); ssaoCalcluate.SetFloat("kernelSize", 64); ssaoCalcluate.SetFloat("power", power); ssaoCalcluate.SetFloat("radius", checkRaidus); ssaoCalcluate.SetMat4("projection", projection); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, positionBuffer); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normalBuffer); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, albedoSpecBuffer); //uniform vec3 samples[64]; for (unsigned int i = 0; i < 64; i ++) { ssaoCalcluate.SetVec3("samples[" + std::to_string(i) + "]", ssaoKernel[i]); } renderQuad(); glBindFramebuffer(GL_FRAMEBUFFER, 0); // ssao blur glBindFramebuffer(GL_FRAMEBUFFER, ssaoblurFrameBuffer); ssaoBlur.Use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, ssaoColorBuffer); renderQuad(); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); lightGeometryPass.Use(); glm::vec3 lightPosView = glm::vec3(camera.GetViewMatrix() * glm::vec4(lightPos, 1.0)); lightGeometryPass.SetVec3("light.Position", lightPosView); lightGeometryPass.SetVec3("light.Color", lightColor); const float constant = 1.0; const float linear = 0.09; const float quadratic = 0.032; lightGeometryPass.SetFloat("light.Linear", linear); lightGeometryPass.SetFloat("light.Quadratic", quadratic); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, positionBuffer); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, normalBuffer); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, albedoSpecBuffer); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, ssaoblurColorBuffer); renderQuad(); glfwSwapBuffers(window); glfwPollEvents(); } /* clear all the stuff */ glfwTerminate(); return 0; } unsigned int cubeVAO = 0; unsigned int cubeVBO = 0; void renderCube() { // initialize (if necessary) if (cubeVAO == 0) { float vertices[] = { // back face -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, // top-left // front face -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // top-left -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left // left face -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-left -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-right -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right // right face 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-left // bottom face -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // top-left 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-right -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right // top face -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left 1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f // bottom-left }; glGenVertexArrays(1, &cubeVAO); glGenBuffers(1, &cubeVBO); // fill buffer glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // link vertex attributes glBindVertexArray(cubeVAO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } // render Cube glBindVertexArray(cubeVAO); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); } unsigned int quadVAO = 0; unsigned int quadVBO; void renderQuad() { if (quadVAO == 0) { float quadVertices[] = { // positions // texture Coords -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, }; // setup plane VAO glGenVertexArrays(1, &quadVAO); glGenBuffers(1, &quadVBO); glBindVertexArray(quadVAO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); } glBindVertexArray(quadVAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll((float)yoffset); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = (float)xpos; lastY = (float)ypos; firstMouse = false; } float offsetX = (float)xpos - lastX; float offsetY = lastY - (float)ypos; lastX = (float)xpos; lastY = (float)ypos; camera.ProcessMouseMovement(offsetX, offsetY); } void framebuffer_size_callback(GLFWwindow *Window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow *window) { float cameraSpeed = 2.5f * deltaTime; if (glfwGetKey(window, GLFW_KEY_ESCAPE)) { glfwSetWindowShouldClose(window, true); } if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) camera.ProcessKeyboard(FORWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard(BACKWARD, deltaTime); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard(LEFT, deltaTime); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard(RIGHT, deltaTime); if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) camera.ProcessKeyboard(DOWN, deltaTime); if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS) camera.ProcessKeyboard(UP, deltaTime); if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS && !switchKeyPressed) { startIndex += 1; if ((startIndex) > max_index) startIndex = 0; switchKeyPressed = true; } if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_RELEASE) { switchKeyPressed = false; } if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS && !checkKeyPressed) { checkRaidus += 0.01; if ((checkRaidus) > 1.5f) checkRaidus = 1.5f; checkKeyPressed = true; } if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_RELEASE) { checkKeyPressed = false; } if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS && !checkKeyPressed) { checkRaidus -= 0.01; if ((checkRaidus) < 0.0f) checkRaidus = 0.0f; checkKeyPressed = true; } if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_RELEASE) { checkKeyPressed = false; } if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS && !powerKeyPressed) { power *= 2; if ((power) > 256.f) power = 256.f; powerKeyPressed = true; } if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_RELEASE) { powerKeyPressed = false; } if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS && !powerKeyPressed) { power /= 2; if ((power) < 1.f) power = 1.f; powerKeyPressed = true; } if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_RELEASE) { powerKeyPressed = false; } } unsigned int createRenderBuffer(GLenum internalFormat) { // renderbuffer object unsigned int renderBuffer; glGenRenderbuffers(1, &renderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, internalFormat, WINDOW_WIDTH, WINDOW_HEIGHT); glBindRenderbuffer(GL_RENDERBUFFER, 0); return renderBuffer; } unsigned int createTextureBuffer(GLint interalFormat, GLenum format, GLenum type) { // texture attachment unsigned int textureColorBuffer; glGenTextures(1, &textureColorBuffer); glBindTexture(GL_TEXTURE_2D, textureColorBuffer); // glTexImage2D(GL_TEXTURE_2D, 0, interalFormat, WINDOW_WIDTH, WINDOW_HEIGHT, 0, format, type, NULL); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); return textureColorBuffer; } unsigned int createFloatFrameBuffer() { unsigned int bloomFBO; glGenFramebuffers(1, &bloomFBO); // create floating point color buffer unsigned int colorBuffer; glGenTextures(1, &colorBuffer); glBindTexture(GL_TEXTURE_2D, colorBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, WINDOW_WIDTH, WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // create depth buffer (renderbuffer) unsigned int rboDepth; glGenRenderbuffers(1, &rboDepth); glBindRenderbuffer(GL_RENDERBUFFER, rboDepth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, WINDOW_WIDTH, WINDOW_HEIGHT); // attach buffers glBindFramebuffer(GL_FRAMEBUFFER, bloomFBO); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rboDepth); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); return bloomFBO; } unsigned int createFrameBuffer(unsigned int textureColorBuffer, unsigned int renderBuffer, GLenum attach) { // configure frame buffer unsigned int framebuffer; glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); //glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureColorBuffer, 0); //glFramebufferRenderbuffer(GL_FRAMEBUFFER, attach, GL_RENDERBUFFER, renderBuffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textureColorBuffer, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderBuffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << __LINE__ << " ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); return framebuffer; } unsigned int loadTexture(char const * path, bool gamma = false) { unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0); if (data) { GLenum dataFormat; GLenum internalFormat; if (nrComponents == 1) { internalFormat = dataFormat = GL_RED; } else if (nrComponents == 3) { internalFormat = gamma ? GL_SRGB : GL_RGB; dataFormat = GL_RGB; } else if (nrComponents == 4) { internalFormat = gamma ? GL_SRGB_ALPHA : GL_RGBA; dataFormat = GL_RGBA; } glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, dataFormat, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; } unsigned int loadSkyBox(std::vector<std::string> faces) { unsigned int skyboxTextureID; glGenTextures(1, &skyboxTextureID); glBindTexture(GL_TEXTURE_CUBE_MAP, skyboxTextureID); int width, height, nrChannels; for (unsigned int i = 0; i < faces.size(); i++) { unsigned char* data = stbi_load(faces[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return skyboxTextureID; }
373b86995aaeba7d31ab4a985ec4d24233a0a3a5
1815b64a60fa9d0ccd3270d53cd176536558153f
/chrome/browser/policy/messaging_layer/util/heartbeat_event_factory.cc
4aab15858c2ce01ee974b486c74f51c320413c15
[ "BSD-3-Clause" ]
permissive
violetForeden/chromium
ae8c65739de96dd141136e6523b4a2c5978491d9
43f3ea874caca29eead4dc4dfb1c8ce6f11fa5da
refs/heads/main
2023-06-29T09:43:21.454580
2021-09-12T08:27:01
2021-09-12T08:27:01
405,598,541
1
0
BSD-3-Clause
2021-09-12T09:22:55
2021-09-12T09:22:55
null
UTF-8
C++
false
false
1,693
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/messaging_layer/util/heartbeat_event_factory.h" #include "chrome/browser/policy/messaging_layer/util/heartbeat_event.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ash/policy/core/user_cloud_policy_manager_ash.h" #else #include "components/policy/core/common/cloud/user_cloud_policy_manager.h" #endif namespace reporting { HeartbeatEventFactory* HeartbeatEventFactory::GetInstance() { return base::Singleton<HeartbeatEventFactory>::get(); } HeartbeatEventFactory::HeartbeatEventFactory() : BrowserContextKeyedServiceFactory( "HeartbeatEvent", BrowserContextDependencyManager::GetInstance()) {} HeartbeatEventFactory::~HeartbeatEventFactory() = default; KeyedService* HeartbeatEventFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { Profile* profile = static_cast<Profile*>(context); #if BUILDFLAG(IS_CHROMEOS_ASH) policy::UserCloudPolicyManagerAsh* manager = profile->GetUserCloudPolicyManagerAsh(); #else policy::UserCloudPolicyManager* manager = profile->GetUserCloudPolicyManager(); #endif if (!manager) { return nullptr; } return new HeartbeatEvent(manager); } bool HeartbeatEventFactory::ServiceIsCreatedWithBrowserContext() const { return true; } bool HeartbeatEventFactory::ServiceIsNULLWhileTesting() const { return true; } } // namespace reporting
6f74e6851a700687498ca18d0785515c19ebc43e
881065f461f7bc9abd1a99dd2e09da78d0348c01
/Programm/VokabeltrainerDGJE.cpp
b507d7c152b915a79ea95de92ce2063ea5961ea0
[]
no_license
DennisGoss99/Projekt-Voc
14a2f0618e7413b510c4c0944e186044b37230f7
c94f51414808959caa34422b60a8b2105668a421
refs/heads/master
2020-05-06T15:18:46.559369
2019-04-30T21:09:46
2019-04-30T21:09:46
180,183,380
0
0
null
null
null
null
UTF-8
C++
false
false
1,108
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <tchar.h> //--------------------------------------------------------------------------- #include <Vcl.Styles.hpp> #include <Vcl.Themes.hpp> USEFORM("uFrmCheckVoc.cpp", frmCheckVoc); USEFORM("uFrmMain.cpp", frmMain); USEFORM("uFrmAddVoc.cpp", frmAddVoc); //--------------------------------------------------------------------------- int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) { try { Application->Initialize(); Application->MainFormOnTaskBar = true; Application->CreateForm(__classid(TfrmMain), &frmMain); Application->CreateForm(__classid(TfrmAddVoc), &frmAddVoc); Application->CreateForm(__classid(TfrmCheckVoc), &frmCheckVoc); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } catch (...) { try { throw Exception(""); } catch (Exception &exception) { Application->ShowException(&exception); } } return 0; } //---------------------------------------------------------------------------
6ace4346789645c05334fadbcae6ddcd85808d28
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/Chaste/2016/8/AbstractAcinarUnitFactory.cpp
1d66673254aedfa5d9313fe09f668d4ff2f7e6f7
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
2,664
cpp
/* Copyright (c) 2005-2016, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AbstractAcinarUnitFactory.hpp" #include "AbstractAcinarUnit.hpp" //void AbstractAcinarUnitFactory::FinaliseAcinarUnitCreation( // std::vector< AbstractAcinarUnit* >* pAcinarUnitsDistributed, // unsigned lo, // unsigned hi) //{ //} unsigned AbstractAcinarUnitFactory::GetNumberOfAcini() { assert(mpMesh != NULL); return mpMesh->GetNumBoundaryNodes(); } AbstractAcinarUnitFactory::AbstractAcinarUnitFactory() : mpMesh(NULL) { } AbstractAcinarUnitFactory::~AbstractAcinarUnitFactory() { } void AbstractAcinarUnitFactory::SetMesh(AbstractTetrahedralMesh<1,3>* pMesh) { mpMesh = pMesh; } AbstractTetrahedralMesh<1,3>* AbstractAcinarUnitFactory::GetMesh() { if (mpMesh == NULL) { EXCEPTION("The mesh object has not been set in the acinar unit factory"); } return mpMesh; } double AbstractAcinarUnitFactory::GetPleuralPressureForNode(double time, Node<3>* pNode) { return 0.0; }
f523f810a34c707f69f06a32a7b6c4cdaab6631b
c22d65113ebf726c89fdc8da2a7e5e3552478014
/src/libraries/Bounce2/Bounce2.h
e9fe87cdbe180c07125b284b793ac10d5ba37123
[]
no_license
d-diot/mainmcu
4b1795607223a65b7f956916912994e87188a9b4
fc2175f937a0f086eb50ddf2b26ac53298460cf4
refs/heads/master
2023-02-27T12:43:55.095736
2021-01-29T20:54:52
2021-01-29T20:54:52
268,135,663
0
0
null
null
null
null
UTF-8
C++
false
false
6,300
h
/* The MIT License (MIT) Copyright (c) 2013 thomasfredericks Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Main code by Thomas O Fredericks ([email protected]) Previous contributions by Eric Lowry, Jim Schimpf and Tom Harkaway * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @todo Make Bounce2 more abstract. Split it from the hardware layer. * @body Remove deboucing code from Bounce2 and make a new Debounce class from that code. Bounce2 should extend Debounce. */ #ifndef Bounce2_h #define Bounce2_h #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif // Uncomment the following line for "LOCK-OUT" debounce method //#define BOUNCE_LOCK_OUT // Uncomment the following line for "BOUNCE_WITH_PROMPT_DETECTION" debounce method //#define BOUNCE_WITH_PROMPT_DETECTION #include <inttypes.h> /** @example bounce.ino Simple example of the Bounce library that switches the debug LED when a button is pressed. */ /** @example change.ino This example toggles the debug LED (pin 13) on or off when a button on pin 2 is pressed. */ /** @example bounce_multiple.ino Detect the falling edge of multiple buttons. Eight buttons with internal pullups. Toggles a LED when any button is pressed. Buttons on pins 2,3,4,5,6,7,8,9 */ /** @example bounce2buttons.ino Example of two instances of the Bounce class that switches the debug LED when either one of the two buttons is pressed. */ static const uint8_t DEBOUNCED_STATE = 0b00000001; static const uint8_t UNSTABLE_STATE = 0b00000010; static const uint8_t CHANGED_STATE = 0b00000100; /** The Bounce class. */ class Bounce { public: /*! @brief Create an instance of the Bounce class. @code // Create an instance of the Bounce class. Bounce() button; @endcode */ Bounce(); /*! @brief Attach to a pin and sets that pin's mode (INPUT, INPUT_PULLUP or OUTPUT). @param pin The pin that is to be debounced. @param mode A valid Arduino pin mode (INPUT, INPUT_PULLUP or OUTPUT). */ void attach(int pin, int mode); /** Attach to a pin for advanced users. Only attach the pin this way once you have previously set it up. Otherwise use attach(int pin, int mode). */ void attach(int pin); /** @brief Sets the debounce interval in milliseconds. @param interval_millis The interval time in milliseconds. */ void interval(uint16_t interval_millis); /*! @brief Updates the pin's state. Because Bounce does not use interrupts, you have to "update" the object before reading its value and it has to be done as often as possible (that means to include it in your loop()). Only call update() once per loop(). @return True if the pin changed state. */ bool update(); /** @brief Returns the pin's state (HIGH or LOW). @return HIGH or LOW. */ bool read(); /** @brief Returns true if pin signal transitions from high to low. */ bool fell(); /** @brief Returns true if pin signal transitions from low to high. */ bool rose(); /** @brief Deprecated (i.e. do not use). Included for partial compatibility for programs written with Bounce version 1 */ bool risingEdge() { return rose(); } /** @brief Deprecated (i.e. do not use). Included for partial compatibility for programs written with Bounce version 1 */ bool fallingEdge() { return fell(); } /** @brief Deprecated (i.e. do not use). Included for partial compatibility for programs written with Bounce version 1 */ Bounce(uint8_t pin, unsigned long interval_millis) : Bounce() { attach(pin); interval(interval_millis); } /** @brief Returns the duration in milliseconds of the current state. Is reset to 0 once the pin rises ( rose() ) or falls ( fell() ). @return The duration in milliseconds (unsigned long) of the current state. */ unsigned long duration(); /** @brief Returns the duration in milliseconds of the previous state. Takes the values of duration() once the pin changes state. @return The duration in milliseconds (unsigned long) of the previous state. */ unsigned long previousDuration(); protected: unsigned long previous_millis; uint16_t interval_millis; uint8_t state; uint8_t pin; unsigned long stateChangeLastTime; unsigned long durationOfPreviousState; virtual bool readCurrentState() { return digitalRead(pin); } virtual void setPinMode(int pin, int mode) { #if defined(ARDUINO_ARCH_STM32F1) pinMode(pin, (WiringPinMode)mode); #else pinMode(pin, mode); #endif } private: inline void changeState(); inline void setStateFlag(const uint8_t flag) { state |= flag; } inline void unsetStateFlag(const uint8_t flag) { state &= ~flag; } inline void toggleStateFlag(const uint8_t flag) { state ^= flag; } inline bool getStateFlag(const uint8_t flag) { return ((state & flag) != 0); } public: bool changed() { return getStateFlag(CHANGED_STATE); } }; #endif
068249937238b4474fabad7e5fccb75659d0154f
9a9297f7760f3e07ce281e7ab0e85dd2e2d607bd
/testbed/tests/es_benchmark_seed1.cpp
72c6623cb649663494468452fcb1bdaedf1d0205
[ "MIT" ]
permissive
DomiKoPL/BoxCar2D.cpp
c63d8b6e181a280529b8271928be3423cb362098
a3bbb80304bccf7a8a232bfb8fe78718c47e03f7
refs/heads/main
2023-07-18T17:55:01.032440
2021-09-19T16:19:47
2021-09-19T16:19:47
332,049,853
0
0
null
null
null
null
UTF-8
C++
false
false
7,818
cpp
#include "test.h" #include <string> #include "car.h" #include "chromosome.h" #include <algorithm> #include "es_benchmark_seed1.hpp" #include <iostream> #include "settings.h" ESBenchmarkSeed1::ESBenchmarkSeed1() { blocked_environment = nullptr; } void ESBenchmarkSeed1::Step(Settings& settings) { if(blocked_environment == nullptr) { blocked_environment = new RandomTrack(true, settings.m_seed); std::thread thread = std::thread([&]() { std::vector<Chromosome> cars { { { -1.40947,3.33867,0.664098,2.02331,-0.789912,0.283467,-4.22899,2.12154,0.626879,-0.589122,0.134152,-0.689913,1.59957,-4.35033,3.48799,1.48576,-0.525083,1.01047,-0.284946,1.95286,1.63649,-1.3947,-0.455445,1.33717,0.659162,-0.994306,-1.91633,1.28992,1.0544,0.239294,0.799867,1.44854 } }, { { -1.34254,2.77852,1.96346,2.03842,1.65576,-0.883999,-0.338317,2.18958,0.293332,-0.254225,-0.786506,-0.393182,1.85326,-2.91368,2.8098,1.63223,-0.456717,1.023,-0.792659,0.602946,1.83317,-0.367612,-0.755923,1.8626,0.816038,-1.68726,-1.36289,-0.0532756,1.21996,0.558007,0.836011,1.10054 } }, { { 1.23172,1.58208,-0.961399,-0.152305,-1.40711,-3.52487,1.09184,1.76378,-0.324951,0.169049,-1.87576,0.653553,-0.28068,0.615594,0.833145,-0.145624,-3.71903,0.111686,1.57014,-3.83783,0.524206,0.524062,4.62487,1.12221,1.52598,1.07277,1.49888,-0.035017,-1.45523,-0.0109419,-2.76209,-1.89912 } }, { { -1.33449,4.52321,3.70357,2.38846,0.869323,1.91141,-1.7445,1.71181,-0.314244,-0.85919,1.09481,-1.17754,1.64182,-4.92674,4.36379,1.90572,-0.478741,0.943701,-0.713955,3.28116,1.90119,-1.14899,-0.428792,0.658593,0.892251,-0.422259,0.157504,3.1598,1.12963,0.800961,1.14253,2.18033 } }, { { -1.30378,2.34645,2.18994,2.13789,0.884323,-0.548365,0.144172,2.2943,0.19159,-0.375857,-0.271666,-0.631576,1.79449,-2.41151,1.99647,1.01554,-0.665393,1.22594,-0.699728,0.471043,1.58099,-0.500927,-0.726044,1.33754,0.835102,-1.86937,-1.22183,0.20355,1.42477,0.483058,0.512687,0.634192 } }, { { -1.43756,3.38925,1.0173,1.64294,0.13809,-0.040811,-3.54202,2.0032,0.0620544,-0.728678,0.548828,-0.632022,1.26219,-3.42748,4.28812,1.73712,-0.462246,0.626316,-0.138531,1.88954,1.07689,-2.88091,-0.435965,1.19563,0.606453,-1.21673,-0.839878,1.64032,1.0846,0.510989,0.98712,1.67677 } }, { { -1.41744,4.50889,3.75318,2.29442,0.661895,1.84666,-1.61401,1.71009,-0.308054,-1.01155,1.08747,-1.24392,1.6422,-4.78829,4.43294,1.84818,-0.512208,0.860169,-0.791697,2.7212,1.83621,-1.00646,-0.415109,0.564517,0.933403,-0.820743,0.203932,3.0868,1.17521,0.735135,1.06031,2.13286 } }, { { -1.37214,4.52271,3.70869,2.34204,0.687904,1.78425,-1.70695,1.71542,-0.362855,-0.96981,1.0412,-1.15131,1.64155,-4.89169,4.37931,1.83937,-0.521984,0.931047,-0.739075,2.55367,1.81743,-0.964664,-0.400725,0.56436,0.936157,-0.771741,0.194409,2.97013,1.17858,0.741626,0.96941,2.19455 } }, { { -1.49759,4.54648,3.51147,2.26144,0.682383,1.87732,-1.59002,1.7761,-0.371096,-0.989877,1.03663,-1.25319,1.647,-4.89054,4.31493,1.84011,-0.49996,0.970815,-0.832744,2.81708,1.79991,-1.0513,-0.3598,0.481395,0.9712,-0.8289,0.228946,3.10124,1.26156,0.690572,0.935311,2.38694 } }, { { -1.43114,4.36324,2.70527,2.3671,0.174668,1.75029,-1.0647,1.71338,-0.350738,-0.964126,0.842392,-1.46709,1.41576,-4.87003,4.31087,1.81047,-0.494689,1.10429,-0.561041,1.54623,1.37849,-1.97408,-0.227956,1.08225,0.902863,-1.79199,0.497882,2.76964,1.08581,0.689272,0.846057,1.79219 } }, { { -1.33592,4.54784,4.09841,2.26524,0.767178,1.88075,-1.69909,1.7108,-0.294582,-0.82303,1.01267,-1.31828,1.65878,-4.94432,4.2381,1.8548,-0.485002,0.91752,-0.785439,3.11954,1.58105,-1.02237,-0.378105,0.692392,0.882718,-0.643044,0.149163,3.0576,1.12836,0.74157,1.08909,2.02294 } }, { { 0.937432,1.96636,-0.519319,-1.90381,-2.36196,-2.64511,1.89112,0.716304,-1.69896,0.660922,0.436538,0.765552,-0.49171,0.815552,-0.427242,-0.442689,-3.37428,-0.0676926,2.47249,-2.76556,0.263268,0.71827,1.36828,1.40123,0.920297,0.579379,-0.95027,-0.374426,-0.281251,-0.444428,-2.39069,-1.83128 } }, { { -1.30469,3.95314,2.70595,1.75433,0.474738,0.346495,-2.27369,1.94852,-0.55601,-0.700441,0.434402,-1.09501,1.51878,-3.73293,3.84442,1.71713,-0.419578,1.295,0.171989,2.33946,1.07703,-2.59278,-1.01249,1.14424,0.257702,-1.49717,-0.268213,2.33265,0.951459,0.56554,1.38247,1.31964 } }, { { -1.41963,4.558,3.79248,2.24108,0.815926,1.85404,-1.73587,1.7067,-0.279325,-0.983141,1.12811,-1.30359,1.65363,-4.6774,4.44585,1.82454,-0.514717,0.765522,-0.788319,2.75584,1.7246,-0.806544,-0.43143,0.54965,0.924547,-0.739333,0.18057,3.08764,1.20206,0.719546,1.11519,2.153 } }, { { -1.38618,4.44349,1.74339,2.45864,0.409986,1.11696,-0.725185,1.85659,-0.209493,-0.865055,0.909353,-1.54459,1.59948,-4.22105,4.35372,1.56981,-0.474918,0.720885,-0.1986,2.30341,1.34587,-2.13707,-0.503546,1.13475,0.54531,-1.58955,-0.181264,2.77132,0.895899,0.6722,1.08879,1.893 } }, { { -1.36608,4.3214,2.41065,1.92672,0.184297,0.822457,-2.10329,1.89452,-0.335913,-0.805207,0.643736,-1.37797,1.54727,-3.68823,4.70483,1.59278,-0.463336,1.1248,-0.0639861,2.2594,1.37386,-2.20402,-0.52579,1.31657,0.300825,-1.56485,-0.412459,2.59702,0.656084,0.704501,1.48468,1.25465 } }, { { 1.87467,0.904289,2.14339,2.14535,-1.51659,-2.25427,1.35623,1.21725,1.00335,0.273344,1.72307,0.560871,0.0946994,0.818288,-0.38045,-0.0801961,-0.0973398,0.322278,0.157355,-1.14501,0.592204,0.846485,2.4908,-0.663649,0.63747,1.16597,-0.579264,-0.329395,-1.15796,0.384267,0.175672,-1.75494 } }, { { -1.07666,3.78694,2.64716,1.75735,0.583805,0.97719,-3.00076,1.9646,-0.445927,-0.63162,0.691023,-0.918021,1.41187,-3.82889,4.28506,1.95643,-0.400429,1.37784,0.162588,2.896,1.14332,-2.40647,-0.852183,1.47837,0.283821,-1.12163,-0.894204,2.29912,0.906513,0.476436,0.634039,1.63864 } }, { { -1.29972,4.29134,2.96153,2.42467,0.289999,2.19114,-0.945401,1.71221,-0.314254,-0.974468,1.37098,-1.3684,1.49147,-4.81778,4.55875,1.98266,-0.482395,0.963373,-0.299534,1.2481,1.10415,-2.27053,-0.0455034,1.26344,0.987298,-1.82346,0.301039,2.74774,1.16861,0.700813,0.533816,1.62654 } }, { { 0.658946,-1.21168,1.55544,0.663537,0.388918,-0.25622,-0.310598,-0.961685,-0.103866,-1.24084,0.207724,0.206308,1.01709,0.28535,1.21121,-1.49031,-1.57569,1.70159,1.55393,1.68224,0.907241,2.17003,-0.145682,-0.31769,0.776039,0.663055,0.0217179,0.659355,-1.70149,0.249843,0.530629,-1.1227 } }, { { -1.37258,4.56223,3.56002,2.19814,0.821358,1.86209,-1.65025,1.71536,-0.34039,-1.0161,1.16846,-1.31563,1.63832,-4.8073,4.42607,1.82074,-0.508304,0.916846,-0.798894,2.80683,1.74971,-0.795976,-0.407574,0.522102,0.902625,-0.936325,0.21313,3.07353,1.17071,0.751045,0.994316,1.92703 } }, { { -1.43043,4.25001,2.90742,2.17694,0.219476,1.1299,-1.5283,1.86125,0.0567535,-0.914998,0.674694,-1.42118,1.56667,-4.27233,4.41315,1.59633,-0.495893,1.20995,-0.171834,2.30459,1.08771,-1.89625,-0.593917,1.37214,0.502426,-1.58983,-0.196384,2.53035,0.566426,0.725079,1.19614,1.77091 } }, { { -2.00146,2.6398,1.62541,2.35822,-0.0500478,-0.0405515,-6.02312,2.14669,1.2231,-0.723178,-0.197425,-0.628557,1.56984,-4.29407,4.68041,1.91457,-0.559551,0.773586,0.154436,1.41542,2.06792,0.0293531,-1.14722,1.99406,0.855385,-1.33799,-1.23796,1.30364,0.539369,0.336999,1.26647,1.73132 } } }; blocked_environment->evaluate_function(cars); }); pthread = thread.native_handle(); thread.detach(); } blocked_environment->Lock(); blocked_environment->Step(settings); blocked_environment->DeleteCars(); blocked_environment->Unlock(); } Test* ESBenchmarkSeed1::Create() { return new ESBenchmarkSeed1; } ESBenchmarkSeed1::~ESBenchmarkSeed1() { pthread_cancel(pthread); delete blocked_environment; blocked_environment = nullptr; } static int testIndex = RegisterTest("BEST CARS", "ES SEED 1", ESBenchmarkSeed1::Create);
52a43133980c01041fea2209f911688d000885f0
bd8cd86bc15d0249c1f369363a6b0c652e530f3f
/tools/caffe2ncnn.cpp
0eff756aed3acf33275dc94177c85897406f4adb
[]
no_license
zjd1988/mtcnn_vs2017_based_on_ncnn
85cd8a62be726aacbf44e431fdd0087abd2dd55d
3487fa3a15dad51b152266086a0c84164d9e7392
refs/heads/master
2020-04-12T14:58:18.352752
2019-05-21T10:46:33
2019-05-21T10:46:33
162,566,929
5
2
null
null
null
null
UTF-8
C++
false
false
28,601
cpp
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include <stdio.h> #include <limits.h> #include <fstream> #include <set> #include <limits> #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <google/protobuf/message.h> #include "caffe.pb.h" static inline size_t alignSize(size_t sz, int n) { return (sz + n-1) & -n; } // convert float to half precision floating point static unsigned short float2half(float value) { // 1 : 8 : 23 union { unsigned int u; float f; } tmp; tmp.f = value; // 1 : 8 : 23 unsigned short sign = (tmp.u & 0x80000000) >> 31; unsigned short exponent = (tmp.u & 0x7F800000) >> 23; unsigned int significand = tmp.u & 0x7FFFFF; // fprintf(stderr, "%d %d %d\n", sign, exponent, significand); // 1 : 5 : 10 unsigned short fp16; if (exponent == 0) { // zero or denormal, always underflow fp16 = (sign << 15) | (0x00 << 10) | 0x00; } else if (exponent == 0xFF) { // infinity or NaN fp16 = (sign << 15) | (0x1F << 10) | (significand ? 0x200 : 0x00); } else { // normalized short newexp = exponent + (- 127 + 15); if (newexp >= 31) { // overflow, return infinity fp16 = (sign << 15) | (0x1F << 10) | 0x00; } else if (newexp <= 0) { // underflow if (newexp >= -10) { // denormal half-precision unsigned short sig = (significand | 0x800000) >> (14 - newexp); fp16 = (sign << 15) | (0x00 << 10) | sig; } else { // underflow fp16 = (sign << 15) | (0x00 << 10) | 0x00; } } else { fp16 = (sign << 15) | (newexp << 10) | (significand >> 13); } } return fp16; } static int quantize_weight(float *data, size_t data_length, std::vector<unsigned short>& float16_weights) { float16_weights.resize(data_length); for (size_t i = 0; i < data_length; i++) { float f = data[i]; unsigned short fp16 = float2half(f); float16_weights[i] = fp16; } // magic tag for half-precision floating point return 0x01306B47; } static bool quantize_weight(float *data, size_t data_length, int quantize_level, std::vector<float> &quantize_table, std::vector<unsigned char> &quantize_index) { assert(quantize_level != 0); assert(data != NULL); assert(data_length > 0); if (data_length < static_cast<size_t>(quantize_level)) { fprintf(stderr, "No need quantize,because: data_length < quantize_level"); return false; } quantize_table.reserve(quantize_level); quantize_index.reserve(data_length); // 1. Find min and max value float max_value = std::numeric_limits<float>::min(); float min_value = std::numeric_limits<float>::max(); for (size_t i = 0; i < data_length; ++i) { if (max_value < data[i]) max_value = data[i]; if (min_value > data[i]) min_value = data[i]; } float strides = (max_value - min_value) / quantize_level; // 2. Generate quantize table for (int i = 0; i < quantize_level; ++i) { quantize_table.push_back(min_value + i * strides); } // 3. Align data to the quantized value for (size_t i = 0; i < data_length; ++i) { size_t table_index = int((data[i] - min_value) / strides); table_index = std::min<float>(table_index, quantize_level - 1); float low_value = quantize_table[table_index]; float high_value = low_value + strides; // find a nearest value between low and high value. float targetValue = data[i] - low_value < high_value - data[i] ? low_value : high_value; table_index = int((targetValue - min_value) / strides); table_index = std::min<float>(table_index, quantize_level - 1); quantize_index.push_back(table_index); } return true; } static bool read_proto_from_text(const char* filepath, google::protobuf::Message* message) { std::ifstream fs(filepath, std::ifstream::in); if (!fs.is_open()) { fprintf(stderr, "open failed %s\n", filepath); return false; } google::protobuf::io::IstreamInputStream input(&fs); bool success = google::protobuf::TextFormat::Parse(&input, message); fs.close(); return success; } static bool read_proto_from_binary(const char* filepath, google::protobuf::Message* message) { std::ifstream fs(filepath, std::ifstream::in | std::ifstream::binary); if (!fs.is_open()) { fprintf(stderr, "open failed %s\n", filepath); return false; } google::protobuf::io::IstreamInputStream input(&fs); google::protobuf::io::CodedInputStream codedstr(&input); codedstr.SetTotalBytesLimit(INT_MAX, INT_MAX / 2); bool success = message->ParseFromCodedStream(&codedstr); fs.close(); return success; } int main(int argc, char** argv) { if (!(argc == 3 || argc == 5 || argc == 6)) { fprintf(stderr, "Usage: %s [caffeproto] [caffemodel] [ncnnproto] [ncnnbin] [quantizelevel]\n", argv[0]); return -1; } const char* caffeproto = argv[1]; const char* caffemodel = argv[2]; const char* ncnn_prototxt = argc >= 5 ? argv[3] : "ncnn.proto"; const char* ncnn_modelbin = argc >= 5 ? argv[4] : "ncnn.bin"; const char* quantize_param = argc == 6 ? argv[5] : "0"; int quantize_level = atoi(quantize_param); if (quantize_level != 0 && quantize_level != 256 && quantize_level != 65536) { fprintf(stderr, "%s: only support quantize level = 0, 256, or 65536", argv[0]); return -1; } caffe::NetParameter proto; caffe::NetParameter net; // load bool s0 = read_proto_from_text(caffeproto, &proto); if (!s0) { fprintf(stderr, "read_proto_from_text failed\n"); return -1; } bool s1 = read_proto_from_binary(caffemodel, &net); if (!s1) { fprintf(stderr, "read_proto_from_binary failed\n"); return -1; } FILE* pp = fopen(ncnn_prototxt, "wb"); FILE* bp = fopen(ncnn_modelbin, "wb"); // rename mapping for identical bottom top style std::map<std::string, std::string> blob_name_decorated; // bottom blob reference std::map<std::string, int> bottom_reference; // global definition line // [layer count] [blob count] int layer_count = proto.layer_size(); std::set<std::string> blob_names; for (int i=0; i<layer_count; i++) { const caffe::LayerParameter& layer = proto.layer(i); for (int j=0; j<layer.bottom_size(); j++) { std::string blob_name = layer.bottom(j); if (blob_name_decorated.find(blob_name) != blob_name_decorated.end()) { blob_name = blob_name_decorated[blob_name]; } blob_names.insert(blob_name); if (bottom_reference.find(blob_name) == bottom_reference.end()) { bottom_reference[blob_name] = 1; } else { bottom_reference[blob_name] = bottom_reference[blob_name] + 1; } } if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0)) { std::string blob_name = layer.top(0) + "_" + layer.name(); blob_name_decorated[layer.top(0)] = blob_name; blob_names.insert(blob_name); } else { for (int j=0; j<layer.top_size(); j++) { std::string blob_name = layer.top(j); blob_names.insert(blob_name); } } } // remove bottom_reference entry with reference equals to one int splitncnn_blob_count = 0; std::map<std::string, int>::iterator it = bottom_reference.begin(); while (it != bottom_reference.end()) { if (it->second == 1) { bottom_reference.erase(it++); } else { splitncnn_blob_count += it->second; // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second); ++it; } } fprintf(pp, "%lu %lu\n", layer_count + bottom_reference.size(), blob_names.size() + splitncnn_blob_count); // populate blob_name_decorated.clear(); int internal_split = 0; for (int i=0; i<layer_count; i++) { const caffe::LayerParameter& layer = proto.layer(i); // layer definition line, repeated // [type] [name] [bottom blob count] [top blob count] [bottom blobs] [top blobs] [layer specific params] fprintf(pp, "%-16s %-16s %d %d", layer.type().c_str(), layer.name().c_str(), layer.bottom_size(), layer.top_size()); for (int j=0; j<layer.bottom_size(); j++) { std::string blob_name = layer.bottom(j); if (blob_name_decorated.find(layer.bottom(j)) != blob_name_decorated.end()) { blob_name = blob_name_decorated[layer.bottom(j)]; } if (bottom_reference.find(blob_name) != bottom_reference.end()) { int refidx = bottom_reference[blob_name] - 1; bottom_reference[blob_name] = refidx; char splitsuffix[256]; sprintf(splitsuffix, "_splitncnn_%d", refidx); blob_name = blob_name + splitsuffix; } fprintf(pp, " %s", blob_name.c_str()); } // decorated if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0)) { std::string blob_name = layer.top(0) + "_" + layer.name(); blob_name_decorated[layer.top(0)] = blob_name; fprintf(pp, " %s", blob_name.c_str()); } else { for (int j=0; j<layer.top_size(); j++) { std::string blob_name = layer.top(j); fprintf(pp, " %s", blob_name.c_str()); } } // find blob binary by layer name int netidx; for (netidx=0; netidx<net.layer_size(); netidx++) { if (net.layer(netidx).name() == layer.name()) { break; } } // layer specific params if (layer.type() == "BatchNorm") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& mean_blob = binlayer.blobs(0); const caffe::BlobProto& var_blob = binlayer.blobs(1); fprintf(pp, " %d", (int)mean_blob.data_size()); const caffe::BatchNormParameter& batch_norm_param = layer.batch_norm_param(); float eps = batch_norm_param.eps(); std::vector<float> ones(mean_blob.data_size(), 1.f); fwrite(ones.data(), sizeof(float), ones.size(), bp);// slope if (binlayer.blobs_size() < 3) { fwrite(mean_blob.data().data(), sizeof(float), mean_blob.data_size(), bp); float tmp; for (int j=0; j<var_blob.data_size(); j++) { tmp = var_blob.data().data()[j] + eps; fwrite(&tmp, sizeof(float), 1, bp); } } else { float scale_factor = 1 / binlayer.blobs(2).data().data()[0]; // premultiply scale_factor to mean and variance float tmp; for (int j=0; j<mean_blob.data_size(); j++) { tmp = mean_blob.data().data()[j] * scale_factor; fwrite(&tmp, sizeof(float), 1, bp); } for (int j=0; j<var_blob.data_size(); j++) { tmp = var_blob.data().data()[j] * scale_factor + eps; fwrite(&tmp, sizeof(float), 1, bp); } } std::vector<float> zeros(mean_blob.data_size(), 0.f); fwrite(zeros.data(), sizeof(float), zeros.size(), bp);// bias } else if (layer.type() == "Convolution") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& weight_blob = binlayer.blobs(0); const caffe::ConvolutionParameter& convolution_param = layer.convolution_param(); fprintf(pp, " %d %d %d %d %d %d %d", convolution_param.num_output(), convolution_param.kernel_size(0), convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1, convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1, convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0, convolution_param.bias_term(), weight_blob.data_size()); for (int j = 0; j < binlayer.blobs_size(); j++) { int quantize_tag = 0; const caffe::BlobProto& blob = binlayer.blobs(j); std::vector<float> quantize_table; std::vector<unsigned char> quantize_index; std::vector<unsigned short> float16_weights; // we will not quantize the bias values if (j == 0 && quantize_level != 0) { if (quantize_level == 256) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index); } else if (quantize_level == 65536) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights); } } // write quantize tag first if (j == 0) fwrite(&quantize_tag, sizeof(int), 1, bp); if (quantize_tag) { int p0 = ftell(bp); if (quantize_level == 256) { // write quantize table and index fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp); fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp); } else if (quantize_level == 65536) { fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp); } // padding to 32bit align int nwrite = ftell(bp) - p0; int nalign = alignSize(nwrite, 4); unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00}; fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp); } else { // write original data fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } } else if (layer.type() == "Crop") { const caffe::CropParameter& crop_param = layer.crop_param(); int num_offset = crop_param.offset_size(); int woffset = (num_offset == 2) ? crop_param.offset(0) : 0; int hoffset = (num_offset == 2) ? crop_param.offset(1) : 0; fprintf(pp, " %d %d", woffset, hoffset); } else if (layer.type() == "Deconvolution") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& weight_blob = binlayer.blobs(0); const caffe::ConvolutionParameter& convolution_param = layer.convolution_param(); fprintf(pp, " %d %d %d %d %d %d %d", convolution_param.num_output(), convolution_param.kernel_size(0), convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1, convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1, convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0, convolution_param.bias_term(), weight_blob.data_size()); int quantized_weight = 0; fwrite(&quantized_weight, sizeof(int), 1, bp); // reorder weight from inch-outch to outch-inch int ksize = convolution_param.kernel_size(0); int num_output = convolution_param.num_output(); int num_input = weight_blob.data_size() / (ksize * ksize) / num_output; const float* weight_data_ptr = weight_blob.data().data(); for (int k=0; k<num_output; k++) { for (int j=0; j<num_input; j++) { fwrite(weight_data_ptr + (j*num_output + k) * ksize * ksize, sizeof(float), ksize * ksize, bp); } } for (int j=1; j<binlayer.blobs_size(); j++) { const caffe::BlobProto& blob = binlayer.blobs(j); fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } else if (layer.type() == "Eltwise") { const caffe::EltwiseParameter& eltwise_param = layer.eltwise_param(); int coeff_size = eltwise_param.coeff_size(); fprintf(pp, " %d %d", (int)eltwise_param.operation(), coeff_size); for (int j=0; j<coeff_size; j++) { fprintf(pp, " %f", eltwise_param.coeff(j)); } } else if (layer.type() == "InnerProduct") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& weight_blob = binlayer.blobs(0); const caffe::InnerProductParameter& inner_product_param = layer.inner_product_param(); fprintf(pp, " %d %d %d", inner_product_param.num_output(), inner_product_param.bias_term(), weight_blob.data_size()); for (int j=0; j<binlayer.blobs_size(); j++) { int quantize_tag = 0; const caffe::BlobProto& blob = binlayer.blobs(j); std::vector<float> quantize_table; std::vector<unsigned char> quantize_index; std::vector<unsigned short> float16_weights; // we will not quantize the bias values if (j == 0 && quantize_level != 0) { if (quantize_level == 256) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index); } else if (quantize_level == 65536) { quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights); } } // write quantize tag first if (j == 0) fwrite(&quantize_tag, sizeof(int), 1, bp); if (quantize_tag) { int p0 = ftell(bp); if (quantize_level == 256) { // write quantize table and index fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp); fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp); } else if (quantize_level == 65536) { fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp); } // padding to 32bit align int nwrite = ftell(bp) - p0; int nalign = alignSize(nwrite, 4); unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00}; fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp); } else { // write original data fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } } else if (layer.type() == "Input") { const caffe::InputParameter& input_param = layer.input_param(); const caffe::BlobShape& bs = input_param.shape(0); for (int j=1; j<std::min((int)bs.dim_size(), 4); j++) { fprintf(pp, " %lld", bs.dim(j)); } for (int j=bs.dim_size(); j<4; j++) { fprintf(pp, " -233"); } } else if (layer.type() == "LRN") { const caffe::LRNParameter& lrn_param = layer.lrn_param(); fprintf(pp, " %d %d %.8f %.8f", lrn_param.norm_region(), lrn_param.local_size(), lrn_param.alpha(), lrn_param.beta()); } else if (layer.type() == "MemoryData") { const caffe::MemoryDataParameter& memory_data_param = layer.memory_data_param(); fprintf(pp, " %d %d %d", memory_data_param.channels(), memory_data_param.width(), memory_data_param.height()); } else if (layer.type() == "Pooling") { const caffe::PoolingParameter& pooling_param = layer.pooling_param(); fprintf(pp, " %d %d %d %d %d", pooling_param.pool(), pooling_param.kernel_size(), pooling_param.stride(), pooling_param.pad(), pooling_param.has_global_pooling() ? pooling_param.global_pooling() : 0); } else if (layer.type() == "Power") { const caffe::PowerParameter& power_param = layer.power_param(); fprintf(pp, " %f %f %f", power_param.power(), power_param.scale(), power_param.shift()); } else if (layer.type() == "PReLU") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& slope_blob = binlayer.blobs(0); fprintf(pp, " %d", slope_blob.data_size()); fwrite(slope_blob.data().data(), sizeof(float), slope_blob.data_size(), bp); } else if (layer.type() == "Proposal") { const caffe::PythonParameter& python_param = layer.python_param(); int feat_stride = 16; sscanf(python_param.param_str().c_str(), "'feat_stride': %d", &feat_stride); int base_size = 16; // float ratio; // float scale; int pre_nms_topN = 6000; int after_nms_topN = 5; float nms_thresh = 0.7; int min_size = 16; fprintf(pp, " %d %d %d %d %f %d", feat_stride, base_size, pre_nms_topN, after_nms_topN, nms_thresh, min_size); } else if (layer.type() == "ReLU") { const caffe::ReLUParameter& relu_param = layer.relu_param(); fprintf(pp, " %f", relu_param.negative_slope()); } else if (layer.type() == "Reshape") { const caffe::ReshapeParameter& reshape_param = layer.reshape_param(); const caffe::BlobShape& bs = reshape_param.shape(); for (int j=1; j<std::min((int)bs.dim_size(), 4); j++) { fprintf(pp, " %lld", bs.dim(j)); } for (int j=bs.dim_size(); j<4; j++) { fprintf(pp, " -233"); } } else if (layer.type() == "ROIPooling") { const caffe::ROIPoolingParameter& roi_pooling_param = layer.roi_pooling_param(); fprintf(pp, " %d %d %.8f", roi_pooling_param.pooled_w(), roi_pooling_param.pooled_h(), roi_pooling_param.spatial_scale()); } else if (layer.type() == "Scale") { const caffe::LayerParameter& binlayer = net.layer(netidx); const caffe::BlobProto& weight_blob = binlayer.blobs(0); const caffe::ScaleParameter& scale_param = layer.scale_param(); fprintf(pp, " %d %d", (int)weight_blob.data_size(), scale_param.bias_term()); for (int j=0; j<binlayer.blobs_size(); j++) { const caffe::BlobProto& blob = binlayer.blobs(j); fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp); } } else if (layer.type() == "Slice") { const caffe::SliceParameter& slice_param = layer.slice_param(); if (slice_param.has_slice_dim()) { int num_slice = layer.top_size(); fprintf(pp, " %d", num_slice); for (int j=0; j<num_slice; j++) { fprintf(pp, " -233"); } } else { int num_slice = slice_param.slice_point_size() + 1; fprintf(pp, " %d", num_slice); int prev_offset = 0; for (int j=0; j<num_slice; j++) { int offset = slice_param.slice_point(j); fprintf(pp, " %d", offset - prev_offset); prev_offset = offset; } fprintf(pp, " -233"); } } else if (layer.type() == "Threshold") { const caffe::ThresholdParameter& threshold_param = layer.threshold_param(); fprintf(pp, " %f", threshold_param.threshold()); } fprintf(pp, "\n"); // add split layer if top reference larger than one if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0)) { std::string blob_name = blob_name_decorated[layer.top(0)]; if (bottom_reference.find(blob_name) != bottom_reference.end()) { int refcount = bottom_reference[blob_name]; if (refcount > 1) { char splitname[256]; sprintf(splitname, "splitncnn_%d", internal_split); fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount); fprintf(pp, " %s", blob_name.c_str()); for (int j=0; j<refcount; j++) { fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j); } fprintf(pp, "\n"); internal_split++; } } } else { for (int j=0; j<layer.top_size(); j++) { std::string blob_name = layer.top(j); if (bottom_reference.find(blob_name) != bottom_reference.end()) { int refcount = bottom_reference[blob_name]; if (refcount > 1) { char splitname[256]; sprintf(splitname, "splitncnn_%d", internal_split); fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount); fprintf(pp, " %s", blob_name.c_str()); for (int j=0; j<refcount; j++) { fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j); } fprintf(pp, "\n"); internal_split++; } } } } } fclose(pp); fclose(bp); return 0; }
ffb2fcdbae14fb0cd8739ebd2217472f2ebafa7d
8d39f509abf62a0947f3e9dd11a1bc02665b609e
/comp2012h/csd_only/lecture/7-class/Emp_codes/static.cpp
2293bea9c145f7f09d3baa86145bde7afd230ab3
[]
no_license
clcheungac/clcheungac.github.io
c77c8a0c5b2261cf37602ce644c143e266184277
815885f2af89ef3ac32fad607786c6e8fa47c6e0
refs/heads/master
2021-01-10T13:08:37.959427
2018-12-30T13:44:20
2018-12-30T13:44:20
48,602,655
1
0
null
null
null
null
UTF-8
C++
false
false
2,608
cpp
// Fig. 10.23: fig10_23.cpp // static data member tracking the number of objects of a class. #include <iostream> using std::cout; using std::endl; #include "SEmployee.h" // Employee class definition int main() { // use class name and binary scope resolution operator to // access static number function getCount cout << "Number of employees before instantiation of any objects is " << Employee::getCount() << endl; // use class name // use new to dynamically create two new Employees // operator new also calls the object's constructor Employee *e1Ptr = new Employee( "Susan", "Baker" ); Employee *e2Ptr = new Employee( "Robert", "Jones" ); // call getCount on first Employee object cout << "Number of employees after objects are instantiated is " << e1Ptr->getCount() << " (same as calling Employee::getCount() = " << Employee::getCount() <<")"; cout << "\n\nEmployee 1: " << e1Ptr->getFirstName() << " " << e1Ptr->getLastName() << "\nEmployee 2: " << e2Ptr->getFirstName() << " " << e2Ptr->getLastName() << "\n\n"; delete e1Ptr; // deallocate memory e1Ptr = 0; // disconnect pointer from free-store space delete e2Ptr; // deallocate memory e2Ptr = 0; // disconnect pointer from free-store space // no objects exist, so call static member function getCount again // using the class name and the binary scope resolution operator cout << "Number of employees after objects are deleted is " << Employee::getCount() << endl; return 0; } // end main /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
199f1967544ea0551c4caf575dcb5a6050442f1a
24068d8b6d306b17beb5c99ca1c113b972929764
/SocialGameOpenGLApplication/PrologEngine.h
e354079c6343cdf7f3c142c26f2b913cabb9a404
[]
no_license
brunoflavio-com/engenius
1a33a772d691fd4d601957675de37edd582d2c2e
0164eefdf59fd8c36ec04b285cdce58bc9683687
refs/heads/master
2020-12-31T02:48:44.104432
2014-01-16T14:04:53
2014-01-16T14:04:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
298
h
#pragma once #include <SWI-cpp.h> class PrologEngine { public: static PrologEngine& getInstance(); PlEngine * getEngine(); private: PrologEngine(); ~PrologEngine(); PlEngine * swiprolog; //disallow copies. PrologEngine(PrologEngine const&); void operator=(PrologEngine const&); };
beda539299351df342cb8150329bafea3b430413
d85f2df596f794c92d1a36ffa3d99c389b30e797
/ArquiSoftSolid/ClienteCredito.cpp
d6d7d05bc655bba289fdf7f132a19c312e0db451
[]
no_license
kevdie/SOLID
057717e683e11987d4d20b647c972721ee726a26
9cc2903bf243ff0e6f73e5a4f070737273a8361f
refs/heads/master
2022-12-28T08:08:26.816722
2020-10-13T16:28:14
2020-10-13T16:28:14
303,761,529
0
0
null
null
null
null
UTF-8
C++
false
false
754
cpp
#include "ClienteCredito.h" int ClienteCredito::getTotalPagos() { return totalPagos; } void ClienteCredito::setTotalPagos(int totalPagos) { this->totalPagos = totalPagos; } int ClienteCredito::getPagosRealizados() { return pagosRealizados; } void ClienteCredito::setPagosRealizados(int pagosRealizados) { this->pagosRealizados = pagosRealizados; } int ClienteCredito::getMontoTotal() { return montoTotal; } void ClienteCredito::setMontoTotal(int montoTotal) { this->montoTotal = montoTotal; } void ClienteCredito::mostrar() { cout << "CLIENTE A CREDITO" << endl; Cliente::mostrar(); cout << "Total Pagos: " << totalPagos << endl; cout << "Pagos Realizados: " << pagosRealizados << endl; cout << "Monto total: " << montoTotal << endl; }
7070cc477d92c7681b725e465ba6f6e6e7f13add
775acebaa6559bb12365c930330a62365afb0d98
/source/sdksamples/gotolasttextedit/IGTTxtEdtUtils.h
94df381a12a98ef4dabcfb5b47babba9c530bce1
[]
no_license
Al-ain-Developers/indesing_plugin
3d22c32d3d547fa3a4b1fc469498de57643e9ee3
36a09796b390e28afea25456b5d61597b20de850
refs/heads/main
2023-08-14T13:34:47.867890
2021-10-05T07:57:35
2021-10-05T07:57:35
339,970,603
1
1
null
2021-10-05T07:57:36
2021-02-18T07:33:40
C++
UTF-8
C++
false
false
1,584
h
//======================================================================================== // // $File: //depot/devtech/16.0.x/plugin/source/sdksamples/gotolasttextedit/IGTTxtEdtUtils.h $ // // Owner: Adobe Developer Technologies // // $Author: pmbuilder $ // // $DateTime: 2020/11/06 13:08:29 $ // // $Revision: #2 $ // // $Change: 1088580 $ // // Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance // with the terms of the Adobe license agreement accompanying it. If you have received // this file from a source other than Adobe, then your use, modification, or // distribution of it requires the prior written permission of Adobe. // //======================================================================================== #ifndef _IGTTxtEdtUtils_ #define _IGTTxtEdtUtils_ #include "GTTxtEdtID.h" class ISelectionManager; /** Utility interface for the GoToText plugin @ingroup gotolasttextedit */ class IGTTxtEdtUtils : public IPMUnknown { public: /** kDefaultIID */ enum { kDefaultIID = IID_IGTTXTEDTUTILS }; /** Activates the specified story, placing the text caret at the specified edit point. @param pSelectionManager IN the selection manager. @param storyUIDRef IN the story to be activated. @param storyIndex IN the index at which the story is to be activated. */ virtual void ActivateStory(ISelectionManager* pSelectionManager, UIDRef storyUIDRef, int32 storyIndex=0) = 0; }; #endif // _IGTTxtEdtUtils_
4ab5076d09392144a7e0b02e9ba61e504671668d
8739fbb376ece424772c617874affb1040739916
/stencils/TurbViscosityBufferFillStencil.cpp
8b13900a8ec7a03bab83d2a3843aae833d1cc416
[]
no_license
gasteigerjo/turbulent
6d34c0aeba0ff797d0d327f50268dc791e405f94
ed61a9503312c99abfe5ffc577f398f7b549681d
refs/heads/master
2022-03-12T07:43:28.750274
2016-01-25T14:38:52
2016-01-25T14:38:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,231
cpp
#include "TurbViscosityBufferFillStencil.h" TurbViscosityBufferFillStencil::TurbViscosityBufferFillStencil(const Parameters & parameters, FLOAT * turbViscLeft, FLOAT * turbViscRight, FLOAT * turbViscBottom, FLOAT * turbViscTop, int lowOffset) : ScalarBufferFillStencil<TurbulentFlowField>(parameters,turbViscLeft,turbViscRight,turbViscBottom,turbViscTop,lowOffset) {} TurbViscosityBufferFillStencil::TurbViscosityBufferFillStencil(const Parameters & parameters, FLOAT * turbViscLeft, FLOAT * turbViscRight, FLOAT * turbViscBottom, FLOAT * turbViscTop, FLOAT * turbViscFront, FLOAT * turbViscBack, int lowOffset) : ScalarBufferFillStencil<TurbulentFlowField>(parameters,turbViscLeft,turbViscRight,turbViscBottom,turbViscTop,turbViscFront,turbViscBack,lowOffset) {} // 2D problem FLOAT & TurbViscosityBufferFillStencil::getScalar( TurbulentFlowField & turbFlowField, int i, int j ){ return turbFlowField.getTurbViscosity().getScalar(i,j); } // 3D problem FLOAT & TurbViscosityBufferFillStencil::getScalar( TurbulentFlowField & turbFlowField, int i, int j, int k ){ return turbFlowField.getTurbViscosity().getScalar(i,j,k); }
b05b768585a2da7932ef59055e8fbfd2723bd683
f77c9ed429f4bdc903815fccb5d5efcdd3110a7f
/RovController/Sensors/ImuSensor.cpp
6935589c85601723cecb982475254c8dc2bbc33c
[]
no_license
lawrence-tech-rov-team/Rov-Controller
1e348c780ec854a06c6862b636a5e1f91379e123
0ac227c88e6630d933af16d1f5e7ebdf6cfa9b69
refs/heads/master
2020-12-02T23:46:59.091308
2020-05-04T20:39:22
2020-05-04T20:39:22
231,159,016
1
0
null
null
null
null
UTF-8
C++
false
false
1,733
cpp
/* * ImuSensor.cpp * * Created: 2/19/2020 8:49:46 PM * Author: zcarey */ #include "ImuSensor.h" #include "../Robot.h" ImuSensor::ImuSensor(const uint8_t TempId, const uint8_t AccelId, const uint8_t MagId, const uint8_t GyroId, const uint8_t EulerId, const uint8_t LinearId, const uint8_t GravityId, const uint8_t QuatId) : imu(55, 0x28), tempId(TempId), accelId(AccelId), magId(MagId), gyroId(GyroId), eulerId(EulerId), linearId(LinearId), gravityId(GravityId), quatId(QuatId) { } bool ImuSensor::begin(){ return rov.RegisterDevice(tempId, this) && rov.RegisterDevice(accelId, this) && rov.RegisterDevice(magId, this) && rov.RegisterDevice(gyroId, this) && rov.RegisterDevice(eulerId, this) && rov.RegisterDevice(linearId, this) && rov.RegisterDevice(gravityId, this) && rov.RegisterDevice(quatId, this) && imu.begin(); } void ImuSensor::Update(uint8_t* buffer){ } void ImuSensor::ReadRegisterRequested(uint8_t id, uint8_t* buffer){ if(id == tempId){ buffer[0] = imu.getTemp(); SendCommand(id, 1); }else if(id == accelId) { SendCommand(id, imu.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER, buffer)); }else if(id == magId){ SendCommand(id, imu.getVector(Adafruit_BNO055::VECTOR_MAGNETOMETER, buffer)); }else if(id == gyroId){ SendCommand(id, imu.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE, buffer)); }else if(id == eulerId){ SendCommand(id, imu.getVector(Adafruit_BNO055::VECTOR_EULER, buffer)); }else if(id == linearId){ SendCommand(id, imu.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL, buffer)); }else if(id == gravityId){ SendCommand(id, imu.getVector(Adafruit_BNO055::VECTOR_GRAVITY, buffer)); }else if(id == quatId){ SendCommand(id, imu.getQuat(buffer)); } }
7b4f9d04098d45c78028e60b4dce3894f976405d
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/SOC/2011/simd/libs/simd/mini_nt2/nt2/include/constants/eps_related.hpp
4c6c82567432698aaf5681e0c840957770bcc788
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
185
hpp
#ifndef NT2_INCLUDE_CONSTANTS_EPS_RELATED_HPP_INCLUDED #define NT2_INCLUDE_CONSTANTS_EPS_RELATED_HPP_INCLUDED #include <nt2/toolbox/constant/include/constants/eps_related.hpp> #endif
4f617d1a7368aee5e091f343751c24cc52f80796
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir13714/dir14735/file14818.cpp
5d3d12d505fb8587fe2dca4a7aa76019fd9febe3
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file14818 #error "macro file14818 must be defined" #endif static const char* file14818String = "file14818";
529d86e6767550da9d1dd9a8261c6098364d2487
5e1cf134e9be0c30ab0f1175e578ebc2917eab9e
/PrimeC++/beforeJan17_2016/callPrivate.cpp
9c6d0f6511a82ced4f4b2ea35a7c933d7135c19d
[]
no_license
LiehuoChen/CPLUSPLUS_STUDY
d0d1339113d8ff34a1bcb4dec7db4ecd3f22c291
2cda080b1ab7893db4145542db69ca2b1c03bc48
refs/heads/master
2021-01-10T16:57:42.639576
2016-01-17T23:54:37
2016-01-17T23:54:37
49,798,875
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
#include<iostream> using namespace std; class Base { public: virtual int fun(int i) { cout << "Base::fun(int i) called" << endl; } }; class Derived: public Base { private: int fun(int x) { cout << "Derived::fun(int x) called" << endl; } }; int main() { //Derived *ptrD = new Derived; //ptrD->fun(10); Base *ptr = new Derived; ptr->fun(10); return 0; }
b4edda58fa62b56b648dea082ab080f138c0bf6a
ea92cb09d832e11ea8b1e74d35326091fb6bbaa6
/demos/d/src/ActivatingCollisionAlgorithm.h
ab0351f6c2d109eb2bc77eeffd836cbf8d53dc64
[ "MIT" ]
permissive
DesignEngrLab/StabilityStudy
3929b704b7365b839a64c34b6273ee1f5e637fba
8ed7685621c76dc74816855a6cf370317fe401fb
refs/heads/master
2021-01-16T23:03:25.276541
2016-10-06T23:59:23
2016-10-06T23:59:23
70,174,035
1
0
null
null
null
null
UTF-8
C++
false
false
241
h
#pragma once #include "CollisionAlgorithm.h" namespace BulletSharp { public ref class ActivatingCollisionAlgorithm abstract : CollisionAlgorithm { internal: ActivatingCollisionAlgorithm(btActivatingCollisionAlgorithm* native); }; };
26b7f5021acb3bd395f22f33e76094533bfd75f4
b643341b408b090e9f83e21713e14fa8b7508a80
/Source/artoolkit6-dependency/include/AR6/ARTrackableSquare.h
4def59bcdab3852404f3d7e96e36172bcc597fcc
[]
no_license
ThorstenBux/artoolkit6-calibration-android
a911fdf15efd00dbba2e95f2ae654262ced9c403
f19b3a707bb7ceef37eccb54ebd15205f1637954
refs/heads/master
2021-07-11T12:06:13.662950
2017-10-13T09:15:34
2017-10-13T09:15:34
105,212,852
1
2
null
2017-09-29T00:44:32
2017-09-29T00:44:31
null
UTF-8
C++
false
false
3,218
h
/* * ARTrackableSquare.h * ARToolKit6 * * This file is part of ARToolKit. * * ARToolKit is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ARToolKit is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with ARToolKit. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, and to * copy and distribute the resulting executable under terms of your choice, * provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module * which is neither derived from nor based on this library. If you modify this * library, you may extend this exception to your version of the library, but you * are not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. * * Copyright 2015-2016 Daqri, LLC. * Copyright 2011-2015 ARToolworks, Inc. * * Author(s): Julian Looser, Philip Lamb * */ #ifndef ARMARKERSQUARE_H #define ARMARKERSQUARE_H #include <AR6/ARTrackable.h> #define AR_PATTERN_TYPE_TEMPLATE 0 #define AR_PATTERN_TYPE_MATRIX 1 /** * Single marker type of ARTrackable. */ class ARTrackableSquare : public ARTrackable { private: bool m_loaded; protected: ARPattHandle *m_arPattHandle; ARdouble m_width; ARdouble m_cf; ARdouble m_cfMin; bool unload(); public: int patt_id; ///< Unique pattern ID provided by ARToolKit int patt_type; ARTrackableSquare(); ~ARTrackableSquare(); bool useContPoseEstimation; ARdouble getConfidence(); ARdouble getConfidenceCutoff(); void setConfidenceCutoff(ARdouble value); bool initWithPatternFile(const char* path, ARdouble width, ARPattHandle *arPattHandle); bool initWithPatternFromBuffer(const char* buffer, ARdouble width, ARPattHandle *arPattHandle); bool initWithBarcode(int barcodeID, ARdouble width); /** * Updates the marker with new tracking info. * Then calls ARTrackable::update() * @param markerInfo Array containing detected marker information * @param markerNum Number of items in the array * @param ar3DHandle AR3DHandle used to extract marker pose. */ bool updateWithDetectedMarkers(ARMarkerInfo* markerInfo, int markerNum, AR3DHandle *ar3DHandle); bool updateWithDetectedMarkersStereo(ARMarkerInfo* markerInfoL, int markerNumL, ARMarkerInfo* markerInfoR, int markerNumR, AR3DStereoHandle *handle, ARdouble transL2R[3][4]); }; #endif // !ARMARKERSQUARE_H
2bf43c6e97fdb10f48d140bc1d60a8e9cd8d8fb3
3a3ed2c22e418467b9a54863e810116d8f3e5f0a
/src/SGIEngine/Timer.h
92efe51c90ffcba116870adf35d1e02cac89e737
[]
no_license
ArnauBigas/SGI-Engine
dbb96d99075fb481e12a64eef4efd7e7752fc808
882ed9647d9be104b5706fdeeed44946f9d16587
refs/heads/master
2021-05-31T13:04:32.336605
2016-05-06T20:22:19
2016-05-06T20:22:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
239
h
#ifndef TIMER_H #define TIMER_H class Timer { public: void start(); void stop(); void reset(); unsigned long getTime(); private: bool running; unsigned long startms; unsigned long ms; }; #endif /* TIMER_H */
9174567b2421b12339f04e4ebff0df7e18b7bfc7
e315a4322fcfb050215c24ac0e8f786138dec096
/HW10 10.cpp
0e088fc9892133fbdb5614bcb06625813df25154
[]
no_license
HasaliEdirisinghe/Homework-10
486460d2f5b581efc67b715a18c5b11fa55189fc
226e7198bcefca066a8bc36ffdd724624d7a400f
refs/heads/main
2023-08-15T04:22:26.486341
2021-10-23T16:55:01
2021-10-23T16:55:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,155
cpp
#include<iostream> #include<string.h> using namespace std; // A program to merge two files and write it in a new file. int main() { FILE *file1, *file2, *fnew; char current, fname1[20], fname2[20], fname3[30]; //getting user inputs cout << "Input the 1st file name: "; cin >> fname1; cout << "Input the 2nd file name: "; cin >> fname2; cout << "Input the new file name where to merge the above two files: "; cin >> fname1; //open files to read file1 = fopen(fname1, "r"); file2 = fopen(fname2, "r"); //check for errors of existence if(file1==NULL || file2==NULL) { printf(" File does not exist or error in opening...!!\n"); exit(EXIT_FAILURE); } //open a file to merge fnew=fopen(fname3, "w"); //check for errors of existence if(fnew == NULL) { printf(" File does not exist or error in opening...!!\n"); exit(EXIT_FAILURE); } //merging while((current=fgetc(file1)) != EOF) { fputc(current, fnew); } while((current=fgetc(file2)) != EOF) { fputc(current, fnew); } //display cout << "The two files merged into " << fname3 << " successfully...!!"; fclose(file1); fclose(file2); fclose(fnew); }
c1f1e3066b063d06b3689ef4b438b9fa39f00b34
0a00b5f68d68c9648dc2bb118210512bc07ced33
/sublime vala/declunchtime.cpp
716c0c02128a4e4c30d246b146e7e1476afed8e7
[]
no_license
Anugrahchaturvedi/my_code_cpp02
98ad9e8edcf6847ca50d558b1a640d50684b20fa
91b4e0d23264c1f11c4033bfbdfd5c95e94fd853
refs/heads/master
2023-05-31T23:42:13.009480
2021-06-01T18:22:29
2021-06-01T18:22:29
372,919,929
0
0
null
null
null
null
UTF-8
C++
false
false
336
cpp
#include<bits/stdc++.h> using namespace std ; int main() { long long int t , n , k; int sum =0 , arr[n]; //cin >> t ; //while (t--) //{ cin >> n >>k; //cin >>k; for (int i =0 ; i< n ;i++) { cin >>arr[i]; } for (int i=0; i< n ; i++) { sum=sum + arr[i]; } cout << "sum id "<<sum << endl; //} return 0; }
2afdfb525ef59c8d35a41a3fc715dee015ccea5c
8929e7535533d43e62f0dde3d384ee46cc28e3c7
/AnimationManager/AnimationModel.cpp
de7eee0b1a74c198c6a4c9d0db161db7d38c4bab
[]
no_license
Nakio195/OSSAM-Editor
4e2b2311a278d3042f7774d8a53fff5846ce2d73
bcaf2fc2cab28a38fd723e48a79eb886d7a61d59
refs/heads/master
2023-03-08T22:52:08.781597
2023-03-03T18:04:43
2023-03-03T18:04:43
86,177,811
0
0
null
null
null
null
UTF-8
C++
false
false
7,974
cpp
#include "AnimationModel.h" #include <QJsonDocument> #include <QJsonArray> #include <QFile> #include <QMessageBox> AnimationModel::AnimationModel(AssetModel *assets, QObject *parent) : QAbstractTableModel(parent), mAssets(assets) { } QVariant AnimationModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole) { switch(section) { case AnimationModel::ID: return QVariant(QString("ID")); case AnimationModel::Name: return QVariant(QString("Nom")); case AnimationModel::TextureUID: return QVariant(QString("Texture ID")); case AnimationModel::FrameCount: return QVariant(QString("Images")); case AnimationModel::RectWidth: return QVariant(QString("Largeur")); case AnimationModel::RectHeight: return QVariant(QString("Hauteur")); case AnimationModel::Period: return QVariant(QString("Periode")); case AnimationModel::TimerMode: return QVariant(QString("Timer Mode")); } } } return QVariant(); } int AnimationModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return mAnimations.count(); // FIXME: Implement me! } int AnimationModel::columnCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return 8; // FIXME: Implement me! } void AnimationModel::sort(int column, Qt::SortOrder order) { layoutAboutToBeChanged(); if(column == ID) { if(order == Qt::AscendingOrder) qSort(mAnimations.begin(), mAnimations.end(), [] (const Animation& a, const Animation& b) { return a.getUID() < b.getUID();}); else qSort(mAnimations.begin(), mAnimations.end(), [] (const Animation& a, const Animation& b) { return a.getUID() > b.getUID();}); } if(column == Name) { if(order == Qt::AscendingOrder) qSort(mAnimations.begin(), mAnimations.end(), [] (const Animation& a, const Animation& b) { return a.getName() < b.getName();}); else qSort(mAnimations.begin(), mAnimations.end(), [] (const Animation& a, const Animation& b) { return a.getName() > b.getName();}); } layoutChanged(); } QVariant AnimationModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); if(index.row() >= mAnimations.count()) return QVariant(); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case AnimationModel::ID: return QVariant(QString::number(mAnimations[index.row()].getUID())); case AnimationModel::Name: return QVariant(mAnimations[index.row()].getName()); case AnimationModel::TextureUID: return QVariant(mAnimations[index.row()].getTextureUID()); case AnimationModel::FrameCount: return QVariant(mAnimations[index.row()].getFrames()); case AnimationModel::RectWidth: return QVariant(mAnimations[index.row()].getWidth()); case AnimationModel::RectHeight: return QVariant(mAnimations[index.row()].getHeight()); case AnimationModel::Period: return QVariant(mAnimations[index.row()].getPeriod()); case AnimationModel::TimerMode: switch(mAnimations[index.row()].getMode()) { case Animation::OneShot: return QVariant(QString("One shot")); case Animation::Continous: return QVariant(QString("Continu")); } break; } } if(role == Qt::BackgroundRole) return index.row() % 2 ? QVariant(QBrush(QColor(0, 140, 255))) : QVariant(QBrush(QColor(100, 180, 255))); return QVariant(); } bool AnimationModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(index.isValid() && role == Qt::EditRole) { if(index.row() < mAnimations.size()) { switch(index.column()) { case AnimationModel::ID: break; case AnimationModel::Name: mAnimations[index.row()].setName(value.toString()); emit dataChanged(index, index, {role}); return true; } } } return false; } Qt::ItemFlags AnimationModel::flags(const QModelIndex &index) const { if (!index.isValid()) return Qt::ItemIsEnabled; return QAbstractItemModel::flags(index) | Qt::ItemIsSelectable; } bool AnimationModel::insertRows(int , int , const QModelIndex &) { return false; } bool AnimationModel::insertColumns(int , int , const QModelIndex &) { return false; } const QVector<Animation>& AnimationModel::getAnimations() { return mAnimations; } bool AnimationModel::readJSON(QJsonObject &json) { if(json.contains("animations") && json["animations"].isArray()) { unsigned long long maxUID = 0; QJsonArray array = json["animations"].toArray(); beginResetModel(); mAnimations.clear(); endResetModel(); beginInsertRows(QModelIndex(), 0, array.size()); mAnimations.reserve(array.size()); for(int row = 0; row < array.size(); row++) { QJsonObject json = array[row].toObject(); Animation anim; anim.fromJSON(json); mAnimations.push_back(anim); mAssets->addAsset(&mAnimations.last()); if(anim.getUID() > maxUID) maxUID = anim.getUID(); } Animation::setCurrentUID(maxUID+1); endInsertRows(); return true; } return false; } void AnimationModel::writeJSON(QJsonObject& json) { json.insert("count", QString::number(mAnimations.count())); QJsonArray animArray; for(auto& anim : mAnimations) { QJsonObject obj; anim.toJSON(obj); animArray.append(obj); } json.insert("animations", animArray); } const Animation AnimationModel::getAnimation(int row) { if(row >= mAnimations.count()) return Animation(); return mAnimations[row]; } const Animation AnimationModel::getByUID(Animation::UID uid) { for(auto& anim : mAnimations) { if(anim.getUID() == uid) return anim; } return Animation(); } void AnimationModel::removeAnimation(Animation::UID uid) { int row = -1; for(int i = 0; i < mAnimations.count(); i++) { if(mAnimations[i].getUID() == uid) { row = i; break; } } if(row == -1) return; beginRemoveRows(QModelIndex(), row, row); mAnimations.removeAt(row); endRemoveRows(); } void AnimationModel::addAnimation(Animation anim) { beginInsertRows(QModelIndex(), mAnimations.count(), mAnimations.count()); mAnimations.insert(mAnimations.count(), anim); mAssets->addAsset(&mAnimations.last()); endInsertRows(); } unsigned long long AnimationModel::getUID(QModelIndex index) { if(!index.isValid()) return 0; return mAnimations[index.row()].getUID(); } bool AnimationModel::loadFromFile(QString path) { QFile AnimFile(path); if(!AnimFile.open(QIODevice::ReadOnly)) QMessageBox::critical(nullptr, "Erreur plutôt critique quand même", "Impossible d'accéder au fichier de sauvegarde des Animations : " + path); else { QJsonObject anims(QJsonDocument::fromJson(AnimFile.readAll()).object()); readJSON(anims); return true; } return false; }
a21ddb1be28ddc8c5ab0ae911830d60d2b45c48a
d8c6bd6d6caf88398169bfdf55dc9b49661c65cc
/proj5/server.cpp
d60c356cd6a9c9642c643cc254ad74b7d4124153
[]
no_license
KendallWeihe/PrimitiveCloudServer
99bacfa35a2bf7efd7db16ea4fbde06997f66a48
412d4de19890015c1617af71efafd73236ba21e5
refs/heads/master
2020-06-17T15:48:01.177295
2016-12-02T04:24:41
2016-12-02T04:24:41
74,990,735
0
0
null
null
null
null
UTF-8
C++
false
false
10,397
cpp
extern "C" { #include "csapp.h" } #include <iostream> #include <string> #include <netinet/in.h> #include <fstream> #include <vector> using namespace std; // function declarations unsigned int convert_header_to_host_order(char client_message[]); void get(char buf[], int connfd); void put(char buf[], int connfd); void del(char buf[], int connfd); void list(char buf[], int connfd); void parse_filename(char buf[], char filename[]); void parse_filedata(char buf[], char filename[]); int search(vector<string>, string); vector<string> file_names; vector<string> file_data; int rio_error_check = 0; const int PUT_REPLY_LEN = 4; const int DELETE_REPLY_LEN = 4; /* function: main() inputs: port number secret key purpose: accept TCP connection from server read data from client connection parse data based on MyCloud Protocol respond to client request */ int main(int argc, char* argv[]){ // socket data int listenfd, connfd, port; socklen_t clientlen; struct sockaddr_in clientaddr; struct hostent *hp; char *haddrp; // check for argument count if (argc != 3) { fprintf(stderr, "usage: %s <port> <key>\n", argv[0]); exit(0); } // user defined port port = atoi(argv[1]); // open connection on user defined port listenfd = Open_listenfd(port); // loop until user enters Ctrl-C to quit while (1){ clientlen = sizeof(clientaddr); // accept connection with client connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen); /* Determine the domain name and IP address of the client */ hp = Gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET); haddrp = inet_ntoa(clientaddr.sin_addr); printf("server connected to %s (%s)\n", hp->h_name, haddrp); // data required to start reading from client char buf[MAXLINE] = {0}; rio_t rio; size_t n; Rio_readinitb(&rio, connfd); // read from client connection n = Rio_readnb(&rio, buf, MAXLINE); if (n < 0){ cout << "Error in reading from client" << endl; rio_error_check = -1; } // assign secret key to local variable char secret_key_char_array[4]; for (int i = 0; i < 4; i++){ secret_key_char_array[i] = buf[i]; } // assign type to local variable char type_char_array[4]; for (int i = 0; i < 4; i++){ type_char_array[i] = buf[4+i]; } // call function to convert header to little endian order unsigned int key = convert_header_to_host_order(secret_key_char_array); cout << "Secret Key = " << key << endl; // check if client key matches the server secret key if (key != (unsigned int)stoi(argv[2])){ cout << "Invalid key" << endl; // case where the keys do not match } else { // convert the type to little endian order unsigned int type = convert_header_to_host_order(type_char_array); cout << "Request Type = " << type << endl; // switch statement to call function based on client specified type switch(type){ case 0: get(buf, connfd); break; case 1: put(buf, connfd); break; case 2: del(buf, connfd); break; case 3: list(buf, connfd); break; } } cout << "--------------------------" << endl; Close(connfd); } return 0; } /* function convert_header_to_host_order() inputs: char array of 4 bytes purpose: convert char array of 4 bytes from network to host order */ unsigned int convert_header_to_host_order(char client_message[]){ // local variables unsigned int byte1, byte2, byte3, byte4; byte1 = (unsigned char)client_message[3] << 24; // bit level operations byte2 = (unsigned char)client_message[2] << 16; byte3 = (unsigned char)client_message[1] << 8; byte4 = (unsigned char)client_message[0]; // cout << byte1 << ", " << byte2 << ", " << byte3 << ", " << byte4 << endl; unsigned int header = byte1 | byte2 | byte3 | byte4; return header; } /* function parse_filename() inputs: buffer of data from client empty char array to store filename purpose: extract filename from buffer read from client */ void parse_filename(char buf[], char filename[]){ // note the filename begins at byte number 9 (i = 8) for (int i = 8; i < 88; i++){ if (buf[i] == '\0'){ // case where the end of the file is found break; } filename[i-8] = buf[i]; } cout << "Filename = " << filename << endl; } /* function parse_filedata() inputs: buffer of data from client empty char array to store file data purpose: extract file data from buffer read from client */ void parse_filedata(char buf[], char filedata[]){ // the length of the file starts at 88 and ends at 91 unsigned char byte_1 = buf[91]; unsigned char byte_2 = buf[90]; unsigned char byte_3 = buf[89]; unsigned char byte_4 = buf[88]; unsigned int a = (unsigned int)byte_1 << 24; // bit level operations unsigned int b = (unsigned int)byte_2 << 16; unsigned int c = (unsigned int)byte_3 << 8; unsigned int d = (unsigned int)byte_4; unsigned int file_length = a | b | c | d; // note the filedata begins at byte number 93 (i = 92) for (unsigned int i = 92; i < 92 + file_length; i++){ if (buf[i] == '\0'){ // case where the end of the file is found break; } filedata[i-92] = buf[i]; } } /* function get() inputs: buffer of data from client client connection file descriptor purpose: read a file send file data back to client */ void get(char buf[], int connfd){ // get filename from buffer char filename[80] = {0}; parse_filename(buf, filename); bool file_exists = false; string file; int error = 0; for (unsigned int i = 0; i < file_names.size(); i++){ if (file_names[i] == filename){ file = file_data[i]; file_exists = true; } } if (!file_exists){ error = -1; } // read the data from the file char return_buf[MAXLINE] = {0}; unsigned int index; for (index = 8; index < file.length()+8; index++){ return_buf[index] = file[index-8]; } // error bytes if (error < 0 || rio_error_check < 0){ return_buf[0] = -1; cout << "Operation status = error" << endl; } else{ return_buf[0] = 0; cout << "Operation status = success" << endl; } return_buf[1] = 0; return_buf[2] = 0; return_buf[3] = 0; // bytes 4-8 are the file size (number of bytes) return_buf[4] = (index - 8) & 0xff; return_buf[5] = ((index - 8) >> 8) & 0xff; return_buf[6] = ((index - 8) >> 16) & 0xff; return_buf[7] = ((index - 8) >> 24) & 0xff; // UNCOMMENT TO CHECK FILE SIZE // cout << "Index = " << index << endl; // cout << "Byte 1 = " << (unsigned int)return_buf[4] << endl; // cout << "Byte 2 = " << (unsigned int)return_buf[5] << endl; // cout << "Byte 3 = " << (unsigned int)return_buf[6] << endl; // cout << "Byte 4 = " << (unsigned int)return_buf[7] << endl; const unsigned int BUF_LENGTH = index; Rio_writen(connfd, return_buf, BUF_LENGTH); } /* function put() inputs: buffer of data from client client connection file descriptor purpose: store a file send confirmation back to client */ void put(char buf[], int connfd){ // get filename from buffer char filename[80] = {0}; parse_filename(buf, filename); string fname(filename); // convert to string char data[MAXLINE] = {0}; parse_filedata(buf, data); string fdata(data); int index = search( file_names, fname ); // check if the file already exists if( index != -1 ) { // If it does, update it. file_data[index] = fdata; } else { // If not, add the new variable and value. file_names.push_back(fname); file_data.push_back(fdata); } // assemble the return message char return_buf[PUT_REPLY_LEN] = {0}; // error bytes if (rio_error_check < 0){ return_buf[0] = -1; rio_error_check = 0; cout << "Operation Status = error\n"; } else{ return_buf[0] = 0; cout << "Operation Status = success\n"; } return_buf[1] = 0; return_buf[2] = 0; return_buf[3] = 0; // write to the client Rio_writen(connfd, return_buf, PUT_REPLY_LEN); } void del(char buf[], int connfd) { char filename[80] = {0}; parse_filename(buf, filename); string fname(filename); // convert to string int index = search( file_names, fname ); // check if the file exists if( index != -1 ) { // If it does, delete it file_names.erase(file_names.begin() + index); file_data.erase(file_data.begin() + index); rio_error_check = 0; cout << "Operation Status = success" << endl; } else { // If the file is not stored in the server rio_error_check = -1; cout << "Operation Status = error" << endl; } // assemble the return message char return_buf[DELETE_REPLY_LEN] = {0}; // error bytes if (rio_error_check < 0){ return_buf[0] = -1; } else{ return_buf[0] = 0; } return_buf[1] = 0; return_buf[2] = 0; return_buf[3] = 0; // write to the client Rio_writen(connfd, return_buf, DELETE_REPLY_LEN); } void list(char buf[], int connfd) { string file_list = ""; // Holds the list of files for(unsigned int i = 0; i < file_names.size(); i++ ) { file_list += file_names[i] + "\n"; } char return_buf[MAXLINE] = {0}; unsigned int index; for (index = 8; index < file_list.length()+8; index++){ return_buf[index] = file_list[index-8]; } // error bytes if (rio_error_check < 0){ return_buf[0] = -1; cout << "Operation status = error" << endl; } else{ return_buf[0] = 0; cout << "Operation status = success" << endl; } return_buf[1] = 0; return_buf[2] = 0; return_buf[3] = 0; // bytes 4-8 are the file size (number of bytes) return_buf[4] = (index - 8) & 0xff; return_buf[5] = ((index - 8) >> 8) & 0xff; return_buf[6] = ((index - 8) >> 16) & 0xff; return_buf[7] = ((index - 8) >> 24) & 0xff; const unsigned int BUF_LENGTH = index; Rio_writen(connfd, return_buf, BUF_LENGTH); } int search(vector<string> vec, string toFind) { for (unsigned int i = 0; i < vec.size(); i++) { if (vec[i] == toFind) { return i; // Return the position if it's found. } } return -1; // If not found, return -1. }
d232b04c5868575cdf2289515c9b811f68c769d6
7568cf9fc1eee857141ab265311edcaf964f54b4
/components/omnibox/common/omnibox_features.cc
aa4ae3d6a631c711ccd82ba9d9112638afd1d90c
[ "BSD-3-Clause" ]
permissive
cbosoft/chromium
f4f0c9e1ae596850c04038eed34d21040103569f
072e9137131be2f8a99efbfc7dc8fd8c1cd4c4eb
refs/heads/master
2023-01-06T22:31:37.388286
2020-05-28T18:24:23
2020-05-28T18:24:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,998
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/omnibox/common/omnibox_features.h" #include "build/build_config.h" namespace omnibox { // Allows Omnibox to dynamically adjust number of offered suggestions to fill in // the space between Omnibox an the soft keyboard. The number of suggestions // shown will be no less than minimum for the platform (eg. 5 for Android). const base::Feature kAdaptiveSuggestionsCount{ "OmniboxAdaptiveSuggestionsCount", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to hide the scheme from steady state URLs displayed in the // toolbar. It is restored during editing. const base::Feature kHideFileUrlScheme { "OmniboxUIExperimentHideFileUrlScheme", // Android and iOS don't have the File security chip, and therefore still // need to show the file scheme. #if defined(OS_ANDROID) || defined(OS_IOS) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Feature used to hide the scheme from steady state URLs displayed in the // toolbar. It is restored during editing. const base::Feature kHideSteadyStateUrlScheme{ "OmniboxUIExperimentHideSteadyStateUrlScheme", base::FEATURE_ENABLED_BY_DEFAULT}; // Feature used to hide trivial subdomains from steady state URLs displayed in // the toolbar. It is restored during editing. const base::Feature kHideSteadyStateUrlTrivialSubdomains{ "OmniboxUIExperimentHideSteadyStateUrlTrivialSubdomains", base::FEATURE_ENABLED_BY_DEFAULT}; // Feature used to hide the path, query and ref from steady state URLs // displayed in the toolbar. It is restored during editing. const base::Feature kHideSteadyStateUrlPathQueryAndRef { "OmniboxUIExperimentHideSteadyStateUrlPathQueryAndRef", #if defined(OS_IOS) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Feature used to enable local entity suggestions. Similar to rich entities but // but location specific. E.g., typing 'starbucks near' could display the local // entity suggestion 'starbucks near disneyland \n starbucks * Anaheim, CA'. const base::Feature kOmniboxLocalEntitySuggestions{ "OmniboxLocalEntitySuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable swapping the rows on answers. const base::Feature kOmniboxReverseAnswers{"OmniboxReverseAnswers", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable matching short words to bookmarks for suggestions. const base::Feature kOmniboxShortBookmarkSuggestions{ "OmniboxShortBookmarkSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to force on the experiment of transmission of tail suggestions // from GWS to this client, currently testing for desktop. const base::Feature kOmniboxTailSuggestions{ "OmniboxTailSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that enables the tab-switch suggestions corresponding to an open // tab, for a button or dedicated suggestion. Enabled by default on Desktop // and iOS. const base::Feature kOmniboxTabSwitchSuggestions{ "OmniboxTabSwitchSuggestions", #if defined(OS_ANDROID) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Feature that enables tab-switch suggestions in their own row. const base::Feature kOmniboxTabSwitchSuggestionsDedicatedRow{ "OmniboxTabSwitchSuggestionsDedicatedRow", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable various experiments on keyword mode, UI and // suggestions. const base::Feature kExperimentalKeywordMode{"OmniboxExperimentalKeywordMode", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to enable Pedal suggestions. const base::Feature kOmniboxPedalSuggestions{"OmniboxPedalSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature to enable clipboard provider to suggest searching for copied images. const base::Feature kEnableClipboardProviderImageSuggestions{ "OmniboxEnableClipboardProviderImageSuggestions", #if defined(OS_IOS) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Feature to enable the search provider to send a request to the suggest // server on focus. This allows the suggest server to warm up, by, for // example, loading per-user models into memory. Having a per-user model // in memory allows the suggest server to respond more quickly with // personalized suggestions as the user types. const base::Feature kSearchProviderWarmUpOnFocus{ "OmniboxWarmUpSearchProviderOnFocus", #if defined(OS_IOS) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Feature used to display the title of the current URL match. const base::Feature kDisplayTitleForCurrentUrl{ "OmniboxDisplayTitleForCurrentUrl", #if !defined(OS_IOS) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Feature used to display the search terms instead of the URL in the Omnibox // when the user is on the search results page of the default search provider. const base::Feature kQueryInOmnibox{"QueryInOmnibox", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to always swap the title and URL. const base::Feature kUIExperimentSwapTitleAndUrl{ "OmniboxUIExperimentSwapTitleAndUrl", #if defined(OS_IOS) || defined(OS_ANDROID) base::FEATURE_DISABLED_BY_DEFAULT #else base::FEATURE_ENABLED_BY_DEFAULT #endif }; // Feature used to enable speculatively starting a service worker associated // with the destination of the default match when the user's input looks like a // query. const base::Feature kSpeculativeServiceWorkerStartOnQueryInput{ "OmniboxSpeculativeServiceWorkerStartOnQueryInput", base::FEATURE_ENABLED_BY_DEFAULT }; // Feature used to fetch document suggestions. const base::Feature kDocumentProvider{"OmniboxDocumentProvider", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to autocomplete bookmark, history, and document suggestions when // the user input is a prefix of their titles, as opposed to their URLs. const base::Feature kAutocompleteTitles{"OmniboxAutocompleteTitles", base::FEATURE_DISABLED_BY_DEFAULT}; // Returns whether IsInstantExtendedAPIEnabled should be ignored when deciding // the number of Google-provided search suggestions. const base::Feature kOmniboxDisableInstantExtendedLimit{ "OmniboxDisableInstantExtendedLimit", #if defined(OS_ANDROID) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Show the search engine logo in the omnibox on Android (desktop already does // this). const base::Feature kOmniboxSearchEngineLogo{"OmniboxSearchEngineLogo", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to allow users to remove suggestions from clipboard. const base::Feature kOmniboxRemoveSuggestionsFromClipboard{ "OmniboxRemoveSuggestionsFromClipboard", #if defined(OS_ANDROID) base::FEATURE_ENABLED_BY_DEFAULT #else base::FEATURE_DISABLED_BY_DEFAULT #endif }; // Feature to debounce drive requests from the document provider. const base::Feature kDebounceDocumentProvider{ "OmniboxDebounceDocumentProvider", base::FEATURE_DISABLED_BY_DEFAULT}; // Preserves the default match against change when providers return results // asynchronously. This prevents the default match from changing after the user // finishes typing. Without this feature, if the default match is updated right // when the user presses Enter, the user may go to a surprising destination. const base::Feature kOmniboxPreserveDefaultMatchAgainstAsyncUpdate{ "OmniboxPreserveDefaultMatchAgainstAsyncUpdate", base::FEATURE_ENABLED_BY_DEFAULT}; // Demotes the relevance scores when comparing suggestions based on the // suggestion's |AutocompleteMatchType| and the user's |PageClassification|. // This feature's main job is to contain the DemoteByType parameter. const base::Feature kOmniboxDemoteByType{"OmniboxDemoteByType", base::FEATURE_DISABLED_BY_DEFAULT}; // A special flag, enabled by default, that can be used to disable all new // search features (e.g. zero suggest). const base::Feature kNewSearchFeatures{"OmniboxNewSearchFeatures", base::FEATURE_ENABLED_BY_DEFAULT}; // Feature used to cap max zero suggestions shown according to the param // OmniboxMaxZeroSuggestMatches. If omitted, // OmniboxUIExperimentMaxAutocompleteMatches will be used instead. If present, // OmniboxMaxZeroSuggestMatches will override // OmniboxUIExperimentMaxAutocompleteMatches when |from_omnibox_focus| is true. const base::Feature kMaxZeroSuggestMatches{"OmniboxMaxZeroSuggestMatches", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to cap max suggestions shown according to the params // UIMaxAutocompleteMatches and UIMaxAutocompleteMatchesByProvider. const base::Feature kUIExperimentMaxAutocompleteMatches{ "OmniboxUIExperimentMaxAutocompleteMatches", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature used to cap the number of URL-type matches shown within the // Omnibox. If enabled, the number of URL-type matches is limited (unless // there are no more non-URL matches available.) If enabled, there is a // companion parameter - OmniboxMaxURLMatches - which specifies the maximum // desired number of URL-type matches. const bool kOmniboxMaxURLMatchesEnabledByDefault = #if defined(OS_IOS) || defined(OS_ANDROID) false; #else true; #endif const base::Feature kOmniboxMaxURLMatches{ "OmniboxMaxURLMatches", kOmniboxMaxURLMatchesEnabledByDefault ? base::FEATURE_ENABLED_BY_DEFAULT : base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that configures ZeroSuggestProvider using the "ZeroSuggestVariant" // per-page-classification parameter. // // Generally speaking - do NOT use this for future server-side experiments. // Instead, create your a new narrowly scoped base::Feature for each experiment. // // Because our Field Trial system can only configure this base::Feature in a // single study, and does not merge parameters, using this creates conflicts. const base::Feature kOnFocusSuggestions{"OmniboxOnFocusSuggestions", base::FEATURE_ENABLED_BY_DEFAULT}; // Enables on-focus suggestions on the Open Web, that are contextual to the // current URL. Will only work if user is signed-in and syncing, or is // otherwise eligible to send the current page URL to the suggest server. const base::Feature kOnFocusSuggestionsContextualWeb{ "OmniboxOnFocusSuggestionsContextualWeb", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables Proactive ZeroSuggestions (PZPS) on the NTP, for the Omnibox and // Realbox respectively. Note: enabling this feature merely makes // ZeroSuggestProvider send the request. There are additional requirements, // like the user being signed-in, and the suggest server having PZPS enabled. const base::Feature kProactiveZeroSuggestionsOnNTPOmnibox{ "OmniboxProactiveZeroSuggestionsOnNTPOmnibox", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kProactiveZeroSuggestionsOnNTPRealbox{ "OmniboxProactiveZeroSuggestionsOnNTPRealbox", base::FEATURE_DISABLED_BY_DEFAULT}; // Allow suggestions to be shown to the user on the New Tab Page upon focusing // URL bar (the omnibox). const base::Feature kZeroSuggestionsOnNTP{"OmniboxZeroSuggestionsOnNTP", base::FEATURE_DISABLED_BY_DEFAULT}; // Allow suggestions to be shown to the user on the New Tab Page upon focusing // the real search box. const base::Feature kZeroSuggestionsOnNTPRealbox{ "OmniboxZeroSuggestionsOnNTPRealbox", base::FEATURE_DISABLED_BY_DEFAULT}; // Allow on-focus query refinements to be shown on the default SERP. const base::Feature kZeroSuggestionsOnSERP{"OmniboxZeroSuggestionsOnSERP", base::FEATURE_ENABLED_BY_DEFAULT}; // Features to provide non personalized head search suggestion from a compact // on device model. More specifically, feature name with suffix Incognito / // NonIncognito will only controls behaviors under incognito / non-incognito // mode respectively. const base::Feature kOnDeviceHeadProviderIncognito{ "OmniboxOnDeviceHeadProviderIncognito", base::FEATURE_DISABLED_BY_DEFAULT}; const base::Feature kOnDeviceHeadProviderNonIncognito{ "OmniboxOnDeviceHeadProviderNonIncognito", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, changes the way Google-provided search suggestions are scored by // the backend. Note that this Feature is only used for triggering a server- // side experiment config that will send experiment IDs to the backend. It is // not referred to in any of the Chromium code. const base::Feature kOmniboxExperimentalSuggestScoring{ "OmniboxExperimentalSuggestScoring", base::FEATURE_DISABLED_BY_DEFAULT}; // If disabled, terms with no wordstart matches disqualify the suggestion unless // they occur in the URL host. If enabled, terms with no wordstart matches are // allowed but not scored. E.g., both inputs 'java script' and 'java cript' will // match a suggestion titled 'javascript' and score equivalently. const base::Feature kHistoryQuickProviderAllowButDoNotScoreMidwordTerms{ "OmniboxHistoryQuickProviderAllowButDoNotScoreMidwordTerms", base::FEATURE_DISABLED_BY_DEFAULT}; // If disabled, midword matches are ignored except in the URL host, and input // terms with no wordstart matches are scored 0, resulting in an overall score // of 0. If enabled, midword matches are allowed and scored when they begin // immediately after the previous match ends. E.g. 'java script' will match a // suggestion titled 'javascript' but the input 'java cript' won't. const base::Feature kHistoryQuickProviderAllowMidwordContinuations{ "OmniboxHistoryQuickProviderAllowMidwordContinuations", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, shows slightly more compact suggestions, allowing the // kAdaptiveSuggestionsCount feature to fit more suggestions on screen. const base::Feature kCompactSuggestions{"OmniboxCompactSuggestions", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, defers keyboard popup when user highlights the omnibox until // the user taps the Omnibox again. extern const base::Feature kDeferredKeyboardPopup{ "OmniboxDeferredKeyboardPopup", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, expands autocompletion to possibly (depending on params) include // suggestion titles and non-prefixes as opposed to be restricted to URL // prefixes. Will also adjust the location bar UI and omnibox text selection to // accommodate the autocompletions. const base::Feature kRichAutocompletion{"OmniboxRichAutocompletion", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that enables not counting submatches towards the maximum // suggestion limit. const base::Feature kOmniboxLooseMaxLimitOnDedicatedRows{ "OmniboxLooseMaxLimitOnDedicatedRows", base::FEATURE_DISABLED_BY_DEFAULT}; // Feature that puts a single row of buttons on suggestions with actionable // elements like keywords, tab-switch buttons, and Pedals. const base::Feature kOmniboxSuggestionButtonRow{ "OmniboxSuggestionButtonRow", base::FEATURE_DISABLED_BY_DEFAULT}; // Enables using an Android RecyclerView to render the suggestions dropdown // instead of a ListView. const base::Feature kOmniboxSuggestionsRecyclerView{ "OmniboxSuggestionsRecyclerView", base::FEATURE_DISABLED_BY_DEFAULT}; // Allows long Omnibox suggestions to wrap around to next line. const base::Feature kOmniboxSuggestionsWrapAround{ "OmniboxSuggestionsWrapAround", base::FEATURE_DISABLED_BY_DEFAULT}; // If enabled, uses WebUI to render the omnibox suggestions popup, similar to // how the NTP "fakebox" is implemented. const base::Feature kWebUIOmniboxPopup{"WebUIOmniboxPopup", base::FEATURE_DISABLED_BY_DEFAULT}; // When enabled, use Assistant for omnibox voice query recognition instead of // Android's built-in voice recognition service. Only works on Android. const base::Feature kOmniboxAssistantVoiceSearch{ "OmniboxAssistantVoiceSearch", base::FEATURE_DISABLED_BY_DEFAULT}; // When enabled, provides an omnibox context menu option that prevents URL // elisions. const base::Feature kOmniboxContextMenuShowFullUrls{ "OmniboxContextMenuShowFullUrls", base::FEATURE_DISABLED_BY_DEFAULT}; } // namespace omnibox
8748e8bcc6c9976b8b85f5131dfb00103a39ed4a
3bbefab6c034154ae4724baf0fe9de1eb2008d82
/src/appleseed/foundation/meta/benchmarks/benchmark_integerdivision.cpp
c11f42b95c6e8d6e42b4fbbd089797611e4717ae
[ "MIT" ]
permissive
johnhaddon/appleseed
e959a30ab24f80a4cb3639d22c1b16b58fc3373c
82eb4693f7a64fcaf238272a1ad62ff38c5b870b
refs/heads/master
2021-01-22T09:32:01.704121
2016-08-22T17:41:23
2016-08-22T17:41:23
17,192,177
1
0
null
2016-08-24T12:04:18
2014-02-25T23:36:11
C++
UTF-8
C++
false
false
2,531
cpp
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // appleseed.foundation headers. #include "foundation/math/rng/distribution.h" #include "foundation/math/rng/mersennetwister.h" #include "foundation/math/scalar.h" #include "foundation/utility/benchmark.h" // Standard headers. #include <cstddef> using namespace foundation; BENCHMARK_SUITE(IntegerDivision) { const size_t N = 1000; struct Fixture { size_t m_num[N]; size_t m_den[N]; double m_one_over_den[N]; size_t m_result; Fixture() : m_result(0) { MersenneTwister rng; for (size_t i = 0; i < N; ++i) { m_num[i] = rand_int1(rng, 0, 100); m_den[i] = rand_int1(rng, 1, 100); m_one_over_den[i] = 1.0 / m_den[i]; } } }; BENCHMARK_CASE_F(IntegerDivision, Fixture) { for (size_t i = 0; i < N; ++i) m_result += m_num[i] / m_den[i]; } BENCHMARK_CASE_F(MultiplicationByReciprocal, Fixture) { for (size_t i = 0; i < N; ++i) m_result += truncate<size_t>(m_num[i] * m_one_over_den[i]); } }