blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
dd444b9fa792c1484aec382a64e3f308487009af
0210c351cddbd585438cbc8d355893dfc78968fb
/source/gameparams.h
e6b60971e74303b8d7ff23a896595f99c7d65717
[]
no_license
pbem-games/Atlaclient
d4bbe15b1a54c02b7c481fc5ae013833027d04e3
afcc4d57824873c416d43ecf23dba38bb0933dfa
refs/heads/master
2022-02-28T02:45:50.163379
2013-11-24T10:12:38
2013-11-24T10:12:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,183
h
//--------------------------------------------------------------------------- #ifndef gameparamsH #define gameparamsH //--------------------------------------------------------------------------- #include <vector.h> //--------------------------------------------------------------------------- extern int LeaderMaintCost; extern int ManMaintCost; extern int FoodMaintKoeff; extern int TaxEffect; extern int EntertainEffect; extern int StudyAddDays; extern int TeachAddDays; extern int TeachMaxStudents; extern int SailSpeed; extern int WalkSpeed; extern int RideSpeed; extern int FlySpeed; extern int WindSpeed; extern AnsiString SailSkill; extern AnsiString EnteSkill; extern AnsiString CombSkill; extern AnsiString RidiSkill; extern AnsiString LbowSkill; extern AnsiString XbowSkill; extern AnsiString TactSkill; extern AnsiString SwinSkill; extern AnsiString SteaSkill; extern AnsiString ObseSkill; extern AnsiString TrueSkill; extern AnsiString IlluSkill; extern AnsiString MindSkill; extern AnsiString PhenSkill; extern AnsiString RingItem; extern AnsiString AmtsItem; extern int RingSteaBonus; extern int AmtsObseBonus; extern AnsiString XXXXItem; extern int MaxFactionsPoints; extern int SilverWeight; namespace Inifiles{class TIniFile;};using namespace Inifiles; class TGameParamsForm; class TGameParam{ public: int type; //0-int,1-AnsiString AnsiString name; AnsiString comment; int *ptr; AnsiString *ptrstr; TGameParam():ptr(0),ptrstr(0){} bool IsPtrSet(); AnsiString GetString(); bool SetString(const AnsiString &value); }; class TGameParams{ friend TGameParamsForm; private: vector<TGameParam> params; bool AddGameParam(AnsiString name, int * ptr, AnsiString comment); bool AddGameParam(AnsiString name, AnsiString * ptr, AnsiString comment); TGameParam *FindGameParam(AnsiString name); bool SetGameParam(AnsiString name, const AnsiString &value); public: TGameParams(); ~TGameParams(); const TGameParam *Find_GameParam(const AnsiString& name) const; bool Load(TIniFile *ini); bool Save(TIniFile *ini); bool Init(); }; extern TGameParams GameParams; #endif
[ "pradd.me@gmail.com" ]
pradd.me@gmail.com
63b72335dc273b17c18f527fcff97dbff009e5eb
96e7347db30d3ae35f2df119a18472cf5b251fa2
/Classes/Native/mscorlib_System_Diagnostics_DebuggerDisplayAttribu2333734480.h
b78865b91ed44f168060ffa41547ae5d8337543f
[]
no_license
Henry0285/abcwriting
04b111887489d9255fd2697a4ea8d9971dc17d89
ed2e4da72fbbad85d9e0e9d912e73ddd33bc91ec
refs/heads/master
2021-01-20T14:16:48.025648
2017-05-08T06:00:06
2017-05-08T06:00:06
90,583,162
0
0
null
null
null
null
UTF-8
C++
false
false
2,021
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.String struct String_t; #include "mscorlib_System_Attribute1145342165.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Diagnostics.DebuggerDisplayAttribute struct DebuggerDisplayAttribute_t2333734480 : public Attribute_t1145342165 { public: // System.String System.Diagnostics.DebuggerDisplayAttribute::value String_t* ___value_0; // System.String System.Diagnostics.DebuggerDisplayAttribute::type String_t* ___type_1; // System.String System.Diagnostics.DebuggerDisplayAttribute::name String_t* ___name_2; public: inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(DebuggerDisplayAttribute_t2333734480, ___value_0)); } inline String_t* get_value_0() const { return ___value_0; } inline String_t** get_address_of_value_0() { return &___value_0; } inline void set_value_0(String_t* value) { ___value_0 = value; Il2CppCodeGenWriteBarrier(&___value_0, value); } inline static int32_t get_offset_of_type_1() { return static_cast<int32_t>(offsetof(DebuggerDisplayAttribute_t2333734480, ___type_1)); } inline String_t* get_type_1() const { return ___type_1; } inline String_t** get_address_of_type_1() { return &___type_1; } inline void set_type_1(String_t* value) { ___type_1 = value; Il2CppCodeGenWriteBarrier(&___type_1, value); } inline static int32_t get_offset_of_name_2() { return static_cast<int32_t>(offsetof(DebuggerDisplayAttribute_t2333734480, ___name_2)); } inline String_t* get_name_2() const { return ___name_2; } inline String_t** get_address_of_name_2() { return &___name_2; } inline void set_name_2(String_t* value) { ___name_2 = value; Il2CppCodeGenWriteBarrier(&___name_2, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "phamnguyentruc@yahoo.com" ]
phamnguyentruc@yahoo.com
b31019dec3dfd4dfe67fc7e896d35f05a3c80b21
772449e3d84e428eff595bde4aeb3d2a0bc30f09
/DeSpeect/Qt/header/line.h
91c3c9b54fb964abb83e65d26b6c1b7f5c894c63
[ "MIT" ]
permissive
graphiteSWE/Despeect-ProductBaseline
026f9d89c47a474a7df71e9fbc5a9c358471828a
28c22f717ffe106b36195967c163e6f08792f260
refs/heads/master
2020-03-07T04:53:26.557881
2018-04-16T11:03:43
2018-04-16T11:03:43
127,279,852
1
2
MIT
2018-04-05T07:46:33
2018-03-29T11:06:32
Makefile
UTF-8
C++
false
false
1,648
h
#ifndef LINE_H #define LINE_H #include <QGraphicsObject> //graphic line between two nodes class Line:public QGraphicsObject { Q_OBJECT private: //used to show the line only if both it's nodes are visible if no parent relation is set int Visibility=1; protected: //radius of the node to offset from center of them const int offsetFromPoint; //color of empty space //draw line is still black const QColor color; //the start and ending point of the line QLineF MyPoints; //true if the two nodes are colliding bool colliding; //true if the line is dashed bool dashed; //check if the nodes are colliding virtual void NodesColliding(); virtual ~Line(); //fix the position of start and end to be the closest of the circle of the two nodes //used when drawing to not draw from center of node to center virtual QPointF FixStart(); virtual QPointF FixEnd(); public: Line(const int radius,const QColor& color,bool dashed=0, QGraphicsItem*parent=0); public slots: //slots to update the position of the line, used to update position when the item it's //connected to move the QPointF given are the center of the object void UpdateStartPoint(const QPointF& startPoint); void UpdateEndPoint(const QPointF& endPoint); //set Visibility to 1 is line must be drawn otherwise to 0 if one node is hidden to -1 if both //nodes are hidden void changeVisibility(bool); // QGraphicsItem interface public: QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); }; #endif // LINE_H
[ "graphite.swe@gmail.com" ]
graphite.swe@gmail.com
f39922d3784fbc4f52b29cbaa7dde35b114fefa9
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/Handle_TColGeom_HSequenceOfSurface.hxx
37e1a3921f606c53725b2a635b5c10f3bf11b8e2
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
829
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Handle_TColGeom_HSequenceOfSurface_HeaderFile #define _Handle_TColGeom_HSequenceOfSurface_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_MMgt_TShared_HeaderFile #include <Handle_MMgt_TShared.hxx> #endif class Standard_Transient; class Handle(Standard_Type); class Handle(MMgt_TShared); class TColGeom_HSequenceOfSurface; DEFINE_STANDARD_HANDLE(TColGeom_HSequenceOfSurface,MMgt_TShared) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
b2397a8e14b630d2400f5370b9755f381d841791
2117e55894da73f8c3e2b921e289f4592f3c7001
/OS Algoritms/Semaphores.cpp
69ecbc4ff104491dcb04ab7fdc910e1cc7bd41c0
[]
no_license
NishkarshRaj/Operating-Systems-with-C-and-Shell
ec43856dd406fb74ca2805f66a3c6b29b8f90df1
8fea0da3dbff03eef29efeaaf7fa6ad9d21e6698
refs/heads/master
2020-03-25T22:41:02.518253
2019-06-06T12:31:28
2019-06-06T12:31:28
144,236,035
4
0
null
2023-09-01T17:44:17
2018-08-10T04:18:27
C
UTF-8
C++
false
false
649
cpp
// C program to demonstrate working of Semaphores #include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> sem_t mutex; void* thread(void* arg) { //wait sem_wait(&mutex); printf("\nEntered..\n"); //critical section sleep(4); //signal printf("\nJust Exiting...\n"); sem_post(&mutex); } int main() { sem_init(&mutex, 0, 1); pthread_t t1,t2; pthread_create(&t1,NULL,thread,NULL); sleep(2); pthread_create(&t2,NULL,thread,NULL); pthread_join(t1,NULL); pthread_join(t2,NULL); sem_destroy(&mutex); return 0; }
[ "500060720@stu.upes.ac.in" ]
500060720@stu.upes.ac.in
cf80203f21f1c72d035948dec509404a9b73d12c
73cfd700522885a3fec41127e1f87e1b78acd4d3
/_Include/boost/numeric/conversion/detail/preprocessed/numeric_cast_traits_common.hpp
50c28556176e52268be44e6078a3142e8739e5ea
[]
no_license
pu2oqa/muServerDeps
88e8e92fa2053960671f9f57f4c85e062c188319
92fcbe082556e11587887ab9d2abc93ec40c41e4
refs/heads/master
2023-03-15T12:37:13.995934
2019-02-04T10:07:14
2019-02-04T10:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
44,824
hpp
//////////////////////////////////////////////////////////////////////////////// // numeric_cast_traits_common.hpp // //! Copyright (c) 2011-2012 //! Brandon Kohn // // 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) // namespace boost { namespace numeric { template <> struct numeric_cast_traits < char , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < char , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < char , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < char , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < char , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < char , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < char , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < char , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < char , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < char , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < char , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < char , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < signed char , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < signed char , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < signed char , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < signed char , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < signed char , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < signed char , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < signed char , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < signed char , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < signed char , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < signed char , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < signed char , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < signed char , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned char , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < short , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < short , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < short , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < short , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < short , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < short , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < short , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < short , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < short , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < short , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < short , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < short , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned short , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < int , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < int , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < int , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < int , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < int , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < int , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < int , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < int , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < int , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < int , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < int , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < int , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned int , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < long , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < long , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < long , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < long , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < long , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < long , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < long , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < long , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < long , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < long , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < long , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < long , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < unsigned long , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < float , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < float , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < float , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < float , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < float , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < float , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < float , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < float , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < float , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < float , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < float , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < float , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < double , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < double , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < double , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < double , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < double , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < double , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < double , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < double , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < double , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < double , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < double , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < double , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; template <> struct numeric_cast_traits < long double , char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<char> rounding_policy; }; template <> struct numeric_cast_traits < long double , signed char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<signed char> rounding_policy; }; template <> struct numeric_cast_traits < long double , unsigned char > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned char> rounding_policy; }; template <> struct numeric_cast_traits < long double , short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<short> rounding_policy; }; template <> struct numeric_cast_traits < long double , unsigned short > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned short> rounding_policy; }; template <> struct numeric_cast_traits < long double , int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<int> rounding_policy; }; template <> struct numeric_cast_traits < long double , unsigned int > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned int> rounding_policy; }; template <> struct numeric_cast_traits < long double , long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long> rounding_policy; }; template <> struct numeric_cast_traits < long double , unsigned long > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<unsigned long> rounding_policy; }; template <> struct numeric_cast_traits < long double , float > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<float> rounding_policy; }; template <> struct numeric_cast_traits < long double , double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<double> rounding_policy; }; template <> struct numeric_cast_traits < long double , long double > { typedef def_overflow_handler overflow_policy; typedef UseInternalRangeChecker range_checking_policy; typedef Trunc<long double> rounding_policy; }; }} ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "langley.joshua@gmail.com" ]
langley.joshua@gmail.com
ebca3b53a2709f271db8512a4bdfef5a8bc7deb3
6651dcac19c17e30388e2004f65465297e6952a5
/LBEP/Demo/Demo.cpp
bca1d02bfa52ade83e8ce9b7a3ae7e7ba6262be1
[]
no_license
arthursnv/AnhNVTH1904015
d1cfbefdcb050a704c3d1d78d5a34199e94a6365
f806996f473d58a4d3c8c1afda6600d5679ea1ac
refs/heads/master
2022-02-27T00:31:57.142919
2019-09-06T08:40:43
2019-09-06T08:40:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
497
cpp
#include <stdio.h> int main(){ int x; float y; double z; char c = c; // printf("Nhap vao gia tri cua x: "); // scanf("%d", &x); // printf("\nNhap vao gia tri cua y: "); // scanf("%f", &y); // printf("\nNhap vao gia tri cua z: "); // scanf("%lf", &z); x = 5; y = 8.2; z = x * y; printf("\nGia tri cua z = %lf", z); printf("\nNhap gia tri bat ky: "); scanf("%d", &x); scanf("%c", &c); printf("Nhap vao gia tri cua c: "); scanf("%c", &c); printf("\nGia tri cua c la: %c", c); }
[ "38343906+thienan0789@users.noreply.github.com" ]
38343906+thienan0789@users.noreply.github.com
37d1b96ca7c0cbea3cdb4ceac1c2b72fa44709db
d428641889fd5d2c62e3f81a34dcc86a0a3e025a
/rqt_example_cpp/include/rqt_example_cpp/my_plugin.h
1a6705968bac3700d9e8ab5f81f58542aa40c3d2
[]
no_license
LEVIJX/rqt_mypkg
33ef9292800c3b0cffaa140e912b29709bbd0afa
9e9dc13d64ff40c332a72fe77767954fa0aa845c
refs/heads/master
2021-01-11T14:23:24.328329
2017-02-08T13:56:12
2017-02-08T13:56:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
880
h
#ifndef rqt_example_cpp_my_plugin_H #define rqt_example_cpp_my_plugin_H #include <rqt_gui_cpp/plugin.h> #include <rqt_example_cpp/ui_my_plugin.h> #include <QWidget> namespace rqt_example_cpp { class MyPlugin : public rqt_gui_cpp::Plugin { Q_OBJECT public: MyPlugin(); virtual void initPlugin(qt_gui_cpp::PluginContext& context); virtual void shutdownPlugin(); virtual void saveSettings(qt_gui_cpp::Settings& plugin_settings, qt_gui_cpp::Settings& instance_settings) const; virtual void restoreSettings(const qt_gui_cpp::Settings& plugin_settings, const qt_gui_cpp::Settings& instance_settings); // Comment in to signal that the plugin has a way to configure it // bool hasConfiguration() const; // void triggerConfiguration(); private: Ui::MyPluginWidget ui_; QWidget* widget_; }; } // namespace rqt_example_cpp #endif // rqt_example_cpp_my_plugin_H
[ "wsacul@gmail.com" ]
wsacul@gmail.com
25e753a2ba917de700217a5e77659f20f1cb9554
2385652507f121c8d2c64e90bd828a70b0eb44d0
/Algorithms/cpp/Multiply Strings/bruteForce.cpp
28524151eb7166b56180499252e068acf824003f
[]
no_license
LuoWDK/leetcode
8e3dbda2ae91db4f6b93f86589efea37505d41af
3b5d9db45aacb390e657097ac8f51fda37505520
refs/heads/master
2021-01-24T20:47:36.546582
2018-04-19T08:57:00
2018-04-19T08:57:00
123,259,957
0
0
null
null
null
null
UTF-8
C++
false
false
1,579
cpp
class Solution { private: string addString(string s1, string s2){ int i = s1.length()-1, j = s2.length()-1; if (i > j) return addString(s2, s1); int carry = 0; string req = ""; while (i >= 0){ carry += (s1[i] - '0') + (s2[j] - '0'); req = (char)('0' + (carry%10)) + req; carry /= 10; --i; --j; } while (j >= 0){ carry += s2[j] - '0'; req = (char)('0' + (carry%10)) + req; carry /= 10; --j; } if (carry){ req = (char)('0' + (carry%10)) + req; } return req; } public: string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") return "0"; long long int carry = 0, n1, n2, start = -1; string tmp = "", ans = "0"; bool flag; while (num1.length()){ ++start; n1 = num1.back() - '0'; num1.pop_back(); if (!n1){ continue; } carry = 0; tmp.assign(start, '0'); for (int i = num2.length() - 1; i >= 0; --i){ n2 = num2[i] - '0'; carry += n1 * n2; tmp = (char)('0' + (carry%10)) + tmp; carry /= 10; } while (carry){ tmp = (char)('0' + (carry%10)) + tmp; carry /= 10; } ans = addString(tmp, ans); } return ans; } };
[ "Maggieluo0120@gmail.com" ]
Maggieluo0120@gmail.com
0625fda0be21bbb61251d49ea58cee5cab95b170
58fcf94986f50c3f951d07ba4d44f3de4bffcf4c
/1006.cpp
8883035f9f5c8c5f6bf34f6eee7b266abb95067a
[]
no_license
nvcooc/WOJ-learn
0557731e9a7b4e6c603c5765b776e4eb3e417d4c
b5fe2996033b3ae2489e187951b72c9c2568864f
refs/heads/master
2021-05-28T07:03:50.279901
2015-02-19T15:16:34
2015-02-19T15:16:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,653
cpp
//By Brickgao #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <vector> #include <queue> using namespace std; #define out(v) cerr << #v << ": " << (v) << endl #define SZ(v) ((int)(v).size()) const int maxint = -1u>>1; template <class T> bool get_max(T& a, const T &b) {return b > a? a = b, 1: 0;} template <class T> bool get_min(T& a, const T &b) {return b < a? a = b, 1: 0;} vector <int> mp[200010]; bool vis[200010]; typedef struct rec { int p, v; } rec; int bfs(int root, int f) { if(root == f) return 0; queue <rec> q; rec tmp; tmp.p = root, tmp.v = -1; q.push(tmp); while(!q.empty()) { rec u = q.front(); vis[u.p] = true; q.pop(); if(u.p == f) return u.v; else { for(int i = 0; i < int(mp[u.p].size()); ++ i) { int v = mp[u.p][i]; if(!vis[v]) { tmp.p = v, tmp.v = u.v + 1; q.push(tmp); } } } } return -1; } int main() { int m, n; while(scanf("%d%d", &m, &n) != EOF) { for(int i = 0; i < m; ++ i) mp[i].clear(); for(int i = 0; i < n; ++ i) { int u, v; scanf("%d%d", &u, &v); mp[u].push_back(v); mp[v].push_back(u); } int t; scanf("%d", &t); for(int i = 0; i < t; ++ i) { int u, v; scanf("%d%d", &u, &v); memset(vis, false, sizeof(vis)); printf("%d\n", bfs(u, v)); } } return 0; }
[ "brickgao@gmail.com" ]
brickgao@gmail.com
7a89f2e0fbac32ea3f1f120a10c6f447dfc7fccb
0569a04ed085bbdec4228270e3cfed79684f6494
/Classes/CommonAudio.cpp
1065dd6bff3c4a9db7f726f2933213ac0bcedcef
[]
no_license
ZhouC125/cocos2d
6d9e31fe82c7fbcd1be8ab1fae5587ad307f8856
55c769fca989487ff5f46016e200c0080113b850
refs/heads/master
2020-04-27T23:56:18.773969
2019-03-10T09:40:48
2019-03-10T09:40:48
174,797,396
0
0
null
null
null
null
GB18030
C++
false
false
1,533
cpp
#include "CommonAudio.h" #include"audio\include\SimpleAudioEngine.h" #include<string.h> #include "cocos2d.h" #include "CardGame.h" using namespace std; using namespace CocosDenshion; USING_NS_CC; //播放某个音效 void CommonAudio::playAudio(int gender) { auto game = CardGame::getInstance(); if (game->is_yinxiao) { switch (gender) { case 0: SimpleAudioEngine::getInstance()->playEffect("sound/a00-l-0.mp3"); break; case 1://跟注 SimpleAudioEngine::getInstance()->playEffect("sound/a01-l-0.mp3"); break; case 2://加注 SimpleAudioEngine::getInstance()->playEffect("sound/a02-l-0.mp3"); break; case 3://弃牌 SimpleAudioEngine::getInstance()->playEffect("sound/a04-l-0.mp3"); break; case 4://比牌 SimpleAudioEngine::getInstance()->playEffect("sound/a05-l-0.mp3"); SimpleAudioEngine::getInstance()->playEffect("sound/bipai.mp3"); break; case 5://丢股比 SimpleAudioEngine::getInstance()->playEffect("sound/add_gold.mp3"); break; case 6://比牌输 SimpleAudioEngine::getInstance()->playEffect("sound/game_lost.mp3"); break; case 7://比牌赢 SimpleAudioEngine::getInstance()->playEffect("sound/pkwin.mp3"); break; case 8: //按钮声音 SimpleAudioEngine::getInstance()->playEffect("sound/common_botton.mp3"); break; case 9: SimpleAudioEngine::sharedEngine()->playBackgroundMusic("sound/bgMain.mp3", true); break; case 10: SimpleAudioEngine::sharedEngine()->playBackgroundMusic("sound/bgFight.mp3", true); break; default: break; } } }
[ "1216175270@qq.com" ]
1216175270@qq.com
9366f9e4966a8bae8d613a062b38788399dea8b3
8bb1943b37b0a4c4ab512658bc0c3507272b3e06
/source/NanairoGui/Renderer/gui_renderer_manager.hpp
4c7ffa107dda3929920578679db2fa9b1680157d
[ "MIT" ]
permissive
kmribti/Nanairo
c89abc8cf4fb222b7383d681facbcc31bc15fc2c
f21fad1b67cd8fc31b0ff2f68445d38418b0652c
refs/heads/master
2020-03-24T14:59:20.966140
2018-07-15T12:37:52
2018-07-15T12:37:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,174
hpp
/*! \file gui_renderer_manager.hpp \author Sho Ikeda Copyright (c) 2015-2018 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef NANAIRO_GUI_RENDERER_MANAGER #define NANAIRO_GUI_RENDERER_MANAGER // Standard C++ library #include <cstdint> // Qt #include <QObject> #include <QString> #include <QUrl> #include <QVariant> #include <QtGlobal> // Zisc #include "zisc/thread_manager.hpp" // Nanairo #include "cui_renderer_manager.hpp" #include "NanairoCore/nanairo_core_config.hpp" namespace nanairo { //! \addtogroup Gui //! \{ // Forward declaration class GuiRenderer; class RenderedImageProvider; class SceneRendererBase; /*! \details No detailed. */ class GuiRendererManager : public QObject, public CuiRendererManager { Q_OBJECT public: //! Initialize manager GuiRendererManager() noexcept; // Utilities //! Return the current working directory Q_INVOKABLE QString currentWorkingDir() const noexcept; //! Generate a random seed randomly Q_INVOKABLE int generateSeedRandomly() const noexcept; //! Get the file name from URL Q_INVOKABLE QString getFileName(const QUrl& file_path) const noexcept; //! Return the ideal thread counts Q_INVOKABLE int getIdealThreadCount() const noexcept; //! Convert a relative path to a url of absolute path Q_INVOKABLE QUrl getAbsolutePath(const QString& relative_path) const noexcept; //! Convert a url of absolute path to a relative path Q_INVOKABLE QString getRelativePath(const QUrl& absolute_path) const noexcept; //! Check if the GUI is debug mode Q_INVOKABLE bool isDebugMode() const noexcept; //! Invoke the rendering function of the renderer Q_INVOKABLE void invokeRendering(const QVariant& scene_data, const bool is_previewing) noexcept; //! Open a scene data Q_INVOKABLE QVariant loadSceneData(const QUrl& file_path) const noexcept; //! Save a scene data Q_INVOKABLE void saveSceneData(const QUrl& file_path, const QVariant& scene_data) const noexcept; //! Set rendered image provider void setRenderedImageProvider(RenderedImageProvider* image_provider) noexcept; signals: //! Notify that rendering is finished void finished() const; //! Notify that rendering is started void started() const; //! Called when the manager is to stop the rendering void stopRendering() const; //! Called when a preview event is occured void previewEvent(const int transformation_event_type, const int axis_event_type, const int value) const; //! Notify of updating rendering info void notifyOfRenderingInfo(const QString& info) const; private: //! Connect with renderer void connectWithRenderer(GuiRenderer* renderer) noexcept; //! Disconnect from renderer void disconnectFromRenderer() noexcept; //! Return the image provider RenderedImageProvider* renderedImageProvider() noexcept; zisc::ThreadManager rendering_thread_; RenderedImageProvider* image_provider_; }; //! \} Gui } // namespace nanairo #endif // NANAIRO_GUI_RENDERER_MANAGER
[ "zin.kosmos.1190@gmail.com" ]
zin.kosmos.1190@gmail.com
91196580962f416ce7625425469946d0f2204201
2f084587d83c89d5576c8a1d60e5a357fe95e859
/source/solver/grid.cpp
710ff38f7cbcbc285bbe16b5bbb0cdafb9189f96
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
garethbrickman/regex-crossword-solver
fa1d4f608e5c84b0ac262c12ce98f5cdd1ccfadc
3d4cfe3b973e44f5250f5438ce6b4b696ecd3cd7
refs/heads/master
2021-07-13T15:19:43.361867
2017-10-14T15:41:50
2017-10-14T15:41:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,837
cpp
// Copyright (c) 2016 Antoine Trux // // The original version is available at // http://solving-regular-expression-crosswords.blogspot.com // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice, the above original version notice, and // this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "grid.hpp" #include "alphabet.hpp" #include "grid_cell.hpp" #include "grid_line.hpp" #include "logger.hpp" #include "utils.hpp" #include <algorithm> #include <cassert> #include <iterator> #include <numeric> using namespace std; namespace { // Return the first lines that appear in a report corresponding to the // given arguments. vector<string> report_header(const vector<unique_ptr<Grid>>& solutions, unsigned int num_solutions_to_find) { const auto num_solutions_found = solutions.size(); if (num_solutions_found == 0) { return { "this grid has no solutions" }; } else { if (num_solutions_found < num_solutions_to_find) { return { "found " + Utils::to_string(num_solutions_found) + " solution(s) (there are no other solutions):" }; } else { return { "first " + Utils::to_string(num_solutions_found) + " solution(s) found (there might be other solutions):", "", "(if you want to see if there are other solutions,", " increase the value of command line option " "'--stop-after')" }; } } } void log_solutions(const vector<unique_ptr<Grid>>& solutions, unsigned int num_solutions_to_find) { static_cast<void>(num_solutions_to_find); LOG_BLANK_LINE(); LOG(report_header(solutions, num_solutions_to_find)); INCREMENT_LOGGING_INDENTATION_LEVEL(); for (const auto& solution : solutions) { static_cast<void>(solution); LOG_BLANK_LINE(); LOG(solution->print_verbose()); } DECREMENT_LOGGING_INDENTATION_LEVEL(); } } // unnamed namespace // instance creation and deletion Grid::Grid() { } Grid::Grid(const Grid& /*rhs*/) { // copy_lines_and_cells() (indirectly) calls virtual functions, so // copy_lines_and_cells() is not called here. Instead, it is called // by the copy constructor of the subclasses. } Grid::~Grid() = default; void Grid::build_cell(size_t x, size_t y) { const auto coordinates_ = coordinates(x, y); auto cell = make_cell(coordinates_); for (size_t line_direction = 0; line_direction != num_line_directions(); ++line_direction) { place_cell(cell, coordinates_, line_direction); } } void Grid::build_cells() { for (size_t x = 0; x != num_rows(); ++x) { for (auto y = begin_y(x); y != end_y(x); ++y) { build_cell(x, y); } } } void Grid::build_grid_structure() { build_lines(); build_cells(); } void Grid::build_lines() { for (size_t line_direction = 0; line_direction != num_line_directions(); ++line_direction) { m_lines_per_direction.push_back(make_lines(line_direction)); } } void Grid::build_regexes(const vector<vector<string>>& regex_groups) const { const auto lines = all_lines(); for (size_t i = 0; i != lines.size(); ++i) { const auto line = lines[i]; line->build_regexes(regex_groups[i]); } } void Grid::construct_grid(const vector<vector<string>>& regex_groups) { build_grid_structure(); build_regexes(regex_groups); set_alphabet(); initialize_cells(); } void Grid::initialize_cells() { for (const auto& cell : all_cells()) { cell->set_possible_characters_to_all_characters(); } } shared_ptr<GridCell> Grid::make_cell(const vector<size_t>& coordinates) { return make_shared<GridCell>(coordinates); } unique_ptr<GridLine> Grid::make_line(size_t line_direction, size_t line_index_within_direction, size_t num_cells) const { return Utils::make_unique<GridLine>(*this, line_direction, line_index_within_direction, num_cells); } void Grid::place_cell(shared_ptr<GridCell> cell, const vector<size_t>& coordinates, size_t line_direction) { const auto lines = lines_through(coordinates); const auto coordinate = coordinates[line_direction]; const auto next_line_direction = (line_direction + 1) % num_line_directions(); const auto next_coordinate = coordinates[next_line_direction]; const auto line = lines[line_direction]; const auto index_of_cell_on_line_ = index_of_cell_on_line(coordinate, next_coordinate); line->set_cell(cell, index_of_cell_on_line_); } // Set the alphabet, according to the characters in the regexes which // were previously assigned to the grid lines. void Grid::set_alphabet() const { Alphabet::set(explicit_regex_characters()); } // copying // Copy to this grid the cell in 'source_grid' at coordinates 'x' and 'y'. void Grid::copy_cell(const Grid& source_grid, size_t x, size_t y) { const auto coordinates = source_grid.coordinates(x, y); const auto cell_to_copy = source_grid.cell(coordinates); const auto cell_copy = make_cell(*cell_to_copy); for (size_t line_direction = 0; line_direction != num_line_directions(); ++line_direction) { place_cell(cell_copy, coordinates, line_direction); } } // Copy to this grid the cells of 'source_grid'. void Grid::copy_cells(const Grid& source_grid) { for (size_t x = 0; x != num_rows(); ++x) { for (auto y = begin_y(x); y != end_y(x); ++y) { copy_cell(source_grid, x, y); } } } // Copy to this grid the lines of 'source_grid'. void Grid::copy_lines(const Grid& source_grid) { build_lines(); copy_regexes(source_grid); } // Copy to this grid the lines and cells of 'source_grid'. void Grid::copy_lines_and_cells(const Grid& source_grid) { copy_lines(source_grid); copy_cells(source_grid); } // Copy to this grid the regexes of 'source_grid'. void Grid::copy_regexes(const Grid& source_grid) { const auto lines = all_lines(); const auto source_lines = source_grid.all_lines(); for (size_t i = 0; i != lines.size(); ++i) { const auto line = lines[i]; const auto source_line = source_lines[i]; line->copy_regexes(*source_line); } } shared_ptr<GridCell> Grid::make_cell(const GridCell& cell_to_copy) { return make_shared<GridCell>(cell_to_copy); } // accessing vector<shared_ptr<GridCell>> Grid::all_cells() const { vector<shared_ptr<GridCell>> result; for (const auto& row : rows()) { const auto& row_cells = row->cells(); result.insert(end(result), row_cells.cbegin(), row_cells.cend()); } return result; } vector<GridLine*> Grid::all_lines() const { vector<GridLine*> result; for (const auto& lines : m_lines_per_direction) { for (const auto& line : lines) { result.push_back(line.get()); } } return result; } shared_ptr<GridCell> Grid::cell(const vector<size_t>& coordinates) const { const auto x = coordinates[0]; const auto y = coordinates[1]; const auto& rows_ = rows(); const auto& row = rows_[x]; const auto index_on_row = index_of_cell_on_line(x, y); return row->cell(index_on_row); } // Precondition: // * there is at least one cell in this grid which can be searched // (i.e., one cell with several possible characters) shared_ptr<GridCell> Grid::cell_to_search() const { const auto cells = all_cells(); vector<shared_ptr<GridCell>> cells_that_can_be_searched; copy_if(cells.cbegin(), cells.cend(), back_inserter(cells_that_can_be_searched), [](shared_ptr<GridCell> cell) { return cell->has_several_possible_characters(); }); assert(!cells_that_can_be_searched.empty()); // It is heuristically best to search a cell with the least number // of possible characters, since the probability to find a solution // by selecting a character at random from such a cell is the // greatest. return *min_element(cells_that_can_be_searched.cbegin(), cells_that_can_be_searched.cend(), [](shared_ptr<GridCell> cell_1, shared_ptr<GridCell> cell_2) { return cell_1->num_possible_characters() < cell_2->num_possible_characters(); }); } // Return the characters which appear explicitly in the regexes of this // grid. string Grid::explicit_regex_characters() const { const auto lines = all_lines(); return accumulate(lines.cbegin(), lines.cend(), string(), [](const string& sum, const GridLine* line) { return sum + line->explicit_regex_characters(); }); } GridLine* Grid::line_at(size_t line_direction, size_t line_index) const { assert(line_direction < num_line_directions()); const auto& lines_for_direction = m_lines_per_direction[line_direction]; assert(line_index < lines_for_direction.size()); return lines_for_direction[line_index].get(); } // Return the lines that go through the cell at 'coordinates'. vector<GridLine*> Grid::lines_through(const vector<size_t>& coordinates) const { vector<GridLine*> result; size_t line_direction = 0; for (auto coordinate : coordinates) { result.push_back( m_lines_per_direction[line_direction][coordinate].get()); ++line_direction; } return result; } // Return the maximum length of the possible characters of cells, when // printed. // // For example, if this grid has two cells with possible characters // "ABC" (cell 1) and "AB" (cell 2), then: // * cell 1 is represented as "ABC", which has length 3, // * cell 2 is represented as "AB", which has length 2, // so this function would return 3. size_t Grid::max_length_of_possible_characters_as_string() const { const auto cells = all_cells(); const auto& max_cell = *max_element( cells.cbegin(), cells.cend(), [](const shared_ptr<GridCell>& cell_1, const shared_ptr<GridCell>& cell_2) { return cell_1->possible_characters_as_string().size() < cell_2->possible_characters_as_string().size(); }); return max_cell->possible_characters_as_string().size(); } GridLine* Grid::row_at(size_t row_index) const { assert(row_index < num_rows()); return rows()[row_index].get(); } const vector<unique_ptr<GridLine>>& Grid::rows() const { return m_lines_per_direction[0]; } // querying bool Grid::is_solved() const { const auto cells = all_cells(); return all_of(cells.cbegin(), cells.cend(), [](const shared_ptr<GridCell>& cell) { return cell->is_solved(); }); } // printing // Log the result of the constrain that was done to this grid. The // constrain was either successful or unsuccessful, according to // 'success'. void Grid::log_constrain_result(bool success) const { LOG_BLANK_LINE(); if (success) { LOG("grid was successfully constrained to:"); INCREMENT_LOGGING_INDENTATION_LEVEL(); LOG(print_verbose()); DECREMENT_LOGGING_INDENTATION_LEVEL(); } else { LOG("grid could not be constrained"); } } vector<string> Grid::print() const { const auto verbose = false; return do_print(verbose); } vector<string> Grid::print_verbose() const { const auto verbose = true; return do_print(verbose); } void Grid::report_solutions(const vector<unique_ptr<Grid>>& solutions, unsigned int num_solutions_to_find) { const auto header_lines = report_header(solutions, num_solutions_to_find); for (const auto& header_line : header_lines) { cout << header_line << endl; } for (const auto& solution : solutions) { cout << endl; cout << *solution; } } ostream& operator<<(ostream& os, const Grid& grid) { for (const auto& line : grid.print()) { os << line << endl; } return os; } // modifying // Constrain this grid. // // Return true if no contradiction was found. The grid, however, may not // have been solved yet: some cells may still contain several possible // characters. // // Return false if a contradiction was found (i.e., if this grid cannot // be solved). bool Grid::constrain() { LOG_BLANK_LINE(); LOG("constraining grid:"); INCREMENT_LOGGING_INDENTATION_LEVEL(); LOG(print_verbose()); DECREMENT_LOGGING_INDENTATION_LEVEL(); INCREMENT_LOGGING_INDENTATION_LEVEL(); const auto result = constrain_no_log(); DECREMENT_LOGGING_INDENTATION_LEVEL(); log_constrain_result(result); return result; } // Same as constrain(), except that this version does not (directly) log. bool Grid::constrain_no_log() { const auto lines = all_lines(); const auto num_lines = lines.size(); size_t num_consecutive_lines_constrained_without_changes = 0; size_t line_index = 0; while (num_consecutive_lines_constrained_without_changes != num_lines) { auto line = lines[line_index]; const auto line_constraint_was_changed = line->constrain(); if (line_constraint_was_changed) { if (line->has_impossible_constraint()) { return false; } else { num_consecutive_lines_constrained_without_changes = 0; } } else { ++num_consecutive_lines_constrained_without_changes; } line_index = (line_index + 1) % num_lines; } return true; } // Optimize the regexes of this grid according to 'optimizations'. void Grid::optimize(const RegexOptimizations& optimizations) { for (auto line : all_lines()) { line->optimize(optimizations); } } // Return the solved grid(s) obtained from this grid by searching // 'cell'. vector<unique_ptr<Grid>> Grid::search_cell(const GridCell& cell, unsigned int& num_remaining_solutions_to_find) { vector<unique_ptr<Grid>> solutions; for (auto possible_character : cell.possible_characters()) { auto solutions_for_character = search_cell(cell, possible_character, num_remaining_solutions_to_find); solutions.insert(end(solutions), make_move_iterator(solutions_for_character.begin()), make_move_iterator(solutions_for_character.end())); if (num_remaining_solutions_to_find == 0) { return solutions; } } return solutions; } // Return the solved grid(s) obtained from this grid by constraining // 'cell' to contain 'c'. vector<unique_ptr<Grid>> Grid::search_cell(const GridCell& cell, char c, unsigned int& num_remaining_solutions_to_find) { LOG_BLANK_LINE(); LOG("searching cell:"); INCREMENT_LOGGING_INDENTATION_LEVEL(); auto copy_of_this_grid = clone(); auto cell_in_copy = copy_of_this_grid->cell(cell.coordinates()); LOG(cell_in_copy->to_string() + ": " + cell_in_copy->possible_characters_as_string() + " => " + c); cell_in_copy->set_possible_characters(c); auto result = copy_of_this_grid->solve_no_log(num_remaining_solutions_to_find); DECREMENT_LOGGING_INDENTATION_LEVEL(); return result; } vector<unique_ptr<Grid>> Grid::search_grid(unsigned int& num_remaining_solutions_to_find) { LOG_BLANK_LINE(); LOG("searching grid:"); INCREMENT_LOGGING_INDENTATION_LEVEL(); LOG(print_verbose()); auto result = search_cell(*cell_to_search(), num_remaining_solutions_to_find); DECREMENT_LOGGING_INDENTATION_LEVEL(); return result; } // Solve this grid. Return no more than 'num_solutions_to_find' // solutions. // // Precondition: // * num_solutions_to_find != 0 vector<unique_ptr<Grid>> Grid::solve(unsigned int num_solutions_to_find) { assert(num_solutions_to_find != 0); LOG_BLANK_LINE(); LOG("attemping to solve this grid:"); INCREMENT_LOGGING_INDENTATION_LEVEL(); LOG(print_verbose()); DECREMENT_LOGGING_INDENTATION_LEVEL(); auto num_remaining_solutions_to_find = num_solutions_to_find; auto solutions = solve_no_log(num_remaining_solutions_to_find); log_solutions(solutions, num_solutions_to_find); return solutions; } // Same as solve(), except that this version does not (directly) log. vector<unique_ptr<Grid>> Grid::solve_no_log(unsigned int& num_remaining_solutions_to_find) { if (!constrain()) { // No solutions. return {}; } if (is_solved()) { Utils::print_verbose_message(cout, "found a solution"); vector<unique_ptr<Grid>> result; result.push_back(clone()); assert(num_remaining_solutions_to_find != 0); --num_remaining_solutions_to_find; return result; } return search_grid(num_remaining_solutions_to_find); }
[ "antoine.trux@gmail.com" ]
antoine.trux@gmail.com
ef84cfc88d1051884b152700d3085ec5ea56149f
e484abe99db558c4bcdff4d5c4dabefba00bf1ab
/ZombieEscape/Private/Game/WinTriggerBox.cpp
56d720dde11c4d4de2f66ebbc2ec68a1ec3598eb
[]
no_license
Luka033/ZombieEscape-UE4
ffd51233ef2f65b2e41f51d406d8cc413da0e55b
6d9480ac44e466b42f6c3d22d9788e33530a1f6d
refs/heads/master
2023-02-09T12:19:55.013926
2021-01-05T17:35:30
2021-01-05T17:35:30
316,078,522
2
0
null
null
null
null
UTF-8
C++
false
false
892
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "WinTriggerBox.h" #include "..\..\Public\Player\CharacterBase.h" #include "..\..\Public\Game\EscapeGameMode.h" #include "DrawDebugHelpers.h" AWinTriggerBox::AWinTriggerBox() { OnActorBeginOverlap.AddDynamic(this, &AWinTriggerBox::OnOverlapBegin); } void AWinTriggerBox::BeginPlay() { Super::BeginPlay(); /*DrawDebugBox(GetWorld(), GetActorLocation(), GetComponentsBoundingBox().GetExtent(), FColor::Green, true, -1, 0, 5);*/ } void AWinTriggerBox::OnOverlapBegin(AActor* OverlappedActor, AActor* OtherActor) { if (ACharacterBase* Player = Cast<ACharacterBase>(OtherActor)) { APlayerController* PlayerController = Cast<APlayerController>(Player->GetController()); if (PlayerController != nullptr) { PlayerController->GameHasEnded(Player, true); } } }
[ "noreply@github.com" ]
noreply@github.com
eafffa60e54fd516aae79e08f659c2823f8e330c
510dd9d3b96c600a3b1f0aaa2e4ab0e4a851b57d
/src/qt/addressbookpage.cpp
8505d89b1331c0a9edea76708c22606e4c176213
[ "MIT" ]
permissive
lifetioncoin/lifetioncoin
e55c25e7b3f1be95e6c42c72d3a179c4d9cada58
566b7bf2268eecc712c708d90f05f85b97d7c2dc
refs/heads/master
2023-02-05T23:00:28.313716
2020-12-24T15:40:14
2020-12-24T15:40:14
319,767,838
0
0
null
null
null
null
UTF-8
C++
false
false
10,185
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The LifetionCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/lifetioncoin-config.h" #endif #include "addressbookpage.h" #include "ui_addressbookpage.h" #include "addresstablemodel.h" #include "bitcoingui.h" #include "csvmodelwriter.h" #include "editaddressdialog.h" #include "guiutil.h" #include "platformstyle.h" #include <QIcon> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> AddressBookPage::AddressBookPage(const PlatformStyle *platformStyle, Mode mode, Tabs tab, QWidget *parent) : QDialog(parent), ui(new Ui::AddressBookPage), model(0), mode(mode), tab(tab) { QString theme = GUIUtil::getThemeName(); ui->setupUi(this); if (!platformStyle->getImagesOnButtons()) { ui->newAddress->setIcon(QIcon()); ui->copyAddress->setIcon(QIcon()); ui->deleteAddress->setIcon(QIcon()); ui->exportButton->setIcon(QIcon()); } else { ui->newAddress->setIcon(QIcon(":/icons/" + theme + "/add")); ui->copyAddress->setIcon(QIcon(":/icons/" + theme + "/editcopy")); ui->deleteAddress->setIcon(QIcon(":/icons/" + theme + "/remove")); ui->exportButton->setIcon(QIcon(":/icons/" + theme + "/export")); } switch(mode) { case ForSelection: switch(tab) { case SendingTab: setWindowTitle(tr("Choose the address to send coins to")); break; case ReceivingTab: setWindowTitle(tr("Choose the address to receive coins with")); break; } connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(accept())); ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->tableView->setFocus(); ui->closeButton->setText(tr("C&hoose")); ui->exportButton->hide(); break; case ForEditing: switch(tab) { case SendingTab: setWindowTitle(tr("Sending addresses")); break; case ReceivingTab: setWindowTitle(tr("Receiving addresses")); break; } break; } switch(tab) { case SendingTab: ui->labelExplanation->setText(tr("These are your LifetionCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.")); ui->deleteAddress->setVisible(true); break; case ReceivingTab: ui->labelExplanation->setText(tr("These are your LifetionCoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.")); ui->deleteAddress->setVisible(false); break; } // Context menu actions QAction *copyAddressAction = new QAction(tr("&Copy Address"), this); QAction *copyLabelAction = new QAction(tr("Copy &Label"), this); QAction *editAction = new QAction(tr("&Edit"), this); deleteAction = new QAction(ui->deleteAddress->text(), this); // Build context menu contextMenu = new QMenu(this); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(editAction); if(tab == SendingTab) contextMenu->addAction(deleteAction); contextMenu->addSeparator(); // Connect signals for context menu actions connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(on_copyAddress_clicked())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(onCopyLabelAction())); connect(editAction, SIGNAL(triggered()), this, SLOT(onEditAction())); connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteAddress_clicked())); connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(accept())); } AddressBookPage::~AddressBookPage() { delete ui; } void AddressBookPage::setModel(AddressTableModel *model) { this->model = model; if(!model) return; proxyModel = new QSortFilterProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setDynamicSortFilter(true); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); switch(tab) { case ReceivingTab: // Receive filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Receive); break; case SendingTab: // Send filter proxyModel->setFilterRole(AddressTableModel::TypeRole); proxyModel->setFilterFixedString(AddressTableModel::Send); break; } ui->tableView->setModel(proxyModel); ui->tableView->sortByColumn(0, Qt::AscendingOrder); // Set column widths #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #else ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(AddressTableModel::Address, QHeaderView::ResizeToContents); #endif connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged())); // Select row for newly created address connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(selectNewAddress(QModelIndex,int,int))); selectionChanged(); } void AddressBookPage::on_copyAddress_clicked() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Address); } void AddressBookPage::onCopyLabelAction() { GUIUtil::copyEntryData(ui->tableView, AddressTableModel::Label); } void AddressBookPage::onEditAction() { if(!model) return; if(!ui->tableView->selectionModel()) return; QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if(indexes.isEmpty()) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::EditSendingAddress : EditAddressDialog::EditReceivingAddress, this); dlg.setModel(model); QModelIndex origIndex = proxyModel->mapToSource(indexes.at(0)); dlg.loadRow(origIndex.row()); dlg.exec(); } void AddressBookPage::on_newAddress_clicked() { if(!model) return; EditAddressDialog dlg( tab == SendingTab ? EditAddressDialog::NewSendingAddress : EditAddressDialog::NewReceivingAddress, this); dlg.setModel(model); if(dlg.exec()) { newAddressToSelect = dlg.getAddress(); } } void AddressBookPage::on_deleteAddress_clicked() { QTableView *table = ui->tableView; if(!table->selectionModel()) return; QModelIndexList indexes = table->selectionModel()->selectedRows(); if(!indexes.isEmpty()) { table->model()->removeRow(indexes.at(0).row()); } } void AddressBookPage::selectionChanged() { // Set button states based on selected tab and selection QTableView *table = ui->tableView; if(!table->selectionModel()) return; if(table->selectionModel()->hasSelection()) { switch(tab) { case SendingTab: // In sending tab, allow deletion of selection ui->deleteAddress->setEnabled(true); ui->deleteAddress->setVisible(true); deleteAction->setEnabled(true); break; case ReceivingTab: // Deleting receiving addresses, however, is not allowed ui->deleteAddress->setEnabled(false); ui->deleteAddress->setVisible(false); deleteAction->setEnabled(false); break; } ui->copyAddress->setEnabled(true); } else { ui->deleteAddress->setEnabled(false); ui->copyAddress->setEnabled(false); } } void AddressBookPage::done(int retval) { QTableView *table = ui->tableView; if(!table->selectionModel() || !table->model()) return; // Figure out which address was selected, and return it QModelIndexList indexes = table->selectionModel()->selectedRows(AddressTableModel::Address); Q_FOREACH (const QModelIndex& index, indexes) { QVariant address = table->model()->data(index); returnValue = address.toString(); } if(returnValue.isEmpty()) { // If no address entry selected, return rejected retval = Rejected; } QDialog::done(retval); } void AddressBookPage::on_exportButton_clicked() { // CSV is currently the only supported format QString filename = GUIUtil::getSaveFileName(this, tr("Export Address List"), QString(), tr("Comma separated file (*.csv)"), NULL); if (filename.isNull()) return; CSVModelWriter writer(filename); // name, column, role writer.setModel(proxyModel); writer.addColumn("Label", AddressTableModel::Label, Qt::EditRole); writer.addColumn("Address", AddressTableModel::Address, Qt::EditRole); if(!writer.write()) { QMessageBox::critical(this, tr("Exporting Failed"), tr("There was an error trying to save the address list to %1. Please try again.").arg(filename)); } } void AddressBookPage::contextualMenu(const QPoint &point) { QModelIndex index = ui->tableView->indexAt(point); if(index.isValid()) { contextMenu->exec(QCursor::pos()); } } void AddressBookPage::selectNewAddress(const QModelIndex &parent, int begin, int /*end*/) { QModelIndex idx = proxyModel->mapFromSource(model->index(begin, AddressTableModel::Address, parent)); if(idx.isValid() && (idx.data(Qt::EditRole).toString() == newAddressToSelect)) { // Select row of newly created address, once ui->tableView->setFocus(); ui->tableView->selectRow(idx.row()); newAddressToSelect.clear(); } }
[ "david@lifetioncoin.org" ]
david@lifetioncoin.org
ca8e7e01ed3ebfa3aaa066a70176b0486bced8cb
03328723d5804ab7081d562461c54598a22a3d1a
/QweakSimRoot.cc
c51fbbd3568ae4572be97f2ce2c339426b7c3800
[]
no_license
rr521111/QweakG4DD
48915e268c34d3133c78f35a50af601fd6c239ae
ab972579552b42a1654ffa08f30822e0415a1d5d
refs/heads/master
2021-06-02T20:39:42.550410
2019-05-03T15:36:07
2019-05-03T15:36:07
96,327,663
0
0
null
2017-07-05T14:22:27
2017-07-05T14:22:27
null
UTF-8
C++
false
false
638
cc
/*------------------------------------------------------------------------*//*! \file QweakSimRoot.cc \brief ROOT wrapper with QweakSim functionality *//*-------------------------------------------------------------------------*/ // ROOT headers #include <TSystem.h> #include <TROOT.h> #include <TString.h> // QweakSim headers #include "QweakSimRint.hh" int main(int argc, char** argv) { // Start QweakSim-Root command prompt QweakSimRint* qweaksimrint = new QweakSimRint("QweakSim ROOT Analyzer", &argc, argv); // Setup include path gROOT->ProcessLine(".include include"); qweaksimrint->Run(); delete qweaksimrint; }
[ "ciprian@dochia.local" ]
ciprian@dochia.local
ff30350c4e4e13378832369a1ffb924671b074c0
bc28409687fb9a91b2994cb94b01e1ff5a580c3a
/03_BuildingEscape/BuildingEscape/Source/BuildingEscape/Grabber.h
5e93453fc6f6b4a2eaff58cee724ed99db087558
[]
no_license
Cabal1996/03_BuidingEscape
b729def2f168e8ef7610fb12a21b8277fb202037
74100747bb3f31927207f46280fc7a02818cfcce
refs/heads/master
2021-05-15T05:25:28.282739
2018-01-12T15:50:22
2018-01-12T15:50:22
117,255,462
0
0
null
null
null
null
UTF-8
C++
false
false
1,537
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "Components/InputComponent.h" #include "Components/PrimitiveComponent.h" #include "Engine/World.h" #include "DrawDebugHelpers.h" #include "CollisionQueryParams.h" #include "PhysicsEngine/PhysicsHandleComponent.h" #include "GameFramework/Actor.h" #include "Grabber.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class BUILDINGESCAPE_API UGrabber : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UGrabber(); protected: // Called when the game starts virtual void BeginPlay() override; public: // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; private: //How far player can reach in cm const float Rach = 100.0f; UPhysicsHandleComponent* PhysicsHadle = nullptr; UInputComponent* PawnInput = nullptr; //Find (assumed) attached physics handle void FindPhysicsHandleComponent(); //Setup (assumed) attached Input Component void SetupInputComponent(); //Rey-cast and grab what's in reach void Grab(); //Release grabbed object void Release(); //Return hit for first physic body in reach FHitResult GetFirstPhysicBodyInReach(); //Get player reach start location FVector GetReachLineStart(); //Get player reach end location FVector GetReachLineEnd(); };
[ "drax1996@gmail.com" ]
drax1996@gmail.com
9d67370cec8ae082ec569cfc17fee8d12cf24326
0d99bcb8b8717008c1ec9b080c6c86c2b1710eee
/날씨/build/Android/Debug/app/src/main/jni/Uno/Memory.cpp
85bbfa29afcd8d8113354bbecc2dc083831f99a2
[]
no_license
shj4849/Fuse
526d92bc49a0a2d8087beece987b1701dc35cccc
447f49f96f9dadf203f5f91e8a1d67f19d8ecc04
refs/heads/master
2021-05-15T23:08:09.523726
2017-12-21T05:28:53
2017-12-21T05:28:53
106,758,124
0
0
null
null
null
null
UTF-8
C++
false
false
26,382
cpp
// This file was generated based on C:/Users/t2/AppData/Local/Fusetools/Packages/UnoCore/1.4.3/Backends/CPlusPlus/Uno/Memory.cpp. // WARNING: Changes might be lost if you edit this file directly. #include <Uno/_internal.h> #include <Uno/Support.h> #include <uBase/Atomic.h> #include <uBase/HashMap.h> #include <uBase/String.h> #include <uBase/StringBuilder.h> #include <uBase/Thread.h> #include <uBase/Traits.h> #include <uBase/Unicode.h> #include <Uno.Type.h> #include <Uno.String.h> static void* _MainThread; static uBase::ThreadLocal* _ThreadLocal; static uBase::Mutex* _WeakMutex; #ifdef DEBUG_DUMPS static uBase::HashMap<uObject*, bool>* _HeapObjects; #endif static bool uTryClearWeak(uObject*); //#if #(REFLECTION:Defined) //void uInitReflection(); //void uFreeReflection(); //void uRegisterIntrinsics(); //#endif void uInitObjectModel(); void uFreeObjectModel(); void uInitSupport(); void uFreeSupport(); static uThreadData* uGetThreadData() { void* value = uBase::GetThreadLocal(_ThreadLocal); if (!value) { value = new uThreadData(); uBase::SetThreadLocal(_ThreadLocal, value); } return (uThreadData*)value; } static void uFreeThreadData(void* value) { delete (uThreadData*)value; } uRuntime::uRuntime() { if (_MainThread) uFatal(NULL, "There is only room for one Uno Runtime object in this process."); _MainThread = uBase::GetThread(); _ThreadLocal = uBase::CreateThreadLocal(uFreeThreadData); _WeakMutex = uBase::CreateMutex(); #ifdef DEBUG_DUMPS _HeapObjects = new uBase::HashMap<uObject*, bool>(); #endif uAutoReleasePool pool; //#if #(REFLECTION:Defined) // uInitReflection(); //#endif uInitSupport(); uInitObjectModel(); //#if #(REFLECTION:Defined) // uRegisterIntrinsics(); //#endif } uRuntime::~uRuntime() { uFreeSupport(); uFreeObjectModel(); //#if #(REFLECTION:Defined) // uFreeReflection(); //#endif #ifdef DEBUG_DUMPS delete _HeapObjects; #endif uBase::DeleteThreadLocal(_ThreadLocal); uBase::DeleteMutex(_WeakMutex); } uType* uSwapThreadType(uType* type) { uThreadData* thread = uGetThreadData(); uType* result = thread->CurrentType; thread->CurrentType = type; return result; } uStackFrame::uStackFrame(const char* type, const char* function) : _thread(uGetThreadData()) { uCallStackFrame* frame = ++_thread->CallStackPtr; U_ASSERT(frame < _thread->CallStackEnd && !frame->Type && !frame->Function); frame->Type = type; frame->Function = function; } uStackFrame::~uStackFrame() { #ifdef DEBUG_UNSAFE uCallStackFrame* frame = #endif _thread->CallStackPtr--; #ifdef DEBUG_UNSAFE frame->Type = NULL; frame->Function = NULL; #endif } uString* uGetStackTrace() { uBase::StringBuilder sb; uThreadData* thread = uGetThreadData(); for (uCallStackFrame* frame = thread->CallStackPtr; frame >= thread->CallStack; frame--) { if (sb.GetLength() > 0) sb += '\n'; sb += " at "; sb += frame->Type; sb += '.'; sb += frame->Function; } return uStringFromXliString(sb.ToString()); } #ifdef DEBUG_ARC static uBase::String uGetCaller() { uThreadData* thread = uGetThreadData(); if (thread->CallStackPtr < thread->CallStack) return ""; uBase::StringBuilder sb; uCallStackFrame* frame = thread->CallStackPtr; sb += " -- at "; sb += frame->Type; sb += '.'; sb += frame->Function; return sb.ToString(); } #endif static void uPushAutoReleasePool(uThreadData* thread) { uAutoReleaseFrame* frame = ++thread->AutoReleasePtr; U_ASSERT(frame < thread->AutoReleaseEnd); frame->StartIndex = thread->AutoReleaseList.Length(); #ifdef DEBUG_ARC frame->AllocCount = 0; frame->AllocSize = 0; frame->FreeCount = 0; frame->FreeSize = 0; #endif } static void uPopAutoReleasePool(uThreadData* thread) { uAutoReleaseFrame* frame = thread->AutoReleasePtr; U_ASSERT(thread->AutoReleasePtr >= thread->AutoReleaseStack); for (size_t i = frame->StartIndex; i < thread->AutoReleaseList.Length(); i++) { uObject* object = thread->AutoReleaseList[i]; #ifdef DEBUG_ARC frame->AllocCount++; frame->AllocSize += object->__size; #endif uRelease(object); } #if DEBUG_ARC >= 1 U_LOG("--- Alloc'd %d objects (%d bytes), Free'd %d objects (%d bytes) ---", frame->AllocCount, frame->AllocSize, frame->FreeCount, frame->FreeSize); #endif thread->AutoReleaseList.Resize(frame->StartIndex); thread->AutoReleasePtr--; } uAutoReleasePool::uAutoReleasePool() : _thread(uGetThreadData()) { uPushAutoReleasePool(_thread); } uAutoReleasePool::~uAutoReleasePool() { U_ASSERT(_thread == uGetThreadData()); uPopAutoReleasePool(_thread); } uForeignPool::uForeignPool() : _thread(uGetThreadData()) , _threadHasPool(_thread->AutoReleasePtr >= _thread->AutoReleaseStack) { if (!_threadHasPool) uPushAutoReleasePool(_thread); } uForeignPool::~uForeignPool() { U_ASSERT(_thread == uGetThreadData()); if (!_threadHasPool) uPopAutoReleasePool(_thread); } void uStoreStrong(uObject** address, uObject* object) { uAutoRelease(*address); uRetain(*address = object); } void uAutoRelease(uObject* object) { if (object) { uThreadData* thread = uGetThreadData(); thread->AutoReleaseList.Add(object); U_ASSERT(thread->AutoReleasePtr >= thread->AutoReleaseStack); #ifdef DEBUG_ARC int releaseCount = 0; for (size_t i = 0; i < thread->AutoReleaseList.Length(); i++) if (thread->AutoReleaseList[i] == object) releaseCount++; int retainCount = object->__retains - releaseCount; if (retainCount < 0) { U_LOG("*** BAD AUTORELEASE: %s #%d (%d bytes, %d retains) ***%s", object->__type->FullName, object->__id, object->__size, retainCount, uGetCaller().Ptr()); U_FATAL(); } #endif #if DEBUG_ARC >= 4 U_LOG("autorelease %s #%d (%d bytes, %d retains)%s", object->__type->FullName, object->__id, object->__size, object->__retains, uGetCaller().Ptr()); #endif } } void uRetainStruct(uType* type, void* address) { #if DEBUG_ARC >= 4 U_LOG("retain %s [struct] (%d bytes)%s", type->FullName, type->ValueSize, uGetCaller().Ptr()); #endif for (size_t i = 0; i < type->Refs.StrongCount; i++) uRetain(*(uObject**)((uint8_t*)address + type->Refs.Strong[i])); } void uReleaseStruct(uType* type, void* address) { #if DEBUG_ARC >= 4 U_LOG("release %s [struct] (%d bytes)%s", type->FullName, type->ValueSize, uGetCaller().Ptr()); #endif for (size_t i = 0; i < type->Refs.StrongCount; i++) { uObject*& ptr = *(uObject**)((uint8_t*)address + type->Refs.Strong[i]); uRelease(ptr); ptr = NULL; } for (size_t i = 0; i < type->Refs.WeakCount; i++) uStoreWeak((uWeakObject**)((uint8_t*)address + type->Refs.Weak[i]), NULL); } void uAutoReleaseStruct(uType* type, void* address) { #if DEBUG_ARC >= 4 U_LOG("autorelease %s [struct] (%d bytes)%s", type->FullName, type->ValueSize, uGetCaller().Ptr()); #endif for (size_t i = 0; i < type->Refs.StrongCount; i++) uAutoRelease(*(uObject**)((uint8_t*)address + type->Refs.Strong[i])); } void uRetain(uObject* object) { if (object) { uBase::AtomicIncrement(&object->__retains); #if DEBUG_ARC >= 3 U_LOG("retain %s #%d (%d bytes, %d retains)%s", object->__type->FullName, object->__id, object->__size, object->__retains, uGetCaller().Ptr()); #endif } } void uRelease(uObject* object) { if (object) { if (uBase::AtomicDecrement(&object->__retains) == 0) { if (!uTryClearWeak(object)) return; #ifdef DEBUG_ARC uThreadData* thread = uGetThreadData(); if (thread->AutoReleasePtr >= thread->AutoReleaseStack) { uAutoReleaseFrame* frame = thread->AutoReleasePtr; if (frame->AllocCount > 0) { frame->FreeCount++; frame->FreeSize += object->__size; } } #endif uType* type = object->__type; switch (type->Type) { case uTypeTypeClass: { uType* baseType = type; do { if (baseType->fp_Finalize) { try { (*baseType->fp_Finalize)(object); } catch (...) { uLog(uLogLevelError, "Runtime Error: Unhandled exception in finalizer for %s", baseType->FullName); } } } while ((baseType = baseType->Base)); uReleaseStruct(type, object); break; } case uTypeTypeStruct: // This must be a boxed value, so append size of object header if (type->Flags & uTypeFlagsRetainStruct) uReleaseStruct(type, (uint8_t*)object + sizeof(uObject)); break; case uTypeTypeDelegate: uRelease(((uDelegate*)object)->_object); uRelease(((uDelegate*)object)->_prev); break; case uTypeTypeArray: { uArray* array = (uArray*)object; uArrayType* arrayType = (uArrayType*)type; uType* elmType = arrayType->ElementType; switch (elmType->Type) { case uTypeTypeClass: case uTypeTypeInterface: case uTypeTypeDelegate: case uTypeTypeArray: for (uObject** objAddr = (uObject**)array->_ptr; array->_length--; objAddr++) uRelease(*objAddr); break; case uTypeTypeStruct: if (elmType->Flags & uTypeFlagsRetainStruct) for (uint8_t* address = (uint8_t*)array->_ptr; array->_length--; address += elmType->ValueSize) uReleaseStruct(elmType, address); break; default: break; } break; } default: break; } if (object->__lockptr) uBase::DeleteMutex(object->__lockptr); if (object->__condptr) uBase::DeleteCond(object->__condptr); #if DEBUG_ARC >= 2 U_LOG("free %s #%d (%d bytes)%s", object->__type->FullName, object->__id, object->__size, uGetCaller().Ptr()); #endif #ifdef DEBUG_DUMPS uEnterCritical(); _HeapObjects->Remove(object); uExitCritical(); #endif U_ASSERT(object->__type != ::g::Uno::Type_typeof()); free(object); return; } if (object->__retains < 0) { #if DEBUG_ARC >= 4 U_LOG("*** BAD OBJECT: %s #%d (%d retains) ***%s", object->__type->FullName, object->__id, object->__retains, uGetCaller().Ptr()); #else U_LOG("*** BAD OBJECT: 0x%llx ***", (uintptr_t)object); #endif U_FATAL(); } else { #if DEBUG_ARC >= 3 U_LOG("release %s #%d (%d bytes, %d retains)%s", object->__type->FullName, object->__id, object->__size, object->__retains, uGetCaller().Ptr()); #endif } } } static void uAlignField(size_t& offset, size_t align) { U_ASSERT(align); size_t rem = offset % align; if (rem > 0) offset += align - rem; } void uBuildMemory(uType* type) { U_ASSERT(type); if (!type->IsClosed()) return; size_t strongCount = 0, weakCount = 0, objOffset = U_IS_OBJECT(type) ? sizeof(uObject) : 0, typeOffset = 0, align = 0; if (type->Base) type->Base->Build(); for (size_t i = 0; i < type->FieldCount; i++) { uFieldInfo& f = type->Fields[i]; U_ASSERT(f.Type); if (f.Type != type && !U_IS_OBJECT(f.Type)) f.Type->Build(); if ((f.Flags & uFieldFlagsStatic) == 0) { if (f.Type->Alignment > align) align = f.Type->Alignment; if ((f.Flags & uFieldFlagsConstrained) == 0) objOffset = f.Offset + f.Type->ValueSize; if (U_IS_VALUE(f.Type)) { strongCount += f.Type->Refs.StrongCount; weakCount += f.Type->Refs.WeakCount; } else if ((f.Flags & uFieldFlagsWeak) != 0) weakCount++; else strongCount++; } else if (type->GenericCount) { uAlignField(typeOffset, f.Type->Alignment); f.Offset = typeOffset; typeOffset += f.Type->ValueSize; } } size_t size = typeOffset + (strongCount + weakCount) * sizeof(size_t); uint8_t* ptr = (uint8_t*)malloc(size); // Leak memset(ptr, 0, size); type->Refs.Strong = (size_t*)ptr; ptr += strongCount * sizeof(size_t); type->Refs.Weak = (size_t*)ptr; ptr += weakCount * sizeof(size_t); for (size_t i = 0; i < type->FieldCount; i++) { uFieldInfo& f = type->Fields[i]; if ((f.Flags & uFieldFlagsStatic) == 0) { if ((f.Flags & uFieldFlagsConstrained) != 0) { uAlignField(objOffset, f.Type->Alignment); f.Flags &= ~uFieldFlagsConstrained; f.Offset = objOffset; objOffset += f.Type->ValueSize; } if (U_IS_VALUE(f.Type)) { f.Flags &= ~uFieldFlagsWeak; for (size_t j = 0; j < f.Type->Refs.StrongCount; j++) type->Refs.Strong[type->Refs.StrongCount++] = f.Type->Refs.Strong[j] + f.Offset; for (size_t j = 0; j < f.Type->Refs.WeakCount; j++) type->Refs.Weak[type->Refs.WeakCount++] = f.Type->Refs.Weak[j] + f.Offset; } else if ((f.Flags & uFieldFlagsWeak) != 0) type->Refs.Weak[type->Refs.WeakCount++] = f.Offset; else type->Refs.Strong[type->Refs.StrongCount++] = f.Offset; } else { if ((f.Flags & uFieldFlagsConstrained) != 0) f.Flags &= ~uFieldFlagsConstrained; if (type->GenericCount) f.Offset += (uintptr_t)ptr; } } if (U_IS_VALUE(type)) { if (align != 0) { U_ASSERT(type->Alignment == 0 || type->Alignment == align); type->Alignment = align; } if (objOffset != 0) { uAlignField(objOffset, type->Alignment); U_ASSERT(type->ValueSize == objOffset || type->ValueSize == 0); type->ValueSize = objOffset; } type->ObjectSize = sizeof(uObject) + type->ValueSize; } else { if (type->Base && type->Base->ObjectSize > objOffset) objOffset = type->Base->ObjectSize; if (objOffset > type->ObjectSize) type->ObjectSize = objOffset; } #ifdef DEBUG_UNSAFE uint8_t* layout = (uint8_t*)U_ALLOCA(type->ObjectSize); memset(layout, 0, type->ObjectSize); for (size_t i = 0; i < type->FieldCount; i++) { uFieldInfo& f = type->Fields[i]; if ((f.Flags & uFieldFlagsStatic) == 0) { for (size_t j = 0; j < f.Type->ValueSize; j++) { U_ASSERT(f.Offset + j < type->ObjectSize); layout[f.Offset + j]++; } } } // Verify that no fields are overlapping for (size_t i = 0; i < type->ObjectSize; i++) U_ASSERT(layout[i] < 2); #endif } void uWeakStateIntercept::SetCallback(uWeakObject* weak, uWeakStateIntercept::Callback cb) { if (!weak || !cb || weak->ZombieState != uWeakObject::Healthy) U_FATAL(); weak->ZombieState = uWeakObject::Infected; weak->ZombieStateIntercept = cb; } template<class RT, class T0> static RT uCallWithWeakRefLock(RT(*func)(T0), T0 t0) { uBase::MutexLock lock(_WeakMutex); return func(t0); } static bool uTryClearWeak_inner(uObject* object) { if (object->__retains != 0) return false; if (object->__weakptr->ZombieState == uWeakObject::Infected) { object->__weakptr->ZombieState = uWeakObject::Zombie; if (!object->__weakptr->ZombieStateIntercept(uWeakStateIntercept::OnRelease, object)) return false; } object->__weakptr->ZombieState = uWeakObject::Dead; object->__weakptr->Object = NULL; return true; } static bool uTryClearWeak(uObject* object) { if (!object->__weakptr) return true; if (!uCallWithWeakRefLock(&uTryClearWeak_inner, object)) return false; if (object->__weakptr) { if (uBase::AtomicDecrement(&object->__weakptr->RefCount) == 0) free(object->__weakptr); object->__weakptr = NULL; } return true; } static void uNewWeak(uObject* object) { if (object->__weakptr) return; uWeakObject* weak = (uWeakObject*)calloc(1, sizeof(uWeakObject)); weak->Object = object; weak->RefCount = 1; weak->ZombieState = uWeakObject::Healthy; weak->ZombieStateIntercept = 0; object->__weakptr = weak; } void uStoreWeak(uWeakObject** address, uObject* object) { if (*address && uBase::AtomicDecrement(&(*address)->RefCount) == 0) free(*address); if (!object) { *address = NULL; return; } if (!object->__weakptr) uCallWithWeakRefLock(&uNewWeak, object); uBase::AtomicIncrement(&object->__weakptr->RefCount); *address = object->__weakptr; } static uObject* uLoadWeak_inner(uWeakObject* weak) { if (weak->ZombieState == uWeakObject::Zombie) { if (!weak->ZombieStateIntercept(uWeakStateIntercept::OnLoad, weak->Object)) { weak->ZombieState = uWeakObject::Dead; weak->Object = NULL; return NULL; } weak->ZombieState = uWeakObject::Infected; } uRetain(weak->Object); return weak->Object; } uObject* uLoadWeak(uWeakObject* weak) { if (!weak) return NULL; uObject* object = uCallWithWeakRefLock(&uLoadWeak_inner, weak); uAutoRelease(object); return object; } static uObject* uInitObject(uType* type, void* ptr, size_t size) { U_ASSERT(type && type->ObjectSize && type->ValueSize && type->IsClosed() && !U_IS_ABSTRACT(type)); if (type->State < uTypeStateInitializing && strcmp(type->FullName, "Uno.String") != 0 && strcmp(type->FullName, "Uno.Type") != 0) type->Init(); uObject* object = (uObject*)ptr; object->__type = type; object->__retains = 1; #ifdef DEBUG_ARC object->__size = size; object->__id = type->Definition->ObjectCount++; #endif #if DEBUG_ARC >= 2 U_LOG("alloc %s #%d (%d bytes)%s", type->FullName, object->__id, size, uGetCaller().Ptr()); #endif #ifdef DEBUG_DUMPS uEnterCritical(); (*_HeapObjects)[object] = true; uExitCritical(); #endif uAutoRelease(object); return object; } uObject* uNew(uType* type) { U_ASSERT(type); size_t size = type->ObjectSize; U_ASSERT(size); return uInitObject(type, calloc(1, size), size); } uObject* uNew(uType* type, size_t size) { U_ASSERT(type && size); return uInitObject(type, calloc(1, size), size); } uString* uString::New(int length) { if (!length && ::g::Uno::String::Empty_) return ::g::Uno::String::Empty_; size_t size = sizeof(uString) + sizeof(uChar) * length + sizeof(uChar); uString* string = (uString*)uInitObject(::g::Uno::String_typeof(), calloc(1, size), size); string->_ptr = (uChar*)((uint8_t*)string + sizeof(uString)); string->_length = length; return string; } #ifdef DEBUG_DUMPS static void uDumpObject(FILE* fp, uObject* object, const char* label) { fprintf(fp, "\tobject_at_%p [label=\"%s refcount: %d\"]\n", object, label, object->__retains); } static void uDumpGlobalRef(FILE* fp, uObject** object, const char* label) { fprintf(fp, "\tglobal_ref_at_%p [label=\"%s\" color=\"blue\"]\n", object, label); if (*object) fprintf(fp, "\tglobal_ref_at_%p -> object_at_%p\n", object, *object); } static void uDumpStrongRef(FILE* fp, uObject* object, const char *label, uObject* target) { if (target) fprintf(fp, "\tobject_at_%p -> object_at_%p [label=\"%s\"]\n", object, target, label); } static void uDumpAllStrongRefs(FILE* fp, uObject* object, void* base, uType* type, const char *labelPrefix = "") { do { const uReflection& reflection = type->Reflection; for (size_t i = 0; i < reflection.FieldCount; i++) { uField* field = reflection.Fields[i]; const uFieldInfo& fieldInfo = field->Info(); if ((fieldInfo.Flags & (uFieldFlagsWeak | uFieldFlagsStatic)) != 0) continue; if (U_IS_OBJECT(fieldInfo.Type)) { uObject* target = *(uObject**)((char *)base + fieldInfo.Offset); if (target) { const char *fieldName = uAllocCStr(field->Name); char *label = new char[strlen(labelPrefix) + strlen(fieldName) + 1]; sprintf(label, "%s%s", labelPrefix, fieldName); uFreeCStr(fieldName); uDumpStrongRef(fp, object, label, target); delete[] label; } } else if (U_IS_VALUE(fieldInfo.Type)) { const char *fieldName = uAllocCStr(field->Name); char *newLabelPrefix = new char[strlen(labelPrefix) + strlen(fieldName) + 2]; sprintf(newLabelPrefix, "%s%s.", labelPrefix, fieldName); uFreeCStr(fieldName); void* target = (void*)((uint8_t*)base + fieldInfo.Offset); uDumpAllStrongRefs(fp, object, target, fieldInfo.Type, newLabelPrefix); delete[] newLabelPrefix; } } type = type->Base; } while (type); } static void uDumpObjectAndStrongRefs(FILE* fp, uObject* object) { uType* type = object->GetType(); // type-info is not "real" types that we care about in this respect if (type == ::g::Uno::Type_typeof()) return; uDumpObject(fp, object, type->FullName); switch (type->Type) { case uTypeTypeClass: uDumpAllStrongRefs(fp, object, object, type); break; case uTypeTypeEnum: break; case uTypeTypeStruct: { uint8_t* address = (uint8_t*)object + sizeof(uObject); uDumpAllStrongRefs(fp, object, address, type); break; } case uTypeTypeDelegate: { uDelegate* delegate = (uDelegate*)object; uDumpStrongRef(fp, object, "_object", delegate->_object); uDumpStrongRef(fp, object, "_prev", delegate->_prev); break; } case uTypeTypeArray: { uArray* array = (uArray*)object; uArrayType* arrayType = (uArrayType*)type; uType* elmType = arrayType->ElementType; switch (elmType->Type) { case uTypeTypeClass: case uTypeTypeInterface: case uTypeTypeDelegate: case uTypeTypeArray: for (int i = 0; i < array->Length(); ++i) { uObject* target = ((uObject**)array->Ptr())[i]; char label[20]; sprintf(label, "[%d]", i); uDumpStrongRef(fp, object, label, target); } break; case uTypeTypeEnum: break; case uTypeTypeStruct: for (int i = 0; i < array->Length(); ++i) { uint8_t* address = (uint8_t*)array->Ptr() + i * elmType->ValueSize; char labelPrefix[20]; sprintf(labelPrefix, "[%d].", i); uDumpAllStrongRefs(fp, object, address, elmType, labelPrefix); } break; default: U_FATAL(); } break; } default: U_FATAL(); } } static void uDumpStaticStrongRefs(FILE* fp, uType* type) { if (type == ::g::Uno::Type_typeof()) return; const uReflection& reflection = type->Reflection; const size_t fullNameLength = strlen(type->FullName); for (size_t i = 0; i < reflection.FieldCount; i++) { uField* field = reflection.Fields[i]; const uFieldInfo& fieldInfo = field->Info(); if (U_IS_OBJECT(fieldInfo.Type) && ((fieldInfo.Flags & uFieldFlagsWeak) == 0) && ((fieldInfo.Flags & uFieldFlagsStatic) != 0)) { uObject* target = field->GetValue(NULL); if (target) { const char *fieldName = uAllocCStr(field->Name); char *label = new char[fullNameLength + strlen(fieldName) + 2]; sprintf(label, "%s.%s", type->FullName, fieldName); uDumpGlobalRef(fp, (uObject**)fieldInfo.Address, label); uFreeCStr(fieldName); delete[] label; } } } } void uDumpAllStrongRefs(const char* path) { FILE* fp = fopen(path, "w"); if (!fp) return; fprintf(fp, "digraph object_dump {\n"); uEnterCritical(); for (int i = _HeapObjects->Begin(); i != _HeapObjects->End(); i = _HeapObjects->Next(i)) uDumpObjectAndStrongRefs(fp, _HeapObjects->GetKey(i)); uArray* allTypes = uReflection::GetTypes(); for (int i = 0; i < allTypes->_length; ++i) uDumpStaticStrongRefs(fp, allTypes->Unsafe<uType*>(i)); uExitCritical(); fprintf(fp, "}\n"); fclose(fp); } #endif // DEBUG_DUMPS
[ "shj4849@naver.com" ]
shj4849@naver.com
efb660d6ff1b7656c00b4ee232224592e229f1b1
e3583249f1275dce38966594eb0502d28f7d27bb
/cpp/thread_11/main.cpp
ffa69b10b951dfba62caf28595565685b22ab947
[]
no_license
evangelist64/litter
7ea5eb06e79e9f3ed77d973cb857af9cd119b2d4
1d9318d53538c2aa942dee90abaa484370279fb1
refs/heads/master
2022-06-08T12:57:42.203038
2020-05-06T08:09:38
2020-05-06T08:09:38
261,686,220
0
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
#include <iostream> #include <thread> #include <chrono> using namespace std; long int count = 0; void stack_alloc() { char msg[102400]; cout<<"count:"<<count<<endl; count++; this_thread::sleep_for(chrono::seconds(1)); stack_alloc(); } void my_fun() { while(1) { cout<<"fff"<<endl; this_thread::sleep_for(chrono::seconds(1)); } } int main() { // thread t1(my_fun); // t1.join(); // t1.detach(); thread t2(stack_alloc); while(1) { cout<<"ggg"<<endl; this_thread::sleep_for(chrono::seconds(1)); } return 0; }
[ "zhaoyinghao@dobest.com" ]
zhaoyinghao@dobest.com
3425a86944f99f6c2ad8aca90e4f2b655121f91f
88dd385fb4f24db9724a75343125e3d91df402f7
/geometry.cpp
833553a28d498751b37fab563a9ab71e401341e5
[]
no_license
Elainek1/ECE3574_Project3
36c906c965b1f2a9bc1e9c9662d3d24578fb73c7
93e306a36f39268da95666655c2264d1f75c337f
refs/heads/master
2020-12-30T12:24:11.128657
2017-05-03T05:01:48
2017-05-03T05:01:48
91,383,544
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
cpp
#include "geometry.hpp" #include <math.h> colorClass::colorClass() { } colorClass::~colorClass() { } colorClass::colorClass(int rIn, int gIn, int bIn) { r = rIn; g = gIn; b = bIn; } void colorClass::scaleBy(double scale) { r = r*scale; g = g*scale; b = b*scale; } point::point(double xIn, double yIn, double zIn) { x = xIn; y = yIn; z = zIn; objectIt = -1; } point::point() { objectIt = -1; } point::~point() { } double dot(point a, point b) { double value = (a.x * b.x) + (a.y * b.y) + (a.z * b.z); return value; } point normal(point center, point edge) { //point norm = point(b.x - a.x, b.y - a.y, b.z - a.z); //return point(norm.x / mag(norm), norm.y / mag(norm), norm.z / mag(norm)); return normalize(diff(center,edge)); } double mag(point a) { return sqrt(a.x*a.x + a.y*a.y + a.z*a.z); } point diff(point start, point end) { return point(end.x - start.x, end.y - start.y, end.z - start.z); } point normalize(point a) { return point(a.x/mag(a), a.y/mag(a), a.z/mag(a)); } camera::camera() { } camera::~camera() { }
[ "elainek1@vt.edu" ]
elainek1@vt.edu
eef39f0579e2bd0fd4a73f430394cef570b3e280
09ae7a1e40916e2b22c0704a2b64610c58e2389d
/lib/cxx/cxx/exception.cpp
1b15ad3469df198227b3a632fb02adbbfc131e54
[ "BSD-3-Clause", "NCSA", "MIT", "LicenseRef-scancode-dco-1.1", "LicenseRef-scancode-unknown-license-reference" ]
permissive
satnam6502/barrelfish
358338d2e0871d3b5e5c6ba88476cc0b1a4ffa31
2e415737c7ab3266107143879e2f45643a71366f
refs/heads/master
2020-06-10T23:23:33.357610
2019-06-25T22:39:38
2019-06-25T22:39:38
193,788,422
0
0
MIT
2019-06-25T21:54:30
2019-06-25T21:54:29
null
UTF-8
C++
false
false
6,786
cpp
//===------------------------ exception.cpp -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <stdlib.h> #include <stdio.h> #include "exception" #include "new" #ifndef __has_include #ifdef LIBCXXABI #define __has_include(inc) 1 #else #define __has_include(inc) 0 #endif #endif #ifdef __APPLE__ #include <cxxabi.h> using namespace __cxxabiv1; #define HAVE_DEPENDENT_EH_ABI 1 #ifndef _LIBCPPABI_VERSION using namespace __cxxabiapple; // On Darwin, there are two STL shared libraries and a lower level ABI // shared library. The globals holding the current terminate handler and // current unexpected handler are in the ABI library. #define __terminate_handler __cxxabiapple::__cxa_terminate_handler #define __unexpected_handler __cxxabiapple::__cxa_unexpected_handler #endif // _LIBCPPABI_VERSION #elif defined(LIBCXXRT) || __has_include(<cxxabi.h>) #include <cxxabi.h> using namespace __cxxabiv1; #if defined(LIBCXXRT) || defined(_LIBCPPABI_VERSION) #define HAVE_DEPENDENT_EH_ABI 1 #endif #elif !defined(__GLIBCXX__) // __has_include(<cxxabi.h>) static std::terminate_handler __terminate_handler; static std::unexpected_handler __unexpected_handler; #endif // __has_include(<cxxabi.h>) namespace std { #if !defined(LIBCXXRT) && !defined(__GLIBCXX__) && !defined(__EMSCRIPTEN__) bool uncaught_exception() _NOEXCEPT { #if defined(__APPLE__) || defined(_LIBCPPABI_VERSION) // on Darwin, there is a helper function so __cxa_get_globals is private return __cxa_uncaught_exception(); #else // __APPLE__ # if defined(_MSC_VER) && ! defined(__clang__) _LIBCPP_WARNING("uncaught_exception not yet implemented") # else # warning uncaught_exception not yet implemented # endif printf("uncaught_exception not yet implemented\n"); ::abort(); #endif // __APPLE__ } #ifndef _LIBCPPABI_VERSION exception::~exception() _NOEXCEPT { } const char* exception::what() const _NOEXCEPT { return "std::exception"; } #endif // _LIBCPPABI_VERSION #endif //LIBCXXRT #if !defined(_LIBCPPABI_VERSION) && !defined(__GLIBCXX__) bad_exception::~bad_exception() _NOEXCEPT { } const char* bad_exception::what() const _NOEXCEPT { return "std::bad_exception"; } #endif #if defined(__GLIBCXX__) // libsupc++ does not implement the dependent EH ABI and the functionality // it uses to implement std::exception_ptr (which it declares as an alias of // std::__exception_ptr::exception_ptr) is not directly exported to clients. So // we have little choice but to hijack std::__exception_ptr::exception_ptr's // (which fortunately has the same layout as our std::exception_ptr) copy // constructor, assignment operator and destructor (which are part of its // stable ABI), and its rethrow_exception(std::__exception_ptr::exception_ptr) // function. namespace __exception_ptr { struct exception_ptr { void* __ptr_; exception_ptr(const exception_ptr&) _NOEXCEPT; exception_ptr& operator=(const exception_ptr&) _NOEXCEPT; ~exception_ptr() _NOEXCEPT; }; } _LIBCPP_NORETURN void rethrow_exception(__exception_ptr::exception_ptr); #endif exception_ptr::~exception_ptr() _NOEXCEPT { #if HAVE_DEPENDENT_EH_ABI __cxa_decrement_exception_refcount(__ptr_); #elif defined(__GLIBCXX__) reinterpret_cast<__exception_ptr::exception_ptr*>(this)->~exception_ptr(); #else # if defined(_MSC_VER) && ! defined(__clang__) _LIBCPP_WARNING("exception_ptr not yet implemented") # else # warning exception_ptr not yet implemented # endif printf("exception_ptr not yet implemented\n"); ::abort(); #endif } exception_ptr::exception_ptr(const exception_ptr& other) _NOEXCEPT : __ptr_(other.__ptr_) { #if HAVE_DEPENDENT_EH_ABI __cxa_increment_exception_refcount(__ptr_); #elif defined(__GLIBCXX__) new (reinterpret_cast<void*>(this)) __exception_ptr::exception_ptr( reinterpret_cast<const __exception_ptr::exception_ptr&>(other)); #else # if defined(_MSC_VER) && ! defined(__clang__) _LIBCPP_WARNING("exception_ptr not yet implemented") # else # warning exception_ptr not yet implemented # endif printf("exception_ptr not yet implemented\n"); ::abort(); #endif } exception_ptr& exception_ptr::operator=(const exception_ptr& other) _NOEXCEPT { #if HAVE_DEPENDENT_EH_ABI if (__ptr_ != other.__ptr_) { __cxa_increment_exception_refcount(other.__ptr_); __cxa_decrement_exception_refcount(__ptr_); __ptr_ = other.__ptr_; } return *this; #elif defined(__GLIBCXX__) *reinterpret_cast<__exception_ptr::exception_ptr*>(this) = reinterpret_cast<const __exception_ptr::exception_ptr&>(other); return *this; #else # if defined(_MSC_VER) && ! defined(__clang__) _LIBCPP_WARNING("exception_ptr not yet implemented") # else # warning exception_ptr not yet implemented # endif printf("exception_ptr not yet implemented\n"); ::abort(); #endif } nested_exception::nested_exception() _NOEXCEPT : __ptr_(current_exception()) { } #if !defined(__GLIBCXX__) nested_exception::~nested_exception() _NOEXCEPT { } #endif _LIBCPP_NORETURN void nested_exception::rethrow_nested() const { if (__ptr_ == nullptr) terminate(); rethrow_exception(__ptr_); } #if !defined(__GLIBCXX__) exception_ptr current_exception() _NOEXCEPT { #if HAVE_DEPENDENT_EH_ABI // be nicer if there was a constructor that took a ptr, then // this whole function would be just: // return exception_ptr(__cxa_current_primary_exception()); exception_ptr ptr; ptr.__ptr_ = __cxa_current_primary_exception(); return ptr; #else # if defined(_MSC_VER) && ! defined(__clang__) _LIBCPP_WARNING( "exception_ptr not yet implemented" ) # else # warning exception_ptr not yet implemented # endif printf("exception_ptr not yet implemented\n"); ::abort(); #endif } #endif // !__GLIBCXX__ _LIBCPP_NORETURN void rethrow_exception(exception_ptr p) { #if HAVE_DEPENDENT_EH_ABI __cxa_rethrow_primary_exception(p.__ptr_); // if p.__ptr_ is NULL, above returns so we terminate terminate(); #elif defined(__GLIBCXX__) rethrow_exception(reinterpret_cast<__exception_ptr::exception_ptr&>(p)); #else # if defined(_MSC_VER) && ! defined(__clang__) _LIBCPP_WARNING("exception_ptr not yet implemented") # else # warning exception_ptr not yet implemented # endif printf("exception_ptr not yet implemented\n"); ::abort(); #endif } } // std
[ "stefan.kaestle@inf.ethz.ch" ]
stefan.kaestle@inf.ethz.ch
4679aa31bf69d2627fd451687389d6a22a3fd4c8
c8effd86fcef400d48ef420e1597a929078adde3
/C3DShellCodingTutorial (Qt)/C3DShellCodingTutorial/C3DShellCodingTutorial/res/texts/kernel/curve.h
2eee6c93852d73df250ca7b506a70bd584b1c8e5
[]
no_license
proxzi/Projects
60d7d7c4de8d3e377f4b01df679ef3fa7fe72098
09749cce546dba1122ff53c153d83be4bf7d5f9f
refs/heads/main
2023-02-25T05:32:53.442023
2021-02-08T23:24:37
2021-02-08T23:24:37
337,149,007
1
0
null
null
null
null
UTF-8
C++
false
false
126,183
h
//////////////////////////////////////////////////////////////////////////////// /** \file \brief \ru Кривая в двумерном пространстве. \en Curve in two-dimensional space. \~ \details \ru Двумерные кривые используются для описания области определения параметров поверхностей, построения трёхмерных кривых на поверхностях, кривых пересечения поверхностей, проекций трёхмерных кривых на поверхности и плоскости локальных систем координат. Двумерные кривые устроены аналогично трёхмерным кривым с той разницей, что вместо трёхмерных точек и векторов в двумерных кривых используются двумерные точки и векторы. \en Two-dimensional curves are used for description of surfaces parameters domain, calculation of three-dimensional curves on surfaces, surfaces intersection curves, projections, three-dimensional curves on surface and plane of local coordinate systems. Two-dimensional curves are organizes in the same way as three-dimensional curves with a difference that instead of three-dimensional points and vectors two-dimensional points and vectors are used in two-dimensional curves. \~ */ //////////////////////////////////////////////////////////////////////////////// #ifndef __CURVE_H #define __CURVE_H #include <plane_item.h> #include <mb_cart_point.h> #include <mb_rect1d.h> #include <mb_data.h> #include <templ_visitor.h> class MATH_CLASS MbPlacement; class MATH_CLASS MbNurbs; class MATH_CLASS MbLine; class MATH_CLASS MbContour; class MATH_CLASS MbPolygon; class MATH_CLASS MbCrossPoint; class MbCurveIntoNurbsInfo; struct MbNurbsParameters; class MATH_CLASS MbCurve; namespace c3d // namespace C3D { typedef SPtr<MbCurve> PlaneCurveSPtr; typedef SPtr<const MbCurve> ConstPlaneCurveSPtr; typedef std::vector<MbCurve *> PlaneCurvesVector; typedef std::vector<const MbCurve *> ConstPlaneCurvesVector; typedef std::vector<PlaneCurveSPtr> PlaneCurvesSPtrVector; typedef std::vector<ConstPlaneCurveSPtr> ConstPlaneCurvesSPtrVector; } //------------------------------------------------------------------------------ /** \brief \ru Кривая в двумерном пространстве. \en Curve in two-dimensional space. \~ \details \ru Кривая в двумерном пространстве представляет собой векторную функцию скалярного параметра, заданную на конечной одномерной области. Кривая представляет собой непрерывное отображение некоторого участка числовой оси в двумерное пространство.\n Двумерная кривая используется:\n для плоского моделирования,\n для описания области определения параметров поверхности,\n для построения кривых на поверхностях,\n для построения кривых пересечения поверхностей. \en A curve in two-dimensional space is a vector function of a scalar parameter, given on a finite one-dimensional space. A curve is continuous mapping of some piece of numeric axis to two-dimensional space.\n Two-dimensional curve is used:\n for planar modeling,\n for description of surface parameters domain,\n for construction of curves on surfaces,\n for constructing of surfaces intersection curves. \~ \ingroup Curves_2D */ // --- class MATH_CLASS MbCurve : public MbPlaneItem { protected: SimpleName name; ///< \ru Имя кривой. \en A curve name. protected : /// \ru Конструктор по умолчанию. \en Default constructor. MbCurve(); /// \ru Конструктор копирования. \en Copy-constructor. MbCurve( const MbCurve & other ) : MbPlaneItem(), name( other.name ) {} public : /// \ru Деструктор. \en Destructor. virtual ~MbCurve(); public : VISITING_CLASS( MbCurve ); // \ru Общие функции геометрического объекта. \en Common functions of a geometric object. virtual MbePlaneType IsA() const = 0; // \ru Тип элемента. \en A type of element. virtual MbePlaneType Type() const; // \ru Групповой тип элемента. \en Group element type. virtual MbePlaneType Family() const; // \ru Семейство объекта. \en Family of object. virtual MbPlaneItem & Duplicate( MbRegDuplicate * = NULL ) const = 0; // \ru Создать копию. \en Create a copy. virtual void Transform( const MbMatrix &, MbRegTransform * ireg = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Преобразовать согласно матрице. \en Transform according to the matrix. virtual void Move ( const MbVector &, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Сдвинуть вдоль вектора. \en Move along a vector. virtual void Rotate( const MbCartPoint & pnt, const MbDirection & angle, MbRegTransform * = NULL, const MbSurface * newSurface = NULL ) = 0; // \ru Поворот вокруг точки на угол. \en Rotation at angle around a point. virtual bool SetEqual( const MbPlaneItem & ) = 0; // \ru Сделать объект равным данному. \en Make an object equal to a given one. virtual bool IsSame( const MbPlaneItem & other, double accuracy = LENGTH_EPSILON ) const = 0; // \ru Является ли кривая curve копией данной кривой? \en Is a curve a copy of a given curve? virtual void Refresh(); // \ru Сбросить все временные данные. \en Reset all temporary data. /** \brief \ru Рассчитать временные (mutable) данные объекта. \en Calculate temporary (mutable) data of an object. \~ \details \ru Рассчитать временные данные объекта в зависимости от параметра forced. Если параметр forced равен false, рассчитываются только ещё не насчитанные данные. Если параметр forced равен true, перерасчитываются все временные данные объекта. \en Calculate the temporary data of an object depending of the "forced" parameter. Calculate only data that was not calculated earlier if parameter "forced" is equal false. Recalculate all temporary data of an object if parameter "forced" is equal true. \param[in] forced - \ru Принудительный перерасчёт. \en Forced recalculation. \~ */ virtual void PrepareIntegralData( const bool forced ) const; virtual void AddYourGabaritTo ( MbRect & ) const = 0; // \ru Добавить в прямоугольник свой габарит. \en Add a bounding box to rectangle. /** \ru \name Общие функции двумерного объекта. \en \name Common functions of two-dimensional object. \{ */ /** \brief \ru Добавить габарит в прямоугольник. \en Add a bounding box to rectangle. \~ \details \ru Добавить в прямоугольник свой габарит с учетом матрицы трансформации. Если матрица не единичная, то происходит трансформация копии объекта по матрице и затем к прямоугольнику добавляется габарит трансформированного объекта. После использования копия уничтожается. \en Add a bounding box to rectangle with taking into account of transformation matrix. If the transformation matrix is not an identity matrix then there is performed a transformation of object's copy by the matrix and after that a bounding box of the transformed object is added to rectangle. A copy is destroyed after using. \~ \param[out] rect - \ru Прямоугольник с информацией по габаритам. \en A rectangle with information about bounds. \~ \param[in] matr - \ru Матрица трансформации. \en Transformation matrix. \~ */ virtual void AddYourGabaritMtr( MbRect & rect, const MbMatrix & matr ) const; /** \brief \ru Определить габаритный прямоугольник кривой. \en Detect the bounding box of a curve. \~ \details \ru Для получения габарита объекта присланный прямоугольник делается пустым. Затем вычисляются габариты объекта и сохраняются в прямоугольнике rect. \en The sent rectangle becomes empty for getting a bounding box. Then bounding boxes of an object are calculated and saved into a rectangle 'rect'. \~ */ virtual void CalculateGabarit ( MbRect & ) const; /** \brief \ru Рассчитать габарит в локальной системы координат. \en Calculate bounding box in the local coordinate system. \~ \details \ru Для получения габарита объекта относительно локальной системы координат, присланный прямоугольник делается пустым. Затем вычисляются габариты объекта в локальной системе координат и сохраняются в прямоугольнике rect. \en For getting a bounding box of an object relatively to the local coordinate system, a sent rectangle becomes empty. After that bounding boxes of an object in the local coordinate system are calculated and saved in a rectangle 'rect'. \~ \param[in] matr - \ru Матрица перехода от текущей для объекта системы координат к локальной системе координат. \en A transition matrix from the current coordinate system of the object to the local coordinate system. \~ \param[out] rect - \ru Прямоугольник с информацией по габаритам. \en A rectangle with information about bounds. \~ */ virtual void CalculateLocalGabarit( const MbMatrix & into, MbRect & local ) const; /** \brief \ru Определить видимость объекта в прямоугольнике. \en Determine visibility of an object in rectangle. \~ \details \ru Определить, виден ли объект в заданном прямоугольнике. Есть возможность выполнить быструю проверку или более тщательную при соответствующем значении второго параметра. \en Determine whether an object is visible in the given rectangle. There is a possibility to perform a fast check or more thorough check when the second parameter has a corresponding value. \~ \param[in] rect - \ru Заданный двумерный прямоугольник. \en A given two-dimensional rectangle. \~ \param[in] exact - \ru Выполнять ли более тщательную проверку? \en Whether to perform a more thorough check. \~ \return \ru true - объект полностью или частично содержится в прямоугольнике, иначе - false. \en true, if the object is fully or partially contained in the rectangle, otherwise false. \~ */ virtual bool IsVisibleInRect ( const MbRect & rect, bool exact = false ) const; /** \brief \ru Определить, виден ли объект полностью в прямоугольнике. \en Determine whether an object is fully visible in rectangle. \~ \details \ru Объект полностью содержится в заданном прямоугольнике, если его габаритный прямоугольник вложен в заданный. \en An object is fully contained in the given rectangle if its bounding rectangle is included in the given rectangle. \~ \param[in] rect - \ru Прямоугольник, вложенность в который проверяется. \en Rectangle to check inclusion to. \~ \return \ru true - объект полностью содержится в прямоугольнике, иначе - false. \en true, if the object is fully contained in the rectangle, otherwise false. \~ */ virtual bool IsCompleteInRect( const MbRect & rect ) const; // \ru Определить расстояние до точки. \en Determine the distance to a point. virtual double DistanceToPoint( const MbCartPoint & toP ) const; // \ru Вычислить расстояние до точки, если оно меньше d. \en Calculate the distance to the point if it is less than d. virtual bool DistanceToPointIfLess( const MbCartPoint & toP, double & d ) const; /** \} */ /** \ru \name Функции описания области определения кривой. \en \name Functions for curve domain description. \{ */ /// \ru Получить максимальное значение параметра. \en Get the maximum value of parameter. virtual double GetTMax () const = 0; /// \ru Получить минимальное значение параметра. \en Get the minimum value of parameter. virtual double GetTMin () const = 0; /** \brief \ru Определить, является ли кривая замкнутой. \en Define whether the curve is closed. \~ \details \ru Определить, является ли кривая замкнутой.\n Замкнутой считается кривая, если она циклична:\n - начальная и конечная точка кривой совпадают,\n - производные в начальной и конечной точке совпадают; \n если по своей природе кривая допускает изломы (контур, ломаная), то допускается не совпадение производных; у кривой Безье производные должны совпадать по направлению, но могут не совпадать по модулю. \en Define whether the curve is closed.\n A curve is considered as closed if it is cyclic:\n - start point is coincident with end point,\n - derivatives in start point and end point coincide, \n if there are breaks at curve (in cases when a curve is contour or polyline), then derivatives may not coincide; in Bezier curve derivatives should coincide by direction, but they may differ by absolute value. \~ \return \ru true, если кривая замкнута. \en True if a curve is closed. \~ */ virtual bool IsClosed() const = 0; /** \brief \ru Вернуть период. \en Return period. \~ \details \ru Вернуть значение периода, если может быть кривая замкнута. Для незамкнутой кривой вернуть нуль. \en Return the period value if a curve can be closed. Let unclosed curve return null. \~ \return \ru Значение периода для замкнутой кривой или нуль - для незамкнутой. \en The value of period for a closed curve or null - for unclosed curve. \~ */ virtual double GetPeriod() const; /// \ru Определить, является ли замкнутая кривая периодической. \en Define whether the curve is periodic. virtual bool IsPeriodic() const; /** \brief \ru Определить, замкнута ли кривая фактически независимо от гладкости замыкания. \en Determine whether a curve is closed regardless of the smoothness of the closure. \~ \details \ru Определить, замкнута ли кривая фактически независимо от гладкости замыкания. \en Determine whether a curve is actually closed regardless of the smoothness of the closure. \~ */ bool IsTouch( double eps = Math::LengthEps ) const; /** \} */ /** \ru \name Функции для работы в области определения кривой. Функции PointOn, FirstDer, SecondDer, ThirdDer,... корректируют параметр при выходе его за пределы области определения. Исключение составляет MbLine (прямая). \en \name Functions for working in the curve's domain. Functions PointOn, FirstDer, SecondDer, ThirdDer,... correct parameter when it is out of domain bounds. The exception is MbLine (line). \{ */ /** \brief \ru Вычислить точку на кривой. \en Calculate a point on the curve. \~ \details \ru Скорректировать параметры при выходе их за пределы области определения и вычислить точку на кривой. \en Correct parameter when getting out of domain bounds and calculate a point on the curve. \~ \param[in] t - \ru Параметр curve. \en Curve parameter. \~ \param[out] p - \ru Вычисленная точка на кривой. \en A point on the curve. \~ \ingroup Curves_2D */ virtual void PointOn ( double & t, MbCartPoint & p ) const = 0; /// \ru Вычислить первую производную. \en Calculate first derivative. virtual void FirstDer ( double & t, MbVector & v ) const = 0; /// \ru Вычислить вторую производную. \en Calculate second derivative. virtual void SecondDer( double & t, MbVector & v ) const = 0; /// \ru Вычислить третью производную. \en Calculate third derivative. virtual void ThirdDer ( double & t, MbVector & v ) const = 0; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). void Tangent ( double & t, MbVector & v ) const; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). void Tangent ( double & t, MbDirection & d ) const; /// \ru Вычислить вектор главной нормали (нормализованный). \en Calculate main normal vector (normalized). void Normal ( double & t, MbVector & v ) const; /// \ru Вычислить вектор главной нормали (нормализованный). \en Calculate main normal vector (normalized). void Normal ( double & t, MbDirection & d ) const; /** \} */ /** \ru \name Функции для работы внутри и вне области определения кривой. Функции _PointOn, _FirstDer, _SecondDer, _ThirdDer,... не корректируют параметр при выходе за пределы области определения. При выходе за область определения незамкнутая кривая, в общем случае, продолжается по касательной, которую она имеет на соответствующем конце. Исключение составляют дуги эллипса и окружности - они продолжаются в соответствии со своими уравнениями. \en \name Functions for working inside and outside the curve's domain. Functions _PointOn, _FirstDer, _SecondDer, _ThirdDer,... do not correct parameter when it is out of domain bounds. When parameter is out of domain bounds, an unclosed curve is extended by tangent vector at corresponding end point in general case. The exceptions are arcs of ellipse and arcs of circle - they are extended according to their equations. \{ */ /** \brief \ru Вычислить точку на кривой и её продолжении. \en Calculate point at curve and its extension. \~ \details \ru Вычислить точку на кривой в том числе и за пределами области определения параметрa. \en Calculate a point on the curve including the outside area determination parameter. \~ \param[in] t - \ru Параметр curve. \en Curve parameter. \~ \param[out] p - \ru Вычисленная точка на кривой. \en A point on the curve. \~ \ingroup Curves_2D */ virtual void _PointOn ( double t, MbCartPoint & p ) const; /// \ru Вычислить первую производную на кривой и её продолжении. \en Calculate first derivative at curve and its extension. virtual void _FirstDer ( double t, MbVector & v ) const; /// \ru Вычислить вторую производную на кривой и её продолжении. \en Calculate second derivative at curve and its extension. virtual void _SecondDer( double t, MbVector & v ) const; /// \ru Вычислить третью производную на кривой и её продолжении. \en Calculate third derivative at curve and its extension. virtual void _ThirdDer ( double t, MbVector & v ) const; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). void _Tangent ( double t, MbVector & v ) const; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). void _Tangent ( double t, MbDirection & d ) const; /// \ru Вычислить вектор главной нормали (нормализованный) на кривой и её продолжении. \en Calculate main normal vector (normalized) at curve and its extension. void _Normal ( double t, MbVector & v ) const; /// \ru Вычислить вектор главной нормали (нормализованный) на кривой и её продолжении. \en Calculate main normal vector (normalized) at curve and its extension. void _Normal ( double t, MbDirection & d ) const; /** \brief \ru Вычислить значения точки и производных для заданного параметра. \en Calculate point and derivatives of object for given parameter. \~ \details \ru Значения точки и производных вычисляются в пределах области определения и на расширенной кривой. \en Values of point and derivatives are calculated on parameter area and on extended curve. \~ \param[in] t - \ru Параметр. \en Parameter. \~ \param[in] ext - \ru В пределах области определения (false), на расширенной кривой (true). \en On parameters area (false), on extended curve (true). \~ \param[out] pnt - \ru Точка. \en Point. \~ \param[out] fir - \ru Производная. \en Derivative with respect to t. \~ \param[out] sec - \ru Вторая производная по t, если не ноль. \en Second derivative with respect to t, if not NULL. \~ \param[out] thir - \ru Третья производная по t, если не ноль. \en Third derivative with respect to t, if not NULL. \~ \ingroup Curves_3D */ virtual void Explore( double & t, bool ext, MbCartPoint & pnt, MbVector & fir, MbVector * sec, MbVector * thir ) const; /** \} */ /** \ru \name Функции движения по кривой \en \name Function of moving by curve \{ */ /** \brief \ru Вычислить шаг параметра. \en Calculate parameter step. \~ \details \ru Вычислить шаг параметра для аппроксимации кривой по величине прогиба кривой. Вычисление шага проходит с учетом радиуса кривизны. Шаг аппроксимации кривой выбирается таким образом, чтобы отклонение кривой от её полигона не превышало заданную величину прогиба. \en Calculate parameter step for the curve's approximation by its sag value. Calculation of the step is performed with consideration of curvature radius. A step of curve's approximation is chosen in such way, that the deviation of a curve from its polygon does not exceed the given sag value. \~ \param[in] t - \ru Параметр, определяющий точку на кривой, в которой надо вычислить шаг. \en A parameter defining the point on a curve, at which a step should be calculated. \~ \param[in] sag - \ru Максимально допустимая величина прогиба. \en Maximum feasible sag value. \~ \return \ru Величина шага по параметру в заданной точке. \en A sag value by parameter at given point. \~ */ virtual double Step ( double t, double sag ) const; /** \brief \ru Вычислить шаг параметра. \en Calculate parameter step. \~ \details \ru Вычислить шаг параметра для аппроксимации кривой по углу отклонения касательной. Шаг аппроксимации кривой выбирается таким образом, чтобы угловое отклонение касательной кривой в следующей точке не превышало заданную величину ang. \en Calculate parameter step for the curve's approximation by the deviation angle of the tangent vector. A step of curve's approximation is chosen in such way, that angular deviation of the tangent curve at the next point does not exceed the given value ang. \~ \param[in] t - \ru Параметр, определяющий точку на кривой, в которой надо вычислить шаг. \en A parameter defining the point on a curve, at which a step should be calculated. \~ \param[in] ang - \ru Максимально допустимый угол отклонения касательной. \en The maximum feasible deviation angle of tangent. \~ \return \ru Величина шага по параметру в заданной точке. \en A sag value by parameter at given point. \~ */ virtual double DeviationStep( double t, double ang ) const; /** \} */ /** \ru \name Общие функции кривой \en \name Common function of curve. \{ */ /// \ru Вычислить кривизну кривой. \en Calculate curvature of curve. virtual double Curvature ( double t ) const; /// \ru Вычислить производную кривизны по параметру. \en Calculate derivative of curvature by parameter. double CurvatureDerive( double t ) const; /// \ru Вычислить радиус кривизны кривой со знаком. \en Calculate radius of curve with a sign. double CurvatureRadius( double t ) const; /** \brief \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. \~ \details \ru Вычислить метрическую длину кривой и записать ее в переменную length. \en Calculate the metric length of a curve and save the result in the variable 'length'. \~ \param[in, out] length - \ru Вычисленная длина кривой. \en Calculated length of a curve. \~ \return \ru true - если длина кривой отлична от нуля. Иначе возвращает false. \en True - if the length of a curve differs from null. Otherwise returns false. \~ */ virtual bool HasLength( double & length ) const = 0; /// \ru Определить, является ли кривая ограниченной. \en Define whether the curve is bounded. virtual bool IsBounded() const; /// \ru Определить, является ли кривая прямолинейной. \en Define whether the curve is rectilinear.. virtual bool IsStraight() const; /// \ru Определить, является ли кривая вырожденной. \en Define whether the curve is degenerate.. virtual bool IsDegenerate( double eps = Math::LengthEps ) const; /// \ru Определить, являются ли стыки контура/кривой гладкими. \en Define whether joints of contour/curve are smooth. virtual bool IsSmoothConnected( double angleEps ) const; /// \ru Вычислить параметрическую длину кривой. \en Calculate the parametric length of a curve. double GetParamLength() const { return GetTMax() - GetTMin(); } // \ru Функции с расчетом метрической длины перегружать все сразу, чтобы не было рассогласования. \en Functions with calculation of metric length, they should be overloaded simultaneously to avoid mismatches. /// \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. virtual double CalculateMetricLength() const; /** \brief \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. \~ \details \ru Вычислить метрическую длину разомкнутой кривой от параметра t1 до t2. Должно выполнятся условие t1 < t2. \en Calculate the metric length of unclosed curve from parameter t1 to parameter t2. The condition t1 < t2 should satisfied. \~ \param[in] t1 - \ru Начальный параметр отрезка кривой. \en Start parameter of a curve section. \~ \param[in] t2 - \ru Конечный параметр отрезка кривой. \en End parameter of a curve section. \~ \return \ru Длина кривой. \en Length of a curve. \~ */ virtual double CalculateLength( double t1, double t2 ) const; /** \brief \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. \~ \details \ru Если длина кривой уже была вычислена и запомнена в объекте, эта функция возвращает готовый результат, не выполняя повторных вычислений. Иначе длина вычисляется с помощью функции CalculateMetricLength(). \en If a length of a curve is already calculated and saved in the object then this function returns the existing result, without repeating of calculations. Otherwise the length is calculated by the function CalculateMetricLength(). \~ \return \ru Длина кривой. \en Length of a curve. \~ */ virtual double GetMetricLength() const = 0; /** \brief \ru Сдвинуть параметр вдоль кривой. \en Translate parameter along the curve. \~ \details \ru Сдвинуть параметр вдоль кривой на заданное расстояние в заданном направлении. Новое значение параметра сохраняется в переменной t. Если кривая не замкнута и длина ее части от точки с параметром t до конца в заданном направлении меньше, чем нужное смещение, то вычисления происходят на продолжении кривой, если можно построить продолжение. \en Translate parameter along the curve by the given distance at the given direction. The new value of parameter is saved in the variable t. If the curve is not closed and the length of its part from the point with parameter t to the end at the given direction is less than the required shift, then calculations are performed on extension of the curve, if it possible to construct such extension. \~ \param[in, out] t - \ru На входе - исходное значение параметра. На выходе - новое значение параметра. \en Input - the initial value of parameter. Output - the new value of parameter. \~ \param[in] len - \ru Величина смещения вдоль кривой. \en The value of shift along the curve. \~ \param[in] curveDir - \ru Направление смещения. Если curveDir - неотрицательно, то смещение направлено в сторону увеличения параметра. Иначе - в сторону уменьшения параметра. \en The offset direction. If curveDir is non-negative, then the shift is directed to the side of increasing of parameter. Otherwise - to the side of decreasing of parameter. \~ \param[in] eps - \ru Точность вычислений. \en Computational tolerance. \~ \param[in] version - \ru Версия. \en Version. \~ \return \ru true - если операция выполнена успешно, иначе false. \en True - if the operation is performed successfully, otherwise false. \~ */ virtual bool DistanceAlong( double & t, double len, int curveDir, double eps = Math::LengthEps, VERSION version = Math::DefaultMathVersion() ) const; /// \ru Сбросить текущее значение параметра. \en Reset the current value of parameter. virtual void ResetTCalc() const; /// \ru Изменить направления кривой на противоположное. \en Set the opposite direction of curve. virtual void Inverse( MbRegTransform * iReg = NULL ) = 0; /// \ru Построить эквидистантную кривую, смещённую на заданное расстояние. \en Construct the equidistant curve which is shifted by the given value. virtual MbCurve * Offset( double rad ) const; /** \brief \ru Начать аппроксимацию для отрисовки. \en Start approximation for the drawing. \~ \details \ru В функции проверяются и при необходимости корректируются параметры начала и конца аппроксимируемой части кривой. Вычисляется первая точка, соответствующая начальному параметру. Определяется, можно ли вычислить следующую точку. Следующие точки вычисляются функцией GetNextPoint. \en Parameters of start and end of approximated part of a curve are checked and corrected this is necessary. There is calculated a first point corresponding to start parameter. There is defined whether it is possible to calculate the next point. The next points are calculated by the function GetNextPoint. \~ \param[in] sag - \ru Максимальная величина прогиба. \en Maximal value of sag. \~ \param[in, out] tbeg - \ru Параметр, соответствующий началу аппроксимируемой части кривой. \en Parameter corresponding to start of approximated part of a curve. \~ \param[in, out] tend - \ru Параметр, соответствующий концу аппроксимируемой части кривой. \en Parameter corresponding to end of approximated part of a curve. \~ \param[in, out] pnt - \ru Вычисленная точка. \en A calculated point. \~ \param[in, out] existNextPoint - \ru Флаг, показывающий, надо ли вычислять следующую точку (true) или вычисленная точка соответствует концу аппроксимируемой кривой (false). \en Flag showing whether the next point should be calculated (true by default) or calculated point corresponds to the end of approximated curve. \~ \return \ru true - если операция выполнена успешно, иначе false. \en True - if the operation is performed successfully, otherwise false. \~ */ virtual bool BeginApprox ( double sag, double & tbeg, double & tend, MbCartPoint & pnt, bool & existNextPoint ) const; /** \brief \ru Вычислить очередную точку. \en Calculate the next point. \~ \details \ru Функция используется для расчета аппроксимации кривой, после вызова функции BeginApprox. В ней определяется параметр для вычисления следующей точки полигона, вычисляется точка и определяется, является ли она конечной. \en This function is used for the calculation of curve's approximation after call of the function BeginApprox. In this function a parameter for calculation of the next point of the polygon is defined, a point is calculated and there is defined whether it is an end point. \~ \param[in] sag - \ru Максимальная величина прогиба. \en Maximal value of sag. \~ \param[in] tend - \ru Параметр, соответствующий концу аппроксимируемой части кривой. \en Parameter corresponding to end of approximated part of a curve. \~ \param[in, out] tcur - \ru На входе - значение параметра в последней вычисленной точке. На выходе - параметр, соответствующий новой вычисленной точке. \en Input - the value of parameter at the last calculated point. Output - parameter corresponding to the new calculated point. \~ \param[in, out] pnt - \ru Вычисленная точка. \en A calculated point. \~ \return \ru true - если необходимы дальнейшие вычисления. false - если вычисленная точка соответствует концу аппроксимируемой кривой. \en True - if the further calculations are required. false - if the calculated point corresponds to the end of approximated curve. \~ */ virtual bool GetNextPoint ( double sag, double tend, double & tcur, MbCartPoint & pnt ) const; /** \brief \ru Рассчитать массив точек для отрисовки. \en Calculate an array of points for drawing. \~ \details \ru Выдать массив отрисовочных точек с заданной стрелкой прогиба. Если кривая представляет собой контур, то узловые точки контура дублируются. \en Get an array of drawn points with a given sag. If the cure is a contour then knots of a contour are duplicated. \~ \param[in] sag - \ru Максимальная величина прогиба. \en Maximal value of sag. \~ \param[in, out] poligon - \ru Полигон рассчитанных точек на кривой. \en A polygon of calculated points on a curve. \~ */ virtual void CalculatePolygon( double sag, MbPolygon & poligon ) const; /** \brief \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. \~ \details \ru Строит NURBS кривую, аппроксимирующую заданную. По возможности, строит точную кривую, возможно с кратными узлами. Количество узлов для NURBS определяется в зависимости от кривой. \en Constructs a NURBS copy which approximates a given curve. If it is possible, constructs the accurate curve, perhaps with multiple knots. The number of knots for NURBS is defined depending on the curve. \~ \param[in, out] nurbs - \ru Построенная NURBS кривая. \en A constructed NURBS-curve. \~ \param[in] nInfo - \ru Параметры преобразования кривой в NURBS. \en Parameters of conversion of a curve to NURBS. \~ \result \ru Построенная NURBS кривая или NULL при неуспешном построении. \en The constructed NURBS curve or NULL in a case of failure. \~ */ MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo * nInfo = NULL ) const; /** \brief \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. \~ \details \ru Строит NURBS кривую, аппроксимирующую заданную в диапазоне параметров [t1, t2] с заданным направлением. По возможности, строит точную кривую, возможно с кратными узлами. Количество узлов для NURBS определяется в зависимости от кривой. \en Constructs a NURBS curve which approximates a given curve inside the range [t1, t2]. with a given direction. If it is possible, constructs the accurate curve, perhaps with multiple knots. The number of knots for NURBS is defined depending on the curve. \~ \param[in, out] nurbs - \ru Построенная NURBS кривая. \en A constructed NURBS-curve. \~ \param[in] t1 - \ru Параметр, соответствующий началу аппроксимируемой части кривой. \en Parameter corresponding to start of approximated part of a curve. \~ \param[in] t2 - \ru Параметр, соответствующий концу аппроксимируемой части кривой. \en Parameter corresponding to end of approximated part of a curve. \~ \param[in] sense - \ru Совпадает ли направление возрастания параметра вдоль NURBS кривой с направлением на исходной кривой. sense > 0 - направление совпадает. \en Does the direction of parameter increasing along the NURBS curve coincide with direction of the initial curve. 'sense' > 0 - direction coincide. \~ \param[in] nInfo - \ru Параметры преобразования кривой в NURBS. \en Parameters of conversion of a curve to NURBS. \~ \result \ru Построенная NURBS кривая или NULL при неуспешном построении. \en The constructed NURBS curve or NULL in a case of failure. \~ */ virtual MbNurbs * NurbsCurve( const MbCurveIntoNurbsInfo & nInfo ) const = 0; /** \brief \ru Построить NURBS копию кривой. \en Construct a NURBS copy of a curve. \~ \details \ru Строит NURBS кривую, аппроксимирующую исходную с заданными параметрами. В параметрах можно задать степень и количество узлов сплайна, диапазон изменения параметра кривой. Если в параметрах не задан флаг точной аппроксимации, то строит NURBS без кратных узлов. \en Constructs a NURBS curve which approximates a given curve with the given parameters. In parameters the degree and the number of knots of a spline and the range of curve's parameters changing may be set. If the flag of accurate approximation is not set in parameters then NURBS without multiple knots is constructed. \~ \param[in] tParameters - \ru Параметры построения NURBS копии кривой. \en Parameters for the construction of a NURBS copy of the curve. \~ \result \ru Построенная NURBS кривая или NULL при неуспешном построении. \en The constructed NURBS curve or NULL in a case of failure. \~ */ virtual MbCurve * NurbsCurve( const MbNurbsParameters & tParameters ) const; /** \brief \ru Построить усеченную кривую. \en Construct a trimmed curve. \~ \details \ru Строит усеченную кривую, начало которой соответствует точке с параметром t1 и конец - точке с параметром t2. Можно изменить направление полученной кривой относительно исходной с помощью параметра sense. Если кривая замкнута, можно получить усеченную кривую, проходящую через начало кривой.\n В случае замкнутой кривой (или для дуги - исключение) три параметра sense, t1 и t2 однозначно определяют результат. В случае разомкнутой кривой параметр sense и параметрами усечения должны соответствовать друг другу:\n 1) если sense == 1, то t1 < t2,\n 2) если sense == -1, то t1 > t2.\n Если есть несоответствие между sense и параметрами усечения, то приоритетным параметром считается sense. Если параметры t1 и t2 равны и кривая замкнута, в результате должны получить замкнутую кривую. \en Constructs a trimmed curve, a start point of which corresponds to a point with parameter t1 and an end point corresponds to a point with parameter t2. Direction of the constructed curve relative to the initial curve may be changed by the parameter 'sense'. If the curve is closed, then there may be obtained a trimmed curve, passing through the start of a curve.\n In a case of closed curve (or for an arc - exception) three parameters 'sense', t1 and t2 clearly define the result. In a case of unclosed curve the parameter 'sense' and parameter of trimming should correspond each other:\n 1) if sense == 1, then t1 < t2,\n 2) if sense == -1, then t1 > t2,\n If there is a discrepancy between 'sense' and parameters of trimming, then 'sense' parameter has higher priority. If parameters t1 and t2 are equal and the curve is closed, then in result a closed curve should be obtained. \~ \param[in] t1 - \ru Параметр, соответствующий началу усеченной кривой. \en Parameter corresponding to start of a trimmed curve. \~ \param[in] t2 - \ru Параметр, соответствующий концу усеченной кривой. \en Parameter corresponding to end of a trimmed curve. \~ \param[in] sense - \ru Направление усеченной кривой относительно исходной.\n sense = 1 - направление кривой сохраняется. sense = -1 - направление кривой меняется на обратное. \en Direction of a trimmed curve in relation to an initial curve. sense = 1 - direction does not change. sense = -1 - direction changes to the opposite value. \~ \internal \ru При изменении поведения или документации метода переделать юнит-тестирование. \en When changing of the behavior or the documentation of the method being performed, the unit-testing should be redone. \~ \endinternal \result \ru Построенная усеченная кривая. \en A constructed trimmed curve. \~ */ virtual MbCurve * Trimmed( double t1, double t2, int sense ) const = 0; /// \ru Аппроксимировать кривую контуром из NURBS-кривых. \en Approximate of a curve by the contour from NURBS curves. virtual MbContour * NurbsContour() const; /** \brief \ru Деформировать кривую. \en Deform the curve. \~ \details \ru Если габаритный прямоугольник кривой пересекаться с заданным, то кривая трансформируется в соответствии с матрицей с помощью функции Transform. \en If the bounding rectangle of a curve intersects the given one, then the curve is transformed according to the matrix with a help of 'Transform' function. \~ \param[in] rect - \ru Прямоугольник, в котором проверяется видимость кривой. \en A rectangle, in which the visibility of a curve is checked. \~ \param[in] matr - \ru Матрица деформации. \en A deformation matrix. \~ \result \ru Состояние кривой после деформации. \en A state of a curve after deformation. \~ */ virtual MbeState Deformation( const MbRect & rect, const MbMatrix & matr ); /// \ru Определить видимость кривой в прямоугольнике. \en Determine visibility of a curve in rectangle. virtual bool IsInRectForDeform( const MbRect & ) const; /** \brief \ru Удалить часть кривой. \en Delete the piece of a curve. \~ \details \ru Удалить часть кривой между параметрами t1 и t2. Если после удаления кривая распалась на две части, то исходный объект соответствует начальной части кривой, а в параметре part2 содержится конечная часть кривой. Если осталась односвязной, то изменяется только исходный объект. \en Delete a part of a curve between parameters t1 and t2. If the curve is split into two parts after deletion, then the initial object corresponds to the start part of a curve, and parameter 'part2' contains the end part of a curve. If the curve remained simply connected, then only the initial object changes. \~ \param[in] t1 - \ru Начальный параметр усечения. \en Start parameter of trimming. \~ \param[in] t2 - \ru Конечный параметр усечения. \en End parameter of trimming. \~ \param[in, out] part2 - \ru Конечная часть кривой после удаления, если исходная кривая распалась на части. Может являться единственной частью кривой после удаления, \ если не смогли изменить саму кривую (например, для прямой MbLine), в этом случае возвращаемый результат dp_Degenerated. \en The end part of a curve after deletion, if an initial curve is split into parts. It may be the only part after deletions, \ if the curve did not change (e. g. for a curve of MbLine type), in this case the returned value is dp_Degenerated. \~ \result \ru Состояние кривой после модификации. \en A state of a curve after modification. \~ */ virtual MbeState DeletePart( double t1, double t2, MbCurve *& part2 ) = 0; /** \brief \ru Оставить часть кривой. \en Keep the piece of a curve. \~ \details \ru Оставить часть кривой между параметрами t1 и t2.\n В случае успеха операции возвращаемое значение равно dp_Changed и кривая удовлетворяет следующим условиям:\n - если исходная кривая замкнута, то начальная точка усеченной кривой должна соответствовать параметру t1, конечная - параметру t2, - если исходная кривая не замкнута, то начальная точка усеченной кривой должна соответствовать минимальному параметру из t1 и t2, конечная - максимальному. \en Leave a part of a curve between parameters t1 and t2.\n In a case of success the returned value equals dp_Changed and a curve satisfies to the next conditions:\n - if an initial curve is closed then the start point of a trimmed curve should correspond to the parameter t1, the end point - to the parameter t2, - if an initial curve is not closed then the start point of a trimmed curve should correspond to the minimum parameter from t1 and t2, the end point - to the maximum one. \~ \param[in] t1 - \ru Начальный параметр усечения. \en Start parameter of trimming. \~ \param[in] t2 - \ru Конечный параметр усечения. \en End parameter of trimming. \~ \param[in, out] part2 - \ru Может заполниться результатом усечения, если не смогли изменить саму кривую. В этом случае возвращаемый результат dp_Degenerated. Иначе = NULL. \en This may be filled by a result of trimming if the curve was not changed. In this case the returned value is dp_Degenerated. Otherwise NULL is returned. \~ \result \ru Состояние кривой после модификации:\n dp_Degenerated - кривая выродилась, может быть три варианта: кривая не была изменена, так как в результате преобразования она бы выродилась, или не была изменена, а результат усечения - part2,\n dp_NoChanged - кривая не изменилась,\n dp_Changed - кривая изменилась. \en A state of a curve after modification:\n dp_Degenerated - the curve is degenerated and there are possible three cases: the curve was not changed, because it would degenerate in a result of transformation, or it it was not changed and the result of trimming is 'part2',\n dp_NoChanged - the curve was not changes, \n dp_Changed - the curve is changed. \~ \warning \ru Функция предназначена для внутреннего использования. \en The function is designed for internal use only. \~ */ virtual MbeState TrimmPart ( double t1, double t2, MbCurve *& part2 ) = 0; /** \brief \ru Определить положение точки относительно кривой. \en Define the point position relative to the curve. \~ \details \ru Определяется, как расположена точка относительно кривой, если двигаться по кривой в положительном направлении. \en There is defined on which side from a curve the point is located, by the positive direction of a curve. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in] eps - \ru Точность определения. \en A tolerance of detection. \~ \result \ru iloc_InItem = 1 - если точка находится слева от кривой, \n iloc_OnItem = 0 - если точка находится на кривой, \n iloc_OutOfItem = -1 - если точка находится справа от кривой. \en Iloc_InItem = 1 - if the point is on the left from a curve, \n iloc_OnItem = 0 - if the point is on a curve, \n iloc_OutOfItem = 1 - if the point is on the right from a curve. \~ */ virtual MbeItemLocation PointRelative( const MbCartPoint & pnt, double eps = Math::LengthEps ) const; /// \ru Положение точки относительно кривой. \en The point position relative to the curve. virtual MbeLocation PointLocation( const MbCartPoint & pnt, double eps = Math::LengthEps ) const; /// \ru Найти проекцию точки на кривую. \en Find the point projection to the curve. virtual double PointProjection( const MbCartPoint & pnt ) const; /** \brief \ru Найти проекцию точки на кривую. \en Find the point projection to the curve. \~ \details \ru Найти проекцию точки на кривую или ее продолжение методом Ньютона по заданному начальному приближению. \en Find the point projection to the curve or its extension by the Newton method with the given initial approximation. \~ \param[in] p - \ru Заданная точка. \en A given point. \~ \param[in] xEpsilon - \ru Точность определения проекции по оси x. \en A tolerance of detection of the projection by x axis. \~ \param[in] yEpsilon - \ru Точность определения проекции по оси y. \en A tolerance of detection of the projection by y axis. \~ \param[in] iterLimit - \ru Максимальное количество итераций. \en The maximum number of iterations. \~ \param[in] t - \ru На входе - начальное приближение, на выходе - параметр кривой, соответствующий ближайшей проекции. \en Input - initial approximation, output - parameter of a curve, corresponding to the nearest projection. \~ \param[in] ext - \ru Флаг, определяющий, искать ли проекцию на продолжении кривой (если true, то искать). \en A flag defining whether to seek projection on the extension of the curve. \~ \result \ru Результат выполнения итерационного метода. \en The result of the iterative method. \~ */ MbeNewtonResult PointProjectionNewton( const MbCartPoint & p, double xEpsilon, double yEpsilon, size_t iterLimit, double & t, bool ext ) const; /** \brief \ru Найти проекцию точки на кривую. \en Find the point projection to the curve. \~ \details \ru Найти ближайшую проекцию точки на кривую или ее продолжение по заданному начальному приближению. Если задан диапазон изменения параметра tRange - то надо найти проекцию в заданном диапазоне. Диапазон параметра может выходить за область определения параметра кривой. Используется метод Ньютона. \en Find the nearest point projection to the curve or its by the given initial approximation. If the range of parameter changing 'tRange' is set, then find a projection in the given range. A range of parameter may not belong to the domain of a curve. The Newton method is used. \~ \note \ru Математическое ядро обеспечивает потокобезопасную реализацию функции для своих объектов. \en Mathematical kernel provides a thread-safe function implementation for its objects. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in] xEpsilon - \ru Точность определения проекции по оси x. \en A tolerance of detection of the projection by x axis. \~ \param[in] yEpsilon - \ru Точность определения проекции по оси y. \en A tolerance of detection of the projection by y axis. \~ \param[in,out] t - \ru На входе - начальное приближение, на выходе - параметр кривой, соответствующий ближайшей проекции. \en Input - initial approximation, output - parameter of a curve corresponding to the nearest projection. \~ \param[in] ext - \ru Флаг, определяющий, искать ли проекцию на продолжении кривой (если true, то искать). \en A flag defining whether to seek projection on the extension of the curve. \~ \param[in] tRange - \ru Диапазон изменения параметра, в котором надо найти решение. \en A range of parameter changing in which the solution should be found. \~ \result \ru true - если найдена проекция, удовлетворяющая всем входным условиям. \en True - if there is found a projection which satisfies to all input conditions. \~ */ virtual bool NearPointProjection( const MbCartPoint & pnt, double xEpsilon, double yEpsilon, double & t, bool ext, MbRect1D * tRange = NULL ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ \details \ru Вычислить точку на кривой, соответствующую проекции заданной точки на эту кривую. \en Calculate the point on the curve corresponding to the projection of the given point on this curve. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in, out] on - \ru Искомая точка - проекция. \en The required point - projection. \~ */ void PointProjection( const MbCartPoint & pnt, MbCartPoint & on ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ \details \ru Вычислить точку на кривой, соответствующую проекции заданной точки на эту кривую. Если кривая - усеченная, то вычисляется проекция на базовую кривую. \en Calculate the point on the curve corresponding to the projection of the given point on this curve. If a curve is trimmed then a projection to the base curve is calculated. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in, out] on - \ru Искомая точка - проекция. \en The required point - projection. \~ */ void BasePointProjection( const MbCartPoint & pnt, MbCartPoint & on ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ \details \ru Вычислить точку на кривой, соответствующую проекции заданной точки на эту кривую. Дополнительно возвращает угол наклона касательной к оси 0X в точке проекции. \en Calculate the point on the curve corresponding to the projection of the given point on this curve. Additionally returns an inclination angle of a tangent to the axis OX at the point of projection. \~ \param[in, out] on - \ru На входе - исходная точка. На выходе - точка-проекция на кривой. \en Input - an initial point. Output - a projection point on a curve. \~ \param[in, out] angle - \ru Вычисленный угол наклона касательной к оси 0X. \en A calculated inclination angle of a curve to the axis OX. \~ */ void PointProjectionAndAngle( MbCartPoint & on, double & angle ) const; /** \brief \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. \~ \details \ru Вычислить ближайшую точку пересечения кривой с лучом, выходящим из заданной точки pnt по направлению dir. Рассматриваются точки, лежащие за начальной точкой луча pnt на расстоянии, превосходящем Math::paramEpsilon. \en Calculate the nearest point of intersection between a curve and a ray from the given point 'pntp by the direction 'dir'. We consider the points lying over the starting point pnt beam at a distance exceeding Math :: paramEpsilon. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in] dir - \ru Заданное направление. \en A given direction. \~ \param[in, out] pp - \ru Искомая точка на кривой. \en Required point on the curve. \~ */ bool DirectPointProjection( const MbCartPoint & pnt, const MbDirection & dir, MbCartPoint & pp ) const; /** \brief \ru Найти ближайший перпендикуляр к кривой. \en Find the nearest perpendicular to the curve. \~ \details \ru Найти ближайший перпендикуляр к кривой, опущенный из заданной точки. В этой функции не рассматриваются перпендикуляры, опущенные на продолжение кривой. \en Find the nearest perpendicular to the curve from the given point. In this function perpendiculars to an extension of a curve are not considered. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in, out] tProj - \ru Параметр на кривой, соответствующий точке на кривой, через которую проходит перпендикуляр. \en Parameter on a curve, corresponding to the point on a curve, which the perpendicular is passed through. \~ \return \ru true, если искомый перпендикуляр построен. \en True if the required perpendicular is constructed. \~ */ virtual bool SmallestPerpendicular( const MbCartPoint & pnt, double & tProj ) const; /** \brief \ru Найти касательные к кривой. \en Find tangents to a curve. \~ \details \ru Найти все касательные к кривой, которые можно провести из заданной точки. Точка может лежать на кривой. В данной функции рассматривается кривая без продолжений. \en Find all tangents to a curve from the given point. A point may belong to a curve. In this function a curve without extensions is considered. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in, out] tFind - \ru Массив параметров кривой, соответствующих точкам касания. \en An array of parameters of a curve, corresponding to the tangent points. \~ */ virtual void TangentPoint( const MbCartPoint & pnt, SArray<double> & tFind ) const; /** \brief \ru Найти перпендикуляры к кривой. \en Find perpendiculars to a curve. \~ \details \ru Найти все перпендикуляры к кривой, которые можно провести из заданной точки. В данной функции рассматривается кривая без продолжений. \en Find all perpendiculars to a curve from the given point. In this function a curve without extensions is considered. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \param[in, out] tFind - \ru Массив параметров кривой, соответствующих точкам на кривой, через которые проходят перпендикуляры. \en An array of parameter on a curve, corresponding to the points on a curve, which the perpendiculars are passed through. \~ */ virtual void PerpendicularPoint( const MbCartPoint & pnt, SArray<double> & tFind ) const; /** \brief \ru Найти пересечения кривой с горизонтальной прямой. \en Find intersections of a curve with horizontal line. \~ \details \ru Найти пересечения кривой с горизонтальной прямой.\n \en Find intersections of a curve with horizontal line.\n \~ \param[in] y - \ru Ордината точек горизонтальной прямой. \en An ordinate of points of a horizontal line. \~ \param[in, out] cross - \ru Массив параметров кривой, соответствующих точкам пересечения. \en An array of parameters of a curve corresponding to the intersection points. \~ */ virtual void IntersectHorizontal( double y, SArray<double> & cross ) const; /** \brief \ru Найти пересечения кривой с вертикальной прямой. \en Find intersections of a curve with vertical line. \~ \details \ru Найти пересечения кривой с вертикальной прямой.\n \en Find intersections of a curve with vertical line.\n \~ \param[in] x - \ru Абсцисса точек вертикальной прямой. \en An abscissa of points of a vertical line. \~ \param[in, out] cross - \ru Массив параметров кривой, соответствующих точкам пересечения. \en An array of parameters of a curve corresponding to the intersection points. \~ */ virtual void IntersectVertical ( double x, SArray<double> & cross ) const; /** \brief \ru Построить изоклины. \en Construct isoclines. \~ \details \ru Построить прямые, проходящие под углом к оси 0X и касательные к кривой. \en Construct lines at an angle to the axis OX and tangent to the curve. \~ \param[in] angle - \ru Вектор, определяющий угол наклона прямой к оси OX. \en A vector defining an inclination angle of line to the axis OX. \~ \param[in, out] tFind - \ru Массив параметров кривой, соответствующих точкам касания. \en An array of parameters of a curve, corresponding to the tangent points. \~ */ virtual void Isoclinal( const MbVector & angle, SArray<double> & tFind ) const; /** \brief \ru Построить горизонтальные изоклины. \en Construct horizontal isoclines. \~ \details \ru Построить горизонтальные прямые, касательные к кривой. \en Construct horizontal lines tangent to the curve. \~ \param[in, out] tFind - \ru Массив параметров кривой, соответствующих точкам касания. \en An array of parameters of a curve, corresponding to the tangent points. \~ */ void HorzIsoclinal( SArray<double> & tFind ) const; /** \brief \ru Построить вертикальные изоклины. \en Construct vertical isoclines. \~ \details \ru Построить вертикальные прямые, касательные к кривой. \en Construct vertical lines tangent to the curve. \~ \param[in, out] tFind - \ru Массив параметров кривой, соответствующих точкам касания. \en An array of parameters of a curve, corresponding to the tangent points. \~ */ void VertIsoclinal( SArray<double> & tFind ) const; /// \ru Найти нижнюю точку кривой и соответствующий ей параметр. \en Find the lowest point of a curve and the corresponding parameter. void LowestPoint( MbCartPoint & lowestPoint, double & tLowest ) const; /** \brief \ru Найти самопересечения кривой. \en Find self-intersections of curve. \~ \details \ru Найти точки самопересечения кривой и соответствующие им параметры. \en Find the points of self-intersection of a curve and the corresponding parameters. \~ \param[in, out] crossPnt - \ru Массив точек самопересечения. \en An array of points of self-intersection. \~ */ virtual void SelfIntersect( SArray<MbCrossPoint> &, double metricEps = Math::LengthEps ) const; /** \brief \ru Найти особые точки эквидистантной кривой. \en Find the special points of an offset curve. \~ \details \ru Особыми точками эквидистантной кривой будем считать точки, в которых радиус кривизны исходной кривой равен величине смещения эквидистантной кривой. \en Special points of an offset curve are the points where the curvature radius of the initial curve equals to the value of shift of an offset curve. \~ \param[in, out] tCusps - \ru Массив параметров особых точек. \en An array of parameters of special points. \~ \param[in] dist - \ru Смещение эквидистантной кривой. \en Shift of the offset curve. \~ */ virtual void OffsetCuspPoint( SArray<double> & tCusps, double dist ) const; /** \brief \ru Провести кривую через точку. \en Create a curve through a point. \~ \details \ru Изменить кривую так, чтобы она проходила через заданную точку. Изменения не должны затрагивать всю кривую. Если у кривой присутствуют какие-либо базовые объекты, связь с ними не должна потеряться при модификации. Если построить искомую кривую невозможно, исходная кривая не изменяется, возвращается false. \en Change a curve such that it passes through the given point. Changes should not affect the whole curve. If the curve has any base objects, then the connection with them should not be modified. If the curve cannot be constructed, then the initial curve will not change, false is returned. \~ \param[in] pnt - \ru Заданная точка. \en A given point. \~ \return \ru true, если модификация выполнена, иначе - false. \en True - if the modification is performed, otherwise - false. \~ */ virtual bool GoThroughPoint( MbCartPoint & pnt ); /// \ru Вычислить среднюю точку кривой. \en Calculate a middle point of a curve. virtual bool GetMiddlePoint( MbCartPoint & ) const; /// \ru Вычислить начальную точку кривой. \en Calculate a start point of a curve. virtual void GetStartPoint ( MbCartPoint & ) const; /// \ru Вычислить конечную точку кривой. \en Calculate an end point of a curve. virtual void GetEndPoint ( MbCartPoint & ) const; /// \ru Вычислить центр кривой. \en Calculate a center of curve. virtual bool GetCentre ( MbCartPoint & ) const; /** \brief \ru Дать физический радиус скривой или ноль, если это невозможно. \en Get the physical radius of the curve or null if it impossible. \~ \details \ru В общем случае на запрос радиуса возвращается 0. Число, отличное от 0, можно получить лишь в том случае, если кривая является дугой окружности или эквивалентна дуге окружности. \en In general case 0 is returned. A value different from 0 may be obtained only in a case, when the curve is an arc of a circle or it is equivalent to an arc of a circle. \~ \return \ru Значение радиуса, если есть, или 0.0. \en A value of radius, if it is existed, or 0.0. \~ */ virtual double GetRadius () const; /** \brief \ru Вычислить точку для построения оси. \en Calculate a point to construct an axis. \~ \details \ru Вычисляет точку для построения оси, если кривая может быть построена вращением точки вокруг некоторой оси. \en Calculates a point to construct an axis, if a curve may be constructed by rotation of a point around an axis. \~ \return \ru true, если такая ось существует. \en true, if such axis exists. \~ */ virtual bool GetAxisPoint( MbCartPoint & p ) const; /// \ru Определить, подобны ли кривые для объединения (слива). \en Define whether the curves are similar for the merge. virtual bool IsSimilarToCurve( const MbCurve & curve, double precision = PARAM_PRECISION ) const; /// \ru Определить количество разбиений для прохода в операциях. \en Define the number of splittings for one passage in operations. virtual size_t GetCount() const; /// \ru Выдать n точек кривой с равными интервалами по параметру. \en Get n points of a curve with equal intervals by parameter. void GetPointsByEvenParamDelta ( size_t n, std::vector<MbCartPoint> & pnts ) const; void GetPointsByEvenParamDelta ( size_t n, SArray<MbCartPoint> & pnts ) const; // Deprecated. /// \ru Выдать n точек кривой с равными интервалами по длине дуги. \en Get n points of a curve with equal intervals by arc length. virtual void GetPointsByEvenLengthDelta( size_t n, std::vector<MbCartPoint> & pnts ) const; void GetPointsByEvenLengthDelta( size_t n, SArray<MbCartPoint> & pnts ) const; // Deprecated. /** \brief \ru Вычислить минимальную длину кривой между двумя точками на ней. \en Calculate minimal length of a curve between two points on it. \~ \details \ru Если кривая не замкнутая, то длина кривой между точками определяется однозначно. Если кривая замкнута, то из двух возможных путей выбирается самый короткий. Для замкнутой кривой можно определить желаемую часть с помощью задания контрольной точки pc. Тогда выбирается та часть кривой, к которой ближе находится контрольная точка. \en If a curve is not closed, then the length between points is clearly defined. If a curve is closed, then there is chosen the shortest path from the two possible paths. For a closed curve the desired part may be defined by the control points pc. In this case the such part of a curve is chosen, which is closer to a control point. \~ \param[in] p1 - \ru Первая точка. \en The first point. \~ \param[in] p2 - \ru Вторая точка. \en The second point \~ \param[in] pc - \ru Контрольная точка. \en A control point \~ \return \ru Длина части кривой между точками. \en A length of a curve between points. \~ */ virtual double LengthBetween2Points( MbCartPoint & p1, MbCartPoint & p2, MbCartPoint * pc = NULL ) const; /// \ru Вычислить центр тяжести кривой. \en Calculate the center of gravity of a curve. virtual bool GetWeightCentre ( MbCartPoint & ) const; /// \ru Проверить лежит ли точка на кривой с точностью eps. \en Check whether the point is on a curve with the tolerance eps. bool IsPointOn( const MbCartPoint &, double eps = Math::LengthEps ) const; /// \ru Проверить лежит ли параметр в диапазоне кривой с точностью eps. \en Check whether the parameter is inside a range with the tolerance eps. bool IsParamOn( double t, double eps = Math::paramEpsilon ) const; /** \brief \ru Корректировать параметр для замкнутых кривых. \en Correct parameter for closed curves. \~ \details \ru Если кривая замкнута, то функция загоняет параметр t в диапазон параметров кривой. Кроме того, если параметр t отличается от одного из граничных параметров меньше, чем на eps, он делается равным граничному параметру. \en If the curve is closed, then the function sets the parameter t to the range of the curve. Besides, if t differs from one of bounding parameters by a value which is less than eps, then it becomes equal to the bounding parameter. \~ \param[in, out] t - \ru На входе - заданное значение параметра, на выходе - скорректированное. \en Input - given value of parameter, output - corrected value of parameter. \~ \param[in] eps - \ru Точность попадания на край диапазона. \en A tolerance of getting to the bound of the range. \~ */ void CorrectCyclicParameter( double & t, double eps = Math::paramRegion ) const; /** \brief \ru Корректировать параметр. \en Correct parameter. \~ \details \ru Функция загоняет параметр t в диапазон параметров кривой. \en The function sets the parameter t to the range of the curve. \~ \param[in, out] t - \ru На входе - заданное значение параметра, на выходе - скорректированное. \en Input - given value of parameter, output - corrected value of parameter. \~ */ void CorrectParameter ( double & t ) const; /// \ru Сделать копию с измененным направлением. \en Create a copy with changed direction. MbCurve * InverseDuplicate() const; /// \ru Определить, являются ли кривая инверсно такой же. \en Define whether an inversed curve is the same. bool IsInverseSame( const MbCurve & curve, double accuracy = LENGTH_EPSILON ) const; /** \brief \ru Определить, является ли кривая репараметризованно такой же. \en Define whether a reparameterized curve is the same. \~ \details \ru Определить, является ли кривая репараметризованно такой же. \en Define whether a reparameterized curve is the same. \~ \param[in] curve - \ru Кривая для сравнения. \en A curve for comparison. \~ \param[out] factor - \ru Коэффициент сжатия параметрической области при переходе к указанной кривой. \en Coefficient of compression of parametric region at the time of transition to the pointed curve. \~ */ virtual bool IsReparamSame( const MbCurve & curve, double & factor ) const; /** \brief \ru Вычислить граничную точку. \en Calculate the boundary point. \~ \details \ru Вычислить граничную точку. \n \en Calculate the boundary point. \n \~ \param[in] number - \ru Номер граничной точки. Значение 1 соответствует начальной точке кривой, 2 - конечной. \en A number of a boundary point. The value 1 corresponds to the start point of a curve, 2 - to the end point. \~ \return \ru Вычисленная точка. \en A calculated point. \~ */ MbCartPoint GetLimitPoint( ptrdiff_t number ) const; /** \brief \ru Вычислить граничную точку. \en Calculate the boundary point. \~ \details \ru Вычислить граничную точку. \n \en Calculate the boundary point. \n \~ \param[in] number - \ru Номер граничной точки. Значение 1 соответствует начальной точке кривой, 2 - конечной. \en A number of a boundary point. The value 1 corresponds to the start point of a curve, 2 - to the end point. \~ \param[in, out] pnt - \ru Вычисленная точка. \en A calculated point. \~ */ void GetLimitPoint( ptrdiff_t number, MbCartPoint & pnt ) const; /** \brief \ru Вычислить касательный вектор в граничной точке. \en Calculate a tangent vector to the boundary point. \~ \details \ru Вычислить нормализованный касательный вектор в граничной точке. \en Calculate a normalized tangent vector to the boundary point. \~ \param[in] number - \ru Номер граничной точки. Значение 1 соответствует начальной точке кривой, 2 - конечной. \en A number of a boundary point. The value 1 corresponds to the start point of a curve, 2 - to the end point. \~ \param[in, out] v - \ru Касательный вектор. \en Tangent vector \~ */ void GetLimitTangent( ptrdiff_t number, MbVector & v ) const; /** \brief \ru Вычислить касательный вектор и точку на конце кривой. \en Calculate a tangent vector and point at the end of a curve. \~ \details \ru Вычислить нормализованный касательный вектор и точку на конце кривой. \en Calculate a normalized tangent vector and point at the end of a curve. \~ \param[in] number - \ru Номер граничной точки. Значение 1 соответствует начальной точке кривой, 2 - конечной. \en A number of a boundary point. The value 1 corresponds to the start point of a curve, 2 - to the end point. \~ \param[in, out] pnt - \ru Вычисленная точка. \en A calculated point. \~ \param[in, out] v - \ru Касательный вектор. \en Tangent vector \~ */ void GetLimitPointAndTangent( ptrdiff_t number, MbCartPoint & pnt, MbVector & v ) const; /** \brief \ru Равны ли граничные точки? \en Are boundary points equal? \~ \details \ru Равны ли граничные точки кривой? \en Are curve boundary points equal? \~ \return \ru true, если точки равны. \en Returns true if points are equal. \~ */ bool AreLimitPointsEqual() const { return GetLimitPoint( 1 ) == GetLimitPoint( 2 ); } /** \brief \ru Вернуть характерную точку кривой. \en Return a specific point of a curve. \~ \details \ru Вернуть характерную точку кривой, если расстояние от нее до заданной точки from меньше, чем dmax. Характерными точками ограниченной кривой являются начальная точка и конечная точка. \en Return a specific point of a curve if the distance from it to the given point is less than dmax. Specific points of a bounded curve are its start and end points. \~ \param[in] from - \ru Контрольная точка. \en A control point \~ \param[in, out] dmax - \ru На входе - максимальное расстояние для поиска характерной точки. На выходе - расстояние от точки from до найденной характерной точки. \en Input - maximum distance for search of specific point. Output - a distance from the point 'from' to the found specific point. \~ \param[in, out] pnt - \ru Касательный вектор. \en Tangent vector. \~ \result \ru true - если характерная точка найдена. \en True - if the specific point is found. \~ */ virtual bool GetSpecificPoint( const MbCartPoint & from, double & dmax, MbCartPoint & pnt ) const; /// \ru Вернуть базовую кривую, если есть, или себя. \en Returns the base curve if exists or itself. virtual const MbCurve & GetBasisCurve() const; /// \ru Вернуть базовую кривую, если есть, или себя. \en Returns the base curve if exists or itself. virtual MbCurve & SetBasisCurve(); /// \ru Вернуть отступ по параметру кривой. \en Return an indent by parameter of a curve. virtual double GetParamDelta() const; // \ru Геометрия подложки тождественна геометрии кривой, отлична параметризация. \en The geometry of the a substrate is identical to the geometry of a curve, a parameterization differs. /// \ru Выдать подложку или себя. \en Get a substrate or itself. virtual const MbCurve & GetSubstrate() const; /// \ru Выдать подложку или себя. \en Get a substrate or itself. virtual MbCurve & SetSubstrate(); /// \ru Вернуть направление подложки относительно кривой или наоборот. \en Return direction of a substrate relative to a curve or vice versa. virtual int SubstrateCurveDirection() const; /// \ru Преобразовать параметр подложки в параметр кривой. \en Transform a substrate parameter to the curve parameter. virtual void SubstrateToCurve( double & ) const; /// \ru Преобразовать параметр кривой в параметр подложки. \en Transform a curve parameter to the substrate parameter. virtual void CurveToSubstrate( double & ) const; /** \brief \ru Вычислить метрическую длину кривой. \en Calculate the metric length of a curve. \~ \details \ru Длина кривой вычисляется неточно, на основе аппроксимации ломаной. Если нужна более точно вычисленная длина кривой, надо пользоваться функцией CalculateMetricLength(). \en The length of a curve is inaccurately calculated, by approximation of polyline. If the more accurate curve's length is required, then use the function CalculateMetricLength(). \~ */ virtual double GetLengthEvaluation() const; /// \ru Вернуть приращение параметра, соответствующее единичной длине в пространстве. \en Return increment of parameter, corresponding to the unit length in space. virtual double GetParamToUnit() const; /// \ru Вернуть приращение параметра, соответствующее единичной длине в пространстве в зависимости от параметра. \en Return increment of parameter, corresponding to the unit length in space according to parameter. virtual double GetParamToUnit( double t ) const; /// \ru Вернуть минимально различимую величину параметра с заданной точностью. \en Return the minimal discernible value of parameter with the given tolerance. virtual double GetTEpsilon( double epsilon ) const; /// \ru Вернуть минимально различимую величину параметра с заданной точностью в зависимости от параметра. \en Return the minimal discernible value of parameter with the given tolerance according to parameter. virtual double GetTEpsilon( double t, double epsilon ) const; /// \ru Вернуть минимально различимую величину параметра с заданной точностью. \en Return the minimal discernible value of parameter with the given tolerance. virtual double GetTRegion ( double epsilon ) const; /// \ru Вернуть минимально различимую величину параметра с заданной точностью в зависимости от параметра. \en Return the minimal discernible value of parameter with the given tolerance according to parameter. virtual double GetTRegion ( double t, double epsilon ) const; /// \ru Вернуть середину параметрического диапазона кривой. \en Return the middle of parametric range of a curve. double GetTMid() const { return ((GetTMin() + GetTMax()) * 0.5); } /// \ru Вернуть параметрическую длину кривой. \en Return the parametric length of a curve. double GetTRange() const { return (GetTMax() - GetTMin()); } /// \ru Вычислить точку на кривой. \en Calculate point on the curve. MbCartPoint PointOn ( double & t ) const; /// \ru Вычислить первую производную. \en Calculate first derivative. MbVector FirstDer ( double & t ) const; /// \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). MbDirection Tangent ( double & t ) const; /// \ru Вычислить нормальный вектор. \en Calculate the normal vector. MbDirection Normal ( double & t ) const; /// \ru Вычислить длину вектора производной. \en Calculate the length of derivative vector. double DerLength( double & t ) const; /** \brief \ru Получить границы участков кривой, на которых сохраняется непрерывность кривизны. \en Get the boundaries of the sections of the curve on which the continuity of curvature is preserved. \~ \details \ru Получить границы участков кривой, на которых сохраняется непрерывность кривизны. \n Функция введена для оптимизации реализации функции MbCurve3D::GetCurvatureSpecialPoints, чтобы не насчитывать точки разрыва. \n \en Get the boundaries of the sections of the curve on which the continuity of curvature is preserved. \n The function was introduced to optimize the implementation of the function MbCurve3D :: GetCurvatureSpecialPoints, so as not to calculate the break points.\n \~ \param[out] params - \ru Точки, в которых кривизна имеет разрыв. \en The points at which the curvature has a discontinuity. \~ */ virtual void GetCurvatureContinuityBounds( std::vector<double> & params ) const; /// \ru Создать собственное свойство. \en Create a custom property. virtual MbProperty& CreateProperty( MbePrompt name ) const; /// \ru Выдать свойства объекта. \en Get properties of the object. virtual void GetProperties( MbProperties & properties ) = 0; /// \ru Записать свойства объекта. \en Set properties of the object. virtual void SetProperties( const MbProperties & properties ) = 0; /// \ru Выдать базовые точки кривой. \en Get the basis points of the curve. virtual void GetBasisPoints( MbControlData & ) const = 0; // \ru Выдать контрольные точки объекта. \en Get control points of object. virtual void SetBasisPoints( const MbControlData & ) = 0; // \ru Изменить объект по контрольным точкам. \en Change the object by control points. /** \brief \ru Непрерывна ли первая производная кривой по длине и направлению? \en Have the first derivative of the curve the continuous length and direction? \details \ru Отсутствуют ли разрывы первой производной кривой по длине и направлению? \n \en Are absent any discontinuities at length or at direction of first derivative of the curve? \n \~ \param[out] contLength - \ru Непрерывность длины (да/нет). \en The length is continuous (true/false). \~ \param[out] contDirect - \ru Непрерывность направления (да/нет). \en The direction of the first derivative is continuous (true/false). \~ \param[out] params - \ru Параметры точек, в которых происходит разрыв направления. \en The parameters of the points at which the direction break occurs. \~ \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ */ virtual bool IsContinuousDerivative( bool & contLength, bool & contDirect, c3d::DoubleVector * params = NULL, double epsilon = EPSILON ) const; /** \brief \ru Устранить разрывы первых производных по длине. \en Eliminate the discontinuities of the first derivative at length. \details \ru Устранить разрывы производных по длине. \n \en Eliminate the discontinuities of the first derivatives of the length. \n \~ \param[in] epsilon - \ru Погрешность вычисления. \en The accuracy of the calculation. \~ */ virtual bool SetContinuousDerivativeLength( double epsilon = EPSILON ); /** \brief \ru Определить, близки ли две кривые метрически. \en Check whether the two curves are metrically close. \~ \details \ru Близость кривых определяется, исходя из равенства их конечных точек и расстояния произвольной точки одной кривой от другой кривой. Параметрически кривые могут отличаться. \en The proximity of curves is defined by equality of their ends and the distance of an arbitrary point of one curve to another curve. Curves may differ parametrically. \~ \param[in] curve - \ru Кривая, с которой производится сравнение. \en A curve to compare with. \~ \param[in] eps - \ru Максимально допустимое расстояние между ближайшими точками двух кривых. \en The maximum allowed distance between the nearest points of two curves. \~ \param[in] ext - \ru Флаг определяет, будет ли при необходимости продолжена кривая curve. Если ext = true, то кривая может быть продолжена. \en A flag defines whether the curve 'curve' may be extended when necessary. If ext = true then the curve may be extended. \~ \param[in] devSag - \ru Максимальная величина прогиба. \en Maximal value of sag. \~ */ bool IsSpaceNear( const MbCurve & curve, double eps, bool ext, double devSag = 5.0*Math::deviateSag ) const; /** \brief \ru Определить, близки ли две кривые метрически. \en Check whether the two curves are metrically close. \~ \details \ru Близость кривых определяется, исходя из равенства их конечных точек и расстояния произвольной точки одной кривой от другой кривой. Параметрически кривые могут отличаться. \en The proximity of curves is defined by equality of their ends and the distance of an arbitrary point of one curve to another curve. Curves may differ parametrically. \~ \param[in] curve - \ru Кривая, с которой производится сравнение. \en A curve to compare with. \~ \param[in] xEps - \ru Точность определения проекции по оси x. \en A tolerance of detection of the projection by x axis. \~ \param[in] yEps - \ru Точность определения проекции по оси y. \en A tolerance of detection of the projection by y axis. \~ \param[in] ext - \ru Флаг определяет, будет ли при необходимости продолжена кривая curve. Если ext = true, то кривая может быть продолжена. \en A flag defines whether the curve 'curve' may be extended when necessary. If ext = true then the curve may be extended. \~ \param[in] xNear - \ru Максимально допустимое расстояние между ближайшими точками двух кривых по X. \en The maximum allowed distance along X between the nearest points of two curves. \~ \param[in] yNear - \ru Максимально допустимое расстояние между ближайшими точками двух кривых по Y. \en The maximum allowed distance along Y between the nearest points of two curves. \~ \param[in] devSag - \ru Максимальная величина прогиба. \en Maximal value of sag. \~ */ bool IsSpaceNear( const MbCurve & curve, double xEps, double yEps, bool ext, double xNear, double yNear, double devSag = 5.0*Math::deviateSag ) const; SimpleName GetCurveName() const { return name; } ///< \ru Имя кривой. \en A curve name. void SetCurveName( SimpleName newName ) { name = newName; } ///< \ru Установить имя кривой. \en Set a curve name. /** \} */ // \ru Функции унификации объекта и вектора объектов в шаблонных функциях. \en Functions for compatibility of a object and a vector of objects in template functions. size_t size() const { return 1; } ///< \ru Количество объектов при трактовке объекта как вектора объектов. \en Number of objects if object is interpreted as vector of objects. const MbCurve * operator [] ( size_t ) const { return this; } ///< \ru Оператор доступа. \en An access operator. private: // \ru Объявление оператора присваивания без реализации, чтобы не было присваивания по умолчанию \en Declaration without implementation of the assignment operator to prevent an assignment by default void operator = ( const MbCurve & ); DECLARE_PERSISTENT_CLASS( MbCurve ) }; // MbCurve IMPL_PERSISTENT_OPS( MbCurve ) //------------------------------------------------------------------------------ // \ru Вычислить точку на кривой. \en Calculate point on the curve. // --- inline MbCartPoint MbCurve::PointOn( double & t ) const { MbCartPoint pOn; PointOn( t, pOn ); return pOn; } //------------------------------------------------------------------------------ // \ru Вычислить первую производную. \en Calculate first derivative. // --- inline MbVector MbCurve::FirstDer( double & t ) const { MbVector der; FirstDer( t, der ); return der; } //------------------------------------------------------------------------------ // \ru Вычислить длину вектора производной. \en Calculate the length of derivative vector. // --- inline double MbCurve::DerLength( double & t ) const { MbVector der; FirstDer( t, der ); return der.Length(); } //------------------------------------------------------------------------------ // \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). // --- inline MbDirection MbCurve::Tangent( double & t ) const { MbDirection tang; Tangent( t, tang ); return tang; } //------------------------------------------------------------------------------ // \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). // --- inline void MbCurve::Tangent( double & t, MbVector & v ) const { FirstDer( t, v ); v.Normalize(); } //------------------------------------------------------------------------------ // \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). // --- inline void MbCurve::Tangent( double & t, MbDirection & tang ) const { MbVector v; FirstDer( t, v ); tang = v; } //------------------------------------------------------------------------------ // \ru Вычислить нормальный вектор. \en Calculate the normal vector. // --- inline MbDirection MbCurve::Normal( double & t ) const { return ~Tangent( t ); } //------------------------------------------------------------------------------ // \ru Вычислить нормальный вектор. \en Calculate the normal vector. // --- inline void MbCurve::Normal( double & t, MbVector & v ) const { Tangent( t, v ); v.Perpendicular(); } //------------------------------------------------------------------------------ // \ru Вычислить нормальный вектор. \en Calculate the normal vector. // --- inline void MbCurve::Normal( double &t, MbDirection &norm ) const { Tangent( t, norm ); norm.Perpendicular(); } //------------------------------------------------------------------------------ // \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). // --- inline void MbCurve::_Tangent( double t, MbVector & v ) const { _FirstDer( t, v ); v.Normalize(); } //------------------------------------------------------------------------------ // \ru Вычислить касательный вектор (нормализованный). \en Calculate tangent vector (normalized). // --- inline void MbCurve::_Tangent( double t, MbDirection & tang ) const { MbVector v; _FirstDer( t, v ); tang = v; } //------------------------------------------------------------------------------ // \ru Вычислить вектор главной нормали (нормализованный) на кривой и её продолжении. \en Calculate main normal vector (normalized) at curve and its extension. // --- inline void MbCurve::_Normal( double t, MbVector & v ) const { _FirstDer( t, v ); v.Perpendicular(); v.Normalize(); } //------------------------------------------------------------------------------ // \ru Вычислить вектор главной нормали (нормализованный) на кривой и её продолжении. \en Calculate main normal vector (normalized) at curve and its extension. // --- inline void MbCurve::_Normal( double t, MbDirection & norm ) const { MbVector v; _FirstDer( t, v ); v.Perpendicular(); norm = v; } //------------------------------------------------------------------------------ // \ru Проверить лежит ли точка на кривой с точностью eps. \en Check whether the point is on a curve with the tolerance eps. // --- inline bool MbCurve::IsPointOn( const MbCartPoint & pOn, double eps ) const { return DistanceToPoint( pOn ) < eps; } //------------------------------------------------------------------------------ // \ru Проверить лежит ли параметр в диапазоне кривой с точностью eps. \en Check whether the parameter is inside a range with the tolerance eps. // --- inline bool MbCurve::IsParamOn( double t, double eps ) const { return ( GetTMin() - t < eps ) && ( t - GetTMax() < eps ); } //------------------------------------------------------------------------------ // \ru Вычислить проекцию точки на кривую. \en Calculate the point projection to the curve. // --- inline void MbCurve::PointProjection( const MbCartPoint & pnt, MbCartPoint & on ) const { double t = PointProjection( pnt ); PointOn( t, on ); } //------------------------------------------------------------------------------ // \ru Вычислить точку на кривой, соответствующую проекции заданной точки на эту кривую. \en Calculate the point on the curve corresponding to the projection of the given point on this curve. // \ru Дополнительно возвращает угол наклона касательной к оси 0X в точке проекции. \en Additionally returns an inclination angle of a tangent to the axis OX at the point of projection. // --- inline void MbCurve::PointProjectionAndAngle( MbCartPoint & on, double & angle ) const { double t = PointProjection( on ); PointOn( t, on ); MbVector fd; FirstDer( t, fd ); angle = fd.DirectionAngle(); // \ru Угол касательной к оси 0X \en An angle of tangent to the axis OX. } //------------------------------------------------------------------------------ // \ru Вычислить граничную точку. \en Calculate the boundary point. // --- inline MbCartPoint MbCurve::GetLimitPoint( ptrdiff_t number ) const { double t = ( number == 1 ) ? GetTMin() : GetTMax(); MbCartPoint pOn; PointOn( t, pOn ); return pOn; } //------------------------------------------------------------------------------ // \ru Вычислить граничную точку. \en Calculate the boundary point. // --- inline void MbCurve::GetLimitPoint( ptrdiff_t number, MbCartPoint & pnt ) const { double t = ( number == 1 ) ? GetTMin() : GetTMax(); PointOn( t, pnt ); } //------------------------------------------------------------------------------ // \ru Вычислить касательный вектор в граничной точке. \en Calculate a tangent vector to the boundary point. // --- inline void MbCurve::GetLimitTangent( ptrdiff_t number, MbVector & tang ) const { double t = ( number == 1 ) ? GetTMin() : GetTMax(); Tangent( t, tang ); } //------------------------------------------------------------------------------ // \ru Вычислить касательный вектор и точку на конце кривой. \en Calculate a tangent vector and point at the end of a curve. // --- inline void MbCurve::GetLimitPointAndTangent( ptrdiff_t number, MbCartPoint & pnt, MbVector & tang ) const { double t = ( number == 1 ) ? GetTMin() : GetTMax(); PointOn( t, pnt ); Tangent( t, tang ); } //------------------------------------------------------------------------------ // \ru Определить, замкнута ли кривая фактически независимо от гладкости замыкания. \en Determine whether a curve is closed regardless of the smoothness of the closure. // --- inline bool MbCurve::IsTouch( double eps ) const { MbCartPoint p1, p2; _PointOn( GetTMin(), p1 ); _PointOn( GetTMax(), p2 ); if ( c3d::EqualPoints( p1, p2, eps ) ) { MbCartPoint p; _PointOn( GetTMid(), p ); double d = p1.DistanceToPoint( p2 ); double d1 = p.DistanceToPoint( p1 ); double d2 = p.DistanceToPoint( p2 ); if ( d <= d1 + d2 - EXTENT_EQUAL ) return true; } return false; } //------------------------------------------------------------------------------ /** \brief \ru Вычислить параметры ближайших точек двух кривых. \en Calculate parameters of the nearest points of two curves. \~ \details \ru Вычислить параметры ближайших точек двух кривых и расстояние между этими точками. \en Calculate parameters of the nearest points of two curves and the distance between these points. \~ \param[in] curve1 - \ru Кривая 1. \en Curve 1. \~ \param[in] ext1 - \ru Признак поиска на продолжении кривой 1. \en An attribute of search on the extension of the curve 1. \~ \param[in] curve2 - \ru Кривая 2. \en Curve 2. \~ \param[in] ext2 - \ru Признак поиска на продолжении кривой 2. \en An attribute of search on the extension of the curve 2. \~ \param[in] xEpsilon - \ru Погрешность по X. \en Tolerance in X direction. \~ \param[in] yEpsilon - \ru Погрешность по Y. \en Tolerance in Y direction. \~ \param[out] t1 - \ru Параметр точки кривой 1. \en A point parameter of curve 1. \~ \param[out] t2 - \ru Параметр точки кривой 2. \en A point parameter of curve 2. \~ \param[out] dmin - \ru Расстояние между точками кривых. \en The distance between points of curves. \~ \param[in] version - \ru Версия. \en Version. \~ \return \ru Возвращает nr_Success (+1) или nr_Special(0) в случае успешного определения, в случае неудачи возвращает nr_Failure(-1). \en Return nr_Success (+1) or nr_Special(0) in a case of successful defining, return nr_Failure(-1) in a case of failure. \~ \ingroup Algorithms_2D */ // --- MATH_FUNC (MbeNewtonResult) NearestPoints( const MbCurve & curve1, bool ext1, const MbCurve & curve2, bool ext2, double xEpsilon, double yEpsilon, double & t1, double & t2, double & dmin, VERSION version = Math::DefaultMathVersion() ); //------------------------------------------------------------------------------ /** \brief \ru Площадь и ориентация замкнутой кривой. \en An area and orientation of a closed curve. \~ \details \ru Вычислить площадь замкнутой кривой. По знаку площади определяется ориентация замкнутой кривой. Если площадь положительна, то замкнутая кривая направлена против движения часовой стрелки. \n Если кривая не замкнута, но установлен флаг замкнутости, то площадь будет вычислена для кривой, замкнутой отрезком, соединяющим края. \en Calculate an area of a closed curve. Orientation of a closed curve is defined by the sign of an area. If the area is positive then the closed curve is directed counterclockwise. \n If the curve is not closed, but the flag of closedness is set, then an area will be calculated for the curve which is closed by a section connecting bounds. \~ \param[in] curve - \ru Исходная кривая. \en The initial curve. \~ \param[in] sag - \ru Угловое отклонение касательной кривой в соседних точках интегрирования, используется для расчета шага по кривой. \en An angular deviation of a tangent curve at the neighbor integration points, is it used for the calculation of the step by a curve. \~ \param[in] close - \ru Флаг замкнутости. \en A flag of closedness. \~ \return \ru Площадь замкнутой кривой со знаком (ориентацией). \en An area of closed curve with a sign (orientation). \~ \ingroup Algorithms_2D */ // --- MATH_FUNC (double) AreaSign( const MbCurve & curve, double sag, bool close ); #endif // __CURVE_H
[ "dogz_z@mail.ru" ]
dogz_z@mail.ru
986cdef20ae241bc94d73089a37e01ffea35b57d
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/UseOfMessageLog/UNIX_UseOfMessageLog_LINUX.hxx
0f1746c18f2c6bfd549c80070965cfaf6cec1d8a
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
1,815
hxx
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifdef PEGASUS_OS_LINUX #ifndef __UNIX_USEOFMESSAGELOG_PRIVATE_H #define __UNIX_USEOFMESSAGELOG_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
1c32a46535b21e72482c448b84b4fb896916e6ae
0d1645e912fc1477eef73245a75af85635a31bd8
/sdk/js/include/nsIWindowCreator.h
74782d0fcc274c1d86696d585868dfbf592c7e76
[ "MIT" ]
permissive
qianxj/XExplorer
a2115106560f771bc3edc084b7e986332d0e41f4
00e326da03ffcaa21115a2345275452607c6bab5
refs/heads/master
2021-09-03T13:37:39.395524
2018-01-09T12:06:29
2018-01-09T12:06:29
114,638,878
0
0
null
null
null
null
UTF-8
C++
false
false
3,703
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM d:/firefox-5.0.1/mozilla-release/embedding/base/nsIWindowCreator.idl */ #ifndef __gen_nsIWindowCreator_h__ #define __gen_nsIWindowCreator_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIWebBrowserChrome; /* forward declaration */ /* starting interface: nsIWindowCreator */ #define NS_IWINDOWCREATOR_IID_STR "30465632-a777-44cc-90f9-8145475ef999" #define NS_IWINDOWCREATOR_IID \ {0x30465632, 0xa777, 0x44cc, \ { 0x90, 0xf9, 0x81, 0x45, 0x47, 0x5e, 0xf9, 0x99 }} class NS_NO_VTABLE NS_SCRIPTABLE nsIWindowCreator : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWINDOWCREATOR_IID) /** Create a new window. Gecko will/may call this method, if made available to it, to create new windows. @param parent parent window, if any. null if not. the newly created window should be made a child/dependent window of the parent, if any (and if the concept applies to the underlying OS). @param chromeFlags chrome features from nsIWebBrowserChrome @return the new window */ /* nsIWebBrowserChrome createChromeWindow (in nsIWebBrowserChrome parent, in PRUint32 chromeFlags); */ NS_SCRIPTABLE NS_IMETHOD CreateChromeWindow(nsIWebBrowserChrome *parent, PRUint32 chromeFlags, nsIWebBrowserChrome **_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIWindowCreator, NS_IWINDOWCREATOR_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIWINDOWCREATOR \ NS_SCRIPTABLE NS_IMETHOD CreateChromeWindow(nsIWebBrowserChrome *parent, PRUint32 chromeFlags, nsIWebBrowserChrome **_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIWINDOWCREATOR(_to) \ NS_SCRIPTABLE NS_IMETHOD CreateChromeWindow(nsIWebBrowserChrome *parent, PRUint32 chromeFlags, nsIWebBrowserChrome **_retval NS_OUTPARAM) { return _to CreateChromeWindow(parent, chromeFlags, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIWINDOWCREATOR(_to) \ NS_SCRIPTABLE NS_IMETHOD CreateChromeWindow(nsIWebBrowserChrome *parent, PRUint32 chromeFlags, nsIWebBrowserChrome **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->CreateChromeWindow(parent, chromeFlags, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsWindowCreator : public nsIWindowCreator { public: NS_DECL_ISUPPORTS NS_DECL_NSIWINDOWCREATOR nsWindowCreator(); private: ~nsWindowCreator(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsWindowCreator, nsIWindowCreator) nsWindowCreator::nsWindowCreator() { /* member initializers and constructor code */ } nsWindowCreator::~nsWindowCreator() { /* destructor code */ } /* nsIWebBrowserChrome createChromeWindow (in nsIWebBrowserChrome parent, in PRUint32 chromeFlags); */ NS_IMETHODIMP nsWindowCreator::CreateChromeWindow(nsIWebBrowserChrome *parent, PRUint32 chromeFlags, nsIWebBrowserChrome **_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif // {30465632-A777-44cc-90F9-8145475EF999} #define NS_WINDOWCREATOR_IID \ {0x30465632, 0xa777, 0x44cc, {0x90, 0xf9, 0x81, 0x45, 0x47, 0x5e, 0xf9, 0x99}} #endif /* __gen_nsIWindowCreator_h__ */
[ "qianxj15@sina.com" ]
qianxj15@sina.com
87bd15521294cce81a3ec15ad065aafccac04583
25e024cf92044a4233991028e5b7f534354b146a
/OTESceneManager/src/OTERunTimeAnalytics.cpp
38457f0eaf89fdfe5b9ec2120c2d353f371baad2
[]
no_license
panguojun/OTE
db8b4d7d1d5242d57dee503b7e405a7a01eed89e
d67a324337cc078f7da84a6d8b3d25b7ad0a7ca2
refs/heads/main
2023-08-20T21:56:08.208514
2021-10-26T01:53:24
2021-10-26T01:53:24
421,238,299
3
1
null
null
null
null
GB18030
C++
false
false
6,980
cpp
#include "oteruntimeanalytics.h" #include "OTED3DManager.h" using namespace OTE; #define MAX_REPORT_SIZE 2000 // 最大的记录调用次数记录 // ========================================================== // COTERunTimeAnalytics // ========================================================== class CRunTimeAnalyticsFrameListener : public Ogre::FrameListener { public: static CRunTimeAnalyticsFrameListener* s_pInst; CRunTimeAnalyticsFrameListener() : m_FrameTKCnt(0) { } virtual ~CRunTimeAnalyticsFrameListener() { } public: void showDebugOverlay(bool show){} // -------------------------------------------- bool frameStarted(const Ogre::FrameEvent& evt) { return true; } // -------------------------------------------- bool frameEnded(const Ogre::FrameEvent& evt) { m_FrameTKCnt ++; return true; } public: // 帧计数 unsigned int m_FrameTKCnt; }; CRunTimeAnalyticsFrameListener* CRunTimeAnalyticsFrameListener::s_pInst = NULL; // ========================================================== // COTERunTimeAnalytics // ========================================================== std::map<std::string, COTERunTimeAnalytics*> COTERunTimeAnalytics::s_AnalyticsTable; COTERunTimeAnalytics::COTERunTimeAnalytics(const std::string& rName) { m_Name = rName; } COTERunTimeAnalytics::~COTERunTimeAnalytics(void) { } // ---------------------------------------------------------- void COTERunTimeAnalytics::BeginAnalytics(const std::string& rFile, const std::string& rFunction) { std::stringstream ss; ss << rFile << " " << rFunction; BeginAnalytics(ss.str()); } // ---------------------------------------------------------- void COTERunTimeAnalytics::BeginAnalytics(const std::string& rName) { // 有必要初始化? if(!CRunTimeAnalyticsFrameListener::s_pInst) { CRunTimeAnalyticsFrameListener::s_pInst = new CRunTimeAnalyticsFrameListener(); Ogre::Root::getSingleton().addFrameListener(CRunTimeAnalyticsFrameListener::s_pInst); } COTERunTimeAnalytics* rts = _GetAnalytics(rName); if(!rts) { rts = new COTERunTimeAnalytics(rName); _AddAnalytics(rName, rts); } rts->m_BeginTK = ::GetTickCount(); } // ---------------------------------------------------------- void COTERunTimeAnalytics::EndAnalytics(const std::string& rFile, const std::string& rFunction) { static char buff[256]; sprintf(buff, "%s %s", rFile.c_str(), rFunction.c_str()); EndAnalytics(buff); } // ---------------------------------------------------------- void COTERunTimeAnalytics::EndAnalytics(const std::string& rName) { COTERunTimeAnalytics* rts = _GetAnalytics(rName); if(!rts) { OTE_MSG_ERR("性能分析器 没有找到 这个分析单元 : " << rName); return; } // 过大删除老的记录 if(rts->m_DTimeList.size() >= MAX_REPORT_SIZE) { rts->m_DTimeList.pop_front(); } rts->m_DTimeList.push_back( std::pair<int, float>(CRunTimeAnalyticsFrameListener::s_pInst->m_FrameTKCnt, (::GetTickCount() - rts->m_BeginTK) / 1000.0f) ); } // ---------------------------------------------------------- void COTERunTimeAnalytics::Init() { if(!CRunTimeAnalyticsFrameListener::s_pInst) { CRunTimeAnalyticsFrameListener::s_pInst = new CRunTimeAnalyticsFrameListener(); Ogre::Root::getSingleton().addFrameListener(CRunTimeAnalyticsFrameListener::s_pInst); } } // ---------------------------------------------------------- void COTERunTimeAnalytics::_AddAnalytics(const std::string& rName, COTERunTimeAnalytics* rta) { // 已经存在的 COTERunTimeAnalytics* oldAts = NULL; std::map<std::string, COTERunTimeAnalytics*>::iterator it = s_AnalyticsTable.find(rName); if(it != s_AnalyticsTable.end()) { oldAts = it->second; OTE_TRACE("已经存在这个分析器单元!添加失败!") return; } // 添加到列表 s_AnalyticsTable[rName] = rta; } // ---------------------------------------------------------- COTERunTimeAnalytics* COTERunTimeAnalytics::_GetAnalytics(const std::string& rName) { std::map<std::string, COTERunTimeAnalytics*>::iterator it = s_AnalyticsTable.find(rName); if(it == s_AnalyticsTable.end()) { return NULL; } return it->second; } // ---------------------------------------------------------- void COTERunTimeAnalytics::ReportAnalytics() { float totalDTime = 0; float maxDTime = 0.0f; float minDTime = MAX_FLOAT; std::list< std::pair<int, float> >::iterator it = m_DTimeList.begin(); while(it != m_DTimeList.end()) { float dTime = (*it ++).second; totalDTime += dTime; if(maxDTime < dTime) maxDTime = dTime; if(minDTime > dTime) minDTime = dTime; } m_TimeCost = totalDTime / float(m_DTimeList.size()); // 平均占用时间 if(COTED3DManager::s_FrameTime > 0) m_TimePercent = m_TimeCost / COTED3DManager::s_FrameTime; // 占用时间百分比 m_WorstTimeCost = maxDTime; // 最长调用时间使用 m_BestTimeCost = minDTime; // 最短调用时间使用 } // ---------------------------------------------------------- void COTERunTimeAnalytics::PrintAnalyticsReport() { if(m_DTimeList.empty()) return; // 先分析 ReportAnalytics(); // 打印信息 OTE_LOGMSG("单元名称: " << m_Name); unsigned int invakNum = m_DTimeList.size(); OTE_LOGMSG("调用记录次数: " << invakNum) int frameCnt = m_DTimeList.back().first - m_DTimeList.front().first + 1; OTE_LOGMSG("调用帧数量: " << frameCnt) OTE_LOGMSG("平均调用时间: " << m_TimeCost << " 平均帧时间比重: " << (m_TimeCost * invakNum / frameCnt) / COTED3DManager::s_FrameTime << " 一次调用所占帧时间比重:" << m_TimeCost / COTED3DManager::s_FrameTime) OTE_LOGMSG("最差调用时间: " << m_WorstTimeCost) OTE_LOGMSG("最好调用时间: " << m_BestTimeCost) } // ---------------------------------------------------------- void COTERunTimeAnalytics::_PrintAnalyticsReport() { if(s_AnalyticsTable.empty()) return; OTE_LOGMSG("======= 性能分析结果报告 ========") std::map<std::string, COTERunTimeAnalytics*>::iterator it = s_AnalyticsTable.begin(); while(it != s_AnalyticsTable.end()) { it->second->PrintAnalyticsReport(); ++ it; } OTE_LOGMSG("=================================") } // ---------------------------------------------------------- void COTERunTimeAnalytics::Clear() { std::map<std::string, COTERunTimeAnalytics*>::iterator it = s_AnalyticsTable.begin(); while(it != s_AnalyticsTable.end()) { delete it->second; ++ it; } s_AnalyticsTable.clear(); } // ---------------------------------------------------------- void COTERunTimeAnalytics::Destory() { // 摧毁之前打印信息 _PrintAnalyticsReport(); Clear(); }
[ "noreply@github.com" ]
noreply@github.com
18d9b3d41aaaa5718cc1d49097e4c25719f61e35
82530cc068e0eacd79179c67afef4a5fc76b9102
/129 task 3.cpp
192735723c107536cfff2e32090e87c60424b469
[]
no_license
jubayerislam17/190041129-CSE-4302
2db2add7f744061ce0bb92d8f7152a92692e05f8
6e6bdb94c39eb4b9782c3c8df3386ba4fe7251b5
refs/heads/main
2023-08-18T21:01:14.525337
2021-10-11T06:20:02
2021-10-11T06:20:02
383,467,152
0
0
null
null
null
null
UTF-8
C++
false
false
972
cpp
#include <bits/stdc++.h> using namespace std; class Product { private: string name; double unitPrice, discountPercent; public: Product(): unitPrice(10), discountPercent(0.5) {} void assignName(string pname) { name=pname; } void setPrice(double price) { if(price>0) unitPrice=price; } void setDiscPercent(double percent) { if(percent>0 && percent<=10) discountPercent=percent; } double getSellingPrice(int nos) { return nos*unitPrice*(100-discountPercent)/100; } void display() { cout<<name<<" has a unit price BDT "<<unitPrice<<". Current discount "<<discountPercent<<'%'<<".\n"; } }; int main() { Product p; p.assignName("Cocola Noodles"); p.setPrice(10); p.setDiscPercent(5); p.display(); cout<<"Current Price of 5 items: BDT "<<p.getSellingPrice(5); return 0; }
[ "noreply@github.com" ]
noreply@github.com
5884cb2893bd719fba2a69042a704e9f62922072
18a3f93e4b94f4f24ff17280c2820497e019b3db
/geant4/G4PolyhedraSide.hh
1dc934a2525264f469ebb1ac688cc046577d5bc5
[]
no_license
jjzhang166/BOSS_ExternalLibs
0e381d8420cea17e549d5cae5b04a216fc8a01d7
9b3b30f7874ed00a582aa9526c23ca89678bf796
refs/heads/master
2023-03-15T22:24:21.249109
2020-11-22T15:11:45
2020-11-22T15:11:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,331
hh
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // // // $Id: G4PolyhedraSide.hh,v 1.11.4.1 2010/03/18 11:04:57 gcosmo Exp $ // GEANT4 tag $Name: geant4-09-03-patch-01 $ // // // -------------------------------------------------------------------- // GEANT 4 class header file // // // G4PolyhedraSide // // Class description: // // Class implementing a face that represents one segmented side // of a polyhedra: // // G4PolyhedraSide( const G4PolyhedraSideRZ *prevRZ, // const G4PolyhedraSideRZ *tail, // const G4PolyhedraSideRZ *head, // const G4PolyhedraSideRZ *nextRZ, // G4int numSide, // G4double phiStart, G4double phiTotal, // G4bool phiIsOpen, G4bool isAllBehind=false ) // // Values for r1,z1 and r2,z2 should be specified in clockwise // order in (r,z). // Author: // David C. Williams (davidw@scipp.ucsc.edu) // -------------------------------------------------------------------- #ifndef G4PolyhedraSide_hh #define G4PolyhedraSide_hh #include "G4VCSGface.hh" class G4IntersectingCone; struct G4PolyhedraSideRZ { G4double r, z; // start of vector }; class G4PolyhedraSide : public G4VCSGface { public: // with description G4PolyhedraSide( const G4PolyhedraSideRZ *prevRZ, const G4PolyhedraSideRZ *tail, const G4PolyhedraSideRZ *head, const G4PolyhedraSideRZ *nextRZ, G4int numSide, G4double phiStart, G4double phiTotal, G4bool phiIsOpen, G4bool isAllBehind=false ); virtual ~G4PolyhedraSide(); G4PolyhedraSide( const G4PolyhedraSide &source ); G4PolyhedraSide& operator=( const G4PolyhedraSide &source ); G4bool Intersect( const G4ThreeVector &p, const G4ThreeVector &v, G4bool outgoing, G4double surfTolerance, G4double &distance, G4double &distFromSurface, G4ThreeVector &normal, G4bool &allBehind ); G4double Distance( const G4ThreeVector &p, G4bool outgoing ); EInside Inside( const G4ThreeVector &p, G4double tolerance, G4double *bestDistance ); G4ThreeVector Normal( const G4ThreeVector &p, G4double *bestDistance ); G4double Extent( const G4ThreeVector axis ); void CalculateExtent( const EAxis axis, const G4VoxelLimits &voxelLimit, const G4AffineTransform &tranform, G4SolidExtentList &extentList ); G4VCSGface *Clone() { return new G4PolyhedraSide( *this ); } public: // without description // Methods used for GetPointOnSurface() G4double SurfaceTriangle( G4ThreeVector p1, G4ThreeVector p2, G4ThreeVector p3, G4ThreeVector *p4 ); G4ThreeVector GetPointOnPlane( G4ThreeVector p0, G4ThreeVector p1, G4ThreeVector p2, G4ThreeVector p3, G4double *Area ); G4double SurfaceArea(); G4ThreeVector GetPointOnFace(); public: // without description G4PolyhedraSide(__void__&); // Fake default constructor for usage restricted to direct object // persistency for clients requiring preallocation of memory for // persistifiable objects. protected: // // A couple internal data structures // struct sG4PolyhedraSideVec; // Secret recipe for allowing friend struct sG4PolyhedraSideVec; // protected nested structures typedef struct sG4PolyhedraSideEdge { G4ThreeVector normal; // Unit normal to this edge G4ThreeVector corner[2]; // The two corners of this phi edge G4ThreeVector cornNorm[2]; // The normals of these corners } G4PolyhedraSideEdge; typedef struct sG4PolyhedraSideVec { G4ThreeVector normal, // Normal (point out of the shape) center, // Point in center of side surfPhi, // Unit vector on surface pointing along phi surfRZ; // Unit vector on surface pointing along R/Z G4PolyhedraSideEdge *edges[2]; // The phi boundary edges to this side // [0]=low phi [1]=high phi G4ThreeVector edgeNorm[2]; // RZ edge normals [i] at {r[i],z[i]} } G4PolyhedraSideVec; G4bool IntersectSidePlane( const G4ThreeVector &p, const G4ThreeVector &v, const G4PolyhedraSideVec vec, G4double normSign, G4double surfTolerance, G4double &distance, G4double &distFromSurface ); G4int LineHitsSegments( const G4ThreeVector &p, const G4ThreeVector &v, G4int *i1, G4int *i2 ); G4int ClosestPhiSegment( G4double phi ); G4int PhiSegment( G4double phi ); G4double GetPhi( const G4ThreeVector& p ); G4double DistanceToOneSide( const G4ThreeVector &p, const G4PolyhedraSideVec &vec, G4double *normDist ); G4double DistanceAway( const G4ThreeVector &p, const G4PolyhedraSideVec &vec, G4double *normDist ); void CopyStuff( const G4PolyhedraSide &source ); protected: G4int numSide; // Number sides G4double r[2], z[2]; // r, z parameters, in specified order G4double startPhi, // Start phi (0 to 2pi), if phiIsOpen deltaPhi, // Delta phi (0 to 2pi), if phiIsOpen endPhi; // End phi (>startPhi), if phiIsOpen G4bool phiIsOpen; // True if there is a phi slice G4bool allBehind; // True if the entire solid is "behind" this face G4IntersectingCone *cone; // Our intersecting cone G4PolyhedraSideVec *vecs; // Vector set for each facet of our face G4PolyhedraSideEdge *edges; // The edges belong to vecs G4double lenRZ, // RZ length of each side lenPhi[2]; // Phi dimensions of each side G4double edgeNorm; // Normal in RZ/Phi space to each side private: std::pair<G4ThreeVector, G4double> fPhi; // Cached value for phi G4double kCarTolerance; // Geometrical surface thickness G4double fSurfaceArea; // Surface Area }; #endif
[ "r.e.deboer@students.uu.nl" ]
r.e.deboer@students.uu.nl
bfe8238c28cd3dc636a55ec5dd92fce0ef5038fd
0b92e54d936baea124ad4e39f17e3ac2c1e98cc5
/libs/fitting/src/fitting/pso/transform_vector.cpp
2f46e6621bcb14c6dc61eff6dd3c150d99fbb438
[]
no_license
Jakub-Ciecierski/CloudFittingV2
5197b9f6269fad6d1dbf30baa62fd61ea3056416
52ff37683436168a2a973640544314ca6badb958
refs/heads/master
2020-04-16T11:35:35.779345
2016-09-19T18:59:05
2016-09-19T18:59:05
68,242,803
0
0
null
null
null
null
UTF-8
C++
false
false
653
cpp
// // Created by jakub on 3/29/16. // #include <fitting/pso/transform_vector.h> #include <iostream> //-----------------------// // CONSTRUCTORS //-----------------------// TransformVector::TransformVector(){ x = y = z = xAngle = yAngle = zAngle = 0; } TransformVector::TransformVector(float x, float y, float z, float xAngle, float yAngle, float zAngle) : x(x), y(y), z(z), xAngle(xAngle), yAngle(yAngle), zAngle(zAngle){ } TransformVector::~TransformVector() { } void TransformVector::transform(RigidObject* rigidBody){ rigidBody->moveTo(x, y, z); rigidBody->rotateTo(xAngle, yAngle, zAngle); }
[ "jakub.ciecier@gmail.com" ]
jakub.ciecier@gmail.com
9cfc2a652b30584b7946362edb0ab2ccb6ce1d15
d1cee40adee73afdbce5b3582bbe4761b595c4e1
/back/RtmpLivePushSDK/boost/boost/regex/config/borland.hpp
fd601e5cafdc671a602f6435fce92e57cda53462
[ "BSL-1.0" ]
permissive
RickyJun/live_plugin
de6fb4fa8ef9f76fffd51e2e51262fb63cea44cb
e4472570eac0d9f388ccac6ee513935488d9577e
refs/heads/master
2023-05-08T01:49:52.951207
2021-05-30T14:09:38
2021-05-30T14:09:38
345,919,594
2
0
null
null
null
null
UTF-8
C++
false
false
2,238
hpp
/* * * Copyright (c) 1998-2002 * John Maddock * * Use, modification and distribution are subject to 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) * */ /* * LOCATION: see http://www.boost.org for most recent version. * FILE boost/regex/config/borland.hpp * VERSION see <boost/version.hpp" * DESCRIPTION: regex borland-specific config setup. */ #if defined(__BORLANDC__) # if (__BORLANDC__ == 0x550) || (__BORLANDC__ == 0x551) // problems with std::basic_string and dll RTL: # if defined(_RTLDLL) && defined(_RWSTD_COMPILE_INSTANTIATE) # ifdef BOOST_REGEX_BUILD_DLL # error _RWSTD_COMPILE_INSTANTIATE must not be defined when building regex++ as a DLL # else # pragma message("Defining _RWSTD_COMPILE_INSTANTIATE when linking to the DLL version of the RTL may produce memory corruption problems in std::basic_string, as a result of separate versions of basic_string's static data in the RTL and you're exe/dll: be warned!!") # endif # endif # ifndef _RTLDLL // this is harmless for a staic link: # define _RWSTD_COMPILE_INSTANTIATE # endif // external templates cause problems for some reason: # define BOOST_REGEX_NO_EXTERNAL_TEMPLATES # endif # if (__BORLANDC__ <= 0x540) && !defined(BOOST_REGEX_NO_LIB) && !defined(_NO_VCL) // C++ Builder 4 and earlier, we can't tell whether we should be using // the VCL runtime or not, do a static link instead: # define BOOST_REGEX_STATIC_LINK # endif // // VCL support: // if we're building a console app then there can't be any VCL (can there?) # if !defined(__CONSOLE__) && !defined(_NO_VCL) # define BOOST_REGEX_USE_VCL # endif // // if this isn't Win32 then don't automatically select link // libraries: // # ifndef _Windows # ifndef BOOST_REGEX_NO_LIB # define BOOST_REGEX_NO_LIB # endif # ifndef BOOST_REGEX_STATIC_LINK # define BOOST_REGEX_STATIC_LINK # endif # endif #if __BORLANDC__ < 0x600 // // string workarounds: // #include <cstring> #undef strcmp #undef strcpy #endif #endif
[ "wenwenjun@weeget.cn" ]
wenwenjun@weeget.cn
043dee2766dbe64aac9067b59f74d7f1ae5b5564
8de91a1aebb00600a98a69b7b8c783cb6a020720
/Codeforces-Online-Judge/Virtual Participation/FFC_elimination/C.cpp
7652b0a7b9ecc2114ab8b0ff8df262aca847eae4
[]
no_license
RenatoBrittoAraujo/Competitive-Programming
2148d5fc4b0ac4b8fdbadc8de2916b31a549e183
de641f129a1ce27deffb7bf7c1635d702d05bf3e
refs/heads/master
2020-05-22T21:17:41.420014
2019-05-17T00:39:20
2019-05-17T00:39:20
186,523,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,599
cpp
#include <bits/stdc++.h> using namespace std; #define ff first #define ss second #define pb push_back #define eb emplace_back #define mp make_pair #define loop(i,a,b) for(int (i) = (a); (i) < (b); (i)++) #define len(a) (int)a.size() #define allv(a) (a).begin(),(a).end() using ll = long long; using ii = pair<int, int>; using pll = pair<ll, ll>; using vi = vector<int>; using vl = vector<ll>; const int INF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3f; const double err = 1e-9; const int mod = 1e9 + 7; const int N = 1e5 + 10; int main() { ios::sync_with_stdio(0);cin.tie(NULL); int t; cin>>t; while(t--) { int n; cin>>n; if(n == 2) { cout<<" 1 1 1 2"<<endl; cout.flush(); int ans; cin>>ans; cout<<"-1 "<<ans<<endl; continue; } vector<int> can(n - 1); for(int i = 0; i < n - 1; i++) can[i] = i + 2; int l = 0, r = n - 2; while(r - l > 0) { int mid = (l + r) / 2; int v1, v2; cout<<"1 "<<mid - l + 1<<" 1 "; for(int i = l; i <= mid; i++) cout<<can[i]<<' '; cout<<endl; cout.flush(); cin>>v1; cout<<"1 "<<r - mid<<" 1 "; for(int i = mid + 1; i <= r; i++) cout<<can[i]<<' '; cout<<endl; cout.flush(); cin>>v2; if(v1 > v2) r = mid; else l = mid + 1; } //cout<<"YO\n"; int lb = l > (n - 1) / 2 ? 0 : (n - 1) / 2 + 1; int rb = l > (n - 1) / 2 ? (n - 1) / 2 : n - 2; cout<<"1 "<< rb - lb + 1 <<' '<<can[l]<<' '; for(int i = lb; i <= rb; i++) cout<<can[i]<<' '; cout.flush(); int ans; cin>>ans; cout<<"-1 "<<ans<<endl; } return 0; }
[ "renatomwbbritto@gmail.com" ]
renatomwbbritto@gmail.com
c6530b2692025d4c0bb5f89c646fa33b2f9e1ba2
ace20ae898aadf18c4ef8a2355b528422fc27bb5
/ccc_cco/golf.cpp
46b6757dad7c68df7e8027f5c2f183b8239fc4ea
[]
no_license
pidddgy/competitive-programming
19fd79e7888789c68bf93afa3e63812587cbb0fe
ec86287a0a70f7f43a13cbe26f5aa9c5b02f66cc
refs/heads/master
2022-01-28T07:01:07.376581
2022-01-17T21:37:06
2022-01-17T21:37:06
139,354,420
0
3
null
2021-04-06T16:56:29
2018-07-01T19:03:53
C++
UTF-8
C++
false
false
1,043
cpp
// https://dmoj.ca/problem/ccc00s4 #include <bits/stdc++.h> #pragma GCC optimize "Ofast" #define endl '\n' using namespace std; int D, N; vector<int> clubs; vector<int> rets; unordered_set<int> dp; void cuteeeeeeeeeeeeeeeeeeeeeeeeeeeee(int count = 0, int total = 0) { if(total == D) rets.push_back(count); else for(auto c: clubs) if(total+c <= D) if(dp.find(total+c) == dp.end() || dp.empty()) { dp.emplace(total+c); cuteeeeeeeeeeeeeeeeeeeeeeeeeeeee(count+1, total+c); } } int main() { cin.sync_with_stdio(0); cin.tie(0); cin >> D >> N; for(int i = 0; i < N; i++) { int a; cin >> a; clubs.push_back(a); } sort(clubs.begin(), clubs.end(), greater<int>()); cuteeeeeeeeeeeeeeeeeeeeeeeeeeeee(); if(rets.empty()) cout << "Roberta acknowledges defeat." << endl; else cout << "Roberta wins in " << *min_element(rets.begin(), rets.end()) << " strokes." << endl; }
[ "marcus.jn.chong@gmail.com" ]
marcus.jn.chong@gmail.com
4f7cbb7cd526bab450e28bd03b1117e7af4ff47c
768924401a52782726f5874ef32e773b3cb09868
/C++_Risk/Player.h
5dcff7f78cc9274d62b7983997cc3b5a4773912d
[]
no_license
JonathanFrey2704/Implementation-of-RISK-board-game
bc6020d4606a2f92bd64a255811b921279156e2c
24c0ac3d50240bb47edddefc96c41b94d8949f67
refs/heads/main
2023-03-08T10:01:48.386341
2021-02-25T10:00:12
2021-02-25T10:00:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,383
h
#pragma once #include<iostream> #include "Hand.h" #include "DiceRoller.h" #include "Map.h" class Country; class Map; class Continent; #include <vector> using namespace std; //using std::vector; class Player { public: //Constructor Player(); Player(int ownerId); //Accessor int getOwnerNum(); vector< Country* > getOwnedCountries(); DiceFacility& getDiceFacility(); Hand getHand(); int getNumOfArmies(); //Mutator void setOwnerNum(int ownerNum); void setOwnedCountry(Country* country); void setDiceFacility(DiceFacility df); void setHand(Hand hand); void setNumOfArmies(int numOfArmies); //Other methods void printPlayerOwnedCountries(); /* Hand object; DiceFacility object1; */ void fortify(); void attack(); void reinforce(); void attack1(); //dummy attack //ATTACK PHASE METHODS void removeCountry(Country country);//Removes the country from ownedCountries void printPlayerOwnedCountries2(); //private: //Attributes vector<Country*> ownedCountries; int ownerNum; DiceFacility df; Hand hand; int numOfArmies; int null = -1; //Attack phase members Country *defendingCountry; Country *attackingCountry; Player *attacker; Player *defender; vector<Country*> canAttack; vector<Country*> canAttackFrom; void compare(vector<int> att, vector<int> def); void conquer(); };
[ "noreply@github.com" ]
noreply@github.com
4687a5abbf6a5fc5f6f0e1034102ebb355e244fb
350858d630bd55a445dfb4091590966bee2f2bd0
/MLProcessor/predict.cpp
026d12d2e3805ea63487b8f0973122211d25d381
[]
no_license
mattcoldwater/ml_app
f4b349a61cc8ec1462b1d7c0f4553b86fbb3f3e6
fc191b12d7032038bdd1cc025c3f5df445d60360
refs/heads/master
2020-05-25T05:43:45.280333
2019-05-21T12:22:19
2019-05-21T12:22:19
181,302,069
0
0
null
null
null
null
UTF-8
C++
false
false
1,113
cpp
#include "predict.h" //输入一组变量得到的y_hat(单个observation) int predict(vector<double> parameters, vector<double> variables){ double sum=0; int y=0; for (int i=0; i<parameters.size(); i++) { sum+=parameters[i]*variables[i]; } if (sum>0.5) { y=1; } return y; } int predict2(vector<double> parameters, vector<double> variables, double threshold){ double sum=0; int y=0; for (int i=0; i<parameters.size(); i++) { sum+=parameters[i]*variables[i]; } if (sum>threshold) { y=1; } return y; } //测试所有输入并计算预测准确的比例 double accuracy(vector<vector<double>> test_data_frame, vector<double> y, vector<double> parameters){ double correction=0; for (int i=0; i<test_data_frame.size(); i++) { vector<double> current_ob=test_data_frame[i]; //DoubleArray current_ob_transformed=transform(current_ob); int result=predict(parameters,current_ob); if (result==y[i]){ correction++; } } double total=y.size(); double accuracy=correction/total; return accuracy; }
[ "mattcoldwater@gmail.com" ]
mattcoldwater@gmail.com
e12ae2ced3303c1e4694ab681ef5b8d7bfdc3ff5
f7b3ffae55ce44de2aeacf32d286ffe1ab648f91
/codeforces/TanyaAndCandies.cpp
0b4942e72f1bee0bfcc31c57d55d30a5fa2b03d3
[]
no_license
kritika0598/codes
40ea58f830a756cd1853a148bb1774def7e663b6
94f8e9e9de4cc819b598be259835468eb617755c
refs/heads/master
2022-04-01T05:11:44.257623
2019-12-30T16:28:14
2019-12-30T16:28:14
230,945,032
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
cpp
#include<iostream> #include<bits/stdc++.h> using namespace std; typedef long long int lli; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); lli N; cin>>N; lli Arr[N+1]; lli odd[N+1]; lli even[N+1]; odd[0]=0; even[0]=0; lli k=1,l=1; lli esum=0; lli essum[N+1]; lli osum=0; lli ossum[N+1]; essum[0]=0; ossum[0]=0; lli p[N+1]; for(lli i=1;i<=N;i++ ) { cin>>Arr[i]; if(i%2==0) { even[k]=i; essum[k]=essum[k-1]+Arr[i]; k++; esum+=Arr[i]; p[i]=k-1; } else { odd[l]=i; ossum[l]=ossum[l-1]+Arr[i]; l++; osum+=Arr[i]; p[i]=l-1; } } lli count=0; if(osum-Arr[1]==esum) count++; if(N%2==0) { if(esum-Arr[N]==osum) count++; } else { if(osum-Arr[N]==esum) count++; } //cout<<count<<endl; for(lli i=2;i<=N-1;i++) { if(i%2==0) { //cout<<p[i]<<" "<<esum<<" "<<Arr[i]<<" "<<ossum[p[i]]<<" "<<essum[p[i]-1]<<" "<<osum<<" "<<ossum[p[i]]<<" "<<essum[p[i]-1]<<endl; //cout<<esum-Arr[i]+ossum[p[i]]-essum[p[i]-1]<<" "<<osum-ossum[p[i]]+essum[p[i]-1]<<endl; if(esum-Arr[i]+ossum[p[i]]-essum[p[i]-1]==osum-ossum[p[i]]+essum[p[i]-1]) count++; } else { //cout<<esum-essum[p[i]-1]+ossum[p[i]-1]<<" "<<osum-Arr[i]+essum[p[i]-1]-ossum[p[i]-1]<<endl; if(esum-essum[p[i]-1]+ossum[p[i]-1]==osum-Arr[i]+essum[p[i]-1]-ossum[p[i]-1]) count++; } } cout<<count<<endl; }
[ "16ucs094@lnmiit.ac.in" ]
16ucs094@lnmiit.ac.in
3515f60ec11c1571ad4b46d4270b4ed834e43d45
aedfb7242153f5716f92f21fb15e8d43d678aebc
/chapter13/sec-05/demo-02/str_vec.cc
33258d37496c9f7407e5c53666d9aa2a71ad8132
[]
no_license
MaxEntroy/cpp-primer
0c75835e345f81163c61e6127458294cbb5ff10e
672ed670c95b148950be4873ea27d3c3c4dac306
refs/heads/master
2021-07-20T16:56:26.375435
2021-05-13T12:24:31
2021-05-13T12:26:58
249,339,103
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
cc
#include "str_vec.h" #include "str_vec_impl.h" namespace cp { StrVec::StrVec(int sz) : pimpl_(new StrVecImpl()) { pimpl_->create(sz); } StrVec::StrVec(std::initializer_list<std::string> il) : pimpl_(new StrVecImpl()) { pimpl_->create(il.begin(), il.end()); } StrVec::~StrVec() { pimpl_->uncreate(); } StrVec::StrVec(const StrVec& rhs) : pimpl_(new StrVecImpl()) { pimpl_->create(rhs.begin(), rhs.end()); } StrVec& StrVec::operator=(const StrVec& rhs) { if (this == &rhs) { return *this; } pimpl_->uncreate(); pimpl_->create(rhs.begin(), rhs.end()); return *this; } StrVec::Iter StrVec::begin() const { return pimpl_->first(); } StrVec::Iter StrVec::end() const { return pimpl_->last(); } size_t StrVec::size() const { return end() - begin(); } size_t StrVec::capacity() const { return pimpl_->end() - begin(); } void StrVec::push_back(const std::string& val) { if (!pimpl_->is_enough_room()) { pimpl_->realloc_mem(); } pimpl_->construct_last(val); } } // namespace cp
[ "likang@tju.edu.cn" ]
likang@tju.edu.cn
24b02df3a3ce3b11e937575ad4ae5df830aac3ee
6fa6b787224c697b27233be35731bc6cd1cdcc51
/Projects_C++/TestQt/pagetwo.h
4d52b17db9493b422206e52d8fe0c3e2989260ee
[]
no_license
Olaful/Olaful.github.io
159703563eca6e505a6516d0a248ad549b0565d1
aeb2cd95599667767c0be3c5f23a040a416652cc
refs/heads/master
2022-12-11T20:31:31.957940
2019-02-20T09:22:22
2019-02-20T09:22:22
139,222,471
0
0
null
2022-12-08T01:37:29
2018-06-30T05:39:47
C
UTF-8
C++
false
false
579
h
#ifndef PAGETWO_H #define PAGETWO_H #include <QWidget> #include <QVBoxLayout> #include <QPushButton> #include <QLineEdit> #include <QTableWidget> #include <QTableView> #include <QHeaderView> #include "typedef.h" class PageTwo : public QWidget { Q_OBJECT public: explicit PageTwo(QWidget *parent = 0); public slots: void QueryInfo(); void sortByColumn(int colum); private: QVBoxLayout *m_pageOneLayout; QPushButton *pushButton_search; QLineEdit *lineEdit_ID, *lineEdit_name; QTableWidget *tableWidget; protected: }; #endif // PAGETWO_H
[ "1764740905@qq.com" ]
1764740905@qq.com
eea9ab4b3143876d823fdcfb29453dabbde35e6d
37cca16f12e7b1d4d01d6f234da6d568c318abee
/src/rice/pastry/socket/nat/rendezvous/RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1.cpp
faa0cf96a53399500cbb3c224bbe7812fdd88e88
[]
no_license
subhash1-0/thirstyCrow
e48155ce68fc886f2ee8e7802567c1149bc54206
78b7e4e3d2b9a9530ad7d66b44eacfe73ceea582
refs/heads/master
2016-09-06T21:25:54.075724
2015-09-21T17:21:15
2015-09-21T17:21:15
42,881,521
0
0
null
null
null
null
UTF-8
C++
false
false
4,575
cpp
// Generated from /pastry-2.1/src/rice/pastry/socket/nat/rendezvous/RendezvousSocketPastryNodeFactory.java #include <rice/pastry/socket/nat/rendezvous/RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/Exception.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuilder.hpp> #include <java/util/ArrayList.hpp> #include <org/mpisws/p2p/transport/SocketRequestHandle.hpp> #include <org/mpisws/p2p/transport/liveness/LivenessProvider.hpp> #include <org/mpisws/p2p/transport/rendezvous/PilotManager.hpp> #include <rice/environment/logging/Logger.hpp> #include <rice/pastry/PastryNode.hpp> #include <rice/pastry/socket/SocketNodeHandle.hpp> #include <rice/pastry/socket/nat/rendezvous/RendezvousSocketNodeHandle.hpp> #include <rice/pastry/socket/nat/rendezvous/RendezvousSocketPastryNodeFactory_getBootstrapper_4.hpp> #include <Array.hpp> template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } extern void lock(::java::lang::Object *); extern void unlock(::java::lang::Object *); namespace { struct synchronized { synchronized(::java::lang::Object *o) : o(o) { ::lock(o); } ~synchronized() { ::unlock(o); } private: synchronized(const synchronized&); synchronized& operator=(const synchronized&); ::java::lang::Object *o; }; } rice::pastry::socket::nat::rendezvous::RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1::RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1(RendezvousSocketPastryNodeFactory_getBootstrapper_4 *RendezvousSocketPastryNodeFactory_getBootstrapper_4_this, ::java::util::ArrayList* closeMeWhenReady, ::boolArray* booted, ::org::mpisws::p2p::transport::rendezvous::PilotManager* manager, ::rice::pastry::socket::SocketNodeHandle* h) : super(*static_cast< ::default_init_tag* >(0)) , RendezvousSocketPastryNodeFactory_getBootstrapper_4_this(RendezvousSocketPastryNodeFactory_getBootstrapper_4_this) , closeMeWhenReady(closeMeWhenReady) , booted(booted) , manager(manager) , h(h) { clinit(); ctor(); } void rice::pastry::socket::nat::rendezvous::RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1::receiveResult(::org::mpisws::p2p::transport::SocketRequestHandle* result) { auto close = false; { synchronized synchronized_0(closeMeWhenReady); { if((*booted)[int32_t(0)]) { close = true; } else { npc(closeMeWhenReady)->add(static_cast< ::java::lang::Object* >(java_cast< RendezvousSocketNodeHandle* >(npc(result)->getIdentifier()))); } } } if(close) { npc(RendezvousSocketPastryNodeFactory_getBootstrapper_4_this->logger)->log(u"closing pilot"_j); npc(manager)->closePilot(java_cast< RendezvousSocketNodeHandle* >(npc(result)->getIdentifier())); return; } npc(npc(RendezvousSocketPastryNodeFactory_getBootstrapper_4_this->pn)->getLivenessProvider())->checkLiveness(h, nullptr); } void rice::pastry::socket::nat::rendezvous::RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1::receiveResult(::java::lang::Object* result) { receiveResult(dynamic_cast< ::org::mpisws::p2p::transport::SocketRequestHandle* >(result)); } void rice::pastry::socket::nat::rendezvous::RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1::receiveException(::java::lang::Exception* exception) { npc(RendezvousSocketPastryNodeFactory_getBootstrapper_4_this->logger)->logException(::java::lang::StringBuilder().append(u"In Rendezvous Bootstrapper.checkLiveness("_j)->append(static_cast< ::java::lang::Object* >(h)) ->append(u")"_j)->toString(), exception); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* rice::pastry::socket::nat::rendezvous::RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1::class_() { static ::java::lang::Class* c = ::class_(u"", 0); return c; } java::lang::Class* rice::pastry::socket::nat::rendezvous::RendezvousSocketPastryNodeFactory_getBootstrapper_4_checkLiveness_4_1::getClass0() { return class_(); }
[ "sgurjar@adobe.com" ]
sgurjar@adobe.com
1f1c6fbdb1227ff8ad8606a9c95083d653372c4f
656c70d5b3b31ec711c8e4807e6ad461c6b2d297
/countapples.cpp
1ade88a4e130b2ed8866f3536144433d5e79d68b
[]
no_license
melvinjames7/CountingApples
4b35793150b6e02e27dc7b09a4a5b1e239b24707
525568d2f749fade25ecbf7129d5f70141feb443
refs/heads/master
2021-05-11T16:14:43.465661
2018-02-06T06:28:52
2018-02-06T06:28:52
117,758,158
0
0
null
null
null
null
UTF-8
C++
false
false
9,805
cpp
// // Created by Melvin James on 2/7/17. // Copyright © 2017 Melvin James. All rights reserved. // #include <opencv2/core/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui/highgui.hpp> #include "opencv2/imgproc/imgproc.hpp" #include <algorithm> #include <iostream> #include <string> using namespace cv; using namespace std; Mat image,gaussian_noise,N1,H1,SnP_noise,N2,H2,B1,temp; void DenoiseSnP() { const int kernalWidth=3; const int kernalHeight=3; int size =kernalWidth*kernalHeight; float kernalArray[kernalWidth][kernalHeight] = {{0}}; int rows=N2.rows; int cols=N2.cols; Mat DenoisedImage(N2.size(),N2.type()); for(int row=0+1; row<rows-1; row++){ for(int col=0+1;col<cols-1;col++){ float valuer[9] = {0},valueg[9] = {0},valueb[9] = {0}; int i =0; for(int kRow=0;kRow<kernalHeight;kRow++){ for(int kCol=0;kCol<kernalWidth;kCol++){ // multiply pixel value with corresponding gaussian kernal value float pixelr=N2.at<Vec3b>(kRow+row-1,kCol+col-1)[2]+kernalArray[kRow][kCol]; valuer[i]=pixelr; float pixelg=N2.at<Vec3b>(kRow+row-1,kCol+col-1)[1]+kernalArray[kRow][kCol]; valueg[i]=pixelg; float pixelb=N2.at<Vec3b>(kRow+row-1,kCol+col-1)[0]+kernalArray[kRow][kCol]; valueb[i]=pixelb; i++; } } sort(valuer,valuer+size); sort(valueg,valueg+size); sort(valueb,valueb+size); //assign new values to central point DenoisedImage.at<Vec3b>(row,col)[2]=(valuer[5]); DenoisedImage.at<Vec3b>(row,col)[1]=(valueg[5]); DenoisedImage.at<Vec3b>(row,col)[0]=(valueb[5]); } } H2 = DenoisedImage; namedWindow("filtered S and P H2", 1); imshow("filtered S and P H2", H2); } void DenoiseG(Mat N1) { const double PI = 3.14 ; double sigma= 1; const int kernalWidth=5; const int kernalHeight=5; float kernalArray[kernalWidth][kernalHeight]; double total=0; //calculate each relavant value to neighour pixels and store it in 2d array for(int row=0;row<kernalWidth;row++){ for(int col=0;col<kernalHeight;col++){ float value=(1/(2*PI*pow(sigma,2)))*exp(-(pow(row-kernalWidth/2,2)+pow(col-kernalHeight/2,2))/(2*pow(sigma,2))); kernalArray[row][col]=value; total+=value; } } for(int row=0;row<kernalWidth;row++){ for(int col=0;col<kernalHeight;col++){ kernalArray[row][col]=kernalArray[row][col]/total; } } Mat DenoisedImage(N1.size(),N1.type()); int rows=N1.rows; int cols=N1.cols; int verticleImageBound=(kernalHeight-1)/2; int horizontalImageBound=(kernalWidth-1)/2; for(int row=0+verticleImageBound; row<rows-verticleImageBound; row++){ for(int col=0+horizontalImageBound;col<cols-horizontalImageBound;col++){ float valuer =0.0,valueg=0.0, valueb=0.0; for(int kRow=0;kRow<kernalHeight;kRow++){ for(int kCol=0;kCol<kernalWidth;kCol++){ // multiply pixel value with corresponding gaussian kernal value float pixelr=N1.at<Vec3b>(kRow+row-verticleImageBound,kCol+col-horizontalImageBound)[2]*kernalArray[kRow][kCol]; valuer+=pixelr; float pixelg=N1.at<Vec3b>(kRow+row-verticleImageBound,kCol+col-horizontalImageBound)[1]*kernalArray[kRow][kCol]; valueg+=pixelg; float pixelb=N1.at<Vec3b>(kRow+row-verticleImageBound,kCol+col-horizontalImageBound)[0]*kernalArray[kRow][kCol]; valueb+=pixelb; } } //assign new values to central point DenoisedImage.at<Vec3b>(row,col)[2]=(valuer); DenoisedImage.at<Vec3b>(row,col)[1]=(valueg); DenoisedImage.at<Vec3b>(row,col)[0]=(valueb); } } H1 = DenoisedImage; namedWindow("Gauss filtered H1", 1); imshow("Gauss filtered H1", H1); } void GaussN() //Add Gaussian noise { gaussian_noise = temp.clone(); N1 = temp; randn(gaussian_noise,0,15); N1+=gaussian_noise; namedWindow("Image with Gaussian noise N1", 1); imshow("Image with Gaussian noise N1", N1); DenoiseG(N1); } void SaltnPepper() { SnP_noise = Mat::zeros(image.rows, image.cols,CV_8U); N2 = image.clone(); // randu(SnP_noise,0,255); // // Mat black = SnP_noise < 30; // Mat white = SnP_noise > 245; // // // N2.setTo(255,white); // N2.setTo(0,black); int specks = ceil(0.01*image.rows*image.cols*0.5); for(int i = 0; i< specks; i++) { int y = rand()%(image.rows - 1); int x = rand()%(image.cols - 1); N2.at<Vec3b>(y,x)[0] = 255; N2.at<Vec3b>(y,x)[1] = 255; N2.at<Vec3b>(y,x)[2] = 255; } for(int i = 0; i< specks; i++) { int y = rand()%(image.rows - 1); int x = rand()%(image.cols - 1); N2.at<Vec3b>(y,x)[0] = 0; N2.at<Vec3b>(y,x)[1] = 0; N2.at<Vec3b>(y,x)[2] = 0; } namedWindow("Image with Salt and Pepper noise N2", 1); imshow("Image with Salt and Pepper noise N2", N2); DenoiseSnP(); } Mat makeBinary(Mat img) { Mat d_image = Mat::zeros( image.size(), image.type() ); for( int y = 0; y < img.rows; y++ ) { for( int x = 0; x < img.cols; x++ ) { float r = (img.at<Vec3b>(y,x)[2]); float g = (img.at<Vec3b>(y,x)[1]); float b = (img.at<Vec3b>(y,x)[0]); if((r-g>50 && r-b>50) || (g>170 && b<200 )){ // if(r>0){ r = 255; g=255; b=255; //white } else{ r = 0; g = 0; b = 0; //black } d_image.at<Vec3b>(y,x)[0] = saturate_cast<uchar>( b); d_image.at<Vec3b>(y,x)[1] = saturate_cast<uchar>( g ); d_image.at<Vec3b>(y,x)[2] = saturate_cast<uchar>( r); } } int erosion_size = 6; Mat element = getStructuringElement(cv::MORPH_CROSS, cv::Size(2 * erosion_size + 1, 2 * erosion_size + 1), cv::Point(erosion_size, erosion_size) ); // Apply erosion or dilation on the image erode(d_image,d_image,element); medianBlur(d_image, d_image, 17); //to filter noise dilate(d_image, d_image, Mat(), Point(-1, -1), 2, 1, 1); int i=0,width=0,X=0,Y=0; for( int y = 0; y < image.rows; y++ ) { for( int x = 0; x < image.cols; x++ ) { float r = (image.at<Vec3b>(y,x)[2]); if(r==255) { i++;} else { if(i>width) { X=x; Y=y; width = i; }i=0; } }i=0; }X-=width/2; return d_image; // namedWindow("Binary", 1); // // imshow("Binary", d_image); } int main(int argc, const char * argv[]) { string imageName("/Users/melvinjames/Desktop/Apples.png"); if( argc > 1) { imageName = argv[1]; } image = imread(imageName.c_str(), IMREAD_COLOR); // Read the file temp =imread(imageName.c_str(), IMREAD_COLOR); if( image.empty() ) // Check for invalid input { cout << "Could not open or find the image" << std::endl ; return -1; } namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display. imshow( "Display window", image ); // For Gaussian Noise GaussN(); // //For Salt and Pepper Noise SaltnPepper(); // For adjusting Brightness B1 = Mat::zeros( image.size(), image.type() ); for( int y = 0; y < image.rows; y++ ) { for( int x = 0; x < image.cols; x++ ) { for( int c = 0; c < 3; c++ ) { B1.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( image.at<Vec3b>(y,x)[c] + 50 ); } } } namedWindow("Brightness Adjusted Image B1", 1); imshow("Brightness Adjusted Image B1", B1); // Mat bin1 = makeBinary(image); //imshow("Binary of original", bin1); Mat bin2 = makeBinary(N1); //imshow("Binary of Gauss Noise N1", bin2); Mat bin3 = makeBinary(H1); //imshow("Binary of W/O Gauss Noise H1", bin3); Mat bin4 = makeBinary(N2); //imshow("Binary of SaltPepper N2", bin4); Mat bin5 = makeBinary(H2); //imshow("Binary of W/O Salt Pepper H2", bin5); Mat bin6 = makeBinary(B1); //imshow("Binary of Brightness Adjusted B1", bin6); cvtColor(bin1, bin1, CV_RGB2GRAY); cout<<"I ="<<connectedComponents(bin1,image, 8)<<endl; cvtColor(bin2, bin2, CV_RGB2GRAY); cout<<"N1 ="<<connectedComponents(bin2,image, 8)<<endl; cvtColor(bin3, bin3, CV_RGB2GRAY); cout<<"H1 ="<<connectedComponents(bin3,image, 8)<<endl; cvtColor(bin4, bin4, CV_RGB2GRAY); cout<<"N2 ="<<connectedComponents(bin4,image, 8)<<endl; cvtColor(bin5, bin5, CV_RGB2GRAY); cout<<"H2 ="<<connectedComponents(bin5,image, 8)<<endl; cvtColor(bin6, bin6, CV_RGB2GRAY); cout<<"B1 ="<<connectedComponents(bin6,image, 8)<<endl; waitKey(0); //to view output return 0; }
[ "melvinjames7@gmail.com" ]
melvinjames7@gmail.com
b1c74900ac3327de517058ddf0b94f88c7f3b775
3e1ac5a6f5473c93fb9d4174ced2e721a7c1ff4c
/build/iOS/Preview/include/Fuse.Triggers.PageBeginLoading.h
ab7deb5289ab0690d6392d1f5730dc470987cbe5
[]
no_license
dream-plus/DreamPlus_popup
49d42d313e9cf1c9bd5ffa01a42d4b7c2cf0c929
76bb86b1f2e36a513effbc4bc055efae78331746
refs/heads/master
2020-04-28T20:47:24.361319
2019-05-13T12:04:14
2019-05-13T12:04:14
175,556,703
0
1
null
null
null
null
UTF-8
C++
false
false
1,438
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Controls.WebView/1.9.0/PageBeginLoading.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IBasePlayerFeedback.h> #include <Fuse.Animations.IUnwrappedPlayerFeedback.h> #include <Fuse.Binding.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.ISourceLocation.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Trigger.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> namespace g{namespace Fuse{namespace Triggers{struct PageBeginLoading;}}} namespace g{ namespace Fuse{ namespace Triggers{ // public sealed class PageBeginLoading :22 // { ::g::Fuse::Triggers::Trigger_type* PageBeginLoading_typeof(); void PageBeginLoading__ctor_5_fn(PageBeginLoading* __this); void PageBeginLoading__New2_fn(PageBeginLoading** __retval); void PageBeginLoading__OnPageBeginLoading_fn(PageBeginLoading* __this, uObject* s, uObject* a); void PageBeginLoading__OnRooted_fn(PageBeginLoading* __this); void PageBeginLoading__OnUnrooted_fn(PageBeginLoading* __this); struct PageBeginLoading : ::g::Fuse::Triggers::Trigger { uStrong<uObject*> _webView; void ctor_5(); void OnPageBeginLoading(uObject* s, uObject* a); static PageBeginLoading* New2(); }; // } }}} // ::g::Fuse::Triggers
[ "cowodbs156@gmail.com" ]
cowodbs156@gmail.com
c403ed8ef2082eda2945731c01c2833d66edf2c7
3209dbda26b87b132768f877122723abcae486e9
/test/initialize_1.cpp
c88766a1cf1a54999936036d38369e0dcd7330ab
[ "BSL-1.0" ]
permissive
rileylev/tuplet
2e12c8f35237dd1b4030a37c3ef9720474c2eb67
e522d62f2e5d701921fb6658230be0f76223b071
refs/heads/main
2023-08-14T18:25:51.897020
2021-10-02T05:13:38
2021-10-02T05:13:47
413,645,538
3
0
null
null
null
null
UTF-8
C++
false
false
706
cpp
#include <cstdio> #include <string> #include <tuplet/tuple.hpp> bool is_good(int a, int b, std::string c) { return a == 1 && b == 2 && c == "Hello, world!"; } int main() { auto tup = tuplet::tuple {1, 2, std::string("Hello, world!")}; static_assert( std::is_same_v<std::tuple_element_t<0, decltype(tup)>, int>, "Expected int& at element 0"); static_assert( std::is_same_v<std::tuple_element_t<1, decltype(tup)>, int>, "Expected int& at element 1"); static_assert( std::is_same_v<std::tuple_element_t<2, decltype(tup)>, std::string>, "Expected std::string& at element 2"); return !is_good(get<0>(tup), get<1>(tup), get<2>(tup)); }
[ "perez.cs@pm.me" ]
perez.cs@pm.me
c441f25792f6a1a65b9a1d42aa10f23ed68b9ea0
8117a3a290a12a8a37282f7a230ab6b730d60c07
/boost/mpl/remove_if.hpp
78125ea06dc29ada33deb88f7017e261bb9eb6e4
[ "BSL-1.0" ]
permissive
fish2000/bx-lexical-cast
4f1e1e7006318e7d26335ce3faddbcec5e53c5f5
8cc5a4da1866546129b703682a1ffb1de7c086db
refs/heads/master
2021-08-30T21:34:31.258340
2017-12-19T13:53:18
2017-12-19T13:53:18
114,752,004
0
0
null
null
null
null
UTF-8
C++
false
false
1,889
hpp
#ifndef BOOST_MPL_REMOVE_IF_HPP_INCLUDED #define BOOST_MPL_REMOVE_IF_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // Copyright David Abrahams 2003-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/fold.hpp> #include <boost/mpl/reverse_fold.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/protect.hpp> #include <boost/mpl/lambda.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/aux_/inserter_algorithm.hpp> namespace bx { namespace mpl { namespace aux { template< typename Pred, typename InsertOp > struct remove_if_helper { template< typename Sequence, typename U > struct apply { typedef typename eval_if< typename apply1<Pred,U>::type , identity<Sequence> , apply2<InsertOp,Sequence,U> >::type type; }; }; template< typename Sequence , typename Predicate , typename Inserter > struct remove_if_impl : fold< Sequence , typename Inserter::state , protect< aux::remove_if_helper< typename lambda<Predicate>::type , typename Inserter::operation > > > { }; template< typename Sequence , typename Predicate , typename Inserter > struct reverse_remove_if_impl : reverse_fold< Sequence , typename Inserter::state , protect< aux::remove_if_helper< typename lambda<Predicate>::type , typename Inserter::operation > > > { }; } // namespace aux BOOST_MPL_AUX_INSERTER_ALGORITHM_DEF(3, remove_if) }} #endif // BOOST_MPL_REMOVE_IF_HPP_INCLUDED
[ "fish2000@gmail.com" ]
fish2000@gmail.com
e2279a771c2bd099c64fbbb10d0bd16ff33ac07b
24f8c1bc84049310ade1ecdea8d041f5aff94bd8
/C++17/idioms/global_variables_in_headers/file1.cpp
e62c6257a163cc591fe192b14b8522ab4f12c29f
[]
no_license
BartVandewoestyne/Cpp
f10d709aed4bbe03b3cca1778ef8f5b7ec554c54
055d3fc61922a29657f48241defcaba744f43d0f
refs/heads/master
2023-08-22T19:42:32.516681
2023-08-03T21:58:02
2023-08-03T21:58:02
4,518,426
126
17
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include "constants.h" #include <iostream> void printFromFile1() { std::cout << "In translation unit 1:" << std::endl; std::cout << " &ci1 = " << &ci1 << std::endl; std::cout << " &ci2 = " << &ci2 << std::endl; std::cout << " &sci1 = " << &sci1 << std::endl; std::cout << " &sci2 = " << &sci2 << std::endl; std::cout << " &x1 = " << &x1 << std::endl; }
[ "Bart.Vandewoestyne@telenet.be" ]
Bart.Vandewoestyne@telenet.be
9661affda1b9c96b7b90d803e42c3043da8c76f8
ce71ba08e9094a4d76c8cc1e0cc7891ae016ff60
/Lib/Chip/CM4/STMicro/STM32F3x4/GPIOA.hpp
cf52ed5deab5f19e608c1bb46d8e5e6009fc6c5c
[ "Apache-2.0" ]
permissive
operativeF/Kvasir
9bfe25e1844d41ffefe527f16117c618af50cde9
dfbcbdc9993d326ef8cc73d99129e78459c561fd
refs/heads/master
2020-04-06T13:12:59.381009
2019-01-25T18:43:17
2019-01-25T18:43:17
157,489,295
0
0
Apache-2.0
2018-11-14T04:12:05
2018-11-14T04:12:04
null
UTF-8
C++
false
false
33,653
hpp
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //General-purpose I/Os namespace GpioaModer{ ///<GPIO port mode register using Addr = Register::Address<0x48000000,0x00000000,0x00000000,std::uint32_t>; ///Port x configuration bits (y =0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> moder15{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> moder14{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,26),Register::ReadWriteAccess,unsigned> moder13{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,unsigned> moder12{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> moder11{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> moder10{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,unsigned> moder9{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> moder8{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> moder7{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,12),Register::ReadWriteAccess,unsigned> moder6{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> moder5{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> moder4{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> moder3{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> moder2{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> moder1{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> moder0{}; } namespace GpioaOtyper{ ///<GPIO port output type register using Addr = Register::Address<0x48000004,0xffff0000,0x00000000,std::uint32_t>; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> ot15{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> ot14{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> ot13{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> ot12{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> ot11{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> ot10{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> ot9{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> ot8{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> ot7{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> ot6{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> ot5{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ot4{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> ot3{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> ot2{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> ot1{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> ot0{}; } namespace GpioaOspeedr{ ///<GPIO port output speed register using Addr = Register::Address<0x48000008,0x00000000,0x00000000,std::uint32_t>; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> ospeedr15{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> ospeedr14{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,26),Register::ReadWriteAccess,unsigned> ospeedr13{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,unsigned> ospeedr12{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> ospeedr11{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> ospeedr10{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,unsigned> ospeedr9{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> ospeedr8{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> ospeedr7{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,12),Register::ReadWriteAccess,unsigned> ospeedr6{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> ospeedr5{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> ospeedr4{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> ospeedr3{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> ospeedr2{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> ospeedr1{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> ospeedr0{}; } namespace GpioaPupdr{ ///<GPIO port pull-up/pull-down register using Addr = Register::Address<0x4800000c,0x00000000,0x00000000,std::uint32_t>; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,30),Register::ReadWriteAccess,unsigned> pupdr15{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,28),Register::ReadWriteAccess,unsigned> pupdr14{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,26),Register::ReadWriteAccess,unsigned> pupdr13{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,24),Register::ReadWriteAccess,unsigned> pupdr12{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,22),Register::ReadWriteAccess,unsigned> pupdr11{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,20),Register::ReadWriteAccess,unsigned> pupdr10{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,18),Register::ReadWriteAccess,unsigned> pupdr9{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,16),Register::ReadWriteAccess,unsigned> pupdr8{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,14),Register::ReadWriteAccess,unsigned> pupdr7{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,12),Register::ReadWriteAccess,unsigned> pupdr6{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,10),Register::ReadWriteAccess,unsigned> pupdr5{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,8),Register::ReadWriteAccess,unsigned> pupdr4{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,6),Register::ReadWriteAccess,unsigned> pupdr3{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,4),Register::ReadWriteAccess,unsigned> pupdr2{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> pupdr1{}; ///Port x configuration bits (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,unsigned> pupdr0{}; } namespace GpioaIdr{ ///<GPIO port input data register using Addr = Register::Address<0x48000010,0xffff0000,0x00000000,std::uint32_t>; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> idr15{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> idr14{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> idr13{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> idr12{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> idr11{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> idr10{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> idr9{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> idr8{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> idr7{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> idr6{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> idr5{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> idr4{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> idr3{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> idr2{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> idr1{}; ///Port input data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> idr0{}; } namespace GpioaOdr{ ///<GPIO port output data register using Addr = Register::Address<0x48000014,0xffff0000,0x00000000,std::uint32_t>; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> odr15{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> odr14{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> odr13{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> odr12{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> odr11{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> odr10{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> odr9{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> odr8{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> odr7{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> odr6{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> odr5{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> odr4{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> odr3{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> odr2{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> odr1{}; ///Port output data (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> odr0{}; } namespace GpioaBsrr{ ///<GPIO port bit set/reset register using Addr = Register::Address<0x48000018,0x00000000,0x00000000,std::uint32_t>; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> br15{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> br14{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> br13{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> br12{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> br11{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> br10{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> br9{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> br8{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> br7{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> br6{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> br5{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> br4{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> br3{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> br2{}; ///Port x reset bit y (y = 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> br1{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> br0{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> bs15{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> bs14{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> bs13{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> bs12{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> bs11{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> bs10{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> bs9{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> bs8{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> bs7{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> bs6{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> bs5{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> bs4{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> bs3{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> bs2{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> bs1{}; ///Port x set bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> bs0{}; } namespace GpioaLckr{ ///<GPIO port configuration lock register using Addr = Register::Address<0x4800001c,0xfffe0000,0x00000000,std::uint32_t>; ///Lok Key constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> lckk{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> lck15{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> lck14{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> lck13{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> lck12{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> lck11{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> lck10{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> lck9{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> lck8{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> lck7{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> lck6{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> lck5{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> lck4{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> lck3{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> lck2{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> lck1{}; ///Port x lock bit y (y= 0..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> lck0{}; } namespace GpioaAfrl{ ///<GPIO alternate function low register using Addr = Register::Address<0x48000020,0x00000000,0x00000000,std::uint32_t>; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::ReadWriteAccess,unsigned> afrl7{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> afrl6{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::ReadWriteAccess,unsigned> afrl5{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> afrl4{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,12),Register::ReadWriteAccess,unsigned> afrl3{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> afrl2{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> afrl1{}; ///Alternate function selection for port x bit y (y = 0..7) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> afrl0{}; } namespace GpioaAfrh{ ///<GPIO alternate function high register using Addr = Register::Address<0x48000024,0x00000000,0x00000000,std::uint32_t>; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,28),Register::ReadWriteAccess,unsigned> afrh15{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,24),Register::ReadWriteAccess,unsigned> afrh14{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,20),Register::ReadWriteAccess,unsigned> afrh13{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,unsigned> afrh12{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,12),Register::ReadWriteAccess,unsigned> afrh11{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,8),Register::ReadWriteAccess,unsigned> afrh10{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,4),Register::ReadWriteAccess,unsigned> afrh9{}; ///Alternate function selection for port x bit y (y = 8..15) constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,0),Register::ReadWriteAccess,unsigned> afrh8{}; } namespace GpioaBrr{ ///<Port bit reset register using Addr = Register::Address<0x48000028,0xffff0000,0x00000000,std::uint32_t>; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> br0{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> br1{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> br2{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> br3{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> br4{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> br5{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> br6{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> br7{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> br8{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> br9{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> br10{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> br11{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> br12{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> br13{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> br14{}; ///Port x Reset bit y constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> br15{}; } }
[ "thomas@dwarfcraft.com" ]
thomas@dwarfcraft.com
c30418b32df94c55061b0dbc9217e6b9a38f4852
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/multimedia/dshow/filters/lin21dec/l21dgdi.h
272d32f8dd508a246a55cf8042741bb015e2a471
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
7,243
h
// Copyright (c) 1998 Microsoft Corporation. All Rights Reserved. // // L21DGDI.h: Line 21 Decoder GDI-related base class code // #ifndef _INC_L21DGDI_H #define _INC_L21DGDI_H // // Forward declarations // class CGDIWork ; // // We start with 8x12 pixel chars by default // #ifndef __DEFAULTCHARSIZE_DEFINED #define __DEFAULTCHARSIZE_DEFINED #define DEFAULT_CHAR_WIDTH 8 #define DEFAULT_CHAR_HEIGHT 12 #endif // __DEFAULTCHARSIZE_DEFINED // #define TEST // // CGDIWork: class for GDI details to print caption text to output bitmap // class CGDIWork { public: CGDIWork(void) ; ~CGDIWork(void) ; BOOL InitFont(void) ; void InitColorNLastChar(void) ; DWORD GetPaletteForFormat(LPBITMAPINFOHEADER lpbmih) ; inline void SetOutputBuffer(LPBYTE lpbOut) { m_bNewOutBuffer = m_lpbOutBuffer != lpbOut ; // Changed? m_lpbOutBuffer = lpbOut ; } ; void SetColorFiller(void) ; void FillOutputBuffer(void) ; HRESULT GetDefaultFormatInfo(LPBITMAPINFO lpbmi, DWORD *pdwSize) ; HRESULT GetOutputFormat(LPBITMAPINFOHEADER lpbmih) ; HRESULT GetOutputOutFormat(LPBITMAPINFOHEADER lpbmih) ; HRESULT SetOutputOutFormat(LPBITMAPINFO lpbmi) ; HRESULT SetOutputInFormat(LPBITMAPINFO lpbmi) ; inline void GetBackgroundColor(DWORD *pdwPhysColor) { *pdwPhysColor = m_dwPhysColor ; } ; BOOL SetBackgroundColor(DWORD dwPhysColor) ; inline BOOL GetBackgroundOpaque(void) { return m_bOpaque ; } ; inline void SetBackgroundOpaque(BOOL bOpaque) { m_bOpaque = bOpaque ; } ; inline UINT GetCharHeight(void) { return m_uCharHeight ; } ; inline int GetScrollStep(void) { return m_iScrollStep ; } ; BOOL CreateOutputDC(void) ; BOOL DeleteOutputDC(void) ; void DrawLeadingSpace(int iLine, int iCol) ; void WriteChar(int iLine, int iCol, CCaptionChar& cc) ; inline BOOL IsNewIntBuffer(void) { return m_bNewIntBuffer ; } ; inline BOOL IsNewOutBuffer(void) { return m_bNewOutBuffer ; } ; inline BOOL IsBitmapDirty(void) { return m_bBitmapDirty ; } ; void ClearInternalBuffer(void) ; inline void ClearNewIntBufferFlag(void) { m_bNewIntBuffer = FALSE ; } ; inline void ClearNewOutBufferFlag(void) { m_bNewOutBuffer = FALSE ; } ; inline void ClearBitmapDirtyFlag(void) { m_bBitmapDirty = FALSE ; } ; void CopyLine(int iSrcLine, int iSrcOffset, int iDestLine, int iDestOffset, UINT uNumScanLines = 0xFF) ; inline BOOL IsTTFont(void) { return m_bUseTTFont ; } ; inline BOOL IsOutDIBClear(void) { return m_bOutDIBClear ; } ; BOOL IsSizeOK(LPBITMAPINFOHEADER lpbmih) ; inline BOOL IsOutputInverted(void) { return m_bOutputInverted ; } ; void GetOutputLines(int iDestLine, RECT *prectLine) ; private: // private data CCritSec m_csL21DGDI ; // to serialize actions on internal DIB secn #ifdef TEST HDC m_hDCTest ; // a DC on the desktop just for testing #endif // TEST HDC m_hDCInt ; // an HDC for output (attached to a DIBSection) BOOL m_bDCInited ; // DC is ready for real output (DIB section created) LPBYTE m_lpbOutBuffer ; // output sample buffer pointer LPBYTE m_lpbIntBuffer ; // memory buffer of output DIBSection HBITMAP m_hBmpInt ; // bitmap for output DIBSection HBITMAP m_hBmpIntOrig ; // original bitmap for output DIBSection LPBITMAPINFO m_lpBMIOut ; // BITMAPINFO for output from downstream filter LPBITMAPINFO m_lpBMIIn ; // BITMAPINFO for output from upstream filter UINT m_uBMIOutSize ; // bytes for BMI data from downstream UINT m_uBMIInSize ; // bytes for BMI data from upstream LONG m_lWidth ; // currently set output width LONG m_lHeight ; // currently set output height int m_iBorderPercent ;// current border percent (10 or 20) DWORD m_dwPhysColor ; // bkgrnd physical color for output bitmap BYTE m_abColorFiller[12] ; // filler to be applied for fast color keying BOOL m_bOpaque ; // should caption background be opaque? BOOL m_bBitmapDirty ; // new output content has been written on DIBSection BOOL m_bNewIntBuffer ; // new DIB section created BOOL m_bNewOutBuffer ; // new output sample buffer BOOL m_bOutputInverted ; // output right side up for -ve height BOOL m_bUseTTFont ; // TT font (Lucida Console) available; use that HFONT m_hFontDef ; // default font (white, normal) to use HFONT m_hFontSpl ; // font with any specialty (italics, underline etc.) HFONT m_hFontOrig ; // original font that came with the DC LOGFONT m_lfChar ; // LOGFONT struct for quick font create BOOL m_bUseSplFont ; // Is special font being used now? BOOL m_bFontSizeOK ; // are font sizes OK? Otherwise we don't draw UINT m_uCharWidth ; // width of each caption char in pixels UINT m_uCharHeight ; // height of each caption char in pixels int m_iScrollStep ; // # scanlines to scroll by in each step UINT m_uIntBmpWidth ; // width of internal output bitmap in pixels UINT m_uIntBmpHeight ; // height of internal output bitmap in pixels UINT m_uHorzOffset ; // pixels to be left from the left UINT m_uVertOffset ; // pixels to be left from the top UINT m_uBytesPerPixel ;// bytes for each pixel of output (based on bpp) UINT m_uBytesPerSrcScanLine ; // bytes for each source scan line's data UINT m_uBytesPerDestScanLine ;// bytes for each destn scan line's data CCaptionChar m_ccLast ; // last caption char and attribs printed COLORREF m_acrFGColors[7] ;// 7 colors from white to magenta UINT m_uColorIndex ; // index of currently used color BOOL m_bOutDIBClear ; // Is output DIB secn clean? #ifdef PERF int m_idClearIntBuff ; int m_idClearOutBuff ; #endif // PERF private: // private helper methods bool InitBMIData(void) ; static int CALLBACK EnumFontProc(ENUMLOGFONTEX *lpELFE, NEWTEXTMETRIC *lpNTM, int iFontType, LPARAM lParam) ; void CheckTTFont(void) ; void ChangeFont(BOOL bItalics, BOOL bUnderline) ; void ChangeFontSize(UINT uCharWidth, UINT uCharHeight) ; void ChangeColor(int iColor) ; BOOL SetOutputSize(LONG lWidth, LONG lHeight) ; BOOL SetCharNBmpSize(void) ; void SetNumBytesValues(void) ; void SetDefaultKeyColor(LPBITMAPINFOHEADER lpbmih) ; DWORD GetOwnPalette(int iNumEntries, PALETTEENTRY *ppe) ; BOOL CharSizeFromOutputSize(LONG lOutWidth, LONG lOutHeight, int *piCharWidth, int *piCharHeight) ; } ; #endif _INC_L21DGDI_H
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
986f223eba5e588c8a5e19f6910ebad0e4b26029
c49e02dbb5392cb1ea841d5ee1a0309ea6b5b86f
/include/algorithms/neural_networks/layers/convolution2d/convolution2d_layer_types.h
b03fe98fbfc0438f309c66919e6f76cfce9daf5d
[ "Intel", "Apache-2.0" ]
permissive
apnavik/daal
faa6f012a68623f34e970bcf309f121097da05f7
3a01b33aa3feb8994c7940116c5a3b4f101f0c04
refs/heads/master
2020-08-02T04:40:23.284552
2019-10-07T06:17:39
2019-10-07T06:17:39
201,421,484
0
0
Apache-2.0
2019-08-09T08:04:29
2019-08-09T08:04:27
null
UTF-8
C++
false
false
6,002
h
/* file: convolution2d_layer_types.h */ /******************************************************************************* * Copyright 2014-2019 Intel Corporation * * 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. *******************************************************************************/ /* //++ // Two-dimensional (2D) convolution layer parameter structure. //-- */ #ifndef __CONVOLUTION2D_LAYER_TYPES_H__ #define __CONVOLUTION2D_LAYER_TYPES_H__ #include "algorithms/algorithm.h" #include "data_management/data/tensor.h" #include "data_management/data/homogen_tensor.h" #include "services/daal_defines.h" #include "algorithms/neural_networks/layers/layer_types.h" namespace daal { namespace algorithms { namespace neural_networks { namespace layers { /** * @defgroup convolution2d Two-dimensional Convolution Layer * \copydoc daal::algorithms::neural_networks::layers::convolution2d * @ingroup layers * @{ */ namespace convolution2d { /** * <a name="DAAL-ENUM-ALGORITHMS__NEURAL_NETWORKS__LAYERS__CONVOLUTION2D__METHOD"></a> * Available methods to compute forward and backward 2D convolution layer */ enum Method { defaultDense = 0, /*!< Default: performance-oriented method. */ }; /** * Available identifiers of results of the forward 2D convolution layer * and input objects for the backward 2D convolution layer */ enum LayerDataId { auxData, /*!< Data processed at the forward stage of the layer */ auxWeights, /*!< Input weights for forward stage of the layer */ lastLayerDataId = auxWeights }; /** * <a name="DAAL-STRUCT-ALGORITHMS__NEURAL_NETWORKS__LAYERS__CONVOLUTION2D__KERNELSIZE"></a> * \brief Data structure representing the size of the two-dimensional kernel subtensor */ struct KernelSizes { /** * Constructs the structure representing the size of the two-dimensional kernel subtensor * \param[in] first Size of the first dimension of the two-dimensional kernel subtensor * \param[in] second Size of the second dimension of the wto-dimensional kernel subtensor */ KernelSizes(size_t first, size_t second) { size[0] = first; size[1] = second; } size_t size[2]; }; /** * <a name="DAAL-STRUCT-ALGORITHMS__NEURAL_NETWORKS__LAYERS__CONVOLUTION2D__STRIDE"></a> * \brief Data structure representing the intervals on which the subtensors for 2D convolution are selected */ struct Strides { /** * Constructs the structure representing the intervals on which the subtensors for 2D convolution are selected * \param[in] first Interval over the first dimension on which the 2D convolution is performed * \param[in] second Interval over the second dimension on which the 2D convolution is performed */ Strides(size_t first, size_t second) { size[0] = first; size[1] = second; } size_t size[2]; }; /** * <a name="DAAL-STRUCT-ALGORITHMS__NEURAL_NETWORKS__LAYERS__CONVOLUTION2D__PADDING"></a> * \brief Data structure representing the number of data elements to implicitly add * to each size of the two-dimensional subtensor on which 2D convolution is performed */ struct Paddings { /** * Constructs the structure representing the number of data elements to implicitly add * to each size of the two-dimensional subtensor on which 2D convolution is performed * \param[in] first Number of data elements to add to the the first dimension of the two-dimensional subtensor * \param[in] second Number of data elements to add to the the second dimension of the two-dimensional subtensor */ Paddings(int first, int second) { size[0] = first; size[1] = second; } int size[2]; }; /** * <a name="DAAL-STRUCT-ALGORITHMS__NEURAL_NETWORKS__LAYERS__CONVOLUTION2D__SPATIALDIMENSIONS"></a> * \brief Data structure representing the indices of the two dimensions on which 2D convolution is performed */ struct Indices { /** * Constructs the structure representing the indices of the two dimensions on which 2D convolution is performed * \param[in] first The first dimension index * \param[in] second The second dimension index */ Indices(size_t first, size_t second) { dims[0] = first; dims[1] = second; } size_t dims[2]; }; namespace interface1 { /** * <a name="DAAL-CLASS-ALGORITHMS__NEURAL_NETWORKS__LAYERS__CONVOLUTION2D__PARAMETER"></a> * \brief 2D convolution layer parameters */ class DAAL_EXPORT Parameter: public layers::Parameter { public: /** * Default constructor */ Parameter(); Indices indices; /*!< Data structure representing the dimension for convolution kernels. (2,3) is supported now */ size_t groupDimension; /*!< Dimension for which the grouping is applied. groupDimension=1 is supported now */ KernelSizes kernelSizes; /*!< Data structure representing the sizes of the two-dimensional kernel subtensor */ Strides strides; /*!< Data structure representing the intervals on which the kernel should be applied to the input */ Paddings paddings; /*!< Data structure representing the number of data to be implicitly added to the subtensor */ size_t nKernels; /*!< Number of kernels applied to the input layer data */ size_t nGroups; /*!< Number of groups which the input data is split in groupDimension dimension */ }; } // namespace interface1 using interface1::Parameter; } // namespace convolution2d /** @} */ } // namespace layers } // namespace neural_networks } // namespace algorithms } // namespace daal #endif
[ "nikolay.a.petrov@intel.com" ]
nikolay.a.petrov@intel.com
e27ffbfbd46a1c2108b94547c76dbc6875294206
881b39830d6e904b6390dd7598929686b145ddd5
/tokens/main.cpp
49fc14007cd9dd7ac55a4427928ed052f88ba87d
[]
no_license
rajatsaxena035/Compiler-Design-Lab
786bbf108e9a16d4b72bf78019296cf06f3ea0f7
7b9f6f7546acdec2f425646082cf7f76a2e08625
refs/heads/master
2020-12-30T13:28:36.112671
2017-05-14T05:31:54
2017-05-14T05:31:54
91,221,743
0
0
null
null
null
null
UTF-8
C++
false
false
1,618
cpp
#include <iostream> #include <string> using namespace std; int token(string t) { if(t=="{" || t=="(") return "Left Parenthesis"; else if(t=="}" || t==")") return "Right Parenthesis"; else if(t=="=") return "Assignment Operator"; else if(t=="+") else if(t=="-") else if(t=="/") else if(t=="*") else if(t=="%") else if(t=="==") else if(t=="!=") else if(t==">") else if(t=="<") else if(t==">=") else if(t=="<=") else if(t==";") else { } } int main() { string exp[100]; int len,i; string keywords[]= {"alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "const", "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for","friend", "goto", "if", "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected public", "register", "reinterpret_cast","return","short","signed","sizeof","static","static_assert","static_cast","struct", "switch", "template", "this","thread_local","throw","true","try","typedef","typeid","typename","union","unsigned", "using","virtual","void", "volatile","wchar_t","while","xor","xor_eq"}; cout << "Enter the expression : " << endl; cin >> exp; len = exp.size(); for(i=0;i<len;i++) { cout << token(exp[i]); } return 0; }
[ "rajat.saxena035@gmail.com" ]
rajat.saxena035@gmail.com
27afbce03b53415951c101fda8a1a099d61742b5
dc2e278726cdc50355cf4cf27d975bd39a935b42
/abc068_a.cpp
2ca6af73b993b368aaa69a62b2f7d33786dcda4c
[]
no_license
yongwhan/atcoder
dfb2a81e17b7841436e96928c7b583b2023225e3
7612e6f2ce235730a6390fbe1d8e67d795f5fe8b
refs/heads/master
2020-11-28T02:08:46.930143
2019-12-23T04:33:41
2019-12-23T04:33:41
229,676,591
0
0
null
null
null
null
UTF-8
C++
false
false
221
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> ii; int main() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); int n; cin>>n; cout << "ABC" << n << endl; return 0; }
[ "yongwhan@yongwhan-macbookpro.roam.corp.google.com" ]
yongwhan@yongwhan-macbookpro.roam.corp.google.com
1c88f967d152c32a429e67623458150f481806c1
af55bd057a76a6bf9122dd74358813ff3408efcc
/Flow3D/Flow3D/src/Flow3D/Collision/AABB.hpp
41158e803dbf8c79f3bc37dc7091d853cedbe2eb
[ "MIT" ]
permissive
florianvoelkers/Flow3D
217a2ba3934ca6e7181de36c8acbb94eedc6b0f9
017d2f321f943dfecc360bec9fc6f17c77ffde68
refs/heads/master
2020-05-06T13:21:25.457151
2019-12-18T11:50:39
2019-12-18T11:50:39
180,131,059
3
3
null
null
null
null
UTF-8
C++
false
false
458
hpp
#pragma once #include "Flow3D/Math.hpp" #include "IntersectData.hpp" class AABB { public: AABB(const Vec3& minExtents, const Vec3& maxExtents) : m_MinExtents(minExtents), m_MaxExtents(maxExtents) {} IntersectData IntersectAABB(const AABB& other) const; inline const Vec3& GetMinExtents() const { return m_MinExtents; } inline const Vec3& GetMaxExtents() const { return m_MaxExtents; } private: const Vec3 m_MinExtents; const Vec3 m_MaxExtents; };
[ "florian.voelkers@mail.de" ]
florian.voelkers@mail.de
89da11305476f5af6241efea265a0a6a5a19ae59
09e5cfe06e437989a2ccf2aeecb9c73eb998a36c
/build/gltbx/gl_functions_01_bpl.cpp
139a2092860a34d8e26d521a271c2ba09c041c5c
[ "BSD-3-Clause" ]
permissive
jorgediazjr/dials-dev20191018
b81b19653624cee39207b7cefb8dfcb2e99b79eb
77d66c719b5746f37af51ad593e2941ed6fbba17
refs/heads/master
2020-08-21T02:48:54.719532
2020-01-25T01:41:37
2020-01-25T01:41:37
216,089,955
0
1
BSD-3-Clause
2020-01-25T01:41:39
2019-10-18T19:03:17
Python
UTF-8
C++
false
false
11,153
cpp
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: gltbx.generate_functions_bpl */ #include <gltbx/special_wrapper_support.h> #include <gltbx/pointer_args_bpl.h> #include <gltbx/error.h> namespace gltbx { namespace gl { namespace { void gl_Color3i( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue) { boost::python::extract<GLint> red_proxy(py_red); GLint red = red_proxy(); boost::python::extract<GLint> green_proxy(py_green); GLint green = green_proxy(); boost::python::extract<GLint> blue_proxy(py_blue); GLint blue = blue_proxy(); glColor3i(red, green, blue); } void gl_Color3s( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue) { boost::python::extract<GLshort> red_proxy(py_red); GLshort red = red_proxy(); boost::python::extract<GLshort> green_proxy(py_green); GLshort green = green_proxy(); boost::python::extract<GLshort> blue_proxy(py_blue); GLshort blue = blue_proxy(); glColor3s(red, green, blue); } void gl_Color3ub( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue) { boost::python::extract<GLubyte> red_proxy(py_red); GLubyte red = red_proxy(); boost::python::extract<GLubyte> green_proxy(py_green); GLubyte green = green_proxy(); boost::python::extract<GLubyte> blue_proxy(py_blue); GLubyte blue = blue_proxy(); glColor3ub(red, green, blue); } void gl_Color3ui( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue) { boost::python::extract<GLuint> red_proxy(py_red); GLuint red = red_proxy(); boost::python::extract<GLuint> green_proxy(py_green); GLuint green = green_proxy(); boost::python::extract<GLuint> blue_proxy(py_blue); GLuint blue = blue_proxy(); glColor3ui(red, green, blue); } void gl_Color3us( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue) { boost::python::extract<GLushort> red_proxy(py_red); GLushort red = red_proxy(); boost::python::extract<GLushort> green_proxy(py_green); GLushort green = green_proxy(); boost::python::extract<GLushort> blue_proxy(py_blue); GLushort blue = blue_proxy(); glColor3us(red, green, blue); } void gl_Color4b( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLbyte> red_proxy(py_red); GLbyte red = red_proxy(); boost::python::extract<GLbyte> green_proxy(py_green); GLbyte green = green_proxy(); boost::python::extract<GLbyte> blue_proxy(py_blue); GLbyte blue = blue_proxy(); boost::python::extract<GLbyte> alpha_proxy(py_alpha); GLbyte alpha = alpha_proxy(); glColor4b(red, green, blue, alpha); } void gl_Color4d( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLdouble> red_proxy(py_red); GLdouble red = red_proxy(); boost::python::extract<GLdouble> green_proxy(py_green); GLdouble green = green_proxy(); boost::python::extract<GLdouble> blue_proxy(py_blue); GLdouble blue = blue_proxy(); boost::python::extract<GLdouble> alpha_proxy(py_alpha); GLdouble alpha = alpha_proxy(); glColor4d(red, green, blue, alpha); } void gl_Color4f( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLfloat> red_proxy(py_red); GLfloat red = red_proxy(); boost::python::extract<GLfloat> green_proxy(py_green); GLfloat green = green_proxy(); boost::python::extract<GLfloat> blue_proxy(py_blue); GLfloat blue = blue_proxy(); boost::python::extract<GLfloat> alpha_proxy(py_alpha); GLfloat alpha = alpha_proxy(); glColor4f(red, green, blue, alpha); } void gl_Color4i( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLint> red_proxy(py_red); GLint red = red_proxy(); boost::python::extract<GLint> green_proxy(py_green); GLint green = green_proxy(); boost::python::extract<GLint> blue_proxy(py_blue); GLint blue = blue_proxy(); boost::python::extract<GLint> alpha_proxy(py_alpha); GLint alpha = alpha_proxy(); glColor4i(red, green, blue, alpha); } void gl_Color4s( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLshort> red_proxy(py_red); GLshort red = red_proxy(); boost::python::extract<GLshort> green_proxy(py_green); GLshort green = green_proxy(); boost::python::extract<GLshort> blue_proxy(py_blue); GLshort blue = blue_proxy(); boost::python::extract<GLshort> alpha_proxy(py_alpha); GLshort alpha = alpha_proxy(); glColor4s(red, green, blue, alpha); } void gl_Color4ub( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLubyte> red_proxy(py_red); GLubyte red = red_proxy(); boost::python::extract<GLubyte> green_proxy(py_green); GLubyte green = green_proxy(); boost::python::extract<GLubyte> blue_proxy(py_blue); GLubyte blue = blue_proxy(); boost::python::extract<GLubyte> alpha_proxy(py_alpha); GLubyte alpha = alpha_proxy(); glColor4ub(red, green, blue, alpha); } void gl_Color4ui( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLuint> red_proxy(py_red); GLuint red = red_proxy(); boost::python::extract<GLuint> green_proxy(py_green); GLuint green = green_proxy(); boost::python::extract<GLuint> blue_proxy(py_blue); GLuint blue = blue_proxy(); boost::python::extract<GLuint> alpha_proxy(py_alpha); GLuint alpha = alpha_proxy(); glColor4ui(red, green, blue, alpha); } void gl_Color4us( boost::python::object const& py_red, boost::python::object const& py_green, boost::python::object const& py_blue, boost::python::object const& py_alpha) { boost::python::extract<GLushort> red_proxy(py_red); GLushort red = red_proxy(); boost::python::extract<GLushort> green_proxy(py_green); GLushort green = green_proxy(); boost::python::extract<GLushort> blue_proxy(py_blue); GLushort blue = blue_proxy(); boost::python::extract<GLushort> alpha_proxy(py_alpha); GLushort alpha = alpha_proxy(); glColor4us(red, green, blue, alpha); } void gl_Color3bv( boost::python::object const& py_v) { boost_python::converter_str<GLbyte> v_proxy( "v", py_v, 3, true); const GLbyte* v = v_proxy.get(); glColor3bv(v); } void gl_Color3dv( boost::python::object const& py_v) { boost_python::converter<GLdouble> v_proxy( "v", py_v, 3, true); const GLdouble* v = v_proxy.get(); glColor3dv(v); } void gl_Color3fv( boost::python::object const& py_v) { boost_python::converter<GLfloat> v_proxy( "v", py_v, 3, true); const GLfloat* v = v_proxy.get(); glColor3fv(v); } void gl_Color3iv( boost::python::object const& py_v) { boost_python::converter<GLint> v_proxy( "v", py_v, 3, true); const GLint* v = v_proxy.get(); glColor3iv(v); } void gl_Color3sv( boost::python::object const& py_v) { boost_python::converter<GLshort> v_proxy( "v", py_v, 3, true); const GLshort* v = v_proxy.get(); glColor3sv(v); } void gl_Color3ubv( boost::python::object const& py_v) { boost_python::converter_str<GLubyte> v_proxy( "v", py_v, 3, true); const GLubyte* v = v_proxy.get(); glColor3ubv(v); } void gl_Color3uiv( boost::python::object const& py_v) { boost_python::converter<GLuint> v_proxy( "v", py_v, 3, true); const GLuint* v = v_proxy.get(); glColor3uiv(v); } void gl_Color3usv( boost::python::object const& py_v) { boost_python::converter<GLushort> v_proxy( "v", py_v, 3, true); const GLushort* v = v_proxy.get(); glColor3usv(v); } void gl_Color4bv( boost::python::object const& py_v) { boost_python::converter_str<GLbyte> v_proxy( "v", py_v, 4, true); const GLbyte* v = v_proxy.get(); glColor4bv(v); } } // namespace <anonymous> namespace boost_python { void wrap_functions_01() { using namespace boost::python; def("glColor3i", gl_Color3i, ( arg("red"), arg("green"), arg("blue"))); def("glColor3s", gl_Color3s, ( arg("red"), arg("green"), arg("blue"))); def("glColor3ub", gl_Color3ub, ( arg("red"), arg("green"), arg("blue"))); def("glColor3ui", gl_Color3ui, ( arg("red"), arg("green"), arg("blue"))); def("glColor3us", gl_Color3us, ( arg("red"), arg("green"), arg("blue"))); def("glColor4b", gl_Color4b, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor4d", gl_Color4d, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor4f", gl_Color4f, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor4i", gl_Color4i, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor4s", gl_Color4s, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor4ub", gl_Color4ub, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor4ui", gl_Color4ui, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor4us", gl_Color4us, ( arg("red"), arg("green"), arg("blue"), arg("alpha"))); def("glColor3bv", gl_Color3bv, ( arg("v"))); def("glColor3dv", gl_Color3dv, ( arg("v"))); def("glColor3fv", gl_Color3fv, ( arg("v"))); def("glColor3iv", gl_Color3iv, ( arg("v"))); def("glColor3sv", gl_Color3sv, ( arg("v"))); def("glColor3ubv", gl_Color3ubv, ( arg("v"))); def("glColor3uiv", gl_Color3uiv, ( arg("v"))); def("glColor3usv", gl_Color3usv, ( arg("v"))); def("glColor4bv", gl_Color4bv, ( arg("v"))); } }}} // namespace gltbx::gl::boost_python
[ "jorge7soccer@gmail.com" ]
jorge7soccer@gmail.com
5bf5a0cdb715ea0f8784c6aa5243ad071d6d2b7b
1f1b4928565732e402b2bf27fa33c6cab8ed8138
/8/exercises/8-2/equal/main.cpp
f0fd5fbbdaeaaa92560c7453f42d8d6036a77b50
[]
no_license
MustaphaRashiduddin/accelerated
68b7b7703e6c79bcd0d583545da7b02a2c1ab089
d768719c20b2db2f399f354e67b8253c14ab3f12
refs/heads/master
2021-08-23T10:42:56.556557
2017-06-24T03:37:01
2017-06-24T03:37:01
113,058,821
0
0
null
null
null
null
UTF-8
C++
false
false
852
cpp
#include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; template <typename inputIterator1, typename inputIterator2> bool equall(inputIterator1 first1, inputIterator1 last1, inputIterator2 first2); int main(int argc, char *argv[]) { int myints[] = {20, 40, 60, 40, 20}; vector<int> myvector(myints, myints+5); if (equall(myints, myints+5, myvector.rbegin())) { cout << "palindrome"; } else { cout << "not palindrome"; } cout << endl; return 0; } template <typename inputIterator1, typename inputIterator2> bool equall(inputIterator1 first1, inputIterator1 last1, inputIterator2 first2) { while (first1 != last1) if (*first1++ != *first2++) return false; return true; }
[ "saif.rashiduddin@gmail.com" ]
saif.rashiduddin@gmail.com
76b23f6843396de7565418540217cc27596ef091
befd896d301d3040fbd6ccda39aa217bf388a0a4
/tensorflow/core/grappler/optimizers/loop_optimizer_test.cc
81f40db8f0b7ec0bc79713493940ad24b2f657b3
[ "Apache-2.0" ]
permissive
mktshhr/tensorflow-theta
98369caf55f676c6ae9a5c82ab151bb53d395f36
fe378e1b690d97ed24bad144dee9efffce893c86
refs/heads/master
2020-03-26T14:29:34.200902
2018-10-21T13:39:56
2018-10-21T13:39:56
144,990,240
5
2
Apache-2.0
2018-10-21T13:39:57
2018-08-16T13:17:25
C++
UTF-8
C++
false
false
35,826
cc
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/optimizers/loop_optimizer.h" #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/grappler/grappler_item.h" #include "tensorflow/core/grappler/inputs/trivial_test_graph_input_yielder.h" #include "tensorflow/core/grappler/utils.h" #include "tensorflow/core/grappler/utils/grappler_test.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace grappler { class LoopOptimizerTest : public GrapplerTest { protected: // These helpers always sets T=DT_FLOAT. void AddEnterNode(const string& name, const string& frame, const bool is_constant, const int piterations, const std::vector<string>& inputs, GraphDef* graph) const { std::vector<std::pair<string, AttrValue>> attributes; AttrValue type; type.set_type(DT_FLOAT); attributes.emplace_back("T", type); AttrValue frame_name; frame_name.set_s(frame); attributes.emplace_back("frame_name", frame_name); AttrValue is_const; is_const.set_b(is_constant); attributes.emplace_back("is_constant", is_const); AttrValue parallel_iterations; parallel_iterations.set_i(piterations); attributes.emplace_back("parallel_iterations", parallel_iterations); AddNode(name, "Enter", inputs, attributes, graph); } void AddSimpleNode(const string& name, const string& op, const std::vector<string>& inputs, GraphDef* graph) const { std::vector<std::pair<string, AttrValue>> attributes; AttrValue type; type.set_type(DT_FLOAT); attributes.emplace_back("T", type); AddNode(name, op, inputs, attributes, graph); } void DisableAllStages(LoopOptimizer* optimizer) { LoopOptimizer::LoopOptimizerOptions options; options.enable_loop_invariant_node_motion = false; options.enable_stack_push_removal = false; optimizer->options_ = options; } void EnableOnlyLoopInvariantNodeMotion(LoopOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.enable_loop_invariant_node_motion = true; } void EnableOnlyStackPushRemoval(LoopOptimizer* optimizer) { DisableAllStages(optimizer); optimizer->options_.enable_stack_push_removal = true; } }; TEST_F(LoopOptimizerTest, Basic) { GraphDef graph; AddSimpleNode("In", "Identity", {}, &graph); AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"}, &graph); AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"}, &graph); AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph); AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph); AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph); AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph); AddSimpleNode("Less", "Less", {"VariantAdd", "Less/y"}, &graph); AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph); AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph); AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph); AddSimpleNode("NextIteration", "NextIteration", {"VariantAdd"}, &graph); AddSimpleNode("Exit", "Exit", {"Switch"}, &graph); AddSimpleNode("Out", "Identity", {"Exit"}, &graph); GrapplerItem item; item.graph = graph; LoopOptimizer optimizer; EnableOnlyLoopInvariantNodeMotion(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::unique_ptr<NodeMap> node_map; std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; node_map.reset(new NodeMap(&graph)); EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).back(), 0); node_map.reset(new NodeMap(&output)); EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 0); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd")).back(), 0); } TEST_F(LoopOptimizerTest, Const) { GraphDef graph; AddSimpleNode("In", "Identity", {}, &graph); AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"}, &graph); AddSimpleNode("Const", "Const", {"^Identity"}, &graph); AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "Const"}, &graph); AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph); AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph); AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph); AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph); AddSimpleNode("Less", "Less", {"VariantAdd", "Less/y"}, &graph); AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph); AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph); AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph); AddSimpleNode("NextIteration", "NextIteration", {"VariantAdd"}, &graph); AddSimpleNode("Exit", "Exit", {"Switch"}, &graph); AddSimpleNode("Out", "Identity", {"Exit"}, &graph); GrapplerItem item; item.graph = graph; LoopOptimizer optimizer; EnableOnlyLoopInvariantNodeMotion(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::unique_ptr<NodeMap> node_map; std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; node_map.reset(new NodeMap(&graph)); EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0); EXPECT_EQ(frames.at(node_map->GetNode("Const")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("Const")).back(), 0); node_map.reset(new NodeMap(&output)); EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 0); EXPECT_EQ(frames.at(node_map->GetNode("Const")).size(), 0); } TEST_F(LoopOptimizerTest, ControlOutput) { GraphDef graph; AddSimpleNode("In", "Identity", {}, &graph); AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"}, &graph); AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"}, &graph); AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph); AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph); AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph); AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph); AddSimpleNode("Less", "Less", {"VariantAdd", "Less/y", "^InvariantAdd"}, &graph); AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph); AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph); AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph); AddSimpleNode("NextIteration", "NextIteration", {"VariantAdd"}, &graph); AddSimpleNode("Exit", "Exit", {"Switch"}, &graph); AddSimpleNode("Out", "Identity", {"Exit"}, &graph); GrapplerItem item; item.graph = graph; LoopOptimizer optimizer; EnableOnlyLoopInvariantNodeMotion(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::unique_ptr<NodeMap> node_map; std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; node_map.reset(new NodeMap(&graph)); EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0); node_map.reset(new NodeMap(&output)); EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0); } TEST_F(LoopOptimizerTest, NestedLoop1) { GraphDef graph; AddSimpleNode("In", "Identity", {}, &graph); AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"}, &graph); AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"}, &graph); AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph); AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph); AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph); AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph); AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph); AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph); AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph); AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph); AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph); AddSimpleNode("Exit", "Exit", {"Switch"}, &graph); AddSimpleNode("Out", "Identity", {"Exit"}, &graph); AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1, {"VariantAdd"}, &graph); AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "InvariantEnter2"}, &graph); AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph); AddEnterNode("VariantEnter2", "while/while/while_context", false, 1, {"VariantEnter"}, &graph); AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph); AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph); AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph); AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph); AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph); AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph); AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph); AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph); GrapplerItem item; item.graph = graph; LoopOptimizer optimizer; EnableOnlyLoopInvariantNodeMotion(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::unique_ptr<NodeMap> node_map; std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; node_map.reset(new NodeMap(&graph)); EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).back(), 0); node_map.reset(new NodeMap(&output)); EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 0); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd")).size(), 0); } TEST_F(LoopOptimizerTest, NestedLoop2) { GraphDef graph; AddSimpleNode("In", "Identity", {}, &graph); AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"}, &graph); AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"}, &graph); AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph); AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph); AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph); AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph); AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph); AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph); AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph); AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph); AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph); AddSimpleNode("Exit", "Exit", {"Switch"}, &graph); AddSimpleNode("Out", "Identity", {"Exit"}, &graph); AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1, {"InvariantAdd"}, &graph); AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "InvariantEnter2"}, &graph); AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph); AddEnterNode("VariantEnter2", "while/while/while_context", false, 1, {"VariantEnter"}, &graph); AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph); AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph); AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph); AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph); AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph); AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph); AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph); AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph); GrapplerItem item; item.graph = graph; LoopOptimizer optimizer; EnableOnlyLoopInvariantNodeMotion(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::unique_ptr<NodeMap> node_map; std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; node_map.reset(new NodeMap(&graph)); EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1); node_map.reset(new NodeMap(&output)); EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 0); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("VariantAdd2")).back(), 1); } TEST_F(LoopOptimizerTest, NestedLoopConst1) { GraphDef graph; AddSimpleNode("In", "Identity", {}, &graph); AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"}, &graph); AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"}, &graph); AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph); AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph); AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph); AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph); AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph); AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph); AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph); AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph); AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph); AddSimpleNode("Exit", "Exit", {"Switch"}, &graph); AddSimpleNode("Out", "Identity", {"Exit"}, &graph); AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1, {"VariantAdd"}, &graph); AddSimpleNode("Const2", "Const", {"^Identity2"}, &graph); AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "Const2"}, &graph); AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph); AddEnterNode("VariantEnter2", "while/while/while_context", false, 1, {"VariantEnter"}, &graph); AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph); AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph); AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph); AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph); AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph); AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph); AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph); AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph); GrapplerItem item; item.graph = graph; LoopOptimizer optimizer; EnableOnlyLoopInvariantNodeMotion(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::unique_ptr<NodeMap> node_map; std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; node_map.reset(new NodeMap(&graph)); EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1); EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("Const2")).back(), 1); node_map.reset(new NodeMap(&output)); EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 0); EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 1); EXPECT_EQ(frames.at(node_map->GetNode("Const2")).back(), 0); } TEST_F(LoopOptimizerTest, NestedLoopConst2) { GraphDef graph; AddSimpleNode("In", "Identity", {}, &graph); AddEnterNode("InvariantEnter", "while/while_context", true, 1, {"In"}, &graph); AddSimpleNode("InvariantAdd", "Add", {"InvariantEnter", "InvariantEnter"}, &graph); AddSimpleNode("VariantAdd", "Add", {"InvariantAdd", "Identity"}, &graph); AddEnterNode("VariantEnter", "while/while_context", false, 1, {"In"}, &graph); AddSimpleNode("Merge", "Merge", {"VariantEnter", "NextIteration"}, &graph); AddSimpleNode("Less/y", "Const", {"^Identity"}, &graph); AddSimpleNode("Less", "Less", {"Exit2", "Less/y"}, &graph); AddSimpleNode("LoopCond", "LoopCond", {"Less"}, &graph); AddSimpleNode("Switch", "Switch", {"Merge", "LoopCond"}, &graph); AddSimpleNode("Identity", "Identity", {"Switch:1"}, &graph); AddSimpleNode("NextIteration", "NextIteration", {"Exit2"}, &graph); AddSimpleNode("Exit", "Exit", {"Switch"}, &graph); AddSimpleNode("Out", "Identity", {"Exit"}, &graph); AddEnterNode("InvariantEnter2", "while/while/while_context", true, 1, {"InvariantAdd"}, &graph); AddSimpleNode("Const2", "Const", {"^Identity2"}, &graph); AddSimpleNode("InvariantAdd2", "Add", {"InvariantEnter2", "Const2"}, &graph); AddSimpleNode("VariantAdd2", "Add", {"InvariantAdd2", "Identity2"}, &graph); AddEnterNode("VariantEnter2", "while/while/while_context", false, 1, {"VariantEnter"}, &graph); AddSimpleNode("Merge2", "Merge", {"VariantEnter2", "NextIteration2"}, &graph); AddSimpleNode("Less2/y", "Const", {"^Identity2"}, &graph); AddSimpleNode("Less2", "Less", {"VariantAdd2", "Less2/y"}, &graph); AddSimpleNode("LoopCond2", "LoopCond", {"Less2"}, &graph); AddSimpleNode("Switch2", "Switch", {"Merge2", "LoopCond2"}, &graph); AddSimpleNode("Identity2", "Identity", {"Switch2:1"}, &graph); AddSimpleNode("NextIteration2", "NextIteration", {"VariantAdd2"}, &graph); AddSimpleNode("Exit2", "Exit", {"Switch2"}, &graph); GrapplerItem item; item.graph = graph; LoopOptimizer optimizer; EnableOnlyLoopInvariantNodeMotion(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::unique_ptr<NodeMap> node_map; std::unordered_map<const NodeDef*, std::vector<int>> frames; int num_frames; node_map.reset(new NodeMap(&graph)); EXPECT_TRUE(IdentifyFrames(graph, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).back(), 1); EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 2); EXPECT_EQ(frames.at(node_map->GetNode("Const2")).back(), 1); node_map.reset(new NodeMap(&output)); EXPECT_TRUE(IdentifyFrames(output, &frames, &num_frames).ok()); EXPECT_EQ(num_frames, 2); EXPECT_EQ(frames.at(node_map->GetNode("InvariantAdd2")).size(), 0); EXPECT_EQ(frames.at(node_map->GetNode("Const2")).size(), 0); } void VerifyGraphsEqual(const GraphDef& original_graph, const GraphDef& optimized_graph, const string& func) { EXPECT_EQ(original_graph.node_size(), optimized_graph.node_size()) << func; for (int i = 0; i < original_graph.node_size(); ++i) { const NodeDef& original = original_graph.node(i); const NodeDef& optimized = optimized_graph.node(i); EXPECT_EQ(original.name(), optimized.name()) << func; EXPECT_EQ(original.op(), optimized.op()) << func; EXPECT_EQ(original.input_size(), optimized.input_size()) << func; for (int j = 0; j < original.input_size(); ++j) { EXPECT_EQ(original.input(j), optimized.input(j)) << func; } } } TEST_F(LoopOptimizerTest, NoOp) { // This trivial graph is so basic there's nothing to optimize. TrivialTestGraphInputYielder fake_input(4, 1, 10, false, {"CPU:0"}); GrapplerItem item; CHECK(fake_input.NextItem(&item)); LoopOptimizer optimizer; EnableOnlyStackPushRemoval(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); VerifyGraphsEqual(item.graph, output, __FUNCTION__); } TEST_F(LoopOptimizerTest, RemovePush_NoOp) { GrapplerItem item; GraphDef& graph = item.graph; AddSimpleNode("c", "Const", {}, &graph); // Stack with corresponding push/pop. AddSimpleNode("stack1", "StackV2", {}, &graph); AddSimpleNode("push1", "StackPushV2", {"stack1", "c"}, &graph); AddSimpleNode("pop1", "StackPopV2", {"stack1"}, &graph); AddSimpleNode("id1", "Identity", {"pop1"}, &graph); // Stack with corresponding push/pop behind Enter. AddSimpleNode("stack2", "StackV2", {}, &graph); AddEnterNode("enter2_c", "frame_name", false, 1, {"c"}, &graph); AddEnterNode("enter2_stack2", "frame_name", false, 1, {"stack2"}, &graph); AddSimpleNode("push2", "StackPushV2", {"enter2_stack2", "enter2_c"}, &graph); AddSimpleNode("pop2", "StackPopV2", {"enter2_stack2"}, &graph); AddSimpleNode("id2", "Identity", {"pop2"}, &graph); // Stack with unexpected op type in fanout of Stack. AddSimpleNode("stack3", "StackV2", {}, &graph); AddSimpleNode("push3", "StackPushV2", {"stack3", "c"}, &graph); AddSimpleNode("stop", "StopGradient", {"stack3"}, &graph); LoopOptimizer optimizer; EnableOnlyStackPushRemoval(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); VerifyGraphsEqual(item.graph, output, __FUNCTION__); } TEST_F(LoopOptimizerTest, RemovePush_NoPopButStackLives) { GrapplerItem item; GraphDef& graph = item.graph; AddSimpleNode("c", "Const", {}, &graph); // Stack with corresponding push AddSimpleNode("stack1", "StackV2", {}, &graph); AddSimpleNode("push1", "StackPushV2", {"stack1", "c"}, &graph); // Stack with corresponding push behind Enter. AddSimpleNode("stack2", "StackV2", {}, &graph); AddEnterNode("enter2_c", "frame_name", false, 1, {"c"}, &graph); AddEnterNode("enter2_stack2", "frame_name", false, 1, {"stack2"}, &graph); AddSimpleNode("push2", "StackPushV2", {"enter2_stack2", "enter2_c"}, &graph); item.keep_ops.push_back("stack1"); item.keep_ops.push_back("stack2"); LoopOptimizer optimizer; EnableOnlyStackPushRemoval(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); VerifyGraphsEqual(item.graph, output, __FUNCTION__); } TEST_F(LoopOptimizerTest, RemovePushWithoutMatchingPop) { GrapplerItem item; GraphDef& graph = item.graph; AddSimpleNode("c", "Const", {}, &graph); // Push without Pop. AddSimpleNode("stack1", "StackV2", {}, &graph); AddSimpleNode("push1", "StackPushV2", {"stack1", "c"}, &graph); // Push without Pop behind Enter. AddSimpleNode("stack2", "StackV2", {}, &graph); AddEnterNode("enter_c", "frame_name", false, 1, {"c"}, &graph); AddEnterNode("enter_stack2", "frame_name", false, 1, {"stack2"}, &graph); AddSimpleNode("push2", "StackPushV2", {"enter_stack2", "enter_c"}, &graph); // Pop without consumer. AddSimpleNode("stack3", "StackV2", {}, &graph); AddSimpleNode("push3", "StackPushV2", {"stack3", "c"}, &graph); AddSimpleNode("pop3", "StackPopV2", {"stack3"}, &graph); // Push for a Pop without consumer that is fetched should not be removed. AddSimpleNode("stack4", "StackV2", {}, &graph); AddSimpleNode("push4", "StackPushV2", {"stack4", "c"}, &graph); AddSimpleNode("pop4", "StackPopV2", {"stack4"}, &graph); item.fetch.push_back("pop4"); LoopOptimizer optimizer; EnableOnlyStackPushRemoval(&optimizer); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); EXPECT_EQ(13, output.node_size()); for (int i = 0; i < output.node_size(); ++i) { const NodeDef& node = output.node(i); if (node.name() == "push1") { EXPECT_EQ("Identity", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("c", node.input(0)); EXPECT_EQ("^stack1", node.input(1)); } else if (node.name() == "push2") { EXPECT_EQ("Identity", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("enter_c", node.input(0)); EXPECT_EQ("^enter_stack2", node.input(1)); } else if (node.name() == "push3") { EXPECT_EQ("Identity", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("c", node.input(0)); EXPECT_EQ("^stack3", node.input(1)); } else { const NodeDef& orig_node = item.graph.node(i); EXPECT_EQ(orig_node.ShortDebugString(), node.ShortDebugString()); } } } TEST_F(LoopOptimizerTest, RemoveDeadBranches_ConstantCondition) { Scope scope = Scope::NewRootScope(); Output v_in = ops::Variable(scope.WithOpName("v_in"), {3}, DT_FLOAT); Output ctrl1 = ops::Const(scope.WithOpName("ctrl1"), false, TensorShape({})); ops::Switch s1(scope.WithOpName("switch1"), v_in, ctrl1); Output square1 = ops::Square(scope.WithOpName("square1"), s1.output_false); Output sqrt1 = ops::Sqrt(scope.WithOpName("sqrt1"), s1.output_true); Output ctrl2 = ops::Const(scope.WithOpName("ctrl2"), true, TensorShape({})); ops::Switch s2(scope.WithOpName("switch2"), v_in, ctrl2); Output square2 = ops::Square(scope.WithOpName("square2"), s2.output_false); Output sqrt2 = ops::Sqrt(scope.WithOpName("sqrt2"), s2.output_true); Output ctrl3 = ops::Const(scope.WithOpName("ctrl3"), false, TensorShape({})); ops::Switch s3(scope.WithOpName("switch3"), v_in, ctrl3); Output square3 = ops::Square(scope.WithOpName("square3"), s3.output_false); Output sqrt3 = ops::Sqrt(scope.WithOpName("sqrt3"), s3.output_true); Output ctrl4 = ops::Const(scope.WithOpName("ctrl4"), false, TensorShape({})); ops::Switch s4(scope.WithOpName("switch4"), v_in, ctrl4); Output square4 = ops::Square(scope.WithOpName("square4"), s4.output_false); Output sqrt4 = ops::Sqrt(scope.WithOpName("sqrt4"), s4.output_true); ops::Merge m1(scope.WithOpName("m1"), {square1, sqrt1}); ops::Merge m2(scope.WithOpName("m2"), {v_in, square1}); ops::Merge m3(scope.WithOpName("m3"), {v_in, sqrt1}); ops::Merge m4(scope.WithOpName("m4"), {square1, sqrt2}); ops::Merge m5(scope.WithOpName("m5"), {square2, sqrt1}); ops::Merge m6(scope.WithOpName("m6").WithControlDependencies(sqrt2), {v_in, square1}); ops::Merge m7(scope.WithOpName("m7").WithControlDependencies(sqrt1), {v_in, square1}); ops::Switch s5(scope.WithOpName("switch5"), v_in, ctrl1); Output id1 = ops::Identity(scope.WithOpName("id1"), s5.output_false); Output id2 = ops::Identity(scope.WithOpName("id2"), s5.output_true); ops::Merge m8(scope.WithOpName("m8"), {id1, id2}); ops::Switch s6(scope.WithOpName("switch6"), v_in, ctrl1); Output id3 = ops::Identity(scope.WithOpName("id3"), s6.output_false); Output id4 = ops::Identity(scope.WithOpName("id4"), s6.output_true); ops::Merge m9(scope.WithOpName("m9"), {id3, id4}); GrapplerItem item; item.fetch.push_back("m8"); item.fetch.push_back("id4"); TF_CHECK_OK(scope.ToGraphDef(&item.graph)); LoopOptimizer optimizer(RewriterConfig::AGGRESSIVE, nullptr); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_CHECK_OK(status); for (const NodeDef& node : output.node()) { // These nodes should have been pruned EXPECT_NE("Square1", node.name()); EXPECT_NE("Sqrt2", node.name()); EXPECT_NE("m5", node.name()); EXPECT_NE("m7", node.name()); if (node.name() == "m1") { // sqrt1 is dead EXPECT_EQ("Identity", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("square1", node.input(0)); } else if (node.name() == "m2") { // both inputs are alive EXPECT_EQ("Merge", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("v_in", node.input(0)); EXPECT_EQ("square1", node.input(1)); } else if (node.name() == "m3") { // sqrt1 is dead EXPECT_EQ("Identity", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("v_in", node.input(0)); } else if (node.name() == "m4") { // both inputs are alive EXPECT_EQ("Merge", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("square1", node.input(0)); EXPECT_EQ("sqrt2", node.input(1)); } else if (node.name() == "m6") { // both inputs are alive and the control dependency can get triggered EXPECT_EQ("Merge", node.op()); EXPECT_EQ(3, node.input_size()); EXPECT_EQ("v_in", node.input(0)); EXPECT_EQ("square1", node.input(1)); EXPECT_EQ("^sqrt2", node.input(2)); } else if (node.name() == "m8") { // The node is to be preserved because of a fetch EXPECT_EQ("Merge", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("id1", node.input(0)); EXPECT_EQ("id2", node.input(1)); } else if (node.name() == "m9") { // The node is to be preserved because of a fetch EXPECT_EQ("Merge", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("id3", node.input(0)); EXPECT_EQ("id4", node.input(1)); } } } TEST_F(LoopOptimizerTest, RemoveDeadBranches_ZeroIterWhile) { const string gdef_ascii = R"EOF( node { name: "Const" op: "Const" attr { key: "dtype" value { type: DT_INT32 } } attr { key: "value" value { tensor { dtype: DT_INT32 tensor_shape { } int_val: 20 } } } } node { name: "while/Enter" op: "Enter" input: "Const" attr { key: "T" value { type: DT_INT32 } } attr { key: "frame_name" value { s: "while/while/" } } attr { key: "is_constant" value { b: false } } attr { key: "parallel_iterations" value { i: 1 } } } node { name: "while/Merge" op: "Merge" input: "while/Enter" input: "while/NextIteration" attr { key: "N" value { i: 2 } } attr { key: "T" value { type: DT_INT32 } } } node { name: "while/Less/y" op: "Const" input: "^while/Merge" attr { key: "dtype" value { type: DT_INT32 } } attr { key: "value" value { tensor { dtype: DT_INT32 tensor_shape { } int_val: 10 } } } } node { name: "while/Less" op: "Less" input: "while/Merge" input: "while/Less/y" attr { key: "T" value { type: DT_INT32 } } } node { name: "while/LoopCond" op: "LoopCond" input: "while/Less" } node { name: "while/Switch" op: "Switch" input: "while/Merge" input: "while/LoopCond" attr { key: "T" value { type: DT_INT32 } } attr { key: "_class" value { list { s: "loc:@while/Merge" } } } } node { name: "while/Identity" op: "Identity" input: "while/Switch:1" attr { key: "T" value { type: DT_INT32 } } } node { name: "while/add/y" op: "Const" input: "^while/Identity" attr { key: "dtype" value { type: DT_INT32 } } attr { key: "value" value { tensor { dtype: DT_INT32 tensor_shape { } int_val: 1 } } } } node { name: "while/add" op: "Add" input: "while/Identity" input: "while/add/y" attr { key: "T" value { type: DT_INT32 } } } node { name: "while/NextIteration" op: "NextIteration" input: "while/add" attr { key: "T" value { type: DT_INT32 } } } node { name: "while/Exit" op: "Exit" input: "while/Switch" attr { key: "T" value { type: DT_INT32 } } } versions { producer: 21 } )EOF"; GrapplerItem item; CHECK(protobuf::TextFormat::ParseFromString(gdef_ascii, &item.graph)); item.fetch = {"while/Exit"}; auto tensors_expected = EvaluateNodes(item.graph, item.fetch); EXPECT_EQ(1, tensors_expected.size()); LoopOptimizer optimizer(RewriterConfig::AGGRESSIVE, nullptr); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_CHECK_OK(status); auto tensors_got = EvaluateNodes(output, item.fetch); EXPECT_EQ(1, tensors_got.size()); test::ExpectTensorEqual<int32>(tensors_expected[0], tensors_got[0]); int nodes_present = 0; for (const NodeDef& node : output.node()) { // All nodes connected to Switch's positive check should be pruned. if (node.name() == "while/add") { LOG(ERROR) << "while/add is present after optimization"; } else if (node.name() == "while/add/y") { LOG(ERROR) << "while/add/y is present after optimization"; } else if (node.name() == "while/NextIteration") { LOG(ERROR) << "while/NextIteration is present after optimization"; } else if (node.name() == "while/Identity") { LOG(ERROR) << "while/Identity is present after optimization"; } ++nodes_present; } EXPECT_EQ(8, nodes_present); } } // namespace grappler } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
b696119fd39d15ec8fc4482e7094bc219c029607
557da518c29e2e803a8c16e7d2a3f0f65b50d763
/Classes/Layer/NextMission.h
9e3983e30cf5167145f6945f16590854b2dd4588
[]
no_license
kikoslee/galaxyinvaders
65895c800cf1c48cd02e454fc6c9df2087c76d19
0dfc8436a4868c80f054c99372cea105791ba784
refs/heads/master
2021-03-27T17:18:55.923510
2013-03-08T09:17:03
2013-03-08T09:17:03
7,727,534
0
0
null
null
null
null
UTF-8
C++
false
false
718
h
#ifndef _NextMission_H_ #define _NextMission_H_ #include "HBCommon.h" class NextMission : public CCLayer , public CCBMemberVariableAssigner , public CCNodeLoaderListener { public: NextMission(); virtual ~NextMission(); CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(NextMission, create); virtual bool onAssignCCBMemberVariable(CCObject* pTarget, const char* pMemberVariableName, CCNode* pNode); virtual void onNodeLoaded(CCNode* pNode, CCNodeLoader* pNodeLoader); private: CCLabelTTF* mLabelNextTitle; CCLabelTTF* mLabelMissionName; CCLabelTTF* mLabelMissionDesc; CCLabelTTF* mLabelMultiTitle; CCLabelTTF* mLabelMultiplier; }; #endif
[ "kikoslee@gmail.com" ]
kikoslee@gmail.com
6876b17f86d8d08ea85a921bb1d07b46b29470b2
c72965f3ec8cbd1aa78023df011a5f2336256a40
/TDML/world.cpp
9cdf376f84f9c0fc86fd05ebd70815bf32511938
[]
no_license
reilleya/TDML
6c4769c5e50820721e8bfaeb6c674f5fa759732c
b1fb936b3cb71c99b852893da6947d5db412fa5d
refs/heads/master
2020-04-17T13:57:36.998280
2014-04-13T22:15:50
2014-04-13T22:15:50
66,592,653
1
1
null
null
null
null
UTF-8
C++
false
false
12,974
cpp
//world.cpp //Created by Andrew Reilley //Development began 7/26/12 //Do not redistribute, modify, or claim ownership of this library! //If you use this library, please credit Andrew Reilley or eggplantanimation.com //Contact email: areill1337@gmail.com #include "TDML.h" using namespace std; namespace TDML { world::world() { fileName = ""; nobjs=0; nparts=0; camx=0; camy=0; camz=0; camxangle=0; camyangle=0; camzangle=0; hasterrain = false; modelMatrix = matrix4x4(); } world::world(std::string filename) { fileName = filename; nobjs=0; nparts=0; camx=0; camy=0; camz=0; camxangle=0; camyangle=0; camzangle=0; hasterrain = false; modelMatrix = matrix4x4(); } void world::dispInfo() { Log.output("World:\n"); Log.output("\tFilename: "+fileName+"\n"); Log.output("\tTerrain: "); Log.output((float)hasterrain); Log.output("\n"); Log.output("\tObjects: "); Log.output((float)nobjs); Log.output("\n"); Log.output("\tParticle Systems: "); Log.output((float)nparts); Log.output("\n"); Log.output("\tCamera Information:\n"); Log.output("\t\tPosition: "); Log.output(camx); Log.output(","); Log.output(camy); Log.output(","); Log.output(camz); Log.output("\n"); Log.output("\t\tAngle: "); Log.output(camxangle); Log.output(","); Log.output(camyangle); Log.output(","); Log.output(camzangle); Log.output("\n"); } void world::update() { for(int updater = 0; updater < nparts; updater++) { particlesystems[updater].update(); } for(int updater = 0; updater < nobjs; updater++) { objects[updater].update(); } } void world::draw() { modelMatrix.loadIdentity(); if(hasterrain) { modelMatrix.rotate(camxangle, camyangle, camzangle, crotorder); modelMatrix.translate(-camx, -camy, -camz); modelMatrix.scale(map.getScaleXZ(), map.getScaleY(), map.getScaleXZ()); matrix3x3 nmat; //nmat = nmat.inverse(); //nmat = nmat.transpose(); Shaders.setNormalMat(nmat.glForm()); Shaders.setModelMat(modelMatrix.glForm()); map.display(); modelMatrix.loadIdentity(); } for(int obj = 0; obj < (int)nobjs; obj++) { modelMatrix.rotate(camxangle, camyangle, camzangle, crotorder); modelMatrix.translate(-camx, -camy, -camz); modelMatrix.translate(objects[obj].getX(), objects[obj].getY(), objects[obj].getZ()); modelMatrix.scale(objects[obj].getScaleX(), objects[obj].getScaleY(), objects[obj].getScaleZ()); modelMatrix.rotate(-objects[obj].getXangle(), -objects[obj].getYangle(), -objects[obj].getZangle(), orotorder); //matrix3x3 nmat = modelMatrix.rotPart(); //nmat = nmat.inverse(); //nmat = nmat.transpose(); matrix4x4 nmat = matrix4x4(); nmat.rotate(-objects[obj].getXangle(), -objects[obj].getYangle(), -objects[obj].getZangle(), orotorder); nmat.rotate(-camxangle, -camyangle, -camzangle, crotorder); matrix3x3 nm = nmat.rotPart(); //nm = nm.inverse(); //nm = nm.transpose(); Shaders.setNormalMat(nm.glForm()); Shaders.setModelMat(modelMatrix.glForm()); Shaders.setProjMat(projMatrix.glForm()); objects[obj].display(); if(objects[obj].getDrawBB()) objects[obj].drawBB(); modelMatrix.loadIdentity(); } for(int par = 0; par < (int)nparts; par++) { modelMatrix.loadIdentity(); modelMatrix.rotate(camxangle, camyangle, camzangle, crotorder); modelMatrix.translate(-camx, -camy, -camz); Shaders.setModelMat(modelMatrix.glForm()); particlesystems[par].display(this); modelMatrix.loadIdentity(); } } void world::addObject(object Obj) { objects.resize(objects.size()+1); objects[objects.size()-1]=Obj; nobjs++; } void world::addParticleSystem(particlesystem newsystem) { particlesystems.resize(particlesystems.size()+1); particlesystems[particlesystems.size()-1]=newsystem; nparts++; } void world::setTerrain(terrain newterrain) { hasterrain = true; map = newterrain; } void world::setCamAngleX(float newXangle) { camxangle = newXangle; } void world::setCamAngleY(float newYangle) { camyangle = newYangle; } void world::setCamAngleZ(float newZangle) { camzangle = newZangle; } void world::setCamAngle(float newXangle, float newYangle, float newZangle) { camxangle = newXangle; camyangle = newYangle; camzangle = newZangle; } void world::setCamAngle(vector3d newAngle) { camxangle = newAngle.x; camyangle = newAngle.y; camzangle = newAngle.z; } void world::setCamPosition(float newX, float newY, float newZ) { camx = newX; camy = newY; camz = newZ; } void world::setCamPosition(vector3d position) { camx = position.x; camy = position.y; camz = position.z; } float world::getCamAngleX() { return camxangle; } float world::getCamAngleY() { return camyangle; } float world::getCamAngleZ() { return camzangle; } void world::setCamX(float newX) { camx = newX; } void world::setCamY(float newY) { camy = newY; } void world::setCamZ(float newZ) { camz = newZ; } float world::getCamX() { return camx; } float world::getCamY() { return camy; } float world::getCamZ() { return camz; } int world::getFirstIDByName(string name) { for(int counter = 0; counter < (int)nobjs; counter++) { if(objects[counter].getName()==name) { return counter; } } Message.errorMessage("World Error:\n\tFound no object with name "+name+" in world loaded from file "+fileName, "World Error"); return -1; } object world::getFirstObjByName(string name) { return getObjectById(getFirstIDByName(name)); } /*vector<int> world::getIDsByName(std::string name) { vector<int> ids; int idsize=0; for(int counter = 0; counter < (int)objects.size(); counter++) { if(objects[counter].getName()==name) { ids.resize(idsize+1); ids[idsize] = counter; idsize++; } } return ids; }*/ /*object* world::getObjsByName(string name) { return getObjsById(getFirstIDByName(name)); }*/ vector<object> world::getObjects() { return objects; } object world::getObjectById(int id) { return objects[id]; } /*vector<object*>* world::getObjectsById(int* id) { vector<object*> objs; for(int iter = 0; iter < nobjs; iter++) { if( } return objs }*/ object& world::getObjectRef(std::string Name) { return objects.at(getFirstIDByName(Name)); } void world::removeObjectById(int id) { objects.erase(objects.begin()+id); nobjs--; } void world::removeObjectByName(string Name) { removeObjectById(getFirstIDByName(Name)); } void world::removeObjectByType(string Type) { //TODO } int world::getParticleSystemNameById(string Name) { int id = -1; for(int ps = 0; ps < nparts; ps++) { Log.output(particlesystems[ps].getName()); if(particlesystems[ps].getName()==Name) { id = ps; break; } } return id; } particlesystem& world::getParticleSystemRef(std::string Name) { int id = getParticleSystemNameById(Name); if(id!=-1) { return particlesystems.at(id); } else { Message.errorMessage("Attempted to reference a particle system that doesn't exist.\nWorld: \tParticle System: "+Name+"\nPossibilities: "+particlesystems[0].getName(), "Particle System Reference Error"); } } terrain& world::getTerrainRef() { if (hasterrain) { return map; } else { Message.errorMessage("Attempted to get terrain reference from a world that doesn't have a terrain object.\n\tWorld: " + fileName, "Terrain Reference Error"); return terrain(); } } float world::getHeightMapAt(float x, float z) { if(hasterrain) { return map.getHeightMapAt(x,z); } else { Message.errorMessage("Attempted to read terrain height from a world that doesn't have a terrain object.\n\tWorld: " + fileName, "Terrain Height Error"); return 0; } } vector3d& world::getAngleMapAt(float x, float z) { if(hasterrain) { return map.getAngleAt(x, z); } else { Message.errorMessage("Attempted to read terrain angle from a world that doesn't have a terrain object.\n\tWorld: " + fileName, "Terrain Angle Error"); return vector3d(0, 0, 0); } } float world::getInclinationAt(float x, float z) { if (hasterrain) { return map.getInclinationAt(x, z); } else { Message.errorMessage("Attempted to read terrain inclination from a world that doesn't have a terrain object.\n\tWorld: " + fileName, "Terrain Inclination Error"); return 0; } } float world::getObjAttribute(string name, string attr) { int id = getFirstIDByName(name); if(attr=="x") return objects[id].getX(); else if(attr=="y") return objects[id].getY(); else if(attr=="z") return objects[id].getZ(); else if(attr=="xscale") return objects[id].getScaleX(); else if(attr=="yscale") return objects[id].getScaleY(); else if(attr=="zscale") return objects[id].getScaleZ(); else if(attr=="xangle") return objects[id].getXangle(); else if(attr=="yangle") return objects[id].getYangle(); else if(attr=="zangle") return objects[id].getZangle(); else if(attr=="wireframe") return objects[id].getWireframe(); else if(attr=="visible") return objects[id].getVisible(); else return 0; } void world::setObjAttribute(string name, string attr, float value) { if(name!="*") { int id = getFirstIDByName(name); //std::cout << id<<endl; if(attr=="x") objects[id].setX(value); if(attr=="y") objects[id].setY(value); if(attr=="z") objects[id].setZ(value); if(attr=="xscale") objects[id].setScaleX(value); if(attr=="yscale") objects[id].setScaleY(value); if(attr=="zscale") objects[id].setScaleZ(value); if(attr=="xangle") objects[id].setXangle(value); if(attr=="yangle") objects[id].setYangle(value); if(attr=="zangle") objects[id].setZangle(value); if(attr=="wireframe") { if(value==1.0) objects[id].setWireframe(true); if(value==0.0) objects[id].setWireframe(false); } if(attr=="visible") { if(value==1.0) objects[id].setVisible(true); if(value==0.0) objects[id].setVisible(false); } } else { for(std::size_t id = 0; id < objects.size(); id++) { if(attr=="x") objects[id].setX(value); if(attr=="y") objects[id].setY(value); if(attr=="z") objects[id].setZ(value); if(attr=="xscale") objects[id].setScaleX(value); if(attr=="yscale") objects[id].setScaleY(value); if(attr=="zscale") objects[id].setScaleZ(value); if(attr=="xangle") objects[id].setXangle(value); if(attr=="yangle") objects[id].setYangle(value); if(attr=="zangle") objects[id].setZangle(value); if(attr=="wireframe") { if(value==1.0) objects[id].setWireframe(true); if(value==0.0) objects[id].setWireframe(false); } if(attr=="visible") { if(value==1.0) objects[id].setVisible(true); if(value==0.0) objects[id].setVisible(false); } } } } float world::getDistance(std::string firstName, std::string secondName) { int fid = getFirstIDByName(firstName); int sid = getFirstIDByName(secondName); float xdist = objects[fid].getX()-objects[sid].getX(); float ydist = objects[fid].getY()-objects[sid].getY(); float zdist = objects[fid].getZ()-objects[sid].getZ(); float distance = sqrtf((xdist*xdist)+(ydist*ydist)+(zdist*zdist)); return distance; } bool world::getBBCollideName(std::string firstName, std::string secondName) { int fid = getFirstIDByName(firstName); int sid = getFirstIDByName(secondName); bool collided = false; bool collidedx = false; bool collidedy = false; bool collidedz = false; if((objects[fid].getMaxX() >= objects[sid].getMinX() && objects[fid].getMaxX() <= objects[sid].getMaxX()) || (objects[sid].getMaxX() >= objects[fid].getMinX() && objects[sid].getMaxX() <= objects[fid].getMaxX())) { collidedx = true; } if((objects[fid].getMaxY() >= objects[sid].getMinY() && objects[fid].getMaxY() <= objects[sid].getMaxY()) || (objects[sid].getMaxY() >= objects[fid].getMinY() && objects[sid].getMaxY() <= objects[fid].getMaxY())) { collidedy = true; } if((objects[fid].getMaxZ() >= objects[sid].getMinZ() && objects[fid].getMaxZ() <= objects[sid].getMaxZ()) || (objects[sid].getMaxX() >= objects[fid].getMinZ() && objects[sid].getMaxZ() <= objects[fid].getMaxZ())) { collidedz = true; } if(collidedx&&collidedy&&collidedz) { collided = true; } return collided; } bool world::getBBCollideType(std::string name, std::string type) { bool collided = false; for(int v = 0; v < nobjs; v++) { if(objects[v].getType()==type) { if(getBBCollideName(name,objects[v].getName())) { collided = true; break; } } } return collided; } bool world::getBoundingSphereCollide(std::string firstName, std::string secondName) { int fid = getFirstIDByName(firstName); int sid = getFirstIDByName(secondName); if(getDistance(firstName,secondName)<(objects[fid].getRadius()+objects[sid].getRadius())) { return true; } else { return false; } } }
[ "areill1337@gmail.com" ]
areill1337@gmail.com
94c1a3b1e6e54734a2481a9d0d54a8af0ec7f990
9ea9b9f83c13d2767066e725d0c828d41c1d787d
/src/crypto/mbedtls/rsa_key_pair.h
30ed43973889d420f3e51044e79e22e85e447c5d
[ "Apache-2.0" ]
permissive
achamayou/CCF
5f5f22e2c7a3ec79481814a03c1d4dea911add65
335fc3613c2dd4a3bda38e10e8e8196dba52465e
refs/heads/master
2023-08-24T19:45:05.326218
2021-11-09T17:17:36
2021-11-09T17:17:36
281,125,040
0
1
Apache-2.0
2023-06-05T16:57:51
2020-07-20T13:33:22
C++
UTF-8
C++
false
false
1,389
h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #pragma once #include "crypto/rsa_key_pair.h" #include "mbedtls_wrappers.h" #include "rsa_public_key.h" #include <optional> #include <vector> namespace crypto { class RSAKeyPair_mbedTLS : public RSAPublicKey_mbedTLS, public RSAKeyPair { public: RSAKeyPair_mbedTLS( size_t public_key_size = default_public_key_size, size_t public_exponent = default_public_exponent); RSAKeyPair_mbedTLS(mbedtls::PKContext&& k); RSAKeyPair_mbedTLS(const RSAKeyPair&) = delete; RSAKeyPair_mbedTLS(const Pem& pem, CBuffer pw = nullb); virtual size_t key_size() const override; virtual ~RSAKeyPair_mbedTLS() = default; virtual std::vector<uint8_t> rsa_oaep_unwrap( const std::vector<uint8_t>& input, std::optional<std::vector<std::uint8_t>> label = std::nullopt) override; virtual Pem private_key_pem() const override; virtual Pem public_key_pem() const override; virtual std::vector<uint8_t> public_key_der() const override; virtual std::vector<uint8_t> sign( CBuffer d, MDType md_type = MDType::NONE) const override; virtual bool verify( const uint8_t* contents, size_t contents_size, const uint8_t* signature, size_t signature_size, MDType md_type = MDType::NONE) override; }; }
[ "noreply@github.com" ]
noreply@github.com
9691cfd7a86b1bc4504544b80eb840f61dc10df9
21528796cc5a0727011b53a2ea7e79d375141401
/WebServer/request.h
110567a2a8f394b0874fd6cbebbb0b4ec5ad9048
[]
no_license
InnovatorRobot/WebServerMongoosQt
5ecace3ac3330b6edef3d7f0c3919688c027c522
8d30556b3d807f723b4ee155ba0185db5d8a2c87
refs/heads/master
2023-07-26T08:08:14.399591
2020-01-26T16:35:07
2020-01-26T16:37:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,062
h
#ifndef _MONGOOSE_REQUEST_H #define _MONGOOSE_REQUEST_H #include <iostream> #include <sstream> #include <vector> #ifdef ENABLE_REGEX_URL #include <regex> #endif #include "mongoose.h" #include "uploadfile.h" #include "response.h" using namespace std; /** * Request is a wrapper for the clients requests */ namespace Mongoose { class Request { public: Request(struct mg_connection *connection); /** * Sends a given response to the client * * @param Response a response for this request */ void writeResponse(Response *response); /** * Check if the variable given by key is present in GET or POST data * * @param string the name of the variable * * @return bool true if the param is present, false else */ bool hasVariable(string key); /** * Get All variable present in GET or POST data * * @brief getAllVariable * @return map<string, string> with all variables */ map<string, string> getAllVariable(); /** * Get the value for a certain variable * * @param string the name of the variable * @param string the fallback value if the variable doesn't exists * * @return string the value of the variable if it exists, fallback else */ string get(string key, string fallback = ""); /** * Checks if the given cookie exists * * @param string the name of the cookie * * @return bool true if the given cookie is set */ bool hasCookie(string key); /** * Try to get the cookie value * * @param string the name of the cookie * @param string the fallback value * * @retun the value of the cookie if it exists, fallback else */ string getCookie(string key, string fallback = ""); string getHeaderKeyValue(const std::string& header_key); /** * Handle uploads to the target directory * * @param string the target directory * @param path the posted file path */ void handleUploads(); string getUrl(); string getMethod(); string getData(); #ifdef ENABLE_REGEX_URL smatch getMatches(); bool match(string pattern); #endif bool readVariable(const char *data, string key, string &output); /** * Files uploaded in this request */ vector<UploadFile> uploadFiles; protected: string method; string url; string data; struct mg_connection *connection; }; } #endif
[ "mahmoudi.saman1@gmail.com" ]
mahmoudi.saman1@gmail.com
268ae81dceb23ebed8a49cf0d1a9e20da5ecb25c
7fbb988a7b223df9783e632354a66dd3616d0bf1
/beta/TopDomeBeta/quickEnemy.cpp
20d1d3aad230e559a8358a89221c1478c156dd6c
[]
no_license
miha53cevic/Top-Dome
baed4840d25109e262ccabd7d5840ae5e6970fad
47c4362ac09880a7e06b3d03eeb7c7d1c29d6959
refs/heads/master
2021-07-10T02:09:39.125187
2020-08-02T10:41:22
2020-08-02T10:41:22
163,223,808
0
0
null
null
null
null
UTF-8
C++
false
false
2,026
cpp
#include "quickEnemy.h" quickEnemy::quickEnemy(float posX, float posY, float fSpeed) : Enemy(posX, posY, fSpeed) { setColour(sf::Color::Yellow); m_HP = 1; } void quickEnemy::Update(std::string& map, const sf::Vector2i& mapSize, const sf::Vector2i& pixelSize, sf::Time Elapsed) { //Get Tile Lambda Function auto getTile = [&](float x, float y) -> char { int nX, nY; nX = x / pixelSize.x; nY = y / pixelSize.y; return map[(nY * mapSize.x) + nX]; }; //Gravity m_velocity.y += m_fGravity * Elapsed.asSeconds(); if (m_bLookingLeft) { m_velocity.x = -m_fSpeed * Elapsed.asSeconds(); } else { m_velocity.x = m_fSpeed * Elapsed.asSeconds(); } // X - Axis if (m_velocity.x <= 0) { if (getTile(m_enemy.getPosition().x + m_velocity.x, m_enemy.getPosition().y) != '.' || getTile(m_enemy.getPosition().x + m_velocity.x, m_enemy.getPosition().y + m_enemy.getSize().y) != '.') { m_velocity.x = 0.f; m_bLookingLeft = false; } } else { if (getTile(m_enemy.getPosition().x + m_enemy.getSize().x + m_velocity.x, m_enemy.getPosition().y) != '.' || getTile(m_enemy.getPosition().x + m_enemy.getSize().x + m_velocity.x, m_enemy.getPosition().y + m_enemy.getSize().y) != '.') { m_velocity.x = 0.f; m_bLookingLeft = true; } } // Y - Axis if (m_velocity.y <= 0) { if (getTile(m_enemy.getPosition().x, m_enemy.getPosition().y + m_velocity.y) != '.' || getTile(m_enemy.getPosition().x + m_enemy.getSize().x, m_enemy.getPosition().y + m_velocity.y) != '.') { m_velocity.y = 0.f; } } else { if (getTile(m_enemy.getPosition().x, m_enemy.getPosition().y + m_enemy.getSize().y + m_velocity.y) != '.' || getTile(m_enemy.getPosition().x + m_enemy.getSize().x, m_enemy.getPosition().y + m_enemy.getSize().y + m_velocity.y) != '.') { m_velocity.y = 0.f; } } //Move Enemy by velocity m_enemy.move(m_velocity.x, m_velocity.y); //Reset Horizontal Speed && Keep Vertical m_velocity.x = 0.f; } void quickEnemy::Draw(sf::RenderWindow* window) { window->draw(m_enemy); }
[ "44951515+miha53cevic@users.noreply.github.com" ]
44951515+miha53cevic@users.noreply.github.com
b0aeb90a3a8d0508fd3382c5c6dc107aa49e86ce
e102e5ace9302a937667eb525bdfcf32aa373d5b
/Workshop/Count/Arduino/Arduino.ino
6eaa9b2ea6e0f5405886704013e79041133b3d4b
[]
no_license
krhoyt/WebVisions2016
bf9254dd42079744c7aec55a731d081345328efa
ab01f6ddcf25471d1a9cf1a9dcf17fce68e8d2e1
refs/heads/master
2021-01-01T04:25:42.447666
2016-05-19T17:07:20
2016-05-19T17:07:20
58,663,974
0
1
null
null
null
null
UTF-8
C++
false
false
247
ino
// Counter long count = 0; // Open serial (USB) void setup() { Serial.begin( 9600 ); } // Infinite void loop() { // Increment count = count + 1; // Send to serial (USB) Serial.println( count ); // Wait a second delay( 1000 ); }
[ "parkerkrhoyt@gmail.com" ]
parkerkrhoyt@gmail.com
1ea638ebda941d692e10d6db2716fa5babe3fbbf
3d2a716515c80c327f0732cd94b55b307206c391
/Cine/ventas.h
ee4d0d49f9ab335c968417c4542fbc681ad94bc6
[]
no_license
mawidicris/TallerEvaluativo
01803891aac3aed59103179953c5dfda73c31e1a
3607249506b57039addb5c9e1c96b9ed50400b1d
refs/heads/master
2022-08-06T21:12:05.893762
2020-05-15T03:48:25
2020-05-15T03:48:25
263,230,055
0
0
null
null
null
null
UTF-8
C++
false
false
447
h
/*Logica y control de la ventas en el día */ #ifndef VENTAS_H #define VENTAS_H #include "venta.h" #include <vector> class Ventas { private: vector<venta> V; public: Ventas(); vector<venta> getV() const; void setV(const vector<venta> value); void GuardarVenta(venta _V); //Escribir sobre el archivo Repote.txt void ReporteVentas(); //Calcula el total de ventas y genera un reporte al administrador }; #endif // VENTAS_H
[ "62735452+mawidicris@users.noreply.github.com" ]
62735452+mawidicris@users.noreply.github.com
94c797ac33927aa33e298a6da4e2da43562b72bf
03c71398ebae1405492d7e141c1fc6199d37d56f
/Projects/Zoo Tycoon/InputVal.cpp
c06f721559d56a4ed21b47e141ee8b4df19082b2
[]
no_license
AStockinger/Cpp-Projects
f40bea19ddd84fb07cc10c1c1e761a82f6bd07b9
f53d22a1067ddbdb8cacb2e5bbc91f4360916d1c
refs/heads/master
2020-04-11T20:14:14.455812
2018-12-18T04:48:03
2018-12-18T04:48:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,238
cpp
/****************************************************************************** ** Program name: Zoo Tycoon ** Author: Amy Stockinger ** Date: October 8, 2018 ** Description: input validation function takes a reference variable and ** two ints for the range that the variable is allowed to be in ** function will reprompt until an acceptable integer is inputted ******************************************************************************/ #include <iostream> #include <string> #include <sstream> #include <cctype> using std::cin; using std::string; using std::cout; using std::stringstream; // input takes a number variable to be changed, along with min and max acceptable values int getInt(int &value, int min, int max){ string s; do{ cout << "Please enter an integer between " << min << " and " << max << ": "; string line; getline(cin, line); // change string to int stringstream ss(line); ss >> value; // check line for numbers for(unsigned int i = 0; i < line.length(); i++){ if(!isdigit(line[i])){ value = min - 1; } } }while(value == min - 1 || value > max || value < min); return value; }
[ "noreply@github.com" ]
noreply@github.com
3bdc6639ef6d861eaa99b936df66a9e8949bfda2
37c7c3c3f0766a0f893e039858f235b28b8991f7
/src/qt/sendcoinsentry.cpp
6f2475a79acf82ac141d6b603d11f358ba9c24d4
[ "MIT" ]
permissive
CCNetWorkCoin/ccnetwork
5a3152ad6c9fcf0d3add75c76c0bcb89df3c17f7
b336b178d9ea2653735078c4654fb21409ea0fa7
refs/heads/master
2020-09-12T02:41:58.385063
2019-11-17T18:30:18
2019-11-17T18:30:18
222,274,129
0
0
null
null
null
null
UTF-8
C++
false
false
4,617
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsentry.h" #include "ui_sendcoinsentry.h" #include "guiutil.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(QWidget *parent) : QFrame(parent), ui(new Ui::SendCoinsEntry), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC ui->payToLayout->setSpacing(4); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); ui->payTo->setPlaceholderText(tr("Enter a CcNetwork address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); GUIUtil::setupAddressWidget(ui->payTo, this); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { if(!model) return; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) ui->addAsLabel->setText(associatedLabel); } void SendCoinsEntry::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel()) connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->payAmount, SIGNAL(textChanged()), this, SIGNAL(payAmountChanged())); clear(); } void SendCoinsEntry::setRemoveEnabled(bool enabled) { ui->deleteButton->setEnabled(enabled); } void SendCoinsEntry::clear() { ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->payTo->setFocus(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::on_deleteButton_clicked() { emit removeEntry(this); } bool SendCoinsEntry::validate() { // Check input validity bool retval = true; if(!ui->payAmount->validate()) { retval = false; } else { if(ui->payAmount->value() <= 0) { // Cannot send 0 coins or less ui->payAmount->setValid(false); retval = false; } } if(!ui->payTo->hasAcceptableInput() || (model && !model->validateAddress(ui->payTo->text()))) { ui->payTo->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { SendCoinsRecipient rv; rv.address = ui->payTo->text(); rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); return rv; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); return ui->payAmount->setupTabChain(ui->addAsLabel); } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { ui->payTo->setText(value.address); ui->addAsLabel->setText(value.label); ui->payAmount->setValue(value.amount); } void SendCoinsEntry::setAddress(const QString &address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } }
[ "djcc2008@yahoo.com" ]
djcc2008@yahoo.com
16faab068f294e3bbf599503d6c0af7aa649341f
f86327d680b3b516348bf87a9400ca3c8118e4c5
/RayTracer/Framebuffer.h
3f1dd6fafa7ee5f7de7cd113a7a6949414b9aa64
[]
no_license
BMann-png/GAT350
8f14370a6aeaf625a633671245e84233e9d523b9
90100d9c8596ce7be0b4fae0ba4a2ca9c58abeed
refs/heads/master
2023-08-25T16:43:14.351844
2021-11-08T17:06:44
2021-11-08T17:06:44
414,251,488
0
0
null
null
null
null
UTF-8
C++
false
false
1,158
h
#pragma once #include "Renderer.h" #include "Image.h" #include "Types.h" #include <vector> class Framebuffer { public: Framebuffer(Renderer* renderer, int width, int height); ~Framebuffer(); void Update(); void Clear(const color_t& color); void DrawPoint(int x, int y, const color_t& color); void DrawRect(int x, int y, int width, int height, const color_t& color); void DrawLine(int x1, int y1, int x2, int y2, const color_t& color); void DrawCircle(int x, int y, int radius, const color_t& color); void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, const color_t& color); void DrawImage(int x1, int y2, class Image* image); void DrawSimpleCurve(int x1, int y1, int x2, int y2, int steps, const color_t& color); void DrawQuadraticCurve(int x1, int y1, int x2, int y2, int x3, int y3, int steps, const color_t& color); void DrawCubicCurve(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4, int steps, const color_t& color); void DrawCircleOctants(int cx, int cy, int x, int y, const color_t& color); int Lerp(int a, int b, float t); public: SDL_Texture* texture{ nullptr }; ColorBuffer colorbuffer; };
[ "bmann@student.neumont.edu" ]
bmann@student.neumont.edu
d80153a1059c3e62b4670e2b5c86e61c7b6e5438
ea9f636f2516fc97b44ed0736dace3512760570f
/Editing/Hidden Values - CategoryManagerWeb/CategoryManagerWeb/Index.cpp
9469c2bd7c10b5a92bb1df15838fba702861a340
[]
no_license
israelfloresdga/Wintempla-Information-System
da4942791c9fb4e1c088b58737e6d35e728e0f80
ba94f4a9e0218efb8bde6d5dc943aac67dedb4cf
refs/heads/master
2021-01-10T10:19:57.415860
2016-04-21T06:02:44
2016-04-21T06:02:44
36,786,208
1
0
null
null
null
null
UTF-8
C++
false
false
1,146
cpp
#include "stdafx.h" //_____________________________________________ Index.cpp #include "Index.h" void Index::Window_Open(Web::HttpConnector& h) { //________________________________________________________ lvCategory lvCategory.Cols.Add(LVCFMT_LEFT, 24, L"Name"); updateListView(); } void Index::btInsert_Click(Web::HttpConnector& h) { hdCategoryID.Data= L"-1"; h.NavigateTo(L"CategoryPage"); } void Index::btEdit_Click(Web::HttpConnector& h) { const int selecetedIndex= lvCategory.SelectedIndex; if(selecetedIndex<0) return; const int category_id= Sys::Convert::ToInt(lvCategory.SelectedData); if(category_id<0) return; hdCategoryID.Data= lvCategory.SelectedData; h.NavigateTo(L"CategoryPage"); } void Index::updateListView() { Sql::SqlConnection conn; try { //conn.OpenSession(DSN, USERNAME, PASSWORD); //Control Panel>Administrative Tools>Data Sources (ODBC)>Create dsn_myDatabase conn.OpenSession(NULL, CONNECTION_STRING); conn.ExecuteSelect(L"SELECT category_id, descr FROM category", 100, lvCategory); } catch (Sql::SqlException e) { this->MessageBox(e.GetDescription(), L"Error", MB_OK | MB_ICONERROR); } }
[ "israel0104@gmail.com" ]
israel0104@gmail.com
290203f78c0dd4c0a4210aa2fd0965940e0be995
4d455581770eb1779272ed331796ddd4c404574a
/zestawy/ZESTAW 4/Najdluzszy fragment zlozony z tych samych liczb/main.cpp
9a3516567f5b86bbf16daf04b4f5c5cb606f20ef
[]
no_license
jakubowiczish/WDI
07c87252bedaf74d0bbdf88bff989b1138259576
577873d07bcabc0e505b1202db7f315e41f6a63f
refs/heads/master
2021-05-16T00:46:31.826131
2019-01-15T19:45:23
2019-01-15T19:45:23
106,967,499
3
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,815
cpp
#include <iostream> #include <ctime> #include <cstdlib> using namespace std; /* Dana jest tablica int t[N][N] wypełniona przypadkowymi wartościami. Proszę napisad funkcję, która dla zmiennej typu tablica zwraca numer wiersza w którym występuje najdłuższy spójny fragment złożony z liczb o tej samej wartości. W przypadku kilku fragmentów o tej samej długości należy zwrócid pozycję pierwszego z nich. */ const int N = 3; void set_table(int tab[N][N]); void print_table(int tab[N][N]); int number_of_row(int tab[N][N]); int main() { int t[N][N]; //set_table(tab); t[0][0]=5; t[0][1]=6; t[0][2]=5; t[1][0]=12; t[1][1]=12; t[1][2]=12; t[2][0]=25; t[2][1]=44; t[2][2]=23; print_table(t); cout << number_of_row(t); return 0; } int number_of_row(int tab[N][N]) { int MaxLength = 0; int row = 0; for(int i=0; i < N; i++) { int length = 1; for(int j=0; j < N; j++) { if(tab[i][j] == tab[i][j+1]) { length++; } else { if(length > MaxLength) { MaxLength = length; row = i; } length = 1; } cout << "Dlugosc: " << length << endl; } } return row; } void set_table(int tab[N][N]) { srand(time(NULL)); for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { tab[i][j] = rand() % 50 + 1; cout<<tab[i][j]<<"\t"; } cout<<endl<<endl; } } void print_table(int tab[N][N]) { for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { cout<<tab[i][j]<<"\t"; } cout<<endl<<endl; } }
[ "jakub77plotnikowski@gmail.com" ]
jakub77plotnikowski@gmail.com
49fb81a0f8afcf846ad9ea7af593cae00ed2a72c
c6be5bf49390f006b4224c64d237053055f26105
/src/Source.cpp
51d3b5d7d282055c2bde19ea578167e8df8afe1d
[]
no_license
EdikGres/MagicNumber-game
430bdf8569e127627cc45bac2bae96c01c117560
8fd9bf9308cc8fa8bdc781e85709b437808b58d4
refs/heads/main
2023-08-22T20:28:06.914827
2021-09-22T03:05:25
2021-09-22T03:05:25
338,355,175
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,888
cpp
#include <iostream> #include <cstdlib> #include <string> /* * c++ without classes. * add W/L table * make .cfg file, for save W/L and extras and rand seed * make .log file, for save difficulty W/L-tryes, use cheat(show magic) * make generator menu extras */ using namespace std; void play(unsigned* magic, unsigned* attempts); void extra(unsigned* range, unsigned* magic, unsigned* attempts); int main() { unsigned option = 0; unsigned range = 10; unsigned attempts = range / 3; unsigned magic = 0; srand(time(NULL)); magic = rand() % range + 1;//диапазон от 1 до range //cout << magic; cout << "Hello! Do you wanna play this game? Cool!\n\n"; do { cout << "-----\n1.Play!\n2.Extra\n3.Exit!\n-----"; do { cout << "\nMake a choice:", cin >> option; } while (option < 1 || option > 3); switch (option) { case 1: play(&magic, &attempts); break; case 2: extra(&range, &magic, &attempts); break; case 3: cout << "\nBye bye!"; break; default: break; } } while (option != 3); return 0; } void extra(unsigned* range, unsigned* magic, unsigned* attempts) { int option = 0; do { system("cls"); cout << "-----\nCurrent range: 1-" << *range << "\nNumber of attempts: " << *attempts << "\nCurrent magic number:[SECRET]\n\n1.Set range\n2.Set number of attempts\n3.Generate new magic number\n4.Show magic number\n5.Back\n-----\n\n"; do { cout << "\nYour choice: ", cin >> option; } while (option < 1 || option > 5); switch (option) { case 1: system("cls"); cout << "\nCurrent range 1-" << *range; do { cout << "\nInput range 1-", cin >> *range; } while (*range < 1); *magic = rand() % *range + 1; cout << "\nThe number was generated in range 1-" << *range << "\n"; system("pause"); break; case 2: system("cls"); cout << "\nCurrent number of attemps: " << *attempts; cout << "\nInput number of attemps: ", cin >> *attempts; break; case 3: system("cls"); *magic = rand() % *range + 1; cout << "!!!!!The number was generated!!!!!\n"; system("pause"); break; case 4: system("cls"); cout << "Magic number is: " << *magic << "\n"; system("pause"); break; case 5: system("cls"); cout << "\nBack to main menu!\n\n"; break; default: cout << "Error!"; break; } } while (option != 5); } void play(unsigned* magic, unsigned* attempts) { unsigned numb = 0; unsigned tryes = 0; system("cls"); cout << "\nLet's go!\nYou have " << *attempts << " attempts\n"; do { cout << "\n\nMagic number is: ", cin >> numb; if (numb == *magic) { system("cls"); cout << "\nWIN!!!!!!!!!\n\n"; return; } else { if (numb < *magic) cout << "few...\n\n"; else cout << "Too much\n\n"; } cout << "You have attempts: " << *attempts - ++tryes; } while (tryes < *attempts); system("cls"); cout << "\n\nLoser....\n\n"; }
[ "edik_gres@icloud.com" ]
edik_gres@icloud.com
83d9b94cb2f4f46b03962bd185ebe9638278c531
bfab85afd4f021e13029ced390b1185e2445bfd7
/TDG/graph.h
e686306db46095b15386a30b359dd45e7f5ea3bd
[]
no_license
Nmalka1109/projet-TDG
c5507b4238dfd9c4d768f0ad6c06092d5a789f70
f152fa3a6507561fb2a3d1dd4cccde1ada1830aa
refs/heads/master
2020-03-08T08:58:47.173580
2018-04-14T15:56:10
2018-04-14T15:56:10
128,034,967
0
1
null
null
null
null
ISO-8859-2
C++
false
false
728
h
#ifndef GRAPH_H_INCLUDED #define GRAPH_H_INCLUDED #include <vector> #include "Sommet.h" #include "arrete.h" using namespace std; class graphe { public : int m_ordre; vector<Sommet> m_som; vector<Arete> m_ar; ///constructeurs graphe(int a); ///destructeur ~graphe(); ///méthodes void recuperation(string name1); void affichage(); void save(int a); void supprimer(int sommet); void ajouter(int n); void modif_sommet(int ps, int i); void modif_arete(int pa, int i, int j); std::vector<int> RechercheCFC(int s); std::vector<std::vector<int>> CFCS(int s); void settemps(int t); int gettemps(); private: int tps; }; #endif // GRAPH_H_INCLUDED
[ "louis.roussel@edu.ece.fr" ]
louis.roussel@edu.ece.fr
1d7da1fd03c61fc31e92fc833c919170aa57e2d0
f29e784cae995b1a7cf230824171c4e6db5e0d98
/MagneticFieldSimulator/samplerState.h
b042b5cea050614e9e1ae5af42d1242d95dbb218
[]
no_license
Globerus/MagneticFieldVisualization
41c316834c6e1b11d9718d0b4be376b89e241a2c
b2e04f01ef8e95f07618e70ff6a43f62626fecd8
refs/heads/master
2021-01-20T19:33:42.444715
2016-06-21T17:31:47
2016-06-21T17:31:47
60,422,155
0
0
null
null
null
null
UTF-8
C++
false
false
771
h
#ifndef SAMPLER_STATE_H #define SAMPLER_STATE_H #include "drawingState.h" class SamplerState : public DrawingState { public: enum Filter { MIN_N_MAG_N_MIP_N, MIN_N_MAG_N_MIP_L, MIN_N_MAG_L_MIP_N, MIN_N_MAG_L_MIP_L, MIN_L_MAG_N_MIP_N, MIN_L_MAG_N_MIP_L, MIN_L_MAG_L_MIP_N, MIN_L_MAG_L_MIP_L, MIN_L_MAG_L, MIN_N_MAG_L, MIN_L_MAG_N, MIN_N_MAG_N, }; enum BoundaryMode { WRAP, MIRROR, CLAMP, BORDER, MIRROR_ONCE }; enum Comparison { NEVER, LESS, EQUAL, LESS_EQUAL, GREATER, NOT_EQUAL, GREATER_EQUAL, ALWAYS }; SamplerState (); Filter m_Filter; BoundaryMode m_Mode[3]; glm::vec4 m_BorderColor; Comparison m_Comparison; static int const shaderLookUp = 2; }; #endif
[ "Inter_bg@hotmail.com" ]
Inter_bg@hotmail.com
9e80cfd61a8119cf6127056aecb55f7cc0b8da0f
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function13916/function13916_schedule_8/function13916_schedule_8_wrapper.cpp
b10fcfd4f799946689e33d0cd44e7f1f3fbd11c3
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,461
cpp
#include "Halide.h" #include "function13916_schedule_8_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){ Halide::Buffer<int32_t> buf00(262144); Halide::Buffer<int32_t> buf01(262144); Halide::Buffer<int32_t> buf02(256); Halide::Buffer<int32_t> buf03(256); Halide::Buffer<int32_t> buf04(262144); Halide::Buffer<int32_t> buf05(256); Halide::Buffer<int32_t> buf06(262144); Halide::Buffer<int32_t> buf07(262144); Halide::Buffer<int32_t> buf08(256); Halide::Buffer<int32_t> buf0(262144, 256); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function13916_schedule_8(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf07.raw_buffer(), buf08.raw_buffer(), buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function13916/function13916_schedule_8/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
[ "ei_mekki@esi.dz" ]
ei_mekki@esi.dz
9294044c4362b2eaaa0e3fc3fcbd4b3442eb4d94
bdcedb3e8cbb8cd1a748423050f56b0d71dff125
/Server/meta_header/thread.h
6f71e7b7da75c3901327e987b1080732f2049f97
[ "MIT" ]
permissive
lxlyh/FxLib
f3858c21f8da76a5f7eab301de3a2539d483e82c
49e3fb12b4fe324c0b5b1503b37492dc742100de
refs/heads/master
2020-09-12T12:19:48.723598
2019-09-20T07:36:52
2019-09-20T07:36:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
844
h
#ifndef __THREAD_H__ #define __THREAD_H__ #include <stdarg.h> class IFxThread { public: virtual ~IFxThread() { } virtual void ThrdFunc() = 0; virtual void Stop() = 0; }; class IFxThreadHandler { public: virtual ~IFxThreadHandler() { } virtual void Stop(void) = 0; virtual bool Kill(unsigned int dwExitCode) = 0; virtual bool WaitFor(unsigned int dwWaitTime = 0xffffffff) = 0; virtual unsigned int GetThreadId(void) = 0; virtual IFxThread* GetThread(void) = 0; virtual void Release(void) = 0; bool IsStop(void) { return m_bIsStop; } #ifdef WIN32 void* GetHandle(void) { return m_hHandle; } protected: void* m_hHandle; // #endif // WIN32 protected: bool m_bIsStop; }; bool FxCreateThreadHandler(IFxThread* poThread, bool bNeedWaitfor, IFxThreadHandler* & refpIFxThreadHandler); #endif // !__THREAD_H__
[ "724789975@qq.com" ]
724789975@qq.com
831a273305c7287398860fd39a5922646cd8b495
ab97a8915347c76d05d6690dbdbcaf23d7f0d1fd
/chrome/browser/apps/app_service/remote_apps.cc
33779cd2b622dacaf15e09c246a9ebe008cc5153
[ "BSD-3-Clause" ]
permissive
laien529/chromium
c9eb243957faabf1b477939e3b681df77f083a9a
3f767cdd5c82e9c78b910b022ffacddcb04d775a
refs/heads/master
2022-11-28T00:28:58.669067
2020-08-20T08:37:31
2020-08-20T08:37:31
288,961,699
1
0
BSD-3-Clause
2020-08-20T09:21:57
2020-08-20T09:21:56
null
UTF-8
C++
false
false
4,212
cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/apps/app_service/remote_apps.h" #include <utility> #include "base/callback.h" #include "chrome/browser/apps/app_service/app_icon_factory.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "ui/gfx/image/image_skia.h" namespace apps { RemoteApps::RemoteApps(Profile* profile, Delegate* delegate) : profile_(profile), delegate_(delegate) { DCHECK(delegate); AppServiceProxy* proxy = AppServiceProxyFactory::GetForProfile(profile_); mojo::Remote<mojom::AppService>& app_service = proxy->AppService(); if (!app_service.is_bound()) { return; } Initialize(app_service, mojom::AppType::kRemote); } RemoteApps::~RemoteApps() = default; void RemoteApps::AddApp(const chromeos::RemoteAppsModel::AppInfo& info) { mojom::AppPtr app = Convert(info); Publish(std::move(app), subscribers_); } void RemoteApps::UpdateAppIcon(const std::string& app_id) { mojom::AppPtr app = mojom::App::New(); app->app_type = mojom::AppType::kRemote; app->app_id = app_id; app->icon_key = icon_key_factory_.MakeIconKey(IconEffects::kNone); Publish(std::move(app), subscribers_); } void RemoteApps::DeleteApp(const std::string& app_id) { mojom::AppPtr app = mojom::App::New(); app->app_type = mojom::AppType::kRemote; app->app_id = app_id; app->readiness = mojom::Readiness::kUninstalledByUser; Publish(std::move(app), subscribers_); } apps::mojom::AppPtr RemoteApps::Convert( const chromeos::RemoteAppsModel::AppInfo& info) { apps::mojom::AppPtr app = PublisherBase::MakeApp( mojom::AppType::kRemote, info.id, mojom::Readiness::kReady, info.name, mojom::InstallSource::kUser); app->show_in_launcher = mojom::OptionalBool::kTrue; app->show_in_management = mojom::OptionalBool::kFalse; app->show_in_search = mojom::OptionalBool::kTrue; app->show_in_shelf = mojom::OptionalBool::kFalse; app->icon_key = icon_key_factory_.MakeIconKey(IconEffects::kNone); return app; } void RemoteApps::Connect( mojo::PendingRemote<mojom::Subscriber> subscriber_remote, mojom::ConnectOptionsPtr opts) { mojo::Remote<mojom::Subscriber> subscriber(std::move(subscriber_remote)); std::vector<mojom::AppPtr> apps; for (const auto& entry : delegate_->GetApps()) { apps.push_back(Convert(entry.second)); } subscriber->OnApps(std::move(apps)); subscribers_.Add(std::move(subscriber)); } void RemoteApps::LoadIcon(const std::string& app_id, mojom::IconKeyPtr icon_key, mojom::IconType icon_type, int32_t size_hint_in_dip, bool allow_placeholder_icon, LoadIconCallback callback) { // TODO(crbug.com/1083331): Handle IconType::kStandard. DCHECK(icon_type != mojom::IconType::kCompressed) << "Remote app should not be shown in management"; mojom::IconValuePtr icon = mojom::IconValue::New(); gfx::ImageSkia icon_image = delegate_->GetIcon(app_id); if (!icon_image.isNull()) { icon->icon_type = icon_type; IconEffects icon_effects = (icon_type == mojom::IconType::kStandard) ? IconEffects::kCrOsStandardIcon : IconEffects::kResizeAndPad; icon->uncompressed = icon_image; apps::ApplyIconEffects(icon_effects, size_hint_in_dip, &icon->uncompressed); } std::move(callback).Run(std::move(icon)); } void RemoteApps::Launch(const std::string& app_id, int32_t event_flags, mojom::LaunchSource launch_source, int64_t display_id) { delegate_->LaunchApp(app_id); } void RemoteApps::GetMenuModel(const std::string& app_id, mojom::MenuType menu_type, int64_t display_id, GetMenuModelCallback callback) { std::move(callback).Run(delegate_->GetMenuModel(app_id)); } } // namespace apps
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ca9db17730a5ccb09f68f07b1b6d9d4be4b8147f
8ae31e5db1f7c25b6ce1c708655ab55c15dde14e
/比赛/学校/2019-11-7测试/source/PC33_jason/2.cpp
bf3763b98e261c3697396461a49a786c8a021d94
[]
no_license
LeverImmy/Codes
99786afd826ae786b5024a3a73c8f92af09aae5d
ca28e61f55977e5b45d6731bc993c66e09f716a3
refs/heads/master
2020-09-03T13:00:29.025752
2019-12-16T12:11:23
2019-12-16T12:11:23
219,466,644
1
0
null
null
null
null
UTF-8
C++
false
false
723
cpp
#include<cstdio> #include<cstring> #include<iostream> #include<vector> #include<algorithm> #include<queue> using namespace std; char s[101][101]; int cnt[5]; signed main() { freopen("2.in","r",stdin); freopen("2.out","w",stdout); int n; scanf("%d",&n); for(int i=1;i<=n;i++) cin>>s[i]+1; int len=strlen(s[1]+1); for(int i=1;i<=len;i++) { memset(cnt,0,sizeof(cnt)); for(int j=1;j<=n;j++) { if(s[j][i]=='A') cnt[1]++; if(s[j][i]=='C') cnt[2]++; if(s[j][i]=='G') cnt[3]++; if(s[j][i]=='T') cnt[4]++; } int mx=0,at=0; for(int j=1;j<=4;j++) if(cnt[j]>mx) mx=cnt[j],at=j; if(at==1) printf("A"); if(at==2) printf("C"); if(at==3) printf("G"); if(at==4) printf("T"); } return 0; }
[ "506503360@qq.com" ]
506503360@qq.com
afdb5d9819326be1daa05d673a025ec7bab4c358
31beeddf858d56c759eb95edb5153412368244b9
/Friends Pairing Problem/code_1.cpp
456be67b8d4e4e00b8087aef1334dafe55a8fc61
[ "MIT" ]
permissive
shoaibrayeen/Data-Structures-and-Algorithms
0747d37ba5c061d81e92adcab789c7ad697c415a
1320919a2693890beb7d3fa7f9235ed1e6d70cf3
refs/heads/master
2023-01-09T05:08:16.839757
2023-01-06T18:43:40
2023-01-06T18:43:40
147,175,708
38
34
MIT
2023-01-06T18:43:41
2018-09-03T08:37:02
C++
UTF-8
C++
false
false
622
cpp
// // code_1.cpp // Algorithm // // Created by Mohd Shoaib Rayeen on 23/11/18. // Copyright © 2018 Shoaib Rayeen. All rights reserved. // #include <iostream> using namespace std; int countFriendsPairings(int n) { int dp[n + 1]; for (int i = 0; i <= n; i++) { if (i <= 2) { dp[i] = i; } else { dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]; } } return dp[n]; } int main() { int n; cout << "\nEnter Number of People\t\t:\t"; cin >> n; cout << "Number of Different Pairs\t:\t" << countFriendsPairings(n) << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
8f31da4fd1cf4152369d0522a428d590ddc03d67
4016a0e87a1f36aa9eda27d800ec3709226c034d
/差分约束.cpp
9571c67113214e576ae6a2aa7f754c54cdef390e
[]
no_license
CCCTong/algorithm-template
14e8fb7044031db1f7df57f8e233d33e2e86915c
fee0f626d18baa4386e7e0c61ef3aa486dd2151c
refs/heads/master
2020-04-07T19:52:36.995561
2018-11-22T08:35:56
2018-11-22T08:35:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,276
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; ll dp[50][50],num[50]; void init(){ memset(dp, 0, sizeof(dp)); for (int i=0; i<10; i++) { dp[1][i] = 1; } for (int i=2; i<20; i++) { for (int j=0; j<10; j++) { for (int k=0; k<10; k++) { if (abs(j-k) >= 2) { dp[i][j] += dp[i-1][k]; } } } } } ll solve(string s){ ll ans = 0; for (int i=1; i<s.size(); i++) for (int j=1; j<10; j++) ans += dp[i][j]; for (int i=1; i<s[0] - '0'; i++){ ans += dp[s.size()][i]; } for (int i=1; i<s.size(); i++) { for (int j=0; j<s[i]-'0'; j++) { if (abs(j - s[i-1] + '0') >= 2) { ans += dp[s.size() - i][j]; } } if (abs(s[i-1] - s[i]) < 2) break; if (i == s.size() - 1) ans++; } if (s.size() == 1) ans++; return ans; } int main(){ int flag = 0; init(); string A,B; cin >> A >> B; ll ans = solve(B) - solve(A) ; for (int i=0; i<A.size()-1; i++) { if (abs(A[i+1] - A[i]) < 2) { flag = 1; break; } } !flag ? cout << ans + 1 << endl : cout << ans << endl; return 0; }
[ "bolizawo@163.com" ]
bolizawo@163.com
0b773cc08d404a225454d86fdf68a37120f78633
1c444bdf16632d78a3801a7fe6b35c054c4cddde
/include/bds/unmapped/Vec3Option.h
bf6da3b67deded021a595b9b360b5720798b57fe
[]
no_license
maksym-pasichnyk/symbols
962a082bf6a692563402c87eb25e268e7e712c25
7673aa52391ce93540f0e65081f16cd11c2aa606
refs/heads/master
2022-04-11T03:17:18.078103
2020-03-15T11:30:36
2020-03-15T11:30:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,198
h
#pragma once #include <string> #include "Option.h" #include <vector> class Vec3Option : public Option { public: ~Vec3Option(); // _ZN10Vec3OptionD2Ev virtual void save(std::vector<std::pair<std::string, std::string>> &); // _ZN10Vec3Option4saveERSt6vectorISt4pairINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES7_ESaIS8_EE virtual void load(std::string const&); // _ZN10Vec3Option4loadERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE virtual void load(Json::Value const&); // _ZN10Vec3Option4loadERKN4Json5ValueE // Vec3Option(OptionID, OptionOwnerType, OptionResetFlags, std::string const&, std::string const&, glm::tvec30<float, (glm::precision>); //TODO: incomplete function definition // _ZN10Vec3OptionC2E8OptionID15OptionOwnerType16OptionResetFlagsRKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESA_RKN3glm5tvec3IfLNSB_9precisionE0EEE // void set(glm::tvec30<float, (glm::precision>); //TODO: incomplete function definition // _ZN10Vec3Option3setERKN3glm5tvec3IfLNS0_9precisionE0EEEb void getValue()const; // _ZNK10Vec3Option8getValueEv void getDefault()const; // _ZNK10Vec3Option10getDefaultEv void reset(); // _ZN10Vec3Option5resetEv };
[ "honzaxp01@gmail.com" ]
honzaxp01@gmail.com
7b551e68ef97d9c23a31560e9936c065b196532a
9bcedb0048c0c7a3908d27c6bdf3def3acb27849
/Day08/Project1/Project1/LList.cpp
6c739e6957041d71f3d14eb22a3781e398c314b0
[]
no_license
youga114/AlgorithmAndDX
653b2e60fa605584353120468febcedf938c59f8
ea94a3bc94aae80e5c188e2596e61a01b39bc290
refs/heads/master
2020-06-02T21:36:21.462739
2019-07-23T09:52:54
2019-07-23T09:52:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
22
cpp
#include "LList.h"
[ "youga114@naver.com" ]
youga114@naver.com
3f0244143170c2624b483fe790b9f646ec7b60fa
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_PrimalItemConsumable_UnderwaterEgg_Toad_Aberrant_structs.hpp
03a43acac3f232187d9cc2cee02f9443e9855724
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
282
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Basic.hpp" #include "ARKSurvivalEvolved_PrimalItemConsumable_UnderwaterEgg_Toad_classes.hpp" namespace sdk { } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
6b824b746cd0743681a64b4151e2aa9581c65aba
46ebadfdd95f8163d7d2877e608cd716b64eae98
/cpp/OFW/SoundCubes_8/src/ofxVectorMath/CuParticle.cpp
fe6d75a968fa2fe965d54c9a9d619e22ac73bfc1
[]
no_license
emmanuelflores/shanghai-mvp
75f52eac7bbc0269f4c858c846760721fe8d182e
fe731d92f95b78fefb71230a0cffaa7bf578bbcb
refs/heads/master
2021-10-10T19:28:02.908755
2019-01-15T21:36:36
2019-01-15T21:36:36
14,225,122
0
0
null
null
null
null
UTF-8
C++
false
false
3,512
cpp
// // CuParticle.cpp // CubesSound // // Created by efe on 1/30/13. // // #include "CuParticle.h" #include "mathCubes.h" CuParticle::CuParticle() { } CuParticle::CuParticle( ofVec3f pos, ofVec3f vel ) { mPos = pos; mTailPos = pos; mVel = vel; mVelNormal = ofVec3f(0,1,0); mAcc = ofVec3f::zero(); mColor = ofColor(1,1,1,1); mNeighborPos = ofVec3f::zero(); mNumNeighbors = 0; mMaxSpeed = (float)ofRandom( 2.5f, 3.0f ); mMaxSpeedSqrd = mMaxSpeed * mMaxSpeed; mMinSpeed = (float)ofRandom( 1.0f, 1.5f ); mMinSpeedSqrd = mMinSpeed * mMinSpeed; mDecay = 0.99f; mRadius = 1.0f; mLength = 10.0f; mCrowdFactor = 1.0f; r = (int)ofRandom(0,255); g = (int)ofRandom(30, 130); b = (int)ofRandom(130,255); } void CuParticle::pullToCenter( const ofVec3f &center ) { ofVec3f dirToCenter = mPos - center; float distToCenter = dirToCenter.length(); float maxDistance = 300.0f; if( distToCenter > maxDistance ){ dirToCenter.normalize(); float pullStrength = 0.0008f; mVel -= dirToCenter * ( ( distToCenter - maxDistance ) * pullStrength ); } } void CuParticle::update( bool flatten ) { //Take care of the tail ofVec3f posOffset1 = mPos; ofVec3f posOffset2 = mPos; posOffset1.x = mPos.x - 1; posOffset2.x = mPos.x + 1; tailPositions.push_back(posOffset1); tailPositions.push_back(posOffset2); if (tailPositions.size() > 50) { tailPositions.erase( tailPositions.begin(), tailPositions.begin()+2); } float alphaValue = 1.0f; tailAlpha.push_back( alphaValue ); tailAlpha.push_back( alphaValue ); //we're pushing alphaValue twice on purpose as we're drawing quads if (tailAlpha.size() > 50) { tailAlpha.erase( tailAlpha.begin(), tailAlpha.begin()+2); } for (int i = 0; i < tailAlpha.size(); i++) { tailAlpha[i] = tailAlpha[i] - 0.02f; } //Crowd Factor mCrowdFactor -= ( mCrowdFactor - ( 1.0f - mNumNeighbors * 0.01f ) ) * 0.1f; if( flatten ) mAcc.z = 0.0f; mVel += mAcc; mVelNormal = mVel.normalized(); limitSpeed(); mPos += mVel; if( flatten ) mPos.z = 0.0f; mTailPos = mPos - ( mVelNormal * mLength ); mVel *= mDecay; mAcc = ofVec3f::zero(); float c = mNumNeighbors/50.0f; //mColor = ColorA( CM_HSV, math<float>::max( 1.0f - c, 0.0f ), c, c + 0.5f, 1.0f ); mColor = ofColor(math<int>::max(255-c,0),c,c+125,255); //mColor = ofColor( math<float>::max( 1.0f - c, 0.0f ), c, c + 0.5f, 1.0f ); mNeighborPos = ofVec3f::zero(); mNumNeighbors = 0; } void CuParticle::limitSpeed() { float vLengthSqrd = mVel.lengthSquared(); if( vLengthSqrd > mMaxSpeedSqrd ){ mVel = mVelNormal * mMaxSpeed; } else if( vLengthSqrd < mMinSpeedSqrd ){ mVel = mVelNormal * mMinSpeed; } } void CuParticle::draw() { ofSetColor(r, g, b); ofSphere(mPos.x, mPos.y, mPos.z, mRadius+4); // glBegin(GL_QUAD_STRIP); // // for (int i = 0; i < tailPositions.size(); i++) { // ofSetColor(r, g, b, tailAlpha[i]); // glVertex3f ( tailPositions[i].x, tailPositions[i].y, tailPositions[i].z ); // } // glEnd(); } void CuParticle::drawTail() { ofSetColor(255,255,255); //glVertex3fv( mPos ); glVertex3f(mPos.x,mPos.y,mPos.z); ofSetColor(255, 0, 0,255); // glVertex3fv( mTailPos ); glVertex3f(mTailPos.x,mTailPos.y,mTailPos.z); } void CuParticle::addNeighborPos( ofVec3f pos ) { mNeighborPos += pos; mNumNeighbors ++; }
[ "efeapple@gmail.com" ]
efeapple@gmail.com
647b892b5426ded0f96f48e70f8081cfa198523a
637c4892287929583bdadd8630d5353dd78dc82c
/test/jacobi/hybrid/C++/jacobi.cpp.opari.inc
72549ebeafcf804a03677c8bf2b4c99ee5297fb9
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
readex-eu/readex-scorep
6819f074bba6b4fe9d6de07cf7037d2829cbbccf
38d7b84145f229b44670656d59f84faa51007ced
refs/heads/master
2020-03-27T01:04:12.730561
2018-08-22T14:42:37
2018-08-22T14:42:37
145,679,275
1
0
null
null
null
null
UTF-8
C++
false
false
945
inc
#include <opari2/pomp2_lib.h> #include <stdint.h> extern "C" { extern int64_t FORTRAN_MANGLED(pomp_tpd); } #pragma omp threadprivate(FORTRAN_MANGLED(pomp_tpd)) #define POMP2_DLIST_00001 shared(pomp2_region_1,pomp2_region_2) static POMP2_Region_handle pomp2_region_1 = NULL; #define pomp2_ctc_1 "247*regionType=parallel*sscl=jacobi.cpp:67:67*escl=jacobi.cpp:88:88**" static POMP2_Region_handle pomp2_region_2 = NULL; #define pomp2_ctc_2 "257*regionType=for*sscl=jacobi.cpp:72:72*escl=jacobi.cpp:87:87*hasReduction=1**" #define POMP2_DLIST_00003 shared(pomp2_region_3) static POMP2_Region_handle pomp2_region_3 = NULL; #define pomp2_ctc_3 "254*regionType=parallelfor*sscl=jacobi.cpp:154:154*escl=jacobi.cpp:161:161**" extern "C" { void POMP2_Init_reg_4h6ldx9tlnr9d_3() { POMP2_Assign_handle( &pomp2_region_1, pomp2_ctc_1 ); POMP2_Assign_handle( &pomp2_region_2, pomp2_ctc_2 ); POMP2_Assign_handle( &pomp2_region_3, pomp2_ctc_3 ); } }
[ "robert.schoene@tu-dresden.de" ]
robert.schoene@tu-dresden.de
f5e6f86aad0bd8604357cee362089920b9b9ae09
45e8df26d895fce1ffced77e2fc7c87aa5fcec71
/codeforces/723/A/sol.cc
7f55bee6f815ba8da1f9a5d684a5cd8de8e56646
[]
no_license
mikehung/competitive-programming
5c4b429942357bfbe3c8ff2820d5cb5b7c5dc828
50713dc5973f2ea42220ac0248c3d1a6d90fcc15
refs/heads/master
2021-06-20T08:21:36.837057
2021-01-01T01:29:56
2021-01-01T01:31:55
153,595,870
1
0
null
null
null
null
UTF-8
C++
false
false
453
cc
#include <bits/stdc++.h> using namespace std; #ifdef DEBUG #define dbg(...) fprintf(stderr, __VA_ARGS__) #else #define dbg(...) #endif int main() { ios::sync_with_stdio(false); cin.tie(0); int a, b, c, ans = 5000; cin >> a >> b >> c; int mx = max(a, max(b, c)), mn = min(a, min(b, c)); for (int i = mn; i <= mx; ++i) { ans = min(ans, abs(a-i)+abs(b-i)+abs(c-i)); } cout << ans << '\n'; return 0; }
[ "slaotvaen@gmail.com" ]
slaotvaen@gmail.com
095bab7114046146e2b482ccf793049473e1809f
583502660903ffca16e377da575a5516c67169ac
/ComputerGraphics/Assignment3/Assignment3Code/PLY.cpp
bf7dc48463222de1694aa51194eb79b6ffbd41be
[]
no_license
HungryAdi/Coursework
4aa00c5d1ae822c423435251bd29db8c0922fca1
1447271ea15aac30c3cc4f865ebef4dcb7c27d74
refs/heads/master
2022-04-04T09:28:31.526519
2020-02-19T19:09:02
2020-02-19T19:09:02
105,039,802
0
0
null
null
null
null
UTF-8
C++
false
false
14,263
cpp
/* * PLY.cpp * PointProcessing * * Created by Renato Pajarola on Wed Nov 05 2003. * Copyright (c) 2003 __MyCompanyName__. All rights reserved. * */ #include <algorithm> #include <stdlib.h> #include <string.h> #include <float.h> #include <math.h> #ifdef WIN32 #include <windows.h> #endif #ifdef __APPLE__ #include <glut/glut.h> #else #include <GL/glut.h> #endif #include "PLY.h" #include "geometry.h" extern int light; //Helper Functions float magnitude(Vector3f v) { float x = v[0]; float y = v[1]; float z = v[2]; x *= x; y *= y; z *= z; float mag = sqrtf(x + y + z); return mag; } // Light and other info extern Vector3f light_pos, viewer_pos; extern Vector4f light_color, ambient_light; // Material properties GLfloat ambient[4] = {0.2, 0.2, 0.2, 1.0}; GLfloat diffuse[4] = {0.7, 0.7, 1.0, 1.0}; GLfloat specular[4] = {0.5, 0.5, 0.5, 1.0}; GLfloat shininess[1] = {5.0}; PLYObject::PLYObject(FILE *in) { int i; nproperties = 0; hasnormal = hastexture = false; nv = nf = 0; vertices = NULL; normals = NULL; colors = NULL; texcoords = NULL; faces = NULL; // init bounding box for (i = 0; i < 3; i++) { min[i] = FLT_MAX; max[i] = -FLT_MAX; } // default order for (i = 0; i < 11; i++) order[i] = -1; if (!checkHeader(in)) { fprintf(stderr, "Error: could not read PLY file.\n"); return; } vertices = (Vector3f*)calloc(nv, sizeof(Vector3f)); normals = (Vector3f*)calloc(nv, sizeof(Vector3f)); colors = (Color3u*)calloc(nv, sizeof(Color3u)); if (hastexture) texcoords = (Texture2f*)calloc(nv, sizeof(Texture2f)); faces = (Index3i*)calloc(nf, sizeof(Index3i)); fnormals = (Vector3f*)calloc(nf, sizeof(Vector3f)); readVertices(in); readFaces(in); } PLYObject::~PLYObject() { // delete all allocated arrays if (vertices) free(vertices); if (normals) free(normals); if (colors) free(colors); if (texcoords) free(texcoords); if (faces) free(faces); } bool PLYObject::checkHeader(FILE *in) { char buf[128], type[128], c[32]; int i; // read ply file header fscanf(in, "%s\n", buf); if (strcmp(buf, "ply") != 0) { fprintf(stderr, "Error: Input file is not of .ply type.\n"); return false; } fgets(buf, 128, in); if (strncmp(buf, "format ascii", 12) != 0) { fprintf(stderr, "Error: Input file is not in ASCII format.\n"); return false; } fgets(buf, 128, in); while (strncmp(buf, "comment", 7) == 0) fgets(buf, 128, in); // read number of vertices if (strncmp(buf, "element vertex", 14) == 0) sscanf(buf, "element vertex %d\n", &nv); else { fprintf(stderr, "Error: number of vertices expected.\n"); return false; } // read vertex properties order i = 0; fgets(buf, 128, in); while (strncmp(buf, "property", 8) == 0) { sscanf(buf, "property %s %s\n", type, c); if (strncmp(c, "x", 1) == 0) order[0] = i; else if (strncmp(c, "y", 1) == 0) order[1] = i; else if (strncmp(c, "z", 1) == 0) order[2] = i; else if (strncmp(c, "nx", 2) == 0) order[3] = i; else if (strncmp(c, "ny", 2) == 0) order[4] = i; else if (strncmp(c, "nz", 2) == 0) order[5] = i; else if (strncmp(c, "red", 3) == 0) order[6] = i; else if (strncmp(c, "green", 5) == 0) order[7] = i; else if (strncmp(c, "blue", 4) == 0) order[8] = i; else if (strncmp(c, "tu", 2) == 0) order[9] = i; else if (strncmp(c, "tv", 2) == 0) order[10] = i; i++; fgets(buf, 128, in); } nproperties = i; for (i = 0; i < 3; i++) { if (order[i] < 0) { fprintf(stderr, "Error: not enough vertex coordinate fields (nx, ny, nz).\n"); return false; } } hasnormal = true; for (i = 3; i < 6; i++) if (order[i] < 0) hasnormal = false; hascolor = true; for (i = 6; i < 9; i++) if (order[i] < 0) hascolor = false; hastexture = true; for (i = 9; i < 11; i++) if (order[i] < 0) hastexture = false; if (!hasnormal) fprintf(stderr, "Warning: no normal coordinates used from file.\n"); if (!hascolor) fprintf(stderr, "Warning: no color used from file.\n"); if (!hastexture) fprintf(stderr, "Warning: no texture coordinates used from file.\n"); // number of faces and face properties if (strncmp(buf, "element face", 12) == 0) sscanf(buf, "element face %d\n", &nf); else { fprintf(stderr, "Error: number of faces expected.\n"); return false; } fgets(buf, 128, in); if (strncmp(buf, "property list", 13) != 0) { fprintf(stderr, "Error: property list expected.\n"); return false; } fgets(buf, 128, in); while (strncmp(buf, "end_header", 10) != 0) fgets(buf, 128, in); return true; } void PLYObject::readVertices(FILE *in) { char buf[128]; int i, j; float values[32]; // read in vertex attributes for (i = 0; i < nv; i++) { fgets(buf, 128, in); sscanf(buf,"%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5], &values[6], &values[7], &values[8], &values[9], &values[10], &values[11], &values[12], &values[13], &values[14], &values[15]); for (j = 0; j < 3; j++) vertices[i][j] = values[order[j]]; if (hasnormal) for (j = 0; j < 3; j++) normals[i][j] = values[order[3+j]]; if (hascolor) for (j = 0; j < 3; j++) colors[i][j] = (unsigned char)values[order[6+j]]; if (hastexture) for (j = 0; j < 2; j++) texcoords[i][j] = values[order[9+j]]; for (j = 0; j < 3; j++) { if (vertices[i][j] < min[j]) min[j] = vertices[i][j]; if (vertices[i][j] > max[j]) max[j] = vertices[i][j]; } } } void PLYObject::readFaces(FILE *in) { char buf[128]; int i, j, k; // read in face connectivity for (i = 0; i < nf; i++) { fgets(buf, 128, in); sscanf(buf, "%d %d %d %d", &k, &faces[i][0], &faces[i][1], &faces[i][2]); if (k != 3) { fprintf(stderr, "Error: not a triangular face.\n"); exit(1); } // set up face normal normal(fnormals[i], vertices[faces[i][0]], vertices[faces[i][1]], vertices[faces[i][2]]); // accumulate normal information of each vertex if (!hasnormal) for (j = 0; j < 3; j++) for (k = 0; k < 3; k++) normals[faces[i][j]][k] += fnormals[i][k]; } if (!hasnormal) for (i = 0; i < nv; i++) normalize(normals[i]); hasnormal = true; } void PLYObject::resize() { int i; float minx, miny, minz, maxx, maxy, maxz; float size, scale; // get bounding box minx = miny = minz = FLT_MAX; maxx = maxy = maxz = -FLT_MAX; for (i = 0; i <nv; i++) { if (vertices[i][0] < minx) minx = vertices[i][0]; if (vertices[i][0] > maxx) maxx = vertices[i][0]; if (vertices[i][1] < miny) miny = vertices[i][1]; if (vertices[i][1] > maxy) maxy = vertices[i][1]; if (vertices[i][2] < minz) minz = vertices[i][2]; if (vertices[i][2] > maxz) maxz = vertices[i][2]; } // rescale vertex coordinates to be in [-1,1] size = 0.0; if (size < maxx-minx) size = maxx-minx; if (size < maxy-miny) size = maxy-miny; if (size < maxz-minz) size = maxz-minz; scale = 2.0 / size; for (i = 0; i < nv; i++) { vertices[i][0] = scale * (vertices[i][0] - minx) - 1.0; vertices[i][1] = scale * (vertices[i][1] - miny) - 1.0; vertices[i][2] = scale * (vertices[i][2] - minz) - 1.0; } } void PLYObject::invertNormals() { int i, tmp; for (i = 0; i < nv; i++) scale(normals[i], -1.0); for (i = 0; i < nf; i++) { scale(fnormals[i], -1.0); tmp = faces[i][0]; faces[i][0] = faces[i][2]; faces[i][2] = tmp; } } void PLYObject::draw() { // setup default material glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess); glColor3fv(diffuse); // set lighting if enabled // Otherwise, compute colors if (light) { glEnable(GL_LIGHTING); } else { // Temporary variables to be used when computing vertex colors Vector3f V, L, H, amb, dif, spe, total, temp; glDisable(GL_LIGHTING); for (int v=0; v<nv; v++) { // Vertex color = (material emission) + (global ambient)*(material ambient) + // (1/( k1+ k2d + k3d 2)) * [(light ambient)*(material ambient) + (max{L.N, 0})*(light diffuse)*(material diffuse) + (max{H.N,0})n *(light specular)*(material specular) ] // ----- TODO : Begin ------ // Instead of this, use the Phong illumination equation to find the color // colors[v][0] = v%256; // colors[v][1] = (2*v)%256; // colors[v][2] = (3*v)%256; //finding L and V for (int i = 0; i < 3; i++) { L[i] = light_pos[i]; } normalize(L); for (int i = 0; i < 3; i++) { V[i] = viewer_pos[i]; } normalize(V); //finding H add(H, L, V); scale(H, 1/magnitude(H)); float d = normalize(H); Vector4f lightAmbient, lightSpecular , lightDiffuse, globalAmbient = {1.0f,1.0f,1.0f,0.0f} , emission = {0,0,0,0} ; glGetLightfv(GL_LIGHT0, GL_AMBIENT, lightAmbient); glGetLightfv(GL_LIGHT0, GL_SPECULAR, lightSpecular); glGetLightfv(GL_LIGHT0, GL_DIFFUSE, lightDiffuse); glGetFloatv( GL_LIGHT_MODEL_AMBIENT, globalAmbient); glGetLightfv(GL_LIGHT0, GL_EMISSION, emission); //emission float k1, k2, k3; glGetLightfv(GL_LIGHT0, GL_CONSTANT_ATTENUATION, &k1); glGetLightfv(GL_LIGHT0, GL_LINEAR_ATTENUATION, &k2); glGetLightfv(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, &k3); float atten = 1/(k1+(k2*d)+(k3*(d*d))); //Implementing Equation multVectors(total,globalAmbient,ambient); add(total,emission); //In brackets multVectors(amb,lightAmbient, ambient); float dotProductDiff = dotProd(L, normals[v]); float maxDiff = std::max(dotProductDiff, 0.0f); multVectors(dif, lightDiffuse, diffuse); scale(dif,maxDiff); float dotProductSpec = dotProd(H, normals[v]); float maxSpec = std::max(dotProductSpec, 0.0f); multVectors(spe, lightSpecular, specular); scale(spe,maxSpec); add(temp,spe,dif); add(temp,amb); scale(temp,atten); add(total,temp); colors[v][0] = total[0]*255; colors[v][1] = total[1]*255; colors[v][2] = total[2]*255; // ----- TODO : End ------ } } // Now do the actual drawing of the model glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glBegin(GL_TRIANGLES); for (int i = 0; i < nf; i++) { for (int j = 0; j < 3; j++) { glColor3ubv((GLubyte*)colors[faces[i][j]]); glNormal3fv(normals[faces[i][j]]); // vertex normal glVertex3fv(vertices[faces[i][j]]); // vertex coordinates } } glEnd(); glDisable(GL_POLYGON_OFFSET_FILL); if (hascolor) glDisable(GL_COLOR_MATERIAL); } void PLYObject::eat() { float scale = 0.01; /* Jitter each vertex */ for(int i=0 ; i<nv ;i++) for(int j=0 ; j<3 ; j++) { vertices[i][j] += scale*normals[i][j]; } } void PLYObject::starve() { float scale = -0.01; /* Jitter each vertex */ for(int i=0 ; i<nv ;i++) for(int j=0 ; j<3 ; j++) { vertices[i][j] += scale*normals[i][j]; } } void PLYObject::dance() { /* This creates a random vector */ Vector3f randomvector; randomvector[0] = rangerand(-0.1, 0.1, 30); randomvector[1] = rangerand(-0.1, 0.1, 30); randomvector[2] = rangerand(-0.1, 0.1, 30); /* Insert code here to add randomvector to all vertices in the PLYObject */ /* Iterate over all the vertices and add randomvector to each one. */ /* The vertex positions are stored in the array called 'vertices' */ for (int v=0 ; v<nv ; v++) { vertices[v][0] += randomvector[0]; vertices[v][1] += randomvector[1]; vertices[v][2] += randomvector[2]; } } /* A not too good pseudo-random number generator */ /* Returns a pseudo-random number between min and max */ double PLYObject::rangerand(double min, double max, long steps) { return min + ((rand() % steps) * (max - min)) / steps; }
[ "hungryadii@gmail.com" ]
hungryadii@gmail.com
27d5e4fa0881f0b3cf8c576215b3eb42ba6bbe46
58a9464987e5faf1fc4f127af4e0909fb2c67678
/sudoku.cpp
4ca0d5ad87252d86ec391ba7f0131b3158755d15
[]
no_license
DropLee/Sudoku
d13289f7b010c7a7bfacc50e2b77da1dcc31cccc
b7879c9c384082488dc51a6fc1be193680864c4e
refs/heads/master
2020-11-30T13:10:30.947041
2019-12-27T13:41:52
2019-12-27T13:41:52
230,403,252
0
0
null
null
null
null
UTF-8
C++
false
false
7,665
cpp
// sudoku.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <cstdio> #include <string> #include <cstring> #include <iostream> #include <fstream> #include <istream> #include <algorithm> #include <cmath> #include <time.h> using namespace std; string g_row[9] = { //sudoku template start with 3(1120173002 (0+2)mod9 + 1 = 3) "345678912", "678912345", "912345678", "234567891", "567891234", "891234567", "456789123", "123456789", "789123456", }; char g_output[200000000]; //output temp char g_input[200000000]; //input temp int unsolvedSudoku[10][10]; //save each unsolved sudoku int rowMark[10][10]; //row numbers' status int colMark[10][10]; //column numbers' status int blockMark[10][10]; //block numbers' status int row[10], col[10], block[10];//how many numbers in each unit int blank[100][3]; //save the location and status of blanks in sudoku int blankCounter = 0; //count number of blanks inline void Write(); inline int BlockNum(int r, int c); //calculate block location inline void Swap(int* a, int* b); inline void SetMark(int r, int c, int n, bool flag); void Reset(); bool DFS(int deep); void SolveSudoku(string path) { ifstream ReadFile(path); if (!ReadFile.is_open()) { cout << "== Invalid Path ==" << endl; cout << "Check your file path!" << endl; return; } int counter = 0; while (!ReadFile.eof()) { ReadFile >> g_input[counter++]; } ReadFile.close(); int iPointer = 0; int oPointer = 0; while (g_input[iPointer]) { for (int r = 1; r < 10; r++) { for (int c = 1; c < 10; c++) { unsolvedSudoku[r][c] = g_input[iPointer++] - 48; if (unsolvedSudoku[r][c] == 0) //count and save blanks { blank[blankCounter][0] = r; blank[blankCounter][1] = c; blankCounter++; } else //save the filled numbers' status { SetMark(r, c, unsolvedSudoku[r][c], 1); row[r]++; col[c]++; block[BlockNum(r, c)]++; } } } for (int i = 0; i < blankCounter; i++) { int r = blank[blankCounter][0], c = blank[blankCounter][1]; blank[blankCounter][2] = row[r] + col[c] + block[BlockNum(r, c)]; } for (int i = 0; i < blankCounter; i++) //sort { int m = i; for (int j = i; j < blankCounter - 1; j++) { if (blank[m][2] < blank[j + 1][2]) m = j + 1; } Swap(blank[i], blank[m]); } if (DFS(0)) { for (int r = 1; r < 10; r++) { for (int c = 1; c < 10; c++) { g_output[oPointer++] = unsolvedSudoku[r][c] + '0'; if (c == 9) g_output[oPointer++] = '\n'; else g_output[oPointer++] = ' '; } } g_output[oPointer++] = '\n'; } Reset(); } Write(); } void CreateSudoku(int& n) { int arr[] = { 4,1,2,3,5,6,7,8,9 }; //default transform order int order[] = { 0,1,2,3,4,5,6,7,8 }; //default write order int trans[9]; //transform table int newRow[9][9]; //save transformed rows int tempPointer = 0; do { for (int i = 0; i < 9; ++i) //make transform table trans[g_row[0][i] - 49] = arr[i]; for (int i = 0; i < 9; ++i) //transform 9 rows of sudoku and save in newRow for (int j = 0; j < 9; ++j) newRow[i][j] = trans[g_row[i][j] - 49]; for (int i = 0; i < 2 && n; i++) //Swap rows of transformed sudoku and save in temp array { for (int j = 0; j < 6 && n; j++) { for (int k = 0; k < 6 && n; k++) { for (int m = 0; m < 9; ++m) { for (int n = 0; n < 9; ++n) { g_output[tempPointer++] = newRow[order[m]][n] + '0'; if (n == 8) g_output[tempPointer++] = '\n'; else g_output[tempPointer++] = ' '; } } if (--n) g_output[tempPointer++] = '\n'; else return; next_permutation(order + 6, order + 9); } next_permutation(order + 3, order + 6); } next_permutation(order + 1, order + 3); } } while (next_permutation(arr + 1, arr + 9)); //change the transform order return; } int main(int argc, char* argv[]) { clock_t start, finish; start = clock(); if (argc != 3) //check number of arguments { cout << "== Invalid Arguments ==" << endl; cout << "If the file path contains spaces:" << endl; cout << "1.Use backslash before spaces as escape character" << endl; cout << "2.Quotes the path with double quotation mark" << endl; return 0; } if (strcmp(argv[1], "-c") && strcmp(argv[1], "-s")) //check command type { cout << "== Invalid Command ==" << endl; cout << "This applicaiton only supports create(-c) and solve(-s) functions!" << endl; return 0; } switch (argv[1][1]) { case 'c': { int num = atoi(argv[2]); if (num <= 0 || strlen(argv[2]) != double(log10(num)) + 1 || num > 1000000)//check range and letter { cout << "== Invalid Input ==" << endl; cout << "Make sure the number is in the range of 1-1,000,000!" << endl; return 0; } else { CreateSudoku(num); Write(); } break; } case 's': { SolveSudoku(argv[2]); break; } } finish = clock(); cout << "Used time = " << (double(finish) - double(start)) / CLOCKS_PER_SEC << "s" << endl; return 0; } /** * Other functions */ inline int BlockNum(int r, int c) { return ((r - 1) / 3) * 3 + ((c - 1) / 3); } inline void SetMark(int r, int c, int n, bool flag) { rowMark[r][n] = flag; colMark[c][n] = flag; blockMark[BlockNum(r, c)][n] = flag; } inline void Swap(int* a, int* b) { int temp[3]; temp[0] = a[0]; temp[1] = a[1]; temp[2] = a[2]; a[0] = b[0]; a[1] = b[1]; a[2] = b[2]; b[0] = temp[0]; b[1] = temp[1]; b[2] = temp[2]; return; } void Reset() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { rowMark[i][j] = 0; colMark[i][j] = 0; blockMark[i][j] = 0; unsolvedSudoku[i][j] = 0; } row[i] = 0; col[i] = 0; block[i] = 0; } blankCounter = 0; for (int i = 0; i < 100; ++i) { blank[i][0] = 0; blank[i][1] = 0; blank[i][2] = 0; } return; } bool DFS(int deep) { if (deep == blankCounter) //done { return true; } int r = blank[deep][0], c = blank[deep][1]; for (int i = 1; i < 10; i++) { if (!rowMark[r][i] && !colMark[c][i] && !blockMark[BlockNum(r, c)][i]) { unsolvedSudoku[r][c] = i; SetMark(r, c, unsolvedSudoku[r][c], 1); //fill if (DFS(deep + 1))return true; SetMark(r, c, unsolvedSudoku[r][c], 0); //unfill unsolvedSudoku[r][c] = 0; } } return false; } void Write() { remove("sudoku.txt"); ofstream WriteFile("sudoku.txt"); WriteFile << g_output; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
[ "noreply@github.com" ]
noreply@github.com
473ac38ec0a6698641ef833dd1c58abe4840c252
9291fdaf87f7720d2ab94fb974961fdc0c5f3569
/ProPinballBridge/AssemblyInfo.cpp
c682dcd3e69f89d088597bef1e1b9148a246611b
[ "MIT" ]
permissive
mjrgh/DirectOutput
e1133d321722836a5f503c118e4424d079412ddd
47712355dc8537918d94b122fa25902f5b42e0c5
refs/heads/master
2023-07-20T01:47:57.468805
2023-07-06T18:33:45
2023-07-06T18:33:45
69,528,472
13
18
MIT
2023-07-06T18:33:47
2016-09-29T03:49:36
C#
UTF-8
C++
false
false
1,266
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute(L"ProPinballBridge")]; [assembly:AssemblyDescriptionAttribute(L"")]; [assembly:AssemblyConfigurationAttribute(L"")]; [assembly:AssemblyCompanyAttribute(L"")]; [assembly:AssemblyProductAttribute(L"ProPinballBridge")]; [assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2016")]; [assembly:AssemblyTrademarkAttribute(L"")]; [assembly:AssemblyCultureAttribute(L"")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)];
[ "freezy@kodi.tv" ]
freezy@kodi.tv
7742bf442163d5032d541728ab8033676800d064
9bf1d7aacb297ed1eae8f8436db500e761af2d86
/apple.cpp
bbc5daac5ffbf3affa7d2f94609bef1e29773b79
[]
no_license
Curriosityy/Snake
8cd35f3d4393da06279965489306947e86f0b0e0
2d183d0278190d997ec3b00f751cd7ec78670193
refs/heads/master
2021-01-01T05:12:34.877141
2016-06-08T16:30:42
2016-06-08T16:30:42
57,597,133
0
0
null
2016-05-12T14:12:19
2016-05-01T12:14:25
C++
UTF-8
C++
false
false
136
cpp
#include "apple.h" apple::apple() { rect.setSize(sf::Vector2f(10, 10)); rect.setFillColor(sf::Color::Red); } apple::~apple() { }
[ "patryk9595@gmail.com" ]
patryk9595@gmail.com
667363c5799ef5955c427fbfde3946507665e08e
1c0f792e5266fe732bf3ed4153693a1f4af69cc0
/Flux++/include/backend/xcb_renderer_fwd.hpp
d7424a40402190b22166d30f73916c4de9a6a4ab
[ "MIT" ]
permissive
Glinrens-corner/Fluxpp
82850cf904652d6aaee88b3f4b75049e8fe6840d
ea64b56d2922a0ab2a946c6a75ceb5633c5ec943
refs/heads/master
2023-06-11T17:08:53.091850
2021-05-17T12:45:57
2021-05-17T12:45:57
341,190,474
2
1
null
2021-03-25T18:19:52
2021-02-22T12:18:35
C++
UTF-8
C++
false
false
245
hpp
#ifndef FLUXPP_XCB_RENDERER_FWD_HPP #define FLUXPP_XCB_RENDERER_FWD_HPP namespace fluxpp { namespace backend{ namespace xcb { class XCBRenderer ; } // backend } // xcb } // fluxpp #endif // FLUXPP_XCB_RENDERER_FWD_HPP
[ "glinren.kre@gmail.com" ]
glinren.kre@gmail.com
5fcc0d3ef7c47f78edb5ebf752ac2c9950faab74
0294f7e787793a7ab5fe6ab64204e3f30dff7729
/basketball/sampson1.cpp
943c68bba1cff2cf6d3037bd3fa7a4088943fecb
[]
no_license
cfelps/solution1
6dbfaee1e49e3f304e6cd56d8583fe9c85ca9e57
b2fec4500d03c39d96c9f0bd50853b074bc08d22
refs/heads/master
2020-06-16T22:33:16.556357
2016-11-30T17:58:26
2016-11-30T17:58:26
75,061,182
0
0
null
null
null
null
UTF-8
C++
false
false
218
cpp
#include "sampson.h" #include "mainform.h" System::Void basketball::sampson::button1_Click(System::Object^ sender, System::EventArgs^ e) { MyForm^ mainForm = gcnew MyForm(); mainForm->Show(); this->Hide(); }
[ "Juche@DESKTOP-QH9D34P" ]
Juche@DESKTOP-QH9D34P
4bd5859efc0f7146844eaa6b02cf5842ab5962ec
7d08993cdb62c362b3d3360e91945858863e7769
/snake/main.cpp
9af766c91d2a3c0515d028e4aef54bc12d78c8ae
[]
no_license
haolei2/lanmo
d8d199449bd6d826734eb4ee4be365bfc49d619f
6e5fbce9d0af653e82155ebbc1f643ba09247e3b
refs/heads/master
2020-04-03T11:28:31.629252
2020-02-02T11:52:20
2020-02-02T11:52:20
155,222,843
1
0
null
null
null
null
GB18030
C++
false
false
3,615
cpp
#define _CRT_SECURE_NO_WARNINGS #include <graphics.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <conio.h> #define MAXSNAKE 1000 HWND hwnd = NULL; int cas = 1; int speed = 50; typedef struct Point { int x; int y; }MYPOINT; struct mySnake { int num; MYPOINT p[MAXSNAKE]; char pos; //蛇的方向 }snake; struct myFood { MYPOINT fdxy; int flag; int eatgrade; }food; enum movPostion { right = 72, left = 75, down = 77, up = 80 }; void initSnake() { snake.num = 3; int position = 20; for (int i = 0; i < snake.num; i++) { snake.p[i].x = position; snake.p[i].y = 0; position -= 10; } snake.pos = right; food.flag = 0; } void drawSnake() { for (int i = 0; i < snake.num; i++) { setcolor(BLACK); setfillcolor(BLACK); fillrectangle(snake.p[i].x, snake.p[i].y, snake.p[i].x+10, snake.p[i].y+10); } } void moveSnake() { for (int i = snake.num - 1; i > 0; i--) { snake.p[i] = snake.p[i-1]; } switch (snake.pos) { case right: snake.p[0].x += 10; break; case left: snake.p[0].x -= 10; break; case down: snake.p[0].y += 10; break; case up: snake.p[0].y -= 10; break; default: break; } } void keyDown() { char ch = _getch(); switch (ch) { case right: if (snake.pos != down) snake.pos = up; break; case left: if (snake.pos != right) snake.pos = left; break; case down: if (snake.pos != left) snake.pos = right; break; case up: if (snake.pos != up) snake.pos = down; break; default: break; } } void initfood() { while (1) { bool is_ok = true; food.fdxy.x = (rand() % 62)*10; food.fdxy.y = (rand() % 47)*10; food.flag = 1; for (int i = 0; i < snake.num; i++) { if (food.fdxy.x == snake.p[i].x && food.fdxy.y == snake.p[i].y) { is_ok = false; } } if (is_ok) break; } } void drawfood() { setlinecolor(BLACK); setfillcolor(BLACK); fillrectangle(food.fdxy.x, food.fdxy.y, food.fdxy.x+10, food.fdxy.y + 10); } void eatFood() { if (food.fdxy.x == snake.p[0].x && food.fdxy.y == snake.p[0].y) { snake.num++; food.eatgrade += 1; food.flag = 0; } } int gameOver() { if (snake.p[0].x < 0 || snake.p[0].y < 0 || snake.p[0].x>640 - 10 || snake.p[0].y>480-10) { MessageBox(hwnd, (LPCWSTR)L"游戏结束",(LPCWSTR)L"失败!",0); return 0; } for (int i = 1; i < snake.num; i++) { if (snake.p[0].x == snake.p[i].x && snake.p[0].y == snake.p[i].y) { MessageBox(hwnd, (LPCWSTR)L"游戏结束", (LPCWSTR)L"失败!", 0); return 0; } } return 1; } void CharToTchar(const char* _char, TCHAR* tchar) { int iLength; iLength = MultiByteToWideChar(CP_ACP, 0, _char, strlen(_char) + 1, NULL, 0); MultiByteToWideChar(CP_ACP, 0, _char, strlen(_char) + 1, tchar, iLength); } void showScore() { char gradetmp[100] = {""}; sprintf(gradetmp, "分数:%d", food.eatgrade); TCHAR grade[100]; CharToTchar(gradetmp,grade); setbkmode(TRANSPARENT); settextcolor(RED); char casStrtmp[100] = { "" }; sprintf(casStrtmp, "第%d关", cas); TCHAR casStr[100]; CharToTchar(casStrtmp, casStr); outtextxy(570,20, grade); outtextxy(570, 40, casStr); } int main() { srand((unsigned int)time(NULL)); hwnd = initgraph(640,480); setbkcolor(WHITE); cleardevice(); initSnake(); while (1) { cleardevice(); if (food.flag == 0) { initfood(); } drawfood(); drawSnake(); if (!gameOver()) { break; } eatFood(); moveSnake(); while (_kbhit()) { keyDown(); } if (food.eatgrade != 0) { cas = food.eatgrade/10 + 1; } showScore(); Sleep(200- speed*cas); } //getchar(); closegraph(); return 0; }
[ "15609237113@163.com" ]
15609237113@163.com
1f7ab4b1dc0c2f4d26b48c8a3f9ff5b2582ab3f9
77bc7c01acffc6eb6cc46d384eb459ea0b102cc4
/ytassignment02/src/apps/02_model.cpp
7ee6ff458422e36b89c681ad1314bb4f514e71a6
[]
no_license
YvonneTian2016/CG
7044b86fff2279691973d337ab27107b219a6cbb
c423d4fd2d9cfcc07248510cf1edfd3fb7d0059a
refs/heads/master
2021-01-21T22:10:48.174251
2016-11-14T06:57:36
2016-11-14T06:57:36
73,676,185
0
0
null
null
null
null
UTF-8
C++
false
false
35,307
cpp
#include "common.h" #include "scene.h" #include "image.h" #include "gls.h" string scene_filename; // scene filename string image_filename; // image filename Scene* scene; // scene arrays void uiloop(); // UI loop // map used to uniquify edges struct EdgeMap { map<pair<int,int>,int> _edge_map; // internal map vector<vec2i> _edge_list; // internal list to generate unique ids // create an edge map for a collection of triangles and quads EdgeMap(vector<vec3i> triangle, vector<vec4i> quad) { for(auto f : triangle) { _add_edge(f.x,f.y); _add_edge(f.y,f.z); _add_edge(f.z,f.x); } for(auto f : quad) { _add_edge(f.x,f.y); _add_edge(f.y,f.z); _add_edge(f.z,f.w); _add_edge(f.w,f.x); } } // internal function to add an edge void _add_edge(int i, int j) { if(_edge_map.find(make_pair(i,j)) == _edge_map.end()) { _edge_map[make_pair(i,j)] = _edge_list.size(); _edge_map[make_pair(j,i)] = _edge_list.size(); _edge_list.push_back(vec2i(i,j)); } } // edge list const vector<vec2i>& edges() const { return _edge_list; } // get an edge from two vertices int edge_index(vec2i e) const { error_if_not(not (_edge_map.find(make_pair(e.x,e.y)) == _edge_map.end()), "non existing edge"); return _edge_map.find(make_pair(e.x, e.y))->second; } }; // make normals for each face - duplicates all vertex data void facet_normals(Mesh* mesh) { // allocates new arrays auto pos = vector<vec3f>(); auto norm = vector<vec3f>(); auto texcoord = vector<vec2f>(); auto triangle = vector<vec3i>(); auto quad = vector<vec4i>(); // foreach triangle for(auto f : mesh->triangle) { // grab current pos size auto nv = (int)pos.size(); // compute face face normal auto fn = normalize(cross(mesh->pos[f.y]-mesh->pos[f.x], mesh->pos[f.z]-mesh->pos[f.x])); // add triangle triangle.push_back({nv,nv+1,nv+2}); // add vertex data for(auto i : range(3)) { pos.push_back(mesh->pos[f[i]]); norm.push_back(fn); if(not mesh->texcoord.empty()) texcoord.push_back(mesh->texcoord[f[i]]); } } // foreach quad for(auto f : mesh->quad) { // grab current pos size auto nv = (int)pos.size(); // compute face normal auto fn = normalize(normalize(cross(mesh->pos[f.y]-mesh->pos[f.x], mesh->pos[f.z]-mesh->pos[f.x])) + normalize(cross(mesh->pos[f.z]-mesh->pos[f.x], mesh->pos[f.w]-mesh->pos[f.x]))); // add quad quad.push_back({nv,nv+1,nv+2,nv+3}); // add vertex data for(auto i : range(4)) { pos.push_back(mesh->pos[f[i]]); norm.push_back(fn); if(not mesh->texcoord.empty()) texcoord.push_back(mesh->texcoord[f[i]]); } } // set back mesh data mesh->pos = pos; mesh->norm = norm; mesh->texcoord = texcoord; mesh->triangle = triangle; mesh->quad = quad; } // smooth out normal - does not duplicate data void smooth_normals(Mesh* mesh) { // set normals array to the same length as pos and init all elements to zero mesh->norm.assign(mesh->pos.size(), zero3f); // put_your_code_here("Implement normal smoothing"); // foreach triangle for(auto f : mesh->triangle) { // compute face normal auto fn = normalize(cross(mesh->pos[f.y]-mesh->pos[f.x], mesh->pos[f.z]-mesh->pos[f.x])); // accumulate face normal to the vertex normals of each face index for (auto i : range(2)) mesh->norm[f[i]] += fn; } // foreach quad for(auto f : mesh->quad) { // compute face normal auto fn = normalize(normalize(cross(mesh->pos[f.y]-mesh->pos[f.x], mesh->pos[f.z]-mesh->pos[f.x])) + normalize(cross(mesh->pos[f.z]-mesh->pos[f.x], mesh->pos[f.w]-mesh->pos[f.x]))); // accumulate face normal to the vertex normals of each face index for (auto i : range(3)) mesh->norm[f[i]] += fn; } // normalize all vertex normals for (auto& f : mesh->norm) f = normalize(f); } // smooth out tangents void smooth_tangents(Mesh* polyline) { // set tangent array polyline->norm = vector<vec3f>(polyline->pos.size(),zero3f); // foreach line for(auto l : polyline->line) { // compute line tangent auto lt = normalize(polyline->pos[l.y]-polyline->pos[l.x]); // accumulate segment tangent to vertex tangent on each vertex for (auto i : range(2)) polyline->norm[l[i]] += lt; } // normalize all vertex tangents for (auto& t : polyline->norm) t = normalize(t); } // subdivide bezier spline into line segments (assume bezier has only bezier segments and no lines) // subdivide using uniform sampling void subdivide_bezier_uniform(Mesh *bezier) { auto pos = vector<vec3f>(); auto line = vector<vec2i>(); // determine number of steps int steps = 1 << bezier->subdivision_bezier_level; // put_your_code_here("Implement uniform Bezier spline subdivision"); vec3f v0,v1,v2,v3,v_new; float t,b0,b1,b2,b3; int line_pos; // foreach spline segment for(int i = 0; i < bezier->spline.size(); i++) { // get control points of segment v0 = bezier->pos[bezier->spline[i].x]; v1 = bezier->pos[bezier->spline[i].y]; v2 = bezier->pos[bezier->spline[i].z]; v3 = bezier->pos[bezier->spline[i].w]; // note the starting index of new points line_pos = pos.size(); // foreach step for(int j = 0; j <= steps; j++) { t = (float)j*(1.0f/(float)steps); // compute t for current segment b0 = bernstein(t,0,3); // compute blending weights b1 = bernstein(t,1,3); b2 = bernstein(t,2,3); b3 = bernstein(t,3,3); v_new = b0*v0 + b1*v1 + b2*v2 +b3*v3; // compute new point position pos.push_back(v_new); // add new point to pos vector } // foreach step // create line segment for(int k = 0; k < steps; k++) { line.push_back(vec2i(line_pos+k,line_pos+k+1)); } } // copy vertex positions bezier->pos = pos; // copy line segments bezier->line = line; // clear bezier array from lines bezier->spline.clear(); bezier->subdivision_bezier_level = 0; // run smoothing to get proper tangents smooth_tangents(bezier); } // subdivide bezier spline into line segments (assume bezier has only bezier segments and no lines) // subdivide using de casteljau algorithm void subdivide_bezier_decasteljau(Mesh *bezier) { auto pos = bezier->pos; auto splines = bezier->spline; //put_your_code_here("Implement de Casteljau algorithm") // *note*: this psuedocode is for an iterative implementation of the algorithm without adaptive subd // foreach level int level = bezier->subdivision_bezier_level; vec3f v0,v1,v2,v3,vm0,vm1,vm2,vmm0,vmm1,vmmm; for(int i = 0; i < level; i++) { auto new_pos = vector<vec3f>(); // make new arrays of positions and bezier segments auto new_splines = vector<vec4i>(); // copy all the vertices into the new array (this waste space but it is easier for now) // foreach bezier segment for(int j = 0; j < splines.size(); j++) { // apply subdivision algorithm int size = new_pos.size(); v0 = pos[splines[j].x]; v1 = pos[splines[j].y]; v2 = pos[splines[j].z]; v3 = pos[splines[j].w]; // prepare indices for two new segments vm0 = (v0+v1)/2.0f; vm1 = (v1+v2)/2.0f; vm2 = (v2+v3)/2.0f; vmm0 = (vm0+vm1)/2.0f; vmm1 = (vm1+vm2)/2.0f; vmmm = (vmm0+vmm1)/2.0f; // add mid point // add points for first segment and fix segment indices // add points for second segment and fix segment indices // add indices for both segments into new segments array new_pos.push_back(v0); new_pos.push_back(vm0); new_pos.push_back(vmm0); new_pos.push_back(vmmm); new_pos.push_back(vmm1); new_pos.push_back(vm2); new_pos.push_back(v3); new_splines.push_back(vec4i(size,size+1,size+2,size+3)); new_splines.push_back(vec4i(size+3,size+4,size+5,size+6)); } // set new arrays pos, segments into the working lineset pos=new_pos; splines=new_splines; } // copy vertex positions bezier->pos = pos; // copy bezier segments into line segments bezier->line.clear(); for(auto spline : splines) bezier->line.push_back({spline.x,spline.w}); // clear bezier array from lines bezier->spline.clear(); bezier->subdivision_bezier_level = 0; // run smoothing to get proper tangents smooth_tangents(bezier); } // subdivide bezier spline into line segments (assume bezier has only bezier segments and no lines) void subdivide_bezier(Mesh* bezier) { // skip is needed if(not bezier->subdivision_bezier_level) return; if(bezier->subdivision_bezier_uniform) subdivide_bezier_uniform(bezier); else subdivide_bezier_decasteljau(bezier); } // apply Catmull-Clark mesh subdivision // does not subdivide texcoord void subdivide_catmullclark(Mesh* subdiv) { // skip is needed if(not subdiv->subdivision_catmullclark_level) return; // allocate a working Mesh copied from the subdiv auto mesh = new Mesh(*subdiv); vec3f v0,v1,v2,v3,v_m; vec2i edges; vec3i triangles; vec4i quads; // foreach level for(auto l : range(subdiv->subdivision_catmullclark_level)) { // make empty pos and quad arrays auto pos = vector<vec3f>(); auto quad = vector<vec4i>(); // create edge_map from current mesh auto edge_map = EdgeMap(mesh->triangle,mesh->quad); //put_your_code_here("Implement Catmull-Clark Subdivision"); // linear subdivision - create vertices -------------------------------------- // copy all vertices from the current mesh for (int i = 0; i < mesh->pos.size(); i++) { pos.push_back(mesh->pos[i]); } // add vertices in the middle of each edge (use EdgeMap) for (int i = 0; i < edge_map.edges().size(); i++) { edges = edge_map.edges()[i]; v0 = mesh->pos[edges.x]; v1 = mesh->pos[edges.y]; v_m = (v0+v1)/2.0f; pos.push_back(v_m); } // add vertices in the middle of each triangle for(int i = 0; i < mesh->triangle.size(); i++) { triangles = mesh->triangle[i]; v0 = mesh->pos[triangles.x]; v1 = mesh->pos[triangles.y]; v2 = mesh->pos[triangles.z]; v_m = (v0+v1+v2)/3.0f; pos.push_back(v_m); } // add vertices in the middle of each quad for(int i = 0; i< mesh->quad.size(); i++) { quads = mesh->quad[i]; v0 = mesh->pos[quads.x]; v1 = mesh->pos[quads.y]; v2 = mesh->pos[quads.z]; v3 = mesh->pos[quads.w]; v_m = (v0+v1+v2+v3)/4.0f; pos.push_back(v_m); } // subdivision pass ---------------------------------------------------------- int edge_off,trian_off,quad_off; int vt0,vt1,vt2,vq0,vq1,vq2,vq3,ve0,ve1,ve2,ve3,vf; vec2i edge0,edge1,edge2,edge3; // compute an offset for the edge vertices edge_off = mesh->pos.size(); // compute an offset for the triangle vertices trian_off = edge_off + edge_map.edges().size(); // compute an offset for the quad vertices quad_off = trian_off + mesh->triangle.size(); // foreach triangle // add three quads to the new quad array for(int i = 0; i < mesh->triangle.size(); i++) { vt0 = mesh->triangle[i].x; vt1 = mesh->triangle[i].y; vt2 = mesh->triangle[i].z; edge0 = vec2i(vt0,vt1); edge1 = vec2i(vt1,vt2); edge2 = vec2i(vt2,vt0); ve0 = edge_off+edge_map.edge_index(edge0); ve1 = edge_off+edge_map.edge_index(edge1); ve2 = edge_off+edge_map.edge_index(edge2); vf = trian_off + i; quad.push_back(vec4i(vt0,ve0,vf,ve2)); //顺序可能有变 quad.push_back(vec4i(ve0,vt1,ve1,vf)); quad.push_back(vec4i(vf,ve1,vt2,ve2)); } // foreach quad // add four quads to the new quad array for(int i = 0; i < mesh->quad.size(); i++) { vq0 = mesh->quad[i].x; vq1 = mesh->quad[i].y; vq2 = mesh->quad[i].z; vq3 = mesh->quad[i].w; edge0 = vec2i(vq0,vq1); edge1 = vec2i(vq1,vq2); edge2 = vec2i(vq2,vq3); edge3 = vec2i(vq3,vq0); ve0 = edge_off+edge_map.edge_index(edge0); ve1 = edge_off+edge_map.edge_index(edge1); ve2 = edge_off+edge_map.edge_index(edge2); ve3 = edge_off+edge_map.edge_index(edge3); vf = quad_off + i; quad.push_back(vec4i(vq0,ve0,vf,ve3)); //顺序可能有变 quad.push_back(vec4i(ve0,vq1,ve1,vf)); quad.push_back(vec4i(vf,ve1,vq2,ve2)); quad.push_back(vec4i(ve3,vf,ve2,vq3)); } // averaging pass ------------------------------------------------------------ vec3f q_center; // create arrays to compute pos averages (avg_pos, avg_count) // arrays have the same length as the new pos array, and are init to zero auto avg_pos = vector<vec3f>(pos.size(),zero3f); auto avg_count = vector<int>(pos.size(),0); // for each new quad for(int i = 0; i < quad.size(); i++) { // compute quad center using the new pos array q_center = (pos[quad[i].x]+ pos[quad[i].y]+ pos[quad[i].z]+ pos[quad[i].w])/4.0f; // foreach vertex index in the quad // accumulate face center to the avg_pos and add 1 to avg_count avg_pos[quad[i].x]+=q_center; avg_pos[quad[i].y]+=q_center; avg_pos[quad[i].z]+=q_center; avg_pos[quad[i].w]+=q_center; avg_count[quad[i].x]++; avg_count[quad[i].y]++; avg_count[quad[i].z]++; avg_count[quad[i].w]++; } // normalize avg_pos with its count avg_count for(int i = 0; i < avg_pos.size(); i++) { avg_pos[i]/=avg_count[i]; } // correction pass ----------------------------------------------------------- // foreach pos, compute correction p = p + (avg_p - p) * (4/avg_count) for(int i = 0; i < pos.size(); i++) { pos[i]=pos[i]+(avg_pos[i]-pos[i])*(4.0f/avg_count[i]); } // set new arrays pos, quad back into the working mesh; clear triangle array mesh->pos = pos; mesh->triangle = vector<vec3i>(); mesh->quad = quad; } // clear subdivision mesh->subdivision_catmullclark_level = 0; // according to smooth, either smooth_normals or facet_normals if(subdiv->subdivision_catmullclark_smooth) smooth_normals(mesh); else facet_normals(mesh); // copy back *subdiv = *mesh; // clear delete mesh; } void subdivide_surface(Surface* surface) { // create mesh struct auto mesh = new Mesh{}; // copy frame mesh->frame = surface->frame; // copy material mesh->mat = surface->mat; // get surface radius auto radius = surface->radius; // vertexidx is used to look up index of vertex corresponding to (i,j) map<pair<int,int>,int> vertexidx; if(surface->isquad) { // compute how much to subdivide auto ci = 1 << surface->subdivision_level; auto cj = 1 << surface->subdivision_level; // compute corners of quad auto p00 = vec3f(-1,-1,0) * radius; auto p01 = vec3f(-1, 1,0) * radius; auto p10 = vec3f( 1,-1,0) * radius; auto p11 = vec3f( 1, 1,0) * radius; // foreach column for(auto i : range(ci+1)) { // foreach row for(auto j : range(cj+1)) { // compute u,v corresponding to column and row auto u = i / (float)ci; auto v = j / (float)cj; // compute new point location auto p = p00*u*v + p01*u*(1-v) + p10*(1-u)*v + p11*(1-u)*(1-v); // insert point into pos vector, remembering its index vertexidx[make_pair(i,j)] = mesh->pos.size(); mesh->pos.push_back(p); mesh->norm.push_back(z3f); } } //edited by Yuan Tian for Displacement_Mapping float u,v,color_bright; vec3f color; float h = 0.2; if(surface->Displacement_Mapping) { image3f png = read_png("images.png",false); for(auto i : range(ci)) { for(auto j : range(cj)) { u = floor(((float)i/ci)*png.width()); v = floor(((float)j/cj)*png.height()); color = png.at(u,v); color_bright = (color.x+color.y+color.z)/3.0f; mesh->pos[vertexidx[make_pair(i,j)]]+=h*color_bright*mesh->norm[vertexidx[make_pair(i,j)]]; } } } // foreach column for(auto i : range(ci)) { // foreach row for(auto j : range(cj)) { // find indices of neigboring vertices int idx0 = vertexidx[make_pair(i+0,j+0)]; int idx1 = vertexidx[make_pair(i+1,j+0)]; int idx2 = vertexidx[make_pair(i+1,j+1)]; int idx3 = vertexidx[make_pair(i+0,j+1)]; // create quad mesh->quad.push_back({idx0, idx1, idx2, idx3}); } } } else { // put_your_code_here("Implement sphere subdivision"); float theta = 0, fai=0; vec3f new_v; // compute how much to subdivide int steps_lat = 1 << (surface->subdivision_level+1); int steps_long = 1 << (surface->subdivision_level+2); mesh->pos.push_back(vec3f(0,0,radius)); //top mesh->pos.push_back(vec3f(0,0,-radius)); //bottom // foreach column // foreach row for(int i = 1; i < steps_lat; i++) { for(int j = 0; j < steps_long; j++) { theta = (float)i/steps_lat*PI; // compute phi,theta for column and row fai = (float)j/steps_long*2*PI; new_v.x=radius*cos(fai)*sin(theta); // compute new point location new_v.y=radius*sin(fai)*sin(theta); new_v.z=radius*cos(theta); // insert point into pos vector, remembering its index vertexidx[make_pair(i,j)] = mesh->pos.size(); mesh->pos.push_back(new_v); mesh->norm.push_back(new_v-mesh->frame.o); } } // foreach column // foreach row for(int i = 1; i < steps_lat-1; i++) for(int j = 0; j < steps_long; j++) { // find indices of neighboring vertices int idx0 = vertexidx[make_pair(i+0,j+0)]; int idx1 = vertexidx[make_pair(i+1,j+0)]; int idx2 = vertexidx[make_pair(i+1,(j+1) % steps_long)]; int idx3 = vertexidx[make_pair(i+0,(j+1) % steps_long)]; // create quad mesh->quad.push_back({idx0, idx1, idx2, idx3}); } int idx_top = 0, idx_bot = 1; for (int i = 0; i < steps_long; i++) { // find indices of neighboring vertices int idx0 = vertexidx[make_pair(1,i)]; int idx1 = vertexidx[make_pair(1,(i+1) % steps_long)]; //create triangle (face touching pole) mesh->triangle.push_back({idx_top,idx0,idx1}); } for (int i = 0; i < steps_long; i++) { // find indices of neighboring vertices int idx0 = vertexidx[make_pair(steps_lat-1,i)]; int idx1 = vertexidx[make_pair(steps_lat-1,(i+1) % steps_long)]; //create triangle (face touching pole) mesh->triangle.push_back({idx0,idx_bot,idx1}); } } // according to smooth, either smooth_normals or facet_normals if(surface->subdivision_smooth) smooth_normals(mesh); else facet_normals(mesh); // update _display_mesh of surface surface->_display_mesh = mesh; } void subdivide(Scene* scene) { for(auto mesh : scene->meshes) { if(mesh->subdivision_catmullclark_level) subdivide_catmullclark(mesh); if(mesh->subdivision_bezier_level) subdivide_bezier(mesh); } for(auto surface : scene->surfaces) { subdivide_surface(surface); } } // main function int main(int argc, char** argv) { auto args = parse_cmdline(argc, argv, { "02_model", "view scene", { {"resolution", "r", "image resolution", typeid(int), true, jsonvalue() } }, { {"scene_filename", "", "scene filename", typeid(string), false, jsonvalue("scene.json")}, {"image_filename", "", "image filename", typeid(string), true, jsonvalue("")} } }); // generate/load scene either by creating a test scene or loading from json file scene_filename = args.object_element("scene_filename").as_string(); scene = nullptr; if(scene_filename.length() > 9 and scene_filename.substr(0,9) == "testscene") { int scene_type = atoi(scene_filename.substr(9).c_str()); scene = create_test_scene(scene_type); scene_filename = scene_filename + ".json"; } else { scene = load_json_scene(scene_filename); } error_if_not(scene, "scene is nullptr"); image_filename = (args.object_element("image_filename").as_string() != "") ? args.object_element("image_filename").as_string() : scene_filename.substr(0,scene_filename.size()-5)+".png"; if(not args.object_element("resolution").is_null()) { scene->image_height = args.object_element("resolution").as_int(); scene->image_width = scene->camera->width * scene->image_height / scene->camera->height; } subdivide(scene); uiloop(); } ///////////////////////////////////////////////////////////////////// // UI and Rendering Code: OpenGL, GLFW, GLSL int gl_program_id = 0; // OpenGL program handle int gl_vertex_shader_id = 0; // OpenGL vertex shader handle int gl_fragment_shader_id = 0; // OpenGL fragment shader handle map<image3f*,int> gl_texture_id;// OpenGL texture handles bool save = false; // whether to start the save loop bool wireframe = false; // display as wireframe void init_shaders(); // initialize the shaders void init_textures(); // initialize the textures void shade(); // render the scene with OpenGL void _shade_mesh(Mesh* mesh); void character_callback(GLFWwindow* window, unsigned int key); // ... // glfw callback for character input void _bind_texture(string name_map, string name_on, image3f* txt, int pos); // ... // utility to bind texture parameters for shaders // uses texture name, texture_on name, texture pointer and texture unit position // glfw callback for character input void character_callback(GLFWwindow* window, unsigned int key) { if(key == 's') save = true; if(key == 'w') wireframe = not wireframe; } // uiloop void uiloop() { auto ok_glfw = glfwInit(); error_if_not(ok_glfw, "glfw init error"); glfwWindowHint(GLFW_SAMPLES, scene->image_samples); auto window = glfwCreateWindow(scene->image_width, scene->image_height, "graphics13 | model", NULL, NULL); error_if_not(window, "glfw window error"); glfwMakeContextCurrent(window); glfwSetCharCallback(window, character_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); auto ok_glew = glewInit(); error_if_not(GLEW_OK == ok_glew, "glew init error"); init_shaders(); init_textures(); auto mouse_last_x = -1.0; auto mouse_last_y = -1.0; while(not glfwWindowShouldClose(window)) { glfwGetFramebufferSize(window, &scene->image_width, &scene->image_height); scene->camera->width = (scene->camera->height * scene->image_width) / scene->image_height; shade(); if(glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT)) { double x, y; glfwGetCursorPos(window, &x, &y); if (mouse_last_x < 0 or mouse_last_y < 0) { mouse_last_x = x; mouse_last_y = y; } auto delta_x = x - mouse_last_x, delta_y = y - mouse_last_y; set_view_turntable(scene->camera, delta_x*0.01, -delta_y*0.01, 0, 0, 0); mouse_last_x = x; mouse_last_y = y; } else { mouse_last_x = -1; mouse_last_y = -1; } if(save) { auto image = image3f(scene->image_width,scene->image_height); glReadPixels(0, 0, scene->image_width, scene->image_height, GL_RGB, GL_FLOAT, &image.at(0,0)); write_png(image_filename, image, true); save = false; } glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); } // initialize the shaders void init_shaders() { // load shader code from files auto vertex_shader_code = load_text_file("model_vertex.glsl"); auto fragment_shader_code = load_text_file("model_fragment.glsl"); auto vertex_shader_codes = (char *)vertex_shader_code.c_str(); auto fragment_shader_codes = (char *)fragment_shader_code.c_str(); // create shaders gl_vertex_shader_id = glCreateShader(GL_VERTEX_SHADER); gl_fragment_shader_id = glCreateShader(GL_FRAGMENT_SHADER); // load shaders code onto the GPU glShaderSource(gl_vertex_shader_id,1,(const char**)&vertex_shader_codes,nullptr); glShaderSource(gl_fragment_shader_id,1,(const char**)&fragment_shader_codes,nullptr); // compile shaders glCompileShader(gl_vertex_shader_id); glCompileShader(gl_fragment_shader_id); // check if shaders are valid error_if_glerror(); error_if_shader_not_valid(gl_vertex_shader_id); error_if_shader_not_valid(gl_fragment_shader_id); // create program gl_program_id = glCreateProgram(); // attach shaders glAttachShader(gl_program_id,gl_vertex_shader_id); glAttachShader(gl_program_id,gl_fragment_shader_id); // bind vertex attributes locations glBindAttribLocation(gl_program_id, 0, "vertex_pos"); glBindAttribLocation(gl_program_id, 1, "vertex_norm"); glBindAttribLocation(gl_program_id, 2, "vertex_texcoord"); // link program glLinkProgram(gl_program_id); // check if program is valid error_if_glerror(); error_if_program_not_valid(gl_program_id); } // initialize the textures void init_textures() { // grab textures from scene auto textures = get_textures(scene); // foreach texture for(auto texture : textures) { // if already in the gl_texture_id map, skip if(gl_texture_id.find(texture) != gl_texture_id.end()) continue; // gen texture id unsigned int id = 0; glGenTextures(1, &id); // set id to the gl_texture_id map for later use gl_texture_id[texture] = id; // bind texture glBindTexture(GL_TEXTURE_2D, id); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); // load texture data glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->width(), texture->height(), 0, GL_RGB, GL_FLOAT, texture->data()); } } // utility to bind texture parameters for shaders // uses texture name, texture_on name, texture pointer and texture unit position void _bind_texture(string name_map, string name_on, image3f* txt, int pos) { // if txt is not null if(txt) { // set texture on boolean parameter to true glUniform1i(glGetUniformLocation(gl_program_id,name_on.c_str()),GL_TRUE); // activate a texture unit at position pos glActiveTexture(GL_TEXTURE0+pos); // bind texture object to it from gl_texture_id map glBindTexture(GL_TEXTURE_2D, gl_texture_id[txt]); // set texture parameter to the position pos glUniform1i(glGetUniformLocation(gl_program_id, name_map.c_str()), pos); } else { // set texture on boolean parameter to false glUniform1i(glGetUniformLocation(gl_program_id,name_on.c_str()),GL_FALSE); // activate a texture unit at position pos glActiveTexture(GL_TEXTURE0+pos); // set zero as the texture id glBindTexture(GL_TEXTURE_2D, 0); } } // render the scene with OpenGL void shade() { // enable depth test glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // disable culling face glDisable(GL_CULL_FACE); // let the shader control the points glEnable(GL_POINT_SPRITE); // set up the viewport from the scene image size glViewport(0, 0, scene->image_width, scene->image_height); // clear the screen (both color and depth) - set cleared color to background glClearColor(scene->background.x, scene->background.y, scene->background.z, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // enable program glUseProgram(gl_program_id); // bind camera's position, inverse of frame and projection // use frame_to_matrix_inverse and frustum_matrix glUniform3fv(glGetUniformLocation(gl_program_id,"camera_pos"), 1, &scene->camera->frame.o.x); glUniformMatrix4fv(glGetUniformLocation(gl_program_id,"camera_frame_inverse"), 1, true, &frame_to_matrix_inverse(scene->camera->frame)[0][0]); glUniformMatrix4fv(glGetUniformLocation(gl_program_id,"camera_projection"), 1, true, &frustum_matrix(-scene->camera->dist*scene->camera->width/2, scene->camera->dist*scene->camera->width/2, -scene->camera->dist*scene->camera->height/2, scene->camera->dist*scene->camera->height/2, scene->camera->dist,10000)[0][0]); // bind ambient and number of lights glUniform3fv(glGetUniformLocation(gl_program_id,"ambient"),1,&scene->ambient.x); glUniform1i(glGetUniformLocation(gl_program_id,"lights_num"),scene->lights.size()); // foreach light auto count = 0; for(auto light : scene->lights) { // bind light position and internsity (create param name with tostring) glUniform3fv(glGetUniformLocation(gl_program_id,tostring("light_pos[%d]",count).c_str()), 1, &light->frame.o.x); glUniform3fv(glGetUniformLocation(gl_program_id,tostring("light_intensity[%d]",count).c_str()), 1, &light->intensity.x); count++; } // foreach mesh for(auto mesh : scene->meshes) { _shade_mesh(mesh); } for(auto surf : scene->surfaces) { _shade_mesh(surf->_display_mesh); } } void _shade_mesh(Mesh* mesh) { // bind material kd, ks, n ERROR_IF_NOT(mesh, "mesh is null"); glUniform3fv(glGetUniformLocation(gl_program_id,"material_kd"),1,&mesh->mat->kd.x); glUniform3fv(glGetUniformLocation(gl_program_id,"material_ks"),1,&mesh->mat->ks.x); glUniform1f(glGetUniformLocation(gl_program_id,"material_n"),mesh->mat->n); // bind texture params (txt_on, sampler) _bind_texture("material_kd_txt", "material_kd_txt_on", mesh->mat->kd_txt, 0); _bind_texture("material_ks_txt", "material_ks_txt_on", mesh->mat->ks_txt, 1); _bind_texture("material_norm_txt", "material_norm_txt_on", mesh->mat->norm_txt, 2); // bind mesh frame - use frame_to_matrix glUniformMatrix4fv(glGetUniformLocation(gl_program_id,"mesh_frame"),1,true,&frame_to_matrix(mesh->frame)[0][0]); // enable vertex attributes arrays and set up pointers to the mesh data auto vertex_pos_location = glGetAttribLocation(gl_program_id, "vertex_pos"); auto vertex_norm_location = glGetAttribLocation(gl_program_id, "vertex_norm"); auto vertex_texcoord_location = glGetAttribLocation(gl_program_id, "vertex_texcoord"); glEnableVertexAttribArray(vertex_pos_location); glVertexAttribPointer(vertex_pos_location, 3, GL_FLOAT, GL_FALSE, 0, &mesh->pos[0].x); glEnableVertexAttribArray(vertex_norm_location); glVertexAttribPointer(vertex_norm_location, 3, GL_FLOAT, GL_FALSE, 0, &mesh->norm[0].x); if(not mesh->texcoord.empty()) { glEnableVertexAttribArray(vertex_texcoord_location); glVertexAttribPointer(vertex_texcoord_location, 2, GL_FLOAT, GL_FALSE, 0, &mesh->texcoord[0].x); } else glVertexAttrib2f(vertex_texcoord_location, 0, 0); // draw triangles and quads if(not wireframe) { if(mesh->triangle.size()) glDrawElements(GL_TRIANGLES, mesh->triangle.size()*3, GL_UNSIGNED_INT, &mesh->triangle[0].x); if(mesh->quad.size()) glDrawElements(GL_QUADS, mesh->quad.size()*4, GL_UNSIGNED_INT, &mesh->quad[0].x); } else { auto edges = EdgeMap(mesh->triangle, mesh->quad).edges(); glDrawElements(GL_LINES, edges.size()*2, GL_UNSIGNED_INT, &edges[0].x); } // draw line sets if(not mesh->line.empty()) glDrawElements(GL_LINES, mesh->line.size()*2, GL_UNSIGNED_INT, mesh->line.data()); for(auto segment : mesh->spline) glDrawElements(GL_LINE_STRIP, 4, GL_UNSIGNED_INT, &segment); // disable vertex attribute arrays glDisableVertexAttribArray(vertex_pos_location); glDisableVertexAttribArray(vertex_norm_location); if(not mesh->texcoord.empty()) glDisableVertexAttribArray(vertex_texcoord_location); }
[ "ciciytian@gmail.com" ]
ciciytian@gmail.com
22fe8812ba9fb0c63a461378de38644f9472c04a
fdeca1313be23ba40a255e0a46856d427987a8ca
/external/boost_1_54_0_arm/boost/mpl/aux_/config/intel.hpp
09f8e2e0a25423251df1b31c1a8906009763eda0
[ "BSL-1.0" ]
permissive
petiaccja/raspberry-rc
ee42f0bf265bd4e1ab6fde4a31d015dcdfdea155
aa0f1cb18be2f6aad6fd5799ab79904fc64a4b24
refs/heads/master
2016-09-06T00:09:10.647868
2015-01-28T22:21:34
2015-01-28T22:21:34
23,356,436
0
0
null
null
null
null
UTF-8
C++
false
false
613
hpp
#ifndef BOOST_MPL_AUX_CONFIG_INTEL_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_INTEL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: intel.hpp 49239 2008-10-10 09:10:26Z agurtovoy $ // $Date: 2008-10-10 11:10:26 +0200 (p, 10 okt 2008) $ // $Revision: 49239 $ // BOOST_INTEL_CXX_VERSION is defined here: #include <boost/config.hpp> #endif // BOOST_MPL_AUX_CONFIG_INTEL_HPP_INCLUDED
[ "kardospeter1994@hotmail.com" ]
kardospeter1994@hotmail.com
6f429b06f600d0c49580763feade25ffd13b53b7
17a7022fe852fac67db9c12dee415872f82e120a
/lab 2/complex.h
b299128c839ed3b692c7068a3f4d2c4705a2c114
[]
no_license
EzhNEesh/Programming-2-sem
091687f0bf886647c518a4d3e96a1ff69eb7d956
f35517100b6eb6877b328b225cec30e7a858bce6
refs/heads/master
2022-10-11T01:48:13.016268
2020-06-13T07:56:28
2020-06-13T07:56:28
248,883,189
0
0
null
null
null
null
UTF-8
C++
false
false
302
h
#pragma once class Complex { public: Complex(double re, double im); Complex(Complex& com); void create(double re, double im); void mult_real(double re); void add_complex(Complex B); void mult_complex(Complex B); void print_length(); void print(); private: double real, imaj; };
[ "noreply@github.com" ]
noreply@github.com
ba3dafe45f6c741383d45c2f5d28c432a01c406f
2c17c289d795c570491022960154b19505b27f27
/googleurl/url/url_util.cc
13c30b35d076b1a7a59702afd9e89cc18d49a541
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
leeyangjie/quiche
4cb2849ce2474ec14c902683d25e9287b95a7078
2870175069d90bcb837f30170f4eff97e161805d
refs/heads/main
2022-06-18T17:05:13.066915
2022-04-13T07:14:13
2022-04-13T07:14:13
433,855,510
0
0
Apache-2.0
2021-12-01T14:17:22
2021-12-01T14:17:21
null
UTF-8
C++
false
false
34,094
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "url/url_util.h" #include <stddef.h> #include <string.h> #include <atomic> #include "polyfills/base/check_op.h" #include "base/compiler_specific.h" #include "base/no_destructor.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "url/url_canon_internal.h" #include "url/url_constants.h" #include "url/url_file.h" #include "url/url_util_internal.h" namespace url { namespace { // A pair for representing a standard scheme name and the SchemeType for it. struct SchemeWithType { std::string scheme; SchemeType type; }; // List of currently registered schemes and associated properties. struct SchemeRegistry { // Standard format schemes (see header for details). std::vector<SchemeWithType> standard_schemes = { {kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, {kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, // Yes, file URLs can have a hostname, so file URLs should be handled as // "standard". File URLs never have a port as specified by the SchemeType // field. Unlike other SCHEME_WITH_HOST schemes, the 'host' in a file // URL may be empty, a behavior which is special-cased during // canonicalization. {kFileScheme, SCHEME_WITH_HOST}, {kFtpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, {kWssScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, // WebSocket secure. {kWsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, // WebSocket. {kFileSystemScheme, SCHEME_WITHOUT_AUTHORITY}, {kQuicTransportScheme, SCHEME_WITH_HOST_AND_PORT}, }; // Schemes that are allowed for referrers. // // WARNING: Adding (1) a non-"standard" scheme or (2) a scheme whose URLs have // opaque origins could lead to surprising behavior in some of the referrer // generation logic. In order to avoid surprises, be sure to have adequate // test coverage in each of the multiple code locations that compute // referrers. std::vector<SchemeWithType> referrer_schemes = { {kHttpsScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, {kHttpScheme, SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION}, }; // Schemes that do not trigger mixed content warning. std::vector<std::string> secure_schemes = { kHttpsScheme, kAboutScheme, kDataScheme, kQuicTransportScheme, kWssScheme, }; // Schemes that normal pages cannot link to or access (i.e., with the same // security rules as those applied to "file" URLs). std::vector<std::string> local_schemes = { kFileScheme, }; // Schemes that cause pages loaded with them to not have access to pages // loaded with any other URL scheme. std::vector<std::string> no_access_schemes = { kAboutScheme, kJavaScriptScheme, kDataScheme, }; // Schemes that can be sent CORS requests. std::vector<std::string> cors_enabled_schemes = { kHttpsScheme, kHttpScheme, kDataScheme, }; // Schemes that can be used by web to store data (local storage, etc). std::vector<std::string> web_storage_schemes = { kHttpsScheme, kHttpScheme, kFileScheme, kFtpScheme, kWssScheme, kWsScheme, }; // Schemes that can bypass the Content-Security-Policy (CSP) checks. std::vector<std::string> csp_bypassing_schemes = {}; // Schemes that are strictly empty documents, allowing them to commit // synchronously. std::vector<std::string> empty_document_schemes = { kAboutScheme, }; bool allow_non_standard_schemes = false; }; // See the LockSchemeRegistries declaration in the header. bool scheme_registries_locked = false; // Ensure that the schemes aren't modified after first use. static std::atomic<bool> g_scheme_registries_used{false}; // Gets the scheme registry without locking the schemes. This should *only* be // used for adding schemes to the registry. SchemeRegistry* GetSchemeRegistryWithoutLocking() { static gurl_base::NoDestructor<SchemeRegistry> registry; return registry.get(); } const SchemeRegistry& GetSchemeRegistry() { #if GURL_DCHECK_IS_ON() g_scheme_registries_used.store(true); #endif return *GetSchemeRegistryWithoutLocking(); } // Pass this enum through for methods which would like to know if whitespace // removal is necessary. enum WhitespaceRemovalPolicy { REMOVE_WHITESPACE, DO_NOT_REMOVE_WHITESPACE, }; // This template converts a given character type to the corresponding // StringPiece type. template<typename CHAR> struct CharToStringPiece { }; template<> struct CharToStringPiece<char> { typedef gurl_base::StringPiece Piece; }; template<> struct CharToStringPiece<gurl_base::char16> { typedef gurl_base::StringPiece16 Piece; }; // Given a string and a range inside the string, compares it to the given // lower-case |compare_to| buffer. template<typename CHAR> inline bool DoCompareSchemeComponent(const CHAR* spec, const Component& component, const char* compare_to) { if (!component.is_nonempty()) return compare_to[0] == 0; // When component is empty, match empty scheme. return gurl_base::LowerCaseEqualsASCII( typename CharToStringPiece<CHAR>::Piece( &spec[component.begin], component.len), compare_to); } // Returns true and sets |type| to the SchemeType of the given scheme // identified by |scheme| within |spec| if in |schemes|. template<typename CHAR> bool DoIsInSchemes(const CHAR* spec, const Component& scheme, SchemeType* type, const std::vector<SchemeWithType>& schemes) { if (!scheme.is_nonempty()) return false; // Empty or invalid schemes are non-standard. for (const SchemeWithType& scheme_with_type : schemes) { if (gurl_base::LowerCaseEqualsASCII(typename CharToStringPiece<CHAR>::Piece( &spec[scheme.begin], scheme.len), scheme_with_type.scheme)) { *type = scheme_with_type.type; return true; } } return false; } template<typename CHAR> bool DoIsStandard(const CHAR* spec, const Component& scheme, SchemeType* type) { return DoIsInSchemes(spec, scheme, type, GetSchemeRegistry().standard_schemes); } template<typename CHAR> bool DoFindAndCompareScheme(const CHAR* str, int str_len, const char* compare, Component* found_scheme) { // Before extracting scheme, canonicalize the URL to remove any whitespace. // This matches the canonicalization done in DoCanonicalize function. STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer; int spec_len; const CHAR* spec = RemoveURLWhitespace(str, str_len, &whitespace_buffer, &spec_len, nullptr); Component our_scheme; if (!ExtractScheme(spec, spec_len, &our_scheme)) { // No scheme. if (found_scheme) *found_scheme = Component(); return false; } if (found_scheme) *found_scheme = our_scheme; return DoCompareSchemeComponent(spec, our_scheme, compare); } template <typename CHAR> bool DoCanonicalize(const CHAR* spec, int spec_len, bool trim_path_end, WhitespaceRemovalPolicy whitespace_policy, CharsetConverter* charset_converter, CanonOutput* output, Parsed* output_parsed) { output->ReserveSizeIfNeeded(spec_len); // Remove any whitespace from the middle of the relative URL if necessary. // Possibly this will result in copying to the new buffer. STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer; if (whitespace_policy == REMOVE_WHITESPACE) { spec = RemoveURLWhitespace(spec, spec_len, &whitespace_buffer, &spec_len, &output_parsed->potentially_dangling_markup); } Parsed parsed_input; #ifdef WIN32 // For Windows, we allow things that look like absolute Windows paths to be // fixed up magically to file URLs. This is done for IE compatibility. For // example, this will change "c:/foo" into a file URL rather than treating // it as a URL with the protocol "c". It also works for UNC ("\\foo\bar.txt"). // There is similar logic in url_canon_relative.cc for // // For Max & Unix, we don't do this (the equivalent would be "/foo/bar" which // has no meaning as an absolute path name. This is because browsers on Mac // & Unix don't generally do this, so there is no compatibility reason for // doing so. if (DoesBeginUNCPath(spec, 0, spec_len, false) || DoesBeginWindowsDriveSpec(spec, 0, spec_len)) { ParseFileURL(spec, spec_len, &parsed_input); return CanonicalizeFileURL(spec, spec_len, parsed_input, charset_converter, output, output_parsed); } #endif Component scheme; if (!ExtractScheme(spec, spec_len, &scheme)) return false; // This is the parsed version of the input URL, we have to canonicalize it // before storing it in our object. bool success; SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION; if (DoCompareSchemeComponent(spec, scheme, url::kFileScheme)) { // File URLs are special. ParseFileURL(spec, spec_len, &parsed_input); success = CanonicalizeFileURL(spec, spec_len, parsed_input, charset_converter, output, output_parsed); } else if (DoCompareSchemeComponent(spec, scheme, url::kFileSystemScheme)) { // Filesystem URLs are special. ParseFileSystemURL(spec, spec_len, &parsed_input); success = CanonicalizeFileSystemURL(spec, spec_len, parsed_input, charset_converter, output, output_parsed); } else if (DoIsStandard(spec, scheme, &scheme_type)) { // All "normal" URLs. ParseStandardURL(spec, spec_len, &parsed_input); success = CanonicalizeStandardURL(spec, spec_len, parsed_input, scheme_type, charset_converter, output, output_parsed); } else if (DoCompareSchemeComponent(spec, scheme, url::kMailToScheme)) { // Mailto URLs are treated like standard URLs, with only a scheme, path, // and query. ParseMailtoURL(spec, spec_len, &parsed_input); success = CanonicalizeMailtoURL(spec, spec_len, parsed_input, output, output_parsed); } else { // "Weird" URLs like data: and javascript:. ParsePathURL(spec, spec_len, trim_path_end, &parsed_input); success = CanonicalizePathURL(spec, spec_len, parsed_input, output, output_parsed); } return success; } template<typename CHAR> bool DoResolveRelative(const char* base_spec, int base_spec_len, const Parsed& base_parsed, const CHAR* in_relative, int in_relative_length, CharsetConverter* charset_converter, CanonOutput* output, Parsed* output_parsed) { // Remove any whitespace from the middle of the relative URL, possibly // copying to the new buffer. STACK_UNINITIALIZED RawCanonOutputT<CHAR> whitespace_buffer; int relative_length; const CHAR* relative = RemoveURLWhitespace( in_relative, in_relative_length, &whitespace_buffer, &relative_length, &output_parsed->potentially_dangling_markup); bool base_is_authority_based = false; bool base_is_hierarchical = false; if (base_spec && base_parsed.scheme.is_nonempty()) { int after_scheme = base_parsed.scheme.end() + 1; // Skip past the colon. int num_slashes = CountConsecutiveSlashes(base_spec, after_scheme, base_spec_len); base_is_authority_based = num_slashes > 1; base_is_hierarchical = num_slashes > 0; } SchemeType unused_scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION; bool standard_base_scheme = base_parsed.scheme.is_nonempty() && DoIsStandard(base_spec, base_parsed.scheme, &unused_scheme_type); bool is_relative; Component relative_component; if (!IsRelativeURL(base_spec, base_parsed, relative, relative_length, (base_is_hierarchical || standard_base_scheme), &is_relative, &relative_component)) { // Error resolving. return false; } // Don't reserve buffer space here. Instead, reserve in DoCanonicalize and // ReserveRelativeURL, to enable more accurate buffer sizes. // Pretend for a moment that |base_spec| is a standard URL. Normally // non-standard URLs are treated as PathURLs, but if the base has an // authority we would like to preserve it. if (is_relative && base_is_authority_based && !standard_base_scheme) { Parsed base_parsed_authority; ParseStandardURL(base_spec, base_spec_len, &base_parsed_authority); if (base_parsed_authority.host.is_nonempty()) { STACK_UNINITIALIZED RawCanonOutputT<char> temporary_output; bool did_resolve_succeed = ResolveRelativeURL(base_spec, base_parsed_authority, false, relative, relative_component, charset_converter, &temporary_output, output_parsed); // The output_parsed is incorrect at this point (because it was built // based on base_parsed_authority instead of base_parsed) and needs to be // re-created. DoCanonicalize(temporary_output.data(), temporary_output.length(), true, REMOVE_WHITESPACE, charset_converter, output, output_parsed); return did_resolve_succeed; } } else if (is_relative) { // Relative, resolve and canonicalize. bool file_base_scheme = base_parsed.scheme.is_nonempty() && DoCompareSchemeComponent(base_spec, base_parsed.scheme, kFileScheme); return ResolveRelativeURL(base_spec, base_parsed, file_base_scheme, relative, relative_component, charset_converter, output, output_parsed); } // Not relative, canonicalize the input. return DoCanonicalize(relative, relative_length, true, DO_NOT_REMOVE_WHITESPACE, charset_converter, output, output_parsed); } template<typename CHAR> bool DoReplaceComponents(const char* spec, int spec_len, const Parsed& parsed, const Replacements<CHAR>& replacements, CharsetConverter* charset_converter, CanonOutput* output, Parsed* out_parsed) { // If the scheme is overridden, just do a simple string substitution and // re-parse the whole thing. There are lots of edge cases that we really don't // want to deal with. Like what happens if I replace "http://e:8080/foo" // with a file. Does it become "file:///E:/8080/foo" where the port number // becomes part of the path? Parsing that string as a file URL says "yes" // but almost no sane rule for dealing with the components individually would // come up with that. // // Why allow these crazy cases at all? Programatically, there is almost no // case for replacing the scheme. The most common case for hitting this is // in JS when building up a URL using the location object. In this case, the // JS code expects the string substitution behavior: // http://www.w3.org/TR/2008/WD-html5-20080610/structured.html#common3 if (replacements.IsSchemeOverridden()) { // Canonicalize the new scheme so it is 8-bit and can be concatenated with // the existing spec. STACK_UNINITIALIZED RawCanonOutput<128> scheme_replaced; Component scheme_replaced_parsed; CanonicalizeScheme(replacements.sources().scheme, replacements.components().scheme, &scheme_replaced, &scheme_replaced_parsed); // We can assume that the input is canonicalized, which means it always has // a colon after the scheme (or where the scheme would be). int spec_after_colon = parsed.scheme.is_valid() ? parsed.scheme.end() + 1 : 1; if (spec_len - spec_after_colon > 0) { scheme_replaced.Append(&spec[spec_after_colon], spec_len - spec_after_colon); } // We now need to completely re-parse the resulting string since its meaning // may have changed with the different scheme. STACK_UNINITIALIZED RawCanonOutput<128> recanonicalized; Parsed recanonicalized_parsed; DoCanonicalize(scheme_replaced.data(), scheme_replaced.length(), true, REMOVE_WHITESPACE, charset_converter, &recanonicalized, &recanonicalized_parsed); // Recurse using the version with the scheme already replaced. This will now // use the replacement rules for the new scheme. // // Warning: this code assumes that ReplaceComponents will re-check all // components for validity. This is because we can't fail if DoCanonicalize // failed above since theoretically the thing making it fail could be // getting replaced here. If ReplaceComponents didn't re-check everything, // we wouldn't know if something *not* getting replaced is a problem. // If the scheme-specific replacers are made more intelligent so they don't // re-check everything, we should instead re-canonicalize the whole thing // after this call to check validity (this assumes replacing the scheme is // much much less common than other types of replacements, like clearing the // ref). Replacements<CHAR> replacements_no_scheme = replacements; replacements_no_scheme.SetScheme(NULL, Component()); return DoReplaceComponents(recanonicalized.data(), recanonicalized.length(), recanonicalized_parsed, replacements_no_scheme, charset_converter, output, out_parsed); } // TODO(csharrison): We could be smarter about size to reserve if this is done // in callers below, and the code checks to see which components are being // replaced, and with what length. If this ends up being a hot spot it should // be changed. output->ReserveSizeIfNeeded(spec_len); // If we get here, then we know the scheme doesn't need to be replaced, so can // just key off the scheme in the spec to know how to do the replacements. if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileScheme)) { return ReplaceFileURL(spec, parsed, replacements, charset_converter, output, out_parsed); } if (DoCompareSchemeComponent(spec, parsed.scheme, url::kFileSystemScheme)) { return ReplaceFileSystemURL(spec, parsed, replacements, charset_converter, output, out_parsed); } SchemeType scheme_type = SCHEME_WITH_HOST_PORT_AND_USER_INFORMATION; if (DoIsStandard(spec, parsed.scheme, &scheme_type)) { return ReplaceStandardURL(spec, parsed, replacements, scheme_type, charset_converter, output, out_parsed); } if (DoCompareSchemeComponent(spec, parsed.scheme, url::kMailToScheme)) { return ReplaceMailtoURL(spec, parsed, replacements, output, out_parsed); } // Default is a path URL. return ReplacePathURL(spec, parsed, replacements, output, out_parsed); } void DoSchemeModificationPreamble() { // If this assert triggers, it means you've called Add*Scheme after // the SchemeRegistry has been used. // // This normally means you're trying to set up a new scheme too late or using // the SchemeRegistry too early in your application's init process. Make sure // that you haven't added any static GURL initializers in tests. GURL_DCHECK(!g_scheme_registries_used.load()) << "Trying to add a scheme after the lists have been used."; // If this assert triggers, it means you've called Add*Scheme after // LockSchemeRegistries has been called (see the header file for // LockSchemeRegistries for more). // // This normally means you're trying to set up a new scheme too late in your // application's init process. Locate where your app does this initialization // and calls LockSchemeRegistries, and add your new scheme there. GURL_DCHECK(!scheme_registries_locked) << "Trying to add a scheme after the lists have been locked."; } void DoAddScheme(const char* new_scheme, std::vector<std::string>* schemes) { DoSchemeModificationPreamble(); GURL_DCHECK(schemes); GURL_DCHECK(strlen(new_scheme) > 0); GURL_DCHECK_EQ(gurl_base::ToLowerASCII(new_scheme), new_scheme); GURL_DCHECK(std::find(schemes->begin(), schemes->end(), new_scheme) == schemes->end()); schemes->push_back(new_scheme); } void DoAddSchemeWithType(const char* new_scheme, SchemeType type, std::vector<SchemeWithType>* schemes) { DoSchemeModificationPreamble(); GURL_DCHECK(schemes); GURL_DCHECK(strlen(new_scheme) > 0); GURL_DCHECK_EQ(gurl_base::ToLowerASCII(new_scheme), new_scheme); GURL_DCHECK(std::find_if(schemes->begin(), schemes->end(), [&new_scheme](const SchemeWithType& scheme) { return scheme.scheme == new_scheme; }) == schemes->end()); schemes->push_back({new_scheme, type}); } } // namespace void ClearSchemesForTests() { GURL_DCHECK(!g_scheme_registries_used.load()) << "Schemes already used " << "(use ScopedSchemeRegistryForTests to relax for tests)."; GURL_DCHECK(!scheme_registries_locked) << "Schemes already locked " << "(use ScopedSchemeRegistryForTests to relax for tests)."; *GetSchemeRegistryWithoutLocking() = SchemeRegistry(); } class ScopedSchemeRegistryInternal { public: ScopedSchemeRegistryInternal() : registry_(std::make_unique<SchemeRegistry>( *GetSchemeRegistryWithoutLocking())) { g_scheme_registries_used.store(false); scheme_registries_locked = false; } ~ScopedSchemeRegistryInternal() { *GetSchemeRegistryWithoutLocking() = *registry_; g_scheme_registries_used.store(true); scheme_registries_locked = true; } private: std::unique_ptr<SchemeRegistry> registry_; }; ScopedSchemeRegistryForTests::ScopedSchemeRegistryForTests() : internal_(std::make_unique<ScopedSchemeRegistryInternal>()) {} ScopedSchemeRegistryForTests::~ScopedSchemeRegistryForTests() = default; void EnableNonStandardSchemesForAndroidWebView() { DoSchemeModificationPreamble(); GetSchemeRegistryWithoutLocking()->allow_non_standard_schemes = true; } bool AllowNonStandardSchemesForAndroidWebView() { return GetSchemeRegistry().allow_non_standard_schemes; } void AddStandardScheme(const char* new_scheme, SchemeType type) { DoAddSchemeWithType(new_scheme, type, &GetSchemeRegistryWithoutLocking()->standard_schemes); } void AddReferrerScheme(const char* new_scheme, SchemeType type) { DoAddSchemeWithType(new_scheme, type, &GetSchemeRegistryWithoutLocking()->referrer_schemes); } void AddSecureScheme(const char* new_scheme) { DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->secure_schemes); } const std::vector<std::string>& GetSecureSchemes() { return GetSchemeRegistry().secure_schemes; } void AddLocalScheme(const char* new_scheme) { DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->local_schemes); } const std::vector<std::string>& GetLocalSchemes() { return GetSchemeRegistry().local_schemes; } void AddNoAccessScheme(const char* new_scheme) { DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->no_access_schemes); } const std::vector<std::string>& GetNoAccessSchemes() { return GetSchemeRegistry().no_access_schemes; } void AddCorsEnabledScheme(const char* new_scheme) { DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->cors_enabled_schemes); } const std::vector<std::string>& GetCorsEnabledSchemes() { return GetSchemeRegistry().cors_enabled_schemes; } void AddWebStorageScheme(const char* new_scheme) { DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->web_storage_schemes); } const std::vector<std::string>& GetWebStorageSchemes() { return GetSchemeRegistry().web_storage_schemes; } void AddCSPBypassingScheme(const char* new_scheme) { DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->csp_bypassing_schemes); } const std::vector<std::string>& GetCSPBypassingSchemes() { return GetSchemeRegistry().csp_bypassing_schemes; } void AddEmptyDocumentScheme(const char* new_scheme) { DoAddScheme(new_scheme, &GetSchemeRegistryWithoutLocking()->empty_document_schemes); } const std::vector<std::string>& GetEmptyDocumentSchemes() { return GetSchemeRegistry().empty_document_schemes; } void LockSchemeRegistries() { scheme_registries_locked = true; } bool IsStandard(const char* spec, const Component& scheme) { SchemeType unused_scheme_type; return DoIsStandard(spec, scheme, &unused_scheme_type); } bool GetStandardSchemeType(const char* spec, const Component& scheme, SchemeType* type) { return DoIsStandard(spec, scheme, type); } bool GetStandardSchemeType(const gurl_base::char16* spec, const Component& scheme, SchemeType* type) { return DoIsStandard(spec, scheme, type); } bool IsStandard(const gurl_base::char16* spec, const Component& scheme) { SchemeType unused_scheme_type; return DoIsStandard(spec, scheme, &unused_scheme_type); } bool IsReferrerScheme(const char* spec, const Component& scheme) { SchemeType unused_scheme_type; return DoIsInSchemes(spec, scheme, &unused_scheme_type, GetSchemeRegistry().referrer_schemes); } bool FindAndCompareScheme(const char* str, int str_len, const char* compare, Component* found_scheme) { return DoFindAndCompareScheme(str, str_len, compare, found_scheme); } bool FindAndCompareScheme(const gurl_base::char16* str, int str_len, const char* compare, Component* found_scheme) { return DoFindAndCompareScheme(str, str_len, compare, found_scheme); } bool DomainIs(gurl_base::StringPiece canonical_host, gurl_base::StringPiece canonical_domain) { if (canonical_host.empty() || canonical_domain.empty()) return false; // If the host name ends with a dot but the input domain doesn't, then we // ignore the dot in the host name. size_t host_len = canonical_host.length(); if (canonical_host.back() == '.' && canonical_domain.back() != '.') --host_len; if (host_len < canonical_domain.length()) return false; // |host_first_pos| is the start of the compared part of the host name, not // start of the whole host name. const char* host_first_pos = canonical_host.data() + host_len - canonical_domain.length(); if (gurl_base::StringPiece(host_first_pos, canonical_domain.length()) != canonical_domain) { return false; } // Make sure there aren't extra characters in host before the compared part; // if the host name is longer than the input domain name, then the character // immediately before the compared part should be a dot. For example, // www.google.com has domain "google.com", but www.iamnotgoogle.com does not. if (canonical_domain[0] != '.' && host_len > canonical_domain.length() && *(host_first_pos - 1) != '.') { return false; } return true; } bool HostIsIPAddress(gurl_base::StringPiece host) { STACK_UNINITIALIZED url::RawCanonOutputT<char, 128> ignored_output; url::CanonHostInfo host_info; url::CanonicalizeIPAddress(host.data(), Component(0, host.length()), &ignored_output, &host_info); return host_info.IsIPAddress(); } bool Canonicalize(const char* spec, int spec_len, bool trim_path_end, CharsetConverter* charset_converter, CanonOutput* output, Parsed* output_parsed) { return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE, charset_converter, output, output_parsed); } bool Canonicalize(const gurl_base::char16* spec, int spec_len, bool trim_path_end, CharsetConverter* charset_converter, CanonOutput* output, Parsed* output_parsed) { return DoCanonicalize(spec, spec_len, trim_path_end, REMOVE_WHITESPACE, charset_converter, output, output_parsed); } bool ResolveRelative(const char* base_spec, int base_spec_len, const Parsed& base_parsed, const char* relative, int relative_length, CharsetConverter* charset_converter, CanonOutput* output, Parsed* output_parsed) { return DoResolveRelative(base_spec, base_spec_len, base_parsed, relative, relative_length, charset_converter, output, output_parsed); } bool ResolveRelative(const char* base_spec, int base_spec_len, const Parsed& base_parsed, const gurl_base::char16* relative, int relative_length, CharsetConverter* charset_converter, CanonOutput* output, Parsed* output_parsed) { return DoResolveRelative(base_spec, base_spec_len, base_parsed, relative, relative_length, charset_converter, output, output_parsed); } bool ReplaceComponents(const char* spec, int spec_len, const Parsed& parsed, const Replacements<char>& replacements, CharsetConverter* charset_converter, CanonOutput* output, Parsed* out_parsed) { return DoReplaceComponents(spec, spec_len, parsed, replacements, charset_converter, output, out_parsed); } bool ReplaceComponents(const char* spec, int spec_len, const Parsed& parsed, const Replacements<gurl_base::char16>& replacements, CharsetConverter* charset_converter, CanonOutput* output, Parsed* out_parsed) { return DoReplaceComponents(spec, spec_len, parsed, replacements, charset_converter, output, out_parsed); } void DecodeURLEscapeSequences(const char* input, int length, DecodeURLMode mode, CanonOutputW* output) { STACK_UNINITIALIZED RawCanonOutputT<char> unescaped_chars; for (int i = 0; i < length; i++) { if (input[i] == '%') { unsigned char ch; if (DecodeEscaped(input, &i, length, &ch)) { unescaped_chars.push_back(ch); } else { // Invalid escape sequence, copy the percent literal. unescaped_chars.push_back('%'); } } else { // Regular non-escaped 8-bit character. unescaped_chars.push_back(input[i]); } } int output_initial_length = output->length(); // Convert that 8-bit to UTF-16. It's not clear IE does this at all to // JavaScript URLs, but Firefox and Safari do. for (int i = 0; i < unescaped_chars.length(); i++) { unsigned char uch = static_cast<unsigned char>(unescaped_chars.at(i)); if (uch < 0x80) { // Non-UTF-8, just append directly output->push_back(uch); } else { // next_ch will point to the last character of the decoded // character. int next_character = i; unsigned code_point; if (ReadUTFChar(unescaped_chars.data(), &next_character, unescaped_chars.length(), &code_point)) { // Valid UTF-8 character, convert to UTF-16. AppendUTF16Value(code_point, output); i = next_character; } else if (mode == DecodeURLMode::kUTF8) { GURL_DCHECK_EQ(code_point, 0xFFFDU); AppendUTF16Value(code_point, output); i = next_character; } else { // If there are any sequences that are not valid UTF-8, we // revert |output| changes, and promote any bytes to UTF-16. We // copy all characters from the beginning to the end of the // identified sequence. output->set_length(output_initial_length); for (int j = 0; j < unescaped_chars.length(); ++j) output->push_back(static_cast<unsigned char>(unescaped_chars.at(j))); break; } } } } void EncodeURIComponent(const char* input, int length, CanonOutput* output) { for (int i = 0; i < length; ++i) { unsigned char c = static_cast<unsigned char>(input[i]); if (IsComponentChar(c)) output->push_back(c); else AppendEscapedChar(c, output); } } bool CompareSchemeComponent(const char* spec, const Component& component, const char* compare_to) { return DoCompareSchemeComponent(spec, component, compare_to); } bool CompareSchemeComponent(const gurl_base::char16* spec, const Component& component, const char* compare_to) { return DoCompareSchemeComponent(spec, component, compare_to); } } // namespace url
[ "wangsheng@bilibili.com" ]
wangsheng@bilibili.com
3a6559e2926654de5d75c54cc4e1b20356bba630
911729e019762ed93b14f49d19c1b7d817c29af6
/OldCmodel/lbuf.h
b9572684909296beee4faa76fcce625916871547
[]
no_license
JackBro/DragonVer1.0
59590809df749540f70b904f83c4093890031fbb
31b3a97f2aa4a66d2ee518b8e6ae4245755009b1
refs/heads/master
2020-06-19T21:02:17.248852
2014-05-08T02:19:33
2014-05-08T02:19:33
74,833,772
0
1
null
2016-11-26T15:29:10
2016-11-26T15:29:10
null
UTF-8
C++
false
false
1,489
h
#ifndef _LBUF_H_ #define _LBUF_H_ #include "ex_OldCmodel.h" #include "chipbase.h" #define REG_LBUF_STATUS 0x00 #define REG_LBUF_YUVMODE 0x01 #define REG_LBUF_WORKMODE 0x02 #define REG_LBUF_DSTWIDTH_H 0x03 #define REG_LBUF_DSTWIDTH_L 0x04 #define REG_LBUF_DSTHEIGHT_H 0x05 #define REG_LBUF_DSTHEIGHT_L 0x06 #define REG_LBUF_SRCWIDTH_H 0x07 #define REG_LBUF_SRCWIDTH_L 0x08 #define REG_LBUF_SRCHEIGHT_H 0x09 #define REG_LBUF_SRCHEIGHT_L 0x0A //================ class CLbufZoom ========= class OLDCMODEL_DLL CLbufZoom : public CYuv422Base { public: int Process(ImageStream *pIn, ImageStream *pOut); protected: int FillImageInfo(ImageStream *pIn, ImageStream *pOut); }; //================ class CLbufConvert ========= class OLDCMODEL_DLL CLbuf2Block : public CYuv422Base { public: int Process(ImageStream *pIn, ImageBlock *pOut); protected: int FillImageInfo(ImageStream *pIn, ImageBlock *pOut); void OutputBlock(ImageStream *pIn, ImageBlock *pOut); private: ImageStream gISbuf[8]; }; //================ class CLbufConvert ========= class OLDCMODEL_DLL CLbuf : public CYuv422Base { public: CLbuf(void); virtual ~CLbuf(void); void RegInit(void); void SetReg(int adr, int val); int Process(ImageStream *pIn, ImageBlock *pOut); int Process(ImageBlock *pIn, ImageStream *pOut); private: CLbufZoom gZoom; CLbuf2Block gBlock; private: ImageStream gISbuf; }; #endif
[ "ranger.su@gmail.com" ]
ranger.su@gmail.com
c4e65a6f23d19e3bffdd52bdeeb50b5a5969f419
0498ac7e488ea74613e95699aebfa734249a9d13
/server_src/headers/ServerSender.h
27f4f783ccff60ce5c4cb66bd9d85e23d393da22
[]
no_license
gianbelinche/Taller-TP-Final
0ced7d745e438a63dbf2087a1fe408d8fb0ab6ac
a143eb19c210d6f04e84e7faf5689a8cc80d83d5
refs/heads/master
2022-11-23T16:30:48.536664
2020-07-21T18:36:48
2020-07-21T18:36:48
269,137,371
1
1
null
null
null
null
UTF-8
C++
false
false
613
h
#ifndef SERVERSENDER_H #define SERVERSENDER_H #include <cstdint> #include <string> #include <utility> #include <vector> #include "Thread.h" #include "ProtectedQueue.h" #include "Socket.h" #include "SocketException.h" class ServerSender : public Thread { private: Socket& peer; ProtectedQueue<std::vector<uint32_t>>& outgoingMessages; // Default init public: ServerSender(Socket& p, ProtectedQueue<std::vector<uint32_t>>& outgoing); ~ServerSender(); void run() override; std::string encodeEvent(std::vector<uint32_t> event); void sendEvent(std::string event); }; #endif // SERVERSENDER_H
[ "juliancrespo15@gmail.com" ]
juliancrespo15@gmail.com
4d89a876ffb2f0ad107487809b806bcfc54b220d
0ed122deeb8afc56a0dd58708c5b78553e0ad6c2
/gemmOren/cutlass/tile_coord.h
881bc602ffe6d117bfa623834c09d7579681098e
[]
no_license
cryptobiu/MPCAnonymousBloging
41e84704b92dbf2ffbd95fda7a7cc1c0041012f9
c3ff5aab99109a6ea8b896737b0eaf907e957c59
refs/heads/master
2022-04-23T00:42:36.390281
2020-04-26T13:57:36
2020-04-26T13:57:36
160,517,609
4
2
null
null
null
null
UTF-8
C++
false
false
6,022
h
/*************************************************************************************************** * Copyright (c) 2017-2018, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the NVIDIA CORPORATION nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TOR (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **************************************************************************************************/ /*! \file \brief Defines a coordinate used for the CUTLASS 4-D tile structure. */ #pragma once #include "cutlass/coord.h" namespace cutlass { /////////////////////////////////////////////////////////////////////////////////////////////////// /// TileCoord wraps Coord<4, int> to provide a helper for accessing named dimensions. Classes /// expecting a coordinate in the rank=4 index space of a CUTLASS tile structure should use TileCoord. template <typename Index_ = int> struct TileCoord : public Coord<4, Index_> { /// Index type typedef Index_ Index; /// Underlying Coord<4> typedef Coord<4, Index> Base; /// D dimension static int kD = 0; /// H dimension static int kH = 1; /// W dimension static int kW = 2; /// C dimension static int kC = 3; // // Methods // /// Default ctor CUTLASS_HOST_DEVICE TileCoord() { } /// Constructs from Coord<3> and infers coord[kC] = 0 CUTLASS_HOST_DEVICE TileCoord(Coord<3, Index> const &coord): Base(make_Coord(coord[0], coord[1], coord[2], 0)) { } /// Constructs from Coord<4> CUTLASS_HOST_DEVICE TileCoord(Coord<4, Index> const &coord): Base(coord) { } /// Constructs from an array of coordinate elements CUTLASS_HOST_DEVICE TileCoord(Index coord[4]): Base(coord) { } /// Helper to construct from a row and column CUTLASS_HOST_DEVICE TileCoord(Index d, Index h, Index w, Index c): Base(make_Coord(d, h, w, c)) { } /// Returns the D element of the coordinate CUTLASS_HOST_DEVICE Index const & d() const { return this->at(kD); } /// Returns the D element of the coordinate CUTLASS_HOST_DEVICE Index & d() { return this->at(kD); } /// Returns the H element of the coordinate CUTLASS_HOST_DEVICE Index const & h() const { return this->at(kH); } /// Returns the H element of the coordinate CUTLASS_HOST_DEVICE Index & h() { return this->at(kH); } /// Returns the W element of the coordinate CUTLASS_HOST_DEVICE Index const & w() const { return this->at(kW); } /// Returns the W element of the coordinate CUTLASS_HOST_DEVICE Index & w() { return this->at(kW); } /// Returns the Celement of the coordinate CUTLASS_HOST_DEVICE Index const & c() const { return this->at(kC); } /// Returns the C element of the coordinate CUTLASS_HOST_DEVICE Index & c() { return this->at(kC); } /// Gets H and W dimensions as a Coord<2> CUTLASS_HOST_DEVICE Coord<2> hw() const { return make_Coord(h(), w()); } /// Gets H, W, and C dimensions as a Coord<3> CUTLASS_HOST_DEVICE Coord<3> hwc() const { return make_Coord(h(), w(), c()); } /// Gets D, H, and W dimensions as a Coord<3> CUTLASS_HOST_DEVICE Coord<3> dhw() const { return make_Coord(d(), h(), w()); } // // Coord operators // /// Element-wise addition CUTLASS_HOST_DEVICE TileCoord operator+(Base const& b) const { return TileCoord(Base::operator+(b)); } /// Element-wise subtraction CUTLASS_HOST_DEVICE TileCoord operator-(Base const& b) const { return TileCoord(Base::operator-(b)); } /// Element-wise multiplication CUTLASS_HOST_DEVICE TileCoord operator*(Base const& b) const { return TileCoord(Base::operator*(b)); } /// Element-wise division CUTLASS_HOST_DEVICE TileCoord operator/(Base const& b) const { return TileCoord(Base::operator/(b)); } /// In-place addition CUTLASS_HOST_DEVICE TileCoord& operator+=(Base const& b) { Base::operator+=(b); return *this; } /// In-place subtraction CUTLASS_HOST_DEVICE TileCoord& operator-=(Base const& b) { Base::operator-=(b); return *this; } /// In-place multiplication CUTLASS_HOST_DEVICE TileCoord& operator*=(Base const& b) { Base::operator*=(b); return *this; } /// In-place division CUTLASS_HOST_DEVICE TileCoord& operator/=(Base const& b) { Base::operator/=(b); return *this; } }; /////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace cutlass
[ "liork.cryptobiu@gmail.com" ]
liork.cryptobiu@gmail.com
a5ee38f4564877cb209c5c557bc1be269e087f11
6bcdf9be056b6e211924771e18984d782d1c8e45
/include/skyr/version.hpp
6b5cf3b82616d26bb884176fb340e62a1f541b15
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ingomueller-net/url
d509817714aff801e33e3ce86b086a2884f1c373
31b0d26bb168dc8383986a1d4f50933c8ce77ecf
refs/heads/master
2020-07-01T07:58:42.280629
2019-08-07T17:39:57
2019-08-07T17:39:57
201,098,595
0
0
BSL-1.0
2019-08-07T17:40:51
2019-08-07T17:40:51
null
UTF-8
C++
false
false
958
hpp
// Copyright 2018 Glyn Matthews. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SKYR_VERSION_INC #define SKYR_VERSION_INC #include <tuple> #include <skyr/config.hpp> #define SKYR_VERSION_MAJOR 1 #define SKYR_VERSION_MINOR 0 #define SKYR_VERSION_PATCH 0 #define SKYR_VERSION_STRING \ SKYR_PREPROCESSOR_TO_STRING(SKYR_VERSION_MAJOR) "." \ SKYR_PREPROCESSOR_TO_STRING(SKYR_VERSION_MINOR) namespace skyr { /// \returns The major, minor and patch version as a tuple static constexpr std::tuple<int, int, int> version() noexcept { return std::make_tuple( SKYR_VERSION_MAJOR, SKYR_VERSION_MINOR, SKYR_VERSION_PATCH); } /// \returns The version as a string in the form MAJOR.MINOR static constexpr const char *version_string() noexcept { return SKYR_VERSION_STRING; } } // namespace skyr #endif // SKYR_VERSION_INC
[ "glyn.matthews@gmail.com" ]
glyn.matthews@gmail.com
b49a1c558daa43efdad525caf41fd4e72ecd55b1
ba9ebc8775c362e64393255966cdf3e19c664660
/Contest/ABC132/F.cpp
ebefb25f3b4dce15b8e96f63da5277f656500f75
[]
no_license
CoffeeKumazaki/AtCoder
84a8917296ba486073b333f4d2f334c6c9173d8d
3d3723992b7c92ea14b100ce3ce9176adeab6687
refs/heads/master
2020-05-03T04:41:47.489630
2019-07-15T13:22:37
2019-07-15T13:22:37
178,429,165
0
0
null
null
null
null
UTF-8
C++
false
false
357
cpp
#include <iostream> #include <iomanip> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <cmath> #include <string> #include <map> #include <queue> #include <stack> #define FOR(arg, ini, end) for(int arg = ini; arg < end; arg++) using namespace std; int main(int argc, const char * argv[]) { return 0; }
[ "kumazaki98@gmail.com" ]
kumazaki98@gmail.com
d9b770434121b3ca478683d93c623d642c05fc15
e5e2856e27475b38e959eefaf32e5df5778390de
/source/adler32.h
40adb16fdeaf1a3ddced105e0099634aee7ad619
[ "MIT" ]
permissive
Artexety/inflatecpp
96515ebf888567e63bc65cef822e7c1924134e0a
e80991d5a0c3c40a5225e57fb1b113603baad157
refs/heads/main
2023-03-14T06:40:05.501553
2021-03-08T09:31:24
2021-03-08T09:31:24
305,088,960
14
2
null
null
null
null
UTF-8
C++
false
false
1,818
h
/* By Mark Adler - https://github.com/madler/zlib/blob/master/adler32.c Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jean-loup Gailly Mark Adler jloup@gzip.org madler@alumni.caltech.edu The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ #ifndef _ADLER_32_H #define _ADLER_32_H #include <iostream> #include <stdio.h> #define BASE 65521U #define NMAX 5552 #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); #define MOD(a) a %= BASE #define MOD28(a) a %= BASE #define MOD63(a) a %= BASE unsigned int adler32_z(unsigned int, const unsigned char *, unsigned int); #endif /* !_ADLER_32_H */
[ "alexander.lowa.04@gmail.com" ]
alexander.lowa.04@gmail.com
1df0cd788e87c73e30c1f9cd582184180e274c72
28943136c1404c79260eb0b2694546885c65d5b9
/src/Subsystems/CanBurgler.h
eee67f98d346ebd80fc79bbde92c296d1cb0b5aa
[]
no_license
4329/Worlds2015-CPP
e0d26332266685e82778b775bc1bd0e1d84af195
cf8616e9886c904c4e677242ced5eba19728c0d5
refs/heads/master
2021-03-12T22:15:48.615467
2015-04-19T05:25:06
2015-04-19T05:25:06
34,194,619
0
1
null
null
null
null
UTF-8
C++
false
false
1,331
h
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #ifndef CANBURGLER_H #define CANBURGLER_H #include "Commands/Subsystem.h" #include "WPILib.h" #include "../Configurable.h" class CanBurgler_Config; class CanBurgler: public Subsystem, public Configurable { private: CanBurgler_Config *myConfig; public: // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS DoubleSolenoid* RightCanBurglerSolenoid; DoubleSolenoid* LeftCanBurglerSolenoid; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS CanBurgler(); virtual ~CanBurgler(); virtual void RetrieveConfig(); virtual void StoreConfig(); virtual void Configure(); void InitDefaultCommand(); void ExtendRight(); void ExtendLeft(); void ExtendBoth(); void RetractRight(); void RetractLeft(); void RetractBoth(); bool IsRightExtended(); bool IsLeftExtended(); }; #endif
[ "mdballard2@charter.net" ]
mdballard2@charter.net
53c075565505e617a44d91893135054fab37b169
0f7a4119185aff6f48907e8a5b2666d91a47c56b
/sstd_utility/windows_boost/boost/log/expressions/predicates.hpp
baf9536c8cb4961b0b565bb2c3a383230d739599
[]
no_license
jixhua/QQmlQuickBook
6636c77e9553a86f09cd59a2e89a83eaa9f153b6
782799ec3426291be0b0a2e37dc3e209006f0415
refs/heads/master
2021-09-28T13:02:48.880908
2018-11-17T10:43:47
2018-11-17T10:43:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,123
hpp
/* * Copyright Andrey Semashev 2007 - 2015. * 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) */ /*! * \file predicates.hpp * \author Andrey Semashev * \date 29.01.2012 * * The header includes all template expression predicates. */ #ifndef BOOST_LOG_EXPRESSIONS_PREDICATES_HPP_INCLUDED_ #define BOOST_LOG_EXPRESSIONS_PREDICATES_HPP_INCLUDED_ #include <boost/log/detail/config.hpp> #include <boost/log/expressions/predicates/has_attr.hpp> #include <boost/log/expressions/predicates/begins_with.hpp> #include <boost/log/expressions/predicates/ends_with.hpp> #include <boost/log/expressions/predicates/contains.hpp> #include <boost/log/expressions/predicates/matches.hpp> #include <boost/log/expressions/predicates/is_in_range.hpp> #include <boost/log/expressions/predicates/is_debugger_present.hpp> #include <boost/log/expressions/predicates/channel_severity_filter.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif #endif // BOOST_LOG_EXPRESSIONS_PREDICATES_HPP_INCLUDED_
[ "nanguazhude@vip.qq.com" ]
nanguazhude@vip.qq.com
52e61da394129b89ec8db4585cfd0ef5ae193151
060b01ae01f8e9fa1bb408c36cba2fe00ed5b442
/libnetframework/Socket.cpp
2555f6ea4c1743f1c734c4107ee5f27742d91d4e
[]
no_license
ryanzhw1987/easynetwork
fa32843433a92feb2afdecddd659442a615cf734
5b8994fd760dd38d9b6b9fc5d3449105b9817c35
refs/heads/master
2021-01-01T18:08:01.716654
2013-02-19T13:32:06
2013-02-19T13:32:06
38,415,331
4
3
null
null
null
null
UTF-8
C++
false
false
11,209
cpp
#include "Socket.h" #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include "slog.h" /////////////////////////////////////////////////////////////// /////////////// Socket /////////////// /////////////////////////////////////////////////////////////// void Socket::copy_ip(const char *ip) { m_ip[0] = '\0'; if(ip==NULL || strlen(ip)<=0) return; int size = sizeof(m_ip)-1; strncpy(m_ip, ip, size); m_ip[size] = '\0'; } Socket::Socket(SocketHandle socket_handle/*=SOCKET_INVALID*/, int port/*=-1*/, const char *ip/*=NULL*/, BlockMode block_mode/*=NOBLOCK*/) { m_socket_handle = socket_handle; m_port = port; copy_ip(ip); m_block_mode = block_mode; } Socket::~Socket() { if(m_socket_handle != SOCKET_INVALID) { SLOG_TRACE("~Socket() close socket. fd=%d", m_socket_handle); close(m_socket_handle); m_socket_handle = SOCKET_INVALID; } } bool Socket::assign(SocketHandle socket_handle, int port, const char *ip, BlockMode block_mode) { if(m_socket_handle != SOCKET_INVALID) return false; m_socket_handle = socket_handle; m_port = port; copy_ip(ip); m_block_mode = block_mode; return true; } /////////////////////////////////////////////////////////////// /////////////// ListenSocket /////////////// /////////////////////////////////////////////////////////////// bool ListenSocket::open(int /*timeout_ms=2000*/) { if(m_socket_handle!=SOCKET_INVALID || m_port<=0) return false; //1. 创建socket int fd = socket(AF_INET, SOCK_STREAM, 0); if(fd < 0) return false; //2. 设置属性 int flags = fcntl(fd, F_GETFL, 0); if(flags == -1 ) { SLOG_ERROR("fcntl<get> failed. errno=%d(%s)", errno, strerror(errno)); close(fd); return false; } if(m_block_mode == NOBLOCK) //non block mode flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK; flags |= FD_CLOEXEC; //close on exec if(fcntl(fd, F_SETFL, flags) == -1) { SLOG_ERROR("<set> failed. errno=%d(%s)", errno, strerror(errno)); close(fd); return false; } //set reuse int reuse = 1; if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) == -1) { SLOG_ERROR("set socket SO_REUSEADDR option failed, errno=%d(%s)",errno, strerror(errno)); close(fd); return false; } //3. 绑定到端口 struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(m_port); if(bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { SLOG_ERROR("bind failed, errno=%d(%s)",errno, strerror(errno)); close(fd); return false; } //4. 监听端口.监听队列中等待accept的最大连接数设置为默认值 if(listen(fd, 128) == -1) { SLOG_ERROR("listen failed, errno=%d(%s)",errno, strerror(errno)); close(fd); return false; } m_socket_handle = fd; return true; } /////////////////////////////////////////////////////////////// /////////////// TransSocket /////////////// /////////////////////////////////////////////////////////////// TransSocket::~TransSocket() { while(!m_send_queue.empty()) { ByteBuffer *byte_buffer = m_send_queue.front(); m_send_queue.pop_front(); delete byte_buffer; } SLOG_DEBUG("~TransSocket().remain %d bytes data unsend", m_send_queue_size); while(!m_recv_queue.empty()) { ByteBuffer *byte_buffer = m_recv_queue.front(); m_recv_queue.pop_front(); delete byte_buffer; } SLOG_DEBUG("~TransSocket().remain %d bytes data unrecv", m_recv_queue_size); } bool TransSocket::open(int timeout_ms/*=2000*/) { if(m_socket_handle!=SOCKET_INVALID || strlen(m_ip)<=0 || m_port <=0) return false; //1. 创建socket m_socket_handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(m_socket_handle < 0) { SLOG_ERROR("create active socket error, errno=%d(%s)", errno, strerror(errno)); m_socket_handle = SOCKET_INVALID; return false; } //2. 初始化 if(init_active_socket() == -1) { SLOG_ERROR("init active socket error. close fd=%d", m_socket_handle); close(m_socket_handle); m_socket_handle = SOCKET_INVALID; return false; } //3. 连接 struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(m_ip); addr.sin_port = htons(m_port); if(connect(m_socket_handle, (struct sockaddr*)&addr, sizeof(addr)) == -1) { if(m_block_mode==NOBLOCK && (errno==EINPROGRESS||errno==EINTR)) //非阻塞并且等待建立连接 { struct timeval tval; fd_set rset, wset; FD_ZERO(&rset); FD_SET(m_socket_handle, &rset); wset = rset; tval.tv_sec = timeout_ms/1000; tval.tv_usec = (timeout_ms%1000)*1000; int tmp = select(m_socket_handle+1, (fd_set*)&rset, (fd_set*)&wset, (fd_set*)NULL, &tval); if (tmp <= 0) { SLOG_ERROR("select failed when connecting server[ip=%s,port=%d]. errno=%d(%s)", m_ip, m_port, errno, strerror(errno)); close(m_socket_handle); m_socket_handle = SOCKET_INVALID; return false; } if(FD_ISSET(m_socket_handle,&rset) || FD_ISSET(m_socket_handle,&wset)) { int error; int len = sizeof(error); tmp = getsockopt(m_socket_handle, SOL_SOCKET, SO_ERROR, (void*)&error, (socklen_t*)&len); if(tmp<0 || (tmp==0&&error!=0)) { SLOG_ERROR("other error when connecting server[ip=%s,port=%d]. errno=%d(%s)", m_ip, m_port, error, strerror(errno)); close(m_socket_handle); m_socket_handle = SOCKET_INVALID; return false; } } } else { SLOG_ERROR("connect server[ip=%s,port=%d]failed. errno=%d(%s)", m_ip, m_port, errno, strerror(errno)); close(m_socket_handle); m_socket_handle = SOCKET_INVALID; return false; } } return true; } //初始化主动连接 int TransSocket::init_active_socket() { //设置socket属性 int flags = fcntl(m_socket_handle, F_GETFL, 0); if(flags == -1 ) { SLOG_ERROR("fcntl<get> active socket faile. errno=%d(%s)", errno, strerror(errno)); return -1; } if(m_block_mode==NOBLOCK) //non block mode flags |= O_NONBLOCK; else flags &= ~O_NONBLOCK; if (fcntl(m_socket_handle, F_SETFL, flags) == -1 ) { SLOG_ERROR("fcntl<set> active socket faile. errno=%d(%s)", errno, strerror(errno)); return -1; } return 0; } //尝试接收指定长度的数据(可能只接收部分数据). //返回值: //成功: 返回收到的字节数(大于等于0). //错误: 返回TRANS_ERROR int TransSocket::recv_data(char *buffer, int len) { assert(buffer!=NULL && len>0); int ret = recv(m_socket_handle, buffer, len, 0); if(ret > 0) return ret; if(ret == 0) { SLOG_ERROR("peer close socket gracefully. fd=%d", m_socket_handle); return TRANS_ERROR; } if(errno==EINTR || errno==EWOULDBLOCK || errno==EAGAIN) return 0; SLOG_ERROR("receive data error. errno=%d(%s)",errno, strerror(errno)); return TRANS_ERROR; } //接收指定长度的数据(全部接收). //返回值: //成功: 返回指定接收的数据大小len. //错误: 返回TRANS_ERROR int TransSocket::recv_data_all(char *buffer, int len) { assert(buffer!=NULL && len>0); int ret = 0; int read_size = 0; //已读数据大小 int need_size = 0; //剩下未读数据大小 while(read_size < len) { need_size = len-read_size; ret = recv_data(buffer+read_size, need_size); if(ret == TRANS_ERROR) return ret; read_size += ret; } return read_size; } //尝试发送指定长度的数据(可能只发送部分数据) //返回值: //成功: 返回发送的字节数(大于等于0) //失败: 返回TRANS_ERROR int TransSocket::send_data(char *buffer, int len) { assert(buffer!=NULL && len>0); int ret = send(m_socket_handle, buffer, len, 0); if(ret > 0)//非阻塞时可能只发送部分数据 return ret; if(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN) //中断,重试 return 0; SLOG_ERROR("send_data return error. errno=%d(%s)", errno, strerror(errno)); return TRANS_ERROR; } //发送指定长度的数据(全部发送) //返回值: //成功:返回指定发送的数据大小len //失败: 返回TRANS_ERROR int TransSocket::send_data_all(char *buffer, int len) { assert(buffer!=NULL && len>0); int ret = 0; int send_size = 0; int need_size = 0; while(send_size < len) { need_size = len-send_size; ret = send_data(buffer+send_size, need_size); if(ret == TRANS_ERROR) return TRANS_ERROR; send_size += ret; } return send_size; } //添加待发送的数据到等待队列 bool TransSocket::push_send_buffer(ByteBuffer *byte_buffer) { if(byte_buffer==NULL) return false; m_send_queue.push_back(byte_buffer); m_send_queue_size += byte_buffer->size(); SLOG_DEBUG("total %d bytes data waiting to send on socket fd=%d", m_send_queue_size, m_socket_handle); return true; } //尝试发送等待队列中的数据 //返回值: //大于等于0: 剩下未发送的数据大小 //TRANS_ERROR: 错误 int TransSocket::send_buffer() { SLOG_DEBUG("try to send %d bytes data of socket fd=%d", m_send_queue_size, m_socket_handle); int ret = 0; int size = 0; char *buf = NULL; while(!m_send_queue.empty()) { ByteBuffer *byte_buffer = m_send_queue.front(); assert(byte_buffer != NULL); size = byte_buffer->size(); if(size <= 0) continue; buf = byte_buffer->get_data(); ret = send_data(buf+m_send_size, size-m_send_size); if(ret == TRANS_ERROR) return ret; m_send_queue_size -= ret; if(ret < size-m_send_size) { m_send_size += ret; break; } m_send_size = 0; m_send_queue.pop_front(); delete byte_buffer; } return m_send_queue_size; } int TransSocket::recv_buffer(ByteBuffer *byte_buffer, int len, bool wait_all=true) { assert(byte_buffer!=NULL && len>0); char *buf = byte_buffer->get_append_buffer(len); if(buf == NULL) { SLOG_ERROR("recv buffer no momory"); return 0; } int ret = 0; if(wait_all) { ret = recv_data_all(buf, len); assert(ret == len); } else ret = recv_data(buf, len); if(ret == TRANS_ERROR) return ret; else byte_buffer->set_append_size(ret); return ret; } //将io_buffer保存到待接收队列末尾 bool TransSocket::push_recv_buffer(ByteBuffer *byte_buffer) { if(byte_buffer == NULL) return false; m_recv_queue.push_back(byte_buffer); m_recv_queue_size += byte_buffer->size(); SLOG_DEBUG("total %d bytes data waiting to recv on socket fd=%d", m_recv_queue_size, m_socket_handle); return true; } //从待接收队列头部获取一个io_buffer(该io_buffer从队列头移除) ByteBuffer* TransSocket::pop_recv_buffer() { if(m_recv_queue.empty()) return NULL; ByteBuffer *byte_buffer = m_recv_queue.front(); m_recv_queue.pop_front(); m_recv_queue_size -= byte_buffer->size(); SLOG_DEBUG("total %d bytes data waiting to recv on socket fd=%d", m_recv_queue_size, m_socket_handle); return byte_buffer; }
[ "xmulyj@gmail.com" ]
xmulyj@gmail.com
e9907ed0d87177b3047cce48a7bf7f69df7f3a6a
dc2f96addc945de3eca2b7413bc1d603fb35a07d
/kernels/subdiv/half_edge.h
0e59daa27599f22db0b13532073b9d2e974a0824
[ "Apache-2.0", "IJG", "LicenseRef-scancode-generic-cla" ]
permissive
marty1885/embree-arm
cd600afc5bcd042bf7fdfcf0873d5659b643add2
60651db1eb56a5ef2c9c56e49eeca175ff05a112
refs/heads/master
2021-01-13T16:24:37.838967
2017-04-05T14:23:48
2017-04-05T14:23:48
79,805,191
13
3
null
null
null
null
UTF-8
C++
false
false
12,107
h
// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // 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. // // ======================================================================== // #pragma once #include "catmullclark_coefficients.h" namespace embree { class __aligned(32) HalfEdge { friend class SubdivMesh; public: enum PatchType : char { REGULAR_QUAD_PATCH = 0, //!< a regular quad patch can be represented as a B-Spline IRREGULAR_QUAD_PATCH = 1, //!< an irregular quad patch can be represented as a Gregory patch COMPLEX_PATCH = 2 //!< these patches need subdivision and cannot be processed by the above fast code paths }; enum VertexType : char { REGULAR_VERTEX = 0, //!< regular vertex NON_MANIFOLD_EDGE_VERTEX = 1, //!< vertex of a non-manifold edge }; __forceinline friend PatchType max( const PatchType& ty0, const PatchType& ty1) { return (PatchType) max((int)ty0,(int)ty1); } HalfEdge () : vtx_index(-1), next_half_edge_ofs(0), prev_half_edge_ofs(0), opposite_half_edge_ofs(0), edge_crease_weight(0), vertex_crease_weight(0), edge_level(0), patch_type(COMPLEX_PATCH), vertex_type(REGULAR_VERTEX) { static_assert(sizeof(HalfEdge) == 32, "invalid half edge size"); } __forceinline bool hasOpposite() const { return opposite_half_edge_ofs != 0; } __forceinline void setOpposite(HalfEdge* opposite) { opposite_half_edge_ofs = int(opposite-this); } __forceinline HalfEdge* next() { assert( next_half_edge_ofs != 0 ); return &this[next_half_edge_ofs]; } __forceinline const HalfEdge* next() const { assert( next_half_edge_ofs != 0 ); return &this[next_half_edge_ofs]; } __forceinline HalfEdge* prev() { assert( prev_half_edge_ofs != 0 ); return &this[prev_half_edge_ofs]; } __forceinline const HalfEdge* prev() const { assert( prev_half_edge_ofs != 0 ); return &this[prev_half_edge_ofs]; } __forceinline HalfEdge* opposite() { assert( opposite_half_edge_ofs != 0 ); return &this[opposite_half_edge_ofs]; } __forceinline const HalfEdge* opposite() const { assert( opposite_half_edge_ofs != 0 ); return &this[opposite_half_edge_ofs]; } __forceinline HalfEdge* rotate() { return opposite()->next(); } __forceinline const HalfEdge* rotate() const { return opposite()->next(); } __forceinline unsigned int getStartVertexIndex() const { return vtx_index; } __forceinline unsigned int getEndVertexIndex () const { return next()->vtx_index; } /*! tests if the start vertex of the edge is regular */ __forceinline PatchType vertexType() const { const HalfEdge* p = this; size_t face_valence = 0; bool hasBorder = false; do { /* we need subdivision to handle edge creases */ if (p->hasOpposite() && p->edge_crease_weight > 0.0f) return COMPLEX_PATCH; face_valence++; /* test for quad */ const HalfEdge* pp = p; pp = pp->next(); if (pp == p) return COMPLEX_PATCH; pp = pp->next(); if (pp == p) return COMPLEX_PATCH; pp = pp->next(); if (pp == p) return COMPLEX_PATCH; pp = pp->next(); if (pp != p) return COMPLEX_PATCH; /* continue with next face */ p = p->prev(); if (likely(p->hasOpposite())) p = p->opposite(); /* if there is no opposite go the long way to the other side of the border */ else { face_valence++; hasBorder = true; p = this; while (p->hasOpposite()) p = p->rotate(); } } while (p != this); /* calculate vertex type */ if (face_valence == 2 && hasBorder) { if (vertex_crease_weight == 0.0f ) return REGULAR_QUAD_PATCH; else if (vertex_crease_weight == float(inf)) return REGULAR_QUAD_PATCH; else return COMPLEX_PATCH; } else if (vertex_crease_weight != 0.0f) return COMPLEX_PATCH; else if (face_valence == 3 && hasBorder) return REGULAR_QUAD_PATCH; else if (face_valence == 4 && !hasBorder) return REGULAR_QUAD_PATCH; else return IRREGULAR_QUAD_PATCH; } /*! calculates the type of the patch */ __forceinline PatchType patchType() const { const HalfEdge* p = this; PatchType ret = REGULAR_QUAD_PATCH; ret = max(ret,p->vertexType()); if ((p = p->next()) == this) return COMPLEX_PATCH; ret = max(ret,p->vertexType()); if ((p = p->next()) == this) return COMPLEX_PATCH; ret = max(ret,p->vertexType()); if ((p = p->next()) == this) return COMPLEX_PATCH; ret = max(ret,p->vertexType()); if ((p = p->next()) != this) return COMPLEX_PATCH; return ret; } /*! tests if the face is a regular b-spline face */ __forceinline bool isRegularFace() const { return patch_type == REGULAR_QUAD_PATCH; } /*! tests if the face can be diced (using bspline or gregory patch) */ __forceinline bool isGregoryFace() const { return patch_type == IRREGULAR_QUAD_PATCH || patch_type == REGULAR_QUAD_PATCH; } /*! tests if the base vertex of this half edge is a corner vertex */ __forceinline bool isCorner() const { return !hasOpposite() && !prev()->hasOpposite(); } /*! tests if the vertex is attached to any border */ __forceinline bool vertexHasBorder() const { const HalfEdge* p = this; do { if (!p->hasOpposite()) return true; p = p->rotate(); } while (p != this); return false; } /*! tests if the face this half edge belongs to has some border */ __forceinline bool faceHasBorder() const { const HalfEdge* p = this; do { if (p->vertexHasBorder()) return true; p = p->next(); } while (p != this); return false; } /*! calculates conservative bounds of a catmull clark subdivision face */ __forceinline BBox3fa bounds(const BufferRefT<Vec3fa>& vertices) const { BBox3fa bounds = this->get1RingBounds(vertices); for (const HalfEdge* p=this->next(); p!=this; p=p->next()) bounds.extend(p->get1RingBounds(vertices)); return bounds; } /*! tests if this is a valid patch */ __forceinline bool valid(const BufferRefT<Vec3fa>& vertices) const { size_t N = 1; if (!this->validRing(vertices)) return false; for (const HalfEdge* p=this->next(); p!=this; p=p->next(), N++) { if (!p->validRing(vertices)) return false; } return N >= 3 && N <= MAX_PATCH_VALENCE; } /*! counts number of polygon edges */ __forceinline unsigned int numEdges() const { unsigned int N = 1; for (const HalfEdge* p=this->next(); p!=this; p=p->next(), N++); return N; } /*! stream output */ friend __forceinline std::ostream &operator<<(std::ostream &o, const HalfEdge &h) { return o << "{ " << "vertex = " << h.vtx_index << ", " << //" -> " << h.next()->vtx_index << ", " << "prev = " << h.prev_half_edge_ofs << ", " << "next = " << h.next_half_edge_ofs << ", " << "opposite = " << h.opposite_half_edge_ofs << ", " << //"edge_crease = " << h.edge_crease_weight << ", " << //"vertex_crease = " << h.vertex_crease_weight << ", " << //"edge_level = " << h.edge_level << " }"; } private: /*! calculates the bounds of the face associated with the half-edge */ __forceinline BBox3fa getFaceBounds(const BufferRefT<Vec3fa>& vertices) const { BBox3fa b = vertices[getStartVertexIndex()]; for (const HalfEdge* p = next(); p!=this; p=p->next()) { b.extend(vertices[p->getStartVertexIndex()]); } return b; } /*! calculates the bounds of the 1-ring associated with the vertex of the half-edge */ __forceinline BBox3fa get1RingBounds(const BufferRefT<Vec3fa>& vertices) const { BBox3fa bounds = empty; const HalfEdge* p = this; do { /* calculate bounds of current face */ bounds.extend(p->getFaceBounds(vertices)); p = p->prev(); /* continue with next face */ if (likely(p->hasOpposite())) p = p->opposite(); /* if there is no opposite go the long way to the other side of the border */ else { p = this; while (p->hasOpposite()) p = p->opposite()->next(); } } while (p != this); return bounds; } /*! tests if this is a valid face */ __forceinline bool validFace(const BufferRefT<Vec3fa>& vertices, size_t& N) const { const Vec3fa v = vertices[getStartVertexIndex()]; if (!isvalid(v)) return false; size_t n = 1; for (const HalfEdge* p = next(); p!=this; p=p->next(), n++) { const Vec3fa v = vertices[p->getStartVertexIndex()]; if (!isvalid(v)) return false; } N += n-2; return n >= 3 && n <= MAX_PATCH_VALENCE; } /*! tests if this is a valid ring */ __forceinline bool validRing(const BufferRefT<Vec3fa>& vertices) const { size_t faceValence = 0; size_t edgeValence = 0; const HalfEdge* p = this; do { /* calculate bounds of current face */ if (!p->validFace(vertices,edgeValence)) return false; faceValence++; p = p->prev(); /* continue with next face */ if (likely(p->hasOpposite())) p = p->opposite(); /* if there is no opposite go the long way to the other side of the border */ else { faceValence++; edgeValence++; p = this; while (p->hasOpposite()) p = p->opposite()->next(); } } while (p != this); return faceValence <= MAX_RING_FACE_VALENCE && edgeValence <= MAX_RING_EDGE_VALENCE; } private: unsigned int vtx_index; //!< index of edge start vertex int next_half_edge_ofs; //!< relative offset to next half edge of face int prev_half_edge_ofs; //!< relative offset to previous half edge of face int opposite_half_edge_ofs; //!< relative offset to opposite half edge public: float edge_crease_weight; //!< crease weight attached to edge float vertex_crease_weight; //!< crease weight attached to start vertex float edge_level; //!< subdivision factor for edge PatchType patch_type; //!< stores type of subdiv patch VertexType vertex_type; //!< stores type of the start vertex char align[2]; }; }
[ "sven.woop@intel.com" ]
sven.woop@intel.com
629583aa71b90a393169c0effba5b4e6a8f3c3b4
74136b46754d5524c96ba8cae1a78ec6c46daf18
/general/cpp/stringview.hpp
fa08d0c64f1ce91c67ddf2a840542cac6563273a
[ "MIT" ]
permissive
Magorx/DecisionTree
8ad4b503d8464e232a096adf05504250465a3df2
8572ef53daa2447f1ebf3c5c6a87ed434df49b6e
refs/heads/main
2023-06-28T00:13:43.055453
2021-07-25T14:28:26
2021-07-25T14:28:26
313,141,786
0
0
null
null
null
null
UTF-8
C++
false
false
3,207
hpp
#ifndef GENERAL_STRINGVIEW #define GENERAL_STRINGVIEW #include <cstdlib> #include <cstdio> #include <cstring> class StringView { private: char *buffer; char null_char; size_t size; bool own_buffer; public: StringView (const StringView& other) = delete; StringView& operator= (const StringView& other) = delete; StringView() : buffer(nullptr), null_char('\0'), size(0), own_buffer(false) {} ~StringView() {} void ctor() {dtor();} static StringView *NEW() { StringView *cake = (StringView*) calloc(1, sizeof(StringView)); if (!cake) { return nullptr; } cake->ctor(); return cake; } void ctor(char *c_string, bool own_buffer_ = false) { if (c_string == nullptr) { dtor(); return; } size = strlen(c_string); buffer = c_string; own_buffer = own_buffer_; } static StringView *NEW(char *c_string, bool own_buffer_) { StringView *cake = (StringView*) calloc(1, sizeof(StringView)); if (!cake) { return nullptr; } cake->ctor(c_string, own_buffer_); return cake; } void dtor() { if (own_buffer && buffer) { free(buffer); } buffer = nullptr; own_buffer = false; null_char = '\0'; size = 0; } static void DELETE(StringView *stringview) { if (!stringview) { return; } stringview->dtor(); free(stringview); } bool is_null() const { return buffer == nullptr; } size_t length() const { return size; } const char &operator[](size_t i) const { if (i >= size) { return null_char; } else { return buffer[i]; } } char &break_index(size_t i) { if (i >= size) { return null_char; } else { return buffer[i]; } } int read(char *c_string, const bool stop_on_space = true, const char ending_char = '\0') { if (c_string == nullptr) { return -1; } char *c = c_string; size_t length = 0; while (*c && (!stop_on_space || !isspace(*c)) && *c != ending_char) { ++c; ++length; } dtor(); size = length; buffer = c_string; return (int) length; } void generate_length_format(char *string) { char format[24]; // to simulate the certain lenth of out stringview sprintf(format, "%%.%lus", size); size_t length = strlen(string); char *string_copy = (char*) calloc(length + 1, sizeof(char)); memcpy(string_copy, string, length); sprintf(string, string_copy, format); free(string_copy); } void print(FILE *file_ptr = stdout, const int sidx = -1, const int eidx = -1) const { if (is_null()) { return; } if (sidx < 0 && eidx < 0) { char format[24]; // to simulate the certain lenth of out stringview sprintf(format, "%%.%lus", size); fprintf(file_ptr, format, buffer); } else { for (int i = sidx; !(i >= (int) size || (eidx >= 0 && i < eidx)); ++i) { fprintf(file_ptr, "%c", buffer[i]); } } } char *get_buffer() const { return buffer; } bool operator==(const StringView &other) const { if (length() != other.length()) { return false; } size_t len = length(); for (size_t i = 0; i < len; ++i) { if ((*this)[i] != other[i]) { return false; } } return true; } bool equal(const StringView &other) const { return (*this) == other; } }; #endif // GENERAL_STRINGVIEW
[ "maxim.gorishniy@gmail.com" ]
maxim.gorishniy@gmail.com