text
stringlengths
8
6.88M
/** \file testThread.hpp \author UnBeatables \date LARC2018 \name testThead */ #ifndef TESTTHREAD_HPP #define TESTTHREAD_HPP #include <basemodule.hpp> #include <time.h> #include <cstdio> #include <vector> #include <cmath> /** \brief Thread to test code and time to execute in the robot for to perception or communicattion */ class test : public baseModule { public: /** \brief Class constructor. \param _ub void pointer for UnBoard. */ test(void*); /** \brief Class destructor. */ ~test(); /** \brief Function that tests code and returns time. */ void tick(); }; #endif // TESTTHREAD_HPP
#pragma once #include <utility> template<typename T> class shared { private: shared(const shared &); shared(); template<typename> friend class launch_core_access; // allows friends to construct dummy shared<T> objects struct construct_dummy_tag {}; shared(construct_dummy_tag) {} shared(void *p) : ptr(reinterpret_cast<T*>(p)) { ::new(static_cast<void*>(ptr)) T(); } template<typename Arg1> shared(void *p, const Arg1 &arg1) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1); } template<typename Arg1, typename Arg2> shared(void *p, const Arg1 &arg1, const Arg2 &arg2) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2); } template<typename Arg1, typename Arg2, typename Arg3> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3,arg4); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4, const Arg5 &arg5) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3,arg4,arg5); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4, const Arg5 &arg5, const Arg6 &arg6) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3,arg4,arg5,arg6); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4, const Arg5 &arg5, const Arg6 &arg6, const Arg7 &arg7) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3,arg4,arg5,arg6,arg7); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4, const Arg5 &arg5, const Arg6 &arg6, const Arg7 &arg7, const Arg8 &arg8) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4, const Arg5 &arg5, const Arg6 &arg6, const Arg7 &arg7, const Arg8 &arg8, const Arg9 &arg9) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9); } template<typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7, typename Arg8, typename Arg9, typename Arg10> shared(void *p, const Arg1 &arg1, const Arg2 &arg2, const Arg3 &arg3, const Arg4 &arg4, const Arg5 &arg5, const Arg6 &arg6, const Arg7 &arg7, const Arg8 &arg8, const Arg9 &arg9, const Arg10 &arg10) { // construct the object given the args ::new(static_cast<void*>(ptr)) T(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10); } ~shared() { // destroy the object ptr->~T(); } T *ptr; }; template<typename T> struct launch_core_access { static shared<T> &shared_dummy() { static shared<T> dummy((typename shared<T>::construct_dummy_tag())); return dummy; } };
// Font block 'arial13_basic_latin_1bpp_0x21_0x7E' definition // // Bitmap data static const esU8 sc_arial13_basic_latin_1bpp_0x21_0x7E_data[] = { ________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________, _X_X_X__,__X_X___,XXX____X,X___X___,___XX___,_X___XX_,____X___,________,________,__X__XXX,_____X__,___XXX__,__XXX___,___X____,XXXX___X,XX___XXX,XX___XXX,____XXX_,________,________,________,______XX,X_______,XXXX____,__X____X,XXXX____,_XXX____,XXXXX___,_XXXXXX_,_XXXXX__,__XXX___,_X_____X,__X_____,X__X____,_X_X____,__X_____,X__X____,_X____XX,X____XXX,XX_____X,XX____XX,XXXX____,XXXX__XX,XXXXX_X_,____X_X_,____XX__,__X____X,X_____XX,_____X_X,XXXXX_XX,X__XX___,X_______,___X____,______X_,________,_______X,________,__X_____,___X____,__X__X__,X_____X_,________,________,________,________,________,________,___X____,________,________,________,________,___X__X_,_X______,________, _X_X_X__,__X_X__X,_X_X__X_,_X_X____,__X__X__,_X__X__X,__XXXXX_,________,________,__X_X___,X___XX__,__X___X_,_X___X__,__XX____,X_____X_,__X_____,X___X___,X__X___X,________,________,________,_____X__,_X____XX,____XX__,_X_X___X,____X___,X___X___,X____X__,_X______,_X______,_X___X__,_X_____X,__X_____,X__X____,X__X____,__XX___X,X__XX___,_X___X__,_X___X__,__X___X_,__X___X_,____X__X,____X___,_X____X_,____X_X_,____XX__,_X_X___X,_X___X__,X___X___,___X__X_,X___X__X,_X______,____X___,______X_,________,_______X,________,_X______,___X____,________,X_____X_,________,________,________,________,________,________,___X____,________,________,________,________,__X___X_,__X_____,________, _X_X_X_X,XXXXXX_X,_X____X_,_X_X____,__X__X__,_X__X__X,____X___,__X_____,________,_X__X___,X__X_X__,______X_,_____X__,__XX___X,______X_,________,X___X___,X__X___X,_XX_XX__,____X___,______X_,_____X__,_X___X__,_____X__,_X_X___X,____X__X,_____X__,X_____X_,_X______,_X______,X_____X_,_X_____X,__X_____,X__X___X,___X____,__XX___X,X__X_X__,_X__X___,__X__X__,__X__X__,___X__X_,____X__X,____X___,_X____X_,____X__X,___X_X__,_X_X__X_,_X___X__,X___X___,__X___X_,_X__X__X,_X______,________,XXX___X_,XX____XX,____XX_X,___XXX__,XXX__XX_,X__X_XX_,__X__X__,X___X_X_,_X_XX__X,X___X_XX,____XXX_,__X_XX__,__XX_X__,X_X__XXX,__XXX_X_,__X_X___,XX___X__,_XX___XX,___XXXXX,X_X___X_,__X_____,________, _X______,_X_X___X,_X____X_,_XX_____,__X_X___,___X____,X__X_X__,__X_____,________,_X__X___,X____X__,______X_,_____X__,_X_X___X,XXX___X_,XX_____X,____X___,X__X___X,_XX_____,_XXX__XX,XXXX___X,XX______,_X___X__,XX_X__X_,_X_X___X,____X__X,________,X_____X_,_X______,_X______,X_______,_X_____X,__X_____,X__X__X_,___X____,__X_X_X_,X__X_X__,_X__X___,__X__X__,__X__X__,___X__X_,____X__X,________,_X____X_,____X__X,___X__X_,_X_X__X_,__X_X___,_X_X____,__X___X_,_X__X__X,_X______,_______X,___X__XX,__X__X__,X__X__XX,__X___X_,_X__X__X,X__XX__X,__X__X__,X__X__X_,_XX__XX_,_X__XX__,X__X___X,__XX__X_,_X__XX__,XX__X___,X__X__X_,__X_X___,XX___X__,_X_X_X_X,___X___X,__X___X_,__X_____,________, _X______,_X_X____,XXX____X,X_X_XX__,__XX____,___X____,X_______,XXXXX___,________,_X__X___,X____X__,_____X__,___XX___,_X_X___X,___X__XX,__X____X,_____XXX,___X__XX,________,X_______,________,__X_____,X___X__X,__XX__X_,X___X__X,XXXXX__X,________,X_____X_,_XXXXXX_,_XXXX___,X___XXX_,_XXXXXXX,__X_____,X__X_X__,___X____,__X_X_X_,X__X__X_,_X__X___,__X__XXX,XX___X__,___X__XX,XXXX____,XXXX____,_X____X_,____X__X,___X__X_,X___X_X_,___X____,__X_____,_X____X_,_X__X_X_,__X_____,________,___X__X_,__X__X__,___X___X,__X___X_,_X__X___,X__X___X,__X__X__,X_X___X_,_X___X__,_X__X___,X__X___X,__X___X_,_X___X__,X___X___,___X__X_,__X__X_X,__X_X_X_,X__X_X__,X_X____X,__X___X_,__X___XX,__X_____, _X_____X,XXXXXX__,_X_X____,__XX__X_,_X__X_X_,___X____,X_______,__X_____,_XXX____,_X__X___,X____X__,_____X__,_____X__,X__X____,___X__X_,__X____X,____X___,X___XX_X,________,_XXX____,_______X,XX_____X,____X_X_,__X___X_,XXXXX__X,____X__X,________,X_____X_,_X______,_X______,X_____X_,_X_____X,__X_____,X__XX_X_,___X____,__X_X_X_,X__X___X,_X__X___,__X__X__,_____X__,___X__X_,__X_____,____X___,_X____X_,____X___,X_X___X_,X___X_X_,__X_X___,__X_____,X_____X_,_X__X___,________,________,XXXX__X_,__X__X__,___X___X,__XXXXX_,_X__X___,X__X___X,__X__X__,XXX___X_,_X___X__,_X__X___,X__X___X,__X___X_,_X___X__,X____XXX,___X__X_,__X__X_X,__X_X_X_,X___X___,X_X___X_,_X____X_,___X_X__,XX______, _X______,_X_X___X,_X_X____,_X_X__X_,_X___X__,___X____,X_______,__X_____,________,_X__X___,X____X__,____X___,_____X__,XXXXX___,___X__X_,__X___X_,____X___,X______X,_XX_____,____X_XX,XXXX__X_,_______X,____X_X_,__X___X_,X___X__X,____X__X,_____X__,X_____X_,_X______,_X______,X_____X_,_X_____X,__X_X___,X__X___X,___X____,__X_X_X_,X__X___X,_X__X___,__X__X__,_____X__,XX_X__X_,___X___X,____X___,_X____X_,____X___,X_X___X_,X___X_X_,_X___X__,__X_____,X_____X_,_X__X___,________,_______X,___X__X_,__X__X__,___X___X,__X_____,_X__X___,X__X___X,__X__X__,X__X__X_,_X___X__,_X__X___,X__X___X,__X___X_,_X___X__,X_______,X__X__X_,__X__X_X,__X_X_X_,X__X_X__,X_X__X__,__X___X_,__X_____,________, ________,X_X____X,_X_X____,_X_X__X_,_X___XX_,___X____,X_______,________,________,X___X___,X____X__,___X____,_X___X__,___X___X,___X__X_,__X___X_,____X___,X__X___X,_XX_____,________,________,________,____X_X_,__X__X_X,_____X_X,____X___,X___X___,X____X__,_X______,_X______,_X___X__,_X_____X,__X_X___,X__X____,X__X____,__X__X__,X__X____,XX___X__,_X___X__,______X_,__X___X_,___X___X,____X___,_X_____X,___X____,_X_____X,_____X__,_X___X__,__X____X,______X_,__X_X___,________,_______X,__XX__XX,__X__X__,X__X___X,__X___X_,_X__X__X,X__X___X,__X__X__,X__X__X_,_X___X__,_X__X___,X__X___X,__XX__X_,_X__XX__,X___X___,X__X__X_,__X___X_,___X___X,___X_X__,_X___X__,__X___X_,__X_____,________, _X______,X_X_____,XXX_____,X___XX__,__XXX__X,____X__X,________,_______X,______X_,X____XXX,_____X__,__XXXXX_,__XXX___,___X____,XXX____X,XX____X_,_____XXX,____XXX_,____XX__,________,________,_______X,____X__X,XXXXX__X,_____X_X,XXXX____,_XXX____,XXXXX___,_XXXXXX_,_X______,__XXX___,_X_____X,__X__XXX,___X____,_X_XXXXX,X_X__X__,X__X____,_X____XX,X____X__,_______X,XX_X__X_,____X___,XXXX____,_X______,XXX_____,_X_____X,_____X__,X_____X_,__X___XX,XXXXX_X_,__X_X___,________,________,XX_X__X_,XX____XX,____XXXX,___XXX__,_X___XX_,X__X___X,__X__X__,X___X_X_,_X___X__,_X__X___,X___XXX_,__X_XX__,__XX_X__,X____XXX,___XX__X,XXX___X_,___X___X,__X___X_,_X__XXXX,X_X___X_,__X_____,________, ________,________,_X______,________,________,____X__X,________,_______X,________,________,________,________,________,________,________,________,________,________,_____X__,________,________,________,_____X__,______X_,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,______X_,____X___,________,________,________,________,________,________,________,X_______,_____X__,________,________,________,________,__X_____,_____X__,________,________,________,________,________,_X______,__X___X_,__X_____,________, ________,________,________,________,________,_____XX_,________,_______X,________,________,________,________,________,________,________,________,________,________,_____X__,________,________,________,______X_,____XX__,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,______XX,___XX___,___XXXXX,XX______,________,________,________,________,____XXXX,________,____X___,________,________,________,________,__X_____,_____X__,________,________,________,________,________,X_______,___X__X_,_X______,________, ________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,_______X,XXXX____,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________,________, }; // Font block 'arial13_basic_latin_1bpp_0x21_0x7E' glyphs offsets data static const esU16 sc_arial13_basic_latin_1bpp_0x21_0x7E_otbl[] = { 0, //< Offset for symbol 0x00000021 ! 3, //< Offset for symbol 0x00000022 " 7, //< Offset for symbol 0x00000023 # 14, //< Offset for symbol 0x00000024 $ 21, //< Offset for symbol 0x00000025 % 32, //< Offset for symbol 0x00000026 & 40, //< Offset for symbol 0x00000027 ' 42, //< Offset for symbol 0x00000028 ( 46, //< Offset for symbol 0x00000029 ) 50, //< Offset for symbol 0x0000002A * 55, //< Offset for symbol 0x0000002B + 62, //< Offset for symbol 0x0000002C , 65, //< Offset for symbol 0x0000002D - 69, //< Offset for symbol 0x0000002E . 72, //< Offset for symbol 0x0000002F / 75, //< Offset for symbol 0x00000030 0 82, //< Offset for symbol 0x00000031 1 89, //< Offset for symbol 0x00000032 2 96, //< Offset for symbol 0x00000033 3 103, //< Offset for symbol 0x00000034 4 110, //< Offset for symbol 0x00000035 5 117, //< Offset for symbol 0x00000036 6 124, //< Offset for symbol 0x00000037 7 131, //< Offset for symbol 0x00000038 8 138, //< Offset for symbol 0x00000039 9 145, //< Offset for symbol 0x0000003A : 148, //< Offset for symbol 0x0000003B ; 151, //< Offset for symbol 0x0000003C < 158, //< Offset for symbol 0x0000003D = 165, //< Offset for symbol 0x0000003E > 172, //< Offset for symbol 0x0000003F ? 179, //< Offset for symbol 0x00000040 @ 191, //< Offset for symbol 0x00000041 A 198, //< Offset for symbol 0x00000042 B 206, //< Offset for symbol 0x00000043 C 215, //< Offset for symbol 0x00000044 D 224, //< Offset for symbol 0x00000045 E 232, //< Offset for symbol 0x00000046 F 239, //< Offset for symbol 0x00000047 G 248, //< Offset for symbol 0x00000048 H 257, //< Offset for symbol 0x00000049 I 260, //< Offset for symbol 0x0000004A J 266, //< Offset for symbol 0x0000004B K 274, //< Offset for symbol 0x0000004C L 281, //< Offset for symbol 0x0000004D M 290, //< Offset for symbol 0x0000004E N 299, //< Offset for symbol 0x0000004F O 308, //< Offset for symbol 0x00000050 P 316, //< Offset for symbol 0x00000051 Q 325, //< Offset for symbol 0x00000052 R 334, //< Offset for symbol 0x00000053 S 342, //< Offset for symbol 0x00000054 T 349, //< Offset for symbol 0x00000055 U 358, //< Offset for symbol 0x00000056 V 365, //< Offset for symbol 0x00000057 W 376, //< Offset for symbol 0x00000058 X 383, //< Offset for symbol 0x00000059 Y 390, //< Offset for symbol 0x0000005A Z 397, //< Offset for symbol 0x0000005B [ 400, //< Offset for symbol 0x0000005C '\' 403, //< Offset for symbol 0x0000005D ] 406, //< Offset for symbol 0x0000005E ^ 411, //< Offset for symbol 0x0000005F _ 418, //< Offset for symbol 0x00000060 ` 422, //< Offset for symbol 0x00000061 a 429, //< Offset for symbol 0x00000062 b 436, //< Offset for symbol 0x00000063 c 442, //< Offset for symbol 0x00000064 d 449, //< Offset for symbol 0x00000065 e 456, //< Offset for symbol 0x00000066 f 459, //< Offset for symbol 0x00000067 g 466, //< Offset for symbol 0x00000068 h 473, //< Offset for symbol 0x00000069 i 476, //< Offset for symbol 0x0000006A j 479, //< Offset for symbol 0x0000006B k 485, //< Offset for symbol 0x0000006C l 488, //< Offset for symbol 0x0000006D m 499, //< Offset for symbol 0x0000006E n 506, //< Offset for symbol 0x0000006F o 513, //< Offset for symbol 0x00000070 p 520, //< Offset for symbol 0x00000071 q 527, //< Offset for symbol 0x00000072 r 531, //< Offset for symbol 0x00000073 s 538, //< Offset for symbol 0x00000074 t 541, //< Offset for symbol 0x00000075 u 548, //< Offset for symbol 0x00000076 v 553, //< Offset for symbol 0x00000077 w 562, //< Offset for symbol 0x00000078 x 567, //< Offset for symbol 0x00000079 y 572, //< Offset for symbol 0x0000007A z 577, //< Offset for symbol 0x0000007B { 581, //< Offset for symbol 0x0000007C | 584, //< Offset for symbol 0x0000007D } 588, //< Offset for symbol 0x0000007E ~ 595 //< Last offset item }; // Font 'arial13_basic_latin_1bpp_0x21_0x7E' block glyphs bitmap static const ESGUI_BITMAP sc_arial13_basic_latin_1bpp_0x21_0x7E_bmp = { // size {595, 13}, // hdr { 1, //< colorFmt 0, //< haveTransparentColor 0 //< clrTransparent }, // data (esU8*)sc_arial13_basic_latin_1bpp_0x21_0x7E_data }; // Font 'arial13_basic_latin_1bpp_0x21_0x7E' block data const ESGUI_FONT_DATA c_arial13_basic_latin_1bpp_0x21_0x7E = { &sc_arial13_basic_latin_1bpp_0x21_0x7E_bmp, //< data (glyphs bitmap) 0x21, //< chFirst 0x7E, //< chLast 3, //< spaceWidth 7, //< nullWidth sc_arial13_basic_latin_1bpp_0x21_0x7E_otbl //< glyphsMap };
#ifndef GNPATH_H #define GNPATH_H #include "GnSystemDefine.h" #if defined(_MAX_PATH) #define GN_MAX_PATH _MAX_PATH #else //#if defined(_MAX_PATH) #define GN_MAX_PATH 260 #endif //#if defined(_MAX_PATH) class GNSYSTEM_ENTRY GnPath { protected: gtchar* mFullFilePath; gtchar* mFileName; gtchar* mFileExtension; public: static size_t ConvertToAbsolute( gchar* pcAbsolutePath, size_t stBytes, const gchar* pcRelativePath, const gchar* pcRelativeToHere); static bool GetFileName(const gwchar* pcFilePath, gwchar* pcOutName, gsize maxPathLength, bool hasExtension = false); static bool GetFullPath(const gwchar* pcFilePath, gwchar* pcOutPath, gsize maxPathLength); static bool GetFileNameA(const gchar* pcFilePath, gchar* pcOutName, gsize maxPathLength, bool hasExtension = false); static bool GetFullPathA(const gchar* pcFilePath, gchar* pcOutPath, gsize maxPathLength); static bool CheckSamePathA(const gchar* pcPath1, const gchar* pcPath2); }; #endif // GNPATH_H
#if !defined(MIDPOINT_CIRCLE) #define MIDPOINT_CIRCLE #include <vector> #include "../custom-headers/Point.h" void setOctetPoints(Point<int> p,std::vector<Point<int>> &points) { int x=p.x,y=p.y; points.push_back(Point<int>(x , y )); points.push_back(Point<int>(-x , y )); points.push_back(Point<int>(x , -y )); points.push_back(Point<int>(-x , -y )); points.push_back(Point<int>(y , x )); points.push_back(Point<int>(-y , x )); points.push_back(Point<int>(y , -x )); points.push_back(Point<int>(-y , -x )); } std::vector<Point<int>> midPointCircleAlgo(int r) { Point<int> point(0,r); float decision = 1 - r; std::vector<Point<int>> points; setOctetPoints(point,points); while (point.y > point.x) { if (decision < 0) { point.x++; decision += 2*point.x+3; } else { point.y--; point.x++; decision += 2*(point.x-point.y)+5; } setOctetPoints(point,points); } return points; } #endif // MIDPOINT_CIRCLE
#include "Objets.h" #define TRIANGLE 0 #define QUADRILAT 1 #define POLYGONE 2 using namespace std; Objet::Objet(QVector3D position, QVector3D orientation, QString nomObjet, QString fichierMesh, QString fichierTexture, bool textureUV, int repeatx, int repeaty) { _position = position; _orientation = orientation; _nomObjet = nomObjet; _fichierMesh = fichierMesh; _nombreDeFaces = 0; _nombreDeVectrices = 0; _nombreDeCoordTexture = 0; _nombreDeCoordNormales = 0; _contientNormalVect = false; _isTextureUVMap = textureUV; //sert a preciser si la texture doit etre affichee comme une texture UV map ou non _repeatx = repeatx; _repeaty = repeaty; _fichierTexture = fichierTexture; _chargementMeshOk = false; _chargementTextureOk = false; }
/* * ===================================================================================== * * Filename: processor.cpp * * Description: Super Scalar Processor with centralised pipeline system * * Version: 1.0 * Created: Monday 12 November 2012 06:28:30 IST * Revision: none * Compiler: gcc * * Author: Vaibhav Agarwal , vaisci310@gmail.com * Points Learnt : * * ===================================================================================== */ #include <iostream> #include <fstream> #include <sstream> #include <math.h> #include "processor.h" using namespace std; bool branchStall = false; unsigned int opOpcode = pow(2,26); int lastIns = 0; // ------------------------ Generic functions --------------------------------- // Assumption : The instruction are 32 bit instructions char getType ( unsigned int ins ) { unsigned int opcode = ins / opOpcode; if ( opcode == 2 || opcode == 3 ) return 'J'; else if ( opcode == 0 ) return 'R'; else return 'I'; } // --------------------------- Processor Class Begins ---------------------------------- Processor::Processor() { // Update which ever memory location is necessary memory[0] = 1; memory[1] = 0; memory[2] = 0; memory[3] = 1; memory[4] = 1; memory[5] = 2; memory[6] = 3; memory[7] = 4; } void Processor::addInstruction ( string hexValue ) { unsigned int ins; stringstream ss; ss << std::hex << hexValue; ss >> ins; char type; type = getType( ins ); //cout << " Instruction : " << ins << " " ; switch(type) { case 'J' : { JInstruction *temp1= new JInstruction(ins); jInstruction[jCount] = *temp1; listInstructions[sCount] = &jInstruction[jCount] ; jCount++; sCount++; break; } case 'R' : { RInstruction *temp2 = new RInstruction(ins); rInstruction[rCount] = *temp2; listInstructions[sCount] = &rInstruction[rCount] ; rCount++; sCount++; break; } case 'I' : { IInstruction *temp3 = new IInstruction(ins); iInstruction[iCount] = *temp3; listInstructions[sCount]= &iInstruction[iCount] ; iCount++; sCount++; break; } default: { //cout << "Last instruction read in" << endl; return; } } } /* * Stages in the execution : * * 1. Commit the last instruction in ROB ( Returns bool ) * 2. Execute the instructions present in the FU. ( Returns the list of registers whose values have been changed ) * 5. Dispatch the next set of instructions. ( List of all instructions that are currently in the FU ) * 6. ID - Decode instructions and add them to reservation station. * 7. IF - Fetch the next k instructions. ( New structure - list of instructions , whether in the BTB , PCvalue ) */ void Processor::execute() { newInstr *insList = new newInstr[SIZEOFSTATION]; int index = 0; int wastage = 0; bool commited; int numberInsGot = 0, numberInsDecoded = 0; int execute, numberInsDispatched = 0; //cout << " Ready to execute !! Ins count : " << sCount << endl; while ( ! ( (PC >= sCount) && !commited && !(numberInsDecoded ) && !(numberInsGot) ) ) { commited = reOrderBuffer.commitIns(intRegisterFile , storeBuffer , memory , resStation ); execute = reOrderBuffer.execute( resStation ); numberInsDispatched = resStation.dispatchInstructions ( reOrderBuffer ); numberInsDispatched = resStation.emptySpace(); if ( index == 0 ) numberInsGot = getInstructions ( SIZEOFSTATION , insList ); else numberInsGot = getInstructions ( numberInsDispatched , insList ); numberInsDecoded = decodeInstructions ( insList , numberInsGot ); while ( branchStall ) { commited = reOrderBuffer.commitIns(intRegisterFile , storeBuffer , memory , resStation ); execute = reOrderBuffer.execute ( resStation ); numberInsDispatched += resStation.dispatchInstructions ( reOrderBuffer ); if ( execute != -1 ) { PC = execute; branchStall = false; } } index++; } } int Processor::decodeInstructions ( newInstr * listIns , int numberIns ) { int i = 0; int flag = 0; for ( i = 0 ; i < numberIns ; i++ ) { insInfo returnVal= listIns[i].ins->IDstage ( listIns[i].PC , intRegisterFile , reOrderBuffer ); if ( returnVal.branch ) { resStation.fillReservationStation ( listIns[i].PC , listIns[i].ins , reOrderBuffer , intRegisterFile ); if ( returnVal.nextPC == -1769 ) { branchStall = true; return i+1; } if ( i == numberIns - 1 ) { if ( PC != returnVal.nextPC ) { PC = returnVal.nextPC; flag = 1; break; } } else { if ( returnVal.nextPC != listIns[i+1].PC ) { PC = returnVal.nextPC; flag = 1; break; } } } else resStation.fillReservationStation( listIns[i].PC , listIns[i].ins , reOrderBuffer , intRegisterFile ); } if ( flag ) return i+1; else return i; } // Gets the required number of instructions that can be fit into the reservation station ( which is an argument -> numberIns ) int Processor::getInstructions ( int numberIns , newInstr * listIns ) { int i; for ( i = 0 ; i < numberIns ; i++ ) { if ( PC >= sCount ) break; else { listIns[i].ins = listInstructions[PC]; listIns[i].PC = PC; int branchAddress = btb.getBranchAddress ( PC ); if ( branchAddress == -1 ) PC = PC + 1; else { bool p = branchPredictor.predictBranch( PC ); if ( p ) PC = branchAddress; else PC = PC+1; } } } /* if ( i != 0 ) cout << "Getting Instructions : " << i << endl; */ return i; } void Processor::printDetails () { cout << " Super Scalar processor : " << endl; cout << " No of instructions executed : " << insCount << endl; cout << " No of stalls : " << stalls << endl; cout << " No of cycles : " << cycles << endl; double temp = (double)cycles / (double)insCount; cout << " Cycles per instruction : " << temp << endl; cout << "====================================================================="<<endl; intRegisterFile.printContents(); } /* void Processor::codeRunning() { cout << "_----------------------------------------------------------" << endl; vector<Instruction *>::iterator startIt , endIt; startIt = listInstructions.begin(); endIt = listInstructions.end(); cout << "List of instructions : " << endl; for ( ; startIt != endIt ; startIt++ ) { cout << (*startIt)->instruction << endl; } cout << "List of R instructions : " << endl; vector<RInstruction>::iterator startRIt , endRIt; startRIt = rInstruction.begin(); endRIt = rInstruction.end(); for ( ; startRIt != endRIt ; startRIt++ ) cout << (*startRIt).instruction << endl; cout << "_----------------------------------------------------------" << endl; } */ // TODO : Add the branch instructions to the BTB
#ifndef MySqlConnect_H #define MySqlConnect_H #include "CDL_TCP_Handler.h" #include "CDL_Timer_Handler.h" #include "Packet.h" #include "DLDecoder.h" #define CMD_BACKSVR_HEART 0x0001 //MysqlServerÐÄÌø°ü class MySqlConnect ; class HeartBeatTimer:public CCTimer { public: HeartBeatTimer(){} ; virtual ~HeartBeatTimer() {}; inline void init(MySqlConnect* backsrv){this->backsrv=backsrv;}; private: virtual int ProcessOnTimerOut(); MySqlConnect* backsrv; }; class MySqlHandle: public CDLSocketHandler { public: MySqlHandle(MySqlConnect* server); MySqlHandle(){}; virtual ~MySqlHandle(){ //this->_decode = NULL; }; int OnConnected(); int OnClose(); int OnPacketComplete(const char * data, int len) { pPacket.Copy(data,len); return OnPacketComplete(&pPacket); } int OnPacketComplete(InputPacket* pPacket); CDL_Decoder* CreateDecoder() { return &DLDecoder::getInstance(); } private : MySqlConnect* server; InputPacket pPacket; }; class MySqlConnect { public: static MySqlConnect* getInstance(); virtual ~MySqlConnect(); int connect(const char* ip, short port); int reconnect(); inline bool isActive(){return isConnect;}; inline void setActive(bool b){ this->isConnect = b; if(!b) handler=NULL; }; int Send(InputPacket* inputPacket) { if(handler) return handler->Send(inputPacket->packet_buf(), inputPacket->packet_size()) >=0 ? 0 : -1; else { if(reconnect()==0) { return handler->Send(inputPacket->packet_buf(), inputPacket->packet_size()) >=0 ? 0 : -1; } return -1; } } int Send(OutputPacket* outputPacket) { if(handler) return handler->Send(outputPacket->packet_buf(), outputPacket->packet_size()) >=0 ? 0 : -1; else { if(reconnect()==0) { return handler->Send(outputPacket->packet_buf(), outputPacket->packet_size()) >=0 ? 0 : -1; } return -1; } } int sendHeartBeat(); private: MySqlConnect(); short port; char ip[32]; bool isConnect; MySqlHandle* handler; HeartBeatTimer* heartBeatTimer; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** George Refseth and Patricia Aas */ #include "core/pch.h" #include "adjunct/quick/managers/DesktopTransferManager.h" #include "modules/inputmanager/inputmanager.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #include "modules/viewers/viewers.h" #include "modules/locale/locale-enum.h" #include "modules/locale/oplanguagemanager.h" #include "modules/url/url_tags.h" #include "modules/util/opfile/opfile.h" #include "modules/formats/url_dfr.h" #include "modules/cache/cache_common.h" #include "modules/cache/cache_int.h" #include "modules/windowcommander/OpTransferManager.h" class DelayedManageAction : public OpTimerListener { public: void Start() { m_timer.SetTimerListener( this ); m_timer.Start(100); // ms } void OnTimeOut(OpTimer* timer) { g_input_manager->InvokeAction(OpInputAction::ACTION_MANAGE, g_pcui->GetIntegerPref(PrefsCollectionUI::TransWinActivateOnNewTransfer) == 2, UNI_L("transfers")); } private: OpTimer m_timer; }; #ifdef DESKTOP_ASYNC_ICON_LOADER /* static */ OP_STATUS OpAsyncFileBitmapLoader::Create(OpAsyncFileBitmapLoader** new_asyncfilebitmaploader) { OP_ASSERT(new_asyncfilebitmaploader != NULL); *new_asyncfilebitmaploader = OP_NEW(DesktopOpAsyncFileBitmapLoader, ()); if(*new_asyncfilebitmaploader == NULL) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } DesktopOpAsyncFileBitmapLoader::~DesktopOpAsyncFileBitmapLoader() { g_main_message_handler->UnsetCallBacks(this); } OP_STATUS DesktopOpAsyncFileBitmapLoader::Init(OpAsyncFileBitmapHandlerListener *listener) { m_listener = listener; g_main_message_handler->SetCallBack(this, MSG_QUICK_LOAD_ICONS, 0); return OpStatus::OK; } void DesktopOpAsyncFileBitmapLoader::Start(OpVector<TransferItemContainer>& transferitems) { OP_ASSERT(transferitems.GetCount()); if(transferitems.GetCount()) { for(UINT32 n = 0; n < transferitems.GetCount(); n++) { TransferItemContainer *item = transferitems.Get(n); if(item->NeedToLoadIcon()) { OpAutoPtr<OpString> filename(OP_NEW(OpString, ())); if(filename.get() && item->GetAssociatedItem()) { if(OpStatus::IsSuccess(filename->Set(*item->GetAssociatedItem()->GetStorageFilename())) && OpStatus::IsSuccess(m_filenames.Add(filename.get()))) filename.release(); } } } g_main_message_handler->PostMessage(MSG_QUICK_LOAD_ICONS,(MH_PARAM_1)this,0); } } void DesktopOpAsyncFileBitmapLoader::LoadItemIcons() { if (m_filenames.GetCount() > 0) { // find the matching transfer item. This also ensures that if the user // removes an item while we're getting icons, we'll just ignore it TransferItemContainer *item = g_desktop_transfer_manager->FindTransferItemContainerFromFilename(*m_filenames.Get(0)); if(item && item->NeedToLoadIcon()) { if(item->LoadIconBitmap()) m_listener->OnBitmapLoaded(item); item->SetHasTriedToLoadIcon(); } m_filenames.Delete(0, 1); } // leave the leftover work to next round if not finished if(!m_filenames.GetCount()) { m_listener->OnBitmapLoadingDone(); } else g_main_message_handler->PostMessage(MSG_QUICK_LOAD_ICONS,(MH_PARAM_1)this,0); } void DesktopOpAsyncFileBitmapLoader::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { switch(msg) { case MSG_QUICK_LOAD_ICONS: LoadItemIcons(); break; default: OP_ASSERT(FALSE); } } #endif // DESKTOP_ASYNC_ICON_LOADER /*********************************************************************************** ** ** ** ***********************************************************************************/ DesktopTransferManager::DesktopTransferManager() : m_timer(NULL), m_delayed_manage_action(0), m_new_transfers_done(FALSE), m_swap_column(0), m_icon_loader(NULL), m_bitmap_loading_in_progress(false) { m_addtransferitemsontop = g_pcui->GetIntegerPref(PrefsCollectionUI::TransferItemsAddedOnTop); g_main_message_handler->SetCallBack(this, MSG_QUICK_LOAD_TRANSFERS_RESCUE_FILE, 0); } OP_STATUS DesktopTransferManager::Init() { RETURN_IF_ERROR(g_transferManager->AddTransferManagerListener(this)); RETURN_IF_ERROR(OpAsyncFileBitmapLoader::Create(&m_icon_loader)); RETURN_IF_ERROR(m_icon_loader->Init(this)); // delay loading the rescue file until after startup. This particular operation is slow if the user has installed // shell extensions, so let's not let that delay showing the main window - pettern 24.08.2010 g_main_message_handler->PostDelayedMessage(MSG_QUICK_LOAD_TRANSFERS_RESCUE_FILE, (MH_PARAM_1)this, 0, 100); return OpStatus::OK; } /*********************************************************************************** ** ** ** ***********************************************************************************/ DesktopTransferManager::~DesktopTransferManager() { g_transferManager->RemoveTransferManagerListener(this); UINT32 i; // make sure we're not listener on any items. Fixes bug DSK-240287 for(i = 0; i < m_transferitems.GetCount(); i++) { TransferItemContainer* tic = m_transferitems.Get(i); if(tic) { OpTransferItem* item = tic->GetAssociatedItem(); if(item) { item->SetTransferListener(NULL); } } } if(m_timer) { OP_DELETE(m_timer); } OP_DELETE(m_delayed_manage_action); g_main_message_handler->UnsetCallBacks(this); OP_DELETE(m_icon_loader); } /*********************************************************************************** ** ** ** ***********************************************************************************/ TransferItemContainer* DesktopTransferManager::FindTransferItemContainerFromFilename(OpStringC filename) { for(INT32 n = 0; n < GetItemCount(); n++) { TransferItemContainer *item = static_cast<TransferItemContainer *>(GetItemByPosition(n)); if(item->GetAssociatedItem()->GetStorageFilename()->Compare(filename) == 0) { return item; } } return NULL; } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::SetNewTransfersDone(BOOL new_transfers_done) { if (new_transfers_done == m_new_transfers_done) return; m_new_transfers_done = new_transfers_done; for (UINT32 i = 0; i < m_listeners.GetCount(); i++) { m_listeners.Get(i)->OnNewTransfersDone(); } } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::OnTimeOut(OpTimer* timer) { switch(m_swap_column) { case 0: { m_swap_column = 1; m_timer->Start(TOGGLE_COLUMN_SHOW_SPEED_MS); } break; case 1: { m_swap_column = 2; m_timer->Start(TOGGLE_COLUMN_SHOW_TIMELEFT_MS); } break; case 2: { m_swap_column = 0; m_timer->Start(TOGGLE_COLUMN_SHOW_TRANSFERRED_SIZE_MS); } break; default: { // No op? } } BroadcastItemChanged(-1); if(!HasActiveTransfer()) //if no more transfers, kill the timers { m_swap_column = 0; OP_DELETE(m_timer); m_timer = NULL; //start new timer when DesktopTransferManager::OnProgress status changes to TRANSFER_PROGRESS } } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::OnProgress(OpTransferItem* transferItem, TransferStatus status) { INT32 model_pos = GetModelIndex(transferItem); TransferItemContainer* tic = m_transferitems.Get(model_pos); if(tic) { tic->SetStatus(status); } BroadcastItemChanged(model_pos); if(g_input_manager) g_input_manager->UpdateAllInputStates(); for (UINT32 i = 0; i < m_listeners.GetCount(); i++) { m_listeners.Get(i)->OnTransferProgress(tic, status); } if(status == OpTransferListener::TRANSFER_PROGRESS && !m_timer) { if (!(m_timer = OP_NEW(OpTimer, ()))) return; m_timer->SetTimerListener(this); m_timer->Start(TOGGLE_COLUMN_SHOW_TRANSFERRED_SIZE_MS); } } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::OnReset(OpTransferItem* transferItem) { INT32 model_pos = GetModelIndex(transferItem); TransferItemContainer* tic = m_transferitems.Get(model_pos); tic->ResetStatus(); } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::OnRedirect(OpTransferItem* transferItem, URL* redirect_from, URL* redirect_to) { if(redirect_to != NULL) { OpStatus::Ignore(redirect_to->LoadToFile(((TransferItem *)transferItem)->GetStorageFilename()->CStr())); } } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::AddTransferListener(TransferListener* listener) { m_listeners.Add(listener); } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::RemoveTransferListener(TransferListener* listener) { INT32 pos = m_listeners.Find(listener); if (pos != -1) { m_listeners.Remove(pos); } } /*********************************************************************************** ** ** ** ***********************************************************************************/ INT32 DesktopTransferManager::GetModelIndex(OpTransferItem* transferItem) { for(int i = 0; i < GetItemCount(); i++) { if(m_transferitems.Get(i)->GetAssociatedItem() == (TransferItem*)transferItem) { return i; } } return -1; } /*********************************************************************************** ** ** ** ***********************************************************************************/ UINT32 DesktopTransferManager::GetMaxTimeRemaining(UINT32* remaining_transfers) { UINT32 maxtime = 0; UINT32 remaining_count = 0; for(int i = 0; i < GetItemCount(); i++) { if(m_transferitems.Get(i)->GetStatus() == TRANSFER_PROGRESS) { remaining_count++; TransferItem* assoc = m_transferitems.Get(i)->GetAssociatedItem(); UINT32 timeestimate = assoc ? assoc->GetTimeEstimate() : 0; if(timeestimate > maxtime && timeestimate < INT32_MAX) // timeestimate above INT32_MAX is unknown so skip it { maxtime = timeestimate; } } } if (remaining_transfers) *remaining_transfers = remaining_count; return maxtime; } /*********************************************************************************** ** ** Get information about the total and download bytes for the active downloads ** ***********************************************************************************/ void DesktopTransferManager::GetFilesSizeInformation(OpFileLength& downloaded_size, OpFileLength& total_sizes, UINT32* remaining_transfers) { UINT32 remaining_count = 0; downloaded_size = total_sizes = 0; for(int i = 0; i < GetItemCount(); i++) { if(m_transferitems.Get(i)->GetStatus() == TRANSFER_PROGRESS) { remaining_count++; TransferItem *item = m_transferitems.Get(i)->GetAssociatedItem(); downloaded_size += item->GetHaveSize(); total_sizes += item->GetSize(); } } if (remaining_transfers) *remaining_transfers = remaining_count; } /*********************************************************************************** ** ** ** ***********************************************************************************/ BOOL DesktopTransferManager::OpenItemByID(INT32 id, BOOL open_folder) { for(int i = 0; i < GetItemCount(); i++) { if(m_transferitems.Get(i)->GetID() == id) { m_transferitems.Get(i)->Open(open_folder); return TRUE; } } return FALSE; } /*********************************************************************************** ** ** ** ***********************************************************************************/ BOOL DesktopTransferManager::OnTransferItemAdded(OpTransferItem* transferItem, BOOL is_populating, double last_speed) { if (!transferItem->GetShowTransfer()) { return FALSE; } transferItem->SetTransferListener(this); TransferItemContainer* tic = OP_NEW(TransferItemContainer, (last_speed)); if (!tic) return FALSE; tic->SetAssociatedItem((TransferItem*)transferItem); if(((TransferItem*)transferItem)->GetType() == TransferItem::TRANSFERTYPE_PEER2PEER_DOWNLOAD) { tic->SetResumableState(Probably_Resumable); } else { tic->SetResumableState((URL_Resumable_Status) transferItem->GetURL()->GetAttribute(URL::KResumeSupported)); } tic->SetParentContainer(this); OP_STATUS status = tic->SetHandlerApplication(); // OP_ASSERT(OpStatus::IsSuccess(status) || is_populating); OpStatus::Ignore(status); int insertposition = 0; if(m_addtransferitemsontop && !is_populating) //if is_populating then add on bottom always { m_transferitems.Insert(insertposition, (TransferItemContainer*)tic); } else { insertposition = GetItemCount(); m_transferitems.Add((TransferItemContainer*)tic); } BroadcastItemAdded(insertposition); if(!is_populating) // the model is being built { for (UINT32 i = 0; i < m_listeners.GetCount(); i++) { m_listeners.Get(i)->OnTransferAdded(tic); } if(g_pcui->GetIntegerPref(PrefsCollectionUI::TransWinActivateOnNewTransfer)) { // Delay activation of OpInputAction::ACTION_MANAGE for now. There are a // number of lost-keyboard-focus (one is cross platform) problems when we open // the transfer window right after closing the file dialog and/or download // dialog. The system will after the dialog closes return focus to the window // that had it (when activation events arrive) and problems arise when there is // suddenly a new window that should have focus (or not, depeding if it is // opened in the background). [espen 2006-11-08] if( !m_delayed_manage_action ) m_delayed_manage_action = OP_NEW(DelayedManageAction, ()); if( m_delayed_manage_action ) m_delayed_manage_action->Start(); } } return TRUE; } /*********************************************************************************** ** ** ** ***********************************************************************************/ void DesktopTransferManager::OnTransferItemRemoved(OpTransferItem* transferItem) { INT32 model_pos = GetModelIndex(transferItem); if(model_pos != -1) { BroadcastItemRemoving(model_pos); TransferItemContainer* tic = m_transferitems.Remove(model_pos); for (UINT32 i = 0; i < m_listeners.GetCount(); i++) { m_listeners.Get(i)->OnTransferRemoved(tic); } OP_DELETE(tic); BroadcastItemRemoved(model_pos); } } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS DesktopTransferManager::GetColumnData(ColumnData* column_data) { Str::LocaleString str(Str::NOT_A_STRING); switch(column_data->column) { case 0: { // progressindicator str = Str::S_STATUS; break; } case 1: { // name str = Str::SI_IDSTR_TRANSWIN_NAME_COL; break; } case 2: { // size str = Str::SI_IDSTR_TRANSWIN_SIZE_COL; break; } case 3: { // progress str = Str::SI_IDSTR_TRANSWIN_PROGRESS_COL; break; } case 4: { // time str = Str::SI_IDSTR_TRANSWIN_TIME_COL; break; } case 5: { // speed str = Str::SI_IDSTR_TRANSWIN_SPEED_COL; break; } case 6: { // toggled str = Str::S_TRANSWIN_INFO_COL; break; } default: { return OpStatus::OK; } } return g_languageManager->GetString(str, column_data->text); } /*********************************************************************************** ** ** ** ***********************************************************************************/ #ifdef ACCESSIBILITY_EXTENSION_SUPPORT OP_STATUS DesktopTransferManager::GetTypeString(OpString& type_string) { return g_languageManager->GetString(Str::M_VIEW_HOTLIST_MENU_TRANSFERS, type_string); } #endif OpTreeModelItem* DesktopTransferManager::GetItemByPosition(INT32 position) { return m_transferitems.Get(position); } void DesktopTransferManager::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2) { switch(msg) { case MSG_QUICK_LOAD_TRANSFERS_RESCUE_FILE: OpStatus::Ignore(g_transferManager->SetRescueFileName(UNI_L("download.dat"))); break; default: OP_ASSERT(FALSE); } } void DesktopTransferManager::StartLoadIcons() { if(!m_bitmap_loading_in_progress) { m_bitmap_loading_in_progress = true; m_icon_loader->Start(m_transferitems); } } void DesktopTransferManager::OnBitmapLoadingDone() { m_bitmap_loading_in_progress = false; } void DesktopTransferManager::OnBitmapLoaded(TransferItemContainer *item) { INT32 model_pos = GetModelIndex(item->GetAssociatedItem()); if(model_pos != -1) { BroadcastItemChanged(model_pos, FALSE); } }
#pragma once #include "ComputationNode.hpp" template<class Type> struct VariableNode : ComputationNode<Type> { void backPropagationPass() override { } };
// PollingCtl.cpp : Implementation of the CPollingCtrl ActiveX Control class. #include "stdafx.h" #include "NetFind.h" #include "PollingCtl.h" #include "PollingPpg.h" #include "ZyFunc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CPollingCtrl, COleControl) ///////////////////////////////////////////////////////////////////////////// // Message map BEGIN_MESSAGE_MAP(CPollingCtrl, COleControl) //{{AFX_MSG_MAP(CPollingCtrl) ON_WM_TIMER() //}}AFX_MSG_MAP ON_MESSAGE(WM_USER_POLL_FAIL, OnPollFail) ON_MESSAGE(OCM_COMMAND, OnOcmCommand) ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // Dispatch map BEGIN_DISPATCH_MAP(CPollingCtrl, COleControl) //{{AFX_DISPATCH_MAP(CPollingCtrl) DISP_FUNCTION(CPollingCtrl, "BeginPoll", BeginPoll, VT_EMPTY, VTS_NONE) DISP_FUNCTION(CPollingCtrl, "StopPolling", StopPolling, VT_EMPTY, VTS_NONE) DISP_STOCKPROP_CAPTION() DISP_STOCKPROP_APPEARANCE() DISP_STOCKPROP_BORDERSTYLE() DISP_STOCKPROP_ENABLED() DISP_STOCKPROP_FONT() //}}AFX_DISPATCH_MAP DISP_FUNCTION_ID(CPollingCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE) END_DISPATCH_MAP() ///////////////////////////////////////////////////////////////////////////// // Event map BEGIN_EVENT_MAP(CPollingCtrl, COleControl) //{{AFX_EVENT_MAP(CPollingCtrl) EVENT_CUSTOM("AbortPoll", FireAbortPoll, VTS_I4) EVENT_CUSTOM("PollFail", FirePollFail, VTS_I2) EVENT_STOCK_CLICK() //}}AFX_EVENT_MAP END_EVENT_MAP() ///////////////////////////////////////////////////////////////////////////// // Property pages // TODO: Add more property pages as needed. Remember to increase the count! BEGIN_PROPPAGEIDS(CPollingCtrl, 1) PROPPAGEID(CPollingPropPage::guid) END_PROPPAGEIDS(CPollingCtrl) ///////////////////////////////////////////////////////////////////////////// // Initialize class factory and guid IMPLEMENT_OLECREATE_EX(CPollingCtrl, "NETFIND.PollingCtrl.1", 0xd44628ba, 0x9282, 0x11d3, 0xb1, 0x9b, 0, 0, 0xe8, 0x77, 0x80, 0xf5) ///////////////////////////////////////////////////////////////////////////// // Type library ID and version IMPLEMENT_OLETYPELIB(CPollingCtrl, _tlid, _wVerMajor, _wVerMinor) ///////////////////////////////////////////////////////////////////////////// // Interface IDs const IID BASED_CODE IID_DPolling = { 0xd44628b8, 0x9282, 0x11d3, { 0xb1, 0x9b, 0, 0, 0xe8, 0x77, 0x80, 0xf5 } }; const IID BASED_CODE IID_DPollingEvents = { 0xd44628b9, 0x9282, 0x11d3, { 0xb1, 0x9b, 0, 0, 0xe8, 0x77, 0x80, 0xf5 } }; ///////////////////////////////////////////////////////////////////////////// // Control type information static const DWORD BASED_CODE _dwPollingOleMisc = OLEMISC_ACTIVATEWHENVISIBLE | OLEMISC_SETCLIENTSITEFIRST | OLEMISC_INSIDEOUT | OLEMISC_CANTLINKINSIDE | OLEMISC_RECOMPOSEONRESIZE; IMPLEMENT_OLECTLTYPE(CPollingCtrl, IDS_POLLING, _dwPollingOleMisc) ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::CPollingCtrlFactory::UpdateRegistry - // Adds or removes system registry entries for CPollingCtrl BOOL CPollingCtrl::CPollingCtrlFactory::UpdateRegistry(BOOL bRegister) { // TODO: Verify that your control follows apartment-model threading rules. // Refer to MFC TechNote 64 for more information. // If your control does not conform to the apartment-model rules, then // you must modify the code below, changing the 6th parameter from // afxRegApartmentThreading to 0. if (bRegister) return AfxOleRegisterControlClass( AfxGetInstanceHandle(), m_clsid, m_lpszProgID, IDS_POLLING, IDB_POLLING, afxRegApartmentThreading, _dwPollingOleMisc, _tlid, _wVerMajor, _wVerMinor); else return AfxOleUnregisterClass(m_clsid, m_lpszProgID); } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::CPollingCtrl - Constructor CPollingCtrl::CPollingCtrl() { InitializeIIDs(&IID_DPolling, &IID_DPollingEvents); // TODO: Initialize your control's instance data here. } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::~CPollingCtrl - Destructor CPollingCtrl::~CPollingCtrl() { // TODO: Cleanup your control's instance data here. } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::OnDraw - Drawing function void CPollingCtrl::OnDraw( CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid) { DoSuperclassPaint(pdc, rcBounds); } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::DoPropExchange - Persistence support void CPollingCtrl::DoPropExchange(CPropExchange* pPX) { ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor)); COleControl::DoPropExchange(pPX); // TODO: Call PX_ functions for each persistent custom property. } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::OnResetState - Reset control to default state void CPollingCtrl::OnResetState() { COleControl::OnResetState(); // Resets defaults found in DoPropExchange // TODO: Reset any other control state here. } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::AboutBox - Display an "About" box to the user void CPollingCtrl::AboutBox() { CDialog dlgAbout(IDD_ABOUTBOX_POLLING); dlgAbout.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::PreCreateWindow - Modify parameters for CreateWindowEx BOOL CPollingCtrl::PreCreateWindow(CREATESTRUCT& cs) { cs.lpszClass = _T("BUTTON"); return COleControl::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::IsSubclassedControl - This is a subclassed control BOOL CPollingCtrl::IsSubclassedControl() { return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl::OnOcmCommand - Handle command messages LRESULT CPollingCtrl::OnOcmCommand(WPARAM wParam, LPARAM lParam) { #ifdef _WIN32 WORD wNotifyCode = HIWORD(wParam); #else WORD wNotifyCode = HIWORD(lParam); #endif // TODO: Switch on wNotifyCode here. return 0; } ///////////////////////////////////////////////////////////////////////////// // CPollingCtrl message handlers void CPollingCtrl::BeginPoll() { int i; Read_TimeConfig(TimeSet,TimeSetNo); Read_PollingUse(TimeSet,TimeSetNo,IpGroup,Timer); for(i=0;i<TimeSetNo;i++) SetTimer(i,Timer[i].TimeSet,NULL);//定义的定时器标志从0到TimeSetNo } UINT ThreadPing(LPVOID pParam) { if(Thread_In) Sleep(10); else { PingStatus* pingstatus; Thread_In=true; PCIP * pcip=(PCIP *)pParam; for (int i=0;i<pcip->IPNO;i++) { /* if(Ping(pcip->IP[i])==0)//没有PING通 { CWinThread* p; p=new CWinThread; p=AfxBeginThread(Update_PollingUse,pcip->IP[i]); SendMessage(pcip->hWnd,WM_USER_POLL_FAIL,pcip->IPNO,0); } */ if(Ping(pcip->IP[i])==0)//没有PING通 { pingstatus=new PingStatus; strcpy(pingstatus->IP,pcip->IP[i]); pingstatus->PingTong=false; } else { pingstatus=new PingStatus; strcpy(pingstatus->IP,pcip->IP[i]); pingstatus->PingTong=true; } CWinThread* p; p=new CWinThread; p=AfxBeginThread(Update_PollingUse,pingstatus); SendMessage(pcip->hWnd,WM_USER_POLL_FAIL,pcip->IPNO,0); } Thread_In=false; } return 1; } void CPollingCtrl::OnTimer(UINT nIDEvent) { //In_Time全局变量 if(!In_Time) { In_Time=true; int i; CWinThread* p; PCIP *pcip;//{char* IP[100]; int IPNO; HWND hWnd;}传给线程该时间段轮寻的IP组及控件的句柄 pcip=new PCIP; for(i=0;i<Timer[nIDEvent].IpNoForThis;i++) { pcip->IP[i]=new char[20]; strcpy(pcip->IP[i],IpGroup[Timer[nIDEvent].Pointer][i]); } pcip->IPNO=i; hWnd=GetSafeHwnd();//CWnd::GetSafeHwnd()获得该类的窗口句柄 pcip->hWnd=hWnd; p=new CWinThread; p=AfxBeginThread(ThreadPing,pcip); In_Time=false; } else FireAbortPoll(Timer[nIDEvent].TimeSet); COleControl::OnTimer(nIDEvent); } void CPollingCtrl::StopPolling() { for(int i=0;i<TimeSetNo;i++) KillTimer(i); } LRESULT CPollingCtrl::OnPollFail(WPARAM wParam, LPARAM lParam) { UINT IpNo=LOWORD(wParam); FirePollFail(IpNo); return 1; }
/* g++ -Wall opencv_exempleCPP.cpp -lopencv_core -lopencv_highgui -lopencv_imgproc -std=c++11 */ #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> #include <math.h> #include <complex> #include <time.h> #include <fstream> using namespace std; using namespace cv; Mat image; #define V 4 #define ITER 250 //nombre de thread #define Nb_Thread 10 // mutex pour protéger VALEUR pthread_mutex_t mutex; // taille de l'image #define HAUT 800 #define LARG 800 //declaration des parametres de la couleur void HSVtoRGB( unsigned char *r, unsigned char *g, unsigned char *b, unsigned char h, unsigned char s, unsigned char v ); // valeur reel et imaginaire de la fracttale std::complex<long double> c( 0.0285,0.013); long double reel=0.285,imaginaire=0.01; double X = 0; double Y = 0; // déclarer la fonction pour la creation de la fractal void *CalculFractaleJulia(void *arg); int main( int argc, char** argv ) { double temps; clock_t t1, t2; pthread_t thread_f[Nb_Thread]; image=cv::Mat(LARG, HAUT, CV_8UC3); refresh: for(int i=0;i< Nb_Thread;i++){ t1 = clock(); pthread_create (&thread_f[i], NULL, CalculFractaleJulia, (void*)NULL); t2 = clock(); temps = ((double)(t2-t1)*1000/CLOCKS_PER_SEC); } cout<<"le temps d'execution "<< temps <<"sec "<<endl; ofstream fichier("resultat.dat", ios::app); if(fichier) { //fichier << "le temps " << duree<< endl; fichier<< " #nombres de threads #temps d'execution en sec\n"<< " "<<Nb_Thread<<" "<< temps << endl; fichier.close(); } else { cout << "Impossible d'ouvrir le fichier !" << endl; } //Gestion des entrées while(char key = cvWaitKey(66)) { switch(key){ case 'a': // Modification de la constante de la fractale reel = reel + 0.1; goto refresh; break; case 'z': reel = reel - 0.1; goto refresh; break; case 'o': imaginaire = imaginaire + 0.1; goto refresh; break; case 'p': imaginaire = imaginaire - 0.05; goto refresh; break; //Utilisation de Zoom/Dezoom case 'd': X -= 100; Y -= 100; goto refresh; break; case 's': X += 100; Y += 100; goto refresh; break; default: break; } if (key == 'q') break; imshow("fractale image",image ); } // ferme la fenêtre cvDestroyWindow("fractale image"); return 0; } // fractale void *CalculFractaleJulia(void *arg){ std::complex<long double> c (reel,imaginaire); for(int x=0;x<LARG;x++){ for(int y=0;y<HAUT;y++){ long double newX=((long double)((long double)x-((long double)((LARG)-X)/2))/((long double)((LARG)-X)/2)); long double newY=((long double)((long double)y-((long double)((HAUT)-Y)/2))/((long double)((HAUT)-Y)/2)); std::complex<long double> point(newY,newX); int iteration=0; long double norm = std::norm(point); while(iteration<ITER && norm<V){ point=(point*point)+c; norm = std::norm(point); iteration++; } if(iteration==ITER && norm<V){ image.at<Vec3b>(x,y)[0]=0; image.at<Vec3b>(x,y)[1]=0; image.at<Vec3b>(x,y)[2]=0; } else{ int couleur=(int)((float)iteration/(float)ITER*255); unsigned char brillance=150; unsigned char saturation=150; unsigned char r,g,b; // definition de la couleur de l'image HSVtoRGB( & r, & g, & b, couleur, brillance, saturation ); image.at<Vec3b>(x,y)[0]=r; image.at<Vec3b>(x,y)[1]=g; image.at<Vec3b>(x,y)[2]=b; } } } return NULL; } // fonction de convertion de HSV A RGB void HSVtoRGB( unsigned char *r, unsigned char *g, unsigned char *b, unsigned char h, unsigned char s, unsigned char v ) { unsigned char i,f, p,q, t; if (s == 0) { *r = 0; *g = 0; *b = 0; } else { i = h / 100;//43 f = (h - (i * 100)) * 9;//6 p = (v * (22 - s)) >> 8; q = (v * (185 - ((s * f) >> 8))) >> 8; t = (v * (255 - ((s * (255 - f)) >> 8))) >> 8; switch (i) { case 0: *r = v; *g = t; *b = p; break; case 1: *r = q; *g = v; *b = p; break; case 2: *r = p; *g = v; *b = t; break; case 3: *r = p; *g = q; *b = v; break; case 4: *r = t; *g = p; *b = v; break; default: *r = v; *g = p; *b = q; break; } } return; } unsigned char randomVal(){ return (unsigned char)(rand()%360); }
#include<bits/stdc++.h> using namespace std; struct Contest{ public: int sc, ns, originalIndex; }; bool accordingtoScore(Contest a, Contest b){ return (a.sc < b.sc); } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int p, s, currentN; vector < pair <int,int> > result; //for storing (n,i) for final sorting cin >> p >> s; for(int i = 0; i < p; i++) { Contest cont[s]; for(int j = 0; j < s; j++) cin >> cont[j].sc; for(int j = 0; j < s; j++) cin >> cont[j].ns; sort(cont, cont + s, accordingtoScore); currentN = 0; for(int j = 0; j < s - 1;j++){ if(cont[j].ns > cont[j+ 1].ns) currentN++; } result.push_back(make_pair(currentN, i + 1)); } sort(result.begin(), result.end()); for(int i = 0; i < p; i++) cout << result[i].second<< "\n"; }
#pragma once #include <vector> #include <algorithm> using namespace std; class Listener { public: virtual void update(int msg) = 0; }; class DataSource { protected: vector<Listener*> listeners; public: void registerListener(Listener* listener); void removeListener(Listener* listener); void notifyListeners(int msg); };
// NOTE: this doesn't really test anything except that things compile #include "gtest/gtest.h" #include "opennwa/Nwa.hpp" #include "opennwa/nwa_pds/conversions.hpp" #include "Tests/unit-tests/Source/opennwa/fixtures.hpp" using namespace wali::wpds; namespace opennwa { namespace nwa_pds { TEST(opennwa$nwa_pds$$WpdsToNwa, compilationTest) { WPDS wpds; NwaRefPtr nwa = WpdsToNwa(wpds); } } }
#include "DynamicObjectLogicCalculator.h" DynamicObjectLogicCalculator::DynamicObjectLogicCalculator() { } DynamicObjectLogicCalculator::~DynamicObjectLogicCalculator() { } void DynamicObjectLogicCalculator::correctStepsDueToWallCollisions() { //in case of collision we stop the movement in that direction float stepX,stepY; m_dynamicObjectModel->getStep(&stepX,&stepY); if(collidesOnRight() == true && stepX > 0) {stepX = 0;} if(collidesOnLeft() == true && stepX < 0) {stepX = 0;} if(collidesOnCeiling() == true && stepY > 0 ) {stepY = 0;} if(collidesOnFloor() == true && stepY < 0 ) {stepY = 0;} m_dynamicObjectModel->setStep(stepX,stepY); } std::pair<float,float> DynamicObjectLogicCalculator::computeDirection(float destinationX, float destinationY) { float dynamicObjectX = m_dynamicObjectModel->getTerrainPosition()[0]; float dynamicObjectY = m_dynamicObjectModel->getTerrainPosition()[1]; float hypo = std::sqrtf( (dynamicObjectX-destinationX)* (dynamicObjectX-destinationX) + (dynamicObjectY-destinationY)* (dynamicObjectY-destinationY) ); float stepX = (destinationX-dynamicObjectX)/hypo; float stepY = (destinationY-dynamicObjectY)/hypo; return std::make_pair(stepX,stepY); } void DynamicObjectLogicCalculator::computeAndSetDirection(float destinationX, float destinationY) { std::pair<float,float> directions = computeDirection(destinationX, destinationY); m_dynamicObjectModel->setStep(directions.first,directions.second); } void DynamicObjectLogicCalculator::setMoveAction() { float stepX; float stepY; m_dynamicObjectModel->getStep(&stepX,&stepY); //the following sets the action according to the angle between the dynamicObject and the steps direction //for this we devide 2pi radians into pi/4 rad slices starting at +pi/8 rads. //We compare stepX to the cos of the angle and we look at the sign of stepY to find out if //The click took part over the dynamicObject or under it. if(stepX > 0.92387953251) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_RIGHT); } else if(stepX > 0.38268343236 && stepX<= 0.92387953251) { if(stepY > 0) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_UP_RIGHT); } else { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_DOWN_RIGHT); } } else if( stepX > -0.38268343236 && stepX <= 0.38268343236) { if(stepY > 0) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_UP); } else { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_DOWN); } } else if(stepX > -0.92387953251 && stepX<= -0.38268343236) { if(stepY > 0) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_UP_LEFT); } else { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_DOWN_LEFT); } } else if (stepX <= -0.92387953251) { m_dynamicObjectModel->setAction(DynamicObjectModel::DYNAMIC_OBJECT_ACTION_MOVE_LEFT); } } bool DynamicObjectLogicCalculator::collidesOnRight() { //get dynamicObject logical location int dynamicObjectX = m_dynamicObjectModel->getTerrainPosition()[0]; int dynamicObjectY = m_dynamicObjectModel->getTerrainPosition()[1]; //get the right position of the sprite in logical position int xRightWall = m_dynamicObjectModel->getTerrainPosition()[0] + (m_dynamicObjectModel->getPixelWidth()/PIXELS_PER_METER)/2; //get reference tile x and y int tile_x = (xRightWall) / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = dynamicObjectY / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of vertical tiles in which the dynamicObject can be divided int numVerticalTiles = (m_dynamicObjectModel->getPixelHeight()/m_levelModel->getTileSetTileHeight()) ; for(int verticalTile = 0 ; verticalTile < numVerticalTiles ; verticalTile++) { //check for solidity of tile matching right border if(m_levelModel->getTileSolidity(tile_x ,tile_y + verticalTile) == 9) {return true;} } return false; } bool DynamicObjectLogicCalculator::collidesOnLeft() { //get dynamicObject logical location int dynamicObjectX = m_dynamicObjectModel->getTerrainPosition()[0]; int dynamicObjectY = m_dynamicObjectModel->getTerrainPosition()[1]; //get the right position of the sprite in logical position int xLeftWall = m_dynamicObjectModel->getTerrainPosition()[0] - (m_dynamicObjectModel->getPixelWidth()/PIXELS_PER_METER)/2; //get reference tile x and y int tile_x = (xLeftWall) / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = dynamicObjectY / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of vertical tiles in which the dynamicObject can be divided int numVerticalTiles = (m_dynamicObjectModel->getPixelHeight()/m_levelModel->getTileSetTileHeight()) ; for(int verticalTile = 0 ; verticalTile < numVerticalTiles ; verticalTile++) { if(m_levelModel->getTileSolidity(tile_x ,tile_y + verticalTile) == 9) {return true;} } return false; } bool DynamicObjectLogicCalculator::collidesOnCeiling() { int dynamicObjectX = m_dynamicObjectModel->getTerrainPosition()[0]; float yCeiling= m_dynamicObjectModel->getTerrainPosition()[1] + (m_levelModel->getTileSetTileWidth()/PIXELS_PER_METER)/2; //get reference tile x and y int tile_x = dynamicObjectX / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = yCeiling / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of horizontal tiles in which the dynamicObject can be divided int numHorizontalTiles = (m_dynamicObjectModel->getPixelWidth()/m_levelModel->getTileSetTileWidth()) ; if( (dynamicObjectX % ((int)(m_levelModel->getTileSetTileWidth()/PIXELS_PER_METER)) ) != 0) numHorizontalTiles++; //check using only central tiles int i=0; if(numHorizontalTiles >2) { i =1; numHorizontalTiles--; } else { numHorizontalTiles = 1; } while( (i<numHorizontalTiles)) { if(m_levelModel->getTileSolidity(tile_x + i,tile_y) == 9) {return true;} i++; } return false; } bool DynamicObjectLogicCalculator::collidesOnFloor() { float dynamicObjectX = m_dynamicObjectModel->getTerrainPosition()[0]; //we use tileset tile width to correct the collision on purpose. Otherwise the player might get stuck when path-walking //This probably should be done differently for the other dynamicObjects. float yFloor= m_dynamicObjectModel->getTerrainPosition()[1] - (m_levelModel->getTileSetTileHeight()/PIXELS_PER_METER)/2; //get reference tile x and y int tile_x = dynamicObjectX / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = yFloor / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of horizontal tiles in which the dynamicObject can be divided int numHorizontalTiles = (m_dynamicObjectModel->getPixelWidth()/m_levelModel->getTileSetTileWidth()) ; if( ((int)dynamicObjectX % ((int)(m_levelModel->getTileSetTileWidth()/PIXELS_PER_METER)) ) != 0) numHorizontalTiles++; //check using only central tiles int i=0; if(numHorizontalTiles >2) { i =1; numHorizontalTiles--; } else { numHorizontalTiles = 1; } while( (i<numHorizontalTiles)) { if(m_levelModel->getTileSolidity(tile_x + i,tile_y) == 9) {return true;} i++; } return false; } bool DynamicObjectLogicCalculator::collides(const AvatarModel::Rect& rect) { return (((m_dynamicObjectModel->getRect().left>=rect.left) && (m_dynamicObjectModel->getRect().left<=rect.right) && (m_dynamicObjectModel->getRect().bottom<=rect.bottom) && (m_dynamicObjectModel->getRect().top>=rect.bottom)) || ((m_dynamicObjectModel->getRect().left<=rect.left) && (m_dynamicObjectModel->getRect().right>=rect.left) && (m_dynamicObjectModel->getRect().bottom<=rect.bottom) && (m_dynamicObjectModel->getRect().top>=rect.bottom)) || ((m_dynamicObjectModel->getRect().left>=rect.left) && (m_dynamicObjectModel->getRect().left<=rect.right) && (m_dynamicObjectModel->getRect().bottom>=rect.bottom) && (m_dynamicObjectModel->getRect().bottom<=rect.top))|| ((m_dynamicObjectModel->getRect().left<=rect.left) && (m_dynamicObjectModel->getRect().right>=rect.left) && (m_dynamicObjectModel->getRect().bottom>=rect.bottom) && (m_dynamicObjectModel->getRect().bottom<=rect.top)) ); }
/* Phil Culverhouse Oct 2016 (c) Plymouth University James Rogers Jan 2020 (c) Plymouth University This demo code will move eye and neck servos with kepresses. Use this code as a base for your assignment. */ #include <iostream> #include <fstream> #include <string> #include <sys/types.h> #ifndef _WIN32 #include <unistd.h> #endif #include "owl-pwm.h" #include "owl-comms.h" #include "owl-cv.h" #include "neck_pan.h" #include "eye_scan.h" #include "chameleon.h" #include "eye_roll.h" #include "annoyed_eye_roll.h" #include "point_focus.h" using namespace std; using namespace cv; int main(int argc, char *argv[]) { //Setup TCP coms ostringstream CMDstream; // string packet string CMD; string PiADDR = "10.0.0.10"; int PORT=12345; SOCKET u_sock = OwlCommsInit(PORT, PiADDR); //Set servo positions to their center-points Rx = RxC; Lx = LxC; Ry = RyC; Ly = LyC; Neck= NeckC; // move servos to centre of field CMDstream.str(""); CMDstream.clear(); CMDstream << Rx << " " << Ry << " " << Lx << " " << Ly << " " << Neck; CMD = CMDstream.str(); string RxPacket= OwlSendPacket (u_sock, CMD.c_str()); Mat Frame, Left, Right; //Open video feed string source = "http://10.0.0.10:8080/stream/video.mjpeg"; VideoCapture cap (source); if (!cap.isOpened()) { cout << "Could not open the input video: " << source << endl; return -1; } // program mode enum { NONE, NECK_PAN, EYE_PAN, CHAMELEON, EYE_ROLL, A_EYE_ROLL, FOCUS } mode = NONE; //main program loop while (1){ if (!cap.read(Frame)) { cout << "Could not open the input video: " << source << endl; break; } //flip input image as it comes in reversed Mat FrameFlpd; flip(Frame,FrameFlpd,1); // Split into LEFT and RIGHT images from the stereo pair sent as one MJPEG iamge Left= FrameFlpd(Rect(0, 0, 640, 480)); // using a rectangle Right=FrameFlpd(Rect(640, 0, 640, 480)); // using a rectangle //Draw a circle in the middle of the left and right image (usefull for aligning both cameras) circle(Left,Point(Left.size().width/2,Left.size().height/2),10,Scalar(255,255,255),1); circle(Right,Point(Right.size().width/2,Right.size().height/2),10,Scalar(255,255,255),1); //Display left and right images imshow("Left",Left); imshow("Right", Right); //Read keypress and move the corresponding motor int key = waitKey(50); switch (key){ case 'w': //up Ry=Ry+5; break; case 's'://down Ry=Ry-5; break; case 'a'://left Rx=Rx-5; break; case 'd'://right Rx=Rx+5; break; case 'i': //up Ly=Ly-5; break; case 'k'://down Ly=Ly+5; break; case 'j'://left Lx=Lx-5; break; case 'l'://right Lx=Lx+5; break; case 'e'://right Neck=Neck+5; break; case 'q'://left Neck=Neck-5; break; case 'x': //eye pan mode = EYE_PAN; break; case 'n': //neck pan mode = NECK_PAN; break; case 'c': //Chameleon mode = CHAMELEON; break; case 'r': //Annoyed eye roll mode = A_EYE_ROLL; break; case 27: //STOP ALL (ESCAPE KEY) mode = NONE; // Center everything Rx = RxC; Lx = LxC; Ry = RyC; Ly = LyC; Neck= NeckC; break; case 'f': //focus on point mode = FOCUS; break; case 'o': //Rolls Eyes mode = EYE_ROLL; break; } switch (mode) { case FOCUS: point_focus(Rx, Lx, Neck); break; case A_EYE_ROLL: annoyed_eye_roll(Rx, Ry, Lx, Ly, Neck); break; case EYE_ROLL: eye_roll(Rx, Ry, Lx, Ly); break; case CHAMELEON: chameleon_eyes(Rx, Ry, Lx, Ly); break; case EYE_PAN: pan_eyes(Rx, Lx); break; case NECK_PAN: pan_sin(Neck); break; case NONE: break; } //Send new motor positions to the owl servos CMDstream.str(""); CMDstream.clear(); CMDstream << Rx << " " << Ry << " " << Lx << " " << Ly << " " << Neck; CMD = CMDstream.str(); printf("main() %s", CMD.c_str()); RxPacket= OwlSendPacket (u_sock, CMD.c_str()); } // END cursor control loop // close windows down destroyAllWindows(); #ifdef _WIN32 RxPacket= OwlSendPacket (u_sock, CMD.c_str()); closesocket(u_sock); #else OwlSendPacket (clientSock, CMD.c_str()); close(clientSock); #endif exit(0); // exit here for servo testing only }
#ifndef MacOpView_H #define MacOpView_H #include "modules/pi/OpView.h" #include "adjunct/desktop_util/actions/delayed_action.h" #include "modules/libgogi/pi_impl/mde_opview.h" #include "platforms/mac/pi/MacOpSystemInfo.h" class MacOpWindow; class MacOpView : public MDE_OpView { public: virtual ~MacOpView(){} virtual void GetMousePos(INT32 *xpos, INT32 *ypos); virtual OpPoint ConvertToScreen(const OpPoint &point); virtual OpPoint ConvertFromScreen(const OpPoint &point); OpPoint MakeGlobal(const OpPoint &point, BOOL stop_at_toplevel=TRUE); virtual OpWindow* GetRootWindow(); virtual void SetDragListener(OpDragListener* inDragListener); virtual ShiftKeyState GetShiftKeys() { return g_op_system_info->GetShiftKeyState(); } void DelayedInvalidate(OpRect rect, UINT32 timeout); OpDragListener *GetDragListener() { return mDragListener; } #ifdef WIDGETS_IME_SUPPORT virtual void AbortInputMethodComposing(); virtual void SetInputMethodMode(IME_MODE mode, IME_CONTEXT context, const uni_char* istyle); #endif // WIDGETS_IME_SUPPORT private: class DelayedInvalidation : public OpDelayedAction { public: DelayedInvalidation(MacOpView* view, OpRect rect, UINT32 timeout) : OpDelayedAction(timeout), m_view(view), m_rect(rect) {} virtual void DoAction() { m_view->Invalidate(m_rect); m_view->RemoveDelayedInvalidate(this); } public: MacOpView* m_view; OpRect m_rect; }; void RemoveDelayedInvalidate(DelayedInvalidation* action); OpDragListener* mDragListener; OpAutoVector<DelayedInvalidation> mDelayedActions; }; #endif //MacOpView_H
// Created on: 1991-03-18 // Created by: Remi GILET // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GccAna_Circ2dTanCen_HeaderFile #define _GccAna_Circ2dTanCen_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Integer.hxx> #include <TColgp_Array1OfCirc2d.hxx> #include <GccEnt_Array1OfPosition.hxx> #include <TColStd_Array1OfInteger.hxx> #include <TColgp_Array1OfPnt2d.hxx> #include <TColStd_Array1OfReal.hxx> #include <GccEnt_Position.hxx> class GccEnt_QualifiedCirc; class gp_Pnt2d; class gp_Lin2d; class gp_Circ2d; //! This class implements the algorithms used to //! create 2d circles tangent to an entity and //! centered on a point. //! The arguments of all construction methods are : //! - The qualified element for the tangency constrains //! (QualifiedCirc, Line, Point). //! - The center point Pcenter. //! - A real Tolerance. //! Tolerance is only used in the limits cases. //! For example : //! We want to create a circle tangent to an EnclosedCirc C1 //! with a tolerance Tolerance. //! If we did not used Tolerance it is impossible to //! find a solution in the following case : Pcenter is //! outside C1. //! With Tolerance we will give a solution if the distance //! between C1 and Pcenter is lower than or equal Tolerance. class GccAna_Circ2dTanCen { public: DEFINE_STANDARD_ALLOC //! This method implements the algorithms used to //! create 2d circles tangent to a circle and //! centered on a point. Standard_EXPORT GccAna_Circ2dTanCen(const GccEnt_QualifiedCirc& Qualified1, const gp_Pnt2d& Pcenter, const Standard_Real Tolerance); //! This method implements the algorithms used to //! create 2d circles tangent to a line and //! centered on a point. Standard_EXPORT GccAna_Circ2dTanCen(const gp_Lin2d& Linetan, const gp_Pnt2d& Pcenter); //! This method implements the algorithms used to //! create 2d circles passing through a point and //! centered on a point. //! Tolerance is a tolerance criterion used by the algorithm //! to find a solution when, mathematically, the problem //! posed does not have a solution, but where there is //! numeric uncertainty attached to the arguments. //! In these algorithms Tolerance is only used in very //! specific cases where the center of the solution is very //! close to the circle to which it is tangential, and where the //! solution is therefore a very small circle. //! Exceptions //! GccEnt_BadQualifier if a qualifier is inconsistent with //! the argument it qualifies (for example, enclosing for a line). Standard_EXPORT GccAna_Circ2dTanCen(const gp_Pnt2d& Point1, const gp_Pnt2d& Pcenter); //! This method returns True if the construction //! algorithm succeeded. //! Note: IsDone protects against a failure arising from a //! more internal intersection algorithm, which has reached //! its numeric limits. Standard_EXPORT Standard_Boolean IsDone() const; //! Returns the number of circles, representing solutions //! computed by this algorithm and raises NotDone //! exception if the algorithm didn't succeed. Standard_EXPORT Standard_Integer NbSolutions() const; //! Returns the circle, representing the solution number Index and raises OutOfRange //! exception if Index is greater than the number of solutions. //! Be careful: the Index is only a way to get all the //! solutions, but is not associated to these outside the //! context of the algorithm-object. //! Raises NotDone if the construction algorithm didn't succeed. //! It raises OutOfRange if Index is greater than the //! number of solutions or less than zer Standard_EXPORT gp_Circ2d ThisSolution (const Standard_Integer Index) const; //! Returns the qualifier Qualif1 of the tangency argument //! for the solution of index Index computed by this algorithm. //! The returned qualifier is: //! - that specified at the start of construction when the //! solutions are defined as enclosed, enclosing or //! It returns the real qualifiers (the qualifiers given to the //! constructor method in case of enclosed, enclosing and outside //! and the qualifiers computedin case of unqualified). Standard_EXPORT void WhichQualifier (const Standard_Integer Index, GccEnt_Position& Qualif1) const; //! Returns information about the tangency point between the //! result number Index and the first argument. //! ParSol is the intrinsic parameter of the point PntSol //! on the solution curv. //! ParArg is the intrinsic parameter of the point PntArg //! on the argument curv. //! It raises NotDone if the construction algorithm //! didn't succeed. //! It raises OutOfRange if Index is greater than the //! number of solutions or less than zero. Standard_EXPORT void Tangency1 (const Standard_Integer Index, Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const; //! Returns True if the solution number Index is equal to //! the first argument. //! It raises NotDone if the construction algorithm //! didn't succeed. //! It raises OutOfRange if Index is greater than the //! number of solutions or less than zero. Standard_EXPORT Standard_Boolean IsTheSame1 (const Standard_Integer Index) const; protected: private: Standard_Boolean WellDone; Standard_Integer NbrSol; TColgp_Array1OfCirc2d cirsol; GccEnt_Array1OfPosition qualifier1; TColStd_Array1OfInteger TheSame1; TColgp_Array1OfPnt2d pnttg1sol; TColStd_Array1OfReal par1sol; TColStd_Array1OfReal pararg1; }; #endif // _GccAna_Circ2dTanCen_HeaderFile
#include <iostream> #include <cstring> using namespace std; const int maxn = 3000005; int a[maxn]; int n; //人数 int t; //卡片数字 int main() { memset(a, 0, sizeof a); //数组a置0, 做标记 cin >> n; for(int i = 0; i < n; i++) { cin >> t; //sort(); if(a[t] != 0) a[t]--; else a[t]++; } for(int i = 0; i < n; i++) { if(a[i] != 0) { cout << i << endl; } } return 0; }
#ifndef INC_SHADY_ENGINE_APPLICATION_MANAGER_H #define INC_SHADY_ENGINE_APPLICATION_MANAGER_H //C++ headers #include<memory> //engine headers #include"application.h" namespace shady_engine { class app_manager { static application* mApp; static void key_callback( GLFWwindow* window, int key, int scancode, int action, int mods ); static void error_callback( int error, const char* desc ); static void window_resize_callback( GLFWwindow* window, int width, int height ); static void mouse_button_callback( GLFWwindow* window, int key, int action, int mods ); static void cursor_pos_callback( GLFWwindow* window, double xPos, double yPos ); public: static void start_app(application* pApp); }; } //End of namespace #endif
// // nehe12.cpp // NeheGL // // Created by Andong Li on 9/11/13. // Copyright (c) 2013 Andong Li. All rights reserved. // #include "nehe12.h" const char* NEHE12::TITLE = "NEHE12"; GLfloat NEHE12::sleepTime = 0.0f; int NEHE12::frameCounter = 0; int NEHE12::currentTime = 0; int NEHE12::lastTime = 0; char NEHE12::FPSstr[15] = "Calculating..."; GLuint NEHE12::texture[1] = {0}; GLfloat NEHE12::xrot = 0.0f; GLfloat NEHE12::yrot = 0.0f; GLuint NEHE12::box = 0; GLuint NEHE12::top = 0; GLuint NEHE12::xloop = 0; GLuint NEHE12::yloop = 0; bool NEHE12::specialKeys[256] = {}; //all set to false GLfloat NEHE12::boxcol[5][3] = { // Bright: Red, Orange, Yellow, Green, Blue {1.0f,0.0f,0.0f}, {1.0f,0.5f,0.0f}, {1.0f,1.0f,0.0f}, {0.0f,1.0f,0.0f}, {0.0f,1.0f,1.0f} }; GLfloat NEHE12::topcol[5][3] = { // Dark: Red, Orange, Yellow, Green, Blue {0.5f,0.0f,0.0f}, {0.5f,0.25f,0.0f}, {0.5f,0.5f,0.0f}, {0.0f,0.5f,0.0f}, {0.0f,0.5f,0.5f} }; GLvoid NEHE12::ReSizeGLScene(GLsizei width, GLsizei height){ // Prevent A Divide By Zero By if(height==0) { height=1; } // Reset The Current Viewport glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } bool NEHE12::LoadGLTextures(const char* dir){ /* load an image file directly as a new OpenGL texture */ texture[0] = SOIL_load_OGL_texture ( Utils::getAbsoluteDir(dir), SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); if(texture[0] == 0){ return false; } // Typical Texture Generation Using Data From The Bitmap glBindTexture(GL_TEXTURE_2D, texture[0]); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); return true; } GLvoid NEHE12::BuildLists(){ box=glGenLists(2); // Building Two Lists glNewList(box,GL_COMPILE); // New Compiled box Display List glBegin(GL_QUADS); // Bottom Face glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); // Front Face glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); // Back Face glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); // Right face glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f); // Left Face glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); // End first list glEndList(); top=box+1; glNewList(top,GL_COMPILE); glBegin(GL_QUADS); // Top Face glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f); glEnd(); glEndList(); } GLvoid NEHE12::InitGL(){ //give the relative directory of image under current project folder if(!LoadGLTextures("NeheGL/img/cube.bmp")){ cout<<"Fail to load textures"<<endl; } BuildLists(); // Enable Texture Mapping glEnable(GL_TEXTURE_2D); // Enables Smooth Shading glShadeModel(GL_SMOOTH); // clear background as black glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_LIGHT0); // Quick And Dirty Lighting glEnable(GL_LIGHTING); // Enable Lighting glEnable(GL_COLOR_MATERIAL); // Enable Material Coloring // want the best perspective correction to be done glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); } GLvoid NEHE12::DrawGLScene(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindTexture(GL_TEXTURE_2D, texture[0]); for(yloop=1;yloop<6;yloop++){ for(xloop=0;xloop<yloop;xloop++){ glLoadIdentity(); // Position The Cubes On The Screen glTranslatef(1.4f+(float(xloop)*2.8f)-(float(yloop)*1.4f), ((6.0f-float(yloop))*2.4f)-7.0f,-20.0f); glRotatef(45.0f-(2.0f*yloop)+xrot,1.0f,0.0f,0.0f); glRotatef(45.0f+yrot,0.0f,1.0f,0.0f); glColor3fv(boxcol[yloop-1]); glCallList(box); glColor3fv(topcol[yloop-1]); glCallList(top); } } //draw FPS text glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); glLoadIdentity (); glTranslatef(0.0f,0.0f,-1.0f); glColor3f(0.8f,0.8f,0.8f);//set text color computeFPS(); Utils::drawText(-0.54f,-0.4f, GLUT_BITMAP_HELVETICA_12, FPSstr); glEnable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); glutSwapBuffers(); if (specialKeys[GLUT_KEY_UP]){ xrot -= 0.2f; } if (specialKeys[GLUT_KEY_DOWN]){ xrot += 0.2f; } if (specialKeys[GLUT_KEY_LEFT]){ yrot -= 0.2f; } if (specialKeys[GLUT_KEY_RIGHT]){ yrot += 0.2f; } } /* This function is used to limit FPS for smooth animation */ GLvoid NEHE12::UpdateScene(int flag){ clock_t startTime = clock(); glutPostRedisplay(); clock_t endTime = clock(); //compute sleep time in millesecond float sleepTime = ((CLOCKS_PER_SEC/EXPECT_FPS)-(endTime-startTime))/1000.0; //sleepTime = floor(sleepTime+0.5); sleepTime < 0 ? sleepTime = 0 : NULL; glutTimerFunc(sleepTime, UpdateScene, flag); } void NEHE12::computeFPS(){ frameCounter++; currentTime=glutGet(GLUT_ELAPSED_TIME); if (currentTime - lastTime > FPS_UPDATE_CAP) { sprintf(FPSstr,"FPS: %4.2f",frameCounter*1000.0/(currentTime-lastTime)); lastTime = currentTime; frameCounter = 0; } } GLvoid NEHE12::KeySpecialFuction(int key, int x, int y){ specialKeys[key] = true; } GLvoid NEHE12::KeySpecialUpFuction(int key, int x, int y){ specialKeys[key] = false; }
// // Created by chris on 11/08/2017. // #include <iostream> #include "Shader.h" Shader::Shader(const char **sources, GLuint *types, int count) { create(sources, types, count); } void Shader::create(const char **sources, GLuint *types, int count) { auto shaders = new GLuint[count]; this->program = glCreateProgram(); // Compile shaders for (int i = 0; i < count; ++i) { shaders[i] = compileShader(sources[i], types[i]); glAttachShader(this->program, shaders[i]); } glLinkProgram(program); // Check for link errors int success; glGetProgramiv(program, GL_LINK_STATUS, &success); if(success == 0) { std::cout << "Error: Failed to link shader program" << std::endl; int logLength; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength); auto infoLog = new char[logLength]; glGetProgramInfoLog(program, logLength, &logLength, infoLog); std::cout << infoLog << std::endl; throw std::runtime_error(infoLog); } registerAllUniforms(); for (int i = 0; i < count; ++i) { glDeleteShader(shaders[i]); } } GLuint Shader::compileShader(const char *source, GLuint type) { if(source == nullptr) throw std::runtime_error("ERROR: Shader source was null!"); GLuint shader = glCreateShader(type); glShaderSource(shader, 1, &source, nullptr); glCompileShader(shader); return shader; } void Shader::use() { glUseProgram(this->program); } GLint Shader::getUniformLocation(const char *name) { return uniformLocations[name]; } void Shader::registerAllUniforms() { int uniformCount; glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &uniformCount); auto lengths = new GLint[uniformCount]; auto indices = new GLuint[uniformCount]; for(GLuint i = 0; i < uniformCount; i++) { indices[i] = i; } glGetActiveUniformsiv(program, uniformCount, indices, GL_UNIFORM_NAME_LENGTH, lengths); for(GLuint i = 0; i < uniformCount; i++) { int length = lengths[i]; auto name = new char[length]; glGetActiveUniformName(program, i, length, &length, name); uniformLocations[name] = glGetUniformLocation(program, name); } }
#include "dock_perforo.h" /** * Dock PerFoRo */ DockPerFoRo::DockPerFoRo() : it_(nh_) { image_sub_ = it_.subscribe("/ps3_eye/image_raw", 1, &DockPerFoRo::ImageCallback, this); mode_sub_ = nh_.subscribe("/ModePerFoRo", 1, &DockPerFoRo::ModeCallback, this); target_dock_sub_ = nh_.subscribe("/SelectTargetDockPerFoRo", 1, &DockPerFoRo::SelectTargetDockCallback, this); image_dock_pub_ = it_.advertise("/object_tracking/image_raw", 1); IMSHOW = false; selectObject = false; trackObject = -1; dilation_size = 1; erosion_size = 1; elemDilate = getStructuringElement( MORPH_ELLIPSE, Size( 2*dilation_size + 1, 2*dilation_size+1 ), Point( dilation_size, dilation_size ) ); elemErode = getStructuringElement( MORPH_ELLIPSE, Size( 2*erosion_size + 1, 2*erosion_size+1 ), Point( erosion_size, erosion_size ) ); mColorRadius = Scalar(10,100,100,0); mUpperBound = Scalar(0); mLowerBound = Scalar(0); // cv::namedWindow(OPENCV_WINDOW); } void DockPerFoRo::ModeCallback(const PerFoRoControl::MODE msg) { PerFoRoMode = msg.MODE; } void DockPerFoRo::SelectTargetDockCallback(const PerFoRoControl::SelectTarget msg) { if (PerFoRoMode == 4) { Mat clickFrame = frame; Mat roiHSV; selection.x = msg.x; selection.y = msg.y; selection.width = msg.width; selection.height = msg.height; if( selection.width > 0 && selection.height > 0 ) trackObject = 1; //defines roi cv::Rect roi( selection.x, selection.y, selection.width, selection.height ); //copies input image in roi cv::Mat image_roi = clickFrame(roi); cvtColor(image_roi, roiHSV, CV_BGR2HSV); //computes mean over roi cv::Scalar hsvColor = cv::mean( roiHSV ); cout<<"Dock hsv"<<hsvColor<<endl; double minH = (hsvColor.val[0] >= mColorRadius.val[0]) ? hsvColor.val[0]-mColorRadius.val[0] : 0; double maxH = (hsvColor.val[0]+mColorRadius.val[0] <= 179) ? hsvColor.val[0]+mColorRadius.val[0] : 179; mLowerBound.val[0] = minH; mUpperBound.val[0] = maxH; mLowerBound.val[1] = hsvColor.val[1] - mColorRadius.val[1]; mUpperBound.val[1] = hsvColor.val[1] + mColorRadius.val[1]; mLowerBound.val[2] = hsvColor.val[2] - mColorRadius.val[2]; mUpperBound.val[2] = hsvColor.val[2] + mColorRadius.val[2]; mLowerBound.val[3] = 0; mUpperBound.val[3] = 255; } } void DockPerFoRo::ImageCallback(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } frame = cv_ptr->image; char key = (char)cvWaitKey(10); if (key == 27 ) { ros::requestShutdown(); } else if ( key =='z' ) { IMSHOW = true; namedWindow(OPENCV_WINDOW); setMouseCallback(OPENCV_WINDOW, onMouse, NULL); } else if (key == 'x') { IMSHOW = false; cvDestroyAllWindows() ; namedWindow(OPENCV_WINDOW); } if ((trackObject == 1) && (PerFoRoMode == 4)) { Mat imgHSV, binFrame, imgThresh; cvtColor(frame, imgHSV, CV_BGR2HSV); //Get binary image using HSV threshold inRange(imgHSV, mLowerBound, mUpperBound, imgThresh); //Morphological operations to get smoother blobs with reduced noise dilate( imgThresh, imgThresh, elemDilate ); erode( imgThresh, imgThresh, elemErode ); dilate( imgThresh, imgThresh, elemDilate ); erode( imgThresh, imgThresh, elemErode ); morphologyEx(imgThresh, imgThresh, MORPH_OPEN, structure_elem); //imshow("Binary Image with Detected Object", imgThresh); // Find contours imgThresh.copyTo(binFrame); vector<vector<Point> > contours; vector<Vec4i> hierarchy; /// Find contours findContours( binFrame, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) ); vector<Point> approx; for (int i = 0; i < contours.size(); i++) { // Approximate contours approxPolyDP(cv::Mat(contours[i]), approx, cv::arcLength(cv::Mat(contours[i]), true)*0.02, true); // Skip small or non-convex objects if (fabs(contourArea(contours[i])) < 100 || !cv::isContourConvex(approx)) { continue; } else { // Detect and label circles double area = contourArea(contours[i]); Rect r = boundingRect(contours[i]); int radius = r.width / 2; if (abs(1 - ((double)r.width / r.height)) <= 0.2 && abs(1 - (area / (CV_PI * std::pow(radius, 2)))) <= 0.2) rectangle( frame, r, Scalar(255,255,255), 2, 8, 0 ); } } // Output modified video stream image_dock_pub_.publish(cv_ptr->toImageMsg()); } // Update GUI Window if (IMSHOW) { imshow(OPENCV_WINDOW, frame); ///imshow("Binary Image with Detected Object", imgThresh); } //cv::waitKey(3); } void DockPerFoRo::SelectObject(int event, int x, int y) { Mat roiHSV; fflush(stdout); if (selectObject) { selection.x = MIN(x, origin.x); selection.y = MIN(y, origin.y); selection.width = std::abs(x - origin.x); selection.height = std::abs(y - origin.y); } switch(event) { case CV_EVENT_RBUTTONDOWN: { Mat clickFrame = frame; Mat hSV; selection = Rect(x-rectOffset,y-rectOffset,rectOffset*2,rectOffset*2); trackObject=0; selectCenter.x = x; selectCenter.y = y; selectCentroid = selectCenter; cvtColor(clickFrame, hSV, CV_BGR2HSV); cv::Mat roiHSV = hSV(selection); ///computes mean over roi cv::Scalar hsvColor = cv::mean( roiHSV ); cout<<"hsv"<<hsvColor<<endl; double minH = (hsvColor.val[0] >= mColorRadius.val[0]) ? hsvColor.val[0]-mColorRadius.val[0] : 0; double maxH = (hsvColor.val[0]+mColorRadius.val[0] <= 179) ? hsvColor.val[0]+mColorRadius.val[0] : 179; mLowerBound.val[0] = minH; mUpperBound.val[0] = maxH; mLowerBound.val[1] = hsvColor.val[1] - mColorRadius.val[1]; mUpperBound.val[1] = hsvColor.val[1] + mColorRadius.val[1]; mLowerBound.val[2] = hsvColor.val[2] - mColorRadius.val[2]; mUpperBound.val[2] = hsvColor.val[2] + mColorRadius.val[2]; mLowerBound.val[3] = 0; mUpperBound.val[3] = 255; trackObject = -1; //cout<<"Bounds"<<mLowerBound.val[0]<<" "<<mUpperBound.val[0]<<endl; break; } case CV_EVENT_LBUTTONDOWN: { //cout<<"L BTN DWN"<<endl; //drawing = true; origin = Point(x,y); selection = Rect(x,y,0,0); selectObject = true; trackObject=0; //cout<<"Left B"<<origin<<endl; break; } case CV_EVENT_LBUTTONUP: { Mat clickFrame = frame; //cout<<"L BTN UP"<<endl; selectObject = false; if( selection.width > 0 && selection.height > 0 ) trackObject = 1; selectCenter.x = (int)(selection.x + selection.width/2); selectCenter.y = (int)(selection.y + selection.height/2); selectCentroid = selectCenter; //defines roi cv::Rect roi( selection.x, selection.y, selection.width, selection.height ); //copies input image in roi cv::Mat image_roi = clickFrame(roi); cvtColor(image_roi, roiHSV, CV_BGR2HSV); //computes mean over roi cv::Scalar hsvColor = cv::mean( roiHSV ); cout<<"hsv"<<hsvColor<<endl; double minH = (hsvColor.val[0] >= mColorRadius.val[0]) ? hsvColor.val[0]-mColorRadius.val[0] : 0; double maxH = (hsvColor.val[0]+mColorRadius.val[0] <= 179) ? hsvColor.val[0]+mColorRadius.val[0] : 179; mLowerBound.val[0] = minH; mUpperBound.val[0] = maxH; mLowerBound.val[1] = hsvColor.val[1] - mColorRadius.val[1]; mUpperBound.val[1] = hsvColor.val[1] + mColorRadius.val[1]; mLowerBound.val[2] = hsvColor.val[2] - mColorRadius.val[2]; mUpperBound.val[2] = hsvColor.val[2] + mColorRadius.val[2]; mLowerBound.val[3] = 0; mUpperBound.val[3] = 255; break; } } } void onMouse(int event, int x, int y, int, void* ) { dp::DP->SelectObject(event,x,y); } int main(int argc, char** argv) { ros::init(argc, argv, "Dock_PerFoRo"); dp::DP = new DockPerFoRo; ros::spin(); return 0; }
#include <iostream> using namespace std; int main() { int t, n, a[150], b, maxi; cin >> t; while(t--) { cin >> n; maxi = 0; for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < n; i++) { cin >> b; maxi = max(20 * a[i] - b * 10, maxi); } cout << maxi << endl; } }
struct RandomListNode { int label; struct RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) { } }; typedef RandomListNode rnode; class CloneRandomList { public: // 思路: 首先拷贝首节点,用哈希表记录其地址,遍历原链表, // 若存在节点则取出其地址, // 若不存在则new出来一个, 再用哈希表记录之。 // 复杂度: 时间 O(n), 空间O(n) RandomListNode* Clone(RandomListNode* pHead) { if (pHead == nullptr) return pHead; map<int, rnode*> memo; rnode* cur = new rnode(pHead->label); rnode* cloned = cur; rnode* p = pHead; memo[pHead->label] = cur; while (p != nullptr) { if (p->next != nullptr) { // corner if (memo.count(p->next->label) != 0) { cur->next = memo[p->next->label]; } else { cur->next = new rnode(p->next->label); memo[p->next->label] = cur->next; } } if (p->random != nullptr) { // corner if (memo.count(p->random->label) != 0) { cur->random = memo[p->random->label]; } else { cur->random = new rnode(p->random->label); memo[p->random->label] = cur->random; } } p = p->next; cur = cur->next; } return cloned; } // 复杂度: 时间 O(n), 空间O(1) rnode* Clonev2(rnode* pHead) { copyRndList(pHead); setRndPtr(pHead); return reconnect(pHead); } void copyRndList(rnode* pHead) { auto p = pHead; while (p != nullptr) { // NOTE:即使 p->next = nullptr 也OK auto temp = p->next; p->next = new rnode(p->label); p->next->next = temp; p = p->next->next; } } void setRndPtr(rnode* pHead) { auto p = pHead; while (p != nullptr && p->next != nullptr) { // corner if (p->random != nullptr) { p->next->random = p->random; } p = p->next->next; } } rnode* reconnect(rnode* pHead) { if (pHead == nullptr || pHead->next == nullptr) return pHead; auto p1 = pHead; auto p2 = pHead->next; auto res = p2; while (p1->next != nullptr && p2->next != nullptr) { // corner p1->next = p1->next->next; p2->next = p2->next->next; p1 = p1->next; p2 = p2->next; } p1->next = nullptr; // corner return res; } void test() { rnode* r1 = new rnode(1); rnode* r2 = new rnode(2); rnode* r3 = new rnode(3); rnode* r4 = new rnode(4); rnode* r5 = new rnode(5); r1->next = r2; r1->random = r3; r2->next = r3; r2->random = r5; r3->next = r4; r4->next = r5; r4->random = r2; cout << "before:" << endl; auto p1 = r1; while (p1 != NULL) { cout << p1->label << " (random)--> "; if (p1->random == NULL) cout << "nullptr" << endl; else cout << p1->random->label << endl; p1 = p1->next; } auto res = Clonev2(r1); p1 = r1; cout << "after:" << endl << endl; while (p1 != NULL) { cout << p1->label << " (random)--> "; if (p1->random == NULL) cout << "nullptr" << endl; else cout << p1->random->label << endl; p1 = p1->next; } cout << "result: " << endl << endl; while (res != NULL) { cout << res->label << " (random)--> "; if (res->random == NULL) cout << "nullptr" << endl; else cout << res->random->label << endl; res = res->next; } } };
#include<iostream> #include<set> using namespace std; int main() { int t,e,x,y; cin >> t; while(t--) { set<int> citySet; set<int>:: iterator it; cin >> e; while(e--) { cin >> x >> y; it = citySet.find(x); if(it == citySet.end()) citySet.insert(x); it = citySet.find(y); if(it == citySet.end()) citySet.insert(y); } cout << citySet.size() << endl; } return 0; }
// Created on: 1993-03-31 // Created by: Bruno DUMORTIER // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Adaptor3d_Surface_HeaderFile #define _Adaptor3d_Surface_HeaderFile #include <Adaptor3d_Curve.hxx> #include <GeomAbs_Shape.hxx> #include <GeomAbs_SurfaceType.hxx> #include <gp_Ax1.hxx> #include <gp_Cylinder.hxx> #include <gp_Cone.hxx> #include <gp_Pln.hxx> #include <gp_Sphere.hxx> #include <gp_Torus.hxx> #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TColStd_Array1OfReal.hxx> class Geom_BezierSurface; class Geom_BSplineSurface; DEFINE_STANDARD_HANDLE(Adaptor3d_Surface, Standard_Transient) //! Root class for surfaces on which geometric algorithms work. //! An adapted surface is an interface between the //! services provided by a surface and those required of //! the surface by algorithms which use it. //! A derived concrete class is provided: //! GeomAdaptor_Surface for a surface from the Geom package. //! The Surface class describes the standard behaviour //! of a surface for generic algorithms. //! //! The Surface can be decomposed in intervals of any //! continuity in U and V using the method NbIntervals. //! A current interval can be set. //! Most of the methods apply to the current interval. //! Warning: All the methods are virtual and implemented with a //! raise to allow to redefined only the methods really used. //! //! Polynomial coefficients of BSpline surfaces used for their evaluation are cached for better performance. //! Therefore these evaluations are not thread-safe and parallel evaluations need to be prevented. class Adaptor3d_Surface : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Adaptor3d_Surface, Standard_Transient) public: //! Shallow copy of adaptor Standard_EXPORT virtual Handle(Adaptor3d_Surface) ShallowCopy() const; Standard_EXPORT virtual Standard_Real FirstUParameter() const; Standard_EXPORT virtual Standard_Real LastUParameter() const; Standard_EXPORT virtual Standard_Real FirstVParameter() const; Standard_EXPORT virtual Standard_Real LastVParameter() const; Standard_EXPORT virtual GeomAbs_Shape UContinuity() const; Standard_EXPORT virtual GeomAbs_Shape VContinuity() const; //! Returns the number of U intervals for continuity //! <S>. May be one if UContinuity(me) >= <S> Standard_EXPORT virtual Standard_Integer NbUIntervals (const GeomAbs_Shape S) const; //! Returns the number of V intervals for continuity //! <S>. May be one if VContinuity(me) >= <S> Standard_EXPORT virtual Standard_Integer NbVIntervals (const GeomAbs_Shape S) const; //! Returns the intervals with the requested continuity //! in the U direction. Standard_EXPORT virtual void UIntervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const; //! Returns the intervals with the requested continuity //! in the V direction. Standard_EXPORT virtual void VIntervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const; //! Returns a surface trimmed in the U direction //! equivalent of <me> between //! parameters <First> and <Last>. <Tol> is used to //! test for 3d points confusion. //! If <First> >= <Last> Standard_EXPORT virtual Handle(Adaptor3d_Surface) UTrim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const; //! Returns a surface trimmed in the V direction between //! parameters <First> and <Last>. <Tol> is used to //! test for 3d points confusion. //! If <First> >= <Last> Standard_EXPORT virtual Handle(Adaptor3d_Surface) VTrim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const; Standard_EXPORT virtual Standard_Boolean IsUClosed() const; Standard_EXPORT virtual Standard_Boolean IsVClosed() const; Standard_EXPORT virtual Standard_Boolean IsUPeriodic() const; Standard_EXPORT virtual Standard_Real UPeriod() const; Standard_EXPORT virtual Standard_Boolean IsVPeriodic() const; Standard_EXPORT virtual Standard_Real VPeriod() const; //! Computes the point of parameters U,V on the surface. //! Tip: use GeomLib::NormEstim() to calculate surface normal at specified (U, V) point. Standard_EXPORT virtual gp_Pnt Value (const Standard_Real U, const Standard_Real V) const; //! Computes the point of parameters U,V on the surface. Standard_EXPORT virtual void D0 (const Standard_Real U, const Standard_Real V, gp_Pnt& P) const; //! Computes the point and the first derivatives on the surface. //! Raised if the continuity of the current intervals is not C1. //! //! Tip: use GeomLib::NormEstim() to calculate surface normal at specified (U, V) point. Standard_EXPORT virtual void D1 (const Standard_Real U, const Standard_Real V, gp_Pnt& P, gp_Vec& D1U, gp_Vec& D1V) const; //! Computes the point, the first and second //! derivatives on the surface. //! Raised if the continuity of the current //! intervals is not C2. Standard_EXPORT virtual void D2 (const Standard_Real U, const Standard_Real V, gp_Pnt& P, gp_Vec& D1U, gp_Vec& D1V, gp_Vec& D2U, gp_Vec& D2V, gp_Vec& D2UV) const; //! Computes the point, the first, second and third //! derivatives on the surface. //! Raised if the continuity of the current //! intervals is not C3. Standard_EXPORT virtual void D3 (const Standard_Real U, const Standard_Real V, gp_Pnt& P, gp_Vec& D1U, gp_Vec& D1V, gp_Vec& D2U, gp_Vec& D2V, gp_Vec& D2UV, gp_Vec& D3U, gp_Vec& D3V, gp_Vec& D3UUV, gp_Vec& D3UVV) const; //! Computes the derivative of order Nu in the direction U and Nv //! in the direction V at the point P(U, V). //! Raised if the current U interval is not not CNu //! and the current V interval is not CNv. //! Raised if Nu + Nv < 1 or Nu < 0 or Nv < 0. Standard_EXPORT virtual gp_Vec DN (const Standard_Real U, const Standard_Real V, const Standard_Integer Nu, const Standard_Integer Nv) const; //! Returns the parametric U resolution corresponding //! to the real space resolution <R3d>. Standard_EXPORT virtual Standard_Real UResolution (const Standard_Real R3d) const; //! Returns the parametric V resolution corresponding //! to the real space resolution <R3d>. Standard_EXPORT virtual Standard_Real VResolution (const Standard_Real R3d) const; //! Returns the type of the surface : Plane, Cylinder, //! Cone, Sphere, Torus, BezierSurface, //! BSplineSurface, SurfaceOfRevolution, //! SurfaceOfExtrusion, OtherSurface Standard_EXPORT virtual GeomAbs_SurfaceType GetType() const; Standard_EXPORT virtual gp_Pln Plane() const; Standard_EXPORT virtual gp_Cylinder Cylinder() const; Standard_EXPORT virtual gp_Cone Cone() const; Standard_EXPORT virtual gp_Sphere Sphere() const; Standard_EXPORT virtual gp_Torus Torus() const; Standard_EXPORT virtual Standard_Integer UDegree() const; Standard_EXPORT virtual Standard_Integer NbUPoles() const; Standard_EXPORT virtual Standard_Integer VDegree() const; Standard_EXPORT virtual Standard_Integer NbVPoles() const; Standard_EXPORT virtual Standard_Integer NbUKnots() const; Standard_EXPORT virtual Standard_Integer NbVKnots() const; Standard_EXPORT virtual Standard_Boolean IsURational() const; Standard_EXPORT virtual Standard_Boolean IsVRational() const; Standard_EXPORT virtual Handle(Geom_BezierSurface) Bezier() const; Standard_EXPORT virtual Handle(Geom_BSplineSurface) BSpline() const; Standard_EXPORT virtual gp_Ax1 AxeOfRevolution() const; Standard_EXPORT virtual gp_Dir Direction() const; Standard_EXPORT virtual Handle(Adaptor3d_Curve) BasisCurve() const; Standard_EXPORT virtual Handle(Adaptor3d_Surface) BasisSurface() const; Standard_EXPORT virtual Standard_Real OffsetValue() const; Standard_EXPORT virtual ~Adaptor3d_Surface(); }; #endif // _Adaptor3d_Surface_HeaderFile
/********************************************************************* ** Author: Chris Matian ** Date: 07/24/2017 ** Description: Class specification header file for the Entree Sampler Functions *********************************************************************/ #ifndef ENTREESAMPLER_HPP #define ENTREESAMPLER_HPP #include "Entree.hpp" class EntreeSampler { private: Entree item1; // contains the Entree Class 1 Entree item2; // contains the Entree Class 2 Entree item3; // contains the Entree Class 3 Entree item4; // contains the Entree Class 4 public: //Constructors EntreeSampler(Entree, Entree, Entree, Entree); //Methods void listEntrees(); int totalCalories(); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1999-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** CREATED DG-170399 ** DESCRIPTION Allow Dynamic linking of RAS API functions ** ** Because - If an application links statically to the RASAPI32 DLL, ** the application will fail to load if Remote Access Service is not ** installed. */ #include "core/pch.h" #if defined(_RAS_SUPPORT_) #include "rasex.h" #include "modules/locale/oplanguagemanager.h" #include "modules/locale/locale-enum.h" #include <raserror.h> static BOOL s_fPrefsManagerAskCloseConnections = FALSE; const int MAXConn = 16; // ___________________________________________________________________________ // OpRasEnableAskCloseConnections // // PrefsManager is void when the dialog is shown after leaving the main message // loop. This function set's the static var s_fPrefsManagerAskCloseConnections // ___________________________________________________________________________ // void OpRasEnableAskCloseConnections( BOOL fEnable) { s_fPrefsManagerAskCloseConnections = fEnable; } // ___________________________________________________________________________ // OpRasAskCloseConnections // // Display a dialog to allow closing all open dialup connections at exit. // If the return value is IDCANCEL Opera should not allow to exit. // // Returns IDCANCEL or IDNO if no close // IDYES if the connections was closed // IDIGNORE No connections was open // ___________________________________________________________________________ // // LRESULT OpRasAskCloseConnections( HWND hWndParent, BOOL fAllowCancel) { if( !s_fPrefsManagerAskCloseConnections) return IDIGNORE; LRESULT lRes; // // Get all open connections. // DWORD dwSize = 0; DWORD dwConnections = 0; RASCONN rasconn[MAXConn]; dwSize = sizeof( rasconn); rasconn[0].dwSize = sizeof(rasconn[0]); DWORD dwResult = RasEnumConnections( rasconn, &dwSize, &dwConnections); DWORD i; if( !dwConnections || dwResult != ERROR_SUCCESS || !g_languageManager) { // No connections was open or an error return IDIGNORE; } // // Ask the user whether he would close them or not // OpString szLangTitle; OpString szLangMsg; g_languageManager->GetString(Str::SI_IDSTR_ASKRASCLOSEALLCAPTION, szLangTitle); g_languageManager->GetString(Str::SI_IDSTR_ASKRASCLOSEALL, szLangMsg); uni_char szConnectionList [MAXConn * RAS_MaxEntryName] = UNI_L(""); for( i=0; i<dwConnections; i++) { uni_strcat( szConnectionList, UNI_L("\"")); uni_strcat( szConnectionList, rasconn[i].szEntryName); uni_strcat( szConnectionList, UNI_L("\"")); if( i==dwConnections-1) uni_strcat( szConnectionList, UNI_L(".")); else uni_strcat( szConnectionList, UNI_L(", ")); } uni_strcat( szConnectionList, UNI_L("\n")); uni_char szMsg[ARRAY_SIZE(szConnectionList)+256]; uni_sprintf(szMsg, szLangMsg.CStr(), szConnectionList); UINT type = fAllowCancel ? MB_YESNOCANCEL : MB_YESNO; lRes = MessageBox( hWndParent, szMsg, szLangTitle.CStr(), type|MB_ICONQUESTION); if( lRes != IDYES) { // Do not close dun return lRes; } // // Close all open connections. // for( i=0; i<dwConnections; i++) { HRASCONN hrasconn = rasconn[i].hrasconn; RasHangUp( hrasconn); RASCONNSTATUS status; status.dwSize = sizeof(status); DWORD dwStart = GetTickCount(); DWORD dwTimeOut = dwStart + 5000; while( !RasGetConnectStatus( hrasconn, &status)) { Sleep( 10); if( GetTickCount() > dwTimeOut) { // // Timed out - unable to close all connections // Has to load this manually - mess and prefsManager might be NULL // OpString sz; g_languageManager->GetString(Str::SI_IDSTR_ERR_RASCLOSEALLFAILED, sz); MessageBox( hWndParent, sz.CStr(), UNI_L("Opera"), MB_ICONERROR); return IDCANCEL; } } } return lRes; } #endif // _RAS_SUPPORT_
#include "resourceManager.h" #include <filesystem> #include <iostream> ResourceManager::ResourceManager(std::string _execPath) : execPath(_execPath) { generateResourcesPath(); } ResourceManager::~ResourceManager() { } void ResourceManager::loadResources(Point<int> expectedTexturesSize) { loadFont(); textures = loadAllImagesWithSize(resourcesPath + texturesDir, expectedTexturesSize); normalMaps = loadAllImagesWithSize(resourcesPath + normalMapsDir, expectedTexturesSize); } std::unordered_map<std::string, Bitmap *> ResourceManager::getTextures() { return textures; } std::unordered_map<std::string, Bitmap *> ResourceManager::getNormalMaps() { return normalMaps; } void ResourceManager::generateResourcesPath() { std::filesystem::path rootPath = std::filesystem::current_path(); std::filesystem::path p = execPath; rootPath /= p.parent_path(); rootPath = std::filesystem::weakly_canonical(rootPath); resourcesPath = rootPath / resourcesDir; } void ResourceManager::loadFont() { } std::unordered_map<std::string, Bitmap *> ResourceManager::loadAllImagesWithSize(std::string dir, Point<int> expectedSize) { std::unordered_map<std::string, Bitmap*> dict; const std::filesystem::path dirPath(dir); if(!std::filesystem::exists(dirPath)) return dict; for(auto const &dirEntry : std::filesystem::directory_iterator(dirPath)) { if(!dirEntry.is_regular_file()) continue; auto bitmapPath = std::filesystem::absolute(dirEntry.path()); Bitmap *bitmap = loadBitmap(bitmapPath, expectedSize); if(bitmap != nullptr) dict[bitmapPath.filename()] = bitmap; } return dict; }
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; using Graph = vector<vector<int>>; const double PI = 3.14159265358979323846; const ll MOD = 1000000007; const int INF = 1e9; const int dx[4] = {1,0,-1,0}; const int dy[4] = {0,1,0,-1}; int main(){ int N; cin >> N; vector<int>A(N); rep(i,N)cin >> A[i]; vector<ll> B(N+1,0); rep(i,N){ B[i+1] = B[i] +A[i]; } ll ans = 0; rep(i,N){ ll sum = (B[N] - B[i+1]) %MOD; ans += A[i] * sum; ans %= MOD; } cout << ans << endl; }
#include <iostream> #include <thread> #include <atomic> //#include <fstream> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/progress.hpp> #include <boost/regex.hpp> #include <boost/algorithm/string/replace.hpp> // #include "boost/timer/timer.hpp" #include <Eigen/Dense> #include <pcl/pcl_base.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/io/pcd_io.h> //#include <pcl/console/parse.h> //#include <pcl/console/print.h> #include "DEdvs/dedvs_auxiliary.h" namespace bfs = boost::filesystem; bool checkPathValidity(bfs::path in_path) { if(bfs::exists(in_path)) { if(!bfs::is_directory(in_path)) { std::cerr << in_path << " does not seem to be a folder!\n"; return false; } } else { std::cerr << "Folder " << in_path << " does not seem to exist!\n"; return false; } // Folder exists return true; } bool validateFilename(const std::string& s) { static const boost::regex e("depth_\\d{1,15}"); return boost::regex_match(s, e); } pcl::PointCloud<pcl::PointXYZRGBA> createPCD(bfs::path path_to_depth_frame, bool use_rgb, bfs::path out_path, int width, int height, int compression, std::atomic<int>* current_threads) { //Load Depth Frame! const uint16_t* depth_frame = new uint16_t[width*height]; const unsigned char* color_frame = new unsigned char[width*height*3]; // load depth { bfs::ifstream ifs(path_to_depth_frame, std::ios::in | std::ios::binary); ifs.read((char*) depth_frame, width*height * sizeof(uint16_t)); } // load color if(use_rgb) { std::string path_to_color_frame = path_to_depth_frame.string(); boost::replace_all(path_to_color_frame, "depth", "rgb"); { std::ifstream ifs(path_to_color_frame, std::ios::in | std::ios::binary); ifs.read((char*) color_frame, width*height * 3); } } // std::cout << path_to_depth_frame << std::endl; // std::cout << path_to_color_frame << std::endl; // Fill in the cloud data pcl::PointCloud<pcl::PointXYZRGBA> pc_depth; pc_depth.width = width; pc_depth.height = height; pc_depth.is_dense = false; pc_depth.points.resize (pc_depth.width * pc_depth.height); const float bad_point = std::numeric_limits<float>::quiet_NaN (); //TODO???! //Temporary data Eigen::Vector3f temp_point; uint16_t depth; uint32_t rgb; int mult = (width == 640) ? 1 : 2; for (int y = 0; y < pc_depth.height; ++y) { for (int x = 0; x < pc_depth.width; ++x) { size_t index = x + width * y; depth = depth_frame[index]; if(use_rgb) { rgb = (static_cast<uint32_t>(255)<<24) + (static_cast<uint32_t>(color_frame[3*index + 2]) << 16) + (static_cast<uint32_t>(color_frame[3*index + 1]) << 8) + (static_cast<uint32_t>(color_frame[3*index + 0])); } else { rgb = 0; } auto& p = pc_depth.points[x + width * y]; p.rgba = rgb; if(depth != 0 && !pcl_isnan(depth) && !pcl_isnan(depth)) { temp_point = dedvs::unprojectKinect(mult*x, mult*y, depth); p.x = temp_point(0); p.y = temp_point(1); p.z = temp_point(2); } else { p.x = bad_point; p.y = bad_point; p.z = bad_point; } } } //Save Point Cloud File std::string out = out_path.native()+path_to_depth_frame.filename().native()+std::string(".pcd"); switch(compression) { case 0: pcl::io::savePCDFileASCII(out, pc_depth); break; case 1: pcl::io::savePCDFileBinary(out, pc_depth); break; case 2: pcl::io::savePCDFileBinaryCompressed(out, pc_depth); break; } delete[] depth_frame; (*current_threads)--; return pc_depth; } int converter(std::string raw_path, bool use_rgb, std::string out_path, int width, int height, int threads, int compression) { bfs::path raw_p(raw_path); bfs::path out_p(out_path); //Check if paths actually exist if(!checkPathValidity(raw_p) || !checkPathValidity(out_p)) return 1; std::vector<bfs::path> all_files; std::vector<bfs::path> raw_files; copy(bfs::directory_iterator(raw_path), bfs::directory_iterator(), back_inserter(all_files)); for (auto iter:all_files) { if(validateFilename(iter.filename().native())) raw_files.push_back(iter); } sort(raw_files.begin(),raw_files.end()); std::atomic<int> current_threads(0); boost::progress_display prog(raw_files.size()); //TODO: Only for debug output?? for(auto iter:raw_files) { while(current_threads >= threads) { std::this_thread::sleep_for( std::chrono::milliseconds(20)); } //createPCD(iter, out_path, width, height, compression, stdout_mtx); std::thread thread(createPCD, iter, use_rgb, out_path, width, height, compression, &current_threads); // std::cout << "Converting " << iter.filename() << " ...\n"; ++prog; thread.detach(); current_threads++; } while(current_threads > 0) { std::this_thread::sleep_for( std::chrono::milliseconds(20)); } std::cout << "\n - Converted all depth frames! -\n\n"; } int main(int argc, char *argv[]) { // boost::timer::auto_cpu_timer t; namespace po = boost::program_options; int width = 320; int height = 240; int threads = 1; int compression = 0; std::string raw_path = ""; std::string out_path = ""; bool use_rgb = false; // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("width,w", po::value<int>(&width), "Width of depth frames in Pixel") ("height,h", po::value<int>(&height), "Width of depth frames in Pixel (640/320)") ("threads,t", po::value(&threads), "How many threads shall be spawned") ("compression,c", po::value(&compression), "Compression: 0=ASCII 1=Binary 2=Binary Compressed") ("raw_depth_frames_folder,raw", po::value(&raw_path), "Folder/Location of the raw depth frames") ("rgb", po::value(&use_rgb), "Wether to use rgb images") ("output_folder,out", po::value(&out_path), "Folder of for generated .pcd files") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if(vm.count("help")) { std::cout << desc << std::endl; return 1; } return converter(raw_path,use_rgb,out_path,width,height,threads,compression); }
// Problem: Battleships (http://codeforces.com/problemset/problem/965/B) // Author: babang #include <algorithm> #include <iostream> #include <map> #include <set> #include <vector> #include <math.h> #define forn(i, n) for(int i = 0; i < n; i++) #define rofn(i, n) for(int i = n-1; i >= 0; i--) #define foran(i, a, n) for(int i = a; i < n; i++) #define rofan(i, a, n) for(int i = a-1; i >= n; i--) #define T() int t; cin>>t; while(t--) #define scan(x) scanf("%lld",&x) #define print(x) printf("%lld ",x) #define eb emplace_back #define pb push_back #define mp make_pair #define fi first #define se second #define be begin() #define en end() #define YES printf("YES\n") #define NO printf("NO\n") #define br printf("\n"); using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef vector<ll> vll; typedef pair<ll, ll> pll; typedef map<ll, ll> mll; typedef set<ll, ll> sll; ll n, k, mx = 0; vector<string> qw; vector<vll> sdf; string ui; class xy { public: int x; int y; }; xy asd, fin; int main() { cin >> n >> k; asd.x = 1; asd.y = 1; forn(qq, n) cin >> ui, qw.pb(ui), sdf.pb(vll(ui.length(),0)); forn(qq, n) { forn(ww, n) { // update last . if (qw[qq][ww] == '.') asd.x=ww+1, asd.y=qq+1; bool yy = true, xx = true; forn(ee, k) { if (ww > n - k) xx &= false; else if (qw[qq][ww+ee] == '#') xx &= false; if (qq > n - k) yy &= false; else if (qw[qq+ee][ww] == '#') yy &= false; if (!xx && !yy) break; } if (xx || yy) forn(ee, k) { if (xx) { sdf[qq][ww+ee]++; if (sdf[qq][ww+ee] > mx) mx=sdf[qq][ww+ee], fin.x=ww+ee+1, fin.y=qq+1; } if (yy) { sdf[qq+ee][ww]++; if (sdf[qq+ee][ww] > mx) mx=sdf[qq+ee][ww], fin.x=ww+1, fin.y=qq+ee+1; } } } } if (!mx) cout << asd.y << " " << asd.x << endl ; else cout << fin.y << " " << fin.x << endl ; return 0; }
/* * selsort.cpp * * Created on: Feb 7, 2014 * Author: Pooja */ /*#include <iostream> using namespace std; class selection //complexity 0(n2) { public: void selsort(int a[]) { int i,j,min,temp; min=i; for(i=0;i<6;i++) { for(j=i+1;j<6;j++){ if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } };*/ /*int mainDogie(){ int a[10],p; cout<<"Enter the elements of the array"; }*/
#include "deck.h" #include <cstdlib> #include <iostream> using namespace std; deck::deck(){ //card cards [52]; cout << "Deck created." << endl; int card_num = 0; for (int i = 1; i < 14; i++){ for (int j = 1; j < 5; j++){ cards[card_num].set_card_rank(i); if(j == 1){ cards[card_num].set_card_suit("Diamonds"); } if(j == 2){ cards[card_num].set_card_suit("Clubs"); } if(j == 3){ cards[card_num].set_card_suit("Hearts"); } if(j == 4){ cards[card_num].set_card_suit("Spades"); } card_num = card_num + 1; } } } deck::~deck(){ cout << "Deck destroyed." << endl; } void deck::shuffle_deck(){ srand(time(0)); for (int i = 0; i < 52; i++){ int remaining = i +(rand() % (52 - i)); swap(cards[remaining], cards[i]); } } void deck::print_deck(){ for(int i = 0; i < 52; i++){ cout << "Card #" << i + 1 << endl; cout << "\tCard Suit: " << cards[i].get_card_suit() << endl; cout << "\tCard Rank: " << cards[i].get_card_rank() << endl << endl; } }
// // Created by giofn on 08/01/2020. // #include "FormulaMin.h" #include "Cell.h" void FormulaMin::update() { min=0; if(cells.size()>0){ min=dynamic_cast<Cell*>((*(cells.begin())))->getValue(); for(auto itr=cells.begin();itr!=cells.end();itr++){ if(dynamic_cast<Cell*>((*itr))->getValue()<min) min=dynamic_cast<Cell*>((*itr))->getValue(); } } } float FormulaMin::calculate() { return min; }
/* * subtile.h * deflektor-ds * * Created by Hugh Cole-Baker on 1/19/09. * A smaller tile (8x8) that is used for walls, etc */ #ifndef deflektor_subtile_h #define deflektor_subtile_h #include "beam.h" enum Corner { TOPLEFT = 16, TOPRIGHT = 32, BOTTOMLEFT = 64, BOTTOMRIGHT = 128, }; class Subtile { protected: int bgHandle; unsigned int xPos; unsigned int yPos; const unsigned int tileBase; unsigned int palIdx; const unsigned int reflectiveSides; const bool goal; bool destroyed; public: Subtile(unsigned int tile, unsigned int reflect, bool isGoal); unsigned int getReflectiveSides(); void setBgHandle(int bg); void setXPos(unsigned int x); void setYPos(unsigned int y); void setPalIdx(unsigned int pal); virtual BeamResult beamEnters(unsigned int x, unsigned int y, BeamDirection angle); virtual void drawUpdate(); bool isGoal(); void destroy(); }; #endif
#include "d.h" #include "c.h" using namespace std; void c(){ d(); }
#pragma once #include <vector> #include "Print_publication.h" class Publisher { private: struct Node { Print_publication* value; Node* next; Node(Print_publication* a_value); ~Node(); }; Node* publications; char* name; public: Publisher(char* a_name); ~Publisher(); void set_name(char* a_name); char* get_name(); Print_publication* get_by_number(int number); void add_publication(Print_publication* publication); void remove_and_delete_publication(Print_publication* publication); void print_publisher_information(); void for_each(void (*function)(Print_publication*)); int count(); };
#include "transform.h" bool transform::Load(const rapidjson::Value& value) { bool success; success = json::get(value, "position", translation); success = json::get(value, "rotation", rotation); success = json::get(value, "scale", scale); return success; } bool transform::Update() { matrix33 mxs; mxs.scale(scale); matrix33 mxr; mxr.rotate(rotation); matrix33 mxt; mxt.translate(translation); mxWorld = mxs * mxr * mxt; return true; } void transform::Update(const transform& parent, const transform& local) { scale = parent.scale * local.scale; rotation = parent.rotation + local.rotation; translation = parent.translation + vector2::rotate(local.translation, rotation); }
// Playstation Move on the PC, shared header file // this file contains function prototypes // by Carl Kenner 4 October 2010 - 16 November 2010 /* This file (and anything derived from it, based on it, or using it) is released under a non-military license, it may not be used for any military purpose, including military research, or military funded research, training, recruitment, troop entertainment, design of military systems, or anything else involving the military. I didn't write this to help kill people, sorry. */ #pragma once #include "MoveButton.h" // Maximum number of moves to support. #define MAXMOVES 30 #ifdef _MSC_VER #define snprintf sprintf_s #endif namespace MoveDevice { typedef struct tmove { int Buttons; int TAnalog; int RawBattery; int RawForceX, RawForceY, RawForceZ; int RawGyroYaw, RawGyroPitch, RawGyroRoll; int RawTemperature; int RawMagnetX, RawMagnetY, RawMagnetZ; int Timestamp; int SeqNumber; } TMove, *PMove; typedef struct tnav { int Buttons; int L1Analog, L2Analog; int UpAnalog, DownAnalog, LeftAnalog, RightAnalog; int LeftStickX, LeftStickY; unsigned char report[49]; } TNav, *PNav; typedef struct tmoveoutput { unsigned char r, g, b; unsigned char rumble; unsigned framecount; } TMoveOutput, *PMoveOutput; typedef struct tmovecalib { short int AccHeader; short int AccVectors[6][3]; short int GyroBiasHeaders[2]; short int GyroBiasVectors[2][3]; short int GyroHeader; short int GyroVectors[3][3]; short int UnknownHeader; float UnknownVectors[2][3]; float UnknownValues[2]; } TMoveCalib, *PMoveCalib; typedef struct tmovebluetooth { char MoveBtMacString[18], HostBtMacString[18]; unsigned char MoveBtMac[6], HostBtMac[6]; unsigned char unknown[3]; } TMoveBluetooth, *PMoveBluetooth; int OpenMoves(); int GetMoveCount(); int GetNavCount(); void CloseMoves(); int PairMoves(); bool SetMoveColour(int index, int r, int g, int b); bool SetMoveRumble(int index, int rumble); bool ReadMove(int index, PMove data, PMove old=0); bool ReadMoveCalibration(int index, PMoveCalib calib); bool ReadMoveBluetoothSettings(int index, PMoveBluetooth bt); bool ReadNav(int index, PNav data); }
#include <cmath> #include <cstdio> #include "Circle.h" #include "Polygon.h" #include "Reuleaux.h" #include "Geom.h" #include "Containable.h" // ======================================= // Constructor ========== Getter Functions ========== // ======================================= ReuleauxTriangle::ReuleauxTriangle(const Point vertices[3]) { for (int i = 0; i < 3; i++) { vertices_[i] = vertices[i]; } } Point ReuleauxTriangle::Vertex(int indx) { return vertices_[indx]; } Point ReuleauxTriangle::Center() { vector<Point>v = {Vertex(0),Vertex(1),Vertex(2)}; Polygon rt = Polygon(v); Point center = Geom::PolygonCenter(rt); return center; } double ReuleauxTriangle::RadiusFromCenter() { return Geom::DistanceBetween(vertices_[1], vertices_[2])/2; } // ======================================= // Main Class Functions=============================== // ======================================= bool ReuleauxTriangle::ContainedBy(Circle &circle) { return Geom::DistanceBetween(circle.Center(), Center()) <= circle.Radius() - RadiusFromCenter(); } bool ReuleauxTriangle::ContainedBy(Polygon &polygon) { for (int i = 0; i < polygon.Vertices()-1; i++) { int intersections = Geom::LineIntersectsCircle(Center(), RadiusFromCenter(), polygon.Vertex(i), polygon.Vertex(i+1)); if (intersections == 2) { return false; } else if (intersections <= 1 && Geom::DistanceBetween(Center(), Geom::PolygonCenter(polygon)) <= RadiusFromCenter()) { return true; } } Point center = Center(); return Geom::PointInPolygon(center, polygon); } bool ReuleauxTriangle::ContainedBy(ReuleauxTriangle &rt) { return Geom::DistanceBetween(rt.Center(), Center()) <= rt.RadiusFromCenter() - RadiusFromCenter(); }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <quic/common/FunctionLooper.h> #include <gtest/gtest.h> using namespace std; using namespace folly; using namespace testing; namespace quic { namespace test { class FunctionLooperTest : public Test {}; TEST(FunctionLooperTest, LooperNotRunning) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; auto func = [&]() { called = true; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); evb.loopOnce(); EXPECT_FALSE(called); evb.loopOnce(); EXPECT_FALSE(called); EXPECT_FALSE(looper->isRunning()); } TEST(FunctionLooperTest, LooperStarted) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; auto func = [&]() { called = true; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looper->run(); EXPECT_TRUE(looper->isRunning()); evb.loopOnce(); EXPECT_TRUE(called); called = false; evb.loopOnce(); EXPECT_TRUE(called); } TEST(FunctionLooperTest, LooperStopped) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; auto func = [&]() { called = true; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looper->run(); evb.loopOnce(); EXPECT_TRUE(called); called = false; looper->stop(); EXPECT_FALSE(looper->isRunning()); evb.loopOnce(); EXPECT_FALSE(called); } TEST(FunctionLooperTest, LooperRestarted) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; auto func = [&]() { called = true; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looper->run(); evb.loopOnce(); EXPECT_TRUE(called); called = false; looper->stop(); evb.loopOnce(); EXPECT_FALSE(called); looper->run(); EXPECT_TRUE(looper->isRunning()); evb.loopOnce(); EXPECT_TRUE(called); } TEST(FunctionLooperTest, DestroyLooperDuringFunc) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; FunctionLooper::Ptr* looperPtr = nullptr; auto func = [&]() { called = true; *looperPtr = nullptr; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looperPtr = &looper; looper->run(); evb.loopOnce(); EXPECT_TRUE(called); EXPECT_EQ(looper, nullptr); } TEST(FunctionLooperTest, StopLooperDuringFunc) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; FunctionLooper::Ptr* looperPtr = nullptr; auto func = [&]() { called = true; (*looperPtr)->stop(); }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looperPtr = &looper; looper->run(); evb.loopOnce(); EXPECT_TRUE(called); called = false; evb.loopOnce(); EXPECT_FALSE(called); } TEST(FunctionLooperTest, RunLooperDuringFunc) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; FunctionLooper::Ptr* looperPtr = nullptr; auto func = [&]() { called = true; (*looperPtr)->run(); }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looperPtr = &looper; looper->run(); evb.loopOnce(); EXPECT_TRUE(called); called = false; evb.loopOnce(); EXPECT_TRUE(called); } TEST(FunctionLooperTest, DetachStopsLooper) { EventBase backingEvb; QuicEventBase evb(&backingEvb); bool called = false; auto func = [&]() { called = true; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looper->run(); EXPECT_TRUE(looper->isRunning()); looper->detachEventBase(); EXPECT_FALSE(looper->isRunning()); looper->attachEventBase(&evb); EXPECT_FALSE(looper->isRunning()); } TEST(FunctionLooperTest, PacingOnce) { EventBase backingEvb; QuicEventBase evb(&backingEvb); TimerHighRes::SharedPtr pacingTimer(TimerHighRes::newTimer(&backingEvb, 1ms)); int count = 0; auto func = [&]() { ++count; }; bool firstTime = true; auto pacingFunc = [&]() -> auto { if (firstTime) { firstTime = false; return 3600000ms; } return std::chrono::milliseconds::zero(); }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looper->setPacingTimer(std::move(pacingTimer)); looper->setPacingFunction(std::move(pacingFunc)); looper->run(); evb.loopOnce(); EXPECT_EQ(1, count); EXPECT_TRUE(looper->isScheduled()); looper->timeoutExpired(); EXPECT_EQ(2, count); looper->stop(); } TEST(FunctionLooperTest, KeepPacing) { EventBase backingEvb; QuicEventBase evb(&backingEvb); TimerHighRes::SharedPtr pacingTimer( TimerHighRes::newTimer(evb.getBackingEventBase(), 1ms)); int count = 0; auto func = [&]() { ++count; }; bool stopPacing = false; auto pacingFunc = [&]() -> auto { if (stopPacing) { return std::chrono::milliseconds::zero(); } return 3600000ms; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(func), LooperType::ReadLooper)); looper->setPacingTimer(std::move(pacingTimer)); looper->setPacingFunction(std::move(pacingFunc)); looper->run(); evb.loopOnce(); EXPECT_EQ(1, count); EXPECT_TRUE(looper->isScheduled()); looper->cancelTimeout(); EXPECT_FALSE(looper->isScheduled()); looper->timeoutExpired(); EXPECT_EQ(2, count); EXPECT_TRUE(looper->isScheduled()); looper->cancelTimeout(); EXPECT_FALSE(looper->isScheduled()); looper->timeoutExpired(); EXPECT_EQ(3, count); EXPECT_TRUE(looper->isScheduled()); stopPacing = true; looper->cancelTimeout(); EXPECT_FALSE(looper->isScheduled()); looper->timeoutExpired(); EXPECT_EQ(4, count); EXPECT_FALSE(looper->isScheduled()); looper->stop(); } TEST(FunctionLooperTest, TimerTickSize) { EventBase backingEvb; QuicEventBase evb(&backingEvb); TimerHighRes::SharedPtr pacingTimer( TimerHighRes::newTimer(evb.getBackingEventBase(), 123ms)); FunctionLooper::Ptr looper(new FunctionLooper( &evb, [&]() {}, LooperType::ReadLooper)); looper->setPacingTimer(std::move(pacingTimer)); EXPECT_EQ(123ms, looper->getTimerTickInterval()); } TEST(FunctionLooperTest, TimerTickSizeAfterNewEvb) { EventBase backingEvb; QuicEventBase evb(&backingEvb); TimerHighRes::SharedPtr pacingTimer( TimerHighRes::newTimer(evb.getBackingEventBase(), 123ms)); FunctionLooper::Ptr looper(new FunctionLooper( &evb, [&]() {}, LooperType::ReadLooper)); looper->setPacingTimer(std::move(pacingTimer)); EXPECT_EQ(123ms, looper->getTimerTickInterval()); looper->detachEventBase(); EventBase backingEvb2; QuicEventBase evb2(&backingEvb2); looper->attachEventBase(&evb2); EXPECT_EQ(123ms, looper->getTimerTickInterval()); } TEST(FunctionLooperTest, NoLoopCallbackInPacingMode) { EventBase backingEvb; QuicEventBase evb(&backingEvb); TimerHighRes::SharedPtr pacingTimer( TimerHighRes::newTimer(evb.getBackingEventBase(), 1ms)); auto runFunc = [&]() {}; auto pacingFunc = [&]() { return 3600000ms; }; FunctionLooper::Ptr looper( new FunctionLooper(&evb, std::move(runFunc), LooperType::ReadLooper)); looper->setPacingTimer(std::move(pacingTimer)); looper->setPacingFunction(std::move(pacingFunc)); // bootstrap the looper looper->run(); // this loop will schedule pacer not looper: evb.loopOnce(); EXPECT_TRUE(looper->isScheduled()); EXPECT_FALSE(looper->isLoopCallbackScheduled()); looper->stop(); } } // namespace test } // namespace quic
#ifndef PROPERTYWIDGET_HPP #define PROPERTYWIDGET_HPP #include <QDialog> #include <mjson.hpp> #include <vector> #include <string> namespace Ui { class PropertyWidget; } namespace Maint { class PropertyItemWidget; class PropertyWidget : public QDialog { Q_OBJECT Ui::PropertyWidget *ui; std::vector<PropertyItemWidget*> _widgets; void ClearItems(); public: explicit PropertyWidget(QWidget *parent = 0); ~PropertyWidget(); void SetProperties(const mjson::Value& value); mjson::Value GetProperties() const; private slots: void AddWidget(); void AddWidget(const std::string& name, const mjson::Value &value); }; } #endif // PROPERTYWIDGET_HPP
#include "CustomPillar.h" #include "CustomPhysics/CustomPhysics.h" #include "Definitions.h" USING_NS_CC; // Initialize instance bool CustomPillar::init() { // Super init first return Pillar::init(); } // Initialize physics void CustomPillar::initPhysics(CPWorld* world) { // Top body creation topBody_ = new CPRectangle(world, topPillar_->getContentSize(), this->getPosition() + topPillar_->getPosition()); topBody_->selfMask = COLLISION_BITMASK_OBSTACLE; topBody_->hitMask = COLLISION_BITMASK_SPACESHIP; // collide with spaceship topBody_->userData = topPillar_; // Bottom body creation botBody_ = new CPRectangle(world, botPillar_->getContentSize(), this->getPosition() + botPillar_->getPosition()); botBody_->selfMask = COLLISION_BITMASK_OBSTACLE; botBody_->hitMask = COLLISION_BITMASK_SPACESHIP; // collide with spaceship botBody_->userData = botPillar_; }
// Question 6 => Write a Program to check whether a string is a valid shuffle of two strings or not /* 1. Suppose we have two string st1 = "onetwofour" and str2 = "hellofourtwooneworld" */ #include<bits/stdc++.h> using namespace std; bool shuffleString(string A, string B) { int n = A.length(); int m = B.length(); // Return false if length of // string A is greater than // length of string B if (n > m) { return false; } else { // Sort string A sort(A.begin(), A.end()); // Traverse string B for (int i = 0; i < m; i++) { // Return false if (i+n-1 >= m) // doesn't satisfy if (i + n - 1 >= m) return false; // Initialise the new string string str = ""; // Copy the characters of // string B in str till // length n for (int j = 0; j < n; j++) str.push_back(B[i + j]); // Sort the string str sort(str.begin(), str.end()); // Return true if sorted // string of "str" & sorted // string of "A" are equal if (str == A) return true; } } return true; } int main(){ string str1 = "onetwofsour"; string str2 = "hellofourtwooneworld"; bool result = shuffleString(str1, str2); if(result) cout<<"YES......."; else cout<<"NO!!!!!"; return 0; }
/* * Copyright 2019 LogMeIn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include "Task.h" #include "detail/TaskCancelable.h" #include <memory> namespace asyncly { class CancelableTask { public: CancelableTask( const std::shared_ptr<Task>& task, const std::shared_ptr<TaskCancelable>& cancelable) : task_(task) , cancelable_(cancelable) { } void operator()() const { if (cancelable_->maybeMarkAsRunning()) { (*task_)(); } } private: std::shared_ptr<Task> task_; std::shared_ptr<TaskCancelable> cancelable_; }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** psmaas - Patricia Aas */ #include "core/pch.h" #ifdef HISTORY_SUPPORT #include "modules/history/OpHistoryPage.h" #include "modules/history/OpHistoryFolder.h" #include "modules/history/OpHistoryPrefixFolder.h" #include "modules/history/OpHistorySiteFolder.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #ifdef HISTORY_DEBUG INT HistoryPage::m_number_of_pages = 0; INT HistoryPage::s_number_of_addresses = 0; INT HistoryPage::s_total_address_length = 0; INT HistoryPage::s_number_of_titles = 0; INT HistoryPage::s_total_title_length = 0; #endif //HISTORY_DEBUG /*********************************************************************************** ** Creates a new HistoryPage with a uniqe id. The field m_title is ** set in the Construct method. ** ** HistoryPage::HistoryPage ** @param acc ** @param average_interval ***********************************************************************************/ HistoryPage::HistoryPage(time_t acc, time_t average_interval, HistoryKey * key): m_accessed(acc), m_average_interval(average_interval), m_flags(0), m_key(0), m_associated_item(0) { SetKey(key); #ifdef HISTORY_DEBUG m_number_of_pages++; #endif //HISTORY_DEBUG } /*********************************************************************************** ** Attempts to allocate for the fields. Will return 0 if ** not successful. If successful will return pointer to a HistoryPage. ** ** HistoryPage::Create ** @param acc ** @param average_interval ** @param title ** @param key ** ** @return HistoryPage* (or 0 if out of memory) ***********************************************************************************/ HistoryPage* HistoryPage::Create(time_t acc, time_t average_interval, const OpStringC& title, HistoryKey * key) { OP_ASSERT(key); OpAutoPtr<HistoryPage> history_page(OP_NEW(HistoryPage, (acc, average_interval, key))); if(!history_page.get()) return 0; RETURN_VALUE_IF_ERROR(history_page->SetTitle(title), 0); return history_page.release(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ const uni_char * HistoryPage::GetStrippedAddress() const { const LexSplayKey* key = GetKey(); return key ? key->GetKey() : 0; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ const uni_char * HistoryPage::GetPrefix() const { HistoryPrefixFolder* folder = GetPrefixFolder(); return folder ? folder->GetPrefix() : 0; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ INT32 HistoryPage::GetPrefixNum() const { HistoryPrefixFolder* folder = GetPrefixFolder(); return folder ? folder->GetIndex() : 0; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS HistoryPage::GetAddress(OpString & address) const { RETURN_IF_ERROR(address.Set(GetPrefix())); RETURN_IF_ERROR(address.Append(GetStrippedAddress())); return OpStatus::OK; } /*********************************************************************************** ** Delete ** ** HistoryPage::~HistoryPage ***********************************************************************************/ HistoryPage::~HistoryPage() { #ifdef HISTORY_DEBUG m_number_of_pages--; #endif //HISTORY_DEBUG SetKey(0); } /*********************************************************************************** ** Calculates an items average popularity in seconds. If item has no average ** interval set the method will return with a monthly visit (2419200 = 28*24*60*60), ** otherwise if the average interval was greater than the new interval the new ** interval is weighted at 20%, if the average interval was less than the new ** interval the new interval is weighted at 10%. Meaning an item will increase in ** popularity faster than it will lose it. ** ** HistoryPage::GetPopularity ** ** @return average interval for this item in seconds ***********************************************************************************/ time_t HistoryPage::GetPopularity() { time_t now = g_timecache->CurrentTime(); if (m_average_interval == -1) { return op_abs(long(now - m_accessed + 2419200)); // initialize with monthly visit } else { if (m_average_interval > (now - m_accessed)) { // increase popularity faster return op_abs(long((m_average_interval * 4 + (now - m_accessed)) / 5)); } else { // decrease popularity slower return op_abs(long((m_average_interval * 9 + (now - m_accessed)) / 10)); } } } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void HistoryPage::UpdateAccessed(time_t acc) { if(acc > m_accessed) { time_t now = g_timecache->CurrentTime(); time_t last = m_accessed; if (now - last > 60) // update popularity max every min m_average_interval = GetPopularity(); m_accessed = acc; BroadcastHistoryItemAccessed(acc); } } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void HistoryPage::SetKey(HistoryKey * key) { if(key) key->Increment(); if(m_key) m_key->Decrement(); #ifdef HISTORY_DEBUG if(m_key) { s_number_of_addresses--; s_total_address_length -= (uni_strlen(m_key->GetKey()) * sizeof(uni_char)); } if(key) { s_number_of_addresses++; s_total_address_length += (uni_strlen(key->GetKey()) * sizeof(uni_char)); } #endif //HISTORY_DEBUG if(m_key && !m_key->InUse()) OP_DELETE(m_key); m_key = key; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS HistoryPage::SetAssociatedItem(HistoryPage * associated_item) { if(m_associated_item) return OpStatus::ERR; m_associated_item = associated_item; return OpStatus::OK; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void HistoryPage::ClearAssociatedItem() { HistoryPage * associated_item = m_associated_item; m_associated_item = 0; if(associated_item) associated_item->ClearAssociatedItem(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ #ifdef HISTORY_DEBUG void HistoryPage::OnTitleSet() { OpString title; GetTitle(title); if(title.HasContent()) { s_number_of_titles++; s_total_title_length += (title.Length() * sizeof(uni_char)); } } #endif // HISTORY_DEBUG /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ void HistoryPage::OnSiteFolderSet() { if(GetSiteFolder()) { if(GetSiteFolder()->GetKey() == GetKey()) SetIsDomain(); else ClearIsDomain(); } } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ BOOL HistoryPage::IsVisited() const { const time_t now = g_timecache->CurrentTime(); const time_t accessed = GetAccessed(); time_t elapsed = now - accessed; return elapsed <= g_pcnet->GetFollowedLinksExpireTime(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ const char* HistoryPage::GetImage() const { return IsBookmarked() ? (IsVisited() ? "Bookmark Visited" : "Bookmark Unvisited") : "Window Document Icon"; } #endif // HISTORY_SUPPORT
#pragma once template <typename Type, typename Traits> class unique_handle { unique_handle(unique_handle const &) = delete; unique_handle &operator=(unique_handle const &) = delete; void close() throw() { if (*this) { Traits::close(m_value); } } Type m_value; public: explicit unique_handle(Type value = Traits::invalid()) throw() : m_value(value) { } ~unique_handle() throw() { close(); } private: struct boolean_struct { int member; }; typedef int boolean_struct::*boolean_type; bool operator==(unique_handle const &) = delete; bool operator!=(unique_handle const &) = delete; public: operator boolean_type() const throw() { return Traits::invalid() != m_value ? &boolean_struct::member : nullptr; } bool reset(Type value = Traits::invalid()) throw() { if (m_value != value) { close(); m_value = value; } return *this; } Type release() throw() { auto value = m_value; m_value = Traits::invalid(); return value; } unique_handle(unique_handle &&other) throw() : m_value(other.release()) { } unique_handle &operator=(unique_handle &&other) throw() { reset(other.release()); return *this; } operator const Type &() const { return m_value; } };
#include "ColorCorrection2bit.h" ColorCorrection2bit::ColorCorrection2bit(uint32_t color1, uint32_t color2, uint32_t color3, uint32_t color4) { colorsRGBA[0] = color1; colorsRGBA[1] = color2; colorsRGBA[2] = color3; colorsRGBA[3] = color4; } ColorCorrection2bit::~ColorCorrection2bit() { }
#include<iostream> #include<math.h> using namespace std; int main(){ int k, q; for(int i = 7; i < 10; i++){ k = (i -6)*pow(10,2) + (i - 3)*pow(10,1) + i; q = (i -6)*pow(10,3) + (i - 3)*pow(10,2) + i; if(q - k == 2250){ cout << k; return 0; } } }
#include <csignal> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL.h> #include "Sound_Queue.h" #include "apu.hpp" #include "cartridge.hpp" #include "cpu.hpp" #include "menu.hpp" #include "gui.hpp" #include "config.hpp" #include <dirent.h> #include <switch.h> namespace GUI { const unsigned WIDTH = 256; const unsigned HEIGHT = 240; // SDL structures: SDL_Window *window; SDL_Renderer *renderer; SDL_Texture *gameTexture; SDL_Texture *background; TTF_Font *font; u8 const *keys; Sound_Queue *soundQueue; SDL_Joystick *joystick[] = {nullptr, nullptr}; // Menus: Menu *menu; Menu *mainMenu; Menu *settingsMenu; Menu *videoMenu; Menu *keyboardMenu[2]; Menu *joystickMenu[2]; FileMenu *fileMenu; bool pause = true; int currentRenderQuality = 0; bool exitFlag = false; Mutex pixelMutex; /*void set_render_quality(int quality) { switch(quality) { case 0: SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); currentRenderQuality = 0; break; case 1: SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); currentRenderQuality = 1; break; case 2: SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best"); currentRenderQuality = 2; break; default: SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest"); currentRenderQuality = 1; break; } }*/ /* Set the window size multiplier */ void set_size(int mul) { last_window_size = mul; SDL_SetWindowSize(window, WIDTH * mul, HEIGHT * mul); SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); } void updateVideoMenu() { /*std::string quality("Render Quality: "); switch(currentRenderQuality) { case 0: quality += "Fastest"; break; case 1: quality += "Medium"; break; case 2: quality += "Nicest"; break; default: quality += "Fastest"; break; }*/ videoMenu = new Menu; videoMenu->add(new Entry("<", [] { menu = settingsMenu; })); videoMenu->add(new Entry("Size 1x", [] { set_size(1); })); videoMenu->add(new Entry("Size 2x", [] { set_size(2); })); videoMenu->add(new Entry("Size 3x", [] { set_size(3); })); /*videoMenu->add(new Entry((quality), []{ set_render_quality((currentRenderQuality + 1) % 3); updateVideoMenu(); menu = videoMenu; })); */ } /* Initialize GUI */ void init() { // Initialize graphics system: if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) < 0) { printf("Failed to init video, audio, and joystick\n"); return; } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); if (TTF_Init() < 0) { printf("Failed to init TTF\n"); return; } printf("Attempting to open joysticks..."); for (int i = 0; i < 2; i++) { joystick[i] = SDL_JoystickOpen(i); if (joystick[i] == nullptr) { printf("Joystick %d Failure!\n", i); return; } } printf("Done.\n"); printf("Initializing APU..."); APU::init(); printf("Done.\n"); soundQueue = new Sound_Queue; soundQueue->init(96000); printf("Initializing graphics structures..."); window = SDL_CreateWindow(NULL, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH * last_window_size, HEIGHT * last_window_size, SDL_WINDOW_FULLSCREEN); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_SOFTWARE); SDL_RenderSetLogicalSize(renderer, WIDTH, HEIGHT); gameTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, WIDTH, HEIGHT); font = TTF_OpenFont("res/font.ttf", FONT_SZ); if(!font) { printf("Failed to open res/font.ttf!"); exit(1); } printf("...done"); // keys = SDL_GetKeyboardState(0); printf("Setting background..."); if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) { printf("Failed to initialize PNG!"); exit(1); } SDL_Surface *backSurface = IMG_Load("res/init.png"); background = SDL_CreateTextureFromSurface(renderer, backSurface); SDL_SetTextureColorMod(background, 60, 60, 60); SDL_FreeSurface(backSurface); if(!background) { printf("Failed to create background!"); exit(1); } // Menus: mainMenu = new Menu; mainMenu->add(new Entry("Load ROM", [] { menu = fileMenu; })); mainMenu->add(new Entry("Settings", [] { menu = settingsMenu; })); mainMenu->add(new Entry("Exit", [] { exitFlag = true; })); settingsMenu = new Menu; settingsMenu->add(new Entry("<", [] { menu = mainMenu; })); // TODO: Add this back and enable substituting the render quality during runtime // settingsMenu->add(new Entry("Video", []{ menu = videoMenu; })); settingsMenu->add(new Entry("Controller 1", []{ menu = joystickMenu[0]; })); // updateVideoMenu(); settingsMenu->add(new Entry("Controller 2", []{ menu = joystickMenu[1]; })); settingsMenu->add(new Entry("Save Settings", [] { save_settings(); menu = mainMenu; })); for (int i = 0; i < 2; i++) { joystickMenu[i] = new Menu; joystickMenu[i]->add(new Entry("<", [] { menu = settingsMenu; })); joystickMenu[i]->add(new ControlEntry("Up", &BTN_UP[i])); joystickMenu[i]->add(new ControlEntry("Down", &BTN_DOWN[i])); joystickMenu[i]->add(new ControlEntry("Left", &BTN_LEFT[i])); joystickMenu[i]->add(new ControlEntry("Right", &BTN_RIGHT[i])); joystickMenu[i]->add(new ControlEntry("A", &BTN_A[i])); joystickMenu[i]->add(new ControlEntry("B", &BTN_B[i])); joystickMenu[i]->add(new ControlEntry("Start", &BTN_START[i])); joystickMenu[i]->add(new ControlEntry("Select", &BTN_SELECT[i])); } fileMenu = new FileMenu; menu = mainMenu; } //* Render a texture on screen */ void render_texture(SDL_Texture *texture, int x, int y) { int w, h; SDL_Rect dest; SDL_QueryTexture(texture, NULL, NULL, &dest.w, &dest.h); if (x == TEXT_CENTER) dest.x = WIDTH / 2 - dest.w / 2; else if (x == TEXT_RIGHT) dest.x = WIDTH - dest.w - 10; else dest.x = x + 10; dest.y = y + 5; SDL_RenderCopy(renderer, texture, NULL, &dest); } /* Generate a texture from text */ SDL_Texture *gen_text(std::string text, SDL_Color color) { SDL_Surface *surface = TTF_RenderText_Blended(font, text.c_str(), color); SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); return texture; } /* Get the joypad state from SDL */ u8 get_joypad_state(int n) { const int DEAD_ZONE = 8000; u8 j = 0; j |= (SDL_JoystickGetButton(joystick[n], BTN_A[n])) << 0; // A. j |= (SDL_JoystickGetButton(joystick[n], BTN_B[n])) << 1; // B. j |= (SDL_JoystickGetButton(joystick[n], BTN_SELECT[n])) << 2; // Select. j |= (SDL_JoystickGetButton(joystick[n], BTN_START[n])) << 3; // Start. j |= (SDL_JoystickGetButton(joystick[n], BTN_UP[n])) << 4; // Up. j |= (SDL_JoystickGetAxis(joystick[n], 1) < -DEAD_ZONE) << 4; j |= (SDL_JoystickGetButton(joystick[n], BTN_DOWN[n])) << 5; // Down. j |= (SDL_JoystickGetAxis(joystick[n], 1) > DEAD_ZONE) << 5; j |= (SDL_JoystickGetButton(joystick[n], BTN_LEFT[n])) << 6; // Left. j |= (SDL_JoystickGetAxis(joystick[n], 0) < -DEAD_ZONE) << 6; j |= (SDL_JoystickGetButton(joystick[n], BTN_RIGHT[n])) << 7; // Right. j |= (SDL_JoystickGetAxis(joystick[n], 0) > DEAD_ZONE) << 7; return j; } /* Send the rendered frame to the GUI */ void new_frame(u32 *pixels) { SDL_UpdateTexture(gameTexture, NULL, pixels, WIDTH * sizeof(u32)); } void new_samples(const blip_sample_t *samples, size_t count) { soundQueue->write(samples, count); } /* Render the screen */ void render() { SDL_RenderClear(renderer); // Draw the NES screen: if (Cartridge::loaded()) SDL_RenderCopy(renderer, gameTexture, NULL, NULL); else SDL_RenderCopy(renderer, background, NULL, NULL); // Draw the menu: if (pause) menu->render(); SDL_RenderPresent(renderer); } /* Play/stop the game */ void toggle_pause() { printf("Toggling pause\n"); pause = !pause; menu = mainMenu; if (pause) { printf("Paused, setting gameTexture\n"); SDL_SetTextureColorMod(gameTexture, 60, 60, 60); } else { printf("Not paused, setting gameTexture\n"); SDL_SetTextureColorMod(gameTexture, 255, 255, 255); } } /* Prompt for a key, return the scancode */ SDL_Scancode query_key() { SDL_Texture *prompt = gen_text("Press a key...", {255, 255, 255}); render_texture(prompt, TEXT_CENTER, HEIGHT - FONT_SZ * 4); SDL_RenderPresent(renderer); SDL_Event e; while (true) { SDL_PollEvent(&e); if (e.type == SDL_KEYDOWN) return e.key.keysym.scancode; } } int query_button() { SDL_Texture *prompt = gen_text("Press a button...", {255, 255, 255}); render_texture(prompt, TEXT_CENTER, HEIGHT - FONT_SZ * 4); SDL_RenderPresent(renderer); SDL_Event e; while (true) { SDL_PollEvent(&e); if (e.type == SDL_JOYBUTTONDOWN) { printf("Button pressed: %d", e.jbutton.button); return e.jbutton.button; } } } /* Run the emulator */ void run() { printf("In run()\n"); SDL_Event e; // Framerate control: u32 frameStart, frameTime; const int FPS = 60; const int DELAY = 100.0f / FPS; while (true) { frameStart = SDL_GetTicks(); // Handle events: while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_QUIT: return; case SDL_JOYBUTTONDOWN: if ((e.jbutton.button == JOY_R) and Cartridge::loaded()) toggle_pause(); else if (pause) menu->update(e.jbutton.button); } } if(not pause) { CPU::run_frame(); } render(); if (exitFlag) { SDL_Quit(); return; } // Wait to mantain framerate: frameTime = SDL_GetTicks() - frameStart; if (frameTime < DELAY) SDL_Delay((int)(DELAY - frameTime)); } } } // namespace GUI
//User function Template for C++ // Get min at pop /* inserts elements of the array into stack and return the stack */ stack<int> _push(int arr[],int n) { // your code here stack<int> s; s.push(arr[0]); for(int i=1; i<n; i++) { if(s.top() >= arr[i]) s.push(arr[i]); else s.push(s.top()); } return s; } /* print minimum element of the stack each time after popping */ void _getMinAtPop(stack<int>s) { // your code here while(!s.empty()) { cout << s.top() << " "; s.pop(); } }
#include <iostream> #include <vector> #include <queue> #include <iterator> using namespace std; int n, l, a[5000001]; vector<int> d; struct MinimumNumber { int number; int index; MinimumNumber(int num, int idx) : number(num), index(idx) {} bool operator<(const MinimumNumber s) const { return this->number > s.number; } }; void SlidingWindow() { int start, i = 1; priority_queue<MinimumNumber> pq; while (i <= n) { start = (i - l + 1 < 1)? 1: i - l + 1; pq.push({ a[i], i }); while (!pq.empty()) { if (pq.top().index < start) pq.pop(); else { d.push_back(pq.top().number); break; } } i++; } } int main(void) { ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); cin >> n >> l; for (int i = 1; i <= n; i++) cin >> a[i]; SlidingWindow(); copy(d.begin(), d.end(), ostream_iterator<int>(cout, " ")); return 0; }
#include <stdio.h> #include <stdlib.h> #include <cstring> #include "DynamicArray.h" typedef struct PERSON { LinkNode node; char name[64]; int age; }Person; void printLinkNode(LinkNode* data){ Person* p = (Person*)data; printf("name: %s\t age: %d\n", p->name, p->age); } int main(int argc, char const *argv[]) { Person p1, p2, p3; strcpy(p1.name, "aaa"); p1.age = 10; strcpy(p2.name, "bbb"); p2.age = 20; strcpy(p3.name, "ccc"); p3.age = 30; LinkStack* stack = initLinkStack(); pushLinkStack(stack, (LinkNode*)&p1); pushLinkStack(stack, (LinkNode*)&p2); pushLinkStack(stack, (LinkNode*)&p3); while (sizeLinkStack(stack) > 0) { LinkNode* node = topLinkStack(stack); popLinkStack(stack); } freeLinkStack(stack); return 0; }
#include "Square.h" double Square::area() { return a * a; }
#include <algorithm> #include <iostream> #include <numeric> #include <vector> using namespace std; using ll = long long; const ll MOD = 1000000007; int main() { int N; cin >> N; ll dp[N + 1]; fill(dp + 1, dp + N + 1, 0); dp[0] = 1; for (int i = 0; i < N; ++i) { // dp[n] = a[1]~a[i]で作れるサイズnのgood subseqs int a; cin >> a; vector<int> facts; for (int n = 1; n <= N && n * n <= a; ++n) { if (a % n == 0) { facts.push_back(n); if (a / n <= N && a / n != n) facts.push_back(a / n); } } sort(facts.rbegin(), facts.rend()); for (int j : facts) { dp[j] += dp[j - 1]; dp[j] %= MOD; } } cout << accumulate(dp + 1, dp + N + 1, 0LL) % MOD << endl; return 0; }
#ifndef _camera_setup_h #define _camera_setup_h #include "vector.hpp" #include <stdint.h> #include <math.h> #define DEBUG #define PI 3.14159 class Camera_Setup { private: Vector camera_center; Vector UP_VEC; Vector W; /* Towards Image plane */ Vector U; /* 3rd vector perpendicular to W & U */ Vector V; /* Head direction */ double distance; /*Distance from image plane*/ int im_plane_width; int im_plane_height; double aspect_ratio; double theta_u; double theta_v; public: Camera_Setup():camera_center(),UP_VEC(Vector(0.0,1.0,0.0)),W(Vector(0.0,0.0,-1.0)),distance(1.0),im_plane_width(640),im_plane_height(640),theta_u(90),theta_v(90){} Camera_Setup(const Vector& center,const Vector& up_vec, const Vector& w, double dist,int img_w, int img_h, double theta_u, double theta_v); void camera_initialization(); Vector compute_pixel_vector(uint32_t row, uint32_t col); Vector get_camera_center(); double get_pixel_height(); }; Camera_Setup::Camera_Setup(const Vector& center,const Vector& up_vec, const Vector& w, double dist,int img_w, int img_h, double theta_u, double theta_v) { camera_center = center; UP_VEC = up_vec; W = w; distance = dist; im_plane_width = img_w; im_plane_height = img_h; this->theta_u = theta_u; this->theta_v = theta_v; camera_initialization(); } void Camera_Setup::camera_initialization() { aspect_ratio = im_plane_width/im_plane_height; U = U.CrossProduct(W,UP_VEC); U = U.unit_vector(); /* Normalize */ V = V.CrossProduct(U,W); V = V.unit_vector(); /* Normalize */ #ifdef DEBUG W.display_vector(); U.display_vector(); V.display_vector(); camera_center.display_vector(); #endif } Vector Camera_Setup::compute_pixel_vector(uint32_t row, uint32_t col) { double pix_w = (2*tan((PI*theta_u/180)/2)*distance)/im_plane_width; double pix_h = (2*tan((PI*theta_v/180)/2)*distance)/im_plane_height; Vector pix_loc = camera_center + W - U*((im_plane_width/2.0)*pix_w) + V*((im_plane_height/2.0)*pix_h) + U*(pix_w/2.0) - V*(pix_h/2.0) + U*(pix_w*col) - V*(pix_h*row); Vector vec_dir = pix_loc - camera_center; vec_dir = vec_dir.unit_vector(); //vec_dir.display_vector(); return vec_dir; } Vector Camera_Setup::get_camera_center() { return camera_center; } double Camera_Setup::get_pixel_height() { double pix_h = (2*tan((PI*theta_v/180)/2)*distance)/im_plane_height; return pix_h; } #endif
#include <tr1/array> #include <tr1/memory> #include <iostream> #include "PortalSpace.h" #include "PortalSpace2d.h" #include <Eigen/Core> #define _USE_MATH_DEFINES #include <cmath> #include "Assert.h" using Eigen::Matrix3d; using Eigen::Vector3d; double PortalSpace::getK() { return log(2*M_PI)/(2*M_PI); } PortalSpace::Point::Point() { hyperbolic = M_PI/2; spherical << 0,0,1; } //std::tr1::array<double,3> PortalSpace::Point::coordinates; PortalSpace::Point::Point(double hyperbolic, double x, double y, double z, PortalSpace* space) { //Hyperbolic is an angle from 0 to 2pi. I think it would be faster and more numerically stable to use the tangent of the angle, but now is not the time for optimization. this->hyperbolic = hyperbolic; spherical[0] = x; spherical[1] = y; spherical[2] = z; this->space = space; } //PortalSpace::Point::~Point() {} Vector3d PortalSpace::Point::getVector() { return exp(hyperbolic)*spherical; } PortalSpace* PortalSpace::Point::getSpace() { return space; } //PortalSpace::Point PortalSpace::PointOfReference::position; //Matrix3d PortalSpace::PointOfReference::orientation; /*Manifold::Point PortalSpace::Point::midpoint(Manifold::Point point) { }*/ /*std::vector<Vector3d> PortalSpace::PointOfReference::vectorsFromPoint(std::tr1::shared_ptr<Manifold::Point> point) { std::vector<Vector3d> outVector; outVector.push_back(Vector3d()); return outVector; }*/ std::vector<Vector3d> PortalSpace::PointOfReference::vectorsFromPoint(std::tr1::shared_ptr<Manifold::Point> point) { //Don't forget to check if they're on the same vertical line. Also, show more points. double k = position.space->getK(); Vector3d x = position.spherical; std::tr1::shared_ptr<PortalSpace::Point> p = std::tr1::static_pointer_cast<PortalSpace::Point>(point); Vector3d y = p->spherical; assert(abs(x.norm()-1) < EPSILON); assert(abs(y.norm()-1) < EPSILON); //Vector3d y(p->spherical[0],p->spherical[1],p->spherical[2]); double dot = x.dot(y); double theta = asin(dot); Vector3d yy = y-dot*x; yy.normalize(); //yy is the normalization of the component of y perpendicular to x. This makes it the spherical component of the direction towards y. PortalSpace2d::Point x2d(position.hyperbolic,0.); PortalSpace2d::Point y2d(position.hyperbolic,theta*k); Vector2d z = x2d.vectorFromPoint(y2d); Vector4d out; out << z[0], z[1]*yy; //Vector4d out(dir_hyperbolic,spherical[0],spherical[1],spherical[2]); out = orientation.transpose()*out; assert(abs(out[3]) < EPSILON); std::vector<Vector3d> outVector; //std::cout << "out: " << out << "\n" << std::flush; outVector.push_back(out.start<3>()); //outVector.push_back(Vector3d(0,0,0)); /*std::cout << "vectorsFromPoint:\n"; //TODO std::cout << orientation << "\n"; //TODO std::cout << "x0: " << x0 << "\nx1: " << x1 << "\n"; std::cout << "y0: " << y0 << "\ny1: " << y1 << "\n"; std::cout << "dir_hyperbolic*dist: " << dir_hyperbolic*dist << "\ndir_spherical*dist: " << dir_spherical*dist << "\n"; std::cout << "y:\n" << y << "\n"; std::cout << "c: " << c << "\nr: " << r << "\n"; std::cout << "vector:\n" << out << "\n"; std::cout << "p->hyperbolic: " << p->hyperbolic-M_PI/2 << "\n";*/ assert(fabs(std::tr1::static_pointer_cast<PortalSpace::Point>(this->pointFromVector(outVector[0]))->hyperbolic-p->hyperbolic) < EPSILON); //std::cout << "std::tr1::static_pointer_cast<PortalSpace::Point>(pointFromVector(outVector[0]))->spherical:\n" << std::tr1::static_pointer_cast<PortalSpace::Point>(pointFromVector(outVector[0]))->spherical << "\n"; //std::cout << "p->spherical:\n" << p->spherical << "\n"; std::cout << "yy:\n" << yy << "\n"; //std::cout << "outVector[0]:\n" << outVector[0] << "\n"; assert((std::tr1::static_pointer_cast<PortalSpace::Point>(this->pointFromVector(outVector[0]))->spherical - p->spherical).norm() < EPSILON); return outVector; } std::tr1::shared_ptr<Manifold::Point> PortalSpace::PointOfReference::pointFromVector(Vector3d vector) { double k = position.space->getK(); Vector4d v(vector[0],vector[1],vector[2],0); //Vector4d v << vector,0; v = orientation*v; std::cout << "v.end<3>().normalized():\n" << v.end<3>().normalized() << "\n"; PortalSpace2d::Point x2d(position.hyperbolic,0.); Vector2d z2d(v[0],v.end<3>().norm()); std::tr1::array<double,2> y2d = x2d.pointFromVector(z2d).getCoordinates(); y2d[1] /= k; Vector4d y; Vector3d ytail = position.spherical*cos(y2d[1])+v.end<3>().normalized()*sin(y2d[1]); y << y2d[0], ytail; //std::cout << "y: " << y << "\n" << std::flush; std::tr1::shared_ptr<PortalSpace::Point> out = std::tr1::shared_ptr<PortalSpace::Point>(new PortalSpace::Point(y[0],y[1],y[2],y[3],position.space)); //std::cout << this->vectorsFromPoint(out)[0] << "\n" << vector << "\n" << std::flush; //TODO /*std::cout << "pointFromVector:\n"; //TODO std::cout << "theta: " << theta << "\n"; std::cout << "sin(theta): " << sin(theta) << "\n"; std::cout << "x0: " << x0 << "\nx1: " << x1 << "\n"; std::cout << "y0: " << y0 << "\ny1: " << y1 << "\n"; std::cout << "z0: " << z0 << "\nz1: " << z1 << "\n"; std::cout << "c: " << c << "\nr: " << r << "\n"; Vector4d x; x << position.hyperbolic, position.spherical; std::cout << "delta:\n" << y-x << "\n"; std::cout << "out->hyperbolic: " << out->hyperbolic-M_PI/2 << "\nout->spherical\n" << out->spherical << "\n"; std::cout << "vector:\n" << vector << "\n";*/ return out; } PortalSpace::PointOfReference::PointOfReference(PortalSpace* space) { orientation = orientation.Identity(); position.space = space; } PortalSpace::PointOfReference::~PointOfReference() { } Manifold::Point* PortalSpace::PointOfReference::getPosition() { return &position; } void PortalSpace::PointOfReference::move(Vector3d dir) { //Don't forget to check if they're on the same vertical line. double k = position.space->getK(); Vector4d v; v << dir, 0; v = orientation*v; PortalSpace2d::Point x2d(position.hyperbolic,0.); Vector2d z2d(v[0],v.end<3>().norm()); std::pair<PortalSpace2d::Point,double> pointAndRot = x2d.pointAndRotFromVector(z2d); std::tr1::array<double,2> y2d = pointAndRot.first.getCoordinates(); y2d[1] /= k; double rot = pointAndRot.second; Vector3d ytail = position.spherical*cos(y2d[1])+v.end<3>().normalized()*sin(y2d[1]); assert(fabs(ytail.norm()-1) < EPSILON); Vector3d row1 = v.end<3>().normalized(); Vector3d row2 = position.spherical; Vector3d row3 = row1.cross(row2); std::cout << "v.end<3>():\n" << v.end<3>() << "\n"; //TODO std::cout << "row1:\n" << row1 << "\n"; //TODO std::cout << "position.spherical:\n" << position.spherical << "\n"; //TODO std::cout << "row2:\n" << row2 << "\n"; //TODO /*std::cout << "row1:\n" << row1 << "\n" << std::flush; //TODO std::cout << "row2:\n" << row2 << "\n" << std::flush; //TODO std::cout << "row3:\n" << row3 << "\n" << std::flush; //TODO*/ //std::cout << "|row1 x row2|: " << row1.cross(row2).norm() << "\n" << std::flush; //TODO std::cout << "row1 . row2:\n" << row1.dot(row2) << "\n" << std::flush; //TODO std::cout << "row2 . row3:\n" << row2.dot(row3) << "\n" << std::flush; //TODO std::cout << "row3 . row1:\n" << row3.dot(row1) << "\n" << std::flush; //TODO /*Matrix3d test; test << row1,row2,row3;*/ Matrix4d conjugate; /*conjugate << 1,0,0,0, 0,row1, 0,row2, 0,row3;*/ conjugate.block<4,1>(0,0) << 1,0,0,0; //Why can't I just use rows? Or just make the whole matrix? conjugate.block<4,1>(0,1) << 0,row1; conjugate.block<4,1>(0,2) << 0,row2; conjugate.block<4,1>(0,3) << 0,row3; std::cout << "conjugate:\n" << conjugate << "\n" << std::flush; //TODO assert((conjugate*conjugate.transpose()-Matrix4d::Identity()).norm() < EPSILON); orientation = conjugate.transpose()*orientation; std::cout << "orientation:\n" << orientation << "\n" << std::flush; //TODO Matrix4d m = Matrix4d::Identity(); m.block<2,2>(0,0) << cos(rot),sin(rot),-sin(rot),cos(rot); assert(fabs(m.determinant()-1) < EPSILON); assert((m*m.transpose()-Matrix4d::Identity()).norm() < EPSILON); orientation = m*orientation; /*double sin0 = c*x0; double cos0 = (x0*(x0-c)+x1*x1); //I'm pretty sure I can combine sin/cos0 and sin/cos1. double multiplier = 1/sqrt(sin0*sin0+cos0*cos0); sin0 *= multiplier; cos0 *= multiplier; Matrix4d m = Matrix4d::Identity(); m.block<2,2>(0,0) << cos0,sin0,-sin0,cos0; assert(fabs(m.determinant()-1) < EPSILON); assert((m*m.transpose()-Matrix4d::Identity()).norm() < EPSILON); orientation = m*orientation; double sin1 = c*y0; double cos1 = (y0*(y0-c)+y1*y1); multiplier = 1/sqrt(sin1*sin1+cos1*cos1); sin1 *= multiplier; cos1 *= multiplier; m = Matrix4d::Identity(); m.block<2,2>(0,0) << cos1,-sin1,sin1,cos1; assert(fabs(m.determinant()-1) < EPSILON); assert((m*m.transpose()-Matrix4d::Identity()).norm() < EPSILON); orientation = m*orientation;*/ double sine = sin(rot); double cosine = cos(rot); m = Matrix4d::Identity(); m.block<2,2>(1,1) << cosine,-sine,sine,cosine; assert(fabs(m.determinant()-1) < EPSILON); assert((m*m.transpose()-Matrix4d::Identity()).norm() < EPSILON); orientation = m.transpose()*orientation; //TODO: Am I supposed to do that? orientation = conjugate*orientation; assert(fabs(orientation.determinant()-1) < EPSILON); assert((orientation*orientation.transpose()-Matrix4d::Identity()).norm() < EPSILON); position.hyperbolic = y2d[0]; position.spherical = ytail; //TODO: I'm going to need to rearrange this stuff. std::cout << "(orientation.transpose()*Vector4d(0,position.spherical[0],position.spherical[1],position.spherical[2])).start(3).norm():\n" << (orientation.transpose()*Vector4d(0,position.spherical[0],position.spherical[1],position.spherical[2])).start(3).norm() << "\n"; assert((orientation.transpose()*Vector4d(0,position.spherical[0],position.spherical[1],position.spherical[2])).start(3).norm() < EPSILON); } void PortalSpace::PointOfReference::rotate(Matrix3d rot) { orientation.block<3,3>(0,0) = rot*orientation.block<3,3>(0,0); }
#ifndef CONTROLLER_H #define CONTROLLER_H #include "SoccerBot.h" #include "InfoBoard.h" #include <string> class Robot; class Vision; class Command; class Controller : public InfoBoardListener { public: Controller(SoccerBot* bot) : bot(bot), robot(bot->getRobot()), vision(bot->getVision()) {} virtual void onEnter() {} virtual void onExit() {}; virtual bool handleRequest(std::string request) { return false; } virtual bool handleCommand(const Command& cmd) { return false; } virtual std::string getJSON() { return ""; } virtual void onGoRequestedChange(bool isGoRequested) {} virtual void onTargetSideChange(Side newTargetSide) {} virtual void onGyroChange(float deltaAngle) {} virtual void step(double dt) = 0; protected: SoccerBot* bot; Robot* robot; Vision* vision; }; #endif // CONTROLLER_H
#include "CirQueue.h" template<typename T> CirQueue<T>::CirQueue() { front_ = 0; rear_ = 0; } template<typename T> CirQueue<T>::~CirQueue() { } template<typename T> void CirQueue<T>::EnQueue(T element) { if (full()) { std::cout << "Queue is full\n"; } else { data[rear_] = element; rear_ = (rear_ + 1) % max_size; } } template<typename T> void CirQueue<T>::DeQueue() { if (empty()) { std::cout << "Queue is empty\n"; } else { front_ = (front_ + 1) % max_size; } } template<typename T> T CirQueue<T>::GetFront() { return data[front_]; } template<typename T> bool CirQueue<T>::Empty() { if (front_ == rear_) return true; return false; } template<typename T> bool CirQueue<T>::Full() { if (((rear_ + 1) % max_size) == front_) return true; return false; } template<typename T> int CirQueue<T>::Size() { if (empty()) return 0; else if (full()) return max_size - 1; else return (rear_ - front_ + max_size) % max_size; }
#include "duiElement.h" duiElement::duiElement(void) { isFocused = false; startsWithFocus = false; topLink = NULL; bottomLink = NULL; leftLink = NULL; rightLink = NULL; } duiElement::~duiElement(void) { } void duiElement::Init() { } void duiElement::Update() { } void duiElement::SetFocus(bool val) { isFocused = val; } void duiElement::OnFocus() { } void duiElement::OnClick() { }
#include "EgaliseHisto.hpp" using namespace ns_wtni; EgaliseHisto::EgaliseHisto( pluglink *p ) : plugin(p) { // Ajout des donnees en entree add_input( input ); // Ajout des donnees en sortie add_output( output ); // Ajout des parametres tailleFenetre = 5; add_param( tailleFenetre, "" ); BooleanHisto = false; add_param( BooleanHisto, "" ); } bool EgaliseHisto::is_tailleFenetre_set( std::string &msg ) { // Ajouter les tests a faire sur le parametre tailleFenetre // Renseigner la variable msg si necessaire if(tailleFenetre >=3) { return true; } return false; } bool EgaliseHisto::is_BooleanHisto_set( std::string &msg ) { // Ajouter les tests a faire sur le parametre BooleanHisto // Renseigner la variable msg si necessaire return true; } bool EgaliseHisto::verifyParameters( std::string &msg, bool isRunning ) { //Tableau contenant les differents messages std::vector<std::string> msgs; std::string _msg; // Message local bool res = true; _msg.clear(); if ( is_param_input( &tailleFenetre )==isRunning && ! is_tailleFenetre_set( _msg ) ) { res = false; msgs.push_back( _msg ); } _msg.clear(); if ( is_param_input( &BooleanHisto )==isRunning && ! is_BooleanHisto_set( _msg ) ) { res = false; msgs.push_back( _msg ); } if ( msgs.size()==1 ) msg = msgs.front(); else if ( msgs.size()>1 ) { msg = "<ul>"; for (unsigned int i=0; i<msgs.size(); ++i) msg += "<li>" + msgs[i] + "</li>"; msg += "</ul>"; } return res; } bool EgaliseHisto::is_ready( std::string & msg ) { return verifyParameters(msg, false); } bool EgaliseHisto::execute( std::string &msg) { //Tester les parametres if ( !verifyParameters( msg, true ) ) return false; // Tester les entrees - A COMPLETER si NECESSAIRE ! if ( ! input ) { msg = "L'entree n°0 n'est pas initialisee."; return false; } // ALLOUER les sorties ! TODO // Ecrire le code du plugin : TODO !! const GrayImage &Input= *input; output = input; for(int i=0; i<(input->height()-1);i++) { for(int j=0; j<(input->width()-1);j++) { e1::signal<long>histoCumul(256); for(int li = i-(tailleFenetre/2);li<i+(tailleFenetre/2);li++) { for(int co=j-(tailleFenetre/2);co<j+(tailleFenetre/2);co++) { if(li>0 && li<input->height() && co>0 && co<input->width()) { int ng_p = Input[li][co]; (histoCumul)[ng_p]+=1; } } } for (int i=1; i<256;i++) { (histoCumul)[i] += (histoCumul)[i-1]; } (*output)[i][j]=histoCumul[(*output)[i][j]]*255/(histoCumul)[255]; } } return true; } CREATE_PLUGIN( EgaliseHisto );
#ifndef WIDGET_H #define WIDGET_H #include <QtGui> #include "common/constants.h" class QLabel; class QLineEdit; class QPushButton; class QTextEdit; class QVBoxLayout; class QTextBrowser; enum logFlag { SUCCESS, FAIL, HASLOGIN, REFUSED, OTHER, LOGOUT }; enum wlIssuePolicy { BROADCAST, REQUEST }; enum encryptMode { ECB, CBC }; class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); char *getUsername(); char *getPassword(); QTextEdit *getListeningFile(); enum logFlag getFlag(); void setFlag(enum logFlag); char *getIpAddress(); int getPortNumber(); void appendLisFile(QString s); void closeEvent( QCloseEvent* qce); bool string_to_unsignedchar(const char *mac,unsigned char newMac[]); private slots: void login(); void loginOK(); void logout(); void exitClient(); void clearListeningFile(); void showAbout(); void setServer(); void setServerOk(); void hideSet(); void showUsualModel(); void returnToSetModel(); void showFingerprintModel(); void showPhoneModel(); void moveEndLisFile(); signals: void loginSuccess(); private: QLabel *usernameLabel; QLabel *passwordLabel; QLabel *ipAddress; QLabel *portNumber; QLabel *macAddress; QLabel *setLabel; QLabel *modelLabel; QLabel *fingerprintModelLabel; QLabel *phoneModelLabel; QLineEdit *usernameLine; QLineEdit *passwordLine; QLineEdit *ipLine; QLineEdit *portLine; QLineEdit *macLine; QPushButton *loginButton; QPushButton *logoutButton; QPushButton *exitButton; QPushButton *aboutButton; QPushButton *setButton; QPushButton *setSubmitButton; QPushButton *hideSetButton; QPushButton *usualModelButton; QPushButton *fingerprintModelButton; QPushButton *phoneModelButton; QPushButton *returnToModelButton; QPushButton *returnToModelButton2; QTextEdit *listeningFile; //QTextBrowser *listeningFile; char username[g_ciMaxUserNameLen]; char password[g_ciMaxPwdLen]; char ccArrLocalAddr[g_ciAddrStrLen]; int ciPort; enum logFlag flag; pthread_t pt; }; #endif // WIDGET_H
#include <iostream> using namespace std; int main() { int n = 0; cin >> n; string str; int len = 0; bool alphabet[26]; char pre = '\0'; bool check = true; int sum = 0; while (n--) { cin >> str; for (int i = 0; i < 26; i++) { alphabet[i] = false; } pre = '\0'; check = true; len = str.length(); for (int i = 0; i < len; i++) { if (alphabet[str[i] - 'a'] == true && pre != str[i]) { check = false; break; } alphabet[str[i] - 'a'] = true; pre = str[i]; } if (check) { sum++; } } cout << sum; return 0; }
#include <iostream> #include <cmath> using namespace std; inline double DistanceFormular(int x1, int y1, int x2, int y2) { return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } /* * r1 = r2, d = 0, -> infinity * |r1 - r2| < d < r1 + r2 -> two point approach * r1 + r2 = d, |r1 - r2| = d -> one point approach * r1 + r2 < d, |r1 - r2| > d, d = 0 -> not approach */ int RelationshipOfTwoCircles(int r1, int r2, double d) { if (r1 == r2 && !d) return -1; if (abs(r1 - r2) < d && d < r1 + r2) return 2; if (abs(r1 - r2) == d || d == r1 + r2) return 1; return 0; } int main(void) { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); int test_case; cin >> test_case; for (int i = 0; i < test_case; i++) { int x1, y1, r1, x2, y2, r2; cin >> x1 >> y1 >> r1 >> x2 >> y2 >> r2; cout << RelationshipOfTwoCircles(r1, r2, DistanceFormular(x1, y1, x2, y2)) << endl; } return 0; }
#include <ESP8266WiFi.h> const char* ssid = "stargate"; const char* password = "4110656003373428"; int pinLed = D5; // pin on ESP that controls LED int pinHall = A0; // pin on ESP that is input of hall sensor int statRunning = 0; // status: is hamster currently running? (0-no 1-yes) int statDistDay = 0; // statistic of distance ran today (meters) int statDistWk = 0; //statistic of distance ran this week (meters) int statLastRun = 0; // statistic moment of last measured run TODO take right datetype int statLastRunDuration = 0; // statistic duration of last measured run TODO take right datetype int value = 0; float volts = 0.0; float tempc = 0.0; WiFiServer server(80); void setup() { Serial.begin(115200); delay(10); pinMode(pinLed, OUTPUT); pinMode(pinHall, INPUT); digitalWrite(pinLed, LOW); // Connect to WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.print("Use this URL : "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/"); } void loop() { int readHall; // Serial.print("temperature= "); // Serial.println(tempc); // Check if a client has connected WiFiClient client = server.available(); if (!client) { readHall = analogRead(pinHall); Serial.print("Hall value: "); Serial.print(readHall); Serial.println(); delay(250); return; } // Wait until the client sends some data Serial.println("new client"); while (!client.available()) { delay(1); } // Read the first line of the request String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); // Match the request int value = LOW; if (request.indexOf("/LED=ON") != -1) { digitalWrite(pinLed, HIGH); value = HIGH; } if (request.indexOf("/LED=OFF") != -1) { digitalWrite(pinLed, LOW); value = LOW; } returnWebPage(client); } void returnWebPage(WiFiClient client) { // Return the response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // do not forget this one client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<H1> Roxy </H1>"); client.println("<H2> Activiteit </H2>"); client.println("Hoe actief is Roxy ? <br> "); if (statRunning == 1) { client.println(" Roxy is nu lekker aan het rennen <br> "); } else { client.println("Roxy doet nu even rustig aan.... <br> "); } client.println("De laatste sessie duurde "); client.println(statLastRunDuration); client.println(" minuten. <br> "); client.println("De laatste sessie is "); client.println(statLastRun); client.println(" minuten geleden. <br>"); client.println("Het is lekker warm bij Roxy..<br> "); value = analogRead(A0); volts = (value / 1024.0)*5.0; tempc = volts*100.0*0.66; // voltage range sensor = 0-5 but esp has 0-3.3V.. client.println("<H2> Temperatuur </H2>"); client.println("Het is "); client.println(tempc); client.println(" graden."); client.println("<br><br>"); client.println("<H2> Schakelaar </H2>"); client.print("Led pin is now: "); if (value == HIGH) { client.print("On"); } else { client.print("Off"); } client.println("<br><br>"); client.println("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 5 ON<br>"); client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 5 OFF<br>"); client.println("</html>"); delay(1); Serial.println("Client disconnected"); Serial.println(""); }
#pragma once #include <iostream> #include <SFML/Graphics.hpp> #include "menu.h" class StartMenu : public sf::Drawable{ double width; double height; public: StartMenu(double w, double h): width(w), height(h){} private: virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const { sf::CircleShape playBtn(30.0, 3); playBtn.setPosition(width/2 - 45, height/2); playBtn.setRotation(-30.0); target.draw(playBtn); }; };
#ifndef PUNTO_H #define PUNTO_H #include "math.h" #include "razionale.h" #include "eccezioni.h" #include "inputitem.h" using std::ostream; using std::cout; using std::string; class punto; ostream& operator<<(ostream&, const punto&); class punto : public inputitem { friend ostream& operator<<(ostream&, const punto&); private: razionale x,y; public: punto() {} punto( razionale a , razionale b ) : x(a),y(b) {} razionale getX() const; razionale getY() const; double distanceTwoPoints(const punto&) const; void pars_point(string); double xToDouble() const; double yToDouble() const; string toString(); vector<punto> intersect(inputitem *) const ; bool operator==( const punto& ); double distance(inputitem *) const; }; #include "retta.h" #include <locale> //serve per verificare char == numero #include <sstream> //serve per verificare char == numero #include <stdlib.h> #endif // PUNTO_H
/* leetcode 306 * * * */ #include <string> #include <unordered_set> #include <algorithm> #include <map> using namespace std; class Solution { public: string addStrings(string num1, string num2) { int num1Size = num1.size(); int num2Size = num2.size(); int i = num1Size - 1, j = num2Size - 1, tmp = 0, carry = 0; string ans; while(i >= 0 && j >= 0) { tmp = num1[i--] - '0' + num2[j--] - '0' + carry; if (tmp >= 10) { tmp = tmp - 10; carry = 1; } else { carry = 0; } ans += (tmp + '0'); } if (i >= 0) { while(i >= 0) { tmp = num1[i--] - '0' + carry; if(tmp >= 10) { tmp = tmp - 10; carry = 1; } else { carry = 0; } ans += (tmp + '0'); } } if (j >= 0) { while (j >= 0) { tmp = num2[j--] - '0' + carry; if(tmp >= 10) { tmp = tmp - 10; carry = 1; } else { carry = 0; } ans += (tmp + '0'); } } if(carry == 1) { ans += '1'; } reverse(ans.begin(), ans.end()); return ans; } bool dfs(string& s, int i, int j, int k) { if((s[i] == '0' && j - i > 1) || (s[j] == '0' && k - j > 1)) { return false; } string a = s.substr(i, j - i); string b = s.substr(j, k - j); string sum = addStrings(a, b); int size = sum.size(); string c = s.substr(k, size); if ((k + size > s.size()) || (sum != c)) { return false; } if ((k + size == s.size())) { // sum == c return true; } return dfs(s, j, k, k + size); } bool isAdditiveNumber(string num) { int i = 0; for(int j = i + 1; j < num.size(); j++) { for (int k = j + 1; k < num.size(); k++) { if (dfs(num, i, j, k)) { return true; } } } return false; } }; /************************** run solution **************************/ bool _solution_run(string nums) { Solution leetcode_306; bool ans = leetcode_306.isAdditiveNumber(nums); return ans; } #ifdef USE_SOLUTION_CUSTOM string _solution_custom(TestCases &tc) { } #endif /************************** get testcase **************************/ #ifdef USE_GET_TEST_CASES_IN_CPP vector<string> _get_test_cases_string() { return {}; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Manuela Hutter (manuelah) */ #ifndef WEBSERVER_SERVICE_DOWNLOAD_CONTEXT_H #define WEBSERVER_SERVICE_DOWNLOAD_CONTEXT_H #ifdef GADGET_SUPPORT #ifdef WEBSERVER_SUPPORT #include "modules/windowcommander/OpWindowCommander.h" /*********************************************************************************** ** @class WebServerServiceDownloadContext ** @brief Paramaters that need to be known for downloading/installing a webserver service. ************************************************************************************/ class WebServerServiceDownloadContext : public DownloadContext, public URLInformation::DoneListener { public: explicit WebServerServiceDownloadContext(URLInformation * url_info); virtual ~WebServerServiceDownloadContext(); OP_STATUS Init(); OP_STATUS StartDownload(); void Abort(); const OpStringC & GetDownloadLocation() const; const OpStringC & GetRepositoryURL() const; OpString& GetLocalLocation(); BOOL IsTrustedServer() const; void SetDownloadTransferListener(OpTransferListener * transfer_listener); //===== DoneListener ========== virtual BOOL OnDone(URLInformation* url_info); //===== DownloadContext ========== virtual OpWindowCommander* GetWindowCommander(); virtual BOOL IsShownDownload() const; virtual OpTransferListener* GetTransferListener() const { return m_transfer_listener; } private: OpString m_repository_url; OpString m_download_location; OpString m_local_location; URLInformation * m_download; OpTransferListener * m_transfer_listener; }; #endif // WEBSERVER_SUPPORT #endif // GADGET_SUPPORT #endif // WEBSERVER_SERVICE_DOWNLOAD_CONTEXT_H
#pragma once #include "bibliotecas.h" class Funcionario{ public: string nome; bool masculino; int numeroDePecas; Funcionario(){ } Funcionario(string nome, bool masculino, int numeroDePecas){ this->nome=nome; this->masculino=masculino; this->numeroDePecas=numeroDePecas; } void adiciona(string nome, bool masculino, int numeroDePecas){ this->nome=nome; this->masculino=masculino; this->numeroDePecas=numeroDePecas; } }; void Lista02Questao02(){ Lista<Funcionario> listaDeFuncionariosMasculinos; Lista<Funcionario> listaDeFuncionariosFemininos; bool continua=true; while(continua){ cout << "Digite um nome: "; string s=leString(); cout << "É homem 0/1 (false/true)?: "; bool b=leBool(); cout << "Quantas pecas possui ? "; int i=leInteiro(); if(b)listaDeFuncionariosMasculinos.adicionaAoFinal(Funcionario(s, b, i)); else listaDeFuncionariosFemininos.adicionaAoFinal(Funcionario(s, b, i)); cout << "Deseja inserir um novo funcionário 0/1 (false/true)? "; continua=leBool(); } resposta(); int quantidade=0; for(int contador=0; contador < listaDeFuncionariosMasculinos.tamanho; contador++){ Funcionario f=listaDeFuncionariosMasculinos.vetor[contador]; quantidade+=f.numeroDePecas; } cout << "Quantidade de peças func. masculinos: " << quantidade << endl; quantidade=0; for(int contador=0; contador < listaDeFuncionariosFemininos.tamanho; contador++){ Funcionario f=listaDeFuncionariosFemininos.vetor[contador]; quantidade+=f.numeroDePecas; } cout << "Quantidade de peças func. femininos: " << quantidade << endl; for(int contador=0; contador < listaDeFuncionariosFemininos.tamanho; contador++){ listaDeFuncionariosMasculinos.adicionaAoFinal(listaDeFuncionariosFemininos.vetor[contador]); } int maiorValor=0; int funcionario=0; for(int contador=0; contador < listaDeFuncionariosMasculinos.tamanho; contador++){ int numeroDePecasDeste=listaDeFuncionariosMasculinos.vetor[contador].numeroDePecas; if(numeroDePecasDeste > maiorValor){ maiorValor=numeroDePecasDeste; funcionario=contador; } } cout << "Funcionario com mais pecas: " << listaDeFuncionariosMasculinos.vetor[funcionario].nome << " Numero de pecas: " << maiorValor << endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2012 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef VEGA_SWEEP_LINE_H #define VEGA_SWEEP_LINE_H #include "modules/libvega/vegafixpoint.h" #include "modules/libvega/vegapath.h" #ifdef _DEBUG # include "modules/libvega/src/vegasweepline_debug.h" #endif // _DEBUG struct VEGASLVertex; /** This class represents an edge in the path. It contains pointers to * the start and end vertices and a couple of utility functions. * * HACKS! In order to allow duplicate edges and vertices, the * following hacks are present in VEGASLEdge: * * - above: Determining aboveness for identical edges is based on * (right-wise) successors. * * - getAngleDelta: In order to avoid hangs some break-conditions * have been added to path-traversal code. */ class VEGASLEdge : public ListElement<VEGASLEdge> { public: #ifdef _DEBUG unsigned short idx; #endif // _DEBUG VEGASLVertex* lt; ///< left-or-top vertex VEGASLVertex* rb; ///< right-or-bottom vertex VEGASLVertex* first; ///< path-wise start vertex of this edge VEGASLVertex* second; ///< path-wise end vertex of this edge /// Initialize edge from vertex from to vertex to. void init(VEGASLVertex* from, VEGASLVertex* to); /// @return true if this line is above the line o bool above(const VEGASLEdge& o) const; /// @return true if this edge intersects o bool intersects(const VEGASLEdge& o) const; /// see static getAngleDelta float getAngleDelta(const VEGASLEdge& o) const; /** Compute difference in angle between two path segments. l1 and * l2 are assumed to be joined insomuch as that at least one * vertex of one edge is on the other edge. The path segments are * traversed until there's a difference in angle between them, * measured by picking a pivot point. See implementation for * details. * @param l1 Edge to traverse until there's a difference in angle. * @param l2 Edge to traverse until there's a difference in angle. * @param l1Dir true if moving from first to second, false otherwise. * @param l2Dir true if moving from first to second, false otherwise. */ static float getAngleDelta(const VEGASLVertex* pivot, const VEGASLEdge* l1, const VEGASLEdge* l2, bool l1Dir, bool l2Dir); /** Check for intersection between two line segments. l1 and l2 * represent line segments and should contain four values each: * [sx, sy, ex, ey]. If one vertex of one edge is on the other * edge this function returns false, but uses *edgenum (if not * NULL) to indicate which endpoint was on the other edge: 1 for * startpoint of l1, 2 for endpoint of l1, 3 for startpoint of l2, * 4 forendpoint of l2. If this is not the case *edgenum will be * set to 0 (if non-NULL). */ static bool intersects(const double* l1, const double* l2, unsigned* edgenum = NULL); /// @return true if endpoint of one edge is startpoint of the other bool connectsTo(const VEGASLEdge& o) const { return (first == o.second || second == o.first); } /// @return true if both edges have identical start- and endpoint bool identicalTo(const VEGASLEdge& o) const; /** get path-wise first point (reversed if dir is false) */ const VEGASLVertex* firstPoint (const bool dir = true) const { return dir ? first : second; } /** get path-wise second point (reversed if dir is false) */ const VEGASLVertex* secondPoint(const bool dir = true) const { return dir ? second : first; } /** get path-wise next edge (reversed if dir is false) */ const VEGASLEdge* nextEdge(const bool dir = true) const; }; /** Ordered list of edges. Added edges are assmed to be overlapping * along y, and are ordered from highest to lowest. */ class VEGASLVerticalEdges : public List<VEGASLEdge> { public: ~VEGASLVerticalEdges() { RemoveAll(); } /// Insert l into head, so that head will remain ordered on y. void insert(VEGASLEdge* l); /// Add edge if vertex is the start (left-top) of edge. void addIfStart(VEGASLEdge* edge, VEGASLVertex* vertex) { if (edge->lt == vertex) insert(edge); } /// Remove edge if vertex is the end (right-bottom) of edge. void removeIfEnd(VEGASLEdge* edge, VEGASLVertex* vertex) { if (edge->rb == vertex) { OP_ASSERT(edge->InList()); edge->Out(); } } }; static inline int floatComp(const float a, const float b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** This class represent a vertex in the path. It contains pointers to * the edges it is part of, along with some utility functions. */ struct VEGASLVertex { unsigned short idx; ///< index of this vertex float x; ///< x coord of this vertex float y; ///< y coord of this vertex // NOTE: Only available until call to buildTrapezoids has returned. VEGASLEdge* startOf; ///< Edge that this vertex is the start of. VEGASLEdge* endOf; ///< Edge that this vertex is the end of. bool reflex_handled; ///< true if this vertex has been used to introduce a reflex edge. /** @return * -1 if this vertex is left of or above o, * 0 if they are equal, * 1 if this vertex is right of or below o. */ int compare(const VEGASLVertex& o) const { return (x == o.x) ? floatComp(y, o.y) : floatComp(x, o.x); } /// @return true if this vertex is left of o. bool leftOf(const VEGASLVertex& o) const { return compare(o) == -1; } /// @return true if this vertex is right of o. bool rightOf(const VEGASLVertex& o) const { return compare(o) == 1; } // The end points of this vertex' two edges are both to the // right of this vertex (ie < with this vertex as middle). bool isRightReflex() { if (reflex_handled) return false; const VEGASLVertex& v1 = *startOf->second; const VEGASLVertex& v2 = *endOf->first; return this->leftOf(v1) && this->leftOf(v2); } // The end points of this vertex' two edges are both to the // left of this vertex (ie > with this vertex as middle). bool isLeftReflex() { if (reflex_handled) return false; const VEGASLVertex& v1 = *startOf->second; const VEGASLVertex& v2 = *endOf->first; return this->rightOf(v1) && this->rightOf(v2); } /// Compute the squared distance from this vertex to o. float squareDistanceTo(const VEGASLVertex& o) const { const float dx = o.x - x; const float dy = o.y - y; return dx*dx + dy*dy; } }; inline bool VEGASLEdge::identicalTo(const VEGASLEdge& o) const { return (!lt->compare(*o.lt) && !rb->compare(*o.rb)); } inline const VEGASLEdge* VEGASLEdge::nextEdge(const bool dir/* = true*/) const { return dir ? second->startOf : first->endOf; } /** Utility class for implementing sweepline-algorithms. This class * creates and holds an internal representation of a VEGAPath in the * form of a set of VEGASLVertex:es and VEGASLEdge:s. Duplicate * vertices and intermediate vertices on line segments will be * pruned. The vertices are ordered primarily on x, secondarily on y * (if accessed using m_order). */ class VEGASweepLine { public: VEGASweepLine(VEGAPath& path); virtual ~VEGASweepLine(); /** Initialize internal state. Creates storage for and initializes * m_vertices and m_edges. Any pointless vertices will be pruned. * @return OpStatus::OK on success and OpStatus::ERR_NO_MEMORY on OOM. */ virtual OP_STATUS init(); # ifdef VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT OP_STATUS initDebugRT(); UINT32 DebugGetColor(unsigned int i, unsigned char alpha = 0xff); VEGA_FIX DebugMapX(float v) { return VEGA_FLTTOFIX(m_px + ((v-m_bx) / m_bw) * (m_dw - 2*m_px)); } VEGA_FIX DebugMapY(float v) { return VEGA_FLTTOFIX(m_py + ((v-m_by) / m_bh) * (m_dh - 2*m_py)); } void DebugDrawOutline(bool lines = true, bool verts = true, bool nums = true, unsigned int from = 0, unsigned int to = 0); void DebugDumpPathSegment(unsigned int from, unsigned int to, const char* fn); void DebugDumpRT(const char* name, unsigned idx = 0); # endif // VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT protected: OP_STATUS initVertices(); OP_STATUS initEdges(); /** p and i are lines in the path for the previous (after pruning) * and current vertex. If isRedundant returns true the current * vertex will be discarded. * @param p Line for the previous vertex (after pruning). * @param v Line for the current vertex. * @return true if current vertex should be discarded, false otherwise. */ virtual bool isRedundant(const VEGA_FIX* p, const VEGA_FIX* v) const; VEGAPath& m_path; /** Number of lines in path. */ const unsigned int m_numLines; /** Number of unique vertices/edges. This will differ from the * number of lines when pointless vertices are encountered, which * can happen after eg transforms have been applied. */ unsigned int m_numUnique; /** Size of m_edges. Default value is 0, in which case it will be * set to m_numLines from initEdges. This allows inheriting * classes to request storage for more than m_numLines edges * (used eg to store edges introduced due to reflex vertices in * VEGATriangulator). */ unsigned int m_maxLines; /** The vertices of the path. */ VEGASLVertex* m_vertices; /** The edges of the path. */ VEGASLEdge* m_edges; /** Indices to vertices ordered primarily on x, secondarily on y. * NOTE: Range of m_order is [0; m_numUnique[ - * [m_numUnique; m_numLines[ contains indices to pruned vertices. */ unsigned short* m_order; # ifdef VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT class VEGARenderer* m_renderer; class VEGARenderTarget* m_renderTarget; class OpBitmap* m_bitmap; float m_bx, m_by, m_bw, m_bh; ///< bounding box unsigned m_dw, m_dh, m_px, m_py; ///< output image size and padding # endif // VEGA_DEBUG_SWEEP_LINE_IMAGE_OUTPUT }; /** A sweep-line approach for detecting self-intersection. Based on * the Bentley-Ottmann algorithm. * * HACKS! In order to allow duplicate edges and vertices, the * following hacks are present in VEGASelfIntersect: * * - isSelfIntersecting: Traversing up and down in Q to cope with * duplicate edges. */ class VEGASelfIntersect : public VEGASweepLine { public: VEGASelfIntersect(VEGAPath& path) : VEGASweepLine(path) {} /** @return * OpStatus::ERR_NO_MEMORY on OOM, * OpBoolean::IS_TRUE if path is self-intersecting, * OpBoolean::IS_FALSE if path is not self-intersecting. */ OP_BOOLEAN isSelfIntersecting(); #ifdef VEGA_DEBUG_SELF_INTERSECT_IMAGE_OUTPUT_OUTLINE void DebugDumpOutline(); #endif // VEGA_DEBUG_SELF_INTERSECT_IMAGE_OUTPUT_OUTLINE }; #endif // !VEGA_SWEEP_LINE_H
#ifndef SNIFF80211_H #define SNIFF80211_H #include <QWidget> #include "radiotap_iter.h" #include "wifilist.h" #include "maclist.h" class sniff80211 : public QWidget { Q_OBJECT public: explicit sniff80211(QWidget *parent = 0); struct wlan_frame { uint16_t fc; uint16_t duration; uint8_t addr1[6]; uint8_t addr2[6]; uint8_t addr3[6]; uint16_t seq; union { uint16_t qos; uint8_t addr4[6]; struct { uint8_t qos; uint32_t ht; } __attribute__ ((packed)) ht; struct { uint8_t addr4[6]; uint16_t qos; uint32_t ht; } __attribute__ ((packed)) addr4_qos_ht; } u; } __attribute__ ((packed)) ; struct SSID { uint8_t version; uint8_t length; char name[100]; } __attribute__ ((packed)) ; struct beaconInfo { uint64_t timestamp; uint16_t beacon_interval; uint16_t capability_info; struct SSID Sname; } __attribute__ ((packed)) ; struct associationInfo{ uint16_t capability_Info; uint16_t listen_interval; struct SSID Sname; } __attribute__ ((packed)); void mac2str(char szMac[20],unsigned char* pMac,const char chKen); void print_radiotap_namespace(struct ieee80211_radiotap_iterator *iter); int parse_radiotap(const char* radiotap_buf); void setFlag(); int recieve_packet(int socket,QList<wifiList::wifi_list> *wlist,QList<macList::mac_list> *mlist); void readWifiDataFromFile(QList<wifiList::wifi_list> *wlist); int parse_packet_wlan(const char *buffer,QList<wifiList::wifi_list> *wlist,QList<macList::mac_list> *mlist,int pktlen); //根据网络包获取频率 int get_freq_radiotap(const char* radiotap_buf); int get_channel_radiotap(const char* radiotap_buf); signals: void datachanged(); void macupdate(); public slots: private: int flag; }; #endif // SNIFF80211_H
#ifndef PortalSpace_h #define PortalSpace_h #include <vector> #include <tr1/array> #include <tr1/memory> #include "Manifold.h" #include <Eigen/Core> using Eigen::Matrix4d; using Eigen::Vector4d; class PortalSpace : public Manifold { public: double getK(); class PointOfReference; class Point : public Manifold::Point { public: PortalSpace* getSpace(); Point(double hyperbolic, double x, double y, double z, PortalSpace* space); //x,y, and z give the position on S^2, and w gives the height on the surface of revolution. I can afford an extra degree of freedom. i tells how many times you have to loop around the sphere. Point(); friend class PointOfReference; //Point midpoint(Point point); private: Vector3d spherical; double hyperbolic; PortalSpace* space; }; class PointOfReference : public Manifold::PointOfReference { public: PointOfReference(PortalSpace* space); ~PointOfReference(); std::vector<Vector3d> vectorsFromPoint(std::tr1::shared_ptr<Manifold::Point> point); std::tr1::shared_ptr<Manifold::Point> pointFromVector(Vector3d vector); Manifold::Point* getPosition(); //void setPosition(Manifold::Point* position); void move(Vector3d dir); void rotate(Matrix3d rot); private: Point position; Matrix4d orientation; }; // typedef std::tr1::array<std::tr1::shared_ptr<Manifold::Point>,3> Triangle; Triangle makeTriangle(); //For debug purposes // std::vector<Triangle> triforce(Triangle); }; #endif
#include "Player.h" Player Player::player; sf::Text Player::text; sf::Font Player::font; bool Player::renderHitbox = false; bool Player::blockShoots = false; Player::Player() { shooted = false; deathDelay = false; renderDeath = false; checkDeathFx = false; canMove = true; canShoot = true; light = false; resetStats(); playerModel.loadFromFile("Images/spaceship.png"); playerModelLighted.loadFromFile("Images/spaceshipLighted.png"); drawPlayerModel.setTexture(playerModel); drawPlayerModel.setPosition(1600 / 2, 800); sf::Vector2u size = playerModel.getSize(); drawPlayerModel.setOrigin(size.x / 2, size.y / 2); heart.loadFromFile("Images/heart.png"); halfHeart.loadFromFile("Images/halfheart.png"); emptyHeart.loadFromFile("Images/emptyheart.png"); drawHeartModel1.setTexture(heart); drawHeartModel2.setTexture(heart); drawHeartModel3.setTexture(heart); Player::player.playerHp(); hitboxTexture.loadFromFile("Images/hitbox.png"); hitbox1.setTexture(hitboxTexture); hitbox2.setTexture(hitboxTexture); sf::Vector2u Hitboxsize = hitboxTexture.getSize(); hitbox1.setOrigin(Hitboxsize.x / 2, Hitboxsize.y / 2); hitbox2.setOrigin(Hitboxsize.x / 2, Hitboxsize.y / 2); playerShootSoundBuffer.loadFromFile("Sounds/playerShootSound.wav"); playerShootSound.setBuffer(playerShootSoundBuffer); playerDeathSoundBuffer.loadFromFile("Sounds/playerDeathSound.wav"); playerDeathSound.setBuffer(playerDeathSoundBuffer); playerDeathSound.setPitch(5); } void Player::render() { Window::window.draw(Player::player.drawPlayerModel); Window::window.draw(Player::player.drawHeartModel1); Window::window.draw(Player::player.drawHeartModel2); Window::window.draw(Player::player.drawHeartModel3); if (Player::player.renderDeath) Window::window.draw(text); if (renderHitbox) Window::window.draw(Player::player.hitbox1); if (renderHitbox) Window::window.draw(Player::player.hitbox2); } void Player::update() { if (Player::player.canMove == true) Player::player.playerMove(); Player::player.playerShoot(); Player::player.checkCollision(); if (Player::player.deathDelay == true) Player::player.playerDeathTime(); if (Player::player.checkDeathFx == true) Player::player.deathFx(); if (Player::player.shooted == true) Player::player.playerShooted(); if (Player::player.light == true) Player::player.playerLighted(); } void Player::resetStats() { shootSpeed = 3; //3 shootDuration = 1500; //1500 speed = 0.5; hp = 6; shootAmmount = 1; hitbox2PosY = 35; drawPlayerModel.setScale(0.2, 0.2); hitbox1.setScale(0.45, 0.9); hitbox2.setScale(1.1, 0.2); } void Player::playerLighted() { static int time = 0; time += GameInfo::getDeltaTime(); drawPlayerModel.setTexture(playerModelLighted); if (time > 200) { drawPlayerModel.setTexture(playerModel); light = false; time = 0; } } void Player::playerMove() { sf::Vector2f pos; pos = drawPlayerModel.getPosition(); if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) pos.x -= GameInfo::getDeltaTime() * speed; if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) pos.x += GameInfo::getDeltaTime() * speed; if (pos.x < 80) pos.x = 80; if (pos.x > 1520) pos.x = 1520; drawPlayerModel.setPosition(pos); } void Player::playerShoot() { static int myDeltaTime = 0; myDeltaTime += GameInfo::getDeltaTime(); if (shootAmmount > 12) shootAmmount = 12; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && myDeltaTime > shootDuration && canShoot == true) { playerShootSound.stop(); playerShootSound.play(); light = true; sf::Vector2f pos; pos = drawPlayerModel.getPosition(); switch (shootAmmount) { case 1: Shoot::create(pos.x, pos.y, 0, -shootSpeed, true, 1, 1); break; case 2: { Shoot::create(pos.x - 25, pos.y, 0, -shootSpeed, true, 1, 0.9); Shoot::create(pos.x + 25, pos.y, 0, -shootSpeed, true, 1, 0.9); } break; case 3: { Shoot::create(pos.x - 40, pos.y + 15, 0, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x, pos.y - 40, 0, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x + 40, pos.y + 15, 0, -shootSpeed, true, 1, 0.8); } break; case 4: { Shoot::create(pos.x - 40, pos.y + 15, -shootSpeed / 6, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x - 25, pos.y - 40, 0, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x + 25, pos.y - 40, 0, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x + 40, pos.y + 15, shootSpeed / 6, -shootSpeed, true, 1, 0.8); } break; case 5: { Shoot::create(pos.x - 40, pos.y + 15, -shootSpeed / 3, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x - 25, pos.y - 40, -shootSpeed / 10, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x, pos.y - 40, 0, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x + 25, pos.y - 40, shootSpeed / 10, -shootSpeed, true, 1, 0.8); Shoot::create(pos.x + 40, pos.y + 15, shootSpeed / 3, -shootSpeed, true, 1, 0.8); } break; case 6: { Shoot::create(pos.x - 50, pos.y - 20, -shootSpeed / 6, -shootSpeed * 1.0, true, 1, 0.7); Shoot::create(pos.x - 30, pos.y - 30, -shootSpeed / 10, -shootSpeed * 1.1, true, 1, 0.7); Shoot::create(pos.x - 20, pos.y - 40, 0, -shootSpeed * 1.2, true, 1, 0.7); Shoot::create(pos.x + 20, pos.y - 40, 0, -shootSpeed * 1.2, true, 1, 0.7); Shoot::create(pos.x + 30, pos.y - 30, shootSpeed / 10, -shootSpeed * 1.1, true, 1, 0.7); Shoot::create(pos.x + 50, pos.y - 20, shootSpeed / 6, -shootSpeed * 1.0, true, 1, 0.7); } break; case 7: { Shoot::create(pos.x - 40, pos.y - 10, -shootSpeed / 4, -shootSpeed * 1.1, true, 1, 0.6); Shoot::create(pos.x - 30, pos.y - 20, -shootSpeed / 6, -shootSpeed * 1.2, true, 1, 0.6); Shoot::create(pos.x - 20, pos.y - 30, -shootSpeed / 10, -shootSpeed * 1.3, true, 1, 0.6); Shoot::create(pos.x, pos.y - 50, 0, -shootSpeed * 1.35, true, 1, 0.6); Shoot::create(pos.x + 20, pos.y - 30, shootSpeed / 10, -shootSpeed * 1.3, true, 1, 0.6); Shoot::create(pos.x + 30, pos.y - 20, shootSpeed / 6, -shootSpeed * 1.2, true, 1, 0.6); Shoot::create(pos.x + 40, pos.y - 10, shootSpeed / 4, -shootSpeed * 1.1, true, 1, 0.6); } break; case 8: { Shoot::create(pos.x - 50, pos.y, -shootSpeed / 4, -shootSpeed, true, 1, 0.5); Shoot::create(pos.x - 40, pos.y - 10, -shootSpeed / 6, -shootSpeed * 1.1, true, 1, 0.5); Shoot::create(pos.x - 30, pos.y - 20, -shootSpeed / 10, -shootSpeed * 1.2, true, 1, 0.5); Shoot::create(pos.x - 20, pos.y - 30, 0, -shootSpeed * 1.3, true, 1, 0.5); Shoot::create(pos.x + 20, pos.y - 30, 0, -shootSpeed * 1.3, true, 1, 0.5); Shoot::create(pos.x + 30, pos.y - 20, shootSpeed / 10, -shootSpeed * 1.2, true, 1, 0.5); Shoot::create(pos.x + 40, pos.y - 10, shootSpeed / 6, -shootSpeed * 1.1, true, 1, 0.5); Shoot::create(pos.x + 50, pos.y, shootSpeed / 4, -shootSpeed, true, 1, 0.5); } break; case 9: { Shoot::create(pos.x - 50, pos.y - 10, -shootSpeed / 3, -shootSpeed * 1, true, 1, 0.45); Shoot::create(pos.x - 40, pos.y - 20, -shootSpeed / 4, -shootSpeed * 1.1, true, 1, 0.45); Shoot::create(pos.x - 30, pos.y - 30, -shootSpeed / 6, -shootSpeed * 1.2, true, 1, 0.45); Shoot::create(pos.x - 20, pos.y - 40, -shootSpeed / 10, -shootSpeed * 1.3, true, 1, 0.45); Shoot::create(pos.x, pos.y - 50, 0, -shootSpeed * 1.4, true, 1, 0.45); Shoot::create(pos.x + 20, pos.y - 40, shootSpeed / 10, -shootSpeed * 1.3, true, 1, 0.45); Shoot::create(pos.x + 30, pos.y - 30, shootSpeed / 6, -shootSpeed * 1.2, true, 1, 0.45); Shoot::create(pos.x + 40, pos.y - 20, shootSpeed / 4, -shootSpeed * 1.1, true, 1, 0.45); Shoot::create(pos.x + 50, pos.y - 10, shootSpeed / 3, -shootSpeed * 1, true, 1, 0.45); } break; case 10: { Shoot::create(pos.x - 60, pos.y + 10, -shootSpeed / 3, -shootSpeed * 0.9, true, 1, 0.4); Shoot::create(pos.x - 50, pos.y - 0, -shootSpeed / 4, -shootSpeed * 1, true, 1, 0.4); Shoot::create(pos.x - 40, pos.y - 10, -shootSpeed / 6, -shootSpeed * 1.1, true, 1, 0.4); Shoot::create(pos.x - 30, pos.y - 20, -shootSpeed / 10, -shootSpeed * 1.2, true, 1, 0.4); Shoot::create(pos.x - 20, pos.y - 30, 0, -shootSpeed * 1.3, true, 1, 0.4); Shoot::create(pos.x + 20, pos.y - 30, 0, -shootSpeed * 1.3, true, 1, 0.4); Shoot::create(pos.x + 30, pos.y - 20, shootSpeed / 10, -shootSpeed * 1.2, true, 1, 0.4); Shoot::create(pos.x + 40, pos.y - 10, shootSpeed / 6, -shootSpeed * 1.1, true, 1, 0.4); Shoot::create(pos.x + 50, pos.y - 0, shootSpeed / 4, -shootSpeed * 1, true, 1, 0.4); Shoot::create(pos.x + 60, pos.y + 10, shootSpeed / 3, -shootSpeed * 0.9, true, 1, 0.4); } break; case 11: { Shoot::create(pos.x - 60, pos.y - 0, -shootSpeed / 2.5, -shootSpeed * 0.9, true, 1, 0.35); Shoot::create(pos.x - 50, pos.y - 10, -shootSpeed / 3, -shootSpeed * 1, true, 1, 0.35); Shoot::create(pos.x - 40, pos.y - 20, -shootSpeed / 4, -shootSpeed * 1.1, true, 1, 0.35); Shoot::create(pos.x - 30, pos.y - 30, -shootSpeed / 6, -shootSpeed * 1.2, true, 1, 0.35); Shoot::create(pos.x - 20, pos.y - 40, -shootSpeed / 10, -shootSpeed * 1.3, true, 1, 0.35); Shoot::create(pos.x, pos.y - 50, 0, -shootSpeed * 1.4, true, 1, 0.35); Shoot::create(pos.x + 20, pos.y - 40, shootSpeed / 10, -shootSpeed * 1.3, true, 1, 0.35); Shoot::create(pos.x + 30, pos.y - 30, shootSpeed / 6, -shootSpeed * 1.2, true, 1, 0.35); Shoot::create(pos.x + 40, pos.y - 20, shootSpeed / 4, -shootSpeed * 1.1, true, 1, 0.35); Shoot::create(pos.x + 50, pos.y - 10, shootSpeed / 3, -shootSpeed * 1, true, 1, 0.35); Shoot::create(pos.x + 60, pos.y - 0, shootSpeed / 2.5, -shootSpeed * 0.9, true, 1, 0.35); } break; case 12: { Shoot::create(pos.x - 70, pos.y + 20, -shootSpeed / 2.5, -shootSpeed * 0.8, true, 1, 0.4); Shoot::create(pos.x - 60, pos.y + 10, -shootSpeed / 3, -shootSpeed * 0.9, true, 1, 0.4); Shoot::create(pos.x - 50, pos.y - 0, -shootSpeed / 4, -shootSpeed * 1, true, 1, 0.4); Shoot::create(pos.x - 40, pos.y - 10, -shootSpeed / 6, -shootSpeed * 1.1, true, 1, 0.4); Shoot::create(pos.x - 30, pos.y - 20, -shootSpeed / 10, -shootSpeed * 1.2, true, 1, 0.4); Shoot::create(pos.x - 20, pos.y - 30, 0, -shootSpeed * 1.3, true, 1, 0.4); Shoot::create(pos.x + 20, pos.y - 30, 0, -shootSpeed * 1.3, true, 1, 0.4); Shoot::create(pos.x + 30, pos.y - 20, shootSpeed / 10, -shootSpeed * 1.2, true, 1, 0.4); Shoot::create(pos.x + 40, pos.y - 10, shootSpeed / 6, -shootSpeed * 1.1, true, 1, 0.4); Shoot::create(pos.x + 50, pos.y - 0, shootSpeed / 4, -shootSpeed * 1, true, 1, 0.4); Shoot::create(pos.x + 60, pos.y + 10, shootSpeed / 3, -shootSpeed * 0.9, true, 1, 0.4); Shoot::create(pos.x + 70, pos.y + 20, shootSpeed / 2.5, -shootSpeed * 0.8, true, 1, 0.4); } break; } myDeltaTime = 0; } } void Player::checkCollision() { hitbox1.setPosition(drawPlayerModel.getPosition()); hitbox2.setPosition(drawPlayerModel.getPosition().x, drawPlayerModel.getPosition().y + hitbox2PosY); for (int i = Shoot::shoot.size() - 1; i >= 0; i--) { if(i >= Shoot::shoot.size() || i < 0) goto end; if (Shoot::shoot[i]->playerShoot == false && (Shoot::shoot[i]->checkCollision(hitbox1) || Shoot::shoot[i]->checkCollision(hitbox2))) { if (shooted == false) { hp -= Shoot::shoot[i]->getDmg(); Particle::addParticle(drawPlayerModel.getPosition().x, drawPlayerModel.getPosition().y, "BasicEnemy", 5, 0.25); switch (hp) { case 6: drawHeartModel3.setTexture(heart); break; case 5: drawHeartModel3.setTexture(halfHeart); break; case 4: drawHeartModel3.setTexture(emptyHeart); break; case 3: drawHeartModel2.setTexture(halfHeart); break; case 2: drawHeartModel2.setTexture(emptyHeart); break; case 1: drawHeartModel1.setTexture(halfHeart); break; case 0: { drawHeartModel1.setTexture(emptyHeart); playerDeath(); goto end; } break; } } Shoot::shoot.erase(Shoot::shoot.begin() + i); shooted = true; } } end:; } void Player::playerHp() { drawHeartModel1.setPosition(20, 10); drawHeartModel2.setPosition(100, 10); drawHeartModel3.setPosition(180, 10); } void Player::playerShooted() { static float time = 0; time += GameInfo::getDeltaTime(); if (time < 333) drawPlayerModel.setColor(sf::Color(255, 255, 255, 0)); if (time > 333 && time < 666) drawPlayerModel.setColor(sf::Color(255, 255, 255, 255)); if (time > 666 && time < 999) drawPlayerModel.setColor(sf::Color(255, 255, 255, 0)); if (time > 1000) { drawPlayerModel.setColor(sf::Color(255, 255, 255, 255)); shooted = false; time = 0; } } void Player::playerDeath() { Shoot::shoot.clear(); resetStats(); drawPlayerModel.setPosition(1600 / 2, 800); font.loadFromFile("Images/arial.ttf"); text.setFont(font); text.setCharacterSize(100); text.setPosition(800, 425); text.setStyle(sf::Text::Bold); text.setString("YOU DIED"); sf::FloatRect textRect = text.getLocalBounds(); text.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f); hp = 6; drawHeartModel1.setTexture(heart); drawHeartModel2.setTexture(heart); drawHeartModel3.setTexture(heart); playerDeathSound.stop(); playerDeathSound.play(); GameHud::resetHud(); Shoot::shoot.clear(); renderDeath = true; deathDelay = true; checkDeathFx = true; canMove = false; canShoot = false; blockShoots = true; } void Player::playerDeathTime() { static float time = 0; time += GameInfo::getDeltaTime(); drawPlayerModel.setColor(sf::Color(255, 255, 255, 0)); if (time <= 2785 && time > 1000) { drawPlayerModel.setColor(sf::Color(255, 255, 255, (time - 1000) / 7)); } if (time > 2785) drawPlayerModel.setColor(sf::Color(255, 255, 255, 255)); if (time > 3000) { renderDeath = false; LevelManager::actualLevel = 0; BasicEnemy::enemy.clear(); deathDelay = false; canMove = true; canShoot = true; blockShoots = false; time = 0; } } void Player::addHp() { hp += 2; if (hp > 6) hp = 6; switch (hp) { case 6: drawHeartModel3.setTexture(heart); break; case 5: drawHeartModel2.setTexture(heart); drawHeartModel3.setTexture(halfHeart); break; case 4: drawHeartModel2.setTexture(heart); drawHeartModel3.setTexture(emptyHeart); break; case 3: drawHeartModel1.setTexture(heart); drawHeartModel2.setTexture(halfHeart); break; case 2: drawHeartModel1.setTexture(heart); drawHeartModel2.setTexture(emptyHeart); break; case 1: drawHeartModel1.setTexture(halfHeart); break; } } void Player::addShootDelay() { if (shootDuration == 1500) { shootDuration *= 0.7; } shootDuration *= 0.88; GameHud::shootDelayLevel(); } void Player::addShootSpeed() { if (shootSpeed == 3) { shootSpeed *= 1.5; } shootSpeed *= 1.12; GameHud::shootSpeedLevel(); } void Player::addShootAmmount() { shootAmmount++; GameHud::shootAmmountLevel(); } void Player::sizeDown() { static bool firstTime = true; if (firstTime) { drawPlayerModel.setScale(drawPlayerModel.getScale().x * 0.85, drawPlayerModel.getScale().y * 0.85); hitbox1.setScale(hitbox1.getScale().x * 0.85, hitbox1.getScale().y * 0.85); hitbox2.setScale(hitbox2.getScale().x * 0.85, hitbox2.getScale().y * 0.85); hitbox2PosY *= 0.85; firstTime = false; } drawPlayerModel.setScale(drawPlayerModel.getScale().x * 0.97, drawPlayerModel.getScale().y * 0.97); hitbox1.setScale(hitbox1.getScale().x * 0.97, hitbox1.getScale().y * 0.97); hitbox2.setScale(hitbox2.getScale().x * 0.97, hitbox2.getScale().y * 0.97); hitbox2PosY *= 0.97; GameHud::sizeDownLevel(); } void Player::deathFx() { Explosion::create(drawPlayerModel.getPosition()); Particle::addParticle(drawPlayerModel.getPosition().x, drawPlayerModel.getPosition().y, "BasicEnemy", 25, 1); checkDeathFx = false; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QPushButton> #include <QLineEdit> #include <QCheckBox> #include <QHBoxLayout> #include <QStackedLayout> #include <QString> #include <QVector> #include <QMessageBox> #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsPixmapItem> #include <QPixmap> #include <QUrl> #include <QDesktopServices> #include "btree.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public slots: void insertSlot(); void readSlot(); void writeSlot(); void openfileSlot(); void searchSlot(); void deleteSlot(); public: explicit MainWindow(QWidget *parent = 0); void plantTree(); ~MainWindow(); private: Ui::MainWindow *ui; QWidget *mainWidget; QVBoxLayout *mainLayout; QVBoxLayout *treeLayout; std::vector<std::vector<int> > levelVector; QHBoxLayout *userfunctionLayout; QPushButton *insertButton, *searchButton, *deleteButton, *readButton, *writeButton; QLineEdit *insertKeyText, *insertDataText, *searchText, *deleteText; QCheckBox *checkbox; QGraphicsView *vw; btree<std::string> *beetree; }; #endif // MAINWINDOW_H
#include <cmath> #include "../vector3.h" #include "../border.h" #include "../piece.h" class Retract: public Border { public: double h; double &r; Retract(): h(0.4), r(piece::r) {} vector3 border_function(double t) { int n; n=int(t); return piece::border[n]->point(t-(double)n); } vertex* new_border_vertex(vertex *v,vertex *w) { vertex *p; double d; if (v->next_border==w || w->next_border==v) { d=(v->border+w->border)/2.0; if (fabs(v->border-w->border)<((double)piece::num_pieces)/2.0) { p=new_vertex(border_function(d)); p->border=d; } else { d+=((double)piece::num_pieces)/2.0; while(d>(double)piece::num_pieces) d-=(double)piece::num_pieces; p=new_vertex(border_function(d)); p->border=d; } if (v->next_border==w) { v->next_border=p; p->next_border=w; } else { w->next_border=p; p->next_border=v; } } else p=new_vertex(0.5*(*v+*w)); return p; } void quadr(vertex *a,vertex *b,vertex *c,vertex *d) { new_triangle(a,b,c); new_triangle(a,c,d); } vector3 moebius(double t) { return vector3((r-h*cos(t/2.0))*cos(t),(r-h*cos(t/2.0))*sin(t),h*(sin(t/2.0))); } vector3 triplo(double t) { return vector3((r-h*cos(t/3))*cos(t),(r-h*cos(t/3))*sin(t),h*sin(t/3)); } void init_border() { int i; vertex *p[7],*q[10],*s[3]; piece *b[4]; cout<<"Superficie che si retrae sul bordo\n"; cout << "###***\n"; b[0]=new t_curve<Retract>(this, &Retract::moebius, vector3(-r/2.0,0,0),h/3-2.0*M_PI,2*M_PI-h/3); cout << "###***\n"; b[1]=new segment(b[0]->point(1.0),vector3(r/2,0,0)); cout << "###***\n"; b[2]=new t_curve<Retract>(this, &Retract::triplo, b[1]->point(1.0), -3.0*M_PI+h/3, 3.0*M_PI-h/3); cout << "###***\n"; b[3]=new segment(b[2]->point(1.0),b[0]->point(0.0)); cout << "###***\n"; for (i=0;i<6;i++) { p[i]=new_vertex (b[0]->point(1.0/6.0*i)); p[i]->border=1.0/6.0*i; if (i>0) p[i-1]->next_border=p[i]; } p[6]=new_vertex (b[0]->point(1.0)); p[6]->border=1.0; p[5]->next_border=p[6]; for (i=0;i<3;i++) quadr(p[i],p[i+1],p[i+4],p[i+3]); new_triangle(p[0],p[3],p[6]); for (i=0;i<3;i++) s[i]=new_vertex(vector3(0,0,0)); for (i=0;i<9;i++) { q[i]=new_vertex(b[2]->point(1.0/9.0*i)); q[i]->border=2.0+1.0/9.0*i; if (i>0) q[i-1]->next_border=q[i]; } q[9]=new_vertex (b[2]->point(1.0)); q[9]->border=3.0; q[9]->next_border=p[0]; q[8]->next_border=q[9]; p[6]->next_border=q[0]; for (i=0;i<9;i++) { quadr(q[i],q[i+1],s[(i+1)%3],s[i%3]); } new_triangle(q[0],q[9],s[0]); quadr(p[0],p[6],q[0],q[9]); } }; static bool initializer = registry_function<Retract>("retract");
// Animal.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<iostream> #include<string> using namespace std; class Animal{ public: virtual string name(){ return 0; } virtual string does(){ return 0; } }; class Bird : public Animal{ public: string name() { return " A BIRD"; } string does(){ return "FLYS"; } }; class Dog : public Animal { public: string name() { return " A DOG"; } string does() { return "BITES"; } }; int main() { Bird b; Dog d; Animal a; Animal *a1 = &b; Animal *a2 = &d; Animal *a3 = &a; a1->name(); a2->name(); a1->does(); a2->does(); cout << b.name() << " " << b.does() << endl; cout << d.name() << " " << d.does() << endl; system("pause"); return 0; }
#include<bits/stdc++.h> using namespace std; int n; int a[10001*2]; int f[10001*2]; void input(){ cin >> n; for(int i = 1; i <= n; i++){ cin >> a[i]; a[i+n] = a[i]; } } int main(){ freopen("VONGSO.inp", "r", stdin); freopen("VONGSO.out", "w", stdout); input(); int jMax; int MAX = -999999999; f[1] = 1; for(int i = 2; i <= 2*n; i++){ if(a[i] > a[i-1]) f[i] = f[i-1] + 1; else f[i] = 1; } for(int i = 1; i <= n; i++) for(int j = i + 1; j <= n + i - 1; j++) for(int k = i; k <= j; k++) if(MAX < f[k]){ MAX = f[k]; jMax = j; } for(int i = jMax-MAX+1; i <= jMax; i++) cout << a[i] << " "; return 0; }
// Created on: 1996-09-04 // Created by: Christian CAILLET // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Transfer_FinderProcess_HeaderFile #define _Transfer_FinderProcess_HeaderFile #include <Transfer_ProcessForFinder.hxx> #include <Interface_InterfaceModel.hxx> class Interface_InterfaceModel; class Transfer_TransientMapper; class Transfer_Finder; class Transfer_FinderProcess; DEFINE_STANDARD_HANDLE(Transfer_FinderProcess, Transfer_ProcessForFinder) //! Adds specific features to the generic definition : //! PrintTrace is adapted class Transfer_FinderProcess : public Transfer_ProcessForFinder { public: //! Sets FinderProcess at initial state, with an initial size Standard_EXPORT Transfer_FinderProcess(const Standard_Integer nb = 10000); //! Sets an InterfaceModel, which can be used during transfer //! for instance if a context must be managed, it is in the Model Standard_EXPORT void SetModel (const Handle(Interface_InterfaceModel)& model); //! Returns the Model which can be used for context Standard_EXPORT Handle(Interface_InterfaceModel) Model() const; //! In the list of mapped items (between 1 and NbMapped), //! searches for the first mapped item which follows <num0> //! (not included) and which has an attribute named <name> //! The considered Attributes are those brought by Finders,i.e. //! by Input data. //! While NextItemWithAttribute works on Result data (Binders) //! //! Hence, allows such an iteration //! //! for (num = FP->NextMappedWithAttribute(name,0); //! num > 0; //! num = FP->NextMappedWithAttribute(name,num) { //! .. process mapped item <num> //! } Standard_EXPORT Standard_Integer NextMappedWithAttribute (const Standard_CString name, const Standard_Integer num0) const; //! Returns a TransientMapper for a given Transient Object //! Either <obj> is already mapped, then its Mapper is returned //! Or it is not, then a new one is created then returned, BUT //! it is not mapped here (use Bind or FindElseBind to do this) Standard_EXPORT Handle(Transfer_TransientMapper) TransientMapper (const Handle(Standard_Transient)& obj) const; //! Specific printing to trace a Finder (by its method ValueType) Standard_EXPORT virtual void PrintTrace (const Handle(Transfer_Finder)& start, Standard_OStream& S) const Standard_OVERRIDE; //! Prints statistics on a given output, according mode Standard_EXPORT void PrintStats (const Standard_Integer mode, Standard_OStream& S) const; DEFINE_STANDARD_RTTIEXT(Transfer_FinderProcess,Transfer_ProcessForFinder) private: Handle(Interface_InterfaceModel) themodel; }; #endif // _Transfer_FinderProcess_HeaderFile
#include <stdio.h> #include <string.h> #include <unistd.h> #include <iostream> #include <sstream> #include <string> #include "../parser/ErrorResponse.h" #define ALLOC(pointer, size) (pointer) = (char *)calloc((size), sizeof(*pointer)) #define MAX_MESSAGE_SIZE 4096 #define BREW "BREW" #define POST "POST" #define PROPFIND "PROPFIND" #define HTCPCP_VERSION "HTCPCP/1.0" #define NBREW 1 #define NPOST 2 #define NPROPFIND 3 #define METHOD 0 #define POT_NUM 1 #define SERVER 2 #define ADDS_HEADER 3 #define ADDS 4 #define TYPE_HEADER 5 #define TYPE 6 #define SIZE_HEADER 7 #define SIZE 8 #define CRLF 9 #define BODY 10 #define NPOORING 1 #define NBREWING 1 #define NO "-" #define YES "YES" #define BREWING_TIME 5 #define POORING_TIME 2 /** * Stores all data needed be parser. */ struct ParserData { int sck; char *message; bool isItBrewing; bool isItPooring; int *potsAreBrewing; int *potsArePooring; }; /** * This function parse the client request and maintain the response. * @param pd Stores the data of all pots and message and the socket. * @return String The response. */ char *parse(ParserData *pd); /** * This function parse the client additions. * @param additions String of all additions. * @param bodyResponse if no addition found stores the list of the additions available in bodyResponse, otherwise do nothing with bodyResponse. * @return int response code number. */ int parseAdditions(char *additions, char *bodyResponse); /** * This function checks if addition (temp) exits. * @param temp temp string of the addition. * @return boolean if it exits or not. */ bool findAddition(const char *temp); /** * This function takes all data required to build the response to the client. * @param pd Stores the data of all pots and message and the socket. * @param potnum The current used potnum. * @param status_code Used to get the status message to build response. * @param additions Currenlty useless! * @param method_num The method that client used. Used to specify response. * @param bodyResponse String of the body message. * @return String of the response. */ char *buildResponse(ParserData *pd, int potnum, int status_code, char *additions, int method_num, char *bodyResponse); /** * This function makes coffee for the client. * @param pd Stores the data of all pots and message and the socket, used to update all data. * @param potnum The current pot used to make coffee. * @param additions to add them on the coffee. * @return String of the coffee. */ char *makeCoffee(ParserData *pd, int potnum, char *additions);
//lang CwC #pragma once #include <stdio.h> #include "object.h" /* Base Bool wrapper class. Represents the basis for all Bools. Only contains two basic features, equals and hash. */ class Bool : public Object { public: /** * Bool constructor * @param bool value of this * @return N/A */ Bool(bool value) {} /** * Bool destructor * @param N/A * @return N/A */ virtual ~Bool() {} /** * equals - compares this and other for equality * * @param Object other * @return bool indicating if the this and other are equal */ bool equals(Object *other) {} /** * getValue - returns this Bool as an bool * * @return bool value of this */ bool getValue() {} /** * hash - returns the hash value for this * * @param N/A * @return size_t hash value */ virtual size_t hash() {} };
#include "cqsdk/cqsdk.h" #include<string> #include<cstring> #include<ctime> #include<fstream> #include<time.h> // My Classes #include "NumberGuess.cpp" #include "ConstPara.cpp" #include "Command.cpp" #include "QuestionAnswer.cpp" #include "MyTimer.cpp" #include "roulette.cpp" using namespace std; void debug_print(string mess); void debug_print(char* mess); void debug_print(int mess); // namespace cq::app 包含插件本身的生命周期事件和管理 // namespace cq::event 用于注册 QQ 相关的事件处理函数 // namespace cq::api 用于调用酷 Q 提供的接口 // namespace cq::logging 用于日志 // namespace cq::message 提供封装了的 Message 等类 class Robot{ public: // state Number_Guess *Number_Guess_ing; bool En_Number_Guess; bool En_Catch_SJJ; // vector<Alarm_Clock*> Const_Para *cp; Question_Answer *qa; Roulette * roulette; Robot(){ } template<typename T> int my_switch(Command &c, const T &e){ bool en = false; for(auto i=c.flags.begin(); i!=c.flags.end(); i++){ // debug_print((*i)); if (strcmp((*i), "enable")==0){ en = true; } else if (strcmp((*i), "disable")==0){ en = false; } else { return -10001; // unknown flags } } if (c.args_c<1){ return -10002; } for(auto i=c.args.begin(); i!=c.args.end(); i++){ if (strcmp((*i), "Catch_SJJ")==0){ if (en){ En_Catch_SJJ = true; cq::message::send(e.target, "捕捉四季功能已打开"); } else { En_Catch_SJJ = false; cq::message::send(e.target, "捕捉四季功能已关闭"); } } else { string msg(*i); cq::message::send(e.target, "Unknown Switch: " + msg); } } return 0; } template<typename T> int set_alarm_clock(Command &c, const T &e){ for(auto i=c.flags.begin(); i!=c.flags.end(); i++){ return -10001; } if (c.args_c<1) return -10002; if (c.args_c>1) return -10003; return 0; } void init(Const_Para* _cp, Question_Answer* _qa, Roulette* _roulette){ debug_print("agent init"); cp = _cp; qa = _qa; roulette = _roulette; roulette->default_init(); roulette->standardize(); roulette->new_seed(); En_Number_Guess = false; En_Catch_SJJ = true; Number_Guess_ing = NULL; } void qa_response(string strmsg, const cq::GroupMessageEvent &e){ QA_Node* qa_response = qa->response(strmsg.c_str()); if (qa_response){ srand((unsigned)time(0)); int tot = qa_response->link.size(); debug_print(tot); if (tot==0) return; int ran = rand()%tot; debug_print(ran); auto i = qa_response->link.begin(); for(; ran!=0 && i!=qa_response->link.end(); ran--,i++); if (i!=qa_response->link.end()){ cq::message::send(e.target, (*i)->context); } } } int qa_print_question(QA_Node* q, const cq::GroupMessageEvent &e){ if (!q) return 1; string msg = ""; // No such question int order = 1; for(auto i=q->link.begin(); i!=q->link.end(); i++, order++){ msg += string((*i)->context) + "\n"; } cq::message::send(e.target, msg); return 0; } int qa_teaching(Command &c, const cq::GroupMessageEvent &e){ for (auto i=c.flags.begin(); i!=c.flags.end(); i++){ if (strcmp((*i), "s")==0){ qa->data_copy(); cq::message::send(e.target, "已保存"); qa->clear_tmp(); return 0; } else if (strcmp((*i), "update")==0){ qa->init(); cq::message::send(e.target, "更新完成"); return 0; } else if (strcmp((*i), "d")==0){ if (c.args_c<2) { return -10002; // too few args } else if (c.args_c>2) { return -10003; // too many args } int ret = qa->remove(c.args[0], c.args[1]); if (ret==1) return -10004; if (ret==2) return -10005; return 0; } else if (strcmp((*i), "fq")==0){ int ret = qa_print_question(qa->response(c.args[0]), e); if(ret==1) return -10004; return 0; } return -10001; // unknown flags } if (c.args_c<2) { return -10002; // too few args } else if (c.args_c>2) { return -10003; // too many args } qa->teach(c.args[0], c.args[1]); cq::message::send(e.target, "学会啦!"); return 0; } int my_roulette(Command &c, const cq::GroupMessageEvent &e){ int times = 1; bool debug = false; for (auto i=c.flags.begin(); i!=c.flags.end(); i++){ if (strcmp((*i), "10")==0){ times = 10; } else if (strcmp((*i), "d")==0) { debug = true; } else { return -10001; } } if (c.args_c>0) { return -10003; } string msg = ""; for(; times>0; times--){ double r = roulette->roll(); string strreward = roulette->reward[roulette->get_reward(r)]; if (debug) { debug_print((int)(r*10000)); } msg += "获得了: " + strreward + "\n"; } cq::message::send(e.target, msg); return 0; } int execute_command(Command &c, const cq::GroupMessageEvent &e){ if (strcmp(c.command, "constpara")==0 && e.user_id==cp->_SHN){ cp->show(e.target); } else if(strcmp(c.command, "teach")==0){ return qa_teaching(c, e); }else if (strcmp(c.command, "repeat")==0){ return 10000; }else if (strcmp(c.command, "switch")==0 && e.user_id==cp->_SHN){ return my_switch(c, e); }else if (strcmp(c.command, "set_alarm_clock")==0 && e.user_id==cp->_SHN){ return set_alarm_clock(c, e); }else if (strcmp(c.command, "掷骰子")==0){ return my_roulette(c, e); }else { return 10000;//未知命令当复读 } } void response_to_shn(const cq::GroupMessageEvent &e) { cq::Message msg = e.message; string strmsg = to_string(msg); cq::logging::debug("shn", "next"); if (strmsg.find("小鸭子,")==0) { cq::logging::debug("shn", "repeat"); strmsg = strmsg.substr(strlen("小鸭子,")); Command c(strmsg.c_str()); int ret = execute_command(c, e); switch(ret){ case 0: // success break; case -1: cq::message::send(e.target, "未知命令"); break; case -10001: cq::message::send(e.target, "未知开关"); break; case -10002: cq::message::send(e.target, "缺少参数"); break; case -10003: cq::message::send(e.target, "过多参数"); break; case -10004: cq::message::send(e.target, "未找到问题"); break; case -10005: cq::message::send(e.target, "未找到回答"); break; case 10000: cq::message::send(e.target, strmsg); } } else { qa_response(strmsg, e); } return; } void response_to_sjj(const cq::GroupMessageEvent &e) { cq::Message msg = e.message; string strmsg = to_string(msg); // cq::logging::debug("csz", strmsg); cq::logging::debug("sjj", "next"); // cq::message::send(e.target, msg); if (En_Catch_SJJ) { if (strmsg.find("没人了?那我喵一声应该不会被发现")!=strmsg.npos) { msg = "抓住一只野生的喵!"; cq::message::send(e.target, msg); } else if (strmsg.find("CQ:image,file=106F2925C7AF2EF4330169B143A89EF1.png")!=strmsg.npos) { msg = "戳!"; cq::message::send(e.target, msg); } else if (strmsg.find("嗯?怎么冷群了?")!=strmsg.npos) { msg = "只剩下AI了,悲惨吧。。。"; cq::message::send(e.target, msg); } } if (En_Number_Guess) { if(strmsg.find("进制猜数字游戏开始")!=strmsg.npos){ Number_Guess_ing = new Number_Guess(); cq::logging::debug("csz", "new game"); msg = "猜数字 9087"; cq::message::send(e.target, msg); } else if (Number_Guess_ing!=NULL) { if (strmsg.find("数字")!=strmsg.npos && strmsg.find("的匹配结果")!=strmsg.npos) { cq::logging::debug("csz", "adding"); int a = int(strmsg[33])-48; int b = int(strmsg[35])-48; char adder[4]; for(int i=0; i<4; i++) { adder[i] = int(strmsg[7+i]); } // debug_print(adder); debug_print(a); debug_print(b); if (a==4 || Number_Guess_ing->get_times()==10) { Number_Guess_ing = NULL; En_Number_Guess = false; cq::logging::debug("csz", "end game!"); return; } Number_Guess_ing->add_rulers(adder, a, b); char suggestion[10]; itoa(Number_Guess_ing->get_suggestion(), suggestion, 10); msg = "猜数字 " + string(suggestion); cq::message::send(e.target, msg); } } } return; } }; inline string get_time_stamp() { char time_stamp[20]; time_t t; time(&t); sprintf("%d", time_stamp, t); return time_stamp; } inline string get_time_string() { time_t t; struct tm *ptminfo; time(&t); ptminfo = localtime(&t); char time_str[50]; sprintf("%02d-%02d-%02d %02d:%02d:%02d\n", time_str, ptminfo->tm_year + 1900, ptminfo->tm_mon + 1, ptminfo->tm_mday, ptminfo->tm_hour, ptminfo->tm_min, ptminfo->tm_sec); return time_str; } inline void debug_print(string mess) { cq::logging::debug("Debug", mess); // printf("%s:\n%s\n", get_time_string().c_str(), type, mess); } inline void debug_print(char* mess) { cq::logging::debug("Debug", string(mess)); } inline void debug_print(int mess) { char str[10]; itoa(mess, str, 10); cq::logging::debug("Debug", string(str)); } Robot agent; Const_Para cp; Question_Answer qa("D:\\coolq-data\\QA_data.txt", "D:\\coolq-data\\QA_data_tmp.txt"); Roulette rl; // 插件入口,在静态成员初始化之后,app::on_initialize 事件发生之前被执行,用于配置 SDK 和注册事件回调 CQ_MAIN { cq::app::on_enable = [] { // cq::logging、cq::api、cq::dir 等命名空间下的函数只能在事件回调函数内部调用,而不能直接在 CQ_MAIN 中调用 debug_print("The plug-in components is enabled!"); // cq::logging::debug(u8"启用", u8"插件已启动"); agent.init(&cp, &qa, &rl); cp.update(); qa.init(); }; cq::app::on_disable = [] { debug_print("The plug-in components is disabled!"); // fclose(stdout); }; cq::event::on_private_msg = [](const cq::PrivateMessageEvent &e) { // cq::logging::debug(u8"消息", u8"收到私聊消息:" + e.message + u8",发送者:" + std::to_string(e.user_id)); debug_print("Private message reveived:" + e.message + " ,From:" + std::to_string(e.user_id)); try { // cq::api::send_private_msg(e.user_id, e.message); // echo 回去 // cq::api::send_msg(e.target, e.message); // 使用 e.target 指定发送目标 // MessageSegment 类提供一些静态成员函数以快速构造消息段 // cq::Message msg = cq::MessageSegment::contact(cq::MessageSegment::ContactType::GROUP, 201865589); // msg.send(e.target); // 使用 Message 类的 send 成员函数 cq::Message msg = std::to_string(e.user_id); msg.send(e.target); // msg.send(cq::Target::user(649310342)); } catch (const cq::exception::ApiError &err) { // API 调用失败 cq::logging::debug(u8"API", u8"调用失败,错误码:" + std::to_string(err.code)); } e.block(); // 阻止事件继续传递给其它插件 }; cq::event::on_group_msg = [](const auto &e /* 使用 C++ 的 auto 关键字 */) { const auto memlist = cq::api::get_group_member_list(e.group_id); // 获取数据接口 cq::Message msg = "debug : group:" + std::to_string(e.group_id) + " from:" + std::to_string(e.user_id); // msg.send(cq::Target::user(649310342)); if (e.user_id==cp._SJJ){ cq::logging::debug("sjj", "response to SJJ"); // cq::message::send(e.target, msg); agent.response_to_sjj(e); return; } else {//if (e.user_id==cp._SHN){ agent.response_to_shn(e); return; } agent.qa_response(to_string(e.message), e); // msg = "group:" + std::to_string(e.group_id) + " from:" + std::to_string(e.user_id); // Message 类可以进行加法运算 // cq::message::send(e.target, msg); // 使用 message 命名空间的 send 函数 // if (e.user_id==2411393416 && e.group_id!=250253824) cq::message::send(e.target, msg); // msg.send(cq::Target::user(649310342)); }; } // 添加菜单项,需要同时在 <appid>.json 文件的 menu 字段添加相应的条目,function 字段为 menu_demo_1 CQ_MENU(Number_Guess_Enable) { try{ if (!agent.En_Number_Guess) { cq::logging::info(u8"菜单", u8"Number_Guess_Enable"); agent.En_Number_Guess = true; } else { cq::logging::info(u8"菜单", u8"Number_Guess_Disable"); agent.En_Number_Guess = false; } } catch (const cq::exception::ApiError &) { cq::logging::warning(u8"菜单", u8"Number_Guess_Fail"); } } CQ_MENU(Catch_SJJ_Enable) { try{ if (!agent.En_Catch_SJJ) { cq::logging::info(u8"菜单", u8"Catch_SJJ_Enable"); agent.En_Catch_SJJ = true; } else { cq::logging::info(u8"菜单", u8"Catch_SJJ_Disable"); agent.En_Catch_SJJ = false; } } catch (const cq::exception::ApiError &) { cq::logging::warning(u8"菜单", u8"Catch_SJJ_Fail"); } } #include <Windows.h> // 不像 CQ_MAIN,CQ_MENU 可以多次调用来添加多个菜单 CQ_MENU(menu_demo_2) { cq::logging::info(u8"菜单", u8"点击了示例菜单2"); MessageBoxW(nullptr, L"这是一个提示", L"提示", MB_OK | MB_SETFOREGROUND | MB_TASKMODAL | MB_TOPMOST); }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QtCore> #include <QtGui> #include <QGraphicsScene> #include <vector> #include<Qcolor> const int Rectangle_Width=30; const int Rectangle_Height=100; struct Process { int pid; float arrival_time; float burst_time; int priority; float waiting_time; float start_time; float finish_time; QColor color; }; QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_pushButton_clicked(); void sj_permiavtive(); void sj_non(); void priority_premative(); void fcfs(); void on_submit_clicked(); void round_robin(); void priority_non(); void draw(std::vector<struct Process> process); float waiting_time(std::vector<struct Process> process, int n); void draw_color_process(std::vector<struct Process> process); private: Ui::MainWindow *ui; QGraphicsScene *scene; QGraphicsScene *scene_2; QTimer *timer; QGraphicsRectItem *rectangle; QColor colors[11] = {QColor("red"), QColor("green"), QColor("yellow"), QColor("blue"), QColor("orange"), QColor("pink"), QColor("magenta"), QColor("brown"), QColor("purple"), QColor("gold"), QColor("cyan")}; }; #endif // MAINWINDOW_H
#include<iostream> #include<iomanip> using namespace std; int main (){ char nome [30]; double salario, venda_total , total_final; cin>>nome; cin>>salario; cin>>venda_total; total_final = salario + venda_total * 0.15; cout << "TOTAL = R$ " << fixed << setprecision(2) << total_final << endl; return 0; }
#include "Phonebook.hpp" Phonebook::Phonebook() { this->amount = 0; } Phonebook::~Phonebook() { } void Phonebook::add_new_contact(void) { if (this->amount == 8) std::cout << "Contact list is full!\n"; else if (this->contact_list[this->amount].create_contact() == true) this->amount++; } void Phonebook::show_contact_info(void) { std::cout << " Index|" << "First Name|" << " Last Name|" << " Nickname|" << std::endl; for(int i = 0; i < this->amount; i++) this->contact_list[i].display_descr(i); } void Phonebook::find_contact(void) { int cont_num; if (this->amount == 0) { std::cout << "-- Contact list is empty!\n"; return ; } this->show_contact_info(); while (true) { std::cout << "Choose contact number (0 for exit): "; std::cin >> cont_num; if (std::cin.fail() || cont_num < 0 || cont_num > this->amount) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "-- Invalid index.\n"; continue ; } std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if (cont_num) this->contact_list[(int)cont_num - 1].display_contact(); return ; } }
#include <iostream> using namespace std; int main() { int sum(2),count; for (int num=3;num<=100;num+=2){ count=0; for (int k=1;k<=num;k+=2) if(num%k==0) count+=1; if(count==2) sum+=num; } cout<<sum; }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014 Shuangyang Yang // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// // disk performance benchmark using OrangeFS direct interface or c++ file I/O API #include <cstdlib> #include <ctime> #include <fstream> #include <iostream> #include <sys/times.h> #include <vector> #include <hpx/util/high_resolution_timer.hpp> #include <boost/cstdint.hpp> #include <boost/format.hpp> #include <boost/shared_array.hpp> #include <boost/thread.hpp> #include <boost/program_options.hpp> using boost::program_options::variables_map; using boost::program_options::options_description; using boost::program_options::value; using hpx::util::high_resolution_timer; ////////////////////////////////////////////////////////////////// #define MAXPROCS 1000 static boost::uint64_t bufsiz = 10 * 1024; static int count = 1; static int procs = 1; static bool is_ofsio = false; static bool is_remove = false; static std::string filepath; struct RESULT { double real; double user; double sys; }; /* ------------------------ added pvfs header stuff --------------- */ #ifdef __cplusplus extern "C" { #endif #include <pvfs2-usrint.h> #include <pvfs2.h> #ifdef __cplusplus } //extern "C" { #endif /* ------------------------- end pvfs header stuff --------------- */ /////////////////////////////////////////////////////////////////////////////// void do_write_files_test(boost::uint64_t wfiles, int proc, RESULT &r) { // perform the I/O operations here char filename[1024]; clock_t start; clock_t end; struct tms t1; struct tms t2; // RESULT r; std::ofstream file; char *buf; if((buf = (char *)valloc(bufsiz)) == NULL) { std::cerr << "error when create char array." << std::endl; return; } srand((unsigned)time(0)); start = times(&t1); for(boost::uint64_t i=0; i<wfiles; i++) { if(is_ofsio) { // using OrageFS syscalls int fd; int oflags; oflags = O_WRONLY|O_CREAT; sprintf(filename, "%s/file%d.%ld", filepath.c_str(), proc, i); if ((fd = pvfs_open(filename, oflags, 0777)) == -1) { std::cout<<"Unable to open orangeFS file "<<filename<<std::endl; return; } for (int j = 0; j < count; j++) { for(boost::uint64_t c = 0; c < bufsiz; c++) buf[c] = (unsigned int) rand() % 256; if (pvfs_write(fd,buf,bufsiz) <= 0) { std::cout<<"Unable to write orangeFS file "<< filename<<std::endl; return; } } pvfs_close(fd); } else { sprintf(filename, "%s/file%d.%ld", filepath.c_str(), proc, i); file.open(filename); if(file.is_open()) { for(boost::uint64_t c = 0; c < bufsiz; c++) buf[c] = (unsigned int) rand() % 256; for(int j=0; j<count; j++) { file.write(buf, bufsiz); } } else { std::cout<<"Unable to write to "<<filename<<std::endl; } file.close(); } } end = times(&t2); r.real = ((double) end - (double) start) / (double) sysconf(_SC_CLK_TCK); r.user = ((double) t2.tms_utime - (double) t1.tms_utime) / (double) sysconf(_SC_CLK_TCK); r.sys = ((double) t2.tms_stime - (double) t1.tms_stime) / (double) sysconf(_SC_CLK_TCK); free(buf); } /////////////////////////////////////////////////////////////////////////////// // this function will be executed by a dedicated OS thread void do_read_files_test(boost::uint64_t rfiles, int proc, RESULT &r) { // perform the I/O operations here char filename[1024]; clock_t start; clock_t end; struct tms t1; struct tms t2; std::ifstream file; char *buf; if((buf = (char *)valloc(bufsiz)) == NULL) { std::cerr << "error when create char array." << std::endl; return; } start = times(&t1); // buf should already been allocated for(boost::uint64_t i=0; i<rfiles; i++) { if(is_ofsio) { // using OrageFS syscalls int fd; int oflags; oflags = O_RDONLY; sprintf(filename, "%s/file%d.%ld", filepath.c_str(), proc, i); if ((fd = pvfs_open(filename, oflags)) == -1) { std::cout<<"Unable to open orangeFS file "<<filename<<std::endl; return; } for (int j = 0; j < count; j++) { if (pvfs_read(fd,buf,bufsiz) <= 0) { std::cout<<"Unable to read orangeFS file "<< filename<<std::endl; return; } } pvfs_close(fd); } else { sprintf(filename, "%s/file%d.%ld", filepath.c_str(), proc, i); file.open(filename); if(file.is_open()) { for(int j=0; j<count; j++) { file.read(buf, bufsiz); } } else { std::cout<<"Unable to read from "<<filename<<std::endl; } file.close(); } } end = times(&t2); r.real = ((double) end - (double) start) / (double) sysconf(_SC_CLK_TCK); r.user = ((double) t2.tms_utime - (double) t1.tms_utime) / (double) sysconf(_SC_CLK_TCK); r.sys = ((double) t2.tms_stime - (double) t1.tms_stime) / (double) sysconf(_SC_CLK_TCK); free(buf); } /////////////////////////////////////////////////////////////////////////////// int now_run(variables_map& vm) { // extract command line argument boost::uint64_t rfiles = vm["rfiles"].as<boost::uint64_t>(); boost::uint64_t wfiles = vm["wfiles"].as<boost::uint64_t>(); is_remove = vm.count("remove"); is_ofsio = vm.count("orangefs"); if (vm.count("path")) { filepath = vm["path"].as<std::string>(); } else { std::cerr << "Need to specify test path!!" << std::endl; return -1; } if(procs > MAXPROCS) { std::cerr << "too many proc numbers!" << std::endl; return -1; } if(rfiles == 0 && wfiles == 0) { std::cerr << "need to specify either to read or write files" << std::endl; return -1; } if(rfiles > 0 && wfiles > 0) { std::cerr << "Can't read and write in the same test" << std::endl; return -1; } std::cout<<"C++ synchronous disk performance test with local file system " "and orangefs file system."<<std::endl; if(is_ofsio) { std::cout<<"Using OrageFS path: "<<filepath<<std::endl; } else { std::cout<<"Using local path: "<<filepath<<std::endl; } { // Keep track of the time required to execute. high_resolution_timer t; boost::shared_array<RESULT> r_ptr (new RESULT[procs]); double min_time = -1.0, max_time = -1.0; std::vector<boost::thread> thr; if(rfiles > 0) // read tests { // Initiate an asynchronous IO operation wait for it to complete without // blocking any of the HPX thread-manager threads. for(int proc=0; proc < procs; proc++) { thr.push_back(boost::thread(do_read_files_test, rfiles, proc, r_ptr[proc])); } } else { for(int proc=0; proc < procs; proc++) { thr.push_back(boost::thread(do_write_files_test, wfiles, proc, r_ptr[proc])); } } for(int proc=0; proc < procs; proc++) { thr[proc].join(); } // overall performance double tt = t.elapsed(); if (rfiles > 0) { std::cout << (boost::format("Reading %1% files") % rfiles); } else { std::cout << (boost::format("Writing %1% files") % wfiles); } char const* fmt = " with count %1% x buffer size %2%M and %3% procs: \n"; std::cout << (boost::format(fmt) % count % (bufsiz*1.0 /(1024*1024)) % procs); for(int proc=0; proc < procs; proc++) { std::cout << (boost::format("process %1% time: Real %2% [s], User %3% [s], System %4% [s]\n") % proc % r_ptr[proc].real % r_ptr[proc].user % r_ptr[proc].sys); if ((min_time < 0) || (r_ptr[proc].real < min_time) ) { min_time = r_ptr[proc].real; } if ((max_time < 0) || (r_ptr[proc].real > max_time) ) { max_time = r_ptr[proc].real; } } std::cout<<"-------------------------------------------\n"; std::cout<<(boost::format("Total elapsed time: %1% [s]\n") % tt); std::cout<<(boost::format("Aggregate %1% Throughput: %2% [MB/s]\n") % ((rfiles>0) ? "Reading" : "Writing") % (procs * count * bufsiz / tt / (1024*1024))); std::cout<<(boost::format("\t Max Throughput per thread: %1% [MB/s]\n") % (count * bufsiz / min_time / (1024*1024))); std::cout<<(boost::format("\t Min Throughput per thread: %1% [MB/s]\n") % (count * bufsiz / max_time / (1024*1024))); std::cout<<std::endl<<std::endl; if (is_remove) { char filename[1024]; boost::uint64_t fileno = (rfiles>0) ? rfiles : wfiles; for(int proc=0; proc < procs; proc++) { for(boost::uint64_t i=0; i<fileno; i++) { sprintf(filename, "%s/file%d.%ld", filepath.c_str(), proc, i); if (is_ofsio) { pvfs_unlink(filename); } else { remove(filename); } } } } } return 0; } /////////////////////////////////////////////////////////////////////////////// int main(int argc, char* argv[]) { // Configure application-specific options options_description desc_commandline("Usage: [options]"); desc_commandline.add_options() ( "rfiles" , value<boost::uint64_t>()->default_value(0), "number of files to for reading") ( "wfiles" , value<boost::uint64_t>()->default_value(0), "number of files to for writing") ( "bufsiz" , value<boost::uint64_t>(&bufsiz)->default_value(10*1024), "buffer size (in bytes)") ( "path" , value<std::string>(), "file test path, default is the current directory.") ( "count", value<int>(&count)->default_value(1), "number of bufsiz in a file") ( "procs" , value<int>(&procs)->default_value(1), "number of threads used for processing") ( "orangefs" , "use OrangeFS file path.") ( "remove" , "remove test files.") ( "help" , "print help message.") ; variables_map vm; store(parse_command_line(argc, argv, desc_commandline), vm); notify(vm); if (vm.count("help")) { std::cerr << desc_commandline << std::endl; return 0; } return now_run(vm); }
#include <Tanker/Share.hpp> #include <Tanker/Crypto/Format/Format.hpp> #include <Tanker/Errors/Errc.hpp> #include <Tanker/Groups/GroupAccessor.hpp> #include <Tanker/Serialization/Serialization.hpp> #include <Tanker/Trustchain/GroupId.hpp> #include <Tanker/Trustchain/ServerEntry.hpp> #include <Tanker/Trustchain/UserId.hpp> #include <Tanker/UserAccessor.hpp> #include <Helpers/Await.hpp> #include <Helpers/Errors.hpp> #include <Helpers/MakeCoTask.hpp> #include "GroupAccessorMock.hpp" #include "MockConnection.hpp" #include "TestVerifier.hpp" #include "TrustchainBuilder.hpp" #include "UserAccessorMock.hpp" #include <doctest.h> #include <trompeloeil.hpp> #include <Helpers/Buffers.hpp> using namespace Tanker; using namespace Tanker::Errors; using namespace Tanker::Trustchain; using namespace Tanker::Trustchain::Actions; namespace { template <typename T> bool hasDevice(gsl::span<Device const> devices, Crypto::BasicHash<T> const& hash) { return std::find_if(devices.begin(), devices.end(), [&](auto const& device) { return device.id.base() == hash.base(); }) != devices.end(); } template <typename U = void, typename T = U> void assertEqual(std::vector<T> aa, std::vector<U> bb) { std::sort(aa.begin(), aa.end()); std::sort(bb.begin(), bb.end()); CAPTURE(aa); CAPTURE(bb); CHECK(std::equal(aa.begin(), aa.end(), bb.begin(), bb.end())); } void assertKeyPublishToUsersTargetedAt( Share::ResourceKey const& resourceKey, std::vector<Trustchain::Actions::KeyPublishToUser> const& keyPublishes, std::vector<Tanker::Crypto::EncryptionKeyPair> const& userKeyPairs) { REQUIRE(keyPublishes.size() == userKeyPairs.size()); for (unsigned int i = 0; i < keyPublishes.size(); ++i) { CHECK(keyPublishes[i].recipientPublicEncryptionKey() == userKeyPairs[i].publicKey); CHECK(keyPublishes[i].resourceId() == std::get<Trustchain::ResourceId>(resourceKey)); CHECK_EQ(Crypto::sealDecrypt(keyPublishes[i].sealedSymmetricKey(), userKeyPairs[i]), std::get<Crypto::SymmetricKey>(resourceKey)); } } void assertKeyPublishToUsersTargetedAt( Share::ResourceKey const& resourceKey, std::vector<KeyPublishToProvisionalUser> const& keyPublishes, std::vector<SecretProvisionalUser> const& provisionalUsers) { REQUIRE(keyPublishes.size() == provisionalUsers.size()); for (unsigned int i = 0; i < keyPublishes.size(); ++i) { CHECK(keyPublishes[i].appPublicSignatureKey() == provisionalUsers[i].appSignatureKeyPair.publicKey); CHECK(keyPublishes[i].tankerPublicSignatureKey() == provisionalUsers[i].tankerSignatureKeyPair.publicKey); CHECK(keyPublishes[i].resourceId() == std::get<Trustchain::ResourceId>(resourceKey)); CHECK_EQ( Crypto::sealDecrypt( Crypto::sealDecrypt(keyPublishes[i].twoTimesSealedSymmetricKey(), provisionalUsers[i].tankerEncryptionKeyPair), provisionalUsers[i].appEncryptionKeyPair), std::get<Crypto::SymmetricKey>(resourceKey)); } } void assertKeyPublishToGroupTargetedAt( Share::ResourceKey const& resourceKey, std::vector<Trustchain::Actions::KeyPublishToUserGroup> const& keyPublishes, std::vector<Tanker::Crypto::EncryptionKeyPair> const& userKeyPairs) { REQUIRE(keyPublishes.size() == userKeyPairs.size()); for (unsigned int i = 0; i < keyPublishes.size(); ++i) { CHECK(keyPublishes[i].recipientPublicEncryptionKey() == userKeyPairs[i].publicKey); CHECK(keyPublishes[i].resourceId() == std::get<Trustchain::ResourceId>(resourceKey)); CHECK_EQ(Crypto::sealDecrypt(keyPublishes[i].sealedSymmetricKey(), userKeyPairs[i]), std::get<Crypto::SymmetricKey>(resourceKey)); } } } TEST_CASE("generateRecipientList of a new user should return their user key") { TrustchainBuilder builder; builder.makeUser3("newUser"); builder.makeUser3("keySender"); auto const newUser = *builder.findUser("newUser"); auto const keySender = *builder.findUser("keySender"); UserAccessorMock userAccessor; GroupAccessorMock groupAccessor; REQUIRE_CALL(userAccessor, pull(trompeloeil::eq( gsl::span<Trustchain::UserId const>{newUser.userId}))) .LR_RETURN(Tanker::makeCoTask( UserAccessor::PullResult{{newUser.asTankerUser()}, {}})); REQUIRE_CALL(userAccessor, pullProvisional(trompeloeil::_)) .LR_RETURN(Tanker::makeCoTask(std::vector<PublicProvisionalUser>{})); REQUIRE_CALL(groupAccessor, getPublicEncryptionKeys(trompeloeil::eq(std::vector<GroupId>{}))) .LR_RETURN( makeCoTask(GroupAccessor::PublicEncryptionKeyPullResult{{}, {}})); auto const recipients = AWAIT(Share::generateRecipientList( userAccessor, groupAccessor, {SPublicIdentity{to_string(Identity::PublicPermanentIdentity{ builder.trustchainId(), newUser.userId})}}, {})); // there should be only user keys CHECK(recipients.recipientProvisionalUserKeys.size() == 0); CHECK(recipients.recipientGroupKeys.size() == 0); assertEqual<Crypto::PublicEncryptionKey>( recipients.recipientUserKeys, {newUser.userKeys.back().keyPair.publicKey}); } TEST_CASE("generateRecipientList of a new group should return their group key") { TrustchainBuilder builder; auto const newUser = builder.makeUser3("newUser"); auto const keySender = builder.makeUser3("keySender"); auto const newGroup = builder.makeGroup(keySender.user.devices.at(0), {newUser.user}); UserAccessorMock userAccessor; GroupAccessorMock groupAccessor; REQUIRE_CALL(userAccessor, pull(trompeloeil::eq(gsl::span<Trustchain::UserId const>{}))) .LR_RETURN(Tanker::makeCoTask(UserAccessor::PullResult{{}, {}})); REQUIRE_CALL(userAccessor, pullProvisional(trompeloeil::_)) .LR_RETURN(Tanker::makeCoTask(std::vector<PublicProvisionalUser>{})); REQUIRE_CALL(groupAccessor, getPublicEncryptionKeys(trompeloeil::eq( std::vector<GroupId>{newGroup.group.tankerGroup.id}))) .LR_RETURN(makeCoTask(GroupAccessor::PublicEncryptionKeyPullResult{ {newGroup.group.tankerGroup.encryptionKeyPair.publicKey}, {}})); auto const recipients = AWAIT( Share::generateRecipientList(userAccessor, groupAccessor, {}, {cppcodec::base64_rfc4648::encode<SGroupId>( newGroup.group.tankerGroup.id)})); // there should be only group keys CHECK(recipients.recipientUserKeys.size() == 0); CHECK(recipients.recipientProvisionalUserKeys.size() == 0); assertEqual<Crypto::PublicEncryptionKey>( recipients.recipientGroupKeys, {newGroup.group.tankerGroup.encryptionKeyPair.publicKey}); } TEST_CASE( "generateRecipientList of a provisional user should return their group key") { TrustchainBuilder builder; auto const provisionalUser = builder.makeProvisionalUser("bob@gmail"); auto const keySender = builder.makeUser3("keySender"); UserAccessorMock userAccessor; GroupAccessorMock groupAccessor; REQUIRE_CALL(userAccessor, pull(trompeloeil::eq(gsl::span<Trustchain::UserId const>{}))) .LR_RETURN(Tanker::makeCoTask(UserAccessor::PullResult{{}, {}})); REQUIRE_CALL(userAccessor, pullProvisional(trompeloeil::_)) .LR_RETURN(Tanker::makeCoTask(std::vector<PublicProvisionalUser>{ provisionalUser.publicProvisionalUser})); REQUIRE_CALL(groupAccessor, getPublicEncryptionKeys(trompeloeil::eq(std::vector<GroupId>{}))) .LR_RETURN( makeCoTask(GroupAccessor::PublicEncryptionKeyPullResult{{}, {}})); auto const recipients = AWAIT(Share::generateRecipientList( userAccessor, groupAccessor, {provisionalUser.spublicIdentity}, {})); CHECK(recipients.recipientUserKeys.size() == 0); CHECK(recipients.recipientGroupKeys.size() == 0); CHECK(recipients.recipientProvisionalUserKeys.size() == 1); CHECK(recipients.recipientProvisionalUserKeys[0].appSignaturePublicKey == provisionalUser.secretProvisionalUser.appSignatureKeyPair.publicKey); CHECK(recipients.recipientProvisionalUserKeys[0].appEncryptionPublicKey == provisionalUser.secretProvisionalUser.appEncryptionKeyPair.publicKey); CHECK(recipients.recipientProvisionalUserKeys[0].tankerSignaturePublicKey == provisionalUser.secretProvisionalUser.tankerSignatureKeyPair.publicKey); CHECK( recipients.recipientProvisionalUserKeys[0].tankerEncryptionPublicKey == provisionalUser.secretProvisionalUser.tankerEncryptionKeyPair.publicKey); } TEST_CASE("generateRecipientList of a not-found user should throw") { TrustchainBuilder builder; builder.makeUser3("newUser"); builder.makeUser3("keySender"); auto const newUser = *builder.findUser("newUser"); auto const keySender = *builder.findUser("keySender"); UserAccessorMock userAccessor; GroupAccessorMock groupAccessor; REQUIRE_CALL(userAccessor, pull(trompeloeil::eq( gsl::span<Trustchain::UserId const>{newUser.userId}))) .LR_RETURN( Tanker::makeCoTask(UserAccessor::PullResult{{}, {newUser.userId}})); REQUIRE_CALL(userAccessor, pullProvisional(trompeloeil::_)) .LR_RETURN(Tanker::makeCoTask(std::vector<PublicProvisionalUser>{})); REQUIRE_CALL(groupAccessor, getPublicEncryptionKeys(trompeloeil::eq(std::vector<GroupId>{}))) .LR_RETURN( makeCoTask(GroupAccessor::PublicEncryptionKeyPullResult{{}, {}})); TANKER_CHECK_THROWS_WITH_CODE( AWAIT(Share::generateRecipientList( userAccessor, groupAccessor, {SPublicIdentity{to_string(Identity::PublicPermanentIdentity{ builder.trustchainId(), newUser.userId})}}, {})), make_error_code(Errc::InvalidArgument)); } TEST_CASE("generateRecipientList of a not-found group should throw") { TrustchainBuilder builder; auto const newUser = builder.makeUser3("newUser"); auto const keySender = builder.makeUser3("keySender"); auto const newGroup = builder.makeGroup(keySender.user.devices.at(0), {newUser.user}); UserAccessorMock userAccessor; GroupAccessorMock groupAccessor; REQUIRE_CALL(userAccessor, pull(trompeloeil::eq(gsl::span<Trustchain::UserId const>{}))) .LR_RETURN(Tanker::makeCoTask(UserAccessor::PullResult{{}, {}})); REQUIRE_CALL(userAccessor, pullProvisional(trompeloeil::_)) .LR_RETURN(Tanker::makeCoTask(std::vector<PublicProvisionalUser>{})); REQUIRE_CALL(groupAccessor, getPublicEncryptionKeys(trompeloeil::eq( std::vector<GroupId>{newGroup.group.tankerGroup.id}))) .LR_RETURN(makeCoTask(GroupAccessor::PublicEncryptionKeyPullResult{ {}, {newGroup.group.tankerGroup.id}})); TANKER_CHECK_THROWS_WITH_CODE(AWAIT(Share::generateRecipientList( userAccessor, groupAccessor, {}, {cppcodec::base64_rfc4648::encode<SGroupId>( newGroup.group.tankerGroup.id)})), make_error_code(Errc::InvalidArgument)); } template <typename T> std::vector<T> extract(std::vector<std::vector<uint8_t>> const& blocks) { std::vector<T> keyPublishes; for (auto const& block : blocks) { auto const entry = blockToServerEntry(Serialization::deserialize<Block>(block)); auto const keyPublish = entry.action().get_if<KeyPublish>(); REQUIRE(keyPublish); auto const keyPublishTo = keyPublish->get_if<T>(); keyPublishes.push_back(*keyPublishTo); } return keyPublishes; } TEST_CASE( "generateShareBlocks of a new user should generate one KeyPublishToUser " "block") { TrustchainBuilder builder; builder.makeUser3("newUser"); builder.makeUser3("keySender"); auto const newUser = *builder.findUser("newUser"); auto const keySender = *builder.findUser("keySender"); auto const keySenderDevice = keySender.devices.front(); auto const keySenderBlockGenerator = builder.makeBlockGenerator(keySenderDevice); Share::ResourceKeys resourceKeys = { {make<Crypto::SymmetricKey>("symmkey"), make<Trustchain::ResourceId>("resource resourceId")}}; auto const newUserKeyPair = newUser.userKeys.back(); Share::KeyRecipients keyRecipients{ {newUserKeyPair.keyPair.publicKey}, {}, {}}; auto const blocks = Share::generateShareBlocks( keySenderBlockGenerator, resourceKeys, keyRecipients); auto const keyPublishes = extract<Trustchain::Actions::KeyPublishToUser>(blocks); assertKeyPublishToUsersTargetedAt( resourceKeys[0], keyPublishes, {newUserKeyPair.keyPair}); } TEST_CASE( "generateShareBlocks of a new user should generate one " "KeyPublishToProvisionalUser block") { TrustchainBuilder builder; auto const provisionalUser = builder.makeProvisionalUser("bob@gmail"); builder.makeUser3("keySender"); auto const keySender = *builder.findUser("keySender"); auto const keySenderDevice = keySender.devices.front(); auto const keySenderBlockGenerator = builder.makeBlockGenerator(keySenderDevice); Share::ResourceKeys resourceKeys = { {make<Crypto::SymmetricKey>("symmkey"), make<Trustchain::ResourceId>("resource mac")}}; Share::KeyRecipients keyRecipients{ {}, {provisionalUser.publicProvisionalUser}, {}}; auto const blocks = Share::generateShareBlocks( keySenderBlockGenerator, resourceKeys, keyRecipients); auto const keyPublishes = extract<KeyPublishToProvisionalUser>(blocks); assertKeyPublishToUsersTargetedAt( resourceKeys[0], keyPublishes, {provisionalUser.secretProvisionalUser}); } TEST_CASE( "generateShareBlocks of a group should generate one KeyPublishToGroup " "block") { TrustchainBuilder builder; auto const newUser = builder.makeUser3("newUser"); auto const keySender = builder.makeUser3("keySender"); auto const newGroup = builder.makeGroup(keySender.user.devices.at(0), {newUser.user}); auto const keySenderDevice = keySender.user.devices.front(); auto const keySenderBlockGenerator = builder.makeBlockGenerator(keySenderDevice); Share::ResourceKeys resourceKeys = { {make<Crypto::SymmetricKey>("symmkey"), make<Trustchain::ResourceId>("resource resourceId")}}; Share::KeyRecipients keyRecipients{ {}, {}, {newGroup.group.asExternalGroup().publicEncryptionKey}}; auto const blocks = Share::generateShareBlocks( keySenderBlockGenerator, resourceKeys, keyRecipients); auto const keyPublishes = extract<Trustchain::Actions::KeyPublishToUserGroup>(blocks); assertKeyPublishToGroupTargetedAt( resourceKeys[0], keyPublishes, {newGroup.group.tankerGroup.encryptionKeyPair}); }
#include "visabustest.h" #include "VisaBus.h" using namespace RsaToolbox; VisaBusTest::VisaBusTest(QObject *parent) : TestClass(parent) { } void VisaBusTest::isVisa() { QStringList paths = QString(qgetenv("PATH")).split(";"); foreach (const QString &path, paths) { qDebug() << path; } if (VisaBus::isVisaInstalled()) { return; } QVERIFY(QLibrary("RsVisa32").load()); } void VisaBusTest::cannotConnect_data() { QTest::addColumn<ConnectionType>("connection"); QTest::addColumn<QString >("address" ); QTest::newRow("no addr") << ConnectionType::VisaTcpConnection << QString(); QTest::newRow("usb" ) << ConnectionType::VisaUsbConnection << "0x000:0:0:0...?"; QTest::newRow("gpib" ) << ConnectionType::VisaGpibConnection << "13"; QTest::newRow("tcp" ) << ConnectionType::VisaTcpConnection << "1.2.3.4"; QTest::newRow("socket") << ConnectionType::VisaTcpSocketConnection << "1.2.3.4::5025"; } void VisaBusTest::cannotConnect() { QFETCH(ConnectionType, connection); QFETCH(QString, address); VisaBus bus(connection, address); QVERIFY(!bus.isOpen()); } void VisaBusTest::connect() { VisaBus bus(ConnectionType::VisaTcpSocketConnection, "127.0.0.1::5025"); QVERIFY(bus.isOpen()); QVERIFY(!bus.query("*IDN?\n").trimmed().isEmpty()); QVERIFY(bus.local()); }
/* -*- Mode: c++; -*- * * Copyright (C) 1995-2009 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * */ group "DOM.Misc.XSLTProcessor"; language ecmascript; require XSLT_SUPPORT; require DOM3_LOAD; require DOM3_SAVE; xml { "<root/>" } test("XSLTProcessor (setup 1)") { loadXML = function parseXML (source) { var lsparser = document.implementation.createLSParser (DOMImplementationLS.MODE_SYNCHRONOUS, ""); var lsinput = document.implementation.createLSInput (); lsinput.stringData = source; return lsparser.parse (lsinput); }; save = function save (document) { function fixHTML (result) { /* Known problem: the XSLT engine always ends HTML output with a newline character, and the HTML parser, correctly ignoring BODY and HTML end tags, incorrectly (but harmlessly) puts the newline text node in the BODY element. */ if (result.substr (-15) == "\n</body></html>") return result.substr (0, result.length - 15) + "</body></html>\n"; else return result; } if (document instanceof DocumentFragment) { var result = ""; for (var child = document.firstChild; child; child = child.nextSibling) if (child instanceof HTMLElement) result += child.outerHTML; else { var lsserializer = document.ownerDocument.implementation.createLSSerializer (); lsserializer.domConfig.setParameter ("xml-declaration", false); result += lsserializer.writeToString (child); } return fixHTML (result); } else if (document instanceof HTMLDocument) return fixHTML (document.documentElement.outerHTML); else { var lsserializer = document.implementation.createLSSerializer (); lsserializer.domConfig.setParameter ("xml-declaration", false); return lsserializer.writeToString (document); } }; } /* Tests default XML output. */ test("XSLTProcessor #1") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests explicit XML output. */ test("XSLTProcessor #2") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='xml'/><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests default HTML output. */ test("XSLTProcessor #3") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><html xmlns=''><p>PASS</p></html></template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (result instanceof HTMLDocument); verify (save (result) == "<html><head></head><body><p>PASS</p></body></html>\n"); } /* Tests explicit HTML output. */ test("XSLTProcessor #4") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='html'/><template match='/'><p xmlns=''>PASS</p></template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (result instanceof HTMLDocument); verify (save (result) == "<html><head></head><body><p>PASS</p></body></html>\n"); } /* Tests explicit text output. */ test("XSLTProcessor #5") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='text'/><template match='/'>PASS</template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests that xsl:import works via XSLTProcessor. */ test("XSLTProcessor #6") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><import href='data:text/xml,%3Cstylesheet version=%271.0%27 xmlns=%27http://www.w3.org/1999/XSL/Transform%27%3E%3Ctemplate match=%27/%27%3E%3Cresult xmlns=%27%27%3EPASS%3C/result%3E%3C/template%3E%3C/stylesheet%3E'/></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests that xsl:include works via XSLTProcessor. */ test("XSLTProcessor #7") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><include href='data:text/xml,%3Cstylesheet version=%271.0%27 xmlns=%27http://www.w3.org/1999/XSL/Transform%27%3E%3Ctemplate match=%27/%27%3E%3Cresult xmlns=%27%27%3EPASS%3C/result%3E%3C/template%3E%3C/stylesheet%3E'/></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests that document() works via XSLTProcessor. */ test("XSLTProcessor #8") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><copy-of select='document(\"data:text/xml,%3Cresult%3EPASS%3C/result%3E\")'/></template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests setting a number parameter. */ test("XSLTProcessor #9") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x' select='0'/><xsl:template match='/'><result><xsl:value-of select='$x'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "x", 4711); verify (xsltprocessor.getParameter (null, "x") == 4711); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>4711</result>"); } /* Tests setting a boolean parameter. */ test("XSLTProcessor #10") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x' select='false()'/><xsl:template match='/'><result><xsl:value-of select='$x'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "x", true); verify (xsltprocessor.getParameter (null, "x") == true); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>true</result>"); } /* Tests setting a string parameter. */ test("XSLTProcessor #11") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x' select='\"FAIL\"'/><xsl:template match='/'><result><xsl:value-of select='$x'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "x", "PASS"); verify (xsltprocessor.getParameter (null, "x") == "PASS"); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests setting a single node parameter. */ test("XSLTProcessor #12") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x'>FAIL</xsl:param><xsl:template match='/'><result><xsl:value-of select='$x'/></result></xsl:template></xsl:stylesheet>")); var node = document.createTextNode ("PASS"); xsltprocessor.setParameter (null, "x", node); verify (xsltprocessor.getParameter (null, "x") === node); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests setting a nodelist parameter. */ test("XSLTProcessor #13") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x'>FAIL</xsl:param><xsl:template match='/'><result><xsl:for-each select='$x[self::text()]'><xsl:value-of select='.'/></xsl:for-each></result></xsl:template></xsl:stylesheet>")); var nodes = loadXML ("<root>P<!--X-->A<!--X-->S<!--X-->S</root>").documentElement.childNodes; xsltprocessor.setParameter (null, "x", nodes); verify (xsltprocessor.getParameter (null, "x") === nodes); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests setting a string parameter removing it again. */ test("XSLTProcessor #14") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x' select='\"removed\"'/><xsl:template match='/'><result><xsl:value-of select='$x'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "x", "set"); xsltprocessor.removeParameter (null, "x"); verify (xsltprocessor.getParameter (null, "x") == null); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>removed</result>"); } /* Tests setting four string parameters. */ test("XSLTProcessor #15") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x1' select='\"F\"'/><xsl:param name='x2' select='\"A\"'/><xsl:param name='x3' select='\"I\"'/><xsl:param name='x4' select='\"L\"'/><xsl:template match='/'><result><xsl:value-of select='$x1'/><xsl:value-of select='$x2'/><xsl:value-of select='$x3'/><xsl:value-of select='$x4'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "x1", "P"); xsltprocessor.setParameter (null, "x4", "S"); xsltprocessor.setParameter (null, "x2", "A"); xsltprocessor.setParameter (null, "x3", "S"); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests setting four string parameters and clearing parameters. */ test("XSLTProcessor #16") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x1' select='\"P\"'/><xsl:param name='x2' select='\"A\"'/><xsl:param name='x3' select='\"S\"'/><xsl:param name='x4' select='\"S\"'/><xsl:template match='/'><result><xsl:value-of select='$x1'/><xsl:value-of select='$x2'/><xsl:value-of select='$x3'/><xsl:value-of select='$x4'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "x1", "F"); xsltprocessor.setParameter (null, "x4", "L"); xsltprocessor.setParameter (null, "x2", "A"); xsltprocessor.setParameter (null, "x3", "I"); xsltprocessor.clearParameters (); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests setting three string parameters and removing the middle one. */ test("XSLTProcessor #17") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='x1' select='\"FAIL\"'/><xsl:param name='x2' select='\"PASS\"'/><xsl:param name='x3' select='\"FAIL\"'/><xsl:template match='/'><result><xsl:value-of select='$x1'/>, <xsl:value-of select='$x2'/>, <xsl:value-of select='$x3'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "x1", "PASS"); xsltprocessor.setParameter (null, "x2", "FAIL"); xsltprocessor.setParameter (null, "x3", "PASS"); xsltprocessor.removeParameter (null, "x2"); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS, PASS, PASS</result>"); } /* Tests setting parameter with namespace URI. */ test("XSLTProcessor #18") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:opera='http://www.opera.com/'><xsl:param name='opera:x' select='\"FAIL\"'/><xsl:template match='/'><result xsl:exclude-result-prefixes='opera'><xsl:value-of select='$opera:x'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter ("http://www.opera.com/", "x", "PASS"); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS</result>"); } /* Tests transforming several times. */ test("XSLTProcessor #19") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:template match='/'><result>PASS<xsl:value-of select='source/@index'/></result></xsl:template></xsl:stylesheet>")); var result1 = xsltprocessor.transformToDocument (loadXML ("<source index='1'/>")); verify (save (result1) == "<result>PASS1</result>"); var result2 = xsltprocessor.transformToDocument (loadXML ("<source index='2'/>")); verify (save (result2) == "<result>PASS2</result>"); var result3 = xsltprocessor.transformToDocument (loadXML ("<source index='3'/>")); verify (save (result3) == "<result>PASS3</result>"); } /* Tests transforming several times with different parameters. */ test("XSLTProcessor #20") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:param name='index' select='\"FAIL\"'/><xsl:template match='/'><result>PASS<xsl:value-of select='$index'/></result></xsl:template></xsl:stylesheet>")); xsltprocessor.setParameter (null, "index", 1); var result1 = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result1) == "<result>PASS1</result>"); xsltprocessor.setParameter (null, "index", 2); var result2 = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result2) == "<result>PASS2</result>"); xsltprocessor.setParameter (null, "index", 3); var result3 = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result3) == "<result>PASS3</result>"); } /* Tests resetting an XSLTProcessor. */ test("XSLTProcessor #21") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS1</result></template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS1</result>"); xsltprocessor.reset (); xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS2</result></template></stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source/>")); verify (save (result) == "<result>PASS2</result>"); } /* Tests error handling in importStylesheet: invalid argument (string). */ test("XSLTProcessor #22") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS1</result></template></stylesheet>"); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in importStylesheet: invalid argument (native object). */ test("XSLTProcessor #23") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet ({ toString: function () { return "<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS1</result></template></stylesheet>"; }}); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in importStylesheet: invalid argument (text node). */ test("XSLTProcessor #24") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (document.createTextNode ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS1</result></template></stylesheet>")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("NOT_SUPPORTED_ERR") == 0); } /* Tests error handling in importStylesheet: importing two stylesheets without resetting. */ test("XSLTProcessor #25") { var xsltprocessor = new XSLTProcessor; var exception = null; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("NOT_SUPPORTED_ERR") == 0); } /* Tests error handling in importStylesheet: invalid stylesheet (missing version attribute). */ test("XSLTProcessor #26") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("XSLT_PARSING_FAILED_ERR") == 0); } /* Tests error handling in importStylesheet: invalid stylesheet (disallowed import). */ test("XSLTProcessor #27") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><import href='http://www.opera.com/'/></stylesheet>")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("XSLT_PARSING_FAILED_ERR") == 0); } /* Tests error handling in importStylesheet: invalid stylesheet (invalid pattern). */ test("XSLTProcessor #28") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><variable name='x'/><template match='$x'/></stylesheet>")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("XSLT_PARSING_FAILED_ERR") == 0); } /* Tests error handling in transformToDocument: invalid argument (string). */ test("XSLTProcessor #29") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToDocument ("source"); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in transformToDocument: invalid argument (native object). */ test("XSLTProcessor #30") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToDocument ({}); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in transformToDocument: invalid argument (text node). */ test("XSLTProcessor #31") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToDocument (document.createTextNode ("source")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("NOT_SUPPORTED_ERR") == 0); } /* Tests error handling in transformToDocument: called without stylesheet. */ test("XSLTProcessor #32") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.transformToDocument (loadXML ("<source/>")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("RESOURCE_UNAVAILABLE_ERR") == 0); } /* Tests error handling in transformToDocument: invalid stylesheet. */ test("XSLTProcessor #33") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><variable name='x' select='\"string\"'/><template match='/'><value-of select='$x/child'/></template></stylesheet>")); xsltprocessor.transformToDocument (loadXML ("<source/>")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("XSLT_PROCESSING_FAILED_ERR") == 0); } /* Tests error handling in transformToFragment: invalid argument (string). */ test("XSLTProcessor #34") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToFragment ("source", document); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in transformToFragment: invalid argument (native object). */ test("XSLTProcessor #35") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToFragment ({}, document); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in transformToFragment: invalid argument (text node). */ test("XSLTProcessor #36") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToFragment (document.createTextNode ("source"), document); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("NOT_SUPPORTED_ERR") == 0); } /* Tests error handling in transformToFragment: invalid second argument (string). */ test("XSLTProcessor #37") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToFragment (loadXML ("<source/>"), "document"); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in transformToFragment: invalid second argument (native object). */ test("XSLTProcessor #38") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToFragment (loadXML ("<source/>"), {}); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in transformToFragment: invalid second argument (text node). */ test("XSLTProcessor #39") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); xsltprocessor.transformToFragment (loadXML ("<source/>"), document.createTextNode ("document")); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("WRONG_ARGUMENTS_ERR") == 0); } /* Tests error handling in transformToFragment: called without stylesheet. */ test("XSLTProcessor #40") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.transformToFragment (loadXML ("<source/>"), document); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("RESOURCE_UNAVAILABLE_ERR") == 0); } /* Tests error handling in transformToFragment: invalid stylesheet. */ test("XSLTProcessor #41") { var xsltprocessor = new XSLTProcessor; var exception = null; try { xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><variable name='x' select='\"string\"'/><template match='/'><value-of select='$x/child'/></template></stylesheet>")); xsltprocessor.transformToFragment (loadXML ("<source/>"), document); } catch (exception0) { exception = exception0; } verify (exception); verify (exception.message.indexOf ("XSLT_PROCESSING_FAILED_ERR") == 0); } /* Tests default XML output with transformToFragment. */ test("XSLTProcessor #42") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (save (result) == "<result>PASS</result>"); } /* Tests explicit XML output with transformToFragment. */ test("XSLTProcessor #43") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='xml'/><template match='/'><result xmlns=''>PASS</result></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (save (result) == "<result>PASS</result>"); } /* Tests default HTML output with transformToFragment (shouldn't work, since we're in an XML document). */ test("XSLTProcessor #44") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><html xmlns=''><p>PASS</p></html></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (result.firstChild instanceof Element); verify (save (result) == "<html><p>PASS</p></html>"); } /* Tests explicit HTML output with transformToFragment. */ test("XSLTProcessor #45") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='html'/><template match='/'><p xmlns=''>PASS</p></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (result.firstChild instanceof HTMLParagraphElement); verify (save (result) == "<p>PASS</p>\n"); } /* Tests explicit text output with transformToFragment. */ test("XSLTProcessor #46") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='text'/><template match='/'>PASS</template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (save (result) == "<result>PASS</result>"); } /* Tests default multiple top-level elements with transformToFragment. */ test("XSLTProcessor #48") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><result xmlns=''>PASS1</result><result xmlns=''>PASS2</result><result xmlns=''>PASS3</result></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (save (result) == "<result>PASS1</result><result>PASS2</result><result>PASS3</result>"); } /* Tests top-level text with transformToFragment. */ test("XSLTProcessor #49") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'>PASS</template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (save (result) == "PASS"); } /* Tests white-space stripping via XSLTProcessor (no stripping). */ test("XSLTProcessor #50") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:strip-space elements='y'/><xsl:template match='/'><result><xsl:copy-of select='*//text()'/></result></xsl:template></xsl:stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source>P<x> </x>A<x> </x>S<x> </x>S</source>"), document); verify (save (result) == "<result>P A S S</result>"); } /* Tests white-space stripping via XSLTProcessor (stripping). */ test("XSLTProcessor #51") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'><xsl:strip-space elements='x'/><xsl:template match='/'><result><xsl:copy-of select='*//text()'/></result></xsl:template></xsl:stylesheet>")); var result = xsltprocessor.transformToDocument (loadXML ("<source>P<x> </x>A<x> </x>S<x> </x>S</source>"), document); verify (save (result) == "<result>PASS</result>"); } html { "<title>Dummy document</title>" } test("XSLTProcessor (setup 2)") { loadXML = function parseXML (source) { var lsparser = document.implementation.createLSParser (DOMImplementationLS.MODE_SYNCHRONOUS, ""); var lsinput = document.implementation.createLSInput (); lsinput.stringData = source; return lsparser.parse (lsinput); }; save = function save (document) { function fixHTML (result) { /* Known problem: the XSLT engine always ends HTML output with a newline character, and the HTML parser, correctly ignoring BODY and HTML end tags, incorrectly (but harmlessly) puts the newline text node in the BODY element. */ if (result.substr (-15) == "\n</BODY></HTML>") return result.substr (0, result.length - 15) + "</BODY></HTML>\n"; else return result; } if (document instanceof DocumentFragment) { var result = ""; for (var child = document.firstChild; child; child = child.nextSibling) if (child instanceof HTMLElement) result += child.outerHTML; else { var lsserializer = document.ownerDocument.implementation.createLSSerializer (); lsserializer.domConfig.setParameter ("xml-declaration", false); result += lsserializer.writeToString (child); } return fixHTML (result); } else if (document instanceof HTMLDocument) return fixHTML (document.documentElement.outerHTML); else { var lsserializer = document.implementation.createLSSerializer (); lsserializer.domConfig.setParameter ("xml-declaration", false); return lsserializer.writeToString (document); } }; } /* Tests default XML output with transformToFragment (shouldn't work, since we're in an HTML document). */ test("XSLTProcessor #52") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><div xmlns=''>PASS</div></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (result.firstChild instanceof HTMLDivElement); verify (save (result) == "<div>PASS</div>\n"); } /* Tests explicit XML output with transformToFragment. */ test("XSLTProcessor #53") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='xml'/><template match='/'><div xmlns=''>PASS</div></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (result.firstChild instanceof Element); verify (save (result) == "<div>PASS</div>"); } /* Tests default HTML output with transformToFragment. */ test("XSLTProcessor #54") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><html xmlns=''><p>PASS</p></html></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (result.firstChild instanceof HTMLParagraphElement); verify (save (result) == "<p>PASS</p>\n"); } /* Tests default HTML output without {null, 'html'} root with transformToFragment. */ test("XSLTProcessor #55") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><template match='/'><div xmlns=''>PASS</div></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (result.firstChild instanceof HTMLDivElement); verify (save (result) == "<div>PASS</div>\n"); } /* Tests explicit HTML output with transformToFragment. */ test("XSLTProcessor #56") { var xsltprocessor = new XSLTProcessor; xsltprocessor.importStylesheet (loadXML ("<stylesheet version='1.0' xmlns='http://www.w3.org/1999/XSL/Transform'><output method='html'/><template match='/'><p xmlns=''>PASS</p></template></stylesheet>")); var result = xsltprocessor.transformToFragment (loadXML ("<source/>"), document); verify (result.firstChild instanceof HTMLParagraphElement); verify (save (result) == "<p>PASS</p>\n"); } /* Tests the result document type after transformToDocument */ test("XSLTProcessor #57") { // Taken from bug CORE-20754 var xml1 = '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" omit-xml-declaration="yes" /><xsl:template match="/"><xsl:element name="ab"></xsl:element></xsl:template></xsl:stylesheet>'; var doc1 = (new DOMParser()).parseFromString(xml1,'text/xml'); verify(doc1); var xml2 = '<?xml version="1.0"?><ab/>'; var doc2 = (new DOMParser()).parseFromString(xml2,'text/xml'); verify(doc2); var xslt = new XSLTProcessor(); xslt.importStylesheet(doc1); var ttd = xslt.transformToDocument(doc2); verify(ttd); verify(ttd instanceof XMLDocument); }
// Created on: 1992-12-02 // Created by: Isabelle GRIGNON // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GProp_CelGProps_HeaderFile #define _GProp_CelGProps_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <GProp_GProps.hxx> class gp_Circ; class gp_Pnt; class gp_Lin; //! Computes the global properties of bounded curves //! in 3D space. //! It can be an elementary curve from package gp such as //! Lin, Circ, Elips, Parab . class GProp_CelGProps : public GProp_GProps { public: DEFINE_STANDARD_ALLOC Standard_EXPORT GProp_CelGProps(); Standard_EXPORT GProp_CelGProps(const gp_Circ& C, const gp_Pnt& CLocation); Standard_EXPORT GProp_CelGProps(const gp_Circ& C, const Standard_Real U1, const Standard_Real U2, const gp_Pnt& CLocation); Standard_EXPORT GProp_CelGProps(const gp_Lin& C, const Standard_Real U1, const Standard_Real U2, const gp_Pnt& CLocation); Standard_EXPORT void SetLocation (const gp_Pnt& CLocation); Standard_EXPORT void Perform (const gp_Circ& C, const Standard_Real U1, const Standard_Real U2); Standard_EXPORT void Perform (const gp_Lin& C, const Standard_Real U1, const Standard_Real U2); protected: private: }; #endif // _GProp_CelGProps_HeaderFile
#include <iostream> using namespace std; template <class T> class array{ T *v; int n; public: array(); array(int nelts); int size(); T & operator()(int i); ~array(); void print(string header=""); void read(string instruction=""); T sum(); T norm(float normval=2); }; typedef array<float> FA; #ifndef ARRAY #define ARRAY template <class T> array<T>::array(){v=NULL; n = 0;} template <class T> array<T>::array(int nelts){ n = nelts; v = new T[n]; } template <class T> array<T>::~array(){ //delete[] v; } template <class T> int array<T>::size(){return n;} template <class T> T & array<T>::operator()(int i){ if(i >= n || i < 0){ cout << "Out of bounds index "<< i << "). Max allowed "<< n-1<<".\n"; } return v[i]; } template <class T> void array<T>::print(string header){ cout << header; for(int i=0; i<n; i++) cout << v[i] << " "; cout << endl; } template <class T> void array<T>::read(string instruction){ cout << instruction; for(int i=0; i<n; i++) cin >> v[i]; } template <class T> T array<T>::sum(){ T s = 0; for(int i=0; i<n; i++) s += v[i]; return s; } template <class T> T array<T>::norm(float normval){ T s = 0; for(int i=0; i<n; i++) s += pow(abs(v[i]),normval); return pow(s,1/normval); } #endif
// // NoGold.h // GetFish // // Created by zhusu on 15/8/17. // // #ifndef __GetFish__NoGold__ #define __GetFish__NoGold__ #include "cocos2d.h" #include "ButtonWithSpriteManage.h" USING_NS_CC; class NoGold : public CCLayer { public: static const int TYPE_GOLD = 0; static const int TYPE_GET = 1; static const int TYPE_GOLD_GET = 2; static const int TYPE_KAI_2 = 10; static const int TYPE_KAI_3 = 11; static const int TYPE_KAI_4 = 12; static const int TYPE_KAI_5 = 13; static const int TYPE_KAI_6 = 14; static const int TYPE_KAI_NO = 20; static NoGold* create(int type); virtual bool init(int type); NoGold(); virtual ~NoGold(); virtual void onExit(); virtual void onEnter(); virtual bool ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent); virtual void ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent); private: protected: ButtonWithSpriteManage* _buttons; int _type; }; #endif /* defined(__GetFish__NoGold__) */
#include <iostream> #include "BasicSocket.h" #include "logger.h" std::string Network::BasicSocket::getIpAddress() { std::string s; s = inet_ntoa(_addr_info.sin_addr); return s; } void Network::BasicSocket::setAddress(struct sockaddr_in &addr) { _addr_info = addr; } bool Network::BasicSocket::connect(struct sockaddr *addr, socklen_t adr_sz) { setAddress(*((struct sockaddr_in *)addr)); return ::connect(_fd, addr, adr_sz) != -1; } bool Network::BasicSocket::bind(struct sockaddr *addr, socklen_t adr_sz) { setAddress(*((struct sockaddr_in *)addr)); return ::bind(_fd, addr, adr_sz) != -1; } bool Network::BasicSocket::listen(int backlog) { return ::listen(_fd, backlog); } SignedSize Network::BasicSocket::recv(void *buf, size_t buf_len, int msgtype) { return ::recv(_fd, buf, buf_len, msgtype); } SignedSize Network::BasicSocket::send(void *buf, size_t buf_len, int msgtype) { return ::send(_fd, buf, buf_len, msgtype); } SignedSize Network::BasicSocket::write(void *buf, size_t buf_len) { return ::write(_fd, buf, buf_len); } SignedSize Network::BasicSocket::read(void *buf, size_t buf_len) { return ::read(_fd, buf, buf_len); } Network::BasicSocket *Network::BasicSocket::accept() { BasicSocket *new_clnt = nullptr; struct sockaddr_in clnt_adr; socklen_t adr_sz = sizeof(clnt_adr); int clnt_sock = ::accept(_fd, (struct sockaddr*) &clnt_adr, &adr_sz); new_clnt = new BasicSocket(clnt_sock); new_clnt->setAddress(clnt_adr); return new_clnt; } void Network::BasicSocket::setNonblockSocket(bool accept) { int flag = fcntl(_fd, F_GETFL, 0); if(accept) { flag = flag|O_NONBLOCK; } else { flag = flag^O_NONBLOCK; } fcntl(_fd, F_SETFL, flag); } bool Network::BasicSocket::isNonblockSocket() { return _nonblock; }
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void PreOrderTraverse(TreeNode* T) { if (T == NULL) return; cout << T->val << " "; PreOrderTraverse(T->left); PreOrderTraverse(T->right); } class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { //基本思想:递归,左右等分建立左右子树,中间节点作为子树根节点,不断递归次过程,小技巧传nums引用减小内存消耗 TreeNode* root = NULL; Recursion(nums, 0, nums.size() - 1, &root); return root; } void Recursion(vector<int> &nums,int low,int high, TreeNode** root) { if (low > high) return; int mid = (low + high) / 2; (*root) = new TreeNode(nums[mid]); Recursion(nums, low, mid - 1, &(*root)->left); Recursion(nums, mid + 1, high, &(*root)->right); } }; int main() { Solution solute; vector<int> nums = { 1,2,3 }; TreeNode* root = solute.sortedArrayToBST(nums); PreOrderTraverse(root); return 0; }
/* * Copyright 2016 Freeman Zhang <zhanggyb@gmail.com> * * 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 <skland/wayland/xdg-surface.hpp> #include <skland/wayland/surface.hpp> #include "internal/xdg-surface-meta.hpp" #include "internal/xdg-shell-meta.hpp" namespace skland { namespace wayland { XdgSurface::XdgSurface() { metadata_.reset(new XdgSurfaceMeta); } XdgSurface::~XdgSurface() { } void XdgSurface::Setup(const XdgShell &xdg_shell, const Surface &surface) { Destroy(); metadata_->zxdg_surface = zxdg_shell_v6_get_xdg_surface(xdg_shell.metadata_->zxdg_shell, surface.wl_surface_); zxdg_surface_v6_add_listener(metadata_->zxdg_surface, &XdgSurfaceMeta::kListener, this); } void XdgSurface::Destroy() { if (metadata_->zxdg_surface) { zxdg_surface_v6_destroy(metadata_->zxdg_surface); metadata_->zxdg_surface = nullptr; } } void XdgSurface::SetWindowGeometry(int x, int y, int width, int height) const { zxdg_surface_v6_set_window_geometry(metadata_->zxdg_surface, x, y, width, height); } void XdgSurface::AckConfigure(uint32_t serial) const { zxdg_surface_v6_ack_configure(metadata_->zxdg_surface, serial); } void XdgSurface::SetUserData(void *user_data) { zxdg_surface_v6_set_user_data(metadata_->zxdg_surface, user_data); } void *XdgSurface::GetUserData() { return zxdg_surface_v6_get_user_data(metadata_->zxdg_surface); } uint32_t XdgSurface::GetVersion() const { return zxdg_surface_v6_get_version(metadata_->zxdg_surface); } bool XdgSurface::IsValid() const { return nullptr != metadata_->zxdg_surface; } } }
#pragma once #include "Channel.h" namespace Hourglass { class FileArchive; class Clip { public: void Serialize( FileArchive* archive ); unsigned int GetChannelCount() const { return m_ChannelCount; } Channel* GetChannels() { return m_Channels; } const char* GetName() const { return m_Name.c_str(); } const char* GetPath() const { return m_Path.c_str(); } void AddChannel( const Channel& channel ) { m_Channels[m_ChannelCount++] = channel; } void SetName( const char* name ) { m_Name = name; } void SetPath( const char* path ) { m_Path = path; } void SetChannelCount( unsigned int count ) { m_ChannelCount = count; } private: static const uint32_t kMaxJoints = 96; Channel m_Channels[kMaxJoints]; uint32_t m_ChannelCount = 0; std::string m_Name; std::string m_Path; }; }