hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
f8dce046425e63838ab09151342b0fa6132a32e0
21,597
h
C
trunk/libcvact/include/actITokenInitializer.h
flomar/CrypTool-VS2015
6468257af2e1002418882f22a9ed9fabddde096d
[ "Apache-2.0" ]
null
null
null
trunk/libcvact/include/actITokenInitializer.h
flomar/CrypTool-VS2015
6468257af2e1002418882f22a9ed9fabddde096d
[ "Apache-2.0" ]
null
null
null
trunk/libcvact/include/actITokenInitializer.h
flomar/CrypTool-VS2015
6468257af2e1002418882f22a9ed9fabddde096d
[ "Apache-2.0" ]
5
2016-07-02T12:59:28.000Z
2021-10-02T14:58:30.000Z
// --------------------------------------------------------------------------- // Name: actITokenInitializer.h // Product: cv act library // Purpose: ITokenInitializer interface declares common token profile initialization functionality. // // Copyright: (c) 2009 cv cryptovision GmbH // all rights reserved // Licence: The conditions for the use of this software are regulated // in the cv act library licence agreement. // // Autor: Markus Tesche // Date: 04/20/2009 // --------------------------------------------------------------------------- #ifndef ACT_ITokenInitializer_h #define ACT_ITokenInitializer_h #include "actBool.h" #include "actBlob.h" #include "actTypeTags.h" #include "actException.h" #include "actTokenBase.h" #include "actITokenFile.h" #include "actIRefCounted.h" // TODO: MTE: *** Replace std::vector<> by simple Range<TIData>(begin, end). #include <vector> namespace act { // Forward declarations // ----------------------------------------------------------------------- class ISCardOS; class IProfileGenerator; class ISCardCmdObserver; class Exception; class SCardToken; struct TIData; // ----------------------------------------------------------------------- extern const byte LEN_SERIALNO; //!< Default token serial number length. extern const byte PIN_PAD_CHAR; //!< Default PIN padding character. extern const byte PIN_RETRY_COUNTER; //!< Default PIN retry counter. extern const byte PIN_ENTRY_TIMEOUT; //!< Default PIN pad entry timeout in seconds. extern const byte GP_PRIVILEGES_NOT_INITIALIZED; //!< Default Global Platform applet privileges. // ----------------------------------------------------------------------- enum NamedParam { // last update: 12/10/2012 np_begin = 32, np_last = np_begin + 32, np_end, }; // ----------------------------------------------------------------------- enum NamedAC { // last update: 12/13/2012 // AC /* Last */ ac_begin = np_end, /* Blob */ ac_u_so = ac_begin, //!< AC Update for SO. /* Blob */ ac_ua_so, //!< AC Update|Append for SO. /* Blob */ ac_ua_user, //!< AC Update|Append for User. /* Blob */ ac_ua_user_or_so, //!< AC Update|Append for User or SO. // AC-DO /* Blob */ ac_do_ro, //!< AC-DO ReadOnly. /* Blob */ ac_do_u_so, //!< AC-DO Update for SO. /* Blob */ ac_do_u_user_or_so, //!< AC-DO Update for User or SO. // AC-Key /* Blob */ ac_key_all_always, //!< AC-Key Everyone all rights. // AC-Persoonalization /* Blob */ ac_personalize, //!< AC Update / Append only during personalization. // AC-?? // NOTE: Add more access conditions ... /* Last */ ac_last, /* End */ ac_end, }; //! //! \brief \a ITokenInitializer support function id's. // ----------------------------------------------------------------------- enum TIFId { TIFID_ERROR = -1, TIFID_BEGIN = 0, TIFID_PRE_LOAD = TIFID_BEGIN, //!< Before each package / applet will be loaded. TIFID_POST_LOAD, //!< After successfull loading package / applet. TIFID_PRE_INSTALL, //!< Before package / applet installation, \sa TIFID_PRE_LOAD. TIFID_PARAMETER, //!< Provide package / applet specific load / installation parameter. TIFID_POST_INSTALL, //!< After successfull package / applet installation, \sa TIFID_POST_LOAD. TIFID_END, TIFID_LENGTH = TIFID_END, /* ... */ TIFID_CHECK_VERSION, //!< OPTIONAL Check compatible version callback. TIFID_TOKEN_FACTORY, //!< OPTIONAL Factory to create post issuance authentication token, \sa CreateSCardTokenPtr TIFID_DATA_PROVIDER, //!< OPTIONAL File content provider (EF.DIR, EF.ATR, ...), used as primary source during creation. }; # include "actPackOn.h" typedef Blob TIPin; struct TIPinKey { TIPinKey() : pin(key) { } Blob& pin; Blob key; }; //! //! \brief Token Capability Flags. // ----------------------------------------------------------------------- union TCFlags { struct { ushort pin_padding : 1; //!< Bit 0, \par Values [\a False | \a True], Default \a False ushort pin_pce_so : 1; //!< Bit 1, \par Values [\a False | \a True], Default \a False ushort pin_pce_user : 1; //!< Bit 2, \par Values [\a False | \a True], Default \a False ushort minidriver : 1; //!< Bit 3, \par Values [\a False | \a True], Default \a False ushort minidriver_pnp : 1; //!< Bit 4, \par Values [\a False | \a True], Default \a False, \req TIData::enable::minidriver ushort biometric : 1; //!< Bit 5, \par Values [\a False | \a True], Default \a False ushort biometric_pins : 4; //!< Bit 6-9, \par Values [\a False | \c 1-10], Default \a False, \req TIData::enable::biometric ushort write_aodf : 1; //!< Bit 10, \par Values [\a False | \a True], Default \a False ushort pace : 1; //!< Bit 11, \par Values [\a False | \a True], Default \a False ushort eba : 1; //!< Bit 12, \par Values [\a False | \a True], Default \a False /* ... */ }; ushort all; }; //! //! \brief Token Content. // ----------------------------------------------------------------------- union TIContent { struct { ushort required : 1; //!< Bit 0, \par Values [\a False | \a True], Default \a False ushort ef_atr : 1; //!< Bit 1, \par Values [\a False | \a True], Default \a False ushort ef_dir : 1; //!< Bit 2, \par Values [\a False | \a True], Default \a False /* ... */ }; ushort all; }; //! //! \brief Token install flags. // ----------------------------------------------------------------------- union TIFlags { struct { ushort required : 1; //!< Bit 0, \par Values [\a False | \a True], Default \a True ushort prerequisite : 1; //!< Bit 1, \par Values [\a False | \a True], Default \a False, verify existance, abort if not exist but \a TIData::package::required ushort existing : 1; //!< Bit 2, \par Values [\a False | \a True], Default \a False, use existing package, no load, no install ushort install : 1; //!< Bit 3, \par Values [\a False | \a True], Default \a True, install card specific package ushort load : 1; //!< Bit 4, \par Values [\a False | \a True], Default \a False, load card specific package ushort load_MoC : 1; //!< Bit 5, \par Values [\a False | \a True], Default \a False, load Match-on-Card package ushort load_2048 : 1; //!< Bit 6, \par Values [\a False | \a True], Default \a False, load 2048 Bit support package ushort load_ecc : 1; //!< Bit 7, \par Values [\a False | \a True], Default \a False, load ECC support package ushort pfx : 1; //!< Bit 8, \par Values [\a False | \a True], Default \a False, contains PFX to import ushort is_virtual : 1; //!< Bit 9, \par Values [\a False | \a True], Default \a False, set \a True if AID is virtual. Requires more then 1 \a TIData where the root is not virtual! /* ... */ }; ushort all; }; //! //! \brief Token install version range. // ----------------------------------------------------------------------- union TIVersion { struct { ushort minver; //!< Lowest compatible version. ushort maxver; //!< Highest compatible version. /* ... */ }; ulong minmax; }; //! //! \brief Token Install Additional Flags. // ----------------------------------------------------------------------- enum TIAFlags { NoAuthentication = 0x0000u, VersionInvalid = -1, VersionAny = 0, }; //! //! \brief Token Install Security Flags. // ----------------------------------------------------------------------- union TISFlags { struct { ushort auth_card : 1; //!< Bit 0, default \a True ushort auth_user : 1; //!< Bit 1, default \a True ushort auth_so : 1; //!< Bit 2, default \a True ushort enable_sm : 1; //!< Bit 3, default \a False /* ... */ }; TIAFlags auth; }; //! //! \brief Token Initializer Function (TIF) - template declaration. // ----------------------------------------------------------------------- template < class ContextT, typename ArgInT, //!< Argument 0 - Input typename ArgOutT, //!< Argument 1 - Output (always byref) typename TypeTagT = TagAny > struct TIF; //! //! \brief TIF<void> specialization - base class. // ----------------------------------------------------------------------- template<class ContextT, typename ArgInT, typename ArgOutT> struct TIF<ContextT, ArgInT, ArgOutT, void> { typedef BOOLean (*FPtr)(const ContextT&, ArgInT, ArgOutT&); const FPtr function; const ContextT& context; TIF(const ContextT& owner, FPtr fptr) : function(fptr) , context(owner) { } }; //! //! \brief TIF<TagAny> specialization - default. // ----------------------------------------------------------------------- template<class ContextT, typename ArgInT, typename ArgOutT> struct TIF<ContextT, ArgInT, ArgOutT, TagAny> : TIF<ContextT, ArgInT*, ArgOutT, void> { typedef TIF<ContextT, ArgInT*, ArgOutT, void> BaseType; typedef typename BaseType::FPtr FPtr; using BaseType::function; using BaseType::context; TIF(const ContextT& owner, FPtr fptr = 0) : BaseType(owner, fptr) { } TIF(const ContextT& owner, size_t id) : BaseType(owner, owner.functions[id]) { } BOOLean operator()(ArgInT* in, ArgOutT& out) const { return 0 == function ? NotInitialized : function(context, in, out); } }; //! //! \brief TIF<TagPtr> specialization - data provider. // ----------------------------------------------------------------------- template<class ContextT, typename ArgInT, typename ArgOutT> struct TIF<ContextT, ArgInT, ArgOutT, TagPtr> : TIF<ContextT, ArgInT, ArgOutT, void> { typedef TIF<ContextT, ArgInT, ArgOutT, void> BaseType; typedef typename BaseType::FPtr FPtr; using BaseType::function; using BaseType::context; TIF(const ContextT& owner, FPtr fptr = 0) : BaseType(owner, fptr) { } TIF(const ContextT& owner, size_t id) : BaseType(owner, owner.functions[id]) { } ArgOutT operator()(ArgInT in) const { ArgOutT out; if(0 != function) function(context, in, out); return out.move(); } const TIF& operator()(ArgInT in, ArgOutT& out, move_from<ArgOutT> defout = move_empty<ArgOutT>()) const { if(0 == function || True != function(context, in, out)) out = defout; return *this; } }; //! //! \brief TIF<TagFac> specialization - token factory. // ----------------------------------------------------------------------- template<class ContextT, typename TokenT, typename SCardOST> struct TIF<ContextT, TokenT, SCardOST, TagFac> { typedef TokenT* (*FPtr)(SCardOST*, TokenT*); const FPtr function; const ContextT& context; TIF(const ContextT& owner, FPtr fptr = 0) : function(fptr) , context(owner) { } TokenT* operator()(SCardOST* os) const { return 0 != function ? function(os, 0) : 0; } }; //! //! \brief Token Initializer Data. // ----------------------------------------------------------------------- struct TIData { private: TIData(const TIData&) throw(); TIData& operator=(const TIData&) throw(); public: //! //! \brief Access condition for oncard files or objects. //! \details Provide generic access conditions for one or more //! files or objects. //! //! \example { { ac_u_so, create_ef, FID_NOT_INITIALIZED }, // 1 //! { ac_u_so, scmd_invalid, 5555 }, // 2 //! { ac_u_so, create_ef, 5555 } }; // 3 //! //! 1. On matching [0-n] id, (like \a create_ef) apply given AC. //! 2. On matching [0-1] fid, apply given AC once or never. //! 3. On matching [0-1] fid AND id (like \a create_ef) apply given //! AC once or never. // ------------------------------------------------------------------- struct AC { NamedAC ac; //!< Generic access condition. ushort id; //!< Related scmd_t<> id, \sa SCardCmd. ushort fid; //!< Unique oncard file id or lo-byte object-id. }; typedef std::vector<AC>::iterator ac_iterator; typedef std::vector<AC>::const_iterator ac_const_iterator; //! //! \brief Data object with access condition to be created on card. //! \details A generic mechanism to create binary data objects. // ------------------------------------------------------------------- struct DO { NamedAC ac; Blob tag; Blob data; }; typedef std::vector<DO>::iterator do_iterator; typedef std::vector<DO>::const_iterator do_const_iterator; //! //! \brief Retry counter values for SO-, User-, Card- and C/R-Pin. // ------------------------------------------------------------------- struct RC { byte cr; byte so; byte user; byte card; }; public: TIData(const char* profile_name_ = 0) : profile_type(PROFILE_UNKNOWN) , profile_name(profile_name_) , profile_path(0) , description(0) , generator(0) , pin_pad_byte(PIN_PAD_CHAR) , privileges(GP_PRIVILEGES_NOT_INITIALIZED) , version_check(0) , token_factory(0) , data_provider(0) , on_error(0) , next(0) { for(size_t i = 0; i < TIFID_LENGTH; ++i) functions[i] = 0; default_rc.pin.cr = 5; default_rc.pin.so = 5; default_rc.pin.user = 3; default_rc.pin.card = 10; session_rc.all = 0; session_rc.pin.user = 1; enable.all = 0; content.all = 0; flags.all = 0; flags.required = True; flags.install = True; version.minmax = VersionAny; security.auth = NoAuthentication; security.auth_so = True; security.auth_user = True; security.enable_sm = False; } bool check(byte number, bool has_parent) const { for(const TIData* data = this; number > 0 && data != 0; data = data->next, --number) has_parent = has_parent ? data->parent_id.empty() : false; return number == 0 && has_parent == false; } TIData& ref() { return *this; } const TIData& cref() const { return *this; } TIData& ref_next() { return *next; } const TIData& ref_next() const { return *next; } TIData* get_next() const { return next; } TIData& set_next(TIData& other) { other.next = next; next = &other; return other; } TIData& set_next_of(TIData& other) { other.set_next(*this); return other; } Blob atr_historical_bytes; Blob serial_number; TIPin so_pin; TIPin user_pin; TIPin card_pin; TIPinKey challenge_response; Blob pin_policy; Blob pin_last_update_utc; Blob passphrase; //!< For PFX TIData objects etc. Blob binary_data; std::vector<AC> array_of_ac; //!< Array of Access Conditions (AC) std::vector<DO> array_of_do; //!< Array of Data Objects (DO) Blob key_slot_info; //!< DER encoded key slot information for ISO7816OS tokens (STARCOS 3.x) Blob aid; Blob label; Blob df_name; //!< optional DFName. Blob parent_id; //!< optional AID of parent (server) or empty. Blob domain_id; Blob package_id; Blob module_id; ProfileType profile_type; ITokenFile* profile_path; const char* profile_name; const char* description; //!< Free to use const char* generator; //!< Name of profile generator factory or 0. byte privileges; byte pin_pad_byte; struct { Blob info; /* ... */ } biometric; union { RC pin; size_t all; } default_rc; union { RC pin; size_t all; } session_rc; TCFlags enable; TIFlags flags; TIVersion version; TIContent content; TISFlags security; private: TIData* next; typedef TIF<TIData, ISCardOS, Exception> FError; //!< Error callback. typedef TIF<TIData, ISCardOS, Blob> FSupport; //!< Support function callback. typedef TIF<TIData, ISCardOS, ushort> FCheckVersion; //!< Version check callback. typedef TIF<TIData, FIDType, Blob, TagPtr> FDataProvider; //!< File content provider. typedef TIF<TIData, SCardToken, ISCardOS, TagFac> FTokenFactory; //!< Token factory method. template<class, typename, typename, typename> friend struct TIF; protected: FError::FPtr on_error; FSupport::FPtr functions[TIFID_LENGTH]; //!< Array of support function callback. FCheckVersion::FPtr version_check; FDataProvider::FPtr data_provider; FTokenFactory::FPtr token_factory; protected: template<TIFId id, typename TagT = TagAny> struct FSelector { enum { index = id >= TIFID_BEGIN && id < TIFID_LENGTH }; typedef FSupport FType; static void set(TIData& self, TIData& other) { if(index) set(self, other.functions[id]); } static void set(TIData& self, FType::FPtr fun) { if(index) self.functions[id] = fun; } static FType get(const TIData& self) { return FType(self, id); } }; template<typename TagT> struct FSelector<TIFID_CHECK_VERSION, TagT> { enum { index = false }; typedef FCheckVersion FType; static void set(TIData& self, TIData& other) { set(self, other.version_check); } static void set(TIData& self, FType::FPtr fun) { self.version_check = fun; } static FType get(const TIData& self) { return FType(self, self.version_check); } }; template<typename TagT> struct FSelector<TIFID_TOKEN_FACTORY, TagT> { enum { index = false }; typedef FTokenFactory FType; static void set(TIData& self, TIData& other) { set(self, other.token_factory); } static void set(TIData& self, FType::FPtr fun) { self.token_factory = fun; } static FType get(const TIData& self) { return FType(self, self.token_factory); } }; template<typename TagT> struct FSelector<TIFID_DATA_PROVIDER, TagT> { enum { index = false }; typedef FDataProvider FType; static void set(TIData& self, TIData& other) { set(self, other.data_provider); } static void set(TIData& self, FType::FPtr fun) { self.data_provider = fun; } static FType get(const TIData& self) { return FType(self, self.data_provider); } }; template<typename TagT> struct FSelector<TIFID_ERROR, TagT> { enum { index = false }; typedef FError FType; static void set(TIData& self, TIData& other) { set(self, other.on_error); } static void set(TIData& self, FType::FPtr fun) { self.on_error = fun; } static FType get(const TIData& self) { return FType(self, self.on_error); } }; public: template<TIFId id> bool valid() const { if(id == TIFID_ERROR) return 0 != on_error; if(id == TIFID_CHECK_VERSION) return 0 != version_check; if(id == TIFID_TOKEN_FACTORY) return 0 != token_factory; if(id == TIFID_DATA_PROVIDER) return 0 != data_provider; { ACT_MSC_WARNING_DISABLE(6201); //!< \note Disable misleading C6201. return FSelector<id>::index ? 0 != functions[id] : false; ACT_MSC_WARNING_POP(); } } template<TIFId id> void set(TIData& other) { FSelector<id>::set(*this, other); } template<TIFId id, typename RegT> void set(const char* name) { FSelector<id>::set(*this, RegT::GetCreatePointer(name)); if(valid<id>() == false) throw InvalidParameterException(); } template<TIFId id> void set(typename FSelector<id>::FType::FPtr fun) { FSelector<id>::set(*this, fun); } template<TIFId id> typename FSelector<id>::FType get() const { return FSelector<id>::get(*this); } template<BOOLean value> struct Prerequisite { bool operator()(const TIData& data) const { return value == data.flags.prerequisite; } }; }; //! //! TITokenInfo //! ----------------------------------------------------------------------- struct TITokenInfo { TITokenInfo(size_t pin_len_max, size_t pin_len_min, size_t key_len_cr_) : serial_number_len(LEN_SERIALNO) , key_len_cr(key_len_cr_) { pin_len_max_admin = pin_len_max_so = pin_len_max_user = pin_len_max; pin_len_min_admin = pin_len_min_so = pin_len_min_user = pin_len_min; } TITokenInfo(const LengthInfo& pin_len_info, size_t key_len_cr_) : serial_number_len(LEN_SERIALNO) , key_len_cr(key_len_cr_) { pin_len_max_admin = pin_len_max_so = pin_len_max_user = pin_len_info.maxLen; pin_len_min_admin = pin_len_min_so = pin_len_min_user = pin_len_info.minLen; } size_t serial_number_len; size_t key_len_cr; size_t pin_len_max_admin; size_t pin_len_max_so; size_t pin_len_max_user; size_t pin_len_min_admin; size_t pin_len_min_so; size_t pin_len_min_user; }; # include "actPackOff.h" //! //! ITokenInitializer //! ----------------------------------------------------------------------- class ITokenInitializer : public IRefCounted { public: virtual ISCardOS* GetOS() const = 0; virtual const TITokenInfo& GetTokenInfo() const = 0; virtual const ProfileType* GetSupportedProfileList() const = 0; virtual bool SupportsProfile(ProfileType profile_type) const = 0; virtual void SetGenerator(IProfileGenerator* generator) = 0; virtual void SetObserver(ISCardCmdObserver* observer) = 0; virtual bool EraseProfile(const TIData& data, ProfileType profile_type = PROFILE_UNKNOWN) = 0; virtual bool ExistProfile(bool& is_pkcs15, bool& requires_adminpin) = 0; virtual void CreateProfile(TIData& data, ProfileType profile_type) = 0; virtual void FinalizeProfile(TIData& data) = 0; virtual void PinChangeReminder(TIData& data, bool enable) = 0; }; } // namespace act #endif // ACT_ITokenInitializer_h
32.476692
185
0.593508
[ "object", "vector" ]
da13e93022e42e9a1700ec615cd14aa577883d6a
1,982
h
C
library/Basic.h
CanftIn/CanftIn_tools
244d758f5c309314563335817fa1c1348c4f18bc
[ "MIT" ]
3
2018-05-28T08:35:41.000Z
2020-03-15T06:37:25.000Z
library/Basic.h
CanftIn/CanftIn_tools
244d758f5c309314563335817fa1c1348c4f18bc
[ "MIT" ]
null
null
null
library/Basic.h
CanftIn/CanftIn_tools
244d758f5c309314563335817fa1c1348c4f18bc
[ "MIT" ]
null
null
null
#ifndef BASIC_H_ #define BASIC_H_ namespace CAN { #ifndef NODEBUG #define CHECK_ERROR(CONDITION,DESCRIPTION) do{if(!(CONDITION))throw Error(DESCRIPTION);}while(0) #else #define CHECK_ERROR(CONDITION,DESCRIPTION) #endif #define CHECK_FAIL(DESCRIPTION) do{throw Error(DESCRIPTION);}while(0) class NoCopyable { private: NoCopyable(const NoCopyable&); NoCopyable& operator=(const NoCopyable&); public: NoCopyable(); }; class Object { public: virtual ~Object(); }; template<typename T> struct POD { static const bool Result=false; }; template<>struct POD<bool>{static const bool Result=true;}; template<>struct POD<signed __int8>{static const bool Result=true;}; template<>struct POD<unsigned __int8>{static const bool Result=true;}; template<>struct POD<signed __int16>{static const bool Result=true;}; template<>struct POD<unsigned __int16>{static const bool Result=true;}; template<>struct POD<signed __int32>{static const bool Result=true;}; template<>struct POD<unsigned __int32>{static const bool Result=true;}; template<>struct POD<signed __int64>{static const bool Result=true;}; template<>struct POD<unsigned __int64>{static const bool Result=true;}; template<>struct POD<char>{static const bool Result=true;}; template<>struct POD<wchar_t>{static const bool Result=true;}; template<typename T>struct POD<T*>{static const bool Result=true;}; template<typename T>struct POD<T&>{static const bool Result=true;}; template<typename T, typename C>struct POD<T C::*>{static const bool Result=true;}; template<typename T, signed __int64 _Size>struct POD<T[_Size]>{static const bool Result=POD<T>::Result;}; template<typename T>struct POD<const T>{static const bool Result=POD<T>::Result;}; template<typename T>struct POD<volatile T>{static const bool Result=POD<T>::Result;}; template<typename T>struct POD<const volatile T>{static const bool Result=POD<T>::Result;}; } #endif // !BASIC_H_
33.59322
106
0.735116
[ "object" ]
da14829d4a48b59aeb01740b44746d5f47bf5e39
1,323
h
C
compiler/src/CFCPyTypeMap.h
dgreatwood/lucy-clownfish
d89bbfb3dc9ec8bb7eaba9a8eb2555c7e42669c9
[ "Apache-2.0" ]
7
2015-04-04T08:35:51.000Z
2021-11-10T15:44:30.000Z
compiler/src/CFCPyTypeMap.h
dgreatwood/lucy-clownfish
d89bbfb3dc9ec8bb7eaba9a8eb2555c7e42669c9
[ "Apache-2.0" ]
24
2015-04-22T14:35:06.000Z
2016-07-22T14:05:53.000Z
compiler/src/CFCPyTypeMap.h
dgreatwood/lucy-clownfish
d89bbfb3dc9ec8bb7eaba9a8eb2555c7e42669c9
[ "Apache-2.0" ]
13
2015-04-20T17:22:24.000Z
2021-11-10T15:42:43.000Z
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef H_CFCPYTYPEMAP #define H_CFCPYTYPEMAP #ifdef __cplusplus extern "C" { #endif struct CFCType; struct CFCParcel; /** Return an expression converts from a variable of type `type` to a * PyObject*. * * @param type A Clownfish::CFC::Model::Type, which will be used to select the * mapping code. * @param cf_var The name of the variable from which we are extracting a * value. */ char* CFCPyTypeMap_c_to_py(struct CFCType *type, const char *cf_var); #ifdef __cplusplus } #endif #endif /* H_CFCPYTYPEMAP */
30.068182
78
0.746788
[ "model" ]
da1caf49ddbecffa72c86092ff92178f64043a87
840
h
C
src/core/event/event.h
minalear/HardPython
786340ca6135751e99ab84f4efc1516fabdfa1da
[ "MIT" ]
null
null
null
src/core/event/event.h
minalear/HardPython
786340ca6135751e99ab84f4efc1516fabdfa1da
[ "MIT" ]
null
null
null
src/core/event/event.h
minalear/HardPython
786340ca6135751e99ab84f4efc1516fabdfa1da
[ "MIT" ]
1
2018-10-01T18:08:25.000Z
2018-10-01T18:08:25.000Z
#ifndef MINALEAR_EVENT_H #define MINALEAR_EVENT_H #include <functional> #include <vector> #include <memory> #include "glm/glm.hpp" #include "SDL2/SDL_scancode.h" namespace minalear { enum class EventType { WindowResize, KeyDown, KeyUp, MouseMove, MouseButtonDown, MouseButtonUp, Tick }; struct TickEvent { }; // KeyDown/KeyUp struct KeyboardEvent { SDL_Scancode scancode; bool repeat; }; struct Event { EventType type; Event(EventType type) : type(type) { } union { TickEvent tick; KeyboardEvent key; }; }; using EventFn = std::function<void(const Event&)>; class EventDispatcher { private: std::vector<EventFn> observers; public: void Subscribe(const EventFn& callback); void Post(const Event& event) const; }; extern EventDispatcher g_EventHandler; } #endif
15.849057
51
0.694048
[ "vector" ]
da1d3076497e0bf2f5004123e53effd101a8ea9d
2,683
h
C
Windows/FireflyDevice/FDExecutor.h
mpkasp/firefly-ice-api
5e43cb56eb3be4391fd55bdc75d5d0db40249519
[ "Apache-2.0" ]
null
null
null
Windows/FireflyDevice/FDExecutor.h
mpkasp/firefly-ice-api
5e43cb56eb3be4391fd55bdc75d5d0db40249519
[ "Apache-2.0" ]
null
null
null
Windows/FireflyDevice/FDExecutor.h
mpkasp/firefly-ice-api
5e43cb56eb3be4391fd55bdc75d5d0db40249519
[ "Apache-2.0" ]
null
null
null
// // FDExecutor.h // FireflyDevice // // Created by Denis Bohm on 9/14/13. // Copyright (c) 2013-2014 Firefly Design LLC / Denis Bohm. All rights reserved. // #ifndef FDEXECUTOR_H #define FDEXECUTOR_H #include "FDCommon.h" #include "FDError.h" #include <exception> #include <list> #include <memory> #include <vector> namespace FireflyDesign { class FDExecutor; class FDFireflyDeviceLog; class FDTimer; class FDTimerFactory; #define FDExecutorErrorDomain "com.fireflydesign.device.FDExecutor" class FDExecutorTask { public: FDExecutorTask(); virtual ~FDExecutorTask(); typedef double time_interval_type; typedef double date_type; time_interval_type timeout; int priority; bool isSuspended; date_type appointment; virtual void executorTaskStarted(FDExecutor *executor) = 0; virtual void executorTaskSuspended(FDExecutor *executor) = 0; virtual void executorTaskResumed(FDExecutor *executor) = 0; virtual void executorTaskCompleted(FDExecutor *executor) = 0; virtual void executorTaskFailed(FDExecutor *executor, std::shared_ptr<FDError> error) = 0; }; enum FDExecutorError { FDExecutorErrorCodeAbort, FDExecutorErrorCodeCancel, FDExecutorErrorCodeTimeout, }; class FDExecutor { public: typedef double time_interval_type; typedef double date_type; FDExecutor(std::shared_ptr<FDTimerFactory> timerFactory); ~FDExecutor(); std::shared_ptr<FDFireflyDeviceLog> log; time_interval_type timeoutCheckInterval; bool getRun(); void setRun(bool run); void execute(std::shared_ptr<FDExecutorTask> task); void cancel(std::shared_ptr<FDExecutorTask> task); std::vector<std::shared_ptr<FDExecutorTask>> allTasks(); bool hasTasks(); void feedWatchdog(std::shared_ptr<FDExecutorTask> task); void complete(std::shared_ptr<FDExecutorTask> task); void fail(std::shared_ptr<FDExecutorTask> task, std::shared_ptr<FDError> error); private: std::list<std::shared_ptr<FDExecutorTask>> tasks; std::list<std::shared_ptr<FDExecutorTask>> appointmentTasks; std::shared_ptr<FDExecutorTask> currentTask; std::shared_ptr<FDTimerFactory> _timerFactory; bool _run; date_type _currentFeedTime; std::shared_ptr<FDTimer> _timer; void cancelTimer(); void start(); void abortTask(std::shared_ptr<FDExecutorTask> task); void abortTasks(std::list<std::shared_ptr<FDExecutorTask>>); void stop(); void sortTasksByPriority(); void checkAppointments(); void addTask(std::shared_ptr<FDExecutorTask> task); void checkTimeout(); void check(); void taskException(std::exception e); void schedule(); void over(std::shared_ptr<FDExecutorTask> task, std::shared_ptr<FDError> error); }; } #endif
25.311321
92
0.758107
[ "vector" ]
da1ea28f602886304ed1daf5420d35d3c51189bf
18,720
h
C
mc/model/com.mentor.nucleus.bp.core/src416/c/t.sys_user_co.h
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
1
2018-01-24T16:28:01.000Z
2018-01-24T16:28:01.000Z
mc/model/com.mentor.nucleus.bp.core/src418/c/t.sys_user_co.h
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
null
null
null
mc/model/com.mentor.nucleus.bp.core/src418/c/t.sys_user_co.h
NDGuthrie/bposs
2c47abf74a3e6fadb174b08e57aa66a209400606
[ "Apache-2.0" ]
null
null
null
T_b("/*----------------------------------------------------------------------------"); T_b("\n"); T_b(" "); T_b("* File: "); T_b(te_file->callout); T_b("."); T_b(te_file->hdr_file_ext); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* Description:"); T_b("\n"); T_b(" "); T_b("* Function declarations for user supplied (non-translated) call out entry"); T_b("\n"); T_b(" "); T_b("* points in the generated application."); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_copyright->body); T_b("\n"); T_b(" "); T_b("*--------------------------------------------------------------------------*/"); T_b("\n"); T_b("#ifndef "); T_b(te_prefix->define_usw); T_b(te_file->callout); T_b("_"); T_b(te_file->hdr_file_ext); T_b("\n"); T_b("#define "); T_b(te_prefix->define_usw); T_b(te_file->callout); T_b("_"); T_b(te_file->hdr_file_ext); T_b("\n"); T_b(te_target->c2cplusplus_linkage_begin); T_b("\n"); if ( ( te_sys->AUTOSAR ) || ( te_sys->VFB ) ) { T_b("/*"); T_b("\n"); T_b(" "); T_b("* Default to enabling the AUTOSAR-specific code. Turn it off by commenting"); T_b("\n"); T_b(" "); T_b("* out the following directive."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("#define "); T_b(te_thread->AUTOSAR_enabled); T_b(" 1"); T_b("\n"); } T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->initialization); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked at the immediate beginning of application"); T_b("\n"); T_b(" "); T_b("* initialization. It is the very first function to be executed at system"); T_b("\n"); T_b(" "); T_b("* startup."); T_b("\n"); T_b(" "); T_b("* User supplied implementation of this function should be restricted to"); T_b("\n"); T_b(" "); T_b("* things like memory initialization, early hardware duties, etc."); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->initialization); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout."); T_b("\n"); if ( 0==strcmp("C",te_target->language) ) { T_b(" "); T_b("(activated by default... Uncomment to deactivate.)"); T_b("\n"); T_b("#define "); T_b(te_callout->initialization); T_b("()"); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); } else { T_b(" "); T_b("*/"); T_b("\n"); T_b("#define "); T_b(te_callout->initialization); T_b("()"); T_b("\n"); } T_b("#ifndef "); T_b(te_callout->initialization); T_b("\n"); T_b("#define "); T_b(te_callout->initialization); T_b("() "); T_b(te_callout->initialization); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->pre_xtUML_initialization); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked immediately prior to executing any xtUML"); T_b("\n"); T_b(" "); T_b("* initialization functions."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->pre_xtUML_initialization); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->pre_xtUML_initialization); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->pre_xtUML_initialization); T_b("\n"); T_b("#define "); T_b(te_callout->pre_xtUML_initialization); T_b("() "); T_b(te_callout->pre_xtUML_initialization); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->post_xtUML_initialization); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked immediately after executing any xtUML"); T_b("\n"); T_b(" "); T_b("* initialization functions."); T_b("\n"); T_b(" "); T_b("* When this callout function returns, the system dispatcher will allow the"); T_b("\n"); T_b(" "); T_b("* xtUML application analysis state models to start consuming events."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->post_xtUML_initialization); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->post_xtUML_initialization); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->post_xtUML_initialization); T_b("\n"); T_b("#define "); T_b(te_callout->post_xtUML_initialization); T_b("() "); T_b(te_callout->post_xtUML_initialization); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->background_processing); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked once during each loop execution of the system"); T_b("\n"); T_b(" "); T_b("* dispather."); T_b("\n"); T_b(" "); T_b("* It is invoked at the 'top' of the system dispatcher loop, immediately"); T_b("\n"); T_b(" "); T_b("* prior to dispatching any xtUML application analysis events."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->background_processing); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout."); T_b("\n"); if ( 0==strcmp("C",te_target->language) ) { T_b(" "); T_b("(activated by default... Uncomment to deactivate.)"); T_b("\n"); T_b("#define "); T_b(te_callout->background_processing); T_b("()"); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); } else { T_b(" "); T_b("*/"); T_b("\n"); T_b("#define "); T_b(te_callout->background_processing); T_b("()"); T_b("\n"); } T_b("#ifndef "); T_b(te_callout->background_processing); T_b("\n"); T_b("#define "); T_b(te_callout->background_processing); T_b("() "); T_b(te_callout->background_processing); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->pre_shutdown); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked at termination of the system dispatcher, but"); T_b("\n"); T_b(" "); T_b("* prior to performing any xtUML application analysis shutdown sequencing."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->pre_shutdown); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->pre_shutdown); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->pre_shutdown); T_b("\n"); T_b("#define "); T_b(te_callout->pre_shutdown); T_b("() "); T_b(te_callout->pre_shutdown); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->post_shutdown); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked immediately before application exit."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->post_shutdown); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->post_shutdown); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->post_shutdown); T_b("\n"); T_b("#define "); T_b(te_callout->post_shutdown); T_b("() "); T_b(te_callout->post_shutdown); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->event_cant_happen); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked any time that an event is received that"); T_b("\n"); T_b(" "); T_b("* results in a \"cant happen\" transition."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->event_cant_happen); T_b("f( const "); T_b(te_typemap->state_number_name); T_b(","); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->state_number_name); T_b(","); T_b("\n"); T_b(" "); T_b("const "); T_b(te_typemap->event_number_name); T_b(" );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->event_cant_happen); T_b("( s1, s2, e )"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->event_cant_happen); T_b("\n"); T_b("#define "); T_b(te_callout->event_cant_happen); T_b("( s1, s2, e ) "); T_b(te_callout->event_cant_happen); T_b("f( s1, s2, e )"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->event_no_instance); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when we failed to validate the instance"); T_b("\n"); T_b(" "); T_b("* to which an event was directed. This can happen in normal operation"); T_b("\n"); T_b(" "); T_b("* when the instance was deleted while the event was in flight (analysis"); T_b("\n"); T_b(" "); T_b("* error)."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->event_no_instance); T_b("f( const "); T_b(te_typemap->event_number_name); T_b(" );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->event_no_instance); T_b("( e )"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->event_no_instance); T_b("\n"); T_b("#define "); T_b(te_callout->event_no_instance); T_b("( e ) "); T_b(te_callout->event_no_instance); T_b("f( e )"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->event_free_list_empty); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when an attempt is made to allocate an"); T_b("\n"); T_b(" "); T_b("* event, but there are no more left."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->event_free_list_empty); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->event_free_list_empty); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->event_free_list_empty); T_b("\n"); T_b("#define "); T_b(te_callout->event_free_list_empty); T_b("() "); T_b(te_callout->event_free_list_empty); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->empty_handle_detected); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when an attempt is made to use an instance"); T_b("\n"); T_b(" "); T_b("* reference variable (handle) that is null (empty)."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->empty_handle_detected); T_b("f( c_t *, c_t * );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->empty_handle_detected); T_b("( s1, s2 )"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->empty_handle_detected); T_b("\n"); T_b("#define "); T_b(te_callout->empty_handle_detected); T_b("( s1, s2 ) "); T_b(te_callout->empty_handle_detected); T_b("f( (c_t *) s1, (c_t *) s2 )"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->object_pool_empty); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when an attempt is made to create an"); T_b("\n"); T_b(" "); T_b("* instance of an object, but there are no instances available."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->object_pool_empty); T_b("f( const "); T_b(te_typemap->domain_number_name); T_b(", const "); T_b(te_typemap->object_number_name); T_b(" );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout."); T_b("\n"); T_b(" "); T_b("(activated by default... Uncomment to deactivate.)"); T_b("\n"); T_b("#define "); T_b(te_callout->object_pool_empty); T_b("( s1, s2 )"); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->object_pool_empty); T_b("\n"); T_b("#define "); T_b(te_callout->object_pool_empty); T_b("( s1, s2 ) "); T_b(te_callout->object_pool_empty); T_b("f( s1, s2 )"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->node_list_empty); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when an attempt is made to allocate a"); T_b("\n"); T_b(" "); T_b("* node, but there are no more left."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->node_list_empty); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->node_list_empty); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->node_list_empty); T_b("\n"); T_b("#define "); T_b(te_callout->node_list_empty); T_b("() "); T_b(te_callout->node_list_empty); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->interleaved_bridge_overflow); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when an attempt is made to post too many"); T_b("\n"); T_b(" "); T_b("* interleaved bridges. The depth of this list is defined by"); T_b("\n"); T_b(" "); T_b("* SYS_MAX_INTERLEAVED_BRIDGES (unless changed in the archetype)."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->interleaved_bridge_overflow); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->interleaved_bridge_overflow); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->interleaved_bridge_overflow); T_b("\n"); T_b("#define "); T_b(te_callout->interleaved_bridge_overflow); T_b("() "); T_b(te_callout->interleaved_bridge_overflow); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->self_event_queue_empty); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when the events to self queue is"); T_b("\n"); T_b(" "); T_b("* interrogated and found to be empty."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->self_event_queue_empty); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->self_event_queue_empty); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->self_event_queue_empty); T_b("\n"); T_b("#define "); T_b(te_callout->self_event_queue_empty); T_b("() "); T_b(te_callout->self_event_queue_empty); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->non_self_event_queue_empty); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when the events to instance queue is"); T_b("\n"); T_b(" "); T_b("* interrogated and found to be empty."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->non_self_event_queue_empty); T_b("f( void );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->non_self_event_queue_empty); T_b("()"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->non_self_event_queue_empty); T_b("\n"); T_b("#define "); T_b(te_callout->non_self_event_queue_empty); T_b("() "); T_b(te_callout->non_self_event_queue_empty); T_b("f()"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b("/*"); T_b("\n"); T_b(" "); T_b("* "); T_b(te_callout->persistence_error); T_b("\n"); T_b(" "); T_b("*"); T_b("\n"); T_b(" "); T_b("* This function is invoked when trouble is detected reading from"); T_b("\n"); T_b(" "); T_b("* or writing to persistent storage."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("void "); T_b(te_callout->persistence_error); T_b("f( i_t );"); T_b("\n"); T_b("/* The following empty definition renders the callout hook invisible."); T_b("\n"); T_b(" "); T_b("Delete or comment out the following define to activate the in line"); T_b("\n"); T_b(" "); T_b("hook for this callout. */"); T_b("\n"); T_b("#define "); T_b(te_callout->persistence_error); T_b("( i1 )"); T_b("\n"); T_b("#ifndef "); T_b(te_callout->persistence_error); T_b("\n"); T_b("#define "); T_b(te_callout->persistence_error); T_b("( i1 ) "); T_b(te_callout->persistence_error); T_b("f( i1 )"); T_b("\n"); T_b("#endif"); T_b("\n"); T_b(te_target->c2cplusplus_linkage_end); T_b("\n"); T_b("#endif /* "); T_b(te_prefix->define_usw); T_b(te_file->callout); T_b("_"); T_b(te_file->hdr_file_ext); T_b(" */"); T_b("\n");
21.345496
86
0.59594
[ "object" ]
da2599a5a5d6d2f878f02ae3a53b5baced5081dd
12,222
h
C
src/mirheo/core/celllist.h
noabauma/Mirheo
bf7979bfbbf402d33c26ac5dc879f880e78e7017
[ "MIT" ]
null
null
null
src/mirheo/core/celllist.h
noabauma/Mirheo
bf7979bfbbf402d33c26ac5dc879f880e78e7017
[ "MIT" ]
null
null
null
src/mirheo/core/celllist.h
noabauma/Mirheo
bf7979bfbbf402d33c26ac5dc879f880e78e7017
[ "MIT" ]
null
null
null
// Copyright 2020 ETH Zurich. All Rights Reserved. #pragma once #include <mirheo/core/containers.h> #include <mirheo/core/datatypes.h> #include <mirheo/core/logger.h> #include <mirheo/core/pvs/particle_vector.h> #include <mirheo/core/pvs/views/pv.h> #include <mirheo/core/utils/cuda_common.h> namespace mirheo { /// describes if the position should be projected inside the /// local subdomain or not enum class CellListsProjection { Clamp, NoClamp }; /** A device-compatible structure that represents the cell-lists structure. Contains geometric info (number of cells, cell sizes) and associated particles info (number of particles per cell and cell-starts). */ class CellListInfo { public: /** \brief Construct a CellListInfo object \param [in] h The size of a single cell along each dimension \param [in] localDomainSize Size of the local domain This will create a cell-lists structure with cell sizes which are larger or equal to \p h, such that the number of cells fit exactly inside the local domain size. */ CellListInfo(real3 h, real3 localDomainSize); /** \brief Construct a CellListInfo object \param [in] rc The minimum size of a single cell along every dimension \param [in] localDomainSize Size of the local domain This will create a cell-lists structure with cell sizes which are larger or equal to \p rc, such that the number of cells fit exactly inside the local domain size. */ CellListInfo(real rc, real3 localDomainSize); #ifdef __CUDACC__ /** \brief map 3D cell indices to linear cell index. \param [in] ix Cell index in the x direction \param [in] iy Cell index in the y direction \param [in] iz Cell index in the z direction \return Linear cell index */ __device__ __host__ inline int encode(int ix, int iy, int iz) const { return (iz*ncells.y + iy)*ncells.x + ix; } /** \brief map linear cell index to 3D cell indices. \param [in] cid Linear cell index \param [out] ix Cell index in the x direction \param [out] iy Cell index in the y direction \param [out] iz Cell index in the z direction */ __device__ __host__ inline void decode(int cid, int& ix, int& iy, int& iz) const { ix = cid % ncells.x; iy = (cid / ncells.x) % ncells.y; iz = cid / (ncells.x * ncells.y); } /// see encode() __device__ __host__ inline int encode(int3 cid3) const { return encode(cid3.x, cid3.y, cid3.z); } /// see decode() __device__ __host__ inline int3 decode(int cid) const { int3 res; decode(cid, res.x, res.y, res.z); return res; } /** \brief Map from position to cell indices \tparam Projection if the cell indices must be clamped or not \param [in] x The position in **local coordinates** \return cell indices */ template<CellListsProjection Projection = CellListsProjection::Clamp> __device__ __host__ inline int3 getCellIdAlongAxes(const real3 x) const { const int3 v = make_int3( math::floor(invh_ * (x + 0.5_r * localDomainSize)) ); if (Projection == CellListsProjection::Clamp) return math::min( ncells - 1, math::max(make_int3(0), v) ); else return v; } /** \brief Map from position to linear indices \tparam Projection if the cell indices must be clamped or not \tparam T The vector type that represents the position \param [in] x The position in **local coordinates** \return linear cell index \rst .. warning:: If The projection is set to CellListsProjection::NoClamp, this function will return -1 if the particle is outside the subdomain. \endrst */ template<CellListsProjection Projection = CellListsProjection::Clamp, typename T> __device__ __host__ inline int getCellId(const T x) const { const int3 cid3 = getCellIdAlongAxes<Projection>(make_real3(x)); if (Projection == CellListsProjection::NoClamp) { if (cid3.x < 0 || cid3.x >= ncells.x || cid3.y < 0 || cid3.y >= ncells.y || cid3.z < 0 || cid3.z >= ncells.z) return -1; } return encode(cid3); } #endif public: int3 ncells; ///< Number of cells along each direction in the local domain int totcells; ///< total number of cells in the local domain real3 localDomainSize; ///< dimensions of the subdomain real rc; ///< cutoff radius real3 h; ///< dimensions of the cells along each direction int *cellSizes; ///< number of particles contained in each cell int *cellStarts; ///< exclusive prefix sum of cellSizes /// used to reorder particles when building the cell lists: /// \c order[pid] is the destination index of the particle with index \c pid before reordering int *order; private: real3 invh_; ///< 1 / h }; /** \brief Contains the cell-list data for a given ParticleVector. As opposed to the PrimaryCellList class, it contains a **copy** of the attached ParticleVector. This means that the original ParticleVector data will not be reorder but rather copied into this container. This is useful when several CellList object can be attached to the same ParticleVector or if the ParticleVector must not be reordered such as e.g. for ObjectVector objects. */ class CellList : public CellListInfo { public: /** Construct a CellList object \param [in] pv The ParticleVector to attach. \param [in] rc The maximum cut-off radius that can be used with that cell list. \param [in] localDomainSize The size of the local subdomain */ CellList(ParticleVector *pv, real rc, real3 localDomainSize); /** Construct a CellList object \param [in] pv The ParticleVector to attach. \param [in] resolution The number of cells along each dimension \param [in] localDomainSize The size of the local subdomain */ CellList(ParticleVector *pv, int3 resolution, real3 localDomainSize); virtual ~CellList(); /// \return the device-compatible handler CellListInfo cellInfo(); /** \brief construct the cell-list associated with the attached ParticleVector \param [in] stream The stream used to execute the process */ virtual void build(cudaStream_t stream); /** \brief Accumulate the channels from the data contained inside the cell-list container to the attached ParticleVector. \param [in] channelNames List that contains the names of all the channels to accumulate \param [in] stream Execution stream */ virtual void accumulateChannels(const std::vector<std::string>& channelNames, cudaStream_t stream); /** \brief Copy the channels from the attached ParticleVector to the cell-lists data. \param [in] channelNames List that contains the names of all the channels to copy \param [in] stream Execution stream */ virtual void gatherChannels(const std::vector<std::string>& channelNames, cudaStream_t stream); /** \brief Clear channels contained inside the cell-list \param [in] channelNames List that contains the names of all the channels to clear \param [in] stream Execution stream */ void clearChannels(const std::vector<std::string>& channelNames, cudaStream_t stream); /** \brief Create a view that points to the data contained in the cell-lists \tparam ViewType The type of the view to create \return View that points to the cell-lists data */ template <typename ViewType> ViewType getView() const { return ViewType(pv_, localPV_); } /** \brief Add an extra channel to the cell-list. \tparam T The type of data to add \param [in] name Name of the channel */ template <typename T> void requireExtraDataPerParticle(const std::string& name) { particlesDataContainer_->dataPerParticle.createData<T>(name); } /// \return The LocalParticleVector that contains the data in the cell-list LocalParticleVector* getLocalParticleVector(); protected: /// initialize internal buffers; used in the constructor void _initialize(); /// \return \c true if needs to build the cell-lists bool _checkNeedBuild() const; /// add needed channels to the internal data container so it matches /// the attached ParricleVector void _updateExtraDataChannels(cudaStream_t stream); /// Compute the number of particles per cell void _computeCellSizes(cudaStream_t stream); /// Compute the cell starts; requires cell sizes void _computeCellStarts(cudaStream_t stream); /// reorder the positions and create \c order. requires cell starts void _reorderPositionsAndCreateMap(cudaStream_t stream); /// reorder the rest of the data that is persistent; requires \c order void _reorderPersistentData(cudaStream_t stream); /// build cell lists (uses the above functions) void _build(cudaStream_t stream); /// see accumulateChannels(); for one channel. void _accumulateExtraData(const std::string& channelName, cudaStream_t stream); /** reorder a given channel according to the internal map \param [in] channelName The name of the channel to reorder \param [in,out] channelDesc the channel data \param [in] stream The execution stream */ void _reorderExtraDataEntry(const std::string& channelName, const DataManager::ChannelDescription *channelDesc, cudaStream_t stream); /** \return a name specific to that cell list, its attached ParticleVector and cut-off radius; useful for logging */ virtual std::string _makeName() const; protected: int changedStamp_{-1}; ///< Helper to keep track of the validity of the cell-list DeviceBuffer<char> scanBuffer; ///< work space to perform the prefix sum DeviceBuffer<int> cellStarts; ///< Container of the cell starts DeviceBuffer<int> cellSizes; ///< Container of the cell sizes DeviceBuffer<int> order; ///< container of the reorder map std::unique_ptr<LocalParticleVector> particlesDataContainer_; ///< local data that holds reordered copy of the attached particle data LocalParticleVector *localPV_; ///< will point to particlesDataContainer or pv->local() if Primary ParticleVector *pv_; ///< The attached ParticleVector }; /** \brief Contains the cell-list map for a given ParticleVector. As opposed to the CellList class, the data is stored only in the ParticleVector. This means that the original ParticleVector data will be reorder according to this cell-list. This allows to save memory and avoid extra copies. On the other hand, this class must not be used with ObjectVector objects. */ class PrimaryCellList : public CellList { public: /** Construct a PrimaryCellList object \param [in] pv The ParticleVector to attach. \param [in] rc The maximum cut-off radius that can be used with that cell list. \param [in] localDomainSize The size of the local subdomain */ PrimaryCellList(ParticleVector *pv, real rc, real3 localDomainSize); /** Construct a PrimaryCellList object \param [in] pv The ParticleVector to attach. \param [in] resolution The number of cells along each dimension \param [in] localDomainSize The size of the local subdomain */ PrimaryCellList(ParticleVector *pv, int3 resolution, real3 localDomainSize); ~PrimaryCellList(); void build(cudaStream_t stream); void accumulateChannels(const std::vector<std::string>& channelNames, cudaStream_t stream) override; void gatherChannels(const std::vector<std::string>& channelNames, cudaStream_t stream) override; protected: /// swap data between the internal container with the attached particle data void _swapPersistentExtraData(); std::string _makeName() const override; }; } // namespace mirheo
38.555205
137
0.682458
[ "object", "vector", "3d" ]
da2a0579b14aac04341b6d2989edf1f976488c0f
507
h
C
util/headers/file_encoder.h
turing228/huffman
78222ad60ecd7616dea5dd4ecd120438ce606a57
[ "MIT" ]
1
2019-10-23T19:13:07.000Z
2019-10-23T19:13:07.000Z
util/headers/file_encoder.h
turing228/huffman
78222ad60ecd7616dea5dd4ecd120438ce606a57
[ "MIT" ]
null
null
null
util/headers/file_encoder.h
turing228/huffman
78222ad60ecd7616dea5dd4ecd120438ce606a57
[ "MIT" ]
null
null
null
// // Created by jesus on 22.06.18. // #ifndef HUFFMAN_FILE_ENCODER_H #define HUFFMAN_FILE_ENCODER_H #include <string> #include <fstream> #include <vector> #include "../lib/headers/consts.h" #include "../lib/headers/encode.h" void encode(std::string, std::string); void write(encoder &, std::vector<unsigned char> &, std::ifstream &, std::ofstream &); void writeSmall(encoder &, std::ofstream &); void fillFreq(encoder &, std::vector<unsigned char> &, std::ifstream &); #endif //HUFFMAN_FILE_ENCODER_H
24.142857
86
0.715976
[ "vector" ]
da39107d64d26a0672c2924ede88d8773d4f4de0
804
h
C
include/apsis/engine/scene.h
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
2
2015-11-05T03:47:29.000Z
2020-01-24T18:48:09.000Z
include/apsis/engine/scene.h
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
null
null
null
include/apsis/engine/scene.h
wilkie/apsis
9e6a37ad9dfc8931b25b9429d7e4a770b4e760bf
[ "WTFPL" ]
null
null
null
#ifndef APSIS_ENGINE_SCENE_H #define APSIS_ENGINE_SCENE_H #include "apsis/world/scene.h" #include <vector> namespace Apsis { namespace Engine { /* * This class manages the current scene. */ class Scene { public: /* * Constructs a scene engine to hold and manage the scene. */ static Apsis::Engine::Scene& basic(); /* * Sets the scene. */ void scene(Apsis::World::Scene& scene); /* * Returns the current scene. */ Apsis::World::Scene& scene(); const Apsis::World::Scene& scene() const; private: Scene(); Apsis::World::Scene* _scene; // Keeps track of Scene engines system-wide. static std::vector<Apsis::Engine::Scene*> _scene_engines; }; } } #endif
18.697674
65
0.579602
[ "vector" ]
da3aa3abdbb3a96a9808eaa0790339a326cd1b9b
109,993
c
C
ubuntu20/projects/libRadtran-2.0.4/libsrc_c/netCDF_functions.c
AmberCrafter/docker-compose_libRadtran
0182f991db6a13e0cacb3bf9f43809e6850593e4
[ "MIT" ]
null
null
null
ubuntu20/projects/libRadtran-2.0.4/libsrc_c/netCDF_functions.c
AmberCrafter/docker-compose_libRadtran
0182f991db6a13e0cacb3bf9f43809e6850593e4
[ "MIT" ]
null
null
null
ubuntu20/projects/libRadtran-2.0.4/libsrc_c/netCDF_functions.c
AmberCrafter/docker-compose_libRadtran
0182f991db6a13e0cacb3bf9f43809e6850593e4
[ "MIT" ]
null
null
null
/*-------------------------------------------------------------------- * $Id$ * * This file is part of libRadtran. * Copyright (c) 1997-2012 by Arve Kylling, Bernhard Mayer, * Claudia Emde, Robert Buras * * ######### Contact info: http://www.libradtran.org ######### * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. *--------------------------------------------------------------------*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #if HAVE_NETCDF4 #include <netcdf.h> #endif #include "netCDF_functions.h" #define ERRCODE 2 #define ERR(e) \ { \ printf ("Error: %s\n", nc_strerror (e)); \ exit (ERRCODE); \ } /***********************************************************************************/ /* Function: write_netCDF_1D_float */ /* Description: */ /* Write a 1D float (like latitude array), according attributes and dimension */ /* (number of array entries) to an opened netCDF result file. */ /* The function checks, if this variables already */ /* exists in the netCDF header. If not, it is created. */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* int *id_data id number of the data (is created, of data is new) */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* float *data the data set itself */ /* char *dim_name name of the according dimension */ /* (in general the same as data_name), e.g. "lat" */ /* int id_dim id number of the dimension */ /* int n number of array entries (dimension size) */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int write_netCDF_1D_float (int ncid, char* filename, char* data_name, int* id_data, char* long_name, char* units, float* data, char* dim_name, int* id_dim, int n) { #if HAVE_NETCDF4 int status = NC_NOERR; size_t iv = 0; char function_name[] = "write_netCDF_1D_float"; char file_name[] = "netCDF_functions.c"; /* get variable id for data_name */ status = nc_inq_varid (ncid, data_name, id_data); if (status != NC_NOERR) { /* variable does not exist, create it! */ status = nc_redef (ncid); /* put in define mode */ if (status != NC_NOERR) { fprintf (stderr, "Error %d putting netCDF file %s into define mode, in %s (%s)\n", status, filename, function_name, file_name); return status; } /* create dimension */ status = nc_def_dim (ncid, dim_name, n, id_dim); if (status != NC_NOERR) { fprintf (stderr, "Error %d defining data '%s' in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_def_var (ncid, data_name, NC_FLOAT, 1, id_dim, id_data); if (status != NC_NOERR) { fprintf (stderr, "Error %d defining data %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_enddef (ncid); /* end define mode */ if (status != NC_NOERR) { fprintf (stderr, "Error %d leaving the define mode for %s, in %s (%s) \n", status, filename, function_name, file_name); return status; } /* write data into the variable */ for (iv = 0; iv < n; iv++) { /* WRITE ONE VARIABLE */ status = nc_put_var1_float (ncid, (*id_data), &iv, &(data[iv])); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } } } else { /* yes, check if they are identical */ } return status; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: write_netCDF_3D_float */ /* Description: */ /* Write one result (float) (time, lat, lon) into a 3D array */ /* The function checks, if this data set already exits in the netCDF header. */ /* If not it will be created with according attributes, units ... and */ /* initialiesed to 0. */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* float data data to write */ /* int *id_dim_array array of dimension id numbers */ /* size_t *index_3D where to write the data */ /* int ndim number of dimenision (here always 3) */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Jan 2008 U. Hamann Created */ /* */ /***********************************************************************************/ int write_netCDF_3D_float (int ncid, char* filename, char* data_name, char* long_name, char* units, float data, int* id_dim_array, size_t* index, int ndim) { #if HAVE_NETCDF4 int status = NC_NOERR; int id_data = NOT_DEFINED_INTEGER; char function_name[] = "write_netCDF_3D_float"; char file_name[] = "netCDF_functions.c"; status = create_float_variable_or_get_id (ncid, filename, data_name, &id_data, ndim, id_dim_array, long_name, units); if (status != NC_NOERR) { fprintf (stderr, "Error %d creating float variable %s in netCDF file %s, in %s (%s)\n", status, long_name, filename, function_name, file_name); return status; } /* WRITE ONE VARIABLE */ status = nc_put_var1_float (ncid, id_data, index, &(data)); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } return status; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: write_netCDF_4D_float */ /* Description: */ /* Write one column of results (mostly z-column) into a 4D array */ /* (time, z, lat, lon). The function checks, if this data set already exits in */ /* the netCDF header. If not it will be created with according attributes, */ /* units ... */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* int *id_data id number of the data (is created, of data is new) */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* float *data the data set itself */ /* int *id_dim_array array of dimension id numbers */ /* size_t *index specifies the position, where to write the entry */ /* into the 4D file */ /* int ndim number of dimenision (here always 4) */ /* size_t *n_end size of the dimensions */ /* int *zout_index index of the zout levels */ /* (nessesary, as some zout-levels, which are below the */ /* ground altitude are obmitted) */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int write_netCDF_4D_float (int ncid, char* filename, char* data_name, char* long_name, char* units, float* data, int* id_dim_array, size_t* index, int ndim, size_t* n_end, int* zout_index, int* simulation_done) { #if HAVE_NETCDF4 int status = NC_NOERR; int id_data = NOT_DEFINED_INTEGER; size_t lev = 0; char function_name[] = "write_netCDF_4D_float"; char file_name[] = "netCDF_functions.c"; /* check if this result is valid */ for (lev = 0; lev < n_end[POSITION_ZOUT_4D]; lev++) { /* replace infinite numbers with NaN (Not a number) */ if (isinf (data[lev])) data[lev] = 0.0 / 0.0; /* check for NaN (Not a Number) */ if (isnan (data[lev])) { (*simulation_done) = FALSE; fprintf (stderr, " *** Warning, unresonable result for '%s' (lev=%d)\n", long_name, (int)lev); } } status = create_float_variable_or_get_id (ncid, filename, data_name, &id_data, ndim, id_dim_array, long_name, units); if (status != NC_NOERR) { fprintf (stderr, "Error %d creating float variable %s in netCDF file %s, in %s (%s)\n", status, long_name, filename, function_name, file_name); return status; } /* write data into the variable */ for (lev = 0; lev < n_end[POSITION_ZOUT_4D]; lev++) { index[POSITION_ZOUT_4D] = zout_index[lev]; /* WRITE ONE VARIABLE */ status = nc_put_var1_float (ncid, id_data, index, &(data[lev])); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } } return status; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: write_netCDF_5D_float */ /* Description: */ /* Write one column of results (mostly z-column) into a 5D array */ /* (time, z, sza, lat, lon). The function checks, if this data set already exits */ /* in the netCDF header. If not it will be created with according attributes, */ /* units ... */ /* If result is not valid (infinity or Not-a-number) simulation done will be */ /* set to FALSE == not done. infinity is replaced by Not-a-number. */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* int *id_data id number of the data (is created, of data is new) */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* float *data the data set itself */ /* int *id_dim_array array of dimension id numbers */ /* size_t *index specifies the position, where to write the entry */ /* into the 4D file */ /* int ndim number of dimenision (here always 5) */ /* size_t *n_end size of the dimensions */ /* int *zout_index index of the zout levels */ /* (nessesary, as some zout-levels, which are below the */ /* ground altitude are obmitted) */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int write_netCDF_5D_float (int ncid, char* filename, char* data_name, char* long_name, char* units, float** data, int* id_dim_array, size_t* index, int ndim, size_t* n_end, int* zout_index, int* simulation_done) { #if HAVE_NETCDF4 int status = NC_NOERR; int id_data = NOT_DEFINED_INTEGER; size_t lev = 0; size_t iv = 0; char function_name[] = "write_netCDF_5D_float"; char file_name[] = "netCDF_functions.c"; /* check if this result is valid */ for (lev = 0; lev < n_end[POSITION_ZOUT_5D]; lev++) for (iv = 0; iv < n_end[POSITION_LAMBDA_5D]; iv++) { /* replace infinite numbers with NaN (Not a number) */ if (isinf (data[lev][iv])) data[lev][iv] = 0.0 / 0.0; /* check for NaN (Not a Number) */ if (isnan (data[lev][iv])) { (*simulation_done) = FALSE; fprintf (stderr, " *** Warning, unresonable result for '%s' (iv=%d, lev=%d)\n", long_name, (int)iv, (int)lev); } } status = create_float_variable_or_get_id (ncid, filename, data_name, &id_data, ndim, id_dim_array, long_name, units); if (status != NC_NOERR) { fprintf (stderr, "Error %d creating float variable %s in netCDF file %s, in %s (%s)\n", status, long_name, filename, function_name, file_name); return status; } for (lev = 0; lev < n_end[POSITION_ZOUT_5D]; lev++) { index[POSITION_ZOUT_5D] = zout_index[lev]; for (iv = 0; iv < n_end[POSITION_LAMBDA_5D]; iv++) { index[POSITION_LAMBDA_5D] = iv; /* WRITE ONE VARIABLE */ status = nc_put_var1_float (ncid, id_data, index, &(data[lev][iv])); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } } } return status; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: write_netCDF_6D_float */ /* Description: */ /* Write one column of results (mostly z-column) into a 6D array */ /* (time, z, sza, lat, lon). The function checks, if this data set already exits */ /* in the netCDF header. If not it will be created with according attributes, */ /* units ... */ /* If result is not valid (infinity or Not-a-number) simulation done will be */ /* set to FALSE == not done. infinity is replaced by Not-a-number. */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* int *id_data id number of the data (is created, of data is new) */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* float *data the data set itself */ /* int *id_dim_array array of dimension id numbers */ /* size_t *index specifies the position, where to write the entry */ /* into the 4D file */ /* int ndim number of dimenision (here always 6) */ /* size_t *n_end size of the dimensions */ /* int *zout_index index of the zout levels */ /* (nessesary, as some zout-levels, which are below the */ /* ground altitude are obmitted) */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int write_netCDF_6D_float (int ncid, char* filename, char* data_name, char* long_name, char* units, float*** data, int* id_dim_array, size_t* index, int ndim, size_t* n_end, int* zout_index, int* simulation_done) { #if HAVE_NETCDF4 int status = NC_NOERR; int id_data = NOT_DEFINED_INTEGER; size_t lev = 0; size_t iv = 0; size_t iu = 0; char function_name[] = "write_netCDF_6D_float"; char file_name[] = "netCDF_functions.c"; /* check if this result is valid */ for (lev = 0; lev < n_end[POSITION_ZOUT_6D]; lev++) for (iu = 0; iu < n_end[POSITION_UMU_6D]; iu++) for (iv = 0; iv < n_end[POSITION_LAMBDA_6D]; iv++) { /* replace infinite numbers with NaN (Not a number) */ if (isinf (data[lev][iu][iv])) data[lev][iu][iv] = 0.0 / 0.0; /* check for NaN (Not a Number) */ if (isnan (data[lev][iu][iv])) { (*simulation_done) = FALSE; fprintf (stderr, " *** Warning, unresonable result for '%s' (iv=%d, lev=%d, iu=%d)\n", long_name, (int)iv, (int)lev, (int)iu); } } status = create_float_variable_or_get_id (ncid, filename, data_name, &id_data, ndim, id_dim_array, long_name, units); if (status != NC_NOERR) { fprintf (stderr, "Error %d creating float variable %s in netCDF file %s, in %s (%s)\n", status, long_name, filename, function_name, file_name); return status; } for (lev = 0; lev < n_end[POSITION_ZOUT_6D]; lev++) { index[POSITION_ZOUT_6D] = zout_index[lev]; for (iv = 0; iv < n_end[POSITION_LAMBDA_6D]; iv++) { index[POSITION_LAMBDA_6D] = iv; for (iu = 0; iu < n_end[POSITION_UMU_6D]; iu++) { index[POSITION_UMU_6D] = iu; /* WRITE ONE VARIABLE */ status = nc_put_var1_float (ncid, id_data, index, &(data[lev][iu][iv])); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } } } } return status; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: write_netCDF_7D_float */ /* Description: */ /* Write one column of results (mostly z-column) into a 7D array */ /* (time, z, sza, lat, lon). The function checks, if this data set already exits */ /* in the netCDF header. If not it will be created with according attributes, */ /* units ... */ /* If result is not valid (infinity or Not-a-number) simulation done will be */ /* set to FALSE == not done. infinity is replaced by Not-a-number. */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* int *id_data id number of the data (is created, of data is new) */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* float *data the data set itself */ /* int *id_dim_array array of dimension id numbers */ /* size_t *index specifies the position, where to write the entry */ /* into the 4D file */ /* int ndim number of dimenision (here always 7) */ /* size_t *n_end size of the dimensions */ /* int *zout_index index of the zout levels */ /* (nessesary, as some zout-levels, which are below the */ /* ground altitude are obmitted) */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int write_netCDF_7D_float (int ncid, char* filename, char* data_name, char* long_name, char* units, float**** data, int* id_dim_array, size_t* index, int ndim, size_t* n_end, int* zout_index, int* simulation_done) { #if HAVE_NETCDF4 int status = NC_NOERR; int id_data = NOT_DEFINED_INTEGER; size_t lev = 0, iv = 0, iu = 0, ip = 0; char function_name[] = "write_netCDF_7D_float"; char file_name[] = "netCDF_functions.c"; /* check if this result is valid */ for (lev = 0; lev < n_end[POSITION_ZOUT_6D]; lev++) for (ip = 0; ip < n_end[POSITION_PHI_7D]; ip++) for (iu = 0; iu < n_end[POSITION_UMU_6D]; iu++) for (iv = 0; iv < n_end[POSITION_LAMBDA_6D]; iv++) { /* replace infinite numbers with NaN (Not a number) */ if (isinf (data[lev][ip][iu][iv])) data[lev][ip][iu][iv] = 0.0 / 0.0; /* check for NaN (Not a Number) */ if (isnan (data[lev][ip][iu][iv])) { (*simulation_done) = FALSE; fprintf (stderr, " *** Warning, unresonable result for '%s' (iv=%d, lev=%d, iu=%d, ip=%d)\n", long_name, (int)iv, (int)lev, (int)iu, (int)ip); } } status = create_float_variable_or_get_id (ncid, filename, data_name, &id_data, ndim, id_dim_array, long_name, units); if (status != NC_NOERR) { fprintf (stderr, "Error %d creating float variable %s in netCDF file %s, in %s (%s)\n", status, long_name, filename, function_name, file_name); return status; } for (lev = 0; lev < n_end[POSITION_ZOUT_7D]; lev++) { index[POSITION_ZOUT_7D] = zout_index[lev]; for (iv = 0; iv < n_end[POSITION_LAMBDA_7D]; iv++) { index[POSITION_LAMBDA_7D] = iv; for (iu = 0; iu < n_end[POSITION_UMU_7D]; iu++) { index[POSITION_UMU_7D] = iu; for (ip = 0; ip < n_end[POSITION_PHI_7D]; ip++) { index[POSITION_PHI_7D] = ip; /* WRITE ONE VARIABLE */ status = nc_put_var1_float (ncid, id_data, index, &(data[lev][ip][iu][iv])); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } } } } } return status; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: create_float_variable_or_get_id */ /* Description: */ /* The function checks, if this data set already exits */ /* in the netCDF header. If not it will be created with according attributes, */ /* units ... */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* int *id_data id number of the data (is created, of data is new) */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* int *id_dim_array array of dimension id numbers */ /* int ndim number of dimenision */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int create_float_variable_or_get_id (int ncid, char* filename, char* data_name, int* id_data, int ndim, int* id_dim_array, char* long_name, char* units) { #if HAVE_NETCDF4 int status = NC_NOERR; float missing_value = -1.E10; char function_name[] = "create_float_variable_or_get_id"; char file_name[] = "netCDF_functions.c"; /* get variable id for data_name */ status = nc_inq_varid (ncid, data_name, id_data); if (status != NC_NOERR) { /* variable does not exist, create it! */ status = nc_redef (ncid); /* put in define mode */ if (status != NC_NOERR) { fprintf (stderr, "Error %d putting netCDF file %s into define mode, in %s (%s)\n", status, filename, function_name, file_name); return status; } /* create variable */ status = nc_def_var (ncid, data_name, NC_FLOAT, ndim, id_dim_array, id_data); if (status != NC_NOERR) { fprintf (stderr, "Error %d defining data '%s' in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_put_att_text (ncid, *id_data, "long_name", strlen (long_name), long_name); if (status != NC_NOERR) { fprintf (stderr, "Error %d put attribute long_name to '%s' in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_put_att_text (ncid, *id_data, "units", strlen (units), units); if (status != NC_NOERR) { fprintf (stderr, "Error %d put attribute units to '%s' in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_put_att_float (ncid, *id_data, "missing_value", NC_FLOAT, 1, &(missing_value)); if (status != NC_NOERR) { fprintf (stderr, "Error %d defining missing argument in netCDF file %s, in %s (%s)\n", status, filename, function_name, file_name); return status; } status = nc_put_att_float (ncid, *id_data, "_FillValue", NC_FLOAT, 1, &(missing_value)); if (status != NC_NOERR) { fprintf (stderr, "Error %d defining missing argument in netCDF file %s, in %s (%s)\n", status, filename, function_name, file_name); return status; } status = nc_enddef (ncid); /* end define mode */ if (status != NC_NOERR) { fprintf (stderr, "Error %d leaving the define mode for %s, in %s (%s) \n", status, filename, function_name, file_name); return status; } } return NC_NOERR; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: write_netCDF_3D_byte */ /* Description: */ /* Write one number of results (TRUE or FLASE) into a 3D array (simulation done) */ /* The function checks, if this data set already exits in the netCDF header. */ /* If not it will be created with according attributes, units ... and */ /* initialiesed to 0. */ /* */ /* Parameters: */ /* int ncid id number of the netCDF input file */ /* char *filename filename of the result file */ /* char *data_name short name of the data set, e.g. "lat" */ /* char *long_name long name of the data set. e.g."latitude" */ /* char *units units of the data set, e.g. "degrees east" */ /* short data data to write */ /* int *id_dim_array array of dimension id numbers */ /* size_t *index_3D where to write the data */ /* int ndim number of dimenision (here always 3) */ /* Return value: */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int write_netCDF_3D_byte (int ncid, char* filename, char* data_name, char* long_name, char* units, short data, int* id_dim_array, size_t* index_3D, int ndim) { #if HAVE_NETCDF4 int status = NC_NOERR; int id_data = NOT_DEFINED_INTEGER; short missing_value = 0; size_t ntime = 0, nlat = 0, nlon = 0; int n_all = 0; int t = -999; signed char* tmp_char = NULL; char function_name[] = "write_netCDF_3D_byte"; char file_name[] = "netCDF_functions.c"; /* get variable id for data_name */ status = nc_inq_varid (ncid, data_name, &id_data); if (status != NC_NOERR) { /* variable does not exist, create it! */ status = nc_redef (ncid); /* put in define mode */ if (status != NC_NOERR) { fprintf (stderr, "Error %d putting netCDF file %s into define mode, in %s (%s)\n", status, filename, function_name, file_name); return status; } /* create variable */ status = nc_def_var (ncid, data_name, NC_BYTE, ndim, id_dim_array, &id_data); if (status != NC_NOERR) { fprintf (stderr, "Error %d defining data '%s' in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_put_att_text (ncid, id_data, "long_name", strlen (long_name), long_name); if (status != NC_NOERR) { fprintf (stderr, "Error %d put attribute long_name to '%s' in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_put_att_text (ncid, id_data, "units", strlen (units), units); if (status != NC_NOERR) { fprintf (stderr, "Error %d put attribute units to '%s' in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } status = nc_put_att_short (ncid, id_data, "missing_value", NC_BYTE, 1, &(missing_value)); if (status != NC_NOERR) { fprintf (stderr, "Error %d defining missing argument in netCDF file %s, in %s (%s)\n", status, filename, function_name, file_name); return status; } status = nc_enddef (ncid); /* end define mode */ if (status != NC_NOERR) { fprintf (stderr, "Error %d leaving the define mode for %s, in %s (%s) \n", status, filename, function_name, file_name); return status; } /* get dimension length for "ntime" */ status = nc_inq_dimlen (ncid, id_dim_array[POSITION_TIME_3D], &ntime); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading ntime from %s, in %s (%s)\n", status, filename, function_name, file_name); return status; } /* get dimension length for "nlat" */ status = nc_inq_dimlen (ncid, id_dim_array[POSITION_LAT_3D], &nlat); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading nlat from %s, in %s (%s)\n", status, filename, function_name, file_name); return status; } /* get dimension length for "nlon" */ status = nc_inq_dimlen (ncid, id_dim_array[POSITION_LON_3D], &nlon); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading nlon from %s, in %s (%s)\n", status, filename, function_name, file_name); return status; } n_all = ntime * nlat * nlon; if ((tmp_char = calloc (n_all, sizeof (char))) == NULL) { fprintf (stderr, "Error, allocating memory for %s, in %s (%s)\n", data_name, function_name, file_name); return -1; } for (t = 0; t < n_all; t++) tmp_char[t] = 0; /* WRITE ONE VARIABLE */ /* does not work on the cluster with unsigned char, that why I use signed chars here !?! */ status = nc_put_var_schar (ncid, id_data, tmp_char); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s in netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } free (tmp_char); } /* WRITE ONE VARIABLE */ status = nc_put_var1_short (ncid, id_data, index_3D, &(data)); if (status != NC_NOERR) { fprintf (stderr, "Error %d writing %s to netCDF file %s, in %s (%s)\n", status, data_name, filename, function_name, file_name); return status; } return status; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: read_3d_float */ /* Description: */ /* Reads a 3D data set from an netCDF file and stores it in an 3D float array, */ /* which will be automatically be allocated */ /* */ /* Parameters: */ /* int ncid id number of the read netCDF file */ /* char *file filename of the read netCDF file */ /* char *var_name short name of the data set, e.g. "lat" */ /* long n1 number of entries in the 1st dimension */ /* long n2 number of entries in the 2nd dimension */ /* long n3 number of entries in the 3rd dimension */ /* Return value: */ /* float ****float3d read data */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Jun 2008 U. Hamann Created */ /* */ /***********************************************************************************/ int read_3d_float (int ncid, char* file, char* var_name, float**** float3d, long n1, long n2, long n3, char*** done, int verbose) { #if HAVE_NETCDF4 int status = 0; int t = 0, j = 0, i = 0; int id_float3d = 0; float* tmp_float3d = NULL; char function_name[] = "read_3d_float"; char file_name[] = "netCDF_functions.c"; if (verbose) fprintf (stderr, " ... read_float_3d: var = %-10s, data_type = %-8s, ndim = %3d \n", var_name, "float", 3); /* allocate space for "float3d" */ if (((*float3d) = calloc (n1, sizeof (float***))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float3d' in %s (%s)\n", function_name, file_name); return -1; } for (t = 0; t < n1; t++) { if (((*float3d)[t] = calloc (n2, sizeof (float**))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float3d' in %s (%s)\n", function_name, file_name); return -2; } for (j = 0; j < n2; j++) { if (((*float3d)[t][j] = calloc (n3, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float3d' in %s (%s)\n", function_name, file_name); return -3; } } } /* allocate space for "tmp_float3d" */ if ((tmp_float3d = calloc (n1 * n2 * n3, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'tmp_float3d' in %s (%s)\n", function_name, file_name); return -1; } /* get id for float3d */ status = nc_inq_varid (ncid, var_name, &id_float3d); if (status != NC_NOERR) { fprintf (stderr, "Error, get id for '%s' field in the netCDF result file %s, in %s (%s) \n", var_name, file, function_name, file_name); return -1; } /* read values from netCDF variable */ status = nc_get_var_float (ncid, id_float3d, tmp_float3d); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading '%s' from %s, in %s (%s)\n", status, var_name, file, function_name, file_name); return status; } for (t = 0; t < n1; t++) for (j = 0; j < n2; j++) for (i = 0; i < n3; i++) { (*float3d)[t][j][i] = tmp_float3d[t * n2 * n3 + j * n3 + i]; /* fprintf (stderr, "t=%4d, z=%4d, y=%4d, x=%4d, float3d=%8.2f \n",t,c2,j,i,(*float3d)[t][c2][j][i]); */ /* fflush(stderr); */ } free (tmp_float3d); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: read_4d_float */ /* Description: */ /* Reads a 4D data set from an netCDF file and stores it in an 4D float array */ /* will will be accordingly allocated */ /* */ /* Parameters: */ /* int ncid id number of the read netCDF file */ /* char *file filename of the read netCDF file */ /* char *var_name short name of the data set, e.g. "lat" */ /* long n1 number of entries in the 1st dimension */ /* long n2 number of entries in the 2nd dimension */ /* long n3 number of entries in the 3rd dimension */ /* long n4 number of entries in the 4th dimension */ /* Return value: */ /* float *****float4d read data */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int read_4d_float (int ncid, char* file, char* var_name, float***** float4d, long n1, long n2, long n3, long n4, char*** done, int verbose) { #if HAVE_NETCDF4 int status = 0; int t = 0, c2 = 0, j = 0, i = 0; int id_float4d = 0; float* tmp_float4d = NULL; char function_name[] = "read_4d_float"; char file_name[] = "netCDF_functions.c"; if (verbose) fprintf (stderr, " ... read_float_4d: var = %-10s, data_type = %-8s, ndim = %3d \n", var_name, "float", 4); /* allocate space for "float4d" */ if (((*float4d) = calloc (n1, sizeof (float***))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float4d' in %s (%s)\n", function_name, file_name); return -1; } for (t = 0; t < n1; t++) { if (((*float4d)[t] = calloc (n2, sizeof (float**))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float4d' in %s (%s)\n", function_name, file_name); return -2; } for (c2 = 0; c2 < n2; c2++) { if (((*float4d)[t][c2] = calloc (n3, sizeof (float*))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float4d' in %s (%s)\n", function_name, file_name); return -3; } for (j = 0; j < n3; j++) { if (((*float4d)[t][c2][j] = calloc (n4, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float4d' in %s (%s)\n", function_name, file_name); return -4; } } } } /* allocate space for "tmp_float4d" */ if ((tmp_float4d = calloc (n1 * n2 * n3 * n4, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'tmp_float4d' in %s (%s)\n", function_name, file_name); return -1; } /* get id for float4d */ status = nc_inq_varid (ncid, var_name, &id_float4d); if (status != NC_NOERR) { fprintf (stderr, "Error, get id for '%s' field in the netCDF result file %s, in %s (%s) \n", var_name, file, function_name, file_name); return -1; } /* read values from netCDF variable */ status = nc_get_var_float (ncid, id_float4d, tmp_float4d); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading '%s' from %s, in %s (%s)\n", status, var_name, file, function_name, file_name); return status; } for (t = 0; t < n1; t++) for (c2 = 0; c2 < n2; c2++) for (j = 0; j < n3; j++) for (i = 0; i < n4; i++) { (*float4d)[t][c2][j][i] = tmp_float4d[t * n2 * n3 * n4 + c2 * n3 * n4 + j * n4 + i]; /* fprintf (stderr, "t=%4d, z=%4d, y=%4d, x=%4d, float4d=%8.2f \n",t,c2,j,i,(*float4d)[t][c2][j][i]); */ /* fflush(stderr); */ } free (tmp_float4d); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: read_5d_float */ /* Description: */ /* Reads a 5D data set from an netCDF file and stores it in an 5D float array */ /* will will be accordingly allocated */ /* */ /* Parameters: */ /* int ncid id number of the read netCDF file */ /* char *file filename of the read netCDF file */ /* char *var_name short name of the data set, e.g. "lat" */ /* long n1 number of entries in the 1st dimension */ /* long n2 number of entries in the 2nd dimension */ /* long n3 number of entries in the 3rd dimension */ /* long n4 number of entries in the 4th dimension */ /* long n5 number of entries in the 5th dimension */ /* Return value: */ /* float ******float5d read data */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int read_5d_float (int ncid, char* file, char* var_name, float****** float5d, long n1, long n2, long n3, long n4, long n5, char*** done, int verbose) { #if HAVE_NETCDF4 int status = 0; int t = 0, c2 = 0, c3 = 0, j = 0, i = 0; int id_float5d = 0; float* tmp_float5d = NULL; char function_name[] = "read_5d_float"; char file_name[] = "netCDF_functions.c"; if (verbose) fprintf (stderr, " ... read_float_5d: var = %-10s, data_type = %-8s, ndim = %3d \n", var_name, "float", 5); /* allocate space for "float5d" */ if (((*float5d) = calloc (n1, sizeof (float****))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float5d' in %s (%s)\n", function_name, file_name); return -1; } for (t = 0; t < n1; t++) { if (((*float5d)[t] = calloc (n2, sizeof (float***))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float5d' in %s (%s)\n", function_name, file_name); return -2; } for (c2 = 0; c2 < n2; c2++) { if (((*float5d)[t][c2] = calloc (n3, sizeof (float**))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float5d' in %s (%s)\n", function_name, file_name); return -3; } for (c3 = 0; c3 < n3; c3++) { if (((*float5d)[t][c2][c3] = calloc (n4, sizeof (float*))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float5d' in %s (%s)\n", function_name, file_name); return -4; } for (j = 0; j < n4; j++) { if (((*float5d)[t][c2][c3][j] = calloc (n5, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float5d' in %s (%s)\n", function_name, file_name); return -5; } } } } } /* allocate space for "tmp_float5d" */ if ((tmp_float5d = calloc (n1 * n2 * n3 * n4 * n5, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'tmp_float5d' in %s (%s)\n", function_name, file_name); return -1; } /* get id for float5d */ status = nc_inq_varid (ncid, var_name, &id_float5d); if (status != NC_NOERR) { fprintf (stderr, "Error, get id for '%s' field in the netCDF result file %s, in %s (%s) \n", var_name, file, function_name, file_name); return -1; } /* read values from netCDF variable */ status = nc_get_var_float (ncid, id_float5d, tmp_float5d); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading '%s' from %s\n", status, var_name, file); return status; } for (t = 0; t < n1; t++) for (c2 = 0; c2 < n2; c2++) for (c3 = 0; c3 < n3; c3++) for (j = 0; j < n4; j++) for (i = 0; i < n5; i++) { (*float5d)[t][c2][c3][j][i] = tmp_float5d[t * n2 * n3 * n4 * n5 + c2 * n3 * n4 * n5 + c3 * n4 * n5 + j * n5 + i]; /* fprintf (stderr, "t=%4d, lambda=%4d, z=%4d, y=%4d, x=%4d, float5d=%8.2f \n",t,c2,c3,j,i,(*float5d)[t][c2][c3][j][i]); */ /* fflush(stderr); */ } free (tmp_float5d); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: read_6d_float */ /* Description: */ /* Reads a 6D data set from an netCDF file and stores it in an 6D float array */ /* will will be accordingly allocated */ /* */ /* Parameters: */ /* int ncid id number of the read netCDF file */ /* char *file filename of the read netCDF file */ /* char *var_name short name of the data set, e.g. "lat" */ /* long n1 number of entries in the 1st dimension */ /* long n2 number of entries in the 2nd dimension */ /* long n3 number of entries in the 3rd dimension */ /* long n4 number of entries in the 4th dimension */ /* long n5 number of entries in the 5th dimension */ /* long n6 number of entries in the 6th dimension */ /* Return value: */ /* float *******float6d read data */ /* int status == 0, if everthing is OK */ /* */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int read_6d_float (int ncid, char* file, char* var_name, float******* float6d, long n1, long n2, long n3, long n4, long n5, long n6, char*** done, int verbose) { #if HAVE_NETCDF4 int status = 0; int t = 0, c2 = 0, c3 = 0, c4 = 0, j = 0, i = 0; int id_float6d = 0; float* tmp_float6d = NULL; char function_name[] = "read_6d_float"; char file_name[] = "netCDF_functions.c"; if (verbose) fprintf (stderr, " ... read_float_6d: var = %-10s, data_type = %-8s, ndim = %3d \n", var_name, "float", 6); /* allocate space for "float6d" */ if (((*float6d) = calloc (n1, sizeof (float*****))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float6d' in %s (%s)\n", function_name, file_name); return -1; } for (t = 0; t < n1; t++) { if (((*float6d)[t] = calloc (n2, sizeof (float****))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float6d' in %s (%s)\n", function_name, file_name); return -2; } for (c2 = 0; c2 < n2; c2++) { if (((*float6d)[t][c2] = calloc (n3, sizeof (float***))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float6d' in %s (%s)\n", function_name, file_name); return -3; } for (c3 = 0; c3 < n3; c3++) { if (((*float6d)[t][c2][c3] = calloc (n4, sizeof (float**))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float6d' in %s (%s)\n", function_name, file_name); return -4; } for (c4 = 0; c4 < n4; c4++) { if (((*float6d)[t][c2][c3][c4] = calloc (n5, sizeof (float*))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float6d' in %s (%s)\n", function_name, file_name); return -5; } for (j = 0; j < n5; j++) { if (((*float6d)[t][c2][c3][c4][j] = calloc (n6, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float6d' in %s (%s)\n", function_name, file_name); return -6; } } } } } } /* allocate space for "tmp_float6d" */ if ((tmp_float6d = calloc (n1 * n2 * n3 * n4 * n5 * n6, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'tmp_float6d' in %s (%s)\n", function_name, file_name); return -1; } /* get id for float6d */ status = nc_inq_varid (ncid, var_name, &id_float6d); if (status != NC_NOERR) { fprintf (stderr, "Error, get id for '%s' field in the netCDF result file %s, in %s (%s)\n", var_name, file, function_name, file_name); return -1; } /* read values from netCDF variable */ status = nc_get_var_float (ncid, id_float6d, tmp_float6d); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading '%s' from %s\n", status, var_name, file); return status; } for (t = 0; t < n1; t++) for (c2 = 0; c2 < n2; c2++) for (c3 = 0; c3 < n3; c3++) for (c4 = 0; c4 < n4; c4++) for (j = 0; j < n5; j++) for (i = 0; i < n6; i++) { /* if (done[t][j][i]) { */ (*float6d)[t][c2][c3][c4][j][i] = tmp_float6d[t * n2 * n3 * n4 * n5 * n6 + c2 * n3 * n4 * n5 * n6 + c3 * n4 * n5 * n6 + c4 * n5 * n6 + j * n6 + i]; /* fprintf (stderr, "t=%4d, lambda=%4d, z=%4d, umu=%4d, y=%4d, x=%4d, float6d=%8.2f \n",t,c2,c3,c4,j,i,(*float6d)[t][c2][c3][c4][j][i]); */ /* fflush(stderr); */ /* } */ } free (tmp_float6d); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: read_7d_float */ /* Description: */ /* Reads a 7D data set from an netCDF file and stores it in an 7D float array */ /* will will be accordingly allocated */ /* */ /* Parameters: */ /* int ncid id number of the read netCDF file */ /* char *file filename of the read netCDF file */ /* char *var_name short name of the data set, e.g. "lat" */ /* long n1 number of entries in the 1st dimension */ /* long n2 number of entries in the 2nd dimension */ /* long n3 number of entries in the 3rd dimension */ /* long n4 number of entries in the 4th dimension */ /* long n5 number of entries in the 5th dimension */ /* long n6 number of entries in the 6th dimension */ /* long n7 number of entries in the 7th dimension */ /* Return value: */ /* float *******float6d read data */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int read_7d_float (int ncid, char* file, char* var_name, float******** float7d, long n1, long n2, long n3, long n4, long n5, long n6, long n7, char*** done, int verbose) { #if HAVE_NETCDF4 int status = 0; int t = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0, j = 0, i = 0; int id_float7d = 0; float* tmp_float7d = NULL; char function_name[] = "read_7d_float"; char file_name[] = "netCDF_functions.c"; if (verbose) fprintf (stderr, " ... read_float_7d: var = %-10s, data_type = %-8s, ndim = %3d \n", var_name, "float", 7); /* allocate space for "float7d" */ if (((*float7d) = calloc (n1, sizeof (float******))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float7d' in %s (%s)\n", function_name, file_name); return -1; } for (t = 0; t < n1; t++) { if (((*float7d)[t] = calloc (n2, sizeof (float*****))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float7d' in %s (%s)\n", function_name, file_name); return -2; } for (c2 = 0; c2 < n2; c2++) { if (((*float7d)[t][c2] = calloc (n3, sizeof (float****))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float7d' in %s (%s)\n", function_name, file_name); return -3; } for (c3 = 0; c3 < n3; c3++) { if (((*float7d)[t][c2][c3] = calloc (n4, sizeof (float***))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float7d' in %s (%s)\n", function_name, file_name); return -4; } for (c4 = 0; c4 < n4; c4++) { if (((*float7d)[t][c2][c3][c4] = calloc (n5, sizeof (float**))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float7d' in %s (%s)\n", function_name, file_name); return -5; } for (c5 = 0; c5 < n5; c5++) { if (((*float7d)[t][c2][c3][c4][c5] = calloc (n6, sizeof (float*))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float7d' in %s (%s)\n", function_name, file_name); return -6; } for (j = 0; j < n6; j++) { if (((*float7d)[t][c2][c3][c4][c5][j] = calloc (n7, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'float7d' in %s (%s)\n", function_name, file_name); return -7; } } } } } } } /* allocate space for "tmp_float7d" */ if ((tmp_float7d = calloc (n1 * n2 * n3 * n4 * n5 * n6 * n7, sizeof (float))) == NULL) { fprintf (stderr, "Error, allocating memory for 'tmp_float7d' in %s (%s)\n", function_name, file_name); return -1; } /* get id for float7d */ status = nc_inq_varid (ncid, var_name, &id_float7d); if (status != NC_NOERR) { fprintf (stderr, "Error, get id for '%s' field in the netCDF result file %s, in %s (%s) \n", var_name, file, function_name, file_name); return -1; } /* read values from netCDF variable */ status = nc_get_var_float (ncid, id_float7d, tmp_float7d); if (status != NC_NOERR) { fprintf (stderr, "Error %d reading '%s' from %s\n", status, var_name, file); return status; } for (t = 0; t < n1; t++) for (c2 = 0; c2 < n2; c2++) for (c3 = 0; c3 < n3; c3++) for (c4 = 0; c4 < n4; c4++) for (c5 = 0; c5 < n5; c5++) for (j = 0; j < n6; j++) for (i = 0; i < n7; i++) { /* if (done[t][j][i]) { */ (*float7d)[t][c2][c3][c4][c5][j][i] = tmp_float7d[(((((t * n2 + c2) * n3 + c3) * n4 + c4) * n5 + c5) * n6 + j) * n7 + i]; /* fprintf (stderr, "t=%4d, lambda=%4d, z=%4d, umu=%4d, y=%4d, x=%4d, float7d=%8.2f \n",t,c2,c3,c4,c5,j,(*float7d)[t][c2][c3][c4][c5][j][i]); */ /* fflush(stderr); */ /* } */ } free (tmp_float7d); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: read_3d_char */ /* Description: */ /* Reads a 3D data set from an netCDF file and stores it in an 3D char array */ /* will will be accordingly allocated. */ /* */ /* Parameters: */ /* int ncid id number of the read netCDF file */ /* char *file filename of the read netCDF file */ /* char *var_name short name of the data set, e.g. "lat" */ /* long ntime number of entries in the 1st dimension */ /* long nlat number of entries in the 2nd dimension */ /* long nlon number of entries in the 3rd dimension */ /* */ /* Return value: */ /* char ****done read data */ /* int status == 0, if everthing is OK */ /* < 0, if there was an error */ /* Example: */ /* Files: netCDF_functions.c */ /* Known bugs: - */ /* Author: */ /* Oct 2007 U. Hamann Created */ /* */ /***********************************************************************************/ int read_3d_char (int ncid, char* file, char* var_name, char**** done, long ntime, long nlat, long nlon, int verbose) { #if HAVE_NETCDF4 int status = 0; long t = 0, j = 0, i = 0; int id_done = 0; signed char* tmp_done = NULL; char function_name[] = "read_3d_char"; char file_name[] = "netCDF_functions.c"; if (verbose) fprintf (stderr, " ... read_char_3d: var = %-10s, data_type = %-8s, ndim = %3d \n", var_name, "char", 3); /* allocate space for "done" */ if (((*done) = calloc ((ntime), sizeof (char**))) == NULL) { fprintf (stderr, "Error, allocating memory for 'done' in %s (%s)\n", function_name, file_name); return -1; } for (t = 0; t < (ntime); t++) { if (((*done)[t] = calloc ((nlat), sizeof (char*))) == NULL) { fprintf (stderr, "Error, allocating memory for 'done' in %s (%s)\n", function_name, file_name); return -1; } for (j = 0; j < (nlat); j++) if (((*done)[t][j] = calloc ((nlon), sizeof (char))) == NULL) { fprintf (stderr, "Error, allocating memory for 'done' in %s (%s)\n", function_name, file_name); return -1; } } /* allocate space for "tmp_done" */ if ((tmp_done = calloc ((ntime) * (nlon) * (nlat), sizeof (char))) == NULL) { fprintf (stderr, "Error, allocating memory for 'tmp_done' in %s (%s)\n", function_name, file_name); return -1; } /* get id for done */ status = nc_inq_varid (ncid, "done", &id_done); if (status != NC_NOERR) { /* this is in most of the cases OK, that's the start of an worldloop job */ /* fprintf (stderr,"Error, get id for 'done' field in the netCDF result file %s, in %s (%s)\n", file, function_name, file_name); */ return status; } /* read values from netCDF variable */ status = nc_get_var_schar (ncid, id_done, tmp_done); if (status != NC_NOERR) { fprintf (stderr, "Error '%s' while reading '%s' from %s, in %s (%s)\n", nc_strerror (status), var_name, file, function_name, file_name); return status; } for (t = 0; t < (ntime); t++) for (j = 0; j < (nlat); j++) for (i = 0; i < (nlon); i++) { (*done)[t][j][i] = tmp_done[t * (nlon) * (nlat) + j * (nlon) + i]; /* if ((*done)[t][j][i]) { */ /* fprintf (stderr, "read_3d_char: t=%3ld j=%3ld i=%3ld, done=%d \n",t,j,i,(*done)[t][j][i]); */ /* fflush(stderr); } */ } free (tmp_done); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } /***********************************************************************************/ /* Function: write_netcdf_type */ /* Description: Write a variable to netCDF file; variable might be either */ /* int, float or double with specific dimension. */ /* rows is the number of (not empty) rows of the file, columns is the */ /* number of columns of the file and columns is the number of columns */ /* of all (not empty) lines. If variable is 3D with regular grid size, */ /* length is the number of entries of each column. If variable is 3d */ /* with irregular grid size, length is a twodimensional array of int */ /* Parameters: */ /* int ncid: Id of netCDF file give by */ /* nc_create(char *filename, int cmode, int &ncid) */ /* value: Pointer to a variable */ /* int rows: Number of rows */ /* int columns: Number of columns */ /* int length: Length of column */ /* */ /* Return value: */ /* 0 if o.k., <0 if error */ /* */ /* Example: */ /* Files: */ /* Known bugs: */ /* Author: Bettina Richter */ /***********************************************************************************/ int write_netcdf_int (int ncid, int value, char* var_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int varid, retval; if ((retval = nc_redef (ncid))) ERR (retval); /********** Define the variable. The type of the variable in this case is NC_INT (4-byte integer). *********/ if ((retval = nc_def_var (ncid, var_name, NC_INT, 0, 0, &varid))) ERR (retval); /********** End define mode. This tells netCDF we are done defining metadata. **********/ if ((retval = nc_enddef (ncid))) ERR (retval); /********** Write the pretend data to the file. Although netCDF supports * reading and writing subsets of data, in this case we write all * the data in one operation. **********/ if ((retval = nc_put_var_int (ncid, varid, &value))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_float (int ncid, float value, char* var_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int varid, retval; if ((retval = nc_redef (ncid))) ERR (retval); if ((retval = nc_def_var (ncid, var_name, NC_FLOAT, 0, 0, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_float (ncid, varid, &value))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_1Dint (int ncid, int* value, int rows, char* var_name, char* row_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int retval, varid, row_dimid; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } int dimid[1] = {row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_INT, 1, dimid, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_int (ncid, varid, &value[0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_1Dsize_t (int ncid, size_t* value, int rows, char* var_name, char* row_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int retval, varid, row_dimid; const unsigned long long* data = (unsigned long long*)value; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } int dimid[1] = {row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_LONG, 1, dimid, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_ulonglong (ncid, varid, &(data[0])))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_1Dfloat (int ncid, float* value, int rows, char* var_name, char* row_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int retval, varid, row_dimid; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } /********** The dimids array is used to pass the IDs of the dimensions of the variable. *********/ int dimid[1] = {row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_FLOAT, 1, dimid, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_float (ncid, varid, &value[0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_1Ddouble (int ncid, double* value, int rows, char* var_name, char* row_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int retval, varid, row_dimid; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } /********** The dimids array is used to pass the IDs of the dimensions of the variable. *********/ int dimid[1] = {row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_DOUBLE, 1, dimid, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_double (ncid, varid, &value[0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_2Dint (int ncid, int** value, int rows, int columns, char* var_name, char* row_name, char* column_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int value_data[rows][columns]; int row, column; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) value_data[row][column] = value[row][column]; } int retval, varid, row_dimid, column_dimid; int NDIMS = 2; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } int dimids[2] = {column_dimid, row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_INT, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_int (ncid, varid, &value_data[0][0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_2Dfloat (int ncid, float** value, int rows, int columns, char* var_name, char* row_name, char* column_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; float value_data[rows][columns]; int row, column; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) value_data[row][column] = value[row][column]; } int retval, varid, row_dimid, column_dimid; int NDIMS = 2; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } int dimids[2] = {column_dimid, row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_FLOAT, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_float (ncid, varid, &value_data[0][0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_2Ddouble (int ncid, double** value, int rows, int columns, char* var_name, char* row_name, char* column_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; double value_data[rows][columns]; int row, column; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) value_data[row][column] = value[row][column]; } int retval, varid, row_dimid, column_dimid; int NDIMS = 2; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } int dimids[2] = {column_dimid, row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_DOUBLE, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_double (ncid, varid, &value_data[0][0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_3Dfloat (int ncid, float*** value, int rows, int columns, int length, char* var_name, char* row_name, char* column_name, char* length_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; float value_data[rows][columns][length]; int row, column, il; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) { for (il = 0; il < length; il++) value_data[row][column][il] = value[row][column][il]; } } int retval, varid, row_dimid, column_dimid, length_dimid; int NDIMS = 3; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, length_name, &length_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, length_name, length, &length_dimid))) ERR (retval); } int dimids[3] = {length_dimid, column_dimid, row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_FLOAT, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_float (ncid, varid, &value_data[0][0][0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_3D_contiguous_float (int ncid, float* value, int rows, int columns, int length, char* var_name, char* row_name, char* column_name, char* length_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int retval, varid, row_dimid, column_dimid, length_dimid; int NDIMS = 3; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, length_name, &length_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, length_name, length, &length_dimid))) ERR (retval); } int dimids[3] = {row_dimid, column_dimid, length_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_FLOAT, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_float (ncid, varid, &value[0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_3Dirr_row_float (int ncid, float*** value, int rows, int columns, int* length, char* var_name, char* row_name, char* column_name, char* length_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int row, column, il; /**** Maximum length of value; in case of regular grid, length_max == length ****/ int length_max; length_max = 0; for (row = 0; row < rows; row++) { if (length_max < length[row]) length_max = length[row]; } /**** Copy ***value into a block of contiguous data values for netcdf ****/ float value_data[rows][columns][length_max]; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) { for (il = 0; il < length_max; il++) if (il < length[row]) value_data[row][column][il] = value[row][column][il]; else value_data[row][column][il] = NOT_DEFINED_FLOAT; } } int retval, varid, row_dimid, column_dimid, length_dimid; int NDIMS = 3; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, length_name, &length_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, length_name, length_max, &length_dimid))) ERR (retval); } int dimids[3] = {length_dimid, column_dimid, row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_FLOAT, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_float (ncid, varid, &value_data[0][0][0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_3Dirrfloat (int ncid, float*** value, int rows, int columns, int** length, char* var_name, char* row_name, char* column_name, char* length_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int row, column, il; /**** Maximum length of value; in case of regular grid, length_max == length ****/ int length_max; length_max = 0; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) { if (length_max < length[row][column]) length_max = length[row][column]; } } if (length_max <= 0) { fprintf (stderr, "ERROR: Could write %s to netcdf_file\n", var_name); return 0; } /**** Copy ***value into a block of contiguous data values for netcdf ****/ float value_data[rows][columns][length_max]; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) { for (il = 0; il < length_max; il++) if (il < length[row][column]) value_data[row][column][il] = value[row][column][il]; else value_data[row][column][il] = NOT_DEFINED_FLOAT; } } int retval, varid, row_dimid, column_dimid, length_dimid; int NDIMS = 3; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, length_name, &length_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, length_name, length_max, &length_dimid))) ERR (retval); } int dimids[3] = {length_dimid, column_dimid, row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_FLOAT, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_float (ncid, varid, &value_data[0][0][0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif } int write_netcdf_3Dirrdouble (int ncid, double*** value, int rows, int columns, int** length, char* var_name, char* row_name, char* column_name, char* length_name) { #if HAVE_NETCDF4 if (ncid == 0) return -1; int row, column, il; /**** Maximum length of value; in case of regular grid, length_max == length ****/ int length_max; length_max = 0; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) { if (length_max < length[row][column]) length_max = length[row][column]; } } if (length_max <= 0) { fprintf (stderr, "WARNING: Did not write %s to netcdf_file because it is empty\n", var_name); return 0; } /**** Copy ***value into a block of contiguous data values for netcdf ****/ double value_data[rows][columns][length_max]; for (row = 0; row < rows; row++) { for (column = 0; column < columns; column++) { for (il = 0; il < length_max; il++) if (il < length[row][column]) value_data[row][column][il] = value[row][column][il]; else value_data[row][column][il] = NOT_DEFINED_FLOAT; } } int retval, varid, row_dimid, column_dimid, length_dimid; int NDIMS = 3; if ((retval = nc_redef (ncid))) ERR (retval); if ((nc_inq_dimid (ncid, row_name, &row_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, row_name, rows, &row_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, column_name, &column_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, column_name, columns, &column_dimid))) ERR (retval); } if ((nc_inq_dimid (ncid, length_name, &length_dimid) != NC_NOERR)) { if ((retval = nc_def_dim (ncid, length_name, length_max, &length_dimid))) ERR (retval); } int dimids[3] = {length_dimid, column_dimid, row_dimid}; if ((retval = nc_def_var (ncid, var_name, NC_DOUBLE, NDIMS, dimids, &varid))) ERR (retval); if ((retval = nc_enddef (ncid))) ERR (retval); if ((retval = nc_put_var_double (ncid, varid, &value_data[0][0][0]))) ERR (retval); return 0; #else fprintf (stderr, " ***********************************************************************\n"); fprintf (stderr, " * You have built uvspec without libnetcdf and hence cannot *\n"); fprintf (stderr, " * use any netCDF option. Please get netcdf and rebuild. *\n"); fprintf (stderr, " ***********************************************************************\n"); return -1; #endif }
43.944467
160
0.420609
[ "3d" ]
da4711325bd9d0d43dc3e1a6d37ea90af1a7038a
1,803
h
C
src/app/jni/src/SUI/Font.h
Helios-vmg/CopperRat
86722197cb4c8732848c132e855c2b206c2e86de
[ "BSD-2-Clause" ]
3
2016-01-20T16:25:08.000Z
2016-12-22T13:39:32.000Z
src/app/jni/src/SUI/Font.h
Helios-vmg/CopperRat
86722197cb4c8732848c132e855c2b206c2e86de
[ "BSD-2-Clause" ]
1
2016-08-29T14:40:56.000Z
2016-08-30T06:14:36.000Z
src/app/jni/src/SUI/Font.h
Helios-vmg/CopperRat
86722197cb4c8732848c132e855c2b206c2e86de
[ "BSD-2-Clause" ]
1
2015-01-06T08:32:38.000Z
2015-01-06T08:32:38.000Z
/* Copyright (c), Helios All rights reserved. Distributed under a permissive license. See COPYING.txt for details. */ #pragma once #include "../Exception.h" #include "../Image.h" #ifndef HAVE_PRECOMPILED_HEADERS #include <vector> #include <fstream> #include <SDL.h> #include <memory> #include <type_traits> #endif #ifndef __ANDROID__ #define BASE_PATH "" #else #define BASE_PATH "/data/data/org.copper.rat/files/" #endif struct rendering_pair{ Uint8 page; GPU_Rect src; GPU_Rect dst; float scale; }; class Font{ std::ifstream font_file; GPU_Target *target; std::vector<bool> width_bitmap; std::vector<Uint32> offsets_table; std::vector<texture_t> textures; void initialize_width_bitmap(Uint32 bitmap_offset, Uint32 offsets_table_offset); void initialize_offsets_table(Uint32 bitmap_offset, Uint32 offsets_table_offset); void load_page(unsigned page); texture_t get_page(Uint8 page){ if (!this->textures[page]) this->load_page(page); return this->textures[page]; } void draw_text(const std::string *, const std::wstring *, int, int, int, double); void compute_rendering_pairs(void (*)(void *, const rendering_pair &), void *, const std::string *, const std::wstring *, int, int, int, double); public: Font(GPU_Target *target); void draw_text(const std::string &text, int x0, int y0, int wrap_at = INT_MAX, double scale = 1.0){ this->draw_text(&text, nullptr, x0, y0, wrap_at, scale); } void draw_text(const std::wstring &text, int x0, int y0, int wrap_at = INT_MAX, double scale = 1.0){ this->draw_text(nullptr, &text, x0, y0, wrap_at, scale); } SDL_Rect calculate_bounding_box(const std::wstring &text, int wrap_at = INT_MAX, double scale = 1.0); unsigned get_font_height() const{ return 16; } };
28.619048
147
0.707709
[ "vector" ]
da488517f972f17505af8afd7b4ca48ea5ace67e
1,303
h
C
WordCounterIterator.h
UCSB-CS32-F15/cs32-f15-lab07-start
bbb7ba5068329cfb0b5a102c4319ee96308f1821
[ "MIT" ]
null
null
null
WordCounterIterator.h
UCSB-CS32-F15/cs32-f15-lab07-start
bbb7ba5068329cfb0b5a102c4319ee96308f1821
[ "MIT" ]
null
null
null
WordCounterIterator.h
UCSB-CS32-F15/cs32-f15-lab07-start
bbb7ba5068329cfb0b5a102c4319ee96308f1821
[ "MIT" ]
null
null
null
#ifndef WORD_COUNTER_ITERATOR_H #define WORD_COUNTER_ITERATOR_H #include <iterator> #include <map> // The purpose of the WordCounterIterator is to adapt the iterator // that is inside the WordCounter object, the one that is for a map, // and allow it to iterate over strings instead of pairs. typedef std::map<std::string,int>::const_iterator OurIteratorType; class WordCounterIterator : public std::iterator<std::input_iterator_tag, std::string *> { public: WordCounterIterator(OurIteratorType iter) : iter(iter) {} // prefix e.g. ++iter WordCounterIterator & operator++() { iter++; return (*this); } // (int) is dummy argument to show postfix ++ // e.g. iter++ /* see http://www.learncpp.com/cpp-tutorial/97-overloading-the-increment-and-decrement-operators/ ) */ WordCounterIterator operator++( int ) { WordCounterIterator tmp(*this); operator++(); return tmp; } bool operator==(const WordCounterIterator& rhs) { return (iter==rhs.iter); } bool operator!=(const WordCounterIterator& rhs) { return !( *this == rhs) ; } const std::string & operator*() { return iter->first; } private: // This will be an iterator // from the map object inside a WordCounter OurIteratorType iter; }; #endif
23.267857
106
0.675365
[ "object" ]
da49c42a9fdff95ef9a0c28f575a68da9d477ecc
2,834
c
C
keymap.c
baudrillardwasright/bdn9
2b240548ab01e41596212f0ab84ac0c2bf696d41
[ "CC0-1.0" ]
null
null
null
keymap.c
baudrillardwasright/bdn9
2b240548ab01e41596212f0ab84ac0c2bf696d41
[ "CC0-1.0" ]
null
null
null
keymap.c
baudrillardwasright/bdn9
2b240548ab01e41596212f0ab84ac0c2bf696d41
[ "CC0-1.0" ]
null
null
null
#include QMK_KEYBOARD_H enum custom_keycodes { SWW = SAFE_RANGE, OBJECT, QKC, PRIV, LETTERHEAD, }; enum encoder_names { _LEFT, _RIGHT, _MIDDLE, }; bool process_record_user(uint16_t keycode, keyrecord_t *record) { switch (keycode) { case SWW: if (record->event.pressed) { SEND_STRING("Subject to and without waiving the above objections, Plaintiff responds as follows:"); } else { case OBJECT: if (record->event.pressed) { SEND_STRING("Plaintiff objects to this Request on the basis that"); } else { case QKC: if (record->event.pressed) { SEND_STRING("qmk compile"SS_TAP(X_ENT)); } else { case PRIV: if (record->event.pressed) { SEND_STRING("Plaintiff objects to this request to the extent that it seeks information which is covered by the attorney-client privilege or the work product privilege."); } else { case LETTERHEAD: if (record->event.pressed) { SEND_STRING(SS_LCTL("j")); } else { } break; { } } } } } } return true; }; const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { // DEBUG LAYER [0] = LAYOUT( TG(1), RESET, DEBUG, KC_MSEL, KC_MSTP, KC_MRWD, KC_MYCM, KC_MPLY, KC_MFFD ), //FTL layer [1] = LAYOUT( TG(2), KC_V, KC_SPACE, KC_1, KC_2, KC_3, KC_X, KC_Z, KC_J ), // hotkey/debug layer [2] = LAYOUT( TO(0), RESET, DEBUG, PRIV, LETTERHEAD, KC_MFFD, OBJECT, SWW, QKC ), }; layer_state_t layer_state_set_user(layer_state_t state) { // Color codes // https://github.com/qmk/qmk_firmware/blob/master/quantum/rgblight_list.h uint8_t layer = biton32(state); switch (layer) { case 0: rgblight_mode(RGBLIGHT_MODE_BREATHING); rgblight_sethsv(213, 255, 255); break; case 1: rgblight_mode(RGBLIGHT_MODE_BREATHING); rgblight_sethsv(85, 255, 255); break; case 2: rgblight_mode(RGBLIGHT_MODE_BREATHING); rgblight_sethsv(128, 255, 255); break; } return state; } void encoder_update_user(uint8_t index, bool clockwise) { if (index == _LEFT) { if (clockwise) { tap_code(KC_VOLD); } else { tap_code(KC_VOLU); } } else if (index == _MIDDLE) { if (clockwise) { tap_code(KC_DOWN); } else { tap_code(KC_UP); } } else if (index == _RIGHT) { if (clockwise) { tap_code(KC_PGDN); } else { tap_code(KC_PGUP); } } }
21.149254
186
0.541284
[ "object" ]
da4ac1d0273da93e13dfccc9a1512c7ec0cc1719
2,849
h
C
media/base/serial_runner.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
media/base/serial_runner.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
media/base/serial_runner.h
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_BASE_SERIAL_RUNNER_H_ #define MEDIA_BASE_SERIAL_RUNNER_H_ #include <memory> #include "base/callback.h" #include "base/containers/circular_deque.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "media/base/media_export.h" #include "media/base/pipeline_status.h" namespace base { class SingleThreadTaskRunner; } namespace media { // Runs a series of bound functions accepting Closures or // PipelineStatusCallback. SerialRunner doesn't use regular // OnceClosure/PipelineStatusCallbacks as it late binds the completion callback // as the series progresses. class MEDIA_EXPORT SerialRunner { public: typedef base::OnceCallback<void(base::OnceClosure)> BoundClosure; typedef base::OnceCallback<void(PipelineStatusCallback)> BoundPipelineStatusCallback; // Serial queue of bound functions to run. class MEDIA_EXPORT Queue { public: Queue(); Queue(Queue&& other); ~Queue(); void Push(base::OnceClosure closure); void Push(BoundClosure bound_fn); void Push(BoundPipelineStatusCallback bound_fn); private: Queue(const Queue&) = delete; Queue& operator=(const Queue&) = delete; friend class SerialRunner; BoundPipelineStatusCallback Pop(); bool empty(); base::circular_deque<BoundPipelineStatusCallback> bound_fns_; }; // Executes the bound functions in series, executing |done_cb| when finished. // // All bound functions are executed on the thread that Run() is called on, // including |done_cb|. // // To eliminate an unnecessary posted task, the first function is executed // immediately on the caller's stack. It is *strongly advised* to ensure // the calling code does no more work after the call to Run(). // // In all cases, |done_cb| is guaranteed to execute on a separate calling // stack. // // Deleting the object will prevent execution of any unstarted bound // functions, including |done_cb|. static std::unique_ptr<SerialRunner> Run(Queue&& bound_fns, PipelineStatusCallback done_cb); private: friend std::default_delete<SerialRunner>; SerialRunner(Queue&& bound_fns, PipelineStatusCallback done_cb); ~SerialRunner(); void RunNextInSeries(PipelineStatus last_status); scoped_refptr<base::SingleThreadTaskRunner> task_runner_; Queue bound_fns_; PipelineStatusCallback done_cb_; // NOTE: Weak pointers must be invalidated before all other member variables. base::WeakPtrFactory<SerialRunner> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(SerialRunner); }; } // namespace media #endif // MEDIA_BASE_SERIAL_RUNNER_H_
29.989474
79
0.740962
[ "object" ]
da4aecb6f144c63be00c575b69f884787ad2fbdd
38,968
h
C
groups/bdl/bdlb/bdlb_indexspanstringutil.h
AlisdairM/bde
bc65db208c32513aa545080f57090cc39c608be0
[ "Apache-2.0" ]
1
2021-11-10T16:53:42.000Z
2021-11-10T16:53:42.000Z
groups/bdl/bdlb/bdlb_indexspanstringutil.h
AlisdairM/bde
bc65db208c32513aa545080f57090cc39c608be0
[ "Apache-2.0" ]
null
null
null
groups/bdl/bdlb/bdlb_indexspanstringutil.h
AlisdairM/bde
bc65db208c32513aa545080f57090cc39c608be0
[ "Apache-2.0" ]
null
null
null
// bdlb_indexspanstringutil.h -*-C++-*- #ifndef INCLUDED_BDLB_INDEXSPANSTRINGUTIL #define INCLUDED_BDLB_INDEXSPANSTRINGUTIL #include <bsls_ident.h> BSLS_IDENT("$Id: $") //@PURPOSE: Provide functions that operate on 'IndexSpan' and string objects. // //@CLASSES: // bdlb::IndexSpanStringUtil: namespace for methods on 'IndexSpan' and strings // //@SEE_ALSO: bdlb_indexspan // //@DESCRIPTION: This component provides a struct, 'IndexSpanStringUtil', that // serves as a namespace for utility functions that operate on 'IndexSpan' and // string objects. This component is designed to work on several // representations of strings, including 'bsl::string', 'bsl::string_view', and // it is also backwards compatible with 'bslstl::StringRef'. Key operations of // this utility include 'bind', for creating a 'bsl::string_view' from an // 'IndexSpan' and a 'string', and the 'create' methods that provide a way to // create 'IndexSpan' objects of a string object (of any kind) using positions // defined by iterators and/or positions and/or length. // ///Usage ///----- // This section illustrates intended use of this component. // ///Example 1: Creating 'IndexSpan' Objects Safely /// - - - - - - - - - - - - - - - - - - - - - - - // Suppose that we are creating a parser, and we want the results of the // parsing to be stored in 'IndexSpan' objects. The parser will have either a // pointer (or "begin" iterator) into the original string input and then // another pointer (or iterator) or a length to identify the end of the input. // Turning the beginning and ending identifiers into an 'IndexSpan' is a simple // calculation, but one that is verbose and potentially error prone. Instead // of implementing the calculation ourselves we use the convenience function // 'create' from 'IndexSpanStringUtil'. // // First, we define a string that we want to parse: //.. // const bsl::string full("James Tiberius Kirk"); //.. // Then, we implement the parsing of the first name: //.. // typedef bsl::string::const_iterator Cit; // Cit it = bsl::find(full.begin(), full.end(), ' '); // // Error checking omitted since we know the string // bdlb::IndexSpan first = bdlb::IndexSpanStringUtil::create(full, // full.begin(), // it); //.. // Next, we implement the parsing of the middle name, this time using length, // rather than an end iterator (demonstrating an alternative 'create' overload // provided by 'IndexSpanStringUtil'): //.. // ++it; // Skip the space // Cit it2 = bsl::find(it, full.end(), ' '); // bdlb::IndexSpan middle; // if (full.end() != it2) { // middle = bdlb::IndexSpanStringUtil::create(full, it, it2 - it); // it = it2 + 1; // } //.. // Then, we create the 'IndexSpan' for the last name, using two positions: //.. // bdlb::IndexSpan last = bdlb::IndexSpanStringUtil::createFromPositions( // full, // it - full.begin(), // full.length()); //.. // Finally, we verify that the resulting 'IndexSpan' objects correctly describe // the parsed names of the 'full' name: //.. // assert(full.substr(first.position(), first.length()) == "James"); // // assert(full.substr(middle.position(), middle.length()) == "Tiberius"); // // assert(full.substr(last.position(), last.length()) == "Kirk"); //.. // ///Example 2: Creating String Views /// - - - - - - - - - - - - - - - - // Suppose that we have 'IndexSpan' objects that define the 'first', 'middle', // and 'last' part of a string that has a full name in it and we want to get // actual string views that correspond to those parts of the string. The // 'bind' functions of 'IndexSpanStringUtil' provide that functionality. The // 'bind' functions return a 'bsl::string_view' into the original string (so // the characters of the string are not copied). Note that this example builds // on Example 1. // // First, we define a string view of the parsed string to show that 'bind' // works both on strings and string views: //.. // const bsl::string_view fullView(full); //.. // Then we demonstrate binding 'IndexSpan' object to that view: //.. // assert(bdlb::IndexSpanStringUtil::bind(fullView, first) == "James"); // // assert(bdlb::IndexSpanStringUtil::bind(fullView, middle) == "Tiberius"); // // assert(bdlb::IndexSpanStringUtil::bind(fullView, last) == "Kirk"); //.. // Finally we demonstrate binding 'IndexSpan' object to a 'bsl::string': //.. // assert(bdlb::IndexSpanStringUtil::bind(full, first) == "James"); // // assert(bdlb::IndexSpanStringUtil::bind(full, middle) == "Tiberius"); // // assert(bdlb::IndexSpanStringUtil::bind(full, last) == "Kirk"); //.. #include <bdlscm_version.h> #include <bdlb_indexspan.h> #include <bsls_assert.h> #include <bsl_functional.h> #include <bsl_string.h> #include <bsl_string_view.h> #include <bsls_libraryfeatures.h> #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR #include <memory_resource> #endif #include <string> namespace BloombergLP { namespace bdlb { // ========================== // struct IndexSpanStringUtil // ========================== struct IndexSpanStringUtil { // This struct serves as a namespace for utility functions that operate on // 'IndexSpan' and string objects. private: // PRIVATE CLASS METHODS template <class CHAR_TYPE, class CHAR_TRAITS> static bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS> bindImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, const IndexSpan& span); // Return a string view to the substring of the specified 'string' as // described by the specified 'span', meaning the substring starting at // the 'span.position()' index in 'string' and having 'span.length()' // characters. The behavior is undefined unless // 'span.position() <= string.length()' and // 'span.position() + span.length() <= string.length()'. template <class CHAR_TYPE, class CHAR_TRAITS> static IndexSpan createFromPosImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, IndexSpan::size_type begin, IndexSpan::size_type end); // Return an 'IndexSpan' describing the substring of the specified // 'string' as starting at the specified 'begin' and ending at the // character preceding the specified 'end'. The behavior is undefined // unless 'begin <= string.end()', 'end <= string.end()', and // 'begin <= end'. template <class CHAR_TYPE, class CHAR_TRAITS> static IndexSpan createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, IndexSpan::size_type begin, IndexSpan::size_type length); // Return an 'IndexSpan' describing the substring of the specified // 'string' as starting at the specified 'begin' and having the // specified 'length'. The behavior is undefined unless // 'begin <= string.length()' and 'begin + length <= string.length()'. template <class CHAR_TYPE, class CHAR_TRAITS> static IndexSpan createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& subString); // Return an 'IndexSpan' describing the substring of the specified // 'string' as defined by the 'begin()' and 'end()' of the specified // 'subString'. The behavior is undefined unless // 'subString.begin() <= string.end()', // 'subString.end() <= string.end()', // 'subString.begin() >= string.begin()', and // 'subString.end() <= string.end()'. template <class CHAR_TYPE, class CHAR_TRAITS> static IndexSpan createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, typename bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>::const_iterator begin, IndexSpan::size_type length); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and having the specified // 'length'. The behavior is undefined unless // 'string.begin() <= begin', 'begin <= string.end()', and // 'begin + length <= string.end()'. template <class CHAR_TYPE, class CHAR_TRAITS> static IndexSpan createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, typename bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>::const_iterator begin, typename bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>::const_iterator end); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and ending (not // including) the specified 'end'. The behavior is undefined unless // 'begin >= string.begin()', 'end >= string.begin()', // 'begin <= string.end()', 'end <= string.end()', and 'begin <= end'. template <class CHAR_TYPE> static IndexSpan createImp( const bslstl::StringRefImp<CHAR_TYPE>& string, typename bslstl::StringRefImp<CHAR_TYPE>::const_iterator begin, IndexSpan::size_type length); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and having the specified // 'length'. The behavior is undefined unless // 'string.begin() <= begin', 'begin <= string.end()', and // 'begin + length <= string.end()'. template <class CHAR_TYPE> static IndexSpan createImp( const bslstl::StringRefImp<CHAR_TYPE>& string, typename bslstl::StringRefImp<CHAR_TYPE>::const_iterator begin, typename bslstl::StringRefImp<CHAR_TYPE>::const_iterator end); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and ending (not // including) the specified 'end'. The behavior is undefined unless // 'begin >= string.begin()', 'end >= string.begin()', // 'begin <= string.end()', 'end <= string.end()', and 'begin <= end'. template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> static IndexSpan createImp( const bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, IndexSpan::size_type length); template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> static IndexSpan createImp( const std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, IndexSpan::size_type length); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and having the specified // 'length'. The behavior is undefined unless // 'begin >= string.begin()', 'begin <= string.end()', and // 'begin + length <= string.end()'. template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> static IndexSpan createImp( const bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, typename bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator end); template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> static IndexSpan createImp( const std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, typename std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator end); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and ending (not // including) the specified 'end'. The behavior is undefined unless // 'begin >= string.begin()', 'begin <= string.end()', // 'end <= string.end()', and 'begin <= end'. public: // CLASS METHODS static bsl::string_view bind(const bsl::string_view& string, const IndexSpan& span); static bsl::wstring_view bind(const bsl::wstring_view& string, const IndexSpan& span); // Return a string reference to the substring of the specified 'string' // as described by the specified 'span', meaning the substring starting // at the 'span.position()' index in 'string' and having // 'span.length()' characters. The behavior is undefined unless // 'span.position() <= string.length()' and // 'span.position() + span.length() <= string.length()'. static IndexSpan createFromPositions(const bsl::string_view& string, IndexSpan::size_type begin, IndexSpan::size_type end); static IndexSpan createFromPositions(const bsl::wstring_view& string, IndexSpan::size_type begin, IndexSpan::size_type end); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and ending (not // including) the specified 'end'. The behavior is undefined unless // 'begin <= string.length()' and 'end <= string.length()'. static IndexSpan create(const bsl::string_view& string, IndexSpan::size_type begin, IndexSpan::size_type length); static IndexSpan create(const bsl::wstring_view& string, IndexSpan::size_type begin, IndexSpan::size_type length); // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and having the specified // 'length'. The behavior is undefined unless // 'begin <= string.length()' and 'begin + length <= string.length()'. static IndexSpan create(const bsl::string_view& string, const bsl::string_view& subString); static IndexSpan create(const bsl::wstring_view& string, const bsl::wstring_view& subString); // Return an 'IndexSpan' describing the substring of the specified // 'string' as defined by the 'begin()' and 'end()' of the specified // 'subString'. The behavior is undefined unless // 'subString.begin() <= string.end()', // 'subString.end() <= string.end()', // 'subString.begin() >= string.begin()', and // 'subString.end() <= string.begin()'. static IndexSpan create(const bsl::string_view& string, bsl::string_view::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const bsl::wstring_view& string, bsl::wstring_view::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const bslstl::StringRef& string, bslstl::StringRef::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const bslstl::StringRefWide& string, bslstl::StringRefWide::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const bsl::string& string, bsl::string::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const bsl::wstring& string, bsl::wstring::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const std::string& string, std::string::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const std::wstring& string, std::wstring::const_iterator begin, IndexSpan::size_type length); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR static IndexSpan create(const std::pmr::string& string, std::pmr::string::const_iterator begin, IndexSpan::size_type length); static IndexSpan create(const std::pmr::wstring& string, std::pmr::wstring::const_iterator begin, IndexSpan::size_type length); #endif // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and having the specified // 'length'. The behavior is undefined unless // 'begin >= string.begin()', 'begin <= string.end()', and // 'begin + length <= string.end()'. static IndexSpan create(const bsl::string_view& string, bsl::string_view::const_iterator begin, bsl::string_view::const_iterator end); static IndexSpan create(const bsl::wstring_view& string, bsl::wstring_view::const_iterator begin, bsl::wstring_view::const_iterator end); static IndexSpan create(const bslstl::StringRef& string, bslstl::StringRef::const_iterator begin, bslstl::StringRef::const_iterator end); static IndexSpan create(const bslstl::StringRefWide& string, bslstl::StringRefWide::const_iterator begin, bslstl::StringRefWide::const_iterator end); static IndexSpan create(const bsl::string& string, bsl::string::const_iterator begin, bsl::string::const_iterator end); static IndexSpan create(const bsl::wstring& string, bsl::wstring::const_iterator begin, bsl::wstring::const_iterator end); static IndexSpan create(const std::string& string, std::string::const_iterator begin, std::string::const_iterator end); static IndexSpan create(const std::wstring& string, std::wstring::const_iterator begin, std::wstring::const_iterator end); #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR static IndexSpan create(const std::pmr::string& string, std::pmr::string::const_iterator begin, std::pmr::string::const_iterator end); static IndexSpan create(const std::pmr::wstring& string, std::pmr::wstring::const_iterator begin, std::pmr::wstring::const_iterator end); #endif // Return an 'IndexSpan' describing the substring of the specified // 'string' starting at the specified 'begin' and ending (not // including) the specified 'end'. The behavior is undefined unless // 'begin >= string.begin()', 'begin <= string.end()', // 'end <= string.end()', and 'begin <= end'. }; // ============================================================================ // INLINE DEFINITIONS // ============================================================================ // -------------------------- // struct IndexSpanStringUtil // -------------------------- // PRIVATE CLASS METHODS template <class CHAR_TYPE, class CHAR_TRAITS> inline bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS> IndexSpanStringUtil::bindImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, const IndexSpan& span) { BSLS_ASSERT(span.position() <= string.length()); BSLS_ASSERT(span.position() + span.length() <= string.length()); return bslstl::StringRefImp<CHAR_TYPE>(string.data() + span.position(), span.length()); } template <class CHAR_TYPE, class CHAR_TRAITS> inline IndexSpan IndexSpanStringUtil::createFromPosImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, IndexSpan::size_type begin, IndexSpan::size_type end) { BSLS_ASSERT(begin <= string.size()); BSLS_ASSERT(end <= string.size()); BSLS_ASSERT(begin <= end); (void)string; // remove unused parameter warnings return IndexSpan(begin, end - begin); } template <class CHAR_TYPE, class CHAR_TRAITS> inline IndexSpan IndexSpanStringUtil::createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, IndexSpan::size_type begin, IndexSpan::size_type length) { BSLS_ASSERT(begin <= string.size()); BSLS_ASSERT(begin + length <= string.size()); (void)string; // remove unused parameter warnings return IndexSpan(begin, length); } template <class CHAR_TYPE, class CHAR_TRAITS> inline IndexSpan IndexSpanStringUtil::createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& subString) { typedef typename bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>::const_pointer const_pointer; bsl::less_equal<const_pointer> lessEqual; bsl::greater_equal<const_pointer> greaterEqual; const_pointer stringBegin = string.data(); const_pointer stringEnd = string.data() + string.length(); const_pointer subStringBegin = subString.data(); const_pointer subStringEnd = subString.data() + subString.length(); // Suppress unused variable warnings (void)lessEqual; (void)greaterEqual; (void)stringEnd; (void)subStringEnd; BSLS_ASSERT(lessEqual( subStringBegin, stringEnd )); BSLS_ASSERT(lessEqual( subStringEnd, stringEnd )); BSLS_ASSERT(greaterEqual(subStringBegin, stringBegin)); BSLS_ASSERT(greaterEqual(subStringEnd, stringBegin)); return IndexSpan(subStringBegin - stringBegin, subString.length()); } template <class CHAR_TYPE, class CHAR_TRAITS> inline IndexSpan IndexSpanStringUtil::createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, typename bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>::const_iterator begin, IndexSpan::size_type length) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= string.end()); BSLS_ASSERT(begin + length <= string.end()); return IndexSpan(begin - string.begin(), length); } template <class CHAR_TYPE, class CHAR_TRAITS> inline IndexSpan IndexSpanStringUtil::createImp( const bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>& string, typename bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>::const_iterator begin, typename bsl::basic_string_view<CHAR_TYPE, CHAR_TRAITS>::const_iterator end) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= end); BSLS_ASSERT(begin <= string.end()); BSLS_ASSERT(end <= string.end()); return IndexSpan(begin - string.begin(), end - begin); } template <class CHAR_TYPE> inline IndexSpan IndexSpanStringUtil::createImp( const bslstl::StringRefImp<CHAR_TYPE>& string, typename bslstl::StringRefImp<CHAR_TYPE>::const_iterator begin, IndexSpan::size_type length) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= string.end() ); BSLS_ASSERT(begin + length <= string.end() ); return IndexSpan(begin - string.begin(), length); } template <class CHAR_TYPE> inline IndexSpan IndexSpanStringUtil::createImp( const bslstl::StringRefImp<CHAR_TYPE>& string, typename bslstl::StringRefImp<CHAR_TYPE>::const_iterator begin, typename bslstl::StringRefImp<CHAR_TYPE>::const_iterator end) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= end ); BSLS_ASSERT(begin <= string.end() ); BSLS_ASSERT(end <= string.end() ); return IndexSpan(begin - string.begin(), end - begin); } template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> inline IndexSpan IndexSpanStringUtil::createImp( const bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, IndexSpan::size_type length) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= string.end()); BSLS_ASSERT(begin + length <= string.end()); return IndexSpan(begin - string.begin(), length); } template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> inline IndexSpan IndexSpanStringUtil::createImp( const std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, IndexSpan::size_type length) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= string.end()); BSLS_ASSERT(begin + length <= string.end()); return IndexSpan(begin - string.begin(), length); } template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> inline IndexSpan IndexSpanStringUtil::createImp( const bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, typename bsl::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator end) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= end); BSLS_ASSERT(begin <= string.end()); BSLS_ASSERT(end <= string.end()); return IndexSpan(begin - string.begin(), end - begin); } template <class CHAR_TYPE, class CHAR_TRAITS, class ALLOCATOR> inline IndexSpan IndexSpanStringUtil::createImp( const std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>& string, typename std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator begin, typename std::basic_string<CHAR_TYPE, CHAR_TRAITS, ALLOCATOR>::const_iterator end) { BSLS_ASSERT(begin >= string.begin()); BSLS_ASSERT(begin <= end); BSLS_ASSERT(begin <= string.end()); BSLS_ASSERT(end <= string.end()); return IndexSpan(begin - string.begin(), end - begin); } // CLASS METHODS inline bsl::string_view IndexSpanStringUtil::bind(const bsl::string_view& string, const IndexSpan& span) { return bindImp(string, span); } inline bsl::wstring_view IndexSpanStringUtil::bind(const bsl::wstring_view& string, const IndexSpan& span) { return bindImp(string, span); } inline IndexSpan IndexSpanStringUtil::createFromPositions(const bsl::string_view& string, IndexSpan::size_type begin, IndexSpan::size_type end) { return createFromPosImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::createFromPositions(const bsl::wstring_view& string, IndexSpan::size_type begin, IndexSpan::size_type end) { return createFromPosImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const bsl::string_view& string, IndexSpan::size_type begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const bsl::wstring_view& string, IndexSpan::size_type begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const bsl::string_view& string, const bsl::string_view& subString) { return createImp(string, subString); } inline IndexSpan IndexSpanStringUtil::create(const bsl::wstring_view& string, const bsl::wstring_view& subString) { return createImp(string, subString); } inline IndexSpan IndexSpanStringUtil::create(const bsl::string_view& string, bsl::string_view::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const bsl::wstring_view& string, bsl::wstring_view::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const bslstl::StringRef& string, bslstl::StringRef::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const bslstl::StringRefWide& string, bslstl::StringRefWide::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const bsl::string& string, bsl::string::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const bsl::wstring& string, bsl::wstring::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const std::string& string, std::string::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const std::wstring& string, std::wstring::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR inline IndexSpan IndexSpanStringUtil::create(const std::pmr::string& string, std::pmr::string::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } inline IndexSpan IndexSpanStringUtil::create(const std::pmr::wstring& string, std::pmr::wstring::const_iterator begin, IndexSpan::size_type length) { return createImp(string, begin, length); } #endif inline IndexSpan IndexSpanStringUtil::create(const bsl::string_view& string, bsl::string_view::const_iterator begin, bsl::string_view::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const bsl::wstring_view& string, bsl::wstring_view::const_iterator begin, bsl::wstring_view::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const bslstl::StringRef& string, bslstl::StringRef::const_iterator begin, bslstl::StringRef::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const bslstl::StringRefWide& string, bslstl::StringRefWide::const_iterator begin, bslstl::StringRefWide::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const bsl::string& string, bsl::string::const_iterator begin, bsl::string::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const bsl::wstring& string, bsl::wstring::const_iterator begin, bsl::wstring::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const std::string& string, std::string::const_iterator begin, std::string::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const std::wstring& string, std::wstring::const_iterator begin, std::wstring::const_iterator end) { return createImp(string, begin, end); } #ifdef BSLS_LIBRARYFEATURES_HAS_CPP17_PMR inline IndexSpan IndexSpanStringUtil::create(const std::pmr::string& string, std::pmr::string::const_iterator begin, std::pmr::string::const_iterator end) { return createImp(string, begin, end); } inline IndexSpan IndexSpanStringUtil::create(const std::pmr::wstring& string, std::pmr::wstring::const_iterator begin, std::pmr::wstring::const_iterator end) { return createImp(string, begin, end); } #endif } // close package namespace } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2021 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
42.356522
79
0.557817
[ "object" ]
da4d3fbfb2914b9e83995cc474622b81cd8b13ef
19,201
c
C
src/graphics/texutils.c
mafu9/dxlibp-kai
dc2e503dd49f019245638e6978ee9a5a107f01fb
[ "Unlicense" ]
1
2020-12-01T20:37:47.000Z
2020-12-01T20:37:47.000Z
src/graphics/texutils.c
mafu9/dxlibp-kai
dc2e503dd49f019245638e6978ee9a5a107f01fb
[ "Unlicense" ]
null
null
null
src/graphics/texutils.c
mafu9/dxlibp-kai
dc2e503dd49f019245638e6978ee9a5a107f01fb
[ "Unlicense" ]
1
2021-04-07T20:31:38.000Z
2021-04-07T20:31:38.000Z
#include <valloc.h> #include <malloc.h> #include <string.h> #include <pspgu.h> #include "dxppng.h" #include"../graphics.h" #include "../fileio.h" DXPTEXTURE3* dxpGraphicsCreateTexture() { u32 i; DXPTEXTURE3 *texptr; for(i = 0;i < DXP_BUILDOPTION_TEXTURE_MAXNUM;++i) if(dxpGraphicsData.texarray[i] == 0)break; if(i == DXP_BUILDOPTION_TEXTURE_MAXNUM)return NULL; texptr = (DXPTEXTURE3*)malloc(sizeof(DXPTEXTURE3)); if(!texptr)return NULL; memset(texptr,0,sizeof(DXPTEXTURE3)); texptr->thisptrptr = &dxpGraphicsData.texarray[i]; dxpGraphicsData.texarray[i] = texptr; return texptr; } int dxpGraphicsReleseTexture(DXPTEXTURE3 *texptr) { if(!texptr)return -1; if(texptr->refcount)return -1; free(texptr->ppalette); free(texptr->texdata); vfree(texptr->texvram); *texptr->thisptrptr = NULL; free(texptr); return 0; } DXPGRAPHICSHANDLE* dxpGraphicsCreateGraphicHandle() { u32 i; DXPGRAPHICSHANDLE *gptr; for(i = 0;i < DXP_BUILDOPTION_GHANDLE_MAXNUM;++i) if(!dxpGraphicsData.grapharray[i])break; if(i == DXP_BUILDOPTION_GHANDLE_MAXNUM)return NULL; gptr = (DXPGRAPHICSHANDLE*)malloc(sizeof(DXPGRAPHICSHANDLE)); if(!gptr)return NULL; memset(gptr,0,sizeof(DXPGRAPHICSHANDLE)); gptr->handle = (int)i; dxpGraphicsData.grapharray[i] = gptr; return gptr; } int dxpGraphicsReleseGraphicHandle(DXPGRAPHICSHANDLE* gptr) { if(!gptr)return -1; if(gptr->tex) { --gptr->tex->refcount; dxpGraphicsReleseTexture(gptr->tex); } dxpGraphicsData.grapharray[gptr->handle] = NULL; free(gptr); return 0; } int dxpGraphicsCalcTexSize(int width,int height,int psm) { height = dxpN_2(height); switch(psm) { case GU_PSM_4444: case GU_PSM_5551: case GU_PSM_5650: case GU_PSM_T16: width = ((width + 7) >> 3) << 3; return width * height * 2; case GU_PSM_8888: case GU_PSM_T32: width = ((width + 3) >> 2) << 2; return width * height * 4; case GU_PSM_DXT1: case GU_PSM_T4: width = ((width + 31) >> 5) << 5; return width * height / 2; case GU_PSM_DXT3: case GU_PSM_DXT5: case GU_PSM_T8: width = ((width + 15) >> 4) << 4; return width * height; } return 0; } static void dxpGraphicsSwizzleFast(u8* out, const u8* in, unsigned int width, unsigned int height) { unsigned int blockx, blocky; unsigned int j; unsigned int width_blocks = (width / 16); unsigned int height_blocks = (height / 8); unsigned int src_pitch = (width-16)/4; unsigned int src_row = width * 8; const u8* ysrc = in; u32* dst = (u32*)out; for (blocky = 0; blocky < height_blocks; ++blocky) { const u8* xsrc = ysrc; for (blockx = 0; blockx < width_blocks; ++blockx) { const u32* src = (u32*)xsrc; for (j = 0; j < 8; ++j)//16byte幅で高さ8の情報を線形に転送 { *(dst++) = *(src++); *(dst++) = *(src++); *(dst++) = *(src++); *(dst++) = *(src++); src += src_pitch; } xsrc += 16; } ysrc += src_row; } } static void dxpGraphicsUnswizzleFast(u8* out, const u8* in, unsigned int width, unsigned int height) { unsigned int blockx, blocky; unsigned int j; unsigned int width_blocks = (width / 16); unsigned int height_blocks = (height / 8); unsigned int src_pitch = (width-16)/4; unsigned int src_row = width * 8; u8* ysrc = out; u32* dst = (u32*)in; for (blocky = 0; blocky < height_blocks; ++blocky) { u8* xsrc = ysrc; for (blockx = 0; blockx < width_blocks; ++blockx) { u32* src = (u32*)xsrc; for (j = 0; j < 8; ++j) { *(src++) = *(dst++); *(src++) = *(dst++); *(src++) = *(dst++); *(src++) = *(dst++); src += src_pitch; } xsrc += 16; } ysrc += src_row; } } int SwizzleGraph(int gh) { GUINITCHECK; GUSYNC; u32 size; DXPTEXTURE3 *texptr = dxpGraphHandle2TexPtr(gh); if(!texptr)return -1; if(texptr->swizzledflag)return 0; size = dxpGraphicsCalcTexSize(texptr->pitch,texptr->height,texptr->psm); if(texptr->texvram) { if(!texptr->texdata)return -1; dxpGraphicsSwizzleFast(texptr->texdata,texptr->texvram,PSM2BYTEX2(texptr->psm) * texptr->pitch / 2,texptr->height); memcpy(texptr->texvram,texptr->texdata,size); } else { const int assertFlag = GetMemoryAssertFlag(); void *buf; SetMemoryAssertFlag(FALSE); buf = malloc(size); SetMemoryAssertFlag(assertFlag); if(!buf)return -1; dxpGraphicsSwizzleFast(buf,texptr->texdata,PSM2BYTEX2(texptr->psm) * texptr->pitch / 2,texptr->height); memcpy(texptr->texdata,buf,size); free(buf); } sceKernelDcacheWritebackAll(); texptr->swizzledflag = 1; texptr->reloadflag = 1; return 0; } int UnswizzleGraph(int gh) { GUINITCHECK; GUSYNC; u32 size; DXPTEXTURE3 *texptr = dxpGraphHandle2TexPtr(gh); if(!texptr)return -1; if(!texptr->swizzledflag)return 0; size = dxpGraphicsCalcTexSize(texptr->pitch,texptr->height,texptr->psm); if(texptr->texvram) { if(!texptr->texdata)return -1; dxpGraphicsUnswizzleFast(texptr->texdata,texptr->texvram,PSM2BYTEX2(texptr->psm) * texptr->pitch / 2,texptr->height); memcpy(texptr->texvram,texptr->texdata,size); } else { const int assertFlag = GetMemoryAssertFlag(); void *buf; SetMemoryAssertFlag(FALSE); buf = malloc(size); SetMemoryAssertFlag(assertFlag); if(!buf)return -1; dxpGraphicsUnswizzleFast(buf,texptr->texdata,PSM2BYTEX2(texptr->psm) * texptr->pitch / 2,texptr->height); memcpy(texptr->texdata,buf,size); free(buf); } sceKernelDcacheWritebackAll(); texptr->swizzledflag = 0; texptr->reloadflag = 1; return 0; } int MoveGraphToVRAM(int gh) { GUINITCHECK; GUSYNC; DXPTEXTURE3 *texptr; int size; texptr = dxpGraphHandle2TexPtr(gh); if(!texptr)return -1; if(texptr->texvram)return 0; size = dxpGraphicsCalcTexSize(texptr->pitch,texptr->height,texptr->psm); texptr->texvram = valloc(size); if(!texptr->texvram)return -1; memcpy(texptr->texvram,texptr->texdata,size); texptr->reloadflag = 1; sceKernelDcacheWritebackAll(); return 0; } int MoveGraphToDDR(int gh) { GUINITCHECK; GUSYNC; //vramあり→vram上のデータを消す //vramなし→なにもしない DXPTEXTURE3 *texptr; int size; texptr = dxpGraphHandle2TexPtr(gh); if(!texptr)return -1; if(!texptr->texvram)return 0; size = dxpGraphicsCalcTexSize(texptr->pitch,texptr->height,texptr->psm); memcpy(texptr->texdata,vCPUPointer(texptr->texvram),size); vfree(texptr->texvram); texptr->texvram = NULL; texptr->reloadflag = 1; sceKernelDcacheWritebackAll(); return 0; } //int UpdateGraphToDDR(int gh) //{ ////vramなし→なにもしない ////vramあり→vramのデータをDDRにコピー // return -1; //} // //int UpdateGraphToVRAM(int gh) //{ ////vramなし→なにもしない ////vramあり→DDRのデータをvramにコピー // return -1; //} /* inline unsigned int AlignPow2( unsigned int a ) { unsigned int i = 1; while ( a > ( i <<= 1 ) ) { if ( !i ) break; } return i; } */ static DXPTEXTURE3* dxpLoadBitmapImage(int fileHandle); static DXPTEXTURE3* dxpLoadJpegImage(int fileHandle); static DXPTEXTURE3* dxpLoadPngImage(int fileHandle); int dxpGraphLoadFromFileHandle(int fileHandle) { GUINITCHECK; DXPGRAPHICSHANDLE *gptr = NULL; DXPTEXTURE3 *texptr = NULL; if(fileHandle == 0)return -1; gptr = dxpGraphicsCreateGraphicHandle(); if(!gptr)return -1; texptr = dxpLoadPngImage(fileHandle); if(texptr) goto success; texptr = dxpLoadJpegImage(fileHandle); if(texptr) goto success; texptr = dxpLoadBitmapImage(fileHandle); if(texptr) goto success; dxpGraphicsReleseGraphicHandle(gptr); return -1; success: gptr->tex = texptr; ++texptr->refcount; gptr->u0 = gptr->v0 = 0; gptr->u1 = texptr->umax; gptr->v1 = texptr->vmax; if(dxpGraphicsData.create_vram_graph)MoveGraphToVRAM(gptr->handle); if(dxpGraphicsData.create_swizzled_graph)SwizzleGraph(gptr->handle); sceKernelDcacheWritebackAll(); return gptr->handle; } /* --------------------------------------------- Bitmap image --------------------------------------------- */ static DXPTEXTURE3* dxpLoadBitmapImage(int fileHandle) { u8 buffer[BMP_HEADER_SIZE]; DXPTEXTURE3 *texptr = dxpGraphicsCreateTexture(); if ( !texptr ) return NULL; //read bitmap header FileRead_seek(fileHandle, 0, SEEK_SET); if ( FileRead_read(buffer, BMP_HEADER_SIZE, fileHandle) != BMP_HEADER_SIZE ) { dxpGraphicsReleseTexture(texptr); return NULL; } //windows bitmap s32 headersize; memcpy(&headersize, buffer + 14, sizeof(s32)); if ( strncmp((const char*)buffer, "BM", 2) || headersize != 40 ) { dxpGraphicsReleseTexture(texptr); return NULL; } //32bit or 24bit s32 bpp; memcpy(&bpp, buffer + 28, sizeof(s32)); bpp = bpp >> 3; if ( !( bpp == 3 || bpp == 4 ) ) { dxpGraphicsReleseTexture(texptr); return NULL; } //bitmap information s32 width, height; memcpy(&width, buffer + 18, sizeof(s32)); memcpy(&height, buffer + 22, sizeof(s32)); int pitch = ((width + 3) >> 2) << 2; int texwidth = AlignPow2(width); int texheight = AlignPow2(height); int bufsize = pitch * texheight * 4; if ( width > 512 || width <= 0 || height > 512 || height <= 0 ) { dxpGraphicsReleseTexture(texptr); return NULL; } u8 *data = (u8*)malloc(bufsize); if ( data == NULL ) { dxpGraphicsReleseTexture(texptr); return NULL; } memset(data, 0, bufsize); //line size unsigned int line_size = width * bpp; if ( (line_size % 4) != 0 ) line_size = ((line_size >> 2) + 1) << 2; int x, y, i; u8 *linedata = (u8 *)malloc(line_size); if ( linedata == NULL ) { for ( y = 0, i = 0; y < height; ++y, i += (pitch - width) * 4 ) { FileRead_seek(fileHandle, BMP_HEADER_SIZE + line_size * (height - (y + 1)), SEEK_SET); for ( x = 0; x < width; ++x ) { FileRead_read(buffer, bpp, fileHandle); data[i++] = buffer[2]; data[i++] = buffer[1]; data[i++] = buffer[0]; data[i++] = 0xFF; } } } else { for ( y = 0, i = 0; y < height; y++, i += (pitch - width) * 4 ) { FileRead_seek(fileHandle, BMP_HEADER_SIZE + line_size * (height - (y + 1)), SEEK_SET); FileRead_read(linedata, line_size, fileHandle); int a; for ( x = 0, a = 0; x < width; x++, a += bpp ) { data[i++] = linedata[a + 2]; data[i++] = linedata[a + 1]; data[i++] = linedata[a + 0]; data[i++] = 0xFF; } } free(linedata); } texptr->texdata = (void *)data; texptr->alphabit = 0; texptr->colorkey = dxpGraphicsData.colorkey; texptr->width = texwidth; texptr->height = texheight; texptr->pitch = pitch; texptr->ppalette = NULL; texptr->psm = PSM_8888; texptr->reloadflag = 1; texptr->size2_nflag = (width == texwidth && height == texheight) ? 1 : 0; texptr->swizzledflag = 0; texptr->texvram = 0; texptr->umax = width; texptr->vmax = height; return texptr; } /* --------------------------------------------- Joint Photographic Experts Group --------------------------------------------- */ static int check_jpeg_header(int fileHandle); #ifdef DXP_BUILDOPTION_USE_LIBJPEG METHODDEF(void) jpeg_init_source(j_decompress_ptr cinfo) { DXPJPEGSRCMGR *src = (DXPJPEGSRCMGR*)cinfo->src; src->startOfFile = TRUE; } METHODDEF(boolean) jpeg_fill_input_buffer(j_decompress_ptr cinfo) { DXPJPEGSRCMGR *src = (DXPJPEGSRCMGR*)cinfo->src; int nbytes = FileRead_read(src->buffer, JPEG_INPUT_BUF_SIZE, src->fileHandle); if(nbytes <= 0) { if(src->startOfFile)ERREXIT(cinfo, JERR_INPUT_EMPTY); /* Treat empty input file as fatal error */ WARNMS(cinfo, JWRN_JPEG_EOF); /* Insert a fake EOI marker */ src->buffer[0] = (JOCTET)0xFF; src->buffer[1] = (JOCTET)JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; src->startOfFile = FALSE; return TRUE; } METHODDEF(void) jpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes) { DXPJPEGSRCMGR *src = (DXPJPEGSRCMGR*)cinfo->src; /* Just a dumb implementation for now. Could use fseek() except * it doesn't work on pipes. Not clear that being smart is worth * any trouble anyway --- large skips are infrequent. */ if(num_bytes > 0) { while(num_bytes > (long) src->pub.bytes_in_buffer) { num_bytes -= (long) src->pub.bytes_in_buffer; jpeg_fill_input_buffer(cinfo); /* note we assume that fill_input_buffer will never return FALSE, * so suspension need not be handled. */ } src->pub.next_input_byte += (size_t)num_bytes; src->pub.bytes_in_buffer -= (size_t)num_bytes; } } METHODDEF(void) jpeg_term_source(j_decompress_ptr cinfo) { /* no work necessary here */ } LOCAL(void) jpeg_dxpio_src(j_decompress_ptr cinfo, int fileHandle) { DXPJPEGSRCMGR *src; /* The source object and input buffer are made permanent so that a series * of JPEG images can be read from the same file by calling jpeg_stdio_src * only before the first one. (If we discarded the buffer at the end of * one image, we'd likely lose the start of the next one.) * This makes it unsafe to use this manager and a different source * manager serially with the same JPEG object. Caveat programmer. */ if (cinfo->src == NULL) /* first time for this JPEG object? */ { cinfo->src = (struct jpeg_source_mgr*)(*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(DXPJPEGSRCMGR)); src = (DXPJPEGSRCMGR*) cinfo->src; src->buffer = (JOCTET*)(*cinfo->mem->alloc_small)((j_common_ptr)cinfo, JPOOL_PERMANENT, JPEG_INPUT_BUF_SIZE * sizeof(JOCTET)); } src = (DXPJPEGSRCMGR*) cinfo->src; src->pub.init_source = jpeg_init_source; src->pub.fill_input_buffer = jpeg_fill_input_buffer; src->pub.skip_input_data = jpeg_skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->pub.term_source = jpeg_term_source; src->fileHandle = fileHandle; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } METHODDEF(void) jpeg_error_exit(j_common_ptr cinfo) { DXPJPEGERRMGR *err = (DXPJPEGERRMGR*)cinfo->err; (*cinfo->err->output_message)(cinfo); longjmp(err->setjmp_buffer, 1); } #endif static DXPTEXTURE3* dxpLoadJpegImage(int fileHandle) { #ifdef DXP_BUILDOPTION_USE_LIBJPEG DXPTEXTURE3 *texptr = dxpGraphicsCreateTexture(); if ( !texptr ) return NULL; int is_jpeg = check_jpeg_header(fileHandle); if ( !is_jpeg ) { dxpGraphicsReleseTexture(texptr); return NULL; } FileRead_seek(fileHandle, 0, SEEK_SET); int y = 0, x = 0, i = 0; struct jpeg_decompress_struct cinfo; DXPJPEGERRMGR jerr; u8 *data = NULL, *linedata = NULL; //read header cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpeg_error_exit; if(setjmp(jerr.setjmp_buffer)) { jpeg_destroy_decompress(&cinfo); free(data); free(linedata); dxpGraphicsReleseTexture(texptr); return NULL; } jpeg_create_decompress(&cinfo); jpeg_dxpio_src(&cinfo, fileHandle); jpeg_read_header(&cinfo, TRUE); jpeg_calc_output_dimensions(&cinfo); jpeg_start_decompress(&cinfo); //jpeg information int width = cinfo.output_width; int height = cinfo.output_height; int pitch = ((width + 3) >> 2) << 2; int texwidth = AlignPow2(width); int texheight = AlignPow2(height); int bufsize = pitch * texheight * 4; if ( width > 512 || height > 512 ) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); dxpGraphicsReleseTexture(texptr); return NULL; } data = (u8*)malloc(bufsize); linedata = (u8*)malloc(3 * width); if ( data == NULL || linedata == NULL ) { if ( data ) free(data); if ( linedata ) free(linedata); jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); dxpGraphicsReleseTexture(texptr); return NULL; } memset(linedata, 0, 3 * width); memset(data, 0, bufsize); for ( i = 0, y = 0; y < height; y++, i += (pitch - width) * 4 ) { jpeg_read_scanlines(&cinfo, &linedata, 1); if(cinfo.out_color_components == 3) // RGB { for ( x = 0; x < width; x++ ) { data[i++] = linedata[x * 3 + 0]; data[i++] = linedata[x * 3 + 1]; data[i++] = linedata[x * 3 + 2]; data[i++] = 0xFF; } } else // (cinfo.out_color_components == 1) // glayscale { for ( x = 0; x < width; x++ ) { data[i++] = linedata[x]; data[i++] = linedata[x]; data[i++] = linedata[x]; data[i++] = 0xFF; } } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(linedata); texptr->texdata = (void *)data; texptr->alphabit = 0; texptr->colorkey = dxpGraphicsData.colorkey; texptr->width = texwidth; texptr->height = texheight; texptr->pitch = pitch; texptr->ppalette = NULL; texptr->psm = PSM_8888; texptr->reloadflag = 1; texptr->size2_nflag = (width == texwidth && height == texheight) ? 1 : 0; texptr->swizzledflag = 0; texptr->texvram = 0; texptr->umax = width; texptr->vmax = height; return texptr; #endif return NULL; } const char jpeg_marker[9][2] = { { 0xFF, 0xD8 }, //SOI { 0xFF, 0xE0 }, //APP0 { 0xFF, 0xDB }, //DQT { 0xFF, 0xC4 }, //DHT { 0xFF, 0xC0 }, //SOF0 { 0xFF, 0xC1 }, //SOF1 { 0xFF, 0xDD }, //DRI { 0xFF, 0xDA }, //SOS { 0xFF, 0xD9 }, //EOI }; static int check_jpeg_header(int fileHandle) { char marker[4] = { 0, }; if ( FileRead_seek(fileHandle, 0, SEEK_SET) != 0 ) return 0; if ( FileRead_read(marker, 4, fileHandle) != 4 ) return 0; if ( strncmp(marker, jpeg_marker[JPEG_MARKER_SOI], 2) != 0 ) return 0; /* char buf[4] unsigned short marker_size; while ( 1 ) { if ( FileRead_read(marker, 2, fileHandle) != 2 ) return 0; if ( !strcmp(marker, jpeg_marker[JPEG_MARKER_APP0]) ) { if ( FileRead_read(&marker_size, 2, fileHandle) != 2 ) return 0; if ( FileRead_read(buf, 4, fileHandle) != 4 ) return 0; if ( strcmp(marker, "JFIF") != 0 ) return 0; if ( FileRead_seek(fileHandle, marker_size - 6, SEEK_CUR) != 0 ) return 0; } else if ( !strcmp(marker, jpeg_marker[JPEG_MARKER_SOS]) ) { break; } else { if ( FileRead_read(&marker_size, 2, fileHandle) != 2 ) return 0; if ( FileRead_seek(fileHandle, marker_size - 2, SEEK_CUR) != 0 ) return 0; } } */ return 1; } static DXPTEXTURE3* dxpLoadPngImage(int fileHandle) { u32 filesize; DXPPNG png; DXPPNG_PARAMS params; void *buf = NULL; DXPTEXTURE3 *texptr = NULL; FileRead_seek(fileHandle, 0, SEEK_END); filesize = FileRead_tell(fileHandle); if(!filesize)return NULL; buf = malloc(filesize); texptr = dxpGraphicsCreateTexture(); if(!buf || !texptr) { free(buf); dxpGraphicsReleseTexture(texptr); return NULL; } FileRead_seek(fileHandle, 0, SEEK_SET); FileRead_read(buf,filesize, fileHandle); params.funcs.pmalloc = malloc; params.funcs.pmemalign = memalign; params.funcs.pfree = free; params.mode = DXPPNG_MODE_GPU; params.src = buf; params.srcLength = filesize; if(dxppng_decode(&params,&png) == -1) { free(buf); dxpGraphicsReleseTexture(texptr); return NULL; } free(buf); texptr->alphabit = png.alpha ? 1 : 0; texptr->colorkey = dxpGraphicsData.colorkey; texptr->width = png.widthN2; texptr->height = png.heightN2; texptr->pitch = png.pitch; texptr->ppalette = (u32 *)png.clut; texptr->psm = png.psm; texptr->reloadflag = 1; texptr->size2_nflag = (png.height == png.heightN2 && png.width == png.widthN2 ? 1 : 0); texptr->swizzledflag = 0; texptr->texdata = png.raw; texptr->texvram = 0; texptr->umax = png.width; texptr->vmax = png.height; return texptr; }
26.017615
128
0.665694
[ "object" ]
da55864a60a51013687f331125607e909a8116d2
3,918
h
C
src/RecordSession.h
cgjones/rr
dcdde9c497cad27618b27f6754c11b0693894178
[ "MIT" ]
3
2015-03-01T23:26:27.000Z
2021-01-14T03:31:36.000Z
src/RecordSession.h
rogerwang/rr
619b8951d392b46c6f62b2bad7c0861a05d9f32e
[ "MIT" ]
null
null
null
src/RecordSession.h
rogerwang/rr
619b8951d392b46c6f62b2bad7c0861a05d9f32e
[ "MIT" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ #ifndef RR_RECORD_SESSION_H_ #define RR_RECORD_SESSION_H_ #include "Scheduler.h" #include "Session.h" #include "task.h" #include "TraceFrame.h" /** Encapsulates additional session state related to recording. */ class RecordSession : public Session { public: typedef std::shared_ptr<RecordSession> shr_ptr; /** * Create a recording session for the initial command line |argv|. */ enum { DISABLE_SYSCALL_BUF = 0x01, CPU_UNBOUND = 0x02 }; static shr_ptr create(const std::vector<std::string>& argv, uint32_t flags = 0); bool use_syscall_buffer() const { return use_syscall_buffer_; } void set_ignore_sig(int ignore_sig) { this->ignore_sig = ignore_sig; } int get_ignore_sig() const { return ignore_sig; } enum RecordStatus { // Some execution was recorded. record_step() can be called again. STEP_CONTINUE, // All tracees are dead. record_step() should not be called again. STEP_EXITED, // Initial exec of the tracee failed. STEP_EXEC_FAILED, // Required performance counter features not detected. STEP_PERF_COUNTERS_UNAVAILABLE }; struct RecordResult { RecordStatus status; // When status == STEP_EXITED int exit_code; }; /** * Record some tracee execution. * This may block. If blocking is interrupted by a signal, will return * STEP_CONTINUE. * Typically you'd call this in a loop until it returns something other than * STEP_CONTINUE. * Note that when this returns, some tasks may be running (not in a ptrace- * stop). In particular, up to one task may be executing user code and any * number of tasks may be blocked in syscalls. */ RecordResult record_step(); /** * Flush buffers and write a termination record to the trace. Don't call * record_step() after this. */ void terminate_recording(); virtual RecordSession* as_record() { return this; } TraceWriter& trace_writer() { return trace_out; } virtual void on_destroy(Task* t); Scheduler& scheduler() { return scheduler_; } private: RecordSession(const std::vector<std::string>& argv, const std::vector<std::string>& envp, const std::string& cwd, uint32_t flags); virtual void on_create(Task* t); enum ContinueType { DONT_CONTINUE = 0, CONTINUE, CONTINUE_SYSCALL }; struct StepState { // Continue with this continuation type. ContinueType continue_type; // If continuing, inject this signal int continue_sig; StepState(ContinueType continue_type) : continue_type(continue_type), continue_sig(0) {} }; void check_perf_counters_working(Task* t, RecordResult* step_result); bool handle_ptrace_event(Task* t, StepState* step_state); bool handle_signal_event(Task* t, StepState* step_state); void runnable_state_changed(Task* t, RecordResult* step_result, bool can_consume_wait_status, StepState* step_state); void signal_state_changed(Task* t, StepState* step_state); void syscall_state_changed(Task* t, StepState* step_state); void desched_state_changed(Task* t); bool prepare_to_inject_signal(Task* t, StepState* step_state); void task_continue(Task* t, const StepState& step_state); TraceWriter trace_out; Scheduler scheduler_; Task* last_recorded_task; TaskGroup::shr_ptr initial_task_group; int ignore_sig; Switchable last_task_switchable; bool use_syscall_buffer_; /* True when it's safe to deliver signals, namely, when the initial * tracee has exec()'d the tracee image. Before then, the address * space layout will not be the same during replay as recording, so * replay won't be able to find the right execution point to deliver * the signal. */ bool can_deliver_signals; }; #endif // RR_RECORD_SESSION_H_
32.114754
80
0.703165
[ "vector" ]
da6881d5bc1bfe49c6ae36571133c12ee24865ae
62,130
h
C
src/UnitTests/Matrices/MultidiagonalMatrixTest.h
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
src/UnitTests/Matrices/MultidiagonalMatrixTest.h
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
src/UnitTests/Matrices/MultidiagonalMatrixTest.h
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <TNL/Devices/Host.h> #include <TNL/Matrices/Matrix.h> #include <TNL/Matrices/MultidiagonalMatrix.h> #include <TNL/Algorithms/contains.h> #include <TNL/Containers/Array.h> #include <TNL/Containers/Vector.h> #include <TNL/Containers/VectorView.h> #include <TNL/Math.h> using Multidiagonal_host_float = TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Host, int >; using Multidiagonal_host_int = TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Host, int >; using Multidiagonal_cuda_float = TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Cuda, int >; using Multidiagonal_cuda_int = TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Cuda, int >; static const char* TEST_FILE_NAME = "test_MultidiagonalMatrixTest.tnl"; #ifdef HAVE_GTEST #include <type_traits> #include <gtest/gtest.h> void test_GetSerializationType() { using namespace TNL::Algorithms::Segments; EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Host, int, RowMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< float, [any_device], int, RowMajorOrder, [any_allocator], [any_allocator] >" ) ); EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Host, int, RowMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< int, [any_device], int, RowMajorOrder, [any_allocator], [any_allocator] >" ) ); EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Cuda, int, RowMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< float, [any_device], int, RowMajorOrder, [any_allocator], [any_allocator] >" ) ); EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Cuda, int, RowMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< int, [any_device], int, RowMajorOrder, [any_allocator], [any_allocator] >" ) ); EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Host, int, ColumnMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< float, [any_device], int, ColumnMajorOrder, [any_allocator], [any_allocator] >" ) ); EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Host, int, ColumnMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< int, [any_device], int, ColumnMajorOrder, [any_allocator], [any_allocator] >" ) ); EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Cuda, int, ColumnMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< float, [any_device], int, ColumnMajorOrder, [any_allocator], [any_allocator] >" ) ); EXPECT_EQ( ( TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Cuda, int, ColumnMajorOrder >::getSerializationType() ), TNL::String( "Matrices::MultidiagonalMatrix< int, [any_device], int, ColumnMajorOrder, [any_allocator], [any_allocator] >" ) ); } template< typename Matrix > void test_SetDimensions() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; const IndexType rows = 9; const IndexType cols = 8; const DiagonalsOffsetsType diagonalsOffsets{ -3, -1, 0, 2, 4 }; Matrix m; m.setDimensions( rows, cols, diagonalsOffsets ); EXPECT_EQ( m.getRows(), 9 ); EXPECT_EQ( m.getColumns(), 8 ); } template< typename Matrix > void test_SetDiagonalsOffsets() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; const IndexType rows = 9; const IndexType cols = 8; const DiagonalsOffsetsType diagonalsOffsets{ -3, -1, 0, 2, 4 }; Matrix m; m.setDimensions( rows, cols ); m.setDiagonalsOffsets( diagonalsOffsets ); EXPECT_EQ( m.getRows(), 9 ); EXPECT_EQ( m.getColumns(), 8 ); } template< typename Matrix > void test_SetDiagonalsOffsets_initalizer_list() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; const IndexType rows = 9; const IndexType cols = 8; Matrix m; m.setDimensions( rows, cols ); m.setDiagonalsOffsets( { -3, -1, 0, 2, 4 } ); EXPECT_EQ( m.getRows(), 9 ); EXPECT_EQ( m.getColumns(), 8 ); } template< typename Matrix1, typename Matrix2 > void test_SetLike() { using RealType = typename Matrix1::RealType; using DeviceType = typename Matrix1::DeviceType; using IndexType = typename Matrix1::IndexType; using DiagonalsOffsetsType = typename Matrix1::DiagonalsOffsetsType; const IndexType rows = 8; const IndexType cols = 7; const DiagonalsOffsetsType diagonalsOffsets{ -3, -1, 0, 2, 4 }; Matrix1 m1; m1.setDimensions( rows + 1, cols + 2, diagonalsOffsets ); Matrix2 m2; m2.setDimensions( rows, cols, diagonalsOffsets ); m1.setLike( m2 ); EXPECT_EQ( m1.getRows(), m2.getRows() ); EXPECT_EQ( m1.getColumns(), m2.getColumns() ); } template< typename Matrix > void test_SetElements() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; const int gridSize( 4 ); const int matrixSize( gridSize * gridSize ); Matrix matrix( matrixSize, matrixSize, { - gridSize, -1, 0, 1, gridSize } ); matrix.setElements( { { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { -1.0, -1.0, 4.0, -1.0, -1.0 }, { -1.0, -1.0, 4.0, -1.0, -1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { -1.0, -1.0, 4.0, -1.0, -1.0 }, { -1.0, -1.0, 4.0, -1.0, -1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 1.0 } } ); for( int i = 0; i < gridSize; i++ ) for( int j = 0; j < gridSize; j++ ) { const int elementIdx = i * gridSize + j; if( i == 0 || j == 0 || i == gridSize - 1 || j == gridSize - 1 ) // check matrix elements corresponding to boundary grid nodes { for( int k = 0; k < matrixSize; k++ ) { if( elementIdx == k ) EXPECT_EQ( matrix.getElement( elementIdx, k ), 1.0 ); else EXPECT_EQ( matrix.getElement( elementIdx, k ), 0.0 ); } } else // check matrix elements corresponding to inner grid nodes { for( int k = 0; k < matrixSize; k++ ) { if( k == elementIdx - gridSize || k == elementIdx - 1 || k == elementIdx + 1 || k == elementIdx + gridSize ) EXPECT_EQ( matrix.getElement( elementIdx, k ), -1.0 ); else if( k == elementIdx ) EXPECT_EQ( matrix.getElement( elementIdx, k ), 4.0 ); else EXPECT_EQ( matrix.getElement( elementIdx, k ), 0.0 ); } } } } template< typename Matrix > void test_GetCompressedRowLengths() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 8x8 matrix: * * / 0 0 0 1 0 1 0 0 \ -> 2 * | 0 1 0 0 1 0 1 0 | -> 3 * | 1 0 1 0 0 1 0 1 | -> 4 * | 0 1 0 1 0 0 1 0 | -> 3 * | 0 0 1 0 1 0 0 1 | -> 3 * | 0 0 0 1 0 1 0 0 | -> 2 * | 0 0 0 0 1 0 1 0 | -> 2 * \ 0 0 0 0 0 1 0 0 / -> 1 */ const IndexType rows = 8; const IndexType cols = 8; Matrix m( rows, cols, DiagonalsOffsetsType({ -2, 0, 3, 5 }) ); m.setValue( 1.0 ); m.setElement( 0, 0, 0.0 ); m.setElement( 7, 7, 0.0 ); typename Matrix::RowsCapacitiesType rowLengths( rows ); rowLengths = 0; m.getCompressedRowLengths( rowLengths ); typename Matrix::RowsCapacitiesType correctRowLengths{ 2, 3, 4, 3, 3, 2, 2, 1 }; EXPECT_EQ( rowLengths, correctRowLengths ); } template< typename Matrix > void test_GetAllocatedElementsCount() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; //const IndexType rows = 7; //const IndexType cols = 6; Matrix m1( 7, 6, DiagonalsOffsetsType( { -2, 0, 3, 5 } ) ); EXPECT_EQ( m1.getAllocatedElementsCount(), 28 ); Matrix m2( 8, 6, DiagonalsOffsetsType( { -2, 0, 3, 5 } ) ); EXPECT_EQ( m2.getAllocatedElementsCount(), 32 ); Matrix m3( 9, 6, DiagonalsOffsetsType( { -2, 0, 3, 5 } ) ); EXPECT_EQ( m3.getAllocatedElementsCount(), 32 ); } template< typename Matrix > void test_GetNonzeroElementsCount() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 7x6 matrix: * * / 0 0 1 0 1 0 \ -> 2 * | 0 1 0 1 0 1 | -> 3 * | 0 0 1 0 1 0 | -> 2 * | 1 0 0 1 0 1 | -> 3 * | 0 1 0 0 1 0 | -> 2 * | 0 0 1 0 0 1 | -> 2 * \ 0 0 0 1 0 0 / -> 1 * ---- * 15 */ const IndexType rows = 7; const IndexType cols = 6; Matrix m( rows, cols, DiagonalsOffsetsType( { -3, 0, 2, 4 } ) ); m.setValue( 1.0 ); m.setElement( 0, 0, 0.0 ); EXPECT_EQ( m.getNonzeroElementsCount(), 15 ); } template< typename Matrix > void test_Reset() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 5x4 matrix: * * / 0 0 0 0 \ * | 0 0 0 0 | * | 0 0 0 0 | * | 0 0 0 0 | * \ 0 0 0 0 / */ const IndexType rows = 5; const IndexType cols = 4; Matrix m( rows, cols, DiagonalsOffsetsType( { 0, 1, 2, 4 } ) ); m.reset(); EXPECT_EQ( m.getRows(), 0 ); EXPECT_EQ( m.getColumns(), 0 ); } template< typename Matrix > void test_SetValue() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 7x6 matrix: * * / 1 0 1 0 1 0 \ * | 0 1 0 1 0 1 | * | 0 0 1 0 1 0 | * | 1 0 0 1 0 1 | * | 0 1 0 0 1 0 | * | 0 0 1 0 0 1 | * \ 0 0 0 1 0 0 / */ const IndexType rows = 7; const IndexType cols = 6; Matrix m( rows, cols, DiagonalsOffsetsType( { -3, 0, 2, 4 } ) ); m.setValue( 1.0 ); EXPECT_EQ( m.getElement( 0, 0 ), 1 ); EXPECT_EQ( m.getElement( 0, 1 ), 0 ); EXPECT_EQ( m.getElement( 0, 2 ), 1 ); EXPECT_EQ( m.getElement( 0, 3 ), 0 ); EXPECT_EQ( m.getElement( 0, 4 ), 1 ); EXPECT_EQ( m.getElement( 0, 5 ), 0 ); EXPECT_EQ( m.getElement( 1, 0 ), 0 ); EXPECT_EQ( m.getElement( 1, 1 ), 1 ); EXPECT_EQ( m.getElement( 1, 2 ), 0 ); EXPECT_EQ( m.getElement( 1, 3 ), 1 ); EXPECT_EQ( m.getElement( 1, 4 ), 0 ); EXPECT_EQ( m.getElement( 1, 5 ), 1 ); EXPECT_EQ( m.getElement( 2, 0 ), 0 ); EXPECT_EQ( m.getElement( 2, 1 ), 0 ); EXPECT_EQ( m.getElement( 2, 2 ), 1 ); EXPECT_EQ( m.getElement( 2, 3 ), 0 ); EXPECT_EQ( m.getElement( 2, 4 ), 1 ); EXPECT_EQ( m.getElement( 2, 5 ), 0 ); EXPECT_EQ( m.getElement( 3, 0 ), 1 ); EXPECT_EQ( m.getElement( 3, 1 ), 0 ); EXPECT_EQ( m.getElement( 3, 2 ), 0 ); EXPECT_EQ( m.getElement( 3, 3 ), 1 ); EXPECT_EQ( m.getElement( 3, 4 ), 0 ); EXPECT_EQ( m.getElement( 3, 5 ), 1 ); EXPECT_EQ( m.getElement( 4, 0 ), 0 ); EXPECT_EQ( m.getElement( 4, 1 ), 1 ); EXPECT_EQ( m.getElement( 4, 2 ), 0 ); EXPECT_EQ( m.getElement( 4, 3 ), 0 ); EXPECT_EQ( m.getElement( 4, 4 ), 1 ); EXPECT_EQ( m.getElement( 4, 5 ), 0 ); EXPECT_EQ( m.getElement( 5, 0 ), 0 ); EXPECT_EQ( m.getElement( 5, 1 ), 0 ); EXPECT_EQ( m.getElement( 5, 2 ), 1 ); EXPECT_EQ( m.getElement( 5, 3 ), 0 ); EXPECT_EQ( m.getElement( 5, 4 ), 0 ); EXPECT_EQ( m.getElement( 5, 5 ), 1 ); EXPECT_EQ( m.getElement( 6, 0 ), 0 ); EXPECT_EQ( m.getElement( 6, 1 ), 0 ); EXPECT_EQ( m.getElement( 6, 2 ), 0 ); EXPECT_EQ( m.getElement( 6, 3 ), 1 ); EXPECT_EQ( m.getElement( 6, 4 ), 0 ); EXPECT_EQ( m.getElement( 6, 5 ), 0 ); } template< typename Matrix > void test_SetElement() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 5x5 matrix: * * / 1 2 0 0 5 \ * | 0 7 8 0 0 | * | 0 0 13 14 0 | * | 16 0 0 19 20 | * \ 0 22 0 0 25 / */ const IndexType rows = 5; const IndexType cols = 5; DiagonalsOffsetsType diagonals{-3, 0, 1, 4 }; Matrix m( rows, cols, diagonals ); RealType value = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++ ) if( TNL::Algorithms::contains( diagonals, j - i ) ) m.setElement( i, j, value++ ); else { EXPECT_THROW( m.setElement( i, j, value++ ), std::logic_error ); } EXPECT_EQ( m.getElement( 0, 0 ), 1 ); EXPECT_EQ( m.getElement( 0, 1 ), 2 ); EXPECT_EQ( m.getElement( 0, 2 ), 0 ); EXPECT_EQ( m.getElement( 0, 3 ), 0 ); EXPECT_EQ( m.getElement( 0, 4 ), 5 ); EXPECT_EQ( m.getElement( 1, 0 ), 0 ); EXPECT_EQ( m.getElement( 1, 1 ), 7 ); EXPECT_EQ( m.getElement( 1, 2 ), 8 ); EXPECT_EQ( m.getElement( 1, 3 ), 0 ); EXPECT_EQ( m.getElement( 1, 4 ), 0 ); EXPECT_EQ( m.getElement( 2, 0 ), 0 ); EXPECT_EQ( m.getElement( 2, 1 ), 0 ); EXPECT_EQ( m.getElement( 2, 2 ), 13 ); EXPECT_EQ( m.getElement( 2, 3 ), 14 ); EXPECT_EQ( m.getElement( 2, 4 ), 0 ); EXPECT_EQ( m.getElement( 3, 0 ), 16 ); EXPECT_EQ( m.getElement( 3, 1 ), 0 ); EXPECT_EQ( m.getElement( 3, 2 ), 0 ); EXPECT_EQ( m.getElement( 3, 3 ), 19 ); EXPECT_EQ( m.getElement( 3, 4 ), 20 ); EXPECT_EQ( m.getElement( 4, 0 ), 0 ); EXPECT_EQ( m.getElement( 4, 1 ), 22 ); EXPECT_EQ( m.getElement( 4, 2 ), 0 ); EXPECT_EQ( m.getElement( 4, 3 ), 0 ); EXPECT_EQ( m.getElement( 4, 4 ), 25 ); } template< typename Matrix > void test_AddElement() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 5x5 matrix: * * / 1 2 0 0 5 \ * | 0 7 8 0 0 | * | 0 0 13 14 0 | * | 0 0 0 19 20 | * \ 0 0 0 0 25 / */ const IndexType rows = 5; const IndexType cols = 5; DiagonalsOffsetsType diagonals{-3, 0, 1, 4 }; Matrix m( rows, cols, diagonals ); RealType value = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++ ) if( TNL::Algorithms::contains( diagonals, j - i ) ) { if( j >= i ) m.setElement( i, j, value ); value++; } else { EXPECT_THROW( m.setElement( i, j, value++ ), std::logic_error ); } // Check the added elements EXPECT_EQ( m.getElement( 0, 0 ), 1 ); EXPECT_EQ( m.getElement( 0, 1 ), 2 ); EXPECT_EQ( m.getElement( 0, 2 ), 0 ); EXPECT_EQ( m.getElement( 0, 3 ), 0 ); EXPECT_EQ( m.getElement( 0, 4 ), 5 ); EXPECT_EQ( m.getElement( 1, 0 ), 0 ); EXPECT_EQ( m.getElement( 1, 1 ), 7 ); EXPECT_EQ( m.getElement( 1, 2 ), 8 ); EXPECT_EQ( m.getElement( 1, 3 ), 0 ); EXPECT_EQ( m.getElement( 1, 4 ), 0 ); EXPECT_EQ( m.getElement( 2, 0 ), 0 ); EXPECT_EQ( m.getElement( 2, 1 ), 0 ); EXPECT_EQ( m.getElement( 2, 2 ), 13 ); EXPECT_EQ( m.getElement( 2, 3 ), 14 ); EXPECT_EQ( m.getElement( 2, 4 ), 0 ); EXPECT_EQ( m.getElement( 3, 0 ), 0 ); EXPECT_EQ( m.getElement( 3, 1 ), 0 ); EXPECT_EQ( m.getElement( 3, 2 ), 0 ); EXPECT_EQ( m.getElement( 3, 3 ), 19 ); EXPECT_EQ( m.getElement( 3, 4 ), 20 ); EXPECT_EQ( m.getElement( 4, 0 ), 0 ); EXPECT_EQ( m.getElement( 4, 1 ), 0 ); EXPECT_EQ( m.getElement( 4, 2 ), 0 ); EXPECT_EQ( m.getElement( 4, 3 ), 0 ); EXPECT_EQ( m.getElement( 4, 4 ), 25 ); // Add new elements to the old elements with a multiplying factor applied to the old elements. /* * The following setup results in the following 6x5 matrix: * * / 1 2 0 0 5 \ / 1 2 0 0 5 \ / 3 6 0 0 15 \ * | 0 7 8 0 0 | | 0 7 8 0 0 | | 0 21 24 0 0 | * 2 * | 0 0 13 14 0 | + | 0 0 13 14 0 | = | 0 0 39 42 0 | * | 0 0 0 19 20 | | 16 0 0 19 20 | | 16 0 0 57 60 | * \ 0 0 0 0 25 / \ 0 22 0 0 25 / \ 0 22 0 0 75 / * */ value = 1; RealType multiplicator = 2; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++ ) if( TNL::Algorithms::contains( diagonals, j - i ) ) m.addElement( i, j, value++, multiplicator ); else { EXPECT_THROW( m.addElement( i, j, value++, multiplicator ), std::logic_error ); } EXPECT_EQ( m.getElement( 0, 0 ), 3 ); EXPECT_EQ( m.getElement( 0, 1 ), 6 ); EXPECT_EQ( m.getElement( 0, 2 ), 0 ); EXPECT_EQ( m.getElement( 0, 3 ), 0 ); EXPECT_EQ( m.getElement( 0, 4 ), 15 ); EXPECT_EQ( m.getElement( 1, 0 ), 0 ); EXPECT_EQ( m.getElement( 1, 1 ), 21 ); EXPECT_EQ( m.getElement( 1, 2 ), 24 ); EXPECT_EQ( m.getElement( 1, 3 ), 0 ); EXPECT_EQ( m.getElement( 1, 4 ), 0 ); EXPECT_EQ( m.getElement( 2, 0 ), 0 ); EXPECT_EQ( m.getElement( 2, 1 ), 0 ); EXPECT_EQ( m.getElement( 2, 2 ), 39 ); EXPECT_EQ( m.getElement( 2, 3 ), 42 ); EXPECT_EQ( m.getElement( 2, 4 ), 0 ); EXPECT_EQ( m.getElement( 3, 0 ), 16 ); EXPECT_EQ( m.getElement( 3, 1 ), 0 ); EXPECT_EQ( m.getElement( 3, 2 ), 0 ); EXPECT_EQ( m.getElement( 3, 3 ), 57 ); EXPECT_EQ( m.getElement( 3, 4 ), 60 ); EXPECT_EQ( m.getElement( 4, 0 ), 0 ); EXPECT_EQ( m.getElement( 4, 1 ), 22 ); EXPECT_EQ( m.getElement( 4, 2 ), 0 ); EXPECT_EQ( m.getElement( 4, 3 ), 0 ); EXPECT_EQ( m.getElement( 4, 4 ), 75 ); } template< typename Matrix > void test_SetRow() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 5x7 matrix: * * / 1 0 2 0 3 0 0 \ * | 4 5 0 6 0 7 0 | * | 0 8 9 0 10 0 11 | * | 0 0 12 13 0 14 0 | * \ 0 0 0 15 16 0 17 / */ const IndexType rows = 5; const IndexType cols = 7; Matrix m( rows, cols, DiagonalsOffsetsType({ -1, 0, 2, 4 }) ); auto matrix_view = m.getView(); auto f = [=] __cuda_callable__ ( IndexType rowIdx ) mutable { RealType values[ 5 ][ 4 ] { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 }, { 12, 13, 14, 0 }, { 15, 16, 17, 0 } }; auto row = matrix_view.getRow( rowIdx ); for( IndexType i = 0; i < 4; i++ ) row.setElement( i, values[ rowIdx ][ i ] ); }; TNL::Algorithms::ParallelFor< DeviceType >::exec( ( IndexType) 0, rows, f ); EXPECT_EQ( m.getElement( 0, 0 ), 1 ); EXPECT_EQ( m.getElement( 0, 1 ), 0 ); EXPECT_EQ( m.getElement( 0, 2 ), 2 ); EXPECT_EQ( m.getElement( 0, 3 ), 0 ); EXPECT_EQ( m.getElement( 0, 4 ), 3 ); EXPECT_EQ( m.getElement( 0, 5 ), 0 ); EXPECT_EQ( m.getElement( 0, 6 ), 0 ); EXPECT_EQ( m.getElement( 1, 0 ), 4 ); EXPECT_EQ( m.getElement( 1, 1 ), 5 ); EXPECT_EQ( m.getElement( 1, 2 ), 0 ); EXPECT_EQ( m.getElement( 1, 3 ), 6 ); EXPECT_EQ( m.getElement( 1, 4 ), 0 ); EXPECT_EQ( m.getElement( 1, 5 ), 7 ); EXPECT_EQ( m.getElement( 1, 6 ), 0 ); EXPECT_EQ( m.getElement( 2, 0 ), 0 ); EXPECT_EQ( m.getElement( 2, 1 ), 8 ); EXPECT_EQ( m.getElement( 2, 2 ), 9 ); EXPECT_EQ( m.getElement( 2, 3 ), 0 ); EXPECT_EQ( m.getElement( 2, 4 ), 10 ); EXPECT_EQ( m.getElement( 2, 5 ), 0 ); EXPECT_EQ( m.getElement( 2, 6 ), 11 ); EXPECT_EQ( m.getElement( 3, 0 ), 0 ); EXPECT_EQ( m.getElement( 3, 1 ), 0 ); EXPECT_EQ( m.getElement( 3, 2 ), 12 ); EXPECT_EQ( m.getElement( 3, 3 ), 13 ); EXPECT_EQ( m.getElement( 3, 4 ), 0 ); EXPECT_EQ( m.getElement( 3, 5 ), 14 ); EXPECT_EQ( m.getElement( 3, 6 ), 0 ); EXPECT_EQ( m.getElement( 4, 0 ), 0 ); EXPECT_EQ( m.getElement( 4, 1 ), 0 ); EXPECT_EQ( m.getElement( 4, 2 ), 0 ); EXPECT_EQ( m.getElement( 4, 3 ), 15 ); EXPECT_EQ( m.getElement( 4, 4 ), 16 ); EXPECT_EQ( m.getElement( 4, 5 ), 0 ); EXPECT_EQ( m.getElement( 4, 6 ), 17 ); } template< typename Matrix > void test_AddRow() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 6x5 matrix: * * / 1 2 3 0 0 \ * | 0 7 8 9 0 | * | 0 0 13 14 15 | * | 0 0 0 19 20 | * | 0 0 0 0 25 | * \ 0 0 0 0 0 / */ const IndexType rows = 6; const IndexType cols = 5; DiagonalsOffsetsType diagonals( { -2, 0, 1, 2 } ); Matrix m( rows, cols, diagonals ); RealType value = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++ ) { IndexType offset = j - i; if( TNL::Algorithms::contains( diagonals, offset ) && offset >= 0) m.setElement( i, j, value ); value++; } // Check the added elements EXPECT_EQ( m.getElement( 0, 0 ), 1 ); EXPECT_EQ( m.getElement( 0, 1 ), 2 ); EXPECT_EQ( m.getElement( 0, 2 ), 3 ); EXPECT_EQ( m.getElement( 0, 3 ), 0 ); EXPECT_EQ( m.getElement( 0, 4 ), 0 ); EXPECT_EQ( m.getElement( 1, 0 ), 0 ); EXPECT_EQ( m.getElement( 1, 1 ), 7 ); EXPECT_EQ( m.getElement( 1, 2 ), 8 ); EXPECT_EQ( m.getElement( 1, 3 ), 9 ); EXPECT_EQ( m.getElement( 1, 4 ), 0 ); EXPECT_EQ( m.getElement( 2, 0 ), 0 ); EXPECT_EQ( m.getElement( 2, 1 ), 0 ); EXPECT_EQ( m.getElement( 2, 2 ), 13 ); EXPECT_EQ( m.getElement( 2, 3 ), 14 ); EXPECT_EQ( m.getElement( 2, 4 ), 15 ); EXPECT_EQ( m.getElement( 3, 0 ), 0 ); EXPECT_EQ( m.getElement( 3, 1 ), 0 ); EXPECT_EQ( m.getElement( 3, 2 ), 0 ); EXPECT_EQ( m.getElement( 3, 3 ), 19 ); EXPECT_EQ( m.getElement( 3, 4 ), 20 ); EXPECT_EQ( m.getElement( 4, 0 ), 0 ); EXPECT_EQ( m.getElement( 4, 1 ), 0 ); EXPECT_EQ( m.getElement( 4, 2 ), 0 ); EXPECT_EQ( m.getElement( 4, 3 ), 0 ); EXPECT_EQ( m.getElement( 4, 4 ), 25 ); EXPECT_EQ( m.getElement( 5, 0 ), 0 ); EXPECT_EQ( m.getElement( 5, 1 ), 0 ); EXPECT_EQ( m.getElement( 5, 2 ), 0 ); EXPECT_EQ( m.getElement( 5, 3 ), 0 ); EXPECT_EQ( m.getElement( 5, 4 ), 0 ); // Add new elements to the old elements with a multiplying factor applied to the old elements. /* * The following setup results in the following 6x5 sparse matrix: * * / 0 0 0 0 0 0 \ / 1 2 3 0 0 \ / 11 0 0 0 0 \ / 11 0 0 0 0 \ * | 0 1 0 0 0 0 | | 0 7 8 9 0 | | 0 22 0 0 0 | | 0 29 8 9 0 | * | 0 0 2 0 0 0 | * | 0 0 13 14 15 | + | 33 0 33 0 0 | = | 33 0 59 28 30 | * | 0 0 0 3 0 0 | | 0 0 0 19 20 | | 0 44 0 44 0 | | 0 44 0 101 60 | * | 0 0 0 0 4 0 | | 0 0 0 0 25 | | 0 0 55 0 55 | | 0 0 55 0 155 | * \ 0 0 0 0 0 5 / \ 0 0 0 0 0 / \ 0 0 0 66 0 / \ 0 0 0 66 0 / */ auto matrix_view = m.getView(); auto f = [=] __cuda_callable__ ( IndexType rowIdx ) mutable { RealType values[ 6 ][ 4 ] { { 0, 11, 0, 0 }, { 0, 22, 0, 0 }, { 33, 33, 0, 0 }, { 44, 44, 0, 0 }, { 55, 55, 0, 0 }, { 66, 0, 0, 0 } }; auto row = matrix_view.getRow( rowIdx ); for( IndexType i = 0; i < 4; i++ ) { RealType& val = row.getValue( i ); val = rowIdx * val + values[ rowIdx ][ i ]; } }; TNL::Algorithms::ParallelFor< DeviceType >::exec( 0, 6, f ); EXPECT_EQ( m.getElement( 0, 0 ), 11 ); EXPECT_EQ( m.getElement( 0, 1 ), 0 ); EXPECT_EQ( m.getElement( 0, 2 ), 0 ); EXPECT_EQ( m.getElement( 0, 3 ), 0 ); EXPECT_EQ( m.getElement( 0, 4 ), 0 ); EXPECT_EQ( m.getElement( 1, 0 ), 0 ); EXPECT_EQ( m.getElement( 1, 1 ), 29 ); EXPECT_EQ( m.getElement( 1, 2 ), 8 ); EXPECT_EQ( m.getElement( 1, 3 ), 9 ); EXPECT_EQ( m.getElement( 1, 4 ), 0 ); EXPECT_EQ( m.getElement( 2, 0 ), 33 ); EXPECT_EQ( m.getElement( 2, 1 ), 0 ); EXPECT_EQ( m.getElement( 2, 2 ), 59 ); EXPECT_EQ( m.getElement( 2, 3 ), 28 ); EXPECT_EQ( m.getElement( 2, 4 ), 30 ); EXPECT_EQ( m.getElement( 3, 0 ), 0 ); EXPECT_EQ( m.getElement( 3, 1 ), 44 ); EXPECT_EQ( m.getElement( 3, 2 ), 0 ); EXPECT_EQ( m.getElement( 3, 3 ), 101 ); EXPECT_EQ( m.getElement( 3, 4 ), 60 ); EXPECT_EQ( m.getElement( 4, 0 ), 0 ); EXPECT_EQ( m.getElement( 4, 1 ), 0 ); EXPECT_EQ( m.getElement( 4, 2 ), 55 ); EXPECT_EQ( m.getElement( 4, 3 ), 0 ); EXPECT_EQ( m.getElement( 4, 4 ), 155 ); EXPECT_EQ( m.getElement( 5, 0 ), 0 ); EXPECT_EQ( m.getElement( 5, 1 ), 0 ); EXPECT_EQ( m.getElement( 5, 2 ), 0 ); EXPECT_EQ( m.getElement( 5, 3 ), 66 ); EXPECT_EQ( m.getElement( 5, 4 ), 0 ); } template< typename Matrix > void test_ForRows() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; /** * Prepare lambda matrix of the following form: * * / 1 -2 0 0 0 \ * | -2 1 -2 0 0 | * | 0 -2 1 -2 0 | * | 0 0 -2 1 -2 | * \ 0 0 0 -2 1 / */ const IndexType size( 5 ); Matrix m( size, size, { -1, 0, 1 } ); ///// // Test without iterator auto f = [=] __cuda_callable__ ( typename Matrix::RowView& row ) mutable { const IndexType rowIdx = row.getRowIndex(); if( rowIdx > 0 ) row.setElement( 0, -2.0 ); row.setElement( 1, 1.0 ); if( rowIdx < size -1 ) row.setElement( 2, -2.0 ); }; m.forAllRows( f ); for( IndexType row = 0; row < size; row++ ) for( IndexType column = 0; column < size; column++ ) { const IndexType diff = row - column; if( diff == 0 ) EXPECT_EQ( m.getElement( row, column ), 1.0 ); else if( diff == 1 && row > 0 ) EXPECT_EQ( m.getElement( row, column ), -2.0 ); else if( diff == -1 && row < size - 1 ) EXPECT_EQ( m.getElement( row, column ), -2.0 ); else EXPECT_EQ( m.getElement( row, column ), 0.0 ); } ///// // Test with iterator m.getValues() = 0.0; auto f_iter = [=] __cuda_callable__ ( typename Matrix::RowView& row ) mutable { for( auto element : row ) { if( element.rowIndex() > 0 && element.localIndex() == 0 ) element.value() = -2.0; if( element.localIndex() == 1 ) element.value() = 1.0; if( element.rowIndex() < size - 1 && element.localIndex() == 2 ) element.value() = -2.0; } }; m.forAllRows( f_iter ); for( IndexType row = 0; row < size; row++ ) for( IndexType column = 0; column < size; column++ ) { const IndexType diff = row - column; if( diff == 0 ) EXPECT_EQ( m.getElement( row, column ), 1.0 ); else if( diff == 1 && row > 0 ) EXPECT_EQ( m.getElement( row, column ), -2.0 ); else if( diff == -1 && row < size - 1 ) EXPECT_EQ( m.getElement( row, column ), -2.0 ); else EXPECT_EQ( m.getElement( row, column ), 0.0 ); } } template< typename Matrix > void test_VectorProduct() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 5x4 matrix: * * / 1 0 3 0 \ * | 0 6 0 8 | * | 9 0 11 0 | * | 0 14 0 16 | * \ 0 0 19 0 / */ const IndexType rows = 5; const IndexType cols = 4; DiagonalsOffsetsType diagonals{ -2, 0, 2 }; Matrix m( rows, cols, diagonals ); RealType value = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++) { if( TNL::Algorithms::contains( diagonals, j - i ) ) m.setElement( i, j, value ); value++; } using VectorType = TNL::Containers::Vector< RealType, DeviceType, IndexType >; VectorType inVector( 4 ); inVector = 2; VectorType outVector( 5 ); outVector = 0; m.vectorProduct( inVector, outVector); EXPECT_EQ( outVector.getElement( 0 ), 8 ); EXPECT_EQ( outVector.getElement( 1 ), 28 ); EXPECT_EQ( outVector.getElement( 2 ), 40 ); EXPECT_EQ( outVector.getElement( 3 ), 60 ); EXPECT_EQ( outVector.getElement( 4 ), 38 ); } template< typename Matrix1, typename Matrix2 = Matrix1 > void test_AddMatrix() { using RealType = typename Matrix1::RealType; using DeviceType = typename Matrix1::DeviceType; using IndexType = typename Matrix1::IndexType; using DiagonalsOffsetsType1 = typename Matrix1::DiagonalsOffsetsType; using DiagonalsOffsetsType2 = typename Matrix2::DiagonalsOffsetsType; /* * Sets up the following 5x4 matrix: * * / 1 2 0 0 \ * | 5 6 7 0 | * | 0 10 11 12 | * | 0 0 15 16 | * \ 0 0 0 20 / */ const IndexType rows = 5; const IndexType cols = 4; DiagonalsOffsetsType1 diagonals1; DiagonalsOffsetsType2 diagonals2; Matrix1 m( rows, cols, diagonals1 ); RealType value = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++) { if( abs( i - j ) <= 1 ) m.setElement( i, j, value ); value++; } /* * Sets up the following 5x4 matrix: * * / 1 2 0 0 \ * | 3 4 5 0 | * | 0 6 7 8 | * | 0 0 9 10 | * \ 0 0 0 11 / */ Matrix2 m2( rows, cols, diagonals2 ); RealType newValue = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++) if( abs( i - j ) <= 1 ) m2.setElement( i, j, newValue++ ); /* * Compute the following 5x4 matrix: * * / 1 2 0 0 \ / 1 2 0 0 \ / 3 6 0 0 \ * | 5 6 7 0 | | 3 4 5 0 | | 11 14 17 0 | * | 0 10 11 12 | + 2 * | 0 6 7 8 | = | 0 22 25 28 | * | 0 0 15 16 | | 0 0 9 10 | | 0 0 33 36 | * \ 0 0 0 20 / \ 0 0 0 11 / \ 0 0 0 42 / */ Matrix1 mResult; mResult.reset(); mResult.setDimensions( rows, cols ); mResult = m; RealType matrixMultiplicator = 2; RealType thisMatrixMultiplicator = 1; mResult.addMatrix( m2, matrixMultiplicator, thisMatrixMultiplicator ); EXPECT_EQ( mResult.getElement( 0, 0 ), matrixMultiplicator * m2.getElement( 0, 0 ) + thisMatrixMultiplicator * m.getElement( 0, 0 ) ); EXPECT_EQ( mResult.getElement( 0, 1 ), matrixMultiplicator * m2.getElement( 0, 1 ) + thisMatrixMultiplicator * m.getElement( 0, 1 ) ); EXPECT_EQ( mResult.getElement( 0, 2 ), matrixMultiplicator * m2.getElement( 0, 2 ) + thisMatrixMultiplicator * m.getElement( 0, 2 ) ); EXPECT_EQ( mResult.getElement( 0, 3 ), matrixMultiplicator * m2.getElement( 0, 3 ) + thisMatrixMultiplicator * m.getElement( 0, 3 ) ); EXPECT_EQ( mResult.getElement( 1, 0 ), matrixMultiplicator * m2.getElement( 1, 0 ) + thisMatrixMultiplicator * m.getElement( 1, 0 ) ); EXPECT_EQ( mResult.getElement( 1, 1 ), matrixMultiplicator * m2.getElement( 1, 1 ) + thisMatrixMultiplicator * m.getElement( 1, 1 ) ); EXPECT_EQ( mResult.getElement( 1, 2 ), matrixMultiplicator * m2.getElement( 1, 2 ) + thisMatrixMultiplicator * m.getElement( 1, 2 ) ); EXPECT_EQ( mResult.getElement( 1, 3 ), matrixMultiplicator * m2.getElement( 1, 3 ) + thisMatrixMultiplicator * m.getElement( 1, 3 ) ); EXPECT_EQ( mResult.getElement( 2, 0 ), matrixMultiplicator * m2.getElement( 2, 0 ) + thisMatrixMultiplicator * m.getElement( 2, 0 ) ); EXPECT_EQ( mResult.getElement( 2, 1 ), matrixMultiplicator * m2.getElement( 2, 1 ) + thisMatrixMultiplicator * m.getElement( 2, 1 ) ); EXPECT_EQ( mResult.getElement( 2, 2 ), matrixMultiplicator * m2.getElement( 2, 2 ) + thisMatrixMultiplicator * m.getElement( 2, 2 ) ); EXPECT_EQ( mResult.getElement( 2, 3 ), matrixMultiplicator * m2.getElement( 2, 3 ) + thisMatrixMultiplicator * m.getElement( 2, 3 ) ); EXPECT_EQ( mResult.getElement( 3, 0 ), matrixMultiplicator * m2.getElement( 3, 0 ) + thisMatrixMultiplicator * m.getElement( 3, 0 ) ); EXPECT_EQ( mResult.getElement( 3, 1 ), matrixMultiplicator * m2.getElement( 3, 1 ) + thisMatrixMultiplicator * m.getElement( 3, 1 ) ); EXPECT_EQ( mResult.getElement( 3, 2 ), matrixMultiplicator * m2.getElement( 3, 2 ) + thisMatrixMultiplicator * m.getElement( 3, 2 ) ); EXPECT_EQ( mResult.getElement( 3, 3 ), matrixMultiplicator * m2.getElement( 3, 3 ) + thisMatrixMultiplicator * m.getElement( 3, 3 ) ); EXPECT_EQ( mResult.getElement( 4, 0 ), matrixMultiplicator * m2.getElement( 4, 0 ) + thisMatrixMultiplicator * m.getElement( 4, 0 ) ); EXPECT_EQ( mResult.getElement( 4, 1 ), matrixMultiplicator * m2.getElement( 4, 1 ) + thisMatrixMultiplicator * m.getElement( 4, 1 ) ); EXPECT_EQ( mResult.getElement( 4, 2 ), matrixMultiplicator * m2.getElement( 4, 2 ) + thisMatrixMultiplicator * m.getElement( 4, 2 ) ); EXPECT_EQ( mResult.getElement( 4, 3 ), matrixMultiplicator * m2.getElement( 4, 3 ) + thisMatrixMultiplicator * m.getElement( 4, 3 ) ); EXPECT_EQ( mResult.getElement( 0, 0 ), 3 ); EXPECT_EQ( mResult.getElement( 0, 1 ), 6 ); EXPECT_EQ( mResult.getElement( 0, 2 ), 0 ); EXPECT_EQ( mResult.getElement( 0, 3 ), 0 ); EXPECT_EQ( mResult.getElement( 1, 0 ), 11 ); EXPECT_EQ( mResult.getElement( 1, 1 ), 14 ); EXPECT_EQ( mResult.getElement( 1, 2 ), 17 ); EXPECT_EQ( mResult.getElement( 1, 3 ), 0 ); EXPECT_EQ( mResult.getElement( 2, 0 ), 0 ); EXPECT_EQ( mResult.getElement( 2, 1 ), 22 ); EXPECT_EQ( mResult.getElement( 2, 2 ), 25 ); EXPECT_EQ( mResult.getElement( 2, 3 ), 28 ); EXPECT_EQ( mResult.getElement( 3, 0 ), 0 ); EXPECT_EQ( mResult.getElement( 3, 1 ), 0 ); EXPECT_EQ( mResult.getElement( 3, 2 ), 33 ); EXPECT_EQ( mResult.getElement( 3, 3 ), 36 ); EXPECT_EQ( mResult.getElement( 4, 0 ), 0 ); EXPECT_EQ( mResult.getElement( 4, 1 ), 0 ); EXPECT_EQ( mResult.getElement( 4, 2 ), 0 ); EXPECT_EQ( mResult.getElement( 4, 3 ), 42 ); } template< typename Matrix > void test_GetMatrixProduct() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 5x4 matrix: * * / 1 2 3 4 \ * | 5 6 7 8 | * | 9 10 11 12 | * | 13 14 15 16 | * \ 17 18 19 20 / */ const IndexType leftRows = 5; const IndexType leftCols = 4; DiagonalsOffsetsType diagonalsOffsets( { 0, 1, 2 } ); Matrix leftMatrix( leftRows, leftCols, diagonalsOffsets ); RealType value = 1; for( IndexType i = 0; i < leftRows; i++ ) for( IndexType j = 0; j < leftCols; j++) leftMatrix.setElement( i, j, value++ ); /* * Sets up the following 4x5 matrix: * * / 1 2 3 4 5 \ * | 6 7 8 9 10 | * | 11 12 13 14 15 | * \ 16 17 18 19 20 / */ const IndexType rightRows = 4; const IndexType rightCols = 5; Matrix rightMatrix; rightMatrix.reset(); rightMatrix.setDimensions( rightRows, rightCols ); RealType newValue = 1; for( IndexType i = 0; i < rightRows; i++ ) for( IndexType j = 0; j < rightCols; j++) rightMatrix.setElement( i, j, newValue++ ); /* * Sets up the following 5x5 resulting matrix: * * / 0 0 0 0 \ * | 0 0 0 0 | * | 0 0 0 0 | * | 0 0 0 0 | * \ 0 0 0 0 / */ Matrix mResult( leftRows, rightCols, diagonalsOffsets ); mResult.setValue( 0 ); RealType leftMatrixMultiplicator = 1; RealType rightMatrixMultiplicator = 2; /* * / 1 2 3 4 \ / 220 240 260 280 300 \ * | 5 6 7 8 | / 1 2 3 4 5 \ | 492 544 596 648 700 | * 1 * | 9 10 11 12 | * 2 * | 6 7 8 9 10 | = | 764 848 932 1016 1100 | * | 13 14 15 16 | | 11 12 13 14 15 | | 1036 1152 1268 1384 1500 | * \ 17 18 19 20 / \ 16 17 18 19 20 / \ 1308 1456 1604 1752 1900 / */ mResult.getMatrixProduct( leftMatrix, rightMatrix, leftMatrixMultiplicator, rightMatrixMultiplicator ); EXPECT_EQ( mResult.getElement( 0, 0 ), 220 ); EXPECT_EQ( mResult.getElement( 0, 1 ), 240 ); EXPECT_EQ( mResult.getElement( 0, 2 ), 260 ); EXPECT_EQ( mResult.getElement( 0, 3 ), 280 ); EXPECT_EQ( mResult.getElement( 0, 4 ), 300 ); EXPECT_EQ( mResult.getElement( 1, 0 ), 492 ); EXPECT_EQ( mResult.getElement( 1, 1 ), 544 ); EXPECT_EQ( mResult.getElement( 1, 2 ), 596 ); EXPECT_EQ( mResult.getElement( 1, 3 ), 648 ); EXPECT_EQ( mResult.getElement( 1, 4 ), 700 ); EXPECT_EQ( mResult.getElement( 2, 0 ), 764 ); EXPECT_EQ( mResult.getElement( 2, 1 ), 848 ); EXPECT_EQ( mResult.getElement( 2, 2 ), 932 ); EXPECT_EQ( mResult.getElement( 2, 3 ), 1016 ); EXPECT_EQ( mResult.getElement( 2, 4 ), 1100 ); EXPECT_EQ( mResult.getElement( 3, 0 ), 1036 ); EXPECT_EQ( mResult.getElement( 3, 1 ), 1152 ); EXPECT_EQ( mResult.getElement( 3, 2 ), 1268 ); EXPECT_EQ( mResult.getElement( 3, 3 ), 1384 ); EXPECT_EQ( mResult.getElement( 3, 4 ), 1500 ); EXPECT_EQ( mResult.getElement( 4, 0 ), 1308 ); EXPECT_EQ( mResult.getElement( 4, 1 ), 1456 ); EXPECT_EQ( mResult.getElement( 4, 2 ), 1604 ); EXPECT_EQ( mResult.getElement( 4, 3 ), 1752 ); EXPECT_EQ( mResult.getElement( 4, 4 ), 1900 ); } template< typename Matrix > void test_GetTransposition() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 3x2 matrix: * * / 1 2 \ * | 3 4 | * \ 5 6 / */ const IndexType rows = 3; const IndexType cols = 2; DiagonalsOffsetsType diagonalsOffsets( { 0, 1, 2 } ); Matrix m( rows, cols, diagonalsOffsets ); RealType value = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++ ) m.setElement( i, j, value++ ); m.print( std::cout ); /* * Sets up the following 2x3 matrix: * * / 0 0 0 \ * \ 0 0 0 / */ Matrix mTransposed( cols, rows, diagonalsOffsets ); mTransposed.print( std::cout ); RealType matrixMultiplicator = 1; mTransposed.getTransposition( m, matrixMultiplicator ); mTransposed.print( std::cout ); /* * Should result in the following 2x3 matrix: * * / 1 3 5 \ * \ 2 4 6 / */ EXPECT_EQ( mTransposed.getElement( 0, 0 ), 1 ); EXPECT_EQ( mTransposed.getElement( 0, 1 ), 3 ); EXPECT_EQ( mTransposed.getElement( 0, 2 ), 5 ); EXPECT_EQ( mTransposed.getElement( 1, 0 ), 2 ); EXPECT_EQ( mTransposed.getElement( 1, 1 ), 4 ); EXPECT_EQ( mTransposed.getElement( 1, 2 ), 6 ); } template< typename Matrix > void test_PerformSORIteration() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 4x4 matrix: * * / 4 1 1 1 \ * | 1 4 1 1 | * | 1 1 4 1 | * \ 1 1 1 4 / */ const IndexType rows = 4; const IndexType cols = 4; DiagonalsOffsetsType diagonalsOffsets( { 0, 1, 2 } ); Matrix m( rows, cols, diagonalsOffsets ); m.setElement( 0, 0, 4.0 ); // 0th row m.setElement( 0, 1, 1.0 ); m.setElement( 0, 2, 1.0 ); m.setElement( 0, 3, 1.0 ); m.setElement( 1, 0, 1.0 ); // 1st row m.setElement( 1, 1, 4.0 ); m.setElement( 1, 2, 1.0 ); m.setElement( 1, 3, 1.0 ); m.setElement( 2, 0, 1.0 ); m.setElement( 2, 1, 1.0 ); // 2nd row m.setElement( 2, 2, 4.0 ); m.setElement( 2, 3, 1.0 ); m.setElement( 3, 0, 1.0 ); // 3rd row m.setElement( 3, 1, 1.0 ); m.setElement( 3, 2, 1.0 ); m.setElement( 3, 3, 4.0 ); RealType bVector [ 4 ] = { 1.0, 1.0, 1.0, 1.0 }; RealType xVector [ 4 ] = { 1.0, 1.0, 1.0, 1.0 }; IndexType row = 0; RealType omega = 1; m.performSORIteration( bVector, row++, xVector, omega); EXPECT_EQ( xVector[ 0 ], -0.5 ); EXPECT_EQ( xVector[ 1 ], 1.0 ); EXPECT_EQ( xVector[ 2 ], 1.0 ); EXPECT_EQ( xVector[ 3 ], 1.0 ); m.performSORIteration( bVector, row++, xVector, omega); EXPECT_EQ( xVector[ 0 ], -0.5 ); EXPECT_EQ( xVector[ 1 ], -0.125 ); EXPECT_EQ( xVector[ 2 ], 1.0 ); EXPECT_EQ( xVector[ 3 ], 1.0 ); m.performSORIteration( bVector, row++, xVector, omega); EXPECT_EQ( xVector[ 0 ], -0.5 ); EXPECT_EQ( xVector[ 1 ], -0.125 ); EXPECT_EQ( xVector[ 2 ], 0.15625 ); EXPECT_EQ( xVector[ 3 ], 1.0 ); m.performSORIteration( bVector, row++, xVector, omega); EXPECT_EQ( xVector[ 0 ], -0.5 ); EXPECT_EQ( xVector[ 1 ], -0.125 ); EXPECT_EQ( xVector[ 2 ], 0.15625 ); EXPECT_EQ( xVector[ 3 ], 0.3671875 ); } template< typename Matrix > void test_AssignmentOperator() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; constexpr TNL::Algorithms::Segments::ElementsOrganization organization = Matrix::getOrganization(); using MultidiagonalHost = TNL::Matrices::MultidiagonalMatrix< RealType, TNL::Devices::Host, IndexType, organization >; using MultidiagonalCuda = TNL::Matrices::MultidiagonalMatrix< RealType, TNL::Devices::Cuda, IndexType, organization == TNL::Algorithms::Segments::RowMajorOrder ? TNL::Algorithms::Segments::ColumnMajorOrder : TNL::Algorithms::Segments::RowMajorOrder >; const IndexType rows( 10 ), columns( 10 ); DiagonalsOffsetsType diagonalsOffsets( { -4, -2, 0, 2, 3, 5 } ); MultidiagonalHost hostMatrix( rows, columns, diagonalsOffsets ); for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < columns; j++ ) if( TNL::Algorithms::contains( diagonalsOffsets, j - i ) ) hostMatrix.setElement( i, j, i + j ); Matrix matrix( rows, columns, diagonalsOffsets ); matrix.getValues() = 0.0; matrix = hostMatrix; for( IndexType i = 0; i < columns; i++ ) for( IndexType j = 0; j < rows; j++ ) if( TNL::Algorithms::contains( diagonalsOffsets, j - i ) ) EXPECT_EQ( matrix.getElement( i, j ), i + j ); else EXPECT_EQ( matrix.getElement( i, j ), 0.0 ); #ifdef HAVE_CUDA MultidiagonalCuda cudaMatrix( rows, columns, diagonalsOffsets ); for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < columns; j++ ) if( TNL::Algorithms::contains( diagonalsOffsets, j - i ) ) cudaMatrix.setElement( i, j, i + j ); matrix.getValues() = 0.0; matrix = cudaMatrix; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < columns; j++ ) { if( TNL::Algorithms::contains( diagonalsOffsets, j - i ) ) EXPECT_EQ( matrix.getElement( i, j ), i + j ); else EXPECT_EQ( matrix.getElement( i, j ), 0.0 ); } #endif } template< typename Matrix > void test_SaveAndLoad() { using RealType = typename Matrix::RealType; using DeviceType = typename Matrix::DeviceType; using IndexType = typename Matrix::IndexType; using DiagonalsOffsetsType = typename Matrix::DiagonalsOffsetsType; /* * Sets up the following 4x4 matrix: * * / 1 2 0 0 \ * | 5 6 7 0 | * | 0 10 11 12 | * \ 0 0 15 16 / */ const IndexType rows = 4; const IndexType cols = 4; DiagonalsOffsetsType diagonalsOffsets( { -1, 0, 1 } ); Matrix savedMatrix( rows, cols, diagonalsOffsets ); RealType value = 1; for( IndexType i = 0; i < rows; i++ ) for( IndexType j = 0; j < cols; j++ ) { if( TNL::Algorithms::contains( diagonalsOffsets, j - i ) ) savedMatrix.setElement( i, j, value ); value++; } ASSERT_NO_THROW( savedMatrix.save( TEST_FILE_NAME ) ); Matrix loadedMatrix; ASSERT_NO_THROW( loadedMatrix.load( TEST_FILE_NAME ) ); EXPECT_EQ( savedMatrix.getElement( 0, 0 ), loadedMatrix.getElement( 0, 0 ) ); EXPECT_EQ( savedMatrix.getElement( 0, 1 ), loadedMatrix.getElement( 0, 1 ) ); EXPECT_EQ( savedMatrix.getElement( 0, 2 ), loadedMatrix.getElement( 0, 2 ) ); EXPECT_EQ( savedMatrix.getElement( 0, 3 ), loadedMatrix.getElement( 0, 3 ) ); EXPECT_EQ( savedMatrix.getElement( 1, 0 ), loadedMatrix.getElement( 1, 0 ) ); EXPECT_EQ( savedMatrix.getElement( 1, 1 ), loadedMatrix.getElement( 1, 1 ) ); EXPECT_EQ( savedMatrix.getElement( 1, 2 ), loadedMatrix.getElement( 1, 2 ) ); EXPECT_EQ( savedMatrix.getElement( 1, 3 ), loadedMatrix.getElement( 1, 3 ) ); EXPECT_EQ( savedMatrix.getElement( 2, 0 ), loadedMatrix.getElement( 2, 0 ) ); EXPECT_EQ( savedMatrix.getElement( 2, 1 ), loadedMatrix.getElement( 2, 1 ) ); EXPECT_EQ( savedMatrix.getElement( 2, 2 ), loadedMatrix.getElement( 2, 2 ) ); EXPECT_EQ( savedMatrix.getElement( 2, 3 ), loadedMatrix.getElement( 2, 3 ) ); EXPECT_EQ( savedMatrix.getElement( 3, 0 ), loadedMatrix.getElement( 3, 0 ) ); EXPECT_EQ( savedMatrix.getElement( 3, 1 ), loadedMatrix.getElement( 3, 1 ) ); EXPECT_EQ( savedMatrix.getElement( 3, 2 ), loadedMatrix.getElement( 3, 2 ) ); EXPECT_EQ( savedMatrix.getElement( 3, 3 ), loadedMatrix.getElement( 3, 3 ) ); EXPECT_EQ( savedMatrix.getElement( 0, 0 ), 1 ); EXPECT_EQ( savedMatrix.getElement( 0, 1 ), 2 ); EXPECT_EQ( savedMatrix.getElement( 0, 2 ), 0 ); EXPECT_EQ( savedMatrix.getElement( 0, 3 ), 0 ); EXPECT_EQ( savedMatrix.getElement( 1, 0 ), 5 ); EXPECT_EQ( savedMatrix.getElement( 1, 1 ), 6 ); EXPECT_EQ( savedMatrix.getElement( 1, 2 ), 7 ); EXPECT_EQ( savedMatrix.getElement( 1, 3 ), 0 ); EXPECT_EQ( savedMatrix.getElement( 2, 0 ), 0 ); EXPECT_EQ( savedMatrix.getElement( 2, 1 ), 10 ); EXPECT_EQ( savedMatrix.getElement( 2, 2 ), 11 ); EXPECT_EQ( savedMatrix.getElement( 2, 3 ), 12 ); EXPECT_EQ( savedMatrix.getElement( 3, 0 ), 0 ); EXPECT_EQ( savedMatrix.getElement( 3, 1 ), 0 ); EXPECT_EQ( savedMatrix.getElement( 3, 2 ), 15 ); EXPECT_EQ( savedMatrix.getElement( 3, 3 ), 16 ); } // test fixture for typed tests template< typename Matrix > class MatrixTest : public ::testing::Test { protected: using MatrixType = Matrix; }; // types for which MatrixTest is instantiated using MatrixTypes = ::testing::Types < TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Host, short >, TNL::Matrices::MultidiagonalMatrix< long, TNL::Devices::Host, short >, TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Host, short >, TNL::Matrices::MultidiagonalMatrix< double, TNL::Devices::Host, short >, TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Host, int >, TNL::Matrices::MultidiagonalMatrix< long, TNL::Devices::Host, int >, TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Host, int >, TNL::Matrices::MultidiagonalMatrix< double, TNL::Devices::Host, int >, TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Host, long >, TNL::Matrices::MultidiagonalMatrix< long, TNL::Devices::Host, long >, TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Host, long >, TNL::Matrices::MultidiagonalMatrix< double, TNL::Devices::Host, long > #ifdef HAVE_CUDA ,TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Cuda, short >, TNL::Matrices::MultidiagonalMatrix< long, TNL::Devices::Cuda, short >, TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Cuda, short >, TNL::Matrices::MultidiagonalMatrix< double, TNL::Devices::Cuda, short >, TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Cuda, int >, TNL::Matrices::MultidiagonalMatrix< long, TNL::Devices::Cuda, int >, TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Cuda, int >, TNL::Matrices::MultidiagonalMatrix< double, TNL::Devices::Cuda, int >, TNL::Matrices::MultidiagonalMatrix< int, TNL::Devices::Cuda, long >, TNL::Matrices::MultidiagonalMatrix< long, TNL::Devices::Cuda, long >, TNL::Matrices::MultidiagonalMatrix< float, TNL::Devices::Cuda, long >, TNL::Matrices::MultidiagonalMatrix< double, TNL::Devices::Cuda, long > #endif >; TYPED_TEST_SUITE( MatrixTest, MatrixTypes ); TYPED_TEST( MatrixTest, getSerializationType ) { test_GetSerializationType(); } TYPED_TEST( MatrixTest, setDimensionsTest ) { using MatrixType = typename TestFixture::MatrixType; test_SetDimensions< MatrixType >(); } TYPED_TEST( MatrixTest, setLikeTest ) { using MatrixType = typename TestFixture::MatrixType; test_SetLike< MatrixType, MatrixType >(); } TYPED_TEST( MatrixTest, setElements ) { using MatrixType = typename TestFixture::MatrixType; test_SetElements< MatrixType >(); } TYPED_TEST( MatrixTest, getCompressedRowLengthTest ) { using MatrixType = typename TestFixture::MatrixType; test_GetCompressedRowLengths< MatrixType >(); } TYPED_TEST( MatrixTest, getAllocatedElementsCountTest ) { using MatrixType = typename TestFixture::MatrixType; test_GetAllocatedElementsCount< MatrixType >(); } TYPED_TEST( MatrixTest, getNumberOfNonzeroMatrixElementsTest ) { using MatrixType = typename TestFixture::MatrixType; test_GetNonzeroElementsCount< MatrixType >(); } TYPED_TEST( MatrixTest, resetTest ) { using MatrixType = typename TestFixture::MatrixType; test_Reset< MatrixType >(); } TYPED_TEST( MatrixTest, setValueTest ) { using MatrixType = typename TestFixture::MatrixType; test_SetValue< MatrixType >(); } TYPED_TEST( MatrixTest, setElementTest ) { using MatrixType = typename TestFixture::MatrixType; test_SetElement< MatrixType >(); } TYPED_TEST( MatrixTest, addElementTest ) { using MatrixType = typename TestFixture::MatrixType; test_AddElement< MatrixType >(); } TYPED_TEST( MatrixTest, setRowTest ) { using MatrixType = typename TestFixture::MatrixType; test_SetRow< MatrixType >(); } TYPED_TEST( MatrixTest, addRowTest ) { using MatrixType = typename TestFixture::MatrixType; test_AddRow< MatrixType >(); } TYPED_TEST( MatrixTest, forRowsTest ) { using MatrixType = typename TestFixture::MatrixType; test_ForRows< MatrixType >(); } TYPED_TEST( MatrixTest, vectorProductTest ) { using MatrixType = typename TestFixture::MatrixType; test_VectorProduct< MatrixType >(); } /*TYPED_TEST( MatrixTest, addMatrixTest ) { using MatrixType = typename TestFixture::MatrixType; test_AddMatrix< MatrixType >(); }*/ TYPED_TEST( MatrixTest, assignmentOperatorTest ) { using MatrixType = typename TestFixture::MatrixType; test_AssignmentOperator< MatrixType >(); } TYPED_TEST( MatrixTest, saveAndLoadTest ) { using MatrixType = typename TestFixture::MatrixType; test_SaveAndLoad< MatrixType >(); } /*TEST( MultidiagonalMatrixTest, Multidiagonal_getMatrixProductTest_Host ) { bool testRan = false; EXPECT_TRUE( testRan ); std::cout << "\nTEST DID NOT RUN. NOT WORKING.\n\n"; std::cout << "If launched on CPU, this test will not build, but will print the following message: \n"; std::cout << " /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h(609): error: no instance of function template \"TNL::Matrices::MultidiagonalMatrixProductKernel\" matches the argument list\n"; std::cout << " argument types are: (TNL::Matrices::Multidiagonal<int, TNL::Devices::Host, int> *, Multidiagonal_host_int *, Multidiagonal_host_int *, const int, const int, int, int)\n"; std::cout << " detected during:\n"; std::cout << " instantiation of \"void TNL::Matrices::Multidiagonal<Real, Device, Index>::getMatrixProduct(const Matrix1 &, const Matrix2 &, const TNL::Matrices::Multidiagonal<Real, Device, Index>::RealType &, const TNL::Matrices::Multidiagonal<Real, Device, Index>::RealType &) [with Real=int, Device=TNL::Devices::Host, Index=int, Matrix1=Multidiagonal_host_int, Matrix2=Multidiagonal_host_int, tileDim=32]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(901): here\n"; std::cout << " instantiation of \"void test_GetMatrixProduct<Matrix>() [with Matrix=Multidiagonal_host_int]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(1315): here\n\n"; } #ifdef HAVE_CUDA TEST( MultidiagonalMatrixTest, Multidiagonal_getMatrixProductTest_Cuda ) { bool testRan = false; EXPECT_TRUE( testRan ); std::cout << "\nTEST DID NOT RUN. NOT WORKING.\n\n"; std::cout << "If launched on GPU, this test will not build, but will print the following message: \n"; std::cout << " /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h(510): error: identifier \"tnlCudaMin\" is undefined\n"; std::cout << " detected during:\n"; std::cout << " instantiation of \"void TNL::Matrices::MultidiagonalMatrixProductKernel<Real,Index,Matrix1,Matrix2,tileDim,tileRowBlockSize>(TNL::Matrices::Multidiagonal<Real, TNL::Devices::Cuda, Index> *, const Matrix1 *, const Matrix2 *, Real, Real, Index, Index) [with Real=int, Index=int, Matrix1=Multidiagonal_cuda_int, Matrix2=Multidiagonal_cuda_int, tileDim=32, tileRowBlockSize=8]\"\n"; std::cout << " instantiation of \"void TNL::Matrices::Multidiagonal<Real, Device, Index>::getMatrixProduct(const Matrix1 &, const Matrix2 &, const TNL::Matrices::Multidiagonal<Real, Device, Index>::RealType &, const TNL::Matrices::Multidiagonal<Real, Device, Index>::RealType &) [with Real=int, Device=TNL::Devices::Cuda, Index=int, Matrix1=Multidiagonal_cuda_int, Matrix2=Multidiagonal_cuda_int, tileDim=32]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(901): here\n"; std::cout << " instantiation of \"void test_GetMatrixProduct<Matrix>() [with Matrix=Multidiagonal_cuda_int]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(1332): here\n\n"; } #endif TEST( MultidiagonalMatrixTest, Multidiagonal_getTranspositionTest_Host ) { // test_GetTransposition< Multidiagonal_host_int >(); bool testRan = false; EXPECT_TRUE( testRan ); std::cout << "\nTEST DID NOT RUN. NOT WORKING.\n\n"; std::cout << "If launched on CPU, this test will not build, but will print the following message: \n"; std::cout << " /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h(836): error: no instance of function template \"TNL::Matrices::MultidiagonalTranspositionAlignedKernel\" matches the argument list\n"; std::cout << " argument types are: (TNL::Matrices::Multidiagonal<int, TNL::Devices::Host, int> *, Multidiagonal_host_int *, const int, int, int)\n"; std::cout << " detected during:\n"; std::cout << " instantiation of \"void TNL::Matrices::Multidiagonal<Real, Device, Index>::getTransposition(const Matrix &, const TNL::Matrices::Multidiagonal<Real, Device, Index>::RealType &) [with Real=int, Device=TNL::Devices::Host, Index=int, Matrix=Multidiagonal_host_int, tileDim=32]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(977): here\n"; std::cout << " instantiation of \"void test_GetTransposition<Matrix>() [with Matrix=Multidiagonal_host_int]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(1420): here\n\n"; std::cout << "AND this message: \n"; std::cout << " /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h(852): error: no instance of function template \"TNL::Matrices::MultidiagonalTranspositionNonAlignedKernel\" matches the argument list\n"; std::cout << " argument types are: (TNL::Matrices::Multidiagonal<int, TNL::Devices::Host, int> *, Multidiagonal_host_int *, const int, int, int)\n"; std::cout << " detected during:\n"; std::cout << " instantiation of \"void TNL::Matrices::Multidiagonal<Real, Device, Index>::getTransposition(const Matrix &, const TNL::Matrices::Multidiagonal<Real, Device, Index>::RealType &) [with Real=int, Device=TNL::Devices::Host, Index=int, Matrix=Multidiagonal_host_int, tileDim=32]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(977): here\n"; std::cout << " instantiation of \"void test_GetTransposition<Matrix>() [with Matrix=Multidiagonal_host_int]\"\n"; std::cout << " /home/lukas/tnl-dev/src/UnitTests/Matrices/MultidiagonalMatrixTest.h(1420): here\n\n"; } #ifdef HAVE_CUDA TEST( MultidiagonalMatrixTest, Multidiagonal_getTranspositionTest_Cuda ) { // test_GetTransposition< Multidiagonal_cuda_int >(); bool testRan = false; EXPECT_TRUE( testRan ); std::cout << "\nTEST DID NOT RUN. NOT WORKING.\n\n"; std::cout << "If launched on GPU, this test throws the following message: \n"; std::cout << " Assertion 'row >= 0 && row < this->getRows() && column >= 0 && column < this->getColumns()' failed !!!\n"; std::cout << " File: /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h \n"; std::cout << " Line: 329 \n"; std::cout << " Diagnostics: Not supported with CUDA.\n"; std::cout << " Assertion 'row >= 0 && row < this->getRows() && column >= 0 && column < this->getColumns()' failed !!! \n"; std::cout << " File: /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h \n"; std::cout << " Line: 329 \n"; std::cout << " Diagnostics: Not supported with CUDA.\n"; std::cout << " Assertion 'row >= 0 && row < this->getRows() && column >= 0 && column < this->getColumns()' failed !!! \n"; std::cout << " File: /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h \n"; std::cout << " Line: 329 \n"; std::cout << " Diagnostics: Not supported with CUDA.\n"; std::cout << " Assertion 'row >= 0 && row < this->getRows() && column >= 0 && column < this->getColumns()' failed !!! \n"; std::cout << " File: /home/lukas/tnl-dev/src/TNL/Matrices/Multidiagonal_impl.h \n"; std::cout << " Line: 329 \n"; std::cout << " Diagnostics: Not supported with CUDA.\n"; std::cout << " terminate called after throwing an instance of 'TNL::Exceptions::CudaRuntimeError'\n"; std::cout << " what(): CUDA ERROR 4 (cudaErrorLaunchFailure): unspecified launch failure.\n"; std::cout << " Source: line 57 in /home/lukas/tnl-dev/src/TNL/Containers/Algorithms/ArrayOperationsCuda_impl.h: unspecified launch failure\n"; std::cout << " [1] 4003 abort (core dumped) ./MultidiagonalMatrixTest-dbg\n"; } #endif TEST( MultidiagonalMatrixTest, Multidiagonal_performSORIterationTest_Host ) { test_PerformSORIteration< Multidiagonal_host_float >(); } #ifdef HAVE_CUDA TEST( MultidiagonalMatrixTest, Multidiagonal_performSORIterationTest_Cuda ) { // test_PerformSORIteration< Multidiagonal_cuda_float >(); bool testRan = false; EXPECT_TRUE( testRan ); std::cout << "\nTEST DID NOT RUN. NOT WORKING.\n\n"; std::cout << "If launched, this test throws the following message: \n"; std::cout << " [1] 6992 segmentation fault (core dumped) ./SparseMatrixTest-dbg\n\n"; std::cout << "\n THIS IS NOT IMPLEMENTED FOR CUDA YET!!\n\n"; } #endif * */ #endif // HAVE_GTEST #include "../main.h"
37.33774
431
0.601819
[ "vector" ]
da76fd33fd7a19fd5432154a3bfcaab4a20630d3
737
h
C
include/Graphics/ScreenBuffer.h
Shunseii/cpp-arcade-app
e7bad1b8401d9886243f3a6af3bedf40d939e9c1
[ "MIT" ]
null
null
null
include/Graphics/ScreenBuffer.h
Shunseii/cpp-arcade-app
e7bad1b8401d9886243f3a6af3bedf40d939e9c1
[ "MIT" ]
null
null
null
include/Graphics/ScreenBuffer.h
Shunseii/cpp-arcade-app
e7bad1b8401d9886243f3a6af3bedf40d939e9c1
[ "MIT" ]
null
null
null
#ifndef GRAPHICS_SCREEN_BUFFER_H #define GRAPHICS_SCREEN_BUFFER_H #include <cstddef> #include <stdint.h> #include "Graphics/Color.h" /* * ScreenBuffer class wraps SDL_Surface object * and provides functionality for pixel * manipulation on an SDL_Surface. */ struct SDL_Surface; class ScreenBuffer { private: SDL_Surface* mSurface; size_t GetIndex(int r, int c); public: ScreenBuffer(); ScreenBuffer(const ScreenBuffer&); ~ScreenBuffer(); ScreenBuffer& operator=(const ScreenBuffer&); void Init(uint32_t format, uint32_t width, uint32_t height); inline SDL_Surface* GetSurface() {return mSurface;} void Clear(const Color& c = Color::Black()); void SetPixel(const Color&, int x, int y); }; #endif
19.918919
62
0.7327
[ "object" ]
da839eda7c0be5534f2d839a62643fe8e41b29dc
7,084
h
C
core/src/specialized_solver/solid_mechanics/dynamic_hyperelasticity/dynamic_hyperelasticity_solver.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
17
2018-11-25T19:29:34.000Z
2021-09-20T04:46:22.000Z
core/src/specialized_solver/solid_mechanics/dynamic_hyperelasticity/dynamic_hyperelasticity_solver.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
1
2020-11-12T15:15:58.000Z
2020-12-29T15:29:24.000Z
core/src/specialized_solver/solid_mechanics/dynamic_hyperelasticity/dynamic_hyperelasticity_solver.h
maierbn/opendihu
577650e2f6b36a7306766b0f4176f8124458cbf0
[ "MIT" ]
4
2018-10-17T12:18:10.000Z
2021-05-28T13:24:20.000Z
#pragma once #include <Python.h> // has to be the first included header #include "time_stepping_scheme/00_time_stepping_scheme.h" #include "specialized_solver/solid_mechanics/hyperelasticity/02_hyperelasticity_solver.h" #include "data_management/specialized_solver/dynamic_hyperelasticity_solver.h" namespace TimeSteppingScheme { /** This is a solver for a dynamic nonlinear finite elasticity problem. * It uses the hyperelasticity solver for the static computations. * The dynamic problem includes the static problem, only the right hand side changes to account for inertia effects. * Furthermore, an integration scheme for 2nd order ODEs is needed. This is given by leap frog integration. * */ template<typename Term = Equation::SolidMechanics::MooneyRivlinIncompressible3D, bool withLargeOutput=true, typename MeshType = Mesh::StructuredDeformableOfDimension<3>> class DynamicHyperelasticitySolver : public TimeSteppingScheme { public: typedef SpatialDiscretization::HyperelasticitySolver<Term,withLargeOutput,MeshType,6> HyperelasticitySolverType; // the hyperelasticity solver that solves the nonlinear problem, 6 non-pressure components (u and v) typedef typename HyperelasticitySolverType::DisplacementsFunctionSpace DisplacementsFunctionSpace; typedef DisplacementsFunctionSpace FunctionSpace; typedef typename HyperelasticitySolverType::PressureFunctionSpace PressureFunctionSpace; typedef PartitionedPetscVecForHyperelasticity<DisplacementsFunctionSpace,PressureFunctionSpace,Term,6> VecHyperelasticity; typedef PartitionedPetscMatForHyperelasticity<DisplacementsFunctionSpace,PressureFunctionSpace,Term,6> MatHyperelasticity; typedef Data::DynamicHyperelasticitySolver<DisplacementsFunctionSpace> Data; //! constructor DynamicHyperelasticitySolver(DihuContext context); //! advance simulation by the given time span void advanceTimeSpan(bool withOutputWritersEnabled = true); //! initialize everything for the simulation void initialize(); //! run the whole simulation, repeatedly calls advanceTimeSpan void run(); //! call the output writer on the data object, output files will contain currentTime, with callCountIncrement !=1 output timesteps can be skipped void callOutputWriter(int timeStepNo, double currentTime, int callCountIncrement = 1); //! return the data object, with the call to this method the output writers get the data to create their output files Data &data(); //! get a reference to the underlying HyperelasticitySolver which has the material formulation and the nonlinear solver HyperelasticitySolverType &hyperelasticitySolver(); //! set new dirichlet boundary condition values for existing dofs void updateDirichletBoundaryConditions(std::vector<std::pair<global_no_t,std::array<double,6>>> newDirichletBCValues); //! add new dirichlet bc's, it is also possible to set new dofs that were not prescribed beforehand //! this calls addBoundaryConditions() of the dirichletBoundaryConditions_ object //! @param overwriteBcOnSameDof if existing bc dofs that are also in the ones to set newly should be overwritten, else they are not touched void addDirichletBoundaryConditions(std::vector<typename SpatialDiscretization::DirichletBoundaryConditions<DisplacementsFunctionSpace,6>::ElementWithNodes> &boundaryConditionElements, bool overwriteBcOnSameDof); //! get the Petsc Vec of the current state (uvp vector), this is needed to save and restore checkpoints from the PreciceAdapter Vec currentState(); private: //! set initial values for u and v from settings void setInitialValues(); //! call the callback function to update dirichlet boundary condition values void callUpdateDirichletBoundaryConditionsFunction(double t); //! call the callback function to update Neumann boundary condition values void callUpdateNeumannBoundaryConditionsFunction(double t); //! recreate the rhs of the neumann boundary conditions, needed if traction was specified in current configuration void updateNeumannBoundaryConditions(); //! compute the total bearing forces and moments at the bottom (z-) and top (z+) of the domain void computeBearingForcesAndMoments(double currentTime); HyperelasticitySolverType hyperelasticitySolver_; //< hyperelasticity solver that solver the static problem Data data_; double density_; //< density rho, used for inertia std::shared_ptr<VecHyperelasticity> uvp_; //< combined vector of u,v and p values Vec internalVirtualWork_; //< internal virtual work, computed by the hyperelasticity solver Vec accelerationTerm_; //< contribution to virtual work from acceleration, computed by the hyperelasticity solver Vec externalVirtualWorkDead_; //< external virtual work, computed by the hyperelasticity solver, dead load i.e. constant over time bool inputMeshIsGlobal_; //< value of the setting "inputMeshIsGlobal", if the new dirichletBC values are given in global or local numbering PyObject *pythonUpdateDirichletBoundaryConditionsFunction_; //< the callback function that updates dirichlet boundary conditions int updateDirichletBoundaryConditionsFunctionCallInterval_; //< the interval with which the function will be called int updateDirichletBoundaryConditionsFunctionCallCount_ = 0; //< the counter of number of calls to the updateDirichletBoundaryConditionsFunction PyObject *pythonUpdateNeumannBoundaryConditionsFunction_; //< the callback function that updates neumann boundary conditions int updateNeumannBoundaryConditionsFunctionCallInterval_; //< the interval with which the function will be called int updateNeumannBoundaryConditionsFunctionCallCount_ = 0; //< the counter of number of calls to the updateNeumannBoundaryConditionsFunction PyObject *pythonTotalForceFunction_; //< the callback function that gets the total bearing forces and moments int pythonTotalForceFunctionCallInterval_; //< the interval with which the function will be called int pythonTotalForceFunctionCallCount_ = 0; //< the counter of number of calls to the pythonTotalForceFunction_ std::vector<std::tuple<element_no_t,bool>> bottomTopElements_; //< (elementNoLocal,isAtTopOfDomain) elements that are used to integrate total forces and moments std::string totalForceLogFilename_; //< filename of the log file that will contain the total bearing forces at top and bottom elements bool isTractionInCurrentConfiguration_; //< if traction is given in current configuration, then it has to be transformed to reference configuration in every timestep bool isReferenceGeometryInitialized_; //< if the copy of the reference geometry in the hyperelasticitySolver_ has already been set in the first timestep }; } // namespace #include "specialized_solver/solid_mechanics/dynamic_hyperelasticity/dynamic_hyperelasticity_solver.tpp"
61.068966
218
0.785714
[ "mesh", "geometry", "object", "vector" ]
da8fe8844df1dad73ac42d5858a6a35e1c94cf56
1,621
h
C
cpp/p3_python/source/p3/python/numpy.h
0lru/p3ui
162c6c68f4a55ec109a593c8ced66a62520b5602
[ "MIT" ]
21
2021-07-22T21:33:01.000Z
2022-02-12T15:17:46.000Z
cpp/p3_python/source/p3/python/numpy.h
0lru/p3ui
162c6c68f4a55ec109a593c8ced66a62520b5602
[ "MIT" ]
3
2021-07-26T19:00:39.000Z
2021-12-12T09:29:09.000Z
cpp/p3_python/source/p3/python/numpy.h
0lru/p3ui
162c6c68f4a55ec109a593c8ced66a62520b5602
[ "MIT" ]
2
2021-07-23T04:57:21.000Z
2021-12-15T22:51:45.000Z
#pragma once #include "p3ui.h" namespace p3::python { template<typename T> py::capsule make_capsule(std::shared_ptr<T> ptr) { return py::capsule(new std::shared_ptr<T>(ptr), [](void* ptr) { delete reinterpret_cast<std::shared_ptr<T>*>(ptr); }); } template<typename Guard, typename T> py::array_t<T> make_guarded_array_overlay(std::shared_ptr<Guard> guard, std::vector<T>& vector) { return py::array_t<T>({ vector.size() }, { sizeof(T) }, vector.data(), make_capsule(guard)); } template<typename T> void copy(py::array_t<T> array, std::vector<T>& vector) { auto in = array.request(); if (in.shape.size() != 1) throw std::invalid_argument("array has wrong shape"); auto src = reinterpret_cast<T*>(in.ptr); vector.resize(in.shape[0]); std::copy(src, &src[in.shape[0]], vector.data()); } template<typename T> void copy(std::optional<py::array_t<T>> array, std::optional<std::vector<T>>& vector) { if (!array) { vector.reset(); } else { if (!vector) vector = std::vector<T>(); copy(array.value(), vector.value()); } } template<typename T> py::array_t<T> wrap(T* data, std::size_t height, std::size_t width, std::size_t depth) { return py::array_t<T>( py::array::ShapeContainer({ height, width, depth }), py::array::StridesContainer({ width * depth * sizeof(T), depth * sizeof(T), sizeof(T) }), data); } }
27.474576
101
0.551511
[ "shape", "vector" ]
da9dc0fe01a6424cbaa30f75aaf41b2bb0214d30
13,990
c
C
ESMF/src/Infrastructure/Mesh/src/Zoltan/key_params.c
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
1
2018-07-05T16:48:58.000Z
2018-07-05T16:48:58.000Z
ESMF/src/Infrastructure/Mesh/src/Zoltan/key_params.c
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
1
2022-03-04T16:12:02.000Z
2022-03-04T16:12:02.000Z
ESMF/src/Infrastructure/Mesh/src/Zoltan/key_params.c
joeylamcy/gchp
0e1676300fc91000ecb43539cabf1f342d718fb3
[ "NCSA", "Apache-2.0", "MIT" ]
null
null
null
/***************************************************************************** * Zoltan Library for Parallel Applications * * Copyright (c) 2000,2001,2002, Sandia National Laboratories. * * For more info, see the README file in the top-level Zoltan directory. * *****************************************************************************/ /***************************************************************************** * CVS File Information : * $RCSfile: key_params.c,v $ * $Author: dneckels $ * $Date: 2007/11/28 16:13:50 $ * Revision: 1.47 $ ****************************************************************************/ #include <stdio.h> #include "zz_const.h" #include "key_params.h" #include "params_const.h" #include "timer_const.h" #include "zz_rand.h" #ifdef __cplusplus /* if C++, define the rest of this header file as extern C */ extern "C" { #endif /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ static PARAM_VARS Key_params[] = { { "IMBALANCE_TOL", NULL, "FLOAT", 1 }, { "AUTO_MIGRATE", NULL, "INT", 0 }, { "OBJ_WEIGHT_DIM", NULL, "INT", 0 }, { "EDGE_WEIGHT_DIM", NULL, "INT", 0 }, { "DEBUG_LEVEL", NULL, "INT", 0 }, { "DEBUG_PROCESSOR", NULL, "INT", 0 }, { "DETERMINISTIC", NULL, "INT", 0 }, { "TIMER", NULL, "STRING", 0 }, { "NUM_GID_ENTRIES", NULL, "INT", 0 }, { "NUM_LID_ENTRIES", NULL, "INT", 0 }, { "RETURN_LISTS", NULL, "STRING", 0 }, { "LB_METHOD", NULL, "STRING", 0 }, { "TFLOPS_SPECIAL", NULL, "INT", 0 }, { "COMM_WEIGHT_DIM", NULL, "INT", 0 }, /* For backward compatibility only. */ /* Prefer use of EDGE_WEIGHT_DIM. */ { "NUM_GLOBAL_PARTITIONS", NULL, "INT", 0 }, { "NUM_LOCAL_PARTITIONS", NULL, "INT", 0 }, { "MIGRATE_ONLY_PROC_CHANGES", NULL, "INT", 0 }, { "REMAP", NULL, "INT", 0 }, { "SEED", NULL, "INT", 0 }, { NULL, NULL, NULL, 0 } }; /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ /* * Handle parameter changes for variables stored in Zoltan structure. */ int Zoltan_Set_Key_Param( ZZ *zz, /* Zoltan structure */ const char *name, /* name of variable */ const char *val, /* value of variable */ int idx /* index of vector param, -1 if scalar */ ) { const char *yo = "Zoltan_Set_Key_Param"; char msg[256]; int status; /* return code */ PARAM_UTYPE result; /* value returned from Check_Param */ int index; /* index returned from Check_Param */ int tmp; int Export, import; status = Zoltan_Check_Param(name, val, Key_params, &result, &index); if (status == 0) { switch (index) { case 0: /* Imbalance_Tol */ if (result.def) result.fval = ZOLTAN_LB_IMBALANCE_TOL_DEF; if (result.fval < 1.0) { sprintf(msg, "Invalid Imbalance_Tol value (%g) " "being set to %g.", result.fval, ZOLTAN_LB_IMBALANCE_TOL_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.fval = ZOLTAN_LB_IMBALANCE_TOL_DEF; } if (idx > zz->Obj_Weight_Dim){ sprintf(msg, "Imbalance_Tol index %d > Obj_Weight_Dim = %d\n", idx, zz->Obj_Weight_Dim); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); } else if (idx < -1){ sprintf(msg, "Invalid Imbalance_Tol index %d\n", idx); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); } else if (idx == -1){ /* Set all entries to the same value. */ for (idx=0; idx<zz->LB.Imb_Tol_Len; idx++) zz->LB.Imbalance_Tol[idx] = result.fval; } else zz->LB.Imbalance_Tol[idx] = result.fval; status = 3; /* Don't add to Params field of ZZ */ break; case 1: /* Help_Migrate */ if (result.def) result.ival = ZOLTAN_AUTO_MIGRATE_DEF; zz->Migrate.Auto_Migrate = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 2: /* Object weight dim. */ if (result.def) result.ival = ZOLTAN_OBJ_WEIGHT_DEF; if (result.ival < 0) { sprintf(msg, "Invalid Obj_Weight_Dim value (%d) " "being set to %d.", result.ival, ZOLTAN_OBJ_WEIGHT_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_OBJ_WEIGHT_DEF; } zz->Obj_Weight_Dim = result.ival; if (zz->Obj_Weight_Dim > zz->LB.Imb_Tol_Len){ /* Resize and reallocate Imb_Tol. */ zz->LB.Imb_Tol_Len += 10; zz->LB.Imbalance_Tol = (float *) ZOLTAN_REALLOC(zz->LB.Imbalance_Tol, zz->LB.Imb_Tol_Len * sizeof(float)); } status = 3; /* Don't add to Params field of ZZ */ break; case 3: /* Edge weight dim. */ case 13: if (result.def) result.ival = ZOLTAN_EDGE_WEIGHT_DEF; if (result.ival < 0) { sprintf(msg, "Invalid Edge_Weight_Dim value (%d) " "being set to %d.", result.ival, ZOLTAN_EDGE_WEIGHT_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_EDGE_WEIGHT_DEF; } zz->Edge_Weight_Dim = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 4: /* Debug level */ if (result.def) result.ival = ZOLTAN_DEBUG_LEVEL_DEF; if (result.ival < 0) { sprintf(msg, "Invalid Debug_Level value (%d) " "being set to %d.", result.ival, ZOLTAN_DEBUG_LEVEL_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_DEBUG_LEVEL_DEF; } zz->Debug_Level = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 5: /* Debug processor */ if (result.def) result.ival = ZOLTAN_DEBUG_PROC_DEF; if (result.ival < 0 || result.ival > zz->Num_Proc) { sprintf(msg, "Invalid Debug_Processor value (%d) " "being set to %d.", result.ival, ZOLTAN_DEBUG_PROC_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_DEBUG_PROC_DEF; } zz->Debug_Proc = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 6: /* Deterministic flag */ if (result.def) result.ival = ZOLTAN_DETERMINISTIC_DEF; if (result.ival < 0) { sprintf(msg, "Invalid Deterministic value (%d) " "being set to %d.", result.ival, ZOLTAN_DETERMINISTIC_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_DETERMINISTIC_DEF; } zz->Deterministic = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 7: /* Timer */ status = Zoltan_Set_Timer_Param(name, val, &tmp); zz->Timer = tmp; Zoltan_Timer_ChangeFlag(zz->ZTime, zz->Timer); if (status==0) status = 3; /* Don't add to Params field of ZZ */ break; case 8: /* Num_GID_Entries */ if (result.def) result.ival = ZOLTAN_NUM_ID_ENTRIES_DEF; if (result.ival < 1) { sprintf(msg, "Invalid Num_GID_Entries value (%d); " "being set to %d.", result.ival, ZOLTAN_NUM_ID_ENTRIES_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_NUM_ID_ENTRIES_DEF; } zz->Num_GID = result.ival; status = 3; break; case 9: /* Num_LID_Entries */ if (result.def) result.ival = ZOLTAN_NUM_ID_ENTRIES_DEF; if (result.ival < 0) { sprintf(msg, "Invalid Num_LID_Entries value (%d); " "being set to %d.", result.ival, ZOLTAN_NUM_ID_ENTRIES_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_NUM_ID_ENTRIES_DEF; } zz->Num_LID = result.ival; status = 3; break; case 10: /* LB.Return_Lists */ Export = (strstr(result.sval, "EXPORT") != NULL); import = (strstr(result.sval, "IMPORT") != NULL); if ((Export && import) || (strcmp(result.sval, "ALL") == 0)) { tmp = ZOLTAN_LB_ALL_LISTS; /* Export AND import lists */ status = 3; } else if (import){ tmp = ZOLTAN_LB_IMPORT_LISTS; /* import lists */ status = 3; } else if (Export){ tmp = ZOLTAN_LB_EXPORT_LISTS; /* Export lists */ status = 3; } else if (strstr(result.sval, "PARTITION")!=NULL) { /* list of every object's process/partition assignment */ tmp = ZOLTAN_LB_COMPLETE_EXPORT_LISTS; status = 3; } else if (strcmp(result.sval, "NONE")==0) { tmp = ZOLTAN_LB_NO_LISTS; /* no lists */ status = 3; } else{ tmp = ZOLTAN_LB_RETURN_LISTS_DEF; sprintf(msg, "Unknown return_lists option %s.", result.sval); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); status = 2; /* Illegal parameter */ } zz->LB.Return_Lists = tmp; break; case 11: /* LB_Method */ status = Zoltan_LB_Set_LB_Method(zz,result.sval); if (status == ZOLTAN_OK) status = 3; break; case 12: /* Tflops Special flag */ if (result.def) result.ival = ZOLTAN_TFLOPS_SPECIAL_DEF; if (result.ival < 0) { sprintf(msg, "Invalid Tflops Special value (%d) " "being set to %d.", result.ival, ZOLTAN_TFLOPS_SPECIAL_DEF); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = ZOLTAN_TFLOPS_SPECIAL_DEF; } zz->Tflops_Special = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 14: /* Num_Global_Partitions */ if (result.def) result.ival = zz->Num_Proc; if (result.ival < 1) { sprintf(msg, "Invalid Num_Global_Partitions value (%d); " "being set to %d.", result.ival,zz->Num_Proc); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = zz->Num_Proc; } zz->LB.Num_Global_Parts_Param = result.ival; status = 3; break; case 15: /* Num_Local_Partitions */ if (result.def) result.ival = -1; if (result.ival < -1) { sprintf(msg, "Invalid Num_Local_Partitions value (%d); " "being set to %d.", result.ival,-1); ZOLTAN_PRINT_WARN(zz->Proc, yo, msg); result.ival = -1; } zz->LB.Num_Local_Parts_Param = result.ival; status = 3; break; case 16: /* Migrate_Only_Proc_Changes */ if (result.def) result.ival = ZOLTAN_MIGRATE_ONLY_PROC_CHANGES_DEF; zz->Migrate.Only_Proc_Changes = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 17: /* LB.Remap */ if (result.def) result.ival = 0; zz->LB.Remap_Flag = result.ival; status = 3; /* Don't add to Params field of ZZ */ break; case 18: /* Seed */ if (result.def) result.ival = Zoltan_Seed(); Zoltan_Srand(result.ival, NULL); status = 3; break; } /* end switch (index) */ } return(status); } /*****************************************************************************/ /*****************************************************************************/ /*****************************************************************************/ /* * Print key parameters. */ void Zoltan_Print_Key_Params(ZZ const *zz) { int i; for (i=0; i<(zz->Obj_Weight_Dim?zz->Obj_Weight_Dim:1); i++) printf("ZOLTAN Parameter %s[%1d] = %f\n", Key_params[0].name, i, zz->LB.Imbalance_Tol[i]); printf("ZOLTAN Parameter %s = %s\n", Key_params[1].name, (zz->Migrate.Auto_Migrate ? "TRUE" : "FALSE")); printf("ZOLTAN Parameter %s = %d\n", Key_params[16].name, zz->Migrate.Only_Proc_Changes); printf("ZOLTAN Parameter %s = %d\n", Key_params[2].name, zz->Obj_Weight_Dim); printf("ZOLTAN Parameter %s = %d\n", Key_params[3].name, zz->Edge_Weight_Dim); printf("ZOLTAN Parameter %s = %d\n", Key_params[4].name, zz->Debug_Level); printf("ZOLTAN Parameter %s = %d\n", Key_params[5].name, zz->Debug_Proc); printf("ZOLTAN Parameter %s = %s\n", Key_params[6].name, (zz->Deterministic ? "TRUE" : "FALSE")); printf("ZOLTAN Parameter %s = %d ", Key_params[7].name, zz->Timer); if (zz->Timer == ZOLTAN_TIME_WALL) printf("(wall)"); else if (zz->Timer == ZOLTAN_TIME_CPU) printf("(cpu)"); printf("\n"); printf("ZOLTAN Parameter %s = %d\n", Key_params[8].name, zz->Num_GID); printf("ZOLTAN Parameter %s = %d\n", Key_params[9].name, zz->Num_LID); printf("ZOLTAN Parameter %s = ", Key_params[10].name); switch (zz->LB.Return_Lists) { case ZOLTAN_LB_ALL_LISTS: printf("IMPORT AND EXPORT\n"); break; case ZOLTAN_LB_IMPORT_LISTS: printf("IMPORT\n"); break; case ZOLTAN_LB_EXPORT_LISTS: printf("EXPORT\n"); break; case ZOLTAN_LB_COMPLETE_EXPORT_LISTS: printf("PARTITION ASSIGNMENTS\n"); break; case ZOLTAN_LB_NO_LISTS: printf("NONE\n"); break; } if (zz->Tflops_Special) /* print only if set */ printf("ZOLTAN Parameter %s = %s\n", Key_params[12].name, "TRUE"); printf("ZOLTAN Parameter %s = %d\n", Key_params[14].name, zz->LB.Num_Global_Parts_Param); printf("ZOLTAN Parameter %s = %d\n", Key_params[15].name, zz->LB.Num_Local_Parts_Param); printf("ZOLTAN Parameter %s = %d\n", Key_params[17].name, zz->LB.Remap_Flag); printf("ZOLTAN Parameter %s = %d (%u)\n", Key_params[18].name, Zoltan_Seed(), Zoltan_Seed()); } #ifdef __cplusplus } /* closing bracket for extern "C" */ #endif
35.507614
80
0.536455
[ "object", "vector" ]
fd4a04d31fcb8975e9855af57d87a6bb953d2577
5,187
c
C
VideoServer/libs/libcodec2/src/c2dec.c
zengfanmao/mpds
c2bba464eaddc9ec70604a8614d84c5334461e8e
[ "MIT" ]
null
null
null
VideoServer/libs/libcodec2/src/c2dec.c
zengfanmao/mpds
c2bba464eaddc9ec70604a8614d84c5334461e8e
[ "MIT" ]
null
null
null
VideoServer/libs/libcodec2/src/c2dec.c
zengfanmao/mpds
c2bba464eaddc9ec70604a8614d84c5334461e8e
[ "MIT" ]
null
null
null
/*---------------------------------------------------------------------------*\ FILE........: c2dec.c AUTHOR......: David Rowe DATE CREATED: 23/8/2010 Decodes a file of bits to a file of raw speech samples using codec2. \*---------------------------------------------------------------------------*/ /* Copyright (C) 2010 David Rowe All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include "codec2.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #define NONE 0 /* no bit errors */ #define UNIFORM 1 /* random bit errors */ #define TWO_STATE 2 /* Two state error model */ int main(int argc, char *argv[]) { int mode; void *codec2; FILE *fin; FILE *fout; short *buf; unsigned char *bits; int nsam, nbit, nbyte, i, byte, frames, bit_errors, error_mode; int state, next_state; float ber, r, pstate0, pstate1; if (argc < 4) { printf("basic usage...............: c2dec 3200|2400|1400|1200 InputBitFile OutputRawSpeechFile\n"); printf("uniform errors usage.......: c2dec 3200|2400|1400|1200 InputBitFile OutputRawSpeechFile uniformBER\n"); printf("two state fading usage....: c2dec 3200|2400|1400|1200 InputBitFile OutputRawSpeechFile probGood probBad\n"); printf("e.g c2dec 1400 hts1a.c2 hts1a_1400.raw\n"); printf("e.g c2dec 1400 hts1a.c2 hts1a_1400.raw 0.9\n"); printf("e.g c2dec 1400 hts1a.c2 hts1a_1400.raw 0.99 0.9\n"); exit(1); } if (strcmp(argv[1],"3200") == 0) mode = CODEC2_MODE_3200; else if (strcmp(argv[1],"2400") == 0) mode = CODEC2_MODE_2400; else if (strcmp(argv[1],"1400") == 0) mode = CODEC2_MODE_1400; else if (strcmp(argv[1],"1200") == 0) mode = CODEC2_MODE_1200; else { fprintf(stderr, "Error in mode: %s. Must be 4800, 3200, 2400, 1400 or 1200\n", argv[1]); exit(1); } if (strcmp(argv[2], "-") == 0) fin = stdin; else if ( (fin = fopen(argv[2],"rb")) == NULL ) { fprintf(stderr, "Error opening input bit file: %s: %s.\n", argv[2], strerror(errno)); exit(1); } if (strcmp(argv[3], "-") == 0) fout = stdout; else if ( (fout = fopen(argv[3],"wb")) == NULL ) { fprintf(stderr, "Error opening output speech file: %s: %s.\n", argv[3], strerror(errno)); exit(1); } error_mode = NONE; ber = 0.0; pstate0 = pstate1 = 0.0; if (argc == 5) { error_mode = UNIFORM; ber = atof(argv[4]); } if (argc == 6) { error_mode = TWO_STATE; pstate0 = atof(argv[4]); pstate1 = atof(argv[5]); state = 0; } codec2 = codec2_create(mode); nsam = codec2_samples_per_frame(codec2); nbit = codec2_bits_per_frame(codec2); buf = (short*)malloc(nsam*sizeof(short)); nbyte = (nbit + 7) / 8; bits = (unsigned char*)malloc(nbyte*sizeof(char)); frames = bit_errors = 0; while(fread(bits, sizeof(char), nbyte, fin) == (size_t)nbyte) { frames++; if (error_mode == UNIFORM) { for(i=0; i<nbit; i++) { r = (float)rand()/RAND_MAX; if (r < ber) { byte = i/8; //printf("nbyte %d nbit %d i %d byte %d\n", nbyte, nbit, i, byte); bits[byte] ^= 1 << (i - byte*8); bit_errors++; } } } if (error_mode == TWO_STATE) { next_state = state; switch(state) { case 0: /* clear channel state - no bit errors */ r = (float)rand()/RAND_MAX; if (r > pstate0) next_state = 1; break; case 1: /* burst error state - 50% bit error rate */ for(i=0; i<nbit; i++) { r = (float)rand()/RAND_MAX; if (r < 0.5) { byte = i/8; bits[byte] ^= 1 << (i - byte*8); bit_errors++; } } r = (float)rand()/RAND_MAX; if (r > pstate1) next_state = 0; break; } state = next_state; } codec2_decode(codec2, buf, bits); fwrite(buf, sizeof(short), nsam, fout); //if this is in a pipeline, we probably don't want the usual //buffering to occur if (fout == stdout) fflush(stdout); if (fin == stdin) fflush(stdin); } if (ber != 0.0) fprintf(stderr, "actual BER: %1.3f\n", (float)bit_errors/(frames*nbit)); codec2_destroy(codec2); free(buf); free(bits); fclose(fin); fclose(fout); return 0; }
28.657459
117
0.539811
[ "model" ]
fd4b93cfcbe8c1fda33185e9c1bbe22cf8f37304
48,314
c
C
platform/shared/ruby/proc.c
insphereapplication/rhodes
57a2b4b64b04667e94c7c8924bf7038e4fdf60b3
[ "MIT" ]
null
null
null
platform/shared/ruby/proc.c
insphereapplication/rhodes
57a2b4b64b04667e94c7c8924bf7038e4fdf60b3
[ "MIT" ]
null
null
null
platform/shared/ruby/proc.c
insphereapplication/rhodes
57a2b4b64b04667e94c7c8924bf7038e4fdf60b3
[ "MIT" ]
null
null
null
/********************************************************************** proc.c - Proc, Binding, Env $Author: yugui $ created at: Wed Jan 17 12:13:14 2007 Copyright (C) 2004-2007 Koichi Sasada **********************************************************************/ #include "eval_intern.h" #include "gc.h" struct METHOD { VALUE oclass; /* class that holds the method */ VALUE rclass; /* class of the receiver */ VALUE recv; ID id, oid; NODE *body; }; VALUE rb_cUnboundMethod; VALUE rb_cMethod; VALUE rb_cBinding; VALUE rb_cProc; static VALUE bmcall(VALUE, VALUE); static int method_arity(VALUE); static VALUE rb_obj_is_method(VALUE m); /* Proc */ static void proc_free(void *ptr) { RUBY_FREE_ENTER("proc"); if (ptr) { ruby_xfree(ptr); } RUBY_FREE_LEAVE("proc"); } static void proc_mark(void *ptr) { rb_proc_t *proc; RUBY_MARK_ENTER("proc"); if (ptr) { proc = ptr; RUBY_MARK_UNLESS_NULL(proc->envval); RUBY_MARK_UNLESS_NULL(proc->blockprocval); RUBY_MARK_UNLESS_NULL(proc->block.proc); RUBY_MARK_UNLESS_NULL(proc->block.self); if (proc->block.iseq && RUBY_VM_IFUNC_P(proc->block.iseq)) { RUBY_MARK_UNLESS_NULL((VALUE)(proc->block.iseq)); } } RUBY_MARK_LEAVE("proc"); } VALUE rb_proc_alloc(VALUE klass) { VALUE obj; rb_proc_t *proc; obj = Data_Make_Struct(klass, rb_proc_t, proc_mark, proc_free, proc); MEMZERO(proc, rb_proc_t, 1); return obj; } VALUE rb_obj_is_proc(VALUE proc) { if (TYPE(proc) == T_DATA && RDATA(proc)->dfree == (RUBY_DATA_FUNC) proc_free) { return Qtrue; } else { return Qfalse; } } static VALUE proc_dup(VALUE self) { VALUE procval = rb_proc_alloc(rb_cProc); rb_proc_t *src, *dst; GetProcPtr(self, src); GetProcPtr(procval, dst); dst->block = src->block; dst->block.proc = procval; dst->envval = src->envval; dst->safe_level = src->safe_level; dst->is_lambda = src->is_lambda; return procval; } static VALUE proc_clone(VALUE self) { VALUE procval = proc_dup(self); CLONESETUP(procval, self); return procval; } /* * call-seq: * prc.lambda? => true or false * * Returns true for a Proc object which argument handling is rigid. * Such procs are typically generated by lambda. * * A Proc object generated by proc ignore extra arguments. * * proc {|a,b| [a,b] }.call(1,2,3) => [1,2] * * It provides nil for lacked arguments. * * proc {|a,b| [a,b] }.call(1) => [1,nil] * * It expand single-array argument. * * proc {|a,b| [a,b] }.call([1,2]) => [1,2] * * A Proc object generated by lambda doesn't have such tricks. * * lambda {|a,b| [a,b] }.call(1,2,3) => ArgumentError * lambda {|a,b| [a,b] }.call(1) => ArgumentError * lambda {|a,b| [a,b] }.call([1,2]) => ArgumentError * * Proc#lambda? is a predicate for the tricks. * It returns true if no tricks. * * lambda {}.lambda? => true * proc {}.lambda? => false * * Proc.new is same as proc. * * Proc.new {}.lambda? => false * * lambda, proc and Proc.new preserves the tricks of * a Proc object given by & argument. * * lambda(&lambda {}).lambda? => true * proc(&lambda {}).lambda? => true * Proc.new(&lambda {}).lambda? => true * * lambda(&proc {}).lambda? => false * proc(&proc {}).lambda? => false * Proc.new(&proc {}).lambda? => false * * A Proc object generated by & argument has the tricks * * def n(&b) b.lambda? end * n {} => false * * The & argument preserves the tricks if a Proc object is given * by & argument. * * n(&lambda {}) => true * n(&proc {}) => false * n(&Proc.new {}) => false * * A Proc object converted from a method has no tricks. * * def m() end * method(:m).to_proc.lambda? => true * * n(&method(:m)) => true * n(&method(:m).to_proc) => true * * define_method is treated same as method definition. * The defined method has no tricks. * * class C * define_method(:d) {} * end * C.new.e(1,2) => ArgumentError * C.new.method(:d).to_proc.lambda? => true * * define_method always defines a method without the tricks, * even if a non-lambda Proc object is given. * This is the only exception which the tricks are not preserved. * * class C * define_method(:e, &proc {}) * end * C.new.e(1,2) => ArgumentError * C.new.method(:e).to_proc.lambda? => true * * This exception is for a wrapper of define_method. * It eases defining a method defining method which defines a usual method which has no tricks. * * class << C * def def2(name, &body) * define_method(name, &body) * end * end * class C * def2(:f) {} * end * C.new.f(1,2) => ArgumentError * * The wrapper, def2, defines a method which has no tricks. * */ static VALUE proc_lambda_p(VALUE procval) { rb_proc_t *proc; GetProcPtr(procval, proc); return proc->is_lambda ? Qtrue : Qfalse; } /* Binding */ static void binding_free(void *ptr) { rb_binding_t *bind; RUBY_FREE_ENTER("binding"); if (ptr) { bind = ptr; ruby_xfree(ptr); } RUBY_FREE_LEAVE("binding"); } static void binding_mark(void *ptr) { rb_binding_t *bind; RUBY_MARK_ENTER("binding"); if (ptr) { bind = ptr; RUBY_MARK_UNLESS_NULL(bind->env); } RUBY_MARK_LEAVE("binding"); } static VALUE binding_alloc(VALUE klass) { VALUE obj; rb_binding_t *bind; obj = Data_Make_Struct(klass, rb_binding_t, binding_mark, binding_free, bind); return obj; } static VALUE binding_dup(VALUE self) { VALUE bindval = binding_alloc(rb_cBinding); rb_binding_t *src, *dst; GetBindingPtr(self, src); GetBindingPtr(bindval, dst); dst->env = src->env; return bindval; } static VALUE binding_clone(VALUE self) { VALUE bindval = binding_dup(self); CLONESETUP(bindval, self); return bindval; } VALUE rb_binding_new(void) { rb_thread_t *th = GET_THREAD(); rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(th, th->cfp); VALUE bindval = binding_alloc(rb_cBinding); rb_binding_t *bind; if (cfp == 0) { rb_raise(rb_eRuntimeError, "Can't create Binding Object on top of Fiber."); } GetBindingPtr(bindval, bind); bind->env = rb_vm_make_env_object(th, cfp); return bindval; } /* * call-seq: * binding -> a_binding * * Returns a +Binding+ object, describing the variable and * method bindings at the point of call. This object can be used when * calling +eval+ to execute the evaluated command in this * environment. Also see the description of class +Binding+. * * def getBinding(param) * return binding * end * b = getBinding("hello") * eval("param", b) #=> "hello" */ static VALUE rb_f_binding(VALUE self) { return rb_binding_new(); } /* * call-seq: * binding.eval(string [, filename [,lineno]]) => obj * * Evaluates the Ruby expression(s) in <em>string</em>, in the * <em>binding</em>'s context. If the optional <em>filename</em> and * <em>lineno</em> parameters are present, they will be used when * reporting syntax errors. * * def getBinding(param) * return binding * end * b = getBinding("hello") * b.eval("param") #=> "hello" */ static VALUE bind_eval(int argc, VALUE *argv, VALUE bindval) { VALUE args[4]; rb_scan_args(argc, argv, "12", &args[0], &args[2], &args[3]); args[1] = bindval; return rb_f_eval(argc+1, args, Qnil /* self will be searched in eval */); } static VALUE proc_new(VALUE klass, int is_lambda) { VALUE procval = Qnil; rb_thread_t *th = GET_THREAD(); rb_control_frame_t *cfp = th->cfp; rb_block_t *block; if ((GC_GUARDED_PTR_REF(cfp->lfp[0])) != 0 && !RUBY_VM_CLASS_SPECIAL_P(cfp->lfp[0])) { block = GC_GUARDED_PTR_REF(cfp->lfp[0]); } else { cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); if ((GC_GUARDED_PTR_REF(cfp->lfp[0])) != 0 && !RUBY_VM_CLASS_SPECIAL_P(cfp->lfp[0])) { block = GC_GUARDED_PTR_REF(cfp->lfp[0]); if (is_lambda) { rb_warn("tried to create Proc object without a block"); } } else { rb_raise(rb_eArgError, "tried to create Proc object without a block"); } } procval = block->proc; if (procval) { if (RBASIC(procval)->klass == klass) { return procval; } else { VALUE newprocval = proc_dup(procval); RBASIC(newprocval)->klass = klass; return newprocval; } } procval = rb_vm_make_proc(th, block, klass); if (is_lambda) { rb_proc_t *proc; GetProcPtr(procval, proc); proc->is_lambda = Qtrue; } return procval; } /* * call-seq: * Proc.new {|...| block } => a_proc * Proc.new => a_proc * * Creates a new <code>Proc</code> object, bound to the current * context. <code>Proc::new</code> may be called without a block only * within a method with an attached block, in which case that block is * converted to the <code>Proc</code> object. * * def proc_from * Proc.new * end * proc = proc_from { "hello" } * proc.call #=> "hello" */ static VALUE rb_proc_s_new(int argc, VALUE *argv, VALUE klass) { VALUE block = proc_new(klass, Qfalse); rb_obj_call_init(block, argc, argv); return block; } /* * call-seq: * proc { |...| block } => a_proc * * Equivalent to <code>Proc.new</code>. */ VALUE rb_block_proc(void) { return proc_new(rb_cProc, Qfalse); } VALUE rb_block_lambda(void) { return proc_new(rb_cProc, Qtrue); } VALUE rb_f_lambda(void) { rb_warn("rb_f_lambda() is deprecated; use rb_block_proc() instead"); return rb_block_lambda(); } /* * call-seq: * lambda { |...| block } => a_proc * * Equivalent to <code>Proc.new</code>, except the resulting Proc objects * check the number of parameters passed when called. */ static VALUE proc_lambda(void) { return rb_block_lambda(); } /* CHECKME: are the argument checking semantics correct? */ /* * call-seq: * prc.call(params,...) => obj * prc[params,...] => obj * prc.(params,...) => obj * * Invokes the block, setting the block's parameters to the values in * <i>params</i> using something close to method calling semantics. * Generates a warning if multiple values are passed to a proc that * expects just one (previously this silently converted the parameters * to an array). Note that prc.() invokes prc.call() with the parameters * given. It's a syntax sugar to hide "call". * * For procs created using <code>Kernel.proc</code>, generates an * error if the wrong number of parameters * are passed to a proc with multiple parameters. For procs created using * <code>Proc.new</code>, extra parameters are silently discarded. * * Returns the value of the last expression evaluated in the block. See * also <code>Proc#yield</code>. * * a_proc = Proc.new {|a, *b| b.collect {|i| i*a }} * a_proc.call(9, 1, 2, 3) #=> [9, 18, 27] * a_proc[9, 1, 2, 3] #=> [9, 18, 27] * a_proc = Proc.new {|a,b| a} * a_proc.call(1,2,3) * * <em>produces:</em> * * prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError) * from prog.rb:4:in `call' * from prog.rb:5 */ /* * call-seq: * prc === obj => obj * * Invokes the block, with <i>obj</i> as the block's parameter. It is * to allow a proc object to be a target of when clause in the case statement. */ static VALUE proc_call(int argc, VALUE *argv, VALUE procval) { rb_proc_t *proc; rb_block_t *blockptr = 0; rb_iseq_t *iseq; GetProcPtr(procval, proc); iseq = proc->block.iseq; if (BUILTIN_TYPE(iseq) == T_NODE || iseq->arg_block != -1) { if (rb_block_given_p()) { rb_proc_t *proc; VALUE procval; procval = rb_block_proc(); GetProcPtr(procval, proc); blockptr = &proc->block; } } return rb_vm_invoke_proc(GET_THREAD(), proc, proc->block.self, argc, argv, blockptr); } #if SIZEOF_LONG > SIZEOF_INT static inline int check_argc(long argc) { if (argc > INT_MAX || argc < 0) { rb_raise(rb_eArgError, "too many arguments (%lu)", (unsigned long)argc); } return (int)argc; } #else #define check_argc(argc) (argc) #endif VALUE rb_proc_call(VALUE self, VALUE args) { rb_proc_t *proc; GetProcPtr(self, proc); return rb_vm_invoke_proc(GET_THREAD(), proc, proc->block.self, check_argc(RARRAY_LEN(args)), RARRAY_PTR(args), 0); } VALUE rb_proc_call_with_block(VALUE self, int argc, VALUE *argv, VALUE pass_procval) { rb_proc_t *proc; rb_block_t *block = 0; GetProcPtr(self, proc); if (!NIL_P(pass_procval)) { rb_proc_t *pass_proc; GetProcPtr(pass_procval, pass_proc); block = &pass_proc->block; } return rb_vm_invoke_proc(GET_THREAD(), proc, proc->block.self, argc, argv, block); } /* * call-seq: * prc.arity -> fixnum * * Returns the number of arguments that would not be ignored. If the block * is declared to take no arguments, returns 0. If the block is known * to take exactly n arguments, returns n. If the block has optional * arguments, return -n-1, where n is the number of mandatory * arguments. A <code>proc</code> with no argument declarations * is the same a block declaring <code>||</code> as its arguments. * * Proc.new {}.arity #=> 0 * Proc.new {||}.arity #=> 0 * Proc.new {|a|}.arity #=> 1 * Proc.new {|a,b|}.arity #=> 2 * Proc.new {|a,b,c|}.arity #=> 3 * Proc.new {|*a|}.arity #=> -1 * Proc.new {|a,*b|}.arity #=> -2 * Proc.new {|a,*b, c|}.arity #=> -3 */ static VALUE proc_arity(VALUE self) { rb_proc_t *proc; rb_iseq_t *iseq; GetProcPtr(self, proc); iseq = proc->block.iseq; if (iseq) { if (BUILTIN_TYPE(iseq) != T_NODE) { if (iseq->arg_rest < 0) { return INT2FIX(iseq->argc); } else { return INT2FIX(-(iseq->argc + 1 + iseq->arg_post_len)); } } else { NODE *node = (NODE *)iseq; if (nd_type(node) == NODE_IFUNC && node->nd_cfnc == bmcall) { /* method(:foo).to_proc.arity */ return INT2FIX(method_arity(node->nd_tval)); } } } return INT2FIX(-1); } int rb_proc_arity(VALUE proc) { return FIX2INT(proc_arity(proc)); } static rb_iseq_t * get_proc_iseq(VALUE self) { rb_proc_t *proc; rb_iseq_t *iseq; GetProcPtr(self, proc); iseq = proc->block.iseq; if (!RUBY_VM_NORMAL_ISEQ_P(iseq)) return 0; return iseq; } static VALUE iseq_location(rb_iseq_t *iseq) { VALUE loc[2]; if (!iseq) return Qnil; loc[0] = iseq->filename; if (iseq->insn_info_table) { loc[1] = INT2FIX(rb_iseq_first_lineno(iseq)); } else { loc[1] = Qnil; } return rb_ary_new4(2, loc); } /* * call-seq: * prc.source_location => [String, Fixnum] * * returns the ruby source filename and line number containing this proc * or nil if this proc was not defined in ruby (i.e. native) */ VALUE rb_proc_location(VALUE self) { return iseq_location(get_proc_iseq(self)); } /* * call-seq: * prc == other_proc => true or false * * Return <code>true</code> if <i>prc</i> is the same object as * <i>other_proc</i>, or if they are both procs with the same body. */ static VALUE proc_eq(VALUE self, VALUE other) { if (self == other) { return Qtrue; } else { if (TYPE(other) == T_DATA && RDATA(other)->dmark == proc_mark) { rb_proc_t *p1, *p2; GetProcPtr(self, p1); GetProcPtr(other, p2); if (p1->envval == p2->envval && p1->block.iseq->iseq_size == p2->block.iseq->iseq_size && p1->block.iseq->local_size == p2->block.iseq->local_size && MEMCMP(p1->block.iseq->iseq, p2->block.iseq->iseq, VALUE, p1->block.iseq->iseq_size) == 0) { return Qtrue; } } } return Qfalse; } /* * call-seq: * prc.hash => integer * * Return hash value corresponding to proc body. */ static VALUE proc_hash(VALUE self) { int hash; rb_proc_t *proc; GetProcPtr(self, proc); hash = (long)proc->block.iseq; hash ^= (long)proc->envval; hash ^= (long)proc->block.lfp >> 16; return INT2FIX(hash); } /* * call-seq: * prc.to_s => string * * Shows the unique identifier for this proc, along with * an indication of where the proc was defined. */ static VALUE proc_to_s(VALUE self) { VALUE str = 0; rb_proc_t *proc; const char *cname = rb_obj_classname(self); rb_iseq_t *iseq; const char *is_lambda; GetProcPtr(self, proc); iseq = proc->block.iseq; is_lambda = proc->is_lambda ? " (lambda)" : ""; if (RUBY_VM_NORMAL_ISEQ_P(iseq)) { int line_no = 0; if (iseq->insn_info_table) { line_no = rb_iseq_first_lineno(iseq); } str = rb_sprintf("#<%s:%p@%s:%d%s>", cname, (void *)self, RSTRING_PTR(iseq->filename), line_no, is_lambda); } else { str = rb_sprintf("#<%s:%p%s>", cname, (void *)proc->block.iseq, is_lambda); } if (OBJ_TAINTED(self)) { OBJ_TAINT(str); } return str; } /* * call-seq: * prc.to_proc -> prc * * Part of the protocol for converting objects to <code>Proc</code> * objects. Instances of class <code>Proc</code> simply return * themselves. */ static VALUE proc_to_proc(VALUE self) { return self; } static void bm_mark(struct METHOD *data) { rb_gc_mark(data->rclass); rb_gc_mark(data->oclass); rb_gc_mark(data->recv); rb_gc_mark((VALUE)data->body); } NODE * rb_method_body(VALUE method) { struct METHOD *data; if (TYPE(method) == T_DATA && RDATA(method)->dmark == (RUBY_DATA_FUNC) bm_mark) { Data_Get_Struct(method, struct METHOD, data); return data->body; } else { return 0; } } NODE *rb_get_method_body(VALUE klass, ID id, ID *idp); static VALUE mnew(VALUE klass, VALUE obj, ID id, VALUE mclass, int scope) { VALUE method; NODE *body; struct METHOD *data; VALUE rclass = klass; ID oid = id; again: if ((body = rb_get_method_body(klass, id, 0)) == 0) { rb_print_undef(rclass, oid, 0); } if (scope && (body->nd_noex & NOEX_MASK) != NOEX_PUBLIC) { rb_print_undef(rclass, oid, (int)(body->nd_noex & NOEX_MASK)); } klass = body->nd_clss; body = body->nd_body; if (nd_type(body) == NODE_ZSUPER) { klass = RCLASS_SUPER(klass); goto again; } while (rclass != klass && (FL_TEST(rclass, FL_SINGLETON) || TYPE(rclass) == T_ICLASS)) { rclass = RCLASS_SUPER(rclass); } if (TYPE(klass) == T_ICLASS) klass = RBASIC(klass)->klass; method = Data_Make_Struct(mclass, struct METHOD, bm_mark, -1, data); data->oclass = klass; data->recv = obj; data->id = id; data->body = body; data->rclass = rclass; data->oid = oid; OBJ_INFECT(method, klass); return method; } /********************************************************************** * * Document-class : Method * * Method objects are created by <code>Object#method</code>, and are * associated with a particular object (not just with a class). They * may be used to invoke the method within the object, and as a block * associated with an iterator. They may also be unbound from one * object (creating an <code>UnboundMethod</code>) and bound to * another. * * class Thing * def square(n) * n*n * end * end * thing = Thing.new * meth = thing.method(:square) * * meth.call(9) #=> 81 * [ 1, 2, 3 ].collect(&meth) #=> [1, 4, 9] * */ /* * call-seq: * meth == other_meth => true or false * * Two method objects are equal if that are bound to the same * object and contain the same body. */ static VALUE method_eq(VALUE method, VALUE other) { struct METHOD *m1, *m2; if (TYPE(other) != T_DATA || RDATA(other)->dmark != (RUBY_DATA_FUNC) bm_mark) return Qfalse; if (CLASS_OF(method) != CLASS_OF(other)) return Qfalse; Data_Get_Struct(method, struct METHOD, m1); Data_Get_Struct(other, struct METHOD, m2); if (m1->oclass != m2->oclass || m1->rclass != m2->rclass || m1->recv != m2->recv || m1->body != m2->body) return Qfalse; return Qtrue; } /* * call-seq: * meth.hash => integer * * Return a hash value corresponding to the method object. */ static VALUE method_hash(VALUE method) { struct METHOD *m; long hash; Data_Get_Struct(method, struct METHOD, m); hash = (long)m->oclass; hash ^= (long)m->rclass; hash ^= (long)m->recv; hash ^= (long)m->body; return INT2FIX(hash); } /* * call-seq: * meth.unbind => unbound_method * * Dissociates <i>meth</i> from it's current receiver. The resulting * <code>UnboundMethod</code> can subsequently be bound to a new object * of the same class (see <code>UnboundMethod</code>). */ static VALUE method_unbind(VALUE obj) { VALUE method; struct METHOD *orig, *data; Data_Get_Struct(obj, struct METHOD, orig); method = Data_Make_Struct(rb_cUnboundMethod, struct METHOD, bm_mark, -1, data); data->oclass = orig->oclass; data->recv = Qundef; data->id = orig->id; data->body = orig->body; data->rclass = orig->rclass; data->oid = orig->oid; OBJ_INFECT(method, obj); return method; } /* * call-seq: * meth.receiver => object * * Returns the bound receiver of the method object. */ static VALUE method_receiver(VALUE obj) { struct METHOD *data; Data_Get_Struct(obj, struct METHOD, data); return data->recv; } /* * call-seq: * meth.name => symbol * * Returns the name of the method. */ static VALUE method_name(VALUE obj) { struct METHOD *data; Data_Get_Struct(obj, struct METHOD, data); return ID2SYM(data->id); } /* * call-seq: * meth.owner => class_or_module * * Returns the class or module that defines the method. */ static VALUE method_owner(VALUE obj) { struct METHOD *data; Data_Get_Struct(obj, struct METHOD, data); return data->oclass; } /* * call-seq: * obj.method(sym) => method * * Looks up the named method as a receiver in <i>obj</i>, returning a * <code>Method</code> object (or raising <code>NameError</code>). The * <code>Method</code> object acts as a closure in <i>obj</i>'s object * instance, so instance variables and the value of <code>self</code> * remain available. * * class Demo * def initialize(n) * @iv = n * end * def hello() * "Hello, @iv = #{@iv}" * end * end * * k = Demo.new(99) * m = k.method(:hello) * m.call #=> "Hello, @iv = 99" * * l = Demo.new('Fred') * m = l.method("hello") * m.call #=> "Hello, @iv = Fred" */ VALUE rb_obj_method(VALUE obj, VALUE vid) { return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qfalse); } VALUE rb_obj_public_method(VALUE obj, VALUE vid) { return mnew(CLASS_OF(obj), obj, rb_to_id(vid), rb_cMethod, Qtrue); } /* * call-seq: * mod.instance_method(symbol) => unbound_method * * Returns an +UnboundMethod+ representing the given * instance method in _mod_. * * class Interpreter * def do_a() print "there, "; end * def do_d() print "Hello "; end * def do_e() print "!\n"; end * def do_v() print "Dave"; end * Dispatcher = { * ?a => instance_method(:do_a), * ?d => instance_method(:do_d), * ?e => instance_method(:do_e), * ?v => instance_method(:do_v) * } * def interpret(string) * string.each_byte {|b| Dispatcher[b].bind(self).call } * end * end * * * interpreter = Interpreter.new * interpreter.interpret('dave') * * <em>produces:</em> * * Hello there, Dave! */ static VALUE rb_mod_instance_method(VALUE mod, VALUE vid) { return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qfalse); } static VALUE rb_mod_public_instance_method(VALUE mod, VALUE vid) { return mnew(mod, Qundef, rb_to_id(vid), rb_cUnboundMethod, Qtrue); } /* * call-seq: * define_method(symbol, method) => new_method * define_method(symbol) { block } => proc * * Defines an instance method in the receiver. The _method_ * parameter can be a +Proc+ or +Method+ object. * If a block is specified, it is used as the method body. This block * is evaluated using <code>instance_eval</code>, a point that is * tricky to demonstrate because <code>define_method</code> is private. * (This is why we resort to the +send+ hack in this example.) * * class A * def fred * puts "In Fred" * end * def create_method(name, &block) * self.class.send(:define_method, name, &block) * end * define_method(:wilma) { puts "Charge it!" } * end * class B < A * define_method(:barney, instance_method(:fred)) * end * a = B.new * a.barney * a.wilma * a.create_method(:betty) { p self } * a.betty * * <em>produces:</em> * * In Fred * Charge it! * #<B:0x401b39e8> */ static VALUE rb_mod_define_method(int argc, VALUE *argv, VALUE mod) { ID id; VALUE body; NODE *node; int noex = NOEX_PUBLIC; if (argc == 1) { id = rb_to_id(argv[0]); body = rb_block_lambda(); } else if (argc == 2) { id = rb_to_id(argv[0]); body = argv[1]; if (!rb_obj_is_method(body) && !rb_obj_is_proc(body)) { rb_raise(rb_eTypeError, "wrong argument type %s (expected Proc/Method)", rb_obj_classname(body)); } } else { rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc); } if (RDATA(body)->dmark == (RUBY_DATA_FUNC) bm_mark) { struct METHOD *method = (struct METHOD *)DATA_PTR(body); VALUE rclass = method->rclass; if (rclass != mod) { if (FL_TEST(rclass, FL_SINGLETON)) { rb_raise(rb_eTypeError, "can't bind singleton method to a different class"); } if (!RTEST(rb_class_inherited_p(mod, rclass))) { rb_raise(rb_eTypeError, "bind argument must be a subclass of %s", rb_class2name(rclass)); } } node = method->body; } else if (rb_obj_is_proc(body)) { rb_proc_t *proc; body = proc_dup(body); GetProcPtr(body, proc); if (BUILTIN_TYPE(proc->block.iseq) != T_NODE) { proc->block.iseq->defined_method_id = id; proc->block.iseq->klass = mod; proc->is_lambda = Qtrue; proc->is_from_method = Qtrue; } node = NEW_BMETHOD(body); } else { /* type error */ rb_raise(rb_eTypeError, "wrong argument type (expected Proc/Method)"); } /* TODO: visibility */ rb_add_method(mod, id, node, noex); return body; } static VALUE rb_obj_define_method(int argc, VALUE *argv, VALUE obj) { VALUE klass = rb_singleton_class(obj); return rb_mod_define_method(argc, argv, klass); } /* * MISSING: documentation */ static VALUE method_clone(VALUE self) { VALUE clone; struct METHOD *orig, *data; Data_Get_Struct(self, struct METHOD, orig); clone = Data_Make_Struct(CLASS_OF(self), struct METHOD, bm_mark, -1, data); CLONESETUP(clone, self); *data = *orig; return clone; } /* * call-seq: * meth.call(args, ...) => obj * meth[args, ...] => obj * * Invokes the <i>meth</i> with the specified arguments, returning the * method's return value. * * m = 12.method("+") * m.call(3) #=> 15 * m.call(20) #=> 32 */ VALUE rb_method_call(int argc, VALUE *argv, VALUE method) { VALUE result = Qnil; /* OK */ struct METHOD *data; int state; volatile int safe = -1; Data_Get_Struct(method, struct METHOD, data); if (data->recv == Qundef) { rb_raise(rb_eTypeError, "can't call unbound method; bind first"); } PUSH_TAG(); if (OBJ_TAINTED(method)) { safe = rb_safe_level(); if (rb_safe_level() < 4) { rb_set_safe_level_force(4); } } if ((state = EXEC_TAG()) == 0) { rb_thread_t *th = GET_THREAD(); VALUE rb_vm_call(rb_thread_t * th, VALUE klass, VALUE recv, VALUE id, ID oid, int argc, const VALUE *argv, const NODE *body, int nosuper); PASS_PASSED_BLOCK_TH(th); result = rb_vm_call(th, data->oclass, data->recv, data->id, data->oid, argc, argv, data->body, 0); } POP_TAG(); if (safe >= 0) rb_set_safe_level_force(safe); if (state) JUMP_TAG(state); return result; } /********************************************************************** * * Document-class: UnboundMethod * * Ruby supports two forms of objectified methods. Class * <code>Method</code> is used to represent methods that are associated * with a particular object: these method objects are bound to that * object. Bound method objects for an object can be created using * <code>Object#method</code>. * * Ruby also supports unbound methods; methods objects that are not * associated with a particular object. These can be created either by * calling <code>Module#instance_method</code> or by calling * <code>unbind</code> on a bound method object. The result of both of * these is an <code>UnboundMethod</code> object. * * Unbound methods can only be called after they are bound to an * object. That object must be be a kind_of? the method's original * class. * * class Square * def area * @side * @side * end * def initialize(side) * @side = side * end * end * * area_un = Square.instance_method(:area) * * s = Square.new(12) * area = area_un.bind(s) * area.call #=> 144 * * Unbound methods are a reference to the method at the time it was * objectified: subsequent changes to the underlying class will not * affect the unbound method. * * class Test * def test * :original * end * end * um = Test.instance_method(:test) * class Test * def test * :modified * end * end * t = Test.new * t.test #=> :modified * um.bind(t).call #=> :original * */ /* * call-seq: * umeth.bind(obj) -> method * * Bind <i>umeth</i> to <i>obj</i>. If <code>Klass</code> was the class * from which <i>umeth</i> was obtained, * <code>obj.kind_of?(Klass)</code> must be true. * * class A * def test * puts "In test, class = #{self.class}" * end * end * class B < A * end * class C < B * end * * * um = B.instance_method(:test) * bm = um.bind(C.new) * bm.call * bm = um.bind(B.new) * bm.call * bm = um.bind(A.new) * bm.call * * <em>produces:</em> * * In test, class = C * In test, class = B * prog.rb:16:in `bind': bind argument must be an instance of B (TypeError) * from prog.rb:16 */ static VALUE umethod_bind(VALUE method, VALUE recv) { struct METHOD *data, *bound; Data_Get_Struct(method, struct METHOD, data); if (data->rclass != CLASS_OF(recv)) { if (FL_TEST(data->rclass, FL_SINGLETON)) { rb_raise(rb_eTypeError, "singleton method called for a different object"); } if (!rb_obj_is_kind_of(recv, data->rclass)) { rb_raise(rb_eTypeError, "bind argument must be an instance of %s", rb_class2name(data->rclass)); } } method = Data_Make_Struct(rb_cMethod, struct METHOD, bm_mark, -1, bound); *bound = *data; bound->recv = recv; bound->rclass = CLASS_OF(recv); return method; } int rb_node_arity(NODE* body) { switch (nd_type(body)) { case NODE_CFUNC: if (body->nd_argc < 0) return -1; return check_argc(body->nd_argc); case NODE_ZSUPER: return -1; case NODE_ATTRSET: return 1; case NODE_IVAR: return 0; case NODE_BMETHOD: return rb_proc_arity(body->nd_cval); case RUBY_VM_METHOD_NODE: { rb_iseq_t *iseq; GetISeqPtr((VALUE)body->nd_body, iseq); if (iseq->arg_rest == -1 && iseq->arg_opts == 0) { return iseq->argc; } else { return -(iseq->argc + 1 + iseq->arg_post_len); } } default: rb_raise(rb_eArgError, "invalid node 0x%x", nd_type(body)); } } /* * call-seq: * meth.arity => fixnum * * Returns an indication of the number of arguments accepted by a * method. Returns a nonnegative integer for methods that take a fixed * number of arguments. For Ruby methods that take a variable number of * arguments, returns -n-1, where n is the number of required * arguments. For methods written in C, returns -1 if the call takes a * variable number of arguments. * * class C * def one; end * def two(a); end * def three(*a); end * def four(a, b); end * def five(a, b, *c); end * def six(a, b, *c, &d); end * end * c = C.new * c.method(:one).arity #=> 0 * c.method(:two).arity #=> 1 * c.method(:three).arity #=> -1 * c.method(:four).arity #=> 2 * c.method(:five).arity #=> -3 * c.method(:six).arity #=> -3 * * "cat".method(:size).arity #=> 0 * "cat".method(:replace).arity #=> 1 * "cat".method(:squeeze).arity #=> -1 * "cat".method(:count).arity #=> -1 */ static VALUE method_arity_m(VALUE method) { int n = method_arity(method); return INT2FIX(n); } static int method_arity(VALUE method) { struct METHOD *data; Data_Get_Struct(method, struct METHOD, data); return rb_node_arity(data->body); } int rb_mod_method_arity(VALUE mod, ID id) { NODE *node = rb_method_node(mod, id); return rb_node_arity(node); } int rb_obj_method_arity(VALUE obj, ID id) { return rb_mod_method_arity(CLASS_OF(obj), id); } static rb_iseq_t * get_method_iseq(VALUE method) { struct METHOD *data; NODE *body; rb_iseq_t *iseq; Data_Get_Struct(method, struct METHOD, data); body = data->body; switch (nd_type(body)) { case RUBY_VM_METHOD_NODE: GetISeqPtr((VALUE)body->nd_body, iseq); if (RUBY_VM_NORMAL_ISEQ_P(iseq)) break; default: return 0; } return iseq; } /* * call-seq: * meth.source_location => [String, Fixnum] * * returns the ruby source filename and line number containing this method * or nil if this method was not defined in ruby (i.e. native) */ VALUE rb_method_location(VALUE method) { return iseq_location(get_method_iseq(method)); } /* * call-seq: * meth.to_s => string * meth.inspect => string * * Show the name of the underlying method. * * "cat".method(:count).inspect #=> "#<Method: String#count>" */ static VALUE method_inspect(VALUE method) { struct METHOD *data; VALUE str; const char *s; const char *sharp = "#"; Data_Get_Struct(method, struct METHOD, data); str = rb_str_buf_new2("#<"); s = rb_obj_classname(method); rb_str_buf_cat2(str, s); rb_str_buf_cat2(str, ": "); if (FL_TEST(data->oclass, FL_SINGLETON)) { VALUE v = rb_iv_get(data->oclass, "__attached__"); if (data->recv == Qundef) { rb_str_buf_append(str, rb_inspect(data->oclass)); } else if (data->recv == v) { rb_str_buf_append(str, rb_inspect(v)); sharp = "."; } else { rb_str_buf_append(str, rb_inspect(data->recv)); rb_str_buf_cat2(str, "("); rb_str_buf_append(str, rb_inspect(v)); rb_str_buf_cat2(str, ")"); sharp = "."; } } else { rb_str_buf_cat2(str, rb_class2name(data->rclass)); if (data->rclass != data->oclass) { rb_str_buf_cat2(str, "("); rb_str_buf_cat2(str, rb_class2name(data->oclass)); rb_str_buf_cat2(str, ")"); } } rb_str_buf_cat2(str, sharp); rb_str_append(str, rb_id2str(data->oid)); rb_str_buf_cat2(str, ">"); return str; } static VALUE mproc(VALUE method) { return rb_funcall(Qnil, rb_intern("proc"), 0); } static VALUE mlambda(VALUE method) { return rb_funcall(Qnil, rb_intern("lambda"), 0); } static VALUE bmcall(VALUE args, VALUE method) { volatile VALUE a; VALUE ret; int argc; if (CLASS_OF(args) != rb_cArray) { args = rb_ary_new3(1, args); argc = 1; } else { argc = check_argc(RARRAY_LEN(args)); } ret = rb_method_call(argc, RARRAY_PTR(args), method); RB_GC_GUARD(a) = args; return ret; } VALUE rb_proc_new( VALUE (*func)(ANYARGS), /* VALUE yieldarg[, VALUE procarg] */ VALUE val) { VALUE procval = rb_iterate(mproc, 0, func, val); return procval; } /* * call-seq: * meth.to_proc => prc * * Returns a <code>Proc</code> object corresponding to this method. */ static VALUE method_proc(VALUE method) { VALUE procval; rb_proc_t *proc; /* * class Method * def to_proc * proc{|*args| * self.call(*args) * } * end * end */ procval = rb_iterate(mlambda, 0, bmcall, method); GetProcPtr(procval, proc); proc->is_from_method = 1; return procval; } static VALUE rb_obj_is_method(VALUE m) { if (TYPE(m) == T_DATA && RDATA(m)->dmark == (RUBY_DATA_FUNC) bm_mark) { return Qtrue; } return Qfalse; } /* * call_seq: * local_jump_error.exit_value => obj * * Returns the exit value associated with this +LocalJumpError+. */ static VALUE localjump_xvalue(VALUE exc) { return rb_iv_get(exc, "@exit_value"); } /* * call-seq: * local_jump_error.reason => symbol * * The reason this block was terminated: * :break, :redo, :retry, :next, :return, or :noreason. */ static VALUE localjump_reason(VALUE exc) { return rb_iv_get(exc, "@reason"); } /* * call-seq: * prc.binding => binding * * Returns the binding associated with <i>prc</i>. Note that * <code>Kernel#eval</code> accepts either a <code>Proc</code> or a * <code>Binding</code> object as its second parameter. * * def fred(param) * proc {} * end * * b = fred(99) * eval("param", b.binding) #=> 99 */ static VALUE proc_binding(VALUE self) { rb_proc_t *proc; VALUE bindval = binding_alloc(rb_cBinding); rb_binding_t *bind; GetProcPtr(self, proc); GetBindingPtr(bindval, bind); if (TYPE(proc->block.iseq) == T_NODE) { rb_raise(rb_eArgError, "Can't create Binding from C level Proc"); } bind->env = proc->envval; return bindval; } static VALUE curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc); static VALUE make_curry_proc(VALUE proc, VALUE passed, VALUE arity) { VALUE args = rb_ary_new3(3, proc, passed, arity); rb_ary_freeze(passed); rb_ary_freeze(args); return rb_proc_new(curry, args); } static VALUE curry(VALUE dummy, VALUE args, int argc, VALUE *argv, VALUE passed_proc) { VALUE proc, passed, arity; proc = RARRAY_PTR(args)[0]; passed = RARRAY_PTR(args)[1]; arity = RARRAY_PTR(args)[2]; passed = rb_ary_plus(passed, rb_ary_new4(argc, argv)); rb_ary_freeze(passed); if(RARRAY_LEN(passed) < FIX2INT(arity)) { if (!NIL_P(passed_proc)) { rb_warn("given block not used"); } arity = make_curry_proc(proc, passed, arity); return arity; } else { return rb_proc_call_with_block(proc, check_argc(RARRAY_LEN(passed)), RARRAY_PTR(passed), passed_proc); } } /* * call-seq: * prc.curry => a_proc * prc.curry(arity) => a_proc * * Returns a curried proc. If the optional <i>arity</i> argument is given, * it determines the number of arguments. * A curried proc receives some arguments. If a sufficient number of * arguments are supplied, it passes the supplied arguments to the original * proc and returns the result. Otherwise, returns another curried proc that * takes the rest of arguments. * * b = proc {|x, y, z| (x||0) + (y||0) + (z||0) } * p b.curry[1][2][3] #=> 6 * p b.curry[1, 2][3, 4] #=> 6 * p b.curry(5)[1][2][3][4][5] #=> 6 * p b.curry(5)[1, 2][3, 4][5] #=> 6 * p b.curry(1)[1] #=> 1 * * b = proc {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) } * p b.curry[1][2][3] #=> 6 * p b.curry[1, 2][3, 4] #=> 10 * p b.curry(5)[1][2][3][4][5] #=> 15 * p b.curry(5)[1, 2][3, 4][5] #=> 15 * p b.curry(1)[1] #=> 1 * * b = lambda {|x, y, z| (x||0) + (y||0) + (z||0) } * p b.curry[1][2][3] #=> 6 * p b.curry[1, 2][3, 4] #=> wrong number of arguments (4 or 3) * p b.curry(5) #=> wrong number of arguments (5 or 3) * p b.curry(1) #=> wrong number of arguments (1 or 3) * * b = lambda {|x, y, z, *w| (x||0) + (y||0) + (z||0) + w.inject(0, &:+) } * p b.curry[1][2][3] #=> 6 * p b.curry[1, 2][3, 4] #=> 10 * p b.curry(5)[1][2][3][4][5] #=> 15 * p b.curry(5)[1, 2][3, 4][5] #=> 15 * p b.curry(1) #=> wrong number of arguments (1 or 3) * * b = proc { :foo } * p b.curry[] #=> :foo */ static VALUE proc_curry(int argc, VALUE *argv, VALUE self) { int sarity, marity = FIX2INT(proc_arity(self)); VALUE arity, opt = Qfalse; if (marity < 0) { marity = -marity - 1; opt = Qtrue; } rb_scan_args(argc, argv, "01", &arity); if (NIL_P(arity)) { arity = INT2FIX(marity); } else { sarity = FIX2INT(arity); if (proc_lambda_p(self) && (sarity < marity || (sarity > marity && !opt))) { rb_raise(rb_eArgError, "wrong number of arguments (%d for %d)", sarity, marity); } } return make_curry_proc(self, rb_ary_new(), arity); } /* * <code>Proc</code> objects are blocks of code that have been bound to * a set of local variables. Once bound, the code may be called in * different contexts and still access those variables. * * def gen_times(factor) * return Proc.new {|n| n*factor } * end * * times3 = gen_times(3) * times5 = gen_times(5) * * times3.call(12) #=> 36 * times5.call(5) #=> 25 * times3.call(times5.call(4)) #=> 60 * */ void Init_Proc(void) { /* Proc */ rb_cProc = rb_define_class("Proc", rb_cObject); rb_undef_alloc_func(rb_cProc); rb_define_singleton_method(rb_cProc, "new", rb_proc_s_new, -1); rb_define_method(rb_cProc, "call", proc_call, -1); rb_define_method(rb_cProc, "[]", proc_call, -1); rb_define_method(rb_cProc, "===", proc_call, -1); rb_define_method(rb_cProc, "yield", proc_call, -1); rb_define_method(rb_cProc, "to_proc", proc_to_proc, 0); rb_define_method(rb_cProc, "arity", proc_arity, 0); rb_define_method(rb_cProc, "clone", proc_clone, 0); rb_define_method(rb_cProc, "dup", proc_dup, 0); rb_define_method(rb_cProc, "==", proc_eq, 1); rb_define_method(rb_cProc, "eql?", proc_eq, 1); rb_define_method(rb_cProc, "hash", proc_hash, 0); rb_define_method(rb_cProc, "to_s", proc_to_s, 0); rb_define_method(rb_cProc, "lambda?", proc_lambda_p, 0); rb_define_method(rb_cProc, "binding", proc_binding, 0); rb_define_method(rb_cProc, "curry", proc_curry, -1); rb_define_method(rb_cProc, "source_location", rb_proc_location, 0); /* Exceptions */ rb_eLocalJumpError = rb_define_class("LocalJumpError", rb_eStandardError); rb_define_method(rb_eLocalJumpError, "exit_value", localjump_xvalue, 0); rb_define_method(rb_eLocalJumpError, "reason", localjump_reason, 0); rb_eSysStackError = rb_define_class("SystemStackError", rb_eException); sysstack_error = rb_exc_new3(rb_eSysStackError, rb_obj_freeze(rb_str_new2("stack level too deep"))); OBJ_TAINT(sysstack_error); OBJ_FREEZE(sysstack_error); /* utility functions */ rb_define_global_function("proc", rb_block_proc, 0); rb_define_global_function("lambda", proc_lambda, 0); /* Method */ rb_cMethod = rb_define_class("Method", rb_cObject); rb_undef_alloc_func(rb_cMethod); rb_undef_method(CLASS_OF(rb_cMethod), "new"); rb_define_method(rb_cMethod, "==", method_eq, 1); rb_define_method(rb_cMethod, "eql?", method_eq, 1); rb_define_method(rb_cMethod, "hash", method_hash, 0); rb_define_method(rb_cMethod, "clone", method_clone, 0); rb_define_method(rb_cMethod, "call", rb_method_call, -1); rb_define_method(rb_cMethod, "[]", rb_method_call, -1); rb_define_method(rb_cMethod, "arity", method_arity_m, 0); rb_define_method(rb_cMethod, "inspect", method_inspect, 0); rb_define_method(rb_cMethod, "to_s", method_inspect, 0); rb_define_method(rb_cMethod, "to_proc", method_proc, 0); rb_define_method(rb_cMethod, "receiver", method_receiver, 0); rb_define_method(rb_cMethod, "name", method_name, 0); rb_define_method(rb_cMethod, "owner", method_owner, 0); rb_define_method(rb_cMethod, "unbind", method_unbind, 0); rb_define_method(rb_cMethod, "source_location", rb_method_location, 0); rb_define_method(rb_mKernel, "method", rb_obj_method, 1); rb_define_method(rb_mKernel, "public_method", rb_obj_public_method, 1); /* UnboundMethod */ rb_cUnboundMethod = rb_define_class("UnboundMethod", rb_cObject); rb_undef_alloc_func(rb_cUnboundMethod); rb_undef_method(CLASS_OF(rb_cUnboundMethod), "new"); rb_define_method(rb_cUnboundMethod, "==", method_eq, 1); rb_define_method(rb_cUnboundMethod, "eql?", method_eq, 1); rb_define_method(rb_cUnboundMethod, "hash", method_hash, 0); rb_define_method(rb_cUnboundMethod, "clone", method_clone, 0); rb_define_method(rb_cUnboundMethod, "arity", method_arity_m, 0); rb_define_method(rb_cUnboundMethod, "inspect", method_inspect, 0); rb_define_method(rb_cUnboundMethod, "to_s", method_inspect, 0); rb_define_method(rb_cUnboundMethod, "name", method_name, 0); rb_define_method(rb_cUnboundMethod, "owner", method_owner, 0); rb_define_method(rb_cUnboundMethod, "bind", umethod_bind, 1); rb_define_method(rb_cUnboundMethod, "source_location", rb_method_location, 0); /* Module#*_method */ rb_define_method(rb_cModule, "instance_method", rb_mod_instance_method, 1); rb_define_method(rb_cModule, "public_instance_method", rb_mod_public_instance_method, 1); rb_define_private_method(rb_cModule, "define_method", rb_mod_define_method, -1); /* Kernel */ rb_define_method(rb_mKernel, "define_singleton_method", rb_obj_define_method, -1); } /* * Objects of class <code>Binding</code> encapsulate the execution * context at some particular place in the code and retain this context * for future use. The variables, methods, value of <code>self</code>, * and possibly an iterator block that can be accessed in this context * are all retained. Binding objects can be created using * <code>Kernel#binding</code>, and are made available to the callback * of <code>Kernel#set_trace_func</code>. * * These binding objects can be passed as the second argument of the * <code>Kernel#eval</code> method, establishing an environment for the * evaluation. * * class Demo * def initialize(n) * @secret = n * end * def getBinding * return binding() * end * end * * k1 = Demo.new(99) * b1 = k1.getBinding * k2 = Demo.new(-3) * b2 = k2.getBinding * * eval("@secret", b1) #=> 99 * eval("@secret", b2) #=> -3 * eval("@secret") #=> nil * * Binding objects have no class-specific methods. * */ void Init_Binding(void) { rb_cBinding = rb_define_class("Binding", rb_cObject); rb_undef_alloc_func(rb_cBinding); rb_undef_method(CLASS_OF(rb_cBinding), "new"); rb_define_method(rb_cBinding, "clone", binding_clone, 0); rb_define_method(rb_cBinding, "dup", binding_dup, 0); rb_define_method(rb_cBinding, "eval", bind_eval, -1); rb_define_global_function("binding", rb_f_binding, 0); }
24.852881
95
0.612845
[ "object" ]
fd6250b2ad0be0c037cd64ace7beca87da8058d4
6,286
h
C
src/Filtering/tubeImageMathFilters.h
kian-weimer/ITKTubeTK
88da3195bfeca017745e7cddfe04f82571bd00ee
[ "Apache-2.0" ]
27
2020-04-06T17:23:22.000Z
2022-03-02T13:25:52.000Z
src/Filtering/tubeImageMathFilters.h
kian-weimer/ITKTubeTK
88da3195bfeca017745e7cddfe04f82571bd00ee
[ "Apache-2.0" ]
14
2020-04-09T00:23:15.000Z
2022-02-26T13:02:35.000Z
src/Filtering/tubeImageMathFilters.h
kian-weimer/ITKTubeTK
88da3195bfeca017745e7cddfe04f82571bd00ee
[ "Apache-2.0" ]
14
2020-04-03T03:56:14.000Z
2022-01-14T07:51:32.000Z
/*========================================================================= Library: TubeTK Copyright Kitware Inc. 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. =========================================================================*/ #ifndef __tubeImageMathFilters_h #define __tubeImageMathFilters_h #include <itkImageFileReader.h> #include <itkContinuousIndex.h> #include <itkImageDuplicator.h> namespace tube { template< unsigned int VDimension > class ImageMathFilters { public: typedef float PixelType; typedef itk::Image< PixelType, VDimension > ImageType; ImageMathFilters(); ~ImageMathFilters(); void SetInput( ImageType * input ) { typename ImageType::Pointer tmpImage = ImageType::New(); tmpImage = input; typename itk::ImageDuplicator< ImageType >::Pointer dupFilter = itk::ImageDuplicator< ImageType >::New(); dupFilter->SetInputImage( tmpImage ); dupFilter->Update(); m_Input = dupFilter->GetOutput(); } ImageType * GetInput( void ) { return m_Input; } ImageType * GetOutput( void ) { return m_Input; } /** Intensity window inVal range to outValRange. */ void ApplyIntensityWindowing( float inValMin, float inValMax, float outMin, float outMax ); /** Intensity multiplicative correct using inMeanField. */ void ApplyIntensityMultiplicativeBiasCorrection( ImageType * inMeanFieldImage ); /** Resamples image a to b if they are different, returns resampled_a */ void ResampleImage( ImageType * ref ); /** Adds uniform noise to all pixels within inVal range */ void AddUniformNoise( float valMin, float valMax, float noiseMean, float noiseRange, int seed ); /** Adds Gaussian noise to all pixels within inVal range */ void AddGaussianNoise( float valMin, float valMax, float noiseMean, float noiseStdDev, int seed ); /** I( x ) = weight1*I( x ) + weight2*inFile2( x ) */ void AddImages( ImageType * input2, float weight1, float weight2 ); /** I( x ) = I( x ) * inFile2( x ) */ void MultiplyImages( ImageType * input2 ); /** Use mirroring to pad an image. */ void MirrorAndPadImage( int numPadVoxels ); /** Normalize: = mean/std; 1 = FWHM ; 2 = FWHM mean ( shift ) only */ void NormalizeImage( int normType ); /** Fuse two images by max, applying offset to second image. */ void FuseImages( ImageType * input2, float offset2 ); /** Apply median filter to the image. */ void MedianImage( int size ); /** If I( x ) in [tLow,tHigh] then I( x )=vTrue else I( x )=vFalse. */ void ThresholdImage( float threshLow, float threshHigh, float valTrue, float valFalse ); /** Return image value within masked region ( mode: 0=mean, 1=stdDev ) */ double ComputeImageStatisticsWithinMaskRange( ImageType * mask, float threshLow, float threshHigh, int mode ); /** Copy origin, spacing, and directions from sourceImage */ void CopyImageInformation( ImageType * sourceImage ); /** Update image applying 'abs' unary operation. */ void AbsoluteImage( void ); /** If inFile( x ) in [tLow, tHigh] then I( x )=I( x ) else I( x )=vFalse */ void ReplaceValuesOutsideMaskRange( ImageType * mask, float maskThreshLow, float maskThreshHigh, float valFalse ); /** Mathematical morphology using a sphere. Mode: 0=erode, 1=dilate. */ void MorphImage( int mode, int radius, float foregroundValue, float backgroundValue ); /** Replace values within the image, with a mask. */ void ReplaceValueWithinMaskRange( ImageType * mask, float maskThreshLow, float maskThreshHigh, float imageVal, float newImageVal ); /** Gaussian blur the image using the given sigma */ void BlurImage( float sigma ); /** Gaussian blur the image using the given sigma, order and direction. */ void BlurOrderImage( float sigma, int order, int direction ); /** Write the image's histogram to the designated file. */ std::vector<double> ComputeImageHistogram( unsigned int nBins, float & binMin, float & binSize ); /** Correct intensity slice-by-slice using HistogramMatchingFilter. */ void CorrectIntensitySliceBySliceUsingHistogramMatching( unsigned int numberOfBins, unsigned int numberOfMatchPoints ); /** Match intensity to another volume using HistogramMatchingFilter. */ void CorrectIntensityUsingHistogramMatching( unsigned int numberOfBins, unsigned int numberOfMatchPoints, ImageType * ref ); /** Resample to reduce by a factor ( factor==0 means make isotropic ) */ void Resize( double factor ); /** Resample to match inFile2. */ void Resize( ImageType * ref ); /** Extract a single slice from the image. */ void ExtractSlice( unsigned int dimension, unsigned int slice ); /** Compute ridgness/vesselness for specified scales. */ void EnhanceVessels( double scaleMin, double scaleMax, double numScales ); /** Segment using ( inclusive ) threshold connected components. */ void SegmentUsingConnectedThreshold( float threshLow, float threshHigh, float labelValue, float x, float y, float z ); /** Run centroid voronoi tessellation on the image. */ std::vector< itk::ContinuousIndex< double, VDimension > > ComputeVoronoiTessellation( unsigned int numberOfCentroids, unsigned int numberOfIterations, unsigned int numberOfSamples ); itk::VariableSizeMatrix< double > GetVoronoiTessellationAdjacencyMatrix() { return m_VoronoiTessellationAdjacencyMatrix; }; private: typename ImageType::Pointer m_Input; itk::VariableSizeMatrix< double > m_VoronoiTessellationAdjacencyMatrix; }; // End class ImageMathFilters } // End namespace tube #ifndef ITK_MANUAL_INSTANTIATION #include "tubeImageMathFilters.hxx" #endif #endif // End !defined( __tubeImageMathFilters_h )
33.795699
78
0.702036
[ "vector" ]
fd757af7a0fe2167b88bb018ae8c463df02d5f3c
20,932
c
C
Usermode/Applications/axwin3_src/WM/renderers/widget.c
thepowersgang/acess2
b52f9a841f47d7f29e9813b215e1290f191b5171
[ "Zlib" ]
58
2015-02-11T23:18:09.000Z
2022-02-23T14:11:11.000Z
Usermode/Applications/axwin3_src/WM/renderers/widget.c
thepowersgang/acess2
b52f9a841f47d7f29e9813b215e1290f191b5171
[ "Zlib" ]
5
2015-01-12T03:28:04.000Z
2016-01-12T12:21:34.000Z
Usermode/Applications/axwin3_src/WM/renderers/widget.c
thepowersgang/acess2
b52f9a841f47d7f29e9813b215e1290f191b5171
[ "Zlib" ]
10
2015-04-05T08:03:36.000Z
2022-02-09T23:33:58.000Z
/* * Acess2 Window Manager v3 * - By John Hodge (thePowersGang) * * render_widget.c * - AxWin2 Widget port */ #include <common.h> #include <wm_renderer.h> #include <renderer_widget.h> #include <string.h> #include <wm_messages.h> #include <stdlib.h> #include "widget/common.h" #define DEFAULT_ELETABLE_SIZE 64 #define BORDER_EVERYTHING 0 // === IMPORTS === extern tWidgetDef _widget_typedef_ELETYPE_IMAGE; extern tWidgetDef _widget_typedef_ELETYPE_BUTTON; extern tWidgetDef _widget_typedef_ELETYPE_TEXT; extern tWidgetDef _widget_typedef_ELETYPE_TEXTINPUT; extern tWidgetDef _widget_typedef_ELETYPE_SPACER; extern tWidgetDef _widget_typedef_ELETYPE_SUBWIN; // === PROTOTYPES === int Renderer_Widget_Init(void); tWindow *Renderer_Widget_Create(int Flags); void Renderer_Widget_Redraw(tWindow *Window); void Widget_RenderWidget(tWindow *Window, tElement *Element); void Widget_UpdateDimensions(tElement *Element); void Widget_UpdatePosition(tElement *Element); // --- Messages tElement *Widget_GetElementById(tWidgetWin *Info, uint32_t ID); int Widget_IPC_Create(tWindow *Win, size_t Len, const void *Data); int Widget_IPC_NewWidgetSubwin(tWindow *Win, size_t Len, const void *Data); // int Widget_IPC_Delete(tWindow *Win, size_t Len, const void *Data); int Widget_IPC_SetFocus(tWindow *Win, size_t Len, const void *Data); int Widget_IPC_SetFlags(tWindow *Win, size_t Len, const void *Data); int Widget_IPC_SetSize(tWindow *Win, size_t Len, const void *Data); int Widget_IPC_SetText(tWindow *Win, size_t Len, const void *Data); int Widget_IPC_GetText(tWindow *Win, size_t Len, const void *Data); // int Widget_IPC_SetColour(tWindow *Win, size_t Len, const void *Data); int Renderer_Widget_HandleMessage(tWindow *Target, int Msg, int Len, const void *Data); // === GLOBALS === tWMRenderer gRenderer_Widget = { .Name = "Widget", .CreateWindow = Renderer_Widget_Create, .Redraw = Renderer_Widget_Redraw, .HandleMessage = Renderer_Widget_HandleMessage, .nIPCHandlers = N_IPC_WIDGET, .IPCHandlers = { [IPC_WIDGET_CREATE] = Widget_IPC_Create, [IPC_WIDGET_CREATESUBWIN] = Widget_IPC_NewWidgetSubwin, [IPC_WIDGET_SETFOCUS] = Widget_IPC_SetFocus, [IPC_WIDGET_SETFLAGS] = Widget_IPC_SetFlags, [IPC_WIDGET_SETSIZE] = Widget_IPC_SetSize, [IPC_WIDGET_SETTEXT] = Widget_IPC_SetText, [IPC_WIDGET_GETTEXT] = Widget_IPC_GetText, } }; // --- Element callbacks tWidgetDef *gaWM_WidgetTypes[NUM_ELETYPES] = { [ELETYPE_IMAGE] = &_widget_typedef_ELETYPE_IMAGE, [ELETYPE_BUTTON] = &_widget_typedef_ELETYPE_BUTTON, [ELETYPE_TEXT] = &_widget_typedef_ELETYPE_TEXT, [ELETYPE_TEXTINPUT] = &_widget_typedef_ELETYPE_TEXTINPUT, [ELETYPE_SPACER] = &_widget_typedef_ELETYPE_SPACER, [ELETYPE_SUBWIN] = &_widget_typedef_ELETYPE_SUBWIN, }; const int ciWM_NumWidgetTypes = sizeof(gaWM_WidgetTypes)/sizeof(gaWM_WidgetTypes[0]); tWidgetDef gWidget_NullWidgetDef; // === CODE === int Renderer_Widget_Init(void) { WM_RegisterRenderer(&gRenderer_Widget); for(int i = 0; i < ciWM_NumWidgetTypes; i ++) { if(gaWM_WidgetTypes[i] != NULL) continue; gaWM_WidgetTypes[i] = &gWidget_NullWidgetDef; } return 0; } void Widget_int_SetTypeDef(int Type, tWidgetDef *Ptr) { if( Type < 0 || Type >= ciWM_NumWidgetTypes ) { _SysDebug("ERROR - Widget ID %i out of range (from %p)", Type, __builtin_return_address(0) ); return ; } if( gaWM_WidgetTypes[Type] && gaWM_WidgetTypes[Type] != &gWidget_NullWidgetDef ) { _SysDebug("ERROR - Widget ID %i redefined by %p", Type, __builtin_return_address(0) ); return ; } gaWM_WidgetTypes[Type] = Ptr; _SysDebug("Registered widget type %i '%s'", Type, Ptr->Name); } tWindow *Renderer_Widget_Create(int Flags) { tWindow *ret; tWidgetWin *info; int eletable_size = DEFAULT_ELETABLE_SIZE; //_SysDebug("Renderer_Widget_Create: (Flags = 0x%x)", Flags); // TODO: Use `Flags` as default element count? // - Actaully, it's taken by the root ele flags // - Use the upper bits? ret = WM_CreateWindowStruct( sizeof(tWidgetWin) + sizeof(tElement*)*eletable_size ); info = ret->RendererInfo; info->TableSize = eletable_size; info->FocusedElement = &info->RootElement; info->RootElement.Window = ret; info->RootElement.ID = -1; info->RootElement.BackgroundColour = 0xCCCCCC; info->RootElement.Flags = Flags; info->RootElement.PaddingT = 2; info->RootElement.PaddingB = 2; info->RootElement.PaddingL = 2; info->RootElement.PaddingR = 2; return ret; } void Renderer_Widget_Redraw(tWindow *Window) { tWidgetWin *info = Window->RendererInfo; WM_Render_FillRect(Window, 0, 0, Window->W, Window->H, info->RootElement.BackgroundColour); Widget_UpdateDimensions(&info->RootElement); Widget_UpdatePosition(&info->RootElement); Widget_RenderWidget(Window, &info->RootElement); } // --- Render / Resize --- void Widget_RenderWidget(tWindow *Window, tElement *Element) { tElement *child; if( Element->Flags & ELEFLAG_NORENDER ) return ; if( Element->Flags & ELEFLAG_INVISIBLE ) return ; #if BORDER_EVERYTHING WM_Render_DrawRect( Window, Element->CachedX, Element->CachedY, Element->CachedW, Element->CachedH, 0 ); #endif if(gaWM_WidgetTypes[Element->Type]->Render) { gaWM_WidgetTypes[Element->Type]->Render(Window, Element); } for(child = Element->FirstChild; child; child = child->NextSibling) { Widget_RenderWidget(Window, child); } } void Widget_UpdateDimensions(tElement *Element) { tElement *child; int nChildren = 0; int nFixed = 0; int maxCross = 0; int fixedSize = 0; int fullCross, dynWith = 0; int bVertical = Element->Flags & ELEFLAG_VERTICAL; // Check if this element can have children if( (gaWM_WidgetTypes[Element->Type]->Flags & WIDGETTYPE_FLAG_NOCHILDREN) ) return ; // Pass 1 // - Get the fixed and minimum sizes of the element for( child = Element->FirstChild; child; child = child->NextSibling ) { int minWith = bVertical ? child->MinH : child->MinW; int minCross = bVertical ? child->MinW : child->MinH; // Ignore elements that will not be rendered if( child->Flags & ELEFLAG_NORENDER ) continue ; // Absolutely positioned elements don't affect dimensions if( child->Flags & ELEFLAG_ABSOLUTEPOS ) continue ; // Fixed width elements if( child->FixedWith ) { nFixed ++; fixedSize += child->FixedWith; } else if( child->Flags & ELEFLAG_NOSTRETCH ) { nFixed ++; fixedSize += minWith; } if( maxCross < child->FixedCross ) maxCross = child->FixedCross; if( maxCross < minCross ) maxCross = minCross; nChildren ++; } // Get the dynamic with size from the unused space in the element if( nChildren > nFixed ) { if( bVertical ) dynWith = Element->CachedH - Element->PaddingT - Element->PaddingB; else dynWith = Element->CachedW - Element->PaddingL - Element->PaddingR; dynWith -= fixedSize; dynWith -= Element->GapSize * (nChildren-1); if( dynWith < 0 ) return ; dynWith /= nChildren - nFixed; } else { dynWith = 0; } // Get the cross size if( bVertical ) fullCross = Element->CachedW - Element->PaddingL - Element->PaddingR; else fullCross = Element->CachedH - Element->PaddingT - Element->PaddingB; //_SysDebug("%i (p=%i) - WxH=%ix%i", // Element->ID, (Element->Parent ? Element->Parent->ID : -1), // Element->CachedW, Element->CachedH // ); //_SysDebug(" %s dynWith = %i, fullCross = %i", // (Element->Flags & ELEFLAG_VERTICAL ? "Vert" : "Horiz"), // dynWith, fullCross // ); // Pass 2 - Set sizes and recurse for( child = Element->FirstChild; child; child = child->NextSibling ) { int w, h; // Ignore elements that will not be rendered if( child->Flags & ELEFLAG_NORENDER ) continue ; // Don't resize floating elements if( child->Flags & ELEFLAG_ABSOLUTEPOS ) continue ; // --- Width --- if( child->Flags & (bVertical ? ELEFLAG_NOEXPAND : ELEFLAG_NOSTRETCH) ) w = child->MinW; else if( bVertical ) w = child->FixedCross ? child->FixedCross : fullCross; else w = child->FixedWith ? child->FixedWith : dynWith; // --- Height --- if( child->Flags & (bVertical ? ELEFLAG_NOSTRETCH : ELEFLAG_NOEXPAND) ) h = child->MinH; else if( bVertical ) h = child->FixedWith ? child->FixedWith : dynWith; else h = child->FixedCross ? child->FixedCross : fullCross; if(w < child->MinW) w = child->MinW; if(h < child->MinH) h = child->MinH; // _SysDebug("Child %ix%i (min %ix%i)", w, h, child->MinW, child->MinH); // Update the dimensions if they have changed if( child->CachedW == w && child->CachedH == h ) continue ; child->CachedW = w; child->CachedH = h; // Force the positions of child elements to be recalculated child->CachedX = -1; // Recurse down so the child elements can be updated Widget_UpdateDimensions(child); } } /** * \brief Update the position of child elements */ void Widget_UpdatePosition(tElement *Element) { int x, y; if( Element->Flags & ELEFLAG_NORENDER ) return ; // Check if this element can have children if( (gaWM_WidgetTypes[Element->Type]->Flags & WIDGETTYPE_FLAG_NOCHILDREN) ) return ; // _SysDebug("Widget_UpdatePosition: (Element=%p(%i Type=%i Flags=0x%x))", // Element, Element->ID, Element->Type, Element->Flags); // Initialise x = Element->CachedX + Element->PaddingL; y = Element->CachedY + Element->PaddingT; // Update each child for(tElement *child = Element->FirstChild; child; child = child->NextSibling) { int newX, newY; // Ignore elements that will not be rendered if( child->Flags & ELEFLAG_NORENDER ) continue ; newX = x; newY = y; // Handle alignment (across parent) if( Element->Flags & ELEFLAG_ALIGN_CENTER ) { if(Element->Flags & ELEFLAG_VERTICAL) newX += Element->CachedW/2 - child->CachedW/2; else newY += Element->CachedH/2 - child->CachedH/2; } else if( Element->Flags & ELEFLAG_ALIGN_END ) { if(Element->Flags & ELEFLAG_VERTICAL ) newX += Element->CachedW - child->CachedW - Element->PaddingL - Element->PaddingR; else newY += Element->CachedH - child->CachedH - Element->PaddingT - Element->PaddingB; } // _SysDebug(" Widget_UpdatePosition[%i]: newX = %i, newY = %i", Element->ID, newX, newY); // Check for changes, and don't update if there was no change if( newX != child->CachedX || newY != child->CachedY ) { child->CachedX = newX; child->CachedY = newY; // Update child's children positions Widget_UpdatePosition(child); } // Increment if(Element->Flags & ELEFLAG_VERTICAL ) { y += child->CachedH + Element->GapSize; } else { x += child->CachedW + Element->GapSize; } } } /** * \brief Update the minimum dimensions of the element * \note Called after a child's minimum dimensions have changed */ void Widget_UpdateMinDims(tElement *Element) { int minW, minH; int nChildren; if(!Element) return; minW = 0; minH = 0; nChildren = 0; for( tElement *child = Element->FirstChild; child; child = child->NextSibling ) { int cross; if(Element->Flags & ELEFLAG_NORENDER) continue ; if( (Element->Flags & ELEFLAG_VERTICAL) ) { cross = child->FixedCross ? child->FixedCross : child->MinW; if(minW < cross) minW = cross; minH += child->FixedWith ? child->FixedWith : child->MinH; } else { cross = child->FixedCross ? child->FixedCross : child->MinH; minW += child->FixedWith ? child->FixedWith : child->MinW; if(minH < cross) minH = cross; } // _SysDebug("%i/%i cross = %i", Element->ID, child->ID, cross); nChildren ++; } if( Element->Flags & ELEFLAG_VERTICAL ) minH += (nChildren - 1) * Element->GapSize; else minW += (nChildren - 1) * Element->GapSize; Element->MinW = Element->PaddingL + minW + Element->PaddingR; Element->MinH = Element->PaddingT + minH + Element->PaddingB; // Recurse upwards Widget_UpdateMinDims(Element->Parent); } tElement *Widget_GetElementByPos(tWidgetWin *Info, int X, int Y) { tElement *ret; tElement *next = &Info->RootElement; // Scan down tree do { ret = next; next = NULL; for(tElement *ele = ret->FirstChild; ele; ele = ele->NextSibling) { if(ele->Flags & ELEFLAG_NORENDER) continue; if(X < ele->CachedX) continue; if(Y < ele->CachedY) continue; if(X >= ele->CachedX + ele->CachedW) continue; if(Y >= ele->CachedY + ele->CachedH) continue; next = ele; } } while(next); return ret; } // --- Helpers --- tElement *Widget_GetElementById(tWidgetWin *Info, uint32_t ID) { tElement *ele; if( ID == -1 ) return &Info->RootElement; if( ID < Info->TableSize ) return Info->ElementTable[ID]; ele = Info->ElementTable[ID % Info->TableSize]; while(ele && ele->ID != ID) ele = ele->ListNext; return ele; } tElement *Widget_int_Create(tWidgetWin *Info, tElement *Parent, int ID, int Type, int Flags) { if( Widget_GetElementById(Info, ID) ) return NULL; if( Type >= NUM_ELETYPES ) { return NULL; } _SysDebug("Widget Create #%i '%s' 0x%x", ID, gaWM_WidgetTypes[Type]->Name, Flags); // Create new element tElement *new = calloc(sizeof(tElement), 1); new->Window = Parent->Window; new->ID = ID; new->Type = Type; new->Parent = Parent; new->Flags = Flags; new->PaddingT = 2; new->PaddingB = 2; new->PaddingL = 2; new->PaddingR = 2; new->CachedX = -1; if( gaWM_WidgetTypes[Type]->Init ) gaWM_WidgetTypes[Type]->Init(new); // Add to parent's list if(Parent->LastChild) Parent->LastChild->NextSibling = new; else Parent->FirstChild = new; Parent->LastChild = new; // Add to info { tElement *ele, *prev = NULL; for(ele = Info->ElementTable[new->ID % Info->TableSize]; ele; prev = ele, ele = ele->ListNext); if(prev) prev->ListNext = new; else Info->ElementTable[new->ID % Info->TableSize] = new; } return new; } void Widget_SetFocus(tWidgetWin *Info, tElement *Ele) { // TODO: Callbacks Info->FocusedElement = Ele; } // --- Message Handlers --- int Widget_IPC_Create(tWindow *Win, size_t Len, const void *Data) { tWidgetWin *Info = Win->RendererInfo; const tWidgetIPC_Create *Msg = Data; const int max_debugname_len = Len - sizeof(*Msg); tElement *parent; // Sanity check if( Len < sizeof(*Msg) ) return -1; if( strnlen(Msg->DebugName, max_debugname_len) == max_debugname_len ) return -1; _SysDebug("Widget_NewWidget (%i %i Type %i Flags 0x%x)", Msg->Parent, Msg->NewID, Msg->Type, Msg->Flags); if(Msg->Type >= ciWM_NumWidgetTypes) { _SysDebug("Widget_NewWidget - Bad widget type %i", Msg->Type); return 1; } // Create parent = Widget_GetElementById(Info, Msg->Parent); if(!parent) { _SysDebug("Widget_NewWidget - Bad parent ID %i", Msg->Parent); return 1; } Widget_int_Create(Info, parent, Msg->NewID, Msg->Type, Msg->Flags); Widget_UpdateMinDims(parent); return 0; } int Widget_IPC_NewWidgetSubwin(tWindow *Win, size_t Len, const void *Data) { tWidgetWin *Info = Win->RendererInfo; const tWidgetIPC_CreateSubWin *Msg = Data; const int max_debugname_len = Len - sizeof(*Msg); tElement *parent, *new; // Sanity check if( Len < sizeof(*Msg) ) return -1; if( strnlen(Msg->DebugName, max_debugname_len) == max_debugname_len ) return -1; _SysDebug("Widget_NewWidgetSubwin(%i %i Type %i Flags 0x%x Subwin %i)", Msg->Parent, Msg->NewID, Msg->Type, Msg->Flags, Msg->WindowHandle); parent = Widget_GetElementById(Info, Msg->Parent); if(!parent) return 1; if( Widget_GetElementById(Info, Msg->NewID) ) return 1; new = Widget_int_Create(Info, parent, Msg->NewID, Msg->Type, Msg->Flags); new->Data = WM_GetWindowByID(parent->Window, Msg->WindowHandle); Widget_UpdateMinDims(parent); return 0; } // TODO: Widget_IPC_Delete int Widget_IPC_SetFocus(tWindow *Win, size_t Len, const void *Data) { tWidgetWin *info = Win->RendererInfo; tElement *ele; const tWidgetIPC_SetFocus *msg = Data; if(Len < sizeof(*msg)) return -1; _SysDebug("Widget_SetFocus(%i)", msg->WidgetID); ele = Widget_GetElementById(info, msg->WidgetID); Widget_SetFocus(info, ele); return 0; } int Widget_IPC_SetFlags(tWindow *Win, size_t Len, const void *Data) { tWidgetWin *Info = Win->RendererInfo; const tWidgetIPC_SetFlags *Msg = Data; tElement *ele; if( Len < sizeof(*Msg) ) return -1; _SysDebug("Widget_SetFlags: (%i 0x%x 0x%x)", Msg->WidgetID, Msg->Value, Msg->Mask); ele = Widget_GetElementById(Info, Msg->WidgetID); if(!ele) return 1; ele->Flags &= ~Msg->Mask; ele->Flags |= Msg->Value & Msg->Mask; return 0; } int Widget_IPC_SetSize(tWindow *Win, size_t Len, const void *Data) { tWidgetWin *Info = Win->RendererInfo; const tWidgetIPC_SetSize *Msg = Data; tElement *ele; if( Len < sizeof(*Msg) ) return -1; _SysDebug("Widget_SetSize(%i, %i)", Msg->WidgetID, Msg->Value); ele = Widget_GetElementById(Info, Msg->WidgetID); if(!ele) return 1; ele->FixedWith = Msg->Value; return 0; } int Widget_IPC_SetText(tWindow *Win, size_t Len, const void *Data) { tWidgetWin *Info = Win->RendererInfo; const tWidgetIPC_SetText *Msg = Data; tElement *ele; if( Len < sizeof(*Msg) + 1 ) return -1; if( Msg->Text[Len - sizeof(*Msg) - 1] != '\0' ) return -1; _SysDebug("Widget_SetText(%i, '%.30s')", Msg->WidgetID, Msg->Text); ele = Widget_GetElementById(Info, Msg->WidgetID); if(!ele) return 1; if( gaWM_WidgetTypes[ele->Type]->UpdateText ) { _SysDebug(" - calling handler"); gaWM_WidgetTypes[ele->Type]->UpdateText( ele, Msg->Text ); } // else // { // if(ele->Text) free(ele->Text); // ele->Text = strdup(Msg->Text); // } return 0; } int Widget_IPC_GetText(tWindow *Win, size_t Len, const void *Data) { tWidgetWin *Info = Win->RendererInfo; const tWidgetIPC_SetText *Msg = Data; if( Len < sizeof(*Msg) ) return -1; const char *text = NULL; tElement *ele = Widget_GetElementById(Info, Msg->WidgetID); if(ele) text = ele->Text; char buf[sizeof(tWidgetIPC_SetText) + strlen(text?text:"") + 1]; tWidgetIPC_SetText *omsg = (void*)buf; if( text ) { omsg->WidgetID = Msg->WidgetID; strcpy(omsg->Text, text); } else { omsg->WidgetID = -1; omsg->Text[0] = 0; } WM_SendIPCReply(Win, IPC_WIDGET_GETTEXT, sizeof(buf), buf); return 0; } int Renderer_Widget_HandleMessage(tWindow *Target, int Msg, int Len, const void *Data) { tWidgetWin *info = Target->RendererInfo; tElement *ele; switch(Msg) { case WNDMSG_RESIZE: { const struct sWndMsg_Resize *msg = Data; if(Len < sizeof(*msg)) return -1; info->RootElement.CachedW = msg->W; info->RootElement.CachedH = msg->H; // TODO: Update dimensions of all child elements? return 0; } case WNDMSG_MOUSEMOVE: { // _SysDebug("TODO: Support widget mouse move events"); return 0; } case WNDMSG_MOUSEBTN: { const struct sWndMsg_MouseButton *msg = Data; tWidgetMsg_MouseBtn client_msg; int x, y; int rv; if(Len < sizeof(*msg)) return -1; x = msg->X; y = msg->Y; client_msg.Button = msg->Button; client_msg.bPressed = msg->bPressed; ele = Widget_GetElementByPos(info, x, y); Widget_SetFocus(info, ele); // Send event to all elements from `ele` upwards for( ; ele; ele = ele->Parent ) { if(gaWM_WidgetTypes[ele->Type]->MouseButton) { rv = gaWM_WidgetTypes[ele->Type]->MouseButton( ele, x - ele->CachedX, y - ele->CachedY, msg->Button, msg->bPressed ); // Allow a type to trap the input from going any higher if(rv == 0) break; } else { // Pass to user client_msg.X = x - ele->CachedX; client_msg.Y = y - ele->CachedY; client_msg.WidgetID = ele->ID; WM_SendMessage(Target, Target, MSG_WIDGET_MOUSEBTN, sizeof(client_msg), &client_msg); } } return 0; } case WNDMSG_KEYDOWN: { const struct sWndMsg_KeyAction *msg = Data; if(Len < sizeof(*msg)) return -1; if(!info->FocusedElement) return 0; ele = info->FocusedElement; if(gaWM_WidgetTypes[ele->Type]->KeyDown) gaWM_WidgetTypes[ele->Type]->KeyDown(ele, msg->KeySym, msg->UCS32); else { // TODO: Pass to user } return 0; } case WNDMSG_KEYFIRE: { const struct sWndMsg_KeyAction *msg = Data; if(Len < sizeof(*msg)) return -1; if(!info->FocusedElement) return 0; ele = info->FocusedElement; if(gaWM_WidgetTypes[ele->Type]->KeyFire) gaWM_WidgetTypes[ele->Type]->KeyFire(ele, msg->KeySym, msg->UCS32); else { // TODO: Pass the buck } return 0; } case WNDMSG_KEYUP: { const struct sWndMsg_KeyAction *msg = Data; if(Len < sizeof(*msg)) return -1; if(!info->FocusedElement) return 0; ele = info->FocusedElement; if(gaWM_WidgetTypes[ele->Type]->KeyUp) gaWM_WidgetTypes[ele->Type]->KeyUp(ele, msg->KeySym); else { // TODO: Pass the buck } return 0; } // default: return 1; // Unhandled, pass to user } } void Widget_Fire(tElement *Element) { tWidgetMsg_Fire msg; msg.WidgetID = Element->ID; _SysDebug("Widget_Fire: Fire on %p %i", Element->Window, Element->ID); WM_SendMessage(Element->Window, Element->Window, MSG_WIDGET_FIRE, sizeof(msg), &msg); }
26.165
97
0.686556
[ "render" ]
fd7c6a030bc3522f97a208a12b13269fbec1cc0c
203,487
c
C
cflow/findoutx.c
mbheinen/bpa-ipf-tsp
bf07dd456bb7d40046c37f06bcd36b7207fa6d90
[ "MIT" ]
14
2020-04-02T15:34:42.000Z
2022-03-24T08:57:45.000Z
cflow/findoutx.c
cuihantao/bpa-ipf-tsp
cb2d0917ae42eff571017e9162f550f87900b83f
[ "MIT" ]
11
2020-02-08T14:21:23.000Z
2021-08-13T01:27:56.000Z
cflow/findoutx.c
mbheinen/bpa-ipf-tsp
bf07dd456bb7d40046c37f06bcd36b7207fa6d90
[ "MIT" ]
14
2020-02-03T04:26:58.000Z
2022-03-20T15:04:31.000Z
/******************************************************************************\ UTILITY: FINDOUT STRUCTURE: common CFLOW architecture. TYPE: Powerflow (BPF) output report post-processor. SUMMARY: Generates a table of outages and corresponding branch overloads or bus voltage violations from multiple pfo files. Sorts and screens. RELATED: LINEFLOW, MIMIC, CFUSE SEE ALSO: TO_DECWRITE.HELP, VMS_TO_PC_TO_EXCEL.HELP UPDATED: April 2, 1997 LANGUAGE: Standard C. CFLOW Library. cf_util.h DEVELOPER: William D. Rogers, BPA, TOP, 230-3806, wdrogers@bpa.gov REQUESTER: IPF User Group (L. Stadler, P. Larguier, K. Kohne) USERS: Kyle Kohne, Larry Stadler, Dorothy Betzing, Kendall Rydell IPF: version 317 or above recommended; also works with PTI PURPOSE: Works with the .pfo output files of /OUTAGE_SIMULATION runs as a post-processor to screen and sort the results and present them in tabular form. Tables of 'Outages and Overloads' or 'Outages and Bus Violations' can be produced. Entries in these tables can be screened according to Zone, Owner, Base kV, Loading and Bus Voltage. Tables can be sorted by Zone, Owner, Base kV, or alphabetically. The idea is to allow the user to automate the creation of a report detailing the results of outages--saving time and reducing errors from the current method of doing so which generally includes cut and paste operation with an editor. Data fields in the output report table are character delimited to ease importing to MS Excel or DECwrite. \******************************************************************************/ /******************************* #include *************************************/ #include <ctype.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include "cflowlib.h" /***************************** end #include ***********************************/ /******************************************************************************\ cf_util.h library Developed by William D. Rogers for use with Bonneville Power Administration's CFLOW library and Interactive Powerflow (IPF) program. Naming conventions: (suggested, note case) Cf_macro, Cf_macroName cf_function, cf_functionName CF_CONSTANT, CF_CONSTANTNAME CF_globalVariable cf_Structure, Structure Cx_, CX, cx,... legacy functions to be retired Library organization: (suggested) #include #define macros #define constants typedef struct global variables function prototypes functions \******************************************************************************/ #define Cf_min(A, B) ((A) < (B) ? (A) : (B)) #define Cf_max(A, B) ((A) > (B) ? (A) : (B)) #define Cf_ratio(N, D) ((D) > 0 ? (N) / (D) : 0) #define Cf_imod(N, D) (int) (fmod((double) N, (double) D)) #define CF_STRSIZE 133 #define CF_INPFOSIZE 135 /* for reading Fortran-generated *.PFO files */ #define CF_INBUFSIZE 250 #define CF_OUTBUFSIZE 250 #define CF_RECSIZE 300 /* maximum length of input or solution record */ #define CF_IPCSIZE 8192 /* CFLOW_IPC_BUS_SIZE */ #define CF_COMMENT '.' #define CF_TRUNCATE "\n\\" #define CF_DATATYPES ".DAT,.TRC,.LIS,.XYC" #define CF_TOKSEP ", \t" #define CF_HISSPEC "CFPROGS:CFLOW.LOG" /* CFLOW usage history log */ #define CF_TIMESTAMP "%d-%b-%Y %H:%M:%S" #define CF_PAGE_FOOTER "\n%-122.122s PAGE %4d\n" #define CF_KIND_LINK 1 /* Link */ #define CF_KIND_STR 2 /* string */ #define CF_KIND_REC 3 /* pf_rec structure */ #define CF_KIND_BUS 4 /* cf_Bus structure */ #define CF_KIND_BRN 5 /* cf_Branch structure */ #define CF_KIND_CHAR 6 /* single character */ #define CF_KIND_INT 7 /* integer */ #define CF_KIND_FLT 8 /* floating point number */ #define CF_KIND_TAG 9 /* tag string for list */ #define CF_KIND_NAME 10 /* cf_Name structure */ #define CF_KIND_GEN 11 /* ff_Gen structure */ #define CF_KIND_SF2 12 /* cf_StrFlt2 (file[80], float, float) structure */ #define CF_KIND_STRSTR 13 /* cf_StrStr (str1[80], str2[80]) structure */ #define CF_TAG_W_LIST 0 /* print tag only if there is a list */ #define CF_TAG_ALWAYS 1 /* always print tag, even with List==NULL */ #define CF_INS_FREE 1 /* discard new links if same as existing links */ #define CF_INS_SKIP 2 /* don't insert new links but keep them */ #define CF_INS_AFTER 3 /* insert new links after current link */ #define CF_INS_BEFORE 4 /* insert new links berfore current link */ typedef struct LinkRecord { struct LinkRecord *prev; /* previous Cell record */ size_t size; /* amount of memory allocated for data */ int kind; /* type of data structure pointed to by *data */ int view; /* code for how to print out data */ void *data; /* pointer to allocated memory */ struct LinkRecord *next; /* next Cell record */ } Link; /* cf_Link */ typedef struct ListStyleRecord { char indent[10]; /* leading characters on each data line */ int mode; /* 0 - always print tag, 1 - print only if links present */ int limit; /* number of links to print per line */ } cf_Style; typedef struct NameIdRecord { char type[3]; char name[39]; } cf_Name; typedef struct BranchIdRecord { char type[3]; char owner[4]; char bus1_name[9]; float bus1_kv; int meter; char bus2_name[9]; float bus2_kv; char ckt_id; int section; float rating; char code; float nominal; float thermal; float emergency; float bottleneck; char date_in[4]; char bus1_zone[3]; char bus2_zone[3]; } cf_Branch; /* modified form of pf_branch */ typedef struct BusIdRecord { char type[3]; char owner[4]; char name[9]; float kv; char zone[3]; } cf_Bus; /* short form of pf_AC_bus and pf_DC_bus */ typedef struct OutputReportRecord { FILE *file; int line; int page; char *time; char spec[FILENAME_MAX]; int type; int form; int wide; int diff; } cf_Out; typedef struct GeneratorLimitsRecord { float set; /* current set value (MW) */ float start; /* fixed starting value (MW) */ float stop; /* fixed stopping value (MW) */ float step; /* fixed step size (MW) */ } cf_Gen; typedef struct StringFloat2 { char file[80]; /* 80 character string (developed for filename) */ float flt1; /* floating point number */ float flt2; /* floating point number */ } cf_StrFlt2; typedef struct StringString { char str1[80]; /* 80 character string (developed for filename) */ char str2[80]; /* 80 character string */ } cf_StrStr; FILE *CF_logFile = NULL; FILE *CF_hisFile = NULL; /* CFLOW usage history file */ char CF_logSpec[FILENAME_MAX] = ""; /****************** add stuff for query and BAD (aka ZAP) logs *******************/ FILE *CF_logQFile = NULL; char CF_logQSpec[FILENAME_MAX] = ""; FILE *CF_logZFile = NULL; char CF_logZSpec[FILENAME_MAX] = ""; /****************** add stuff for query and BAD logs *******************/ char CF_inbuf[CF_INBUFSIZE]; long CF_memCurAlloc = 0; /* current bytes allocated at present time */ long CF_memMaxAlloc = 0; /* maximum bytes allocated at any one time */ long CF_memTotAlloc = 0; /* total bytes allocated so far */ long CF_memTotFreed = 0; /* total bytes de-allocated (freed) so far */ time_t CF_time0 = 0; time_t CF_time1 = 0; cf_Style CF_oneStyl = { " ", CF_TAG_ALWAYS, 1 }; /* filenames, trace data */ cf_Style CF_sixStyl = { " ", CF_TAG_ALWAYS, 6 }; /* base kv */ cf_Style CF_dznStyl = { " ", CF_TAG_ALWAYS, 12 }; /* zones, owners */ cf_Style CF_dotStyl = { ". ", CF_TAG_ALWAYS, 1 }; /* comments, trace data */ cf_Style CF_recStyl = { "", CF_TAG_ALWAYS, 1 }; /* branches, buses, names */ cf_Style CF_lisStyl = { "", CF_TAG_W_LIST, 1 }; /* branches, buses, masks */ void cf_cprompt(char *prompt, char dflt, char *reply); void cf_sprompt(char *prompt, char *dflt, char *reply); void cf_mprompt(char *prompt, char *dflt, char *mask, char *reply); void cf_nprompt(char *prompt, char *dflt, int n, char *reply); void cf_kprompt(char *prompt, char dflt, char *reply); void cf_fprompt(char *prompt, float dflt, float *reply); void cf_dprompt(char *prompt, double dflt, double *reply); void cf_iprompt(char *prompt, int dflt, int *reply); int cf_yprompt(char *prompt, int dflt); void cf_eprint(FILE *fp, char *fmt, ...); void cf_aprint(char *target, char *fmt, ...); void cf_exit(int error, char *fmt, ...); void cf_pfexit(int error, char *fmt, ...); void cf_stoupper(char *str); int cf_str2list(char *list, int group, char delim); char *cf_strsuf(char *dest, char *source, char term, char *suffix); int cf_strcon(char *s1, char *s2); char *cf_parse(char *spec, char *part, int code); int cf_query2spec(char *spec, char *query, char *type); FILE *cf_openFile(char *spec, char *mode); /****************** add stuff here ***************************/ void cf_logErr(char *fmt, ...); void *cf_calloc(size_t nobj, size_t size); void cf_free(void *obj, size_t size); size_t cf_time(char *s, size_t smax, char *format); char *cf_str2upper(char *str); char *cf_str2lower(char *str); int cf_isblank(char *cp); int cf_iscomment(char *str); int cf_isDataFile(char *filename); Link *cf_newLink(size_t size); int cf_cntLink(Link *cur); Link *cf_addLink(Link *tar, size_t size); Link *cf_delLink(Link **top, Link *del); Link *cf_appList(Link **top, Link *src); Link *cf_dupList(Link *src); void cf_freeList(Link *cur); Link *cf_link2row(Link *dat); void cf_freeRow(Link *row); Link *cf_delRow(Link **rowList, Link *curRow); int cf_rec_l2h(pf_branch *r); int cf_rec_h2l(pf_branch *r); int cf_cmpBus(pf_AC_bus *b1, pf_AC_bus *b2); int cf_cmpBranch(pf_branch *b1, pf_branch *b2); Link *cf_text2Link(char *s); Link *cf_text2List(char *s); int cf_validOwner(Link *ownrList, char *owner); int cf_validBasekv(Link *bskvList, float bus1_kv, float bus2_kv); int cf_validZone(Link *zoneList, char *z1, char *z2); void *cf_malloc(size_t size); void cf_logUse(char *prog, char *vers, char *user); char *cf_strsub(char *str, char *sub, char fill); void cf_freeRowList(Link **rowList); void cf_bus2rec(cf_Bus *bus, pf_rec *rec); void cf_rec2bus(pf_rec *rec, cf_Bus *bus); void cf_branch2rec(cf_Branch *branch, pf_rec *rec); void cf_rec2branch(pf_rec *rec, cf_Branch *branch); Link *cf_id2Link(char *s, char order); int cf_cntchr(char *str, char chr); char *cf_strdup(char *str); int cf_branch_l2h(cf_Branch *b); Link *cf_rec2Link(char *s); cf_Out *cf_initOut(char *fs, char *ts, int ty, int fm); float cf_getRating(pf_rec *n, int tx, char *code); float cf_getLoad(pf_rec *n); int cf_printGroup(FILE *fp, Link *list, cf_Style style, char *tag); int cf_printList(FILE *fp, Link *list, cf_Style style, char *tag); int cf_printLink(FILE *fp, Link *link); int cf_printTag(FILE *fp, Link *list, cf_Style style, char *tag); char *cf_link2tagName(Link *tagLink, char *tagName); Link *cf_tag2link(char *tag); void cf_fillGroup(char *mstrSpec, Link **grpList, char *key); void cf_insLink(Link **top, Link **cur, Link *new, long sort, int mode, int (*cmp)(Link *, Link *, int)); void cf_insBefore(Link **cur, Link **new, Link **top); void cf_insAfter(Link **cur, Link **new); int cx_printList(FILE *fp, Link *list, char *tag, char *indent, char type, char *fmt, int n); int cx_printRowList(FILE *fp, Link *list, char *list_tag, char *row_tag, char type, char *fmt, int n); /******************************* #define **************************************/ #define FF_IPF_VERSION 320 /* GPF.EXE_V320 or above recommended */ #define FF_PAGE_LENGTH 61 #define DOT_LINE "..................................................." #define FF_WILD '?' #define LOG_SPEC "findout.log" #define OUT_NAME "findout" #define DFLT_CASE_PER_PAGE 2 #define DFLT_MIN_LOAD_PCT 80.00 #define DFLT_MAX_DELTA_PCT 0.0 #define DFLT_MAX_500_PU 1.100 #define DFLT_MIN_500_PU 1.000 #define DFLT_MAX_BUS_PU 1.052 #define DFLT_MIN_BUS_PU 0.950 #define QUERY_PFO (int) (1<< 0) /* prompt for *.pfo files */ #define QUERY_DATA (int) (1<< 1) /* prompt for data file listing branch/bus*/ #define QUERY_SOLN (int) (1<< 2) /* prompt for including sol'n problem data*/ #define QUERY_OWNR (int) (1<< 3) /* prompt for owners of interest */ #define QUERY_ZONE (int) (1<< 4) /* prompt for zones of interest */ #define QUERY_BSKV (int) (1<< 5) /* prompt for base kV of interest */ #define QUERY_LOAD (int) (1<< 6) /* prompt for MAX PCT LOADING */ #define QUERY_SORT (int) (1<< 7) /* prompt for sort order */ #define QUERY_FORM (int) (1<< 8) /* prompt for report format */ #define QUERY_NAME (int) (1<< 9) /* prompt for report name */ #define QUERY_WDTH (int) (1<<10) /* prompt for report width in cases/table */ #define QUERY__TRC (int) (1<<11) /* prompt for whether or not to make .TRC */ #define QUERY_CONT (int) (1<<12) /* prompt for continuation of run */ #define QUERY_TYPE (int) (1<<13) /* prompt for continuation of run */ #define QUERY_VOLT (int) (1<<14) /* prompt for continuation of run */ #define QUERY_OUTG (int) (1<<15) /* prompt for list of branches/busses */ #define QUERY_COMO (int) (1<<16) /* prompt for list of branches/busses */ #define QUERY_OVLD (int) (1<<17) /* prompt for list of branches/busses */ #define QUERY_BUSV (int) (1<<18) /* prompt for list of branches/busses */ #define QUERY_OW_P (int) (1<<19) /* prompt for owners of interest */ #define QUERY_ZN_P (int) (1<<20) /* prompt for zones of interest */ #define QUERY_KV_P (int) (1<<21) /* prompt for base kV of interest */ #define QUERY_DLTA (int) (1<<22) /* prompt for max change in load or volt */ #define QUERY_DIFF (int) (1<<23) /* prompt for whether to do difference rpt */ #define QUERY_REDU (int) (1<<24) /* prompt for removal of redundant outages */ #define QUERY_VARI (int) (1<<25) /* prompt for whether to do variance rpt */ #define QUERY_SPAN (int) (1<<26) /* prompt for variance span */ #define READ_INC (int) 1 /* found /INCLUDE card in CFLOW data file */ #define READ_PFO (int) 2 /* found /PFO card in CFLOW data file */ #define READ_OUT (int) 3 /* found /OUTAGE card in CFLOW data file */ #define READ_COM (int) 4 /* found /COMMON_MODE in CFLOW data file */ #define READ_OVR (int) 5 /* found /OVERLOAD in CFLOW data file */ #define READ_BUS (int) 6 /* found /BUS card in CFLOW data file */ #define READ_OWN (int) 8 /* found /OUTG_OWNER in CFLOW data file */ #define READ_ZON (int) 9 /* found /OUTG_ZONE in CFLOW data file */ #define READ_BKV (int) 10 /* found /OUTG_BASE_KV in CFLOW data file */ #define READ_LIM (int) 11 /* found /LIMITS card in CFLOW data file */ #define READ_REP (int) 12 /* found /REPORT card in CFLOW data file */ #define READ_OWP (int) 13 /* found /PROB_OWNER in CFLOW data file */ #define READ_ZNP (int) 14 /* found /PROB_ZONE in CFLOW data file */ #define READ_KVP (int) 15 /* found /PROB_BASE_KV in CFLOW data file */ #define SORT_BY_ALPHA (int) 1 #define SORT_BY_BASEKV (int) 2 #define SORT_BY_OWNER (int) 3 #define SORT_BY_ZONE (int) 4 #define SORT_BY_INPUT (int) 5 #define SORT_BY_SOLN (int) 6 #define SORT_BY_DIFF (int) 7 #define VARI_NO (int) 0 #define VARI_YES (int) 1 #define TRACE_NO (int) 0 #define TRACE_YES (int) 1 #define TYPE_NONE (int) 0 #define TYPE_TRACE (int) 1 #define TYPE_OUTG_OVLD (int) 1 #define TYPE_OUTG_BUSV (int) 2 #define TYPE_OVLD_OUTG (int) 3 #define TYPE_BUSV_OUTG (int) 4 #define TYPE_OVLD_BOTH (int) 5 #define TYPE_BUSV_BOTH (int) 6 #define REDUN_KEEP (int) 0 #define REDUN_REMOVE (int) 1 #define SKP_SOLN_PROB (int) 0 /* skip reporting of solution problems */ #define INC_SOLN_PROB (int) 1 /* include report of solution problems */ #define FORM_DATA_FULL (int) 1 #define FORM_DATA_BREF (int) 2 /* BRIEF DATA FORMAT */ #define FORM_PAGE_WIDE (int) 3 #define FORM_PAGE_COMP (int) 4 /* COMPACT PAGE FORMAT */ #define HEADER_BREAK_PTI "................................................................................" #define HEADER_COMME_PTI ". " #define DIS_FAC_FILE_PTI "DISTRIBUTION FACTOR FILE:" #define SUB_DES_FILE_PTI "SUBSYSTEM DESCRIPTION FILE:" #define MON_ELE_FILE_PTI "MONITORED ELEMENT FILE:" #define CON_DES_FILE_PTI "CONTINGENCY DESCRIPTION FILE:" #define CONTIN_EVENT_PTI "--- C O N T I N G E N C Y E V E N T S ---" #define OPEN_LINE_FR_PTI "OPEN LINE FROM BUS" #define BPA_PF_PROG_VERS "BPA POWER FLOW PROGRAM VERSION:IPF" #define PTI_INTERAC_PSSE "PTI INTERACTIVE POWER SYSTEM SIMULATOR--PSS/E" #define SUM_PROBS_4E_OUT "Summary of bus and line problems for each outage" #define SUM_SYST_SEP_DIV "Summary of System Separations and Divergences" #define SUM_COM_MODE_OUT "Summary of Common Mode Outages" #define OUTG_SIMUL_INPUT "Outage Simulation Input" #define BUS_BUS_VPU_PTI "X------ BUS -----X V(PU)" #define BUS_VV_A_PU_316 "Bus voltage violation Actual Per unit Actual / change /( limits )" #define BUS_VV_A_PU_312 "Bus voltage violation actual per unit actual/( limits )" #define CONTINGENCY_ANAL " C O N T I N G E N C Y A N A L Y S I S " #define __O_U_T_A_G_E__ "* * O U T A G E * *" #define OVLD_FRO_TO_PTI "FROM NAME TO NAME CKT PRE-CNT POST-CNT RATING PERCENT" #define OVLD_RAT_TY_316 "Overloads Rating Type per unit / pst-cont pre-cont Date in" #define OVLD_RAT_TY_314 "Overloads Rating Type per unit / actual" #define OVLD_RAT_TY_312 "Overloads Rating Type per unit / actual" #define OUTG_ID_OWN_314 "-------- Outage ------------- ID Owner Zones ------- Problem" #define OUTG_ID_OWN_312 "-------- Outage ------------- ID Owner ------- Problem" /********************* stuff to follow powerflow changes **********************/ /* #define COMO_MOD_NA_312 " %*d%*4c%38[^\n]" */ #define COMO_MOD_NA_312 " %*d%*3c%38[^\n]" /********************* stuff to follow powerflow changes **********************/ #define TY_CH_OWN_Z_315 "Ty Ch Own Zones Bus1 Bus2" #define TY_CH_OWN_B_312 "Ty Ch Own Bus1 Bus2" #define BUSV_FORMAT_PTI "%*60c%8[^\n]%f%*c%f" #define BUSV_FORM_2_PTI "%*60c%*26c%8[^\n]%f%*c%f" #define BUSV_FORM_3_PTI "%*60c%*26c%*26c%8[^\n]%f%*c%f" #define BUSV_FORMAT_316 " %8[^\n]%*c%f%*2c%3[^\n]%*2c%2[^\n]%*24c %f KV %f / %f /( %f, %f)" #define BUSV_FORMAT_312 " %8[^\n]%*c%f%*2c%3[^\n]%*2c%2[^\n]%*21c %f KV %f /( %f, %f)" /* extra %f add for alignment */ #define COMO_FORMAT_314 "%*6c%2[^\n]%*2c%c%*3c%3[^\n]%*2c%2[^\n]%*c%2[^\n]%*2c%*8[^\n]%f %*8[^\n]%f" #define COMO_FORMAT_312 "%*6c%2[^\n]%*2c%c%*3c%3[^\n]%1[^\n]%1[^\n]%*8[^\n]%f %*8[^\n]%f" #define OVLD_FORMAT_PTI "%*61c%8[^\n]%f%*1c%*6c%8[^\n]%f%*1c%c %f %f %f %f" #define OVLD_FORMAT_316 "%*24c %8[^\n]%f %8[^\n]%f%*1c%c%*1c%d%*2c%3[^\n]%*2c%2[^\n]%*c%2[^\n] %f %*3[^\n] %c %f / %f %f %5[^\n]" #define OVLD_FORMAT_314 "%*26c%8[^\n]%f %8[^\n]%f%*2c%c%*2c%d%*2c%3[^\n]%*2c%2[^\n]%*c%2[^\n] %f %*3[^\n] %c %f / %f" #define OVLD_FORMAT_312 "%*26c%8[^\n]%f %8[^\n]%f%*2c%c%*2c%d%*2c%3[^\n]%1[^\n]%1[^\n] %f %*3[^\n] %c %f / %f" #define OUTG_FORMAT_PTI "%*25c[%8[^\n] %f]%*14c[%8[^\n] %f] CKT %c ---%3[^\n]%*2c%2[^\n]%*1c%2[^\n]" #define OUTG_FORMAT_312 " %8[^\n] %f %8[^\n] %f%*2c%c%*2c%3[^\n]%*2c%2[^\n]%*1c%2[^\n]" #define SYST_FORMAT_312 " %8[^\n] %f %8[^\n] %f%*2c%c%*4c%3[^\n]%*2c%2[^\n]%*1c%2[^\n]" #define MSG_CRTCL "\n. CRITCL RATING taken from the first non-zero case.\n" #define MSG_UNITS ". Load in AMPS for lines and MVA for transformers.\n" #define MSG_FLAGS ". F Rating flags indicate type of critical rating.\n" #define MSG_LWRCS ". Lowercase flag indicates rating differs from listed value.\n" #define MSG_SYMBL ". T Thermal, N Nominal, B Bottleneck, E Emergency (Loss of Life)\n" #define MSG_FALRX ". FAILED RX (or RX) - Failed reactive solution; Solved real power only\n" #define MSG_NOSOL ". NO SOLUTION (or FAIL) - Failed solution\n" #define MSG_SEPAR ". SEPARATION (or SEPA) - System Separation\n" #define SRCHN_4_COMO_SUM (int) (1<< 0) /* Summary of common mode outages */ #define SRCHN_4_OUTG_SUM (int) (1<< 1) /* Sum of bus & line probs 4 ea outg */ #define SRCHN_4_FAIL_SUM (int) (1<< 2) /* Sum of system separation & diverg */ #define READING_COMO_SUM (int) (1<< 3) #define READING_OUTG_SUM (int) (1<< 4) #define READING_FAIL_SUM (int) (1<< 5) #define GET_OVLD (int) (1<< 6) #define GET_BUSV (int) (1<< 7) #define GET_OUTG (int) (1<< 8) #define VALID_DATA (int) (1<< 9) #define DATA_PTI (int) (1<<10) #define SRCHING (int) (SRCHN_4_COMO_SUM | SRCHN_4_OUTG_SUM | SRCHN_4_FAIL_SUM) #define READING (int) (READING_COMO_SUM | READING_OUTG_SUM | READING_FAIL_SUM) #define HASHSIZE 30 /***************************** end #define ************************************/ /******************************* typedef **************************************/ typedef struct { float actual; /* post-condition MVA, AMPS, or KV, or absolute (new-ref) */ float ratio; /* PU, per cent, or delta (new-ref/ref) */ float min_ref; /* minimum (low limit), or reference */ float max_new; /* maximum (high limit), or rating, or new */ float pre_con; /* pre-condition MVA, AMPS, or KV */ char code; /* rating code: T, N, E, or B */ char date[6]; /* date in MO/YR format */ } ff_soln; typedef struct traceRecord { Link *pfoList; Link *outgList; Link *comoList; Link *ovldList; Link *busvList; Link *outgMask; Link *comoMask; Link *ovldMask; Link *busvMask; Link *mainTable; Link *rptTable; Link *ownrOutg; Link *zoneOutg; Link *bskvOutg; Link *ownrProb; Link *zoneProb; Link *bskvProb; Link *chkBranchStart; /* Link to branches in No O/L Log */ int query; int sort; /* sort criteria: i.e. (trace *) or trace->sort */ int soln; /* indicates whether or not to report solution problems */ int type; /* output report type of rpt and aux reports */ int redun; int nCases; float minLoadPct; float maxDeltaPct; float varCeiling; float varFloor; float max5; float min5; float maxV; float minV; cf_Out *trc; cf_Out *rpt; cf_Out *aux; char outName[FILENAME_MAX]; char timeStamp[CF_STRSIZE]; char userID[CF_STRSIZE]; char IPFversion[CF_STRSIZE]; /* PRG (program) could be IPF or PTI */ } Trace; struct nlist { /* table entry */ struct nlist *next; /* next entry in chain */ char *name; /* common-mode outage */ int keep; /* 1 = report, 0 = ignore */ }; /******************************* end typedef **********************************/ int count=0; int entry=0; long total_memory_allocated=0, total_requests=0; /* top FINDOUT functions - called by main() **********************************/ void initializeTrace(Trace *trace); void processCommandLine(Trace *trace, int argc, char *argv[]); void instructions(Trace *trace); void promptUser(Trace *trace); void openReport(cf_Out *rpt); void printTrace(Trace *trace); void queryContinue(Trace *trace); void collectData(Trace *trace); void buildReport(Trace *trace, cf_Out *rpt); void printReport(Trace *trace, cf_Out *rpt); void swapReport(Trace *trace); void finalRemarks(Trace *trace); /* end FINDOUT functions - called by main() **********************************/ /* top FINDOUT functions - report functions **********************************/ void ff_printBlankLines(cf_Out *rpt, int n); int ff_printPageFooter(cf_Out *rpt, int m); void pageFooter(cf_Out *rpt, Link *nxRow, Link *nxPfo); void tableLegend(cf_Out *rpt); void printHeader(cf_Out *rpt, Link *curPfo); void printID(cf_Out *rpt, Link *curID, int position); void printSoln(cf_Out *rpt, Link *curID, Link *curSoln, int doN); void printOvldHeader(cf_Out *rpt, Link *curPfo); void printOtBrHeader(cf_Out *rpt, Link *curPfo); void printOtBsHeader(cf_Out *rpt, Link *curPfo); void printBusvHeader(cf_Out *rpt, Link *curPfo); void printTableCases(cf_Out *rpt, Link *curPfo, char *l, char *r, char *d); void printTableHeader(cf_Out *rpt, Link *curPfo, char *l, char *r, char *d); void printOutg(FILE *fp, Link *outgLink, int form); void printOvld(FILE *fp, Link *ovldLink, int form); void chkBranch(Trace *trace, Link *curID); /* No O/L Log support */ void chkBranchLog(Trace *trace, Link *curPfo); /* No O/L Log support */ void printBusv(FILE *fp, Link *busvLink, int form); void printLoad(cf_Out *rpt, Link *loadLink, int doN); void printVolt(cf_Out *rpt, Link *voltLink, int doN); void printProb(cf_Out *rpt, Link *probLink, int doN); void printDiff(cf_Out *rpt, Link *solnLink, int doN); /* end FINDOUT functions - report functions **********************************/ /* top FINDOUT functions - support functions *********************************/ int screenProb(Link *problem, Trace trace); int buildMainTable(FILE *pfo_File, Trace *trace); Link *getOutgSet(FILE *pfo_File, int *state, Link *problem, Trace *trace); int getCoMoRslt(char *s, char *format, Trace trace); int getOvldLoad(char *s, char *format, Link *problem); int getBusvVolt(char *s, char *format, Link *problem); Link *getSystProb(char *s, char *format, Link *problem); Link *getBrchOutg(char *s, char *format); Link *getCoMoOutg(char *s); int identifyInput(char *s); void installResult(char *s); int ff_srtByInput(Link *newRow, Link *xstRow, void *sort); int srtByInput(Link *newRow, Link *xstRow, Trace trace); int getIndex(Link *newRow, Link *xstRow, Link *list); int validVariance(Trace trace, Link *solnLink); int validLoad(Trace trace, Link *solnPtr); int validVolt(Trace trace, Link *solnPtr); int validSoln(Link *solnPtr); int validInput(Link *listPtr, cf_Branch *data); void swapRowIdLinks(Link *rowPtr); int validMask(Link *maskList, cf_Name *r); int ff_srtBus(pf_AC_bus *b1, pf_AC_bus *b2, int sort); /* sort bus */ int ff_srtSoln(Link *newSoln, Link *xstSoln, int sort); int ff_cmpType(Link *newId, Link *xstId); int ff_cmpName(cf_Name *b1, cf_Name *b2); int ff_cmpID(Link *newLink, Link *xstLink); int ff_srtID(Link *newLink, Link *xstLink, int sort); int ff_cmpRow(Link *newRow, Link *xstRow, int sort); /* end FINDOUT functions - support functions *********************************/ /* top LINEFLOW, FINDOUT, MIMIC - similar functions ***************************/ void ff_stream2List(FILE *readMe, Trace *trace, Link **expList); void ff_report(char *s, Trace *trace); void ff_limits(char *s, Trace *trace); void ff_expList(Trace *trace, Link *dataList, Link **expList); void ff_appSoln2Row(Link *curRow, Link *solnLink, int nCases); int ff_srtBranch(cf_Branch *b1, cf_Branch *b2, int sort); int ff_wildBranch(pf_branch *b1, pf_branch *b2); /* end LINEFLOW, FINDOUT, MIMIC - similar functions ***************************/ /* top CF_UTIL.H candidate functions ******************************************/ void date(char *date); /* end CF_UTIL.H candidate functions ******************************************/ /* top FINDOUT functions - hash table functions ******************************/ unsigned hash(char *s); struct nlist *install(char *name, int keep); struct nlist *lookup(char *s); /* end FINDOUT functions - hash table functions ******************************/ /******************************** global variable candidates ******************/ static struct nlist *hashtab[HASHSIZE]; /* pointer table or cm outages */ /**************************** end global variable candidates ******************/ cf_Style FF_mskStyl = { "", CF_TAG_W_LIST, 1 }; int main(int argc, char *argv[]) { Trace trace; time(&CF_time0); initializeTrace(&trace); processCommandLine(&trace, argc, argv); instructions(&trace); promptUser(&trace); printTrace(&trace); queryContinue(&trace); collectData(&trace); trace.chkBranchStart = cf_dupList (trace.ovldList); /* Link to No O/L Log */ buildReport(&trace, trace.rpt); printReport(&trace, trace.rpt); swapReport(&trace); printReport(&trace, trace.aux); finalRemarks(&trace); time(&CF_time1); cf_logUse("FindOut", trace.IPFversion, trace.userID); return 0; } void initializeTrace(Trace *trace) { /* special function to do set up/init for FINDOUT */ memset(trace, '\0', sizeof(Trace)); trace->query = ( QUERY_PFO | QUERY_DATA | QUERY_DIFF | QUERY_SOLN | QUERY_TYPE | QUERY_NAME | QUERY_LOAD | QUERY_VOLT | QUERY_SORT | QUERY_OWNR | QUERY_ZONE | QUERY_BSKV | QUERY_OW_P | QUERY_ZN_P | QUERY_KV_P | QUERY_FORM | QUERY_WDTH | QUERY__TRC | QUERY_CONT | QUERY_OUTG | QUERY_COMO | QUERY_OVLD | QUERY_BUSV | QUERY_DLTA | QUERY_REDU | QUERY_VARI | QUERY_SPAN ); trace->varCeiling = 1; trace->varFloor = -1; trace->minLoadPct = DFLT_MIN_LOAD_PCT; trace->maxDeltaPct= DFLT_MAX_DELTA_PCT; trace->max5 = DFLT_MAX_500_PU; trace->min5 = DFLT_MIN_500_PU; trace->maxV = DFLT_MAX_BUS_PU; trace->minV = DFLT_MIN_BUS_PU; trace->sort = SORT_BY_ALPHA; trace->type = TYPE_OUTG_OVLD; trace->redun = REDUN_KEEP; trace->nCases = 0; trace->IPFversion[0] = '\0'; cuserid(trace->userID); cf_time(trace->timeStamp, CF_STRSIZE, CF_TIMESTAMP); strcpy(CF_logSpec, LOG_SPEC); strcpy(trace->outName, OUT_NAME); trace->trc = cf_initOut("", trace->timeStamp, TRACE_YES, FORM_DATA_FULL); trace->rpt = cf_initOut("", trace->timeStamp, TYPE_NONE, FORM_DATA_FULL); trace->aux = cf_initOut("", trace->timeStamp, TYPE_NONE, FORM_DATA_FULL); } void processCommandLine(Trace *trace, int argc, char *argv[]) { Link *list, *topLink; int i; topLink = NULL; if (argc <= 1) return; for (i = argc; --i > 0; cf_appList(&topLink, list)) { list = cf_text2Link(argv[i]); } ff_expList(trace, topLink, &trace->pfoList); return; } void instructions(Trace *trace) { if (trace->query==0) return;/* skip if there is not going to be any queries */ printf("\n Welcome to FINDOUT - updated 01-10-98"); printf("\n"); printf("\n - Defaults in brackets []. Press Ctrl-Y & type STOP to abort."); printf("\n - Use .trc, .dat, or .lis or append / to designate data files."); printf("\n - Powerflow version %d recommended.", FF_IPF_VERSION); printf("\n"); } void promptUser(Trace *trace) { char query[CF_INBUFSIZE]; Link *list; printf("%s", DOT_LINE); if (trace->query & QUERY_PFO) { printf("\n\n/PFO, /TRACE, or /INCLUDE"); cf_nprompt("\n > Enter list of .PFO files (and/or data files): ", "", CF_INBUFSIZE, query); list = cf_text2List(query); ff_expList(trace, list, &trace->pfoList); } if (trace->pfoList==NULL) { printf("\n\n *** Warning ***, No *.PFO files have been specified!"); printf("\n\n/PFO, /TRACE, or /INCLUDE"); cf_nprompt("\n > Enter list of .PFO files (and/or data files): ", "", CF_INBUFSIZE, query); list = cf_text2List(query); ff_expList(trace, list, &trace->pfoList); } cf_exit(trace->pfoList==NULL, "No data or *.PFO files! Quitting!\n"); if (trace->query == QUERY_CONT) trace->query &= ~(QUERY_CONT); if (cf_cntLink(trace->pfoList)==1) { trace->query &= ~(QUERY_WDTH); /* only one *.pfo file present */ } if (trace->query & (QUERY_NAME|QUERY_TYPE|QUERY_SORT|QUERY_FORM|QUERY_WDTH|QUERY_REDU)) { printf("\n\n/REPORT"); } if (trace->query & QUERY_NAME) { cf_sprompt("\n > Enter output files default name, NAME = [%s]: ", trace->outName, trace->outName); printf("\n"); } if (trace->query & QUERY_TYPE) { printf("\n Specify the type of output report (by number)"); printf("\n 1. OUTAGEs causing OVERLOADs 2. OUTAGEs causing BUS Violations"); printf("\n 3. OVERLOADs caused by OUTAGEs 4. BUS Violations caused by OUTAGES"); printf("\n 5. OVERLOADs BOTH WAYS (1 & 3) 6. BUS Violations BOTH WAYS (2 & 4)"); cf_iprompt("\n > Enter report choice, TYPE =[OUTAGE-OVERLOAD]: ", trace->type, &trace->type); printf("\n"); } if (trace->type==1) { trace->rpt->type = TYPE_OUTG_OVLD; trace->aux->type = 0; } if (trace->type==2) { trace->rpt->type = TYPE_OUTG_BUSV; trace->aux->type = 0; } if (trace->type==3) { trace->rpt->type = TYPE_OVLD_OUTG; trace->aux->type = 0; } if (trace->type==4) { trace->rpt->type = TYPE_BUSV_OUTG; trace->aux->type = 0; } if (trace->type==5) { trace->rpt->type = TYPE_OUTG_OVLD; trace->aux->type = TYPE_OVLD_OUTG; } if (trace->type==6) { trace->rpt->type = TYPE_OUTG_BUSV; trace->aux->type = TYPE_BUSV_OUTG; } if (cf_cntLink(trace->pfoList)==1) { /* only one *.pfo file present */ trace->query &= ~(QUERY_VARI); trace->query &= ~(QUERY_SPAN); trace->trc->diff = VARI_NO; } if (trace->query & QUERY_VARI) { trace->trc->diff = cf_yprompt("\n > Do a variance report? VARIANCE = [YES]: ", 'Y'); printf("\n"); } if (trace->trc->diff==VARI_NO) trace->query &= ~(QUERY_SPAN); trace->rpt->diff = trace->trc->diff; trace->aux->diff = trace->trc->diff; if (trace->query & QUERY_REDU) { trace->redun = cf_yprompt("\n > Redundant outages: REMOVE_REDUNDANT = [NO]: ", 'N'); printf("\n"); } if (trace->query & QUERY_SORT) { printf("\n Specify sort priority (by number)"); printf("\n 1. ALPHA-base_kv 3. OWNER-alpha-base_kv 5. INPUT order"); printf("\n 2. BASE_KV-alpha 4. ZONE-alpha-base_kv 6. SOLUTION"); cf_iprompt("\n > Enter sort choice, SORT = [ALPHA]: ", trace->sort, &trace->sort); printf("\n"); } if (trace->sort==SORT_BY_SOLN && trace->trc->diff==VARI_YES) { trace->sort = SORT_BY_DIFF; } if (trace->query & QUERY_FORM) { printf("\n Specify output report format (by number)"); printf("\n 1. DATA-FULL (Excel) 2. DATA-BRIEF (Excel) 3. PAGE-WIDE 4. PAGE-COMPACT"); cf_iprompt("\n > Enter format choice, FORMAT = [DATA-FULL]: ", trace->trc->form, &trace->trc->form); printf("\n"); } trace->rpt->form = trace->trc->form; trace->aux->form = trace->trc->form; if (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OVLD_OUTG) { if (trace->query & QUERY_WDTH) { /* get default width */ if (trace->trc->form==FORM_DATA_BREF) trace->trc->wide = 9; else if (trace->trc->form==FORM_PAGE_COMP) trace->trc->wide = 4; else trace->trc->wide = 2; } } else if (trace->rpt->type==TYPE_OUTG_BUSV || trace->rpt->type==TYPE_BUSV_OUTG) { if (trace->query & QUERY_WDTH) { /* get default width */ if (trace->trc->form==FORM_DATA_BREF) trace->trc->wide = 12; else if (trace->trc->form==FORM_PAGE_COMP) trace->trc->wide = 4; else trace->trc->wide = 3; } } if (trace->query & QUERY_WDTH) { printf("\n"); printf("\n Specify the maximum number of cases per table (%d fit in 132 columns).", trace->trc->wide); cf_iprompt("\n > Enter width in cases, CASES_PER_TABLE = [%d]: ", trace->trc->wide, &trace->trc->wide); } trace->rpt->wide = trace->trc->wide; trace->aux->wide = trace->trc->wide; if (trace->query & QUERY_DATA) { printf("\n\n/INCLUDE"); cf_nprompt("\n > Enter list of files with branch or bus lists: ", "", CF_INBUFSIZE, query); list = cf_text2List(query); ff_expList(trace, list, NULL); } if (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OVLD_OUTG) trace->query &= ~(QUERY_BUSV | QUERY_VOLT); if (trace->rpt->type==TYPE_OUTG_BUSV || trace->rpt->type==TYPE_BUSV_OUTG) trace->query &= ~(QUERY_OVLD | QUERY_LOAD); if (trace->query & QUERY_OUTG) { printf("\n\n/OUTAGE"); printf("\n > Enter outaged branches list :"); printf("\n > Tycown< BUS1 ><V1> < BUS2 ><V2>cs"); do { cf_nprompt("\n > ", "", CF_INBUFSIZE, query); if (strchr(query, FF_WILD)==NULL) { list = cf_id2Link(query, 'L'); cf_appList(&trace->outgList, list); } else { list = cf_text2Link(query); cf_appList(&trace->outgMask, list); } if ( list!=NULL && (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OUTG_BUSV) ) trace->query &= ~(QUERY_ZONE | QUERY_OWNR | QUERY_BSKV); } while (!cf_isblank(query)); } if (trace->query & QUERY_COMO) { printf("\n/COMMON_MODE"); printf("\n > Enter common-mode outages list :"); do { cf_nprompt("\n > ", "", CF_INBUFSIZE, query); if (strchr(query, FF_WILD)==NULL) { list = getCoMoOutg(query); cf_appList(&trace->comoList, list); } else { list = cf_text2Link(query); cf_appList(&trace->comoMask, list); } if ( list!=NULL && (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OUTG_BUSV) ) trace->query&= ~(QUERY_ZONE | QUERY_OWNR | QUERY_BSKV); } while (!cf_isblank(query)); if (list!=NULL && (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OUTG_BUSV)) trace->query &= ~(QUERY_ZONE | QUERY_OWNR | QUERY_BSKV); } if (trace->query & (QUERY_OWNR | QUERY_ZONE | QUERY_BSKV)) { printf("\n\n/OUTG_OWNER, /OUTG_ZONE, /OUTG_BASE_KV"); printf("\n Specify selection of branch OUTAGEs and COMMON_MODE outages"); } if (trace->query & QUERY_OWNR) { cf_nprompt("\n > Enter owners of interest..[all owners='%s']: ", "***", CF_INBUFSIZE, query); list = cf_text2List(query); cf_appList(&trace->ownrOutg, list); } if (trace->query & QUERY_ZONE) { cf_nprompt("\n > Enter zones of interest.....[all zones='%s']: ", "**", CF_INBUFSIZE, query); list = cf_text2List(query); cf_appList(&trace->zoneOutg, list); } if (trace->query & QUERY_BSKV) { cf_nprompt("\n > Enter base_kv of interest.[all base kV='%s']: ", ">0", CF_INBUFSIZE, query); list = cf_text2List(query); cf_appList(&trace->bskvOutg, list); } if (trace->query & QUERY_OVLD) { printf("\n\n/OVERLOAD"); printf("\n > Enter overloaded branches list :"); printf("\n > Tycown< BUS1 ><V1> < BUS2 ><V2>cs"); do { cf_nprompt("\n > ", "", CF_INBUFSIZE, query); if (strchr(query, FF_WILD)==NULL) { list = cf_id2Link(query, 'L'); cf_appList(&trace->ovldList, list); } else { list = cf_text2Link(query); cf_appList(&trace->ovldMask, list); } if ( list!=NULL && (trace->rpt->type==TYPE_OVLD_OUTG || trace->rpt->type==TYPE_BUSV_OUTG) ) trace->query&= ~(QUERY_ZN_P | QUERY_OW_P | QUERY_KV_P); } while (!cf_isblank(query)); if (list!=NULL && (trace->rpt->type==TYPE_OVLD_OUTG || trace->rpt->type==TYPE_BUSV_OUTG)) trace->query &= ~(QUERY_ZN_P | QUERY_OW_P | QUERY_KV_P); } if (trace->query & QUERY_BUSV) { printf("\n\n/BUS"); printf("\n > Enter busses list :"); printf("\n > Tycown< NAME ><KV>"); do { cf_nprompt("\n > ", "", CF_INBUFSIZE, query); if (strchr(query, FF_WILD)==NULL) { list = cf_id2Link(query, 'I'); cf_appList(&trace->busvList, list); } else { list = cf_text2Link(query); cf_appList(&trace->busvMask, list); } if ( list!=NULL && (trace->rpt->type==TYPE_OVLD_OUTG || trace->rpt->type==TYPE_BUSV_OUTG) ) trace->query &= ~(QUERY_ZN_P | QUERY_OW_P | QUERY_KV_P); } while (!cf_isblank(query)); if (list!=NULL && (trace->rpt->type==TYPE_OVLD_OUTG || trace->rpt->type==TYPE_BUSV_OUTG)) trace->query &= ~(QUERY_ZN_P | QUERY_OW_P | QUERY_KV_P); } if (trace->query & (QUERY_OW_P | QUERY_ZN_P | QUERY_KV_P)) { printf("\n\n/PROB_OWNER, /PROB_ZONE, /PROB_BASE_KV"); if (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OVLD_OUTG) printf("\n Specify selection of OVERLOADed branches"); if (trace->rpt->type==TYPE_OUTG_BUSV || trace->rpt->type==TYPE_BUSV_OUTG) printf("\n Specify selection of over- or under-voltage BUSses"); } if (trace->query & QUERY_OW_P) { cf_nprompt("\n > Enter owners of interest..[all owners='%s']: ", "***", CF_INBUFSIZE, query); list = cf_text2List(query); cf_appList(&trace->ownrProb, list); } if (trace->query & QUERY_ZN_P) { cf_nprompt("\n > Enter zones of interest.....[all zones='%s']: ", "**", CF_INBUFSIZE, query); list = cf_text2List(query); cf_appList(&trace->zoneProb, list); } if (trace->query & QUERY_KV_P) { cf_nprompt("\n > Enter base_kv of interest.[all base kV='%s']: ", ">0", CF_INBUFSIZE, query); list = cf_text2List(query); cf_appList(&trace->bskvProb, list); } if (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OVLD_OUTG) { trace->query &= ~(QUERY_VOLT); } if (trace->rpt->type==TYPE_OUTG_BUSV || trace->rpt->type==TYPE_BUSV_OUTG) { trace->query &= ~(QUERY_LOAD); } if (trace->query & (QUERY_LOAD | QUERY_VOLT | QUERY_SPAN | QUERY_SOLN)) { printf("\n\n/LIMITS"); } if (trace->query & QUERY_SPAN) { if (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OVLD_OUTG) { cf_fprompt("\n > Enter variance ceiling (%%),VARI_CEILING=[%2.0f]: ", 1.0, &trace->varCeiling); cf_fprompt("\n > Enter variance floor (%%), VARI_FLOOR =[%2.0f]: ",-1.0, &trace->varFloor); } if (trace->rpt->type==TYPE_OUTG_BUSV || trace->rpt->type==TYPE_BUSV_OUTG) { cf_fprompt("\n > Enter variance ceiling PU, VARI_CEILING =[%3.3f]: ", .01, &trace->varCeiling); cf_fprompt("\n > Enter variance floor PU, VARI_FLOOR =[%3.3f]: ",-.01, &trace->varFloor); } } if (trace->query & QUERY_LOAD) { cf_fprompt("\n > Enter min loading in %%, MIN_LOAD_PCT = [%2.0f%%]: ", trace->minLoadPct, &trace->minLoadPct); } if (trace->query & QUERY_VOLT) { cf_fprompt("\n > Max 500kV-bus voltage PU, MAX_500_PU=[%5.3f]: ", trace->max5, &trace->max5); cf_fprompt("\n > Min 500kV-bus voltage PU, MIN_500_PU=[%5.3f]: ", trace->min5, &trace->min5); cf_fprompt("\n > Max sub-500kV voltage PU, MAX_BUS_PU=[%5.3f]: ", trace->maxV, &trace->maxV); cf_fprompt("\n > Min sub-500kV voltage PU, MIN_BUS_PU=[%5.3f]: ", trace->minV, &trace->minV); } if (trace->query & QUERY_SOLN) { printf("\n"); trace->soln = cf_yprompt("\n > Include solution problems? INC_SOLN_PROB=[%c]: ", 'Y'); } printf("\n"); cf_strsuf(trace->rpt->spec, trace->outName, '.', ".rpt"); cf_strsuf(trace->aux->spec, trace->outName, '.', ".aux"); cf_strsuf(trace->trc->spec, trace->outName, '.', ".trc"); printf("%s\n", DOT_LINE); return; } void openReport(cf_Out *rpt) { rpt->file = cf_openFile(rpt->spec, "w"); cf_exit(rpt->file==NULL, "Quitting!\n"); } void printTrace(Trace *trace) { FILE *fp; if (trace->trc->type==TYPE_NONE) return; openReport(trace->trc); fp = trace->trc->file; if (fp == NULL) fp = stderr; fprintf(fp, ". %s %s %s %s\n", trace->trc->spec, trace->trc->time, trace->userID, trace->IPFversion); cf_printList(fp, trace->pfoList, CF_oneStyl, "/PFO\n"); fprintf(fp, "/REPORT\n"); fprintf(fp, " NAME = %s\n", trace->outName); if (trace->type ==TYPE_OUTG_OVLD) fprintf(fp," TYPE = OUTAGE-OVERLOAD\n"); if (trace->type ==TYPE_OUTG_BUSV) fprintf(fp," TYPE = OUTAGE-BUS_V\n"); if (trace->type ==TYPE_OVLD_OUTG) fprintf(fp," TYPE = OVERLOAD-OUTAGE\n"); if (trace->type ==TYPE_BUSV_OUTG) fprintf(fp," TYPE = BUS_V-OUTAGE\n"); if (trace->type ==TYPE_OVLD_BOTH) fprintf(fp," TYPE = OVERLOAD-BOTH-WAYS\n"); if (trace->type ==TYPE_BUSV_BOTH) fprintf(fp," TYPE = BUS_V-BOTH-WAYS\n"); if (trace->sort ==SORT_BY_ALPHA ) fprintf(fp," SORT = ALPHA\n"); if (trace->sort ==SORT_BY_BASEKV) fprintf(fp," SORT = BASE_KV\n"); if (trace->sort ==SORT_BY_OWNER ) fprintf(fp," SORT = OWNER\n"); if (trace->sort ==SORT_BY_ZONE ) fprintf(fp," SORT = ZONE\n"); if (trace->sort ==SORT_BY_INPUT ) fprintf(fp," SORT = INPUT\n"); if (trace->sort ==SORT_BY_SOLN ) fprintf(fp," SORT = SOLUTION\n"); if (trace->sort ==SORT_BY_DIFF ) fprintf(fp," SORT = SOLUTION\n"); if (trace->trc->form==FORM_DATA_FULL) fprintf(fp," FORMAT = DATA_FULL\n"); if (trace->trc->form==FORM_DATA_BREF) fprintf(fp," FORMAT = DATA_BRIEF\n"); if (trace->trc->form==FORM_PAGE_WIDE) fprintf(fp," FORMAT = PAGE_WIDE\n"); if (trace->trc->form==FORM_PAGE_COMP) fprintf(fp," FORMAT = PAGE_COMPACT\n"); if (trace->redun ==REDUN_REMOVE ) fprintf(fp," REMOVE_REDUNDANT = YES\n"); if (trace->redun ==REDUN_KEEP ) fprintf(fp," REMOVE_REDUNDANT = NO\n"); if (trace->trc->type==TYPE_TRACE ) fprintf(fp," TRACE = YES\n"); if (trace->trc->type!=TYPE_TRACE ) fprintf(fp," TRACE = NO\n"); if (trace->trc->diff==VARI_YES ) fprintf(fp," VARIANCE = YES\n"); if (trace->trc->diff==VARI_NO ) fprintf(fp," VARIANCE = NO\n"); fprintf(fp, " CASES_PER_TABLE = %d\n", trace->trc->wide); fprintf(fp, "/LIMITS\n"); if (trace->trc->diff==VARI_YES) { fprintf(fp, " VARIANCE_CEILING = %6.4f\n", trace->varCeiling); fprintf(fp, " VARIANCE_FLOOR = %6.4f\n", trace->varFloor); } if (trace->rpt->type==TYPE_OUTG_OVLD || trace->rpt->type==TYPE_OVLD_OUTG) { fprintf(fp, " MIN_LOAD_PCT = %6.4f\n", trace->minLoadPct); } if (trace->rpt->type==TYPE_OUTG_BUSV || trace->rpt->type==TYPE_BUSV_OUTG) { fprintf(fp, " MAX_500_PU = %6.4f\n", trace->max5); fprintf(fp, " MIN_500_PU = %6.4f\n", trace->min5); fprintf(fp, " MAX_BUS_PU = %6.4f\n", trace->maxV); fprintf(fp, " MIN_BUS_PU = %6.4f\n", trace->minV); } if (trace->soln == INC_SOLN_PROB ) fprintf(fp," INC_SOLN_PROB = YES\n"); if (trace->soln == SKP_SOLN_PROB ) fprintf(fp," INC_SOLN_PROB = NO\n"); cf_printList(fp, trace->ownrOutg, CF_dznStyl, "/OUTG_OWNER\n"); cf_printList(fp, trace->zoneOutg, CF_dznStyl, "/OUTG_ZONE\n"); cf_printList(fp, trace->bskvOutg, CF_sixStyl, "/OUTG_BASE_KV\n"); cf_printList(fp, trace->ownrProb, CF_dznStyl, "/PROB_OWNER\n"); cf_printList(fp, trace->zoneProb, CF_dznStyl, "/PROB_ZONE\n"); cf_printList(fp, trace->bskvProb, CF_sixStyl, "/PROB_BASE_KV\n"); cf_printList(fp, trace->outgList, FF_mskStyl, "/OUTAGE\n.ycown< BUS1 ><V1> < BUS2 ><V2>cs\n"); cf_printList(fp, trace->outgMask, FF_mskStyl, "/OUTAGE\n.ycown< BUS1 ><V1> < BUS2 ><V2>cs\n"); cf_printList(fp, trace->comoList, FF_mskStyl, "/COMMON_MODE\n"); cf_printList(fp, trace->comoMask, FF_mskStyl, "/COMMON_MODE\n"); cf_printList(fp, trace->ovldList, FF_mskStyl, "/OVERLOAD\n.ycown< BUS1 ><V1> < BUS2 ><V2>cs\n"); cf_printList(fp, trace->ovldMask, FF_mskStyl, "/OVERLOAD\n.ycown< BUS1 ><V1> < BUS2 ><V2>cs\n"); cf_printList(fp, trace->busvList, FF_mskStyl, "/BUS\n.ycown< BUS ><KV>zn\n"); cf_printList(fp, trace->busvMask, FF_mskStyl, "/BUS\n.ycown< BUS ><KV>zn\n"); } void queryContinue(Trace *trace) { int yes; if (trace->trc->type==TRACE_YES) printf("\nTrace written to %s", trace->trc->spec); if (CF_logFile != NULL) printf("\nError Summary written to %s", CF_logSpec); if ( trace->query & QUERY_CONT) { yes= cf_yprompt("\n > Do you want to continue this run? [%c]: ",'Y'); cf_exit(!yes, "Quitting!"); } } void collectData(Trace *trace) { FILE *pfo_File; Link *curPfo; trace->mainTable = NULL; curPfo=trace->pfoList; while (curPfo!=NULL) { if ( (pfo_File = cf_openFile(curPfo->data, "r")) == NULL ) { cf_logErr(" Cannot open this *.pfo file: %s\n", curPfo->data); curPfo = cf_delLink(&trace->pfoList, curPfo); continue; } fprintf(stdout, " Searching %s\n", curPfo->data); if (buildMainTable(pfo_File, trace)==0) { printf(" No data in this .pfo file.\n"); curPfo = cf_delLink(&trace->pfoList, curPfo); continue; } fclose(pfo_File); trace->nCases++; curPfo=curPfo->next; } } void finalRemarks(Trace *trace) { printf("\n"); printf("\nMemory allocation (bytes): Cur:%ld Max:%ld Alloc:%ld Freed:%ld\n", CF_memCurAlloc, CF_memMaxAlloc, CF_memTotAlloc, CF_memTotFreed); if (trace->rpt->type!=TYPE_NONE) printf("\nOutput report written to %s", trace->rpt->spec); if (trace->aux->type!=TYPE_NONE) printf("\nOutput report written to %s", trace->aux->spec); if (trace->trc->type!=TYPE_NONE) printf("\nTrace report written to %s", trace->trc->spec); if (CF_logFile != NULL) printf("\nError report written to %s", CF_logSpec); printf("\n"); return; } void tableLegend(cf_Out *rpt) { fprintf(rpt->file,"%s", MSG_CRTCL); fprintf(rpt->file,"%s", MSG_UNITS); fprintf(rpt->file,"%s", MSG_FLAGS); fprintf(rpt->file,"%s", MSG_LWRCS); fprintf(rpt->file,"%s", MSG_SYMBL); fprintf(rpt->file,"%s", MSG_FALRX); fprintf(rpt->file,"%s", MSG_NOSOL); fprintf(rpt->file,"%s", MSG_SEPAR); rpt->line += 9; } int buildMainTable(FILE *pfo_File, Trace *trace) { int state; Link *curRow, *problem, *newRow, *newSoln, *newProb; state = (SRCHN_4_COMO_SUM | SRCHN_4_OUTG_SUM | SRCHN_4_FAIL_SUM); curRow = trace->mainTable; /* system("show time"); */ problem = NULL; trace->IPFversion[0] = '\0'; while ( (problem=getOutgSet(pfo_File, &state, problem, trace)) != NULL ) { if (screenProb(problem, *trace)==0) continue; newProb = cf_dupList(problem); newSoln = newProb->next->next; newProb->next->next = NULL; newRow = cf_link2row(newProb); cf_insLink(&trace->mainTable, &curRow, newRow, (long) SORT_BY_ALPHA, CF_INS_FREE, (int (*)(Link*, Link*, int))(ff_cmpRow)); ff_appSoln2Row(curRow, newSoln, trace->nCases+1);/* add 1 to skip prob id */ } /* system("show time"); */ printf(" IPF Executible Used: version = %3.3s\n", trace->IPFversion); return (state & VALID_DATA) ? 1 : 0; } int screenProb(Link *problem, Trace trace) { /* return 0 if problem is to be skipped over, else non-zero */ cf_Branch *outg, *ovld; cf_Bus *busv; int type, vo = 0, vp = 0; type = trace.type; outg = (cf_Branch *) problem->data; if ( outg==NULL) { return; } else if ( outg->type[0]=='c' ) { /* common mode outages */ if ( validInput(trace.comoList, outg)==1 ) vo = 1; if ( validMask(trace.comoMask, (cf_Name *) outg)==1 ) vo = 1; if ( trace.zoneOutg!=NULL || trace.ownrOutg!=NULL || trace.bskvOutg!=NULL ) vo = 1; } else if ( outg->type[0]!='c' ) { /* branch outages */ cf_branch_l2h(outg); if ( validInput(trace.outgList, outg)==1 ) vo = 1; if ( validMask(trace.outgMask, (cf_Name *) outg)==1 ) vo = 1; if ( cf_validZone(trace.zoneOutg,outg->bus1_zone,outg->bus2_zone)==1 && cf_validOwner(trace.ownrOutg,outg->owner)==1 && cf_validBasekv(trace.bskvOutg,outg->bus1_kv,outg->bus2_kv)==1 ) vo = 1; } if (vo==0) return 0; if (type==TYPE_OUTG_OVLD || type==TYPE_OVLD_OUTG || type==TYPE_OVLD_BOTH) { ovld = (cf_Branch *) problem->next->data; if ( ovld->type[0]=='s' ) return trace.soln; /*include system problems*/ if ( ovld->type[0]=='B' ) return 0; /*skip voltage violations*/ cf_branch_l2h(ovld); if ( validInput(trace.ovldList, ovld)==1 ) vp = 1; if ( validMask(trace.ovldMask, (cf_Name *) ovld)==1 ) vp = 1; if ( cf_validZone(trace.zoneProb,ovld->bus1_zone,ovld->bus2_zone)==1 && cf_validOwner(trace.ownrProb, ovld->owner)==1 && cf_validBasekv(trace.bskvProb, ovld->bus1_kv, ovld->bus2_kv)==1 ) vp = 1; } if (type==TYPE_OUTG_BUSV || type==TYPE_BUSV_OUTG || type==TYPE_BUSV_BOTH) { busv = (cf_Bus *) problem->next->data; if ( busv->type[0]=='s' ) return trace.soln; /*include system problems*/ if ( busv->type[0]!='B' ) return 0; /* skip overloads */ if ( validInput(trace.busvList, (cf_Branch *) busv)==1 ) vp = 1; if ( validMask(trace.busvMask, (cf_Name *) busv)==1 ) vp = 1; if ( cf_validZone(trace.zoneProb, busv->zone, busv->zone)==1 && cf_validOwner(trace.ownrProb, busv->owner)==1 && cf_validBasekv(trace.bskvProb, busv->kv, busv->kv)==1 ) vp = 1; } return vp; } Link *getOutgSet(FILE *pfo_File, int *state, Link *problem, Trace *trace) { /* searching the summary of bus and line problems for each outage */ long id, pos; char s[CF_INPFOSIZE+1], name[39], *end, *dbg_file = "FINDOUT.DBG", *dbg_mode = "a"; static char format[132]; struct nlist *np; FILE *dbg_fp; entry++; /* dbg_fp = fopen (dbg_file, dbg_mode); if (dbg_fp == NULL) { fprintf (stderr, "Can't open debug file FINDOUT.DBG\n"); exit (1); } */ while (1) { pos = ftell(pfo_File); /* needed to get 3 buses per line in PTI data */ if (fgets(s, CF_INPFOSIZE, pfo_File)==NULL) break; /* fprintf (dbg_fp, " %5d %5d [%s]\n", entry, ++count, s); */ fprintf (stderr, " %5d %5d [%s]\n", entry, ++count, s); if (count > 6544) { fprintf (stderr, "getOutgSet: Processing record # %10d\n", count); } if (s[0]=='0' || s[0]=='1') s[0]=' '; end = strrchr(s, '\r'); if (end!=NULL) *end = '\0';/* needed for PTI data */ id = identifyInput(s); /****************** debug stuff **************************/ /* printf("\n%2d %50.50s", id, s); */ /****************** debug stuff **************************/ if ( id==7 ) continue; /*********** funky fix stuff to get around funky hacked code ***********/ /* if ( id==5 ) { sscanf(s, "%*35c %3s", trace->IPFversion); continue; } */ if ( id==5 ){sscanf(s, "%*35c %3s", trace->IPFversion); id=identifyInput(&s[5]);} /*********** funky fix stuff to get around funky hacked code ***********/ if ( id==6 ) { strcpy(trace->IPFversion,"PTI"); *state|=DATA_PTI; continue;} if ( id==60) { strcpy(format, SYST_FORMAT_312); continue; } if ( id==50) { strcpy(format, COMO_FORMAT_312); continue; } if ( id==51) { strcpy(format, COMO_FORMAT_314); continue; } if ( id==20) { strcpy(format, OUTG_FORMAT_312); } if ( id==21) { strcpy(format, OUTG_FORMAT_PTI); } if ( id==30) { strcpy(format, OVLD_FORMAT_312); } if ( id==31) { strcpy(format, OVLD_FORMAT_314); } if ( id==32) { strcpy(format, OVLD_FORMAT_316); } if ( id==33) { strcpy(format, OVLD_FORMAT_PTI); } if ( id==40) { strcpy(format, BUSV_FORMAT_312); } if ( id==41) { strcpy(format, BUSV_FORMAT_316); } if ( id==42) { strcpy(format, BUSV_FORMAT_PTI); } if ( (*state & SRCHN_4_COMO_SUM) && (id==10) ) { *state &= ~(SRCHN_4_COMO_SUM); *state |= READING_COMO_SUM; continue; } if ( (*state & SRCHN_4_OUTG_SUM) && (id==11 || id==13) ) { *state &= ~(SRCHN_4_OUTG_SUM); *state |= READING_OUTG_SUM; continue; } if ( (*state & SRCHN_4_FAIL_SUM) && (id==12) ) { *state &= ~(GET_OVLD | GET_BUSV); *state &= ~(SRCHN_4_FAIL_SUM); *state |= READING_FAIL_SUM; continue; } if (id==-1) { if ( *state & READING_COMO_SUM ) *state &= ~READING_COMO_SUM; if ( *state & READING_OUTG_SUM ) *state &= ~READING_OUTG_SUM; if ( *state & READING_FAIL_SUM ) *state &= ~READING_FAIL_SUM; } if ( !(*state & (READING | SRCHING)) ) { return NULL; } if ( !(*state & READING) ) continue; if ( (id==30 || id==31 || id==32 || id==33) && (*state & GET_OUTG) ) { *state &= ~GET_BUSV; *state |= GET_OVLD; } if ( (id==40 || id==41 || id==42) && (*state & GET_OUTG) ) { *state &= ~GET_OVLD; *state |= GET_BUSV; } if ( (id==20 || id==21) && (*state & READING_OUTG_SUM) ) { /* branch/common mode/PTI outage */ *state &= ~(GET_OVLD | GET_BUSV | GET_OUTG); /* clear all GET_* flags */ if (*state & DATA_PTI) { np = NULL; /* no common-mode redundant outages */ } else { /* only check for redundant outages with IPF data */ sscanf(s, " %38[^\n]", name); np = lookup(name); } if ( np!=NULL ) { /* condition satified only if IPF AND redundant */ if (np->keep == 0) continue; if (np->keep == 2) { cf_logErr("Redundant Outage Skipped: [%s]\n", name); continue; } cf_freeList(problem); problem = getCoMoOutg(s); } else { cf_freeList(problem); problem = getBrchOutg(s, format); } if (problem!=NULL) *state |= GET_OUTG;/*set only if valid outage found*/ if (*state & DATA_PTI) { *state |= GET_OVLD; strcpy(format, OVLD_FORMAT_PTI); } } if ( (id==0) && (*state & READING_COMO_SUM) ) { /* install: 0-skip, 1-rpt */ if ( sscanf(s, COMO_MOD_NA_312, name) == 1) { if (install(name, 0)==NULL) cf_logErr("install(name, 0) failed\n"); } else if ( getCoMoRslt(s, format, *trace) == 1) { if (install(name, 1)==NULL) cf_logErr("install(name, 1) failed\n"); } if (trace->redun==REDUN_REMOVE) installResult(s); /* screen out outages already taken by com.mode */ } /* default is 0, upgrade to keep=1 if any result yields keep */ if ( (id==0) && (*state & GET_OVLD) ) { cf_freeList(problem->next); if ( (getOvldLoad(s, format, problem)) == 1) continue; *state |= VALID_DATA; return problem; } if ( (id==0) && (*state & GET_BUSV) ) { cf_freeList(problem->next); if ( (getBusvVolt(s, format, problem)) == 1) continue; *state |= VALID_DATA; if (*state & DATA_PTI) { if (strcmp(format, BUSV_FORM_3_PTI)==0) { strcpy(format, BUSV_FORMAT_PTI); } else if (strcmp(format, BUSV_FORM_2_PTI)==0) { if (pos > 0) { fseek(pfo_File, pos, SEEK_SET); strcpy(format, BUSV_FORM_3_PTI); } } else if (strcmp(format, BUSV_FORMAT_PTI)==0) { if (pos > 0) { fseek(pfo_File, pos, SEEK_SET); strcpy(format, BUSV_FORM_2_PTI); } } } return problem; } if ( (id==0) && (*state & READING_FAIL_SUM) ) { if ( (problem=getSystProb(s, format, problem))==NULL) continue; *state |= VALID_DATA; return problem; } } return NULL; } void installResult(char *s) { int convL, convT; char n1[9], v1[6], n2[9], v2[6], ckt, own[4], result[39]; convL = sscanf(s, " L%*3cD%*3c%3[^\n]%*9c%8[^\n]%*c%5[^\n]%*c%8[^\n]%*c%5[^\n]%*c%1c", own, n1, v1, n2, v2, &ckt); convT = sscanf(s, " T%*3cD%*3c%3[^\n]%*9c%8[^\n]%*c%5[^\n]%*c%8[^\n]%*c%5[^\n]%*c%1c", own, n1, v1, n2, v2, &ckt); if (convL<5 && convT<5) return; sprintf(result, "%-8.8s %5.5s %-8.8s %5.5s %c %-3.3s", n1, v1, n2, v2, ckt, own); if (install(result, 2)==NULL) /* 2 indicates a common-mode outage result */ cf_logErr("install(result, 2) failed\n"); /* cf_logErr("Result Installed: [%s]\n", result); */ } int getCoMoRslt(char *s, char *format, Trace trace) { /* return 1 if keep, else 0 to not report on this outage */ char type[3], chng, own[4], z1[3], z2[3]; float v1, v2; if ( sscanf(s, format, type, &chng, own, z1, z2, &v1, &v2) != 7 ) return 0; if (type[0]!='B' && type[0]!='T' && type[0]!='L') return 0; if (type[0]=='B') { strcpy(z2, z1); v2 = v1; } if ( cf_validZone(trace.zoneOutg, z1, z2)==0 ) return 0; if ( cf_validOwner(trace.ownrOutg, own)==0 ) return 0; if ( cf_validBasekv(trace.bskvOutg, v1, v2)==0 ) return 0; return 1; /* report */ } Link *getSystProb(char *s, char *format, Link *problem) { /* returns: NULL if not valid, Link * if valid */ cf_Name b, *systData; ff_soln bo, *solnData; Link *systLink, *solnLink; char name[39]; struct nlist *np; sscanf(s, " %38[^\n]", name); np = lookup(name); if (np==NULL) problem = getBrchOutg(s, format); else if (np->keep==1) problem = getCoMoOutg(s); else return NULL; systLink = cf_addLink(problem, sizeof(cf_Name)); systData = (cf_Name *) systLink->data; strcpy(b.type, "sp"); /* solution problems */ memcpy(systData, &b, sizeof(cf_Name)); if (strstr(s, "separation")!=NULL) bo.code = 'S'; else if (strstr(s, "(Reactive)" )!=NULL) bo.code = 'X'; else if (strstr(s, "No solution")!=NULL) bo.code = 'F'; else return NULL; solnLink = cf_addLink(systLink, sizeof(ff_soln)); solnData = (ff_soln *) solnLink->data; memcpy(solnData, &bo, sizeof(ff_soln)); return problem; } int getBusvVolt(char *s, char *format, Link *problem) { cf_Bus b, *busvData; ff_soln bo, *solnData; Link *busvLink, *solnLink; memset(&b, '\0', sizeof(cf_Bus)); memset(&bo, '\0', sizeof(ff_soln)); if (strncmp(format, BUSV_FORMAT_PTI, 5)==0) { if ( sscanf(s, format, b.name, &b.kv, &bo.ratio) < 3) return 1; bo.actual = bo.ratio * b.kv; } else { if ( sscanf(s, format, b.name, &b.kv, b.owner, b.zone, &bo.actual, &bo.ratio, &bo.pre_con, &bo.min_ref, &bo.max_new) < 8 ) return 1; if (bo.max_new==0) { /* shift over values for old format, <v.316 */ bo.max_new = bo.min_ref; bo.min_ref=bo.pre_con; bo.pre_con = -9999; } } strcpy(b.type, "B "); busvLink = cf_addLink(problem, sizeof(cf_Bus)); solnLink = cf_addLink(busvLink, sizeof(ff_soln)); busvData = (cf_Bus *) busvLink->data; solnData = (ff_soln *) solnLink->data; memcpy(busvData, &b, sizeof(cf_Bus)); memcpy(solnData, &bo, sizeof(ff_soln)); return 0; } int getOvldLoad(char *s, char *format, Link *problem) { cf_Branch r, *ovldData; ff_soln ro, *solnData; Link *ovldLink, *solnLink; memset(&r, '\0', sizeof(cf_Branch)); memset(&ro, '\0', sizeof(ff_soln)); if (strncmp(format, OVLD_FORMAT_PTI, 5)==0) { if (sscanf(s, format, r.bus1_name, &r.bus1_kv, r.bus2_name, &r.bus2_kv, &r.ckt_id, &ro.pre_con, &ro.actual, &ro.max_new, &ro.ratio)<9) return 1; } else { if (sscanf(s, format, r.bus1_name, &r.bus1_kv, r.bus2_name, &r.bus2_kv, &r.ckt_id, &r.section, r.owner, r.bus1_zone, r.bus2_zone, &ro.max_new, &ro.code, &ro.ratio, &ro.actual, &ro.pre_con, ro.date) < 13) return 1; if (ro.pre_con==0) ro.pre_con = -9999; ro.ratio = 100 * ro.ratio; /* per cent = 100 * Per Unit */ date(&ro.date[0]); } if (r.bus1_kv==r.bus2_kv) strcpy(r.type, "L "); else strcpy(r.type, "T "); ovldLink = cf_addLink(problem, sizeof(cf_Branch)); solnLink = cf_addLink(ovldLink, sizeof(ff_soln)); ovldData = (cf_Branch *) ovldLink->data; solnData = (ff_soln *) solnLink->data; memcpy(ovldData, &r, sizeof(cf_Branch)); memcpy(solnData, &ro, sizeof(ff_soln)); return 0; } Link *getCoMoOutg(char *s) { cf_Name *comoData; Link *comoLink; char name[CF_INBUFSIZE]; if (sscanf(s, " %38[^\n]", name) < 1) return NULL; comoLink = cf_newLink(sizeof(cf_Name)); if (comoLink==NULL || comoLink->data==NULL) return NULL; comoLink->kind = CF_KIND_NAME; comoData = (cf_Name *) comoLink->data; strcpy(comoData->type, "cm"); sprintf(comoData->name, "%-38s", name); return comoLink; } Link *getBrchOutg(char *s, char *format) { cf_Branch *brznData, t; Link *brznLink; memset(&t, '\0', sizeof(cf_Branch)); if (sscanf(s, format, t.bus1_name, &t.bus1_kv, t.bus2_name, &t.bus2_kv, &t.ckt_id, t.owner, t.bus1_zone, t.bus2_zone) < 8) return NULL; brznLink = cf_newLink(sizeof(cf_Branch)); if ( t.bus1_zone[0]=='-' || t.bus1_zone[1]=='-' ) t.bus1_zone[0] = '\0'; if ( t.bus2_zone[0]=='-' || t.bus2_zone[1]=='-' ) t.bus2_zone[0] = '\0'; if ( t.owner[0]=='-' ) t.owner[0] = '\0'; if (t.bus1_kv==t.bus2_kv) strcpy(t.type, "L "); else strcpy(t.type, "T "); brznData = (cf_Branch *) brznLink->data; memcpy(brznData, &t, sizeof(cf_Branch)); return brznLink; } int identifyInput(char *s) { if (strstr(s, BPA_PF_PROG_VERS) != NULL) return 5; /* 5 = program version */ if (strstr(s, PTI_INTERAC_PSSE) != NULL) return 6; /* 6 = PTI program */ if (strstr(s, HEADER_BREAK_PTI) != NULL) return 7; /* 7 = page break */ if (strstr(s, HEADER_COMME_PTI) != NULL) return 7; /* 7 = header comment */ if (strstr(s, DIS_FAC_FILE_PTI) != NULL) return 7; /* 7 = misc. data files */ if (strstr(s, SUB_DES_FILE_PTI) != NULL) return 7; /* 7 = misc. data files */ if (strstr(s, MON_ELE_FILE_PTI) != NULL) return 7; /* 7 = misc. data files */ if (strstr(s, CON_DES_FILE_PTI) != NULL) return 7; /* 7 = misc. data files */ if (strstr(s, CONTINGENCY_ANAL) != NULL) return 7; /* 7 = page break */ if (strstr(s, OUTG_SIMUL_INPUT) != NULL) return 7; /* 7 = page break */ if (strstr(s, __O_U_T_A_G_E__ ) != NULL) return 7; /* 7 = page header */ if (strstr(s, "Mode Name ") != NULL) return 7; /* 7 = old failed sol r */ if (strstr(s, "Results in:" ) != NULL) return 7; /* 7 = common mode outg */ if (strstr(s, " --- " ) != NULL) return 7; /* 7 = common mode list */ if (strstr(s, "(MW) (MVAR) ") != NULL) return 7; /* 7 = common mode list */ if (strstr(s, " MW MVAR ") != NULL) return 7; /* 7 = common mode list */ if (strlen(s) <= 3) return 7; /* 7 = blank line */ if (strstr(s, SUM_COM_MODE_OUT) != NULL) return 10; /*10 = common mode outg */ /**************** debug Stuff ****************** if (strstr(s, SUM_COM_MODE_OUT) != NULL) { printf("\n SUM_COM_MODE_OUT has been found \n"); return 10;} **************** debug Stuff ******************/ if (strstr(s, SUM_PROBS_4E_OUT) != NULL) return 11; /*11 = outage report */ if (strstr(s, SUM_SYST_SEP_DIV) != NULL) return 12; /*12 = failed soln rept */ if (strstr(s, CONTIN_EVENT_PTI) != NULL) return 13; /*13 = outage report,PTI*/ if (strstr(s, "Summary of" ) != NULL) return -1; /*-1 = wrong summary */ if (strstr(s, "- - - - - - - ") != NULL) return 20; /*20 = outage */ if (strstr(s, OPEN_LINE_FR_PTI) != NULL) return 21; /*21 = outage, PTI */ if (strstr(s, OVLD_RAT_TY_312 ) != NULL) return 30; /*30 = overload follows */ if (strstr(s, OVLD_RAT_TY_314 ) != NULL) return 31; /*31 = ovld new format */ if (strstr(s, OVLD_RAT_TY_316 ) != NULL) return 32; /*32 = ovld newest form*/ if (strstr(s, OVLD_FRO_TO_PTI ) != NULL) return 33; /*33 = ovld PTI format */ if (strstr(s, BUS_VV_A_PU_312 ) != NULL) return 40; /*40 = old bus volt form*/ if (strstr(s, BUS_VV_A_PU_316 ) != NULL) return 41; /*41 = new bus volt form*/ if (strstr(s, BUS_BUS_VPU_PTI ) != NULL) return 42; /*42 = PTI bus volt form*/ if (strstr(s, TY_CH_OWN_B_312 ) != NULL) return 50; /*50 = old co mo format */ if (strstr(s, TY_CH_OWN_Z_315 ) != NULL) return 51; /*51 = new co mo format */ if (strstr(s, OUTG_ID_OWN_314 ) != NULL) return 60; /*60 = failed soln rept */ if (strstr(s, OUTG_ID_OWN_312 ) != NULL) return 60; /*60 = old failed sol r */ return 0; /* 0 = possible data */ } void buildReport(Trace *trace, cf_Out *rpt) { /* build table for output report */ Link *curRow, *mainRow, *newRow, *probLink, *outgLink, *solnLink; cf_Name *probData; cf_Branch *outgData; int Dbug = 0; trace->rptTable = NULL; printf(" Building Report Table\n"); curRow = NULL; for(mainRow=trace->mainTable; mainRow!=NULL; mainRow=mainRow->next) { outgLink = (Link *) mainRow->data; probLink = (outgLink!=NULL) ? outgLink->next : NULL; solnLink = (probLink!=NULL) ? probLink->next : NULL; probData = (probLink!=NULL) ? (cf_Name *) probLink->data : NULL; outgData = (cf_Branch *) outgLink->data; if (Dbug==1) { printf("\noutg: %s%5.1f %s%5.1f %c", outgData->bus1_name, outgData->bus1_kv, outgData->bus2_name, outgData->bus2_kv, outgData->ckt_id); } if (probData==NULL) continue; if (probData->type[0]!='s') { if (rpt->type==TYPE_OUTG_OVLD || rpt->type==TYPE_OVLD_OUTG) { /* outg, ovld */ if ( validLoad(*trace, solnLink)==0 ) continue; } else if (rpt->type==TYPE_OUTG_BUSV || rpt->type==TYPE_BUSV_OUTG) {/* outg, busv */ if (solnLink->prev!=probLink) printf("uggg!\n"); if (probLink->next!=solnLink) printf("bugg!\n"); if ( validVolt(*trace, solnLink)==0 ) continue; } } else if (validSoln(solnLink)==0) continue; /* skip if 0 */ if (rpt->diff==VARI_YES) { if (!validVariance(*trace, solnLink)) continue; } newRow = cf_link2row(outgLink); if (rpt->type==TYPE_OVLD_OUTG || rpt->type==TYPE_BUSV_OUTG) swapRowIdLinks((Link *) newRow->data); if (trace->sort==SORT_BY_INPUT) { cf_insLink(&(trace->rptTable), &curRow, newRow, (long) trace, CF_INS_SKIP, (int (*)(Link*, Link*, int))(ff_srtByInput)); } else { cf_insLink(&(trace->rptTable), &curRow, newRow, (long) trace->sort, CF_INS_SKIP, (int (*)(Link*, Link*, int))(ff_cmpRow)); } if (Dbug==1) { printf(" valid: %s%5.1f %s%5.1f %c", outgData->bus1_name, outgData->bus1_kv, outgData->bus2_name, outgData->bus2_kv, outgData->ckt_id); } } return; } void swapReport(Trace *trace) { /* build table for output report */ Link *curRow, *rptRow, *tmpRow, *tmpTable; if (trace->aux->type==TYPE_NONE) return; printf(" Swapping Report Table\n"); curRow = NULL; rptRow = trace->rptTable; tmpTable = NULL; while(rptRow!=NULL) { tmpRow = rptRow; if (rptRow->prev!=NULL) rptRow->prev->next = rptRow->next; if (rptRow->next!=NULL) rptRow->next->prev = rptRow->prev; rptRow = rptRow->next; tmpRow->next = NULL; tmpRow->prev = NULL; swapRowIdLinks((Link *) tmpRow->data); if (trace->sort==SORT_BY_INPUT) { cf_insLink(&(tmpTable), &curRow, tmpRow, (long) trace, CF_INS_SKIP, (int (*)(Link*, Link*, int))(ff_srtByInput)); } else { cf_insLink(&(tmpTable), &curRow, tmpRow, (long) trace->sort, CF_INS_SKIP, (int (*)(Link*, Link*, int))(ff_cmpRow)); } } trace->rptTable = tmpTable; return; } void swapRowIdLinks(Link *idLink) { /* swaps only the pointers to the Id objects */ Link *tempLink; tempLink = (Link *) idLink->data; idLink->data = idLink->next->data; idLink->next->data = tempLink; } void ff_appSoln2Row(Link *curRow, Link *solnLink, int skip) { Link *linkPtr; linkPtr = (Link *) curRow->data; while (skip-- > 0) { if (linkPtr->next==NULL) { linkPtr->next = cf_newLink(0); if (linkPtr->next!=NULL) linkPtr->next->prev=linkPtr; } linkPtr = linkPtr->next; } linkPtr->next = solnLink; solnLink->prev = linkPtr; } int ff_cmpID(Link *newLink, Link *xstLink) { cf_Branch *newIdData, *xstIdData; if (newLink==NULL || xstLink==NULL) return 1; if (newLink->data==NULL || xstLink->data==NULL) return -1; newIdData = (cf_Branch *) newLink->data; xstIdData = (cf_Branch *) xstLink->data; if (newIdData->type[0]=='c') { /* common_mode_outage */ return ff_cmpName((cf_Name *) newIdData, (cf_Name *) xstIdData); } else if (newIdData->type[0]=='B') { /* bus u/o volt */ return cf_cmpBus((pf_AC_bus *) newIdData, (pf_AC_bus *) xstIdData); } else if (newIdData->type[0]=='s') { /* system problem */ return (newIdData->type[0] - xstIdData->type[0]); } else { /* branch outage or overloaded branch */ return cf_cmpBranch((pf_branch *) newIdData, (pf_branch *) xstIdData); } } int ff_cmpType(Link *newId, Link *xstId) { cf_Name *newType, *xstType; newType = (cf_Name *) newId->data; xstType = (cf_Name *) xstId->data; if ( newType->type[0] < xstType->type[0] ) return -1; /* [type]-sort */ if ( newType->type[0] > xstType->type[0] ) return 1; /* [type]-sort */ if ( newType->type[0]=='s' ) return 1; /* force sort with ff_srtID */ return 0; } int ff_cmpName(cf_Name *b1, cf_Name *b2) { float c; if ( c=strncmp(b1->type, b2->type, 1) ) return c>0 ? 1 : -1; if ( c=strcmp(b1->name, b2->name) ) return c>0 ? 1 : -1; return 0; } int ff_cmpRow(Link *newRow, Link *xstRow, int sort) { int srt; Link *newId, *xstId; newId = (Link *) newRow->data; xstId = (Link *) xstRow->data; if (sort==SORT_BY_SOLN || sort==SORT_BY_DIFF) { if ( (srt=ff_cmpType(newId, xstId)) !=0 ) return srt; if ( (srt=ff_srtSoln(newId->next->next, xstId->next->next, sort)) != 0 ) return srt; } if ( (srt=ff_srtID(newId, xstId, sort)) != 0 ) return srt; else return ff_srtID(newId->next, xstId->next, sort); } int ff_srtSoln(Link *newSoln, Link *xstSoln, int sort) { /* compares only the solution in the first case for sorting purposes */ ff_soln *newData, *xstData; float newValu, xstValu; if (newSoln==NULL && xstSoln==NULL) return 0; if (newSoln==NULL && xstSoln!=NULL) return 1; if (newSoln!=NULL && xstSoln==NULL) return -1; if (newSoln->next==NULL && xstSoln->next==NULL) return 0; if (newSoln->next==NULL && xstSoln->next!=NULL) return 1; if (newSoln->next!=NULL && xstSoln->next==NULL) return -1; /* also could be called SORT_BY_LAST */ if (sort==SORT_BY_DIFF) { /* newSoln->refSoln->delSoln: delSoln may be NULL */ while (newSoln!=NULL && newSoln->next!=NULL) newSoln=newSoln->next; while (xstSoln!=NULL && xstSoln->next!=NULL) xstSoln=xstSoln->next; newData = (ff_soln *) ( newSoln!=NULL ? newSoln->data : NULL ); xstData = (ff_soln *) ( xstSoln!=NULL ? xstSoln->data : NULL ); } else { newData = (ff_soln *) newSoln->data; xstData = (ff_soln *) xstSoln->data; } newValu = (newData!=NULL) ? newData->ratio : 0; xstValu = (xstData!=NULL) ? xstData->ratio : 0; if (newValu==0 && xstValu==0) return 0; if (newValu < xstValu) return 1; if (newValu > xstValu) return -1; return 0; } int ff_srtID(Link *newLink, Link *xstLink, int sort) { cf_Branch *newIdData, *xstIdData; if (newLink==NULL || xstLink==NULL) return 1; if (newLink->data==NULL || xstLink->data==NULL) return -1; newIdData = (cf_Branch *) newLink->data; xstIdData = (cf_Branch *) xstLink->data; if (newIdData->type[0]=='c') { /* common_mode_outage */ return ff_cmpName((cf_Name *) newIdData, (cf_Name *) xstIdData); } else if (newIdData->type[0]=='B') { /* bus u/o volt */ return ff_srtBus((pf_AC_bus *) newIdData, (pf_AC_bus *) xstIdData, sort); } else if (newIdData->type[0]=='s') { /* system problem */ return (newIdData->type[0] - xstIdData->type[0]); } else { /* branch outage or overloaded branch */ return ff_srtBranch((cf_Branch *) newIdData, (cf_Branch *) xstIdData, sort); } } int ff_srtBus(pf_AC_bus *b1, pf_AC_bus *b2, int sort) /* sort bus */ { int c; float d; if ( (c=strcmp(b1->type, b2->type)) != 0 ) return c; /* [type]-sort */ if (sort==5) return 1; /* [input order] */ if (sort==4) { /* [zone]-alpha-kv */ if ( (c=strcmp(b1->zone, b2->zone)) != 0 ) return c; } else if (sort==3) { /* [owner]-alpha-kv */ if ( (c=strcmp(b1->owner, b2->owner)) != 0 ) return c; } else if (sort==2) { /* [kv]-alpha-kv */ d = (b1->kv - b2->kv); if ( fabs(d) > .001 ) return d; } return cf_cmpBus(b1, b2); /* [alpha-kv] */ } int ff_srtByInput(Link *newRow, Link *xstRow, void *sort) { int type; int index1, index2; /* 1 - first Link, 2 - second Link (first Link->next) */ Link *newRowId, *list1, *list2, *newId1, *newId2, *xstId1, *xstId2; cf_Branch *newOutgData, *newProbData; Trace *trace; trace = (Trace *) sort; type = trace->rpt->type; if (type==TYPE_OUTG_OVLD || type==TYPE_OUTG_BUSV) { newRowId = (Link *) newRow->data; newOutgData = (cf_Branch *) newRowId->data; newProbData = (cf_Branch *) newRowId->next->data; list1 = (newOutgData->type[0]=='c') ? trace->comoList : trace->outgList; list2 = (newProbData->type[0]=='B') ? trace->busvList : trace->ovldList; } else if (type==TYPE_OVLD_OUTG || type==TYPE_BUSV_OUTG) { newRowId = (Link *) newRow->data; newProbData = (cf_Branch *) newRowId->data; newOutgData = (cf_Branch *) newRowId->next->data; list1 = (newProbData->type[0]=='B') ? trace->busvList : trace->ovldList; list2 = (newOutgData->type[0]=='c') ? trace->comoList : trace->outgList; } newId1 = (Link *) newRow->data; newId2 = (Link *) newId1->next; xstId1 = (Link *) xstRow->data; xstId2 = (Link *) xstId1->next; index1 = getIndex((Link *) newId1, (Link *) xstId1, list1); if (index1!=0) return index1; index2 = getIndex((Link *) newId2, (Link *) xstId2, list2); return index2; } int getIndex(Link *newLink, Link *xstLink, Link *list) /* determine which branch/bus comes first in the input list */ /* uses a start-at-beginning-and-search-whole-list approach */ { if (list==NULL) return ff_cmpID(newLink, xstLink); /* default [alpha-kv] */ if (ff_cmpID(newLink, xstLink)==0) return 0; /* newLink same as xstLink */ for (; list!=NULL; list=list->next) { if (ff_cmpID(list, newLink)==0) return -1; /* switching return values */ if (ff_cmpID(list, xstLink)==0) return 1; /* reverses the sort order */ } return 1; /* +1 & -1 seem to have same result for return value */ } void printReport(Trace *trace, cf_Out *rpt) { int i, doN, skipN, cmp; Link *curRow, *curID, *curSoln, *refID, *pfoPtr, *curPfo; if (rpt->type==TYPE_NONE) return; openReport(rpt); skipN = 0; curPfo = trace->pfoList; if (curPfo==NULL || trace->rptTable==NULL) { fprintf(rpt->file, "*** Warning: No Data Found! ***"); } for (pfoPtr=curPfo;curPfo!=NULL && trace->rptTable!=NULL;curPfo=pfoPtr) { for (doN=0; pfoPtr!=NULL && doN<rpt->wide; pfoPtr=pfoPtr->next) doN++; printHeader(rpt, curPfo); for (curRow = trace->rptTable; curRow != NULL; curRow=curRow->next) { if ( rpt->form!=FORM_DATA_FULL && rpt->line==0 ) printHeader(rpt, curPfo); curID = (Link *) curRow->data; curSoln = curID->next->next; for (i = skipN; curSoln!=NULL && i-- > 0; curSoln = curSoln->next); refID = (curRow->prev!=NULL) ? (Link *) curRow->prev->data : NULL; cmp = ff_cmpID(curID, refID); if (rpt->form==FORM_DATA_FULL || rpt->form==FORM_DATA_BREF || cmp) { printID(rpt, curID, 1); } if (rpt->form!=FORM_DATA_FULL && rpt->form!=FORM_DATA_BREF && cmp) { fprintf(rpt->file, "\n"); rpt->line++; } if (rpt->form==FORM_PAGE_WIDE) { printID(rpt, NULL, 1); } printID(rpt, curID->next, 2); chkBranch (trace, curID); /* deLink branches with overloads from No O/L Log */ printSoln(rpt, curID, curSoln, doN); refID = (curRow->next!=NULL) ? (Link *) curRow->next->data : NULL; cmp = ff_cmpID(curID, refID); if (rpt->form!=FORM_DATA_FULL && rpt->form!=FORM_DATA_BREF && cmp) { fprintf(rpt->file, "\n"); rpt->line++; } if (rpt->form!=FORM_DATA_FULL && rpt->form!=FORM_DATA_BREF) { pageFooter(rpt, curRow->next, pfoPtr); } } chkBranchLog (trace, curPfo); /* send No O/L Log to cf_logErr */ skipN += doN; } } void chkBranch(Trace *trace, Link *curID) /* deLink branches with overloads from No O/L Log */ { cf_Branch *ovldData, *chkBranchData; /* No O/L Log support */ Link *chkBranchStep, *chkBranchOvld; /* No O/L Log support */ chkBranchOvld = curID->next; ovldData = (cf_Branch *)chkBranchOvld->data; chkBranchStep = trace->chkBranchStart; /* dmstest */ while (chkBranchStep!=NULL) { chkBranchData = (cf_Branch *)chkBranchStep->data; if (ff_cmpID(chkBranchStep, chkBranchOvld) == 0) { chkBranchStep = cf_delLink(&trace->chkBranchStart, chkBranchStep); } else { chkBranchStep = chkBranchStep->next; } } return; } void chkBranchLog(Trace *trace, Link *curPfo) /* send No O/L Log to cf_logErr */ { int cmp; cf_Branch *ovldData, *chkBranchData; /* No O/L Log support */ Link *chkBranchStep, *chkBranchOvld; /* No O/L Log support */ chkBranchStep = trace->chkBranchStart; while (chkBranchStep!=NULL) { chkBranchData = (cf_Branch *)chkBranchStep->data; cf_logErr(" %9s %7.2f %9s %7.2f %c is not overloaded in %s\n", chkBranchData->bus1_name, chkBranchData->bus1_kv, chkBranchData->bus2_name, chkBranchData->bus2_kv, chkBranchData->ckt_id, curPfo->data); chkBranchStep = chkBranchStep->next; } return; } void printHeader(cf_Out *rpt, Link *curPfo) { if (rpt->type==TYPE_OUTG_OVLD) printOtBrHeader(rpt, curPfo); else if (rpt->type==TYPE_OUTG_BUSV) printOtBsHeader(rpt, curPfo); else if (rpt->type==TYPE_OVLD_OUTG) printOvldHeader(rpt, curPfo); else if (rpt->type==TYPE_BUSV_OUTG) printBusvHeader(rpt, curPfo); return; } void printID(cf_Out *rpt, Link *curID, int position) { if (rpt->type==TYPE_OUTG_OVLD) { if (position==1) printOutg(rpt->file, curID, rpt->form); if (position==2) printOvld(rpt->file, curID, rpt->form); } if (rpt->type==TYPE_OUTG_BUSV) { if (position==1) printOutg(rpt->file, curID, rpt->form); if (position==2) printBusv(rpt->file, curID, rpt->form); } if (rpt->type==TYPE_OVLD_OUTG) { if (position==1) printOvld(rpt->file, curID, rpt->form); if (position==2) printOutg(rpt->file, curID, rpt->form); } if (rpt->type==TYPE_BUSV_OUTG) { if (position==1) printBusv(rpt->file, curID, rpt->form); if (position==2) printOutg(rpt->file, curID, rpt->form); } } void printSoln(cf_Out *rpt, Link *curID, Link *curSoln, int doN) { cf_Name *data; if (rpt->type==TYPE_OUTG_OVLD) data = (cf_Name *) curID->next->data; else if (rpt->type==TYPE_OUTG_BUSV) data = (cf_Name *) curID->next->data; else if (rpt->type==TYPE_OVLD_OUTG) data = (cf_Name *) curID->data; else if (rpt->type==TYPE_BUSV_OUTG) data = (cf_Name *) curID->data; if (data->type[0]=='s') { printProb(rpt, curSoln, doN); } else if (rpt->type==TYPE_OUTG_OVLD || rpt->type==TYPE_OVLD_OUTG) { printLoad(rpt, curSoln, doN); } else if (rpt->type==TYPE_OUTG_BUSV || rpt->type==TYPE_BUSV_OUTG) { printVolt(rpt, curSoln, doN); } return; } void pageFooter(cf_Out *rpt, Link *nxRow, Link *nxPfo) { if (nxRow!=NULL) { ff_printPageFooter(rpt, 3); } else if (nxRow==NULL && nxPfo!=NULL) { ff_printPageFooter(rpt, 9); fprintf(rpt->file, "%s\n", DOT_LINE); rpt->line++; ff_printPageFooter(rpt, FF_PAGE_LENGTH); } else if (nxRow==NULL && nxPfo==NULL) { ff_printPageFooter(rpt, 10); tableLegend(rpt); ff_printPageFooter(rpt, FF_PAGE_LENGTH); } } int ff_printPageFooter(cf_Out *rpt, int m) /* Guarantee room for m lines before page break */ { int n; n = cf_cntchr(CF_PAGE_FOOTER, '\n'); rpt->line = Cf_imod(rpt->line, FF_PAGE_LENGTH); if ( (FF_PAGE_LENGTH - n - rpt->line) > m ) return 0; ff_printBlankLines(rpt, n); fprintf(rpt->file, CF_PAGE_FOOTER, rpt->time, rpt->page); rpt->line = Cf_imod(rpt->line + n, FF_PAGE_LENGTH); rpt->page++; return 1; } void ff_printBlankLines(cf_Out *rpt, int n) { while (rpt->line < FF_PAGE_LENGTH - n) { fprintf(rpt->file, "\n"); rpt->line++; } return; } void printOtBrHeader(cf_Out *rpt, Link *pfo) { /* COULD USE DEFINE STATEMENTS */ char *HdLd[] = { /* lead */ ".| |OUTAGES CAUSING OVERLOADS| | | | | | CASE NAME: -> | | | | | | |", ".| | | | | | | | | | | | | | |", ".| | Outaged Branches | | | | | | Overloaded Branches | | | | |CRTC|IN |", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|Z1|Z2|T|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|S|Z1|Z2|RATG|MYY|", " ", ".| |OUTAGES CAUSING OVERLOADS| | | | CASE NAME: -> | | |", ".| | | | | | | | |", ".| | Outaged Branches | | | | Overloaded Branches | |CRTC|", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|T|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|RATG|", " ", ".| |OUTAGES CAUSING OVERLOADS| | | | | | |", ".| | Outage followed by... | | | | | | |", ".| | ...List of Overloads | | | | |CRTC|IN |", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|S|Z1|Z2|RATG|MYY|", " ", }; char *HdRp[] = { /* repeat */ "%16.16s||||", " ||||", " PRE | POST |POST||", " LOAD | LOAD |(%)|F|", " ", "%4.4s||", " ||", "POST||", "(%)|F|", " ", }; char *HdDf[] = { /* difference */ "", "", "", "", "", " | |", "POST(%)|POST(%)|", "VARIANC|VARIANC|", " UP | DOWN |", " ", }; int lf, rf, df; if (rpt->form==FORM_PAGE_WIDE) lf = 0; if (rpt->form==FORM_DATA_FULL) lf = 0; if (rpt->form==FORM_DATA_BREF) lf = 5; if (rpt->form==FORM_PAGE_COMP) lf = 10; rf = (rpt->form==FORM_DATA_BREF) ? 5 : 0; df = (rpt->diff==VARI_YES) ? 5 : 0; printTableCases(rpt, pfo, HdLd[0+lf], HdRp[0+rf], HdDf[0+df]); printTableHeader(rpt, pfo, HdLd[1+lf], HdRp[1+rf], HdDf[1+df]); printTableHeader(rpt, pfo, HdLd[2+lf], HdRp[2+rf], HdDf[2+df]); printTableHeader(rpt, pfo, HdLd[3+lf], HdRp[3+rf], HdDf[3+df]); printTableHeader(rpt, pfo, HdLd[4+lf], HdRp[4+rf], HdDf[4+df]); rpt->line += 5; return; } void printOtBsHeader(cf_Out *rpt, Link *pfo) { char *HdLd[] = { /* lead */ ".| |OUTAGE CAUSING UO VOLTAGE| | | | | |CASE NAME:->| | | |", ".| | | | | | | | | |LOWER|UPPER|", ".| | Outaged Branch | | | | | |U/O Voltage| |LIMIT|LIMIT|", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|Z1|Z2|T|OWN|< BUS1 ><V1>|ZN|( PU)|( PU)|", " ", ".| |OUTAGE CAUSING UO VOLTAGE| | | |CASE NAME:->| |", ".| | | | | | | |", ".| | Outaged Branch | | | |U/O Voltage| |", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|T|OWN|< BUS1 ><V1>|ZN|", " ", ".| |OUTAGE CAUSING UO VOLTAGE| | | | | | |", ".| | Outage followed by... | | | | |LOWER|UPPER|", ".| | ...List of Busses | | | | |LIMIT|LIMIT|", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|S|Z1|Z2|( PU)|( PU)|", " ", }; char *HdRp[] = { /* repeat */ "%16.16s|||", " |||", "ACTUA|ACTUA|CHANGE|", "( KV)|( PU)|( PU )|", " ", "%5.5s|", " |", "ACTUA|", "( PU)|", " ", }; char *HdDf[] = { /* difference */ "", "", "", "", "", " | |", "VARIANC|VARIANC|", " UP | DOWN |", "( PU )|( PU )|", " ", }; int lf, rf, df; if (rpt->form==FORM_PAGE_WIDE) lf = 0; if (rpt->form==FORM_DATA_FULL) lf = 0; if (rpt->form==FORM_DATA_BREF) lf = 5; if (rpt->form==FORM_PAGE_COMP) lf = 10; rf = (rpt->form==FORM_DATA_BREF) ? 5 : 0; df = (rpt->diff==VARI_YES) ? 5 : 0; printTableCases(rpt, pfo, HdLd[0+lf], HdRp[0+rf], HdDf[0+df]); printTableHeader(rpt, pfo, HdLd[1+lf], HdRp[1+rf], HdDf[1+df]); printTableHeader(rpt, pfo, HdLd[2+lf], HdRp[2+rf], HdDf[2+df]); printTableHeader(rpt, pfo, HdLd[3+lf], HdRp[3+rf], HdDf[3+df]); printTableHeader(rpt, pfo, HdLd[4+lf], HdRp[4+rf], HdDf[4+df]); rpt->line += 5; return; } void printOvldHeader(cf_Out *rpt, Link *pfo) { /* COULD USE DEFINE STATEMENTS */ char *HdLd[] = { /* lead */ ".| |OVERLOAD CAUSED BY OUTAGE| | | | | | | CASE NAME: -> | | | | | |", ".| | | | | | | | | | | | | | |", ".| | Overloaded Branches | | | | | | | Outaged Branches | | | |CRTC|IN |", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|S|Z1|Z2|T|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|Z1|Z2|RATG|MYY|", " ", ".| |OVERLOAD CAUSED BY OUTAGE| | | | CASE NAME: -> | | |", ".| | | | | | | | |", ".| | Overloaded Branches | | | | Outaged Branches | |CRTC|", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|T|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|RATG|", " ", ".| |OVERLOAD CAUSED BY OUTAGE| | | | | | |", ".| | Overload followed by... | | | | | | |", ".| | ...List of Outages | | | | |CRTC|IN |", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|S|Z1|Z2|RATG|MYY|", " ", }; char *HdRp[] = { /* repeat */ "%16.16s||||", " ||||", " PRE | POST |POST||", " LOAD | LOAD |(%)|F|", " ", "%4.4s||", " ||", "POST||", "(%)|F|", " ", }; char *HdDf[] = { /* difference */ "", "", "", "", "", " | |", "POST(%)|POST(%)|", "VARIANC|VARIANC|", " UP | DOWN |", " ", }; int lf, rf, df; if (rpt->form==FORM_PAGE_WIDE) lf = 0; if (rpt->form==FORM_DATA_FULL) lf = 0; if (rpt->form==FORM_DATA_BREF) lf = 5; if (rpt->form==FORM_PAGE_COMP) lf = 10; rf = (rpt->form==FORM_DATA_BREF) ? 5 : 0; df = (rpt->diff==VARI_YES) ? 5 : 0; printTableCases(rpt, pfo, HdLd[0+lf], HdRp[0+rf], HdDf[0+df]); printTableHeader(rpt, pfo, HdLd[1+lf], HdRp[1+rf], HdDf[1+df]); printTableHeader(rpt, pfo, HdLd[2+lf], HdRp[2+rf], HdDf[2+df]); printTableHeader(rpt, pfo, HdLd[3+lf], HdRp[3+rf], HdDf[3+df]); printTableHeader(rpt, pfo, HdLd[4+lf], HdRp[4+rf], HdDf[4+df]); rpt->line += 5; return; } void printBusvHeader(cf_Out *rpt, Link *pfo) { /* COULD USE DEFINE STATEMENTS */ char *HdLd[] = { /* lead */ ".| |U/O VOLT DUE| | | | CASE NAME: -> | | | | | |", ".| | TO OUTAGE | | | | | | | |LOWER|UPPER|", ".| |U/O Voltage| | | | Outaged Branches | | | |LIMIT|LIMIT|", ".|OWN|< BUS1 ><V1>|ZN|T|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|Z1|Z2|( PU)|( PU)|", " ", ".| |U/O VOLT DUE| | | | CASE NAME: -> | |", ".| | TO OUTAGE | | | | | |", ".| |U/O Voltage| | | | Outaged Branches | |", ".|OWN|< BUS1 ><V1>|ZN|T|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|", " ", ".| |U/O VOLTAGE DUE TO OUTAGE| | | | | | |", ".| | Bus followed by... | | | | |LOWER|UPPER|", ".| | ...List of Outages | | | | |LIMIT|LIMIT|", ".|OWN|< BUS1 ><V1> < BUS2 ><V2>|C|S|Z1|Z2|( PU)|( PU)|", " ", }; char *HdRp[] = { /* repeat */ "%16.16s|||", " |||", "ACTUA|ACTUA|CHANGE|", "( KV)|( PU)|( PU )|", " ", "%5.5s|", " |", "ACTUA|", "( PU)|", " ", }; char *HdDf[] = { /* difference */ "", "", "", "", "", " | |", "VARIANC|VARIANC|", " UP | DOWN |", "( PU )|( PU )|", " ", }; int lf, rf, df; if (rpt->form==FORM_PAGE_WIDE) lf = 0; if (rpt->form==FORM_DATA_FULL) lf = 0; if (rpt->form==FORM_DATA_BREF) lf = 5; if (rpt->form==FORM_PAGE_COMP) lf = 10; rf = (rpt->form==FORM_DATA_BREF) ? 5 : 0; df = (rpt->diff==VARI_YES) ? 5 : 0; printTableCases(rpt, pfo, HdLd[0+lf], HdRp[0+rf], HdDf[0+df]); printTableHeader(rpt, pfo, HdLd[1+lf], HdRp[1+rf], HdDf[1+df]); printTableHeader(rpt, pfo, HdLd[2+lf], HdRp[2+rf], HdDf[2+df]); printTableHeader(rpt, pfo, HdLd[3+lf], HdRp[3+rf], HdDf[3+df]); printTableHeader(rpt, pfo, HdLd[4+lf], HdRp[4+rf], HdDf[4+df]); rpt->line += 5; return; } void printTableCases(cf_Out *rpt, Link *curPfo, char *l, char *r, char *d) { int width; fprintf(rpt->file, "%s", l); for (width=rpt->wide; curPfo!=NULL && width-- > 0; curPfo=curPfo->next) { fprintf(rpt->file, r, curPfo->data); /* case name */ } fprintf(rpt->file, "%s", d); fprintf(rpt->file, "\n"); } void printTableHeader(cf_Out *rpt, Link *curPfo, char *l, char *r, char *d) { int width; fprintf(rpt->file, "%s", l); /* lead */ for (width=rpt->wide; curPfo!=NULL && width-- > 0; curPfo=curPfo->next) { fprintf(rpt->file, "%s", r); /* repeat */ } fprintf(rpt->file, "%s", d); /* difference */ fprintf(rpt->file, "\n"); } void printOutg(FILE *fp, Link *outgLink, int form) { char id[CF_STRSIZE], out[CF_STRSIZE]; pf_rec d; cf_Branch *outgData; cf_Name *comoData; outgData = (outgLink!=NULL) ? (cf_Branch *) outgLink->data : NULL; if (outgData==NULL || outgLink==NULL) { if (form==FORM_PAGE_COMP) sprintf(out, "%41.41s|", ""); else if (form==FORM_DATA_BREF) sprintf(out, "%32.32s|", ""); else sprintf(out, "%39.39s|", ""); } else if (outgData->type[0]!='c') { cf_branch2rec(outgData, &d); pf_rec_b2a(id, &d, "I"); if (form==FORM_PAGE_COMP) sprintf(out, "%-1.1s|%-3.3s|%-12.12s %-12.12s|%1.1s| |%-2.2s|%-2.2s|", &id[0], &id[3], &id[6], &id[19], &id[31], outgData->bus1_zone, outgData->bus2_zone); else if (form==FORM_DATA_BREF) sprintf(out, "%-1.1s|%-3.3s|%-12.12s %-12.12s|%1.1s|", &id[0], &id[3], &id[6], &id[19], &id[31]); else sprintf(out, "%-1.1s|%-3.3s|%-12.12s %-12.12s|%1.1s|%-2.2s|%-2.2s|", &id[0], &id[3], &id[6], &id[19], &id[31], outgData->bus1_zone, outgData->bus2_zone); } else if (outgData->type[0]=='c') { /* common mode */ comoData = (cf_Name *) outgData; if (form==FORM_PAGE_COMP) sprintf(out,"%-35.35s|||||||",comoData->name); else if (form==FORM_DATA_BREF) sprintf(out,"%-30.30s||||", comoData->name); else sprintf(out,"%-34.34s||||||", comoData->name); } fprintf(fp, "%s", out); } void printOvld(FILE *fp, Link *ovldLink, int form) { char id[CF_STRSIZE], out[CF_STRSIZE]; pf_rec d; cf_Branch *ovldData; ovldData = (ovldLink!=NULL) ? (cf_Branch *) ovldLink->data : NULL; if (ovldData==NULL || ovldLink==NULL) { if (form==FORM_DATA_BREF) sprintf(out, "%32.32s|", ""); else sprintf(out, "%41.41s|", ""); } else if (ovldData->type[0]!='s') { cf_branch2rec(ovldData, &d); pf_rec_b2a(id, &d, "I"); if (form==FORM_DATA_BREF) sprintf(out, "%-1.1s|%-3.3s|%-12.12s %-12.12s|%1.1s|", &id[0], &id[3], &id[6], &id[19], &id[31]); else sprintf(out, "%-1.1s|%-3.3s|%-12.12s %-12.12s|%1.1s|%1.1s|%-2.2s|%-2.2s|", &id[0], &id[3], &id[6], &id[19], &id[31], &id[32], ovldData->bus1_zone, ovldData->bus2_zone); } else if (ovldData->type[0]=='s') { if (form==FORM_DATA_BREF) sprintf(out, " SOLUTION PROBLEMS ||||"); else sprintf(out, " SOLUTION PROBLEMS |||||||"); } fprintf(fp, "%s", out); } void printBusv(FILE *fp, Link *busvLink, int form) { char id[CF_STRSIZE], out[CF_STRSIZE]; pf_rec d; cf_Bus *busvData; busvData = (busvLink!=NULL) ? (cf_Bus *) busvLink->data : NULL; if (busvData==NULL || busvLink==NULL) { if (form==FORM_DATA_BREF) sprintf(out, "%21.21s|", ""); else sprintf(out, "%21.21s|", ""); } else if (busvData->type[0]=='s') { if (form==FORM_PAGE_COMP) /* compact sparse */ sprintf(out, " SOLUTION PROBLEMS |||||||"); else if (form==FORM_DATA_BREF) sprintf(out," SOLUTION PROBLEMS||||"); else sprintf(out," SOLUTION PROBLEMS||||"); } else if (busvData->type[0]!='s') { memset(&d, '\0', sizeof(pf_rec)); memcpy(&d, busvData, sizeof(cf_Bus)); pf_rec_b2a(id, &d, "I"); if (form==FORM_PAGE_COMP) /* compact sparse */ sprintf(out, "%-1.1s|%-3.3s|%-12.12s %-12.12s|%1.1s| |%-2.2s|%-2.2s|", &id[0], &id[3], &id[6], "", "", &id[18], ""); else if (form==FORM_DATA_BREF) sprintf(out, "%-1.1s|%-3.3s|%-12.12s|%-2.2s|", &id[0], &id[3], &id[6], &id[18]); else sprintf(out, "%-1.1s|%-3.3s|%-12.12s|%-2.2s|", &id[0], &id[3], &id[6], &id[18]); } fprintf(fp, "%s", out); } void printDiff(cf_Out *rpt, Link *solnLink, int mode) { ff_soln *varData; while (solnLink!=NULL && solnLink->next!=NULL) solnLink = solnLink->next; if (mode==0 || solnLink==NULL || solnLink->data==NULL) { fprintf(rpt->file, " | |"); } else { varData = (ff_soln *) solnLink->data; if (mode==1) { fprintf(rpt->file, "%7.1f|%7.1f|", varData->max_new, varData->min_ref); } if (mode==2) { fprintf(rpt->file, "%7.3f|%7.3f|", varData->max_new, varData->min_ref); } } return; } void printLoad(cf_Out *rpt, Link *solnLink, int doN) { Link *curLink, *refLink; ff_soln *curSoln, *refSoln; char code; refLink=solnLink; /* find first valid data for CRITCL RATING */ for (; refLink!=NULL && refLink->data==NULL; refLink=refLink->next); if (refLink!=NULL && refLink->data!=NULL) { refSoln = (ff_soln *) refLink->data; if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, "%4.0f|", refSoln->max_new); else fprintf(rpt->file, "%4.0f|%3.3s|",refSoln->max_new,refSoln->date); } else fprintf(rpt->file, " | |"); for (curLink = solnLink; curLink!=NULL; curLink=curLink->next) { if (doN-- <= 0) break; if (curLink->data==NULL) { if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, " | |"); else fprintf(rpt->file, " | | | |"); } else { curSoln = (ff_soln *) curLink->data; code = curSoln->code; if (refLink->data!=NULL && curSoln->max_new != refSoln->max_new) { code = tolower(curSoln->code); } if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, "%3.0f|%1.1s|", curSoln->ratio, &code); else { if ((int)curSoln->pre_con == -9999) /* no pre_con data found */ fprintf(rpt->file, " |%6.1f|%3.0f|%1.1s|", curSoln->actual, curSoln->ratio, &code); else fprintf(rpt->file, "%6.1f|%6.1f|%3.0f|%1.1s|", curSoln->pre_con, curSoln->actual, curSoln->ratio, &code); } } } while (doN-- > 0) { if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, " | |"); else fprintf(rpt->file, " | | | |"); } if (rpt->diff==VARI_YES) printDiff(rpt, solnLink, 1); fprintf(rpt->file, "\n"); rpt->line += 1; return; } void printVolt(cf_Out *rpt, Link *solnLink, int doN) { Link *curLink, *refLink; ff_soln *curSoln, *refSoln; refLink=solnLink; /* find LIMITS */ for (; refLink!=NULL && refLink->data==NULL; refLink=refLink->next); if (refLink!=NULL && refLink->data!=NULL) { refSoln = (ff_soln *) refLink->data; if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, ""); else fprintf(rpt->file, "%5.3f|%5.3f|",refSoln->min_ref, refSoln->max_new); } else { if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, ""); else fprintf(rpt->file, " | | |"); } for (curLink = solnLink; curLink!=NULL; curLink=curLink->next) { if (doN-- <= 0) break; if (curLink->data==NULL) { if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, " |"); else fprintf(rpt->file, " | | |"); } else { curSoln = (ff_soln *) curLink->data; if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, "%5.3f|", curSoln->ratio); else { if ((int)curSoln->pre_con == -9999) /* no change data found */ fprintf(rpt->file,"%5.1f|%5.3f| |", curSoln->actual, curSoln->ratio); else fprintf(rpt->file,"%5.1f|%5.3f|%6.3f|", curSoln->actual, curSoln->ratio, curSoln->pre_con); } } } while (doN-- > 0) { if (rpt->form==FORM_DATA_BREF) fprintf(rpt->file, " |"); else fprintf(rpt->file, " | | |"); } if (rpt->diff==VARI_YES) printDiff(rpt, solnLink, 2); fprintf(rpt->file, "\n"); rpt->line += 1; return; } void printProb(cf_Out *rpt, Link *probLink, int doN) { char *Problem[] = { " | |", /* overload report; blank rating, blank in-date */ " |||", /* overload report; blank solution problem */ " %11.11s|||", /* overload report; format for probData->name */ " | |", /* bus violation; blank lower-, upper-limit */ " ||", /* bus violation; blank solution problem */ " %11.11s||", /* bus violation; format for probData->name */ " |", /* overload report; blank rating, blank code */ " ||", /* overload report; blank solution problem */ "%4.4s||", /* overload report; format for probData->name */ "", /* bus violation; blank lower-, upper-limit */ " |", /* bus violation; blank solution problem */ "%5.5s|", /* bus violation; format for probData->name */ }; int offset; Link *curProb; ff_soln *probData; char descrip[11]; offset=(rpt->type==TYPE_OUTG_OVLD || rpt->type==TYPE_OVLD_OUTG) ? 0:3; offset += (rpt->form==FORM_DATA_BREF) ? 6 : 0; fprintf(rpt->file, Problem[0+offset]); for (curProb = probLink; curProb!=NULL; curProb=curProb->next) { if (doN-- <= 0) break; probData = (ff_soln *) curProb->data; if (probData==NULL) fprintf(rpt->file, Problem[1+offset]); else { if (rpt->form!=FORM_DATA_BREF) { if (probData->code=='F') strcpy(descrip, "NO SOLUTION"); else if (probData->code=='X') strcpy(descrip, "FAILED RX "); else if (probData->code=='S') strcpy(descrip, "SEPARATION "); else if (probData->code=='K') strcpy(descrip, "SOLUTION OK"); else strcpy(descrip, "UNKNOWN "); } else { if (probData->code=='F') strcpy(descrip, "FAIL"); else if (probData->code=='X') strcpy(descrip, " RX "); else if (probData->code=='S') strcpy(descrip, "SEPA"); else if (probData->code=='K') strcpy(descrip, " OK "); else strcpy(descrip, " ?? "); } fprintf(rpt->file, Problem[2+offset], descrip); } } while (doN-- > 0) fprintf(rpt->file, Problem[1+offset]); if (rpt->diff==VARI_YES) printDiff(rpt, probLink, 0); fprintf(rpt->file, "\n"); rpt->line += 1; return; } int validSoln(Link *solnLink) { ff_soln *solnData; while (solnLink!=NULL) { solnData = (ff_soln *) solnLink->data; if (solnData!=NULL) { if ( solnData->code != 'S' ) return 1; /* keep if solution failed for other than a separation */ } solnLink = solnLink->next; } return 0; } int validInput(Link *listPtr, cf_Branch *data) { /* uses a start-at-beginning-and-search-whole-list approach */ cf_Branch *listData; int cmp; if (listPtr==NULL) return -1; for (cmp=1; listPtr!=NULL; listPtr=listPtr->next) { listData = (cf_Branch *) listPtr->data; if (listData->type[0] != data->type[0]) continue; if (data->type[0]=='c') { /* common-mode outages */ cmp = ff_cmpName((cf_Name *) listData, (cf_Name *) data); } else if (data->type[0]=='B') { /* buses */ cmp = cf_cmpBus( (pf_AC_bus *) listData, (pf_AC_bus *) data ); } else { /* branch outages and overloads */ cmp = ff_wildBranch( (pf_branch *) listData, (pf_branch *) data ); } if (cmp==0) return 1; } return 0; } int validVariance(Trace trace, Link *refLink) /* return 1 if difference with problem solving, or variation exceeds span */ { Link *variLink, *solnLink; ff_soln *refData, *solnData, *variData; float refRat, solRat, solMax, solMin, varUp, varDown, varSpan; int refCode, solCode; refData = (refLink==NULL) ? NULL : (ff_soln *) refLink->data; refCode = (refData==NULL) ? ' ' : ((ff_soln *) refLink->data)->code; /* the following loop returns 1 (valid) if not all the cases have data or if they failed to solve for different reasons */ for (solnLink=refLink->next; solnLink!=NULL; solnLink=solnLink->next) { solCode = (solnLink->data!=NULL) ? ((ff_soln *)solnLink->data)->code : ' '; if ((refCode=='S')|(refCode=='X')|(refCode=='F')|(refCode=='K')) { if (refCode!=solCode) return 1; } } refRat = (refData==NULL) ? 0 : refData->ratio; solMax = refRat; solMin = refRat; for (solnLink=refLink->next; solnLink!=NULL; solnLink=solnLink->next) { solnData = (ff_soln *)solnLink->data; solRat = (solnData==NULL) ? 0 : solnData->ratio; solMax = Cf_max(solMax, solRat); solMin = Cf_min(solMin, solRat); } varUp = solMax - refRat; /* i.e. 3% = 101% - 98% */ varDown = solMin - refRat; /* i.e. -5% = 93% - 98% */ varSpan = varUp - varDown; if (refData==NULL) { varUp = varDown = varSpan = 0; } variLink = cf_newLink(sizeof(ff_soln)); cf_appList(&refLink, variLink); variData = (ff_soln *) variLink->data; variData->min_ref = varDown; variData->max_new = varUp; variData->actual = varSpan; variData->ratio = (varUp > -1*varDown) ? varUp : varDown; variData->code = ' '; if (varUp<trace.varCeiling && varDown>trace.varFloor) return 0; return 1; } int validLoad(Trace trace, Link *solnLink) { ff_soln *solnData; while (solnLink!=NULL) { solnData = (ff_soln *) solnLink->data; if (solnData!=NULL && solnData->ratio >= trace.minLoadPct) return 1; solnLink = solnLink->next; } return 0; } int validVolt(Trace trace, Link *solnLink) { ff_soln *solnData; float vpu, basekv; cf_Bus *busvData; if (solnLink==NULL || solnLink->prev==NULL || solnLink->prev->data==NULL) return 0; busvData = (cf_Bus *) solnLink->prev->data; basekv = busvData->kv; for (; solnLink!=NULL; solnLink = solnLink->next) { if ( (solnData = (ff_soln *) solnLink->data) == NULL ) continue; vpu = solnData->ratio; if ((int)basekv==500 && (vpu>=trace.max5 || vpu<=trace.min5)) return 1; else if ((int)basekv!=500 && (vpu>=trace.maxV || vpu<=trace.minV)) return 1; } return 0; } int ff_wildBranch(pf_branch *b1, pf_branch *b2) /******************************************************************************\ * ff_wildBranch: compare id data of two pf_branch records with wild card. * pf_branch *b1 - ptr to branch rec. with optional wild card ckt_id and section. * pf_branch *b2 - pointer to branch record. * returns: int - 0 if same, 1 if b1 > b2, -1 if b1 < b2. * developed by: WDRogers created: 08-22-96 \******************************************************************************/ { float c; if ( c=strncmp(b1->type, b2->type, 1) ) return c>0 ? 1 : -1; if ( c=strcmp(b1->bus1_name, b2->bus1_name) ) return c>0 ? 1 : -1; if ( fabs(c=b1->bus1_kv-b2->bus1_kv) > .001 ) return c>0 ? 1 : -1; if ( c=strcmp(b1->bus2_name, b2->bus2_name) ) return c>0 ? 1 : -1; if ( fabs(c=b1->bus2_kv-b2->bus2_kv) > .001 ) return c>0 ? 1 : -1; if ( b1->ckt_id != ' ' ) { /* if blank, accept any ckt_id */ if ( c=b1->ckt_id - b2->ckt_id ) return c>0 ? 1 : -1; } if ( b1->section != 0 ) { /* if zero, accept any section */ if ( c=b1->section - b2->section ) return c>0 ? 1 : -1; } return 0; } /* hash: form hash value for string s */ unsigned hash(char *s) { unsigned hashval; for (hashval = 0; *s != '\0'; s++) hashval = *s + 31 * hashval; return hashval % HASHSIZE; } /* lookup: look for s in hashtab */ struct nlist *lookup(char *s) { struct nlist *np; for (np = hashtab[hash(s)]; np != NULL; np = np->next) if (strcmp(s, np->name) == 0) return np; /* found */ return NULL; /* not found */ } /* install: put (name, keep) in hash tab */ struct nlist *install(char *name, int keep) { struct nlist *np; unsigned hashval; if ((np = lookup(name)) == NULL) { /* not found */ np = (struct nlist *) malloc(sizeof(*np)); if (np == NULL || (np->name = cf_strdup(name)) == NULL) return NULL; hashval = hash(name); np->next = hashtab[hashval]; hashtab[hashval] = np; } np->keep = keep; return np; } void ff_stream2List(FILE *readMe, Trace *trace, Link **expList) { char str[CF_INBUFSIZE], STR[CF_INBUFSIZE]; Link *list; int mode = READ_INC; /* default /INCLUDE */ while (fgets(str, CF_INBUFSIZE, readMe)!=NULL) { fprintf (stderr, " %5d %5d [%s]\n", entry, ++count, str); if (count > 6545) { fprintf (stderr, "ff_stream2List: Processing record # %10d\n", count); } if ( cf_iscomment(str) ) continue; strcpy(STR, str); cf_str2upper(STR); if ( strstr(STR, "/INCLUDE" )!=NULL ) { mode = READ_INC; continue; } if ( strstr(STR, "/PFO" )!=NULL ) { mode = READ_PFO; continue; } if ( strstr(STR, "/OUTAGE" )!=NULL ) { mode = READ_OUT; continue; } if ( strstr(STR, "/COMMON_MODE" )!=NULL ) { mode = READ_COM; continue; } if ( strstr(STR, "/OVERLOAD" )!=NULL ) { mode = READ_OVR; continue; } if ( strstr(STR, "/BUS" )!=NULL ) { mode = READ_BUS; continue; } if ( strstr(STR, "/OUTG_OWNER" )!=NULL ) { mode = READ_OWN; continue; } if ( strstr(STR, "/OUTG_ZONE" )!=NULL ) { mode = READ_ZON; continue; } if ( strstr(STR, "/OUTG_BASE_KV")!=NULL ) { mode = READ_BKV; continue; } if ( strstr(STR, "/PROB_OWNER" )!=NULL ) { mode = READ_OWP; continue; } if ( strstr(STR, "/PROB_ZONE" )!=NULL ) { mode = READ_ZNP; continue; } if ( strstr(STR, "/PROB_BASE_KV")!=NULL ) { mode = READ_KVP; continue; } if ( strstr(STR, "/LIMITS" )!=NULL ) { mode = READ_LIM; continue; } if ( strstr(STR, "/REPORT" )!=NULL ) { mode = READ_REP; continue; } if ( STR[0]=='/' ) { mode = 0; continue; } /* unrecognized slash card */ if ( mode == 0 ) continue; /* note: mode is defaulted to READ_INC */ if ( mode == READ_INC ) { list = cf_text2List(str); ff_expList(trace, list, expList); } if ( mode == READ_PFO ) { list = cf_text2List(str); cf_appList(&trace->pfoList, list); if (list!=NULL) trace->query &= ~(QUERY_PFO); } if ( mode == READ_OUT ) { if (strchr(STR, FF_WILD)==NULL) { list = cf_id2Link(STR, 'L'); cf_appList(&trace->outgList, list); } else { list = cf_text2Link(STR); cf_appList(&trace->outgMask, list); } if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OUTG); if (list!=NULL) trace->query &= ~(QUERY_COMO); if (list!=NULL) trace->query &= ~(QUERY_ZONE); if (list!=NULL) trace->query &= ~(QUERY_OWNR); if (list!=NULL) trace->query &= ~(QUERY_BSKV); } if ( mode == READ_COM ) { if (strchr(STR, FF_WILD)==NULL) { list = getCoMoOutg(STR); cf_appList(&trace->comoList, list); } else { list = cf_text2Link(STR); cf_appList(&trace->comoMask, list); } if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OUTG); if (list!=NULL) trace->query &= ~(QUERY_COMO); if (list!=NULL) trace->query &= ~(QUERY_ZONE); if (list!=NULL) trace->query &= ~(QUERY_OWNR); if (list!=NULL) trace->query &= ~(QUERY_BSKV); } if ( mode == READ_OVR ) { if (strchr(STR, FF_WILD)==NULL) { list = cf_id2Link(STR, 'L'); cf_appList(&trace->ovldList, list); } else { list = cf_text2Link(STR); cf_appList(&trace->ovldMask, list); } if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OVLD); if (list!=NULL) trace->query &= ~(QUERY_BUSV); if (list!=NULL) trace->query &= ~(QUERY_ZN_P); if (list!=NULL) trace->query &= ~(QUERY_OW_P); if (list!=NULL) trace->query &= ~(QUERY_KV_P); } if ( mode == READ_BUS ) { if (strchr(STR, FF_WILD)==NULL) { list = cf_id2Link(STR, 'I'); cf_appList(&trace->busvList, list); } else { list = cf_text2Link(STR); cf_appList(&trace->busvMask, list); } if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OVLD); if (list!=NULL) trace->query &= ~(QUERY_BUSV); if (list!=NULL) trace->query &= ~(QUERY_ZN_P); if (list!=NULL) trace->query &= ~(QUERY_OW_P); if (list!=NULL) trace->query &= ~(QUERY_KV_P); } if ( mode == READ_OWN ) { list = cf_text2List(STR); if (list!=NULL) trace->query &= ~(QUERY_OWNR); if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OUTG); if (list!=NULL) trace->query &= ~(QUERY_COMO); cf_appList(&trace->ownrOutg, list); } if ( mode == READ_ZON ) { list = cf_text2List(STR); if (list!=NULL) trace->query &= ~(QUERY_ZONE); if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OUTG); if (list!=NULL) trace->query &= ~(QUERY_COMO); cf_appList(&trace->zoneOutg, list); } if ( mode == READ_BKV ) { list = cf_text2List(STR); if (list!=NULL) trace->query &= ~(QUERY_BSKV); if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OUTG); if (list!=NULL) trace->query &= ~(QUERY_COMO); cf_appList(&trace->bskvOutg, list); } if ( mode == READ_OWP ) { list = cf_text2List(STR); if (list!=NULL) trace->query &= ~(QUERY_OW_P); if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OVLD); if (list!=NULL) trace->query &= ~(QUERY_BUSV); cf_appList(&trace->ownrProb, list); } if ( mode == READ_ZNP ) { list = cf_text2List(STR); if (list!=NULL) trace->query &= ~(QUERY_ZN_P); if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OVLD); if (list!=NULL) trace->query &= ~(QUERY_BUSV); cf_appList(&trace->zoneProb, list); } if ( mode == READ_KVP ) { list = cf_text2List(STR); if (list!=NULL) trace->query &= ~(QUERY_KV_P); if (list!=NULL) trace->query &= ~(QUERY_DATA); if (list!=NULL) trace->query &= ~(QUERY_OVLD); if (list!=NULL) trace->query &= ~(QUERY_BUSV); cf_appList(&trace->bskvProb, list); } if ( mode == READ_LIM ) ff_limits(STR, trace); if ( mode == READ_REP ) ff_report(str, trace); } return; } void ff_limits(char *s, Trace *trace) { float f; if (strstr(s, "VARIANCE_CEILING")!=NULL) { sscanf(s, "%*s = %f", &f); trace->varCeiling = f; trace->query &= ~(QUERY_SPAN); } if (strstr(s, "VARIANCE_FLOOR")!=NULL) { sscanf(s, "%*s = %f", &f); trace->varFloor = f; trace->query &= ~(QUERY_SPAN); } if (strstr(s, "MIN_LOAD_PCT")!=NULL) { sscanf(s, "%*s = %f", &f); trace->minLoadPct = f; trace->query &= ~(QUERY_LOAD); } if (strstr(s, "MAX_500_PU")!=NULL) { sscanf(s, "%*s = %f", &f); trace->max5 = f; trace->query &= ~(QUERY_VOLT); } if (strstr(s, "MIN_500_PU")!=NULL) { sscanf(s, "%*s = %f", &f); trace->min5 = f; trace->query &= ~(QUERY_VOLT); } if (strstr(s, "MAX_BUS_PU")!=NULL) { sscanf(s, "%*s = %f", &f); trace->maxV = f; trace->query &= ~(QUERY_VOLT); } if (strstr(s, "MIN_BUS_PU")!=NULL) { sscanf(s, "%*s = %f", &f); trace->minV = f; trace->query &= ~(QUERY_VOLT); } if (strstr(s, "INC_SOLN_PROB")!=NULL) { if (strstr(s, "NO" )!=NULL) trace->soln = SKP_SOLN_PROB; if (strstr(s, "YES")!=NULL) trace->soln = INC_SOLN_PROB; trace->query &= ~(QUERY_SOLN); } } void ff_report(char *s, Trace *trace) { if (strstr(s, "NAME" )!=NULL) { sscanf(s, "%*s = %s", trace->outName); trace->query &= ~(QUERY_NAME); return; } if (strstr(s, "TYPE" )!=NULL) { if (strstr(s, "OUTAGE-OVERLOAD" )!=NULL) trace->type = TYPE_OUTG_OVLD; if (strstr(s, "OVERLOAD-OUTAGE" )!=NULL) trace->type = TYPE_OVLD_OUTG; if (strstr(s, "OVERLOAD-BOTH" )!=NULL) trace->type = TYPE_OVLD_BOTH; if (strstr(s, "OUTAGE-BUS_V" )!=NULL) trace->type = TYPE_OUTG_BUSV; if (strstr(s, "BUS_V-OUTAGE" )!=NULL) trace->type = TYPE_BUSV_OUTG; if (strstr(s, "BUS_V-BOTH" )!=NULL) trace->type = TYPE_BUSV_BOTH; if (trace->type==TYPE_OUTG_OVLD) trace->query &= ~(QUERY_BUSV | QUERY_VOLT); if (trace->type==TYPE_OVLD_OUTG) trace->query &= ~(QUERY_BUSV | QUERY_VOLT); if (trace->type==TYPE_OVLD_BOTH) trace->query &= ~(QUERY_BUSV | QUERY_VOLT); if (trace->type==TYPE_OUTG_BUSV) trace->query &= ~(QUERY_OVLD | QUERY_LOAD); if (trace->type==TYPE_BUSV_OUTG) trace->query &= ~(QUERY_OVLD | QUERY_LOAD); if (trace->type==TYPE_BUSV_BOTH) trace->query &= ~(QUERY_OVLD | QUERY_LOAD); trace->query &= ~(QUERY_TYPE); return; } if (strstr(s, "CASES_PER_TABLE")!=NULL) { sscanf(s, "%*s = %d", &trace->trc->wide); if (trace->trc->wide<=0) trace->trc->wide = 1; trace->query &= ~(QUERY_WDTH); } if (strstr(s, "FORMAT" )!=NULL) { if (strstr(s, "DATA" )!=NULL) trace->trc->form = FORM_DATA_FULL; /* default */ if (strstr(s, "BRIEF")!=NULL) trace->trc->form = FORM_DATA_BREF; /* modifier */ if (strstr(s, "PAGE" )!=NULL) trace->trc->form = FORM_PAGE_WIDE; /* default */ if (strstr(s, "COMP" )!=NULL) trace->trc->form = FORM_PAGE_COMP; /* modifier */ trace->query &= ~(QUERY_FORM); } if (strstr(s, "SORT" )!=NULL) { if (strstr(s, "ALPHA" )!=NULL) trace->sort = SORT_BY_ALPHA; if (strstr(s, "BASE_KV" )!=NULL) trace->sort = SORT_BY_BASEKV; if (strstr(s, "OWNER" )!=NULL) trace->sort = SORT_BY_OWNER; if (strstr(s, "ZONE" )!=NULL) trace->sort = SORT_BY_ZONE; if (strstr(s, "INPUT" )!=NULL) trace->sort = SORT_BY_INPUT; if (strstr(s, "SOLUTION" )!=NULL) trace->sort = SORT_BY_SOLN; if (strstr(s, "DIFFERENCE" )!=NULL) trace->sort = SORT_BY_SOLN; trace->query &= ~(QUERY_SORT); } if (strstr(s, "TRACE" )!=NULL) { if (strstr(s, "YES")!=NULL) trace->trc->type = TYPE_TRACE; if (strstr(s, "NO" )!=NULL) trace->trc->type = TYPE_NONE; trace->query &= ~(QUERY__TRC); } if (strstr(s, "VARIANCE" )!=NULL) { if (strstr(s, "YES")!=NULL) trace->trc->diff = VARI_YES; if (strstr(s, "NO" )!=NULL) trace->trc->diff = VARI_NO; trace->query &= ~(QUERY_VARI); } if (strstr(s, "REMOVE_REDUNDANT")!=NULL) { if (strstr(s, "YES")!=NULL) trace->redun = REDUN_REMOVE; if (strstr(s, "NO" )!=NULL) trace->redun = REDUN_KEEP; trace->query &= ~(QUERY_REDU); } } void ff_expList(Trace *trace, Link *dataList, Link **expList) { /* expand double-linked list */ Link *curLink, *newList; FILE *readMe; curLink = dataList; while (curLink != NULL) { if ( cf_isDataFile(curLink->data) ){/*DAT, LIS, or TRC to be opened & read*/ readMe = cf_openFile(curLink->data, "r");/* it's okay if readMe==NULL */ ff_stream2List(readMe, trace, expList); fclose(readMe); } else if (expList!=NULL) { /* expansion list */ newList = cf_text2List(curLink->data); cf_appList(expList, newList); } curLink = cf_delLink(&dataList, curLink); } } int ff_srtBranch(cf_Branch *b1, cf_Branch *b2, int sort) /* sort branch */ { int c; float d; if ( (c=strcmp(b1->type, b2->type)) != 0 ) return c; /* [type]-sort */ if (sort==SORT_BY_ZONE) { /* [zone]-alpha-kv */ if ( (c=strcmp(b1->bus1_zone, b2->bus1_zone)) != 0 ) return c; if ( (c=strcmp(b1->bus2_zone, b2->bus2_zone)) != 0 ) return c; } else if (sort==SORT_BY_OWNER) { /* [owner]-alpha-kv */ if ( (c=strcmp(b1->owner, b2->owner)) != 0 ) return c; } else if (sort==SORT_BY_BASEKV) { /* [kv]-alpha-kv */ if ( fabs(d = b1->bus1_kv - b2->bus1_kv) > .001 ) return d; if ( fabs(d = b1->bus2_kv - b2->bus2_kv) > .001 ) return d; } return cf_cmpBranch((pf_branch *) b1, (pf_branch *) b2); /* [alpha-kv] */ } int validMask(Link *maskList, cf_Name *r) { Link *maskLink; char *maskData, netData[CF_STRSIZE], netVal[34], mskVal[34]; int n; pf_rec t; if (maskList==NULL || maskList->data==NULL) return -1; for (maskLink=maskList; maskLink!=NULL; maskLink=maskLink->next) { maskData = (char *) maskLink->data; switch (toupper(r->type[0])) { case 'B' : cf_bus2rec((cf_Bus *) r, &t); pf_rec_b2a(netData, &t, "I"); break; case 'E' : case 'L' : case 'T' : cf_branch2rec((cf_Branch *) r, &t); pf_rec_b2a(netData, &t, "I"); break; case 'C' : strcpy(netData, r->name); break; default : return 0; /* data at *r is not valid */ } sprintf(mskVal, "%-33.33s", maskData); sprintf(netVal, "%-33.33s", netData); for (n=0; mskVal[n]!='\0'; n++) { if (mskVal[n] == '?') netVal[n] = '?'; if (mskVal[n] == '*') netVal[n] = '*'; if (mskVal[n] == ' ') netVal[n] = ' '; if (mskVal[n] == '0') netVal[n] = '0'; } if (strncmp(mskVal, netVal, 33)==0) return 1; /* keep */ } return 0; } /************ documented, common CF_UTIL.H candidates prototypes **************/ /* all documented, CF_UTIL.H candidates shall be designated, cf_name(). */ void date(char *date) { int mo, yr; if (sscanf(date, "%d/%d", &mo, &yr) != 2) return; if (mo>12 || mo<1 || yr<0 || yr>99) return; if (mo==10) sprintf(date, "O%02d", yr); else if (mo==11) sprintf(date, "N%02d", yr); else if (mo==12) sprintf(date, "D%02d", yr); else sprintf(date, "%1d%02d", mo, yr); } /******** end documented, common CF_UTIL.H candidates prototypes **************/ /******************************************************************************\ cf_util.c library Developed by William D. Rogers for use with Bonneville Power Administration's CFLOW library and Interactive Powerflow (IPF) program. Naming conventions: (suggested, note case) Cf_macro, Cf_macroName cf_function, cf_functionName CF_CONSTANT, CF_CONSTANTNAME CF_globalVariable cf_Structure, Structure Cx_, CX, cx,... legacy functions to be retired Library organization: (suggested) #include #define macros #define constants typedef struct global variables function prototypes functions \******************************************************************************/ void cf_sprompt(char *prompt, char *dflt, char *reply) /******************************************************************************\ * cf_sprompt: (s-string, white-space delimited) * Prompt with default for a white-space delimited string. * char *prompt - string directing user response with optional default string * char *dflt - default response string if user-reply not convertable * char *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { int conv = 0; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); conv = sscanf(CF_inbuf, "%s", reply); if ( conv <= 0 ) strcpy(reply, dflt); } void cf_kprompt(char *prompt, char dflt, char *reply) /******************************************************************************\ * cf_kprompt: (k-character, first non-white) * Prompt with default for a single non-white-space character. * char *prompt - string directing user response with optional default character * char dflt - default response character if user-reply not convertable * char *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { int conv = 0; char temp[2]; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); conv = sscanf(CF_inbuf, "%1s", temp); if ( conv <= 0 ) *reply = dflt; else *reply = temp[0]; } void cf_mprompt(char *prompt, char *dflt, char *mask, char *reply) /******************************************************************************\ * cf_mprompt: (m-mask, sscanf format) * Prompt with default for a string to be scanned in with specified mask. * char *prompt - string directing user response with optional default string * char *dflt - default response string if user-reply not convertable * char *mask - mask string for sscanf to process user-reply with * char *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { int conv = 0; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); conv = sscanf(CF_inbuf, mask, reply); if ( conv <= 0 ) strcpy(reply, dflt); } void cf_nprompt(char *prompt, char *dflt, int n, char *reply) /******************************************************************************\ * cf_nprompt: (n-number, first n characters) * Prompt with default for a string containing the first n characters. * char *prompt - string directing user response with optional default string * char *dflt - default response string if user-reply not convertable * int n - max. number of characters to be scanned into response string * char *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { int conv = 0; char mask[16]; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); sprintf(mask, "%%%d[^\n]", n); conv = sscanf(CF_inbuf, mask, reply); if ( conv <= 0 ) strcpy(reply, dflt); } void cf_cprompt(char *prompt, char dflt, char *reply) /******************************************************************************\ * cf_cprompt: (c-character, first one) * Prompt with default for a single character. * char *prompt - string directing user response with optional default character * char dflt - default response character if user-reply not convertable * char *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { int conv = 0; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); conv = sscanf(CF_inbuf, "%1c", &reply); if ( conv <= 0 ) *reply = dflt; } void cf_fprompt(char *prompt, float dflt, float *reply) /******************************************************************************\ * cf_fprompt: (f-float, real number) * Prompt with default for a real (floating-point) number. * char *prompt - string directing user response with optional default value * float dflt - default response value if user-reply not convertable * float *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { int conv = 0; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); conv = sscanf(CF_inbuf, "%f", reply); if ( conv <= 0 ) *reply = dflt; } void cf_dprompt(char *prompt, double dflt, double *reply) /******************************************************************************\ * cf_dprompt: (d-double, double-precision real number) * Prompt with default for a real (double-precision floating-point) number. * char *prompt - string directing user response with optional default value * double dflt - default response value if user-reply not convertable * double *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers 10-3-96 \******************************************************************************/ { int conv = 0; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); conv = sscanf(CF_inbuf, "%f", reply); if ( conv <= 0 ) *reply = dflt; } void cf_iprompt(char *prompt, int dflt, int *reply) /******************************************************************************\ * cf_iprompt: (i-integer) * Prompt with default for an integer. * char *prompt - string directing user response with optional default value * int dflt - default response value if user-reply not convertable * int *reply - pointer to destination of response: default or user-reply * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { int conv = 0; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); conv = sscanf(CF_inbuf, "%d", reply); if ( conv <= 0 ) *reply = dflt; } int cf_yprompt(char *prompt, int dflt) /******************************************************************************\ * cf_yprompt: (y-yes or no response) * Prompt with default for a yes (Y) or no (N) response. * Return 1 for [Y]es, 0 for [N]o, else -1 * char *prompt - string directing user response with optional default string * int dflt - default response character, 'Y' or 'N' * Developed by: WDRogers 7-12-95 \******************************************************************************/ { char *cp, c; printf(prompt, dflt); fgets(CF_inbuf, CF_INBUFSIZE, stdin); for (cp=CF_inbuf; isspace(*cp); cp++); /* find first character */ c = (*cp=='\0') ? toupper(dflt) : toupper(*cp); switch (toupper(dflt)) { case 'Y': return (c=='Y') ? 1 : 0; case 'N': return (c=='N') ? 0 : 1; case ' ': return (c=='Y') ? 1 : ((c=='N') ? 0 : -1); default : printf("cf_yprompt: invalid default %c", dflt); break; } return -1; } void cf_eprint(FILE *fp, char *fmt, ...) /******************************************************************************\ * cf_eprint: (e-echo, print to stdout and file) * prints formated string with arguments to stdout and to specified file * FILE *fp - pointer to file to print string to * char *fmt - format string for printf function followed by arguments * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { /* print to file and to stdout */ va_list ap; va_start(ap, fmt); vfprintf(fp, fmt, ap); vfprintf(stdout, fmt, ap); va_end(ap); return; } void cf_aprint(char *target, char *fmt, ...) /******************************************************************************\ * cf_aprint: (a-append, append sprintf to string) * appends results of sprintf() to target string * char *target - pointer to string to append results of sprintf to * char *fmt - format string for sprintf function followed by arguments * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { va_list ap; va_start(ap, fmt); vsprintf(CF_inbuf, fmt, ap); strcat(target, CF_inbuf); va_end(ap); return; } void cf_exit(int error, char *fmt, ...) /******************************************************************************\ * cf_exit: * on error (error == 1) print messages and exit program, else continue * int error - value to be evaluated to determine if exit should occur * char *fmt - format of message string for printf() followed by arguments * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { /* error == 0 means OK, no exit */ va_list ap; if (!error) return; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); exit(0); } void cf_pfexit(int error, char *fmt, ...) /******************************************************************************\ * cf_pfexit: (pf - powerflow, break connection with server before exiting) * on error (error == 1) print messages and exit program, else continue * int error - value to be evaluated to determine if exit should occur * char *fmt - format of message string for printf() followed by arguments * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { /* error == 0 means OK, no exit */ va_list ap; if (!error) return; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); pf_cflow_exit(); exit(0); } void cf_stoupper(char *str) /******************************************************************************\ * cf_stoupper: (s - string) * convert all characters in string to upper case. * char *str - pointer to string to be converted to upper case * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { char *cp; for( cp = str ; *cp != '\0' ; cp++ ) { *cp = toupper(*cp); } } int cf_str2list(char *list, int group, char delim) /******************************************************************************\ * cf_str2list: * Example: cf_str2list("B BCBE+F +I,+N ^%$AD", 2, ' ') => "B BC BE +F +I +N AD" * parse list into string of delimited character sequences of max. given length * char *list - pointer to string to be parsed and destination of result * int group - maximum number of consecutive characters in a sequences * char delim - character used to delimit parsed sequences in returned list * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { #define CF_NONSEP_CHARS ".+-_" char c, *src, *sp; int i = 0; if (*list == '\0') return 0; src = strchr(list, '\n'); if ( src != NULL ) *src = '\0'; src = calloc(sizeof(char), strlen(list) + 1); if ( src == NULL ) return 1; sp = src; strcpy(src, list); while ( (c = *src++) != '\0' ) { if (i == group) { *list++ = delim; i = 0; } if ( isalnum(c) || (strchr(CF_NONSEP_CHARS,c)!=NULL) ) { *list++ = c; i++; } else if ( (i > 0) && (i < group) ) { *list++ = delim; i++; } } while ( (i > 0) && (i < group) ) { *list++ = delim; i++; } *list = '\0'; free(sp); return 0; } char *cf_strsuf(char *dest, char *source, char term, char *suffix) /******************************************************************************\ * cf_strsuf: (suf - suffix) * append suffix to source at last instance of terminating character or at end * Example: cf_strsuf(dest, "FGROVE.BSE", '.', ".NET") ==> dest = "FGROVE.NET" * char *dest - pointer to the destination string * char *source - pointer to the source string * char term - terminating character in source string * char *suffix - string to be appended to end of source * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { char *end; strcpy(dest, source); if ( (end = strrchr(dest, term)) != NULL ) *end = '\0'; return strcat(dest, suffix); } int cf_strcon(char *s1, char *s2) /******************************************************************************\ * cf_strcon: (con - contains, does s1 contain s2?) * return 1 if a string contains any occurance of a second string, else return 0 * char *s1 - pointer to string to be searched for occurances of second string * char *s2 - pointer to string to be searched for in first string * Developed by: WDRogers Updated: 2-14-95 \******************************************************************************/ { return (strstr(s1, s2) == NULL) ? 0 : 1; } char *cf_parse(char *spec, char *part, int code) /******************************************************************************\ * cf_parse: parse a file spec into its components * char *spec: - string containing a valid VMS file spec * char *part: - destination string of file spec component, or NULL * int code: - indicates source file spec component, codes are as follows: * [S]pec,n[O]de,dis[K],[D]irectory,[N]ame,[T]ype,[V]ersion,[P]ath,[F]ile * BPA60::DISK1:[BASECASE]FGROVE.DAT;102 * <nOde-><disK><Director><Name><Ty><Ve> * <--------Path---------><----File----> * <---------------Spec----------------> * Return: char pointer to file spec component indicated by code * Developed by: WDRogers 7-12-95 updated: 08-06-96 \******************************************************************************/ { char *sp, *op, *kp, *dp, *np, *tp,*vp, *ep; static char item[FILENAME_MAX]; item[0] = '\0'; /* cf_stoupper(spec); */ for (sp = spec; isspace(*sp); sp++);/* skip leading whitespace */ for (ep = sp; isgraph(*ep); ep++); *ep='\0';/* remove trailing whitespace */ if (ep==sp) { if (part!=NULL) strcpy(part, item); return item; /* strlen = 0 */ } op=strstr(sp, "::"); if (op==NULL) op=sp; else op+=2; kp=strrchr(op, ':'); if (kp==NULL) kp=op; else kp++; /* find : or :[ */ dp=strrchr(kp, ']'); if (dp==NULL) dp=kp; else dp++; np=strpbrk(dp,".;"); if (np==NULL) np=ep; tp=strrchr(np, ';'); if (tp==NULL) tp=ep; vp=strrchr(tp, ';'); if (vp==NULL) vp=ep; switch (toupper(code)) { case 'S' : strncat(item, sp, Cf_min(ep-sp, FILENAME_MAX-1)); break; case 'O' : strncat(item, sp, Cf_min(op-sp, FILENAME_MAX-1)); break; case 'K' : strncat(item, op, Cf_min(kp-op, FILENAME_MAX-1)); break; case 'D' : strncat(item, kp, Cf_min(dp-kp, FILENAME_MAX-1)); break; case 'N' : strncat(item, dp, Cf_min(np-dp, FILENAME_MAX-1)); break; case 'T' : strncat(item, np, Cf_min(tp-np, FILENAME_MAX-1)); break; case 'V' : strncat(item, tp, Cf_min(ep-vp, FILENAME_MAX-1)); break; case 'P' : strncat(item, sp, Cf_min(dp-sp, FILENAME_MAX-1)); break; case 'F' : strncat(item, dp, Cf_min(ep-dp, FILENAME_MAX-1)); break; default : strncat(item, sp, Cf_min(ep-sp, FILENAME_MAX-1)); break; } if (part!=NULL) strcpy(part, item); return item; } int cf_query2spec(char *spec, char *query, char *type) /******************************************************************************\ * cf_query2spec: parse query into a file spec and determine if it is a source file or a text file containing a list of source files. * char *spec - destination string for a valid file spec * char *query - string containing text entered at a prompt * char *type - the file type indicating that the file is a text list * Return type: int - 0: no file spec, 1: source file, 2: list of source files * Calls: cf_parse * Developed by: WDRogers 7-21-95 \******************************************************************************/ { int len; cf_parse(query, spec, 'S'); if ((len=strlen(spec))==0) return 0; /* no input */ if ( strcmp(cf_parse(spec, NULL, 'T'), type)==0 ) { /* type of list */ return 2; /* list of files */ } if (spec[len-1]=='/') { /* / for list */ spec[len-1] = '\0'; /* remove / char */ return 2; /* list of files */ } return 1; /* single file */ } void cf_logErr(char *fmt, ...) /******************************************************************************\ * cf_logErr: write a formatted string to a log file or to stderr * requires CF_logFile, a globally defined file pointer initialized to NULL * requires CF_logSpec, a globally defined string initialized by a cflow program * char *fmt - format string for fprintf function followed by arguments * Return type: void * Calls: cf_openFile * Developed by: WDRogers 7-21-95 \******************************************************************************/ { va_list ap; if (CF_logFile==NULL) { CF_logFile = stderr; CF_logFile = cf_openFile(CF_logSpec, "w"); if (CF_logFile==NULL) { CF_logFile = stderr; /* if open fails, use stderr */ strcpy(CF_logSpec, "stderr"); } } va_start(ap, fmt); if (CF_logFile != NULL) vfprintf(CF_logFile, fmt, ap); vfprintf(stderr, fmt, ap); va_end(ap); } /****************** add stuff for query log *******************/ void cf_logQuery(char *fmt, ...) /******************************************************************************\ * cf_logQuery: write a formatted string to a log file or to stderr * All strings sent to powerflow via query_pf are recorded here * requires CF_logQFile, a globally defined file pointer initialized to NULL * requires CF_logQSpec, a globally defined string initialized by a cflow program * char *fmt - format string for fprintf function followed by arguments * Return type: void * Calls: cf_openFile * Developed by: DMStefonek 12-12-97 \******************************************************************************/ { va_list ap; if (CF_logQFile==NULL) { CF_logQFile = stderr; CF_logQFile = cf_openFile(CF_logQSpec, "w"); if (CF_logQFile==NULL) { CF_logQFile = stderr; /* if open fails, use stderr */ strcpy(CF_logQSpec, "stderr"); } } va_start(ap, fmt); if (CF_logQFile != NULL) vfprintf(CF_logQFile, fmt, ap); vfprintf(stderr, fmt, ap); va_end(ap); } /****************** add stuff for query log *******************/ /****************** add stuff for BAD (aka ZAP) log *******************/ void cf_logBAD(char *fmt, ...) /******************************************************************************\ * cf_logBAD: write a formatted string to a log file or to stderr * This file is used to advise PVCURVE users where the critical outages exist. * requires CF_logZFile, a globally defined file pointer initialized to NULL * requires CF_logZSpec, a globally defined string initialized by a cflow program * char *fmt - format string for fprintf function followed by arguments * Return type: void * Calls: cf_openFile * Developed by: DMStefonek 12-12-97 \******************************************************************************/ { va_list ap; if (CF_logZFile==NULL) { CF_logZFile = stderr; CF_logZFile = cf_openFile(CF_logZSpec, "w"); if (CF_logZFile==NULL) { CF_logZFile = stderr; /* if open fails, use stderr */ strcpy(CF_logZSpec, "stderr"); } } va_start(ap, fmt); if (CF_logZFile != NULL) vfprintf(CF_logZFile, fmt, ap); vfprintf(stderr, fmt, ap); va_end(ap); } /****************** add stuff for BAD (aka ZAP) log *******************/ FILE *cf_openFile(char *spec, char *mode) /******************************************************************************\ * cf_openFile: write a formatted string to a log file or to stderr * char *spec - a string containing a file specification * char *mode - a string containing a valid file operation mode * Return type: FILE * - pointer to opened stream or NULL if failed * Calls: cf_logErr * Developed by: WDRogers 7-21-95 \******************************************************************************/ { FILE *fp; if ( (fp = fopen(spec, mode)) == NULL) cf_logErr("cf_openFile: Cannot open file: %s with mode %s\n", spec, mode); return fp; } size_t cf_time(char *s, size_t smax, char *format) /******************************************************************************\ * cf_time: writes date and time information into s according to format. * char *s - destination for time/date string. * size_t smax - maximum number of characters written to s. * char *format - character string analogous to a printf format string. * returns: size_t - number of characters written into s, excluding '\0', or zero * if more than smax characters were produced. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { time_t t; t = time(NULL); return strftime(s, smax, format, localtime(&t)); } void *cf_calloc(size_t nobj, size_t size) /******************************************************************************\ * cf_calloc: call calloc() with error messaging; increment CF_memCurAlloc; * size_t nobj - number of objects in the allocated array * size_t size - size of each object in the allocated array * calls: void cf_logErr(char *fmt, ...) * globals: CF_memCurAlloc, CF_memTotAlloc, CF_memMaxAlloc * returns: void * - pointer to allocated space and zero initialized space * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { void *p; p = NULL; p = calloc(nobj, size); if (p!=NULL) { CF_memCurAlloc += nobj*size; if (CF_memCurAlloc < 0) { fprintf (stderr, "cf_calloc: memory allocated = %10d %10d %10d %10d %10d\n", total_requests, size, total_memory_allocated, CF_memCurAlloc, CF_memTotAlloc); } CF_memTotAlloc += nobj*size; if (CF_memCurAlloc > CF_memMaxAlloc) CF_memMaxAlloc = CF_memCurAlloc; } else cf_logErr("cf_calloc: Can't allocate any more memory!\n"); return p; } void cf_free(void *obj, size_t size) /******************************************************************************\ * cf_free: call free(); decrement CF_memCurAlloc; * size_t size - size of object to be free'd * globals: CF_memCurAlloc, CF_memTotFreed * returns: void * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { free(obj); CF_memCurAlloc -= size; CF_memTotFreed += size; } int cf_iscomment(char *str) /******************************************************************************\ * cf_iscomment: determine if line has data on it; truncate at CF_TRUNCATE. * char *str - pointer to string possibly containing data * calls: int cf_isblank(char *str) * returns: int - 1 if str is a comment, otherwise 0 * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { char *cp; if ( str[0]==CF_COMMENT ) return 1; /* str is a comment */ cp = strpbrk(str, CF_TRUNCATE); if (cp!=NULL) *cp='\0'; /* truncate string */ if (cf_isblank(str)) return 1; /* str is all white space, treat as comment */ return 0; } char *cf_str2upper(char *str) /******************************************************************************\ * cf_str2upper: (str - string, 2 - to, upper - uppercase) convert all characters * in string to upper case. * char *str - pointer to string to be converted to upper case * returns: char * - pointer to uppercase string * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { char *cp; for( cp = str ; *cp != '\0' ; cp++ ) *cp = toupper(*cp); return str; } char *cf_str2lower(char *str) /******************************************************************************\ * cf_str2lower: (str - string, 2 - to, lower - lowercase) convert all characters * in string to lower case. * char *str - pointer to string to be converted to lower case * returns: char * - pointer to lowercase string * developed by: WDRogers created: 08-06-96 \******************************************************************************/ { char *cp; for( cp = str ; *cp != '\0' ; cp++ ) *cp = tolower(*cp); return str; } int cf_isblank(char *sp) /******************************************************************************\ * cf_isblank: examines characters in string starting at cp. * char *sp - pointer to a string. * returns: int - 1 if sp is all white space; otherwise 0. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { while (*sp!='\0' && isspace(*sp)) sp++; return (*sp=='\0') ? 1 : 0; } int cf_isDataFile(char *name) /******************************************************************************\ * cf_isDataFile: checks file type and post-fix character to see if it is data; * removes / from end of name. * char *name - the name of a file. * calls: char *cf_parse(char *spec, char *part, int code) * calls: char *cf_str2upper(char *s) * returns: int - 1 if file type is in CF_DATATYPES or name appended with '/'; * otherwise 0. * developed by: WDRogers updated: 01-31-96 updated: 08-06-96 \******************************************************************************/ { char type[FILENAME_MAX], *cp; cp = &name[strlen(name)-1]; if ( *cp == '/' ) { *cp = '\0'; return 1; } cf_parse(name, type, 'T'); /* get file type, i.e. ".DAT" */ cf_str2upper(type); if ( strstr(CF_DATATYPES, type) != NULL ) return 1; return 0; } Link *cf_newLink(size_t size) /******************************************************************************\ * cf_newLink: allocates memory for Link struct and its data. * size_t size - size of data structure associated with the Link. * calls: void *cf_malloc(size_t size) * returns: Link * - pointer to Link or NULL if request fails. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { Link *new; new = NULL; new = (Link *) cf_malloc(sizeof(Link)); if (new!=NULL) { new->data = (size>0) ? (void *) cf_malloc(size) : NULL; new->size = size; new->next = NULL; new->prev = NULL; } return new; } int cf_cntLink(Link *cur) /******************************************************************************\ * cf_cntLink: counts the number of links to the end of the list. * Link *cur - pointer to a Link in a linked list of Link structs. * returns: int - number of links to the end of the list * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { int n; for (n=0; cur != NULL; cur=cur->next) n++; return n; } Link *cf_addLink(Link *tar, size_t size) /******************************************************************************\ * cf_addLink: add a new Link directly after the target Link. * Link *tar - pointer to the targeted Link to which to add the new Link. * size_t size - size of the data area for the new Link. * calls: Link *cf_newLink(size_t size) * returns: pointer to the new Link. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { Link *new; new = cf_newLink(size); if (new!=NULL) new->prev = tar; if (tar!=NULL) tar->next = new; return (new!=NULL) ? new : tar; } Link *cf_delLink(Link **top, Link *del) /******************************************************************************\ * cf_delLink: removes Link struct from list of Link structs. Frees memory. * Link *del - pointer to Link to be deleted from the linked list of Links. * Link *top - pointer to pointer to top Link in linked list. * calls: void cf_free(void *obj, size_t size) * returns: pointer to next Link in list. * Developed by: WDRogers Updated: 12-06-95 \******************************************************************************/ { Link *prv, *nxt; if (del==NULL) return del; prv = del->prev; nxt = del->next; if (del==*top) *top = nxt; if (prv!=NULL) prv->next = nxt; if (nxt!=NULL) nxt->prev = prv; cf_free(del->data, del->size); cf_free(del, sizeof(Link)); return nxt; } Link *cf_appList(Link **top, Link *src) /******************************************************************************\ * cf_appList: append source list of Link structs to destination list. * Link **top - pointer to pointer to the first link in the destination list. * Link *src - pointer to the first link in the source list. * returns: pointer to first Link in the list to which second list was appended. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { Link *end; for ( end = *top; end != NULL && end->next != NULL; end = end->next ); if (*top==NULL) *top = src; if (end!=NULL) end->next = src; if (src!=NULL) src->prev = end; return *top; } Link *cf_dupList(Link *src) /******************************************************************************\ * cf_dupList: duplicate a list. * Link *src - pointer to top link in list to be copied. * calls: Link *cf_addLink(Link *tar, size_t size) * returns: Link * - pointer to new list. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { Link *new, *top; top = NULL; new = NULL; while (src!=NULL) { new = cf_addLink(new, src->size); if (top==NULL) top = new; memcpy(new->data, src->data, src->size); src = src->next; } return top; } void cf_freeList(Link *cur) /******************************************************************************\ * cf_freeList: free current Link and all following Links in a list. * Link *cur - pointer to the current link in the targeted list. * calls: void cf_free(void *obj, size_t size) * returns: void * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { Link *del; while (cur!=NULL) { del = cur; cur = cur->next; cf_free(del->data, del->size); cf_free(del, sizeof(Link)); del = NULL; } return; } Link *cf_link2row(Link *dat) /******************************************************************************\ * cf_link2row: allocate space for new Link whose data is another Link. * Link *dat - pointer to a Link. * calls: Link *cf_newLink(size_t size) * returns: Link * - pointer to row link. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { Link *new; new = cf_newLink(0); if (new!=NULL) new->data = dat; if (dat!=NULL) dat->prev = new; if (new!=NULL) new->kind = CF_KIND_LINK; return new; } void cf_freeRow(Link *row) /******************************************************************************\ * cf_freeRow: free row Link and all data Links in row. * Link *row - pointer to the targeted row. * calls: void cf_free(void *obj, size_t size), void cf_freeList(Link *cur) * returns: void * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { Link *dat; dat = (row!=NULL) ? (Link *) row->data : NULL; cf_freeList(dat); cf_free(row, sizeof(Link)); return; } Link *cf_delRow(Link **top, Link *tar) /******************************************************************************\ * cf_delRow: deletes a row from a linked list of rows. * Link **top - pointer to pointer to top of list containing target row. * Link *tar - pointer to target row to be deleted. * calls: void cf_freeRow(Link *row) * returns: pointer to next Link after target. * developed by: WDRogers updated: 01-31-96 \******************************************************************************/ { /* removes a row from a row list */ Link *nxt; nxt = tar->next; if (tar == *top) *top = tar->next; if (tar->prev!=NULL) tar->prev->next = tar->next; if (tar->next!=NULL) tar->next->prev = tar->prev; cf_freeRow(tar); return nxt; } int cf_rec_l2h(pf_branch *r) /******************************************************************************\ * cf_rec_l2h: rearranges branch data into low-to-hi alpha, hi-to-low numeric. * pf_branch *r - pointer to a branch. * returns: int, 1 if already in l2h, otherwise -1. * developed by: WDRogers updated: 05-08-96 \******************************************************************************/ { int n; float temp_v, v; char temp_n[9]; n = strcmp(r->bus1_name, r->bus2_name); v = r->bus1_kv - r->bus2_kv; if ( (v>0) || (v==0 && n<=0) ) return 1; strcpy(temp_n, r->bus1_name); strcpy(r->bus1_name, r->bus2_name); strcpy(r->bus2_name, temp_n); temp_v = r->bus1_kv; r->bus1_kv = r->bus2_kv; r->bus2_kv = temp_v; return -1; } int cf_rec_h2l(pf_branch *r) /******************************************************************************\ * cf_rec_h2l: rearranges branch data into hi-to-low alpha, low-to-hi numeric. * pf_branch *r - pointer to a branch. * returns: int, 1 if already in h2l, otherwise -1. * developed by: WDRogers 12-31-96 \******************************************************************************/ { int n; float temp_v, v; char temp_n[9]; n = strcmp(r->bus1_name, r->bus2_name); v = r->bus1_kv - r->bus2_kv; if ( (v<0) || (v==0 && n>=0) ) return 1; strcpy(temp_n, r->bus1_name); strcpy(r->bus1_name, r->bus2_name); strcpy(r->bus2_name, temp_n); temp_v = r->bus1_kv; r->bus1_kv = r->bus2_kv; r->bus2_kv = temp_v; return -1; } int cf_cmpBranch(pf_branch *b1, pf_branch *b2) /******************************************************************************\ * cf_cmpBranch: compare identifying data of two pf_branch records. * pf_branch *b1 - pointer to branch record. * pf_branch *b2 - pointer to branch record. * returns: int - 0 if same, 1 if b1 > b2, -1 if b1 < b2. * developed by: WDRogers updated: 02-02-96 \******************************************************************************/ { float c; if ( (c=strncmp(b1->type, b2->type, 1)) ) return c>0 ? 1 : -1; if ( (c=strcmp(b1->bus1_name, b2->bus1_name)) ) return c>0 ? 1 : -1; if ( fabs(c=b1->bus1_kv-b2->bus1_kv) > .001 ) return c>0 ? 1 : -1; if ( (c=strcmp(b1->bus2_name, b2->bus2_name)) ) return c>0 ? 1 : -1; if ( fabs(c=b1->bus2_kv-b2->bus2_kv) > .001 ) return c>0 ? 1 : -1; if ( (c=b1->ckt_id - b2->ckt_id) ) return c>0 ? 1 : -1; if ( (c=b1->section - b2->section) ) return c>0 ? 1 : -1; return 0; } int cf_cmpBus(pf_AC_bus *b1, pf_AC_bus *b2) /******************************************************************************\ * cf_cmpBus: compare identifying data of two pf_AC_bus records. * pf_AC_bus *b1 - pointer to bus record. * pf_AC_bus *b2 - pointer to bus record. * returns: int - 0 if same, 1 if b1 > b2, -1 if b1 < b2. * developed by: WDRogers updated: 02-02-96 \******************************************************************************/ { float c; if ( (c=strncmp(b1->type, b2->type, 1)) ) return c>0 ? 1 : -1; if ( (c=strcmp(b1->name, b2->name)) ) return c>0 ? 1 : -1; if ( fabs(c=b1->kv - b2->kv) > .001 ) return c>0 ? 1 : -1; return 0; } Link *cf_text2Link(char *s) /******************************************************************************\ * cf_text2Link: make string into a Link. * char *s - string containing text to be made into a Link. * calls: Link *cf_newLink(size_t); * returns: Link * - pointer to new Link or NULL if none formed. * developed by: WDRogers updated: 02-02-96 updated: 01-16-97 \******************************************************************************/ { Link *link; if (cf_isblank(s)) return NULL; link = cf_newLink(strlen(s)+1); if (link==NULL || link->data==NULL) return NULL; strcpy(link->data, s); link->kind = CF_KIND_STR; return link; } Link *cf_text2List(char *s) /******************************************************************************\ * cf_text2List: make each word in string into a Link in a linked list. * char *s - string containing words to be broken into Links. * calls: Link *cf_addLink(Link *, size_t); * returns: Link * - pointer to top of list or NULL if no list formed. * developed by: WDRogers updated: 02-02-96 updated: 01-16-97 \******************************************************************************/ { Link *curLink, *topLink; char *qp; topLink = NULL; curLink = NULL; for (qp=strtok(s, CF_TOKSEP); qp!=NULL; qp=strtok(NULL, CF_TOKSEP) ) { curLink = cf_addLink(curLink, strlen(qp)+1); if (curLink==NULL || curLink->data==NULL) continue; if (topLink==NULL) topLink = curLink; strcpy(curLink->data, qp); curLink->kind = CF_KIND_STR; } return topLink; } int cf_validOwner(Link *ownerList, char *owner) /******************************************************************************\ * cf_validOwner: checks owner against linked list of owner specifications. Can * use: OWN, !OWN, or *** for include, exclude, and wild card, respectively. * Link *ownerList - top link in linked list of owner specifications. * char *owner - char string containing an owner code. * returns: int - 1 if included, 0 if excluded, -1 if not on list; * developed by: WDRogers updated: 02-02-96 \******************************************************************************/ { Link *ownerLink; char *ownerData, listVal[4], maskVal[4]; int retval = -1, n; if (ownerList==NULL || ownerList->data==NULL) return -1; if (memcmp(ownerList->data, "***", 3)==0) return 1; for (ownerLink=ownerList; ownerLink!=NULL; ownerLink=ownerLink->next) { ownerData = (char *) ownerLink->data; n = (ownerData[0]=='!') ? 1 : 0; sprintf(listVal, "%-3.3s", &ownerData[n]); sprintf(maskVal, "%-3.3s", owner); if (listVal[0] == '*') maskVal[0] = '*'; if (listVal[1] == '*') maskVal[1] = '*'; if (listVal[2] == '*') maskVal[2] = '*'; if (ownerData[0]=='!') { if (retval==-1) retval = 1; /* keep, unless explicitly skipped */ if (strcmp(listVal, maskVal)==0) return 0; /* skip this owner */ } else { if (retval==-1) retval = 0; /* skip, unless explicitly kept */ if (strcmp(listVal, maskVal)==0) return 1; /* keep this owner */ } } return (retval == -1) ? 1 : retval; } int cf_validBasekv(Link *basekvList, float v1, float v2) /******************************************************************************\ * cf_validBasekv: checks kv 1 and kv 2 against linked list of kv specifications. * Use: 00 (exactly 00), >00 (greater than 00), <00 (less than 00), or * 00-00 (00 to 00, inclusive). * Link *basekvList - top link in linked list of base kV specifications. * float v1 - bus base voltage. * float v2 - bus base voltage. * returns: int - 1 if either included, 0 if both excluded, -1 if neither listed. * developed by: WDRogers updated: 02-02-96 \******************************************************************************/ { /* return 1 if base kv are valid, else 0 */ Link *basekvLink; char *basekvData; float listVal1, listVal2; int retval = -1; if (basekvList==NULL || basekvList->data==NULL) return -1; if (memcmp(basekvList->data, ">0", 2)==0) return 1; for (basekvLink=basekvList; basekvLink!=NULL; basekvLink=basekvLink->next) { basekvData = (char *) basekvLink->data; if (basekvData[0]=='>') { if (retval==-1) retval = 0; /* skip, unless explicitly kept */ sscanf(basekvData, ">%f", &listVal1); if (v1 > listVal1 || v2 > listVal1) retval = 1; } else if (basekvData[0]=='<') { if (retval==-1) retval = 0; /* skip, unless explicitly kept */ sscanf(basekvData, "<%f", &listVal1); if (v1 < listVal1 || v2 < listVal1) retval = 1; } else if (strchr(basekvData, '-')!=NULL) { if (retval==-1) retval = 0; /* skip, unless explicitly kept */ sscanf(basekvData, "%f-%f", &listVal1, &listVal2); if ( (v1 >= listVal1 || v2 >= listVal1) && (v1 <= listVal2 || v2 <= listVal2) ) retval = 1;/*LO-HI*/ if ( (v1 >= listVal2 || v2 >= listVal2) && (v1 <= listVal1 || v2 <= listVal1) ) retval = 1;/*HI-LO*/ } else { if (retval==-1) retval = 0; /* skip, unless explicitly kept */ sscanf(basekvData, "%f", &listVal1); if ( fabs(v1-listVal1) < .001 || fabs(v2-listVal1) < .001 ) retval = 1; } } return (retval == -1) ? 1 : retval; } int cf_validZone(Link *zoneList, char *z1, char *z2) /******************************************************************************\ * cf_validZone: checks zone 1 and zone 2 against linked list of zone specificat- * ions. Use: ZN, !ZN, or ** for include, exclude, and wild card, respectively. * Link *zoneList - top link in linked list of owner specifications. * char *z1 - char string containing a zone code. * char *z2 - char string containing a zone code. * returns: int - 1 if either included, 0 if both excluded, -1 if neither listed. * developed by: WDRogers updated: 02-02-96 \******************************************************************************/ { Link *zoneLink; char *zoneData, listVal[4], maskVal1[4], maskVal2[4]; int retval = -1, n; if (zoneList==NULL || zoneList->data==NULL) return -1; if (memcmp(zoneList->data, "**", 2)==0) return 1; for (zoneLink=zoneList; zoneLink!=NULL; zoneLink=zoneLink->next) { zoneData = (char *) zoneLink->data; n = (zoneData[0]=='!') ? 1 : 0; sprintf(listVal, "%2.2s", &zoneData[n]); sprintf(maskVal1, "%2.2s", z1); sprintf(maskVal2, "%2.2s", z2); if (listVal[0] == '*') { maskVal1[0] = '*'; maskVal2[0] = '*'; } if (listVal[1] == '*') { maskVal1[1] = '*'; maskVal2[1] = '*'; } if (zoneData[0]== '!') { if (retval==-1) retval = 1; /* keep, unless explicitly skipped */ if ( strcmp(listVal, maskVal1)==0 && strcmp(listVal, maskVal2)==0 ) return 0; /* skip if both zones match listVal */ } else { if (retval==-1) retval = 0; /* skip, unless explicitly kept */ if ( strcmp(listVal, maskVal1)==0 || strcmp(listVal, maskVal2)==0 ) return 1; /* keep if either zone matches listVal */ } } return (retval == -1) ? 1 : retval; } void *cf_malloc(size_t size) /******************************************************************************\ * cf_malloc: call malloc() with error messaging; increment CF_memCurAlloc; * size_t size - size of each object in the allocated array * calls: void cf_logErr(char *fmt, ...) * globals: CF_memCurAlloc, CF_memTotAlloc, CF_memMaxAlloc * returns: void * - pointer to allocated space and zero initialized space * developed by: WDRogers created: 05-23-96 \******************************************************************************/ { void *p; p = NULL; total_memory_allocated += size; total_requests++; fprintf (stderr, "cf_malloc: memory allocated = %10d %10d %10d %10d %10d\n", total_requests, size, total_memory_allocated, CF_memCurAlloc, CF_memTotAlloc); if (total_requests > 19079) { fprintf (stderr, "cf_malloc: memory about to be corrupted!\n"); } p = malloc(size); if (p!=NULL) { CF_memCurAlloc += size; CF_memTotAlloc += size; if (CF_memCurAlloc > CF_memMaxAlloc) CF_memMaxAlloc = CF_memCurAlloc; } else { cf_logErr("cf_malloc: Can't allocate any more memory!\n"); } return p; } void cf_logUse(char *prog, char *vers, char *user) /******************************************************************************\ * void cf_logUse(char *prog, char *vers, char *user); * cf_logUse: write a formated string to a log file to time stamp program usage * Requires: CF_hisFile, a globally defined file pointer initialized to NULL * CF_HISSPEC, a globally defined string initialized to log file name * CF_time0, CF_time1, global variables of type time_t * CF_TIMESTAMP, a globally defined string specifying time/date format * CF_INBUFSIZE, global integer constant * char *prog: name of the CFLOW program being run * char *vers: version of IPF being used * char *user: ID of user running the CFLOW program * Return type: void * Calls: cf_openFile * Developed by: WDRogers 10-22-96 Updated: WDR 11-25-96 \******************************************************************************/ { char t0[CF_INBUFSIZE], t1[CF_INBUFSIZE]; double s, m, h; if (CF_time0>0 && CF_time1>0) { s = difftime(CF_time1, CF_time0); s = 60 * modf(s/60, &m); m = 60 * modf(m/60, &h); strftime(t0, CF_INBUFSIZE, CF_TIMESTAMP, localtime(&CF_time0)); strftime(t1, CF_INBUFSIZE, CF_TIMESTAMP, localtime(&CF_time1)); } else { h = m = s = 0; t0[0] = t1[0] = '\0'; } if (CF_hisFile==NULL) { CF_hisFile = cf_openFile(CF_HISSPEC, "a"); } if (CF_hisFile!=NULL) { /* fprintf(CF_hisFile, "%s %s Elapsed %2.0f:%02.0f:%02.0f (hh:mm:ss)\n", t0, t1, h, m, s); */ fprintf(CF_hisFile, "%-15.15s %-18.18s %-7.7s %-20.20s Elapsed %2.0f:%02.0f:%02.0f\n", prog, vers, user, t0, h, m, s); } fclose(CF_hisFile); return; } char *cf_strsub(char *str, char *sub, char fill) /******************************************************************************\ * cf_strsub: (sub - substitute) * function: replace all occurances of any character in sub with fill character * returns: char * - pointer to str * char *str - pointer to string to be filled * char *sub - pointer to string containing characters in str to be filled * char *fill - character to replaces sub characters with * Developed by: WDRogers 10-23-96 \******************************************************************************/ { char *cp; for ( cp = str ; *cp != '\0' ; cp++ ) if (strchr(sub, *cp)!=NULL) *cp = fill; return str; } void cf_freeRowList(Link **rowList) /******************************************************************************\ * void cf_freeRowList(Link **rowList); * cf_freeRowList: free list of row Links and all data Links in each row. * Link *rowList - pointer to pointer to the top of targeted list of rows. * calls: void cf_delRow(Link **top, Link *tar) * returns: void * developed by: WDRogers updated: 10-29-96 \******************************************************************************/ { Link *curRow = *rowList; while (curRow!=NULL) curRow = cf_delRow(rowList, curRow); return; } void cf_bus2rec(cf_Bus *bus, pf_rec *rec) /******************************************************************************\ * void cf_bus2rec(cf_Bus *bus, pf_rec *rec); * cf_bus2rec: translate cf_Bus structure to pf_rec structure * cf_Bus *bus - structure containing bus identification data * pf_rec *rec - target structure to contain bus id data * returns: void * developed by: WDRogers updated: 10-31-96 \******************************************************************************/ { memset(rec, '\0', sizeof(pf_rec)); strcpy(rec->i.ACbus.type, bus->type); strcpy(rec->i.ACbus.owner, bus->owner); strcpy(rec->i.ACbus.name, bus->name); rec->i.ACbus.kv = bus->kv; strcpy(rec->i.ACbus.zone, bus->zone); } void cf_rec2bus(pf_rec *rec, cf_Bus *bus) /******************************************************************************\ * void cf_rec2bus(pf_rec *rec, cf_Bus *bus); * cf_rec2bus: translate pf_rec structure to cf_Bus structure * pf_rec *rec - structure containing bus identification data * cf_Bus *bus - target structure to contain bus id data * returns: void * developed by: WDRogers updated: 10-31-96 \******************************************************************************/ { memset(bus, '\0', sizeof(cf_Bus)); strcpy(bus->type, rec->i.ACbus.type); strcpy(bus->owner, rec->i.ACbus.owner); strcpy(bus->name, rec->i.ACbus.name); bus->kv = rec->i.ACbus.kv; strcpy(bus->zone, rec->i.ACbus.zone); } void cf_branch2rec(cf_Branch *branch, pf_rec *rec) /******************************************************************************\ * void cf_branch2rec(cf_Branch *branch, pf_rec *rec); * cf_branch2rec: translate cf_Branch structure to pf_rec structure * cf_Branch *branch - structure containing branch input data * pf_rec *rec - target structure to contain branch input data * returns: void * developed by: WDRogers updated: 10-29-96 \******************************************************************************/ { memset(rec, '\0', sizeof(pf_rec)); strcpy(rec->i.branch.type, branch->type); strcpy(rec->i.branch.owner, branch->owner); strcpy(rec->i.branch.bus1_name, branch->bus1_name); strcpy(rec->i.branch.bus2_name, branch->bus2_name); strcpy(rec->i.branch.date_in, branch->date_in); rec->i.branch.bus1_kv = branch->bus1_kv; rec->i.branch.bus2_kv = branch->bus2_kv; rec->i.branch.ckt_id = branch->ckt_id; rec->i.branch.section = branch->section; rec->i.branch.total_rating = branch->nominal; rec->i.branch.thermal_rating = branch->thermal; rec->i.branch.bottleneck_rating = branch->bottleneck; rec->i.branch.emergency_rating = branch->emergency; } void cf_rec2branch(pf_rec *rec, cf_Branch *branch) /******************************************************************************\ * void cf_rec2branch(pf_rec *rec, cf_Branch *branch) * cf_rec2branch: translate pf_rec structure to cf_Branch structure * pf_rec *rec - structure containing branch input data * cf_Branch *branch - target structure to contain branch input data * returns: void * developed by: WDRogers updated: 10-29-96 \******************************************************************************/ { memset(branch, '\0', sizeof(cf_Branch)); strcpy(branch->type, rec->i.branch.type); strcpy(branch->owner, rec->i.branch.owner); strcpy(branch->bus1_name, rec->i.branch.bus1_name); strcpy(branch->bus2_name, rec->i.branch.bus2_name); strcpy(branch->date_in, rec->i.branch.date_in); branch->bus1_kv = rec->i.branch.bus1_kv; branch->bus2_kv = rec->i.branch.bus2_kv; branch->ckt_id = rec->i.branch.ckt_id; branch->section = rec->i.branch.section; branch->nominal = rec->i.branch.total_rating; branch->thermal = rec->i.branch.thermal_rating; branch->bottleneck = rec->i.branch.bottleneck_rating; branch->emergency = rec->i.branch.emergency_rating; } Link *cf_id2Link(char *s, char order) /******************************************************************************\ * Link *cf_id2Link(char *s, char order); * cf_id2Link: create Link with cf_Branch or cf_Bus data copied from s * char *s - string containing bus or branch input data * char order - character indicating sort order: * 'H'- h2l; 'L'- l2h; 'I'- input; * calls: cf_isblank, cf_str2upper, cf_newLink, pf_rec_a2b, cf_rec2bus * calls: cf_rec2branch, cf_rec_l2h, cf_rec_h2l * returns: Link * - pointer to Link referencing cf_Branch or cf_Bus data * developed by: WDRogers updated: 12-31-96 \******************************************************************************/ { Link *link; pf_rec r; size_t size; if (cf_isblank(s)) return NULL; cf_str2upper(s); size = (s[0]=='B') ? sizeof(cf_Bus) : sizeof(cf_Branch); link = cf_newLink(size); if (link==NULL || link->data==NULL) return NULL; pf_rec_a2b(s, &r, "I"); if (s[0]=='B') { cf_rec2bus(&r, (cf_Bus *) link->data); link->kind = CF_KIND_BUS; } else { switch(toupper(order)) { case 'H': cf_rec_h2l((pf_branch *) &r); break; case 'L': cf_rec_l2h((pf_branch *) &r); break; case 'I': break; /* retain input order */ default : fprintf(stderr,"cf_id2Link: invalid order code %c\n",order); } cf_rec2branch(&r, (cf_Branch *) link->data); link->kind = CF_KIND_BRN; } return link; } int cf_cntchr(char *str, char chr) /******************************************************************************\ * cf_cntchr: (cnt - count, chr - character) * function: count the number of occurances of character chr in string str * returns: int - number of occurances of chr in str * char *str - pointer to string to be examined * char chr - character to be counted * Developed by: WDRogers 11-12-96 \******************************************************************************/ { char *cp; int n; n = 0; for ( cp = str ; *cp != '\0' ; cp++ ) if (*cp==chr) n++; return n; } char *cf_strdup(char *str) /******************************************************************************\ * cf_strdup: (str - string, dup - duplicate) * function: duplicate the string str * calls: cf_malloc * returns: char * - pointer to new occurance of string str * char *str - pointer to string to be duplicated * Developed by: WDRogers 11-7-96 \******************************************************************************/ { char *new; new = (char *) cf_malloc(strlen(str)+1); /* +1 to make room for '\0' */ if (new != NULL) strcpy(new, str); return new; } int cf_branch_l2h(cf_Branch *b) /******************************************************************************\ * int cf_branch_l2h(cf_Branch *b); * cf_branch_l2h: (branch - cf_Branch, l2h - low to high) * function: rearranges branch data into low-to-hi alpha, hi-to-low numeric. * cf_Branch *b - pointer to branch data * returns: int, 1 if already in l2h, otherwise -1. * developed by: WDRogers updated: 11-18-96 \******************************************************************************/ { int n; float temp_v, v; char temp_n[9], temp_z[3]; n = strcmp(b->bus1_name, b->bus2_name); v = b->bus1_kv - b->bus2_kv; if ( (v>0) || (v==0 && n<=0) ) return 1; strcpy(temp_n, b->bus1_name); strcpy(temp_z, b->bus1_zone); temp_v = b->bus1_kv; strcpy(b->bus1_name, b->bus2_name); strcpy(b->bus2_name, temp_n); strcpy(b->bus1_zone, b->bus2_zone); strcpy(b->bus2_zone, temp_z); b->bus1_kv = b->bus2_kv; b->bus2_kv = temp_v; return -1; } Link *cf_rec2Link(char *s) /******************************************************************************\ * Link *cf_rec2Link(char *s); * cf_rec2Link: create Link with pf_rec data taken from s * char *s - string containing bus or branch input data * calls: cf_isblank, cf_str2upper, cf_newLink, pf_rec_a2b * returns: Link * - pointer to Link referencing pf_rec data * developed by: WDRogers updated: 12-31-96 \******************************************************************************/ { Link *link; if (cf_isblank(s)) return NULL; cf_str2upper(s); link = cf_newLink(sizeof(pf_rec)); if (link==NULL || link->data==NULL) return NULL; pf_rec_a2b(s, (pf_rec *) link->data, "I"); link->kind = CF_KIND_REC; return link; } cf_Out *cf_initOut(char *fs, char *ts, int ty, int fm) /******************************************************************************\ * cf_Out *cf_initOut(char *fs, char *ts, int ty, int fm) * cf_initOut: allocate and initialize memory for cf_Out struct * char *fs - file specification * char *ts - time stamp * int ty - report type * int fm - report format * returns: cf_Out * - pointer to new cf_Out struct * developed by: WDRogers updated: 03-14-97 \******************************************************************************/ { cf_Out *rpt; rpt = (cf_Out *) cf_malloc(sizeof(cf_Out)); strcpy(rpt->spec, fs); /* file spec */ rpt->file = NULL; /* file pointer */ rpt->line = 0; /* line number */ rpt->page = 1; /* page number */ rpt->time = ts; /* time stamp */ rpt->type = ty; /* report type */ rpt->form = fm; /* format */ rpt->wide = 1; /* width */ rpt->diff = 0; /* difference */ return rpt; } float cf_getRating(pf_rec *n, int tx, char *code) /******************************************************************************\ * float cf_getRating(pf_rec *n, int tx, char *code) * cf_getRating: return branch rating based on type and usage code * pf_rec *n - pointer to branch record * int tx - use 0 for outage conditions, 1 for basecase conditions * char *code - pointer to destination for rating code character: N, T, B, or E * returns: float - branch rating * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { float nom, thm, btl, emr; nom = n->i.branch.total_rating; thm = n->i.branch.thermal_rating; btl = n->i.branch.bottleneck_rating; emr = n->i.branch.emergency_rating; if (n->i.branch.type[0]!='T') emr = 0; if (thm==0 && btl==0 && emr==0) { *code = 'N'; return nom; } if (thm >0 && btl==0 && emr==0) { *code = 'T'; return thm; } if (thm==0 && btl >0 && emr==0) { *code = 'B'; return btl; } if (thm==0 && btl==0 && emr >0) { *code = 'E'; return emr; } if (n->i.branch.type[0]=='T' && tx==0) { /* TX look at btl and emr if tx==0 */ if (btl==0 && emr >0) { *code = 'E'; return emr; } if (btl >0 && emr==0) { *code = 'B'; return btl; } if (btl >0 && btl<=emr) { *code = 'B'; return btl; } if (emr >0 && emr<=btl) { *code = 'E'; return emr; } } if (n->i.branch.type[0]=='T' && tx==1) { /* TX look at btl,emr,&thm if tx==1*/ if (thm >0 && btl >0 && emr >0) { if (btl<=thm && btl<=emr) { *code = 'B'; return btl; } if (emr<=thm && emr<=btl) { *code = 'E'; return emr; } if (thm<=btl && thm<=emr) { *code = 'T'; return thm; } } if (thm >0 && btl >0 && emr==0) { if (btl<=thm) { *code = 'B'; return btl; } if (thm<=btl) { *code = 'T'; return thm; } } if (thm >0 && btl==0 && emr >0) { if (emr<=thm) { *code = 'E'; return emr; } if (thm<=emr) { *code = 'T'; return thm; } } if (thm==0 && btl >0 && emr >0) { if (btl<=emr) { *code = 'B'; return btl; } if (emr<=btl) { *code = 'E'; return emr; } } } else { /* LINES look at btl and thm, emr=0 */ if (btl >0 && btl<=thm) { *code = 'B'; return btl; } if (thm >0 && thm<=btl) { *code = 'T'; return thm; } } *code = ' '; return 0; } float cf_getLoad(pf_rec *n) /******************************************************************************\ * float cf_getLoad(pf_rec *n) * cf_getLoad: return branch total branch loading based on type * pf_rec *n - pointer to branch record * returns: float - branch loading in MVA (for Tx) or Amps (for Lines) * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { float load; if (n->i.branch.type[0]=='T') { load = n->s.branch.tot_xfmr_load_mva; } else { load = n->s.branch.tot_line_load_amps; } return load; } int cf_printGroup(FILE *fp, Link *list, cf_Style style, char *tag) /******************************************************************************\ * int cf_printGroup(FILE *fp, Link *list, cf_Style style, char *tag) * cf_printGroup: convert and print formated data in a linked list of groups * groups could be a linked list of change records (for a common-mode outage) or * a branches (for a cut-plane) * FILE *fp - pointer to output file * Link *list - pointer to top of list to be printed * cf_Style style - struct containing control signals for printing link data * char *tag - character string heading for list of Group * returns: int - number of carriage returns printed to file fp * developed by: WDRogers updated: 03-05-97 \******************************************************************************/ { int n_cr = 0; Link *link; if (list==NULL || (list!=NULL && list->kind!=CF_KIND_TAG)) n_cr = cf_printTag(fp, list, style, tag); for (; list!=NULL; list=list->next) { if (list->kind==CF_KIND_LINK) { n_cr += cf_printList(fp,(Link *) list->data, style, ""); } /* modified 3-5-97: cf_printList no longer inherits tag from above */ else { n_cr += cf_printLink(fp, list); } } return n_cr; } int cf_printList(FILE *fp, Link *list, cf_Style style, char *tag) /******************************************************************************\ * int cf_printList(FILE *fp, Link *list, cf_Style style, char *tag) * cf_printList: convert and print formated data in a linked list * FILE *fp - pointer to output file * Link *list - pointer to top of list to be printed * cf_Style style - struct containing control signals for printing link data * char *tag - character string heading for list * returns: int - number of carriage returns printed to file fp * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { int n_cr = 0, n_more; Link *link; if (list==NULL || (list!=NULL && list->kind!=CF_KIND_TAG)) n_cr = cf_printTag(fp, list, style, tag); for (n_more = 0; list!=NULL; list=list->next) { if (n_more==0) n_more = style.limit; if (n_more==style.limit) fprintf(fp, style.indent); link = (Link *) ( list->kind==CF_KIND_LINK ? list->data : list ); n_cr += cf_printLink(fp, link); if (list->next!=NULL && --n_more>0) { fprintf(fp, ", "); } else { fprintf(fp, "\n"); n_cr++; } } return n_cr; } int cf_printLink(FILE *fp, Link *link) /******************************************************************************\ * int cf_printLink(FILE *fp, Link *link) * cf_printLink: convert and print data contents of link according to Link kind * FILE *fp - pointer to output file * Link *link - pointer to Link that contains data for printing * returns: int - number of carriage returns printed to file fp * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { char data[CF_INBUFSIZE]; int cr; /* carriage return */ pf_rec r; cr = 0; if (link==NULL) return 0; if (link->kind==CF_KIND_STR) { cr = cf_cntchr(link->data, '\n'); fprintf(fp, link->data); } else if (link->kind==CF_KIND_FLT) { sprintf(data, "%f", (float *) link->data); fprintf(fp, data); } else if (link->kind==CF_KIND_INT) { sprintf(data, "%d", (int *) link->data); fprintf(fp, data); } else if (link->kind==CF_KIND_BUS) { cf_bus2rec((cf_Bus *) link->data, &r); pf_rec_b2a(data, &r, "I"); fprintf(fp, "%20.20s", data); } else if (link->kind==CF_KIND_BRN) { cf_branch2rec((cf_Branch *) link->data, &r); pf_rec_b2a(data, &r, "I"); fprintf(fp, "%33.33s", data); } else if (link->kind==CF_KIND_REC) { pf_rec_b2a(data, (pf_rec *) link->data, "I"); if (data[0]=='B') fprintf(fp, "%20.20s", data); else fprintf(fp, "%33.33s", data); } else if (link->kind==CF_KIND_TAG) { cr = cf_cntchr(link->data, '\n'); fprintf(fp, link->data); } else if (link->kind==CF_KIND_NAME) { cr = cf_cntchr(((cf_Name *) link->data)->name, '\n'); fprintf(fp, ((cf_Name *)link->data)->name); } else if (link->kind==CF_KIND_GEN) { sprintf(data, " %7.1f %7.1f %7.1f", ((cf_Gen *)link->data)->start, ((cf_Gen *)link->data)->stop, ((cf_Gen *)link->data)->step); fprintf(fp, data); } else if (link->kind==CF_KIND_SF2) { sprintf(data, " %s %7.1f %7.1f", ((cf_StrFlt2 *)link->data)->file, ((cf_StrFlt2 *)link->data)->flt1, ((cf_StrFlt2 *)link->data)->flt2); fprintf(fp, data); } else if (link->kind==CF_KIND_STRSTR) { sprintf(data, " %s %s", ((cf_StrStr *)link->data)->str1, ((cf_StrStr *)link->data)->str2); fprintf(fp, data); } return cr; } int cf_printTag(FILE *fp, Link *list, cf_Style style, char *tag) /******************************************************************************\ * int cf_printTag(FILE *fp, Link *list, cf_Style style, char *tag) * cf_printTag: print tag string based on value of style and list * FILE *fp - pointer to output file * Link *list - pointer to a Link in a list * cf_Style style - struct containing control signals for printing tag * char *tag - string to print * returns: int - number of carriage returns printed to file fp * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { int cr = 0; /* carriage return */ if (list!=NULL || style.mode==CF_TAG_ALWAYS) { cr = cf_cntchr(tag, '\n'); fprintf(fp, tag); if (list==NULL && cr==0 && style.mode==CF_TAG_ALWAYS) fprintf(fp, "\n"); } return cr; } char *cf_link2tagName(Link *link, char *name) /******************************************************************************\ * char *cf_link2tagName(Link *link, char *name) * cf_link2tagName: scan data from Link of kind CF_KIND_TAG into name * Link *link - pointer to link of kind CF_KIND_TAG * char *name - destination string scanned contents of Link data * expected data format is "> keyword id string" where "id string" is copied * into name[]. * returns: Link * - pointer to link data * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { sscanf(link->data, ">%*s %[^\n]", name); return link->data; } Link *cf_tag2link(char *s) /******************************************************************************\ * Link *cf_tag2link(char *s) * cf_tag2link: make a new Link of kind CF_KIND_TAG. * char *s - string to be copied into Link data array. * calls: Link *cf_newLink(size_t); * returns: Link * - pointer to new Link or NULL if none formed. * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { Link *link; link = cf_newLink(strlen(s)+1); if (link==NULL || link->data==NULL) return NULL; strcpy(link->data, s); link->kind = CF_KIND_TAG; return link; } void cf_fillGroup(char *mstrSpec, Link **grpList, char *key) /******************************************************************************\ * void cf_fillGroup(char *mstrSpec, Link **grpList, char *key) * cf_fillGroup: build a list of linked groups from input file * groups could be a linked list of change records (for a common-mode outage) or * a branches (for a cut-plane) * look for input strings with this format: "> groupkey group id name" * char *mstrSpec - file specification of master data file for group data * Link **grpList - pointer to pointer to top of list of groups to fill or create * char *key - string containing group key word identifier * returns: void * developed by: WDRogers updated: 02-04-97 \******************************************************************************/ { char s[CF_STRSIZE], curName[CF_STRSIZE]; Link *curGroup, *curTag, *link, *row, *list; FILE *mstrFile; int def = 1, mode = 0; if ( strlen(mstrSpec)==0 ) { return; } if ((mstrFile = cf_openFile(mstrSpec, "r"))==NULL) return; if (*grpList==NULL) { /* read in all groups */ rewind(mstrFile); while ( fgets(s, CF_STRSIZE, mstrFile) != NULL ) { if ( s[0] == '.' ) continue; /* skip comments, skip data */ if (cf_isblank(s)) continue; cf_str2upper(s); cf_strsub(s, "\n", '\0'); if (strstr(s, key)) { /* key word */ printf("cf_fillGroup found: %s\n", s); link = cf_tag2link(s); row = cf_link2row(link); cf_appList(grpList, row); list = (Link *) row->data; continue; } else { if (list==NULL) { sprintf(curName, "> %s cut #%d", key, def++); link = cf_tag2link(curName); row = cf_link2row(link); cf_appList(grpList, row); list = (Link *) row->data; } if (strcmp(key, "CUT-PLANE")==0) link = cf_rec2Link(s); else if (strcmp(key, "MODE")==0) link = cf_text2Link(s); cf_appList(&list, link); } } } else { /* *grpList != NULL */ printf(" Filling group from master file: %s\n", mstrSpec); for (curGroup = *grpList ; curGroup!=NULL; curGroup = curGroup->next ) { curTag = (Link *) curGroup->data; if (curTag->next!=NULL) continue; /* already filled */ cf_link2tagName(curTag, curName); rewind(mstrFile); while (fgets(s, CF_STRSIZE, mstrFile)!=NULL) { if ( s[0] == '.' ) continue; /* skip comments */ if (cf_isblank(s)) continue; cf_str2upper(s); cf_strsub(s, "\n", '\0'); if (strstr(s, key)) { if (strstr(s, curName)!=NULL) { mode = 1; /* filling group */ printf("cf_fillGroup found: %s\n", s); } else mode = 0; /* wrong group */ continue; } else if (mode==1) { if (strcmp(key, "CUT-PLANE")==0) link = cf_rec2Link(s); else if (strcmp(key, "MODE")==0) link = cf_text2Link(s); cf_appList(&curTag, link); } } if (curTag->next==NULL) printf("cf_fillGroup can't find %s\n", curName); } } } void cf_insLink(Link **top, Link **cur, Link *new, long sort, int mode, int (*cmp)(Link *, Link *, int)) /******************************************************************************\ * void cf_insLink(Link **top, Link **cur, Link *new, int sort, int mode, * int (*cmp)(Link *, Link *, int)); * cf_insLink: insert Link into list in sorted order * Link **top - pointer to pointer to top Link in list * Link **cur - pointer to pointer to previously added Link (point of insertion) * Link *new - pointer to new Link to add to list * long sort - long int or pointer to sort criteria: (trace *), trace->sort, etc. * int mode - integer determining what to do when cur and new links are the same * for the compare==0 case, one could invision skip, insert, replace, overwrite, * or secondary sort as valid responses. * int (*cmp)(Link *, Link *, int) - pointer to function comparing two Links * calls: cf_insAfter, cf_insBefore, cf_freeRow * returns: void * developed by: WDRogers updated: 03-27-97 \******************************************************************************/ { int comp, last; last = 0; while (1) { if ((*cur)==NULL) { (*top) = new; break; } comp = (*cmp)(new, (*cur), sort); if ( comp < 0 ) { if ((*cur)->prev==NULL || last>0) { cf_insBefore(cur, &new, top); /* insert new before cur or at top */ break; } else { (*cur) = (*cur)->prev; /* move backward */ last = comp; } } else if (comp==0 ) { switch (mode) { case CF_INS_FREE : cf_freeRow(new); new = (*cur); break; case CF_INS_AFTER : cf_insAfter(cur, &new); break; case CF_INS_BEFORE : cf_insBefore(cur, &new, top); break; case CF_INS_SKIP : new = (*cur); break; default : new = (*cur); break; } break; } else if (comp > 0) { if ((*cur)->next==NULL || last<0) { cf_insAfter(cur, &new); /* insert new after cur or at end */ break; } else { (*cur) = (*cur)->next; /* move foreward */ last = comp; } } } (*cur) = new; } void cf_insBefore(Link **cur, Link **new, Link **top) /******************************************************************************\ * void cf_insBefore(Link **cur, Link **new, Link **top) * cf_insBefore: insert new Link before current Link or at top of list * Link **cur - pointer to pointer to previously added Link (point of insertion) * Link **new - pointer to pointer to new Link to add to list * Link **top - pointer to pointer to top Link in list * returns: void * developed by: WDRogers updated: 03-14-97 \******************************************************************************/ { if ((*cur)->prev==NULL) (*top) = (*new); (*new)->next = (*cur); (*new)->prev = (*cur)->prev; if ((*cur)->prev!=NULL) (*cur)->prev->next = (*new); (*cur)->prev = (*new); } void cf_insAfter(Link **cur, Link **new) /******************************************************************************\ * void cf_insAfter(Link **cur, Link **new) * cf_insAfter: insert new Link after current Link or at end of list * Link **cur - pointer to pointer to previously added Link (point of insertion) * Link **new - pointer to pointer to new Link to add to list * returns: void * developed by: WDRogers updated: 03-14-97 \******************************************************************************/ { (*new)->prev = (*cur); (*new)->next = (*cur)->next; if ((*cur)->next!=NULL) (*cur)->next->prev = (*new); (*cur)->next = (*new); } int cx_printList(FILE *fp, Link *list, char *tag, char *indent, char type, char *fmt, int n) /******************************************************************************\ * int cx_printList(FILE *fp, Link *list, char *tag, char *indent, char type, * char *fmt, int n); * cx_printList: convert and print formated data in a linked list * FILE *f - pointer to file * Link *list - pointer to top of list to be printed * char *tag - character string heading for list * char *indent - indentation string * char type - type of data to be printed * P,p - primitive(string, float,...), 'P' - list->link->data, 'p' - link->data * B,b - cf_Bus 'B' - list->link->data, 'b' - link->data * L,l - cf_Branch 'L' - list->link->data, 'l' - link->data * R,r - pf_rec 'R' - list->link->data, 'r' - link->data * char *fmt - format string for printing data * int n - fabs(n) is the number of links to print per row; * n<0 - if no items in list (list==NULL) then don't print tag, else print tag * n>0 - always print tag * calls: cf_cntchr, cf_bus2rec, cf_branch2rec, pf_rec_b2a * returns: int - number of lines printed (carriage returns). * developed by: WDRogers updated: 10-30-96 \******************************************************************************/ { int i, cr; pf_rec r; Link *link; char data[CF_INBUFSIZE]; if (list==NULL && n<0) return 0; cr = cf_cntchr(tag, '\n'); if (list==NULL) { fprintf(fp, tag); if (tag[strlen(tag)-1]!='\n') { fprintf(fp, "\n"); cr++; } return cr; } else { /* list != NULL */ fprintf(fp, tag); } n = (int) fabs(n); for (i=n; list!=NULL; list=list->next) { if (i==0) i = n; if (i==n) fprintf(fp, indent); link = (Link *) ( isupper(type) ? list->data : list ); if (toupper(type)=='P') { /* 'P' - list->link->data, 'p' - link->data */ strcpy(data, (char *) link->data); } if (toupper(type)=='B') { /* 'B' - list->link->data, 'b' - link->data */ cf_bus2rec((cf_Bus *) link->data, &r); pf_rec_b2a(data, &r, "I"); } if (toupper(type)=='L') { /* 'L' - list->link->data, 'l' - link->data */ cf_branch2rec((cf_Branch *) link->data, &r); pf_rec_b2a(data, &r, "I"); } if (toupper(type)=='R') { /* 'R' - list->link->data, 'r' - link->data */ pf_rec_b2a(data, (pf_rec *) link->data, "I"); } fprintf(fp, fmt, data); if (list->next!=NULL && n!=1 && --i>0) { fprintf(fp, ", "); } else { fprintf(fp, "\n"); cr++; } } return cr; } int cx_printRowList(FILE *fp, Link *row, char *list_tag, char *row_tag, char type, char *fmt, int n) /******************************************************************************\ * int cx_printRowList(FILE *fp, Link *list, char *list_tag, char *row_tag, * char type, char *fmt, int n) * cx_printRowList: convert and print formated data in a linked list of rows * FILE *fp - pointer to output file * Link *row - pointer to top row in list of rows to be printed * char *list_tag - character string heading for list of rows * char *row_tag - character string separating each row list * char type - type of data to be printed, as follows: * P,p - primitive(string, float,...), 'P' - list->link->data, 'p' - link->data * B,b - cf_Bus 'B' - list->link->data, 'b' - link->data * L,l - cf_Branch 'L' - list->link->data, 'l' - link->data * R,r - pf_rec 'R' - list->link->data, 'r' - link->data * char *fmt - format string for printing data * int n - fabs(n) is the number of links to print per row; * n<0 - if no items in list (list==NULL) then don't print tag, else print tag * n>0 - always print tag * calls: cf_cntchr, cx_printList * returns: int - number of lines printed (carriage returns). * developed by: WDRogers updated: 12-04-96 \******************************************************************************/ { Link *list; int r; r = cf_cntchr(list_tag, '\n'); fprintf(fp, list_tag); while (row!=NULL) { list = (Link *) row->data; r += cx_printList(fp, list, row_tag, "", type, fmt, n); row = row->next; } return r; }
41.009069
135
0.552802
[ "object" ]
fd7f206ddfd639a15de483119e396a67ab7c791f
3,691
h
C
components/offline_pages/offline_page_storage_manager.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
components/offline_pages/offline_page_storage_manager.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
components/offline_pages/offline_page_storage_manager.h
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_OFFLINE_PAGES_OFFLINE_PAGE_STORAGE_MANAGER_H_ #define COMPONENTS_OFFLINE_PAGES_OFFLINE_PAGE_STORAGE_MANAGER_H_ #include <stdint.h> #include <vector> #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "components/offline_pages/offline_page_types.h" namespace base { class Clock; } namespace offline_pages { class ClientPolicyController; // This class is used for storage management of offline pages. It provides // a ClearPagesIfNeeded method which is used to clear expired offline pages // based on last_access_time and lifetime policy of its namespace. // It has its own throttle mechanism so calling the method would not be // guaranteed to clear the pages immediately. // // OfflinePageModel should own and control the lifecycle of this manager. // And this manager would use OfflinePageModel to get/remove pages. class OfflinePageStorageManager { public: // This interface should have no knowledge of offline page model. // This interface should be implemented by clients managed by storage manager. class Client { public: virtual ~Client() {} // Asks the client to get all offline pages and invoke |callback|. virtual void GetAllPages( const MultipleOfflinePageItemCallback& callback) = 0; // Asks the client to delete pages based on |offline_ids| and invoke // |callback|. virtual void DeletePagesByOfflineId(const std::vector<int64_t>& offline_ids, const DeletePageCallback& callback) = 0; }; // Callback used when calling ClearPagesIfNeeded. // int: the number of deleted pages. // DeletePageResult: result of deleting pages. typedef base::Callback<void(int, DeletePageResult)> ClearPageCallback; explicit OfflinePageStorageManager(Client* client, ClientPolicyController* policy_controller); ~OfflinePageStorageManager(); // The manager would *try* to clear pages when called. It may not delete any // pages (if clearing condition wasn't satisfied). void ClearPagesIfNeeded(const ClearPageCallback& callback); // Sets the clock for testing. void SetClockForTesting(std::unique_ptr<base::Clock> clock); private: // Selects and removes pages that need to be expired. Triggered as a callback // to |GetAllPages|. void ClearExpiredPages(const ClearPageCallback& callback, const MultipleOfflinePageItemResult& pages); // Gets offline IDs of all expired pages and return in |offline_ids|. void GetExpiredPageIds(const MultipleOfflinePageItemResult& pages, std::vector<int64_t>& offline_ids); // Callback when expired pages has been deleted. void OnExpiredPagesDeleted(const ClearPageCallback& callback, int pages_to_clear, DeletePageResult result); // Determine if manager should clear pages. bool ShouldClearPages(); // Return true if |page| is expired comparing to |now|. bool ShouldBeExpired(const base::Time& now, const OfflinePageItem& page); // Not owned. Client* client_; // Not owned. ClientPolicyController* policy_controller_; bool in_progress_; // Clock for getting time. std::unique_ptr<base::Clock> clock_; base::WeakPtrFactory<OfflinePageStorageManager> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(OfflinePageStorageManager); }; } // namespace offline_pages #endif // COMPONENTS_OFFLINE_PAGES_OFFLINE_PAGE_STORAGE_MANAGER_H_
34.175926
80
0.733677
[ "vector", "model" ]
fd846efe4340cfa20df0e6431293ca8c4537feff
11,502
h
C
include/arboretum/stRNode-inl.h
marcosivni/arboretum
329147b2d147903bc8e527fc3dcfe2349141725a
[ "Apache-2.0" ]
null
null
null
include/arboretum/stRNode-inl.h
marcosivni/arboretum
329147b2d147903bc8e527fc3dcfe2349141725a
[ "Apache-2.0" ]
null
null
null
include/arboretum/stRNode-inl.h
marcosivni/arboretum
329147b2d147903bc8e527fc3dcfe2349141725a
[ "Apache-2.0" ]
null
null
null
/* Copyright 2003-2017 GBDI-ICMC-USP <caetano@icmc.usp.br> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * * This file implements the RTree nodes. */ //------------------------------------------------------------------------------ // class stRNode //------------------------------------------------------------------------------ stRNode * stRNode::CreateNode(stPage * page){ stRNode::stRNodeHeader * header; header = (stRNodeHeader *)(page->GetData()); switch (header->Type){ case INDEX: // Create an index page return new stRIndexNode(page, false); case LEAF: // Create a leaf page return new stRLeafNode(page, false); default: return NULL; }//end switch }//end stRNode::CreateNode() //------------------------------------------------------------------------------ // class stRIndexNode //------------------------------------------------------------------------------ stRIndexNode::stRIndexNode(stPage * page, bool create): stRNode(page){ // Attention to this manouver! It is the brain of this // implementation. Entries = (stRIndexEntry *)(page->GetData() + sizeof(stRNodeHeader)); // Initialize page if (create){ #ifdef __stDEBUG__ Page->Clear(); #endif //__stDEBUG__ this->Header->Type = INDEX; this->Header->Occupation = 0; }//end if }//end stRIndexNode::stRIndexNode() //------------------------------------------------------------------------------ int stRIndexNode::AddEntry(u_int32_t size, const unsigned char * object){ u_int32_t entrySize; // Does it fit ? entrySize = size + sizeof(stRIndexEntry); if (entrySize > this->GetFree()){ // No, it doesn't. return -1; }//end if // Ok. I can put it. Lets put it in the last position. // Adding the object. Take care with these pointers or you will destroy the // node. The idea is to put the object of an entry in the reverse order // in the data array. if (Header->Occupation == 0){ Entries[Header->Occupation].Offset = Page->GetPageSize() - size; }else{ Entries[Header->Occupation].Offset = Entries[Header->Occupation - 1].Offset - size; }//end if memcpy((void *)(Page->GetData() + Entries[Header->Occupation].Offset), (void *)object, size); // Update # of entries Header->Occupation++; // One more! return Header->Occupation - 1; }//end stRIndexNode::AddEntry() //------------------------------------------------------------------------------ const unsigned char * stRIndexNode::GetObject(u_int32_t idx){ #ifdef __stDEBUG__ if (idx >= GetNumberOfEntries()){ throw std::logic_error("idx value is out of range."); }//end if #endif //__stDEBUG__ return Page->GetData() + Entries[idx].Offset; }//end stRIndexNode::GetObject() //------------------------------------------------------------------------------ u_int32_t stRIndexNode::GetObjectSize(u_int32_t idx){ #ifdef __stDEBUG__ if (idx >= GetNumberOfEntries()){ throw std::logic_error("idx value is out of range."); }//end if #endif //__stDEBUG__ if (idx == 0){ // First object return Page->GetPageSize() - Entries[0].Offset; }else{ // Any other return Entries[idx - 1].Offset - Entries[idx].Offset; }//end if }//end stRIndexNode::GetObjectSize() //------------------------------------------------------------------------------ void stRIndexNode::RemoveEntry(u_int32_t idx){ u_int32_t rObjSize; u_int32_t i, lastID; // Programmer's note: This procedure is simple but tricky! See the // RIndexNode structure documentation for more details. #ifdef __stDEBUG__ if (idx >= GetNumberOfEntries()){ // Oops! This idx doesn't exists. throw range_error("idx is out of range."); }//end if #endif //__stDEBUG__ // Let's remove lastID = Header->Occupation - 1; // The idx of the last object. This // value will be very useful. // Do I need to move something ? if (idx != lastID){ // Yes, I do. rObjSize = GetObjectSize(idx); // Save the removed object size // Let's move objects first. We will use memmove() from stdlib because // it handles the overlap between src and dst. Remember that src is the // offset of the last object and the dst is the offset of the last // object plus removed object size. memmove(Page->GetData() + Entries[lastID].Offset + rObjSize, Page->GetData() + Entries[lastID].Offset, Entries[idx].Offset - Entries[lastID].Offset); // Let's move entries... for (i = idx; i < lastID; i++){ // Copy all fields with memcpy (it's faster than field copy). memcpy(Entries + i, Entries + i + 1, sizeof(stRIndexEntry)); // Update offset by adding the removed object size to it. It will // reflect the previous move operation. Entries[i].Offset += rObjSize; }//end for }//end if // Update counter... Header->Occupation--; }//end stRIndexNode::RemoveEntry() //------------------------------------------------------------------------------ u_int32_t stRIndexNode::GetFree(){ u_int32_t usedsize; // Fixed size usedsize = sizeof(stRNodeHeader); // Entries if (GetNumberOfEntries() > 0){ usedsize += // Total size of entries (sizeof(stRIndexEntry) * GetNumberOfEntries()) + // Total object size (Page->GetPageSize() - Entries[GetNumberOfEntries() - 1].Offset); }//end if return Page->GetPageSize() - usedsize; }//end stRIndexNode::GetFree() //------------------------------------------------------------------------------ u_int32_t stRIndexNode::GetTotalObjectCount(){ u_int32_t count; u_int32_t i; count = 0; for (i = 0; i < GetNumberOfEntries(); i++){ count += GetIndexEntry(i).NEntries; }//end for return count; }//end stRIndexNode::GetTotalObjectCount //------------------------------------------------------------------------------ // class stRLeafNode //------------------------------------------------------------------------------ stRLeafNode::stRLeafNode(stPage * page, bool create): stRNode(page){ // Attention to this manouver! It is the brain of this // implementation. Entries = (stRLeafEntry*)(page->GetData() + sizeof(stRNodeHeader)); // Initialize page if (create){ #ifdef __stDEBUG__ Page->Clear(); #endif //__stDEBUG__ this->Header->Type = LEAF; this->Header->Occupation = 0; }//end if }//end stRLeafNode::stRLeafNode() //------------------------------------------------------------------------------ int stRLeafNode::AddEntry(u_int32_t size, const unsigned char * object){ u_int32_t entrySize; #ifdef __stDEBUG__ if (size == 0){ throw std::logic_error("The object size is 0."); }//end if #endif //__stDEBUG__ // Does it fit ? entrySize = size + sizeof(stRLeafEntry); if (entrySize > this->GetFree()){ // No, it doesn't. return -1; }//end if // Ok. I can put it. Lets put it in the last position. // Adding the object. Take care with these pointers or you will destroy the // node. The idea is to put the object of an entry in the reverse order // in the data array. if (Header->Occupation == 0){ Entries[Header->Occupation].Offset = Page->GetPageSize() - size; }else{ Entries[Header->Occupation].Offset = Entries[Header->Occupation - 1].Offset - size; }//end if memcpy((void *)(Page->GetData() + Entries[Header->Occupation].Offset), (void *)object, size); // Update # of entries Header->Occupation++; // One more! return Header->Occupation - 1; }//end stRLeafNode::AddEntry() //------------------------------------------------------------------------------ const unsigned char * stRLeafNode::GetObject(u_int32_t idx){ #ifdef __stDEBUG__ if (idx >= GetNumberOfEntries()){ throw std::logic_error("idx value is out of range."); }//end if #endif //__stDEBUG__ return Page->GetData() + Entries[idx].Offset; }//end stRLeafNode::GetObject() //------------------------------------------------------------------------------ u_int32_t stRLeafNode::GetObjectSize(u_int32_t idx){ #ifdef __stDEBUG__ if (idx >= GetNumberOfEntries()){ throw std::logic_error("idx value is out of range."); }//end if #endif //__stDEBUG__ if (idx == 0){ // First object return Page->GetPageSize() - Entries[0].Offset; }else{ // Any other return Entries[idx - 1].Offset - Entries[idx].Offset; }//end if }//end stRLeafIndexNode::GetObjectSize() //------------------------------------------------------------------------------ void stRLeafNode::RemoveEntry(u_int32_t idx){ u_int32_t lastID; u_int32_t i; u_int32_t rObjSize; // Programmer's note: This procedure is simple but tricky! See the // RIndexNode structure documentation for more details. #ifdef __stDEBUG__ if (idx >= GetNumberOfEntries()){ // Oops! This idx doesn't exists. throw range_error("idx value is out of range."); }//end if #endif //__stDEBUG__ // Let's remove lastID = Header->Occupation - 1; // The idx of the last object. This // value will be very useful. // Do I need to move something ? if (idx != lastID){ // Yes, I do. rObjSize = GetObjectSize(idx); // Save the removed object size // Let's move objects first. We will use memmove() from stdlib because // it handles the overlap between src and dst. Remember that src is the // offset of the last object and the dst is the offset of the last // object plus removed object size. memmove(Page->GetData() + Entries[lastID].Offset + rObjSize, Page->GetData() + Entries[lastID].Offset, Entries[idx].Offset - Entries[lastID].Offset); // Let's move entries... for (i = idx; i < lastID; i++){ // Copy all fields with memcpy (it's faster than field copy). memcpy(Entries + i, Entries + i + 1, sizeof(stRLeafEntry)); // Update offset by adding the removed object size to it. It will // reflect the previous move operation. Entries[i].Offset += rObjSize; }//end for }//end if // Update counter... Header->Occupation--; }//end stRLeafNode::RemoveEntry //------------------------------------------------------------------------------ u_int32_t stRLeafNode::GetFree(){ u_int32_t usedSize; // Fixed size usedSize = sizeof(stRNodeHeader); // Entries if (GetNumberOfEntries() > 0){ usedSize += // Total size of entries (sizeof(stRLeafEntry) * GetNumberOfEntries()) + // Total object size (Page->GetPageSize() - Entries[GetNumberOfEntries() - 1].Offset); }//end if return Page->GetPageSize() - usedSize; }//end stRLeafNode::GetFree()
33.631579
96
0.56338
[ "object" ]
fd8d5ba4e5a20d5d0ee3d789d5253fc874cd5be8
3,354
h
C
Computational_Geometry/src/GUI/GUI.h
manuelpagliuca/Computational_Geometry_2021
45560d464f25959d058aaf14d4084e9d894072f4
[ "MIT" ]
null
null
null
Computational_Geometry/src/GUI/GUI.h
manuelpagliuca/Computational_Geometry_2021
45560d464f25959d058aaf14d4084e9d894072f4
[ "MIT" ]
null
null
null
Computational_Geometry/src/GUI/GUI.h
manuelpagliuca/Computational_Geometry_2021
45560d464f25959d058aaf14d4084e9d894072f4
[ "MIT" ]
null
null
null
#pragma once #pragma warning(push, 0) #include "../../Dependencies/imgui/imgui_impl_glfw.h" #include "../../Dependencies/imgui/imgui_impl_opengl3.h" #include "../../Dependencies/imgui/imgui.h" #include <GLM/glm.hpp> #include <GLM/gtc/matrix_transform.hpp> #include <GLM/gtc/type_ptr.hpp> #pragma warning(pop) #include <map> #include <iostream> #include <vector> #include <fstream> #include "../Shader/Shader.h" /* editable radiuses from user for the subdivided m_vertices (middlepoint) */ struct MiddlepointsRadius { float v1{ 1.f }; float v2{ 1.f }; float v3{ 1.f }; }; /* Params of the objects in the GUI */ struct ObjectGUIParams { bool toVisualize{ false }; int selectedShader{ 0 }; /* Affine Transfomations */ float xScale{ 1.0f }; float yScale{ 1.0f }; float zScale{ 1.0f }; float overallScale{ 1.0f }; float xRot{ 0.f }; float yRot{ 0.f }; float zRot{ 0.f }; bool autoRotX{ false }; bool autoRotY{ false }; bool autoRotZ{ false }; float rotSpeed{ 0.f }; float increment{ 0.f }; float xPos{ 0.f }; float yPos{ 0.f }; float zPos{ -2.5f }; /* barycentric color, 0-red 1-green 2-blue */ int channelOrder{ 0 }; int x_tess_color{ 0 }; int y_tess_color{ 1 }; int z_tess_color{ 2 }; struct { MiddlepointsRadius midpointRadius; int subdivisionLevel{ 0 }; float radius{ 1.f }; }icosahedron; struct { int sectorCount{ 3 }; int stackCount{ 1 }; float baseRadius{ 1.f }; float topRadius{ 1.f }; float height{ 1.f }; }prism; struct { float mainRadius{ 0.5f }; float tubeRadius{ 0.2f }; int mainSegments{ 20 }; int tubeSegments{ 20 }; }torus; /* colors */ int colorMode{ 0 }; glm::vec4 pickedColor = glm::vec4(1.0f, 1.0f, 0.0f, 1.0f); }; /* editable data from user for tessellation */ struct TessellationGUIParams { int selectedShader{ 1 }; int outerLevel1{ 1 }; int outerLevel2{ 1 }; int outerLevel3{ 1 }; int outerLevel4{ 1 }; int innerLevel1{ 1 }; int innerLevel2{ 1 }; bool wireframeMode{ false }; }; namespace GUI_OBJ { constexpr unsigned int CUBE = 0U; constexpr unsigned int PYRAMID = 1U; constexpr unsigned int ICOSAHEDRON = 2U; constexpr unsigned int PRISM = 3U; constexpr unsigned int TORUS = 4U; }; class GUI { public: GUI() { checkCache(); } GUI(float t_aspectRatio, int t_width, int t_height) : m_aspectRatio{ t_aspectRatio }, m_width{ t_width }, m_height{ t_height } { checkCache(); } ~GUI(); void setupContext(GLFWwindow* m_window) const; void initFrame() const; void renderData() const; void destroyContext() const; void objectsPanel(); void tessPanel(); void shaderPanel(); void menuBar(); void checkCache(); bool* getCache() const { return &m_cache; } /* getters */ std::map<int, ObjectGUIParams>& getObjectGUIParams(); const TessellationGUIParams& getTessellationGUIParams() const; private: void disableAllShapes(); /* imgui.ini */ static bool m_cache; /* m_window data */ float m_aspectRatio{}; int m_width{}; int m_height{}; /* handle objects panel*/ int m_objectsIndices{ 0 }; int const labelSpace = 300; int const labelTitles = 170; /* hold objects GUI params */ std::map<int, ObjectGUIParams> m_objectParams{}; /* handle tess panel */ bool m_tessAllLevels{ false }; int m_stepSize{ 1 }; /* hold tess GUI params*/ TessellationGUIParams m_tessParams{}; /******/ int selection{ 0 }; };
19.387283
127
0.678891
[ "vector" ]
fd9111016181e74e138391fd764a805d652f2c58
4,087
c
C
mosaic.c
ArthurFerreira2/mosaic
742b9223281a0f85d417fe9ee1a631502fb5fb5b
[ "MIT" ]
null
null
null
mosaic.c
ArthurFerreira2/mosaic
742b9223281a0f85d417fe9ee1a631502fb5fb5b
[ "MIT" ]
null
null
null
mosaic.c
ArthurFerreira2/mosaic
742b9223281a0f85d417fe9ee1a631502fb5fb5b
[ "MIT" ]
null
null
null
/* mosaic image effect Last modified 17th of January 2019 Copyright (c) 2019 Arthur Ferreira 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. */ // usage : mosaic <bmp filename> <numbers of blocks> <max block size> [collide] // last argument is optionnal and can be any string - if set the blocks won't overlap // example : mosaic lena.bmp 200000 6 // mosaic lena.bmp 70000 6 whyNot #include <stdlib.h> #include <SDL2/SDL.h> SDL_bool collide(SDL_Rect r1, SDL_Rect r2){ if (r1.x + r1.w < r2.x || r1.x > r2.x + r2.w) return SDL_FALSE; if (r1.y + r1.h < r2.y || r1.y > r2.y + r2.h) return SDL_FALSE; return SDL_TRUE; } Uint32 getPixel(SDL_Surface *surface, int x, int y){ int depth = surface->format->BytesPerPixel; Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * depth; if (depth == 3) { if (SDL_BYTEORDER == SDL_BIG_ENDIAN) return p[0] << 16 | p[1] << 8 | p[2]; else return p[0] | p[1] << 8 | p[2] << 16; } if (depth == 1) return *p; if (depth == 2) return *(Uint16 *)p; if (depth == 4) return *(Uint32 *)p; return 0; } int main(int argc, char **argv){ SDL_Init(SDL_INIT_VIDEO); SDL_Surface *surface = SDL_LoadBMP(argv[1]); Uint32 width = surface->w; Uint32 height = surface->h; SDL_Window *wdo = SDL_CreateWindow(argv[1], SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, 0); SDL_Renderer *rdr = SDL_CreateRenderer(wdo, -1, SDL_RENDERER_ACCELERATED); SDL_Event event; Uint32 squaresNum = atoi(argv[2]); Uint8 squareSize = atoi(argv[3]) ; if (squareSize < 2) squareSize = 2; Uint8 noColide = (argc==5) ? 1 : 0; SDL_Rect *squares = malloc(squaresNum * sizeof(SDL_Rect)); Uint8 R, G, B; Uint32 color; for (int i=0; i<squaresNum; i++){ squares[i].w = rand() % (squareSize -1) + 1; squares[i].h = squares[i].w; squares[i].x = rand() % width - squares[i].w / 2; squares[i].y = rand() % height - squares[i].h / 2; if (noColide) // user requested no collision for (int j=0; j<i; j++) // test collision with all existing squares if (collide(squares[i], squares[j])) { squaresNum--; i--; break; } color = getPixel(surface, squares[i].x + (squares[i].w / 2), squares[i].y + (squares[i].h / 2)); SDL_GetRGB(color, surface->format, &R, &G, &B); SDL_SetRenderDrawColor(rdr, R, G, B, 255); SDL_RenderFillRect(rdr, &squares[i]); if (!(i%1000)){ // render progress every thousand of squares SDL_RenderPresent(rdr); while(SDL_PollEvent(&event)) if (event.type==SDL_QUIT || event.type==SDL_KEYDOWN) i = squaresNum; // stop adding squares } } SDL_RenderPresent(rdr); // render final result while(SDL_TRUE) if (SDL_PollEvent(&event) && (event.type==SDL_QUIT || event.type==SDL_KEYDOWN)) break; else SDL_Delay(256); SDL_DestroyRenderer(rdr); SDL_DestroyWindow(wdo); SDL_Quit(); exit(EXIT_SUCCESS); }
34.058333
113
0.648153
[ "render" ]
fd9417cef8a85dc0e854ae4ad30eb78382ff642a
1,386
h
C
src/IO/ConcatSeekableReadBuffer.h
KinderRiven/ClickHouse
2edc03b3d4a950848720064db82f11581b2e8d8a
[ "Apache-2.0" ]
2
2022-01-10T04:50:22.000Z
2022-01-10T04:51:42.000Z
src/IO/ConcatSeekableReadBuffer.h
KinderRiven/ClickHouse
2edc03b3d4a950848720064db82f11581b2e8d8a
[ "Apache-2.0" ]
16
2022-02-14T15:53:29.000Z
2022-03-25T18:39:16.000Z
src/IO/ConcatSeekableReadBuffer.h
Vector-Similarity-Search-for-ClickHouse/ClickHouse
996d838ca33f1156a1c6d0868140bab23f8b6155
[ "Apache-2.0" ]
1
2020-05-28T07:29:23.000Z
2020-05-28T07:29:23.000Z
#pragma once #include <IO/SeekableReadBuffer.h> #include <vector> namespace DB { /// Reads from the concatenation of multiple SeekableReadBuffer's class ConcatSeekableReadBuffer : public SeekableReadBuffer, public WithFileSize { public: ConcatSeekableReadBuffer() : SeekableReadBuffer(nullptr, 0) { } ConcatSeekableReadBuffer(std::unique_ptr<SeekableReadBuffer> buf1, size_t size1, std::unique_ptr<SeekableReadBuffer> buf2, size_t size2); ConcatSeekableReadBuffer(SeekableReadBuffer & buf1, size_t size1, SeekableReadBuffer & buf2, size_t size2); void appendBuffer(std::unique_ptr<SeekableReadBuffer> buffer, size_t size); void appendBuffer(SeekableReadBuffer & buffer, size_t size); off_t seek(off_t off, int whence) override; off_t getPosition() override; std::optional<size_t> getFileSize() override { return total_size; } private: bool nextImpl() override; void appendBuffer(SeekableReadBuffer * buffer, bool own, size_t size); struct BufferInfo { BufferInfo() = default; BufferInfo(BufferInfo &&) = default; ~BufferInfo(); SeekableReadBuffer * in = nullptr; bool own_in = false; size_t size = 0; }; std::vector<BufferInfo> buffers; size_t total_size = 0; size_t current = 0; size_t current_start_pos = 0; /// Position of the current buffer's begin. }; }
29.489362
141
0.715729
[ "vector" ]
fd96dd1414954e0a7c640d49c3524ff99e0c4cd6
4,972
h
C
includes/GenICam/Usb/UsbCamera.h
yarkable/RP_Infantry_Plus
124481efd0aa94180d1cd45b0faa887187902f62
[ "MIT" ]
113
2019-08-16T10:52:27.000Z
2022-03-28T07:01:37.000Z
includes/GenICam/Usb/UsbCamera.h
RonghaoXXXu/RP_Infantry_Plus
124481efd0aa94180d1cd45b0faa887187902f62
[ "MIT" ]
null
null
null
includes/GenICam/Usb/UsbCamera.h
RonghaoXXXu/RP_Infantry_Plus
124481efd0aa94180d1cd45b0faa887187902f62
[ "MIT" ]
54
2019-08-16T08:01:09.000Z
2021-12-10T13:06:14.000Z
#ifndef __DAHUA_GENICAM_IUSBCAMERA_H__ #define __DAHUA_GENICAM_IUSBCAMERA_H__ #include "GenICam/Defs.h" #include "GenICam/Camera.h" #include "Infra/String.h" #include "Memory/SharedPtr.h" GENICAM_NAMESPACE_BEGIN class IUsbCamera; typedef Memory::TSharedPtr<IUsbCamera> IUsbCameraPtr; /// \~chinese /// \brief 相机对象接口类 /// \defgroup UsbCamera Usb相机对象操作接口 /// \~english /// \brief camera object interface class /// \defgroup UsbCamera API for U3V Cameras Only /// @{ /// \~chinese /// \brief Usb相机对象 /// \~english /// \brief Usb camera object class GENICAM_API IUsbCamera { protected: /// \~chinese /// \brief 析构函数 /// \~english /// \brief destruct function virtual ~IUsbCamera(){} public: /// \~chinese /// \brief Usb相机对象获取接口,同一个cameraPtr对应的是同一个Usb相机对象 /// \param [in] cameraPtr Usb类型的相机智能指针对象,如果传入了其它非Usb相机类型,该接口返回空指针,表示无效 /// \~english /// \brief Usb camera object access interface, same cameraPtr is correspond to same Usb camera object /// \brief [in] cameraPtr Smart pointer object of Usb camera, if the cameraPtr point to a camera which is not Usb camera, the interface return NULL which means it is invalid static IUsbCameraPtr getInstance(const ICameraPtr &cameraPtr); /// \~chinese /// \brief 获取相机的 Configuration Valid /// \return 返回相机的 Configuration Valid,失败返回NULL /// \~english /// \brief get Configuration Valid of camera /// \return success:return Configuration Valid of camera, fail:return NULL virtual const char * getConfigurationValid() = 0; /// \~chinese /// \brief 获取相机的 GenCP Version /// \return 返回相机的GenCP Version,失败返回NULL /// \~english /// \brief get subnetMask of camera /// \return success:return camera's subnetMask, fail:return NULL virtual const char * getGenCPVersion() = 0; /// \~chinese /// \brief 返回相机的U3V Version /// \return 返回相机的U3V Version,失败返回NULL /// \~english /// \brief get U3V Version of camera /// \return success:return camera's U3V Version, fail:return NULL virtual const char * getU3VVersion() = 0; /// \~chinese /// \brief 获取相机的 Device GUID /// \return 返回相机的GUID,失败返回NULL /// \~english /// \brief get Device GUID of camera /// \return success:return camera's GUID, fail:return NULL virtual const char * getDeviceGUID() = 0; /// \~chinese /// \brief 获取相机的 Family Name /// \return 返回相机的Family Name,失败返回NULL /// \~english /// \brief get Family Name of camera /// \return success:return camera's Family Name, fail:return NULL virtual const char * getFamilyName() = 0; /// \~chinese /// \brief 获取相机的序列号 /// \return 返回相机的序列号,失败返回NULL /// \~english /// \brief get serial number of camera /// \return success:return camera's serial number, fail:return NULL virtual const char * getU3VSerialNumber() = 0; /// \~chinese /// \brief 获取相机的 Low Speed Support /// \return 返回相机的 Low Speed Support /// \~english /// \brief get Low Speed Support of camera /// \return success:return camera's Low Speed Support virtual bool isLowSpeedSupported() const = 0; /// \~chinese /// \brief 获取相机的 Full Speed Support /// \return 返回相机的Full Speed Support /// \~english /// \brief get Full Speed Support of camera /// \return success:return camera's Full Speed Support virtual bool isFullSpeedSupported() const = 0; /// \~chinese /// \brief 获取相机的 High Speed Support /// \return 返回相机的 High Speed Support /// \~english /// \brief get High Speed Support of camera /// \return success:return camera's High Speed Support virtual bool isHighSpeedSupported() const = 0; /// \~chinese /// \brief 获取相机的 Super Speed Support /// \return 返回相机的 Super Speed Support /// \~english /// \brief get Super Speed Support of camera /// \return success:return camera's Super Speed Support virtual bool isSuperSpeedSupported() const = 0; /// \~chinese /// \brief 获取相机的 Speed /// \return 返回相机的 Speed,失败返回NULL /// \~english /// \brief get Speed of camera /// \return success:return camera's Speed, fail:return NULL virtual const char * getSpeed() = 0; /// \~chinese /// \brief 获取相机的 Max Power /// \return 返回相机的 Max Power,失败返回NULL /// \~english /// \brief get Max Power of camera /// \return success:return camera's Max Power, fail:return NULL virtual const char * getMaxPower() = 0; /// \~chinese /// \brief 获取相机的 Driver Installed /// \return 返回相机的 Driver Installed /// \~english /// \brief get Driver Installed of camera /// \return success:return camera's Driver Installed virtual bool isDriverInstalled() const = 0; }; /// @} GENICAM_NAMESPACE_END #endif//__DAHUA_GENICAM_IUSBCAMERA_H__
32.496732
178
0.638978
[ "object" ]
fd9801491ca3cc4a2971c7e6a0f1f74259ecf535
31,958
h
C
src/baseUI.h
virru/function-mgr
bed644c8d54c0f93f3dda35d2eb0b74f51bcdfd6
[ "MIT" ]
null
null
null
src/baseUI.h
virru/function-mgr
bed644c8d54c0f93f3dda35d2eb0b74f51bcdfd6
[ "MIT" ]
null
null
null
src/baseUI.h
virru/function-mgr
bed644c8d54c0f93f3dda35d2eb0b74f51bcdfd6
[ "MIT" ]
null
null
null
/* baseUI.h This class, baseUI, includes most GUI related content for the program, besides information dumped into text files and compile / build run time execution data. All buttons, textboxes, etc will be stored here. */ #define NOMINMAX // this is later used for iterating through data and preventing stream corruption. #pragma once #include <string> #include <iomanip> #include <iostream> #include <sstream> #include <fstream> #include <limits> #include <iterator> #include <boost/algorithm/string.hpp> // if this is not included, select the solution and go to project -> properties and then... // Go to C/C++ --> General -> Additional include directories and select the boost_1_63_0 folder. #include <msclr\marshal_cppstd.h> // used to exchange std::string data and system String ^ data. const std::string pythonKeywords[35] = { "False", "class ", "finally ", " is ", "return ", "None ", "continue ", "for ", "lambda ", "try:", "True", "def ", "from ", "nonlocal ", "while ", "else ", "import ", "pass ", "break ", "except ", "in ", "raise ", "and ", "del ", "global ", "not ", "with ", "as ", "elif ", "if ", " or ", "yield ", "assert ", "print(", "input(" }; const std::string pythonDataTypes[16] = { "int ", "str ", "float", "complex", "list(", "tuple(", "dict(", "set(", "frozenset", "chr", "unichr", "ord", "hex", "oct", "int(", "str(" }; const std::string cppKeywords[75] = { "alignas ", "alignof ", "and ", " and_eq ", "asm ", "atomic_cancel ", "atomic_commit ", "atomic_noexcept ", "bitand ", " bitor ", "break", "case:", "catch", "compl ", "concept ", "constexpr ", "const_cast ", "continue ", "decltype ", "default ", "delete ", "do ", "dynamic_cast ", "else ", "explicit ", "export ", "extern ", "false", "for(", "friend", "goto ", "if(", "import", "inline", "module", "mutable", "namespace ", "new ", "noexcept ", "not", " not_eq", "nullptr", "operator", " or", " or_eq", "private:", "protected:", "public:", "register ", "reinterpret_cast", "requires", "return ", "signed", "sizeof", "static ", "static_assert", "static_cast", "switch (", "synchronized", "template", "this-", "thread_local", "throw ", "true", "try", "typedef ", "typeid", "typename", "union", "using ", "virtual ", "volatile", "while", "xor", " xor_eq" }; const std::string cppDataTypes[20] = { "struct ", "int", "bool", "double", "float", "long", "void", "unsigned", "string", "char", "char16_t", "char32_t", "class ", " const", "short", "enum", "auto", "wchar_t", "std", "size_t" }; const std::string numberList[10] = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0" }; const std::string operatorList[20] = { "+", "-", "/", "*", ".", "&", "^", "%", "$", "=", "!", ">", "<", "|", "~", "?", ":", "__init__", "\"", "\'" }; const std::string containerList[6] = { "(", ")", "[", "]", "{", "}" }; const std::string commentList[4] = { "//", "/*", "*/", "#" }; namespace fctMgr { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// baseUI provides all interactable services (buttons, inputs, textboxes) for the user, and establishes a design. /// </summary> public ref class baseUI : public System::Windows::Forms::Form { public: baseUI(void) { InitializeComponent(); // basic constructor component } protected: ~baseUI() { if (components) { delete components; } } private: System::Windows::Forms::RichTextBox^ programText; public: System::Windows::Forms::TextBox^ nameBox; private: System::Windows::Forms::Label^ nameLabel; private: System::Windows::Forms::Label^ languageLabel; private: System::Windows::Forms::ComboBox^ languageBox; private: System::Windows::Forms::PictureBox^ divider; public: System::Windows::Forms::ListBox^ functionSelector; private: System::Windows::Forms::Label^ funtionCollectionLabel; private: System::Windows::Forms::Button^ saveButton; Color monokaiPink = Color::FromArgb(253, 151, 31); Color monokaiYellow = Color::FromArgb(249, 38, 114); Color monokaiOrange = Color::FromArgb(230, 218, 115); Color monokaiComment = Color::FromArgb(83, 78, 63); Color monokaiPurple = Color::FromArgb(102, 217, 239); Color monokaiGreen = Color::FromArgb(162, 217, 43); msclr::interop::marshal_context access; // create an alias for marshal_context access private: System::Windows::Forms::Button^ copyButton; private: System::Windows::Forms::Button^ deleteButton; private: /// <summary> /// Required designer variable for execution. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the IDE as it will mess up resx files. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(baseUI::typeid)); this->programText = (gcnew System::Windows::Forms::RichTextBox()); this->nameBox = (gcnew System::Windows::Forms::TextBox()); this->nameLabel = (gcnew System::Windows::Forms::Label()); this->languageLabel = (gcnew System::Windows::Forms::Label()); this->languageBox = (gcnew System::Windows::Forms::ComboBox()); this->divider = (gcnew System::Windows::Forms::PictureBox()); this->functionSelector = (gcnew System::Windows::Forms::ListBox()); this->funtionCollectionLabel = (gcnew System::Windows::Forms::Label()); this->saveButton = (gcnew System::Windows::Forms::Button()); this->copyButton = (gcnew System::Windows::Forms::Button()); this->deleteButton = (gcnew System::Windows::Forms::Button()); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->divider))->BeginInit(); this->SuspendLayout(); // // programText // this->programText->AcceptsTab = true; this->programText->BackColor = System::Drawing::Color::FromArgb(static_cast<System::Int32>(static_cast<System::Byte>(23)), static_cast<System::Int32>(static_cast<System::Byte>(23)), static_cast<System::Int32>(static_cast<System::Byte>(23))); this->programText->ForeColor = System::Drawing::SystemColors::Window; resources->ApplyResources(this->programText, L"programText"); this->programText->Name = L"programText"; this->programText->TextChanged += gcnew System::EventHandler(this, &baseUI::codeTextUpdate); // // nameBox // this->nameBox->ForeColor = System::Drawing::SystemColors::WindowFrame; resources->ApplyResources(this->nameBox, L"nameBox"); this->nameBox->Name = L"nameBox"; // // nameLabel // resources->ApplyResources(this->nameLabel, L"nameLabel"); this->nameLabel->Name = L"nameLabel"; // // languageLabel // resources->ApplyResources(this->languageLabel, L"languageLabel"); this->languageLabel->Name = L"languageLabel"; this->languageLabel->Click += gcnew System::EventHandler(this, &baseUI::sendCode); // // languageBox // this->languageBox->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->languageBox->ForeColor = System::Drawing::SystemColors::WindowFrame; this->languageBox->FormattingEnabled = true; this->languageBox->Items->AddRange(gcnew cli::array< System::Object^ >(2) { resources->GetString(L"languageBox.Items"), resources->GetString(L"languageBox.Items1") }); resources->ApplyResources(this->languageBox, L"languageBox"); this->languageBox->Name = L"languageBox"; // // divider // resources->ApplyResources(this->divider, L"divider"); this->divider->Name = L"divider"; this->divider->TabStop = false; // // functionSelector // this->functionSelector->FormattingEnabled = true; resources->ApplyResources(this->functionSelector, L"functionSelector"); this->functionSelector->Name = L"functionSelector"; this->functionSelector->SelectedIndexChanged += gcnew System::EventHandler(this, &baseUI::sendCode); // // funtionCollectionLabel // resources->ApplyResources(this->funtionCollectionLabel, L"funtionCollectionLabel"); this->funtionCollectionLabel->Name = L"funtionCollectionLabel"; // // saveButton // resources->ApplyResources(this->saveButton, L"saveButton"); this->saveButton->Name = L"saveButton"; this->saveButton->UseVisualStyleBackColor = true; this->saveButton->Click += gcnew System::EventHandler(this, &baseUI::writeToFile); // // copyButton // resources->ApplyResources(this->copyButton, L"copyButton"); this->copyButton->Name = L"copyButton"; this->copyButton->UseVisualStyleBackColor = true; this->copyButton->Click += gcnew System::EventHandler(this, &baseUI::copyToClipboard); // // deleteButton // resources->ApplyResources(this->deleteButton, L"deleteButton"); this->deleteButton->Name = L"deleteButton"; this->deleteButton->UseVisualStyleBackColor = true; this->deleteButton->Click += gcnew System::EventHandler(this, &baseUI::deleteData); // // baseUI // resources->ApplyResources(this, L"$this"); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->BackColor = System::Drawing::Color::White; this->Controls->Add(this->deleteButton); this->Controls->Add(this->copyButton); this->Controls->Add(this->saveButton); this->Controls->Add(this->funtionCollectionLabel); this->Controls->Add(this->functionSelector); this->Controls->Add(this->divider); this->Controls->Add(this->languageBox); this->Controls->Add(this->languageLabel); this->Controls->Add(this->nameLabel); this->Controls->Add(this->nameBox); this->Controls->Add(this->programText); this->MaximizeBox = false; this->MinimizeBox = false; this->Name = L"baseUI"; this->Opacity = 0.99; this->Load += gcnew System::EventHandler(this, &baseUI::accessFunctionNames); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->divider))->EndInit(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void codeTextUpdate(System::Object^ sender, System::EventArgs^ e) { /// ------------------------------------------------------------------------------------ /// /* This function is merely here to catch updates to code text in the RichTextBox^ programText. */ /// ------------------------------------------------------------------------------------ /// } private: System::Void deleteData(System::Object^ sender, System::EventArgs^ e) { /// ------------------------------------------------------------------------------------ /// /* Function is used for all delete buttons. The slightly ambiguous function name (deleteFunction and deleteData) literally refers to deleting function content and a button.)\ This function is activated when the delete button is pressed. It calls a function, deleteFunction which deletes the function in the file. (It deletes the file and rewrites it completely.) */ /// ------------------------------------------------------------------------------------ /// deleteFunction(functionSelector->GetItemText(functionSelector->SelectedItem)); programText->Text = " "; // we do not want to reset this in the function, as it is used for other manipulations. } private: System::Void sendCode(System::Object^ sender, System::EventArgs^ e) { /// ------------------------------------------------------------------------------------ /// /* This function, which is passed down the location of the GUI object / class, and event arguments, retrieves code text from the file database.txt and sends it to a RichTextbox^ called programText. The function is heavily reliant on msclr marshal and the string library. */ /// ------------------------------------------------------------------------------------ /// std::ifstream fin("database.txt"); int selectedIndex = functionSelector->SelectedIndex; auto i = 0, j = 0, line = 1; std::string fileString; // In the line above, the function selected by the user is created as an int, and multiple counters are made to iterate through a file. Line is used to represent which line in the file the pointer is. std::string codeArray[1450] = { "" }; if (fin.is_open()) { do { // find the function in the filename, and iterate until the function selected in the ListBox^ matches the index of the function name in database.txt std::getline(fin, fileString); ++line; if (fileString[0] == '*' && fileString[1] == '^') { ++i; } } while (i <= selectedIndex); std::string container; gotoLine(fin, line); // move the pointer viewing the file to the line where the code is. std::getline(fin, container); while (container != "*%." || container == "*%.\n" || container == "*%. ") { std::getline(fin, container); if (!(container == "*%" || container == "*%.") && j < 1450) { codeArray[j] = std::string(container); ++j; } } fin.close(); std::string compositeString(""); for (auto u = 0; u < 1450; ++u) { compositeString.append(codeArray[u] + "\n"); } std::ifstream finPatcher("patchErrors.txt"); std::string baseString; std::getline(finPatcher, baseString); // fix color highlighitng with patch .txt file data. finPatcher.close(); boost::trim_right(compositeString); String ^ fileStringSystem = System::Runtime::InteropServices::Marshal::PtrToStringAnsi((IntPtr)(char *)compositeString.c_str()); String ^ destructor = System::Runtime::InteropServices::Marshal::PtrToStringAnsi((IntPtr)(char *)baseString.c_str()); programText->Text = destructor; // deconstruct text inside box programText->Text = fileStringSystem; std::string language(grabLanguage()); operateHighlights(language); nameBox->Text = functionSelector->GetItemText(functionSelector->SelectedItem); // update if a user tries to edit String ^ sysLang = System::Runtime::InteropServices::Marshal::PtrToStringAnsi((IntPtr)(char *)language.c_str()); languageBox->Text = sysLang; // ... so that metadata is preserved. } else { ; // database.txt File not found. Create a new file, database.txt in the same directory as the .cpp files } } private: System::Void accessFunctionNames(System::Object^ sender, System::EventArgs^ e) { /// ------------------------------------------------------------------------------------ /// /* This function retrieves functionNames from database.txt using the function getFunctions. It is merely an event attatcher. */ /// ------------------------------------------------------------------------------------ /// getFunctions(); checkUserAuthToken(); } private: System::Void copyToClipboard(System::Object^ sender, System::EventArgs^ e) { /// ------------------------------------------------------------------------------------ /// /* This function retrieves data from a RichTextBox^, and copies it to a windows clipboard. */ /// ------------------------------------------------------------------------------------ /// System::String^ theCode = programText->Text; Clipboard::SetText(theCode); } public: System::Void writeToFile(System::Object^ sender, System::EventArgs^ e) { /// ------------------------------------------------------------------------------------ /// /* This function, which takes in the eventArgs / event data, and a reference to the object / class of the GUI, updates the database.txt file that is found in the same directory as this .h file. This function is heavily reliant on the marshal msclr library, as it needs to convert strings and system String ^.*/ /// ------------------------------------------------------------------------------------ /// // Create a System String to Hold Function Name, A String of Code, and the Language of said code System::String^ functionName; System::String^ codeString; System::String^ languageString; functionName = nameBox->Text; codeString = programText->Text; languageString = languageBox->Text; // Convert System::String^ arg to cppstd lib string. std::string functionNameStandard(access.marshal_as<std::string>(functionName)); std::string codeStringStandard(access.marshal_as<std::string>(codeString)); std::string languageStringStandard(access.marshal_as<std::string>(languageString)); removeAsterisks(functionNameStandard); std::string functionCollection[250]; auto m = 0; std::string contentText; std::fstream getData("database.txt"); if (getData.is_open()) { while (!(getData.eof())) { std::getline(getData, contentText); if (contentText[0] == '*' && contentText[1] == '^') { functionCollection[m] = contentText; ++m; } } getData.close(); } std::string checkFunction = ("*^" + functionNameStandard); for (auto t = 0; t < 250; ++t) { if (functionCollection[t] == (checkFunction)){ deleteFunction(functionName); break; } } std::fstream fout; fout.open("database.txt", std::fstream::app); // prevent overriding on foutstream. source: http://stackoverflow.com/questions/4155537/writing-into-a-text-file-without-overwriting-it if (fout.is_open()) { fout << "*^" << functionNameStandard << "\n"; fout << "*&" << languageStringStandard << "\n"; fout << "*%\n" << codeStringStandard << "\n*%." << "\n"; } else { ;//database.txt File not found. Create a new file, database.txt in the same directory as the .cpp files } fout.close(); getFunctions(); } void removeAsterisks(std::string& inputString) { /// ------------------------------------------------------------------------------------ /// /* Takes in a parameter, std::string (from <#include string> by reference. This function will remove all asterisks from a string passed by reference. We want to remove asterisks from function names in the program often because asterisks are used in the back end system to categorize data. */ /// ------------------------------------------------------------------------------------ /// for (int i = 0; i < int(inputString.length() - 1); ++i) { if (char(inputString[i]) == '*') { // Assume that users do not NEED * in function names... inputString.erase(i, i); // we want to remove all traces of * in the function name... } // since * is used to index where new functions are in the text file. } } std::string grabLanguage() { /// ------------------------------------------------------------------------------------ /// /* This function, grabLanguage, obtains the language of a given function through the "database.txt" file and returns it as a string. */ /// ------------------------------------------------------------------------------------ /// std::string language; int selectedIndex = functionSelector->SelectedIndex; auto i = 0, line = 1; std::string fileString; std::ifstream finFind("database.txt"); if (finFind.is_open()) { do { // find the function in the filename, and iterate until the function selected in the ListBox^ matches the index of the function name in database.txt std::getline(finFind, fileString); ++line; if (fileString[0] == '*' && fileString[1] == '^') { ++i; } } while (i <= selectedIndex); finFind.close(); finFind.open("database.txt"); std::string container; gotoLine(finFind, (line + 0)); // move the pointer viewing the file to the line where the code is. std::getline(finFind, container); language = std::string(container); language.erase(0, 2); } finFind.close(); return language; } void checkUserAuthToken() { /// ------------------------------------------------------------------------------------ /// /* See if the user has ever used the program before. If not, give a popup that shows them instructions. FOR THIS FUNCTION TO WORK ON A USED VERSION OF THE PROGRAM, THIS APPLICATION MUST HAVE ADMIN AND UAC / REGISTRY EDIT PERMISSIONS. */ /// ------------------------------------------------------------------------------------ /// String^ registryLocation = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography"; String^ userIdentifier = (String^)Microsoft::Win32::Registry::GetValue(registryLocation, "MachineGuid", "0"); std::string userID(access.marshal_as<std::string>(userIdentifier)); std::ifstream finID("userAuthToken.txt"); std::string token;; if (finID.is_open()) { std::getline(finID, token); if (token != userID) { finID.close(); std::fstream fout("userAuthToken.txt"); fout << userID; System::Windows::Forms::MessageBox::Show("How to use the function manager:\n\n\ To write code that you want to save into your function, type in the black IDE like box. \ For your code to be saved, you will have to name the function and hit save.\n\ Type in the function name in the name textbox. \ Choose a language from the drop - down box if you would like syntax highlighting when you *next* view the code.\n\n\ If you leave the program, your function code will not be saved unless you hit save.\n\ Functions will appear on the left-hand side of the menu. Click or use the arrow keys to view the code of the function.\n\n ", "Instructions"); fout.close(); } else { finID.close(); } } else { ;//userAuthToken.txt not found. User authentication cannot proceed until this file exists in the same directory as this .h file } } void operateHighlights(std::string language) { /// ------------------------------------------------------------------------------------ /// /* This function updates a RichTextBox^ programText to add syntax highlighting for a given function. */ /// ------------------------------------------------------------------------------------ /// if(programText->TextLength > 30000) { ; // pass if there is too much to highlight } else { if (language == "Python" || language == "C++") { if (language == "Python") { for (auto k = 0; k <= 15; ++k) { // data types syntaxHighlight(programText, pythonDataTypes[k], monokaiPink); } for (auto i = 0; i <= 34; ++i) { // keywords syntaxHighlight(programText, pythonKeywords[i], monokaiYellow); } syntaxHighlight(programText, "#", monokaiComment); commentHighlight(programText, monokaiComment); } else if (language == "C++") { for (auto k = 0; k <= 19; ++k) { // data types syntaxHighlight(programText, cppDataTypes[k], monokaiPink); } for (auto i = 0; i <= 74; ++i) { // keywords syntaxHighlight(programText, cppKeywords[i], monokaiYellow); } for (auto p = 0; p <= 3; ++p) { syntaxHighlight(programText, commentList[p], monokaiComment); } cCommentHighlight(programText, monokaiComment); } for (auto l = 0; l <= 9; ++l) { syntaxHighlight(programText, numberList[l], monokaiPurple); } for (auto z = 0; z <= 19; ++z) { syntaxHighlight(programText, operatorList[z], monokaiGreen); } for (auto z = 0; z <= 5; ++z) { syntaxHighlight(programText, containerList[z], monokaiOrange); } } } } void deleteFunction(String^ functionToDestroySystemVers) { /// ------------------------------------------------------------------------------------ /// /* Given the system string that contains the name of a function we want to destroy, delete that function from the database. */ /// ------------------------------------------------------------------------------------ /// std::ifstream fin("database.txt"); std::string code(""); std::string container(""); if (fin.is_open()) { while (!(fin.eof())) { std::getline(fin, container); code.append(container + "\n"); } } // default parameter: String^ functionToDestroySystemVers = functionSelector->GetItemText(functionSelector->SelectedItem); std::string functionToDestroy(access.marshal_as<std::string>(functionToDestroySystemVers)); functionToDestroy.insert(0, "*^"); //int found = int(code.find_first_of(functionToDestroy)) int found = code.find(functionToDestroy); int endCut = found; while (!(char(code[endCut]) == '*' && char(code[endCut + 1]) == '%' && char(code[endCut + 2]) == '.')) { // while not at end of the function ++endCut; } endCut += 3; code.erase(found, (endCut-found)); fin.close(); std::ofstream outputFile; if (remove("database.txt") != 0){ ;//database.txt not found } else { outputFile.open("database.txt"); outputFile << code; outputFile.close(); } getFunctions(); std::string placeholder = " "; String^ sysPlace = System::Runtime::InteropServices::Marshal::PtrToStringAnsi((IntPtr)(char *)placeholder.c_str()); nameBox->Text = sysPlace; // update if a user tries to edit } void getFunctions() { /// ------------------------------------------------------------------------------------ /// /* This function takes in no inputs, and updates the listBox called functionSelector. Data is taken from "database.txt" which is in the same directory as the .h file. Function names start with *^ in .txt database. Items are also refreshed in this function to prevent duplication. */ /// ------------------------------------------------------------------------------------ /// functionSelector->Items->Clear(); // remove duplicates std::string fileLine; std::string functionNames[250] = { "" }; std::ifstream fin("database.txt"); int i = 0; if (fin.is_open()) { while (!fin.eof()) { std::getline(fin, fileLine); if (fileLine[0] == '*' && fileLine[1] == '^') { // if the string has a function name encoding fileLine.erase(0, 2); // remove the encoding from the string to just have function name functionNames[i] = fileLine; ++i; } } } else { ;//database.txt File not found. Create a new file, database.txt in the same directory as the .cpp files } for (auto i = 0; i < 250; ++i) { // for all possible elements in the array of function names if (!(functionNames[i] == "")) { String ^ ansiStringStandard = System::Runtime::InteropServices::Marshal::PtrToStringAnsi((IntPtr)(char *)functionNames[i].c_str()); functionSelector->Items->Add(ansiStringStandard); // above, we have converted an array of std::string to system String ^. } } fin.close(); } std::ifstream& gotoLine(std::ifstream& file, int num) { /// ------------------------------------------------------------------------------------ /// /* This function has been inspired by this source, Xeo: http://stackoverflow.com/questions/5207550/in-c-is-there-a-way-to-go-to-a-specific-line-in-a-text-file The function takes in a file through the passed ifstream, and an integer num, which is used to iterate though the file. Essentially, the function moves the pointer in the system viewing file to the line given by num. */ /// ------------------------------------------------------------------------------------ /// file.seekg(std::ios::beg); for (auto i = 0; i < num - 1; ++i) { file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } return file; } void syntaxHighlight(RichTextBox^ box, std::string highlight, Color color) { /// ------------------------------------------------------------------------------------ /// /* Function Inspired by this source, Hans Passant : http://stackoverflow.com/questions/455713/selectively-coloring-text-in-richtextbox This function takes in a system RichTextBox, string from the #include <string module> and a System::Drawing::Color type The function searches the text in a text box, box, for the phrase to change the color of, highlight. The color of the phrase is set to color. */ /// ------------------------------------------------------------------------------------ /// int position = box->SelectionStart; int length = highlight.length(); String ^ boxContent = box->Text; // get the content of textbox parameter. std::string content(access.marshal_as<std::string>(boxContent)); // convert system String ^ to std::string for (int i = 0; ;) { int j = content.find(highlight, i); if (j < 0) { // if no more found strings with content of parameter highlight, then stop. break; } box->SelectionStart = j; //start recolor at the index of highlight. box->SelectionLength = length; box->SelectionColor = color; i = j + 1; // iterate through content faster by using j+1 instead of i++ } } void commentHighlight(RichTextBox^ searchBox, Color commentColor) { /// ------------------------------------------------------------------------------------ /// /* This protoype testing function takes in a RichTextBox^ to grab text from, and a System::Drawing::Color type which is used a comment color. The function searches the text in a text box, sarchBox, and the color of all text after a # in a line is set to commentColor. */ /// ------------------------------------------------------------------------------------ /// String ^ boxContent = searchBox->Text; // get the content of textbox parameter. std::string content(access.marshal_as<std::string>(boxContent)); // convert system String ^ to std::string int position = 0; std::istringstream stringStrm(content); std::string lineContent; auto a = 0; auto t = 0; // total of how many chars have been counted. auto totalLength = content.size(); while (!(stringStrm.eof())) { std::getline(stringStrm, lineContent); int lineLength = lineContent.length(); while(a < lineLength){ ++t;// weve seen a character if (lineContent[a] == '#' || (lineContent[a] == '\"' && lineContent[a + 1] == '\"' && lineContent[a + 2] == '\"')) { searchBox->SelectionStart = t; searchBox->SelectionLength = lineLength - a; searchBox->SelectionColor = commentColor; } ++a; } ++t; a = 0; // reset a because we are on the next line. } } void cCommentHighlight(RichTextBox^ searchBox, Color commentColor) { /// ------------------------------------------------------------------------------------ /// /* This protoype testing function takes in a RichTextBox^ to grab text from, and a System::Drawing::Color type which is used a comment color. The function searches the text in a text box, sarchBox, and the color of all text after a # in a line is set to commentColor. */ /// ------------------------------------------------------------------------------------ /// String ^ boxContent = searchBox->Text; // get the content of textbox parameter. std::string content(access.marshal_as<std::string>(boxContent)); // convert system String ^ to std::string int position = 0; std::istringstream stringStrm(content); std::string lineContent; auto a = 0; auto t = 0; // total of how many chars have been counted. auto totalLength = content.size(); while (!(stringStrm.eof())) { std::getline(stringStrm, lineContent); int lineLength = lineContent.length(); while (a < lineLength) { ++t;// weve seen a character if (lineContent[a] == '/' && lineContent[a+1] == '/' || lineContent[a] == '/' && lineContent[a + 1] == '*') { searchBox->SelectionStart = t; searchBox->SelectionLength = lineLength - a; searchBox->SelectionColor = commentColor; } ++a; } ++t; a = 0; // reset a because we are on the next line. } } }; }
41.884666
203
0.60179
[ "object" ]
fb70b1b2dd084a2f7d9628f1a03f45f5a752dd30
542
h
C
include/UIKit/NSDictionary.h
iMokhles/MyTheosHeaders
2c263362a8a6f947b1a868e03983ed188ead6539
[ "MIT" ]
7
2016-07-22T14:29:58.000Z
2021-03-19T05:31:48.000Z
iphone-private-frameworks-master/UIKit/NSDictionary.h
tt295362026/demo
7d6e9e75f29c992ea9c5693d38f76e0012bbbf15
[ "BSD-4-Clause" ]
null
null
null
iphone-private-frameworks-master/UIKit/NSDictionary.h
tt295362026/demo
7d6e9e75f29c992ea9c5693d38f76e0012bbbf15
[ "BSD-4-Clause" ]
3
2017-02-06T23:58:01.000Z
2017-10-31T03:47:52.000Z
/** * This header is generated by class-dump-z 0.1-11o. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. */ #import <Foundation/NSDictionary.h> @interface NSDictionary (UICollectionAdditions) -(BOOL)boolForKey:(id)key; @end @interface NSDictionary (UIWebDocumentViewMessaging) // In 3.2 the category name is UIWebBrowserViewPrivate. -(id)text; -(int)lineNumber; -(id)sourceURL; -(int)type; @end @interface NSDictionary (BrowserAdditions) -(void)_safari_setObject:(id)object forUncopiedKey:(id)uncopiedKey; @end
23.565217
108
0.758303
[ "object" ]
fb751cb6083dd7a20bc4f687ae71c46dd0974366
1,752
h
C
source/headers/creature.h
soikkea/dungeoncrawler
16cd9e6ecc1885bc5701a762a7d0564dc4effe7a
[ "MIT" ]
null
null
null
source/headers/creature.h
soikkea/dungeoncrawler
16cd9e6ecc1885bc5701a762a7d0564dc4effe7a
[ "MIT" ]
null
null
null
source/headers/creature.h
soikkea/dungeoncrawler
16cd9e6ecc1885bc5701a762a7d0564dc4effe7a
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <memory> #include <string> #include "sprite.h" #include "skillset.h" #include "stat.h" class Player; class Item; class Weapon; class Creature : public Sprite { public: Creature(int x, int y); virtual ~Creature(); Creature(Creature& other); Creature& operator=(Creature& other); const int getHitPoints() const; const int getMaxHitPoints() const; void gainHitpoints(int amount); virtual bool isAlive() const; virtual bool canMove() const; const std::string getName() const; void setName(std::string name); const int getLevel() const; const int getExperience() const; const int getExperienceWorth() const; const int getExpRequiredToNextLevel() const; void gainExperience(int amount); void gainLevel(int amount); void equipWeapon(std::unique_ptr<Weapon> weapon); std::vector<std::unique_ptr<Item>>& getInventory(); bool addItem(std::unique_ptr<Item>& item); bool useInventoryItem(int itemIndex); const int getDamage() const; SkillSet& getSkillSet(); void startTurn(); virtual bool moveStep(Direction direction, const Level& level); void update(Level& level, Player& player); virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; void drawHealth(sf::RenderTarget& target, sf::RenderStates states) const; virtual void attackCreature(Creature& target); virtual void calculateStats(bool force = false); std::map<StatEnum, Stat> stats; static constexpr int MAX_INVENTORY_SIZE = 5; protected: std::string _name; int _level; int _experience; int _experienceWorth; int _experienceReqToNextLevel; std::unique_ptr<Weapon> _equippedWeapon; std::vector<std::unique_ptr<Item>> _inventory; SkillSet _skillSet; sf::VertexArray _sightLine; bool _seesPlayer; };
25.764706
76
0.756849
[ "vector" ]
fb767f0ca9e8808ac753c946cc69eb9155a3da6a
2,297
h
C
src/strategy/include/strategy/strategy_main.h
TKUICLab-humanoid/BB
badb9d2669c4f0dca64c221761c11ea2d56e7412
[ "MIT" ]
null
null
null
src/strategy/include/strategy/strategy_main.h
TKUICLab-humanoid/BB
badb9d2669c4f0dca64c221761c11ea2d56e7412
[ "MIT" ]
null
null
null
src/strategy/include/strategy/strategy_main.h
TKUICLab-humanoid/BB
badb9d2669c4f0dca64c221761c11ea2d56e7412
[ "MIT" ]
6
2020-09-15T14:13:54.000Z
2021-01-14T06:45:39.000Z
#include <ros/ros.h> #include <ros/package.h> #include <vector> #include <stdio.h> #include <std_msgs/String.h> #include "tku_libs/strategy_info.h" #include "tku_libs/TKU_tool.h" #include "tku_libs/RosCommunication.h" #include "tku_libs/WalkContinuouse.h" #include "strategy/basketballinfo.h" #include "strategy/loadparameter.h" using namespace std; class KidsizeStrategy { public: KidsizeStrategy() { strategy_info = StrategyInfoInstance::getInstance(); tool = ToolInstance::getInstance(); ros_com = RosCommunicationInstance::getInstance(); walk_con = WalkContinuouseInstance::getInstance(); sendbodystandflag = false; DIOSTRATAGAIN = true; }; ~KidsizeStrategy() { StrategyInfoInstance::deleteInstance(); ToolInstance::deleteInstance(); RosCommunicationInstance::deleteInstance(); WalkContinuouseInstance::deleteInstance(); }; StrategyInfoInstance *strategy_info; ToolInstance *tool; RosCommunicationInstance *ros_com; WalkContinuouseInstance *walk_con; void strategymain(); void InversePerspective(); void Triangulation(); void AreaSizeDistance(); void image(); void MoveHead(HeadMotorID , int , int ); void ComputeSpeed(); void SelectBaseLine(); void FindballInitial(); void FindballHead(); void TraceballHead(); void TraceballBody(); void FindbasketHead(); void TurnbasketHead(); void TracebasketHead(); void TracebasketBody(); void Draw(); void MoveContinuous(int ); void AreaSizeMeasure(); //LayUp void UPbasket(); void SlamDunk(); typedef enum{ //BB //Catch Ball BB_WaistDown1 = 900, BB_WaistCatch1 = 901, BB_WaistUp1 = 902, BB_WaistDown2 = 118, BB_WaistCatch2 = 1110, BB_WaistUp2 = 1114, BB_WaistUpFeedBack = 1112, BB_WaistUpFeedBack2 = 2112, //Shooting BB_RaiseHand = 1115, BB_ReadyToShoot = 1116, BB_ShootingBall = 1125, BB_ShootingBall2 = 1126, BB_ShootingBall3 = 1127, BB_KeepBall = 1117, //LayUp BB_UpHand = 1140, BB_SlamDunk = 1150, //Stand BB_StandFix = 1218, BB_CatchballStandFix = 128, Robot_StandUp = 29 }MotionTable; SensorMode IMUSet; WalkingMode walkingmode; bool sendbodystandflag; bool DIOSTRATAGAIN; struct timeval tstart, tend; double timeuse; };
22.742574
54
0.709186
[ "vector" ]
fb768712bf877cb61b7c7715222cf597e55b5c8e
6,216
h
C
v3d_main/basic_c_fun/basic_memory.h
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
39
2015-05-10T23:23:03.000Z
2022-01-26T01:31:30.000Z
v3d_main/basic_c_fun/basic_memory.h
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
13
2016-03-04T05:29:23.000Z
2021-02-07T01:11:10.000Z
v3d_main/basic_c_fun/basic_memory.h
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
44
2015-11-11T07:30:59.000Z
2021-12-26T16:41:21.000Z
/* * Copyright (c)2006-2010 Hanchuan Peng (Janelia Farm, Howard Hughes Medical Institute). * All rights reserved. */ /************ ********* LICENSE NOTICE ************ This folder contains all source codes for the V3D project, which is subject to the following conditions if you want to use it. You will ***have to agree*** the following terms, *before* downloading/using/running/editing/changing any portion of codes in this package. 1. This package is free for non-profit research, but needs a special license for any commercial purpose. Please contact Hanchuan Peng for details. 2. You agree to appropriately cite this work in your related studies and publications. Peng, H., Ruan, Z., Long, F., Simpson, J.H., and Myers, E.W. (2010) “V3D enables real-time 3D visualization and quantitative analysis of large-scale biological image data sets,” Nature Biotechnology, Vol. 28, No. 4, pp. 348-353, DOI: 10.1038/nbt.1612. ( http://penglab.janelia.org/papersall/docpdf/2010_NBT_V3D.pdf ) Peng, H, Ruan, Z., Atasoy, D., and Sternson, S. (2010) “Automatic reconstruction of 3D neuron structures using a graph-augmented deformable model,” Bioinformatics, Vol. 26, pp. i38-i46, 2010. ( http://penglab.janelia.org/papersall/docpdf/2010_Bioinfo_GD_ISMB2010.pdf ) 3. This software is provided by the copyright holders (Hanchuan Peng), Howard Hughes Medical Institute, Janelia Farm Research Campus, and contributors "as is" and any express or implied warranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the copyright owner, Howard Hughes Medical Institute, Janelia Farm Research Campus, or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; reasonable royalties; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. 4. Neither the name of the Howard Hughes Medical Institute, Janelia Farm Research Campus, nor Hanchuan Peng, may be used to endorse or promote products derived from this software without specific prior written permission. *************/ /* basic_memory.h Some basic memory functions for applications. by Hanchuan Peng 2007-02-16: separated from the original "basic_func.h" so that only include the memory functions. Note that the interface functions have been rewritten so that they only have one template function without type conversion. Also change the return type from "int" to "bool", so that they are clearer. 2007-02-16: Because I removed all the type conversion in the "new*" functions, an explicit copying function from a type such as "unsigned char" to "double" is needed. Thus I added a few often-needed wrappers for these EXPLICIT conversions. These functions are named using "copy1dMem*". 2009-08-2: add 5d memory management 2010-05-19: add v3d_basicdatatype.h */ #ifndef __BASIC_MEMORY_H__ #define __BASIC_MEMORY_H__ #include "v3d_basicdatatype.h" template <class T> bool new2dpointer(T ** & p, V3DLONG sz0, V3DLONG sz1, const T * p1d); template <class T> void delete2dpointer(T ** & p, V3DLONG sz0, V3DLONG sz1); template <class T> bool new3dpointer(T *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, const T * p1d); template <class T> void delete3dpointer(T *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2); template <class T> bool new4dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3, const T * p1d); template <class T> void delete4dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3); template <class T> bool new5dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3, V3DLONG sz4, const T * p1d); template <class T> void delete5dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3, V3DLONG sz4); template <class T> bool copy1dMem(T * &p, V3DLONG len, const char * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const unsigned char * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const int * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const unsigned int * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const short int * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const unsigned short int * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const V3DLONG * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const unsigned V3DLONG * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const float * p1d); template <class T> bool copy1dMem(T * &p, V3DLONG len, const double * p1d); /* template <class T> int new3dpointer(T *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, unsigned char * p1d); template <class T> int new3dpointer(T *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, double * p1d); template <class T> int new3dpointer(T *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, float * p1d); //template <class T> int new3dpointer(T *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, T * p1d); //template <class T> int new3dpointer(double *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, T * p1d); template <class T> void delete3dpointer(T *** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2); template <class T> int new4dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3, unsigned char * p1d); template <class T> int new4dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3, double * p1d); template <class T> int new4dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3, float * p1d); //template <class T> int new4dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3, T * p1d); template <class T> void delete4dpointer(T **** & p, V3DLONG sz0, V3DLONG sz1, V3DLONG sz2, V3DLONG sz3); */ #endif
66.12766
941
0.723616
[ "model", "3d" ]
fb76f94423ea5ec141b7991209c32bd847ff3b49
53,127
c
C
src/Rts/Sys/larceny.c
larcenists/larceny-oldimport
4bfd2d2571d3f11f9a51e2d5fa5982211fb276cb
[ "MIT" ]
2
2015-05-15T05:36:20.000Z
2020-12-12T02:56:43.000Z
src/Rts/Sys/larceny.c
larcenists/larceny-oldimport
4bfd2d2571d3f11f9a51e2d5fa5982211fb276cb
[ "MIT" ]
null
null
null
src/Rts/Sys/larceny.c
larcenists/larceny-oldimport
4bfd2d2571d3f11f9a51e2d5fa5982211fb276cb
[ "MIT" ]
null
null
null
/* Copyright 1998 Lars T Hansen -*- indent-tabs-mode: nil -*- * * $Id$ * * Larceny run-time system -- main file. * * FIXME: Over-complex. A gazillion parameters are supported, which * introduces: * - parsing and error checking * - text into the usage message * - value printing if parameter value printing is on * Since various GCs have various parameters, factor this cruft out * into a spec that can be handled by the GC, via function pointers or * whatever. */ #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "config.h" #include "larceny.h" #include "gc.h" #include "stats.h" /* for stats_init() */ #include "gc_t.h" #include "young_heap_t.h" /* for yh_create_initial_stack() */ opt_t command_line_options; static void param_error( char *s ); static void invalid( char *s ); static void usage( void ); static void help(int wizardp); static void parse_options( int argc, char **argv, opt_t *opt ); static int getsize( char *s, int *p ); static void dump_options( opt_t *o ); static bool quiet = 0; /* 'quiet' controls consolemsg() */ static bool annoying = 0; /* 'annoying' controls annoying_msg() */ static bool supremely_annoying = 0; /* 'supremely_annoying' controls supremely_annoyingmsg() */ static void print_banner(void) { #ifndef PETIT_LARCENY consolemsg( "%s v%d.%d%s (%s, %s:%s:%s)", larceny_system_name, larceny_major_version, larceny_minor_version, larceny_version_qualifier, date, larceny_gc_technology, osname, (globals[ G_CACHE_FLUSH ] ? "split" : "unified") ); #else consolemsg( "%s v%d.%d%s (%s:%s)", larceny_system_name, larceny_major_version, larceny_minor_version, larceny_version_qualifier, larceny_gc_technology, osname ); #endif } #if defined PETIT_LARCENY || defined X86_NASM int larceny_main( int argc, char **os_argv ) #else int main( int argc, char **os_argv ) #endif { int generations; char **argv; /* FIXME: this allows us to (temporarily) circumvent DEP problems for the majority of windows users */ #if WIN32 /* there are four possible returns to this function. We care about AlwaysOn and OptOut. If the policy is set to AlwaysOn then larceny cannot run. Otherwise we can opt out of the restriction. The other two cases (AlwaysOff and OptIn) have no affect */ switch(GetSystemDEPPolicy()) { case 0: break; /* AlwaysOff: we don't care about this */ case 1: /* DEP has been set in the windows boot.ini to be always on */ panic_exit("The system DEP Policy is to restrictive to allow larceny to run"); break; case 2: break; /* OptIn: we don't care about this either */ case 3: /* DEP has been set to be OptOut, which is what we do */ if(!SetProcessDEPPolicy(0)) { consolemsg("Failed to set DEP policy"); } break; } #endif /* WIN32 */ #if defined(DEC_ALPHA_32BIT) /* I know this looks weird. When running Petit Larceny on the Alpha in 32-bit mode, pointers are 32-bit, but the interface to main() is 64-bit (for reasons I do not understand yet). The following seemingly unnecessary loop moves the argument vector into 32-bit space. Presumably there's a better way, as this must be a common problem. */ argv = (char**)malloc( sizeof( char* )*(argc+1) ); for ( i=0 ; i < argc ; i++ ) { argv[i] = (char*)malloc( strlen( os_argv[i] )+1 ); strcpy( argv[i], os_argv[i] ); } argv[i] = 0; #else argv = os_argv; #endif osdep_init(); cache_setup(); memset( &command_line_options, 0, sizeof( command_line_options ) ); command_line_options.maxheaps = MAX_GENERATIONS; command_line_options.timerval = 0xFFFFFFFF; command_line_options.heapfile = 0; command_line_options.enable_breakpoints = 1; command_line_options.restv = 0; command_line_options.gc_info.ephemeral_info = 0; command_line_options.gc_info.use_static_area = 1; command_line_options.gc_info.mmu_buf_size = -1; command_line_options.gc_info.globals = globals; #if defined( BDW_GC ) command_line_options.gc_info.is_conservative_system = 1; #endif command_line_options.nobanner = 0; command_line_options.unsafe = 0; command_line_options.foldcase = 0; command_line_options.nofoldcase = 0; command_line_options.r5rs = 0; command_line_options.err5rs = 0; command_line_options.r6rs = 0; command_line_options.ignore1 = 0; command_line_options.r6fast = 0; command_line_options.r6slow = 0; command_line_options.r6pedantic = 0; command_line_options.r6less_pedantic = 0; command_line_options.r6program = ""; command_line_options.r6path = ""; command_line_options.transcoder = 0; if (larceny_version_qualifier[0] == '.') { /* If we our version qualifier starts with a period, then the * version prints out as M.NN.XXX (a development version number). * On development versions, we always print the banner with * information about the build date, host system, and gc * technology. */ print_banner(); /* since we printed the banner here, there's no reason to print it * again below. */ command_line_options.nobanner = 1; } /* FIXME: This should all be factored out as osdep_get_program_options() or something like that. That requires factoring out the type of 'o' in a header somewhere, and exposing parse_options. */ #if defined(MACOS) { /* Look for the file "larceny.args" in the application's home directory. */ int argc, maxargs = 100; char *argv[100], buf[256], *p; char *args_filename = "larceny.args"; /* fixme: don't hardwire file name */ FILE *fp; argv[0] = "Petit Larceny"; /* fixme: get application name */ argc = 1; if ((fp = fopen( args_filename, "r")) != 0) { while (fgets( buf, sizeof(buf), fp ) != 0) { p = strtok( buf, " \t\n\r" ); while (p != 0 && argc < maxargs-1) { argv[argc++] = strdup( p ); p = strtok( 0, " \t\n\r" ); } } fclose( fp ); } argv[argc] = 0; parse_options( argc, argv, &command_line_options ); } #else parse_options( argc, argv, &command_line_options ); #endif if (!command_line_options.nobanner) print_banner(); osdep_poll_startup_events(); if (command_line_options.heapfile == 0) { char *path = getenv(LARCENY_ROOT); size_t path_length = strlen(path); size_t base_length = strlen(larceny_heap_name); /* This leaks, but only once at startup. I think it's worth it: */ command_line_options.heapfile = malloc(path_length + base_length + 2); if (command_line_options.heapfile == NULL) { panic_exit("Cannot allocate buffer for heapfile name."); } sprintf(command_line_options.heapfile, "%s/%s", path, larceny_heap_name); } quiet = command_line_options.quiet; annoying = command_line_options.annoying; supremely_annoying = command_line_options.supremely_annoying; if (annoying || supremely_annoying) dump_options( &command_line_options ); if (command_line_options.flush) globals[ G_CACHE_FLUSH ] = 1; else if (command_line_options.noflush) globals[ G_CACHE_FLUSH ] = 0; if (command_line_options.reorganize_and_dump && !command_line_options.gc_info.is_stopcopy_system) { command_line_options.gc_info.is_conservative_system = 0; command_line_options.gc_info.is_generational_system = 0; command_line_options.gc_info.is_stopcopy_system = 1; command_line_options.gc_info.use_static_area = 1; command_line_options.gc_info.use_non_predictive_collector = 0; command_line_options.gc_info.use_incremental_bdw_collector = 0; command_line_options.gc_info.sc_info.size_bytes = DEFAULT_STOPCOPY_SIZE; command_line_options.gc_info.sc_info.load_factor = DEFAULT_LOAD_FACTOR; } if (!create_memory_manager( &command_line_options.gc_info, &generations )) panic_exit( "Unable to set up the garbage collector." ); if (!load_heap_image_from_file( command_line_options.heapfile )) panic_exit( "Unable to load the heap image." ); if (command_line_options.reorganize_and_dump) { char buf[ FILENAME_MAX ]; /* Standard C */ sprintf( buf, "%s.split", command_line_options.heapfile ); if (!reorganize_and_dump_static_heap( buf )) panic_exit( "Failed heap reorganization." ); return 0; } /* initialize some policy globals */ globals[ G_BREAKPT_ENABLE ] = (command_line_options.enable_breakpoints ? TRUE_CONST : FALSE_CONST); globals[ G_SINGLESTEP_ENABLE ] = (command_line_options.enable_singlestep ? TRUE_CONST : FALSE_CONST ); globals[ G_TIMER_ENABLE ] = (command_line_options.enable_timer ? TRUE_CONST : FALSE_CONST ); globals[ G_TIMER ] = 0; globals[ G_TIMER2 ] = command_line_options.timerval; globals[ G_RESULT ] = fixnum( 0 ); /* No arguments */ setup_signal_handlers(); stats_init( the_gc(globals) ); scheme_init( globals ); /* The initial stack can't be created when the garbage collector is created because stack creation depends on certain data structures allocated by scheme_init() in Petit Larceny when the system is compiled with USE_GOTOS_LOCALLY. So we create the stack here. */ yh_create_initial_stack( the_gc(globals)->young_area ); /* Allocate vector of command line arguments and pass it as an * argument to the startup procedure. */ { word args[1], res; args[0] = allocate_argument_vector( the_gc(globals), command_line_options.restc, command_line_options.restv ); larceny_call( globals[ G_STARTUP ], 1, args, &res ); consolemsg( "Startup procedure returned with value %08lx", (long)res ); } /* Not usually reached */ return 0; } /*************************************************************************** * * Console messages * */ int panic_exit( const char *fmt, ... ) { static int in_panic = 0; va_list args; va_start( args, fmt ); fprintf( stderr, "Larceny Panic: " ); vfprintf( stderr, fmt, args ); va_end( args ); fprintf( stderr, "\n" ); if (in_panic) abort(); in_panic = 1; exit( 1 ); /* Never returns. Return type is 'int' to facilitate an idiom. */ return 0; } #ifdef __GNUC__ extern int panic_abort( const char *fmt, ... ) __attribute__ ((__noreturn__)); #endif int panic_abort( const char *fmt, ... ) { static int in_panic = 0; va_list args; va_start( args, fmt ); fprintf( stderr, "Larceny Panic: " ); vfprintf( stderr, fmt, args ); va_end( args ); fprintf( stderr, "\n" ); if (in_panic) abort(); in_panic = 1; abort(); /* Never returns. Return type is 'int' to facilitate an idiom. */ #ifndef __GNUC__ return 0; #endif } void annoyingmsg( const char *fmt, ... ) { va_list args; if (!annoying) return; va_start( args, fmt ); if (!quiet) { vfprintf( stderr, fmt, args ); fprintf( stderr, "\n" ); fflush( stderr ); } va_end( args ); } void supremely_annoyingmsg( const char *fmt, ... ) { va_list args; if (!supremely_annoying) return; va_start( args, fmt ); if (!quiet) { vfprintf( stderr, fmt, args ); fprintf( stderr, "\n" ); fflush( stderr ); } va_end( args ); } void consolemsg( const char *fmt, ... ) { va_list args; if (quiet) return; va_start( args, fmt ); vfprintf( stdout, fmt, args ); fprintf( stdout, "\n" ); va_end( args ); fflush( stdout ); } void hardconsolemsg( const char *fmt, ... ) { va_list args; va_start( args, fmt ); vfprintf( stderr, fmt, args ); va_end( args ); fprintf( stderr, "\n" ); } static long long generic_event_counter = 0; static const long long max_event_count = 0; static const long long key_event_count = 0; static const long long event_trace_len = 100; int saw_event() { generic_event_counter++; if (max_event_count > 0) { if (generic_event_counter+1 == max_event_count) panic_abort( "hit max event count %lld", generic_event_counter); } return generic_event_counter; } void eventmsg( const char *fmt, ... ) { if (generic_event_counter > (key_event_count - event_trace_len) && (generic_event_counter < (key_event_count + event_trace_len))) { va_list args; va_start( args, fmt ); fprintf( stderr, "(event %8lld)", generic_event_counter ); vfprintf( stderr, fmt, args ); va_end( args ); fprintf( stderr, "\n" ); } } /**************************************************************************** * * Command line parsing. */ static int hstrcmp( const char *s1, const char* s2 ); /* A SizeSpec is either a Number n, or a Number n followed by the character 'M', * or a Number n followed by the character 'K' * interpretation: [[ n ]] = n; [[ nM ]] = n*1024*1024; [[ nK ]] = n*1024 */ /* requires: (to be determined) * effects: if *argv[0] matches str as an option, *argc > 1, and *argv[1] holds * a SizeSpec, then *var holds the number corresponding to *argv[1], * advances *argv, decrements *argc, and returns 1. Else returns 0. * example: sizearg( "-option", 2, { "-option", "3K" }, receiver ) * returns 1, with *receiver == 3072 */ static int sizearg( char *str, int *argc, char ***argv, int *var ); /* requires: (to be determined) * effects: if exists integer N such that *argv[0] matches strN as an option, * argc > 1, and *argv[1] holds a SizeSpec, * then *var holds the number corresponding to *argv[1] * and *loc holds (the largest such) N. * example: hsizearg( "-optnum", 2, { "-optnum3" "2K" }, recv1, recv2 ) * returns 1, with *recv1 == 2048 and *recv2 == 3 */ static int hsizearg( char *str, int *argc, char ***argv, int *var, int *loc ); static int doublearg( char *str, int *argc, char ***argv, double *var ); /* requires: (to be determined) * effects: if *argv[0] matches str as an option, *argc > 1, and *argv[1] holds * an integer, then *var holds the integer corresponding to *argv[1], * advances *argv, decrements *argc, and returns 1. Else returns 0. * example: numbarg( "-option", 2 { "-option" "4" }, receiver ) * returns 1, with *receiver = 4. */ static int numbarg( char *str, int *argc, char ***argv, int *var ); static int hnumbarg( char *str, int *argc, char ***argv, int *var, int *loc ); static void compute_np_parameters( opt_t *o, int suggested_size ); static void init_generational( opt_t *o, int areas, char *name ) { if (areas < 2) invalid( name ); if (o->gc_info.ephemeral_info != 0) { consolemsg( "Error: Number of areas re-specified with '%s'", name ); consolemsg( "Type \"larceny -help\" for help." ); exit( 1 ); } o->gc_info.is_generational_system = 1; o->gc_info.ephemeral_info = (sc_info_t*)must_malloc( sizeof( sc_info_t )*areas-2 ); o->gc_info.ephemeral_area_count = areas-2; } static void init_regional( opt_t *o, int areas, char *name ) { if (areas < 1) invalid( name ); if (o->gc_info.ephemeral_info != 0) { consolemsg( "Error: Number of areas re-specified with '%s'", name ); consolemsg( "Type \"larceny -help\" for help." ); exit( 1 ); } o->gc_info.is_regional_system = 1; o->gc_info.ephemeral_info = (sc_info_t*)must_malloc( sizeof( sc_info_t)*areas ); o->gc_info.ephemeral_area_count = areas; } static void parse_options( int argc, char **argv, opt_t *o ) { int i, loc, prev_size, areas = DEFAULT_AREAS; int mmu_size; int mark_period; int oracle_countdown; double popular_factor = 0.0; double infamy_factor = 0.0; double refine_factor = 0.0; double sumz_budget = 0.0; double sumz_coverage = 0.0; int sumz_retries; #if defined( BDW_GC ) double load_factor = 0.0; /* Ignore it. */ #else double load_factor = DEFAULT_LOAD_FACTOR; #endif double load_factor_hard = DEFAULT_LOAD_FACTOR_HARD; double expansion = 0.0; /* Ignore it. */ int divisor = 0; /* Ignore it. */ double feeling_lucky = 0.0; /* Not lucky at all. */ double phase_detection = -1.0; /* No detection. */ int np_remset_limit = INT_MAX; /* Infinity, or close enough. */ int full_frequency = 0; double growth_divisor = 1.0; int dynamic_max = 0; int dynamic_min = 0; int val; while (--argc) { ++argv; #if !defined( BDW_GC ) if (hstrcmp( *argv, "-stopcopy" ) == 0) o->gc_info.is_stopcopy_system = 1; else if (numbarg( "-areas", &argc, &argv, &areas )) init_generational( o, areas, "-areas" ); else if (hstrcmp( *argv, "-gen" ) == 0) init_generational( o, areas, "-gen" ); else if (hstrcmp( *argv, "-nostatic" ) == 0) o->gc_info.use_static_area = 0; else if (hstrcmp( *argv, "-nocontract" ) == 0) o->gc_info.dont_shrink_heap = 1; else if (hstrcmp( *argv, "-oracle" ) == 0) o->gc_info.use_oracle_to_update_remsets = 1; else if (numbarg( "-oracle_countdown", &argc, &argv, &oracle_countdown )) { o->gc_info.oracle_countdown = oracle_countdown; } else if (hsizearg( "-size", &argc, &argv, &val, &loc )) { if (loc > 1 && ! o->gc_info.is_regional_system) { /* FIXME: Maybe we shouldn't be inferring this anymore */ o->gc_info.is_generational_system = 1; } if (loc < 0 || loc > o->maxheaps) { invalid( "-size" ); } else if (o->gc_info.is_generational_system) { if (loc > 0) o->size[loc-1] = val; else for ( i=1 ; i < o->maxheaps ; i++ ) if (o->size[i-1] == 0) o->size[i-1] = val; } /* FIXME: The following could be simplified. */ else if (o->gc_info.is_regional_system) { o->size[loc] = val; } else if (o->gc_info.is_stopcopy_system) { o->size[loc] = val; } else { o->size[loc] = val; } } else if (numbarg( "-mmusize", &argc, &argv, &mmu_size)) { o->gc_info.mmu_buf_size = mmu_size; } else if (numbarg( "-regions", &argc, &argv, &areas)) { init_regional( o, areas, "-regions" ); } else if (hstrcmp( *argv, "-rrof" ) == 0 || hstrcmp( *argv, "-regional" ) == 0) { init_regional( o, areas, *argv ); } else if (hstrcmp( *argv, "-rrof_prefer_big_summ" ) == 0) { o->gc_info.rrof_prefer_big_summ = TRUE; o->gc_info.rrof_prefer_lil_summ = FALSE; o->gc_info.rrof_prefer_lat_summ = FALSE; } else if (hstrcmp( *argv, "-rrof_prefer_lil_summ" ) == 0) { o->gc_info.rrof_prefer_lil_summ = TRUE; o->gc_info.rrof_prefer_big_summ = FALSE; o->gc_info.rrof_prefer_lat_summ = FALSE; } else if (hstrcmp( *argv, "-rrof_prefer_late_summ" ) == 0) { o->gc_info.rrof_prefer_lat_summ = TRUE; o->gc_info.rrof_prefer_lil_summ = FALSE; o->gc_info.rrof_prefer_big_summ = FALSE; } else if (numbarg( "-mark_period", &argc, &argv, &mark_period)) { o->gc_info.mark_period = mark_period; } else if (doublearg( "-refinement", &argc, &argv, &refine_factor)) { o->gc_info.has_refine_factor = TRUE; o->gc_info.refinement_factor = refine_factor; } else if (hstrcmp( *argv, "-alloc_mark_bmp_once" ) == 0) { o->gc_info.alloc_mark_bmp_once = 1; } else if (doublearg( "-sumzbudget", &argc, &argv, &sumz_budget)) { o->gc_info.has_sumzbudget = TRUE; o->gc_info.sumzbudget_inv = sumz_budget; } else if (doublearg( "-sumzcoverage", &argc, &argv, &sumz_coverage)) { o->gc_info.has_sumzcoverage = TRUE; o->gc_info.sumzcoverage_inv = sumz_coverage; } else if (numbarg( "-sumzretries", &argc, &argv, &sumz_retries )) { o->gc_info.has_sumz_retries = TRUE; o->gc_info.max_sumz_retries = sumz_retries; } else if (doublearg( "-popularity", &argc, &argv, &popular_factor)) { o->gc_info.has_popularity_factor = TRUE; o->gc_info.popularity_factor = popular_factor; } else if (doublearg( "-infamy", &argc, &argv, &infamy_factor)) { if (infamy_factor == 0) { o->gc_info.has_infamy_factor = FALSE; } else { o->gc_info.has_infamy_factor = TRUE; o->gc_info.infamy_factor = infamy_factor; } } else if (hstrcmp( *argv, "-print_float_stats_cycle" ) == 0) o->gc_info.print_float_stats_cycle = TRUE; else if (hstrcmp( *argv, "-print_float_stats_major" ) == 0) o->gc_info.print_float_stats_major = TRUE; else if (hstrcmp( *argv, "-print_float_stats_minor" ) == 0) o->gc_info.print_float_stats_minor = TRUE; else if (hstrcmp( *argv, "-print_float_stats_refine" ) == 0) o->gc_info.print_float_stats_refine = TRUE; else if (sizearg( "-rhash", &argc, &argv, (int*)&o->gc_info.rhash )) ; else if (sizearg( "-ssb", &argc, &argv, (int*)&o->gc_info.ssb )) ; else if (hstrcmp( *argv, "-rhashrep" ) == 0) { o->gc_info.chose_rhashrep = TRUE; o->gc_info.chose_rbitsrep = FALSE; } else if (hstrcmp( *argv, "-rbitsrep" ) == 0) { o->gc_info.chose_rhashrep = FALSE; o->gc_info.chose_rbitsrep = TRUE; } else #endif /* !BDW_GC */ if (numbarg( "-ticks", &argc, &argv, (int*)&o->timerval )) ; else if (doublearg( "-load", &argc, &argv, &load_factor )) { #if defined(BDW_GC) if (load_factor < 1.0 && load_factor != 0.0) param_error( "Load factor must be at least 1.0" ); #else if (load_factor < 1.0) param_error( "Load factor must be at least 1.0" ); #endif } else if (doublearg( "-load_hard", &argc, &argv, &load_factor_hard )) { if (load_factor_hard < 1.0) param_error( "Load factor must be at least 1.0" ); } #if ROF_COLLECTOR else if (hstrcmp( *argv, "-np" ) == 0 || hstrcmp( *argv, "-rof" ) == 0) { o->gc_info.is_generational_system = 1; o->gc_info.use_non_predictive_collector = 1; } else if (numbarg( "-steps", &argc, &argv, &o->gc_info.dynamic_np_info.steps )) { o->gc_info.is_generational_system = 1; o->gc_info.use_non_predictive_collector = 1; } else if (sizearg( "-stepsize", &argc, &argv, &o->gc_info.dynamic_np_info.stepsize )) { o->gc_info.is_generational_system = 1; o->gc_info.use_non_predictive_collector = 1; } else if (doublearg( "-phase-detection", &argc, &argv, &phase_detection )) ; else if (numbarg( "-np-remset-limit", &argc, &argv, &np_remset_limit )) ; #endif else if (hstrcmp( *argv, "-nobreak" ) == 0) o->enable_breakpoints = 0; else if (hstrcmp( *argv, "-step" ) == 0) o->enable_singlestep = 1; else if (sizearg( "-min", &argc, &argv, &dynamic_min )) ; else if (sizearg( "-max", &argc, &argv, &dynamic_max )) ; else if (hstrcmp( *argv, "-help" ) == 0 || strcmp( *argv, "-h" ) == 0) help(0); else if (hstrcmp( *argv, "-wizard" ) == 0) help(1); else if (hstrcmp( *argv, "-quiet" ) == 0) o->quiet = 1; else if (hstrcmp( *argv, "-annoy-user" ) == 0) o->annoying = 1; else if (hstrcmp( *argv, "-annoy-user-greatly" ) == 0) { o->annoying = 1; o->supremely_annoying = 1; } else if (hstrcmp( *argv, "-flush" ) == 0) o->flush = 1; else if (hstrcmp( *argv, "-noflush" ) == 0) o->noflush = 1; else if (hstrcmp( *argv, "-reorganize-and-dump" ) == 0) o->reorganize_and_dump = 1; else if (hstrcmp( *argv, "-heap" ) == 0) { ++argv; --argc; o->heapfile = *argv; } else if (hstrcmp( *argv, "-nobanner" ) == 0) o->nobanner = 1; else if (hstrcmp( *argv, "-foldcase" ) == 0) o->foldcase = 1; else if (hstrcmp( *argv, "-nofoldcase" ) == 0) o->nofoldcase = 1; else if (hstrcmp( *argv, "-r5rs" ) == 0) { o->r5rs = 1; o->foldcase = 1; } else if (hstrcmp( *argv, "-err5rs" ) == 0) o->err5rs = 1; else if (hstrcmp( *argv, "-r6rs" ) == 0) { o->r6rs = 1; o->nobanner = 1; } else if (hstrcmp( *argv, "-ignore1" ) == 0) { o->ignore1 = 1; } else if (hstrcmp( *argv, "-unsafe" ) == 0) o->unsafe = 1; else if (hstrcmp( *argv, "-fast" ) == 0) o->r6fast = 1; else if (hstrcmp( *argv, "-slow" ) == 0) o->r6slow = 1; else if (hstrcmp( *argv, "-pedantic" ) == 0) o->r6pedantic = 1; else if (hstrcmp( *argv, "-but-not-that-pedantic" ) == 0) o->r6less_pedantic = 1; else if (hstrcmp( *argv, "-program" ) == 0) { ++argv; --argc; o->r6program = *argv; } else if (hstrcmp( *argv, "-path" ) == 0) { ++argv; --argc; /* FIXME */ if (hstrcmp ( o->r6path, "" ) == 0) { o->r6path = *argv; } else { param_error ( "Currently, only one path can be specified. " ); } } else if (numbarg( "-transcoder", &argc, &argv, &(o->transcoder) )) { if ((o->transcoder < 32) || (o->transcoder >= 128)) param_error( "Illegal transcoder" ); } else if (hstrcmp( *argv, "-latin1" ) == 0) { if (o->transcoder == 0) o->transcoder = 33; else param_error( "Only one default transcoder can be specified." ); } else if (hstrcmp( *argv, "-utf8" ) == 0) { if (o->transcoder == 0) o->transcoder = 65; else param_error( "Only one default transcoder can be specified." ); } else if (hstrcmp( *argv, "-utf16" ) == 0) { param_error( "UTF-16 console ports are not yet implemented." ); if (o->transcoder == 0) o->transcoder = 97; else param_error( "Only one default transcoder can be specified." ); } else if (hstrcmp( *argv, "-args" ) == 0 || strcmp( *argv, "--" ) == 0) { o->restc = argc-1; o->restv = argv+1; break; } #if defined(BDW_GC) else if (numbarg( "-divisor", &argc, &argv, &divisor )) { if (divisor < 1) param_error( "Divisor must be at least 1." ); } else if (doublearg( "-expansion", &argc, &argv, &expansion )) { if (expansion < 1.0) param_error( "Expansion factor must be at least 1.0" ); } #endif else if (**argv == '-') { consolemsg( "Error: Invalid option '%s'", *argv ); usage(); } else { consolemsg( "Error: Deprecated heap file syntax." ); usage(); } } /* Initial validation */ if (o->foldcase && o->nofoldcase) param_error( "Both -foldcase and -nofoldcase selected." ); if ((o->r5rs && (o->err5rs || o->r6rs)) || (o->err5rs && (o->r5rs || o->r6rs)) || (o->r6rs && (o->r5rs || o->err5rs))) param_error( "More than one of -r5rs -err5rs -r6rs selected." ); if ((o->r6slow || o->r6pedantic) && ((! (o->r6rs)) || (! (o->r6slow)) || (! (o->r6pedantic)) || (o->r6program == 0))) param_error( "Missing one of -r6rs -slow -pedantic -program options." ); if (o->r6less_pedantic && (! (o->r6pedantic))) param_error( "Missing -pedantic option." ); if (o->r6slow && (strcmp (o->r6path, "") != 0)) param_error( "The -slow and -path options are incompatible." ); if ((strcmp (o->r6program, "") != 0) && (! (o->r6rs))) param_error( "Missing -r6rs option." ); if (o->ignore1 && (! (o->r6program))) param_error( "Missing -program option." ); if ((((int)o->gc_info.is_conservative_system) + ((int)o->gc_info.is_generational_system) + ((int)o->gc_info.is_stopcopy_system) + ((int)o->gc_info.is_regional_system)) > 1) { param_error( "More than one kind of collector tech selected." ); } if (o->gc_info.is_conservative_system && (o->gc_info.is_generational_system || o->gc_info.is_stopcopy_system || o->gc_info.is_regional_system)) param_error( "Both precise and conservative gc selected." ); if (o->gc_info.is_generational_system && o->gc_info.is_stopcopy_system) param_error( "Both generational and non-generational gc selected." ); /* TODO: double check logic in this case. */ if (!o->gc_info.is_stopcopy_system && !o->gc_info.is_conservative_system && !o->gc_info.is_regional_system && o->gc_info.ephemeral_info == 0) init_generational( o, areas, "*invalid*" ); if (o->gc_info.is_generational_system) if (load_factor < 2.0) param_error( "Load factor must be at least 2.0" ); if (dynamic_max && dynamic_min && dynamic_max < dynamic_min) param_error( "Expandable MAX is less than expandable MIN." ); if (dynamic_max || dynamic_min) { int n = (o->gc_info.is_generational_system ? areas-1 : 0); if (o->size[n] && dynamic_max && o->size[n] > dynamic_max) param_error( "Size of expandable area is larger than selected max." ); if (o->size[n] && dynamic_min && o->size[n] < dynamic_min) param_error( "Size of expandable area is smaller than selected min." ); } /* Complete parameter structure by computing the not-specified values. */ if (o->gc_info.is_generational_system) { int n = areas-1; /* Index of dynamic generation */ /* Nursery */ o->gc_info.nursery_info.size_bytes = (o->size[0] > 0 ? o->size[0] : DEFAULT_NURSERY_SIZE); /* Ephemeral generations */ prev_size = o->gc_info.nursery_info.size_bytes; for ( i = 1 ; i <= areas-2 ; i++ ) { if (o->size[i] == 0) o->size[i] = prev_size + DEFAULT_EPHEMERAL_INCREMENT; o->gc_info.ephemeral_info[i-1].size_bytes = o->size[i]; prev_size = o->size[i]; } /* Dynamic generation */ #if ROF_COLLECTOR if (o->gc_info.use_non_predictive_collector) { int size; o->gc_info.dynamic_np_info.load_factor = load_factor; o->gc_info.dynamic_np_info.dynamic_max = dynamic_max; o->gc_info.dynamic_np_info.dynamic_min = dynamic_min; if (o->size[n] != 0) o->gc_info.dynamic_np_info.size_bytes = o->size[n]; size = prev_size + DEFAULT_DYNAMIC_INCREMENT; if (dynamic_min) size = max( dynamic_min, size ); if (dynamic_max) size = min( dynamic_max, size ); compute_np_parameters( o, size ); if (feeling_lucky < 0.0 || feeling_lucky > 1.0) param_error( "NP luck parameter (-feeling-lucky) out of range." ); else o->gc_info.dynamic_np_info.luck = feeling_lucky; if (phase_detection != -1.0 && (phase_detection < 0.0 || phase_detection > 1.0)) param_error( "NP phase detection paramater out of range." ); else o->gc_info.dynamic_np_info.phase_detection = phase_detection; if (np_remset_limit < 0) param_error( "NP remset limit must be nonnegative." ); else o->gc_info.dynamic_np_info.extra_remset_limit = np_remset_limit; } #endif /* ROF_COLLECTOR */ else { o->gc_info.dynamic_sc_info.load_factor = load_factor; o->gc_info.dynamic_sc_info.dynamic_max = dynamic_max; o->gc_info.dynamic_sc_info.dynamic_min = dynamic_min; if (o->size[n] == 0) { int size = prev_size + DEFAULT_DYNAMIC_INCREMENT; if (dynamic_min) size = max( dynamic_min, size ); if (dynamic_max) size = min( dynamic_max, size ); o->gc_info.dynamic_sc_info.size_bytes = size; } else o->gc_info.dynamic_sc_info.size_bytes = o->size[n]; } } else if (o->gc_info.is_stopcopy_system) { if (o->size[0] == 0) { int size = DEFAULT_STOPCOPY_SIZE; if (dynamic_min) size = max( dynamic_min, size ); if (dynamic_max) size = min( dynamic_max, size ); o->gc_info.sc_info.size_bytes = size; } else o->gc_info.sc_info.size_bytes = o->size[0]; /* Already validated */ o->gc_info.sc_info.load_factor = load_factor; o->gc_info.sc_info.dynamic_min = dynamic_min; o->gc_info.sc_info.dynamic_max = dynamic_max; } else if (o->gc_info.is_conservative_system) { if (load_factor > 0.0 && expansion > 0.0) param_error( "-load and -expansion are mutually exclusive." ); o->gc_info.bdw_info.load_factor = load_factor; o->gc_info.bdw_info.expansion_factor = expansion; o->gc_info.bdw_info.divisor = divisor; o->gc_info.bdw_info.dynamic_min = dynamic_min; o->gc_info.bdw_info.dynamic_max = dynamic_max; } else if (o->gc_info.is_regional_system) { /* (roughly cut and pasted from is_generational_system case above) */ /* Nursery */ o->gc_info.nursery_info.size_bytes = (o->size[0] > 0 ? o->size[0] : DEFAULT_REGIONAL_NURSERY_SIZE); /* Ephemeral generations */ prev_size = 5*o->gc_info.nursery_info.size_bytes; if (prev_size < DEFAULT_REGIONAL_REGION_SIZE) prev_size = DEFAULT_REGIONAL_REGION_SIZE; for ( i = 1 ; i <= areas ; i++ ) { if (o->size[i] == 0) o->size[i] = prev_size; assert( o->size[i] > 0 ); o->gc_info.ephemeral_info[i-1].size_bytes = o->size[i]; prev_size = o->size[i]; } o->gc_info.dynamic_sc_info.load_factor = load_factor; o->gc_info.dynamic_sc_info.load_factor_hard = load_factor_hard; o->gc_info.dynamic_sc_info.dynamic_max = dynamic_max; o->gc_info.dynamic_sc_info.dynamic_min = dynamic_min; } } #if ROF_COLLECTOR /* Note that by design, we do not take the load factor into account. */ static void compute_np_parameters( opt_t *o, int suggested_size ) { int steps = o->gc_info.dynamic_np_info.steps; int stepsize = o->gc_info.dynamic_np_info.stepsize; int size = o->gc_info.dynamic_np_info.size_bytes; if (steps == 0 && stepsize == 0) { if (size == 0) size = suggested_size; stepsize = DEFAULT_STEPSIZE; steps = ceildiv( size, stepsize ); } else if (steps != 0 && stepsize == 0) { if (size == 0) { stepsize = DEFAULT_STEPSIZE; size = stepsize * steps; } else stepsize = size / steps; } else if (steps == 0 && stepsize != 0) { if (size == 0) { steps = DEFAULT_STEPS; size = stepsize * steps; } else steps = size / stepsize; } else size = stepsize * steps; o->gc_info.dynamic_np_info.steps = steps; o->gc_info.dynamic_np_info.stepsize = stepsize; o->gc_info.dynamic_np_info.size_bytes = size; } #endif /* ROF_COLLECTOR */ /* Takes a positive integer only, suffixes K and M are accepted. */ static int sizearg( char *str, int *argc, char ***argv, int *loc ) { if (hstrcmp( **argv, str ) == 0) { if (*argc == 1 || !getsize( *(*argv+1), loc ) || *loc <= 0) { char buf[ 128 ]; sprintf( buf, "%s requires a positive integer.", str ); invalid( buf ); } ++*argv; --*argc; return 1; } else return 0; } /* FIXME: doesn't allow --size0 1M etc */ static int hsizearg( char *str, int *argc, char ***argv, int *var, int *loc ) { int l = strlen(str); if (strncmp( **argv, str, l ) == 0) { if (*(**argv+l) != 0) { if (sscanf( **argv+strlen(str), "%d", loc ) != 1) invalid( str ); } else *loc = 0; if (*argc == 1 || !getsize( *(*argv+1), var )) invalid( str ); ++*argv; --*argc; return 1; } else return 0; } static int numbarg( char *str, int *argc, char ***argv, int *loc ) { if (hstrcmp( **argv, str ) == 0) { if (*argc == 1 || sscanf( *(*argv+1), "%d", loc ) != 1 ) invalid( str ); ++*argv; --*argc; return 1; } else return 0; } static int doublearg( char *str, int *argc, char ***argv, double *loc ) { if (hstrcmp( **argv, str ) == 0) { if (*argc == 1 || sscanf( *(*argv+1), "%lf", loc ) != 1 ) invalid( str ); ++*argv; --*argc; return 1; } else return 0; } static int hnumbarg( char *str, int *argc, char ***argv, int *var, int *loc ) { int l = strlen(str); if (strncmp( **argv, str, l ) == 0) { if (*(**argv+l) != 0) { if (sscanf( **argv+strlen(str), "%d", loc ) != 1) invalid( str ); } else *loc = 0; if (*argc == 1 || sscanf( *(*argv+1), "%d", var ) != 1 ) invalid( str ); ++*argv; --*argc; return 1; } else return 0; } static int getsize( char *s, int *p ) { int r; char c, d; r = sscanf( s, "%i%c%c", p, &c, &d ); if (r == 0) return 0; if (r == 1) return 1; if (r == 3) return 0; if (c == 'M' || c == 'm') { *p *= 1024*1024; return 1; } if (c == 'K' || c == 'k') { *p *= 1024; return 1; } return 0; } static int hstrcmp( const char *s1, const char *s2 ) { /* Treat --foo as equivalent to -foo; --foo is standard (in other programs) */ if (s1[0] == '-' && s1[1] == '-') return strcmp( s1+1, s2 ); else return strcmp( s1, s2 ); } static void dump_options( opt_t *o ) { int i; consolemsg( "" ); consolemsg( "Command line parameter dump" ); consolemsg( "---------------------------" ); consolemsg( "Stepping: %d", o->enable_singlestep ); consolemsg( "Breakpoints: %d", o->enable_breakpoints ); consolemsg( "Timer: %d (val=%d)", o->enable_timer, o->timerval ); consolemsg( "Heap file: %s", o->heapfile ); consolemsg( "Quiet: %d", o->quiet ); consolemsg( "Annoying: %d", o->annoying ); consolemsg( "Supremely annoying: %d", o->supremely_annoying ); consolemsg( "Flush/noflush: %d/%d", o->flush, o->noflush ); consolemsg( "Reorganize and dump: %d", o->reorganize_and_dump ); consolemsg( "" ); if (o->gc_info.is_conservative_system) { consolemsg( "Using conservative garbage collector." ); consolemsg( " Incremental: %d", o->gc_info.use_incremental_bdw_collector); consolemsg( " Inverse load factor: %f", o->gc_info.bdw_info.load_factor ); consolemsg( " Inverse expansion factor: %f", o->gc_info.bdw_info.expansion_factor ); consolemsg( " Divisor: %d", o->gc_info.bdw_info.divisor ); consolemsg( " Min size: %d", o->gc_info.bdw_info.dynamic_min ); consolemsg( " Max size: %d", o->gc_info.bdw_info.dynamic_max ); } else if (o->gc_info.is_stopcopy_system) { consolemsg( "Using stop-and-copy garbage collector." ); consolemsg( " Size (bytes): %d", o->gc_info.sc_info.size_bytes ); consolemsg( " Inverse load factor: %f", o->gc_info.sc_info.load_factor ); consolemsg( " Using static area: %d", o->gc_info.use_static_area ); consolemsg( " Min size: %d", o->gc_info.sc_info.dynamic_min ); consolemsg( " Max size: %d", o->gc_info.sc_info.dynamic_max ); } else if (o->gc_info.is_regional_system) { consolemsg( "Using regional garbage collector." ); consolemsg( " Nursery" ); consolemsg( " Size (bytes): %d", o->gc_info.nursery_info.size_bytes ); for ( i=1 ; i<= o->gc_info.ephemeral_area_count ; i++ ) { consolemsg( " Ephemeral area %d", i ); consolemsg( " Size (bytes): %d", o->gc_info.ephemeral_info[i-1].size_bytes ); } consolemsg( " Using static area: %d", o->gc_info.use_static_area ); } else if (o->gc_info.is_generational_system) { consolemsg( "Using generational garbage collector." ); consolemsg( " Nursery" ); consolemsg( " Size (bytes): %d", o->gc_info.nursery_info.size_bytes ); for ( i=1 ; i<= o->gc_info.ephemeral_area_count ; i++ ) { consolemsg( " Ephemeral area %d", i ); consolemsg( " Size (bytes): %d", o->gc_info.ephemeral_info[i-1].size_bytes ); } #if ROF_COLLECTOR if (o->gc_info.use_non_predictive_collector ) { np_info_t *i = &o->gc_info.dynamic_np_info; consolemsg( " Dynamic area (nonpredictive copying)" ); consolemsg( " Steps: %d", i->steps ); consolemsg( " Step size (bytes): %d", i->stepsize ); consolemsg( " Total size (bytes): %d", i->size_bytes ); consolemsg( " Inverse load factor: %f", i->load_factor ); consolemsg( " Min size: %d", i->dynamic_min ); consolemsg( " Max size: %d", i->dynamic_max ); consolemsg( " Luck: %f", i->luck ); } else #endif { sc_info_t *i = &o->gc_info.dynamic_sc_info; consolemsg( " Dynamic area (normal copying)" ); consolemsg( " Size (bytes): %d", i->size_bytes ); consolemsg( " Inverse load factor: %f", i->load_factor ); consolemsg( " Min size: %d", i->dynamic_min ); consolemsg( " Max size: %d", i->dynamic_max ); } consolemsg( " Using non-predictive dynamic area: %d", o->gc_info.use_non_predictive_collector ); consolemsg( " Using static area: %d", o->gc_info.use_static_area ); } else { consolemsg( "ERROR: inconsistency: GC type not known." ); exit( 1 ); } consolemsg( "---------------------------" ); } static void param_error( char *s ) { consolemsg( "Error: %s", s ); usage(); } static void invalid( char *s ) { consolemsg( "" ); consolemsg( "Error: Invalid argument to option: %s", s ); consolemsg( "Type \"larceny -help\" for help." ); exit( 1 ); } static void usage( void ) { consolemsg( "" ); consolemsg( "Usage: larceny [ OPTIONS ][-- ARGUMENTS]" ); consolemsg( "Type \"larceny -help\" for help." ); exit( 1 ); } #define STR(x) STR2(x) #define STR2(x) #x static char *helptext[] = { " -heap <filename>", " Select the initial heap image.", " -nofoldcase", " Symbols are case-sensitive (the default; #!fold-case overrides).", " -foldcase", " Symbols are case-insensitive (#!no-fold-case overrides).", " -latin1", " Use Latin-1 as default for console and file io.", " -utf8", " Use UTF-8 as default for console and file io.", " -utf16", " Use UTF-16 as default for console and file io (not yet allowed).", " -r5rs", " Enter Larceny's traditional read/eval/print loop (the default).", " -err5rs", " Enter an ERR5RS read/eval/print loop.", " -r6rs", " Execute an R6RS-style program in batch mode.", " The following option should also be specified:", " -program <filename>", " Execute the R6RS-style program found in the file.", " -path <directories>", " Search the directories when using require or import.", " Use colon (Unix) or semicolon (Windows) to separate directories.", " -quiet", " Suppress nonessential messages.", " -nobanner", " Suppress runtime startup banner (implied by -r6rs).", " -- <argument> ...", " Tell (command-line-arguments) to return #(<argument> ...)", " This option, if present, must come last.", " In R5RS and ERR5RS modes, Larceny's standard heap interprets", " these command line arguments:", " -e <expr>", " Evaluate <expr> at startup.", " <file>", " Load the specified file (if it exists) at startup.", " -help", " Print this message.", " -wizard", " Print this message as well as help on wizard options.", "", 0 }; static char *wizardhelptext[] = { " (Wizard options below this point.)", " -unsafe", " Crash spectacularly when errors occur.", " These five options may accompany the -r6rs option:", " -ignore1", " Ignore the first line of the file specified by -program.", " -fast", " Execute the R6RS-style program as compiled code (the default).", " -slow", " Execute in Spanky mode; must be accompanied by -pedantic.", " -pedantic", " Execute in Spanky mode; must be accompanied by -slow.", " -but-not-that-pedantic", " Modifies -pedantic, which must also be specified.", " -transcoder nn", " Use transcoder nn for console io.", #if !defined(BDW_GC) " -annoy-user", " Print a bunch of annoying debug messages, usually about GC.", " -annoy-user-greatly", " Print a great many very annoying debug messages, usually about GC.", " -stopcopy", " Use the stop-and-copy garbage collector." , " -gen", " Use the standard generational collector. This is the default.", #if ROF_COLLECTOR " -rof", " Use the hybrid renewal-oldest-first collector (experimental).", #endif " -regional", " Use the bounded-latency regional collector (experimental).", " -load d", " Use inverse load factor d to control allocation and collection.", " The garbage collector will try to resize the heap as necessary", " to keep memory consumption below d*live, where live data", " is computed or estimated following major collections.", #if !defined(BDW_GC) " The regional collector allows d to be less than 2.0.", " All of Larceny's other collectors require d to be at least 2.0.", " The default is 3.0.", #else " In the conservative collector, d must be at least 1.0; no default is", " set, as the conservative collector by default manages heap growth", " using the heap space divisor (see -divisor parameter). The -load", " and -expansion parameters are mutually exclusive.", #endif " -min nnnn", " Set the lower limit on the size of the expandable (\"dynamic\") area.", " -max nnnn", " Set the upper limit on the size of the expandable (\"dynamic\") area.", " -size# nnnn", " Heap area number '#' is given size 'nnnn' bytes.", " Area 0 is the nursery.", " If # > 1, this selects the standard generational collector.", " -areas n", " Use the standard generational collector with n heap areas.", " The default number of heap areas is " STR(DEFAULT_AREAS) ".", #endif #if defined(BDW_GC) " -divisor n", " The divisor controls collection frequency: at least heapsize/n bytes", " are allocated between one collection and the next. The default value", " is 4, and n=1 effectively disables GC. The divisor is the", " conservative collector's default allocation and expansion control.", " -expansion d", " Use expansion factor d to control heap expansion. Following garbage", " collection the heap size is set to max(live*d,heapsize). No", " expansion factor is set by default, as the conservative collector", " manages heap growth using the heap space divisor (see -divisor", " parameter). The -expansion and -load parameters are mutually", " exclusive.", #endif /* need double indirection to get a number in output rather than just the * literal "DEFAULT_MMU_BUFFER_SIZE" */ #define STRINGIZE(val) #val #define STRINGIZE2(val) STRINGIZE(val) #if !defined(BDW_GC) " -nostatic", " Do not use the static area, but load the heap image into the", " garbage-collected heap." , " -nocontract", " Do not allow the heap to contract according to the load factor,", " but continue to use all memory that has been allocated.", " -mmusize n", " Record minimum mutator utilization within a buffer of size n.", " If n is 0, the default size (" STRINGIZE2(DEFAULT_MMU_BUFFER_SIZE) ") will be used.", /* The --regions option can cause a Larceny panic. */ #if 0 " -regions n", " Use the regional collector with n heap areas.", " The default number number of heap areas is " STR(DEFAULT_AREAS) ".", #endif /* These make sense only for researchers, who can read the code base. */ #if 0 /* FIXME * The -refinement switch should be exposed, but Will doesn't fully * understand its semantics, and there's an ad hoc adjustment in * memmgr.c anyway. */ " -refinement d", " For the regional collector only: Allocate d words for each", " word marked. Incompatible with -mark_period. The default is 1.0.", " -mark_period n", " For the regional collector only: Do some incremental marking", " after every n minor collections. Incompatible with -refinement.", " -oracle", " For the regional collector only: Don't count time spent updating", " the remembered set. (Used to estimate the cost of updating.)", " -print_float_stats_cycle", " -print_float_stats_major", " -print_float_stats_minor", " -print_float_stats_refine", " For the regional collector only: Print information about object", " float during various stages of regional collection. The character", " 'Z' represents trivially collectable storage, 'R' represents ", " dead storage referenced from unreachable objects in other regions", " (and thus not guaranteed to be reclaimed in next major collection).", #endif /* Users should probably use the regional collector instead. */ #if 0 #if ROF_COLLECTOR " -steps n", " Select the initial number of steps in the non-predictive collector.", " This selects generational collection and the non-predictive GC.", " -stepsize nnnn", " Select the size of each step in the non-predictive collector.", " This selects generational collection and the non-predictive GC.", " -phase-detection d", " A fudge factor for the non-predictive collector, 0.0 <= d <= 1.0.", " If the non-predictive remembered set has grown by a factor of more ", " than d for some (short) time, and then has grown by a factor of ", " less than d for the same amount of time, then the collector is ", " allowed to decide that a growth phase has ended and that any data", " in the non-predictive young area may be shuffled into the old area", " by adjusting j. This parameter is sometimes very effective at", " reducing float. It does not select anything else, not even the", " nonpredictive GC. By default, phase detection is off.", " Time is measured in the number of promotions into the young area.", " -feeling-lucky d", " A fudge factor for the non-predictive collector, 0.0 <= d <= 1.0.", " After a non-predictive collection and selection of j and k, d*j steps", " are added to k to adjust for the fact that the collector probably", " over-estimates the amount of live storage. This probably only makes", " sense in a fixed-heap setting, where under-estimation may cause", " failure, so you have to ask yourself, do I feel lucky? Well, do you?", " The default value is 0.0. This does not select anything else, not", " even the nonpredictive GC.", " -np-remset-limit n", " A fudge factor for the non-predictive collector, n >= 0.", " If, after a promotion into the non-predictive young area, the number", " of entries in the remembered set that tracks pointers from the", " non-predictive young area to the non-predictive old area, ", " extrapolated to the point when the young area is full, exceeds n, ", " then the collector is allowed to shuffle the entire contents of the", " young area to the old area and to clear the remembered set. By", " default, the limit is infinity. This parameter does not select", " anything else, not even the nonpredictive GC.", #endif #endif " -rhash nnnn", " Set the remembered-set hash table size, in elements. The size must", " be a power of 2.", " -ssb nnnn", " Set the write barrier's Sequential Store Buffer (SSB) size, in " "elements.", " -rhashrep", " Use a hashtable (array) representation of the remembered set.", " -rbitsrep", " Use a bitmap (tree) representation of the remembred set.", #endif " -ticks nnnn", " Set the initial countdown timer interval value.", " -nobreak", " Disable breakpoints." , " -step", " Enable MAL-level single-stepping." , #if !defined(BDW_GC) " -reorganize-and-dump", " Split a heap image into text and data, and save the split heap in a", " file. If Larceny is started with foo.heap, this command will create", " foo.heap.split. The heap image is not executed.", #endif "" , "Values can be decimal, octal (0nnn), hex (0xnnn), or suffixed", "with K (for KB) or M (for MB) when that makes sense." , "", 0 }; static void help(int wizardp) { int i; consolemsg("Usage: larceny [options][-- arg-to-scheme ...]"); consolemsg("" ); consolemsg("Options:" ); for (i=0 ; helptext[i] != 0 ; i++ ) consolemsg( helptext[i] ); if (wizardp) { for (i=0 ; wizardhelptext[i] != 0 ; i++ ) consolemsg( wizardhelptext[i] ); } consolemsg("The Larceny User's Manual is available on the web at"); consolemsg(" http://www.larcenists.org/doc.html/"); exit( 0 ); } int memfail( int code, char *fmt, ... ) { va_list args; static char *code_str[] = { "malloc", "heap", "realloc", "calloc", "rts" }; va_start( args, fmt ); fprintf( stderr, "Allocation failed (code '%s').\n", code_str[code] ); vfprintf( stderr, fmt, args ); va_end( args ); fprintf( stderr, "\n" ); exit( 1 ); /* Never returns; return type is `int' to facilitate an idiom. */ return 0; } void conditional_abort( void ) { char buf[ 10 ]; while (1) { hardconsolemsg( "Abort (yes/no)?" ); if (fgets( buf, 10, stdin ) == NULL) { hardconsolemsg( "EOF -- exiting." ); exit(1); } if (strncasecmp( buf, "yes", 3 ) == 0) abort(); if (strncasecmp( buf, "no", 2 ) == 0) return; } } /* eof */
34.610423
93
0.617407
[ "object", "vector" ]
fb7a5f62b1a33049f053085adf92f69466b7760e
2,000
h
C
component/oai-amf/src/sbi/smf_client/model/SecondaryRatUsageReport.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/smf_client/model/SecondaryRatUsageReport.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/sbi/smf_client/model/SecondaryRatUsageReport.h
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/** * Nsmf_PDUSession * SMF PDU Session Service. © 2019, 3GPP Organizational Partners (ARIB, ATIS, * CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved. * * The version of the OpenAPI document: 1.1.0.alpha-1 * * NOTE: This class is auto generated by OpenAPI-Generator 4.1.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ /* * SecondaryRatUsageReport.h * * */ #ifndef OAI_SMF_MODEL_SecondaryRatUsageReport_H_ #define OAI_SMF_MODEL_SecondaryRatUsageReport_H_ #include "../ModelBase.h" #include "QosFlowUsageReport.h" #include "RatType.h" #include <vector> namespace oai { namespace smf { namespace model { /// <summary> /// /// </summary> class SecondaryRatUsageReport : public ModelBase { public: SecondaryRatUsageReport(); virtual ~SecondaryRatUsageReport(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; void fromJson(const web::json::value& json) override; void toMultipart( std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; void fromMultiPart( std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// SecondaryRatUsageReport members /// <summary> /// /// </summary> std::shared_ptr<RatType> getSecondaryRatType() const; void setSecondaryRatType(const std::shared_ptr<RatType>& value); /// <summary> /// /// </summary> std::vector<std::shared_ptr<QosFlowUsageReport>>& getQosFlowsUsageData(); void setQosFlowsUsageData( const std::vector<std::shared_ptr<QosFlowUsageReport>>& value); protected: std::shared_ptr<RatType> m_SecondaryRatType; std::vector<std::shared_ptr<QosFlowUsageReport>> m_QosFlowsUsageData; }; } // namespace model } // namespace smf } // namespace oai #endif /* OAI_SMF_MODEL_SecondaryRatUsageReport_H_ */
24.096386
77
0.6875
[ "vector", "model" ]
fb7ff937192746261af31b0d9ff8e0accc6cbefc
5,078
h
C
WDL/lice/lice_extended.h
hor-net/wdl-ol
4a88575f82c0c577b28fc3b27279456b12b187fe
[ "Zlib" ]
2
2017-12-05T04:18:55.000Z
2021-03-20T03:04:56.000Z
WDL/lice/lice_extended.h
Metabog/wdl-ol
bfe87d2c4297d003f2475dc22d460440e5e1b4fa
[ "Zlib" ]
null
null
null
WDL/lice/lice_extended.h
Metabog/wdl-ol
bfe87d2c4297d003f2475dc22d460440e5e1b4fa
[ "Zlib" ]
2
2017-04-24T12:45:33.000Z
2019-12-22T04:31:51.000Z
#ifndef _LICE_EXTENDED_ #define _LICE_EXTENDED_ #include "lice.h" #define DISABLE_LICE_EXTENSIONS // stuff to pass to LICE_IBitmap::Extended enum // IDs { LICE_EXT_SUPPORTS_ID, // data = ID, returns 1 if that extension ID is supported LICE_EXT_CLEAR_ACCEL, LICE_EXT_LINE_ACCEL, LICE_EXT_FILLRECT_ACCEL, LICE_EXT_DRAWCBEZIER_ACCEL, LICE_EXT_DRAWGLYPH_ACCEL, LICE_EXT_BLIT_ACCEL, LICE_EXT_SCALEDBLIT_ACCEL, LICE_EXT_GETFBOTEX_ACCEL, // if the bitmap is implemented as an openGL framebuffer object, get its texture backing store LICE_EXT_DASHEDLINE_ACCEL, LICE_EXT_GETPIXEL_ACCEL, LICE_EXT_PUTPIXEL_ACCEL, LICE_EXT_SETCLIP, // data == 0 to clear clip LICE_EXT_WINDOW_BLIT, LICE_EXT_FORGET, // optimizations can sometimes happen if a bitmap can be told it doesn't need to retain data after it's accessed LICE_EXT_DRAWTRIANGLE_ACCEL, }; struct LICE_Ext_Line_acceldata { float x1, y1, x2, y2; LICE_pixel color; float alpha; int mode; bool aa; LICE_Ext_Line_acceldata(float _x1, float _y1, float _x2, float _y2, LICE_pixel _color, float _alpha, int _mode, bool _aa) : x1(_x1), y1(_y1), x2(_x2), y2(_y2), color(_color), alpha(_alpha), mode(_mode), aa(_aa) {} }; struct LICE_Ext_FillRect_acceldata { int x, y, w, h; LICE_pixel color; float alpha; int mode; LICE_Ext_FillRect_acceldata(int _x, int _y, int _w, int _h, LICE_pixel _color, float _alpha, int _mode) : x(_x), y(_y), w(_w), h(_h), color(_color), alpha(_alpha), mode(_mode) {} }; struct LICE_Ext_DrawCBezier_acceldata { float xstart, ystart, xctl1, yctl1, xctl2, yctl2, xend, yend; LICE_pixel color; float alpha; int mode; bool aa; LICE_Ext_DrawCBezier_acceldata(float _xstart, float _ystart, float _xctl1, float _yctl1, float _xctl2, float _yctl2, float _xend, float _yend, LICE_pixel _color, float _alpha, int _mode, bool _aa) : xstart(_xstart), ystart(_ystart), xctl1(_xctl1), yctl1(_yctl1), xctl2(_xctl2), yctl2(_yctl2), xend(_xend), yend(_yend), color(_color), alpha(_alpha), mode(_mode), aa(_aa) {} }; struct LICE_Ext_DrawGlyph_acceldata { int x; int y; LICE_pixel color; const LICE_pixel_chan* alphas; int glyph_w, glyph_h; float alpha; int mode; LICE_Ext_DrawGlyph_acceldata(int _x, int _y, LICE_pixel _color, LICE_pixel_chan* _alphas, int _glyph_w, int _glyph_h, float _alpha, int _mode) : x(_x), y(_y), color(_color), alphas(_alphas), glyph_w(_glyph_w), glyph_h(_glyph_h), alpha(_alpha), mode(_mode) {} }; struct LICE_Ext_Blit_acceldata { LICE_IBitmap* src; int dstx, dsty, srcx, srcy, srcw, srch; float alpha; int mode; LICE_Ext_Blit_acceldata(LICE_IBitmap* _src, int _dstx, int _dsty, int _srcx, int _srcy, int _srcw, int _srch, float _alpha, int _mode) : src(_src), dstx(_dstx), dsty(_dsty), srcx(_srcx), srcy(_srcy), srcw(_srcw), srch(_srch), alpha(_alpha), mode(_mode) {} }; struct LICE_Ext_ScaledBlit_acceldata { LICE_IBitmap* src; int dstx, dsty, dstw, dsth; float srcx, srcy, srcw, srch; float alpha; int mode; LICE_Ext_ScaledBlit_acceldata(LICE_IBitmap* _src, int _dstx, int _dsty, int _dstw, int _dsth, float _srcx, float _srcy, float _srcw, float _srch, float _alpha, int _mode) : src(_src), dstx(_dstx), dsty(_dsty), dstw(_dstw), dsth(_dsth), srcx(_srcx), srcy(_srcy), srcw(_srcw), srch(_srch), alpha(_alpha), mode(_mode) {} }; struct LICE_Ext_DashedLine_acceldata { float x1, y1, x2, y2; int pxon, pxoff; LICE_pixel color; float alpha; int mode; bool aa; LICE_Ext_DashedLine_acceldata(float _x1, float _y1, float _x2, float _y2, int _pxon, int _pxoff, LICE_pixel _color, float _alpha, int _mode, bool _aa) : x1(_x1), y1(_y1), x2(_x2), y2(_y2), pxon(_pxon), pxoff(_pxoff), color(_color), alpha(_alpha), mode(_mode), aa(_aa) {} }; struct LICE_Ext_GetPixel_acceldata { int x, y; LICE_pixel px; // return LICE_Ext_GetPixel_acceldata(int _x, int _y) : x(_x), y(_y), px(0) {} }; struct LICE_Ext_PutPixel_acceldata { int x, y; LICE_pixel color; float alpha; int mode; LICE_Ext_PutPixel_acceldata(int _x, int _y, LICE_pixel _color, float _alpha, int _mode) : x(_x), y(_y), color(_color), alpha(_alpha), mode(_mode) {} }; struct LICE_Ext_SetClip_data { int x, y, w, h; LICE_Ext_SetClip_data(int _x, int _y, int _w, int _h) : x(_x), y(_y), w(_w), h(_h) {} }; class pl_Mat; struct LICE_Ext_DrawTriangle_acceldata { pl_Mat *mat; // will need to include plush.h to access this double VertexShades[3][3]; // for solid element float scrx[3], scry[3], scrz[3]; // scrz = 1/Zdist double mapping_coords[2][3][2]; // [texture or texture2][vertex][uv] }; struct LICE_Ext_WindowBlit_data { HWND hwnd; int destx, desty, srcx, srcy, w, h; LICE_Ext_WindowBlit_data(HWND _hwnd, int _destx, int _desty, int _srcx, int _srcy, int _w, int _h) : hwnd(_hwnd), destx(_destx), desty(_desty), srcx(_srcx), srcy(_srcy), w(_w), h(_h) {} }; #endif
30.775758
173
0.693974
[ "object", "solid" ]
fb8000548210bb9ca23119ac263195d457f232d3
1,937
h
C
model/ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload.h
eZmaxinc/eZmax-SDK-c
355145bda84cbd548159163391ef09d1ef3c204d
[ "curl", "MIT" ]
null
null
null
model/ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload.h
eZmaxinc/eZmax-SDK-c
355145bda84cbd548159163391ef09d1ef3c204d
[ "curl", "MIT" ]
null
null
null
model/ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload.h
eZmaxinc/eZmax-SDK-c
355145bda84cbd548159163391ef09d1ef3c204d
[ "curl", "MIT" ]
null
null
null
/* * ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload.h * * Payload for the /1/object/ezsignfoldersignerassociation/getInPersonLoginUrl API Request */ #ifndef _ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_H_ #define _ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_H_ #include <string.h> #include "../external/cJSON.h" #include "../include/list.h" #include "../include/keyValuePair.h" #include "../include/binary.h" typedef struct ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t; typedef struct ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t { char *s_login_url; // string } ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t; ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t *ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_create( char *s_login_url ); void ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_free(ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t *ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload); ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t *ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_parseFromJSON(cJSON *ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payloadJSON); cJSON *ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_convertToJSON(ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_t *ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload); #endif /* _ezsignfoldersignerassociation_get_in_person_login_url_v1_response_m_payload_H_ */
50.973684
257
0.9143
[ "object" ]
fb95aedd23a07998b26f09679ab268e1655007ff
17,974
c
C
src/c_wn_stdscr.c
yuneta/yuno_cli
75485227f73309ff4220c25a15946f26ba963d3e
[ "MIT" ]
null
null
null
src/c_wn_stdscr.c
yuneta/yuno_cli
75485227f73309ff4220c25a15946f26ba963d3e
[ "MIT" ]
null
null
null
src/c_wn_stdscr.c
yuneta/yuno_cli
75485227f73309ff4220c25a15946f26ba963d3e
[ "MIT" ]
null
null
null
/*********************************************************************** * C_WN_STDSCR.C * Wn_stdscr GClass. * * Copyright (c) 2015-2016 Niyamaka. * All Rights Reserved. ***********************************************************************/ #include <signal.h> #include <sys/ioctl.h> #include <ncurses/ncurses.h> #include <string.h> #include "c_wn_stdscr.h" /*************************************************************************** * Constants ***************************************************************************/ /*************************************************************************** * Structures ***************************************************************************/ /*************************************************************************** * Prototypes ***************************************************************************/ PRIVATE int get_color_pair(int fg, int bg); PRIVATE int get_color_id(const char *color); PRIVATE void my_endwin(void) { endwin();} PRIVATE void catch_signals(void); /*************************************************************************** * Data: config, public data, private data ***************************************************************************/ PRIVATE struct { int id; const char *name; } table_id[] = { {COLOR_BLACK, "black"}, {COLOR_RED, "red"}, {COLOR_GREEN, "green"}, {COLOR_YELLOW, "yellow"}, {COLOR_BLUE, "blue"}, {COLOR_MAGENTA, "magenta"}, {COLOR_CYAN, "cyan"}, {COLOR_WHITE, "white"} }; // When SetFocus is rejected (return -1) the focus will be set int __gobj_default_focus__ PRIVATE hgobj __gobj_default_focus__ = 0; PRIVATE hgobj __gobj_with_focus__ = 0; PRIVATE char __new_stdsrc_size__ = FALSE; /*---------------------------------------------* * Attributes - order affect to oid's *---------------------------------------------*/ PRIVATE sdata_desc_t tattr_desc[] = { SDATA (ASN_INTEGER, "timeout", 0, 500, "Timeout, to detect size change in stdscr"), SDATA (ASN_INTEGER, "cx", 0, 0, "cx window size"), SDATA (ASN_INTEGER, "cy", 0, 0, "cy window size"), SDATA (ASN_POINTER, "user_data", 0, 0, "user data"), SDATA (ASN_POINTER, "user_data2", 0, 0, "more user data"), SDATA (ASN_POINTER, "subscriber", 0, 0, "subscriber of output-events. If it's null then subscriber is the parent."), SDATA_END() }; /*---------------------------------------------* * GClass trace levels *---------------------------------------------*/ enum { TRACE_MESSAGES = 0x0001, }; PRIVATE const trace_level_t s_user_trace_level[16] = { {"messages", "Trace messages"}, {0, 0}, }; /*---------------------------------------------* * Private data *---------------------------------------------*/ typedef struct _PRIVATE_DATA { hgobj timer; int32_t timeout; WINDOW *wn; // ncurses handler uint32_t cx; uint32_t cy; } PRIVATE_DATA; /****************************** * Framework Methods ******************************/ /*************************************************************************** * Framework Method create ***************************************************************************/ PRIVATE void mt_create(hgobj gobj) { PRIVATE_DATA *priv = gobj_priv_data(gobj); /* * CHILD subscription model */ hgobj subscriber = (hgobj)gobj_read_pointer_attr(gobj, "subscriber"); if(!subscriber) subscriber = gobj_parent(gobj); gobj_subscribe_event(gobj, NULL, NULL, subscriber); /* * Do copy of heavy used parameters, for quick access. * HACK The writable attributes must be repeated in mt_writing method. */ SET_PRIV(timeout, gobj_read_int32_attr) /* * Start up ncurses */ catch_signals(); atexit(my_endwin); /* * stdscr timer to detect window size change */ priv->timer = gobj_create("", GCLASS_TIMER, 0, gobj); #ifndef TEST_KDEVELOP priv->wn = initscr(); /* Start curses mode */ cbreak(); /* Line buffering disabled */ noecho(); /* Don't echo() while we do getch */ keypad(priv->wn, TRUE); /* We get F1, F2 etc.. */ halfdelay(1); //wtimeout(priv->wn, 10); /* input non-blocking, wait 1 msec */ if(has_colors()) { start_color(); } #endif } /*************************************************************************** * Framework Method writing ***************************************************************************/ PRIVATE void mt_writing(hgobj gobj, const char *path) { PRIVATE_DATA *priv = gobj_priv_data(gobj); IF_EQ_SET_PRIV(timeout, gobj_read_int32_attr) if(gobj_is_running(gobj)) { set_timeout_periodic(priv->timer, priv->timeout); } ELIF_EQ_SET_PRIV(cx, gobj_read_int32_attr) ELIF_EQ_SET_PRIV(cy, gobj_read_int32_attr) END_EQ_SET_PRIV() } /*************************************************************************** * Framework Method start ***************************************************************************/ PRIVATE int mt_start(hgobj gobj) { PRIVATE_DATA *priv = gobj_priv_data(gobj); gobj_start(priv->timer); set_timeout_periodic(priv->timer, priv->timeout); int cx, cy; get_stdscr_size(&cx, &cy); gobj_write_int32_attr(gobj, "cx", cx); gobj_write_int32_attr(gobj, "cy", cy); //log_debug_printf(0, "initial size cx %d cy %d %s\n", cx, cy, gobj_name(gobj)); json_t *jn_kw = json_object(); json_object_set_new(jn_kw, "cx", json_integer(cx)); json_object_set_new(jn_kw, "cy", json_integer(cy)); gobj_send_event_to_childs(gobj, "EV_SIZE", jn_kw, gobj); gobj_start_childs(gobj); //wrefresh(priv->wn); return 0; } /*************************************************************************** * Framework Method stop ***************************************************************************/ PRIVATE int mt_stop(hgobj gobj) { PRIVATE_DATA *priv = gobj_priv_data(gobj); clear_timeout(priv->timer); gobj_stop(priv->timer); gobj_stop_childs(gobj); return 0; } /*************************************************************************** * Framework Method destroy ***************************************************************************/ PRIVATE void mt_destroy(hgobj gobj) { } /*************************** * Local Methods ***************************/ /*************************************************************************** * ***************************************************************************/ PRIVATE int get_color_pair(int fg, int bg) { static int next_pair = 1; int pair; static int cp[8][8]; if(fg < 0 || fg >= 8 || bg < 0 || bg >= 8) { return 0; } if ((pair = cp[fg][bg])) { return COLOR_PAIR(pair); } if (next_pair >= COLOR_PAIRS) { return 0; } if (init_pair(next_pair, fg, bg) != OK){ return 0; } pair = cp[fg][bg] = next_pair++; return COLOR_PAIR(pair); } /*************************************************************************** * ***************************************************************************/ PRIVATE int get_color_id(const char *color) { int i; int len = ARRAY_NSIZE(table_id); for(i=0; i<len; i++) { if(strcasecmp(table_id[i].name, color)==0) { return table_id[i].id; } } return COLOR_WHITE; } /*************************************************************************** * ***************************************************************************/ PUBLIC int get_stdscr_size(int *w, int *h) { struct winsize size; if(ioctl(fileno(stdout), TIOCGWINSZ, &size) == 0) { resizeterm (size.ws_row, size.ws_col); if(size.ws_col <= 0) { size.ws_col = 80; } if(size.ws_row <= 0) { size.ws_row = 24; } *w = size.ws_col; *h = size.ws_row; } else { int new_width, new_height; getmaxyx(stdscr, new_height, new_width); if(new_width < 0) { new_width = 0; } if(new_height < 0) { new_height = 0; } *w = new_width; *h = new_height; } //printf("w=%d, h=%d\r\n", *w, *h); return 0; } /*************************************************************************** * Signal handlers ***************************************************************************/ PRIVATE void sighandler(int sig) { if(sig == SIGWINCH) { __new_stdsrc_size__ = TRUE; } } PRIVATE void catch_signals(void) { struct sigaction sigIntHandler; memset(&sigIntHandler, 0, sizeof(sigIntHandler)); sigIntHandler.sa_handler = sighandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGWINCH, &sigIntHandler, NULL); } /*************************** * Actions ***************************/ /*************************************************************************** * ***************************************************************************/ PRIVATE int ac_timeout(hgobj gobj, const char *event, json_t *kw, hgobj src) { if(__new_stdsrc_size__) { __new_stdsrc_size__ = FALSE; int cx, cy; get_stdscr_size(&cx, &cy); gobj_write_int32_attr(gobj, "cx", cx); gobj_write_int32_attr(gobj, "cy", cy); json_t *jn_kw = json_object(); json_object_set_new(jn_kw, "cx", json_integer(cx)); json_object_set_new(jn_kw, "cy", json_integer(cy)); json_incref(jn_kw); gobj_send_event_to_childs(gobj, "EV_SIZE", jn_kw, gobj); gobj_publish_event(gobj, "EV_SCREEN_SIZE_CHANGE", jn_kw); } KW_DECREF(kw); return 0; } /*************************************************************************** * FSM ***************************************************************************/ PRIVATE const EVENT input_events[] = { // {"EV_SIZE", 0, 0, 0}, // {"EV_PAINT", 0, 0, 0}, // {"EV_HSCROLL", 0, 0, 0}, // {"EV_VSCROLL", 0, 0, 0}, // {"EV_MOUSE", 0, 0, 0}, // {"EV_KEY", 0, 0, 0}, // {"EV_KILLFOCUS", 0, 0, 0}, // {"EV_SETFOCUS", 0, 0, 0}, // {"EV_MOVE", 0, 0, 0}, {"EV_TIMEOUT", 0, 0, 0}, {"EV_STOPPED", 0, 0, 0}, {NULL, 0, 0, 0} }; PRIVATE const EVENT output_events[] = { {"EV_SCREEN_SIZE_CHANGE", 0, 0, 0}, {NULL, 0, 0, 0} }; PRIVATE const char *state_names[] = { "ST_IDLE", NULL }; PRIVATE EV_ACTION ST_IDLE[] = { {"EV_TIMEOUT", ac_timeout, 0}, {"EV_STOPPED", 0, 0}, {0,0,0} }; PRIVATE EV_ACTION *states[] = { ST_IDLE, NULL }; PRIVATE FSM fsm = { input_events, output_events, state_names, states, }; /*************************************************************************** * GClass ***************************************************************************/ /*---------------------------------------------* * Local methods table *---------------------------------------------*/ PRIVATE LMETHOD lmt[] = { {0, 0, 0} }; /*---------------------------------------------* * GClass *---------------------------------------------*/ PRIVATE GCLASS _gclass = { 0, // base GCLASS_WN_STDSCR_NAME, &fsm, { mt_create, 0, //mt_create2, mt_destroy, mt_start, mt_stop, 0, //mt_play, 0, //mt_pause, mt_writing, 0, //mt_reading, 0, //mt_subscription_added, 0, //mt_subscription_deleted, 0, //mt_child_added, 0, //mt_child_removed, 0, //mt_stats, 0, //mt_command, 0, //mt_inject_event, 0, //mt_create_resource, 0, //mt_list_resource, 0, //mt_update_resource, 0, //mt_delete_resource, 0, //mt_add_child_resource_link 0, //mt_delete_child_resource_link 0, //mt_get_resource 0, //mt_authorization_parser, 0, //mt_authenticate, 0, //mt_list_childs, 0, //mt_stats_updated, 0, //mt_disable, 0, //mt_enable, 0, //mt_trace_on, 0, //mt_trace_off, 0, //mt_gobj_created, 0, //mt_future33, 0, //mt_future34, 0, //mt_publish_event, 0, //mt_publication_pre_filter, 0, //mt_publication_filter, 0, //mt_authz_checker, 0, //mt_future39, 0, //mt_create_node, 0, //mt_update_node, 0, //mt_delete_node, 0, //mt_link_nodes, 0, //mt_future44, 0, //mt_unlink_nodes, 0, //mt_topic_jtree, 0, //mt_get_node, 0, //mt_list_nodes, 0, //mt_shoot_snap, 0, //mt_activate_snap, 0, //mt_list_snaps, 0, //mt_treedbs, 0, //mt_treedb_topics, 0, //mt_topic_desc, 0, //mt_topic_links, 0, //mt_topic_hooks, 0, //mt_node_parents, 0, //mt_node_childs, 0, //mt_list_instances, 0, //mt_node_tree, 0, //mt_topic_size, 0, //mt_future62, 0, //mt_future63, 0, //mt_future64 }, lmt, tattr_desc, sizeof(PRIVATE_DATA), 0, // acl s_user_trace_level, 0, // cmds 0, // gcflag }; /*************************************************************************** * Public access ***************************************************************************/ PUBLIC GCLASS *gclass_wn_stdscr(void) { return &_gclass; } /*************************************************************************** * ***************************************************************************/ PUBLIC int _get_curses_color(const char *fg_color, const char *bg_color) { return get_color_pair( get_color_id(fg_color), get_color_id(bg_color) ); } /*************************************************************************** * ***************************************************************************/ PUBLIC int SetDefaultFocus(hgobj gobj) { __gobj_default_focus__ = gobj; return 0; } /*************************************************************************** * ***************************************************************************/ PUBLIC int SetFocus(hgobj gobj) { if(gobj != __gobj_with_focus__) { // Si hay nuevo focus avisa al antiguo if(__gobj_with_focus__) { gobj_send_event(__gobj_with_focus__, "EV_KILLFOCUS", 0, 0); if(gobj_trace_level(gobj) & (TRACE_MACHINE|TRACE_EV_KW)) { trace_msg("👁 👁 ⏪ %s", gobj_short_name(__gobj_with_focus__)); } } } __gobj_with_focus__ = gobj; if(gobj_send_event(__gobj_with_focus__, "EV_SETFOCUS", 0, 0)<0) { // Si el nuevo focus no acepta pon el default focus __gobj_with_focus__ = __gobj_default_focus__; gobj_send_event(__gobj_default_focus__, "EV_SETFOCUS", 0, 0); if(gobj_trace_level(gobj) & (TRACE_MACHINE|TRACE_EV_KW)) { trace_msg("👁 👁 ⏩ %s", gobj_short_name(__gobj_with_focus__)); } } else { if(gobj_trace_level(gobj) & (TRACE_MACHINE|TRACE_EV_KW)) { trace_msg("👁 👁 ⏩ %s", gobj_short_name(__gobj_with_focus__)); } } return 0; } /*************************************************************************** * ***************************************************************************/ PUBLIC hgobj GetFocus(void) { return __gobj_with_focus__; } /*************************************************************************** * ***************************************************************************/ PUBLIC int SetTextColor(hgobj gobj, const char *color) { return gobj_write_str_attr(gobj, "fg_color", color); } /*************************************************************************** * ***************************************************************************/ PUBLIC int SetBkColor(hgobj gobj, const char *color) { return gobj_write_str_attr(gobj, "bk_color", color); } /*************************************************************************** * ***************************************************************************/ PUBLIC int DrawText(hgobj gobj, int x, int y, const char *s) { json_t *kw = json_pack("{s:s, s:i, s:i}", "text", s, "x", x, "y", y ); gobj_send_event(gobj, "EV_SETTEXT", kw, gobj); if(__gobj_with_focus__) { gobj_send_event(__gobj_with_focus__, "EV_SETFOCUS", 0, 0); } return 0; } /*************************************************************************** * ***************************************************************************/ PRIVATE int cb_play(rc_instance_t *i_gobj, hgobj gobj, void *user_data, void *user_data2, void *user_data3) { gobj_play(gobj); return 0; } PRIVATE int cb_pause(rc_instance_t *i_gobj, hgobj gobj, void *user_data, void *user_data2, void *user_data3) { gobj_pause(gobj); return 0; } PUBLIC int EnableWindow(hgobj gobj, BOOL enable) { if(enable) { gobj_walk_gobj_childs_tree(gobj, WALK_TOP2BOTTOM, cb_play, 0, 0, 0); // TODO send EV_ACTIVATE si es una window padre } else { gobj_walk_gobj_childs_tree(gobj, WALK_TOP2BOTTOM, cb_pause, 0, 0, 0); } return 0; }
29.369281
131
0.421998
[ "model" ]
fb9b389f57cf8d8cf4ffde0d9840effddbae9441
6,125
c
C
TH/crp_pc/golay23.c
gegel/JackPair_Win
b3400ae8cb4d05c806244dc485f16b85c7a00395
[ "Unlicense" ]
4
2019-05-18T19:01:22.000Z
2021-01-17T07:59:02.000Z
TH/crp_pc/golay23.c
gegel/JackPair_Win
b3400ae8cb4d05c806244dc485f16b85c7a00395
[ "Unlicense" ]
null
null
null
TH/crp_pc/golay23.c
gegel/JackPair_Win
b3400ae8cb4d05c806244dc485f16b85c7a00395
[ "Unlicense" ]
1
2021-01-17T07:59:04.000Z
2021-01-17T07:59:04.000Z
/*---------------------------------------------------------------------------*\ FILE........: golay23.c AUTHOR......: Robert Morelos-Zaragoza & David Rowe DATE CREATED: 3 March 2013 To test: src$ gcc golay23.c -o golay23 -Wall -DGOLAY23_UNITTEST -DRUN_TIME_TABLES src$ ./golay23 To generate tables: src$ gcc golay23.c -o golay23 -Wall -DGOLAY23_MAKETABLES -DRUN_TIME_TABLES \*---------------------------------------------------------------------------*/ /* File: golay23.c * Title: Encoder/decoder for a binary (23,12,7) Golay code * Author: Robert Morelos-Zaragoza (robert@spectra.eng.hawaii.edu) * Date: August 1994 * * The binary (23,12,7) Golay code is an example of a perfect code, that is, * the number of syndromes equals the number of correctable error patterns. * The minimum distance is 7, so all error patterns of Hamming weight up to * 3 can be corrected. The total number of these error patterns is: * * Number of errors Number of patterns * ---------------- ------------------ * 0 1 * 1 23 * 2 253 * 3 1771 * ---- * Total number of error patterns = 2048 = 2^{11} = number of syndromes * -- * number of redundant bits -------^ * * Because of its relatively low length (23), dimension (12) and number of * redundant bits (11), the binary (23,12,7) Golay code can be encoded and * decoded simply by using look-up tables. The program below uses a 16K * encoding table and an 8K decoding table. * * For more information, suggestions, or other ideas on implementing error * correcting codes, please contact me at (I'm temporarily in Japan, but * below is my U.S. address): * * Robert Morelos-Zaragoza * 770 S. Post Oak Ln. #200 * Houston, Texas 77056 * * email: robert@spectra.eng.hawaii.edu * * Homework: Add an overall parity-check bit to get the (24,12,8) * extended Golay code. * * COPYRIGHT NOTICE: This computer program is free for non-commercial purposes. * You may implement this program for any non-commercial application. You may * also implement this program for commercial purposes, provided that you * obtain my written permission. Any modification of this program is covered * by this copyright. * * == Copyright (c) 1994 Robert Morelos-Zaragoza. All rights reserved. == */ #include "golay23.h" #include <stdio.h> #include <stdlib.h> #define X22 0x00400000 /* vector representation of X^{22} */ #define X11 0x00000800 /* vector representation of X^{11} */ #define MASK12 0xfffff800 /* auxiliary vector for testing */ #define GENPOL 0x00000c75 /* generator polinomial, g(x) */ /* Global variables: * * pattern = error pattern, or information, or received vector * encoding_table[] = encoding table * decoding_table[] = decoding table * data = information bits, i(x) * codeword = code bits = x^{11}i(x) + (x^{11}i(x) mod g(x)) * numerr = number of errors = Hamming weight of error polynomial e(x) * position[] = error positions in the vector representation of e(x) * recd = representation of corrupted received polynomial r(x) = c(x) + e(x) * decerror = number of decoding errors * a[] = auxiliary array to generate correctable error patterns */ #include "golayenctable.h" #include "golaydectable.h" void nextcomb(int n, int r, int a[]) /* * Calculate next r-combination of an n-set. */ { int i, j; a[r]++; if (a[r] <= n) return; j = r - 1; while (a[j] == n - r + j) j--; for (i = r; i >= j; i--) a[i] = a[j] + i - j + 1; return; } int get_syndrome(int pattern) /* * Compute the syndrome corresponding to the given pattern, i.e., the * remainder after dividing the pattern (when considering it as the vector * representation of a polynomial) by the generator polynomial, GENPOL. * In the program this pattern has several meanings: (1) pattern = infomation * bits, when constructing the encoding table; (2) pattern = error pattern, * when constructing the decoding table; and (3) pattern = received vector, to * obtain its syndrome in decoding. */ { int aux = X22; if (pattern >= X11) while (pattern & MASK12) { while (!(aux & pattern)) aux = aux >> 1; pattern ^= (aux/X11) * GENPOL; } return(pattern); } /*---------------------------------------------------------------------------*\ FUNCTION....: golay23_init() AUTHOR......: David Rowe DATE CREATED: 3 March 2013 Call this once when you start your program to init the Golay tables. \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ FUNCTION....: golay23_encode() AUTHOR......: David Rowe DATE CREATED: 3 March 2013 Given 12 bits of data retiurns a 23 bit codeword for transmission over the channel. \*---------------------------------------------------------------------------*/ int golay23_encode(int data) { return encoding_table[data]; } /*---------------------------------------------------------------------------*\ FUNCTION....: golay23_decode() AUTHOR......: David Rowe DATE CREATED: 3 March 2013 Given a 23 bit received codeword, returns the 12 bit corrected data. \*---------------------------------------------------------------------------*/ int golay23_decode(int received_codeword) { return received_codeword ^= decoding_table[get_syndrome(received_codeword)]; } int golay23_count_errors(int recd_codeword, int corrected_codeword) { int errors = 0; int diff, i; diff = recd_codeword ^ corrected_codeword; for(i=0; i<23; i++) { if (diff & 0x1) errors++; diff >>= 1; } return errors; }
32.407407
80
0.553959
[ "vector" ]
fba1cede73341bffb3f093a489f385d42df85a87
4,259
c
C
pkgs/libs/glib/src/tests/gobject/dynamictype.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
64
2015-03-06T00:30:56.000Z
2022-03-24T13:26:53.000Z
pkgs/libs/glib/src/tests/gobject/dynamictype.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
12
2020-12-15T08:30:19.000Z
2022-03-13T03:54:24.000Z
pkgs/libs/glib/src/tests/gobject/dynamictype.c
manggoguy/parsec-modified
d14edfb62795805c84a4280d67b50cca175b95af
[ "BSD-3-Clause" ]
40
2015-02-26T15:31:16.000Z
2022-03-03T23:23:37.000Z
/* GObject - GLib Type, Object, Parameter and Signal Library * Copyright (C) 2001, 2003 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307, USA. */ #undef G_LOG_DOMAIN #define G_LOG_DOMAIN "TestDynamicType" #undef G_DISABLE_ASSERT #undef G_DISABLE_CHECKS #undef G_DISABLE_CAST_CHECKS #include <glib-object.h> #include "testcommon.h" #include "testmodule.h" /* This test tests the macros for defining dynamic types. */ static gboolean loaded = FALSE; struct _TestIfaceClass { GTypeInterface base_iface; guint val; }; #define TEST_TYPE_IFACE (test_iface_get_type ()) #define TEST_IFACE_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_INTERFACE ((obj), TEST_TYPE_IFACE, TestIfaceClass)) typedef struct _TestIface TestIface; typedef struct _TestIfaceClass TestIfaceClass; static void test_iface_base_init (TestIfaceClass *iface); static void test_iface_default_init (TestIfaceClass *iface, gpointer class_data); static DEFINE_IFACE(TestIface, test_iface, test_iface_base_init, test_iface_default_init) static void test_iface_default_init (TestIfaceClass *iface, gpointer class_data) { } static void test_iface_base_init (TestIfaceClass *iface) { } #define DYNAMIC_OBJECT_TYPE (dynamic_object_get_type ()) typedef GObject DynamicObject; typedef struct _DynamicObjectClass DynamicObjectClass; struct _DynamicObjectClass { GObjectClass parent_class; guint val; }; static void dynamic_object_iface_init (TestIface *iface); G_DEFINE_DYNAMIC_TYPE_EXTENDED(DynamicObject, dynamic_object, G_TYPE_OBJECT, 0, G_IMPLEMENT_INTERFACE_DYNAMIC (TEST_TYPE_IFACE, dynamic_object_iface_init)); static void dynamic_object_class_init (DynamicObjectClass *class) { class->val = 42; loaded = TRUE; } static void dynamic_object_class_finalize (DynamicObjectClass *class) { loaded = FALSE; } static void dynamic_object_iface_init (TestIface *iface) { } static void dynamic_object_init (DynamicObject *dynamic_object) { } static void module_register (GTypeModule *module) { dynamic_object_register_type (module); } static void test_dynamic_type (void) { GTypeModule *module; DynamicObjectClass *class; module = test_module_new (module_register); /* Not loaded until we call ref for the first time */ class = g_type_class_peek (DYNAMIC_OBJECT_TYPE); g_assert (class == NULL); g_assert (!loaded); /* Make sure interfaces work */ g_assert (g_type_is_a (DYNAMIC_OBJECT_TYPE, TEST_TYPE_IFACE)); /* Ref loads */ class = g_type_class_ref (DYNAMIC_OBJECT_TYPE); g_assert (class && class->val == 42); g_assert (loaded); /* Peek then works */ class = g_type_class_peek (DYNAMIC_OBJECT_TYPE); g_assert (class && class->val == 42); g_assert (loaded); /* Make sure interfaces still work */ g_assert (g_type_is_a (DYNAMIC_OBJECT_TYPE, TEST_TYPE_IFACE)); /* Unref causes finalize */ g_type_class_unref (class); /* Peek returns NULL */ class = g_type_class_peek (DYNAMIC_OBJECT_TYPE); g_assert (!class); g_assert (!loaded); /* Ref reloads */ class = g_type_class_ref (DYNAMIC_OBJECT_TYPE); g_assert (class && class->val == 42); g_assert (loaded); /* And Unref causes finalize once more*/ g_type_class_unref (class); class = g_type_class_peek (DYNAMIC_OBJECT_TYPE); g_assert (!class); g_assert (!loaded); } int main (int argc, char *argv[]) { g_log_set_always_fatal (g_log_set_always_fatal (G_LOG_FATAL_MASK) | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL); g_type_init (); test_dynamic_type (); return 0; }
24.477011
106
0.748063
[ "object" ]
fba228b9900d14fa7c6b2e25df421bd5f2e54713
1,646
h
C
src/ripple/rocksdb/rocksdb/tools/shell/DBClientProxy.h
Ziftr/stellard
626514cbbb2c6c2b6844315ca98a2bfcbca0b43d
[ "BSL-1.0" ]
58
2015-01-07T09:10:59.000Z
2019-07-15T14:34:01.000Z
tools/shell/DBClientProxy.h
ajrulez/rocksdb
a0ce3fd00a1ae35bcbb9edc603b7398d83a8eb23
[ "BSD-3-Clause" ]
12
2015-01-02T00:01:45.000Z
2018-04-25T12:35:02.000Z
tools/shell/DBClientProxy.h
ajrulez/rocksdb
a0ce3fd00a1ae35bcbb9edc603b7398d83a8eb23
[ "BSD-3-Clause" ]
23
2015-01-04T00:13:27.000Z
2019-02-15T18:01:17.000Z
#ifndef TOOLS_SHELL_DBCLIENTPROXY #define TOOLS_SHELL_DBCLIENTPROXY #include <vector> #include <map> #include <string> #include <boost/utility.hpp> #include <boost/shared_ptr.hpp> #include "DB.h" /* * class DBClientProxy maintains: * 1. a connection to rocksdb service * 2. a map from db names to opened db handles * * it's client codes' responsibility to catch all possible exceptions. */ namespace rocksdb { class DBClientProxy : private boost::noncopyable { public: // connect to host_:port_ void connect(void); // return true on success, false otherwise bool get(const std::string & db, const std::string & key, std::string & value); // return true on success, false otherwise bool put(const std::string & db, const std::string & key, const std::string & value); // return true on success, false otherwise bool scan(const std::string & db, const std::string & start_key, const std::string & end_key, const std::string & limit, std::vector<std::pair<std::string, std::string> > & kvs); // return true on success, false otherwise bool create(const std::string & db); DBClientProxy(const std::string & host, int port); ~DBClientProxy(); private: // some internal help functions void cleanUp(void); void open(const std::string & db); std::map<std::string, Trocksdb::DBHandle>::iterator getHandle(const std::string & db); const std::string host_; const int port_; std::map<std::string, Trocksdb::DBHandle> dbToHandle_; boost::shared_ptr<Trocksdb::DBClient> dbClient_; }; } // namespace #endif
25.323077
88
0.671324
[ "vector" ]
fba3dd165e1b44f9a22a91ddc0dfcef625c2a5da
93
h
C
src/abc171/replacing.h
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc171/replacing.h
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
src/abc171/replacing.h
nryotaro/at_c
8d7d3aecb4e3c768aefdf0ceaeefb269ca9ab34c
[ "MIT" ]
null
null
null
#include<vector> std::vector<long long> replacing(int n, int a[], int q, int b[], int c[]);
23.25
74
0.634409
[ "vector" ]
fba581f518e8b2614c2e65777591549ce0109217
5,300
h
C
board/AZ3166/mxos_board_conf.h
MXCHIP/mxos
2d93e6e2a90d9af090d6b1698d8674119da96608
[ "MIT" ]
3
2019-04-04T09:29:58.000Z
2019-06-26T10:15:44.000Z
board/AZ3166/mxos_board_conf.h
MXCHIP/mxos
2d93e6e2a90d9af090d6b1698d8674119da96608
[ "MIT" ]
1
2019-10-28T20:17:19.000Z
2019-10-28T20:17:19.000Z
board/AZ3166/mxos_board_conf.h
MXCHIP/mxos
2d93e6e2a90d9af090d6b1698d8674119da96608
[ "MIT" ]
2
2019-04-13T02:27:51.000Z
2021-08-01T21:54:21.000Z
/* MiCO Team * Copyright (c) 2017 MXCHIP Information Tech. Co.,Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __MXOS_BOARD_CONF_H__ #define __MXOS_BOARD_CONF_H__ #ifdef __cplusplus extern "C" { #endif /****************************************************** * Macros ******************************************************/ /****************************************************** * Constants ******************************************************/ #define HARDWARE_REVISION "1.0" #define DEFAULT_NAME "AZ3166" #define MODEL "AZ3166_1" /* MICO RTOS tick rate in Hz */ #define MXOS_DEFAULT_TICK_RATE_HZ (1000) /************************************************************************ * Uncomment to disable watchdog. For debugging only */ //#define MXOS_DISABLE_WATCHDOG /************************************************************************ * Uncomment to disable standard IO, i.e. printf(), etc. */ //#define MXOS_DISABLE_STDIO /************************************************************************ * Uncomment to disable MCU powersave API functions */ //#define MXOS_DISABLE_MCU_POWERSAVE /************************************************************************ * Uncomment to enable MCU real time clock */ #define MXOS_ENABLE_MCU_RTC /************************************************************************ * Restore default and start easylink after press down EasyLink button for 3 seconds. */ #define RestoreDefault_TimeOut (3000) /************************************************************************ * Restore default and start easylink after press down EasyLink button for 3 seconds. */ #define MCU_CLOCK_HZ (96000000) /************************************************************************ * How many bits are used in NVIC priority configuration */ #define CORTEX_NVIC_PRIO_BITS (4) /************************************************************************ * Enable write protection to write-disabled embedded flash sectors */ //#define MCU_ENABLE_FLASH_PROTECT /************************************************************************ * This platform has bluetooth function, use part of core data as BT pairing table */ #define MXOS_BLUETOOTH_ENABLE #define HSE_SOURCE RCC_HSE_ON /* Use external crystal */ #define AHB_CLOCK_DIVIDER RCC_SYSCLK_Div1 /* AHB clock = System clock */ #define APB1_CLOCK_DIVIDER RCC_HCLK_Div2 /* APB1 clock = AHB clock / 2 */ #define APB2_CLOCK_DIVIDER RCC_HCLK_Div1 /* APB2 clock = AHB clock / 1 */ #define PLL_SOURCE RCC_PLLSource_HSE /* PLL source = external crystal */ #define PLL_M_CONSTANT 13 /* PLLM = 16 */ #define PLL_N_CONSTANT 192 /* PLLN = 400 */ #define PLL_P_CONSTANT 4 /* PLLP = 4 */ #define PPL_Q_CONSTANT 8 /* PLLQ = 7 */ #define PPL_R_CONSTANT 2 /* PLLR = 2 */ #define SYSTEM_CLOCK_SOURCE RCC_SYSCLKSource_PLLCLK /* System clock source = PLL clock */ #define SYSTICK_CLOCK_SOURCE SysTick_CLKSource_HCLK /* SysTick clock source = AHB clock */ #define INT_FLASH_WAIT_STATE FLASH_Latency_3 /* Internal flash wait state = 3 cycles */ #define PWR_WakeUp_Pin PWR_WakeUp_Pin2 /* PWR_Wake_Up_Pin */ /****************************************************** * EMW1062 Options ******************************************************/ /* GPIO pins are used to bootstrap Wi-Fi to SDIO or gSPI mode */ //#define MXOS_WIFI_USE_GPIO_FOR_BOOTSTRAP_1 //#define MXOS_WIFI_USE_GPIO_FOR_BOOTSTRAP_1_HIGH_FOR_SDIO /* Wi-Fi GPIO0 pin is used for out-of-band interrupt */ #define MXOS_WIFI_OOB_IRQ_GPIO_PIN ( 0 ) /* Wi-Fi power pin is present */ //#define MXOS_USE_WIFI_POWER_PIN /* Wi-Fi reset pin is present */ #define MXOS_USE_WIFI_RESET_PIN /* Wi-Fi 32K pin is present */ #define MXOS_USE_WIFI_32K_PIN /* USE SDIO 1bit mode */ //#define SDIO_1_BIT /* Wi-Fi power pin is active high */ #define MXOS_USE_WIFI_POWER_PIN_ACTIVE_HIGH /* WLAN Powersave Clock Source * The WLAN sleep clock can be driven from one of two sources: * 1. MCO (MCU Clock Output) - default * 2. WLAN 32K internal oscillator (30% inaccuracy) */ //#define MXOS_USE_WIFI_32K_CLOCK_MCO //#define MXOS_USE_BUILTIN_RF_DRIVER #ifdef __cplusplus } /*extern "C" */ #endif #endif
39.849624
99
0.521887
[ "model" ]
fbb52c2b99d6c8cfc8f61041593f32c515731a38
2,716
h
C
headers/reinforcementAgent.h
Ophien/RogueLike-Flooding-Engine-for-Reinforcement-Learning
b2a842812e1c759c33afaf305ef7470180e163ee
[ "MIT" ]
null
null
null
headers/reinforcementAgent.h
Ophien/RogueLike-Flooding-Engine-for-Reinforcement-Learning
b2a842812e1c759c33afaf305ef7470180e163ee
[ "MIT" ]
null
null
null
headers/reinforcementAgent.h
Ophien/RogueLike-Flooding-Engine-for-Reinforcement-Learning
b2a842812e1c759c33afaf305ef7470180e163ee
[ "MIT" ]
null
null
null
/*MIT License * *Copyright (c) 2018 Alysson Ribeiro da Silva * *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. */ #ifndef REINFORCEMENT_AGENT_H #define REINFORCEMENT_AGENT_H #include "GenericReinforcementAgent.h" #include "AdaptiveQTable.h" #include "SimulationCore.h" #include "SearchEngine.h" #include "world.h" #include "statistics.h" #include <vector> using namespace std; class reinforcementAgent : public GenericReinforcementAgent { public: world* _world; ivec position; ivec targetPosition; int agentId; int iteration; char code; ivec previousPosition; double* currentObservation; statistics::observations* obs; const int max_allowed_tests = 2; const int max_allowed_iterations = 100; const int max_epochs = 40; const int epoch_size = 25; int current_test; int epoch; int epoch_success; int trials; int success; vector<int> availableActions; vector<ivec> availableActionsPositions; reinforcementAgent(FalconAdaptiveQTable& table, Object* _world, statistics::observations* obs, int agentId); ~reinforcementAgent(); void _start(); void _update(); void reset(double &resetReward); void restart(); vector<int> generateAvailableActionsList(); vector<double> getEnvironmentSensor(); void performAction(int &action); void previousStateKeeper(); double calculateReward(); // simples q-learning double predictQValue(vector<double> &environment, vector<double> &action); double learnStimulus(vector<double> &prevEnv, vector<double> &action, double& reward); void debugPrint(bool& print_Q_table, bool& print_map); FalconAdaptiveQTable* table; }; #endif
31.952941
127
0.744845
[ "object", "vector" ]
fbbfcdf89c9b995ffa54dcaa3bd4b9f2bc1e0840
5,893
h
C
threepp/material/Material.h
Graphics-Physics-Libraries/three.cpp-imported
788b4202e15fa245a4b60e2da0b91f7d4d0592e1
[ "MIT" ]
76
2017-12-20T05:09:04.000Z
2022-01-24T10:20:15.000Z
threepp/material/Material.h
Graphics-Physics-Libraries/three.cpp-imported
788b4202e15fa245a4b60e2da0b91f7d4d0592e1
[ "MIT" ]
5
2018-06-06T15:41:01.000Z
2019-11-30T15:10:25.000Z
threepp/material/Material.h
Graphics-Physics-Libraries/three.cpp-imported
788b4202e15fa245a4b60e2da0b91f7d4d0592e1
[ "MIT" ]
23
2017-10-12T16:46:33.000Z
2022-03-16T06:16:03.000Z
// // Created by byter on 22.08.17. // #ifndef THREEPP_MATERIAL_H #define THREEPP_MATERIAL_H #include <memory> #include <threepp/util/osdecl.h> #include <threepp/Constants.h> #include <threepp/textures/Texture.h> #include <threepp/util/sole.h> #include <threepp/util/simplesignal.h> #include <threepp/math/Plane.h> #include <threepp/util/Resolver.h> #include <threepp/core/Color.h> namespace three { class Camera; namespace material { struct Diffuse { using Selector = std::function<void(Diffuse &)>; Color color {0xffffff}; //diffuse, really float opacity = 1; Texture::Ptr map; }; struct LightMap { using Selector = std::function<void(LightMap &)>; Texture::Ptr lightMap; float lightMapIntensity = 1.0; }; struct Emissive { using Selector = std::function<void(Emissive &)>; Texture::Ptr emissiveMap; Color emissive {0x000000}; float emissiveIntensity = 1.0; }; struct AoMap { using Selector = std::function<void(AoMap &)>; Texture::Ptr aoMap; float aoMapIntensity = 1.0; }; struct EnvMap { using Selector = std::function<void(EnvMap &)>; Texture::Ptr envMap; CombineOperation combine = CombineOperation::Multiply; float reflectivity = 1; float refractionRatio = 0.98; float envMapIntensity = 1.0f; }; struct AlphaMap { using Selector = std::function<void(AlphaMap &)>; Texture::Ptr alphaMap; }; struct SpecularMap { using Selector = std::function<void(SpecularMap &)>; Texture::Ptr specularMap; }; struct Specular : public SpecularMap { using Selector = std::function<void(Specular &)>; float shininess = 30; Color specular {0x111111}; }; struct DisplacementMap { using Selector = std::function<void(DisplacementMap &)>; Texture::Ptr displacementMap; float displacementScale = 1; float displacementBias = 0; }; struct BumpMap { using Selector = std::function<void(BumpMap &)>; Texture::Ptr bumpMap; float bumpScale = 1; }; struct NormalMap { using Selector = std::function<void(NormalMap &)>; Texture::Ptr normalMap; math::Vector2 normalScale {1, 1}; }; struct RoughnessMap { using Selector = std::function<void(RoughnessMap &)>; float roughness = 0.5f; Texture::Ptr roughnessMap; }; struct MetalnessMap { using Selector = std::function<void(MetalnessMap &)>; float metalness = 0.5f; Texture::Ptr metalnessMap; }; } struct DLX Material { static uint16_t ___material_id_count; const sole::uuid uuid; uint16_t id; std::string name; bool fog = true; bool lights = true; Color ambientColor = Color::null(); Blending blending = Blending::Normal; Side side = Side::Front; bool flatShading = false; Colors vertexColors = Colors::None; BlendFunc blendSrc = BlendFunc::SrcAlpha; BlendFunc blendDst = BlendFunc::OneMinusSrcAlpha; BlendEq blendEquation = BlendEq::Add; BlendFunc blendSrcAlpha = BlendFunc::None; BlendFunc blendDstAlpha = BlendFunc::None; BlendEq blendEquationAlpha = BlendEq::None; Func depthFunc = Func::LessEqual; bool depthTest = true; bool depthWrite = true; std::vector<math::Plane> clippingPlanes; bool clipIntersection = false; bool clipShadows = false; bool colorWrite = true; bool wireframe = false; unsigned wireframeLineWidth = 1; LineCap wireframeLineCap = LineCap::round; LineJoin wireframeLineJoin = LineJoin::round; Precision precision = Precision::unknown; // override the renderer's default precision for this material bool polygonOffset = false; unsigned polygonOffsetFactor = 0; unsigned polygonOffsetUnits = 0; bool dithering = false; float alphaTest = 0; bool premultipliedAlpha = false; bool skinning = false; bool morphTargets = false; unsigned numSupportedMorphTargets = 0; bool morphNormals = false; unsigned numSupportedMorphNormals = 0; unsigned overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer bool visible = true; bool needsUpdate = true; material::Info info; material::Typer typer; Signal<void(Material *)> onDispose; protected: Material(const material::Info &info, const material::Typer &typer) : uuid(sole::uuid4()), id(___material_id_count++), info(info), typer(typer) {} Material(const Material &material, const material::Info &info, const material::Typer &typer); public: virtual ~Material() {} using Ptr = std::shared_ptr<Material>; virtual void dispose() { onDispose.emitSignal(this); onDispose.disconnectAll(); } template <typename Mat> bool is() { return (bool)((Mat *)typer); } virtual bool transparent() const {return false;} virtual Material *cloned() const = 0; }; template <typename ... Maps> struct MixinResolve; template <typename ... Maps> struct MaterialT; template<typename Map> struct MaterialT<Map> : public Material, public Map { using ResolveT = MixinResolve<Map>; protected: MaterialT(const material::Info &info, const material::Typer &typer) : Material(info, typer) {} MaterialT(const MaterialT &material, const material::Info &info, const material::Typer &typer) : Map(material), Material(material, info, typer) {} }; template<> struct MaterialT<> : public Material { protected: MaterialT(const material::Info &info, const material::Typer &typer) : Material(info, typer) {} MaterialT(const MaterialT &material, const material::Info &info, const material::Typer &typer) : Material(material, info, typer) {} }; template<typename Map, typename ... Maps> struct MaterialT<Map, Maps...> : public Material, Map, Maps... { using ResolveT = MixinResolve<Map, Maps...>; protected: MaterialT(const material::Info &info, const material::Typer &typer) : Material(info, typer) {} MaterialT(const MaterialT &material, const material::Info &info, const material::Typer &typer) : Map(material), Maps(material)..., Material(material, info, typer) {} }; } #endif //THREEPP_MATERIAL_H
23.109804
119
0.715425
[ "vector" ]
fbc50ea7c657281b5ac5013529c8a1da61d6f1c5
20,949
c
C
external/bsd/nvi/dist/gtk/gtkviscreen.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
external/bsd/nvi/dist/gtk/gtkviscreen.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
external/bsd/nvi/dist/gtk/gtkviscreen.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
#include <stdio.h> #include <string.h> #include <gtk/gtkmain.h> #include <gtk/gtksignal.h> #include "gtkviscreen.h" #include <gdk/gdkx.h> #define INTISUCS(c) ((c & ~0x7F) && !(((c) >> 16) & 0x7F)) #define INTUCS(c) (c) #ifdef USE_WIDECHAR #define CHAR_WIDTH(sp, ch) wcwidth(ch) #else #define CHAR_WIDTH(sp, ch) 1 #endif void * v_strset __P((CHAR_T *s, CHAR_T c, size_t n)); #define DEFAULT_VI_SCREEN_WIDTH_CHARS 80 #define DEFAULT_VI_SCREEN_HEIGHT_LINES 25 #define VI_SCREEN_BORDER_ROOM 1 enum { ARG_0, ARG_VADJUSTMENT, }; enum { RESIZED, LAST_SIGNAL }; static void gtk_vi_screen_class_init (GtkViScreenClass *klass); static void gtk_vi_screen_set_arg (GtkObject *object, GtkArg *arg, guint arg_id); static void gtk_vi_screen_get_arg (GtkObject *object, GtkArg *arg, guint arg_id); static void gtk_vi_screen_init (GtkViScreen *vi); static void gtk_vi_screen_destroy (GtkObject *object); static void gtk_vi_screen_realize (GtkWidget *widget); /* static void gtk_vi_screen_map (GtkWidget *widget); static void gtk_vi_screen_unmap (GtkWidget *widget); */ static void gtk_vi_screen_size_request (GtkWidget *widget, GtkRequisition *requisition); static void gtk_vi_screen_size_allocate (GtkWidget *widget, GtkAllocation *allocation); /* static void gtk_vi_screen_adjustment (GtkAdjustment *adjustment, GtkViScreen *text); */ static gint gtk_vi_screen_expose (GtkWidget *widget, GdkEventExpose *event); static void recompute_geometry (GtkViScreen* vi); static void expose_text (GtkViScreen* vi, GdkRectangle *area, gboolean cursor); static void draw_lines(GtkViScreen *vi, gint y, gint x, gint ymax, gint xmax); static void mark_lines(GtkViScreen *vi, gint ymin, gint xmin, gint ymax, gint xmax); static GtkWidgetClass *parent_class = NULL; static guint vi_screen_signals[LAST_SIGNAL] = { 0 }; static GdkFont *gb_font; static GdkFont *tfn; static GdkFont *tfw; #define CharAt(scr,y,x) scr->chars + (y) * scr->cols + x #define FlagAt(scr,y,x) (scr->reverse + (y) * scr->cols + x) #define ColAt(scr,y,x) (scr->endcol + (y) * scr->cols + x) #define COLOR_STANDARD 0x00 #define COLOR_STANDOUT 0x01 /* XXX */ enum { SA_ALTERNATE, SA_INVERSE }; void gtk_vi_screen_attribute(GtkViScreen *vi, gint attribute, gint on) { switch (attribute) { case SA_INVERSE: vi->color = on ? COLOR_STANDOUT : COLOR_STANDARD; break; } } /* col is screen column */ void gtk_vi_screen_move(GtkViScreen *vi, gint row, gint col) { gint x; guchar *endcol; endcol = vi->endcol + row*vi->cols; for (x = 0; col > endcol[x]; ++x); vi->curx = x; vi->cury = row; } static void cleartoel (GtkViScreen *vi, guint row, guint col) { CHAR_T *p, *e; if (MEMCMP(p = CharAt(vi,row,col), e = CharAt(vi,vi->rows,0), vi->cols - col)) { MEMMOVE(p, e, vi->cols - col); memset(FlagAt(vi,row,col), COLOR_STANDARD, vi->cols - col); mark_lines(vi, row, col, row+1, vi->cols); } } void gtk_vi_screen_clrtoel (GtkViScreen *vi) { cleartoel(vi, vi->cury, vi->curx); } void gtk_vi_screen_addstr(GtkViScreen *vi, const char *str, int len) { CHAR_T *p, *end; CHAR_T *line; guchar *endcol; gint col, startcol; gint x; line = vi->chars + vi->cury*vi->cols; endcol = vi->endcol + vi->cury*vi->cols; x = vi->curx; startcol = x ? endcol[x-1] : -1; for (p = CharAt(vi,vi->cury,vi->curx), end = p + len, col = startcol; p < end; ++x) { *p++ = *str++; endcol[x] = ++col; } memset(FlagAt(vi,vi->cury,vi->curx), vi->color, len); mark_lines(vi, vi->cury, startcol+1, vi->cury+1, endcol[x-1]+1); if (endcol[x-1] >= vi->cols) { if (++vi->cury >= vi->rows) { vi->cury = vi->rows-1; vi->curx = x-1; } else { vi->curx = 0; } } else vi->curx += len; if (x < vi->cols) endcol[x] = vi->cols; } void gtk_vi_screen_waddstr(GtkViScreen *vi, const CHAR_T *str, int len) { CHAR_T *p, *end; CHAR_T *line; guchar *endcol; gint col, startcol; gint x; MEMMOVE(CharAt(vi,vi->cury,vi->curx),str,len); memset(FlagAt(vi,vi->cury,vi->curx), vi->color, len); line = vi->chars + vi->cury*vi->cols; endcol = vi->endcol + vi->cury*vi->cols; x = vi->curx; startcol = x ? endcol[x-1] : -1; for (col = startcol; x < vi->curx + len; ++x) endcol[x] = col += CHAR_WIDTH(NULL, *(line+x)); mark_lines(vi, vi->cury, startcol+1, vi->cury+1, endcol[x-1]+1); if (endcol[x-1] >= vi->cols) { if (++vi->cury >= vi->rows) { vi->cury = vi->rows-1; vi->curx = x-1; } else { vi->curx = 0; } } else vi->curx += len; if (x < vi->cols) endcol[x] = vi->cols; } void gtk_vi_screen_deleteln(GtkViScreen *vi) { gint y = vi->cury; gint rows = vi->rows - (y+1); MEMMOVE(CharAt(vi,y,0), CharAt(vi,y+1,0), rows * vi->cols); cleartoel(vi,vi->rows-1,0); memmove(FlagAt(vi,y,0), FlagAt(vi,y+1,0), rows * vi->cols); memmove(ColAt(vi,y,0), ColAt(vi,y+1,0), rows * vi->cols); mark_lines(vi, y, 0, vi->rows-1, vi->cols); } void gtk_vi_screen_insertln(GtkViScreen *vi) { gint y = vi->cury; gint rows = vi->rows - (y+1); MEMMOVE(CharAt(vi,y+1,0), CharAt(vi,y,0), rows * vi->cols); cleartoel(vi,y,0); memmove(FlagAt(vi,y+1,0), FlagAt(vi,y,0), rows * vi->cols); memmove(ColAt(vi,y+1,0), ColAt(vi,y,0), rows * vi->cols); mark_lines(vi, y+1, 0, vi->rows, vi->cols); } void gtk_vi_screen_refresh(GtkViScreen *vi) { if (vi->lastx != vi->curx || vi->lasty != vi-> cury) { mark_lines(vi, vi->lasty, vi->lastx ? *ColAt(vi,vi->lasty,vi->lastx-1) + 1 : 0, vi->lasty+1, *ColAt(vi,vi->lasty,vi->lastx)+1); mark_lines(vi, vi->cury, vi->curx ? *ColAt(vi,vi->cury,vi->curx-1) + 1 : 0, vi->cury+1, *ColAt(vi,vi->cury,vi->curx)+1); } if (vi->marked_maxy == 0) return; draw_lines(vi, vi->marked_y, vi->marked_x, vi->marked_maxy, vi->marked_maxx); vi->marked_x = vi->cols; vi->marked_y = vi->rows; vi->marked_maxx = 0; vi->marked_maxy = 0; vi->lastx = vi->curx; vi->lasty = vi->cury; } void gtk_vi_screen_rewrite(GtkViScreen *vi, gint row) { memset(FlagAt(vi,row,0), COLOR_STANDARD, vi->cols); mark_lines(vi, row, 0, row+1, vi->cols); } GtkType gtk_vi_screen_get_type (void) { static GtkType vi_screen_type = 0; if (!vi_screen_type) { static const GtkTypeInfo vi_screen_info = { "GtkViScreen", sizeof (GtkViScreen), sizeof (GtkViScreenClass), (GtkClassInitFunc) gtk_vi_screen_class_init, (GtkObjectInitFunc) gtk_vi_screen_init, /* reserved_1 */ NULL, /* reserved_2 */ NULL, (GtkClassInitFunc) NULL, }; vi_screen_type = gtk_type_unique (GTK_TYPE_WIDGET, &vi_screen_info); } return vi_screen_type; } static void gtk_vi_screen_class_init (GtkViScreenClass *class) { GtkObjectClass *object_class; GtkWidgetClass *widget_class; object_class = (GtkObjectClass*) class; widget_class = (GtkWidgetClass*) class; parent_class = gtk_type_class (GTK_TYPE_WIDGET); vi_screen_signals[RESIZED] = gtk_signal_new ("resized", GTK_RUN_FIRST, GTK_CLASS_TYPE(object_class), GTK_SIGNAL_OFFSET (GtkViScreenClass, resized), gtk_marshal_NONE__INT_INT, GTK_TYPE_NONE, 2, GTK_TYPE_INT, GTK_TYPE_INT, 0); #ifndef HAVE_PANGO gtk_object_class_add_signals(object_class, vi_screen_signals, LAST_SIGNAL); #endif gtk_object_add_arg_type ("GtkViScreen::vadjustment", GTK_TYPE_ADJUSTMENT, GTK_ARG_READWRITE | GTK_ARG_CONSTRUCT, ARG_VADJUSTMENT); object_class->set_arg = gtk_vi_screen_set_arg; object_class->get_arg = gtk_vi_screen_get_arg; object_class->destroy = gtk_vi_screen_destroy; widget_class->realize = gtk_vi_screen_realize; /* widget_class->map = gtk_vi_screen_map; widget_class->unmap = gtk_vi_screen_unmap; */ widget_class->size_request = gtk_vi_screen_size_request; widget_class->size_allocate = gtk_vi_screen_size_allocate; widget_class->expose_event = gtk_vi_screen_expose; class->rename = NULL; class->resized = NULL; gb_font = gdk_font_load ("-*-*-*-*-*-*-16-*-*-*-*-*-gb2312.1980-*"); /* tf = gdk_font_load ("-misc-fixed-*-*-*-*-16-*-*-*-*-*-iso10646-*"); */ tfn = gdk_font_load ("-misc-fixed-medium-r-semicondensed--13-120-75-75-c-60-iso10646"); tfw = gdk_font_load ("-Misc-Fixed-Medium-R-*-*-13-120-75-75-C-120-ISO10646-1"); } static void gtk_vi_screen_set_arg (GtkObject *object, GtkArg *arg, guint arg_id) { GtkViScreen *vi_screen; vi_screen = GTK_VI_SCREEN (object); switch (arg_id) { case ARG_VADJUSTMENT: gtk_vi_screen_set_adjustment (vi_screen, GTK_VALUE_POINTER (*arg)); break; default: break; } } static void gtk_vi_screen_get_arg (GtkObject *object, GtkArg *arg, guint arg_id) { GtkViScreen *vi_screen; vi_screen = GTK_VI_SCREEN (object); switch (arg_id) { case ARG_VADJUSTMENT: GTK_VALUE_POINTER (*arg) = vi_screen->vadj; break; default: arg->type = GTK_TYPE_INVALID; break; } } static void gtk_vi_screen_init (GtkViScreen *vi) { GtkStyle *style; GTK_WIDGET_SET_FLAGS (vi, GTK_CAN_FOCUS); vi->text_area = NULL; vi->chars = 0; vi->reverse = 0; vi->cols = 0; vi->color = COLOR_STANDARD; vi->cols = 0; vi->rows = 0; #ifdef HAVE_PANGO vi->conx = NULL; #endif style = gtk_style_copy(GTK_WIDGET(vi)->style); gdk_font_unref(style->font); style->font = gdk_font_load("-*-fixed-*-*-*-*-16-*-*-*-*-*-iso8859-*"); GTK_WIDGET(vi)->style = style; } static void gtk_vi_screen_destroy (GtkObject *object) { GtkViScreen *vi_screen; g_return_if_fail (object != NULL); g_return_if_fail (GTK_IS_VI_SCREEN (object)); vi_screen = (GtkViScreen*) object; /* gtk_signal_disconnect_by_data (GTK_OBJECT (vi_screen->vadj), vi_screen); */ GTK_OBJECT_CLASS(parent_class)->destroy (object); } GtkWidget* gtk_vi_screen_new (GtkAdjustment *vadj) { GtkWidget *vi; vi = gtk_widget_new (GTK_TYPE_VI_SCREEN, "vadjustment", vadj, NULL); return vi; } void gtk_vi_screen_set_adjustment (GtkViScreen *vi_screen, GtkAdjustment *vadj) { g_return_if_fail (vi_screen != NULL); g_return_if_fail (GTK_IS_VI_SCREEN (vi_screen)); if (vadj) g_return_if_fail (GTK_IS_ADJUSTMENT (vadj)); else vadj = GTK_ADJUSTMENT (gtk_adjustment_new (0.0, 1.0, 0.0, 1.0, 0.0, 0.0)); if (vi_screen->vadj && (vi_screen->vadj != vadj)) { gtk_signal_disconnect_by_data (GTK_OBJECT (vi_screen->vadj), vi_screen); gtk_object_unref (GTK_OBJECT (vi_screen->vadj)); } if (vi_screen->vadj != vadj) { vi_screen->vadj = vadj; gtk_object_ref (GTK_OBJECT (vi_screen->vadj)); gtk_object_sink (GTK_OBJECT (vi_screen->vadj)); /* gtk_signal_connect (GTK_OBJECT (vi_screen->vadj), "changed", (GtkSignalFunc) gtk_vi_screen_adjustment, vi_screen); gtk_signal_connect (GTK_OBJECT (vi_screen->vadj), "value_changed", (GtkSignalFunc) gtk_vi_screen_adjustment, vi_screen); gtk_signal_connect (GTK_OBJECT (vi_screen->vadj), "disconnect", (GtkSignalFunc) gtk_vi_screen_disconnect, vi_screen); gtk_vi_screen_adjustment (vadj, vi_screen); */ } } static void gtk_vi_screen_realize (GtkWidget *widget) { GtkViScreen *vi; GdkWindowAttr attributes; gint attributes_mask; g_return_if_fail (widget != NULL); g_return_if_fail (GTK_IS_VI_SCREEN (widget)); vi = GTK_VI_SCREEN (widget); GTK_WIDGET_SET_FLAGS (vi, GTK_REALIZED); attributes.window_type = GDK_WINDOW_CHILD; attributes.x = widget->allocation.x; attributes.y = widget->allocation.y; attributes.width = widget->allocation.width; attributes.height = widget->allocation.height; attributes.wclass = GDK_INPUT_OUTPUT; attributes.visual = gtk_widget_get_visual (widget); attributes.colormap = gtk_widget_get_colormap (widget); attributes.event_mask = gtk_widget_get_events (widget); attributes.event_mask |= (GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_MOTION_MASK | GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK | GDK_KEY_PRESS_MASK); attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP; widget->window = gdk_window_new (gtk_widget_get_parent_window (widget), &attributes, attributes_mask); gdk_window_set_user_data (widget->window, vi); attributes.x = (widget->style->xthickness + VI_SCREEN_BORDER_ROOM); attributes.y = (widget->style->ythickness + VI_SCREEN_BORDER_ROOM); attributes.width = MAX (1, (gint)widget->allocation.width - (gint)attributes.x * 2); attributes.height = MAX (1, (gint)widget->allocation.height - (gint)attributes.y * 2); vi->text_area = gdk_window_new (widget->window, &attributes, attributes_mask); gdk_window_set_user_data (vi->text_area, vi); widget->style = gtk_style_attach (widget->style, widget->window); /* Can't call gtk_style_set_background here because it's handled specially */ gdk_window_set_background (widget->window, &widget->style->base[GTK_STATE_NORMAL]); gdk_window_set_background (vi->text_area, &widget->style->base[GTK_STATE_NORMAL]); vi->gc = gdk_gc_new (vi->text_area); /* What's this ? */ gdk_gc_set_exposures (vi->gc, TRUE); gdk_gc_set_foreground (vi->gc, &widget->style->text[GTK_STATE_NORMAL]); vi->reverse_gc = gdk_gc_new (vi->text_area); gdk_gc_set_foreground (vi->reverse_gc, &widget->style->base[GTK_STATE_NORMAL]); gdk_window_show (vi->text_area); recompute_geometry (vi); } static void gtk_vi_screen_size_request (GtkWidget *widget, GtkRequisition *requisition) { gint xthick; gint ythick; gint char_height; gint char_width; GtkViScreen *vi; g_return_if_fail (widget != NULL); g_return_if_fail (GTK_IS_VI_SCREEN (widget)); g_return_if_fail (requisition != NULL); vi = GTK_VI_SCREEN (widget); xthick = widget->style->xthickness + VI_SCREEN_BORDER_ROOM; ythick = widget->style->ythickness + VI_SCREEN_BORDER_ROOM; vi->ch_ascent = widget->style->font->ascent; vi->ch_height = (widget->style->font->ascent + widget->style->font->descent) + 1; vi->ch_width = gdk_text_width (widget->style->font, "A", 1); char_height = DEFAULT_VI_SCREEN_HEIGHT_LINES * vi->ch_height; char_width = DEFAULT_VI_SCREEN_WIDTH_CHARS * vi->ch_width; requisition->width = char_width + xthick * 2; requisition->height = char_height + ythick * 2; } static void gtk_vi_screen_size_allocate (GtkWidget *widget, GtkAllocation *allocation) { GtkViScreen *vi; g_return_if_fail (widget != NULL); g_return_if_fail (GTK_IS_VI_SCREEN (widget)); g_return_if_fail (allocation != NULL); vi = GTK_VI_SCREEN (widget); widget->allocation = *allocation; if (GTK_WIDGET_REALIZED (widget)) { gdk_window_move_resize (widget->window, allocation->x, allocation->y, allocation->width, allocation->height); gdk_window_move_resize (vi->text_area, widget->style->xthickness + VI_SCREEN_BORDER_ROOM, widget->style->ythickness + VI_SCREEN_BORDER_ROOM, MAX (1, (gint)widget->allocation.width - (gint)(widget->style->xthickness + (gint)VI_SCREEN_BORDER_ROOM) * 2), MAX (1, (gint)widget->allocation.height - (gint)(widget->style->ythickness + (gint)VI_SCREEN_BORDER_ROOM) * 2)); recompute_geometry (vi); } } /* static void gtk_vi_screen_adjustment (GtkAdjustment *adjustment, GtkViScreen *vi_screen) { g_return_if_fail (adjustment != NULL); g_return_if_fail (GTK_IS_ADJUSTMENT (adjustment)); g_return_if_fail (vi_screen != NULL); g_return_if_fail (GTK_IS_VI_SCREEN (vi_screen)); } */ static gint gtk_vi_screen_expose (GtkWidget *widget, GdkEventExpose *event) { g_return_val_if_fail (widget != NULL, FALSE); g_return_val_if_fail (GTK_IS_VI_SCREEN (widget), FALSE); g_return_val_if_fail (event != NULL, FALSE); if (event->window == GTK_VI_SCREEN (widget)->text_area) { expose_text (GTK_VI_SCREEN (widget), &event->area, TRUE); } return FALSE; } static void recompute_geometry (GtkViScreen* vi) { //gint xthickness; //gint ythickness; gint height; gint width; gint rows, cols; gint i; //xthickness = widget->style->xthickness + VI_SCREEN_BORDER_ROOM; //ythickness = widget->style->ythickness + VI_SCREEN_BORDER_ROOM; gdk_window_get_size (vi->text_area, &width, &height); rows = height / vi->ch_height; cols = width / vi->ch_width; if (rows == vi->rows && cols == vi->cols) return; vi->marked_x = vi->cols = cols; vi->marked_y = vi->rows = rows; vi->marked_maxx = 0; vi->marked_maxy = 0; g_free(vi->chars); vi->chars = (CHAR_T*)g_new(gchar, (vi->rows+1)*vi->cols * sizeof(CHAR_T)); STRSET(vi->chars, L(' '), (vi->rows+1)*vi->cols); g_free(vi->endcol); vi->endcol = g_new(guchar, vi->rows*vi->cols); g_free(vi->reverse); vi->reverse = g_new(guchar, vi->rows*vi->cols); memset(vi->reverse, 0, vi->rows*vi->cols); gtk_signal_emit(GTK_OBJECT(vi), vi_screen_signals[RESIZED], vi->rows, vi->cols); } static void expose_text (GtkViScreen* vi, GdkRectangle *area, gboolean cursor) { gint ymax; gint xmax, xmin; gdk_window_clear_area (vi->text_area, area->x, area->y, area->width, area->height); ymax = MIN((area->y + area->height + vi->ch_height - 1) / vi->ch_height, vi->rows); xmin = area->x / vi->ch_width; xmax = MIN((area->x + area->width + vi->ch_width - 1) / vi->ch_width, vi->cols); draw_lines(vi, area->y / vi->ch_height, xmin, ymax, xmax); } #define Inverse(screen,y,x) \ ((*FlagAt(screen,y,x) == COLOR_STANDOUT) ^ \ (screen->cury == y && screen->curx == x)) static void draw_lines(GtkViScreen *vi, gint ymin, gint xmin, gint ymax, gint xmax) { gint y, x, len, blen, xpos; CHAR_T *line; GdkGC *fg, *bg; GdkFont *font; gchar buf[2]; gchar *p; gboolean pango; for (y = ymin, line = vi->chars + y*vi->cols; y < ymax; ++y, line += vi->cols) { for (x = 0, xpos = 0; xpos <= xmin; ++x) xpos += CHAR_WIDTH(NULL, *(line+x)); --x; xpos -= CHAR_WIDTH(NULL, *(line+x)); for (; xpos < xmax; x+=len, xpos+= blen) { gchar inverse; inverse = Inverse(vi,y,x); len = 1; if (sizeof(CHAR_T) == sizeof(gchar)) for (; x+len < xmax && Inverse(vi,y,x+len) == inverse; ++len); if (inverse) { fg = vi->reverse_gc; bg = vi->gc; } else { bg = vi->reverse_gc; fg = vi->gc; } pango = 0; #ifdef HAVE_PANGO if (INTISUCS(*(line+x))) { if (!vi->conx) { PangoFontDescription font_description; font_description.family_name = g_strdup ("monospace"); font_description.style = PANGO_STYLE_NORMAL; font_description.variant = PANGO_VARIANT_NORMAL; font_description.weight = 500; font_description.stretch = PANGO_STRETCH_NORMAL; font_description.size = 15000; vi->conx = gdk_pango_context_get(); pango_context_set_font_description (vi->conx, &font_description); pango_context_set_lang(vi->conx, "en_US"); vi->alist = pango_attr_list_new(); } blen = CHAR_WIDTH(NULL, *(line+x)); pango = 1; } else #endif { font = GTK_WIDGET(vi)->style->font; if (sizeof(CHAR_T) == sizeof(gchar)) p = (gchar*)line+x; else { buf[0] = *(line+x); p = buf; } blen = len; } gdk_draw_rectangle(vi->text_area, bg, 1, xpos * vi->ch_width, y * vi->ch_height, blen * vi->ch_width, vi->ch_height); /* hack to not display half a wide character that wasn't * removed. */ if (!pango) gdk_draw_text (vi->text_area, font, fg, xpos * vi->ch_width, y * vi->ch_height + vi->ch_ascent, p, blen); #ifdef HAVE_PANGO else { PangoGlyphString *gs; GList *list; PangoItem *item; char buf[3]; int len; len = ucs2utf8(line+x, 1, buf); list = pango_itemize(vi->conx, buf, 0, len, vi->alist, NULL); item = list->data; gs = pango_glyph_string_new (); pango_shape(buf, len, &item->analysis, gs); gdk_draw_glyphs (vi->text_area, fg, item->analysis.font, xpos * vi->ch_width, y * vi->ch_height + vi->ch_ascent, gs); } #endif } } } static void mark_lines(GtkViScreen *vi, gint ymin, gint xmin, gint ymax, gint xmax) { if (ymin < vi->marked_y) vi->marked_y = ymin; if (xmin < vi->marked_x) vi->marked_x = xmin; if (ymax > vi->marked_maxy) vi->marked_maxy = ymax; if (xmax > vi->marked_maxx) vi->marked_maxx = xmax; }
27.384314
104
0.652298
[ "object" ]
76c17d64fe1bd98e3608eb8c49e93ba41a93c960
14,609
c
C
bin/varnishd/cache/cache_vrt_var.c
huayra/Varnish-Cache
952e1ce5ae27c76ed9681efcd71337ccdb86e45d
[ "BSD-2-Clause" ]
null
null
null
bin/varnishd/cache/cache_vrt_var.c
huayra/Varnish-Cache
952e1ce5ae27c76ed9681efcd71337ccdb86e45d
[ "BSD-2-Clause" ]
null
null
null
bin/varnishd/cache/cache_vrt_var.c
huayra/Varnish-Cache
952e1ce5ae27c76ed9681efcd71337ccdb86e45d
[ "BSD-2-Clause" ]
null
null
null
/*- * Copyright (c) 2006 Verdens Gang AS * Copyright (c) 2006-2011 Varnish Software AS * All rights reserved. * * Author: Poul-Henning Kamp <phk@phk.freebsd.dk> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Runtime support for compiled VCL programs */ #include "config.h" #include <stdio.h> #include <stdlib.h> #include "cache.h" #include "common/heritage.h" #include "cache_backend.h" #include "vrt_obj.h" #include "vtcp.h" #include "vtim.h" static char vrt_hostname[255] = ""; /*--------------------------------------------------------------------*/ static void vrt_do_string(const struct http *hp, int fld, const char *err, const char *p, va_list ap) { char *b; AN(hp); b = VRT_String(hp->ws, NULL, p, ap); if (b == NULL || *b == '\0') { VSLb(hp->vsl, SLT_LostHeader, "%s", err); } else { http_SetH(hp, fld, b); } va_end(ap); } #define VRT_DO_HDR(obj, hdr, http, fld) \ void \ VRT_l_##obj##_##hdr(const struct req *req, const char *p, ...) \ { \ va_list ap; \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ va_start(ap, p); \ vrt_do_string(http, fld, #obj "." #hdr, p, ap); \ va_end(ap); \ } \ \ const char * \ VRT_r_##obj##_##hdr(const struct req *req) \ { \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ CHECK_OBJ_NOTNULL(http, HTTP_MAGIC); \ return (http->hd[fld].b); \ } VRT_DO_HDR(req, request, req->http, HTTP_HDR_REQ) VRT_DO_HDR(req, url, req->http, HTTP_HDR_URL) VRT_DO_HDR(req, proto, req->http, HTTP_HDR_PROTO) VRT_DO_HDR(bereq, request, req->busyobj->bereq, HTTP_HDR_REQ) VRT_DO_HDR(bereq, url, req->busyobj->bereq, HTTP_HDR_URL) VRT_DO_HDR(bereq, proto, req->busyobj->bereq, HTTP_HDR_PROTO) VRT_DO_HDR(obj, proto, req->obj->http, HTTP_HDR_PROTO) VRT_DO_HDR(obj, response, req->obj->http, HTTP_HDR_RESPONSE) VRT_DO_HDR(resp, proto, req->resp, HTTP_HDR_PROTO) VRT_DO_HDR(resp, response, req->resp, HTTP_HDR_RESPONSE) VRT_DO_HDR(beresp, proto, req->busyobj->beresp, HTTP_HDR_PROTO) VRT_DO_HDR(beresp, response, req->busyobj->beresp, HTTP_HDR_RESPONSE) /*--------------------------------------------------------------------*/ #define VRT_DO_STATUS(obj, http) \ void \ VRT_l_##obj##_status(const struct req *req, long num) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ assert(num >= 100 && num <= 999); \ http->status = (uint16_t)num; \ } \ \ long \ VRT_r_##obj##_status(const struct req *req) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ return(http->status); \ } VRT_DO_STATUS(obj, req->obj->http) VRT_DO_STATUS(beresp, req->busyobj->beresp) VRT_DO_STATUS(resp, req->resp) /*--------------------------------------------------------------------*/ /* XXX: review this */ /* Add an objecthead to the saintmode list for the (hopefully) relevant * backend. Some double-up asserting here to avoid assert-errors when there * is no object. */ void VRT_l_beresp_saintmode(const struct req *req, double a) { struct trouble *new; struct trouble *tr; struct trouble *tr2; struct vbc *vbc; CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(req->busyobj, BUSYOBJ_MAGIC); vbc = req->busyobj->vbc; if (!vbc) return; CHECK_OBJ_NOTNULL(vbc, VBC_MAGIC); if (!vbc->backend) return; CHECK_OBJ_NOTNULL(vbc->backend, BACKEND_MAGIC); if (!req->objcore->objhead) return; CHECK_OBJ_NOTNULL(req->objcore, OBJCORE_MAGIC); /* Setting a negative holdoff period is a mistake. Detecting this * when compiling the VCL would be better. */ assert(a > 0); ALLOC_OBJ(new, TROUBLE_MAGIC); AN(new); memcpy(new->digest, req->digest, sizeof new->digest); new->timeout = req->t_req + a; /* Insert the new item on the list before the first item with a * timeout at a later date (ie: sort by which entry will time out * from the list */ Lck_Lock(&vbc->backend->mtx); VTAILQ_FOREACH_SAFE(tr, &vbc->backend->troublelist, list, tr2) { if (tr->timeout < new->timeout) { VTAILQ_INSERT_BEFORE(tr, new, list); new = NULL; break; } } /* Insert the item at the end if the list is empty or all other * items have a longer timeout. */ if (new) VTAILQ_INSERT_TAIL(&vbc->backend->troublelist, new, list); Lck_Unlock(&vbc->backend->mtx); } /*--------------------------------------------------------------------*/ #define VBERESP(dir, type, onm, field) \ void \ VRT_l_##dir##_##onm(const struct req *req, type a) \ { \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ req->field = a; \ } \ \ type \ VRT_r_##dir##_##onm(const struct req *req) \ { \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ return (req->field); \ } VBERESP(beresp, unsigned, do_esi, busyobj->do_esi) VBERESP(beresp, unsigned, do_gzip, busyobj->do_gzip) VBERESP(beresp, unsigned, do_gunzip, busyobj->do_gunzip) VBERESP(beresp, unsigned, do_stream, busyobj->do_stream) VBERESP(beresp, unsigned, do_pass, busyobj->do_pass) /*--------------------------------------------------------------------*/ const char * VRT_r_client_identity(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); if (req->client_identity != NULL) return (req->client_identity); else return (req->sp->addr); } void VRT_l_client_identity(struct req *req, const char *str, ...) { va_list ap; char *b; va_start(ap, str); b = VRT_String(req->http->ws, NULL, str, ap); va_end(ap); req->client_identity = b; } /*--------------------------------------------------------------------*/ #define BEREQ_TIMEOUT(which) \ void __match_proto__() \ VRT_l_bereq_##which(struct req *req, double num) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ CHECK_OBJ_NOTNULL(req->busyobj, BUSYOBJ_MAGIC); \ req->busyobj->which = (num > 0.0 ? num : 0.0); \ } \ \ double \ VRT_r_bereq_##which(const struct req *req) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ CHECK_OBJ_NOTNULL(req->busyobj, BUSYOBJ_MAGIC); \ return(req->busyobj->which); \ } BEREQ_TIMEOUT(connect_timeout) BEREQ_TIMEOUT(first_byte_timeout) BEREQ_TIMEOUT(between_bytes_timeout) /*--------------------------------------------------------------------*/ const char * VRT_r_beresp_backend_name(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(req->busyobj->vbc, VBC_MAGIC); return(req->busyobj->vbc->backend->vcl_name); } struct sockaddr_storage * VRT_r_beresp_backend_ip(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(req->busyobj->vbc, VBC_MAGIC); return(req->busyobj->vbc->addr); } long VRT_r_beresp_backend_port(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(req->busyobj->vbc, VBC_MAGIC); return (VTCP_port(req->busyobj->vbc->addr)); } const char * VRT_r_beresp_storage(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); if (req->storage_hint != NULL) return (req->storage_hint); else return (NULL); } void VRT_l_beresp_storage(struct req *req, const char *str, ...) { va_list ap; char *b; CHECK_OBJ_NOTNULL(req, REQ_MAGIC); va_start(ap, str); b = VRT_String(req->busyobj->ws, NULL, str, ap); va_end(ap); req->storage_hint = b; } /*--------------------------------------------------------------------*/ void VRT_l_req_backend(struct req *req, struct director *be) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); req->director = be; } struct director * VRT_r_req_backend(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); return (req->director); } /*--------------------------------------------------------------------*/ void VRT_l_req_esi(struct req *req, unsigned process_esi) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); /* * Only allow you to turn of esi in the main request * else everything gets confused */ if(req->esi_level == 0) req->disable_esi = !process_esi; } unsigned VRT_r_req_esi(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); return (!req->disable_esi); } long VRT_r_req_esi_level(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); return(req->esi_level); } /*--------------------------------------------------------------------*/ unsigned VRT_r_req_can_gzip(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); return (RFC2616_Req_Gzip(req->http)); } /*--------------------------------------------------------------------*/ long VRT_r_req_restarts(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); return (req->restarts); } /*-------------------------------------------------------------------- * NB: TTL is relative to when object was created, whereas grace and * keep are relative to ttl. */ #define VRT_DO_EXP(which, exp, fld, offset, extra) \ \ void \ VRT_l_##which##_##fld(struct req *req, double a) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ if (a > 0.) \ a += offset; \ EXP_Set_##fld(&exp, a); \ extra; \ } \ \ double \ VRT_r_##which##_##fld(const struct req *req) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ return(EXP_Get_##fld(&exp) - offset); \ } static void vrt_wsp_exp(struct req *req, unsigned xid, const struct exp *e) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); VSLb(req->vsl, SLT_TTL, "%u VCL %.0f %.0f %.0f %.0f %.0f", xid, e->ttl - (req->t_req - e->entered), e->grace, e->keep, req->t_req, e->age + (req->t_req - e->entered)); } VRT_DO_EXP(req, req->exp, ttl, 0, ) VRT_DO_EXP(req, req->exp, grace, 0, ) VRT_DO_EXP(req, req->exp, keep, 0, ) VRT_DO_EXP(obj, req->obj->exp, grace, 0, EXP_Rearm(req->obj); vrt_wsp_exp(req, req->obj->vxid, &req->obj->exp);) VRT_DO_EXP(obj, req->obj->exp, ttl, (req->t_req - req->obj->exp.entered), EXP_Rearm(req->obj); vrt_wsp_exp(req, req->obj->vxid, &req->obj->exp);) VRT_DO_EXP(obj, req->obj->exp, keep, 0, EXP_Rearm(req->obj); vrt_wsp_exp(req, req->obj->vxid, &req->obj->exp);) VRT_DO_EXP(beresp, req->busyobj->exp, grace, 0, vrt_wsp_exp(req, req->vsl->wid & VSL_IDENTMASK, &req->busyobj->exp);) VRT_DO_EXP(beresp, req->busyobj->exp, ttl, 0, vrt_wsp_exp(req, req->vsl->wid & VSL_IDENTMASK, &req->busyobj->exp);) VRT_DO_EXP(beresp, req->busyobj->exp, keep, 0, vrt_wsp_exp(req, req->vsl->wid & VSL_IDENTMASK, &req->busyobj->exp);) /*-------------------------------------------------------------------- * req.xid */ const char * VRT_r_req_xid(const struct req *req) { char *p; int size; CHECK_OBJ_NOTNULL(req, REQ_MAGIC); size = snprintf(NULL, 0, "%u", req->vsl->wid & VSL_IDENTMASK) + 1; AN(p = WS_Alloc(req->http->ws, size)); assert(snprintf(p, size, "%u", req->vsl->wid & VSL_IDENTMASK) < size); return (p); } /*--------------------------------------------------------------------*/ #define REQ_BOOL(hash_var) \ void \ VRT_l_req_##hash_var(struct req *req, unsigned val) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ req->hash_var = val ? 1 : 0; \ } \ \ unsigned \ VRT_r_req_##hash_var(const struct req *req) \ { \ \ CHECK_OBJ_NOTNULL(req, REQ_MAGIC); \ return(req->hash_var); \ } REQ_BOOL(hash_ignore_busy) REQ_BOOL(hash_always_miss) /*--------------------------------------------------------------------*/ struct sockaddr_storage * VRT_r_client_ip(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); return (&req->sp->sockaddr); } struct sockaddr_storage * VRT_r_server_ip(const struct req *req) { int i; CHECK_OBJ_NOTNULL(req, REQ_MAGIC); if (req->sp->mysockaddr.ss_family == AF_UNSPEC) { i = getsockname(req->sp->fd, (void*)&req->sp->mysockaddr, &req->sp->mysockaddrlen); assert(VTCP_Check(i)); } return (&req->sp->mysockaddr); } const char* VRT_r_server_identity(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); if (heritage.identity[0] != '\0') return (heritage.identity); else return (heritage.name); } const char* VRT_r_server_hostname(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); if (vrt_hostname[0] == '\0') AZ(gethostname(vrt_hostname, sizeof(vrt_hostname))); return (vrt_hostname); } /*-------------------------------------------------------------------- * XXX: This is pessimistically silly */ long VRT_r_server_port(const struct req *req) { int i; CHECK_OBJ_NOTNULL(req, REQ_MAGIC); if (req->sp->mysockaddr.ss_family == AF_UNSPEC) { i = getsockname(req->sp->fd, (void*)&req->sp->mysockaddr, &req->sp->mysockaddrlen); assert(VTCP_Check(i)); } return (VTCP_port(&req->sp->mysockaddr)); } /*--------------------------------------------------------------------*/ long VRT_r_obj_hits(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(req->obj, OBJECT_MAGIC); /* XXX */ return (req->obj->hits); } double VRT_r_obj_lastuse(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); CHECK_OBJ_NOTNULL(req->obj, OBJECT_MAGIC); /* XXX */ return (VTIM_real() - req->obj->last_use); } unsigned VRT_r_req_backend_healthy(const struct req *req) { CHECK_OBJ_NOTNULL(req, REQ_MAGIC); /* * XXX: Not optimal, but we do not have a backend in vcl_deliver * XXX: and we have to return something. */ if (req->director == NULL) return (0); CHECK_OBJ_NOTNULL(req->director, DIRECTOR_MAGIC); return (VDI_Healthy(req->director, req)); }
25.765432
77
0.619618
[ "object" ]
76cf87acadf8d9d820884ddc22313f0c6c630ba0
792
h
C
applications/ParticlesEditor/include/PropertiesWidget/SizeControlWidget.h
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/include/PropertiesWidget/SizeControlWidget.h
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/include/PropertiesWidget/SizeControlWidget.h
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <QtWidgets/QWidget> #include <mtt/application/Widgets/PropertiesWidgets/FloatSpinConnection.h> #include <Objects/SizeControlObject.h> namespace mtt { class UndoStack; } namespace Ui { class SizeControlWidget; } class SizeControlWidget : public QWidget { public: SizeControlWidget(SizeControlObject& object, mtt::UndoStack& undoStack); SizeControlWidget(const SizeControlWidget&) = delete; SizeControlWidget& operator = (const SizeControlWidget&) = delete; virtual ~SizeControlWidget() noexcept; private: std::unique_ptr<Ui::SizeControlWidget> _ui; using FloatConnection = mtt::FloatSpinConnection<SizeControlObject>; std::optional<FloatConnection> _startSizeConnection; std::optional<FloatConnection> _endSizeConnection; };
22.628571
74
0.789141
[ "object" ]
76d05106a22c4fe4abe2288218f813385f9a6150
1,248
h
C
LTL_SAT_solver/Aalta_v2.0/checking/deter_checker.h
reactive-systems/eahyper
32660b55e12296df772b835add3248034ce0f70f
[ "0BSD" ]
1
2019-10-08T10:17:11.000Z
2019-10-08T10:17:11.000Z
LTL_SAT_solver/Aalta_v2.0/checking/deter_checker.h
reactive-systems/eahyper
32660b55e12296df772b835add3248034ce0f70f
[ "0BSD" ]
null
null
null
LTL_SAT_solver/Aalta_v2.0/checking/deter_checker.h
reactive-systems/eahyper
32660b55e12296df772b835add3248034ce0f70f
[ "0BSD" ]
1
2021-03-01T14:26:05.000Z
2021-03-01T14:26:05.000Z
/* * formula progression structure * * File: checker.h * Author: Jianwen Li * * * Created on October 21, 2014 */ #ifndef CHECK_H #define CHECK_H #include "formula/aalta_formula.h" #include "progression/progression.h" #include "state/check_deter_state.h" #include <vector> class checker { public: checker (aalta_formula*); ~checker (); bool check (); void show_evidence (); typedef hash_map<aalta_formula*, progression::progf_set, aalta_formula::af_prt_hash> af_progf_map; private: aalta_formula *_input; //evidence *_evi; static std::vector<check_deter_state*> _visited; //states visited in current branch, the progf needs also to be recorded //static std::vector<cycle*> _cycles; static af_progf_map _visited_map; static aalta_formula::af_prt_set _explored; //formulas explored in all branches bool dfs (); progression* find (std::vector<check_deter_state*>, aalta_formula*); aalta_formula* negation (aalta_formula::af_prt_set); bool model (progression*, progression*); void print (aalta_formula::af_prt_set); static std::vector<check_deter_state*> _all_sts; //static void destroy (); }; #endif
25.469388
132
0.678686
[ "vector", "model" ]
76d967f9802fd00b24275acf717ed96c418f0f25
4,717
h
C
include/qrcode/qr/dark_module_score.h
yax-lakam-tuun/libqrcode
1010c7a1ed83cb01a7ab889ff716ffa9e5665fc4
[ "MIT" ]
4
2021-01-16T18:01:52.000Z
2021-11-15T05:02:58.000Z
include/qrcode/qr/dark_module_score.h
yax-lakam-tuun/libqrcode
1010c7a1ed83cb01a7ab889ff716ffa9e5665fc4
[ "MIT" ]
2
2021-01-20T19:15:33.000Z
2021-05-29T15:20:56.000Z
include/qrcode/qr/dark_module_score.h
yax-lakam-tuun/libqrcode
1010c7a1ed83cb01a7ab889ff716ffa9e5665fc4
[ "MIT" ]
1
2021-06-17T18:24:57.000Z
2021-06-17T18:24:57.000Z
/* * The MIT License * * Copyright (c) 2021 Sebastian Bauer * * 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. */ #pragma once #include <numeric> #include <ranges> #include <qrcode/qr/penalty_weight.h> #include <qrcode/structure/matrix.h> #include <qrcode/structure/element_view.h> #include <qrcode/structure/horizontal_view.h> #include <qrcode/structure/module_traits.h> namespace qrcode::qr::detail { using qrcode::structure::matrix; template<class T> requires std::convertible_to<T, bool> [[nodiscard]] constexpr auto dark_module_count(matrix<T> const& matrix) noexcept { using qrcode::structure::module_traits; auto range = views::horizontal({0,0}, size(matrix)) | views::element(matrix) | std::views::transform([](auto v){ return module_traits<T>::is_set(v); }); auto sum = 0; std::ranges::for_each(range, [&sum](auto i) { sum += i; }); return sum; } [[nodiscard]] constexpr auto nearest_five_percentage_step(float proportion) noexcept { auto abs = [](auto value){ return value >= 0.f ? value : -value; }; // constexpr abs return static_cast<int>(abs(50.f-proportion) / 5.f); } } namespace qrcode::qr { using qrcode::structure::matrix; template<class T> [[nodiscard]] constexpr auto dark_module_score(matrix<T> const& modules) { using qrcode::qr::detail::dark_module_count; using qrcode::qr::detail::nearest_five_percentage_step; auto const total = width(modules) * height(modules); auto const count = dark_module_count(modules); auto const proportion = 100.f * count / total; return nearest_five_percentage_step(proportion) * penalty_weight(4); } } #ifdef QRCODE_TESTS_ENABLED #include <qrcode/structure/make_matrix.h> namespace qrcode::qr::detail::test { constexpr auto dark_module_count_returns_the_number_of_dark_modules() { using qrcode::structure::make_matrix; constexpr auto some_modules = make_matrix<int>({7,3}, std::array{ 1,0,0,0,0,0,1, 1,0,1,1,0,0,1, 0,0,0,0,0,0,1 }); static_assert(dark_module_count(some_modules) == 7); } constexpr auto nearest_five_percentage_step_returns_the_distance_to_50_percent_in_five_percent_steps() { static_assert(nearest_five_percentage_step(50.f) == 0); static_assert(nearest_five_percentage_step(48.f) == 0); static_assert(nearest_five_percentage_step(43.f) == 1); static_assert(nearest_five_percentage_step(39.f) == 2); static_assert(nearest_five_percentage_step(33.f) == 3); static_assert(nearest_five_percentage_step(28.f) == 4); static_assert(nearest_five_percentage_step(22.f) == 5); static_assert(nearest_five_percentage_step(53.f) == 0); static_assert(nearest_five_percentage_step(58.f) == 1); static_assert(nearest_five_percentage_step(61.f) == 2); static_assert(nearest_five_percentage_step(66.f) == 3); static_assert(nearest_five_percentage_step(72.f) == 4); static_assert(nearest_five_percentage_step(79.f) == 5); } } namespace qrcode::qr::test { constexpr auto dark_module_score_returns_the_penalty_score_derived_from_number_of_five_percent_steps_away_from_50_percent_dark_modules() { using qrcode::structure::make_matrix; constexpr auto some_modules = make_matrix<int>({7,3}, std::array{ 1,0,0,0,0,0,1, 1,0,1,1,0,0,1, 0,0,0,0,0,0,1 }); static_assert(dark_module_score(some_modules) == (3 * penalty_weight(4))); } } #endif
35.734848
140
0.687089
[ "transform" ]
76e3366a8b141e33c0b2c03cf258af4a4bd934b4
35,314
h
C
Tests/TestQuantArray0.h
StanleyZheng-FDU/ApproxFlow
1c24016d0139746409a06e85a4ddbcd8fedd4145
[ "MIT" ]
null
null
null
Tests/TestQuantArray0.h
StanleyZheng-FDU/ApproxFlow
1c24016d0139746409a06e85a4ddbcd8fedd4145
[ "MIT" ]
null
null
null
Tests/TestQuantArray0.h
StanleyZheng-FDU/ApproxFlow
1c24016d0139746409a06e85a4ddbcd8fedd4145
[ "MIT" ]
null
null
null
#ifndef __TESTQUANTARRAY0__ #define __TESTQUANTARRAY0__ #include "../Headers/Common.h" #include "../Headers/Timer.h" #include "../Headers/Range.h" #include "../Headers/Ref.h" #include "../Headers/Thread.h" #include "../Headers/NDArrayQuantCPU.h" #include "../Headers/NDArrayApproxCPU.h" #include "../Headers/OpsQuant.h" #include "../Tests/Utils.h" int testMNIST(const string lutfile = "../Utils/zli_LUT_ours.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/MNIST/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1", "Conv2", "Conv3", "FC1", "FC_Logits"}; vector<size_t> sizesWeights = {5*5*1*16, 5*5*16*32, 5*5*32*64, 1024*256, 256*10}; vector<size_t> sizesBiases = {16, 32, 64, 256, 10}; vector<vector<size_t>> shapesWeights = {{5*5*1, 16}, {5*5*16, 32}, {5*5*32, 64}, {1024, 256}, {256, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 1})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } cout << "Building Conv1: S = " << map_S_weights["Conv1"] << "; Z = " << map_Z_weights["Conv1"] << "; S_act = " << map_S_activations["Conv1"] << "; Z_act = " << map_Z_activations["Conv1"] << endl; vector<Ref<Var>> weightsConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1_pool.push_back(new Var(map_weights["Conv1"])); } vector<Ref<vector<int>>> biasesConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1_pool.push_back(new vector<int>(map_Q_biases["Conv1"])); } vector<Ref<Var>> preconv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv1_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1"], map_Z_activations["Conv1"], input_pool[idx], weightsConv1_pool[idx], biasesConv1_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1_pool.push_back(MaxPool<NDArray>(preconv1_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv2: S = " << map_S_weights["Conv2"] << "; Z = " << map_Z_weights["Conv2"] << "; S_act = " << map_S_activations["Conv2"] << "; Z_act = " << map_Z_activations["Conv2"] << endl; vector<Ref<Var>> weightsConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2_pool.push_back(new Var(map_weights["Conv2"])); } vector<Ref<vector<int>>> biasesConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2_pool.push_back(new vector<int>(map_Q_biases["Conv2"])); } vector<Ref<Var>> preconv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2"], map_Z_activations["Conv2"], conv1_pool[idx], weightsConv2_pool[idx], biasesConv2_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2_pool.push_back(MaxPool<NDArray>(preconv2_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3: S = " << map_S_weights["Conv3"] << "; Z = " << map_Z_weights["Conv3"] << "; S_act = " << map_S_activations["Conv3"] << "; Z_act = " << map_Z_activations["Conv3"] << endl; vector<Ref<Var>> weightsConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3_pool.push_back(new Var(map_weights["Conv3"])); } vector<Ref<vector<int>>> biasesConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3_pool.push_back(new vector<int>(map_Q_biases["Conv3"])); } vector<Ref<Var>> preconv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3"], map_Z_activations["Conv3"], conv2_pool[idx], weightsConv3_pool[idx], biasesConv3_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3_pool.push_back(MaxPool<NDArray>(preconv3_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv3_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } cout << "Building FC2: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } vector<vector<float>> images = getImages(); vector<unsigned> labels = getLabels(); float count = 0; size_t TestSize = 10000; for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784); for(size_t kdx = 0; kdx < 784; kdx++) { float tmp = images[idx+jdx][kdx]; Q_image[kdx] = (Z_input + tmp / S_input > 0) ? round(Z_input + tmp / S_input) : 0; } image_pool[jdx]->set(Q_image); } #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc2_pool[jdx]->evaluate(idx+1); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t label = fc2_pool[jdx]->value().posmax(); if(label == labels[idx+jdx]) { count++; } //fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << endl; } } cout << "Accuray: " << (count / TestSize) << endl; return 0; } int testFashionMNIST(const string &lutfile = "../Utils/zli_LUT_ours.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/FashionMNIST/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1", "Conv2", "Conv3", "FC1", "FC_Logits"}; vector<size_t> sizesWeights = {5*5*1*32, 5*5*32*64, 5*5*64*128, 2048*512, 512*10}; vector<size_t> sizesBiases = {32, 64, 128, 512, 10}; vector<vector<size_t>> shapesWeights = {{5*5*1, 32}, {5*5*32, 64}, {5*5*64, 128}, {2048, 512}, {512, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 1})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } cout << "Building Conv1: S = " << map_S_weights["Conv1"] << "; Z = " << map_Z_weights["Conv1"] << "; S_act = " << map_S_activations["Conv1"] << "; Z_act = " << map_Z_activations["Conv1"] << endl; vector<Ref<Var>> weightsConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1_pool.push_back(new Var(map_weights["Conv1"])); } vector<Ref<vector<int>>> biasesConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1_pool.push_back(new vector<int>(map_Q_biases["Conv1"])); } vector<Ref<Var>> preconv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv1_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1"], map_Z_activations["Conv1"], input_pool[idx], weightsConv1_pool[idx], biasesConv1_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1_pool.push_back(MaxPool<NDArray>(preconv1_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv2: S = " << map_S_weights["Conv2"] << "; Z = " << map_Z_weights["Conv2"] << "; S_act = " << map_S_activations["Conv2"] << "; Z_act = " << map_Z_activations["Conv2"] << endl; vector<Ref<Var>> weightsConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2_pool.push_back(new Var(map_weights["Conv2"])); } vector<Ref<vector<int>>> biasesConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2_pool.push_back(new vector<int>(map_Q_biases["Conv2"])); } vector<Ref<Var>> preconv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2"], map_Z_activations["Conv2"], conv1_pool[idx], weightsConv2_pool[idx], biasesConv2_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2_pool.push_back(MaxPool<NDArray>(preconv2_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3: S = " << map_S_weights["Conv3"] << "; Z = " << map_Z_weights["Conv3"] << "; S_act = " << map_S_activations["Conv3"] << "; Z_act = " << map_Z_activations["Conv3"] << endl; vector<Ref<Var>> weightsConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3_pool.push_back(new Var(map_weights["Conv3"])); } vector<Ref<vector<int>>> biasesConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3_pool.push_back(new vector<int>(map_Q_biases["Conv3"])); } vector<Ref<Var>> preconv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3"], map_Z_activations["Conv3"], conv2_pool[idx], weightsConv3_pool[idx], biasesConv3_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3_pool.push_back(MaxPool<NDArray>(preconv3_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv3_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } cout << "Building FC2: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } vector<vector<float>> images = getImagesFashion(); vector<unsigned> labels = getLabelsFashion(); float count = 0; size_t TestSize = 10000; for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784); for(size_t kdx = 0; kdx < 784; kdx++) { float tmp = images[idx+jdx][kdx]; Q_image[kdx] = (Z_input + tmp / S_input > 0) ? round(Z_input + tmp / S_input) : 0; } image_pool[jdx]->set(Q_image); } #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc2_pool[jdx]->evaluate(idx+1); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t label = fc2_pool[jdx]->value().posmax(); if(label == labels[idx+jdx]) { count++; } //fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << endl; } } cout << "Accuray: " << (count / TestSize) << endl; return 0; } int testCIFAR10(const string &lutfile = "../Utils/zli_LUT_ours.txt") { float S_input = 1.0 / 255.0; int Z_input = 0; const size_t NUMTHREADS = 20; const string WEIGHTFOLDER = "../Weights/CIFAR10/"; NDArray::_loadLUT(lutfile); unordered_map<string, float> map_S_weights; unordered_map<string, int> map_Z_weights; unordered_map<string, vector<Scalar>> map_Q_weights; unordered_map<string, NDArray> map_weights; unordered_map<string, float> map_S_biases; unordered_map<string, int> map_Z_biases; unordered_map<string, vector<int>> map_Q_biases; unordered_map<string, float> map_S_activations; unordered_map<string, int> map_Z_activations; vector<string> namesLayers = {"Conv1", "Conv2", "Conv3", "FC1", "FC_Logits"}; vector<size_t> sizesWeights = {5*5*3*32, 5*5*32*64, 5*5*64*128, 2048*512, 512*10}; vector<size_t> sizesBiases = {32, 64, 128, 512, 10}; vector<vector<size_t>> shapesWeights = {{5*5*3, 32}, {5*5*32, 64}, {5*5*64, 128}, {2048, 512}, {512, 10}}; for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_weights; int Z_weights; vector<Scalar> Q_weights(sizesWeights[idx]); ifstream fin_weights(WEIGHTFOLDER + namesLayers[idx] + "_weights.txt"); if(!fin_weights) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_weights >> S_weights; fin_weights >> Z_weights; for(size_t jdx = 0; jdx < sizesWeights[idx]; jdx++) { int tmp; fin_weights >> tmp; Q_weights[jdx] = tmp; } fin_weights.close(); NDArray weights(S_weights, Z_weights, shapesWeights[idx], Q_weights); map_S_weights[namesLayers[idx]] = S_weights; map_Z_weights[namesLayers[idx]] = Z_weights; map_Q_weights[namesLayers[idx]] = Q_weights; map_weights[namesLayers[idx]] = weights; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_biases; int Z_biases; vector<int> Q_biases(sizesBiases[idx]); ifstream fin_biases(WEIGHTFOLDER + namesLayers[idx] + "_biases.txt"); if(!fin_biases) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_biases >> S_biases; fin_biases >> Z_biases; for(size_t jdx = 0; jdx < sizesBiases[idx]; jdx++) { int tmp; fin_biases >> tmp; Q_biases[jdx] = tmp; } fin_biases.close(); map_S_biases[namesLayers[idx]] = S_biases; map_Z_biases[namesLayers[idx]] = Z_biases; map_Q_biases[namesLayers[idx]] = Q_biases; } for(size_t idx = 0; idx < namesLayers.size(); idx++) { float S_activations; int Z_activations; ifstream fin_activations(WEIGHTFOLDER + namesLayers[idx] + "_activations.txt"); if(!fin_activations) { cerr << "ERROR: failed to open the file. " << endl; exit(1); } fin_activations >> S_activations; fin_activations >> Z_activations; fin_activations.close(); map_S_activations[namesLayers[idx]] = S_activations; map_Z_activations[namesLayers[idx]] = Z_activations; } vector<Ref<NDArray>> image_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { image_pool.push_back(new NDArray(S_input, Z_input, {28, 28, 3})); } vector<Ref<Var>> input_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { input_pool.push_back(new Var(image_pool[idx])); } cout << "Building Conv1: S = " << map_S_weights["Conv1"] << "; Z = " << map_Z_weights["Conv1"] << "; S_act = " << map_S_activations["Conv1"] << "; Z_act = " << map_Z_activations["Conv1"] << endl; vector<Ref<Var>> weightsConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv1_pool.push_back(new Var(map_weights["Conv1"])); } vector<Ref<vector<int>>> biasesConv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv1_pool.push_back(new vector<int>(map_Q_biases["Conv1"])); } vector<Ref<Var>> preconv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv1_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv1"], map_Z_activations["Conv1"], input_pool[idx], weightsConv1_pool[idx], biasesConv1_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv1_pool.push_back(MaxPool<NDArray>(preconv1_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv2: S = " << map_S_weights["Conv2"] << "; Z = " << map_Z_weights["Conv2"] << "; S_act = " << map_S_activations["Conv2"] << "; Z_act = " << map_Z_activations["Conv2"] << endl; vector<Ref<Var>> weightsConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv2_pool.push_back(new Var(map_weights["Conv2"])); } vector<Ref<vector<int>>> biasesConv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv2_pool.push_back(new vector<int>(map_Q_biases["Conv2"])); } vector<Ref<Var>> preconv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv2_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv2"], map_Z_activations["Conv2"], conv1_pool[idx], weightsConv2_pool[idx], biasesConv2_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv2_pool.push_back(MaxPool<NDArray>(preconv2_pool[idx], {2, 2}, {2, 2}, true)); } cout << "Building Conv3: S = " << map_S_weights["Conv3"] << "; Z = " << map_Z_weights["Conv3"] << "; S_act = " << map_S_activations["Conv3"] << "; Z_act = " << map_Z_activations["Conv3"] << endl; vector<Ref<Var>> weightsConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsConv3_pool.push_back(new Var(map_weights["Conv3"])); } vector<Ref<vector<int>>> biasesConv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesConv3_pool.push_back(new vector<int>(map_Q_biases["Conv3"])); } vector<Ref<Var>> preconv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { preconv3_pool.push_back(Conv2DReLU<NDArray>(map_S_activations["Conv3"], map_Z_activations["Conv3"], conv2_pool[idx], weightsConv3_pool[idx], biasesConv3_pool[idx], {5, 5}, {1, 1}, true)); } vector<Ref<Var>> conv3_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { conv3_pool.push_back(MaxPool<NDArray>(preconv3_pool[idx], {2, 2}, {2, 2}, true)); } vector<Ref<Var>> flatten_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { flatten_pool.push_back(Flatten<NDArray>(conv3_pool[idx])); } cout << "Building FC1: S = " << map_S_weights["FC1"] << "; Z = " << map_Z_weights["FC1"] << "; S_act = " << map_S_activations["FC1"] << "; Z_act = " << map_Z_activations["FC1"] << endl; vector<Ref<Var>> weightsFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC1_pool.push_back(new Var(map_weights["FC1"])); } vector<Ref<vector<int>>> biasesFC1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC1_pool.push_back(new vector<int>(map_Q_biases["FC1"])); } vector<Ref<Var>> fc1_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc1_pool.push_back(MADReLU<NDArray>(map_S_activations["FC1"], map_Z_activations["FC1"], flatten_pool[idx], weightsFC1_pool[idx], biasesFC1_pool[idx])); } Ref<Var> weightsConv1 = new Var(map_weights["Conv1"]); Ref<vector<int>> biasesConv1 = new vector<int>(map_Q_biases["Conv1"]); cout << "Weight Conv1: " << endl; weightsConv1->value().print(); weightsConv1->value().eval().print(); NDArrayFloatCPU<float> _weightsConv1 = weightsConv1->value().eval(); cout << "Bias Conv1: " << endl; print(*biasesConv1); NDArrayFloatCPU<float> _biasesConv1(sizesBiases[0]); for(size_t idx = 0; idx < _biasesConv1.size(); idx++) { _biasesConv1[idx] = map_S_biases["Conv1"] * (*biasesConv1)[idx]; } Ref<Var> weightsConv2 = new Var(map_weights["Conv2"]); Ref<vector<int>> biasesConv2 = new vector<int>(map_Q_biases["Conv2"]); cout << "Weight Conv2: " << endl; weightsConv2->value().print(); weightsConv2->value().eval().print(); NDArrayFloatCPU<float> _weightsConv2 = weightsConv2->value().eval(); cout << "Bias Conv2: " << endl; print(*biasesConv2); NDArrayFloatCPU<float> _biasesConv2(sizesBiases[1]); for(size_t idx = 0; idx < _biasesConv2.size(); idx++) { _biasesConv2[idx] = map_S_biases["Conv2"] * (*biasesConv2)[idx]; } Ref<Var> weightsConv3 = new Var(map_weights["Conv3"]); Ref<vector<int>> biasesConv3 = new vector<int>(map_Q_biases["Conv3"]); cout << "Weight Conv3: " << endl; weightsConv3->value().print(); weightsConv3->value().eval().print(); NDArrayFloatCPU<float> _weightsConv3 = weightsConv3->value().eval(); cout << "Bias Conv3: " << endl; print(*biasesConv3); NDArrayFloatCPU<float> _biasesConv3(sizesBiases[2]); for(size_t idx = 0; idx < _biasesConv3.size(); idx++) { _biasesConv3[idx] = map_S_biases["Conv3"] * (*biasesConv3)[idx]; } Ref<Var> weightsFC1 = new Var(map_weights["FC1"]); Ref<vector<int>> biasesFC1 = new vector<int>(map_Q_biases["FC1"]); cout << "Weight FC1: " << endl; weightsFC1->value().print(); weightsFC1->value().eval().print(); NDArrayFloatCPU<float> _weightsFC1 = weightsFC1->value().eval(); cout << "Bias FC1: " << endl; print(*biasesFC1); NDArrayFloatCPU<float> _biasesFC1(sizesBiases[3]); for(size_t idx = 0; idx < _biasesFC1.size(); idx++) { _biasesFC1[idx] = map_S_biases["FC1"] * (*biasesFC1)[idx]; } Ref<Var> weightsFC2 = new Var(map_weights["FC_Logits"]); Ref<vector<int>> biasesFC2 = new vector<int>(map_Q_biases["FC_Logits"]); cout << "Weight FC2: " << endl; weightsFC2->value().print(); weightsFC2->value().eval().print(); NDArrayFloatCPU<float> _weightsFC2 = weightsFC2->value().eval(); cout << "Bias FC2: " << endl; print(*biasesFC2); NDArrayFloatCPU<float> _biasesFC2(sizesBiases[4]); for(size_t idx = 0; idx < _biasesFC2.size(); idx++) { _biasesFC2[idx] = map_S_biases["FC_Logits"] * (*biasesFC2)[idx]; } cout << "Building FC2: S = " << map_S_weights["FC_Logits"] << "; Z = " << map_Z_weights["FC_Logits"] << "; S_act = " << map_S_activations["FC_Logits"] << "; Z_act = " << map_Z_activations["FC_Logits"] << endl; vector<Ref<Var>> weightsFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { weightsFC2_pool.push_back(new Var(map_weights["FC_Logits"])); } vector<Ref<vector<int>>> biasesFC2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { biasesFC2_pool.push_back(new vector<int>(map_Q_biases["FC_Logits"])); } vector<Ref<Var>> fc2_pool; for(size_t idx = 0; idx < NUMTHREADS; idx++) { fc2_pool.push_back(MAD<NDArray>(map_S_activations["FC_Logits"], map_Z_activations["FC_Logits"], fc1_pool[idx], weightsFC2_pool[idx], biasesFC2_pool[idx])); } vector<vector<float>> images = getImagesCIFAR10(); vector<unsigned> labels = getLabelsCIFAR10(); float count = 0, _count = 0; size_t TestSize = 10000; for(size_t idx = 0; idx < TestSize; idx+=NUMTHREADS) { for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { vector<Scalar> Q_image(784*3); for(size_t kdx = 0; kdx < 784*3; kdx++) { Q_image[kdx] = images[idx+jdx][kdx]; } image_pool[jdx]->set(Q_image); } int _labels[NUMTHREADS] = {0, }; #pragma omp parallel for num_threads(NUMTHREADS) for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { fc2_pool[jdx]->evaluate(idx+1); NDArrayFloatCPU<float> _image({28, 28, 3}, images[idx+jdx]); _image = _image * (1.0 / 255.0); NDArrayFloatCPU<float> _conv1 = (_image.im2col({5, 5}, {1, 1}, true) * _weightsConv1).reshape({28, 28, 32}).addChWise(_biasesConv1).ReLU().maxPool({2, 2}, {2, 2}, true); // std::cout << _conv1.shape()[0] << ", " << _conv1.shape()[1] << ", " << _conv1.shape()[2] << std::endl; NDArrayFloatCPU<float> _conv2 = (_conv1.im2col({5, 5}, {1, 1}, true) * _weightsConv2).reshape({14, 14, 64}).addChWise(_biasesConv2).ReLU().maxPool({2, 2}, {2, 2}, true); // std::cout << _conv2.shape()[0] << ", " << _conv2.shape()[1] << ", " << _conv2.shape()[2] << std::endl; NDArrayFloatCPU<float> _conv3 = (_conv2.im2col({5, 5}, {1, 1}, true) * _weightsConv3).reshape({7, 7, 128}).addChWise(_biasesConv3).ReLU().maxPool({2, 2}, {2, 2}, true); // std::cout << _conv3.shape()[0] << ", " << _conv3.shape()[1] << ", " << _conv3.shape()[2] << std::endl; NDArrayFloatCPU<float> _fc1 = (_conv3.reshape({1, 2048}) * _weightsFC1 +_biasesFC1.reshape({1, 512})).ReLU(); NDArrayFloatCPU<float> _fc2 = _fc1 * _weightsFC2 +_biasesFC2.reshape({1, 10}); _labels[jdx] = _fc2.posmax(); } for(size_t jdx = 0; jdx < NUMTHREADS; jdx++) { size_t label = fc2_pool[jdx]->value().posmax(); size_t _label = _labels[jdx]; if(label == labels[idx+jdx]) { count++; } if(_label == labels[idx+jdx]) { _count++; } //fc2_pool[jdx]->value().eval().print(); cout << "Sample No." << (idx+jdx+1) << " " << "; Label: " << labels[idx+jdx] << ", Predicted: " << label << " / " << _label << " -> " << ((label == labels[idx+jdx]) ? "Right" : "Wrong") << " / " << ((_label == labels[idx+jdx]) ? "Right" : "Wrong") << "; Accuracy: " << (count / (idx+jdx+1)) << " / " << (_count / (idx+jdx+1)) << endl; } } cout << "Accuray: " << (count / TestSize) << endl; cout << "_Accuray: " << (_count / TestSize) << endl; return 0; } #endif
39.545353
351
0.578383
[ "shape", "vector" ]
76ea0d2d475f882f1b61aaeb3a75de87c29fa2a7
2,631
h
C
Include/RmlUi/Core/StyleSheetTypes.h
MatthiasJFM/RmlUi
557dfdbf76ca1397d72c70003081aae4f33b82d0
[ "MIT" ]
1,099
2019-05-11T07:04:26.000Z
2022-03-30T12:39:09.000Z
Include/RmlUi/Core/StyleSheetTypes.h
MatthiasJFM/RmlUi
557dfdbf76ca1397d72c70003081aae4f33b82d0
[ "MIT" ]
251
2019-05-07T08:35:47.000Z
2022-03-31T20:28:49.000Z
Include/RmlUi/Core/StyleSheetTypes.h
MatthiasJFM/RmlUi
557dfdbf76ca1397d72c70003081aae4f33b82d0
[ "MIT" ]
148
2019-07-08T14:46:04.000Z
2022-03-31T10:59:33.000Z
/* * This source file is part of RmlUi, the HTML/CSS Interface Middleware * * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * Copyright (c) 2019 The RmlUi Team, and contributors * * 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. * */ #ifndef RMLUI_CORE_STYLESHEETTYPES_H #define RMLUI_CORE_STYLESHEETTYPES_H #include "Types.h" #include "PropertyDictionary.h" namespace Rml { class Decorator; class DecoratorInstancer; class StyleSheet; struct KeyframeBlock { KeyframeBlock(float normalized_time) : normalized_time(normalized_time) {} float normalized_time; // [0, 1] PropertyDictionary properties; }; struct Keyframes { Vector<PropertyId> property_ids; Vector<KeyframeBlock> blocks; }; using KeyframesMap = UnorderedMap<String, Keyframes>; struct DecoratorSpecification { String decorator_type; PropertyDictionary properties; SharedPtr<Decorator> decorator; }; using DecoratorSpecificationMap = UnorderedMap<String, DecoratorSpecification>; struct DecoratorDeclaration { String type; DecoratorInstancer* instancer; PropertyDictionary properties; }; struct DecoratorDeclarationList { Vector<DecoratorDeclaration> list; String value; }; struct MediaBlock { MediaBlock() {} MediaBlock(PropertyDictionary _properties, SharedPtr<StyleSheet> _stylesheet) : properties(std::move(_properties)), stylesheet(std::move(_stylesheet)) {} PropertyDictionary properties; // Media query properties SharedPtr<StyleSheet> stylesheet; }; using MediaBlockList = Vector<MediaBlock>; } // namespace Rml #endif
32.8875
154
0.779932
[ "vector" ]
76eab3db61895f819c2006e544ebf085b5f03d0d
4,600
h
C
GPU/GPUTracking/Merger/GPUTPCGMOfflineStatisticalErrors.h
mpoghos/AliRoot
e81490f640ad6f2a6189f679de96b07a94304b58
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
GPU/GPUTracking/Merger/GPUTPCGMOfflineStatisticalErrors.h
mpoghos/AliRoot
e81490f640ad6f2a6189f679de96b07a94304b58
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
GPU/GPUTracking/Merger/GPUTPCGMOfflineStatisticalErrors.h
mpoghos/AliRoot
e81490f640ad6f2a6189f679de96b07a94304b58
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
//**************************************************************************\ //* This file is property of and copyright by the ALICE Project *\ //* ALICE Experiment at CERN, All rights reserved. *\ //* *\ //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> *\ //* for The ALICE HLT Project. *\ //* *\ //* Permission to use, copy, modify and distribute this software and its *\ //* documentation strictly for non-commercial purposes is hereby granted *\ //* without fee, provided that the above copyright notice appears in all *\ //* copies and that both the copyright notice and this permission notice *\ //* appear in the supporting documentation. The authors make no claims *\ //* about the suitability of this software for any purpose. It is *\ //* provided "as is" without express or implied warranty. *\ //************************************************************************** /// \file GPUTPCGMOfflineStatisticalErrors.h /// \author David Rohr #ifndef GPUTPCGMOFFLINESTATISTICALERRORS #define GPUTPCGMOFFLINESTATISTICALERRORS #if defined(GPUCA_TPC_USE_STAT_ERROR) #include "AliTPCcalibDB.h" #include "AliTPCclusterMI.h" #include "AliTPCtracker.h" #include "AliTPCTransform.h" #include "GPUTPCGMMergedTrackHit.h" #include "AliTPCReconstructor.h" #endif namespace GPUCA_NAMESPACE { namespace gpu { struct GPUTPCGMMergedTrackHit; #if defined(GPUCA_TPC_USE_STAT_ERROR) struct GPUTPCGMOfflineStatisticalErrors { void SetCurCluster(GPUTPCGMMergedTrackHit* c) { mCurCluster = c; } void GetOfflineStatisticalErrors(float& err2Y, float& err2Z, float sinPhi, float dzds, unsigned char clusterState) const { float snp2 = sinPhi * sinPhi; if (snp2 > 1. - 1e-6) { snp2 = 1. - 1e-6; } float tgp2 = snp2 / (1.f - snp2); float tgp = sqrt(tgp2); double serry2 = 0, serrz2 = 0; AliTPCclusterMI cl; cl.SetRow(mCurCluster->mRow); cl.SetPad(mCurCluster->mPad); cl.SetTimeBin(mCurCluster->fTime); int type = 0; if (clusterState & GPUTPCGMMergedTrackHit::flagSplit) { type = 50; } if (clusterState & GPUTPCGMMergedTrackHit::flagEdge) { type = -type - 3; } cl.SetType(type); cl.SetSigmaY2(0.5); cl.SetSigmaZ2(0.5); cl.SetQ(mCurCluster->fAmp); cl.SetMax(25); cl.SetX(mCurCluster->mX); cl.SetY(mCurCluster->fY); cl.SetZ(mCurCluster->fZ); cl.SetDetector(mCurCluster->mSlice); if (mCurCluster->mRow >= 63) { cl.SetRow(mCurCluster->mRow - 63); cl.SetDetector(mCurCluster->mSlice + 36); } static AliTPCtracker trk; /*AliTPCRecoParam *par = const_cast<AliTPCRecoParam*>(AliTPCReconstructor::GetRecoParam()), *par2; AliTPCReconstructor rec; if (par == nullptr) { par2 = new AliTPCRecoParam; par2->SetUseSectorAlignment(false); rec.SetRecoParam(par2); }*/ // This needs AliTPCRecoParam::GetUseSectorAlignment(), so we should make sure that the RecoParam exists! // This is not true during HLT simulation by definition, so the above code should fix it, but it leads to non-understandable bug later on in TPC transformation. // Anyway, this is only a debugging class. // So in order to make this work, please temporarily outcomment any use of TPCRecoParam in AliTPCTracker::Transform (it is not needed here anyway...) trk.Transform(&cl); /*if (par == nullptr) { delete par2; rec.SetRecoParam(nullptr); }*/ AliTPCcalibDB::Instance()->GetTransform()->ErrY2Z2Syst(&cl, tgp, dzds, serry2, serrz2); // GPUInfo("TEST Sector %d Row %d: X %f %f Y %f %f Z %f %f - Err Y %f + %f, Z %f + %f", mCurCluster->mSlice, mCurCluster->mRow, mCurCluster->mX, cl.GetX(), mCurCluster->fY, cl.GetY(), mCurCluster->fZ, cl.GetZ(), err2Y, serry2, err2Z, serrz2); err2Y += serry2; err2Z += serrz2; } GPUTPCGMMergedTrackHit* mCurCluster; }; #else struct GPUTPCGMOfflineStatisticalErrors { GPUd() void SetCurCluster(GPUTPCGMMergedTrackHit* /*c*/) {} GPUd() void GetOfflineStatisticalErrors(float& /*err2Y*/, float& /*err2Z*/, float /*sinPhi*/, float /*dzds*/, unsigned char /*clusterState*/) const {} }; #endif } // namespace gpu } // namespace GPUCA_NAMESPACE #endif
40
246
0.608696
[ "transform" ]
76eb3d6f2bc2b4cb5c23d5281177188bfaed5479
51,187
c
C
src/hg/encode3/eap/eapSchedule/eapSchedule.c
diekhans/kent
f714d84de41a802085b997abac94bb1abab4bd7a
[ "IJG" ]
null
null
null
src/hg/encode3/eap/eapSchedule/eapSchedule.c
diekhans/kent
f714d84de41a802085b997abac94bb1abab4bd7a
[ "IJG" ]
null
null
null
src/hg/encode3/eap/eapSchedule/eapSchedule.c
diekhans/kent
f714d84de41a802085b997abac94bb1abab4bd7a
[ "IJG" ]
null
null
null
/* edwScheduleAnalysis - Schedule analysis runs.. */ /* Copyright (C) 2014 The Regents of the University of California * See README in this or parent directory for licensing information. */ #include "common.h" #include "linefile.h" #include "hash.h" #include "options.h" #include "portable.h" #include "bamFile.h" #include "obscure.h" #include "intValTree.h" #include "../../encodeDataWarehouse/inc/encodeDataWarehouse.h" #include "../../encodeDataWarehouse/inc/edwLib.h" #include "../../../../parasol/inc/paraMessage.h" #include "eapDb.h" #include "eapLib.h" boolean again = FALSE; boolean retry = FALSE; boolean noJob = FALSE; boolean ignoreQa = FALSE; boolean justLink = FALSE; boolean dry = FALSE; boolean clTest = FALSE; boolean clUpgrade = FALSE; char *clStep = "*"; char *clInFormat = "*"; char *clTarget = "hg38"; char *clIdFile = NULL; int clMax = 0; void usage() /* Explain usage and exit. */ { errAbort( "eapSchedule - Schedule analysis runs.\n" "usage:\n" " eapSchedule startFileId endFileId\n" "options:\n" " -step=pattern - Just run steps with names matching pattern which is * by default\n" " -target=targetName - Target name may be ucscDb like hg38 or something more specific\n" " -inFormat=pattern - Just run steps that are triggered by files of this format\n" " -retry - if job has run and failed retry it\n" " -upgrade - redo older analysis runs if steps have been upgraded in optional way\n" " -again - if set schedule it even if it's been run once\n" " -noJob - if set then don't put job on eapJob table\n" " -ignoreQa - if set then ignore QA results when scheduling\n" " -justLink - just symbolically link rather than copy EDW files to cache\n" " -max=count - Maximum number of jobs to schedule\n" " -idFile=file - Restrict to file id's in file, which is whitespace separated\n" " -dry - just print out the commands that would result\n" ); } /* Command line validation table. */ static struct optionSpec options[] = { {"test", OPTION_BOOLEAN}, {"step", OPTION_STRING}, {"target", OPTION_STRING}, {"inFormat", OPTION_STRING}, {"retry", OPTION_BOOLEAN}, {"upgrade", OPTION_BOOLEAN}, {"again", OPTION_BOOLEAN}, {"noJob", OPTION_BOOLEAN}, {"ignoreQa", OPTION_BOOLEAN}, {"justLink", OPTION_BOOLEAN}, {"max", OPTION_INT}, {"idFile", OPTION_STRING}, {"dry", OPTION_BOOLEAN}, {NULL, 0}, }; /* Another calculated from the command line, consider read only outside of main: */ enum eapRedoPriority gRedoPriority = eapRedo; struct hash *gRedoThresholdCache = NULL; struct eapSwVersion *eapSwVersionForStepVersion(struct sqlConnection *conn, unsigned stepVersionId) /* Get a list of swVersion for all software used by the given step version */ { char query[128]; sqlSafef(query, sizeof(query), "select sv.* from eapSwVersion sv,eapStepSwVersion ssv " " where ssv.swVersionId = sv.id and ssv.stepVersionId=%u ", stepVersionId); return eapSwVersionLoadByQuery(conn, query); } unsigned eapStepVersionIdRedoThreshold(struct sqlConnection *conn, char *stepName, enum eapRedoPriority threshold) /* Returns lowest stepVersionId that does not *have* to be rerun according to * eapSwVersionRedoPriority being no more than threshold. */ { /* Query system for what version it would use currently. This actually forces it to * build version if need be to fit all the latest software. */ unsigned lastGoodVersion = eapCurrentStepVersion(conn, stepName); /* Get a list of all versions of this step ordered with most recent first. */ char query[256]; sqlSafef(query, sizeof(query), "select * from eapStepVersion where step='%s' order by id desc", stepName); struct eapStepVersion *stepVersion, *stepVersionList = eapStepVersionLoadByQuery(conn, query); /* So some cheap sanity checking to make sure indeed we have a step and know what the latest is. */ if (stepVersionList == NULL) internalErr(); assert(stepVersionList->id == lastGoodVersion); /* If we are only version of step things are easy, we'll skip most of the rest. */ if (stepVersionList->next != NULL) { verbose(2, "Oh my, more than one version of this step. Life gets hard.\n"); /* Get a list of all swVersion used in current step, assumed good */ struct eapSwVersion *curVer, *curVerList = eapSwVersionForStepVersion(conn, lastGoodVersion); /* Build up a hash keyed by software with eapSwVersion as values */ struct hash *curVersionHash = hashNew(5); for (curVer = curVerList; curVer != NULL; curVer = curVer->next) hashAdd(curVersionHash, curVer->software, curVer); /* Loop through each step version seeing if there is a required upgrade to a piece of * software used by step. */ for (stepVersion = stepVersionList->next; stepVersion != NULL; stepVersion = stepVersion->next) { struct eapSwVersion *ver, *verList = eapSwVersionForStepVersion(conn, stepVersion->id); boolean anyMeetThreshold = FALSE; for (ver = verList; ver != NULL; ver = ver->next) { struct hashEl *hel = hashLookup(curVersionHash, ver->software); if (hel == NULL) { warn("Older version of step %s is using software %s not used in current\n" "version of step. What to do?", stepName, ver->software); internalErr(); } struct eapSwVersion *curVer = hel->val; if (curVer->id != ver->id) { if (curVer->redoPriority >= threshold) { anyMeetThreshold = TRUE; break; } } } if (anyMeetThreshold) break; verbose(2, "Looks like we can go back a version ok to %d\n", stepVersion->id); lastGoodVersion = stepVersion->id; } } eapStepVersionFreeList(&stepVersionList); return lastGoodVersion; } unsigned stepVersionIdRedoThreshold(struct sqlConnection *conn, struct hash *cache, char *stepName, enum eapRedoPriority threshold) /* Look up minimum stepVersion required for this step, using cache to avoid overheating * database. You need a separate cache for each different threshold */ { struct hashEl *hel = hashLookup(cache, stepName); unsigned redoThreshold; if(hel == NULL) { redoThreshold = eapStepVersionIdRedoThreshold(conn, stepName, threshold); hashAddInt(cache, stepName, redoThreshold); } else { redoThreshold = ptToInt(hel->val); } return redoThreshold; } struct hashEl *hashAddInt(struct hash *hash, char *name, int val); void doTest(struct sqlConnection *conn, struct edwFile *efList) /* Do some test something */ { char query[512]; sqlSafef(query, sizeof(query), "select * from eapStep"); struct eapStep *step, *stepList = eapStepLoadByQuery(conn, query); for (step = stepList; step != NULL; step = step->next) { unsigned curStepVersion = eapCurrentStepVersion(conn, step->name); printf("%s\t%u\t", step->name, curStepVersion); long redoThreshold2 = eapStepVersionIdRedoThreshold(conn, step->name, 2); long redoThreshold1 = eapStepVersionIdRedoThreshold(conn, step->name, 2); printf("redo1 %ld\tredo2 %ld\n", redoThreshold1, redoThreshold2); } } int countAlphaPrefix(char *s) /* Return how many characters in string that are upper or lowercase letters. Will return * length of entire string if whole string is letters, 0 if first char is not a letter. */ { int count = 0; char c; while ((c = *s++) != 0) { if (!isalpha(c)) break; ++count; } return count; } boolean targetsCompatible(char *a, char *b) /* Return TRUE if a, b have shared alphabetic prefix. */ { int aSize = countAlphaPrefix(a); int bSize = countAlphaPrefix(b); if (aSize != bSize) return FALSE; // Do slightly better internal error checking than an assert. If we have no // prefix things are going to be pretty confused if (aSize == 0) errAbort("Internal error: Target '%s' vs '%s' in targetsCompatible?", a, b); // Return TRUE if alphabetic prefixes of a and b are the same. return memcmp(a, b, aSize) == 0; } struct edwAssembly *targetAssemblyForDbAndSex(struct sqlConnection *conn, char *ucscDb, char *sex) /* Figure out best target assembly for something that is associated with a given ucscDB. * In general this will be the most recent for the organism. */ { char sexedName[128]; safef(sexedName, sizeof(sexedName), "%s.%s", sex, clTarget); char query[256]; sqlSafef(query, sizeof(query), "select * from edwAssembly where name='%s'", sexedName); struct edwAssembly *assembly = edwAssemblyLoadByQuery(conn, query); if (assembly == NULL) errAbort("Unexpected fail on %s", query); return assembly; } struct edwBiosample *edwBiosampleFromTerm(struct sqlConnection *conn, char *term) /* Return biosamples associated with term. */ { char query[512]; sqlSafef(query, sizeof(query), "select * from edwBiosample where term = '%s'", term); return edwBiosampleLoadByQuery(conn, query); } char *sexFromExp(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf) /* Return "male" or "female" */ { char *sex = "male"; // Consequences of Y as a mapping target not too bad, so default is male. struct edwExperiment *exp = edwExperimentFromAccession(conn, vf->experiment); if (exp != NULL) { struct edwBiosample *bio = edwBiosampleFromTerm(conn, exp->biosample); if (bio != NULL) { if (sameWord(bio->sex, "F")) sex = "female"; // Other things, unknown, pooled, etc. get to try to map to Y at least. } } return sex; } struct edwAssembly *chooseTarget(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf) /* Pick mapping target - according to taxon and sex. */ { char *sex = sexFromExp(conn, ef, vf); return targetAssemblyForDbAndSex(conn, vf->ucscDb, sex); } static boolean alreadyTakenCareOf(struct sqlConnection *conn, struct edwAssembly *assembly, char *analysisStep, long long firstInput) /* Return true if job is already scheduled or otherwise taken care of */ { if (!wildMatch(clStep, analysisStep)) return TRUE; if (again) return FALSE; char query[512]; int statusMin = -1; if (retry) statusMin = 0; sqlSafef(query, sizeof(query), "select count(*) from eapRun,eapInput" " where eapRun.id = eapInput.runId" " and eapInput.fileId=%lld and analysisStep='%s' and createStatus >= %d" " and assemblyId = %u and stepVersionId >= %u", firstInput, analysisStep, statusMin, assembly->id, stepVersionIdRedoThreshold(conn, gRedoThresholdCache, analysisStep, gRedoPriority)); int count = sqlQuickNum(conn, query); verbose(2, "query %s\ncount %d\n", query, count); return count > 0; } static char *newTempDir(char *name) /* Return a freshly created temp dir where name occurs somewhere in it's name. */ { char *tempDir = rTempName(eapTempDir, name, ""); makeDir(tempDir); int withLastSize = strlen(tempDir) + 2; char withLast[withLastSize]; safef(withLast, sizeof(withLast), "%s/", tempDir); return cloneString(withLast); } void scheduleStepInputBundle(struct sqlConnection *conn, char *tempDir, char *analysisStep, char *commandLine, char *experiment, struct edwAssembly *assembly, int inCount, unsigned inputIds[], char *inputTypes[], boolean bundleInputs) /* Schedule a step. Optionally bundle together all inputs into single vector input. */ { char *commandPrefix = "edwCdJob "; int commandPad = strlen(commandPrefix); pmCheckCommandSize(commandLine, strlen(commandLine) + commandPad); struct eapStep *step = eapStepFromNameOrDie(conn, analysisStep); unsigned stepVersionId = eapCheckVersions(conn, analysisStep); /* Check count of steps we've made against max set by command line. */ if (clMax > 0) { static int stepCount = 0; if (++stepCount > clMax) return; } if (dry) printf("%u %s\n", inputIds[0], commandLine); else { verbose(1, "scheduling %s on %u in %s\n", analysisStep, inputIds[0], tempDir); /* Wrap command line in cd to temp dir */ char fullCommandLine[strlen(commandLine)+128]; safef(fullCommandLine, sizeof(fullCommandLine), "%s%s", commandPrefix, commandLine); /* Make up eapRun record and save it. */ struct eapRun *run; AllocVar(run); if (!noJob) run->jobId = eapJobAdd(conn, fullCommandLine, step->cpusRequested); safef(run->experiment, sizeof(run->experiment), "%s", experiment); run->analysisStep = analysisStep; run->stepVersionId = stepVersionId; run->tempDir = tempDir; if (assembly != NULL) run->assemblyId = assembly->id; run->jsonResult = ""; eapRunSaveToDb(conn, run, "eapRun", 0); run->id = sqlLastAutoId(conn); /* Write input records. */ int i; for (i=0; i<inCount; ++i) { struct eapInput in = {.runId=run->id}; in.name = inputTypes[i]; in.fileId = inputIds[i]; in.ix = (bundleInputs ? i : 0); eapInputSaveToDb(conn, &in, "eapInput", 0); } /* Write output records during eapFinish.... */ freez(&run); } } void scheduleStep(struct sqlConnection *conn, char *tempDir, char *analysisStep, char *commandLine, char *experiment, struct edwAssembly *assembly, int inCount, unsigned inputIds[], char *inputTypes[]) /* Schedule a step, or maybe just think it if the dry option is set. */ { scheduleStepInputBundle(conn, tempDir, analysisStep, commandLine, experiment, assembly, inCount, inputIds, inputTypes, FALSE); } static void makeBwaIndexPath(char *target, char indexPath[PATH_LEN]) /* Fill in path to BWA index. */ { safef(indexPath, PATH_LEN, "%s%s/bwaData/%s.fa", "/scratch/data/encValDir/", target, target); } struct edwAssembly *getBwaIndex(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, char indexPath[PATH_LEN]) /* Target for now is same as UCSC DB. Returns assembly ID */ { struct edwAssembly *assembly = chooseTarget(conn, ef, vf); if (assembly == NULL) errAbort("Couldn't chooseTarget"); makeBwaIndexPath(assembly->name, indexPath); return assembly; } struct cache /* Keep track of files to keep local copies of. */ { struct slRef *list; // Keyed by licensePlate, value is file name w/in cache }; void eapCacheName(struct edwFile *ef, char fileName[PATH_LEN]) /* Fill in fileName with name of ef when cached locally */ { /* Figure out file name within cache. */ char *noDir = strrchr(ef->edwFileName, '/'); assert(noDir != NULL); noDir += 1; safef(fileName, PATH_LEN, "%s%s", eapEdwCacheDir, noDir); } char *cacheMore(struct cache *cache, struct edwFile *ef) /* Add file to hash and return translated name. */ { refAdd(&cache->list, ef); char fileName[PATH_LEN]; eapCacheName(ef, fileName); return cloneString(fileName); } struct cache *cacheNew() /* Return new empty cache */ { struct cache *cache; return AllocVar(cache); } void preloadCache(struct sqlConnection *conn, struct cache *cache) /* If there's anything that needs precaching, return a command line * with a semicolon at the end to precache. Otherwise return blank. */ { if (dry) return; struct slRef *el; for (el = cache->list; el != NULL; el = el->next) { /* Figure out file name within cache. */ struct edwFile *ef = el->val; char fileName[PATH_LEN]; eapCacheName(ef, fileName); /* Copy file into cache if it's not already there */ if (!fileExists(fileName)) { char *source = edwPathForFileId(conn, ef->id); if (justLink) { verbose(1, "Symbolic link of %s to %s (%6.1g gig)\n", source, fileName, fileSize(source)/1e9); if (symlink(source, fileName) < 0) errnoAbort("Couldn't symlink %s to %s", source, fileName); } else { verbose(1, "Copy %s to %s (%6.1g gig)\n", source, fileName, fileSize(source)/1e9); copyFile(source, fileName); } } } } char *pickPairedBwaCommand(struct sqlConnection *conn, struct edwValidFile *vf1, struct edwValidFile *vf2) /* Pick either regular of solexa-converting bwa step. */ { char *result = NULL; struct edwFastqFile *fq1 = edwFastqFileFromFileId(conn, vf1->fileId); struct edwFastqFile *fq2 = edwFastqFileFromFileId(conn, vf2->fileId); if (!sameString(fq1->qualType, fq2->qualType)) errAbort("Mixed quality types in %u and %u", vf1->fileId, vf2->fileId); if (sameWord(fq1->qualType, "solexa")) result = "eap_run_slx_bwa_pe"; else if (sameWord(fq1->qualType, "sanger")) result = "eap_run_bwa_pe"; else internalErr(); edwFastqFileFree(&fq1); edwFastqFileFree(&fq2); return result; } char *pickSingleBwaCommand(struct sqlConnection *conn, struct edwValidFile *vf) /* Pick either regular of solexa-converting bwa step. */ { struct edwFastqFile *fq = edwFastqFileFromFileId(conn, vf->fileId); char *result = NULL; if (sameWord(fq->qualType, "solexa")) result = "eap_run_slx_bwa_se"; else if (sameWord(fq->qualType, "sanger")) result = "eap_run_bwa_se"; else internalErr(); edwFastqFileFree(&fq); return result; } void scheduleBwaPaired(struct sqlConnection *conn, struct edwValidFile *vf1, struct edwValidFile *vf2, struct edwExperiment *exp) /* If it hasn't already been done schedule bwa analysis of the two files. */ { /* Get ef records */ struct edwFile *ef1 = edwFileFromIdOrDie(conn, vf1->fileId); struct edwFile *ef2 = edwFileFromIdOrDie(conn, vf2->fileId); /* Figure out path to BWA index */ char indexPath[PATH_LEN]; struct edwAssembly *assembly = getBwaIndex(conn, ef1, vf1, indexPath); /* Make sure that we don't schedule it again and again */ char *analysisStep = "bwa_paired_end"; if (!alreadyTakenCareOf(conn, assembly, analysisStep, vf1->fileId)) { /* Grab temp dir */ char *tempDir = newTempDir(analysisStep); char *outBamName = "out.bam"; /* Stage inputs and make command line. */ struct cache *cache = cacheNew(); char *ef1Name = cacheMore(cache, ef1); char *ef2Name = cacheMore(cache, ef2); char *command = pickPairedBwaCommand(conn, vf1, vf2); preloadCache(conn, cache); char commandLine[4*PATH_LEN]; safef(commandLine, sizeof(commandLine), "%s %s %s %s %s%s", command, indexPath, ef1Name, ef2Name, tempDir, outBamName); /* Make up eapRun record and schedule it*/ unsigned inFileIds[2] = {ef1->id, ef2->id}; char *inTypes[2] = {"read1", "read2"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } /* Clean up */ edwFileFree(&ef1); edwFileFree(&ef2); } void scheduleBwaSingle(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* If it hasn't already been done schedule bwa analysis of the two files. */ { /* Figure out path to BWA index */ char indexPath[PATH_LEN]; struct edwAssembly *assembly = getBwaIndex(conn, ef, vf, indexPath); /* Make sure that we don't schedule it again and again */ char *analysisStep = "bwa_single_end"; if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; /* Grab temp dir */ char *tempDir = newTempDir(analysisStep); char *outBamName = "out.bam"; /* Stage inputs and make command line. */ struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); char *command = pickSingleBwaCommand(conn, vf); preloadCache(conn, cache); char commandLine[4*PATH_LEN]; safef(commandLine, sizeof(commandLine), "%s %s %s %s%s", command, indexPath, efName, tempDir, outBamName); /* Make up eapRun record and schedule it*/ unsigned inFileIds[1] = {ef->id}; char *inTypes[1] = {"reads"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } boolean bamIsPaired(char *fileName, int maxCount) /* Read up to maxCount records, figure out if BAM is from a paired run */ { boolean isPaired = FALSE; samfile_t *sf = samopen(fileName, "rb", NULL); bam1_t one; ZeroVar(&one); // This seems to be necessary! int i; for (i=0; i<maxCount; ++i) { int err = bam_read1(sf->x.bam, &one); if (err < 0) break; if (one.core.flag&BAM_FPAIRED) { isPaired = TRUE; break; } } samclose(sf); return isPaired; } void scheduleMacsDnase(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* If it hasn't already been done schedule macs analysis of the file. */ { // Figure out input bam name char bamName[PATH_LEN]; safef(bamName, sizeof(bamName), "%s%s", edwRootDir, ef->edwFileName); // Figure out analysis step and script based on paired end status of input bam boolean isPaired = bamIsPaired(bamName, 1000); char *analysisStep, *scriptName; if (isPaired) { analysisStep = "macs2_dnase_pe"; scriptName = "eap_run_macs2_dnase_pe"; } else { analysisStep = "macs2_dnase_se"; scriptName = "eap_run_macs2_dnase_se"; } verbose(2, "schedulingMacsDnase on %s step %s, script %s\n", ef->edwFileName, analysisStep, scriptName); /* Make sure that we don't schedule it again and again */ struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, vf->ucscDb); if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; char *tempDir = newTempDir(analysisStep); /* Stage inputs and make command line. */ struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); preloadCache(conn, cache); char commandLine[4*PATH_LEN]; safef(commandLine, sizeof(commandLine), "%s %s %s %s%s %s%s", scriptName, assembly->name, efName, tempDir, "out.narrowPeak.bigBed", tempDir, "out.bigWig"); /* Declare step input and output arrays and schedule it. */ unsigned inFileIds[] = {ef->id}; char *inTypes[] = {"alignments"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } struct edwExperiment *findChipControlExp(struct sqlConnection *conn, char *accession) /* Given experiment accession try to find control. */ { char query[512]; sqlSafef(query, sizeof(query), "select control from edwExperiment where accession='%s'", accession); char *controlName = sqlQuickString(conn, query); if (isEmpty(controlName)) return NULL; sqlSafef(query, sizeof(query), "select * from edwExperiment where accession='%s'", controlName); freez(&controlName); return edwExperimentLoadByQuery(conn, query); } struct edwFile *mayFindChipControlFile(struct sqlConnection *conn, struct edwValidFile *vf, struct edwExperiment *exp) /* Find control file for this chip file. Return NULL if not found */ { struct edwExperiment *controlExp = findChipControlExp(conn, exp->accession); if (controlExp == NULL) { verbose(2, "Can't find control experiment for ChIP experiment %s\n", exp->accession); return NULL; } // Got control experiment, now let's go for a matching bam file. char query[PATH_LEN*3]; sqlSafef(query, sizeof(query), "select * from edwValidFile where experiment='%s' and format='%s' and ucscDb='%s'" , controlExp->accession, vf->format, vf->ucscDb); struct edwValidFile *controlVf, *controlVfList = edwValidFileLoadByQuery(conn, query); int controlCount = slCount(controlVfList); if (controlCount <= 0) return NULL; // Go through list and try to pick one int bestScore = 0; struct edwValidFile *bestControl = NULL; for (controlVf = controlVfList; controlVf != NULL; controlVf = controlVf->next) { int score = 0; if (sameString(controlVf->outputType, vf->outputType)) score += 100000000; if (sameString(controlVf->replicate, vf->replicate)) score += 50000000; if (sameString(controlVf->technicalReplicate, vf->technicalReplicate)) score += 25000000; long long sizeDiff = controlVf->itemCount - vf->itemCount; if (sizeDiff < 0) sizeDiff = -sizeDiff; if (sizeDiff > 25000000) sizeDiff = 25000000; score += 25000000 - sizeDiff; if (score > bestScore) { bestScore = score; bestControl = controlVf; } } if (bestControl == NULL) { verbose(2, "Can't find control file for ChIP experiment %s\n", exp->accession); return NULL; } // Figure out control bam file info return edwFileFromId(conn, bestControl->fileId); } void scheduleSppChip(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* If it hasn't already been done schedule SPP peak calling for a chip-seq bam file. */ { // Figure out input bam name char bamName[PATH_LEN]; safef(bamName, sizeof(bamName), "%s%s", edwRootDir, ef->edwFileName); // Figure out analysis step and script based on paired end status of input bam boolean isPaired = bamIsPaired(bamName, 1000); char *analysisStep, *scriptName; if (isPaired) { /* analysisStep = "spp_chip_pe"; scriptName = "eap_run_spp_chip_pe"; */ return; } else { analysisStep = "spp_chip_se"; scriptName = "eap_run_spp_chip_se"; } verbose(2, "Looking for control for chip file %s\n", ef->edwFileName); // Get control bam file info struct edwFile *controlEf = mayFindChipControlFile(conn, vf, exp); if (controlEf == NULL) return; verbose(2, "schedulingSppChip on %s with control %s, step %s, script %s\n", ef->edwFileName, controlEf->edwFileName, analysisStep, scriptName); /* Make sure that we don't schedule it again and again */ struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, vf->ucscDb); if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; char *tempDir = newTempDir(analysisStep); /* Stage inputs and make command line. */ struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); char *controlEfName = cacheMore(cache, controlEf); preloadCache(conn, cache); char commandLine[4*PATH_LEN]; safef(commandLine, sizeof(commandLine), "%s %s %s %s %s%s", scriptName, assembly->name, efName, controlEfName, tempDir, "out.narrowPeak.bigBed"); /* Declare step input and output arrays and schedule it. */ unsigned inFileIds[] = {ef->id, controlEf->id}; char *inTypes[] = {"chipBam", "controlBam"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } void scheduleMacsChip(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* If it hasn't already been done schedule Macs peak calling for a chip-seq bam file. */ { // Figure out input bam name char bamName[PATH_LEN]; safef(bamName, sizeof(bamName), "%s%s", edwRootDir, ef->edwFileName); // Figure out analysis step and script based on paired end status of input bam boolean isPaired = bamIsPaired(bamName, 1000); char *analysisStep, *scriptName; if (isPaired) { analysisStep = "macs2_chip_pe"; scriptName = "eap_run_macs2_chip_pe"; } else { analysisStep = "macs2_chip_se"; scriptName = "eap_run_macs2_chip_se"; } // Get control bam file info struct edwFile *controlEf = mayFindChipControlFile(conn, vf, exp); if (controlEf == NULL) return; verbose(2, "schedulingMacsChip on %s with control %s, step %s, script %s\n", ef->edwFileName, controlEf->edwFileName, analysisStep, scriptName); /* Make sure that we don't schedule it again and again */ struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, vf->ucscDb); if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; char *tempDir = newTempDir(analysisStep); /* Stage inputs and make command line. */ struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); char *controlEfName = cacheMore(cache, controlEf); preloadCache(conn, cache); char commandLine[4*PATH_LEN]; safef(commandLine, sizeof(commandLine), "%s %s %s %s %s%s %s%s", scriptName, assembly->name, efName, controlEfName, tempDir, "out.narrowPeak.bigBed", tempDir, "out.bigWig"); /* Declare step input and output arrays and schedule it. */ unsigned inFileIds[] = {ef->id, controlEf->id}; char *inTypes[] = {"chipBam", "controlBam"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } double mustGetReadLengthForFastq(struct sqlConnection *conn, unsigned fileId, boolean *retAllSame) /* Verify that associated file is in edwFastqFile table and return average read length */ { char query[256]; sqlSafef(query, sizeof(query), "select readSizeMean from edwFastqFile where fileId=%u", fileId); double result = sqlQuickDouble(conn, query); if (result < 1) errAbort("No edwFastqFile record for %u", fileId); sqlSafef(query, sizeof(query), "select readSizeMax - readSizeMin from edwFastqFile where fileId=%u", fileId); double diff = sqlQuickDouble(conn, query); *retAllSame = (diff == 0.0); return result; } unsigned getFirstParentOfFormat(struct sqlConnection *conn, char *format, unsigned childFileId) /* Return fastq id associated with bam file or die trying. */ { unsigned fastqId = 0; /* Scan backwards input/output tables until reach a fastq */ /* Look for input that led to us, getting both file ID and format */ char query[256]; sqlSafef(query, sizeof(query), "select eapInput.fileId,edwValidFile.format from eapInput,eapOutput,edwValidFile " " where eapOutput.runId = eapInput.runId and eapInput.fileId = edwValidFile.fileId" " and eapOutput.fileId=%u", childFileId); struct sqlResult *sr = sqlGetResult(conn, query); char **row; /* Hopefully fastq is an immediate parent. We loop through all input and * check it for fastqs. If it's not fastq we put it on a list in case we need * to look further upstream for the fastq. */ struct slUnsigned *parentList = NULL; while ((row = sqlNextRow(sr)) != NULL) { unsigned fileId = sqlUnsigned(row[0]); if (sameString(format, row[1])) { fastqId = fileId; break; } else { struct slUnsigned *el = slUnsignedNew(fileId); slAddHead(&parentList,el); } } sqlFreeResult(&sr); if (fastqId == 0) // No joy here, then go look in parents. { struct slUnsigned *parent; for (parent = parentList; parent != NULL; parent = parent->next) { unsigned result = getFirstParentOfFormat(conn, format, parent->val); if (result > 0) { fastqId = result; break; } } } slFreeList(&parentList); return fastqId; } double bamReadLength(char *fileName, int maxCount, boolean *retAllSame) /* Open up bam, read up to maxCount reads, and return size of read, checking * all are same size. */ { long long totalReadLength = 0; int count = 0; int readLength = 0; boolean allSame = TRUE; samfile_t *sf = samopen(fileName, "rb", NULL); bam1_t one; ZeroVar(&one); // This seems to be necessary! int i; for (i=0; i<maxCount; ++i) { int err = bam_read1(sf->x.bam, &one); if (err < 0) break; int length = one.core.l_qseq; if (readLength == 0) readLength = length; else if (readLength != length) { if (allSame) warn("Varying size reads in %s, %d and %d", fileName, readLength, length); allSame = FALSE; } totalReadLength += length; ++count; } samclose(sf); assert(readLength != 0); double averageReadLength = 0; *retAllSame = allSame; if (count > 0) averageReadLength = (double)totalReadLength/count; return averageReadLength; } static boolean hotspotReadLengthOk(int length) /* Return TRUE if hotspot read length is ok */ { int okReadLengths[] = {32,36,40,50,58,72,76,100}; int i; for (i=0; i<ArraySize(okReadLengths); ++i) { if (length == okReadLengths[i]) return TRUE; } return FALSE; } int getReadLengthAndCheckForHotspot(struct sqlConnection *conn, struct edwFile *ef) /* Figure out read length for file. */ { unsigned fastqId = getFirstParentOfFormat(conn, "fastq", ef->id); double readLength = 0; boolean allSame = FALSE; if (fastqId == 0) readLength = bamReadLength(edwPathForFileId(conn, ef->id), 1000, &allSame); else readLength = mustGetReadLengthForFastq(conn, fastqId, &allSame); if (!allSame) { verbose(2, "Couldn't schedule hotspot on %s, not all reads the same size.\n", ef->edwFileName); return 0; } if (!hotspotReadLengthOk(readLength)) { verbose(2, "Hotspot read length %g not supported on %s\n", readLength, ef->edwFileName); return 0; } return readLength; } void scheduleHotspot(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* If it hasn't already been done schedule hotspot analysis of the file. */ { /* Make sure that we don't schedule it again and again */ char *analysisStep = "hotspot"; struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, vf->ucscDb); if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; /* Just do ones where it's an output of previous analysis. */ { char query[512]; sqlSafef(query, sizeof(query), "select count(*) from eapOutput where fileId=%u", ef->id); if (sqlQuickNum(conn, query) == 0) { verbose(2, "Skipping fileId %u, not an EAP output", ef->id); return; } } verbose(2, "schedulingHotspot on %s step %s\n", ef->edwFileName, analysisStep); /* Make command line */ int readLength = getReadLengthAndCheckForHotspot(conn, ef); if (readLength <= 0) return; char *tempDir = newTempDir(analysisStep); /* Stage inputs and make command line. */ struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); preloadCache(conn, cache); char commandLine[4*PATH_LEN]; safef(commandLine, sizeof(commandLine), "eap_run_hotspot %s %s %d %s%s %s%s %s%s", edwSimpleAssemblyName(assembly->ucscDb), efName, readLength, tempDir, "out.narrowPeak.bigBed", tempDir, "out.broadPeak.bigBed", tempDir, "out.bigWig"); /* Declare step input arrays and schedule it. */ unsigned inFileIds[] = {ef->id}; char *inTypes[] = {"alignments"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } void schedulePhantomPeakSpp(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Calculate phantom peak stats on a bam file we hope will be peaky. */ { verbose(2, "Scheduling phantomPeakSpp\n"); /* Make sure that we don't schedule it again and again */ char *analysisStep = "phantom_peak_stats"; struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, vf->ucscDb); if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; /* Make temp dir and stage input files */ char *tempDir = newTempDir(analysisStep); struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); preloadCache(conn, cache); /* Make command line */ char commandLine[3*PATH_LEN]; safef(commandLine, sizeof(commandLine), "eap_run_phantom_peak_spp %s %s%s", efName, tempDir, "out.tab"); /* Declare step input arrays and schedule it. */ unsigned inFileIds[] = {ef->id}; char *inTypes[] = {"alignments"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } void scheduleDnaseStats(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Calculate dnase qa stats on a bam file we hope will be peaky. */ { verbose(2, "Scheduling dnaseStats\n"); /* Make sure that we don't schedule it again and again */ char *analysisStep = "dnase_stats"; struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, vf->ucscDb); if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; /* Figure out read length */ int readLength = getReadLengthAndCheckForHotspot(conn, ef); if (readLength <= 0) return; /* Make temp dir and stage input files */ char *tempDir = newTempDir(analysisStep); struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); preloadCache(conn, cache); /* Make command line */ char commandLine[3*PATH_LEN]; safef(commandLine, sizeof(commandLine), "eap_dnase_stats %s %s %d %s%s %s%s %s%s", efName, edwSimpleAssemblyName(assembly->name), readLength, tempDir, "bamStats.ra", tempDir, "phantomPeaks.tab", tempDir, "spot.ra"); /* Declare step input arrays and schedule it. */ unsigned inFileIds[] = {ef->id}; char *inTypes[] = {"alignments"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } void scheduleBamSort(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Look to see if a bam is sorted, and if not, then produce a sorted version of it */ { /* Make sure that we don't schedule it again and again */ char *analysisStep = "bam_sort"; struct edwAssembly *assembly = chooseTarget(conn, ef, vf); if (alreadyTakenCareOf(conn, assembly, analysisStep, ef->id)) return; char *tempDir = newTempDir(analysisStep); /* Figure out command line */ struct cache *cache = cacheNew(); char *efName = cacheMore(cache, ef); preloadCache(conn, cache); char commandLine[3*PATH_LEN]; safef(commandLine, sizeof(commandLine), "eap_bam_sort %s %s%s", efName, tempDir, "out.bam"); /* Declare step input arrays and schedule it. */ unsigned inFileIds[] = {ef->id}; char *inTypes[] = {"unsorted"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } void runFastqAnalysis(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Run fastq analysis, at least on the data types where we can handle it. */ { char *dataType = exp->dataType; if (sameString(dataType, "DNase-seq") || sameString(dataType, "ChIP-seq") || sameString(dataType, "ChiaPet") || sameString(dataType, "DnaPet") ) { if (!isEmpty(vf->pairedEnd)) { struct edwValidFile *vfB = edwOppositePairedEnd(conn, vf); if (vfB != NULL) { struct edwValidFile *vf1, *vf2; struct edwQaPairedEndFastq *pair = edwQaPairedEndFastqFromVfs(conn, vf, vfB, &vf1, &vf2); if (pair != NULL) { scheduleBwaPaired(conn, vf1, vf2, exp); edwQaPairedEndFastqFree(&pair); } edwValidFileFree(&vfB); } } else { scheduleBwaSingle(conn, ef, vf, exp); } } } void runBamAnalysis(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Run fastq analysis, at least on the data types where we can handle it. */ { if (sameString(exp->dataType, "DNase-seq")) { scheduleMacsDnase(conn, ef, vf, exp); scheduleHotspot(conn, ef, vf, exp); schedulePhantomPeakSpp(conn, ef, vf, exp); scheduleDnaseStats(conn, ef, vf, exp); } else if (sameString(exp->dataType, "ChIP-seq")) { scheduleSppChip(conn, ef, vf, exp); scheduleMacsChip(conn, ef, vf, exp); #ifdef SOON #endif /* SOON */ } #ifdef SOON #endif /* SOON */ } void runSingleAnalysis(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) { verbose(2, "run single analysis format %s, dataType %s\n", vf->format, exp->dataType); if (sameWord("fastq", vf->format)) runFastqAnalysis(conn, ef, vf, exp); if (sameWord("bam", vf->format)) runBamAnalysis(conn, ef, vf, exp); } struct edwFile *listOutputTypeForExp(struct sqlConnection *conn, char *experiment, char *outputType, char *format, char *ucscDb) /* Return all files of given output type and format associated with given experiment */ { char query[512]; sqlSafef(query, sizeof(query), "select edwFile.* from edwFile,edwValidFile where edwValidFile.fileId=edwFile.id " " and experiment='%s' and outputType='%s' and format='%s' and ucscDb='%s' " " and deprecated='' and errorMessage=''" " order by fileId desc" , experiment, outputType, format, ucscDb); return edwFileLoadByQuery(conn, query); } void scheduleWigPooler(struct sqlConnection *conn, struct edwExperiment *exp, struct edwValidFile *youngestVf, struct edwFile *pool) /* Create job to run wig pooler */ { struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, youngestVf->ucscDb); char *analysisStep = "sum_bigWig"; if (alreadyTakenCareOf(conn, assembly, analysisStep, youngestVf->fileId)) return; verbose(2, "Theoretically I'd be pooling %d wigs around %s\n", slCount(pool), exp->accession); struct eapStep *step = eapStepFromNameOrDie(conn, analysisStep); char *tempDir = newTempDir(analysisStep); /* Stage inputs and write file names into a file */ struct cache *cache = cacheNew(); struct edwFile *ef; char inListFile[PATH_LEN]; safef(inListFile,sizeof(inListFile), "%s%s", tempDir, "in.lst"); FILE *f = mustOpen(inListFile, "w"); for (ef = pool; ef != NULL; ef = ef->next) { char *fileName = cacheMore(cache, ef); fprintf(f, "%s\n", fileName); } carefulClose(&f); preloadCache(conn, cache); /* Make up command line */ struct dyString *command = dyStringNew(2048); dyStringPrintf(command, "eap_pool_big_wig %s %s %s%s ", assembly->name, inListFile, tempDir, "out.bigWig"); /* Create step input arrays and schedule it. */ int inCount = slCount(pool); unsigned inFileIds[inCount]; char *inTypes[inCount]; int i; for (i=0, ef = pool; i<inCount; ++i, ef = ef->next) { inFileIds[i] = ef->id; inTypes[i] = step->inputTypes[0]; } /* Schedule it */ scheduleStepInputBundle(conn, tempDir, analysisStep, command->string, exp->accession, assembly, inCount, inFileIds, inTypes, TRUE); /* Clean up and go home. */ dyStringFree(&command); eapStepFree(&step); } void replicaWigAnalysis(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Run analysis on wigs that have been replicated. */ { #ifdef SOON char *outputType = vf->outputType; if (sameString(outputType, "macs2_dnase_signal") || sameString(outputType, "macs2_chip_signal") || sameString(outputType, "hotspot_signal")) { struct edwFile *pool = listOutputTypeForExp(conn, vf->experiment, vf->outputType, vf->format, vf->ucscDb); if (slCount(pool) > 1) { /* Output is sorted, so if we are first we are youngest (highest id) and responsible. * (Since scheduler is called on all in pool, don't want all to try to do this.) */ if (pool->id == ef->id) { verbose(2, "Looks like %u is the youngest in the pool!\n", pool->id); scheduleWigPooler(conn, exp, vf, pool); } } } #endif /* SOON */ } struct edwFile *bestRepOnList(struct sqlConnection *conn, char *notRep, struct edwFile *efList) /* Return best looking replica on list. How to decide? Hmm, good question! */ /* At the moment it is using the enrichment*coverage calcs if available, otherwise covereage * depth. It looks like it is not preferring peaks that have been processed all the way * from scratch from the fastq files by pipeline though. */ { verbose(2, "bestRepOnList for list of %d\n", slCount(efList)); /* If we are only one in list the choice is easy! */ if (efList->next == NULL) return efList; /* We multiply together two factors to make a score - the enrichment in our target area * times the coverage. Find the best scoring by this criteria and use it. */ double bestScore = -1; struct edwFile *bestEf = NULL, *ef; struct edwQaEnrichTarget *target = NULL; for (ef = efList; ef != NULL; ef = ef->next) { struct edwValidFile *vf = edwValidFileFromFileId(conn, ef->id); if (differentString(vf->replicate, notRep) ) { double score = 0; if (!isEmpty(vf->enrichedIn) && !sameString(vf->enrichedIn, "unknown")) { char query[256]; if (target == NULL) { char *assemblyName = edwSimpleAssemblyName(vf->ucscDb); struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, assemblyName); sqlSafef(query, sizeof(query), "select * from edwQaEnrichTarget where assemblyId=%u and name='%s'" , assembly->id, vf->enrichedIn); target = edwQaEnrichTargetLoadByQuery(conn, query); if (target == NULL) errAbort("Unexpected empty result from %s", query); edwAssemblyFree(&assembly); } sqlSafef(query, sizeof(query), "select coverage*enrichment from edwQaEnrich where fileId=%u and qaEnrichTargetId=%u" , vf->fileId, target->id); score = sqlQuickDouble(conn, query); } else { score = vf->depth; } if (score > bestScore) { bestScore = score; bestEf = ef; } } edwValidFileFree(&vf); } edwQaEnrichTargetFree(&target); return bestEf; } void replicaPeakAnalysis(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp, char *peakType) /* Run analysis on replicated peaks */ { #ifdef SOON char *outputType = vf->outputType; verbose(2, "replicaPeakAnalysis(outputType=%s)\n", outputType); if (sameString(outputType, "macs2_narrow_peaks") || sameString(outputType, "hotspot_narrow_peaks") || sameString(outputType, "hotspot_broad_peaks")) { struct edwFile *pool = listOutputTypeForExp(conn, vf->experiment, vf->outputType, vf->format, vf->ucscDb); if (slCount(pool) > 1) { /* Output is sorted, so if we are first we are youngest (highest id) and responsible. * (Since scheduler is called on all in pool, don't want all to try to do this.) */ if (pool->id == ef->id) { scheduleReplicatedPeaks(conn, peakType, exp, vf, pool); } } } #endif /* SOON */ } void scheduleReplicatedHotspot(struct sqlConnection *conn, struct edwExperiment *exp, struct edwValidFile *youngestVf, struct edwFile *pool) /* Schedule job that produces replicated peaks out of individual peaks from two replicates. */ { char *analysisStep = "replicated_hotspot"; verbose(2, "Considering %s on %s\n", analysisStep, youngestVf->licensePlate); /* Get assembly and figure out if we are already done */ struct edwAssembly *assembly = edwAssemblyForUcscDb(conn, youngestVf->ucscDb); if (alreadyTakenCareOf(conn, assembly, analysisStep, youngestVf->fileId)) return; verbose(2, "Theoretically I'd be making replicated hotspots in %s on file %u=%u\n", exp->accession, pool->id, youngestVf->fileId); /* We always take the most recent replicate. Choose best remaining rep by some measure for second */ struct edwFile *ef1 = pool; struct edwValidFile *vf1 = edwValidFileFromFileId(conn, ef1->id); struct edwFile *ef2 = bestRepOnList(conn, vf1->replicate, pool->next); if (ef2 == NULL) return; /* Make sure that the read lengths are all the same. Hotspot needs this */ int readLength1 = getReadLengthAndCheckForHotspot(conn, ef1); if (readLength1 <= 0) return; int readLength2 = getReadLengthAndCheckForHotspot(conn, ef2); if (readLength2 <= 0) return; if (readLength1 != readLength2) { warn("Replicates don't have matching read lengths in %u vs %u", ef1->id, ef2->id); return; } /* Stage inputs. */ struct cache *cache = cacheNew(); char *ef1Name = cacheMore(cache, ef1); char *ef2Name = cacheMore(cache, ef2); preloadCache(conn, cache); /* Grab temp dir */ char *tempDir = newTempDir(analysisStep); /* Make up a file in temp dir that is list of all inputs, just two... */ char inListFile[PATH_LEN]; safef(inListFile,sizeof(inListFile), "%s%s", tempDir, "in.lst"); FILE *f = mustOpen(inListFile, "w"); fprintf(f, "%s\n%s\n", ef1Name, ef2Name); carefulClose(&f); /* Make command line. */ char commandLine[4*PATH_LEN]; safef(commandLine, sizeof(commandLine), "eap_pool_hotspot %s %s %d %s%s %s%s %s%s", edwSimpleAssemblyName(assembly->ucscDb), inListFile, readLength1, tempDir, "out.narrowPeak.bigBed", tempDir, "out.broadPeak.bigBed", tempDir, "out.bigWig"); /* Make up eapRun record and schedule it*/ unsigned inFileIds[2] = {ef1->id, ef2->id}; char *inTypes[2] = {"rep1", "rep2"}; scheduleStep(conn, tempDir, analysisStep, commandLine, exp->accession, assembly, ArraySize(inFileIds), inFileIds, inTypes); } void replicaBamAnalysis(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Run analysis on bams that have been replicated. */ { if (sameString(exp->dataType, "DNase-seq")) { struct edwFile *pool = listOutputTypeForExp(conn, vf->experiment, vf->outputType, vf->format, vf->ucscDb); if (slCount(pool) > 1) { scheduleReplicatedHotspot(conn, exp, vf, pool); } } } void runReplicateAnalysis(struct sqlConnection *conn, struct edwFile *ef, struct edwValidFile *vf, struct edwExperiment *exp) /* Run analysis we hold off on until we have replicates. */ { verbose(2, "run replicate analysis format %s, dataType %s\n", vf->format, exp->dataType); if (vf->replicateQaStatus > 0) { if (sameWord("bigWig", vf->format)) replicaWigAnalysis(conn, ef, vf, exp); else if (sameWord("broadPeak", vf->format) || sameWord("narrowPeak", vf->format)) replicaPeakAnalysis(conn, ef, vf, exp, vf->format); else if (sameWord("bam", vf->format)) replicaBamAnalysis(conn, ef, vf, exp); } } struct rbTree *intTreeFromFile(char *fileName) /* Create intVal tree with empty vals from a space separated file of integer IDs */ { struct rbTree *it = intValTreeNew(); struct lineFile *lf = lineFileOpen(fileName, TRUE); char *line; while (lineFileNextReal(lf, &line)) { char *word; while ((word = nextWord(&line)) != NULL) { int key = sqlUnsigned(word); intValTreeAdd(it, key, NULL); } } lineFileClose(&lf); return it; } void edwScheduleAnalysis(int startFileId, int endFileId) /* edwScheduleAnalysis - Schedule analysis runs.. */ { struct sqlConnection *conn = edwConnectReadWrite(); struct edwFile *ef, *efList = edwFileAllIntactBetween(conn, startFileId, endFileId); verbose(2, "Got %d intact files between %d and %d\n", slCount(efList), startFileId, endFileId); if (clTest) { doTest(conn, efList); return; } struct rbTree *idTree = NULL; if (clIdFile != NULL) { idTree = intTreeFromFile(clIdFile); verbose(1, "%d items in %s\n", idTree->n, clIdFile); } for (ef = efList; ef != NULL; ef = ef->next) { if (idTree != NULL) { struct intVal iv = {ef->id, NULL}; if (rbTreeFind(idTree, &iv) == NULL) continue; } struct edwValidFile *vf = edwValidFileFromFileId(conn, ef->id); if (vf != NULL && wildMatch(clInFormat, vf->format) && targetsCompatible(vf->ucscDb, clTarget)) { verbose(2, "aka %s\n", vf->licensePlate); struct edwExperiment *exp = edwExperimentFromAccession(conn, vf->experiment); if (exp != NULL) { verbose(2, "experiment %s, singleQaStatus %d, replicateQaStatus %d\n", exp->accession, vf->singleQaStatus, vf->replicateQaStatus); if (vf->singleQaStatus > 0 || ignoreQa) runSingleAnalysis(conn, ef, vf, exp); if (vf->replicateQaStatus > 0 || ignoreQa) runReplicateAnalysis(conn, ef, vf, exp); } } } sqlDisconnect(&conn); } int main(int argc, char *argv[]) /* Process command line. */ { optionInit(&argc, argv, options); if (argc != 3) usage(); clTest= optionExists("test"); retry = optionExists("retry"); again = optionExists("again"); noJob = optionExists("noJob"); ignoreQa = optionExists("ignoreQa"); justLink = optionExists("justLink"); dry = optionExists("dry"); clStep = optionVal("step", clStep); clInFormat = optionVal("inFormat", clInFormat); clMax = optionInt("max", clMax); clUpgrade = optionExists("upgrade"); clTarget = optionVal("target", clTarget); clIdFile = optionVal("idFile", clIdFile); if (clUpgrade) gRedoPriority = eapUpgrade; gRedoThresholdCache = hashNew(8); edwScheduleAnalysis(sqlUnsigned(argv[1]), sqlUnsigned(argv[2])); return 0; }
33.433703
106
0.701057
[ "vector" ]
0a0280c40b7d7e5922022cff39f1902ebbb0946a
4,784
h
C
src/autowiring/AnySharedPointer.h
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/AnySharedPointer.h
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/AnySharedPointer.h
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #pragma once #include "auto_id.h" #include "fast_pointer_cast.h" /// AnySharedPointer struct AnySharedPointer { public: AnySharedPointer(void) = default; AnySharedPointer(AnySharedPointer&& rhs); AnySharedPointer(const AnySharedPointer& rhs) = default; AnySharedPointer(std::nullptr_t) : AnySharedPointer() {} template<class T> AnySharedPointer(const std::shared_ptr<T>& rhs) : m_ti(auto_id_t<T>{}), m_ptr(rhs) {} ~AnySharedPointer(void); protected: auto_id m_ti; std::shared_ptr<void> m_ptr; public: explicit operator bool(void) const { return (bool)m_ptr; } void* ptr(void) const { return m_ptr.get(); } bool empty(void) const { return !m_ptr; } auto_id type(void) const { return m_ti; } std::shared_ptr<void>& operator*(void) { return m_ptr; } const std::shared_ptr<void>& operator*(void) const { return m_ptr; } void reset(void) { m_ptr.reset(); } std::shared_ptr<CoreObject> as_obj(void) const { return m_ti.block->pToObj ? m_ti.block->pToObj(m_ptr) : nullptr; } /// <summary> /// Attempts to dynamically assign this slot to the specified object without changing the current type /// </summary> /// <returns>True if the assignment succeeds</returns> bool try_assign(const std::shared_ptr<CoreObject>& rhs) AUTO_NOEXCEPT { if (!m_ti.block->pFromObj) return false; auto ptr = m_ti.block->pFromObj(rhs); if (!ptr) return false; m_ptr = std::move(ptr); return true; } /// <summary> /// Attempts to dynamically assign this slot to the specified object without changing the current type /// </summary> /// <returns>True if the assignment succeeds</returns> bool try_assign(const AnySharedPointer& rhs) { auto obj = rhs.as_obj(); return obj && try_assign(obj); } const std::shared_ptr<void>& as_void(void) const { return m_ptr; } template<class T> const std::shared_ptr<T>& as(void) const { // The safety of this routine is verified by the AnySharedPointer unit tests return *reinterpret_cast<const std::shared_ptr<T>*>(&m_ptr); } template<class T> std::shared_ptr<T>& as(void) { return *reinterpret_cast<std::shared_ptr<T>*>(&m_ptr); } bool operator==(const AnySharedPointer& rhs) const { // Need to compare the control blocks, not the pointer values, because we could be pointing to // different spots in the same object. return !m_ptr.owner_before(rhs.m_ptr) && !rhs.m_ptr.owner_before(m_ptr); } template<typename T> bool operator==(const std::shared_ptr<T>& rhs) const { return m_ptr == rhs; } bool operator==(std::nullptr_t) const { return !m_ptr; } bool operator!=(std::nullptr_t) const { return !!m_ptr; } template<typename T> void init(void) { m_ti = auto_id_t<T>{}; m_ptr.reset(); } // Additional operator overloads: bool operator<(const AnySharedPointer& rhs) const { return m_ptr < rhs.m_ptr;} bool operator!=(const AnySharedPointer& rhs) const { return !(*this == rhs); } void operator=(AnySharedPointer&& rhs) { m_ti = rhs.m_ti; m_ptr = std::move(rhs.m_ptr); rhs.m_ptr.reset(); } void operator=(const AnySharedPointer& rhs) { m_ti = rhs.m_ti; m_ptr = rhs.m_ptr; } // Allows dynamic assignment of the type directly from an auto_id field void operator=(auto_id ti) { m_ti = ti; m_ptr = {}; } void operator=(std::nullptr_t) { m_ti = {}; m_ptr = {}; } /// <summary> /// Convenience overload for shared pointer assignment /// </summary> template<class T> void operator=(const std::shared_ptr<T>& rhs) { m_ptr = rhs; } }; /// <summary> /// Convenience implementation of AnySharedPointer which is initially of type T /// </summary> /// <remarks> /// Using this type will automatically ensure that the underlying auto_id is fully instantiated /// </remarks> template<class T> class AnySharedPointerT: public AnySharedPointer { public: AnySharedPointerT(void): AnySharedPointer(std::shared_ptr<T>{}) {} AnySharedPointerT(T&& value) : AnySharedPointer(std::make_shared<T>(std::forward<T&&>(value))) {} template<typename U> AnySharedPointerT(U&& value) : AnySharedPointer(std::make_shared<T>(std::forward<U&&>(value))) {} T& operator*(void) { return *as<T>(); } const T& operator*(void) const { return *as<T>(); } T* operator->(void) { return as<T>()->get(); } const T* operator->(void) const { return as<T>()->get(); } const std::shared_ptr<T>& get(void) const { return AnySharedPointer::as<T>(); } }; template<class T> inline bool operator==(const std::shared_ptr<T>& lhs, const AnySharedPointer& rhs) { return rhs == lhs; }
25.859459
104
0.664089
[ "object" ]
0a0a303c08d07d12b486f78d40105338a8b6a82e
5,432
h
C
include/pr/gui/gdiplus.h
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
2
2020-11-11T16:19:04.000Z
2021-01-19T01:53:29.000Z
include/pr/gui/gdiplus.h
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2020-07-27T09:00:21.000Z
2020-07-27T10:58:10.000Z
include/pr/gui/gdiplus.h
psryland/rylogic_code
f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b
[ "CNRI-Python" ]
1
2021-04-04T01:39:55.000Z
2021-04-04T01:39:55.000Z
//******************************************************* // GDI+ helpers // Copyright (c) Rylogic 2009 //******************************************************* #pragma once #ifndef NOGDI #ifndef GDIPVER #define GDIPVER 0x0110 #endif #include <vector> #include <filesystem> #pragma warning(push,1) #pragma warning(disable:4458) #include <gdiplus.h> #pragma warning(pop) #include "pr/common/to.h" #pragma comment(lib, "gdiplus.lib") static_assert(GDIPVER == 0x0110, ""); namespace pr { // Import the 'Gdiplus' namespace into 'pr::gdi' namespace gdi = Gdiplus; // RAII object for initialised/shutting down the GdiPlus framework struct GdiPlus { ULONG_PTR m_token; gdi::GdiplusStartupInput m_startup_input; gdi::GdiplusStartupOutput m_startup_output; GdiPlus() { gdi::GdiplusStartup(&m_token, &m_startup_input, &m_startup_output); } ~GdiPlus() { gdi::GdiplusShutdown(m_token); } }; namespace convert { // GDI types to string template <typename Str, typename = std::enable_if_t<is_string_v<Str>>> struct GdiToString { }; // Whatever to GdiColour struct ToGdiColor { static gdi::Color To(COLORREF col) { gdi::Color c; c.SetFromCOLORREF(col); return c; } }; // Whatever to GdiRect struct ToGdiRect { static gdi::Rect To(RECT const& r) { return gdi::Rect(r.left, r.top, r.right - r.left, r.bottom - r.top); } static gdi::Rect To(gdi::RectF const& r) { return gdi::Rect(int(r.X), int(r.Y), int(r.Width), int(r.Height)); } }; // Whatever to GdiRectF struct ToGdiRectF { static gdi::RectF To(RECT const& r) { return gdi::RectF(float(r.left), float(r.top), float(r.right - r.left), float(r.bottom - r.top)); } }; // GdiRect to RECT struct GdiRectToRECT { static RECT To(gdi::RectF const& r) { return RECT{int(r.GetLeft()), int(r.GetTop()), int(r.GetRight()), int(r.GetBottom())}; } static RECT To(gdi::Rect const& r) { return RECT{r.GetLeft(), r.GetTop(), r.GetRight(), r.GetBottom()}; } }; } template <typename TFrom> struct Convert<gdi::Color, TFrom> :convert::ToGdiColor {}; template <typename TFrom> struct Convert<gdi::Rect , TFrom> :convert::ToGdiRect {}; template <typename TFrom> struct Convert<gdi::RectF, TFrom> :convert::ToGdiRectF {}; template <> struct Convert<RECT, gdi::RectF> :convert::GdiRectToRECT {}; template <> struct Convert<RECT, gdi::Rect> :convert::GdiRectToRECT {}; } namespace Gdiplus { // Singleton for accessing image codecs class ImageCodec { std::vector<ImageCodecInfo> m_codecs; ImageCodec() { UINT num = 0; // number of image encoders UINT size = 0; // size of the image encoder array in bytes if (GetImageEncodersSize(&num, &size) != pr::gdi::Status::Ok) throw std::exception("GDI+ Image encoders not available"); if (size != 0) { m_codecs.resize(size); GetImageEncoders(num, size, m_codecs.data()); } } static ImageCodec const& This() { static ImageCodec inst; return inst; } public: static ImageCodecInfo const& Info(wchar_t const* mime) { for (auto& codec : This().m_codecs) { if (wcscmp(codec.MimeType, mime) != 0) continue; return codec; } throw std::exception("Image codec not found"); } static CLSID const& Clsid(wchar_t const* mime) { return Info(mime).Clsid; } }; // Helper for saving GDI Images that infers the codec from the file extension inline Status Save(Image const& image, std::filesystem::path const& filepath) { if (!filepath.has_extension()) throw std::runtime_error("Image save could not infer the image format from the file extension"); auto extn = filepath.extension().c_str() + 1; // skip the '.' auto mime = std::wstring(L"image/").append(extn); return const_cast<Image&>(image).Save(filepath.c_str(), &ImageCodec::Clsid(mime.c_str())); } // Helper for checking GDI return codes inline void Throw(Status result, char const* message) { if (result == Status::Ok) return; throw std::exception(message); } } // Update Manifest // We use features from GDI+ v1.1 which is new as of Windows Vista. There is no re-distributable for Windows XP. // This adds information to the .exe manifest to force GDI+ 1.1 version of gdiplus.dll to be loaded on Vista // without this, Vista defaults to loading version 1.0 and our application will fail to launch with missing entry points. #if defined _M_IX86 #pragma comment(linker, "\"/manifestdependency:type='Win32' name='Microsoft.Windows.GdiPlus' version='1.1.0.0' processorArchitecture='X86' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_IA64 #pragma comment(linker, "\"/manifestdependency:type='Win32' name='Microsoft.Windows.GdiPlus' version='1.1.0.0' processorArchitecture='ia64' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_X64 #pragma comment(linker, "\"/manifestdependency:type='Win32' name='Microsoft.Windows.GdiPlus' version='1.1.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") #else #pragma comment(linker, "\"/manifestdependency:type='Win32' name='Microsoft.Windows.GdiPlus' version='1.1.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #endif #endif // NOGDI
31.04
192
0.655191
[ "object", "vector" ]
0a0cf9265646a6f0648151924292f8ad60cb78bc
856
h
C
PlanetEditor/src/GitClone/Command.h
Piratkopia13/DV1508_Planet_editor
7b6784d87dc3368461347586e14c79dbeabed3cf
[ "Apache-2.0" ]
null
null
null
PlanetEditor/src/GitClone/Command.h
Piratkopia13/DV1508_Planet_editor
7b6784d87dc3368461347586e14c79dbeabed3cf
[ "Apache-2.0" ]
null
null
null
PlanetEditor/src/GitClone/Command.h
Piratkopia13/DV1508_Planet_editor
7b6784d87dc3368461347586e14c79dbeabed3cf
[ "Apache-2.0" ]
null
null
null
#pragma once #include "pch.h" struct Tool { struct ToolInfo { std::string icon; std::string name; std::string shortcut; std::string helpText; ToolInfo() { icon = "N/A"; name = "N/A"; shortcut = "N/A"; helpText = "N/A"; } ToolInfo(std::string _icon, std::string _name, std::string _shortcut, std::string _helpText) { icon = _icon; name = _name; shortcut = _shortcut; helpText = _helpText; } } info; std::function<void(Vertex*, std::vector<std::pair<unsigned int, float>>)> func; Tool(ToolInfo _info, std::function<void(Vertex*, std::vector<std::pair<unsigned int, float>>)> _func) { info = _info; func = _func; } }; struct Command { Tool* toolUsed; struct Parameters { float toolStrength = 0.0f; float toolWidth = 0.0f; } parameters; std::vector<std::pair<unsigned int, XMFLOAT3>> newPosition; };
21.948718
104
0.650701
[ "vector" ]
0a103dbccb162ca47c3f813d24932917f055bbc6
6,192
h
C
oski-1.0.1h/include/oski/blas_names.h
peterahrens/FillEstimationIPDPS2017
857b6ee8866a2950aa5721d575d2d7d0797c4302
[ "BSD-3-Clause" ]
null
null
null
oski-1.0.1h/include/oski/blas_names.h
peterahrens/FillEstimationIPDPS2017
857b6ee8866a2950aa5721d575d2d7d0797c4302
[ "BSD-3-Clause" ]
null
null
null
oski-1.0.1h/include/oski/blas_names.h
peterahrens/FillEstimationIPDPS2017
857b6ee8866a2950aa5721d575d2d7d0797c4302
[ "BSD-3-Clause" ]
null
null
null
/** * \file oski/blas_names.h * \ingroup AUXIL * \brief Header containing mangled F77 BLAS routine names. * * This file depends on config.h, and so is intended * for use only at library build time. */ #if !defined(INC_OSKI_BLAS_NAMES_H) /** blas_names.h included. */ #define INC_OSKI_BLAS_NAMES_H #include <oski/config.h> #if !defined(F77_FUNC) /** Default definition for F77_FUNC if none exists */ #define F77_FUNC(x, y) x #endif /** * \name Macros for creating BLAS routine names. */ /*@{*/ /** * \brief Creates an Fortran-77 name by concatenating a type tag * and a base name. * * This macro directly concatenates. To allow for macro expansion, * see #MAKE_BLAS_NAME1(). * * \param[in] tag Lowercase, single-letter type tag. * \param[in] name Lowercase base name. * \param[in] TAG Uppercase, single-letter type tag. * \param[in] NAME Uppercase base name. * \returns A Fortran 77 name following the naming conventions * determined at configure-time (e.g., adding a trailing * underscore). * * \see #MAKE_BLAS_NAME1() * \see #F77_FUNC() */ #define MAKE_BLAS_NAME0(tag, name, TAG, NAME) \ F77_FUNC(tag ## name, TAG ## NAME) /** * \brief Generate a non-standard BLAS name which includes an * additional prefix to indicate the integer precision. */ #define MAKE_BLAS_NAME0_I(itag, tag, name, ITAG, TAG, NAME) \ F77_FUNC(itag ## tag ## name, ITAG ## TAG ## NAME) /** * \brief Creates a Fortran 77 name by concatenating a type tag * and a base name. * * This macro immediately calls #MAKE_BLAS_NAME0(), thereby * allowing the tags and base names to be macros that are * expanded just before concatenation. * * \see #MAKE_BLAS_NAME0() */ #define MAKE_BLAS_NAME1(tag, name, TAG, NAME) \ MAKE_BLAS_NAME0(tag, name, TAG, NAME) /** * \brief Generates a non-standard BLAS name which includes an * additional prefix to indicate the integer precision. */ #define MAKE_BLAS_NAME1_I(itag, tag, name, ITAG, TAG, NAME) \ MAKE_BLAS_NAME0_I(itag, tag, name, ITAG, TAG, NAME) /** * \brief Make the standard name of a BLAS routine. * * Given the base BLAS routine name, in both lowercase and * uppercase versions (e.g., gemm and GEMM, trsv and TRSV), * create a Fortran 77 compatible name, given the C-to-Fortran * calling conventions determined at configure time. */ #define MAKE_BLAS_NAME(name, NAME) \ MAKE_BLAS_NAME1(VAL_TAG, name, VAL_TAG_CAPS, NAME) /** * \brief Make the non-standard name of a BLAS routine which uses a * non-standard integer precision. */ #define MAKE_BLAS_NAME_I(name, NAME) \ MAKE_BLAS_NAME1_I(IND_TAG, VAL_TAG, name, \ IND_TAG_CAPS, VAL_TAG_CAPS, NAME) /*@}*/ /** * \name BLAS routine names, hidden behind macros. */ /*@{*/ #if IND_TAG_CHAR == 'i' /* Use standard names */ # define BLAS_xSCAL MAKE_BLAS_NAME(scal, SCAL) # define BLAS_xAXPY MAKE_BLAS_NAME(axpy, AXPY) # define BLAS_xGEMV MAKE_BLAS_NAME(gemv, GEMV) # define BLAS_xTRSV MAKE_BLAS_NAME(trsv, TRSV) #else /* non-standard integer type */ # define BLAS_xSCAL MAKE_BLAS_NAME_I(scal, SCAL) # define BLAS_xAXPY MAKE_BLAS_NAME_I(axpy, AXPY) # define BLAS_xGEMV MAKE_BLAS_NAME_I(gemv, GEMV) # define BLAS_xTRSV MAKE_BLAS_NAME_I(trsv, TRSV) #endif /*@}*/ /** * \brief BLAS vector scale routine, ?scal, which computes \f$x * \leftarrow \alpha\cdot x\f$. * * \param[in] len Length of the vector. * \param[in] alpha Scalar multiplier, \f$\alpha\f$. * \param[in,out] x Vector, \f$x\f$. * \param[in] stride Distance between consecutive elements. */ void BLAS_xSCAL (const oski_index_t * len, oski_value_t * alpha, oski_value_t * x, const oski_index_t * stride); /** * \brief BLAS vector AXPY operation, ?axpy, which computes \f$y * \leftarrow y + \alpha\cdot x\f$. * * \param[in] len Length of x and y. * \param[in] alpha Scalar multiplier, \f$\alpha\f$. * \param[in] x Vector \f$x\f$. * \param[in] incx Distance between consecutive elements of \f$x\f$. * \param[in,out] y Vector \f$y\f$. * \param[in] incy Distance between consecutive elements of \f$x\f$. */ void BLAS_xAXPY (const oski_index_t * len, const oski_value_t * alpha, const oski_value_t * x, const oski_index_t * incx, oski_value_t * y, const oski_index_t * incy); /** * \brief BLAS matrix-vector multiply routine, ?gemv, which computes * the dense matrix-vector multiply operation, \f$y \leftarrow * \beta\cdot y + \alpha\cdot\mathrm{op}(A)\cdot x\f$. * * \param[in] op Transpose operation ('n', 't'), * \param[in] m Number of rows in \f$A\f$. * \param[in] n Number of columns in \f$A\f$. * \param[in] A Array storing \f$A\f$, in column major format. * \param[in] lda Leading dimension of A. * \param[in] alpha Scalar \f$\alpha\f$. * \param[in] x Vector \f$x\f$. * \param[in] incx Distance between \f$x_i, x_{i+1}\f$ in x. * \param[in] beta Scalar \f$\beta\f$. * \param[in,out] y Vector \f$y\f$. * \param[in] incy Distance between \f$y_i, y_{i+1}\f$ in y. */ void BLAS_xGEMV (const char *op, const oski_index_t * m, const oski_index_t * n, const oski_value_t * alpha, const oski_value_t * A, const oski_index_t * lda, const oski_value_t * x, const oski_index_t * incx, const oski_value_t * beta, oski_value_t * y, const oski_index_t * incy); /** * \brief BLAS triangular solve routine, ?trsv, which computes dense * triangular solve operation, \f$x \leftarrow * \mathrm{op}(A^{-1})\cdot x\f$. * * \param[in] shape Lower or upper triangular ('l' or 'u'). * \param[in] op Transpose operation ('n', 't', 'c'). * \param[in] diag Has unit diag or not ('u', 'n'). * \param[in] n Dimension of \f$A\f$. * \param[in] A Values of the dense matrix \f$A\f$, in column * major layout. * \param[in] lda Leading dimension of A. * \param[in,out] x Initial right-hand side, which is overwritten * by the solution on output. * \param[in] incx Distance between elements of x. */ void BLAS_xTRSV (const char* shape, const char* op, const char* diag, const oski_index_t* n, const oski_value_t* A, const oski_index_t* lda, oski_value_t* x, const oski_index_t* incx); #endif /* eof */
33.290323
70
0.675872
[ "shape", "vector" ]
0a13643a9aa5c86cf1001be073352436050030a9
375
h
C
kinematic.h
burbokop/3te
d8a9597338144a7a48fb8993836ff21db7fb563d
[ "MIT" ]
null
null
null
kinematic.h
burbokop/3te
d8a9597338144a7a48fb8993836ff21db7fb563d
[ "MIT" ]
null
null
null
kinematic.h
burbokop/3te
d8a9597338144a7a48fb8993836ff21db7fb563d
[ "MIT" ]
null
null
null
#ifndef KINEMATIC_H #define KINEMATIC_H #include "vector.h" #include <vector> #include <spm.h> namespace burbokop { class Kinematic { protected: Vector *position; Vector *velocity; Vector *acceleration; public: Kinematic(); Kinematic(Vector *position); void applyTransformation(); void applyTransformation(int c); }; } #endif // KINEMATIC_H
13.888889
36
0.698667
[ "vector" ]
0a22c2b7bd83b259aa2b62ebbd513db5b2fb3abb
872
h
C
Graphics/Graphics/Shaders/Shader.h
Neko81795/Graphics
134b174609c609f7762ef0cc3e10398d2472a1b4
[ "MIT" ]
null
null
null
Graphics/Graphics/Shaders/Shader.h
Neko81795/Graphics
134b174609c609f7762ef0cc3e10398d2472a1b4
[ "MIT" ]
null
null
null
Graphics/Graphics/Shaders/Shader.h
Neko81795/Graphics
134b174609c609f7762ef0cc3e10398d2472a1b4
[ "MIT" ]
null
null
null
#pragma once #pragma warning(push, 0) #include <wrl.h> #include <d3d11_4.h> #include <string> #pragma warning(pop) using Microsoft::WRL::ComPtr; namespace Graphics { class GraphicsEngine; enum ShaderType { Compute, Domain, Geometry, Hull, Pixel, Vertex, }; class Shader { public: ComPtr<ID3DBlob> ByteCode; Shader(GraphicsEngine& graphics, std::string path, ShaderType type); bool Create(); void Use(); void UnUse(); private: ComPtr<ID3D11ComputeShader> ComputeShader; ComPtr<ID3D11DomainShader> DomainShader; ComPtr<ID3D11GeometryShader> GeometryShader; ComPtr<ID3D11HullShader> HullShader; ComPtr<ID3D11PixelShader> PixelShader; ComPtr<ID3D11VertexShader> VertexShader; GraphicsEngine& Graphics; ShaderType Type; Shader& operator=(const Shader& shader) = delete; }; }
18.553191
71
0.697248
[ "geometry" ]
0a2843c2342827ac991392e045476139b54ac05f
1,041
h
C
src/ui/traffic_sign_images.h
nikunjpansari/open-adas
64bc65aee5596dc86017b2afdc22af6b04bf65ae
[ "MIT" ]
117
2021-03-10T06:28:15.000Z
2022-03-30T07:16:41.000Z
src/ui/traffic_sign_images.h
skyw0889/open-adas
64bc65aee5596dc86017b2afdc22af6b04bf65ae
[ "MIT" ]
17
2021-03-23T02:08:31.000Z
2022-03-28T15:31:04.000Z
src/ui/traffic_sign_images.h
skyw0889/open-adas
64bc65aee5596dc86017b2afdc22af6b04bf65ae
[ "MIT" ]
49
2021-03-05T10:02:54.000Z
2022-03-22T08:51:25.000Z
#ifndef TRAFFIC_SIGN_IMAGES_H #define TRAFFIC_SIGN_IMAGES_H #include <string> #include <vector> #include <opencv2/opencv.hpp> struct TrafficSignImage { static constexpr int kImgWidth = 48; static constexpr int kImgHeight = 48; int speed; cv::Mat image; TrafficSignImage(int speed, std::string img_path, std::string default_img_path): speed(speed) { std::cout << img_path << std::endl; image = cv::imread(img_path); if (image.empty()) { image = cv::imread(default_img_path); } cv::resize(image, image, cv::Size(kImgWidth, kImgHeight)); } }; class TrafficSignImages { private: const std::string IMG_DIR = "images/traffic_signs/"; const std::vector<int> valid_speeds = {0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; const std::string DEFAULT_IMG_PATH = "images/traffic_signs/DEFAULT.png"; std::vector<TrafficSignImage> images; public: TrafficSignImages(); cv::Mat getSpeedSignImage(int speed); }; #endif
28.135135
99
0.653218
[ "vector" ]
0a32c2259064ac1516b8197539d44bf9647a7f9a
24,287
h
C
src/swxJson.h
swxlion/swxJson
b90f0784cf4ace7d45be6a8c6ce69937985fd5d2
[ "MIT" ]
17
2017-08-06T12:45:57.000Z
2022-01-02T09:24:25.000Z
src/swxJson.h
swxlion/swxJson
b90f0784cf4ace7d45be6a8c6ce69937985fd5d2
[ "MIT" ]
null
null
null
src/swxJson.h
swxlion/swxJson
b90f0784cf4ace7d45be6a8c6ce69937985fd5d2
[ "MIT" ]
5
2017-08-07T14:46:34.000Z
2020-11-09T03:08:32.000Z
#ifndef SWX_JSON_H #define SWX_JSON_H #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <array> #include <deque> #include <list> #include <vector> #include <string> #include <sstream> #include <iostream> #include <memory> #include <tuple> #include <queue> #include "swxJsonUtils.h" namespace swxJson { /******************************************************************* Exception *******************************************************************/ DEFINE_ERROR(JsonError, JosnNodeExistError) DEFINE_ERROR(JsonError, JosnNodeNotExistError) DEFINE_ERROR(JsonError, JosnInvalidContentError) DEFINE_ERROR(JsonError, JsonNodeTypeMissMatchError) class Json; typedef std::shared_ptr<Json> JsonPtr; std::ostream& operator << (std::ostream& os, const Json& node); std::ostream& operator << (std::ostream& os, const JsonPtr node); /******************************************************************* NOTICE: API Group: setXXX(): change the node type and value; addXXX(): if node is array or object, add as sub-node; pushXXX(): if node is array or object, add as sub-node; mergeXXX(): if node is array or object, merge data into current node. (only for containers) getXXX(): fetch node or value, if failed, return nullptr or default value, no throw exceptions; wantXXX(): fetch node or value, if failed, throw exceptions which is sub-type of JsonError. more APIs: please see swxJson.Enhancement.inc.h. Empty string as key in Object: Because ECMA-404 (The JSON Data Interchange Standard) is not disable the empty as key in object, so path such as "..//../." means it has NINE step object and the keys are empty string. Number: support NaN & Infinity (inf) (ignore the cases). *** Only Support utf-8 *** If you want this class support UCS-2, UCS-4, utf-16, utf-32, and BOM, please information me. All throwed exceptions are the sub-type of JsonError. *******************************************************************/ class Json { public: enum ElementType { JSON_Object, JSON_Array, JSON_String, JSON_Integer, JSON_UInteger, JSON_Real, JSON_Boolean, JSON_Null, JSON_Uninit }; private: enum ElementType _type; /* ---------------------------------------------- void *_data maybe: NULL: when type is null, or boolean not NULL: when type is boolean intmax_t * uintmax_t * double * string * std::list<JsonPtr> * std::map<std::string, JsonPtr> * ---------------------------------------------- */ void *_data; void clean(); std::ostream& output(std::ostream& os) const; friend std::ostream& operator << (std::ostream& os, const Json& node); friend std::ostream& operator << (std::ostream& os, const JsonPtr node); JsonPtr getNodeByKey(const std::string& key); JsonPtr getNodeByIndex(int index); JsonPtr getParentNode(const std::string& path, const std::string& delim, std::string& lastSection, bool& nodeTypeError, bool& nodeNotFound); //-- return nullptr if node type miss match in the path. //-- If target existed, just return the node simply. //-- If target isn't exist, just create a uninited node, and return. //-- If throwable, throw JsonNodeTypeMissMatchError. JsonPtr createNode(const std::string& path, const std::string& delim, bool throwable); // bool dictAddBool(const std::string& key, bool value) { return addBasicValue(key, value); } // bool dictAddReal(const std::string& key, double value) { return addBasicValue(key, value); } // bool dictAddInt(const std::string& key, intmax_t value) { return addBasicValue(key, value); } // bool dictAddString(const std::string& key, const std::string& value) { return addBasicValue(key, value); } // bool dictAddNull(const std::string& key); // JsonPtr dictAddArray(const std::string& key); JsonPtr dictAddObject(const std::string& key); Json& operator = (const Json&) = delete; Json(const Json&) = delete; Json(const std::string& value): _type(JSON_String), _data(new std::string(value)) {} Json(const char* value): _type(JSON_String), _data(new std::string(value ? value : "")) {} Json(intmax_t value): _type(JSON_Integer), _data(new intmax_t(value)) {} Json(uintmax_t value): _type(JSON_UInteger), _data(new uintmax_t(value)) {} Json(long double value): _type(JSON_Real), _data(new double((double)value)) {} Json(double value): _type(JSON_Real), _data(new double(value)) {} Json(bool value): _type(JSON_Boolean), _data(value ? (void*)1 : 0) {} //---------- utils functions : Arrays -------------// bool pushNode(JsonPtr node); //-- If node type miss match, return false. //---------- utils functions : Objects -------------// bool addNode(const std::string& key, JsonPtr node); //-- If node type miss match, or key exist, return false. template<typename TYPE> inline bool addBasicValue(const std::string& key, TYPE value) { //JsonPtr node(new Json(value)); JsonPtr node(new Json()); (*node) = value; return addNode(key, node); } friend class JsonParser; public: Json(): _type(JSON_Uninit), _data(NULL) {} ~Json() { clean(); } static JsonPtr parse(const char* data); std::string str(); //==============================[ Set values ]==============================// //-- Old value & sub-nodes will be dropped, and changed node type as the value's type. //-- Following function will not throw any exception. //-------------------[ basic set values ]-------------------// void setNull(); void setBool(bool value); void setInt(intmax_t value); void setUInt(uintmax_t value); void setReal(double value); void setString(const char* value); void setString(const std::string& value); void setArray(); //-- empty array void setDict(); //-- empty dict Json& operator = (bool value) { setBool(value); return *this; } Json& operator = (double value) { setReal(value); return *this; } Json& operator = (long double value) { setReal(value); return *this; } Json& operator = (const char* value) { setString(value); return *this; } Json& operator = (const std::string& value) { setString(value); return *this; } Json& operator = (short value) { setInt(value); return *this; } Json& operator = (unsigned short value) { setUInt(value); return *this; } Json& operator = (int value) { setInt(value); return *this; } Json& operator = (unsigned int value) { setUInt(value); return *this; } Json& operator = (long value) { setInt(value); return *this; } Json& operator = (unsigned long value) { setUInt(value); return *this; } Json& operator = (long long value) { setInt(value); return *this; } Json& operator = (unsigned long long value) { setUInt(value); return *this; } //-------------------[ Advanced set values ]-------------------// //-- Please refer the inc file. //==============================[ Add Array members ]==============================// //-- for array //-- Following functions will throw JsonNodeTypeMissMatchError exception. //-------------------[ basic push values ]-------------------// //-- If current node's type is not array, will return false or nullptr. bool push(bool value) { return pushBool(value); } bool push(double value) { return pushReal(value); } bool push(long double value) { return pushReal(value); } bool push(const char* value) { return pushString(value); } bool push(const std::string& value) { return pushString(value); } bool push(short value) { return pushInt (value); } bool push(unsigned short value) { return pushUInt(value); } bool push(int value) { return pushInt (value); } bool push(unsigned int value) { return pushUInt(value); } bool push(long value) { return pushInt (value); } bool push(unsigned long value) { return pushUInt(value); } bool push(long long value) { return pushInt (value); } bool push(unsigned long long value) { return pushUInt(value); } bool pushNull(); bool pushBool(bool value) { JsonPtr node(new Json(value)); return pushNode(node); } bool pushReal(double value) { JsonPtr node(new Json(value)); return pushNode(node); } bool pushInt(intmax_t value) { JsonPtr node(new Json(value)); return pushNode(node); } bool pushUInt(uintmax_t value) { JsonPtr node(new Json(value)); return pushNode(node); } bool pushString(const char* value) { JsonPtr node(new Json(value)); return pushNode(node); } bool pushString(const std::string& value) { JsonPtr node(new Json(value)); return pushNode(node); } JsonPtr pushArray(); //-- point added array node. JsonPtr pushDict(); //-- point added dict node. //-------------------[ Advanced push values ]-------------------// //-- Please refer the inc file. //-------------------[ Pathlized push values ]-------------------// //-- for array //-- ** The following functions will throw exception: JsonNodeTypeMissMatchError ** //-- If target existed, this operation will change the target node to array type implicitly. void push(const std::string& path, bool value, const std::string& delim = "./") { pushBool(path, value, delim); } void push(const std::string& path, double value, const std::string& delim = "./") { pushReal(path, value, delim); } void push(const std::string& path, long double value, const std::string& delim = "./") { pushReal(path, value, delim); } void push(const std::string& path, const char* value, const std::string& delim = "./") { pushString(path, value, delim); } void push(const std::string& path, const std::string& value, const std::string& delim = "./") { pushString(path, value, delim); } void push(const std::string& path, short value, const std::string& delim = "./") { pushInt (path, value, delim); } void push(const std::string& path, unsigned short value, const std::string& delim = "./") { pushUInt(path, value, delim); } void push(const std::string& path, int value, const std::string& delim = "./") { pushInt (path, value, delim); } void push(const std::string& path, unsigned int value, const std::string& delim = "./") { pushUInt(path, value, delim); } void push(const std::string& path, long value, const std::string& delim = "./") { pushInt (path, value, delim); } void push(const std::string& path, unsigned long value, const std::string& delim = "./") { pushUInt(path, value, delim); } void push(const std::string& path, long long value, const std::string& delim = "./") { pushInt (path, value, delim); } void push(const std::string& path, unsigned long long value, const std::string& delim = "./") { pushUInt(path, value, delim); } void pushNull(const std::string& path, const std::string& delim = "./"); void pushBool(const std::string& path, bool value, const std::string& delim = "./"); void pushReal(const std::string& path, double value, const std::string& delim = "./"); void pushInt(const std::string& path, intmax_t value, const std::string& delim = "./"); void pushUInt(const std::string& path, uintmax_t value, const std::string& delim = "./"); void pushString(const std::string& path, const char* value, const std::string& delim = "./"); void pushString(const std::string& path, const std::string& value, const std::string& delim = "./"); JsonPtr pushArray(const std::string& path, const std::string& delim = "./"); //-- point pushed array node. JsonPtr pushDict(const std::string& path, const std::string& delim = "./"); //-- point pushed dict node. //==============================[ Merge data to Dict or Array Node ]==============================// //-------------------[ Advanced merge values ]-------------------// //-- Please refer the inc file. //-------------------[ Pathlized merge values ]-------------------// //-- Please refer the inc file. //==============================[ Add data to Dict Node ]==============================// //-- for dict //-- the following functions will throw exception: JsonNodeTypeMissMatchError or JosnNodeExistError void add(const std::string& path, bool value, const std::string& delim = "./") { addBool(path, value, delim); } void add(const std::string& path, double value, const std::string& delim = "./") { addReal(path, value, delim); } void add(const std::string& path, long double value, const std::string& delim = "./") { addReal(path, value, delim); } void add(const std::string& path, const char* value, const std::string& delim = "./") { addString(path, value, delim); } void add(const std::string& path, const std::string& value, const std::string& delim = "./") { addString(path, value, delim); } void add(const std::string& path, short value, const std::string& delim = "./") { addInt (path, value, delim); } void add(const std::string& path, unsigned short value, const std::string& delim = "./") { addUInt(path, value, delim); } void add(const std::string& path, int value, const std::string& delim = "./") { addInt (path, value, delim); } void add(const std::string& path, unsigned int value, const std::string& delim = "./") { addUInt(path, value, delim); } void add(const std::string& path, long value, const std::string& delim = "./") { addInt (path, value, delim); } void add(const std::string& path, unsigned long value, const std::string& delim = "./") { addUInt(path, value, delim); } void add(const std::string& path, long long value, const std::string& delim = "./") { addInt (path, value, delim); } void add(const std::string& path, unsigned long long value, const std::string& delim = "./") { addUInt(path, value, delim); } void addBool(const std::string& path, bool value, const std::string& delim = "./"); void addReal(const std::string& path, double value, const std::string& delim = "./"); void addInt(const std::string& path, intmax_t value, const std::string& delim = "./"); void addUInt(const std::string& path, uintmax_t value, const std::string& delim = "./"); void addString(const std::string& path, const char* value, const std::string& delim = "./"); void addString(const std::string& path, const std::string& value, const std::string& delim = "./"); void addNull(const std::string& path, const std::string& delim = "./"); JsonPtr addArray(const std::string& path, const std::string& delim = "./"); JsonPtr addDict(const std::string& path, const std::string& delim = "./"); //-------------------[ Advanced add values ]-------------------// //-- Please refer the inc file. //==============================[ remove sub-nodes ]==============================// //-- If node is not array type, return false; //-- if index out of range, just return true simply. bool remove(int index); //-- If node in path is not object type, return false; //-- if key or node in path is not exist, just return true simply. bool remove(const std::string& path, const std::string& delim = "./"); //==============================[ member checking ]==============================// inline bool isNull() const { return _type == JSON_Null; } inline enum ElementType type() const { return _type; } //-- isNull(): return true only the target exist and which is null. bool isNull(const std::string& path, const std::string& delim = "./") noexcept; bool exist(const std::string& path, const std::string& delim = "./") noexcept { return (getNode(path, delim) != nullptr); } enum ElementType type(const std::string& path, const std::string& delim = "./"); //==============================[ fetch members ]==============================// //------------ get part ------------// bool getBool(bool dft = false) const; intmax_t getInt(intmax_t dft = 0) const; uintmax_t getUInt(uintmax_t dft = 0) const; double getReal(double dft = 0.0) const; std::string getString(const std::string& dft = std::string()) const; const std::list<JsonPtr> * const getList() const; const std::map<std::string, JsonPtr> * const getDict() const; //------------ want part ------------// operator bool() const { return wantBool(); } operator float() const { return (float)wantReal(); } operator double() const { return wantReal(); } operator long double() const { return wantReal(); } operator std::string() const { return wantString(); } operator char() const { return (char) wantInt (); } operator unsigned char() const { return (unsigned char) wantUInt(); } operator short() const { return (short) wantInt (); } operator unsigned short() const { return (unsigned short) wantUInt(); } operator int() const { return (int) wantInt (); } operator unsigned int() const { return (unsigned int) wantUInt(); } operator long() const { return (long) wantInt (); } operator unsigned long() const { return (unsigned long) wantUInt(); } operator long long() const { return (long long) wantInt (); } operator unsigned long long() const { return (unsigned long long)wantUInt(); } bool wantBool() const; intmax_t wantInt() const; uintmax_t wantUInt() const; double wantReal() const; std::string wantString() const; /* * Deprecated !!! * All want???Vector(), want???Dict() are deprecated!!! Please using: wantVector<???>(), wantList<???>(), wantSet<???>(), ..., wantDict<???>() Please refer "swxJson.Enhancement.inc.h" for all new interfaces. */ std::vector<bool> wantBoolVector() const; std::vector<double> wantRealVector() const; std::vector<intmax_t> wantIntVector() const; std::vector<std::string> wantStringVector() const; std::map<std::string, bool> wantBoolDict() const; std::map<std::string, double> wantRealDict() const; std::map<std::string, intmax_t> wantIntDict() const; std::map<std::string, std::string> wantStringDict() const; //-------------------[ fetch members by path ]-------------------// //------------ get part ------------// bool getBool(const std::string& path, bool dft = false, const std::string& delim = "./"); intmax_t getInt(const std::string& path, intmax_t dft = 0, const std::string& delim = "./"); uintmax_t getUInt(const std::string& path, uintmax_t dft = 0, const std::string& delim = "./"); double getReal(const std::string& path, double dft = 0.0, const std::string& delim = "./"); std::string getStringAt(const std::string& path, const std::string& dft = std::string(), const std::string& delim = "./"); bool getBool(const char* path, bool dft = false, const std::string& delim = "./") { return getBool(std::string(path), dft, delim); } intmax_t getInt(const char* path, intmax_t dft = 0, const std::string& delim = "./") { return getInt(std::string(path), dft, delim); } uintmax_t getUInt(const char* path, uintmax_t dft = 0, const std::string& delim = "./") { return getUInt(std::string(path), dft, delim); } double getReal(const char* path, double dft = 0.0, const std::string& delim = "./") { return getReal(std::string(path), dft, delim); } std::string getStringAt(const char* path, const std::string& dft = std::string(), const std::string& delim = "./") { return getStringAt(std::string(path), dft, delim); } JsonPtr getNode(const std::string& path, const std::string& delim = "./"); const std::list<JsonPtr> * const getList(const std::string& path, const std::string& delim = "./"); const std::map<std::string, JsonPtr> * const getDict(const std::string& path, const std::string& delim = "./"); JsonPtr getNode(const char* path, const std::string& delim = "./") { return getNode(std::string(path), delim); } const std::list<JsonPtr> * const getList(const char* path, const std::string& delim = "./") { return getList(std::string(path), delim); } const std::map<std::string, JsonPtr> * const getDict(const char* path, const std::string& delim = "./") { return getDict(std::string(path), delim); } //------------ want part ------------// bool wantBool(const std::string& path, const std::string& delim = "./"); intmax_t wantInt(const std::string& path, const std::string& delim = "./"); uintmax_t wantUInt(const std::string& path, const std::string& delim = "./"); double wantReal(const std::string& path, const std::string& delim = "./"); std::string wantString(const std::string& path, const std::string& delim = "./"); std::string wantStringAt(const std::string& path, const std::string& delim = "./") { return wantString(path, delim); } bool wantBool(const char* path, const std::string& delim = "./") { return wantBool(std::string(path), delim); } intmax_t wantInt(const char* path, const std::string& delim = "./") { return wantInt(std::string(path), delim); } uintmax_t wantUInt(const char* path, const std::string& delim = "./") { return wantUInt(std::string(path), delim); } double wantReal(const char* path, const std::string& delim = "./") { return wantReal(std::string(path), delim); } std::string wantString(const char* path, const std::string& delim = "./") { return wantString(std::string(path), delim); } std::string wantStringAt(const char* path, const std::string& delim = "./") { return wantString(std::string(path), delim); } //-- If any node in path (except the last node) which node type is not dict/object, will throw exception. Json& operator [] (const char* path); Json& operator [] (const std::string& path); Json& operator [] (int index); /* * Deprecated !!! * All want???Vector(...), want???Dict(...) are deprecated!!! Please using: wantVector<???>(...), wantList<???>(...), wantSet<???>(...), ..., wantDict<???>(...) Please refer "swxJson.Enhancement.inc.h" for all new interfaces. */ std::vector<bool> wantBoolVector(const std::string& path, const std::string& delim = "./"); std::vector<double> wantRealVector(const std::string& path, const std::string& delim = "./"); std::vector<intmax_t> wantIntVector(const std::string& path, const std::string& delim = "./"); std::vector<std::string> wantStringVector(const std::string& path, const std::string& delim = "./"); std::map<std::string, bool> wantBoolDict(const std::string& path, const std::string& delim = "./"); std::map<std::string, double> wantRealDict(const std::string& path, const std::string& delim = "./"); std::map<std::string, intmax_t> wantIntDict(const std::string& path, const std::string& delim = "./"); std::map<std::string, std::string> wantStringDict(const std::string& path, const std::string& delim = "./"); std::vector<bool> wantBoolVector(const char* path, const std::string& delim = "./") { return wantBoolVector(std::string(path), delim); } std::vector<double> wantRealVector(const char* path, const std::string& delim = "./") { return wantRealVector(std::string(path), delim); } std::vector<intmax_t> wantIntVector(const char* path, const std::string& delim = "./") { return wantIntVector(std::string(path), delim); } std::vector<std::string> wantStringVector(const char* path, const std::string& delim = "./") { return wantStringVector(std::string(path), delim); } std::map<std::string, bool> wantBoolDict(const char* path, const std::string& delim = "./") { return wantBoolDict(std::string(path), delim); } std::map<std::string, double> wantRealDict(const char* path, const std::string& delim = "./") { return wantRealDict(std::string(path), delim); } std::map<std::string, intmax_t> wantIntDict(const char* path, const std::string& delim = "./") { return wantIntDict(std::string(path), delim); } std::map<std::string, std::string> wantStringDict(const char* path, const std::string& delim = "./") { return wantStringDict(std::string(path), delim); } public: #include "swxJson.Enhancement.inc.h" }; } #endif
54.091314
170
0.61712
[ "object", "vector" ]
0a3be2dc3cea53aa854cbd728aea91bd40897481
21,929
c
C
window.c
damaru/window
4c696eddd307b8d249cf7de2f37832bade394cc9
[ "MIT" ]
null
null
null
window.c
damaru/window
4c696eddd307b8d249cf7de2f37832bade394cc9
[ "MIT" ]
null
null
null
window.c
damaru/window
4c696eddd307b8d249cf7de2f37832bade394cc9
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <errno.h> #include <unistd.h> #include <stdint.h> #include <sys/types.h> #include <sys/wait.h> #include <X11/X.h> #include <X11/Xos.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> typedef struct ReasonDesc ReasonDesc; struct ReasonDesc { char *name; int nargs; int opargs; void (*fn)(char**); char *usage; }; Display *dpy; char *argv0; static void getWindowProperty(Window window, char * name, Bool delete); static void listProps(Window window, char * name, char **values); static Window wind(char *p) { long l; char *endp; if (!strcmp(p, "root")) { return DefaultRootWindow(dpy); } l = strtol(p, &endp, 0); if (*p != '\0' && *endp == '\0') { return (Window) l; } fprintf(stderr, "%s: %s is not a valid window id\n", argv0, p); exit(EXIT_FAILURE); } static int listwindows(Window w, Window **ws) { unsigned nkids; Window dumb; XQueryTree(dpy, w, &dumb, &dumb, ws, &nkids); return nkids; } void XClientMessage( Window win, long type, long l0, long l1, long l2) { XClientMessageEvent xev; Window root = DefaultRootWindow(dpy); xev.type = ClientMessage; xev.window = win; xev.message_type = type; xev.format = 32; xev.data.l[0] = l0; xev.data.l[1] = l1; xev.data.l[2] = l2; xev.data.l[3] = 0; xev.data.l[4] = 0; XSendEvent(dpy, root, False, (SubstructureNotifyMask | SubstructureRedirectMask), (XEvent *) & xev); } static void SetView(char **argv) { Window w = wind(argv[0]); long desk = atoi(argv[1]); Atom prop = XInternAtom(dpy, "_NET_WM_DESKTOP", False); XClientMessage(w, prop, desk, 0, 0); } static void GetView(char ** argv) { getWindowProperty(wind(argv[0]), "_NET_WM_DESKTOP", False); } static void CurrentView(char **argv) { int desk = atoi(argv[0]); Window root = DefaultRootWindow(dpy); Atom prop, numdesks; Atom realType; unsigned long n = 0; unsigned long extra; int format; int status; char * value; prop = XInternAtom(dpy, "_NET_CURRENT_DESKTOP", False); numdesks = XInternAtom(dpy, "_NET_NUMBER_OF_DESKTOPS", False); if(desk < 0) { status = XGetWindowProperty(dpy, root, prop, 0L, 512L, False, AnyPropertyType, &realType, &format, &n, &extra, (unsigned char **) &value); printf("%d / ",*(int*)value); status = XGetWindowProperty(dpy, root, numdesks, 0L, 512L, False, AnyPropertyType, &realType, &format, &n, &extra, (unsigned char **) &value); printf("%d \n",*(int*)value); } else { XClientMessage(root, prop, desk, 0, 0); } } static void RaiseWindow(char **argv) { Window w = wind(*argv); XClientMessage(w, XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False), 2, CurrentTime, 0); XRaiseWindow(dpy, w); XSetInputFocus (dpy, w, RevertToPointerRoot, CurrentTime); } static void MapRaiseWindow(char **argv) { Window w = wind(*argv); XMapRaised(dpy, w); } static void LowerWindow(char **argv) { XLowerWindow(dpy, wind(*argv)); } static void IconifyWindow(char **argv) { XIconifyWindow(dpy, wind(*argv), DefaultScreen(dpy)); } static Bool isprotodel(Window w) { int i, n; Atom *protocols; Bool ret = False; Atom wmd = XInternAtom(dpy, "WM_DELETE_WINDOW", False); if(XGetWMProtocols(dpy, w, &protocols, &n)) { for(i = 0; !ret && i < n; i++) if(protocols[i] == wmd) ret = True; XFree(protocols); } return ret; } static void KillWindow(char **argv) { XEvent ev; Window w = wind(*argv); if(isprotodel(w)) { ev.type = ClientMessage; ev.xclient.window = w; ev.xclient.message_type = XInternAtom(dpy, "WM_PROTOCOLS", False); ev.xclient.format = 32; ev.xclient.data.l[0] = XInternAtom(dpy, "WM_DELETE_WINDOW", False); ev.xclient.data.l[1] = CurrentTime; XSendEvent(dpy, w, False, NoEventMask, &ev); } else { XKillClient(dpy, w); } } static void HideWindow(char **argv) { Window w = wind(*argv); Atom wm_change_state; wm_change_state = XInternAtom(dpy, "WM_CHANGE_STATE", False); XClientMessage(w, wm_change_state,IconicState, CurrentTime, 0); } static void UnhideWindow(char **argv) { Window w = wind(*argv); Atom wm_active = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False); XClientMessage(w, wm_active, 2, CurrentTime, 0); } static void LabelWindow(char **argv) { Window w; w = wind(argv[0]); XStoreName(dpy, w, argv[1]); XSetIconName(dpy, w, argv[1]); } /* * This can only give us an approximate geometry since * we can't find out what decoration the window has. */ static void WhereWindow(char **argv) { Window root; int x, y; unsigned w, h, border, depth; XGetGeometry(dpy, wind(*argv), &root, &x, &y, &w, &h, &border, &depth); printf("%u %u %u %u\n", w, h, x, y); } static void MoveWindow(char **argv) { XMoveWindow(dpy, wind(argv[0]), atoi(argv[1]), atoi(argv[2])); } static void ResizeWindow(char **argv) { XResizeWindow(dpy, wind(argv[0]), atoi(argv[1]), atoi(argv[2])); } static void Max(char **argv) { Window win; int x, y; unsigned w, h, border, depth; XGetGeometry(dpy, DefaultRootWindow(dpy), &win, &x, &y, &w, &h, &border, &depth); win = wind(argv[0]); XMoveWindow(dpy, win, 0, 0); XResizeWindow(dpy, win, w, h); } #if 1 static void printwindowname(Window w) { unsigned char *name; Atom actual_type; int format; unsigned long n; unsigned long extra; /* * This rather unpleasant hack is necessary because xwsh uses * COMPOUND_TEXT rather than STRING for its WM_NAME property, * and anonymous xwsh windows are annoying. */ if(Success == XGetWindowProperty(dpy, w, XA_WM_NAME, 0L, 100L, False, AnyPropertyType, &actual_type, &format, &n, &extra, &name) && name != 0) printf("%#x\t%s\n", (unsigned)w, (char*)name); // else // printf("%#x\t%s\n", (unsigned)w, "(none)"); if(name) XFree(name); } static void ListWindows(char **argv) { char *class = argv[0]; Window *wins; Window dumb; Atom prop; int i; unsigned nkids; int j; nkids = listwindows(DefaultRootWindow(dpy), &wins); if(class) { // printf("class: %s\n",class); prop = XInternAtom(dpy, "WM_CLASS", True); } for(i = nkids-1; i >= 0; i--) { XWindowAttributes attr; Window *kids2; unsigned nkids2; int i2; char *classes[122]; if( XGetWindowAttributes(dpy, wins[i], &attr)) { if(attr.override_redirect == 0 && attr.map_state != IsUnmapped && !XGetTransientForHint(dpy, wins[i], &dumb)){ if(class) { #if 0 Atom actual_type; int format; unsigned long n; unsigned long extra; char *value; XGetWindowProperty(dpy, wins[i], prop, 0L, 512L, False, AnyPropertyType, &actual_type, &format, &n, &extra, (unsigned char **) &value); classes[0] = value; for(j = 0, i2 = 0; i2 < n; i2++) { if(value[i2] == 0){ classes[j+1] = &value[i2+1]; j++; } } classes[j] = NULL; for(i2 = 0; i2 < j && classes[i2]; i2++) { if(strstr(classes[i2], class) ){ printwindowname(wins[i]); break; } } XFree(value); #else listProps(wins[i], "WM_CLASS", classes); for(j = 0; classes[j]; j++) { if(strstr(classes[j], class) ){ //printf("classb[%X] = \'%s\' %p\n",wins[i],classes[j], classes[j]); printwindowname(wins[i]); break; } } #endif } else { printwindowname(wins[i]); } } nkids2 = listwindows(wins[i], &kids2); for(i2 = 0; i2 < nkids2; i2++) { XGetWindowAttributes(dpy, kids2[i2], &attr); if(attr.override_redirect == 0 && attr.map_state == IsViewable) { if(class) { classes[0] = 0; listProps(kids2[i2], "WM_CLASS", classes); for(j = 0; classes[j]; j++) { if(strstr(classes[j], class) ){ // printf("classa[%X] = \'%s\'\n",kids2[i2],classes[j]); printwindowname(kids2[i2]); break; } } } else { printwindowname(kids2[i2]); } } } if(kids2) XFree(kids2); } } if(wins) XFree(wins); } #else static void printwindowname(Window window) { XTextProperty tp; if (window) { if (!XGetWMName(dpy, window, &tp)) { /* Get window name if any */ printf("%#x %s\n",(unsigned)window,"(none)"); } else if (tp.nitems > 0) { printf("%#x ",(unsigned)window); { int count = 0, i, ret; char **list = NULL; ret = XmbTextPropertyToTextList(dpy, &tp, &list, &count); if((ret == Success || ret > 0) && list != NULL){ for(i=0; i<count; i++) printf(list[i]); XFreeStringList(list); } else { printf("%s", tp.value); } } printf("\n"); } else printf("%#x %s\n",(unsigned)window," (none)"); } return; } static void ListWindows(char **argv) { unsigned int i, num; Window root; Window *wins, d1; XWindowAttributes wa; root = DefaultRootWindow(dpy); if((num = listwindows(root, &wins))) { for(i = 0; i < num; i++) { //printwindowname(wins[i]); if(!XGetWindowAttributes(dpy, wins[i], &wa) || XGetTransientForHint(dpy, wins[i], &d1)) continue; if(wa.override_redirect) continue; if(wa.map_state == IsViewable){ printwindowname(wins[i]); sel = wins[i]; } } } if(wins) XFree(wins); } #endif Window sel; void Root(char **argv) { printf("%#x %s\n",(unsigned)DefaultRootWindow(dpy),"root"); } void TopWindow(char **argv) { unsigned int i, num; Window root; Window *wins, d1; XWindowAttributes wa; root = DefaultRootWindow(dpy); sel = BadWindow; if((num = listwindows(root, &wins))) { for(i = 0; i < num; i++) { if(!XGetWindowAttributes(dpy, wins[i], &wa) || XGetTransientForHint(dpy, wins[i], &d1)) continue; if(wa.override_redirect) continue; if(wa.map_state == IsViewable){ sel = wins[i]; } } } if(sel != BadWindow){ printwindowname(sel); } if(wins) XFree(wins); } #define LONG_MAX (~((unsigned long)0)) #define DEF_ATOM(name) Atom ATOM_##name DEF_ATOM(_NET_WM_WINDOW_TYPE); DEF_ATOM(_NET_WM_WINDOW_TYPE_DESKTOP); DEF_ATOM(_NET_WM_WINDOW_TYPE_DOCK); DEF_ATOM(_NET_WM_WINDOW_TYPE_DIALOG); DEF_ATOM(_NET_WM_WINDOW_TYPE_SPLASH); DEF_ATOM(WM_PROTOCOLS); DEF_ATOM(WM_DELETE_WINDOW); DEF_ATOM(WM_NAME); DEF_ATOM(WM_STATE); DEF_ATOM(WM_CHANGE_STATE); DEF_ATOM(_NET_WM_NAME); DEF_ATOM(_NET_WM_STATE); DEF_ATOM(_NET_WM_STATE_MODAL); DEF_ATOM(_NET_SUPPORTED); //#define NATOMS ((Atom*)&ATOM__NET_SUPPORTED - (Atom*)&ATOM__NET_CLIENT_LIST) #define NATOMS 25 void zwm_init_atoms(void) { #define INIT_ATOM(name) ATOM_##name = XInternAtom(dpy, #name, False) INIT_ATOM(_NET_WM_WINDOW_TYPE); INIT_ATOM(_NET_WM_WINDOW_TYPE_DESKTOP); INIT_ATOM(_NET_WM_WINDOW_TYPE_DOCK); INIT_ATOM(_NET_WM_WINDOW_TYPE_DIALOG); INIT_ATOM(_NET_WM_WINDOW_TYPE_SPLASH); INIT_ATOM(WM_PROTOCOLS); INIT_ATOM(WM_DELETE_WINDOW); INIT_ATOM(WM_NAME); INIT_ATOM(WM_STATE); INIT_ATOM(_NET_WM_NAME); INIT_ATOM(_NET_WM_STATE); INIT_ATOM(_NET_WM_STATE_MODAL); INIT_ATOM(_NET_SUPPORTED); } Bool zwm_x11_check_atom(Window win, Atom bigatom, Atom smallatom){ Atom real, *state; int format; unsigned char *data = NULL; unsigned long i, n, extra; if(XGetWindowProperty(dpy, win, bigatom, 0L, LONG_MAX, False, XA_ATOM, &real, &format, &n, &extra, (unsigned char **) &data) == Success && data){ state = (Atom *) data; for(i = 0; i < n; i++){ if(state[i] == smallatom) return True; } } return False; } static int check_panel(Window w) { if(zwm_x11_check_atom(w, ATOM__NET_WM_WINDOW_TYPE, ATOM__NET_WM_WINDOW_TYPE_DOCK)){ return 1; } return 0; } static int check_desktop(Window w) { if(zwm_x11_check_atom(w, ATOM__NET_WM_WINDOW_TYPE, ATOM__NET_WM_WINDOW_TYPE_DESKTOP)){ return 1; } return 0; } void NextWindow(char **argv) { unsigned int i, num, w, h, d, b; int x,y; int revertToReturn; Window root, focusReturn; Window *wins, d1; XWindowAttributes wa; root = DefaultRootWindow(dpy); sel = BadWindow; zwm_init_atoms(); XGetInputFocus(dpy, &focusReturn, &revertToReturn); printwindowname(focusReturn); // XCirculateSubwindowsUp(dpy, DefaultRootWindow(dpy)); if((num = listwindows(root, &wins))) { for(i = 0; i < num; i++) { printwindowname(wins[i]); if(!XGetWindowAttributes(dpy, wins[i], &wa) || XGetTransientForHint(dpy, wins[i], &d1) || check_panel(wins[i]) || check_desktop(wins[i]) ) continue; if(wa.override_redirect) continue; if(wa.map_state == IsViewable && focusReturn == wins[i]){ i++; break; } } for(; i < num; i++) { printwindowname(wins[i]); if(!XGetWindowAttributes(dpy, wins[i], &wa) || XGetTransientForHint(dpy, wins[i], &d1) || check_panel(wins[i]) || check_desktop(wins[i]) ) continue; if(wa.override_redirect) continue; if(wa.map_state == IsViewable ){ sel = wins[i]; break; } } } if(sel == BadWindow){ for(i = 0; i < num; i++) { printwindowname(wins[i]); if(!XGetWindowAttributes(dpy, wins[i], &wa) || XGetTransientForHint(dpy, wins[i], &d1) || check_panel(wins[i]) || check_desktop(wins[i]) ) continue; if(wa.override_redirect) continue; if(wa.map_state == IsViewable ){ sel = wins[i]; break; } } } if (sel != BadWindow) { //focus XMapWindow(dpy, sel); XRaiseWindow(dpy, sel); XSetInputFocus (dpy, sel, RevertToPointerRoot, CurrentTime); XGetGeometry(dpy, sel, &root, &x, &y, &w, &h, &d, &b); XWarpPointer(dpy, None, sel, 0, 0, 0, 0, w/2, h/2); printwindowname(sel); } if(wins) XFree(wins); } static void listProps(Window window, char * name, char **values) { Atom prop; Atom realType; unsigned long n; unsigned long extra; int format; int status; char * value; int i,j = 0; prop = XInternAtom(dpy, name, True); if (prop == None) { fprintf(stderr, "%s: no such property '%s'\n", argv0, name); return; } status = XGetWindowProperty(dpy, window, prop, 0L, 512L, 0, AnyPropertyType, &realType, &format, &n, &extra, (unsigned char **) &value); if (status != Success || n == 0) { values[0] = 0; return; } values[0] = NULL; if(format == 8) { values[0] = strdup(value); for(j = 0, i = 0; i < n; i++) { if(value[i] == 0){ values[++j] = strdup(&value[i+1]); } } j++; } else if(format == 32) { for(j=0, i = 0; i < n; i++) { #if __x86_64__ values[j++] = (char*)((uint64_t*)value)[i]; #else values[j++] = (char*)((int*)value)[i]; #endif } } values[j] = NULL; XFree(value); } static void getWindowProperty(Window window, char * name, Bool delete) { Atom prop; Atom realType; unsigned long n; unsigned long extra; int format; int status; char * value; char *values[32]; int i,j; prop = XInternAtom(dpy, name, True); if (prop == None) { fprintf(stderr, "%s: no such property '%s'\n", argv0, name); return; } status = XGetWindowProperty(dpy, window, prop, 0L, 512L, delete, AnyPropertyType, &realType, &format, &n, &extra, (unsigned char **) &value); if (status != Success || value == 0 || *value == 0 || n == 0) { fprintf(stderr, "%s: couldn't read property on window %lx\n", argv0, window); return; } // printf("%d %d",realType, format); if(format == 8) { values[0] = value; for(j = 0, i = 0; i < n; i++) { if(value[i] == 0){ values[j+1] = &value[i+1]; j++; } } values[j+1] = NULL; for(i = 0; values[i]; i++) { if(strlen(values[i])){ if(i>0) printf(", "); printf("%s",values[i]); } } } else if(format == 32) { for(i = 0; i < n; i++) { printf("%d%c",((int*)value)[i],n>1?',':0); } } if(n)printf("\n"); XFree(value); } static void GetProperty(char ** argv) { getWindowProperty(wind(argv[0]), argv[1], False); } static void SetProperty(char ** argv) { Atom prop; char * name = argv[1]; char * value = argv[2]; prop = XInternAtom(dpy, name, False); if (prop == None) { fprintf(stderr, "%s: no such property '%s'\n", argv0, name); return; } XChangeProperty(dpy, wind(argv[0]), prop, XA_STRING, 8, PropModeReplace, (unsigned char*)value, strlen(value)); } static void WarpPointer(char ** argv) { XWarpPointer(dpy, None, wind(argv[0]), 0, 0, 0, 0, atoi(argv[1]), atoi(argv[2])); } static void GetFocusWindow(char ** argv) { Window focusReturn; int revertToReturn; XGetInputFocus(dpy, &focusReturn, &revertToReturn); printwindowname(focusReturn); } static void FocusWindow(char ** argv) { XSetInputFocus(dpy, wind(argv[0]), RevertToPointerRoot, CurrentTime); } static void GetSelection(char ** argv) { Window window; Atom dataProperty; XEvent ev; /* Create an unmapped invisible window. */ window = XCreateWindow(dpy, DefaultRootWindow(dpy), 0, 0, 1, 1, 0, CopyFromParent, InputOnly, CopyFromParent, 0, 0); /* Ask that the current selection be placed in a property on the window. */ dataProperty = XInternAtom(dpy, "SELECTION", False); XConvertSelection(dpy, XA_PRIMARY, XA_STRING, dataProperty, window, CurrentTime); /* Wait for it to arrive. */ do { XNextEvent(dpy, &ev); } while (ev.type != SelectionNotify); getWindowProperty(window, "SELECTION", True); } static void DeleteSelection(char ** argv) { XSetSelectionOwner(dpy, XA_PRIMARY, None, CurrentTime); } static void CirculateUp(char ** argv) { XCirculateSubwindowsUp(dpy, DefaultRootWindow(dpy)); } static void CirculateDown(char ** argv) { XCirculateSubwindowsDown(dpy, DefaultRootWindow(dpy)); } static void GetDisplayWidth(char ** argv) { printf("%d\n", DisplayWidth(dpy, DefaultScreen(dpy))); } static void GetDisplayHeight(char ** argv) { printf("%d\n", DisplayHeight(dpy, DefaultScreen(dpy))); } #ifdef CONFIG_XINERAMA #include <X11/extensions/Xinerama.h> #endif static void resolution(char **argv) { int vscreen_x,vscreen_y,vscreen_w,vscreen_h; int i; #ifdef CONFIG_XINERAMA if ( XineramaIsActive(dpy) ) { int nscreen; XineramaScreenInfo * info = XineramaQueryScreens( dpy, &nscreen ); for( i = 0; i< nscreen; i++ ) { if( i == 0 || (info[i].x_org != info[i-1].x_org)) { printf( "Screen %d : %d+%d+%dx%d\n", info[i].screen_number, info[i].x_org, info[i].y_org, info[i].width, info[i].height ); if(vscreen_y >= info[i].y_org) vscreen_y = info[i].y_org; if(vscreen_x >= info[i].x_org) vscreen_x = info[i].x_org; vscreen_w += info[i].width ; if(vscreen_h < info[i].height) vscreen_h = info[i].height; } } XFree(info); } else #endif { vscreen_x = 0; vscreen_y = 0; vscreen_w = DisplayWidth(dpy, DefaultScreen(dpy)); vscreen_h = DisplayHeight(dpy, DefaultScreen(dpy)); printf( "Screen %d: %d+%d+%dx%d\n", 0, vscreen_x, vscreen_y, vscreen_w , vscreen_h); } } static void WherePointer(char ** argv) { Window rr,ch; int x, y; Window root = DefaultRootWindow(dpy); int wx, wy, mask; Bool ret = XQueryPointer(dpy, root, &rr, &ch, &x, &y, &wx, &wy, &mask); if(ret){ printf("%d %d\n", x, y); } } static ReasonDesc reasons[] = { { "-circdown", 0, 0,CirculateDown, "" }, { "-circup", 0, 0,CirculateUp, "" }, { "-delsel", 0, 0,DeleteSelection, "" }, { "-displayheight",0, 0,GetDisplayHeight, "" }, { "-displaywidth",0, 0,GetDisplayWidth, "" }, { "-focus", 1, 0,FocusWindow, "<id>" }, { "-focused", 0, 0,GetFocusWindow, "" }, { "-getprop", 2, 0,GetProperty, "<id> <name>" }, { "-getsel", 0, 0,GetSelection, "" }, { "-hide", 1, 0,HideWindow, "<id>" }, { "-iconify", 1, 0,IconifyWindow, "<id>" }, { "-kill", 1, 0,KillWindow, "<id>" }, { "-label", 2, 0,LabelWindow, "<id> <text>" }, { "-leaf", 0, 0,TopWindow, "" }, { "-list", 1, 1,ListWindows, "<class>" }, { "-lower", 1, 0,LowerWindow, "<id>" }, { "-mapraised", 1, 0,MapRaiseWindow, "<id>" }, { "-max", 1, 0,Max, "<id>" }, { "-move", 3, 0,MoveWindow, "<id> <x> <y>" }, { "-next", 0, 0,NextWindow, "" }, { "-raise", 1, 0,RaiseWindow, "<id>" }, { "-resize", 3, 0,ResizeWindow, "<id> <x> <y>" }, { "-resolution",0 , 0,resolution, "" }, { "-root", 0, 0,Root, "" }, { "-setprop", 3, 0,SetProperty, "<id> <name> <value>" }, { "-setview", 2, 0,SetView, "<id> <view>" }, { "-getview", 1, 0,GetView, "<id>" }, { "-unhide", 1, 0,UnhideWindow, "<id>" }, { "-view", 1, 0,CurrentView, "<view|-1>" }, { "-warppointer", 3, 0, WarpPointer, "<id> <x> <y>" }, { "-where", 1, 0,WhereWindow, "<id>" }, { "-pointer", 0, 0,WherePointer, "" }, }; static int handler(Display *disp, XErrorEvent *err) { fprintf(stderr, "%s: no window with id %#x\n", argv0, (int) err->resourceid); exit(EXIT_FAILURE); } static void usage(void) { ReasonDesc * p; fprintf(stderr, "usage: %s\n", argv0); for (p = reasons; p < reasons + sizeof reasons/sizeof reasons[0]; p++) { fprintf(stderr, " %s %s %s\n", argv0, p->name, p->usage); } } extern int main(int argc, char * argv[]) { ReasonDesc * p; argv0 = argv[0]; dpy = XOpenDisplay(""); if (dpy == 0) { fprintf(stderr, "%s: can't open display.\n", argv0); exit(EXIT_FAILURE); } XSetErrorHandler(handler); if (argc > 1) { for (p = reasons; p < reasons + sizeof reasons / sizeof reasons[0]; p++) { if (strcmp(p->name, argv[1]) == 0 || strcmp(&p->name[1], argv[1]) == 0) { if (argc - 2 != p->nargs && ((p->opargs && argc - 2 > p->opargs) || p->opargs == 0) ) { fprintf(stderr, "%s: the %s option requires %d argument%s.\n", argv0, argv[1], p->nargs, p->nargs > 1 ? "s" : ""); exit(EXIT_FAILURE); } p->fn(argv + 2); XSync(dpy, True); return EXIT_SUCCESS; } } } usage(); return EXIT_FAILURE; }
22.5607
91
0.608236
[ "geometry" ]
0a445232b485b1983a29181a511f3c423102e4ea
4,460
h
C
include/iga/IGACreator.h
Autodesk/IGA-saveload
31d1f80c4c8c1f64bc00be1c67aa230ddeac51ec
[ "Apache-2.0" ]
4
2020-09-17T03:37:04.000Z
2021-05-12T11:11:35.000Z
include/iga/IGACreator.h
Autodesk/IGA-saveload
31d1f80c4c8c1f64bc00be1c67aa230ddeac51ec
[ "Apache-2.0" ]
null
null
null
include/iga/IGACreator.h
Autodesk/IGA-saveload
31d1f80c4c8c1f64bc00be1c67aa230ddeac51ec
[ "Apache-2.0" ]
2
2020-08-20T02:02:54.000Z
2021-12-08T14:50:14.000Z
// Copyright 2020 Autodesk, Inc. // // Licensed under the Apache License, Version 2.0 ( the "License" ); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http ://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef IGA_CREATOR_H_ #define IGA_CREATOR_H_ #include "IGAData.h" #include <map> namespace iga_fileio { struct CoeffVectorLessThan { bool operator()( const CoeffVector &a, const CoeffVector &b ) const; }; /// Type used for coefficient vector lookup tables. using CoeffLookup = std::map< CoeffVector, uint32_t, CoeffVectorLessThan >; /// Type used for face layout lookup tables. using LayoutLookup = std::map< FaceLayout, uint32_t >; /// Use this class to add data to an IGAData object. This class is used /// to hold the lookup tables needed to build the dictionaries, which /// are used to avoid storing redundant data in an IGA file. class IGACreator { public: /// This constructor clears the parent IGAData. It would probably /// be possible to rebuild the lookup tables for the parent IGAData and /// thus allow editing of existing ones, but we don't need that currently. IGACreator( IGAData *parent ); /// Add a vector of coefficients and returns the (first) index added. /// The vector occupies the following coeffs.size() indices. Returns /// INVALID_INDEX if the operation fails. uint32_t addCoeffs( const CoeffVector &coeffs ); /// Add an edge and its interval. Pass a negative number for the /// knot_interval if you don't want to save intervals, or pass a value /// >= 0.0 if you do. You must be consistent about this, and it will /// return INVALID_INDEX (failure) if you aren't. uint32_t addEdge( uint32_t elem, double knot_interval ); /// Adds an Elem and returns the index added. Returns INVALID_INDEX if /// the operation fails. uint32_t addElem( const Elem &elem ); /// Adds a single explicit piece to the end of the data vector. Note that /// all pieces for a given patch must be added together. The t_order can /// be inferred from the size of coeffs. uint32_t addExplicitPiece( int s_order, uint32_t pt_index, const CoeffVector &coeffs ); /// Adds a FaceLayout and returns the index added. Returns INVALID_INDEX /// if the operation fails. uint32_t addLayout( const FaceLayout &layout ); /// Adds a Piece2D and returns the index added. Returns INVALID_INDEX if /// the operation fails. This requires you to build the Piece2D data /// yourself; use addExplicitPiece or addTensorPiece to avoid that. uint32_t addPiece( const Piece2D &piece ); /// Adds a Point3d and returns the index added. Returns INVALID_INDEX if /// the operation fails. uint32_t addPoint( const Point3d &pt ); // Must implement this before I'm done. uint32_t addTensorPiece( const CoeffVector &s_coeffs, const CoeffVector &t_coeffs, uint32_t pt_index ); /// Call this after you've finished adding all the pieces and edges for /// the current element. Pass the index of the layout being used, which must /// be consistent with the number of edges which were added (otherwise it /// will return INVALID_INDEX). The index of the added element is returned. uint32_t finishElem( uint32_t layout_index ); /// Given the coefficient vector 'coeffs', get an index in mCoeffDictionary /// that can be used to represent the start of that coefficient block. uint32_t getDictionaryIndex( const CoeffVector &coeffs ); /// Given a face layout, returns the index used for representing that layout in /// the layout dictionary. Adds the layout if it didn't already have an index. uint32_t getLayoutIndex( const FaceLayout &layout ); /// Set a string to record the type of surface that's being saved. void setSurfaceType( const std::string &surface_type ); private: /// A "parent" IGAData object. This is the object to which we are /// adding data. IGAData *mParent = nullptr; /// A lookup table used to add new vectors to the coeff dictionary. CoeffLookup mCoeffLookup; /// A lookup table for the face layouts. LayoutLookup mLayoutLookup; }; } #endif
39.821429
105
0.736099
[ "object", "vector" ]
0a4de54214f49a44a048e48bddccff32a0c4df83
33,106
c
C
node_modules/extsprintf/deps/javascriptlint/spidermonkey/src/jsiter.c
tross78/placematch
07bb4463b75bc68c3ee275c288890232f91533af
[ "MIT" ]
324
2015-01-01T14:56:10.000Z
2022-03-08T04:52:37.000Z
node_modules/extsprintf/deps/javascriptlint/spidermonkey/src/jsiter.c
tross78/placematch
07bb4463b75bc68c3ee275c288890232f91533af
[ "MIT" ]
38
2015-01-31T03:57:16.000Z
2019-04-21T03:30:53.000Z
node_modules/extsprintf/deps/javascriptlint/spidermonkey/src/jsiter.c
tross78/placematch
07bb4463b75bc68c3ee275c288890232f91533af
[ "MIT" ]
60
2015-01-14T14:19:41.000Z
2021-02-10T21:54:12.000Z
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sw=4 et tw=78: * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * JavaScript iterators. */ #include "jsstddef.h" #include <string.h> /* for memcpy */ #include "jstypes.h" #include "jsutil.h" #include "jsarena.h" #include "jsapi.h" #include "jsarray.h" #include "jsatom.h" #include "jsbool.h" #include "jscntxt.h" #include "jsconfig.h" #include "jsexn.h" #include "jsfun.h" #include "jsgc.h" #include "jsinterp.h" #include "jsiter.h" #include "jslock.h" #include "jsnum.h" #include "jsobj.h" #include "jsopcode.h" #include "jsscope.h" #include "jsscript.h" #if JS_HAS_XML_SUPPORT #include "jsxml.h" #endif extern const char js_throw_str[]; /* from jsscan.h */ #define JSSLOT_ITER_STATE (JSSLOT_PRIVATE) #define JSSLOT_ITER_FLAGS (JSSLOT_PRIVATE + 1) #if JSSLOT_ITER_FLAGS >= JS_INITIAL_NSLOTS #error JS_INITIAL_NSLOTS must be greater than JSSLOT_ITER_FLAGS. #endif /* * Shared code to close iterator's state either through an explicit call or * when GC detects that the iterator is no longer reachable. */ void js_CloseIteratorState(JSContext *cx, JSObject *iterobj) { jsval *slots; jsval state, parent; JSObject *iterable; JS_ASSERT(JS_InstanceOf(cx, iterobj, &js_IteratorClass, NULL)); slots = iterobj->slots; /* Avoid double work if js_CloseNativeIterator was called on obj. */ state = slots[JSSLOT_ITER_STATE]; if (JSVAL_IS_NULL(state)) return; /* Protect against failure to fully initialize obj. */ parent = slots[JSSLOT_PARENT]; if (!JSVAL_IS_PRIMITIVE(parent)) { iterable = JSVAL_TO_OBJECT(parent); #if JS_HAS_XML_SUPPORT if ((JSVAL_TO_INT(slots[JSSLOT_ITER_FLAGS]) & JSITER_FOREACH) && OBJECT_IS_XML(cx, iterable)) { ((JSXMLObjectOps *) iterable->map->ops)-> enumerateValues(cx, iterable, JSENUMERATE_DESTROY, &state, NULL, NULL); } else #endif OBJ_ENUMERATE(cx, iterable, JSENUMERATE_DESTROY, &state, NULL); } slots[JSSLOT_ITER_STATE] = JSVAL_NULL; } JSClass js_IteratorClass = { "Iterator", JSCLASS_HAS_RESERVED_SLOTS(2) | /* slots for state and flags */ JSCLASS_HAS_CACHED_PROTO(JSProto_Iterator), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS }; static JSBool InitNativeIterator(JSContext *cx, JSObject *iterobj, JSObject *obj, uintN flags) { jsval state; JSBool ok; JS_ASSERT(JSVAL_TO_PRIVATE(iterobj->slots[JSSLOT_CLASS]) == &js_IteratorClass); /* Initialize iterobj in case of enumerate hook failure. */ iterobj->slots[JSSLOT_PARENT] = OBJECT_TO_JSVAL(obj); iterobj->slots[JSSLOT_ITER_STATE] = JSVAL_NULL; iterobj->slots[JSSLOT_ITER_FLAGS] = INT_TO_JSVAL(flags); if (!js_RegisterCloseableIterator(cx, iterobj)) return JS_FALSE; if (!obj) return JS_TRUE; ok = #if JS_HAS_XML_SUPPORT ((flags & JSITER_FOREACH) && OBJECT_IS_XML(cx, obj)) ? ((JSXMLObjectOps *) obj->map->ops)-> enumerateValues(cx, obj, JSENUMERATE_INIT, &state, NULL, NULL) : #endif OBJ_ENUMERATE(cx, obj, JSENUMERATE_INIT, &state, NULL); if (!ok) return JS_FALSE; iterobj->slots[JSSLOT_ITER_STATE] = state; if (flags & JSITER_ENUMERATE) { /* * The enumerating iterator needs the original object to suppress * enumeration of deleted or shadowed prototype properties. Since the * enumerator never escapes to scripts, we use the prototype slot to * store the original object. */ JS_ASSERT(obj != iterobj); iterobj->slots[JSSLOT_PROTO] = OBJECT_TO_JSVAL(obj); } return JS_TRUE; } static JSBool Iterator(JSContext *cx, JSObject *iterobj, uintN argc, jsval *argv, jsval *rval) { JSBool keyonly; uintN flags; JSObject *obj; keyonly = JS_FALSE; if (!js_ValueToBoolean(cx, argv[1], &keyonly)) return JS_FALSE; flags = keyonly ? 0 : JSITER_FOREACH; if (cx->fp->flags & JSFRAME_CONSTRUCTING) { /* XXX work around old valueOf call hidden beneath js_ValueToObject */ if (!JSVAL_IS_PRIMITIVE(argv[0])) { obj = JSVAL_TO_OBJECT(argv[0]); } else { obj = js_ValueToNonNullObject(cx, argv[0]); if (!obj) return JS_FALSE; argv[0] = OBJECT_TO_JSVAL(obj); } return InitNativeIterator(cx, iterobj, obj, flags); } *rval = argv[0]; return js_ValueToIterator(cx, flags, rval); } static JSBool NewKeyValuePair(JSContext *cx, jsid key, jsval val, jsval *rval) { jsval vec[2]; JSTempValueRooter tvr; JSObject *aobj; vec[0] = ID_TO_VALUE(key); vec[1] = val; JS_PUSH_TEMP_ROOT(cx, 2, vec, &tvr); aobj = js_NewArrayObject(cx, 2, vec); *rval = OBJECT_TO_JSVAL(aobj); JS_POP_TEMP_ROOT(cx, &tvr); return aobj != NULL; } static JSBool IteratorNextImpl(JSContext *cx, JSObject *obj, jsval *rval) { JSObject *iterable; jsval state; uintN flags; JSBool foreach, ok; jsid id; JS_ASSERT(OBJ_GET_CLASS(cx, obj) == &js_IteratorClass); iterable = OBJ_GET_PARENT(cx, obj); JS_ASSERT(iterable); state = OBJ_GET_SLOT(cx, obj, JSSLOT_ITER_STATE); if (JSVAL_IS_NULL(state)) goto stop; flags = JSVAL_TO_INT(OBJ_GET_SLOT(cx, obj, JSSLOT_ITER_FLAGS)); JS_ASSERT(!(flags & JSITER_ENUMERATE)); foreach = (flags & JSITER_FOREACH) != 0; ok = #if JS_HAS_XML_SUPPORT (foreach && OBJECT_IS_XML(cx, iterable)) ? ((JSXMLObjectOps *) iterable->map->ops)-> enumerateValues(cx, iterable, JSENUMERATE_NEXT, &state, &id, rval) : #endif OBJ_ENUMERATE(cx, iterable, JSENUMERATE_NEXT, &state, &id); if (!ok) return JS_FALSE; OBJ_SET_SLOT(cx, obj, JSSLOT_ITER_STATE, state); if (JSVAL_IS_NULL(state)) goto stop; if (foreach) { #if JS_HAS_XML_SUPPORT if (!OBJECT_IS_XML(cx, iterable) && !OBJ_GET_PROPERTY(cx, iterable, id, rval)) { return JS_FALSE; } #endif if (!NewKeyValuePair(cx, id, *rval, rval)) return JS_FALSE; } else { *rval = ID_TO_VALUE(id); } return JS_TRUE; stop: JS_ASSERT(OBJ_GET_SLOT(cx, obj, JSSLOT_ITER_STATE) == JSVAL_NULL); *rval = JSVAL_HOLE; return JS_TRUE; } static JSBool js_ThrowStopIteration(JSContext *cx, JSObject *obj) { jsval v; JS_ASSERT(!JS_IsExceptionPending(cx)); if (js_FindClassObject(cx, NULL, INT_TO_JSID(JSProto_StopIteration), &v)) JS_SetPendingException(cx, v); return JS_FALSE; } static JSBool iterator_next(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { if (!JS_InstanceOf(cx, obj, &js_IteratorClass, argv)) return JS_FALSE; if (!IteratorNextImpl(cx, obj, rval)) return JS_FALSE; if (*rval == JSVAL_HOLE) { *rval = JSVAL_NULL; js_ThrowStopIteration(cx, obj); return JS_FALSE; } return JS_TRUE; } static JSBool iterator_self(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = OBJECT_TO_JSVAL(obj); return JS_TRUE; } static JSFunctionSpec iterator_methods[] = { {js_iterator_str, iterator_self, 0,JSPROP_READONLY|JSPROP_PERMANENT,0}, {js_next_str, iterator_next, 0,JSPROP_READONLY|JSPROP_PERMANENT,0}, {0,0,0,0,0} }; uintN js_GetNativeIteratorFlags(JSContext *cx, JSObject *iterobj) { if (OBJ_GET_CLASS(cx, iterobj) != &js_IteratorClass) return 0; return JSVAL_TO_INT(OBJ_GET_SLOT(cx, iterobj, JSSLOT_ITER_FLAGS)); } void js_CloseNativeIterator(JSContext *cx, JSObject *iterobj) { uintN flags; /* * If this iterator is not an instance of the native default iterator * class, leave it to be GC'ed. */ if (!JS_InstanceOf(cx, iterobj, &js_IteratorClass, NULL)) return; /* * If this iterator was not created by js_ValueToIterator called from the * for-in loop code in js_Interpret, leave it to be GC'ed. */ flags = JSVAL_TO_INT(OBJ_GET_SLOT(cx, iterobj, JSSLOT_ITER_FLAGS)); if (!(flags & JSITER_ENUMERATE)) return; js_CloseIteratorState(cx, iterobj); } /* * Call ToObject(v).__iterator__(keyonly) if ToObject(v).__iterator__ exists. * Otherwise construct the defualt iterator. */ JSBool js_ValueToIterator(JSContext *cx, uintN flags, jsval *vp) { JSObject *obj; JSTempValueRooter tvr; const JSAtom *atom; JSBool ok; JSObject *iterobj; jsval arg; JSString *str; JS_ASSERT(!(flags & ~(JSITER_ENUMERATE | JSITER_FOREACH | JSITER_KEYVALUE))); /* JSITER_KEYVALUE must always come with JSITER_FOREACH */ JS_ASSERT(!(flags & JSITER_KEYVALUE) || (flags & JSITER_FOREACH)); /* XXX work around old valueOf call hidden beneath js_ValueToObject */ if (!JSVAL_IS_PRIMITIVE(*vp)) { obj = JSVAL_TO_OBJECT(*vp); } else { /* * Enumerating over null and undefined gives an empty enumerator. * This is contrary to ECMA-262 9.9 ToObject, invoked from step 3 of * the first production in 12.6.4 and step 4 of the second production, * but it's "web JS" compatible. */ if ((flags & JSITER_ENUMERATE)) { if (!js_ValueToObject(cx, *vp, &obj)) return JS_FALSE; if (!obj) goto default_iter; } else { obj = js_ValueToNonNullObject(cx, *vp); if (!obj) return JS_FALSE; } } JS_ASSERT(obj); JS_PUSH_TEMP_ROOT_OBJECT(cx, obj, &tvr); atom = cx->runtime->atomState.iteratorAtom; #if JS_HAS_XML_SUPPORT if (OBJECT_IS_XML(cx, obj)) { if (!js_GetXMLFunction(cx, obj, ATOM_TO_JSID(atom), vp)) goto bad; } else #endif { if (!OBJ_GET_PROPERTY(cx, obj, ATOM_TO_JSID(atom), vp)) goto bad; } if (JSVAL_IS_VOID(*vp)) { default_iter: /* * Fail over to the default enumerating native iterator. * * Create iterobj with a NULL parent to ensure that we use the correct * scope chain to lookup the iterator's constructor. Since we use the * parent slot to keep track of the iterable, we must fix it up after. */ iterobj = js_NewObject(cx, &js_IteratorClass, NULL, NULL); if (!iterobj) goto bad; /* Store iterobj in *vp to protect it from GC (callers must root vp). */ *vp = OBJECT_TO_JSVAL(iterobj); if (!InitNativeIterator(cx, iterobj, obj, flags)) goto bad; } else { arg = BOOLEAN_TO_JSVAL((flags & JSITER_FOREACH) == 0); if (!js_InternalInvoke(cx, obj, *vp, JSINVOKE_ITERATOR, 1, &arg, vp)) goto bad; if (JSVAL_IS_PRIMITIVE(*vp)) { str = js_DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, *vp, NULL); if (str) { JS_ReportErrorNumberUC(cx, js_GetErrorMessage, NULL, JSMSG_BAD_ITERATOR_RETURN, JSSTRING_CHARS(str), JSSTRING_CHARS(ATOM_TO_STRING(atom))); } goto bad; } } ok = JS_TRUE; out: if (obj) JS_POP_TEMP_ROOT(cx, &tvr); return ok; bad: ok = JS_FALSE; goto out; } static JSBool CallEnumeratorNext(JSContext *cx, JSObject *iterobj, uintN flags, jsval *rval) { JSObject *obj, *origobj; jsval state; JSBool foreach; jsid id; JSObject *obj2; JSBool cond; JSClass *clasp; JSExtendedClass *xclasp; JSProperty *prop; JSString *str; JS_ASSERT(flags & JSITER_ENUMERATE); JS_ASSERT(JSVAL_TO_PRIVATE(iterobj->slots[JSSLOT_CLASS]) == &js_IteratorClass); obj = JSVAL_TO_OBJECT(iterobj->slots[JSSLOT_PARENT]); origobj = JSVAL_TO_OBJECT(iterobj->slots[JSSLOT_PROTO]); state = iterobj->slots[JSSLOT_ITER_STATE]; if (JSVAL_IS_NULL(state)) goto stop; foreach = (flags & JSITER_FOREACH) != 0; #if JS_HAS_XML_SUPPORT /* * Treat an XML object specially only when it starts the prototype chain. * Otherwise we need to do the usual deleted and shadowed property checks. */ if (obj == origobj && OBJECT_IS_XML(cx, obj)) { if (foreach) { JSXMLObjectOps *xmlops = (JSXMLObjectOps *) obj->map->ops; if (!xmlops->enumerateValues(cx, obj, JSENUMERATE_NEXT, &state, &id, rval)) { return JS_FALSE; } } else { if (!OBJ_ENUMERATE(cx, obj, JSENUMERATE_NEXT, &state, &id)) return JS_FALSE; } iterobj->slots[JSSLOT_ITER_STATE] = state; if (JSVAL_IS_NULL(state)) goto stop; } else #endif { restart: if (!OBJ_ENUMERATE(cx, obj, JSENUMERATE_NEXT, &state, &id)) return JS_TRUE; iterobj->slots[JSSLOT_ITER_STATE] = state; if (JSVAL_IS_NULL(state)) { #if JS_HAS_XML_SUPPORT if (OBJECT_IS_XML(cx, obj)) { /* * We just finished enumerating an XML obj that is present on * the prototype chain of a non-XML origobj. Stop further * prototype chain searches because XML objects don't * enumerate prototypes. */ JS_ASSERT(origobj != obj); JS_ASSERT(!OBJECT_IS_XML(cx, origobj)); } else #endif { obj = OBJ_GET_PROTO(cx, obj); if (obj) { iterobj->slots[JSSLOT_PARENT] = OBJECT_TO_JSVAL(obj); if (!OBJ_ENUMERATE(cx, obj, JSENUMERATE_INIT, &state, NULL)) return JS_FALSE; iterobj->slots[JSSLOT_ITER_STATE] = state; if (!JSVAL_IS_NULL(state)) goto restart; } } goto stop; } /* Skip properties not in obj when looking from origobj. */ if (!OBJ_LOOKUP_PROPERTY(cx, origobj, id, &obj2, &prop)) return JS_FALSE; if (!prop) goto restart; OBJ_DROP_PROPERTY(cx, obj2, prop); /* * If the id was found in a prototype object or an unrelated object * (specifically, not in an inner object for obj), skip it. This step * means that all OBJ_LOOKUP_PROPERTY implementations must return an * object further along on the prototype chain, or else possibly an * object returned by the JSExtendedClass.outerObject optional hook. */ if (obj != obj2) { cond = JS_FALSE; clasp = OBJ_GET_CLASS(cx, obj2); if (clasp->flags & JSCLASS_IS_EXTENDED) { xclasp = (JSExtendedClass *) clasp; cond = xclasp->outerObject && xclasp->outerObject(cx, obj2) == obj; } if (!cond) goto restart; } if (foreach) { /* Get property querying the original object. */ if (!OBJ_GET_PROPERTY(cx, origobj, id, rval)) return JS_FALSE; } } if (foreach) { if (flags & JSITER_KEYVALUE) { if (!NewKeyValuePair(cx, id, *rval, rval)) return JS_FALSE; } } else { /* Make rval a string for uniformity and compatibility. */ if (JSID_IS_ATOM(id)) { *rval = ATOM_KEY(JSID_TO_ATOM(id)); } #if JS_HAS_XML_SUPPORT else if (JSID_IS_OBJECT(id)) { str = js_ValueToString(cx, OBJECT_JSID_TO_JSVAL(id)); if (!str) return JS_FALSE; *rval = STRING_TO_JSVAL(str); } #endif else { str = js_NumberToString(cx, (jsdouble)JSID_TO_INT(id)); if (!str) return JS_FALSE; *rval = STRING_TO_JSVAL(str); } } return JS_TRUE; stop: JS_ASSERT(iterobj->slots[JSSLOT_ITER_STATE] == JSVAL_NULL); *rval = JSVAL_HOLE; return JS_TRUE; } JSBool js_CallIteratorNext(JSContext *cx, JSObject *iterobj, jsval *rval) { uintN flags; /* Fast path for native iterators */ if (OBJ_GET_CLASS(cx, iterobj) == &js_IteratorClass) { flags = JSVAL_TO_INT(OBJ_GET_SLOT(cx, iterobj, JSSLOT_ITER_FLAGS)); if (flags & JSITER_ENUMERATE) return CallEnumeratorNext(cx, iterobj, flags, rval); /* * Call next directly as all the methods of the native iterator are * read-only and permanent. */ if (!IteratorNextImpl(cx, iterobj, rval)) return JS_FALSE; } else { jsid id = ATOM_TO_JSID(cx->runtime->atomState.nextAtom); if (!JS_GetMethodById(cx, iterobj, id, &iterobj, rval)) return JS_FALSE; if (!js_InternalCall(cx, iterobj, *rval, 0, NULL, rval)) { /* Check for StopIteration. */ if (!cx->throwing || JSVAL_IS_PRIMITIVE(cx->exception) || OBJ_GET_CLASS(cx, JSVAL_TO_OBJECT(cx->exception)) != &js_StopIterationClass) { return JS_FALSE; } /* Inline JS_ClearPendingException(cx). */ cx->throwing = JS_FALSE; cx->exception = JSVAL_VOID; *rval = JSVAL_HOLE; return JS_TRUE; } } return JS_TRUE; } static JSBool stopiter_hasInstance(JSContext *cx, JSObject *obj, jsval v, JSBool *bp) { *bp = !JSVAL_IS_PRIMITIVE(v) && OBJ_GET_CLASS(cx, JSVAL_TO_OBJECT(v)) == &js_StopIterationClass; return JS_TRUE; } JSClass js_StopIterationClass = { js_StopIteration_str, JSCLASS_HAS_CACHED_PROTO(JSProto_StopIteration), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, NULL, NULL, NULL, NULL, NULL, stopiter_hasInstance, NULL, NULL }; #if JS_HAS_GENERATORS static void generator_finalize(JSContext *cx, JSObject *obj) { JSGenerator *gen; gen = (JSGenerator *) JS_GetPrivate(cx, obj); if (gen) { /* * gen can be open on shutdown when close hooks are ignored or when * the embedding cancels scheduled close hooks. */ JS_ASSERT(gen->state == JSGEN_NEWBORN || gen->state == JSGEN_CLOSED || gen->state == JSGEN_OPEN); JS_free(cx, gen); } } static uint32 generator_mark(JSContext *cx, JSObject *obj, void *arg) { JSGenerator *gen; gen = (JSGenerator *) JS_GetPrivate(cx, obj); if (gen) { /* * We must mark argv[-2], as js_MarkStackFrame will not. Note that * js_MarkStackFrame will mark thisp (argv[-1]) and actual arguments, * plus any missing formals and local GC roots. */ JS_ASSERT(!JSVAL_IS_PRIMITIVE(gen->frame.argv[-2])); GC_MARK(cx, JSVAL_TO_GCTHING(gen->frame.argv[-2]), "generator"); js_MarkStackFrame(cx, &gen->frame); } return 0; } JSClass js_GeneratorClass = { js_Generator_str, JSCLASS_HAS_PRIVATE | JSCLASS_IS_ANONYMOUS | JSCLASS_HAS_CACHED_PROTO(JSProto_Generator), JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, generator_finalize, NULL, NULL, NULL, NULL, NULL, NULL, generator_mark, NULL }; /* * Called from the JSOP_GENERATOR case in the interpreter, with fp referring * to the frame by which the generator function was activated. Create a new * JSGenerator object, which contains its own JSStackFrame that we populate * from *fp. We know that upon return, the JSOP_GENERATOR opcode will return * from the activation in fp, so we can steal away fp->callobj and fp->argsobj * if they are non-null. */ JSObject * js_NewGenerator(JSContext *cx, JSStackFrame *fp) { JSObject *obj; uintN argc, nargs, nvars, depth, nslots; JSGenerator *gen; jsval *newsp; /* After the following return, failing control flow must goto bad. */ obj = js_NewObject(cx, &js_GeneratorClass, NULL, NULL); if (!obj) return NULL; /* Load and compute stack slot counts. */ argc = fp->argc; nargs = JS_MAX(argc, fp->fun->nargs); nvars = fp->nvars; depth = fp->script->depth; nslots = 2 + nargs + nvars + 2 * depth; /* Allocate obj's private data struct. */ gen = (JSGenerator *) JS_malloc(cx, sizeof(JSGenerator) + (nslots - 1) * sizeof(jsval)); if (!gen) goto bad; gen->obj = obj; /* Steal away objects reflecting fp and point them at gen->frame. */ gen->frame.callobj = fp->callobj; if (fp->callobj) { JS_SetPrivate(cx, fp->callobj, &gen->frame); fp->callobj = NULL; } gen->frame.argsobj = fp->argsobj; if (fp->argsobj) { JS_SetPrivate(cx, fp->argsobj, &gen->frame); fp->argsobj = NULL; } /* These two references can be shared with fp until it goes away. */ gen->frame.varobj = fp->varobj; gen->frame.thisp = fp->thisp; /* Copy call-invariant script and function references. */ gen->frame.script = fp->script; gen->frame.fun = fp->fun; /* Use newsp to carve space out of gen->stack. */ newsp = gen->stack; gen->arena.next = NULL; gen->arena.base = (jsuword) newsp; gen->arena.limit = gen->arena.avail = (jsuword) (newsp + nslots); #define COPY_STACK_ARRAY(vec,cnt,num) \ JS_BEGIN_MACRO \ gen->frame.cnt = cnt; \ gen->frame.vec = newsp; \ newsp += (num); \ memcpy(gen->frame.vec, fp->vec, (num) * sizeof(jsval)); \ JS_END_MACRO /* Copy argv, rval, and vars. */ *newsp++ = fp->argv[-2]; *newsp++ = fp->argv[-1]; COPY_STACK_ARRAY(argv, argc, nargs); gen->frame.rval = fp->rval; COPY_STACK_ARRAY(vars, nvars, nvars); #undef COPY_STACK_ARRAY /* Initialize or copy virtual machine state. */ gen->frame.down = NULL; gen->frame.annotation = NULL; gen->frame.scopeChain = fp->scopeChain; gen->frame.pc = fp->pc; /* Allocate generating pc and operand stack space. */ gen->frame.spbase = gen->frame.sp = newsp + depth; /* Copy remaining state (XXX sharp* and xml* should be local vars). */ gen->frame.sharpDepth = 0; gen->frame.sharpArray = NULL; gen->frame.flags = fp->flags | JSFRAME_GENERATOR; gen->frame.dormantNext = NULL; gen->frame.xmlNamespace = NULL; gen->frame.blockChain = NULL; /* Note that gen is newborn. */ gen->state = JSGEN_NEWBORN; if (!JS_SetPrivate(cx, obj, gen)) { JS_free(cx, gen); goto bad; } /* * Register with GC to ensure that suspended finally blocks will be * executed. */ js_RegisterGenerator(cx, gen); return obj; bad: cx->weakRoots.newborn[GCX_OBJECT] = NULL; return NULL; } typedef enum JSGeneratorOp { JSGENOP_NEXT, JSGENOP_SEND, JSGENOP_THROW, JSGENOP_CLOSE } JSGeneratorOp; /* * Start newborn or restart yielding generator and perform the requested * operation inside its frame. */ static JSBool SendToGenerator(JSContext *cx, JSGeneratorOp op, JSObject *obj, JSGenerator *gen, jsval arg, jsval *rval) { JSStackFrame *fp; jsval junk; JSArena *arena; JSBool ok; JS_ASSERT(gen->state == JSGEN_NEWBORN || gen->state == JSGEN_OPEN); switch (op) { case JSGENOP_NEXT: case JSGENOP_SEND: if (gen->state == JSGEN_OPEN) { /* * Store the argument to send as the result of the yield * expression. */ gen->frame.sp[-1] = arg; } gen->state = JSGEN_RUNNING; break; case JSGENOP_THROW: JS_SetPendingException(cx, arg); gen->state = JSGEN_RUNNING; break; default: JS_ASSERT(op == JSGENOP_CLOSE); JS_SetPendingException(cx, JSVAL_ARETURN); gen->state = JSGEN_CLOSING; break; } /* Extend the current stack pool with gen->arena. */ arena = cx->stackPool.current; JS_ASSERT(!arena->next); JS_ASSERT(!gen->arena.next); JS_ASSERT(cx->stackPool.current != &gen->arena); cx->stackPool.current = arena->next = &gen->arena; /* Push gen->frame around the interpreter activation. */ fp = cx->fp; cx->fp = &gen->frame; gen->frame.down = fp; ok = js_Interpret(cx, gen->frame.pc, &junk); cx->fp = fp; gen->frame.down = NULL; /* Retract the stack pool and sanitize gen->arena. */ JS_ASSERT(!gen->arena.next); JS_ASSERT(arena->next == &gen->arena); JS_ASSERT(cx->stackPool.current == &gen->arena); cx->stackPool.current = arena; arena->next = NULL; if (gen->frame.flags & JSFRAME_YIELDING) { /* Yield cannot fail, throw or be called on closing. */ JS_ASSERT(ok); JS_ASSERT(!cx->throwing); JS_ASSERT(gen->state == JSGEN_RUNNING); JS_ASSERT(op != JSGENOP_CLOSE); gen->frame.flags &= ~JSFRAME_YIELDING; gen->state = JSGEN_OPEN; *rval = gen->frame.rval; return JS_TRUE; } gen->state = JSGEN_CLOSED; if (ok) { /* Returned, explicitly or by falling off the end. */ if (op == JSGENOP_CLOSE) return JS_TRUE; return js_ThrowStopIteration(cx, obj); } /* * An error, silent termination by branch callback or an exception. * Propagate the condition to the caller. */ return JS_FALSE; } /* * Execute gen's close hook after the GC detects that the object has become * unreachable. */ JSBool js_CloseGeneratorObject(JSContext *cx, JSGenerator *gen) { /* We pass null as rval since SendToGenerator never uses it with CLOSE. */ return SendToGenerator(cx, JSGENOP_CLOSE, gen->obj, gen, JSVAL_VOID, NULL); } /* * Common subroutine of generator_(next|send|throw|close) methods. */ static JSBool generator_op(JSContext *cx, JSGeneratorOp op, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { JSGenerator *gen; JSString *str; jsval arg; if (!JS_InstanceOf(cx, obj, &js_GeneratorClass, argv)) return JS_FALSE; gen = (JSGenerator *) JS_GetPrivate(cx, obj); if (gen == NULL) { /* This happens when obj is the generator prototype. See bug 352885. */ goto closed_generator; } switch (gen->state) { case JSGEN_NEWBORN: switch (op) { case JSGENOP_NEXT: case JSGENOP_THROW: break; case JSGENOP_SEND: if (!JSVAL_IS_VOID(argv[0])) { str = js_DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, argv[0], NULL); if (str) { JS_ReportErrorNumberUC(cx, js_GetErrorMessage, NULL, JSMSG_BAD_GENERATOR_SEND, JSSTRING_CHARS(str)); } return JS_FALSE; } break; default: JS_ASSERT(op == JSGENOP_CLOSE); gen->state = JSGEN_CLOSED; return JS_TRUE; } break; case JSGEN_OPEN: break; case JSGEN_RUNNING: case JSGEN_CLOSING: str = js_DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, argv[-1], JS_GetFunctionId(gen->frame.fun)); if (str) { JS_ReportErrorNumberUC(cx, js_GetErrorMessage, NULL, JSMSG_NESTING_GENERATOR, JSSTRING_CHARS(str)); } return JS_FALSE; default: JS_ASSERT(gen->state == JSGEN_CLOSED); closed_generator: switch (op) { case JSGENOP_NEXT: case JSGENOP_SEND: return js_ThrowStopIteration(cx, obj); case JSGENOP_THROW: JS_SetPendingException(cx, argv[0]); return JS_FALSE; default: JS_ASSERT(op == JSGENOP_CLOSE); return JS_TRUE; } } arg = (op == JSGENOP_SEND || op == JSGENOP_THROW) ? argv[0] : JSVAL_VOID; if (!SendToGenerator(cx, op, obj, gen, arg, rval)) return JS_FALSE; return JS_TRUE; } static JSBool generator_send(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { return generator_op(cx, JSGENOP_SEND, obj, argc, argv, rval); } static JSBool generator_next(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { return generator_op(cx, JSGENOP_NEXT, obj, argc, argv, rval); } static JSBool generator_throw(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { return generator_op(cx, JSGENOP_THROW, obj, argc, argv, rval); } static JSBool generator_close(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { return generator_op(cx, JSGENOP_CLOSE, obj, argc, argv, rval); } static JSFunctionSpec generator_methods[] = { {js_iterator_str, iterator_self, 0,JSPROP_READONLY|JSPROP_PERMANENT,0}, {js_next_str, generator_next, 0,JSPROP_READONLY|JSPROP_PERMANENT,0}, {js_send_str, generator_send, 1,JSPROP_READONLY|JSPROP_PERMANENT,0}, {js_throw_str, generator_throw, 1,JSPROP_READONLY|JSPROP_PERMANENT,0}, {js_close_str, generator_close, 0,JSPROP_READONLY|JSPROP_PERMANENT,0}, {0,0,0,0,0} }; #endif /* JS_HAS_GENERATORS */ JSObject * js_InitIteratorClasses(JSContext *cx, JSObject *obj) { JSObject *proto, *stop; /* Idempotency required: we initialize several things, possibly lazily. */ if (!js_GetClassObject(cx, obj, JSProto_StopIteration, &stop)) return NULL; if (stop) return stop; proto = JS_InitClass(cx, obj, NULL, &js_IteratorClass, Iterator, 2, NULL, iterator_methods, NULL, NULL); if (!proto) return NULL; proto->slots[JSSLOT_ITER_STATE] = JSVAL_NULL; #if JS_HAS_GENERATORS /* Initialize the generator internals if configured. */ if (!JS_InitClass(cx, obj, NULL, &js_GeneratorClass, NULL, 0, NULL, generator_methods, NULL, NULL)) { return NULL; } #endif return JS_InitClass(cx, obj, NULL, &js_StopIterationClass, NULL, 0, NULL, NULL, NULL, NULL); }
30.625347
80
0.604181
[ "object" ]
0a4e47e083c33e34f9abcc21234749104605dfc5
561
h
C
PolyAbs.h
C-And-Cpp-Libraries/Triangulation
8b432a203f69992598c42fce3b2d6c8760006f17
[ "MIT" ]
4
2021-02-05T04:38:40.000Z
2022-01-13T04:55:42.000Z
PolyAbs.h
PavelNajman/Triangulation
8b432a203f69992598c42fce3b2d6c8760006f17
[ "MIT" ]
null
null
null
PolyAbs.h
PavelNajman/Triangulation
8b432a203f69992598c42fce3b2d6c8760006f17
[ "MIT" ]
2
2020-07-07T21:15:56.000Z
2022-01-11T12:45:48.000Z
#ifndef POLYABS_H_ #define POLYABS_H_ #include "PolyBase.h" namespace Triangulation { /** * \brief Performs non-linear triangulation of two image points by minimizing the sum of absolute values of the distances. */ class PolyAbs : public PolyBase { public: using PolyBase::PolyBase; using PolyBase::TriangulationBase::triangulate; private: std::vector<double> PreparePolyCoeffs(const PolyParams& params) const override; std::vector<double> EvaluateRootsCosts(const Roots& roots, const PolyParams& params) const override; }; } #endif /* POLYABS_H_ */
23.375
122
0.771836
[ "vector" ]
0a4e7b22448a952e783e1ffcd28dde4a9f4a4e25
12,560
h
C
B2G/gecko/layout/style/nsCSSRules.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/layout/style/nsCSSRules.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/layout/style/nsCSSRules.h
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ // vim:cindent:ts=2:et:sw=2: /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* rules in a CSS stylesheet other than style rules (e.g., @import rules) */ #ifndef nsCSSRules_h_ #define nsCSSRules_h_ #include "mozilla/Attributes.h" #include "mozilla/css/GroupRule.h" #include "mozilla/Preferences.h" #include "nsIDOMCSSFontFaceRule.h" #include "nsIDOMCSSMediaRule.h" #include "nsIDOMCSSMozDocumentRule.h" #include "nsIDOMCSSSupportsRule.h" #include "nsIDOMMozCSSKeyframeRule.h" #include "nsIDOMMozCSSKeyframesRule.h" #include "nsIDOMCSSStyleDeclaration.h" #include "nsICSSRuleList.h" #include "nsAutoPtr.h" #include "nsCSSProperty.h" #include "nsCSSValue.h" #include "nsIDOMCSSCharsetRule.h" #include "nsTArray.h" #include "nsDOMCSSDeclaration.h" #include "Declaration.h" namespace mozilla { namespace css { class StyleRule; } } class nsMediaList; namespace mozilla { namespace css { class MediaRule MOZ_FINAL : public GroupRule, public nsIDOMCSSMediaRule { public: MediaRule(); private: MediaRule(const MediaRule& aCopy); ~MediaRule(); public: NS_DECL_ISUPPORTS_INHERITED // nsIStyleRule methods #ifdef DEBUG virtual void List(FILE* out = stdout, int32_t aIndent = 0) const; #endif // Rule methods virtual void SetStyleSheet(nsCSSStyleSheet* aSheet); //override GroupRule virtual int32_t GetType() const; virtual already_AddRefed<Rule> Clone() const; virtual nsIDOMCSSRule* GetDOMRule() { return this; } virtual nsIDOMCSSRule* GetExistingDOMRule() { return this; } // nsIDOMCSSRule interface NS_DECL_NSIDOMCSSRULE // nsIDOMCSSMediaRule interface NS_DECL_NSIDOMCSSMEDIARULE // rest of GroupRule virtual bool UseForPresentation(nsPresContext* aPresContext, nsMediaQueryResultCacheKey& aKey); // @media rule methods nsresult SetMedia(nsMediaList* aMedia); virtual NS_MUST_OVERRIDE size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const; protected: nsRefPtr<nsMediaList> mMedia; }; class DocumentRule MOZ_FINAL : public GroupRule, public nsIDOMCSSMozDocumentRule { public: DocumentRule(); private: DocumentRule(const DocumentRule& aCopy); ~DocumentRule(); public: NS_DECL_ISUPPORTS_INHERITED // nsIStyleRule methods #ifdef DEBUG virtual void List(FILE* out = stdout, int32_t aIndent = 0) const; #endif // Rule methods virtual int32_t GetType() const; virtual already_AddRefed<Rule> Clone() const; virtual nsIDOMCSSRule* GetDOMRule() { return this; } virtual nsIDOMCSSRule* GetExistingDOMRule() { return this; } // nsIDOMCSSRule interface NS_DECL_NSIDOMCSSRULE // nsIDOMCSSMozDocumentRule interface NS_DECL_NSIDOMCSSMOZDOCUMENTRULE // rest of GroupRule virtual bool UseForPresentation(nsPresContext* aPresContext, nsMediaQueryResultCacheKey& aKey); enum Function { eURL, eURLPrefix, eDomain, eRegExp }; struct URL { Function func; nsCString url; URL *next; URL() : next(nullptr) {} URL(const URL& aOther) : func(aOther.func) , url(aOther.url) , next(aOther.next ? new URL(*aOther.next) : nullptr) { } ~URL(); }; void SetURLs(URL *aURLs) { mURLs = aURLs; } virtual NS_MUST_OVERRIDE size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const; protected: nsAutoPtr<URL> mURLs; // linked list of |struct URL| above. }; } // namespace css } // namespace mozilla // A nsCSSFontFaceStyleDecl is always embedded in a nsCSSFontFaceRule. class nsCSSFontFaceRule; class nsCSSFontFaceStyleDecl : public nsICSSDeclaration { public: NS_DECL_ISUPPORTS_INHERITED NS_DECL_NSIDOMCSSSTYLEDECLARATION NS_DECL_NSICSSDECLARATION nsCSSFontFaceStyleDecl() { SetIsDOMBinding(); } virtual nsINode *GetParentObject() MOZ_OVERRIDE; virtual void IndexedGetter(uint32_t aIndex, bool& aFound, nsAString& aPropName) MOZ_OVERRIDE; nsresult GetPropertyValue(nsCSSFontDesc aFontDescID, nsAString & aResult) const; virtual JSObject* WrapObject(JSContext *cx, JSObject *scope, bool *triedToWrap); protected: friend class nsCSSFontFaceRule; #define CSS_FONT_DESC(name_, method_) nsCSSValue m##method_; #include "nsCSSFontDescList.h" #undef CSS_FONT_DESC static nsCSSValue nsCSSFontFaceStyleDecl::* const Fields[]; inline nsCSSFontFaceRule* ContainingRule(); inline const nsCSSFontFaceRule* ContainingRule() const; private: // NOT TO BE IMPLEMENTED // This object cannot be allocated on its own, only as part of // nsCSSFontFaceRule. void* operator new(size_t size) CPP_THROW_NEW; }; class nsCSSFontFaceRule MOZ_FINAL : public mozilla::css::Rule, public nsIDOMCSSFontFaceRule { public: nsCSSFontFaceRule() {} nsCSSFontFaceRule(const nsCSSFontFaceRule& aCopy) // copy everything except our reference count : mozilla::css::Rule(aCopy), mDecl(aCopy.mDecl) {} NS_DECL_CYCLE_COLLECTING_ISUPPORTS NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(nsCSSFontFaceRule, mozilla::css::Rule) // nsIStyleRule methods #ifdef DEBUG virtual void List(FILE* out = stdout, int32_t aIndent = 0) const; #endif // Rule methods DECL_STYLE_RULE_INHERIT virtual int32_t GetType() const; virtual already_AddRefed<mozilla::css::Rule> Clone() const; // nsIDOMCSSRule interface NS_DECL_NSIDOMCSSRULE // nsIDOMCSSFontFaceRule interface NS_DECL_NSIDOMCSSFONTFACERULE void SetDesc(nsCSSFontDesc aDescID, nsCSSValue const & aValue); void GetDesc(nsCSSFontDesc aDescID, nsCSSValue & aValue); virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const MOZ_OVERRIDE; protected: friend class nsCSSFontFaceStyleDecl; nsCSSFontFaceStyleDecl mDecl; }; // nsFontFaceRuleContainer - used for associating sheet type with // specific @font-face rules struct nsFontFaceRuleContainer { nsRefPtr<nsCSSFontFaceRule> mRule; uint8_t mSheetType; }; inline nsCSSFontFaceRule* nsCSSFontFaceStyleDecl::ContainingRule() { return reinterpret_cast<nsCSSFontFaceRule*> (reinterpret_cast<char*>(this) - offsetof(nsCSSFontFaceRule, mDecl)); } inline const nsCSSFontFaceRule* nsCSSFontFaceStyleDecl::ContainingRule() const { return reinterpret_cast<const nsCSSFontFaceRule*> (reinterpret_cast<const char*>(this) - offsetof(nsCSSFontFaceRule, mDecl)); } namespace mozilla { namespace css { class CharsetRule MOZ_FINAL : public Rule, public nsIDOMCSSCharsetRule { public: CharsetRule(const nsAString& aEncoding); private: // For |Clone| CharsetRule(const CharsetRule& aCopy); ~CharsetRule() {} public: NS_DECL_ISUPPORTS DECL_STYLE_RULE_INHERIT // nsIStyleRule methods #ifdef DEBUG virtual void List(FILE* out = stdout, int32_t aIndent = 0) const; #endif // Rule methods virtual int32_t GetType() const; virtual already_AddRefed<Rule> Clone() const; // nsIDOMCSSRule interface NS_DECL_NSIDOMCSSRULE // nsIDOMCSSCharsetRule methods NS_IMETHOD GetEncoding(nsAString& aEncoding); NS_IMETHOD SetEncoding(const nsAString& aEncoding); virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const; private: nsString mEncoding; }; } // namespace css } // namespace mozilla class nsCSSKeyframeRule; class nsCSSKeyframeStyleDeclaration MOZ_FINAL : public nsDOMCSSDeclaration { public: nsCSSKeyframeStyleDeclaration(nsCSSKeyframeRule *aRule); virtual ~nsCSSKeyframeStyleDeclaration(); NS_IMETHOD GetParentRule(nsIDOMCSSRule **aParent) MOZ_OVERRIDE; void DropReference() { mRule = nullptr; } virtual mozilla::css::Declaration* GetCSSDeclaration(bool aAllocate) MOZ_OVERRIDE; virtual nsresult SetCSSDeclaration(mozilla::css::Declaration* aDecl) MOZ_OVERRIDE; virtual void GetCSSParsingEnvironment(CSSParsingEnvironment& aCSSParseEnv) MOZ_OVERRIDE; virtual nsIDocument* DocToUpdate() MOZ_OVERRIDE; NS_DECL_CYCLE_COLLECTING_ISUPPORTS NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS_AMBIGUOUS(nsCSSKeyframeStyleDeclaration, nsICSSDeclaration) virtual nsINode* GetParentObject(); protected: // This reference is not reference-counted. The rule object tells us // when it's about to go away. nsCSSKeyframeRule *mRule; }; class nsCSSKeyframeRule MOZ_FINAL : public mozilla::css::Rule, public nsIDOMMozCSSKeyframeRule { public: // WARNING: Steals the contents of aKeys *and* aDeclaration nsCSSKeyframeRule(nsTArray<float> aKeys, nsAutoPtr<mozilla::css::Declaration> aDeclaration) : mDeclaration(aDeclaration) { mKeys.SwapElements(aKeys); } private: nsCSSKeyframeRule(const nsCSSKeyframeRule& aCopy); ~nsCSSKeyframeRule(); public: NS_DECL_ISUPPORTS // nsIStyleRule methods #ifdef DEBUG virtual void List(FILE* out = stdout, int32_t aIndent = 0) const; #endif // Rule methods DECL_STYLE_RULE_INHERIT virtual int32_t GetType() const; virtual already_AddRefed<mozilla::css::Rule> Clone() const; // nsIDOMCSSRule interface NS_DECL_NSIDOMCSSRULE // nsIDOMMozCSSKeyframeRule interface NS_DECL_NSIDOMMOZCSSKEYFRAMERULE const nsTArray<float>& GetKeys() const { return mKeys; } mozilla::css::Declaration* Declaration() { return mDeclaration; } void ChangeDeclaration(mozilla::css::Declaration* aDeclaration); virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const MOZ_OVERRIDE; private: nsAutoTArray<float, 1> mKeys; nsAutoPtr<mozilla::css::Declaration> mDeclaration; // lazily created when needed: nsRefPtr<nsCSSKeyframeStyleDeclaration> mDOMDeclaration; }; class nsCSSKeyframesRule MOZ_FINAL : public mozilla::css::GroupRule, public nsIDOMMozCSSKeyframesRule { public: nsCSSKeyframesRule(const nsSubstring& aName) : mName(aName) { } private: nsCSSKeyframesRule(const nsCSSKeyframesRule& aCopy); ~nsCSSKeyframesRule(); public: NS_DECL_ISUPPORTS_INHERITED // nsIStyleRule methods #ifdef DEBUG virtual void List(FILE* out = stdout, int32_t aIndent = 0) const; #endif // Rule methods virtual int32_t GetType() const; virtual already_AddRefed<mozilla::css::Rule> Clone() const; virtual nsIDOMCSSRule* GetDOMRule() { return this; } virtual nsIDOMCSSRule* GetExistingDOMRule() { return this; } // nsIDOMCSSRule interface NS_DECL_NSIDOMCSSRULE // nsIDOMMozCSSKeyframesRule interface NS_DECL_NSIDOMMOZCSSKEYFRAMESRULE // rest of GroupRule virtual bool UseForPresentation(nsPresContext* aPresContext, nsMediaQueryResultCacheKey& aKey); const nsString& GetName() { return mName; } virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const MOZ_OVERRIDE; private: uint32_t FindRuleIndexForKey(const nsAString& aKey); nsString mName; }; namespace mozilla { class CSSSupportsRule : public css::GroupRule, public nsIDOMCSSSupportsRule { public: CSSSupportsRule(bool aConditionMet, const nsString& aCondition); CSSSupportsRule(const CSSSupportsRule& aCopy); // nsIStyleRule methods #ifdef DEBUG virtual void List(FILE* out = stdout, int32_t aIndent = 0) const; #endif // Rule methods virtual int32_t GetType() const; virtual already_AddRefed<mozilla::css::Rule> Clone() const; virtual bool UseForPresentation(nsPresContext* aPresContext, nsMediaQueryResultCacheKey& aKey); virtual nsIDOMCSSRule* GetDOMRule() { return this; } virtual nsIDOMCSSRule* GetExistingDOMRule() { return this; } NS_DECL_ISUPPORTS_INHERITED // nsIDOMCSSRule interface NS_DECL_NSIDOMCSSRULE // nsIDOMCSSSupportsRule interface NS_DECL_NSIDOMCSSSUPPORTSRULE virtual size_t SizeOfIncludingThis(nsMallocSizeOfFun aMallocSizeOf) const; static bool PrefEnabled() { return Preferences::GetBool("layout.css.supports-rule.enabled"); } protected: bool mUseGroup; nsString mCondition; }; } // namespace mozilla #endif /* !defined(nsCSSRules_h_) */
25.790554
95
0.727309
[ "object" ]
0a4f224ae1d53a25f1953f3d03542dadfe025f27
183
h
C
vector_tester.h
AmeyaShahane/Stocky
961cf0ae151d0cbdcdc95c410824a99bf2e3d758
[ "Apache-2.0" ]
null
null
null
vector_tester.h
AmeyaShahane/Stocky
961cf0ae151d0cbdcdc95c410824a99bf2e3d758
[ "Apache-2.0" ]
null
null
null
vector_tester.h
AmeyaShahane/Stocky
961cf0ae151d0cbdcdc95c410824a99bf2e3d758
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> #include <vector> /* String method for unit testing sub vectors */ class vector_tester { public: std::string stock_changes(std::vector<double> x); };
15.25
50
0.73224
[ "vector" ]
f701cee8c02f7973fc8d40e323cc3b52e891302b
2,254
c
C
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/sse2-extract-1.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/sse2-extract-1.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/sse2-extract-1.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
/* { dg-do run } */ /* { dg-options "-O2 -msse2" } */ /* { dg-require-effective-target sse2_runtime } */ extern void abort (void); typedef unsigned long long uint64_t; #define vector(elcount, type) \ __attribute__((vector_size((elcount)*sizeof(type)))) type #define FN(elcount, type, idx) \ __attribute__((noinline, noclone)) \ type f##type##elcount##_##idx (vector (elcount, type) x) { return x[idx] + 1; } #define T2(elcount, type) \ H (elcount, type) \ F (elcount, type, 0) \ F (elcount, type, 1) #define T4(elcount, type) \ T2 (elcount, type) \ F (elcount, type, 2) \ F (elcount, type, 3) #define T8(elcount, type) \ T4 (elcount, type) \ F (elcount, type, 4) \ F (elcount, type, 5) \ F (elcount, type, 6) \ F (elcount, type, 7) #define T16(elcount, type) \ T8 (elcount, type) \ F (elcount, type, 8) \ F (elcount, type, 9) \ F (elcount, type, 10) \ F (elcount, type, 11) \ F (elcount, type, 12) \ F (elcount, type, 13) \ F (elcount, type, 14) \ F (elcount, type, 15) #define T32(elcount, type) \ T16 (elcount, type) \ F (elcount, type, 16) \ F (elcount, type, 17) \ F (elcount, type, 18) \ F (elcount, type, 19) \ F (elcount, type, 20) \ F (elcount, type, 21) \ F (elcount, type, 22) \ F (elcount, type, 23) \ F (elcount, type, 24) \ F (elcount, type, 25) \ F (elcount, type, 26) \ F (elcount, type, 27) \ F (elcount, type, 28) \ F (elcount, type, 29) \ F (elcount, type, 30) \ F (elcount, type, 31) #define TESTS_SSE2 \ T2 (2, double) E \ T2 (2, uint64_t) E \ T4 (4, float) E \ T4 (4, int) E \ T8 (8, short) E \ T16 (16, char) E #define TESTS_AVX \ T4 (4, double) E \ T4 (4, uint64_t) E \ T8 (8, float) E \ T8 (8, int) E \ T16 (16, short) E \ T32 (32, char) E #ifdef __AVX__ #define TESTS TESTS_SSE2 TESTS_AVX #else #define TESTS TESTS_SSE2 #endif #define F FN #define H(elcount, type) #define E TESTS int main () { #undef F #undef H #undef E #define H(elcount, type) \ vector (elcount, type) v##type##elcount = { #define E }; #define F(elcount, type, idx) idx + 1, TESTS #undef F #undef H #undef E #define H(elcount, type) #define E #define F(elcount, type, idx) \ if (f##type##elcount##_##idx (v##type##elcount) != idx + 2) \ abort (); TESTS return 0; }
21.883495
79
0.602484
[ "vector" ]
f701ff5a3d4cf510c4a6fcf37a0e484d73bff8c1
8,147
h
C
ibtk/include/ibtk/CoarseFineBoundaryRefinePatchStrategy.h
akashdhruv/IBAMR
a2b47946d795fb5a40c181b43e44a6ec387585a9
[ "BSD-3-Clause" ]
264
2015-01-04T12:11:02.000Z
2022-03-31T13:10:37.000Z
ibtk/include/ibtk/CoarseFineBoundaryRefinePatchStrategy.h
akashdhruv/IBAMR
a2b47946d795fb5a40c181b43e44a6ec387585a9
[ "BSD-3-Clause" ]
1,057
2015-04-27T04:27:57.000Z
2022-03-31T13:14:59.000Z
ibtk/include/ibtk/CoarseFineBoundaryRefinePatchStrategy.h
drwells/IBAMR
0ceda3873405a35da4888c99e7d2b24d132f9071
[ "BSD-3-Clause" ]
126
2015-02-13T15:36:02.000Z
2022-03-27T21:59:50.000Z
// --------------------------------------------------------------------- // // Copyright (c) 2011 - 2020 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- /////////////////////////////// INCLUDE GUARD //////////////////////////////// #ifndef included_IBTK_CoarseFineBoundaryRefinePatchStrategy #define included_IBTK_CoarseFineBoundaryRefinePatchStrategy /////////////////////////////// INCLUDES ///////////////////////////////////// #include <ibtk/config.h> #include "Box.h" #include "ComponentSelector.h" #include "IntVector.h" #include "RefinePatchStrategy.h" #include <set> namespace SAMRAI { namespace hier { template <int DIM> class Patch; template <int DIM> class PatchHierarchy; } // namespace hier namespace tbox { template <class TYPE> class Pointer; } // namespace tbox } // namespace SAMRAI /////////////////////////////// CLASS DEFINITION ///////////////////////////// namespace IBTK { /*! * \brief Class CoarseFineBoundaryRefinePatchStrategy is a subclass of the * abstract base class SAMRAI::xfer::RefinePatchStrategy that extends the * functionality of SAMRAI::xfer::RefinePatchStrategy to facilitate the * implementation of coarse-fine interface discretizations. */ class CoarseFineBoundaryRefinePatchStrategy : public SAMRAI::xfer::RefinePatchStrategy<NDIM> { public: /*! * \brief Constructor. */ CoarseFineBoundaryRefinePatchStrategy() = default; /*! * \brief Destructor. */ virtual ~CoarseFineBoundaryRefinePatchStrategy() = default; /*! * \name SAMRAI::xfer::RefinePatchStrategy interface. */ //\{ /*! * Function to set data associated with the given list of patch data indices * at patch boundaries that intersect the physical domain boundary. The * patch data components set in this routine correspond to the "scratch" * components specified in calls to the registerRefine() function in the * SAMRAI::xfer::RefineAlgorithm class. * * \param patch Patch on which to fill boundary data. * \param fill_time Double simulation time for boundary filling. * \param ghost_width_to_fill Integer vector describing maximum ghost width to fill over *all *registered scratch components. */ void setPhysicalBoundaryConditions(SAMRAI::hier::Patch<NDIM>& patch, double fill_time, const SAMRAI::hier::IntVector<NDIM>& ghost_width_to_fill) override = 0; /*! * Function to return maximum stencil width needed over user-defined data * interpolation operations. This is needed to determine the correct * interpolation data dependencies. */ SAMRAI::hier::IntVector<NDIM> getRefineOpStencilWidth() const override = 0; /*! * Function to perform user-defined preprocess data refine operations. This * member function is called before standard refine operations (expressed * using concrete subclasses of the SAMRAI::xfer::RefineOperator base * class). The preprocess function must refine data from the scratch * components of the coarse patch into the scratch components of the fine * patch on the specified fine box region. Recall that the scratch * components are specified in calls to the registerRefine() function in the * SAMRAI::xfer::RefineAlgorithm class. * * \param fine Fine patch containing destination data. * \param coarse Coarse patch containing source data. * \param fine_box Box region on fine patch into which data is refined. * \param ratio Integer vector containing ratio relating index space between coarse and *fine *patches. */ void preprocessRefine(SAMRAI::hier::Patch<NDIM>& fine, const SAMRAI::hier::Patch<NDIM>& coarse, const SAMRAI::hier::Box<NDIM>& fine_box, const SAMRAI::hier::IntVector<NDIM>& ratio) override = 0; /*! * Function to perform user-defined postprocess data refine operations. * This member function is called after standard refine operations * (expressed using concrete subclasses of the SAMRAI::xfer::RefineOperator * base class). The postprocess function must refine data from the scratch * components of the coarse patch into the scratch components of the fine * patch on the specified fine box region. Recall that the scratch * components are specified in calls to the registerRefine() function in the * SAMRAI::xfer::RefineAlgorithm class. * * \param fine Fine patch containing destination data. * \param coarse Coarse patch containing source data. * \param fine_box Box region on fine patch into which data is refined. * \param ratio Integer vector containing ratio relating index space between coarse and *fine *patches. */ void postprocessRefine(SAMRAI::hier::Patch<NDIM>& fine, const SAMRAI::hier::Patch<NDIM>& coarse, const SAMRAI::hier::Box<NDIM>& fine_box, const SAMRAI::hier::IntVector<NDIM>& ratio) override = 0; //\} /*! * \name Extension of SAMRAI::xfer::RefinePatchStrategy interface to support more * complex coarse-fine interface discretizations. */ //\{ /*! * Whether or not to employ a consistent interpolation scheme at "Type 2" * coarse-fine interface ghost cells. * * \note This subclasses may choose not to support a consistent "Type 2" * coarse-fine interface ghost cell interpolation scheme. */ virtual void setConsistentInterpolationScheme(bool consistent_type_2_bdry) = 0; /*! * \brief Reset the patch data index operated upon by this class. */ virtual void setPatchDataIndex(int patch_data_index) = 0; /*! * \brief Reset the patch data indices operated upon by this class. */ virtual void setPatchDataIndices(const std::set<int>& patch_data_indices) = 0; /*! * \brief Reset the patch data indices operated upon by this class. */ virtual void setPatchDataIndices(const SAMRAI::hier::ComponentSelector& patch_data_indices) = 0; /*! * Set the patch hierarchy used in constructing coarse-fine interface * boundary boxes. */ virtual void setPatchHierarchy(SAMRAI::tbox::Pointer<SAMRAI::hier::PatchHierarchy<NDIM> > hierarchy) = 0; /*! * Clear the patch hierarchy used in constructing coarse-fine interface * boundary boxes. */ virtual void clearPatchHierarchy() = 0; /*! * Compute the normal extension of fine data at coarse-fine interfaces. */ virtual void computeNormalExtension(SAMRAI::hier::Patch<NDIM>& patch, const SAMRAI::hier::IntVector<NDIM>& ratio, const SAMRAI::hier::IntVector<NDIM>& ghost_width_to_fill) = 0; //\} protected: private: /*! * \brief Copy constructor. * * \note This constructor is not implemented and should not be used. * * \param from The value to copy to this object. */ CoarseFineBoundaryRefinePatchStrategy(const CoarseFineBoundaryRefinePatchStrategy& from) = delete; /*! * \brief Assignment operator. * * \note This operator is not implemented and should not be used. * * \param that The value to assign to this object. * * \return A reference to this object. */ CoarseFineBoundaryRefinePatchStrategy& operator=(const CoarseFineBoundaryRefinePatchStrategy& that) = delete; }; } // namespace IBTK ////////////////////////////////////////////////////////////////////////////// #endif //#ifndef included_IBTK_CoarseFineBoundaryRefinePatchStrategy
36.698198
113
0.641586
[ "object", "vector" ]
f70537b41dd94bba890bcef4876ed239858b39d2
1,435
h
C
base/trace_event/process_memory_dump.h
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/trace_event/process_memory_dump.h
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/trace_event/process_memory_dump.h
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TRACE_EVENT_PROCESS_MEMORY_DUMP_H_ #define BASE_TRACE_EVENT_PROCESS_MEMORY_DUMP_H_ #include "base/base_export.h" #include "base/trace_event/process_memory_totals.h" namespace base { namespace trace_event { class ConvertableToTraceFormat; // ProcessMemoryDump is as a strongly typed container which enforces the data // model for each memory dump point and holds the dumps produced by the // MemoryDumpProvider(s) for a specific process. // At trace generation time (i.e. when AsValue() is called), ProcessMemoryDump // will compose a key-value dictionary of the various dumps obtained at trace // dump point time. class BASE_EXPORT ProcessMemoryDump { public: ProcessMemoryDump(); ~ProcessMemoryDump(); // Called at trace generation time to populate the TracedValue. void AsValueInto(TracedValue* value) const; ProcessMemoryTotals* process_totals() { return &process_totals_; } bool has_process_totals() const { return has_process_totals_; } void set_has_process_totals() { has_process_totals_ = true; } private: ProcessMemoryTotals process_totals_; bool has_process_totals_; DISALLOW_COPY_AND_ASSIGN(ProcessMemoryDump); }; } // namespace trace_event } // namespace base #endif // BASE_TRACE_EVENT_PROCESS_MEMORY_DUMP_H_
31.888889
78
0.789547
[ "model" ]
f71414f3b0d3de750e12d6a93332d3c4f3de04eb
3,396
h
C
src/graphics/tile_batch.h
pandepic/PandaSDL
5e57859ea4b3870926428439b1e4c4b90e6d4cd9
[ "MIT" ]
3
2020-09-02T00:13:23.000Z
2021-08-14T23:13:11.000Z
src/graphics/tile_batch.h
pandepic/PandaSDL
5e57859ea4b3870926428439b1e4c4b90e6d4cd9
[ "MIT" ]
null
null
null
src/graphics/tile_batch.h
pandepic/PandaSDL
5e57859ea4b3870926428439b1e4c4b90e6d4cd9
[ "MIT" ]
1
2021-06-17T05:46:19.000Z
2021-06-17T05:46:19.000Z
#ifndef __pandasdl_tilebatch_h__ #define __pandasdl_tilebatch_h__ #include "../../lib_include/GLEW/glew.h" #include <GL/gl.h> #include "../../lib_include/glm/glm.hpp" #include "../../lib_include/glm/gtc/type_ptr.hpp" #include "../general/game.h" #include "texture_2D.h" #include "shader.h" #include "../math/vector2.h" #include "graphics_platform_opengl.h" namespace PandaSDL { /* On an empty tile X and Y will both be 255, this will discard the fragment in the shader R = atlas X co-ord G = atlas Y co-ord B = reserved for animation data A = free */ struct TileTextureData { unsigned char X; unsigned char Y; unsigned char AnimationIndex; }; struct TileBatchLayer { bool IsBelow; std::shared_ptr<PandaSDL::Texture2D> DataTexture; }; class TileBatch { public: TileBatch(); ~TileBatch(); std::vector<PandaSDL::TileBatchLayer> Layers; std::shared_ptr<PandaSDL::Texture2D> AtlasTexture; void BeginBuild( unsigned int width, unsigned int height, unsigned int tileWidth, unsigned int tileHeight, std::shared_ptr<PandaSDL::Texture2D> atlasTexture, std::shared_ptr<Shader> tileShader = DefaultTileShader); void SetTileAtPosition(unsigned int posx, unsigned int posy, unsigned char x, unsigned char y); void SetTileAtPosition(unsigned int posx, unsigned int posy, unsigned int tileIndex); void SetTileAtIndex(unsigned int index, unsigned char x, unsigned char y); void SetTileAtIndex(unsigned int index, unsigned int tileIndex); void EndLayer(bool below); void EndBuild(bool below = true); void Draw(PandaSDL::Vector2 position, bool below, float scale = 1.0f); unsigned int GetWidth(); unsigned int GetHeight(); static std::shared_ptr<PandaSDL::Shader> DefaultTileShader; static std::string DefaultTileShaderVertexCode; static std::string DefaultTileShaderFragmentCode; static bool DefaultShaderInitialised; protected: bool _setup; bool _currentLayerEnded; unsigned int _width, _height; unsigned int _tileWidth, _tileHeight; unsigned int _tilesheetTilesWidth, _tilesheetTilesHeight; std::unique_ptr<VertexArrayObject> _vao; std::shared_ptr<VertexBufferObject> _vbo; std::shared_ptr<Shader> _tileShader; float _tileScale; glm::vec2 _tileSize, _inverseTileSize; glm::vec2 _viewportSize, _scaledViewportSize; glm::vec2 _inverseSpriteTextureSize; TileTextureData* _dataArray; bool _dataAllocated; float _templateVertexBuffer[PANDASDL_QUAD_VERTEX_FLOAT_COUNT]; void Setup(); void CheckDefaultShader(); void ClearData(); }; } #endif
33.96
107
0.567138
[ "vector" ]
f714cd4b6c5d2451ca40e49015d1abb7488d73cc
2,872
h
C
src/core/biology_module/grow_divide.h
geektoni/biodynamo
09e3673043a7b1888b8e8a47c7b98a393b9d9d29
[ "Apache-2.0" ]
null
null
null
src/core/biology_module/grow_divide.h
geektoni/biodynamo
09e3673043a7b1888b8e8a47c7b98a393b9d9d29
[ "Apache-2.0" ]
null
null
null
src/core/biology_module/grow_divide.h
geektoni/biodynamo
09e3673043a7b1888b8e8a47c7b98a393b9d9d29
[ "Apache-2.0" ]
null
null
null
// ----------------------------------------------------------------------------- // // Copyright (C) The BioDynaMo Project. // 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. // // See the LICENSE file distributed with this work for details. // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. // // ----------------------------------------------------------------------------- #ifndef CORE_BIOLOGY_MODULE_GROW_DIVIDE_H_ #define CORE_BIOLOGY_MODULE_GROW_DIVIDE_H_ #include "core/biology_module/biology_module.h" #include "core/event/cell_division_event.h" #include "core/sim_object/cell.h" #include "core/util/log.h" #include "core/util/root.h" namespace bdm { /// This biology module grows the simulation object until the diameter reaches /// the specified threshold and divides the object afterwards. struct GrowDivide : public BaseBiologyModule { GrowDivide() : BaseBiologyModule(gAllEventIds) {} GrowDivide(double threshold, double growth_rate, std::initializer_list<EventId> event_list) : BaseBiologyModule(event_list), threshold_(threshold), growth_rate_(growth_rate) {} GrowDivide(const Event& event, BaseBiologyModule* other, uint64_t new_oid = 0) : BaseBiologyModule(event, other, new_oid) { if (GrowDivide* gdbm = dynamic_cast<GrowDivide*>(other)) { threshold_ = gdbm->threshold_; growth_rate_ = gdbm->growth_rate_; } else { Log::Fatal("GrowDivide::EventConstructor", "other was not of type GrowDivide"); } } /// Create a new instance of this object using the default constructor. BaseBiologyModule* GetInstance(const Event& event, BaseBiologyModule* other, uint64_t new_oid = 0) const override { return new GrowDivide(event, other, new_oid); } /// Create a copy of this biology module. BaseBiologyModule* GetCopy() const override { return new GrowDivide(*this); } /// Default event handler (exising biology module won't be modified on /// any event) void EventHandler(const Event& event, BaseBiologyModule* other1, BaseBiologyModule* other2 = nullptr) override { BaseBiologyModule::EventHandler(event, other1, other2); } void Run(SimObject* so) override { if (Cell* cell = dynamic_cast<Cell*>(so)) { if (cell->GetDiameter() <= threshold_) { cell->ChangeVolume(growth_rate_); } else { cell->Divide(); } } else { Log::Fatal("GrowDivide::Run", "SimObject is not a Cell"); } } private: BDM_CLASS_DEF_OVERRIDE(GrowDivide, 1); double threshold_ = 40; double growth_rate_ = 300; }; } // namespace bdm #endif // CORE_BIOLOGY_MODULE_GROW_DIVIDE_H_
34.190476
80
0.65773
[ "object" ]
f71a97571725daa795b45e1d855b26ff5a677dcc
11,186
h
C
Source/Urho3D/Resource/JSONArchive.h
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
441
2018-12-26T14:50:23.000Z
2021-11-05T03:13:27.000Z
Source/Urho3D/Resource/JSONArchive.h
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
221
2018-12-29T17:40:23.000Z
2021-11-06T21:41:55.000Z
Source/Urho3D/Resource/JSONArchive.h
vinhig/rbfx
884de45c623d591f346a2abd5e52edaa84bcc137
[ "MIT" ]
101
2018-12-29T13:08:10.000Z
2021-11-02T09:58:37.000Z
// // Copyright (c) 2017-2020 the rbfx project. // // 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. // #pragma once #include "../IO/Archive.h" #include "../Resource/JSONFile.h" #include "../Resource/JSONValue.h" namespace Urho3D { /// Return whether the block type should be serialized as JSON array. inline bool IsArchiveBlockJSONArray(ArchiveBlockType type) { return type == ArchiveBlockType::Array || type == ArchiveBlockType::Sequential; } /// Return whether the block type should be serialized as JSON object. inline bool IsArchiveBlockJSONObject(ArchiveBlockType type) { return type == ArchiveBlockType::Map || type == ArchiveBlockType::Unordered; } /// Return whether the block type matches JSONValue type. inline bool IsArchiveBlockTypeMatching(const JSONValue& value, ArchiveBlockType type) { return IsArchiveBlockJSONArray(type) && (value.IsArray() || value.IsNull()) || IsArchiveBlockJSONObject(type) && (value.IsObject() || value.IsNull()); } /// Base archive for JSON serialization. template <class T, bool IsInputBool> class JSONArchiveBase : public ArchiveBaseT<IsInputBool, true> { public: /// Get context. Context* GetContext() final { return context_; } /// Return name of the archive. ea::string_view GetName() const final { return jsonFile_ ? jsonFile_->GetName() : ""; } /// Whether the unordered element access is supported for Unordered blocks. bool IsUnorderedSupportedNow() const final { return !stack_.empty() && stack_.back().GetType() == ArchiveBlockType::Unordered; } /// Return current string stack. ea::string GetCurrentStackString() final { ea::string result; for (const Block& block : stack_) { if (!result.empty()) result += "/"; result += ea::string{ block.GetName() }; } return result; } protected: /// Construct from context and optional file. explicit JSONArchiveBase(Context* context, const JSONFile* jsonFile) : context_(context) , jsonFile_(jsonFile) { } /// Block type. using Block = T; /// Get current block. Block& GetCurrentBlock() { return stack_.back(); } /// Context. Context* context_{}; /// Blocks stack. ea::vector<Block> stack_; private: /// JSON file. const JSONFile* jsonFile_{}; }; /// JSON output archive block. Internal. struct JSONOutputArchiveBlock { public: /// Construct. JSONOutputArchiveBlock(const char* name, ArchiveBlockType type, JSONValue* blockValue, unsigned sizeHint); /// Get block name. ea::string_view GetName() const { return name_; } /// Return block type. ArchiveBlockType GetType() const { return type_; } /// Set element key. bool SetElementKey(ArchiveBase& archive, ea::string key); /// Create element in the block. JSONValue* CreateElement(ArchiveBase& archive, const char* elementName); /// Close block. bool Close(ArchiveBase& archive); private: /// Block name. ea::string_view name_{}; /// Block type. ArchiveBlockType type_{}; /// Block value. JSONValue* blockValue_; /// Expected block size (for arrays and maps). unsigned expectedElementCount_{ M_MAX_UNSIGNED }; /// Number of elements in block. unsigned numElements_{}; /// Key of the next created element (for Map blocks). ea::string elementKey_; /// Whether the key is set. bool keySet_{}; }; class URHO3D_API JSONOutputArchive : public JSONArchiveBase<JSONOutputArchiveBlock, false> { public: /// Base type. using Base = JSONArchiveBase<JSONOutputArchiveBlock, false>; /// Construct from element. JSONOutputArchive(Context* context, JSONValue& value, JSONFile* jsonFile = nullptr) : Base(context, jsonFile) , rootValue_(value) { } /// Construct from file. explicit JSONOutputArchive(JSONFile* jsonFile) : Base(jsonFile->GetContext(), jsonFile) , rootValue_(jsonFile->GetRoot()) {} /// Begin archive block. bool BeginBlock(const char* name, unsigned& sizeHint, bool safe, ArchiveBlockType type) final; /// End archive block. bool EndBlock() final; /// Serialize string key. Used with Map block only. bool SerializeKey(ea::string& key) final; /// Serialize unsigned integer key. Used with Map block only. bool SerializeKey(unsigned& key) final; /// Serialize bool. bool Serialize(const char* name, bool& value) final; /// Serialize signed char. bool Serialize(const char* name, signed char& value) final; /// Serialize unsigned char. bool Serialize(const char* name, unsigned char& value) final; /// Serialize signed short. bool Serialize(const char* name, short& value) final; /// Serialize unsigned short. bool Serialize(const char* name, unsigned short& value) final; /// Serialize signed int. bool Serialize(const char* name, int& value) final; /// Serialize unsigned int. bool Serialize(const char* name, unsigned int& value) final; /// Serialize signed long. bool Serialize(const char* name, long long& value) final; /// Serialize unsigned long. bool Serialize(const char* name, unsigned long long& value) final; /// Serialize float. bool Serialize(const char* name, float& value) final; /// Serialize double. bool Serialize(const char* name, double& value) final; /// Serialize string. bool Serialize(const char* name, ea::string& value) final; /// Serialize bytes. Size is not encoded and should be provided externally! bool SerializeBytes(const char* name, void* bytes, unsigned size) final; /// Serialize Variable Length Encoded unsigned integer, up to 29 significant bits. bool SerializeVLE(const char* name, unsigned& value) final; private: /// Check EOF. bool CheckEOF(const char* elementName, const char* debugName); /// Check EOF and root block. bool CheckEOFAndRoot(const char* elementName, const char* debugName); /// Serialize any JSON value. bool CreateElement(const char* name, const JSONValue& value); /// Temporary string. ea::string tempString_; /// Root value. JSONValue& rootValue_; }; /// Archive stack frame helper. struct JSONInputArchiveBlock { public: /// Construct valid. JSONInputArchiveBlock(const char* name, ArchiveBlockType type, const JSONValue* value); /// Return name. const ea::string_view GetName() const { return name_; } /// Return block type. ArchiveBlockType GetType() const { return type_; } /// Return size hint. unsigned GetSizeHint() const { return value_->Size(); } /// Return current child's key. bool ReadCurrentKey(ArchiveBase& archive, ea::string& key); /// Read current child and move to the next one. const JSONValue* ReadElement(ArchiveBase& archive, const char* elementName, const ArchiveBlockType* elementBlockType); private: /// Debug block name. ea::string_view name_{}; /// Frame type. ArchiveBlockType type_{}; /// Frame base value. const JSONValue* value_{}; /// Next array index (for array frames). unsigned nextElementIndex_{}; /// Next map element iterator (for map frames). JSONObject::const_iterator nextMapElementIterator_{}; /// Whether the key was read. bool keyRead_{}; }; class URHO3D_API JSONInputArchive : public JSONArchiveBase<JSONInputArchiveBlock, true> { public: /// Base type. using Base = JSONArchiveBase<JSONInputArchiveBlock, true>; /// Construct from element. JSONInputArchive(Context* context, const JSONValue& value, const JSONFile* jsonFile = nullptr) : Base(context, jsonFile) , rootValue_(value) { } /// Construct from file. explicit JSONInputArchive(const JSONFile* jsonFile) : Base(jsonFile->GetContext(), jsonFile) , rootValue_(jsonFile->GetRoot()) {} /// Begin archive block. bool BeginBlock(const char* name, unsigned& sizeHint, bool safe, ArchiveBlockType type) final; /// End archive block. bool EndBlock() final; /// Serialize string key. Used with Map block only. bool SerializeKey(ea::string& key) final; /// Serialize unsigned integer key. Used with Map block only. bool SerializeKey(unsigned& key) final; /// Serialize bool. bool Serialize(const char* name, bool& value) final; /// Serialize signed char. bool Serialize(const char* name, signed char& value) final; /// Serialize unsigned char. bool Serialize(const char* name, unsigned char& value) final; /// Serialize signed short. bool Serialize(const char* name, short& value) final; /// Serialize unsigned short. bool Serialize(const char* name, unsigned short& value) final; /// Serialize signed int. bool Serialize(const char* name, int& value) final; /// Serialize unsigned int. bool Serialize(const char* name, unsigned int& value) final; /// Serialize signed long. bool Serialize(const char* name, long long& value) final; /// Serialize unsigned long. bool Serialize(const char* name, unsigned long long& value) final; /// Serialize float. bool Serialize(const char* name, float& value) final; /// Serialize double. bool Serialize(const char* name, double& value) final; /// Serialize string. bool Serialize(const char* name, ea::string& value) final; /// Serialize bytes. Size is not encoded and should be provided externally! bool SerializeBytes(const char* name, void* bytes, unsigned size) final; /// Serialize Variable Length Encoded unsigned integer, up to 29 significant bits. bool SerializeVLE(const char* name, unsigned& value) final; private: /// Check EOF. bool CheckEOF(const char* elementName, const char* debugName); /// Check EOF and root block. bool CheckEOFAndRoot(const char* elementName, const char* debugName); /// Deserialize JSONValue. const JSONValue* ReadElement(const char* name); /// Temporary buffer. ea::vector<unsigned char> tempBuffer_; /// Root value. const JSONValue& rootValue_; }; }
36.436482
142
0.689165
[ "object", "vector" ]
f71fb107b19afb8e390a8534e48fd0793a26f98c
19,394
c
C
polygon.c
ricofehr/engine
dd87da538cbfa6773f5468285d06704d6e7f66a6
[ "MIT" ]
null
null
null
polygon.c
ricofehr/engine
dd87da538cbfa6773f5468285d06704d6e7f66a6
[ "MIT" ]
null
null
null
polygon.c
ricofehr/engine
dd87da538cbfa6773f5468285d06704d6e7f66a6
[ "MIT" ]
null
null
null
/* * Manage polygons object: init, transforms, collisions, ... * @author Eric Fehr (ricofehr@nextdeploy.io, @github: ricofehr) */ #include "polygon.h" #include "loader.h" #include <unistd.h> #include <time.h> /* Program Global vars */ int cnt_cubes = 64; int mode_grid = 0; struct polygon *poly_head = NULL; /* Polygon global vars */ static struct vector *init_trans; static struct vector *init_vartrans; static int is_matrix = 0; #define INDPOL_UNIVERSE 0 /* Default coordinates for the 6 faces of a cube */ static GLfloat cube[6][16] = { {-0.5f, 1.0f, -0.5f, 1.0f, 0.5f, 1.0f, -0.5f, 1.0f, 0.5f, 0.0f, -0.5f, 1.0f, -0.5f, 0.0f, -0.5f, 1.0f}, {-0.5f, 1.0f, 0.5f, 1.0f, 0.5f, 1.0f, 0.5f, 1.0f, 0.5f, 0.0f, 0.5f, 1.0f, -0.5f, 0.0f, 0.5f, 1.0f}, {0.5f, 1.0f, -0.5f, 1.0f, 0.5f, 1.0f, 0.5f, 1.0f, 0.5f, 0.0f, 0.5f, 1.0f, 0.5f, 0.0f, -0.5f, 1.0f}, {-0.5f, 1.0f, -0.5f, 1.0f, -0.5f, 1.0f, 0.5f, 1.0f, -0.5f, 0.0f, 0.5f, 1.0f, -0.5f, 0.0f, -0.5f, 1.0f}, {-0.5f, 1.0f, -0.5f, 1.0f, 0.5, 1.0f, -0.5f, 1.0f, 0.5f, 1.0f, 0.5f, 1.0f, -0.5f, 1.0f, 0.5f, 1.0f}, {-0.5f, 0.0f, -0.5f, 1.0f, 0.5, 0.0f, -0.5f, 1.0f, 0.5f, 0.0f, 0.5f, 1.0f, -0.5f, 0.0f, 0.5f, 1.0f}, }; /** * init_transforms - generates translation transforms * * Generates ramdomly on the fly translations transform arrays. * init_trans is the array who defines initial cube placement in opengl viewport * init_vartrans is the array who defines current translation between two hop moves */ void init_transforms() { int i, r; GLfloat x, y, z; int x0, z0; init_trans = (struct vector *) malloc(cnt_cubes * sizeof(struct vector)); init_vartrans = (struct vector *) malloc(cnt_cubes * sizeof(struct vector)); srand(time(NULL)); for (i = 0; i < cnt_cubes; i++) { r = rand(); x = rand() % 70 * 0.01f; x = x < 0.02 ? x + 0.04f : x; x = (r % 2 == 0) ? -x : x; x = (i % 34 == 0) ? 0 : x; y = rand() % 30 * 0.01f; y = y < 0.02 ? y + 0.04f : y; y = (i % 17 == 0) ? y : 0.0f; z = rand() % 70 * 0.01f; z = z < 0.02 ? z + 0.04f : z; z = (r % 2 == 0) ? -z : z; z = (i % 34 == 0) ? 0 : z; x0 = rand() % 15; x0 = (x0 % 2 == 0) ? -x0 : x0; z0 = rand() % 15; z0 = (z0 % 2 == 0) ? -z0 : z0; init_trans[i] = vector_init(x0 + x, (r % 5) * 2.0f, z0 + z); init_vartrans[i] = vector_init(x, y, z); } } /** * free_transforms - Destroy init_trans and init_vartrans global arrays * * Free memory allocated for init_trans and init_vartrans global arrays */ void free_transforms() { free(init_trans); free(init_vartrans); init_trans = NULL; init_vartrans = NULL; } /** * intersec_quad - intersection between an line and a polygon * @poly: the polygon targetted * @e: the line targetted * * Compute intersection point between one line e and one plan * ==== Not used currently */ static struct point poly_intersec_quad(const struct polygon *poly, struct line e) { struct point inter = {10000,10000,10000}; struct line dr; float me = e.dir.vector_magnitude(e.dir), dist, u; struct vector v = vector_set(poly->equa[2].orig, poly->equa[0].orig); double angles = poly->equa[0].dir.vector_get_angle(poly->equa[0].dir, e.dir); double angle2 = poly->equa[0].dir.vector_get_angle(poly->equa[0].dir, v); if (!e.dir.vector_is_same_dir(e.dir, v)) return inter; if (angles > PI/2 || angles < 0) { return inter; } else if (angles <= absolute(angle2)) { dr = poly->equa[1]; dist = poly->equa[0].dir.vector_magnitude(poly->equa[0].dir); } else if (angles != PI/2) { dr = poly->equa[2]; angles = PI/2 - angles; dist = poly->equa[3].dir.vector_magnitude(poly->equa[3].dir); } if (angles == PI/2) { dr = poly->equa[3]; if (me <= dr.dir.vector_magnitude(dr.dir)) { inter = e.orig2; } else { return inter; } } else if(!angles) { dr = poly->equa[0]; if (me <= dr.dir.vector_magnitude(dr.dir)) inter = e.orig2; else return inter; } else { dist = dist / cos(angles); u = dist / me; if (u < 1.0) return inter; inter = e.line_compute_point(e, u); } if (dr.dir.x) u = (inter.x - dr.orig.x) / dr.dir.x; else if(dr.dir.y) u = (inter.y - dr.orig.y) / dr.dir.y; else if(dr.dir.z) u = (inter.z - dr.orig.z) / dr.dir.z; if (u >= 0.0 && u <= 1.0) return inter; inter.x = 100000.0f; inter.y = 100000.0f; inter.z = 100000.0f; return inter; } /** * poly_contains - check if a point is on a polygon * @poly: polygon targetted * @inter: point targetted * * return 1 if point inter is on cpt face, else return 0 * ==== Not used currently */ static int poly_contains(struct polygon *poly, struct point inter) { struct line d; struct point tmp = {poly->pts[0], poly->pts[1], poly->pts[2]}; struct point tmp2; struct vector vtmp; vtmp = vector_set(inter, tmp); tmp2 = poly->poly_intersec_quad(poly, line_init(tmp, vtmp)); if (tmp2.x != 100000) return 1; else return 0; } /** * intersec - Compute the intersect point with a polygon * @poly: polygon targetted * @d: line targetted * * Compute the intersection point between a line (d.orig, d.dir) and poly * ==== Not used currently */ static struct point poly_intersec(struct polygon *poly, struct line d) { struct point inter = {100000.0f, 100000.0f, 100000.0f}; struct vector v1, v2, vcm, norm, vctr; struct point ctr; GLfloat u, k; struct point p[3]; int i = 0, j; vcm = d.dir; ctr = d.orig; vctr = vector_init(ctr.x, ctr.y, ctr.z); /* Parse the 4 points of the cpt face */ for(j = 0; j < 3; j++) { p[j].x = (float) poly->pts[i++]; p[j].y = (float) poly->pts[i++]; p[j].z = (float) poly->pts[i++]; i++; } v1 = vector_set(p[0], p[1]); v2 = vector_set(p[2], p[1]); norm = v1.vector_product(v1, v2); if (!vcm.vector_dot(vcm, norm)) return inter; k = norm.vector_dot(norm, vector_init(p[0].x, p[0].y, p[0].z)); u = (k - vctr.vector_dot(vctr, norm)) / vcm.vector_dot(vcm, norm); inter = d.line_compute_point(d, u); if (poly->poly_contains(poly, inter)) return inter; inter.x = 100000.0f; inter.y = 100000.0f; inter.z = 100000.0f; return inter; } /** * intersec_3_plans - intersection point between 3 plans * @n: the 3 vectors array * @k: the 3 k-norm array * * Compute intersction point between 3 plans with theirs translation * vector and theirs k norm. * ==== Not used currently */ static struct point intersec_3_plans(struct vector *n, float *k) { int i; GLfloat m[16]; GLfloat *inv; struct point ret,inter={10000,10000,10000}; for (i=0; i < 12; i+=4) { m[i] = n[i/4].x; m[i+1] = n[i/4].y; m[i+2] = n[i/4].z; m[i+3] = -k[i/4]; } for (i=12; i < 15; i++) m[i]=0.0f; m[15]=1.0f; inv = inverse_matr(m); if (inv == NULL) return inter; ret.x = inv[3]; ret.y = inv[7]; ret.z = inv[11]; free(inv); return ret; } /** * pl_compute_coord - compute coordinates with current active matrix * @poly: polygon targetted * * Compute opengl polygon poly with current active matrix */ static void poly_compute_coord(struct polygon *poly) { GLfloat *tabfl; if (poly->move) { tabfl = poly->vartrans.vector_to_matrix(poly->vartrans, poly->distcol); gl_matrix_mult(tabfl, poly->pts); free(tabfl); } if (poly->col != NULL) { poly->vartrans.x *= -1; poly->vartrans.y *= -1; poly->vartrans.z *= -1; poly->oldcol = poly->col; } poly->col = NULL; poly->distcol = 1.0f; } /** * init_cube: init a cube with coordinate and transform values * @moved: cube is moving or not (0/1) * * Create a new cube into tabpoly4 global arrays and init his properties */ void init_cube(int move) { struct polygon *current, *poly; GLfloat *tabfl; int indpol, i, j, cnt = 0, texture; GLfloat fact[64] = {0.25f, 1.0f, 1.0f, 0.5f, 2.0f, 0.5f, 0.25f, 2.0f, 0.25f, 0.5f, 0.5f, 0.5f, 0.25f, 0.5f, 0.25f, 0.5f, 0.25f, 0.5f, 0.5f, 0.25f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.25f, 0.5f, 0.25f, 0.5f, 0.25f, 0.5f, 0.5f, 0.5f, 0.5f, 1.0f, 0.25f, 0.5f, 0.5f, 0.5f, 1.0f, 0.5f, 1.0f, 0.5f, 0.25f, 0.5f, 0.25f, 0.5f, 1.0f, 0.25f, 0.25f, 0.5f, 0.5f, 0.5f, 1.0f, 0.5f, 0.5f, 0.5f, 0.25f, 0.5f, 0.25f, 0.5f}; GLfloat t[16]; indpol = 0; current = poly_head; if (current != NULL && current->next != NULL) { for (;current->next != poly_head; cnt++) current = current->next; } if (current != NULL) indpol = current->indpol + 1; /* Init 6 faces for a cube */ for (i = 0; i < 6; i++) { /* Init cube points */ for (j = 0; j < 16; j++) { if ((j+1) % 4) t[j] = cube[i][j] * fact[indpol % 64]; else t[j] = 1.0f; } texture = indpol % 2; if (init_vartrans[indpol % cnt_cubes].y != 0.0f) texture = 5; poly = polygon_init(cnt++, 4, move, indpol, 6, i, texture, t); tabfl = poly->trans.vector_to_matrix(poly->trans, 1.0f); gl_matrix_mult(tabfl, poly->pts); free(tabfl); if (current != NULL) { current->next = poly; poly->prev = current; poly->next = poly_head; poly_head->prev = poly; } else { poly->prev = NULL; poly->next = NULL; poly_head = poly; } current = poly; } } /** * poly_pivot_collision - Pivot collision function for a polygon * @poly: polygon targetted * * This function detect for each polygon of the universe if there will be a collision * with the polygon poly. */ static void poly_pivot_collision(struct polygon *poly) { struct polygon *current; int indpol = -1; /* Loop on the polygon list but avoid same polygon and last collision one */ current = poly_head; do { if ((current != poly->oldcol || (current->indpol != 0 && current->oldcol != poly)) && current->indpol != poly->indpol && (indpol == INDPOL_UNIVERSE || current->indpol != indpol)) poly->poly_detect_collision(poly, current); indpol = current->indpol; current = current->next; } while (current != poly_head); } /** * poly_detect_collision - Detect a collision between polygons * @poly1: first polygon * @poly2: second polygon * * Detect a collision between 2 polygons and set properties for manage this */ static void poly_detect_collision(struct polygon *poly1, struct polygon *poly2) { struct polygon *oldcol1; struct polygon *oldcol2; struct polygon *samepol; int indpol = -1; int fact = 1, fact2 = 0; double distcol = 0; /* First polygon point (x,y,z) and dimensions (h,w,d) */ GLfloat x1, y1, z1, h1, w1, d1; GLfloat x2, y2, z2, h2, w2, d2; x1 = poly1->pts[0]; y1 = poly1->pts[1]; z1 = poly1->pts[2]; x2 = poly2->pts[0]; y2 = poly2->pts[1]; z2 = poly2->pts[2]; h1 = poly1->pts[13] - y1; w1 = poly1->pts[4] - x1; d1 = 0.0f; if (poly1->next != NULL) d1 = poly1->next->pts[2] - z1; /* indpol=0 => universe, specific case */ if (poly2->indpol != 0) { h2 = poly2->pts[13] - y2; w2 = poly2->pts[4] - x2; d2 = 0.0f; if (poly2->next != NULL) d2 = poly2->next->pts[2] - z2; } else { switch (poly2->indfaces) { /* Front */ case 0: h2 = poly2->pts[13] - y2; w2 = poly2->pts[4] - x2; d2 = 10.0f; z2 -= 10.0f; break; /* Back */ case 1: h2 = poly2->pts[13] - y2; w2 = poly2->pts[4] - x2; d2 = 10.0f; break; /* Left Side */ case 2: w2 = 10.0f; d2 = poly2->pts[6] - z2; h2 = poly2->pts[13] - y2; break; /* Right Side */ case 3: w2 = 10.0f; x2 -= 10.0f; d2 = poly2->pts[6] - z2; h2 = poly2->pts[13] - y2; break; /* Top */ case 4: h2 = -10.0f; y2 += 10.0f; w2 = poly2->pts[4] - x2; d2 = poly2->pts[14] - z2; break; /* Roof */ case 5: h2 = -10.0f; w2 = poly2->pts[4] - x2; d2 = poly2->pts[14] - z2; break; } } /* 1/10 precision */ while (fact < 11) { x1 += 0.1 * poly1->vartrans.x; y1 += 0.1 * poly1->vartrans.y; z1 += 0.1 * poly1->vartrans.z; x2 += 0.1 * poly2->vartrans.x; y2 += 0.1 * poly2->vartrans.y; z2 += 0.1 * poly2->vartrans.z; if ((x2 >= x1 + w1) /* Too much at right */ || (x2 + w2 <= x1) /* Too much at left */ || (y2 + h2 >= y1) /* Too much at top */ || (y2 <= y1 + h1) /* Too much at bottom */ || (z2 >= z1 + d1) /* Too much at back */ || (z2 + d2 <= z1)) { /* Too much at front */ fact++; continue; } else { x1 -= 0.1 * poly1->vartrans.x; y1 -= 0.1 * poly1->vartrans.y; z1 -= 0.1 * poly1->vartrans.z; x2 -= 0.1 * poly2->vartrans.x; y2 -= 0.1 * poly2->vartrans.y; z2 -= 0.1 * poly2->vartrans.z; /* 1/100 precision */ fact2 = 1; while (1) { x1 += 0.001 * poly1->vartrans.x; y1 += 0.001 * poly1->vartrans.y; z1 += 0.001 * poly1->vartrans.z; x2 += 0.001 * poly2->vartrans.x; y2 += 0.001 * poly2->vartrans.y; z2 += 0.001 * poly2->vartrans.z; if ((x2 >= x1 + w1) || (x2 + w2 <= x1) || (y2 + h2 >= y1) || (y2 <= y1 + h1) || (z2 >= z1 + d1) || (z2 + d2 <= z1)) { ++fact2; continue; } break; } distcol = 0.1 * (fact - 1) + 0.001 * (fact2 - 1); if (debug) { printf("%d:%d:%f:", poly1->indpol, poly2->indpol, distcol); printf("%.1f:%.1f:%.1f:%.1f:%.1f:%.1f:", x1, y1, z1, w1, h1, d1); printf("%.1f:%.1f:%.1f:%.1f:%.1f:%.1f\n", x2, y2, z2, w2, h2, d2); } if ((poly1->col == NULL || distcol < poly1->distcol) && (poly2->col == NULL || distcol < poly2->distcol)) { oldcol1 = poly1->col; oldcol2 = poly2->col; poly1->col = poly2; poly1->distcol = distcol; samepol = poly1->next; while (samepol->indpol == poly1->indpol) { samepol->col = poly2; samepol->distcol = distcol; samepol = samepol->next; } if (poly2->move) { poly2->col = poly1; poly2->distcol = distcol; samepol = poly2->next; while (samepol->indpol == poly2->indpol) { samepol->col = poly1; samepol->distcol = distcol; samepol = samepol->next; } } if (oldcol1 != NULL && oldcol1->move) { oldcol1->col = NULL; oldcol1->distcol = 1.0f; samepol = oldcol1->next; while (samepol->indpol == oldcol1->indpol) { samepol->col = NULL; samepol->distcol = 1.0f; samepol = samepol->next; } } if (oldcol2 != NULL && oldcol2->move) { oldcol2->col = NULL; oldcol2->distcol = 1.0f; samepol = oldcol2->next; while (samepol->indpol == oldcol2->indpol) { samepol->col = NULL; samepol->distcol = 1.0f; samepol = samepol->next; } } /* Recompute for polygon unbinded */ if (oldcol1 != NULL) oldcol1->poly_pivot_collision(oldcol1); if (oldcol2 != NULL) oldcol2->poly_pivot_collision(oldcol2); oldcol1 = NULL; oldcol2 = NULL; } fact = 11; } } } /** * polygon_init: init polygon with his properties * */ struct polygon *polygon_init(int counter, int cntsides, int move, int indpol, int cntfaces, int indfaces, int texture, GLfloat pts[]) { struct polygon *poly; struct point p[3], tmp, tmp2; struct vector v1, v2, vtmp; struct line diag; float rayon; int i, j; /* Allocate polygon object */ poly = (struct polygon*) malloc(sizeof(struct polygon)); if (poly == NULL) return poly; /* Init main properties */ poly->counter = counter; poly->indpol = indpol; poly->cntfaces = cntfaces; poly->indfaces = indfaces; poly->move = move; poly->texture = texture; poly->cntsides = cntsides; poly->pts = (GLfloat*) malloc((cntsides * 4) * sizeof(GLfloat)); for(j = 0; j < (cntsides * 4); j++) poly->pts[j] = pts[j]; poly->col = NULL; poly->oldcol = NULL; poly->distcol = 1.0f; /* Compute lines equation for the cntsides segments of the face */ poly->equa = (struct line*) malloc(cntsides * sizeof(struct line)); for(i = 0; i < cntsides; i++) { if(i == cntsides-1) j = 0; else j = i+1; /* tmp and tmp2 are the 2 points of current segment */ tmp.x = poly->pts[4*i]; tmp.y = poly->pts[4*i+1]; tmp.z = poly->pts[4*i+2]; tmp2.x = poly->pts[4*j]; tmp2.y = poly->pts[4*j+1]; tmp2.z = poly->pts[4*j+2]; /* Init equation line for current segment */ poly->equa[i].dir = vector_set(tmp2, tmp); poly->equa[i].orig = tmp; } /* Polygon center */ poly->center.x = (poly->equa[0].orig.x + poly->equa[(cntsides/2)].orig.x)/2; poly->center.y = (poly->equa[0].orig.y + poly->equa[(cntsides/2)].orig.y)/2; poly->center.z = (poly->equa[0].orig.z + poly->equa[(cntsides/2)].orig.z)/2; vtmp = vector_set(poly->equa[0].orig, poly->center); poly->rayon = vtmp.vector_magnitude(vtmp); /* Init transmation transform */ if (poly->move) { poly->trans = init_trans[poly->indpol%cnt_cubes]; poly->vartrans = init_vartrans[poly->indpol%cnt_cubes]; } else { poly->vartrans = vector_init(0.0f, 0.0f, 0.0f); } /* Init polygon functions */ poly->poly_compute_coord = poly_compute_coord; poly->poly_intersec_quad = poly_intersec_quad; poly->poly_contains = poly_contains; poly->poly_intersec = poly_intersec; poly->poly_pivot_collision = poly_pivot_collision; poly->poly_detect_collision = poly_detect_collision; return poly; } /** * next_coords - Compute new coordinates for polygons * * This function loop on polygons list and compute new coordinates */ void next_coords() { struct polygon *current; current = poly_head; do { current->poly_compute_coord(current); current = current->next; } while (current != poly_head); } /** * next_hop - Next polygons move * * This function manage polygons move with collision detection * and coordinates compute. */ void next_hop() { struct polygon *current; int indpol = -1; current = poly_head; do { if (current->move && current->indpol != indpol) current->poly_pivot_collision(current); indpol = current->indpol; current = current->next; } while (current != poly_head); next_coords(); } /** * display_polygons - Shape quad polygons in opengl * * Dispaly all cubes in opengl viewport. */ void display_polygons() { int i,j; struct polygon *current = poly_head; do { j = 2; if (current->texture == 2) j = 10; if (current->texture == 1) j = 1; if (current->texture == 4) j = 1; if (mode_grid) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); /* Because camera position, we want this 2 room sides transparent */ if (current->texture == 3 && (current->indfaces == 0 || current->indfaces == 2)) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); /* Set texture */ glBindTexture(GL_TEXTURE_2D, texturenames[current->texture]); /* Shape quad polygon */ glBegin(GL_QUADS); glTexCoord2i(0, 0); glVertex3f(current->pts[0], current->pts[1], current->pts[2]); glTexCoord2i(j, 0); glVertex3f(current->pts[4], current->pts[5], current->pts[6]); glTexCoord2i(j, j); glVertex3f(current->pts[8], current->pts[9], current->pts[10]); glTexCoord2i(0, j); glVertex3f(current->pts[12], current->pts[13], current->pts[14]); glEnd(); /* First display init opengl matrix and compute coordinates with this */ if (is_matrix == 0) { glPushMatrix(); glMultMatrixf(current->pts); glGetFloatv(GL_MODELVIEW_MATRIX, current->pts); glPopMatrix(); } current = current->next; } while (current != poly_head); is_matrix = 1; return; } /** * destroy_polygons - Reset polygons stack * * Destroy all polygons */ void destroy_polygons() { struct polygon *current = poly_head, *tmp; if (current->prev != NULL) current->prev->next = NULL; while (current != NULL) { tmp = current->next; free(current); current = tmp; } poly_head = NULL; }
24.580482
111
0.60034
[ "object", "shape", "vector", "transform" ]
f721d2bc501b86a334f6b996a796bf0bad0355f7
4,954
h
C
src/object.h
dominicprice/tinylisp
f93146049f95e51863fa4b9bb874d850f45d2bb4
[ "MIT" ]
null
null
null
src/object.h
dominicprice/tinylisp
f93146049f95e51863fa4b9bb874d850f45d2bb4
[ "MIT" ]
null
null
null
src/object.h
dominicprice/tinylisp
f93146049f95e51863fa4b9bb874d850f45d2bb4
[ "MIT" ]
null
null
null
#ifndef LISP_OBJECT_H #define LISP_OBJECT_H #include "error.h" typedef struct TinyLisp_ *TinyLisp; typedef enum LispObjectType_ LispObjectType; typedef struct LispList_ *LispList; typedef struct LispSymbol_ *LispSymbol; typedef struct LispObject_ *LispObject; typedef struct LispStack_ *LispStack; typedef int LispInteger; typedef LispObject(*LispBuiltin)(TinyLisp, LispObject); enum LispObjectType_ { T_LIST, T_INTEGER, T_SYMBOL, T_BUILTIN, T_SIZE }; struct type_desc_ { int code; char* name; }; extern struct type_desc_ typedesc[T_SIZE]; struct LispList_ { int size, capacity; LispObject* data; }; struct LispSymbol_ { int size; char* data; }; struct LispObject_ { union { LispList l; LispSymbol s; LispInteger i; LispBuiltin b; } data; LispObjectType type; int refcount; }; // malloc a new LispObject_ struct and initialise type and refcount. returns NULL on error. LispObject lisp_object_new_(LispObjectType type); // Increase refount of obj and return; never returns NULL LispObject lisp_object_create_reference(LispObject obj); // delegate to lisp_*_free based on type void lisp_object_free(LispObject obj); // delegate to lisp_*_equal based on type, return 0 for different types int lisp_object_equal(LispObject lhs, LispObject rhs); // delegate to lisp_*_lessthan based on type, return 0 for different types int lisp_object_lessthan(LispObject lhs, LispObject rhs); // return 1 if object is an empty list of 0, else returns 0 int lisp_object_is_nil(LispObject obj); // delegate to lisp_*_print based on type void lisp_object_print(LispObject obj); // malloc a new empty list LispObject lisp_list_new(); // malloc a list and initialise with the 'nvals' vals given LispObject lisp_list_new_from_args(int nvals, ...); // malloc a new list with new references to the objects in list LispObject lisp_list_copy(LispObject list); // malloc a new list with new referencs to the objects in the sublist (start, end) LispObject lisp_list_copy_n(LispObject list, int start, int end); // decrease refcount of list; if recount is then 0 then call lisp_object_free on all items and free memory for list void lisp_list_free(LispObject list); // compare element-wise for equality int lisp_list_equal(LispObject lhs, LispObject rhs); // compare element-wise for lessthan int lisp_list_lessthan(LispObject lhs, LispObject rhs); // number of elements in list int lisp_list_size(LispObject list); // number of elements space is reserved for int lisp_list_capacity(LispObject list); // borrowed reference to the element at position n LispObject lisp_list_at(LispObject list, int n); // push an element to the end of the list modifying it; expands as needed error_t lisp_list_push(LispObject list, LispObject val); // return a new list consisting of new references to the elements in list and other LispObject lisp_list_concat(LispObject list, LispObject other); // return a new reference to the element at the front of the list LispObject lisp_list_head(LispObject list); // return a new list containing new references to the elements in the sublist (1, ...) LispObject lisp_list_tail(LispObject list); // print the list void lisp_list_print(LispObject list); // malloc a new symbol with value val LispObject lisp_symbol_new(char* val); // malloc a new symbol with the substring of val starting at 0 and spanning len chars LispObject lisp_symbol_new_n(char* val, int len); // decref symbol; if refcount is then 0 free all memory associated with it void lisp_symbol_free(LispObject symbol); // compare string values for equality int lisp_symbol_equal(LispObject lhs, LispObject rhs); // return 1 if lhs is lexicographically less than rhs, else 0 int lisp_symbol_lessthan(LispObject lhs, LispObject rhs); // return a borrowed reference to the string value of symbol char* lisp_symbol_get(LispObject symbol); // print the symbol void lisp_symbol_print(LispObject symbol); // malloc a new integer with value val LispObject lisp_integer_new(int val); // decref object; if refcount is then 0 free all memory associated with it void lisp_integer_free(LispObject integer); // compare integer value for equality int lisp_integer_equal(LispObject lhs, LispObject rhs); // return lhs < rhs int lisp_integer_lessthan(LispObject lhs, LispObject rhs); // return integer value int lisp_integer_get(LispObject integer); // print the integer void lisp_integer_print(LispObject integer); // malloc a new lispobject containing the builtin val LispObject lisp_builtin_new(LispBuiltin val); // compare function pointers for equality int lisp_builtin_equal(LispObject lhs, LispObject rhs); // return lhs < rhs int lisp_builtin_lessthan(LispObject lhs, LispObject rhs); // return the function pointer LispBuiltin lisp_builtin_get(LispObject builtin); // decref object; if refcount is then 0 free all memory associated with it void lisp_builtin_free(LispObject builtin); // print the builtins address void lisp_builtin_print(LispObject builtin); #endif
34.402778
115
0.795317
[ "object" ]
f72ae2ca95cc0d4a8bf46ec79187d6ba1b68abe4
9,006
c
C
src/python-zstd.c
sergey-dryabzhinsky/python-zstd
eea41d26e7a9f00f940307051d35b6a28c6d31ab
[ "BSD-2-Clause" ]
110
2015-03-22T10:41:55.000Z
2022-03-19T14:02:30.000Z
src/python-zstd.c
sergey-dryabzhinsky/python-zstd
eea41d26e7a9f00f940307051d35b6a28c6d31ab
[ "BSD-2-Clause" ]
52
2015-11-02T13:40:04.000Z
2022-03-13T20:53:00.000Z
src/python-zstd.c
sergey-dryabzhinsky/python-zstd
eea41d26e7a9f00f940307051d35b6a28c6d31ab
[ "BSD-2-Clause" ]
23
2015-09-18T11:42:56.000Z
2021-12-25T04:14:41.000Z
/* * ZSTD Library Python bindings * Copyright (c) 2015-2020, Sergey Dryabzhinsky * All rights reserved. * * BSD License * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stddef.h> /* Since 3.8 it is mandatory to use proper type for # formats */ #define PY_SSIZE_T_CLEAN #include <Python.h> #include "bytesobject.h" #include "zstd.h" #include "util.h" #include "python-zstd.h" /** * New function for multi-threaded compression. * Uses origin zstd header, nothing more. * Simple version: not for streaming, no dict support, full block compression. * Uses new API with context object. */ static PyObject *py_zstd_compress_mt(PyObject* self, PyObject *args) { PyObject *result; const char *source; Py_ssize_t source_size; char *dest; Py_ssize_t dest_size; size_t cSize; int32_t level = ZSTD_CLEVEL_DEFAULT; int32_t threads = 0; ZSTD_CCtx* cctx = 0; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args, "y#|ii", &source, &source_size, &level, &threads)) return NULL; #else if (!PyArg_ParseTuple(args, "s#|ii", &source, &source_size, &level, &threads)) return NULL; #endif if (0 == level) level=ZSTD_CLEVEL_DEFAULT; /* Fast levels (zstd >= 1.3.4) - [-1..-100] */ /* Usual levels - [ 1..22] */ /* If level less than -100 or 1 - raise Error, level 0 handled before. */ if (level < ZSTD_MIN_CLEVEL) { PyErr_Format(ZstdError, "Bad compression level - less than %d: %d", ZSTD_MIN_CLEVEL, level); return NULL; } /* If level more than 22 - raise Error. */ if (level > ZSTD_MAX_CLEVEL) { PyErr_Format(ZstdError, "Bad compression level - more than %d: %d", ZSTD_MAX_CLEVEL, level); return NULL; } if (threads < 0) { PyErr_Format(ZstdError, "Bad threads count - less than %d: %d", 0, threads); return NULL; } if (0 == threads) threads = UTIL_countPhysicalCores(); /* If threads more than 200 - raise Error. */ if (threads > ZSTDMT_NBWORKERS_MAX) { PyErr_Format(ZstdError, "Bad threads count - more than %d: %d", ZSTDMT_NBWORKERS_MAX, threads); return NULL; } dest_size = (Py_ssize_t)ZSTD_compressBound(source_size); result = PyBytes_FromStringAndSize(NULL, dest_size); if (result == NULL) { return NULL; } if (source_size > 0) { dest = PyBytes_AS_STRING(result); cctx = ZSTD_createCCtx(); ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, level); ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, threads); Py_BEGIN_ALLOW_THREADS cSize = ZSTD_compress2(cctx, dest, (size_t)dest_size, source, (size_t)source_size); Py_END_ALLOW_THREADS ZSTD_freeCCtx(cctx); if (ZSTD_isError(cSize)) { PyErr_Format(ZstdError, "Compression error: %s", ZSTD_getErrorName(cSize)); Py_CLEAR(result); return NULL; } Py_SIZE(result) = cSize; } return result; } /** * New more interoperable function * Uses origin zstd header, nothing more * Simple version: not for streaming, no dict support, full block decompression */ static PyObject *py_zstd_uncompress(PyObject* self, PyObject *args) { PyObject *result; const char *source; Py_ssize_t source_size; uint64_t dest_size; char error = 0; size_t cSize; #if PY_MAJOR_VERSION >= 3 if (!PyArg_ParseTuple(args, "y#", &source, &source_size)) return NULL; #else if (!PyArg_ParseTuple(args, "s#", &source, &source_size)) return NULL; #endif dest_size = (uint64_t) ZSTD_getDecompressedSize(source, source_size); if (dest_size == 0) { PyErr_Format(ZstdError, "Input data invalid or missing content size in frame header."); return NULL; } result = PyBytes_FromStringAndSize(NULL, dest_size); if (result != NULL) { char *dest = PyBytes_AS_STRING(result); Py_BEGIN_ALLOW_THREADS cSize = ZSTD_decompress(dest, dest_size, source, source_size); Py_END_ALLOW_THREADS if (ZSTD_isError(cSize)) { PyErr_Format(ZstdError, "Decompression error: %s", ZSTD_getErrorName(cSize)); error = 1; } else if (cSize != dest_size) { PyErr_Format(ZstdError, "Decompression error: length mismatch -> decomp %lu != %lu [header]", (uint64_t)cSize, dest_size); error = 1; } } if (error) { Py_CLEAR(result); result = NULL; } return result; } /** * Returns this module version as string */ static PyObject *py_zstd_module_version(PyObject* self, PyObject *args) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("%s", VERSION); #else return PyString_FromFormat("%s", VERSION); #endif } /** * Returns ZSTD library version as string */ static PyObject *py_zstd_library_version(PyObject* self, PyObject *args) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("%s", ZSTD_versionString()); #else return PyString_FromFormat("%s", ZSTD_versionString()); #endif } /** * Returns ZSTD library version as int (major * 100*100 + minor * 100 + release) */ static PyObject *py_zstd_library_version_int(PyObject* self, PyObject *args) { return Py_BuildValue("i", ZSTD_VERSION_NUMBER); } /** * Returns 0 or 1 if ZSTD library build as external */ static PyObject *py_zstd_library_external(PyObject* self, PyObject *args) { return Py_BuildValue("i", LIBZSTD_EXTERNAL); } static PyMethodDef ZstdMethods[] = { {"ZSTD_compress", py_zstd_compress_mt, METH_VARARGS, COMPRESS_DOCSTRING}, {"ZSTD_uncompress", py_zstd_uncompress, METH_VARARGS, UNCOMPRESS_DOCSTRING}, {"compress", py_zstd_compress_mt, METH_VARARGS, COMPRESS_DOCSTRING}, {"uncompress", py_zstd_uncompress, METH_VARARGS, UNCOMPRESS_DOCSTRING}, {"decompress", py_zstd_uncompress, METH_VARARGS, UNCOMPRESS_DOCSTRING}, {"dumps", py_zstd_compress_mt, METH_VARARGS, COMPRESS_DOCSTRING}, {"loads", py_zstd_uncompress, METH_VARARGS, UNCOMPRESS_DOCSTRING}, {"version", py_zstd_module_version, METH_NOARGS, VERSION_DOCSTRING}, {"ZSTD_version", py_zstd_library_version, METH_NOARGS, ZSTD_VERSION_DOCSTRING}, {"ZSTD_version_number", py_zstd_library_version_int, METH_NOARGS, ZSTD_INT_VERSION_DOCSTRING}, {"ZSTD_external", py_zstd_library_external, METH_NOARGS, ZSTD_EXTERNAL_DOCSTRING}, {NULL, NULL, 0, NULL} }; struct module_state { PyObject *error; }; #if PY_MAJOR_VERSION >= 3 #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m)) #else /* not needed */ #endif #if PY_MAJOR_VERSION >= 3 static int myextension_traverse(PyObject *m, visitproc visit, void *arg) { Py_VISIT(GETSTATE(m)->error); return 0; } static int myextension_clear(PyObject *m) { Py_CLEAR(GETSTATE(m)->error); return 0; } static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "zstd", NULL, sizeof(struct module_state), ZstdMethods, NULL, myextension_traverse, myextension_clear, NULL }; #define INITERROR return NULL PyObject *PyInit_zstd(void) #else #define INITERROR return void initzstd(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module = PyModule_Create(&moduledef); #else PyObject *module = Py_InitModule("zstd", ZstdMethods); #endif if (module == NULL) { INITERROR; } ZstdError = PyErr_NewException("zstd.Error", NULL, NULL); if (ZstdError == NULL) { Py_DECREF(module); INITERROR; } Py_INCREF(ZstdError); PyModule_AddObject(module, "Error", ZstdError); #if PY_MAJOR_VERSION >= 3 return module; #endif }
30.02
134
0.682989
[ "object" ]
f73159b8aa436fcd93c25efee4d122ed29617acf
499
h
C
helpscreen.h
ebrahimebrahim/fictional-fortnight
df34120193590a08642bc8b9ee87923f68e799eb
[ "MIT" ]
null
null
null
helpscreen.h
ebrahimebrahim/fictional-fortnight
df34120193590a08642bc8b9ee87923f68e799eb
[ "MIT" ]
null
null
null
helpscreen.h
ebrahimebrahim/fictional-fortnight
df34120193590a08642bc8b9ee87923f68e799eb
[ "MIT" ]
null
null
null
#pragma once #include<string> #include "textbox.h" #include "logger.h" class App; // forward declaration class HelpScreen { public: HelpScreen(SDL_Renderer *, TTF_Font *, Logger *); ~HelpScreen() {} void events(const SDL_Event *); void update(App *); void render(SDL_Renderer *); private: SDL_Renderer * renderer = nullptr; TTF_Font * font = nullptr; Logger * log = nullptr; SDL_Color textColor; TextBox helpTextBox; bool tryExitHelp = false; };
19.192308
53
0.659319
[ "render" ]
f73488a60cc89f1bf8dcd060002fabee5f083a3a
3,720
h
C
third_party/npapi/npspy/extern/nspr/prrng.h
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
third_party/npapi/npspy/extern/nspr/prrng.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
third_party/npapi/npspy/extern/nspr/prrng.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code is the Netscape Portable Runtime (NSPR). * * The Initial Developer of the Original Code is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1999-2000 Netscape Communications Corporation. All * Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL"), in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your * version of this file only under the terms of the GPL and not to * allow others to use your version of this file under the MPL, * indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient * may use your version of this file under either the MPL or the * GPL. */ /* ** prrng.h -- NSPR Random Number Generator ** ** ** lth. 29-Oct-1999. */ #ifndef prrng_h___ #define prrng_h___ #include "prtypes.h" PR_BEGIN_EXTERN_C /* ** PR_GetRandomNoise() -- Get random noise from the host platform ** ** Description: ** PR_GetRandomNoise() provides, depending on platform, a random value. ** The length of the random value is dependent on platform and the ** platform's ability to provide a random value at that moment. ** ** The intent of PR_GetRandomNoise() is to provide a "seed" value for a ** another random number generator that may be suitable for ** cryptographic operations. This implies that the random value ** provided may not be, by itself, cryptographically secure. The value ** generated by PR_GetRandomNoise() is at best, extremely difficult to ** predict and is as non-deterministic as the underlying platfrom can ** provide. ** ** Inputs: ** buf -- pointer to a caller supplied buffer to contain the ** generated random number. buf must be at least as large as ** is specified in the 'size' argument. ** ** size -- the requested size of the generated random number ** ** Outputs: ** a random number provided in 'buf'. ** ** Returns: ** PRSize value equal to the size of the random number actually ** generated, or zero. The generated size may be less than the size ** requested. A return value of zero means that PR_GetRandomNoise() is ** not implemented on this platform, or there is no available noise ** available to be returned at the time of the call. ** ** Restrictions: ** Calls to PR_GetRandomNoise() may use a lot of CPU on some platforms. ** Some platforms may block for up to a few seconds while they ** accumulate some noise. Busy machines generate lots of noise, but ** care is advised when using PR_GetRandomNoise() frequently in your ** application. ** ** History: ** Parts of the model dependent implementation for PR_GetRandomNoise() ** were taken in whole or part from code previously in Netscape's NSS ** component. ** */ NSPR_API(PRSize) PR_GetRandomNoise( void *buf, PRSize size ); PR_END_EXTERN_C #endif /* prrng_h___ */ /* end prrng.h */
35.428571
79
0.722849
[ "model" ]
f73e1c34e6c6dacc382b7f80c0c0afabe091ca80
11,949
h
C
cuda_src/utils.h
javierlorenzod/RubiksNet
d389d18976beef5bd6e395b0d7576e4e26c520a2
[ "MIT" ]
86
2020-08-19T09:52:29.000Z
2022-03-21T06:35:49.000Z
cuda_src/utils.h
javierlorenzod/RubiksNet
d389d18976beef5bd6e395b0d7576e4e26c520a2
[ "MIT" ]
6
2020-09-01T07:10:30.000Z
2021-07-06T08:15:18.000Z
cuda_src/utils.h
javierlorenzod/RubiksNet
d389d18976beef5bd6e395b0d7576e4e26c520a2
[ "MIT" ]
11
2020-09-10T06:56:47.000Z
2022-02-06T05:58:54.000Z
#include <vector> #include <sstream> #include <iterator> #include <iostream> #include <type_traits> #include <cassert> #include <cstdlib> #include <ATen/Utils.h> #if __CUDACC_VER_MAJOR__ == 9 #include <ATen/ATen.h> #include <ATen/core/Tensor.h> namespace torch = at; #else // NVCC on CUDA 9 will fail if you include this header. CUDA 10 is fine #include <torch/extension.h> #endif #ifndef TORCHX_H_ #define TORCHX_H_ using std::string; using std::cout; using std::endl; using std::vector; using std::ostringstream; using std::initializer_list; using torch::Tensor; #ifndef __CUDACC_VER_MAJOR__ using namespace pybind11::literals; #endif namespace torchx { template< bool B, class T = void > using enable_if_t = typename std::enable_if<B,T>::type; typedef torch::IntArrayRef ShapeRef; typedef vector<int64_t> ShapeVector; typedef string s_; // quickly convert const char* to string class /* * ************************ * printing utils * ************************ */ // Overload torchx_str_hook with your custom class to enable printing with // to_str(), pyprint(), spyprint(), and sjoin()! template<typename T> void torchx_str_hook(std::ostream& oss, const T& object) { oss << object; } template<typename VectorT> void _vector_str( std::ostream& oss, const VectorT& vec, const string& sep, const string& parentheses ) { bool first = true; if (parentheses.size() > 0) oss << parentheses[0]; for (auto& elem: vec) { if (!first) oss << sep; torchx_str_hook(oss, elem); first = false; } if (parentheses.size() > 0) oss << parentheses[1]; } template<typename E> void torchx_str_hook(std::ostream& oss, const vector<E>& vec) { _vector_str(oss, vec, ", ", "[]"); } template<typename E> void torchx_str_hook(std::ostream& oss, const std::initializer_list<E>& vec) { _vector_str(oss, vec, ", ", "[]"); } template<typename E> void torchx_str_hook(std::ostream& oss, const torch::ArrayRef<E>& vec) { _vector_str(oss, vec, ", ", "()"); } template<typename T> string to_str(const T& obj) { ostringstream oss; torchx_str_hook(oss, obj); return oss.str(); } /* printing utils mimicing python interface */ struct PrintOption { string _end = "\n"; string _sep = " "; bool _fixed = false; bool _scientific = false; int _precision = -2; // default std::ostream* _stream = &std::cout; PrintOption end(const string& end) { _end = end; return *this; } PrintOption sep(const string& sep) { _sep = sep; return *this; } PrintOption stream(std::ostream& stream) { _stream = &stream; return *this; } PrintOption fixed() { _fixed = true; return *this; } PrintOption scientific() { _scientific = true; return *this; } PrintOption precision(int n) { _precision = n; return *this; } PrintOption max_precision() { _precision = -1; return *this; } PrintOption _add_iomanip() { *_stream << std::boolalpha; // delayed execution of iomanip if (_fixed) *_stream << std::fixed; if (_scientific) *_stream << std::scientific; if (_precision > 0) *_stream << std::setprecision(_precision); if (_precision == -1) // max precision *_stream << std::setprecision(std::numeric_limits<long double>::digits10 + 1); return *this; } }; inline void _pyprint_helper(const PrintOption& option) { *option._stream << option._end; } template<typename T> void _pyprint_helper(const PrintOption& option, T&& arg) { auto& oss = *option._stream; torchx_str_hook(oss, arg); oss << option._end; } template<typename T, typename... Ts> void _pyprint_helper(const PrintOption& option, T&& arg, Ts&& ... rest) { auto& oss = *option._stream; torchx_str_hook(oss, arg); oss << option._sep; _pyprint_helper(option, std::forward<Ts>(rest) ...); } template<typename... Ts> void pyprint(PrintOption option, Ts&& ... args) { // pass PrintOption by copy avoids duplicating code for lvalue and rvalue _pyprint_helper(option._add_iomanip(), std::forward<Ts>(args) ...); } template<typename... Ts> void pyprint(Ts&& ... args) { pyprint(PrintOption(), std::forward<Ts>(args) ...); } template<typename... Ts> string spyprint(PrintOption option, Ts&& ... args) { ostringstream oss; _pyprint_helper( option.stream(oss)._add_iomanip(), std::forward<Ts>(args) ... ); return oss.str(); } template<typename... Ts> string spyprint(Ts&& ... args) { return spyprint(PrintOption().end(""), std::forward<Ts>(args) ...); } // must be invoked with at least 2 args template<typename T1, typename T2, typename... Ts> string sjoin(const string& sep, T1&& arg1, T2&& arg2, Ts&& ... args) { return spyprint( PrintOption().sep(sep).end(""), std::forward<T1>(arg1), std::forward<T2>(arg2), std::forward<Ts>(args) ... ); } // must be invoked with at least 2 args template<typename Iterable> string sjoin(const string& sep, const Iterable& vec) { ostringstream oss; _vector_str(oss, vec, sep, ""); return oss.str(); } // mimic python multiply string template<typename Char, typename Traits, typename Allocator> std::basic_string<Char, Traits, Allocator> operator*( const std::basic_string<Char, Traits, Allocator> s, size_t n ) { std::basic_string<Char, Traits, Allocator> result = s; for (size_t i = 0; i < n; ++i) { result += s; } return result; } // now s * 3 and 3 * s both work template<typename Char, typename Traits, typename Allocator> std::basic_string<Char, Traits, Allocator> operator*( size_t n, const std::basic_string<Char, Traits, Allocator>& s ) { return s * n; } inline void ptitle(const string& title, const string& sep = "=") { pyprint(sep*30, title, sep*30); } /* * ************************ * torch utils * ************************ */ inline string _file_line_errmsg(string file_name, int line_num) { return spyprint(" at file \"" + file_name + "\", line", line_num, ":\n"); } struct AssertError: public std::exception { AssertError(string msg, string file_name, int line_num): _msg("TorchX AssertError" + _file_line_errmsg(file_name, line_num) + msg) {} const char* what() const noexcept { return _msg.c_str(); } string _msg; }; struct ShapeException : public std::exception { ShapeException( ShapeRef expected, ShapeRef actual, string msg, string file_name, int line_num) { _msg = spyprint( "ShapeException" + _file_line_errmsg(file_name, line_num), msg, "expected shape =", expected, "; actual shape =", actual ); } ShapeException( int64_t expected_dim, int64_t actual_dim, string msg, string file_name, int line_num) { _msg = spyprint( "ShapeException" + _file_line_errmsg(file_name, line_num), msg, "expected dimension =", expected_dim, "; actual dimension =", actual_dim ); } const char* what() const noexcept { return _msg.c_str(); } string _msg; }; // from latest "c10/util/Exception.h" // Return x if it is non-empty; otherwise return y. inline string _if_empty_then(const string& x, const string& y) { if (x.empty()) { return y; } else { return x; } } #define TX_ASSERT(cond, ...) \ if (!(cond)) { \ throw AssertError( \ _if_empty_then( \ spyprint(__VA_ARGS__), \ "Expected " #cond " to be true, but got false." \ ), __FILE__, __LINE__ \ ); \ } // NOTE: latest pytorch has TORCH_CHECK to replace AT_CHECK #define _TX_CHECK_CUDA(x) TX_ASSERT(x.type().is_cuda(), #x " must be a CUDA tensor") #define _TX_CHECK_CONTIGUOUS(x) TX_ASSERT(x.is_contiguous(), #x " must be contiguous") #define TX_CHECK_TENSOR(x) _TX_CHECK_CUDA(x); _TX_CHECK_CONTIGUOUS(x) #define TX_CHECK_SHAPE(expected, actual, msg) \ if (expected != actual) { \ throw ShapeException(expected, actual, msg, __FILE__, __LINE__); \ } #define TX_CHECK_DIM(tensor, expected_dim) \ if (tensor.dim() != expected_dim) { \ throw ShapeException(expected_dim, tensor.dim(), "tensor " #tensor, __FILE__, __LINE__); \ } inline bool is_empty(const Tensor& x) { return x.sizes().empty(); } inline void create_tensor_if_empty( Tensor& output, const Tensor& shape_like, const string& shape_err_msg ) /** * Check if the output tensor is empty. * - if yes, allocate a new tensor with the same shape as `shape_like` * - if no, check if the tensor has the same shape as `shape_like` * @param output * @param shape * @param msg */ { if (is_empty(output)) { output = torch::zeros_like(shape_like); } else { TX_CHECK_TENSOR(output); TX_CHECK_SHAPE(shape_like.sizes(), output.sizes(), shape_err_msg); } } inline void create_tensor_if_empty( Tensor& output, ShapeRef shape, const torch::TensorOptions& options, const string& shape_err_msg ) /** * Check if the output tensor is empty. * - if yes, allocate a new tensor of the expected shape * - if no, check if the tensor has the expected shape * @param output * @param shape * @param msg */ { if (is_empty(output)) { output = torch::zeros(shape, options); } else { TX_CHECK_TENSOR(output); TX_CHECK_SHAPE(shape, output.sizes(), shape_err_msg); } } /* * ************************ * Misc * ************************ */ #define SELF_DIR string{__FILE__}.substr(0, string{__FILE__}.rfind("/")+1) inline string get_root_dir() { string file_path = __FILE__; return file_path.substr(0, file_path.rfind("/")+1); } /** * Turn on env variable TORCHX_CPP_DEBUG to allow debugging mode without recompile */ inline bool is_sys_debug() { const char* env_value = std::getenv("TORCHX_CPP_DEBUG"); if (env_value == 0) { return false; } string env_s = env_value; return env_s == "true" || env_s == "True" || env_s == "1"; } class Timer { public: void start() { m_StartTime = std::chrono::system_clock::now(); m_bRunning = true; } void stop() { m_EndTime = std::chrono::system_clock::now(); m_bRunning = false; } double elapsed_ms() { std::chrono::time_point<std::chrono::system_clock> endTime; if(m_bRunning) { endTime = std::chrono::system_clock::now(); } else { endTime = m_EndTime; } return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - m_StartTime).count(); } double elapsed_s() { return elapsed_ms() / 1000.0; } private: std::chrono::time_point<std::chrono::system_clock> m_StartTime; std::chrono::time_point<std::chrono::system_clock> m_EndTime; bool m_bRunning = false; }; /** * Overload N-arg macro * example: * #define mymacro(...) OVERLOAD_MACRO(mymacro, __VA_ARGS__) * #define mymacro2(arg1, arg2) // implement 2-arg macro version * #define mymacro3(arg1, arg2, arg3) // implement 3-arg macro version */ // https://stackoverflow.com/questions/11761703/overloading-macro-on-number-of-arguments #define OVERLOAD_MACRO(M, ...) _OVERLOAD_MACRO(M, _COUNT_ARGS(__VA_ARGS__)) (__VA_ARGS__) #define _OVERLOAD_MACRO(macro_name, number_of_args) _OVERLOAD_MACRO_EXPAND(macro_name, number_of_args) #define _OVERLOAD_MACRO_EXPAND(macro_name, number_of_args) macro_name##number_of_args #define _COUNT_ARGS(...) _ARG_PATTERN_MATCH(__VA_ARGS__, 9,8,7,6,5,4,3,2,1) #define _ARG_PATTERN_MATCH(_1,_2,_3,_4,_5,_6,_7,_8,_9, N, ...) N } // namespace torchx #endif // TORCHX_H_
26.79148
103
0.628253
[ "object", "shape", "vector" ]
f73f3f6e7dbc4e8ce8d13ea98a27aeb1fec1ec5f
3,446
h
C
windows/wrapper/impl_webrtc_VideoCapturer.h
kevinhartman/webrtc-apis
c95bc4b8515bfb0920f3694ccba34ee5e2f63692
[ "BSD-3-Clause" ]
null
null
null
windows/wrapper/impl_webrtc_VideoCapturer.h
kevinhartman/webrtc-apis
c95bc4b8515bfb0920f3694ccba34ee5e2f63692
[ "BSD-3-Clause" ]
null
null
null
windows/wrapper/impl_webrtc_VideoCapturer.h
kevinhartman/webrtc-apis
c95bc4b8515bfb0920f3694ccba34ee5e2f63692
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "impl_webrtc_IVideoCapturer.h" #ifdef WINUWP #ifdef CPPWINRT_VERSION #include <wrapper/impl_org_webRtc_pre_include.h> #include "rtc_base/criticalsection.h" #include "media/base/videocapturer.h" #include "system_wrappers/include/event_wrapper.h" #include <wrapper/impl_org_webRtc_post_include.h> #include <zsLib/types.h> #include <zsLib/Proxy.h> #include <zsLib/ProxySubscriptions.h> #include <atomic> #include <mfidl.h> #include <functional> #include <vector> #include <queue> #include "impl_webrtc_VideoCaptureMediaSink.h" namespace webrtc { class DisplayOrientation; class CaptureDevice; class DisplayOrientationListener { public: virtual void OnDisplayOrientationChanged( winrt::Windows::Graphics::Display::DisplayOrientations orientation) = 0; }; class CaptureDeviceListener { public: virtual void OnIncomingFrame(uint8_t* video_frame, size_t video_frame_length, const cricket::VideoFormat& frame_info) = 0; virtual void OnCaptureDeviceFailed(HRESULT code, winrt::hstring const& message) = 0; }; class VideoCapturer : public IVideoCapturer, public cricket::VideoCapturer, public CaptureDeviceListener, public DisplayOrientationListener { private: struct make_private {}; private: void init(const CreationProperties &props) noexcept; public: VideoCapturer(const make_private &); virtual ~VideoCapturer(); static VideoCapturerUniPtr create(const CreationProperties &info) noexcept; IVideoCapturerSubscriptionPtr subscribe(IVideoCapturerDelegatePtr delegate) override; std::string id() const noexcept override { return id_; } // Overrides from cricket::VideoCapturer virtual cricket::CaptureState Start(const cricket::VideoFormat& capture_format) override; virtual void Stop() override; virtual bool IsRunning() override; virtual bool IsScreencast() const override; virtual bool GetPreferredFourccs(std::vector<uint32_t>* fourccs) override; // Overrides from DisplayOrientationListener void OnDisplayOrientationChanged( winrt::Windows::Graphics::Display::DisplayOrientations orientation) override; private: // Overrides from CaptureDeviceListener virtual void OnIncomingFrame(uint8_t* video_frame, size_t video_frame_length, const cricket::VideoFormat& frame_info) override; virtual void OnCaptureDeviceFailed(HRESULT code, winrt::hstring const& message) override; virtual void ApplyDisplayOrientation( winrt::Windows::Graphics::Display::DisplayOrientations orientation); private: mutable zsLib::RecursiveLock lock_; IVideoCapturerDelegateSubscriptions subscriptions_; IVideoCapturerSubscriptionPtr defaultSubscription_; std::string id_; char* deviceUniqueId_ { nullptr }; rtc::CriticalSection apiCs_; VideoRotation rotateFrame_ { kVideoRotation_0 }; bool apply_rotation_ { false }; winrt::hstring device_id_; std::shared_ptr<CaptureDevice> device_; winrt::Windows::Devices::Enumeration::Panel camera_location_; std::shared_ptr<DisplayOrientation> display_orientation_; cricket::VideoFormat last_frame_info_; winrt::Windows::Media::MediaProperties::IVideoEncodingProperties video_encoding_properties_; winrt::Windows::Media::MediaProperties::MediaEncodingProfile media_encoding_profile_; }; } #endif //CPPWINRT_VERSION #endif //WINUWP
28.479339
93
0.761463
[ "vector" ]
f7401fafb0c759b39db8b3c1d218c681e80d7ab0
339
h
C
include/hdlConvertor/hdlAst/hdlLibrary.h
the-moog/hdlConvertor
5c8f5c6bf2bdceddf0c8cf6b5213d1b56b358f00
[ "MIT" ]
184
2016-08-12T14:26:52.000Z
2022-03-24T21:42:17.000Z
include/hdlConvertor/hdlAst/hdlLibrary.h
hdl4fpga/hdlConvertor
291991042135bf688ee2864cf7fb37d8e8a057db
[ "MIT" ]
142
2016-08-10T03:12:03.000Z
2022-03-30T17:35:06.000Z
include/hdlConvertor/hdlAst/hdlLibrary.h
hdl4fpga/hdlConvertor
291991042135bf688ee2864cf7fb37d8e8a057db
[ "MIT" ]
50
2016-08-06T10:38:29.000Z
2022-03-30T11:03:42.000Z
#pragma once #include <vector> #include <memory> #include <hdlConvertor/hdlAst/named.h> #include <hdlConvertor/hdlAst/iHdlObj.h> namespace hdlConvertor { namespace hdlAst { /* * HDL library reference * */ class HdlLibrary : public WithNameAndDoc, public iHdlObj { public: HdlLibrary(const std::string& name); ~HdlLibrary(); }; } }
15.409091
58
0.728614
[ "vector" ]
f75098e0fabfb8f8e2ab59a946384707000c81e7
1,886
h
C
Modules-old/bhwalk/Tools/Math/GaussianDistribution.h
ToyotaResearchInstitute/rad-robot
9a47e4d88382719ab9bf142932fbcc83dcbcd665
[ "MIT" ]
null
null
null
Modules-old/bhwalk/Tools/Math/GaussianDistribution.h
ToyotaResearchInstitute/rad-robot
9a47e4d88382719ab9bf142932fbcc83dcbcd665
[ "MIT" ]
null
null
null
Modules-old/bhwalk/Tools/Math/GaussianDistribution.h
ToyotaResearchInstitute/rad-robot
9a47e4d88382719ab9bf142932fbcc83dcbcd665
[ "MIT" ]
2
2018-06-04T12:38:54.000Z
2018-09-22T10:31:27.000Z
/** * @file GaussianDistribution.h * * Definition of class GaussianDistribution * * @author <a href="mailto:timlaue@informatik.uni-bremen.de">Tim Laue</a> */ #pragma once #include "Vector2.h" /** * @class GaussianDistribution * Represents a 1-dimensional normal distribution */ class GaussianDistribution { public: /** The mean value of the distribution*/ float mean; /** The variance of the distribution*/ float variance; /** Empty standard constructor*/ GaussianDistribution() {} /** Copy constructor * @param other The other distribution that is copied to this one */ GaussianDistribution(const GaussianDistribution& other) {*this = other;} /** Computes the Mahalanobis distance to another distribution. * This function is used to compare two different distributions for checking, if * they describe the same phenomenon. * @param other Another distribution * @return A value without any unit */ float distanceTo(const GaussianDistribution& other) const; /** Computes the probability density at a given position * @param p The position * @return The probability at pos. */ virtual float probabilityAt(float p) const; /** Computes the probability density at the center of the distribution * @return The probability */ float probabilityAtMean() const { return probabilityAt(mean);} /** Computes mean and variance of the distribution * @param x A list of measurements of a variable * @param numOfX The number of measurements */ void generateDistributionFromMeasurements(float* x, int numOfX); /** Assignment operator * @param other The other distribution that is assigned to this one * @return A reference to this object after the assignment. */ GaussianDistribution& operator=(const GaussianDistribution& other) { mean = other.mean; variance = other.variance; return *this; } };
26.56338
83
0.725875
[ "object" ]
f753ba48b8dd8d95dffec4e425a5e2c70e0bb3d2
37,034
c
C
source/blender/makesrna/intern/rna_brush.c
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
source/blender/makesrna/intern/rna_brush.c
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
source/blender/makesrna/intern/rna_brush.c
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
/* * $Id: rna_brush.c 37031 2011-05-31 02:14:25Z campbellbarton $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Contributor(s): Blender Foundation (2008), Juho Veps�l�inen * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/makesrna/intern/rna_brush.c * \ingroup RNA */ #include <stdlib.h> #include <assert.h> #include "RNA_define.h" #include "rna_internal.h" #include "DNA_brush_types.h" #include "DNA_texture_types.h" #include "DNA_scene_types.h" #include "DNA_object_types.h" #include "BLI_math.h" #include "IMB_imbuf.h" #include "WM_types.h" static EnumPropertyItem prop_direction_items[]= { {0, "ADD", 0, "Add", "Add effect of brush"}, {BRUSH_DIR_IN, "SUBTRACT", 0, "Subtract", "Subtract effect of brush"}, {0, NULL, 0, NULL, NULL}}; EnumPropertyItem brush_sculpt_tool_items[] = { {SCULPT_TOOL_BLOB, "BLOB", ICON_BRUSH_BLOB, "Blob", ""}, {SCULPT_TOOL_CLAY, "CLAY", ICON_BRUSH_CLAY, "Clay", ""}, {SCULPT_TOOL_CREASE, "CREASE",ICON_BRUSH_CREASE, "Crease", ""}, {SCULPT_TOOL_DRAW, "DRAW", ICON_BRUSH_SCULPT_DRAW, "Draw", ""}, {SCULPT_TOOL_FILL, "FILL", ICON_BRUSH_FILL, "Fill", ""}, {SCULPT_TOOL_FLATTEN, "FLATTEN", ICON_BRUSH_FLATTEN, "Flatten", ""}, {SCULPT_TOOL_GRAB, "GRAB", ICON_BRUSH_GRAB, "Grab", ""}, {SCULPT_TOOL_INFLATE, "INFLATE", ICON_BRUSH_INFLATE, "Inflate", ""}, {SCULPT_TOOL_LAYER, "LAYER", ICON_BRUSH_LAYER, "Layer", ""}, {SCULPT_TOOL_NUDGE, "NUDGE", ICON_BRUSH_NUDGE, "Nudge", ""}, {SCULPT_TOOL_PINCH, "PINCH", ICON_BRUSH_PINCH, "Pinch", ""}, {SCULPT_TOOL_ROTATE, "ROTATE", ICON_BRUSH_ROTATE, "Rotate", ""}, {SCULPT_TOOL_SCRAPE, "SCRAPE", ICON_BRUSH_SCRAPE, "Scrape", ""}, {SCULPT_TOOL_SMOOTH, "SMOOTH", ICON_BRUSH_SMOOTH, "Smooth", ""}, {SCULPT_TOOL_SNAKE_HOOK, "SNAKE_HOOK", ICON_BRUSH_SNAKE_HOOK, "Snake Hook", ""}, {SCULPT_TOOL_THUMB, "THUMB", ICON_BRUSH_THUMB, "Thumb", ""}, {0, NULL, 0, NULL, NULL}}; EnumPropertyItem brush_vertex_tool_items[] = { {0, "MIX", ICON_BRUSH_MIX, "Mix", "Use mix blending mode while painting"}, {1, "ADD", ICON_BRUSH_ADD, "Add", "Use add blending mode while painting"}, {2, "SUB", ICON_BRUSH_SUBTRACT, "Subtract", "Use subtract blending mode while painting"}, {3, "MUL", ICON_BRUSH_MULTIPLY, "Multiply", "Use multiply blending mode while painting"}, {4, "BLUR", ICON_BRUSH_BLUR, "Blur", "Blur the color with surrounding values"}, {5, "LIGHTEN", ICON_BRUSH_LIGHTEN, "Lighten", "Use lighten blending mode while painting"}, {6, "DARKEN", ICON_BRUSH_DARKEN, "Darken", "Use darken blending mode while painting"}, {0, NULL, 0, NULL, NULL}}; EnumPropertyItem brush_image_tool_items[] = { {PAINT_TOOL_DRAW, "DRAW", ICON_BRUSH_TEXDRAW, "Draw", ""}, {PAINT_TOOL_SOFTEN, "SOFTEN", ICON_BRUSH_SOFTEN, "Soften", ""}, {PAINT_TOOL_SMEAR, "SMEAR", ICON_BRUSH_SMEAR, "Smear", ""}, {PAINT_TOOL_CLONE, "CLONE", ICON_BRUSH_CLONE, "Clone", ""}, {0, NULL, 0, NULL, NULL}}; #ifdef RNA_RUNTIME #include "MEM_guardedalloc.h" #include "DNA_object_types.h" #include "RNA_access.h" #include "BKE_texture.h" #include "BKE_brush.h" #include "BKE_icons.h" #include "BKE_paint.h" #include "WM_api.h" static void rna_Brush_reset_icon(Brush *br, const char *UNUSED(type)) { ID *id = &br->id; if(br->flag & BRUSH_CUSTOM_ICON) return; if(id->icon_id >= BIFICONID_LAST) { BKE_icon_delete(id); BKE_previewimg_free_id(id); } id->icon_id = 0; } static void rna_Brush_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { Brush *br= (Brush*)ptr->data; WM_main_add_notifier(NC_BRUSH|NA_EDITED, br); //WM_main_add_notifier(NC_SPACE|ND_SPACE_VIEW3D, NULL); } static void rna_Brush_sculpt_tool_update(Main *bmain, Scene *scene, PointerRNA *ptr) { Brush *br= (Brush*)ptr->data; rna_Brush_reset_icon(br, "sculpt"); rna_Brush_update(bmain, scene, ptr); } static void rna_Brush_vertex_tool_update(Main *bmain, Scene *scene, PointerRNA *ptr) { Brush *br= (Brush*)ptr->data; rna_Brush_reset_icon(br, "vertex_paint"); rna_Brush_update(bmain, scene, ptr); } static void rna_Brush_imagepaint_tool_update(Main *bmain, Scene *scene, PointerRNA *ptr) { Brush *br= (Brush*)ptr->data; rna_Brush_reset_icon(br, "image_paint"); rna_Brush_update(bmain, scene, ptr); } static void rna_Brush_icon_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr) { Brush *br= (Brush*)ptr->data; if(br->icon_imbuf) { IMB_freeImBuf(br->icon_imbuf); br->icon_imbuf= NULL; } br->id.icon_id = 0; if(br->flag & BRUSH_CUSTOM_ICON) { BKE_previewimg_get(&br->id); BKE_icon_changed(BKE_icon_getid(&br->id)); } WM_main_add_notifier(NC_BRUSH|NA_EDITED, br); } static void rna_Brush_set_size(PointerRNA *ptr, int value) { Brush* me = (Brush*)(ptr->data); float size= (float)brush_size(me); float unprojected_radius; // paranoia: previous checks should make sure we don't divide by zero assert(size != 0); // set unprojected radius, so it remains consistent with size unprojected_radius= (float)(brush_unprojected_radius(me) * value / size); brush_set_unprojected_radius(me, unprojected_radius); brush_set_size(me, value); } static int rna_Brush_get_size(PointerRNA *ptr) { Brush* me = (Brush*)(ptr->data); return brush_size(me); } static void rna_Brush_set_use_locked_size(PointerRNA *ptr, int value) { Brush* me = (Brush*)(ptr->data); brush_set_use_locked_size(me, value); } static int rna_Brush_get_use_locked_size(PointerRNA *ptr) { Brush* me = (Brush*)(ptr->data); return brush_use_locked_size(me); } static void rna_Brush_set_use_size_pressure(PointerRNA *ptr, int value) { Brush* me = (Brush*)(ptr->data); brush_set_use_size_pressure(me, value); } static int rna_Brush_get_use_size_pressure(PointerRNA *ptr) { Brush* me = (Brush*)(ptr->data); return brush_use_size_pressure(me); } static void rna_Brush_set_use_alpha_pressure(PointerRNA *ptr, int value) { Brush* me = (Brush*)(ptr->data); brush_set_use_alpha_pressure(me, value); } static int rna_Brush_get_use_alpha_pressure(PointerRNA *ptr) { Brush* me = (Brush*)(ptr->data); return brush_use_alpha_pressure(me); } static void rna_Brush_set_unprojected_radius(PointerRNA *ptr, float value) { Brush* me = (Brush*)(ptr->data); float unprojected_radius= brush_unprojected_radius(me); int size; // paranoia: previous checks should make sure we don't divide by zero assert(unprojected_radius != 0.0f); // set size, so that it is consistent with unprojected_radius size= (int)((float)brush_size(me) * value / unprojected_radius); brush_set_size(me, size); brush_set_unprojected_radius(me, value); } static float rna_Brush_get_unprojected_radius(PointerRNA *ptr) { Brush* me = (Brush*)(ptr->data); return brush_unprojected_radius(me); } static void rna_Brush_set_alpha(PointerRNA *ptr, float value) { Brush* me = (Brush*)(ptr->data); brush_set_alpha(me, value); } static float rna_Brush_get_alpha(PointerRNA *ptr) { Brush* me = (Brush*)(ptr->data); return brush_alpha(me); } static EnumPropertyItem *rna_Brush_direction_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), int *UNUSED(free)) { static EnumPropertyItem prop_default_items[]= { {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem prop_flatten_contrast_items[]= { {0, "FLATTEN", 0, "Flatten", "Add effect of brush"}, {BRUSH_DIR_IN, "CONTRAST", 0, "Contrast", "Subtract effect of brush"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem prop_fill_deepen_items[]= { {0, "FILL", 0, "Fill", "Add effect of brush"}, {BRUSH_DIR_IN, "DEEPEN", 0, "Deepen", "Subtract effect of brush"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem prop_scrape_peaks_items[]= { {0, "SCRAPE", 0, "Scrape", "Add effect of brush"}, {BRUSH_DIR_IN, "PEAKS", 0, "Peaks", "Subtract effect of brush"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem prop_pinch_magnify_items[]= { {0, "PINCH", 0, "Pinch", "Add effect of brush"}, {BRUSH_DIR_IN, "MAGNIFY", 0, "Magnify", "Subtract effect of brush"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem prop_inflate_deflate_items[]= { {0, "INFLATE", 0, "Inflate", "Add effect of brush"}, {BRUSH_DIR_IN, "DEFLATE", 0, "Deflate", "Subtract effect of brush"}, {0, NULL, 0, NULL, NULL}}; Brush *me= (Brush*)(ptr->data); switch (me->sculpt_tool) { case SCULPT_TOOL_DRAW: case SCULPT_TOOL_CREASE: case SCULPT_TOOL_BLOB: case SCULPT_TOOL_LAYER: case SCULPT_TOOL_CLAY: return prop_direction_items; case SCULPT_TOOL_FLATTEN: return prop_flatten_contrast_items; case SCULPT_TOOL_FILL: return prop_fill_deepen_items; case SCULPT_TOOL_SCRAPE: return prop_scrape_peaks_items; case SCULPT_TOOL_PINCH: return prop_pinch_magnify_items; case SCULPT_TOOL_INFLATE: return prop_inflate_deflate_items; default: return prop_default_items; } } #else static void rna_def_brush_texture_slot(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; static EnumPropertyItem prop_map_mode_items[] = { {MTEX_MAP_MODE_FIXED, "FIXED", 0, "Fixed", ""}, {MTEX_MAP_MODE_TILED, "TILED", 0, "Tiled", ""}, {MTEX_MAP_MODE_3D, "3D", 0, "3D", ""}, {0, NULL, 0, NULL, NULL}}; srna= RNA_def_struct(brna, "BrushTextureSlot", "TextureSlot"); RNA_def_struct_sdna(srna, "MTex"); RNA_def_struct_ui_text(srna, "Brush Texture Slot", "Texture slot for textures in a Brush datablock"); prop= RNA_def_property(srna, "angle", PROP_FLOAT, PROP_ANGLE); RNA_def_property_float_sdna(prop, NULL, "rot"); RNA_def_property_range(prop, 0, M_PI*2); RNA_def_property_ui_text(prop, "Angle", "Defines brush texture rotation"); RNA_def_property_update(prop, 0, "rna_TextureSlot_update"); prop= RNA_def_property(srna, "map_mode", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "brush_map_mode"); RNA_def_property_enum_items(prop, prop_map_mode_items); RNA_def_property_ui_text(prop, "Mode", ""); RNA_def_property_update(prop, 0, "rna_TextureSlot_update"); } static void rna_def_brush(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; static EnumPropertyItem prop_blend_items[] = { {IMB_BLEND_MIX, "MIX", 0, "Mix", "Use mix blending mode while painting"}, {IMB_BLEND_ADD, "ADD", 0, "Add", "Use add blending mode while painting"}, {IMB_BLEND_SUB, "SUB", 0, "Subtract", "Use subtract blending mode while painting"}, {IMB_BLEND_MUL, "MUL", 0, "Multiply", "Use multiply blending mode while painting"}, {IMB_BLEND_LIGHTEN, "LIGHTEN", 0, "Lighten", "Use lighten blending mode while painting"}, {IMB_BLEND_DARKEN, "DARKEN", 0, "Darken", "Use darken blending mode while painting"}, {IMB_BLEND_ERASE_ALPHA, "ERASE_ALPHA", 0, "Erase Alpha", "Erase alpha while painting"}, {IMB_BLEND_ADD_ALPHA, "ADD_ALPHA", 0, "Add Alpha", "Add alpha while painting"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem brush_stroke_method_items[] = { {0, "DOTS", 0, "Dots", "Apply paint on each mouse move step"}, {BRUSH_RESTORE_MESH, "DRAG_DOT", 0, "Drag Dot", "Allows a single dot to be carefully positioned"}, {BRUSH_SPACE, "SPACE", 0, "Space", "Limit brush application to the distance specified by spacing"}, {BRUSH_ANCHORED, "ANCHORED", 0, "Anchored", "Keep the brush anchored to the initial location"}, {BRUSH_AIRBRUSH, "AIRBRUSH", 0, "Airbrush", "Keep applying paint effect while holding mouse (spray)"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem texture_angle_source_items[] = { {0, "USER", 0, "User", "Rotate the brush texture by given angle"}, {BRUSH_RAKE, "RAKE", 0, "Rake", "Rotate the brush texture to match the stroke direction"}, {BRUSH_RANDOM_ROTATION, "RANDOM", 0, "Random", "Rotate the brush texture at random"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem texture_angle_source_no_random_items[] = { {0, "USER", 0, "User", "Rotate the brush texture by given angle"}, {BRUSH_RAKE, "RAKE", 0, "Rake", "Rotate the brush texture to match the stroke direction"}, {0, NULL, 0, NULL, NULL}}; static EnumPropertyItem brush_sculpt_plane_items[] = { {SCULPT_DISP_DIR_AREA, "AREA", 0, "Area Plane", ""}, {SCULPT_DISP_DIR_VIEW, "VIEW", 0, "View Plane", ""}, {SCULPT_DISP_DIR_X, "X", 0, "X Plane", ""}, {SCULPT_DISP_DIR_Y, "Y", 0, "Y Plane", ""}, {SCULPT_DISP_DIR_Z, "Z", 0, "Z Plane", ""}, {0, NULL, 0, NULL, NULL}}; srna= RNA_def_struct(brna, "Brush", "ID"); RNA_def_struct_ui_text(srna, "Brush", "Brush datablock for storing brush settings for painting and sculpting"); RNA_def_struct_ui_icon(srna, ICON_BRUSH_DATA); /* enums */ prop= RNA_def_property(srna, "blend", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, prop_blend_items); RNA_def_property_ui_text(prop, "Blending mode", "Brush blending mode"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "sculpt_tool", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, brush_sculpt_tool_items); RNA_def_property_ui_text(prop, "Sculpt Tool", ""); RNA_def_property_update(prop, 0, "rna_Brush_sculpt_tool_update"); prop= RNA_def_property(srna, "vertex_tool", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "vertexpaint_tool"); RNA_def_property_enum_items(prop, brush_vertex_tool_items); RNA_def_property_ui_text(prop, "Vertex/Weight Paint Tool", ""); RNA_def_property_update(prop, 0, "rna_Brush_vertex_tool_update"); prop= RNA_def_property(srna, "image_tool", PROP_ENUM, PROP_NONE); RNA_def_property_enum_sdna(prop, NULL, "imagepaint_tool"); RNA_def_property_enum_items(prop, brush_image_tool_items); RNA_def_property_ui_text(prop, "Image Paint Tool", ""); RNA_def_property_update(prop, NC_SPACE|ND_SPACE_IMAGE, "rna_Brush_imagepaint_tool_update"); prop= RNA_def_property(srna, "direction", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag"); RNA_def_property_enum_items(prop, prop_direction_items); RNA_def_property_enum_funcs(prop, NULL, NULL, "rna_Brush_direction_itemf"); RNA_def_property_ui_text(prop, "Direction", ""); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "stroke_method", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag"); RNA_def_property_enum_items(prop, brush_stroke_method_items); RNA_def_property_ui_text(prop, "Stroke Method", ""); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "texture_angle_source_random", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag"); RNA_def_property_enum_items(prop, texture_angle_source_items); RNA_def_property_ui_text(prop, "Texture Angle Source", ""); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "texture_angle_source_no_random", PROP_ENUM, PROP_NONE); RNA_def_property_enum_bitflag_sdna(prop, NULL, "flag"); RNA_def_property_enum_items(prop, texture_angle_source_no_random_items); RNA_def_property_ui_text(prop, "Texture Angle Source", ""); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "sculpt_plane", PROP_ENUM, PROP_NONE); RNA_def_property_enum_items(prop, brush_sculpt_plane_items); RNA_def_property_ui_text(prop, "Sculpt Plane", ""); RNA_def_property_update(prop, 0, "rna_Brush_update"); /* number values */ prop= RNA_def_property(srna, "size", PROP_INT, PROP_DISTANCE); RNA_def_property_int_funcs(prop, "rna_Brush_get_size", "rna_Brush_set_size", NULL); RNA_def_property_range(prop, 1, MAX_BRUSH_PIXEL_RADIUS*10); RNA_def_property_ui_range(prop, 1, MAX_BRUSH_PIXEL_RADIUS, 1, 0); RNA_def_property_ui_text(prop, "Radius", "Radius of the brush in pixels"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "unprojected_radius", PROP_FLOAT, PROP_DISTANCE); RNA_def_property_float_funcs(prop, "rna_Brush_get_unprojected_radius", "rna_Brush_set_unprojected_radius", NULL); RNA_def_property_range(prop, 0.001, FLT_MAX); RNA_def_property_ui_range(prop, 0.001, 1, 0, 0); RNA_def_property_ui_text(prop, "Unprojected Radius", "Radius of brush in Blender units"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "jitter", PROP_FLOAT, PROP_NONE); RNA_def_property_float_sdna(prop, NULL, "jitter"); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Jitter", "Jitter the position of the brush while painting"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "spacing", PROP_INT, PROP_PERCENTAGE); RNA_def_property_int_sdna(prop, NULL, "spacing"); RNA_def_property_range(prop, 1, 1000); RNA_def_property_ui_range(prop, 1, 500, 5, 0); RNA_def_property_ui_text(prop, "Spacing", "Spacing between brush daubs as a percentage of brush diameter"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "smooth_stroke_radius", PROP_INT, PROP_DISTANCE); RNA_def_property_range(prop, 10, 200); RNA_def_property_ui_text(prop, "Smooth Stroke Radius", "Minimum distance from last point before stroke continues"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "smooth_stroke_factor", PROP_FLOAT, PROP_FACTOR); RNA_def_property_range(prop, 0.5, 0.99); RNA_def_property_ui_text(prop, "Smooth Stroke Factor", "Higher values give a smoother stroke"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "rate", PROP_FLOAT, PROP_NONE); RNA_def_property_float_sdna(prop, NULL, "rate"); RNA_def_property_range(prop, 0.0001f , 10000.0f); RNA_def_property_ui_range(prop, 0.01f, 1.0f, 1, 3); RNA_def_property_ui_text(prop, "Rate", "Interval between paints for Airbrush"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR_GAMMA); RNA_def_property_range(prop, 0.0, 1.0); RNA_def_property_float_sdna(prop, NULL, "rgb"); RNA_def_property_ui_text(prop, "Color", ""); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "strength", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "alpha"); RNA_def_property_float_funcs(prop, "rna_Brush_get_alpha", "rna_Brush_set_alpha", NULL); RNA_def_property_float_default(prop, 0.5f); RNA_def_property_range(prop, 0.0f, 10.0f); RNA_def_property_ui_range(prop, 0.0f, 1.0f, 0.001, 0.001); RNA_def_property_ui_text(prop, "Strength", "How powerful the effect of the brush is when applied"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "plane_offset", PROP_FLOAT, PROP_DISTANCE); RNA_def_property_float_sdna(prop, NULL, "plane_offset"); RNA_def_property_float_default(prop, 0); RNA_def_property_range(prop, -2.0f, 2.0f); RNA_def_property_ui_range(prop, -0.5f, 0.5f, 0.001, 0.001); RNA_def_property_ui_text(prop, "Plane Offset", "Adjusts plane on which the brush acts towards or away from the object surface"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "plane_trim", PROP_FLOAT, PROP_DISTANCE); RNA_def_property_float_sdna(prop, NULL, "plane_trim"); RNA_def_property_float_default(prop, 0.5f); RNA_def_property_range(prop, 0, 1.0f); RNA_def_property_ui_text(prop, "Plane Trim", "If a vertex is further from offset plane than this then it is not affected"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "height", PROP_FLOAT, PROP_DISTANCE); RNA_def_property_float_sdna(prop, NULL, "height"); RNA_def_property_float_default(prop, 0.5f); RNA_def_property_range(prop, 0, 1.0f); RNA_def_property_ui_text(prop, "Brush Height", "Affectable height of brush (layer height for layer tool, i.e.)"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "texture_sample_bias", PROP_FLOAT, PROP_DISTANCE); RNA_def_property_float_sdna(prop, NULL, "texture_sample_bias"); RNA_def_property_float_default(prop, 0); RNA_def_property_range(prop, -1, 1); RNA_def_property_ui_text(prop, "Texture Sample Bias", "Value added to texture samples"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "normal_weight", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "normal_weight"); RNA_def_property_float_default(prop, 0); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Normal Weight", "How much grab will pull vertexes out of surface during a grab"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "crease_pinch_factor", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "crease_pinch_factor"); RNA_def_property_float_default(prop, 2.0f/3.0f); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Crease Brush Pinch Factor", "How much the crease brush pinches"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "auto_smooth_factor", PROP_FLOAT, PROP_FACTOR); RNA_def_property_float_sdna(prop, NULL, "autosmooth_factor"); RNA_def_property_float_default(prop, 0); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_range(prop, 0.0f, 1.0f, 0.001, 0.001); RNA_def_property_ui_text(prop, "Autosmooth", "Amount of smoothing to automatically apply to each stroke"); RNA_def_property_update(prop, 0, "rna_Brush_update"); /* flag */ prop= RNA_def_property(srna, "use_airbrush", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_AIRBRUSH); RNA_def_property_ui_text(prop, "Airbrush", "Keep applying paint effect while holding mouse (spray)"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_original_normal", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_ORIGINAL_NORMAL); RNA_def_property_ui_text(prop, "Original Normal", "When locked keep using normal of surface where stroke was initiated"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_wrap", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_TORUS); RNA_def_property_ui_text(prop, "Wrap", "Enable torus wrapping while painting"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_pressure_strength", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_ALPHA_PRESSURE); RNA_def_property_boolean_funcs(prop, "rna_Brush_get_use_alpha_pressure", "rna_Brush_set_use_alpha_pressure"); RNA_def_property_ui_icon(prop, ICON_STYLUS_PRESSURE, 0); RNA_def_property_ui_text(prop, "Strength Pressure", "Enable tablet pressure sensitivity for strength"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_offset_pressure", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_OFFSET_PRESSURE); RNA_def_property_ui_icon(prop, ICON_STYLUS_PRESSURE, 0); RNA_def_property_ui_text(prop, "Plane Offset Pressure", "Enable tablet pressure sensitivity for offset"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_pressure_size", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_SIZE_PRESSURE); RNA_def_property_boolean_funcs(prop, "rna_Brush_get_use_size_pressure", "rna_Brush_set_use_size_pressure"); RNA_def_property_ui_icon(prop, ICON_STYLUS_PRESSURE, 0); RNA_def_property_ui_text(prop, "Size Pressure", "Enable tablet pressure sensitivity for size"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_pressure_jitter", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_JITTER_PRESSURE); RNA_def_property_ui_icon(prop, ICON_STYLUS_PRESSURE, 0); RNA_def_property_ui_text(prop, "Jitter Pressure", "Enable tablet pressure sensitivity for jitter"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_pressure_spacing", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_SPACING_PRESSURE); RNA_def_property_ui_icon(prop, ICON_STYLUS_PRESSURE, 0); RNA_def_property_ui_text(prop, "Spacing Pressure", "Enable tablet pressure sensitivity for spacing"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_inverse_smooth_pressure", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_INVERSE_SMOOTH_PRESSURE); RNA_def_property_ui_icon(prop, ICON_STYLUS_PRESSURE, 0); RNA_def_property_ui_text(prop, "Inverse Smooth Pressure", "Lighter pressure causes more smoothing to be applied"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_rake", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_RAKE); RNA_def_property_ui_text(prop, "Rake", "Rotate the brush texture to match the stroke direction"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_random_rotation", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_RANDOM_ROTATION); RNA_def_property_ui_text(prop, "Random Rotation", "Rotate the brush texture at random"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_plane_trim", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_PLANE_TRIM); RNA_def_property_ui_text(prop, "Use Plane Trim", "Enable Plane Trim"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_frontface", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_FRONTFACE); RNA_def_property_ui_text(prop, "Use Front-Face", "Brush only affects vertexes that face the viewer"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_anchor", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_ANCHORED); RNA_def_property_ui_text(prop, "Anchored", "Keep the brush anchored to the initial location"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_space", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_SPACE); RNA_def_property_ui_text(prop, "Space", "Limit brush application to the distance specified by spacing"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_smooth_stroke", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_SMOOTH_STROKE); RNA_def_property_ui_text(prop, "Smooth Stroke", "Brush lags behind mouse and follows a smoother path"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_persistent", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_PERSISTENT); RNA_def_property_ui_text(prop, "Persistent", "Sculpts on a persistent layer of the mesh"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_accumulate", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_ACCUMULATE); RNA_def_property_ui_text(prop, "Accumulate", "Accumulate stroke dabs on top of each other"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_space_atten", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_SPACE_ATTEN); RNA_def_property_ui_text(prop, "Use Automatic Strength Adjustment", "Automatically adjusts strength to give consistent results for different spacings"); RNA_def_property_update(prop, 0, "rna_Brush_update"); /* adaptive space is not implemented yet */ prop= RNA_def_property(srna, "use_adaptive_space", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_ADAPTIVE_SPACE); RNA_def_property_ui_text(prop, "Adaptive Spacing", "Space daubs according to surface orientation instead of screen space"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_locked_size", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_funcs(prop, "rna_Brush_get_use_locked_size", "rna_Brush_set_use_locked_size"); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_LOCK_SIZE); RNA_def_property_ui_text(prop, "Use Blender Units", "When locked brush stays same size relative to object; when unlocked brush size is given in pixels"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_texture_overlay", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_TEXTURE_OVERLAY); RNA_def_property_ui_text(prop, "Use Texture Overlay", "Show texture in viewport"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_edge_to_edge", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_EDGE_TO_EDGE); RNA_def_property_ui_text(prop, "Edge-to-edge", "Drag anchor brush from edge-to-edge"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_restore_mesh", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_RESTORE_MESH); RNA_def_property_ui_text(prop, "Restore Mesh", "Allows a single dot to be carefully positioned"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_fixed_texture", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_FIXED_TEX); RNA_def_property_ui_text(prop, "Fixed Texture", "Keep texture origin in fixed position"); RNA_def_property_update(prop, 0, "rna_Brush_update"); /* only for projection paint, TODO, other paint modes */ prop= RNA_def_property(srna, "use_alpha", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", BRUSH_LOCK_ALPHA); RNA_def_property_ui_text(prop, "Alpha", "When this is disabled, lock alpha while painting"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "curve", PROP_POINTER, PROP_NONE); RNA_def_property_flag(prop, PROP_NEVER_NULL); RNA_def_property_ui_text(prop, "Curve", "Editable falloff curve"); RNA_def_property_update(prop, 0, "rna_Brush_update"); /* paint mode flags */ prop= RNA_def_property(srna, "use_paint_sculpt", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ob_mode", OB_MODE_SCULPT); RNA_def_property_ui_text(prop, "Use Sculpt", "Use this brush in sculpt mode"); prop= RNA_def_property(srna, "use_paint_vertex", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ob_mode", OB_MODE_VERTEX_PAINT); RNA_def_property_ui_text(prop, "Use Vertex", "Use this brush in vertex paint mode"); prop= RNA_def_property(srna, "use_paint_weight", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ob_mode", OB_MODE_WEIGHT_PAINT); RNA_def_property_ui_text(prop, "Use Weight", "Use this brush in weight paint mode"); prop= RNA_def_property(srna, "use_paint_image", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "ob_mode", OB_MODE_TEXTURE_PAINT); RNA_def_property_ui_text(prop, "Use Texture", "Use this brush in texture paint mode"); /* texture */ prop= RNA_def_property(srna, "texture_slot", PROP_POINTER, PROP_NONE); RNA_def_property_struct_type(prop, "BrushTextureSlot"); RNA_def_property_pointer_sdna(prop, NULL, "mtex"); RNA_def_property_clear_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Texture Slot", ""); prop= RNA_def_property(srna, "texture", PROP_POINTER, PROP_NONE); RNA_def_property_pointer_sdna(prop, NULL, "mtex.tex"); RNA_def_property_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Texture", ""); RNA_def_property_update(prop, NC_TEXTURE, "rna_Brush_update"); prop= RNA_def_property(srna, "texture_overlay_alpha", PROP_INT, PROP_PERCENTAGE); RNA_def_property_int_sdna(prop, NULL, "texture_overlay_alpha"); RNA_def_property_range(prop, 1, 100); RNA_def_property_ui_text(prop, "Texture Overlay Alpha", ""); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "cursor_color_add", PROP_FLOAT, PROP_COLOR); RNA_def_property_float_sdna(prop, NULL, "add_col"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Add Color", "Color of cursor when adding"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "cursor_color_subtract", PROP_FLOAT, PROP_COLOR); RNA_def_property_float_sdna(prop, NULL, "sub_col"); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Subtract Color", "Color of cursor when subtracting"); RNA_def_property_update(prop, 0, "rna_Brush_update"); prop= RNA_def_property(srna, "use_custom_icon", PROP_BOOLEAN, PROP_NONE); RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_CUSTOM_ICON); RNA_def_property_ui_text(prop, "Custom Icon", "Set the brush icon from an image file"); RNA_def_property_update(prop, 0, "rna_Brush_icon_update"); prop= RNA_def_property(srna, "icon_filepath", PROP_STRING, PROP_FILEPATH); RNA_def_property_string_sdna(prop, NULL, "icon_filepath"); RNA_def_property_ui_text(prop, "Brush Icon Filepath", "File path to brush icon"); RNA_def_property_update(prop, 0, "rna_Brush_icon_update"); /* clone tool */ prop= RNA_def_property(srna, "clone_image", PROP_POINTER, PROP_NONE); RNA_def_property_pointer_sdna(prop, NULL, "clone.image"); RNA_def_property_flag(prop, PROP_EDITABLE); RNA_def_property_ui_text(prop, "Clone Image", "Image for clone tool"); RNA_def_property_update(prop, NC_SPACE|ND_SPACE_IMAGE, "rna_Brush_update"); prop= RNA_def_property(srna, "clone_alpha", PROP_FLOAT, PROP_NONE); RNA_def_property_float_sdna(prop, NULL, "clone.alpha"); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Clone Alpha", "Opacity of clone image display"); RNA_def_property_update(prop, NC_SPACE|ND_SPACE_IMAGE, "rna_Brush_update"); prop= RNA_def_property(srna, "clone_offset", PROP_FLOAT, PROP_XYZ); RNA_def_property_float_sdna(prop, NULL, "clone.offset"); RNA_def_property_ui_text(prop, "Clone Offset", ""); RNA_def_property_ui_range(prop, -1.0f , 1.0f, 10.0f, 3); RNA_def_property_update(prop, NC_SPACE|ND_SPACE_IMAGE, "rna_Brush_update"); } /* A brush stroke is a list of changes to the brush that * can occur during a stroke * * o 3D location of the brush * o 2D mouse location * o Tablet pressure * o Direction flip * o Tool switch * o Time */ static void rna_def_operator_stroke_element(BlenderRNA *brna) { StructRNA *srna; PropertyRNA *prop; srna= RNA_def_struct(brna, "OperatorStrokeElement", "PropertyGroup"); RNA_def_struct_ui_text(srna, "Operator Stroke Element", ""); prop= RNA_def_property(srna, "location", PROP_FLOAT, PROP_XYZ); RNA_def_property_flag(prop, PROP_IDPROPERTY); RNA_def_property_array(prop, 3); RNA_def_property_ui_text(prop, "Location", ""); prop= RNA_def_property(srna, "mouse", PROP_FLOAT, PROP_XYZ); RNA_def_property_flag(prop, PROP_IDPROPERTY); RNA_def_property_array(prop, 2); RNA_def_property_ui_text(prop, "Mouse", ""); prop= RNA_def_property(srna, "pressure", PROP_FLOAT, PROP_NONE); RNA_def_property_flag(prop, PROP_IDPROPERTY); RNA_def_property_range(prop, 0.0f, 1.0f); RNA_def_property_ui_text(prop, "Pressure", "Tablet pressure"); prop= RNA_def_property(srna, "pen_flip", PROP_BOOLEAN, PROP_NONE); RNA_def_property_flag(prop, PROP_IDPROPERTY); RNA_def_property_ui_text(prop, "Flip", ""); // used in uv painting prop= RNA_def_property(srna, "time", PROP_FLOAT, PROP_UNSIGNED); RNA_def_property_flag(prop, PROP_IDPROPERTY); RNA_def_property_ui_text(prop, "Time", ""); /* used for Grease Pencil sketching sessions */ prop= RNA_def_property(srna, "is_start", PROP_BOOLEAN, PROP_NONE); RNA_def_property_flag(prop, PROP_IDPROPERTY); RNA_def_property_ui_text(prop, "Is Stroke Start", ""); /* XXX: Tool (this will be for pressing a modifier key for a different brush, e.g. switching to a Smooth brush in the middle of the stroke */ // XXX: i don't think blender currently supports the ability to properly do a remappable modifier in the middle of a stroke } void RNA_def_brush(BlenderRNA *brna) { rna_def_brush(brna); rna_def_brush_texture_slot(brna); rna_def_operator_stroke_element(brna); } #endif
43.62073
154
0.766755
[ "mesh", "object", "3d" ]
f764c4216ba3f085ea558980f49f4d3da501badd
9,656
h
C
src/odbc/PreparedStatement.h
csmu-cenr/odbc-cpp-wrapper
e32a004c6bcfcb00d9853a85a6b8632ec69f63c3
[ "Apache-2.0" ]
null
null
null
src/odbc/PreparedStatement.h
csmu-cenr/odbc-cpp-wrapper
e32a004c6bcfcb00d9853a85a6b8632ec69f63c3
[ "Apache-2.0" ]
null
null
null
src/odbc/PreparedStatement.h
csmu-cenr/odbc-cpp-wrapper
e32a004c6bcfcb00d9853a85a6b8632ec69f63c3
[ "Apache-2.0" ]
null
null
null
#ifndef ODBC_PREPAREDSTATEMENT_H_INCLUDED #define ODBC_PREPAREDSTATEMENT_H_INCLUDED //------------------------------------------------------------------------------ #include <memory> #include <vector> #include <odbc/Config.h> #include <odbc/Forwards.h> #include <odbc/StatementBase.h> #include <odbc/Types.h> //------------------------------------------------------------------------------ namespace odbc { //------------------------------------------------------------------------------ class Batch; class ParameterData; //------------------------------------------------------------------------------ /** * Represents a precompiled SQL statement. */ class ODBC_EXPORT PreparedStatement : public StatementBase { friend class Connection; friend class ParameterMetaData; private: PreparedStatement(Connection* parent); public: ~PreparedStatement(); private: void setHandleAndQuery(void* hstmt, const char* query); void setHandleAndQuery(void* hstmt, const char16_t* query); public: /** * Retrieves the number, types and properties of the parameters. * * @return Returns a ParameterMetaData object that contains information * about the number, types and properties for each parameter. */ ParameterMetaDataRef getParameterMetaData(); /** * Sets the specified parameter to the given boolean value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setBoolean(unsigned short paramIndex, const Boolean& value); /** * Sets the specified parameter to the given signed byte value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setByte(unsigned short paramIndex, const Byte& value); /** * Sets the specified parameter to the given unsigned byte value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setUByte(unsigned short paramIndex, const UByte& value); /** * Sets the specified parameter to the given signed short integer value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setShort(unsigned short paramIndex, const Short& value); /** * Sets the specified parameter to the given unsigned short integer value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setUShort(unsigned short paramIndex, const UShort& value); /** * Sets the specified parameter to the given signed integer value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setInt(unsigned short paramIndex, const Int& value); /** * Sets the specified parameter to the given unsigned integer value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setUInt(unsigned short paramIndex, const UInt& value); /** * Sets the specified parameter to the given signed long integer value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setLong(unsigned short paramIndex, const Long& value); /** * Sets the specified parameter to the given unsigned long integer value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setULong(unsigned short paramIndex, const ULong& value); /** * Sets the specified parameter to the given decimal value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setDecimal(unsigned short paramIndex, const Decimal& value); /** * Sets the specified parameter to the given float value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setFloat(unsigned short paramIndex, const Float& value); /** * Sets the specified parameter to the given double value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setDouble(unsigned short paramIndex, const Double& value); /** * Sets the specified parameter to the given string value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setString(unsigned short paramIndex, const String& value); /** * Sets the specified parameter to the given null-terminated character * sequence (C-String). * * @param paramIndex The parameter index starting from 1. * @param s The null-terminated character sequence. */ void setCString(unsigned short paramIndex, const char* s); /** * Sets the specified parameter to the given character sequence of the * desired length. * * @param paramIndex The parameter index starting from 1. * @param s The sequence of characters. * @param len The length of the sequence. */ void setCString(unsigned short paramIndex, const char* s, std::size_t len); /** * Sets the specified parameter to the given string with 16-bit characters. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setNString(unsigned short paramIndex, const NString& value); /** * Sets the specified parameter to the given null-terminated 16-bit * character sequence (C-String). * * @param paramIndex The parameter index starting from 1. * @param s The null-terminated character sequence. */ void setNCString(unsigned short paramIndex, const char16_t* s); /** * Sets the specified parameter to the given 16-bit character sequence of * the desired length. * * @param paramIndex The parameter index starting from 1. * @param s The sequence of characters. * @param len The length of the sequence. */ void setNCString(unsigned short paramIndex, const char16_t* s, std::size_t len); /** * Sets the specified parameter to the given Binary object. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setBinary(unsigned short paramIndex, const Binary& value); /** * Sets the specified parameter to the given byte sequence of the desired * length. * * @param paramIndex The parameter index starting from 1. * @param data The sequence of bytes. * @param size The length of the sequence. */ void setBytes(unsigned short paramIndex, const void* data, std::size_t size); /** * Sets the specified parameter to the given Date value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setDate(unsigned short paramIndex, const Date& value); /** * Sets the specified parameter to the given Time value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setTime(unsigned short paramIndex, const Time& value); /** * Sets the specified parameter to the given Timestamp value. * * @param paramIndex The parameter index starting from 1. * @param value The parameter value. */ void setTimestamp(unsigned short paramIndex, const Timestamp& value); /** * Clears the parameter values. */ void clearParameters(); /** * Retrieves a ResultSetMetaData object that contains information about a * ResultSet object returned by executeQuery method. * * @return Returns a ResultSetMetaData object. */ ResultSetMetaDataRef getMetaData(); /** * Executes the SQL query of this PreparedStatement object and returns a * ResultSet object. * * @return Returns a ResultSet object that contains the data produced * by the given SQL statement. */ ResultSetRef executeQuery(); /** * Executes the SQL query of this PreparedStatement object and returns * the number of rows affected by an UPDATE, INSERT, or DELETE statement. * * @return Returns the number of rows affected by an UPDATE, INSERT, or * DELETE statement. */ size_t executeUpdate(); /** * Add the current set of parameters to the batch of commands. */ void addBatch(); /** * Executes the batch of commands. */ void executeBatch(); /** * Clears the batch of commands. */ void clearBatch(); private: void bindParameters(); template<typename T> void setFixedSizeData(unsigned short paramIndex, const Nullable<T>& value); void verifyValidParamIndex(unsigned short paramIndex) const; void verifyAllParametersValid() const; private: std::vector<ParameterData> parameterData_; std::unique_ptr<Batch> batch_; }; //------------------------------------------------------------------------------ } // namespace odbc //------------------------------------------------------------------------------ #endif
34
80
0.62034
[ "object", "vector" ]
f7747f795d6d329a98a76fe40447938818001298
2,491
h
C
src/devices/cpu/z80/kp69.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/cpu/z80/kp69.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/cpu/z80/kp69.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:AJR /*************************************************************************** Kawasaki Steel (Kawatetsu) KP69 Interrupt Controller ***************************************************************************/ #ifndef MAME_CPU_Z80_KP69_H #define MAME_CPU_Z80_KP69_H #pragma once #include "machine/z80daisy.h" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** class kp69_base_device : public device_t, public device_z80daisy_interface { public: // callback to CPU auto int_callback() { return m_int_callback.bind(); } // read handlers u8 isrl_r(); u8 isrh_r(); u8 imrl_r(); u8 imrh_r(); // interrupt inputs template <int N> DECLARE_WRITE_LINE_MEMBER(ir_w) { static_assert(N >= 0 && N < 16, "Invalid level"); set_input_level(N, state); } void add_to_state(device_state_interface &state, int index); protected: // construction/destruction kp69_base_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, u32 clock); // device-level overrides virtual void device_resolve_objects() override; virtual void device_start() override; virtual void device_reset() override; // device_z80daisy_interface overrides virtual int z80daisy_irq_state() override; virtual int z80daisy_irq_ack() override; virtual void z80daisy_irq_reti() override; // internal helpers bool int_active() const; void set_int(bool active); void set_input_level(int level, bool state); void set_irr(u16 data); void set_isr(u16 data); void set_imr(u16 data); void set_ler(u16 data); void set_pgr(u16 data); // callback object devcb_write_line m_int_callback; // internal state u16 m_input_levels; u16 m_irr; u16 m_isr; bool m_illegal_state; u8 m_ivr; u16 m_imr; u16 m_ler; u16 m_pgr; bool m_int_active; }; class kp69_device : public kp69_base_device { public: // device type constructor kp69_device(const machine_config &mconfig, const char *tag, device_t *owner, u32 clock = 0); // write handlers void lerl_pgrl_w(u8 data); void lerh_pgrh_w(u8 data); void imrl_w(u8 data); void ivr_imrh_w(u8 data); protected: // device-level overrides virtual void device_start() override; virtual void device_reset() override; private: bool m_ivr_written; }; // device type declaration DECLARE_DEVICE_TYPE(KP69, kp69_device) #endif // MAME_CPU_Z80_KP69_H
23.5
112
0.661983
[ "object" ]
f79240c039bbb14eeefbef87dc4965cfea36bd83
1,226
c
C
ff/rr/gui/gui_object_list/gui_object_sphere.c
alexbayc/rtsept
f993bf22e348262dfec5ef1f7e6279c7909623db
[ "Apache-2.0" ]
null
null
null
ff/rr/gui/gui_object_list/gui_object_sphere.c
alexbayc/rtsept
f993bf22e348262dfec5ef1f7e6279c7909623db
[ "Apache-2.0" ]
null
null
null
ff/rr/gui/gui_object_list/gui_object_sphere.c
alexbayc/rtsept
f993bf22e348262dfec5ef1f7e6279c7909623db
[ "Apache-2.0" ]
1
2019-09-28T11:47:23.000Z
2019-09-28T11:47:23.000Z
#include "gui_object.h" void gui_object_sphere_init (t_gui_object_sphere *sphere, GtkBuilder *builder, GtkOverlay *target) { sphere->base.object = GTK_BOX(gtk_builder_get_object(builder, GO_SPHERE_OBJECT)); sphere->base.offscreen_parent = GTK_VIEWPORT(gtk_builder_get_object(builder, GO_SPHERE_PARENT)); gui_object_base_init(&sphere->base, target); sphere->position_x = GTK_ENTRY(gtk_builder_get_object(builder, GO_SPHERE_POS_X)); sphere->position_y = GTK_ENTRY(gtk_builder_get_object(builder, GO_SPHERE_POS_Y)); sphere->position_z = GTK_ENTRY(gtk_builder_get_object(builder, GO_SPHERE_POS_Z)); sphere->radius = GTK_ENTRY(gtk_builder_get_object(builder, GO_SPHERE_RAD)); } void gui_sphere_load(t_gui_object_sphere *gui, t_object *sphere) { char buffer[16]; t_object_sphere *data; data = (t_object_sphere *)sphere->data; sprintf(buffer, "%3.1f", data->position.x); gtk_entry_set_text(gui->position_x, buffer); sprintf(buffer, "%3.1f", data->position.y); gtk_entry_set_text(gui->position_y, buffer); sprintf(buffer, "%3.1f", data->position.z); gtk_entry_set_text(gui->position_z, buffer); sprintf(buffer, "%3.1f", data->radius); gtk_entry_set_text(gui->radius, buffer); }
33.135135
67
0.75938
[ "object" ]
f795f7dcc2cf519131d84eb67a77467b6e0aeeb6
4,000
c
C
python-ios/src/scipy_files/scipy/patches/linalg/src/id_dist/src/id_rtrans_subr_9.c
ktraunmueller/Computable
5a6a872c4c0f5e122c24c321cd877a949877dcf7
[ "MIT" ]
26
2018-02-14T23:52:58.000Z
2021-08-16T13:50:03.000Z
scipy_build_2.0/linalg/src/id_dist/src/id_rtrans_subr_9.c
wtbh/scipy_arm64
00f8f9ca06cc941a854601546ab4bfb259ef6bda
[ "Apache-2.0" ]
3
2019-09-03T05:50:32.000Z
2020-05-10T05:35:11.000Z
scipy_build_2.0/linalg/src/id_dist/src/id_rtrans_subr_9.c
wtbh/scipy_arm64
00f8f9ca06cc941a854601546ab4bfb259ef6bda
[ "Apache-2.0" ]
10
2018-08-13T19:38:39.000Z
2020-04-19T03:02:00.000Z
/* id_rtrans_subr_9.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "f2c.h" /* Subroutine */ int idz_random_transf0_(integer *nsteps, doublecomplex *x, doublecomplex *y, integer *n, doublecomplex *w2, doublereal *albetas, doublecomplex *gammas, integer *iixs) { /* System generated locals */ integer gammas_dim1, gammas_offset, albetas_dim2, albetas_offset, iixs_dim1, iixs_offset, i__1, i__2, i__3, i__4; /* Local variables */ static integer i__, j; extern /* Subroutine */ int idz_random_transf00_(doublecomplex *, doublecomplex *, integer *, doublereal *, doublecomplex *, integer *); static integer ijk; /* routine idz_random_transf serves as a memory wrapper */ /* for the present routine; please see routine idz_random_transf */ /* for documentation. */ /* Parameter adjustments */ --x; --y; iixs_dim1 = *n; iixs_offset = 1 + iixs_dim1; iixs -= iixs_offset; gammas_dim1 = *n; gammas_offset = 1 + gammas_dim1; gammas -= gammas_offset; albetas_dim2 = *n; albetas_offset = 1 + 2 * (1 + albetas_dim2); albetas -= albetas_offset; --w2; /* Function Body */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { i__2 = i__; i__3 = i__; w2[i__2].r = x[i__3].r, w2[i__2].i = x[i__3].i; /* L1200: */ } i__1 = *nsteps; for (ijk = 1; ijk <= i__1; ++ijk) { idz_random_transf00_(&w2[1], &y[1], n, &albetas[(ijk * albetas_dim2 + 1 << 1) + 1], &gammas[ijk * gammas_dim1 + 1], &iixs[ijk * iixs_dim1 + 1]); i__2 = *n; for (j = 1; j <= i__2; ++j) { i__3 = j; i__4 = j; w2[i__3].r = y[i__4].r, w2[i__3].i = y[i__4].i; /* L1400: */ } /* L2000: */ } return 0; } /* idz_random_transf0__ */ /* Subroutine */ int idz_random_transf00_(doublecomplex *x, doublecomplex *y, integer *n, doublereal *albetas, doublecomplex *gammas, integer *ixs) { /* System generated locals */ integer i__1, i__2, i__3, i__4; doublereal d__1; doublecomplex z__1, z__2, z__3; /* Local variables */ static doublecomplex a, b; static integer i__, j; static doublereal beta, alpha; /* implements one step of the random transform */ /* required by routine idz_random_transf0 (please see the latter). */ /* implement the permutation */ /* and multiply by the random numbers */ /* on the unit circle */ /* Parameter adjustments */ --ixs; --gammas; albetas -= 3; --y; --x; /* Function Body */ i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { j = ixs[i__]; i__2 = i__; i__3 = j; i__4 = i__; z__1.r = x[i__3].r * gammas[i__4].r - x[i__3].i * gammas[i__4].i, z__1.i = x[i__3].r * gammas[i__4].i + x[i__3].i * gammas[i__4] .r; y[i__2].r = z__1.r, y[i__2].i = z__1.i; /* L1600: */ } /* implement 2 \times 2 matrices */ i__1 = *n - 1; for (i__ = 1; i__ <= i__1; ++i__) { alpha = albetas[(i__ << 1) + 1]; beta = albetas[(i__ << 1) + 2]; i__2 = i__; a.r = y[i__2].r, a.i = y[i__2].i; i__2 = i__ + 1; b.r = y[i__2].r, b.i = y[i__2].i; i__2 = i__; z__2.r = alpha * a.r, z__2.i = alpha * a.i; z__3.r = beta * b.r, z__3.i = beta * b.i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; i__2 = i__ + 1; d__1 = -beta; z__2.r = d__1 * a.r, z__2.i = d__1 * a.i; z__3.r = alpha * b.r, z__3.i = alpha * b.i; z__1.r = z__2.r + z__3.r, z__1.i = z__2.i + z__3.i; y[i__2].r = z__1.r, y[i__2].i = z__1.i; /* L2600: */ } return 0; } /* idz_random_transf00__ */
25.477707
77
0.589
[ "object", "transform" ]
7409315e736383df406be143b4e568cf93ee2983
829
h
C
Header/settings.h
kenshen112/ChatPlays
2898d5803e0dc454a1ca242740056b21741e74ed
[ "MIT" ]
7
2021-06-05T08:56:48.000Z
2022-03-02T17:46:04.000Z
Header/settings.h
kenshen112/ChatPlays
2898d5803e0dc454a1ca242740056b21741e74ed
[ "MIT" ]
null
null
null
Header/settings.h
kenshen112/ChatPlays
2898d5803e0dc454a1ca242740056b21741e74ed
[ "MIT" ]
1
2022-02-22T12:22:16.000Z
2022-02-22T12:22:16.000Z
#pragma once #include <filesystem> #include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #ifdef __linux__ #include "Linux/control.h" #include "Linux/connect.h" #elif _WIN32 #include "Windows/winConnect.h" #include "Windows/control.h" #endif #include "twitch.h" #include "json.hpp" using json = nlohmann::json; namespace fs = std::filesystem; class Settings { private: // ToDo: Fix path handling to generate settings folder in the executeable's directory. Missing a gui libary makes finding that a challenge. fs::path filePath = "settings/settings.json"; fs::path executeable; Emit* controllerSettings; TwitchInfo* twitchSettings; json j; public: Settings(); Settings(Emit& c, TwitchInfo& t); void edit(); bool load(); bool save(); };
20.219512
143
0.696019
[ "vector" ]
7410c6b226a972b7670c1910a8f35260e6cf76d8
3,471
h
C
src/SmallFBX/sfbxAlgorithm.h
think-biq/SmallFBX
20a960d995bc714a792a2fec2af520d245da8afa
[ "MIT" ]
36
2021-03-10T13:27:09.000Z
2022-03-24T03:26:01.000Z
src/SmallFBX/sfbxAlgorithm.h
think-biq/SmallFBX
20a960d995bc714a792a2fec2af520d245da8afa
[ "MIT" ]
2
2021-08-10T02:07:50.000Z
2021-09-23T06:16:37.000Z
src/SmallFBX/sfbxAlgorithm.h
think-biq/SmallFBX
20a960d995bc714a792a2fec2af520d245da8afa
[ "MIT" ]
8
2021-03-10T14:02:26.000Z
2021-08-08T01:59:27.000Z
#pragma once #include <cstring> #include "sfbxTypes.h" namespace sfbx { // call resize() if Cont has. otherwise do nothing. template <class Cont> inline void resize(Cont& dst, size_t n) { if constexpr (has_resize<Cont>) { dst.resize(n); } } template<class T, sfbxRestrict(std::is_pointer_v<T>)> inline T get_raw_ptr(T v) { return v; } template<class T> inline T* get_raw_ptr(const std::shared_ptr<T>& v) { return v.get(); } template<class Container, class Body> inline void each(Container& val, const Body& body) { for (auto& v : val) body(v); } template<class Container, class Indices, class Body> inline void each_indexed(Container& val, Indices& idx, const Body& body) { for (auto i : idx) body(val[i]); } template<class D, class S> inline void copy(D* dst, const S* src, size_t n) { for (size_t i = 0; i < n; ++i) *dst++ = *src++; } template<class D, class S> inline void copy(span<D> dst, span<S> src) { copy(dst.data(), src.data(), src.size()); } template<class Dst, class Src> inline void copy(Dst& dst, const Src& src) { resize(dst, src.size()); copy(make_span(dst), make_span(src)); } template<class Dst, class Src, class Indices> inline void copy_indexed(Dst& dst, const Src& src, const Indices& idx) { resize(dst, idx.size()); auto* d = dst.data(); for (auto i : idx) *d++ = src[i]; } template<class Dst, class Src, class Body> inline void transform(Dst& dst, const Src& src, const Body& body) { resize(dst, src.size()); auto* d = dst.data(); for (const auto& v : src) *d++ = body(v); } template<class Dst, class Src, class Indices, class Body> inline void transform_indexed(Dst& dst, const Src& src, const Indices& idx, const Body& body) { resize(dst, idx.size()); auto* d = dst.data(); for (auto i : idx) *d++ = body(src[i]); } template<class Container, class Body> inline size_t count(const Container& cont, const Body& body) { size_t r = 0; for (auto& v : cont) if (body(v)) ++r; return r; } template<class Container> inline get_value_type<Container> find(const Container& cont, const get_value_type<Container>& v) { for (auto& c : cont) if (c == v) return c; return {}; } template<class Container, class Condition> inline get_value_type<Container> find_if(const Container& cont, const Condition& cond) { for (auto& c : cont) if (cond(c)) return c; return {}; } template<class Container, class T> inline bool erase(Container& cont, const T& v) { auto it = std::find(cont.begin(), cont.end(), v); if (it != cont.end()) { cont.erase(it); return true; } return false; } template<class Container, class Body> inline bool erase_if(Container& cont, const Body& v) { auto it = std::remove_if(cont.begin(), cont.end(), v); if (it != cont.end()) { cont.erase(it, cont.end()); return true; } return false; } template<class Container, class T> inline bool replace(Container& cont, const T& before, const T& after) { for (auto& c : cont) { if (c == before) { c = after; return true; } } return false; } // substitution for std::string_view::starts_with() (which require C++20) inline bool starts_with(string_view str, string_view v) { return std::strncmp(str.data(), v.data(), v.size()) == 0; } } // namespace sfbx
22.986755
96
0.617689
[ "transform" ]
7413d36eec039f87bf1697034a9619b864fc418a
14,158
h
C
components/site_engagement/content/site_engagement_service.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/site_engagement/content/site_engagement_service.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/site_engagement/content/site_engagement_service.h
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SITE_ENGAGEMENT_CONTENT_SITE_ENGAGEMENT_SERVICE_H_ #define COMPONENTS_SITE_ENGAGEMENT_CONTENT_SITE_ENGAGEMENT_SERVICE_H_ #include <memory> #include <vector> #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/time/time.h" #include "build/build_config.h" #include "components/browsing_data/core/browsing_data_utils.h" #include "components/keyed_service/core/keyed_service.h" #include "components/site_engagement/core/mojom/site_engagement_details.mojom.h" #include "components/site_engagement/core/site_engagement_score_provider.h" #include "third_party/blink/public/mojom/site_engagement/site_engagement.mojom.h" #include "ui/base/page_transition_types.h" namespace base { class Clock; } namespace webapps { FORWARD_DECLARE_TEST(AppBannerManagerBrowserTest, WebAppBannerNeedsEngagement); } namespace content { class BrowserContext; class WebContents; } // namespace content namespace web_app { class WebAppEngagementBrowserTest; } class GURL; class HostContentSettingsMap; class PrefRegistrySimple; namespace site_engagement { enum class EngagementType; class SiteEngagementObserver; class SiteEngagementScore; #if defined(OS_ANDROID) class SiteEngagementServiceAndroid; #endif // Stores and retrieves the engagement score of an origin. // // An engagement score is a non-negative double that represents how much a user // has engaged with an origin - the higher it is, the more engagement the user // has had with this site recently. // // User activity such as visiting the origin often, interacting with the origin, // and adding it to the homescreen will increase the site engagement score. If // a site's score does not increase for some time, it will decay, eventually // reaching zero with further disuse. // // The SiteEngagementService object must be created and used on the UI thread // only. Engagement scores may be queried in a read-only fashion from other // threads using SiteEngagementService::GetScoreFromSettings, but use of this // method is discouraged unless it is not possible to use the UI thread. class SiteEngagementService : public KeyedService, public SiteEngagementScoreProvider { public: // The provider allows code agnostic to the embedder (e.g. in // //components) to retrieve the SiteEngagementService. It should be set by // each embedder that uses the SiteEngagementService, via SetServiceProvider. class ServiceProvider { public: ~ServiceProvider() = default; // Should always return a non null value, creating the service if it does // not exist. virtual SiteEngagementService* GetSiteEngagementService( content::BrowserContext* browser_context) = 0; }; // WebContentsObserver that detects engagement triggering events and notifies // the service of them. class Helper; // The name of the site engagement variation field trial. static const char kEngagementParams[]; static void RegisterProfilePrefs(PrefRegistrySimple* registry); // Sets and clears the service provider. These are separate functions to // enable better checking. static void SetServiceProvider(ServiceProvider* provider); static void ClearServiceProvider(ServiceProvider* provider); // Returns the site engagement service attached to this Browser Context. The // service exists in incognito mode; scores will be initialised using the // score from the Browser Context that the incognito session was created from, // and will increase and decrease as usual. Engagement earned or decayed in // incognito will not be persisted or reflected in the original Browser // Context. // // This method must be called on the UI thread. static SiteEngagementService* Get(content::BrowserContext* browser_context); // Returns the maximum possible amount of engagement that a site can accrue. static double GetMaxPoints(); // Returns whether or not the site engagement service is enabled. static bool IsEnabled(); // Returns the score for |origin| based on |settings|. Can be called on any // thread and does not cause any cleanup, decay, etc. // // Should only be used if you cannot create a SiteEngagementService (i.e. you // cannot run on the UI thread). static double GetScoreFromSettings(HostContentSettingsMap* settings, const GURL& origin); // Retrieves all details. Can be called from a background thread. |now| must // be the current timestamp. Takes a scoped_refptr to keep // HostContentSettingsMap alive. See crbug.com/901287. static std::vector<mojom::SiteEngagementDetails> GetAllDetailsInBackground( base::Time now, scoped_refptr<HostContentSettingsMap> map); explicit SiteEngagementService(content::BrowserContext* browser_context); SiteEngagementService(const SiteEngagementService&) = delete; SiteEngagementService& operator=(const SiteEngagementService&) = delete; ~SiteEngagementService() override; // Returns the engagement level of |url|. blink::mojom::EngagementLevel GetEngagementLevel(const GURL& url) const; // Returns an array of engagement score details for all origins which have // a score, whether due to direct engagement, or other factors that cause // an engagement bonus to be applied. // // Note that this method is quite expensive, so try to avoid calling it in // performance-critical code. std::vector<mojom::SiteEngagementDetails> GetAllDetails() const; // Return an array of engagement score details for all origins which have // had engagement since the specified time. // // Note that this method is quite expensive, so try to avoid calling it in // performance-critical code. std::vector<mojom::SiteEngagementDetails> GetAllDetailsEngagedInTimePeriod( browsing_data::TimePeriod time_period) const; // Update the engagement score of |url| for a notification interaction. void HandleNotificationInteraction(const GURL& url); // Returns whether the engagement service has enough data to make meaningful // decisions. Clients should avoid using engagement in their heuristic until // this is true. bool IsBootstrapped() const; // Returns whether |url| has at least the given |level| of engagement. bool IsEngagementAtLeast(const GURL& url, blink::mojom::EngagementLevel level) const; // Resets the base engagement for |url| to |score|, clearing daily limits. Any // bonus engagement that |url| has acquired is not affected by this method, so // the result of GetScore(|url|) may not be the same as |score|. void ResetBaseScoreForURL(const GURL& url, double score); // Update the last time |url| was opened from an installed shortcut (hosted in // |web_contents|) to be clock_->Now(). void SetLastShortcutLaunchTime(content::WebContents* web_contents, const GURL& url); // Returns the site engagement details for the specified |url|. mojom::SiteEngagementDetails GetDetails(const GURL& url) const; // Overridden from SiteEngagementScoreProvider. double GetScore(const GURL& url) const override; double GetTotalEngagementPoints() const override; // Just forwards calls AddPoints. void AddPointsForTesting(const GURL& url, double points); void SetClockForTesting(base::Clock* clock) { clock_ = clock; } protected: // Retrieves the SiteEngagementScore object for |origin|. SiteEngagementScore CreateEngagementScore(const GURL& origin) const; void SetLastEngagementTime(base::Time last_engagement_time) const; content::BrowserContext* browser_context() { return browser_context_; } const base::Clock& clock() { return *clock_; } private: friend class SiteEngagementObserver; friend class SiteEngagementServiceTest; friend class web_app::WebAppEngagementBrowserTest; FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, CheckHistograms); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, CleanupEngagementScores); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, CleanupMovesScoreBackToNow); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, CleanupMovesScoreBackToRebase); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, CleanupEngagementScoresProportional); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, GetTotalNavigationPoints); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, GetTotalUserInputPoints); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, RestrictedToHTTPAndHTTPS); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, Observers); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, LastEngagementTime); FRIEND_TEST_ALL_PREFIXES(SiteEngagementServiceTest, IncognitoEngagementService); FRIEND_TEST_ALL_PREFIXES(webapps::AppBannerManagerBrowserTest, WebAppBannerNeedsEngagement); FRIEND_TEST_ALL_PREFIXES(AppBannerSettingsHelperTest, SiteEngagementTrigger); FRIEND_TEST_ALL_PREFIXES(HostedAppPWAOnlyTest, EngagementHistogram); #if defined(OS_ANDROID) // Shim class to expose the service to Java. friend class SiteEngagementServiceAndroid; SiteEngagementServiceAndroid* GetAndroidService() const; void SetAndroidService( std::unique_ptr<SiteEngagementServiceAndroid> android_service); #endif // Adds the specified number of points to the given origin, respecting the // maximum limits for the day and overall. void AddPoints(const GURL& url, double points); // Runs site engagement maintenance tasks. void AfterStartupTask(); // Removes any origins which have decayed to 0 engagement. If // |update_last_engagement_time| is true, the last engagement time of all // origins is reset by calculating the delta between the last engagement event // recorded by the site engagement service and the origin. The origin's last // engagement time is then set to clock_->Now() - delta. // // If a user does not use the browser at all for some period of time, // engagement is not decayed, and the state is restored equivalent to how they // left it once they return. void CleanupEngagementScores(bool update_last_engagement_time) const; // Possibly records UMA metrics if we haven't recorded them lately. void MaybeRecordMetrics(); // Actually records metrics for the engagement in |details|. void RecordMetrics(std::vector<mojom::SiteEngagementDetails>); // Returns true if we should record engagement for this URL. Currently, // engagement is only earned for HTTP and HTTPS. bool ShouldRecordEngagement(const GURL& url) const; // Get and set the last engagement time from prefs. base::Time GetLastEngagementTime() const; // Get the maximum decay period and the stale period for last engagement // times. base::TimeDelta GetMaxDecayPeriod() const; base::TimeDelta GetStalePeriod() const; // Returns the median engagement score of all recorded origins. |details| must // be sorted in ascending order of score. double GetMedianEngagementFromSortedDetails( const std::vector<mojom::SiteEngagementDetails>& details) const; // Update the engagement score of the origin loaded in |web_contents| for // media playing. The points awarded are discounted if the media is being // played in a non-visible tab. void HandleMediaPlaying(content::WebContents* web_contents, bool is_hidden); // Update the engagement score of the origin loaded in |web_contents| for // navigation. void HandleNavigation(content::WebContents* web_contents, ui::PageTransition transition); // Update the engagement score of the origin loaded in |web_contents| for // time-on-site, based on user input. void HandleUserInput(content::WebContents* web_contents, EngagementType type); // Called when the engagement for |url| loaded in |web_contents| is changed, // due to an event of type |type|. Calls OnEngagementEvent in all observers. // |web_contents| may be null if the engagement has increased when |url| is // not in a tab, e.g. from a notification interaction. Also records // engagement-type metrics. void OnEngagementEvent(content::WebContents* web_contents, const GURL& url, EngagementType type); // Returns true if the last engagement increasing event seen by the site // engagement service was sufficiently long ago that we need to reset all // scores to be relative to now. This ensures that users who do not use the // browser for an extended period of time do not have their engagement decay. bool IsLastEngagementStale() const; // Returns the number of origins with maximum daily and total engagement // respectively. int OriginsWithMaxDailyEngagement() const; // Add and remove observers of this service. void AddObserver(SiteEngagementObserver* observer); void RemoveObserver(SiteEngagementObserver* observer); raw_ptr<content::BrowserContext> browser_context_; // The clock used to vend times. raw_ptr<base::Clock> clock_; #if defined(OS_ANDROID) std::unique_ptr<SiteEngagementServiceAndroid> android_service_; #endif // Metrics are recorded at non-incognito browser startup, and then // approximately once per hour thereafter. Store the local time at which // metrics were previously uploaded: the first event which affects any // origin's engagement score after an hour has elapsed triggers the next // upload. base::Time last_metrics_time_; // A list of observers. When any origin registers an engagement-increasing // event, each observer's OnEngagementEvent method will be called. base::ObserverList<SiteEngagementObserver>::Unchecked observer_list_; base::WeakPtrFactory<SiteEngagementService> weak_factory_{this}; }; } // namespace site_engagement #endif // COMPONENTS_SITE_ENGAGEMENT_CONTENT_SITE_ENGAGEMENT_SERVICE_H_
42.262687
81
0.762678
[ "object", "vector" ]
7417ef01cdfb1f9bce55bdf2e82c39fdc04fb762
3,231
h
C
korrent/korrent.h
BackupTheBerlios/korrent-svn
41014422d4f8b921f479a1f55d0abdba36725dc6
[ "BSD-2-Clause" ]
null
null
null
korrent/korrent.h
BackupTheBerlios/korrent-svn
41014422d4f8b921f479a1f55d0abdba36725dc6
[ "BSD-2-Clause" ]
null
null
null
korrent/korrent.h
BackupTheBerlios/korrent-svn
41014422d4f8b921f479a1f55d0abdba36725dc6
[ "BSD-2-Clause" ]
null
null
null
/*************************************************************************** * * Copyright (C) 2004 Roberto Selbach Teixeira <roberto@kde.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ***************************************************************************/ #ifndef KORRENT_H #define KORRENT_H #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <kapplication.h> #include <kmainwindow.h> #include "korrentview.h" class KPrinter; class KURL; /** * This class serves as the main window for Korrent. It handles the * menus, toolbars, and status bars. * * @short Main window class * @author Roberto Teixeira <roberto@kde.org> * @version 0.1 */ class Korrent : public KMainWindow { Q_OBJECT public: /** * Default Constructor */ Korrent(); /** * Default Destructor */ virtual ~Korrent(); /** * Use this method to load whatever file/URL you have */ void load(const KURL& url); protected: /** * Overridden virtuals for Qt drag 'n drop (XDND) */ virtual void dragEnterEvent(QDragEnterEvent *event); virtual void dropEvent(QDropEvent *event); protected: /** * This function is called when it is time for the app to save its * properties for session management purposes. */ void saveProperties(KConfig *); /** * This function is called when this app is restored. The KConfig * object points to the session management config file that was saved * with @ref saveProperties */ void readProperties(KConfig *); private slots: void fileNew(); void fileOpen(); void fileSave(); void fileSaveAs(); void filePrint(); void optionsConfigureToolbars(); void optionsPreferences(); void newToolbarConfig(); void changeStatusbar(const QString& text); void changeCaption(const QString& text); private: void setupAccel(); void setupActions(); private: KorrentView *m_view; KPrinter *m_printer; }; #endif // KORRENT_H
27.853448
77
0.670071
[ "object" ]
741d3c10eaefefaa4b70851c8ba20157522e834e
1,154
h
C
plugins/renderer/directx12/src/DirectX12/directx12renderwindow.h
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
5
2018-05-16T14:09:34.000Z
2019-10-24T19:01:15.000Z
plugins/renderer/directx12/src/DirectX12/directx12renderwindow.h
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
71
2017-06-20T06:41:42.000Z
2021-01-11T11:18:53.000Z
plugins/renderer/directx12/src/DirectX12/directx12renderwindow.h
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
2
2018-05-16T13:57:25.000Z
2018-05-16T13:57:51.000Z
#pragma once #include "directx12rendertarget.h" #include <dxgi.h> namespace Engine { namespace Render { struct MADGINE_DIRECTX12_EXPORT DirectX12RenderWindow : DirectX12RenderTarget { DirectX12RenderWindow(DirectX12RenderContext *context, Window::OSWindow *w); DirectX12RenderWindow(const DirectX12RenderWindow &) = delete; ~DirectX12RenderWindow(); virtual void beginIteration(size_t iteration) override; virtual void endIteration(size_t iteration) override; virtual TextureDescriptor texture(size_t index, size_t iteration = std::numeric_limits<size_t>::max()) const override; virtual size_t textureCount() const override; virtual TextureDescriptor depthTexture() const override; virtual bool resizeImpl(const Vector2i &size) override; virtual Vector2i size() const override; protected: void createRenderTargetViews(); private: Window::OSWindow *mWindow; IDXGISwapChain3 *mSwapChain; OffsetPtr mTargetViews[2]; ID3D12Resource *mBackBuffers[2]; }; } } RegisterType(Engine::Render::DirectX12RenderWindow);
28.85
126
0.719237
[ "render" ]
741e76c1784330d2aa4874c04ec1b9d3e9e3d8cb
2,522
h
C
lib/essex/server/vlrankmap.h
holtzermann17/Noosphere
7be63c122f778ef00e56ffe847a6d40d004527dd
[ "MIT" ]
1
2018-05-31T06:29:48.000Z
2018-05-31T06:29:48.000Z
lib/essex/server/vlrankmap.h
holtzermann17/Noosphere
7be63c122f778ef00e56ffe847a6d40d004527dd
[ "MIT" ]
null
null
null
lib/essex/server/vlrankmap.h
holtzermann17/Noosphere
7be63c122f778ef00e56ffe847a6d40d004527dd
[ "MIT" ]
1
2021-05-02T15:14:36.000Z
2021-05-02T15:14:36.000Z
/****************************************************************************** A valueless rank map, based on a hash. This really is only useful for keeping track of whether or not we've seen a specific search engine similarity rank (a number between 0 and 1). Features: - key is float, assumed between 0 and 1 - smart sizing and linear probing, based on optimal primes as described at http://planetmath.org/encyclopedia/GoodHashTablePrimes.html - exists() provided. - resizing upwards ******************************************************************************/ #ifndef __VLRANKMAP_H_ #define __VLRANKMAP_H_ #include <iostream> #include <cassert> #include <vector> #include <string.h> #include "hash.h" using namespace std; // the vlrankmap // class vlrankmap { protected: /* data */ float* _keys; int probe; // linear probing increment int size; // array size allocated for storage int size_idx; // index of current size in hash primes table int filled; // used cells in the array /* methods */ unsigned int hash_func( float ); // the hash function void grow(); // grow the table up to the next level public: int index_of( float ); // get table index of a key // destructor-- free memory // ~vlrankmap() { delete [] _keys; } // do-nothing constructor. just init to sane defaults. vlrankmap() : filled(0), size_idx(0) { // init size stuff // size = PRIMES[0]; // initialize table array // init_table(); // initialize probe interval // probe = int(size/4) + 1; } // constructor without max or min size vlrankmap(int _startsize) : filled(0) { // init size stuff // size_idx = nearest_prime_index(_startsize); size = PRIMES[size_idx]; // initialize table arrays // // init_table(); // initialize probe interval // probe = int(size/4) + 1; } // initialize the hash table arrays // void init_table() { // allocate memory for key and value arrays // _keys = new float[size]; // fill with default values // for (int i = 0; i < size; i++) { _keys[i] = -1; } } // set a key to taken void add( float ); // get the list of ranks vector<float> get(); // see if a key exists // int exists( float key ) { return ( _keys[index_of(key)] >= 0); } // some useful accessors // int get_size() { return size; } int get_filled() { return filled; } // get the capacity of the underlying vectors (same as get_size) // int get_capacity() { return size; } }; #endif
19.106061
79
0.61142
[ "vector" ]
743065bdf50708a1d19d82e1b20e5322f65cff51
3,503
h
C
Sources/STK/include/Drummer.h
sroik/AudioKit
4750745817bf5ec3ba2355c6f109fcf4751952ee
[ "MIT" ]
5
2017-09-21T03:50:37.000Z
2020-04-30T23:03:37.000Z
Sources/STK/include/Drummer.h
sroik/AudioKit
4750745817bf5ec3ba2355c6f109fcf4751952ee
[ "MIT" ]
2
2021-06-30T06:05:56.000Z
2022-02-19T08:47:33.000Z
Sources/STK/include/Drummer.h
sroik/AudioKit
4750745817bf5ec3ba2355c6f109fcf4751952ee
[ "MIT" ]
5
2021-06-29T10:21:20.000Z
2022-03-19T19:04:45.000Z
#ifndef STK_DRUMMER_H #define STK_DRUMMER_H #include "FileWvIn.h" #include "Instrmnt.h" #include "OnePole.h" namespace stk { /***************************************************/ /*! class Drummer \brief STK drum sample player class. This class implements a drum sampling synthesizer using WvIn objects and one-pole filters. The drum rawwave files are sampled at 22050 Hz, but will be appropriately interpolated for other sample rates. You can specify the maximum polyphony (maximum number of simultaneous voices) via a #define in the Drummer.h. by Perry R. Cook and Gary P. Scavone, 1995--2016. */ /***************************************************/ const int DRUM_NUMWAVES = 11; const int DRUM_POLYPHONY = 4; class Drummer : public Instrmnt { public: //! Class constructor. /*! An StkError will be thrown if the rawwave path is incorrectly set. */ Drummer(void); //! Class destructor. ~Drummer(void); //! Start a note with the given drum type and amplitude. /*! Use general MIDI drum instrument numbers, converted to frequency values as if MIDI note numbers, to select a particular instrument. An StkError will be thrown if the rawwave path is incorrectly set. */ void noteOn(StkFloat instrument, StkFloat amplitude); //! Stop a note with the given amplitude (speed of decay). void noteOff(StkFloat amplitude); //! Compute and return one output sample. StkFloat tick(unsigned int channel = 0); //! Fill a channel of the StkFrames object with computed outputs. /*! The \c channel argument must be less than the number of channels in the StkFrames argument (the first channel is specified by 0). However, range checking is only performed if _STK_DEBUG_ is defined during compilation, in which case an out-of-range value will trigger an StkError exception. */ StkFrames &tick(StkFrames &frames, unsigned int channel = 0); protected: FileWvIn waves_[DRUM_POLYPHONY]; OnePole filters_[DRUM_POLYPHONY]; std::vector<int> soundOrder_; std::vector<int> soundNumber_; int nSounding_; }; inline StkFloat Drummer ::tick(unsigned int) { lastFrame_[0] = 0.0; if (nSounding_ == 0) return lastFrame_[0]; for (int i = 0; i < DRUM_POLYPHONY; i++) { if (soundOrder_[i] >= 0) { if (waves_[i].isFinished()) { // Re-order the list. for (int j = 0; j < DRUM_POLYPHONY; j++) { if (soundOrder_[j] > soundOrder_[i]) soundOrder_[j] -= 1; } soundOrder_[i] = -1; nSounding_--; } else lastFrame_[0] += filters_[i].tick(waves_[i].tick()); } } return lastFrame_[0]; } inline StkFrames &Drummer ::tick(StkFrames &frames, unsigned int channel) { unsigned int nChannels = lastFrame_.channels(); #if defined(_STK_DEBUG_) if (channel > frames.channels() - nChannels) { oStream_ << "Drummer::tick(): channel and StkFrames arguments are incompatible!"; handleError(StkError::FUNCTION_ARGUMENT); } #endif StkFloat *samples = &frames[channel]; unsigned int j, hop = frames.channels() - nChannels; if (nChannels == 1) { for (unsigned int i = 0; i < frames.frames(); i++, samples += hop) *samples++ = tick(); } else { for (unsigned int i = 0; i < frames.frames(); i++, samples += hop) { *samples++ = tick(); for (j = 1; j < nChannels; j++) *samples++ = lastFrame_[j]; } } return frames; } } // namespace stk #endif
27.801587
80
0.641165
[ "object", "vector" ]